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
397fd8d73a6327118754f1bbd335164ad50bd410
77aa13a51685597585abf89b5ad30f9ef4011bde
/dep/src/boost/boost/detail/atomic_count_solaris.hpp
99571d666955758f6fc6b286d8d06b4d2bd3fddd
[]
no_license
Zic/Xeon-MMORPG-Emulator
2f195d04bfd0988a9165a52b7a3756c04b3f146c
4473a22e6dd4ec3c9b867d60915841731869a050
refs/heads/master
2021-01-01T16:19:35.213330
2009-05-13T18:12:36
2009-05-14T03:10:17
200,849
8
10
null
null
null
null
UTF-8
C++
false
false
1,186
hpp
#ifndef BOOST_DETAIL_ATOMIC_COUNT_SOLARIS_HPP_INCLUDED #define BOOST_DETAIL_ATOMIC_COUNT_SOLARIS_HPP_INCLUDED // // boost/detail/atomic_count_solaris.hpp // based on: boost/detail/atomic_count_win32.hpp // // Copyright (c) 2001-2005 Peter Dimov // Copyright (c) 2006 Michael van der Westhuizen // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <atomic.h> namespace boost { namespace detail { class atomic_count { public: explicit atomic_count( uint32_t v ): value_( v ) { } long operator++() { return atomic_inc_32_nv( &value_ ); } long operator--() { return atomic_dec_32_nv( &value_ ); } operator uint32_t() const { return static_cast<uint32_t const volatile &>( value_ ); } private: atomic_count( atomic_count const & ); atomic_count & operator=( atomic_count const & ); uint32_t value_; }; } // namespace detail } // namespace boost #endif // #ifndef BOOST_DETAIL_ATOMIC_COUNT_SOLARIS_HPP_INCLUDED
[ "pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88" ]
[ [ [ 1, 59 ] ] ]
ab29f4099644999c5e432b029dfc2ba634512aba
871585f3c45603024488cabd14184610af7a081f
/conv_std_d/library.h
4366a7744dc0900310aa3af7276fece838f104cb
[]
no_license
davideanastasia/ORIP
9ac6fb8c490d64da355d34804d949b85ea17dbff
54c180b442a02a202076b8072ceb573f5e345871
refs/heads/master
2016-09-06T14:17:22.765343
2011-11-05T16:23:23
2011-11-05T16:23:23
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,090
h
/* ORIP_v2 –> Op Ref Im Proc -> Oper Refin Imag Process -> Operational Refinement of Image Processing * * Copyright Davide Anastasia and Yiannis Andreopoulos, University College London * * http://www.ee.ucl.ac.uk/~iandreop/ORIP.html * If you have not retrieved this source code via the above link, please contact [email protected] and [email protected] * */ #ifndef __LIBRARY_H_ #define __LIBRARY_H_ #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "common_lib.h" using namespace std; typedef double my_t; typedef my_t** matrix; void setup_conv_matrix(matrix input, int col, int row, int max_val); void setup_conv_gaussian_12x12(matrix input); void setup_conv_gaussian_18x18(matrix input); void setup_conv_gaussian_6x6(matrix input); void conv2(matrix mat1, int rows1, int cols1, matrix mat2, int rows2, int cols2, matrix res, int n_shift = 0); void conv2_symmetric(matrix mat1, int rows1, int cols1, matrix mat2, int rows2, int cols2, matrix res); #endif // __LIBRARY_H_
[ [ [ 1, 35 ] ] ]
29fbc0e7becf0667ae1439f293cfb986cafd6e5e
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/multiplayer/dlls/animation.cpp
f22ca9ab78470bbdc44bb0e47af5bdf95cbd3988
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
UTF-8
C++
false
false
13,326
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. * ****/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../common/nowin.h" typedef int BOOL; #define TRUE 1 #define FALSE 0 // hack into header files that we can ship typedef int qboolean; typedef unsigned char byte; #include "../utils/common/mathlib.h" #include "const.h" #include "progdefs.h" #include "edict.h" #include "eiface.h" #include "studio.h" #ifndef ACTIVITY_H #include "activity.h" #endif #include "activitymap.h" #ifndef ANIMATION_H #include "animation.h" #endif #ifndef SCRIPTEVENT_H #include "scriptevent.h" #endif #ifndef ENGINECALLBACK_H #include "enginecallback.h" #endif extern globalvars_t *gpGlobals; #pragma warning( disable : 4244 ) int ExtractBbox( void *pmodel, int sequence, float *mins, float *maxs ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if (! pstudiohdr) return 0; mstudioseqdesc_t *pseqdesc; pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex); mins[0] = pseqdesc[ sequence ].bbmin[0]; mins[1] = pseqdesc[ sequence ].bbmin[1]; mins[2] = pseqdesc[ sequence ].bbmin[2]; maxs[0] = pseqdesc[ sequence ].bbmax[0]; maxs[1] = pseqdesc[ sequence ].bbmax[1]; maxs[2] = pseqdesc[ sequence ].bbmax[2]; return 1; } int LookupActivity( void *pmodel, entvars_t *pev, int activity ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if (! pstudiohdr) return 0; mstudioseqdesc_t *pseqdesc; pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex); int weighttotal = 0; int seq = ACTIVITY_NOT_AVAILABLE; for (int i = 0; i < pstudiohdr->numseq; i++) { if (pseqdesc[i].activity == activity) { weighttotal += pseqdesc[i].actweight; if (!weighttotal || RANDOM_LONG(0,weighttotal-1) < pseqdesc[i].actweight) seq = i; } } return seq; } int LookupActivityHeaviest( void *pmodel, entvars_t *pev, int activity ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if ( !pstudiohdr ) return 0; mstudioseqdesc_t *pseqdesc; pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex); int weight = 0; int seq = ACTIVITY_NOT_AVAILABLE; for (int i = 0; i < pstudiohdr->numseq; i++) { if (pseqdesc[i].activity == activity) { if ( pseqdesc[i].actweight > weight ) { weight = pseqdesc[i].actweight; seq = i; } } } return seq; } void GetEyePosition ( void *pmodel, float *vecEyePosition ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if ( !pstudiohdr ) { ALERT ( at_console, "GetEyePosition() Can't get pstudiohdr ptr!\n" ); return; } VectorCopy ( pstudiohdr->eyeposition, vecEyePosition ); } int LookupSequence( void *pmodel, const char *label ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if (! pstudiohdr) return 0; mstudioseqdesc_t *pseqdesc; pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex); for (int i = 0; i < pstudiohdr->numseq; i++) { if (stricmp( pseqdesc[i].label, label ) == 0) return i; } return -1; } int IsSoundEvent( int eventNumber ) { if ( eventNumber == SCRIPT_EVENT_SOUND || eventNumber == SCRIPT_EVENT_SOUND_VOICE ) return 1; return 0; } void SequencePrecache( void *pmodel, const char *pSequenceName ) { int index = LookupSequence( pmodel, pSequenceName ); if ( index >= 0 ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if ( !pstudiohdr || index >= pstudiohdr->numseq ) return; mstudioseqdesc_t *pseqdesc; mstudioevent_t *pevent; pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex) + index; pevent = (mstudioevent_t *)((byte *)pstudiohdr + pseqdesc->eventindex); for (int i = 0; i < pseqdesc->numevents; i++) { // Don't send client-side events to the server AI if ( pevent[i].event >= EVENT_CLIENT ) continue; // UNDONE: Add a callback to check to see if a sound is precached yet and don't allocate a copy // of it's name if it is. if ( IsSoundEvent( pevent[i].event ) ) { if ( !strlen(pevent[i].options) ) { ALERT( at_error, "Bad sound event %d in sequence %s :: %s (sound is \"%s\")\n", pevent[i].event, pstudiohdr->name, pSequenceName, pevent[i].options ); } PRECACHE_SOUND( (char *)(gpGlobals->pStringBase + ALLOC_STRING(pevent[i].options) ) ); } } } } void GetSequenceInfo( void *pmodel, entvars_t *pev, float *pflFrameRate, float *pflGroundSpeed ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if (! pstudiohdr) return; mstudioseqdesc_t *pseqdesc; if (pev->sequence >= pstudiohdr->numseq) { *pflFrameRate = 0.0; *pflGroundSpeed = 0.0; return; } pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex) + (int)pev->sequence; if (pseqdesc->numframes > 1) { *pflFrameRate = 256 * pseqdesc->fps / (pseqdesc->numframes - 1); *pflGroundSpeed = sqrt( pseqdesc->linearmovement[0]*pseqdesc->linearmovement[0]+ pseqdesc->linearmovement[1]*pseqdesc->linearmovement[1]+ pseqdesc->linearmovement[2]*pseqdesc->linearmovement[2] ); *pflGroundSpeed = *pflGroundSpeed * pseqdesc->fps / (pseqdesc->numframes - 1); } else { *pflFrameRate = 256.0; *pflGroundSpeed = 0.0; } } int GetSequenceFlags( void *pmodel, entvars_t *pev ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if ( !pstudiohdr || pev->sequence >= pstudiohdr->numseq ) return 0; mstudioseqdesc_t *pseqdesc; pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex) + (int)pev->sequence; return pseqdesc->flags; } int GetAnimationEvent( void *pmodel, entvars_t *pev, MonsterEvent_t *pMonsterEvent, float flStart, float flEnd, int index ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if ( !pstudiohdr || pev->sequence >= pstudiohdr->numseq || !pMonsterEvent ) return 0; int events = 0; mstudioseqdesc_t *pseqdesc; mstudioevent_t *pevent; pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex) + (int)pev->sequence; pevent = (mstudioevent_t *)((byte *)pstudiohdr + pseqdesc->eventindex); if (pseqdesc->numevents == 0 || index > pseqdesc->numevents ) return 0; if (pseqdesc->numframes > 1) { flStart *= (pseqdesc->numframes - 1) / 256.0; flEnd *= (pseqdesc->numframes - 1) / 256.0; } else { flStart = 0; flEnd = 1.0; } for (; index < pseqdesc->numevents; index++) { // Don't send client-side events to the server AI if ( pevent[index].event >= EVENT_CLIENT ) continue; if ( (pevent[index].frame >= flStart && pevent[index].frame < flEnd) || ((pseqdesc->flags & STUDIO_LOOPING) && flEnd >= pseqdesc->numframes - 1 && pevent[index].frame < flEnd - pseqdesc->numframes + 1) ) { pMonsterEvent->event = pevent[index].event; pMonsterEvent->options = pevent[index].options; return index + 1; } } return 0; } float SetController( void *pmodel, entvars_t *pev, int iController, float flValue ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if (! pstudiohdr) return flValue; mstudiobonecontroller_t *pbonecontroller = (mstudiobonecontroller_t *)((byte *)pstudiohdr + pstudiohdr->bonecontrollerindex); // find first controller that matches the index for (int i = 0; i < pstudiohdr->numbonecontrollers; i++, pbonecontroller++) { if (pbonecontroller->index == iController) break; } if (i >= pstudiohdr->numbonecontrollers) return flValue; // wrap 0..360 if it's a rotational controller if (pbonecontroller->type & (STUDIO_XR | STUDIO_YR | STUDIO_ZR)) { // ugly hack, invert value if end < start if (pbonecontroller->end < pbonecontroller->start) flValue = -flValue; // does the controller not wrap? if (pbonecontroller->start + 359.0 >= pbonecontroller->end) { if (flValue > ((pbonecontroller->start + pbonecontroller->end) / 2.0) + 180) flValue = flValue - 360; if (flValue < ((pbonecontroller->start + pbonecontroller->end) / 2.0) - 180) flValue = flValue + 360; } else { if (flValue > 360) flValue = flValue - (int)(flValue / 360.0) * 360.0; else if (flValue < 0) flValue = flValue + (int)((flValue / -360.0) + 1) * 360.0; } } int setting = 255 * (flValue - pbonecontroller->start) / (pbonecontroller->end - pbonecontroller->start); if (setting < 0) setting = 0; if (setting > 255) setting = 255; pev->controller[iController] = setting; return setting * (1.0 / 255.0) * (pbonecontroller->end - pbonecontroller->start) + pbonecontroller->start; } float SetBlending( void *pmodel, entvars_t *pev, int iBlender, float flValue ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if (! pstudiohdr) return flValue; mstudioseqdesc_t *pseqdesc; pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex) + (int)pev->sequence; if (pseqdesc->blendtype[iBlender] == 0) return flValue; if (pseqdesc->blendtype[iBlender] & (STUDIO_XR | STUDIO_YR | STUDIO_ZR)) { // ugly hack, invert value if end < start if (pseqdesc->blendend[iBlender] < pseqdesc->blendstart[iBlender]) flValue = -flValue; // does the controller not wrap? if (pseqdesc->blendstart[iBlender] + 359.0 >= pseqdesc->blendend[iBlender]) { if (flValue > ((pseqdesc->blendstart[iBlender] + pseqdesc->blendend[iBlender]) / 2.0) + 180) flValue = flValue - 360; if (flValue < ((pseqdesc->blendstart[iBlender] + pseqdesc->blendend[iBlender]) / 2.0) - 180) flValue = flValue + 360; } } int setting = 255 * (flValue - pseqdesc->blendstart[iBlender]) / (pseqdesc->blendend[iBlender] - pseqdesc->blendstart[iBlender]); if (setting < 0) setting = 0; if (setting > 255) setting = 255; pev->blending[iBlender] = setting; return setting * (1.0 / 255.0) * (pseqdesc->blendend[iBlender] - pseqdesc->blendstart[iBlender]) + pseqdesc->blendstart[iBlender]; } int FindTransition( void *pmodel, int iEndingAnim, int iGoalAnim, int *piDir ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if (! pstudiohdr) return iGoalAnim; mstudioseqdesc_t *pseqdesc; pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex); // bail if we're going to or from a node 0 if (pseqdesc[iEndingAnim].entrynode == 0 || pseqdesc[iGoalAnim].entrynode == 0) { return iGoalAnim; } int iEndNode; // ALERT( at_console, "from %d to %d: ", pEndNode->iEndNode, pGoalNode->iStartNode ); if (*piDir > 0) { iEndNode = pseqdesc[iEndingAnim].exitnode; } else { iEndNode = pseqdesc[iEndingAnim].entrynode; } if (iEndNode == pseqdesc[iGoalAnim].entrynode) { *piDir = 1; return iGoalAnim; } byte *pTransition = ((byte *)pstudiohdr + pstudiohdr->transitionindex); int iInternNode = pTransition[(iEndNode-1)*pstudiohdr->numtransitions + (pseqdesc[iGoalAnim].entrynode-1)]; if (iInternNode == 0) return iGoalAnim; int i; // look for someone going for (i = 0; i < pstudiohdr->numseq; i++) { if (pseqdesc[i].entrynode == iEndNode && pseqdesc[i].exitnode == iInternNode) { *piDir = 1; return i; } if (pseqdesc[i].nodeflags) { if (pseqdesc[i].exitnode == iEndNode && pseqdesc[i].entrynode == iInternNode) { *piDir = -1; return i; } } } ALERT( at_console, "error in transition graph" ); return iGoalAnim; } void SetBodygroup( void *pmodel, entvars_t *pev, int iGroup, int iValue ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if (! pstudiohdr) return; if (iGroup > pstudiohdr->numbodyparts) return; mstudiobodyparts_t *pbodypart = (mstudiobodyparts_t *)((byte *)pstudiohdr + pstudiohdr->bodypartindex) + iGroup; if (iValue >= pbodypart->nummodels) return; int iCurrent = (pev->body / pbodypart->base) % pbodypart->nummodels; pev->body = (pev->body - (iCurrent * pbodypart->base) + (iValue * pbodypart->base)); } int GetBodygroup( void *pmodel, entvars_t *pev, int iGroup ) { studiohdr_t *pstudiohdr; pstudiohdr = (studiohdr_t *)pmodel; if (! pstudiohdr) return 0; if (iGroup > pstudiohdr->numbodyparts) return 0; mstudiobodyparts_t *pbodypart = (mstudiobodyparts_t *)((byte *)pstudiohdr + pstudiohdr->bodypartindex) + iGroup; if (pbodypart->nummodels <= 1) return 0; int iCurrent = (pev->body / pbodypart->base) % pbodypart->nummodels; return iCurrent; }
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 527 ] ] ]
49dcf6a909efc3c8c69751c1b21e8630ce13447a
282e6353fbdf90100119bc4c2106109db7e18d15
/baldwin-gillam/hfknew.cpp
863401df15a4a9950f5e47d6d2ff79a37d225897
[]
no_license
lipshitz/hfk-parallel
80c891803ca640d3509cfb7ed9d01b8298779eab
9b43f87f42270d65422623f1ac66e215c6d13250
refs/heads/master
2020-06-04T05:28:32.790747
2011-09-08T23:11:26
2011-09-08T23:11:26
32,195,183
0
0
null
null
null
null
UTF-8
C++
false
false
19,006
cpp
// Computes Heegaard Floer knot homology. // Some speed improvements due to Marc Culler // Compile: g++ -o hfk -O3 hfk-mc.cpp // TO do other knots, edit the global values before compiling #include <time.h> #include <iostream> #include <vector> #include <list> using std::list; using std::vector; using std::cout; using std::cin; class Generator { public: list<int> out; list<int> in; bool alive; Generator(); ~Generator(); }; // Globals const int gridsize = 12; // arc-index // Don't waste time computing factorials. Look them up. // Fill in the big ones later since g++ doesn't seem to like big constants long long Factorial[16] = { 1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600, 0,0,0}; //braid: (xy)^{-5} //int white[10] = {7,6,5,3,4,1,2,0,9,8}; //int black[10] = {0,9,8,6,7,4,5,3,2,1}; //another braid //int white[11] = {5,2,3,1,4,6,7,8,9,0}; //int black[11] = {1,9,0,5,2,3,4,6,7,8}; int white[12] = {9,5,11,7,8,1,10,4,0,3,2,6}; int black[12] = {1,0,4,3,2,6,5,9,8,11,7,10}; //int white[2] = {0,1}; //int black[2] = {1,0}; // Function Prototypes void GetPerm(long long k, int h []); // Fills h with the k^th permutation (in lexico. order) void NextPerm(short counter[], int h[]); bool RectDotFree(int xll, int yll, int xur, int yur, int which); // Decides whether one of the four rectangles on the torus with corners at(xll,yll) and (xur,yur) contains no white or black dots /* 1 | 2 | 1 ---+---+--- 3 | 0 | 3 ---+---+--- 1 | 2 | 1 */ long long Index(int y []); // Returns the number of permutations appearing before y lexicographically int WindingNumber(int x, int y); // Return winding number of the knot projection around (x,y) int MaslovGrading(int y []); int NumComp(); //Returns the number of components of the link. bool ValidGrid(); int Find(vector<long long> & V, long long x); // Returns i if V[i]=x or -1 if x isn't V[i] for any i // Main int main(int argc, char *argv[]){ Factorial[13] = 13*Factorial[12]; Factorial[14] = 14*Factorial[13]; Factorial[15] = 15*Factorial[14]; int amin=0; int amax=20; int numcomp = NumComp(); cout<<"Number of components:"<<numcomp<<"\n"; if(!ValidGrid()) {cout << "Invalid grid!!\n"; return 0;} // Check that the grid is valid time_t starttime = time(NULL); // Used to record how long this takes // Record winding numbers around grid points for Alexander grading computations // Also record the Alexander grading shift // Want this to be non-positive; if it isn't, exchange the white and black dots, // multiply all winding numbers by -1 and try again. int WN[gridsize][gridsize]; for(int x=0; x<gridsize; x++) { for(int y=0; y<gridsize; y++) { WN[x][y] = WindingNumber(x,y); } } int temp=0; for(int i=0; i<gridsize; i++) { temp += WN[i][black[i]]; temp += WN[i][(black[i]+1) % gridsize]; temp += WN[(i+1) % gridsize][black[i]]; temp += WN[(i+1) % gridsize][(black[i]+1) % gridsize]; } for(int i=0; i<gridsize; i++) { temp += WN[i][white[i]]; temp += WN[i][(white[i]+1) % gridsize]; temp += WN[(i+1) % gridsize][white[i]]; temp += WN[(i+1) % gridsize][(white[i]+1) % gridsize]; } const int AShift = (temp - 4 * gridsize + 4)/8; cout << "Alexander Grading Shift: " << AShift << "\n"; cout << "Matrix of winding numbers and Black/White grid:\n"; for(int y=gridsize-1; y>=0; y--) { for(int x=0; x<gridsize; x++) { if(WN[x][y] >= 0) cout << " "; cout << WN[x][y]; } cout << " "; for(int x=0; x<gridsize; x++) { cout << " "; if(black[x]==y) cout << "X"; if(white[x]==y) cout << "O"; if(black[x] != y && white[x] != y) cout << " "; } cout << "\n"; } // Record for later use whether every possible rectangle has a black or white dot in it // This will speed boundary computations. cout << "Computing which rectangles on the torus have no black or white dots inside.\n"; bool Rectangles[gridsize][gridsize][gridsize][gridsize][4]; for(int xll=0; xll < gridsize; xll++) { for(int xur=xll+1; xur < gridsize; xur++) { for(int yll=0; yll < gridsize; yll++) { for(int yur=yll+1; yur < gridsize; yur++) { Rectangles[xll][yll][xur][yur][0] = RectDotFree(xll,yll,xur,yur,0); Rectangles[xll][yll][xur][yur][1] = RectDotFree(xll,yll,xur,yur,1); Rectangles[xll][yll][xur][yur][2] = RectDotFree(xll,yll,xur,yur,2); Rectangles[xll][yll][xur][yur][3] = RectDotFree(xll,yll,xur,yur,3); } } } } // Iterate through the generators in lexicographic // order and calculate their boundaries // Identify each permutation with the integer given by the number of permutations preceding // it in lexicographic order. // Populate Graph[count].out with a list of integers corresponding to the permutations that // are boundaries of the permutation corresponding to count. // Populate Graph[count]. int NumGenByAGrading[60]; // NumGenByAGrading[i] holds number of generators in A Grading i-30 vector<long long> label; // label[i] will hold the number of perms lexicographically before the i^th generator for(int i=0; i<60; i++) NumGenByAGrading[i]=0; int g[gridsize]; cout << "Iterating through " << Factorial[gridsize] << " generators to compute Alexander gradings...\n"; long long count=0; // Loop through generators... change the loop for different gridsize // This array is a factorial base counter used for counting through // permutations. - MC short counter[gridsize-1]; for(int i=0; i<gridsize-1; i++) counter[i] = 0; for(count = 0; count < Factorial[gridsize]; count++) { NextPerm(counter,g); int AGrading = AShift; for(int i=0; i<gridsize; i++) AGrading -= WN[i][g[i]]; if (AGrading >= amin && AGrading <= amax) { label.push_back(count); NumGenByAGrading[AGrading+30]++; } } for(int i=0;i<60;i++) { if(NumGenByAGrading[i]>0) cout << "Number of generators in Alexander grading " << (i-30) << ": " << NumGenByAGrading[i] << "\n"; } cout << "Total generators: " << label.size() << "\n"; vector<Generator> Graph( label.size() ); // Will hold boundary data. cout << "Populating the Graph...\n"; long long edges=0; for(int index=0; index < label.size(); index++) { GetPerm(label[index],g); bool firstrect; bool secondrect; for(int i=0; i<gridsize; i++) { for(int j=i+1; j<gridsize; j++) { if(g[i]<g[j]) { firstrect = Rectangles[i][g[i]][j][g[j]][0]; for(int k=i+1; k<j && firstrect; k++) { if(g[i] < g[k] && g[k] < g[j]) firstrect=0; } secondrect = Rectangles[i][g[i]][j][g[j]][1]; for(int k=0; k<i && secondrect; k++) { if(g[k]<g[i] || g[k] > g[j]) secondrect=0; } for(int k=j+1; k<gridsize && secondrect; k++) { if(g[k]<g[i] || g[k] > g[j]) secondrect=0; } } if(g[j]<g[i]) { firstrect = Rectangles[i][g[j]][j][g[i]][2]; for(int k=i+1; k<j && firstrect; k++) { if(g[k]<g[j] || g[k] > g[i]) firstrect=0; } secondrect = Rectangles[i][g[j]][j][g[i]][3]; for(int k=0; k<i && secondrect; k++) { if(g[k]>g[j] && g[k]<g[i]) secondrect=0; } for(int k=j+1; k<gridsize && secondrect; k++) { if(g[k]>g[j] && g[k]<g[i]) secondrect=0; } } if(firstrect != secondrect) { // Exactly one rectangle is a boundary int gij [gridsize]; for(int k=0; k<i; k++) { gij[k] = g[k]; } gij[i]=g[j]; for(int k=i+1; k<j; k++) { gij[k]=g[k]; } gij[j] = g[i]; for(int k=j+1; k<gridsize; k++) { gij[k] = g[k]; } long long Indexgij = Index(gij); int indexgij = Find(label,Indexgij); if(indexgij==-1) {cout << "Error with Alexander grading:\n"; return 0; } Graph[index].out.push_back( indexgij ); Graph[indexgij].in.push_back( index ); edges++; } } } } cout << "Done computing the graph. Total edges (boundaries): " << edges << ".\n"; //PrintGraph(Graph); // Kill all the edges in the graph. // No live generator should ever have a dead generator on its "out" list cout << "Killing edges in the graph...\n"; for(int i=0; i<Graph.size(); i++) { if(i % 1000000 == 0 && i > 0) cout << "Finished " << i << " generators.\n"; if( (!Graph[i].alive) || Graph[i].out.size()==0) continue; int target = Graph[i].out.front(); // We plan to delete the edge from i to target... // For every m with i in dm, remove i from dm for(list<int>::iterator j=Graph[i].in.begin(); j!=Graph[i].in.end(); j++) { if(Graph[*j].alive) Graph[*j].out.remove(i); } Graph[i].alive = 0; // For every m with target in dm adjust dm appropriately for(list<int>::iterator j= Graph[ target ].in.begin(); j != Graph[ target ].in.end(); j++) { if( !Graph[*j].alive ) continue; for(list<int>::iterator k = Graph[i].out.begin(); k != Graph[i].out.end(); k++) { // Search for *k in the boundary of *j // If found, remove it; if not, add it to the boundary of *j list<int>::iterator search = find( Graph[*j].out.begin(), Graph[*j].out.end(), *k); if( search != Graph[*j].out.end() ) { Graph[ *j ].out.erase( search ); if( *k != target) Graph[ *k ].in.remove( *j ); } else { Graph[*j].out.push_back(*k); Graph[*k].in.push_back(*j); } } } // For each a in di, remove i from the in list of a for(list<int>::iterator j=Graph[i].out.begin(); j != Graph[i].out.end(); j++) Graph[*j].in.remove(i); Graph[target].alive = 0; Graph[target].out.clear(); Graph[target].in.clear(); Graph[i].out.clear(); Graph[i].in.clear(); } int HomologyRanks [60][60]; // HomologyRanks[i][j] will hold rank of homology Maslov grading=i-30 and Alexander grading j-30 for(int a=0; a<60; a++) { for(int m=0; m<60; m++) HomologyRanks[m][a]=0; } for(int i=0; i< Graph.size(); i++) { if(Graph[i].alive) { GetPerm(label[i],g); int AGrading = AShift; for(int j=0; j<gridsize; j++) AGrading -= WN[j][g[j]]; HomologyRanks[MaslovGrading(g)+30][AGrading+30]++; } } cout << "Ranks of unshifted homology groups in Alexander grading [" << amin << "," << amax << "]:\n"; for(int a=amax+30; a>=amin+30; a--) { for(int m=20; m<40; m++) { if(HomologyRanks[m][a] < 10) cout << " "; if(HomologyRanks[m][a] >= 10 && HomologyRanks[m][a] < 100) cout << " "; if(HomologyRanks[m][a] >= 100 && HomologyRanks[m][a] < 1000) cout << " "; cout << HomologyRanks[m][a]; } cout << "\n"; } int HFKRanks [60][60]; // HFKRanks[i][j] will hold rank of HFK^ in Maslov grading=i-30 and Alexander grading=j-30 for(int a=0; a<60; a++) { for(int m=0; m<60; m++) HFKRanks[m][a]=0; } // Reproduce HFK^ from HFK^ \otimes K^{gridsize-1} in non-negative Alexander grading for(int a=59; a>=0; a--) { for(int m=59; m>=0; m--) { if( HomologyRanks[m][a] > 0) { HFKRanks[m][a] = HomologyRanks[m][a]; for(int i=0; i<=gridsize-numcomp; i++) HomologyRanks[m-i][a-i] -= (HFKRanks[m][a] * Factorial[gridsize-numcomp]) / (Factorial[i] * Factorial[gridsize-numcomp-i]); } } } // Use symmetry to fill up HFKRanks in negative Alexander gradings for(int alex=-1; alex>=-9; alex--){ for(int mas=-20; mas < 12; mas++) { HFKRanks[mas+30][alex+30] = HFKRanks[mas-2*alex+30 ][-alex+30]; } } if(amin > 0) cout << "This Poincare polynomial is only valid in Alexander grading >= " << amin << ":\n"; // Print Results bool first=1; for(int a=-20; a<19; a++) { for(int m=-20; m<19; m++) { int rankam = HFKRanks[m+30][a+30]; if(rankam > 0) { if(!first) cout << "+"; else first=0; if(rankam > 1 || (rankam==1 && a==0 && m==0) ) cout << rankam; if(m==1) cout << "q"; if(m != 0 && m != 1) cout << "q^{" << m << "}"; if(a==1) cout << "t"; if(a != 0 && a != 1) cout << "t^{" << a << "}"; } } } cout << "\n"; time_t endtime = time(NULL); cout << "Total time elapsed: " << (endtime-starttime) << " seconds.\n"; return 0; } // Class Functions Generator::Generator(){alive=1;}; Generator::~Generator(){}; // Actual Functions int NumComp(){ int nc = 0; int c[gridsize]; int d=0; int k; for (int i=0; i<gridsize; i++) c[i]=i; int dblack[gridsize]; int dwhite[gridsize]; for (int i =0; i<gridsize; i++){ dblack[black[i]]=i; dwhite[white[i]]=i; } bool t=0; while(!t){ d=0; k=0; while(c[k]==-1){ d++; k++; } c[d]=-1; int l = dblack[white[d]]; while(l!=d){ c[l]=-1; l=dblack[white[l]]; } nc++; t=1; for (int j=0; j<gridsize; j++) t = t&& (c[j] ==-1); } return nc; } int Find(vector<long long> & V, long long x) { int above=V.size()-1; int below=0; while(above - below > 1) { if (x >= V[below+(above-below)/2]) below += (above-below)/2; else above = below+(above-below)/2; } if (V[below] == x) return below; if (V[above] == x) return above; return -1; } int WindingNumber(int x, int y){ // Return winding number around (x,y) int ret=0; for(int i=0; i<x; i++) { if ((black[i] >= y) && (white[i] < y)) ret++; if ((white[i] >= y) && (black[i] < y)) ret--; } return ret; } int MaslovGrading(int y []) { // Use the formula: // 4M(y) = 4M(white)+4P_y(R_{y, white})+4P_{white}(R_{y, white})-8W(R_{y, white}) // = 4-4*gridsize+4P_y(R_{y, white})+4P_{x_0}(R_{y, white})-8W(R_{y, white}) int P=4-4*gridsize; // Four times the Maslov grading for(int i=0; i<gridsize; i++) { // Calculate incidence number R_{y x_0}.S for each of the four // squares S having (i,white[i]) as a corner and each of the // four squares having (i,y[i]) as a corner and shift P appropriately for(int j=0; j<=i; j++) { // Squares whose BL corners are (i,white[i]) and (i,y[i]) if ((white[j] > white[i]) && (y[j] <= white[i])) P-=7; // because of the -8W(R_{y, white}) contribution if ((y[j] > white[i]) && (white[j] <= white[i])) P+=7; if ((white[j] > y[i]) && (y[j] <= y[i])) P++; if ((y[j] > y[i]) && (white[j] <= y[i])) P--; } for(int j=0; j<=((i-1)% gridsize); j++) { // Squares whose BR corners are (i,white[i]) and (i,y[i]) (mod gridsize) if ((white[j] > white[i]) && (y[j] <= white[i])) P++; if ((y[j] > white[i]) && (white[j] <= white[i])) P--; if ((white[j] > y[i]) && (y[j] <= y[i])) P++; if ((y[j] > y[i]) && (white[j] <= y[i])) P--; } for(int j=0; j<=((i-1) % gridsize); j++) { // Squares whose TR corners are... if ((white[j] > ((white[i]-1) % gridsize)) && (y[j] <= ((white[i]-1) % gridsize))) P++; if ((y[j] > ((white[i]-1) % gridsize) ) && (white[j] <= ((white[i]-1) % gridsize))) P--; if ((white[j] > ((y[i]-1) % gridsize)) && (y[j] <= ((y[i]-1) % gridsize))) P++; if ((y[j] > ((y[i]-1) % gridsize) ) && (white[j] <= ((y[i]-1) % gridsize))) P--; } for(int j=0; j<=i; j++) { // Squares whose TL corners are... if ((white[j] > ((white[i]-1) % gridsize)) && (y[j] <= ((white[i]-1) % gridsize))) P++; if ((y[j] > ((white[i]-1) % gridsize) ) && (white[j] <= ((white[i]-1) % gridsize))) P--; if ((white[j] > ((y[i]-1) % gridsize)) && (y[j] <= ((y[i]-1) % gridsize))) P++; if ((y[j] > ((y[i]-1) % gridsize) ) && (white[j] <= ((y[i]-1) % gridsize))) P--; } } return (P/4); } bool RectDotFree(int xll, int yll, int xur, int yur, int which) { bool dotfree = 1; switch (which) { case 0: for(int x=xll; x<xur && dotfree; x++) { if (white[x] >= yll && white[x] < yur) dotfree = 0; if (black[x] >= yll && black[x] < yur) dotfree = 0; } return dotfree; case 1: for(int x=0; x<xll && dotfree; x++) { if (white[x] < yll || white[x] >= yur) dotfree = 0; if (black[x] < yll || black[x] >= yur) dotfree = 0; } for(int x=xur; x<gridsize && dotfree; x++) { if (white[x] < yll || white[x] >= yur) dotfree = 0; if (black[x] < yll || black[x] >= yur) dotfree = 0; } return dotfree; case 2: for(int x=xll; x<xur && dotfree; x++) { if (white[x] < yll || white[x] >= yur) dotfree = 0; if (black[x] < yll || black[x] >= yur) dotfree = 0; } return dotfree; case 3: for(int x=0; x<xll && dotfree; x++) { if (white[x] >= yll && white[x] < yur) dotfree = 0; if (black[x] >= yll && black[x] < yur) dotfree = 0; } for(int x=xur; x<gridsize && dotfree; x++) { if (white[x] >= yll && white[x] < yur) dotfree = 0; if (black[x] >= yll && black[x] < yur) dotfree = 0; } return dotfree; } return 0; //Error! } bool ValidGrid() { int numwhite=0; int numblack=0; for(int i=0; i<gridsize; i++) { for(int j=0; j<gridsize; j++) { if (white[j]==i) numwhite++; if (black[j]==i) numblack++; } if (numwhite != 1 || numblack != 1) { std::cout << "\nInvalid Grid!\n"; return 0; } numwhite=0; numblack=0; } return 1; } // Code below added by MC // Maps a permutation of size n to an integer < n! // See: Knuth, Volume 2, Section 3.3.2, Algorithm P long long Index(int P []) { long long index=0; int temp, m, r = gridsize; while (r > 0){ for (m=0; m < r; m++){ if (r - P[m] == 1) break; } index = index*(r) + m; r -= 1; temp = P[r]; P[r] = P[m]; P[m] = temp; } return index; } // Inverse mapping, from integers < n! to permutations of size n // Writes the permutation corresponding to N into the array P. void GetPerm(long long N, int P []) { int r, m, temp; for(int i=0; i<gridsize; i++) P[i]=i; r = 1; while (r < gridsize) { m = N%(r+1); N = N/(r+1); temp = P[r]; P[r] = P[m]; P[m] = temp; r += 1; } return; } // Generator for permutations. Inputs a factorial based counter and // an array. Writes the permutation indexed by the counter into the // array, and then increments the counter. void NextPerm(short counter[], int P[]) { int r, m, temp, i; for(i=0; i<gridsize; i++) P[i]=i; r = 1; while (r < gridsize) { m = counter[r-1]; temp = P[r]; P[r] = P[m]; P[m] = temp; r += 1; } for (i=0; i<gridsize-1; i++) { counter[i] += 1; if (counter[i] == i+2) counter[i] = 0; else break; } return; }
[ "benjamin.lip@c2f0229c-37c9-6e89-a4ff-2bb24d9bb920" ]
[ [ [ 1, 578 ] ] ]
8dfc2cc9da28b043101fa11b10b825d5cf2a8432
21da454a8f032d6ad63ca9460656c1e04440310e
/test/utest/WscomTest.h
15336e15f0f4b8879031e35cbe6d59112519962b
[]
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
UTF-8
C++
false
false
354
h
#pragma once #include "testcase.h" class WscomTest : public TestCase { public: static const ws_char * const s_class_name; public: WscomTest(void); ~WscomTest(void); static void New(iTestCase ** ret); WS_METHOD( ws_result , doTest )(void); void test_LoadLibrary(void); void test_WSCOM_static_funcs(void); };
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 24 ] ] ]
86b2076319b6b7abff36e7a10167128d0f16ddac
c034a6ffa81773a279c4cd25bdbd3b23a999d4b7
/gmfcomp/GMFComp/gmidFunctions.cpp
5b4973efaf6c644ff2c1c0b2b6b2383d2870eff4
[]
no_license
Shima33/gmftoolkit
08ee92bb5700af984286c71dd54dbfd1ffecd35a
0e602d27b9b8cce83942f9624cbb892b0fd44b6b
refs/heads/master
2021-01-10T15:45:10.838305
2010-06-20T19:09:19
2010-06-20T19:09:19
50,957,203
0
0
null
null
null
null
UTF-8
C++
false
false
13,417
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <windows.h> #include "byteFunctions.h" #include "asciiFunctions.h" #include "objectFunctions.h" extern FILE* input; extern FILE* output; int readGMIDAttachmentPt() { printInt(21); printInt(2); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); char* ptName = readString("*NODE_NAME"); printString(ptName); readTM(); fscanf(input, "USER DATA"); fgetc(input); int offset = ftell(input); int length = 0; while (fgetc(input) != '}') length++; fseek(input, offset, 0); char* ptUserData = (char*)malloc(sizeof(char)*(length+1)); fread(ptUserData, sizeof(char), length, input); ptUserData[length-2] = '\x00'; if (length != 0) printString(ptUserData); else printInt(0); closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(size); fseek(output, endOffset, 0); return 0; } int readHavokSimobject() { printInt(30); printInt(2); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); char* soName = readString("*NODE_NAME"); if (strncmp("(null)", soName, 6)) printString(soName); else printInt(0); bracketize(); float soGravity[3]; fscanf(input, "*GRAVITY\t%f %f %f\n", &soGravity[0], &soGravity[1], &soGravity[2]); float soWorldScale = readFloat("*WORLDSCALE"); float soSimTolerance = readFloat("*SIMTOLERANCE"); int soResolver = readInt("*RESOLVER"); int soIncludeDrag = readInt("*INCLUDE_DRAG"); float soLinearDrag = readFloat("*LINEAR_DRAG"); float soAngularDrag = readFloat("*ANGULAR_DRAG"); int soDeactivator = readInt("*INCLUDE_DEACTIVATOR"); float soShortFreq = readFloat("*SHORTFREQ"); float soLongFreq = readFloat("*LONGFREQ"); int soUseFastSubspace = readInt("*USE_FAST_SUBSPACE"); float soUpdatesPerTimeStep = readFloat("*UPDATES_PER_TIMESTEP"); int soNumCollisionPairs = readInt("*NUM_COLLISION_PAIRS"); printFloat(soGravity[0]); printFloat(soGravity[1]); printFloat(soGravity[2]); printFloat(soWorldScale); printFloat(soSimTolerance); printBytes((char*)&soResolver, 1); printInt(soIncludeDrag); printFloat(soLinearDrag); printFloat(soAngularDrag); printBytes((char*)&soDeactivator, 1); printFloat(soShortFreq); printFloat(soLongFreq); printBytes((char*)&soUseFastSubspace, 1); printFloat(soUpdatesPerTimeStep); printInt(soNumCollisionPairs); closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(size - 4); fseek(output, endOffset, 0); return 0; } int readHavokRB() { printInt(32); printInt(4); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); char* rbName = readString("*NODE_NAME"); printString(rbName); float rbMass = readFloat("*MASS"); printFloat(rbMass); float rbElasticity = readFloat("*ELASTICITY"); printFloat(rbElasticity); float rbFriction = readFloat("*FRICTION"); printFloat(rbFriction); float rbOptimization = readFloat("*OPTIMIZATION_LEVEL"); printFloat(rbOptimization); int rbUnyielding = readInt("*UNYIELDING"); printInt(rbUnyielding); int rbSimulationGeometry = readInt("*SIMULATION_GEOMETRY"); printInt(rbSimulationGeometry); char* rbGeometryProxyName = readString("*GEOMETRY_PROXY_NAME"); if(strncmp(rbGeometryProxyName, "(null)", 6)) printString(rbGeometryProxyName); else printInt(0); int rbUseDisplayProxy = readInt("*USE_DISPLAY_PROXY"); printBytes((char*)&rbUseDisplayProxy, 1); int rbDisableCollisions = readInt("*DISABLE_COLLISIONS"); printBytes((char*)&rbDisableCollisions, 1); int rbInactive = readInt("*INACTIVE"); printBytes((char*)&rbInactive, 1); char* rbDisplayProxyName = readString("*DISPLAY_PROXY_NAME"); if(strncmp(rbDisplayProxyName, "(null)", 6)) printString(rbDisplayProxyName); else printInt(0); readTM(); char* rbHavokGeoType = readString("*HAVOK_GEO_TYPE"); if (!strncmp(rbHavokGeoType, "Standard", 8)) printInt(0); else printInt(0); int rbNumberOfChildren = readInt("*NUMBER_OF_CHILDREN"); printInt(rbNumberOfChildren); closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(0); fseek(output, endOffset, 0); return 0; } int readHavokRBList() { printInt(33); printInt(2); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); int rblCount = readInt("*COUNT"); printInt(rblCount); int i; for (i = 0; i < rblCount; i++) { readNothing("*GMID_HAVOK_RIGIDBODY"); readHavokRB(); } closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(0); //yes, this is weird, but otherwise RA2 crashes. fseek(output, endOffset, 0); return 0; } int readHavokDisabledPairs() { printInt(51); printInt(2); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); int dpNumPairs = readInt("*COUNT"); printInt(dpNumPairs); int i; for (i = 0; i < dpNumPairs; i++) { bracketize(); //fscanf(input, "{ %s\t%s }"); int body1Length = 0; int body2Length = 0; fscanf(input, "{ %i", &body1Length); char* body1 = (char*)malloc(sizeof(char) * body1Length); fscanf(input, "%s\t%i", body1, &body2Length); char* body2 = (char*)malloc(sizeof(char) * body1Length); fscanf(input, "%s }\n", body2); printString(body1); printString(body2); } closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(0); // WUT fseek(output, endOffset, 0); return 0; } int readHavokRBCollection() { printInt(31); printInt(4); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); char* rbcName = readString("*NODE_NAME"); int rbcNumDisabledPairs = readInt("*NUM_DISABLED_PAIRS"); int rbcSolverType = readInt("*SOLVER_TYPE"); int rbcRbCount = readInt("*COUNT"); printString(rbcName); printInt(rbcNumDisabledPairs); printInt(rbcSolverType); bracketize(); char* nextThing = (char*)malloc(sizeof(char)*128); while(1) { int offset = ftell(input); fscanf(input, "%s\n", nextThing); if (!strncmp(nextThing, "*GMID_HAVOK_RIGIDBODY_LIST", 26)) { /*fscanf(input, "\t%*i\n"); readNothing("*GMID_HAVOK_RIGIDBODY_LIST");*/ readHavokRBList(); } else if (!strncmp(nextThing, "*COUNT", 6)) { fscanf(input, "\t%*i\n"); readNothing("*GMID_HAVOK_RIGIDBODY_LIST"); readHavokRBList(); } else if (!strncmp(nextThing, "*GMID_HAVOK_DIS_COLLISION_PAIRS", 31)) { readHavokDisabledPairs(); } else if (!strncmp(nextThing, "}", 1)) { fseek(input, offset, 0); break; } else { error(nextThing); } } closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(size); fseek(output, endOffset, 0); return 0; } int readHavokHingeC() { printInt(47); printInt(2); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); char* cName = readString("*NODE_NAME"); printString(cName); readTM(); char* cBody1 = readString("*BODY1"); char* cBody2 = readString("*BODY2"); float p[3]; bracketize(); fscanf(input, "*POINT %f\t%f\t%f\n", &p[0], &p[1], &p[2]); float s[3]; bracketize(); fscanf(input, "*SPIN_AXIS %f\t%f\t%f\n", &s[0], &s[1], &s[2]); int cLimited = readInt("*IS_LIMITED"); float cFriction = readFloat("*FRICTION"); float a[2]; bracketize(); fscanf(input, "*ANGLE_LIMITS %f\t%f\n", &a[0], &a[1]); printString(cBody1); printString(cBody2); printFloat(p[0]); printFloat(p[1]); printFloat(p[2]); printFloat(s[0]); printFloat(s[1]); printFloat(s[2]); printBytes((char*)&cLimited, 1); printFloat(cFriction); printFloat(a[0]); printFloat(a[1]); closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(0); fseek(output, endOffset, 0); return 0; } int readHavokPivotC() { MessageBox(NULL, "Warning! The PIVOT constraint is deprecated. Please use the WHEEL constraint instead (see decompiled carsteering for details)!\nThe file will continue to compile.", "Deprecation error", MB_ICONWARNING); printInt(46); printInt(2); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); char* cName = readString("*NODE_NAME"); printString(cName); readTM(); char* cBody1 = readString("*BODY1"); char* cBody2 = readString("*BODY2"); float p[3]; bracketize(); fscanf(input, "*POINT %f\t%f\t%f\n", &p[0], &p[1], &p[2]); float s[3]; bracketize(); fscanf(input, "*SPIN_AXIS %f\t%f\t%f\n", &s[0], &s[1], &s[2]); float unkn[8]; bracketize(); fscanf(input, "*UNKNOWN %f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n", &unkn[0], &unkn[1], &unkn[2], &unkn[3], &unkn[4], &unkn[5], &unkn[6], &unkn[7]); printString(cBody1); printString(cBody2); printFloat(p[0]); printFloat(p[1]); printFloat(p[2]); printFloat(s[0]); printFloat(s[1]); printFloat(s[2]); int x; for (x = 0; x < 8; x++) printFloat(unkn[x]); closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(0); fseek(output, endOffset, 0); return 0; } int readHavokWheelC() { printInt(46); printInt(2); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); char* cName = readString("*NODE_NAME"); printString(cName); readTM(); char* cBody1 = readString("*BODY1"); char* cBody2 = readString("*BODY2"); float p[3]; bracketize(); fscanf(input, "*POINT %f\t%f\t%f\n", &p[0], &p[1], &p[2]); float s[3]; bracketize(); fscanf(input, "*SPIN_AXIS %f\t%f\t%f\n", &s[0], &s[1], &s[2]); float suspAxis[3]; bracketize(); fscanf(input, "*SUSPENSION_AXIS %f\t%f\t%f\n", &suspAxis[0], &suspAxis[1], &suspAxis[2]); float suspLimits[2]; bracketize(); fscanf(input, "*SUSPENSION_LIMITS %f\t%f\n", &suspLimits[0], &suspLimits[1]); float suspFriction = readFloat("*SUSPENSION_FRICTION"); float angSpeed = readFloat("*ANGULAR_SPEED"); float gain = readFloat("*GAIN"); printString(cBody1); printString(cBody2); printFloat(p[0]); printFloat(p[1]); printFloat(p[2]); printFloat(s[0]); printFloat(s[1]); printFloat(s[2]); printFloat(suspAxis[0]); printFloat(suspAxis[1]); printFloat(suspAxis[2]); printFloat(suspLimits[0]); printFloat(suspLimits[1]); printFloat(suspFriction); printFloat(angSpeed); printFloat(gain); closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(0); fseek(output, endOffset, 0); return 0; } int readHavokCItem() { char* cType = (char*)malloc(sizeof(char)*128); bracketize(); fscanf(input, "%s\n", cType); if (!strncmp(cType, "*GMID_HAVOK_HINGE_CONSTRAINT", 28)) { readHavokHingeC(); } else if (!strncmp(cType, "*GMID_HAVOK_PIVOT_CONSTRAINT", 29)) { readHavokPivotC(); } else if (!strncmp(cType, "*GMID_HAVOK_WHEEL_CONSTRAINT", 29)) { readHavokWheelC(); } else { char* message = (char*)malloc(sizeof(char)*128); sprintf(message, "readHavokCItem(): Unknown Constraint type %s!", cType); error(message); } return 0; } int readHavokCList() { int cnlCountAgainOffset = ftell(output); printBytes("\xFF\xFF\xFF\xFF", 4); printInt(44); printInt(2); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); int clCount = readInt("*COUNT"); printInt(clCount); int curOffset = ftell(output); fseek(output, cnlCountAgainOffset, 0); printInt(clCount); fseek(output, curOffset, 0); int i; for(i = 0; i < clCount; i++) readHavokCItem(); closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(0); fseek(output, endOffset, 0); return 0; } int readHavokCSolver() { printInt(42); printInt(3); printBytes("\xFF\xFF\xFF\xFF", 4); int beginningOffset = ftell(output); openBracket(); char* csName = readString("*NODE_NAME"); float csThreshold = readFloat("*THRESHOLD"); char* csRBCollectionName = readString("*RB_COLLECTION_NAME"); printString(csName); printFloat(csThreshold); printString(csRBCollectionName); int offset = ftell(input); char* next = (char*)malloc(sizeof(char)*128); fscanf(input, "%s", next); fseek(input, offset, 0); if (strncmp(next, "}", 1)) { readNothing("*GMID_HAVOK_CONSTRAINT_LIST"); readHavokCList(); } else printInt(0); closeBracket(); int endOffset = ftell(output); int size = endOffset - beginningOffset; fseek(output, beginningOffset - 4, 0); printInt(size); fseek(output, endOffset, 0); return 0; }
[ "Bazanski@1d10bff2-9961-11dd-bd51-a78b85c98fae" ]
[ [ [ 1, 562 ] ] ]
9c7feeacc13a358feb245cf74b3a0d8787e9bd83
0f19aa6d0ba7b58e5ded3c63bb6846ab84d84c88
/dependencies/irrlicht/tests/testVector2d.cpp
0aa5fab480265c049b0d3947e519c09a1269040b
[ "LicenseRef-scancode-other-permissive", "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
aep/slay
200387b28b4dc1d21a9f5931967a85ff610d563a
daa808795fe352135e75a101520f208d4ba90433
refs/heads/master
2022-11-11T21:18:55.229691
2009-11-07T05:50:28
2009-11-07T05:50:28
275,114,718
0
0
null
null
null
null
UTF-8
C++
false
false
6,461
cpp
// Copyright (C) 2008-2009 Colin MacDonald // No rights reserved: this software is in the public domain. #include "testUtils.h" using namespace irr; using namespace core; template<class T> static bool compareVectors(const core::vector2d<T> & compare, const core::vector2d<T> & with) { if(compare != with) { logTestString("\nERROR: vector2d %.16f, %.16f != vector2d %.16f, %.16f\n", (f64)compare.X, (f64)compare.Y, (f64)with.X, (f64)with.Y); assert(compare == with); return false; } return true; } template <class T> static bool doTests() { #define COMPARE_VECTORS(compare, with)\ if(!compareVectors(compare, with)) return false; vector2d<T> vec(5, 5); vector2d<T> otherVec(10, 20); if(!equals(vec.getDistanceFrom(otherVec), (T)15.8113883)) { logTestString("vector2d::getDistanceFrom() failed\n"); assert(0); return false; } vec.rotateBy(45); // Test implicit (0, 0) center COMPARE_VECTORS(vec, vector2d<T>(0, (T)7.0710678118654755)); vec.normalize(); COMPARE_VECTORS(vec, vector2d<T>(0, (T)1.0000000461060017)); vec.set(10, 10); vector2d<T> center(5, 5); vec.rotateBy(-5, center); // -5 means rotate clockwise slightly, so expect the X to increase // slightly and the Y to decrease slightly. COMPARE_VECTORS(vec, vector2d<T>((T)10.416752204197017, (T)9.5451947767204359)); vec.set(5, 5); vec.normalize(); COMPARE_VECTORS(vec, vector2d<T>((T)0.70710681378841400, (T)0.70710681378841400)); vec.set(5, 5); otherVec.set(10, 20); logTestString("vector2df interpolation\n"); vector2d<T> interpolated; (void)interpolated.interpolate(vec, otherVec, 0.f); COMPARE_VECTORS(interpolated, otherVec); // 0.f means all the second vector (void)interpolated.interpolate(vec, otherVec, 0.25f); COMPARE_VECTORS(interpolated, vector2d<T>((T)8.75, (T)16.25)); (void)interpolated.interpolate(vec, otherVec, 0.75f); COMPARE_VECTORS(interpolated, vector2d<T>((T)6.25, (T)8.75)); (void)interpolated.interpolate(vec, otherVec, 1.f); COMPARE_VECTORS(interpolated, vec); // 1.f means all the first vector interpolated = vec.getInterpolated(otherVec, 0.f); COMPARE_VECTORS(interpolated, otherVec); // 0.f means all the second vector interpolated = vec.getInterpolated(otherVec, 0.25f); COMPARE_VECTORS(interpolated, vector2d<T>((T)8.75, (T)16.25)); interpolated = vec.getInterpolated(otherVec, 0.75f); COMPARE_VECTORS(interpolated, vector2d<T>((T)6.25, (T)8.75)); interpolated = vec.getInterpolated(otherVec, 1.f); COMPARE_VECTORS(interpolated, vec); // 1.f means all the first vector logTestString("vector2df quadratic interpolation\n"); vector2d<T> thirdVec(20, 10); interpolated = vec.getInterpolated_quadratic(otherVec, thirdVec, 0.f); COMPARE_VECTORS(interpolated, vec); // 0.f means all the 1st vector interpolated = vec.getInterpolated_quadratic(otherVec, thirdVec, 0.25f); COMPARE_VECTORS(interpolated, vector2d<T>((T)7.8125, (T)10.9375)); interpolated = vec.getInterpolated_quadratic(otherVec, thirdVec, 0.5f); COMPARE_VECTORS(interpolated, vector2d<T>((T)11.25, (T)13.75)); interpolated = vec.getInterpolated_quadratic(otherVec, thirdVec, 0.75f); COMPARE_VECTORS(interpolated, vector2d<T>((T)15.3125, (T)13.4375)); interpolated = vec.getInterpolated_quadratic(otherVec, thirdVec, 1.f); COMPARE_VECTORS(interpolated, thirdVec); // 1.f means all the 3rd vector // check if getAngle returns values matching those of the double precision version logTestString("vector2df getAngle\n"); for (s32 i=0; i<200; ++i) { core::vector2d<T> tmp((T)-1, (T)(-100+i)); core::vector2d<f64> ref(-1, -100+i); if (!equals(tmp.getAngle(),ref.getAngle(), 0.0003)) { logTestString("\nERROR: angle %.16f != angle %.16f\n", tmp.getAngle(), ref.getAngle()); return false; } f32 val = atan2f((float)tmp.Y, (float)tmp.X)*core::RADTODEG; if (val<=0) val=-val; else val=360-val; if (!equals((f32)tmp.getAngle(),val, 0.5f)) { logTestString("\nERROR: angle %.16f != atan2 %.16f\n vector %.16f, %.16f\n", tmp.getAngle(), val, tmp.X, tmp.Y); return false; } tmp = core::vector2d<T>((T)1, (T)(-100+i)); ref = core::vector2d<f64>(1, -100+i); if (!equals(tmp.getAngle(),ref.getAngle(), 0.0003)) { logTestString("\nERROR: angle %.16f != angle %.16f\n", tmp.getAngle(), ref.getAngle()); return false; } val = atan2f((float)tmp.Y, (float)tmp.X)*core::RADTODEG; if (val<=0) val=-val; else val=360-val; if (!equals((f32)tmp.getAngle(),val, 0.5f)) { logTestString("\nERROR: angle %.16f != atan2 %.16f\n vector %.16f, %.16f\n", tmp.getAngle(), val, tmp.X, tmp.Y); return false; } } core::vector2d<T> tmp(0, -100); core::vector2d<f64> ref(0, -100); if (!equals(tmp.getAngle(),ref.getAngle())) { logTestString("\nERROR: angle %.16f != angle %.16f\n", tmp.getAngle(), ref.getAngle()); return false; } tmp = core::vector2d<T>(0, 100); ref = core::vector2d<f64>(0, 100); if (!equals(tmp.getAngle(),ref.getAngle())) { logTestString("\nERROR: angle %.16f != angle %.16f\n", tmp.getAngle(), ref.getAngle()); return false; } core::vector2d<T> zeroZero(0, 0); core::vector2d<T> oneOne(1, 1); // Check if comparing (0.0, 0.0) with (1.0, 1.0) returns false. if(zeroZero == oneOne) { logTestString("\nERROR: vector2d %.16f, %.16f == vector2d %.16f, %.16f\n", (f64)zeroZero.X, (f64)zeroZero.Y, (f64)oneOne.X, (f64)oneOne.Y); return false; } return true; } /** Test the functionality of vector2d<T>, particularly methods that involve calculations done using different precision than <T>. Note that all reference vector2d<T>s are creating using double precision values cast to (T), as we need to test <f64>. */ bool testVector2d(void) { bool f32Success = doTests<f32>(); if(f32Success) logTestString("vector2df tests passed\n\n"); else logTestString("\n*** vector2df tests failed ***\n\n"); bool f64Success = doTests<f64>(); if(f64Success) logTestString("vector2d<f64> tests passed\n\n"); else logTestString("\n*** vector2d<f64> tests failed ***\n\n"); bool s32Success = doTests<s32>(); if(s32Success) logTestString("vector2di tests passed\n\n"); else logTestString("\n*** vector2di tests failed ***\n\n"); return f32Success && f64Success && s32Success; }
[ [ [ 1, 204 ] ] ]
90447e13caeba012fc58c926ce8e0082011d305a
d9f1cc8e697ae4d1c74261ae6377063edd1c53f8
/src/orders/StopOrder.h
516887745916cdb127cb31a71a7d432a546556ff
[]
no_license
commel/opencombat2005
344b3c00aaa7d1ec4af817e5ef9b5b036f2e4022
d72fc2b0be12367af34d13c47064f31d55b7a8e0
refs/heads/master
2023-05-19T05:18:54.728752
2005-12-01T05:11:44
2005-12-01T05:11:44
375,630,282
0
0
null
null
null
null
UTF-8
C++
false
false
125
h
#pragma once #include "order.h" class StopOrder : public Order { public: StopOrder(void); ~StopOrder(void); };
[ "opencombat" ]
[ [ [ 1, 10 ] ] ]
075e4929a78ce68539540a835c0e8224591d41b1
df070aa6eb5225412ebf0c3916b41449edfa16ac
/AVS_Transcoder_SDK/kernel/audio/AudioTransCoder_Lame/av3enc/src/psychfft.cpp
cfac5b431aae17709447d760eee8330085de3245
[]
no_license
numericalBoy/avs-transcoder
659b584cc5bbc4598a3ec9beb6e28801d3d33f8d
56a3238b34ec4e0bf3a810cedc31284ac65361c5
refs/heads/master
2020-04-28T21:08:55.048442
2010-03-10T13:28:18
2010-03-10T13:28:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,667
cpp
/* *********************************************************************** * COPYRIGHT AND WARRANTY INFORMATION * * Copyright 2004, Audio Video Coding Standard, Part III * * This software module was originally developed by * edited by * * DISCLAIMER OF WARRANTY * * These software programs are available to the users without any * license fee or royalty on an "as is" basis. The AVS disclaims * any and all warranties, whether express, implied, or statutory, * including any implied warranties of merchantability or of fitness * for a particular purpose. In no event shall the contributors or * the AVS be liable for any incidental, punitive, or consequential * damages of any kind whatsoever arising from the use of this program. * * This disclaimer of warranty extends to the user of this program * and user's customers, employees, agents, transferees, successors, * and assigns. * * The AVS does not represent or warrant that the program furnished * hereunder are free of infringement of any third-party patents. * Commercial implementations of AVS, including shareware, may be * subject to royalty fees to patent holders. Information regarding * the AVS patent policy is available from the AVS Web site at * http://www.avs.org.cn * * THIS IS NOT A GRANT OF PATENT RIGHTS - SEE THE AVS PATENT POLICY. ************************************************************************ */ #include <math.h> #include "psychfft.h" Complex set(double r,double i) { Complex temp; temp.real=r; temp.imag=i; return temp; } Complex conjg(Complex x) { Complex temp; temp.real=x.real; temp.imag=-x.imag; return temp; } Complex cmulc(Complex c1,Complex c2) { Complex temp; temp.real=c1.real*c2.real -c1.imag *c2.imag; temp.imag =c1.imag*c2.real +c1.real *c2.imag ; return temp; } Complex cmulf(Complex c1,float c2) { Complex temp; temp.real =c1.real *c2; temp.imag =c1.imag *c2; return temp; } Complex caddc(Complex c1,Complex c2) { Complex temp; temp.real =c1.real +c2.real ; temp.imag =c1.imag +c2.imag ; return temp; } Complex csubc(Complex c1,Complex c2) { Complex temp; temp.real =c1.real -c2.real ; temp.imag =c1.imag -c2.imag ; return temp; } void prepsychfft(int n,int mode,int *nexp,Complex *w) { int i,k,nt,nexp1; float s; Complex c1,c2; nexp1=1;nt=1; do{ nt=1; for(i=1;i<=nexp1;i++) nt=2*nt; if(nt>=n) break; nexp1=nexp1+1; }while(1); if(nt==n) { s=8*atan(1.0)/(float)(nt); c1=set(cos(s),-sin(s)); if(mode!=0) c1=conjg(c1); c2=set(1.,0); for(k=1;k<=nt;k++) { w[k]=c2; c2=cmulc(c2,c1); } } else { nexp1=-1; } *nexp=nexp1; } void psychfft(int n,int mode,float t,int nexp,Complex *w,Complex *x) { Complex c1,c2; int k,mm,ll,j,jj,kk,i,nn,nv2,nm1; float s; mm=1; ll=n; for(k=1;k<=nexp;k++) { nn=ll/2; jj=mm+1; for(i=1;i<=n;i=i+ll) { kk=i+nn; c1=caddc(x[i],x[kk]); x[kk]=csubc(x[i],x[kk]); x[i]=c1; } if(nn==1) continue; else { for(j=2;j<=nn;j++) { c2=w[jj]; for(i=j;i<=n;i=i+ll) { kk=i+nn; c1=caddc(x[i],x[kk]); x[kk]=cmulc(csubc(x[i],x[kk]),c2); x[i]=c1; } jj=jj+mm; } ll=nn; mm=mm*2; } } nv2=n/2; nm1=n-1; j=1; for(i=1;i<nm1;i++) { if(i>=j); else { c1=x[j]; x[j]=x[i]; x[i]=c1; } k=nv2; do { if(k>=j) break; else { j=j-k; k=k/2; } }while(1); j=j+k; } if(mode==0) s=t; else s=1./(t*(float)n); for(i=1;i<=n;i++) x[i]=cmulf(x[i],s); }
[ "[email protected]@6c8d3a4c-d4d5-11dd-b6b4-918b84bbd919" ]
[ [ [ 1, 192 ] ] ]
5776cde8bec86a626e2e03401ac9af7e9b3125be
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/console/Console_run.h
f1e5cf9d1720acb336afdf5c25533edc45628885
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
821
h
#ifndef MESECINA_CONSOLE_RUN #define MESECINA_CONSOLE_RUN #include <console/Console_logger.h> #include <QtCore/QString> class Console_run { public: Console_run(int argc, char* argv[]); ~Console_run(); virtual void do_processing() {} protected: void print_settings(QString start); Console_logger logger; int argc; char** argv; QString path_to_filename(const QString& path); static char* get_param_variable(int argc, char *argv[], char* filter); static bool assign_int_parameter_if_exists(int argc, char *argv[], char* filter, int &variable); static bool assign_float_parameter_if_exists(int argc, char *argv[], char* filter, double &variable); static bool assign_string_parameter_if_exists(int argc, char *argv[], char* filter, char* &variable); }; #endif //MESECINA_CONSOLE_RUN
[ "balint.miklos@localhost" ]
[ [ [ 1, 27 ] ] ]
d546a687871447f3bdfd5a946a2cd4a68c1d0fbc
2c1e5a69ca68fe185cc04c5904aa104b0ba42e32
/src/game/SUtil.cpp
e20781d7b84dd7f9948d7300abcebeb6fe0df7f6
[]
no_license
dogtwelve/newsiderpg
e3f8284a7cd9938156ef8d683dca7bcbd928c593
303566a034dca3e66cf0f29cf9eaea1d54d63e4a
refs/heads/master
2021-01-10T13:03:31.986204
2010-06-27T05:36:33
2010-06-27T05:36:33
46,550,247
0
1
null
null
null
null
UTF-8
C++
false
false
16,449
cpp
#include "SUtil.h" SUtil* SUtil::pSUtil = NULL; //-------------------------------------------------------------------------- SUtil::SUtil() //-------------------------------------------------------------------------- { // Graphics CGraphics& _g = GetDevice().GetScreenImage().GetGraphics(); g = &_g; // Random setSeed((int)SUTIL_GetTime()/1000); pDrawList = GL_NEW List2<ASpriteInstance*>(); // pDrawList->delmode = 1; // pDrawList->SetDelMode(L_DEL_ONLY_POINTER); pFont = GL_NEW S_KR_Font(SCREEN_WIDTH, SCREEN_HEIGHT); pSound = GL_NEW CMediaPlayer(); } //-------------------------------------------------------------------------- SUtil::~SUtil() //-------------------------------------------------------------------------- { SAFE_DELETE(pDrawList); SAFE_DEL(pFont); } //-------------------------------------------------------------------------- SUtil* SUtil::GetInstance() //-------------------------------------------------------------------------- { if(NULL == pSUtil) { pSUtil = GL_NEW SUtil(); } return pSUtil; } //-------------------------------------------------------------------------- void SUtil::FreeInstance() //-------------------------------------------------------------------------- { if(NULL != pSUtil) { delete pSUtil; pSUtil = NULL; } } //-------------------------------------------------------------------------- int SUtil::GetSpriteDB_Index(char* _packtype, int _spriteNum) //-------------------------------------------------------------------------- { int idx = 0; while(1) { if( !STRCMP(_packtype, PACK_SPRITE_MAP) ) {break;} else {idx+= SPRITE_MAP_MAX;} if( !STRCMP(_packtype, PACK_SPRITE_WORLDMAP) ) {break;} else {idx+= SPRITE_WORLDMAP_MAX;} if( !STRCMP(_packtype, PACK_SPRITE_UI) ) {break;} else {idx+= SPRITE_UI_MAX;} if( !STRCMP(_packtype, PACK_SPRITE_COSTUME) ) {break;} else {idx+= SPRITE_COSTUME_MAX;} if( !STRCMP(_packtype, PACK_SPRITE) ) {break;} else {idx+= SPRITE_MAX;} if( !STRCMP(_packtype, PACK_SPRITE_MON) ) {break;} else {idx+= SPRITE_MON_MAX;} if( !STRCMP(_packtype, PACK_SPRITE_NPC) ) {break;} else {idx+= SPRITE_NPC_MAX;} if( !STRCMP(_packtype, PACK_SPRITE_FACE) ) {break;} else {idx+= SPRITE_FACE_MAX;} if( !STRCMP(_packtype, PACK_SPRITE_MAINMENU) ) {break;} else {idx+= SPRITE_MAINMENU_MAX;} if( !STRCMP(_packtype, PACK_SPRITE_LOADING) ) {break;} else {idx+= SPRITE_LOADING_MAX;} if( !STRCMP(_packtype, PACK_SPRITE_CINEMA) ) {break;} else {idx+= SPRITE_CINEMA_MAX;} } idx += _spriteNum; return idx; } //-------------------------------------------------------------------------- ASprite* SUtil::LoadAsprite(char* _packtype, int _spriteNum) //-------------------------------------------------------------------------- { int idx = GetSpriteDB_Index(_packtype, _spriteNum); SpriteRefDB[idx] += 1; if(1 < SpriteRefDB[idx]) {return SpriteDB[idx];} byte* buf; //ASprite* tmpSprite = NULL; pGame->Data_init(_packtype); buf = pGame->Data_readAll(_spriteNum); SAFE_DEL(SpriteDB[idx]); SpriteDB[idx] = GL_NEW ASprite(); SpriteDB[idx]->Load(buf, 0); SpriteDB[idx]->uniqueIdx = idx; pGame->Data_free(); SAFE_DELETE(buf); return SpriteDB[idx]; } //-------------------------------------------------------------------------- void SUtil::LoadAspritePack(char* _packtype) //-------------------------------------------------------------------------- { // int idx = GetSpriteDB_Index(_packtype, _spriteNum); // // SpriteRefDB[idx] += 1; // if(1 < SpriteRefDB[idx]) {return SpriteDB[idx];} // // byte* buf; // //ASprite* tmpSprite = NULL; pGame->Data_init(_packtype); } //-------------------------------------------------------------------------- ASprite* SUtil::LoadAspriteFromPack(char* _packtype, int _spriteNum) //-------------------------------------------------------------------------- { int idx = GetSpriteDB_Index(_packtype, _spriteNum); SpriteRefDB[idx] += 1; if(1 < SpriteRefDB[idx]) {return SpriteDB[idx];} byte* buf; //ASprite* tmpSprite = NULL; // pGame->Data_init(_packtype); buf = pGame->Data_readAll(_spriteNum); SAFE_DEL(SpriteDB[idx]); SpriteDB[idx] = GL_NEW ASprite(); SpriteDB[idx]->Load(buf, 0); SpriteDB[idx]->uniqueIdx = idx; SAFE_DELETE(buf); return SpriteDB[idx]; } //-------------------------------------------------------------------------- void SUtil::ReleaseAspritePack() //-------------------------------------------------------------------------- { pGame->Data_free(); } //-------------------------------------------------------------------------- ASpriteInstance* SUtil::LoadAspriteInstance(ASprite* _Asprite, int xPos = 0, int yPos = 0) //-------------------------------------------------------------------------- { return (ASpriteInstance*)(GL_NEW ASpriteInstance(_Asprite, xPos, yPos, NULL)); } //-------------------------------------------------------------------------- void SUtil::FreeAsprite(ASprite* _delAsprite) //-------------------------------------------------------------------------- { if(NULL == _delAsprite) {return;} int idx = _delAsprite->uniqueIdx; SpriteRefDB[idx] -= 1; if(1 > SpriteRefDB[idx]) { SAFE_DELETE(SpriteDB[idx]); } } //-------------------------------------------------------------------------- void SUtil::FreeAspriteInstance(ASpriteInstance* _delAspriteInstance) //-------------------------------------------------------------------------- { SAFE_DELETE(_delAspriteInstance); } //-------------------------------------------------------------------------- void SUtil::PaintAsprite(ASpriteInstance* _srcASpriteInstance, int issort) //-------------------------------------------------------------------------- { if(S_NOT_INCLUDE_SORT == issort) { _srcASpriteInstance->PaintSprite(g); } else { if(0 == GetNodeCount(pDrawList)) { MoveTail(pDrawList); pDrawList->Insert_prev(_srcASpriteInstance); return; } else { MoveHead(pDrawList); MoveNext(pDrawList); while(NotEndList(pDrawList)) { if(GetData(pDrawList)->m_posY > _srcASpriteInstance->m_posY) { pDrawList->Insert_prev(_srcASpriteInstance); return; } MoveNext(pDrawList); } } pDrawList->Insert_prev(_srcASpriteInstance); /* pDrawList->Move(L_START); if(0 == pDrawList->GetCount()) { pDrawList->Insert(_srcASpriteInstance); return; } while(NULL != pDrawList->CurNode()) { if(pDrawList->CurNode()->m_posY > _srcASpriteInstance->m_posY) { pDrawList->Insert(_srcASpriteInstance, L_IPRE); return; } if(!(pDrawList->Move(L_NEXT))) {break;} } pDrawList->Insert(_srcASpriteInstance, L_INEXT); */ } } //-------------------------------------------------------------------------- void SUtil::InitAni(ASprite* p_Asprite) //-------------------------------------------------------------------------- { p_Asprite->InitAnimation(); } //-------------------------------------------------------------------------- void SUtil::PaintAni(ASprite* p_Asprite, int ani, int posX, int posY, int flags/*, bool LOOP*/) //-------------------------------------------------------------------------- { p_Asprite->PaintAnimation(g, ani, posX, posY, flags, 0, 0/*, LOOP*/); } //-------------------------------------------------------------------------- void SUtil::PaintFrame(ASprite* p_Asprite, int frame, int posX, int posY, int flags) //-------------------------------------------------------------------------- { p_Asprite->PaintFrame(g, frame, posX, posY, flags, 0, 0); } //-------------------------------------------------------------------------- void SUtil::PaintModule(ASprite* p_Asprite, int module, int posX, int posY, int flags, int anchor) //-------------------------------------------------------------------------- { p_Asprite->PaintModule(g, module, posX, posY, flags, anchor); } //-------------------------------------------------------------------------- void SUtil::UpdateAsprite() //-------------------------------------------------------------------------- { MoveHead(pDrawList); MoveNext(pDrawList); while(NotEndList(pDrawList)) { GetData(pDrawList)->PaintSprite(g); MoveNext(pDrawList); } MoveHead(pDrawList); MoveNext(pDrawList); while(NotEndList(pDrawList)) { pDrawList->Delete(); } /* pDrawList->Move(L_START); while(NULL != pDrawList->CurNode()) { pDrawList->CurNode()->PaintSprite(g); if(!(pDrawList->Move(L_NEXT))) {break;} } pDrawList->Move(L_START); pDrawList->DeleteAll(); */ } //-------------------------------------------------------------------------- void SUtil::SetTypeAsprite(ASpriteInstance* _srcASpriteInstance, int type, int printnum) //-------------------------------------------------------------------------- { switch(type) { case 0 : {_srcASpriteInstance->SetModule(printnum); break;} // module case 1 : {_srcASpriteInstance->SetFrame(printnum); break;} // frame case 2 : {_srcASpriteInstance->SetAnim(printnum); break;} // animation default: {break;} } } //-------------------------------------------------------------------------- void SUtil::SetDirAsprite(ASpriteInstance* _delAspriteInstance, int flag) //-------------------------------------------------------------------------- { if(SDIR_LEFT == flag) {_delAspriteInstance->m_flags=1;} else if(SDIR_RIGHT == flag) {_delAspriteInstance->m_flags=0;} } void SUtil::getAniRect( int *rc, ASprite* asp, int aniIdx, int aniFrmIdx) { int off = (asp->_anims_af_start[aniIdx] + aniFrmIdx) * 5; int frame = asp->_aframes[off]&0xFF; asp->GetFrameRect(rc, frame, 0, 0, (asp->_aframes[off+4]&0x0F), -asp->_aframes[off+2], -asp->_aframes[off+3]); } //-------------------------------------------------------------------------- int SUtil::next(int bits) //-------------------------------------------------------------------------- { m_Seed = (m_Seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1); return (int)(m_Seed >> (48 - bits)); } //-------------------------------------------------------------------------- int SUtil::nextInt() //-------------------------------------------------------------------------- { int tmp = next(32); if(0 > tmp) {tmp *= (-1);} return tmp; } //-------------------------------------------------------------------------- int SUtil::nextInt(int n) //-------------------------------------------------------------------------- { if (n<=0) {return -1;} if ((n & -n) == n) // i.e., n is a power of 2 { return ((int)((n * (long)next(31)) >> 31)); } int bits, val; do { bits = next(31); val = bits % n; } while((bits - val + (n-1) < 0)); return val; } //-------------------------------------------------------------------------- long SUtil::nextLong() //-------------------------------------------------------------------------- { return ((long)next(32) << 32) + next(32); } //-------------------------------------------------------------------------- void SUtil::setSeed(long lSeed) //-------------------------------------------------------------------------- { m_Seed = (lSeed ^ 0x5DEECE66DL) & ((1L << 48) - 1); } //-------------------------------------------------------------------------- TEXT_PACK* SUtil::LoadTextPack(char* _packtype, int _TextNum) //-------------------------------------------------------------------------- { TEXT_PACK* tmpPack; tmpPack = GL_NEW TEXT_PACK; pGame->Data_init(_packtype); pGame->Data_open(_TextNum); tmpPack->nTextNum = pGame->Data_readS32(); int* offset = GL_NEW int [tmpPack->nTextNum+1]; // read text array offsets for (int i = 1; i < tmpPack->nTextNum+1; i++) {offset[i] = pGame->Data_readS32();} tmpPack->nText = GL_NEW byte*[tmpPack->nTextNum]; for (int i = 0; i < tmpPack->nTextNum; i++) { int size = offset[i+1] - offset[i]; tmpPack->nText[i] = GL_NEW byte[size+1]; MEMSET((char*)tmpPack->nText[i], 0, size+1); pGame->Data_read(tmpPack->nText[i], size); } pGame->Data_free(); SAFE_DEL_ARRAY(offset); return tmpPack; } //-------------------------------------------------------------------------- void SUtil::FreeTextPack(TEXT_PACK* pTextpack) //-------------------------------------------------------------------------- { if(pTextpack == NULL)return; for(int loop = 0; loop < pTextpack->nTextNum; loop++) { SAFE_DEL_ARRAY(pTextpack->nText[loop]); } SAFE_DEL_ARRAY(pTextpack->nText); SAFE_DELETE(pTextpack); } void SUtil::Sound_Load(int soundID) { if(pSound->m_pData[soundID]) return; if(soundID >= MAX_SOUND) return; CStream *stream; switch(soundID){ case EFFECT_SWORD_A : stream = GetResourceManager().GetResourceAsStream("/sfx_sword_A.mmf"); break; case EFFECT_SWORD_B : stream = GetResourceManager().GetResourceAsStream("/sfx_sword_B.mmf"); break; case EFFECT_SWORD_C : stream = GetResourceManager().GetResourceAsStream("/sfx_sword_C.mmf"); break; case EFFECT_SWORD_D : stream = GetResourceManager().GetResourceAsStream("/sfx_sword_D.mmf"); break; case EFFECT_GUN_A : stream = GetResourceManager().GetResourceAsStream("/sfx_shotgun_A.mmf"); break; case EFFECT_GUN_B : stream = GetResourceManager().GetResourceAsStream("/sfx_shotgun_B.mmf"); break; case EFFECT_ORB_A : stream = GetResourceManager().GetResourceAsStream("/sfx_orb_A.mmf"); break; case EFFECT_ORB_B : stream = GetResourceManager().GetResourceAsStream("/sfx_orb_B.mmf"); break; case EFFECT_ORB_C : stream = GetResourceManager().GetResourceAsStream("/sfx_orb_C.mmf"); break; case BGM_TEST_A : stream = GetResourceManager().GetResourceAsStream("/bgm_Test.mmf"); break; default: return; } pSound->m_pDataSize[soundID] = stream->GetLength(); pSound->m_pData[soundID] = GL_NEW/*(memType) */unsigned char[pSound->m_pDataSize[soundID]]; if(pSound->m_pData[soundID]) stream->Read(pSound->m_pData[soundID], pSound->m_pDataSize[soundID]); SAFE_DELETE(stream); } void SUtil::Sound_Play(int soundID, bool loopflag) { // if(g_pGame->m_sndVol == 0) return; if(soundID >= MAX_SOUND) return; pSound->PlaySound(soundID, true, loopflag); pSound->Update(); } void SUtil::Sound_Stop() { pSound->StopSound(); } void SUtil::Sound_Free(int soundID) { SAFE_DEL_ARRAY(pSound->m_pData[soundID]); } //void SUtil::setVol(int _vol) //{ // if( _vol < 0 ) // { // _vol = 0; // } // if( _vol > 100 ) // { // _vol = 100; // } // // pSound->m_nVolume = _vol; // // // // if(_vol == 0) // { // pSound->StopSound(); // } //} //void SUtil::getVol() //{ // return MC_mdaClipGetVolume(pSound-> m_pMediaPlayer); // /*if( _vol < 0 ) // { // _vol = 0; // } // if( _vol > 100 ) // { // _vol = 100; // } // // pSound->m_nVolume = _vol; // // // // if(_vol == 0) // { // pSound->StopSound(); // }*/ //} //////////////////////////////////////////////////////// /* //-------------------------------------------------------------------------- ASprite* SUtil::LoadAsprite(char* _packtype, int _spriteNum) //-------------------------------------------------------------------------- { byte* buf; ASprite* tmpSprite = NULL; pGame->Data_init(_packtype); buf = pGame->Data_readAll(_spriteNum); SAFE_DEL(tmpSprite); tmpSprite = GL_NEW ASprite(); tmpSprite->Load(buf, 0); pGame->Data_free(); SAFE_DELETE(buf); return tmpSprite; } //-------------------------------------------------------------------------- ASpriteInstance* SUtil::LoadAspriteInstance(ASprite* _Asprite, int xPos = 0, int yPos = 0) //-------------------------------------------------------------------------- { return (ASpriteInstance*)(GL_NEW ASpriteInstance(_Asprite, xPos, yPos, NULL)); } //-------------------------------------------------------------------------- void SUtil::FreeAsprite(ASprite* _delAsprite) //-------------------------------------------------------------------------- { SAFE_DELETE(_delAsprite); } */ ////////////////////////////////////////////////////////////
[ [ [ 1, 592 ] ] ]
af173511b10a674ae9b7dcb3443bc5ae7eb3ea91
ffb363eadafafb4b656355b881395f8d59270f55
/my/include/my/matrix.hpp
8fe2046d910cb57da3852d45f105c2dc1ee6f04d
[ "MIT" ]
permissive
hanji/matrix
1c28830eb4fdb7eefe21b2f415a9ec354e18f168
9f3424628ab182d249c62aeaf4beb4fb2d073518
refs/heads/master
2023-08-08T07:36:26.581667
2009-12-03T06:25:24
2009-12-03T06:25:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,658
hpp
#ifndef MY_MATRIX_HPP #define MY_MATRIX_HPP /* matrix.hpp Copyright (C) 2009, Ji Han Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdlib> #include <cstring> #include <cmath> #include <complex> #include <iostream> #if !defined(NOTHROW) # include <exception> #endif // !defined(NOTHROW) #include "my/real_traits.hpp" #include "my/promotion_traits.hpp" #include "my/vector.hpp" #include "my/matrix/matrix_base.hpp" #include "my/matrix/matrix_impl.hpp" #include "my/matrix/matrix_non_mem_fun.hpp" #include "my/matrix/matrix_slice.hpp" #include "my/matrix/matrix_slice_interop.hpp" #endif // MY_MATRIX_HPP
[ "[email protected]@2159fae2-c2cd-11de-acfc-b766374499fb", "hanji1984@2159fae2-c2cd-11de-acfc-b766374499fb" ]
[ [ [ 1, 47 ], [ 50, 51 ] ], [ [ 48, 49 ] ] ]
5980690853db133e189da3da6f71992356d2bb89
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/depends/ClanLib/src/Core/Text/string_help.cpp
796578687d1d6e93c1761927569ba06fa81680a3
[]
no_license
ptrefall/smn6200fluidmechanics
841541a26023f72aa53d214fe4787ed7f5db88e1
77e5f919982116a6cdee59f58ca929313dfbb3f7
refs/heads/master
2020-08-09T17:03:59.726027
2011-01-13T22:39:03
2011-01-13T22:39:03
32,448,422
1
0
null
null
null
null
UTF-8
C++
false
false
33,335
cpp
/* ** ClanLib SDK ** Copyright (c) 1997-2010 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ #include "precomp.h" #include "API/Core/Text/string_help.h" #include "API/Core/Text/logger.h" #include "API/Core/System/exception.h" #ifndef WIN32 #include <wchar.h> #include <wctype.h> #include <cstring> #include <cstdlib> #include <cstdio> #else #include <cstring> #include <tchar.h> #endif // This function or variable may be unsafe. Consider using xxxx instead. // To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details. #ifdef WIN32 #pragma warning(disable: 4996) #endif // We disable this warning because the usage patterns we use here are safe, // and although we could switch to newer more 'safe' versions, this may break // compilation in earlier versions of Visual Studio. -- mbn 13. sep 2006 #ifndef WIN32 #ifndef HAVE_WCSCASECMP int cl_wcscasecmp(const wchar_t *, const wchar_t *); #define wcscasecmp cl_wcscasecmp #endif #endif ///////////////////////////////////////////////////////////////////////////// // CL_StringHelp Operations: std::vector<CL_String> CL_StringHelp::split_text( const CL_StringRef &text, const CL_StringRef &split_string, bool skip_empty) { std::vector<CL_String> result; CL_String::size_type end_pos = 0, begin_pos = 0; while (true) { end_pos = text.find(split_string, begin_pos); if (end_pos == CL_String::npos) { if (begin_pos != text.length()) result.push_back(text.substr(begin_pos)); break; } else { if (!skip_empty || begin_pos != end_pos) result.push_back(text.substr(begin_pos, end_pos-begin_pos)); begin_pos = end_pos + split_string.length(); } } return result; } CL_String CL_StringHelp::trim(const CL_StringRef &text) { CL_String::size_type first_char = text.find_first_not_of(" \r\n\t"); CL_String::size_type last_char = text.find_last_not_of(" \r\n\t"); if (first_char == CL_String::npos) return CL_String(); if (last_char == CL_String::npos) return CL_String(); return text.substr(first_char, last_char - first_char + 1); } int CL_StringHelp::compare(const CL_StringRef8 &a, const CL_StringRef8 &b, bool case_insensitive) { #ifdef WIN32 if (case_insensitive) return stricmp(a.c_str(), b.c_str()); else return strcmp(a.c_str(), b.c_str()); #else if (case_insensitive) return strcasecmp(a.c_str(), b.c_str()); else return strcmp(a.c_str(), b.c_str()); #endif } int CL_StringHelp::compare(const CL_StringRef16 &a, const CL_StringRef16 &b, bool case_insensitive) { #ifdef WIN32 if (case_insensitive) return wcsicmp(a.c_str(), b.c_str()); else return wcscmp(a.c_str(), b.c_str()); #else if (case_insensitive) return wcscasecmp(a.c_str(), b.c_str()); else return wcscmp(a.c_str(), b.c_str()); #endif } CL_String CL_StringHelp::text_to_upper(const CL_StringRef &s) { return local8_to_upper(s); } CL_String8 CL_StringHelp::wchar_to_utf8(wchar_t value) { char text[8]; if ( (value < 0x80) && (value > 0) ) { text[0] = (char) value; text[1] = 0; } else if( value < 0x800 ) { text[0] = (char) ( 0xc0 | ( value >> 6 )); text[1] = (char) ( 0x80 | ( value & 0x3f )); text[2] = 0; } else if( value < 0x10000 ) { text[0] = (char) ( 0xe0 | ( value >> 12 )); text[1] = (char) ( 0x80 | ( (value >> 6) & 0x3f )); text[2] = (char) ( 0x80 | ( value & 0x3f )); text[3] = 0; } else if( value < 0x200000 ) { #ifndef WIN32 text[0] = (char) ( 0xf0 | ( value >> 18 )); #endif text[1] = (char) ( 0x80 | ( (value >> 12) & 0x3f )); text[2] = (char) ( 0x80 | ( (value >> 6) & 0x3f )); text[3] = (char) ( 0x80 | ( value & 0x3f )); text[4] = 0; } else if( value < 0x4000000 ) { #ifndef WIN32 text[0] = (char) ( 0xf8 | ( value >> 24 )); text[1] = (char) ( 0x80 | ( (value >> 18) & 0x3f )); #endif text[2] = (char) ( 0x80 | ( (value >> 12) & 0x3f )); text[3] = (char) ( 0x80 | ( (value >> 6) & 0x3f )); text[4] = (char) ( 0x80 | ( value & 0x3f )); text[5] = 0; } else if( value < 0x80000000 ) { #ifndef WIN32 text[0] = (char) ( 0xfc | ( value >> 30 )); text[1] = (char) ( 0x80 | ( (value >> 24) & 0x3f )); text[2] = (char) ( 0x80 | ( (value >> 18) & 0x3f )); #endif text[3] = (char) ( 0x80 | ( (value >> 12) & 0x3f )); text[4] = (char) ( 0x80 | ( (value >> 6) & 0x3f )); text[5] = (char) ( 0x80 | ( value & 0x3f )); text[6] = 0; } else { text[0] = 0; // Invalid wchar value } return text; } CL_String8 CL_StringHelp::local8_to_upper(const CL_StringRef8 &s) { CL_String8 result = s; CL_String8::size_type index, size; size = result.length(); for (index = 0; index < size; index++) { result[index] = (unsigned char) toupper((unsigned char) result[index]); } return result; } CL_String16 CL_StringHelp::ucs2_to_upper(const CL_StringRef16 &s) { CL_String16 result = s; CL_String16::size_type index, size; size = result.length(); for (index = 0; index < size; index++) { result[index] = towupper(result[index]); } return result; } CL_String CL_StringHelp::text_to_lower(const CL_StringRef &s) { return local8_to_lower(s); } CL_String8 CL_StringHelp::local8_to_lower(const CL_StringRef8 &s) { CL_String8 result = s; CL_String8::size_type index, size; size = result.length(); for (index = 0; index < size; index++) { result[index] = (unsigned char) tolower((unsigned char) result[index]); } return result; } CL_String16 CL_StringHelp::ucs2_to_lower(const CL_StringRef16 &s) { CL_String16 result = s; CL_String16::size_type index, size; size = result.length(); for (index = 0; index < size; index++) { result[index] = towlower(result[index]); } return result; } CL_String CL_StringHelp::float_to_text(float value, int num_decimal_places) { return float_to_local8(value, num_decimal_places); } CL_String8 CL_StringHelp::float_to_local8(float value, int num_decimals) { char buf[64]; memset(buf, 0, 64); #ifdef WIN32 _snprintf(buf, 63, ("%." + CL_StringHelp::int_to_local8(num_decimals) + "f").c_str(), value); #else snprintf(buf, 63, ("%." + CL_StringHelp::int_to_local8(num_decimals) + "f").c_str(), value); #endif return CL_String8(buf); } CL_String16 CL_StringHelp::float_to_ucs2(float value, int num_decimals) { #ifdef WIN32 WCHAR buf[64]; memset(buf, 0, 64 * sizeof(WCHAR)); swprintf(buf, ("%." + CL_StringHelp::int_to_ucs2(num_decimals) + "f").c_str(), value); return CL_String16(buf); #else wchar_t buf[64]; memset(buf, 0, 64 * sizeof(wchar_t)); swprintf(buf, 63, ("%." + CL_StringHelp::int_to_ucs2(num_decimals) + "f").c_str(), value); return CL_String16(buf); #endif } float CL_StringHelp::text_to_float(const CL_StringRef &value) { return local8_to_float(value); } float CL_StringHelp::local8_to_float(const CL_StringRef8 &value) { float result = 0.0; sscanf(value.c_str(), "%f", &result); return result; } float CL_StringHelp::ucs2_to_float(const CL_StringRef16 &value) { float result = 0.0; swscanf(value.c_str(), L"%f", &result); return result; } CL_String CL_StringHelp::double_to_text(double value, int num_decimals) { return double_to_local8(value, num_decimals); } CL_String8 CL_StringHelp::double_to_local8(double value, int num_decimals) { char buf[64]; memset(buf, 0, 64); #ifdef WIN32 _snprintf(buf, 63, ("%." + CL_StringHelp::int_to_local8(num_decimals) + "f").c_str(), value); #else snprintf(buf, 63, ("%." + CL_StringHelp::int_to_local8(num_decimals) + "f").c_str(), value); #endif return CL_String8(buf); } CL_String16 CL_StringHelp::double_to_ucs2(double value, int num_decimals) { #ifdef WIN32 WCHAR buf[64]; memset(buf, 0, 64 * sizeof(WCHAR)); swprintf(buf, ("%." + CL_StringHelp::int_to_ucs2(num_decimals) + "f").c_str(), value); return CL_String16(buf); #else wchar_t buf[64]; memset(buf, 0, 64 * sizeof(wchar_t)); swprintf(buf, 63, ("%." + CL_StringHelp::int_to_ucs2(num_decimals) + "f").c_str(), value); return CL_String16(buf); #endif } double CL_StringHelp::text_to_double(const CL_StringRef &value) { return local8_to_double(value); } double CL_StringHelp::local8_to_double(const CL_StringRef8 &value) { double result = 0.0; sscanf(value.c_str(), "%lf", &result); return result; } double CL_StringHelp::ucs2_to_double(const CL_StringRef16 &value) { double result = 0.0; swscanf(value.c_str(), L"%lf", &result); return result; } CL_String CL_StringHelp::int_to_text(int value) { return int_to_local8(value); } CL_String8 CL_StringHelp::int_to_local8(int value) { char buf[32]; memset(buf, 0, 32); #ifdef WIN32 _snprintf(buf, 31, "%d", value); #else snprintf(buf, 31, "%d", value); #endif return CL_String8(buf); } CL_String16 CL_StringHelp::int_to_ucs2(int value) { #ifdef WIN32 WCHAR buf[32]; memset(buf, 0, 32 * sizeof(WCHAR)); swprintf(buf, L"%d", value); return CL_String16(buf); #else wchar_t buf[32]; memset(buf, 0, 32 * sizeof(wchar_t)); swprintf(buf, 31, L"%d", value); return CL_String16(buf); #endif } int CL_StringHelp::text_to_int(const CL_StringRef &value, int base) { return local8_to_int(value, base); } int CL_StringHelp::local8_to_int(const CL_StringRef8 &value, int base) { if (base == 10) { return atoi(value.c_str()); } else if (base == 16) { int result = 0; CL_String8::size_type i, length; length = value.length(); for (i = 0; i < length; i++) { if (value[i] >= '0' && value[i] <= '9') { result = (result << 4) + (value[i] - '0'); } else if (value[i] >= 'a' && value[i] <= 'f') { result = (result << 4) + 10 + (value[i] - 'a'); } else if (value[i] >= 'A' && value[i] <= 'F') { result = (result << 4) + 10 + (value[i] - 'A'); } else { break; } } return result; } else { throw CL_Exception("Unsupported base passed for local8_to_int"); } } int CL_StringHelp::ucs2_to_int(const CL_StringRef16 &value, int base) { if (base == 10) { #ifdef WIN32 return _wtoi(value.c_str()); #else throw CL_Exception("ucs2_to_int not implemented on unix yet"); return 0; #endif } else if (base == 16) { int result = 0; CL_String16::size_type i, length; length = value.length(); for (i = 0; i < length; i++) { if (value[i] >= L'0' && value[i] <= L'9') { result = (result << 4) + (value[i] - L'0'); } else if (value[i] >= L'a' && value[i] <= L'f') { result = (result << 4) + 10 + (value[i] - L'a'); } else if (value[i] >= L'A' && value[i] <= L'F') { result = (result << 4) + 10 + (value[i] - L'A'); } else { break; } } return result; } else { throw CL_Exception("Unsupported base passed for ucs2_to_int"); } } CL_String CL_StringHelp::uint_to_text(unsigned int value) { return uint_to_local8(value); } CL_String8 CL_StringHelp::uint_to_local8(unsigned int value) { char buf[32]; memset(buf, 0, 32); #ifdef WIN32 _snprintf(buf, 31, "%u", value); #else snprintf(buf, 31, "%u", value); #endif return CL_String8(buf); } CL_String16 CL_StringHelp::uint_to_ucs2(unsigned int value) { #ifdef WIN32 WCHAR buf[32]; memset(buf, 0, 32 * sizeof(WCHAR)); swprintf(buf, L"%u", value); return CL_String16(buf); #else wchar_t buf[32]; memset(buf, 0, 32 * sizeof(wchar_t)); swprintf(buf, 31, L"%u", value); return CL_String16(buf); #endif } unsigned int CL_StringHelp::text_to_uint(const CL_StringRef &value, int base) { return local8_to_uint(value, base); } unsigned int CL_StringHelp::local8_to_uint(const CL_StringRef8 &value, int base) { if (base == 10) { return (unsigned int) atoi(value.c_str()); } else if (base == 16) { int result = 0; CL_String8::size_type i, length; length = value.length(); for (i = 0; i < length; i++) { if (value[i] >= '0' && value[i] <= '9') { result = (result << 4) + (value[i] - '0'); } else if (value[i] >= 'a' && value[i] <= 'f') { result = (result << 4) + 10 + (value[i] - 'a'); } else if (value[i] >= 'A' && value[i] <= 'F') { result = (result << 4) + 10 + (value[i] - 'A'); } else { break; } } return result; } else { throw CL_Exception("Unsupported base passed for local8_to_int"); } } unsigned int CL_StringHelp::ucs2_to_uint(const CL_StringRef16 &value, int base) { if (base == 10) { #ifdef WIN32 return (unsigned int) _wtoi(value.c_str()); #else throw CL_Exception("ucs2_to_uint not implemented on unix yet"); return 0; #endif } else if (base == 16) { unsigned int result = 0; CL_String16::size_type i, length; length = value.length(); for (i = 0; i < length; i++) { if (value[i] >= L'0' && value[i] <= L'9') { result = (result << 4) + (value[i] - L'0'); } else if (value[i] >= L'a' && value[i] <= L'f') { result = (result << 4) + 10 + (value[i] - L'a'); } else if (value[i] >= L'A' && value[i] <= L'F') { result = (result << 4) + 10 + (value[i] - L'A'); } else { break; } } return result; } else { throw CL_Exception("Unsupported base passed for ucs2_to_int"); } } CL_String CL_StringHelp::bool_to_text(bool value) { return bool_to_local8(value); } CL_String8 CL_StringHelp::bool_to_local8(bool value) { return value ? "true" : "false"; } CL_String16 CL_StringHelp::bool_to_ucs2(bool value) { return value ? L"true" : L"false"; } bool CL_StringHelp::text_to_bool(const CL_StringRef &value) { return local8_to_bool(value); } bool CL_StringHelp::local8_to_bool(const CL_StringRef8 &value) { if (CL_StringHelp::compare(value, "true", true) == 0) return true; else if (CL_StringHelp::compare(value, "yes", true) == 0) return true; else if (value == "1") return true; else return false; } bool CL_StringHelp::ucs2_to_bool(const CL_StringRef16 &value) { if (CL_StringHelp::compare(value, L"true", true) == 0) return true; else if (CL_StringHelp::compare(value, L"yes", true) == 0) return true; else if (value == L"1") return true; else return false; } CL_String8 CL_StringHelp::text_to_local8(const CL_StringRef &text) { return text; } CL_String8 CL_StringHelp::text_to_utf8(const CL_StringRef &text) { return text; } CL_String8 CL_StringHelp::ucs2_to_latin1(const CL_StringRef16 &ucs2) { CL_String8::size_type i, length = ucs2.length(); CL_String8 latin1(length, ' '); for (i=0; i<length; i++) latin1[i] = (char) ucs2[i]; return latin1; } CL_String8 CL_StringHelp::ucs2_to_latin9(const CL_StringRef16 &ucs2) { CL_String8::size_type i, length = ucs2.length(); CL_String8 latin1(length, ' '); for (i=0; i<length; i++) latin1[i] = (ucs2[i] != 0x20ac) ? ucs2[i] : 0xa4; return latin1; } CL_String8 CL_StringHelp::ucs2_to_local8(const CL_StringRef16 &ucs2) { return ucs2_to_latin9(ucs2); } CL_String8 CL_StringHelp::ucs2_to_utf8(const CL_StringRef16 &ucs2) { // Calculate length: CL_String16::size_type length_ucs2 = ucs2.length(); CL_String8::size_type length_utf8 = 0; CL_String16::size_type pos; for (pos = 0; pos < length_ucs2; pos++) { if (ucs2[pos] < 0x0080) length_utf8++; else if (ucs2[pos] < 0x0800) length_utf8 += 2; else length_utf8 += 3; } // Perform conversion: CL_String8 utf8(length_utf8, ' '); CL_String8::size_type pos_utf8 = 0; for (pos = 0; pos < length_ucs2; pos++) { if (ucs2[pos] < 0x0080) { utf8[pos_utf8++] = (char) ucs2[pos]; } else if (ucs2[pos] < 0x0800) { utf8[pos_utf8++] = 0xc0 + (ucs2[pos] >> 6); utf8[pos_utf8++] = 0x80 + (ucs2[pos] & 0x3f); } else { utf8[pos_utf8++] = 0xe0 + (ucs2[pos] >> 12); utf8[pos_utf8++] = 0x80 + ((ucs2[pos] >> 6) & 0x3f); utf8[pos_utf8++] = 0x80 + (ucs2[pos] & 0x3f); } } return utf8; } CL_String16 CL_StringHelp::latin1_to_ucs2(const CL_StringRef8 &latin1) { CL_String16::size_type i, length = latin1.length(); CL_String16 ucs2(length, ' '); for (i=0; i<length; i++) ucs2[i] = latin1[i]; return ucs2; } CL_String16 CL_StringHelp::latin9_to_ucs2(const CL_StringRef8 &latin9) { CL_String16::size_type i, length = latin9.length(); CL_String16 ucs2(length, ' '); for (i=0; i<length; i++) ucs2[i] = ((unsigned char) latin9[i] != 0xa4) ? latin9[i] : 0x20ac; return ucs2; } CL_String CL_StringHelp::local8_to_text(const CL_StringRef8 &local8) { return local8; } CL_String CL_StringHelp::ucs2_to_text(const CL_StringRef16 &ucs2) { return ucs2_to_utf8(ucs2); } CL_String16 CL_StringHelp::local8_to_ucs2(const CL_StringRef8 &local8) { return latin9_to_ucs2(local8); } CL_String16 CL_StringHelp::utf8_to_ucs2(const CL_StringRef8 &utf8) { // Calculate length: CL_String16::size_type length_ucs2 = 0; CL_String8::size_type length_utf8 = utf8.length(); CL_String8::size_type pos = 0; while (pos < length_utf8) { unsigned char c = utf8[pos++]; int trailing_bytes = trailing_bytes_for_utf8[c]; length_ucs2++; pos += trailing_bytes; } if (pos != length_utf8) { // error in utf8 string length_ucs2--; } if (pos <= 0) return CL_String16(); // Perform conversion: CL_String16 ucs2(length_ucs2, L'?'); pos = 0; CL_String16::size_type ucs2_pos = 0; while (pos < length_utf8 && ucs2_pos < length_ucs2) { unsigned char c = utf8[pos++]; int trailing_bytes = trailing_bytes_for_utf8[c]; unsigned int ucs4 = (c & bitmask_leadbyte_for_utf8[trailing_bytes]); for (int i=0; i<trailing_bytes; i++) { c = (unsigned char) utf8[pos+i]; if (c < 0xc0) { ucs4 = (ucs4 << 6) + (c & 0x3f); } else { // error in utf8 string ucs4 = L'?'; break; } } if (ucs4 > 0 && ucs4 <= 0xffff) ucs2[ucs2_pos] = ucs4; else ucs2[ucs2_pos] = L'?'; ucs2_pos++; pos += trailing_bytes; } return ucs2; } CL_String CL_StringHelp::utf8_to_text(const CL_StringRef8 &utf8) { return utf8; } CL_String8 CL_StringHelp::text_to_cp437(const CL_StringRef &text) { return ucs2_to_cp437(local8_to_ucs2(text)); } CL_String CL_StringHelp::cp437_to_text(const CL_StringRef8 &cp437) { return ucs2_to_utf8(cp437_to_ucs2(cp437)); } CL_String16 CL_StringHelp::cp437_to_ucs2(const CL_StringRef8 &cp437) { static CL_String16::char_type cp437_charset[] = { 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x007F, 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 }; CL_String16 str16; str16.resize(cp437.length()); const unsigned char *input = (const unsigned char *) cp437.data(); CL_String16::char_type *output = str16.data(); CL_String16::size_type index, size; size = cp437.length(); for (index = 0; index < size; index++) output[index] = cp437_charset[input[index]]; return str16; } CL_String8 CL_StringHelp::ucs2_to_cp437(const CL_StringRef16 &text) { CL_String8 str8; str8.resize(text.length()); unsigned char *output = (unsigned char *) str8.data(); const CL_String16::char_type *input = text.data(); CL_String16::size_type index, size; size = text.length(); for (index = 0; index < size; index++) { if (input[index] >= 0x00 && input[index] <= 0x7f) { str8[index] = text[index]; continue; } if (input[index] == 0x00C7) { output[index] = 0x80; continue; } if (input[index] == 0x00FC) { output[index] = 0x81; continue; } if (input[index] == 0x00E9) { output[index] = 0x82; continue; } if (input[index] == 0x00E2) { output[index] = 0x83; continue; } if (input[index] == 0x00E4) { output[index] = 0x84; continue; } if (input[index] == 0x00E0) { output[index] = 0x85; continue; } if (input[index] == 0x00E5) { output[index] = 0x86; continue; } if (input[index] == 0x00E7) { output[index] = 0x87; continue; } if (input[index] == 0x00EA) { output[index] = 0x88; continue; } if (input[index] == 0x00EB) { output[index] = 0x89; continue; } if (input[index] == 0x00E8) { output[index] = 0x8A; continue; } if (input[index] == 0x00EF) { output[index] = 0x8B; continue; } if (input[index] == 0x00EE) { output[index] = 0x8C; continue; } if (input[index] == 0x00EC) { output[index] = 0x8D; continue; } if (input[index] == 0x00C4) { output[index] = 0x8E; continue; } if (input[index] == 0x00C5) { output[index] = 0x8F; continue; } if (input[index] == 0x00C9) { output[index] = 0x90; continue; } if (input[index] == 0x00E6) { output[index] = 0x91; continue; } if (input[index] == 0x00C6) { output[index] = 0x92; continue; } if (input[index] == 0x00F4) { output[index] = 0x93; continue; } if (input[index] == 0x00F6) { output[index] = 0x94; continue; } if (input[index] == 0x00F2) { output[index] = 0x95; continue; } if (input[index] == 0x00FB) { output[index] = 0x96; continue; } if (input[index] == 0x00F9) { output[index] = 0x97; continue; } if (input[index] == 0x00FF) { output[index] = 0x98; continue; } if (input[index] == 0x00D6) { output[index] = 0x99; continue; } if (input[index] == 0x00DC) { output[index] = 0x9A; continue; } if (input[index] == 0x00A2) { output[index] = 0x9B; continue; } if (input[index] == 0x00A3) { output[index] = 0x9C; continue; } if (input[index] == 0x00A5) { output[index] = 0x9D; continue; } if (input[index] == 0x20A7) { output[index] = 0x9E; continue; } if (input[index] == 0x0192) { output[index] = 0x9F; continue; } if (input[index] == 0x00E1) { output[index] = 0xA0; continue; } if (input[index] == 0x00ED) { output[index] = 0xA1; continue; } if (input[index] == 0x00F3) { output[index] = 0xA2; continue; } if (input[index] == 0x00FA) { output[index] = 0xA3; continue; } if (input[index] == 0x00F1) { output[index] = 0xA4; continue; } if (input[index] == 0x00D1) { output[index] = 0xA5; continue; } if (input[index] == 0x00AA) { output[index] = 0xA6; continue; } if (input[index] == 0x00BA) { output[index] = 0xA7; continue; } if (input[index] == 0x00BF) { output[index] = 0xA8; continue; } if (input[index] == 0x2310) { output[index] = 0xA9; continue; } if (input[index] == 0x00AC) { output[index] = 0xAA; continue; } if (input[index] == 0x00BD) { output[index] = 0xAB; continue; } if (input[index] == 0x00BC) { output[index] = 0xAC; continue; } if (input[index] == 0x00A1) { output[index] = 0xAD; continue; } if (input[index] == 0x00AB) { output[index] = 0xAE; continue; } if (input[index] == 0x00BB) { output[index] = 0xAF; continue; } if (input[index] == 0x2591) { output[index] = 0xB0; continue; } if (input[index] == 0x2592) { output[index] = 0xB1; continue; } if (input[index] == 0x2593) { output[index] = 0xB2; continue; } if (input[index] == 0x2502) { output[index] = 0xB3; continue; } if (input[index] == 0x2524) { output[index] = 0xB4; continue; } if (input[index] == 0x2561) { output[index] = 0xB5; continue; } if (input[index] == 0x2562) { output[index] = 0xB6; continue; } if (input[index] == 0x2556) { output[index] = 0xB7; continue; } if (input[index] == 0x2555) { output[index] = 0xB8; continue; } if (input[index] == 0x2563) { output[index] = 0xB9; continue; } if (input[index] == 0x2551) { output[index] = 0xBA; continue; } if (input[index] == 0x2557) { output[index] = 0xBB; continue; } if (input[index] == 0x255D) { output[index] = 0xBC; continue; } if (input[index] == 0x255C) { output[index] = 0xBD; continue; } if (input[index] == 0x255B) { output[index] = 0xBE; continue; } if (input[index] == 0x2510) { output[index] = 0xBF; continue; } if (input[index] == 0x2514) { output[index] = 0xC0; continue; } if (input[index] == 0x2534) { output[index] = 0xC1; continue; } if (input[index] == 0x252C) { output[index] = 0xC2; continue; } if (input[index] == 0x251C) { output[index] = 0xC3; continue; } if (input[index] == 0x2500) { output[index] = 0xC4; continue; } if (input[index] == 0x253C) { output[index] = 0xC5; continue; } if (input[index] == 0x255E) { output[index] = 0xC6; continue; } if (input[index] == 0x255F) { output[index] = 0xC7; continue; } if (input[index] == 0x255A) { output[index] = 0xC8; continue; } if (input[index] == 0x2554) { output[index] = 0xC9; continue; } if (input[index] == 0x2569) { output[index] = 0xCA; continue; } if (input[index] == 0x2566) { output[index] = 0xCB; continue; } if (input[index] == 0x2560) { output[index] = 0xCC; continue; } if (input[index] == 0x2550) { output[index] = 0xCD; continue; } if (input[index] == 0x256C) { output[index] = 0xCE; continue; } if (input[index] == 0x2567) { output[index] = 0xCF; continue; } if (input[index] == 0x2568) { output[index] = 0xD0; continue; } if (input[index] == 0x2564) { output[index] = 0xD1; continue; } if (input[index] == 0x2565) { output[index] = 0xD2; continue; } if (input[index] == 0x2559) { output[index] = 0xD3; continue; } if (input[index] == 0x2558) { output[index] = 0xD4; continue; } if (input[index] == 0x2552) { output[index] = 0xD5; continue; } if (input[index] == 0x2553) { output[index] = 0xD6; continue; } if (input[index] == 0x256B) { output[index] = 0xD7; continue; } if (input[index] == 0x256A) { output[index] = 0xD8; continue; } if (input[index] == 0x2518) { output[index] = 0xD9; continue; } if (input[index] == 0x250C) { output[index] = 0xDA; continue; } if (input[index] == 0x2588) { output[index] = 0xDB; continue; } if (input[index] == 0x2584) { output[index] = 0xDC; continue; } if (input[index] == 0x258C) { output[index] = 0xDD; continue; } if (input[index] == 0x2590) { output[index] = 0xDE; continue; } if (input[index] == 0x2580) { output[index] = 0xDF; continue; } if (input[index] == 0x03B1) { output[index] = 0xE0; continue; } if (input[index] == 0x00DF) { output[index] = 0xE1; continue; } if (input[index] == 0x0393) { output[index] = 0xE2; continue; } if (input[index] == 0x03C0) { output[index] = 0xE3; continue; } if (input[index] == 0x03A3) { output[index] = 0xE4; continue; } if (input[index] == 0x03C3) { output[index] = 0xE5; continue; } if (input[index] == 0x00B5) { output[index] = 0xE6; continue; } if (input[index] == 0x03C4) { output[index] = 0xE7; continue; } if (input[index] == 0x03A6) { output[index] = 0xE8; continue; } if (input[index] == 0x0398) { output[index] = 0xE9; continue; } if (input[index] == 0x03A9) { output[index] = 0xEA; continue; } if (input[index] == 0x03B4) { output[index] = 0xEB; continue; } if (input[index] == 0x221E) { output[index] = 0xEC; continue; } if (input[index] == 0x03C6) { output[index] = 0xED; continue; } if (input[index] == 0x03B5) { output[index] = 0xEE; continue; } if (input[index] == 0x2229) { output[index] = 0xEF; continue; } if (input[index] == 0x2261) { output[index] = 0xF0; continue; } if (input[index] == 0x00B1) { output[index] = 0xF1; continue; } if (input[index] == 0x2265) { output[index] = 0xF2; continue; } if (input[index] == 0x2264) { output[index] = 0xF3; continue; } if (input[index] == 0x2320) { output[index] = 0xF4; continue; } if (input[index] == 0x2321) { output[index] = 0xF5; continue; } if (input[index] == 0x00F7) { output[index] = 0xF6; continue; } if (input[index] == 0x2248) { output[index] = 0xF7; continue; } if (input[index] == 0x00B0) { output[index] = 0xF8; continue; } if (input[index] == 0x2219) { output[index] = 0xF9; continue; } if (input[index] == 0x00B7) { output[index] = 0xFA; continue; } if (input[index] == 0x221A) { output[index] = 0xFB; continue; } if (input[index] == 0x207F) { output[index] = 0xFC; continue; } if (input[index] == 0x00B2) { output[index] = 0xFD; continue; } if (input[index] == 0x25A0) { output[index] = 0xFE; continue; } if (input[index] == 0x00A0) { output[index] = 0xFF; continue; } output[index] = '_'; } return str8; } CL_StringHelp::BOMType CL_StringHelp::detect_bom(const void *data, CL_String::size_type length) { const unsigned char utf32_be[] = { 0x00, 0x00, 0xfe, 0xff }; const unsigned char utf32_le[] = { 0xff, 0xfe, 0x00, 0x00 }; const unsigned char utf16_be[] = { 0xfe, 0xff }; const unsigned char utf16_le[] = { 0xff, 0xfe }; const unsigned char utf8[] = { 0xef, 0xbb, 0xbf }; if (length >= 3 && memcmp(data, utf8, 3) == 0) return bom_utf8; else if (length >= 2 && memcmp(data, utf16_le, 2) == 0) return bom_utf16_le; else if (length >= 2 && memcmp(data, utf16_be, 2) == 0) return bom_utf16_be; else if (length >= 4 && memcmp(data, utf32_le, 4) == 0) return bom_utf32_le; else if (length >= 4 && memcmp(data, utf32_be, 4) == 0) return bom_utf32_be; else return bom_none; } ///////////////////////////////////////////////////////////////////////////// // CL_StringHelp Implementation: const char CL_StringHelp::trailing_bytes_for_utf8[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; const unsigned char CL_StringHelp::bitmask_leadbyte_for_utf8[6] = { 0x7f, 0x1f, 0x0f, 0x07, 0x03, 0x01 }; #ifndef WIN32 #ifndef HAVE_WCSCASECMP int cl_wcscasecmp(const wchar_t *s1, const wchar_t *s2) { const wchar_t *us1 = (const wchar_t *)s1; const wchar_t *us2 = (const wchar_t *)s2; while (towlower(*us1) == towlower(*us2++)) if (*us1++ == '\0') return (0); return (towlower(*us1) - towlower(*--us2)); } #endif #endif
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 1078 ] ] ]
d4bdf33f8437dd82b6f2c017960f717d77d39642
748b6e3b51df5d1cd02735469ea66d5bb29c68e3
/src/cvp_dynamic.hxx
65dd96a719e455acbc2db6f0f2f59de41ca0979e
[ "ISC" ]
permissive
vedantk/cvp
d1dfdfb6aad0143f045fdba2559ca4e567bede4f
222b45cb16e095f4d1dc3e4f45eaf9f606024ae9
refs/heads/master
2021-01-20T12:00:23.927548
2010-11-01T01:13:56
2010-11-01T01:13:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,065
hxx
/* * specialized region-growing for noise reduction * * Copyright (c) 2009 Vedant Kumar <[email protected]> */ #ifndef CVP_DYNAMIC_HXX #define CVP_DYNAMIC_HXX #include "image.hpp" #include <map> const ushort edge = 175; static bool locate_seed(img* mra_volume, vector<ushort>& rar, vector<ushort>& car, vector<ushort>& zar) { for (ushort q2=edge; q2 < 512-edge; ++q2) { for (ushort q3=edge; q3 < 512-edge; ++q3) { if (mra_volume[num_imgs-1].pix[q2][q3] == white) { rar.clear(); car.clear(); zar.clear(); rar.push_back(q2); car.push_back(q3); zar.push_back(num_imgs-1); return true; } } } return false; } void cvp_region_growing(img* mra_volume) { dp("cvp region-growing..."); int i, j, z, k3, k2, k1; uint arc; uint visiting_pts; vector<ushort> rar, car, zar; map<uint, uint> regions; // flag : fcount uint flag = 0; while (locate_seed(mra_volume, rar, car, zar)) { arc = 1; visiting_pts = 0; flag++; while (arc != visiting_pts) { i = rar[visiting_pts]; j = car[visiting_pts]; z = zar[visiting_pts]; for (k3 = z-1; k3 <= z+1; k3++) { if (k3 < 0 || k3 >= num_imgs) continue; for (k1 = i-1; k1 <= i+1; k1++) { if (k1 < 0 || k1 > 511) continue; for (k2 = j-1; k2 <= j+1; k2++) { if (k2 < 0 || k2 > 511) continue; if (mra_volume[k3].pix[k1][k2] == white) { rar.push_back(k1); car.push_back(k2); zar.push_back(k3); arc++; mra_volume[k3].pix[k1][k2] = flag; } } } } visiting_pts += 1; } regions[flag] = arc; } dp("stripping voxels..."); uint wcount = regions[ white ]; for (ushort q=0; q < num_imgs; ++q) { for (ushort q2=0; q2 < 512; ++q2) { for (ushort q3=0; q3 < 512; ++q3) { if (regions[ mra_volume[q].pix[q2][q3] ] < 100) { mra_volume[q].pix[q2][q3] = 0; } else { mra_volume[q].pix[q2][q3] = white; } } } } } #endif
[ [ [ 1, 97 ] ] ]
d57a9f9d0a02d4fa75494fe2e8e2a1158abe89d9
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/dingus/gfx/RenderableOrderedBillboards.cpp
872832870c98e4d90130e05d46f5791a04af60d2
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,997
cpp
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #include "stdafx.h" #include "RenderableOrderedBillboards.h" #include "Vertices.h" #include "../kernel/D3DDevice.h" using namespace dingus; CRenderableOrderedBillboards::CRenderableOrderedBillboards( CD3DIndexBuffer& ib, CEffectParams::TParamName texParamName ) : mIB( &ib ), mVBSource( sizeof(TVertex) ), mTexParamName( texParamName ) { // add self as a listener addListener( *this ); mChunk = 0; } CRenderableOrderedBillboards::~CRenderableOrderedBillboards() { removeListener( *this ); } // ------------------------------------------------------------------ // Rendering void CRenderableOrderedBillboards::beforeRender( CRenderable& r, CRenderContext& ctx ) { assert( !mChunk ); if( mBills.empty() ) return; // render into VB mChunk = mVBSource.lock( static_cast<unsigned int>(mBills.size()) * 4 ); // 4 verts per billboard TVertex* vb = reinterpret_cast<TVertex*>( mChunk->getData() ); TBillVector::const_iterator bit, bitEnd = mBills.end(); for( bit = mBills.begin(); bit != bitEnd; ++bit ) { const SOBillboard& bill = *bit; vb->p.x = bill.x1; vb->p.y = bill.y1; vb->p.z = 0.1f; // TBD vb->diffuse = bill.color; vb->tu = bill.tu1; vb->tv = bill.tv1; ++vb; vb->p.x = bill.x2; vb->p.y = bill.y1; vb->p.z = 0.1f; // TBD vb->diffuse = bill.color; vb->tu = bill.tu2; vb->tv = bill.tv1; ++vb; vb->p.x = bill.x2; vb->p.y = bill.y2; vb->p.z = 0.1f; // TBD vb->diffuse = bill.color; vb->tu = bill.tu2; vb->tv = bill.tv2; ++vb; vb->p.x = bill.x1; vb->p.y = bill.y2; vb->p.z = 0.1f; // TBD vb->diffuse = bill.color; vb->tu = bill.tu1; vb->tv = bill.tv2; ++vb; } mChunk->unlock( 0 ); } void CRenderableOrderedBillboards::afterRender( CRenderable& r, CRenderContext& ctx ) { mChunk = 0; } void CRenderableOrderedBillboards::render( const CRenderContext& ctx ) { CD3DDevice& device = CD3DDevice::getInstance(); IDirect3DDevice9& dx = device.getDevice(); CRenderStats& stats = device.getStats(); if( mBills.empty() ) return; assert( mChunk ); // set IB/VB assert( mIB ); device.setIndexBuffer( mIB ); device.setVertexBuffer( 0, &mChunk->getBuffer(), 0, static_cast<UINT>(mChunk->getStride()) ); device.setDeclarationFVF( FVF_XYZ_DIFFUSE_TEX1 ); // render pieces of billboards CD3DTexture* texture = mBills[0].texture; int texStart = 0; unsigned int n = (unsigned int)mBills.size(); for( unsigned int i = 1; i < n; ++i ) { // from second one const SOBillboard& b = mBills[i]; if( b.texture == texture ) continue; // set texture on effect assert( texture ); // TBD: better supply handle, not name - would be faster // TBD: refactor getParams().getEffect()->getObject()->SetTexture( mTexParamName, texture->getObject() ); getParams().getEffect()->commitParams(); // draw portion dx.DrawIndexedPrimitive( D3DPT_TRIANGLELIST, static_cast<UINT>(mChunk->getOffset()) + texStart*4, 0, (i-texStart)*4, 0, (i-texStart)*2 ); // new texture texture = b.texture; texStart = i; // stats stats.incDrawCalls(); } // last portion // set texture on effect assert( texture ); // TBD: better supply handle, not name - would be faster // TBD: refactor getParams().getEffect()->getObject()->SetTexture( mTexParamName, texture->getObject() ); getParams().getEffect()->commitParams(); // draw portion dx.DrawIndexedPrimitive( D3DPT_TRIANGLELIST, static_cast<INT>(mChunk->getOffset()) + texStart*4, 0, (n-texStart)*4, 0, (n-texStart)*2 ); // stats stats.incDrawCalls(); // stats stats.incVerticesRendered( static_cast<int>(mChunk->getSize()) ); stats.incPrimsRendered( static_cast<int>(mChunk->getSize()/2) ); }
[ [ [ 1, 131 ] ] ]
696dffefff8a7d3b241f99a53ea351e4c2ea36f1
cb1c6c586d769f919ed982e9364d92cf0aa956fe
/examples/TRTInstancing/TRTInstancing.cpp
1d4060a03b0b80eee8b5bf76ec7c9056c3862e24
[]
no_license
jrk/tinyrt
86fd6e274d56346652edbf50f0dfccd2700940a6
760589e368a981f321e5f483f6d7e152d2cf0ea6
refs/heads/master
2016-09-01T18:24:22.129615
2010-01-07T15:19:44
2010-01-07T15:19:44
462,454
3
0
null
null
null
null
UTF-8
C++
false
false
9,285
cpp
//===================================================================================================================== // // TRTInstancing.h // // Example illustrating instanced mesh rendering using TinyRT. In this example we demonstrate instanced meshes, // with a seperate BVH tree built for each unique mesh. The instances are nested inside a uniform grid. // // These data structures were chosen to illustrate the ease with which various raytracing algorithms may be // composed together using TinyRT. // // // Part of the TinyRT Raytracing Library. // Author: Joshua Barczak // // Copyright 2009 Joshua Barczak. All rights reserved. // See Doc/LICENSE.txt for terms and conditions. // //===================================================================================================================== #include "PPMImage.h" #include "PlyLoad.h" #include "TinyRT.h" using namespace TinyRT; typedef TinyRT::BasicMesh<Vec3f,unsigned int> Mesh; // Some mesh data struct MeshData { std::vector< TinyRT::Vec3f > vertices; std::vector< unsigned int > indices; AxisAlignedBox meshAABB; TinyRT::AABBTree<Mesh> Tree; // Tree built over the mesh }; class MeshInstance; // Information about a triangle/ray intersection struct InstanceHitInfo { const MeshInstance* pMeshInstance; TinyRT::TriangleRayHit triangleHit; }; // An instance of a mesh class MeshInstance { public: MeshInstance( MeshData& rData, const Vec3f& rPosition ) : m_Mesh( &rData.vertices[0], &rData.indices[0], rData.vertices.size(), rData.indices.size()/3 ), m_aabb( rData.meshAABB.Min() + rPosition, rData.meshAABB.Max() + rPosition ), m_vPosition( rPosition ), m_pMeshData( &rData ) { } void RayIntersect( TinyRT::Ray& rRay, InstanceHitInfo& rHitInfo ) const { // transform the ray TinyRT::Ray transformedRay( rRay ); transformedRay.SetOrigin( rRay.Origin() - m_vPosition ); TinyRT::TriangleRayHit hit; hit.nTriIdx = m_Mesh.GetObjectCount(); // cast ray at mesh instance static TinyRT::ScratchMemory ScratchMemory; TinyRT::RaycastBVH( &m_pMeshData->Tree, &m_Mesh, transformedRay, hit, m_pMeshData->Tree.GetRoot(), ScratchMemory ); if( hit.nTriIdx != m_Mesh.GetObjectCount() ) { // we hit something in this instance, update hit info record rHitInfo.pMeshInstance = this; rHitInfo.triangleHit = hit; // update maximum distance in parent ray rRay.SetMaxDistance( transformedRay.MaxDistance() ); } } inline const AxisAlignedBox& GetAABB() const { return m_aabb; }; inline const Mesh* GetMesh() const { return &m_Mesh; }; private: MeshData* m_pMeshData; Mesh m_Mesh; // The mesh AxisAlignedBox m_aabb; // AABB of the mesh instance (in world space) Vec3f m_vPosition; // for simplicity, this sample assumes only translation, but a full matrix is certainly doable }; // A class encapsulating the set of instance mesh objects. This class implements the TinyRT::ObjectSet_C concept. class InstancedMeshObjectSet { public: typedef TinyRT::uint32 obj_id; InstancedMeshObjectSet( MeshInstance** pInstances, uint nInstances ) : m_pInstances(pInstances), m_nInstances(nInstances) { m_grid.Build( this, 50.0f ); } void RayIntersect( TinyRT::Ray& rRay, InstanceHitInfo& rHitInfo, obj_id nObject ) const { m_pInstances[nObject]->RayIntersect( rRay, rHitInfo ); } void RayIntersect( TinyRT::Ray& rRay, InstanceHitInfo& rHitInfo, obj_id nObject, obj_id nCount ) const { for( obj_id i=0; i<nCount; i++ ) RayIntersect( rRay, rHitInfo, nObject+i ); } inline void RemapObjects( obj_id* pObjectRemap ) { TinyRT::RemapArray( m_pInstances, m_nInstances, pObjectRemap ); } void GetAABB( TinyRT::AxisAlignedBox& rBox ) { if( m_nInstances > 0 ) { rBox = m_pInstances[0]->GetAABB(); for( uint i=1; i<m_nInstances; i++ ) { rBox.Merge( m_pInstances[i]->GetAABB() ); } } } inline void GetObjectAABB( obj_id nObject, TinyRT::AxisAlignedBox& rBoxOut ) { rBoxOut = m_pInstances[nObject]->GetAABB(); } inline obj_id GetObjectCount() const { return m_nInstances; } void CastRay( TinyRT::Ray& rRay, InstanceHitInfo& rRayHit ) const { TinyRT::RaycastUniformGrid< TinyRT::DirectMapMailbox<obj_id,8> >( &m_grid, this, rRay, rRayHit ); } private: MeshInstance** m_pInstances; uint m_nInstances; TinyRT::UniformGrid< InstancedMeshObjectSet > m_grid; }; void Render( const TinyRT::Vec3f& rPosition, const TinyRT::Vec3f& rLookAt, PPMImage& rImage, const InstancedMeshObjectSet& rObjects ) { PPMImage image; TinyRT::PerspectiveCamera cam( rPosition, rLookAt-rPosition, Vec3f(0,1,0), 60.0f, 1 ); int nHeight = rImage.GetHeight(); int nWidth = rImage.GetWidth(); for( int y = 0; y<nHeight; y++ ) { printf("%u\r", y ); for( int x = 0; x < nWidth; x++ ) { float s = (float) x / (float) nWidth; float t = (float) y / (float) nHeight; const TinyRT::Vec3f& vOrigin = cam.GetPosition(); TinyRT::Vec3f vDir = cam.GetRayDirectionNDC( TinyRT::Vec2f(s,t) ); TinyRT::Ray ray( vOrigin, vDir ); InstanceHitInfo hitInfo; hitInfo.pMeshInstance = 0; hitInfo.triangleHit.nTriIdx = 0xffffffff; hitInfo.triangleHit.vUVCoords = Vec2f(0,0); rObjects.CastRay( ray, hitInfo ); if( !hitInfo.pMeshInstance ) { rImage.SetPixel( x,y, 0,0,0 ); } else { // compute face normal and do N.V shading const Mesh* pMesh = hitInfo.pMeshInstance->GetMesh(); const TinyRT::Vec3f& v0 = pMesh->VertexPosition( pMesh->Index( hitInfo.triangleHit.nTriIdx, 0 ) ); const TinyRT::Vec3f& v1 = pMesh->VertexPosition( pMesh->Index( hitInfo.triangleHit.nTriIdx, 1 ) ); const TinyRT::Vec3f& v2 = pMesh->VertexPosition( pMesh->Index( hitInfo.triangleHit.nTriIdx, 2 ) ); const TinyRT::Vec3f& vNormal = TinyRT::Normalize3( TinyRT::Cross3( v2-v0, v1-v0 ) ); TinyRT::Vec3f vHit = vOrigin + vDir*ray.MaxDistance(); TinyRT::Vec3f vV = TinyRT::Normalize3( vHit - vOrigin ); float f = fabs( TinyRT::Dot3( vV, vNormal ) ); rImage.SetPixel( x, y, f,f,f ); } } } } bool LoadMesh( const char* pFileName, MeshData& rMeshData ) { if( !LoadPlyMesh( pFileName, rMeshData.vertices, rMeshData.indices, true ) ) return false; TinyRT::SahAABBTreeBuilder< Mesh > TreeBuilder( 0.7f ); Mesh tmpMesh( &rMeshData.vertices[0], &rMeshData.indices[0], rMeshData.vertices.size(), rMeshData.indices.size()/3 ); rMeshData.Tree.Build( &tmpMesh, TreeBuilder ); rMeshData.meshAABB.ComputeFromPoints( &rMeshData.vertices[0], rMeshData.vertices.size() ); return true; } int main( ) { static const int MESH_TYPE_COUNT = 5; static const int INSTANCE_COUNT = 1000; const char* MESH_FILES[MESH_TYPE_COUNT] = { "..\\models\\bunny.ply", "..\\models\\horse.ply", "..\\models\\elephant.ply", "..\\models\\toasters.ply", "..\\models\\ben.ply", }; // load all meshes MeshData meshes[MESH_TYPE_COUNT]; for( int i=0; i<MESH_TYPE_COUNT; i++ ) { printf("Parsing mesh: '%s'\n", MESH_FILES[i] ); if( !LoadMesh( MESH_FILES[i], meshes[i] ) ) { printf("Failure loading mesh: '%s'\n", MESH_FILES[i] ); return 1; } } // create mesh instances MeshInstance* pInstances[INSTANCE_COUNT]; int nSize = (int) sqrt( (float) INSTANCE_COUNT ); for( int i=0; i<INSTANCE_COUNT; i++ ) { float x = rand() / (float)RAND_MAX; float y = rand() / (float)RAND_MAX; x *= nSize; y *= nSize; pInstances[i] = new MeshInstance( meshes[ rand()%MESH_TYPE_COUNT ], TinyRT::Vec3f(x,0,y) ); } InstancedMeshObjectSet objects( &pInstances[0], INSTANCE_COUNT ); // position the camera TinyRT::Vec3f vLookAt( nSize/2.0f, 0, nSize/2.0f ); TinyRT::Vec3f vOrigin = vLookAt + Vec3f( 0, nSize/2.0f, (float) -nSize ); // draw PPMImage image(512,512); Render( vOrigin, vLookAt, image, objects ); image.SaveFile( "out.ppm"); return 0; }
[ "jbarcz1@6ce04321-59f9-4392-9e3f-c0843787e809" ]
[ [ [ 1, 287 ] ] ]
a73eec11e9381ba13cd06412ac052023cfdb1598
3e69b159d352a57a48bc483cb8ca802b49679d65
/trunk/pcbnew/move_copy_track.cpp
47c413d7d6c65e0b51e08ca5c9344382fd5df65a
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
UTF-8
C++
false
false
19,075
cpp
/****************************************************/ /* Edition des pistes */ /* Routines de duplication et deplacement de pistes */ /****************************************************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "pcbnew.h" #include "autorout.h" #include "drag.h" #include "protos.h" /* Routines externes */ static void Show_MoveTrack(WinEDA_DrawPanel * panel, wxDC * DC, bool erase); static void Exit_MoveTrack(WinEDA_DrawFrame * frame, wxDC *DC); #if 0 /* Routines Locales */ static void Duplic_Track(COMMAND * Cmd); static void Place_Dupl_Route(COMMAND * Cmd); #endif /* variables locales */ static wxPoint PosInit, LastPos; static TRACK * NewTrack; /* Nouvelle piste creee ou piste deplacee */ static int NbPtNewTrack; static int Old_HightLigth_NetCode; static bool Old_HightLigt_Status; /**************************************************************/ static void Exit_MoveTrack(WinEDA_DrawFrame * frame, wxDC *DC) /***************************************************************/ /* routine d'annulation de la commande drag, copy ou move track si une piste est en cours de tracage, ou de sortie de l'application EDITRACK. Appel par la touche ESC */ { TRACK * NextS; int ii; /* Effacement du trace en cours */ wxPoint oldpos = frame->GetScreen()->m_Curseur; frame->GetScreen()->m_Curseur = PosInit; frame->GetScreen()->ManageCurseur(frame->DrawPanel, DC, TRUE); frame->GetScreen()->m_Curseur = oldpos; g_HightLigt_Status = FALSE; ( (WinEDA_PcbFrame *)frame)->DrawHightLight( DC, g_HightLigth_NetCode) ; if( NewTrack ) { if (NewTrack->m_Flags & IS_NEW ) { for( ii = 0; ii < NbPtNewTrack; ii++, NewTrack = NextS) { if(NewTrack == NULL) break; NextS = (TRACK*) NewTrack->Pnext; delete NewTrack; } } else /* Move : remise en ancienne position */ { TRACK * Track = NewTrack; int dx = LastPos.x - PosInit.x; int dy = LastPos.y - PosInit.y; for( ii = 0; ii < NbPtNewTrack; ii++, Track = (TRACK*) Track->Pnext) { if( Track == NULL ) break; Track->m_Start.x -= dx; Track->m_Start.y -= dy; Track->m_End.x -= dx; Track->m_End.y -= dy; Track->m_Flags = 0; } Trace_Une_Piste(frame->DrawPanel, DC, NewTrack,NbPtNewTrack,GR_OR); } NewTrack = NULL; } frame->GetScreen()->ManageCurseur = NULL; frame->GetScreen()->ForceCloseManageCurseur = NULL; frame->GetScreen()->m_CurrentItem = NULL; frame->EraseMsgBox(); /* Annulation deplacement et Redessin des segments dragges */ DRAG_SEGM * pt_drag = g_DragSegmentList; for( ; pt_drag != NULL; pt_drag = pt_drag->Pnext) { TRACK * Track = pt_drag->m_Segm; pt_drag->SetInitialValues(); Track->SetState(EDIT,OFF); Track->m_Flags = 0; Track->Draw(frame->DrawPanel, DC, GR_OR); } g_HightLigth_NetCode = Old_HightLigth_NetCode; g_HightLigt_Status = Old_HightLigt_Status; if(g_HightLigt_Status) ( (WinEDA_PcbFrame *)frame)->DrawHightLight( DC, g_HightLigth_NetCode) ; EraseDragListe(); } /*************************************************************************/ static void Show_MoveTrack(WinEDA_DrawPanel * panel, wxDC * DC, bool erase) /*************************************************************************/ /* redessin du contour de la piste lors des deplacements de la souris */ { int ii, dx, dy; TRACK * Track; BASE_SCREEN * screen = panel->GetScreen(); int track_fill_copy = DisplayOpt.DisplayPcbTrackFill; DisplayOpt.DisplayPcbTrackFill = SKETCH ; erase = TRUE; /* efface ancienne position si elle a ete deja dessinee */ if( erase ) { if ( NewTrack ) Trace_Une_Piste(panel, DC, NewTrack,NbPtNewTrack,GR_XOR) ; } /* mise a jour des coordonnees des segments de la piste */ wxPoint Pos = screen->m_Curseur; dx = Pos.x - LastPos.x; dy = Pos.y - LastPos.y; LastPos = Pos; ii = NbPtNewTrack, Track = NewTrack; for( ; ii > 0; ii--, Track = Track->Next() ) { if( Track->m_Flags & STARTPOINT) { Track->m_Start.x += dx; Track->m_Start.y += dy; } if( Track->m_Flags & ENDPOINT) { Track->m_End.x += dx; Track->m_End.y += dy; } } /* dessin de la nouvelle piste */ Trace_Une_Piste(panel, DC, NewTrack,NbPtNewTrack,GR_XOR) ; /* Tracage des segments dragges */ DRAG_SEGM * pt_drag = g_DragSegmentList; for( ; pt_drag != NULL; pt_drag = pt_drag->Pnext) { Track = pt_drag->m_Segm; if ( erase ) Track->Draw(panel, DC, GR_XOR); if( Track->m_Flags & STARTPOINT) { Track->m_Start.x += dx; Track->m_Start.y += dy; } if( Track->m_Flags & ENDPOINT) { Track->m_End.x += dx; Track->m_End.y += dy; } Track->Draw(panel, DC, GR_XOR); } DisplayOpt.DisplayPcbTrackFill = track_fill_copy ; } /***********************************************************************************/ void WinEDA_PcbFrame::Start_MoveOneTrackSegment(TRACK * track, wxDC * DC, bool Drag) /***********************************************************************************/ { /* Change hight light net: the new one will be hightlighted */ Old_HightLigt_Status = g_HightLigt_Status; Old_HightLigth_NetCode = g_HightLigth_NetCode; if(g_HightLigt_Status) Hight_Light(DC); if ( Drag && track->m_StructType == TYPEVIA) { track->m_Flags = IS_DRAGGED|STARTPOINT|ENDPOINT; Collect_TrackSegmentsToDrag(DrawPanel, DC, track->m_Start, track->ReturnMaskLayer(), track->m_NetCode); NewTrack = track; NbPtNewTrack = 1; PosInit = track->m_Start; } else { int diag = track->IsPointOnEnds(GetScreen()->m_Curseur, -1); wxPoint pos = (diag & STARTPOINT) ? track->m_Start : track->m_End; Collect_TrackSegmentsToDrag(DrawPanel, DC, pos, track->ReturnMaskLayer(), track->m_NetCode); track->m_Flags |= IS_DRAGGED; NewTrack = NULL; NbPtNewTrack = 0; PosInit = pos; } LastPos = PosInit; GetScreen()->ManageCurseur = Show_MoveTrack; GetScreen()->ForceCloseManageCurseur = Exit_MoveTrack; g_HightLigth_NetCode = track->m_NetCode; g_HightLigt_Status = TRUE; DrawHightLight( DC, g_HightLigth_NetCode) ; GetScreen()->ManageCurseur(DrawPanel, DC, TRUE); } /**********************************************************************/ bool WinEDA_PcbFrame::PlaceDraggedTrackSegment(TRACK * Track, wxDC * DC) /**********************************************************************/ /* Place a dragged track segment or via */ { int errdrc; DRAG_SEGM * pt_drag; if(Track == NULL ) return FALSE; // DRC control: if(Drc_On) { errdrc = Drc(this, DC, Track, m_Pcb->m_Track,1); if(errdrc == BAD_DRC) return FALSE; /* Tracage des segments dragges */ pt_drag = g_DragSegmentList; for( ; pt_drag; pt_drag = pt_drag->Pnext) { errdrc = Drc(this, DC, pt_drag->m_Segm, m_Pcb->m_Track,1); if(errdrc == BAD_DRC) return FALSE; } } // DRC Ok: place track segments Track->m_Flags = 0; Track->Draw(DrawPanel, DC, GR_OR); /* Tracage des segments dragges */ pt_drag = g_DragSegmentList; for( ; pt_drag; pt_drag = pt_drag->Pnext) { Track = pt_drag->m_Segm; Track->SetState(EDIT,OFF); Track->m_Flags = 0; Track->Draw(DrawPanel, DC, GR_OR); } EraseDragListe(); GetScreen()->SetModify(); GetScreen()->ManageCurseur = NULL; GetScreen()->ForceCloseManageCurseur = NULL; return TRUE; } #if 0 /***********************************************/ void WinEDA_PcbFrame::Place_Dupl_Route(Track * Track, wxDC * DC) /******************************************/ /* Routine de placement d'une piste (succession de segments) */ { D_PAD * pt_pad; TRACK * pt_track, *Track, * pt_classe, *NextS; int masquelayer; EDA_BaseStruct * LockPoint; int ii, old_net_code, new_net_code, DRC_error = 0; wxDC * DC = Cmd->DC; ActiveScreen->ManageCurseur = NULL; if( NewTrack == NULL ) return ; old_net_code = NewTrack->net_code; /* Placement du flag BUSY de la piste originelle, qui ne doit pas etre vue dans les recherches de raccordement suivantes */ ii = NbPtNewTrack; pt_track = NewTrack; for ( ; ii > 0; ii --, pt_track = (TRACK*) pt_track->Pnext) { pt_track->SetState(BUSY, ON); } /* Detection du nouveau net_code */ ii = NbPtNewTrack; pt_track = NewTrack; for ( ; ii > 0; ii --, pt_track = (TRACK*) pt_track->Pnext) { pt_track->net_code = 0; } new_net_code = 0; ii = 0; pt_track = NewTrack; for( ; ii < NbPtNewTrack ; ii++, pt_track = (TRACK*)pt_track->Pnext) { /* Localisation de la pastille ou segment en debut de segment: */ masquelayer = tab_layer[pt_track->Layer]; LockPoint = LocateLockPoint(pt_track->m_Start.x,pt_track->m_Start.y,masquelayer); if( LockPoint ) { if ( LockPoint->m_StructType == TYPEPAD ) { pt_pad = (D_PAD*) LockPoint; new_net_code = pt_pad->net_code; if ( new_net_code > 0 ) break; } else /* debut de piste sur un segment de piste */ { Track = (TRACK *) LockPoint; new_net_code = Track->net_code; if ( new_net_code > 0 ) break; } } LockPoint = LocateLockPoint(pt_track->m_End.x,pt_track->m_End.y,masquelayer); if( LockPoint ) { if ( LockPoint->m_StructType == TYPEPAD ) { pt_pad = (D_PAD*) LockPoint; new_net_code = pt_pad->net_code; if ( new_net_code > 0 ) break; } else /* debut de piste sur un segment de piste */ { Track = (TRACK *) LockPoint; new_net_code = Track->net_code; if ( new_net_code > 0 ) break; } } } /* Mise a jour du nouveau net code de la piste */ ii = 0; pt_track = NewTrack; for( ; ii < NbPtNewTrack; ii++, pt_track = (TRACK*)pt_track->Pnext) { pt_track->net_code = new_net_code; } /* Controle DRC de la nouvelle piste */ ii = 0; pt_track = NewTrack; for( ; ii < NbPtNewTrack; ii++, pt_track = pt_track->Next() ) { if( Drc_On == RUN ) if( drc(DC, pt_track, pt_pcb->Track, 1) == BAD_DRC ) { if( confirmation(" Erreur DRC, Place piste:") == YES ) continue; else { DRC_error = 1; break; } } } if( DRC_error == 0) { if(FlagState == MOVE_ROUTE) { /* copie nouvelle piste */ pt_track = NewTrack; NewTrack = pt_track->Copy(NbPtNewTrack); /* effacement ancienne ( chainage et liens mauvais */ ii = NbPtNewTrack; for ( ; ii > 0; ii --, pt_track = NextS) { NextS = (TRACK*) pt_track->Pnext; DeleteStructure(pt_track); } test_1_net_connexion(DC, old_net_code ); } pt_classe = NewTrack->GetBestInsertPoint(); NewTrack->Insert(pt_classe); Trace_Une_Piste(DC, NewTrack,NbPtNewTrack,GR_OR) ; /* Mise a jour des connexions sur pads et sur pistes */ ii = 0; pt_track = NewTrack; for( ; ii < NbPtNewTrack; ii++, pt_track = NextS) { NextS = (TRACK*)pt_track->Pnext; pt_track->SetState(BEGIN_ONPAD|END_ONPAD, OFF); masquelayer = tab_layer[pt_track->Layer]; /* Localisation de la pastille ou segment sur debut segment: */ LockPoint = LocateLockPoint(pt_track->m_Start.x,pt_track->m_Start.y,masquelayer); if( LockPoint ) { pt_track->start = LockPoint; if ( LockPoint->m_StructType == TYPEPAD ) { /* fin de piste sur un pad */ pt_pad = (D_PAD*) LockPoint; pt_track->SetState(BEGIN_ONPAD, ON); } else /* debut de piste sur un segment de piste */ { Track = (TRACK *) LockPoint; CreateLockPoint(&pt_track->m_Start.x,&pt_track->m_Start.y,Track,pt_track); } } /* Localisation de la pastille ou segment sur fin de segment: */ LockPoint = LocateLockPoint(pt_track->m_End.x,pt_track->m_End.y,masquelayer); if( LockPoint ) { pt_track->end = LockPoint; if ( LockPoint->m_StructType == TYPEPAD ) { /* fin de piste sur un pad */ pt_pad = (D_PAD*) LockPoint; pt_track->SetState(END_ONPAD, ON); } else /* debut de piste sur un segment de piste */ { Track = (TRACK *) LockPoint; CreateLockPoint(&pt_track->m_Start.x,&pt_track->m_Start.y,Track,pt_track); } } } /* Suppression du flag BUSY */ ii = NbPtNewTrack; pt_track = NewTrack; for ( ; ii > 0; ii --, pt_track = (TRACK*) pt_track->Pnext) { pt_track->SetState(BUSY, OFF); } test_1_net_connexion(DC, new_net_code ); ActiveScreen->SetModify(); } else /* Erreur DRC: Annulation commande */ { DisplayOpt.DisplayPcbTrackFill = SKETCH ; Trace_Une_Piste(DC, NewTrack,NbPtNewTrack,GR_XOR); DisplayOpt.DisplayPcbTrackFill = Track_fill_copy ; if(FlagState == MOVE_ROUTE) { /* Remise en position de la piste deplacee */ Track = NewTrack; PosInitX -= Track->m_Start.x; PosInitY -= Track->m_Start.y; for( ii = 0; ii < NbPtNewTrack; ii++, Track = (TRACK*) Track->Pnext) { if( Track == NULL ) break; Track->m_Start.x += PosInitX; Track->m_Start.y += PosInitY; Track->m_End.x += PosInitX; Track->m_End.y += PosInitY; Track->SetState(BUSY,OFF); } Trace_Une_Piste(DC, NewTrack,NbPtNewTrack,GR_OR); } if (FlagState == COPY_ROUTE ) { /* Suppression copie */ for( ii = 0; ii < NbPtNewTrack; NewTrack = NextS) { if(NewTrack == NULL) break; NextS = (TRACK*) NewTrack->Pnext; delete NewTrack; } } } NewTrack = NULL; Affiche_Infos_Status_Pcb(Cmd); if(Etat_Surbrillance) Hight_Light(DC); } /************************************************/ void WinEDA_PcbFrame::Start_CopieMove_Route(TRACK * track, wxDC * DC, bool Drag) /************************************************/ /* Routine permettant la recopie d'une piste (suite de segments) deja tracee */ { int ii; TRACK *pt_segm, *pt_track; int masquelayer = tab_layer[ActiveScreen->Active_Layer]; wxDC * DC = Cmd->DC; if( NewTrack ) return; FlagState = (int)Cmd->Menu->param_inf; /* Recherche de la piste sur la couche active (non zone) */ for(pt_segm = pt_pcb->Track; pt_segm != NULL; pt_segm = (TRACK*)pt_segm->Pnext) { pt_segm = Locate_Pistes(pt_segm,masquelayer, CURSEUR_OFF_GRILLE); if( pt_segm == NULL ) break ; break ; } if( pt_segm != NULL ) { if (FlagState == COPY_ROUTE ) pt_track = Marque_Une_Piste(DC, pt_segm, &NbPtNewTrack, 0); else pt_track = Marque_Une_Piste(DC, pt_segm, &NbPtNewTrack, GR_XOR); if(NbPtNewTrack) /* Il y a NbPtNewTrack segments de piste a traiter */ { /* effacement du flag BUSY de la piste originelle */ ii = NbPtNewTrack; pt_segm = pt_track; for ( ; ii > 0; ii --, pt_segm = (TRACK*) pt_segm->Pnext) { pt_segm->SetState(BUSY, OFF); } if (FlagState == COPY_ROUTE ) NewTrack = pt_track->Copy(NbPtNewTrack); else NewTrack = pt_track; Affiche_Infos_Piste(Cmd, pt_track) ; startX = ActiveScreen->Curseur_X; startY = ActiveScreen->Curseur_Y; Place_Dupl_Route_Item.State = WAIT; ActiveScreen->ManageCurseur = Show_Move_Piste; DisplayOpt.DisplayPcbTrackFill = SKETCH ; Trace_Une_Piste(DC, NewTrack,NbPtNewTrack,GR_XOR) ; DisplayOpt.DisplayPcbTrackFill = Track_fill_copy ; PosInitX = NewTrack->m_Start.x; PosInitY = NewTrack->m_Start.y; } } } #endif /************************************************************************/ EDA_BaseStruct * LocateLockPoint(BOARD * Pcb, wxPoint pos, int LayerMask) /************************************************************************/ /* Routine trouvant le point " d'accrochage " d'une extremite de piste. Ce point peut etre un PAD ou un autre segment de piste Retourne: - pointeur sur ce PAD ou: - pointeur sur le segment ou: - NULL Parametres d'appel: coord pX, pY du point tst masque des couches a tester */ { D_PAD * pt_pad; TRACK * ptsegm; MODULE * Module; /* detection du point type PAD */ pt_pad = NULL; Module = Pcb->m_Modules; for( ; Module != NULL; Module = (MODULE*)Module->Pnext ) { pt_pad = Locate_Pads(Module, pos, LayerMask); if (pt_pad) return(pt_pad); } /* ici aucun pad n'a ete localise: detection d'un segment de piste */ ptsegm = Fast_Locate_Piste( Pcb->m_Track, NULL, pos, LayerMask); if( ptsegm == NULL ) ptsegm = Locate_Pistes( Pcb->m_Track, pos, LayerMask); return(ptsegm); } /******************************************************************************/ TRACK * CreateLockPoint(int *pX, int *pY, TRACK * ptsegm, TRACK * refsegm) /******************************************************************************/ /* Routine de creation d'un point intermediaire sur un segment le segment ptsegm est casse en 2 segments se raccordant au point pX, pY retourne: NULL si pas de nouveau point ( c.a.d si pX, pY correspondait deja a une extremite ou: pointeur sur le segment cree si refsegm != NULL refsegm est pointeur sur le segment incident, et le point cree est l'intersection des 2 axes des segments ptsegm et refsegm retourne la valeur exacte de pX et pY Si ptsegm pointe sur une via: retourne la valeur exacte de pX et pY et ptsegm, mais ne cree pas de point supplementaire */ { int cX, cY; int dx, dy; /* Coord de l'extremite du segm ptsegm / origine */ int ox, oy, fx , fy; /* coord de refsegm / origine de prsegm */ TRACK * NewTrack; if( (ptsegm->m_Start.x == *pX) && (ptsegm->m_Start.y == *pY) ) return(NULL); if( (ptsegm->m_End.x == *pX) && (ptsegm->m_End.y == *pY) ) return(NULL); /* le point n'est pas sur une extremite de piste */ if(ptsegm->m_StructType == TYPEVIA ) { *pX = ptsegm->m_Start.x; *pY = ptsegm->m_Start.y; return(ptsegm); } /* calcul des coord vraies du point intermediaire dans le repere d'origine = origine de ptsegm */ cX = *pX - ptsegm->m_Start.x; cY = *pY - ptsegm->m_Start.y; dx = ptsegm->m_End.x - ptsegm->m_Start.x; dy = ptsegm->m_End.y - ptsegm->m_Start.y; // ***** A COMPLETER : non utilise if ( refsegm ) { ox = refsegm->m_Start.x - ptsegm->m_Start.x; oy = refsegm->m_Start.y - ptsegm->m_Start.y; fx = refsegm->m_End.x - ptsegm->m_Start.x; fy = refsegm->m_End.y - ptsegm->m_Start.y; } /* pour que le point soit sur le segment ptsegm: cY/cX = dy/dx */ if ( dx == 0 ) cX = 0; /* segm horizontal */ else cY = (cX * dy) / dx; /* creation du point intermediaire ( c'est a dire creation d'un nouveau segment, debutant au point intermediaire */ cX += ptsegm->m_Start.x; cY += ptsegm->m_Start.y; NewTrack = ptsegm->Copy(); NewTrack->Insert(NULL, ptsegm); /* correction du pointeur de fin du nouveau segment */ NewTrack->end = ptsegm->end; /* le segment primitif finit au nouveau point : */ ptsegm->m_End.x = cX; ptsegm->m_End.y = cY; ptsegm->SetState(END_ONPAD, OFF); /* le nouveau segment debute au nouveau point : */ ptsegm = NewTrack;; ptsegm->m_Start.x = cX; ptsegm->m_Start.y = cY; ptsegm->SetState(BEGIN_ONPAD, OFF); *pX = cX; *pY = cY; return(ptsegm); }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26", "fcoiffie@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 554 ], [ 556, 560 ], [ 562, 562 ], [ 564, 645 ] ], [ [ 555, 555 ], [ 561, 561 ], [ 563, 563 ] ] ]
1b9edf2d61f7039a7586ebae32a3d18c130329cc
7ba7440b6a7b6068c900d561ad03c3ff86439c09
/GalDemo/GalDemo/GameFSM.cpp
a1afe96d214f94ffc97c6d3dd36e5d01d6ae5e7e
[]
no_license
weimingtom/gal-demo
96dc06f8f02b4c767412aac7fcf050e241b40c04
f2b028591a195516af3ce33d084b7b29cbea84aa
refs/heads/master
2021-01-20T11:47:07.598476
2011-08-10T23:48:43
2011-08-10T23:48:43
42,379,726
2
0
null
null
null
null
UTF-8
C++
false
false
43
cpp
#include "stdafx.h" #include "GameFSM.h"
[ [ [ 1, 2 ] ] ]
5f9b13a7a3bf74a79516fc46e4d99b420fce818c
353bd39ba7ae46ed521936753176ed17ea8546b5
/src/layer1_system/input/src/axip_keyboard.cpp
029e83e1d135bb453139cb91e66ab6651433fa64
[]
no_license
d0n3val/axe-engine
1a13e8eee0da667ac40ac4d92b6a084ab8a910e8
320b08df3a1a5254b776c81775b28fa7004861dc
refs/heads/master
2021-01-01T19:46:39.641648
2007-12-10T18:26:22
2007-12-10T18:26:22
32,251,179
1
0
null
null
null
null
UTF-8
C++
false
false
1,395
cpp
/** * @file * Class for keyboard device type * @author Ricard Pillosu <d0n3val\@gmail.com> * @date 23 May 2004 */ #include "axip_stdafx.h" /** * Constructor */ axip_keyboard::axip_keyboard() : axip_device() { num_vkeys = MAX_KEYBOARD_VKEYS; type = AXIP_DEVICE_KEYBOARD; } /** * Update */ bool axip_keyboard::update(const int my_id) { /*$1- First, clear previuos events -----------------------------------------*/ num_events = 0; //! Receives buffered data DIDEVICEOBJECTDATA buffered_data[MAX_KEYBOARD_EVENTS]; DWORD buffer_size = MAX_KEYBOARD_EVENTS; /*$1- First, update DInput device ------------------------------------------*/ if( false == update_device(buffered_data, &buffer_size) ) { return( false ); } AXE_ASSERT(buffer_size <= MAX_KEYBOARD_EVENTS); /*$1- Here we flush with the contents of the buffered data from directinput */ for( DWORD i = 0; i < buffer_size; i++ ) { events[i].device = my_id; events[i].type = ( buffered_data[i].dwData & 0x80 ) ? AXIP_EVENT_KEY_PRESSED : AXIP_EVENT_KEY_RELEASED; events[i].value = buffered_data[i].dwOfs; events[i].time = buffered_data[i].dwTimeStamp; } num_events = buffer_size; return( true ); } /** * Returns list of last events */ const axip_event* axip_keyboard::get_events() const { return(&events[0]); }
[ "d0n3val@2cff7946-3f3c-0410-b79f-f9b517ddbf54" ]
[ [ [ 1, 53 ] ] ]
728bfd8a4246c108f6d401afac2d239ba5d009ab
7b7a3f9e0cac33661b19bdfcb99283f64a455a13
/Engine/dll/Core/flx_light.cpp
799169f3015a5d2c7ad0e20491402842c1b88f55
[]
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,643
cpp
/*--------------------------------------------------------------------------- This source file is part of the FluxEngine. Copyright (c) 2008 - 2009 Marvin K. (starvinmarvin) This program is free software. ---------------------------------------------------------------------------*/ #include "flx_light.h" #include "flx_renderer.h" int Light::s_iMaxNumLights = 0; Light::Light() { m_LightType = LIGHT_POINT; m_bOn = true; m_f4ColorAmbient[0] = 0.0f; //black ambient light m_f4ColorAmbient[1] = 0.0f; m_f4ColorAmbient[2] = 0.0f; m_f4ColorAmbient[3] = 1.0f; m_f4ColorDiffuse[0] = 1.0f; //white diffuse color m_f4ColorDiffuse[1] = 1.0f; m_f4ColorDiffuse[2] = 1.0f; m_f4ColorDiffuse[3] = 1.0f; //alpha = 1 -> visible m_f4ColorSpecular[0] = 1.0f; m_f4ColorSpecular[0] = 1.0f; m_f4ColorSpecular[0] = 1.0f; m_f4ColorSpecular[0] = 1.0f; m_fExponent = 0.0f; m_fCutoff = 180.f; m_f3Attenuation[0] = 1.0f; m_f3Attenuation[1] = 0.0f; m_f3Attenuation[2] = 0.0f; m_f4Position[0] = 0.0f; m_f4Position[1] = 0.0f; m_f4Position[2] = 0.0f; m_f4Position[3] = 1.0f; m_f3Direction[0] = 0.0f; m_f3Direction[1] = 0.0f; m_f3Direction[2] = -1.0f; switch (Flux::Renderer::getInstance()->GetRendererType()) { case R_OPENGL: { //how many lights do the gpu support? glGetIntegerv(GL_MAX_LIGHTS, &s_iMaxNumLights); break; } } } Light::~Light() { //penis :D } void Light::Disable(int iLightCounter) { switch (Flux::Renderer::getInstance()->GetRendererType()) { case R_OPENGL: m_iLightID = GL_LIGHT0 + iLightCounter; glDisable(m_iLightID); break; } } void Light::SetOn(bool bOn) { m_bOn = bOn; } bool Light::isOn() { return m_bOn; } void Light::SetAmbientColor(ColorOGL fColor) { m_f4ColorAmbient[0] = fColor.m_fRed; m_f4ColorAmbient[1] = fColor.m_fGreen; m_f4ColorAmbient[2] = fColor.m_fBlue; m_f4ColorAmbient[3] = fColor.m_fAlpha; } float* Light::GetAmbienColor() { return &m_f4ColorAmbient[0]; } void Light::SetDiffuseColor(ColorOGL fColor) { m_f4ColorDiffuse[0] = fColor.m_fRed; m_f4ColorDiffuse[1] = fColor.m_fGreen; m_f4ColorDiffuse[2] = fColor.m_fBlue; m_f4ColorDiffuse[3] = fColor.m_fAlpha; } float* Light::GetDiffuseColor() { return &m_f4ColorDiffuse[0]; } void Light::SetSpecularColor(ColorOGL fColor) { m_f4ColorSpecular[0] = fColor.m_fRed; m_f4ColorSpecular[1] = fColor.m_fGreen; m_f4ColorSpecular[2] = fColor.m_fBlue; m_f4ColorSpecular[3] = fColor.m_fAlpha; } float* Light::GetSpecularColor() { return &m_f4ColorSpecular[0]; }
[ "marvin.kicha@e13029a8-578f-11de-8abc-d1c337b90d21" ]
[ [ [ 1, 131 ] ] ]
b1216150c7ebfeeb0ff112600dea0a13a3e3afbc
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.2/bctestservicehandler/inc/bctestservicehandlercontainer.h
c454e9ded7e19fb412815b955794b1b4b2595904
[]
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
2,046
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: container * */ #ifndef BCTEST_SERVICEHANDLERCONTAINER_H #define BCTEST_SERVICEHANDLERCONTAINER_H #include <coecntrl.h> /** * container class */ class CBCTestServiceHandlerContainer: public CCoeControl { public: // constructor and destructor /** * C++ default constructor */ CBCTestServiceHandlerContainer(); /** * Destructor */ virtual ~CBCTestServiceHandlerContainer(); /** * Symbian 2nd constructor */ void ConstructL( const TRect& aRect ); public: // new functions /** * Set component control, and container will own the control * @param aControl pointer to a control. */ void SetControl( CCoeControl* aControl ); /** * Delete control */ void ResetControl(); public: // from CCoeControl /** * Return count of component controls */ TInt CountComponentControls() const; /** * Return pointer to component control specified by index * @param aIndex, a index to specify a component control */ CCoeControl* ComponentControl( TInt aIndex ) const; private: // from CCoeControl /** * From CCoeControl, Draw. * Fills the window's rectangle. * @param aRect Region of the control to be (re)drawn. */ void Draw( const TRect& aRect ) const; private: // data /** * Pointer to component control. * Owned */ CCoeControl* iControl; }; #endif // BCTEST_SERVICEHANDLERCONTAINER_H
[ "none@none" ]
[ [ [ 1, 90 ] ] ]
9dcd5e45780f65a80208f7ed09ff2f910cbe5b48
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/maxsdk2008/include/maxscrpt/maxobj.h
bbfd410b69f38816d1c46c2ffea643859423e6a3
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
75,424
h
/* * MAXObject.h - MAX object wrapper classes in MAXScript * * Copyright © John Wainwright 1996 * */ #ifndef _H_MAXOBJECT #define _H_MAXOBJECT #include "Max.h" #include "SimpObj.h" #include "Pathname.h" #include "istdplug.h" #include "tvnode.h" #include "funcs.h" #include "tvUtil.h" #include "custattrib.h" #include "macrorec.h" #include "3dsmaxport.h" extern ScripterExport Interface* MAXScript_interface; extern ScripterExport Interface7* MAXScript_interface7; extern ScripterExport Interface8* MAXScript_interface8; extern ScripterExport Interface9* MAXScript_interface9; class MAXControl; #define MESH_READ_ACCESS 0 // mesh access modes #define MESH_WRITE_ACCESS 1 #define MESH_BASE_OBJ 2 #define EPOLYOBJ_CLASS_ID Class_ID(0x1bf8338d,0x192f6098) /* --------------------- base wrapper class ------------------------ */ /* subclasses of MAXWrapper act as MAXScript-side proxies for MAX-side objects, * such as nodes, modifiers, materials, etc. The prime purpose of MAXWrapper is * to maintain MAX referenced to the MAX-side objects it wraps & process delete notify messages * * subclasses should all do a ReplaceReference for each ref on creation & check for * any ref deletion on the MAX side by using the check_for_deletion() macro. */ extern ScripterExport MCHAR* get_deleted_obj_err_message(); #define check_for_deletion_test() \ ( ref_deleted || \ ( NumRefs() > 0 && (GetReference(0) == NULL) ) || \ ( NumRefs() > 0 && \ GetReference(0)->TestAFlag(A_IS_DELETED) && \ ( (GetReference(0)->GetInterface(INODE_INTERFACE)==NULL) || \ (((INode*)GetReference(0))->GetTMController() == NULL) || \ (((INode*)GetReference(0))->GetParentNode() == NULL) \ ) \ ) \ ) #define check_for_deletion() if (check_for_deletion_test()) throw RuntimeError (get_deleted_obj_err_message(), class_name()); #define deletion_check_test(val) \ ( (val)->ref_deleted || \ ( (val)->NumRefs() > 0 && ((val)->GetReference(0) == NULL) ) || \ ( (val)->NumRefs() > 0 && \ (val)->GetReference(0)->TestAFlag(A_IS_DELETED) && \ ( ((val)->GetReference(0)->GetInterface(INODE_INTERFACE)==NULL) || \ (((INode*)(val)->GetReference(0))->GetTMController() == NULL) || \ (((INode*)(val)->GetReference(0))->GetParentNode() == NULL) \ ) \ ) \ ) #define deletion_check(val) if (deletion_check_test(val)) throw RuntimeError (get_deleted_obj_err_message(), (val)->class_name()); visible_class (MAXWrapper) class MAXWrapper : public Value, public ReferenceTarget // ReferenceMaker { public: Tab<RefTargetHandle> refs; /* reference array */ short ref_deleted; ScripterExport MAXWrapper(); ScripterExport virtual ~MAXWrapper(); // Needed to solve ambiguity between Collectable's operators and MaxHeapOperators using Collectable::operator new; using Collectable::operator delete; ScripterExport Value* classOf_vf(Value** arg_list, int count); ScripterExport Value* superClassOf_vf(Value** arg_list, int count); ScripterExport Value* isKindOf_vf(Value** arg_list, int count); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXWrapper)) ? 1 : Value::is_kind_of(c); } ScripterExport BOOL not_on_undo_stack(); void collect() { if (not_on_undo_stack()) delete this; } ScripterExport void gc_trace(); virtual MCHAR* class_name() = 0; virtual ReferenceTarget* get_max_object() { return (NumRefs()) ? GetReference(0) : NULL; } // LAM - 7/18/01 ScripterExport Value* copy_no_undo(Value** arg_list, int count); BOOL derives_from_MAXWrapper() { return TRUE; } // LAM - 7/8/03 - defect 504956 ScripterExport void make_ref(int ref_no, ReferenceTarget* ref); void drop_MAX_refs() { DeleteAllRefsFromMe(); } // Animatable Class_ID ClassID() { return Class_ID(MAXSCRIPT_WRAPPER_CLASS_ID, 0); } SClass_ID SuperClassID() { return MAXSCRIPT_WRAPPER_CLASS_ID; } // ReferenceMaker int NumRefs() { return refs.Count(); } RefTargetHandle GetReference(int i) { return refs[i]; } ScripterExport void SetReference(int i, RefTargetHandle rtarg); ScripterExport RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message); ScripterExport void DeleteThis(); BOOL CanTransferReference(int i) { return FALSE; } // For adding special cases for wrappers of object that we want to allow to be deleted // even though MAXScript may hold a reference to them. ScripterExport BOOL IsRealDependency(ReferenceTarget *rtarg); // generic property accessors (operate on ref(0)) ScripterExport Value* get_property(Value** arg_list, int count); ScripterExport Value* set_property(Value** arg_list, int count); // direct property access, when no wrapper exists, but we have the MAX-side ref static ScripterExport Value* get_property(ReferenceTarget* ref, Value* prop, Value* owner); static ScripterExport Value* set_property(ReferenceTarget* ref, Value* prop, Value* val); //#include "defimpfn.h" // RK: 06/01/99 Redefining these macros with ScripterExport directive so that // .dlx plugins can have classes derived from MAXWrapper // RK: Start #ifdef def_generic # undef def_generic # undef def_generic_debug_ok # undef def_property # undef def_2_prop_path # undef def_nested_prop #endif #ifdef def_prop_getter # undef def_prop_getter # undef def_prop_setter #endif #define def_generic(fn, name) \ ScripterExport Value* fn##_vf(Value** arglist, int arg_count) #define def_generic_debug_ok(fn, name) \ ScripterExport Value* fn##_vf(Value** arglist, int arg_count) #define def_property(p) \ ScripterExport Value* get_##p(Value** arg_list, int count); \ ScripterExport Value* set_##p(Value** arg_list, int count) #define def_prop_getter(p) \ ScripterExport Value* get_##p(Value** arg_list, int count) #define def_prop_setter(p) \ ScripterExport Value* set_##p(Value** arg_list, int count) #define def_2_prop_path(p1, p2) \ ScripterExport Value* get_##p1##_##p2(Value** arg_list, int count); \ ScripterExport Value* set_##p1##_##p2(Value** arg_list, int count) #define def_nested_prop(p1) \ ScripterExport Value* get_nested_##p1(Value** arg_list, int count); \ ScripterExport Value* set_nested_##p1(Value** arg_list, int count) // RK: End // russom - 08/16/01 - 307022 def_generic( eq, "="); def_generic( ne, "!="); def_generic (numrefs, "numRefs"); // peek & poke for MAXScript... def_generic (getref, "getRef"); def_generic (setref, "getRef"); def_generic (numsubs, "numSubs"); def_generic (getsub, "getSub"); def_generic (setsub, "getSub"); def_generic (show_props, "showProperties"); def_generic (get_props, "getPropNames"); def_generic (copy, "copy"); def_generic (isDeleted, "isDeleted"); def_generic (exprForMAXObject, "exprForMAXObject"); // def_generic (dependsOn, "dependsOn"); def_generic (show_interfaces, "showInterfaces"); // LAM - 6/29/00 def_generic (get_interfaces, "getInterfaces"); def_generic (get_interface, "getInterface"); // the standard transform subanim properties def_property ( pos ); def_2_prop_path ( pos, controller ); def_2_prop_path ( pos, isAnimated ); def_2_prop_path ( pos, keys ); def_2_prop_path ( pos, track ); def_2_prop_path ( pos, x ); def_2_prop_path ( pos, y ); def_2_prop_path ( pos, z ); def_property ( rotation ); def_2_prop_path ( rotation, angle ); def_2_prop_path ( rotation, x_rotation ); def_2_prop_path ( rotation, y_rotation ); def_2_prop_path ( rotation, z_rotation ); def_2_prop_path ( rotation, axis ); def_2_prop_path ( rotation, controller ); def_2_prop_path ( rotation, isAnimated ); def_2_prop_path ( rotation, keys ); def_2_prop_path ( rotation, track ); def_property ( scale ); def_2_prop_path ( scale, controller ); def_2_prop_path ( scale, isAnimated ); def_2_prop_path ( scale, keys ); def_2_prop_path ( scale, track ); def_2_prop_path ( scale, x ); def_2_prop_path ( scale, y ); def_2_prop_path ( scale, z ); def_property ( controller ); def_property ( transform ); def_property ( isAnimated ); def_property ( numsubs ); def_nested_prop ( angle ); def_nested_prop ( x_rotation ); def_nested_prop ( y_rotation ); def_nested_prop ( z_rotation ); def_nested_prop ( axis ); def_nested_prop ( controller ); def_nested_prop ( isAnimated ); def_nested_prop ( keys ); def_nested_prop ( x ); def_nested_prop ( y ); def_nested_prop ( z ); def_nested_prop ( w ); // utility methods for the above subanim property accessors, implemented by // those that have standard transform subsanims virtual Control* get_max_pos_controller(ParamDimension** pdim) { return NULL; } virtual Control* get_max_scale_controller(ParamDimension** pdim) { return NULL; } virtual Control* get_max_rotation_controller(ParamDimension** pdim) { return NULL; } virtual Control* get_max_tm_controller(ParamDimension** pdim) { return NULL; } virtual Control* get_max_controller(ParamDimension** pdim) { return NULL; } ScripterExport virtual Control* get_max_prop_controller(Value* prop, ParamDimension** pdim); virtual BOOL set_max_pos_controller(MAXControl* c) { return FALSE; } virtual BOOL set_max_scale_controller(MAXControl* c) { return FALSE; } virtual BOOL set_max_rotation_controller(MAXControl* c) { return FALSE; } virtual BOOL set_max_tm_controller(MAXControl* c) { return FALSE; } virtual BOOL set_max_controller(MAXControl* c) { return FALSE; } ScripterExport virtual BOOL set_max_prop_controller(Value* prop, MAXControl* c); static ScripterExport Control* get_max_prop_controller(ReferenceTarget* ref, Value* prop, ParamDimension** pdim); static ScripterExport BOOL set_max_prop_controller(ReferenceTarget* ref, Value* prop, MAXControl* c); ScripterExport virtual BOOL is_max_prop_animatable(Value* prop); ScripterExport Value* get_container_property(Value* prop, Value* cur_prop); ScripterExport Value* set_container_property(Value* prop, Value* val, Value* cur_prop); // coordsystem mappers, default is no mapping virtual void object_to_current_coordsys(Point3& p, int mode=0) { } virtual void object_from_current_coordsys(Point3& p, int mode=0) { } virtual void world_to_current_coordsys(Point3& p, int mode=0) { } virtual void world_from_current_coordsys(Point3& p, int mode=0) { } virtual void world_to_current_coordsys(Quat& q) { } virtual void world_from_current_coordsys(Quat& q) { } // map to & from controller value coordsys, eg, parent for nodes, modcontext for modifiers, etc. virtual void ctrl_to_current_coordsys(Point3& p, int mode=0) { } virtual void ctrl_from_current_coordsys(Point3& p, int mode=0) { } virtual void ctrl_to_current_coordsys(Quat& q) { } virtual void ctrl_from_current_coordsys(Quat& q) { } virtual void ctrl_to_current_coordsys(ScaleValue& s) { } virtual void ctrl_from_current_coordsys(ScaleValue& s) { } virtual Matrix3& local_tm() { return idTM; } virtual Matrix3 local_tm_inv() { return Inverse(local_tm()); } // recursive time functions #undef def_time_fn #define def_time_fn(_fn) ScripterExport Value* _fn##_vf(Value** arglist, int arg_count) #include "time_fns.h" // once for the generics #undef def_time_fn #define def_time_fn(_fn) ScripterExport Value* _fn(Animatable* anim, Value** arglist, int arg_count) #include "time_fns.h" // and once again for the factored animatable form // mesh & mesh-sub-object access setup ScripterExport virtual Mesh* set_up_mesh_access(int access, ReferenceTarget** owner = NULL); ScripterExport virtual Mesh* set_up_mesh_face_access(int index, int access, ReferenceTarget** owner = NULL); ScripterExport virtual Mesh* set_up_mesh_vertex_access(int index, int access, ReferenceTarget** owner = NULL); ScripterExport virtual MNMesh* set_up_mnmesh_access(int access, ReferenceTarget** owner = NULL); ScripterExport virtual MNMesh* set_up_mnmesh_face_access(int index, int access, ReferenceTarget** owner = NULL); ScripterExport virtual MNMesh* set_up_mnmesh_vertex_access(int index, int access, ReferenceTarget** owner = NULL); ScripterExport virtual BitArray get_vertsel(); ScripterExport virtual BitArray get_facesel(); ScripterExport virtual BitArray get_edgesel(); ScripterExport virtual void set_vertsel(BitArray &sel); ScripterExport virtual void set_facesel(BitArray &sel); ScripterExport virtual void set_edgesel(BitArray &sel); ScripterExport virtual GenericNamedSelSetList& get_named_vertsel_set(); ScripterExport virtual GenericNamedSelSetList& get_named_facesel_set(); ScripterExport virtual GenericNamedSelSetList& get_named_edgesel_set(); virtual void update_sel() { NotifyDependents(FOREVER, PART_SELECT, REFMSG_CHANGE); } ScripterExport virtual bool isPolyObject(int access); ScripterExport virtual IMeshSelectData* set_up_IMeshSelectData_access(int access, ReferenceTarget** owner); #ifndef NO_PATCHES ScripterExport virtual bool isPatchObject(int access); ScripterExport virtual PatchObject* set_up_patch_access(int access, ReferenceTarget** owner = NULL); ScripterExport virtual PatchObject* set_up_patch_face_access(int index, int access, ReferenceTarget** owner = NULL); ScripterExport virtual PatchObject* set_up_patch_vertex_access(int index, int access, ReferenceTarget** owner = NULL); ScripterExport virtual IPatchSelectData* set_up_IPatchSelectData_access(int access, ReferenceTarget** owner); #endif // NO_PATCHES // R2.5 stuff def_property ( category ); def_prop_getter( classID ); def_prop_getter( superclassID ); def_generic ( get, "get" ); // <mw>[i] => subAnim[i] def_generic ( getSubAnim, "getSubAnim" ); // equivalent def_generic ( getSubAnimName, "getSubAnimName" ); def_generic ( getSubAnimNames, "getSubAnimNames" ); def_generic ( getAppData, "getAppData"); def_generic ( setAppData, "setAppData"); def_generic ( deleteAppData, "deleteAppData"); def_generic ( clearAllAppData, "clearAllAppData"); def_generic ( addPluginRollouts, "addPluginRollouts"); ReferenceTarget* to_reftarg() { return get_max_object(); } void to_fpvalue(FPValue& v) { v.r = get_max_object(); v.type = TYPE_REFTARG; } // scene I/O ScripterExport IOResult Save(ISave* isave); static ScripterExport Value* Load(ILoad* iload, USHORT chunkID, ValueLoader* vload); // FPInterface access using ReferenceTarget::GetInterface; ScripterExport BaseInterface* GetInterface(Interface_ID id); }; // coordsys mappers defines.. #define NO_TRANSLATE 0x0001 #define NO_SCALE 0x0002 #define ctrl_to_current_coordsys_rotate(p) ctrl_to_current_coordsys(p, NO_TRANSLATE + NO_SCALE) #define ctrl_from_current_coordsys_rotate(p) ctrl_from_current_coordsys(p, NO_TRANSLATE + NO_SCALE) #define object_to_current_coordsys_rotate(p) object_to_current_coordsys(p, NO_TRANSLATE + NO_SCALE) #define object_from_current_coordsys_rotate(p) object_from_current_coordsys(p, NO_TRANSLATE + NO_SCALE) #define world_to_current_coordsys_rotate(p) world_to_current_coordsys(p, NO_TRANSLATE + NO_SCALE) #define world_from_current_coordsys_rotate(p) world_from_current_coordsys(p, NO_TRANSLATE + NO_SCALE) #define object_to_current_coordsys_scaleRotate(p) object_to_current_coordsys(p, NO_TRANSLATE) #define object_from_current_coordsys_scaleRotate(p) object_from_current_coordsys(p, NO_TRANSLATE) /* ---------------------- MAXClass ----------------------- */ /* this is the class that provides a runtime representation for * the classes of MAX objects. It is essentially the MAXScript * equivalent of the ClassDesc instance with extra metadata * about creation parameters, ec. */ typedef struct // parameter descriptor struct { Value* name; // parameter name MCHAR desc_type; // descriptor type... paramblock/fn/etc. MCHAR flags; union { struct // paramblock entry descriptor { int parm_id; }; struct // fn entry descriptor { max_getter_cf getter; max_setter_cf setter; }; struct // subanim entry descriptor { int subanim_num; }; struct // paramblockn - paramblock at given refno { int refno; int pbn_id; }; }; ParamType type; // common type code & initval union { float fval; int ival; BOOL bval; INT_PTR pval; // WIN64 Cleanup: Shuler -Need a pointer sized type (see TYPE_STRING) struct {float x, y, z, w;}; struct {float r, g, b, a;}; struct {float h, s, v;}; struct {int btn_min, btn_max, btn_val;}; } init_val; } parm_desc; #define PD_NO_INIT 0x01 // flags this property as reqiring no init #define PD_LOCAL_DUP 0x02 // this is a duplicate local translation #define PD_HAS_LOCAL_DUPS 0x04 // this has duplicate local translations #define PD_SHOWN 0x08 // temp flag to mark already shown props in showProps() class MAXClass; class MAXSuperClass; typedef struct // entries in the superclass table { SClass_ID key; MAXSuperClass* mx_superclass; } superclass_table; typedef Value* (*maker_fn)(MAXClass* cls, ReferenceTarget* obj, Value** arglist, int count); visible_class_debug_ok (MAXSuperClass) class MAXSuperClass : public Value { public: Value* name; SClass_ID sclass_id; Value* superclass; maker_fn maker; short n_parms; short flags; parm_desc* parms; // LAM 4/1/00 - exporting the following... ScripterExport MAXSuperClass(MCHAR* cname, SClass_ID sid, Value* superClass, maker_fn maker, ...); ScripterExport ~MAXSuperClass(); void complete_init(); static superclass_table* superclasses; // lookup table of all superclasses by SClass_ID static short n_superclasses; static BOOL superclass_table_dirty; static MAXSuperClass* lookup_superclass(SClass_ID sid); Value* classOf_vf(Value** arg_list, int count); Value* superClassOf_vf(Value** arg_list, int count); Value* isKindOf_vf(Value** arg_list, int count); // BOOL is_kind_of(ValueMetaClass* c) { return ((c == class_tag(MAXWrapper)) ? 1 : Value::is_kind_of(c)); } // LAM: 2/23/01 BOOL is_kind_of(ValueMetaClass* c) { return ((c == class_tag(MAXSuperClass)) ? 1 : Value::is_kind_of(c)); } # define is_maxsuperclass(v) ((v)->tag == class_tag(MAXSuperClass)) void collect() { delete this; } void gc_trace(); ScripterExport void sprin1(CharStream* s); void export_to_scripter(); // LAM 6/29/00 - added the following... ScripterExport short getNumSuperclasses (); ScripterExport MAXSuperClass* getSuperclass (int index); // LAM 4/1/00 - exporting the following... ScripterExport void apply_keyword_parms(ReferenceTarget* obj, Value** key_arg_list, int count); def_generic (get_props, "getPropNames"); def_generic (show_interfaces, "showInterfaces"); // LAM - 6/29/00 def_generic (get_interfaces, "getInterfaces"); def_generic (get_interface, "getInterface"); def_property( categories ); // LAM 4/22/00 - added the following... def_property( classes ); }; // The following function has been added // in 3ds max 4.3. If your plugin utilizes this new // mechanism, be sure that your clients are aware that they // must run your plugin with 3ds max version 4.3 or higher. extern ScripterExport MAXSuperClass* lookup_MAXSuperClass (SClass_ID scid); // End of 3ds max 4.3 Extension #define SC_SUPERCLASS_INITED 0x0001 #define SC_NON_REFTARG 0x0002 typedef struct { Class_ID cid; SClass_ID scid; } class_key; typedef struct // entries in the class table { class_key key; MAXClass* mx_class; } class_table; enum metadata_flags { md_use_getref = 0x0001, /* class flags */ md_use_getref0 = 0x0002, md_use_getref1 = 0x0004, md_no_create = 0x0008, md_no_access = 0x0010, md_direct_index = 0x0020, md_new_plugin = 0x0040, md_auto_parms = 0x0080, md_name_clash = 0x0100, md_initialized = 0x0200, }; enum metadata_flag { // end = 0, /* metadata vararg tags */ getters = 1, setters, accessors, path_getters, path_setters, path_accessors, fns, paramblock, subanims, paramblockn, subanimparamblock }; enum { TYPE_POINT3_ANGLE = TYPE_USER + 128, /* MAXScript special paramblock types... */ TYPE_POINT3_PCNT, }; visible_class_debug_ok (MAXClass) class MAXClass : public Value { public: Value* name; Class_ID class_id; SClass_ID sclass_id; ClassDesc* cd; ClassDesc2* cd2; // for now, pointer to ClassDesc2 if this class is PB2-based short md_flags; int n_parms; parm_desc* parms; MAXSuperClass* superclass; short paramblock_ref_no; Value* category; HashTable* interfaces; // plugin's FnPub published functions static class_table* classes; // lookup table of all classes by Class_ID static short n_classes; static BOOL class_table_dirty; static ScripterExport MAXClass* lookup_class(Class_ID* cid, SClass_ID scid, bool make_new_if_missing = true); MAXClass() { } ScripterExport MAXClass(MCHAR* cname, Class_ID cid, SClass_ID sid, MAXSuperClass* sclass, short cflags, ...); ScripterExport ~MAXClass(); ClassDesc* complete_init(); static void setup(); Value* classOf_vf(Value** arg_list, int count); Value* superClassOf_vf(Value** arg_list, int count); Value* isKindOf_vf(Value** arg_list, int count); // BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXWrapper)) ? 1 : Value::is_kind_of(c); } // LAM: 2/23/01 BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXClass)) ? 1 : Value::is_kind_of(c); } # define is_maxclass(v) ((v)->tag == class_tag(MAXClass)) void collect() { delete this; } void gc_trace(); ScripterExport void sprin1(CharStream* s); void export_to_scripter(); ScripterExport Value* apply(Value** arglist, int count, CallContext* cc=NULL); // object creation by applying class object static ScripterExport Value* make_wrapper_for(ReferenceTarget* ref); static ScripterExport Value* make_node_for(ReferenceTarget* ref); parm_desc* get_parm_desc(ReferenceTarget* ref, Value* key); BOOL build_parm_descs(ReferenceTarget* ref); // LAM 4/1/00 - exporting the following... ScripterExport void apply_keyword_parms(ReferenceTarget* ref, Value** key_arg_list, int count); ScripterExport void initialize_object(ReferenceTarget* ref); Value* get_max_property(ReferenceTarget* ref, parm_desc* pd, TimeValue t, Interval& valid); void set_max_property(ReferenceTarget* ref, parm_desc* pd, TimeValue t, Value* val); // PB2-related ParamDef* get_parm_def(Value* prop, ParamBlockDesc2*& pbd, int& tabIndex, ReferenceTarget* ref = NULL); void set_max_property(ReferenceTarget* ref, ParamDef* pd, int tabIndex, ParamBlockDesc2* pbd, TimeValue t, Value* val); Value* get_max_property(ReferenceTarget* ref, ParamDef* pd, int tabIndex, ParamBlockDesc2* pbd, TimeValue t, Interval& valid); static Value* get_pb2_property(IParamBlock2* pb, ParamDef* pd, int tabIndex, TimeValue t, Interval& valid); static void set_pb2_property(IParamBlock2* pb, ParamDef* pd, int tabIndex, TimeValue t, Value* val); static ParamDef* get_parm_def(ClassDesc2* cd2, Value* prop, ParamBlockDesc2*& pbd, int& tabIndex, ReferenceTarget* ref = NULL); def_generic (get_props, "getPropNames"); def_generic (create_instance, "createInstance"); def_generic (show_interfaces, "showInterfaces"); // LAM - 6/29/00 def_generic (get_interfaces, "getInterfaces"); def_generic (get_interface, "getInterface"); Class_ID get_max_class_id() { return class_id; } def_property ( category ); def_prop_getter( classID ); def_prop_getter( superclassID ); // LAM 4/22/00 - added the following... def_property ( creatable ); void to_fpvalue(FPValue& v); Value* Category(); Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); }; /* MAX object makers... */ Value* make_max_node(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_object(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_light(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_camera(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_modifier(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_material(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_texturemap(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_mtlbase(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_system(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_helper(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_controller(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_atmospheric(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_effect(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); // RK: Added this Value* make_max_mpassCamEffect(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); // LAM: Added this Value* make_max_filter(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); // RK: Added this Value* make_max_shadow(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); // LE: Added this Value* make_max_reftarg(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* no_max_maker(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); Value* make_max_renderer(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); // LAM - 9/15/01 Value* make_max_custattrib(MAXClass* cls, ReferenceTarget* obj, Value** arg_list, int count); // NH - 02/21/02 // The following function has been added // in 3ds max 4.3. If your plugin utilizes this new // mechanism, be sure that your clients are aware that they // must run your plugin with 3ds max version 4.3 or higher. extern ScripterExport MAXClass* lookup_MAXClass (Class_ID* cid, SClass_ID scid, bool make_new_if_missing = false); // End of 3ds max 4.3 Extension /* ------------------ MAXWrapper instance cache -----------------*/ // MAXWrapper instance cache - it's critical we don't wind up generating a million // MAXWrappers with References to the same MAX-side object as this KILLS the collector // during the DeleteAllRefsFromMe() which seems to do a linear search through its refs // if object not found in cache, use FindMAXWrapperEnum (below) to search dependents // of the ReferenceTarget for a wrapper value #define MAXWRAPPER_CACHE_SIZE 2048 // must be power of 2 extern ScripterExport MAXWrapper* maxwrapper_cache[]; //#define MAXWRAPPER_CACHE_STATS // uncomment to get maxwrapper cache hit/miss stats #ifndef MAXWRAPPER_CACHE_STATS inline BOOL _maxwrapper_cache_get(LONG_PTR index_ptr, MAXWrapper*** pw) { // compute cache index - fold halfwords & fold to cache size, get cache entry int index = DL_abs((int)((PointerLoPart(index_ptr) ^ PointerHiPart(index_ptr)))) % MAXWRAPPER_CACHE_SIZE; *pw = &maxwrapper_cache[index]; // we match initially if entry contains a non-deleted MAXWrapper MAXWrapper* w = **pw; return (w && !w->ref_deleted); } // a macro for implementing MAXWrapper interning member functions #define maxwrapper_cache_get(_mw_class, _mw_ref, _mw_var, _ce_var) \ (_maxwrapper_cache_get((LONG_PTR)(_mw_ref) ^ (LONG_PTR)class_tag(_mw_class), (MAXWrapper***)&_ce_var) && \ (_mw_var = *_ce_var)->tag == class_tag(_mw_class)) #else static long _maxwrapper_cache_hit = 0; static long _maxwrapper_cache_miss = 0; static long _maxwrapper_cache_clash = 0; static BOOL _maxwrapper_cache_get(LONG_PTR index_ptr, MAXWrapper*** pw, ValueMetaClass* tag) { // compute cache index - fold halfwords & fold to cache size, get cache entry int index = DL_abs((UINT)((PointerLoPart(index_ptr) ^ PointerHiPart(index_ptr)))) % MAXWRAPPER_CACHE_SIZE; *pw = &maxwrapper_cache[index]; // we match initially if entry contains a non-deleted MAXWrapper MAXWrapper* w = **pw; BOOL res_h = w && !w->ref_deleted; BOOL res_nc = res_h && (w->tag == tag); if (res_h) { if (res_nc) _maxwrapper_cache_hit++; else _maxwrapper_cache_clash++; } else _maxwrapper_cache_miss++; return res_h; } #define maxwrapper_cache_get(_mw_class, _mw_ref, _mw_var, _ce_var) \ (_maxwrapper_cache_get((LONG_PTR)(_mw_ref) ^ (LONG_PTR)class_tag(_mw_class), (MAXWrapper***)&_ce_var, class_tag(_mw_class)) && \ (_mw_var = *_ce_var)->tag == class_tag(_mw_class)) #endif // We sometime combine a pointer to an object with another value and then send this to // maxwrapper_cache_get. This little inlined function takes care of the nitty-gritty // of Win64-correctness. inline LONG_PTR maxwrapper_genref(void* pObject, LONG_PTR index) { return(reinterpret_cast<LONG_PTR>(pObject) ^ index); } inline LONG_PTR maxwrapper_genref(void* pObject1, void* pObject2) { return(maxwrapper_genref(pObject1, reinterpret_cast<LONG_PTR>(pObject2))); } // Use the following in MAXWrapper-derived intern methods to determine if // a MXS value already wraps the ReferenceTarget, and return that value. // intern method should then that value. This guarantees a single MXS wrapper // value per ReferenceTarget // class FindMAXWrapperEnum : public DependentEnumProc { ValueMetaClass* mytag; // the type of MAXWrapper being created ReferenceTarget* myref; // the ReferenceTarget being searched void* arg; // 2nd argument passed to finalCheckProc bool (*finalCheckProc)(MAXWrapper*, void*); // if needed, a secondary callback proc for testing the ReferenceTarget // needed for things like MAXTVNode, which consist of both a ReferenceTarget and an index public: FindMAXWrapperEnum(ReferenceTarget* ref, ValueMetaClass* tag, bool (*finalCheckProc)(MAXWrapper*, void*) = NULL, void* arg = NULL) { mytag = tag; myref = ref; result = NULL; this->finalCheckProc = finalCheckProc; this->arg = arg; } int proc(ReferenceMaker* rm) { if (rm == myref) return DEP_ENUM_CONTINUE; if (rm->SuperClassID() == MAXSCRIPT_WRAPPER_CLASS_ID && ((MAXWrapper*)rm)->tag == mytag && rm->NumRefs() && rm->GetReference(0) == myref && (finalCheckProc == NULL || (*finalCheckProc)((MAXWrapper*)rm, arg)) ) { result = (MAXWrapper*)rm; return DEP_ENUM_HALT; } return DEP_ENUM_SKIP; // just look at direct dependents } Value* result; }; /* ------------------------ MAXNode class ------------------------ */ /* this class is the MAXScript wrapper for object hierarchy * INodes. */ // following will invalidate the node's rectangle in either the foreground or background // plane, depending on whether the node is in the foreground or not. Also sets that redraw // is needed. // The following function has been added // in 3ds max 4.2. If your plugin utilizes this new // mechanism, be sure that your clients are aware that they // must run your plugin with 3ds max version 4.2 or higher. extern ScripterExport void InvalidateNodeRect(INode*node, TimeValue t); // End of 3ds max 4.2 Extension visible_class (MAXNode) class MAXNode : public MAXWrapper { public: INode *node; ScripterExport MAXNode(INode* init_node); static ScripterExport Value* intern(INode* init_node); Value* classOf_vf(Value** arg_list, int count); Value* superClassOf_vf(Value** arg_list, int count); Value* isKindOf_vf(Value** arg_list, int count); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXNode)) ? 1 : MAXWrapper::is_kind_of(c); } # define is_node(v) ((v)->tag == class_tag(MAXNode)) ScripterExport void sprin1(CharStream* s); MCHAR* class_name(); ScripterExport ReferenceTarget* get_max_object(); Value* ConvertTo(INode* node, Class_ID ccid); /* include all the protocol declarations */ #include "defimpfn.h" # include "nodepro.h" def_generic( distance, "distance" ); // shortcut distance fn for nodes def_generic( eq, "="); def_generic( ne, "!="); def_generic( coerce, "coerce"); def_generic (get_interfaces, "getInterfaces"); def_generic (get_interface, "getInterface"); /* declare built-in property accessors */ def_property ( dir ); def_property ( target ); def_property ( mat ); def_property ( modifiers ); def_property ( name ); def_property ( max ); def_property ( min ); def_property ( center ); def_property ( transform ); def_property ( parent ); def_property ( children ); def_property ( pivot ); def_2_prop_path ( pivot, x ); def_2_prop_path ( pivot, y ); def_2_prop_path ( pivot, z ); def_property ( objectoffsetpos ); def_property ( objectoffsetrot ); def_property ( objectoffsetscale ); def_property ( objecttransform ); def_nested_prop ( angle ); def_nested_prop ( axis ); /* mesh props */ def_property ( numverts ); def_property ( numtverts ); def_property ( numfaces ); def_property ( numcpvverts ); def_property ( mesh ); /* LE added these */ def_property ( displacementMapping ); def_property ( subdivisionDisplacement ); def_property ( splitMesh ); /* end LE */ /* mesh sub-objects (implemented in MeshSub.cpp) */ def_property ( vertices ); def_property ( selectedVertices ); def_property ( faces ); def_property ( selectedFaces ); def_property ( edges ); def_property ( selectedEdges ); /* NURBS sub-objects (implemented in NurbsSub.cpp) */ def_property ( selectedCurveCVs ); def_property ( selectedCurves ); def_property ( selectedImports ); def_property ( selectedPoints ); def_property ( selectedSurfaces ); def_property ( selectedSurfCVs ); def_property ( curveCVs ); def_property ( curves ); def_property ( imports ); def_property ( surfaces ); def_property ( surfCVs ); def_property ( points ); /* spline shape props */ def_property ( numsplines ); /* general property & substructure access */ Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); Value* find_modifier(Object* obj, Value* prop); Value* get_property_via_metadata(Value* prop); Control* get_max_prop_controller(Value* prop, ParamDimension** pdim); BOOL set_max_prop_controller(Value* prop, MAXControl* c); /* children mappers */ ScripterExport Value* map(node_map& m); ScripterExport Value* map_path(PathName* path, node_map& m); ScripterExport Value* find_first(BOOL (*test_fn)(INode* node, int level, void* arg), void* test_arg); ScripterExport Value* get_path(PathName* path); INode* to_node() { check_for_deletion(); return node; } void to_fpvalue(FPValue& v) { v.n = node; v.type = TYPE_INODE; } // coordsystem mappers ScripterExport void object_to_current_coordsys(Point3& p, int mode=0); ScripterExport void object_from_current_coordsys(Point3& p, int mode=0); ScripterExport void world_to_current_coordsys(Point3& p, int mode=0); ScripterExport void world_from_current_coordsys(Point3& p, int mode=0); ScripterExport void world_to_current_coordsys(Quat& q); ScripterExport void world_from_current_coordsys(Quat& q); ScripterExport void world_to_current_coordsys(ScaleValue& s); ScripterExport void world_from_current_coordsys(ScaleValue& s); // standard transorm controller access Control* get_max_pos_controller(ParamDimension** pdim); Control* get_max_scale_controller(ParamDimension** pdim); Control* get_max_rotation_controller(ParamDimension** pdim); Control* get_max_tm_controller(ParamDimension** pdim); Control* get_max_controller(ParamDimension** pdim); BOOL set_max_pos_controller(MAXControl* c); BOOL set_max_scale_controller(MAXControl* c); BOOL set_max_rotation_controller(MAXControl* c); BOOL set_max_tm_controller(MAXControl* c); BOOL set_max_controller(MAXControl* c); void ctrl_to_current_coordsys(Point3& p, int mode=0); void ctrl_from_current_coordsys(Point3& p, int mode=0); void ctrl_to_current_coordsys(Quat& q); void ctrl_from_current_coordsys(Quat& q); void ctrl_to_current_coordsys(ScaleValue& s); void ctrl_from_current_coordsys(ScaleValue& s); // recursive time functions #undef def_time_fn #define def_time_fn(_fn) Value* _fn##_vf(Value** arglist, int arg_count) #include "time_fns.h" // mesh access setup Mesh* set_up_mesh_access(int access, ReferenceTarget** owner = NULL); Mesh* set_up_mesh_face_access(int index, int access, ReferenceTarget** owner = NULL); Mesh* set_up_mesh_vertex_access(int index, int access, ReferenceTarget** owner = NULL); MNMesh* set_up_mnmesh_access(int access, ReferenceTarget** owner = NULL); MNMesh* set_up_mnmesh_face_access(int index, int access, ReferenceTarget** owner = NULL); MNMesh* set_up_mnmesh_vertex_access(int index, int access, ReferenceTarget** owner = NULL); BitArray get_vertsel(); BitArray get_facesel(); BitArray get_edgesel(); void set_vertsel(BitArray &sel); void set_facesel(BitArray &sel); void set_edgesel(BitArray &sel); GenericNamedSelSetList& get_named_vertsel_set(); GenericNamedSelSetList& get_named_facesel_set(); GenericNamedSelSetList& get_named_edgesel_set(); void update_sel(); bool isPolyObject(int access); IMeshSelectData* set_up_IMeshSelectData_access(int access, ReferenceTarget** owner); // NURBS access setup Object* set_up_nurbs_access(NURBSSubObjectLevel level, BitArray& sel); Object* set_up_nurbs_access(NURBSSubObjectLevel level); // Patch Access #ifndef NO_PATCHES bool isPatchObject(int access); PatchObject* set_up_patch_access(int access, ReferenceTarget** owner = NULL); PatchObject* set_up_patch_face_access(int index, int access, ReferenceTarget** owner = NULL); PatchObject* set_up_patch_vertex_access(int index, int access, ReferenceTarget** owner = NULL); IPatchSelectData* set_up_IPatchSelectData_access(int access, ReferenceTarget** owner); #endif // NO_PATCHES }; #define INODE_CLASS_ID Class_ID(BASENODE_CLASS_ID, 0) /* INode class ID for MAXScript metadata table indexing */ #define INODE_SUPERCLASS_ID BASENODE_CLASS_ID /* ---------------------- MAXNodeChildrenArray ----------------------- */ visible_class (MAXNodeChildrenArray) class MAXNodeChildrenArray : public Value, public Collection { public: MAXNode* parent; /* parent node */ ENABLE_STACK_ALLOCATE(MAXNodeChildrenArray); ScripterExport MAXNodeChildrenArray(INode* parent); ScripterExport MAXNodeChildrenArray(MAXNode* parent); classof_methods (MAXNodeChildrenArray, Value); BOOL _is_collection() { return 1; } void collect() { delete this; } void gc_trace(); ScripterExport void sprin1(CharStream* s); // operations ScripterExport Value* map(node_map& m); #include "defimpfn.h" # include "arraypro.h" // built-in property accessors def_property ( count ); def_property ( center ); def_property ( min ); def_property ( max ); }; /* ---------------------- MAXObject ----------------------- */ // generic wrapper for MAX reftarg objects (as opposed to nodes); ie, things inside nodes, mod stacks, etc. visible_class (MAXObject) class MAXObject : public MAXWrapper { public: Object* obj; // the MAX-side object ScripterExport MAXObject(Object* o); static ScripterExport Value* intern(Object* o); // The following method has been added // in 3ds max 4.2. If your plugin utilizes this new // mechanism, be sure that your clients are aware that they // must run your plugin with 3ds max version 4.2 or higher. BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXObject)) ? 1 : MAXWrapper::is_kind_of(c); } // End of 3ds max 4.2 Extension void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name(); BOOL CanTransferReference(int i) { return FALSE; } // prevent mod applications from making us refer to a derived object def_property ( mesh ); Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); void to_fpvalue(FPValue& v) { v.obj = obj; v.type = TYPE_OBJECT; } def_visible_generic ( updateXRef, "updateXRef"); }; /* ---------------------- MAXPB2ArrayParam ----------------------- */ // a virtual array wrapper for ParamBlock2 Tab<> array parameters // allows indexed access to Tab<> paramaters held in ParamBlock2's visible_class (MAXPB2ArrayParam) class MAXPB2ArrayParam : public MAXWrapper, public Collection { public: IParamBlock2* pblock; // owning paramblock ParamDef* pdef; // Tab<> parameter def MAXPB2ArrayParam(IParamBlock2* pb, ParamDef* pd); static ScripterExport Value* intern(IParamBlock2* pb, ParamDef* pd); classof_methods (MAXPB2ArrayParam, MAXWrapper); // BOOL _is_collection() { return 1; } # define is_tab_param(v) ((v)->tag == class_tag(MAXPB2ArrayParam)) void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("Array Parameter"); } // operations ScripterExport Value* map(node_map& m); #include "defimpfn.h" # include "arraypro.h" def_generic( coerce, "coerce"); ScripterExport Value* insertItem(Value** arg_list, int count); // called by insertItem_cf // built-in property accessors def_property ( count ); // nested props on indexed elements (notably <param>[i].controller) ScripterExport Value* get_container_property(Value* prop, Value* cur_prop); ScripterExport Value* set_container_property(Value* prop, Value* val, Value* cur_prop); // NULL get/showprops Value* show_props_vf(Value** arg_list, int count) { return &false_value; } Value* get_props_vf(Value** arg_list, int count) { return &undefined; } }; /* ---------------------- MAXModifier ----------------------- */ /* generic wrapper for MAX modifiers. */ visible_class (MAXModifier) class MAXModifier : public MAXWrapper { public: Modifier* mod; // the MAX-side modifier ScripterExport MAXModifier(Modifier* imod); static ScripterExport Value* intern(Modifier* imod); # define is_modifier(v) ((v)->tag == class_tag(MAXModifier)) BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXModifier)) ? 1 : MAXWrapper::is_kind_of(c); } void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name(); def_property ( name ); Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); Modifier* to_modifier() { check_for_deletion(); return mod; } void to_fpvalue(FPValue& v) { v.r = mod; v.type = TYPE_REFTARG; } }; visible_class (MAXModifierArray) class MAXModifierArray : public Value { public: MAXNode* node; /* the noed containing the modifiers */ ENABLE_STACK_ALLOCATE(MAXModifierArray); ScripterExport MAXModifierArray(INode* node); ScripterExport MAXModifierArray(MAXNode* node); classof_methods (MAXModifierArray, Value); void collect() { delete this; } void gc_trace(); BOOL _is_collection() { return 1; } ScripterExport void sprin1(CharStream* s); Modifier* get_modifier(int index); Modifier* find_modifier(MCHAR* name); MCHAR* class_name(); // operations ScripterExport Value* map(node_map& m); #include "defimpfn.h" # include "arraypro.h" // built-in property accessors def_property ( count ); }; /* ---------------------- MAXControl ----------------------- */ /* generic wrapper for MAX controls. */ //! RefMessage sent by Controls to tell MAXControl values that they are not new. Clears flag bit MAX_CTRL_NEW //! The hTarg argument is the Control being operated on #define REFMSG_MAXCONTROL_NOT_NEW REFMSG_USER + 0x4af551aa visible_class (MAXControl) class MAXControl : public MAXWrapper { public: Control* controller; /* the MAX-side controller */ ParamDimension* dim; /* dimension from originating animatable */ short flags; ScripterExport MAXControl(Control* icont, ParamDimension* idim); ScripterExport MAXControl(Control* icont, int flags = 0); static ScripterExport Value* intern(Control* icont, ParamDimension* idim); static ScripterExport Value* intern(Control* icont, int flags = 0); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXControl)) ? 1 : MAXWrapper::is_kind_of(c); } void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name(); # define is_controller(v) ((v)->tag == class_tag(MAXControl)) RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message); // the non-recursive controller ops... (recursive's are implemented as MAXWrapper methods) #include "defimpfn.h" use_generic ( copy, "copy"); def_visible_generic ( supportsTimeOperations, "supportsTimeOperations"); def_visible_generic ( getTimeRange, "getTimeRange"); def_visible_generic ( deleteKey, "deleteKey"); def_visible_generic ( selectKey, "selectKey"); def_visible_generic ( deselectKey, "deselectKey"); def_visible_generic ( isKeySelected, "isKeySelected"); def_visible_generic ( moveKey, "moveKey"); def_visible_generic ( numKeys, "numKeys"); def_visible_generic ( getKey, "getKey"); def_visible_generic ( getKeyTime, "getKeyTime"); def_visible_generic ( getKeyIndex, "getKeyIndex"); def_visible_generic ( numSelKeys, "numSelKeys"); def_visible_generic ( numEaseCurves, "numEaseCurves"); def_visible_generic ( applyEaseCurve, "applyEaseCurve"); def_visible_generic ( addMultiplierCurve, "addMultiplierCurve"); def_visible_generic ( deleteMultiplierCurve, "deleteMultiplierCurve"); def_visible_generic ( numMultiplierCurves, "numMultiplierCurves"); def_visible_generic ( getMultiplierValue, "getMultiplierValue"); def_visible_generic ( getBeforeORT, "getBeforeORT"); def_visible_generic ( getAfterORT, "getAfterORT"); // built-in property accessors def_property ( value ); def_property ( keys ); Control* to_controller() { check_for_deletion(); return controller; } void to_fpvalue(FPValue& v) { v.ctrl = controller; v.type = TYPE_CONTROL; } // trap reduceKeys() here to supply controllers dim def_visible_generic ( reduceKeys, "reduceKeys"); Value* get_property(Value** arg_list, int count); // LAM - 11/16/02 Value* set_property(Value** arg_list, int count); }; #define MAX_CTRL_NO_DIM 0x01 // indicates no explicit dimension yet assigned #define MAX_CTRL_NEW 0x02 // new controller, copy(old) when first assigned /* ---------------------- MAXSubAnim ----------------------- */ /* generic wrapper for MAX subanims. */ visible_class (MAXSubAnim) class MAXSubAnim : public MAXWrapper { public: ReferenceTarget* ref; /* parent object */ int subanim_num; /* the subanim index */ ScripterExport MAXSubAnim(ReferenceTarget* ref, int index); static ScripterExport Value* intern(ReferenceTarget* ref, int index); classof_methods(MAXSubAnim, MAXWrapper); void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("SubAnim"); } ScripterExport ReferenceTarget* get_max_object(); Value* _set_property(Value* prop, Value* val) { return val; } // NULL nested setter for subanims # define is_subAnim(v) ((v)->tag == class_tag(MAXSubAnim)) // standard transform controller access Control* get_max_pos_controller(ParamDimension** pdim); Control* get_max_scale_controller(ParamDimension** pdim); Control* get_max_rotation_controller(ParamDimension** pdim); Control* get_max_tm_controller(ParamDimension** pdim); Control* get_max_controller(ParamDimension** pdim); BOOL set_max_pos_controller(MAXControl* c); BOOL set_max_scale_controller(MAXControl* c); BOOL set_max_rotation_controller(MAXControl* c); BOOL set_max_tm_controller(MAXControl* c); BOOL set_max_controller(MAXControl* c); def_property( controller ); def_property( isAnimated ); def_property( keys ); def_property( value ); def_property( object ); def_property( name ); def_property( parent ); def_property( index ); // these converters all attempt to bounce off the subanim object Value* subanim_obj(); INode* to_node() { return subanim_obj() != this ? subanim_obj()->to_node() : Value::to_node(); } Mtl* to_mtl() { return subanim_obj() != this ? subanim_obj()->to_mtl() : Value::to_mtl(); } Texmap* to_texmap() { return subanim_obj() != this ? subanim_obj()->to_texmap() : Value::to_texmap(); } Modifier* to_modifier() { return subanim_obj() != this ? subanim_obj()->to_modifier() : Value::to_modifier(); } Control* to_controller() { return subanim_obj() != this ? subanim_obj()->to_controller() : Value::to_controller() ; } Atmospheric* to_atmospheric() { return subanim_obj() != this ? subanim_obj()->to_atmospheric() : Value::to_atmospheric(); } Effect* to_effect() { return subanim_obj() != this ? subanim_obj()->to_effect() : Value::to_effect(); } ITrackViewNode* to_trackviewnode() { return subanim_obj() != this ? subanim_obj()->to_trackviewnode() : Value::to_trackviewnode(); } void to_fpvalue(FPValue& v); }; /* ---------------------- MAXRefTarg ----------------------- */ // generic wrapper for MAX ReferenceTargets. visible_class (MAXRefTarg) class MAXRefTarg : public MAXWrapper { public: ReferenceTarget* ref; /* the object */ ScripterExport MAXRefTarg(ReferenceTarget* ref); static ScripterExport Value* intern(ReferenceTarget* ref); // classof_methods(MAXRefTarg, MAXWrapper); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXRefTarg)) ? 1 : MAXWrapper::is_kind_of(c); } void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("MAXRefTarg"); } }; /* ---------------------- MAXTVNode ----------------------- */ // generic wrapper for MAX TrackView Nodes. visible_class (MAXTVNode) class MAXTVNode : public MAXWrapper { public: ITrackViewNode* parent; // parent node int index; // the TVNode index ITrackViewNode* me; // LAM - 8/11/02 - defect 507276 - leaf class, not used outside MXS ScripterExport MAXTVNode(ITrackViewNode* parent, int index); static ScripterExport Value* intern(ITrackViewNode* parent, int index); classof_methods (MAXTVNode, MAXWrapper); void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("TrackViewNode"); } ReferenceTarget* get_max_object(); Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); Control* get_max_prop_controller(Value* prop, ParamDimension** pdim); BOOL set_max_prop_controller(Value* prop, MAXControl* c); Control* get_max_pos_controller(ParamDimension** pdim) { return get_max_prop_controller(n_position, pdim); } Control* get_max_scale_controller(ParamDimension** pdim) { return get_max_prop_controller(n_scale, pdim); } Control* get_max_rotation_controller(ParamDimension** pdim) { return get_max_prop_controller(n_rotation, pdim); } def_generic ( get_props, "getPropNames" ); def_property ( name ); RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message); ITrackViewNode* to_trackviewnode() { check_for_deletion(); return (parent == NULL) ? MAXScript_interface->GetTrackViewRootNode() : parent->GetNode(index); } }; /* ---------------------- TrackViewPick ----------------------- */ // The following class has been added // in 3ds max 4.2. If your plugin utilizes this new // mechanism, be sure that your clients are aware that they // must run your plugin with 3ds max version 4.2 or higher. visible_class (TrackViewPickValue) class TrackViewPickValue : public Value { public: TrackViewPick track; Value* client; Value* anim; int sub_num; MSTR name; ScripterExport TrackViewPickValue(TrackViewPick pick); classof_methods (TrackViewPickValue, Value); void collect() { delete this; } ScripterExport void sprin1(CharStream* s); void gc_trace(); # define is_trackviewpick(p) ((p)->tag == class_tag(TrackViewPickValue)) Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); }; // End of 3ds max 4.2 Extension // The following class has been added // in 3ds max 4.y. If your plugin utilizes this new // mechanism, be sure that your clients are aware that they // must run your plugin with 3ds max version 4.y or higher. visible_class (MAXTVUtility) class MAXTVUtility : public MAXWrapper { public: ITreeView* tv; // the trackview the utility was created in MSTR name; TrackViewUtility* tvUtil; ScripterExport MAXTVUtility(TrackViewUtility* util, ITreeView* tv); static ScripterExport Value* intern(TrackViewUtility* util, ITreeView* tv); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXTVUtility)) ? 1 : MAXWrapper::is_kind_of(c); } MCHAR* class_name(); void collect() { delete this; } ScripterExport void sprin1(CharStream* s); void gc_trace(); Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); def_generic ( get_props, "getPropNames" ); def_property ( name ); }; /* ---------------------- MAXMeshClass ----------------------- */ // the sole instance of the MAXMeshClass represents the Nodes made from the core tri-mesh object class TriObject. // reflecting its special status in MAX, it is defined by a separate class in MAXScript, // allowing access to all the things you want to get at when procedurally working // with meshes. visible_class (MAXMeshClass) class MAXMeshClass : public Value { public: MAXMeshClass(); classof_methods (MAXMeshClass, Value); void collect() { delete this; } ScripterExport void sprin1(CharStream* s); void export_to_scripter(); ScripterExport Value* apply(Value** arglist, int count, CallContext* cc=NULL); // object creation by applying class object Class_ID get_max_class_id() { return triObjectClassID; } }; /* ---------------------- MeshValue ----------------------- */ // A wrapper for the MAX SDK Mesh objects, typically used in Object plugins for creating scene // object meshes applyable_class (MeshValue) class MeshValue : public MAXWrapper { public: Object* obj; // MAX object if indirect ref to mesh (ref 0) Mesh* mesh; // direct mesh ref BOOL owned; // if direct ref owned by this value (& so s/b deleted on collect) ScripterExport MeshValue(Mesh* imesh, BOOL owned = FALSE); ScripterExport MeshValue(Object* obj); static ScripterExport Value* intern(Object* obj); ~MeshValue(); classof_methods (MeshValue, MAXWrapper); # define is_mesh(v) ((v)->tag == class_tag(MeshValue)) void collect() { delete this; } void sprin1(CharStream* s); MCHAR* class_name() { return _M("TriMesh"); } ReferenceTarget* get_max_object() { return obj; } void SetReference(int i, RefTargetHandle rtarg); RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message); BOOL CanTransferReference(int i) { return FALSE; } // prevent mod applications from making us refer to a derived object BOOL IsRealDependency(ReferenceTarget* target); void setup_mesh(int access = MESH_READ_ACCESS); // mesh protocol (same as for MAXNode) def_generic ( setvert, "setvert"); def_generic_debug_ok ( getvert, "getvert"); def_generic ( settvert, "settvert"); def_generic_debug_ok ( gettvert, "gettvert"); def_generic ( setvertcolor, "setvertcolor"); def_generic_debug_ok ( getvertcolor, "getvertcolor"); def_generic ( setnumverts, "setnumverts"); def_generic_debug_ok ( getnumverts, "getnumverts"); def_generic ( setnumtverts, "setnumtverts"); def_generic_debug_ok ( getnumtverts, "getnumtverts"); def_generic ( setnumcpvverts, "setnumcpvverts"); def_generic_debug_ok ( getnumcpvverts, "getnumcpvverts"); def_generic ( setnumfaces, "setnumfaces"); def_generic_debug_ok ( getnumfaces, "getnumfaces"); def_generic ( buildtvfaces, "buildTVFaces"); def_generic ( buildvcfaces, "buildVCFaces"); def_generic ( defaultvcfaces, "defaultVCFaces"); def_generic_debug_ok ( getnormal, "getnormal"); def_generic ( setnormal, "setnormal"); def_generic ( setface, "setface"); def_generic_debug_ok ( getface, "getface"); def_generic ( settvface, "setTVFace"); def_generic_debug_ok ( gettvface, "getTVFace"); def_generic ( setvcface, "setVCFace"); def_generic_debug_ok ( getvcface, "getVCFace"); def_generic_debug_ok ( getfacenormal, "getfacenormal"); def_generic ( setfacenormal, "setfacenormal"); def_generic ( setfacematid, "setfaceMatID"); def_generic_debug_ok ( getfacematid, "getfaceMatID"); def_generic ( setfacesmoothgroup, "setfaceSmoothGroup"); def_generic_debug_ok ( getfacesmoothgroup, "getfaceSmoothGroup"); def_generic ( setedgevis, "setedgevis"); def_generic_debug_ok ( getedgevis, "getedgevis"); def_generic ( detachVerts, "detachVerts"); def_generic ( detachFaces, "detachFaces"); def_generic ( extrudeface, "extrudeface"); def_generic ( deletevert, "deletevert"); def_generic ( deleteface, "deleteface"); def_generic ( collapseface, "collapseface"); def_generic ( setMesh, "setMesh"); def_generic ( update, "update"); def_generic_debug_ok ( getVertSelection, "getVertSelection"); def_generic ( setVertSelection, "setVertSelection"); def_generic_debug_ok ( getFaceSelection, "getFaceSelection"); def_generic ( setFaceSelection, "setFaceSelection"); def_generic_debug_ok ( getEdgeSelection, "getEdgeSelection"); def_generic ( setEdgeSelection, "setEdgeSelection"); def_generic ( copy, "copy"); def_generic ( delete, "delete"); use_generic ( plus, "+" ); // mesh boolean ops use_generic ( minus, "-" ); use_generic ( times, "*" ); use_generic ( move, "move" ); // transform verts use_generic ( rotate, "rotate" ); use_generic ( scale, "scale" ); use_generic ( transform, "transform" ); use_generic ( free, "free"); def_property( numverts ); def_property( numtverts ); def_property( numfaces ); def_property( numcpvverts ); def_property( mesh ); def_property( vertices ); def_property( selectedVertices ); def_property( faces ); def_property( selectedFaces ); def_property( edges ); def_property( selectedEdges ); Mesh* to_mesh() { setup_mesh(); return mesh; } void to_fpvalue(FPValue& v) { setup_mesh(); v.msh = mesh; v.type = TYPE_MESH; } Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); BitArray get_vertsel() { setup_mesh(); return mesh->vertSel; } BitArray get_facesel() { setup_mesh(); return mesh->faceSel; } BitArray get_edgesel() { setup_mesh(); return mesh->edgeSel; } void set_vertsel(BitArray &sel) { setup_mesh(MESH_WRITE_ACCESS); mesh->vertSel = sel; } void set_facesel(BitArray &sel) { setup_mesh(MESH_WRITE_ACCESS); mesh->faceSel = sel; } void set_edgesel(BitArray &sel) { setup_mesh(MESH_WRITE_ACCESS); mesh->edgeSel = sel; } Mesh* set_up_mesh_access(int access, ReferenceTarget** owner = NULL); Mesh* set_up_mesh_face_access(int index, int access, ReferenceTarget** owner = NULL); Mesh* set_up_mesh_vertex_access(int index, int access, ReferenceTarget** owner = NULL); }; /* ---------------------- MAXAtmospheric ----------------------- */ visible_class (MAXAtmospheric) class MAXAtmospheric : public MAXWrapper { public: Atmospheric* atmos; // the MAX-side Atmospheric ScripterExport MAXAtmospheric(Atmospheric* iatmos); static ScripterExport Value* intern(Atmospheric* iatmos); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXAtmospheric)) ? 1 : MAXWrapper::is_kind_of(c); } void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("Atmospheric"); } #include "defimpfn.h" #include "atmspro.h" def_property ( name ); def_prop_getter ( numGizmos ); Atmospheric* to_atmospheric() { check_for_deletion(); return atmos; } }; // RK: Start /* ---------------------- MAXEffect ----------------------- */ visible_class (MAXEffect) class MAXEffect : public MAXWrapper { public: Effect* effect; // the MAX-side Effect ScripterExport MAXEffect(Effect* ieffect); static ScripterExport Value* intern(Effect* ieffect); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXEffect)) ? 1 : MAXWrapper::is_kind_of(c); } void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("Effect"); } #include "defimpfn.h" #include "atmspro.h" def_property ( name ); def_prop_getter ( numGizmos ); Effect* to_effect() { check_for_deletion(); return effect; } }; // RK: End // LAM: Start /* ---------------------- MAXMultiPassCameraEffect ----------------------- */ visible_class (MAXMultiPassCameraEffect) class MAXMultiPassCameraEffect : public MAXWrapper { public: IMultiPassCameraEffect* effect; // the MAX-side Effect ScripterExport MAXMultiPassCameraEffect(IMultiPassCameraEffect* ieffect); static ScripterExport Value* intern(IMultiPassCameraEffect* ieffect); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXMultiPassCameraEffect)) ? 1 : MAXWrapper::is_kind_of(c); } void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("MultiPassCameraEffect"); } def_generic( iscompatible, "isCompatible"); IMultiPassCameraEffect* to_mpassCamEffect() { check_for_deletion(); return effect; } }; /* ---------------------- MAXShadowType ----------------------- */ // The following class has been added // in 3ds max 4.2. If your plugin utilizes this new // mechanism, be sure that your clients are aware that they // must run your plugin with 3ds max version 4.2 or higher. visible_class (MAXShadowType) class MAXShadowType : public MAXWrapper { public: ShadowType* shadow; // the MAX-side Effect ScripterExport MAXShadowType(ShadowType* ishadow); static ScripterExport Value* intern(ShadowType* ishadow); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXShadowType)) ? 1 : MAXWrapper::is_kind_of(c); } void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("MAXShadowType"); } ShadowType* to_shadowtype() { check_for_deletion(); return shadow; } }; // End of 3ds max 4.2 Extension // LAM: End // LAM - 9/15/01 /* ---------------------- MAXRenderer ----------------------- */ // The following class has been added // in 3ds max 4.y. If your plugin utilizes this new // mechanism, be sure that your clients are aware that they // must run your plugin with 3ds max version 4.y or higher. visible_class (MAXRenderer) class MAXRenderer : public MAXWrapper { public: Renderer* renderer; // the MAX-side Renderer ScripterExport MAXRenderer(Renderer* irenderer); static ScripterExport Value* intern(Renderer* irenderer); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXRenderer)) ? 1 : MAXWrapper::is_kind_of(c); } void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("MAXRenderer"); } Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); Renderer* to_renderer() { check_for_deletion(); return renderer; } }; // NH - 02/21/02 /* ---------------------- MAXCustAttrib ----------------------- */ // The following class has been added // in 3ds max 5. If your plugin utilizes this new // mechanism, be sure that your clients are aware that they // must run your plugin with 3ds max version 5 or higher. visible_class (MAXCustAttrib) class MAXCustAttrib : public MAXWrapper { public: CustAttrib* custattrib; ScripterExport MAXCustAttrib(CustAttrib* icustattrib); static ScripterExport Value* intern(CustAttrib* icustattrib); BOOL is_kind_of(ValueMetaClass* c) { return (c == class_tag(MAXCustAttrib)) ? 1 : MAXWrapper::is_kind_of(c); } void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("MAXCustAttrib"); } // Value* get_property(Value** arg_list, int count); // Value* set_property(Value** arg_list, int count); def_property ( name ); CustAttrib* to_custattrib() { check_for_deletion(); return custattrib; } }; visible_class (MAXCustAttribArray) class MAXCustAttribArray : public Value { public: MAXWrapper* ref; /* the ref containing the CAs */ ENABLE_STACK_ALLOCATE(MAXCustAttribArray); ScripterExport MAXCustAttribArray(MAXWrapper* ref); ScripterExport MAXCustAttribArray(ReferenceTarget* ref); ScripterExport MAXCustAttribArray(MAXRefTarg* ref); classof_methods (MAXCustAttribArray, Value); void collect() { delete this; } void gc_trace(); BOOL _is_collection() { return 1; } ScripterExport void sprin1(CharStream* s); CustAttrib* get_CustAttrib(int index); CustAttrib* find_CustAttrib(MCHAR* name); // operations ScripterExport Value* map(node_map& m); #include "defimpfn.h" # include "arraypro.h" // built-in property accessors def_property ( count ); }; /* ---------------------- ChangeHandler ----------------------- */ /* maintains notification references to a bunch of objects & a scitped function * to execute if one changes - runtime object for the 'on object changed ....' construct */ class ChangeHandler; visible_class (ChangeHandler) class CHTimeChangeCallback : public TimeChangeCallback { public: static BOOL registered; // if active static Tab<ChangeHandler*> handlers; // active handlers static BOOL notified; // set if any delayed-handle events have been notified public: void TimeChanged(TimeValue t); }; class CHRedrawViewsCallback : public RedrawViewsCallback { public: static BOOL registered; // if active static Tab<ChangeHandler*> handlers; // active handlers static BOOL notified; // set if any delayed-handle events have been notified public: void proc(Interface *ip); }; class ChangeHandler : public MAXWrapper { public: Value* fn; // function to run Value* attribute; // controlling change atribute Value* id; // optional handler ID for group deleting Value* handle_at; // delayed handling event code (#redraw, #timeChange) short parameter_count; // # formal params for fn short flags; Tab<ReferenceTarget*> targets; // table of targets who've notified delayed-handling handler static CHRedrawViewsCallback chrvcb; // redrawviews callback static CHTimeChangeCallback chtccb; // timechange callback static Tab<ChangeHandler*> handlers; // immediate-mode active handlers static BOOL delete_flagged; // signals a delayed delete was flagged ChangeHandler(Value* ifn, Value* attrib, Value* id, Value* handle_at); classof_methods (ChangeHandler, Value); void collect() { delete this; } void gc_trace(); MCHAR* class_name() { return _M("<ChangeHandler>"); } void handle_event(ReferenceTarget* target); void call_handler(ReferenceTarget* target); RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message); BOOL IsRealDependency(ReferenceTarget* target) { return FALSE; } }; #define CH_BROKEN 0x0001 // fn had a runtime error, disabled #define CH_BUSY 0x0002 // fn is running, ignore recursive events #define CH_NOTIFIED 0x0004 // change notified, handle at next specied handleAt: event #define CH_DELETE 0x0008 // attempted delete within the change handler, mark for delayed delete /* ------------------------ MAXRootNode class ------------------------ */ /* this class is the MAXScript wrapper for root nodes */ // The following class has been added // in 3ds max 4.2. If your plugin utilizes this new // mechanism, be sure that your clients are aware that they // must run your plugin with 3ds max version 4.2 or higher. visible_class (MAXRootNode) class MAXRootNode : public MAXWrapper { public: INode *node; ScripterExport MAXRootNode(INode* init_node); static ScripterExport Value* intern(INode* init_node); classof_methods (MAXRootNode, MAXWrapper); # define is_rootnode(v) ((v)->tag == class_tag(MAXRootNode)) void collect() { delete this; } ScripterExport void sprin1(CharStream* s); MCHAR* class_name() { return _M("<root>"); } /* include all the protocol declarations */ #include "defimpfn.h" def_generic( eq, "="); def_generic( ne, "!="); /* declare built-in property accessors */ def_property ( name ); def_property ( children ); INode* to_rootnode() { check_for_deletion(); return node; } }; // End of 3ds max 4.2 Extension /* ---------------------- Node mapping stuff ----------------------- */ /* node mapping argument structures */ struct node_map { value_vf vfn_ptr; // virtual fn to map value_cf cfn_ptr; // or, c fn to map (one or the other must be null) Value** arg_list; // args to pass on... int count; BOOL (*selector)(INode*, int, void*); // set selector fn void* sel_arg; // arg for the selector int get_index; // index if we are doing an indexed get int get_count; // local running traverse count during get Value** get_result_p; // ptr to result holder for indexed get Array* collection; // append map results here if non-null (used in for ... collect) short flags; // control flags }; #define NM_INVERT 0x0001 // invert map order, map parents last on the way out of the recursion #define NM_SELECT 0x0002 // applying a select, adjust clear flag #define NM_GET 0x0004 // doing a get, return get_index'th item #define NM_MXS_FN 0x0008 // cfn_ptr is actually a MAXScriptFunction*, apply directly typedef struct { BOOL (*tester)(INode*, int, void*); // node test fn void* test_arg; // tester arg BOOL (*selector)(INode*, int, void*); // set selector fn void* sel_arg; // arg for the selector } node_find; typedef struct { PathName* path; // path to the node BOOL (*selector)(INode*, int, void*); // set selector fn void* sel_arg; // arg for the selector } node_get; class ConvertToRestore : public RestoreObj { BOOL onlyForRedo; public: ConvertToRestore(BOOL onlyForRedo = FALSE) { this->onlyForRedo = onlyForRedo; } void Restore(int isUndo); void Redo(); MSTR Description() {return MSTR(_M("convertTo()"));} }; // G-bufer channel names & IDs typedef struct { MCHAR* name; int code; } gbuff_chan_code; extern gbuff_chan_code gbuff_chan_codes[]; // various externs extern bool for_all_nodes(INode* root, node_map* m); extern Value* find_first_node(INode* root, node_find* f); extern Value* get_node(INode* root, node_get* g); extern bool for_all_path_nodes(INode* root, PathName* path, node_map* m); extern BOOL all_objects_selector(INode* node, int level, void* selector_arg); extern int max_name_compare(MCHAR* max_name, MCHAR* other); extern Value* get_subanim_property(Animatable* anim, Value* prop); extern Value* get_subanim_property(Animatable* anim, int i); extern Value* set_subanim_property(Animatable* anim, Value* prop, Value* val); extern Value* set_subanim_property(Animatable* anim, int i, Value* val); extern BOOL set_subanim_controller(Animatable* anim, Value* prop, Control* newc, MAXControl* newcv); extern Control* find_subanim_controller(Animatable* anim, Value* prop, ParamDimension** dim); extern void deselect_if_motion_panel_open(); // class for suspending/resuming motion panel around controller assignment. // Added post-r5.0 - 8/22/02 // example usage: // if (theHold.Holding()) // theHold.Put(new AssignContRestore2(0)); // BOOL result = tmc->SetPositionController(c); // if (theHold.Holding()) // theHold.Put(new AssignContRestore2(1)); class AssignControllerRestore : public RestoreObj { BOOL parity; public: ScripterExport AssignControllerRestore(BOOL p); void Restore(int isUndo); void Redo(); MSTR Description(); }; class NodeTab : public INodeTab { public: INodeTab* AsINodeTabPtr() { return reinterpret_cast<INodeTab*>(this); } INodeTab& AsINodeTabRef() { return reinterpret_cast<INodeTab&>(*this); } }; // node tab collector for collection node mapping // arg0 is node candidate, arg1 is NodeTab* extern ScripterExport Value* collect_nodes(Value** arg_list, int count); // R7 - moved from MXSAgni visible_class (MAXSceneXRef) class MAXSceneXRef : public MAXWrapper { public: int index; MSTR name; MSTR full_name; INode *root; ULONG nodeHandle; ScripterExport MAXSceneXRef (INode* root, int i); static ScripterExport Value* intern(INode* root, int i); MCHAR* class_name() { return _M("XRefScene"); } classof_methods (MAXSceneXRef, MAXWrapper); void collect() { delete this; } ScripterExport void sprin1(CharStream* s); void check_for_xref_deletion(); /* operations */ #include "defimpfn.h" # include "xrefspro.h" /* built-in property accessors */ def_property( tree ); def_property( parent ); def_property( fileName ); def_property( autoUpdate ); def_property( boxDisp ); def_property( hidden ); def_property( disabled ); def_property( ignoreLights ); def_property( ignoreCameras ); def_property( ignoreShapes ); def_property( ignoreHelpers ); def_property( ignoreAnimation ); Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); }; #endif
[ [ [ 1, 1992 ] ] ]
96fa9aaa3efb801fea15c045e0e6e52bdb18023c
6ae8dac71f401abe5393a26e82f5a9747ad4df0e
/ofxCvMarkers/src/dtouch/binarytree.h
9aa165428b67c48692a564765e6d5c25106173d0
[]
no_license
connectthefuture/ofxPrimes
4565c2df0ded2b8315e08d7c98f4e29755fd19ca
8acd84cdcb04ed9cdb2953ed9b1d573b4bb6e4bc
refs/heads/master
2021-01-19T22:14:46.565208
2010-02-11T22:22:46
2010-02-11T22:22:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,729
h
/*************************************************************************** binarytree.h A template binary tree. The template implicitely rely on the existence of a function int cmp( const T& a, const T& b ) similar to strcmp. The tree is based on the C code published on http://www.macs.hw.ac.uk/~rjp/Coursewww/Cwww/tree.html ------------------- begin : Wed Nov 15 2007 copyright : (C) 2007 by Enrico Costanza @ EPFL LDM email : [email protected] ***************************************************************************/ /*************************************************************************** * * * 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 * * * ***************************************************************************/ #ifndef _EC_BINARYTREE #define _EC_BINARYTREE #include <iostream> using namespace std; /* char * seq2String( int * x, char * buf){ for(int i=0;i<=x[0];i++){ //cout << "x["<<i<<"]: " << x[i] << endl; char tmp[] = "99,"; sprintf(tmp,"%d,", x[i]); strcat(buf,tmp); } return buf; }//*/ int cmp( const int &a, const int &b ); int cmp( const int * a, const int * b ); template <class T> class TreeNode{ public: T _value; TreeNode<T> * _right, * _left; TreeNode( const T& item ){ _value = item; _right = NULL; _left = NULL; } ~TreeNode(){ if(_right!=NULL){ delete _right; _right=NULL; } if(_left!=NULL){ delete _left; _left=NULL; } } }; template <class T> class BinaryTree{ public: BinaryTree() { _root = NULL; } ~BinaryTree() { if(_root != NULL){ delete _root; _root=NULL;} } TreeNode<T> * _root; void apply( void(*f)(T) ){ if( _root != NULL ){ f(_root->_value); apply( f, _root->_left ); apply( f, _root->_right ); } return; } void apply( void(*f)(T), TreeNode<T> * node ){ if( node != NULL ){ f(node->_value); apply( f, node->_left ); apply( f, node->_right ); } return; } void insert( const T& item ) { TreeNode<T> * newNode = new TreeNode<T>( item ); if( _root == NULL ){ _root = newNode; return; } if( cmp( item, _root->_value ) < 0 ){ this->insert( newNode, &_root->_right ); }else{ this->insert( newNode, &_root->_left ); } } void insert( TreeNode<T> * newNode, TreeNode<T> ** node ) { if( *node == NULL ){ *node = newNode; return; } if( cmp( newNode->_value, (*node)->_value ) < 0 ){ this->insert( newNode, &((*node)->_right) ); }else{ this->insert( newNode, &((*node)->_left) ); } } bool contains( const T item ){ if( _root == NULL ){ return false; } int comparisonResult = cmp(item,_root->_value); if( comparisonResult == 0 ){ return true; } if( comparisonResult < 0 ){ if( _root->_right == NULL ){ return false; } return this->contains( item, _root->_right ); }else{ if( _root->_left == NULL ){ return false; } return this->contains( item, _root->_left ); } } bool contains( const T item, TreeNode<T> * node ){ int comparisonResult = cmp(item,node->_value); if( comparisonResult == 0 ){ return true; } if( comparisonResult < 0 ){ if( node->_right == NULL ){ return false; } return this->contains( item, node->_right ); }else{ if( node->_left == NULL ){ return false; } return this->contains( item, node->_left ); } } }; #endif //_EC_BINARYTREE
[ [ [ 1, 161 ] ] ]
b863cba4ec45b263198591c161312f01bc0e47c7
c0a577ec612a721b324bb615c08882852b433949
/englishplayer/EnTranscription/EnTranscription.cpp
c1bc978ba4d9dc4d3a3142c3cbbacc1151938ef3
[]
no_license
guojerry/cppxml
ca87ca2e3e62cbe2a132d376ca784f148561a4cc
a4f8b7439e37b6f1f421445694c5a735f8beda71
refs/heads/master
2021-01-10T10:57:40.195940
2010-04-21T13:25:29
2010-04-21T13:25:29
52,403,012
0
0
null
null
null
null
UTF-8
C++
false
false
4,443
cpp
// EnTranscription.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "EnTranscription.h" #include "MainFrm.h" #include "mdump.h" #include "EnTranscriptionDoc.h" #include "EnTranscriptionView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CEnTranscriptionApp BEGIN_MESSAGE_MAP(CEnTranscriptionApp, CWinApp) ON_COMMAND(ID_APP_ABOUT, &CEnTranscriptionApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen) // Standard print setup command END_MESSAGE_MAP() // CEnTranscriptionApp construction CEnTranscriptionApp::CEnTranscriptionApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CEnTranscriptionApp object CEnTranscriptionApp theApp; // CEnTranscriptionApp initialization BOOL CEnTranscriptionApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); CMiniDumper theDumper(_T("EnglishPlayer")); if (!AfxSocketInit()) { AfxMessageBox(IDP_SOCKETS_INIT_FAILED); return FALSE; } // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } 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 // 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(4); // 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(CEnTranscriptionDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CEnTranscriptionView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // Enable DDE Execute open EnableShellOpen(); RegisterShellFileTypes(TRUE); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. 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(); CString strCmdLine(m_lpCmdLine); if(!strCmdLine.IsEmpty()) { if(m_lpCmdLine[0] == '"') strCmdLine = strCmdLine.Mid(1, strCmdLine.GetLength() - 2); ((CMainFrame*)m_pMainWnd)->OpenMediaFile(strCmdLine); } else ((CMainFrame*)m_pMainWnd)->ShowTutorial(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); return TRUE; } // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // App command to run the dialog void CEnTranscriptionApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CEnTranscriptionApp message handlers
[ "oeichenwei@0e9f5f58-6d57-11de-950b-9fccee66d0d9" ]
[ [ [ 1, 168 ] ] ]
0d49eb26069cab6e3e2aa39ffb800c6cddd5aef5
477cd2cf408d0367d15beddfc53795dfbfbc0b53
/OSCPlugin/Include/Example.hpp
5cf6d73e451c4463c566a0da7faf63a505a815a0
[]
no_license
argl/eternal-track-cycle
14e8763f95ca483474f5a1453f87f217ee3b6c08
17aef4af7cdee62d50a6df7331b9fda6124831a8
refs/heads/master
2016-09-01T22:52:56.344931
2010-06-15T16:04:48
2010-06-15T16:04:48
606,870
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
6,172
hpp
//ÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜ //Ý Þ //Ý Module: Internals Example Header File Þ //Ý Þ //Ý Description: Declarations for the Internals Example Plugin Þ //Ý Þ //Ý Þ //Ý This source code module, and all information, data, and algorithms Þ //Ý associated with it, are part of CUBE technology (tm). Þ //Ý PROPRIETARY AND CONFIDENTIAL Þ //Ý Copyright (c) 1996-2007 Image Space Incorporated. All rights reserved. Þ //Ý Þ //Ý Þ //Ý Change history: Þ //Ý tag.2005.11.30: created Þ //Ý Þ //ßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßß #ifndef _INTERNALS_EXAMPLE_H #define _INTERNALS_EXAMPLE_H #include <iostream> #include <string.h> #include "OscOutboundPacketStream.h" #include "UdpSocket.h" #include "IpEndpointName.h" #define IP_MTU_SIZE 1536 #include "InternalsPlugin.hpp" // This is used for app to find out information about the plugin class InternalsPluginInfo : public PluginObjectInfo { public: // Constructor/destructor InternalsPluginInfo(); ~InternalsPluginInfo() {} // Derived from base class PluginObjectInfo virtual const char* GetName() const; virtual const char* GetFullName() const; virtual const char* GetDesc() const; virtual const unsigned GetType() const; virtual const char* GetSubType() const; virtual const unsigned GetVersion() const; virtual void* Create() const; private: char m_szFullName[128]; }; // This is used for the app to use the plugin for its intended purpose class ExampleInternalsPlugin : public InternalsPluginV3 { protected: const static char m_szName[]; const static char m_szSubType[]; const static unsigned m_uID; const static unsigned m_uVersion; public: // Constructor/destructor ExampleInternalsPlugin() {} ~ExampleInternalsPlugin() {} // Called from class InternalsPluginInfo to return specific information about plugin static const char * GetName() { return m_szName; } static const unsigned GetType() { return PO_INTERNALS; } static const char * GetSubType() { return m_szSubType; } static const unsigned GetVersion() { return m_uVersion; } // Derived from base class PluginObject void Destroy() { Shutdown(); } // poorly named ... doesn't destroy anything PluginObjectInfo * GetInfo(); unsigned GetPropertyCount() const { return 0; } PluginObjectProperty *GetProperty( const char * ) { return 0; } PluginObjectProperty *GetProperty( const unsigned ) { return 0; } // These are the functions derived from base class InternalsPlugin // that can be implemented. void Startup(); // game startup void Shutdown(); // game shutdown void EnterRealtime(); // entering realtime void ExitRealtime(); // exiting realtime void StartSession(); // session has started void EndSession(); // session has ended // GAME OUTPUT bool WantsTelemetryUpdates() { return( true ); } // CHANGE TO TRUE TO ENABLE TELEMETRY EXAMPLE! void UpdateTelemetry( const TelemInfoV2 &info ); bool WantsGraphicsUpdates() { return( false ); } // CHANGE TO TRUE TO ENABLE GRAPHICS EXAMPLE! void UpdateGraphics( const GraphicsInfoV2 &info ); // GAME INPUT bool HasHardwareInputs() { return( false ); } // CHANGE TO TRUE TO ENABLE HARDWARE EXAMPLE! void UpdateHardware( const float fDT ) { mET += fDT; } // update the hardware with the time between frames void EnableHardware() { mEnabled = true; } // message from game to enable hardware void DisableHardware() { mEnabled = false; } // message from game to disable hardware // See if the plugin wants to take over a hardware control. If the plugin takes over the // control, this method returns true and sets the value of the float pointed to by the // second arg. Otherwise, it returns false and leaves the float unmodified. bool CheckHWControl( const char * const controlName, float &fRetVal ); bool ForceFeedback( float &forceValue ); // SEE FUNCTION BODY TO ENABLE FORCE EXAMPLE // SCORING OUTPUT bool WantsScoringUpdates() { return( true ); } // CHANGE TO TRUE TO ENABLE SCORING EXAMPLE! void UpdateScoring( const ScoringInfoV2 &info ); // COMMENTARY INPUT bool RequestCommentary( CommentaryRequestInfo &info ); // SEE FUNCTION BODY TO ENABLE COMMENTARY EXAMPLE private: void WriteToAllExampleOutputFiles( const char * const openStr, const char * const msg ); float mET; // needed for the hardware example float m_tel_base_timer; float m_tel_damage_timer; float m_tel_space_timer; float m_tel_wheel_timer; float m_tel_user_input_timer; float m_scoring_global_timer; int m_scoring_driver_counter; int m_scoring_space_counter; bool mEnabled; // needed for the hardware example bool m_in_car; char m_buffer[IP_MTU_SIZE]; bool m_send_telemetry; bool m_send_scoring; osc::OutboundPacketStream* m_packetStream; UdpTransmitSocket* m_socket; }; #endif // _INTERNALS_EXAMPLE_H
[ [ [ 1, 149 ] ] ]
016e0695c1aaf93dcee97652dba37153e0e36a17
85d9531c984cd9ffc0c9fe8058eb1210855a2d01
/QxOrm/inl/QxDao/QxSqlQueryHelper_Exist.inl
2a1221a85685918874e357cb75d7deaf8421bd9f
[]
no_license
padenot/PlanningMaker
ac6ece1f60345f857eaee359a11ee6230bf62226
d8aaca0d8cdfb97266091a3ac78f104f8d13374b
refs/heads/master
2020-06-04T12:23:15.762584
2011-02-23T21:36:57
2011-02-23T21:36:57
1,125,341
0
1
null
null
null
null
UTF-8
C++
false
false
2,197
inl
/**************************************************************************** ** ** http://www.qxorm.com/ ** http://sourceforge.net/projects/qxorm/ ** Original file by Lionel Marty ** ** This file is part of the QxOrm library ** ** 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. ** ** GNU Lesser General Public License Usage ** This file must be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file 'license.lgpl.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact : ** [email protected] ** ****************************************************************************/ namespace qx { namespace dao { namespace detail { template <class T> struct QxSqlQueryHelper_Exist { static void sql(QString & sql, qx::IxSqlQueryBuilder & builder) { BOOST_STATIC_ASSERT(qx::trait::is_qx_registered<T>::value); qx::IxDataMember * pId = builder.getDataId(); qAssert(pId); QString table = builder.table(); sql = "SELECT "; if (pId) { sql += (table + "." + pId->getName() + " AS " + pId->getSqlAlias(& table)); } sql += " FROM " + table; sql += " WHERE " + pId->getSqlAlias(& table, true) + " = " + pId->getSqlPlaceHolder(); } static void resolveInput(T & t, QSqlQuery & query, qx::IxSqlQueryBuilder & builder) { BOOST_STATIC_ASSERT(qx::trait::is_qx_registered<T>::value); qx::IxDataMember * pId = builder.getDataId(); qAssert(pId); pId->setSqlPlaceHolder(query, (& t)); } static void resolveOutput(T & t, QSqlQuery & query, qx::IxSqlQueryBuilder & builder) { Q_UNUSED(t); Q_UNUSED(query); Q_UNUSED(builder); } }; } // namespace detail } // namespace dao } // namespace qx
[ [ [ 1, 59 ] ] ]
db6b2cf77d157cceb890455510e63bbbf66c068f
5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e
/Include/CompoundComponent.cpp
dfde4291113cbd6b8e20e6a2ebe31a8e4615005b
[ "BSD-3-Clause" ]
permissive
gui-works/ui
3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b
023faf07ff7f11aa7d35c7849b669d18f8911cc6
refs/heads/master
2020-07-18T00:46:37.172575
2009-11-18T22:05:25
2009-11-18T22:05:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,608
cpp
/* * Copyright (c) 2003-2006, Bram Stein * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "./CompoundComponent.h" namespace ui { }
[ "bs@bram.(none)" ]
[ [ [ 1, 33 ] ] ]
b360e62c781978d0ed64580ff37fa50a9caf74f4
447ee1dcff6b50e2993912eaa18ec0673ea68544
/Tutorial1/src/io/intf/File.h
3d7bfa7db099a7eae37fa72a3c5bc6d04bb0dd52
[]
no_license
pizibing/skeleton-animation
69f5e53c8b1cb65609cfca1ff5ca4049a30e6bdf
16602f5754c33ff604d2fe1690daba7eac540225
refs/heads/master
2020-04-17T12:30:47.872799
2009-06-23T21:04:13
2009-06-23T21:04:13
33,969,359
0
0
null
null
null
null
UTF-8
C++
false
false
1,670
h
#ifndef FILE_H_ #define FILE_H_ #include <cstdio> /** * Clasa abstracta pura ce reprezinta * un fisier accesibil engine-ului pe un sistem de fisiere oarecare. * Citirea/scrierea se face in stilul lucrului FILE*(fopen, fread...) * Fisierele sunt automat inchise sau explicit */ class File { public: /** * Deschide un fisier, si il pune in obiectul curent; * Aceasi conventie pt. mode ca la fopen("rb"...) */ virtual bool Open(const char* filename, const char* mode = "rb") = 0; /** * Verfica daca a fost deschis fisierul; mai ales daca obiectul a * fost construit cu constructorul fara parametri */ virtual bool IsOpen() = 0; /** * Citeste din fisier si pune in buffer */ virtual size_t Read(void* data, size_t size, size_t count) = 0; /** * Scrie in fisier; la fel ca fwrite */ virtual size_t Write(const void* data, size_t size, size_t count) = 0; /** * Pozitioneaza cursor in fisier, la fel ca si fseek; * Foloseste aceasi conventie pt. origin(SEEK_SET...) */ virtual int Seek(long offset, int origin = SEEK_SET) = 0; /** * Intoarce pozitia curenta in fisier */ virtual long Tell() = 0; /** * Dimensiunea in octeti a fisierului */ virtual long GetSize() = 0; /** * Inchide fisierul */ virtual void Close() = 0; /** * Unele tipuri de fisiere contin un stream, * pentru acestea returneaza true */ virtual bool IsStream() = 0; /** * Pentru fisierele care au stream, returneaza stream-ul */ virtual void* GetInternalData() = 0; /** * Pentru a folosi polimorfismul destructorilor */ virtual ~File(){}; }; #endif /*FILE_H_*/
[ "adrian.airinei@2bd093b0-4162-11de-b6cc-f32266f7ba4a" ]
[ [ [ 1, 75 ] ] ]
2c1084520c9b16f8f4fda9ff6a6fce21ef127020
28b0332fabba904ac0668630f185e0ecd292d2a1
/FuzzyBuilder/src/Unit1.cpp
e464f215bcf9d48095049dadacdeb13a7e9f217b
[]
no_license
iplayfast/crylib
57a507ba996d1abe020f93ea4a58f47f62b31434
dbd435e14abc508c31d1f2f041f8254620e24dc0
refs/heads/master
2016-09-05T10:33:02.861605
2009-04-19T05:17:55
2009-04-19T05:17:55
35,353,897
0
0
null
null
null
null
UTF-8
C++
false
false
24,635
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" #include "Unit2.h" #include "Unit3.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; #include "TFuzzy.h" FuzzyList *gf=0; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { Head = 0; Connections = 0; } //--------------------------------------------------------------------------- void __fastcall TForm1::Refresh(TObject *Sender) { AnsiString In,Out; int MaxLength; if (Head==0) { Fuzzy1->Visible = false; return; } else Fuzzy1->Visible = true; ImageInfo *l = Head; TRect r; r.Left = 1; r.Top = 1; r.Right = Image1->Width; r.Bottom = Image1->Height; // Image1->Canvas->FillRect(r); Image1->Invalidate(); if (ComboBox1->Items->Count==0) return; ImageInfo *ii = (ImageInfo *)ComboBox1->Items->Objects[ComboBox1->ItemIndex]; vl->Visible = false; Output1->Visible = false; Label1->Visible = false; Button1->Visible = false; Button2->Visible = false; Button3->Visible = false; switch(ii->Type) { case ImageInfo::Fuzzy: { FuzzyList *f = (FuzzyList *)ii; vl->Strings->Clear(); for(int i=0;i<f->Fuzzy.Length();i++) { In = f->Fuzzy.IndexAt(i); Out = f->Fuzzy.ValueAt(i); vl->InsertRow(In,Out,true); } vl->Visible = true; Output1->Visible = true; Label1->Visible = true; Button1->Visible = true; Button2->Visible = true; Button3->Visible = true; } break; case ImageInfo::Not: Label2->Caption = "Maximum Value"; break; } return; FuzzyList *f; AnsiString a; if (f->Fuzzy.Length()<MyFuzzy[1].Length()) MaxLength = MyFuzzy[1].Length(); else MaxLength = f->Fuzzy.Length(); grid->RowCount = 1+MaxLength; int Complexity = 0; if (TwoFuzzyLogics1->Checked) Complexity =1; if (FuzzyLogicOperations1->Checked) Complexity = 2; switch(Complexity) { case 0: { grid->ColCount = 3; } break; case 1: { grid->ColCount = 5; } break; case 2: { grid->ColCount = 5; } break; } grid->Cells[1][0] = "Fuzzy 1 Input"; grid->Cells[2][0] = "Fuzzy 1 Output"; if (!OneFuzzyLogic1->Checked) { grid->Cells[3][0] = "Fuzzy 2 Input"; grid->Cells[4][0] = "Fuzzy 2 Output"; } for(int i=0;i<MaxLength;i++) { if (f->Fuzzy.Length()>i) { a = f->Fuzzy.IndexAt(i); grid->Cells[1][i+1] = a; a = f->Fuzzy.ValueAt(i); grid->Cells[2][i+1] = a; } if (!OneFuzzyLogic1->Checked) { if (MyFuzzy[1].Length()>i) { a = MyFuzzy[1].IndexAt(i); grid->Cells[3][i+1] = a; a = MyFuzzy[1].ValueAt(i); grid->Cells[4][i+1] = a; } } } TChartSeries *s = (*Chart1->SeriesList)[0]; s->Clear(); for(int i=0;i<f->Fuzzy.Length();i++) { s->AddXY(f->Fuzzy.IndexAt(i),f->Fuzzy.ValueAt(i)); } s = (*Chart1->SeriesList)[1]; s->Clear(); if (!OneFuzzyLogic1->Checked) { for(int i=0;i<MyFuzzy[1].Length();i++) { s->AddXY(MyFuzzy[1].IndexAt(i),MyFuzzy[1].ValueAt(i)); } } s = (*Chart1->SeriesList)[2]; s->Clear(); /* if (FuzzyLogicOperations1->Checked) { for(int i=0;i<LogicIn->Max;i+=UpDown5->Position) { VALUE_TYPE x,y; x = i; y = LogicFunctionResult(x); s->AddXY(x,y); } } */ } //--------------------------------------------------------------------------- void __fastcall TForm1::Button2Click(TObject *Sender) { VALUE_TYPE x,y; FuzzyList *f = (FuzzyList *)ComboBox1->Items->Objects[ComboBox1->ItemIndex]; x = Input1->Position; y = Output1->Position; f->Fuzzy.TFuzzyAddPoint(x,y); Refresh(Sender); } void TForm1::UpdateLogic() { ImageInfo *l = Head; AnsiString a; // Reset values /* while(l) { if (l->Type!=ImageInfo::In) { l->DoneIn1 = l->DoneIn2 = false; l->SetOutValue(0); } l = l->Next; }*/ Connection *C = Connections; while(C) { C->Done = false; if (C->From->Type==ImageInfo::In) { if (C->ToIn==1) { C->To->SetIn1Value(C->From->In1V); C->To->DoneIn1 = true; if (C->To->In1Y==C->To->In2Y) // only one input C->To->DoneIn2 = true; } else { C->To->SetIn2Value(C->From->In1V); C->To->DoneIn2 = true; } C->To->Calculate(); C->Done = true; } C = C->Next; } bool Done = false; int InfLoopWatch=200; // bigger then anything anyone would do while(!Done) { Done = true; C = Connections; while(C) { if (!C->Done) // C In is not from an input (which is already done) { if (C->From->DoneIn1 && C->From->DoneIn2) { C->From->Calculate(); if (C->ToIn==1) { C->To->SetIn1Value(C->From->OutV); C->To->DoneIn1 = true; if (C->To->In1Y==C->To->In2Y) // only one input C->To->DoneIn2 = true; } else { C->To->SetIn2Value(C->From->OutV); C->To->DoneIn2 = true; } C->To->Calculate(); C->Done = true; } } else Done = false; C = C->Next; } InfLoopWatch--; if (InfLoopWatch==0) break; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Input1Change(TObject *Sender) { ImageInfo *ii = (ImageInfo *)ComboBox1->Items->Objects[ComboBox1->ItemIndex]; switch(ii->Type) { case ImageInfo::In: ii->SetIn1Value(Input1->Position); break; case ImageInfo::Not: { ii->SetIn2Value(Input1->Position); } break; case ImageInfo::Fuzzy: { FuzzyList *f = (FuzzyList *) ii; gf = f; AnsiString sender = Sender->ClassName(); Label2->Caption = AnsiString("Input ") + Input1->Position; if (Input1==Active) { Output1->Position = f->Fuzzy.Value(Input1->Position); f->SetIn1Value(Input1->Position); f->SetOutValue(Output1->Position); } } break; } UpdateLogic(); Image1->Invalidate(); } //--------------------------------------------------------------------------- void __fastcall TForm1::Output1Change(TObject *Sender) { Label1->Caption = AnsiString("Output ") + Output1->Position; } //--------------------------------------------------------------------------- void __fastcall TForm1::Input1Enter(TObject *Sender) { Active = Input1; } //--------------------------------------------------------------------------- void __fastcall TForm1::Output1Enter(TObject *Sender) { Active = Output1; } //--------------------------------------------------------------------------- void TForm1::GridClear() { for(int i=0;i<grid->ColCount;i++) { grid->Cells[1][i+1] = ""; grid->Cells[2][i+1] = ""; grid->Cells[3][i+1] = ""; grid->Cells[4][i+1] = ""; } } void __fastcall TForm1::Button3Click(TObject *Sender) { FuzzyList *f = (FuzzyList *)ComboBox1->Items->Objects[ComboBox1->ItemIndex]; f->Fuzzy.Clear(); GridClear(); Refresh(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::Input2Exit(TObject *Sender) { // Active = Output2; } //--------------------------------------------------------------------------- void __fastcall TForm1::Input2Change(TObject *Sender) { /* Label4->Caption = AnsiString("Input ") + Input2->Position; if (Input2==Active) Output2->Position = MyFuzzy[1].Value(Input2->Position); UpdateLogic(); */ } //--------------------------------------------------------------------------- void __fastcall TForm1::Button5Click(TObject *Sender) { /*VALUE_TYPE x,y; x = Input2->Position; y = Output2->Position; MyFuzzy[1].TFuzzyAddPoint(x,y); Refresh(Sender); */ } //--------------------------------------------------------------------------- void __fastcall TForm1::Button4Click(TObject *Sender) { MyFuzzy[1].Clear(); GridClear(); Refresh(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::Input1Exit(TObject *Sender) { Active = Output1; } //--------------------------------------------------------------------------- void __fastcall TForm1::Input2Enter(TObject *Sender) { //Active = Input2; } //--------------------------------------------------------------------------- void __fastcall TForm1::Output2Change(TObject *Sender) { // Label5->Caption = AnsiString("Output ") + Output2->Position; } //--------------------------------------------------------------------------- void __fastcall TForm1::LogicSelectionClick(TObject *Sender) { UpdateLogic(); } //--------------------------------------------------------------------------- void __fastcall TForm1::LogicInChange(TObject *Sender) { /* UpdateLogic(); AnsiString a = LogicIn->Position; LogicInText->Caption = a; */ } //--------------------------------------------------------------------------- void __fastcall TForm1::New1Click(TObject *Sender) { FuzzyList *f = (FuzzyList *)ComboBox1->Items->Objects[ComboBox1->ItemIndex]; f->Fuzzy.Clear(); MyFuzzy[1].Clear(); OneFuzzyLogic1Click(Sender); GridClear(); Refresh(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::Open1Click(TObject *Sender) { if (OpenTextFileDialog1->Execute()) { FILE *F = fopen(OpenTextFileDialog1->FileName.c_str(),"rt"); /* if (F) { int c; char ch1,ch2; char Buffer[200]; SaveTextFileDialog1->FileName = OpenTextFileDialog1->FileName; New1Click(Sender); OneFuzzyLogic1Click(Sender); fgets(Buffer,199,F); // intro (ignore) fgets(Buffer,199,F); // Fuzzy1 Name Fuzzy1Name->Text = Buffer+2; fgets(Buffer,199,F); // number of items sscanf(Buffer+2,"%d",&c); for(int i=0;i<c;i++) { VALUE_TYPE x,y; fgets(Buffer,199,F); sscanf(Buffer+2,"%f,%f",&x,&y); f->Fuzzy.TFuzzyAddPoint(x,y); } fgets(Buffer,199,F); // Fuzzy2 Name Fuzzy2Name->Text = Buffer; fgets(Buffer,199,F); // number of items for second fuzzy sscanf(Buffer+2,"%d",&c); for(int i=0;i<c;i++) { VALUE_TYPE x,y; fgets(Buffer,199,F); sscanf(Buffer+2,"%f,%f",&x,&y); MyFuzzy[1].TFuzzyAddPoint(x,y); FuzzyLogicOperations1Click(Sender); } fgets(Buffer,199,F); if ((Buffer[0]=='/') && (Buffer[1]=='/')) { int max; sscanf(Buffer+2,"%d",&max); UpDown1->Position = (max / 1000) * 1000; max %= 1000; UpDown2->Position = (max / 100) * 100; max %= 100; UpDown3->Position = (max / 10) * 10; max %= 10; UpDown4->Position = max; UpDown1Click(Sender, 0); } fclose(F); }*/ Refresh(Sender); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Save1Click(TObject *Sender) { if ((SaveTextFileDialog1->FileName!="") || (SaveTextFileDialog1->Execute())) { AnsiString a; a = SaveTextFileDialog1->FileName; if (a.Pos(".h")==0) a = a + ".h"; TFileStream *f = new TFileStream(a,fmCreate); a = "// The next lines are used by the fuzzy editor to save and load data\n"; f->Write(a.c_str(),a.Length()); a = "//"; // a += Fuzzy1Name->Text; a += "\n"; f->Write(a.c_str(),a.Length()); a = "//"; FuzzyList *fuzzy = (FuzzyList *) ComboBox1->Items->Objects[ComboBox1->ItemIndex]; a += fuzzy->Fuzzy.Count(); a += " \t\t// Fuzzy 1 number of data values\n"; f->Write(a.c_str(),a.Length()); for(int i=0;i<fuzzy->Fuzzy.Count();i++) { a = "//"; TFuzzyXY *v = fuzzy->Fuzzy.GetItem(i); a += v->x; a += ","; a += v->y; while(a.Length()<10) a += " "; a += " \t// data item "; a += (i+1); a += "\n"; f->Write(a.c_str(),a.Length()); } a = "//"; // a += Fuzzy1Name->Text; f->Write(a.c_str(),a.Length()); a = "//"; a += MyFuzzy[1].Count(); a += " \t\t// Fuzzy 2 number of data values\n"; f->Write(a.c_str(),a.Length()); for(int i=0;i<MyFuzzy[1].Count();i++) { a = "//"; TFuzzyXY *v = MyFuzzy[1].GetItem(i); a += v->x; a += ","; a += v->y; while(a.Length()<10) a += " "; a += " \t// data item "; a += (i+1); a += "\n"; f->Write(a.c_str(),a.Length()); } a = "//"; a += Input1->Max; a += " // Maximum allowed\n"; f->Write(a.c_str(),a.Length()); a = "\n\n//The next section is code which can be included to set the values of Fuzzy1 and Fuzzy2\n"; f->Write(a.c_str(),a.Length()); a = "\nextern TFuzzy Fuzzy1;\nextern TFuzzy Fuzzy2;\n\nvoid LoadFuzzies()\n{\n"; f->Write(a.c_str(),a.Length()); for(int i=0;i<fuzzy->Fuzzy.Count();i++) { TFuzzyXY *v = fuzzy->Fuzzy.GetItem(i); a = " TFuzzyAddPoint(Fuzzy1,"; a += v->x; a += ","; a += v->y; a += ");\n"; f->Write(a.c_str(),a.Length()); } for(int i=0;i<MyFuzzy[1].Count();i++) { TFuzzyXY *v = MyFuzzy[1].GetItem(i); a = " TFuzzyAddPoint(Fuzzy2,"; a += v->x; a += ","; a += v->y; a += ");\n"; f->Write(a.c_str(),a.Length()); } a = "}\n\n"; f->Write(a.c_str(),a.Length()); delete f; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { FuzzyList *f = (FuzzyList *) ComboBox1->Items->Objects[ComboBox1->ItemIndex]; f->Fuzzy.Optimize(1.0); Refresh(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::Button6Click(TObject *Sender) { MyFuzzy[1].Optimize(1.0); Refresh(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::SaveAs1Click(TObject *Sender) { SaveTextFileDialog1->FileName = ""; Save1Click(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::Exit1Click(TObject *Sender) { Close(); } //--------------------------------------------------------------------------- void __fastcall TForm1::RadioGroup1Click(TObject *Sender) { if (RadioGroup1->ItemIndex==0) Chart1->Visible = false; else Chart1->Visible = true; CheckBox3d->Visible = Chart1->Visible; UpDown5->Visible = CheckBox3d->Checked && Chart1->Visible; Refresh(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::CheckBox3dClick(TObject *Sender) { Chart1->View3D = CheckBox3d->Checked; UpDown5->Visible = CheckBox3d->Checked && Chart1->Visible; } //--------------------------------------------------------------------------- void __fastcall TForm1::UpDown5Click(TObject *Sender, TUDBtnType Button) { Refresh(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::OneFuzzyLogic1Click(TObject *Sender) { OneFuzzyLogic1->Checked = true; TwoFuzzyLogics1->Checked = false; FuzzyLogicOperations1->Checked = false; Refresh(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::TwoFuzzyLogics1Click(TObject *Sender) { OneFuzzyLogic1->Checked = false; TwoFuzzyLogics1->Checked = true; FuzzyLogicOperations1->Checked = false; Refresh(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::FuzzyLogicOperations1Click(TObject *Sender) { OneFuzzyLogic1->Checked = false; TwoFuzzyLogics1->Checked = false; FuzzyLogicOperations1->Checked = true; Refresh(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm1::Button7Click(TObject *Sender) { static int count=1; Form3->Name->Text = "Name" + IntToStr(count); count++; if (Form3->ShowModal()==mrOk) { ImageInfo *l = Head; while(l) { if (Form3->Name->Text==l->Name) { ShowMessage("Fuzzy Logic Block with that Name already created"); return; } l = l->Next; } int min,max; min = StrToInt(Form3->Min->Text); max = StrToInt(Form3->Max->Text); l = new FuzzyList(Form3->Name->Text,Form3->Description->Text,min,max); l->Next = Head; Head = l; UpdateComboBox(); static StartX = 10; static StartY = 100; Head->y = StartX; Head->x = StartY; StartX += 10; StartY += 10; Refresh(Sender); } } void TForm1::UpdateComboBox() { ImageInfo *l = Head; ComboBox1->Items->Clear(); while(l) { switch(l->Type) { case ImageInfo::Fuzzy: ComboBox1->Items->AddObject(l->Name,l); break; case ImageInfo::Not: { AnsiString a; a = "Not:"; a += l->Name; ComboBox1->Items->AddObject(a,l); } break; case ImageInfo::In: { AnsiString a; a = "In:"; a += l->Name; ComboBox1->Items->AddObject(a,l); } } l = l->Next; } ComboBox1->ItemIndex = 0; } //--------------------------------------------------------------------------- bool ImageInfo::Selected(int X,int Y) { return (x <=X && y<=Y && x+64>=X && y+64>=Y); } bool ImageInfo::MouseAtIn(int X,int Y) // returns true if at left side of symbol { return (x <=X && y<=Y && x+32>=X && y+64>=Y); } bool ImageInfo::MouseAtOut(int X,int Y) // returns true if at right side of symbol { return (x+32 <=X && y<=Y && x+64>=X && y+64>=Y); } bool ImageInfo::MouseAtIn1(int X,int Y) // returns true if at top left side of symbol { return (x <=X && y<=Y && x+32>=X && y+32>=Y); } bool ImageInfo::MouseAtIn2(int X,int Y) // returns true if at bottom left side of symbol { return (x <=X && y>=Y+32 && x+32>=X && y+64>=Y); } void __fastcall TForm1::Image11MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { ImageInfo *l = Head; if (DoubleClick) { DoubleClick = false; return; } if ((Button ==mbLeft) || From==0) while(l) { if (l->Selected(X,Y)) { if (From==0) { From = l; LastMouseX = X; LastMouseY = Y; Moving = (Button==mbRight); return; } else { if (!Moving) { int ConnectionPoint = 1; // default if (l->MouseAtIn2(X,Y)) ConnectionPoint = 2; if (l->MouseAtIn(X,Y)) { Connection *pc=0,*c = Connections; while(c) { if (c->From==From && c->To ==l) // connection already present, get rid of it. { if (pc==0) Connections = c->Next; else pc->Next = c->Next; delete c; From=0; Refresh(Sender); return; } pc = c; c = c->Next; } c = new Connection(From,l); c->ToIn = ConnectionPoint; c->Next = Connections; Connections = c; From = 0; } } } } l = l->Next; } if (From) { Image1->Canvas->Pen->Width = 1; Image1->Canvas->Pen->Mode = pmNotXor; Image1->Canvas->MoveTo(From->x+64,From->y+32); Image1->Canvas->LineTo(LastMouseX,LastMouseY); } From = 0; // user click outside of anything so drop from Refresh(Sender); // incase a drop needs to redraw screen } //--------------------------------------------------------------------------- void __fastcall TForm1::Image11MouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { if (From) { if (Moving) { TRect r; r.left = From->x-1; r.top = From->y-1; r.right = From->x+64+2; r.Bottom = From->y + 64+2; // Image1->Canvas->Pen->Color = clWhite; // Image1->Canvas->Rectangle(r); // Image1->Canvas->Refresh(); // Image1->Canvas->Pen->Color = clBlack; From->x = X; From->y = Y; ImageList1->Draw(Image1->Canvas,From->x,From->y,From->ImageID,true); // Image1->Canvas->Refresh(); this->Refresh(Sender); } else { Image1->Canvas->Pen->Width = 1; Image1->Canvas->Pen->Mode = pmNotXor; // Image1->Canvas->Pen->Style = psClear; Image1->Canvas->MoveTo(From->x+64,From->y+32); Image1->Canvas->LineTo(LastMouseX,LastMouseY); // Image1->Canvas->Pen->Style = psSolid; // Image1->Canvas->Pen->Mode = pmBlack; Image1->Canvas->MoveTo(From->x+64,From->y+32); Image1->Canvas->LineTo(X,Y); } LastMouseX = X; LastMouseY = Y; } else { ImageInfo *l = Head; while(l) { if (l->Selected(X,Y)) { StatusBar1->Panels->Items[0]->Text = l->Name; StatusBar1->Panels->Items[1]->Text = l->Description; } l = l->Next; } } } //--------------------------------------------------------------------------- void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action) { ImageInfo *l; Connection *C; LogicList *ll; while(Head) { l = Head; Head = l->Next; delete l; } while(Connections) { C = Connections; Connections = C->Next; delete C; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button8Click(TObject *Sender) { if (Form2->ShowModal()==mrOk) { int min,max; static StartX = 10; static StartY = 10; min = StrToInt(Form3->Min->Text); max = StrToInt(Form3->Max->Text); ImageInfo *l = new LogicList(Form2->LogicSelection->ItemIndex,Form2->Description->Text); l->Next = Head; Head = l; if (((LogicList *)Head)->Type==LogicList::In) { Head->x = 10; } else if (((LogicList *)Head)->Type==LogicList::Out) { Head->x = Image1->Width-70; } else { Head->x = StartX; StartX += 10; } Head->y = StartY; StartY += 10; UpdateComboBox(); Refresh(Sender); } } //--------------------------------------------------------------------------- void __fastcall TForm1::ComboBox1Change(TObject *Sender) { for(int x=0;x<grid->ColCount;x++) for(int y=0;y<grid->RowCount;y++) grid->Cells[x][y] = ""; Refresh(Sender); //FuzzyList *f = (FuzzyList *)ComboBox1->Items[ComboBox1->ItemIndex].Objects[0]; } //--------------------------------------------------------------------------- void __fastcall TForm1::Image1Paint(TObject *Sender) { ImageInfo *l = Head; TRect r; r.Left = 1; r.Top = 1; r.Right = Image1->Width; r.Bottom = Image1->Height; Image1->Canvas->FillRect(r); AnsiString a; l = Head; while(l) { ImageList1->Draw(Image1->Canvas,l->x,l->y,l->ImageID,true); r.left = l->x+5; r.top = l->y+35; r.right = l->x + 58; r.Bottom = l->y + 58; Image1->Canvas->TextOutA(r.Left+10,r.top+1,l->Name); r.top = l->In2Y+16 + l->y; r.left = l->x+58; if (l->Type==ImageInfo::In) { l->GetIn1Value(a); } else { l->GetOutValue(a); } Image1->Canvas->TextOutA(r.left,r.top,a); // TextRect(r,r.left+1,r.top+2,l->Name); l = l->Next; } Connection *C = Connections; while(C) { Image1->Canvas->MoveTo(C->From->x+64,C->From->y+32); if (C->ToIn==1) Image1->Canvas->LineTo(C->To->x,C->To->y+C->To->In1Y); else Image1->Canvas->LineTo(C->To->x,C->To->y + C->To->In2Y); C = C->Next; } } //--------------------------------------------------------------------------- void __fastcall TForm1::FormCreate(TObject *Sender) { DoubleBuffered = true; } //--------------------------------------------------------------------------- void __fastcall TForm1::Image1DblClick(TObject *Sender) { ImageInfo *l = Head; while(l) { if (l->Selected(LastMouseX,LastMouseY)) { if (l->Type==ImageInfo::Fuzzy) { FuzzyList *fl = (FuzzyList *)l; Form3->Description->Text = fl->Description; Form3->Name->Text = fl->Name; Form3->Min->Text = fl->Min; Form3->Max->Text = fl->Max; if (Form3->ShowModal()!=mrCancel) { fl->Name = Form3->Name->Text; fl->Description = Form3->Description->Text; fl->Min = StrToInt(Form3->Min->Text); fl->Max = StrToInt(Form3->Max->Text); fl->SetImageID(); } From = 0; Refresh(Sender); From = 0; } else { Form2->Description->Text = l->Description; Form2->LogicSelection->ItemIndex = l->Type; if (Form2->ShowModal()!=mrCancel) { l->Type = Form2->LogicSelection->ItemIndex; l->Description = Form2->Description->Text; l->SetImageID(); } From = 0; Refresh(Sender); From = 0; } } l = l->Next; } DoubleClick = true; } //---------------------------------------------------------------------------
[ "cwbruner@f8ea3247-a519-0410-8bc2-439d413616df" ]
[ [ [ 1, 1025 ] ] ]
931b7b99fb02829b058597ddcf10acd5ba815317
555ce7f1e44349316e240485dca6f7cd4496ea9c
/DirectShowFilters/MPWriter/source/ProgramToTransportStream.cpp
bf328f7d64c6b056dbf3c63b8c80ac12753c97eb
[]
no_license
Yura80/MediaPortal-1
c71ce5abf68c70852d261bed300302718ae2e0f3
5aae402f5aa19c9c3091c6d4442b457916a89053
refs/heads/master
2021-04-15T09:01:37.267793
2011-11-25T20:02:53
2011-11-25T20:11:02
2,851,405
2
0
null
null
null
null
UTF-8
C++
false
false
5,991
cpp
#include <winsock2.h> #include <ws2tcpip.h> #include <streams.h> #include "ProgramToTransportStream.h" #include "MemoryStreamSource.h" extern void LogDebug(const char *fmt, ...) ; extern void LogDebug(const wchar_t *fmt, ...); CProgramToTransportStream::CProgramToTransportStream(void) { m_bRunning=false; LogDebug("CProgramToTransportStream::ctor"); TaskScheduler* scheduler = MPTaskScheduler::createNew(); m_env = BasicUsageEnvironment::createNew(*scheduler); m_outputSink=NULL; m_inputSource=NULL; m_tsFrames=NULL; m_bSendVideoAudioObserverEvents = true; } CProgramToTransportStream::~CProgramToTransportStream(void) { LogDebug("CProgramToTransportStream::dtor"); } void afterPlaying(void* clientData) { LogDebug("CProgramToTransportStream afterPlaying"); MPEG2TransportStreamFromPESSource* outputSink=(MPEG2TransportStreamFromPESSource*)clientData; } void CProgramToTransportStream::Initialize(wchar_t* fileNameOut) { LogDebug(L"CProgramToTransportStream::Initialize %s", fileNameOut); m_BufferThreadActive=false; m_buffer.Clear(); m_inputSource = CMemoryStreamSource::createNew(*m_env, "",m_buffer); if (m_inputSource == NULL) { *m_env << "Unable to open memorystream as a byte-stream source\n"; return; } // Create a MPEG demultiplexor that reads from that source. MPEG1or2Demux* baseDemultiplexor = MPEG1or2Demux::createNew(*m_env, m_inputSource); // Create, from this, a source that returns raw PES packets: MPEG1or2DemuxedElementaryStream* pesSource = baseDemultiplexor->newRawPESStream(); // And, from this, a filter that converts to MPEG-2 Transport Stream frames: m_tsFrames = MPEG2TransportStreamFromPESSource::createNew(*m_env, pesSource); ((MPEG2TransportStreamFromPESSource*) m_tsFrames)->SetSourceType(m_iProgramType); m_outputSink = CMultiWriterFileSink::createNew(*m_env, fileNameOut, m_minFiles, m_maxFiles, m_maxFileSize); m_outputSink->SetChannelType(m_iProgramType); if (m_outputSink == NULL) { *m_env << "Unable to open file \"" << fileNameOut << "\" as a file sink\n"; return; } m_buffer.Clear(); m_iPacketsToSkip=100; //StartBufferThread(); m_bSendVideoAudioObserverEvents = true; m_bStarting=true; m_bRunning=true; } void CProgramToTransportStream::Flush() { LogDebug("CProgramToTransportStream::Flush()"); m_bSendVideoAudioObserverEvents = true; m_iPacketsToSkip=10; m_buffer.Clear(); } void CProgramToTransportStream::SetTimeShiftParams( int minFiles, int maxFiles, ULONG maxFileSize) { m_minFiles=minFiles; m_maxFiles=maxFiles; m_maxFileSize=maxFileSize; } void CProgramToTransportStream::SetProgramType(int programType) { // 0 = video, 1 = audio m_iProgramType = programType; } void CProgramToTransportStream::ClearStreams() { LogDebug("CProgramToTransportStream::ClearStreams()"); m_outputSink->ClearStreams(); } void CProgramToTransportStream::Write(byte* data, int len) { if (m_bRunning) { if (m_iPacketsToSkip>0) { m_iPacketsToSkip--; // LogDebug("skip:%d",m_iPacketsToSkip); return; } m_buffer.PutBuffer(data, len, 1); if (m_bStarting && m_buffer.Size()>300000) { m_bStarting=false; m_BufferThreadActive = true; if (m_outputSink->startPlaying(*m_tsFrames, afterPlaying, m_tsFrames)==True) { LogDebug("CProgramToTransportStream::Thread playing()"); } else { LogDebug("CProgramToTransportStream::Failed to start output sink"); } } while (m_buffer.Size()>300000) { if(m_bSendVideoAudioObserverEvents && m_pCallback != NULL){ m_bSendVideoAudioObserverEvents = false; m_pCallback->OnNotify(Audio); m_pCallback->OnNotify(Video); } m_env->taskScheduler().doEventLoop(); } } } void CProgramToTransportStream::Close() { LogDebug("CProgramToTransportStream::Close()"); m_bRunning=false; m_buffer.Stop(); StopBufferThread(); } void CProgramToTransportStream::StartBufferThread() { LogDebug("CProgramToTransportStream::StartBufferThread()"); m_buffer.Clear(); /* if (!m_BufferThreadActive) { //StartThread(); m_BufferThreadActive = true; if (m_outputSink->startPlaying(*m_tsFrames, afterPlaying, m_tsFrames)==True) { LogDebug("CProgramToTransportStream::Thread playing()"); } else { LogDebug("CProgramToTransportStream::Failed to start output sink"); } }*/ } void CProgramToTransportStream::StopBufferThread() { LogDebug("CProgramToTransportStream::StopBufferThread()"); // if (!m_BufferThreadActive) // return; //StopThread(INFINITE); if (m_outputSink!=NULL) Medium::close(m_outputSink); if (m_inputSource!=NULL) Medium::close(m_inputSource); if (m_tsFrames!=NULL) Medium::close(m_tsFrames); m_outputSink=NULL; m_inputSource=NULL; m_tsFrames=NULL; LogDebug("CProgramToTransportStream::Thread stopped()"); m_BufferThreadActive = false; } void CProgramToTransportStream::ThreadProc() { HRESULT hr = S_OK; m_BufferThreadActive = TRUE; // BoostThread Boost; //::SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL); LogDebug("CProgramToTransportStream::Thread started()"); if (m_outputSink->startPlaying(*m_tsFrames, afterPlaying, m_tsFrames)==True) { LogDebug("CProgramToTransportStream::Thread playing()"); } else { LogDebug("CProgramToTransportStream::Failed to start output sink"); } while (m_env!=NULL && !ThreadIsStopping(0)) { m_env->taskScheduler().doEventLoop(); } Medium::close(m_outputSink); Medium::close(m_inputSource); Medium::close(m_tsFrames); m_outputSink=NULL; m_inputSource=NULL; LogDebug("CProgramToTransportStream::Thread stopped()"); m_BufferThreadActive = false; return; } void CProgramToTransportStream::SetVideoAudioObserver(IAnalogVideoAudioObserver* callback){ LogDebug("CProgramToTransportStream::SetVideoAudioObserver - %x", callback); m_pCallback = callback; }
[ [ [ 1, 2 ], [ 9, 9 ], [ 11, 18 ], [ 23, 23 ], [ 28, 29 ], [ 34, 52 ], [ 54, 54 ], [ 57, 67 ], [ 71, 74 ], [ 78, 80 ], [ 87, 91 ], [ 94, 125 ], [ 130, 135 ], [ 137, 165 ], [ 168, 171 ], [ 173, 178 ], [ 187, 187 ], [ 190, 200 ], [ 204, 204 ], [ 206, 211 ], [ 214, 220 ] ], [ [ 3, 6 ], [ 8, 8 ], [ 10, 10 ], [ 19, 22 ], [ 24, 27 ], [ 30, 30 ], [ 32, 32 ], [ 68, 70 ], [ 75, 77 ], [ 81, 81 ], [ 92, 93 ], [ 126, 129 ], [ 136, 136 ], [ 166, 167 ], [ 172, 172 ], [ 179, 186 ], [ 188, 189 ], [ 201, 203 ], [ 205, 205 ], [ 212, 213 ] ], [ [ 7, 7 ], [ 31, 31 ], [ 33, 33 ], [ 55, 55 ] ], [ [ 53, 53 ], [ 56, 56 ], [ 82, 82 ], [ 84, 85 ] ], [ [ 83, 83 ], [ 86, 86 ] ] ]
c0053686336aeec91f9810d18c57f133d1c2db27
e776dbbd4feab1ce37ad62e5608e22a55a541d22
/MMOGame/Engine/LogicServer.cpp
07bbccd734ea93dca0d96cc71c133e624e8ae6fd
[]
no_license
EmuxEvans/sailing
80f2e2b0ae0f821ce6da013c3f67edabc8ca91ec
6d3a0f02732313f41518839376c5c0067aea4c0f
refs/heads/master
2016-08-12T23:47:57.509147
2011-04-06T03:39:19
2011-04-06T03:39:19
43,952,647
0
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
#include "CmdData.h" #include "LogicServer.h" class CLogicServer : public ILogicServer { public: CLogicServer(ILogicServerCallback* pCallback) { m_pCallback = pCallback; } virtual ~CLogicServer() { } virtual bool Start(unsigned int nIp, unsigned int nPort) { return false; } virtual void Stop() { } virtual void Wait() { } private: ILogicServerCallback* m_pCallback; }; class CLogicClient : public ILogicClient { public: virtual ~CLogicClient() { } virtual bool SendCommand(const CmdData* pData) { return false; } }; ILogicServer* CreateLogicServer(ILogicServerCallback* pCallback) { return new CLogicServer(pCallback); } ILogicClient* AcquieLogicClient(unsigned int nIp, unsigned int nPort) { return new CLogicClient(); }
[ "gamemake@74c81372-9d52-0410-afc2-f743258a769a" ]
[ [ [ 1, 34 ] ] ]
56e914f535971421cf21a0de7089b6cea01af9b9
bf6629ffb24850d41f5cf207c6350664b031920f
/src/adl.cpp
b80cfc37a74b81d7c882d711f2a8967a19c40b8c
[]
no_license
3dfxmadscientist/AMDOverdriveControlled
9d454faf8cbd2f2d423a2ee1800b158bfd558e18
7746d93f29de1fc591883f7e606cb47da7192f33
refs/heads/master
2020-12-24T11:25:59.678398
2011-04-12T10:50:01
2011-04-12T10:50:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,037
cpp
/******************************************************************************* * This program reads HW information from your ATI Radeon card and displays them * You can also change frequencies and voltages. * THIS PROGRAM MAY DAMAGE YOUR VIDEO CARD, IF YOU APPLY NONSENSIAL VALUES. * e.g. INCREASING THE VOLTAGES AND FREQUENCIES IN CONJUNCTION WITH LOWERING THE * FAN SPEED IS NOT ADVISABLE! * Copyright(C) Thorsten Gilling ([email protected]) * 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 "adl.h" #include <iostream> #ifdef FAKE_ATI_CARD #define GPA(x,y) x=NULL; #else #define GPA(x,y) x=(y)GetProcAddress(hDLL, #x); if(x == NULL) { cout << "ERR: ADL API function: " << #x << " is missing." << endl; /*return false;*/ } #endif using namespace std; ADL* ADL::ms_instance = NULL; ADL::ADL() : ADL_Main_Control_Create(NULL) , ADL_Main_Control_Refresh(NULL) , ADL_Main_Control_Destroy(NULL) , ADL_Graphics_Platform_Get(NULL) , ADL_Adapter_Active_Get(NULL) , ADL_Adapter_NumberOfAdapters_Get(NULL) , ADL_Adapter_AdapterInfo_Get(NULL) , ADL_Adapter_ASICFamilyType_Get(NULL) , ADL_Adapter_Speed_Caps(NULL) , ADL_Adapter_Speed_Get(NULL) , ADL_Adapter_Speed_Set(NULL) , ADL_Adapter_Accessibility_Get(NULL) , ADL_Adapter_VideoBiosInfo_Get(NULL) , ADL_Adapter_ID_Get(NULL) , ADL_Adapter_CrossdisplayAdapterRole_Caps(NULL) , ADL_Adapter_CrossdisplayInfo_Get(NULL) , ADL_Adapter_CrossdisplayInfo_Set(NULL) , ADL_Adapter_Crossfire_Caps(NULL) , ADL_Adapter_Crossfire_Get(NULL) , ADL_Adapter_Crossfire_Set(NULL) , ADL_Display_DisplayInfo_Get(NULL) , ADL_Display_NumberOfDisplays_Get(NULL) , ADL_Display_PreservedAspectRatio_Get(NULL) , ADL_Display_PreservedAspectRatio_Set(NULL) , ADL_Display_ImageExpansion_Get(NULL) , ADL_Display_ImageExpansion_Set(NULL) , ADL_Display_Position_Get(NULL) , ADL_Display_Position_Set(NULL) , ADL_Display_Size_Get(NULL) , ADL_Display_Size_Set(NULL) , ADL_Display_AdjustCaps_Get(NULL) , ADL_Display_Capabilities_Get(NULL) , ADL_Display_ConnectedDisplays_Get(NULL) , ADL_Display_DeviceConfig_Get(NULL) , ADL_Display_Property_Get(NULL) , ADL_Display_Property_Set(NULL) , ADL_Display_SwitchingCapability_Get(NULL) , ADL_Display_DitherState_Get(NULL) , ADL_Display_DitherState_Set(NULL) , ADL_Display_SupportedPixelFormat_Get(NULL) , ADL_Display_PixelFormat_Get(NULL) , ADL_Display_PixelFormat_Set(NULL) , ADL_Display_ODClockInfo_Get(NULL) , ADL_Display_ODClockConfig_Set(NULL) , ADL_Display_AdjustmentCoherent_Get(NULL) , ADL_Display_AdjustmentCoherent_Set(NULL) , ADL_Display_ReducedBlanking_Get(NULL) , ADL_Display_ReducedBlanking_Set(NULL) , ADL_Display_FormatsOverride_Get(NULL) , ADL_Display_FormatsOverride_Set(NULL) , ADL_Display_MVPUCaps_Get(NULL) , ADL_Display_MVPUStatus_Get(NULL) , ADL_Adapter_Active_Set(NULL) , ADL_Adapter_Active_SetPrefer(NULL) , ADL_Adapter_Primary_Get(NULL) , ADL_Adapter_Primary_Set(NULL) , ADL_Adapter_ModeSwitch(NULL) , ADL_Display_Modes_Get(NULL) , ADL_Display_Modes_Set(NULL) , ADL_Display_PossibleMode_Get(NULL) , ADL_Display_ForcibleDisplay_Get(NULL) , ADL_Display_ForcibleDisplay_Set(NULL) , ADL_Adapter_NumberOfActivatableSources_Get(NULL) , ADL_Adapter_Display_Caps(NULL) , ADL_Display_DisplayMapConfig_Get(NULL) , ADL_Display_DisplayMapConfig_Set(NULL) , ADL_Display_PossibleMapping_Get(NULL) , ADL_Display_DisplayMapConfig_Validate(NULL) , ADL_Display_DisplayMapConfig_PossibleAddAndRemove(NULL) , ADL_Display_SLSGrid_Caps(NULL) , ADL_Display_SLSMapIndexList_Get(NULL) , ADL_Display_SLSMapIndex_Get(NULL) , ADL_Display_SLSMapConfig_Get(NULL) , ADL_Display_SLSMapConfig_Create(NULL) , ADL_Display_SLSMapConfig_Delete(NULL) , ADL_Display_SLSMapConfig_SetState(NULL) , ADL_Display_SLSMapConfig_Rearrange(NULL) , ADL_Display_PossibleMode_WinXP_Get(NULL) , ADL_Display_BezelOffsetSteppingSize_Get(NULL) , ADL_Display_BezelOffset_Set(NULL) , ADL_Display_BezelSupported_Validate(NULL) , ADL_Display_ColorCaps_Get(NULL) , ADL_Display_Color_Set(NULL) , ADL_Display_Color_Get(NULL) , ADL_Display_ColorTemperatureSource_Get(NULL) , ADL_Display_ColorTemperatureSource_Set(NULL) , ADL_Display_ModeTimingOverride_Get(NULL) , ADL_Display_ModeTimingOverride_Set(NULL) , ADL_Display_ModeTimingOverrideList_Get(NULL) , ADL_Display_CustomizedModeListNum_Get(NULL) , ADL_Display_CustomizedModeList_Get(NULL) , ADL_Display_CustomizedMode_Add(NULL) , ADL_Display_CustomizedMode_Delete(NULL) , ADL_Display_CustomizedMode_Validate(NULL) , ADL_Display_Underscan_Set(NULL) , ADL_Display_Underscan_Get(NULL) , ADL_Display_Overscan_Set(NULL) , ADL_Display_Overscan_Get(NULL) , ADL_Display_ControllerOverlayAdjustmentCaps_Get(NULL) , ADL_Display_ControllerOverlayAdjustmentData_Get(NULL) , ADL_Display_ControllerOverlayAdjustmentData_Set(NULL) , ADL_Display_PowerXpressVersion_Get(NULL) , ADL_Display_PowerXpressActiveGPU_Get(NULL) , ADL_Display_PowerXpressActiveGPU_Set(NULL) , ADL_Display_PowerXpress_AutoSwitchConfig_Get(NULL) , ADL_Display_PowerXpress_AutoSwitchConfig_Set(NULL) , ADL_DFP_BaseAudioSupport_Get(NULL) , ADL_DFP_HDMISupport_Get(NULL) , ADL_DFP_MVPUAnalogSupport_Get(NULL) , ADL_DFP_PixelFormat_Caps(NULL) , ADL_DFP_PixelFormat_Get(NULL) , ADL_DFP_PixelFormat_Set(NULL) , ADL_DFP_GPUScalingEnable_Get(NULL) , ADL_DFP_GPUScalingEnable_Set(NULL) , ADL_DFP_AllowOnlyCETimings_Get(NULL) , ADL_DFP_AllowOnlyCETimings_Set(NULL) , ADL_Display_TVCaps_Get(NULL) , ADL_TV_Standard_Set(NULL) , ADL_TV_Standard_Get(NULL) , ADL_CV_DongleSettings_Get(NULL) , ADL_CV_DongleSettings_Set(NULL) , ADL_CV_DongleSettings_Reset(NULL) , ADL_Overdrive5_CurrentActivity_Get(NULL) , ADL_Overdrive5_ThermalDevices_Enum(NULL) , ADL_Overdrive5_Temperature_Get(NULL) , ADL_Overdrive5_FanSpeedInfo_Get(NULL) , ADL_Overdrive5_FanSpeed_Get(NULL) , ADL_Overdrive5_FanSpeed_Set(NULL) , ADL_Overdrive5_FanSpeedToDefault_Set(NULL) , ADL_Overdrive5_ODParameters_Get(NULL) , ADL_Overdrive5_ODPerformanceLevels_Get(NULL) , ADL_Overdrive5_ODPerformanceLevels_Set(NULL) , ADL_Display_WriteAndReadI2CRev_Get(NULL) , ADL_Display_WriteAndReadI2C(NULL) , ADL_Display_DDCBlockAccess_Get(NULL) , ADL_Display_DDCInfo_Get(NULL) , ADL_Display_EdidData_Get(NULL) , ADL_Workstation_Caps(NULL) , ADL_Workstation_Stereo_Get(NULL) , ADL_Workstation_Stereo_Set(NULL) , ADL_Workstation_AdapterNumOfGLSyncConnectors_Get(NULL) , ADL_Workstation_DisplayGenlockCapable_Get(NULL) , ADL_Workstation_GLSyncModuleDetect_Get(NULL) , ADL_Workstation_GLSyncModuleInfo_Get(NULL) , ADL_Workstation_GLSyncGenlockConfiguration_Get(NULL) , ADL_Workstation_GLSyncGenlockConfiguration_Set(NULL) , ADL_Workstation_GLSyncPortState_Get(NULL) , ADL_Workstation_GLSyncPortState_Set(NULL) , ADL_Workstation_DisplayGLSyncMode_Get(NULL) , ADL_Workstation_DisplayGLSyncMode_Set(NULL) , ADL_Workstation_GLSyncSupportedTopology_Get(NULL) , ADL_Workstation_LoadBalancing_Get(NULL) , ADL_Workstation_LoadBalancing_Set(NULL) , ADL_Workstation_LoadBalancing_Caps(NULL) #ifdef LINUX , ADL_Adapter_MemoryInfo_Get(NULL) , ADL_DesktopConfig_Get(NULL) , ADL_DesktopConfig_Set(NULL) , ADL_NumberOfDisplayEnable_Get(NULL) , ADL_DisplayEnable_Set(NULL) , ADL_Display_IdentifyDisplay(NULL) , ADL_Display_LUTColor_Set(NULL) , ADL_Display_LUTColor_Get(NULL) , ADL_Adapter_XScreenInfo_Get(NULL) , ADL_Display_XrandrDisplayName_Get(NULL) #endif , mNrOfAdapters(0) , mpAdapterInfo(NULL) , mpODPerformanceLevels(NULL) , hDLL(NULL) , mFeatures(0) , mGPUIndex(0) { } ADL::~ADL() { if (mpODPerformanceLevels != NULL) { free (mpODPerformanceLevels); mpODPerformanceLevels = NULL; } } ADL* ADL::Instance() { if(ms_instance == NULL) { ms_instance = new ADL(); if (ms_instance) { if (!ms_instance->Init()) { ERR_LOG("Error: Could not Init library."); } } } return ms_instance; } void ADL::Release() { if(ms_instance) { ms_instance->ADL_Main_Control_Destroy (); #if defined (LINUX) dlclose(ms_instance->hDLL); #else FreeLibrary(ms_instance->hDLL); #endif delete ms_instance; } ms_instance = NULL; } #ifdef LINUX void* ADL::GetProcAddress(void* pLibrary, const char* name) { return dlsym(pLibrary, name); } #endif // Memory allocation function void* __stdcall ADL::sADL_Main_Memory_Alloc (int iSize) { void* lpBuffer = malloc ( iSize ); return lpBuffer; } void* __stdcall ADL::ADL_Main_Memory_Alloc (int iSize) { return sADL_Main_Memory_Alloc(iSize); } // Optional Memory de-allocation function void __stdcall ADL::ADL_Main_Memory_Free (void** lpBuffer) { if ( NULL != *lpBuffer ) { free ( *lpBuffer ); *lpBuffer = NULL; } } bool ADL::Init() { #ifndef FAKE_ATI_CARD #if defined (LINUX) hDLL = dlopen( "libatiadlxx.so", RTLD_LAZY|RTLD_GLOBAL); #else hDLL = LoadLibrary("atiadlxx.dll"); if (hDLL == NULL) // A 32 bit calling application on 64 bit OS will fail to LoadLIbrary. // Try to load the 32 bit library (atiadlxy.dll) instead hDLL = LoadLibrary("atiadlxy.dll"); #endif if (NULL == hDLL) { return false; } #else mNrOfAdapters = 1; #endif GPA(ADL_Main_Control_Create, ADL_MAIN_CONTROL_CREATE) GPA(ADL_Main_Control_Destroy, ADL_MAIN_CONTROL_DESTROY) GPA(ADL_Adapter_NumberOfAdapters_Get, ADL_ADAPTER_NUMBEROFADAPTERS_GET) GPA(ADL_Adapter_AdapterInfo_Get, ADL_ADAPTER_ADAPTERINFO_GET) GPA(ADL_Display_DisplayInfo_Get, ADL_DISPLAY_DISPLAYINFO_GET) GPA(ADL_Display_ColorCaps_Get, ADL_DISPLAY_COLORCAPS_GET) GPA(ADL_Display_Color_Get, ADL_DISPLAY_COLOR_GET) GPA(ADL_Display_Color_Set, ADL_DISPLAY_COLOR_SET) GPA(ADL_Main_Control_Create, ADL_MAIN_CONTROL_CREATE) GPA(ADL_Main_Control_Refresh, ADL_MAIN_CONTROL_REFRESH) GPA(ADL_Main_Control_Destroy, ADL_MAIN_CONTROL_DESTROY) GPA(ADL_Graphics_Platform_Get, ADL_GRAPHICS_PLATFORM_GET) GPA(ADL_Adapter_Active_Get, ADL_ADAPTER_ACTIVE_GET) GPA(ADL_Adapter_NumberOfAdapters_Get, ADL_ADAPTER_NUMBEROFADAPTERS_GET) GPA(ADL_Adapter_AdapterInfo_Get, ADL_ADAPTER_ADAPTERINFO_GET) GPA(ADL_Adapter_ASICFamilyType_Get, ADL_ADAPTER_ASICFAMILYTYPE_GET) GPA(ADL_Adapter_Speed_Caps, ADL_ADAPTER_SPEED_CAPS) GPA(ADL_Adapter_Speed_Get, ADL_ADAPTER_SPEED_GET) GPA(ADL_Adapter_Speed_Set, ADL_ADAPTER_SPEED_SET) GPA(ADL_Adapter_Accessibility_Get, ADL_ADAPTER_ACCESSIBILITY_GET) GPA(ADL_Adapter_VideoBiosInfo_Get, ADL_ADAPTER_VIDEOBIOSINFO_GET) GPA(ADL_Adapter_ID_Get, ADL_ADAPTER_ID_GET) GPA(ADL_Adapter_CrossdisplayAdapterRole_Caps, ADL_ADAPTER_CROSSDISPLAYADAPTERROLE_CAPS) GPA(ADL_Adapter_CrossdisplayInfo_Get, ADL_ADAPTER_CROSSDISPLAYINFO_GET) GPA(ADL_Adapter_CrossdisplayInfo_Set, ADL_ADAPTER_CROSSDISPLAYINFO_SET) GPA(ADL_Adapter_Crossfire_Caps, ADL_ADAPTER_CROSSFIRE_CAPS) GPA(ADL_Adapter_Crossfire_Get, ADL_ADAPTER_CROSSFIRE_GET) GPA(ADL_Adapter_Crossfire_Set, ADL_ADAPTER_CROSSFIRE_SET) GPA(ADL_Display_DisplayInfo_Get, ADL_DISPLAY_DISPLAYINFO_GET) GPA(ADL_Display_NumberOfDisplays_Get, ADL_DISPLAY_NUMBEROFDISPLAYS_GET) GPA(ADL_Display_PreservedAspectRatio_Get, ADL_DISPLAY_PRESERVEDASPECTRATIO_GET) GPA(ADL_Display_PreservedAspectRatio_Set, ADL_DISPLAY_PRESERVEDASPECTRATIO_SET) GPA(ADL_Display_ImageExpansion_Get, ADL_DISPLAY_IMAGEEXPANSION_GET) GPA(ADL_Display_ImageExpansion_Set, ADL_DISPLAY_IMAGEEXPANSION_SET) GPA(ADL_Display_Position_Get, ADL_DISPLAY_POSITION_GET) GPA(ADL_Display_Position_Set, ADL_DISPLAY_POSITION_SET) GPA(ADL_Display_Size_Get, ADL_DISPLAY_SIZE_GET) GPA(ADL_Display_Size_Set, ADL_DISPLAY_SIZE_SET) GPA(ADL_Display_AdjustCaps_Get, ADL_DISPLAY_ADJUSTCAPS_GET) GPA(ADL_Display_Capabilities_Get, ADL_DISPLAY_CAPABILITIES_GET) GPA(ADL_Display_ConnectedDisplays_Get, ADL_DISPLAY_CONNECTEDDISPLAYS_GET) GPA(ADL_Display_DeviceConfig_Get, ADL_DISPLAY_DEVICECONFIG_GET) GPA(ADL_Display_Property_Get, ADL_DISPLAY_PROPERTY_GET) GPA(ADL_Display_Property_Set, ADL_DISPLAY_PROPERTY_SET) GPA(ADL_Display_SwitchingCapability_Get, ADL_DISPLAY_SWITCHINGCAPABILITY_GET) GPA(ADL_Display_DitherState_Get, ADL_DISPLAY_DITHERSTATE_GET) GPA(ADL_Display_DitherState_Set, ADL_DISPLAY_DITHERSTATE_SET) GPA(ADL_Display_SupportedPixelFormat_Get, ADL_DISPLAY_SUPPORTEDPIXELFORMAT_GET) GPA(ADL_Display_PixelFormat_Get, ADL_DISPLAY_PIXELFORMAT_GET) GPA(ADL_Display_PixelFormat_Set, ADL_DISPLAY_PIXELFORMAT_SET) GPA(ADL_Display_ODClockInfo_Get, ADL_DISPLAY_ODCLOCKINFO_GET) GPA(ADL_Display_ODClockConfig_Set, ADL_DISPLAY_ODCLOCKCONFIG_SET) GPA(ADL_Display_AdjustmentCoherent_Get, ADL_DISPLAY_ADJUSTMENTCOHERENT_GET) GPA(ADL_Display_AdjustmentCoherent_Set, ADL_DISPLAY_ADJUSTMENTCOHERENT_SET) GPA(ADL_Display_ReducedBlanking_Get, ADL_DISPLAY_REDUCEDBLANKING_GET) GPA(ADL_Display_ReducedBlanking_Set, ADL_DISPLAY_REDUCEDBLANKING_SET) GPA(ADL_Display_FormatsOverride_Get, ADL_DISPLAY_FORMATSOVERRIDE_GET) GPA(ADL_Display_FormatsOverride_Set, ADL_DISPLAY_FORMATSOVERRIDE_SET) GPA(ADL_Display_MVPUCaps_Get, ADL_DISPLAY_MVPUCAPS_GET) GPA(ADL_Display_MVPUStatus_Get, ADL_DISPLAY_MVPUSTATUS_GET) GPA(ADL_Adapter_Active_Set, ADL_ADAPTER_ACTIVE_SET) GPA(ADL_Adapter_Active_SetPrefer, ADL_ADAPTER_ACTIVE_SETPREFER) GPA(ADL_Adapter_Primary_Get, ADL_ADAPTER_PRIMARY_GET) GPA(ADL_Adapter_Primary_Set, ADL_ADAPTER_PRIMARY_SET) GPA(ADL_Adapter_ModeSwitch, ADL_ADAPTER_MODESWITCH) GPA(ADL_Display_Modes_Get, ADL_DISPLAY_MODES_GET) GPA(ADL_Display_Modes_Set, ADL_DISPLAY_MODES_SET) GPA(ADL_Display_PossibleMode_Get, ADL_DISPLAY_POSSIBLEMODE_GET) GPA(ADL_Display_ForcibleDisplay_Get, ADL_DISPLAY_FORCIBLEDISPLAY_GET) GPA(ADL_Display_ForcibleDisplay_Set, ADL_DISPLAY_FORCIBLEDISPLAY_SET) GPA(ADL_Adapter_NumberOfActivatableSources_Get, ADL_ADAPTER_NUMBEROFACTIVATABLESOURCES_GET) GPA(ADL_Adapter_Display_Caps, ADL_ADAPTER_DISPLAY_CAPS) GPA(ADL_Display_DisplayMapConfig_Get, ADL_DISPLAY_DISPLAYMAPCONFIG_GET) GPA(ADL_Display_DisplayMapConfig_Set, ADL_DISPLAY_DISPLAYMAPCONFIG_SET) GPA(ADL_Display_PossibleMapping_Get, ADL_DISPLAY_POSSIBLEMAPPING_GET) GPA(ADL_Display_DisplayMapConfig_Validate, ADL_DISPLAY_DISPLAYMAPCONFIG_VALIDATE) GPA(ADL_Display_DisplayMapConfig_PossibleAddAndRemove, ADL_DISPLAY_DISPLAYMAPCONFIG_POSSIBLEADDANDREMOVE) GPA(ADL_Display_SLSGrid_Caps, ADL_DISPLAY_SLSGRID_CAPS) GPA(ADL_Display_SLSMapIndexList_Get, ADL_DISPLAY_SLSMAPINDEXLIST_GET) GPA(ADL_Display_SLSMapIndex_Get, ADL_DISPLAY_SLSMAPINDEX_GET) GPA(ADL_Display_SLSMapConfig_Get, ADL_DISPLAY_SLSMAPCONFIG_GET) GPA(ADL_Display_SLSMapConfig_Create, ADL_DISPLAY_SLSMAPCONFIG_CREATE) GPA(ADL_Display_SLSMapConfig_Delete, ADL_DISPLAY_SLSMAPCONFIG_DELETE) GPA(ADL_Display_SLSMapConfig_SetState, ADL_DISPLAY_SLSMAPCONFIG_SETSTATE) GPA(ADL_Display_SLSMapConfig_Rearrange, ADL_DISPLAY_SLSMAPCONFIG_REARRANGE) #ifndef LINUX //ADL_Display_PossibleMode_WinXP_Get= NULL; GPA(ADL_Display_PossibleMode_WinXP_Get, ADL_DISPLAY_POSSIBLEMODE_WINXP_GET) #else ADL_Display_PossibleMode_WinXP_Get = NULL; #endif GPA(ADL_Display_BezelOffsetSteppingSize_Get, ADL_DISPLAY_BEZELOFFSETSTEPPINGSIZE_GET) GPA(ADL_Display_BezelOffset_Set, ADL_DISPLAY_BEZELOFFSET_SET) GPA(ADL_Display_BezelSupported_Validate, ADL_DISPLAY_BEZELSUPPORTED_VALIDATE) GPA(ADL_Display_ColorCaps_Get, ADL_DISPLAY_COLORCAPS_GET) GPA(ADL_Display_Color_Set, ADL_DISPLAY_COLOR_SET) GPA(ADL_Display_Color_Get, ADL_DISPLAY_COLOR_GET) GPA(ADL_Display_ColorTemperatureSource_Get, ADL_DISPLAY_COLORTEMPERATURESOURCE_GET) GPA(ADL_Display_ColorTemperatureSource_Set, ADL_DISPLAY_COLORTEMPERATURESOURCE_SET) GPA(ADL_Display_ModeTimingOverride_Get, ADL_DISPLAY_MODETIMINGOVERRIDE_GET) GPA(ADL_Display_ModeTimingOverride_Set, ADL_DISPLAY_MODETIMINGOVERRIDE_SET) GPA(ADL_Display_ModeTimingOverrideList_Get, ADL_DISPLAY_MODETIMINGOVERRIDELIST_GET) GPA(ADL_Display_CustomizedModeListNum_Get, ADL_DISPLAY_CUSTOMIZEDMODELISTNUM_GET) GPA(ADL_Display_CustomizedModeList_Get, ADL_DISPLAY_CUSTOMIZEDMODELIST_GET) GPA(ADL_Display_CustomizedMode_Add, ADL_DISPLAY_CUSTOMIZEDMODE_ADD) GPA(ADL_Display_CustomizedMode_Delete, ADL_DISPLAY_CUSTOMIZEDMODE_DELETE) GPA(ADL_Display_CustomizedMode_Validate, ADL_DISPLAY_CUSTOMIZEDMODE_VALIDATE) GPA(ADL_Display_Underscan_Set, ADL_DISPLAY_UNDERSCAN_SET) GPA(ADL_Display_Underscan_Get, ADL_DISPLAY_UNDERSCAN_GET) GPA(ADL_Display_Overscan_Set, ADL_DISPLAY_OVERSCAN_SET) GPA(ADL_Display_Overscan_Get, ADL_DISPLAY_OVERSCAN_GET) GPA(ADL_Display_ControllerOverlayAdjustmentCaps_Get, ADL_DISPLAY_CONTROLLEROVERLAYADJUSTMENTCAPS_GET) GPA(ADL_Display_ControllerOverlayAdjustmentData_Get, ADL_DISPLAY_CONTROLLEROVERLAYADJUSTMENTDATA_GET) GPA(ADL_Display_ControllerOverlayAdjustmentData_Set, ADL_DISPLAY_CONTROLLEROVERLAYADJUSTMENTDATA_SET) GPA(ADL_Display_PowerXpressVersion_Get, ADL_DISPLAY_POWERXPRESSVERSION_GET) GPA(ADL_Display_PowerXpressActiveGPU_Get, ADL_DISPLAY_POWERXPRESSACTIVEGPU_GET) GPA(ADL_Display_PowerXpressActiveGPU_Set, ADL_DISPLAY_POWERXPRESSACTIVEGPU_SET) GPA(ADL_Display_PowerXpress_AutoSwitchConfig_Get, ADL_DISPLAY_POWERXPRESS_AUTOSWITCHCONFIG_GET) GPA(ADL_Display_PowerXpress_AutoSwitchConfig_Set, ADL_DISPLAY_POWERXPRESS_AUTOSWITCHCONFIG_SET) GPA(ADL_DFP_BaseAudioSupport_Get, ADL_DFP_BASEAUDIOSUPPORT_GET) GPA(ADL_DFP_HDMISupport_Get, ADL_DFP_HDMISUPPORT_GET) GPA(ADL_DFP_MVPUAnalogSupport_Get, ADL_DFP_MVPUANALOGSUPPORT_GET) GPA(ADL_DFP_PixelFormat_Caps, ADL_DFP_PIXELFORMAT_CAPS) GPA(ADL_DFP_PixelFormat_Get, ADL_DFP_PIXELFORMAT_GET) GPA(ADL_DFP_PixelFormat_Set, ADL_DFP_PIXELFORMAT_SET) GPA(ADL_DFP_GPUScalingEnable_Get, ADL_DFP_GPUSCALINGENABLE_GET) GPA(ADL_DFP_GPUScalingEnable_Set, ADL_DFP_GPUSCALINGENABLE_SET) GPA(ADL_DFP_AllowOnlyCETimings_Get, ADL_DFP_ALLOWONLYCETIMINGS_GET) GPA(ADL_DFP_AllowOnlyCETimings_Set, ADL_DFP_ALLOWONLYCETIMINGS_SET) GPA(ADL_Display_TVCaps_Get, ADL_DISPLAY_TVCAPS_GET) GPA(ADL_TV_Standard_Set, ADL_TV_STANDARD_SET) GPA(ADL_TV_Standard_Get, ADL_TV_STANDARD_GET) GPA(ADL_CV_DongleSettings_Get, ADL_CV_DONGLESETTINGS_GET) GPA(ADL_CV_DongleSettings_Set, ADL_CV_DONGLESETTINGS_SET) GPA(ADL_CV_DongleSettings_Reset, ADL_CV_DONGLESETTINGS_RESET) GPA(ADL_Overdrive5_CurrentActivity_Get, ADL_OVERDRIVE5_CURRENTACTIVITY_GET) GPA(ADL_Overdrive5_ThermalDevices_Enum, ADL_OVERDRIVE5_THERMALDEVICES_ENUM) GPA(ADL_Overdrive5_Temperature_Get, ADL_OVERDRIVE5_TEMPERATURE_GET) GPA(ADL_Overdrive5_FanSpeedInfo_Get, ADL_OVERDRIVE5_FANSPEEDINFO_GET) GPA(ADL_Overdrive5_FanSpeed_Get, ADL_OVERDRIVE5_FANSPEED_GET) GPA(ADL_Overdrive5_FanSpeed_Set, ADL_OVERDRIVE5_FANSPEED_SET) GPA(ADL_Overdrive5_FanSpeedToDefault_Set, ADL_OVERDRIVE5_FANSPEEDTODEFAULT_SET) GPA(ADL_Overdrive5_ODParameters_Get, ADL_OVERDRIVE5_ODPARAMETERS_GET) GPA(ADL_Overdrive5_ODPerformanceLevels_Get, ADL_OVERDRIVE5_ODPERFORMANCELEVELS_GET) GPA(ADL_Overdrive5_ODPerformanceLevels_Set, ADL_OVERDRIVE5_ODPERFORMANCELEVELS_SET) GPA(ADL_Display_WriteAndReadI2CRev_Get, ADL_DISPLAY_WRITEANDREADI2CREV_GET) GPA(ADL_Display_WriteAndReadI2C, ADL_DISPLAY_WRITEANDREADI2C) GPA(ADL_Display_DDCBlockAccess_Get, ADL_DISPLAY_DDCBLOCKACCESS_GET) GPA(ADL_Display_DDCInfo_Get, ADL_DISPLAY_DDCINFO_GET) GPA(ADL_Display_EdidData_Get, ADL_DISPLAY_EDIDDATA_GET) GPA(ADL_Workstation_Caps, ADL_WORKSTATION_CAPS) GPA(ADL_Workstation_Stereo_Get, ADL_WORKSTATION_STEREO_GET) GPA(ADL_Workstation_Stereo_Set, ADL_WORKSTATION_STEREO_SET) GPA(ADL_Workstation_AdapterNumOfGLSyncConnectors_Get, ADL_WORKSTATION_ADAPTERNUMOFGLSYNCCONNECTORS_GET) GPA(ADL_Workstation_DisplayGenlockCapable_Get, ADL_WORKSTATION_DISPLAYGENLOCKCAPABLE_GET) GPA(ADL_Workstation_GLSyncModuleDetect_Get, ADL_WORKSTATION_GLSYNCMODULEDETECT_GET) GPA(ADL_Workstation_GLSyncModuleInfo_Get, ADL_WORKSTATION_GLSYNCMODULEINFO_GET) GPA(ADL_Workstation_GLSyncGenlockConfiguration_Get, ADL_WORKSTATION_GLSYNCGENLOCKCONFIGURATION_GET) GPA(ADL_Workstation_GLSyncGenlockConfiguration_Set, ADL_WORKSTATION_GLSYNCGENLOCKCONFIGURATION_SET) GPA(ADL_Workstation_GLSyncPortState_Get, ADL_WORKSTATION_GLSYNCPORTSTATE_GET) GPA(ADL_Workstation_GLSyncPortState_Set, ADL_WORKSTATION_GLSYNCPORTSTATE_SET) GPA(ADL_Workstation_DisplayGLSyncMode_Get, ADL_WORKSTATION_DISPLAYGLSYNCMODE_GET) GPA(ADL_Workstation_DisplayGLSyncMode_Set, ADL_WORKSTATION_DISPLAYGLSYNCMODE_SET) GPA(ADL_Workstation_GLSyncSupportedTopology_Get, ADL_WORKSTATION_GLSYNCSUPPORTEDTOPOLOGY_GET) GPA(ADL_Workstation_LoadBalancing_Get, ADL_WORKSTATION_LOADBALANCING_GET) GPA(ADL_Workstation_LoadBalancing_Set, ADL_WORKSTATION_LOADBALANCING_SET) GPA(ADL_Workstation_LoadBalancing_Caps, ADL_WORKSTATION_LOADBALANCING_CAPS) #ifdef LINUX GPA(ADL_Adapter_MemoryInfo_Get, ADL_ADAPTER_MEMORYINFO_GET) GPA(ADL_DesktopConfig_Get, ADL_DESKTOPCONFIG_GET) GPA(ADL_DesktopConfig_Set, ADL_DESKTOPCONFIG_SET) GPA(ADL_NumberOfDisplayEnable_Get, ADL_NUMBEROFDISPLAYENABLE_GET) GPA(ADL_DisplayEnable_Set, ADL_DISPLAYENABLE_SET) GPA(ADL_Display_IdentifyDisplay, ADL_DISPLAY_IDENTIFYDISPLAY) GPA(ADL_Display_LUTColor_Set, ADL_DISPLAY_LUTCOLOR_SET) GPA(ADL_Display_LUTColor_Get, ADL_DISPLAY_LUTCOLOR_GET) GPA(ADL_Adapter_XScreenInfo_Get, ADL_ADAPTER_XSCREENINFO_GET) GPA(ADL_Display_XrandrDisplayName_Get, ADL_DISPLAY_XRANDRDISPLAYNAME_GET) #endif #ifndef FAKE_ATI_CARD // Initialize ADL. The second parameter is 1, which means: // retrieve adapter information only for adapters that are physically present and enabled in the system if (ADL_OK != ADL_Main_Control_Create (sADL_Main_Memory_Alloc, 1)) { return false; } if (ADL_Adapter_NumberOfAdapters_Get(&mNrOfAdapters) == ADL_OK) { INF_LOG("Nr. of Adapters: " << mNrOfAdapters); if (mNrOfAdapters > 0) { mpAdapterInfo = (LPAdapterInfo) malloc (sizeof(AdapterInfo) * mNrOfAdapters); if (mpAdapterInfo != NULL) { memset (mpAdapterInfo, '\0', sizeof(AdapterInfo) * mNrOfAdapters); if (ADL_Adapter_AdapterInfo_Get (mpAdapterInfo, sizeof (AdapterInfo) * mNrOfAdapters) != ADL_OK) { ERR_LOG("ERROR: no adapter info available!"); } for (int i=0; i<mNrOfAdapters; i++) { int status; SAVE_CALL(ADL_Adapter_Active_Get)(i, &status); int id; SAVE_CALL(ADL_Adapter_ID_Get)(i, &id); INF_LOG("Adapter index: " << mpAdapterInfo[i].iAdapterIndex << (status == ADL_TRUE ? ", active" : ", inact.") << ", ID:" << id << ", " << mpAdapterInfo[i].strAdapterName); } if (UpdateData() == 0) { ERR_LOG("ERROR: failed to read card values!"); } } else { return false; } } else { return false; } return true; } else { return false; } #else return true; #endif } bool ADL::IsATICardAndCatalystPresent() const { return (mNrOfAdapters > 0); } int ADL::UpdateData() { int result = 0; if (mNrOfAdapters > 0) { #ifdef FAKE_ATI_CARD mFanSpeedInfo.iMinRPM = 500; mFanSpeedInfo.iMaxRPM = 4000; mFanSpeedInfo.iMaxPercent = 85; mFanSpeedInfo.iMinPercent = 12; mODActivity.iMaximumBusLanes = 16; mODActivity.iCurrentBusLanes = 16; mODActivity.iCurrentBusSpeed = 5000; static int cnt = 0; ++cnt; if (cnt < 20) { mODActivity.iEngineClock = 75000; mODActivity.iMemoryClock = 95000; mODActivity.iCurrentPerformanceLevel = 2; mCurrentFanSpeed.iFanSpeed = 1734 + (rand() % 2) * 3 - (rand() % 3) * 5; mTemperature.iTemperature = 46500 + (rand() % 2) * 500; } else if (cnt < 40) { mODActivity.iEngineClock = 65000; mODActivity.iMemoryClock = 75000; mODActivity.iCurrentPerformanceLevel = 1; mCurrentFanSpeed.iFanSpeed = 1534 + (rand() % 2) * 3 - (rand() % 3) * 5; mTemperature.iTemperature = 43500 + (rand() % 2) * 500; } else if (cnt < 60) { mODActivity.iEngineClock = 25000; mODActivity.iMemoryClock = 35000; mODActivity.iCurrentPerformanceLevel = 0; mCurrentFanSpeed.iFanSpeed = 1234 + (rand() % 2) * 3 - (rand() % 3) * 5; mTemperature.iTemperature = 40500 + (rand() % 2) * 500; } else { cnt = 0; } mODActivity.iVddc = 1023; mODActivity.iActivityPercent = 50 + (rand() % 2) * 25 - (rand() % 3) * 25; mODClockInfo.sEngineClock.iDefaultClock = 75000; mODClockInfo.sMemoryClock.iDefaultClock = 90000; int perf_level_size = sizeof(ADLODPerformanceLevels) + sizeof(ADLODPerformanceLevel) * (3 - 1); mpODPerformanceLevels = (ADLODPerformanceLevels*)malloc(perf_level_size); mpODPerformanceLevels->iSize = perf_level_size; mpODPerformanceLevels->aLevels[0].iEngineClock = 20000; mpODPerformanceLevels->aLevels[0].iMemoryClock = 30000; mpODPerformanceLevels->aLevels[0].iVddc = 1023; mpODPerformanceLevels->aLevels[1].iEngineClock = 30000; mpODPerformanceLevels->aLevels[1].iMemoryClock = 40000; mpODPerformanceLevels->aLevels[1].iVddc = 1263; mpODPerformanceLevels->aLevels[2].iEngineClock = 40000; mpODPerformanceLevels->aLevels[2].iMemoryClock = 50000; mpODPerformanceLevels->aLevels[2].iVddc = 1263; mNrOfAdapters = 1; mpAdapterInfo = (LPAdapterInfo) malloc (sizeof(AdapterInfo) * mNrOfAdapters); if (mpAdapterInfo != NULL) { memset (mpAdapterInfo, 0, sizeof(AdapterInfo) * mNrOfAdapters); strncpy(mpAdapterInfo[mGPUIndex].strAdapterName, "Fake AMD/ATI Card", ADL_MAX_PATH-1); } mODParameters.sEngineClock.iMax = 85000; mODParameters.sEngineClock.iMin = 11000; mODParameters.sEngineClock.iStep = 500; mODParameters.sMemoryClock.iMax = 110000; mODParameters.sMemoryClock.iMin = 10000; mODParameters.sMemoryClock.iStep = 1000; mODParameters.sVddc.iMax = 1263; mODParameters.sVddc.iMin = 1023; mODParameters.sVddc.iStep = 80; mODParameters.iNumberOfPerformanceLevels = 3; result = 0; // result = ERR_GET_CURRENT_FANSPEED_FAILED; // mCurrentFanSpeed.iFanSpeed = 0; // mFanSpeedInfo.iMinRPM = 0; // mFanSpeedInfo.iMaxRPM = 0; // mFanSpeedInfo.iMaxPercent = 0; // mFanSpeedInfo.iMinPercent = 0; // result = ERR_GET_TEMPERATURE_FAILED; // mTemperature.iTemperature = 0; // result = ERR_GET_OD_PERF_LEVELS_FAILED | ERR_GET_ACTIVITY_FAILED; // mODParameters.sEngineClock.iMax = 0; // mODParameters.sEngineClock.iMin = 0; // mODParameters.sEngineClock.iStep = 0; // // mODParameters.sMemoryClock.iMax = 0; // mODParameters.sMemoryClock.iMin = 0; // mODParameters.sMemoryClock.iStep = 0; // // mODParameters.sVddc.iMax = 0; // mODParameters.sVddc.iMin = 0; // mODParameters.sVddc.iStep = 0; #else mTemperature.iSize = sizeof(ADLTemperature); if (SAVE_CALL(ADL_Overdrive5_Temperature_Get)(mGPUIndex, 0, &mTemperature) != ADL_OK) { mTemperature.iTemperature = 0; result |= ERR_GET_TEMPERATURE_FAILED; } mFanSpeedInfo.iSize = sizeof(ADLFanSpeedInfo); if (SAVE_CALL(ADL_Overdrive5_FanSpeedInfo_Get)(mGPUIndex, 0, &mFanSpeedInfo) != ADL_OK) { mFanSpeedInfo.iMinRPM = 0; mFanSpeedInfo.iMaxRPM = 0; mFanSpeedInfo.iMinPercent = 0; mFanSpeedInfo.iMaxPercent = 0; result |= ERR_GET_FANSPEED_INFO_FAILED; } if (mFanSpeedInfo.iMaxRPM == 0 || mFanSpeedInfo.iMaxPercent == 0 || mFanSpeedInfo.iMinRPM == mFanSpeedInfo.iMaxRPM || mFanSpeedInfo.iMinPercent == mFanSpeedInfo.iMaxPercent || mFanSpeedInfo.iMinRPM > mFanSpeedInfo.iMaxRPM || mFanSpeedInfo.iMinPercent > mFanSpeedInfo.iMaxPercent) { result |= ERR_GET_FANSPEED_INFO_FAILED; } mCurrentFanSpeed.iSize = sizeof(ADLFanSpeedValue); mCurrentFanSpeed.iFlags = ADL_DL_FANCTRL_SPEED_TYPE_RPM; if (SAVE_CALL(ADL_Overdrive5_FanSpeed_Get)(mGPUIndex, 0, &mCurrentFanSpeed) != ADL_OK) { mCurrentFanSpeed.iFanSpeed = 0; result |= ERR_GET_CURRENT_FANSPEED_FAILED; } mODParameters.iSize = sizeof(ADLODParameters); if (SAVE_CALL(ADL_Overdrive5_ODParameters_Get)(mGPUIndex, &mODParameters) == ADL_OK) { if (mODParameters.sEngineClock.iMin == mODParameters.sEngineClock.iMax || mODParameters.sMemoryClock.iMin == mODParameters.sMemoryClock.iMax || mODParameters.sVddc.iMin == mODParameters.sVddc.iMax || mODParameters.sEngineClock.iMin > mODParameters.sEngineClock.iMax || mODParameters.sMemoryClock.iMin > mODParameters.sMemoryClock.iMax || mODParameters.sVddc.iMin > mODParameters.sVddc.iMax) { result |= ERR_GET_OD_PARAMETERS_FAILED; } else { if (mpODPerformanceLevels == NULL) { int perf_level_size = sizeof(ADLODPerformanceLevels) + sizeof(ADLODPerformanceLevel) * (mODParameters.iNumberOfPerformanceLevels - 1); mpODPerformanceLevels = (ADLODPerformanceLevels*)malloc(perf_level_size); mpODPerformanceLevels->iSize = perf_level_size; } if (SAVE_CALL(ADL_Overdrive5_ODPerformanceLevels_Get)(mGPUIndex, 0, mpODPerformanceLevels) != ADL_OK) { free(mpODPerformanceLevels); mpODPerformanceLevels = NULL; result |= ERR_GET_OD_PERF_LEVELS_FAILED; } } } else { result |= ERR_GET_OD_PARAMETERS_FAILED; } mODActivity.iSize = sizeof(ADLPMActivity); if (SAVE_CALL(ADL_Overdrive5_CurrentActivity_Get)(mGPUIndex, &mODActivity) != ADL_OK) { mODActivity.iEngineClock = 0; mODActivity.iMemoryClock = 0; mODActivity.iVddc = 0; mODActivity.iCurrentPerformanceLevel = 0; mODActivity.iActivityPercent = 0; result |= ERR_GET_ACTIVITY_FAILED; } mODClockInfo.iSize = sizeof(ADLAdapterODClockInfo); if (SAVE_CALL(ADL_Display_ODClockInfo_Get)(mGPUIndex, &mODClockInfo) != ADL_OK) { mODClockInfo.sEngineClock.iCurrentClock = 0; mODClockInfo.sEngineClock.iDefaultClock = 0; mODClockInfo.sMemoryClock.iCurrentClock = 0; mODClockInfo.sMemoryClock.iDefaultClock = 0; result |= ERR_GET_DEFAULTCLOCKINFO_FAILED; } #endif } mFeatures = ~result; return mFeatures; } void ADL::SetGPUIndex(long int* index) { if (*index >= mNrOfAdapters) { *index = 0; WRN_LOG("Adapter index out of range. Index forced to zero."); } INF_LOG("Adapter index " << *index << " choosen."); mGPUIndex = *index; UpdateData(); INF_LOG("Nr. of Performance Levels: " << mODParameters.iNumberOfPerformanceLevels); for (int i=0; i<mODParameters.iNumberOfPerformanceLevels; i++) { INF_LOG("Perf Level " << i << ": GPU " << mpODPerformanceLevels->aLevels[i].iEngineClock / 100 << "MHz Memory " << mpODPerformanceLevels->aLevels[i].iMemoryClock / 100 << "MHz Voltage " << mpODPerformanceLevels->aLevels[i].iVddc / 1000.0 << "V"); } }
[ "thorsten@phenomx4.(none)", "[email protected]" ]
[ [ [ 1, 34 ], [ 36, 196 ], [ 198, 207 ], [ 209, 212 ], [ 215, 235 ], [ 237, 251 ], [ 253, 259 ], [ 261, 264 ], [ 266, 401 ], [ 403, 517 ], [ 520, 527 ], [ 529, 529 ], [ 548, 646 ], [ 648, 664 ], [ 687, 690 ], [ 692, 697 ], [ 699, 700 ], [ 702, 702 ], [ 704, 704 ], [ 713, 716 ], [ 718, 723 ], [ 725, 725 ], [ 732, 732 ], [ 734, 734 ], [ 736, 736 ], [ 750, 757 ], [ 759, 768 ], [ 770, 778 ], [ 783, 783 ] ], [ [ 35, 35 ], [ 197, 197 ], [ 208, 208 ], [ 213, 214 ], [ 236, 236 ], [ 252, 252 ], [ 260, 260 ], [ 265, 265 ], [ 402, 402 ], [ 518, 519 ], [ 528, 528 ], [ 530, 547 ], [ 647, 647 ], [ 665, 686 ], [ 691, 691 ], [ 698, 698 ], [ 701, 701 ], [ 703, 703 ], [ 705, 712 ], [ 717, 717 ], [ 724, 724 ], [ 726, 731 ], [ 733, 733 ], [ 735, 735 ], [ 737, 749 ], [ 758, 758 ], [ 769, 769 ], [ 779, 782 ], [ 784, 806 ] ] ]
922b6285428fff4b8810574b8a55666a0f039dfb
c70941413b8f7bf90173533115c148411c868bad
/core/src/vtxButtonResource.cpp
98b4e1cf242cc1bfa27399f35d56a681c33328de
[]
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,897
cpp
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "vtxButtonResource.h" #include "vtxButtonState.h" namespace vtx { //----------------------------------------------------------------------- ButtonResource::ButtonResource(const String& id) : Resource(id) { mStates[0] = NULL; mStates[1] = NULL; mStates[2] = NULL; mStates[3] = NULL; } //----------------------------------------------------------------------- ButtonResource::~ButtonResource() { // one ButtonState object can be assigned to multiple fields of this // state array, therefore we have to make sure to not delete it twice delete mStates[0]; if(mStates[1] != mStates[0]) delete mStates[1]; if(mStates[2] != mStates[0] && mStates[2] != mStates[1]) delete mStates[2]; if(mStates[3] != mStates[0] && mStates[3] != mStates[1] && mStates[3] != mStates[2]) delete mStates[3]; } //----------------------------------------------------------------------- const String& ButtonResource::getType() const { static String type = "Button"; return type; } //----------------------------------------------------------------------- void ButtonResource::setState(ButtonState* state, const StateID& id) { mStates[id] = state; } //----------------------------------------------------------------------- ButtonState* ButtonResource::getState(const StateID& id) { return mStates[id]; } //----------------------------------------------------------------------- }
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 81 ] ] ]
3c6f1bca5b7df622a99ab064a6563f99473fa46d
4d91ca4dcaaa9167928d70b278b82c90fef384fa
/CedeCryptViewer/CedeCrypt/CedeCrypt/UIHyperLink.cpp
755dbd1b75534479ddfccd174c9c10af0500cbd2
[]
no_license
dannydraper/CedeCryptClassic
13ef0d5f03f9ff3a9a1fe4a8113e385270536a03
5f14e3c9d949493b2831710e0ce414a1df1148ec
refs/heads/master
2021-01-17T13:10:51.608070
2010-10-01T10:09:15
2010-10-01T10:09:15
63,413,327
0
0
null
null
null
null
UTF-8
C++
false
false
2,406
cpp
#include "UIHyperLink.h" UIHyperLink::UIHyperLink () { m_bMouseover = false; m_bVisible = true; m_bUseCommand = false; m_Handcursor = LoadCursor (NULL, IDC_HAND); } UIHyperLink::~UIHyperLink () { } unsigned long UIHyperLink::GetSize () { return sizeof (UIHyperLink); } void UIHyperLink::Paint (HDC hdc) { if (m_bVisible == false) { return; } PaintText (hdc); } void UIHyperLink::SetCommandMode (bool bCommand) { m_bUseCommand = bCommand; } void UIHyperLink::SetVisible (bool bVisible) { m_bVisible = bVisible; InvalidateControl (false); } void UIHyperLink::SetHyperlinkProperties (TCHAR *szFontName, int FontSize, char *szCaption, char *szTarget) { m_szTarget = (int *) szTarget; SetTextProperties (szFontName, FontSize, 4, 0, 0, szCaption, RGB (0, 0, 255)); } void UIHyperLink::NotifyMouseMove (int iXPos, int iYPos) { g_mouseXPos = iXPos; g_mouseYPos = iYPos; if (m_bVisible == false) { return; } if (IsMouseRect (true) == true) { if (m_bMouseover == false) { m_bMouseover = true; SetTextForeColor (RGB (0, 150, 255)); m_Prevcursor = SetCursor (m_Handcursor); InvalidateControl (true); SetClassLongPtr (g_hWnd, GCLP_HCURSOR, (LONG) m_Handcursor); if (m_bUseCommand == true) { PostMessage (g_hWnd, WM_UIHIGHLIGHT, (WPARAM) g_controlID, 0); } } } else { if (m_bMouseover == true) { m_bMouseover = false; SetTextForeColor (RGB (0, 0, 255)); InvalidateControl (true); SetClassLongPtr (g_hWnd, GCLP_HCURSOR, (LONG) m_Prevcursor); if (m_bUseCommand == true) { PostMessage (g_hWnd, WM_UINOHIGHLIGHT, (WPARAM) g_controlID, 0); } } } } void UIHyperLink::NotifyMouseDown () { if (m_bVisible == false) { return; } if (m_bMouseover == true) { SetTextForeColor (RGB (0, 190, 255)); InvalidateControl (true); } } void UIHyperLink::NotifyMouseUp () { if (m_bVisible == false) { return; } if (m_bMouseover == false) { SetTextForeColor (RGB (0, 0, 255)); } else { SetTextForeColor (RGB (0, 150, 255)); if (m_bUseCommand == false) { //MessageBox (g_hWnd, (char *) m_szTarget, "Target", MB_OK); ShellExecute (g_hWnd, "open", (char *) m_szTarget, NULL, NULL, SW_SHOWNORMAL); } else { PostMessage (g_hWnd, WM_UICOMMAND, (WPARAM) g_controlID, 0); } } InvalidateControl (true); }
[ "ddraper@f12373e4-23ff-6a4a-9817-e77f09f3faef" ]
[ [ [ 1, 111 ] ] ]
36345df49fbf1d0f76fadcdb404d73a7147520d7
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/multiplayer/ricochet/cl_dll/vgui_CustomObjects.cpp
22a6e199729fb3904082745c0c4ef4e0a9d14078
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
UTF-8
C++
false
false
12,970
cpp
//=========== (C) Copyright 1999 Valve, L.L.C. All rights reserved. =========== // // The copyright to the contents herein is the property of Valve, L.L.C. // The contents may be used and/or copied only with the written permission of // Valve, L.L.C., or in accordance with the terms and conditions stipulated in // the agreement/contract under which the contents have been supplied. // // Purpose: Contains implementation of various VGUI-derived objects // // $Workfile: $ // $Date: $ // //----------------------------------------------------------------------------- // $Log: $ // // $NoKeywords: $ //============================================================================= #include "VGUI_Font.h" #include "hud.h" #include "cl_util.h" #include "camera.h" #include "kbutton.h" #include "cvardef.h" #include "usercmd.h" #include "const.h" #include "camera.h" #include "in_defs.h" #include "parsemsg.h" #include "vgui_int.h" #include "vgui_TeamFortressViewport.h" #include "vgui_ServerBrowser.h" #include "vgui_LoadTGA.h" // Arrow filenames char *sArrowFilenames[] = { "arrowup", "arrowdn", "arrowlt", "arrowrt", }; // Get the name of TGA file, without a gamedir char *GetTGANameForRes(const char *pszName) { int i; char sz[256]; static char gd[256]; if (ScreenWidth < 640) i = 320; else i = 640; sprintf(sz, pszName, i); sprintf(gd, "gfx/vgui/%s.tga", sz); return gd; } //----------------------------------------------------------------------------- // Purpose: Loads a .tga file and returns a pointer to the VGUI tga object //----------------------------------------------------------------------------- BitmapTGA *LoadTGAForRes( const char* pImageName ) { BitmapTGA *pTGA; char sz[256]; sprintf(sz, "%%d_%s", pImageName); pTGA = vgui_LoadTGA(GetTGANameForRes(sz)); return pTGA; } //=========================================================== // All TFC Hud buttons are derived from this one. CommandButton::CommandButton( const char* text,int x,int y,int wide,int tall, bool bNoHighlight) : Button("",x,y,wide,tall) { m_iPlayerClass = 0; m_bNoHighlight = bNoHighlight; Init(); setText( text ); } CommandButton::CommandButton( int iPlayerClass, const char* text,int x,int y,int wide,int tall) : Button("",x,y,wide,tall) { m_iPlayerClass = iPlayerClass; m_bNoHighlight = false; Init(); setText( text ); } void CommandButton::Init( void ) { m_pSubMenu = NULL; m_pSubLabel = NULL; m_pParentMenu = NULL; // Set text color to orange setFgColor(Scheme::sc_primary1); // left align setContentAlignment( vgui::Label::a_west ); // Add the Highlight signal if (!m_bNoHighlight) addInputSignal( new CHandler_CommandButtonHighlight(this) ); // not bound to any button yet m_cBoundKey = 0; } //----------------------------------------------------------------------------- // Purpose: Prepends the button text with the current bound key // if no bound key, then a clear space ' ' instead //----------------------------------------------------------------------------- void CommandButton::RecalculateText( void ) { char szBuf[128]; if ( m_cBoundKey != 0 ) { sprintf( szBuf, " %c %s", m_cBoundKey, m_sMainText ); szBuf[MAX_BUTTON_SIZE-1] = 0; } else { // just draw a space if no key bound sprintf( szBuf, " %s", m_sMainText ); szBuf[MAX_BUTTON_SIZE-1] = 0; } Button::setText( szBuf ); } void CommandButton::setText( const char *text ) { strncpy( m_sMainText, text, MAX_BUTTON_SIZE ); m_sMainText[MAX_BUTTON_SIZE-1] = 0; RecalculateText(); } void CommandButton::setBoundKey( char boundKey ) { m_cBoundKey = boundKey; RecalculateText(); } char CommandButton::getBoundKey( void ) { return m_cBoundKey; } void CommandButton::AddSubMenu( CCommandMenu *pNewMenu ) { m_pSubMenu = pNewMenu; // Prevent this button from being pushed setMouseClickEnabled( MOUSE_LEFT, false ); } void CommandButton::UpdateSubMenus( int iAdjustment ) { if ( m_pSubMenu ) m_pSubMenu->RecalculatePositions( iAdjustment ); } void CommandButton::paint() { // Make the sub label paint the same as the button if ( m_pSubLabel ) { if ( isSelected() ) m_pSubLabel->PushDown(); else m_pSubLabel->PushUp(); } // draw armed button text in white if ( isArmed() ) { setFgColor( Scheme::sc_secondary2 ); } else { setFgColor( Scheme::sc_primary1 ); } Button::paint(); } void CommandButton::paintBackground() { if ( isArmed() ) { // Orange highlight background drawSetColor( Scheme::sc_primary2 ); drawFilledRect(0,0,_size[0],_size[1]); } // Orange Border drawSetColor( Scheme::sc_secondary1 ); drawOutlinedRect(0,0,_size[0],_size[1]); } //----------------------------------------------------------------------------- // Purpose: Highlights the current button, and all it's parent menus //----------------------------------------------------------------------------- void CommandButton::cursorEntered( void ) { // unarm all the other buttons in this menu CCommandMenu *containingMenu = getParentMenu(); if ( containingMenu ) { containingMenu->ClearButtonsOfArmedState(); // make all our higher buttons armed CCommandMenu *pCParent = containingMenu->GetParentMenu(); if ( pCParent ) { CommandButton *pParentButton = pCParent->FindButtonWithSubmenu( containingMenu ); pParentButton->cursorEntered(); } } // arm ourselves setArmed( true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CommandButton::cursorExited( void ) { // only clear ourselves if we have do not have a containing menu // only stay armed if we have a sub menu // the buttons only unarm themselves when another button is armed instead if ( !getParentMenu() || !GetSubMenu() ) { setArmed( false ); } } //----------------------------------------------------------------------------- // Purpose: Returns the command menu that the button is part of, if any // Output : CCommandMenu * //----------------------------------------------------------------------------- CCommandMenu *CommandButton::getParentMenu( void ) { return m_pParentMenu; } //----------------------------------------------------------------------------- // Purpose: Sets the menu that contains this button // Input : *pParentMenu - //----------------------------------------------------------------------------- void CommandButton::setParentMenu( CCommandMenu *pParentMenu ) { m_pParentMenu = pParentMenu; } //=========================================================== int ClassButton::IsNotValid() { // If this is the main ChangeClass button, remove it if the player's only able to be civilians if ( m_iPlayerClass == -1 ) { if (gViewPort->GetValidClasses(g_iTeamNumber) == -1) return true; return false; } // Is it an illegal class? if ((gViewPort->GetValidClasses(0) & sTFValidClassInts[ m_iPlayerClass ]) || (gViewPort->GetValidClasses(g_iTeamNumber) & sTFValidClassInts[ m_iPlayerClass ])) return true; // Only check current class if they've got autokill on bool bAutoKill = CVAR_GET_FLOAT( "hud_classautokill" ) != 0; if ( bAutoKill ) { // Is it the player's current class? if ( (gViewPort->IsRandomPC() && m_iPlayerClass == PC_RANDOM) || (!gViewPort->IsRandomPC() && (m_iPlayerClass == g_iPlayerClass)) ) return true; } return false; } //=========================================================== // Button with Class image beneath it CImageLabel::CImageLabel( const char* pImageName,int x,int y ) : Label( "", x,y ) { setContentFitted(true); m_pTGA = LoadTGAForRes(pImageName); setImage( m_pTGA ); } CImageLabel::CImageLabel( const char* pImageName,int x,int y,int wide,int tall ) : Label( "", x,y,wide,tall ) { setContentFitted(true); m_pTGA = LoadTGAForRes(pImageName); setImage( m_pTGA ); } //=========================================================== // Image size int CImageLabel::getImageWide( void ) { if( m_pTGA ) { int iXSize, iYSize; m_pTGA->getSize( iXSize, iYSize ); return iXSize; } else { return 1; } } int CImageLabel::getImageTall( void ) { if( m_pTGA ) { int iXSize, iYSize; m_pTGA->getSize( iXSize, iYSize ); return iYSize; } else { return 1; } } void CImageLabel::LoadImage(const char * pImageName) { if ( m_pTGA ) delete m_pTGA; // Load the Image m_pTGA = LoadTGAForRes(pImageName); if ( m_pTGA == NULL ) { // we didn't find a matching image file for this resolution // try to load file resolution independent char sz[256]; sprintf(sz, "%s/%s",gEngfuncs.pfnGetGameDirectory(), pImageName ); FileInputStream* fis = new FileInputStream( sz, false ); m_pTGA = new BitmapTGA(fis,true); fis->close(); } if ( m_pTGA == NULL ) return; // unable to load image int w,t; m_pTGA->getSize( w, t ); setSize( XRES (w),YRES (t) ); setImage( m_pTGA ); } //=========================================================== // Various overloaded paint functions for Custom VGUI objects void CCommandMenu::paintBackground() { // Transparent black background drawSetColor(Scheme::sc_primary3); drawFilledRect(0,0,_size[0],_size[1]); } //================================================================================= // CUSTOM SCROLLPANEL //================================================================================= CTFScrollButton::CTFScrollButton(int iArrow, const char* text,int x,int y,int wide,int tall) : CommandButton(text,x,y,wide,tall) { // Set text color to orange setFgColor(Scheme::sc_primary1); // Load in the arrow m_pTGA = LoadTGAForRes( sArrowFilenames[iArrow] ); setImage( m_pTGA ); // Highlight signal InputSignal *pISignal = new CHandler_CommandButtonHighlight(this); addInputSignal(pISignal); } void CTFScrollButton::paint( void ) { if (!m_pTGA) return; // draw armed button text in white if ( isArmed() ) { m_pTGA->setColor( Color(255,255,255, 0) ); } else { m_pTGA->setColor( Color(255,255,255, 128) ); } m_pTGA->doPaint(this); } void CTFScrollButton::paintBackground( void ) { /* if ( isArmed() ) { // Orange highlight background drawSetColor( Scheme::sc_primary2 ); drawFilledRect(0,0,_size[0],_size[1]); } // Orange Border drawSetColor( Scheme::sc_secondary1 ); drawOutlinedRect(0,0,_size[0]-1,_size[1]); */ } void CTFSlider::paintBackground( void ) { int wide,tall,nobx,noby; getPaintSize(wide,tall); getNobPos(nobx,noby); // Border drawSetColor( Scheme::sc_secondary1 ); drawOutlinedRect( 0,0,wide,tall ); if( isVertical() ) { // Nob Fill drawSetColor( Scheme::sc_primary2 ); drawFilledRect( 0,nobx,wide,noby ); // Nob Outline drawSetColor( Scheme::sc_primary1 ); drawOutlinedRect( 0,nobx,wide,noby ); } else { // Nob Fill drawSetColor( Scheme::sc_primary2 ); drawFilledRect( nobx,0,noby,tall ); // Nob Outline drawSetColor( Scheme::sc_primary1 ); drawOutlinedRect( nobx,0,noby,tall ); } } CTFScrollPanel::CTFScrollPanel(int x,int y,int wide,int tall) : ScrollPanel(x,y,wide,tall) { ScrollBar *pScrollBar = getVerticalScrollBar(); pScrollBar->setButton( new CTFScrollButton( ARROW_UP, "", 0,0,16,16 ), 0 ); pScrollBar->setButton( new CTFScrollButton( ARROW_DOWN, "", 0,0,16,16 ), 1 ); pScrollBar->setSlider( new CTFSlider(0,wide-1,wide,(tall-(wide*2))+2,true) ); pScrollBar->setPaintBorderEnabled(false); pScrollBar->setPaintBackgroundEnabled(false); pScrollBar->setPaintEnabled(false); pScrollBar = getHorizontalScrollBar(); pScrollBar->setButton( new CTFScrollButton( ARROW_LEFT, "", 0,0,16,16 ), 0 ); pScrollBar->setButton( new CTFScrollButton( ARROW_RIGHT, "", 0,0,16,16 ), 1 ); pScrollBar->setSlider( new CTFSlider(tall,0,wide-(tall*2),tall,false) ); pScrollBar->setPaintBorderEnabled(false); pScrollBar->setPaintBackgroundEnabled(false); pScrollBar->setPaintEnabled(false); } //================================================================================= // CUSTOM HANDLERS //================================================================================= void CHandler_MenuButtonOver::cursorEntered(Panel *panel) { if ( gViewPort && m_pMenuPanel ) { m_pMenuPanel->SetActiveInfo( m_iButton ); } } void CMenuHandler_StringCommandClassSelect::actionPerformed(Panel* panel) { CMenuHandler_StringCommand::actionPerformed( panel ); bool bAutoKill = CVAR_GET_FLOAT( "hud_classautokill" ) != 0; if ( bAutoKill && g_iPlayerClass != 0 ) gEngfuncs.pfnClientCmd("kill"); }
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 501 ] ] ]
f69cb9433b32b9075e7d770c4587aad60c1b5ecb
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Common/Serialize/UnitTest/serializeUtilities.h
f2d3a4047e6d92eacfd859306b083a8ff1a5b06a
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,295
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef SERIALIZE_UTILITIES_H #define SERIALIZE_UTILITIES_H #include <Common/Serialize/Packfile/hkPackfileWriter.h> // Saves and reloads the object using Reader and Writer of the provided types and performs the test using TestFunc. // TestFunc must compare two objects of type Object and return HK_SUCCESS if the objects are considered equal. template<typename Reader, typename Writer, typename Object> static void serializeTest(const Object& object, const hkClass& klass, hkResult (*TestFunc)(const Object& o1, const Object& o2) ) { hkArray<char> newBuf; { hkOstream os(newBuf); Writer writer; writer.setContents( &object, klass ); hkPackfileWriter::Options options; writer.save( os.getStreamWriter(), options ); } hkOstream("dump.txt").write( newBuf.begin(), newBuf.getSize() ); { hkIstream is(newBuf.begin(), newBuf.getSize()); Reader reader; reader.loadEntireFile( is.getStreamReader() ); Object* copy = static_cast<Object*>( reader.getContents( klass.getName() ) ); HK_TEST( TestFunc(object, *copy) == HK_SUCCESS ); } } #endif // SERIALIZE_UTILITIES_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 57 ] ] ]
3665751ae4d8f87f49f194731943ab6011449d2a
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestscrollerbar/inc/bctestscrollercase.h
1c2fb6550af3d47c252b53b623360f37fc30af15
[]
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
2,381
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: test case * */ #ifndef BCTEST_ScrollerCASE_H #define BCTEST_ScrollerCASE_H #include "bctestcase.h" class CBCTestScrollerContainer; class CCoeControl; class CBCTestScrollerView; /** * test case for various list classes */ class CBCTestScrollerCase: public CBCTestCase { public: // constructor and destructor /** * Symbian 2nd static constructor */ static CBCTestScrollerCase* NewL( CBCTestScrollerContainer* aContainer , CBCTestScrollerView* aView ); /** * Destructor */ virtual ~CBCTestScrollerCase(); public: // from CBCTestCase /** * Execute corresponding test functions for UI command * @param aCmd, UI command */ void RunL( TInt aCmd ); protected: // new functions /** * Build autotest script */ void BuildScriptL(); /** * Create control or allocate resource for test * @param aCmd UI command, maybe you need to do some work * for different outline */ void PrepareCaseL( TInt aCmd ); /** * Release resource used in test */ void ReleaseCaseL(); /** * Test functions */ void TestScroBarL(); void TestScroBarFrameL(); void TestScrollButtonL(); private: // constructor /** * C++ default constructor */ CBCTestScrollerCase( CBCTestScrollerContainer* aContainer, CBCTestScrollerView* aView ); /** * Symbian 2nd constructor */ void ConstructL(); private: // data /** * Pointer to a control, maybe you need one in your test * own */ CCoeControl* iControl; /** * Pointer to container. * not own */ CBCTestScrollerContainer* iContainer; CBCTestScrollerView* iView; }; #endif // BCTEST_ScrollerCASE_H
[ "none@none" ]
[ [ [ 1, 112 ] ] ]
65007b05bd1334181fb9339fbabf976ce7378fb2
600065575d74f6ff18107510c527fce4830b98a2
/vdubauo/src/convert_yuy2.cpp
0197924a6ac68e055d94c41b1bb13067bfb41f78
[]
no_license
chattama/vdubauo
ba129a57ac893367588ec02acf784f92d33d7d92
0bca13001debe98192c4a09a9ad38ed475775376
refs/heads/master
2021-01-20T11:19:18.169404
2009-07-17T05:13:17
2009-07-17T05:13:17
253,281
6
3
null
null
null
null
UTF-8
C++
false
false
12,749
cpp
// Avisynth v2.5. Copyright 2002 Ben Rudiak-Gould et al. // http://www.avisynth.org // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making a // combined work based on Avisynth. Thus, the terms and conditions of the GNU // General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate with // Avisynth solely through the interfaces defined in avisynth.h, regardless of the license // terms of these independent modules, and to copy and distribute the // resulting combined work under terms of your choice, provided that // every copy of the combined work is accompanied by a complete copy of // the source code of Avisynth (the version of Avisynth used to produce the // combined work), being distributed under the terms of the GNU General // Public License plus this exception. An independent module is a module // which is not derived from or based on Avisynth, such as 3rd-party filters, // import and export plugins, or graphical user interfaces. //#include "convert_yuy2.h" /***************************** * MMX code by Klaus Post * - Notes on MMX: * Fractions are one bit less than integer code, * but otherwise the algorithm is the same, except * r_y and b_y are calculated at the same time. * Order of executin has been changed much for better pairing possibilities. * It is important that the 64bit values are 8 byte-aligned * otherwise it will give a huge penalty when accessing them. * Instructions pair rather ok, instructions from the top is merged * into last part, to avoid dependency stalls. * (paired instrucions are indented by a space) *****************************/ void mmx_ConvertRGB32toYUY2(const unsigned int *src,unsigned int *dst,int src_pitch, int dst_pitch,int w, int h) { __declspec(align(8)) static const __int64 rgb_mask = 0x00ffffff00ffffff; __declspec(align(8)) static const __int64 fraction = 0x0000000000084000; //= 0x108000/2 = 0x84000 __declspec(align(8)) static const __int64 add_32 = 0x000000000000000020; //= 32 shifted 15 up __declspec(align(8)) static const __int64 rb_mask = 0x0000ffff0000ffff; //=Mask for unpacked R and B __declspec(align(8)) static const __int64 y1y2_mult = 0x0000000000004A85; __declspec(align(8)) static const __int64 fpix_add = 0x0080800000808000; __declspec(align(8)) static const __int64 fpix_mul = 0x000000282000001fb; __declspec(align(8)) static const __int64 chroma_mask = 0x000000000ff00ff00; __declspec(align(8)) static const __int64 low32_mask = 0x000000000ffffffff; // const int cyb = int(0.114*219/255*32768+0.5); // const int cyg = int(0.587*219/255*32768+0.5); // const int cyr = int(0.299*219/255*32768+0.5); // __declspec(align(8)) const __int64 cybgr_64 = (__int64)cyb|(((__int64)cyg)<<16)|(((__int64)cyr)<<32); __declspec(align(8)) const __int64 cybgr_64 = 0x000020DE40870c88; int lwidth_bytes = w<<2; // Width in bytes src+=src_pitch*(h-1); // ;Move source to bottom line (read top->bottom) #define SRC eax #define DST edi #define RGBOFFSET ecx #define YUVOFFSET edx for (int y=0;y<h;y++) { __asm { mov SRC,src mov DST,dst mov RGBOFFSET,0 mov YUVOFFSET,0 cmp RGBOFFSET,[lwidth_bytes] jge outloop ; Jump out of loop if true (width==0?? - somebody brave should remove this test) movq mm0,[SRC+RGBOFFSET] ; mm0= XXR2 G2B2 XXR1 G1B1 punpcklbw mm1,mm0 ; mm1= 0000 R100 G100 B100 movq mm4,[cybgr_64] align 16 re_enter: punpckhbw mm2,mm0 ; mm2= 0000 R200 G200 B200 movq mm3,[fraction] psrlw mm1,8 ; mm1= 0000 00R1 00G1 00B1 psrlw mm2,8 ; mm2= 0000 00R2 00G2 00B2 movq mm6,mm1 ; mm6= 0000 00R1 00G1 00B1 (shifter unit stall) pmaddwd mm1,mm4 ; mm1= v2v2 v2v2 v1v1 v1v1 y1 //(cyb*rgb[0] + cyg*rgb[1] + cyr*rgb[2] + 0x108000) movq mm7,mm2 ; mm7= 0000 00R2 00G2 00B2 movq mm0,[rb_mask] pmaddwd mm2,mm4 ; mm1= w2w2 w2w2 w1w1 w1w1 y2 //(cyb*rgbnext[0] + cyg*rgbnext[1] + cyr*rgbnext[2] + 0x108000) paddd mm1,mm3 ; Add rounding fraction paddw mm6,mm7 ; mm6 = accumulated RGB values (for b_y and r_y) paddd mm2,mm3 ; Add rounding fraction (lower dword only) movq mm4,mm1 movq mm5,mm2 pand mm1,[low32_mask] psrlq mm4,32 pand mm6,mm0 ; Clear out accumulated G-value mm6= 0000 RRRR 0000 BBBB pand mm2,[low32_mask] psrlq mm5,32 paddd mm1,mm4 ;mm1 Contains final y1 value (shifted 15 up) psllq mm6, 14 ; Shift up accumulated R and B values (<<15 in C) paddd mm2,mm5 ;mm2 Contains final y2 value (shifted 15 up) psrlq mm1,15 movq mm3,mm1 psrlq mm2,15 movq mm4,[add_32] paddd mm3,mm2 ;mm3 = y1+y2 movq mm5,[y1y2_mult] psubd mm3,mm4 ; mm3 = y1+y2-32 mm0,mm4,mm5,mm7 free movq mm0,[fpix_add] ; Constant that should be added to final UV pixel pmaddwd mm3,mm5 ; mm3=scaled_y (latency 2 cycles) movq mm4,[fpix_mul] ; Constant that should be multiplied to final UV pixel psllq mm2,16 ; mm2 Y2 shifted up (to clear fraction) mm2 ready punpckldq mm3,mm3 ; Move scaled_y to upper dword mm3=SCAL ED_Y SCAL ED_Y psubd mm6,mm3 ; mm6 = b_y and r_y (stall) psrld mm6,9 ; Shift down b_y and r_y (>>10 in C-code) por mm1,mm2 ; mm1 = 0000 0000 00Y2 00Y1 pmaddwd mm6,mm4 ; Mult b_y and r_y pxor mm2,mm2 movq mm7,[chroma_mask] paddd mm6, mm0 ; Add 0x800000 to r_y and b_y add RGBOFFSET,8 psrld mm6,9 ; Move down, so fraction is only 7 bits cmp RGBOFFSET,[lwidth_bytes] jge outloop ; Jump out of loop if true packssdw mm6,mm2 ; mm6 = 0000 0000 VVVV UUUU (7 bits fraction) (values above 0xff are saturated) psllq mm6,1 ; Move up, so fraction is 8 bit movq mm0,[SRC+RGBOFFSET] ; mm0= XXR2 G2B2 XXR1 G1B1 [From top (to get better pairing)] pand mm6,mm7 ; Clear out fractions por mm6,mm1 ; Or luma and chroma together movq mm4,[cybgr_64] ; [From top (to get better pairing)] movd [DST+YUVOFFSET],mm6 ; Store final pixel punpcklbw mm1,mm0 ; mm1= 0000 R100 G100 B100 add YUVOFFSET,4 // Two pixels (packed) jmp re_enter outloop: // Do store without loading next pixel packssdw mm6,mm2 ; mm6 = 0000 0000 VVVV UUUU (7 bits fraction) (values above 0xff are saturated) psllq mm6,1 ; Move up, so fraction is 8 bit pand mm6,mm7 ; Clear out fractions por mm1,mm6 ; Or luma and chroma together movd [DST+YUVOFFSET],mm1 ; Store final pixel } // end asm src -= src_pitch; dst += dst_pitch; } // end for y #undef SRC #undef DST #undef RGBOFFSET #undef YUVOFFSET __asm emms; } /******************************* * MMX RGB24 version *******************************/ void mmx_ConvertRGB24toYUY2(const unsigned char *src,unsigned char *dst,int src_pitch, int dst_pitch,int w, int h) { __declspec(align(8)) static const __int64 fraction = 0x0000000000084000; //= 0x108000/2 = 0x84000 __declspec(align(8)) static const __int64 add_32 = 0x000000000000000020; //= 32 shifted 15 up __declspec(align(8)) static const __int64 rb_mask = 0x0000ffff0000ffff; //=Mask for unpacked R and B __declspec(align(8)) static const __int64 y1y2_mult = 0x0000000000004A85; __declspec(align(8)) static const __int64 fpix_add = 0x0080800000808000; __declspec(align(8)) static const __int64 fpix_mul = 0x000000282000001fb; __declspec(align(8)) static const __int64 chroma_mask = 0x000000000ff00ff00; __declspec(align(8)) static const __int64 low32_mask = 0x000000000ffffffff; __declspec(align(8)) const __int64 cybgr_64 = 0x000020DE40870c88; int lwidth_bytes = w*3; // Width in bytes src+=src_pitch*(h-1); // ;Move source to bottom line (read top->bottom) #define SRC eax #define DST edi #define RGBOFFSET ecx #define YUVOFFSET edx for (int y=0;y<h;y++) { __asm { mov SRC,src mov DST,dst mov RGBOFFSET,0 mov YUVOFFSET,0 cmp RGBOFFSET,[lwidth_bytes] jge outloop ; Jump out of loop if true (width==0) movq mm0,[SRC+RGBOFFSET] ; mm0= XXXX R2G2 B2R1 G1B1 punpcklbw mm1,mm0 ; mm1= B200 R100 G100 B100 movq mm4,[cybgr_64] psrlq mm0, 24 // Compensate for RGB24 align 16 re_enter: punpcklbw mm2,mm0 ; mm2= 0000 R200 G200 B200 // high changed to low for RGB24 psrlw mm1,8 ; mm1= 0000 00R1 00G1 00B1 movq mm3,[fraction] psrlw mm2,8 ; mm2= 0000 00R2 00G2 00B2 movq mm6,mm1 ; mm6= 0000 00R1 00G1 00B1 (shifter unit stall) pmaddwd mm1,mm4 ; mm1= v2v2 v2v2 v1v1 v1v1 y1 //(cyb*rgb[0] + cyg*rgb[1] + cyr*rgb[2] + 0x108000) movq mm7,mm2 ; mm7= 0000 00R2 00G2 00B2 movq mm0,[rb_mask] pmaddwd mm2,mm4 ; mm1= w2w2 w2w2 w1w1 w1w1 y2 //(cyb*rgbnext[0] + cyg*rgbnext[1] + cyr*rgbnext[2] + 0x108000) paddd mm1,mm3 ; Add rounding fraction paddw mm6,mm7 ; mm6 = accumulated RGB values (for b_y and r_y) paddd mm2,mm3 ; Add rounding fraction (lower dword only) movq mm4,mm1 movq mm5,mm2 pand mm1,[low32_mask] psrlq mm4,32 pand mm6,mm0 ; Clear out accumulated G-value mm6= 0000 RRRR 0000 BBBB pand mm2,[low32_mask] psrlq mm5,32 paddd mm1,mm4 ;mm1 Contains final y1 value (shifted 15 up) psllq mm6, 14 ; Shift up accumulated R and B values (<<15 in C) paddd mm2,mm5 ;mm2 Contains final y2 value (shifted 15 up) psrlq mm1,15 movq mm3,mm1 psrlq mm2,15 movq mm4,[add_32] paddd mm3,mm2 ;mm3 = y1+y2 movq mm5,[y1y2_mult] psubd mm3,mm4 ; mm3 = y1+y2-32 mm0,mm4,mm5,mm7 free movq mm0,[fpix_add] ; Constant that should be added to final UV pixel pmaddwd mm3,mm5 ; mm3=scaled_y (latency 2 cycles) movq mm4,[fpix_mul] ; Constant that should be multiplied to final UV pixel psllq mm2,16 ; mm2 Y2 shifted up (to clear fraction) mm2 ready punpckldq mm3,mm3 ; Move scaled_y to upper dword mm3=SCAL ED_Y SCAL ED_Y psubd mm6,mm3 ; mm6 = b_y and r_y (stall) psrld mm6,9 ; Shift down b_y and r_y (>>10 in C-code) por mm1,mm2 ; mm1 = 0000 0000 00Y2 00Y1 pmaddwd mm6,mm4 ; Mult b_y and r_y pxor mm2,mm2 movq mm7,[chroma_mask] paddd mm6, mm0 ; Add 0x800000 to r_y and b_y add RGBOFFSET,6 ; Only change for RGB24! psrld mm6,9 ; Move down, so fraction is only 7 bits cmp RGBOFFSET,[lwidth_bytes] jge outloop ; Jump out of loop if true packssdw mm6,mm2 ; mm6 = 0000 0000 VVVV UUUU (7 bits fraction) (values above 0xff are saturated) psllq mm6,1 ; Move up, so fraction is 8 bit movq mm0,[SRC+RGBOFFSET] ; mm0= XXR2 G2B2 XXR1 G1B1 [From top (to get better pairing)] pand mm6,mm7 ; Clear out fractions por mm6,mm1 ; Or luma and chroma together movq mm4,[cybgr_64] ; [From top (to get better pairing)] movd [DST+YUVOFFSET],mm6 ; Store final pixel punpcklbw mm1,mm0 ; mm1= 0000 R100 G100 B100 add YUVOFFSET,4 // Two pixels (packed) psrlq mm0, 24 // Compensate for RGB24 jmp re_enter outloop: // Do store without loading next pixel packssdw mm6,mm2 ; mm6 = 0000 0000 VVVV UUUU (7 bits fraction) (values above 0xff are saturated) psllq mm6,1 ; Move up, so fraction is 8 bit pand mm6,mm7 ; Clear out fractions por mm1,mm6 ; Or luma and chroma together movd [DST+YUVOFFSET],mm1 ; Store final pixel } // end asm src -= src_pitch; dst += dst_pitch; } // end for y #undef SRC #undef DST #undef RGBOFFSET #undef YUVOFFSET __asm emms; }
[ [ [ 1, 281 ] ] ]
b69c0132aa9b20436f3d142aabaf99f0b96b80b4
c0ca8ca02ab7137d9f1a10e1b74395fb199d488e
/WPILib/Encoder.cpp
afd4f5c20ed9999debcfa893fa6c1831a99285be
[]
no_license
dminion/Whitney-High-School-FIRST-Robotics
7f8843328280f97e1c8dd81d7a0051fd9d8fef30
a4be12908fe0a39fb585ba5268c6e91178b2ad87
refs/heads/master
2021-01-23T22:42:55.899519
2011-01-22T22:36:07
2011-01-22T22:36:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,494
cpp
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */ /*----------------------------------------------------------------------------*/ #include "Encoder.h" #include "DigitalInput.h" #include "Resource.h" #include "Utility.h" #include "WPIStatus.h" static Resource *quadEncoders = NULL; /** * Common initialization code for Encoders. * This code allocates resources for Encoders and is common to all constructors. * @param reverseDirection If true, counts down instead of up (this is all relative) * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then * a counter object will be used and the returned value will either exactly match the spec'd count * or be double (2x) the spec'd count. */ void Encoder::InitEncoder(bool reverseDirection, EncodingType encodingType) { m_encodingType = encodingType; switch (encodingType) { case k4X: Resource::CreateResourceObject(&quadEncoders, tEncoder::kNumSystems); //TODO: need to check for errors here m_index = quadEncoders->Allocate(); m_encoder = new tEncoder(m_index, &status); m_encoder->writeConfig_ASource_Module(m_aSource->GetModuleForRouting(), &status); m_encoder->writeConfig_ASource_Channel(m_aSource->GetChannelForRouting(), &status); m_encoder->writeConfig_ASource_AnalogTrigger(m_aSource->GetAnalogTriggerForRouting(), &status); m_encoder->writeConfig_BSource_Module(m_bSource->GetModuleForRouting(), &status); m_encoder->writeConfig_BSource_Channel(m_bSource->GetChannelForRouting(), &status); m_encoder->writeConfig_BSource_AnalogTrigger(m_bSource->GetAnalogTriggerForRouting(), &status); m_encoder->strobeReset(&status); m_encoder->writeConfig_Reverse(reverseDirection, &status); m_encoder->writeTimerConfig_AverageSize(4, &status); m_counter = NULL; break; case k1X: case k2X: m_counter = new Counter(m_encodingType, m_aSource, m_bSource, reverseDirection); break; } m_distancePerPulse = 1.0; wpi_assertCleanStatus(status); } /** * Encoder constructor. * Construct a Encoder given a and b modules and channels fully specified. * @param aSlot The a channel digital input module. * @param aChannel The a channel digital input channel. * @param bSlot The b channel digital input module. * @param bChannel The b channel digital input channel. * @param reverseDirection represents the orientation of the encoder and inverts the output values * if necessary so forward represents positive values. * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then * a counter object will be used and the returned value will either exactly match the spec'd count * or be double (2x) the spec'd count. */ Encoder::Encoder(UINT32 aSlot, UINT32 aChannel, UINT32 bSlot, UINT32 bChannel, bool reverseDirection, EncodingType encodingType) { m_aSource = new DigitalInput(aSlot, aChannel); m_bSource = new DigitalInput(bSlot, bChannel); InitEncoder(reverseDirection, encodingType); m_allocatedASource = true; m_allocatedBSource = true; } /** * Encoder constructor. * Construct a Encoder given a and b channels assuming the default module. * @param aChannel The a channel digital input channel. * @param bChannel The b channel digital input channel. * @param reverseDirection represents the orientation of the encoder and inverts the output values * if necessary so forward represents positive values. * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then * a counter object will be used and the returned value will either exactly match the spec'd count * or be double (2x) the spec'd count. */ Encoder::Encoder(UINT32 aChannel, UINT32 bChannel, bool reverseDirection, EncodingType encodingType) { m_aSource = new DigitalInput(aChannel); m_bSource = new DigitalInput(bChannel); InitEncoder(reverseDirection, encodingType); m_allocatedASource = true; m_allocatedBSource = true; } /** * Encoder constructor. * Construct a Encoder given a and b channels as digital inputs. This is used in the case * where the digital inputs are shared. The Encoder class will not allocate the digital inputs * and assume that they already are counted. * @param aSource The source that should be used for the a channel. * @param bSource the source that should be used for the b channel. * @param reverseDirection represents the orientation of the encoder and inverts the output values * if necessary so forward represents positive values. * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then * a counter object will be used and the returned value will either exactly match the spec'd count * or be double (2x) the spec'd count. */ Encoder::Encoder(DigitalSource *aSource, DigitalSource *bSource, bool reverseDirection, EncodingType encodingType) { m_aSource = aSource; m_bSource = bSource; m_allocatedASource = false; m_allocatedBSource = false; if (m_aSource == NULL || m_bSource == NULL) wpi_fatal(NullParameter); else InitEncoder(reverseDirection, encodingType); } /** * Encoder constructor. * Construct a Encoder given a and b channels as digital inputs. This is used in the case * where the digital inputs are shared. The Encoder class will not allocate the digital inputs * and assume that they already are counted. * @param aSource The source that should be used for the a channel. * @param bSource the source that should be used for the b channel. * @param reverseDirection represents the orientation of the encoder and inverts the output values * if necessary so forward represents positive values. * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then * a counter object will be used and the returned value will either exactly match the spec'd count * or be double (2x) the spec'd count. */ Encoder::Encoder(DigitalSource &aSource, DigitalSource &bSource, bool reverseDirection, EncodingType encodingType) { m_aSource = &aSource; m_bSource = &bSource; m_allocatedASource = false; m_allocatedBSource = false; InitEncoder(reverseDirection, encodingType); } /** * Free the resources for an Encoder. * Frees the FPGA resources associated with an Encoder. */ Encoder::~Encoder() { if (m_allocatedASource) delete m_aSource; if (m_allocatedBSource) delete m_bSource; if (m_counter) { delete m_counter; } else { quadEncoders->Free(m_index); delete m_encoder; } } /** * Start the Encoder. * Starts counting pulses on the Encoder device. */ void Encoder::Start() { if (m_counter) m_counter->Start(); else { m_encoder->writeConfig_Enable(1, &status); wpi_assertCleanStatus(status); } } /** * Stops counting pulses on the Encoder device. The value is not changed. */ void Encoder::Stop() { if (m_counter) m_counter->Stop(); else { m_encoder->writeConfig_Enable(0, &status); wpi_assertCleanStatus(status); } } /** * Gets the raw value from the encoder. * The raw value is the actual count unscaled by the 1x, 2x, or 4x scale * factor. * @return Current raw count from the encoder */ INT32 Encoder::GetRaw() { INT32 value; if (m_counter) value = m_counter->Get(); else { value = m_encoder->readOutput_Value(&status); wpi_assertCleanStatus(status); } return value; } /** * Gets the current count. * Returns the current count on the Encoder. * This method compensates for the decoding type. * * @return Current count from the Encoder adjusted for the 1x, 2x, or 4x scale factor. */ INT32 Encoder::Get() { return (INT32) (GetRaw() * DecodingScaleFactor()); } /** * Reset the Encoder distance to zero. * Resets the current count to zero on the encoder. */ void Encoder::Reset() { if (m_counter) m_counter->Reset(); else { m_encoder->strobeReset(&status); wpi_assertCleanStatus(status); } } /** * Returns the period of the most recent pulse. * Returns the period of the most recent Encoder pulse in seconds. * This method compenstates for the decoding type. * * @deprecated Use GetRate() in favor of this method. This returns unscaled periods and GetRate() scales using value from SetDistancePerPulse(). * * @return Period in seconds of the most recent pulse. */ double Encoder::GetPeriod() { double measuredPeriod; if (m_counter) { measuredPeriod = m_counter->GetPeriod(); } else { tEncoder::tTimerOutput output = m_encoder->readTimerOutput(&status); double value; if (output.Stalled) { // Return infinity double zero = 0.0; value = 1.0 / zero; } else { // output.Period is a fixed point number that counts by 2 (24 bits, 25 integer bits) value = (double)(output.Period << 1) / (double)output.Count; } wpi_assertCleanStatus(status); measuredPeriod = value * 1.0e-6; } return measuredPeriod / DecodingScaleFactor(); } /** * Sets the maximum period for stopped detection. * Sets the value that represents the maximum period of the Encoder before it will assume * that the attached device is stopped. This timeout allows users to determine if the wheels or * other shaft has stopped rotating. * This method compensates for the decoding type. * * @deprecated Use SetMinRate() in favor of this method. This takes unscaled periods and SetMinRate() scales using value from SetDistancePerPulse(). * * @param maxPeriod The maximum time between rising and falling edges before the FPGA will * report the device stopped. This is expressed in seconds. */ void Encoder::SetMaxPeriod(double maxPeriod) { if (m_counter) { m_counter->SetMaxPeriod(maxPeriod * DecodingScaleFactor()); } else { m_encoder->writeTimerConfig_StallPeriod((UINT32)(maxPeriod * 1.0e6 * DecodingScaleFactor()), &status); wpi_assertCleanStatus(status); } } /** * Determine if the encoder is stopped. * Using the MaxPeriod value, a boolean is returned that is true if the encoder is considered * stopped and false if it is still moving. A stopped encoder is one where the most recent pulse * width exceeds the MaxPeriod. * @return True if the encoder is considered stopped. */ bool Encoder::GetStopped() { if (m_counter) { return m_counter->GetStopped(); } else { bool value = m_encoder->readTimerOutput_Stalled(&status) != 0; wpi_assertCleanStatus(status); return value; } } /** * The last direction the encoder value changed. * @return The last direction the encoder value changed. */ bool Encoder::GetDirection() { if (m_counter) { return m_counter->GetDirection(); } else { bool value = m_encoder->readOutput_Direction(&status); wpi_assertCleanStatus(status); return value; } } /** * The scale needed to convert a raw counter value into a number of encoder pulses. */ double Encoder::DecodingScaleFactor() { switch (m_encodingType) { case k1X: return 1.0; case k2X: return 0.5; case k4X: return 0.25; default: return 0.0; } } /** * Get the distance the robot has driven since the last reset. * * @return The distance driven since the last reset as scaled by the value from SetDistancePerPulse(). */ double Encoder::GetDistance() { return GetRaw() * DecodingScaleFactor() * m_distancePerPulse; } /** * Get the current rate of the encoder. * Units are distance per second as scaled by the value from SetDistancePerPulse(). * * @return The current rate of the encoder. */ double Encoder::GetRate() { return (m_distancePerPulse / GetPeriod()); } /** * Set the minimum rate of the device before the hardware reports it stopped. * * @param minRate The minimum rate. The units are in distance per second as scaled by the value from SetDistancePerPulse(). */ void Encoder::SetMinRate(double minRate) { SetMaxPeriod(m_distancePerPulse / minRate); } /** * Set the distance per pulse for this encoder. * This sets the multiplier used to determine the distance driven based on the count value * from the encoder. * Do not include the decoding type in this scale. The library already compensates for the decoding type. * Set this value based on the encoder's rated Pulses per Revolution and * factor in gearing reductions following the encoder shaft. * This distance can be in any units you like, linear or angular. * * @param distancePerPulse The scale factor that will be used to convert pulses to useful units. */ void Encoder::SetDistancePerPulse(double distancePerPulse) { m_distancePerPulse = distancePerPulse; } /** * Set the direction sensing for this encoder. * This sets the direction sensing on the encoder so that it could count in the correct * software direction regardless of the mounting. * @param reverseDirection true if the encoder direction should be reversed */ void Encoder::SetReverseDirection(bool reverseDirection) { if (m_counter) { m_counter->SetReverseDirection(reverseDirection); } else { m_encoder->writeConfig_Reverse(reverseDirection, &status); wpi_assertCleanStatus(status); } }
[ "WHS@.(none)" ]
[ [ [ 1, 431 ] ] ]
d2d23aa33d0c6fd0409907a44bbfaa2b1c5672fc
3c2dc480d637cc856a1be74be1bbc197a0b24bd2
/s34Size.h
f067e7959ce693b8a4a33832165ac93302a46d12
[]
no_license
cjus/s34mme
d49ff5ede63fbae83fa0694eeea66b0024a4b72b
77d372c9f55d2053c11e41bdfd9d2f074329e451
refs/heads/master
2020-04-14T19:30:39.690545
2010-09-05T18:23:37
2010-09-05T18:23:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,759
h
/********************************************************************* * S E C T I O N 3 4 * M U L T I M E D I A E X T E N T I O N L I B R A R Y D L L * * S34Size.h * Header file for the CS34Size class * * SIZE class based on the MFC CSize class * * This source code contains trade secrets and copyrighted materials, * which is the intellectual property of Section34 Inc. * * This source code is being licensed to SelvaSoft Inc. under contract * for a limited time only, for the purpose of evaluation and early * business development. This code may not be used in an actual * project or service. Reverse engineering and the removal of this * header is expressly prohibited. * * Unauthorized use, copying or distribution is a violation of U.S. * and international laws and is strictly prohibited. * * Send inquires to: [email protected] or contract the address * or phone number shown below. * * (c)1998-99 Section34 Inc. * 5250 Colodny Drive, #5 * Agoura Hills, CA 91301 * 818 371-5785 * *********************************************************************/ #if !defined(AFX_SIZE_H__3BD67537_FE00_11D2_96B8_00A0C982B57D__INCLUDED_) #define AFX_SIZE_H__3BD67537_FE00_11D2_96B8_00A0C982B57D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifdef DLL_EXPORTS #define DLL_EXP __declspec(dllexport) #else #define DLL_EXP __declspec(dllimport) #endif class DLL_EXP CS34Size { public: int cx; int cy; CS34Size(); ~CS34Size(); CS34Size(int NewX, int NewY) { cx = NewX; cy = NewY; } CS34Size(CS34Size &size) { cx = size.cx; cy = size.cy; } }; #endif // !defined(AFX_SIZE_H__3BD67537_FE00_11D2_96B8_00A0C982B57D__INCLUDED_)
[ [ [ 1, 57 ] ] ]
8a5517fa6fd5dd39c9e289e5cb7f89d5fe38d55c
5fb9b06a4bf002fc851502717a020362b7d9d042
/developertools/GumpEditor/diagram/DiagramButton.h.bak
d23fce80b9fd4c4cfa47b016b825e3b4578546c3
[]
no_license
bravesoftdz/iris-svn
8f30b28773cf55ecf8951b982370854536d78870
c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4
refs/heads/master
2021-12-05T18:32:54.525624
2006-08-21T13:10:54
2006-08-21T13:10:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
475
bak
#pragma once #include "DiagramEditor/DiagramEntity.h" #include "ButtonPropertyDlg.h" // CDiagramButton window class CDiagramButton : public CDiagramEntity { // Construction public: CDiagramButton(); static CDiagramEntity* CreateFromString( XML::Node* node ); // Overrides virtual CDiagramEntity* Clone(); virtual void Draw( CDC* dc, CRect rect ); virtual CString Export( UINT format = 0 ); private: CButtonPropertyDlg m_dlg; };
[ "sience@a725d9c3-d2eb-0310-b856-fa980ef11a19" ]
[ [ [ 1, 27 ] ] ]
97305b9e7f5cdc8ea59518b2caa37c15848839f7
a0155e192c9dc2029b231829e3db9ba90861f956
/MFFilterICE.GUI/stdafx.h
9e9462ba7aa0260fa6abe241c1fa9bfcf6543665
[]
no_license
zeha/mailfilter
d2de4aaa79bed2073cec76c93768a42068cfab17
898dd4d4cba226edec566f4b15c6bb97e79f8001
refs/heads/master
2021-01-22T02:03:31.470739
2010-08-12T23:51:35
2010-08-12T23:51:35
81,022,257
0
0
null
null
null
null
UTF-8
C++
false
false
2,062
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #pragma once #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. #define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif #ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. #define _WIN32_WINNT 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif #ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif #ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. #define _WIN32_IE 0x0400 // Change this to the appropriate value to target IE 5.0 or later. #endif #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxdisp.h> // MFC Automation classes #include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include <afxsock.h> // MFC socket extensions #include <afxdlgs.h> #include <stdio.h> #include <string> #include <string.h> #include <iostream> #include <vector> #include <algorithm>
[ [ [ 1, 53 ] ] ]
ab837fc1e1b19216bef068aee8294174e6a5ed17
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/misc/pre90s/d_flstory.cpp
4e07f2106f04b958c7e9d74560686ca2d46032bd
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
45,028
cpp
// FB Alpha Fairyland Story driver module // Based on MAME driver by Nicola Salmoria, Gareth Hall, and Takahiro Nog // Missing MSM5232 sound #include "tiles_generic.h" #include "../../taito/taito_m68705.h" #include "driver.h" #include "dac.h" extern "C" { #include "ay8910.h" } static unsigned char *AllMem; static unsigned char *MemEnd; static unsigned char *AllRam; static unsigned char *RamEnd; static unsigned char *DrvZ80ROM0; static unsigned char *DrvZ80ROM1; static unsigned char *DrvGfxROM0; static unsigned char *DrvGfxROM1; static unsigned char *DrvMcuROM; static unsigned char *DrvZ80RAM0; static unsigned char *DrvZ80RAM1; static unsigned char *DrvVidRAM; static unsigned char *DrvSprRAM; static unsigned char *DrvPalRAM; static unsigned char *DrvMcuRAM; static unsigned int *DrvPalette; static unsigned char DrvRecalc; static short *pAY8910Buffer[3]; static unsigned char DrvJoy1[8]; static unsigned char DrvJoy2[8]; static unsigned char DrvJoy3[8]; static unsigned char DrvJoy4[8]; static unsigned char DrvJoy5[8]; static unsigned char DrvDips[3]; static unsigned char DrvInputs[5]; static unsigned char DrvReset; static unsigned char *flipscreen; static unsigned char *soundlatch; static unsigned char snd_data; static unsigned char snd_flag; static int nmi_enable; static int pending_nmi; static int char_bank; static int mcu_select; static int select_game; static struct BurnInputInfo FlstoryInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvJoy1 + 4, "p1 coin" }, {"P1 Start", BIT_DIGITAL, DrvJoy1 + 0, "p1 start" }, {"P1 Left", BIT_DIGITAL, DrvJoy2 + 2, "p1 left" }, {"P1 Right", BIT_DIGITAL, DrvJoy2 + 3, "p1 right" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy2 + 0, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy2 + 1, "p1 fire 2" }, {"P2 Coin", BIT_DIGITAL, DrvJoy1 + 5, "p2 coin" }, {"P2 Start", BIT_DIGITAL, DrvJoy1 + 1, "p2 start" }, {"P2 Left", BIT_DIGITAL, DrvJoy3 + 2, "p2 left" }, {"P2 Right", BIT_DIGITAL, DrvJoy3 + 3, "p2 right" }, {"P2 Button 1", BIT_DIGITAL, DrvJoy3 + 0, "p2 fire 1" }, {"P2 Button 2", BIT_DIGITAL, DrvJoy3 + 1, "p2 fire 2" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Service", BIT_DIGITAL, DrvJoy1 + 2, "service" }, {"Tilt", BIT_DIGITAL, DrvJoy1 + 3, "tilt" }, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, {"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" }, {"Dip C", BIT_DIPSWITCH, DrvDips + 2, "dip" }, }; STDINPUTINFO(Flstory) static struct BurnInputInfo Onna34roInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvJoy1 + 4, "p1 coin" }, {"P1 Start", BIT_DIGITAL, DrvJoy1 + 0, "p1 start" }, {"P1 Up", BIT_DIGITAL, DrvJoy2 + 5, "p1 up" }, {"P1 Down", BIT_DIGITAL, DrvJoy2 + 4, "p1 down" }, {"P1 Left", BIT_DIGITAL, DrvJoy2 + 2, "p1 left" }, {"P1 Right", BIT_DIGITAL, DrvJoy2 + 3, "p1 right" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy2 + 0, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy2 + 1, "p1 fire 2" }, {"P2 Coin", BIT_DIGITAL, DrvJoy1 + 5, "p2 coin" }, {"P2 Start", BIT_DIGITAL, DrvJoy1 + 1, "p2 start" }, {"P2 Up", BIT_DIGITAL, DrvJoy3 + 5, "p2 up" }, {"P2 Down", BIT_DIGITAL, DrvJoy3 + 4, "p2 down" }, {"P2 Left", BIT_DIGITAL, DrvJoy3 + 2, "p2 left" }, {"P2 Right", BIT_DIGITAL, DrvJoy3 + 3, "p2 right" }, {"P2 Button 1", BIT_DIGITAL, DrvJoy3 + 0, "p2 fire 1" }, {"P2 Button 2", BIT_DIGITAL, DrvJoy3 + 1, "p2 fire 2" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Service", BIT_DIGITAL, DrvJoy1 + 2, "service" }, {"Tilt", BIT_DIGITAL, DrvJoy1 + 3, "tilt" }, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, {"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" }, {"Dip C", BIT_DIPSWITCH, DrvDips + 2, "dip" }, }; STDINPUTINFO(Onna34ro) static struct BurnInputInfo VictnineInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvJoy1 + 4, "p1 coin" }, {"P1 Start", BIT_DIGITAL, DrvJoy1 + 0, "p1 start" }, {"P1 Up", BIT_DIGITAL, DrvJoy2 + 5, "p1 up" }, {"P1 Down", BIT_DIGITAL, DrvJoy2 + 4, "p1 down" }, {"P1 Left", BIT_DIGITAL, DrvJoy2 + 2, "p1 left" }, {"P1 Right", BIT_DIGITAL, DrvJoy2 + 3, "p1 right" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy2 + 0, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy2 + 1, "p1 fire 2" }, {"P1 Button 3", BIT_DIGITAL, DrvJoy4 + 2, "p1 fire 3" }, {"P1 Button 4", BIT_DIGITAL, DrvJoy4 + 3, "p1 fire 4" }, {"P1 Button 5", BIT_DIGITAL, DrvJoy4 + 4, "p1 fire 5" }, {"P1 Button 6", BIT_DIGITAL, DrvJoy4 + 5, "p1 fire 6" }, {"P2 Coin", BIT_DIGITAL, DrvJoy1 + 5, "p2 coin" }, {"P2 Start", BIT_DIGITAL, DrvJoy1 + 1, "p2 start" }, {"P2 Up", BIT_DIGITAL, DrvJoy3 + 5, "p2 up" }, {"P2 Down", BIT_DIGITAL, DrvJoy3 + 4, "p2 down" }, {"P2 Left", BIT_DIGITAL, DrvJoy3 + 2, "p2 left" }, {"P2 Right", BIT_DIGITAL, DrvJoy3 + 3, "p2 right" }, {"P2 Button 1", BIT_DIGITAL, DrvJoy3 + 0, "p2 fire 1" }, {"P2 Button 2", BIT_DIGITAL, DrvJoy3 + 1, "p2 fire 2" }, {"P2 Button 3", BIT_DIGITAL, DrvJoy5 + 2, "p2 fire 3" }, {"P2 Button 4", BIT_DIGITAL, DrvJoy5 + 3, "p2 fire 4" }, {"P2 Button 5", BIT_DIGITAL, DrvJoy5 + 4, "p2 fire 5" }, {"P2 Button 6", BIT_DIGITAL, DrvJoy5 + 5, "p2 fire 6" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Service", BIT_DIGITAL, DrvJoy1 + 2, "service" }, {"Tilt", BIT_DIGITAL, DrvJoy1 + 3, "tilt" }, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, {"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" }, {"Dip C", BIT_DIPSWITCH, DrvDips + 2, "dip" }, }; STDINPUTINFO(Victnine) static struct BurnDIPInfo FlstoryDIPList[]= { {0x0f, 0xff, 0xff, 0xec, NULL }, {0x10, 0xff, 0xff, 0x00, NULL }, {0x11, 0xff, 0xff, 0xf8, NULL }, {0 , 0xfe, 0 , 4, "Bonus Life" }, {0x0f, 0x01, 0x03, 0x00, "30000 100000" }, {0x0f, 0x01, 0x03, 0x01, "30000 150000" }, {0x0f, 0x01, 0x03, 0x02, "50000 150000" }, {0x0f, 0x01, 0x03, 0x03, "70000 150000" }, {0 , 0xfe, 0 , 2, "Free Play" }, {0x0f, 0x01, 0x04, 0x04, "Off" }, {0x0f, 0x01, 0x04, 0x00, "On" }, {0 , 0xfe, 0 , 4, "Lives" }, {0x0f, 0x01, 0x18, 0x08, "3" }, {0x0f, 0x01, 0x18, 0x10, "4" }, {0x0f, 0x01, 0x18, 0x18, "5" }, {0x0f, 0x01, 0x18, 0x00, "Infinite (Cheat)" }, {0 , 0xfe, 0 , 2, "Debug Mode" }, {0x0f, 0x01, 0x20, 0x20, "Off" }, {0x0f, 0x01, 0x20, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Flip Screen" }, {0x0f, 0x01, 0x40, 0x40, "Off" }, {0x0f, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Cabinet" }, {0x0f, 0x01, 0x80, 0x80, "Upright" }, {0x0f, 0x01, 0x80, 0x00, "Cocktail" }, {0 , 0xfe, 0 , 16, "Coin A" }, {0x10, 0x01, 0x0f, 0x0f, "9 Coins 1 Credits" }, {0x10, 0x01, 0x0f, 0x0e, "8 Coins 1 Credits" }, {0x10, 0x01, 0x0f, 0x0d, "7 Coins 1 Credits" }, {0x10, 0x01, 0x0f, 0x0c, "6 Coins 1 Credits" }, {0x10, 0x01, 0x0f, 0x0b, "5 Coins 1 Credits" }, {0x10, 0x01, 0x0f, 0x0a, "4 Coins 1 Credits" }, {0x10, 0x01, 0x0f, 0x09, "3 Coins 1 Credits" }, {0x10, 0x01, 0x0f, 0x08, "2 Coins 1 Credits" }, {0x10, 0x01, 0x0f, 0x00, "1 Coin 1 Credits" }, {0x10, 0x01, 0x0f, 0x01, "1 Coin 2 Credits" }, {0x10, 0x01, 0x0f, 0x02, "1 Coin 3 Credits" }, {0x10, 0x01, 0x0f, 0x03, "1 Coin 4 Credits" }, {0x10, 0x01, 0x0f, 0x04, "1 Coin 5 Credits" }, {0x10, 0x01, 0x0f, 0x05, "1 Coin 6 Credits" }, {0x10, 0x01, 0x0f, 0x06, "1 Coin 7 Credits" }, {0x10, 0x01, 0x0f, 0x07, "1 Coin 8 Credits" }, {0 , 0xfe, 0 , 16, "Coin B" }, {0x10, 0x01, 0xf0, 0xf0, "9 Coins 1 Credits" }, {0x10, 0x01, 0xf0, 0xe0, "8 Coins 1 Credits" }, {0x10, 0x01, 0xf0, 0xd0, "7 Coins 1 Credits" }, {0x10, 0x01, 0xf0, 0xc0, "6 Coins 1 Credits" }, {0x10, 0x01, 0xf0, 0xb0, "5 Coins 1 Credits" }, {0x10, 0x01, 0xf0, 0xa0, "4 Coins 1 Credits" }, {0x10, 0x01, 0xf0, 0x90, "3 Coins 1 Credits" }, {0x10, 0x01, 0xf0, 0x80, "2 Coins 1 Credits" }, {0x10, 0x01, 0xf0, 0x00, "1 Coin 1 Credits" }, {0x10, 0x01, 0xf0, 0x10, "1 Coin 2 Credits" }, {0x10, 0x01, 0xf0, 0x20, "1 Coin 3 Credits" }, {0x10, 0x01, 0xf0, 0x30, "1 Coin 4 Credits" }, {0x10, 0x01, 0xf0, 0x40, "1 Coin 5 Credits" }, {0x10, 0x01, 0xf0, 0x50, "1 Coin 6 Credits" }, {0x10, 0x01, 0xf0, 0x60, "1 Coin 7 Credits" }, {0x10, 0x01, 0xf0, 0x70, "1 Coin 8 Credits" }, {0 , 0xfe, 0 , 2, "Allow Continue" }, {0x11, 0x01, 0x08, 0x00, "No" }, {0x11, 0x01, 0x08, 0x08, "Yes" }, {0 , 0xfe, 0 , 2, "Attract Animation" }, {0x11, 0x01, 0x10, 0x00, "Off" }, {0x11, 0x01, 0x10, 0x10, "On" }, {0 , 0xfe, 0 , 2, "Leave Off" }, {0x11, 0x01, 0x20, 0x20, "Off" }, {0x11, 0x01, 0x20, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Invulnerability (Cheat)" }, {0x11, 0x01, 0x40, 0x40, "Off" }, {0x11, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Coin Slots" }, {0x11, 0x01, 0x80, 0x00, "1" }, {0x11, 0x01, 0x80, 0x80, "2" }, }; STDDIPINFO(Flstory) static struct BurnDIPInfo Onna34roDIPList[]= { {0x13, 0xff, 0xff, 0xe0, NULL }, {0x14, 0xff, 0xff, 0x00, NULL }, {0x15, 0xff, 0xff, 0x80, NULL }, {0 , 0xfe, 0 , 4, "Bonus Life" }, {0x13, 0x01, 0x03, 0x00, "200000 200000" }, {0x13, 0x01, 0x03, 0x01, "200000 300000" }, {0x13, 0x01, 0x03, 0x02, "100000 200000" }, {0x13, 0x01, 0x03, 0x03, "200000 100000" }, {0 , 0xfe, 0 , 2, "Free Play" }, {0x13, 0x01, 0x04, 0x00, "Off" }, {0x13, 0x01, 0x04, 0x04, "On" }, {0 , 0xfe, 0 , 4, "Lives" }, {0x13, 0x01, 0x18, 0x10, "1" }, {0x13, 0x01, 0x18, 0x08, "2" }, {0x13, 0x01, 0x18, 0x00, "3" }, {0x13, 0x01, 0x18, 0x18, "Endless (Cheat)" }, {0 , 0xfe, 0 , 2, "Flip Screen" }, {0x13, 0x01, 0x40, 0x40, "Off" }, {0x13, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Cabinet" }, {0x13, 0x01, 0x80, 0x80, "Upright" }, {0x13, 0x01, 0x80, 0x00, "Cocktail" }, {0 , 0xfe, 0 , 16, "Coin A" }, {0x14, 0x01, 0x0f, 0x0f, "9 Coins 1 Credits" }, {0x14, 0x01, 0x0f, 0x0e, "8 Coins 1 Credits" }, {0x14, 0x01, 0x0f, 0x0d, "7 Coins 1 Credits" }, {0x14, 0x01, 0x0f, 0x0c, "6 Coins 1 Credits" }, {0x14, 0x01, 0x0f, 0x0b, "5 Coins 1 Credits" }, {0x14, 0x01, 0x0f, 0x0a, "4 Coins 1 Credits" }, {0x14, 0x01, 0x0f, 0x09, "3 Coins 1 Credits" }, {0x14, 0x01, 0x0f, 0x08, "2 Coins 1 Credits" }, {0x14, 0x01, 0x0f, 0x00, "1 Coin 1 Credits" }, {0x14, 0x01, 0x0f, 0x01, "1 Coin 2 Credits" }, {0x14, 0x01, 0x0f, 0x02, "1 Coin 3 Credits" }, {0x14, 0x01, 0x0f, 0x03, "1 Coin 4 Credits" }, {0x14, 0x01, 0x0f, 0x04, "1 Coin 5 Credits" }, {0x14, 0x01, 0x0f, 0x05, "1 Coin 6 Credits" }, {0x14, 0x01, 0x0f, 0x06, "1 Coin 7 Credits" }, {0x14, 0x01, 0x0f, 0x07, "1 Coin 8 Credits" }, {0 , 0xfe, 0 , 16, "Coin B" }, {0x14, 0x01, 0xf0, 0xf0, "9 Coins 1 Credits" }, {0x14, 0x01, 0xf0, 0xe0, "8 Coins 1 Credits" }, {0x14, 0x01, 0xf0, 0xd0, "7 Coins 1 Credits" }, {0x14, 0x01, 0xf0, 0xc0, "6 Coins 1 Credits" }, {0x14, 0x01, 0xf0, 0xb0, "5 Coins 1 Credits" }, {0x14, 0x01, 0xf0, 0xa0, "4 Coins 1 Credits" }, {0x14, 0x01, 0xf0, 0x90, "3 Coins 1 Credits" }, {0x14, 0x01, 0xf0, 0x80, "2 Coins 1 Credits" }, {0x14, 0x01, 0xf0, 0x00, "1 Coin 1 Credits" }, {0x14, 0x01, 0xf0, 0x10, "1 Coin 2 Credits" }, {0x14, 0x01, 0xf0, 0x20, "1 Coin 3 Credits" }, {0x14, 0x01, 0xf0, 0x30, "1 Coin 4 Credits" }, {0x14, 0x01, 0xf0, 0x40, "1 Coin 5 Credits" }, {0x14, 0x01, 0xf0, 0x50, "1 Coin 6 Credits" }, {0x14, 0x01, 0xf0, 0x60, "1 Coin 7 Credits" }, {0x14, 0x01, 0xf0, 0x70, "1 Coin 8 Credits" }, {0 , 0xfe, 0 , 2, "Invulnerability (Cheat)"}, {0x15, 0x01, 0x01, 0x00, "Off" }, {0x15, 0x01, 0x01, 0x01, "On" }, {0 , 0xfe, 0 , 2, "Rack Test" }, {0x15, 0x01, 0x02, 0x00, "Off" }, {0x15, 0x01, 0x02, 0x02, "On" }, {0 , 0xfe, 0 , 2, "Freeze" }, {0x15, 0x01, 0x08, 0x00, "Off" }, {0x15, 0x01, 0x08, 0x08, "On" }, {0 , 0xfe, 0 , 2, "Coinage Display" }, {0x15, 0x01, 0x10, 0x10, "Off" }, {0x15, 0x01, 0x10, 0x00, "On" }, {0 , 0xfe, 0 , 4, "Difficulty" }, {0x15, 0x01, 0x60, 0x20, "Easy" }, {0x15, 0x01, 0x60, 0x00, "Normal" }, {0x15, 0x01, 0x60, 0x40, "Difficult" }, {0x15, 0x01, 0x60, 0x60, "Very Difficult" }, {0 , 0xfe, 0 , 2, "Coinage" }, {0x15, 0x01, 0x80, 0x80, "A and B" }, {0x15, 0x01, 0x80, 0x00, "A only" }, }; STDDIPINFO(Onna34ro) static struct BurnDIPInfo VictnineDIPList[]= { {0x1b, 0xff, 0xff, 0x67, NULL }, {0x1c, 0xff, 0xff, 0x00, NULL }, {0x1d, 0xff, 0xff, 0x7f, NULL }, {0 , 0xfe, 0 , 2, "Free Play" }, {0x1b, 0x01, 0x04, 0x04, "Off" }, {0x1b, 0x01, 0x04, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Flip Screen" }, {0x1b, 0x01, 0x40, 0x40, "Off" }, {0x1b, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 3, "Cabinet" }, {0x1b, 0x01, 0xa0, 0x20, "Upright" }, {0x1b, 0x01, 0xa0, 0xa0, "Cocktail" }, {0x1b, 0x01, 0xa0, 0x00, "MA / MB" }, {0 , 0xfe, 0 , 16, "Coin A" }, {0x1c, 0x01, 0x0f, 0x0f, "9 Coins 1 Credits" }, {0x1c, 0x01, 0x0f, 0x0e, "8 Coins 1 Credits" }, {0x1c, 0x01, 0x0f, 0x0d, "7 Coins 1 Credits" }, {0x1c, 0x01, 0x0f, 0x0c, "6 Coins 1 Credits" }, {0x1c, 0x01, 0x0f, 0x0b, "5 Coins 1 Credits" }, {0x1c, 0x01, 0x0f, 0x0a, "4 Coins 1 Credits" }, {0x1c, 0x01, 0x0f, 0x09, "3 Coins 1 Credits" }, {0x1c, 0x01, 0x0f, 0x08, "2 Coins 1 Credits" }, {0x1c, 0x01, 0x0f, 0x00, "1 Coin 1 Credits" }, {0x1c, 0x01, 0x0f, 0x01, "1 Coin 2 Credits" }, {0x1c, 0x01, 0x0f, 0x02, "1 Coin 3 Credits" }, {0x1c, 0x01, 0x0f, 0x03, "1 Coin 4 Credits" }, {0x1c, 0x01, 0x0f, 0x04, "1 Coin 5 Credits" }, {0x1c, 0x01, 0x0f, 0x05, "1 Coin 6 Credits" }, {0x1c, 0x01, 0x0f, 0x06, "1 Coin 7 Credits" }, {0x1c, 0x01, 0x0f, 0x07, "1 Coin 8 Credits" }, {0 , 0xfe, 0 , 16, "Coin B" }, {0x1c, 0x01, 0xf0, 0xf0, "9 Coins 1 Credits" }, {0x1c, 0x01, 0xf0, 0xe0, "8 Coins 1 Credits" }, {0x1c, 0x01, 0xf0, 0xd0, "7 Coins 1 Credits" }, {0x1c, 0x01, 0xf0, 0xc0, "6 Coins 1 Credits" }, {0x1c, 0x01, 0xf0, 0xb0, "5 Coins 1 Credits" }, {0x1c, 0x01, 0xf0, 0xa0, "4 Coins 1 Credits" }, {0x1c, 0x01, 0xf0, 0x90, "3 Coins 1 Credits" }, {0x1c, 0x01, 0xf0, 0x80, "2 Coins 1 Credits" }, {0x1c, 0x01, 0xf0, 0x00, "1 Coin 1 Credits" }, {0x1c, 0x01, 0xf0, 0x10, "1 Coin 2 Credits" }, {0x1c, 0x01, 0xf0, 0x20, "1 Coin 3 Credits" }, {0x1c, 0x01, 0xf0, 0x30, "1 Coin 4 Credits" }, {0x1c, 0x01, 0xf0, 0x40, "1 Coin 5 Credits" }, {0x1c, 0x01, 0xf0, 0x50, "1 Coin 6 Credits" }, {0x1c, 0x01, 0xf0, 0x60, "1 Coin 7 Credits" }, {0x1c, 0x01, 0xf0, 0x70, "1 Coin 8 Credits" }, {0 , 0xfe, 0 , 2, "Coinage Display" }, {0x1d, 0x01, 0x10, 0x00, "Off" }, {0x1d, 0x01, 0x10, 0x10, "On" }, {0 , 0xfe, 0 , 2, "Show Year" }, {0x1d, 0x01, 0x20, 0x00, "Off" }, {0x1d, 0x01, 0x20, 0x20, "On" }, {0 , 0xfe, 0 , 2, "No hit" }, {0x1d, 0x01, 0x40, 0x40, "Off" }, {0x1d, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Coinage" }, {0x1d, 0x01, 0x80, 0x80, "A and B" }, {0x1d, 0x01, 0x80, 0x00, "A only" }, }; STDDIPINFO(Victnine) static void gfxctrl_write(int data) { char_bank = (data & 0x10) >> 4; int bank = (data & 0x20) << 3; ZetMapArea(0xdd00, 0xddff, 0, DrvPalRAM + 0x000 + bank); ZetMapArea(0xdd00, 0xddff, 1, DrvPalRAM + 0x000 + bank); ZetMapArea(0xde00, 0xdeff, 0, DrvPalRAM + 0x200 + bank); ZetMapArea(0xde00, 0xdeff, 1, DrvPalRAM + 0x200 + bank); if (data & 4) *flipscreen = (~data & 0x01); } static void onna34ro_mcu_write(int data) { int score_adr = (ZetReadByte(0xe29e) << 8) | ZetReadByte(0xe29d); mcu_sent = 1; switch (data) { case 0x0e: from_mcu = 0xff; break; case 0x01: from_mcu = 0x6a; break; case 0x40: from_mcu = ZetReadByte(score_adr); break; case 0x41: from_mcu = ZetReadByte(score_adr+1); break; case 0x42: from_mcu = ZetReadByte(score_adr+2) & 0x0f; break; default: from_mcu = 0x80; } } static const unsigned char victnine_mcu_data[0x100] = { 0x3e, 0x08, 0xdd, 0x29, 0xcb, 0x14, 0xfd, 0x29, 0xcb, 0x15, 0xd9, 0x29, 0xd9, 0x30, 0x0d, 0xd9, 0x19, 0xd9, 0xdd, 0x09, 0x30, 0x01, 0x24, 0xfd, 0x19, 0x30, 0x01, 0x2c, 0x3d, 0x20, 0xe3, 0xc9, 0x11, 0x14, 0x00, 0x19, 0x7e, 0x32, 0xed, 0xe4, 0x2a, 0x52, 0xe5, 0x22, 0xe9, 0xe4, 0x2a, 0x54, 0xe5, 0x22, 0xeb, 0xe4, 0x21, 0x2a, 0xe6, 0xfe, 0x06, 0x38, 0x02, 0xcb, 0xc6, 0xcb, 0xce, 0xc9, 0x06, 0x00, 0x3a, 0xaa, 0xe4, 0x07, 0x07, 0x07, 0xb0, 0x47, 0x3a, 0xab, 0xe4, 0x07, 0x07, 0xb0, 0x47, 0x3a, 0xac, 0xe4, 0xe6, 0x03, 0xb0, 0x21, 0xe3, 0xe6, 0xc9, 0x38, 0xe1, 0x29, 0x07, 0xc9, 0x23, 0x7e, 0x47, 0xe6, 0x1f, 0x32, 0x0c, 0xe6, 0x78, 0xe6, 0xe0, 0x07, 0x07, 0x47, 0xe6, 0x03, 0x28, 0x06, 0xcb, 0x7a, 0x28, 0x02, 0xc6, 0x02, 0x32, 0x0a, 0xe6, 0x78, 0xe6, 0x80, 0xc9, 0x3a, 0x21, 0x29, 0xe5, 0x7e, 0xe6, 0xf8, 0xf6, 0x01, 0x77, 0x23, 0x3a, 0x0a, 0xe6, 0x77, 0x21, 0x08, 0xe6, 0xcb, 0xc6, 0xcb, 0x8e, 0x3a, 0x2b, 0xe5, 0x21, 0xff, 0xe5, 0xfe, 0x02, 0xc9, 0x1f, 0xc6, 0x47, 0x3a, 0xaa, 0xe4, 0xa7, 0x21, 0x00, 0xe5, 0x28, 0x03, 0x21, 0x1b, 0xe5, 0x70, 0x3a, 0xaa, 0xe4, 0xee, 0x01, 0x32, 0xaa, 0xe4, 0x21, 0xb0, 0xe4, 0x34, 0x23, 0x36, 0x00, 0xc9, 0x2b, 0xb2, 0xaf, 0x77, 0x12, 0x23, 0x13, 0x3c, 0xfe, 0x09, 0x20, 0xf7, 0x3e, 0x01, 0x32, 0xad, 0xe4, 0x21, 0x48, 0xe5, 0xcb, 0xfe, 0xc9, 0x32, 0xe5, 0xaa, 0x21, 0x00, 0x13, 0xe4, 0x47, 0x1b, 0xa1, 0xc9, 0x00, 0x08, 0x04, 0x0c, 0x05, 0x0d, 0x06, 0x0e, 0x22, 0x66, 0xaa, 0x22, 0x33, 0x01, 0x11, 0x88, 0x06, 0x05, 0x03, 0x04, 0x08, 0x01, 0x03, 0x02, 0x06, 0x07, 0x02, 0x03, 0x15, 0x17, 0x11, 0x13 }; static void victnine_mcu_write(int data) { int seed = ZetReadByte(0xe685); if (!seed && (data & 0x37) == 0x37) { from_mcu = 0xa6; } else { data += seed; if ((data & ~0x1f) == 0xa0) { mcu_select = data & 0x1f; } else if (data < 0x20) { int offset = mcu_select * 8 + data; from_mcu = victnine_mcu_data[offset]; } else if (data >= 0x38 && data <= 0x3a) { from_mcu = ZetReadByte(0xe691 - 0x38 + data); } } } void __fastcall flstory_main_write(unsigned short address, unsigned char data) { if ((address & 0xff00) == 0xdc00) { DrvSprRAM[address & 0xff] = data; if (select_game == 2 && address == 0xdce0) { gfxctrl_write((data ^ 1) & ~0x10); } return; } switch (address) { case 0xd000: if (select_game == 2) { victnine_mcu_write(data); } if (select_game == 1) { onna34ro_mcu_write(data); } else { standard_taito_mcu_write(data); } return; case 0xd400: { *soundlatch = data; if (nmi_enable) { ZetClose(); ZetOpen(1); ZetNmi(); ZetClose(); ZetOpen(0); } else { pending_nmi = 1; } } return; case 0xdf03: if (select_game != 2) gfxctrl_write(data | 0x04); return; } } unsigned char __fastcall flstory_main_read(unsigned short address) { switch (address) { case 0xd000: if (select_game == 2) { return from_mcu - ZetReadByte(0xe685); } else { return standard_taito_mcu_read(); } case 0xd400: snd_flag = 0; return snd_data; case 0xd401: return snd_flag | 0xfd; case 0xd800: case 0xd801: case 0xd802: return DrvDips[address & 3]; case 0xd803: return DrvInputs[0] & 0x3f; case 0xd804: return DrvInputs[1]; case 0xd805: { int res = 0; if (!main_sent) res |= 0x01; if (mcu_sent) res |= 0x02; if (select_game == 2) res |= DrvInputs[3]; return res; } case 0xd806: return DrvInputs[2]; case 0xd807: return DrvInputs[4]; } return 0; } void __fastcall flstory_sound_write(unsigned short address, unsigned char data) { switch (address) { case 0xc800: case 0xc801: AY8910Write(0, address & 1, data); return; case 0xca00: case 0xca01: case 0xca02: case 0xca03: case 0xca04: case 0xca05: case 0xca06: case 0xca07: case 0xca08: case 0xca09: case 0xca0a: case 0xca0b: case 0xca0c: case 0xca0d: // msm5232 return; case 0xd800: snd_data = data; snd_flag = 2; return; case 0xda00: nmi_enable = 1; if (pending_nmi) { ZetNmi(); pending_nmi = 0; } return; case 0xdc00: nmi_enable = 0; return; case 0xde00: DACSignedWrite(data); return; } } unsigned char __fastcall flstory_sound_read(unsigned short address) { if (address == 0xd800) { return *soundlatch; } return 0; } static int DrvDoReset() { DrvReset = 0; memset (AllRam, 0, RamEnd - AllRam); ZetOpen(0); ZetReset(); ZetClose(); ZetOpen(1); ZetReset(); ZetClose(); m67805_taito_reset(); AY8910Reset(0); DACReset(); snd_data = 0; snd_flag = 0; nmi_enable = 0; pending_nmi = 0; char_bank = 0; mcu_select = 0; return 0; } static int MemIndex() { unsigned char *Next; Next = AllMem; DrvZ80ROM0 = Next; Next += 0x010000; DrvZ80ROM1 = Next; Next += 0x010000; DrvMcuROM = Next; Next += 0x000800; DrvGfxROM0 = Next; Next += 0x040000; DrvGfxROM1 = Next; Next += 0x040000; DrvPalette = (unsigned int*)Next; Next += 0x0200 * sizeof(int); AllRam = Next; DrvVidRAM = Next; Next += 0x001000; DrvZ80RAM0 = Next; Next += 0x000800; DrvZ80RAM1 = Next; Next += 0x000800; DrvPalRAM = Next; Next += 0x000400; DrvSprRAM = Next; Next += 0x000100; DrvMcuRAM = Next; Next += 0x000080; soundlatch = Next; Next += 0x000001; flipscreen = Next; Next += 0x000001; RamEnd = Next; pAY8910Buffer[0] = (short*)Next; Next += nBurnSoundLen * sizeof(short); pAY8910Buffer[1] = (short*)Next; Next += nBurnSoundLen * sizeof(short); pAY8910Buffer[2] = (short*)Next; Next += nBurnSoundLen * sizeof(short); MemEnd = Next; return 0; } static int DrvGfxDecode() { int Plane[4] = { 0x80000, 0x80004, 0x00000, 0x00004 }; int XOffs[16] = { 0x003, 0x002, 0x001, 0x000, 0x00b, 0x00a, 0x009, 0x008, 0x083, 0x082, 0x081, 0x080, 0x08b, 0x08a, 0x089, 0x088 }; int YOffs[16] = { 0x000, 0x010, 0x020, 0x030, 0x040, 0x050, 0x060, 0x070, 0x100, 0x110, 0x120, 0x130, 0x140, 0x150, 0x160, 0x170 }; unsigned char *tmp = (unsigned char*)malloc(0x20000); if (tmp == NULL) { return 1; } for (int i = 0; i < 0x20000; i++) tmp[i] = DrvGfxROM0[i] ^ 0xff; GfxDecode(0x1000, 4, 8, 8, Plane, XOffs, YOffs, 0x080, tmp, DrvGfxROM0); GfxDecode(0x0400, 4, 16, 16, Plane, XOffs, YOffs, 0x200, tmp, DrvGfxROM1); free (tmp); return 0; } static int DrvInit() { AllMem = NULL; MemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((AllMem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(AllMem, 0, nLen); MemIndex(); { if (select_game == 0) { if (BurnLoadRom(DrvZ80ROM0 + 0x00000, 0, 1)) return 1; if (BurnLoadRom(DrvZ80ROM0 + 0x04000, 1, 1)) return 1; if (BurnLoadRom(DrvZ80ROM0 + 0x08000, 2, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x00000, 3, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x02000, 4, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x00000, 5, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x04000, 6, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x08000, 7, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x0c000, 8, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x10000, 9, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x14000, 10, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x18000, 11, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x1c000, 12, 1)) return 1; if (BurnLoadRom(DrvMcuROM + 0x00000, 13, 1)) return 1; } else if (select_game == 1) { if (BurnLoadRom(DrvZ80ROM0 + 0x00000, 0, 1)) return 1; if (BurnLoadRom(DrvZ80ROM0 + 0x04000, 1, 1)) return 1; if (BurnLoadRom(DrvZ80ROM0 + 0x08000, 2, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x00000, 3, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x02000, 4, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x04000, 5, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x06000, 6, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x08000, 7, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x00000, 8, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x04000, 9, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x08000, 10, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x0c000, 11, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x10000, 12, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x14000, 13, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x18000, 14, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x1c000, 15, 1)) return 1; } else if (select_game == 2) { if (BurnLoadRom(DrvZ80ROM0 + 0x00000, 0, 1)) return 1; if (BurnLoadRom(DrvZ80ROM0 + 0x02000, 1, 1)) return 1; if (BurnLoadRom(DrvZ80ROM0 + 0x04000, 2, 1)) return 1; if (BurnLoadRom(DrvZ80ROM0 + 0x06000, 3, 1)) return 1; if (BurnLoadRom(DrvZ80ROM0 + 0x08000, 4, 1)) return 1; if (BurnLoadRom(DrvZ80ROM0 + 0x0a000, 5, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x00000, 6, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x02000, 7, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x04000, 8, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x06000, 9, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x08000, 10, 1)) return 1; if (BurnLoadRom(DrvZ80ROM1 + 0x0a000, 11, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x00000, 12, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x02000, 13, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x04000, 14, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x06000, 15, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x10000, 16, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x12000, 17, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x14000, 18, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x16000, 19, 1)) return 1; } DrvGfxDecode(); } ZetInit(2); ZetOpen(0); ZetMapArea(0x0000, 0xbfff, 0, DrvZ80ROM0); ZetMapArea(0x0000, 0xbfff, 2, DrvZ80ROM0); ZetMapArea(0xc000, 0xcfff, 0, DrvVidRAM); ZetMapArea(0xc000, 0xcfff, 1, DrvVidRAM); ZetMapArea(0xc000, 0xcfff, 2, DrvVidRAM); ZetMapArea(0xdc00, 0xdcff, 0, DrvSprRAM); // ZetMapArea(0xdc00, 0xdcff, 1, DrvSprRAM); ZetMapArea(0xdc00, 0xdcff, 2, DrvSprRAM); ZetMapArea(0xdd00, 0xddff, 0, DrvPalRAM); ZetMapArea(0xdd00, 0xddff, 1, DrvPalRAM); ZetMapArea(0xdd00, 0xddff, 2, DrvPalRAM); ZetMapArea(0xde00, 0xdeff, 0, DrvPalRAM + 0x200); ZetMapArea(0xde00, 0xdeff, 1, DrvPalRAM + 0x200); ZetMapArea(0xde00, 0xdeff, 2, DrvPalRAM + 0x200); ZetMapArea(0xe000, 0xe7ff, 0, DrvZ80RAM0); ZetMapArea(0xe000, 0xe7ff, 1, DrvZ80RAM0); ZetMapArea(0xe000, 0xe7ff, 2, DrvZ80RAM0); ZetSetWriteHandler(flstory_main_write); ZetSetReadHandler(flstory_main_read); ZetMemEnd(); ZetClose(); ZetOpen(1); ZetMapArea(0x0000, 0xbfff, 0, DrvZ80ROM1); ZetMapArea(0x0000, 0xbfff, 2, DrvZ80ROM1); ZetMapArea(0xc000, 0xc7ff, 0, DrvZ80RAM1); ZetMapArea(0xc000, 0xc7ff, 1, DrvZ80RAM1); ZetMapArea(0xc000, 0xc7ff, 2, DrvZ80RAM1); ZetMapArea(0xe000, 0xefff, 0, DrvZ80ROM1 + 0xe000); ZetMapArea(0xe000, 0xefff, 2, DrvZ80ROM1 + 0xe000); ZetSetWriteHandler(flstory_sound_write); ZetSetReadHandler(flstory_sound_read); ZetMemEnd(); ZetClose(); m67805_taito_init(DrvMcuROM, DrvMcuRAM, &standard_m68705_interface); AY8910Init(0, 2000000, nBurnSoundRate, NULL, NULL, NULL, NULL); DACInit(0, 1); GenericTilesInit(); DrvDoReset(); return 0; } static int DrvExit() { GenericTilesExit(); ZetExit(); m67805_taito_exit(); AY8910Exit(0); DACExit(); free (AllMem); AllMem = NULL; select_game = 0; return 0; } static void draw_background_layer(int type, int priority) { int masks[4] = { 0x3fff, 0xc000, 0x8000, 0x7fff }; int mask = masks[type]; for (int offs = 0; offs < 32 * 32; offs++) { int sx = (offs & 0x1f) << 3; int sy = (offs >> 5) << 3; sy -= DrvSprRAM[0xa0 + (offs & 0x1f)] + 16; if (sy < -7) sy += 256; if (sy >= nScreenHeight) continue; int attr = DrvVidRAM[offs * 2 + 1]; int code = DrvVidRAM[offs * 2 + 0] | ((attr & 0xc0) << 2) | 0x400 | (char_bank * 0x800); int flipy = attr & 0x10; int flipx = attr & 0x08; int color = (attr & 0x0f) << 4; int prio = (attr & 0x20) >> 5; if (priority && !prio) continue; { if (flipy) flipy = 0x38; if (flipx) flipy |= 0x07; unsigned char *src = DrvGfxROM0 + (code * 8 * 8); unsigned short *dst; for (int y = 0; y < 8; y++, sy++) { if (sy < 0 || sy >= nScreenHeight) continue; dst = pTransDraw + sy * nScreenWidth; for (int x = 0; x < 8; x++, sx++) { if (sx < 0 || sx >= nScreenWidth) continue; int pxl = src[((y << 3) | x) ^ flipy]; if (mask & (1 << pxl)) continue; dst[sx] = pxl | color; } sx -= 8; } } } } static void victnine_draw_background_layer() { for (int offs = 0; offs < 32 * 32; offs++) { int sx = (offs & 0x1f) << 3; int sy = (offs >> 5) << 3; sy -= DrvSprRAM[0xa0 + (offs & 0x1f)] + 16; if (sy < -7) sy += 256; if (sy >= nScreenHeight) continue; int attr = DrvVidRAM[offs * 2 + 1]; int code = DrvVidRAM[offs * 2 + 0] | ((attr & 0x38) << 5); int flipy = attr & 0x80; int flipx = attr & 0x40; int color = attr & 0x07; if (flipy) { if (flipx) { Render8x8Tile_FlipXY_Clip(pTransDraw, code, sx, sy, color, 4, 0, DrvGfxROM0); } else { Render8x8Tile_FlipY_Clip(pTransDraw, code, sx, sy, color, 4, 0, DrvGfxROM0); } } else { if (flipx) { Render8x8Tile_FlipX_Clip(pTransDraw, code, sx, sy, color, 4, 0, DrvGfxROM0); } else { Render8x8Tile_Clip(pTransDraw, code, sx, sy, color, 4, 0, DrvGfxROM0); } } } } static void draw_sprite_tiles(int code, int color, int sx, int sy, int flipx, int flipy) { if (flipy) { if (flipx) { Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, code, sx, sy, color, 4, 15, 0x100, DrvGfxROM1); } else { Render16x16Tile_Mask_FlipY_Clip(pTransDraw, code, sx, sy, color, 4, 15, 0x100, DrvGfxROM1); } } else { if (flipx) { Render16x16Tile_Mask_FlipX_Clip(pTransDraw, code, sx, sy, color, 4, 15, 0x100, DrvGfxROM1); } else { Render16x16Tile_Mask_Clip(pTransDraw, code, sx, sy, color, 4, 15, 0x100, DrvGfxROM1); } } } static void draw_sprites(int pri, int type) { for (int i = 0; i < 0x20; i++) { int pr = DrvSprRAM[0xa0-1 -i]; int offs = (pr & 0x1f) * 4; if ((pr & 0x80) == pri || type) { int sy = DrvSprRAM[offs + 0]; int attr = DrvSprRAM[offs + 1]; int code = DrvSprRAM[offs + 2]; if (type) { code += (attr & 0x20) << 3; } else { code += ((attr & 0x30) << 4); } int sx = DrvSprRAM[offs + 3]; int flipx = attr & 0x40; int flipy = attr & 0x80; if (*flipscreen) { sx = (240 - sx) & 0xff; sy = sy - 1; flipx ^= 0x40; flipx ^= 0x80; } else sy = 240 - sy - 1; draw_sprite_tiles(code, attr & 0x0f, sx, sy - 16, flipx, flipy); if (sx > 240) { draw_sprite_tiles(code, attr & 0x0f, sx - 256, sy - 16, flipx, flipy);; } } } } static inline void DrvRecalcPalette() { unsigned char r,g,b; for (int i = 0; i < 0x200; i++) { int d = DrvPalRAM[i] | (DrvPalRAM[i + 0x200] << 8); b = (d >> 8) & 0x0f; g = (d >> 4) & 0x0f; r = d & 0x0f; DrvPalette[i] = BurnHighCol((r << 4) | r, (g << 4) | g, (b << 4) | b, 0); } } static int DrvDraw() { if (DrvRecalc) { DrvRecalcPalette(); } BurnTransferClear(); if (nBurnLayer & 1) if (nBurnLayer & 1) draw_background_layer(1, 0); if (nBurnLayer & 2) if (nBurnLayer & 4) draw_background_layer(3, 1); if (nSpriteEnable & 1) draw_sprites(0x00, 0); if (nBurnLayer & 4) if (nBurnLayer & 2) draw_background_layer(0, 0); if (nSpriteEnable & 2) draw_sprites(0x80, 0); if (nBurnLayer & 8) if (nBurnLayer & 8) draw_background_layer(2, 1); BurnTransferCopy(DrvPalette); return 0; } static int victnineDraw() { if (DrvRecalc) { DrvRecalcPalette(); } victnine_draw_background_layer(); draw_sprites(0, 1); BurnTransferCopy(DrvPalette); return 0; } static int DrvFrame() { if (DrvReset) { DrvDoReset(); } { memset (DrvInputs, 0xff, 5); for (int i = 0; i < 8; i++) { DrvInputs[0] ^= (DrvJoy1[i] & 1) << i; DrvInputs[1] ^= (DrvJoy2[i] & 1) << i; DrvInputs[2] ^= (DrvJoy3[i] & 1) << i; DrvInputs[3] ^= (DrvJoy4[i] & 1) << i; DrvInputs[4] ^= (DrvJoy5[i] & 1) << i; } } int nSoundBufferPos = 0; int nInterleave = nBurnSoundLen ? nBurnSoundLen : 100; int nCyclesTotal[3] = { 5366500 / 60, 4000000 / 60, 3072000 / 60 }; int nCyclesDone[3] = { 0, 0, 0 }; if (select_game == 2) nCyclesTotal[0] = nCyclesTotal[1]; for (int i = 0; i < nInterleave; i++) { int nSegment = nCyclesTotal[0] / nInterleave; ZetOpen(0); nCyclesDone[0] += ZetRun(nSegment); if (i == (nInterleave - 1)) ZetSetIRQLine(0, ZET_IRQSTATUS_AUTO); ZetClose(); ZetOpen(1); nSegment = nCyclesTotal[1] / nInterleave; nCyclesDone[1] += ZetRun(nSegment); if (i == (nInterleave / 2) - 1) ZetSetIRQLine(0, ZET_IRQSTATUS_AUTO); if (i == (nInterleave / 1) - 1) ZetSetIRQLine(0, ZET_IRQSTATUS_AUTO); ZetClose(); if (select_game == 0) { m6805Open(0); nSegment = nCyclesTotal[2] / nInterleave; nCyclesDone[2] += m6805Run(nSegment); m6805Close(); } if (pBurnSoundOut) { int nSample; int nSegmentLength = nBurnSoundLen / nInterleave; short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); AY8910Update(0, &pAY8910Buffer[0], nSegmentLength); for (int n = 0; n < nSegmentLength; n++) { nSample = pAY8910Buffer[0][n]; nSample += pAY8910Buffer[1][n]; nSample += pAY8910Buffer[2][n]; nSample /= 4; if (nSample < -32768) { nSample = -32768; } else { if (nSample > 32767) { nSample = 32767; } } pSoundBuf[(n << 1) + 0] = nSample; pSoundBuf[(n << 1) + 1] = nSample; } DACUpdate(pSoundBuf, nSegmentLength); nSoundBufferPos += nSegmentLength; } } if (pBurnSoundOut) { int nSample; int nSegmentLength = nBurnSoundLen - nSoundBufferPos; short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); if (nSegmentLength) { AY8910Update(0, &pAY8910Buffer[0], nSegmentLength); for (int n = 0; n < nSegmentLength; n++) { nSample = pAY8910Buffer[0][n]; nSample += pAY8910Buffer[1][n]; nSample += pAY8910Buffer[2][n]; nSample /= 4; if (nSample < -32768) { nSample = -32768; } else { if (nSample > 32767) { nSample = 32767; } } pSoundBuf[(n << 1) + 0] = nSample; pSoundBuf[(n << 1) + 1] = nSample; } } DACUpdate(pSoundBuf, nSegmentLength); } if (pBurnDraw) { BurnDrvRedraw(); } return 0; } static int DrvScan(int nAction,int *pnMin) { struct BurnArea ba; if (pnMin) { *pnMin = 0x029707; } if (nAction & ACB_VOLATILE) { ba.Data = AllRam; ba.nLen = RamEnd - AllRam; ba.szName = "All RAM"; BurnAcb(&ba); ZetScan(nAction); m68705_taito_scan(nAction); AY8910Scan(nAction, pnMin); SCAN_VAR(nmi_enable); SCAN_VAR(pending_nmi); SCAN_VAR(char_bank); SCAN_VAR(mcu_select); SCAN_VAR(snd_flag); SCAN_VAR(snd_data); } return 0; } // The FairyLand Story static struct BurnRomInfo flstoryRomDesc[] = { { "cpu-a45.15", 0x4000, 0xf03fc969, 1 | BRF_PRG | BRF_ESS }, // 0 Main Z80 Code { "cpu-a45.16", 0x4000, 0x311aa82e, 1 | BRF_PRG | BRF_ESS }, // 1 { "cpu-a45.17", 0x4000, 0xa2b5d17d, 1 | BRF_PRG | BRF_ESS }, // 2 { "snd.22", 0x2000, 0xd58b201d, 2 | BRF_PRG | BRF_ESS }, // 3 Sound Z80 Code { "snd.23", 0x2000, 0x25e7fd9d, 2 | BRF_PRG | BRF_ESS }, // 4 { "vid-a45.18", 0x4000, 0x6f08f69e, 3 | BRF_GRA }, // 5 Tiles and Sprites { "vid-a45.06", 0x4000, 0xdc856a75, 3 | BRF_GRA }, // 6 { "vid-a45.08", 0x4000, 0xd0b028ca, 3 | BRF_GRA }, // 7 { "vid-a45.20", 0x4000, 0x1b0edf34, 3 | BRF_GRA }, // 8 { "vid-a45.19", 0x4000, 0x2b572dc9, 3 | BRF_GRA }, // 9 { "vid-a45.07", 0x4000, 0xaa4b0762, 3 | BRF_GRA }, // 10 { "vid-a45.09", 0x4000, 0x8336be58, 3 | BRF_GRA }, // 11 { "vid-a45.21", 0x4000, 0xfc382bd1, 3 | BRF_GRA }, // 12 { "a45.mcu", 0x0800, 0x5378253c, 4 | BRF_PRG | BRF_ESS }, // 13 M68705 MCU Code }; STD_ROM_PICK(flstory) STD_ROM_FN(flstory) static int flstoryInit() { select_game = 0; return DrvInit(); } struct BurnDriver BurnDrvFlstory = { "flstory", NULL, NULL, "1985", "The FairyLand Story\0", "Imperfect sound", "Taito", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_ORIENTATION_FLIPPED, 2, HARDWARE_MISC_MISC, NULL, flstoryRomInfo, flstoryRomName, FlstoryInputInfo, FlstoryDIPInfo, flstoryInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 256, 224, 4, 3 }; // The FairyLand Story (Japan) static struct BurnRomInfo flstoryjRomDesc[] = { { "cpu-a45.15", 0x4000, 0xf03fc969, 1 | BRF_PRG | BRF_ESS }, // 0 Main Z80 Code { "cpu-a45.16", 0x4000, 0x311aa82e, 1 | BRF_PRG | BRF_ESS }, // 1 { "cpu-a45.17", 0x4000, 0xa2b5d17d, 1 | BRF_PRG | BRF_ESS }, // 2 { "a45_12.8", 0x2000, 0xd6f593fb, 2 | BRF_PRG | BRF_ESS }, // 3 Sound Z80 Code { "a45_13.9", 0x2000, 0x451f92f9, 2 | BRF_PRG | BRF_ESS }, // 4 { "vid-a45.18", 0x4000, 0x6f08f69e, 3 | BRF_GRA }, // 5 Tiles and Sprites { "vid-a45.06", 0x4000, 0xdc856a75, 3 | BRF_GRA }, // 6 { "vid-a45.08", 0x4000, 0xd0b028ca, 3 | BRF_GRA }, // 7 { "vid-a45.20", 0x4000, 0x1b0edf34, 3 | BRF_GRA }, // 8 { "vid-a45.19", 0x4000, 0x2b572dc9, 3 | BRF_GRA }, // 9 { "vid-a45.07", 0x4000, 0xaa4b0762, 3 | BRF_GRA }, // 10 { "vid-a45.09", 0x4000, 0x8336be58, 3 | BRF_GRA }, // 11 { "vid-a45.21", 0x4000, 0xfc382bd1, 3 | BRF_GRA }, // 12 { "a45.mcu", 0x0800, 0x5378253c, 4 | BRF_PRG | BRF_ESS }, // 13 M68705 MCU Code }; STD_ROM_PICK(flstoryj) STD_ROM_FN(flstoryj) struct BurnDriver BurnDrvFlstoryj = { "flstoryj", "flstory", NULL, "1985", "The FairyLand Story (Japan)\0", "Imperfect sound", "Taito", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_FLIPPED, 2, HARDWARE_MISC_MISC, NULL, flstoryjRomInfo, flstoryjRomName, FlstoryInputInfo, FlstoryDIPInfo, flstoryInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 256, 224, 4, 3 }; // Onna Sansirou - Typhoon Gal (set 1) static struct BurnRomInfo onna34roRomDesc[] = { { "a52-01-1.40c", 0x4000, 0xffddcb02, 1 | BRF_PRG | BRF_ESS }, // 0 Main Z80 Code { "a52-02-1.41c", 0x4000, 0xda97150d, 1 | BRF_PRG | BRF_ESS }, // 1 { "a52-03-1.42c", 0x4000, 0xb9749a53, 1 | BRF_PRG | BRF_ESS }, // 2 { "a52-12.08s", 0x2000, 0x28f48096, 2 | BRF_PRG | BRF_ESS }, // 3 Sound Z80 Code { "a52-13.09s", 0x2000, 0x4d3b16f3, 2 | BRF_PRG | BRF_ESS }, // 4 { "a52-14.10s", 0x2000, 0x90a6f4e8, 2 | BRF_PRG | BRF_ESS }, // 5 { "a52-15.37s", 0x2000, 0x5afc21d0, 2 | BRF_PRG | BRF_ESS }, // 6 { "a52-16.38s", 0x2000, 0xccf42aee, 2 | BRF_PRG | BRF_ESS }, // 7 { "a52-04.11v", 0x4000, 0x5b126294, 3 | BRF_GRA }, // 8 Tiles and Sprites { "a52-06.10v", 0x4000, 0x78114721, 3 | BRF_GRA }, // 9 { "a52-08.09v", 0x4000, 0x4a293745, 3 | BRF_GRA }, // 10 { "a52-10.08v", 0x4000, 0x8be7b4db, 3 | BRF_GRA }, // 11 { "a52-05.35v", 0x4000, 0xa1a99588, 3 | BRF_GRA }, // 12 { "a52-07.34v", 0x4000, 0x0bf420f2, 3 | BRF_GRA }, // 13 { "a52-09.33v", 0x4000, 0x39c543b5, 3 | BRF_GRA }, // 14 { "a52-11.32v", 0x4000, 0xd1dda6b3, 3 | BRF_GRA }, // 15 { "a52-17.54c", 0x0800, 0x00000000, 4 | BRF_NODUMP }, // 16 M68705 MCU Code }; STD_ROM_PICK(onna34ro) STD_ROM_FN(onna34ro) static int onna34roInit() { select_game = 1; return DrvInit(); } struct BurnDriver BurnDrvOnna34ro = { "onna34ro", NULL, NULL, "1985", "Onna Sansirou - Typhoon Gal (set 1)\0", "Imperfect sound", "Taito", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, onna34roRomInfo, onna34roRomName, Onna34roInputInfo, Onna34roDIPInfo, onna34roInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 256, 224, 4, 3 }; // Onna Sansirou - Typhoon Gal (set 2) static struct BurnRomInfo onna34raRomDesc[] = { { "ry-08.rom", 0x4000, 0xe4587b85, 1 | BRF_PRG | BRF_ESS }, // 0 Main Z80 Code { "ry-07.rom", 0x4000, 0x6ffda515, 1 | BRF_PRG | BRF_ESS }, // 1 { "ry-06.rom", 0x4000, 0x6fefcda8, 1 | BRF_PRG | BRF_ESS }, // 2 { "a52-12.08s", 0x2000, 0x28f48096, 2 | BRF_PRG | BRF_ESS }, // 3 Sound Z80 Code { "a52-13.09s", 0x2000, 0x4d3b16f3, 2 | BRF_PRG | BRF_ESS }, // 4 { "a52-14.10s", 0x2000, 0x90a6f4e8, 2 | BRF_PRG | BRF_ESS }, // 5 { "a52-15.37s", 0x2000, 0x5afc21d0, 2 | BRF_PRG | BRF_ESS }, // 6 { "a52-16.38s", 0x2000, 0xccf42aee, 2 | BRF_PRG | BRF_ESS }, // 7 { "a52-04.11v", 0x4000, 0x5b126294, 3 | BRF_GRA }, // 8 Tiles and Sprites { "a52-06.10v", 0x4000, 0x78114721, 3 | BRF_GRA }, // 9 { "a52-08.09v", 0x4000, 0x4a293745, 3 | BRF_GRA }, // 10 { "a52-10.08v", 0x4000, 0x8be7b4db, 3 | BRF_GRA }, // 11 { "a52-05.35v", 0x4000, 0xa1a99588, 3 | BRF_GRA }, // 12 { "a52-07.34v", 0x4000, 0x0bf420f2, 3 | BRF_GRA }, // 13 { "a52-09.33v", 0x4000, 0x39c543b5, 3 | BRF_GRA }, // 14 { "a52-11.32v", 0x4000, 0xd1dda6b3, 3 | BRF_GRA }, // 15 { "a52-17.54c", 0x0800, 0x00000000, 4 | BRF_NODUMP }, // 16 M68705 MCU Code }; STD_ROM_PICK(onna34ra) STD_ROM_FN(onna34ra) struct BurnDriver BurnDrvOnna34ra = { "onna34roa", "onna34ro", NULL, "1985", "Onna Sansirou - Typhoon Gal (set 2)\0", "Imperfect sound", "Taito", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_MISC_MISC, NULL, onna34raRomInfo, onna34raRomName, Onna34roInputInfo, Onna34roDIPInfo, onna34roInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 256, 224, 4, 3 }; // Victorious Nine static struct BurnRomInfo victnineRomDesc[] = { { "a16-19.1", 0x2000, 0xdeb7c439, 1 | BRF_PRG | BRF_ESS }, // 0 Main Z80 Code { "a16-20.2", 0x2000, 0x60cdb6ae, 1 | BRF_PRG | BRF_ESS }, // 1 { "a16-21.3", 0x2000, 0x121bea03, 1 | BRF_PRG | BRF_ESS }, // 2 { "a16-22.4", 0x2000, 0xb20e3027, 1 | BRF_PRG | BRF_ESS }, // 3 { "a16-23.5", 0x2000, 0x95fe9cb7, 1 | BRF_PRG | BRF_ESS }, // 4 { "a16-24.6", 0x2000, 0x32b5c155, 1 | BRF_PRG | BRF_ESS }, // 5 { "a16-12.8", 0x2000, 0x4b9bff43, 2 | BRF_PRG | BRF_ESS }, // 6 Sound Z80 Code { "a16-13.9", 0x2000, 0x355121b9, 2 | BRF_PRG | BRF_ESS }, // 7 { "a16-14.10", 0x2000, 0x0f33ef4d, 2 | BRF_PRG | BRF_ESS }, // 8 { "a16-15.37", 0x2000, 0xf91d63dc, 2 | BRF_PRG | BRF_ESS }, // 9 { "a16-16.38", 0x2000, 0x9395351b, 2 | BRF_PRG | BRF_ESS }, // 10 { "a16-17.39", 0x2000, 0x872270b3, 2 | BRF_PRG | BRF_ESS }, // 11 { "a16-06-1.7", 0x2000, 0xb708134d, 3 | BRF_GRA }, // 12 Tiles and Sprites { "a16-07-2.8", 0x2000, 0xcdaf7f83, 3 | BRF_GRA }, // 13 { "a16-10.90", 0x2000, 0xe8e42454, 3 | BRF_GRA }, // 14 { "a16-11-1.91", 0x2000, 0x1f766661, 3 | BRF_GRA }, // 15 { "a16-04.5", 0x2000, 0xb2fae99f, 3 | BRF_GRA }, // 16 { "a16-05-1.6", 0x2000, 0x85dfbb6e, 3 | BRF_GRA }, // 17 { "a16-08.88", 0x2000, 0x1ddb6466, 3 | BRF_GRA }, // 18 { "a16-09-1.89", 0x2000, 0x23d4c43c, 3 | BRF_GRA }, // 19 { "a16-18.mcu", 0x0800, 0x00000000, 4 | BRF_NODUMP }, // 20 M68705 MCU Code }; STD_ROM_PICK(victnine) STD_ROM_FN(victnine) static int victnineInit() { select_game = 2; return DrvInit(); } struct BurnDriver BurnDrvVictnine = { "victnine", NULL, NULL, "1984", "Victorious Nine\0", "Imperfect sound", "Taito", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, victnineRomInfo, victnineRomName, VictnineInputInfo, VictnineDIPInfo, victnineInit, DrvExit, DrvFrame, victnineDraw, DrvScan, &DrvRecalc, 256, 224, 4, 3 };
[ [ [ 1, 1450 ] ] ]
60cfaab2c13dffb5af430e03f04bd1d430871584
6fd162d2cade2db745e68f11d7e9722a3855f033
/Source/BetterVSM_2009_08_31_SAVSM_64BitFloatSAT/SoftShadows_first_version_movie.cpp
e853205c7cda12c81f180a19d0b46bc20ef378f6
[]
no_license
SenichiFSeiei/oursavsm
8f418325bc9883bcb245e139dbd0249e72c18d78
379e77cab67b3b1423a4c6f480b664f79b03afa9
refs/heads/master
2021-01-10T21:00:52.797565
2010-04-27T13:18:19
2010-04-27T13:18:19
41,737,615
0
0
null
null
null
null
UTF-8
C++
false
false
48,735
cpp
// // demonstrates use of SSMap class. // #include <dxut.h> #include <dxutgui.h> #include <dxutsettingsdlg.h> #include <sdkmisc.h> #include <nvutcamera.h> #include <nvutmesh.h> #include "SoftShadowMap.h" #include "SilhouetteBackprojection.h" #include "HierarchalEdgeExtraction.h" #include "SilhouetteBackprojectionNoSample.h" #include "MarchingSilhouetteBP.h" #include "HierBP.h" #include "RenderFinal.h" #include "BPGI.h" #include "NoShadow.h" #include "CommonDef.h" #include "OGRE.h" #include "HDRCubeTexture.h" #include <NVUTSkybox.h> #define MAX_WCHAR_SIZE 260 static NVUTCamera g_Camera; //light management static NVUTCamera g_LCamera[NUM_LIGHT]; static CD3DSettingsDlg g_D3DSettingsDlg; static CDXUTDialogResourceManager g_DialogResourceManager; static CDXUTDialog g_HUD; static NVUTMesh g_MeshScene; static NVUTMesh g_MeshLight; static ID3DX10Font* g_pFont10 = NULL; static ID3DX10Sprite* g_pSprite10 = NULL; static CDXUTDialog g_SampleUI; static ID3D10InputLayout *g_pMaxLayout = NULL; static D3DXVECTOR3 g_vLightDir; static ID3D10RasterizerState *g_pRenderState = NULL; //parameter static SSMap ssmap; static bool g_bShowUI = true; static bool g_bMoveCamera = true; static float g_fFilterSizeCtrl = 0.1; static float g_fFilterSize = 0.1; static SilhouetteBP g_ABP; static HierarchalEdgeExtraction g_HEEBP; static SilhouetteBP_NOSMP g_ABP_nosmp; static MarchSilhouetteBP g_MBP; static HierBP g_HBP; static BPGlobalIllumination g_BPGI; static NoShadow g_NoShadow; static RenderFinal g_Final; static int ShadowAlgorithm = SINGLE_LIGHT; static float g_fDepthBiasDefault = 0.1; static float g_fLightZn = 40; static int g_nNumLightSample = 0; static bool g_LightVary = false; static bool g_CameraMove = false; static bool g_LightMove = false; HDRCubeTexture* g_pEnvMap = NULL; NVUTSkybox* g_pSkyBox = NULL; DXGI_SURFACE_DESC g_pFloatBufferSurfaceDesc; #define MAX_PATH_STR 512 WCHAR g_EnvMapFilePath[MAX_PATH_STR]; WCHAR* g_DefaultEnvMapName[]={ DEFAULT_HDR_ENVMAP }; static float g_fDefaultDepthBias = 0.00125; static float g_fDepthBiasHammer = 0.02325; static float g_fDepthBiasLeftForearm = 0.0055; static float g_fDepthBiasRightForearm = 0.00745; static float g_fDepthBiasLeftShoulder = 0.003745; static float g_fDepthBiasRightShoulder = 0.00175; static float g_fDepthBiasBlackPlate = 0.0005; static float g_fDepthBiasHelmet = 0.00425; static float g_fDepthBiasEyes = 0.02475; static float g_fDepthBiasBelt = 0.0005; static float g_fDepthBiasLeftThigh = 0.017; static float g_fDepthBiasRightThigh = 0.00525; static float g_fDepthBiasLeftShin = 0.0015; static float g_fDepthBiasRightShin = 0.001; static float g_fDepthBiasObject0 = 0.00225; //light management static RenderObject *g_pLightLumiBuffer[NUM_LIGHT]; static RenderObject *g_pPingpongBuffer[2]; //---------------------------------------------------------- //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pDev10, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnD3D10SwapChainResized( ID3D10Device* pDev10, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnD3D10FrameRender( ID3D10Device* pDev10, double fTime, float fElapsedTime, void* pUserContext ); void CALLBACK OnD3D10SwapChainReleasing( void* pUserContext ); void CALLBACK OnD3D10DestroyDevice( void* pUserContext ); //-------------------------------------------------------------------------------------- // Load new model //-------------------------------------------------------------------------------------- static void LoadNewModel(bool bNeedUI = false) { //HRESULT hr; static WCHAR g_wcCleanFileName[MAX_WCHAR_SIZE]; memcpy(g_wcCleanFileName, SCENE_SOURCE, sizeof(SCENE_SOURCE)); BOOL bResult = TRUE; if( bResult ) { g_MeshScene.Destroy(); // setup the camera view parameters static const D3D10_INPUT_ELEMENT_DESC mesh_layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; //if (g_MeshScene.Create(DXUTGetD3D10Device(), g_wcCleanFileName, (D3D10_INPUT_ELEMENT_DESC*)mesh_layout, 3) != S_OK) UINT scene_file_num = 1; LPCTSTR pSceneFileNames[1] = { //L"4Columns.x", L"sponza\\sponza.x", }; static WCHAR FAN_Mesh0[MAX_PATH] = L"MotionBlur\\windmillstage.sdkmesh"; static WCHAR FAN_Mesh1[MAX_PATH] = L"MotionBlur\\Fan.sdkmesh"; if( g_MeshScene.Create( MESH_SOURCE,//Animation mesh source ANIM_SOURCE, DXUTGetD3D10Device(), (D3D10_INPUT_ELEMENT_DESC*)suitlayout, (D3D10_INPUT_ELEMENT_DESC*)bodylayout, g_wcCleanFileName, pSceneFileNames, scene_file_num, (D3D10_INPUT_ELEMENT_DESC*)mesh_layout, 3, FAN_Mesh0, FAN_Mesh1, true) ) { MessageBox(DXUTGetHWND(), L"Could not load geometry from sunclock.x", L"Error", MB_OK); exit(0); } D3DXVECTOR3 vLight[NUM_LIGHT] = LIGHT_POS; D3DXVECTOR3 vEye = EYE_POS; D3DXVECTOR3 vLookAt = LOOK_AT_POS; //light management for( int light_idx = 0; light_idx < NUM_LIGHT; ++light_idx ) { g_LCamera[light_idx].SetViewParams(&vLight[light_idx], &vLookAt); } g_Camera.SetViewParams(&vEye, &vLookAt); } } static void InitApp() { g_D3DSettingsDlg.Init( &g_DialogResourceManager ); g_HUD.Init( &g_DialogResourceManager ); g_SampleUI.Init( &g_DialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int iY = 10; g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY, 125, 22, VK_F2 ); g_SampleUI.EnableKeyboardInput( true ); g_SampleUI.SetCallback( OnGUIEvent ); iY = 10; g_SampleUI.AddStatic( IDC_SHADOW_ALGORITHM_LABEL, L"Shadow algorithm:", 35, iY, 125, 22 ); CDXUTComboBox *pComboBox; g_SampleUI.AddComboBox( IDC_SHADOW_ALGORITHM, 35, iY += 20, 125, 30, 0, false, &pComboBox); pComboBox->AddItem(L"StandardBP", NULL); pComboBox->AddItem(L"BP_NoSMP", NULL); pComboBox->AddItem(L"MarchingBP", NULL); pComboBox->AddItem(L"HirEdgeExtraction", NULL); pComboBox->AddItem(L"HirBP", NULL); pComboBox->AddItem(L"BPGI", NULL); pComboBox->AddItem(L"NoShadows", NULL); pComboBox->AddItem(L"SingleLight", NULL); g_SampleUI.AddStatic( IDC_COMMON_LABEL, L"Light Zn", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider( IDC_LIGHT_ZN, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"NumLightSample", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_NUM_LIGHT_SAMPLE, 160, iY, 124, 22, 0, 16, 0 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDefaultDepthBias", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDefaultDepthBias, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasHammer", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasHammer, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasLeftForearm", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasLeftForearm, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasRightForearm", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasRightForearm, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasLeftShoulder", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasLeftShoulder, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasRightShoulder", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasRightShoulder, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasBlackPlate", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasBlackPlate, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasHelmet", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasHelmet, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasEyes", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasEyes, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasBelt", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasBelt, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasLeftThigh", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasLeftThigh, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasRightThigh", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasRightThigh, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasLeftShin", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasLeftShin, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasRightShin", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasRightShin, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddStatic(IDC_COMMON_LABEL, L"fDepthBiasObject0", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider(IDC_fDepthBiasObject0, 160, iY, 124, 22, 0, 100, 40 ); g_SampleUI.AddCheckBox( IDC_BTEXTURED, L"Enable Texturing", 35, iY += 25, 124, 22, true); g_SampleUI.AddCheckBox( IDC_BMOVECAMERA, L"Move Camera", 35, iY += 25, 124, 22, true); g_SampleUI.AddCheckBox( IDC_BDUMP_SHADOWMAP, L"Dump Shadow Map", 35, iY += 25, 124, 22, false); g_SampleUI.AddCheckBox( IDC_STATIC, L"Freeze Model", 35, iY += 25, 124, 22, true); g_SampleUI.AddCheckBox( IDC_ANIMATE, L"Show Animated Model", 35, iY += 25, 124, 22, true); g_SampleUI.AddCheckBox( IDC_SCENE, L"Show scene", 35, iY += 25, 124, 22, true); g_SampleUI.AddCheckBox( IDC_FAN, L"Show Fan", 35, iY += 25, 124, 22, true); g_SampleUI.AddCheckBox( IDC_FRAME_DUMP, L"Show Fan", 35, iY += 25, 124, 22, false); g_SampleUI.AddStatic( IDC_LIGHT_SIZE_LABEL, L"Light source size:", 35, iY += 25, 125, 22 ); g_SampleUI.AddSlider( IDC_LIGHT_SIZE, 160, iY, 124, 22, 0, 100, 0 ); g_pSkyBox = new NVUTSkybox(); g_pEnvMap = new HDRCubeTexture; } static void RenderText() { CDXUTTextHelper txtHelper( g_pFont10, g_pSprite10, 15 ); txtHelper.Begin(); txtHelper.SetInsertionPos( 5, 5 ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 0.0f, 0.0f, 1.0f ) ); txtHelper.DrawTextLine( DXUTGetFrameStats(true) ); txtHelper.DrawTextLine( DXUTGetDeviceStats() ); txtHelper.End(); } HRESULT CreatePipeBuffer(ID3D10Device* pDev10, UINT uiNumSpawnPoints, UINT uiMaxFaces); HRESULT CreateRandomTexture(ID3D10Device* pDev10); HRESULT GenerateTriCenterBuffer( ID3D10Device* pDev10, LPCTSTR szMesh, UINT *puNumFaces ); HRESULT LoadTextureArray( ID3D10Device* pDev10, LPCTSTR* szTextureNames, int iNumTextures, ID3D10Texture2D** ppTex2D, ID3D10ShaderResourceView** ppSRV); //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // DXUT will create and use the best device (either D3D9 or D3D10) // that is available on the system depending on which D3D callbacks are set below // Set DXUT callbacks DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( OnKeyboard ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackD3D10DeviceAcceptable( IsD3D10DeviceAcceptable ); DXUTSetCallbackD3D10DeviceCreated( OnD3D10CreateDevice ); DXUTSetCallbackD3D10SwapChainResized( OnD3D10SwapChainResized ); DXUTSetCallbackD3D10FrameRender( OnD3D10FrameRender ); DXUTSetCallbackD3D10SwapChainReleasing( OnD3D10SwapChainReleasing ); DXUTSetCallbackD3D10DeviceDestroyed( OnD3D10DestroyDevice ); HRESULT hr; V_RETURN(DXUTSetMediaSearchPath(L"..\\Source\\SoftShadows")); InitApp(); DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen DXUTCreateWindow( L"SoftShadows" ); DXUTCreateDevice( true, 1024, 768 ); DXUTMainLoop(); // Enter into the DXUT render loop return DXUTGetExitCode(); } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { // For the first device created if its a REF device, optionally display a warning dialog box static bool s_bFirstTime = true; pDeviceSettings->d3d10.sd.SampleDesc.Count = 1; pDeviceSettings->d3d10.sd.SampleDesc.Quality = 0; if( s_bFirstTime ) { s_bFirstTime = false; if((DXUT_D3D9_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF) || (DXUT_D3D10_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d10.DriverType == D3D10_DRIVER_TYPE_REFERENCE)) DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); } return true; } //-------------------------------------------------------------------------------------- // Handle updates to the scene. This is called regardless of which D3D API is used //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { // update the camera's position based on user input g_Camera.FrameMove(fElapsedTime); //light management for( int light_idx = 0; light_idx < 1/*NUM_LIGHT*/; ++light_idx )//FIX A LIGHT FOR CONSTANT ILLUMINATION { g_LCamera[light_idx].FrameMove(fElapsedTime); } } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Pass messages to dialog resource manager calls so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass messages to settings dialog if its active if( g_D3DSettingsDlg.IsActive() ) { g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } // Give the dialogs a chance to handle the message first *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; *pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass all remaining windows messages to camera so it can respond to user input unsigned iTmp = g_SampleUI.GetCheckBox(IDC_BMOVECAMERA)->GetChecked(); if ( iTmp ) // left button pressed { g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam ); } else{ //light management for( int light_idx = 0; light_idx < NUM_LIGHT; ++ light_idx ) { g_LCamera[light_idx].HandleMessages( hWnd, uMsg, wParam, lParam ); } } return 0; } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- void CALLBACK OnKeyboard(UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext) { if( !bKeyDown ) return; switch( nChar ) { case VK_F1: g_bShowUI = !g_bShowUI; break; case VK_F7: g_LightVary = !g_LightVary; break; case VK_F8: g_CameraMove = !g_CameraMove; break; case VK_F9: g_LightMove = !g_LightMove; break; } } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent(UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext) { switch( nControlID ) { case IDC_CHANGEDEVICE: g_D3DSettingsDlg.SetActive( !g_D3DSettingsDlg.IsActive() ); break; case IDC_LIGHT_SIZE: g_fFilterSizeCtrl = (float)g_SampleUI.GetSlider(IDC_LIGHT_SIZE)->GetValue() / 100.0; break; case IDC_SHADOW_ALGORITHM: ShadowAlgorithm = ((CDXUTComboBox*)pControl)->GetSelectedIndex(); break; case IDC_LIGHT_ZN: g_fLightZn = 2*(float)g_SampleUI.GetSlider(IDC_LIGHT_ZN)->GetValue(); break; case IDC_fDefaultDepthBias: g_fDefaultDepthBias = (float)g_SampleUI.GetSlider(IDC_fDefaultDepthBias)->GetValue()/4000.0; break; case IDC_fDepthBiasHammer: g_fDepthBiasHammer = (float)g_SampleUI.GetSlider(IDC_fDepthBiasHammer)->GetValue()/4000.0; break; case IDC_fDepthBiasLeftForearm: g_fDepthBiasLeftForearm = (float)g_SampleUI.GetSlider(IDC_fDepthBiasLeftForearm)->GetValue()/4000.0; break; case IDC_fDepthBiasRightForearm: g_fDepthBiasRightForearm = (float)g_SampleUI.GetSlider(IDC_fDepthBiasRightForearm)->GetValue()/4000.0; break; case IDC_fDepthBiasLeftShoulder: g_fDepthBiasLeftShoulder = (float)g_SampleUI.GetSlider(IDC_fDepthBiasLeftShoulder)->GetValue()/4000.0; break; case IDC_fDepthBiasRightShoulder: g_fDepthBiasRightShoulder = (float)g_SampleUI.GetSlider(IDC_fDepthBiasRightShoulder)->GetValue()/4000.0; break; case IDC_fDepthBiasBlackPlate: g_fDepthBiasBlackPlate = (float)g_SampleUI.GetSlider(IDC_fDepthBiasBlackPlate)->GetValue()/4000.0; break; case IDC_fDepthBiasHelmet: g_fDepthBiasHelmet = (float)g_SampleUI.GetSlider(IDC_fDepthBiasHelmet)->GetValue()/4000.0; break; case IDC_fDepthBiasEyes: g_fDepthBiasEyes = (float)g_SampleUI.GetSlider(IDC_fDepthBiasEyes)->GetValue()/4000.0; break; case IDC_fDepthBiasBelt: g_fDepthBiasBelt = (float)g_SampleUI.GetSlider(IDC_fDepthBiasBelt)->GetValue()/4000.0; break; case IDC_fDepthBiasLeftThigh: g_fDepthBiasLeftThigh = (float)g_SampleUI.GetSlider(IDC_fDepthBiasLeftThigh)->GetValue()/4000.0; break; case IDC_fDepthBiasRightThigh: g_fDepthBiasRightThigh = (float)g_SampleUI.GetSlider(IDC_fDepthBiasRightThigh)->GetValue()/4000.0; break; case IDC_fDepthBiasLeftShin: g_fDepthBiasLeftShin = (float)g_SampleUI.GetSlider(IDC_fDepthBiasLeftShin)->GetValue()/4000.0; break; case IDC_fDepthBiasRightShin: g_fDepthBiasRightShin = (float)g_SampleUI.GetSlider(IDC_fDepthBiasRightShin)->GetValue()/4000.0; break; case IDC_fDepthBiasObject0: g_fDepthBiasObject0 = (float)g_SampleUI.GetSlider(IDC_fDepthBiasObject0)->GetValue()/4000.0; break; case IDC_NUM_LIGHT_SAMPLE: g_nNumLightSample = 2*(int)g_SampleUI.GetSlider(IDC_NUM_LIGHT_SAMPLE)->GetValue(); break; } } //-------------------------------------------------------------------------------------- // Reject any D3D10 devices that aren't acceptable by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsD3D10DeviceAcceptable(UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext) { return true; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10CreateDevice(ID3D10Device* pDev10, const DXGI_SURFACE_DESC *pBackBufferSurfaceDesc, void* pUserContext) { HRESULT hr; V_RETURN(DXUTSetMediaSearchPath(L"..\\Source\\SoftShadows")); V_RETURN(g_DialogResourceManager.OnD3D10CreateDevice(pDev10)); V_RETURN(g_D3DSettingsDlg.OnD3D10CreateDevice(pDev10)); V_RETURN(D3DX10CreateFont(pDev10, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFont10)); g_SampleUI.GetSlider(IDC_LIGHT_SIZE)->SetValue((int)(g_fFilterSize * 200.0)); g_SampleUI.GetComboBox(IDC_SHADOW_ALGORITHM)->SetSelectedByIndex(ssmap.bAccurateShadow == true ? 0 : 1); V_RETURN(D3DX10CreateSprite(pDev10, 512, &g_pSprite10)); LoadNewModel(); V_RETURN( DXUTFindDXSDKMediaFileCch( g_EnvMapFilePath, MAX_PATH_STR, g_DefaultEnvMapName[0] ) ); g_pEnvMap->OnCreateDevice(pDev10, g_EnvMapFilePath, DXGI_FORMAT_R8G8B8A8_UNORM); g_pSkyBox->OnCreateDevice( pDev10 ); g_pSkyBox->SetTexture( g_pEnvMap->m_TextureRV ); g_pFloatBufferSurfaceDesc.SampleDesc.Count = pBackBufferSurfaceDesc->SampleDesc.Count; g_pFloatBufferSurfaceDesc.SampleDesc.Quality = pBackBufferSurfaceDesc->SampleDesc.Quality; ssmap.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); D3DXVECTOR3 vTmp = D3DXVECTOR3(1, 2, 3); D3DXVec3Normalize(&g_vLightDir, &vTmp); SAFE_RELEASE(g_pRenderState); D3D10_RASTERIZER_DESC RasterizerState; RasterizerState.FillMode = D3D10_FILL_SOLID; RasterizerState.CullMode = D3D10_CULL_FRONT; RasterizerState.FrontCounterClockwise = true; RasterizerState.DepthBias = false; RasterizerState.DepthBiasClamp = 0; RasterizerState.SlopeScaledDepthBias = 0; RasterizerState.DepthClipEnable = true; RasterizerState.ScissorEnable = false; RasterizerState.MultisampleEnable = false; RasterizerState.AntialiasedLineEnable = false; V(pDev10->CreateRasterizerState(&RasterizerState, &g_pRenderState)); g_ABP.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_NoShadow.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_BPGI.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_HBP.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_ABP_nosmp.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_MBP.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_HEEBP.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); g_Final.OnD3D10CreateDevice(pDev10,pBackBufferSurfaceDesc,pUserContext); {//must be after g_ABP create a device,because they uses the members of g_ABP static const D3D10_INPUT_ELEMENT_DESC mesh_layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; if (g_MeshLight.Create(pDev10, L"arrow.x", (D3D10_INPUT_ELEMENT_DESC*)mesh_layout, 3) != S_OK) { MessageBox(DXUTGetHWND(), L"Could not load geometry from arrow.x", L"Error", MB_OK); exit(0); } D3D10_PASS_DESC PassDesc; V_RETURN(g_ABP.m_pEffect->GetTechniqueByName(SILHOUETTE_BP_SCENE_TECH)->GetPassByIndex(0)->GetDesc(&PassDesc)); V_RETURN(pDev10->CreateInputLayout(mesh_layout, 3, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &g_pMaxLayout)); } //light management for( int light_idx = 0; light_idx < NUM_LIGHT; ++light_idx ) { g_pLightLumiBuffer[light_idx] = new RenderObject( "RenderScreenPixelPos" ); g_pLightLumiBuffer[light_idx] ->OnD3D10CreateDevice( NULL,pDev10, pBackBufferSurfaceDesc, pUserContext); } for( int p_idx = 0 ; p_idx < 2 ; ++p_idx ) { g_pPingpongBuffer[p_idx] = new RenderObject( "RenderScreenPixelPos" ); g_pPingpongBuffer[p_idx] ->OnD3D10CreateDevice( NULL,pDev10, pBackBufferSurfaceDesc, pUserContext); } //-------------------------------------------------------------------------------------------------------- return S_OK; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that depend on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10SwapChainResized( ID3D10Device* pDev10, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr = S_OK; V_RETURN(g_DialogResourceManager.OnD3D10ResizedSwapChain(pDev10, pBackBufferSurfaceDesc)); // setup the camera projection parameters g_Camera.SetWindow(pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height); //light management for( int light_idx = 0; light_idx < NUM_LIGHT; ++light_idx ) { g_LCamera[light_idx].SetWindow(pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height); } g_HUD.SetLocation(pBackBufferSurfaceDesc->Width-170, 0); g_HUD.SetSize(170, 170); g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width-300, pBackBufferSurfaceDesc->Height-700 ); g_SampleUI.SetSize( 170, 300 ); g_ABP.OnD3D10SwapChainResized(pDev10,pSwapChain,pBackBufferSurfaceDesc,pUserContext ); g_NoShadow.OnD3D10SwapChainResized(pDev10,pSwapChain,pBackBufferSurfaceDesc,pUserContext ); g_BPGI.OnD3D10SwapChainResized(pDev10,pSwapChain,pBackBufferSurfaceDesc,pUserContext ); g_Final.OnD3D10SwapChainResized(pDev10,pSwapChain,pBackBufferSurfaceDesc,pUserContext ); g_HBP.OnD3D10SwapChainResized(pDev10,pSwapChain,pBackBufferSurfaceDesc,pUserContext ); g_HEEBP.OnD3D10SwapChainResized(pDev10,pSwapChain,pBackBufferSurfaceDesc,pUserContext ); g_MBP.OnD3D10SwapChainResized(pDev10,pSwapChain,pBackBufferSurfaceDesc,pUserContext ); //light management D3D10_TEXTURE2D_DESC rtDesc_scrpos = { pBackBufferSurfaceDesc->Width, //UINT Width; pBackBufferSurfaceDesc->Height, //UINT Height; 1,//UINT MipLevels; 1,//UINT ArraySize; DXGI_FORMAT_R16G16B16A16_FLOAT,//DXGI_FORMAT Format; {1, 0}, //DXGI_SAMPLE_DESC SampleDesc; D3D10_USAGE_DEFAULT, //D3D10_USAGE Usage; D3D10_BIND_SHADER_RESOURCE | D3D10_BIND_RENDER_TARGET ,//UINT BindFlags; 0,//UINT CPUAccessFlags; 0,//UINT MiscFlags; }; for( int light_idx = 0; light_idx < NUM_LIGHT; ++light_idx ) { g_pLightLumiBuffer[light_idx]->OnD3D10SwapChainResized( rtDesc_scrpos, pDev10, pSwapChain, pBackBufferSurfaceDesc, pUserContext); } for( int p_idx = 0 ; p_idx < 2 ; ++p_idx ) { g_pPingpongBuffer[p_idx]->OnD3D10SwapChainResized( rtDesc_scrpos, pDev10, pSwapChain, pBackBufferSurfaceDesc, pUserContext); } //--------------------------------------- g_pSkyBox->OnResizedSwapChain ( pDev10, &g_pFloatBufferSurfaceDesc ); g_pFloatBufferSurfaceDesc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; g_pFloatBufferSurfaceDesc.Height = pBackBufferSurfaceDesc->Height; g_pFloatBufferSurfaceDesc.Width = pBackBufferSurfaceDesc->Width; return hr; } //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10FrameRender(ID3D10Device* pDev10, double fTime, float fElapsedTime, void* pUserContext) { HRESULT hr; D3DXVECTOR3 vEye = *g_Camera.GetEyePt(); float x_incre = 0.1; static float total_x_incre = 0; float z_incre = 0.1; static float total_z_incre = 0; float y_incre = 0.15; static float total_y_incre = 0; static float move_dir = 0; static float animation_timer = 0; if( g_CameraMove ) { if( move_dir == 0 ) { vEye.y -= y_incre * 10; vEye.x -= x_incre*0.35*1.5*10; D3DXVECTOR3 vLookAt = *g_Camera.GetLookAtPt(); g_Camera.SetViewParams(&vEye, &vLookAt); total_y_incre += y_incre * 10; if( total_y_incre >52) { move_dir = 0.5; } } if( move_dir == 0.5 ) { animation_timer += 0.5; if( animation_timer > 48 ) { move_dir = 1; animation_timer = 0; } } if( move_dir == 1 ) { animation_timer += 0.1; if( animation_timer > 25 ) { move_dir = 2; animation_timer = 0; } } if( move_dir == 2 ) { vEye.x += x_incre * 3; D3DXVECTOR3 vLookAt = *g_Camera.GetLookAtPt(); g_Camera.SetViewParams(&vEye, &vLookAt); total_x_incre += x_incre * 3; if( total_x_incre > 20 ) { move_dir = 3; total_x_incre = 0; } } if( move_dir == 3 ) { vEye.z += z_incre * 3; vEye.y += y_incre* 1.5 * 1.5; D3DXVECTOR3 vLookAt = *g_Camera.GetLookAtPt(); g_Camera.SetViewParams(&vEye, &vLookAt); total_z_incre += z_incre * 3; if( total_z_incre > 25 ) { move_dir = 4; total_z_incre = 0; } } if( move_dir == 4 ) { vEye.x -= x_incre * 3; D3DXVECTOR3 vLookAt = *g_Camera.GetLookAtPt(); g_Camera.SetViewParams(&vEye, &vLookAt); total_x_incre += x_incre * 3; if( total_x_incre > 20 ) { move_dir = 5; total_x_incre = 0; } } if( move_dir == 5 ) { vEye.z -= z_incre * 1.5; vEye.y -= y_incre*0.9*1.5 * 0.5; vEye.x -= x_incre * 0.1; D3DXVECTOR3 vLookAt = *g_Camera.GetLookAtPt(); g_Camera.SetViewParams(&vEye, &vLookAt); total_z_incre += z_incre * 1.5; if( total_z_incre > 25 ) { move_dir = 6; total_z_incre = 0; } } if( move_dir == 6 ) { move_dir = 7; //vEye.x += x_incre; //D3DXVECTOR3 vLookAt = *g_Camera.GetLookAtPt(); //g_Camera.SetViewParams(&vEye, &vLookAt); //total_x_incre += x_incre; //if( total_x_incre > 3 ) //{ // move_dir = 7; // total_x_incre = 0; //} } if( move_dir == 7 ) { move_dir = 8; } if( move_dir == 8 ) { animation_timer += 0.1; if( animation_timer > 200 ) { move_dir = 8; animation_timer = 0; } } } if( move_dir == 7 || move_dir == 0.5) g_LightVary = true; else g_LightVary = false; if( move_dir == 8 ) g_LightMove = true; else g_LightMove = false; static double old_fTime = 0.001; fTime = old_fTime; old_fTime += 0.05; static double oldTime = 0; static unsigned old_iSta = 0; static double stop_time = 0; static double total_stop_time = 0; double tmp = fTime; unsigned iSta = g_SampleUI.GetCheckBox(IDC_STATIC)->GetChecked(); if( move_dir == 1 && animation_timer>2 ) iSta = 0; else if( move_dir == 1 && animation_timer>47.5 ) iSta = 1; else if( move_dir == 2 ) iSta = 1; if( 0 == old_iSta && 1 == iSta )//turn to be static { stop_time = fTime - total_stop_time; } if( 1 == iSta ) { total_stop_time += ( fTime - oldTime ); fTime = stop_time; } if( 0 == iSta ) { fTime -= total_stop_time; } old_iSta = iSta; oldTime = tmp; NVUTCamera& g_CameraRef = g_Camera; // compute view matrix D3DXMATRIX mTmp, mWorldView, mWorldViewProj, mWorldViewInv; D3DXMatrixInverse(&mTmp, NULL, g_CameraRef.GetWorldMatrix()); D3DXMatrixMultiply(&mWorldView, &mTmp, g_CameraRef.GetViewMatrix()); // correct near/far clip planes according to camera location const DXGI_SURFACE_DESC *pBackBufferSurfaceDesc = DXUTGetDXGIBackBufferSurfaceDesc(); D3DXVECTOR3 vBox[2]; float fAspectRatio = pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height; g_CameraRef.SetProjParams(D3DX_PI/3, fAspectRatio, 0.1, 500); // clear depth and color ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView(); pDev10->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0); ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView(); if( g_D3DSettingsDlg.IsActive() ) { g_D3DSettingsDlg.OnRender( fElapsedTime ); return; } Parameters para; para.fLightZn = g_fLightZn; float biases[15]; biases[0] = g_fDepthBiasObject0; biases[1] = g_fDefaultDepthBias; biases[2] = g_fDepthBiasHammer; biases[3] = g_fDepthBiasLeftForearm; biases[4] = g_fDepthBiasRightForearm; biases[5] = g_fDepthBiasLeftShoulder; biases[6] = g_fDepthBiasRightShoulder; biases[7] = g_fDepthBiasBlackPlate; biases[8] = g_fDepthBiasHelmet; biases[9] = g_fDepthBiasEyes; biases[10] = g_fDepthBiasBelt; biases[11] = g_fDepthBiasLeftThigh; biases[12] = g_fDepthBiasRightThigh; biases[13] = g_fDepthBiasLeftShin; biases[14] = g_fDepthBiasRightShin; g_MeshScene.set_biases(biases,15); float light_size[NUM_LIGHT] = LIGHT_SIZE; float light_ZNS[NUM_LIGHT] = LIGHT_ZNS; float light_view_angle[NUM_LIGHT] = LIGHT_VIEW_ANGLES; D3DXVECTOR4 light_color[NUM_LIGHT] = LIGHT_COLOR; bool render_ogre = g_SampleUI.GetCheckBox( IDC_ANIMATE )->GetChecked(); bool render_scene = g_SampleUI.GetCheckBox( IDC_SCENE )->GetChecked(); bool render_fan = g_SampleUI.GetCheckBox( IDC_FAN )->GetChecked(); float ClearColor[4] = { 0, 0, 0, 1 }; for( int p_idx = 0 ; p_idx < 2 ; ++p_idx ) { pDev10->ClearRenderTargetView(g_pPingpongBuffer[p_idx]->m_pRTView, ClearColor); } //light management ID3D10RenderTargetView *p_RTV; ID3D10ShaderResourceView *p_SRV; D3DXVECTOR3 vLookAt = LOOK_AT_POS; static float light_scale_factor = 0.2; static float ls_incre = 0.01; if( g_LightVary == true || g_fFilterSize < g_fFilterSizeCtrl ) { g_fFilterSize -= ls_incre; if( g_fFilterSize < 0.1 || g_fFilterSize > g_fFilterSizeCtrl ) ls_incre = -ls_incre; } else { g_fFilterSize = g_fFilterSizeCtrl; } // rendering a subdivided light float scaled_light_size = (g_fFilterSize*LIGHT_SCALE_FACTOR); float fStartPt = -scaled_light_size; float fInterval = 2 * scaled_light_size / g_nNumLightSample; float fSubLightSize = g_fFilterSize; if( g_nNumLightSample > 0 ) { fSubLightSize = fSubLightSize / g_nNumLightSample; } if( g_nNumLightSample == 0 ) { g_nNumLightSample = 1; } static float total_light_x_incre = 0; static int light_mov_dir = 0; float shadow_factor = 0.8/(g_nNumLightSample * g_nNumLightSample); for( int ix = 0; ix < g_nNumLightSample; ++ix ) { for( int iy = 0; iy < g_nNumLightSample; ++iy ) { D3DXVECTOR3 vLight = *g_LCamera[0].GetEyePt(); float x_incre = 0.005; if( g_LightMove ) { float range = 3.8; if( light_mov_dir == 0 ) { vLight.x += x_incre; D3DXVECTOR3 vLookAt = *g_LCamera[0].GetLookAtPt(); g_LCamera[0].SetViewParams(&vLight, &vLookAt); total_light_x_incre += x_incre; if( total_light_x_incre > range * 1.0 ) { light_mov_dir = 1; } } else { vLight.x -= x_incre; D3DXVECTOR3 vLookAt = *g_LCamera[0].GetLookAtPt(); g_LCamera[0].SetViewParams(&vLight, &vLookAt); total_light_x_incre -= x_incre; if( total_light_x_incre < -range * 2.0 ) { light_mov_dir = 0; } } } NVUTCamera local_cam = g_LCamera[0]; D3DXVECTOR3 vTrans( fStartPt+(ix+0.5)*fInterval,fStartPt+(iy+0.5)*fInterval,0 ); if( g_nNumLightSample == 1 ) { vTrans = D3DXVECTOR3(0,0,0); } D3DXMATRIX mInvLightView; D3DXVECTOR4 tmp_light_pos; D3DXMatrixInverse(&mInvLightView, NULL, local_cam.GetViewMatrix()); D3DXVec3Transform(&tmp_light_pos, &vTrans, &mInvLightView ); D3DXVECTOR3 tmp_light_pos_3(tmp_light_pos.x,tmp_light_pos.y,tmp_light_pos.z); local_cam.SetViewParams( &tmp_light_pos_3, &vLookAt ); g_MeshScene.set_parameters( render_ogre, render_scene, render_fan, false ); NVUTCamera& g_LCameraRef = local_cam; g_fLightZn = light_ZNS[0]; D3DXMATRIX mLightView; // here we compute light viewprojection so that light oversees the whole scene D3DXMATRIX mTranslate; D3DXMatrixInverse(&mTranslate, NULL, g_LCameraRef.GetWorldMatrix()); D3DXMatrixMultiply(&mLightView, &mTranslate, g_LCameraRef.GetViewMatrix()); g_LCameraRef.SetProjParams(light_view_angle[0], 1.0, g_fLightZn, g_fLightZn + LIGHT_ZF_DELTA); unsigned iTmp = g_SampleUI.GetCheckBox(IDC_BDUMP_SHADOWMAP)->GetChecked(); ssmap.Render(pDev10, &g_MeshScene, g_LCameraRef,fTime,fElapsedTime,iTmp); pDev10->RSSetState(g_pRenderState); if( (ix * g_nNumLightSample + iy) % 2 == 0 ) { p_RTV = g_pPingpongBuffer[0]->m_pRTView; p_SRV = g_pPingpongBuffer[1]->m_pSRView; } else { p_RTV = g_pPingpongBuffer[1]->m_pRTView; p_SRV = g_pPingpongBuffer[0]->m_pSRView; } V(g_BPGI.m_pEffect->GetVariableByName("g_fLumiFactor")->AsScalar()->SetFloat( shadow_factor )); g_BPGI.set_parameters( para,p_RTV,p_SRV,&light_color[0] ); g_BPGI.OnD3D10FrameRender(render_ogre,render_scene,g_SampleUI,g_MeshScene,fSubLightSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); } } //----------------------------------------------------------------------------------- int light_idx = 0; float unshadow_factor; int num_applied_light = NUM_APPLIED_LIGHT; if( num_applied_light == 0 ) unshadow_factor = 0; else unshadow_factor = 0.2 / num_applied_light; for( ; light_idx < NUM_APPLIED_LIGHT; ++light_idx ) { int cam_idx = light_idx; if( light_idx == 0 ) { cam_idx = 1; } // MESH parameters may change inside loop, so reset them every time g_MeshScene.set_parameters( render_ogre, render_scene, render_fan, false ); //g_fFilterSize = light_size[light_idx]; NVUTCamera& g_LCameraRef = g_LCamera[cam_idx];//potential dangerous here g_fLightZn = light_ZNS[light_idx]; D3DXMATRIX mLightView; // here we compute light viewprojection so that light oversees the whole scene D3DXMATRIX mTranslate; D3DXMatrixInverse(&mTranslate, NULL, g_LCameraRef.GetWorldMatrix()); D3DXMatrixMultiply(&mLightView, &mTranslate, g_LCameraRef.GetViewMatrix()); g_LCameraRef.SetProjParams(light_view_angle[light_idx], 1.0, g_fLightZn, g_fLightZn + LIGHT_ZF_DELTA); // render shadow map unsigned iTmp = g_SampleUI.GetCheckBox(IDC_BDUMP_SHADOWMAP)->GetChecked(); //ssmap.Render(pDev10, &g_MeshScene, g_LCameraRef,fTime,fElapsedTime,iTmp); pDev10->RSSetState(g_pRenderState); if( ( light_idx + g_nNumLightSample * g_nNumLightSample ) % 2 == 0 ) { p_RTV = g_pPingpongBuffer[0]->m_pRTView; p_SRV = g_pPingpongBuffer[1]->m_pSRView; } else { p_RTV = g_pPingpongBuffer[1]->m_pRTView; p_SRV = g_pPingpongBuffer[0]->m_pSRView; } if( ShadowAlgorithm == STANDARD_BP ) { g_ABP.set_parameters( para,p_RTV,p_SRV,&light_color[light_idx] ); g_ABP.OnD3D10FrameRender(g_SampleUI,g_MeshScene,g_fFilterSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); } else if( ShadowAlgorithm == BP_NOSMP ) { g_ABP_nosmp.set_parameters( para,p_RTV,p_SRV,&light_color[light_idx] ); g_ABP_nosmp.OnD3D10FrameRender(g_SampleUI,g_MeshScene,g_fFilterSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); } else if( ShadowAlgorithm == MARCHING_BP ) { g_MBP.set_parameters( para,p_RTV,p_SRV,&light_color[light_idx] ); g_MBP.OnD3D10FrameRender(g_SampleUI,g_MeshScene,g_fFilterSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); } else if( ShadowAlgorithm == HIR_EDGE_EXTRACTION ) { g_HEEBP.set_parameters( para,p_RTV,p_SRV,&light_color[light_idx] ); g_HEEBP.OnD3D10FrameRender(g_SampleUI,g_MeshScene,g_fFilterSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); } else if( ShadowAlgorithm == HIR_BP ) { g_HBP.set_parameters( para,p_RTV,p_SRV,&light_color[light_idx] ); g_HBP.OnD3D10FrameRender(g_SampleUI,g_MeshScene,g_fFilterSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); } else if( ShadowAlgorithm == BP_GI ) { g_BPGI.set_parameters( para,p_RTV,p_SRV,&light_color[light_idx] ); g_BPGI.OnD3D10FrameRender(render_ogre,render_scene,g_SampleUI,g_MeshScene,g_fFilterSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); } else if( ShadowAlgorithm == NO_SHADOW_ALGORITHM ) { g_NoShadow.set_parameters( para,p_RTV,p_SRV,&light_color[light_idx] ); g_NoShadow.OnD3D10FrameRender(g_SampleUI,g_MeshScene,g_fFilterSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); } else if( ShadowAlgorithm == SINGLE_LIGHT ) { if( light_idx < 0 ) { g_BPGI.set_parameters( para,p_RTV,p_SRV,&light_color[light_idx] ); g_BPGI.OnD3D10FrameRender(render_ogre,render_scene,g_SampleUI,g_MeshScene,fSubLightSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); } else { V(g_NoShadow.m_pEffect->GetVariableByName("g_fLumiFactor")->AsScalar()->SetFloat( unshadow_factor )); g_NoShadow.set_parameters( para,p_RTV,p_SRV,&light_color[light_idx] ); g_NoShadow.OnD3D10FrameRender(g_SampleUI,g_MeshScene,g_fFilterSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); } } //render light { D3DXMATRIX mTmp, mWorldView; D3DXMatrixInverse(&mTmp, NULL, g_CameraRef.GetWorldMatrix()); D3DXMatrixMultiply(&mWorldView, &mTmp, g_CameraRef.GetViewMatrix()); D3DXMatrixMultiply(&mWorldViewProj, &mWorldView, g_CameraRef.GetProjMatrix()); D3DXMATRIX mLightViewInv; D3DXMatrixInverse(&mLightViewInv, NULL, g_LCameraRef.GetViewMatrix()); D3DXMATRIX mLightViewInvWorldViewProj; D3DXMatrixMultiply(&mLightViewInvWorldViewProj, &mLightViewInv, &mWorldViewProj); V(g_ABP.m_pEffect->GetVariableByName("mViewProj")->AsMatrix()->SetMatrix((float *)&mLightViewInvWorldViewProj)); g_ABP.m_pEffect->GetTechniqueByName("RenderNoShadows")->GetPassByIndex(0)->Apply(0); D3D10_RASTERIZER_DESC RasterizerState; RasterizerState.FillMode = D3D10_FILL_SOLID; RasterizerState.CullMode = D3D10_CULL_NONE; RasterizerState.FrontCounterClockwise = true; RasterizerState.DepthBias = false; RasterizerState.DepthBiasClamp = 0; RasterizerState.SlopeScaledDepthBias = 0; RasterizerState.DepthClipEnable = true; RasterizerState.ScissorEnable = false; RasterizerState.MultisampleEnable = false; RasterizerState.AntialiasedLineEnable = false; V(pDev10->CreateRasterizerState(&RasterizerState, &g_pRenderState)); //pDev10->RSSetState(g_pRenderState); //pDev10->IASetInputLayout(g_pMaxLayout); //g_MeshLight.Render(pDev10); } } if( ( light_idx + g_nNumLightSample * g_nNumLightSample ) % 2 == 0 ) { p_RTV = g_pPingpongBuffer[0]->m_pRTView; p_SRV = g_pPingpongBuffer[1]->m_pSRView; } else { p_RTV = g_pPingpongBuffer[1]->m_pRTView; p_SRV = g_pPingpongBuffer[0]->m_pSRView; } D3DXMATRIX mMatrixScale; D3DXMATRIX mMatrixScaleWVP; D3DXMatrixScaling( &mMatrixScale,(FLOAT)5,(FLOAT)5,(FLOAT)5 ); D3DXMatrixMultiply( &mMatrixScaleWVP, &mMatrixScale, &mWorldViewProj ); ID3D10RenderTargetView* pOrigRTV = DXUTGetD3D10RenderTargetView(); pDev10->OMSetRenderTargets(1,&pOrigRTV,pDSV); g_MeshScene.set_parameters( render_ogre,render_scene, render_fan ); g_Final.set_parameters( para, pOrigRTV, p_SRV,NULL ); NVUTCamera& g_LCameraRef = g_LCamera[0]; V(g_Final.m_pEffect->GetVariableByName("LightLumi0")->AsShaderResource()->SetResource( g_pLightLumiBuffer[0]->m_pSRView )); V(g_Final.m_pEffect->GetVariableByName("LightLumi1")->AsShaderResource()->SetResource( g_pLightLumiBuffer[1]->m_pSRView )); V(g_Final.m_pEffect->GetVariableByName("LightLumi2")->AsShaderResource()->SetResource( g_pLightLumiBuffer[2]->m_pSRView )); V(g_Final.m_pEffect->GetVariableByName("LightLumi3")->AsShaderResource()->SetResource( g_pLightLumiBuffer[3]->m_pSRView )); V(g_Final.m_pEffect->GetVariableByName("LightLumi4")->AsShaderResource()->SetResource( g_pLightLumiBuffer[4]->m_pSRView )); V(g_Final.m_pEffect->GetVariableByName("LightLumi5")->AsShaderResource()->SetResource( g_pLightLumiBuffer[5]->m_pSRView )); V(g_Final.m_pEffect->GetVariableByName("LightLumi6")->AsShaderResource()->SetResource( g_pLightLumiBuffer[6]->m_pSRView )); V(g_Final.m_pEffect->GetVariableByName("LightLumi7")->AsShaderResource()->SetResource( g_pLightLumiBuffer[7]->m_pSRView )); //g_pSkyBox->OnFrameRender( mMatrixScaleWVP ); g_Final.OnD3D10FrameRender(g_SampleUI,g_MeshScene,g_fFilterSize,ssmap,g_CameraRef,g_LCameraRef,pDev10,fTime,fElapsedTime,pUserContext); // render UI if (g_bShowUI) { RenderText(); g_SampleUI.OnRender(fElapsedTime); g_HUD.OnRender(fElapsedTime); } if( g_SampleUI.GetCheckBox( IDC_FRAME_DUMP )->GetChecked() ) { static int g_Frame = 0; IDXGISwapChain* pSwapChain = DXUTGetDXGISwapChain(); ID3D10Texture2D* pRT; pSwapChain->GetBuffer(0, __uuidof(pRT), reinterpret_cast<void**>(&pRT)); WCHAR filename[32]; StringCchPrintf(filename, 100, L"d:\\screenshot%.3d.bmp", g_Frame); D3DX10SaveTextureToFile(pRT, D3DX10_IFF_BMP, filename); pRT->Release(); ++g_Frame; } } //-------------------------------------------------------------------------------------- // Release D3D10 resources created in OnD3D10ResizedSwapChain //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10SwapChainReleasing( void* pUserContext ) { g_DialogResourceManager.OnD3D10ReleasingSwapChain(); ssmap.OnWindowResize(); g_pSkyBox->OnReleasingSwapChain(); } //-------------------------------------------------------------------------------------- // Release D3D10 resources created in OnD3D10CreateDevice //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10DestroyDevice( void* pUserContext ) { //light management for( int light_idx = 0; light_idx < NUM_LIGHT; ++light_idx ) { g_pLightLumiBuffer[light_idx]->OnD3D10DestroyDevice(pUserContext); } for( int p_idx = 0 ; p_idx < 2 ; ++p_idx ) { g_pPingpongBuffer[p_idx]->OnD3D10DestroyDevice(pUserContext); } //----------------------------------------- g_ABP.OnD3D10DestroyDevice(pUserContext); g_NoShadow.OnD3D10DestroyDevice(pUserContext); g_BPGI.OnD3D10DestroyDevice(pUserContext); g_HBP.OnD3D10DestroyDevice(pUserContext); g_HEEBP.OnD3D10DestroyDevice(pUserContext); g_MBP.OnD3D10DestroyDevice(pUserContext); g_ABP_nosmp.OnD3D10DestroyDevice(pUserContext); g_Final.OnD3D10DestroyDevice(pUserContext); ssmap.OnDestroy(); g_DialogResourceManager.OnD3D10DestroyDevice(); g_D3DSettingsDlg.OnD3D10DestroyDevice(); SAFE_RELEASE(g_pFont10); SAFE_RELEASE(g_pSprite10); SAFE_RELEASE(g_pRenderState); SAFE_RELEASE(g_pMaxLayout); g_MeshScene.Destroy(); g_MeshLight.Destroy(); g_pSkyBox->OnDestroyDevice(); g_pEnvMap->OnDestroyDevice(); }
[ [ [ 1, 1252 ] ] ]
f5bb341e0c0e8759afaf54b52b704d592f90d0dd
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/GameDLL/RocketLauncher.cpp
ccf8f99514fd50fa6fb3af581d48534a16269343
[]
no_license
richmondx/dead6
b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161
955f76f35d94ed5f991871407f3d3ad83f06a530
refs/heads/master
2021-12-05T14:32:01.782047
2008-01-01T13:13:39
2008-01-01T13:13:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,273
cpp
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2007. ------------------------------------------------------------------------- $Id:$ $DateTime$ Description: Class for specific rocket launcher functionality ------------------------------------------------------------------------- History: - 22:06:2007: Created by Benito G.R. *************************************************************************/ #include "StdAfx.h" #include "RocketLauncher.h" #include "Actor.h" #include "HUD/HUD.h" #include "HUD/HUDCrosshair.h" #include "GameRules.h" #define RL_LASER_RANGE 150.0f #define RL_LASER_TP_RANGE 8.0f #define LASER_TIMEOUT 0.15f CRocketLauncher::CRocketLauncher() { m_dotEffectSlot = m_smokeEffectSlot = -1; m_auxSlotUsed = m_auxSlotUsedBQS = m_laserTPOn = m_laserFPOn = false; m_lastLaserHitPt.Set(0.0f,0.0f,0.0f); m_lastLaserHitSolid = m_lastLaserHitViewPlane = false; m_smoothLaserLength = -1.0f; } //======================================== void CRocketLauncher::OnReset() { if(m_stats.backAttachment==eIBA_Unknown) m_auxSlotUsed = true; CWeapon::OnReset(); if(m_stats.backAttachment==eIBA_Unknown) { SetViewMode(0); DrawSlot(eIGS_ThirdPersonAux,true); } else m_stats.first_selection = false; if(m_smokeEffectSlot!=-1) { GetEntity()->FreeSlot(m_smokeEffectSlot); m_smokeEffectSlot = -1; } ActivateTPLaser(false); m_laserFPOn = m_laserTPOn = false; m_lastLaserHitPt.Set(0.0f,0.0f,0.0f); m_lastLaserHitSolid = false; m_smoothLaserLength = -1.0f; m_listeners.clear(); } //========================================= void CRocketLauncher::ProcessEvent(SEntityEvent &event) { FUNCTION_PROFILER(gEnv->pSystem, PROFILE_GAME); CWeapon::ProcessEvent(event); if(event.event == ENTITY_EVENT_RESET) { //Exiting game mode if(gEnv->pSystem->IsEditor() && !event.nParam[0]) { if(!GetOwner()) { DrawSlot(eIGS_ThirdPerson,false); DrawSlot(eIGS_ThirdPersonAux,true); m_auxSlotUsed = true; } ActivateLaserDot(false, false); } } } //======================================== bool CRocketLauncher::SetAspectProfile(EEntityAspects aspect, uint8 profile) { if(aspect!=eEA_Physics) return CWeapon::SetAspectProfile(aspect, profile); bool ok = false; if(!gEnv->bMultiplayer && gEnv->pSystem->IsSerializingFile() && m_auxSlotUsedBQS) ok = true; int slot = (m_auxSlotUsed||ok)?eIGS_ThirdPersonAux:eIGS_ThirdPerson; if (aspect == eEA_Physics) { switch (profile) { case eIPhys_PhysicalizedStatic: { SEntityPhysicalizeParams params; params.type = PE_STATIC; params.nSlot = slot; GetEntity()->Physicalize(params); return true; } break; case eIPhys_PhysicalizedRigid: { SEntityPhysicalizeParams params; params.type = PE_RIGID; params.nSlot = slot; params.mass = m_params.mass; pe_params_buoyancy buoyancy; buoyancy.waterDamping = 1.5; buoyancy.waterResistance = 1000; buoyancy.waterDensity = 0; params.pBuoyancy = &buoyancy; GetEntity()->Physicalize(params); IPhysicalEntity *pPhysics = GetEntity()->GetPhysics(); if (pPhysics) { pe_action_awake action; action.bAwake = m_ownerId!=0; pPhysics->Action(&action); } } return true; case eIPhys_NotPhysicalized: { IEntityPhysicalProxy *pPhysicsProxy = GetPhysicalProxy(); if (pPhysicsProxy) { SEntityPhysicalizeParams params; params.type = PE_NONE; params.nSlot = slot; pPhysicsProxy->Physicalize(params); } } return true; } } return false; } //======================================= void CRocketLauncher::Select(bool select) { if(select && m_auxSlotUsed) { DrawSlot(eIGS_ThirdPersonAux,false); m_auxSlotUsed = false; } CWeapon::Select(select); if(select) { if(IsOwnerFP()) { ActivateLaserDot(true,true); m_laserFPOn = true; } else { ActivateTPLaser(true); m_laserTPOn = true; } } else { m_laserFPOn = false; ActivateTPLaser(false); //Will do the rest (FP and TP) } } //======================================== void CRocketLauncher::PickUp(EntityId pickerId, bool sound, bool select, bool keepHistory) { CWeapon::PickUp(pickerId,sound,select,keepHistory); if(m_auxSlotUsed) { DrawSlot(eIGS_ThirdPersonAux,false); m_auxSlotUsed = false; } if(GetOwnerActor() && !GetOwnerActor()->IsPlayer()) m_stats.first_selection = false; } //======================================== void CRocketLauncher::FullSerialize(TSerialize ser) { CWeapon::FullSerialize(ser); int smoke = m_smokeEffectSlot; ser.Value("dotEffectSlot",m_dotEffectSlot); ser.Value("auxSlotUsed", m_auxSlotUsed); ser.Value("smokeEffect", m_smokeEffectSlot); if(ser.IsReading()) { if((smoke!=-1) && (m_smokeEffectSlot==-1)) GetEntity()->FreeSlot(smoke); } else { m_auxSlotUsedBQS = m_auxSlotUsed; } } //========================================= void CRocketLauncher::PostSerialize() { CWeapon::PostSerialize(); if(m_auxSlotUsed) { SetViewMode(0); DrawSlot(CItem::eIGS_ThirdPersonAux,true); ActivateTPLaser(false); } else DrawSlot(CItem::eIGS_ThirdPersonAux,false); if(m_smokeEffectSlot>-1) Pickalize(false,true); } //========================================= void CRocketLauncher::ActivateLaserDot(bool activate, bool fp) { if(activate) { IParticleEffect * pEffect = gEnv->p3DEngine->FindParticleEffect(fp?"muzzleflash.LAM.aimdot_FP":"muzzleflash.LAM.aimdot"); if(pEffect) { if(m_dotEffectSlot<0) { m_dotEffectSlot = GetEntity()->LoadParticleEmitter(CItem::eIGS_Aux0,pEffect); if(IParticleEmitter* pEmitter = GetEntity()->GetParticleEmitter(m_dotEffectSlot)) { pEmitter->SetRndFlags(pEmitter->GetRndFlags()|ERF_RENDER_ALWAYS); pEmitter->SetViewDistUnlimited(); pEmitter->SetLodRatio(10000); } } } } else if(m_dotEffectSlot>-1) { GetEntity()->FreeSlot(m_dotEffectSlot); m_dotEffectSlot = -1; } } //======================================= void CRocketLauncher::UpdateFPView(float frameTime) { CWeapon::UpdateFPView(frameTime); if(m_laserFPOn) UpdateDotEffect(frameTime); } //======================================= void CRocketLauncher::Update(SEntityUpdateContext& ctx, int slot) { FUNCTION_PROFILER(GetISystem(), PROFILE_GAME); CWeapon::Update(ctx,slot); if(slot==eIUS_General && m_laserTPOn) { UpdateTPLaser(ctx.fFrameTime); RequireUpdate(eIUS_General); } } //======================================== void CRocketLauncher::Drop(float impulseScale, bool selectNext, bool byDeath) { //Don't let the player drop it if it has not been opened if(m_stats.first_selection && GetOwnerActor() && GetOwnerActor()->IsPlayer() && GetOwnerActor()->GetHealth()>0) return; if(GetOwnerActor() && !GetOwnerActor()->IsPlayer()) { //In this case goes to the clip, no the inventory for(TAmmoMap::const_iterator it = m_minDroppedAmmo.begin();it!=m_minDroppedAmmo.end();it++) m_ammo[it->first] = it->second; m_minDroppedAmmo.clear(); } CWeapon::Drop(impulseScale,selectNext,byDeath); if(m_fm && GetAmmoCount(m_fm->GetAmmoType())<=0) { Pickalize(false,true); if(m_smokeEffectSlot==-1) { IParticleEffect * pEffect = gEnv->p3DEngine->FindParticleEffect("weapon_fx.LAW.empty"); if(pEffect) m_smokeEffectSlot = GetEntity()->LoadParticleEmitter(-1,pEffect); } } } //========================================= bool CRocketLauncher::CanPickUp(EntityId userId) const { CActor *pActor = GetActor(userId); IInventory *pInventory=GetActorInventory(pActor); if (m_params.pickable && m_stats.pickable && !m_stats.flying && !m_frozen &&(!m_ownerId || m_ownerId==userId) && !m_stats.selected && !GetEntity()->IsHidden()) { if (pInventory && pInventory->FindItem(GetEntityId())!=-1) return false; } else return false; uint8 uniqueId = m_pItemSystem->GetItemUniqueId(GetEntity()->GetClass()->GetName()); //Can not pick up a LAW while I have one already if(pInventory && (pInventory->GetCountOfUniqueId(uniqueId)>0)) { if(pActor->IsClient()) g_pGame->GetGameRules()->OnTextMessage(eTextMessageCenter, "@mp_CannotCarryMoreLAW"); return false; } return true; } //========================================= void CRocketLauncher::UpdateDotEffect(float frameTime) { Vec3 laserPos, dir; laserPos = GetSlotHelperPos(eIGS_FirstPerson,"scope",true); Quat rot = Quat(GetSlotHelperRotation(eIGS_FirstPerson,"weapon_term",true)); dir = rot.GetColumn0(); dir.Normalize(); CActor *pActor = GetOwnerActor(); IMovementController * pMC = pActor ? pActor->GetMovementController() : NULL; if (pMC) { SMovementState info; pMC->GetMovementState(info); if(dir.Dot(info.fireDirection)>0.985f) { CCamera& camera = gEnv->pSystem->GetViewCamera(); laserPos = camera.GetPosition(); dir = camera.GetMatrix().GetColumn1(); dir.Normalize(); } } float len = RL_LASER_RANGE; Vec3 hitPos(0,0,0); float laserLength = 0.0f; float dotScale=1.0f; { float nearFoV = *(float*)gEnv->pRenderer->EF_Query(EFQ_DrawNearFov); float fovScale = 60.0f/nearFoV; IPhysicalEntity* pSkipEntity = NULL; if(GetOwner()) pSkipEntity = GetOwner()->GetPhysics(); const int objects = ent_all; const int flags = (geom_colltype_ray << rwi_colltype_bit) | rwi_colltype_any | (10 & rwi_pierceability_mask) | (geom_colltype14 << rwi_colltype_bit); ray_hit hit; if (gEnv->pPhysicalWorld->RayWorldIntersection(laserPos, dir*RL_LASER_RANGE, objects, flags, &hit, 1, &pSkipEntity, pSkipEntity?1:0)) { laserLength = hit.dist; hitPos = hit.pt; if(fovScale>2.0f) { if(laserLength<15.0f) dotScale = (2.0f/fovScale); else dotScale = (4.0f/fovScale); } } else { hitPos = laserPos + dir * RL_LASER_RANGE; laserLength = RL_LASER_RANGE + 0.1f; } } if (m_dotEffectSlot>=0) { //Force it always to be active //if(IParticleEmitter* pEmitter = GetEntity()->GetParticleEmitter(m_dotEffectSlot)) //pEmitter->Hide(false); Matrix34 worldMatrix = GetEntity()->GetWorldTM(); if((hitPos-laserPos).len2()<=4.0f) hitPos = laserPos+(2.0f*dir); Matrix34 localMatrix = worldMatrix.GetInverted()*Matrix34::CreateTranslationMat(hitPos-(0.2f*dir)); localMatrix.Scale(Vec3(dotScale,dotScale,dotScale)); GetEntity()->SetSlotLocalTM(m_dotEffectSlot, localMatrix); } } //---------------------------------------------------- void CRocketLauncher::ActivateTPLaser(bool activate) { if(activate) { DrawSlot(CItem::eIGS_Aux1,true); ActivateLaserDot(true,false); m_laserTPOn = true; //Force first update m_lastUpdate = 0.0f; m_smoothLaserLength = -1.0f; UpdateTPLaser(0.0f); RequireUpdate(eIUS_General); } else { DrawSlot(CItem::eIGS_Aux1,false); GetEntity()->SetSlotLocalTM(CItem::eIGS_Aux1,Matrix34::CreateIdentity()); ActivateLaserDot(false,false); m_laserTPOn = false; } } //---------------------------------------------------- void CRocketLauncher::UpdateTPLaser(float frameTime) { m_lastUpdate -= frameTime; bool allowUpdate = true; if(m_lastUpdate<=0.0f) m_lastUpdate = LASER_TIMEOUT; else allowUpdate = false; const CCamera& camera = gEnv->pRenderer->GetCamera(); //If character not visible, laser is not correctly updated if(CActor* pOwner = GetOwnerActor()) { ICharacterInstance* pCharacter = pOwner->GetEntity()->GetCharacter(0); if(pCharacter && !pCharacter->IsCharacterVisible()) return; } Vec3 offset(-0.06f,0.28f,0.115f); //To match scope position in TP LAW model Vec3 pos = GetEntity()->GetWorldTM().TransformPoint(offset); Vec3 dir = GetEntity()->GetWorldRotation().GetColumn1(); float len = RL_LASER_TP_RANGE; Vec3 hitPos(0,0,0); float laserLength = 0.0f; if(allowUpdate) { IPhysicalEntity* pSkipEntity = NULL; if(GetOwner()) pSkipEntity = GetOwner()->GetPhysics(); const float range = RL_LASER_TP_RANGE; // Use the same flags as the AI system uses for visibility. const int objects = ent_terrain|ent_static|ent_rigid|ent_sleeping_rigid|ent_independent; //ent_living; const int flags = (geom_colltype_ray << rwi_colltype_bit) | rwi_colltype_any | (10 & rwi_pierceability_mask) | (geom_colltype14 << rwi_colltype_bit); ray_hit hit; if (gEnv->pPhysicalWorld->RayWorldIntersection(pos, dir*range, objects, flags, &hit, 1, &pSkipEntity, pSkipEntity ? 1 : 0)) { laserLength = hit.dist; m_lastLaserHitPt = hit.pt; m_lastLaserHitSolid = true; } else { m_lastLaserHitSolid = false; m_lastLaserHitPt = pos + dir * range; laserLength = range + 0.1f; } // Hit near plane if (dir.Dot(camera.GetViewdir()) < 0.0f) { Plane nearPlane; nearPlane.SetPlane(camera.GetViewdir(), camera.GetPosition()); nearPlane.d -= camera.GetNearPlane()+0.15f; Ray ray(pos, dir); Vec3 out; m_lastLaserHitViewPlane = false; if (Intersect::Ray_Plane(ray, nearPlane, out)) { float dist = Distance::Point_Point(pos, out); if (dist < laserLength) { laserLength = dist; m_lastLaserHitPt = out; m_lastLaserHitSolid = true; m_lastLaserHitViewPlane = true; } } } hitPos = m_lastLaserHitPt; } else { laserLength = Distance::Point_Point(m_lastLaserHitPt, pos); hitPos = pos + dir * laserLength; } if (m_smoothLaserLength < 0.0f) m_smoothLaserLength = laserLength; else { if (laserLength < m_smoothLaserLength) m_smoothLaserLength = laserLength; else m_smoothLaserLength += (laserLength - m_smoothLaserLength) * min(1.0f, 10.0f * frameTime); } const float assetLength = 2.0f; m_smoothLaserLength = CLAMP(m_smoothLaserLength,0.01f,RL_LASER_TP_RANGE); float scale = m_smoothLaserLength / assetLength; // Scale the laser based on the distance. Matrix34 scl; scl.SetIdentity(); scl.SetScale(Vec3(1,scale,1)); scl.SetTranslation(offset); GetEntity()->SetSlotLocalTM(CItem::eIGS_Aux1, scl); if (m_dotEffectSlot >= 0) { if (m_lastLaserHitSolid) { Matrix34 dotMatrix = Matrix34::CreateTranslationMat(Vec3(0,m_smoothLaserLength,0)); dotMatrix.AddTranslation(offset); if(m_lastLaserHitViewPlane) dotMatrix.Scale(Vec3(0.2f,0.2f,0.2f)); GetEntity()->SetSlotLocalTM(m_dotEffectSlot,dotMatrix); } else { Matrix34 scaleMatrix; scaleMatrix.SetIdentity(); scaleMatrix.SetScale(Vec3(0.001f,0.001f,0.001f)); GetEntity()->SetSlotLocalTM(m_dotEffectSlot, scaleMatrix); } } } //=============================================== void CRocketLauncher::GetAttachmentsAtHelper(const char *helper, std::vector<string> &rAttachments) { //Do nothing... //Rocket launcher has an special helper for the scope, but it must be skipped by the HUD }
[ "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 600 ] ] ]
fcf5e18bb682107319215e5ce8acc3b6be9607be
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Platforms/Ogre/OgrePlatform/include/MyGUI_OgreDataManager.h
c931c380bd252bf501a07469aa4a759e555f2b34
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
1,370
h
/*! @file @author Albert Semenov @date 05/2008 */ #ifndef __MYGUI_OGRE_DATA_MANAGER_H__ #define __MYGUI_OGRE_DATA_MANAGER_H__ #include "MyGUI_Prerequest.h" #include "MyGUI_DataManager.h" namespace MyGUI { class OgreDataManager : public DataManager { public: OgreDataManager(); void initialise(const std::string& _group); void shutdown(); static OgreDataManager& getInstance() { return *getInstancePtr(); } static OgreDataManager* getInstancePtr() { return static_cast<OgreDataManager*>(DataManager::getInstancePtr()); } const std::string& getGroup() { return mGroup; } /** @see DataManager::getData */ virtual IDataStream* getData(const std::string& _name); typedef std::vector<std::string> VectorString; /** @see DataManager::isDataExist */ virtual bool isDataExist(const std::string& _name); /** @see DataManager::getDataListNames */ virtual const VectorString& getDataListNames(const std::string& _pattern); /** @see DataManager::getDataPath */ virtual const std::string& getDataPath(const std::string& _name); private: const VectorString& getDataListNames(const std::string& _pattern, bool _fullpath); private: std::string mGroup; bool mIsInitialise; }; } // namespace MyGUI #endif // __MYGUI_OGRE_DATA_MANAGER_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 64 ] ] ]
e4b3c77d8bb955a88a49414112ae415a4d5626c4
c63685bfe2d1ecfdfebcda0eab70642f6fcf4634
/Dog_GLSL_ABR/ShaderObject.h
c464787bec26990d13e28ea355f57fffbccb5ea8
[]
no_license
Shell64/cgdemos
8afa9272cef51e6d0544d672caa0142154e231fc
d34094d372fea0536a5b3a17a861bb1a1bfac8c4
refs/heads/master
2021-01-22T23:26:19.112999
2011-10-13T12:38:10
2011-10-13T12:38:10
35,008,078
1
0
null
null
null
null
UTF-8
C++
false
false
786
h
#ifndef __SHADER_OBJECT_H__ #define __SHADER_OBJECT_H__ class ShaderObject { public: static int ReadSahderFile( const char* file, char*& code ); ShaderObject( int type, const char* source, bool is_file = false ); ~ShaderObject( ); inline bool IsValidShaderObject() { return 0 != m_shaderID && m_is_compiled; } inline bool IsValidVertexShader() { return GL_VERTEX_SHADER == m_type && IsValidShaderObject(); } inline bool IsValidFragmentShader() { return GL_FRAGMENT_SHADER == m_type && IsValidShaderObject(); } inline GLuint GetShaderID() { return m_shaderID; } private: void CheckCompileLog(); void PrintCompileLog( std::ostream & os ); private: GLuint m_shaderID; int m_type; bool m_is_compiled; }; #endif//__SHADER_OBJECT_H__
[ "hpsoar@6e3944b4-cba9-11de-a8df-5d31f88aefc0" ]
[ [ [ 1, 32 ] ] ]
b40b6265d4e3a5ddb349fefb6c01cd496f610f2b
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/nsrpc/include/nsrpc/utility/SystemUtil.h
942696aae78add3e5912e27d8543aaed2a232ace
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UHC
C++
false
false
365
h
#ifndef NSRPC_SYSTEMUTIL_H #define NSRPC_SYSTEMUTIL_H #ifdef _MSC_VER # pragma once #endif #include "../nsrpc.h" namespace nsrpc { /** @addtogroup utility * @{ */ /// msec만큼 현재 쓰레드를 중지시킨다. void NSRPC_API pause(size_t msec); /** @} */ // addtogroup utility } // namespace nsrpc #endif // NSRPC_SYSTEMUTIL_H
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 24 ] ] ]
73beeed130e1d7d0a650a9c4ba3dff1d80629e41
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/applications/maxPlugin/RigidBodyController.cpp
c837d4290508ee1af938a973d7b5ee381cac320b
[]
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
15,911
cpp
/* Copyright (c) <2003-2011> <Julio Jerez, 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, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "Common.h" #include "RigidBodyWorld.h" #include "RigidBodyController.h" class RigidBodyControllerUndoRedo: public RestoreObj { public: RigidBodyControllerUndoRedo(RigidBodyController* const control, TimeValue t) :m_undotime (t) ,m_redotime (t) ,m_control (control) { Interval valid; m_control->GetValue(t, &m_undoMatrix, valid, CTRL_ABSOLUTE); m_undoCollision = NewtonBodyGetCollision (control->m_body); NewtonBodyGetVelocity(control->m_body, &m_undoveloc[0]); NewtonBodyGetOmega(control->m_body, &m_undoomega[0]); NewtonAddCollisionReference (m_undoCollision); } ~RigidBodyControllerUndoRedo() { _ASSERTE (m_undoCollision); RigidBodyWorldDesc* const me = (RigidBodyWorldDesc*) RigidBodyWorldDesc::GetDescriptor(); NewtonReleaseCollision (me->m_newton, m_undoCollision); } void Restore(int isUndo) { if (isUndo) { Interval valid; m_redotime = m_undotime; m_control->GetValue(m_redotime, &m_redoMatrix, valid, CTRL_ABSOLUTE); NewtonBodyGetVelocity(m_control->m_body, &m_redoveloc[0]); NewtonBodyGetOmega(m_control->m_body, &m_redoomega[0]); } m_control->m_undoCollision = m_undoCollision; SetXFormPacket transform (m_undoMatrix); NewtonBodySetVelocity(m_control->m_body, &m_undoveloc[0]); NewtonBodySetOmega(m_control->m_body, &m_undoomega[0]); m_control->SetValue(m_undotime, &transform, 1, CTRL_ABSOLUTE); m_control->NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); } void Redo() { SetXFormPacket transform (m_redoMatrix); NewtonBodySetVelocity(m_control->m_body, &m_redoveloc[0]); NewtonBodySetOmega(m_control->m_body, &m_redoomega[0]); m_control->SetValue(m_redotime, &transform, 1, CTRL_ABSOLUTE); m_control->NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); m_control->m_undoCollision = m_undoCollision; m_control->m_updateMatrixFormRedo = true; } int Size() { return sizeof(RigidBodyControllerUndoRedo); } void EndHold() { m_control->ClearAFlag(A_HELD); } TimeValue m_undotime; TimeValue m_redotime; Matrix3 m_undoMatrix; Matrix3 m_redoMatrix; dVector m_undoveloc; dVector m_redoveloc; dVector m_undoomega; dVector m_redoomega; RigidBodyController* m_control; NewtonCollision* m_undoCollision; }; struct RendefGizmoInfo { dMatrix m_matrix; GraphicsWindow* m_graphicWindow; RigidBodyController* m_me; }; RigidBodyController::RigidBodyController(BOOL loading) :Control() ,RigidBodyData() ,m_scaleControl(NULL) ,m_positionControl(NULL) ,m_rotationControl(NULL) ,pblock(NULL) ,m_updateMatrixFormRedo(false) { // curval = Matrix3(1); blockUpdate = FALSE; if(!loading) { ReplaceReference(0, NewDefaultPositionController()); ReplaceReference(1, NewDefaultRotationController()); ReplaceReference(2, NewDefaultScaleController()); ivalid = FOREVER; } else { ivalid.SetEmpty(); } } RigidBodyController::~RigidBodyController() { DeleteAllRefsFromMe(); } IOResult RigidBodyController::Load(ILoad *iload) { IOResult ret = Control::Load(iload); RigidBodyData* const data = this; iload->OpenChunk(); data->Load(iload); iload->CloseChunk(); return ret; } IOResult RigidBodyController::Save(ISave *isave) { IOResult ret = Control::Save(isave); RigidBodyData* const data = this; Class_ID id (RigidBodyController::ClassID()); isave->BeginChunk(USHORT (id.PartB())); data->Save(isave); isave->EndChunk(); return ret; } void RigidBodyController::SaveUndoState(TimeValue t) { if ( theHold.Holding() ) { theHold.Put(new RigidBodyControllerUndoRedo (this, t)); } } void RigidBodyController::MouseCycleStarted (TimeValue t) { SaveUndoState(t); } void RigidBodyController::Init (const RigidBodyData& data, INode* const node) { RigidBodyWorldDesc* const plugin = (RigidBodyWorldDesc*) RigidBodyWorldDesc::GetDescriptor(); RigidBodyData* const myData = this; memcpy (myData, &data, sizeof (RigidBodyData)); float scale = float (GetMasterScale(UNITS_METERS)); ObjectState os (node->EvalWorldState(0)); _ASSERTE (os.obj); Box3 box; os.obj->GetLocalBoundBox(0, node, NULL, box); Point3 center (box.Center()); Point3 boxSize (box.Width()); dMatrix GeoMatrix (GetMatrixFromMaxMatrix (node->GetObjectTM(GetCOREInterface()->GetTime()))); dMatrix nodeMatrix (GetMatrixFromMaxMatrix (node->GetNodeTM(GetCOREInterface()->GetTime()))); dMatrix offset (GeoMatrix * nodeMatrix.Inverse4x4()); offset.m_posit.m_x += center.x; offset.m_posit.m_y += center.y; offset.m_posit.m_z += center.z; offset = plugin->m_systemMatrixInv * offset * plugin->m_systemMatrix; offset.m_posit = offset.m_posit.Scale (scale); dVector size (plugin->m_systemMatrix.RotateVector(dVector(boxSize.x, boxSize.y, boxSize.z, 0.0f))); size = size.Scale (scale); NewtonCollision* collision = NULL; switch (m_collisionShape) { case m_box: { collision = NewtonCreateBox(plugin->m_newton, size.m_x, size.m_y, size.m_z, 0, &offset[0][0]); break; } case m_convexHull: { _ASSERTE (0); break; } default:; { _ASSERTE (0); } } nodeMatrix = plugin->m_systemMatrixInv * nodeMatrix * plugin->m_systemMatrix; nodeMatrix.m_posit = nodeMatrix.m_posit.Scale (scale); NewtonConvexCollisionCalculateInertialMatrix (collision, &m_inertia[0], &m_origin[0]); CreateBody (collision, dVector (0.0f, 0.0f, 0.0f, 0.0f), dVector (0.0f, 0.0f, 0.0f, 0.0f)); // m_body = NewtonCreateBody(plugin->m_newton, collision, &nodeMatrix[0][0]); NewtonBodySetUserData(m_body, node); NewtonBodySetMatrix(m_body, &nodeMatrix[0][0]); // NewtonBodySetCentreOfMass(m_body, &m_origin[0]); // NewtonBodySetMassMatrix(m_body, m_mass, m_mass * m_inertia.m_x, m_mass * m_inertia.m_y, m_mass * m_inertia.m_z); // NewtonBodySetForceAndTorqueCallback(m_body, ApplyGravityForce); NewtonReleaseCollision(plugin->m_newton, collision); } void RigidBodyController::DeleteThis() { delete this; } // return number of ParamBlocks in this instance int RigidBodyController::NumParamBlocks() { return 1; } // return i'th ParamBlock IParamBlock2* RigidBodyController::GetParamBlock(int i) { return pblock; } // return id'd ParamBlock IParamBlock2* RigidBodyController::GetParamBlockByID(BlockID id) { return (pblock->ID() == id) ? pblock : NULL; } void RigidBodyController::GetClassName(TSTR& s) { s = GetString(IDS_CLASS_NAME); } Class_ID RigidBodyController::ClassID() { return RigidBodyControllerDesc::GetDescriptor()->ClassID(); } SClass_ID RigidBodyController::SuperClassID() { return RigidBodyControllerDesc::GetDescriptor()->SuperClassID(); } int RigidBodyController::NumSubs() { return 3; } Animatable* RigidBodyController::SubAnim(int i) { return GetReference(i); } TSTR RigidBodyController::SubAnimName(int i) { switch (i) { case 0: return _T("POS"); case 1: return _T("ROT"); case 2: return _T("SCL"); default: return _T(""); } } int RigidBodyController::NumRefs() { return 1; } RefTargetHandle RigidBodyController::GetReference(int i) { switch (i) { case 0: return m_positionControl; case 1: return m_rotationControl; case 2: return m_scaleControl; default: return NULL; } } void RigidBodyController::SetReference(int i, RefTargetHandle rtarg) { switch (i) { case 0: m_positionControl = (Control*)rtarg; break; case 1: m_rotationControl = (Control*)rtarg; break; case 2: m_scaleControl = (Control*)rtarg; break; } } RefResult RigidBodyController::NotifyRefChanged(Interval iv, RefTargetHandle hTarg, PartID& partID, RefMessage msg) { ivalid.SetEmpty(); return REF_SUCCEED; } void RigidBodyController::PostCloneNode() { } RefTargetHandle RigidBodyController::Clone(RemapDir& remap) { RigidBodyController* const myctrl = new RigidBodyController(); myctrl->ReplaceReference(0, remap.CloneRef(m_positionControl)); myctrl->ReplaceReference(1, remap.CloneRef(m_rotationControl)); myctrl->ReplaceReference(2, remap.CloneRef(m_scaleControl)); BaseClone(this, myctrl, remap); RigidBodyControllerDesc& controlDesc = *(RigidBodyControllerDesc*)RigidBodyControllerDesc::GetDescriptor(); RigidBodyData* const srcData = this; RigidBodyData* const dstData = myctrl; memcpy (dstData, srcData, sizeof (RigidBodyData)); dstData->m_undoCollision = NewtonBodyGetCollision(srcData->m_body); dstData->m_body = NULL; return myctrl; } void RigidBodyController::Copy(Control* from) { if (from->ClassID()==ClassID()) { RigidBodyController *ctrl = (RigidBodyController*)from; ReplaceReference(0, ctrl->m_positionControl); ReplaceReference(1, ctrl->m_rotationControl); ReplaceReference(2, ctrl->m_scaleControl); // curval = ctrl->curval; ivalid = ctrl->ivalid; } else { SetXFormPacket pckt; Interval iv; pckt.tmAxis.IdentityMatrix(); pckt.tmParent.IdentityMatrix(); from->GetValue(0, &pckt.tmAxis, iv, CTRL_RELATIVE); pckt.command = XFORM_SET; SetValue(0, &pckt, TRUE, CTRL_ABSOLUTE); } NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); } void RigidBodyController::Move(TimeValue t, Matrix3& partm, Matrix3& tmAxis, Point3& v, BOOL localOrigin, int commit) { Point3 p = VectorTransform( tmAxis*Inverse(partm), v ); m_positionControl->SetValue(t, &p, commit, CTRL_RELATIVE); } void RigidBodyController::Rotate(TimeValue t, const AngAxis& aa, int commit) { Quat quat (aa); m_rotationControl->SetValue (t, &quat, commit, CTRL_RELATIVE); } void RigidBodyController::SetAbsValue(TimeValue t, const Matrix3 &val, const Matrix3 &parent, int commit) { Matrix3 pparent = ApplyInheritance(t, parent, m_positionControl); AffineParts parts; Matrix3 mat = val * Inverse(pparent); decomp_affine(mat, &parts); m_positionControl->SetValue(t,&parts.t,commit,CTRL_ABSOLUTE); m_rotationControl->SetValue(t,&parts.q,commit,CTRL_ABSOLUTE); ScaleValue sv; sv.s = parts.k * parts.f; sv.q = parts.u; m_scaleControl->SetValue(t,&sv,commit,CTRL_ABSOLUTE); } void RigidBodyController::UpdateRigidBodyMatrix(TimeValue t) { if (m_body) { Interval valid; Matrix3 maxMatrix; GetValue(t, &maxMatrix, valid, CTRL_ABSOLUTE); dMatrix matrix (GetMatrixFromMaxMatrix (maxMatrix)); RigidBodyWorldDesc* const desc = (RigidBodyWorldDesc*) RigidBodyWorldDesc::GetDescriptor(); float scale = float (GetMasterScale(UNITS_METERS)); matrix = desc->m_systemMatrixInv * matrix * desc->m_systemMatrix; matrix.m_posit = matrix.m_posit.Scale (scale); // this does not handle scale yet, remember to extra scale for the matrix, // the simplest way is removing the scale controller form the PRS controller NewtonBodySetMatrix (m_body, &matrix[0][0]); } } void RigidBodyController::SetValue(TimeValue t, void *val, int commit, GetSetMethod method) { PreRefNotifyDependents(); SetXFormPacket* const ptr = (SetXFormPacket*)val; Matrix3 ptm = ApplyInheritance(t, ptr->tmParent, m_positionControl); RigidBodyWorldDesc* const desc = (RigidBodyWorldDesc*) RigidBodyWorldDesc::GetDescriptor(); float scale = float (GetMasterScale(UNITS_METERS)); switch (ptr->command) { case XFORM_SCALE: { break; } case XFORM_ROTATE: { Rotate(t, ptr->aa, commit); break; } case XFORM_MOVE: { Move(t, ptm, ptr->tmAxis, ptr->p, ptr->localOrigin, commit); break; } case XFORM_SET: { SetAbsValue(t, ptr->tmAxis, ptm, commit); break; } } if (desc->m_updateRigidBodyMatrix) { UpdateRigidBodyMatrix(t); } NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE); PostRefNotifyDependents(); } Matrix3 RigidBodyController::ApplyInheritance(TimeValue t, const Matrix3 &ptm, Control *pos, Point3 cpos, BOOL usecpos) { return ptm; } void RigidBodyController::GetValue(TimeValue t, void *val, Interval &valid, GetSetMethod method) { if (method == CTRL_ABSOLUTE) { Interval valid; Point3 posit; Quat rotation; m_positionControl->GetValue(t, &posit, valid, CTRL_ABSOLUTE); m_rotationControl->GetValue(t, &rotation, valid, CTRL_ABSOLUTE); dMatrix controlMatrix (dQuaternion (rotation.w, -rotation.x, -rotation.y, -rotation.z), dVector (posit.x, posit.y, posit.z, 1.0f)); Matrix3& matrix = *((Matrix3*)val); matrix = GetMatrixFromdMatrix (controlMatrix); } else { Matrix3& matrix = *((Matrix3*)val); matrix = ApplyInheritance(t, matrix, m_positionControl); m_positionControl->GetValue(t, val, valid, method); m_rotationControl->GetValue(t, val, valid, method); m_scaleControl->GetValue(t, val, valid, method); } } void RigidBodyController::ApplyGravityForce (const NewtonBody* const body, dFloat timestep, int threadIndex) { dFloat Ixx; dFloat Iyy; dFloat Izz; dFloat mass; NewtonBodyGetMassMatrix (body, &mass, &Ixx, &Iyy, &Izz); RigidBodyWorldDesc* const plugin = (RigidBodyWorldDesc*) RigidBodyWorldDesc::GetDescriptor(); dVector gravity (plugin->m_gravity.Scale (mass)); NewtonBodySetForce (body, &gravity.m_x); } void RigidBodyController::RenderGizmo (void* const userData, int vertexCount, const dFloat* const faceArray, int faceId) { RendefGizmoInfo* const info = (RendefGizmoInfo*) userData; GraphicsWindow* const gw = info->m_graphicWindow; Point3 point3[256]; info->m_matrix.TransformTriplex (&point3[0].x, sizeof (Point3), faceArray, 3 * sizeof (dFloat), vertexCount); gw->polyline (vertexCount, point3, NULL, NULL, TRUE, NULL); } int RigidBodyController::Display(TimeValue t, INode* inode, ViewExp *vpt, int flags) { if (!m_hideGizmos && m_body && NewtonBodyGetUserData(m_body)) { if (m_updateMatrixFormRedo) { UpdateRigidBodyMatrix(t); m_updateMatrixFormRedo = false; } _ASSERTE (NewtonBodyGetUserData(m_body) == inode); GraphicsWindow* const gw = vpt->getGW(); float scale = 1.0f / float (GetMasterScale(UNITS_METERS)); RigidBodyWorldDesc* const desc = (RigidBodyWorldDesc*) RigidBodyWorldDesc::GetDescriptor(); gw->setColor (LINE_COLOR, Point3 (1.0f, 0.5f, 0.0f)); RendefGizmoInfo info; dMatrix scaleMtarix (GetIdentityMatrix()); scaleMtarix[0][0] = scale; scaleMtarix[1][1] = scale; scaleMtarix[2][2] = scale; info.m_me = this; info.m_matrix = scaleMtarix * desc->m_systemMatrixInv; info.m_graphicWindow = gw; gw->setTransform(Matrix3(TRUE)); NewtonCollision* const collision = NewtonBodyGetCollision(m_body); dMatrix matrix; NewtonBodyGetMatrix (m_body, &matrix[0][0]); NewtonCollisionForEachPolygonDo (collision, &matrix[0][0], RenderGizmo, &info); return 1; } else { return 0; } }
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 590 ] ] ]
6ae6ef7db9b230e1b1f445c442cd1c45f1cc93a8
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Pilot/Lokapala_Neverdie/Raptor/OSDecisionSD.cpp
75db48ea002f8342a6e7891f798df6fc819facc3
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UHC
C++
false
false
151
cpp
/**@file OSDecisionSD.cpp * @brief OSM의 DecisionSD의 멤버함수 구현 * @author siva */ #include "stdafx.h" #include "OSDecisionSD.h"
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 7 ] ] ]
5f77e1b7535ba36c02811e04939db8b5ccabff2b
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/systemhealth/systemhealthgadgetwidget.h
7c5817820c741421cd0505d8ea4e13ab74fc46d1
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,176
h
/** ****************************************************************************** * * @file systemhealthgadgetwidget.h * @author Edouard Lafargue Copyright (C) 2010. * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup SystemHealthPlugin System Health Plugin * @{ * @brief The System Health gadget plugin *****************************************************************************/ /* * 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, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef SYSTEMHEALTHGADGETWIDGET_H_ #define SYSTEMHEALTHGADGETWIDGET_H_ #include "systemhealthgadgetconfiguration.h" #include "uavobjects/uavobject.h" #include <QGraphicsView> #include <QtSvg/QSvgRenderer> #include <QtSvg/QGraphicsSvgItem> #include <QFile> #include <QTimer> class SystemHealthGadgetWidget : public QGraphicsView { Q_OBJECT public: SystemHealthGadgetWidget(QWidget *parent = 0); ~SystemHealthGadgetWidget(); void setSystemFile(QString dfn); void setIndicator(QString indicator); void paint(); protected: void paintEvent(QPaintEvent *event); void resizeEvent(QResizeEvent *event); private slots: void updateAlarms(UAVObject *systemAlarm); // Called by the systemalarms UAVObject private: QSvgRenderer *m_renderer; QGraphicsSvgItem *background; QGraphicsSvgItem *foreground; // Simple flag to skip rendering if the bool fgenabled; // layer does not exist. }; #endif /* SYSTEMHEALTHGADGETWIDGET_H_ */
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 67 ] ] ]
384ab32d07c13b563b5d35759453ed2b0a5d5db3
93eac58e092f4e2a34034b8f14dcf847496d8a94
/ncl30-cpp/ncl30-generator/src/SwitchNodeGenerator.cpp
1837373644dd2159f4606f5997bb13f79c6840bc
[]
no_license
lince/ginga-srpp
f8154049c7e287573f10c472944315c1c7e9f378
5dce1f7cded43ef8486d2d1a71ab7878c8f120b4
refs/heads/master
2020-05-27T07:54:24.324156
2011-10-17T13:59:11
2011-10-17T13:59:11
2,576,332
0
0
null
null
null
null
UTF-8
C++
false
false
4,344
cpp
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribuido na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br *******************************************************************************/ /** * @file SwitchNodeGenerator.cpp * @author Caio Viel * @date 29-01-10 */ #include "../include/generables/SwitchNodeGenerator.h" namespace br { namespace ufscar { namespace lince { namespace ncl { namespace generator { string SwitchNodeGenerator::generateCode(NclDocument* nclDocument) { string ret = "<switch id=\"" + this->getId() + "\" >"; Node* defaultNode = this->getDefaultNode(); if (defaultNode != NULL) { ret += "<defaultComponent component=\"" + defaultNode->getId() + "\" />"; } vector<Node*>* nodes = this->getNodes(); vector<Node*>::iterator itNode; itNode = nodes->begin(); while (itNode != nodes->end()) { Node* node = *itNode; if (node->instanceOf("ReferNode")) { ReferNode* referNode = (ReferNode*)node; ret += GeneratorUtil::referNodeCodeGenerate(referNode, nclDocument); } else if (node->instanceOf("ContextNode")) { ContextNode * contextNode = (ContextNode*)node; ret+= static_cast<ContextNodeGenerator*>(contextNode)->generateCode(nclDocument) + "\n"; } else if (node->instanceOf("ContentNode")) { ContentNode* contentNode = (ContentNode*)node; ret+= static_cast<ContentNodeGenerator*>(contentNode)->generateCode() + "\n"; } else if (node->instanceOf("SwitchNode")) { SwitchNode* switchNode = (SwitchNode*) node; ret+= static_cast<SwitchNodeGenerator*>(switchNode)->generateCode(nclDocument) + "\n"; } itNode++; } unsigned int numRules = this->getNumRules(); if (numRules > 0) { for (int index = 0; index < numRules; index++) { Rule* rule = this->getRule(index); Node* node = this->getNode(rule); ret += "<bindRule rule=\"" + rule->getId() + "\" "; ret += "constituent=\"" + descriptor->getId() + "\" />\n"; } } vector<Port*>* ports = this->getPorts(); vector<Port*>::iterator itPorts; itPorts = ports->begin(); while (itPorts != ports->end()) { Port* port = *itPorts; if (port->instanceOf("SwitchPort")) { SwitchPort* switchPort = (SwitchPort*) port; ret += (static_cast<SwitchPortGenerator*>(switchPort))->generateCode() + "\n"; } } ret += "</switch>\n"; return ret; } } } } } }
[ [ [ 1, 121 ] ] ]
244fc035b0256f91c60b703488ada0814ae2f42a
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak.wxWidgets/wxPropertiesWindow.inl
3b02cedf1738c569e70ee0f7cfc5a8683724644a
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
60
inl
namespace Halak { namespace wxWidgets { } }
[ [ [ 1, 6 ] ] ]
8b20c12a950cab0040133635c22954cde5c9d8e3
4c6237dccf0d88085e1477c2678509cd75919fa0
/src/raytracer/cylinder.cxx
53544981264857d33a3e394b8ba610014e4b9051
[ "BSD-3-Clause" ]
permissive
tomka/copo-tracer
7ebd4670067bf404b19990bcd83db55384e7b87a
7a272acbf19acef9eea8330e503ad95e371bd9b3
refs/heads/master
2021-01-10T19:43:35.757275
2010-10-04T15:35:33
2010-10-04T15:35:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,280
cxx
// Copyright: The original source code was provided by Sören König (Soeren.Koenig // AT tu-dresden.de). You are free to modify and/or redistribute that code in // terms of the BSD license. #include "cylinder.h" #include "math_utils.h" cylinder::cylinder():bottom(0,0,0),top(0,1,0),radius(0.25),finite(true),caps(true) { } cylinder::cylinder(const tiny_vec<float,3>& p1, const tiny_vec<float,3>& p2,const float& r) { bottom = p1; top = p2; radius = r; finite=true; caps=true; } void cylinder::calc_normal(intersection_info* hit) { tiny_vec<float,3> l = hit->get_location(); tiny_vec<float,3> p = l-top; tiny_vec<float,3> q = l-bottom; tiny_vec<float,3> Va = (top-bottom); Va.normalize(); tiny_vec<float,3> nml; bool capnml = false; if(caps) { if(p.sqr_length() < radius*radius && std::abs(dot(p,Va)) < 0.001) { nml = Va; capnml=true; } if(q.sqr_length() < radius*radius && std::abs(dot(q,Va)) < 0.001) { nml = -Va; capnml=true; } } if(!capnml) { nml = l-dot(q,Va)*Va; nml.normalize(); } if(dot(nml,hit->get_incoming_ray().get_direction()) < 0) hit->set_normal(nml); else hit->set_normal (-nml); } bool cylinder::closest_intersection(intersection_info* hit, float min_lambda) { // if(dont_hit == this) // return false; tiny_vec<float,3> V = hit->get_incoming_ray().get_direction(); tiny_vec<float,3> P = hit->get_incoming_ray().get_origin(); tiny_vec<float,3> Va = top-bottom; Va.normalize(); tiny_vec<float,3> dp = P - bottom; tiny_vec<float,3> Avec =V-dot(V,Va)*Va; tiny_vec<float,3> Cvec = dp - dot(dp,Va)*Va; float A = Avec.sqr_length(); float B = 2*dot(Avec,Cvec); float C = Cvec.sqr_length() - radius*radius; float ts[4]; int n=0; if(caps) { ts[n]=dot(Va,bottom-P)/dot(Va,V); tiny_vec<float,3> Q = P + ts[n] * V; if( (Q-bottom).sqr_length() < radius*radius) n++; ts[n]=dot(Va,top-P)/dot(Va,V); Q = P + ts[n] * V; if( (Q-top).sqr_length() < radius*radius) n++; } int nroots= solve_real_quadratic(A, B, C, &(ts[n])); if(finite) { if(nroots > 0) { tiny_vec<float,3> Q = P + ts[n] * V; if ( dot(Q-bottom,Va) > 0 && dot(Q-top,Va) < 0) n++; else ts[n] =ts[n+1]; if(nroots > 1) { tiny_vec<float,3> Q = P + ts[n] * V; if ( dot(Q-bottom,Va) > 0 && dot(Q-top,Va) < 0) n++; } } } bool ret = false; for(int i = 0; i < n;i++) { if(ts[i] > min_lambda && ts[i] < hit->get_lambda()) { hit->set_lambda( ts[i]); hit->set_object ( this); calc_normal(hit); ret = true; } } return ret; } bool cylinder::any_intersection(ray<float>& r,float min_lambda, float max_lambda) { // if(dont_hit == this) // return false; tiny_vec<float,3> V = r.get_direction(); tiny_vec<float,3> P = r.get_origin(); tiny_vec<float,3> Va = top-bottom; Va.normalize(); tiny_vec<float,3> dp = P - bottom; tiny_vec<float,3> Avec =V-dot(V,Va)*Va; tiny_vec<float,3> Cvec = dp - dot(dp,Va)*Va; float A = Avec.sqr_length(); float B = 2*dot(Avec,Cvec); float C = Cvec.sqr_length() - radius*radius; float ts[4]; int n=0; if(caps) { ts[n]=dot(Va,bottom-P)/dot(Va,V); tiny_vec<float,3> Q = P + ts[n] * V; if( (Q-bottom).sqr_length() < radius*radius) n++; ts[n]=dot(Va,top-P)/dot(Va,V); Q = P + ts[n] * V; if( (Q-top).sqr_length() < radius*radius) n++; } int nroots= solve_real_quadratic(A, B, C, &(ts[n])); if(finite) { if(nroots > 0) { tiny_vec<float,3> Q = P + ts[n] * V; if ( dot(Q-bottom,Va) > 0 && dot(Q-top,Va) < 0) n++; else ts[n] =ts[n+1]; if(nroots > 1) { tiny_vec<float,3> Q = P + ts[n] * V; if ( dot(Q-bottom,Va) > 0 && dot(Q-top,Va) < 0) n++; } } } for(int i = 0; i < n;i++) { if(ts[i] > min_lambda && ts[i] < max_lambda) return true; } return false; } void cylinder::set_finite(bool b) { finite = b; } bool cylinder::is_finite() { return finite; } void cylinder::set_caps(bool b) { caps = b; if(caps) finite=true; } bool cylinder::has_caps() { return caps; }
[ [ [ 1, 222 ] ] ]
cba4f50dc8a6c3369ab5a783af2f18804ac287c4
2f77d5232a073a28266f5a5aa614160acba05ce6
/01.DevelopLibrary/04.SmsCode/InfoCenterOfSmartPhone/RecieversStringParser.cpp
0ef123454da3ebfebe8d9c23c564023f4b09f242
[]
no_license
radtek/mobilelzz
87f2d0b53f7fd414e62c8b2d960e87ae359c81b4
402276f7c225dd0b0fae825013b29d0244114e7d
refs/heads/master
2020-12-24T21:21:30.860184
2011-03-26T02:19:47
2011-03-26T02:19:47
58,142,323
0
0
null
null
null
null
UTF-8
C++
false
false
9,078
cpp
#include "stdafx.h" #include "RecieversStringParser.h" #define UI_RecieversString_Separator (L';') #define UI_RecieversString_SeparatorStr (L";") CRecieversStringParser::CRecieversStringParser() { memset(m_wcsStringNeedParsed,0x0,sizeof(m_wcsStringNeedParsed)); m_lWSize = sizeof(m_wcsStringNeedParsed)/sizeof(m_wcsStringNeedParsed[0]); } CRecieversStringParser::~CRecieversStringParser() { } void CRecieversStringParser::UpdateStringByContactors() { wchar_t* pCur = m_wcsStringNeedParsed; long lWCount = wcslen(m_wcsStringNeedParsed); wchar_t* pEnd = &m_wcsStringNeedParsed[lWCount]; long lLoop = 0; wchar_t* pBegin = pCur; vector<long> vecExistIndex; while(pCur!=pEnd) { if ( UI_RecieversString_Separator == *pCur ){ wchar_t wcsContactor[50] = L""; long lCount = pCur-pBegin; if ( lCount > 0 ){ wcsncpy(wcsContactor, pBegin, lCount); long lMatchIndex = Invalid_4Byte; BOOL b = IsContactor(wcsContactor, lMatchIndex); if ( !b ){ b = IsNumbers(wcsContactor); if ( !b ){ long lCurPos = pCur-m_wcsStringNeedParsed+1; MoveChars(lCurPos, Move_Direction_Forward, (lCount+1)); long lWCount = wcslen(m_wcsStringNeedParsed); m_wcsStringNeedParsed[lWCount-(lCount+1)] = L'\0'; pEnd = &m_wcsStringNeedParsed[lWCount-(lCount+1)]; pCur = pBegin-1; }else{ pBegin = pCur+1; } }else{ pBegin = pCur+1; vecExistIndex.push_back(lMatchIndex); } }else{ pBegin = pCur+1; } } pCur++; } long lCount = g_ReciversList.GetItemCount(); for ( int j = 0; j < lCount; j++ ) { int i = 0; long lvecSize = vecExistIndex.size(); for ( i = 0; i < lvecSize; i++ ) { if ( j == vecExistIndex.at(i) ){ break; } } if ( i == lvecSize ){ F_wcscatn( m_wcsStringNeedParsed, g_ReciversList.GetItem(j)->StringTitle, m_lWSize ); F_wcscatn( m_wcsStringNeedParsed, UI_RecieversString_SeparatorStr, m_lWSize ); } } } void CRecieversStringParser::UpdateRecievers() { wchar_t* pCur = m_wcsStringNeedParsed; long lWCount = wcslen(m_wcsStringNeedParsed); long lLoop = 0; wchar_t* pBegin = pCur; while(lLoop<lWCount) { if ( UI_RecieversString_Separator == *pCur ){ wchar_t wcsContactor[50] = L""; long lCount = pCur-pBegin; if ( lCount > 0 ){ wcsncpy(wcsContactor, pBegin, lCount); BOOL b = IsNumbers(wcsContactor); if ( b ){ long lMatchIndex = Invalid_4Byte; b = IsContactor(wcsContactor, lMatchIndex); if ( !b ){ MyListItemData Temp; Temp.StringTitle = wcsContactor; Temp.StringDescription = wcsContactor; g_ReciversList.AppendItem(&Temp); } } } pBegin = pCur+1; } pCur++; lLoop++; } } void CRecieversStringParser::UpdateContactors() { wchar_t* pCur = m_wcsStringNeedParsed; long lWCount = wcslen(m_wcsStringNeedParsed); vector<long> vecExistIndex; long lLoop = 0; wchar_t* pBegin = pCur; while(lLoop<lWCount) { if ( UI_RecieversString_Separator == *pCur ){ wchar_t wcsContactor[50] = L""; long lCount = pCur-pBegin; if ( lCount > 0 ){ wcsncpy(wcsContactor, pBegin, lCount); long lMatchIndex = Invalid_4Byte; BOOL b = IsContactor(wcsContactor, lMatchIndex); if ( b ){ vecExistIndex.push_back(lMatchIndex); } } pBegin = pCur+1; } pCur++; lLoop++; } long lCount = g_ReciversList.GetItemCount(); for ( int j = 0; j < lCount; j++ ) { int i = 0; long lvecSize = vecExistIndex.size(); for ( i = 0; i < lvecSize; i++ ) { if ( j == vecExistIndex.at(i) ){ break; } } if ( i == lvecSize ){ g_ReciversList.DeleteItem(j); } } } void CRecieversStringParser::AddSeparator(long lCurcorPos) { if ( lCurcorPos > 0 ){ if ( UI_RecieversString_Separator == m_wcsStringNeedParsed[lCurcorPos-1] ){ MoveChars(lCurcorPos, Move_Direction_Backward, 1); m_wcsStringNeedParsed[lCurcorPos] = UI_RecieversString_Separator; } }else{ MoveChars(lCurcorPos, Move_Direction_Backward, 1); m_wcsStringNeedParsed[lCurcorPos] = UI_RecieversString_Separator; } } void CRecieversStringParser::GetContactorRangeByPos(long lCurcorPos, long& lBeginPos, long& lEndPos) { if (( L'\0' != m_wcsStringNeedParsed[0] ) && ( lCurcorPos <= (m_lWSize-1) )){ long lWCount = wcslen(m_wcsStringNeedParsed); if ( lCurcorPos <= (lWCount-1) ){ lBeginPos = FindBoundaryByPos(lCurcorPos, Move_Direction_Forward); lEndPos = FindBoundaryByPos(lCurcorPos, Move_Direction_Backward); } } } long CRecieversStringParser::DeleteContentByPos(long lCurcorPos) { long lRtV = lCurcorPos; if ( lCurcorPos > 0 ){ if ( UI_RecieversString_Separator == m_wcsStringNeedParsed[lCurcorPos-1] ){ long lBeginPos = Invalid_4Byte; long lEndPos = Invalid_4Byte; GetContactorRangeByPos((lCurcorPos-1), lBeginPos, lEndPos); MoveChars((lEndPos+1), Move_Direction_Forward, (lEndPos-lBeginPos)); long lLen = wcslen(m_wcsStringNeedParsed); m_wcsStringNeedParsed[lLen-(lEndPos-lBeginPos+1)+1] = L'\0'; m_wcsStringNeedParsed[lBeginPos] = UI_RecieversString_Separator; lRtV = lBeginPos+1; } } return lRtV; } wchar_t* CRecieversStringParser::GetWStringBuf(long& lWSize) { lWSize = m_lWSize; return m_wcsStringNeedParsed; } long CRecieversStringParser::FindBoundaryByPos(long lCurcorPos, Move_Direction enDirection) { long lRetVal = Invalid_4Byte; long lStepLength = 0; long lMaxStepCount = 0; if ( Move_Direction_Forward == enDirection ){ lStepLength = -1; lMaxStepCount = (lCurcorPos+1)/abs(lStepLength); lCurcorPos -= 1; }else{ lStepLength = 1; long lWCount = wcslen(m_wcsStringNeedParsed); lMaxStepCount = (lWCount - lCurcorPos)/lStepLength; } int i = 0; for ( i = 0; i < lMaxStepCount; i++ ) { if ( UI_RecieversString_Separator == m_wcsStringNeedParsed[lCurcorPos + i*lStepLength] ){ break; } } if ( i == lMaxStepCount ){ if (Move_Direction_Forward == enDirection){ lRetVal = 0; }else{ ASSERT(0); } }else{ if (Move_Direction_Forward == enDirection){ lRetVal = lCurcorPos + i*lStepLength+1; }else{ lRetVal = lCurcorPos + i*lStepLength; } } return lRetVal; } void CRecieversStringParser::MoveChars(long lCurcorPos, Move_Direction enDirection, long lStepLength) { if ( L'\0' != m_wcsStringNeedParsed[0] ){ long lWCount = wcslen(m_wcsStringNeedParsed); if ( lWCount > (lCurcorPos+1) ){ long lCurPos = 0; long lNextPos = 0; long lDir = 0; if ( Move_Direction_Forward == enDirection ){ lCurPos = lCurcorPos-lStepLength; lNextPos = lCurPos+lStepLength; lDir = 1; }else{ lCurPos = lWCount-1+lStepLength; lNextPos = lCurPos-lStepLength; lDir = -1; } if ( (lCurPos>=0)&&(lCurPos<m_lWSize) ){ for ( int i = 0; i < (lWCount-lCurcorPos); i++ ) { m_wcsStringNeedParsed[lCurPos] = m_wcsStringNeedParsed[lNextPos]; lCurPos+=lDir; lNextPos+=lDir; } } } } } BOOL CRecieversStringParser::IsNumbers(long lBeginPos, long lEndPos) { BOOL bRet = FALSE; if ( L'\0' != m_wcsStringNeedParsed[0] ){ long lWCount = wcslen(m_wcsStringNeedParsed); if (( lBeginPos >= 0 )&&(lBeginPos<lWCount)&& ( lEndPos >= 0 )&&(lEndPos<lWCount)){ int i = 0; for ( i = 0; i < (lEndPos-lBeginPos+1); i++ ) { if ( (L'0' > m_wcsStringNeedParsed[lBeginPos+i]) || (L'9' < m_wcsStringNeedParsed[lBeginPos+i]) ){ break; } } if ( i == (lEndPos-lBeginPos+1) ){ bRet = TRUE; } } } return bRet; } BOOL CRecieversStringParser::IsNumbers(wchar_t* pwcsWChars) { BOOL bRet = FALSE; int i = 0; long lCount = wcslen(pwcsWChars); for ( i = 0; i < lCount; i++ ) { if ( (L'0' > pwcsWChars[i]) || (L'9' < pwcsWChars[i]) ){ break; } } if ( i == lCount ){ bRet = TRUE; } return bRet; } BOOL CRecieversStringParser::IsContactor(long lBeginPos, long lEndPos) { BOOL bRet = FALSE; if ( L'\0' != m_wcsStringNeedParsed[0] ){ long lWCount = wcslen(m_wcsStringNeedParsed); if (( lBeginPos >= 0 )&&(lBeginPos<lWCount)&& ( lEndPos >= 0 )&&(lEndPos<lWCount)){ wchar_t wcsContactor[50] = L""; wcsncpy(wcsContactor, &m_wcsStringNeedParsed[lBeginPos], (lEndPos-lBeginPos)); long lCount = g_ReciversList.GetItemCount(); for ( int i = 0; i < lCount; i++ ) { if ( 0 == wcscmp(wcsContactor, g_ReciversList.GetItem(i)->StringTitle.C_Str()) ){ bRet = TRUE; } } } } return bRet; } BOOL CRecieversStringParser::IsContactor(wchar_t* pwcsContactor, long& lMatchIndex) { BOOL bRet = FALSE; lMatchIndex = Invalid_4Byte; long lCount = g_ReciversList.GetItemCount(); for ( int i = 0; i < lCount; i++ ) { if ( 0 == wcscmp(pwcsContactor, g_ReciversList.GetItem(i)->StringTitle.C_Str()) ){ lMatchIndex = i; bRet = TRUE; } } return bRet; }
[ "lidan8908589@8983de3c-2b35-11df-be6c-f52728ce0ce6" ]
[ [ [ 1, 345 ] ] ]
c30787f5812e9c6f5f5f9260c30ba5492e8395c7
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/techdemo2/engine/common/include/XmlResource.h
493e4a959e39e96aad97032eed924674e4389800
[ "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,326
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 __XmlResource_H__ #define __XmlResource_H__ #pragma warning (push) #pragma warning (disable : 4244) #include <xercesc/framework/MemBufInputSource.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/sax2/SAX2XMLReader.hpp> #pragma warning (pop) #include "CommonPrerequisites.h" #include <OgreResource.h> namespace rl { class _RlCommonExport XmlResource : public Ogre::Resource { public: XmlResource( Ogre::ResourceManager* creator, const Ogre::String& name, Ogre::ResourceHandle handle, const Ogre::String& group, bool isManual = false, Ogre::ManualResourceLoader* loader = NULL); virtual ~XmlResource(); void parseBy(XERCES_CPP_NAMESPACE::XercesDOMParser* parser); void parseBy(XERCES_CPP_NAMESPACE::SAX2XMLReader* parser); protected: size_t calculateSize() const; void loadImpl(); void unloadImpl(); private: XERCES_CPP_NAMESPACE::MemBufInputSource* mXmlBuffer; char* mCharBuffer; }; class _RlCommonExport XmlPtr : public Ogre::SharedPtr<XmlResource> { public: XmlPtr() : Ogre::SharedPtr<XmlResource>() {} explicit XmlPtr(XmlResource* rep) : Ogre::SharedPtr<XmlResource>(rep) {} XmlPtr(const XmlPtr& res) : Ogre::SharedPtr<XmlResource>(res) {} XmlPtr(const Ogre::ResourcePtr& res); XmlPtr& operator=(const Ogre::ResourcePtr& res); protected: void destroy(); }; } #endif
[ "tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 75 ] ] ]
c3862b47a966810779fc027670010d3aa4c72311
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Common/fusion/RandomNumberCache.h
9463e1a79a999d585d496b74111c4d720c1a6f54
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,004
h
#ifndef RANDOMNUMBERCACHE_H #define RANDOMNUMBERCACHE_H #include <STDIO.H> #include <STDLIB.H> #ifdef __cplusplus_cli #pragma managed(push,off) #endif #define RNC_CACHESIZE RAND_MAX+1 class RandomNumberCache { //A cache of RNC_CACHESIZE random numbers to be used for fast drawing. //NOTE: THIS CLASS IS NOT THREAD SAFE! DO NOT MAKE IT GLOBAL!!! private: //whether the cache has been initialized bool mIsInitialized; //the size of the cache int mCacheSize; //the number of valid values in the cache (0 - RNC_CACHESIZE) int mNumValues; //the cache of numbers double* mCache; public: RandomNumberCache(); ~RandomNumberCache(); bool IsInitialized() {return mIsInitialized;} int SizeOfCache() {return mCacheSize;} bool AddNumber(double iNewRandomNumber); void EmptyCache(); double RandomNumber(); void ReplaceRandomNumber(double iNewRandomNumber); }; #ifdef __cplusplus_cli #pragma managed(pop) #endif #endif //RANDOMNUMBERCACHE_H
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 47 ] ] ]
df85b7da2af81606c03bb93a5c61c6ad5dd188db
58ef4939342d5253f6fcb372c56513055d589eb8
/CloverDemo/source/control/src/ListBoxHighLightControl.cpp
0ed79d246cb2cd4eb0894ddf11afb82eb4274431
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,216
cpp
/* ============================================================================ Name : ListBoxHighLightControl.cpp Author : zengcity Version : 1.0 Copyright : Your copyright notice Description : CListBoxHighLightControl implementation ============================================================================ */ #include "ListBoxHighLightControl.h" CListBoxHighLightControl::CListBoxHighLightControl() { // No implementation required } CListBoxHighLightControl::~CListBoxHighLightControl() { } CListBoxHighLightControl* CListBoxHighLightControl::NewLC() { CListBoxHighLightControl* self = new (ELeave) CListBoxHighLightControl(); CleanupStack::PushL(self); self->ConstructL(); return self; } CListBoxHighLightControl* CListBoxHighLightControl::NewL() { CListBoxHighLightControl* self = CListBoxHighLightControl::NewLC(); CleanupStack::Pop(); // self; return self; } void CListBoxHighLightControl::ConstructL() { } void CListBoxHighLightControl::Draw(CBitmapContext& gc) const { gc.SetBrushStyle( CGraphicsContext::ESolidBrush ); if (iPainter) gc.SetBrushColor( iPainter->GetHightLightClock() ); gc.Clear(Rect()); }
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 49 ] ] ]
7c5c8eefc76e9c8fa56473bcb51fa1cd315a178f
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.2/bctestservicehandler/inc/bctestservicehandlerappUi.h
47bf3bf9cfe36f6367ee7351c752a2b775a5ead4
[]
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,466
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: Test BC for ServiceHandler control API. * */ #ifndef C_BCTESTSERVICEHANDLERAPPUI_H #define C_BCTESTSERVICEHANDLERAPPUI_H #include <aknviewappui.h> class CBCTestServiceHandlerView; class CBCTestUtil; class CAiwServiceHandler; /** * Application UI class * * @lib bctestutil.lib */ class CBCTestServiceHandlerAppUi : public CAknViewAppUi { public: // Constructors and destructor /** * ctor */ CBCTestServiceHandlerAppUi(); /** * symbian 2nd ctor */ void ConstructL(); /** * dtor */ virtual ~CBCTestServiceHandlerAppUi(); private: /** * From CEikAppUi */ void HandleCommandL( TInt aCommand ); private: // data /** * pointor to the view. * Owned */ CBCTestServiceHandlerView* iView; }; #endif // C_BCTESTSERVICEHANDLERAPPUI_H // End of File
[ "none@none" ]
[ [ [ 1, 70 ] ] ]
07cfd0b9ec2e8d07fd74379e64fe73e9de004b29
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/core/src/LightObject.cpp
98bdb7983c8bdefbf076bf74750d165fd8242faf
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,223
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 "LightObject.h" #include "Actor.h" #include "CoreSubsystem.h" #include "World.h" using namespace Ogre; namespace rl { LightObject::LightObject(const String& name, rl::LightObject::LightTypes type) { Light* light = CoreSubsystem::getSingleton().getWorld()-> getSceneManager()->createLight(name); light->setType(Ogre::Light::LightTypes(type) ); mMovableObject = light; } Light* LightObject::getLight() { return reinterpret_cast<Light*>(mMovableObject); } String LightObject::getObjectType() { return "LightObject"; } void LightObject::setAttenuation( Real range, Real constant, Real linear, Real quadric) { getLight()->setAttenuation( range, constant, linear, quadric ); } void LightObject::setDiffuseColour( Real red, Real green, Real blue) { getLight()->setDiffuseColour(red,green,blue); } void LightObject::setDirection( Real x, Real y, Real z) { getLight()->setDirection(x,y,z); } void LightObject::setSpecularColour( Real red, Real green, Real blue) { getLight()->setSpecularColour(red,green,blue); } void LightObject::setSpotlightRange( Real innerAngle, Real outerAngle, Real falloff ) { getLight()->setSpotlightRange(Angle(innerAngle), Angle(outerAngle), falloff ); } void LightObject::setCastShadows( bool cast ) { getLight()->setCastShadows( cast ); } }
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 74 ] ] ]
b8fc1a482dd8a54779cdd629e121b1b4f9177f3c
1e4daaa1f0846720f608094479aadb58759e1021
/p2p-simulation/coupled/peer/SessionManager.cpp
fa049700a1b2d09bb1640f7a28a6c05cfd22c442
[]
no_license
DDionne/SpiderWeb
d7d69091a08aaf6b2ae7f50ad7a8bd40406cc693
0d3e78a0a053e4c0e826cf9b9eae332930929fc0
refs/heads/master
2021-01-16T19:56:44.257854
2011-06-07T19:33:40
2011-06-07T19:33:40
1,860,449
0
0
null
null
null
null
UTF-8
C++
false
false
12,123
cpp
/******************************************************************* * * DESCRIPTION: Atomic Model SessionManager : simulate the user's session in the p2p network. * The user goes online, is active or passive until she goes offline. If active, the user outputs a random number of queries at a random time interval, then goes offline. * * * AUTHOR: Alan * * * DATE: November 2010 - May 2011 * *******************************************************************/ /** include files **/ #include <math.h> // fabs( ... ) #include <stdlib.h> #include "randlib.h" // Random numbers library #include "SessionManager.h" // base header #include "message.h" // InternalMessage .... #include "distri.h" // class Distribution #include "mainsimu.h" // class MainSimulator #include "strutil.h" // str2float( ... ) #include <sstream> #include <fstream> // i o streaming from files /******************************************************************* * Function Name: SessionManager * Description: constructor ********************************************************************/ SessionManager::SessionManager( const string &name ) : Atomic( name ) , queryhit( addInputPort( "queryhit" ) ) , query( addInputPort( "query" ) ) , online( addOutputPort( "online" ) ) , offline( addOutputPort( "offline" ) ) , publish( addOutputPort( "publish") ) , remove( addOutputPort( "remove") ) { //get the parameter that specifies the id of this peer string Id_str = MainSimulator::Instance().getParameter( description(), "whoAmI" ); whoAmI = int(floor(str2float(Id_str))); // clumsy way of turning a string into an integer //in this version we load the querylist from a file ------------------------------- string param = MainSimulator::Instance().getParameter( description(), "querylist" ); istringstream sis; sis.str(param); // open stream to string // read list of queries while(true) { int w; char coma; // find separator character sis >> w; savequerylist.insert(w); if(!sis.eof()) sis >> coma; //separating from next value (if there is one) else break; //otherwise we're done //if(PVERBOSE) cout<<"Peer"<<whoAmI<<" adding query : "<<w<<endl; } ///---------------------------------------------------- //list of published documents param = MainSimulator::Instance().getParameter( description(), "doclist" ); istringstream sis2; sis2.str(param); // open stream to string // read list of queries while(true) { int w; char coma; sis2 >> w; doclist.insert(w); if(!sis2.eof()) sis2 >> coma; //separating from next value (if there is one) else break; //otherwise we're done //if(PVERBOSE) cout<<"Peer"<<whoAmI<<" adding doc : "<<w<<endl; } try { /* parameters are : betweenquerydistribution * betweenquery[paramname1] * betweenquery[paramname(n)] * * beforequerydistribution * beforequery[param1] * * afterquerydistribution * * offlinetimedistribution * * inactivesessionlengthdistribution * * etc. */ timeBetweenQueryDist = Distribution::create( MainSimulator::Instance().getParameter( description(), "betweenquerydistribution" ) ); for ( register int i = 0 ; i < timeBetweenQueryDist->varCount() ; i++ ) { string parameter( MainSimulator::Instance().getParameter( description(), "betweenquery"+timeBetweenQueryDist->getVar(i) ) ) ; timeBetweenQueryDist->setVar( i, str2float( parameter ) ) ; } timeBeforeQueryDist = Distribution::create( MainSimulator::Instance().getParameter( description(), "beforequerydistribution" ) ); for ( register int i = 0 ; i < timeBeforeQueryDist->varCount() ; i++ ) { string parameter( MainSimulator::Instance().getParameter( description(), "beforequery"+timeBeforeQueryDist->getVar(i) ) ) ; timeBeforeQueryDist->setVar( i, str2float( parameter ) ) ; } timeAfterQueryDist = Distribution::create( MainSimulator::Instance().getParameter( description(), "afterquerydistribution" ) ); for ( register int i = 0 ; i < timeAfterQueryDist->varCount() ; i++ ) { string parameter( MainSimulator::Instance().getParameter( description(), "afterquery"+timeAfterQueryDist->getVar(i) ) ) ; timeAfterQueryDist->setVar( i, str2float( parameter ) ) ; } offlineTimeDist = Distribution::create( MainSimulator::Instance().getParameter( description(), "offlinetimedistribution" ) ); for ( register int i = 0 ; i < offlineTimeDist->varCount() ; i++ ) { string parameter( MainSimulator::Instance().getParameter( description(), "offlinetime"+offlineTimeDist->getVar(i) ) ) ; offlineTimeDist->setVar( i, str2float( parameter ) ) ; } inactiveSessionLength = Distribution::create( MainSimulator::Instance().getParameter( description(), "inactivesessionlengthdistribution" )) ; for ( register int i = 0 ; i < inactiveSessionLength->varCount() ; i++ ) { string parameter( MainSimulator::Instance().getParameter( description(), "inactivesessionlength"+inactiveSessionLength->getVar(i) ) ) ; inactiveSessionLength->setVar( i, str2float( parameter ) ) ; } unif_01 = Distribution::create("uniform"); unif_01-> setVar(0,0); //min if first parameter, set to 0 unif_01-> setVar(1,1); //max is 2nd parameter, set to 1 activityProb = str2float(MainSimulator::Instance().getParameter( description(), "probabilityofactivity" ) ); //MASSERT( dist ); } catch( InvalidDistribution &e ) { e.addText( "The model " + description() + " has distribution problems!" ) ; e.print(cerr); MTHROW( e ) ; } catch( MException &e ) { MTHROW( e ) ; } } Model &SessionManager::initFunction() { //stay in the active state for some random time, before going online. Use offline distribution float t = max(static_cast<float>( distribution(OFFLINETIME).get() ), 0.0f); //low-bound distribution by zero mystate = OFFLINETIME; officiallyonline=false; //start offline if(PVERBOSE) cout<<"Peer"<<whoAmI<<" about to start with waiting time: "<<t<<endl;; Time toto = makeTimefromSeconds( t ); if(PVERBOSE) cout<<"formatted time: "<<toto<<endl;; holdIn(active, toto); //input of constructor is in seconds return *this; } /******************************************************************* * Function Name: externalFunction * Description: only queryhits come in here. * At this point we don't change the model state for them, we just trace them ********************************************************************/ Model &SessionManager::externalFunction( const ExternalMessage &msg ) { if (this->state() != passive && mystate != OFFLINETIME) //if I'm not offline I'll do something about the queryhit { if(PVERBOSE) cout<<msg.time()<<"Peer "<<whoAmI<<" got queryhit:"<<msg.value()<<endl; //publish the document if I didn't have it int thedoc = getPeerId(msg.value()); if(alldocs.find(thedoc)==alldocs.end()) { // we haven't got this one yet AND we're not about to go offline ! doclist.insert(thedoc); // list it to be published } holdIn(active, nextChange());//just go to active state for as long as was remaining before the next scheduled internal change } return *this ; } /******************************************************************* * Function Name: internalFunction ********************************************************************/ Model &SessionManager::internalFunction( const InternalMessage & ) { float t; switch(mystate){ case BEFOREQUERY : mystate = INTERQUERY; t = max(static_cast<float>( distribution(INTERQUERY).get() ), 0.0f); holdIn(active, makeTimefromSeconds(t)); break; case INTERQUERY : if (!querylist.empty()) { //just wait a random time for the next query. t = max(static_cast<float>( distribution(INTERQUERY).get() ), 0.0f); holdIn(active, makeTimefromSeconds(t)); } else { //linger after query activity mystate = AFTERQUERY; t = max(static_cast<float>( distribution(AFTERQUERY).get() ), 0.0f); holdIn(active, makeTimefromSeconds(t)); } break; case AFTERQUERY : //go offline for a while, at the end of either active or inactive session case INACTIVETIME : mystate=OFFLINETIME; t = max(static_cast<float>( distribution(OFFLINETIME).get() ), 0.0f); holdIn(active, makeTimefromSeconds(t)); break; case OFFLINETIME : //we're going online again if(!doclist.empty()){ //publish all docs, if necessary holdIn(active, Time(0,0,1,0 )); //wait 1s between publishing docs } else { //go online float choice = unif_01->get(); if(PVERBOSE)cout<<"active/inactive choice:"<<choice<<" vs. prob="<<activityProb<<endl; if ( choice<activityProb){ // choose between active or inactive session mystate = BEFOREQUERY; //active session //reload queries set<int>::iterator it; for ( it=savequerylist.begin() ; it != savequerylist.end(); it++ ) querylist.insert(*it); t = max(static_cast<float>( distribution(BEFOREQUERY).get() ), 0.0f); holdIn(active, makeTimefromSeconds(t)); } else{ mystate =INACTIVETIME; //inactivesession t = max(static_cast<float>( distribution(INACTIVETIME).get() ), 0.0f); holdIn(active, makeTimefromSeconds(t)); } } break; default : cout<<"error : undefined state"; } return *this; } /******************************************************************* * Function Name: outputFunction ********************************************************************/ Model &SessionManager::outputFunction( const InternalMessage &msg ) { switch(mystate){ case BEFOREQUERY : case INTERQUERY : if (!querylist.empty()) //we're querying { set<int>::iterator it; it = querylist.begin(); if(PVERBOSE) cout<<msg.time()<<" : Peer "<<whoAmI<< " queries:"<<*it<<endl; int tosend = buildMessage(*it, whoAmI); // encode query, who am I sendOutput( msg.time(), query , tosend ); // we output the value in the query set on the query output port querylist.erase(it); // remove the query from list. } if(!doclist.empty()){ // a document to publish following a queryhit set<int>::iterator it; it = doclist.begin(); int tosend = buildMessage(*it, whoAmI); // encode query, who am I sendOutput( msg.time(), publish , tosend ); // we output the value in the query set on the query output port alldocs.insert(*it); // save it in the collection of already published documents doclist.erase(it); } //the list shouldn't be empty, unless there were no queries to begin with break; case AFTERQUERY : //go offline for a while, at the end of either active or inactive session case INACTIVETIME : officiallyonline=false; //going offline next sendOutput( msg.time(), offline, whoAmI ); break; case OFFLINETIME : //we're going online again if(!officiallyonline) {//if we haven't gone online yet sendOutput( msg.time(), online, whoAmI ); officiallyonline=true; } else if (!doclist.empty()) //we're publishing stuff { set<int>::iterator it; it = doclist.begin(); int tosend = buildMessage(*it, whoAmI); // encode query, who am I sendOutput( msg.time(), publish , tosend ); // we output the value in the query set on the query output port alldocs.insert(*it); // save it in the collection of already published documents doclist.erase(it); } // if (doclist.empty()) //once all docs are published we can go online; check again in case we just output the last publish // sendOutput( msg.time(), online, whoAmI ); break; default : cout<<"error : undefined state"; } return *this; } SessionManager::~SessionManager() { //delete all statistical distribution objects delete timeBetweenQueryDist ; delete timeBeforeQueryDist ; delete timeAfterQueryDist ; delete offlineTimeDist ; delete inactiveSessionLength ; delete unif_01; }
[ [ [ 1, 350 ] ] ]
74bf2d70bb1589b7abbaf795d1eb982fe64d0a06
a865bcbb6dce0236d5e581987968d8c78fd57231
/Quall/Quall/Input.cpp
8ee6edf6de71e19311e389bc4451db57d2d15efd
[]
no_license
noansknv/quall
876d6148632008db6f58aae4a6f0c974ff05649e
c204054a5d9ac348934a268aeda58c89b07feecf
refs/heads/master
2016-09-06T01:53:35.644454
2010-06-28T19:07:43
2010-06-28T19:07:43
32,244,694
0
0
null
null
null
null
UTF-8
C++
false
false
9,496
cpp
#include "input.hpp" InputHandler::InputHandler(WorldManagerPtr worldManager, Simulation *sim, unsigned long hWnd) : worldMgr(worldManager) { OIS::ParamList pl; pl.insert(OIS::ParamList::value_type("WINDOW", Ogre::StringConverter::toString(hWnd))); mHWnd = hWnd; mOis = OIS::InputManager::createInputSystem(pl); mMouse = static_cast<OIS::Mouse*>(mOis->createInputObject(OIS::OISMouse, true)); mKeyboard = static_cast<OIS::Keyboard*>(mOis->createInputObject(OIS::OISKeyboard, true)); mMouse->setEventCallback(this); mKeyboard->setEventCallback(this); mSimulation = sim; } InputHandler::~InputHandler() { if (mMouse) delete mMouse; if (mKeyboard) delete mKeyboard; OIS::InputManager::destroyInputSystem(mOis); } void InputHandler::capture() { mMouse->capture(); mKeyboard->capture(); } void InputHandler::setWindowExtents(int width, int height) { //Set Mouse Region.. if window resizes, we should alter this to reflect as well const OIS::MouseState &mouseState = mMouse->getMouseState(); mouseState.width = width; mouseState.height = height; } class Euler { public: // Constructor which takes yaw, pitch and roll values. Euler(Ogre::Radian y = Ogre::Radian(0.0f), Ogre::Radian p = Ogre::Radian(0.0f), Ogre::Radian r = Ogre::Radian(0.0f)):m_yaw(y),m_pitch(p),m_roll(r),m_changed(true) { } // Get the Yaw angle. inline Ogre::Radian getYaw() { return m_yaw; } // Get the Pitch angle. inline Ogre::Radian getPitch() { return m_pitch; } // Get the Roll angle. inline Ogre::Radian getRoll() { return m_roll; } // Apply a relative yaw. (Adds angle to current yaw) // Angles wrap around within the range 0 to 2*PI radians (0 to 360 degrees) inline Euler &yaw(Ogre::Radian y) { m_yaw += y; if(m_yaw.valueRadians() < 0.0f) { m_yaw = fmod(m_yaw.valueRadians(), Ogre::Math::PI * 2.0f) + Ogre::Math::PI * 2.0f; } else if(m_yaw.valueRadians() > Ogre::Math::PI) { m_yaw = fmod(m_yaw.valueRadians(), Ogre::Math::PI * 2.0f); } m_changed = true; return *this; } // Apply a relative pitch. (Adds angle to current pitch) inline Euler &pitch(Ogre::Radian p) { m_pitch += p; m_changed = true; return *this; } // Apply a relative roll. (Adds angle to current roll) inline Euler &roll(Ogre::Radian r) { m_roll += r; m_changed = true; return *this; } // Set the yaw. inline Euler &setYaw(Ogre::Radian y) { m_yaw = y; m_changed = true; return *this; } // Set the pitch. inline Euler &setPitch(Ogre::Radian p) { m_pitch = p; m_changed = true; return *this; } // Set the roll. inline Euler &setRoll(Ogre::Radian r) { m_roll = r; m_changed = true; return *this; } // Get a vector pointing forwards. inline Ogre::Vector3 getForward() { return toQuaternion() * Ogre::Vector3::NEGATIVE_UNIT_Z; } // Get a vector pointing to the right. inline Ogre::Vector3 getRight() { return toQuaternion() * Ogre::Vector3::UNIT_X; } // Get a vector pointing up. inline Ogre::Vector3 getUp() { return toQuaternion() * Ogre::Vector3::UNIT_Y; } // Calculate the quaternion of a euler object. // The result is cached, it is only recalculated when the component euler angles are changed. inline Ogre::Quaternion toQuaternion() { if(m_changed) { m_cachedQuaternion = Ogre::Quaternion(m_yaw, Ogre::Vector3::NEGATIVE_UNIT_Y) * Ogre::Quaternion(m_pitch, Ogre::Vector3::UNIT_X) * Ogre::Quaternion(m_roll, Ogre::Vector3::NEGATIVE_UNIT_Z); m_changed = false; } return m_cachedQuaternion; } // Casting operator. This allows any ogre function that wants a Quaternion to accept a Euler instead. inline operator Ogre::Quaternion() { return toQuaternion(); } // Set the yaw and pitch to face in the given direction. // The direction doesn't need to be normalised. // Roll is unaffected. Euler &setDirection(const Ogre::Vector3 &v) { Ogre::Vector3 d(v.normalisedCopy()); m_pitch = asin(d.y); m_yaw = atan2(d.z, d.x)+Ogre::Math::PI/2.0; m_changed = true; return *this; } // Get the angular difference between the current yaw and the specified yaw. // Only yaw is considered, pitch and roll are ignored. inline Ogre::Radian getYawToDirection(const Ogre::Radian &a) { Ogre::Real angle = (a - m_yaw).valueRadians(); if(angle>Ogre::Math::PI) angle = -Ogre::Math::PI*2.0f + angle; else if(angle<-Ogre::Math::PI) angle = Ogre::Math::PI*2.0f + angle; return Ogre::Radian(angle); } // Get the angular difference between the current yaw and the specified direction vector. // Only yaw is considered, pitch and roll are ignored. inline Ogre::Radian getYawToDirection(const Ogre::Vector3 &v) { return getYawToDirection(Ogre::Radian(atan2(v.z, v.x) + Ogre::Math::PI/2.0f)); } // Get the angular difference between the current yaw and the specified euler object. // Only yaw is considered, pitch and roll are ignored. inline Ogre::Radian getYawToDirection(const Euler &e) { return getYawToDirection(e.m_yaw); } // Change the yaw to face in the direction of the vector. // Only yaw is changed, pitch and roll are ignored. inline Euler &yawToDirection(const Ogre::Vector3 &v) { m_yaw = getYawToDirection(v); m_changed = true; return *this; } // Change the yaw to face in the direction of the euler object. // Only yaw is changed, pitch and roll are ignored. inline Euler &yawToDirection(const Euler &e) { m_yaw = getYawToDirection(e); m_changed = true; return *this; } // stream operator, for printing the euler component angles to a stream inline friend std::ostream &operator<<(std::ostream &o, const Euler &e) { o << "<Y:" << e.m_yaw << ", P:" << e.m_pitch << ", R:" << e.m_roll << ">"; return o; } protected: Ogre::Radian m_yaw; // Rotation around the Y axis. Ogre::Radian m_pitch; // Rotation around the X axis. Ogre::Radian m_roll; // Rotation around the Z axis. Ogre::Quaternion m_cachedQuaternion; // Cached quaternion equivalent of this euler object. bool m_changed; // Is the cached quaternion out of date? }; // MouseListener bool InputHandler::mouseMoved(const OIS::MouseEvent &evt) { Ogre::Real mRotate = 0.13; worldMgr->getCamera()->getParentSceneNode()->getParentSceneNode()->yaw(Ogre::Degree(-mRotate * evt.state.X.rel), Ogre::Node::TS_WORLD); Ogre::Real yCam = worldMgr->getCamera()->getParentSceneNode()->_getDerivedPosition().y; Ogre::Real yMain = worldMgr->getCamera()->getParentSceneNode()->getParentSceneNode()->_getDerivedPosition().y; Ogre::Real dist = worldMgr->getCamera()->getParentSceneNode()->_getDerivedPosition().distance(worldMgr->getCamera()->getParentSceneNode()->getParentSceneNode()->_getDerivedPosition()); Ogre::Radian originalKat = Ogre::Math::ASin((yCam - yMain) / dist); Ogre::Radian newKat = originalKat + Ogre::Degree(mRotate * evt.state.Y.rel); if (newKat.valueDegrees() > 0 && newKat.valueDegrees() < 70) worldMgr->getCamera()->getParentSceneNode()->getParentSceneNode()->pitch(Ogre::Degree(-mRotate * evt.state.Y.rel), Ogre::Node::TS_LOCAL); return true; } bool InputHandler::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID btn) { return true; } bool InputHandler::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID btn) { return true; } // KeyListener bool InputHandler::keyPressed(const OIS::KeyEvent &evt) { // Poruszanie sie kuleczka. switch (evt.key) { case OIS::KC_W: //if (mSimulation->getCurrentState() == SIMULATION) worldMgr->setDirectionZ(-1); break; case OIS::KC_S: //if (mSimulation->getCurrentState() == SIMULATION) worldMgr->setDirectionZ(1); break; case OIS::KC_A: //if (mSimulation->getCurrentState() == SIMULATION) worldMgr->setDirectionX(-1); break; case OIS::KC_D: //if (mSimulation->getCurrentState() == SIMULATION) worldMgr->setDirectionX(1); break; case OIS::KC_SPACE: //jump worldMgr->jump(); break; default: break; } return true; } bool InputHandler::keyReleased(const OIS::KeyEvent &evt) { switch (evt.key) { case OIS::KC_ESCAPE: mSimulation->requestStateChange(SHUTDOWN); break; case OIS::KC_W: case OIS::KC_S: //if (mSimulation->getCurrentState() == SIMULATION) worldMgr->setDirectionZ(0); break; case OIS::KC_A: case OIS::KC_D: //if (mSimulation->getCurrentState() == SIMULATION) worldMgr->setDirectionX(0); break; default: break; } return true; }
[ "[email protected]", "pkozlowski320@8a10c9d2-0e52-11df-8d37-15e3504968c6", "mazgul@8a10c9d2-0e52-11df-8d37-15e3504968c6" ]
[ [ [ 1, 41 ], [ 232, 235 ], [ 247, 282 ], [ 287, 314 ] ], [ [ 42, 231 ], [ 236, 246 ] ], [ [ 283, 286 ] ] ]
9a52efa65ab8f563fd3287158ee1a96eee14f4d3
68bfdfc18f1345d1ff394b8115681110644d5794
/Examples/Example01/ModelTexture.h
0460ebdc0b320bff8de67123e1ba3dea48c1666b
[]
no_license
y-gupta/glwar3
43afa1efe475d937ce0439464b165c745e1ec4b1
bea5135bd13f9791b276b66490db76d866696f9a
refs/heads/master
2021-05-28T12:20:41.532727
2010-12-09T07:52:12
2010-12-09T07:52:12
32,911,819
1
0
null
null
null
null
UTF-8
C++
false
false
1,028
h
#pragma once //+----------------------------------------------------------------------------- //| Included files //+----------------------------------------------------------------------------- #include "ModelBase.h" //+----------------------------------------------------------------------------- //| Model texture data structure //+----------------------------------------------------------------------------- struct MODEL_TEXTURE_DATA { MODEL_TEXTURE_DATA() { } INT ReplaceableId; BOOL WarpWidth; BOOL WarpHeight; std::string FileName; INT InternalTextureId; }; //+----------------------------------------------------------------------------- //| Model texture class //+----------------------------------------------------------------------------- class MODEL_TEXTURE { public: CONSTRUCTOR MODEL_TEXTURE(); DESTRUCTOR ~MODEL_TEXTURE(); VOID Clear(); INT GetSize(); MODEL_TEXTURE_DATA& Data(); protected: MODEL_TEXTURE_DATA TextureData; public: };
[ "sihan6677@deb3bc48-0ee2-faf5-68d7-13371a682d83" ]
[ [ [ 1, 50 ] ] ]
71e915c0ad36d491833e63e80972a2a7e7908f02
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/WheelGobal/include/ThirdParty/Ofusion/OgreOSMScene.h
6458500bf691db0fa212b9611b3dd18e22391372
[]
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
4,418
h
/********************************************************************** *< oFusion Scene Loader Pro (see License.txt) FILE: OgreOSMScene.h DESCRIPTION: OE_XMLScene reader (oe_scene) include header IMPLEMENTED BY: Andres Carrera HISTORY: Original implementation by Lasse Tassing (Channex) 2005 ITE ApS, Lasse Tassing *> Copyright (c) 2007, All Rights Reserved. **********************************************************************/ #ifndef _OGREOSMSCENE_H_ #define _OGREOSMSCENE_H_ #include <boost/property_tree/detail/rapidxml.hpp> #include "WheelGobalConfig.h" #include <Ogre/Ogre.h> #include "IOSMSceneCallbacks.h" #include "OSMAnimSerializer.h" #define OSM_RENDERTEXTURE_GROUP "OSM_RENDERTEXTURE_GROUP_" //class boost::shared_ptr<rapidxml::xml_document<> > : public Ogre::SharedPtr<rapidxml::xml_document<>> { //public: // boost::shared_ptr<rapidxml::xml_document<> >() : Ogre::SharedPtr<rapidxml::xml_document<>>() {} // explicit boost::shared_ptr<rapidxml::xml_document<> >(rapidxml::xml_document<>* rep) : Ogre::SharedPtr<rapidxml::xml_document<>>(rep) {} // //}; inline const char * GetAttrString(rapidxml::xml_attribute<> * attr) { if(attr) return attr->value(); return NULL; } typedef struct TAG_SCENE_HEADER_PROPS { TAG_SCENE_HEADER_PROPS() : version(0), unitsPerMasterRef(1) {} float version; float unitsPerMasterRef; Ogre::String masterScaleRef; Ogre::String unitType; } OSceneHeader; class _OrzWheelGobalExport OSMScene { public: typedef std::vector<Ogre::Camera*> CameraList; typedef std::vector<Ogre::Light*> LightList; typedef std::vector<Ogre::Entity*> EntityList; OSMScene(Ogre::SceneManager* pSceneMgr = 0, Ogre::RenderWindow* win = 0); ~OSMScene(void); // Initialise bool initialise(const char* pszFilename, OSMSceneCallbacks* pCallbacks = NULL); // Declare all resources used in the scene void declareResources(void); // Create scene, optionally attaching it to a parent node bool createScene(Ogre::SceneNode* pParent = NULL); // Get list of cameras in this scene CameraList& getCameraList(void); // Get list of lights in this scene LightList& getLightList(void); // Get list of lights in this scene EntityList& getEntityList(void); // Get created scene manager Ogre::SceneManager* getSceneManager(void) { return mSceneMgr; } const OSceneHeader& getSceneHeader(void) { return mSceneHeader; } protected: // Create node from information Ogre::SceneNode* createNode(rapidxml::xml_node<> * pElem, Ogre::SceneNode* pSceneRoot); // Create SceneManager Ogre::SceneNode* initSceneManager(rapidxml::xml_node<> * sceneProp, bool& bHandled); //Ogre::SceneNode* createSceneManager(rapidxml::xml_node<> * sceneProp, bool& bHandled); // Set scene properties void setSceneProperties(rapidxml::xml_node<> * sceneProp); // Creation helpers void createEntities(rapidxml::xml_node<> * pEntityNode, Ogre::SceneNode* pSceneRoot); void createLights(rapidxml::xml_node<> * pLightNode, Ogre::SceneNode* pSceneRoot); void createCameras(rapidxml::xml_node<> * pCameraNode, Ogre::SceneNode* pSceneRoot); void createStaticGeometry(rapidxml::xml_node<> * pStaticGeom); void createHelpers(rapidxml::xml_node<> * pLightNode, Ogre::SceneNode* pSceneRoot); void createShapes(rapidxml::xml_node<> * pHelperNode); void createRenderTexture(rapidxml::xml_node<> * pRenderTexNode); typedef std::set<unsigned int> SkeletonHandles; void loadAnimations(rapidxml::xml_node<> * animationsNode, SkeletonHandles& handles); void loadMaterialAnimations(rapidxml::xml_node<> * animationsNode); void setRenderTextureNodes(Ogre::RenderTexture* rTex, const EntityList* showNodes, const EntityList* hideNodes); // Created objects CameraList mCameras; LightList mLights; EntityList mEntities; Ogre::SceneNode* mSceneRoot; Ogre::String mSceneName, mFileExtension; // Callback interface OSMSceneCallbacks* mCallbacks; // Scene manager Ogre::SceneManager* mSceneMgr; Ogre::RenderWindow* mWindow; // Current Scene header properties OSceneHeader mSceneHeader; // Incremented count for next node name extension static unsigned long mNextGeneratedNameExt; // Scene XML document boost::shared_ptr<rapidxml::xml_document<> > mXMLDoc; std::string _data; }; #endif // _OGREOSMSCENE_H_
[ [ [ 1, 146 ] ] ]
16e719e261809b67853a1bdf281877e6b8be9893
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-10-27/gerbview/block.cpp
cd1152528365bcee052af4dc093367ec91efa51f
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
11,867
cpp
/*****************************************************************/ /* Operations sur Blocks : deplacement, rotation, effacement ... */ /*****************************************************************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "gerbview.h" #include "trigo.h" #include "protos.h" #define BLOCK_COLOR BROWN /* Routines Locales */ static void DrawMovingBlockOutlines(WinEDA_DrawPanel * panel, wxDC * DC, bool erase); static TRACK * IsSegmentInBox(DrawBlockStruct & blocklocate, TRACK * PtSegm ); /* Variables locales :*/ /*************************************************/ int WinEDA_GerberFrame::ReturnBlockCommand(int key) /*************************************************/ /* Return the block command (BLOCK_MOVE, BLOCK_COPY...) corresponding to the key (ALT, SHIFT ALT ..) */ { int cmd = 0; switch ( key ) { default: cmd = key & 0x255; break; case 0: cmd = BLOCK_MOVE; break; case GR_KB_SHIFT: break; case GR_KB_CTRL : break; case GR_KB_SHIFTCTRL : cmd = BLOCK_DELETE; break; case GR_KB_ALT : cmd = BLOCK_COPY; break; case MOUSE_MIDDLE: cmd = BLOCK_ZOOM; break; } return cmd ; } /*****************************************************/ void WinEDA_GerberFrame::HandleBlockPlace(wxDC * DC) /*****************************************************/ /* Routine to handle the BLOCK PLACE commande */ { bool err = FALSE; if(GetScreen()->ManageCurseur == NULL) { err = TRUE; DisplayError(this, "Error in HandleBlockPLace : ManageCurseur = NULL" ); } GetScreen()->BlockLocate.m_State = STATE_BLOCK_STOP; switch(GetScreen()->BlockLocate.m_Command ) { case BLOCK_IDLE: err = TRUE; break; case BLOCK_DRAG: /* Drag */ case BLOCK_MOVE: /* Move */ case BLOCK_PRESELECT_MOVE: /* Move with preselection list*/ if ( GetScreen()->ManageCurseur ) GetScreen()->ManageCurseur(DrawPanel, DC, FALSE); Block_Move(DC); GetScreen()->BlockLocate.m_BlockDrawStruct = NULL; break; case BLOCK_COPY: /* Copy */ if ( GetScreen()->ManageCurseur ) GetScreen()->ManageCurseur(DrawPanel, DC, FALSE); Block_Duplicate(DC); GetScreen()->BlockLocate.m_BlockDrawStruct = NULL; break; case BLOCK_PASTE: break; case BLOCK_ZOOM: // Handle by HandleBlockEnd() case BLOCK_ROTATE: case BLOCK_INVERT: case BLOCK_DELETE: case BLOCK_SAVE: case BLOCK_ABORT: case BLOCK_SELECT_ITEMS_ONLY: break; } GetScreen()->SetModify(); GetScreen()->ManageCurseur = NULL; GetScreen()->ForceCloseManageCurseur = NULL; GetScreen()->BlockLocate.m_Flags = 0; GetScreen()->BlockLocate.m_State = STATE_NO_BLOCK; GetScreen()->BlockLocate.m_Command = BLOCK_IDLE; if ( GetScreen()->BlockLocate.m_BlockDrawStruct ) { DisplayError(this, "Error in HandleBlockPLace DrawStruct != NULL" ); GetScreen()->BlockLocate.m_BlockDrawStruct = NULL; } DisplayToolMsg(""); } /**********************************************/ int WinEDA_GerberFrame::HandleBlockEnd(wxDC * DC) /**********************************************/ /* Routine de gestion de la commande BLOCK END returne : 0 si aucun compos ant selectionne 1 sinon -1 si commande terminée et composants trouvés (block delete, block save) */ { int endcommande = TRUE; bool zoom_command = FALSE; if(GetScreen()->ManageCurseur ) switch( GetScreen()->BlockLocate.m_Command ) { case BLOCK_IDLE: DisplayError(this, "Error in HandleBlockPLace"); break; case BLOCK_DRAG: /* Drag (not used, for future enhancements)*/ case BLOCK_MOVE: /* Move */ case BLOCK_COPY: /* Copy */ case BLOCK_PRESELECT_MOVE: /* Move with preselection list*/ GetScreen()->BlockLocate.m_State = STATE_BLOCK_MOVE; endcommande = FALSE; GetScreen()->ManageCurseur(DrawPanel, DC, FALSE); GetScreen()->ManageCurseur = DrawMovingBlockOutlines; GetScreen()->ManageCurseur(DrawPanel, DC, FALSE); break; case BLOCK_DELETE: /* Delete */ GetScreen()->BlockLocate.m_State = STATE_BLOCK_STOP; GetScreen()->ManageCurseur(DrawPanel, DC, FALSE); Block_Delete(DC); break; case BLOCK_ROTATE: /* Unused */ break; case BLOCK_INVERT: /* Fip */ break; case BLOCK_SAVE: /* Save (not used)*/ break; case BLOCK_PASTE: break; case BLOCK_ZOOM: /* Window Zoom */ zoom_command = TRUE; break; case BLOCK_ABORT: case BLOCK_SELECT_ITEMS_ONLY: break; } if ( endcommande == TRUE ) { GetScreen()->BlockLocate.m_Flags = 0; GetScreen()->BlockLocate.m_State = STATE_NO_BLOCK; GetScreen()->BlockLocate.m_Command = BLOCK_IDLE; GetScreen()->BlockLocate.m_BlockDrawStruct = NULL; GetScreen()->ManageCurseur = NULL; GetScreen()->ForceCloseManageCurseur = NULL; DisplayToolMsg(""); } if ( zoom_command ) Window_Zoom( GetScreen()->BlockLocate ); return(endcommande); } /**************************************************************************/ static void DrawMovingBlockOutlines(WinEDA_DrawPanel * panel, wxDC * DC, bool erase) /**************************************************************************/ /* Retrace le contour du block de repositionnement des structures a déplacer */ { int Color; BASE_SCREEN * screen = panel->GetScreen(); Color = YELLOW; GRSetDrawMode(DC, XOR_MODE); /* Effacement ancien cadre */ if( erase ) { screen->BlockLocate.Draw(panel, DC); if ( screen->BlockLocate.m_MoveVector.x || screen->BlockLocate.m_MoveVector.y ) { screen->BlockLocate.Offset(screen->BlockLocate.m_MoveVector); screen->BlockLocate.Draw(panel, DC); screen->BlockLocate.Offset(-screen->BlockLocate.m_MoveVector.x, -screen->BlockLocate.m_MoveVector.y); } } if ( panel->m_Parent->GetScreen()->BlockLocate.m_State != STATE_BLOCK_STOP ) { screen->BlockLocate.m_MoveVector.x = screen->m_Curseur.x - screen->BlockLocate.GetRight(); screen->BlockLocate.m_MoveVector.y = screen->m_Curseur.y - screen->BlockLocate.GetBottom(); } screen->BlockLocate.Draw(panel, DC); if ( screen->BlockLocate.m_MoveVector.x || screen->BlockLocate.m_MoveVector.y ) { screen->BlockLocate.Offset(screen->BlockLocate.m_MoveVector); screen->BlockLocate.Draw(panel, DC); screen->BlockLocate.Offset(-screen->BlockLocate.m_MoveVector.x, -screen->BlockLocate.m_MoveVector.y); } } /************************************************/ void WinEDA_BasePcbFrame::Block_Delete(wxDC *DC) /************************************************/ /* routine d'effacement du block deja selectionne */ { if ( !IsOK(this, _("Ok to delete block ?") ) ) return; GetScreen()->SetModify(); GetScreen()->BlockLocate.Normalize(); GetScreen()->m_CurrentItem = NULL; /* Effacement des Pistes */ TRACK * pt_segm, * NextS; for ( pt_segm = m_Pcb->m_Track; pt_segm != NULL; pt_segm = NextS) { NextS = pt_segm->Next(); if( IsSegmentInBox(GetScreen()->BlockLocate, pt_segm ) ) { /* la piste est ici bonne a etre efface */ pt_segm->Draw(DrawPanel, DC, GR_XOR) ; DeleteStructure(pt_segm); } } /* Effacement des Zones */ for ( pt_segm = m_Pcb->m_Zone; pt_segm != NULL; pt_segm = NextS) { NextS = pt_segm->Next(); if( IsSegmentInBox(GetScreen()->BlockLocate, pt_segm ) ) {/* la piste est ici bonne a etre efface */ pt_segm->Draw(DrawPanel, DC, GR_XOR) ; DeleteStructure(pt_segm); } } /* Rafraichissement de l'ecran : */ RedrawActiveWindow(DC, TRUE); } /************************************************/ void WinEDA_BasePcbFrame::Block_Move(wxDC * DC) /************************************************/ /* routine de deplacement des elements du block deja selectionne */ { int deltaX, deltaY; wxPoint oldpos; oldpos = GetScreen()->m_Curseur; GetScreen()->ManageCurseur = NULL; GetScreen()->m_Curseur = oldpos; DrawPanel->MouseToCursorSchema(); GetScreen()->SetModify(); GetScreen()->BlockLocate.Normalize(); /* calcul du vecteur de deplacement pour les deplacements suivants */ deltaX = GetScreen()->BlockLocate.m_MoveVector.x ; deltaY = GetScreen()->BlockLocate.m_MoveVector.y ; /* Deplacement des Segments de piste */ TRACK * track; track = m_Pcb->m_Track; while( track ) { if( IsSegmentInBox(GetScreen()->BlockLocate, track ) ) { /* la piste est ici bonne a etre deplacee */ m_Pcb->m_Status_Pcb = 0 ; track->Draw(DrawPanel, DC, GR_XOR) ; // effacement track->m_Start.x += deltaX ; track->m_Start.y += deltaY ; track->m_End.x += deltaX ; track->m_End.y += deltaY ; track->m_Param += deltaX ; track->m_Sous_Netcode += deltaY ; track->Draw(DrawPanel, DC, GR_OR) ; // reaffichage } track = (TRACK*) track->Pnext; } /* Deplacement des Segments de Zone */ track = (TRACK*)m_Pcb->m_Zone; while( track ) { if( IsSegmentInBox(GetScreen()->BlockLocate, track ) ) { /* la piste est ici bonne a etre deplacee */ track->Draw(DrawPanel, DC, GR_XOR) ; // effacement track->m_Start.x += deltaX ; track->m_Start.y += deltaY ; track->m_End.x += deltaX ; track->m_End.y += deltaY ; track->m_Param += deltaX ; track->m_Sous_Netcode += deltaY ; track->Draw(DrawPanel, DC, GR_OR) ; // reaffichage } track = (TRACK*) track->Pnext; } DrawPanel->Refresh(TRUE); } /**************************************************/ void WinEDA_BasePcbFrame::Block_Duplicate(wxDC * DC) /**************************************************/ /* routine de duplication des elements du block deja selectionne */ { int deltaX, deltaY; wxPoint oldpos; oldpos = GetScreen()->m_Curseur; GetScreen()->ManageCurseur = NULL; GetScreen()->m_Curseur = oldpos; DrawPanel->MouseToCursorSchema(); GetScreen()->SetModify(); GetScreen()->BlockLocate.Normalize(); /* calcul du vecteur de deplacement pour les deplacements suivants */ deltaX = GetScreen()->BlockLocate.m_MoveVector.x ; deltaY = GetScreen()->BlockLocate.m_MoveVector.y ; /* Deplacement des Segments de piste */ TRACK * track, *next_track, *new_track; track = m_Pcb->m_Track; while( track ) { next_track = track->Next(); if( IsSegmentInBox(GetScreen()->BlockLocate, track ) ) { /* la piste est ici bonne a etre deplacee */ m_Pcb->m_Status_Pcb = 0 ; new_track = track->Copy(1); new_track->Insert(m_Pcb,NULL); new_track->m_Start.x += deltaX ; new_track->m_Start.y += deltaY ; new_track->m_End.x += deltaX ; new_track->m_End.y += deltaY ; new_track->Draw(DrawPanel, DC, GR_OR) ; // reaffichage } track = next_track; } /* Deplacement des Segments de Zone */ track = (TRACK*)m_Pcb->m_Zone; while( track ) { next_track = track->Next(); if( IsSegmentInBox(GetScreen()->BlockLocate, track ) ) { /* la piste est ici bonne a etre deplacee */ new_track = new TRACK(m_Pcb); new_track = track->Copy(1); new_track->Insert(m_Pcb,NULL); new_track->m_Start.x += deltaX ; new_track->m_Start.y += deltaY ; new_track->m_End.x += deltaX ; new_track->m_End.y += deltaY ; new_track->Draw(DrawPanel, DC, GR_OR) ; // reaffichage } track = next_track; } } /**************************************************************************/ static TRACK * IsSegmentInBox( DrawBlockStruct & blocklocate, TRACK * PtSegm ) /**************************************************************************/ /* Teste si la structure PtStruct est inscrite dans le block selectionne Retourne PtSegm si oui NULL si non */ { if ( blocklocate.Inside(PtSegm->m_Start.x ,PtSegm->m_Start.y) ) return ( PtSegm ); if ( blocklocate.Inside(PtSegm->m_End.x, PtSegm->m_End.y) ) return ( PtSegm ); return ( NULL ); }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 426 ] ] ]
90e0ab39fa4f13ef08e721690a538f3345b27346
3ec03fa7bb038ea10801d09a685b9561f827928b
/js_gecko2/stdafx.cpp
d45b6d5e7111468b7d3ed12595a0fecf7ef09f7c
[]
no_license
jbreams/njord
e2354f2013af0d86390ae7af99a419816ee417cb
ef7ff45fa4882fe8d2c6cabfa7691e2243fe8341
refs/heads/master
2021-01-24T17:56:32.048502
2009-12-15T18:57:32
2009-12-15T18:57:32
38,331,688
1
0
null
null
null
null
UTF-8
C++
false
false
296
cpp
// stdafx.cpp : source file that includes just the standard includes // js_gecko2.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "jreams@1c42f586-7543-11de-ba67-499d525147dd" ]
[ [ [ 1, 8 ] ] ]
9e1e21e318cf3104b17824aa0c68f2f07d7e234e
59a6020b36f5a757b62034471381b75985a4bb3d
/src/util/stopwatch.h
e19b7c2a763f635e99d8c55d2bbf7d2fcd17fb19
[]
no_license
feengg/MeshLib
74322ba7a88a69d727612d0869858c48c0b734c7
ae212df1c75c07fe4ab2b1f5a239be02b72f9da5
refs/heads/master
2020-03-28T16:43:52.332838
2011-06-26T14:56:50
2011-06-26T14:56:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
849
h
#ifndef _BASIC_OS_STOPWATCH_H #define _BASIC_OS_STOPWATCH_H //_________________________________________________________ #ifdef WIN32 #include <windows.h> #else #include <sys/types.h> #include <sys/times.h> #endif //______________________________________________________________________ class SystemStopwatch { public : SystemStopwatch() ; /** * prints real, user and system times since the * construction of this SystemStopWatch (in seconds). */ void print_elapsed_time() ; /** * returns user elapsed time since the construction * of this SystemStopWatch (in seconds). */ double elapsed_user_time() const ; /** * returns current time (in seconds). */ static double now() ; private: #ifdef WIN32 long start_ ; #else tms start_ ; clock_t start_user_ ; #endif } ; #endif
[ [ [ 1, 47 ] ] ]
1a9de54eaf5773051c294b52dfb243031794a3db
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Modules/UiCtrl/AudioCtrlScript.cpp
267a22fff7795019622cf2f7ceda0c1045dac572
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
37,473
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Quality.h" #include "AudioCtrlScript.h" #include "RouteEnums.h" #include "AudioClipsEnum.h" #include "Log.h" #define LOGPOINTER if(m_log)m_log #include "LogMacros.h" /* ****************** Scripted audio syntax. Loads files prepared by the SyntaxEdit java application. ********************* */ namespace isab{ using namespace RouteEnums; using namespace AudioClipsEnum; AudioCtrlLanguageScript::AudioCtrlLanguageScript() : AudioCtrlLanguage(), m_lastDistanceIndex(-1) { // FIXME - XXX - Only for debugging m_log = NULL; m_file = NULL; m_numSounds = 0; m_clipFileNames = NULL; m_clipFileNameBuffer = NULL; m_macros = NULL; // Metric is the safe bet - all languages support it InitDistanceTableMetric(); m_soundListNormalMacro = -1; m_crossingListMacro = -1; m_newCrossingMacro = -1; m_cameraMacro = -1; m_atDestMacro = -1; m_offTrackMacro = -1; m_wrongWayMacro = -1; m_gpsChangeMacro = -1; m_positiveMacro = -1; m_negativeMacro = -1; m_verbosity = VerbosityNormal; } AudioCtrlLanguageScript::~AudioCtrlLanguageScript() { delete[] m_clipFileNames; delete[] m_clipFileNameBuffer; distanceTable.clear(); delete m_log; } class AudioCtrlLanguage* AudioCtrlLanguageScript::New() { AudioCtrlLanguageScript * a = new AudioCtrlLanguageScript(); return a; } int AudioCtrlLanguageScript::supportsFeetMiles() { return 1; } int AudioCtrlLanguageScript::supportsYardsMiles() { return 1; } /********** Start of temporary code ***************/ /* borrowed from AudioCtrlStd */ #define DPB distanceTable.push_back void AudioCtrlLanguageScript::InitDistanceTableMetric() { distanceTable.clear(); /* spokenDistance, sayAtDistance, abortTooShortDistance, abortTooFarDistance, ignoreIfFaster */ DPB(DistanceTableEntry( -1, DistanceInfo( NoDistance, -1, -1 ), 9999 )); /* priosound */ DPB(DistanceTableEntry(2000, DistanceInfo( 2000, 1700, MAX_INT32 ), 9999 )); DPB(DistanceTableEntry(1000, DistanceInfo( 1000, 800, 2050 ), 9999 )); DPB(DistanceTableEntry( 500, DistanceInfo( 500, 450, 1050 ), 9999 )); DPB(DistanceTableEntry( 200, DistanceInfo( 200, 170, 550 ), 9999 )); DPB(DistanceTableEntry( 100, DistanceInfo( 100, 60, 210 ), 16 )); DPB(DistanceTableEntry( 50, DistanceInfo( 55, 35, 110 ), 5 )); DPB(DistanceTableEntry( 25, DistanceInfo( 30, 20, 60 ), 2 )); DPB(DistanceTableEntry( 0, DistanceInfo( 18, -1, 30 ), 9999 )); DPB(DistanceTableEntry( -1, DistanceInfo( NeverSay, -1, 50 ), 9999 )); /* Never spoken! */ m_currentUnits = MetricUnits; } void AudioCtrlLanguageScript::InitDistanceTableFeetMiles() { distanceTable.clear(); /* spokenDistance, sayAtDistance, abortTooShortDistance, abortTooFarDistance, ignoreIfFaster */ DPB(DistanceTableEntry( -1, DistanceInfo( NoDistance, -1, -1 ), 9999 )); /* priosound */ DPB(DistanceTableEntry(3219, DistanceInfo( 3219, 2919, MAX_INT32 ), 9999 )); DPB(DistanceTableEntry(1609, DistanceInfo( 1609, 1409, 3269 ), 9999 )); DPB(DistanceTableEntry( 803, DistanceInfo( 803, 753, 1659 ), 9999 )); DPB(DistanceTableEntry( 402, DistanceInfo( 402, 352, 853 ), 9999 )); DPB(DistanceTableEntry( 152, DistanceInfo( 152, 122, 452 ), 16 )); DPB(DistanceTableEntry( 61, DistanceInfo( 66, 46, 162 ), 5 )); DPB(DistanceTableEntry( 31, DistanceInfo( 36, 26, 71 ), 2 )); DPB(DistanceTableEntry( 0, DistanceInfo( 18, -1, 36 ), 9999 )); DPB(DistanceTableEntry( -1, DistanceInfo( NeverSay, -1, 61 ), 9999 )); /* Never spoken! */ m_currentUnits = ImperialFeetMilesUnits; } void AudioCtrlLanguageScript::InitDistanceTableYardsMiles() { distanceTable.clear(); /* spokenDistance, sayAtDistance, abortTooShortDistance, abortTooFarDistance, ignoreIfFaster */ DPB(DistanceTableEntry( -1, DistanceInfo( NoDistance, -1, -1 ), 9999 )); /* priosound */ DPB(DistanceTableEntry(3219, DistanceInfo( 3219, 2919, MAX_INT32 ), 9999 )); DPB(DistanceTableEntry(1609, DistanceInfo( 1609, 1409, 3269 ), 9999 )); DPB(DistanceTableEntry( 803, DistanceInfo( 803, 753, 1659 ), 9999 )); DPB(DistanceTableEntry( 402, DistanceInfo( 402, 352, 853 ), 9999 )); DPB(DistanceTableEntry( 182, DistanceInfo( 182, 152, 452 ), 9999 )); DPB(DistanceTableEntry( 91, DistanceInfo( 91, 51, 192 ), 16 )); DPB(DistanceTableEntry( 46, DistanceInfo( 51, 31, 101 ), 5 )); DPB(DistanceTableEntry( 23, DistanceInfo( 28, 18, 56 ), 2 )); DPB(DistanceTableEntry( 0, DistanceInfo( 18, -1, 34 ), 9999 )); DPB(DistanceTableEntry( -1, DistanceInfo( NeverSay, -1, 56 ), 9999 )); /* Never spoken! */ m_currentUnits = ImperialYardsMilesUnits; } #undef DPB void AudioCtrlLanguageScript::selectUnits(enum SpokenUnits units) { if (units == m_currentUnits) { return; } switch (units) { case MetricUnits: InitDistanceTableMetric(); resetState(); break; case ImperialFeetMilesUnits: if (supportsFeetMiles()) { InitDistanceTableFeetMiles(); resetState(); } else { // This call must not fail!!! selectUnits(MetricUnits); } break; case ImperialYardsMilesUnits: if (supportsYardsMiles()) { InitDistanceTableYardsMiles(); resetState(); } else { // This call must not fail!!! selectUnits(ImperialFeetMilesUnits); } break; default: // FIXME - warn here? break; } } /* FIXME - r.distToWpt är inte bra, använd extrapolerad position! */ int32 AudioCtrlLanguageScript::policyNextDistance(const RouteInfo &r, DistanceInfo &deadlines) { int32 spokenDistance; if (r.onTrackStatus != OnTrack) { // WARN("policyNextDistance called with onTrackStatus != OnTrack"); deadlines = distanceTable[0].info; m_lastDistanceIndex = 0; spokenDistance = 0; // Placeholder, not used return spokenDistance; } int lastSound; if (m_lastDistanceIndex < 0) { lastSound = 0; } else { lastSound = m_lastDistanceIndex; } int nextSound = lastSound + 1; /* Accept any sound within the interval sayAtDistance..abortTooShortDistance if this is the first sound after a priority sound. We want to say something as soon as possible. This is done by switching from sayAtDistance to abortTooShortDistance as a criteria. */ if (lastSound == 0) { /* Find the first possible distance. This is the next sound to play, * were it not for the user override settings. Those settings are * taken into account in the next while loop. */ while (distanceTable[nextSound].info.abortTooShortDistance > r.distToWpt ) { ++nextSound; } } else { /* Find the first possible distance. This is the next sound to play, * were it not for the user override settings. Those settings are * taken into account in the next while loop. */ while (distanceTable[nextSound].info.sayAtDistance > r.distToWpt ) { ++nextSound; } } #if 1 int tooFarDeadline = distanceTable[nextSound].info.abortTooFarDistance; /* Find the first allowed sound, and carry the abortTooFarDistance from the * first match above. */ // This loop terminates since the last elements in the distance tables // cannot be prohibited by the user. while (1) { bool prohibited = false; // Supress some extra distances if verbosity is set to "less" if (m_verbosity == VerbosityReduced) { if (distanceTable[nextSound].spokenDistance > 1700) { prohibited = true; } if (lastSound != 0) { // If a sound has already been played we skip down to 200m or 100m depending // on the current speed. // This limits are chosen to coincide with the limits in the distanceTable. int distanceLimit; if (r.speed >= 16) { distanceLimit = 450; } else { distanceLimit = 160; } if (distanceTable[nextSound].spokenDistance > distanceLimit) { prohibited = true; } } } // Supress some distances when driving fast. if (r.speed > distanceTable[nextSound].ignoreIfFaster) prohibited = true; // Supress "Finally" when closer than 100 meters to the goal. if ( (RouteAction(r.currCrossing.action) == Finally) && (distanceTable[nextSound].info.sayAtDistance <= 50) ) prohibited = true; // Always use the "no next sound" sound. if (distanceTable[nextSound].info.sayAtDistance == NeverSay) prohibited = false; if (!prohibited) { deadlines = distanceTable[nextSound].info; deadlines.abortTooFarDistance = tooFarDeadline; spokenDistance = distanceTable[nextSound].spokenDistance; if (deadlines.sayAtDistance >= 0) { m_lastDistanceIndex = nextSound; } return spokenDistance; } ++nextSound; } #else deadlines = distanceTable[nextSound].info; spokenDistance = distanceTable[nextSound].spokenDistance; // If this is the special last marker sound, reuse the last m_lastDistanceIndex if (deadlines.sayAtDistance >= 0) { m_lastDistanceIndex = nextSound; } #endif return spokenDistance; } int32 AudioCtrlLanguageScript::policyAdditionalDistance(int32 distance) { int nextSound = 1; /* Find the first possible distance. This is the next sound to play, * were it not for the user override settings. Those settings are * taken into account in the next while loop. */ if (distance < 0) { distance = 0; } while (distanceTable[nextSound].info.sayAtDistance > distance ) { ++nextSound; } return (distanceTable[nextSound].spokenDistance); } /********** End of temporary code ***************/ int AudioCtrlLanguageScript::executeSpecialMacro( int macro, DistanceInfo &deadlines, SoundClipsList &soundClips) { deadlines.sayAtDistance = -1; deadlines.abortTooShortDistance = -1; deadlines.abortTooFarDistance = -1; RunState rs(soundClips); rs.xings[0].action = 0; rs.xings[0].spokenDist= 0; rs.xings[0].valid = false; rs.xings[0].exitCount = 0; rs.xings[0].side = 0; rs.xings[0].gpsQ = 0; rs.xings[1].action = 0; rs.xings[1].spokenDist= 0; rs.xings[1].valid = false; rs.xings[1].exitCount = 0; rs.xings[1].side = 0; rs.xings[1].gpsQ = 0; if (macro >= 0) { runGraph( macro, rs ); } else { WARN("No special macro\n"); } resetState(); return 0; } int AudioCtrlLanguageScript::newCrossingSoundList( DistanceInfo &deadlines, SoundClipsList &soundClips) { if (m_newCrossingMacro >= 0) { executeSpecialMacro(m_newCrossingMacro, deadlines, soundClips); } else { WARN("No NewCrossing macro\n"); } return 0; } int AudioCtrlLanguageScript::newCameraSoundList( DistanceInfo &deadlines, SoundClipsList &soundClips) { if (m_cameraMacro >= 0) { executeSpecialMacro(m_cameraMacro, deadlines, soundClips); } else { WARN("No SoundListCamera macro\n"); } return 0; } int AudioCtrlLanguageScript::badSoundList( DistanceInfo &deadlines, SoundClipsList &soundClips) { if ( m_negativeMacro >= 0 ) { executeSpecialMacro( m_negativeMacro, deadlines, soundClips ); } else { WARN( "No Bad sound macro\n" ); } return 0; } int AudioCtrlLanguageScript::goodSoundList( DistanceInfo &deadlines, SoundClipsList &soundClips) { if ( m_positiveMacro >= 0 ) { executeSpecialMacro( m_positiveMacro, deadlines, soundClips ); } else { WARN( "No Good sound macro\n" ); } return 0; } int AudioCtrlLanguageScript::statusOfGPSChangedSoundList( const Quality& q, DistanceInfo &deadlines, SoundClipsList &soundList ) { if ( m_gpsChangeMacro >= 0 ) { deadlines.sayAtDistance = -1; deadlines.abortTooShortDistance = -1; deadlines.abortTooFarDistance = -1; RunState rs( soundList ); rs.xings[0].action = 0; rs.xings[0].exitCount = 0; rs.xings[0].spokenDist = 0; rs.xings[0].side = 0; rs.xings[0].valid = true; rs.xings[0].gpsQ = q; rs.xings[1].action = 0; rs.xings[1].exitCount = 0; rs.xings[1].spokenDist = 0; rs.xings[1].side = 0; rs.xings[1].valid = false; rs.xings[1].gpsQ = 0; runGraph( m_gpsChangeMacro, rs ); } return 0; } void AudioCtrlLanguageScript::immediateDeadline(DistanceInfo &deadlines) { deadlines = distanceTable[0].info; m_lastDistanceIndex = 0; } void AudioCtrlLanguageScript::resetState() { m_lastDistanceIndex = -1; } int AudioCtrlLanguageScript::syntheziseSoundList(const RouteInfo &r, bool onTrackStatusChanged, DistanceInfo &deadlines, SoundClipsList &soundList) { // FIXME - XXX - Only for debugging if (NULL == m_log) { m_log = new Log("AudioScript"); } switch (r.onTrackStatus) { case OnTrack: { RunState rs(soundList); // Extract information from the crossing c rs.xings[0].action = r.currCrossing.action; rs.xings[0].exitCount = r.currCrossing.exitCount; rs.xings[0].valid = r.currCrossing.valid; if (rs.xings[0].valid) { rs.xings[0].spokenDist= policyNextDistance(r, deadlines); } rs.xings[0].side = r.currSeg.isLeftTraffic() ? 0 : 1; rs.xings[0].gpsQ = 0; rs.xings[1].action = r.nextCrossing1.action; rs.xings[1].exitCount = r.nextCrossing1.exitCount; rs.xings[1].valid = r.nextCrossing1.valid; rs.xings[1].spokenDist= policyAdditionalDistance(r.currCrossing.distToNextCrossing); rs.xings[1].side = r.nextSeg1.isLeftTraffic() ? 0 : 1; rs.xings[1].gpsQ = 0; if (m_verbosity == VerbosityReduced) { rs.xings[1].valid = false; } if ( ! (rs.xings[0].valid) ) { // No valid first crossing. return 0; } if (m_soundListNormalMacro >= 0) { runGraph( m_soundListNormalMacro, rs ); } else { WARN("No SoundListNormal macro\n"); } } break; case OffTrack: if (onTrackStatusChanged) { executeSpecialMacro(m_offTrackMacro, deadlines, soundList); } break; case WrongWay: if (onTrackStatusChanged) { executeSpecialMacro(m_wrongWayMacro, deadlines, soundList); } break; case Goal: if (onTrackStatusChanged) { executeSpecialMacro(m_atDestMacro, deadlines, soundList); } break; } return 0; } int AudioCtrlLanguageScript::syntheziseCrossingSoundList(const RouteInfoParts::Crossing &c, DistanceInfo &deadlines, SoundClipsList &soundList) { // FIXME - XXX - Only for debugging if (NULL == m_log) { m_log = new Log("AudioScript"); } deadlines.sayAtDistance = -1; deadlines.abortTooShortDistance = -1; deadlines.abortTooFarDistance = -1; RunState rs(soundList); // Extract information from the crossing c rs.xings[0].action = c.action; rs.xings[0].spokenDist= 100; // Hack to get the roundabout sounds right. rs.xings[0].valid = c.valid; rs.xings[0].exitCount = c.exitCount; rs.xings[0].side = 0; rs.xings[0].gpsQ = 0; rs.xings[1].action = 0; // Should never be selected rs.xings[1].spokenDist= 0; rs.xings[1].valid = false; rs.xings[1].exitCount = 0; rs.xings[1].side = 0; rs.xings[1].gpsQ = 0; if ( ! (rs.xings[0].valid) ) { // No valid first crossing. return 0; } if (m_crossingListMacro >= 0) { runGraph( m_crossingListMacro, rs ); } else { WARN("No crossingListMacro\n"); } return 0; } bool AudioCtrlLanguageScript::gotoNodeInMacro(RunState & rs, int nextNode) { DBG("gotoNodeInMacro m=%s, nextNode=%i\n", rs.gs.macro->name, nextNode); // Loop until a real node is reached while (1) { if (nextNode >= 0) { // Regular node rs.gs.node = &(rs.gs.macro->nodes[nextNode]); return true; } else { // Fake node (i.e. return, fail etc) switch (static_cast<KnownNodeIds>(nextNode)) { case Fail: { while (1) { if (rs.callStack.empty()) { // We have failed out of the start macro. No // audio will be played. rs.soundList.erase(rs.soundList.begin(), rs.soundList.end()); return false; } RunState::CallStackEntry cse = rs.callStack.top(); rs.callStack.pop(); if (cse.type == RunState::CallStackEntry::Try) { rs.gs = cse.oldGraphState; rs.soundList.erase(rs.soundList.begin()+cse.clipListSize, rs.soundList.end()); nextNode = rs.gs.node->falseId; break; } } } break; case None: // Fall through case Return: // Fall through default: // Internal error - what to do? Treat as return for now { while (1) { if (rs.callStack.empty()) { // Return off of the start macro. We are done. return false; } RunState::CallStackEntry cse = rs.callStack.top(); rs.callStack.pop(); if (cse.type == RunState::CallStackEntry::Call) { rs.gs = cse.oldGraphState; nextNode = rs.gs.node->nextOrTrueId; break; } } } break; } DBG(" once more m=%s, nextNode=%i\n", rs.gs.macro->name, nextNode); } } } bool AudioCtrlLanguageScript::moveToNextNode(RunState & rs) { return gotoNodeInMacro(rs, rs.gs.node->nextOrTrueId); } bool AudioCtrlLanguageScript::evalCondition(const RunState & rs, const Node & node) { int16 varVal; DBG("evalCondition %i %i %i\n", node.variable, node.relation, node.limit); switch (static_cast<Node::Variable>(node.variable)) { case Node::VarDist: varVal = rs.xings[rs.gs.xing].spokenDist; break; case Node::VarTurn: varVal = rs.xings[rs.gs.xing].action; break; case Node::VarXing: varVal = rs.gs.xing+1; // One-based test break; case Node::VarExit: varVal = rs.xings[rs.gs.xing].exitCount; break; case Node::VarSide: varVal = rs.xings[rs.gs.xing].side; break; case Node::VarGpsQ: varVal = rs.xings[rs.gs.xing].gpsQ; break; case Node::VarZero: default: varVal = 0; break; } DBG(" val=%i\n", varVal); int16 limit = node.limit; switch (static_cast<Node::Relation>(node.relation)) { case Node::Equal: return varVal == limit; case Node::NotEqual: return varVal != limit; case Node::LessThan: return varVal < limit; case Node::GreaterThan: return varVal > limit; case Node::LessThanOrEqual: return varVal <= limit; case Node::GreaterThanOrEqual: return varVal >= limit; default: return false; } } void AudioCtrlLanguageScript::runGraph( int startMacro, RunState & rs) { rs.gs.macro = &(m_macros[startMacro]); rs.gs.node = &(rs.gs.macro->nodes[rs.gs.macro->startnode]); // Assume the first crossing on entry rs.gs.xing = 0; while (1) { //Macro & macro = *rs.gs.macro; DBG("Node addr %p\n", rs.gs.node); Node & node = *rs.gs.node; switch (static_cast<Node::Type>(node.type)) { case Node::Clip: DBG("Got clip %i\n", node.clipOrMacroId); rs.soundList.push_back(node.clipOrMacroId); DBG(" clip2\n"); if ( ! moveToNextNode(rs)) { return; } DBG(" clip3\n"); break; case Node::Macro: { RunState::CallStackEntry cse; cse.type=RunState::CallStackEntry::Call; cse.oldGraphState=rs.gs; rs.callStack.push(cse); rs.gs.macro=&(m_macros[node.clipOrMacroId]); DBG("Got Macro call to %s\n", rs.gs.macro->name); if ( ! gotoNodeInMacro(rs, rs.gs.macro->startnode) ) { return; } } break; case Node::Boolean: { DBG("Got boolean\n"); int nodeId; if (evalCondition(rs, node)) { nodeId=rs.gs.node->nextOrTrueId; } else { nodeId=rs.gs.node->falseId; } if ( ! gotoNodeInMacro(rs, nodeId)) { return; } } break; case Node::Try: { DBG("Got try\n"); RunState::CallStackEntry cse; cse.type=RunState::CallStackEntry::Try; cse.oldGraphState=rs.gs; cse.clipListSize = rs.soundList.size(); rs.callStack.push(cse); if ( ! moveToNextNode(rs)) { return; } } break; case Node::Xing: DBG("Got xing\n"); rs.gs.xing = node.xing-1; // Zero-based index if ( ! (rs.xings[rs.gs.xing].valid) ) { // No such crossing - fail if ( ! gotoNodeInMacro(rs, static_cast<int>(Fail))) { return; } } if ( ! moveToNextNode(rs)) { return; } break; default: return; } } /* while */ } /************ File reader *****************/ int AudioCtrlLanguageScript::readInt8(int8 & i) { int num_read = fread(&i, 1, 1, m_file); return (num_read!=1); } int AudioCtrlLanguageScript::readInt16(int16 & i) { uint8 low, high; if (1 != fread(&low, 1, 1, m_file)) { return 1; } if (1 != fread(&high, 1, 1, m_file)) { return 1; } i = static_cast<int16>((( static_cast<uint16>(high) ) << 8) | low); return 0; } int AudioCtrlLanguageScript::skipString() { int8 length; if ( readInt8(length)) { return 1; } fseek(m_file, length, SEEK_CUR); return 0; } int AudioCtrlLanguageScript::readString(char * str) { int8 length; if ( readInt8(length)) { return 1; } if ( 1 != fread(str, length, 1, m_file)) { return 1; } str[length]=0; return 0; } int AudioCtrlLanguageScript::readAllocString(char * & str) { int8 length; if ( readInt8(length)) { return 1; } str = new char[length+1]; if (NULL==str) { return 1; } if ( 1 != fread(str, length, 1, m_file)) { delete[] str; str = NULL; return 1; } str[length]=0; return 0; } bool AudioCtrlLanguageScript::isInvalidNodeId(int16 id) { if ( (id < -3) || (id >= (int)(m_curM->nodes.size())) ) { return true; } return false; } bool AudioCtrlLanguageScript::isInvalidClipId(int16 id) { // Allow the timing marker. if ( id == -3) { return false; } if ( (id < 0) || (id >= m_numSounds) ) { return true; } return false; } bool AudioCtrlLanguageScript::isInvalidMacroId(int16 id) { if ( (id < 0) || (id >= m_readMacros) ) { return true; } return false; } int AudioCtrlLanguageScript::readStartNode() { int16 id; if (readInt16(id) || isInvalidNodeId(id)) { return 1; } m_curM->startnode = id; return 0; } int AudioCtrlLanguageScript::readSoundClipNode() { Node n; if (readInt16(n.nextOrTrueId) || isInvalidNodeId(n.nextOrTrueId)) { return 1; } if (readInt16(n.clipOrMacroId) || isInvalidClipId(n.clipOrMacroId)) { return 1; } n.type = Node::Clip; m_curM->nodes.push_back(n); return 0; } int AudioCtrlLanguageScript::readMacroCallNode() { Node n; if (readInt16(n.nextOrTrueId) || isInvalidNodeId(n.nextOrTrueId)) { return 1; } if (readInt16(n.clipOrMacroId) || isInvalidMacroId(n.clipOrMacroId)) { return 1; } n.type = Node::Macro; m_curM->nodes.push_back(n); return 0; } int AudioCtrlLanguageScript::readBooleanNode() { Node n; if (readInt8(n.variable)) { return 1; } if (readInt8(n.relation)) { return 1; } if (readInt16(n.limit)) { return 1; } DBG("Read boolean node %i %i %i\n", n.variable, n.relation, n.limit); if (readInt16(n.nextOrTrueId) || isInvalidNodeId(n.nextOrTrueId)) { return 1; } if (readInt16(n.falseId) || isInvalidNodeId(n.falseId)) { return 1; } n.type = Node::Boolean; m_curM->nodes.push_back(n); return 0; } int AudioCtrlLanguageScript::readTryCatchNode() { Node n; if (readInt16(n.nextOrTrueId) || isInvalidNodeId(n.nextOrTrueId)) { return 1; } if (readInt16(n.falseId) || isInvalidNodeId(n.falseId)) { return 1; } n.type = Node::Try; m_curM->nodes.push_back(n); return 0; } int AudioCtrlLanguageScript::readSelectXingNode() { Node n; if (readInt16(n.nextOrTrueId) || isInvalidNodeId(n.nextOrTrueId)) { return 1; } if (readInt8(n.xing)) { return 1; } n.type = Node::Xing; m_curM->nodes.push_back(n); return 0; } int AudioCtrlLanguageScript::selectSyntaxVersion(const char *fileName, int & numClips, char ** & clipFileNames) { // FIXME - XXX - Only for debugging if (NULL == m_log) { m_log = new Log("AudioScript"); } DBG("selectSyntaxVersion %s", fileName); static const char * const expectedHeader = "WF_AUDIO_SYNTAX: 1\n"; m_file = fopen(fileName, "rb"); if (m_file == NULL) { // File not found? return 1; } char header[19]; if (1 != fread(header,19,1,m_file)) { // Failed to read header goto out; } if (0 != memcmp(header, expectedHeader, strlen(expectedHeader))) { // Wrong file format goto out; } // Read out all options // Ignore all options for now int8 option; do { if (readInt8(option)) { // Read past end of file goto out; } } while (option != 0x00); // Read the sound clips // Ignore the name, only the filename is important if (readInt16(m_numSounds)) { goto out; } numClips = m_numSounds; { clipFileNames = new char*[m_numSounds]; for (int soundNo = 0; soundNo<m_numSounds; ++soundNo) { // name - ignore if (skipString()) { goto out; } if (readAllocString(clipFileNames[soundNo])) { goto out; } } } // Read the distrance table // Not implemented yet. // Read the macros m_soundListNormalMacro = -1; m_crossingListMacro = -1; m_newCrossingMacro = -1; m_cameraMacro = -1; m_atDestMacro = -1; m_wrongWayMacro = -1; m_offTrackMacro = -1; m_gpsChangeMacro = -1; m_positiveMacro = -1; m_negativeMacro = -1; int16 nummacros; if (readInt16(nummacros)) { goto out; } if (m_macros) { delete[] m_macros; } m_macros = new Macro[nummacros]; for (m_readMacros = 0; m_readMacros<nummacros; ++m_readMacros) { m_curM = m_macros+m_readMacros; char tmpName[50]; if (readString(tmpName)) { goto out; } if (0 == strcmp(tmpName, "SoundListNormal")) { m_soundListNormalMacro = m_readMacros; } else if (0 == strcmp(tmpName, "SoundListXing")) { m_crossingListMacro = m_readMacros; } else if (0 == strcmp(tmpName, "NewCrossing")) { m_newCrossingMacro = m_readMacros; } else if (0 == strcmp(tmpName, "SoundListSpeedCam")) { m_cameraMacro = m_readMacros; } else if (0 == strcmp(tmpName, "SoundListAtDest")) { m_atDestMacro = m_readMacros; } else if (0 == strcmp(tmpName, "SoundListOffTrack")) { m_offTrackMacro = m_readMacros; } else if (0 == strcmp(tmpName, "SoundListWrongWay")) { m_wrongWayMacro = m_readMacros; } else if (0 == strcmp(tmpName, "SoundListGpsChange")) { m_gpsChangeMacro = m_readMacros; } else if (0 == strcmp(tmpName, "Positive")) { m_positiveMacro = m_readMacros; } else if (0 == strcmp(tmpName, "Negative")) { m_negativeMacro = m_readMacros; } // Store the macro name - debugging only strcpy(m_curM->name, tmpName); // Read the graph int8 nodeType; do { if (readInt8(nodeType)) { goto out; } switch (nodeType) { case 0: // Start node if (readStartNode()) { goto out; } break; case 1: // Play sound node if (readSoundClipNode()) { goto out; } break; case 2: // Macro call node if (readMacroCallNode()) { goto out; } break; case 3: // Boolean condition node if (readBooleanNode()) { goto out; } break; case 4: // Try/catch node if (readTryCatchNode()) { goto out; } break; case 5: // Select xing node if (readSelectXingNode()) { goto out; } break; default: goto out; } } while (nodeType != 0x00); } fclose(m_file); m_file = NULL; return 0; out: fclose(m_file); m_file = NULL; return 1; } int AudioCtrlLanguageScript::setVerbosity(AudioVerbosity verbosity) { m_verbosity = verbosity; resetState(); return 0; } } /* namespace isab */
[ [ [ 1, 1053 ] ] ]
2f31cf62de346518e97871d062aa80a2f09ac037
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nnavmesh/src/ncnavmesh/ncnavmeshnode_main.cc
655adaf1bf4b2ad8409789993144cfae59361a0b
[]
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
20,619
cc
#include "precompiled/pchnnavmesh.h" //------------------------------------------------------------------------------ // ncnavmeshnode.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "ncnavmesh/ncnavmeshnode.h" #include "mathlib/polygon.h" #include "nspatial/nspatialserver.h" #include "nspatial/ncspatial.h" #include "ngeomipmap/ncterraingmmclass.h" #include "nspatial/ncspatialquadtree.h" #include "nnavmesh/nnavutils.h" #ifndef NGAME #include "gfx2/ngfxserver2.h" #include "gfx2/nlineserver.h" #include "nscene/nsceneserver.h" #endif //------------------------------------------------------------------------------ nNebulaComponentObject(ncNavMeshNode,ncNavNode); //------------------------------------------------------------------------------ NSCRIPT_INITCMDS_BEGIN(ncNavMeshNode) NSCRIPT_INITCMDS_END() namespace { // Tolerance to consider two points to be in the same ground level when // comparing their projected height on the ground. const float GroundHeightTolerance( 0.05f ); } //------------------------------------------------------------------------------ /** Constructor */ ncNavMeshNode::ncNavMeshNode() #ifndef NGAME : isInOutdoor( false ) #endif { this->CreateNode(); } //------------------------------------------------------------------------------ /** Constructor */ ncNavMeshNode::ncNavMeshNode (const polygon* zone) { this->CreateNode (zone); } //------------------------------------------------------------------------------ /** Destructor */ ncNavMeshNode::~ncNavMeshNode() { n_delete (this->zone); n_delete (this->userData); this->zone = 0; this->userData = 0; } //------------------------------------------------------------------------------ /** CreateNode */ void ncNavMeshNode::CreateNode (const polygon* zone) { if ( zone ) { this->zone = n_new (polygon)(*zone); // Copies the polygon to the node } else { this->zone = 0; } this->userData = 0; this->f = this->g = this->h = 0; this->parent = 0; } //------------------------------------------------------------------------------ /** GetMidPoint */ void ncNavMeshNode::GetMidpoint( vector3& midpoint ) const { #ifndef NGAME n_assert( this->zone ); if ( !this->zone ) { return; } #endif midpoint = this->zone->Midpoint(); this->GetGroundHeight( midpoint.x, midpoint.z, midpoint.y ); } //------------------------------------------------------------------------------ /** Tell if a point is inside this node A point is considered to be inside this node if the point's projection over the polygon is inside it and if both the point and the polygon are in the same ground level. */ bool ncNavMeshNode::IsPointInside( const vector3& point ) const { n_assert( this->zone ); // Do a first fast culling by skipping those nav nodes whose 2D bounding box doesn't contain the point at all const bbox3& bbox( this->GetComponentSafe<ncSpatial>()->GetBBox() ); if ( (point.x < bbox.vmin.x) || (point.x > bbox.vmax.x) || (point.z < bbox.vmin.z) || (point.z > bbox.vmax.z) ) { return false; } // Do a second slower culling by checking if the point projects inside the polygon if ( !this->zone->IsPointInside( point.x, point.z ) ) { return false; } // Finally check if the nav node is at the same ground level as the given point // @todo Use GetGroundLevelHeight instead of GetGroundHeight to avoid the special // case where there's an obstacle between the node and the real ground. // For now this cannot be used because movement is allowed over that kind // of obstacles through nav nodes, but currently there isn't any way to // detect that "ground layer". float nodeHeight; float pointHeight; if ( this->GetGroundHeight( point.x, point.z, nodeHeight ) && nNavUtils::GetGroundHeight( point, pointHeight ) ) { if ( n_abs( pointHeight - nodeHeight ) <= GroundHeightTolerance ) { return true; } } return false; } //------------------------------------------------------------------------------ /** IsPointInside */ bool ncNavMeshNode::IsPointInside (float x, float z) const { n_assert(this->zone); bool inside = false; if ( this->zone ) { inside = this->zone->IsPointInside (x, z); } return inside; } //------------------------------------------------------------------------------ /** Get the node's closest navigable point to the given point */ void ncNavMeshNode::GetClosestNavigablePoint( const vector3& point, vector3& closestPoint ) const { n_assert( this->zone ); this->zone->GetClosestPoint2d( point, closestPoint ); this->GetGroundHeight( closestPoint.x, closestPoint.z, closestPoint.y ); } //------------------------------------------------------------------------------ /** Get cross information regarding to a ray exiting this node */ ncNavMeshNode::CrossType ncNavMeshNode::GetCrossInfo( const line3& ray, ncNavMeshNode*& neighbor, vector3& crossPoint, vector3& crossNormal ) const { // If the ray ends inside the node then it doesn't leave it for sure // Need to do the most expensive 3D check due to overlayed navmeshes if ( this->IsPointInside( ray.end() ) ) { return STAYING_INSIDE; } // Check if the ray intersects some edge, getting the one that intersects further from the ray's origin // (the furthest intersected edge is the one crossed when the ray exits the node) float crossDistanceSq( -FLT_MAX ); int numVertices( this->zone->GetNumVertices() ); for ( int i(0); i < numVertices; ++i ) { // Build next edge and its plane orthogonal to XZ plane line3 edge( this->zone->GetVertex(i), this->zone->GetVertex( (i+1) % numVertices ) ); plane edgePlane( edge.start(), edge.end(), edge.end() + vector3(0,1,0) ); // Check if the ray crosses the edge float t; if ( edgePlane.intersect( ray, t ) ) { if ( t >= -TINY ) { vector3 rayCrossPoint( ray.ipol(t) ); t = edge.closestpoint( rayCrossPoint ); if ( t >= -TINY && t <= 1 + TINY ) { // Keep cross information if it's the furthest cross point so far float distanceSq( ( rayCrossPoint - ray.start() ).lensquared() ); if ( distanceSq > crossDistanceSq ) { neighbor = this->GetNeighborSharingEdge( edge ); crossDistanceSq = distanceSq; crossPoint = rayCrossPoint; // Assume mesh nodes are flat on XZ plane crossPoint.y = ray.start().y; crossNormal = edgePlane.normal(); if ( (ray.end() - ray.start()) % crossNormal > 0 ) { crossNormal *= -1; } } } } } } // Extra safety check to protect from float errors when ray's origin is on an edge if ( crossDistanceSq < TINY ) { return STAYING_INSIDE; } // If there's no neighbor after crossing the point, then the ray is leaving the mesh return neighbor ? GOING_TO_NEIGHBOR : GOING_OUT_OF_MESH; } //------------------------------------------------------------------------------ /** Get the neighbor sharing the given edge, or NULL if none shares it */ ncNavMeshNode* ncNavMeshNode::GetNeighborSharingEdge( const line3& edge ) const { // Iterate over all the neighbors looking for the one that shares the given edge for ( int i(0); i < this->GetLinksNumber(); ++i ) { ncNavNode* node( this->GetLink(i) ); if ( node ) { ncNavMeshNode* meshNode( node->GetComponent<ncNavMeshNode>() ); if ( meshNode ) { // Check if the node shares the edge polygon* poly( meshNode->GetZone() ); if ( poly->HasEdge( edge ) ) { return meshNode; } } } } // No neighbor shares the given edge return NULL; } #ifndef NGAME //------------------------------------------------------------------------------ /** Search and store which edges aren't shared with any neighbor */ void ncNavMeshNode::LookForBoundaryEdges() { this->boundaryEdges.Clear(); int numVertices = this->zone->GetNumVertices(); for ( int i(0); i < numVertices; ++i ) { line3 edge( this->zone->GetVertex(i), this->zone->GetVertex( (i+1) % numVertices ) ); if ( !this->GetNeighborSharingEdge(edge) ) { this->boundaryEdges.Append( i ); } } } //------------------------------------------------------------------------------ /** Draw */ void ncNavMeshNode::Draw( nLineHandler* lineHandler, bool wireframe, bool overlay, bool showLinks ) { this->Draw( lineHandler, this->isInOutdoor, 0, wireframe, overlay, showLinks ); } //------------------------------------------------------------------------------ /** Draw */ void ncNavMeshNode::Draw ( nLineHandler* lineHandler, bool isOutdoor, float /*high*/, bool wireframe, bool overlay, bool showLinks) { nGfxServer2* server = nGfxServer2::Instance(); this->DrawEdges (server, isOutdoor, wireframe, overlay); this->DrawBoundary( lineHandler, isOutdoor, overlay ); // Uncomment line below to debug mesh generation // this->DrawVertices (server, high); if ( showLinks ) { this->DrawLinks (server, isOutdoor, overlay); } // Uncomment block below to debug pathfinding /* // Draw 'parent' if ( this->parent ) { vector3 center; this->GetMidpoint( center ); vector3 parentCenter; this->parent->GetMidpoint( parentCenter ); vector3 direction = parentCenter - center; direction.norm(); direction *= 2.f; direction += center; vector3 line[2]; line[0] = center; line[1] = direction; line[0].y = -10.f; line[1].y = -10.f; server->BeginLines(); server->DrawLines3d (line, 2, vector4(0.4f, 0.6f, 0.4f, 1.f)); server->EndLines(); }*/ } //------------------------------------------------------------------------------ /** DrawBoundary */ void ncNavMeshNode::DrawBoundary( nLineHandler* lineHandler, bool isOutdoor, bool overlay ) { n_assert( lineHandler ); vector4& colour( isOutdoor ? this->outdoorBoundaryColour : this->indoorBoundaryColour ); int numVertices( this->zone->GetNumVertices() ); for ( int i(0); i < this->boundaryEdges.Size(); ++i ) { int edgeIndex = this->boundaryEdges[i]; vector3 v[2] = { this->zone->GetVertex(edgeIndex), this->zone->GetVertex( (edgeIndex+1) % numVertices ) }; this->UpdateDrawHeight( v[0], isOutdoor, overlay ); this->UpdateDrawHeight( v[1], isOutdoor, overlay ); lineHandler->DrawLines3d( v, NULL, 2, colour ); } } //------------------------------------------------------------------------------ /** DrawEdges */ void ncNavMeshNode::DrawEdges (nGfxServer2* server, bool isOutdoor, bool wireframe, bool overlay) { vector4 indoorLineColor( 0.8f, 0.2f, 0.8f, 1.0f ); vector4 indoorFillColor( 0.3f, 0.0f, 0.3f, 0.5f ); vector4 outdoorLineColor( 0.2f, 0.8f, 0.2f, 1.0f ); vector4 outdoorFillColor( 0.1f, 0.4f, 0.1f, 0.5f ); const int MaxVertices( 100 ); vector3 vertexes[MaxVertices]; vector3 center = this->zone->Midpoint(); for ( int j=0; j<this->zone->GetNumVertices() && j < MaxVertices - 1; j++ ) { vertexes[j] = this->zone->GetVertex(j); this->UpdateDrawHeight( vertexes[j], isOutdoor, overlay ); } vertexes[ this->zone->GetNumVertices() ] = vertexes[0]; matrix44 model; model.ident(); nGfxServer2::Instance()->BeginShapes( this->GetShader(overlay) ); if ( wireframe ) { nGfxServer2::Instance()->DrawShapePrimitives( nGfxServer2::LineStrip, this->zone->GetNumVertices(), vertexes, 3, model, isOutdoor ? outdoorLineColor : indoorLineColor ); } else { nGfxServer2::Instance()->DrawShapePrimitives( nGfxServer2::TriangleFan, this->zone->GetNumVertices() - 2, vertexes, 3, model, isOutdoor ? outdoorFillColor : indoorFillColor ); } nGfxServer2::Instance()->EndShapes(); if ( wireframe ) { server->SetTransform(nGfxServer2::Model, matrix44()); server->BeginLines(); vector3 crossLeft[2], crossRight[2]; const float fCross = 0.03f; float y = vertexes[0].y; crossLeft[0] = center + vector3 (-fCross, 0, fCross); crossLeft[1] = center + vector3 ( fCross, 0, -fCross); crossRight[0] = center + vector3 (-fCross, 0, -fCross); crossRight[1] = center + vector3 ( fCross, 0, fCross); crossLeft[0].y = crossLeft[1].y = y; crossRight[0].y = crossRight[1].y = y; vector4& color( isOutdoor ? outdoorLineColor : indoorLineColor ); server->DrawLines3d (crossLeft, 2, color); server->DrawLines3d (crossRight, 2, color); server->EndLines(); } } //------------------------------------------------------------------------------ /** DrawLinks */ void ncNavMeshNode::DrawLinks (nGfxServer2* server, bool isOutdoor, bool overlay) { vector4 color (0.f, 0.8f, 0.4f, 1.f); matrix44 theMatrix; server->SetTransform(nGfxServer2::Model, theMatrix); server->BeginLines(); vector3 lineLinks[2]; lineLinks[0]; this->GetMidpoint( lineLinks[0] ); this->UpdateDrawHeight( lineLinks[0], isOutdoor, overlay ); for ( int i=0; i<this->GetLocalLinksNumber(); i++ ) { this->GetLocalLink(i)->GetMidpoint( lineLinks[1] ); this->UpdateDrawHeight( lineLinks[1], isOutdoor, overlay ); server->DrawLines3d (lineLinks, 2, color); } server->EndLines(); } //------------------------------------------------------------------------------ /** DrawVetices */ void ncNavMeshNode::DrawVertices (nGfxServer2* server, float high) { vector4 green (0.f, 1.f, 0.f, 1.f); vector4 final (0.3f, 1.f, 0.8f, 1.f); vector4 red (1.f, 0.f, 0.f, 1.f); vector4 color, polyColor; matrix44 theMatrix; const float dotRadius = 0.01f; server->SetTransform(nGfxServer2::Model, theMatrix); const int MaxVertices( 100 ); vector3 vertexes[ MaxVertices ]; vector3 center[2]; int iVertices = this->zone->GetNumVertices(); this->GetMidpoint( center[0] ); center[0].y += high; void* p = (void*)this; size_t i = reinterpret_cast<size_t>(p); int col1 = int(i) & 0x0f; int col2 = (int(i) & 0xf0) >> 4; polyColor = vector4 (0.0f, col1/16.0f, col2/16.0f, 1.0f); for ( int j=0; j<iVertices && j < MaxVertices; j++ ) { vertexes[j] = this->zone->GetVertex(j); vertexes[j].y += high; matrix44 model1; color = j==0 ? green : j==iVertices-1 ? final : red; model1.scale (vector3(dotRadius, dotRadius, dotRadius)); model1.set_translation (vertexes[j]); server->BeginShapes(); server->DrawShape (nGfxServer2::Sphere, model1, color); server->EndShapes(); // Debug lines from the center to every single vertex of the node /*server->BeginLines(); center[1] = vertexes[j]; server->DrawLines3d (center, 2, polyColor); server->EndLines();*/ } } //------------------------------------------------------------------------------ /** DrawLinks */ nShader2* ncNavMeshNode::GetShader( bool overlay ) const { nShader2* shader( NULL ); int shaderIndex( -1 ); if ( overlay ) { shaderIndex = nSceneServer::Instance()->FindShader( "shape_overlay" ); } else { shaderIndex = nSceneServer::Instance()->FindShader( "shape_no_cull" ); } if ( shaderIndex != -1 ) { shader = nSceneServer::Instance()->GetShaderAt( shaderIndex ).GetShaderObject(); } return shader; } //------------------------------------------------------------------------------ /** UpdateDrawHeight */ void ncNavMeshNode::UpdateDrawHeight( vector3& point, bool isOutdoor, bool overlay ) const { if ( isOutdoor ) { this->UpdateHeight( &point ); } if ( !overlay ) { point.y += isOutdoor ? 0.5f : 0.1f; } } //------------------------------------------------------------------------------ /** */ vector4 ncNavMeshNode::GetIndoorBoundaryColour() const { return this->indoorBoundaryColour; } //------------------------------------------------------------------------------ /** */ void ncNavMeshNode::SetIndoorBoundaryColour(vector4 colour) { this->indoorBoundaryColour = colour; } //------------------------------------------------------------------------------ /** */ vector4 ncNavMeshNode::GetOutdoorBoundaryColour() const { return this->outdoorBoundaryColour; } //------------------------------------------------------------------------------ /** */ void ncNavMeshNode::SetOutdoorBoundaryColour(vector4 colour) { this->outdoorBoundaryColour = colour; } #endif // !NGAME //------------------------------------------------------------------------------ /** GetByteSize */ int ncNavMeshNode::GetByteSize() const { // Base data int size( ncNavNode::GetByteSize() ); // Zone size += sizeof( this->zone ); if ( zone ) { size += sizeof(polygon) + this->zone->GetNumVertices() * sizeof(vector3); } // User data size += sizeof( this->userData ); return size; } //------------------------------------------------------------------------------ /** UpdateHeight */ void ncNavMeshNode::UpdateHeight (vector3* position) const { n_assert(position); nSpatialServer* spatialServer = nSpatialServer::Instance(); n_assert(spatialServer); if ( spatialServer->GetOutdoorEntity() ) { ncTerrainGMMClass* terrainGMM = spatialServer->GetOutdoorEntity()->GetClassComponent <ncTerrainGMMClass>(); n_assert(terrainGMM); nFloatMap* heightMap = terrainGMM->GetHeightMap(); n_assert(heightMap); float height; if ( heightMap->GetHeight (position->x, position->z, height) ) { position->y = height; } } } //------------------------------------------------------------------------------ /** Get the height of the ground belonging to the given point in the navmeshnode This function returns false only when it hasn't find a ground. In a well constructed level this should never happen and this function should always return true. But desynchronization between physics and navigation worlds due to later changes may cause to have invalid navmeshnodes in the level, making this function to don't find a ground and thus returning false. */ bool ncNavMeshNode::GetGroundHeight( float x, float z, float& groundHeight ) const { // Get the point in the nearness of the ground surface vector3 nodePoint( x, 0, z ); if ( this->IsInOutdoor() ) { nNavUtils::GetHeightMap()->GetHeight( x, z, nodePoint.y ); } else { n_assert( this->zone ); nodePoint.y = this->zone->GetVertex(0).y; } // Project exactly the point to the physical ground surface return nNavUtils::GetGroundHeight( nodePoint, groundHeight ); } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 695 ] ] ]
86bd0e23eca26223dad276b2d520ea92a174621a
7eb81dd252c71766e047eaf6c0a78549b3eeee20
/trunk/src/egmg/Stencil/Helmholtz2D2.cpp
eb80dd7ce2cbe1026d729a3349d24fc4561f653a
[]
no_license
BackupTheBerlios/egmg-svn
1325afce712567c99bd7601e24c6cac44a032905
71d770fc123611de8a62d2cabf4134e783dbae49
refs/heads/master
2021-01-01T15:18:37.469550
2007-04-30T11:31:27
2007-04-30T11:31:27
40,614,587
0
0
null
null
null
null
UTF-8
C++
false
false
1,922
cpp
/** \file Helmholtz2D2.h * \author Andre Oeckerath * \brief Contains the implementation of the class Helmholtz2D2 */ #include "Helmholtz2D2.h" namespace mg { PositionArray Helmholtz2D2::initJx_() const { const int t[]={0,-1,0,1,0}; return PositionArray(t,5); } PositionArray Helmholtz2D2::initJy_() const { const int t[]={0,0,1,0,-1}; return PositionArray(t,5); } Helmholtz2D2::Helmholtz2D2( Precision ax, Precision ay, Precision c ) : jx_( initJx_() ), jy_( initJy_() ), ax_( ax ), ay_( ay ), c_( c ) {} Helmholtz2D2::~Helmholtz2D2() {} Precision Helmholtz2D2::apply( const NumericArray& u, const Position, const Index sx, const Index sy, const Index nx, const Index ny) const { return (2.0*ax_*nx*nx+2.0*ay_*ny*ny+c_)*u[sy*(nx+1)+sx] -1.0*ax_*nx*nx*u[sy*(nx+1)+sx-1] -1.0*ax_*nx*nx*u[sy*(nx+1)+sx+1] -1.0*ay_*ny*ny*u[(sy-1)*(nx+1)+sx] -1.0*ay_*ny*ny*u[(sy+1)*(nx+1)+sx]; } Precision Helmholtz2D2::getCenter( const Position, const Index, const Index, const Index nx, const Index ny) const { return 2.0*ax_*nx*nx+2.0*ay_*ny*ny+c_; } NumericArray Helmholtz2D2::getL( const Position, const Index, const Index, const Index nx, const Index ny) const { NumericArray result( 0.0, 5 ); result[0]=2.0*ax_*nx*nx+2.0*ay_*ny*ny+c_; result[1]=result[3]=-1.0*ax_*nx*nx; result[2]=result[4]=-1.0*ay_*ny*ny; return result; } PositionArray Helmholtz2D2::getJx( const Position, const Index, const Index ) const { return jx_; } PositionArray Helmholtz2D2::getJy( const Position, const Index, const Index ) const { return jy_; } Index Helmholtz2D2::size() const { return 1; } bool Helmholtz2D2::isConstant() const { return true; } }
[ "jirikraus@c8ad9165-030d-0410-b95e-c1df97c73749" ]
[ [ [ 1, 99 ] ] ]
a8138c74ce2d55f759ce9e1e040c71bf911eef0f
41c264ec05b297caa2a6e05e4476ce0576a8d7a9
/OpenScrape/DialogEditHashPoint.cpp
d00b055d04b56cda21d62cac72baf25ab8beab38
[]
no_license
seawei/openholdem
cf19a90911903d7f4d07f956756bd7e521609af3
ba408c835b71dc1a9d674eee32958b69090fb86c
refs/heads/master
2020-12-25T05:40:09.628277
2009-01-25T01:17:10
2009-01-25T01:17:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,670
cpp
// DialogEditHashPoint.cpp : implementation file // #include "stdafx.h" #include "DialogEditHashPoint.h" // CDlgEditHashPoint dialog IMPLEMENT_DYNAMIC(CDlgEditHashPoint, CDialog) CDlgEditHashPoint::CDlgEditHashPoint(CWnd* pParent /*=NULL*/) : CDialog(CDlgEditHashPoint::IDD, pParent) { __SEH_SET_EXCEPTION_HANDLER } CDlgEditHashPoint::~CDlgEditHashPoint() { } void CDlgEditHashPoint::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_TYPE, m_Type); DDX_Control(pDX, IDC_X, m_X); DDX_Control(pDX, IDC_Y, m_Y); } BEGIN_MESSAGE_MAP(CDlgEditHashPoint, CDialog) ON_BN_CLICKED(IDOK, &CDlgEditHashPoint::OnBnClickedOk) END_MESSAGE_MAP() // CDlgEditHashPoint message handlers BOOL CDlgEditHashPoint::OnInitDialog() { CDialog::OnInitDialog(); CString text; CDialog::OnInitDialog(); SetWindowText(titletext.GetString()); m_Type.AddString("Type 0"); m_Type.AddString("Type 1"); m_Type.AddString("Type 2"); m_Type.AddString("Type 3"); m_Type.SelectString(-1, type.GetString()); m_Type.SetWindowPos(NULL, 0, 0, 75, 300, SWP_NOMOVE | SWP_NOZORDER); text.Format("%d", x); m_X.SetWindowText(text.GetString()); text.Format("%d", y); m_Y.SetWindowText(text.GetString()); m_Type.SetFocus(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDlgEditHashPoint::OnBnClickedOk() { CString text; m_Type.GetWindowText(type); m_X.GetWindowText(text); x = atoi(text.GetString()); m_Y.GetWindowText(text); y = atoi(text.GetString()); OnOK(); }
[ [ [ 1, 80 ] ] ]
e5d59c483cfb38d7f6aac8282f4de03614c36c82
241c6a1683325fdae37f5cea2716e8e639dd09a4
/extension.cpp
00184ecb889edfa072fcff01e791adb514d1a6a9
[]
no_license
awstanley/rpgtools-hg-tmp
060bb8abe19512b282bb04ec433a0158623afaf8
02b50dff4d80c32f12065b18390ea71bedb130df
refs/heads/master
2020-11-24T17:43:26.561364
2011-07-17T21:40:02
2011-07-17T21:40:02
228,278,083
0
0
null
null
null
null
UTF-8
C++
false
false
24,240
cpp
/****************************************************************************** * vim: set ts=4 : ****************************************************************************** * RPGTools Extension * Copyright (C) 2011 A.W. 'Swixel' Stanley. ****************************************************************************** * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. *****************************************************************************/ #include "extension.h" // Singleton Design RPGTools g_RPGTools; SMEXT_LINK(&g_RPGTools); ICvar *icvar = NULL; IServerGameDLL *server = NULL; IServerGameEnts *gameents = NULL; IGameConfig *g_pGameConf = NULL; CGlobalVars *gpGlobals; IServerGameClients *gameclients = NULL; IServerPluginCallbacks *vsp_callbacks = NULL; IServerPluginHelpers *helpers = NULL; // Carry the late load until it's safe to do so. bool LLoad; // Version ConVars ConVar g_Version("sm_rpgtools_version", SMEXT_CONF_VERSION, FCVAR_NOTIFY|FCVAR_PRINTABLEONLY, "RPGTools SourceMod Extension Version"); ConVar g_OhGodWhy("sm_rpgtools_please_spam_my_logs", "0", FCVAR_NOTIFY|FCVAR_PRINTABLEONLY, "Print Debug Messages"); /***************************************************************************** * Do Not Need reconfiguring *****************************************************************************/ // GAAAAAAAAAAAAAAH SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, 0, bool, const char *, const char *, const char *, const char *, bool, bool); SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, 0); // Client Joins SH_DECL_HOOK2_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, edict_t *, char const *); // Client Leaves SH_DECL_HOOK1_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, edict_t *); /***************************************************************************** * Do Need reconfiguring *****************************************************************************/ // Damage related SH_DECL_MANUALHOOK1(SHook_OnTakeDamage, 0, 0, 0, int, CTakeDamageInfo &); // Health Related SH_DECL_MANUALHOOK0(SHook_GetMaxHealth, 0, 0, 0, int); // Speed Related SH_DECL_MANUALHOOK0(SHook_GetPlayerMaxSpeed, 0, 0, 0, float); // Fake Death SH_DECL_MANUALHOOK0_void(SHook_CreateRagdollEntity, 0, 0, 0); // Flash Light SH_DECL_MANUALHOOK0_void(SHook_FlashLightTurnOn, 0, 0, 0); SH_DECL_MANUALHOOK0_void(SHook_FlashLightTurnOff, 0, 0, 0); SH_DECL_MANUALHOOK0(SHook_FlashLightIsOn, 0, 0, 0, bool); // OnUpdateRemove (map change) SH_DECL_MANUALHOOK0_void(SHook_UpdateOnRemove, 0, 0, 0); /***************************************************************************** * Natives *****************************************************************************/ sp_nativeinfo_t g_ExtensionNatives[] = { // Set player statistic { "RPG_SetPlayerStat", RPG_SetPlayerStat }, { "RPG_SetPlayerStats", RPG_SetPlayerStats }, { "RPG_GetPlayerStats", RPG_GetPlayerStats }, { "RPG_ToggleFlashLight", RPG_ToggleFlashLight }, { "RPG_GetFlashLight", RPG_GetFlashLight }, { "RPG_SetFlashLight", RPG_SetFlashLight }, { "RPG_FakeDeath", RPG_FakeDeath }, // Null :3 { NULL, NULL } }; /***************************************************************************** * Fowards *****************************************************************************/ IForward *g_pFwdGetPlayerData = NULL; /***************************************************************************** * Extension Core *****************************************************************************/ bool IsPlayerValid(int iClient, CBaseEntity *&pBasePlayer) { IGamePlayer *pPlayer = playerhelpers->GetGamePlayer(iClient); if (pPlayer == NULL) return false; if (pPlayer->IsConnected() == false) return false; if (pPlayer->IsFakeClient() == true) return false; if (pPlayer->IsInGame() == false) return false; edict_t * pEdict = pPlayer->GetEdict(); if (pEdict == NULL) return false; if (pEdict->IsFree()) return false; pBasePlayer = (CBaseEntity *)pEdict->m_pNetworkable->GetBaseEntity(); if (pBasePlayer == NULL) return false; return true; // WINNAR :D } bool RPGTools::SDK_OnLoad(char *error, size_t maxlength, bool late) { Hooks = new bool[7]; char conf_error[255] = ""; Slots = new RPGChar*[33]; /* This mod's conf */ if (!gameconfs->LoadGameConfigFile("rpgtools.games", &g_pGameConf, conf_error, sizeof(conf_error))) { if (conf_error[0]) { sprintf(error, "Could not read rpgtools data file: %s", conf_error); g_pSM->LogMessage(myself, error); } return false; } int iOffset; if (!g_pGameConf->GetOffset("UpdateOnRemove", &iOffset)) { sprintf(error, "Disabling: Found no offset for 'UpdateOnRemove' (required to stop mapchange crashes)"); g_pSM->LogMessage(myself, error); return false; } else { SH_MANUALHOOK_RECONFIGURE(SHook_UpdateOnRemove, iOffset, 0, 0); } if (!g_pGameConf->GetOffset("GetPlayerMaxSpeed", &iOffset)) { sprintf(error, "Disabling Player Speed Manipulation: Found no offset for 'GetPlayerMaxSpeed'"); g_pSM->LogMessage(myself, error); Hooks[HOOK_SPEED] = false; Hooks[HOOK_SPEED] = true; } else { SH_MANUALHOOK_RECONFIGURE(SHook_GetPlayerMaxSpeed, iOffset, 0, 0); } if (!g_pGameConf->GetOffset("OnTakeDamage", &iOffset)) { sprintf(error, "Disabling Damage Manipulation: Found no offset for 'OnTakeDamage'"); g_pSM->LogMessage(myself, error); Hooks[HOOK_ONTAKEDAMAGE] = false; } else { Hooks[HOOK_ONTAKEDAMAGE] = true; SH_MANUALHOOK_RECONFIGURE(SHook_OnTakeDamage, iOffset, 0, 0); } if (!g_pGameConf->GetOffset("GetMaxHealth", &iOffset)) { sprintf(error, "Disabling Health Manipulation: Found no offset for 'GetMaxHealth'"); g_pSM->LogMessage(myself, error); Hooks[HOOK_HEALTH] = false; } else { Hooks[HOOK_HEALTH] = true; SH_MANUALHOOK_RECONFIGURE(SHook_GetMaxHealth, iOffset, 0, 0); } int iOffset2; int iOffset3; if (g_pGameConf->GetOffset("FlashLightTurnOn", &iOffset) && g_pGameConf->GetOffset("FlashLightTurnOff", &iOffset2) && g_pGameConf->GetOffset("FlashLightIsOn", &iOffset3)) { sprintf(error, "Disabling FlashLight Manipulation: Could not find offsets for 'FlashLightTurnOn', 'FlashLightTurnOff', and/or 'FlashLightIsOn'."); g_pSM->LogMessage(myself, error); Hooks[HOOK_FLASHLIGHT] = false; } else { Hooks[HOOK_FLASHLIGHT] = true; SH_MANUALHOOK_RECONFIGURE(SHook_FlashLightTurnOn, iOffset, 0, 0); SH_MANUALHOOK_RECONFIGURE(SHook_FlashLightTurnOff, iOffset2, 0, 0); SH_MANUALHOOK_RECONFIGURE(SHook_FlashLightIsOn, iOffset3, 0, 0); } if (!g_pGameConf->GetOffset("CreateRagdollEntity", &iOffset)) { sprintf(error, "Disabling FakeDeath: Found no offset for 'CreateRagdollEntity'"); g_pSM->LogMessage(myself, error); Hooks[HOOK_HEALTH] = false; } else { Hooks[HOOK_FAKEDEATH] = true; SH_MANUALHOOK_RECONFIGURE(SHook_GetMaxHealth, iOffset, 0, 0); } // Hook client join/part SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, gamedll, Hook_LevelInit, false); SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, server, Hook_LevelShutdown, false); SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientPutInServer, gameclients, Hook_ClientPutInServer, true); SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientDisconnect, gameclients, Hook_ClientLeaveServer, false); // CVar g_pCVar = icvar; ConVar_Register(0, this); // Get MaxPlayer Count int iMaxClients = playerhelpers->GetMaxClients(); // Build a vacant slot for for(int iClient = 0; iClient <= iMaxClients; iClient++) { Slots[iClient] = NULL; } // The world has stats ;) Slots[0] = new RPGChar(0,0,0,0); // Natives sharesys->AddNatives(myself, g_ExtensionNatives); sharesys->RegisterLibrary(myself, "rpgtools"); // Forwards g_pFwdGetPlayerData = forwards->CreateForward("RPG_GetPlayerData", ET_Event, 1, NULL, Param_Cell); // ConCommands if ((vsp_callbacks = g_SMAPI->GetVSPInfo(NULL)) == NULL) { g_SMAPI->AddListener(this, this); g_SMAPI->EnableVSPListener(); } // Do Late Load check if(late) { // Hook everyone in game for (int iClient = 1; iClient <= iMaxClients; iClient++) { CBaseEntity *pBasePlayer; if(!IsPlayerValid(iClient, pBasePlayer)) continue; // Register the player RegisterPlayer(pBasePlayer); } } // Notify the log g_pSM->LogMessage(myself, "RPGTools Extension Loaded."); return true; } // On All Loaded void RPGTools::SDK_OnAllLoaded() { } // When the extension is unloaded void RPGTools::SDK_OnUnload() { KillAllStats(); SH_REMOVE_HOOK(IServerGameClients, ClientPutInServer, gameclients, Hook_ClientPutInServer, true); SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, gameclients, Hook_ClientLeaveServer, false); SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, gamedll, Hook_LevelInit, false); SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, server, Hook_LevelShutdown, false); forwards->ReleaseForward(g_pFwdGetPlayerData); gameconfs->CloseGameConfigFile(g_pGameConf); g_pSM->LogMessage(myself, "RPGTools Extension Unloaded."); } // ConCommand and ConVar handlers bool RPGTools::RegisterConCommandBase(ConCommandBase *pCommand) { META_REGCVAR(pCommand); return true; } bool RPGTools::SDK_OnMetamodLoad( ISmmAPI *ismm, char *error, size_t maxlen, bool late ) { GET_V_IFACE_ANY(GetServerFactory, gameclients, IServerGameClients, INTERFACEVERSION_SERVERGAMECLIENTS); GET_V_IFACE_ANY(GetServerFactory, server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL); GET_V_IFACE_ANY(GetServerFactory, gameents, IServerGameEnts, INTERFACEVERSION_SERVERGAMEENTS); GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER); GET_V_IFACE_CURRENT(GetEngineFactory, icvar, ICvar, CVAR_INTERFACE_VERSION); GET_V_IFACE_CURRENT(GetEngineFactory, helpers, IServerPluginHelpers, INTERFACEVERSION_ISERVERPLUGINHELPERS); gpGlobals = ismm->GetCGlobals(); return true; } // Register and hook the player. void RegisterPlayer(CBaseEntity *pBasePlayer) { edict_t *pEdict = gameents->BaseEntityToEdict(pBasePlayer); int iClient = engine->IndexOfEdict(pEdict); // Setup an empty character g_RPGTools.Slots[iClient] = new RPGChar(0,0,0,0); // Forward (to load the character, if they want) cell_t cellResults = 0; cell_t cellOverrideHandle = 0; g_pFwdGetPlayerData->PushCell(iClient); g_pFwdGetPlayerData->Execute(&cellResults); // Do Hooks SH_ADD_MANUALHOOK_STATICFUNC(SHook_UpdateOnRemove, pBasePlayer, Hook_UpdateOnRemove, false); if(g_RPGTools.Hooks[HOOK_ONTAKEDAMAGE]) SH_ADD_MANUALHOOK_STATICFUNC(SHook_OnTakeDamage, pBasePlayer, Hook_OnTakeDamage, true); if(g_RPGTools.Hooks[HOOK_HEALTH]) SH_ADD_MANUALHOOK_STATICFUNC(SHook_GetMaxHealth, pBasePlayer, Hook_GetMaxHealth, false); if(g_RPGTools.Hooks[HOOK_SPEED]) SH_ADD_MANUALHOOK_STATICFUNC(SHook_GetPlayerMaxSpeed, pBasePlayer, Hook_GetPlayerMaxSpeed, false); if(g_RPGTools.Hooks[HOOK_FAKEDEATH]) SH_ADD_MANUALHOOK_STATICFUNC(SHook_CreateRagdollEntity, pBasePlayer, Hook_CreateRagdollEntity, false); if(g_RPGTools.Hooks[HOOK_FLASHLIGHT]) { SH_ADD_MANUALHOOK_STATICFUNC(SHook_FlashLightTurnOn, pBasePlayer, Hook_FlashLightTurnOn, false); SH_ADD_MANUALHOOK_STATICFUNC(SHook_FlashLightTurnOff, pBasePlayer, Hook_FlashLightTurnOff, false); SH_ADD_MANUALHOOK_STATICFUNC(SHook_FlashLightIsOn, pBasePlayer, Hook_FlashLightIsOn, false); } } // Unregister the player. void UnregisterPlayer(CBaseEntity *pBasePlayer) { edict_t *pEdict = gameents->BaseEntityToEdict(pBasePlayer); int iClient = engine->IndexOfEdict(pEdict); SH_REMOVE_MANUALHOOK_STATICFUNC(SHook_UpdateOnRemove, pBasePlayer, Hook_UpdateOnRemove, false); if(g_RPGTools.Hooks[HOOK_ONTAKEDAMAGE]) SH_REMOVE_MANUALHOOK_STATICFUNC(SHook_OnTakeDamage, pBasePlayer, Hook_OnTakeDamage, true); if(g_RPGTools.Hooks[HOOK_HEALTH]) SH_REMOVE_MANUALHOOK_STATICFUNC(SHook_GetMaxHealth, pBasePlayer, Hook_GetMaxHealth, false); if(g_RPGTools.Hooks[HOOK_SPEED]) SH_REMOVE_MANUALHOOK_STATICFUNC(SHook_GetPlayerMaxSpeed, pBasePlayer, Hook_GetPlayerMaxSpeed, false); g_RPGTools.Slots[iClient] = NULL; } /***************************************************************************** * Hooks *****************************************************************************/ void Hook_UpdateOnRemove() { CBaseEntity *pBasePlayer = META_IFACEPTR(CBaseEntity); if(IsPlayerValid(engine->IndexOfEdict(gameents->BaseEntityToEdict(pBasePlayer)), pBasePlayer)) { UnregisterPlayer(pBasePlayer); } } bool Hook_LevelInit(const char *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame,bool background) { int iMaxClients = playerhelpers->GetMaxClients(); for (int iClient = 1; iClient <= iMaxClients; iClient++) { CBaseEntity *pBasePlayer; if(!IsPlayerValid(iClient, pBasePlayer)) continue; // Register the player RegisterPlayer(pBasePlayer); } return true; } void KillAllStats() { int iMaxClients = playerhelpers->GetMaxClients(); for (int iClient = 1; iClient <= iMaxClients; iClient++) { CBaseEntity *pBasePlayer; if(!IsPlayerValid(iClient, pBasePlayer)) continue; // Register the player UnregisterPlayer(pBasePlayer); } } void Hook_LevelShutdown() { KillAllStats(); } void Hook_ClientLeaveServer(edict_t *pEntity) { CBaseEntity *baseentity = pEntity->m_pNetworkable->GetBaseEntity(); UnregisterPlayer(baseentity); } void Hook_ClientPutInServer(edict_t *pEntity, char const *playername) { if(pEntity->m_pNetworkable) { CBaseEntity *baseentity = pEntity->m_pNetworkable->GetBaseEntity(); if(!baseentity) { return; } RegisterPlayer(baseentity); } } // Damage Modification int Hook_OnTakeDamage(CTakeDamageInfo &info) { // Attack CBaseEntity *pPlayer = META_IFACEPTR(CBaseEntity); float BaseDamage = info.GetDamage(); CBaseEntity *CBE_Attacker = info.GetAttacker(); if(pPlayer) { int DefenderSlot = engine->IndexOfEdict(gameents->BaseEntityToEdict(pPlayer)); if(DefenderSlot > 0 && DefenderSlot < 33) { float DMod = g_RPGTools.Slots[DefenderSlot]->ShieldStat; if(DMod > 1.0f) { float SubFromDamage = float(BaseDamage * DMod/100.0f); info.SubtractDamage(SubFromDamage); if(g_OhGodWhy.GetBool()) { g_pSM->LogMessage(myself, "Defence (Base: %4.2f | Defence %4.2f) removes %4.2f damage", BaseDamage, DMod, SubFromDamage); } } } } if(CBE_Attacker) { int AttackerSlot = engine->IndexOfEdict(gameents->BaseEntityToEdict(CBE_Attacker)); if(AttackerSlot > 0 && AttackerSlot < 33) { float AMod = g_RPGTools.Slots[AttackerSlot]->DamageStat; if(AMod > 1.0f) { float AddToDamage = float(BaseDamage * AMod/100.0f); info.AddDamage(AddToDamage); if(g_OhGodWhy.GetBool()) { g_pSM->LogMessage(myself, "Attack (Base: %4.2f | DamageBonus %4.2f) adds %4.2f damage", BaseDamage, AMod, AddToDamage); } } } } RETURN_META_VALUE(MRES_HANDLED, 1); } int Hook_GetMaxHealth() { CBaseEntity *pPlayer = META_IFACEPTR(CBaseEntity); int PlayerSlot = engine->IndexOfEdict(gameents->BaseEntityToEdict(pPlayer)); int BaseHealth = SH_MCALL(pPlayer, SHook_GetMaxHealth)(); int PlayerHealth = g_RPGTools.Slots[PlayerSlot]->HealthStat; if(PlayerHealth > 1) { BaseHealth = PlayerHealth; } RETURN_META_VALUE(MRES_SUPERCEDE,BaseHealth); } void Hook_CreateRagdollEntity() { RETURN_META(MRES_IGNORED); } void Hook_FlashLightTurnOn() { RETURN_META(MRES_IGNORED); } void Hook_FlashLightTurnOff() { RETURN_META(MRES_IGNORED); } bool Hook_FlashLightIsOn() { // Ugly patch to stop the most idiotic error ever RETURN_META_VALUE(MRES_IGNORED, SH_MCALL(META_IFACEPTR(CBaseEntity), SHook_FlashLightIsOn)()); } float Hook_GetPlayerMaxSpeed() { CBaseEntity *pPlayer = META_IFACEPTR(CBaseEntity); int PlayerSlot = engine->IndexOfEdict(gameents->BaseEntityToEdict(pPlayer)); float BaseSpeed = SH_MCALL(pPlayer, SHook_GetPlayerMaxSpeed)(); float PlayerSpeed = g_RPGTools.Slots[PlayerSlot]->SpeedStat; if(PlayerSpeed >= 1.0f) { BaseSpeed = PlayerSpeed; } //return BaseSpeed; RETURN_META_VALUE(MRES_SUPERCEDE, BaseSpeed); } // native bool:RPG_SetPlayerStat(iClient, RPG_STAT, Float:fValue); static cell_t RPG_SetPlayerStat(IPluginContext *pContext, const cell_t *params) { if(params[0] == 3) { float Value = sp_ctof(params[3]); if(params[0] != 1) return false; int iClient = params[1]; CBaseEntity *pBasePlayer; if(!IsPlayerValid(iClient, pBasePlayer)) { pContext->ThrowNativeError("Invalid client index: %i", iClient); } if(g_RPGTools.Slots[params[1]] == NULL) { g_RPGTools.Slots[params[1]] = new RPGChar(0,0,0,0); } switch(params[1]) { case 0:g_RPGTools.Slots[params[1]]->DamageStat = Value; break; case 1:g_RPGTools.Slots[params[1]]->ShieldStat = Value; break; case 2:g_RPGTools.Slots[params[1]]->HealthStat = (int)Value; break; case 3:g_RPGTools.Slots[params[1]]->SpeedStat = Value; break; default: return 0; break; } return 1; } else { pContext->ThrowNativeError("Incorrect parameter count \n - Proper usage: \n RPG_SetPlayerStat(iClient, RPG_STAT, Float:fValue)"); } return 0; } // native bool:RPG_SetPlayerStats(iClient, Float:fDamageStat=0.0, Float:fShieldStat=0.0, iHealthStat=0, Float:fSpeedStat=0.0); static cell_t RPG_SetPlayerStats(IPluginContext *pContext, const cell_t *params) { if(params[0] == 5) { if(params[0] != 1) return false; int iClient = params[1]; CBaseEntity *pBasePlayer; if(!IsPlayerValid(iClient, pBasePlayer)) { pContext->ThrowNativeError("Invalid client index: %i", iClient); } if(g_RPGTools.Slots[params[1]] == NULL) { g_RPGTools.Slots[params[1]] = new RPGChar(0,0,0,0); } g_RPGTools.Slots[params[1]] = new RPGChar(sp_ctof(params[2]), sp_ctof(params[3]), params[4], sp_ctof(params[5])); if(g_OhGodWhy.GetBool()) g_pSM->LogMessage(myself, "RPG_SETPLAYERSTATS: %i | %4.2f | %4.2f| %i | %4.2f", params[1], g_RPGTools.Slots[params[1]]->DamageStat, g_RPGTools.Slots[params[1]]->ShieldStat, g_RPGTools.Slots[params[1]]->HealthStat, g_RPGTools.Slots[params[1]]->SpeedStat); return 1; } else { pContext->ThrowNativeError("Incorrect parameter count \n - Proper usage: \n RPG_SetPlayerStats(iClient, Float:iDamageStat, Float:iShieldStat, iHealthStat, iSpeedStat)"); } return 0; } // native bool:RPG_GetPlayerStats(iClient, Float:fDamageStat, Float:fShieldStat, iHealthStat, Float:fSpeedStat); static cell_t RPG_GetPlayerStats(IPluginContext *pContext, const cell_t *params) { if(params[0] == 5) { if(params[0] != 1) return false; int iClient = params[1]; CBaseEntity *pBasePlayer; if(!IsPlayerValid(iClient, pBasePlayer)) { pContext->ThrowNativeError("Invalid client index: %i", iClient); } if(g_RPGTools.Slots[params[1]] == NULL) { g_RPGTools.Slots[params[1]] = new RPGChar(0,0,0,0); } RPGChar *C = g_RPGTools.Slots[params[1]]; cell_t *p2; pContext->LocalToPhysAddr(params[2], &p2); *p2 = sp_ftoc(C->DamageStat); cell_t *p3; pContext->LocalToPhysAddr(params[3], &p3); *p3 = sp_ftoc(C->ShieldStat); cell_t *p4; pContext->LocalToPhysAddr(params[4], &p4); *p4 = C->HealthStat; cell_t *p5; pContext->LocalToPhysAddr(params[5], &p5); *p5 = sp_ftoc(C->SpeedStat); return 1; } else { pContext->ThrowNativeError("Incorrect number of buffers"); } return 0; } // native bool:RPG_ToggleFlashLight(iClient); static cell_t RPG_ToggleFlashLight(IPluginContext *pContext, const cell_t *params) { if(!g_RPGTools.Hooks[HOOK_FLASHLIGHT]) return false; if(params[0] != 1) return false; int iClient = params[1]; CBaseEntity *pBasePlayer; if(!IsPlayerValid(iClient, pBasePlayer)) { pContext->ThrowNativeError("Invalid client index: %i", iClient); } bool Status = SH_MCALL(pBasePlayer, SHook_FlashLightIsOn)(); if(Status) { SH_MCALL(pBasePlayer, SHook_FlashLightTurnOff)(); } else { SH_MCALL(pBasePlayer, SHook_FlashLightTurnOn)(); } bool Status2 = SH_MCALL(pBasePlayer, SHook_FlashLightIsOn)(); if(Status != Status2) { if(g_OhGodWhy.GetBool()) g_pSM->LogMessage(myself, "Flashlight toggle succeeded on %i : now set to %s", iClient, Status2 ? "true":"false"); g_RPGTools.FlashLight[iClient] = Status2; return true; } return false; } // native bool:RPG_GetFlashLight(iClient); static cell_t RPG_GetFlashLight(IPluginContext *pContext, const cell_t *params) { if(!g_RPGTools.Hooks[HOOK_FLASHLIGHT]) return false; if(params[0] != 1) return false; int iClient = params[1]; CBaseEntity *pBasePlayer; if(!IsPlayerValid(iClient, pBasePlayer)) { pContext->ThrowNativeError("Invalid client index: %i", iClient); } // Query it bool Status = SH_MCALL(pBasePlayer, SHook_FlashLightIsOn)(); if(Status != g_RPGTools.FlashLight[iClient]) { g_RPGTools.FlashLight[iClient] = Status; } return Status; } // native bool:RPG_SetFlashLight(iClient, bool:SetOn=true); static cell_t RPG_SetFlashLight(IPluginContext *pContext, const cell_t *params) { if(!g_RPGTools.Hooks[HOOK_FLASHLIGHT]) return false; if(params[0] != 2) return false; int iClient = params[1]; CBaseEntity *pBasePlayer; if(!IsPlayerValid(iClient, pBasePlayer)) { pContext->ThrowNativeError("Invalid client index: %i", iClient); } bool Status = SH_MCALL(pBasePlayer, SHook_FlashLightIsOn)(); bool OnOff = (bool)params[2]; if(Status == OnOff) return true; // Otherwise ... if(OnOff) { SH_MCALL(pBasePlayer, SHook_FlashLightTurnOn)(); } else { SH_MCALL(pBasePlayer, SHook_FlashLightTurnOff)(); } bool Status2 = SH_MCALL(pBasePlayer, SHook_FlashLightIsOn)(); if(Status != Status2) { if(g_OhGodWhy.GetBool()) g_pSM->LogMessage(myself, "Flashlight toggle succeeded on %i : now set to %s", iClient, Status2 ? "true":"false"); g_RPGTools.FlashLight[iClient] = Status2; return true; } return false; } // native bool:RPG_FakeDeath(iClient); static cell_t RPG_FakeDeath(IPluginContext *pContext, const cell_t *params) { if(!g_RPGTools.Hooks[HOOK_FAKEDEATH]) return false; if(params[0] != 1) return false; int iClient = params[1]; CBaseEntity *pBasePlayer; if(!IsPlayerValid(iClient, pBasePlayer)) { pContext->ThrowNativeError("Invalid client index: %i", iClient); } SH_MCALL(pBasePlayer, SHook_CreateRagdollEntity); return true; }
[ [ [ 1, 741 ] ] ]
724e6a1855066565a39145a4f87a90146f51c67c
c7f1dcc066955e698ab5a42acf1ed50680bf4d0b
/samples/PDLWizard/PDLWizard.cpp
958d4e60d847fa1ff121b7f969d4ac718a72ff99
[]
no_license
wjcsharp/pdl-titilima
8618082d734e5c1d051b2fab5e975ab15e8bbdd8
2bb4f618b00d2d57b509a64d792eff7d1208d380
refs/heads/master
2020-04-20T16:20:11.236062
2010-11-25T10:17:01
2010-11-25T10:17:01
32,128,071
0
1
null
null
null
null
GB18030
C++
false
false
1,586
cpp
/////////////////////////////////////////////////////////////////////////////// // 文件名: PDLWizard.cpp // 创建时间:2009-01-16 // 作者: 李马 // 版权所有:Titi Studio (?) 2001-2009 //----------------------------------------------------------------------------- // 说明: 程序入口 /////////////////////////////////////////////////////////////////////////////// #include <pdl_base.h> #include <pdl_module.h> #include "config.h" #include "PageStart.h" #include "PageApp.h" #include "PageFinish.h" int WINAPI _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nShowCmd) { LComCtlInit init(ICC_WIN95_CLASSES); LAppModule::Initialize(hInstance); ZeroMemory(&theConfig, sizeof(CONFIG)); TCHAR szIni[MAX_PATH]; GetModuleFileName(NULL, szIni, MAX_PATH); lstrcpy(_tcsrchr(szIni, _T('\\')) + 1, _T("PDLWizard.ini")); theIni.Open(szIni); CPageStart pageStart; CPageApp pageApp; CPageFinish pageFinish; LPropSheet prop; pageStart.Create(PSP_DEFAULT, _T("PDL 应用程序向导 - 起始页"), 0, NULL); pageApp.Create(PSP_DEFAULT, _T("PDL 应用程序向导 - 应用程序"), 0, NULL); pageFinish.Create(PSP_DEFAULT, _T("PDL 应用程序向导 - 完成"), 0, NULL); prop.AddPage(&pageStart); prop.AddPage(&pageApp); prop.AddPage(&pageFinish); prop.SetFlags(PSH_WIZARD); prop.DoModal(NULL, _T("PDL 应用程序向导")); LAppModule::Destroy(); theIni.Save(szIni); return 0; }
[ "titilima@89554c5a-91f9-11de-87e2-8d177609176d" ]
[ [ [ 1, 50 ] ] ]
61d1d0c23eb239e283e151f82ff65b4fee8f9ce5
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_6_036.cpp
c88319805d01f937b536e3c1bcd70ec20ef4d236
[ "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
2,353
cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2006 Hartmut Kaiser. 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) The tests included in this file were initially taken from the mcpp V2.5 preprocessor validation suite and were modified to fit into the Boost.Wave unit test requirements. The original files of the mcpp preprocessor are distributed under the license reproduced at the end of this file. =============================================================================*/ // Tests error reporting: #define syntax errors. // 18.7: Duplicate parameter names. //E t_6_036.cpp(20): error: duplicate macro parameter name: a #define math( op, a, a) op( (a), (b)) /*- * Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 47 ] ] ]
94dbc6f2c6b8268b633df2387f7a4c39bc27e76d
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/src/nvimage/openexr/src/HalfTest/testSize.cpp
c3ced5fd870078c5e00fbd47dc97c0ae73e244a8
[]
no_license
saggita/nvidia-mesh-tools
9df27d41b65b9742a9d45dc67af5f6835709f0c2
a9b7fdd808e6719be88520e14bc60d58ea57e0bd
refs/heads/master
2020-12-24T21:37:11.053752
2010-09-03T01:39:02
2010-09-03T01:39:02
56,893,300
0
1
null
null
null
null
UTF-8
C++
false
false
483
cpp
#include <testSize.h> #include "half.h" #include <iostream> #include <assert.h> #include <stddef.h> using namespace std; void testSize () { cout << "size and alignment\n"; half h[2]; int size = sizeof (half); ptrdiff_t algn = (char *)&h[1] - (char *)&h[0]; cout << "sizeof (half) = " << size << endl; cout << "alignof (half) = " << (int) algn << endl; assert (size == 2 && algn == 2); cout << "ok\n\n" << flush; }
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 27 ] ] ]
87ebfc61b5112c28db764208260c24af3c60f2a4
24adabaec8e7b0c8bb71366fea2b02e4e8b34203
/db-builder/lib/src/texturefilters/contrasttexturefilter.cpp
070fd781a8e217eace29e5098b4923ed8642e3cb
[]
no_license
weimingtom/db-verkstan
246fb8ce2890b3833a2a84f2369e8e0e5495390f
9101195975ec48f4eed33e65e33c83b2dd9ba8c0
refs/heads/master
2021-01-10T01:36:39.787220
2009-02-23T22:36:09
2009-02-23T22:36:09
43,455,399
1
0
null
null
null
null
UTF-8
C++
false
false
1,269
cpp
#include "db-util.hpp" #include "builder.hpp" #include "filters.hpp" #include "texture.hpp" Texture* TextureFilters::contrast(Texture* texture, int amount, bool inPlace) { Texture* newTexture = new Texture(); texture->lock(); newTexture->lock(); float contrast = powf((amount / 128.0f), 3.0f); for (int y = 0; y < 256; y++) { for (int x = 0; x < 256; x++) { D3DCOLOR srcColor = texture->getPixel(x, y); int r = (int)((D3DCOLOR_R(srcColor) - 128.0f) * contrast + 128.0f); int g = (int)((D3DCOLOR_G(srcColor) - 128.0f) * contrast + 128.0f); int b = (int)((D3DCOLOR_B(srcColor) - 128.0f) * contrast + 128.0f); if (r < 0) r = 0; if (r > 255) r = 255; if (g < 0) g = 0; if (g > 255) g = 255; if (b < 0) b = 0; if (b > 255) b = 255; newTexture->putPixel(x, y, D3DCOLOR_XRGB(r, g, b)); } } texture->unlock(); newTexture->unlock(); return newTexture; }
[ "olof.naessen@75511648-93a4-11dd-b566-b74dd1c53f51" ]
[ [ [ 1, 46 ] ] ]
278b16eb5cd289d7538634df44d39b95bddf7169
99d3989754840d95b316a36759097646916a15ea
/trunk/2011_09_07_to_baoxin_gpd/ferrylibs/src/ferry/imutil/core/ImageHistogram.h
5c6fa8125512f0d3e543b44662efc3809c568e4f
[]
no_license
svn2github/ferryzhouprojects
5d75b3421a9cb8065a2de424c6c45d194aeee09c
482ef1e6070c75f7b2c230617afe8a8df6936f30
refs/heads/master
2021-01-02T09:20:01.983370
2011-10-20T11:39:38
2011-10-20T11:39:38
11,786,263
1
0
null
null
null
null
UTF-8
C++
false
false
1,450
h
/************************************************************************ * Sharp Labs of America, Inc. * Copyright 2006. All rights reserved ************************************************************************ */ /*! ************************************************************************ * \file ImageHistogram.h * \brief class of Frame Histogram, four channels. * \author Jin Zhou <[email protected]> \n * ************************************************************************ */ #pragma once #include "cv.h" #include "ImageSingleChannelHistogram.h" namespace ferry { namespace imutil { namespace core { //R/G/B/V class ImageHistogram { public: ImageHistogram() {} ImageHistogram(IplImage* frame, int sampleStep = 1); ~ImageHistogram(void); void setDepth(int depth) { for (int i = 0; i < 4; i++) { histogram[i].setDepth(depth); } } public: int getNChannels() { return nChannels; } void computeShort() { for (int i = 0; i < 4; i++) { histogram[i].getShortData(); } } public: void readImage(IplImage* frame, int sampleStep = 1); int getCvMax() { return (int)pow(2.0, depth) - 1; } public: ImageSingleChannelHistogram histogram[4]; private: void clear() { for (int i = 0; i < 4; i++) { histogram[i].clear(); } } private: int nChannels; //usually 8. also allows [0, 16] int depth; }; } } }
[ "ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2" ]
[ [ [ 1, 74 ] ] ]
de68da0a366e920fef6f252334035237fc760a1b
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Graphic/Main/Buffer.h
abeb11d64e2b7e3607248543194039947e83c469
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
GB18030
C++
false
false
728
h
#ifndef _BUFFER_H_ #define _BUFFER_H_ #include <Common/Prerequisites.h> namespace Flagship { class _DLL_Export Buffer { public: Buffer(); virtual ~Buffer(); public: // 创建缓存 bool Create( DWORD dwSize ); // 拷贝数据 bool Copy( char * pBuffer, DWORD dwSize ); // 设置缓存指针 void SetPointer( void * pData ); // 获取缓存指针 void * GetPointer(); // 设置缓存大小 void SetSize( DWORD dwSize ); // 获取缓存大小 DWORD GetSize(); // 释放缓存 void Release(); protected: // 缓存 char * m_pBuffer; // 换成大小 DWORD m_dwSize; private: }; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 48 ] ] ]
db228eb995dc0acefa0683a86e0b1e68e627f325
dd007771e947dbed60fe6a80d4f325c4ed006f8c
/Application.h
678212533871d4c62a06b168093e9ea1f9af9935
[]
no_license
chenzhi/CameraGame
fccea24426ea5dacbe140b11adc949e043e84ef7
914e1a2b8bb45b729e8d55b4baebc9ba18989b55
refs/heads/master
2016-09-05T20:06:11.694787
2011-09-09T09:09:39
2011-09-09T09:09:39
2,005,632
0
0
null
null
null
null
GB18030
C++
false
false
4,022
h
// // Application.h // ogreApp // // Created by iMac on 11-6-15. // Copyright 2011年 __MyCompanyName__. All rights reserved. // #pragma once //#include "ogreConfig.h" //#include "Ogreplatform.h" #if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE #include "FileSystemLayerImpl.h" #include "ogreapp/ofxiPhoneVideoGrabber.h" #include "ogreapp/Accelerometer.h" #include <sys/types.h> #include <sys/stat.h> #endif #include "stateMachine.h" #include "UIManager.h" #include "UIImagesetManager.h" class ofxiPhoneVideoGrabber; class SdkTrayManager; class InputListen; class UIDebug; class Application :public Ogre::Singleton<Application>, public StateMachine , public UIManager { public: Application(); ~Application(); /**初始化 */ void init(); /**销毁所以物体 */ void destory(); /**暂停整个游戏 *@remark 只会暂停游戏逻辑。ui和渲染不会暂停 */ void pauseApp(); /**继续游戏*/ void continueApp(); /**初始化ogre渲染器*/ bool initOgreRender(); /**销毁所有的ogre对像*/ void destroyOgreRender(); /**初始化ogre插件,包括openles都在这里初始化*/ // bool initOgrePlugs(); /**每帧更新 @param time 单位为秒 */ void update(float time); /**初始化渲染资源*/ void initResource(); /**初始化输入设备*/ void initInputDevice(); /***/ void destroyInputDevice(); /**返回场景的的主摄像机节点*/ Ogre::SceneNode* getMainCameraNode()const {return m_pCameraNode;} /**返回主摄像*/ Ogre::Camera* getMainCamera()const{return m_pCamera;} /**返回场景管理器*/ Ogre::SceneManager* getMainSceneManager()const {return m_pSceneManager;} //*/输入事件, /**开始按下*/ void TouchBegan(int x,int y); /**手指离开*/ void TouchEnd(int x,int y); /**手指滑动*/ void TouchMove(int x,int y); /**初始化游戏目录*/ void initGamePath(); /**获取渲染窗口*/ Ogre::RenderWindow* getRenderWindows()const {return m_pRenderWindow;} //*/输入事件结束 #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 ///开始帧循环,windows平台下使用 void go(); ///window下函创建窗口函数 bool InitWindow(int width,int height); static LRESULT MsgProc(HWND hWnd, DWORD message, WPARAM wParam, LPARAM lParam); #else OgreBites::FileSystemLayerImpl* getFileSystem()const {return m_pFileSystem;} #endif protected: /**初始化函数,一般在这个函数里注册所有的状态 *在这个函数里需要手动指定当前活动状态。同时调用活动状态的begin函数 */ virtual void initState(); /**根据手机现在的方向转变ui位置*/ void transformInputCoordinate(int&x, int &y); protected: protected: /**初始化场景*/ void initScene(); Ogre::Root* m_pRoot; // Ogre::StaticPluginLoader mStaticPluginLoader; Ogre::RenderWindow* m_pRenderWindow; Ogre::Viewport* m_pViewPort; Ogre::SceneNode* m_pCameraNode; Ogre::Camera* m_pCamera; Ogre::SceneManager* m_pSceneManager; #if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE OgreBites::FileSystemLayerImpl* m_pFileSystem; #else OGRE_PLATFORM ==OGRE_PLATFORM_WIN32 HWND mHwnd; HINSTANCE mInstance; #endif InputListen* m_pInputListen; UIDebug* m_pDebugPanel;///debug面板 bool m_Pause;///是否暂停 UIImagesetManager* m_pImagesetMrg; };
[ "chenzhi@aee8fb6d-90e1-2f42-9ce8-abdac5710353" ]
[ [ [ 1, 223 ] ] ]
383040d4f34ee373d0d64d9d3bcfb9257f2c71c4
4891542ea31c89c0ab2377428e92cc72bd1d078f
/Arcanoid/Arcanoid/Animation.cpp
8095fa1886e914ee59d224f23c305be86fbe3a38
[]
no_license
koutsop/arcanoid
aa32c46c407955a06c6d4efe34748e50c472eea8
5bfef14317e35751fa386d841f0f5fa2b8757fb4
refs/heads/master
2021-01-18T14:11:00.321215
2008-07-17T21:50:36
2008-07-17T21:50:36
33,115,792
0
0
null
null
null
null
UTF-8
C++
false
false
51
cpp
/* * author: koutsop */ #include "Animation.h"
[ "apixkernel@5c4dd20e-9542-0410-abe3-ad2d610f3ba4" ]
[ [ [ 1, 4 ] ] ]
7a62fa5ef1539d2f3f4eb120011b8c2835aba9f3
96e96a73920734376fd5c90eb8979509a2da25c0
/C3DE/PerVertexLighting.h
821e5e5629651d1c9a24ad0460b1da31265bb1fe
[]
no_license
lianlab/c3de
9be416cfbf44f106e2393f60a32c1bcd22aa852d
a2a6625549552806562901a9fdc083c2cacc19de
refs/heads/master
2020-04-29T18:07:16.973449
2009-11-15T10:49:36
2009-11-15T10:49:36
32,124,547
0
0
null
null
null
null
UTF-8
C++
false
false
760
h
#ifndef PER_VERTEX_LIGHTING_H #define PER_VERTEX_LIGHTING_H #include "FX.h" class PerVertexLighting : public FX { public: PerVertexLighting(ID3DXEffect * effect); ~PerVertexLighting(); void SetObjectMaterials(D3DXCOLOR ambientMaterial, D3DXCOLOR diffuseMaterial, D3DXCOLOR specularMaterial, float specularPower); void SetObjectTexture(IDirect3DTexture9 *texture); void SetAlpha(float alpha); void ResetHandlers(); protected: D3DXHANDLE m_shaderObjectAmbientMaterial;//gAmbientMtrl D3DXHANDLE m_shaderObjectDiffuseMaterial;//gDiffuseMtrl D3DXHANDLE m_shaderObjectSpecularMaterial;//gSpecMtrl D3DXHANDLE m_shaderSpecularLightPower;//gSpecPower D3DXHANDLE m_shaderAlpha;//gSpecPower D3DXHANDLE m_hTex; }; #endif
[ "caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158" ]
[ [ [ 1, 27 ] ] ]
3a5e833b88afff32affb07dfb9f1a0df3f0d2c44
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Scene Estimator 2/PosteriorPoseSolution.cpp
04311adc0b13b9a498d00d8ecaa5f7d665fd3829
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,673
cpp
#include "PosteriorPoseSolution.h" #ifdef __cplusplus_cli #pragma unmanaged #endif PosteriorPoseSolution::PosteriorPoseSolution(void) { /* Default constructor for posterior pose solution object INPUTS: none. OUTPUTS: none. */ int i; int j; //initialize the posterior pose solution lock InitializeCriticalSection(&mPPlock); EnterCriticalSection(&mPPlock); //mark the solution as being invalid mIsValid = false; //initialize all the variables for the posterior pose solution mPPTime = 0.0; mEastMMSE = 0.0; mNorthMMSE = 0.0; mHeadingMMSE = 0.0; mGPSBiasEastMMSE = 0.0; mGPSBiasNorthMMSE = 0.0; for (i = 0; i < PF_NUMSTATES; i++) { for (j = 0; j < PF_NUMSTATES; j++) { mCovMMSE[midx(i, j, PF_NUMSTATES)] = 0.0; } } mRoadLocation = NULL; LeaveCriticalSection(&mPPlock); return; } PosteriorPoseSolution::~PosteriorPoseSolution(void) { /* Destructor for posterior pose solution object INPUTS: none. OUTPUTS: none. */ EnterCriticalSection(&mPPlock); mIsValid = false; //delete the posterior pose solution lock DeleteCriticalSection(&mPPlock); return; } bool PosteriorPoseSolution::IsValid(void) { /* Accessor function for mIsValid, the validity variable INPUTS: none. OUTPUTS: rIsValid - returns mIsValid. */ bool rIsValid; EnterCriticalSection(&mPPlock); rIsValid = mIsValid; LeaveCriticalSection(&mPPlock); return rIsValid; } void PosteriorPoseSolution::SetPosteriorPoseSolution(double iPPTime, double iEastMMSE, double iNorthMMSE, double iHeadingMMSE, double iGPSBiasEastMMSE, double iGPSBiasNorthMMSE, double iCovMMSE[PF_NUMSTATES*PF_NUMSTATES], RoadPartition* iRoadLocation) { /* Sets the posterior pose solution with input values. INPUTS: iPPtime - current posterior pose time iEastMMSE, iNorthMMSE, iHeadingMMSE - MMSE position estimate iGPSBiasEastMMSE, iGPSBiasNorthMMSE - MMSE gps bias estimate iCovMMSE - MMSE covariance (MSE) matrix OUTPUTS: none. */ int i; int j; //acquire the posterior pose lock EnterCriticalSection(&mPPlock); if (iPPTime > mPPTime || mIsValid == false) { //copy over all the variables mPPTime = iPPTime; mEastMMSE = iEastMMSE; mNorthMMSE = iNorthMMSE; mHeadingMMSE = iHeadingMMSE; mGPSBiasEastMMSE = iGPSBiasEastMMSE; mGPSBiasNorthMMSE = iGPSBiasNorthMMSE; for (i = 0; i < PF_NUMSTATES; i++) { for (j = 0; j < PF_NUMSTATES; j++) { mCovMMSE[midx(i, j, PF_NUMSTATES)] = iCovMMSE[midx(i, j, PF_NUMSTATES)]; } } mRoadLocation = iRoadLocation; //solution becomes valid once information is stored in it mIsValid = true; } else { printf("Warning: SetPosteriorPoseSolution called with an old solution.\n"); } LeaveCriticalSection(&mPPlock); return; } bool PosteriorPoseSolution::GetPosteriorPosePosition(double& oEastMMSE, double& oNorthMMSE, double& oHeadingMMSE) { /* Retrieves the posterior pose position solution. INPUTS: oEastMMSE, oNorthMMSE, oHeadingMMSE - will contain the ppose position estimate on a successful return. OUTPUTS: rSuccess - true if successful, false otherwise. If true, input variables are populated with the posterior pose solution. If false, they are not touched. */ bool rSuccess = false; EnterCriticalSection(&mPPlock); if (mIsValid == true) { //retrieve the ppose position solution oEastMMSE = mEastMMSE; oNorthMMSE = mNorthMMSE; oHeadingMMSE = mHeadingMMSE; rSuccess = true; } LeaveCriticalSection(&mPPlock); return rSuccess; }
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 180 ] ] ]
e22947cec0bcb84da6e8f7ad4e55954f6338e07c
e1f7c2f6dd66916fe5b562d9dd4c0a5925197ec4
/Engine/Test skybox/src/Game.cpp
2c78e9aed0b0235b82e17b4e788ac892e86aff9f
[]
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
4,225
cpp
#include "Game.h" #include "AgSystem.h" #include "AGResource.h" #include "AGWindowManager.h" #include "AGResourceManager.h" #include "AGInputManager.h" #include "AGSceneManager.h" #include "AGRenderer.h" #include "AG3DDefaultMaterial.h" #include "AGPRTLightProbe.h" #include "NormalMapMaterial.h" #include "SkyboxMaterial.h" #include "PRTLightMaterial.h" #include "AGTypesDX9.h" #include <iostream> using namespace std; #include "MouseInputs.h" //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------ void Game::InitEngine() { cout << "Game Init Engine" << endl; AGWindowManager::GetSingleton()->SetSize(1280, 1024); } //------------------------------------------------------------------------------------------------------------------------------ void Game::Init() { _mScene = AGSceneManager::GetSingleton()->GetNew3DScene(); AG3DGraphicEntity* pGraphicEntity; // Skybox SkyboxMaterial* pSkyMaterial = new SkyboxMaterial(); //pSkyMaterial->SetCubeMapFromFile(".\\Data\\rnl_cross.dds"); pSkyMaterial->SetCubeMapFromFile(".\\Data\\galileo_cross.dds"); //pSkyMaterial->SetCubeMapFromFile(".\\Data\\uffizi_cross.dds"); AGPRTLightProbe* pLightProbe = _mScene->GetNewPRTSkybox(); pLightProbe->mScale = AGVector3f(1000.f, 1000.f, 1000.f); pLightProbe->SetMaterial(pSkyMaterial); float** SHCoef = pLightProbe->ComputeSHFromCubeMap(pSkyMaterial->GetCubeMap()); pLightProbe->Update(); // Object pGraphicEntity = _mScene->GetNewGraphicEntity(); pGraphicEntity->SetMesh(".\\Data\\bunny.x"); PRTLightMaterial* pPRTMaterial = new PRTLightMaterial(); pGraphicEntity->SetMaterial(pPRTMaterial); pPRTMaterial->SetDiffuse(".\\Data\\marble.dds"); pPRTMaterial->SetNormal (".\\Data\\marble_normal.dds"); pPRTMaterial->SetSHCoefFromCubeMap(SHCoef); pPRTMaterial->SetYlmCoef0(pLightProbe->GetYlmCoeff0()); pPRTMaterial->SetYlmCoef4(pLightProbe->GetYlmCoeff4()); pPRTMaterial->SetYlmCoef8(pLightProbe->GetYlmCoeff8()); pPRTMaterial->SetYlmCoef12(pLightProbe->GetYlmCoeff12()); pPRTMaterial->SetTransmitColor(AGVector3f(1.0f, 1.0f, 1.0f)); pPRTMaterial->SetLightContribution(2.0f); pPRTMaterial->SetEnvironmentContribution(0.3f); // Light AGSpotLight* pSpotLight = _mScene->GetNewSpotLight(); pSpotLight->mPosition = AGVector3f(0.f, 300.f, 0.f); pSpotLight->SetDiffuse (0.7f, 0.7f, 0.7f); pSpotLight->SetSpecular(1.0f, 1.0f, 1.0f); pSpotLight->mDirection = AGVector3f(-0.7f, 0.5f, 0.3f); pSpotLight->mInHalfAngle = AGPi / 4.f; pSpotLight->mOutHalfAngle = AGPi / 3.f; _mCamera = new AG3DCamera (); _mCamera->mFOV = AGDegToRad (45.f); _mCamera->mRatio = 1.f; _mCamera->mZNear = 1.f; _mCamera->mZFar = 1000.f; _mCamera->mPosition = AGVector3f(0.f, 0.f, -10.f); _mMouseInputsId = AGInputManager::GetSingleton()->AddInputs(new MouseInputs()); AGRenderer::GetSingleton()->mCamera.SetProjParams(AGDegToRad(45.f), 1280.f / 1024.f, 0.1f, 100000.f); D3DXVECTOR3 Eye (0.0f, 0.0f, -70.0f); D3DXVECTOR3 LookAt (0.0f, 0.0f, 0.0f); AGRenderer::GetSingleton()->mCamera.SetViewParams(&Eye, &LookAt); } //------------------------------------------------------------------------------------------------------------------------------ void Game::Destroy() { cout << "Game Destroy" << endl; SAFE_DELETE(_mCamera); } //------------------------------------------------------------------------------------------------------------------------------ void Game::Update() { AGVector2s lMousePosition = MouseInputs::Get(_mMouseInputsId)->GetPosition(); //AGDebugPrint("Mouse position : %i; %i", lMousePosition.x, lMousePosition.y); /* if (false) { D3DXVECTOR3* Vector; Vector = (D3DXVECTOR3*)(AGRenderer::GetSingleton()->mCamera.GetEyePt()); AGDebugPrint("Eye = %f, %f, %f", Vector->x, Vector->y, Vector->z); Vector = (D3DXVECTOR3*)(AGRenderer::GetSingleton()->mCamera.GetLookAtPt()); AGDebugPrint("Look At = %f, %f, %f", Vector->x, Vector->y, Vector->z); } */ }
[ "germain.mazac@fe70d4ac-e33c-11de-8d18-5b59c22968bc" ]
[ [ [ 1, 118 ] ] ]
cd42367632668e788114bbbc1a9a3a5dbf2b9bac
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Visualize/hkProcessRegisterUtil.h
ec444d848c9b1bf5d4b47dd7849b3d408f86add4
[]
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,576
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_VISUALIZE_PROCESS_REGISTER_UTIL_H #define HK_VISUALIZE_PROCESS_REGISTER_UTIL_H /// A helper class that registers all of the processes (viewers) in the system with the hkProcessFactory. class hkProcessRegisterUtil { public: /// Registers all viewers with the hkProcessFactory static void HK_CALL registerAllCommonProcesses(); }; #endif // HK_VISUALIZE_PROCESS_REGISTER_UTIL_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, 35 ] ] ]
01b44489384d8ec112097ed4dbbdc72d7458e494
009dd29ba75c9ee64ef6d6ba0e2d313f3f709bdd
/Android/MV_N1/MV_21/jni/encodervideo.h
fe3aba65c35c4a4a5dbb9f26c6df22963e0fd97d
[]
no_license
AnthonyNystrom/MobiVU
c849857784c09c73b9ee11a49f554b70523e8739
b6b8dab96ae8005e132092dde4792cb363e732a2
refs/heads/master
2021-01-10T19:36:50.695911
2010-10-25T03:39:25
2010-10-25T03:39:25
1,015,426
3
3
null
null
null
null
UTF-8
C++
false
false
1,056
h
#ifndef _ENCODER #define _ENCODER #include <jni.h> #include <include/pvm4vencoder.h> #include "include/cvei.h" //#include "include/ccyuv420semitoyuv420.h" #define BUFFER_ENCODE_SIZE_VIDEO 100000 class CEncoderVideo : MPVCVEIObserver { public: CEncoderVideo(); ~CEncoderVideo(); int Init(JNIEnv* env, int iWidth, int iHeight, int iBitRate); int GetSizeBufferEncoded(){ return m_iSizeEncoded; } int EncodeVideo(JNIEnv* env, jbyteArray iData, int iTimeStamp); void Release(JNIEnv* env); jbyteArray m_byEncodedVideo; jbyteArray m_byYUV420; private: void HandlePVCVEIEvent(uint32 aId, uint32 aEvent, uint32 aParam1 = 0){} jbyte *m_pbyEncodedVideo; jbyte *m_pbyYUV420; int m_iSizeEncoded; CPVM4VEncoder *m_pvEncVid; TPVVideoInputFormat m_inForm; TPVVideoEncodeParam m_enParam; TPVVideoInputData m_inData; TPVVideoOutputData m_outData; //CCYUV420SEMItoYUV420 *_pCC; FILE* _fplog; int _iW, _iH, _iSizeYUV, _ioutYsize; uint16 *_outcb, *_outcr; uint32 *_outy; void Semi2Planar(uint32 *inyuv_4); }; #endif
[ [ [ 1, 39 ] ] ]
e3d328ca91367ba04eaac495b7ebf23c030d8c5b
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/event_signal.inl
10f3804a3db63f3b4d8926934cefbb6fc135c11e
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
1,336
inl
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // #ifndef AOSLCPP_AOSL__EVENT_SIGNAL_INL #define AOSLCPP_AOSL__EVENT_SIGNAL_INL // Begin prologue. // // // End prologue. #include "aosl/event_signal_base.inl" #include "aosl/signal_source.hpp" #include "aosl/signal_source.inl" namespace aosl { // Event_signal // inline const Event_signal::SourceType& Event_signal:: source () const { return this->source_.get (); } inline Event_signal::SourceType& Event_signal:: source () { return this->source_.get (); } inline void Event_signal:: source (const SourceType& x) { this->source_.set (x); } inline void Event_signal:: source (::std::auto_ptr< SourceType > x) { this->source_.set (x); } inline ::std::auto_ptr< Event_signal::SourceType > Event_signal:: detach_source () { return this->source_.detach (); } } // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__EVENT_SIGNAL_INL
[ "klaim@localhost" ]
[ [ [ 1, 69 ] ] ]
49e620e7d3992eb67a9ab1ad634f3ffac7fcc843
252e638cde99ab2aa84922a2e230511f8f0c84be
/toollib/src/TripTourMoveDialogForm.cpp
f2cf6b6f9e158cef03be81b0bde1786ece33dbfc
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
916
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "StdTool.h" #include "TripTourMoveDialogForm.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "VStringStorage" #pragma link "ShortTimePicker" #pragma resource "*.dfm" TTourTripTourMoveDialogForm *TourTripTourMoveDialogForm; //--------------------------------------------------------------------------- __fastcall TTourTripTourMoveDialogForm::TTourTripTourMoveDialogForm(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TTourTripTourMoveDialogForm::FormClose(TObject *Sender, TCloseAction &Action) { Action = caHide; } //---------------------------------------------------------------------------
[ [ [ 1, 28 ] ] ]
316cd84a043126fff6dd0ae91072a2bafcc0bc95
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/WayFinder/symbian-r6/GuideContainer.cpp
5bfa109f4a5fecb97558d1dbb4a8164678477f77
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,167
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // INCLUDE FILES #include <eiklabel.h> // for labels #include <f32file.h> #include <aknviewappui.h> #include <akntabgrp.h> #include <aknnavide.h> #include <msvapi.h> #include <arch.h> #include "RouteEnums.h" #include "TimeOutNotify.h" #include "GuiProt/GuiProtEnums.h" #include "WayFinderAppUi.h" #include "RsgInclude.h" #include "wficons.mbg" #include "wayfinder.hrh" #include "GuideContainer.h" #include "GuidePicture.h" #include "GuideProgressBar.h" #include "GuideView.h" #include "WFTextUtil.h" #include "memlog.h" #include "DistancePrintingPolicy.h" #include "ImageHandler.h" #include "WFLayoutUtils.h" #include "RectTools.h" #define S60V2_SCREEN_WIDTH 176 #define S60V2_SCREEN_HEIGHT 208 #define IMAGE_PADDING 2 #define NEXTSTREET_LABEL_POS TPoint( 10, 5) #define GUIDE_PICTURE_POS TPoint( 10, 20) #define EXIT_PICTURE_POS TPoint( 47, 61) #define CURRSTREET_LABEL_POS TPoint( 10,128) #define PROGRESS_BAR_POS TPoint(125, 20) #define DISTANCE_LABEL_POS TPoint(120,110) #define NEXT_TURN_PICTURE_POS TPoint( 84, 22) #define DETOUR_PICTURE_POS TPoint( 12, 94) #define SPEEDCAM_PICTURE_POS TPoint( 84, 94) #define NEXT_STREET_LABEL_X_LS 0.1 #define NEXT_STREET_LABEL_Y_LS 0.0 #define NEXT_STREET_LABEL_X_PR 0.06 #define NEXT_STREET_LABEL_Y_PR 0.03 #define CURR_STREET_LABEL_X_LS 0.1 #define CURR_STREET_LABEL_Y_LS 0.85 #define CURR_STREET_LABEL_X_PR 0.06 #define CURR_STREET_LABEL_Y_PR 0.89 #define DIST_STREET_LABEL_X_LS 0.68 #define DIST_STREET_LABEL_Y_LS 0.70 #define DIST_STREET_LABEL_X_PR 0.68 #define DIST_STREET_LABEL_Y_PR 0.76 // Enumarations enum TControls { ENextStreetLabel, EGuidePicture, EExitPicture, ECurrStreetLabel, EDistanceLabel, EProgressBar, ENextTurnPicture, EDetourPicture, ESpeedCamPicture, ENumberControls }; // ================= MEMBER FUNCTIONS ======================= // --------------------------------------------------------- // CGuideContainer::ConstructL(const TRect& aRect) // EPOC two phased constructor // --------------------------------------------------------- // void CGuideContainer::ConstructL( CWayFinderAppUi* appUi, const TRect& aRect, CGuideView* aView ) { iAppUI = appUi; iView = aView; CreateWindowL(); iNextStreetLabel = new (ELeave) CEikLabel; LOGNEW(iNextStreetLabel, CEikLabel); iNextStreetLabel->SetContainerWindowL( *this ); iNextStreetLabel->SetBufferReserveLengthL( KBuf256Length ); iNextStreetLabel->SetTextL( _L("") ); iCurrStreetLabel = new (ELeave) CEikLabel; LOGNEW(iCurrStreetLabel, CEikLabel); iCurrStreetLabel->SetContainerWindowL( *this ); iCurrStreetLabel->SetBufferReserveLengthL( KBuf256Length ); iCurrStreetLabel->SetTextL( _L("") ); iDistanceLabel = new (ELeave) CEikLabel; LOGNEW(iDistanceLabel, CEikLabel); iDistanceLabel->SetContainerWindowL( *this ); iDistanceLabel->SetTextL( _L(" ") ); #ifdef NAV2_CLIENT_SERIES60_V3 if (WFLayoutUtils::LandscapeMode()) { CalculateLandscapeLayout(); } else { CalculatePortraitLayout(); } #else // FIXME hfasth, use CImageHandler here to! Then we can migrate // v2 and v3. iGuidePicture = new (ELeave) CGuidePicture( iLog ); LOGNEW(iGuidePicture, CGuidePicture); iGuidePicture->ConstructL( TRect( GUIDE_PICTURE_POS, TSize( 100, 100 ) ), this ); iProgressBar = CGuideProgressBar::NewL(*this, TRect(PROGRESS_BAR_POS, TSize(40, 90)), iView->GetMbmName(), EMbmWficonsGpb_triangle, EMbmWficonsGpb_triangle_active, EMbmWficonsGpb_triangle_mask, EMbmWficonsGpb_rect, EMbmWficonsGpb_rect_active, EMbmWficonsGpb_rect_mask); iNextTurnPicture = new (ELeave) CGuidePicture( iLog ); LOGNEW(iNextTurnPicture, CGuidePicture); iNextTurnPicture->ConstructL( TRect( NEXT_TURN_PICTURE_POS, TSize( 24, 24 ) ), this ); iDetourPicture = new (ELeave) CGuidePicture( iLog ); LOGNEW(iDetourPicture, CGuidePicture); iDetourPicture->ConstructL( TRect( DETOUR_PICTURE_POS, TSize( 24, 24 ) ), this ); iDetourPicture->OpenBitmapFromMbm( iView->GetMbmName(), EMbmWficonsSmall_detour ); iDetourPicture->SetShow(EFalse); iSpeedCamPicture = new (ELeave) CGuidePicture( iLog ); LOGNEW(iSpeedCamPicture, CGuidePicture); iSpeedCamPicture->ConstructL( TRect( SPEEDCAM_PICTURE_POS, TSize( 24, 24 ) ), this ); iSpeedCamPicture->OpenBitmapFromMbm( iView->GetMbmName(), EMbmWficonsSmall_speedcam ); iSpeedCamPicture->SetShow(EFalse); iExitPicture = new (ELeave) CGuidePicture( iLog ); LOGNEW(iExitPicture, CGuidePicture); iExitPicture->ConstructL( TRect( EXIT_PICTURE_POS, TSize( 26, 16 ) ), this ); iExitPicture->SetShow(EFalse); #endif iAppUI->GetBackgroundColor(iR, iG, iB); SetRect(aRect); ActivateL(); } // Destructor CGuideContainer::~CGuideContainer() { LOGDEL(iNextStreetLabel); delete iNextStreetLabel; iNextStreetLabel = NULL; LOGDEL(iGuidePicture); delete iGuidePicture; iGuidePicture = NULL; LOGDEL(iCurrStreetLabel); delete iCurrStreetLabel; iCurrStreetLabel = NULL; LOGDEL(iDistanceLabel); delete iDistanceLabel; iDistanceLabel = NULL; LOGDEL(iProgressBar); delete iProgressBar; iProgressBar = NULL; LOGDEL(iNextTurnPicture); delete iNextTurnPicture; iNextTurnPicture = NULL; LOGDEL(iDetourPicture); delete iDetourPicture; iDetourPicture = NULL; LOGDEL(iSpeedCamPicture); delete iSpeedCamPicture; iSpeedCamPicture = NULL; LOGDEL(iExitPicture); delete iExitPicture; iExitPicture = NULL; } void CGuideContainer::SetGuidePictureL( TInt aMbmIndex ) { if( aMbmIndex >= 0 ){ iGuidePicture->SetShow( ETrue ); iGuidePicture->SetClear( EFalse ); #ifdef NAV2_CLIENT_SERIES60_V3 TRect oldRect = iGuidePicture->Rect(); iGuidePicture->CreateIconL(iView->GetMbmName(), aMbmIndex, EMbmWficonsKeep_left_mask, EAspectRatioPreservedAndUnusedSpaceRemoved); //iGuidePicture->NightFilter(iAppUI->IsNightMode()); #else iGuidePicture->OpenBitmapFromMbm( iView->GetMbmName(), aMbmIndex ); iGuidePicture->OpenBitmapMaskFromMbm( iView->GetMbmName(), EMbmWficonsTurn_mask ); #endif if (iLayoutChanged) { // If a layout switch has been done then we can assume that // the size has changed. If the size has changed there is a // possibility that the aspect ratio of the screen has changed. // Since the image rect of the guide picture is being scaled we // need to be sure that no left overs from the previous image // rect is left on the screen. if (oldRect.Width() < iGuidePicture->Rect().Width()) { // If the new width is larger than the old one, use the new // height when repainting the image. oldRect.SetWidth(iGuidePicture->Rect().Width()); } if (oldRect.Height() < iGuidePicture->Rect().Height()) { // If the new height is larger than the old one, use the new // height when repainting the image. oldRect.SetHeight(iGuidePicture->Rect().Height()); } iLayoutChanged = EFalse; Window().Invalidate(oldRect); } else { Window().Invalidate(iGuidePicture->Rect()); } } else { iGuidePicture->SetShow( EFalse ); Window().Invalidate(iGuidePicture->Rect()); } } void CGuideContainer::SetNextTurnPictureL( TInt aMbmIndex , TInt aMbmMaskIndex ) { if( aMbmIndex >= 0 ){ SetImagePos(iNextTurnPicture, iGuidePicture->GetRect(), &TopRight, -iImagePaddingX, iImagePaddingY); iNextTurnPicture->SetShow( ETrue ); iNextTurnPicture->SetClear( EFalse ); #ifdef NAV2_CLIENT_SERIES60_V3 iNextTurnPicture->CreateIconL(iView->GetMbmName(), aMbmIndex, aMbmMaskIndex//, /*EAspectRatioPreservedAndUnusedSpaceRemoved*/); //iNextTurnPicture->NightFilter(iAppUI->IsNightMode()); #else iNextTurnPicture->OpenBitmapFromMbm( iView->GetMbmName(), aMbmIndex ); iNextTurnPicture->OpenBitmapMaskFromMbm( iView->GetMbmName(), aMbmMaskIndex ); #endif Window().Invalidate(iNextTurnPicture->Rect()); } else{ iNextTurnPicture->SetShow( EFalse ); Window().Invalidate(iNextTurnPicture->Rect()); } } void CGuideContainer::SetDetourPicture(TInt on) { SetImagePos(iDetourPicture, iGuidePicture->GetRect(), &LowerRight, iImagePaddingX, -iImagePaddingY); iDetourPicture->SetShow(on == 1); Window().Invalidate(iDetourPicture->Rect()); } void CGuideContainer::SetSpeedCamPicture(TInt on) { SetImagePos(iSpeedCamPicture, iGuidePicture->GetRect(), &LowerRight, -iImagePaddingX, -iImagePaddingY); iSpeedCamPicture->SetShow(on == 1); Window().Invalidate(iSpeedCamPicture->Rect()); } void CGuideContainer::SetExitL( TInt aMbmIndex, TInt aMbmMaskIndex ) { if( aMbmIndex >= 0 ){ iExitPicture->SetShow( ETrue ); #ifdef NAV2_CLIENT_SERIES60_V3 iExitPicture->CreateIconL(iView->GetMbmName(), aMbmIndex, aMbmMaskIndex, EAspectRatioPreservedAndUnusedSpaceRemoved, ETrue); //iExitPicture->NightFilter(iAppUI->IsNightMode()); #else aMbmMaskIndex = aMbmMaskIndex; iExitPicture->OpenBitmapFromMbm( iView->GetMbmName(), aMbmIndex ); #endif iExitPicture->SetImageRect(Center(iGuidePicture->GetRect(), TRect(TPoint(), iExitPicture->GetSize()))); Window().Invalidate(iExitPicture->Rect()); } else{ iExitPicture->SetShow( EFalse ); Window().Invalidate(iExitPicture->Rect()); } } void CGuideContainer::RefreshPictures() { // Refreshes all the positions of the images, it // first recalcs the size of the next turn picture since // when changed layout this image will have different // size as it had before. Since all the other images (except // the progress bar) is positioned within next turn pictures // rect, the will be positioned wrong if there positions wont // be based on a correct rect. SetGuidePictureL(iView->GetCurrentTurnPicture()); if (iNextTurnPicture && iNextTurnPicture->GetShow()) { SetImagePos(iNextTurnPicture, iGuidePicture->GetRect(), &TopRight, -iImagePaddingX, iImagePaddingY); } if (iSpeedCamPicture && iSpeedCamPicture->GetShow()) { SetImagePos(iSpeedCamPicture, iGuidePicture->GetRect(), &LowerRight, -iImagePaddingX, -iImagePaddingY); } if (iExitPicture && iExitPicture->GetShow()) { iExitPicture->SetImageRect(Center(iGuidePicture->GetRect(), TRect(TPoint(), iExitPicture->GetSize()))); } } void CGuideContainer::SetDistanceL( TUint aDistance ) { TBuf<KBuf32Length> distance; TBuf<KBuf32Length> temp; isab::DistancePrintingPolicy::DistanceMode mode = isab::DistancePrintingPolicy::DistanceMode(iView->GetDistanceMode()); char* tmp2 = isab::DistancePrintingPolicy::convertDistance(aDistance, mode, isab::DistancePrintingPolicy::Round); TInt foo = 0; distance.Copy(_L("")); if (tmp2) { WFTextUtil::char2TDes(temp, tmp2); foo = strlen(tmp2)/2; delete[] tmp2; } else { distance.Copy(_L(" ")); foo = 4; } while (foo < 4) { distance.Append(_L(" ")); foo++; } distance.Append( temp ); distance.Append( _L(" ")); if (*(iDistanceLabel->Text()) != distance) { iDistanceLabel->SetTextL( distance ); #ifdef NAV2_CLIENT_SERIES60_V3 if (WFLayoutUtils::LandscapeMode()) { SetLabelExtent(iDistanceLabel, DIST_STREET_LABEL_X_LS, DIST_STREET_LABEL_Y_LS); } else { SetLabelExtent(iDistanceLabel, DISTANCE_LABEL_POS); } #else iDistanceLabel->SetExtent( DISTANCE_LABEL_POS, iDistanceLabel->MinimumSize() ); #endif iDistanceLabel->DrawDeferred(); } iProgressBar->SetDistance( aDistance ); } void CGuideContainer::SetStreetsL( TDesC &aCurrName, TDesC &aNextName ) { if (iCurrStreetLabel) { iCurrStreetLabel->SetTextL( aCurrName ); if (WFLayoutUtils::LandscapeMode()) { SetLabelExtent(iCurrStreetLabel, CURR_STREET_LABEL_X_LS, CURR_STREET_LABEL_Y_LS, ETrue); } else { SetLabelExtent(iCurrStreetLabel, CURRSTREET_LABEL_POS, ETrue); } } if (iNextStreetLabel) { iNextStreetLabel->SetTextL( aNextName ); if (WFLayoutUtils::LandscapeMode()) { SetLabelExtent(iNextStreetLabel, NEXT_STREET_LABEL_X_LS, NEXT_STREET_LABEL_Y_LS, ETrue); } else { SetLabelExtent(iNextStreetLabel, NEXTSTREET_LABEL_POS, ETrue); } } } void CGuideContainer::GetRoundedDistance( TUint aDistance, TUint &aNewDistance ) { aNewDistance = aDistance; TInt distDif; if( aDistance > 0 && aDistance > 50 ){ if( aDistance < 200 ){ distDif = aDistance%5; if( distDif < 3 ){ aNewDistance -= distDif; } else{ distDif = 5-distDif; aNewDistance += distDif; } } else if( aDistance < 1000 ){ distDif = aDistance%10; if( distDif < 5 ){ aNewDistance -= distDif; } else{ distDif = 10-distDif; aNewDistance += distDif; } } else{ distDif = aDistance%100; if( distDif < 50 ){ aNewDistance -= distDif; } else{ distDif = 100-distDif; aNewDistance += distDif; } } } } void CGuideContainer::PictureError( TInt aError ) { iView->PictureError( aError ); } void CGuideContainer::ScalingDone() { //DrawNow(); DrawDeferred(); } // ---------------------------------------------------------------------------- // TKeyResponse CGuideContainer::OfferKeyEventL( const TKeyEvent&, // TEventCode ) // Handles the key events. // ---------------------------------------------------------------------------- // TKeyResponse CGuideContainer::OfferKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType ) { if ( aType != EEventKey ){ // Is not key event? return EKeyWasNotConsumed; } switch ( aKeyEvent.iScanCode ) { // Switches tab. case EStdKeyUpArrow: if( !(iAppUI->IsGpsAllowed()) && iAppUI->HasRoute() ){ iView->GoToTurn( ETrue ); return EKeyWasConsumed; } break; case EStdKeyDownArrow: if( !(iAppUI->IsGpsAllowed()) && iAppUI->HasRoute() ){ iView->GoToTurn( EFalse ); return EKeyWasConsumed; } break; case EStdKeyDevice3: iView->HandleCommandL( EWayFinderCmdGuideReroute ); return EKeyWasConsumed; break; // No hash for you, for now anyway // case EStdKeyHash: // iView->HandleCommandL( EWayFinderCmdMap ) ; // return EKeyWasConsumed; // break; } return EKeyWasNotConsumed; } // --------------------------------------------------------- // CGuideContainer::SizeChanged() // Called by framework when the view size is changed // --------------------------------------------------------- // void CGuideContainer::SizeChanged() { if (WFLayoutUtils::LandscapeMode()) { if( iNextStreetLabel ) SetLabelExtent(iNextStreetLabel, NEXT_STREET_LABEL_X_LS, NEXT_STREET_LABEL_Y_LS, ETrue); if( iCurrStreetLabel ) SetLabelExtent(iCurrStreetLabel, CURR_STREET_LABEL_X_LS, CURR_STREET_LABEL_Y_LS, ETrue); if( iDistanceLabel ) SetLabelExtent(iDistanceLabel, DIST_STREET_LABEL_X_LS, DIST_STREET_LABEL_Y_LS); } else { if( iNextStreetLabel ) SetLabelExtent(iNextStreetLabel, NEXTSTREET_LABEL_POS, ETrue); if( iCurrStreetLabel ) SetLabelExtent(iCurrStreetLabel, CURRSTREET_LABEL_POS, ETrue); if( iDistanceLabel ) SetLabelExtent(iDistanceLabel, DISTANCE_LABEL_POS); } } // --------------------------------------------------------- // CGuideContainer::CountComponentControls() const // --------------------------------------------------------- // TInt CGuideContainer::CountComponentControls() const { return ENumberControls; // return nbr of controls inside this container } // --------------------------------------------------------- // CGuideContainer::ComponentControl(TInt aIndex) const // --------------------------------------------------------- // CCoeControl* CGuideContainer::ComponentControl(TInt aIndex) const { switch ( aIndex ) { case ENextStreetLabel: return iNextStreetLabel; case EGuidePicture: return iGuidePicture; case EExitPicture: return iExitPicture; case ECurrStreetLabel: return iCurrStreetLabel; case EDistanceLabel: return iDistanceLabel; case EProgressBar: return iProgressBar; case ENextTurnPicture: return iNextTurnPicture; case EDetourPicture: return iDetourPicture; case ESpeedCamPicture: return iSpeedCamPicture; default: return NULL; } } // --------------------------------------------------------- // CGuideContainer::Draw(const TRect& aRect) const // --------------------------------------------------------- // void CGuideContainer::Draw(const TRect& aRect) const { CWindowGc& gc = SystemGc(); // TODO: Add your drawing code here // example code... gc.SetPenStyle(CGraphicsContext::ENullPen); // gc.SetBrushColor( TRgb( KBackgroundRed, KBackgroundGreen, KBackgroundBlue ) ); gc.SetBrushColor(TRgb(iR, iG, iB)); gc.SetBrushStyle(CGraphicsContext::ESolidBrush); gc.DrawRect(aRect); #undef DRAW_IMAGE_RECTS_DBG //#define DRAW_IMAGE_RECTS_DBG #ifdef DRAW_IMAGE_RECTS_DBG if (iGuidePicture) { gc.SetBrushStyle(CGraphicsContext::ENullBrush); gc.SetPenStyle(CGraphicsContext::ESolidPen); gc.SetPenColor(TRgb(0, 0, 0)); gc.DrawRect(iGuidePicture->Rect()); } if (iNextTurnPicture) { gc.SetBrushStyle(CGraphicsContext::ENullBrush); gc.SetPenStyle(CGraphicsContext::ESolidPen); gc.SetPenColor(TRgb(0, 255, 0)); gc.DrawRect(iNextTurnPicture->Rect()); } if (iDetourPicture) { gc.SetBrushStyle(CGraphicsContext::ENullBrush); gc.SetPenStyle(CGraphicsContext::ESolidPen); gc.SetPenColor(TRgb(0, 255, 0)); gc.DrawRect(iDetourPicture->Rect()); } if (iSpeedCamPicture) { gc.SetBrushStyle(CGraphicsContext::ENullBrush); gc.SetPenStyle(CGraphicsContext::ESolidPen); gc.SetPenColor(TRgb(255, 0, 0)); gc.DrawRect(iSpeedCamPicture->Rect()); } #endif } // --------------------------------------------------------- // CGuideContainer::HandleControlEventL( // CCoeControl* aControl,TCoeEvent aEventType) // --------------------------------------------------------- // void CGuideContainer::HandleControlEventL( CCoeControl* /*aControl*/, TCoeEvent /*aEventType*/) { // TODO: Add your control event handler code here } void CGuideContainer::SetLabelExtent(class CEikLabel* aLabel, const TPoint &aPosition, TBool aExtendToSceenWidth) { // All the sizen for V3 are relative points // based on the positions for V2 #ifdef NAV2_CLIENT_SERIES60_V3 TSize size = aLabel->MinimumSize(); // We need to increase the height otherwise we wont see // a complete letter of type g/p etc. size.iHeight = aLabel->Font()->HeightInPixels() + aLabel->Font()->DescentInPixels(); if (aExtendToSceenWidth) { size.iWidth = WFLayoutUtils::GetMainPaneRect().Width(); } aLabel->SetExtent(WFLayoutUtils:: CalculatePosUsingMainPane(aPosition, WFLayoutUtils::WideScreen()), size); aLabel->DrawDeferred(); #else // v2 does not use the size that is sent in, it has // allways used MinimumSize and I dont want to change // this now. aLabel->SetExtent(aPosition, aLabel->MinimumSize()); #endif } void CGuideContainer::SetLabelExtent(class CEikLabel* aLabel, float aWidth, float aHeight, TBool aExtendToSceenWidth) { // All the sizen for V3 are relative points // based on the positions for V2 TSize size = aLabel->MinimumSize(); #if defined NAV2_CLIENT_SERIES60_V3 // We need to increase the height otherwise we wont see // a complete letter of type g/p etc. size.iHeight = aLabel->Font()->HeightInPixels() + aLabel->Font()->DescentInPixels(); #endif if (aExtendToSceenWidth) { size.iWidth = WFLayoutUtils::GetMainPaneRect().Width(); } aLabel->SetExtent(WFLayoutUtils:: CalculatePosUsingMainPaneFloat(aWidth, aHeight, WFLayoutUtils::WideScreen()), size); aLabel->DrawDeferred(); } void CGuideContainer::CreatePictureL(class CImageHandler*& aImage, const TRect& /*aRect*/, const TPoint aPoint, TInt aWidth, TInt aHeight) { TSize size; if (aWidth == aHeight) { // The width and height are equal, we are calculating the size based // on the width of the image and the width of the screen so that the // image size allways becomes a square. size = TSize(WFLayoutUtils::CalculateSizeUsingWidth(aWidth, WFLayoutUtils::WideScreen())); } else { // The widht are not equal to the height, the image rect should // have the shape of a rectangle. size = TSize(WFLayoutUtils::CalculateSizeUsingMainPane(aWidth, aHeight, WFLayoutUtils::WideScreen())); } if (aImage) { aImage->SetImageRect(TRect(WFLayoutUtils:: CalculatePosUsingMainPane(aPoint, WFLayoutUtils::WideScreen()), size)); } else { aImage = CImageHandler::NewL(TRect(WFLayoutUtils:: CalculatePosUsingMainPane(aPoint, WFLayoutUtils::WideScreen()), size)); } } // void CGuideContainer::SetPicture(class CImageHandler*& aImage, ) void CGuideContainer::HandleResourceChange(TInt aType) { CCoeControl::HandleResourceChange(aType); if (aType == KEikDynamicLayoutVariantSwitch) { iLayoutChanged = ETrue; if (WFLayoutUtils::LandscapeMode()) { // We are in landscape mode! CalculateLandscapeLayout(); } else { // We are in portratit mode! CalculatePortraitLayout(); } RefreshPictures(); SetRect(WFLayoutUtils::GetMainPaneRect()); } } void CGuideContainer::CalculateLandscapeLayout() { #ifdef NAV2_CLIENT_SERIES60_V3 // Landscape mode! // Clear all labeltexts before setting the new extent, // by doing this we will get rid of the text in the // old positions. ActivateGc(); CWindowGc& gc = SystemGc(); gc.Clear(iCurrStreetLabel->Rect()); SetLabelExtent(iCurrStreetLabel, CURR_STREET_LABEL_X_LS, CURR_STREET_LABEL_Y_LS, ETrue); gc.Clear(iNextStreetLabel->Rect()); SetLabelExtent(iNextStreetLabel, NEXT_STREET_LABEL_X_LS, NEXT_STREET_LABEL_Y_LS, ETrue); gc.Clear(iDistanceLabel->Rect()); SetLabelExtent(iDistanceLabel, DIST_STREET_LABEL_X_LS, DIST_STREET_LABEL_Y_LS); DeactivateGc(); TBool wideScreen = WFLayoutUtils::WideScreen(); if (iGuidePicture) { // Recalculate iGuidePicture->SetImageRect(TRect(WFLayoutUtils:: CalculatePosUsingMainPaneFloat(0.1, 0.15, wideScreen), WFLayoutUtils:: CalculateSizeUsingMainPaneFloat(0.45, 0.70, wideScreen))); } else { iGuidePicture = CImageHandler::NewL(TRect(WFLayoutUtils:: CalculatePosUsingMainPaneFloat(0.1, 0.15, wideScreen), WFLayoutUtils:: CalculateSizeUsingMainPaneFloat(0.45, 0.70, wideScreen))); } if (iProgressBar) { iProgressBar->SetSizeAndPosition(TRect(WFLayoutUtils::CalculatePosUsingMainPaneFloat(0.7, 0.15, wideScreen), WFLayoutUtils::CalculateSizeUsingMainPaneFloat(0.20, 0.6, wideScreen))); } else { TInt progressTriangleIndex; TInt progressRectIndex; if (iAppUI->IsNightMode()) { progressTriangleIndex = EMbmWficonsProgress_triangle_night; progressRectIndex = EMbmWficonsProgress_bar_night; } else { progressTriangleIndex = EMbmWficonsProgress_triangle_blue; progressRectIndex = EMbmWficonsProgress_bar_blue; } iProgressBar = CGuideProgressBar::NewL(*this, TRect( WFLayoutUtils:: CalculatePosUsingMainPaneFloat(0.7, 0.15, wideScreen), WFLayoutUtils:: CalculateSizeUsingMainPaneFloat(0.20, 0.6, wideScreen)), iView->GetMbmName(), EMbmWficonsProgress_triangle_grey, progressTriangleIndex, EMbmWficonsProgress_triangle_grey_mask, EMbmWficonsProgress_bar_grey, progressRectIndex, EMbmWficonsProgress_bar_grey_mask); } // Calculate the padding iImagePaddingX = WFLayoutUtils::CalculateXValue(IMAGE_PADDING, wideScreen); iImagePaddingY = WFLayoutUtils::CalculateYValueUsingMainPane(IMAGE_PADDING); SetImage(iNextTurnPicture, iGuidePicture->GetRect(), &TopRight, 0.24, 0.24, -iImagePaddingX, iImagePaddingY); SetImage(iDetourPicture, iGuidePicture->GetRect(), &LowerLeft, 0.24, 0.24, iImagePaddingX, -iImagePaddingY); SetImage(iSpeedCamPicture, iGuidePicture->GetRect(), &LowerRight, 0.24, 0.24, -iImagePaddingX, -iImagePaddingY); iDetourPicture->CreateIconL(iView->GetMbmName(), EMbmWficonsDetour_square, EMbmWficonsDetour_square_mask, EAspectRatioPreservedAndUnusedSpaceRemoved); iSpeedCamPicture->CreateIconL(iView->GetMbmName(), EMbmWficonsSpeedcamera_square, EMbmWficonsSpeedcamera_square, EAspectRatioPreservedAndUnusedSpaceRemoved); TRect exitRect = Center(iGuidePicture->GetRect(), TRect(TPoint(), WFLayoutUtils:: CalculateSizeUsingSize(iGuidePicture->GetSize(), 0.1, 0.16, wideScreen))); if (iExitPicture) { iExitPicture->SetImageRect(exitRect, EAspectRatioPreservedAndUnusedSpaceRemoved, ETrue); } else { iExitPicture = CImageHandler::NewL(exitRect); } #endif } void CGuideContainer::CalculatePortraitLayout() { #ifdef NAV2_CLIENT_SERIES60_V3 ActivateGc(); CWindowGc& gc = SystemGc(); gc.Clear(iCurrStreetLabel->Rect()); SetLabelExtent(iCurrStreetLabel, CURRSTREET_LABEL_POS, ETrue); gc.Clear(iNextStreetLabel->Rect()); SetLabelExtent(iNextStreetLabel, NEXTSTREET_LABEL_POS, ETrue); gc.Clear(iDistanceLabel->Rect()); SetLabelExtent(iDistanceLabel, DISTANCE_LABEL_POS); DeactivateGc(); TBool wideScreen = WFLayoutUtils::WideScreen(); if (iProgressBar) { iProgressBar->SetSizeAndPosition(TRect( WFLayoutUtils:: CalculatePosUsingMainPane( PROGRESS_BAR_POS, wideScreen), WFLayoutUtils:: CalculateSizeUsingMainPane( 40, 90, wideScreen) ) ); } else { TInt progressTriangleIndex; TInt progressRectIndex; if (iAppUI->IsNightMode()) { progressTriangleIndex = EMbmWficonsProgress_triangle_night; progressRectIndex = EMbmWficonsProgress_bar_night; } else { progressTriangleIndex = EMbmWficonsProgress_triangle_blue; progressRectIndex = EMbmWficonsProgress_bar_blue; } iProgressBar = CGuideProgressBar::NewL(*this, TRect( WFLayoutUtils:: CalculatePosUsingMainPane( PROGRESS_BAR_POS, wideScreen ), WFLayoutUtils:: CalculateSizeUsingMainPane( 40, 90, wideScreen ) ), iView->GetMbmName(), EMbmWficonsProgress_triangle_grey, progressTriangleIndex, EMbmWficonsProgress_triangle_grey_mask, EMbmWficonsProgress_bar_grey, progressRectIndex, EMbmWficonsProgress_bar_grey_mask); } TRect rect = WFLayoutUtils::GetMainPaneRect(); CreatePictureL(iGuidePicture, rect, GUIDE_PICTURE_POS, 100, 100); iImagePaddingX = WFLayoutUtils::CalculateXValue(IMAGE_PADDING); iImagePaddingY = WFLayoutUtils::CalculateYValueUsingMainPane(IMAGE_PADDING); SetImage(iNextTurnPicture, iGuidePicture->GetRect(), &TopRight, 0.24, 0.24, -iImagePaddingX, iImagePaddingY); SetImage(iDetourPicture, iGuidePicture->GetRect(), &LowerLeft, 0.24, 0.24, iImagePaddingX, -iImagePaddingY); SetImage(iSpeedCamPicture, iGuidePicture->GetRect(), &LowerRight, 0.24, 0.24, -iImagePaddingX, -iImagePaddingY); iDetourPicture->CreateIconL(iView->GetMbmName(), EMbmWficonsDetour_square, EMbmWficonsDetour_square_mask, EAspectRatioPreservedAndUnusedSpaceRemoved); iSpeedCamPicture->CreateIconL(iView->GetMbmName(), EMbmWficonsSpeedcamera_square, EMbmWficonsSpeedcamera_square, EAspectRatioPreservedAndUnusedSpaceRemoved); TRect exitRect = Center(iGuidePicture->GetRect(), TRect(TPoint(), WFLayoutUtils:: CalculateSizeUsingSize(iGuidePicture->GetSize(), 0.26, 0.16, wideScreen))); if (iExitPicture) { iExitPicture->SetImageRect(exitRect); } else { iExitPicture = CImageHandler::NewL(exitRect); } #endif } void CGuideContainer::SetImage(class CImageHandler*& aImage, const TRect& aBaseRect, TRect (*ptrFunc) (const class TRect& aRect, const class TSize& aSize), float aXPos, float aYPos, TInt aDx, TInt aDy) { TBool wideScreen = WFLayoutUtils::WideScreen(); TRect rect = (*ptrFunc)(aBaseRect, TSize(WFLayoutUtils::CalculateXValue(aBaseRect.Width(), aXPos, wideScreen), WFLayoutUtils::CalculateYValue(aBaseRect.Height(), aYPos))); rect.Move(aDx, aDy); if (aImage) { aImage->SetImageRect(rect); } else { aImage = CImageHandler::NewL(rect); } } void CGuideContainer::SetImagePos(class CImageHandler*& aImage, const TRect& aBaseRect, TRect (*ptrFunc) (const class TRect& aRect, const class TSize& aSize), TInt aDx, TInt aDy) { if(!aImage) { return; } TRect rect = (*ptrFunc)(aBaseRect, aImage->GetSize()); rect.Move(aDx, aDy); aImage->SetImageRect(rect); } void CGuideContainer::SetNightModeL(TBool aNightMode) { #ifdef NAV2_CLIENT_SERIES60_V3 iAppUI->GetBackgroundColor(iR, iG, iB); CGuideProgressBar* tmpBar; CGuideProgressBar* tmpBar2 = iProgressBar; TRect rect; // Calculate the size of the progressbar if (WFLayoutUtils::LandscapeMode(*iAppUI)) { rect.SetRect(WFLayoutUtils:: CalculatePosUsingMainPaneFloat(0.7, 0.15, WFLayoutUtils::WideScreen()), WFLayoutUtils:: CalculateSizeUsingMainPaneFloat(0.20, 0.6, WFLayoutUtils::WideScreen())); } else { rect.SetRect(WFLayoutUtils::CalculatePosUsingMainPane(PROGRESS_BAR_POS, WFLayoutUtils::WideScreen()), WFLayoutUtils::CalculateSizeUsingMainPane(40, 90, WFLayoutUtils::WideScreen())); } if (aNightMode) { tmpBar = CGuideProgressBar::NewL(*this, rect, iView->GetMbmName(), EMbmWficonsProgress_triangle_grey, EMbmWficonsProgress_triangle_night, EMbmWficonsProgress_triangle_grey_mask, EMbmWficonsProgress_bar_grey, EMbmWficonsProgress_bar_night, EMbmWficonsProgress_bar_grey_mask); TRgb nightColor(KForegroundTextColorNightRed, KForegroundTextColorNightGreen, KForegroundTextColorNightBlue); iCurrStreetLabel->OverrideColorL(EColorLabelText, nightColor); iNextStreetLabel->OverrideColorL(EColorLabelText, nightColor); iDistanceLabel->OverrideColorL(EColorLabelText, nightColor); /* //NightFilter disabled for the pictures. //Enable the NightFilter calls for the images in the following functions // if you enable it here: SetGuidePictureL, SetNextTurnPictureL and SetExitL. if (iGuidePicture) { iGuidePicture->NightFilter(iAppUI->IsNightMode()); } if (iNextTurnPicture){ iNextTurnPicture->NightFilter(iAppUI->IsNightMode()); } if (iDetourPicture){ iDetourPicture->NightFilter(iAppUI->IsNightMode()); } if (iSpeedCamPicture){ iSpeedCamPicture->NightFilter(iAppUI->IsNightMode()); } if (iExitPicture){ iExitPicture->NightFilter(iAppUI->IsNightMode()); } */ } else { tmpBar = CGuideProgressBar::NewL(*this, rect, iView->GetMbmName(), EMbmWficonsProgress_triangle_grey, EMbmWficonsProgress_triangle_blue, EMbmWficonsProgress_triangle_grey_mask, EMbmWficonsProgress_bar_grey, EMbmWficonsProgress_bar_blue, EMbmWficonsProgress_bar_grey_mask); iCurrStreetLabel->OverrideColorL(EColorLabelText, TRgb(0, 0, 0)); iNextStreetLabel->OverrideColorL(EColorLabelText, TRgb(0, 0, 0)); iDistanceLabel->OverrideColorL(EColorLabelText, TRgb(0, 0, 0)); /* iGuidePicture->TurnNightModeOff(iView->GetMbmName(), iView->GetCurrentTurnPicture(), EMbmWficonsKeep_left_mask); TInt imageIndex, maskIndex; iView->GetNextTurnPicture(imageIndex, maskIndex); iNextTurnPicture->TurnNightModeOff(iView->GetMbmName(), imageIndex, maskIndex); iDetourPicture->TurnNightModeOff(iView->GetMbmName(), EMbmWficonsDetour_square, EMbmWficonsDetour_square_mask); iSpeedCamPicture->TurnNightModeOff(iView->GetMbmName(), EMbmWficonsSpeedcamera_square, EMbmWficonsSpeedcamera_square); if (iNextTurnPicture->GetShow()) { Window().Invalidate(iNextTurnPicture->Rect()); } if (iGuidePicture->GetShow()) { Window().Invalidate(iGuidePicture->Rect()); } if (iDetourPicture->GetShow()) { Window().Invalidate(iDetourPicture->Rect()); } if (iSpeedCamPicture->GetShow()) { Window().Invalidate(iSpeedCamPicture->Rect()); } */ } tmpBar->SetDistance(iProgressBar->GetDistance()); iProgressBar = tmpBar; delete tmpBar2; #endif } // End of File
[ [ [ 1, 1130 ] ] ]
203c97f3aa89bdcc386b1251935a2c3f99432217
952d78c7f43f694f2d676579ec9fa6e31211edaf
/aichallenge/ants/bots/KethBot/AI/Path.h
711ebf691543127d92e40e419793786798c441d6
[]
no_license
pombreda/aichallenge-1
e991db57cc30d4a8115fd2e5232727c085ad4c1d
5cd69435673e417f5abf7ee99077fbb9138666b5
refs/heads/master
2020-12-31T03:55:51.292414
2011-09-25T05:14:45
2011-09-25T05:14:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
946
h
#ifndef PATH_H #define PATH_H //#include "Location.h" #include <stack> struct Location; struct Path { Path() { iterations = totalCost = 0; touchedFog = false; }; std::stack<const Location*> moves; int totalCost; int iterations; bool touchedFog; inline int stepsLeft() { return moves.size(); }; inline const Location& targetLocation() { return *target; }; inline const Location& sourceLocation() { return *source; }; inline bool hasTarget() { return target; }; inline bool hasSource() { return source; }; inline void setTarget(const Location& loc) { target = &loc; }; inline void setSource(const Location& loc) { source = &loc; }; const Location* target; const Location* source; }; struct SearchLocation { int cost; double opened; double distanceLeft; const Location* loc; const Location* ref; }; #endif // PATH_H
[ [ [ 1, 44 ] ] ]
ac7e48227a15f553a9bf8ef966cfbe7b5a67fc48
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Ngllib/include/Ngl/Factory/Factory.h
278bcb686f832cfe27aa523c1b2016bbe84d9849
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,378
h
/*******************************************************************************/ /** * @file Factory.h. * * @brief 工場テンプレートクラス定義. * * @date 2008/11/02. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #ifndef _NGL_FACTORY_H_ #define _NGL_FACTORY_H_ #include <map> #include <string> namespace Ngl{ /** * @class Factory. * @brief 工場テンプレートクラス. * * @tparam T 製品. * @tparam ID 製品ID. * * @warning 製品として追加するクラスには、"T* clone( void )"関数を持つクローン機能が必要です * * Ngl::IClonableクラスを使用すると、クローン関数に対応した関数名を強制することができます。<br> * Ngl/IClonable.hをインクルードしてください<br> */ template < class T, class ID = std::string > class Factory { private: //製品コンテナクラス typedef std::map< ID, T* > ProductContainer; public: /*=========================================================================*/ /** * @brief デストラクタ * * @param[in] なし. */ virtual ~Factory() { // 保持している製品を全て削除 ProductContainer::iterator itor=productContainer_.begin(); while( itor != productContainer_.end() ){ delete itor->second; itor = productContainer_.erase( itor ); } } /*=========================================================================*/ /** * @brief 製品の原型を追加 * * @param[in] id 追加する製品のID. * @param[in] product 追加する製品. * @return なし. */ void add( const ID& id, T* product ) { productContainer_[ id ] = product; } /*=========================================================================*/ /** * @brief 製品を作成 * * @param[in] id 作成する製品のID. * @return 作成した製品. */ T* create( const ID& id ) { //指定された製品のクローンを作成 return productContainer_[ id ]->clone(); } private: /** 製品コンテナ */ ProductContainer productContainer_; }; } // namespace Ngl #endif /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 106 ] ] ]
26020e2ea90af5648e667d66cfb645bd26c52389
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Dynamics/World/hkpPhysicsSystem.h
e0abd37bcf839bcf93a5571919a3d027263aaa8f
[]
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
5,195
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_DYNAMICS2_PHYSICS_SYSTEM_H #define HK_DYNAMICS2_PHYSICS_SYSTEM_H extern const hkClass hkpPhysicsSystemClass; class hkpRigidBody; class hkpConstraintData; class hkpConstraintInstance; class hkpAction; class hkpPhantom; /// A class to group collections of objects, which typically are serialized together, /// and should be added and removed from the world together. /// Examples are a ragdoll, and a vehicle. class hkpPhysicsSystem : public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_WORLD); HK_DECLARE_REFLECTION(); hkpPhysicsSystem(); virtual ~hkpPhysicsSystem(); /// Return a copy of the system, in which all items /// are clones of the originals, sharing as much data /// as possible (eg: shapes, constraintdata, etc) virtual hkpPhysicsSystem* clone() const; /// removes all elements void removeAll(); /// Shallow copy a system. Just copies arrays of ptrs. void copy(const hkpPhysicsSystem& toCopy); /// Add a rigidbody to the list void addRigidBody( hkpRigidBody* rb ); /// Add a phantom to the list void addPhantom( hkpPhantom* p ); /// Add a constraint to the list void addConstraint( hkpConstraintInstance* c ); /// Add an action to the list void addAction( hkpAction* a ); /// Remove a rigidbody from the list /// It does a quick remove, so will not preserve /// the order of the list void removeRigidBody( int i ); /// Remove a phantom from the list /// It does a quick remove, so will not preserve /// the order of the list void removePhantom( int i ); /// Remove an constraint from the list /// It does a quick remove, so will not preserve /// the order of the list void removeConstraint( int i ); /// Remove an action from the list /// It does a quick remove, so will not preserve /// the order of the list void removeAction( int i ); /// Removes all null pointers from the phantoms array. /// This is handy when loading a snapshot where hkpPhantom-derived classes have not been serialized. void removeNullPhantoms(); /// Get the held array of bodies inline const hkArray<hkpRigidBody*>& getRigidBodies() const; /// Get the held array of phantoms inline const hkArray<hkpPhantom*>& getPhantoms() const; /// Get the held array of constraints inline const hkArray<hkpConstraintInstance*>& getConstraints() const; /// Get the held array of actions inline const hkArray<hkpAction*>& getActions() const; /// Get the name of the system inline const char* getName() const; /// Set the name of the system inline void setName(const char* name); /// Get the user data for the system inline hkUlong getUserData() const; /// Set the user data for the system inline void setUserData(hkUlong d); /// inline hkBool isActive() const; /// inline void setActive(hkBool active); virtual hkBool hasContacts() { return false; } /// This function transforms the physics system. void transform(const hkTransform& transformation); protected: /// Note, ALL these arrays contain reference counted instances. /// The destructor for the system will decrement the references on all held objects /// so it assumes that when you fill out these arrays that you give it a referenced /// count incremented object hkArray<class hkpRigidBody*> m_rigidBodies; hkArray<class hkpConstraintInstance*> m_constraints; hkArray<class hkpAction*> m_actions; hkArray<class hkpPhantom*> m_phantoms; hkStringPtr m_name; hkUlong m_userData; //+default(0) hkBool m_active; //+default(true) public: hkpPhysicsSystem( hkFinishLoadedObjectFlag f ) : hkReferencedObject(f), m_rigidBodies(f), m_constraints(f), m_actions(f), m_phantoms(f), m_name(f) { } }; #include <Physics/Dynamics/World/hkpPhysicsSystem.inl> #endif // HK_DYNAMICS2_PHYSICS_SYSTEM_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, 161 ] ] ]
f444f08ca8a4bb629940599fa3e3fcce2efe4781
1caba14ec096b36815b587f719dda8c963d60134
/tags/start/smx/libsmx/qarg.h
d6cbb94d9264dee81258e3bc8b6d1ab857e83545
[]
no_license
BackupTheBerlios/smx-svn
0502dff1e494cffeb1c4a79ae8eaa5db647e5056
7955bd611e88b76851987338b12e47a97a327eaf
refs/heads/master
2021-01-10T19:54:39.450497
2009-03-01T12:24:56
2009-03-01T12:24:56
40,749,397
0
0
null
null
null
null
UTF-8
C++
false
false
1,229
h
/* COPYRIGHT 1998 Prime Data Corp. All Rights Reserved. Use of this file without prior written authorization is strictly prohibited. */ #ifndef _QARG_H #define _QARG_H class qObj; class qCtx; #include "strary.h" typedef CStr qArg; class qArgAry : public CStrAry { char *myOpts; char myOptsN; enum { myGrowBy = 16 }; public: qArgAry() { myOpts = 0; myOptsN = 0; } ~qArgAry() { free(myOpts); } qArgAry(CStr *args, int n) : CStrAry(args, n) { myOpts = 0; myOptsN = 0; } qArgAry(int n) : CStrAry(n) { myOpts = 0; myOptsN = 0; } void Shift(int n) { CStrAry::Shift(n); if (myOpts) { myOpts++; myOptsN--; } } void Restore(int n) { CStrAry::Restore(n); if (myOpts) { myOpts--; myOptsN++; } } void SetQuot(int n, char value) { if (!this) return; if (n >= myOptsN) { myOpts = (char *) realloc(myOpts, n + myGrowBy); memset(myOpts + myOptsN, 0, n + myGrowBy - myOptsN); myOptsN = n + myGrowBy; } myOpts[n] = value; } char GetQuot(char n) { return (this && n < myOptsN) ? myOpts[n] : 0; } char *GetQuots() { return this ? myOpts : 0; } }; #endif //#ifndef _QARG_H
[ "(no author)@407f561b-fe63-0410-8234-8332a1beff53" ]
[ [ [ 1, 75 ] ] ]
32a56d7557e8e9cf13524cf6e5ac3e7fd8c331c3
24b0a9486db1b945cd9b7623d880377029670a9b
/ASProtect/CppEnvelopeCheck.inc
e1cf7b2d238c0e1fcdb39fbf739dfa611ca00ed8
[]
no_license
tmpprj/tmpprj
ea9fbe1e4f584cf1c80c287b1eac19ae18c2d9b6
1b1e19d01f6dbfdacdb3000778ca822e57862ca6
refs/heads/master
2020-05-17T23:55:36.397473
2009-11-08T21:04:37
2009-11-08T21:04:37
138,308
3
1
null
null
null
null
UTF-8
C++
false
false
914
inc
// Cpp include file // ASProtect Envelope checking routine #ifndef __BORLANDC__ __asm #endif { ENVELOPE_CHECK ENVELOPE_CHECK_BUFFER // 10 DEFAULT_BUFFER DEFAULT_BUFFER // 20 DEFAULT_BUFFER DEFAULT_BUFFER // 30 DEFAULT_BUFFER DEFAULT_BUFFER // 40 DEFAULT_BUFFER DEFAULT_BUFFER // 50 DEFAULT_BUFFER DEFAULT_BUFFER // 60 DEFAULT_BUFFER DEFAULT_BUFFER // 70 DEFAULT_BUFFER DEFAULT_BUFFER // 80 DEFAULT_BUFFER DEFAULT_BUFFER // 90 DEFAULT_BUFFER DEFAULT_BUFFER // A0 DEFAULT_BUFFER DEFAULT_BUFFER // B0 DEFAULT_BUFFER DEFAULT_BUFFER // C0 DEFAULT_BUFFER DEFAULT_BUFFER // D0 DEFAULT_BUFFER DEFAULT_BUFFER // E0 DEFAULT_BUFFER DEFAULT_BUFFER // F0 DEFAULT_BUFFER DEFAULT_BUFFER // 100 DEFAULT_BUFFER DEFAULT_BUFFER // 110 };
[ "Administrator@.(none)" ]
[ [ [ 1, 29 ] ] ]
7a8f83e670e327366b2104015795fe63e88da54c
df5277b77ad258cc5d3da348b5986294b055a2be
/GameEngineV0.35/Source/Network.cpp
bb3f97a591489d9369590ad38ca643c43bf55149
[]
no_license
beentaken/cs260-last2
147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22
61b2f84d565cc94a0283cc14c40fb52189ec1ba5
refs/heads/master
2021-03-20T16:27:10.552333
2010-04-26T00:47:13
2010-04-26T00:47:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,397
cpp
#include "Precompiled.h" #include "Network.h" #include "GameProtocol.h" #include "GameMessages.h" #include <iostream> namespace Framework { ///Global pointer to the Network system. Network *NETWORK = NULL; ///30 second timeout phase. const double Network::CONNECTION_TIMEOUT = 15.0; void Network::Connection::EmptyInBasket( void ) { for (unsigned i = 0; i < NMid::NumIds; ++i) { MessageList::iterator begin = inbasket[i].begin(), end = inbasket[i].end(); while (begin != end) delete *begin++; inbasket[i].clear(); } } void Network::Connection::EmptyOutBasket( void ) { for (unsigned i = 0; i < NMid::NumIds; ++i) { MessageList::iterator begin = outbasket[i].begin(), end = outbasket[i].end(); while (begin != end) delete *begin++; outbasket[i].clear(); } } bool Network::Connection::IsOutBasketEmpty( void ) { for (unsigned type = 0; type < NMid::NumIds; ++type) if (outbasket[type].size()) return false; return true; } bool Network::Connection::IsInBasketEmpty( void ) { for (unsigned type = 0; type < NMid::NumIds; ++type) if (inbasket[type].size()) return false; return true; } void Network::Connection::DistributeMessages( void ) { for (unsigned i = 0; i < NMid::NumIds; ++i) { MessageList::iterator begin = inbasket[i].begin(), end = inbasket[i].end(); while (begin != end) { const_cast<INetMessage*>(*begin)->SendThis(); delete *begin++; } inbasket[i].clear(); } } void Network::InitializeThread( void ) { } void Network::Run( void ) { ///Listen continuously for packets from users/server. while (listening) { NetAddress remote; int ret = socket->RecvFrom( remote ); remote.ResetData(); ///If we received data and it's from someone we know. if (ret > 0) { ///If this isn't a new connection. if (connections.count(remote)) { Lock lock(mutex); ///Save all the messages into the queue. socket->RetieveData(connections[remote].inbasket); ///Reset the timeout timer. connections[remote].timer.Start(); } else ///New connection. { Lock lock(mutex); ///Get the data from the socket. int num = socket->RetieveData(connections[remote].inbasket); ///If we couldn't extract any messages it was random data/connection if (num == 0) connections.erase(remote); } } } // end while (listening) } void Network::ExitThread( void ) throw() { ///Remove any data and cleanup. } void Network::FlushThread( void ) { listening = false; } ///Pauses and Resumes listening. void Network::Pause( void ) { mutex.Acquire(); } void Network::Resume( void ) { mutex.Release(); } ///Create the actual socket in void Network::InitializeSocket( void ) { ///Don't make multiple sockets. if (!socket) socket = NetAPI->NewUDPSocket(); ///Make sure socket is non-blocking. socket->ToggleBlocking(false); } void Network::CheckForTimeouts( void ) { ///Check to see if any users have timed out... ConnectionMap::iterator begin = connections.begin(), end = connections.end(); while (begin != end) { if (begin->second.timer.TimeElapsed() > CONNECTION_TIMEOUT) { TimeoutMessage(begin->first).SendThis(); connections.erase(begin++); } else ++begin; } } void Network::UpdateConnections( void ) { ///Go through and send all messages to each connection. ConnectionMap::iterator begin = connections.begin(), end = connections.end(); while (begin != end) { /// Tell the protocol which message basket to send from. if (!begin->second.IsOutBasketEmpty()) { protocol->SetMessageList(begin->second.outbasket); socket->SendTo(begin->first, protocol); begin->second.EmptyOutBasket(); } if (!begin->second.IsInBasketEmpty()) { static Timer timer; std::cout << "Time since last message: " << timer.TimeElapsed() << std::endl; timer.Start(); ///Send the messages we received out to the system. begin->second.DistributeMessages(); begin->second.EmptyInBasket(); } ++begin; } } Network::Network( void ) : socket(0) { ErrorIf(NETWORK!=NULL,"Network already initialized."); NETWORK = this; NetAPI->Init(); } Network::~Network( void ) { thread_.Resume(); Kill(); delete protocol; CloseConnection(); NetAPI->Cleanup(); } ///Used for system messages only. These will not be put across the connection. void Network::SendMessage( Message *m ) { } ///Sends all messages out to all connected parties. void Network::Update( float dt ) { Lock lock(mutex); ///Check timers on all connections. CheckForTimeouts(); //Send all messages to connections. UpdateConnections(); } void Network::Initialize( void ) { //Hard coded for now. RegisterProtocol(GameProtocol); protocol = NetAPI->GetProtocol("GameProtocol"); } ///Builds up a buffer of messages to send to all connections. void Network::SendNetMessage( const INetMessage &m ) { ///Add the message to all of the message queues. ConnectionMap::iterator begin = connections.begin(), end = connections.end(); while (begin != end) begin++->second.outbasket[m.Type()].push_back(m.Clone()); } ///Builds up a buffer of messages to send to a specific connection. void Network::SendNetMessage( const NetAddress &connection, const INetMessage &m ) { ///Add the message to the requested connection. if (connections.count(connection)) connections[connection].outbasket[m.Type()].push_back(m.Clone()); } ///Creates a socket and waits for connections. bool Network::HostServer( void ) { InitializeSocket(); ///Spawn new thread. thread_.Resume(); return true; } ///Attempts to find a server already running and connect to it. bool Network::FindServer() { InitializeSocket(); //Build a connection message. ConnectionMessage msg; msg.name = NetAPI->Username(); msg.address = socket->GetAddress(); const NetAddress server = NetAPI->GetServerAddress(); Connection &connection = connections[server]; // add the broadcast connection to the connection list. connection.outbasket[NMid::Connection].push_back(&msg); protocol->SetMessageList(connection.outbasket); ///Send out the request for the server... socket->SendTo(NetAPI->GetServerAddress(), protocol); ///Clear the outbasket. connection.outbasket[NMid::Connection].clear(); thread_.Resume(); return true; } ///Closes the socket void Network::CloseConnection( void ) { if (socket) NetAPI->CloseSocket(socket); socket = 0; } }
[ "ProstheticMind43@af704e40-745a-32bd-e5ce-d8b418a3b9ef", "westleyargentum@af704e40-745a-32bd-e5ce-d8b418a3b9ef", "rziugy@af704e40-745a-32bd-e5ce-d8b418a3b9ef" ]
[ [ [ 1, 10 ], [ 12, 191 ], [ 193, 197 ], [ 201, 233 ], [ 235, 256 ], [ 258, 262 ], [ 264, 293 ] ], [ [ 11, 11 ], [ 192, 192 ], [ 234, 234 ], [ 257, 257 ], [ 263, 263 ] ], [ [ 198, 200 ] ] ]
8f072150a6e4c90e1ca3fe39c96d6aa8f64d8355
fab77712e8dfd19aea9716b74314f998093093e2
/Utility/ShareResource.h
271afdedbf2b182805b40b8b51c56e925b26755f
[]
no_license
alandigi/tsfriend
95f98b123ae52f1f515ab4a909de9af3724b138d
b8f246a51f01afde40a352248065a6a42f0bcbf8
refs/heads/master
2016-08-12T07:09:23.928793
2011-11-13T15:12:54
2011-11-13T15:12:54
45,849,814
0
2
null
null
null
null
UTF-8
C++
false
false
458
h
/* as a tree , root shouldn't have brothers */ #pragma once #include "TypeDefine.h" #include "afxmt.h"/* for semaphore */ class CShareResource { public: CShareResource(u8 IntSem = 1); ~CShareResource(); BOOL Lock1(); BOOL UnLock1(); BOOL IsLocked1(); BOOL Lock2(); BOOL UnLock2(); BOOL IsLocked2(); private: CSemaphore * ptrSemaphore; CSingleLock * pSignalLock1; CSingleLock * pSignalLock2; };
[ [ [ 1, 33 ] ] ]
ed97b9cec6923d09d88364b511763aead9515aa3
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/regx/ParenToken.hpp
b0b99866cc418a87f497e8ed1aa8f6fbb93e40b1
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
2,761
hpp
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: ParenToken.hpp,v 1.6 2004/09/08 13:56:47 peiyongz Exp $ */ #if !defined(PARENTOKEN_HPP) #define PARENTOKEN_HPP // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/regx/Token.hpp> XERCES_CPP_NAMESPACE_BEGIN class XMLUTIL_EXPORT ParenToken : public Token { public: // ----------------------------------------------------------------------- // Public Constructors and Destructor // ----------------------------------------------------------------------- ParenToken(const unsigned short tokType, Token* const tok, const int noParen, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); ~ParenToken(); // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- int size() const; int getNoParen() const; Token* getChild(const int index) const; private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- ParenToken(const ParenToken&); ParenToken& operator=(const ParenToken&); // ----------------------------------------------------------------------- // Private data members // ----------------------------------------------------------------------- int fNoParen; Token* fChild; }; // --------------------------------------------------------------------------- // ParenToken: getter methods // --------------------------------------------------------------------------- inline int ParenToken::size() const { return 1; } inline int ParenToken::getNoParen() const { return fNoParen; } inline Token* ParenToken::getChild(const int) const { return fChild; } XERCES_CPP_NAMESPACE_END #endif /** * End of file ParenToken.hpp */
[ [ [ 1, 86 ] ] ]
602f6b482a9633aa63c7c6d5971867f8638a182b
10fa450eeae0966a0ffbbddb8a2504ea5cccbeab
/src/cec09.cpp
f902562e2ebc65f57b07a4b5b7cfac12689f5f42
[]
no_license
wudong/rmoead
595f6e947a4b777b697ccb4f5854e743a594522d
188a172071fbbb788a3995149ab6bf6be46de02f
refs/heads/master
2020-05-20T12:05:19.673929
2010-06-23T21:47:55
2010-06-23T21:47:55
709,165
1
0
null
null
null
null
UTF-8
C++
false
false
27,107
cpp
// cec09.cpp #include "cec09.h" #include <math.h> namespace CEC09 { #define PI 3.1415926535897932384626433832795 #define MYSIGN(x) ((x)>0?1.0:-1.0) void UF1(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2; double sum1, sum2, yj; sum1 = sum2 = 0.0; count1 = count2 = 0; for(j = 2; j <= nx; j++) { yj = x[j-1] - sin(6.0*PI*x[0] + j*PI/nx); yj = yj * yj; if(j % 2 == 0) { sum2 += yj; count2++; } else { sum1 += yj; count1++; } } f[0] = x[0] + 2.0 * sum1 / (double)count1; f[1] = 1.0 - sqrt(x[0]) + 2.0 * sum2 / (double)count2; } void UF2(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2; double sum1, sum2, yj; sum1 = sum2 = 0.0; count1 = count2 = 0; for(j = 2; j <= nx; j++) { if(j % 2 == 0) { yj = x[j-1]-0.3*x[0]*(x[0]*cos(4.0*(6.0*PI*x[0]+j*PI/nx))+2.0)*cos(6.0*PI*x[0]+j*PI/nx); sum2 += yj*yj; count2++; } else { yj = x[j-1]-0.3*x[0]*(x[0]*cos(4.0*(6.0*PI*x[0]+j*PI/nx))+2.0)*sin(6.0*PI*x[0]+j*PI/nx); sum1 += yj*yj; count1++; } } f[0] = x[0] + 2.0 * sum1 / (double)count1; f[1] = 1.0 - sqrt(x[0]) + 2.0 * sum2 / (double)count2; } void UF3(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2; double sum1, sum2, prod1, prod2, yj, pj; sum1 = sum2 = 0.0; count1 = count2 = 0; prod1 = prod2 = 1.0; for(j = 2; j <= nx; j++) { yj = x[j-1]-pow(x[0],0.5*(1.0+3.0*(j-2.0)/(nx-2.0))); pj = cos(20.0*yj*PI/sqrt(j+0.0)); if (j % 2 == 0) { sum2 += yj*yj; prod2 *= pj; count2++; } else { sum1 += yj*yj; prod1 *= pj; count1++; } } f[0] = x[0] + 2.0*(4.0*sum1 - 2.0*prod1 + 2.0) / (double)count1; f[1] = 1.0 - sqrt(x[0]) + 2.0*(4.0*sum2 - 2.0*prod2 + 2.0) / (double)count2; } void UF4(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2; double sum1, sum2, yj, hj; sum1 = sum2 = 0.0; count1 = count2 = 0; for(j = 2; j <= nx; j++) { yj = x[j-1]-sin(6.0*PI*x[0]+j*PI/nx); hj = fabs(yj)/(1.0+exp(2.0*fabs(yj))); if (j % 2 == 0) { sum2 += hj; count2++; } else { sum1 += hj; count1++; } } f[0] = x[0] + 2.0*sum1 / (double)count1; f[1] = 1.0 - x[0]*x[0] + 2.0*sum2 / (double)count2; } void UF5(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2; double sum1, sum2, yj, hj, N, E; sum1 = sum2 = 0.0; count1 = count2 = 0; N = 10.0; E = 0.1; for(j = 2; j <= nx; j++) { yj = x[j-1] - sin(6.0*PI*x[0]); hj = 2.0*yj*yj - cos(4.0*PI*yj) + 1.0; if (j % 2 == 0) { sum2 += hj; count2++; } else { sum1 += hj; count1++; } } hj = 0.5*(0.5/N + E)*fabs(sin(2.0*N*PI*x[0])); f[0] = x[0] + hj + 2.0*sum1 / (double)count1; f[1] = 1.0 - x[0] + hj + 2.0*sum2 / (double)count2; } void UF5_1(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2; double sum1, sum2, yj, hj, N, E; sum1 = sum2 = 0.0; count1 = count2 = 0; N = 10.0; E = 0.01; for(j = 2; j <= nx; j++) { yj = x[j-1] - sin(6.0*PI*x[0]); //hj = 2.0*yj*yj - cos(4.0*PI*yj) + 1.0; //hj = 2.0*yj*yj + 1.0; hj = yj*yj; if (j % 2 == 0) { sum2 += hj; count2++; } else { sum1 += hj; count1++; } } hj = 0.5*(0.5/N + E)*fabs(sin(2.0*N*PI*x[0])); f[0] = x[0] + hj + 2.0*sum1 / (double)count1; f[1] = 1.0 - x[0] + hj + 2.0*sum2 / (double)count2; } void UF6(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2; double sum1, sum2, yj, hj, N, E; sum1 = sum2 = 0.0; count1 = count2 = 0; N = 2.0; E = 0.1; for(j = 2; j <= nx; j++) { yj = x[j-1] - sin(6.0*PI*x[0]+j*PI/nx); if (j % 2 == 0) { sum2 += yj*yj; count2++; } else { sum1 += yj*yj; count1++; } } hj = 0.5*(0.5/N + E)*sin(2.0*N*PI*x[0]); if(hj<0.0) hj = 0.0; f[0] = x[0] + hj + 2.0*sum1 / (double)count1; f[1] = 1.0 - x[0] + hj + 2.0*sum2 / (double)count2; } void UF7(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2; double sum1, sum2, yj; sum1 = sum2 = 0.0; count1 = count2 = 0; for(j = 2; j <= nx; j++) { yj = x[j-1] - sin(6.0*PI*x[0]+j*PI/nx); if (j % 2 == 0) { sum2 += yj*yj; count2++; } else { sum1 += yj*yj; count1++; } } yj = pow(x[0],0.2); f[0] = yj + 2.0*sum1 / (double)count1; f[1] = 1.0 - yj + 2.0*sum2 / (double)count2; } void UF8(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2, count3; double sum1, sum2, sum3, yj; sum1 = sum2 = sum3 = 0.0; count1 = count2 = count3 = 0; for(j = 3; j <= nx; j++) { yj = x[j-1] - 2.0*x[1]*sin(2.0*PI*x[0]+j*PI/nx); if(j % 3 == 1) { sum1 += yj*yj; count1++; } else if(j % 3 == 2) { sum2 += yj*yj; count2++; } else { sum3 += yj*yj; count3++; } } f[0] = cos(0.5*PI*x[0])*cos(0.5*PI*x[1]) + 2.0*sum1 / (double)count1; f[1] = cos(0.5*PI*x[0])*sin(0.5*PI*x[1]) + 2.0*sum2 / (double)count2; f[2] = sin(0.5*PI*x[0]) + 2.0*sum3 / (double)count3; } void UF9(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2, count3; double sum1, sum2, sum3, yj, E; E = 0.1; sum1 = sum2 = sum3 = 0.0; count1 = count2 = count3 = 0; for(j = 3; j <= nx; j++) { yj = x[j-1] - 2.0*x[1]*sin(2.0*PI*x[0]+j*PI/nx); if(j % 3 == 1) { sum1 += yj*yj; count1++; } else if(j % 3 == 2) { sum2 += yj*yj; count2++; } else { sum3 += yj*yj; count3++; } } yj = (0.5+E)*(1.0-4.0*(2.0*x[0]-1.0)*(2.0*x[0]-1.0)); if(yj<0.0) yj = 0.0; f[0] = 0.5*(yj + 2*x[0])*x[1] + 2.0*sum1 / (double)count1; f[1] = 0.5*(yj - 2*x[0] + 2.0)*x[1] + 2.0*sum2 / (double)count2; f[2] = 1.0 - x[1] + 2.0*sum3 / (double)count3; } void UF10(double *x, double *f, const unsigned int nx) { unsigned int j, count1, count2, count3; double sum1, sum2, sum3, yj, hj; sum1 = sum2 = sum3 = 0.0; count1 = count2 = count3 = 0; for(j = 3; j <= nx; j++) { yj = x[j-1] - 2.0*x[1]*sin(2.0*PI*x[0]+j*PI/nx); hj = 4.0*yj*yj - cos(8.0*PI*yj) + 1.0; if(j % 3 == 1) { sum1 += hj; count1++; } else if(j % 3 == 2) { sum2 += hj; count2++; } else { sum3 += hj; count3++; } } f[0] = cos(0.5*PI*x[0])*cos(0.5*PI*x[1]) + 2.0*sum1 / (double)count1; f[1] = cos(0.5*PI*x[0])*sin(0.5*PI*x[1]) + 2.0*sum2 / (double)count2; f[2] = sin(0.5*PI*x[0]) + 2.0*sum3 / (double)count3; } /****************************************************************************/ // 5-objctive test instances /****************************************************************************/ #define a 1 #define b 10 #define c 8 #define c1 (a+c/2) #define c2 (c+2*a) #define b1 (b/2) void R2_DTLZ2_M5(double *x, double *f, const unsigned int nx, const unsigned int n_obj) { int i=0,j=0; int k = nx - n_obj + 1; double g = 0; double sum = 0; //double z[nx],zz[nx],p[nx],psum[n_obj],M[nx][nx],lamda_l[nx]; double *z, *zz, *p, *psum, **M, *lamda_l; double M_10D[10][10]={{0.0346, -0.7523, 0.3561, -0.2958, 0.4675,0,0,0,0,0},{0.8159, -0.0423, 0.4063, 0.3455, -0.2192,0,0,0,0,0},{-0.3499, 0.3421, 0.8227, -0.2190, -0.1889,0,0,0,0,0},{-0.0963, -0.4747, -0.0998, -0.2429, -0.8345,0,0,0,0,0},{-0.4487, -0.2998, 0.1460, 0.8283, -0.0363,0,0,0,0,0},{0,0,0,0,0,1,0,0,0,0},{0,0,0,0,0,0,1,0,0,0},{0,0,0,0,0,0,0,1,0,0},{0,0,0,0,0,0,0,0,1,0},{0,0,0,0,0,0,0,0,0,1}}; double lamda_l_10D[10]={0.313,0.312,0.321,0.316,0.456,1,1,1,1,1}; double M_30D[30][30]={{0.0128,0.2165,0.4374,-0.0800,0.0886,-0.2015,0.1071,0.2886,0.2354,0.2785,-0.1748,0.2147,0.1649,-0.3043,0.5316,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.4813, 0.2420, -0.3663, -0.0420, -0.0088, -0.4945, -0.3073, 0.1990, 0.0441, -0.0627, 0.0191, 0.3880, -0.0618, -0.0319, -0.1833,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.4816, -0.2254, 0.0663, 0.4801, 0.2009, -0.0008, -0.1501, 0.0269, -0.2037,0.4334, -0.2157, -0.3175, -0.0923, 0.1451, 0.1118,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {-0.0876, -0.2667, -0.0063, 0.2114, 0.4506, 0.0823, -0.0125, 0.2313, 0.0840,-0.2376, 0.1938, -0.0030, 0.3391, 0.0863, 0.1231,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {-0.1025, 0.4011, -0.0117, 0.2076, 0.2585, 0.1124, -0.0288, 0.3095, -0.6146,-0.2376, 0.1938, -0.0030, 0.3391, 0.0863, 0.1231,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.4543, -0.2761, -0.2985, -0.2837, 0.0634, 0.1070, 0.2996, -0.2690, -0.1634,-0.1452, 0.1799, -0.0014, 0.2394, -0.2745, 0.3969,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {-0.1422, -0.4364, 0.0751, -0.2235, 0.3966, -0.0252, 0.0908, 0.0477, -0.2254,0.1801, -0.0552, 0.5770, -0.0396, 0.3765, -0.0522,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.3542, -0.2245, 0.3497, -0.1609, -0.1107, 0.0079, 0.2241, 0.4517, 0.1309,-0.3355, -0.1123, -0.1831, 0.3000, 0.2045, -0.3191,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.0005, 0.0377, -0.2808, -0.0641, 0.1316, 0.2191, 0.0207, 0.3308, 0.4117,0.3839, 0.5775, -0.1219, 0.1192, 0.2435, 0.0414,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {-0.1177, -0.0001, -0.1992, -0.4533, 0.4234, -0.0191, -0.3740, 0.1325, 0.0972,-0.2042, -0.3493, -0.4018, -0.1087, 0.0918, 0.2217,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.1818, 0.3022, -0.1388, -0.2380, -0.0773, 0.6463, 0.0450, 0.1030, -0.0958,0.2837, -0.3969, 0.1779, -0.0251, -0.1543, -0.2452,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {-0.1889, -0.4397, -0.2206, 0.0981, -0.5203, 0.1325, -0.3427, 0.4242, -0.1271,-0.0291, -0.0795, 0.1213, 0.0565, -0.1092, 0.2720,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {-0.1808, -0.0624, -0.2689, 0.2289, 0.1128, -0.0844, -0.0549, -0.2202, 0.2450,0.0825, -0.3319, 0.0513, 0.7523, 0.0043, -0.1472,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {-0.0983, 0.0611, -0.4145, 0.3017, 0.0410, -0.0703, 0.6250, 0.2449, 0.1307,-0.1714, -0.3045, 0.0218, -0.2837, 0.1408, 0.1633,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0.2026, 0.0324, 0.1496, 0.3129, 0.1437, 0.4331, -0.2629, -0.1498, 0.3746,-0.4366, 0.0163, 0.3316, -0.0697, 0.1833, 0.2412,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}; double lamda_l_30D[30]={0.113,0.105,0.117,0.119,0.108,0.110,0.101,0.107,0.111,0.109,0.120,0.108,0.101,0.105,0.116,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000}; z = new double[nx]; zz = new double[nx]; p = new double[nx]; psum = new double[n_obj]; M = new double*[nx]; for(i=0; i<nx; i++) M[i] = new double[nx]; lamda_l = new double[nx]; if (nx==10) { for (i=0;i<nx;i++) { for (j=0;j<nx;j++) { M[i][j]=M_10D[i][j]; } lamda_l[i]=lamda_l_10D[i]; } } else { for (i=0;i<nx;i++) { for (j=0;j<nx;j++) { M[i][j]=M_30D[i][j]; } lamda_l[i]=lamda_l_30D[i]; } } for (i=0;i<nx;i++) { z[i]=0; for (j=0;j<nx;j++) { z[i]+=M[i][j]*x[j]; } if (z[i]>=0 && z[i]<=1) { zz[i]=z[i]; p[i]=0; } else if (z[i]<0) { zz[i]=-lamda_l[i] * z[i]; p[i]=-z[i]; } else { zz[i]=1-lamda_l[i]*(z[i]-1); p[i]=z[i]-1; } } for(j=0;j<n_obj;j++) { psum[j] = 0; } for (i = nx - k + 1; i <= nx; i++) { g += pow(zz[i-1]-0.5,2); for(j=0;j<n_obj;j++) { psum[j]= sqrt( pow(psum[j],2) + pow(p[i-1],2) ); } } for (i = 1; i <= n_obj; i++) { double ff = (1 + g); for (j = n_obj - i; j >= 1; j--) { ff *= cos(zz[j-1] * PI / 2.0); psum[i-1] = sqrt( pow(psum[i-1],2) + pow(p[j-1],2) ); } if (i > 1) { ff *= sin(zz[(n_obj - i + 1) - 1] * PI / 2.0); psum[i-1] = sqrt( pow(psum[i-1],2) + pow(p[(n_obj - i + 1) - 1],2) ); } f[i-1] = 2.0/(1+exp(-psum[i-1])) * (ff+1); } delete []z; delete []zz; delete []p;delete []psum; delete []lamda_l; for(i=0; i<nx; i++) delete []M[i]; delete []M; } void R2_DTLZ3_M5(double *x, double *f, const unsigned int nx, const unsigned int n_obj) { int i=0,j=0; int k = nx - n_obj + 1; double g = 0; double sum = 0; //double z[nx],zz[nx],p[nx],psum[n_obj],M[nx][nx],lamda_l[nx]; double *z, *zz, *p, *psum, **M, *lamda_l; double M_10D[10][10]={{-0.2861, 0.2796, -0.8507, 0.2837, 0.1893,0,0,0,0,0},{0.2837, 0.8861, 0.1219, -0.3157, 0.1407,0,0,0,0,0},{0.6028, 0.1119, -0.0810, 0.5963, -0.5119,0,0,0,0,0},{-0.6450, 0.3465, 0.4447, 0.4753, -0.2005,0,0,0,0,0},{0.2414, -0.0635, 0.2391, 0.4883, 0.8013,0,0,0,0,0},{0,0,0,0,0,1,0,0,0,0},{0,0,0,0,0,0,1,0,0,0},{0,0,0,0,0,0,0,1,0,0},{0,0,0,0,0,0,0,0,1,0},{0,0,0,0,0,0,0,0,0,1}}; double lamda_l_10D[10]={0.313,0.312,0.321,0.316,0.456,1,1,1,1,1}; double M_30D[30][30]={{-0.1565, -0.2418, 0.5427, -0.2191, 0.2522, -0.0563, 0.1991, 0.1166, 0.2140,-0.0973, -0.0755, 0.4073, 0.4279, -0.1876, -0.0968,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.1477, -0.2396, -0.0022, 0.4180, 0.2675, -0.1365, -0.0729, 0.4761, -0.0685,0.2105, 0.1388, 0.1465, -0.0256, 0.0292, 0.5767,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.0322, 0.3727, -0.0467, 0.1651, -0.0672, 0.0638, -0.1168, 0.4055, 0.6714,-0.1948, -0.1451, 0.1734, -0.2788, -0.0769, -0.1433,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {-0.3688, 0.1935, 0.3691, 0.4298, 0.2340, 0.2593, -0.3081, -0.2013, -0.2779,-0.0932, 0.0003, 0.0149, -0.2303, -0.3261, -0.0517,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.0580, -0.0609, 0.0004, -0.1831, 0.0003, 0.4742, -0.2530, -0.0750, 0.0839,0.1606, 0.6020, 0.4103, -0.0857, 0.2954, -0.0819,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {-0.2145, -0.0056, -0.0251, 0.2288, -0.4870, -0.5486, 0.1253, -0.1512, -0.0390,0.0722, 0.3074, 0.4160, -0.1304, -0.1610, -0.0848,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.2557, -0.1087, 0.0679, -0.3120, 0.3567, -0.4644, -0.3535, 0.1060, -0.2158,-0.1330, -0.0154, 0.0911, -0.4154, 0.0356, -0.3085,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.2303, 0.4996, 0.1883, 0.1870, 0.1850, -0.0216, 0.4409, -0.0573, -0.2396,0.1471, -0.1540, 0.2731, -0.0398, 0.4505, -0.1131,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {-0.1576, -0.0023, 0.2588, 0.2105, 0.2250, -0.2978, 0.0175, -0.1157, 0.3717,0.0562, 0.4068, -0.5081, 0.0718, 0.3443, -0.1488,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.1047, -0.0568, -0.2771, 0.3803, 0.0046, 0.0188, -0.1500, 0.2053, -0.2290,-0.4582, 0.1191, 0.0639, 0.4946, 0.1121, -0.4018,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.3943, -0.0374, 0.3004, 0.1472, -0.2988, 0.0443, -0.2483, 0.1350, -0.0160,0.5834, -0.1095, -0.1398, 0.1711, -0.1867, -0.3518,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000,0.000}, {0.1244, -0.6134, 0.1823, 0.3012, -0.1968, 0.1616, 0.1025, -0.1972, 0.1162,-0.2079, -0.3062, 0.0585, -0.3286, 0.3187, -0.0812,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0.1832, -0.1559, -0.4327, 0.2059, 0.4677, 0.0317, 0.2233, -0.3589, 0.2393,0.2468, 0.0148, 0.1193, -0.0279, -0.3600, -0.2261,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0.5027, 0.1935, 0.1571, 0.0503, -0.0503, -0.1443, -0.3080, -0.4939, 0.1847,-0.2762, 0.0042, 0.0960, 0.2239, -0.0579, 0.3840,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0.3948, -0.0002, 0.2172, -0.0293, -0.0835, 0.1614, 0.4559, 0.1626, -0.1155,-0.3087, 0.4331, -0.2223, -0.2213, -0.3658, -0.0188,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}}; double lamda_l_30D[30]={0.113,0.105,0.117,0.119,0.108,0.110,0.101,0.107,0.111,0.109,0.120,0.108,0.101,0.105,0.116,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000,1.000}; z = new double[nx]; zz = new double[nx]; p = new double[nx]; psum = new double[n_obj]; M = new double*[nx]; for(i=0; i<nx; i++) M[i] = new double[nx]; lamda_l = new double[nx]; if (nx==10) { for (i=0;i<nx;i++) { for (j=0;j<nx;j++) { M[i][j]=M_10D[i][j]; } lamda_l[i]=lamda_l_10D[i]; } } else { for (i=0;i<nx;i++) { for (j=0;j<nx;j++) { M[i][j]=M_30D[i][j]; } lamda_l[i]=lamda_l_30D[i]; } } for (i=0;i<nx;i++) { z[i]=0; for (j=0;j<nx;j++) { z[i]+=M[i][j]*x[j]; } if (z[i]>=0 && z[i]<=1) { zz[i]=z[i]; p[i]=0; } else if (z[i]<0) { zz[i]=-lamda_l[i] * z[i]; p[i]=-z[i]; } else { zz[i]=1-lamda_l[i]*(z[i]-1); p[i]=z[i]-1; } } for(j=0;j<n_obj;j++) { psum[j] = 0; } for (i = nx - k + 1; i <= nx; i++) { g += pow(zz[i-1]-0.5,2) - cos(20 * PI * (zz[i-1]-0.5)); for(j=0;j<n_obj;j++) { psum[j]= sqrt( pow(psum[j],2) + pow(p[i-1],2) ); } } g = 100 * (k + g); for (i = 1; i <= n_obj; i++) { double ff = (1 + g); for (j = n_obj - i; j >= 1; j--) { ff *= cos(zz[j-1] * PI / 2.0); psum[i-1] = sqrt( pow(psum[i-1],2) + pow(p[j-1],2) ); } if (i > 1) { ff *= sin(zz[(n_obj - i + 1) - 1] * PI / 2.0); psum[i-1] = sqrt( pow(psum[i-1],2) + pow(p[(n_obj - i + 1) - 1],2) ); } f[i-1] = 2.0/(1+exp(-psum[i-1])) * (ff+1); } delete []z; delete []zz; delete []p;delete []psum; delete []lamda_l; for(i=0; i<nx; i++) delete []M[i]; delete []M; } //// Implemented constants. ///////////////////////////////////////////////// #define EPSILON (1.0e-10) double correct_to_01(double aa, double epsilon) { double min = 0.0, max = 1.0; double min_epsilon = min - epsilon; double max_epsilon = max + epsilon; if ( aa <= min && aa >= min_epsilon ) { return min; } else if ( aa >= max && aa <= max_epsilon ) { return max; } else { return aa; } } int vector_in_01( const double *x, int nx ) { int i; for( i = 0; i < nx; i++ ) { if( x[i] < 0.0 || x[i] > 1.0 ) { return 0; } } return 1; } //// Local functions/values. //////////////////////////////////////////////// double linear( const double *x, const int m,int M ) { int i; double result = 1.0; for( i=1; i <= M-m; i++ ) { result *= x[i-1]; } if( m != 1 ) { result *= 1 - x[M-m]; } return correct_to_01( result, EPSILON ); } double convex( const double *x, const int m,int M ) { int i; double result = 1.0; for( i=1; i <= M-m; i++ ) { result *= 1.0 - cos( x[i-1]*PI/2.0 ); } if( m != 1 ) { result *= 1.0 - sin( x[M-m]*PI/2.0 ); } return correct_to_01( result, EPSILON ); } double concave( const double *x, const int m,int M ) { int i; double result = 1.0; for( i=1; i <= M-m; i++ ) { result *= sin( x[i-1]*PI/2.0 ); } if( m != 1 ) { result *= cos( x[M-m]*PI/2.0 ); } return correct_to_01( result, EPSILON ); } double mixed( const double *x, const int A, const double alpha ) { const double tmp = 2.0*A*PI; return correct_to_01( pow( 1.0-x[0]-cos( tmp*x[0] + PI/2.0 )/tmp, alpha ), EPSILON ); } double disc( const double *x, const int A, const double alpha, const double beta ) { const double tmp1 = A*pow( x[0], beta )*PI; return correct_to_01( 1.0 - pow( x[0], alpha )*pow( cos( tmp1 ), 2.0 ), EPSILON ); } //** Calculate the minimum of two doubles. ********************************** static double min_double( const double aa, const double bb ) { return aa < bb ? aa : bb; } //// Implemented functions. ///////////////////////////////////////////////// double b_poly( const double y, const double alpha ) { return correct_to_01( pow( y, alpha ), EPSILON ); } double b_flat ( const double y, const double A, const double B, const double C ) { const double tmp1 = min_double( 0.0, floor( y-B ) ) * A*( B-y )/B; const double tmp2 = min_double( 0.0, floor( C-y ) ) * ( 1.0-A )*( y-C )/( 1.0-C ); return correct_to_01( A+tmp1-tmp2, EPSILON ); } double b_param ( const double y, const double u, const double A, const double B, const double C ) { const double v = A - ( 1.0-2.0*u )*fabs( floor( 0.5-u )+A ); return correct_to_01( pow( y, B + ( C-B )*v ), EPSILON ); } double s_linear( const double y, const double A ) { return correct_to_01( fabs( y-A )/fabs( floor( A-y )+A ), EPSILON ); } double s_decept(const double y, const double A, const double B, const double C ) { const double tmp1 = floor( y-A+B )*( 1.0-C+( A-B )/B )/( A-B ); const double tmp2 = floor( A+B-y )*( 1.0-C+( 1.0-A-B )/B )/( 1.0-A-B ); return correct_to_01( 1.0 + ( fabs( y-A )-B )*( tmp1 + tmp2 + 1.0/B ), EPSILON ); } double s_multi ( const double y, const int A, const double B, const double C ) { const double tmp1 = fabs( y-C )/( 2.0*( floor( C-y )+C ) ); const double tmp2 = ( 4.0*A+2.0 )*PI*( 0.5-tmp1 ); return correct_to_01( ( 1.0 + cos( tmp2 ) + 4.0*B*pow( tmp1, 2.0 ) )/( B+2.0 ), EPSILON ); } double r_sum( const double *y, const double *w, int ny) { int i; double numerator = 0.0; double denominator = 0.0; for( i = 0; i < ny; i++ ) { numerator += w[i]*y[i]; denominator += w[i]; } return correct_to_01( numerator / denominator, EPSILON ); } double r_nonsep( const double *y, const int A, int ny) { const int y_len = ny; int j; double numerator = 0.0; for( j = 0; j < y_len; j++ ) { int k; numerator += y[j]; for( k = 0; k <= A-2; k++ ) { numerator += fabs( y[j] - y[( j+k+1 ) % y_len] ); } } { const double tmp = ceil( A/2.0 ); const double denominator = y_len*tmp*( 1.0 + 2.0*A - 2.0*tmp )/A; return correct_to_01( numerator / denominator, EPSILON ); } } void WFG1_M5( double *z, double *f, const unsigned int nx, const unsigned int M) { int i,j; double y[30],t1[30],t2[30],t3[30],t4[5]; const int k=M==2?4:2*(M-1); for( i = 0; i < nx; i++ ) { y[i] = z[i] / (2.0*( i+1 )); } //y = WFG1_t1(y, k); for( i = 0; i < k; i++ ) { t1[i] = y[i]; } for( i = k; i < nx; i++ ) { t1[i] = s_linear( y[i], 0.35 ); } //y = WFG1_t2(y, k); for( i = 0; i < k; i++ ) { t2[i] = t1[i]; } for( i = k; i < nx; i++ ) { t2[i] = b_flat( t1[i], 0.8, 0.75, 0.85 ); } //y = WFG1_t3(y); for( i = 0; i < nx; i++ ) { t3[i] = b_poly( t2[i], 0.02 ); } //y = WFG1_t4( y,k,M,nx); { double w[30]; double y_sub[30],w_sub[30]; double y_sub2[30],w_sub2[30]; for( i = 1; i <= nx; i++) { w[i-1] = 2.0*i; } for( i = 1; i <= M-1; i++ ) { const int head = ( i-1 )*k/( M-1 ); const int tail = i*k/( M-1 ); for( j = head; j < tail; j++ ) { y_sub[j-head] = t3[j]; w_sub[j-head] = w[j]; } t4[i-1] = r_sum( y_sub, w_sub,tail-head ); } for( j = k; j < nx; j++ ) { y_sub2[j-k] = t3[j]; w_sub2[j-k] = w[j]; } t4[i-1] = r_sum( y_sub2, w_sub2,nx-k ); } //shape { int m; short A[5]; double x[5],h[5],S[5]; A[0] = 1; for( i = 1; i < M-1; i++ ) { A[i] = 1; } for( i = 0; i < M-1; i++ ) { double tmp1; tmp1 = t4[M-1]; if( A[i] > tmp1 ) tmp1 = A[i]; x[i] = tmp1*( t4[i] - 0.5 ) + 0.5; } x[M-1] = t4[M-1]; for( m = 1; m <= M-1; m++ ) { h[m-1] = convex( x, m,M ); } h[m-1] = mixed( x, 5, 1.0 ); for( m = 1; m <= M; m++ ) { S[m-1] = m*2.0; } for( i = 0; i < M; i++ ) { f[i] = 1.0*x[M-1] + S[i]*h[i]; } } } }
[ [ [ 1, 934 ] ] ]
936d58573f311a6a5470bf6a8a71781959a47466
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/dialog/src/processors/ConditionProcessor.cpp
69ff1cd1d3c1ffb17bbc36d9a8e2c34d04f147c6
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,562
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 <string> #include <CEGUIPropertyHelper.h> #include "XmlHelper.h" #include "CoreSubsystem.h" #include "RulesSubsystem.h" #include "Interpreter.h" #include "Creature.h" #include "QuestBook.h" #include "Quest.h" #include "Utils.h" #include "DialogSubsystem.h" #include "DialogCharacter.h" #include "DialogScriptObject.h" #include "processors/ConditionProcessor.h" using namespace std; namespace rl { CeGuiString ConditionProcessor::process(DOMNode* node,Match* m, const CeGuiString& str, NaturalLanguageProcessor* nlp) { CeGuiString buffer; CeGuiString typeInfo; // get attributes CeGuiString conditionContext = XmlHelper::getAttributeValueAsString( static_cast<DOMElement*>(node), "context" ); CeGuiString conditionType = XmlHelper::getAttributeValueAsString( static_cast<DOMElement*>(node), "type" ); CeGuiString conditionName = XmlHelper::getAttributeValueAsString( static_cast<DOMElement*>(node), "name" ); int rVal = 0; int tmpVal = 0;//XmlHelper::getAttributeValueAsInteger( (DOMElement*)node,XMLString::transcode("value") ); int modifier = 0; if(static_cast<DOMElement*>(node)->hasAttribute((XMLCh*)"mod")) { modifier = XmlHelper::getAttributeValueAsInteger( static_cast<DOMElement*>(node), "mod" ); } DialogScriptObject* scriptObject = (static_cast<DialogCharacter*>(nlp))->getScriptObject(); Quest* quest = NULL; if(conditionType == "quest" || conditionType == "Quest") { quest = RulesSubsystem::getSingletonPtr()->getQuestBook()->getQuest(conditionName); } else if(conditionType == "Talent") { typeInfo = " (T) "; rVal = scriptObject->getDialogCharacter()->doTalentprobe(conditionName, modifier); } else if (conditionType == "Eigenschaft") { typeInfo = " (E) "; rVal = scriptObject->getDialogCharacter()->doEigenschaftsprobe(conditionName, modifier); } else if(conditionType == "Basiswert") { } else if(conditionType == "Predicate") { // ToDo, resp. check if there should be something done here } else { if(conditionContext == "response") { rVal = scriptObject->calcResponseValue(conditionName); } else if(conditionContext == "option") { rVal = scriptObject->calcOptionValue(conditionName); } else if(conditionContext == "selection") { rVal = scriptObject->calcSelectionValue(conditionName); } } bool conditionChild = false; if(XmlHelper::transcodeToString( node->getParentNode()->getNodeName()).compare("li") == 0) { conditionChild = true; buffer += typeInfo; buffer += "<option type=\"" + conditionType + "\" "; buffer += "name=\"" + conditionName + "\" "; buffer += ">"; } // Search through all li-elements for (DOMNode* childNode = node->getFirstChild(); childNode != NULL; childNode = childNode->getNextSibling() ) { if ( childNode->getNodeType() == DOMNode::ELEMENT_NODE ) { CeGuiString nodeName = XmlHelper::transcodeToString( childNode->getNodeName()); if(nodeName.compare("li") == 0) { //tmpVal = XmlHelper::getAttributeValueAsInteger( // static_cast<DOMElement*>(childNode), "value" ); CeGuiString strValue = XmlHelper::getAttributeValueAsString( static_cast<DOMElement*>(childNode), "value" ); std::string sValue = XmlHelper::getAttributeValueAsStdString( static_cast<DOMElement*>(childNode), "value" ); std::string id = XmlHelper::getAttributeValueAsStdString( static_cast<DOMElement*>(childNode), "id" ); tmpVal = CEGUI::PropertyHelper::stringToInt(strValue); bool conditionFulfilled = false; // Add elements in <li> Tag only if <li>-value = return value of the named function if(conditionContext == "selection") { conditionFulfilled = true; } else if(conditionType == "Predicate") { CeGuiString predicate = nlp->getPredicates().getPredicate( conditionName, "default"); if(!predicate.empty()) { conditionFulfilled = (predicate == strValue); } } else if ( (conditionType == "Talent" || conditionType == "Eigenschaft") ) { if( (rVal > 0 && tmpVal > 0) || (rVal <= 0 && tmpVal == 0)) { conditionFulfilled = true; } } else if(quest != NULL) { conditionFulfilled = (tmpVal == quest->getState()); } else { conditionFulfilled = (tmpVal == rVal); } if(conditionFulfilled) { CeGuiString temp = nlp->process(childNode, m, str); if(conditionContext.empty()) { // used for postprocessing of the option-tag when // checking for skills(talents) buffer += id + " " + temp; } else if(conditionContext == "selection") { buffer += "<li id=\"" + id + "\" "; buffer += "value=\"" + sValue + "\" "; buffer += ">"; buffer += temp; buffer += "</li>"; } else { buffer += "<li id=\"" + id + "\" "; buffer += "value=\"" + sValue + "\" "; buffer += "/>"; buffer += temp; } } // end if conditionFulfilled } // end compare nodeName } // end compare nodeType else if( childNode->getNodeType() == DOMNode::TEXT_NODE ) { CeGuiString text = XmlHelper::transcodeToString( static_cast<DOMText*>(childNode)->getData()); if( !normalise(text).empty()) { buffer += nlp->process(node, m, str); return buffer; } } } // end for loop if(conditionChild) { buffer += "</option>"; } return buffer; } }// Namespace rl end
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 220 ] ] ]
2550c1747c72f7cdfd0068a7d5873346a59f0dab
7f6fe18cf018aafec8fa737dfe363d5d5a283805
/ntk/interface/src/filepanel.cpp
8f075fe1a4dc0e05a86a9fdf07413c80d0499940
[]
no_license
snori/ntk
4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba
86d1a32c4ad831e791ca29f5e7f9e055334e8fe7
refs/heads/master
2020-05-18T05:28:49.149912
2009-08-04T16:47:12
2009-08-04T16:47:12
268,861
2
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,520
cpp
/****************************************************************************** The NTK Library Copyright (C) 1998-2003 Noritaka Suzuki $Id: filepanel.cpp,v 1.1 2003/11/11 12:07:08 nsuzuki Exp $ ******************************************************************************/ #define NTK_BUILD #include "ntk/interface/filepanel.h" #include <stdlib.h> #include <assert.h> #include <windows.h> #include <ntk/application/application.h> namespace ntk { //######################################################## // public methods FilePanel::FilePanel(PanelMode mode, const Messenger& target, Message* message, bool modal, bool hide_when_done) : m_panel_mode(mode) { if(target.is_valid()) m_messenger = new Messenger(target); else m_messenger = new Messenger(NULL, application()); if(message) m_message = message; else if(mode == OPEN_PANEL) m_message = new Message(REFS_RECEIVED); else if(mode == SAVE_PANEL) m_message = new Message(SAVE_REQUESTED); else assert(false && "FilePanel: Illegal Mode"); } FilePanel::~FilePanel() { delete m_messenger; delete m_message; } void FilePanel::show() { enum{ BUF_SIZE = 512 }; char buf[BUF_SIZE]; buf[0] = '\0'; OPENFILENAME m_info; memset(&m_info, 0, sizeof(m_info)); m_info.lStructSize = sizeof(m_info); m_info.hwndOwner = NULL; m_info.lpstrFilter = "*"; m_info.nMaxFile = BUF_SIZE; m_info.lpstrFile = buf; int ret = 0; if(panel_mode() == OPEN_PANEL) { m_info.Flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; m_info.lpstrTitle = "開く"; ret = GetOpenFileName(&m_info); } else { m_info.lpstrTitle = "名前を付けて保存"; ret = GetSaveFileName(&m_info); } if(ret) { Message message(*m_message); message.add_string("name", buf); m_messenger->send_message(message); } } FilePanel::PanelMode FilePanel::panel_mode() const { return m_panel_mode; } void FilePanel::set_panel_mode(PanelMode mode) { m_panel_mode = mode; assert(false);// currently not supported } const Messenger& FilePanel::messenger() const { return *m_messenger; } void FilePanel::set_target(const Messenger& target) { *m_messenger = target; } const Message& FilePanel::message() const { return *m_message; } void FilePanel::set_message(Message* message) { delete m_message; m_message = message; } //######################################################## }// namespace ntk
[ [ [ 1, 126 ] ] ]
f480379ac7d27a89e849da273f61a1a48d04b571
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/LuaPlus/Src/Modules/Misc/MemFile.h
255fbe36ad65aa45f0a718f2afef449f2e5afd7a
[ "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,061
h
#ifndef MEMFILE_H #define MEMFILE_H #include "File.h" #include <stdio.h> namespace Misc { /** **/ class MemFile : public File { public: MemFile(); virtual ~MemFile(); void SetGrowAmount(size_t growAmount); void Attach(const BYTE* buffer, size_t bufferSize, size_t growAmount = 0); BYTE* Detach(); virtual bool Open(const char* fileName, UINT openFlags = File::MODE_READONLY); virtual void Close(); virtual ULONGLONG GetPosition() const; virtual ULONGLONG GetLength() const; virtual void SetLength(ULONGLONG dwNewLen); virtual LONGLONG Seek(LONGLONG offset, SeekFlags seekFlags = SEEKFLAG_BEGIN); virtual ULONGLONG Read(void* buffer, ULONGLONG count); virtual ULONGLONG Write(const void* buffer, ULONGLONG count); BYTE* GetBuffer() { return this->buffer; } void GrowBuffer(ULONGLONG newBufferSize); private: size_t growAmount; ULONGLONG position; ULONGLONG bufferSize; ULONGLONG fileSize; BYTE* buffer; bool ownBuffer; }; } // namespace Misc #endif // MEMFILE_H
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
[ [ [ 1, 48 ] ] ]