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
8314e506353125eb7d02951cc5e52531b6e3f731
5ff30d64df43c7438bbbcfda528b09bb8fec9e6b
/kcore/base/Types.h
c7e21d79c1e4755ef693d3dc6749d895194b5b42
[]
no_license
lvtx/gamekernel
c80cdb4655f6d4930a7d035a5448b469ac9ae924
a84d9c268590a294a298a4c825d2dfe35e6eca21
refs/heads/master
2016-09-06T18:11:42.702216
2011-09-27T07:22:08
2011-09-27T07:22:08
38,255,025
3
1
null
null
null
null
UTF-8
C++
false
false
843
h
#pragma once typedef unsigned char byte; typedef unsigned short ushort; typedef unsigned long ulong; typedef unsigned int uint; typedef unsigned long uint4; typedef unsigned __int64 uint8; typedef long long longlong; typedef long int4; typedef __int64 int8; #ifdef _UNICODE #define tstring std::wstring #define tofstream std::wofstream #define tifstream std::wifstream #define tostream std::wostream #define tistream std::wifstream #define tostringstream std::wostringstream #else #define tstring std::string #define tofstream std::ofstream #define tifstream std::ifstream #define tostream std::ostream #define tistream std::ifstream #define tostringstream std::ostringstream #endif // use result instead of bool or int code #include <kcore/base/Result.h>
[ "darkface@localhost" ]
[ [ [ 1, 32 ] ] ]
ba1f1cf8fe698675af7df20e72330512faa67295
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Local Map 2/SensorCallbacks.cpp
b821e5d906d1d3b0f8aca90c7a7bd2fa5b3ca2bb
[]
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
31,824
cpp
#include "SensorCallbacks.h" void ClusteredIbeoCallback(const vector<LidarCluster> &IbeoMessage, double IbeoTime, void* Arg) { /* The callback for received Ibeo data. Creates an Ibeo event and adds it to the event queue. INPUTS: IbeoMessage - the cluster data packet IbeoTime - the vehicle time stamp, in seconds Arg - a void pointer for extra information OUTPUTS: none. (Adds an Ibeo event to the event queue) */ int i; int j; //count the number of clusters int nc; nc = (int) IbeoMessage.size(); //extract the event time double iEventTime; iEventTime = IbeoTime; //check the event time for valid timestamp extern CarTime* TheCarTime; double cct = TheCarTime->CurrentCarTime(); if (fabs(iEventTime - cct) > CT_TIMEJUMPREJECT) { //do not allow events with inconsistent timestamps into the event queues printf("Warning: got clustered ibeo timestamp %.12lg; expected something near %.12lg\n", iEventTime, cct); return; } //count the total number of points in all clusters LidarCluster cc; int np = 0; for (i = 0; i < nc; i++) { //count the total number of ibeo points cc = IbeoMessage[i]; np += (int) cc.pts.size(); } //declare memory for the whole Ibeo packet double* iEventData = NULL; if (np > 0) { iEventData = new double[np*LM_CLUSTEREDIBEOPACKETSIZE]; } int idx = 0; for (i = 0; i < nc; i++) { //pull all the points from the ith cluster cc = IbeoMessage[i]; int npc = (int) cc.pts.size(); for (j = 0; j < npc; j++) { //timestamp iEventData[midx(idx, 0, np)] = iEventTime; //point index iEventData[midx(idx, 1, np)] = (double) idx; //total number of points iEventData[midx(idx, 2, np)] = (double) np; //cluster ID (0 - nc-1, the cluster ID) iEventData[midx(idx, 3, np)] = (double) i; //cluster stability flag (0 = stable, 1 = unstable) if (cc.stable == true) { iEventData[midx(idx, 4, np)] = 0.0; } else { iEventData[midx(idx, 4, np)] = 1.0; } //cluster occlusion flag (0 = not occluded, 1 = CCW occluded, 2 = CW occluded, 3 = both occluded) iEventData[midx(idx, 5, np)] = 0.0; if (cc.leftOccluded == true) { iEventData[midx(idx, 5, np)] += 1.0; } if (cc.rightOccluded == true) { iEventData[midx(idx, 5, np)] += 2.0; } //cluster height flag (0 = low obstacle, 1 = high obstacle) if (cc.highObstacle == false) { iEventData[midx(idx, 6, np)] = 0.0; } else { iEventData[midx(idx, 6, np)] = 1.0; } //the point itself, xyz coordinates off the center ibeo iEventData[midx(idx, 7, np)] = cc.pts[j].x; iEventData[midx(idx, 8, np)] = cc.pts[j].y; iEventData[midx(idx, 9, np)] = cc.pts[j].z; idx++; } } //when the code gets here, iEventData is populated with a complete sensor packet //this will be used to create each new event as it arrives Event *NewEvent; NewEvent = new Event(); NewEvent->SetEventType(IBEO_EVENT, iEventTime); NewEvent->SetEventData(np, LM_CLUSTEREDIBEOPACKETSIZE, iEventData); #ifdef LM_PRINTLOGS //create a separate logging event with the same data Event* LogEvent = new Event(NewEvent); #endif //access to the local map event queue extern SynchronizedEventQueue* TheLocalMapEventQueue; //drop the event onto the event queue bool spush = TheLocalMapEventQueue->PushEvent(NewEvent); #ifdef LM_PRINTLOGS //only log the packet if it successfully entered the event queue extern EventQueue* TheLoggingQueue; if (spush == true) { TheLoggingQueue->PushEvent(LogEvent); } else { delete LogEvent; } #endif return; } void ClusteredSickCallback(const vector<LidarCluster> &CSMessage, double SickTime, void* Arg) { /* The callback for received clustered horizontal SICK data. Creates an event and adds it to the event queue. INPUTS: CSMessage - the cluster data packet SickTime - the vehicle time stamp, in seconds Arg - a void pointer for extra information OUTPUTS: none. (Adds an Ibeo event to the event queue) */ int i; int j; //count the number of clusters int nc; nc = (int) CSMessage.size(); //extract the event time double iEventTime; iEventTime = SickTime; //check the event time for valid timestamp extern CarTime* TheCarTime; double cct = TheCarTime->CurrentCarTime(); if (fabs(iEventTime - cct) > CT_TIMEJUMPREJECT) { //do not allow events with inconsistent timestamps into the event queues printf("Warning: got clustered sick timestamp %.12lg; expected something near %.12lg\n", iEventTime, cct); return; } //count the total number of points in all clusters LidarCluster cc; int np = 0; for (i = 0; i < nc; i++) { //count the total number of ibeo points cc = CSMessage[i]; np += (int) cc.pts.size(); } //declare memory for the whole Ibeo packet double* iEventData = NULL; if (np > 0) { iEventData = new double[np*LM_CLUSTEREDSICKPACKETSIZE]; } int idx = 0; for (i = 0; i < nc; i++) { //pull all the points from the ith cluster cc = CSMessage[i]; int npc = (int) cc.pts.size(); for (j = 0; j < npc; j++) { //timestamp iEventData[midx(idx, 0, np)] = iEventTime; //point index iEventData[midx(idx, 1, np)] = (double) idx; //total number of points iEventData[midx(idx, 2, np)] = (double) np; //cluster ID (0 - nc-1, the cluster ID) iEventData[midx(idx, 3, np)] = (double) i; //cluster stability flag (0 = stable, 1 = unstable) if (cc.stable == true) { iEventData[midx(idx, 4, np)] = 0.0; } else { iEventData[midx(idx, 4, np)] = 1.0; } //cluster occlusion flag (0 = not occluded, 1 = CCW occluded, 2 = CW occluded, 3 = both occluded) iEventData[midx(idx, 5, np)] = 0.0; if (cc.leftOccluded == true) { iEventData[midx(idx, 5, np)] += 1.0; } if (cc.rightOccluded == true) { iEventData[midx(idx, 5, np)] += 2.0; } /* //cluster height flag (0 = low obstacle, 1 = high obstacle) if (cc.highObstacle == false) { iEventData[midx(idx, 6, np)] = 0.0; } else { iEventData[midx(idx, 6, np)] = 1.0; } */ //call all clustered SICK points high obstacles for now iEventData[midx(idx, 6, np)] = 1.0; //the point itself, xyz coordinates off the SICK iEventData[midx(idx, 7, np)] = cc.pts[j].x; iEventData[midx(idx, 8, np)] = cc.pts[j].y; iEventData[midx(idx, 9, np)] = cc.pts[j].z; idx++; } } //when the code gets here, iEventData is populated with a complete sensor packet //this will be used to create each new event as it arrives Event *NewEvent; NewEvent = new Event(); NewEvent->SetEventType(BACKCLUSTEREDSICK_EVENT, iEventTime); NewEvent->SetEventData(np, LM_CLUSTEREDSICKPACKETSIZE, iEventData); #ifdef LM_PRINTLOGS //create a separate logging event with the same data Event* LogEvent = new Event(NewEvent); #endif //access to the local map event queue extern SynchronizedEventQueue* TheLocalMapEventQueue; //drop the event onto the event queue bool spush = TheLocalMapEventQueue->PushEvent(NewEvent); #ifdef LM_PRINTLOGS //only log the packet if it successfully entered the event queue extern EventQueue* TheLoggingQueue; if (spush == true) { TheLoggingQueue->PushEvent(LogEvent); } else { delete LogEvent; } #endif return; } void DelphiCallback(DelphiRadarScan DelphiMessage, DelphiInterfaceReceiver* DRX, int ID, void* Arg) { /* Called when a delphi radar packet is received INPUTS: DelphiMessage - the actual radar message DRX - pointer to the interface receiver (not used) ID - enumerated ID indicating which radar generated the measurement Arg - a void pointer (not used here) OUTPUTS: none. Formats delphi information and drops into the appropriate event queue */ //gain access to the event queue extern SynchronizedEventQueue* TheLocalMapEventQueue; int i; //number of targets detected by radar int nt = 0; double iEventTime = DelphiMessage.timestamp; //check the event time for valid timestamp extern CarTime* TheCarTime; double cct = TheCarTime->CurrentCarTime(); if (fabs(iEventTime - cct) > CT_TIMEJUMPREJECT) { //do not allow events with inconsistent timestamps into the event queues printf("Warning: got radar timestamp %.12lg; expected something near %.12lg\n", iEventTime, cct); return; } for (i = 0; i < DELPHI_NUM_TRACKS; i++) { //count the number of valid tracks if (DelphiMessage.tracks[i].isValid == true) { nt++; } } //declare space for the event data //NOTE: this memory is cleared automatically when the event is pulled from the queue Event* NewEvent = new Event(); int iEventType; double* iEventData = NULL; if (nt > 0) { iEventData = new double[nt*LM_DELPHIPACKETSIZE]; } int inr = nt; int inc = LM_DELPHIPACKETSIZE; int idx = 0; for (i = 0; i < DELPHI_NUM_TRACKS; i++) { //loop through and keep all valid tracks if (DelphiMessage.tracks[i].isValid == false) { //invalid track, ignore it continue; } //timestamp iEventData[midx(idx, 0, nt)] = iEventTime; //obstacle index in the packet iEventData[midx(idx, 1, nt)] = (double) idx; //total number of obstacles iEventData[midx(idx, 2, nt)] = (double) nt; //obstacle track ID number iEventData[midx(idx, 3, nt)] = (double) DelphiMessage.tracks[i].id; //measurement invalid flag if (DelphiMessage.status.errorCommunication == true || DelphiMessage.status.errorInternal == true || DelphiMessage.status.errorOverheat == true || DelphiMessage.status.errorRangePerformance == true || DelphiMessage.status.errorVoltage == true || DelphiMessage.status.isBlockageDetection == true || DelphiMessage.status.scanOperational == false || DelphiMessage.status.xvrOperational == false) { //the measurement was invalid iEventData[midx(idx, 4, nt)] = 1.0; } else { iEventData[midx(idx, 4, nt)] = 0.0; } //target scan count age iEventData[midx(idx, 5, nt)] = (double) DelphiMessage.tracks[i].counter; //combined object ID iEventData[midx(idx, 6, nt)] = (double) DelphiMessage.tracks[i].combinedObjectID; //target class ID iEventData[midx(idx, 7, nt)] = 0.0; if (DelphiMessage.tracks[i].isSidelobe == true) { iEventData[midx(idx, 7, nt)] = 1.0; } else if (DelphiMessage.tracks[i].isForwardTruckReflector == true) { iEventData[midx(idx, 7, nt)] = 2.0; } else if (DelphiMessage.tracks[i].isBridge == true) { iEventData[midx(idx, 7, nt)] = 3.0; } else if (DelphiMessage.tracks[i].isMatureObject == true) { iEventData[midx(idx, 7, nt)] = 4.0; } //target power iEventData[midx(idx, 8, nt)] = (double) DelphiMessage.tracks[i].power; //range to target (filtered) iEventData[midx(idx, 9, nt)] = (double) DelphiMessage.tracks[i].range; //range to target (unfiltered) iEventData[midx(idx, 10, nt)] = (double) DelphiMessage.tracks[i].rangeUnfiltered; //range rate (filtered) iEventData[midx(idx, 11, nt)] = (double) DelphiMessage.tracks[i].rangeRate; //range rate (unfiltered) iEventData[midx(idx, 12, nt)] = (double) DelphiMessage.tracks[i].rangeRateUnfiltered; //NOTE: delphi uses a left-handed coordinate frame, so negate all the angles //target bearing angle (filtered) iEventData[midx(idx, 13, nt)] = -(double) DelphiMessage.tracks[i].trackAngle; //target bearing angle (unfiltered) iEventData[midx(idx, 14, nt)] = -(double) DelphiMessage.tracks[i].trackAngleUnfiltered; //left and right unfiltered edge angles (rad.) iEventData[midx(idx, 15, nt)] = -(double) DelphiMessage.tracks[i].edgeAngleLeftUnfiltered; iEventData[midx(idx, 16, nt)] = -(double) DelphiMessage.tracks[i].edgeAngleRightUnfiltered; idx++; } switch (ID) { case DELPHI_Z_REAR0: iEventType = BACK0RADAR_EVENT; break; case DELPHI_X_DRIV3: iEventType = DRIV3RADAR_EVENT; break; case DELPHI_G_DRIV2: iEventType = DRIV2RADAR_EVENT; break; case DELPHI_F_DRIV1: iEventType = DRIV1RADAR_EVENT; break; case DELPHI_E_DRIV0: iEventType = DRIV0RADAR_EVENT; break; case DELPHI_D_FRONT0: iEventType = FRONT0RADAR_EVENT; break; case DELPHI_C_PASS0: iEventType = PASS0RADAR_EVENT; break; case DELPHI_B_PASS1: iEventType = PASS1RADAR_EVENT; break; case DELPHI_A_PASS2: iEventType = PASS2RADAR_EVENT; break; case DELPHI_Y_PASS3: iEventType = PASS3RADAR_EVENT; break; default: iEventType = INVALID_EVENT; break; } //store the event data in the event container NewEvent->SetEventType(iEventType, iEventTime); NewEvent->SetEventData(inr, inc, iEventData); #ifdef LM_PRINTLOGS //create a separate logging event with the same data Event* LogEvent = new Event(NewEvent); #endif //drop the event onto the event queue bool spush = TheLocalMapEventQueue->PushEvent(NewEvent); #ifdef LM_PRINTLOGS //only log the packet if it successfully entered the event queue extern EventQueue* TheLoggingQueue; if (spush == true) { TheLoggingQueue->PushEvent(LogEvent); } else { delete LogEvent; } #endif return; } void OdometryCallback(const pose_rel_msg& OdomMessage, void* Arg) { /* Called when an odometry packet is received INPUTS: OdomMessage - contains the odometry packet information Arg - a void pointer (not used here) OUTPUTS: none. Reformats the odometry inforamtion into an event and deposits the event into TheRelativePoseQueue. */ //gain access to the relative pose queue extern RelativePoseQueue* TheRelativePoseQueue; //timestamp double iEventTime = (double)(OdomMessage.car_ts_secs) + (double)(OdomMessage.car_ts_ticks)/10000.0; //check the event time for valid timestamp extern CarTime* TheCarTime; double cct = TheCarTime->CurrentCarTime(); if (fabs(iEventTime - cct) > CT_TIMEJUMPREJECT) { //do not allow events with inconsistent timestamps into the event queues printf("Warning: got odometry timestamp %.12lg; expected something near %.12lg\n", iEventTime, cct); return; } double iEventData[LM_ODOMPACKETSIZE]; iEventData[0] = iEventTime; //integration time dt iEventData[1] = OdomMessage.dt; //elements of the transformation matrix iEventData[2] = OdomMessage.Rinit2veh[0][0]; iEventData[3] = OdomMessage.Rinit2veh[1][0]; iEventData[4] = OdomMessage.Rinit2veh[2][0]; iEventData[5] = OdomMessage.Rinit2veh[0][1]; iEventData[6] = OdomMessage.Rinit2veh[1][1]; iEventData[7] = OdomMessage.Rinit2veh[2][1]; iEventData[8] = OdomMessage.Rinit2veh[0][2]; iEventData[9] = OdomMessage.Rinit2veh[1][2]; iEventData[10] = OdomMessage.Rinit2veh[2][2]; iEventData[11] = OdomMessage.Rinit2veh[0][3]; iEventData[12] = OdomMessage.Rinit2veh[1][3]; iEventData[13] = OdomMessage.Rinit2veh[2][3]; #ifdef LM_PRINTLOGS //create a separate logging event with the same data Event* LogEvent = new Event(); double* LogEventData = new double[LM_ODOMPACKETSIZE]; memcpy(LogEventData, iEventData, sizeof(double) * LM_ODOMPACKETSIZE); LogEvent->SetEventType(ODOM_EVENT, iEventTime); LogEvent->SetEventData(1, LM_ODOMPACKETSIZE, LogEventData); #endif //push the packet to the relative pose queue bool spush = TheRelativePoseQueue->PushPacket(iEventData); #ifdef LM_PRINTLOGS //only log the packet if it successfully entered the odometry queue extern EventQueue* TheLoggingQueue; if (spush == true) { TheLoggingQueue->PushEvent(LogEvent); } else { delete LogEvent; } #endif return; } void MobileyeObstacleCallback(MobilEyeObstacles MobileyeMessage, MobilEyeInterfaceReceiver* MRX, MobilEyeID ID, void* Arg) { /* Sensor callback for receiving obstacle packets from the Mobileyes INPUTS: MobileyeMessage - class containing the mobileye obstacle packet information MRX - Mobileye interface receiver (not used here) ID - enumerated value telling which mobileye camera generated the message Arg - void pointer (not used here) OUTPUTS: none. Creates an event for the mobileye information and pushes the event onto the appropriate event queue */ //gain access to the event queue extern SynchronizedEventQueue* TheLocalMapEventQueue; int i; int no = MobileyeMessage.numObstacles; double iEventTime; iEventTime = MobileyeMessage.carTime; //check the event time for valid timestamp extern CarTime* TheCarTime; double cct = TheCarTime->CurrentCarTime(); if (fabs(iEventTime - cct) > CT_TIMEJUMPREJECT) { //do not allow events with inconsistent timestamps into the event queues printf("Warning: got mobileye obstacle timestamp %.12lg; expected something near %.12lg\n", iEventTime, cct); return; } //declare space for the event data //NOTE: this memory is cleared automatically when the event is pulled from the queue Event* NewEvent = new Event(); int iEventType; double* iEventData = NULL; if (no > 0) { iEventData = new double[no*LM_MOBILEYEOBSTACLEPACKETSIZE]; } int inr = no; int inc = LM_MOBILEYEOBSTACLEPACKETSIZE; for (i = 0; i < no; i++) { //timestamp (should be the same for both road and environment message iEventData[midx(i, 0, no)] = iEventTime; //obstacle index in the packet iEventData[midx(i, 1, no)] = (double) i; //total number of obstacles iEventData[midx(i, 2, no)] = (double) no; //obstacle ID number iEventData[midx(i, 3, no)] = (double) (MobileyeMessage.obstacles[i].obstacleID); //obstacle forward distance from the camera iEventData[midx(i, 4, no)] = (double) (MobileyeMessage.obstacles[i].obstacleDistZ); //obstacle lateral distance from the camera if (MobileyeMessage.obstacles[i].obstacleDistXDirection == false) { //obstacle to the left of center iEventData[midx(i, 5, no)] = (double) (MobileyeMessage.obstacles[i].obstacleDistX); } else { //obstacle to the right of center iEventData[midx(i, 5, no)] = -(double) (MobileyeMessage.obstacles[i].obstacleDistX); } //obstacle forward relative speed double speed = (double) (MobileyeMessage.obstacles[i].velocity); if (_isnan(speed) != 0 || _finite(speed) == 0) { //if mobileye speed calculation is NaN or infinite, reject the entire frame printf("Warning: NaN or Inf encountered in Mobileye obstacle speed.\n"); delete NewEvent; delete [] iEventData; return; } iEventData[midx(i, 6, no)] = speed; //obstacle width iEventData[midx(i, 7, no)] = (double) (MobileyeMessage.obstacles[i].obstacleWidth); //obstacle path iEventData[midx(i, 8, no)] = (double) (MobileyeMessage.obstacles[i].path); //current in-path vehicle if (MobileyeMessage.obstacles[i].currentInPathVehicle == true) { iEventData[midx(i, 9, no)] = 1.0; } else { iEventData[midx(i, 9, no)] = 0.0; } //obstacle confidence iEventData[midx(i, 10, no)] = (double) (MobileyeMessage.obstacles[i].confidence); } switch (ID) { case MOBILEYE_CTR: iEventType = FRONTMOBILEYEOBSTACLE_EVENT; break; case MOBILEYE_REAR: iEventType = BACKMOBILEYEOBSTACLE_EVENT; break; default: iEventType = INVALID_EVENT; break; } //store the event data in the event container NewEvent->SetEventType(iEventType, iEventTime); NewEvent->SetEventData(inr, inc, iEventData); #ifdef LM_PRINTLOGS //create a separate logging event with the same data Event* LogEvent = new Event(NewEvent); #endif //drop the event onto the event queue bool spush = TheLocalMapEventQueue->PushEvent(NewEvent); #ifdef LM_PRINTLOGS //only log the packet if it successfully entered the event queue extern EventQueue* TheLoggingQueue; if (spush == true) { TheLoggingQueue->PushEvent(LogEvent); } else { delete LogEvent; } #endif return; } void MobileyeRoadCallback(MobilEyeRoadEnv MobileyeMessage, MobilEyeInterfaceReceiver* MRX, MobilEyeID ID, void* Arg) { /* Sensor callback for receiving road and environment packets from the Mobileyes INPUTS: MobileyeMessage - class containing the mobileye road / environment packet information MRX - Mobileye interface receiver (not used here) ID - enumerated value telling which mobileye camera generated the message Arg - void pointer (not used here) OUTPUTS: none. Creates an event for the mobileye information and pushes the event onto the event queue */ //gain access to the event queue extern SynchronizedEventQueue* TheLocalRoadEventQueue; double iEventTime = MobileyeMessage.road.carTime; //check the event time for valid timestamp extern CarTime* TheCarTime; double cct = TheCarTime->CurrentCarTime(); if (fabs(iEventTime - cct) > CT_TIMEJUMPREJECT) { //do not allow events with inconsistent timestamps into the event queues printf("Warning: got mobileye road timestamp %.12lg; expected something near %.12lg\n", iEventTime, cct); return; } //declare space for the event data //NOTE: this memory is cleared automatically when the event is pulled from the queue Event* NewEvent = new Event(); int iEventType; double* iEventData = new double[LM_MOBILEYEROADPACKETSIZE]; int inr = 1; int inc = LM_MOBILEYEROADPACKETSIZE; //timestamp (should be the same for both road and environment message) iEventData[0] = iEventTime; //left and right road edge distances (not danger zone) iEventData[1] = (double) MobileyeMessage.road.distToLeftEdge; iEventData[2] = (double) MobileyeMessage.road.distToRightEdge; //left and right lane distances for the car's current lane iEventData[3] = (double) MobileyeMessage.road.distToLeftMark; iEventData[4] = (double) MobileyeMessage.road.distToRightMark; //far left and far right lane line distances iEventData[5] = (double) MobileyeMessage.road.distToLeftNeighborMark; iEventData[6] = (double) MobileyeMessage.road.distToRightNeighborMark; //heading of the vehicle wrt the road iEventData[7] = (double) MobileyeMessage.road.roadModelSlope; //curvature of the road iEventData[8] = (double) MobileyeMessage.road.roadModelCurvature; //left and right road edge line mark types iEventData[9] = (double) MobileyeMessage.road.leftEdgeMarkType; iEventData[10] = (double) MobileyeMessage.road.rightEdgeMarkType; //left and right lane mark types iEventData[11] = (double) MobileyeMessage.road.leftMarkType; iEventData[12] = (double) MobileyeMessage.road.rightMarkType; //far left and far right lane mark types iEventData[13] = (double) MobileyeMessage.road.leftNeighborMarkType; iEventData[14] = (double) MobileyeMessage.road.rightNeighborMarkType; //left and right road edge confidences iEventData[15] = (double) MobileyeMessage.road.leftEdgeConfidence; iEventData[16] = (double) MobileyeMessage.road.rightEdgeConfidence; //left and right lane confidences iEventData[17] = (double) MobileyeMessage.road.leftLaneConfidence; iEventData[18] = (double) MobileyeMessage.road.rightLaneConfidence; //far left and far right lane confidences iEventData[19] = (double) MobileyeMessage.road.leftNeighborConfidence; iEventData[20] = (double) MobileyeMessage.road.rightNeighborConfidence; //model validity distance iEventData[21] = (double) MobileyeMessage.road.roadModelValidRange; //whether a stop line is present if (MobileyeMessage.road.stopLineDistance == 0xFFF) { //no stopline detected iEventData[22] = 0.0; } else { //stopline detected iEventData[22] = 1.0; } iEventData[23] = (double) MobileyeMessage.road.stopLineDistance; iEventData[24] = (double) MobileyeMessage.road.stopLineConf; switch (ID) { case MOBILEYE_CTR: iEventType = FRONTMOBILEYEROAD_EVENT; break; case MOBILEYE_REAR: iEventType = BACKMOBILEYEROAD_EVENT; break; default: iEventType = INVALID_EVENT; break; } //store the event data in the event container NewEvent->SetEventType(iEventType, iEventTime); NewEvent->SetEventData(inr, inc, iEventData); #ifdef LM_PRINTLOGS //create a separate logging event with the same data Event* LogEvent = new Event(NewEvent); #endif //drop the event onto the event queue bool spush = TheLocalRoadEventQueue->PushEvent(NewEvent); #ifdef LM_PRINTLOGS //only log the packet if it successfully entered the event queue extern EventQueue* TheLoggingQueue; if (spush == true) { TheLoggingQueue->PushEvent(LogEvent); } else { delete LogEvent; } #endif return; } void JasonRoadCallback(RoadFitterOutput JasonMessage, RoadFitterInterfaceReceiver* JRX, RoadFitterID ID, void* Arg) { /* Called when jason's algorithm returns a road fix INPUTS: JasonMessage - the results stored in Jason's data packet JRX - pointer to the interface receiver (not used here) ID - enumerated ID indicating which camera was used to create the message Arg - null pointer (not used here) OUTPUTS: none. Reformats the packet into an event and drops it onto ThePosteriorPoseEventQueue */ int i; int j; //extract the number of jason's road segments (always RF_MAX_FITS) int nj = RF_VALID_FITS; //set timestamp from car time double iEventTime = JasonMessage.carTime; //check the event time for valid timestamp extern CarTime* TheCarTime; double cct = TheCarTime->CurrentCarTime(); if (fabs(iEventTime - cct) > CT_TIMEJUMPREJECT) { //do not allow events with inconsistent timestamps into the event queues printf("Warning: got roadfinder timestamp %.12lg; expected something near %.12lg\n", iEventTime, cct); return; } //gain access to the event queue extern SynchronizedEventQueue* TheLocalRoadEventQueue; //declare space for the event data //NOTE: this memory is cleared automatically when the event is pulled from the queue Event* NewEvent = new Event(); int iEventType; double* iEventData = new double[LM_JASONROADPACKETSIZE*nj]; for (i = 0; i < nj; i++) { for (j = 0; j < LM_JASONROADPACKETSIZE; j++) { iEventData[midx(i, j, nj)] = 0.0; } } for (i = 0; i < nj; i++) { //timestamp (synchronized vehicle time) iEventData[midx(i, 0, nj)] = iEventTime; //index of the segmentation and number of segmentations iEventData[midx(i, 1, nj)] = (double) (i); iEventData[midx(i, 2, nj)] = (double) (nj); //number of lines / boundaries found (0 - 4) int nb = JasonMessage.roadFits[i].borders_observed; iEventData[midx(i, 3, nj)] = (double) nb; for (j = 0; j < nb; j++) { //distance to boundaries found (m from camera, positive for lines to the left of center) iEventData[midx(i, j+4, nj)] = JasonMessage.roadFits[i].border_offsets[j]; //boundary types switch (JasonMessage.roadFits[i].observed_border_types[j]) { case RoadFitterOutputData::BT_SingleLaneLine: iEventData[midx(i, j+8, nj)] = 1.0; break; case RoadFitterOutputData::BT_Edge: iEventData[midx(i, j+8, nj)] = 0.0; break; default: iEventData[midx(i, j+8, nj)] = 0.0; break; } } //heading of road wrt camera (m/m, positive for roads heading right) iEventData[midx(i, 12, nj)] = -JasonMessage.roadFits[i].road_heading; //curvature of road wrt camera (m/m^2, positive for roads curving right) iEventData[midx(i, 13, nj)] = -JasonMessage.roadFits[i].system_curvature; //confidence in segmentation fit iEventData[midx(i, 14, nj)] = JasonMessage.roadFits[i].confidence; } switch (ID) { case RF_CTR: iEventType = FRONTJASONROAD_EVENT; break; case RF_REAR: iEventType = BACKJASONROAD_EVENT; break; default: iEventType = INVALID_EVENT; break; } //store the event data in the event container NewEvent->SetEventType(iEventType, iEventTime); NewEvent->SetEventData(nj, LM_JASONROADPACKETSIZE, iEventData); #ifdef LM_PRINTLOGS //create a separate logging event with the same data Event* LogEvent = new Event(NewEvent); #endif //drop the event onto the event queue bool spush = TheLocalRoadEventQueue->PushEvent(NewEvent); #ifdef LM_PRINTLOGS //only log the packet if it successfully entered the event queue extern EventQueue* TheLoggingQueue; if (spush == true) { TheLoggingQueue->PushEvent(LogEvent); } else { delete LogEvent; } #endif return; } void LN200Callback(LN200_data_packet_struct LNMessage, LN200InterfaceReceiver* LRX, void* Arg) { /* Callback for the LN200 timing message INPUTS: LNMessage - the LN200 message packet LRX - pointer to the interface receiver Arg - a void pointer (not used) OUTPUTS: none. */ //extract the current car time from the LN200 double CurrentTime = ((double) ntohs(LNMessage.ts_s)) + ((double) ntohl(LNMessage.ts_t)) / 10000.0; extern CarTime* TheCarTime; TheCarTime->SetCurrentCarTime(CurrentTime); return; } void SideSickCallback(SideSickMsg SSMessage, SideSickReceiver* SSRX, SIDESICKID ID, void* Arg) { /* Callback used for side SICK distance / height type measurments INPUTS: SSMessage - the side SICK message data SSRX - the side SICK message receiver ID - the enumerated ID of the scanner Arg - a void pointer (not used here) OUTPUTS: none. Creates an event and drops it onto the event queue */ int i; int nss = SSMessage.numObstacles; double iEventTime = SSMessage.carTime; //check the event time for valid timestamp extern CarTime* TheCarTime; double cct = TheCarTime->CurrentCarTime(); if (fabs(iEventTime - cct) > CT_TIMEJUMPREJECT) { //do not allow events with inconsistent timestamps into the event queues printf("Warning: got side sick timestamp %.12lg; expected something near %.12lg\n", iEventTime, cct); return; } //declare space for the event data //NOTE: this memory is cleared automatically when the event is pulled from the queue Event* NewEvent = new Event(); int iEventType = INVALID_EVENT; double* iEventData = NULL; if (nss > 0) { iEventData = new double[nss*LM_SIDESICKPACKETSIZE]; } for (i = 0; i < nss; i++) { //set all the data for this side sick detection //timestamp iEventData[midx(i, 0, nss)] = iEventTime; //index iEventData[midx(i, 1, nss)] = (double) i; //number of events iEventData[midx(i, 2, nss)] = (double) nss; //distance to object of interest iEventData[midx(i, 3, nss)] = SSMessage.obstacles[i].distance; //height of object of interest iEventData[midx(i, 4, nss)] = SSMessage.obstacles[i].height; } switch (ID) { case SS_DRIVER: iEventType = SIDESICKDRIV_EVENT; break; case SS_PASSENGER: iEventType = SIDESICKPASS_EVENT; break; } //gain access to the event queue extern SynchronizedEventQueue* TheLocalMapEventQueue; //store the event data in the event container NewEvent->SetEventType(iEventType, iEventTime); NewEvent->SetEventData(nss, LM_SIDESICKPACKETSIZE, iEventData); #ifdef LM_PRINTLOGS //create a separate logging event with the same data Event* LogEvent = new Event(NewEvent); #endif //drop the event onto the event queue bool spush = TheLocalMapEventQueue->PushEvent(NewEvent); #ifdef LM_PRINTLOGS //only log the packet if it successfully entered the event queue extern EventQueue* TheLoggingQueue; if (spush == true) { TheLoggingQueue->PushEvent(LogEvent); } else { delete LogEvent; } #endif return; }
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 1094 ] ] ]
905d5373760bafd8dc0583f907d06fa7b671ae8a
4891542ea31c89c0ab2377428e92cc72bd1d078f
/TerrainBuilder/TerrainBuilder.cpp
36c74e4a18d0d7cd2c60f054a0434164b056cedc
[]
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
2,475
cpp
/* TerrainBuilder.cpp */ #include "TerrainBuilder.h" #define BUFF_SZ 9999 #define PREFIX_FRAME_NUMBER "farme Number = " #define PREFIX_UP_POINT_X "up.x=" #define PREFIX_UP_POINT_Y "up.y=" #define PREFIX_DOWN_POINT_X "down.x=" #define PREFIX_DOWN_POINT_Y "down.y=" #define PREFIX_WIDTH "Width = " #define PREFIX_HEIGHT "Height = " #define PREFIX_CAN_BREAK "canBreak = " #define PREFIX_TIMES_TO_BREAK "time to break = " #define PREFIX_SCORE "score = " TerrainBuilder::TerrainBuilder(CollisionChecker *_cc){ cc = _cc; return; } bool TerrainBuilder::Load(char *filename){ std::ifstream input; // input stream char buffy[BUFF_SZ]; int counter = 0; // variable to hold brick data. Brick *newBrick = 0; // DEBUG: std::cout << "Opening file\n"; input.open(filename); if(!input.good()) return false; while(input.good()){ memset(buffy, 0, BUFF_SZ); input.getline(buffy, BUFF_SZ, '\n'); if(!strlen(buffy)) continue; // In case there is a line in the file with just an enter... // DEBUG: std::cout << "got line: " << buffy << std::endl; ++counter; // Get the frame number newBrick = new Brick( getNumber(buffy, PREFIX_FRAME_NUMBER), new Point(getNumber(buffy, PREFIX_UP_POINT_X), getNumber(buffy, PREFIX_UP_POINT_Y)), new Point(getNumber(buffy, PREFIX_DOWN_POINT_X), getNumber(buffy, PREFIX_DOWN_POINT_Y)), getNumber(buffy, PREFIX_WIDTH), getNumber(buffy, PREFIX_HEIGHT), (getNumber(buffy, PREFIX_CAN_BREAK))?(true):(false), getNumber(buffy, PREFIX_TIMES_TO_BREAK), getNumber(buffy, PREFIX_SCORE), true // _isActive ); Register( dynamic_cast<Sprite *>(newBrick) ); // Collision checker registering //TODO: add the Sprite holder register. // DEBUG: std::cout << "I have a new brick with " << newBrick->frameNum << " times to break: " << newBrick->timesToBreak << " and score : " << newBrick->score << std::endl; } std::cout << "You have :" << counter << " bricks." << std::endl; return true; } int TerrainBuilder::getNumber(char *buffer, const char *pattern){ char *tmp = 0; char temp[BUFF_SZ]; int counter = 0; tmp = strstr(buffer, pattern); tmp += strlen(pattern); counter = 0; while(tmp && isdigit(*tmp)) temp[counter++] = *(tmp++); return atoi(temp); } void TerrainBuilder::Register(Sprite *toreg){ cc->AddUnmovable(toreg); // Debuging purpose : cc->AddMovable(toreg); return; }
[ "apixkernel@5c4dd20e-9542-0410-abe3-ad2d610f3ba4" ]
[ [ [ 1, 76 ] ] ]
897766e6f300d426df3713b78e8bac006e98fee9
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Database/AccountCacheMgr.h
a92dd2957fb3e1560c54c948b95fc783bd65a9a5
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
962
h
#ifndef _ACCOUNTCACHEMANAGER_H_ #define _ACCOUNTCACHEMANAGER_H_ struct ACCOUNT_CACHE; class CAccountCacheMgr { private: map<string, ACCOUNT_CACHE*> m_2Account; // map<u_long, string> m_2AccountPtr; MemPooler<ACCOUNT_CACHE>* m_pAccountMemPooler; list< ACCOUNT_CACHE* > m_list; int m_nAlloc; public: CAccountCacheMgr(); ACCOUNT_CACHE* Find( LPCTSTR szAccount ); void Clear(); void AddMover( u_long idPlayer, LPCTSTR szAccount, int nSlot ); void RemoveMover( u_long idPlayer, LPCTSTR szAccount ); void AddAccount( u_long idPlayer, LPCTSTR szAccount, BOOL bCache, ACCOUNT_CACHE *pCache ); // ACCOUNT_CACHE* _Find( u_long idPlayer ); ACCOUNT_CACHE* GetAccount( LPCTSTR szAccount, BOOL *pbCacheHit ); #ifdef __INVALID_LOGIN_0320 void ChangeMultiServer( LPCTSTR szAccount, u_long uMultiServer ); int InitMultiServer( u_long uMultiServer ); #endif // __INVALID_LOGIN_0320 }; #endif // _ACCOUNTCACHEMANAGER_H_
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 29 ] ] ]
51748ff2fe4586ecbd02dbe114141c2919b5ddb5
119ba245bea18df8d27b84ee06e152b35c707da1
/unreal/branches/svn/qrgui/mainwindow/shapeEdit/arch.cpp
23d67465efbb187978dbb5e3c6fe3fc84acfab13
[]
no_license
nfrey/qreal
05cd4f9b9d3193531eb68ff238d8a447babcb3d2
71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164
refs/heads/master
2020-04-06T06:43:41.910531
2011-05-30T19:30:09
2011-05-30T19:30:09
1,634,768
0
0
null
null
null
null
UTF-8
C++
false
false
2,285
cpp
#include "arch.h" #include "math.h" #include <QtGui/QGraphicsSceneMouseEvent> Arch::Arch(QRectF rect, int startAngle, int spanAngle, Item* parent = 0) :Item(parent) { mPen.setColor(Qt::gray); mBrush.setStyle(Qt::NoBrush); mDomElementType = pictureType; mX1 = rect.left(); mX2 = rect.right(); mY1 = rect.top(); mY2 = rect.bottom(); mSpanAngle = spanAngle; mStartAngle = startAngle; mRect = rect; } int Arch::startAngle() const { return mStartAngle; } int Arch::spanAngle() const { return mSpanAngle; } void Arch::setStartAngle(int start) { mStartAngle = start; } void Arch::setSpanAngle(int span) { mSpanAngle = span; } QRectF Arch::boundingRect() const { QPainterPath line; QPainterPath path; if (mRect.isNull()) return path.boundingRect(); if (mSpanAngle != 360 * 16) { path.moveTo(mRect.center()); line.moveTo(mRect.center()); line.lineTo(x(), y()); path.arcTo(mRect, mStartAngle / 16.0, mSpanAngle / 16.0); } else { path.addEllipse(mRect); } return path.boundingRect(); } void Arch::drawItem(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { Q_UNUSED(option); Q_UNUSED(widget); painter->drawArc(mRect, mStartAngle, mSpanAngle); } void Arch::drawExtractionForItem(QPainter* painter) { painter->drawPoint(boundingRect().topLeft()); painter->drawPoint(boundingRect().topRight()); painter->drawPoint(boundingRect().bottomLeft()); painter->drawPoint(boundingRect().bottomRight()); } void Arch::resizeItem(QGraphicsSceneMouseEvent *event) { Q_UNUSED(event); } QRectF Arch::sceneBoundingRectCoord(QPointF const &topLeftPicture) { qreal const x1 = scenePos().x() + mRect.x() - topLeftPicture.x(); qreal const y1 = scenePos().y() + mRect.y() - topLeftPicture.y(); return QRectF(x1, y1, mRect.width(), mRect.height()); } QPair<QDomElement, Item::DomElementTypes> Arch::generateItem(QDomDocument &document, QPointF const &topLeftPicture) { QDomElement arch = document.createElement("arc"); arch.setAttribute("startAngle", mStartAngle); arch.setAttribute("spanAngle", mSpanAngle); setXandY(arch, sceneBoundingRectCoord(topLeftPicture)); return QPair<QDomElement, Item::DomElementTypes>(arch, mDomElementType); }
[ [ [ 1, 92 ] ] ]
f9bf548b618aa50535d5774eb81f3d3fe44b6cf5
9d58409162a450f5dd162c43cfe0dc7c12c00e14
/src/AudioStream.h
0358fee8ca38c8039eab065cb4b7b600b467e349
[]
no_license
robharper/beat-detect
0f8e9c6feb64e52409972117bed9417795057c76
2f0905d3b657155521c1f4c354b1f75d48d63b04
refs/heads/master
2021-01-01T20:06:05.435288
2011-08-07T17:48:07
2011-08-07T17:48:07
2,169,522
17
2
null
null
null
null
UTF-8
C++
false
false
656
h
// AudioStream.h: interface for the CPCMAudio class. // ////////////////////////////////////////////////////////////////////// #if !defined(_AUDIOSTREAM_H_) #define _AUDIOSTREAM_H_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CAudioStream : public CDataStream { public: CAudioStream(); virtual ~CAudioStream(); HRESULT LoadFromWaveFile( LPCTSTR lpszFilename ); HRESULT SaveToWaveFile( LPCTSTR lpszFilename ); protected: HRESULT LoadReadWaveData( HMMIO hmmioFile, LPMMCKINFO pckInRIFF ); HRESULT SaveWriteWaveData( HMMIO hmmioFile ); }; #endif // _AUDIOSTREAM_H_
[ [ [ 1, 29 ] ] ]
6f973a651386dd59552d6b40800aeec50786746c
22438bd0a316b62e88380796f0a8620c4d129f50
/libs/napl/amplifier.h
059db99cc02c63e478695239c9f338498c1c5528
[ "BSL-1.0" ]
permissive
DannyHavenith/NAPL
1578f5e09f1b825f776bea9575f76518a84588f4
5db7bf823bdc10587746d691cb8d94031115b037
refs/heads/master
2021-01-20T02:17:01.186461
2010-11-26T22:26:25
2010-11-26T22:26:25
1,856,141
0
1
null
null
null
null
UTF-8
C++
false
false
1,358
h
template< typename sampletype> class amplifier_mutator { private: struct amplify_op { template< typename actual_type> void operator()( actual_type &sample) { sample = actual_type( sample * m_factor); } void operator()( sampletype_m8 &sample) { sample = static_cast<sampletype_m8>((static_cast<int>(sample) - sampletraits<sampletype_m8>::get_middle()) * m_factor) + sampletraits<sampletype_m8>::get_middle(); } amplify_op( double factor) : m_factor( factor) { } amplify_op() : m_factor( 0.0) { } double m_factor; }; public: typedef sampletype sample_type; typedef bool result_information_type; void MutateHeader( const stream_header &) { // nop } void Mutate( sampletype *sample) { sampletraits<sampletype>::apply_to_all_channels( m_operation, *sample); } result_information_type GetResult() { return true; } void SetFactor( double factor) { m_operation = amplify_op( factor); } private: amplify_op m_operation; }; template< typename sample_type> struct amplifier : public uniform_block_converter< mutator_adapter< amplifier_mutator< sample_type> > > { amplifier( double factor) { uniform_block_converter< mutator_adapter< amplifier_mutator< sample_type> > >:: m_converter.SetFactor( factor); } };
[ [ [ 1, 71 ] ] ]
7dca81c347ecf64002294dee2c0ccce7791f7038
c31bd425f234be558d9535bf140696dbc798aafb
/src/client.cpp
5e4b8c9bc623def98875055530bcb5ff9ad5b2a2
[]
no_license
dfyx/SibNet
43efb47f02022d468c969bdd9937b28bc602e16c
14090f599d97249ad82a1ff4dd67a620be01afeb
refs/heads/master
2018-12-28T19:56:09.982294
2011-04-15T14:34:55
2011-04-15T14:34:55
1,291,784
1
0
null
null
null
null
UTF-8
C++
false
false
677
cpp
#include <client.h> #include <vector> #include <blocksocket.h> using namespace std; Client::Client() { m_pinSocket = new BlockSocket(); } Client::Client(BlockSocket *p_pinSocket) { m_pinSocket = p_pinSocket; } Client::~Client() { delete m_pinSocket; } bool Client::Connect(string p_strAddress, unsigned short p_sPort) { return m_pinSocket->Connect(p_strAddress, p_sPort); } void Client::Disconnect() { m_pinSocket->Disconnect(BlockSocket::QUEUE_CLEAR); } void Client::SendBlock(Block *p_pinBlock) { m_pinSocket->WriteBlock(p_pinBlock); } Block* Client::ReceiveBlock(bool p_bWait) { return m_pinSocket->ReadBlock(p_bWait); }
[ [ [ 1, 34 ], [ 40, 40 ] ], [ [ 35, 39 ] ] ]
b6eb83610d4f37ed4943d5dc4eb4e52b03d1ec61
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/source/aosl/name.cpp
41088828c2c260dcc4886650cbbb0e54f4321086
[]
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
3,525
cpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // // Begin prologue. // #define AOSLCPP_SOURCE // // End prologue. #include <xsd/cxx/pre.hxx> #include "aosl/name.hpp" #include <xsd/cxx/xml/dom/wildcard-source.hxx> #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> #include <xsd/cxx/tree/comparison-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; static const ::xsd::cxx::tree::comparison_plate< 0, char > comparison_plate_init; } namespace aosl { // Name // Name:: Name () : ::xml_schema::String () { } Name:: Name (const char* _xsd_String_base) : ::xml_schema::String (_xsd_String_base) { } Name:: Name (const ::std::string& _xsd_String_base) : ::xml_schema::String (_xsd_String_base) { } Name:: Name (const ::xml_schema::String& _xsd_String_base) : ::xml_schema::String (_xsd_String_base) { } Name:: Name (const Name& x, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::xml_schema::String (x, f, c) { } Name:: Name (const ::xercesc::DOMElement& e, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::xml_schema::String (e, f, c) { } Name:: Name (const ::xercesc::DOMAttr& a, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::xml_schema::String (a, f, c) { } Name:: Name (const ::std::string& s, const ::xercesc::DOMElement* e, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::xml_schema::String (s, e, f, c) { } Name* Name:: _clone (::xml_schema::Flags f, ::xml_schema::Container* c) const { return new class Name (*this, f, c); } Name:: ~Name () { } } #include <ostream> #include <xsd/cxx/tree/std-ostream-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::std_ostream_plate< 0, char > std_ostream_plate_init; } namespace aosl { ::std::ostream& operator<< (::std::ostream& o, const Name& i) { o << static_cast< const ::xml_schema::String& > (i); return o; } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace aosl { } #include <ostream> #include <xsd/cxx/tree/error-handler.hxx> #include <xsd/cxx/xml/dom/serialization-source.hxx> #include <xsd/cxx/tree/type-serializer-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_serializer_plate< 0, char > type_serializer_plate_init; } namespace aosl { void operator<< (::xercesc::DOMElement& e, const Name& i) { e << static_cast< const ::xml_schema::String& > (i); } void operator<< (::xercesc::DOMAttr& a, const Name& i) { a << static_cast< const ::xml_schema::String& > (i); } void operator<< (::xml_schema::ListStream& l, const Name& i) { l << static_cast< const ::xml_schema::String& > (i); } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
[ "klaim@localhost" ]
[ [ [ 1, 187 ] ] ]
92228b90445f40383a528446441c9b662b9ce039
3a72cb54a5209f8d5be90df8b0bbac116119a36d
/core/ghost/gameprotocol.h
ed6ef4eddc62859ca50325207b7e837758ec0729
[]
no_license
luqasn/ghost4mac
43409b56f7f1fb8783af467741246a198ae87470
ccfc153ccd5274b09eabbc749e80db23d9c163b5
refs/heads/master
2021-03-12T20:17:03.261275
2011-07-06T11:02:59
2011-07-06T11:02:59
2,005,954
0
0
null
null
null
null
UTF-8
C++
false
false
8,678
h
/* Copyright [2008] [Trevor Hogan] 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. CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/ */ #ifndef GAMEPROTOCOL_H #define GAMEPROTOCOL_H // // CGameProtocol // #define W3GS_HEADER_CONSTANT 247 #define GAME_NONE 0 // this case isn't part of the protocol, it's for internal use only #define GAME_FULL 2 #define GAME_PUBLIC 16 #define GAME_PRIVATE 17 #define GAMETYPE_CUSTOM 1 #define GAMETYPE_BLIZZARD 9 #define PLAYERLEAVE_DISCONNECT 1 #define PLAYERLEAVE_LOST 7 #define PLAYERLEAVE_LOSTBUILDINGS 8 #define PLAYERLEAVE_WON 9 #define PLAYERLEAVE_DRAW 10 #define PLAYERLEAVE_OBSERVER 11 #define PLAYERLEAVE_LOBBY 13 #define REJECTJOIN_FULL 9 #define REJECTJOIN_STARTED 10 #define REJECTJOIN_WRONGPASSWORD 27 #include "gameslot.h" class CGamePlayer; class CIncomingJoinPlayer; class CIncomingAction; class CIncomingChatPlayer; class CIncomingMapSize; class CGameProtocol { public: CGHost *m_GHost; enum Protocol { W3GS_PING_FROM_HOST = 1, // 0x01 W3GS_SLOTINFOJOIN = 4, // 0x04 W3GS_REJECTJOIN = 5, // 0x05 W3GS_PLAYERINFO = 6, // 0x06 W3GS_PLAYERLEAVE_OTHERS = 7, // 0x07 W3GS_GAMELOADED_OTHERS = 8, // 0x08 W3GS_SLOTINFO = 9, // 0x09 W3GS_COUNTDOWN_START = 10, // 0x0A W3GS_COUNTDOWN_END = 11, // 0x0B W3GS_INCOMING_ACTION = 12, // 0x0C W3GS_CHAT_FROM_HOST = 15, // 0x0F W3GS_START_LAG = 16, // 0x10 W3GS_STOP_LAG = 17, // 0x11 W3GS_HOST_KICK_PLAYER = 28, // 0x1C W3GS_REQJOIN = 30, // 0x1E W3GS_LEAVEGAME = 33, // 0x21 W3GS_GAMELOADED_SELF = 35, // 0x23 W3GS_OUTGOING_ACTION = 38, // 0x26 W3GS_OUTGOING_KEEPALIVE = 39, // 0x27 W3GS_CHAT_TO_HOST = 40, // 0x28 W3GS_DROPREQ = 41, // 0x29 W3GS_SEARCHGAME = 47, // 0x2F (UDP/LAN) W3GS_GAMEINFO = 48, // 0x30 (UDP/LAN) W3GS_CREATEGAME = 49, // 0x31 (UDP/LAN) W3GS_REFRESHGAME = 50, // 0x32 (UDP/LAN) W3GS_DECREATEGAME = 51, // 0x33 (UDP/LAN) W3GS_CHAT_OTHERS = 52, // 0x34 W3GS_PING_FROM_OTHERS = 53, // 0x35 W3GS_PONG_TO_OTHERS = 54, // 0x36 W3GS_MAPCHECK = 61, // 0x3D W3GS_STARTDOWNLOAD = 63, // 0x3F W3GS_MAPSIZE = 66, // 0x42 W3GS_MAPPART = 67, // 0x43 W3GS_MAPPARTOK = 68, // 0x44 W3GS_MAPPARTNOTOK = 69, // 0x45 - just a guess, received this packet after forgetting to send a crc in W3GS_MAPPART (f7 45 0a 00 01 02 01 00 00 00) W3GS_PONG_TO_HOST = 70, // 0x46 W3GS_INCOMING_ACTION2 = 72 // 0x48 - received this packet when there are too many actions to fit in W3GS_INCOMING_ACTION }; CGameProtocol( CGHost *nGHost ); ~CGameProtocol( ); // receive functions CIncomingJoinPlayer *RECEIVE_W3GS_REQJOIN( BYTEARRAY data ); bool RECEIVE_W3GS_LEAVEGAME( BYTEARRAY data ); bool RECEIVE_W3GS_GAMELOADED_SELF( BYTEARRAY data ); CIncomingAction *RECEIVE_W3GS_OUTGOING_ACTION( BYTEARRAY data, unsigned char PID ); uint32_t RECEIVE_W3GS_OUTGOING_KEEPALIVE( BYTEARRAY data ); CIncomingChatPlayer *RECEIVE_W3GS_CHAT_TO_HOST( BYTEARRAY data ); bool RECEIVE_W3GS_SEARCHGAME( BYTEARRAY data, unsigned char war3Version ); CIncomingMapSize *RECEIVE_W3GS_MAPSIZE( BYTEARRAY data, BYTEARRAY mapSize ); uint32_t RECEIVE_W3GS_MAPPARTOK( BYTEARRAY data ); uint32_t RECEIVE_W3GS_PONG_TO_HOST( BYTEARRAY data ); // send functions BYTEARRAY SEND_W3GS_PING_FROM_HOST( ); BYTEARRAY SEND_W3GS_SLOTINFOJOIN( unsigned char PID, BYTEARRAY port, BYTEARRAY externalIP, vector<CGameSlot> &slots, uint32_t randomSeed, unsigned char gameType, unsigned char playerSlots ); BYTEARRAY SEND_W3GS_REJECTJOIN( uint32_t reason ); BYTEARRAY SEND_W3GS_PLAYERINFO( unsigned char PID, string name, BYTEARRAY externalIP, BYTEARRAY internalIP ); BYTEARRAY SEND_W3GS_PLAYERLEAVE_OTHERS( unsigned char PID, uint32_t leftCode ); BYTEARRAY SEND_W3GS_GAMELOADED_OTHERS( unsigned char PID ); BYTEARRAY SEND_W3GS_SLOTINFO( vector<CGameSlot> &slots, uint32_t randomSeed, unsigned char gameType, unsigned char playerSlots ); BYTEARRAY SEND_W3GS_COUNTDOWN_START( ); BYTEARRAY SEND_W3GS_COUNTDOWN_END( ); BYTEARRAY SEND_W3GS_INCOMING_ACTION( queue<CIncomingAction *> actions, uint16_t sendInterval ); BYTEARRAY SEND_W3GS_CHAT_FROM_HOST( unsigned char fromPID, BYTEARRAY toPIDs, unsigned char flag, BYTEARRAY flagExtra, string message ); BYTEARRAY SEND_W3GS_START_LAG( vector<CGamePlayer *> players, bool loadInGame = false ); BYTEARRAY SEND_W3GS_STOP_LAG( CGamePlayer *player, bool loadInGame = false ); BYTEARRAY SEND_W3GS_SEARCHGAME( unsigned char war3Version ); BYTEARRAY SEND_W3GS_GAMEINFO( unsigned char war3Version, BYTEARRAY mapGameType, BYTEARRAY mapFlags, BYTEARRAY mapWidth, BYTEARRAY mapHeight, string gameName, string hostName, uint32_t upTime, string mapPath, BYTEARRAY mapCRC, uint32_t slotsTotal, uint32_t slotsOpen, uint16_t port, uint32_t hostCounter ); BYTEARRAY SEND_W3GS_CREATEGAME( unsigned char war3Version ); BYTEARRAY SEND_W3GS_REFRESHGAME( uint32_t players, uint32_t playerSlots ); BYTEARRAY SEND_W3GS_DECREATEGAME( ); BYTEARRAY SEND_W3GS_MAPCHECK( string mapPath, BYTEARRAY mapSize, BYTEARRAY mapInfo, BYTEARRAY mapCRC, BYTEARRAY mapSHA1 ); BYTEARRAY SEND_W3GS_STARTDOWNLOAD( unsigned char fromPID ); BYTEARRAY SEND_W3GS_MAPPART( unsigned char fromPID, unsigned char toPID, uint32_t start, string *mapData ); BYTEARRAY SEND_W3GS_INCOMING_ACTION2( queue<CIncomingAction *> actions ); // other functions private: bool AssignLength( BYTEARRAY &content ); bool ValidateLength( BYTEARRAY &content ); BYTEARRAY EncodeSlotInfo( vector<CGameSlot> &slots, uint32_t randomSeed, unsigned char gameType, unsigned char playerSlots ); }; // // CIncomingJoinPlayer // class CIncomingJoinPlayer { private: string m_Name; BYTEARRAY m_InternalIP; public: CIncomingJoinPlayer( string nName, BYTEARRAY &nInternalIP ); ~CIncomingJoinPlayer( ); string GetName( ) { return m_Name; } BYTEARRAY GetInternalIP( ) { return m_InternalIP; } }; // // CIncomingAction // class CIncomingAction { private: unsigned char m_PID; BYTEARRAY m_CRC; BYTEARRAY m_Action; public: CIncomingAction( unsigned char nPID, BYTEARRAY &nCRC, BYTEARRAY &nAction ); ~CIncomingAction( ); unsigned char GetPID( ) { return m_PID; } BYTEARRAY GetCRC( ) { return m_CRC; } BYTEARRAY GetAction( ) { return m_Action; } uint32_t GetLength( ) { return m_Action.size( ) + 3; } }; // // CIncomingChatPlayer // class CIncomingChatPlayer { public: enum ChatToHostType { CTH_MESSAGE = 0, // a chat message CTH_MESSAGEEXTRA = 1, // a chat message with extra flags CTH_TEAMCHANGE = 2, // a team change request CTH_COLOURCHANGE = 3, // a colour change request CTH_RACECHANGE = 4, // a race change request CTH_HANDICAPCHANGE = 5 // a handicap change request }; private: ChatToHostType m_Type; unsigned char m_FromPID; BYTEARRAY m_ToPIDs; unsigned char m_Flag; string m_Message; unsigned char m_Byte; BYTEARRAY m_ExtraFlags; public: CIncomingChatPlayer( unsigned char nFromPID, BYTEARRAY &nToPIDs, unsigned char nFlag, string nMessage ); CIncomingChatPlayer( unsigned char nFromPID, BYTEARRAY &nToPIDs, unsigned char nFlag, string nMessage, BYTEARRAY &nExtraFlags ); CIncomingChatPlayer( unsigned char nFromPID, BYTEARRAY &nToPIDs, unsigned char nFlag, unsigned char nByte ); ~CIncomingChatPlayer( ); ChatToHostType GetType( ) { return m_Type; } unsigned char GetFromPID( ) { return m_FromPID; } BYTEARRAY GetToPIDs( ) { return m_ToPIDs; } unsigned char GetFlag( ) { return m_Flag; } string GetMessage( ) { return m_Message; } unsigned char GetByte( ) { return m_Byte; } BYTEARRAY GetExtraFlags( ) { return m_ExtraFlags; } }; class CIncomingMapSize { private: unsigned char m_SizeFlag; uint32_t m_MapSize; public: CIncomingMapSize( unsigned char nSizeFlag, uint32_t nMapSize ); ~CIncomingMapSize( ); unsigned char GetSizeFlag( ) { return m_SizeFlag; } uint32_t GetMapSize( ) { return m_MapSize; } }; #endif
[ [ [ 1, 113 ], [ 115, 131 ], [ 137, 246 ] ], [ [ 114, 114 ], [ 132, 136 ] ] ]
82004465e845bd773762963beabc1dbb20ed8fee
cf579692f2e289563160b6a218fa5f1b6335d813
/xbflashlib/xbunpack.cpp
a18bd48ffcc86b9252951b7f13684661a66fdeb6
[]
no_license
opcow/XBtool
a7451971de3296e1ce5632b0c9d95430f6d3b223
718a7fbf87e08c12c0c829dd2e2c0d6cee967cbe
refs/heads/master
2021-01-16T21:02:17.759102
2011-03-09T23:36:54
2011-03-09T23:36:54
1,461,420
8
2
null
null
null
null
UTF-8
C++
false
false
14,963
cpp
/* XBFLASH - Xbox Flash image utility * Copyright (C) 2002 Paul Bartholomew * * 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. * * * xbunpack.c - Functions for unpacking a ROM image * */ #include "stdafx.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <direct.h> #include "xbconfig.h" #include "xbflashlib.h" #include "cabio.h" #include "fbl_hash.h" #include "tea_hash.h" #include "cryptlib/hash/sha.h" #include "cryptlib/crypt/rc4.h" #include "xbunpack.h" static int load_rom_image(const char *romfname, unsigned char **p_rombuf, unsigned int *p_size); static int extract_fbl_image(unsigned char *p_rom_image, unsigned int size_rom_image, unsigned char **p_fbl_image, unsigned int *p_size_fbl_image); static int extract_2bl_image(unsigned char *p_rom_image, unsigned int size_rom_image, unsigned char **p_2bl_image, unsigned int *p_size_2bl_image); static int decrypt_2bl_image(unsigned char *p_2bl_image, unsigned int size_2bl_image, unsigned char *p_fbl_image, unsigned int size_fbl_image); static int extract_compressed_kernel_image(unsigned char *p_rom_image, unsigned int size_rom_image, unsigned char *p_2bl_image, unsigned int size_2bl_image, unsigned char **p_kernelZ_image, unsigned int *p_size_kernelZ_image); static int decrypt_compressed_kernel_image(unsigned char *p_kernelZ_image, unsigned int size_kernelZ_image, unsigned char *p_2bl_image, unsigned int size_2bl_image); // // Reads input ROM file 'romfname' // // Creates multiple files inside directory 'outdirname': // bootloader2.img // xboxkrnl.img // remainder.img // XBFLASHLIB_API void freeKernelBuffer(unsigned char *kernelBuffer) { free(kernelBuffer); } XBFLASHLIB_API int do_xbunpack(const char *romfname, const char *outdirname) { unsigned char *p_rom_image; unsigned int size_rom_image; unsigned char *p_fbl_image; unsigned int size_fbl_image; unsigned char *p_2bl_image; unsigned int size_2bl_image; unsigned char *p_kernelZ_image; unsigned int size_kernelZ_image; char outdir_prefix[BUFSIZ+1]; char fname_cabtmp[BUFSIZ+1]; char fname_2bl[BUFSIZ+1]; char fname_fbl[BUFSIZ+1]; char fname_remainder[BUFSIZ+1]; char fname_kernel[BUFSIZ+1]; FILE *fh; unsigned int sizeRomOut; strcpy(outdir_prefix, outdirname); strcat(outdir_prefix, PATH_SEP); strcpy(fname_cabtmp, outdir_prefix); strcat(fname_cabtmp, IMGFNAME_CABTMP); strcpy(fname_2bl, outdir_prefix); strcat(fname_2bl, IMGFNAME_2BL); strcpy(fname_fbl, outdir_prefix); strcat(fname_fbl, IMGFNAME_FBL); strcpy(fname_kernel, outdir_prefix); strcat(fname_kernel, IMGFNAME_XBOXKRNL); strcpy(fname_remainder, outdir_prefix); strcat(fname_remainder, IMGFNAME_REMAINDER); if (logFile) fprintf(logFile, "Loading ROM image file '%s'... ", romfname); if (!load_rom_image(romfname, &p_rom_image, &size_rom_image)) { return 0; } if (CFG_fbl_address && CFG_fbl_size) { if (logFile) fprintf(logFile, "\nExtracting FBL image... "); if (!extract_fbl_image(p_rom_image, size_rom_image, &p_fbl_image, &size_fbl_image)) { free(p_rom_image); return 0; } } else { p_fbl_image = 0; size_fbl_image = 0; } if (logFile) fprintf(logFile, "\nExtracting 2BL image... "); if (!extract_2bl_image(p_rom_image, size_rom_image, &p_2bl_image, &size_2bl_image)) { free(p_rom_image); if (p_fbl_image) free(p_fbl_image); return 0; } if (CFG_RC4_key_encrypt == 2) { if (logFile) fprintf(logFile, "\nDecrypting 2BL image... "); if (!decrypt_2bl_image(p_2bl_image, size_2bl_image, p_fbl_image, size_fbl_image)) { free(p_rom_image); if (p_fbl_image) free(p_fbl_image); free(p_2bl_image); return 0; } } if (logFile) fprintf(logFile, "\nExtracting compressed KERNEL image... "); if (!extract_compressed_kernel_image(p_rom_image, size_rom_image, p_2bl_image, size_2bl_image, &p_kernelZ_image, &size_kernelZ_image)) { free(p_rom_image); if (p_fbl_image) free(p_fbl_image); free(p_2bl_image); return 0; } if (CFG_RC4_key_encrypt) { if (logFile) fprintf(logFile, "\nDecrypting compressed KERNEL image... "); if (!decrypt_compressed_kernel_image(p_kernelZ_image, size_kernelZ_image, p_2bl_image, size_2bl_image)) { free(p_rom_image); if (p_fbl_image) free(p_fbl_image); free(p_2bl_image); free(p_kernelZ_image); return 0; } } // Now ready to start writing output files, so create target directory mkdir(outdirname); // If the output file(s) already exist, then remove them first unlink(fname_cabtmp); unlink(fname_2bl); unlink(fname_kernel); unlink(fname_remainder); if (logFile) fprintf(logFile, "\nDecompressing KERNEL image (compressed size: %u)... ", size_kernelZ_image); if (!create_kernel_cab_from_compressed(fname_cabtmp, IMGFNAME_XBOXKRNL, p_kernelZ_image, size_kernelZ_image)) { free(p_rom_image); if (p_fbl_image) free(p_fbl_image); free(p_2bl_image); free(p_kernelZ_image); rmdir(outdirname); return 0; } // We no longer need compressed kernel image, so free it up free(p_kernelZ_image); if (logFile) fprintf(logFile, "\nWriting KERNEL image file '%s'... ", fname_kernel); if (!extract_decompressed_from_kernel_cab(IMGFNAME_CABTMP, outdir_prefix)) { free(p_rom_image); if (p_fbl_image) free(p_fbl_image); free(p_2bl_image); unlink(fname_cabtmp); rmdir(outdirname); return 0; } // We no longer need temp cab file, so remove it unlink(fname_cabtmp); // Write our output files if (logFile) fprintf(logFile, "\nWriting 2BL image file '%s'... ", fname_2bl); if (!(fh = fopen(fname_2bl, "wb"))) { if (logFile) fprintf(logFile, "Cannot write output 2bl file!\n"); free(p_rom_image); if (p_fbl_image) free(p_fbl_image); free(p_2bl_image); return 0; } if (fwrite(p_2bl_image, 1, size_2bl_image, fh) != size_2bl_image) { if (logFile) fprintf(logFile, "Error writing output 2bl file!\n"); fclose(fh); unlink(fname_2bl); free(p_rom_image); if (p_fbl_image) free(p_fbl_image); free(p_2bl_image); return 0; } fclose(fh); // We no longer need 2bl image, so free it up free(p_2bl_image); if (p_fbl_image) { if (logFile) fprintf(logFile, "\nWriting FBL image file '%s'... ", fname_fbl); if (!(fh = fopen(fname_fbl, "wb"))) { if (logFile) fprintf(logFile, "Cannot write output fbl file!\n"); free(p_rom_image); free(p_fbl_image); return 0; } if (fwrite(p_fbl_image, 1, size_fbl_image, fh) != size_fbl_image) { if (logFile) fprintf(logFile, "Error writing output fbl file!\n"); fclose(fh); unlink(fname_fbl); free(p_rom_image); free(p_fbl_image); return 0; } fclose(fh); // We no longer need fbl image, so free it up free(p_fbl_image); } // Lets just write out a minimum sized 2bl. This may break something, // but for now it might avoid some confusion. sizeRomOut = size_rom_image; if (sizeRomOut > 0x40000) { for (int i = sizeRomOut / 2; i >= 0x40000; i /= 2) { if (memcmp(p_rom_image + (size_rom_image - i), p_rom_image, 0x10) == 0) sizeRomOut = i; } } if (logFile) fprintf(logFile, "\nWriting REMAINDER image file '%s'... ", fname_remainder); if (!(fh = fopen(fname_remainder, "wb"))) { if (logFile) fprintf(logFile, "Cannot write output remainder file!\n"); free(p_rom_image); return 0; } if (fwrite(p_rom_image + (size_rom_image - sizeRomOut), 1, sizeRomOut, fh) != sizeRomOut) { if (logFile) fprintf(logFile, "Error writing output remainder file!\n"); fclose(fh); unlink(fname_remainder); free(p_rom_image); return 0; } fclose(fh); // We no longer need rom image, so free it up free(p_rom_image); if (logFile) fprintf(logFile, "\nSuccess!\n"); return 1; } static int load_rom_image(const char *romfname, unsigned char **p_rombuf, unsigned int *p_size) { FILE *fh; unsigned char *rom_buf; unsigned int filesize; if (!(fh = fopen(romfname, "rb"))) { if (logFile) fprintf(logFile, "Cannot open input ROM file: '%s'!\n", romfname); return 0; } fseek(fh, 0L, SEEK_END); filesize = ftell(fh); // Verify ROM file size is non-zero and a power of 2 if (!filesize || (filesize & (filesize-1))) { if (logFile) fprintf(logFile, "Invalid filesize for ROM file: %u\n", filesize); fclose(fh); return 0; } if (!(rom_buf = (unsigned char *) malloc(filesize))) { if (logFile) fprintf(logFile, "Not enough memory to load ROM!\n"); fclose(fh); return 0; } fseek(fh, 0L, SEEK_SET); if ((fread(rom_buf, 1, filesize, fh) != filesize)) { if (logFile) fprintf(logFile, "Error reading ROM file!\n"); free(rom_buf); fclose(fh); return 0; } fclose(fh); *p_rombuf = rom_buf; *p_size = filesize; return 1; } static int extract_2bl_image(unsigned char *p_rom_image, unsigned int size_rom_image, unsigned char **p_2bl_image, unsigned int *p_size_2bl_image) { unsigned char *p_buf; unsigned int rom_image_offset; rom_image_offset = (CFG_2bl_address & (size_rom_image - 1)); if ((rom_image_offset + CFG_2bl_size) > size_rom_image) { if (logFile) fprintf(logFile, "CFG 2bl address/size problem!\n"); return 0; } if (!(p_buf = (unsigned char *) malloc(CFG_2bl_size))) { if (logFile) fprintf(logFile, "Not enough memory to load 2BL!\n"); return 0; } // Copy-out the 2bl image memcpy(p_buf, (p_rom_image + rom_image_offset), CFG_2bl_size); // Now go back to ROM image and wipe-out the area used by 2bl memset((p_rom_image + rom_image_offset), 0, CFG_2bl_size); *p_2bl_image = p_buf; *p_size_2bl_image = CFG_2bl_size; return 1; } static int extract_fbl_image(unsigned char *p_rom_image, unsigned int size_rom_image, unsigned char **p_fbl_image, unsigned int *p_size_fbl_image) { unsigned char *p_buf; unsigned int rom_image_offset; if (!CFG_fbl_address || !CFG_fbl_size) { *p_fbl_image = 0; *p_size_fbl_image = 0; return 1; } rom_image_offset = (CFG_fbl_address & (size_rom_image - 1)); if ((rom_image_offset + CFG_fbl_size) > size_rom_image) { if (logFile) fprintf(logFile, "CFG fbl address/size problem!\n"); return 0; } if (!(p_buf = (unsigned char *) malloc(CFG_fbl_size))) { if (logFile) fprintf(logFile, "Not enough memory to load FBL!\n"); return 0; } // Copy-out the fbl image memcpy(p_buf, (p_rom_image + rom_image_offset), CFG_fbl_size); // Now go back to ROM image and wipe-out the area used by fbl memset((p_rom_image + rom_image_offset), 0, CFG_fbl_size); *p_fbl_image = p_buf; *p_size_fbl_image = CFG_fbl_size; return 1; } static int decrypt_2bl_image(unsigned char *p_2bl_image, unsigned int size_2bl_image, unsigned char *p_fbl_image, unsigned int size_fbl_image) { SHA_CTX sha_ctx; RC4_KEY rc4_key; unsigned char sha_digest[SHA_DIGEST_LENGTH]; unsigned char tmp_key[16]; int i; if (CFG_RC4_keymethod == 1) { SHA1_Init(&sha_ctx); // start with rc4 key SHA1_Update(&sha_ctx, CFG_RC4_key, 16); if (0 && p_fbl_image && size_fbl_image) { SHA1_Update(&sha_ctx, &p_fbl_image[size_fbl_image-16], 16); } else { SHA1_Update(&sha_ctx, &p_2bl_image[size_2bl_image-16], 16); } for (i = 0; i < 16; i++) { tmp_key[i] = CFG_RC4_key[i] ^ 0x5c; } SHA1_Update(&sha_ctx, tmp_key, 16); SHA1_Final(sha_digest, &sha_ctx); RC4_set_key(&rc4_key, 20, sha_digest); RC4(&rc4_key, size_2bl_image-16, p_2bl_image, p_2bl_image); } else { RC4_set_key(&rc4_key, RC4_keylen, CFG_RC4_key); RC4(&rc4_key, size_2bl_image, p_2bl_image, p_2bl_image); } return 1; } static int extract_compressed_kernel_image(unsigned char *p_rom_image, unsigned int size_rom_image, unsigned char *p_2bl_image, unsigned int size_2bl_image, unsigned char **p_kernelZ_image, unsigned int *p_size_kernelZ_image) { unsigned char *p_kernelZ; unsigned int kernelZ_size; unsigned int kernel_data_size; unsigned int kernel_top_rom_offset; unsigned int kernel_rom_offset; if ( ((CFG_2bl_kernelkey_offset + RC4_KEYLEN) > size_2bl_image) || ((CFG_2bl_dwkernelsize_offset + sizeof(int)) > size_2bl_image) || ((CFG_2bl_dwkerneldatasize_offset + sizeof(int)) > size_2bl_image) ) { if (logFile) fprintf(logFile, "Invalid config params for kernel extract!\n"); return 0; } kernelZ_size = *(unsigned int *)(p_2bl_image + CFG_2bl_dwkernelsize_offset); kernel_data_size = *(unsigned int *)(p_2bl_image + CFG_2bl_dwkerneldatasize_offset); kernel_top_rom_offset = (CFG_kernel_top_address & (size_rom_image-1)); if ((kernelZ_size + kernel_data_size - 1) > kernel_top_rom_offset) { if (logFile) fprintf(logFile, "Invalid config params for kernel extract!\n"); return 0; } kernel_rom_offset = (kernel_top_rom_offset + 1) - kernel_data_size - kernelZ_size; if (!(p_kernelZ = (unsigned char *) malloc(kernelZ_size))) { if (logFile) fprintf(logFile, "Not enough memory for kernel extract!\n"); return 0; } // Copy-out the compressed kernel image memcpy(p_kernelZ, (p_rom_image + kernel_rom_offset), kernelZ_size); // Now go back to ROM image and wipe-out the area used by compressed kernel memset((p_rom_image + kernel_rom_offset), 0, kernelZ_size); // And the area used by the kernel initialized data section memset((p_rom_image + kernel_rom_offset + kernelZ_size), 0, kernel_data_size); *p_kernelZ_image = p_kernelZ; *p_size_kernelZ_image = kernelZ_size; return 1; } static int decrypt_compressed_kernel_image(unsigned char *p_kernelZ_image, unsigned int size_kernelZ_image, unsigned char *p_2bl_image, unsigned int size_2bl_image) { RC4_KEY rc4_key; unsigned char kernel_key[RC4_KEYLEN]; if (((CFG_2bl_kernelkey_offset + RC4_KEYLEN) > size_2bl_image)) { if (logFile) fprintf(logFile, "Invalid config params for kernel decrypt!\n"); return 0; } memcpy(kernel_key, (p_2bl_image + CFG_2bl_kernelkey_offset), RC4_KEYLEN); RC4_set_key(&rc4_key, RC4_KEYLEN, kernel_key); RC4(&rc4_key, size_kernelZ_image, p_kernelZ_image, p_kernelZ_image); return 1; }
[ [ [ 1, 489 ] ] ]
bcde48594014492a0598c7ce8019d8aa6b8bc4d9
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/python/src/str.cpp
209855058654f97d9e7eff0db55287539e874462
[ "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
9,753
cpp
// Copyright David Abrahams 2004. Distributed under the Boost // Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/python/str.hpp> #include <boost/python/extract.hpp> #include <boost/python/ssize_t.hpp> namespace boost { namespace python { namespace detail { detail::new_reference str_base::call(object const& arg_) { return (detail::new_reference)PyObject_CallFunction( (PyObject*)&PyString_Type, "(O)", arg_.ptr()); } str_base::str_base() : object(detail::new_reference(::PyString_FromString(""))) {} str_base::str_base(const char* s) : object(detail::new_reference(::PyString_FromString(s))) {} namespace { ssize_t str_size_as_py_ssize_t(std::size_t n) { if (n > ssize_t_max) { throw std::range_error("str size > ssize_t_max"); } return static_cast<ssize_t>(n); } } // namespace <anonymous> str_base::str_base(char const* start, char const* finish) : object( detail::new_reference( ::PyString_FromStringAndSize( start, str_size_as_py_ssize_t(finish - start) ) ) ) {} str_base::str_base(char const* start, std::size_t length) // new str : object( detail::new_reference( ::PyString_FromStringAndSize( start, str_size_as_py_ssize_t(length) ) ) ) {} str_base::str_base(object_cref other) : object(str_base::call(other)) {} #define BOOST_PYTHON_FORMAT_OBJECT(z, n, data) "O" #define BOOST_PYTHON_OBJECT_PTR(z, n, data) , x##n .ptr() #define BOOST_PYTHON_DEFINE_STR_METHOD(name, arity) \ str str_base:: name ( BOOST_PP_ENUM_PARAMS(arity, object_cref x) ) const \ { \ return str(new_reference( \ expect_non_null( \ PyObject_CallMethod( \ this->ptr(), #name, \ "(" BOOST_PP_REPEAT(arity, BOOST_PYTHON_FORMAT_OBJECT, _) ")" \ BOOST_PP_REPEAT_1(arity, BOOST_PYTHON_OBJECT_PTR, _))))); \ } BOOST_PYTHON_DEFINE_STR_METHOD(capitalize, 0) BOOST_PYTHON_DEFINE_STR_METHOD(center, 1) long str_base::count(object_cref sub) const { return extract<long>(this->attr("count")(sub)); } long str_base::count(object_cref sub, object_cref start) const { return extract<long>(this->attr("count")(sub,start)); } long str_base::count(object_cref sub, object_cref start, object_cref end) const { return extract<long>(this->attr("count")(sub,start,end)); } object str_base::decode() const { return this->attr("decode")(); } object str_base::decode(object_cref encoding) const { return this->attr("decode")(encoding); } object str_base::decode(object_cref encoding, object_cref errors) const { return this->attr("decode")(encoding,errors); } object str_base::encode() const { return this->attr("encode")(); } object str_base::encode(object_cref encoding) const { return this->attr("encode")(encoding); } object str_base::encode(object_cref encoding, object_cref errors) const { return this->attr("encode")(encoding,errors); } bool str_base::endswith(object_cref suffix) const { bool result = PyInt_AsLong(this->attr("endswith")(suffix).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } BOOST_PYTHON_DEFINE_STR_METHOD(expandtabs, 0) BOOST_PYTHON_DEFINE_STR_METHOD(expandtabs, 1) long str_base::find(object_cref sub) const { long result = PyInt_AsLong(this->attr("find")(sub).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } long str_base::find(object_cref sub, object_cref start) const { long result = PyInt_AsLong(this->attr("find")(sub,start).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } long str_base::find(object_cref sub, object_cref start, object_cref end) const { long result = PyInt_AsLong(this->attr("find")(sub,start,end).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } long str_base::index(object_cref sub) const { long result = PyInt_AsLong(this->attr("index")(sub).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } long str_base::index(object_cref sub, object_cref start) const { long result = PyInt_AsLong(this->attr("index")(sub,start).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } long str_base::index(object_cref sub, object_cref start, object_cref end) const { long result = PyInt_AsLong(this->attr("index")(sub,start,end).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } bool str_base::isalnum() const { bool result = PyInt_AsLong(this->attr("isalnum")().ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } bool str_base::isalpha() const { bool result = PyInt_AsLong(this->attr("isalpha")().ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } bool str_base::isdigit() const { bool result = PyInt_AsLong(this->attr("isdigit")().ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } bool str_base::islower() const { bool result = PyInt_AsLong(this->attr("islower")().ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } bool str_base::isspace() const { bool result = PyInt_AsLong(this->attr("isspace")().ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } bool str_base::istitle() const { bool result = PyInt_AsLong(this->attr("istitle")().ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } bool str_base::isupper() const { bool result = PyInt_AsLong(this->attr("isupper")().ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } BOOST_PYTHON_DEFINE_STR_METHOD(join, 1) BOOST_PYTHON_DEFINE_STR_METHOD(ljust, 1) BOOST_PYTHON_DEFINE_STR_METHOD(lower, 0) BOOST_PYTHON_DEFINE_STR_METHOD(lstrip, 0) BOOST_PYTHON_DEFINE_STR_METHOD(replace, 2) BOOST_PYTHON_DEFINE_STR_METHOD(replace, 3) long str_base::rfind(object_cref sub) const { long result = PyInt_AsLong(this->attr("rfind")(sub).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } long str_base::rfind(object_cref sub, object_cref start) const { long result = PyInt_AsLong(this->attr("rfind")(sub,start).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } long str_base::rfind(object_cref sub, object_cref start, object_cref end) const { long result = PyInt_AsLong(this->attr("rfind")(sub,start,end).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } long str_base::rindex(object_cref sub) const { long result = PyInt_AsLong(this->attr("rindex")(sub).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } long str_base::rindex(object_cref sub, object_cref start) const { long result = PyInt_AsLong(this->attr("rindex")(sub,start).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } long str_base::rindex(object_cref sub, object_cref start, object_cref end) const { long result = PyInt_AsLong(this->attr("rindex")(sub,start,end).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } BOOST_PYTHON_DEFINE_STR_METHOD(rjust, 1) BOOST_PYTHON_DEFINE_STR_METHOD(rstrip, 0) list str_base::split() const { return list(this->attr("split")()); } list str_base::split(object_cref sep) const { return list(this->attr("split")(sep)); } list str_base::split(object_cref sep, object_cref maxsplit) const { return list(this->attr("split")(sep,maxsplit)); } list str_base::splitlines() const { return list(this->attr("splitlines")()); } list str_base::splitlines(object_cref keepends) const { return list(this->attr("splitlines")(keepends)); } bool str_base::startswith(object_cref prefix) const { bool result = PyInt_AsLong(this->attr("startswith")(prefix).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } bool str_base::startswith(object_cref prefix, object_cref start) const { bool result = PyInt_AsLong(this->attr("startswith")(prefix,start).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } bool str_base::startswith(object_cref prefix, object_cref start, object_cref end) const { bool result = PyInt_AsLong(this->attr("startswith")(prefix,start,end).ptr()); if (PyErr_Occurred()) throw_error_already_set(); return result; } BOOST_PYTHON_DEFINE_STR_METHOD(strip, 0) BOOST_PYTHON_DEFINE_STR_METHOD(swapcase, 0) BOOST_PYTHON_DEFINE_STR_METHOD(title, 0) BOOST_PYTHON_DEFINE_STR_METHOD(translate, 1) BOOST_PYTHON_DEFINE_STR_METHOD(translate, 2) BOOST_PYTHON_DEFINE_STR_METHOD(upper, 0) }}} // namespace boost::python
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 353 ] ] ]
0337e8eccd4eb6b102039979534e2f4c16e69a0e
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/newton20/engine/core/src/ActorManager.cpp
29fd816eece4f301a39955204efc7565beeb760e
[ "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
ISO-8859-1
C++
false
false
16,168
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "stdinc.h" //precompiled header #include "ActorManager.h" #include "CoreSubsystem.h" #include "Actor.h" #include "CameraObject.h" #include "LightObject.h" #include "ListenerMovable.h" #include "ListenerObject.h" #include "MergeableMeshObject.h" #include "MeshObject.h" #include "BoxPrimitive.h" #include "MovableText.h" #include "PhysicalThing.h" #include "ScriptWrapper.h" #include "Sound.h" #include "SoundDriver.h" #include "SoundManager.h" #include "SoundObject.h" #include "World.h" using namespace Ogre; template<> rl::ActorManager* Singleton<rl::ActorManager>::ms_Singleton = 0; namespace rl { ActorManager::ActorManager() : mActors(), mWorld(CoreSubsystem::getSingleton().getWorld()), mActorRenderingDistance(100.0f) { } ActorManager::~ActorManager() { destroyAllActors(); } void ActorManager::setWorld( World* world ) { mWorld = world; } const World* const ActorManager::getWorld() const { return mWorld; } Ogre::Real ActorManager::getDefaultActorRenderingDistance() const { return mActorRenderingDistance; } void ActorManager::setDefaultActorRenderingDistance( Ogre::Real dist ) { for (ActorPtrMap::iterator it = mActors.begin(); it != mActors.end();) { Actor* actor = it->second; // Nur die Actoren verรคndern, deren Distanz nicht geรคndert wurde if( actor->getRenderingDistance() == mActorRenderingDistance ) { actor->setRenderingDistance( dist ); } ++it; } mActorRenderingDistance = dist; } Actor* ActorManager::getActor(const String& name) { ActorPtrMap::const_iterator pActorIter = mActors.find(name); if( pActorIter != mActors.end() ) return pActorIter->second; return 0; } void ActorManager::destroyActor(Actor* actor) { if (actor == NULL) { Throw(NullPointerException, "Argument actor darf nicht null sein." ); } ActorPtrMap::iterator it = mActors.find(actor->getName()); if (it == mActors.end()) { Throw(IllegalArgumentException, "Argument actor wird nicht vom ActorManager verwaltet."); } mActors.erase(it); LOG_MESSAGE("ActorManager", "Delete actor '"+actor->getName()+"'"); //actor->detachAllChildren(); //just avoiding a crash. is there a better resolution? // should not be needed, is also done in the destructor of the actor doDestroyActor(actor); } void ActorManager::doDestroyActor(Actor* actor) { RlAssert1(actor != NULL); ActorControlledObject* actObj = actor->getControlledObject(); PhysicalThing* physThing = actor->getPhysicalThing(); if (actor == SoundManager::getSingleton().getListenerActor()) { SoundManager::getSingleton()._clearListenerActor(); } ScriptWrapper::getSingleton().deleted(actor); delete actor; if (actObj) { ScriptWrapper::getSingleton().deleted(actObj); delete actObj; } if (physThing) { PhysicsManager::getSingleton().removeAndDestroyPhysicalThing(physThing); } } void ActorManager::destroyAllActors() { for (ActorPtrMap::iterator it = mActors.begin(); it != mActors.end();) { Actor* actor = it->second; mActors.erase(it++); doDestroyActor(actor); } } Actor* ActorManager::createLightActor(const String& name, rl::LightObject::LightTypes type ) { const String& uniquename = nextUniqueName(name); Actor* actor = 0; try { ///@todo Typen in Einklang bringen LightObject* lo = new LightObject(uniquename, type); actor = new Actor(uniquename, lo); mActors.insert(ActorPtrPair(uniquename,actor)); } catch (Ogre::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Das Licht '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getFullDescription()); } catch (rl::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Das Licht '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getMessage()); } return actor; } Actor* ActorManager::createSoundSampleActor(const String& name, const String& soundfile) { const String& uniquename = nextUniqueName(name); Actor* actor = 0; try { Sound* sm = SoundManager::getSingleton().getActiveDriver()-> createSound(soundfile, ST_SAMPLE); SoundObject* so = new SoundObject(sm, soundfile); actor = new Actor(uniquename, so); mActors.insert(ActorPtrPair(uniquename,actor)); } catch (Ogre::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Der Sound '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getFullDescription()); } catch (rl::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Der Sound '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getMessage()); } return actor; } Actor* ActorManager::createSoundStreamActor(const String& name, const String& soundfile) { const String& uniquename = nextUniqueName(name); Actor* actor = 0; try { Sound* sm = SoundManager::getSingleton().getActiveDriver()-> createSound(soundfile, ST_STREAM); SoundObject* so = new SoundObject(sm, soundfile); actor = new Actor(uniquename, so); mActors.insert(ActorPtrPair(uniquename,actor)); } catch (Ogre::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Der Sound '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getFullDescription()); } catch (rl::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Der Sound '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getMessage()); } return actor; } Actor* ActorManager::createListenerActor(const String& name) { const String& uniquename = nextUniqueName(name); Actor* actor = 0; try { ListenerMovable* lm = SoundManager::getSingleton(). getActiveDriver()->createListener(name); ListenerObject* lo = new ListenerObject(lm); actor = new Actor(uniquename, lo); mActors.insert(ActorPtrPair(uniquename,actor)); } catch (Ogre::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Der Listener '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getFullDescription()); } catch (rl::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Der Listener '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getMessage()); } return actor; } Actor* ActorManager::createEmptyActor(const String& name) { const String& uniquename = nextUniqueName(name); Actor* actor = new Actor(uniquename); mActors.insert(ActorPtrPair(uniquename,actor)); return actor; } Actor* ActorManager::createCameraActor(const String& name) { const String& uniquename = nextUniqueName(name); Actor* actor = 0; try { CameraObject* co = new CameraObject(uniquename); // the mass should be as small as possible, so the camera doesn't interact with other bodies, // but setting the mass to 0 means, that the body is static! PhysicalThing* pt = PhysicsManager::getSingleton() .createPhysicalThing(GT_SPHERE, co, 0.001f, true); PhysicsManager::getSingleton().createPhysicsProxy(pt, NULL); pt->_getBody()->setMaterialGroupID( PhysicsManager::getSingleton().createMaterialID("camera")); actor = new Actor(uniquename, co, pt); mActors.insert(ActorPtrPair(uniquename,actor)); } catch (Ogre::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Die Kamera '" + name + "' fรผr den Aktor '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getFullDescription()); } catch (rl::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Die Kamera '" + name + "' fรผr den Aktor '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getMessage()); } return actor; } Actor* ActorManager::createMeshActor(const String& name, const Ogre::String& basemeshname, const MeshPartMap& meshparts, GeometryType geomType, Ogre::Real mass) { if (meshparts.empty()) { return NULL; } const String& uniquename = nextUniqueName(name); Actor* actor = NULL; try { MergeableMeshObject* mmo = new MergeableMeshObject(uniquename, basemeshname); for (MeshPartMap::const_iterator partIt = meshparts.begin(); partIt != meshparts.end(); ++partIt) { if (partIt->second == basemeshname) { mmo->setBaseMeshPart(partIt->first); } mmo->addSubmesh(partIt->first, partIt->second); } PhysicalThing* pt = PhysicsManager::getSingleton() .createPhysicalThing(geomType, mmo, mass); actor = new Actor(uniquename, mmo, pt); mActors.insert(ActorPtrPair(uniquename,actor)); } catch (Ogre::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Mesh parts for actor '" + uniquename + "' could not be created. Reason: " + e.getFullDescription()); } catch (rl::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Mesh parts for actor '" + uniquename + "' could not be created. Reason: " + e.getMessage()); } return actor; } Actor* ActorManager::createMeshActor(const String& name, const String& meshname, GeometryType geomType, Ogre::Real mass, bool mergeable) { const String& uniquename = nextUniqueName(name); Actor* actor = NULL; try { MeshObject* mo = NULL; if (mergeable) { mo = new MergeableMeshObject(uniquename, meshname); } else { mo = new MeshObject(uniquename, meshname); } PhysicalThing* pt = PhysicsManager::getSingleton() .createPhysicalThing(geomType, mo, mass); actor = new Actor(uniquename, mo, pt); mActors.insert(ActorPtrPair(uniquename,actor)); } catch (Ogre::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Das Mesh '" + meshname + "' fรผr den Aktor '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getFullDescription()); } catch (rl::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Das Mesh '" + meshname + "' fรผr den Aktor '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getMessage()); } return actor; } Actor* ActorManager::createBoxPrimitiveActor(const Ogre::String& name, const Ogre::Vector3& minCorner, const Ogre::Vector3& maxCorner, const Ogre::String& materialName, Ogre::Real mass) { const String uniquename = nextUniqueName(name); // Make sure that min/maxCorners are valid. Since this is called by scripters, be lenient. Vector3 minC = minCorner; minC.makeFloor(maxCorner); Vector3 maxC = maxCorner; maxC.makeCeil(minCorner); AxisAlignedBox size = AxisAlignedBox(minC, maxC); Actor* actor = NULL; try { BoxPrimitive* bp = new BoxPrimitive(size, uniquename, materialName); PhysicalThing* pt = PhysicsManager::getSingleton() .createPhysicalThing(GT_BOX, bp, mass); actor = new Actor(uniquename, bp, pt); mActors.insert(ActorPtrPair(uniquename,actor)); } catch (Ogre::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Das BoxPrimitive fรผr den Aktor '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getFullDescription()); } catch (rl::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Das BoxPrimitive fรผr den Aktor '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getMessage()); } return actor; } Actor* ActorManager::createParticleSystemActor(const String& name,const String& partname) { const String& uniquename = nextUniqueName(name); Actor* actor = 0; try { ParticleSystemObject* po = new ParticleSystemObject(uniquename, partname); actor = new Actor(uniquename, po, 0); mActors.insert(ActorPtrPair(uniquename,actor)); } catch (Ogre::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Das Partikelsystem '" + partname + "' fรผr den Aktor '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getFullDescription()); } catch (rl::Exception& e) { LOG_ERROR(Logger::CORE, "ActorManager - Das Partikelsystem '" + partname + "' fรผr den Aktor '" + uniquename + "' konnte nicht erstellt werden. Grund: " + e.getMessage()); } return actor; } String ActorManager::nextUniqueName(const String& basename) { String newname = basename; static int id = 0; while( getActor(newname) != NULL ) { newname = basename + "_" + StringConverter::toString(++id); } if( basename != newname ) { LOG_WARNING(Logger::CORE, "ActorManager - Warnung! '" + basename + "' war schon vergeben! Neuer Name ist '" + newname + "'."); } return newname; } }
[ "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 502 ] ] ]
cc5549a6c7ce97ea012cd6e24810abf9ebd94322
fad6f9883d4ad2686c196dc532a9ecb9199500ee
/NXP-LPC/CommTest/CommTest/boost/memory/pools.hpp
3780b5cb91ffe110aed8334f8518b85dad68b389
[]
no_license
aquarius20th/nxp-lpc
fe83d6a140d361a1737d950ff728c6ea9a16a1dd
4abfb804daf0ac9c59bd90d879256e7a3c1b2f30
refs/heads/master
2021-01-10T13:54:40.237682
2009-12-22T14:54:59
2009-12-22T14:54:59
48,420,260
0
0
null
null
null
null
UTF-8
C++
false
false
2,572
hpp
// // boost/memory/pools.hpp // // Copyright (c) 2004 - 2008 xushiwei ([email protected]) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/memory/index.htm for documentation. // #ifndef BOOST_MEMORY_POOLS_HPP #define BOOST_MEMORY_POOLS_HPP #ifndef BOOST_MEMORY_POOL_HPP #include "pool.hpp" #endif #ifndef BOOST_MEMORY_REGION_ALLOC_HPP #include "region_alloc.hpp" #endif NS_BOOST_MEMORY_BEGIN // ------------------------------------------------------------------------- // class pools, scoped_pools template <class PolicyT, size_t nPool = 16, size_t nAlignBits = 3, int m_fPreAlloc = 1> class pools_alloc { private: pools_alloc(const pools_alloc&); const pools_alloc& operator=(const pools_alloc&); public: typedef size_t size_type; typedef fixed_alloc<PolicyT> pool_type; typedef region_alloc<PolicyT, m_fPreAlloc> region_alloc_type; typedef typename pool_type::alloc_type block_pool_type; private: enum { ALIGN_BITS = nAlignBits }; enum { NPOOL = nPool }; enum { ALIGN = 1 << ALIGN_BITS }; enum { MIN_BYTES = ALIGN }; enum { MAX_BYTES = ALIGN * NPOOL }; private: pool_type* m_pools[nPool]; block_pool_type m_recycle; region_alloc_type m_alloc; public: pools_alloc() { std::fill_n(m_pools, nPool, (pool_type*)NULL); } pools_alloc(block_pool_type recycle) : m_recycle(recycle), m_alloc(recycle) { std::fill_n(m_pools, nPool, (pool_type*)NULL); } block_pool_type BOOST_MEMORY_CALL get_block_pool() const { return m_recycle; } region_alloc_type& BOOST_MEMORY_CALL get_region_alloc() { return m_alloc; } pool_type& BOOST_MEMORY_CALL get_pool(size_type cb) { BOOST_MEMORY_ASSERT(has_pool(cb)); const size_type index = (cb - 1) >> ALIGN_BITS; pool_type* p = m_pools[index]; if (p == NULL) { const size_type cbElem = (index + 1) << ALIGN_BITS; m_pools[index] = p = BOOST_MEMORY_NEW(m_alloc, pool_type)(m_recycle, cbElem); } return *p; } bool BOOST_MEMORY_CALL has_pool(size_type cb) const { const size_type index = (cb - 1) >> ALIGN_BITS; return index < nPool; } }; typedef pools_alloc<NS_BOOST_MEMORY_POLICY::stdlib> pools; typedef pools_alloc<NS_BOOST_MEMORY_POLICY::scoped> scoped_pools; // ------------------------------------------------------------------------- // $Log: $ NS_BOOST_MEMORY_END #endif /* BOOST_MEMORY_POOLS_HPP */
[ "lijin.unix@13de9a6c-71d3-11de-b374-81e7cb8b6ca2" ]
[ [ [ 1, 104 ] ] ]
b9b13eb5dbaf9136a420daf87860d032aba3f73f
b0252ba622183d115d160eb28953189930ebf9c0
/Source/CGame.cpp
71d5225841298a1247d4747383ae3169138d13a8
[]
no_license
slewicki/khanquest
6c0ced33bffd3c9ee8a60c1ef936139a594fe2fc
f2d68072a1d207f683c099372454add951da903a
refs/heads/master
2020-04-06T03:40:18.180208
2008-08-28T03:43:26
2008-08-28T03:43:26
34,305,386
2
0
null
null
null
null
UTF-8
C++
false
false
40,122
cpp
////////////////////////////////////////////////////////// // File: "CGame.cpp" // // Author: Sean Hamstra (SH) // // Purpose: To contain all outer game functionality. ////////////////////////////////////////////////////////// #include "CGame.h" #include "CFactory.h" #include <fstream> #include <iostream> #include <string> #include "IntroState.h" #include "irrXML.h" #include "WinGameState.h" #include "LoseGameState.h" #include "DirectShow.h" #include "CWorldMapState.h" #include "KeyBindState.h" using namespace std; CGame::CGame(void) { PROFILE("CGame::CGame()"); m_pD3D = NULL; m_pTM = NULL; m_pDS = NULL; m_pWM = NULL; m_pDI = NULL; // m_pMap = NULL; m_nTerrorLevel = 0; m_dwPreviousTime = GetTickCount(); m_nFrameCounter = 0; m_nFPS = 0; m_dwFrameTimer = GetTickCount(); m_fGameTime = 0; m_nSFXVolume = 100; m_nMusicVolume = 50; *m_pCities = NULL; m_nGold = 0; m_nWins = 1; m_nLoses = 0; m_nFood = 0; m_pSelectedCity = NULL; m_chJinCount = m_chKCount = m_chXiaCount = 0; m_bFPS = true; m_szPlayerName[0] = 'E'; m_szPlayerName[1] = 'M'; m_szPlayerName[2] = 'P'; m_szPlayerName[3] = 'T'; m_szPlayerName[4] = 'Y'; m_szPlayerName[5] = '\0'; m_nCurrentSaveSlot = SLOT1; STOP("CGame::CGame()"); } CGame::~CGame(void) { PROFILE("CGame::~CGame()"); delete m_nPlayList; STOP("CGame::~CGame()"); } CGame* CGame::GetInstance(void) { PROFILE("CGame::GetInstance()"); static CGame instance; // Lazy instantiation // Since CGame is running the entire time STOP("CGame::GetInstance()"); return &instance; } bool CGame::Initialize(HWND hWnd, HINSTANCE hInstance, int nScreenWidth, int nScreenHeight, bool bIsWindowed) { PROFILE("CGame::Initialize(HWND, HINSTANCE, int, int, bool)"); srand(GetTickCount()); // Do game initialization here. m_hWnd = hWnd; m_hInstance = hInstance; //this->ParseBinaryUnitInfo("Resource/KQ_unitStats.dat"); // Get pointers to singletons: m_pD3D = CSGD_Direct3D::GetInstance(); m_pTM = CSGD_TextureManager::GetInstance(); m_pDS = CSGD_DirectSound::GetInstance(); m_pWM = CSGD_WaveManager::GetInstance(); m_pDI = CSGD_DirectInput::GetInstance(); // Call initialize on each wrapper: #pragma region WrapperInit if (!m_pD3D->InitDirect3D(hWnd, nScreenWidth, nScreenHeight, bIsWindowed, false)) { MessageBox(0, "InitDirect3D Failed", " Error", MB_OK); STOP("CGame::Initialize(HWND, HINSTANCE, int, int, bool)"); return false; } if (!m_pTM->InitTextureManager(m_pD3D->GetDirect3DDevice(), m_pD3D->GetSprite())) { MessageBox(0, "InitTextureManager Failed", " Error", MB_OK); STOP("CGame::Initialize(HWND, HINSTANCE, int, int, bool)"); return false; } if (!m_pDS->InitDirectSound(hWnd)) { MessageBox(0, "InitDirectSound Failed", " Error", MB_OK); STOP("CGame::Initialize(HWND, HINSTANCE, int, int, bool)"); return false; } if (!m_pWM->InitWaveManager(hWnd, m_pDS->GetDSObject())) { MessageBox(0, "InitWaveManager Failed", " Error", MB_OK); STOP("CGame::Initialize(HWND, HINSTANCE, int, int, bool)"); return false; } if (!m_pDI->InitDevices(hWnd, hInstance)) { MessageBox(0, "InitDevices Failed", " Error", MB_OK); STOP("CGame::Initialize(HWND, HINSTANCE, int, int, bool)"); return false; } #pragma endregion int nLoading; nLoading = m_pTM->LoadTexture("Resource/KQ_Loading.png"); m_pD3D->DeviceBegin(); m_pD3D->SpriteBegin(); m_pTM->Draw(nLoading,0,0); m_pD3D->SpriteEnd(); m_pD3D->DeviceEnd(); m_pD3D->Present(); /*if(bIsWindowed) m_pD3D->ChangeDisplayParam(800, 600, bIsWindowed);*/ // Init the Pixel Shader if (!m_PixelShader.Create("Resource/KQ_FoW.fx", m_pD3D->GetDirect3DDevice())) MessageBox(hWnd, "Failed to load Pixel Shader", "Error", MB_OK); m_nScreenWidth = nScreenWidth; m_nScreenHeight = nScreenHeight; this->ParseBinaryUnitInfo("Resource/KQ_unitStats.dat"); // Remember how the window started m_bIsWindowed = bIsWindowed; //m_pMap = CTileEngine::GetInstance(); InitCities(); SetCursorNormal(); m_nCurrentSong = 0; ParseOptions("Resource/KQ_Options.dat"); m_pAM = CAnimationManager::GetInstance(); m_pAM->BinParse("Resource/KQ_Infantry.dat", "Resource/KQ_Player_Infantry.png","Resource/Enemies/KQ_AI_Infantry.png"); m_pAM->BinParse("Resource/KQ_Axmen.dat", "Resource/KQ_Player_Axmen.png","Resource/Enemies/KQ_AI_Axmen.png"); m_pAM->BinParse("Resource/KQ_Cavalry.dat", "Resource/KQ_Player_Cavalry.png","Resource/Enemies/KQ_AI_Cavalry.png"); m_pAM->BinParse("Resource/KQ_Cavalry_Archer.dat", "Resource/KQ_Player_CavalryArcher.png","Resource/Enemies/KQ_AI_CavalryArcher.png"); m_pAM->BinParse("Resource/KQ_Archer.dat", "Resource/KQ_Player_Archer.png","Resource/Enemies/KQ_AI_Archer.png"); m_pAM->BinParse("Resource/KQ_War_Elephant.dat", "Resource/KQ_Player_War_Elephant.png","Resource/Enemies/KQ_AI_War_Elephant.png"); ChangeState(CIntroState::GetInstance()); // Create the render target. // D3DUSAGE_RENDERTARGET can only be used with D3DPOOL_DEFAULT m_pD3D->GetDirect3DDevice()->CreateTexture(m_nScreenWidth, m_nScreenHeight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_pRenderTarget, NULL); //m_pD3D->GetDirect3DDevice()->CreateTexture(m_nScreenWidth, m_nScreenHeight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_pVisibleTarget, NULL); m_nFontID = m_pTM->LoadTexture("Resource/KQ_FontLucidiaWhite.png"); m_BF.InitBitmapFont(m_nFontID,' ',16,128,128); this->ParsePlayList("Resource/KQ_PlayList.xml"); m_nAttackSoundID[UNIT_CAVALRY] =m_nAttackSoundID[UNIT_AXMEN] = m_nAttackSoundID[UNIT_INFANTRY] = m_pWM->LoadWave("Resource/KQ_SwordAttack.wav"); m_nAttackSoundID[UNIT_CAVALRY_ARCHER] = m_nAttackSoundID[UNIT_ARCHER] = m_pWM->LoadWave("Resource/KQ_ArrowAttack.wav"); m_nAttackSoundID[UNIT_WAR_ELEPHANT] = m_pWM->LoadWave("Resource/KQ_AttackElephant.wav"); m_nDeathSoundID[UNIT_AXMEN] = m_nDeathSoundID[UNIT_INFANTRY] = m_nDeathSoundID[UNIT_ARCHER] = m_pWM->LoadWave("Resource/KQ_DeathMen.wav"); m_nDeathSoundID[UNIT_CAVALRY] = m_nDeathSoundID[UNIT_CAVALRY_ARCHER] = m_pWM->LoadWave("Resource/KQ_DeathHorse.wav"); m_nDeathSoundID[UNIT_WAR_ELEPHANT] = m_pWM->LoadWave("Resource/KQ_DeathElephant.wav"); STOP("CGame::Initialize(HWND, HINSTANCE, int, int, bool)"); return true; } void CGame::Shutdown(void) { PROFILE("CGame::ShutDown()"); // Clean up current state ChangeState(NULL); CAnimationManager::GetInstance()->ReleaseImages(); CAnimationManager::GetInstance()->ClearSheets(); // Unload assets for (int i = 0; i < 10; i++) { m_pTM->ReleaseTexture(m_nFontID); m_pTM->ReleaseTexture(m_pCities[i]->GetImageID()); delete m_pCities[i]; m_pCities[i] = NULL; } // Safe Release if (m_pDI) { m_pDI->ShutdownDirectInput(); m_pDI = NULL; } if (m_pWM) { m_pWM->ShutdownWaveManager(); m_pWM = NULL; } if (m_pDS) { m_pDS->ShutdownDirectSound(); m_pDS = NULL; } if (m_pTM) { m_pTM->ShutdownTextureManager(); m_pTM = NULL; } if (m_pD3D) { m_pD3D->ShutdownDirect3D(); m_pD3D = NULL; } STOP("CGame::ShutDown()"); } bool CGame::Main(void) { PROFILE("CGame::Main()"); // Calculating Elapsed Time DWORD dwCurrentTime = GetTickCount(); float fElapsedTime = (float)(dwCurrentTime - m_dwPreviousTime) / 1000.0f; m_fGameTime += fElapsedTime; // Remember previous time for next frame m_dwPreviousTime = dwCurrentTime; // 1. Input m_pDI->ReadDevices(); // usually only want to call this ONCE per frame // Get input from all since during battle the HUD still needs input // Because of this use paused bools to stop input to other states // when pushing on states such as CCityInfoState over CWorldMapState // Fullscreen Toggling /*if( (m_pDI->GetBufferedKey(DIK_RETURN) || m_pDI->GetBufferedKey(DIK_NUMPADENTER) ) && (m_pDI->GetKey(DIK_LMENU) || m_pDI->GetKey(DIK_RMENU))) { m_bIsWindowed = !m_bIsWindowed; m_pD3D->ChangeDisplayParam(800, 600, m_bIsWindowed); ShowCursor(true); }*/ for(unsigned int i = 0; i < m_vStates.size(); i++) { // If false is returned, exit the game if(!m_vStates[i]->Input(fElapsedTime)) { STOP("CGame::Main()"); return false; } } // 2. Update - move objects, check collisions, do physics, do AI m_pWM->Update(); // clean up sound copies that aren't being used. // Update all, read Input comment for reason why for(unsigned int i = 0; i < m_vStates.size(); i++) { m_vStates[i]->Update(fElapsedTime); } if(!m_pWM->IsWavePlaying(m_nPlayList[m_nCurrentSong])) { m_pWM->SetVolume(m_nPlayList[m_nCurrentSong],m_nMusicVolume); m_pWM->Stop(m_nPlayList[m_nPreviousSong]); m_pWM->Play(m_nPlayList[m_nCurrentSong],DSBPLAY_LOOPING); m_nPreviousSong = m_nCurrentSong; } // 3. Draw // Check for Device //bool bDevice = m_pD3D->GetDirect3DDevice()->TestCooperativeLevel() == D3DERR_DEVICENOTRESET; //if(bDevice) //{ // m_pRenderTarget->Release(); // //m_pVisibleTarget->Release(); // HRESULT hr = m_pD3D->GetDirect3DDevice()->CreateTexture(m_nScreenWidth, m_nScreenHeight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_pRenderTarget, NULL); // if(hr != D3D_OK) // { // if(hr == D3DERR_INVALIDCALL) // int i = 1; // else if(hr == D3DERR_OUTOFVIDEOMEMORY) // int i = 1; // else if(hr == D3DERR_NOTAVAILABLE) // int i = 1; // else if (hr == E_OUTOFMEMORY) // int i = 1; // MessageBox(m_hWnd, "Failed to load texture", "Error", MB_OK); // } //} // /*hr = m_pD3D->GetDirect3DDevice()->CreateTexture(m_nScreenWidth, m_nScreenHeight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_pVisibleTarget, NULL); // if(hr != D3D_OK) // { // if(hr == D3DERR_INVALIDCALL) // int i = 1; // else if(hr == D3DERR_OUTOFVIDEOMEMORY) // int i = 1; // else if(hr == D3DERR_NOTAVAILABLE) // int i = 1; // else if (hr == E_OUTOFMEMORY) // int i = 1; // MessageBox(m_hWnd, "Failed to load texture", "Error", MB_OK); // }*/ //} if(/*m_bIsWindowed && */CDirectShow::GetInstance()->IsPlaying() && InvalidateRect(m_hWnd, 0, 0)) { STOP("CGame::Main()"); return true; } m_pD3D->Clear(0, 0, 0); m_pD3D->DeviceBegin(); m_pD3D->LineBegin(); m_pD3D->SpriteBegin(); //grab the backbuffer m_pD3D->GetDirect3DDevice()->GetRenderTarget(0, &m_pBackBuffer); if(m_vStates[0] == CGamePlayState::GetInstance()) { //Set Render Target LPDIRECT3DSURFACE9 pSurface = NULL; m_pRenderTarget->GetSurfaceLevel(0, &pSurface); m_pD3D->GetDirect3DDevice()->SetRenderTarget(0, pSurface); pSurface->Release(); //LPDIRECT3DTEXTURE9 pVisible = NULL; //D3DXCreateTextureFromFile(m_pD3D->GetDirect3DDevice(), "Resource/KQ_Circle.bmp", &pVisible); //m_pVisibleTarget = pVisible; ////m_pD3D->GetDirect3DDevice()->SetRenderTarget(0, pVisible); //pVisible->Release(); } m_pD3D->Clear(0, 0, 0); ////Print mouse position //char buffer2[128]; GetCursorPosition(); //sprintf_s(buffer2, _countof(buffer2), "Position: %i %i", ptMouse.x, ptMouse.y); //CSGD_Direct3D::GetInstance()->DrawTextA(buffer2, 120,20,255,255,255); // Render all states on the stack for(unsigned int i = 0; i < m_vStates.size(); i++) { m_vStates[i]->Render(fElapsedTime); } //m_pTM->Draw(m_nCursorID, ptMouse.x, ptMouse.y); //m_BF.DrawTextA(buffer2, 10, 10, .3f, .3f); //Print Frames Per Second if (m_bFPS) { char buffer[128]; sprintf_s(buffer, _countof(buffer), "FPS: %i", m_nFPS); m_BF.DrawTextA(buffer,0,20,.3f,.3f,D3DCOLOR_ARGB(255,255,255,255));//CSGD_Direct3D::GetInstance()->DrawTextA(buffer, 0,20,255,255,255); } m_pD3D->SpriteEnd(); m_pD3D->LineEnd(); m_pD3D->DeviceEnd(); // Count number of frames m_nFrameCounter++; // Check if one second has passed if (GetTickCount() - m_dwFrameTimer > 1000) { m_nFPS = m_nFrameCounter; // remember fps m_nFrameCounter = 0; // reset frame counter m_dwFrameTimer = GetTickCount(); } if(m_vStates[0] != CGamePlayState::GetInstance()) m_pD3D->Present(); else if (ObjectManager::GetInstance()->GetUnits().size() > 0) { //Setup Pixel shader for second loop m_pD3D->GetDirect3DDevice()->SetRenderTarget(0, m_pBackBuffer); m_pBackBuffer->Release(); //Pixel Shader Render m_pD3D->Clear(0, 0, 0); m_pD3D->DeviceBegin(); m_pD3D->SpriteBegin(); //process shader m_PixelShader.SetConstantFloat("Pos.x",ObjectManager::GetInstance()->GetUnits()[0]->GetPosX()); m_PixelShader.SetConstantFloat("Pos.Y", ObjectManager::GetInstance()->GetUnits()[0]->GetPosX()); //m_PixelShader.SetConstantFloat("texture1", m_pTM->LoadTexture("Resource/KQ_Circle.bmp")); m_PixelShader.Begin(); //Draw to the backbuffer m_pD3D->GetSprite()->Draw(m_pRenderTarget, 0, 0, 0, D3DCOLOR_XRGB(255, 255, 255)); m_pD3D->SpriteEnd(); m_PixelShader.End(); m_pD3D->DeviceEnd(); m_pD3D->Present(); } STOP("CGame::Main()"); return true; } void CGame::ChangeState(IGameState* pNewState) { PROFILE("CGame::ChangeState(IGameState*)"); // Exit out of all states on the stack for (unsigned int i = 0; i < m_vStates.size(); i++) { m_vStates[i]->Exit(); } // Clear all states from the stack m_vStates.clear(); // Add on the new state and Enter it if(pNewState) { m_vStates.push_back(pNewState); m_vStates[0]->Enter(); } STOP("CGame::ChangeState(IGameState*)"); } void CGame::PushState(IGameState* pNewState) { PROFILE("CGame::PushState(IGameState*)"); // Add on the new state and Enter it if(pNewState) { pNewState->Enter(); m_vStates.push_back(pNewState); } STOP("CGame::PushState(IGameState*)"); } void CGame::PopCurrentState() { PROFILE("CGame::PopCurrentState()"); // Exit the top state and remove it from the stack m_vStates[m_vStates.size()-1]->Exit(); m_vStates.pop_back(); STOP("CGame::PopCurrentState()"); } bool CGame::ParseXMLUnitInfo (const char* szFile) { PROFILE("CGame::ParseXMLUnitInfo(const char*)"); int nUnit, nHP, nAttack, nRange; nUnit = 0; float fAttackSpeed, fMovement; irr::io::IrrXMLReader* xml = irr::io::createIrrXMLReader(szFile); string szName; // parse the file until end reached while(xml && xml->read()) { switch(xml->getNodeType()) { case irr::io::EXN_ELEMENT: { szName = xml->getNodeName(); } break; case irr::io::EXN_TEXT: { if (!strcmp("HP", szName.c_str())) nHP = atoi(xml->getNodeName()); else if (!strcmp("Attack", szName.c_str())) nAttack = atoi(xml->getNodeName()); else if (!strcmp("Range", szName.c_str())) nRange = atoi(xml->getNodeName()); else if (!strcmp("AttackSpeed", szName.c_str())) fAttackSpeed = (float)atof(xml->getNodeName()); else if (!strcmp("Cost", szName.c_str())) fAttackSpeed = (float)atof(xml->getNodeName()); else if (!strcmp("Movement", szName.c_str())) { fMovement = (float)atof(xml->getNodeName()); // Player unit info m_pPlayerUnitInfo[nUnit].SetType(nUnit); m_pPlayerUnitInfo[nUnit].SetMaxHP(nHP); m_pPlayerUnitInfo[nUnit].SetAttackPower(nAttack); m_pPlayerUnitInfo[nUnit].SetRange(nRange); m_pPlayerUnitInfo[nUnit].SetAttackSpeed(fAttackSpeed); m_pPlayerUnitInfo[nUnit].SetSpeed(fMovement); // CPU unit info m_pCPUUnitInfo[nUnit].SetType(nUnit); m_pCPUUnitInfo[nUnit].SetMaxHP(nHP); m_pCPUUnitInfo[nUnit].SetAttackPower(nAttack); m_pCPUUnitInfo[nUnit].SetRange(nRange); m_pCPUUnitInfo[nUnit].SetAttackSpeed(fAttackSpeed); m_pCPUUnitInfo[nUnit].SetSpeed(fMovement); nUnit++; } szName = "none"; } break; } } // delete the xml parser after usage delete xml; STOP("CGame::ParseXMLUnitInfo(const char*)"); return true; } bool CGame::ParseBinaryUnitInfo (const char* szFile) { PROFILE("CGame::ParseBinaryUnitInfo(const char*)"); int nType, nHP, nAttack, nRange, nCost, nBuffer; double dAttackSpeed, dMovement, dBuffer; try { ifstream input(szFile,ios_base::binary); short length = 0; input.read((char*)&length, sizeof(length)); for (int i = 0; i < length; i++) { input.read((char*)&nType,sizeof(nType)); input.read((char*)&nHP,sizeof(nHP)); input.read((char*)&nAttack,sizeof(nAttack)); input.read((char*)&nRange,sizeof(nRange)); input.read((char*)&dAttackSpeed,sizeof(dAttackSpeed)); input.read((char*)&dMovement,sizeof(dMovement)); input.read((char*)&nCost,sizeof(nCost)); // Unneeded info //------------- input.read((char*)&nBuffer,sizeof(nBuffer)); input.read((char*)&nBuffer,sizeof(nBuffer)); input.read((char*)&nBuffer,sizeof(nBuffer)); input.read((char*)&nBuffer,sizeof(nBuffer)); input.read((char*)&nBuffer,sizeof(nBuffer)); input.read((char*)&nBuffer,sizeof(nBuffer)); input.read((char*)&dBuffer,sizeof(dBuffer)); input.read((char*)&dBuffer,sizeof(dBuffer)); input.read((char*)&dBuffer,sizeof(dBuffer)); input.read((char*)&dBuffer,sizeof(dBuffer)); input.read((char*)&nBuffer,sizeof(nBuffer)); input.read((char*)&nBuffer,sizeof(nBuffer)); //------------- // Player unit info m_pPlayerUnitInfo[i].SetType(nType); m_pPlayerUnitInfo[i].SetMaxHP(nHP); m_pPlayerUnitInfo[i].SetAttackPower(nAttack); m_pPlayerUnitInfo[i].SetRange(nRange); m_pPlayerUnitInfo[i].SetCost(nCost); m_pPlayerUnitInfo[i].SetAttackSpeed((float)dAttackSpeed); m_pPlayerUnitInfo[i].SetSpeed((float)dMovement); // CPU unit info m_pCPUUnitInfo[i].SetType(nType); m_pCPUUnitInfo[i].SetMaxHP(nHP); m_pCPUUnitInfo[i].SetAttackPower(nAttack); m_pCPUUnitInfo[i].SetRange(nRange); m_pCPUUnitInfo[i].SetAttackSpeed((float)dAttackSpeed); m_pCPUUnitInfo[i].SetSpeed((float)dMovement); } input.close(); } catch (std::exception e) { MessageBox(m_hWnd, "Error reading data. Reinstalling may fix the problem", "Error", MB_OK); STOP("CGame::ParseBinaryUnitInfo(const char*)"); return false; } STOP("CGame::ParseBinaryUnitInfo(const char*)"); return true; } bool CGame::ParsePlayList(const char* szFileName) { PROFILE("CGame::ParsePlayList(const char*)"); //Function variables - do not change string szName, szTempBool; IrrXMLReader* xml = createIrrXMLReader(szFileName); int nCounter = 0; while(xml && xml->read()) { switch(xml->getNodeType()) { case EXN_ELEMENT: { //Grabs the attribute name szName = xml->getNodeName(); } break; case EXN_TEXT: { //Checks the Attribute name and sets the approiate value if(!strcmp("NumSongs",szName.c_str())) { m_nNumSongs = atoi(xml->getNodeName()); m_nPlayList = new int[m_nNumSongs]; } if (!strcmp("Song", szName.c_str())) { string idk = xml->getNodeName(); char temp[128]; strncpy(temp,idk.c_str(),idk.length()); temp[idk.length()] = 0; m_nPlayList[nCounter] = m_pWM->LoadWave(temp); nCounter++; } szName = "none"; } break; } } //Delete the parser delete xml; STOP("CGame::ParsePlayList(const char*)"); return true; } CUnit CGame::GetUnitInfo (int nType) { PROFILE("CGame::GetUnitInfo(int)"); if(nType >=0 && nType <=5) { STOP("CGame::GetUnitInfo(int)"); return this->m_pPlayerUnitInfo[nType]; } else { CUnit unit; STOP("CGame::GetUnitInfo(int)"); return unit; } } CUnit CGame::GetCPUUnitInfo (int nType) { PROFILE("CGame::GetCPUInfo(int)"); if(nType >=0 && nType <=5) { STOP("CGame::GetCPUInfo(int)"); return this->m_pCPUUnitInfo[nType]; } else { CUnit unit; STOP("CGame::GetCPUInfo(int)"); return unit; } } POINT CGame::GetCursorPosition() { PROFILE("CGame::GetCursorPosition()"); GetCursorPos(&m_ptMousePos); POINT pos = GetWindowPosition(); m_ptMousePos.x -= pos.x; m_ptMousePos.y -= pos.y; STOP("CGame::GetCursorPosition()"); return m_ptMousePos; } POINT CGame::GetWindowPosition() { PROFILE("CGame::getWindowPosition()"); RECT rWindow; GetWindowRect(m_hWnd,&rWindow); POINT pos = {rWindow.left, rWindow.top}; if(this->m_bIsWindowed) { pos.x += (int)(m_ptWindOffset.x*.5f); pos.y += (int)(m_ptWindOffset.y-m_ptWindOffset.x*.5f); } STOP("CGame::getWindowPosition()"); return pos; } void CGame::InitCities() { PROFILE("CGame::InitCities()"); for (int i = 0; i < 10; i++) { if(m_pCities[i]) { delete m_pCities[i]; } m_pCities[i] = new CCity(); m_pCities[i]->SetID(i); } // Player City m_pCities[PCITY]->SetDefaultColor(PCITY); m_pCities[PCITY]->SetGoldTribute(0); m_pCities[PCITY]->SetOriginalOwner(PLAYER_CITY); m_pCities[PCITY]->SetImageID(m_pTM->LoadTexture("Resource/KQ_Mongolia.png")); m_pCities[PCITY]->SetClickRect(0, 0, 0, 0); m_pCities[PCITY]->AddAdjacent(KCITY1); m_pCities[PCITY]->AddAdjacent(XCITY1); m_pCities[PCITY]->AddAdjacent(JCITY1); m_pCities[PCITY]->AddAdjacent(JCITY2); m_pCities[PCITY]->AddAdjacent(KCITY2); // Khwarezmian Cities //------------------------------------------------------------------- // Click Rects m_pCities[KCITY1]->SetClickRect(109, 225, 56, 56); m_pCities[KCITY2]->SetClickRect(229, 250, 56, 56); m_pCities[KCITY3]->SetClickRect(194, 371, 56, 56); // Attack point symbol m_pCities[KCITY1]->SetAttackPoint(109, 225); m_pCities[KCITY2]->SetAttackPoint(229, 250); m_pCities[KCITY3]->SetAttackPoint(194, 371); m_pCities[KCITY1]->SetDefaultColor(KCITY1); m_pCities[KCITY1]->SetGoldTribute(300); m_pCities[KCITY1]->SetOriginalOwner(K_CITY); m_pCities[KCITY1]->SetImageID(m_pTM->LoadTexture("Resource/KQ_kEasy.png")); // Adjacent m_pCities[KCITY1]->AddAdjacent(KCITY2); m_pCities[KCITY1]->AddAdjacent(KCITY3); m_pCities[KCITY2]->SetDefaultColor(KCITY2); m_pCities[KCITY2]->SetGoldTribute(525); m_pCities[KCITY2]->SetOriginalOwner(K_CITY); m_pCities[KCITY2]->SetImageID(m_pTM->LoadTexture("Resource/KQ_kMedium.png")); // Adjacent m_pCities[KCITY2]->AddAdjacent(KCITY1); m_pCities[KCITY2]->AddAdjacent(KCITY3); m_pCities[KCITY2]->AddAdjacent(XCITY1); m_pCities[KCITY2]->AddAdjacent(XCITY2); m_pCities[KCITY3]->SetDefaultColor(KCITY3); m_pCities[KCITY3]->SetGoldTribute(850); m_pCities[KCITY3]->SetOriginalOwner(K_CITY); m_pCities[KCITY3]->SetImageID(m_pTM->LoadTexture("Resource/KQ_kHard.png")); // Adjacent m_pCities[KCITY3]->AddAdjacent(KCITY1); m_pCities[KCITY3]->AddAdjacent(KCITY2); m_pCities[KCITY3]->AddAdjacent(XCITY2); //------------------------------------------------------------------- // Xia Cities //------------------------------------------------------------------- // Click Rects m_pCities[XCITY1]->SetClickRect(376, 285, 56, 56); m_pCities[XCITY2]->SetClickRect(469, 407, 56, 56); m_pCities[XCITY3]->SetClickRect(642, 413, 56, 56); // Attack point symbol m_pCities[XCITY1]->SetAttackPoint(376, 285); m_pCities[XCITY2]->SetAttackPoint(469, 407); m_pCities[XCITY3]->SetAttackPoint(642, 413); m_pCities[XCITY1]->SetDefaultColor(XCITY1); m_pCities[XCITY1]->SetGoldTribute(275); m_pCities[XCITY1]->SetOriginalOwner(XIA_CITY); m_pCities[XCITY1]->SetImageID(m_pTM->LoadTexture("Resource/KQ_xiaEasy.png")); // Adjacent m_pCities[XCITY1]->AddAdjacent(XCITY2); m_pCities[XCITY1]->AddAdjacent(KCITY2); m_pCities[XCITY1]->AddAdjacent(JCITY2); m_pCities[XCITY2]->SetDefaultColor(XCITY2); m_pCities[XCITY2]->SetGoldTribute(525); m_pCities[XCITY2]->SetOriginalOwner(XIA_CITY); m_pCities[XCITY2]->SetImageID(m_pTM->LoadTexture("Resource/KQ_xiaMedium.png")); // Adjacent m_pCities[XCITY2]->AddAdjacent(KCITY2); m_pCities[XCITY2]->AddAdjacent(KCITY3); m_pCities[XCITY2]->AddAdjacent(XCITY1); m_pCities[XCITY2]->AddAdjacent(JCITY2); m_pCities[XCITY2]->AddAdjacent(XCITY3); m_pCities[XCITY3]->SetDefaultColor(XCITY3); m_pCities[XCITY3]->SetGoldTribute(850); m_pCities[XCITY3]->SetOriginalOwner(XIA_CITY); m_pCities[XCITY3]->SetImageID(m_pTM->LoadTexture("Resource/KQ_xiaHard.png")); // Adjacent m_pCities[XCITY3]->AddAdjacent(XCITY2); m_pCities[XCITY3]->AddAdjacent(JCITY2); //------------------------------------------------------------------- // Jin Cities //------------------------------------------------------------------- // Click Rects m_pCities[JCITY1]->SetClickRect(534, 53, 56, 56); m_pCities[JCITY2]->SetClickRect(547, 207, 56, 56); m_pCities[JCITY3]->SetClickRect(661, 123, 56, 56); // Attack point symbol m_pCities[JCITY1]->SetAttackPoint(534, 53); m_pCities[JCITY2]->SetAttackPoint(547, 207); m_pCities[JCITY3]->SetAttackPoint(661, 123); m_pCities[JCITY1]->SetDefaultColor(JCITY1); m_pCities[JCITY1]->SetGoldTribute(300); m_pCities[JCITY1]->SetOriginalOwner(JIN_CITY); m_pCities[JCITY1]->SetImageID(m_pTM->LoadTexture("Resource/KQ_jinEasy.png")); // Adjacent m_pCities[JCITY1]->AddAdjacent(JCITY2); m_pCities[JCITY1]->AddAdjacent(JCITY3); m_pCities[JCITY2]->SetDefaultColor(JCITY2); m_pCities[JCITY2]->SetGoldTribute(525); m_pCities[JCITY2]->SetOriginalOwner(JIN_CITY); m_pCities[JCITY2]->SetImageID(m_pTM->LoadTexture("Resource/KQ_jinMedium.png")); // Adjacent m_pCities[JCITY2]->AddAdjacent(JCITY1); m_pCities[JCITY2]->AddAdjacent(JCITY3); m_pCities[JCITY2]->AddAdjacent(XCITY1); m_pCities[JCITY2]->AddAdjacent(XCITY2); m_pCities[JCITY2]->AddAdjacent(XCITY3); m_pCities[JCITY3]->SetDefaultColor(JCITY3); m_pCities[JCITY3]->SetGoldTribute(850); m_pCities[JCITY3]->SetOriginalOwner(JIN_CITY); m_pCities[JCITY3]->SetImageID(m_pTM->LoadTexture("Resource/KQ_jinHard.png")); // Adjacent m_pCities[JCITY3]->AddAdjacent(JCITY1); m_pCities[JCITY3]->AddAdjacent(JCITY2); //------------------------------------------------------------------- STOP("CGame::InitCities()"); } int CGame::GetNumConquered() { PROFILE("CGame::getNumConquered()"); int nConquered = 0; // Skip the Mongolia (i=0) for (int i = 1; i < 10; i++) { if(m_pCities[i]->GetOwner() == PLAYER_CITY) nConquered++; } STOP("CGame::getNumConquered()"); return nConquered; } int CGame::GetNextFoodTribute() { PROFILE("CGame::GetNextFoodTribute()"); int nConquered = GetNumConquered(); if(nConquered >= 6) { STOP("CGame::GetNextFoodTribute()"); return 0; } switch(GetNumConquered()+1) { case 1: return 250; break; case 2: return 300; break; case 3: return 300; break; case 4: return 350; break; case 5: return 400; break; case 6: return 400; break; default: STOP("CGame::GetNextFoodTribute()"); return 0; } } int CGame::GetTotalFoodTribute() { PROFILE("CGame::getTotalFoodTribute()"); switch(GetNumConquered()) { case 0: m_nFood = 1000; break; case 1: m_nFood = 1250; break; case 2: m_nFood = 1550; break; case 3: m_nFood = 1850; break; case 4: m_nFood = 2200; break; case 5: m_nFood = 2600; break; default: m_nFood = 3000; break; } STOP("CGame::getTotalFoodTribute()"); return m_nFood; } void CGame::SetCityConquered(CCity* pCity) { PROFILE("CGame::SetCityConquered(CCity*)"); switch(pCity->GetOwner()) { case XIA_CITY: m_chXiaCount++; break; case JIN_CITY: m_chJinCount++; break; case K_CITY: m_chKCount++; break; }; pCity->SetOwner(PLAYER_CITY); // Add it to our conquered ID list m_vConqueredCities.push_back(pCity->GetID()); // Give our player the gold loot! CGame::GetInstance()->SetTotalGold(CGame::GetInstance()->GetTotalGold() + pCity->GetGoldTribute()); // This city can no longer be sacked for gold pCity->SetGoldTribute(0); GetTotalFoodTribute(); //AddWins(); STOP("CGame::SetCityConquered(CCity*)"); } void CGame::LoseLastCity() { PROFILE("CGame::LoseLastCity()"); if(m_vConqueredCities.size() < 1) { STOP("CGame::LoseLastCity()"); return; } int nCityID = m_vConqueredCities[m_vConqueredCities.size()-1]; m_vConqueredCities.pop_back(); m_pCities[nCityID]->Revolt(); switch(m_pCities[nCityID]->GetOwner()) { case XIA_CITY: if(m_chXiaCount < 3) m_chXiaCount--; break; case JIN_CITY: if(m_chJinCount < 3) m_chJinCount--; break; case K_CITY: if(m_chKCount < 3) m_chKCount--; break; }; if(m_nWins > 1) --m_nWins; STOP("CGame::LoseLastCity()"); } void CGame::AddWins(bool bUsedTerror) { bool bNewUnit1 = false; bool bNewUnit2 = false; bool bNewUnit3 = false; PROFILE("CGame::AddWins()"); if(m_chKCount <3) bNewUnit1 = true; if(m_chXiaCount <3) bNewUnit2 = true; if(m_chJinCount <3) bNewUnit3 = true; SetCityConquered(m_pSelectedCity); ++m_nWins; if(m_nLoses > 0) --m_nLoses; if(GetTerrorLevel() < 100 && !bUsedTerror) { SetTerrorLevel(GetTerrorLevel() + 25); } else if(bUsedTerror) SetTerrorLevel(0); if(GetTerrorLevel() == 100) { CWorldMapState::GetInstance()->SetTerror(true); } if(m_chKCount ==3 && bNewUnit1) CWorldMapState::GetInstance()->SetUnlockedUnit(true); if(m_chXiaCount ==3 && bNewUnit2) CWorldMapState::GetInstance()->SetUnlockedUnit(true); if(m_chJinCount ==3 && bNewUnit3) CWorldMapState::GetInstance()->SetUnlockedUnit(true); if(m_vConqueredCities.size() == (TOTAL_CITIES-1)) { ChangeState(CWinGameState::GetInstance()); } else Save(false); STOP("CGame::AddWins()"); } void CGame::AddLoses() { PROFILE("CGame::AddLoses()"); ++m_nLoses; SetTerrorLevel(GetTerrorLevel() - 25); if(m_nLoses >= 2 && this->GetNumConquered() == 0) { while(m_vStates.size() > 0) PopCurrentState(); PushState(CMainMenuState::GetInstance()); PushState(CLoseGameState::GetInstance()); } else if(m_nLoses >= 2) { LoseLastCity(); m_nLoses = 0; } else { Save(false); } STOP("CGame::AddLoses()"); } bool CGame::LoadSlot(int nSlot) { PROFILE("CGame::LoadSlot(int)"); NewGame(nSlot); string szSaveSlot; switch (nSlot) { case SLOT1: m_nCurrentSaveSlot = SLOT1; szSaveSlot = "Resource/KQ_Save1.dat"; break; case SLOT2: m_nCurrentSaveSlot = SLOT2; szSaveSlot = "Resource/KQ_Save2.dat"; break; case SLOT3: m_nCurrentSaveSlot = SLOT3; szSaveSlot = "Resource/KQ_Save3.dat"; break; default: m_nCurrentSaveSlot = -1; STOP("CGame::LoadSlot(int)"); return false; } try { ifstream input; input.open(szSaveSlot.c_str(),ios_base::binary); if(!input.is_open()) { MessageBox(m_hWnd, "Save file not found. Try making a new one." , "Error", MB_OK); STOP("CGame::LoadSlot(int)"); return false; } int nLength = 0; input.read((char*)&nLength, sizeof(nLength)); input.read(m_szPlayerName, nLength); // Food total input.read((char*)&m_nFood , sizeof(m_nFood)); // Gold total input.read((char*)&m_nGold , sizeof(m_nGold)); int tempGold = m_nGold; //Conquered Cities int nConquered = 0; int nCity = 0; input.read((char*) &nConquered , sizeof( nConquered)); for ( int i = 0; i < nConquered; i++) { input.read((char*)&nCity , sizeof(nCity )); SetCityConquered(m_pCities[nCity]); } input.read((char*)&m_nTerrorLevel, sizeof(m_nTerrorLevel)); int nType, nMaxHP, nAttack, nRange, nCost; float fAttack, fSpeed; for (int i = 0; i < 6; i++) { // read out player unit stats (upgrades inside) input.read((char*)&nType, sizeof(nType)); input.read((char*)&nMaxHP, sizeof(nMaxHP)); input.read((char*)&nAttack, sizeof(nAttack)); input.read((char*)&nRange, sizeof(nRange)); input.read((char*)&fAttack, sizeof(fAttack)); input.read((char*)&fSpeed, sizeof(fSpeed)); input.read((char*)&nCost, sizeof(nCost)); m_pPlayerUnitInfo[i].SetType(nType); m_pPlayerUnitInfo[i].SetMaxHP(nMaxHP); m_pPlayerUnitInfo[i].SetAttackPower(nAttack); m_pPlayerUnitInfo[i].SetRange(nRange); m_pPlayerUnitInfo[i].SetAttackSpeed(fAttack); m_pPlayerUnitInfo[i].SetSpeed(fSpeed); m_pPlayerUnitInfo[i].SetCost(nCost); } // read out which upgrades are active // Wins total input.read((char*)&m_nWins , sizeof(m_nWins)); // Loses total input.read((char*)&m_nLoses , sizeof(m_nLoses)); // Jin Count (num jin conquered) input.read((char*)&m_chJinCount , sizeof(m_chJinCount)); input.read((char*)&m_chXiaCount , sizeof(m_chXiaCount)); input.read((char*)&m_chKCount , sizeof(m_chKCount)); input.read((char*)&m_bUpGrades, sizeof(m_bUpGrades)); input.close(); // Reset gold since setcityconquered will add on to it m_nGold = tempGold; } catch (std::exception e) { MessageBox(m_hWnd, "Error loading data. My bad...", "Error", MB_OK); STOP("CGame::LoadSlot(int)"); return false; } PushState(CWorldMapState::GetInstance()); STOP("CGame::LoadSlot(int)"); return true; } void CGame::NewGame(int nSlot) { PROFILE("CGame::NewGame(int)"); m_nCurrentSaveSlot = nSlot; *m_pCities = NULL; m_nGold = 0; m_nTerrorLevel = 0; m_nWins = 1; m_nLoses = 0; m_nFood = 0; m_pSelectedCity = NULL; m_vConqueredCities.clear(); m_chJinCount = m_chKCount = m_chXiaCount = 0; this->ParseBinaryUnitInfo("Resource/KQ_unitStats.dat"); InitCities(); for(int j = 0; j < 6; ++j) { for(int i = 0; i < 3; ++i) { m_bUpGrades[j][i] = false; } } STOP("CGame::NewGame(int)"); } bool CGame::Save(bool bNewSave) { PROFILE("CGame::Save(bool)"); string szSaveSlot; switch (m_nCurrentSaveSlot) { case SLOT1: m_nCurrentSaveSlot = SLOT1; szSaveSlot = "Resource/KQ_Save1.dat"; m_szPlayerName[0] = 'G'; m_szPlayerName[1] = 'A'; m_szPlayerName[2] = 'M'; m_szPlayerName[3] = 'E'; m_szPlayerName[4] = '1'; m_szPlayerName[5] = '\0'; break; case SLOT2: m_nCurrentSaveSlot = SLOT2; szSaveSlot = "Resource/KQ_Save2.dat"; m_szPlayerName[0] = 'G'; m_szPlayerName[1] = 'A'; m_szPlayerName[2] = 'M'; m_szPlayerName[3] = 'E'; m_szPlayerName[4] = '2'; m_szPlayerName[5] = '\0'; break; case SLOT3: m_nCurrentSaveSlot = SLOT3; szSaveSlot = "Resource/KQ_Save3.dat"; m_szPlayerName[0] = 'G'; m_szPlayerName[1] = 'A'; m_szPlayerName[2] = 'M'; m_szPlayerName[3] = 'E'; m_szPlayerName[4] = '3'; m_szPlayerName[5] = '\0'; break; default: m_nCurrentSaveSlot = -1; STOP("CGame::Save(bool)"); return false; } if(bNewSave) { m_szPlayerName[0] = 'E'; m_szPlayerName[1] = 'M'; m_szPlayerName[2] = 'P'; m_szPlayerName[3] = 'T'; m_szPlayerName[4] = 'Y'; m_szPlayerName[5] = '\0'; } try { ofstream output(szSaveSlot.c_str(),ios_base::binary); int length = sizeof(m_szPlayerName); output.write((char*)&length, sizeof(length)); output.write(m_szPlayerName, sizeof(m_szPlayerName)); // Food total output.write((char*)&m_nFood , sizeof(m_nFood)); // Gold total output.write((char*)&m_nGold , sizeof(m_nGold)); //Conquered Cities int nConquered = (int)m_vConqueredCities.size(); output.write((char*)&nConquered , sizeof( nConquered)); for (unsigned int i = 0; i < m_vConqueredCities.size(); i++) { output.write((char*)&m_vConqueredCities[i] , sizeof(m_vConqueredCities[i] )); } output.write((char*)&m_nTerrorLevel, sizeof(m_nTerrorLevel)); int nType, nMaxHP, nAttack, nRange, nCost; float fAttack, fSpeed; for (int i = 0; i < 6; i++) { // Write out player unit stats (upgrades inside) //output.write(reinterpret_cast<char *>(&m_pPlayerUnitInfo[i]) , sizeof(m_pPlayerUnitInfo[i])); nType = m_pPlayerUnitInfo[i].GetType(); nMaxHP = m_pPlayerUnitInfo[i].GetMaxHP(); nAttack = m_pPlayerUnitInfo[i].GetAttackPower(); nRange = m_pPlayerUnitInfo[i].GetRange(); fAttack = m_pPlayerUnitInfo[i].GetAttackSpeed(); fSpeed = m_pPlayerUnitInfo[i].GetSpeed(); nCost = m_pPlayerUnitInfo[i].GetCost(); output.write((char *)(&nType ), sizeof(nType)); output.write((char *)(&nMaxHP ), sizeof(nMaxHP)); output.write((char *)(&nAttack ), sizeof(nAttack)); output.write((char *)(&nRange ), sizeof(nRange)); output.write((char *)(&fAttack ), sizeof(fAttack)); output.write((char *)(&fSpeed ), sizeof(fSpeed)); output.write((char *)(&nCost ), sizeof(nCost)); } // Write out which upgrades are active // Wins total output.write((char*)&m_nWins , sizeof(m_nWins)); // Loses total output.write((char*)&m_nLoses , sizeof(m_nLoses)); // Jin Count (num jin conquered) output.write((char*)&m_chJinCount , sizeof(m_chJinCount)); output.write((char*)&m_chXiaCount , sizeof(m_chXiaCount)); output.write((char*)&m_chKCount , sizeof(m_chKCount)); output.write((char*)&m_bUpGrades, sizeof(m_bUpGrades)); output.close(); } catch (std::exception e) { MessageBox(m_hWnd, "Error saving data. Reinstalling may fix the problem (yeah right).", "Error", MB_OK); STOP("CGame::Save(bool)"); return false; } STOP("CGame::Save(bool)"); return true; } string CGame::GetSaveName(int nSlot, bool bTitle) { PROFILE("CGame::GetSaveName(int, bool)"); string szSaveSlot; char szName[6]; int nFood, nGold, nConquered; switch (nSlot) { case SLOT1: szSaveSlot = "Resource/KQ_Save1.dat"; break; case SLOT2: szSaveSlot = "Resource/KQ_Save2.dat"; break; case SLOT3: szSaveSlot = "Resource/KQ_Save3.dat"; break; default: m_nCurrentSaveSlot = -1; STOP("CGame::GetSaveName(int, bool)"); return false; } try { ifstream input; input.open(szSaveSlot.c_str(),ios_base::binary); if(!input.is_open()) { //MessageBox(m_hWnd, "Save file not found. Try making a new one." , "Error", MB_OK); if(bTitle) { STOP("CGame::GetSaveName(int, bool)"); return "EMPTY"; } else " "; } int nLength = 0; input.read((char*)&nLength, sizeof(nLength)); input.read(szName, nLength); // Food total input.read((char*)&nFood , sizeof(nFood)); // Gold total input.read((char*)&nGold , sizeof(nGold)); input.read((char*) &nConquered , sizeof( nConquered)); } catch (std::exception e) { MessageBox(m_hWnd, "Error reading files.", "Error", MB_OK); STOP("CGame::GetSaveName(int, bool)"); return false; } string szInfo; char buffer[128]; sprintf_s(buffer, 128, "/Conquered: %i Food: %i Gold: %i", nConquered, nFood, nGold); szInfo = buffer; if(bTitle) { STOP("CGame::GetSaveName(int, bool)"); return szName; } else { STOP("CGame::GetSaveName(int, bool)"); return szInfo; } } void CGame::ParseOptions(char* szFileName) { PROFILE("CGame::ParseOptions(char*)"); ifstream toRead; toRead.open(szFileName,ios::in | ios::binary); for( int i = 0; i < 4 ;++i) { DWORD temp; toRead.read((char*)&temp,sizeof(temp)); CKeyBindState::GetInstance()->BindKey(temp,i); } toRead.read((char*)&m_bFPS,sizeof(m_bFPS)); toRead.read((char*)&m_bShowBoxes,sizeof(m_bShowBoxes)); toRead.read((char*)&m_nMusicVolume,sizeof(m_nMusicVolume)); toRead.read((char*)&m_nSFXVolume,sizeof(m_nSFXVolume)); STOP("CGame::ParseOptions(char*)"); } void CGame::SwitchFullScreen() { m_bIsWindowed = !m_bIsWindowed; if(m_bIsWindowed) m_pD3D->ChangeDisplayParam(808, 629, m_bIsWindowed); else m_pD3D->ChangeDisplayParam(800, 600, m_bIsWindowed); Shutdown(); this->Initialize(m_hWnd, m_hInstance, 800, 600, m_bIsWindowed); if(!m_bIsWindowed) SetWindowOffset(0, 0); else SetWindowOffset(6, 29); ChangeState(CMainMenuState::GetInstance()); }
[ "[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec", "[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec", "[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec", "[email protected]@631b4192-2952-0410-9426-c5ed74a7d3ec" ]
[ [ [ 1, 13 ], [ 19, 19 ], [ 21, 24 ], [ 26, 30 ], [ 32, 38 ], [ 40, 41 ], [ 45, 46 ], [ 48, 54 ], [ 56, 59 ], [ 63, 66 ], [ 68, 69 ], [ 71, 76 ], [ 79, 95 ], [ 97, 101 ], [ 103, 107 ], [ 109, 114 ], [ 116, 121 ], [ 123, 125 ], [ 130, 130 ], [ 132, 132 ], [ 134, 135 ], [ 141, 144 ], [ 148, 150 ], [ 154, 154 ], [ 161, 161 ], [ 172, 173 ], [ 180, 182 ], [ 184, 186 ], [ 188, 191 ], [ 193, 196 ], [ 198, 223 ], [ 225, 228 ], [ 230, 258 ], [ 261, 261 ], [ 263, 276 ], [ 285, 285 ], [ 287, 323 ], [ 331, 335 ], [ 337, 337 ], [ 339, 353 ], [ 359, 360 ], [ 362, 370 ], [ 380, 394 ], [ 396, 423 ], [ 425, 429 ], [ 431, 445 ], [ 447, 450 ], [ 452, 457 ], [ 459, 462 ], [ 464, 466 ], [ 468, 471 ], [ 473, 531 ], [ 533, 537 ], [ 539, 601 ], [ 603, 605 ], [ 607, 609 ], [ 657, 657 ], [ 659, 659 ], [ 662, 662 ], [ 664, 666 ], [ 668, 673 ], [ 675, 675 ], [ 678, 678 ], [ 680, 682 ], [ 684, 689 ], [ 691, 694 ], [ 696, 700 ], [ 702, 709 ], [ 711, 715 ], [ 717, 718 ], [ 723, 869 ], [ 871, 875 ], [ 877, 883 ], [ 885, 889 ], [ 891, 892 ], [ 895, 895 ], [ 897, 917 ], [ 919, 923 ], [ 925, 927 ], [ 929, 930 ], [ 932, 933 ], [ 935, 936 ], [ 938, 939 ], [ 941, 942 ], [ 944, 945 ], [ 947, 948 ], [ 951, 954 ], [ 956, 981 ], [ 983, 986 ], [ 988, 988 ], [ 991, 991 ], [ 993, 1011 ], [ 1016, 1016 ], [ 1018, 1018 ], [ 1020, 1022 ], [ 1024, 1029 ], [ 1034, 1052 ], [ 1054, 1054 ], [ 1056, 1058 ], [ 1066, 1069 ], [ 1076, 1080 ], [ 1082, 1088 ], [ 1091, 1095 ], [ 1097, 1114 ], [ 1116, 1125 ], [ 1127, 1202 ], [ 1204, 1207 ], [ 1209, 1213 ], [ 1215, 1233 ], [ 1235, 1238 ], [ 1240, 1274 ], [ 1276, 1351 ], [ 1353, 1355 ], [ 1357, 1359 ], [ 1361, 1364 ], [ 1366, 1381 ], [ 1383, 1393 ], [ 1396, 1396 ], [ 1398, 1417 ], [ 1419, 1427 ], [ 1430, 1430 ], [ 1432, 1432 ], [ 1435, 1435 ], [ 1459, 1463 ], [ 1467, 1467 ], [ 1469, 1469 ], [ 1471, 1471 ] ], [ [ 14, 17 ], [ 31, 31 ], [ 42, 44 ], [ 61, 61 ], [ 78, 78 ], [ 145, 147 ], [ 155, 160 ], [ 162, 162 ], [ 356, 358 ], [ 361, 361 ], [ 656, 656 ], [ 719, 722 ], [ 928, 928 ], [ 931, 931 ], [ 934, 934 ], [ 937, 937 ], [ 940, 940 ], [ 943, 943 ], [ 946, 946 ], [ 950, 950 ], [ 1012, 1013 ], [ 1017, 1017 ], [ 1019, 1019 ], [ 1030, 1033 ], [ 1053, 1053 ], [ 1055, 1055 ], [ 1061, 1063 ], [ 1065, 1065 ], [ 1070, 1075 ], [ 1081, 1081 ], [ 1352, 1352 ], [ 1453, 1453 ] ], [ [ 18, 18 ], [ 20, 20 ], [ 39, 39 ], [ 47, 47 ], [ 126, 129 ], [ 131, 131 ], [ 133, 133 ], [ 151, 153 ], [ 168, 171 ], [ 174, 177 ], [ 187, 187 ], [ 192, 192 ], [ 277, 284 ], [ 325, 325 ], [ 328, 328 ], [ 330, 330 ], [ 371, 379 ], [ 610, 612 ], [ 614, 651 ], [ 653, 655 ], [ 1437, 1452 ] ], [ [ 25, 25 ], [ 55, 55 ], [ 60, 60 ], [ 62, 62 ], [ 67, 67 ], [ 70, 70 ], [ 77, 77 ], [ 96, 96 ], [ 102, 102 ], [ 108, 108 ], [ 115, 115 ], [ 122, 122 ], [ 136, 140 ], [ 163, 167 ], [ 178, 179 ], [ 183, 183 ], [ 197, 197 ], [ 224, 224 ], [ 229, 229 ], [ 259, 260 ], [ 262, 262 ], [ 286, 286 ], [ 324, 324 ], [ 326, 327 ], [ 329, 329 ], [ 336, 336 ], [ 338, 338 ], [ 354, 355 ], [ 395, 395 ], [ 424, 424 ], [ 430, 430 ], [ 446, 446 ], [ 451, 451 ], [ 458, 458 ], [ 463, 463 ], [ 467, 467 ], [ 472, 472 ], [ 532, 532 ], [ 538, 538 ], [ 602, 602 ], [ 606, 606 ], [ 613, 613 ], [ 652, 652 ], [ 658, 658 ], [ 660, 661 ], [ 663, 663 ], [ 667, 667 ], [ 674, 674 ], [ 676, 677 ], [ 679, 679 ], [ 683, 683 ], [ 690, 690 ], [ 695, 695 ], [ 701, 701 ], [ 710, 710 ], [ 716, 716 ], [ 870, 870 ], [ 876, 876 ], [ 884, 884 ], [ 890, 890 ], [ 893, 894 ], [ 896, 896 ], [ 918, 918 ], [ 924, 924 ], [ 949, 949 ], [ 955, 955 ], [ 982, 982 ], [ 987, 987 ], [ 989, 990 ], [ 992, 992 ], [ 1014, 1015 ], [ 1023, 1023 ], [ 1059, 1060 ], [ 1064, 1064 ], [ 1089, 1090 ], [ 1096, 1096 ], [ 1115, 1115 ], [ 1126, 1126 ], [ 1203, 1203 ], [ 1208, 1208 ], [ 1214, 1214 ], [ 1234, 1234 ], [ 1239, 1239 ], [ 1275, 1275 ], [ 1356, 1356 ], [ 1360, 1360 ], [ 1365, 1365 ], [ 1382, 1382 ], [ 1394, 1395 ], [ 1397, 1397 ], [ 1418, 1418 ], [ 1428, 1429 ], [ 1431, 1431 ], [ 1433, 1434 ], [ 1436, 1436 ], [ 1454, 1458 ], [ 1464, 1466 ], [ 1468, 1468 ], [ 1470, 1470 ] ] ]
1d339e8b34f4278d8a827d1cf1b05fed7495b75d
901512f73a7ffc83849c787ab44376520a713ac1
/narb-sw/rce/rce_log.cc
eca4be9eda92b29db188a37708a7b932cf218497
[ "BSD-3-Clause" ]
permissive
penguin2005/NARB
3e33316d3f378c2f9f1a660c917bdd42cac88d34
a2fd5e01904581f91f4558f0f41ad52bbcd1ce82
refs/heads/master
2020-06-23T02:19:24.434895
2010-02-04T22:07:55
2010-02-04T22:07:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,536
cc
/* * Copyright (c) 2007 * DRAGON Project. * University of Southern California/Information Sciences Institute. * All rights reserved. * * Created by Xi Yang 2004-2007 * * 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. Neither the name of the project 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 PROJECT 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 PROJECT 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 "rce_log.hh" #include <stdarg.h> // Global variable - the only instance of Log. Log Log::logger; ostream* Log::log_file = (ostream*)NULL; u_int32_t Log::options = 0; ostream* Log::log_stdout = &cout; ostream* Log::log_stderr = &cerr; bool Log::blDebug = false; string Log::more_info = ""; const string Log::Preamble(LogOption option) { string s; time_t t; time(&t); tm* ltime = localtime(&t); switch (option) { case LOG_LOGFILE: s = "RCE"; break; case LOG_STDOUT: s = "RCE_OUTPUT"; break; case LOG_STDERR: s = "ERROR "; break; case LOG_DEBUG: s = "DEBUG "; break; default: s ="??##?? "; } static char buf[30]; strftime (buf, 30, "@[%Y/%m/%d %H:%M:%S] : ", ltime); s += buf; if (!more_info.empty()) { s += "<"; s += more_info; s += "> : "; } return s; } void Log::Init(u_int32_t options_val, const string &fileName) { options = options_val; if (fileName.empty()) return; log_file = new ofstream(fileName.c_str()); if (!log_file || log_file->bad()) { LOG_FILE << "Failed to open the log file: " << fileName << endl; LOG_FILE << "Logging to stdout instead." << endl; log_stderr = &cout; } } int Log::Logf(const char *format, ...) { static char buf[256]; buf[0] = 0; va_list ap; va_start(ap, format); int ret=vsprintf(buf, format, ap); if (log_file && (options&LOG_LOGFILE)) *log_file<< Preamble(LOG_LOGFILE) << buf << flush; if (log_stdout && (options&LOG_STDOUT)) *log_stdout<<Preamble(LOG_LOGFILE) << buf << flush; va_end(ap); return ret; }
[ "isiehpn@aacf9c1e-ac80-435b-8e83-6affbfa3956d", "xyang@aacf9c1e-ac80-435b-8e83-6affbfa3956d" ]
[ [ [ 1, 56 ], [ 58, 59 ], [ 61, 115 ] ], [ [ 57, 57 ], [ 60, 60 ] ] ]
6a1bd185b8406a97c08a09cc84d1f537ae6afce7
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/smart_pointers/weak_ptr.h
0a5d3feca401a75c4e6cd6e8d2098ea85d1154ba
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
5,481
h
// Copyright (C) 2007 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_WEAK_PTr_ #define DLIB_WEAK_PTr_ #include <algorithm> #include <memory> #include "shared_ptr.h" #include "../algs.h" #include "weak_ptr_abstract.h" namespace dlib { template < typename T > class weak_ptr { /*! CONVENTION - if (weak_node != 0) then - data == valid pointer to shared data - weak_node->ref_count == the number of weak_ptrs that reference this->data - else - data == 0 - expired() == ((weak_node == 0) || (weak_node->shared_node == 0)) - if (expired() == false) then - use_count() == weak_node->shared_node->ref_count - else - use_count() == 0 !*/ public: typedef T element_type; weak_ptr( ) : data(0), weak_node(0) { } template<typename Y> weak_ptr( const shared_ptr<Y>& r ) { data = r.data; if (r.shared_node) { if (r.shared_node->weak_node) { weak_node = r.shared_node->weak_node; weak_node->ref_count += 1; } else { weak_node = new weak_ptr_node(r.shared_node); r.shared_node->weak_node = weak_node; } } else { weak_node = 0; } } weak_ptr( const weak_ptr& r ) { data = r.data; weak_node = r.weak_node; if (weak_node) weak_node->ref_count += 1; } template<typename Y> weak_ptr( const weak_ptr<Y>& r ) { data = r.data; weak_node = r.weak_node; if (weak_node) weak_node->ref_count += 1; } ~weak_ptr( ) { if (weak_node) { // make note that this weak_ptr is being destroyed weak_node->ref_count -= 1; // if this is the last weak_ptr then we should clean up our stuff if (weak_node->ref_count == 0) { if (expired() == false) weak_node->shared_node->weak_node = 0; delete weak_node; } } } weak_ptr& operator= ( const weak_ptr& r ) { weak_ptr(r).swap(*this); return *this; } template<typename Y> weak_ptr& operator= ( const weak_ptr<Y>& r ) { weak_ptr(r).swap(*this); return *this; } template<typename Y> weak_ptr& operator=( const shared_ptr<Y>& r ) { weak_ptr(r).swap(*this); return *this; } long use_count( ) const { if (expired()) return 0; else return weak_node->shared_node->ref_count; } bool expired() const { return weak_node == 0 || weak_node->shared_node == 0; } shared_ptr<T> lock( ) const { if (expired()) return shared_ptr<T>(); else return shared_ptr<T>(*this); } void reset( ) { weak_ptr().swap(*this); } void swap( weak_ptr<T>& b ) { std::swap(data, b.data); std::swap(weak_node, b.weak_node); } template <typename Y> bool _private_less ( const weak_ptr<Y>& rhs ) const { if (expired()) { if (rhs.expired()) { return false; } else { return true; } } else { if (rhs.expired()) { return false; } else { // in this case they have both not expired so lets // compare the shared_node pointers return (weak_node->shared_node) < (rhs.weak_node->shared_node); } } } private: template <typename Y> friend class shared_ptr; template <typename Y> friend class weak_ptr; T* data; weak_ptr_node* weak_node; }; template<typename T, typename U> bool operator< ( const weak_ptr<T>& a, const weak_ptr<U>& b ) { return a._private_less(b); } template<typename T> void swap( weak_ptr<T>& a, weak_ptr<T> & b ) { a.swap(b); } } #endif // DLIB_WEAK_PTr_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 225 ] ] ]
182c6061fb8cdf89ad329681985e314d5b9f5e21
aad2ca8b47d0460ff496c8bbee9d08caaf0bae16
/alchemy/lib/libtcod/bresenham.cpp
7ae43e54e2506a6d12c5256cabc84de4f3de151d
[]
no_license
rstehwien/libtcod-alchemy
247f0d25b794066898fc7bf58fd2daab3544b632
bf20fa5ebe0793da8a60c03c8d7e13823162ad24
refs/heads/master
2021-01-21T23:28:50.765002
2009-03-16T02:57:26
2009-03-16T02:57:26
149,320
2
0
null
null
null
null
UTF-8
C++
false
false
2,049
cpp
/* * libtcod 1.4.1 * Copyright (c) 2008,2009 J.C.Wilk * 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. * * The name of J.C.Wilk may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY J.C.WILK ``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 J.C.WILK 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 "libtcod.hpp" // ********** bresenham line drawing ********** void TCODLine::init(int xFrom, int yFrom, int xTo, int yTo) { TCOD_line_init(xFrom,yFrom,xTo,yTo); } bool TCODLine::step(int *xCur, int *yCur) { return TCOD_line_step(xCur,yCur); } static TCODLineListener *listener=NULL; // C to C++ bridge extern "C" bool internalListener(int x,int y) { return listener->putPoint(x,y); } bool TCODLine::line(int xFrom, int yFrom, int xTo, int yTo, TCODLineListener *plistener) { listener=plistener; return TCOD_line(xFrom,yFrom,xTo,yTo,internalListener); }
[ [ [ 1, 51 ] ] ]
71e1f5ea9e09e61ba47fb7e73f0e7628605fcc15
1deb3507c241b7e2417ba041c9c71cb5cf7eef06
/heroin_data/create_magical_affix_data.cpp
02fd74416914244a42c06b1d91a4996e641e936c
[]
no_license
ChefKeeper/heroinglands
2a076db02bc48d578eb1d8d0eb2771079e8a9e9d
4585a4adf8c6f3b42e57928fe956cddb5a91ef1a
refs/heads/master
2016-08-13T02:20:18.085064
2009-02-13T20:30:21
2009-02-13T20:30:21
47,699,838
1
1
null
null
null
null
UTF-8
C++
false
false
3,404
cpp
#include <iostream> #include <cstdlib> #include <nil/file.hpp> #include <nil/array.hpp> #include <nil/string.hpp> #include "excel_data.hpp" #include "creation.hpp" #include "utility.hpp" void create_affixes(std::string const & affix_data, std::string const & affix_descriptor, std::string const & output_file, string_table_manager & string_manager, std::string const & output_directory) { std::stringstream magical_affixes_stream; excel_data magicaffix_data(affix_data); std::string const magicaffix_column_strings[] = {"Name", "levelreq", "mod1code", "mod1param", "mod1min", "mod1max", "mod2code", "mod2param", "mod2min", "mod2max", "mod3code", "mod3param", "mod3min", "mod3max"}; string_vector magicaffix_columns = array_to_vector(magicaffix_column_strings, nil::countof(magicaffix_column_strings)); string_vectors magicaffix_output; magicaffix_data.read_lines(magicaffix_columns, magicaffix_output); for(std::size_t i = 0; i < magicaffix_output.size(); i++) { //wow this code is terrible string_vector line = magicaffix_output[i]; std::size_t offset = 0; std::string name = string_manager.transform(line[offset++]); //if(name.empty()) // magical_affixes_stream << "\n"; std::string const & level_requirement = line[offset++]; std::string const & mod1code = line[offset++]; std::string const & mod1param = line[offset++]; std::string const & mod1min = line[offset++]; std::string const & mod1max = line[offset++]; std::string const & mod2code = line[offset++]; std::string const & mod2param = line[offset++]; std::string const & mod2min = line[offset++]; std::string const & mod2max = line[offset++]; std::string const & mod3code = line[offset++]; std::string const & mod3param = line[offset++]; std::string const & mod3min = line[offset++]; std::string const & mod3max = line[offset++]; std::string mod1 = mod_map[mod1code]; std::string mod2 = mod_map[mod2code]; std::string mod3 = mod_map[mod3code]; if( (!mod1code.empty() && mod1.empty()) || (!mod2code.empty() && mod2.empty()) || (!mod3code.empty() && mod3.empty()) ) { std::cout << "Failed to parse mod: " << name << ": " << mod1code << ", " << mod2code << ", " << mod3code << std::endl; std::cout << "Parsed: " << mod1 << ", " << mod2 << ", " << mod3 << std::endl; return; } std::string mod1string; if(!mod1code.empty()) mod1string = mod1 + "," + mod1param + "," + mod1min + "," + mod1max; std::string mod2string; if(!mod2code.empty()) mod2string = mod2 + "," + mod2param + "," + mod2min + "," + mod2max; std::string mod3string; if(!mod3code.empty()) mod3string = mod3 + "," + mod3param + "," + mod3min + "," + mod3max; magical_affixes_stream << name << "|" << level_requirement << "|" << mod1string << "|" << mod2string << "|" << mod3string << "\n"; } write_file("magical " + affix_descriptor, output_directory, output_file, magical_affixes_stream); } void create_magical_affix_data(std::string const & magicprefix_txt, std::string const & magicsuffix_txt, string_table_manager & string_manager, std::string const & output_directory) { create_affixes(magicprefix_txt, "prefixes", "magical_prefixes.txt", string_manager, output_directory); create_affixes(magicsuffix_txt, "suffixes", "magical_suffixes.txt", string_manager, output_directory); }
[ "binrapt@92c0f8f3-e753-0410-a10c-b3df2c4a8671" ]
[ [ [ 1, 82 ] ] ]
55ec1481342470f3c02109900dde0ec412921851
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/testbedservice/testbedservice_init.cpp
43c8a294e630df71f58bbcd80556a4e65631494a
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,976
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #include "apps/testbedservice/testbedservice_init.h" #ifdef ENABLE_TESTBEDSERVICE #include <iostream> #include "sys/simulation/simulation_controller.h" #include "sys/simulation/simulation_task_keeper.h" #include "sys/transm_models/transmission_model_keeper.h" #include "apps/testbedservice/testbedservice_task.h" #include "apps/testbedservice/sockets/socket_task.h" #include "apps/testbedservice/core/testbedservice_client.h" #include "apps/testbedservice/ws_handler/virtual_link_control.h" #include "apps/testbedservice/virtual_links/virtual_link_task.h" #include "apps/testbedservice/virtual_links/virtual_link_transmission_model_factory.h" #include "apps/testbedservice/processor/example_testbedservice_processor_factory.h" #include "apps/testbedservice/core/testbedservice_client.h" #include "sys/simulation/simulation_controller.h" extern "C" void init_testbedservice( shawn::SimulationController& sc ) { std::cout << "Initialising Testbedservice Module" << std::endl; sc.simulation_task_keeper_w().add( new testbedservice::TestbedServiceTask ); sc.simulation_task_keeper_w().add( new testbedservice::SocketTask ); sc.simulation_task_keeper_w().add( new testbedservice::TestbedServiceVirtualLinkTask ); sc.transmission_model_keeper_w().add( new testbedservice::VirtualLinkTransmissionModelFactory() ); testbedservice::ExampleTestbedServiceProcessorFactory::register_factory( sc ); } #endif
[ [ [ 1, 38 ] ] ]
73069df256e8da3016ceee069713a4f11d1f5a12
2d4221efb0beb3d28118d065261791d431f4518a
/OIDEๆบไปฃ็ /OLIDE/MemWatchWnd.h
846cf55fd5ac9f96babb8feef148d9d2902167ad
[]
no_license
ophyos/olanguage
3ea9304da44f54110297a5abe31b051a13330db3
38d89352e48c2e687fd9410ffc59636f2431f006
refs/heads/master
2021-01-10T05:54:10.604301
2010-03-23T11:38:51
2010-03-23T11:38:51
48,682,489
1
0
null
null
null
null
GB18030
C++
false
false
2,588
h
#pragma once #include "./Controls/TreePropSheet/ResizableDialog.h" #include "./Controls/HexEdit/HexEdit.h" #include "MemWatchHexEdit.h" #include "afxwin.h" // CMemWatchWnd ๅฏน่ฏๆก† class CMemWatchWnd : public CResizableDialog { DECLARE_DYNAMIC(CMemWatchWnd) public: CMemWatchWnd(CWnd* pParent = NULL); // ๆ ‡ๅ‡†ๆž„้€ ๅ‡ฝๆ•ฐ virtual ~CMemWatchWnd(); // ๅฏน่ฏๆก†ๆ•ฐๆฎ enum { IDD = IDD_MEM_WATCH_WND }; enum SEBMENT_TYPE { ST_NULL, ST_CODE, ST_STACK, ST_DATA, ST_ALL, }; public: CHexEdit m_editMemAddr; CHexEdit m_editMemLength; CHexEdit m_editReadCodeLength; CMemWatchHexEdit m_editHexViewCodeSegment; CMemWatchHexEdit m_editHexViewStackSegment; CMemWatchHexEdit m_editHexViewDataSegment; BOOL m_bShowDSViewOnly; CRect m_rcHexViewDataSegment; CString m_strDataAddr; CString m_strDataString; CString m_strDataUchar; CString m_strDataChar; CString m_strDataUShort; CString m_strDataShort; CString m_strDataUInt; CString m_strDataInt; CString m_strCodeDoasm; LPBYTE m_pCodeSegmentBuffer; UINT m_nCodeSegmentBufferLength; LPBYTE m_pStackSegmentBuffer; UINT m_nStackSegmentBufferLength; LPBYTE m_pDataSegmentBuffer; UINT m_nDataSegmentBufferLength; void ShowDataSegmentViewOnly(BOOL bShowDSViewOnly); BOOL GetDebugMemData(unsigned int uiMemAddr,unsigned int uiLength,LPBYTE pDataBuffer,unsigned int& uiRead); BOOL SaveDebugMemData(unsigned int uiMemAddr,LPBYTE pDataBuffer,unsigned int uiLength,BOOL bIsCodeSegment); void ClearSegmentBuffer(int nSegmentType); BOOL MallocSegmentBuffer(int nSegmentType,UINT nLength); void CodeSegmentDoasm(); void ShowEditHexViewData(CMemWatchHexEdit& memWatchHexEdit,POINT* pPoint); private: CFont m_listFont; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV ๆ”ฏๆŒ DECLARE_MESSAGE_MAP() virtual BOOL OnInitDialog(); afx_msg void OnBnClickedButtonGetData(); afx_msg LRESULT OnDebuggerClearDebugData(WPARAM wParam,LPARAM lParam); afx_msg LRESULT OnMoveCaretPos(WPARAM wParam,LPARAM lParam); afx_msg void OnEnChangeEditHexViewCodeSegment(); afx_msg void OnEnChangeEditHexViewDataSegment(); afx_msg void OnEnChangeEditHexViewStackSegment(); afx_msg void OnBnClickedBtnSaveCodeSegment(); afx_msg void OnBnClickedBtnSaveDataSegment(); afx_msg void OnBnClickedBtnSaveStackSegment(); afx_msg void OnBnClickedCheckShowDsViewOnly(); afx_msg void OnBnClickedBtnCodeDoasm(); afx_msg LRESULT OnDebuggerShowCPUData(WPARAM wParam,LPARAM lParam); };
[ [ [ 1, 91 ] ] ]
49c34c290b484f8f9a6ebf4d5c1472bea603a058
a2904986c09bd07e8c89359632e849534970c1be
/topcoder/CuttingPoles.cpp
07c51208be2dd0b48fc8754347e8018edc2bb9f3
[]
no_license
naturalself/topcoder_srms
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
refs/heads/master
2021-01-22T04:36:40.592620
2010-11-29T17:30:40
2010-11-29T17:30:40
444,669
1
0
null
null
null
null
UTF-8
C++
false
false
2,825
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "CuttingPoles.cpp" #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> using namespace std; #define debug(p) cout << #p << "=" << p << endl; #define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i) #define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i) #define all(a) a.begin(), a.end() #define pb push_back class CuttingPoles { public: int countCuts(vector <int> poles) { vector<int> pole=poles; int n = (int)poles.size(); int ret=0; sort(pole.rbegin(),pole.rend()); int avg= accumulate(all(pole),0)/n; while(!Isend(pole)){ sort(pole.rbegin(),pole.rend()); pole[n-1] += pole[0]-avg; pole[0]=avg; ret++; } return ret; } private: bool Isend(vector<int> p){ for(int i=0;i<(int)p.size()-1;i++){ if(p[i]!=p[i+1]){ return false; } } return true; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {1,3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(0, Arg1, countCuts(Arg0)); } void test_case_1() { int Arr0[] = {10,10,10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; verify_case(1, Arg1, countCuts(Arg0)); } void test_case_2() { int Arr0[] = {1,1,3,3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(2, Arg1, countCuts(Arg0)); } void test_case_3() { int Arr0[] = {10,10,10,10,10,10,10,18}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 7; verify_case(3, Arg1, countCuts(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CuttingPoles ___test; ___test.run_test(-1); } // END CUT HERE
[ "shin@CF-7AUJ41TT52JO.(none)" ]
[ [ [ 1, 84 ] ] ]
5b5419f45f8e145063a46dbdf178b539ab38f6e2
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/testcondinit/src/tcondinit.cpp
867d0ebff4198e290ce65a7cc8a87fa7de03ee31
[]
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,838
cpp
/* * Copyright (c) 2009 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: * */ #include "tcondinit.h" #include <unistd.h> #include <errno.h> #include <stdio.h> #include <e32std.h> #include <stdlib.h> #include <string.h> CTestCondinit::~CTestCondinit() { } CTestCondinit::CTestCondinit(const TDesC& aStepName) { // MANDATORY Call to base class method to set up the human readable name for logging. SetTestStepName(aStepName); } TVerdict CTestCondinit::doTestStepPreambleL() { __UHEAP_MARK; SetTestStepResult(EPass); return TestStepResult(); } TVerdict CTestCondinit::doTestStepPostambleL() { __UHEAP_MARKEND; return TestStepResult(); } TVerdict CTestCondinit::doTestStepL() { int err; if(TestStepName() == KTestCond401) { INFO_PRINTF1(_L("TestCond401():")); err = TestCond401(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestCond403) { INFO_PRINTF1(_L("TestCond403():")); err = TestCond403(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestCond404) { INFO_PRINTF1(_L("TestCond404():")); err = TestCond404(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestCond668) { INFO_PRINTF1(_L("TestCond668():")); err = TestCond668(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestCond670) { INFO_PRINTF1(_L("TestCond670():")); err = TestCond670(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestCond671) { INFO_PRINTF1(_L("TestCond671():")); err = TestCond671(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestCond672) { INFO_PRINTF1(_L("TestCond672():")); err = TestCond672(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestCond673) { INFO_PRINTF1(_L("TestCond673():")); err = TestCond673(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } return TestStepResult(); }
[ "none@none" ]
[ [ [ 1, 111 ] ] ]
8b5312861c1525c15e6e54b95237ffdb997191b2
0c5fd443401312fafae18ea6a9d17bac9ee61474
/code/engine/AudioBlaster/Transport.h
60ee65836d06edd86c067f866015f5b5e132054c
[]
no_license
nurF/Brute-Force-Game-Engine
fcfebc997d6ab487508a5706b849e9d7bc66792d
b930472429ec6d6f691230e36076cd2c868d853d
refs/heads/master
2021-01-18T09:29:44.038036
2011-12-02T17:31:59
2011-12-02T17:31:59
2,877,061
1
0
null
null
null
null
UTF-8
C++
false
false
2,748
h
/* ___ _________ ____ __ / _ )/ __/ ___/____/ __/___ ___ _/_/___ ___ / _ / _// (_ //___/ _/ / _ | _ `/ // _ | -_) /____/_/ \___/ /___//_//_|_, /_//_//_|__/ /___/ This file is part of the Brute-Force Game Engine, BFG-Engine For the latest info, see http://www.brute-force-games.com Copyright (c) 2011 Brute-Force Games GbR The BFG-Engine is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The BFG-Engine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the BFG-Engine. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AUDIO_BLASTER_TRANSPORT_H #define AUDIO_BLASTER_TRANSPORT_H #include <Core/Types.h> #include <Core/v3.h> #include <Core/Utils.h> #include <AudioBlaster/Enums.hh> namespace BFG { struct AOLocation { AOLocation(const v3& position = v3(0,0,0), const v3& orientation = v3(0,0,0), const v3& velocity = v3(0,0,0)): mPosition(position), mOrientation(orientation), mVelocity(velocity) {} v3 mPosition; v3 mOrientation; v3 mVelocity; }; struct AOPresetData { AOPresetData(float gain, float pitch, float coneInnerAngle, float coneOuterAngle, float coneOuterGain, float referenceDistance, float rolloffFactor): mGain(gain), mPitch(pitch), mConeInnerAngle(coneInnerAngle), mConeOuterAngle(coneOuterAngle), mConeOuterGain(coneOuterGain), mReferenceDistance(referenceDistance), mRolloffFactor(rolloffFactor) {} float mGain; float mPitch; float mConeInnerAngle; float mConeOuterAngle; float mConeOuterGain; float mReferenceDistance; float mRolloffFactor; }; struct AOCreation { AOCreation(GameHandle handle, const std::string& name, ID::AudioObjectType aot = ID::AOT_SINGLE_SERVING, ID::AudioPreset aop = ID::AOP_DEFAULT_SOUND, const AOLocation& location = AOLocation()): mHandle(handle), mName(name), mAudioObjectType(aot), mAudioPreset(aop), mLocation(location) {} GameHandle mHandle; std::string mName; ID::AudioObjectType mAudioObjectType; ID::AudioPreset mAudioPreset; AOLocation mLocation; }; } // namespace BFG #endif
[ [ [ 1, 103 ] ] ]
b50487c7472f4f6cade4dca13548be4497ee8580
483d66ba0bc9ff989695d978e99c900d2c4c9418
/Client/LoginDlg.cpp
95e6ef274416585ff0ffc90d23e52414ff839579
[]
no_license
uwitec/storesystem
3aeeef77837bed312e6cac5bb9b18e1e96a3156d
b703e4747fa035e221eb8f2d7bf586dae83f5e6f
refs/heads/master
2021-03-12T20:17:54.942667
2011-06-06T17:46:15
2011-06-06T17:46:15
40,976,352
0
0
null
null
null
null
UTF-8
C++
false
false
162
cpp
#include "StdAfx.h" #include "LoginDlg.h" LoginDlg::LoginDlg(QWidget *parent) : QWidget(parent) { ui.setupUi(this); } LoginDlg::~LoginDlg() { }
[ [ [ 1, 13 ] ] ]
09a73f9973a5a9594526ef19dc8868de3ee0ab49
115cdd77595f80aa6870893657f26f6b4e7cdd2b
/src/include/Model.hpp
345d07d00732a777b0ddbfebaff10a8f278ae089
[]
no_license
douglyuckling/peek
0bc036906bab49fec63944e4c23e3b0c6935d820
9d7c3022366290a43830be5f19a47bd406038f3c
refs/heads/master
2021-01-23T07:21:11.076300
2010-07-09T04:48:33
2010-07-09T04:48:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,291
hpp
/** * @file Model.hpp */ #pragma once #include "Geometry.hpp" #include "Object.hpp" #include "SmoothMesh.hpp" #include "handle_traits.hpp" #include "list_traits.hpp" namespace peek { class Model : public Object { public: /** Constructor */ Model(); /** Draws the model */ void draw() const; /** Draws the model for picking */ void pick() const; /** Draws the vertices */ void drawVerts() const; /** Increases the size of the (visible) normals */ void increaseNormalScale() { this->normalScale *= 2.0; } /** Decreases the size of the (visible) normals */ void decreaseNormalScale() { this->normalScale /= 2.0; } /** Adds a mesh to the model */ void addMesh(SmoothMesh::handle mesh); /** Toggles smooth shading on and off */ void toggleSmoothShading() { this->smoothShading = !this->smoothShading; } /** Toggles visibility of solid geometry */ void toggleShowSolidGeometry() { this->showSolid = !this->showSolid; } /** Toggles visibility of the wireframe */ void toggleShowWireframe() { this->showWireframe = !this->showWireframe; } /** Toggles visibility of face/vector normals */ void toggleShowNormals() { this->showNormals = !this->showNormals; } /** Get the dimensions of the axis-aligned bouding box for the polygon mesh */ inline Vector3d getDimensions() { return this->boundingBoxHigh - this->boundingBoxLow; } typedef handle_traits<Model>::handle_type handle; typedef list_traits<Model::handle>::list_type list; protected: SmoothMesh::list meshes; /** Whether or not smooth shading is enabled */ bool smoothShading; /** Whether or not solid geometry is visible */ bool showSolid; /** Whether or not the wireframe is visible */ bool showWireframe; /** Whether or not normals are visible */ bool showNormals; /** The scale at which to draw the normals */ double normalScale; /** The low corner of the axis-aligned bounding box which contains the mesh */ Point3d boundingBoxLow; /** The high corner of the axis-aligned bounding box which contains the mesh */ Point3d boundingBoxHigh; /** (Re)calculates the axis-aligned bounding box for the mesh. */ void findBoundingBox(); }; }
[ "douglyuckling@483a7388-aa76-4cae-9b69-882d6fd7d2f9" ]
[ [ [ 1, 87 ] ] ]
188a0fad82a254e880d64a461ff6215297c3b36b
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/pgm.h
f08b90d441a712cb4bda2e9f8f8aec04c6c7290b
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,326
h
class pgm_state : public driver_device { public: pgm_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ // UINT16 * m_mainram; // currently this is also used by nvram handler UINT16 * m_bg_videoram; UINT16 * m_tx_videoram; UINT16 * m_videoregs; UINT16 * m_rowscrollram; UINT16 * m_videoram; UINT8 * m_z80_mainram; UINT32 * m_arm7_shareram; UINT32 * m_svg_shareram[2]; //for 5585G MACHINE UINT16 * m_sharedprotram; // killbld & olds UINT8 * m_sprite_a_region; size_t m_sprite_a_region_size; UINT16 * m_spritebufferram; // buffered spriteram // UINT16 * m_paletteram; // currently this uses generic palette handling /* video-related */ tilemap_t *m_bg_tilemap; tilemap_t *m_tx_tilemap; UINT16 *m_sprite_temp_render; bitmap_t *m_tmppgmbitmap; /* misc */ // kov2 UINT32 m_kov2_latchdata_68k_w; UINT32 m_kov2_latchdata_arm_w; // kovsh UINT16 m_kovsh_highlatch_arm_w; UINT16 m_kovsh_lowlatch_arm_w; UINT16 m_kovsh_highlatch_68k_w; UINT16 m_kovsh_lowlatch_68k_w; UINT32 m_kovsh_counter; // svg int m_svg_ram_sel; // killbld & olds int m_kb_cmd; int m_kb_reg; int m_kb_ptr; int m_kb_region_sequence_position; UINT32 m_kb_regs[0x10]; UINT16 m_olds_bs; UINT16 m_olds_cmd3; // pstars UINT16 m_pstars_key; UINT16 m_pstars_int[2]; UINT32 m_pstars_regs[16]; UINT32 m_pstars_val; UINT16 m_pstar_e7; UINT16 m_pstar_b1; UINT16 m_pstar_ce; UINT16 m_pstar_ram[3]; // ASIC 3 (oriental legends protection) UINT8 m_asic3_reg; UINT8 m_asic3_latch[3]; UINT8 m_asic3_x; UINT8 m_asic3_y; UINT8 m_asic3_z; UINT8 m_asic3_h1; UINT8 m_asic3_h2; UINT16 m_asic3_hold; // ASIC28 UINT16 m_asic28_key; UINT16 m_asic28_regs[10]; UINT16 m_asic_params[256]; UINT16 m_asic28_rcnt; UINT32 m_eoregs[16]; /* calendar */ UINT8 m_cal_val; UINT8 m_cal_mask; UINT8 m_cal_com; UINT8 m_cal_cnt; system_time m_systime; /* devices */ cpu_device *m_soundcpu; cpu_device *m_prot; device_t *m_ics; }; extern UINT16 *pgm_mainram; // used by nvram handler, we cannot move it to driver data struct /*----------- defined in machine/pgmcrypt.c -----------*/ void pgm_kov_decrypt(running_machine &machine); void pgm_kovsh_decrypt(running_machine &machine); void pgm_kov2_decrypt(running_machine &machine); void pgm_kov2p_decrypt(running_machine &machine); void pgm_mm_decrypt(running_machine &machine); void pgm_dw2_decrypt(running_machine &machine); void pgm_photoy2k_decrypt(running_machine &machine); void pgm_py2k2_decrypt(running_machine &machine); void pgm_dw3_decrypt(running_machine &machine); void pgm_killbld_decrypt(running_machine &machine); void pgm_pstar_decrypt(running_machine &machine); void pgm_puzzli2_decrypt(running_machine &machine); void pgm_theglad_decrypt(running_machine &machine); void pgm_ddp2_decrypt(running_machine &machine); void pgm_dfront_decrypt(running_machine &machine); void pgm_oldsplus_decrypt(running_machine &machine); void pgm_kovshp_decrypt(running_machine &machine); void pgm_killbldp_decrypt(running_machine &machine); void pgm_svg_decrypt(running_machine &machine); void pgm_ket_decrypt(running_machine &machine); void pgm_espgal_decrypt(running_machine &machine); /*----------- defined in machine/pgmprot.c -----------*/ READ16_HANDLER( pstars_protram_r ); READ16_HANDLER( pstars_r ); WRITE16_HANDLER( pstars_w ); READ16_HANDLER( pgm_asic3_r ); WRITE16_HANDLER( pgm_asic3_w ); WRITE16_HANDLER( pgm_asic3_reg_w ); READ16_HANDLER( sango_protram_r ); READ16_HANDLER( asic28_r ); WRITE16_HANDLER( asic28_w ); READ16_HANDLER( dw2_d80000_r ); /*----------- defined in video/pgm.c -----------*/ WRITE16_HANDLER( pgm_tx_videoram_w ); WRITE16_HANDLER( pgm_bg_videoram_w ); VIDEO_START( pgm ); SCREEN_EOF( pgm ); SCREEN_UPDATE( pgm );
[ "Mike@localhost" ]
[ [ [ 1, 138 ] ] ]
58fefa969350fe012e7dcc63f233e4d448aee08f
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Common/Base/System/Stopwatch/hkSystemClock.h
952b3f80a675c54e1d05e40475221cb3a657e96b
[]
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
1,847
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 HKBASE_HKSYSTEMCLOCK_H #define HKBASE_HKSYSTEMCLOCK_H /// An interface to hardware timers. #if !defined(HK_PLATFORM_PS3SPU) class hkSystemClock : public hkReferencedObject, public hkSingleton<hkSystemClock> { public: /// Get the current tick counter. virtual hkUint64 getTickCounter() = 0; /// Return how many ticks elapse per second. virtual hkUint64 getTicksPerSecond() = 0; }; #else class hkSystemClock { public: /// Get the current tick counter. static hkUint64 getTickCounter(); /// Return how many ticks elapse per second. static hkUint64 getTicksPerSecond(); }; #endif #endif //HKBASE_HKSYSTEMCLOCK_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 ] ] ]
f1195b90f5b964a77db893d747f2f9e430102219
cd0987589d3815de1dea8529a7705caac479e7e9
/includes/webkitsupport/platform/BlackBerryPlatformGraphics.h
faf629a6056c0412f5ffd8db0e96bcf54fee0fb4
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,727
h
/* * Copyright (C) Research In Motion, Limited 2009-2010. All rights reserved. */ #ifndef BlackBerryPlatformGraphics_h #define BlackBerryPlatformGraphics_h #include "BlackBerryPlatformMemory.h" #include "BlackBerryPlatformPrimitives.h" #if defined(USE_SKIA) #include <skia/ext/platform_canvas.h> #else #include <egl.h> #endif namespace BlackBerry { namespace Platform { namespace Graphics { enum BufferType { TileBuffer, TemporaryBuffer, TemporaryBufferWithAlpha, }; struct Buffer; #if defined(USE_SKIA) typedef skia::PlatformCanvas Drawable; #else class Drawable { public: Drawable(EGLSurface surface, EGLint surfaceType, bool isFlipTransformationRequired = false) : m_surface(surface) , m_surfaceType(surfaceType) , m_isFlipTransformationRequired(isFlipTransformationRequired) { } EGLSurface surface() const { return m_surface; } EGLint surfaceType() const { return m_surfaceType; } bool isFlipTransformationRequired() const { return m_isFlipTransformationRequired; } private: EGLSurface m_surface; EGLint m_surfaceType; bool m_isFlipTransformationRequired; }; #endif void initialize(); void shutdown(); #if !defined(USE_SKIA) EGLDisplay& display(); Drawable* drawingSurface(); #endif Buffer* createBuffer(const BlackBerry::Platform::IntSize&, BufferType); void destroyBuffer(Buffer*); #if defined(USE_SKIA) Drawable* lockBufferDrawable(Buffer*); void releaseBufferDrawable(Buffer*); #else // Returns 0 for EGL implementation, you have to use temporary drawing surface inline Drawable* lockBufferDrawable(Buffer*) { return 0; } inline void releaseBufferDrawable(Buffer*) {} #endif void clearBufferWhite(Buffer*); void clearBufferTransparent(Buffer*); void clearBuffer(Buffer*, const BlackBerry::Platform::IntRect&, unsigned char red, unsigned char green, unsigned char blue); #if !defined(USE_SKIA) void blitToBuffer(Buffer* dst, const BlackBerry::Platform::IntPoint& dstPoint, Drawable* drawable, const BlackBerry::Platform::IntRect& srcRect); #endif void blitToBuffer(Buffer* dst, const BlackBerry::Platform::IntPoint& dstPoint, const Buffer* src, const BlackBerry::Platform::IntRect& srcRect); void stretchBlitToBuffer(Buffer* dst, const BlackBerry::Platform::IntRect& dstRect, const Buffer* src, const BlackBerry::Platform::IntRect& srcRect); void blendOntoBuffer(Buffer* dst, const BlackBerry::Platform::IntPoint& dstPoint, const Buffer* src, const BlackBerry::Platform::IntRect& srcRect, const unsigned char globalAlpha); void flush(); } // namespace Graphics } // namespace Platform } // namespace Olympia #endif // BlackBerryPlatformGraphics_h
[ [ [ 1, 85 ] ] ]
42ee1e1637e7bf836560fecb66d757c106cbc2d7
1ab9457b2e2183ec8275a9713d8c7cbb48c835d1
/Source/Common/BWAPI/include/BWTA.h
2e0b7207b810b9d3a8512781d983c62ba596ae32
[]
no_license
ianfinley89/emapf-starcraft-ai
0f6ca09560092e798873b6b5dda01d463fa71518
b1bf992dff681a7feb618b7a781bacc61d2d477d
refs/heads/master
2020-05-19T20:52:17.080667
2011-03-04T11:59:46
2011-03-04T11:59:46
32,126,953
1
0
null
null
null
null
UTF-8
C++
false
false
2,141
h
#pragma once #include <BWAPI.h> #include <BWTA/Chokepoint.h> #include <BWTA/Polygon.h> #include <BWTA/Region.h> #include <BWTA/BaseLocation.h> #include <BWTA/RectangleArray.h> namespace BWTA { void readMap(); void analyze(); const std::set<Region*>& getRegions(); const std::set<Chokepoint*>& getChokepoints(); const std::set<BaseLocation*>& getBaseLocations(); const std::set<BaseLocation*>& getStartLocations(); const std::set<Polygon*>& getUnwalkablePolygons(); BaseLocation* getStartLocation(BWAPI::Player* player); Region* getRegion(int x, int y); Region* getRegion(BWAPI::TilePosition tileposition); Chokepoint* getNearestChokepoint(int x, int y); Chokepoint* getNearestChokepoint(BWAPI::TilePosition tileposition); Chokepoint* getNearestChokepoint(BWAPI::Position position); BaseLocation* getNearestBaseLocation(int x, int y); BaseLocation* getNearestBaseLocation(BWAPI::TilePosition tileposition); BaseLocation* getNearestBaseLocation(BWAPI::Position position); Polygon* getNearestUnwalkablePolygon(int x, int y); Polygon* getNearestUnwalkablePolygon(BWAPI::TilePosition tileposition); BWAPI::Position getNearestUnwalkablePosition(BWAPI::Position position); bool isConnected(int x1, int y1, int x2, int y2); bool isConnected(BWAPI::TilePosition a, BWAPI::TilePosition b); double getGroundDistance(BWAPI::TilePosition start, BWAPI::TilePosition end); std::pair<BWAPI::TilePosition, double> getNearestTilePosition(BWAPI::TilePosition start, const std::set<BWAPI::TilePosition>& targets); std::map<BWAPI::TilePosition, double> getGroundDistances(BWAPI::TilePosition start, const std::set<BWAPI::TilePosition>& targets); void getGroundDistanceMap(BWAPI::TilePosition start, RectangleArray<double>& distanceMap); void getGroundWalkDistanceMap(int walkx, int walky, RectangleArray<double>& distanceMap); std::vector<BWAPI::TilePosition> getShortestPath(BWAPI::TilePosition start, BWAPI::TilePosition end); std::vector<BWAPI::TilePosition> getShortestPath(BWAPI::TilePosition start, const std::set<BWAPI::TilePosition>& targets); }
[ "[email protected]@26a4d94b-85da-9150-e52c-6e401ef01510" ]
[ [ [ 1, 46 ] ] ]
f0e3f562975c19067646ffc0b8e90d753db67585
028d6009f3beceba80316daa84b628496a210f8d
/connectivity/com.nokia.tcf/native/TCFNative/TCFCommVirtualSerial/TCFCommVirtualSerial.cpp
92a031486836f01fa9498733c261d18a3705bb0d
[]
no_license
JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp
fa50cafa69d3e317abf0db0f4e3e557150fd88b3
4420f338bc4e522c563f8899d81201857236a66a
refs/heads/master
2020-12-30T16:45:28.474973
2010-10-20T16:19:31
2010-10-20T16:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,771
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // TCFCommVirtualSerial.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" #include <sys/stat.h> #include "TCFCommVirtualSerial.h" #include "VirtualSerialComm.h" static const char* pCommType="virtualserial"; static CBaseCom* pCommClass=NULL; #ifdef _DEBUG BOOL gDoLogging = FALSE; #endif BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { #ifdef _DEBUG struct _stat buf; char* dirname = "c:\\tcf"; int result = _stat(dirname, &buf); if (result == 0) // exists { gDoLogging = TRUE; } else { gDoLogging = FALSE; } #endif } break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } // register this connection type TCFCOMMVIRTUALSERIAL_API const char* RegisterComm() { return pCommType; } // create this connection type TCFCOMMVIRTUALSERIAL_API CBaseCom* CreateComm(ConnectData* connectSettings, DWORD connectionId, CBaseProtocol* protocol) { pCommClass = new VirtualSerialComm(connectSettings, connectionId, protocol); return pCommClass; }
[ "none@none" ]
[ [ [ 1, 75 ] ] ]
9250fa21a3233400f6117dd195b552bd8518950a
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/util/IllegalArgumentException.hpp
e96a9fdb8cd04736ce4cd36aa7240f26f8449171
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
1,032
hpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: IllegalArgumentException.hpp 176026 2004-09-08 13:57:07Z peiyongz $ */ #if !defined(ILLEGALARGUMENTEXCEPTION_HPP) #define ILLEGALARGUMENTEXCEPTION_HPP #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/XMLException.hpp> XERCES_CPP_NAMESPACE_BEGIN MakeXMLException(IllegalArgumentException, XMLUTIL_EXPORT) XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 34 ] ] ]
6b98cb7e53d4c4f09358e3cfd0bbdb8feda0284e
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/Tactical/Handle Items.h
f6d6f25f3f1db8cdcd00ae152af98a877bae78de
[]
no_license
infernuslord/ja2
d5ac783931044e9b9311fc61629eb671f376d064
91f88d470e48e60ebfdb584c23cc9814f620ccee
refs/heads/master
2021-01-02T23:07:58.941216
2011-10-18T09:22:53
2011-10-18T09:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,029
h
#ifndef __HANDLE_ITEMS_H #define __HANDLE_ITEMS_H #include "World Items.h" #include "structure.h" #include "Soldier Control.h" #define ITEM_HANDLE_OK 1 #define ITEM_HANDLE_RELOADING -1 #define ITEM_HANDLE_UNCONSCIOUS -2 #define ITEM_HANDLE_NOAPS -3 #define ITEM_HANDLE_NOAMMO -4 #define ITEM_HANDLE_CANNOT_GETTO_LOCATION -5 #define ITEM_HANDLE_BROKEN -6 #define ITEM_HANDLE_NOROOM -7 #define ITEM_HANDLE_REFUSAL -8 // Define for code to try and pickup all items.... #define ITEM_PICKUP_ACTION_ALL 32000 #define ITEM_PICKUP_SELECTION 31000 #define ITEM_IGNORE_Z_LEVEL -1 #define ITEMLIST_INIT_HANDLE 1 #define ITEMLIST_DISPLAY 2 #define ITEMLIST_HANDLE 3 #define ITEMLIST_END_HANDLE 4 #define ITEMLIST_HANDLE_SELECTION 5 // visibility defines #define ANY_VISIBILITY_VALUE -10 #define HIDDEN_ITEM -4 #define BURIED -3 #define HIDDEN_IN_OBJECT -2 #define INVISIBLE -1 #define VISIBLE 1 #define ITEM_LOCATOR_DELAY 0x01 #define ITEM_LOCATOR_LOCKED 0x02 // MACRO FOR DEFINING OF ITEM IS VISIBLE #define ITEMPOOL_VISIBLE( pItemPool ) ( ( pItemPool->bVisible >= 1 ) || (gTacticalStatus.uiFlags&SHOW_ALL_ITEMS) ) typedef void ( *ITEM_POOL_LOCATOR_HOOK )( void ); class WORLDITEM; struct LEVELNODE; typedef struct TAG_ITEM_POOL { struct TAG_ITEM_POOL *pNext; struct TAG_ITEM_POOL *pPrev; INT32 iItemIndex; INT8 bVisible; INT8 bFlashColor; UINT32 uiTimerID; INT32 sGridNo; UINT8 ubLevel; UINT16 usFlags; INT8 bRenderZHeightAboveLevel; LEVELNODE *pLevelNode; } ITEM_POOL; typedef struct { ITEM_POOL *pItemPool; // Additional info for locators INT8 bRadioFrame; UINT32 uiLastFrameUpdate; ITEM_POOL_LOCATOR_HOOK Callback; BOOLEAN fAllocated; UINT8 ubFlags; } ITEM_POOL_LOCATOR; class SOLDIERTYPE; INT32 HandleItem( SOLDIERTYPE *pSoldier, INT32 sGridNo, INT8 bLevel, UINT16 usHandItem, BOOLEAN fFromUI ); void SoldierPickupItem( SOLDIERTYPE *pSoldier, INT32 iItemIndex, INT32 sGridNo, INT8 bZLevel ); void HandleSoldierPickupItem( SOLDIERTYPE *pSoldier, INT32 iItemIndex, INT32 sGridNo, INT8 bZLevel ); void HandleFlashingItems( ); BOOLEAN SoldierDropItem( SOLDIERTYPE * pSoldier, OBJECTTYPE * pObj ); void HandleSoldierThrowItem( SOLDIERTYPE *pSoldier, INT32 sGridNo ); BOOLEAN VerifyGiveItem( SOLDIERTYPE *pSoldier, SOLDIERTYPE **ppTargetSoldier ); void SoldierGiveItemFromAnimation( SOLDIERTYPE *pSoldier ); void SoldierGiveItem( SOLDIERTYPE *pSoldier, SOLDIERTYPE *pTargetSoldier, OBJECTTYPE *pObject, INT8 bInvPos ); void NotifySoldiersToLookforItems( ); void AllSoldiersLookforItems( BOOLEAN RevealRoofsAndItems ); void SoldierGetItemFromWorld( SOLDIERTYPE *pSoldier, INT32 iItemIndex, INT32 sGridNo, INT8 bZLevel, BOOLEAN *pfSelectionList ); OBJECTTYPE* AddItemToPool( INT32 sGridNo, OBJECTTYPE *pObject, INT8 bVisible, UINT8 ubLevel, UINT16 usFlags, INT8 bRenderZHeightAboveLevel, INT8 soldierID = -1 ); OBJECTTYPE* AddItemToPoolAndGetIndex( INT32 sGridNo, OBJECTTYPE *pObject, INT8 bVisible, UINT8 ubLevel, UINT16 usFlags, INT8 bRenderZHeightAboveLevel, INT8 soldierID, INT32 * piItemIndex ); OBJECTTYPE* InternalAddItemToPool( INT32 *psGridNo, OBJECTTYPE *pObject, INT8 bVisible, UINT8 ubLevel, UINT16 usFlags, INT8 bRenderZHeightAboveLevel, INT8 soldierID, INT32 * piItemIndex ); INT32 AdjustGridNoForItemPlacement( SOLDIERTYPE *pSoldier, INT32 sGridNo ); BOOLEAN GetItemPool( INT32 usMapPos, ITEM_POOL **ppItemPool, UINT8 ubLevel ); BOOLEAN GetItemPoolFromGround( INT32 sMapPos, ITEM_POOL **ppItemPool ); BOOLEAN DrawItemPoolList( ITEM_POOL *pItemPool, INT32 sGridNo, UINT8 bCommand, INT8 bZLevel, INT16 sXPos, INT16 sYPos ); BOOLEAN RemoveItemFromPool( INT32 sGridNo, INT32 iItemIndex, UINT8 ubLevel ); BOOLEAN ItemExistsAtLocation( INT32 sGridNo, INT32 iItemIndex, UINT8 ubLevel ); BOOLEAN MoveItemPools( INT32 sStartPos, INT32 sEndPos, INT8 bStartLevel, INT8 bEndLevel ); void SetItemPoolLocator( ITEM_POOL *pItemPool ); void SetItemPoolLocatorWithCallback( ITEM_POOL *pItemPool, ITEM_POOL_LOCATOR_HOOK Callback ); BOOLEAN SetItemPoolVisibilityOn( ITEM_POOL *pItemPool, INT8 bAllGreaterThan, BOOLEAN fSetLocator ); void AdjustItemPoolVisibility( ITEM_POOL *pItemPool ); void SetItemPoolVisibilityHiddenInObject( ITEM_POOL *pItemPool ); void SetItemPoolVisibilityHidden( ITEM_POOL *pItemPool ); INT32 GetItemOfClassTypeInPool( INT32 sGridNo, UINT32 uiItemClass, UINT8 ubLevel ); void RemoveItemPool( INT32 sGridNo, UINT8 ubLevel ); void RenderTopmostFlashingItems( ); void RemoveAllUnburiedItems( INT32 sGridNo, UINT8 ubLevel ); BOOLEAN DoesItemPoolContainAnyHiddenItems( ITEM_POOL *pItemPool ); BOOLEAN DoesItemPoolContainAllHiddenItems( ITEM_POOL *pItemPool ); void HandleSoldierDropBomb( SOLDIERTYPE *pSoldier, INT32 sGridNo ); void HandleSoldierUseRemote( SOLDIERTYPE *pSoldier, INT32 sGridNo ); BOOLEAN ItemPoolOKForDisplay( ITEM_POOL *pItemPool, INT8 bZLevel ); INT16 GetNumOkForDisplayItemsInPool( ITEM_POOL *pItemPool, INT8 bZLevel ); void SoldierHandleDropItem( SOLDIERTYPE *pSoldier ); BOOLEAN LookForHiddenItems( INT32 sGridNo, INT8 ubLevel, BOOLEAN fSetLocator, INT8 bZLevel ); INT8 GetZLevelOfItemPoolGivenStructure( INT32 sGridNo, UINT8 ubLevel, STRUCTURE *pStructure ); INT8 GetLargestZLevelOfItemPool( ITEM_POOL *pItemPool ); BOOLEAN NearbyGroundSeemsWrong( SOLDIERTYPE * pSoldier, INT32 sGridNo, BOOLEAN fCheckAroundGridNo, INT32 * psProblemGridNo ); void MineSpottedDialogueCallBack( void ); extern INT32 gsBoobyTrapGridNo; extern SOLDIERTYPE * gpBoobyTrapSoldier; void AddBlueFlag( INT32 sGridNo, INT8 bLevel ); void RemoveBlueFlag( INT32 sGridNo, INT8 bLevel ); // check if item is booby trapped BOOLEAN ContinuePastBoobyTrapInMapScreen( OBJECTTYPE *pObject, SOLDIERTYPE *pSoldier ); // set off the booby trap in mapscreen void SetOffBoobyTrapInMapScreen( SOLDIERTYPE *pSoldier, OBJECTTYPE *pObject ); void RefreshItemPools( WORLDITEM* pItemList, INT32 iNumberOfItems ); BOOLEAN HandItemWorks( SOLDIERTYPE *pSoldier, INT8 bSlot ); BOOLEAN ItemTypeExistsAtLocation( INT32 sGridNo, UINT16 usItem, UINT8 ubLevel, INT32 * piItemIndex ); INT32 FindNearestAvailableGridNoForItem( INT32 sSweetGridNo, INT8 ubRadius ); BOOLEAN CanPlayerUseRocketRifle( SOLDIERTYPE *pSoldier, BOOLEAN fDisplay ); void MakeNPCGrumpyForMinorOffense( SOLDIERTYPE * pSoldier, SOLDIERTYPE *pOffendingSoldier ); void SoldierStealItemFromSoldier( SOLDIERTYPE *pSoldier, SOLDIERTYPE *pOpponent,ITEM_POOL *pItemPool, INT32 iItemIndex, INT32 sGridNo, INT8 bZLevel, BOOLEAN *pfSelectionList ); UINT8 StealItems(SOLDIERTYPE* pSoldier,SOLDIERTYPE* pOpponent, UINT8* ubIndexRet); BOOLEAN MarblesExistAtLocation( INT32 sGridNo, UINT8 ubLevel, INT32 * piItemIndex ); extern ITEM_POOL *gpItemPool;//dnl ch26 210909 #endif
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 180 ] ] ]
74824ab4457a63bd0db8168b67eebe18b0965836
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/proto/test/matches.cpp
c73e660fe071d64f85052b496d2c40da2776cd3e
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,814
cpp
/////////////////////////////////////////////////////////////////////////////// // matches.hpp // // Copyright 2008 Eric Niebler. 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 <string> #include <iostream> #include <boost/config.hpp> #include <boost/detail/workaround.hpp> #include <boost/mpl/assert.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/proto/core.hpp> #include <boost/proto/transform/arg.hpp> #include <boost/test/unit_test.hpp> using namespace boost; using namespace proto; template<typename Grammar, typename Expr> void assert_matches(Expr const &expr) { BOOST_MPL_ASSERT((matches<Expr, Grammar>)); } template<typename Grammar, typename Expr> void assert_not_matches(Expr const &expr) { BOOST_MPL_ASSERT_NOT((matches<Expr, Grammar>)); } struct int_convertible { int_convertible() {} operator int() const { return 0; } }; struct Input : or_< shift_right< terminal< std::istream & >, _ > , shift_right< Input, _ > > {}; struct Output : or_< shift_left< terminal< std::ostream & >, _ > , shift_left< Output, _ > > {}; terminal< std::istream & >::type const cin_ = {std::cin}; terminal< std::ostream & >::type const cout_ = {std::cout}; struct Anything : or_< terminal<_> , nary_expr<_, vararg<Anything> > > {}; void a_function() {} struct MyCases { template<typename Tag> struct case_ : proto::not_<proto::_> {}; }; template<> struct MyCases::case_<proto::tag::shift_right> : proto::_ {}; template<> struct MyCases::case_<proto::tag::plus> : proto::_ {}; enum binary_representation_enum { magnitude , two_complement }; typedef mpl::integral_c<binary_representation_enum, magnitude> magnitude_c; typedef mpl::integral_c<binary_representation_enum, two_complement> two_complement_c; template<typename Type, typename Representation> struct number {}; struct NumberGrammar : proto::or_ < proto::terminal<number<proto::_, two_complement_c> > , proto::terminal<number<proto::_, magnitude_c> > > {}; struct my_terminal {}; void test_matches() { assert_matches< _ >( lit(1) ); assert_matches< _ >( as_child(1) ); assert_matches< _ >( as_expr(1) ); assert_matches< terminal<int> >( lit(1) ); assert_matches< terminal<int> >( as_child(1) ); assert_matches< terminal<int> >( as_expr(1) ); assert_not_matches< terminal<int> >( lit('a') ); assert_not_matches< terminal<int> >( as_child('a') ); assert_not_matches< terminal<int> >( as_expr('a') ); assert_matches< terminal<convertible_to<int> > >( lit('a') ); assert_matches< terminal<convertible_to<int> > >( as_child('a') ); assert_matches< terminal<convertible_to<int> > >( as_expr('a') ); assert_not_matches< terminal<int> >( lit((int_convertible())) ); assert_not_matches< terminal<int> >( as_child((int_convertible())) ); assert_not_matches< terminal<int> >( as_expr((int_convertible())) ); assert_matches< terminal<convertible_to<int> > >( lit((int_convertible())) ); assert_matches< terminal<convertible_to<int> > >( as_child((int_convertible())) ); assert_matches< terminal<convertible_to<int> > >( as_expr((int_convertible())) ); assert_matches< if_<is_same<_value, int>() > >( lit(1) ); assert_not_matches< if_<is_same<_value, int>() > >( lit('a') ); assert_matches< and_< terminal<_> , if_<is_same<_value, int>() > > >( lit(1) ); assert_not_matches< and_< terminal<_> , if_<is_same<_value, int>() > > >( lit('a') ); assert_matches< terminal<char const *> >( lit("hello") ); assert_matches< terminal<char const *> >( as_child("hello") ); assert_matches< terminal<char const *> >( as_expr("hello") ); assert_matches< terminal<char const[6]> >( lit("hello") ); assert_matches< terminal<char const (&)[6]> >( as_child("hello") ); assert_matches< terminal<char const[6]> >( as_expr("hello") ); assert_matches< terminal<char [6]> >( lit("hello") ); assert_matches< terminal<char [6]> >( as_child("hello") ); assert_matches< terminal<char [6]> >( as_expr("hello") ); assert_matches< terminal<char const[N]> >( lit("hello") ); assert_matches< terminal<char const (&)[N]> >( as_child("hello") ); assert_matches< terminal<char const[N]> >( as_expr("hello") ); assert_matches< terminal<char [N]> >( lit("hello") ); assert_matches< terminal<char [N]> >( as_child("hello") ); assert_matches< terminal<char [N]> >( as_expr("hello") ); assert_not_matches< if_<is_same<_value, int>()> >( lit("hello") ); assert_matches< terminal<std::string> >( lit(std::string("hello")) ); assert_matches< terminal<std::string> >( as_child(std::string("hello")) ); assert_matches< terminal<std::string> >( as_expr(std::string("hello")) ); assert_matches< terminal<std::basic_string<_> > >( lit(std::string("hello")) ); assert_matches< terminal<std::basic_string<_> > >( as_child(std::string("hello")) ); assert_matches< terminal<std::basic_string<_> > >( as_expr(std::string("hello")) ); assert_not_matches< terminal<std::basic_string<_> > >( lit(1) ); assert_not_matches< terminal<std::basic_string<_> > >( as_child(1) ); assert_not_matches< terminal<std::basic_string<_> > >( as_expr(1) ); assert_not_matches< terminal<std::basic_string<_,_,_> > >( lit(1) ); assert_not_matches< terminal<std::basic_string<_,_,_> > >( as_child(1) ); assert_not_matches< terminal<std::basic_string<_,_,_> > >( as_expr(1) ); #if BOOST_WORKAROUND(__HP_aCC, BOOST_TESTED_AT(61700)) typedef std::string const const_string; #else typedef std::string const_string; #endif assert_matches< terminal<std::basic_string<_> const & > >( lit(const_string("hello")) ); assert_matches< terminal<std::basic_string<_> const & > >( as_child(const_string("hello")) ); assert_not_matches< terminal<std::basic_string<_> const & > >( as_expr(const_string("hello")) ); assert_matches< terminal< void(&)() > >( lit(a_function) ); assert_matches< terminal< void(&)() > >( as_child(a_function) ); assert_matches< terminal< void(&)() > >( as_expr(a_function) ); assert_not_matches< terminal< void(*)() > >( lit(a_function) ); assert_not_matches< terminal< void(*)() > >( as_child(a_function) ); assert_not_matches< terminal< void(*)() > >( as_expr(a_function) ); assert_matches< terminal< convertible_to<void(*)()> > >( lit(a_function) ); assert_matches< terminal< convertible_to<void(*)()> > >( as_child(a_function) ); assert_matches< terminal< convertible_to<void(*)()> > >( as_expr(a_function) ); assert_matches< terminal< void(*)() > >( lit(&a_function) ); assert_matches< terminal< void(*)() > >( as_child(&a_function) ); assert_matches< terminal< void(*)() > >( as_expr(&a_function) ); assert_matches< terminal< void(* const &)() > >( lit(&a_function) ); assert_matches< terminal< void(* const &)() > >( as_child(&a_function) ); assert_not_matches< terminal< void(* const &)() > >( as_expr(&a_function) ); assert_matches< or_< if_<is_same<_value, char>() > , if_<is_same<_value, int>() > > >( lit(1) ); assert_not_matches< or_< if_<is_same<_value, char>() > , if_<is_same<_value, int>() > > >( lit(1u) ); assert_matches< Input >( cin_ >> 1 >> 2 >> 3 ); assert_not_matches< Output >( cin_ >> 1 >> 2 >> 3 ); assert_matches< Output >( cout_ << 1 << 2 << 3 ); assert_not_matches< Input >( cout_ << 1 << 2 << 3 ); assert_matches< function< terminal<int>, vararg< terminal<char> > > >( lit(1)('a','b','c','d') ); assert_not_matches< function< terminal<int>, vararg< terminal<char> > > >( lit(1)('a','b','c',"d") ); assert_matches< Anything >( cout_ << 1 << +lit('a') << lit(1)('a','b','c',"d") ); assert_matches< proto::switch_<MyCases> >( lit(1) >> 'a' ); assert_matches< proto::switch_<MyCases> >( lit(1) + 'a' ); assert_not_matches< proto::switch_<MyCases> >( lit(1) << 'a' ); number<int, two_complement_c> num; assert_matches<NumberGrammar>(proto::as_expr(num)); // check custom terminal types { proto::nullary_expr<my_terminal, int>::type i = {0}; assert_matches<proto::nullary_expr<my_terminal, _> >( i ); assert_not_matches<proto::terminal<_> >( i ); proto::terminal<int>::type j = {0}; assert_matches<proto::terminal<_> >( j ); assert_not_matches<proto::nullary_expr<my_terminal, _> >( j ); assert_matches<proto::nullary_expr<_, _> >( i ); } // check 0 and 1 arg forms or or_ and and_ { assert_matches< proto::and_<> >( lit(1) ); assert_not_matches< proto::or_<> >( lit(1) ); assert_matches< proto::and_<proto::terminal<int> > >( lit(1) ); assert_matches< proto::or_<proto::terminal<int> > >( lit(1) ); } } using namespace unit_test; /////////////////////////////////////////////////////////////////////////////// // init_unit_test_suite // test_suite* init_unit_test_suite( int argc, char* argv[] ) { test_suite *test = BOOST_TEST_SUITE("test proto::matches<>"); test->add(BOOST_TEST_CASE(&test_matches)); return test; }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 291 ] ] ]
828d9963b90edad752240cb869dd772cf6ca5af8
0619c96beb1d46e813d5171755c856ea378916b5
/Generation2/mainwindow.cpp
1ca21806583359ef3cb2ec370f68b86230fe57db
[]
no_license
Neuromancer2701/irrigationgui
d8f77eb299d1beadc04222e1663459fbdff123cc
9da8610a1f81aa47506a30da0f1fc94cac447129
refs/heads/master
2020-04-09T02:08:11.897300
2011-03-17T00:11:08
2011-03-17T00:11:08
32,092,689
0
0
null
null
null
null
UTF-8
C++
false
false
4,312
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QtCore/QTimer> #include <QDateTime> #include <qwaitcondition.h> #include "stdio.h" #include "math.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->port = new QextSerialPort("COM5"); port->setBaudRate(BAUD38400); port->setFlowControl(FLOW_OFF); port->setParity(PAR_NONE); port->setDataBits(DATA_8); port->setStopBits(STOP_2); port->setTimeout(100); //SyncTime(); internalTimer = new QTimer( this ); // create internal timer connect( internalTimer, SIGNAL(timeout()), SLOT(getdata()) ); internalTimer->start( 1000 ); // emit signal every second } MainWindow::~MainWindow() { delete ui; } void MainWindow::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void MainWindow::getdata() { char acHeader[2]; char acCmd[] = "G1"; char acBuffer[64]; QString format; int iEarthTemp; int iWindTemp; int iFireRaw; int iWaterRaw; int iEarthDuty; int iWindDuty; char acTime[32]; if(port->open(QIODevice::ReadWrite) == true) { qDebug("Port opened!!"); port->write(acCmd,sizeof(acCmd)); sleepMs(100); if(port->bytesAvailable() > 2) { port->peek(acHeader,sizeof(acHeader)); qDebug("Header: %s",acHeader); } if(acHeader[0] == 'G' && acHeader[1] == 'S') { port->read(acBuffer, port->bytesAvailable()); QString Data = acBuffer; ui->rawdataEdit->clear(); ui->rawdataEdit->insert(Data); sscanf(acBuffer, "GS%04d%04d%04d%04d%03d%03d%sDONE",&iEarthTemp, &iWindTemp, &iFireRaw, &iWaterRaw, &iEarthDuty,&iWindDuty, acTime); ui->EarthTemplineEdit->clear(); ui->EarthTemplineEdit->insert(format.sprintf("%.01f",(double)(iEarthTemp)/10)); ui->WindTemplineEdit->clear(); ui->WindTemplineEdit->insert(format.sprintf("%.01f",(double)(iWindTemp)/10)); ui->FirelineEdit->clear(); ui->FirelineEdit->insert(format.sprintf("%d",iFireRaw)); ui->WaterlineEdit->clear(); ui->WaterlineEdit->insert(format.sprintf("%d",iWaterRaw)); ui->EarthDutylineEdit->clear(); ui->EarthDutylineEdit->insert(format.sprintf("%d",iEarthDuty)); ui->WindDutylineEdit->clear(); ui->WindDutylineEdit->insert(format.sprintf("%d",iWindDuty)); ui->UnixTimelineEdit->clear(); format.sprintf("%s",acTime); format.chop(4); ui->UnixTimelineEdit->insert(format); } port->close(); } } void MainWindow::sleepMs(int milliseconds) { QWaitCondition sleep; QMutex dummy; dummy.lock(); sleep.wait(&dummy, milliseconds); } void MainWindow::SyncTime() { char acUnixTime[32]; char acBuffer[64]; unsigned int uiControllerTime; QDateTime CurrentTime = QDateTime::currentDateTime(); sprintf(acUnixTime,"G2%dS\n",CurrentTime.toTime_t()); qDebug(acUnixTime); if(port->open(QIODevice::ReadWrite) == true) { qDebug("Port opened!!"); port->write(acUnixTime,sizeof(acUnixTime)); sleepMs(1000); port->write("G5",sizeof("G5")); sleepMs(300); if(port->bytesAvailable() > 6) { port->read(acBuffer, port->bytesAvailable()); uiControllerTime = atoi(acBuffer); qDebug("%d",uiControllerTime); qDebug("%d",CurrentTime.toTime_t()); if(abs(CurrentTime.toTime_t() - uiControllerTime) < 60) { ui->statusLabel->clear(); ui->statusLabel->setText("Status : Time Synced"); } else { ui->statusLabel->clear(); ui->statusLabel->setText("Status : Time Out of synced"); } } port->close(); } }
[ "king.seth@1baa6d84-2001-11df-aa13-c314d3631722" ]
[ [ [ 1, 166 ] ] ]
2eb76f0ddb8fe48a12cd9f109dbe5b0692f0edd7
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testlocalsocket/src/tlocalsocketserver.cpp
972b4cc8137167dcf043a2834fc01fe1b962e51a
[]
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
4,824
cpp
/* * Copyright (c) 2007 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: * */ #include <c32comm.h> #if defined (__WINS__) #define PDD_NAME _L("ECDRV") #else #define PDD_NAME _L("EUART1") #define PDD2_NAME _L("EUART2") #define PDD3_NAME _L("EUART3") #define PDD4_NAME _L("EUART4") #endif #define LDD_NAME _L("ECOMM") /** * @file * * Pipe test server implementation */ #include "tlocalsocketserver.h" #include "tlocalsocket.h" _LIT(KServerName, "tlocalsocket"); CLocalSocketTestServer* CLocalSocketTestServer::NewL() { CLocalSocketTestServer *server = new(ELeave) CLocalSocketTestServer(); CleanupStack::PushL(server); server->ConstructL(KServerName); CleanupStack::Pop(server); return server; } static void InitCommsL() { TInt ret = User::LoadPhysicalDevice(PDD_NAME); User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret); #ifndef __WINS__ ret = User::LoadPhysicalDevice(PDD2_NAME); ret = User::LoadPhysicalDevice(PDD3_NAME); ret = User::LoadPhysicalDevice(PDD4_NAME); #endif ret = User::LoadLogicalDevice(LDD_NAME); User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret); ret = StartC32(); User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret); } LOCAL_C void MainL() { // Leave the hooks in for platform security #if (defined __DATA_CAGING__) RProcess().DataCaging(RProcess::EDataCagingOn); RProcess().SecureApi(RProcess::ESecureApiOn); #endif //InitCommsL(); CActiveScheduler* sched=NULL; sched=new(ELeave) CActiveScheduler; CActiveScheduler::Install(sched); CLocalSocketTestServer* server = NULL; // Create the CTestServer derived server TRAPD(err, server = CLocalSocketTestServer::NewL()); if(!err) { // Sync with the client and enter the active scheduler RProcess::Rendezvous(KErrNone); sched->Start(); } delete server; delete sched; } /** * Server entry point * @return Standard Epoc error code on exit */ TInt main() { __UHEAP_MARK; CTrapCleanup* cleanup = CTrapCleanup::New(); if(cleanup == NULL) { return KErrNoMemory; } TRAP_IGNORE(MainL()); delete cleanup; __UHEAP_MARKEND; return KErrNone; } CTestStep* CLocalSocketTestServer::CreateTestStep(const TDesC& aStepName) { CTestStep* testStep = NULL; // This server creates just one step but create as many as you want // They are created "just in time" when the worker thread is created // install steps if(aStepName == KTestBind) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestLseek) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestFstat) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestThreadSocketRead) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestThreadSocketWrite) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestMultProc) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestMultThread) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestListen) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestSetGetSockOpt) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestSetSockOptNegative1) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestSetSockOptNegative2) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestSetSockOptNegative3) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestSetSockOptNegative4) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestGetSockOptNegative1) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestGetSockOptNegative2) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestGetSockOptNegative3) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestGetSockOptNegative4) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestLocalSockIoctl) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestLocalSockFcntl) { testStep = new CTestLocalSocket(aStepName); } if(aStepName == KTestLocalSockSelect) { testStep = new CTestLocalSocket(aStepName); } return testStep; }
[ "none@none" ]
[ [ [ 1, 201 ] ] ]
79887d0ec42b6f580ec7418d5dd36f991f3fefa7
1cacbe790f7c6e04ca6b0068c7b2231ed2b827e1
/Oolong Engine2/Examples/Renderer/Tutorials/08 Shaders Demo (3DShaders.com)/Classes/Shader/3DShaders.src/Podium.h
415f75940c9236e99bbdfe9fc730a2845e8edbdf
[ "BSD-3-Clause" ]
permissive
tianxiao/oolongengine
f3d2d888afb29e19ee93f28223fce6ea48f194ad
8d80085c65ff3eed548549657e7b472671789e6a
refs/heads/master
2020-05-30T06:02:32.967513
2010-05-05T05:52:03
2010-05-05T05:52:03
8,245,292
3
3
null
null
null
null
UTF-8
C++
false
false
752
h
// // Author: Philip Rideout // Copyright: 2002-2006 3Dlabs Inc. Ltd. All rights reserved. // License: see 3Dlabs-license.txt // #ifndef PODIUM_H #define PODIUM_H // Represents the circular reflective podium. class TPodium { public: TPodium(); void Draw() const; void DrawTop(bool outline = false) const { drawCircle(y, outline, false); } void DrawBottom(bool outline = false) const { drawCircle(y - thickness, outline, true); } void DrawSide() const; private: void drawCircle(float y, bool outline, bool clockwise) const; void drawCircle(float y, bool clockwise) const; float delta; float xrad; float yrad; float trad; float thickness; float y; }; #endif
[ "mozeal@7fa7efda-f44a-0410-a86a-c1fddb4bcab7" ]
[ [ [ 1, 30 ] ] ]
ef65e39703d41b3505a27c6accda733a9c57e24f
530900d8d48f93e75c6c17db9e35346928da81d1
/src/shader.cpp
7ee12cc7744531a1426db3a25f94954c332b5451
[]
no_license
a5huynh/cse-167-final-project
6db9b6c223c7c2a0d8672f5d23854199364c24a3
05858eed5e118153d9fa3087cdcb296f12fa2e5a
refs/heads/master
2021-01-13T02:03:38.641043
2009-12-12T22:30:58
2009-12-12T22:30:58
420,976
0
2
null
null
null
null
UTF-8
C++
false
false
3,109
cpp
/* Copyright (C) 2006 So Yamaoka 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. */ #include <cstdio> #include <cstdlib> #include "shader.h" Shader::Shader(const char *vert, const char *frag, bool isFile) { binded = false; if(isFile) { char* vv = read(vert); char* vf = read(frag); setup(vv, vf); delete[] vv; delete[] vf; } else setup(vert, frag); } Shader::~Shader() { glDeleteObjectARB(pid); } void Shader::toggle() { if( binded ) { unbind(); } else { bind(); } } void Shader::bind() { binded = true; glUseProgramObjectARB(pid); } void Shader::unbind() { binded = false; glUseProgramObjectARB(0); } void Shader::printLog(const char* tag) { char glslLog[1024]; GLsizei glslLogSize; glGetInfoLogARB(pid, 1024, &glslLogSize, glslLog); if(glslLogSize>0) { fprintf(stderr, "%s:shader error log: %s\n", tag, glslLog); } else { fprintf(stdout, "%s:shader all ok.\n", tag); } } char* Shader::read(const char *filename) { char* shaderFile = 0; FILE* fp = fopen(filename, "rb"); if(!fp){fprintf(stderr, "File doesn't exist (%s)\n", filename); std::exit(-1);} // obtain the file size fseek(fp, 0, SEEK_END); long size = ftell(fp); rewind(fp); // alloc memory - will be deleted while setting the shader up shaderFile = new char[size+1]; // copy the file to the shaderFile fread(shaderFile, sizeof(char), size, fp); shaderFile[size]='\0'; // eliminate the garbage at EOF fclose(fp); fprintf(stdout, "shaderfile = %p\n", shaderFile); return shaderFile; } void Shader::setup(const char *vs, const char *fs) { //fprintf(stdout, "vs, fs = %p, %p\n", vs, fs); //GLuint vid = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB); //GLuint fid = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB); GLhandleARB vid = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB); GLhandleARB fid = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB); glShaderSourceARB(vid, 1, &vs, 0); glShaderSourceARB(fid, 1, &fs, 0); glCompileShaderARB(vid); glCompileShaderARB(fid); char glslLog[1024]; GLsizei glslLogSize; glGetInfoLogARB(vid, 1024, &glslLogSize, glslLog); if (glslLogSize) printf("vertex program log: %s\n", glslLog); glGetInfoLogARB(fid, 1024, &glslLogSize, glslLog); if (glslLogSize) printf("fragment program log: %s\n", glslLog); pid = glCreateProgramObjectARB(); glAttachObjectARB(pid, vid); glAttachObjectARB(pid, fid); // delete shader objects as soon as they have been attached to a program glDeleteObjectARB(vid); glDeleteObjectARB(fid); glLinkProgramARB(pid); }
[ [ [ 1, 138 ] ] ]
95435205e34df79552773ea3e601b229b77614d4
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/gbusters.h
798064c89629a19cd9555c6d3509a5b7e4827d5b
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,146
h
/************************************************************************* Gangbusters *************************************************************************/ class gbusters_state : public driver_device { public: gbusters_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ UINT8 * m_ram; // UINT8 * m_paletteram; // currently this uses generic palette handling /* video-related */ int m_layer_colorbase[3]; int m_sprite_colorbase; /* misc */ int m_palette_selected; int m_priority; /* devices */ device_t *m_maincpu; device_t *m_audiocpu; device_t *m_k007232; device_t *m_k052109; device_t *m_k051960; }; /*----------- defined in video/gbusters.c -----------*/ extern void gbusters_tile_callback(running_machine &machine, int layer,int bank,int *code,int *color,int *flags, int *priority); extern void gbusters_sprite_callback(running_machine &machine, int *code,int *color,int *priority,int *shadow); VIDEO_START( gbusters ); SCREEN_UPDATE( gbusters );
[ "Mike@localhost" ]
[ [ [ 1, 39 ] ] ]
5ec8dd910a18a87d51010b8cce92d91637e9af8b
cd387cba6088f351af4869c02b2cabbb678be6ae
/lib/geometry/example/3_linestring_example.cpp
cae6d36d86bed79e1f69855c948d48613ed41fad
[ "BSL-1.0" ]
permissive
pedromartins/mew-dev
e8a9cd10f73fbc9c0c7b5bacddd0e7453edd097e
e6384775b00f76ab13eb046509da21d7f395909b
refs/heads/master
2016-09-06T14:57:00.937033
2009-04-13T15:16:15
2009-04-13T15:16:15
32,332,332
0
0
null
null
null
null
UTF-8
C++
false
false
7,021
cpp
// Geometry Library // // Copyright Barend Gehrels, Geodan Holding B.V. Amsterdam, the Netherlands. // Copyright Bruno Lalande 2008 // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <vector> #include <deque> #include <iterator> #include <algorithm> // for reverse, unique #include <geometry/geometry.hpp> class derived_linestring : public geometry::linestring<geometry::point_xy<float>, std::deque, std::allocator> { public : typedef geometry::box<point_type> box_type; inline void rebox() { geometry::envelope(this->begin(), this->end(), m_box); } inline box_type box() const { return m_box; } private : box_type m_box; }; struct own_linestring : public std::vector<geometry::point_xy<double> > { typedef geometry::point_xy<double> point_type; // required for, at least, the simplify_linestring algorithm }; template<typename P> std::ostream & operator<<(std::ostream &s, const geometry::box<P> &b) { s << b.min_corner() << " - " << b.max_corner(); return s; } template<typename P> inline void translate_function(P& p) { p.x(p.x() + 100.0); } template<typename P> struct scale_functor { inline void operator()(P& p) { p.x(p.x() * 1000.0); p.y(p.y() * 1000.0); } }; int main(void) { // Define a linestring, which is a vector of points, and add some points geometry::linestring<geometry::point_xy<double> > ls; ls.push_back(geometry::point_xy<double>(1.1, 1.1)); geometry::point_xy<double> lp(2.5, 2.1); ls.push_back(lp); // Lines can be streamed as Well Known Text (OGC WKT) std::cout << ls << std::endl; // The bounding box of lines can be calculated and streamd useing the method above geometry::box<geometry::point_xy<double> > b; geometry::envelope(ls.begin(), ls.end(), b); std::cout << b << std::endl; // The length of the line can be calulated std::cout << "length: " << geometry::length(ls.begin(), ls.end()) << std::endl; // All things from vector can be called, because a linestring is a vector std::cout << "number of points: " << ls.size() << std::endl; // The distance from a point to a linestring can be calculated geometry::point_xy<double> p(1.9, 1.2); std::cout << "distance of " << p << " to line: " << geometry::distance(p, ls.begin(), ls.end()) << std::endl; // A linestring is a vector. However, some algorithms consider "segments", // which are the line pieces between two points of a linestring. // Here we go to the "primary versions" //geometry::distance_result d = geometry::impl::distance::point_to_segment( // p, geometry::segment<geometry::point_xy<double> >(ls.front(), ls.back())); //std::cout << sqrt(geometry::square_distance_point_to_segment(p, geometry::segment<geometry::point_xy<double> >(ls.front(), ls.back()))) << std::endl; // Add some points more, let's do it using a classic array. See documentation for picture typedef geometry::point_xy<double> P; const double c[][2] = { {3.1, 3.1}, {4.9, 1.1}, {3.1, 1.9} }; const int n = sizeof(c) / sizeof(c[0]); for (int i = 0; i < n; i++) { ls.push_back(P(c[i][0], c[i][1])); } std::cout << "original: " << ls << std::endl; // Output as iterator-pair on a vector { std::vector<geometry::point_xy<double> > v; std::copy(ls.begin(), ls.end(), std::back_inserter(v)); std::cout << "as vector-it-pair: " << geometry::make_as_wkt(std::make_pair(v.begin(), v.end())) << std::endl; } // All algorithms from std can be used: a linestring is a vector std::reverse(ls.begin(), ls.end()); std::cout << "reversed: " << ls << std::endl; std::reverse(ls.begin(), ls.end()); // The other way, using a vector instead of a linestring, is also possible std::vector<P> pv(ls.begin(), ls.end()); // However, you can NOT call length then, because length is defined for linestring<P> // All methods are templatized in two ways, so it is still possible to get the length // but with another name. This is like "find" and "find_if" std::cout << "length: " << geometry::length(pv.begin(), pv.end()) << std::endl; // If there are double points in the line, you can use unique to remove them // So we add the last point, print, make a unique copy and print ls.push_back(ls.back()); std::cout << "extra point: " << ls << std::endl; { geometry::linestring<P> ls_copy; std::unique_copy(ls.begin(), ls.end(), std::back_inserter(ls_copy)); ls = ls_copy; std::cout << "uniquecopy: " << ls << std::endl; } // Lines can be simplified using e.g. Douglas Peucker geometry::linestring<P> ls_simplified; geometry::simplify(ls.begin(), ls.end(), std::back_inserter(ls_simplified), 0.5); std::cout << "simplified: " << ls_simplified << std::endl; // Declare and fill a derived linestring derived_linestring dl; for (geometry::linestring<P>::const_iterator it = ls.begin(); it != ls.end(); it++) { dl.push_back(geometry::point_xy<float>(it->x(), it->y())); } // In this case it has its own box dl.rebox(); std::cout << dl.box() << std::endl; derived_linestring dls; // Simplify also works for derived classes geometry::simplify(dl.begin(), dl.end(), std::back_inserter(dls), 0.5); own_linestring ol; for (geometry::linestring<P>::const_iterator it = ls.begin(); it != ls.end(); it++) { ol.push_back(geometry::point_xy<double>(it->x(), it->y())); } own_linestring ols; // and for vectors or for own classes... geometry::simplify(ol.begin(), ol.end(), std::back_inserter(ols), 0.5); // for_each: // 1) Lines can be visited with std::for_each // 2) geometry::for_each_point is also defined for all geometries // 3) geometry::for_each_segment is defined for all geometries to all segments // 4) geometry::loop is defined for geometries to visit segments // with state apart, and to be able to break out (not shown here) { geometry::linestring<geometry::point_xy<double> > lscopy = ls; std::for_each(ls.begin(), ls.end(), translate_function<P>); geometry::for_each_point(ls.begin(), ls.end(), scale_functor<P>()); std::cout << ls << std::endl; ls = lscopy; std::cout << ls << std::endl; } // Finally, lines can be clipped using a clipping box. Clipped lines are added to the output iterator // Clipping is possible using vectors, or geometry::linestring types geometry::box<P> cb(P(1.5, 1.5), P(4.5, 2.5)); // Also possible: clip-output to a vector of vectors std::vector<std::vector<P> > vector_out; geometry::intersection(cb, ls.begin(), ls.end(), std::back_inserter(vector_out)); std::cout << "clipped output as vector:" << std::endl; for (size_t i = 0; i < vector_out.size(); i++) { std::copy(vector_out[i].begin(), vector_out[i].end(), std::ostream_iterator<P>(std::cout, " ")); std::cout << std::endl; } return 0; }
[ "fushunpoon@1fd432d8-e285-11dd-b2d9-215335d0b316" ]
[ [ [ 1, 205 ] ] ]
d90c79733f5495e65352fac5fb50e687d5696b43
c2abb873c8b352d0ec47757031e4a18b9190556e
/src/ogreIncludes/OgreEntity.h
b040218ef3600bab2d4a190cf42ed65206e0dabb
[]
no_license
twktheainur/vortex-ee
70b89ec097cd1c74cde2b75f556448965d0d345d
8b8aef42396cbb4c9ce063dd1ab2f44d95e994c6
refs/heads/master
2021-01-10T02:26:21.913972
2009-01-30T12:53:21
2009-01-30T12:53:21
44,046,528
0
0
null
null
null
null
UTF-8
C++
false
false
34,382
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #ifndef __Entity_H__ #define __Entity_H__ #include "OgrePrerequisites.h" #include "OgreCommon.h" #include "OgreString.h" #include "OgreMovableObject.h" #include "OgreQuaternion.h" #include "OgreVector3.h" #include "OgreHardwareBufferManager.h" #include "OgreMesh.h" #include "OgreRenderable.h" namespace Ogre { /** Defines an instance of a discrete, movable object based on a Mesh. @remarks Ogre generally divides renderable objects into 2 groups, discrete (separate) and relatively small objects which move around the world, and large, sprawling geometry which makes up generally immovable scenery, aka 'level geometry'. @par The Mesh and SubMesh classes deal with the definition of the geometry used by discrete movable objects. Entities are actual instances of objects based on this geometry in the world. Therefore there is usually a single set Mesh for a car, but there may be multiple entities based on it in the world. Entities are able to override aspects of the Mesh it is defined by, such as changing material properties per instance (so you can have many cars using the same geometry but different textures for example). Because a Mesh is split into SubMeshes for this purpose, the Entity class is a grouping class (much like the Mesh class) and much of the detail regarding individual changes is kept in the SubEntity class. There is a 1:1 relationship between SubEntity instances and the SubMesh instances associated with the Mesh the Entity is based on. @par Entity and SubEntity classes are never created directly. Use the createEntity method of the SceneManager (passing a model name) to create one. @par Entities are included in the scene by associating them with a SceneNode, using the attachEntity method. See the SceneNode class for full information. @note No functions were declared virtual to improve performance. */ class _OgreExport Entity: public MovableObject, public Resource::Listener { // Allow EntityFactory full access friend class EntityFactory; friend class SubEntity; public: typedef std::set<Entity*> EntitySet; protected: /** Private constructor (instances cannot be created directly). */ Entity(); /** Private constructor - specify name (the usual constructor used). */ Entity( const String& name, MeshPtr& mesh); /** The Mesh that this Entity is based on. */ MeshPtr mMesh; /** List of SubEntities (point to SubMeshes). */ typedef std::vector<SubEntity*> SubEntityList; SubEntityList mSubEntityList; /// State of animation for animable meshes AnimationStateSet* mAnimationState; /// Temp buffer details for software skeletal anim of shared geometry TempBlendedBufferInfo mTempSkelAnimInfo; /// Vertex data details for software skeletal anim of shared geometry VertexData* mSkelAnimVertexData; /// Temp buffer details for software vertex anim of shared geometry TempBlendedBufferInfo mTempVertexAnimInfo; /// Vertex data details for software vertex anim of shared geometry VertexData* mSoftwareVertexAnimVertexData; /// Vertex data details for hardware vertex anim of shared geometry /// - separate since we need to s/w anim for shadows whilst still altering /// the vertex data for hardware morphing (pos2 binding) VertexData* mHardwareVertexAnimVertexData; /// Have we applied any vertex animation to shared geometry? bool mVertexAnimationAppliedThisFrame; /// Have the temp buffers already had their geometry prepared for use in rendering shadow volumes? bool mPreparedForShadowVolumes; /** Internal method - given vertex data which could be from the Mesh or any submesh, finds the temporary blend copy. */ const VertexData* findBlendedVertexData(const VertexData* orig); /** Internal method - given vertex data which could be from the Mesh or any SubMesh, finds the corresponding SubEntity. */ SubEntity* findSubEntityForVertexData(const VertexData* orig); /** Internal method for extracting metadata out of source vertex data for fast assignment of temporary buffers later. */ void extractTempBufferInfo(VertexData* sourceData, TempBlendedBufferInfo* info); /** Internal method to clone vertex data definitions but to remove blend buffers. */ VertexData* cloneVertexDataRemoveBlendInfo(const VertexData* source); /** Internal method for preparing this Entity for use in animation. */ void prepareTempBlendBuffers(void); /** Mark all vertex data as so far unanimated. */ void markBuffersUnusedForAnimation(void); /** Internal method to restore original vertex data where we didn't perform any vertex animation this frame. */ void restoreBuffersForUnusedAnimation(bool hardwareAnimation); /** Ensure that any unbound pose animation buffers are bound to a safe default. @param srcData Original vertex data containing original positions @param destData Hardware animation vertex data to be checked */ void bindMissingHardwarePoseBuffers(const VertexData* srcData, VertexData* destData); /// Cached bone matrices, including any world transform Matrix4 *mBoneWorldMatrices; /// Cached bone matrices in skeleton local space, might shares with other entity instances. Matrix4 *mBoneMatrices; unsigned short mNumBoneMatrices; /// Records the last frame in which animation was updated unsigned long mFrameAnimationLastUpdated; /// Perform all the updates required for an animated entity void updateAnimation(void); /// Records the last frame in which the bones was updated /// It's a pointer because it can be shared between different entities with /// a shared skeleton. unsigned long *mFrameBonesLastUpdated; /** * A set of all the entities which shares a single SkeletonInstance. * This is only created if the entity is in fact sharing it's SkeletonInstance with * other Entities. */ EntitySet* mSharedSkeletonEntities; /// Private method to cache bone matrices from skeleton void cacheBoneMatrices(void); /// Flag determines whether or not to display skeleton bool mDisplaySkeleton; /// Flag indicating whether hardware animation is supported by this entities materials bool mHardwareAnimation; /// Number of hardware poses supported by materials ushort mHardwarePoseCount; /// Flag indicating whether we have a vertex program in use on any of our subentities bool mVertexProgramInUse; /// Counter indicating number of requests for software animation. int mSoftwareAnimationRequests; /// Counter indicating number of requests for software blended normals. int mSoftwareAnimationNormalsRequests; /// The LOD number of the mesh to use, calculated by _notifyCurrentCamera ushort mMeshLodIndex; /// LOD bias factor, inverted for optimisation when calculating adjusted depth Real mMeshLodFactorInv; /// Index of minimum detail LOD (NB higher index is lower detail) ushort mMinMeshLodIndex; /// Index of maximum detail LOD (NB lower index is higher detail) ushort mMaxMeshLodIndex; /// LOD bias factor, inverted for optimisation when calculating adjusted depth Real mMaterialLodFactorInv; /// Index of minimum detail LOD (NB higher index is lower detail) ushort mMinMaterialLodIndex; /// Index of maximum detail LOD (NB lower index is higher detail) ushort mMaxMaterialLodIndex; /** List of LOD Entity instances (for manual LODs). We don't know when the mesh is using manual LODs whether one LOD to the next will have the same number of SubMeshes, therefore we have to allow a separate Entity list with each alternate one. */ typedef std::vector<Entity*> LODEntityList; LODEntityList mLodEntityList; /** This Entity's personal copy of the skeleton, if skeletally animated */ SkeletonInstance* mSkeletonInstance; /// Has this entity been initialised yet? bool mInitialised; /// Last parent xform Matrix4 mLastParentXform; /// Mesh state count, used to detect differences size_t mMeshStateCount; /** Builds a list of SubEntities based on the SubMeshes contained in the Mesh. */ void buildSubEntityList(MeshPtr& mesh, SubEntityList* sublist); /// internal implementation of attaching a 'child' object to this entity and assign the parent node to the child entity void attachObjectImpl(MovableObject *pMovable, TagPoint *pAttachingPoint); /// internal implementation of detaching a 'child' object of this entity and clear the parent node of the child entity void detachObjectImpl(MovableObject* pObject); /// internal implementation of detaching all 'child' objects of this entity void detachAllObjectsImpl(void); /// Trigger reevaluation of the kind of vertex processing in use void reevaluateVertexProcessing(void); /// Apply vertex animation void applyVertexAnimation(bool hardwareAnimation, bool stencilShadows); /// Initialise the hardware animation elements for given vertex data void initHardwareAnimationElements(VertexData* vdata, ushort numberOfElements); /// Are software vertex animation temp buffers bound? bool tempVertexAnimBuffersBound(void) const; /// Are software skeleton animation temp buffers bound? bool tempSkelAnimBuffersBound(bool requestNormals) const; public: /// Contains the child objects (attached to bones) indexed by name typedef std::map<String, MovableObject*> ChildObjectList; protected: ChildObjectList mChildObjectList; /// Bounding box that 'contains' all the mesh of each child entity mutable AxisAlignedBox mFullBoundingBox; ShadowRenderableList mShadowRenderables; /** Nested class to allow entity shadows. */ class _OgreExport EntityShadowRenderable : public ShadowRenderable { protected: Entity* mParent; // Shared link to position buffer HardwareVertexBufferSharedPtr mPositionBuffer; // Shared link to w-coord buffer (optional) HardwareVertexBufferSharedPtr mWBuffer; // Link to current vertex data used to bind (maybe changes) const VertexData* mCurrentVertexData; // Original position buffer source binding unsigned short mOriginalPosBufferBinding; /// Link to SubEntity, only present if SubEntity has it's own geometry SubEntity* mSubEntity; public: EntityShadowRenderable(Entity* parent, HardwareIndexBufferSharedPtr* indexBuffer, const VertexData* vertexData, bool createSeparateLightCap, SubEntity* subent, bool isLightCap = false); ~EntityShadowRenderable(); /// Overridden from ShadowRenderable void getWorldTransforms(Matrix4* xform) const; HardwareVertexBufferSharedPtr getPositionBuffer(void) { return mPositionBuffer; } HardwareVertexBufferSharedPtr getWBuffer(void) { return mWBuffer; } /// Rebind the source positions (for temp buffer users) void rebindPositionBuffer(const VertexData* vertexData, bool force); /// Overridden from ShadowRenderable bool isVisible(void) const; }; public: /** Default destructor. */ ~Entity(); /** Gets the Mesh that this Entity is based on. */ const MeshPtr& getMesh(void) const; /** Gets a pointer to a SubEntity, ie a part of an Entity. */ SubEntity* getSubEntity(unsigned int index) const; /** Gets a pointer to a SubEntity by name @remarks - names should be initialized during a Mesh creation. */ SubEntity* getSubEntity( const String& name ) const; /** Retrieves the number of SubEntity objects making up this entity. */ unsigned int getNumSubEntities(void) const; /** Clones this entity and returns a pointer to the clone. @remarks Useful method for duplicating an entity. The new entity must be given a unique name, and is not attached to the scene in any way so must be attached to a SceneNode to be visible (exactly as entities returned from SceneManager::createEntity). @param newName Name for the new entity. */ Entity* clone( const String& newName ) const; /** Sets the material to use for the whole of this entity. @remarks This is a shortcut method to set all the materials for all subentities of this entity. Only use this method is you want to set the same material for all subentities or if you know there is only one. Otherwise call getSubEntity() and call the same method on the individual SubEntity. */ void setMaterialName(const String& name); /** Overridden - see MovableObject. */ void _notifyCurrentCamera(Camera* cam); /// Overridden - see MovableObject. void setRenderQueueGroup(uint8 queueID); /** Overridden - see MovableObject. */ const AxisAlignedBox& getBoundingBox(void) const; /// merge all the child object Bounds a return it AxisAlignedBox getChildObjectsBoundingBox(void) const; /** Overridden - see MovableObject. */ void _updateRenderQueue(RenderQueue* queue); /** Overridden from MovableObject */ const String& getMovableType(void) const; /** For entities based on animated meshes, gets the AnimationState object for a single animation. @remarks You animate an entity by updating the animation state objects. Each of these represents the current state of each animation available to the entity. The AnimationState objects are initialised from the Mesh object. */ AnimationState* getAnimationState(const String& name) const; /** For entities based on animated meshes, gets the AnimationState objects for all animations. @returns In case the entity is animated, this functions returns the pointer to a AnimationStateSet containing all animations of the entries. If the entity is not animated, it returns 0. @remarks You animate an entity by updating the animation state objects. Each of these represents the current state of each animation available to the entity. The AnimationState objects are initialised from the Mesh object. */ AnimationStateSet* getAllAnimationStates(void) const; /** Tells the Entity whether or not it should display it's skeleton, if it has one. */ void setDisplaySkeleton(bool display); /** Returns whether or not the entity is currently displaying its skeleton. */ bool getDisplaySkeleton(void) const; /** Gets a pointer to the entity representing the numbered manual level of detail. @remarks The zero-based index never includes the original entity, unlike Mesh::getLodLevel. */ Entity* getManualLodLevel(size_t index) const; /** Returns the number of manual levels of detail that this entity supports. @remarks This number never includes the original entity, it is difference with Mesh::getNumLodLevels. */ size_t getNumManualLodLevels(void) const; /** Returns the current LOD used to render */ ushort getCurrentLodIndex() { return mMeshLodIndex; } /** Sets a level-of-detail bias for the mesh detail of this entity. @remarks Level of detail reduction is normally applied automatically based on the Mesh settings. However, it is possible to influence this behaviour for this entity by adjusting the LOD bias. This 'nudges' the mesh level of detail used for this entity up or down depending on your requirements. You might want to use this if there was a particularly important entity in your scene which you wanted to detail better than the others, such as a player model. @par There are three parameters to this method; the first is a factor to apply; it defaults to 1.0 (no change), by increasing this to say 2.0, this model would take twice as long to reduce in detail, whilst at 0.5 this entity would use lower detail versions twice as quickly. The other 2 parameters are hard limits which let you set the maximum and minimum level-of-detail version to use, after all other calculations have been made. This lets you say that this entity should never be simplified, or that it can only use LODs below a certain level even when right next to the camera. @param factor Proportional factor to apply to the distance at which LOD is changed. Higher values increase the distance at which higher LODs are displayed (2.0 is twice the normal distance, 0.5 is half). @param maxDetailIndex The index of the maximum LOD this entity is allowed to use (lower indexes are higher detail: index 0 is the original full detail model). @param minDetailIndex The index of the minimum LOD this entity is allowed to use (higher indexes are lower detail). Use something like 99 if you want unlimited LODs (the actual LOD will be limited by the number in the Mesh) */ void setMeshLodBias(Real factor, ushort maxDetailIndex = 0, ushort minDetailIndex = 99); /** Sets a level-of-detail bias for the material detail of this entity. @remarks Level of detail reduction is normally applied automatically based on the Material settings. However, it is possible to influence this behaviour for this entity by adjusting the LOD bias. This 'nudges' the material level of detail used for this entity up or down depending on your requirements. You might want to use this if there was a particularly important entity in your scene which you wanted to detail better than the others, such as a player model. @par There are three parameters to this method; the first is a factor to apply; it defaults to 1.0 (no change), by increasing this to say 2.0, this entity would take twice as long to use a lower detail material, whilst at 0.5 this entity would use lower detail versions twice as quickly. The other 2 parameters are hard limits which let you set the maximum and minimum level-of-detail index to use, after all other calculations have been made. This lets you say that this entity should never be simplified, or that it can only use LODs below a certain level even when right next to the camera. @param factor Proportional factor to apply to the distance at which LOD is changed. Higher values increase the distance at which higher LODs are displayed (2.0 is twice the normal distance, 0.5 is half). @param maxDetailIndex The index of the maximum LOD this entity is allowed to use (lower indexes are higher detail: index 0 is the original full detail model). @param minDetailIndex The index of the minimum LOD this entity is allowed to use (higher indexes are lower detail. Use something like 99 if you want unlimited LODs (the actual LOD will be limited by the number of lod indexes used in the Material) */ void setMaterialLodBias(Real factor, ushort maxDetailIndex = 0, ushort minDetailIndex = 99); /** Sets whether the polygon mode of this entire entity may be overridden by the camera detail settings. */ void setPolygonModeOverrideable(bool PolygonModeOverrideable); /** Attaches another object to a certain bone of the skeleton which this entity uses. @remarks This method can be used to attach another object to an animated part of this entity, by attaching it to a bone in the skeleton (with an offset if required). As this entity is animated, the attached object will move relative to the bone to which it is attached. @par An exception is thrown if the movable object is already attached to the bone, another bone or scenenode. If the entity has no skeleton or the bone name cannot be found then an exception is thrown. @param boneName The name of the bone (in the skeleton) to attach this object @param pMovable Pointer to the object to attach @param offsetOrientation An adjustment to the orientation of the attached object, relative to the bone. @param offsetPosition An adjustment to the position of the attached object, relative to the bone. @returns The TagPoint to which the object has been attached */ TagPoint* attachObjectToBone(const String &boneName, MovableObject *pMovable, const Quaternion &offsetOrientation = Quaternion::IDENTITY, const Vector3 &offsetPosition = Vector3::ZERO); /** Detach a MovableObject previously attached using attachObjectToBone. If the movable object name is not found then an exception is raised. @param movableName is the name of the movable object to be detached. */ MovableObject* detachObjectFromBone(const String &movableName); /** Detaches an object by pointer. @remarks Use this method to destroy a MovableObject which is attached to a bone of belonging this entity. But sometimes the object may be not in the child object list because it is a lod entity, this method can safely detect and ignore in this case and won't raise an exception. */ void detachObjectFromBone(MovableObject* obj); /// Detach all MovableObjects previously attached using attachObjectToBone void detachAllObjectsFromBone(void); typedef MapIterator<ChildObjectList> ChildObjectListIterator; /** Gets an iterator to the list of objects attached to bones on this entity. */ ChildObjectListIterator getAttachedObjectIterator(void); /** @see MovableObject::getBoundingRadius */ Real getBoundingRadius(void) const; /** @copy MovableObject::getWorldBoundingBox */ const AxisAlignedBox& getWorldBoundingBox(bool derive = false) const; /** @copy MovableObject::getWorldBoundingSphere */ const Sphere& getWorldBoundingSphere(bool derive = false) const; /** Overridden member from ShadowCaster. */ EdgeData* getEdgeList(void); /** Overridden member from ShadowCaster. */ bool hasEdgeList(void); /** Overridden member from ShadowCaster. */ ShadowRenderableListIterator getShadowVolumeRenderableIterator( ShadowTechnique shadowTechnique, const Light* light, HardwareIndexBufferSharedPtr* indexBuffer, bool extrudeVertices, Real extrusionDistance, unsigned long flags = 0 ); /** Internal method for retrieving bone matrix information. */ const Matrix4* _getBoneMatrices(void) const { return mBoneMatrices;} /** Internal method for retrieving bone matrix information. */ unsigned short _getNumBoneMatrices(void) const { return mNumBoneMatrices; } /** Returns whether or not this entity is skeletally animated. */ bool hasSkeleton(void) const { return mSkeletonInstance != 0; } /** Get this Entity's personal skeleton instance. */ SkeletonInstance* getSkeleton(void) const { return mSkeletonInstance; } /** Returns whether or not hardware animation is enabled. @remarks Because fixed-function indexed vertex blending is rarely supported by existing graphics cards, hardware animation can only be done if the vertex programs in the materials used to render an entity support it. Therefore, this method will only return true if all the materials assigned to this entity have vertex programs assigned, and all those vertex programs must support 'includes_morph_animation true' if using morph animation, 'includes_pose_animation true' if using pose animation and 'includes_skeletal_animation true' if using skeletal animation. */ bool isHardwareAnimationEnabled(void) const { return mHardwareAnimation; } /** Overridden from MovableObject */ void _notifyAttached(Node* parent, bool isTagPoint = false); /** Returns the number of requests that have been made for software animation @remarks If non-zero then software animation will be performed in updateAnimation regardless of the current setting of isHardwareAnimationEnabled or any internal optimise for eliminate software animation. Requests for software animation are made by calling the addSoftwareAnimationRequest() method. */ int getSoftwareAnimationRequests(void) const { return mSoftwareAnimationRequests; } /** Returns the number of requests that have been made for software animation of normals @remarks If non-zero, and getSoftwareAnimationRequests() also returns non-zero, then software animation of normals will be performed in updateAnimation regardless of the current setting of isHardwareAnimationEnabled or any internal optimise for eliminate software animation. Currently it is not possible to force software animation of only normals. Consequently this value is always less than or equal to that returned by getSoftwareAnimationRequests(). Requests for software animation of normals are made by calling the addSoftwareAnimationRequest() method with 'true' as the parameter. */ int getSoftwareAnimationNormalsRequests(void) const { return mSoftwareAnimationNormalsRequests; } /** Add a request for software animation @remarks Tells the entity to perform animation calculations for skeletal/vertex animations in software, regardless of the current setting of isHardwareAnimationEnabled(). Software animation will be performed any time one or more requests have been made. If 'normalsAlso' is 'true', then the entity will also do software blending on normal vectors, in addition to positions. This advanced method useful for situations in which access to actual mesh vertices is required, such as accurate collision detection or certain advanced shading techniques. When software animation is no longer needed, the caller of this method should always remove the request by calling removeSoftwareAnimationRequest(), passing the same value for 'normalsAlso'. */ void addSoftwareAnimationRequest(bool normalsAlso); /** Removes a request for software animation @remarks Calling this decrements the entity's internal counter of the number of requests for software animation. If the counter is already zero then calling this method throws an exception. The 'normalsAlso' flag if set to 'true' will also decrement the internal counter of number of requests for software animation of normals. */ void removeSoftwareAnimationRequest(bool normalsAlso); /** Shares the SkeletonInstance with the supplied entity. * Note that in order for this to work, both entities must have the same * Skeleton. */ void shareSkeletonInstanceWith(Entity* entity); /** Returns whether or not this entity is either morph or pose animated. */ bool hasVertexAnimation(void) const; /** Stops sharing the SkeletonInstance with other entities. */ void stopSharingSkeletonInstance(); /** * Returns whether this entity shares it's SkeltonInstance with other entity instances. */ inline bool sharesSkeletonInstance() const { return mSharedSkeletonEntities != NULL; } /** * Returns a pointer to the set of entities which share a SkeletonInstance. * If this instance does not share it's SkeletonInstance with other instances NULL will be returned */ inline const EntitySet* getSkeletonInstanceSharingSet() const { return mSharedSkeletonEntities; } /** Updates the internal animation state set to include the latest available animations from the attached skeleton. @remarks Use this method if you manually add animations to a skeleton, or have linked the skeleton to another for animation purposes since creating this entity. @note If you have called getAnimationState prior to calling this method, the pointers will still remain valid. */ void refreshAvailableAnimationState(void); /** Advanced method to perform all the updates required for an animated entity. @remarks You don't normally need to call this, but it's here in case you wish to manually update the animation of an Entity at a specific point in time. Animation will not be updated more than once a frame no matter how many times you call this method. */ void _updateAnimation(void); /** Tests if any animation applied to this entity. @remarks An entity is animated if any animation state is enabled, or any manual bone applied to the skeleton. */ bool _isAnimated(void) const; /** Tests if skeleton was animated. */ bool _isSkeletonAnimated(void) const; /** Advanced method to get the temporarily blended skeletal vertex information for entities which are software skinned. @remarks Internal engine will eliminate software animation if possible, this information is unreliable unless added request for software animation via addSoftwareAnimationRequest. @note The positions/normals of the returned vertex data is in object space. */ VertexData* _getSkelAnimVertexData(void) const; /** Advanced method to get the temporarily blended software vertex animation information @remarks Internal engine will eliminate software animation if possible, this information is unreliable unless added request for software animation via addSoftwareAnimationRequest. @note The positions/normals of the returned vertex data is in object space. */ VertexData* _getSoftwareVertexAnimVertexData(void) const; /** Advanced method to get the hardware morph vertex information @note The positions/normals of the returned vertex data is in object space. */ VertexData* _getHardwareVertexAnimVertexData(void) const; /** Advanced method to get the temp buffer information for software skeletal animation. */ TempBlendedBufferInfo* _getSkelAnimTempBufferInfo(void); /** Advanced method to get the temp buffer information for software morph animation. */ TempBlendedBufferInfo* _getVertexAnimTempBufferInfo(void); /// Override to return specific type flag uint32 getTypeFlags(void) const; /// Retrieve the VertexData which should be used for GPU binding VertexData* getVertexDataForBinding(void); /// Identify which vertex data we should be sending to the renderer enum VertexDataBindChoice { BIND_ORIGINAL, BIND_SOFTWARE_SKELETAL, BIND_SOFTWARE_MORPH, BIND_HARDWARE_MORPH }; /// Choose which vertex data to bind to the renderer VertexDataBindChoice chooseVertexDataForBinding(bool hasVertexAnim) const; /** Are buffers already marked as vertex animated? */ bool _getBuffersMarkedForAnimation(void) const { return mVertexAnimationAppliedThisFrame; } /** Mark just this vertex data as animated. */ void _markBuffersUsedForAnimation(void); /** Has this Entity been initialised yet? @remarks If this returns false, it means this Entity hasn't been completely constructed yet from the underlying resources (Mesh, Skeleton), which probably means they were delay-loaded and aren't available yet. This Entity won't render until it has been successfully initialised, nor will many of the manipulation methods function. */ bool isInitialised(void) const { return mInitialised; } /** Try to initialise the Entity from the underlying resources. @remarks This method builds the internal structures of the Entity based on it resources (Mesh, Skeleton). This may or may not succeed if the resources it references have been earmarked for background loading, so you should check isInitialised afterwards to see if it was sucessful. @param forceReinitialise If true, this forces the Entity to tear down it's internal structures and try to rebuild them. Useful if you changed the content of a Mesh or Skeleton at runtime. */ void _initialise(bool forceReinitialise = false); /** Tear down the internal structures of this Entity, rendering it uninitialised. */ void _deinitialise(void); /** Resource::Listener hook to notify Entity that a delay-loaded Mesh is complete. */ void backgroundLoadingComplete(Resource* res); /// @copydoc MovableObject::visitRenderables void visitRenderables(Renderable::Visitor* visitor, bool debugRenderables = false); }; /** Factory object for creating Entity instances */ class _OgreExport EntityFactory : public MovableObjectFactory { protected: MovableObject* createInstanceImpl( const String& name, const NameValuePairList* params); public: EntityFactory() {} ~EntityFactory() {} static String FACTORY_TYPE_NAME; const String& getType(void) const; void destroyInstance( MovableObject* obj); }; } // namespace #endif
[ "seb.owk@37e2baaa-b253-11dd-9381-bf584fb1fa83" ]
[ [ [ 1, 764 ] ] ]
6c2b537361faf13a375e8f377b0977c0271fa085
426ce36f170ef51acea1583c4c76c5fc5923fe08
/OpticalFlow.h
b09799424e8921c72b248e3fc89a7d0a0bd5fc56
[]
no_license
ayushpurohit/human-action-recognition
b42c7c6c746c9fb1e83e6d85fe88804a38ef70ef
da9653b4f41119e23de9b66ad65871a02f1b3dc7
refs/heads/master
2021-01-10T14:00:39.120712
2008-08-18T21:25:41
2008-08-18T21:25:41
46,225,758
1
2
null
null
null
null
UTF-8
C++
false
false
895
h
#pragma once #include "stdafx.h" #include "Texture.h" #define N_FRAMES_SUM 12 class OpticalFlow { public: OpticalFlow(CvSize frameSize, CvSize finalSize = cvSize(80,60)); ~OpticalFlow(void); void Calculate(IplImage *frame, double mspf=41.72); void Draw(int x=0, int y=0, int w=0, int h=0); void Write(ofstream &fout); void Align(CvPoint center, double radius, IplImage *mask = NULL); void Normalize(IplImage *image); void Smooth(IplImage *image); void Split(); void Finalize(); double* GetData(); public: IplImage *_velx, *_vely, *_velz, *_tmp, *_gray1, *_gray2, *_vis; CvSize _finalSize; IplImage *_nFlow[N_FRAMES_SUM], *_eFlow[N_FRAMES_SUM], *_sFlow[N_FRAMES_SUM], *_wFlow[N_FRAMES_SUM], *_zFlow[N_FRAMES_SUM]; IplImage *_nSum, *_eSum, *_sSum, *_wSum, *_zSum; double *_data; Texture _tex; const double _lambda; CvTermCriteria _criteria; };
[ "mnbayazit@391b830b-d650-0410-bb89-83bffae94361" ]
[ [ [ 1, 30 ] ] ]
5560b56794297a04ac12da3deaba3dbfce25a625
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/othldrby.h
8774550e4b609d6bb9d19211da10d310213f1331
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,057
h
/************************************************************************* Othello Derby *************************************************************************/ #define OTHLDRBY_VREG_SIZE 18 class othldrby_state : public driver_device { public: othldrby_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ UINT16 * m_vram; UINT16 * m_buf_spriteram; UINT16 * m_buf_spriteram2; /* video-related */ tilemap_t *m_bg_tilemap[3]; UINT16 m_vreg[OTHLDRBY_VREG_SIZE]; UINT32 m_vram_addr; UINT32 m_vreg_addr; /* misc */ int m_toggle; }; /*----------- defined in video/othldrby.c -----------*/ WRITE16_HANDLER( othldrby_videoram_addr_w ); READ16_HANDLER( othldrby_videoram_r ); WRITE16_HANDLER( othldrby_videoram_w ); WRITE16_HANDLER( othldrby_vreg_addr_w ); WRITE16_HANDLER( othldrby_vreg_w ); VIDEO_START( othldrby ); SCREEN_EOF( othldrby ); SCREEN_UPDATE( othldrby );
[ "Mike@localhost" ]
[ [ [ 1, 41 ] ] ]
2c5136eb0d60a4ed32e6a0b483692dd888488e92
e9ed44eaee7b0004e39073e05c2bc4659d8ca5ab
/tetrisgame.cpp
b102d253fbd64aa4e409873afbd3ad49389df01c
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
tkleisas/monolithpsp
37251e067df4a80daaca44ab1ac5d71e96fa0406
2c04bdc3643a406269aaf34b3dd970ffe8400f9e
refs/heads/master
2016-09-06T12:21:33.855616
2007-12-23T23:53:26
2007-12-23T23:53:26
33,156,364
0
0
null
null
null
null
UTF-8
C++
false
false
15,294
cpp
#include <pspkernel.h> #include <pspdisplay.h> #include <pspdebug.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <pspgu.h> #include <pspgum.h> #include <pspctrl.h> #include <psprtc.h> #include "callbacks.h" #include "vram.h" #include "controller.h" #include "text.h" #include "tetrisgame.h" #define BUF_WIDTH (512) #define SCR_WIDTH (480) #define SCR_HEIGHT (272) PSP_MODULE_INFO("psptetris", 0, 1, 1); PSP_HEAP_SIZE_KB(4096); //PSP_HEAP_SIZE_MAX(); PSP_MAIN_THREAD_ATTR(THREAD_ATTR_USER| THREAD_ATTR_VFPU); PSP_MAIN_THREAD_STACK_SIZE_KB(1024); int defaultminkeytime=75; TickCounter counter; Cube c0(0xff0000ff); Cube c1(0xff00ff00); Cube c2(0xffff0000); Cube c3(0xffff00ff); Cube c4(0xff00ffff); Cube c5(0xffffff00); Cube c6(0xffff9933); Cube c7(0xffffffff); Entity<6> textpixel; Entity<6> leftField; Entity<6> rightField; Entity<6> bottomField; Cube cubes[8]; static unsigned int __attribute__((aligned(16))) list[262144]; void CreateSquare(Entity<6>& square,float x1,float y1,float z1,float x2,float y2,float z2,float x3,float y3,float z3,float x4,float y4,float z4,unsigned int color) { /* square.SetVertex(0,-1.0,-1.0,color,x1,y1,z1); square.SetVertex(1,-1.0,1.0,color,x3,y3,z3); square.SetVertex(2,1.0,1.0,color,x2,y2,z2); square.SetVertex(3,1.0,-1.0,color,x1,y1,z1); square.SetVertex(4,-1.0,-1.0,color,x4,y4,z4); square.SetVertex(5,1.0,1.0,color,x3,y3,z3); */ square.SetVertex(0,0.0,0.0,color,x1,y1,z1); square.SetVertex(1,0.0,0.0,color,x3,y3,z3); square.SetVertex(2,0.0,0.0,color,x2,y2,z2); square.SetVertex(3,0.0,0.0,color,x1,y1,z1); square.SetVertex(4,0.0,0.0,color,x4,y4,z4); square.SetVertex(5,0.0,0.0,color,x3,y3,z3); } TetrisGame::TetrisGame() { setupCallbacks(); SetupController(); xzAngle=0.0; yzAngle=0.0; xyAngle=0.0; xzOffset=15; RotateAngle=0; yAngle=0; xAngle=0; xzOffsetDefault = xzOffset; rotationVertexDefaults.x=1.0; rotationVertexDefaults.y=1.0; rotationVertexDefaults.z=0; rotationVertex=rotationVertexDefaults; xpos=0; ypos=0; explosionComplete=true; acceleration = 0.001; explosionFrames=60; explosionCurrentFrame=0; explosion=false; isPaused=false; } TetrisGame::~TetrisGame() { sceGuTerm(); sceKernelExitGame(); } int TetrisGame::HandleInput() { int done; done = 0; int xpad = GetJoystickX()-128; int ypad = GetJoystickY()-128; float anglestep = 2.0*GU_PI/720.0f; if(xpad>15 || xpad<-15) { xzAngle = xzAngle+(((float)xpad)/15)*anglestep; } if(ypad>15 || ypad<-15) { yzAngle = yzAngle+(((float)ypad)/15)*anglestep; } unsigned int buttons = GetButtonsPressed(); if(buttons & PSP_CTRL_SELECT) { xyAngle=0.0; xzAngle=0.0; yzAngle=0.0; } if(buttons & PSP_CTRL_START) { return -16; } if(buttons & PSP_CTRL_UP) { return -4; } if(buttons & PSP_CTRL_RIGHT) { return -2; } if(buttons & PSP_CTRL_DOWN) { return -8; } if(buttons & PSP_CTRL_LEFT) { return -1; } if(buttons & PSP_CTRL_LTRIGGER) { } if(buttons & PSP_CTRL_RTRIGGER) { } if(buttons & PSP_CTRL_TRIANGLE) { } if(buttons & PSP_CTRL_CIRCLE) { } if(buttons & PSP_CTRL_CROSS) { return -4; } if(buttons & PSP_CTRL_SQUARE) { isPaused=!isPaused; } return done; } unsigned int TetrisGame::GetColor(char color) { switch(color) { case '1': return 0; break; case '2': return 1; break; case '3': return 2; break; case '4': return 3; break; case '5': return 4; break; case '6': return 5; break; case '7': return 6; break; default: return 7; break; } } void TetrisGame::InitGraphics() { void* fbp0 = getStaticVramBuffer(BUF_WIDTH,SCR_HEIGHT,GU_PSM_8888); void* fbp1 = getStaticVramBuffer(BUF_WIDTH,SCR_HEIGHT,GU_PSM_8888); void* zbp = getStaticVramBuffer(BUF_WIDTH,SCR_HEIGHT,GU_PSM_4444); sceGuInit(); sceGuStart(GU_DIRECT,list); sceGuDrawBuffer(GU_PSM_8888,fbp0,BUF_WIDTH); sceGuDispBuffer(SCR_WIDTH,SCR_HEIGHT,fbp1,BUF_WIDTH); sceGuDepthBuffer(zbp,BUF_WIDTH); sceGuOffset(2048 - (SCR_WIDTH/2),2048 - (SCR_HEIGHT/2)); sceGuViewport(2048,2048,SCR_WIDTH,SCR_HEIGHT); sceGuDepthRange(65535,0); sceGuScissor(0,0,SCR_WIDTH,SCR_HEIGHT); sceGuEnable(GU_SCISSOR_TEST); sceGuDepthFunc(GU_GEQUAL); sceGuEnable(GU_DEPTH_TEST); //sceGuDepthRange(65535,0); //sceGuFrontFace(GU_CW); sceGuShadeModel(GU_SMOOTH); //sceGuShadeModel(GU_FLAT); //sceGuEnable(GU_CULL_FACE); //sceGuEnable(GU_TEXTURE_2D); sceGuEnable(GU_CLIP_PLANES);///// sceGuFinish(); sceGuSync(0,0); sceDisplayWaitVblankStart(); sceGuDisplay(GU_TRUE); } void TetrisGame::DrawCube(float x,float y, float z,float xrot,float yrot,float zrot,int colorindex) { //sceGumPushMatrix(); sceGumLoadIdentity(); ScePspFVector3 pos = { x, y, z }; ScePspFVector3 rot = { xrot, yrot, zrot}; sceGumTranslate(&pos); sceGumRotateXYZ(&rot); sceGumDrawArray(GU_TRIANGLES,GU_TEXTURE_32BITF|GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D,12*3,0,cubes[colorindex].v); //sceGumPopMatrix(); } void TetrisGame::DrawPlayfield() { //sceGumPushMatrix(); sceGumLoadIdentity(); sceGumDrawArray(GU_TRIANGLES,GU_TEXTURE_32BITF|GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D,6*3,0,leftField.v); //sceGumPopMatrix(); //sceGumPushMatrix(); sceGumLoadIdentity(); sceGumDrawArray(GU_TRIANGLES,GU_TEXTURE_32BITF|GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D,6*3,0,rightField.v); //sceGumPopMatrix(); //sceGumPushMatrix(); sceGumLoadIdentity(); sceGumDrawArray(GU_TRIANGLES,GU_TEXTURE_32BITF|GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D,6*3,0,bottomField.v); //sceGumPopMatrix(); } void TetrisGame::Draw3DText(string text,unsigned int color, float offx, float offy, float offz, float scale,float thickness) { Text<128> theText(text); for(int y=0;y<8;y++) { for(int x=0;x<128;x++) { if(theText.billboard[x][y]==1) { //sceGumPushMatrix(); sceGumLoadIdentity(); ScePspFVector3 pos = { offx+(((float)x)*scale),offy+(-((float)y)*scale) , offz }; ScePspFVector3 rot = { 0, 0, 0}; sceGumTranslate(&pos); sceGumRotateXYZ(&rot); sceGumDrawArray(GU_TRIANGLES,GU_TEXTURE_32BITF|GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D,6*3,0,textpixel.v); //sceGumPopMatrix(); } } } } void TetrisGame::DrawNextPiece( float x, float y, float z) { unsigned int color = GetColor(tetris.NextBlock_.GetColor()); sceGumLoadIdentity(); ScePspFVector3 pos = { x, y, z }; ScePspFVector3 pos2 = { -1.0f, 1.0f, 0.0f }; ScePspFVector3 rot = { 0.0f, 0.0f, RotateAngle}; sceGumTranslate(&pos); sceGumRotateXYZ(&rot); sceGumTranslate(&pos2); for(int i=0;i<4;i++) { int x1 = tetris.NextBlock_.subblocks_[i].Xpos+tetris.NextBlock_.GetXPos(); int y1 = tetris.NextBlock_.subblocks_[i].Ypos+tetris.NextBlock_.GetYPos(); sceGumPushMatrix(); ScePspFVector3 pos = { x1*1.0f, -y1*1.0f, 0 }; ScePspFVector3 rot = { 0.0f, 0.0f, 0.0f}; sceGumTranslate(&pos); sceGumRotateXYZ(&rot); sceGumDrawArray(GU_TRIANGLES,GU_TEXTURE_32BITF|GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D,12*3,0,cubes[color].v); sceGumPopMatrix(); } } void TetrisGame::DrawBoard() { for(int y=0;y<20;y++) { for(int x=0;x<10;x++) { char result = tetris.GetGridValue(x,y); int color; switch(result) { case '1': color=0; break; case '2': color=1; break; case '3': color=2; break; case '4': color=3; break; case '5': color=4; break; case '6': color=5; break; case '7': color=6; break; default: color=-1; break; } if(color!=-1) { if(!(tetris.cleared_lines[y]==1)) { sceGumLoadIdentity(); ScePspFVector3 pos = { -5.0f+x*1.0f, 9.0f-y*1.0f, -2.5f }; ScePspFVector3 rot = { 0, 0, 0}; sceGumTranslate(&pos); sceGumRotateXYZ(&rot); sceGumDrawArray(GU_TRIANGLES,GU_TEXTURE_32BITF|GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D,12*3,0,cubes[color].v); } } } } } void TetrisGame::DrawFallingPiece() { unsigned int color = GetColor(tetris.CurrentBlock_.GetColor()); for(int i=0;i<4;i++) { int x1 = tetris.CurrentBlock_.subblocks_[i].Xpos+tetris.CurrentBlock_.GetXPos(); int y1 = tetris.CurrentBlock_.subblocks_[i].Ypos+tetris.CurrentBlock_.GetYPos(); sceGumLoadIdentity(); ScePspFVector3 pos = { -5.0f+x1*1.0f, 9.0f-y1*1.0f, -2.5f }; ScePspFVector3 rot = { 0.0f, 0.0f, 0.0f}; sceGumTranslate(&pos); sceGumRotateXYZ(&rot); sceGumDrawArray(GU_TRIANGLES,GU_TEXTURE_32BITF|GU_COLOR_8888|GU_VERTEX_32BITF|GU_TRANSFORM_3D,12*3,0,cubes[color].v); } } void TetrisGame::DrawExplosion() { vector<Explosion>::iterator iter=explosions.end(); while(iter!=explosions.begin()) { Explosion e=*iter; if(e.frame>explosionFrames) { explosions.erase(iter); } else { DrawCube(e.x,e.y,e.z,0.0,0.0,0.0,e.color); e.x=e.x+e.velx*e.frame; e.y=e.y+e.vely*e.frame; e.z=e.z+e.velz*e.frame; e.vely=e.vely-acceleration*e.frame; e.frame++; *iter=e; } iter--; } } void TetrisGame::ClearExplosion() { explosions.clear(); } void TetrisGame::CreateCubeExplosion(int x, int y, unsigned int color) { float velx = (((rand()%2)?-1:1))*(rand()%100/2000.0); float vely = (((rand()%2)?-1:1))*(rand()%100/2000.0); float velz = (((rand()%2)?-1:1))*(rand()%100/2000.0); Explosion e(-5.0f+x*1.0f,9.0f-y*1.0f,-2.5f,velx,vely,velz,0,color); explosions.push_back(e); } void TetrisGame::CreateLineExplosion(int line) { for(int x=0;x<GRID_MAX_WIDTH;x++) { unsigned int color = GetColor(tetris.GetGridValue(x,line)); CreateCubeExplosion(x,line,color); } } bool TetrisGame::CheckExplosions() { int clearedLines=tetris.GetClearedLineCount(); if(clearedLines>0) { for(int i=0;i<GRID_MAX_HEIGHT;i++) { if(tetris.cleared_lines[i]==1) { CreateLineExplosion(i); } } explosion = true; } else { explosion = false; return false; } return explosion; } void TetrisGame::GameLoop() { tetris.InitGame(1); tetris.SetStatus(TETRIS_PLAYING); tetris.ClearGrid(); tetris.TimerEnabled_ = true; unsigned int gameoversize=255; unsigned char gameoverstep=1; unsigned int now=tickcounter.GetTicks(); unsigned int lastKeyPress = tickcounter.GetTicks(); unsigned int minKeyTime = defaultminkeytime; float g_valyz=0; float g_valxz=0; sceKernelDcacheWritebackAll(); ClearExplosion(); while(running()) { sceKernelDelayThread(1000); sceGuStart(GU_DIRECT,list); sceGuClearColor(0x00000000); sceGuClearDepth(0); sceGuClear(GU_COLOR_BUFFER_BIT|GU_DEPTH_BUFFER_BIT); sceGumMatrixMode(GU_PROJECTION); sceGumLoadIdentity(); sceGumPerspective(75.0f,16.0f/9.0f,0.5f,1000.0f); sceGumMatrixMode(GU_VIEW); sceGumLoadIdentity(); ScePspFVector3 pos1 = { 0, 0, -16.0f }; ScePspFVector3 rot = { yzAngle, xzAngle, 0}; ScePspFVector3 pos2 = { 0, 0, 2.5f }; sceGumTranslate(&pos1); sceGumRotateXYZ(&rot); sceGumTranslate(&pos2); sceGumMatrixMode(GU_MODEL); DrawPlayfield(); DrawFallingPiece(); char str[255]; char level[255]; char lines[255]; char tick[255]; char sxpos[255]; char sypos[255]; sprintf(sxpos,"%f",yzAngle); sprintf(sypos,"%f",xzAngle); //sprintf(tick,"%u",tickcounter.GetTicks()); sprintf(lines,"%d",tetris.lines_); sprintf(str,"%d",tetris.score_); string s(str); while(s.length()<8) { s = "0"+s; } Draw3DText("SCORE",8,-18.0f,10.0f,0,0.2,0.2); Draw3DText(s,8,-18.0f,8.0f,0,0.2,0.2); //Draw3DText(string(sxpos),8,-15.0,10.0,0,0.2,0.2); //Draw3DText(string(sypos),8,-15.0,8.0,0,0.2,0.2); sprintf(level,"%d",tetris.level_); Draw3DText(string("LEVEL"),8,-18.0f,6.0f,0.0f,0.22f,0.22f); Draw3DText(string(level),8,-18.0f,4.0f,0.0f,0.22f,0.22f); Draw3DText(string("LINES"),8,-18.0f,2.0f,0.0f,0.22f,0.22f); Draw3DText(string(lines),8,-18.0f,0.0f,0.0f,0.22f,0.22f); Draw3DText(string("(C)TEACAKE"),8,4.2f,-8.0f,0.0f,0.18f,0.18f); DrawNextPiece(14.0f,-0.0f,-2.5f); if(isPaused && (tetris.GetStatus()==TETRIS_PLAYING)) { Draw3DText(string("PAUSED"),8,-5,2,3,0.4,0.4); } if(tetris.GetStatus()==TETRIS_GAME_OVER) { Draw3DText(string("GAME OVER"),8,-10.0f,1.0f,2.0f,0.3,0.3); gameoversize = gameoversize+gameoverstep; if (gameoversize>255) { gameoverstep=-gameoverstep; } if(gameoversize<30) { gameoverstep=-gameoverstep; } } DrawExplosion(); tetris.FlagCompletedLines(); if(tetris.GetClearedLineCount()>0) { CheckExplosions(); } DrawBoard(); RotateAngle = RotateAngle+0.01f; if(RotateAngle>360.0f) { RotateAngle=0.0f; } unsigned int timenow = tickcounter.GetTicks(); int done= HandleInput(); if(done==-16) { tetris.InitGame(1); tetris.SetStatus(TETRIS_PLAYING); tetris.ClearGrid(); ClearExplosion(); tetris.TimerEnabled_ = true; now=tickcounter.GetTicks(); lastKeyPress = tickcounter.GetTicks(); minKeyTime = defaultminkeytime; } if(isPaused) { //unsigned char message[255]; } else if(tetris.GetStatus()!=TETRIS_PLAYING) { } else if(timenow>now+tetris.timer_) { tetris.GameLoop(); now = tickcounter.GetTicks(); } else { if(done==-1) { if(tickcounter.GetTicks()-lastKeyPress>minKeyTime) { tetris.MoveBlockLeft(); } lastKeyPress = tickcounter.GetTicks(); } if(done==-2) { if(tickcounter.GetTicks()-lastKeyPress>minKeyTime) { tetris.MoveBlockRight(); } lastKeyPress = tickcounter.GetTicks(); } if(done==-4) { if(tickcounter.GetTicks()-lastKeyPress>minKeyTime*2) { tetris.RotateCurrentBlockClockwise(); } lastKeyPress = tickcounter.GetTicks(); } if(done==-8 ) { tetris.GameLoop(); } } //sceGumPopMatrix(); sceGuFinish(); sceGuSync(0,0); sceDisplayWaitVblankStart(); sceGuSwapBuffers(); } } int main(int argc, char* argv[]) { cubes[0] = c0; cubes[1] = c1; cubes[2] = c2; cubes[3] = c3; cubes[4] = c4; cubes[5] = c5; cubes[6] = c6; cubes[7] = c7; CreateSquare(textpixel,0.05,0.05,0.0,-0.05,0.05,0,-0.05,-0.05,0,0.05,-0.05,0,0xffffffff); CreateSquare(leftField,-5.6,-10.6,-2.0,-5.6,-10.6,-3.5f,-5.6,12.1,-3.5f,-5.6,12.1,-2.0,0xfff0f0f0); CreateSquare(rightField,4.6,-10.6,-2.0,4.6,-10.6,-3.5f,4.6,12.1,-3.5f,4.6,12.1,-2.0,0xfff0f0f0); CreateSquare(bottomField,-5.6,-10.6,-2.0,4.6,-10.6,-2.0,4.6,-10.6,-3.5,-5.6,-10.6,-3.5,0xfff0f0f0); TetrisGame game; game.InitGraphics(); game.GameLoop(); return 0; }
[ "Tasos.Kleisas@245eeae3-fe3f-0410-add2-53876a12f377", "tasos.kleisas@245eeae3-fe3f-0410-add2-53876a12f377" ]
[ [ [ 1, 27 ], [ 29, 90 ], [ 93, 411 ], [ 414, 414 ], [ 416, 416 ], [ 418, 419 ], [ 421, 421 ], [ 433, 434 ], [ 436, 438 ], [ 440, 445 ], [ 447, 449 ], [ 452, 470 ], [ 473, 501 ], [ 503, 504 ], [ 507, 508 ], [ 512, 585 ], [ 588, 588 ], [ 593, 593 ], [ 595, 595 ], [ 597, 611 ], [ 613, 615 ], [ 617, 632 ], [ 636, 636 ], [ 639, 643 ], [ 645, 652 ], [ 654, 662 ], [ 664, 664 ], [ 666, 671 ], [ 673, 683 ], [ 685, 713 ] ], [ [ 28, 28 ], [ 91, 92 ], [ 412, 413 ], [ 415, 415 ], [ 417, 417 ], [ 420, 420 ], [ 422, 432 ], [ 435, 435 ], [ 439, 439 ], [ 446, 446 ], [ 450, 451 ], [ 471, 472 ], [ 502, 502 ], [ 505, 506 ], [ 509, 511 ], [ 586, 587 ], [ 589, 592 ], [ 594, 594 ], [ 596, 596 ], [ 612, 612 ], [ 616, 616 ], [ 633, 635 ], [ 637, 638 ], [ 644, 644 ], [ 653, 653 ], [ 663, 663 ], [ 665, 665 ], [ 672, 672 ], [ 684, 684 ] ] ]
4ef8310489bf9ffc4dd20a7554db770d098d2aa7
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Utilities/VisualDebugger/Viewer/Dynamics/hkpConstraintViewer.h
c598954784f0b1061794f6e2826e84f26a8cf485
[]
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,714
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_UTILITIES2_CONSTRAINT_VIEWER_H #define HK_UTILITIES2_CONSTRAINT_VIEWER_H #include <Physics/Utilities/VisualDebugger/Viewer/Dynamics/hkpWorldViewerBase.h> #include <Physics/Dynamics/World/Listener/hkpWorldPostSimulationListener.h> #include <Physics/Dynamics/Constraint/hkpConstraintListener.h> class hkDebugDisplayHandler; class hkpWorld; class hkpRigidBody; /// Shows constraint limits and frames. class hkpConstraintViewer : public hkpWorldViewerBase, protected hkpWorldPostSimulationListener { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_TOOLS); /// Creates a hkpConstraintViewer. static hkProcess* HK_CALL create(const hkArray<hkProcessContext*>& contexts); /// Registers the hkpConstraintViewer with the hkViewerFactory. static void HK_CALL registerViewer(); /// Gets the tag associated with this viewer type virtual int getProcessTag() { return m_tag; } static inline const char* HK_CALL getName() { return "Constraints"; } protected: hkpConstraintViewer(const hkArray<hkProcessContext*>& contexts); virtual ~hkpConstraintViewer(); virtual void postSimulationCallback( hkpWorld* world ); virtual void worldAddedCallback( hkpWorld* world); virtual void worldRemovedCallback( hkpWorld* world); void draw(hkpConstraintInstance* constraint, hkDebugDisplayHandler* displayHandler); protected: static int m_tag; hkArray<hkpConstraintInstance*> m_constraints; }; #endif // HK_UTILITIES2_CONSTRAINT_VIEWER_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, 77 ] ] ]
1ba4a44147ca68a9cbaaabb37f54974c70d1f255
acf0e8a6d8589532d5585b28ec61b44b722bf213
/mod_eval_panfilter/component_value_transl.cpp
49d0605351bdb11538f21279197cf89a0754a9d7
[]
no_license
mchouza/ngpd
0f0e987a95db874b3cde4146364bf1d69cf677cb
5cca5726910bfc97844689f1f40c94b27e0fb9f9
refs/heads/master
2016-09-06T02:09:32.007855
2008-04-06T14:17:55
2008-04-06T14:17:55
35,064,755
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,850
cpp
// // Copyright (c) 2008, Mariano M. Chouza // 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. // // * The names of the contributors may not be used to endorse or promote // products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // //============================================================================= // component_value_transl.cpp //----------------------------------------------------------------------------- // Creado por Mariano M. Chouza | Agregado a NGPD el 6 de abril de 2008 //============================================================================= #include "component_value_transl.h" #include <cmath> using std::pow; /// Namespace anรณnimo para ocultar las tablas namespace { // Todas las tablas estรกn basadas en las del estรกndar IEC 606063. // Ver mรกs informaciรณn en http://en.wikipedia.org/wiki/Preferred_number. /// Tabla de valores de la serie de 5 % (E24) int fivePercentTable[] = { 100, 110, 120, 130, 150, 160, 180, 200, 220, 240, 270, 300, 330, 360, 390, 430, 470, 510, 560, 620, 680, 750, 820, 910 }; } ComponentValueTransl::ComponentValueTransl(int tolerance) { // Se fija si es uno de los valores permitidos switch (tolerance) { case 50: // La tabla es la del 5 % table_ = fivePercentTable; valuesPerDec_ = sizeof(fivePercentTable) / sizeof(int); break; default: // No es una tolerancia vรกlida // FIXME: lanzar algo apropiado throw; } // En todos los casos vรกlidos guardo el valor de la tolerancia tolerance_ = tolerance; // En todos los casos tengo 12 dรฉcadas // R: 0.1 - 1 - 10 - 100 - 1k - 10k - 100k - 1M - 100M - 1G - 10G - 100G // C/L: 0.1p - 1p - 10p - 100p - 1n - 10n - 100n - 1u - 10u - 100u - 1m - // 10m - 100m cantDec_ = 12; } double ComponentValueTransl::GetComponentValue(unsigned index) const { // Primero escalo el nรบmero al rango apropiado index %= (cantDec_ * valuesPerDec_); // Obtengo la dรฉcada y el offset adentro de ella int dec = index / valuesPerDec_; int offset = index % valuesPerDec_; // Obtengo el multiplicador representando a las dรฉcadas double mult = pow(10.0, dec); // Obtengo el valor correspondiente de la tabla double offsetValue = table_[offset] / 1000.0; // Devuelvo el resultado (asume que es una resistencia, // sino debe escalarse) return offsetValue * mult; } int ComponentValueTransl::GetMaxIndex() const { // FIXME: Hacer que funcione return -1; }
[ "mchouza@b858013c-4649-0410-a850-dde43e08a396" ]
[ [ [ 1, 108 ] ] ]
ba0ee9e87e6f291f9ee16272a550108eae11e021
7d5bde00c1d3f3e03a0f35ed895068f0451849b2
/mainwindow.h
135f3c2cd0a4e728f23f70cebcf43bfa9cd47da4
[]
no_license
jkackley/jeremykackley-dfjobs-improvment
6638af16515d140e9d68c7872b11b47d4f6d7587
73f53a26daa7f66143f35956150c8fe2b922c2e2
refs/heads/master
2021-01-16T01:01:38.642050
2011-05-16T18:03:23
2011-05-16T18:03:23
32,128,889
0
0
null
null
null
null
UTF-8
C++
false
false
2,082
h
/*- * Copyright (c) 2011, Derek Young * 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 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QString> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); public slots: void saveAs(); void save(); void exit(); void open(); void statusClicked(); void configClicked(); void logClicked(); void tickClicked(); void tick(); void updateStatus(QString); void processingDone(); void showPopup(QString, bool); signals: void activate(int); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
[ "Devek@localhost" ]
[ [ [ 1, 67 ] ] ]
a009e1e52bb853f3602e394db07151d14b29116d
dae66863ac441ab98adbd2d6dc2cabece7ba90be
/examples/flexscan/ASWorkFlexScan.h
be92c875f1020fa34e8f1fb11a03e44a1699b803
[]
no_license
bitcrystal/flexcppbridge
2485e360f47f8d8d124e1d7af5237f7e30dd1980
474c17cfa271a9d260be6afb2496785e69e72ead
refs/heads/master
2021-01-10T14:14:30.928229
2008-11-11T06:11:34
2008-11-11T06:11:34
48,993,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,101
h
/* * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Flex C++ Bridge. * * The Initial Developer of the Original Code is * Anirudh Sasikumar (http://anirudhs.chaosnet.org/). * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): * */ #pragma once #include "aswork.h" class CASWorkFlexScan : public CASWork { protected: virtual void Worker(); public: void* m_pTwain; CASWorkFlexScan(void); CASWorkFlexScan(void* pTwain); virtual ~CASWorkFlexScan(void); virtual CASWork* Clone(); };
[ "anirudhsasikumar@1c1c0844-4f48-0410-9872-0bebc774e022" ]
[ [ [ 1, 39 ] ] ]
6d229488142db9a90b7223c5ae8cad8371bfba92
4c3c35e4fe1ff2567ef20f0b203fe101a4a2bf20
/teamProject/src/main.cpp
36764925d5cd32e6c20c8d922f4b1e140bf94744
[]
no_license
kolebole/monopolocoso
63c0986707728522650bd2704a5491d1da20ecf7
a86c0814f5da2f05e7676b2e41f6858d87077e6a
refs/heads/master
2021-01-19T15:04:09.283953
2011-03-27T23:21:53
2011-03-27T23:21:53
34,309,551
0
0
null
null
null
null
UTF-8
C++
false
false
10,474
cpp
#include <ctime> #include <iostream> #include <set> #include <stdlib.h> #include <cstdio> #include <vector> #ifdef WINDOWS #include <GL/gl.h> #include "glut.h" #else #include <GL/glut.h> #include <GL/glu.h> #endif #include "Octree.h" #include "vec3f.h" #include "Particle.h" using namespace std; //Return a random float from 0 to 1 float randomFloat() { return (float)rand() / ((float)RAND_MAX + 1); } //View params int ox, oy; int buttonState = 0; float camera_trans[] = {0, 0, -25}; float angle = 0.0f; int mode = 0; bool Pause = false; bool wireframe = true; bool HUDshow = false; //The amount of time between each time that we handle collisions and apply the //effects of gravity const float TIME_BETWEEN_UPDATES = 0.01f; const int TIMER_MS = 25; //The number of milliseconds to which the timer is set //Simulation params float timestep = 0.5f; Vec3f GRAVITY(0,-8,0); float iterations = 1; float ballr = 1.0f/64.0f; float collideSpring = 0.5f;; float collideDamping = 0.02f;; float collideShear = 0.1f; float boundaryDamping = -0.5f; bool bruteForce = false; bool gravity = true; //Tree params const int MAX_DEPTH = 3; const Vec3f CENTER = Vec3f(0,0,0); const float HALF_WIDTH = BOX_SIZE/2; //datas vector<Particle*> pList; //all the present particles Node* Octree; float timeUntilUpdate = 0; Vec3f collideSpheres(Vec3f posA, Vec3f posB, Vec3f velA, Vec3f velB, float radiusA, float radiusB) { Vec3f relPos = posB -posA; float dist = relPos.magnitude(); float collideDist = radiusA + radiusB; Vec3f force = Vec3f(0,0,0); if (dist < collideDist) { Vec3f norm = relPos/dist; //relative velocity Vec3f relVel = velB - velA; //relative tangential velocity Vec3f tanVel = relVel - (relVel.dot(norm)*norm); //spring force force = -collideSpring*(collideDist - dist)*norm; //dashpot (damping) force force += collideDamping*relVel; // tangential shear force force += collideShear*tanVel; // printf("force: %f %f %f\n",force[0],force[1],force[2]); } return force; } void handleParticleCollisions(vector<Particle*> &particles, Node* pTree) { stack<ParticleCollision> pCollide; TestParticleCollision(pTree,pCollide,MAX_DEPTH); while(!pCollide.empty()) { Particle* p1 = pCollide.top().p1; Particle* p2 = pCollide.top().p2; Vec3f force = collideSpheres(p1->center, p2->center,p1->v,p2->v,p1->radius,p2->radius); p1->v = p1->v + 100*force*TIME_BETWEEN_UPDATES/p1->radius; p2->v = p2->v - 100*force*TIME_BETWEEN_UPDATES/p2->radius; // Vec3f displacement = (p1->center - p2->center).normalize(); // p1->v -= 2 * displacement * p1->v.dot(displacement)*(1-collideDamping); // p2->v -= 2 * displacement * p2->v.dot(displacement)*(1-collideDamping); pCollide.pop(); } } void handleWallCollisions(vector<Particle*> &particles, Node* pTree) { stack<WallCollision> bwps; TestWallCollision(pTree,bwps); while(!bwps.empty()) { WallCollision wc = bwps.top(); Particle* p = wc.p; Wall w = wc.wall; Vec3f dir = (wallDirection(w)).normalize(); p->v = boundaryDamping*dir*p->v.dot(dir); bwps.pop(); } } //burte force calculating void handleParticleCollisions(vector<Particle*> &particles) { for(vector<Particle*>::iterator a = particles.begin();a != particles.end();a++) { for(vector<Particle*>::iterator b = particles.begin();b != particles.end();b++) { Particle* p1 = *a; Particle* p2 = *b; float dist = (p2->center-p1->center).magnitude(); float rSum = p2->radius + p1->radius; if(rSum < dist) { if(a != b) { Vec3f displacement = (p1->center - p2->center).normalize(); p1->v -= 2 * displacement * p1->v.dot(displacement)*(1-collideDamping); p2->v -= 2 * displacement * p2->v.dot(displacement)*(1-collideDamping); } } } } } void handleWallCollisions(vector<Particle*> &particles) { Wall walls[] = {UP, DOWN, LEFT, RIGHT, NEAR, FAR}; for(vector<Particle*>::iterator a = particles.begin();a != particles.end();a++) { for(int i = 0; i < 6; i++) { if(checkWallCollision(*a, walls[i])) { Particle *p = *a; Vec3f dir = (wallDirection(walls[i])).normalize(); p->v = boundaryDamping*dir*p->v.dot(dir); } } } } void applyGravity(vector<Particle*> &particles) { for(vector<Particle*>::iterator it = particles.begin(); it != particles.end();it++) { Particle* p = *it; p->v = p->v + (TIME_BETWEEN_UPDATES * GRAVITY); } } //Apply gravity and handles collisions void performUpdate(vector<Particle*> &particles, Node* pTree) { if(gravity) applyGravity(particles); if(!bruteForce){ handleParticleCollisions(particles, pTree); handleWallCollisions(particles, pTree); } else { handleParticleCollisions(particles); handleWallCollisions(particles); } } void moveParticles(vector<Particle*> &particles, float dt) { for(vector<Particle*>::iterator it = particles.begin();it != particles.end();it++) { Particle* p = *it; p->center += p->v * dt; } } //Advances the state of the balls by t. timeUntilUpdate is the amount of time //until the next call to performUpdate. void advance(vector<Particle*> &particles, Node* pTree, float t, float &timeUntilUpdate) { while (t > 0) { if (timeUntilUpdate <= t) { moveParticles(particles, timeUntilUpdate); clearObj(pTree,MAX_DEPTH); InsertObject(pTree, particles); performUpdate(particles,pTree); t -= timeUntilUpdate; timeUntilUpdate = TIME_BETWEEN_UPDATES; } else { moveParticles(particles, t); timeUntilUpdate -= t; t = 0; } } } void cleanup() { pList.clear(); delete Octree; } void handleKeypress(unsigned char key, int x, int y) { switch(key){ case 27: //Escape key cleanup(); exit(0); case ' ': //space bar, add 20 balls with random position, velocity, radius and color for(int i = 0; i < 200; i++) { Particle* p = new Particle; p->center = Vec3f(8 * randomFloat() - 4, 8 * randomFloat() - 4, 8 * randomFloat() - 4); p->v = Vec3f(8 * randomFloat() - 4, 8 * randomFloat() - 4, 8 * randomFloat() - 4); // p->radius = 1.0f * randomFloat() + 0.1f; p->radius = 0.5f; p->color = Vec3f(0.6f * randomFloat() + 0.2f, 0.6f * randomFloat() + 0.2f, 0.6f * randomFloat() + 0.2f); pList.push_back(p); Object* obj = new Object; obj->particle = p; InsertObject(Octree,obj); } break; case 'g': gravity = !gravity; break; case 'w': wireframe = !wireframe; break; } } void initRendering() { glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_NORMALIZE); glEnable(GL_COLOR_MATERIAL); } void handleResize(int w, int h) { glViewport(0,0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0,(double)w / (double)h,1.0,200.0); } void drawScene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //translate the camera to gain full view of the scene glTranslatef(camera_trans[0],camera_trans[1],camera_trans[2]); glRotatef(-angle, 0.0f,1.0f,0.0f); //Light sources GLfloat ambientColor[] = {0.5f, 0.5f, 0.5f, 1.0f}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor); GLfloat lightColor[] = {0.7f, 0.7f, 0.7f, 1.0f}; GLfloat lightPos[] = {1.0f, 0.2f, 0.0f, 0.0f}; glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor); glLightfv(GL_LIGHT0, GL_POSITION, lightPos); //Draw the bounding box if(wireframe) glutWireCube(BOX_SIZE); //Draw the particles for(vector<Particle*>::iterator it = pList.begin(); it != pList.end();it++) { Particle* p = *it; glPushMatrix(); glTranslatef(p->center[0],p->center[1],p->center[2]); glColor3f(p->color[0],p->color[1],p->color[2]); glutSolidSphere(p->radius,12,12); glPopMatrix(); } glutSwapBuffers(); } void update(int value) { advance(pList, Octree, (float)TIMER_MS / 1000.0f, timeUntilUpdate); angle += (float)TIMER_MS / 100; if (angle > 360) { angle -= 360; } glutPostRedisplay(); glutTimerFunc(TIMER_MS, update, 0); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); //Set the window size //Create the window glutCreateWindow("Team project - collisions"); initRendering(); //Initialize rendering Octree = BuildOctree(CENTER,HALF_WIDTH,MAX_DEPTH); glutWireCube(BOX_SIZE); //Set handler functions for drawing, keypresses, and window resizes glutDisplayFunc(drawScene); glutKeyboardFunc(handleKeypress); glutReshapeFunc(handleResize); glutTimerFunc(TIMER_MS, update, 0); glutMainLoop(); //Start the main loop. glutMainLoop doesn't return. return 0; }
[ "[email protected]@a7811d78-34aa-4512-2aaf-9c23cbf1bc95" ]
[ [ [ 1, 383 ] ] ]
093324b92bb16af2d89cf6f739d5267873bd776b
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/sun/src/InstanceScripts/Instance_TheShatteredHalls.cpp
59e16ce4ff46893a62b2e291a67e8425b69ba81f
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
73,430
cpp
/* * Moon++ Scripts for Ascent MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/> * * 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 * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Base.h" #include "StdAfx.h" #include "Setup.h" /************************************************************************/ /* Instance_TheShatteredHalls.cpp Script */ /************************************************************************/ // Fel Orc ConvertAI #define CN_FEL_ORC_CONVERT 17083 #define HEMORRHAGE 30478 class FELORCCONVERTAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(FELORCCONVERTAI); SP_AI_Spell spells[1]; bool m_spellcheck[1]; FELORCCONVERTAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(HEMORRHAGE); spells[0].targettype = TARGET_ATTACKING; spells[0].instant = true; spells[0].cooldown = 25; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shattered Hand HeathenAI #define CN_SHATTERED_HAND_HEATHEN 17420 #define BLOODTHIRST 30474 // 30475 #define ENRAGE_HEATHEN 30485 // those should be correct, but still not sure class SHATTEREDHANDHEATHENAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHATTEREDHANDHEATHENAI); SP_AI_Spell spells[2]; bool m_spellcheck[2]; SHATTEREDHANDHEATHENAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 2; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(BLOODTHIRST); spells[0].targettype = TARGET_ATTACKING; spells[0].instant = true; spells[0].cooldown = 25; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(ENRAGE_HEATHEN); spells[1].targettype = TARGET_SELF; spells[1].instant = true; spells[1].cooldown = 70; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); _unit->CastSpell(_unit, spells[1].info, spells[1].instant); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shattered Hand LegionnaireAI #define CN_SHATTERED_HAND_LEGIONNAIRE 16700 #define AURA_OF_DISCIPLINE 30472 #define PUMMEL 15615 // should be all good (Idk if those are all spells [summon/spawn spell?]) #define ENRAGE 30485 class SHATTEREDHANDLEGIONNAIREAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHATTEREDHANDLEGIONNAIREAI); SP_AI_Spell spells[3]; bool m_spellcheck[3]; SHATTEREDHANDLEGIONNAIREAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 3; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(AURA_OF_DISCIPLINE); spells[0].targettype = TARGET_VARIOUS; spells[0].instant = true; spells[0].cooldown = -1; // no idea if this should be like that spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(PUMMEL); spells[1].targettype = TARGET_ATTACKING; spells[1].instant = true; spells[1].cooldown = 25; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; spells[2].info = dbcSpell.LookupEntry(ENRAGE); spells[2].targettype = TARGET_SELF; spells[2].instant = true; spells[2].cooldown = 70; spells[2].perctrigger = 0.0f; spells[2].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); _unit->CastSpell(_unit, spells[0].info, spells[0].instant); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shattered Hand SavageAI #define CN_SHATTERED_HAND_SAVAGE 16523 #define SLICE_AND_DICE 30470 #define ENRAGE_SAVAGE 30485 #define DEATHBLOW 36023 class SHATTEREDHANDSAVAGEAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHATTEREDHANDSAVAGEAI); SP_AI_Spell spells[3]; bool m_spellcheck[3]; SHATTEREDHANDSAVAGEAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 3; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(SLICE_AND_DICE); spells[0].targettype = TARGET_SELF; spells[0].instant = true; spells[0].cooldown = 35; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(ENRAGE_SAVAGE); spells[1].targettype = TARGET_SELF; spells[1].instant = true; spells[1].cooldown = 70; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; spells[2].info = dbcSpell.LookupEntry(DEATHBLOW); spells[2].targettype = TARGET_ATTACKING; spells[2].instant = true; spells[2].cooldown = 25; spells[2].perctrigger = 0.0f; spells[2].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); _unit->CastSpell(_unit, spells[1].info, spells[1].instant); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shadowmoon AcolyteAI #define CN_SHADOWMOON_ACOLYTE 16594 #define HEAL 31730 // 32130, 31730, 39378, 31739 // is this really used? #define POWER_WORD_SHIELD 35944 // 41373, 29408, 36052, 35944, 32595 #define MIND_BLAST 31516 //26048 //38259 // ofc not sure (and this one can be really overpowered) #define RESIST_SHADOW 30479 // not sure to those both //#define PRAYER_OF_HEALING 15585 // crashes server //#define 105 resist shadow buff? // Self Visual - Sleep Until Cancelled (DND) 16093 ? class SHADOWMOONACOLYTEAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHADOWMOONACOLYTEAI); SP_AI_Spell spells[4]; bool m_spellcheck[4]; SHADOWMOONACOLYTEAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 4; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(HEAL); spells[0].targettype = TARGET_SELF; spells[0].instant = false; spells[0].cooldown = 35; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(POWER_WORD_SHIELD); spells[1].targettype = TARGET_SELF; spells[1].instant = true; spells[1].cooldown = 45; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; spells[2].info = dbcSpell.LookupEntry(MIND_BLAST); spells[2].targettype = TARGET_ATTACKING; spells[2].instant = false; spells[2].cooldown = 10; spells[2].perctrigger = 0.0f; spells[2].attackstoptimer = 1000; spells[3].info = dbcSpell.LookupEntry(RESIST_SHADOW); spells[3].targettype = TARGET_SELF; // should be ally spells[3].instant = true; spells[3].cooldown = 65; spells[3].perctrigger = 0.0f; spells[3].attackstoptimer = 1000; /* spells[4].info = dbcSpell.LookupEntry(PRAYER_OF_HEALING); spells[4].targettype = TARGET_VARIOUS; spells[4].instant = false; spells[4].cooldown = 15; spells[4].perctrigger = 0.0f; spells[4].attackstoptimer = 1000; */ } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); if (RandomUInt(4) == 1) _unit->CastSpell(_unit, spells[3].info, spells[3].instant); else spells[3].casttime = RandomUInt(20)+10; } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shattered Hand AssassinAI #define CN_SHATTERED_HAND_ASSASSIN 17695 // [*] #define SAP 30980 #define STEALTH 30991 // 32615, 30831, 30991, 31526, 31621, 34189, 32199 // I think should be harder to detect #define CHEAP_SHOT 30986 class SHATTEREDHANDASSASSINAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHATTEREDHANDASSASSINAI); SP_AI_Spell spells[3]; bool m_spellcheck[3]; SHATTEREDHANDASSASSINAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 3; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(SAP); spells[0].targettype = TARGET_ATTACKING; spells[0].instant = true; spells[0].cooldown = -1; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(STEALTH); spells[1].targettype = TARGET_SELF; spells[1].instant = true; spells[1].cooldown = -1; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; spells[2].info = dbcSpell.LookupEntry(CHEAP_SHOT); spells[2].targettype = TARGET_ATTACKING; spells[2].instant = true; spells[2].cooldown = 25; spells[2].perctrigger = 0.0f; spells[2].attackstoptimer = 1000; _unit->CastSpell(_unit, spells[1].info, spells[1].instant); } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); if (_unit->GetCurrentSpell() && mTarget) _unit->CastSpell(mTarget, spells[0].info, spells[0].instant); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->CastSpell(_unit, spells[1].info, spells[1].instant); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shadowmoon Darkcaster AI #define CN_SHADOWMOON_DARKCASTER 17694 #define RAIN_OF_FIRE 37279 // DBC: 11990; 37279, 39376, 36808, 34360, 33617 #define FEAR 12542 //38154 // 38595, 38660, 39119, 39210, 39415, 38154, 34259, 33924, 31358, 30615 #define SHADOW_BOLT 12471 // not sure class SHADOWMOONDARKCASTERAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHADOWMOONDARKCASTERAI); SP_AI_Spell spells[3]; bool m_spellcheck[3]; SHADOWMOONDARKCASTERAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 3; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(RAIN_OF_FIRE); spells[0].targettype = TARGET_DESTINATION; spells[0].instant = true; spells[0].cooldown = 20; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(FEAR); spells[1].targettype = TARGET_ATTACKING; spells[1].instant = false; spells[1].cooldown = 35; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; spells[2].info = dbcSpell.LookupEntry(SHADOW_BOLT); spells[2].targettype = TARGET_ATTACKING; spells[2].instant = false; spells[2].cooldown = 10; spells[2].perctrigger = 0.0f; spells[2].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shattered Hand Gladiator AI #define CN_SHATTERED_HAND_GLADIATOR 17464 // [*] #define MORTAL_STRIKE 31911 // 31911, 29572, 32736, 35054, 39171, 37335 // sth more? class SHATTEREDHANDGLADIATORAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHATTEREDHANDGLADIATORAI); SP_AI_Spell spells[1]; bool m_spellcheck[1]; SHATTEREDHANDGLADIATORAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(MORTAL_STRIKE); spells[0].targettype = TARGET_ATTACKING; spells[0].instant = true; spells[0].cooldown = 15; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shattered Hand Houndmaster AI #define CN_SHATTERED_HAND_HOUNDMASTER 17670 // [*] #define VOLLEY 34100 // 34100, 35950, 30933, 22908 // he patrols with Rabid Warhounds class SHATTEREDHANDHOUNDMASTERAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHATTEREDHANDHOUNDMASTERAI); SP_AI_Spell spells[1]; bool m_spellcheck[1]; SHATTEREDHANDHOUNDMASTERAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(VOLLEY); spells[0].targettype = TARGET_DESTINATION; spells[0].instant = false; spells[0].cooldown = 30; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shattered Hand Reaver AI #define CN_SHATTERED_HAND_REAVER 16699 #define CLEAVE_REAVER 15754 //34995 // no idea if this is good id #define UPPERCUT 30471 // 32055, 34014, 34996, 39069, 41388, 30471 #define ENRAGE 30485 // 34624, 37023, 37648, 38046, 41305, 34670, 34970, 34971, 36992, 38947, 41447 and many others =/ class SHATTEREDHANDREAVERAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHATTEREDHANDREAVERAI); SP_AI_Spell spells[3]; bool m_spellcheck[3]; SHATTEREDHANDREAVERAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 3; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(CLEAVE_REAVER); spells[0].targettype = TARGET_VARIOUS; spells[0].instant = true; spells[0].cooldown = 10; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(UPPERCUT); spells[1].targettype = TARGET_ATTACKING; spells[1].instant = true; spells[1].cooldown = 35; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; spells[2].info = dbcSpell.LookupEntry(ENRAGE); spells[2].targettype = TARGET_SELF; spells[2].instant = true; spells[2].cooldown = 70; spells[2].perctrigger = 0.0f; spells[2].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); if (RandomUInt(4) == 1) _unit->CastSpell(_unit, spells[2].info, spells[2].instant); else spells[2].casttime = RandomUInt(30)+20; } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shattered Hand Sentry AI #define CN_SHATTERED_HAND_SENTRY 16507 #define CHARGE 22911 // 35570 many others #define HAMSTERING 31553 // not sure if it uses it class SHATTEREDHANDSENTRYAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHATTEREDHANDSENTRYAI); SP_AI_Spell spells[2]; bool m_spellcheck[2]; SHATTEREDHANDSENTRYAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(HAMSTERING); spells[0].targettype = TARGET_ATTACKING; spells[0].instant = true; spells[0].cooldown = 20; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(CHARGE); spells[1].targettype = TARGET_ATTACKING; spells[1].instant = true; spells[1].cooldown = -1; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { if (_unit->GetAIInterface()->GetNextTarget() && _unit->GetCurrentSpell()) { Unit *target = NULL; target = _unit->GetAIInterface()->GetNextTarget(); if (_unit->GetDistance2dSq(target) > 225.0f && RandomUInt(4) == 1) { _unit->CastSpell(target, spells[1].info, spells[1].instant); return; } } float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Shattered Hand Sharpshooter AI #define CN_SHATTERED_HAND_SHARPSHOOTER 16704 #define SCATTER_SHOT 23601 // 36732 // not sure #define IMMOLATION_ARROW 35932 // same here (Idk if it uses it for sure) #define SHOT 15620 // must find way to force mob to cast this only when dist > xx #define INCENDIARY_SHOT 30481 // not sure to these class SHATTEREDHANDSHARPSHOOTERAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHATTEREDHANDSHARPSHOOTERAI); SP_AI_Spell spells[4]; bool m_spellcheck[4]; SHATTEREDHANDSHARPSHOOTERAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 4; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(SCATTER_SHOT); spells[0].targettype = TARGET_ATTACKING; spells[0].instant = true; spells[0].cooldown = 20; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(IMMOLATION_ARROW); spells[1].targettype = TARGET_ATTACKING; // no idea why fire stays under caster instead of target spells[1].instant = false; spells[1].cooldown = 5; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; spells[2].info = dbcSpell.LookupEntry(SHOT); // disabled for now spells[2].targettype = TARGET_ATTACKING; spells[2].instant = true; spells[2].cooldown = -1; spells[2].perctrigger = 0.0f; spells[2].attackstoptimer = 1000; spells[3].info = dbcSpell.LookupEntry(INCENDIARY_SHOT); spells[3].targettype = TARGET_ATTACKING; spells[3].instant = false; spells[3].cooldown = 35; spells[3].perctrigger = 0.0f; spells[3].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); } void OnCombatStop(Unit *mTarget) { _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { RemoveAIUpdateEvent(); } void AIUpdate() { _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); if (_unit->GetAIInterface()->GetNextTarget() && _unit->GetDistance2dSq(_unit->GetAIInterface()->GetNextTarget()) <= 900.0f) { _unit->GetAIInterface()->setCurrentAgent(AGENT_SPELL); if (_unit->GetCurrentSpell() == NULL) { uint32 Chance = RandomUInt(100); if (Chance <= 70) { _unit->CastSpell(_unit->GetAIInterface()->GetNextTarget(), spells[2].info, spells[2].instant); } else if (Chance > 70 && Chance <= 78) { _unit->CastSpell(_unit->GetAIInterface()->GetNextTarget(), spells[1].info, spells[1].instant); } else if (Chance > 78 && Chance <= 82) { _unit->CastSpell(_unit->GetAIInterface()->GetNextTarget(), spells[3].info, spells[3].instant); } else if (Chance > 82 && Chance <= 86) { _unit->CastSpell(_unit->GetAIInterface()->GetNextTarget(), spells[0].info, spells[0].instant); } } } } protected: int nrspells; }; // Shattered Hand Brawler AI #define CN_SHATTERED_HAND_BRAWLER 16593 #define CURSE_OF_THE_SHATTERED_HAND 36020 //36020 #define KICK 36033 // no idea about these spells #define TRASH 3391 // W00T? doesn't work (maybe lack of core support?) // Self Visual - Sleep Until Cancelled (DND) 16093 ? class SHATTEREDHANDBRAWLERAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(SHATTEREDHANDBRAWLERAI); SP_AI_Spell spells[3]; bool m_spellcheck[3]; SHATTEREDHANDBRAWLERAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 3; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(CURSE_OF_THE_SHATTERED_HAND); spells[0].targettype = TARGET_ATTACKING; spells[0].instant = true; spells[0].cooldown = 35; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(KICK); spells[1].targettype = TARGET_ATTACKING; spells[1].instant = true; spells[1].cooldown = 25; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; spells[2].info = dbcSpell.LookupEntry(TRASH); spells[2].targettype = TARGET_SELF; spells[2].instant = true; spells[2].cooldown = 20; spells[2].perctrigger = 0.0f; spells[2].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = spells[i].cooldown; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { spells[i].casttime--; if (m_spellcheck[i]) { spells[i].casttime = spells[i].cooldown; target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } if (spells[i].speech != "") { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str()); _unit->PlaySoundToSet(spells[i].soundid); } m_spellcheck[i] = false; return; } if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; /*****************************/ /* */ /* Boss AIs */ /* */ /*****************************/ //---------------- Grand Warlock Nethekurse Encounter ----------------// struct Coords Darkcasters[]= { { 160.563004f, 272.989014f, -13.189000f }, { 176.201004f, 264.669006f, -13.141600f }, { 194.951004f, 265.657990f, -13.181700f } }; // Shadowmoon Darkcaster AI #define CN_SHADOWMOON_DARKCASTER 17694 class ShadowmoonDarkcasterAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(ShadowmoonDarkcasterAI); ShadowmoonDarkcasterAI(Creature* pCreature) : CreatureAIScript(pCreature) { Unit *GrandWarlock = NULL; GrandWarlock = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(178.811996f, 292.377991f, -8.190210f, 16807); if (GrandWarlock) { GrandWarlock->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_9); GrandWarlock->GetAIInterface()->SetAllowedToEnterCombat(false); } } void OnCombatStart(Unit* mTarget) { Unit *GrandWarlock = NULL; GrandWarlock = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(178.811996f, 292.377991f, -8.190210f, 16807); if (GrandWarlock) { int RandomSpeach = rand()%4; switch (RandomSpeach) // must be verified + emotes? { case 0: GrandWarlock->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You can have that one. I no longer need him."); GrandWarlock->PlaySoundToSet(10263); break; case 1: GrandWarlock->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Yes! Beat him mercilessly!"); // to add GrandWarlock->PlaySoundToSet(10264); break; case 2: GrandWarlock->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Don't waste your time on that one. He's weak."); GrandWarlock->PlaySoundToSet(10265); break; case 3: GrandWarlock->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You want him? Farewell, take him."); GrandWarlock->PlaySoundToSet(10266); break; } } } void OnCombatStop(Unit *mTarget) { _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); } void OnDied(Unit * mKiller) { Creature *GrandWarlock = NULL; GrandWarlock = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(178.811996f, 292.377991f, -8.190210f, 16807); if (GrandWarlock) // any emotes needed? { uint32 Counter = 0; for (int i = 0; i < 3; i++) { Unit *Servant = NULL; Servant = _unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(Darkcasters[i].mX, Darkcasters[i].mY, Darkcasters[i].mZ, 17694); if (!Servant) continue; if (!Servant->isAlive()) continue; Counter++; } if (Counter == 0) { GrandWarlock->GetAIInterface()->HandleEvent(EVENT_ENTERCOMBAT, GrandWarlock, 0); } int RandomSpeach = rand()%3; switch (RandomSpeach) // those need to be verified too { case 0: GrandWarlock->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "One pitiful wretch down. Go on, take another one."); GrandWarlock->PlaySoundToSet(10267); break; case 1: GrandWarlock->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Ah, what a waste. Next!"); GrandWarlock->PlaySoundToSet(10268); break; case 2: GrandWarlock->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I was going to kill him anyway."); GrandWarlock->PlaySoundToSet(10269); break; } } } }; // Grand Warlock NethekurseAI #define CN_GRAND_WARLOCK_NETHEKURSE 16807 #define DEATH_COIL 30500 // 30741 or 30500; not sure if this is right id and if it's working like it should #define DARK_SPIN 30502 // this should be correct // doesn't work because of lack of core support? (so can't check) #define LESSER_SHADOW_FISSURE 30496 // can be: 36147, 30496, 30744 // doesn't work, coz lack of core support for summons // It has much more sounds (like for servant dies etc.). // For future makes researches on them. class GrandWarlockNethekurseAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(GrandWarlockNethekurseAI); SP_AI_Spell spells[3]; bool m_spellcheck[3]; GrandWarlockNethekurseAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(DEATH_COIL); spells[0].targettype = TARGET_RANDOM_SINGLE; spells[0].instant = true; spells[0].cooldown = 15; spells[0].perctrigger = 10.0f; spells[0].attackstoptimer = 1000; spells[0].mindist2cast = 0.0f; spells[0].maxdist2cast = 40.0f; // disabled for now spells[1].info = dbcSpell.LookupEntry(LESSER_SHADOW_FISSURE); spells[1].targettype = TARGET_RANDOM_SINGLE; spells[1].instant = true; // doesn't work, because of lack of core support (so to prevent channeling I changed false to true) spells[1].cooldown = 25; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; spells[1].mindist2cast = 0.0f; spells[1].maxdist2cast = 40.0f; spells[2].info = dbcSpell.LookupEntry(DARK_SPIN); spells[2].targettype = TARGET_VARIOUS; spells[2].instant = false; spells[2].cooldown = 60; spells[2].perctrigger = 0.0f; spells[2].attackstoptimer = 1000; Started = false; } void OnCombatStart(Unit* mTarget) { for (int i=0; i<3; i++) spells[i].casttime = 0; if (Started) { int RandomSpeach = rand()%3; switch (RandomSpeach) { case 0: _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I'm already bored!"); _unit->PlaySoundToSet(10271); break; case 1: _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Come on! Show me a real fight!"); _unit->PlaySoundToSet(10272); break; case 2: _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I had more fun torturing the peons!"); _unit->PlaySoundToSet(10273); break; } RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); } else RegisterAIUpdateEvent(4000); } void OnTargetDied(Unit* mTarget) { if (_unit->GetHealthPct() > 0) // Hack to prevent double yelling (OnDied and OnTargetDied when creature is dying) { int RandomSpeach = rand()%2; switch (RandomSpeach) { case 0: _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You loose!"); _unit->PlaySoundToSet(10274); break; case 1: _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Oh, just die!"); _unit->PlaySoundToSet(10275); break; } } } void OnCombatStop(Unit *mTarget) { _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); if (Started) RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "What a... shame."); _unit->PlaySoundToSet(10276); RemoveAIUpdateEvent(); } void AIUpdate() { if (!Started) { _unit->GetAIInterface()->SetAllowedToEnterCombat(true); _unit->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0); _unit->SetUInt64Value(UNIT_FIELD_FLAGS, 0); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); Started = true; Unit *target = NULL; target = FindTarget(); if (target) { _unit->GetAIInterface()->AttackReaction(target, 1, 0); } } if (_unit->FindAura(DARK_SPIN)) { _unit->setAttackTimer(2500, false); return; } uint32 t = (uint32)time(NULL); // not sure if this should work like that if (t > spells[2].casttime && _unit->GetHealthPct() <= 20 && _unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { _unit->setAttackTimer(2500, false); _unit->CastSpell(_unit, spells[2].info, spells[2].instant); spells[2].casttime = t + 120; return; } else { float val = (float)RandomFloat(100.0f); SpellCast(val); } } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: case TARGET_RANDOM_DESTINATION: CastSpellOnRandomTarget(i, spells[i].mindist2cast, spells[i].maxdist2cast, spells[i].minhp2cast, spells[i].maxhp2cast); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast, int minhp2cast, int maxhp2cast) { if (!maxdist2cast) maxdist2cast = 100.0f; if (!maxhp2cast) maxhp2cast = 100; if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */ /* If anyone wants to use this function, then leave this note! */ for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr) { if (((spells[i].targettype == TARGET_RANDOM_FRIEND && isFriendly(_unit, (*itr))) || (spells[i].targettype != TARGET_RANDOM_FRIEND && isHostile(_unit, (*itr)) && (*itr) != _unit)) && ((*itr)->GetTypeId()== TYPEID_UNIT || (*itr)->GetTypeId() == TYPEID_PLAYER) && (*itr)->GetInstanceID() == _unit->GetInstanceID()) // isAttackable(_unit, (*itr)) && { Unit* RandomTarget = NULL; RandomTarget = (Unit*)(*itr); if (RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast*mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast*maxdist2cast && ((RandomTarget->GetHealthPct() >= minhp2cast && RandomTarget->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) || (_unit->GetAIInterface()->getThreatByPtr(RandomTarget) > 0 && isHostile(_unit, RandomTarget)))) { TargetTable.push_back(RandomTarget); } } } if (_unit->GetHealthPct() >= minhp2cast && _unit->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) TargetTable.push_back(_unit); if (!TargetTable.size()) return; size_t RandTarget = rand()%TargetTable.size(); Unit * RTarget = TargetTable[RandTarget]; if (!RTarget) return; switch (spells[i].targettype) { case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: _unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break; case TARGET_RANDOM_DESTINATION: _unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break; } TargetTable.clear(); } } // A bit rewritten FindTarget function Unit* FindTarget() { Unit* target = NULL; float distance = 50.0f; Unit *pUnit; float dist; for (std::set<Object*>::iterator itr = _unit->GetInRangeOppFactsSetBegin(); itr != _unit->GetInRangeOppFactsSetEnd(); itr++) { if((*itr)->GetTypeId() != TYPEID_UNIT && (*itr)->GetTypeId() != TYPEID_PLAYER) continue; pUnit = static_cast<Unit*>((*itr)); if(pUnit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FEIGN_DEATH)) continue; if(pUnit->m_invisible) continue; if(!pUnit->isAlive() || _unit == pUnit) continue; dist = _unit->GetDistance2dSq(pUnit); if(dist > distance*distance) continue; target = pUnit; break; } return target; } protected: bool Started; int nrspells; }; // Blood Guard PorungAI #define CN_BLOOD_GUARD_PORUNG 20923 #define CLEAVE 37476 // right description, but no idea if this is right spell //#define FEAR <-- disabled in 2.1 // Note: This boss appears only in Heroic mode and I don't have much infos about it =/ class BloodGuardPorungAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(BloodGuardPorungAI); SP_AI_Spell spells[1]; bool m_spellcheck[1]; BloodGuardPorungAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(CLEAVE); spells[0].targettype = TARGET_VARIOUS; spells[0].instant = true; spells[0].cooldown = 15; spells[0].perctrigger = 10.0f; spells[0].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); } void CastTime() { for(int i=0;i<nrspells;i++) spells[i].casttime = 0; } void OnCombatStop(Unit *mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = (float)RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget()) { float comulativeperc = 0; Unit *target = NULL; for(int i=0;i<nrspells;i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->GetNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } protected: int nrspells; }; // Maybe timer for 'afterspeech' should be added too? #define CN_WARBRINGER_OMROGG 16809 #define WARBRINGER_OMROGG_THUNDERCLAP 30633 #define WARBRINGER_OMROGG_FEAR 30584 #define WARBRINGER_OMROGG_BURNING_MAUL 30598 // 30598 or 30599 #define WARBRINGER_OMROGG_BLAST_WAVE 30600 #define CN_LEFT_HEAD 19523 #define CN_RIGHT_HEAD 19524 void SpellFunc_Warbringer_BurningMaul(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType); class WarbringerOmroggAI : public MoonScriptCreatureAI { public: MOONSCRIPT_FACTORY_FUNCTION( WarbringerOmroggAI, MoonScriptCreatureAI ); WarbringerOmroggAI( Creature *pCreature ) : MoonScriptCreatureAI( pCreature ) { AddSpell( WARBRINGER_OMROGG_THUNDERCLAP, Target_Self, 25, 1, 12 ); AddSpell( WARBRINGER_OMROGG_FEAR, Target_Self, 7, 0, 20 ); AddSpellFunc( &SpellFunc_Warbringer_BurningMaul, Target_Self, 100, 0, 30 ); mBlastWave = AddSpell( WARBRINGER_OMROGG_BLAST_WAVE, Target_Self, 0, 1, 0 ); mBlastWaveTimer = mSpeechTimer = mSpeechId = mAggroShiftTimer = INVALIDATE_TIMER; mRightHead = mLeftHead = NULL; } void OnCombatStart(Unit *pTarget) { ParentClass::OnCombatStart( pTarget ); mAggroShiftTimer = AddTimer( 20000 + RandomUInt( 10 ) * 1000 ); mBlastWaveTimer = mSpeechTimer = mSpeechId = INVALIDATE_TIMER; mLeftHead = SpawnCreature( 19523 ); mRightHead = SpawnCreature( 19524 ); if ( mLeftHead != NULL ) { mLeftHead->GetUnit()->GetAIInterface()->SetUnitToFollow( _unit ); } if ( mRightHead != NULL ) { mRightHead->GetUnit()->GetAIInterface()->SetUnitToFollow( _unit ); } if ( mLeftHead == NULL || mRightHead == NULL ) return; switch( RandomUInt( 2 ) ) { case 0: mLeftHead->Emote( "If you nice me let you live.", Text_Yell, 10308 ); mSpeechTimer = AddTimer( 4000 ); mSpeechId = 1; break; case 1: mLeftHead->Emote( "Me hungry!", Text_Yell, 10309 ); mSpeechTimer = AddTimer( 2500 ); mSpeechId = 2; break; case 2: mLeftHead->Emote( "Smash!", Text_Yell, 10306 ); mSpeechTimer = AddTimer( 2000 ); mSpeechId = 3; break; } } void OnCombatStop(Unit *pTarget) { ParentClass::OnCombatStop( pTarget ); if ( IsAlive() ) { if ( mLeftHead != NULL ) { mLeftHead->Despawn( 1000 ); mLeftHead = NULL; } if ( mRightHead != NULL ) { mRightHead->Despawn( 1000 ); mRightHead = NULL; } } } void OnTargetDied(Unit *pTarget) { if ( mLeftHead == NULL || mRightHead == NULL || mSpeechTimer != INVALIDATE_TIMER ) return; switch ( RandomUInt( 1 ) ) { case 0: mLeftHead->Emote( "I'm tired. You kill the next one!", Text_Yell, 10320 ); break; case 1: mLeftHead->Emote( "This one die easy!", Text_Yell, 10310 ); mSpeechTimer = AddTimer( 3000 ); mSpeechId = 0; break; } } void OnDied(Unit *pKiller) { ParentClass::OnDied( pKiller ); if ( mLeftHead == NULL || mRightHead == NULL ) return; mLeftHead->Emote( "This all... your fault!", Text_Yell, 10311 ); mLeftHead->Despawn( 1000 ); mRightHead->RegisterAIUpdateEvent( 3000 ); mRightHead->Despawn( 4000 ); } void AIUpdate() { ParentClass::AIUpdate(); if ( mSpeechTimer != INVALIDATE_TIMER && IsTimerFinished( mSpeechTimer ) ) { bool ResetSpeech = true; RemoveTimer( mSpeechTimer ); if ( mLeftHead != NULL && mRightHead != NULL ) { switch ( mSpeechId ) { case 0: mRightHead->Emote( "That's because I do all the hard work!", Text_Yell, 10321 ); break; case 1: mRightHead->Emote( "No, we will NOT let you live!", Text_Yell, 10318 ); break; case 2: mRightHead->Emote( "You always hungry. That why we so fat!", Text_Yell, 10319 ); break; case 3: mRightHead->Emote( "Why don't you let me do the talking!", Text_Yell, 10317 ); break; case 4: mRightHead->Emote( "I'm not done yet, idiot!", Text_Yell, 10313 ); break; case 5: mRightHead->Emote( "Bored, he's almost dead!", Text_Yell, 10316 ); break; case 6: mRightHead->Emote( "That's not funny!", Text_Yell, 10314 ); mSpeechTimer = AddTimer( 6000 ); mSpeechId = 8; ResetSpeech = false; break; case 7: mRightHead->Emote( "What are you doing!?", Text_Yell, 10315 ); break; case 8: mLeftHead->Emote( "Ha ha ha!", Text_Yell, 10304 ); break; } } if ( ResetSpeech ) mSpeechId = -1; } else if ( IsTimerFinished( mAggroShiftTimer ) ) { ResetTimer( mAggroShiftTimer, 20000 + RandomUInt( 10 ) * 1000 ); ShiftAggro(); } if ( mBlastWaveTimer != INVALIDATE_TIMER && IsTimerFinished( mBlastWaveTimer ) ) { RemoveTimer( mBlastWaveTimer ); CastSpell( mBlastWave ); } } void ShiftAggro() { Unit *pTarget = GetBestPlayerTarget( TargetFilter_NotCurrent ); if ( pTarget != NULL ) { ClearHateList(); _unit->GetAIInterface()->SetNextTarget( pTarget ); _unit->GetAIInterface()->modThreatByPtr( pTarget, 1000 ); if ( mLeftHead == NULL || mRightHead == NULL || mSpeechTimer != INVALIDATE_TIMER ) return; switch ( RandomUInt( 6 ) ) { case 0: mLeftHead->Emote( "We kill his friend!", Text_Yell, 10301 ); break; case 1: mLeftHead->Emote( "Me not like this one...", Text_Yell, 10300 ); mSpeechTimer = AddTimer( 3000 ); mSpeechId = 4; break; case 2: mRightHead->Emote( "Hey, you numbskull!", Text_Yell, 10312 ); break; case 3: mLeftHead->Emote( "Me get bored.", Text_Yell, 10305 ); mSpeechTimer = AddTimer( 3000 ); mSpeechId = 5; break; case 4: mRightHead->Emote( "What are you doing!?", Text_Yell, 10315 ); break; case 5: mLeftHead->Emote( "You stay here. Me go kill someone else!", Text_Yell, 10303 ); mSpeechTimer = AddTimer( 4000 ); mSpeechId = 6; break; case 6: mLeftHead->Emote( "Me kill someone else!", Text_Yell, 10302 ); mSpeechTimer = AddTimer( 3000 ); mSpeechId = 7; break; } } } MoonScriptCreatureAI* mLeftHead; MoonScriptCreatureAI* mRightHead; int32 mAggroShiftTimer; int32 mBlastWaveTimer; int32 mSpeechTimer; int32 mSpeechId; SpellDesc* mBlastWave; }; void SpellFunc_Warbringer_BurningMaul(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { WarbringerOmroggAI *Warbringer = (pCreatureAI) ? (WarbringerOmroggAI*)pCreatureAI : NULL; if ( Warbringer != NULL ) { Warbringer->CastSpell( Warbringer->mBlastWave ); Warbringer->mBlastWaveTimer = Warbringer->AddTimer( RandomUInt( 5 ) + 5 ); } } class HeadAI : public MoonScriptCreatureAI { MOONSCRIPT_FACTORY_FUNCTION( HeadAI, MoonScriptCreatureAI ); HeadAI( Creature *pCreature ) : MoonScriptCreatureAI( pCreature ) { SetScale( 4.0f ); _unit->SetUInt32Value( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE ); _unit->m_noRespawn = true; } void AIUpdate() { if ( _unit->GetEntry() != CN_RIGHT_HEAD ) return; Emote( "I... hate... you!", Text_Yell, 10322 ); RemoveAIUpdateEvent(); // Dangerous! } void Destroy() { Unit *pUnit = ForceCreatureFind( CN_WARBRINGER_OMROGG ); if ( pUnit != NULL && static_cast< Creature* >( pUnit )->GetScript() != NULL ) { WarbringerOmroggAI *pAI = static_cast< WarbringerOmroggAI* >( static_cast< Creature* >( pUnit )->GetScript() ); if ( pAI->mLeftHead == ( MoonScriptCreatureAI* )( this ) ) pAI->mLeftHead = NULL; if ( pAI->mRightHead == ( MoonScriptCreatureAI* )( this ) ) pAI->mRightHead = NULL; } } }; // Warchief Kargath BladefistAI #define CN_WARCHIEF_KARGATH_BLADEFIST 16808 #define BLADE_DANCE 30739 // should be each 30 sec, but Idk correct attktime // Should call for support? // does he use only one ability? class WarchiefKargathBladefistAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(WarchiefKargathBladefistAI); SP_AI_Spell spells[1]; bool m_spellcheck[1]; WarchiefKargathBladefistAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i=0;i<nrspells;i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(BLADE_DANCE); spells[0].targettype = TARGET_VARIOUS; spells[0].instant = true; spells[0].cooldown = 30; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { int RandomSpeach = rand()%3; switch (RandomSpeach) { case 0: _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Ours is the true horde! The only horde!"); _unit->PlaySoundToSet(10323); break; case 1: _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I'll carve the meat from your bones!"); _unit->PlaySoundToSet(10324); break; case 2: _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I am called Bladefists for a reason... as you will see!"); _unit->PlaySoundToSet(10325); break; } RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME)); spells[0].casttime = (uint32)time(NULL) + 30; } void OnTargetDied(Unit* mTarget) { if (_unit->GetHealthPct() > 0) // Hack to prevent double yelling (OnDied and OnTargetDied when creature is dying) { int RandomSpeach; RandomUInt(1000); RandomSpeach=rand()%2; switch (RandomSpeach) { case 0: _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "For the real horde!"); _unit->PlaySoundToSet(10326); break; case 1: _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I am the only warchief!"); _unit->PlaySoundToSet(10327); break; } } } void OnCombatStop(Unit *mTarget) { _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit * mKiller) { _unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "The true horde... will... prevail!"); _unit->PlaySoundToSet(10328); RemoveAIUpdateEvent(); } void AIUpdate() { uint32 t = (uint32)time(NULL); if (t > spells[0].casttime && _unit->GetAIInterface()->GetNextTarget() && _unit->GetCurrentSpell() == NULL) { _unit->setAttackTimer(1500, false); _unit->CastSpell(_unit->GetAIInterface()->GetNextTarget(), spells[0].info, spells[0].instant); spells[0].casttime = t + spells[0].cooldown; } } protected: int nrspells; }; void SetupTheShatteredHalls(ScriptMgr * mgr) { mgr->register_creature_script(CN_FEL_ORC_CONVERT, &FELORCCONVERTAI::Create); mgr->register_creature_script(CN_SHATTERED_HAND_HEATHEN, &SHATTEREDHANDHEATHENAI::Create); mgr->register_creature_script(CN_SHATTERED_HAND_LEGIONNAIRE, &SHATTEREDHANDLEGIONNAIREAI::Create); mgr->register_creature_script(CN_SHATTERED_HAND_SAVAGE, &SHATTEREDHANDSAVAGEAI::Create); mgr->register_creature_script(CN_SHADOWMOON_ACOLYTE, &SHADOWMOONACOLYTEAI::Create); mgr->register_creature_script(CN_SHATTERED_HAND_ASSASSIN, &SHATTEREDHANDASSASSINAI::Create); mgr->register_creature_script(CN_SHADOWMOON_DARKCASTER, &SHADOWMOONDARKCASTERAI::Create); mgr->register_creature_script(CN_SHATTERED_HAND_GLADIATOR, &SHATTEREDHANDGLADIATORAI::Create); mgr->register_creature_script(CN_SHATTERED_HAND_HOUNDMASTER, &SHATTEREDHANDHOUNDMASTERAI::Create); mgr->register_creature_script(CN_SHATTERED_HAND_REAVER, &SHATTEREDHANDREAVERAI::Create); mgr->register_creature_script(CN_SHATTERED_HAND_SENTRY, &SHATTEREDHANDSENTRYAI::Create); mgr->register_creature_script(CN_SHATTERED_HAND_SHARPSHOOTER, &SHATTEREDHANDSHARPSHOOTERAI::Create); mgr->register_creature_script(CN_SHATTERED_HAND_BRAWLER, &SHATTEREDHANDBRAWLERAI::Create); mgr->register_creature_script(CN_SHADOWMOON_DARKCASTER, &ShadowmoonDarkcasterAI::Create); mgr->register_creature_script(CN_GRAND_WARLOCK_NETHEKURSE, &GrandWarlockNethekurseAI::Create); mgr->register_creature_script(CN_BLOOD_GUARD_PORUNG, &BloodGuardPorungAI::Create); mgr->register_creature_script(CN_WARBRINGER_OMROGG, &WarbringerOmroggAI::Create); mgr->register_creature_script(CN_LEFT_HEAD, &HeadAI::Create); mgr->register_creature_script(CN_RIGHT_HEAD, &HeadAI::Create); mgr->register_creature_script(CN_WARCHIEF_KARGATH_BLADEFIST, &WarchiefKargathBladefistAI::Create); } // TO DO: Shattered Hand Executioner 17301, Shattered Hand Champion 17671, // Shattered Hand Centurion 17465, Shattered Hand Blood Guard 17461, // Shattered Hand Archer 17427, Sharpshooter Guard 17622, Shattered Hand Zealot 17462 // (lack of infos or don't have any spells!) more?
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 2032 ], [ 2034, 2572 ] ], [ [ 2033, 2033 ] ] ]
c07e40a548991e060df7dc99918d96a5929ae27f
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/pcsx2/IopBios.cpp
66fb34db38bebe0f1c26dc5be0d12328a8b81f31
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
14,652
cpp
/* PCSX2 - PS2 Emulator for PCs * Copyright (C) 2002-2010 PCSX2 Dev Team * * PCSX2 is free software: you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Found- * ation, either version 3 of the License, or (at your option) any later version. * * PCSX2 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 PCSX2. * If not, see <http://www.gnu.org/licenses/>. */ #include "PrecompiledHeader.h" #include "IopCommon.h" #include "R5900.h" // for g_GameStarted #include <ctype.h> #include <string.h> #ifndef O_BINARY #define O_BINARY 0 #endif // set this to 0 to disable rewriting 'host:' paths! #define USE_HOST_REWRITE 1 #if USE_HOST_REWRITE # ifdef WIN32 // disable this if you DON'T want "host:/usr/local/" paths // to get rewritten into host:/ # define HOST_REWRITE_USR_LOCAL 1 # else // unix/linux users might want to set it to 1 // if they DO want to keep demos from accessing their systems' /usr/local # define HOST_REWRITE_USR_LOCAL 0 # endif static char HostRoot[1024]; #endif void Hle_SetElfPath(const char* elfFileName) { #if USE_HOST_REWRITE DevCon.WriteLn("HLE Host: Will load ELF: %s\n", elfFileName); const char* pos1 = strrchr(elfFileName,'/'); const char* pos2 = strrchr(elfFileName,'\\'); if(pos2 > pos1) // we want the LAST path separator pos1=pos2; if(!pos1) // if pos1 is NULL, then pos2 was not > pos1, so it must also be NULL { Console.Warning("HLE Warning: ELF does not have a path!!\n"); // use %CD%/host/ getcwd(HostRoot,1000); // save the other 23 chars to append /host/ :P HostRoot[1000]=0; // Be Safe. char* last = HostRoot + strlen(HostRoot) - 1; if((*last!='/') && (*last!='\\')) // PathAppend()-ish last++; strcpy(last,"/host/"); return; } int len = pos1-elfFileName+1; memcpy(HostRoot,elfFileName,len); // include the / (or \\) HostRoot[len] = 0; Console.WriteLn("HLE Host: Set 'host:' root path to: %s\n", HostRoot); #endif } namespace R3000A { #define v0 (psxRegs.GPR.n.v0) #define a0 (psxRegs.GPR.n.a0) #define a1 (psxRegs.GPR.n.a1) #define a2 (psxRegs.GPR.n.a2) #define a3 (psxRegs.GPR.n.a3) #define sp (psxRegs.GPR.n.sp) #define ra (psxRegs.GPR.n.ra) #define pc (psxRegs.pc) #define Ra0 (iopVirtMemR<char>(a0)) #define Ra1 (iopVirtMemR<char>(a1)) #define Ra2 (iopVirtMemR<char>(a2)) #define Ra3 (iopVirtMemR<char>(a3)) // TODO: sandbox option, other permissions class HostFile : public IOManFile { public: int fd; HostFile(int hostfd) { fd = hostfd; } static __fi int translate_error(int err) { if (err >= 0) return err; switch(err) { case -ENOENT: return -IOP_ENOENT; case -EACCES: return -IOP_EACCES; case -EISDIR: return -IOP_EISDIR; case -EIO: default: return -IOP_EIO; } } static int open(IOManFile **file, const char *name, s32 flags, u16 mode) { const char *path = strchr(name, ':') + 1; // host: actually DOES let you write! //if (flags != IOP_O_RDONLY) // return -IOP_EROFS; // WIP code. Works well on win32, not so sure on unixes // TODO: get rid of dependency on CWD/PWD #if USE_HOST_REWRITE // we want filenames to be relative to pcs2dir / host static char pathMod[1024]; // partial "rooting", // it will NOT avoid a path like "../../x" from escaping the pcsx2 folder! #if HOST_REWRITE_USR_LOCAL const char *_local_root = "/usr/local/"; if(strncmp(path,_local_root,strlen(_local_root))==0) { strcpy(pathMod,HostRoot); strcat(pathMod,path+strlen(_local_root)); } else #endif if((path[0] == '/') || (path[0] == '\\') || (isalpha(path[0]) && (path[1] == ':'))) // absolute NATIVE path (X:\blah) { // TODO: allow some way to use native paths in non-windows platforms // maybe hack it so linux prefixes the path with "X:"? ;P // or have all platforms use a common prefix for native paths strcpy(pathMod,path); } else // relative paths { strcpy(pathMod,HostRoot); strcat(pathMod,path); } #else const char* pathMod = path; #endif int native_flags = O_BINARY; // necessary in Windows. switch(flags&IOP_O_RDWR) { case IOP_O_RDONLY: native_flags |= O_RDONLY; break; case IOP_O_WRONLY: native_flags |= O_WRONLY; break; case IOP_O_RDWR: native_flags |= O_RDWR; break; } if(flags&IOP_O_APPEND) native_flags |= O_APPEND; if(flags&IOP_O_CREAT) native_flags |= O_CREAT; if(flags&IOP_O_TRUNC) native_flags |= O_TRUNC; int hostfd = ::open(pathMod, native_flags); if (hostfd < 0) return translate_error(hostfd); *file = new HostFile(hostfd); if (!*file) return -IOP_ENOMEM; return 0; } virtual void close() { ::close(fd); delete this; } virtual int lseek(s32 offset, s32 whence) { int err; switch (whence) { case IOP_SEEK_SET: err = ::lseek(fd, offset, SEEK_SET); break; case IOP_SEEK_CUR: err = ::lseek(fd, offset, SEEK_CUR); break; case IOP_SEEK_END: err = ::lseek(fd, offset, SEEK_END); break; default: return -IOP_EIO; } return translate_error(err); } virtual int read(void *buf, u32 count) { return translate_error(::read(fd, buf, count)); } virtual int write(void *buf, u32 count) { return translate_error(::write(fd, buf, count)); } }; namespace ioman { const int firstfd = 0x100; const int maxfds = 0x100; int openfds = 0; int freefdcount() { return maxfds - openfds; } struct filedesc { enum { FILE_FREE, FILE_FILE, FILE_DIR, } type; union { IOManFile *file; IOManDir *dir; }; operator bool() const { return type != FILE_FREE; } operator IOManFile*() const { return type == FILE_FILE ? file : NULL; } operator IOManDir*() const { return type == FILE_DIR ? dir : NULL; } void operator=(IOManFile *f) { type = FILE_FILE; file = f; openfds++; } void operator=(IOManDir *d) { type = FILE_DIR; dir = d; openfds++; } void close() { if (type == FILE_FREE) return; switch (type) { case FILE_FILE: file->close(); file = NULL; break; case FILE_DIR: dir->close(); dir = NULL; break; } type = FILE_FREE; openfds--; } }; filedesc fds[maxfds]; template<typename T> T* getfd(int fd) { fd -= firstfd; if (fd < 0 || fd >= maxfds) return NULL; return fds[fd]; } template <typename T> int allocfd(T *obj) { for (int i = 0; i < maxfds; i++) { if (!fds[i]) { fds[i] = obj; return firstfd + i; } } obj->close(); return -IOP_EMFILE; } void freefd(int fd) { fd -= firstfd; if (fd < 0 || fd >= maxfds) return; fds[fd].close(); } void reset() { for (int i = 0; i < maxfds; i++) fds[i].close(); } int open_HLE() { IOManFile *file = NULL; const char *name = Ra0; s32 flags = a1; u16 mode = a2; if ((!g_GameStarted || EmuConfig.HostFs) && !strncmp(name, "host", 4) && name[4 + strspn(name + 4, "0123456789")] == ':') { if (!freefdcount()) { v0 = -IOP_EMFILE; pc = ra; return 1; } int err = HostFile::open(&file, name, flags, mode); if (err != 0 || !file) { if (err == 0) // ??? err = -IOP_EIO; if (file) // ?????? file->close(); v0 = err; } else { v0 = allocfd(file); if ((s32)v0 < 0) file->close(); } pc = ra; return 1; } return 0; } int close_HLE() { s32 fd = a0; if (getfd<IOManFile>(fd)) { freefd(fd); v0 = 0; pc = ra; return 1; } return 0; } int lseek_HLE() { s32 fd = a0; s32 offset = a1; s32 whence = a2; if (IOManFile *file = getfd<IOManFile>(fd)) { v0 = file->lseek(offset, whence); pc = ra; return 1; } return 0; } int read_HLE() { s32 fd = a0; u32 buf = a1; u32 count = a2; if (IOManFile *file = getfd<IOManFile>(fd)) { if (!iopVirtMemR<void>(buf)) return 0; v0 = file->read(iopVirtMemW<void>(buf), count); pc = ra; return 1; } return 0; } int write_HLE() { s32 fd = a0; u32 buf = a1; u32 count = a2; if (fd == 1) // stdout { iopConLog(ShiftJIS_ConvertString(Ra1, a2)); pc = ra; v0 = a2; return 1; } else if (IOManFile *file = getfd<IOManFile>(fd)) { if (!iopVirtMemR<void>(buf)) return 0; v0 = file->write(iopVirtMemW<void>(buf), count); pc = ra; return 1; } return 0; } } namespace sysmem { int Kprintf_HLE() { // Emulate the expected Kprintf functionality: iopMemWrite32(sp, a0); iopMemWrite32(sp + 4, a1); iopMemWrite32(sp + 8, a2); iopMemWrite32(sp + 12, a3); pc = ra; // From here we're intercepting the Kprintf and piping it to our console, complete with // printf-style formatting processing. This part can be skipped if the user has the // console disabled. if (!SysConsole.iopConsole.IsActive()) return 1; char tmp[1024], tmp2[1024]; char *ptmp = tmp; int n=1, i=0, j = 0; while (Ra0[i]) { switch (Ra0[i]) { case '%': j = 0; tmp2[j++] = '%'; _start: switch (Ra0[++i]) { case '.': case 'l': tmp2[j++] = Ra0[i]; goto _start; default: if (Ra0[i] >= '0' && Ra0[i] <= '9') { tmp2[j++] = Ra0[i]; goto _start; } break; } tmp2[j++] = Ra0[i]; tmp2[j] = 0; switch (Ra0[i]) { case 'f': case 'F': ptmp+= sprintf(ptmp, tmp2, (float)iopMemRead32(sp + n * 4)); n++; break; case 'a': case 'A': case 'e': case 'E': case 'g': case 'G': ptmp+= sprintf(ptmp, tmp2, (double)iopMemRead32(sp + n * 4)); n++; break; case 'p': case 'i': case 'd': case 'D': case 'o': case 'O': case 'x': case 'X': ptmp+= sprintf(ptmp, tmp2, (u32)iopMemRead32(sp + n * 4)); n++; break; case 'c': ptmp+= sprintf(ptmp, tmp2, (u8)iopMemRead32(sp + n * 4)); n++; break; case 's': ptmp+= sprintf(ptmp, tmp2, iopVirtMemR<char>(iopMemRead32(sp + n * 4))); n++; break; case '%': *ptmp++ = Ra0[i]; break; default: break; } i++; break; default: *ptmp++ = Ra0[i++]; break; } } *ptmp = 0; iopConLog( ShiftJIS_ConvertString(tmp, 1023) ); return 1; } } namespace loadcore { void RegisterLibraryEntries_DEBUG() { DbgCon.WriteLn(Color_Gray, "RegisterLibraryEntries: %8.8s", iopVirtMemR<char>(a0 + 12)); } } namespace intrman { static const char* intrname[] = { "INT_VBLANK", "INT_GM", "INT_CDROM", "INT_DMA", //00 "INT_RTC0", "INT_RTC1", "INT_RTC2", "INT_SIO0", //04 "INT_SIO1", "INT_SPU", "INT_PIO", "INT_EVBLANK", //08 "INT_DVD", "INT_PCMCIA", "INT_RTC3", "INT_RTC4", //0C "INT_RTC5", "INT_SIO2", "INT_HTR0", "INT_HTR1", //10 "INT_HTR2", "INT_HTR3", "INT_USB", "INT_EXTR", //14 "INT_FWRE", "INT_FDMA", "INT_1A", "INT_1B", //18 "INT_1C", "INT_1D", "INT_1E", "INT_1F", //1C "INT_dmaMDECi", "INT_dmaMDECo", "INT_dmaGPU", "INT_dmaCD", //20 "INT_dmaSPU", "INT_dmaPIO", "INT_dmaOTC", "INT_dmaBERR", //24 "INT_dmaSPU2", "INT_dma8", "INT_dmaSIF0", "INT_dmaSIF1", //28 "INT_dmaSIO2i", "INT_dmaSIO2o", "INT_2E", "INT_2F", //2C "INT_30", "INT_31", "INT_32", "INT_33", //30 "INT_34", "INT_35", "INT_36", "INT_37", //34 "INT_38", "INT_39", "INT_3A", "INT_3B", //38 "INT_3C", "INT_3D", "INT_3E", "INT_3F", //3C "INT_MAX" //40 }; void RegisterIntrHandler_DEBUG() { DbgCon.WriteLn(Color_Gray, "RegisterIntrHandler: intr %s, handler %x", intrname[a0], a2); } } namespace sifcmd { void sceSifRegisterRpc_DEBUG() { DbgCon.WriteLn( Color_Gray, "sifcmd sceSifRegisterRpc: rpc_id %x", a1); } } const char* irxImportLibname(u32 entrypc) { u32 i; i = entrypc; while (iopMemRead32(i -= 4) != 0x41e00000) // documented magic number ; return iopVirtMemR<char>(i + 12); } const char* irxImportFuncname(const char libname[8], u16 index) { #include "IopModuleNames.cpp" switch (index) { case 0: return "start"; // case 1: reinit? case 2: return "shutdown"; // case 3: ??? } return 0; } #define MODULE(n) if (!strncmp(libname, #n, 8)) { using namespace n; switch (index) { #define END_MODULE }} #define EXPORT_D(i, n) case (i): return n ## _DEBUG; #define EXPORT_H(i, n) case (i): return n ## _HLE; irxHLE irxImportHLE(const char libname[8], u16 index) { // debugging output MODULE(sysmem) EXPORT_H( 14, Kprintf) END_MODULE MODULE(ioman) EXPORT_H( 4, open) EXPORT_H( 5, close) EXPORT_H( 6, read) EXPORT_H( 7, write) EXPORT_H( 8, lseek) END_MODULE return 0; } irxDEBUG irxImportDebug(const char libname[8], u16 index) { MODULE(loadcore) EXPORT_D( 6, RegisterLibraryEntries) END_MODULE MODULE(intrman) EXPORT_D( 4, RegisterIntrHandler) END_MODULE MODULE(sifcmd) EXPORT_D( 17, sceSifRegisterRpc) END_MODULE return 0; } #undef MODULE #undef END_MODULE #undef EXPORT_D #undef EXPORT_H void __fastcall irxImportLog(const char libname[8], u16 index, const char *funcname) { PSXBIOS_LOG("%8.8s.%03d: %s (%x, %x, %x, %x)", libname, index, funcname ? funcname : "unknown", a0, a1, a2, a3); } int __fastcall irxImportExec(const char libname[8], u16 index) { const char *funcname = irxImportFuncname(libname, index); irxHLE hle = irxImportHLE(libname, index); irxDEBUG debug = irxImportDebug(libname, index); irxImportLog(libname, index, funcname); if (debug) debug(); if (hle) return hle(); else return 0; } } // end namespace R3000A
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 683 ] ] ]
0812ddc6f5eca9a6e5c5fbcbae9e29d3c6491144
85e86cd5c3bd0458ae94de3c384d1b07e5a9a0cf
/MainFrm.h
da874954c514127459b131a9b93435202c4090f7
[]
no_license
dbv771/Ditto
6fbe858e28d73ae5366b4eb864f6a7d1d90b3383
faa5dda8beafd85eb38f06274c0bc6ec2f1ba462
refs/heads/master
2021-05-27T14:57:38.613868
2011-10-29T05:19:24
2011-10-29T05:19:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,908
h
#pragma once #include "SystemTray.h" #include "QuickPaste.h" #include "ToolTipEx.h" #include "EditFrameWnd.h" #include "MainFrmThread.h" #include "ClipboardSaveRestore.h" #define CLOSE_WINDOW_TIMER 1 #define HIDE_ICON_TIMER 2 #define REMOVE_OLD_ENTRIES_TIMER 3 #define REMOVE_OLD_REMOTE_COPIES 6 #define END_DITTO_BUFFER_CLIPBOARD_TIMER 7 #define KEY_STATE_MODIFIERS 8 #define ACTIVE_WINDOW_TIMER 9 #define FOCUS_CHANGED_TIMER 10 #define TEXT_ONLY_PASTE 11 class CMainFrame: public CFrameWnd { public: CMainFrame(); protected: DECLARE_DYNAMIC(CMainFrame) // Attributes public: // Operations public: BOOL ResetKillDBTimer(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMainFrame) public: virtual BOOL PreCreateWindow(CREATESTRUCT &cs); // virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL); //}}AFX_VIRTUAL // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid()const; virtual void Dump(CDumpContext &dc)const; #endif CQuickPaste m_quickPaste; CSystemTray m_TrayIcon; ULONG m_ulCopyGap; CString m_csKeyboardPaste; CAlphaBlend m_Transparency; BYTE m_keyStateModifiers; DWORD m_startKeyStateTime; bool m_bMovedSelectionMoveKeyState; short m_keyModifiersTimerCount; HWND m_tempFocusWnd; CMainFrmThread m_thread; CClipboardSaveRestore m_textOnlyPaste; CDialog *m_pGlobalClips; CPropertySheet *m_pOptions; void DoDittoCopyBufferPaste(int nCopyBuffer); void DoFirstTenPositionsPaste(int nPos); bool PasteQuickPasteEntry(CString csQuickPaste); bool SaveQuickPasteEntry(CString csQuickPaste, CClipList *pClipList); void ShowErrorMessage(CString csTitle, CString csMessage); bool CloseAllOpenDialogs(); void DoTextOnlyPaste(); void ShowEditWnd(CClipIDs &Ids); CEditFrameWnd *m_pEditFrameWnd; // Generated message map functions protected: //{{AFX_MSG(CMainFrame) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnFirstOption(); afx_msg void OnFirstExit(); afx_msg void OnChangeCbChain(HWND hWndRemove, HWND hWndAfter); afx_msg void OnDrawClipboard(); afx_msg void OnTimer(UINT_PTR nIDEvent); afx_msg void OnFirstShowquickpaste(); afx_msg void OnFirstToggleConnectCV(); afx_msg void OnUpdateFirstToggleConnectCV(CCmdUI *pCmdUI); afx_msg void OnFirstHelp(); //}}AFX_MSG afx_msg LRESULT OnHotKey(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnShowTrayIcon(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnClipboardCopied(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnAddToDatabaseFromSocket(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnErrorOnSendRecieve(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnFocusChanged(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnCustomizeTrayMenu(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnEditWndClose(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnSetConnected(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnLoadClipOnClipboard(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnSystemTrayMouseMove(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnGlobalClipsClosed(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnOptionsClosed(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnShowOptions(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP()public: virtual BOOL PreTranslateMessage(MSG *pMsg); afx_msg void OnClose(); afx_msg void OnFirstImport(); afx_msg void OnDestroy(); afx_msg void OnFirstNewclip(); afx_msg void OnFirstGlobalhotkeys(); };
[ "sabrogden@d0e771a7-b16f-4c6e-81b0-f3fd8ace72c5" ]
[ [ [ 1, 113 ] ] ]
420f17c3fa33a909c801f66400b0ac189970bfe3
102d8810abb4d1c8aecb454304ec564030bf2f64
/TP3/Tanque/ClienteTanque/ClienteTanque/BattleCityClient.h
69241de5b9f685a431b0879815e20dd06b3570c4
[]
no_license
jfacorro/tp-taller-prog-1-fiuba
2742d775b917cc6df28188ecc1f671d812017a0a
a1c95914c3be6b1de56d828ea9ff03e982560526
refs/heads/master
2016-09-14T04:32:49.047792
2008-07-15T20:17:27
2008-07-15T20:17:27
56,912,077
0
0
null
null
null
null
UTF-8
C++
false
false
1,815
h
#ifndef BattleCityClient_h #define BattleCityClient_h #include "Socket.h" #include "BattleCityCommunicationProtocol.h" #include "BattleCityEngine.h" #include "SDLHelper.h" #include "SDL_ttf.h" #include "map" using namespace std; #define MAX_TANKS 2 #define MAX_DIRECTIONS 5 class BattleCityClient { private: Socket socket; SDLHelper sdlHelper; TTF_Font * sdlFont; BattleCityClientParameters parameters; BattleCityState state; vector<Texture *> textures; int nextTick; int lastTick; void InitializeTicks(); void UpdateTicks(); int GetDelayTime() { return nextTick - lastTick; }; bool isConnected; int clientNumber; void UpdateEngine (int tecla); void RenderScreenChars(); void RenderScreenSDL(); void AddTexture(char * name, char * filename); SDL_Surface * GetTexture(char * name); void ReceiveParametersAndTextures(); static DWORD __stdcall ReceiveDataFromServer ( LPVOID param ); static void ProcessPacket(BattleCityClient * client, BattleCityDataPacket * packet); Rect GetScaledRectangle(Rect source, Rect quadrant, int pixelsPerUM); HANDLE mutex; SDL_Surface * background; SDL_Surface* tanks[MAX_TANKS][MAX_DIRECTIONS]; map<int,SDL_Surface*> walls; public: BattleCityClient() : background(NULL) { this->mutex = CreateMutex ( NULL , FALSE , NULL ); for ( int i = 0 ; i < MAX_TANKS ; i++ ) for ( int j = 0 ; j < MAX_DIRECTIONS ; j++ ) tanks[i][j] = NULL; }; void Connect(char * dir, int socketNumber); bool IsConnected() { return this->isConnected; }; void StartPlaying(); }; #endif
[ "juan.facorro@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb", "nahuelgonzalez@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb" ]
[ [ [ 1, 8 ], [ 15, 51 ], [ 56, 56 ], [ 58, 59 ], [ 64, 72 ] ], [ [ 9, 14 ], [ 52, 55 ], [ 57, 57 ], [ 60, 63 ] ] ]
32aa8fb0b2b66feb752cf22d6ace52a39a644b52
b8c3d2d67e983bd996b76825f174bae1ba5741f2
/RTMP/utils/gil_2/libs/gil/io_new/stdafx.cpp
7be052f7409a0de51cbce44dc80a8ba8119cf2b8
[]
no_license
wangscript007/rtmp-cpp
02172f7a209790afec4c00b8855d7a66b7834f23
3ec35590675560ac4fa9557ca7a5917c617d9999
refs/heads/master
2021-05-30T04:43:19.321113
2008-12-24T20:16:15
2008-12-24T20:16:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
// stdafx.cpp : source file that includes just the standard includes // io_new.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
[ "fpelliccioni@71ea4c15-5055-0410-b3ce-cda77bae7b57" ]
[ [ [ 1, 8 ] ] ]
b7c86f2e425fa9f15c35f3077aad904ea82db365
8e11ffb1c18f2a50e508b8a81f39136dd9c92075
/trunk/EUSandbox/src/CheckPointSystem/CheckPointManager.cpp
4c47517acc07fdef535f39a160153c4a2fb637b9
[]
no_license
BackupTheBerlios/evouni-svn
6e3e1bb4fac5ad606a648d45d62561be798d1318
7712c38b41f43f689e13acf325d96869c3a664fd
refs/heads/master
2021-01-10T19:11:17.911300
2007-01-02T15:39:27
2007-01-02T15:39:27
40,672,279
0
0
null
null
null
null
UTF-8
C++
false
false
6,886
cpp
#include "EUClient.h" CheckPointManager::CheckPointManager() { mName = ""; mSceneMgr = 0; mPosition = 0; num_of_cp = 0; counter = 0; done = true; pTargets = 0; } CheckPointManager::CheckPointManager(String name, SceneManager *sceneMgr, Vector3 position) { init(name,sceneMgr,position); } void CheckPointManager::init(String name, SceneManager *sceneMgr, Vector3 position) { Log* log = LogManager::getSingletonPtr()->getDefaultLog(); log->logMessage("Name: " + name); mName = name; log->logMessage("Name: " + mName); mSceneMgr = sceneMgr; mPosition = mSceneMgr->getRootSceneNode()->createChildSceneNode ( mName + "_node" ); mPosition->setPosition(position); num_of_cp = 0; counter = 0; done = true; pTargets = mSceneMgr->createParticleSystem( mName + "_particlesystem", num_of_cp * MAX_PARTICLES_PER_CHECKPOINT); pTargets->setMaterialName( "Examples/Flare" ); pTargets->setDefaultDimensions( 20, 20 ); mPosition->attachObject(pTargets); mSolid = new ManualObject("Test"); mPosition->attachObject(mSolid); loadLevel("level 1"); } CheckPointManager::~CheckPointManager(void) { resetLevel(); delete pTargets; mPosition->detachAllObjects (); mPosition->removeAndDestroyAllChildren (); mSceneMgr->destroySceneNode (mName + "_node"); mSceneMgr->destroyParticleSystem(mName + "_particlesystem"); } void CheckPointManager::resetLevel() { for(int i = 0; i < num_of_cp; i++) { delete cp[i]; } pTargets->removeAllEmitters(); done = true; num_of_cp = 0; counter = 0; mSolid->clear(); } void CheckPointManager::CheckColission(Character *object) { if(done) return; Vector3 vObject = object->getWorldPosition(); Vector3 position = mPosition->getPosition(); Vector3 temp; float distance; temp = vObject - cp[counter]->getPosition() - position; distance = temp.length(); if(distance <= 200) { CPState state = DONE; cp[counter++]->setState(state); if(counter >= num_of_cp) { done = true; for(int i = 0; i < num_of_cp; i++) { state = INACTIVE; cp[i]->setState(state); } return; } state = CURRENT; cp[counter]->setState(state); } } void CheckPointManager::AddCheckPoint(Vector3 position, CPState state) { cp[num_of_cp++] = new CheckPoint( mName + "_Emitter_" + StringConverter::toString(num_of_cp), mSceneMgr, state, pTargets, position); pTargets->setParticleQuota(num_of_cp * MAX_PARTICLES_PER_CHECKPOINT); } void CheckPointManager::loadLevel(String level) { resetLevel(); if( level == "random" ) { CPState status = CURRENT; AddCheckPoint(Vector3(0,0,1000), status); status = TODO; for( int i = 1; i < 15; i++ ) // generate 3 CPs AddCheckPoint(Vector3(Math::RangeRandom (-600, 600),Math::RangeRandom(-600, 600),Math::RangeRandom (0000, 15000)), status); done = false; } else if( level == "level 1" ) { CPState status = CURRENT; AddCheckPoint(Vector3(0,0,3000), status); status = TODO; AddCheckPoint(Vector3(3000,0,3000), status); AddCheckPoint(Vector3(3000,0,0), status); AddCheckPoint(Vector3(0,0,0), status); done = false; mSolid->begin("BaseWhiteNoLighting",RenderOperation::OT_LINE_STRIP); //BaseWhiteNoLighting"); //Ogre/Compositor/OldTV"); mSolid->position(0,0,3000); mSolid->colour(0,0,1); mSolid->position(3000,0,3000); mSolid->colour(1,0,1); mSolid->position(3000,0,0); mSolid->colour(1,0,0); mSolid->position(0,0,0); mSolid->colour(0,0,0); mSolid->position(0,0,3000); mSolid->colour(0,0,1); mSolid->end(); } else if( level == "level 2" ) { CPState status = CURRENT; AddCheckPoint(Vector3(0,0,3000), status); status = TODO; AddCheckPoint(Vector3(0,3000,3000), status); AddCheckPoint(Vector3(3000,3000,3000), status); AddCheckPoint(Vector3(3000,0000,3000), status); AddCheckPoint(Vector3(3000,0,0), status); AddCheckPoint(Vector3(3000,3000,0), status); AddCheckPoint(Vector3(0,3000,0), status); AddCheckPoint(Vector3(0,0,0), status); done = false; mSolid->begin("BaseWhiteNoLighting",RenderOperation::OT_LINE_LIST); //BaseWhiteNoLighting"); //Ogre/Compositor/OldTV"); mSolid->position(0,0,0); mSolid->colour(0,0,0); mSolid->position(0,0,3000); mSolid->colour(0,0,1); mSolid->position(3000,0,3000); mSolid->colour(1,0,1); mSolid->position(3000,0,0); mSolid->colour(1,0,0); mSolid->position(0,3000,0); mSolid->colour(0,1,0); mSolid->position(0,3000,3000); mSolid->colour(0,1,1); mSolid->position(3000,3000,3000); mSolid->colour(1,1,1); mSolid->position(3000,3000,0); mSolid->colour(1,1,0); mSolid->index(0); mSolid->index(1); mSolid->index(0); mSolid->index(3); mSolid->index(0); mSolid->index(4); mSolid->index(1); mSolid->index(2); mSolid->index(1); mSolid->index(5); mSolid->index(2); mSolid->index(3); mSolid->index(2); mSolid->index(6); mSolid->index(3); mSolid->index(7); mSolid->index(4); mSolid->index(5); mSolid->index(4); mSolid->index(7); mSolid->index(5); mSolid->index(6); mSolid->index(6); mSolid->index(7); mSolid->end(); } else if( level == "level 3" ) { CPState status = CURRENT; AddCheckPoint(Vector3(0,0,3000), status); status = TODO; AddCheckPoint(Vector3(0,3000,0), status); AddCheckPoint(Vector3(3000,0,0), status); AddCheckPoint(Vector3(-3000,0,0), status); AddCheckPoint(Vector3(0,-3000,0), status); AddCheckPoint(Vector3(0,0,-3000), status); done = false; mSolid->begin("BaseWhiteNoLighting",RenderOperation::OT_LINE_LIST); //BaseWhiteNoLighting"); //Ogre/Compositor/OldTV"); mSolid->position(0,0,3000); mSolid->colour(0,0,1); mSolid->position(0,3000,0); mSolid->colour(0,1,0); mSolid->position(3000,0,0); mSolid->colour(1,0,0); mSolid->position(-3000,0,0); mSolid->colour(0,1,1); mSolid->position(0,-3000,0); mSolid->colour(1,0,1); mSolid->position(0,0,-3000); mSolid->colour(1,1,0); mSolid->index(0); mSolid->index(1); mSolid->index(0); mSolid->index(2); mSolid->index(0); mSolid->index(3); mSolid->index(0); mSolid->index(4); mSolid->index(1); mSolid->index(2); mSolid->index(1); mSolid->index(3); mSolid->index(1); mSolid->index(5); mSolid->index(2); mSolid->index(4); mSolid->index(2); mSolid->index(5); mSolid->index(3); mSolid->index(4); mSolid->index(3); mSolid->index(5); mSolid->index(4); mSolid->index(5); mSolid->end(); } else { CPState status = CURRENT; AddCheckPoint(Vector3(0,0,0), status); status = TODO; for( int i = 1; i < 15; i++ ) // generate 3 CPs AddCheckPoint(Vector3(Math::RangeRandom (-600, 600),Math::RangeRandom(-600, 600),Math::RangeRandom (0, 15000)), status); done = false; } } /**/
[ "tomen@783cb599-3120-0410-820c-bbc20197cc9d" ]
[ [ [ 1, 261 ] ] ]
9e377b63ee5ee54565aff032a8279aed22bfef9d
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/MapLib/Windows/include/WinTCPConnectionHandler.h
72b6049f6794726174edfaebce6272e064930903
[ "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
8,294
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WINTCPCONNECTIONHANDLER_H #define WINTCPCONNECTIONHANDLER_H #include "HttpClientConnection.h" #include <windows.h> #include <winsock.h> #include <string> /* Windows Implementation of TCPConnectionHandler */ /* Uses WinSock 1.1 */ /* Simple Socket class - synch DNS, asynch connection, disconnection and I/O */ class ClientSocket { /** data **/ private: /* the socket */ SOCKET m_socket; /* the parent window */ HWND m_parentWindow; /* the host and port */ std::string m_host; int32 m_port; public: /* return codes for the read\write (IO) methods */ enum { IO_OK = -100, IO_ERROR = -101, IO_CLOSED = -102, IO_TIMEDOUT = -103 }; /** methods **/ private: /* private constructor */ ClientSocket(); /* second-phase constructor */ bool construct(HWND parentWin); public: /* allocator - async messages are sent to the parent window */ static ClientSocket* allocate(HWND parentWin); /* destructor */ ~ClientSocket(); /* connects to the specified host and port */ int connect(const char* hostName, int32 port); /* reconnects the socket to the previously specified host:port */ int reconnect(); /* disconnects the socket */ int disconnect(); /* shuts down all operations on the socket, but the socket remains connected */ int shutdown(); /* writes the specified bytes to the socket */ int write(const byte* dataBuf, int32 len); /* reads bytes from the socket and returns the data in the specified buffer. Returns the actual number of bytes read in bytesRead */ int read(byte* dataBuf, int32 maxReadLen, int32& bytesRead); }; class WinTCPConnectionHandler : public TCPConnectionHandler { /*** data ***/ private: // hack to get the codes passed thru : FIXME /** * Enum describing the status of the different calls. */ enum status_t { /// All is done. TCPOK = 0, /// Some error occured. TCPERROR = -1, /// A timout occured TCPTIMEOUT = -2, /// An operation of the same kind has been requested already. TCPALREADY_REQUESTED = -3, /// The connection was closed TCPCLOSED = -4, }; /* application instance */ HINSTANCE m_appInstance; /* the window which handles the socket messages */ HWND m_hwnd; /* the socket handle for connection */ ClientSocket* m_conn; /* the current listener being called */ TCPClientConnection* m_listener; /* the number of bytes to be written in the current write request */ /* used during the async callback to check if another write is required */ int m_bytesToWrite; /* the write buffer */ byte* m_writeBuffer; /* number of bytes to read and the buffer to read them into */ int m_bytesToRead; /* the read buffer */ byte* m_readBuffer; /* the currently active object */ static WinTCPConnectionHandler* m_curObject; /*** methods ***/ private: /* private constructor */ WinTCPConnectionHandler(); /* second-phase constructor */ bool construct(HINSTANCE hInst); /* sets the current handler */ static void setCurObject(WinTCPConnectionHandler* obj) { m_curObject = obj; return; } /* prepare for an asynchronous operation */ void prepareForAsync(TCPClientConnection* conn) { /* set the current object to ourselves */ WinTCPConnectionHandler::setCurObject(this); /* set the listener */ m_listener = conn; return; } /* check if the class name already exists */ bool classExists(LPCTSTR className); public: /* Allocator. * hInst : the parent application's instance. */ static WinTCPConnectionHandler* allocate(HINSTANCE hInst); /* destructor */ ~WinTCPConnectionHandler(); /** * Tells the underlying layer to connect to the * supplied host and port. When connected, connected * should be called. * Should call ccon->connectDone when done. * Max one connect per ClientConnection is allowed simultaneously. */ void connect(const char* host, unsigned int port, TCPClientConnection* ccon); /** * Tells the underlying layer to disconnect the * current connection. */ void disconnect(TCPClientConnection* ccon); /** * Tells the underlying layer to write the supplied * bytes. The underlying layer must keep the order * of the write requests. * Should call ccon->writeDone when done. * Max one write per ClientConnection is allowed. * Not allowed if not connected. */ void write(const byte* bytes, int length, TCPClientConnection* ccon); /** * Tells the underlying layer to start receiving reads * with up to maxLength bytes from the * socket. Max <code>length</code> bytes. * Should call the ccon->readDone when done. * Max one read per ClientConnection is allowed. * Not allowed if not connected. */ void read(int maxLength, TCPClientConnection* ccon); /** * Removes the connection from the internal list of * connections in the TCPConnectionHandler. */ void remove(TCPClientConnection* conn); /** * Requests a timeout for the connection conn. * After the timeout, the connectionhandler should call * timerExpired on the connection. * @param nbrMillis The number of milliseconds to wait before * sending the timeout. * @param conn The connection that should have the timeout. * @return ID of the timeout. */ int requestTimer(uint32 nbrMillis, TCPClientConnection* conn); /** * Cancels the timer with id timerID. */ void cancelTimer(int timerID); /* * The Window Message Processing method. */ static LRESULT CALLBACK SocketWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); }; #endif
[ [ [ 1, 234 ] ] ]
d757bdfa458b72770d41b428279febbd7e93bad8
9f18fcd1e740b0b365cb9d97e2f99f315418be70
/simple_cube.cpp
e193b1b80741f99bccd0ffcd25c87ab00df4ce87
[]
no_license
ajantis/opengltetris3d
3227317648a66faa5456198d8c72c8727493157f
0626134baf4ff19e975de18e55344afb228969bd
refs/heads/master
2016-09-10T13:40:28.279730
2010-04-21T13:59:48
2010-04-21T13:59:48
32,183,937
0
0
null
null
null
null
UTF-8
C++
false
false
1,618
cpp
#include <GL/glut.h> static void drawBox_spec(GLfloat size, GLenum type,GLuint texture) { static GLfloat n[6][3] = { {-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0} }; static GLint faces[6][4] = { {0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4}, {4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3} }; GLfloat v[8][3]; GLint i; v[0][0] = v[1][0] = v[2][0] = v[3][0] = -size / 2; v[4][0] = v[5][0] = v[6][0] = v[7][0] = size / 2; v[0][1] = v[1][1] = v[4][1] = v[5][1] = -size / 2; v[2][1] = v[3][1] = v[6][1] = v[7][1] = size / 2; v[0][2] = v[3][2] = v[4][2] = v[7][2] = -size / 2; v[1][2] = v[2][2] = v[5][2] = v[6][2] = size / 2; glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture); //Bottom //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); for (i = 5; i >= 0; i--) { glBegin(type); glNormal3fv(&n[i][0]); glTexCoord2f(0,0); glVertex3fv(&v[faces[i][0]][0]); glTexCoord2f(0,1); glVertex3fv(&v[faces[i][1]][0]); glTexCoord2f(1,1); glVertex3fv(&v[faces[i][2]][0]); glTexCoord2f(1,0); glVertex3fv(&v[faces[i][3]][0]); glEnd(); } glDisable(GL_TEXTURE_2D); } void glutSolidCube_own(GLdouble size,GLuint texture) { drawBox_spec(size, GL_QUADS,texture); }
[ [ [ 1, 63 ] ] ]
10e2efe645ca1b191441e1b2b4016dd979faae8a
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Modules/include/DestinationsEnums.h
896dafbb24fadfddf591645a1a48ddb7a6c4ab9d
[ "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
1,931
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DESTINATIONSENUMS_H #define DESTINATIONSENUMS_H namespace isab{ /* namespace DestinationsEnums{ */ enum DestError{ FAV_DO_NOT_EXIST, USER_NAME_MISSING, SYNC_ALREADY_IN_PROGRESS, SYNC_FAILED, }; //enum DestError /* } // namespace DestinationsEnums */ } // namespace isab #endif // DESTINATIONSENUMS_H
[ [ [ 1, 29 ] ] ]
1cc54debc6171bf42c8b38d7dfc82ad4a0685798
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/TeCom/src/TdkLayout/Source Files/TdkPageSize.cpp
6d02b11befd5e6dce23decb8cff1b3db56308fbf
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
ISO-8859-2
C++
false
false
4,468
cpp
#include <TdkPageSize.h> /////////////////////////////////////////////////////////////////////////////// //Empty Constructor //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// TdkPageSize::TdkPageSize() { _sizeValue[A0].width=841; _sizeValue[A0].height=1189; _sizeValue[A1].width=594; _sizeValue[A1].height=841; _sizeValue[A2].width=420; _sizeValue[A2].height=594; _sizeValue[A3].width=297; _sizeValue[A3].height=420; _sizeValue[A4].width=210; _sizeValue[A4].height=297; _sizeValue[A5].width=148; _sizeValue[A5].height=210; _sizeValue[A6].width=105; _sizeValue[A6].height=148; _sizeValue[Custom].width=210; _sizeValue[Custom].height=297; _pageSize=A4; _pageOrientation=portrait; } /////////////////////////////////////////////////////////////////////////////// //Destructor //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// TdkPageSize::~TdkPageSize() { } /////////////////////////////////////////////////////////////////////////////// //Set Page Orientation ( Portrait or Landscape ) //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// void TdkPageSize::setOrientation(const pageOrientation &orientation) { _pageOrientation=orientation; } /////////////////////////////////////////////////////////////////////////////// //Returns the page Orientation //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// pageOrientation TdkPageSize::getOrientation() { return _pageOrientation; } /////////////////////////////////////////////////////////////////////////////// //Set Page Size //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// void TdkPageSize::setSize(const pageSize &size) { _pageSize=size; } /////////////////////////////////////////////////////////////////////////////// //Returns the page size //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// pageSize TdkPageSize::getSize() { return _pageSize; } /////////////////////////////////////////////////////////////////////////////// //Set Custom Page Size //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// void TdkPageSize::setCustomSize(const double &width, const double &height) { _sizeValue[Custom].width=width; _sizeValue[Custom].height=height; _pageSize=Custom; } /////////////////////////////////////////////////////////////////////////////// //Returns the page width //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// double TdkPageSize::getWidth() { mapDimension::iterator it; if((it=_sizeValue.find(_pageSize))!=_sizeValue.end()) { if(_pageOrientation == portrait) return it->second.width; else return it->second.height; } return 0; } /////////////////////////////////////////////////////////////////////////////// //Returns the page height //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// double TdkPageSize::getHeight() { mapDimension::iterator it; if((it=_sizeValue.find(_pageSize))!=_sizeValue.end()) { if(_pageOrientation == portrait) return it->second.height; else return it->second.width; } return 0; } /////////////////////////////////////////////////////////////////////////////// //Returns the horizontal page center //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// double TdkPageSize::getCenterWidth() { return this->getWidth()/2.0; } /////////////////////////////////////////////////////////////////////////////// //Returns the vertical page center //Author : Rui Mauricio Gregรณrio //Date : 12/2008 /////////////////////////////////////////////////////////////////////////////// double TdkPageSize::getCenterHeight() { return this->getHeight()/2.0; }
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 147 ] ] ]
c1afec8716129316a3f942c5b3902ff1a2ec24db
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Scada/ScdOPC/Client/ConnectionPoint.h
46609f005a7ed14f43cac19fcd629d3945bc0414
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,323
h
//************************************************************************** // // Copyright (c) FactorySoft, INC. 1996-1998, All Rights Reserved // //************************************************************************** // // Filename : ConnectionPoint.h // $Author : Jim Hansen // // Description: Callback class for OPC Data Access 2.0 // // //************************************************************************** extern CComModule _Module; #include <atlcom.h> class OPCCallback : public IOPCDataCallback, public CComObjectRootEx<CComMultiThreadModel> { public: OPCCallback() {;} virtual ~OPCCallback(){;} BEGIN_COM_MAP(OPCCallback) COM_INTERFACE_ENTRY(IOPCDataCallback) END_COM_MAP() DECLARE_NOT_AGGREGATABLE(OPCCallback) // The OPC Callback functions STDMETHODIMP OnDataChange( DWORD Transid, OPCHANDLE grphandle, HRESULT masterquality, HRESULT mastererror, DWORD count, OPCHANDLE * clienthandles, VARIANT * values, WORD * quality, FILETIME * time, HRESULT * errors); STDMETHODIMP OnReadComplete( DWORD Transid, OPCHANDLE grphandle, HRESULT masterquality, HRESULT mastererror, DWORD count, OPCHANDLE * clienthandles, VARIANT * values, WORD * quality, FILETIME * time, HRESULT * errors); STDMETHODIMP OnWriteComplete( DWORD Transid, OPCHANDLE grphandle, HRESULT mastererr, DWORD count, OPCHANDLE * clienthandles, HRESULT * errors); STDMETHODIMP OnCancelComplete( DWORD transid, OPCHANDLE grphandle); }; typedef CComObject<OPCCallback> OPCCallbackObject; //************************************************************************** class OPCShutdown : public IOPCShutdown, public CComObjectRootEx<CComMultiThreadModel> { public: OPCShutdown() {;} virtual ~OPCShutdown(){;} BEGIN_COM_MAP(OPCShutdown) COM_INTERFACE_ENTRY(IOPCShutdown) END_COM_MAP() DECLARE_NOT_AGGREGATABLE(OPCShutdown) // The OPC Callback function STDMETHODIMP ShutdownRequest(LPCWSTR szReason); CString reason; }; typedef CComObject<OPCShutdown> OPCShutdownObject;
[ [ [ 1, 92 ] ] ]
a77c9fd9c82ea4824775874354426b574052612e
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlConvexRegion.h
d8c877dd8ee45b79ccdcabb5dcc68060337149fe
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
2,196
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLCONVEXREGION_H #define WMLCONVEXREGION_H #include "WmlBspNode.h" namespace Wml { class Portal; class WML_ITEM ConvexRegion : public BspNode { WmlDeclareRTTI; WmlDeclareStream; public: // Construction and destruction. ConvexRegion accepts responsibility // for deleting the input array. ConvexRegion (int iPortalQuantity, Portal** apkPortal, Spatial* pkRepresentation); virtual ~ConvexRegion (); // The left and right children of ConvexRegion must be null. The // middle child is where the representation of the region is stored. // This can be an arbitrary subgraph, not just drawable geometry. SpatialPtr AttachRepresentation (Spatial* pkRepresentation); SpatialPtr DetachRepresentation (); SpatialPtr GetRepresentation (); // portal access int GetPortalQuantity () const; Portal* GetPortal (int i) const; virtual Object* GetObjectByName (const char* acName); virtual void GetAllObjectsByName (const char* acName, std::vector<Object*>& rkObjects); protected: // streaming ConvexRegion (); // geometric updates virtual void UpdateWorldData (float fAppTime); // Drawing. ConvexRegionManager starts the region graph traversal // with the region containing the eye point. Portal continues the // traversal. friend class ConvexRegionManager; friend class Portal; virtual void Draw (Renderer& rkRenderer); // portals of the region (these are not set up to be shared) int m_iPortalQuantity; Portal** m_apkPortal; // for region graph traversal bool m_bVisited; }; WmlSmartPointer(ConvexRegion); WmlRegisterStream(ConvexRegion); #include "WmlConvexRegion.inl" } #endif
[ [ [ 1, 77 ] ] ]
df63d210accdafbec64f2ffa22be7ec2512eb3fb
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/TeCom/src/Tdk/Source Files/TdkAbstractCanvasDraw.cpp
b9545b8f8a33ab48899bcde3a846c8c0fad32fcd
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,782
cpp
#include <TdkAbstractCanvasDraw.h> #include <TeProjection.h> #include <TeRaster.h> #include <TeDecoderMemory.h> TdkAbstractCanvasDraw::TdkAbstractCanvasDraw(const int& canvasId) : _paintMode(pmdREPLACE), _canvasId(canvasId), _currentBufferId(-1), _backgroundColor(TeColor(255, 255, 255)) { } TdkAbstractCanvasDraw::~TdkAbstractCanvasDraw() { } void TdkAbstractCanvasDraw::setWindow(const double& llx, const double& lly, const double& urx, const double& ury) { _transformer.setWindow(llx, lly, urx, ury); } void TdkAbstractCanvasDraw::setWindow(const TeBox& box) { setWindow(box.x1(), box.y1(), box.x2(), box.y2()); } void TdkAbstractCanvasDraw::getWindow(double& llx, double& lly, double& urx, double& ury) { _transformer.getWindow(llx, lly, urx, ury); } void TdkAbstractCanvasDraw::getWindow(TeBox& window) { getWindow(window.x1_, window.y1_, window.x2_, window.y2_); } void TdkAbstractCanvasDraw::setViewport(const double& llx, const double& lly, const double& urx, const double& ury) { _transformer.setViewport(llx, lly, urx, ury); } void TdkAbstractCanvasDraw::setViewport(const TeBox& box) { setViewport(box.x1(), box.y1(), box.x2(), box.y2()); } void TdkAbstractCanvasDraw::getViewport(double& llx, double& lly, double& urx, double& ury) { _transformer.getViewport(llx, lly, urx, ury); } void TdkAbstractCanvasDraw::getViewport(TeBox& viewport) { getViewport(viewport.x1_, viewport.y1_, viewport.x2_, viewport.y2_); } void TdkAbstractCanvasDraw::window2Viewport(const double& wx, const double& wy, double& vx, double& vy) { _transformer.window2Viewport(wx, wy, vx, vy); } void TdkAbstractCanvasDraw::window2Viewport(const double& w, double& v, const bool& xdirection) { _transformer.window2Viewport(w, v, xdirection); } void TdkAbstractCanvasDraw::window2Viewport(const TePolygon& pIn, TePolygon& pOut) { _transformer.window2Viewport(pIn, pOut); } void TdkAbstractCanvasDraw::window2Viewport(const TeLine2D& lIn, TeLine2D& lOut) { _transformer.window2Viewport(lIn, lOut); } void TdkAbstractCanvasDraw::viewport2Window(const TePolygon& pIn, TePolygon& pOut) { _transformer.viewport2Window(pIn, pOut); } void TdkAbstractCanvasDraw::viewport2Window(const double& vx, const double& vy, double& wx, double& wy) { _transformer.viewport2Window(vx, vy, wx, wy); } void TdkAbstractCanvasDraw::viewport2Window(const double& v, double& w, const bool& xdirection) { _transformer.viewport2Window(v, w, xdirection); } void TdkAbstractCanvasDraw::getDimension(double& width, double& height) { width = getWidth(); height = getHeight(); } void TdkAbstractCanvasDraw::setBackgroundColor(const TeColor& color) { _backgroundColor = color; } void TdkAbstractCanvasDraw::clear(const int& bufferId) { int oldBuffer = setActiveBuffer(bufferId); clear(); setActiveBuffer(oldBuffer); } double TdkAbstractCanvasDraw::getPixelSize() { // Gets the drawing area in world coordinates. TeBox windowsBBox; getWindow(windowsBBox.x1_, windowsBBox.y1_, windowsBBox.x2_, windowsBBox.y2_); // Gets the canvas dimensions in pixels. double canvasWidthPx; double canvasHeightPx; getDimension(canvasWidthPx, canvasHeightPx); // Computes the pixel size. return (windowsBBox.width() / canvasWidthPx); } double TdkAbstractCanvasDraw::getScale(TeProjection* viewProj) { //FROM TERRAVIEW TeBox windowsBBox; getWindow(windowsBBox.x1_, windowsBBox.y1_, windowsBBox.x2_, windowsBBox.y2_); // Gets the canvas dimension in pixels. double canvasWidthPx; double canvasHeightPx; getDimension(canvasWidthPx, canvasHeightPx); // Gets the canvas dimension in mm. double canvasWidthMM; double canvasHeightMM; getDimensionMM(canvasWidthMM, canvasHeightMM); double dxw = windowsBBox.width(), dyw = windowsBBox.height(), dxv = canvasWidthPx, dyv = canvasHeightPx; double fx = dxv/dxw, fy = dyv/dyw, factor; if (fx > fy) { factor = fy; canvasWidthPx = (int)(factor * dxw + .5); } else { factor = fx; canvasHeightPx = (int)(factor * dyw + .5); } double wpixels = canvasWidthPx; double wMM = canvasWidthMM; double wT = wMM; // Gets canvas dimension in view coordinates. if (viewProj) { const string unit = viewProj->units(); if (TeConvertToUpperCase(unit) == "METERS") wT = wMM / 1000.; else if (TeConvertToUpperCase(unit) == "KILOMETERS") wT = wMM / 1000000.; else if (TeConvertToUpperCase(unit) == "CENTIMETERS") wT = wMM / 100.; else if (TeConvertToUpperCase(unit) == "MILLIMETERS") wT = wMM; else if (TeConvertToUpperCase(unit) == "FEET") wT = wMM / (12. * 25.4); else if (TeConvertToUpperCase(unit) == "INCHES") wT = wMM / 25.4; else if (TeConvertToUpperCase(unit) == "DECIMALDEGREES") wT = wMM / 110000000.; } double wp = wT / wpixels; return (1. / factor ) / wp; } int TdkAbstractCanvasDraw::setActiveBuffer(const int& bufferId) { int oldBufferId = _currentBufferId; _currentBufferId = bufferId; return oldBufferId; } int TdkAbstractCanvasDraw::getActiveBuffer() { return _currentBufferId; } inline int TdkAbstractCanvasDraw::setPaintMode(const int& mode) { int oldMode = _paintMode; _paintMode = mode; return oldMode; } inline int TdkAbstractCanvasDraw::getPaintMode() const { return _paintMode; } void TdkAbstractCanvasDraw::drawPointW(const TePoint& pt) { drawPointW(pt.location()); } void TdkAbstractCanvasDraw::drawPointsW(TePointSet& points) { TePointSet::iterator it; for(it = points.begin(); it != points.end(); ++it) { drawPointW((*it)); } } void TdkAbstractCanvasDraw::drawLineW(const TeLine2D& line, const bool& showPoint) { TeLine2D vline; _transformer.window2Viewport(line, vline); drawLine(vline, showPoint); } void TdkAbstractCanvasDraw::drawLinesW(TeLineSet& lines, const bool& showPoint) { TeLineSet::iterator it; for(it = lines.begin(); it != lines.end(); ++it) { drawLineW((*it)); } } void TdkAbstractCanvasDraw::drawPolygonW(const TePolygon& poly, const bool& showPoint) { TePolygon p; _transformer.window2Viewport(poly, p); drawPolygon(p, showPoint); } void TdkAbstractCanvasDraw::drawPolygonsW(TePolygonSet& polys, const bool& showPoint) { TePolygonSet::iterator it; for(it = polys.begin(); it != polys.end(); ++it) { drawPolygonW((*it)); } } void TdkAbstractCanvasDraw::drawCellW(const TeCell& cell, const bool& showPoint) { TeCell c = cell; TeBox vBox; _transformer.window2Viewport(c.box(), vBox); c.setBox(vBox); drawCell(c); } void TdkAbstractCanvasDraw::drawCellsW(TeCellSet& cells, const bool& showPoint) { } void TdkAbstractCanvasDraw::drawTextW(const TeText& text) { TeCoord2D vcoord; TeText vText; _transformer.window2Viewport(text.location(), vcoord); drawText(vcoord.x(),vcoord.y(),text.textValue()); } void TdkAbstractCanvasDraw::drawTextW(const TeBox &box, const std::string &text) { double llx,lly; double urx,ury; _transformer.window2Viewport(box.x1(),box.y1(),llx,lly); _transformer.window2Viewport(box.x2(),box.y2(),urx,ury); drawText(TeBox(llx,lly,urx,ury),text); } void TdkAbstractCanvasDraw::drawTextsW(TeTextSet& texts) { } void TdkAbstractCanvasDraw::drawPointW(const TeCoord2D& coord) { TeCoord2D vcoord; _transformer.window2Viewport(coord, vcoord); drawPoint(vcoord); } void TdkAbstractCanvasDraw::drawBoxW(TeBox& box, const bool& showPoint) { double llx,lly; double urx,ury; _transformer.window2Viewport(box.x1(),box.y1(),llx,lly); _transformer.window2Viewport(box.x2(),box.y2(),urx,ury); this->drawRect(llx,lly,urx,ury); } void TdkAbstractCanvasDraw::drawPointW(const double& x, const double& y) { TeCoord2D coord(x, y); TeCoord2D vcoord; _transformer.window2Viewport(coord, vcoord); drawPoint(vcoord.x_, vcoord.y_); } void TdkAbstractCanvasDraw::drawLineSegmentW(const double& x0, const double& y0, const double& x1, const double& y1) { double vX0, vY0; double vX1, vY1; _transformer.window2Viewport(x0,y0,vX0,vY0); _transformer.window2Viewport(x1,y1,vX1,vY1); drawLineSegment(vX0,vY0,vX1,vY1); } void TdkAbstractCanvasDraw::drawLineSegmentW(const TeCoord2D& c1, const TeCoord2D& c2) { drawLineSegmentW(c1.x_, c1.y_, c2.x_, c2.y_); } void TdkAbstractCanvasDraw::drawRectW(const double& llx, const double& lly, const double& urx, const double& ury) { double vx1, vx2, vy1, vy2; window2Viewport(llx, lly, vx1, vy1); window2Viewport(urx, ury, vx2, vy2); drawRect(vx1, vy1, vx2, vy2); } void TdkAbstractCanvasDraw::drawRectW(const TeBox& rect) { drawRectW(rect.x1(), rect.y1(), rect.x2(), rect.y2()); } void TdkAbstractCanvasDraw::fillRectW(const double& llx, const double& lly, const double& urx, const double& ury) { double vx1, vx2, vy1, vy2; window2Viewport(llx, lly, vx1, vy1); window2Viewport(urx, ury, vx2, vy2); fillRect(vx1, vy1, vx2, vy2); } void TdkAbstractCanvasDraw::fillRectW(const TeBox& rect) { fillRectW(rect.x1(), rect.y1(), rect.x2(), rect.y2()); } void TdkAbstractCanvasDraw::drawLineW(TdkPrimitiveCoord* line, const int& lineSize) { } void TdkAbstractCanvasDraw::drawPolygonW(TdkPrimitiveCoord* poly, int* ringSize, const int& nRings) { } void TdkAbstractCanvasDraw::drawEllipseW(const double& xc, const double& yc, const double& rx, const double& ry, const double& angle) { double vxc, vrx, vyc, vry; window2Viewport(xc, yc, vxc, vyc); window2Viewport(rx, vrx); window2Viewport(ry, vry); drawEllipse(vxc, vyc, vrx, vry, angle); } void TdkAbstractCanvasDraw::drawEllipseW(const double& xc, const double& yc, const double& rx1, const double& ry1, const double& rx2, const double& ry2) { double vxc, vrx1, vrx2, vyc, vry1, vry2; window2Viewport(xc, yc, vxc, vyc); window2Viewport(rx1, vrx1); window2Viewport(ry1, vry1); window2Viewport(rx2, vrx2); window2Viewport(ry2, vry2); drawEllipse(vxc, vyc, vrx1, vry1, vrx2, vry2); } void TdkAbstractCanvasDraw::fillEllipseW(const double& xc, const double& yc, const double& rx, const double& ry, const double& angle) { double vxc, vrx, vyc, vry; window2Viewport(xc, yc, vxc, vyc); window2Viewport(rx, vrx); window2Viewport(ry, vry); fillEllipse(vxc, vyc, vrx, vry, angle); } void TdkAbstractCanvasDraw::fillEllipseW(const double& xc, const double& yc, const double& rx1, const double& ry1, const double& rx2, const double& ry2) { } void TdkAbstractCanvasDraw::drawArcW(const double& xc, const double& yc, const double& w, const double& h, const double& startAngle, const double& finalAngle) { } void TdkAbstractCanvasDraw::drawSectorW(const double& xc, const double& yc, const double& w, const double& h, const double& startAngle, const double& finalAngle) { } void TdkAbstractCanvasDraw::fillSectorW(const double& xc, const double& yc, const double& w, const double& h, const double& startAngle, const double& finalAngle) { } void TdkAbstractCanvasDraw::drawImageRGBW(const unsigned int& imgW, const unsigned int& imgH, unsigned char* red, unsigned char* green, unsigned char* blue, const double& dstX, const double& dstY, const unsigned int& dstW, const unsigned int& dstH, const double& angle) { double dstXv, dstYv; double dstWv, dstHv; window2Viewport(dstX, dstY, dstXv, dstYv); window2Viewport(dstW, dstWv); window2Viewport(dstH, dstHv); drawImageRGB(imgW, imgH, red, green, blue, dstXv, dstYv, (int)dstWv, (int)dstHv, angle); } void TdkAbstractCanvasDraw::drawImageRGBW(const unsigned int& imgW, const unsigned int& imgH, unsigned char* red, unsigned char* green, unsigned char* blue, const double& dstX, const double& dstY, const unsigned int& dstW, const unsigned int& dstH, const double& srcX, const double& srcY, const unsigned int& srcW, const unsigned int& srcH, const double& angle) { double dstXv, dstYv; double srcXv, srcYv; double dstWv, dstHv; double srcWv, srcHv; window2Viewport(dstX, dstY, dstXv, dstYv); window2Viewport(srcX, srcY, srcXv, srcYv); window2Viewport(dstW, dstWv); window2Viewport(dstH, dstHv); window2Viewport(srcW, srcWv); window2Viewport(srcH, srcHv); drawImageRGB(imgW, imgH, red, green, blue, dstXv, dstYv, (int)dstWv, (int)dstHv, srcXv, srcYv, (int)srcWv, (int)srcHv, angle); } void TdkAbstractCanvasDraw::drawTextW(const double& x, const double& y, const string& text) { double vX; double vY; _transformer.window2Viewport(x,y,vX,vY); drawText(vX,vY,text); } void TdkAbstractCanvasDraw::drawPoint(const TePoint& pt) { drawPoint(pt.location().x_, pt.location().y_); } void TdkAbstractCanvasDraw::drawPoints(TePointSet& points) { TePointSet::iterator it; for(it = points.begin(); it != points.end(); ++it) { drawPoint((*it)); } } void TdkAbstractCanvasDraw::drawLines(TeLineSet& lines, const bool& showPoint) { } void TdkAbstractCanvasDraw::drawPolygons(TePolygonSet& polys, const bool& showPoint) { } void TdkAbstractCanvasDraw::drawCells(TeCellSet& cells, const bool& showPoint) { } void TdkAbstractCanvasDraw::drawText(const TeText& text) { } void TdkAbstractCanvasDraw::drawTexts(TeTextSet& texts) { } void TdkAbstractCanvasDraw::drawPoint(const TeCoord2D& coord) { drawPoint(coord.x_, coord.y_); } void TdkAbstractCanvasDraw::drawBox(const TeBox& box, const bool& showPoint) { } void TdkAbstractCanvasDraw::drawRect(const TeBox& rect) { drawRect(rect.x1(), rect.y1(), rect.x2(), rect.y2()); } void TdkAbstractCanvasDraw::fillRect(const TeBox& rect) { fillRect(rect.x1(), rect.y1(), rect.x2(), rect.y2()); } int TdkAbstractCanvasDraw::getCanvasId() { return _canvasId; } void TdkAbstractCanvasDraw::setRasterDecoder(TeRaster* raster, TeRasterParams& params) { TeDecoderMemory *dec = new TeDecoderMemory(params); raster->setDecoder(dec); }
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 568 ] ] ]
05ddca8e55f993ee709e0431626eb35b90badda0
3d7d8969d540b99a1e53e00c8690e32e4d155749
/IEBgps/src/IEImageEncoder.cpp
722e239af26b8fbff2ce3171b348c99f876488dc
[]
no_license
SymbianSource/oss.FCL.sf.incubator.photobrowser
50c4ea7142102068f33fc62e36baab9d14f348f9
818b5857895d2153c4cdd653eb0e10ba6477316f
refs/heads/master
2021-01-11T02:45:51.269916
2010-10-15T01:18:29
2010-10-15T01:18:29
70,931,013
0
0
null
null
null
null
UTF-8
C++
false
false
3,945
cpp
/* * Copyright (c) 2009 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: Juha Kauppinen, Mika Hokkanen * * Description: Photo Browser * */ // Include files #include "IEImageEncoder.h" // ========================== MEMBER FUNCTIONS ============================= // CIEImageEncoder* CIEImageEncoder::NewL(RFs& aFileServer, MEncodingObserver& aObserver) { CIEImageEncoder* self = new (ELeave) CIEImageEncoder(aFileServer, aObserver); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(); return self; } CIEImageEncoder::~CIEImageEncoder() { if(iFrameImageData) { delete iFrameImageData; iFrameImageData = NULL; } if(iImageEncoder) { delete iImageEncoder; iImageEncoder = NULL; } if(iExtImageEncoder) { delete iExtImageEncoder; iExtImageEncoder = NULL; } if(iVisualFrame) { delete iVisualFrame; iVisualFrame = NULL; } } CIEImageEncoder::CIEImageEncoder(RFs& aFileServer, MEncodingObserver& aObserver) : CActive(EPriorityStandard), iFileServer(aFileServer), iObserver(aObserver) { } void CIEImageEncoder::ConstructL() { iEncoderBusy = EFalse; CActiveScheduler::Add(this); } void CIEImageEncoder::RunL() { TInt error = iStatus.Int(); //iObserver.JpegImageReady(iStatus.Int()); iEncoderBusy = EFalse; } void CIEImageEncoder::DoCancel() { } void CIEImageEncoder::ConvertYuv2JpegL(HBufC8*& aDestBuffer, HBufC8& aSourceBuffer, const TSize aSize) { TInt blocks = 0; iEncoderBusy = ETrue; if(iExtImageEncoder) { delete iExtImageEncoder; iExtImageEncoder = NULL; } iExtImageEncoder = CExtJpegEncoder::DataNewL(aDestBuffer, _L8("image/jpeg")); TPtr8 ptrSrc = aSourceBuffer.Des(); TInt bufSize = aSourceBuffer.Size(); if(iVisualFrame) { delete iVisualFrame; iVisualFrame = NULL; } iVisualFrame = CVisualFrame::NewL(ptrSrc, aSize, CVisualFrame::EFormatYUV420Planar); SetJpegImageDataL(); iExtImageEncoder->ConvertL(&iStatus, iVisualFrame, blocks, iFrameImageData); if(!IsActive()) SetActive(); } void CIEImageEncoder::ConvertYuv2JpegL(TDesC& aFileName, HBufC8& aSourceBuffer, const TSize aSize) { TInt blocks = 0; iEncoderBusy = ETrue; if(iExtImageEncoder) { delete iExtImageEncoder; iExtImageEncoder = NULL; } iExtImageEncoder = CExtJpegEncoder::FileNewL(iFileServer, aFileName, _L8("image/jpeg")); TPtr8 ptrSrc = aSourceBuffer.Des(); TInt bufSize = aSourceBuffer.Size(); if(iVisualFrame) { delete iVisualFrame; iVisualFrame = NULL; } iVisualFrame = CVisualFrame::NewL(ptrSrc, aSize, CVisualFrame::EFormatYUV420Planar); SetJpegImageDataL(); iExtImageEncoder->ConvertL(&iStatus, iVisualFrame, blocks, iFrameImageData); if(!IsActive()) SetActive(); } void CIEImageEncoder::SetJpegImageDataL() { TJpegImageData* jpegImageData; jpegImageData = new (ELeave) TJpegImageData; jpegImageData->iSampleScheme = TJpegImageData::EColor420; jpegImageData->iQualityFactor = 90; if(iFrameImageData) { delete iFrameImageData; iFrameImageData = NULL; } iFrameImageData = CFrameImageData::NewL(); // Ownership of jpegImageData lies with CFrameImageData User::LeaveIfError(iFrameImageData->AppendImageData(jpegImageData)); } void CIEImageEncoder::CancelEncoding() { if(iEncoderBusy) { if(iImageEncoder) iImageEncoder->Cancel(); if(iExtImageEncoder) iExtImageEncoder->Cancel(); } if(IsActive()) Cancel(); } // EOF
[ "none@none" ]
[ [ [ 1, 187 ] ] ]
e839c16a5998c423c8da403d36bc0372469cc4e1
9f00cc73bdc643215425e6bc43ea9c6ef3094d39
/OOP/Project-Lines/Board.cpp
341eddfd61d66a47763eb075e28e4b1750696f5a
[]
no_license
AndreyShamis/oopos
c0700e1d9d889655a52ad2bc58731934e968b1dd
0114233944c4724f242fd38ac443a925faf81762
refs/heads/master
2021-01-25T04:01:48.005423
2011-07-16T14:23:12
2011-07-16T14:23:12
32,789,875
0
0
null
null
null
null
UTF-8
C++
false
false
915
cpp
#include "Board.h" //============================================================================= // Constructor Board::Board(const float &X,const float &Y) { // set coords _cordX = X; _cordY = Y; _showMode = 0; // put the images to the vector of sprites _sprites.push_back(GAME_BOARD); _sprites.push_back(GAME_RULES); _sprites.push_back(GAME_OVER); } //============================================================================= // Destructor Board::~Board(void) { } //============================================================================= // Function that draw sprite void Board::Draw() { _sprites[_showMode].Draw(_cordX, _cordY); } //============================================================================= // Function wich say to class wich sprtie to shoe // It depend on Game mode void Board::setShowMode(const short int val) { _showMode = val; }
[ "[email protected]@c8aee422-7d7c-7b79-c2f1-0e09d0793d10" ]
[ [ [ 1, 34 ] ] ]
18926517bda735621019e553ca84cf14bccddab6
1493997bb11718d3c18c6632b6dd010535f742f5
/qchess/chessboard.cpp
542228cb36dba9d00d796bf1fcbbe1445b2c4ca6
[]
no_license
kovrov/scrap
cd0cf2c98a62d5af6e4206a2cab7bb8e4560b168
b0f38d95dd4acd89c832188265dece4d91383bbb
refs/heads/master
2021-01-20T12:21:34.742007
2010-01-12T19:53:23
2010-01-12T19:53:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,357
cpp
#include "chessboard.h" #include "movebits.h" ChessBoard::ChessBoard() : _whitePawns (0x000000000000FF00LL), _blackPawns (0x00FF000000000000LL), _whiteKnights (0x0000000000000042LL), _blackKnights (0x4200000000000000LL), _whiteBishops (0x0000000000000024LL), _blackBishops (0x2400000000000000LL), _whiteRooks (0x0000000000000081LL), _blackRooks (0x8100000000000000LL), _whiteQueens (0x0000000000000008LL), _blackQueens (0x0800000000000000LL), _whiteKings (0x0000000000000010LL), _blackKings (0x1000000000000000LL), _moves (0) { _recalc(); } void ChessBoard::_recalc() { _whitePieces = _whitePawns | _whiteKnights | _whiteBishops | _whiteRooks | _whiteQueens | _whiteKings; _blackPieces = _blackPawns | _blackKnights | _blackBishops | _blackRooks | _blackQueens | _blackKings; _occupiedSquares = _whitePieces | _blackPieces; //_enemy = (_moves % 2) == 1 ? _whitePieces : _blackPieces; //in_check = _in_check(); } void ChessBoard::move(int src_index, int dst_index) { // TODO: validate! Bitboard src_bit = 1LL << src_index; Bitboard dst_bit = 1LL << dst_index; // capture if (_whitePieces & dst_bit) { _whitePawns &= ~dst_bit; _whiteKnights &= ~dst_bit; _whiteBishops &= ~dst_bit; _whiteRooks &= ~dst_bit; _whiteQueens &= ~dst_bit; _whiteKings &= ~dst_bit; } else if (_blackPieces & dst_bit) { _blackPawns &= ~dst_bit; _blackKnights &= ~dst_bit; _blackBishops &= ~dst_bit; _blackRooks &= ~dst_bit; _blackQueens &= ~dst_bit; _blackKings &= ~dst_bit; } // move if (_whitePawns & src_bit) // a white pawn move... { _whitePawns ^= src_bit; _whitePawns |= dst_bit; } else if (_blackPawns & src_bit) // a black pawn move... { _blackPawns ^= src_bit; _blackPawns |= dst_bit; } else if (_whiteKnights & src_bit) // a white knight move... { _whiteKnights ^= src_bit; _whiteKnights |= dst_bit; } else if (_blackKnights & src_bit) // a black knight move... { _blackKnights ^= src_bit; _blackKnights |= dst_bit; } else if (_whiteBishops & src_bit) // a move... { _whiteBishops ^= src_bit; _whiteBishops |= dst_bit; } else if (_blackBishops & src_bit) // a move... { _blackBishops ^= src_bit; _blackBishops |= dst_bit; } else if (_whiteRooks & src_bit) // a move... { _whiteRooks ^= src_bit; _whiteRooks |= dst_bit; } else if (_blackRooks & src_bit) // a move... { _blackRooks ^= src_bit; _blackRooks |= dst_bit; } else if (_whiteQueens & src_bit) // a move... { _whiteQueens ^= src_bit; _whiteQueens |= dst_bit; } else if (_blackQueens & src_bit) { _blackQueens ^= src_bit; _blackQueens |= dst_bit; } else if (_whiteKings & src_bit) { _whiteKings ^= src_bit; _whiteKings |= dst_bit; } else if (_blackKings & src_bit) { _blackKings ^= src_bit; _blackKings |= dst_bit; } _moves++; _recalc(); } Bitboard ChessBoard::getMoves(int index) { Bitboard bit = 1LL << index; if (_whitePawns & bit) return _whitePawnMoves(index, ~_occupiedSquares ^ _blackPieces); if (_blackPawns & bit) return _blackPawnMoves(index, ~_occupiedSquares ^ _whitePieces); if (_whiteKnights & bit) return _knightMoves(index, ~_occupiedSquares ^ _blackPieces); if (_blackKnights & bit) return _knightMoves(index, ~_occupiedSquares ^ _whitePieces); if (_whiteBishops & bit) return _bishopMoves(index, ~_occupiedSquares ^ _blackPieces); if (_blackBishops & bit) return _bishopMoves(index, ~_occupiedSquares ^ _whitePieces); if (_whiteRooks & bit) return _rookMoves(index, ~_occupiedSquares ^ _blackPieces); if (_blackRooks & bit) return _rookMoves(index, ~_occupiedSquares ^ _whitePieces); if (_whiteQueens & bit) return _queenMoves(index, ~_occupiedSquares ^ _blackPieces); if (_blackQueens & bit) return _queenMoves(index, ~_occupiedSquares ^ _whitePieces); if (_whiteKings & bit) return _kingMoves(index, ~_occupiedSquares ^ _blackPieces); if (_blackKings & bit) return _kingMoves(index, ~_occupiedSquares ^ _whitePieces); return 0LL; } Bitboard ChessBoard::_whitePawnMoves(int index, Bitboard enemy_and_empty) { Bitboard pos = 1LL << index; Bitboard captures = 0LL; Bitboard pawn_moves = pos << 8 & ~_occupiedSquares; if (pawn_moves && index >= 8 && index < 16) pawn_moves |= pos << 16 & ~_occupiedSquares; if (index % 8) captures = pos << 7; if ((index + 1) % 8) captures |= pos << 9; captures &= enemy_and_empty & _occupiedSquares; // TODO: en passant return pawn_moves | captures; } Bitboard ChessBoard::_blackPawnMoves(int index, Bitboard enemy_and_empty) { Bitboard pos = 1LL << index; Bitboard captures = 0LL; Bitboard pawn_moves = pos >> 8 & ~_occupiedSquares; if (pawn_moves && index >= 48 && index < 56) pawn_moves |= pos >> 16 & ~_occupiedSquares; if (index % 8) captures = pos >> 9; if ((index + 1) % 8) captures |= pos >> 7; captures &= enemy_and_empty & _occupiedSquares; // TODO: en passant return pawn_moves | captures; } Bitboard ChessBoard::_knightMoves(int index, Bitboard enemy_and_empty) { return knight_moves[index] & enemy_and_empty; } Bitboard ChessBoard::_bishopMoves(int index, Bitboard enemy_and_empty) { return _neMoves(index, enemy_and_empty) | _swMoves(index, enemy_and_empty) | _seMoves(index, enemy_and_empty) | _nwMoves(index, enemy_and_empty); } Bitboard ChessBoard::_rookMoves(int index, Bitboard enemy_and_empty) { return _rightMoves(index, enemy_and_empty) | _leftMoves(index, enemy_and_empty) | _upMoves(index, enemy_and_empty) | _downMoves(index, enemy_and_empty); } Bitboard ChessBoard::_queenMoves(int index, Bitboard enemy_and_empty) { return _rookMoves(index, enemy_and_empty) | _bishopMoves(index, enemy_and_empty); } Bitboard ChessBoard::_kingMoves(int index, Bitboard enemy_and_empty) { Bitboard pos = 1LL << index; Bitboard king_moves = pos << 8 | pos >> 8; if (index % 8) king_moves |= pos << 7 | pos >> 9; king_moves |= pos >> 1; if ((index + 1) % 8) king_moves |= pos << 9 | pos >> 7; king_moves |= pos << 1; // TODO: castling return king_moves & enemy_and_empty; } Bitboard ChessBoard::_rightMoves(int index, Bitboard enemy_and_empty) { Bitboard blockers = right_moves[index] & _occupiedSquares; Bitboard blocked_slide = blockers<<1 | blockers<<2 | blockers<<3 | blockers<<4 | blockers<<5 | blockers<<6; Bitboard blocked_moves = blocked_slide & right_moves[index]; return ~blocked_moves & (right_moves[index] & enemy_and_empty); } Bitboard ChessBoard::_leftMoves(int index, Bitboard enemy_and_empty) { Bitboard blockers = left_moves[index] & _occupiedSquares; Bitboard blocked_slide = blockers>>1 | blockers>>2 | blockers>>3 | blockers>>4 | blockers>>5 | blockers>>6; Bitboard blocked_moves = blocked_slide & left_moves[index]; return ~blocked_moves & (left_moves[index] & enemy_and_empty); } Bitboard ChessBoard::_upMoves(int index, Bitboard enemy_and_empty) { Bitboard blockers = up_moves[index] & _occupiedSquares; Bitboard blocked_slide = blockers<<8 | blockers<<16 | blockers<<24 | blockers<<32 | blockers<<40 | blockers<<48; Bitboard blocked_moves = blocked_slide & up_moves[index]; return ~blocked_moves & (up_moves[index] & enemy_and_empty); } Bitboard ChessBoard::_downMoves(int index, Bitboard enemy_and_empty) { Bitboard blockers = down_moves[index] & _occupiedSquares; Bitboard blocked_slide = blockers>>8 | blockers>>16 | blockers>>24 | blockers>>32 | blockers>>40 | blockers>>48; Bitboard blocked_moves = blocked_slide & down_moves[index]; return ~blocked_moves & (down_moves[index] & enemy_and_empty); } Bitboard ChessBoard::_neMoves(int index, Bitboard enemy_and_empty) { Bitboard blockers = ne_moves[index] & _occupiedSquares; Bitboard blocked_slide = blockers<<9 | blockers<<18 | blockers<<27 | blockers<<36 | blockers<<45 | blockers<<54; Bitboard blocked_moves = blocked_slide & ne_moves[index]; return ~blocked_moves & (ne_moves[index] & enemy_and_empty); } Bitboard ChessBoard::_swMoves(int index, Bitboard enemy_and_empty) { Bitboard blockers = sw_moves[index] & _occupiedSquares; Bitboard blocked_slide = blockers>>9 | blockers>>18 | blockers>>27 | blockers>>36 | blockers>>45 | blockers>>54; Bitboard blocked_moves = blocked_slide & sw_moves[index]; return ~blocked_moves & (sw_moves[index] & enemy_and_empty); } Bitboard ChessBoard::_seMoves(int index, Bitboard enemy_and_empty) { Bitboard blockers = se_moves[index] & _occupiedSquares; Bitboard blocked_slide = blockers>>7 | blockers>>14 | blockers>>21 | blockers>>28 | blockers>>35 | blockers>>42; Bitboard blocked_moves = blocked_slide & se_moves[index]; return ~blocked_moves & (se_moves[index] & enemy_and_empty); } Bitboard ChessBoard::_nwMoves(int index, Bitboard enemy_and_empty) { Bitboard blockers = nw_moves[index] & _occupiedSquares; Bitboard blocked_slide = blockers<<7 | blockers<<14 | blockers<<21 | blockers<<28 | blockers<<35 | blockers<<42; Bitboard blocked_moves = blocked_slide & nw_moves[index]; return ~blocked_moves & (nw_moves[index] & enemy_and_empty); } PIECE ChessBoard::getPiece(int index) { Bitboard bit = 1LL << index; if (_whitePawns & bit) return WHITE_PAWN; if (_blackPawns & bit) return BLACK_PAWN; if (_whiteKnights & bit) return WHITE_KNIGHT; if (_blackKnights & bit) return BLACK_KNIGHT; if (_whiteBishops & bit) return WHITE_BISHOP; if (_blackBishops & bit) return BLACK_BISHOP; if (_whiteRooks & bit) return WHITE_ROOK; if (_blackRooks & bit) return BLACK_ROOK; if (_whiteQueens & bit) return WHITE_QUEEN; if (_blackQueens & bit) return BLACK_QUEEN; if (_whiteKings & bit) return WHITE_KING; if (_blackKings & bit) return BLACK_KING; return NONE; }
[ [ [ 1, 320 ] ] ]
1a0535c1dc9e46e99ce1b1659674f2d6afa670b4
02c2e62bcb9a54738bfbd95693978b8709e88fdb
/opencv/cvlinefit.cpp
97f7558c07b8a850360abbaf748b83663983ad2c
[]
no_license
ThadeuFerreira/sift-coprojeto
7ab823926e135f0ac388ae267c40e7069e39553a
bba43ef6fa37561621eb5f2126e5aa7d1c3f7024
refs/heads/master
2021-01-10T15:15:21.698124
2009-05-08T17:38:51
2009-05-08T17:38:51
45,042,655
0
0
null
null
null
null
UTF-8
C++
false
false
18,734
cpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ #include "_cv.h" #define _FP double static CvStatus icvFitLine2D_wods( CvPoint2D32f * points, int _count, float *weights, float *line ) { _FP x = 0, y = 0, x2 = 0, y2 = 0, xy = 0, w = 0; _FP dx2, dy2, dxy; int i; int count = _count; float t; /* Calculating the average of x and y... */ if( weights == 0 ) { for( i = 0; i < count; i += 1 ) { x += points[i].x; y += points[i].y; x2 += points[i].x * points[i].x; y2 += points[i].y * points[i].y; xy += points[i].x * points[i].y; } w = (float) count; } else { for( i = 0; i < count; i += 1 ) { x += weights[i] * points[i].x; y += weights[i] * points[i].y; x2 += weights[i] * points[i].x * points[i].x; y2 += weights[i] * points[i].y * points[i].y; xy += weights[i] * points[i].x * points[i].y; w += weights[i]; } } x /= w; y /= w; x2 /= w; y2 /= w; xy /= w; dx2 = x2 - x * x; dy2 = y2 - y * y; dxy = xy - x * y; t = (float) atan2( 2 * dxy, dx2 - dy2 ) / 2; line[0] = (float) cos( t ); line[1] = (float) sin( t ); line[2] = (float) x; line[3] = (float) y; return CV_NO_ERR; } static CvStatus icvFitLine3D_wods( CvPoint3D32f * points, int count, float *weights, float *line ) { int i; float w0 = 0; float x0 = 0, y0 = 0, z0 = 0; float x2 = 0, y2 = 0, z2 = 0, xy = 0, yz = 0, xz = 0; float dx2, dy2, dz2, dxy, dxz, dyz; float *v; float n; float det[9], evc[9], evl[3]; memset( evl, 0, 3*sizeof(evl[0])); memset( evc, 0, 9*sizeof(evl[0])); if( weights ) { for( i = 0; i < count; i++ ) { float x = points[i].x; float y = points[i].y; float z = points[i].z; float w = weights[i]; x2 += x * x * w; xy += x * y * w; xz += x * z * w; y2 += y * y * w; yz += y * z * w; z2 += z * z * w; x0 += x * w; y0 += y * w; z0 += z * w; w0 += w; } } else { for( i = 0; i < count; i++ ) { float x = points[i].x; float y = points[i].y; float z = points[i].z; x2 += x * x; xy += x * y; xz += x * z; y2 += y * y; yz += y * z; z2 += z * z; x0 += x; y0 += y; z0 += z; } w0 = (float) count; } x2 /= w0; xy /= w0; xz /= w0; y2 /= w0; yz /= w0; z2 /= w0; x0 /= w0; y0 /= w0; z0 /= w0; dx2 = x2 - x0 * x0; dxy = xy - x0 * y0; dxz = xz - x0 * z0; dy2 = y2 - y0 * y0; dyz = yz - y0 * z0; dz2 = z2 - z0 * z0; det[0] = dz2 + dy2; det[1] = -dxy; det[2] = -dxz; det[3] = det[1]; det[4] = dx2 + dz2; det[5] = -dyz; det[6] = det[2]; det[7] = det[5]; det[8] = dy2 + dx2; /* Searching for a eigenvector of det corresponding to the minimal eigenvalue */ #if 1 { CvMat _det = cvMat( 3, 3, CV_32F, det ); CvMat _evc = cvMat( 3, 3, CV_32F, evc ); CvMat _evl = cvMat( 3, 1, CV_32F, evl ); cvEigenVV( &_det, &_evc, &_evl, 0 ); i = evl[0] < evl[1] ? (evl[0] < evl[2] ? 0 : 2) : (evl[1] < evl[2] ? 1 : 2); } #else { CvMat _det = cvMat( 3, 3, CV_32F, det ); CvMat _evc = cvMat( 3, 3, CV_32F, evc ); CvMat _evl = cvMat( 1, 3, CV_32F, evl ); cvSVD( &_det, &_evl, &_evc, 0, CV_SVD_MODIFY_A+CV_SVD_U_T ); } i = 2; #endif v = &evc[i * 3]; n = (float) sqrt( (double)v[0] * v[0] + (double)v[1] * v[1] + (double)v[2] * v[2] ); line[0] = v[0] / n; line[1] = v[1] / n; line[2] = v[2] / n; line[3] = x0; line[4] = y0; line[5] = z0; return CV_NO_ERR; } static void icvCalcDist2D( CvPoint2D32f * points, int count, float *_line, float *dist ) { int j; float px = _line[2], py = _line[3]; float nx = _line[1], ny = -_line[0]; for( j = 0; j < count; j++ ) { float x, y; x = points[j].x - px; y = points[j].y - py; dist[j] = (float) fabs( nx * x + ny * y ); } } static void icvCalcDist3D( CvPoint3D32f * points, int count, float *_line, float *dist ) { int j; float px = _line[3], py = _line[4], pz = _line[5]; float vx = _line[0], vy = _line[1], vz = _line[2]; for( j = 0; j < count; j++ ) { float x, y, z; double p1, p2, p3; x = points[j].x - px; y = points[j].y - py; z = points[j].z - pz; p1 = vy * z - vz * y; p2 = vz * x - vx * z; p3 = vx * y - vy * x; dist[j] = (float) sqrt( p1*p1 + p2*p2 + p3*p3 ); } } static void icvWeightL1( float *d, int count, float *w ) { int i; for( i = 0; i < count; i++ ) { w[i] = 1 / (float) fabs( (double) d[i] ); } } static void icvWeightL12( float *d, int count, float *w ) { int i; for( i = 0; i < count; i++ ) { w[i] = 1.0f / (float) sqrt( 1 + (double) (d[i] * d[i] * 0.5) ); } } static void icvWeightHuber( float *d, int count, float *w, float _c ) { int i; const float c = _c <= 0 ? 1.345f : _c; for( i = 0; i < count; i++ ) { if( d[i] < c ) w[i] = 1.0f; else w[i] = c/d[i]; } } static void icvWeightFair( float *d, int count, float *w, float _c ) { int i; const float c = _c == 0 ? 1 / 1.3998f : 1 / _c; for( i = 0; i < count; i++ ) { w[i] = 1 / (1 + d[i] * c); } } static void icvWeightWelsch( float *d, int count, float *w, float _c ) { int i; const float c = _c == 0 ? 1 / 2.9846f : 1 / _c; for( i = 0; i < count; i++ ) { w[i] = (float) exp( -d[i] * d[i] * c * c ); } } /* Takes an array of 2D points, type of distance (including user-defined distance specified by callbacks, fills the array of four floats with line parameters A, B, C, D, where (A, B) is the normalized direction vector, (C, D) is the point that belongs to the line. */ static CvStatus icvFitLine2D( CvPoint2D32f * points, int count, int dist, float _param, float reps, float aeps, float *line ) { void (*calc_weights) (float *, int, float *) = 0; void (*calc_weights_param) (float *, int, float *, float) = 0; float *w; /* weights */ float *r; /* square distances */ int i; float _line[6], _lineprev[6]; int first = 1; float rdelta = reps != 0 ? reps : 1.0f; float adelta = aeps != 0 ? aeps : 0.01f; CvStatus ret; switch (dist) { case CV_DIST_L2: return icvFitLine2D_wods( points, count, 0, line ); case CV_DIST_L1: calc_weights = icvWeightL1; break; case CV_DIST_L12: calc_weights = icvWeightL12; break; case CV_DIST_FAIR: calc_weights_param = icvWeightFair; break; case CV_DIST_WELSCH: calc_weights_param = icvWeightWelsch; break; case CV_DIST_HUBER: calc_weights_param = icvWeightHuber; break; /*case CV_DIST_USER: calc_weights = (void ( * )(float *, int, float *)) _PFP.fp; break;*/ default: return CV_BADFACTOR_ERR; } w = (float *) cvAlloc( count * sizeof( float )); r = (float *) cvAlloc( count * sizeof( float )); for( i = 0; i < count; i++ ) w[i] = 1.0f; ret = icvFitLine2D_wods( points, count, 0, _line ); for( i = 0; i < 100; i++ ) { if( ret != CV_NO_ERR ) { cvFree( (void**)&w ); cvFree( (void**)&r ); return ret; } if( first ) { first = 0; } else { if( fabs( acos( (float) (_line[0] * _lineprev[0] + _line[1] * _lineprev[1]) )) < adelta ) { float x, y, d; x = (float) fabs( _line[2] - _lineprev[2] ); y = (float) fabs( _line[3] - _lineprev[3] ); d = x > y ? x : y; if( d < rdelta ) { // Return... memcpy( line, _line, 4 * sizeof( float )); cvFree( (void**)&w ); cvFree( (void**)&r ); return CV_NO_ERR; } } } /* calculate distances */ icvCalcDist2D( points, count, _line, r ); /* calculate weights */ if( calc_weights ) { calc_weights( r, count, w ); } else if( calc_weights_param ) { calc_weights_param( r, count, w, _param ); } else { assert( 0 ); return CV_BADFACTOR_ERR; } /* save the line parameters */ memcpy( _lineprev, _line, 4 * sizeof( float )); /* Run again... */ ret = icvFitLine2D_wods( points, count, w, _line ); } cvFree( (void**)&w ); cvFree( (void**)&r ); return CV_BADCONVERGENCE_ERR; } /* Takes an array of 3D points, type of distance (including user-defined distance specified by callbacks, fills the array of four floats with line parameters A, B, C, D, E, F, where (A, B, C) is the normalized direction vector, (D, E, F) is the point that belongs to the line. */ static CvStatus icvFitLine3D( CvPoint3D32f * points, int count, int dist, float _param, float reps, float aeps, float *line ) { void (*calc_weights) (float *, int, float *) = 0; void (*calc_weights_param) (float *, int, float *, float) = 0; float *w; /* weights */ float *r; /* square distances */ int i; float _line[6], _lineprev[6]; int first = 1; float rdelta = reps != 0 ? reps : 1.0f; float adelta = aeps != 0 ? aeps : 0.01f; CvStatus ret; switch (dist) { case CV_DIST_L2: return icvFitLine3D_wods( points, count, 0, line ); case CV_DIST_L1: calc_weights = icvWeightL1; break; case CV_DIST_L12: calc_weights = icvWeightL12; break; case CV_DIST_FAIR: calc_weights_param = icvWeightFair; break; case CV_DIST_WELSCH: calc_weights_param = icvWeightWelsch; break; case CV_DIST_HUBER: calc_weights_param = icvWeightHuber; break; /*case CV_DIST_USER: _PFP.p = param; calc_weights = (void ( * )(float *, int, float *)) _PFP.fp; break;*/ default: return CV_BADFACTOR_ERR; } w = (float *) cvAlloc( count * sizeof( float )); r = (float *) cvAlloc( count * sizeof( float )); for( i = 0; i < count; i++ ) w[i] = 1.0f; ret = icvFitLine3D_wods( points, count, 0, _line ); for( i = 0; i < 100; i++ ) { if( ret != CV_NO_ERR ) { cvFree( (void**)&w ); cvFree( (void**)&r ); return ret; } if( first ) { first = 0; } else { if( fabs ( acos ( (float) (_line[0] * _lineprev[0] + _line[1] * _lineprev[1] + _line[2] * _lineprev[2]) )) < adelta ) { float x, y, z, ax, ay, az, dx, dy, dz, d; x = _line[3] - _lineprev[3]; y = _line[4] - _lineprev[4]; z = _line[5] - _lineprev[5]; ax = _line[0] - _lineprev[0]; ay = _line[1] - _lineprev[1]; az = _line[2] - _lineprev[2]; dx = (float) fabs( y * az - z * ay ); dy = (float) fabs( z * ax - x * az ); dz = (float) fabs( x * ay - y * ax ); d = dx > dy ? (dx > dz ? dx : dz) : (dy > dz ? dy : dz); if( d < rdelta ) { // Return... memcpy( line, _line, 6 * sizeof( float )); cvFree( (void**)&w ); cvFree( (void**)&r ); return CV_NO_ERR; } } } /* calculate distances */ icvCalcDist3D( points, count, _line, r ); /* calculate weights */ if( calc_weights ) { calc_weights( r, count, w ); } else if( calc_weights_param ) { calc_weights_param( r, count, w, _param ); } else { assert( 0 ); return CV_BADFACTOR_ERR; } /* save the line parameters */ memcpy( _lineprev, _line, 6 * sizeof( float )); /* Run again... */ ret = icvFitLine3D_wods( points, count, w, _line ); } cvFree( (void**)&w ); cvFree( (void**)&r ); return CV_BADCONVERGENCE_ERR; } CV_IMPL void cvFitLine( const CvArr* array, int dist, double param, double reps, double aeps, float *line ) { char* buffer = 0; CV_FUNCNAME( "cvFitLine" ); __BEGIN__; char* points = 0; CvContour contour_header; CvSeqBlock block; CvSeq* ptseq = (CvSeq*)array; int type; if( !line ) CV_ERROR( CV_StsNullPtr, "NULL pointer to line parameters" ); if( CV_IS_SEQ(ptseq) ) { type = CV_SEQ_ELTYPE(ptseq); if( ptseq->total == 0 ) CV_ERROR( CV_StsBadSize, "The sequence has no points" ); if( (type!=CV_32FC2 && type!=CV_32FC3 && type!=CV_32SC2 && type!=CV_32SC3) || CV_ELEM_SIZE(type) != ptseq->elem_size ) CV_ERROR( CV_StsUnsupportedFormat, "Input sequence must consist of 2d points or 3d points" ); } else { CvMat* mat = (CvMat*)array; type = CV_MAT_TYPE(mat->type); if( !CV_IS_MAT(mat)) CV_ERROR( CV_StsBadArg, "Input array is not a sequence nor matrix" ); if( !CV_IS_MAT_CONT(mat->type) || (type!=CV_32FC2 && type!=CV_32FC3 && type!=CV_32SC2 && type!=CV_32SC3) || (mat->width != 1 && mat->height != 1)) CV_ERROR( CV_StsBadArg, "Input array must be 1d continuous array of 2d or 3d points" ); CV_CALL( ptseq = cvMakeSeqHeaderForArray( CV_SEQ_KIND_GENERIC|type, sizeof(CvContour), CV_ELEM_SIZE(type), mat->data.ptr, mat->width + mat->height - 1, (CvSeq*)&contour_header, &block )); } if( reps < 0 || aeps < 0 ) CV_ERROR( CV_StsOutOfRange, "Both reps and aeps must be non-negative" ); if( CV_MAT_DEPTH(type) == CV_32F && ptseq->first->next == ptseq->first ) { /* no need to copy data in this case */ points = ptseq->first->data; } else { CV_CALL( buffer = points = (char*)cvAlloc( ptseq->total*CV_ELEM_SIZE(type) )); CV_CALL( cvCvtSeqToArray( ptseq, points, CV_WHOLE_SEQ )); if( CV_MAT_DEPTH(type) != CV_32F ) { int i, total = ptseq->total*CV_MAT_CN(type); assert( CV_MAT_DEPTH(type) == CV_32S ); for( i = 0; i < total; i++ ) ((float*)points)[i] = (float)((int*)points)[i]; } } if( dist == CV_DIST_USER ) CV_ERROR( CV_StsBadArg, "User-defined distance is not allowed" ); if( CV_MAT_CN(type) == 2 ) { IPPI_CALL( icvFitLine2D( (CvPoint2D32f*)points, ptseq->total, dist, (float)param, (float)reps, (float)aeps, line )); } else { IPPI_CALL( icvFitLine3D( (CvPoint3D32f*)points, ptseq->total, dist, (float)param, (float)reps, (float)aeps, line )); } __END__; cvFree( (void**)&buffer ); } /* End of file. */
[ [ [ 1, 676 ] ] ]
e0cf9f62d78b658852bc0a8732e07c529ace1db8
a0e7d52a0b5231a64adf61ebce5bdfe82814cbd0
/exept.h
3d7fdb3344fba243b48141a799db895bbeab6e9b
[]
no_license
cthulhu/smart-bugs
435296ffe88ed3497a6050de474227feb25096c1
5fa11aa4eae32991596ed383475730d2df7b9156
refs/heads/master
2021-01-20T11:06:29.319229
2009-09-29T06:55:34
2009-09-29T06:55:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
298
h
#ifndef _EXEPTION_H_ #define _EXEPTION_H_ class eExeption { protected: std::string strExeptionMessage; public: eExeption(std::string strExeptionMsg):strExeptionMessage(strExeptionMsg){} eExeption():strExeptionMessage(""){} std::string ExeptionStr(void); ~eExeption(){} }; #endif
[ [ [ 1, 14 ] ] ]
dc3e8f104ebdaf6edfd363ef82e6a59a2afdc543
898bce7e226fcd51aa6cacfa73ffbbecf9a8425b
/src/core/NppPlugin.cpp
9d2812b8c5bc88c6665973380795f8ab866d0471
[]
no_license
azhai/IndentByFold
a1b966255f34e97eb7940e165c67800a403c5a0a
45e193ab4f8c413c0090633893eaad815181bfc2
refs/heads/master
2021-01-01T03:53:56.723994
2011-09-18T19:21:49
2011-09-18T19:21:49
58,097,931
0
0
null
null
null
null
UTF-8
C++
false
false
987
cpp
#include "NppPlugin.h" CNppPlugin::CNppPlugin() { m_hDllModule = NULL; m_szDllFileName[0] = 0; m_szIniFileName[0] = 0; } CNppPlugin::~CNppPlugin() { } void CNppPlugin::OnDllProcessAttach( HINSTANCE hDLLInstance ) { int nLen; TCHAR szPath[2*MAX_PATH + 1]; m_hDllModule = ( HMODULE ) hDLLInstance; nLen = ( int ) ::GetModuleFileName( m_hDllModule, szPath, 2*MAX_PATH ); while ( nLen-- > 0 ) { if ( ( szPath[nLen] == _T( '\\' ) ) || ( szPath[nLen] == _T( '/' ) ) ) { lstrcpy( m_szDllFileName, szPath + nLen + 1 ); lstrcpy( m_szIniFileName, m_szDllFileName ); break; } } nLen = lstrlen( m_szIniFileName ); while ( nLen-- > 0 ) { if ( m_szIniFileName[nLen] == _T( '.' ) ) { lstrcpy( m_szIniFileName + nLen + 1, _T( "ini" ) ); break; } } } void CNppPlugin::OnDllProcessDetach() const { } void CNppPlugin::nppSetInfo( const NppData& nppd ) { m_nppMsgr.setNppData( nppd ); OnNppSetInfo( nppd ); }
[ [ [ 1, 49 ] ] ]
e868fe6198d0c5e8203ab2a33d653cfb78846e14
2b3ff42b129d9af57079558a41e826089ab570c2
/0.99.x/lib/Source/SpTBX/SpTBXExtEditors.hpp
1c8d4bfe6d75f3e4941ceee0d1d53261377ebeae
[]
no_license
bravesoftdz/contexteditor-1
07c242f7080846aa56b62b4d0e7790ecbb0167da
9f26c456cda4d7546217fed6557bf2440ca097fd
refs/heads/master
2020-03-25T18:36:18.350531
2009-08-25T01:34:08
2009-08-25T01:34:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,842
hpp
// CodeGear C++Builder // Copyright (c) 1995, 2008 by CodeGear // All rights reserved // (DO NOT EDIT: machine generated header) 'Sptbxexteditors.pas' rev: 20.00 #ifndef SptbxexteditorsHPP #define SptbxexteditorsHPP #pragma delphiheader begin #pragma option push #pragma option -w- // All warnings off #pragma option -Vx // Zero-length empty class member functions #pragma pack(push,8) #include <System.hpp> // Pascal unit #include <Sysinit.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <Sysutils.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Graphics.hpp> // Pascal unit #include <Imglist.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Menus.hpp> // Pascal unit #include <Stdctrls.hpp> // Pascal unit #include <Extctrls.hpp> // Pascal unit #include <Sptbxskins.hpp> // Pascal unit #include <Sptbxitem.hpp> // Pascal unit #include <Sptbxeditors.hpp> // Pascal unit #include <Sptbxcontrols.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Sptbxexteditors { //-- type declarations ------------------------------------------------------- #pragma option push -b- enum TSpTBXColorListBoxStyle { clbsStandardColors, clbsSystemColors, clbsIncludeNone, clbsIncludeDefault, clbsCustomColor, clbsPrettyNames, clbsNoneAsTransparent }; #pragma option pop typedef Set<TSpTBXColorListBoxStyle, clbsStandardColors, clbsNoneAsTransparent> TSpTBXColorListBoxStyles; class DELPHICLASS TSpTBXColorEditButton; class PASCALIMPLEMENTATION TSpTBXColorEditButton : public Sptbxeditors::TSpTBXEditButton { typedef Sptbxeditors::TSpTBXEditButton inherited; private: Graphics::TColor FSelectedColor; void __fastcall SetSelectedColor(const Graphics::TColor Value); protected: virtual bool __fastcall DoDrawItem(Graphics::TCanvas* ACanvas, const Types::TRect &ARect, const Sptbxitem::TSpTBXPaintStage PaintStage); virtual Menus::TPopupMenu* __fastcall GetInternalDropDownMenu(void); public: __property Graphics::TColor SelectedColor = {read=FSelectedColor, write=SetSelectedColor, nodefault}; public: /* TSpTBXEditButton.Create */ inline __fastcall virtual TSpTBXColorEditButton(Classes::TComponent* AOwner) : Sptbxeditors::TSpTBXEditButton(AOwner) { } public: /* TSpTBXCustomButton.Destroy */ inline __fastcall virtual ~TSpTBXColorEditButton(void) { } public: /* TWinControl.CreateParented */ inline __fastcall TSpTBXColorEditButton(HWND ParentWindow) : Sptbxeditors::TSpTBXEditButton(ParentWindow) { } }; class DELPHICLASS TSpTBXColorEdit; class PASCALIMPLEMENTATION TSpTBXColorEdit : public Sptbxeditors::TSpTBXEdit { typedef Sptbxeditors::TSpTBXEdit inherited; private: TSpTBXColorEditButton* FColorButton; Sptbxskins::TSpTBXColorTextType FSelectedFormat; Classes::TNotifyEvent FOnSelectedColorChanged; Graphics::TColor __fastcall GetSelectedColor(void); void __fastcall SetSelectedColor(const Graphics::TColor Value); void __fastcall SetSelectedFormat(const Sptbxskins::TSpTBXColorTextType Value); HIDESBASE MESSAGE void __fastcall CMExit(Messages::TWMNoParams &Message); protected: DYNAMIC void __fastcall KeyPress(System::WideChar &Key); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); virtual void __fastcall DoSelectedColorChanged(void); void __fastcall UpdateTextFromValue(void); void __fastcall UpdateValueFromText(bool RevertWhenInvalid = true); public: __fastcall virtual TSpTBXColorEdit(Classes::TComponent* AOwner); __fastcall virtual ~TSpTBXColorEdit(void); __property TSpTBXColorEditButton* ColorButton = {read=FColorButton}; __published: __property Text = {stored=false}; __property Graphics::TColor SelectedColor = {read=GetSelectedColor, write=SetSelectedColor, nodefault}; __property Sptbxskins::TSpTBXColorTextType SelectedFormat = {read=FSelectedFormat, write=SetSelectedFormat, default=2}; __property Classes::TNotifyEvent OnSelectedColorChanged = {read=FOnSelectedColorChanged, write=FOnSelectedColorChanged}; public: /* TWinControl.CreateParented */ inline __fastcall TSpTBXColorEdit(HWND ParentWindow) : Sptbxeditors::TSpTBXEdit(ParentWindow) { } }; class DELPHICLASS TSpTBXFontComboBoxPreview; class PASCALIMPLEMENTATION TSpTBXFontComboBoxPreview : public Controls::TCustomControl { typedef Controls::TCustomControl inherited; private: Extctrls::TPanel* FPreviewPanel; protected: virtual void __fastcall CreateParams(Controls::TCreateParams &Params); public: __fastcall virtual TSpTBXFontComboBoxPreview(Classes::TComponent* AOwner); __fastcall virtual ~TSpTBXFontComboBoxPreview(void); __property Extctrls::TPanel* PreviewPanel = {read=FPreviewPanel}; public: /* TWinControl.CreateParented */ inline __fastcall TSpTBXFontComboBoxPreview(HWND ParentWindow) : Controls::TCustomControl(ParentWindow) { } }; class DELPHICLASS TSpTBXFontComboBox; class PASCALIMPLEMENTATION TSpTBXFontComboBox : public Sptbxeditors::TSpTBXComboBox { typedef Sptbxeditors::TSpTBXComboBox inherited; private: bool FFontPreview; bool FFontNamePreview; int FMaxMRUItems; int FMRUCount; TSpTBXFontComboBoxPreview* FPreviewWindow; Graphics::TFontName FSelectedFont; Sptbxeditors::TSpTBXEditGetTextEvent FOnFontPreview; void __fastcall UpdateSelectedFont(bool AddMRU); void __fastcall SetFontNamePreview(const bool Value); void __fastcall SetSelectedFont(const Graphics::TFontName Value); void __fastcall SetMaxMRUItems(int Value); void __fastcall SetFontPreview(const bool Value); protected: virtual void __fastcall CreateWnd(void); DYNAMIC void __fastcall Click(void); DYNAMIC void __fastcall CloseUp(void); DYNAMIC void __fastcall DropDown(void); virtual void __fastcall DrawItem(int Index, const Types::TRect &Rect, Windows::TOwnerDrawState State); public: __fastcall virtual TSpTBXFontComboBox(Classes::TComponent* AOwner); __fastcall virtual ~TSpTBXFontComboBox(void); __property int MRUCount = {read=FMRUCount, nodefault}; __published: __property Items = {stored=false}; __property AutoItemHeight = {default=0}; __property bool FontPreview = {read=FFontPreview, write=SetFontPreview, default=1}; __property bool FontNamePreview = {read=FFontNamePreview, write=SetFontNamePreview, default=1}; __property int MaxMRUItems = {read=FMaxMRUItems, write=SetMaxMRUItems, default=5}; __property Graphics::TFontName SelectedFont = {read=FSelectedFont, write=SetSelectedFont}; __property Sptbxeditors::TSpTBXEditGetTextEvent OnFontPreview = {read=FOnFontPreview, write=FOnFontPreview}; public: /* TWinControl.CreateParented */ inline __fastcall TSpTBXFontComboBox(HWND ParentWindow) : Sptbxeditors::TSpTBXComboBox(ParentWindow) { } }; class DELPHICLASS TSpTBXColorListBox; class PASCALIMPLEMENTATION TSpTBXColorListBox : public Sptbxeditors::TSpTBXListBox { typedef Sptbxeditors::TSpTBXListBox inherited; private: bool FItems; bool FNeedToPopulate; Graphics::TColor FSelectedColor; TSpTBXColorListBoxStyles FStyle; void __fastcall ColorCallBack(const System::UnicodeString AName); System::UnicodeString __fastcall GetColorName(int Index); Graphics::TColor __fastcall GetColor(int Index); HIDESBASE Graphics::TColor __fastcall GetSelected(void); HIDESBASE void __fastcall SetSelected(const Graphics::TColor Value); HIDESBASE void __fastcall SetStyle(const TSpTBXColorListBoxStyles Value); protected: virtual void __fastcall CreateWnd(void); virtual void __fastcall Loaded(void); DYNAMIC void __fastcall DblClick(void); DYNAMIC void __fastcall KeyPress(System::WideChar &Key); virtual void __fastcall DoDrawItem(Graphics::TCanvas* ACanvas, Types::TRect &ARect, int Index, const Windows::TOwnerDrawState State, const Sptbxitem::TSpTBXPaintStage PaintStage, bool &PaintDefault); bool __fastcall PickCustomColor(void); void __fastcall PopulateList(void); public: __fastcall virtual TSpTBXColorListBox(Classes::TComponent* AOwner); void __fastcall AddColor(Graphics::TColor AColor, System::UnicodeString AColorName); int __fastcall ColorCount(void); __property Graphics::TColor Colors[int Index] = {read=GetColor}; __property System::UnicodeString ColorNames[int Index] = {read=GetColorName}; __published: __property bool Items = {read=FItems, nodefault}; __property Graphics::TColor Selected = {read=GetSelected, write=SetSelected, default=0}; __property TSpTBXColorListBoxStyles Style = {read=FStyle, write=SetStyle, default=67}; public: /* TSpTBXListBox.Destroy */ inline __fastcall virtual ~TSpTBXColorListBox(void) { } public: /* TWinControl.CreateParented */ inline __fastcall TSpTBXColorListBox(HWND ParentWindow) : Sptbxeditors::TSpTBXListBox(ParentWindow) { } }; //-- var, const, procedure --------------------------------------------------- extern PACKAGE Controls::TImageList* FontGlyphImgList; extern PACKAGE void __fastcall SpFillFontNames(Classes::TStrings* ADest); extern PACKAGE void __fastcall SpCalcMaxDropDownWidth(Sptbxeditors::TSpTBXComboBox* Combo); extern PACKAGE void __fastcall SpDrawCheckeredBackground(Graphics::TCanvas* ACanvas, const Types::TRect &ARect); extern PACKAGE void __fastcall SpDrawColorDropDownButton(Graphics::TCanvas* ACanvas, const Types::TRect &ARect, bool Pushed, Graphics::TColor AColor, bool CheckeredBkgndWhenTransparent = true); } /* namespace Sptbxexteditors */ using namespace Sptbxexteditors; #pragma pack(pop) #pragma option pop #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // SptbxexteditorsHPP
[ "[email protected]@5d03d0dc-17f0-11de-b413-eb0469710719" ]
[ [ [ 1, 234 ] ] ]
e512ad6d4c73955f218bb1e9d1dc949def687fc1
5e5e02f7663d86089d87d47aebf609ec6dbcf97c
/Paccy.cpp
aa9ec60fc32b6a8db44ced9865e51b2fb37e3767
[]
no_license
mcejp/PacWorld
3483fce6512848dbc45dcea33a558b522faf24e2
b900387ac36d3f2f226c4534cd34ba90c7e7e9c3
refs/heads/master
2020-05-18T17:23:10.795308
2000-10-08T09:22:14
2019-05-02T09:22:14
184,553,619
2
0
null
null
null
null
ISO-8859-1
C++
false
false
3,136
cpp
// Paccy.cpp: Implementierung der Klasse CPaccy. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "stdafx.h" #include "Paccy.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif static int LEFT=1; static int RIGHT=2; static int UP=3; static int DOWN=4; ////////////////////////////////////////////////////////////////////// // Konstruktion/Destruktion ////////////////////////////////////////////////////////////////////// CPaccy::CPaccy() { pc1.Start(); moving=RIGHT; //Anfangsrichtung lives=3; alive=true; } CPaccy::~CPaccy() { } void CPaccy::MovePaccy() { //pc1 ist der Taktgeber fรผr die Framerate UINT sp; //normal: 10 und 14 int s1=8; int s2=12; if(chase||doped)sp=s1; else sp=s2; if(pc1.GetValue()>sp) { v=1; pc1.Reset(); } else v=0; int i; bool onVBorder=false; //Paccy auf der vert. Grenzlinie? bool onHBorder=false; //Paccy auf der horiz. Grenzlinie? int offX=5; int offY=5; bool canMoveUp=false; bool canMoveDown=false; bool canMoveLeft=false; bool canMoveRight=false; locX=(x+13)/32+1; locY=(y+13)/32+1; ///Kachel unter Paccy identifizieren/// int type=Map->GetTile(locX,locY); tile=type; int above=Map->GetTile(locX,locY-1); int below=Map->GetTile(locX,locY+1); int leftHand=Map->GetTile(locX-1,locY); int rightHand=Map->GetTile(locX+1,locY); //////32 x 32 Raster/////////// for(i=0;i<15;i++) { if(x==(i*32+offX))//x liegt im vert. Raster { canMoveDown=true; canMoveUp=true; onVBorder=true; } } for(i=0;i<13;i++) { if(y==(i*32+offY))//y liegt im horiz. Raster { canMoveLeft=true; canMoveRight=true; onHBorder=true; } } //Kachelwert bis 6 = passierbar if(onVBorder&&rightHand>6) canMoveRight=false; if(onVBorder&&leftHand>6) canMoveLeft=false; if(onHBorder&&above>6) canMoveUp=false; if(onHBorder&&below>6) canMoveDown=false; if(keyRight&&canMoveRight) {right=true;left=false;up=false;down=false;} if(keyLeft&&canMoveLeft) {right=false;left=true;up=false;down=false;} if(keyUp&&canMoveUp) {right=false;left=false;up=true;down=false;} if(keyDown&&canMoveDown) {right=false;left=false;up=false;down=true;} if(right&&canMoveRight) {x+=v; moving=RIGHT;} else if(left&&canMoveLeft) {x-=v; moving=LEFT;} else if(down&&canMoveDown) {y+=v; moving=DOWN;} else if(up&&canMoveUp) {y-=v; moving=UP;} else moving=0; int vanish1=-30; int vanish2=488; if(x<vanish1&&y==leftPassage) {x=vanish2; y=rightPassage;} if(x>vanish2&&y==rightPassage) {x=vanish1; y=leftPassage;} } void CPaccy::SetMap(CDXMap *map) { Map=map; } void CPaccy::SetStartPos(int x, int y) { this->x=x*32+5; this->y=y*32+5; } void CPaccy::SetPassages(int y1, int y2) { leftPassage=y1*32+5; rightPassage=y2*32+5; } void CPaccy::Kill() { if(lives<1) alive=false; right=left=up=down=false; keyUp=keyDown=keyLeft=keyRight=false; }
[ [ [ 1, 171 ] ] ]
47e54d577a337153248851b140f920faa992e2b2
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/WorldModelDebris.cpp
c47c23f5cc7c07f9e58d769e221949c2b88429b6
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
6,481
cpp
// ----------------------------------------------------------------------- // // // MODULE : WorldModelDebris.cpp // // PURPOSE : A WorldModelDebris object // // CREATED : 2/27/98 // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "WorldModelDebris.h" #include "ServerUtilities.h" #include <stdio.h> LINKFROM_MODULE( WorldModelDebris ); #pragma force_active on BEGIN_CLASS(WorldModelDebris) END_CLASS_DEFAULT_FLAGS(WorldModelDebris, Door, NULL, NULL, CF_WORLDMODEL) #pragma force_active off // ----------------------------------------------------------------------- // // // ROUTINE: WorldModelDebris::WorldModelDebris() // // PURPOSE: Initialize object // // ----------------------------------------------------------------------- // WorldModelDebris::WorldModelDebris() : Door() { m_bRotate = LTTRUE; m_fXRotVel = 0.0f; m_fYRotVel = 0.0f; m_fZRotVel = 0.0f; m_fLastTime = 0.0f; m_fPitch = 0.0f; m_fYaw = 0.0f; m_fRoll = 0.0f; } // ----------------------------------------------------------------------- // // // ROUTINE: WorldModelDebris::Setup // // PURPOSE: Set up a WorldModelDebris with the information needed // // ----------------------------------------------------------------------- // void WorldModelDebris::Start(LTVector *pvRotationPeriods, LTVector* pvVel) { if (!pvRotationPeriods || !pvVel) return; LTFLOAT fMag = VEC_MAGSQR(*pvRotationPeriods); if (fMag > 0.001f) { m_bRotate = LTTRUE; if (pvRotationPeriods->x < -0.001 || 0.001f < pvRotationPeriods->x) { m_fXRotVel = MATH_CIRCLE / pvRotationPeriods->x; } if (pvRotationPeriods->y < -0.001 || 0.001f < pvRotationPeriods->y) { m_fXRotVel = MATH_CIRCLE / pvRotationPeriods->y; } if (pvRotationPeriods->z < -0.001 || 0.001f < pvRotationPeriods->z) { m_fXRotVel = MATH_CIRCLE / pvRotationPeriods->z; } } uint32 dwFlags = FLAG_VISIBLE | FLAG_GRAVITY | FLAG_RAYHIT; g_pCommonLT->SetObjectFlags(m_hObject, OFT_Flags, dwFlags, FLAGMASK_ALL); SetNextUpdate(UPDATE_NEXT_FRAME); g_pPhysicsLT->SetVelocity(m_hObject, (LTVector*)pvVel); g_pLTServer->SetBlockingPriority(m_hObject, 100); g_pPhysicsLT->SetForceIgnoreLimit(m_hObject, 0.0f); g_pPhysicsLT->SetFrictionCoefficient(m_hObject, GetRandom(10.0f, 20.0f)); m_fLastTime = g_pLTServer->GetTime(); } // --------------------------------------------------------------------------- // // // ROUTINE: WorldModelDebris::EngineMessageFn() // // PURPOSE: Handler for engine messages // // --------------------------------------------------------------------------- // uint32 WorldModelDebris::EngineMessageFn(uint32 messageID, void *pData, float fData) { switch (messageID) { case MID_UPDATE: { Update(); } break; case MID_PRECREATE: { if (fData == PRECREATE_WORLDFILE) { ReadProp((ObjectCreateStruct*)pData); } } break; case MID_SAVEOBJECT: { Save((ILTMessage_Write*)pData, (uint32)fData); } break; case MID_LOADOBJECT: { Load((ILTMessage_Read*)pData, (uint32)fData); } break; default : break; } return Door::EngineMessageFn(messageID, pData, fData); } // --------------------------------------------------------------------------- // // // ROUTINE: WorldModelDebris::ReadProp() // // PURPOSE: Reads WorldModelDebris properties // // --------------------------------------------------------------------------- // void WorldModelDebris::ReadProp(ObjectCreateStruct *pStruct) { LTVector vAngles; if (g_pLTServer->GetPropRotationEuler("Rotation", &vAngles) == LT_OK) { // Set initial pitch, yaw, roll... m_fPitch = vAngles.x; m_fYaw = vAngles.y; m_fRoll = vAngles.z; } } // ----------------------------------------------------------------------- // // // ROUTINE: WorldModelDebris::Update // // PURPOSE: Update the WorldModelDebris // // ----------------------------------------------------------------------- // void WorldModelDebris::Update() { CollisionInfo standingInfo; if (m_bRotate) { SetNextUpdate(UPDATE_NEXT_FRAME); g_pLTServer->GetStandingOn(m_hObject, &standingInfo); if (standingInfo.m_hObject) { m_bRotate = LTFALSE; } else { UpdateRotation(); } } else { SetNextUpdate(UPDATE_NEVER); } } // ----------------------------------------------------------------------- // // // ROUTINE: WorldModelDebris::UpdateRotation // // PURPOSE: Update Rotation // // ----------------------------------------------------------------------- // void WorldModelDebris::UpdateRotation() { LTFLOAT fTime = g_pLTServer->GetTime(); LTFLOAT fDeltaTime = fTime - m_fLastTime; LTRotation rRot; g_pLTServer->GetObjectRotation(m_hObject, &rRot); if (m_fXRotVel < 0.0f || 0.0f < m_fXRotVel) { m_fPitch += m_fXRotVel * fDeltaTime; } if (m_fYRotVel < 0.0f || 0.0f < m_fYRotVel) { m_fYaw += m_fYRotVel * fDeltaTime; } if (m_fZRotVel < 0.0f || 0.0f < m_fZRotVel) { m_fRoll += m_fZRotVel * fDeltaTime; } rRot = LTRotation(m_fPitch, m_fYaw, m_fRoll); g_pLTServer->SetObjectRotation(m_hObject, &rRot); m_fLastTime = fTime; } // ----------------------------------------------------------------------- // // // ROUTINE: WorldModelDebris::Save // // PURPOSE: Save the object // // ----------------------------------------------------------------------- // void WorldModelDebris::Save(ILTMessage_Write *pMsg, uint32 dwSaveFlags) { if (!pMsg) return; SAVE_BOOL(m_bRotate); SAVE_FLOAT(m_fXRotVel); SAVE_FLOAT(m_fYRotVel); SAVE_FLOAT(m_fZRotVel); SAVE_FLOAT(m_fPitch); SAVE_FLOAT(m_fYaw); SAVE_FLOAT(m_fRoll); SAVE_TIME(m_fLastTime); } // ----------------------------------------------------------------------- // // // ROUTINE: WorldModelDebris::Load // // PURPOSE: Load the object // // ----------------------------------------------------------------------- // void WorldModelDebris::Load(ILTMessage_Read *pMsg, uint32 dwLoadFlags) { if (!pMsg) return; LOAD_BOOL(m_bRotate); LOAD_FLOAT(m_fXRotVel); LOAD_FLOAT(m_fYRotVel); LOAD_FLOAT(m_fZRotVel); LOAD_FLOAT(m_fPitch); LOAD_FLOAT(m_fYaw); LOAD_FLOAT(m_fRoll); LOAD_TIME(m_fLastTime); }
[ [ [ 1, 266 ] ] ]
f8965b671fddce0ca3e55b16d6e2b842b1369737
d9a78f212155bb978f5ac27d30eb0489bca87c3f
/PB/src/PbLib/GeneratedFiles/Release/moc_pbgameoptions.cpp
3635eaa027265fcc30da18c5a269a32f85403f3f
[]
no_license
marchon/pokerbridge
1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c
97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9
refs/heads/master
2021-01-10T07:15:26.496252
2010-05-17T20:01:29
2010-05-17T20:01:29
36,398,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,755
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'pbgameoptions.h' ** ** Created: Fri 2. Apr 21:30:27 2010 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "stdafx.h" #include "..\..\pbgameoptions.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'pbgameoptions.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_PBGameOptions[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 1, 12, // enums/sets 0, 0, // constructors // enums: name, flags, count, data 14, 0x0, 6, 16, // enum data: key, value 27, uint(PBGameOptions::FullRing), 36, uint(PBGameOptions::NoLimit), 44, uint(PBGameOptions::Limit), 50, uint(PBGameOptions::SNG), 54, uint(PBGameOptions::MTT), 58, uint(PBGameOptions::Cash), 0 // eod }; static const char qt_meta_stringdata_PBGameOptions[] = { "PBGameOptions\0EGameOptions\0FullRing\0" "NoLimit\0Limit\0SNG\0MTT\0Cash\0" }; const QMetaObject PBGameOptions::staticMetaObject = { { 0, qt_meta_stringdata_PBGameOptions, qt_meta_data_PBGameOptions, 0 } }; QT_END_MOC_NAMESPACE
[ [ [ 1, 55 ] ] ]
58a44418d89501524c9f55326ba6bdca0fd1272d
cfc9acc69752245f30ad3994cce0741120e54eac
/bikini/include/bikini/flash/renderer.hpp
66960411f4f7ec3b0c98f08b6434fed4bf9cb807
[]
no_license
Heartbroken/bikini-iii
3b7852d1af722b380864ac87df57c37862eb759b
93ffa5d43d9179b7c5e7f7c2df9df7dafd79a739
refs/heads/master
2020-03-28T00:41:36.281253
2009-04-30T14:58:10
2009-04-30T14:58:10
37,190,689
0
0
null
null
null
null
UTF-8
C++
false
false
606
hpp
/*---------------------------------------------------------------------------------------------*//* Binary Kinematics 3 - C++ Game Programming Library Copyright (C) 2008 Viktor Reutzky [email protected] *//*---------------------------------------------------------------------------------------------*/ #pragma once struct renderer { virtual ~renderer() {} virtual void draw_line(const real2 &_s, const real2 &_e, const color &_c, real _width) = 0; virtual void draw_tris(const real2 *_points, const uint *_tris, uint _count, const color &_c, const r3x3 &_position) = 0; };
[ "my.mass.storage@f4697e32-284f-0410-9ba2-936c71724aef" ]
[ [ [ 1, 15 ] ] ]
dd51e0b57a14289cbe9fd6ab36ca4c8f252b257f
d37a1d5e50105d82427e8bf3642ba6f3e56e06b8
/DVR/DVRMD_Filter/DVRMD_Filter/XColorStatic.cpp
220492bf3c6a5ca41a3e7f0d9661fda848c94f2e
[]
no_license
080278/dvrmd-filter
176f4406dbb437fb5e67159b6cdce8c0f48fe0ca
b9461f3bf4a07b4c16e337e9c1d5683193498227
refs/heads/master
2016-09-10T21:14:44.669128
2011-10-17T09:18:09
2011-10-17T09:18:09
32,274,136
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
6,946
cpp
// XColorStatic.cpp Version 1.0 // // Author: Hans Dietrich // [email protected] // // This software is released into the public domain. // You are free to use it in any way you like. // // This software is provided "as is" with no expressed // or implied warranty. I accept no liability for any // damage or loss of business that this software may cause. // /////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "XColorStatic.h" #include "FontSize.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////////// // CXColorStatic BEGIN_MESSAGE_MAP(CXColorStatic, CStatic) //{{AFX_MSG_MAP(CXColorStatic) ON_WM_PAINT() ON_WM_ERASEBKGND() //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////////// // ctor CXColorStatic::CXColorStatic() { m_rgbText = GetSysColor(COLOR_BTNTEXT); m_rgbBackground = GetSysColor(COLOR_BTNFACE); m_pBrush = new CBrush(m_rgbBackground); m_bBold = FALSE; m_hIcon = NULL; m_nXMargin = 0; m_nYMargin = 0; m_strText = _T(""); } /////////////////////////////////////////////////////////////////////////////// // dtor CXColorStatic::~CXColorStatic() { TRACE(_T("in CXColorStatic::~CXColorStatic\n")); if (m_font.GetSafeHandle()) { m_font.DeleteObject(); } if (m_pBrush) { m_pBrush->DeleteObject(); delete m_pBrush; } m_pBrush = NULL; } /////////////////////////////////////////////////////////////////////////////// // PreSubclassWindow void CXColorStatic::PreSubclassWindow() { TRACE(_T("in CXColorStatic::PreSubclassWindow\n")); // get current font CFont* pFont = GetFont(); if (!pFont) { HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT); if (hFont == NULL) { hFont = (HFONT) GetStockObject(ANSI_VAR_FONT); } if (hFont) { pFont = CFont::FromHandle(hFont); } } ASSERT(pFont); ASSERT(pFont->GetSafeHandle()); // create the font for this control LOGFONT lf; pFont->GetLogFont(&lf); m_font.CreateFontIndirect(&lf); } /////////////////////////////////////////////////////////////////////////////// // OnPaint void CXColorStatic::OnPaint() { CPaintDC dc(this); // device context for painting CRect rect; GetClientRect(rect); CDC memDC; CBitmap memBitmap; CBitmap* pOldBmp = NULL; memDC.CreateCompatibleDC(&dc); memBitmap.CreateCompatibleBitmap(&dc, rect.right, rect.bottom); pOldBmp = memDC.SelectObject(&memBitmap); memDC.SetTextColor(m_rgbText); memDC.SetBkColor(m_rgbBackground); memDC.SetBkMode(OPAQUE); memDC.SelectObject(m_pBrush); memDC.FillRect(&rect, m_pBrush); // cannot have both an icon and text if (m_hIcon) { int nIconX = ::GetSystemMetrics(SM_CXICON); int nIconY = ::GetSystemMetrics(SM_CYICON); rect.left = rect.left + (rect.Width() - nIconX) / 2; rect.top = rect.top + (rect.Height() - nIconY) / 2; memDC.DrawIcon(rect.left, rect.top, m_hIcon); } else { memDC.SelectObject(&m_font); // get static's text // GetWindowText(m_strText); UINT nFormat = 0; DWORD dwStyle = GetStyle(); // set DrawText format from static style settings if (dwStyle & SS_CENTER) { nFormat |= DT_CENTER; } else if (dwStyle & SS_LEFT) { nFormat |= DT_LEFT; } else if (dwStyle & SS_RIGHT) { nFormat |= DT_RIGHT; } if (dwStyle & SS_CENTERIMAGE) // vertical centering ==> single line only { nFormat |= DT_VCENTER | DT_SINGLELINE; } else { nFormat |= DT_WORDBREAK; } rect.left += m_nXMargin; rect.top += m_nYMargin; memDC.DrawText(m_strText, rect, nFormat); } dc.BitBlt(rect.left, rect.top, rect.right, rect.bottom, &memDC, 0, 0, SRCCOPY); //รŠรยทร…ร„รšยดรฆยผรฆรˆรรŽยปรยผ memDC.SelectObject(pOldBmp); memDC.DeleteDC(); memBitmap.DeleteObject(); } /////////////////////////////////////////////////////////////////////////////// // OnEraseBkgnd BOOL CXColorStatic::OnEraseBkgnd(CDC* pDC) { UNREFERENCED_PARAMETER(pDC); return TRUE; //CStatic::OnEraseBkgnd(pDC); } /////////////////////////////////////////////////////////////////////////////// // SetFont void CXColorStatic::SetFont(LOGFONT *pLogFont, BOOL bRedraw /*= TRUE*/) { ASSERT(pLogFont); if (!pLogFont) { return; } if (m_font.GetSafeHandle()) { m_font.DeleteObject(); } LOGFONT lf = *pLogFont; lf.lfWeight = m_bBold ? FW_BOLD : FW_NORMAL; m_font.CreateFontIndirect(&lf); if (bRedraw) { RedrawWindow(); } } /////////////////////////////////////////////////////////////////////////////// // SetFont void CXColorStatic::SetFont(LPCTSTR lpszFaceName, int nPointSize, BOOL bRedraw /*= TRUE*/) { // null face name is ok - we will use current font LOGFONT lf; memset(&lf, 0, sizeof(lf)); if (lpszFaceName == NULL) { CFont *pFont = GetFont(); ASSERT(pFont); pFont->GetLogFont(&lf); } else { _tcsncpy(lf.lfFaceName, lpszFaceName, sizeof(lf.lfFaceName)/sizeof(TCHAR)-1); } lf.lfHeight = GetFontHeight(nPointSize); SetFont(&lf, bRedraw); } /////////////////////////////////////////////////////////////////////////////// // SetFont void CXColorStatic::SetFont(CFont *pFont, BOOL bRedraw /*= TRUE*/) { ASSERT(pFont); if (!pFont) { return; } LOGFONT lf; memset(&lf, 0, sizeof(lf)); pFont->GetLogFont(&lf); SetFont(&lf, bRedraw); } /////////////////////////////////////////////////////////////////////////////// // SetTextColor void CXColorStatic::SetTextColor(COLORREF rgb, BOOL bRedraw /*= TRUE*/) { m_rgbText = rgb; if (bRedraw) { RedrawWindow(); } } /////////////////////////////////////////////////////////////////////////////// // SetBold void CXColorStatic::SetBold(BOOL bFlag, BOOL bRedraw /*= TRUE*/) { m_bBold = bFlag; LOGFONT lf; memset(&lf, 0, sizeof(lf)); CFont *pFont = GetFont(); ASSERT(pFont); pFont->GetLogFont(&lf); lf.lfWeight = m_bBold ? FW_BOLD : FW_NORMAL; SetFont(&lf, bRedraw); } /////////////////////////////////////////////////////////////////////////////// // SetBackgroundColor void CXColorStatic::SetBackgroundColor(COLORREF rgb, BOOL bRedraw /*= TRUE*/) { m_rgbBackground = rgb; if (m_pBrush) { m_pBrush->DeleteObject(); delete m_pBrush; } m_pBrush = new CBrush(m_rgbBackground); if (bRedraw) { RedrawWindow(); } } /////////////////////////////////////////////////////////////////////////////// // SetIcon void CXColorStatic::SetIcon(HICON hIcon, BOOL bRedraw /*= TRUE*/) { ASSERT(hIcon); m_hIcon = hIcon; if (bRedraw) { RedrawWindow(); } }
[ "[email protected]@27769579-7047-b306-4d6f-d36f87483bb3" ]
[ [ [ 1, 316 ] ] ]
adefada5b1a685cc52dab7cc6f723c47e8133111
51628f1076825ea0982f8f7140c6ebd46e75cb8c
/GeneralObjectRecognition/main.cpp
bb91f9ded50dbb265bec8fa12534e8adbb53cb26
[]
no_license
miyabiarts/GeneralObjectRecognition
7bfc271bff801e43c1c1c17d0acbc9775e98267a
17b1c50c1832ca9193d268f8624b6f81bad23f60
refs/heads/master
2021-01-15T17:45:34.271980
2011-09-18T08:44:34
2011-09-18T08:44:34
2,407,782
0
0
null
null
null
null
UTF-8
C++
false
false
107
cpp
#include "Recognizer.h" // int main() { Recognizer recognizer; recognizer(); return 0; }
[ [ [ 1, 10 ] ] ]
d82b51462e8735087a0c71a2767a97265dded4f3
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/player_chat_automute_meaningless_t.hpp
25e5d136df39cdc961bab988db20b6c2e662534c
[]
no_license
neverm1ndo/gta-paradise-sa
d564c1ed661090336621af1dfd04879a9c7db62d
730a89eaa6e8e4afc3395744227527748048c46d
refs/heads/master
2020-04-27T22:00:22.221323
2010-09-04T19:02:28
2010-09-04T19:02:28
174,719,907
1
0
null
2019-03-09T16:44:43
2019-03-09T16:44:43
null
WINDOWS-1251
C++
false
false
1,599
hpp
#ifndef PLAYER_CHAT_AUTOMUTE_MEANINGLESS_T_HPP #define PLAYER_CHAT_AUTOMUTE_MEANINGLESS_T_HPP #include <string> #include <istream> #include <boost/algorithm/string.hpp> struct player_chat_automute_meaningless_chars_type_t { int min_count; // ะœะธะฝะธะผะฐะปัŒะฝะพะต ั‡ะธัะปะพ ัะธะผะฒะพะปะพะฒ ะธะท ะทะฐะดะฐะฝะฝะพะณะพ ะบะปะฐััะฐ, ั‡ั‚ะพะฑั‹ ะฝะฐั‡ะฐั‚ัŒ ัั‡ะธั‚ะฐั‚ัŒ ะผะตั‚ั€ะธะบัƒ (-1 - ะฒัะตะณะดะฐ ัั‡ะธั‚ะฐะตะผ) float min_relative_count; // ะœะธะฝะธะผะฐะปัŒะฝะพะต ะพั‚ะฝะพัะธั‚ะตะปัŒะฝะพะต ั‡ะธัะปะพ ัะธะผะฒะพะปะพะฒ, ั‡ั‚ะพะฑั‹ ะฝะฐั‡ะฐั‚ัŒ ัั‡ะธั‚ะฐั‚ัŒ ะผะตั‚ั€ะธะบัƒ (-1.0f - ะฒัะตะณะดะฐ ัั‡ะธั‚ะฐะตะผ) float mentic_factor; // ะšะพัั„ั„ะธั†ะธะตะฝั‚ ะผะตั‚ั€ะธะบะธ, ะดะปั ะบะปะฐััะฐ ัะธะผะฒะพะปะพะฒ std::string chars; // ะกะธะผะฒะพะปั‹, ะบะปะฐััะฐ ัะธะผะฒะพะปะพะฒ }; template <class char_t, class traits_t> inline std::basic_istream<char_t, traits_t>& operator>>(std::basic_istream<char_t, traits_t>& is, player_chat_automute_meaningless_chars_type_t& chars_type) { is>>chars_type.min_count>>chars_type.min_relative_count>>chars_type.mentic_factor; std::getline(is, chars_type.chars); boost::trim(chars_type.chars); if (is, chars_type.chars.empty()) is, chars_type.chars = " "; return is; } #include "core/serialization/is_streameble.hpp" namespace serialization { template <> struct is_streameble_read <player_chat_automute_meaningless_chars_type_t>: std::tr1::true_type {}; } // namespace serialization { #endif // PLAYER_CHAT_AUTOMUTE_MEANINGLESS_T_HPP
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
[ [ [ 1, 28 ] ] ]
b607ce6e5a0430f95ec8235aa97d144d12d5d514
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/uavobjects/ahrscalibration.h
bab623f7b3e7252335b152db9ca9fdc2a6b13aca
[]
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
5,484
h
/** ****************************************************************************** * * @file ahrscalibration.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @see The GNU Public License (GPL) Version 3 * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup UAVObjectsPlugin UAVObjects Plugin * @{ * * @note Object definition file: ahrscalibration.xml. * This is an automatically generated file. * DO NOT modify manually. * * @brief The UAVUObjects GCS 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 AHRSCALIBRATION_H #define AHRSCALIBRATION_H #include "uavdataobject.h" #include "uavobjectmanager.h" class UAVOBJECTS_EXPORT AHRSCalibration: public UAVDataObject { Q_OBJECT public: // Field structure typedef struct { quint8 measure_var; float accel_bias[3]; float accel_scale[3]; float accel_ortho[3]; float accel_var[3]; float gyro_bias[3]; float gyro_scale[3]; float gyro_var[3]; float mag_bias[3]; float mag_scale[3]; float mag_var[3]; } __attribute__((packed)) DataFields; // Field information // Field measure_var information /* Enumeration options for field measure_var */ typedef enum { MEASURE_VAR_SET=0, MEASURE_VAR_MEASURE=1 } measure_varOptions; // Field accel_bias information /* Array element names for field accel_bias */ typedef enum { ACCEL_BIAS_X=0, ACCEL_BIAS_Y=1, ACCEL_BIAS_Z=2 } accel_biasElem; /* Number of elements for field accel_bias */ static const quint32 ACCEL_BIAS_NUMELEM = 3; // Field accel_scale information /* Array element names for field accel_scale */ typedef enum { ACCEL_SCALE_X=0, ACCEL_SCALE_Y=1, ACCEL_SCALE_Z=2 } accel_scaleElem; /* Number of elements for field accel_scale */ static const quint32 ACCEL_SCALE_NUMELEM = 3; // Field accel_ortho information /* Array element names for field accel_ortho */ typedef enum { ACCEL_ORTHO_XY=0, ACCEL_ORTHO_XZ=1, ACCEL_ORTHO_YZ=2 } accel_orthoElem; /* Number of elements for field accel_ortho */ static const quint32 ACCEL_ORTHO_NUMELEM = 3; // Field accel_var information /* Array element names for field accel_var */ typedef enum { ACCEL_VAR_X=0, ACCEL_VAR_Y=1, ACCEL_VAR_Z=2 } accel_varElem; /* Number of elements for field accel_var */ static const quint32 ACCEL_VAR_NUMELEM = 3; // Field gyro_bias information /* Array element names for field gyro_bias */ typedef enum { GYRO_BIAS_X=0, GYRO_BIAS_Y=1, GYRO_BIAS_Z=2 } gyro_biasElem; /* Number of elements for field gyro_bias */ static const quint32 GYRO_BIAS_NUMELEM = 3; // Field gyro_scale information /* Array element names for field gyro_scale */ typedef enum { GYRO_SCALE_X=0, GYRO_SCALE_Y=1, GYRO_SCALE_Z=2 } gyro_scaleElem; /* Number of elements for field gyro_scale */ static const quint32 GYRO_SCALE_NUMELEM = 3; // Field gyro_var information /* Array element names for field gyro_var */ typedef enum { GYRO_VAR_X=0, GYRO_VAR_Y=1, GYRO_VAR_Z=2 } gyro_varElem; /* Number of elements for field gyro_var */ static const quint32 GYRO_VAR_NUMELEM = 3; // Field mag_bias information /* Array element names for field mag_bias */ typedef enum { MAG_BIAS_X=0, MAG_BIAS_Y=1, MAG_BIAS_Z=2 } mag_biasElem; /* Number of elements for field mag_bias */ static const quint32 MAG_BIAS_NUMELEM = 3; // Field mag_scale information /* Array element names for field mag_scale */ typedef enum { MAG_SCALE_X=0, MAG_SCALE_Y=1, MAG_SCALE_Z=2 } mag_scaleElem; /* Number of elements for field mag_scale */ static const quint32 MAG_SCALE_NUMELEM = 3; // Field mag_var information /* Array element names for field mag_var */ typedef enum { MAG_VAR_X=0, MAG_VAR_Y=1, MAG_VAR_Z=2 } mag_varElem; /* Number of elements for field mag_var */ static const quint32 MAG_VAR_NUMELEM = 3; // Constants static const quint32 OBJID = 2849879032U; static const QString NAME; static const bool ISSINGLEINST = 1; static const bool ISSETTINGS = 1; static const quint32 NUMBYTES = sizeof(DataFields); // Functions AHRSCalibration(); DataFields getData(); void setData(const DataFields& data); Metadata getDefaultMetadata(); UAVDataObject* clone(quint32 instID); static AHRSCalibration* GetInstance(UAVObjectManager* objMngr, quint32 instID = 0); private: DataFields data; void setDefaultFieldValues(); }; #endif // AHRSCALIBRATION_H
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 140 ] ] ]
80fad0e981e6dba52f4025a6ad4340db13fc0bf5
ab41c2c63e554350ca5b93e41d7321ca127d8d3a
/glm/gtx/fast_square_root.inl
0e8be944d782d55c845d5e19681876a9eeb106c0
[]
no_license
burner/e3rt
2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e
775470cc9b912a8c1199dd1069d7e7d4fc997a52
refs/heads/master
2021-01-11T08:08:00.665300
2010-04-26T11:42:42
2010-04-26T11:42:42
337,021
3
0
null
null
null
null
UTF-8
C++
false
false
4,820
inl
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2006-01-04 // Updated : 2008-10-07 // Licence : This source is under MIT License // File : glm/gtx/fast_square_root.inl /////////////////////////////////////////////////////////////////////////////////////////////////// namespace glm{ namespace gtx{ namespace fast_square_root{ // fastSqrt template <typename genType> inline genType fastSqrt ( genType const & x ) { return genType(1) / fastInverseSqrt(x); } template <typename valType> inline detail::tvec2<valType> fastSqrt ( detail::tvec2<valType> const & x ) { return detail::tvec2<valType>( fastSqrt(x.x), fastSqrt(x.y)); } template <typename valType> inline detail::tvec3<valType> fastSqrt ( detail::tvec3<valType> const & x ) { return detail::tvec3<valType>( fastSqrt(x.x), fastSqrt(x.y), fastSqrt(x.z)); } template <typename valType> inline detail::tvec4<valType> fastSqrt ( detail::tvec4<valType> const & x ) { return detail::tvec4<valType>( fastSqrt(x.x), fastSqrt(x.y), fastSqrt(x.z), fastSqrt(x.w)); } // fastInversesqrt template <typename genType> inline genType fastInverseSqrt ( genType const & x ) { genType tmp = x; float xhalf = 0.5f * float(tmp); uint i = *(uint*)&x; i = 0x5f375a86 - (i >> 1); //x = *(float*)&i; //x = *((float*)(char*)&i); tmp = detail::uif(i).f; tmp = tmp * (1.5f - xhalf * tmp * tmp); return genType(tmp); } template <typename valType> inline detail::tvec2<valType> fastInverseSqrt ( detail::tvec2<valType> const & x ) { return detail::tvec2<valType>( fastInverseSqrt(x.x), fastInverseSqrt(x.y)); } template <typename valType> inline detail::tvec3<valType> fastInverseSqrt ( detail::tvec3<valType> const & x ) { return detail::tvec3<valType>( fastInverseSqrt(x.x), fastInverseSqrt(x.y), fastInverseSqrt(x.z)); } template <typename valType> inline detail::tvec4<valType> fastInverseSqrt ( detail::tvec4<valType> const & x ) { return detail::tvec4<valType>( fastInverseSqrt(x.x), fastInverseSqrt(x.y), fastInverseSqrt(x.z), fastInverseSqrt(x.w)); } // fastLength template <typename genType> inline genType fastLength ( genType const & x ) { return abs(x); } template <typename valType> inline valType fastLength ( detail::tvec2<valType> const & x ) { valType sqr = x.x * x.x + x.y * x.y; return fastSqrt(sqr); } template <typename valType> inline valType fastLength ( detail::tvec3<valType> const & x ) { valType sqr = x.x * x.x + x.y * x.y + x.z * x.z; return fastSqrt(sqr); } template <typename valType> inline valType fastLength ( detail::tvec4<valType> const & x ) { valType sqr = x.x * x.x + x.y * x.y + x.z * x.z + x.w * x.w; return fastSqrt(sqr); } // fastDistance template <typename genType> inline genType fastDistance ( genType const & x, genType const & y ) { return fastLength(y - x); } template <typename valType> inline valType fastDistance ( detail::tvec2<valType> const & x, detail::tvec2<valType> const & y ) { return fastLength(y - x); } template <typename valType> inline valType fastDistance ( detail::tvec3<valType> const & x, detail::tvec3<valType> const & y ) { return fastLength(y - x); } template <typename valType> inline valType fastDistance ( detail::tvec4<valType> const & x, detail::tvec4<valType> const & y ) { return fastLength(y - x); } // fastNormalize template <typename genType> inline genType fastNormalize ( genType const & x ) { return x > genType(0) ? genType(1) : -genType(1); } template <typename valType> inline detail::tvec2<valType> fastNormalize ( detail::tvec2<valType> const & x ) { valType sqr = x.x * x.x + x.y * x.y; return x * fastInverseSqrt(sqr); } template <typename valType> inline detail::tvec3<valType> fastNormalize ( detail::tvec3<valType> const & x ) { valType sqr = x.x * x.x + x.y * x.y + x.z * x.z; return x * fastInverseSqrt(sqr); } template <typename valType> inline detail::tvec4<valType> fastNormalize ( detail::tvec4<valType> const & x ) { valType sqr = x.x * x.x + x.y * x.y + x.z * x.z + x.w * x.w; return x * fastInverseSqrt(sqr); } }//namespace fast_square_root }//namespace gtx }//namespace glm
[ [ [ 1, 237 ] ] ]
57ca72c6cabba620d56b81b164122a6880cd445e
90834e9db9d61688c796d0a30e77dd3acc2a9492
/SauerbratenRemote/src/remote/remote.cpp
b6ffab52526353f77ae4a937b2b978809103784d
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT", "Zlib" ]
permissive
zot/Plexus-original
1a79894797ca209af566bb67f72d6164869d7742
f9c3c66c697066e63ea0509c5ff9a8d6b27e369a
refs/heads/master
2020-09-20T21:51:57.194398
2009-04-21T12:45:19
2009-04-21T12:45:19
224,598,317
0
0
null
null
null
null
UTF-8
C++
false
false
6,763
cpp
/* * Copyright (c) 2008 TEAM CTHULHU, Bill Burdick, Roy Riggs * Plexus is licensed under the ZLIB license (http://www.opensource.org/licenses/zlib-license.php): */ #include "pch.h" #include "engine.h" #include <fcntl.h> #include <errno.h> #include "remote.h" #include "tc.h" #define UNSET 0 #define SET 1 #define NOT_ALLOWED 2 static int initialized = UNSET; static int remotePort = -1; static char *remoteHost; ENetSocket mysocket = -1; static long totalBytesRead = 0L, totalBytesWritten = 0L; static vector<char> input; static vector<char> output; static char *remotedisconnect(char *msg) { executeret("mysocket = -1"); if (mysocket != -1) { enet_socket_destroy(mysocket); //close(mysocket); mysocket = -1; conoutf("Disconnected from remote host: %s", msg ? msg : ""); } output.setsize(0); input.setsize(0); perror(msg ? msg : ""); totalBytesRead = totalBytesWritten = 0L; return NULL; } //extern int remotePort; //extern char *remoteHost; //extern ENetSocket mysocket; //extern long totalBytesRead, totalBytesWritten; ICOMMAND(remotestatus, "", (), { char buf[512]; snprintf(buf, sizeof(buf), "hostname %s port %d socket %d read %ld written %ld", remoteHost, remotePort, mysocket, totalBytesRead, totalBytesWritten); result(buf); }); ICOMMAND(remotedisconnect, "s", (char *msg), remotedisconnect(msg)); ICOMMAND(remotedisable, "", (), if (initialized == SET) { remotedisconnect("remote connections disabled"); delete[] remoteHost; enet_deinitialize(); } initialized = NOT_ALLOWED; ); static char *remoteallow(char *host, int port) { if (host == 0) { conoutf("REMOTE ERROR: host is NULL for remote connect"); } else if (strlen(host) == 0) { conoutf("REMOTE ERROR: host is empty for remote connect"); } else if (port == 0) { conoutf("REMOTE ERROR: No port given for remote connect"); } else if (port < 0) { conoutf("REMOTE ERROR: Invalid port for remote connect: %d", port); } else { switch (initialized) { case SET: if (strcmp(host, remoteHost)) { conoutf("REMOTE SECURITY VIOLATION: attempt to change allowed remote host from: %s to %s.", remoteHost, host); break; } else if (port != remotePort) { conoutf("REMOTE SECURITY VIOLATION: attempt to change allowed remote port from: %d to %d.", remotePort, port); break; } break; case NOT_ALLOWED: conoutf("REMOTE SECURITY VIOLATION: attempt to allow remote connections when they have been disabled"); break; case UNSET: initialized = SET; enet_initialize(); remoteHost = newstring(host); remotePort = port; conoutf("Allowing remote connections to %s:%d", remoteHost, remotePort); break; } } return NULL; } ICOMMAND(remoteallow, "si", (char *host, int *port), remoteallow(host, port ? *port : 0);); static char *remoteconnect() { if (mysocket != -1) { conoutf("REMOTE ERROR: attempt to connect when already connected."); return NULL; } switch (initialized) { case UNSET: conoutf("REMOTE ERROR: attempt to connect when host and port are not set"); break; case NOT_ALLOWED: conoutf("REMOTE SECURITY VIOLATION: attempt to connect when remote connections have been disabled"); break; case SET: static ENetAddress address; bool isIPAddr = true; address.port = remotePort; address.host = 0; conoutf("attempting to connect to %s", remoteHost); for (char *p = remoteHost; *p; p++) { if ((*p < '0' || '9' < *p) && *p != '.') { isIPAddr = false; break; } } if (isIPAddr) { printf("USING IP ADDR: %s\n", remoteHost); enet_address_set_host_ip(&address, remoteHost); } else { printf("USING HOST NAME: %s\n", remoteHost); if(!resolverwait(remoteHost, &address)) { conoutf("REMOTE ERROR: could not resolve server %s", remoteHost); break; } } if (-1 == (mysocket = enet_socket_create(ENET_SOCKET_TYPE_STREAM, NULL))) { conoutf("REMOTE ERROR: Could not create remote socket"); break; } //fprintf(stderr, "Host internal %ld, port %d\n", (long) address.host, address.port); if (enet_socket_connect(mysocket, &address)) { conoutf("REMOTE ERROR: Could not connect to remote host %s:%d", remoteHost, remotePort); mysocket = -1; break; } enet_socket_set_option(mysocket, ENET_SOCKOPT_NONBLOCK, 1); conoutf("Connected to %s:%d", remoteHost, remotePort); break; } char buf [32]; sprintf(buf, "mysocket = %d", mysocket); executeret(buf); return NULL; } ICOMMAND(remoteconnect, "", (), remoteconnect();); void tc_remotesend(char *line) { //remoteconnect(); if (mysocket != -1) { output.put(line, strlen(line)); output.add('\n'); } } ICOMMAND(remotesend, "C", (char *line), tc_remotesend(line); ); static void readChunk() { databuf<char> buf = input.reserve(1000); ENetBuffer buffer; buffer.data = buf.buf; buffer.dataLength = 1000; int bytesRead = enet_socket_receive(mysocket, NULL, &buffer,1); //recv(mysocket, buf.buf, 1000, MSG_DONTWAIT); if (bytesRead < 0 && errno != EAGAIN && bytesRead != EAGAIN) { remotedisconnect("connection closed while reading"); } else if (bytesRead > 0) { totalBytesRead += bytesRead; int lastNl = -1; int oldLen = input.length(); buf.len = bytesRead; input.addbuf(buf); for (int i = 0; i < bytesRead; i++) { if (buf.buf[i] == '\n') { buf.buf[i] = ';'; lastNl = i; } } if (lastNl > -1) { lastNl += oldLen; input[lastNl] = 0; if (input.length() > 1) { char *command = input.getbuf(); //fprintf(stderr, "Zot (%d):%s\n", lastNl, command); executeret(command); } if (lastNl + 1 < input.length()) { input.remove(0, lastNl + 1); } else { input.setsize(0); } } } } static void writeChunk() { if (output.length()) { int written; ENetBuffer buffer; buffer.data = output.getbuf(); buffer.dataLength = output.length(); written = enet_socket_send(mysocket, NULL, &buffer, 1); if (written == EOF) { remotedisconnect("connection closed while writing"); } else { totalBytesWritten += written; if (written < output.length()) { output.remove(0, written); } else { output.setsize(0); } } } } vector<void (*)()> *tickhooks = NULL; void remotetick() { if (-1 != mysocket) { writeChunk(); readChunk(); } if (tickhooks) { loopi(tickhooks->length()) { ((*tickhooks)[i])(); } } } void addTickHook(void (*hook)()) { if (!tickhooks) { tickhooks = new vector<void (*)()>; } tickhooks->add(hook); }
[ "bill@sheba.(none)", "[email protected]", "[email protected]" ]
[ [ [ 1, 9 ], [ 11, 18 ], [ 21, 24 ], [ 26, 30 ], [ 35, 36 ], [ 48, 58 ], [ 60, 65 ], [ 68, 73 ], [ 75, 85 ], [ 87, 92 ], [ 94, 96 ], [ 98, 133 ], [ 135, 143 ], [ 147, 150 ], [ 153, 156 ], [ 161, 172 ], [ 174, 189 ], [ 191, 213 ], [ 215, 226 ], [ 231, 243 ] ], [ [ 10, 10 ], [ 19, 20 ], [ 31, 34 ], [ 37, 47 ], [ 59, 59 ], [ 66, 67 ], [ 74, 74 ], [ 86, 86 ], [ 93, 93 ], [ 97, 97 ], [ 134, 134 ], [ 152, 152 ], [ 173, 173 ], [ 190, 190 ], [ 214, 214 ], [ 227, 230 ] ], [ [ 25, 25 ], [ 144, 146 ], [ 151, 151 ], [ 157, 160 ] ] ]
a94f3d89035d20a6f9e2c69b8d9268c527ffd805
0b1111e870b496aae0d6210806eebf1c942c9d3a
/AnalyticGeometry/TSegment2.h
3ea9d92737f09c730020aec7098865658eb8da99
[ "WTFPL" ]
permissive
victorliu/Templated-Numerics
8ca3fabd79435fa40e95e9c8c944ecba42a0d8db
35ca6bb719615d5498a450a2d58e2aa2bb7ef5f9
refs/heads/master
2016-09-05T16:32:22.250276
2009-12-30T07:48:03
2009-12-30T07:48:03
318,857
3
1
null
null
null
null
UTF-8
C++
false
false
771
h
#ifndef _TSEGMENT2_H_ #define _TSEGMENT2_H_ #include "TPt2.h" #include "TVec2.h" #include "TLine2.h" template <class NumericType> class TSegment2{ public: typedef NumericType value_type; typedef TPt2<value_type> Pt2; typedef TVec2<value_type> Vec2; Pt2 a,b; TSegment2(const Pt2 &A, const Pt2 &B):a(A),b(B){} TSegment2(const Pt2 &A, const Vec2 &AB):a(A),b(A+AB){} TSegment2(const TSegment2 &s):a(s.a),b(s.b){} const Pt2& operator[](size_t which) const{ return ((which & 1) == 0) ? a : b; } Pt2& operator[](size_t which){ return ((which & 1) == 0) ? a : b; } value_type Length() const{ return (b-a).Length(); } TLine2<NumericType> Line() const{ return TLine2<NumericType>(a,b); } }; #endif // _TSEGMENT2_H_
[ [ [ 1, 35 ] ] ]
cf4a6e287ec6c1328bd3a666430490af84e550fc
55f0fcc198d4646235e75c0eff6fc6d3fad85313
/zenilib/src/HardAgent.cpp
d1ec29c96506bffebd9f89e75b2e392d29813c5a
[]
no_license
ernieg/493final
b6484ea3d09801404a15ee1df974004cb9dffe14
83c9527c3d289dad5496b1fd0eb45bffba09f1d5
refs/heads/master
2021-01-01T16:13:08.191675
2011-04-19T22:04:11
2011-04-19T22:04:11
32,241,477
0
0
null
null
null
null
UTF-8
C++
false
false
2,649
cpp
#include "zenilib.h" #include "HardAgent.h" #include "MediumAgent.h" #include "GameModel.h" #include "Board.h" HardAgent::HardAgent(int playerIndex_) : MediumAgent(playerIndex_) { for (int i = 0; i < NUM_COLUMNS; i++) { values[i] = 0; } } void HardAgent::getValue(int index) { GameModel& model = getGameModel(); Board *board = model.getBoard(); // Chooses the first location at random if (board->getNumCoins() == 1 || board->getNumCoins() == 0) { values[index] = 0; return; } int emptyRow = board->getEmptyRow(index); // Filling in values for (int i = 1; i < 4; i++) { // Check horizontal rows if (board->ownerOfSlot(emptyRow, index + i) == playerIndex) values[index] += 2 * (4 - i) * (4 - i); if (board->ownerOfSlot(emptyRow, index - i) == playerIndex) values[index] += 2 * (4 - i) * (4 - i); // Check below if (board->ownerOfSlot(emptyRow - i, index) == playerIndex) values[index] += 4 * (4 - i) * (4 - i); // Check diagnols if (board->ownerOfSlot(emptyRow - i, index + i) == playerIndex) values[index] += 1 * (4 - i) * (4 - i); if (board->ownerOfSlot(emptyRow - i, index - i) == playerIndex) values[index] += 1 * (4 - i) * (4 - i); if (board->ownerOfSlot(emptyRow + i, index + i) == playerIndex) values[index] += 1 * (4 - i) * (4 - i); if (board->ownerOfSlot(emptyRow + i, index - i) == playerIndex) values[index] += 1 * (4 - i) * (4 - i); // Take away value for empty spaces if (board->ownerOfSlot(emptyRow, index + i) == -1) values[index] -= 1 * (4 - i) * (4 - i); if (board->ownerOfSlot(emptyRow, index - i) == -1) values[index] -= 1 * (4 - i) * (4 - i); if (board->ownerOfSlot(emptyRow - i, index + i) == -1) values[index] -= 1 * (4 - i) * (4 - i); if (board->ownerOfSlot(emptyRow - i, index - i) == -1) values[index] -= 1 * (4 - i) * (4 - i); if (board->ownerOfSlot(emptyRow + i, index + i) == -1) values[index] -= 1 * (4 - i) * (4 - i); if (board->ownerOfSlot(emptyRow + i, index - i) == -1) values[index] -= 1 * (4 - i) * (4 - i); } // Prioritize winning if (board->threeInARow2(index, playerIndex)) { values[index] += 800; } // If opponent is about to win, stop him if (board->threeInARow2(index, (playerIndex == 0) ? 1 : 0)) { values[index] += 400; } if (twoInRow(index)) { values[index] += 100; } // Avoid putting coin in place where player can exploit a win resulting from Agent's coin if (board->lookAheadWin(index, (playerIndex == 0) ? 1 : 0)) { values[index] -= 1000; } // Don't put coin in full column if (board->columnFull(index)) { values[index] -= 1000; } }
[ "[email protected]@68425394-8837-c440-6ca7-5483a7d6cf0c" ]
[ [ [ 1, 76 ] ] ]
a3d6747132db75bfab7dfc25b086ae28c4ddc5d9
f2b4a9d938244916aa4377d4d15e0e2a6f65a345
/gxlib/gxl.topmostview.cpp
feed72be5f6d5068028b0e635c1c461f8cbd20b8
[ "Apache-2.0" ]
permissive
notpushkin/palm-heroes
d4523798c813b6d1f872be2c88282161cb9bee0b
9313ea9a2948526eaed7a4d0c8ed2292a90a4966
refs/heads/master
2021-05-31T19:10:39.270939
2010-07-25T12:25:00
2010-07-25T12:25:00
62,046,865
2
1
null
null
null
null
UTF-8
C++
false
false
1,890
cpp
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "gxl.inc.h" #ifdef OS_WINCE #include <gx.h> #endif //OS_WINCE #include "gxl.ctr.cbuff.h" #include "gxl.ctr.array.h" #include "gxl.window.h" #include "gxl.input.h" #include "gxl.timer.h" #include "gxl.display.h" #include "gxl.view.h" #include "gxl.dialog.h" #include "gxl.topmostview.h" #include "gxl.viewmgr.h" #include "gxl.application.h" iTopmostView::iTopmostView(iViewMgr* pViewMgr) : iView(pViewMgr, pViewMgr->Metrics(), GENERIC_VIEWPORT, 0, Visible|Enabled) {} // Message handler bool iTopmostView::ProcessMessage(const iInput::iEntry& msg) { switch(msg.taskType) { case iInput::iEntry::MouseMove: MouseTrack(iPoint(msg.px,msg.py)); break; case iInput::iEntry::MouseDown: MouseDown(iPoint(msg.px,msg.py)); break; case iInput::iEntry::MouseUp: MouseUp(iPoint(msg.px,msg.py)); break; case iInput::iEntry::KeyDown: KeyDown(msg.key); break; case iInput::iEntry::KeyUp: KeyUp(msg.key); break; } return true; } bool iTopmostView::KeyDown(sint32 key) { return OnKeyDown(key); } bool iTopmostView::KeyUp(sint32 key) { return OnKeyUp(key); }
[ "palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276" ]
[ [ [ 1, 60 ] ] ]
39e8f24f01c6385f14e105b680abfa765eb402a0
3c0d7fc6c0187a8a0eae01b15a77e8e302e524e8
/masterServer/src/networkMasterServer.hpp
d52ca216cdcd39af33b7cebdf40d8b1807bb0fe9
[ "Artistic-2.0" ]
permissive
klusark/mdpr
0342bea08e9585a46d8d1c5ada29a662875d9d6f
da2b2287e4ed7eab302255221381a9bcbc5e5dcd
refs/heads/master
2021-01-01T15:30:10.633491
2009-08-23T05:14:36
2009-08-23T05:14:36
32,649,940
0
0
null
null
null
null
UTF-8
C++
false
false
1,228
hpp
#ifndef networkMasterServer_hpp #define networkMasterServer_hpp #include <Poco/Net/SocketReactor.h> #include <Poco/Net/SocketNotification.h> #include <Poco/Util/ServerApplication.h> #include <Poco/Net/DatagramSocket.h> #include <vector> #include "network/packets.hpp" //!The master server class class NetworkMasterServer : public Poco::Util::ServerApplication { public: //!constructor NetworkMasterServer(); //!deconstructor ~NetworkMasterServer(); //!Equivilent to a global main. int main(const std::vector<std::string>& args); //!the container for holding the server typedef std::vector<serverEntry> serverListContainer; //!the serverListContainer of servers serverListContainer serverList; protected: //!Called when a packet is received void onReceivePacket(const Poco::AutoPtr<Poco::Net::ReadableNotification>& pNf); //!initializes the application void initialize(Poco::Util::Application& self); enum { //!The size of the buffer BUFFER_SIZE = 256 }; //!the socket used for all communication Poco::Net::DatagramSocket socket; //!the buffer used for reciveing information char* buffer; }; #endif // #ifndef networkMasterServer_hpp
[ "joelteichroeb@localhost" ]
[ [ [ 1, 54 ] ] ]
a96f18057efcab1b03e1f0dadb4ee74cee433f0e
7eb5a1c70c0ca8aa072a2ab79f4777203bf80a94
/src/Square.h
5d4889da87f1ef79c570b85716bf7ffa88eeaf5c
[]
no_license
costabile/car-training-4gc3
665c8e5e785d3cb65a80a698648981f0346cba8d
5af0c488f4588aa38747d8aaee451a7f515792a2
refs/heads/master
2016-09-03T07:08:39.440095
2011-04-07T16:06:22
2011-04-07T16:06:22
32,459,656
0
0
null
null
null
null
UTF-8
C++
false
false
605
h
#ifndef Square_h #define Square_h #include <windows.h> #include <gl\gl.h> #include <gl\glu.h> //#include <gl\glaux.h> #include "Vector2D.h" class Square { protected: Point2D position; float width; float height; public: Square(Point2D position, float width, float height); ~Square(); Point2D GetPosition(void) { return position; } void SetPosition(Point2D newPos) { position = newPos; } float GetWidth(void) { return width; } float GetHeight(void) { return height; } void Draw(); }; #endif
[ "[email protected]@4cf41146-4c76-f84c-7f41-f6f778b8fb49" ]
[ [ [ 1, 49 ] ] ]
581ad35f887234fe5cf5a32ba84fc609fd9f8cda
b7b58c5e83ae0e868414e8a6900b92fcfa87b4b1
/Tools/atlas/AtlasCore.h
94578926ebb571ceb9f64615326f665326bd3d92
[]
no_license
dailongao/cheat-fusion
87df8bd58845f30808600b72167ff6c778a36245
ab7cd0fe56df0edabb9064da70b93a2856df7fac
refs/heads/master
2021-01-10T12:42:37.958692
2010-12-31T13:42:51
2010-12-31T13:42:51
51,513,373
0
0
null
null
null
null
UTF-8
C++
false
false
1,890
h
#pragma once #include "stdafx.h" #include <iostream> #include <string> #include <vector> #include <fstream> #include <hash_map> #include "Table.h" #include "GenericVariable.h" #include "AtlasParser.h" #include "AtlasFile.h" #include "Pointer.h" #include "AtlasLogger.h" #include "AtlasStats.h" #include "PointerHandler.h" #include "AtlasExtension.h" extern unsigned int LastPos; //----------------------------------------------------------------------------- // AtlasCore Functionality //----------------------------------------------------------------------------- class AtlasCore { public: AtlasCore(); ~AtlasCore(); bool Insert(const char* RomFileName, const char* ScriptFileName); void SetDebugging(FILE* output); void CreateContext(AtlasContext** Context); bool ExecuteExtension(std::string& ExtId, std::string& FunctionName, AtlasContext** Context); bool ExecuteExtensionFunction(ExtensionFunction Func, AtlasContext** Context); private: AtlasParser Parser; AtlasFile File; VariableMap VarMap; // Variable Map for identifiers PointerHandler PtrHandler; Pointer DefaultPointer; EmbeddedPointerHandler EmbPtrs; InsertionStatistics Total; ExtensionManager Extensions; bool IsInJmp; unsigned int HeaderSize; bool ExecuteCommand(Command& Cmd); void PrintSummary(const char* Title, unsigned int TimeCompleted); void PrintStatistics(); void PrintStatisticsBlock(const char* Title, InsertionStatistics& Stats); bool AddTable(Command& Cmd); bool ActivateTable(std::string& TableName); bool LoadTable(std::string& FileName, Table** Tbl); }; // Global Core variables extern unsigned int CurrentLine; extern AtlasCore Atlas; // Misc functions inline unsigned int StringToUInt(std::string& NumberString); __int64 StringToInt64(std::string& NumberString); unsigned int GetHexDigit(char digit);
[ "forbbsneo@1e91e87a-c719-11dd-86c2-0f8696b7b6f9" ]
[ [ [ 1, 68 ] ] ]
d11c33e526cbbc96ee4934bfc82677c6474b2b63
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/TransCritical/TTechWOR/brahmapsd.cpp
aea0530bee941e7c1af83726bc1105f104b260b8
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,782
cpp
#include "stdafx.h" #include "brahmapsd.h" const double L[] = { 1.58740105197 , 2.0 , 2.51984209979 , 3.17480210394 , 4.0 , 5.03968419958 , 6.34960420787 , 8.0 , 10.0793683992 , 12.6992084157 , 16.0 , 20.1587367983 , 25.3984168315 , 32.0 , 40.3174735966 , 50.796833663 , 64.0 , 80.6349471933 , 101.593667326 , 128.0 , 161.269894387 , 203.187334652 , 256.0 , 322.539788773 , 406.374669304 , 512.0 }; const double Lav[] = { 1.78179743628 , 2.24492409662 , 2.82842712475 , 3.56359487256 , 4.48984819324 , 5.65685424949 , 7.12718974512 , 8.97969638647 , 11.313708499 , 14.2543794902 , 17.9593927729 , 22.627416998 , 28.5087589805 , 35.9187855459 , 45.2548339959 , 57.017517961 , 71.8375710918 , 90.5096679919 , 114.035035922 , 143.675142184 , 181.019335984 , 228.070071844 , 287.350284367 , 362.038671968 , 456.140143688 , 574.700568734 }; const static double r = 1.25992105; const static double conA = (r*r+r+1)/3; // { 1.282441 } const static double conV = (r*r*r+r*r+r+1)/4 / conA; // { 1.139882 } BrahmaPSD::BrahmaPSD(MStream &s) { MIPSD & sP = s.IF<MIPSD>(false); //if (IsNothing(sP)) return; double rhoS = 2420; // s.Density(MP_Sol, bayerRefTemp); // Solids Density double solidsContent = s.MassFlow(MP_Sol)/s.VolumeFlow(MP_All, bayerRefTemp);// kg solids/m3 slurry @ref v = solidsContent/rhoS; // m^3 solids/m^3 slurry double sumar = 0.0, sumv=0.0, sumn=0.0; for (int i = 0; i<=nClasses; i++) { double L2 = Sqr(L[i]); double L3 = L2*L[i]; double avvol = PI/6.*L3*DIST_CORR*1.0e-18; n[i] = v*sP.getFrac(i)/avvol; sumn += n[i]; sumar += L2*n[i]; sumv += L3*n[i]; } m_dSumAr = PI*1.0e-12*conA*sumar; m_dSumVol = PI/6*1.0e-18*DIST_CORR*sumv; //m_dSumVol = v; m_dSumN = sumn; } double BrahmaPSD::put(MStream &s) { MIPSD & sP = s.IF<MIPSD>(false); // if (IsNothing(sP)) return 0.0; double sumfr = 0.0; for (int i=0; i<=nClasses; i++) { double L3 = Sqr(L[i])*L[i]; double avvol = PI/6.*L3*DIST_CORR*1.0e-18; double frac = n[i]*avvol/m_dSumVol; sumfr+= frac; sP.putFrac(i, frac); } return sumfr; } BrahmaPSD::BrahmaPSD(double *n_, double SD) { double sumar = 0.0, sumv=0.0, sumn=0.0; for (int i=0; i<=nClasses; i++) { n[i]=n_[i]*SD; double z = L[i]*L[i]*n[i]; sumar += z; sumv += z*L[i]; sumn += n[i]; } m_dSumAr = PI*1.0e-12*conA*sumar; m_dSumVol = PI/6*1.0e-18*DIST_CORR*sumv; m_dSumN = sumn; } BrahmaPSD::BrahmaPSD() { } // Modify the PSD in a MStream
[ [ [ 1, 145 ] ] ]
e6849f8d38808ce8172ac32908c1861ccae04dac
080941f107281f93618c30a7aa8bec9e8e2d8587
/include/polygons2lines.h
599c79ee18e5b090940c8e67d3eb8a08ab41c7b7
[ "MIT" ]
permissive
scoopr/COLLADA_Refinery
6d40ee1497b9f33818ec1e71677c3d0a0bf8ced4
3a5ad1a81e0359f9025953e38e425bc10b5bf6c5
refs/heads/master
2021-01-22T01:55:14.642769
2009-03-10T21:31:04
2009-03-10T21:31:04
194,828
2
0
null
null
null
null
UTF-8
C++
false
false
2,077
h
/* The MIT License Copyright 2006 Sony Computer Entertainment Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __POLYGONS2LINES_H__ #define __POLYSGON2LINES_H__ // Collada API includes #include "dae.h" #include "dom/domCOLLADA.h" #include "defines.h" #include "conditionerBase.h" //using namespace std; class Polygons2lines : public ConditionerBase { public: REF_EXPORT bool init(); REF_EXPORT int execute(); REF_EXPORT std::string getBaseName() const { return "polygons2lines"; } REF_EXPORT std::string getDescription() const { return "turn all polygons to lines"; } REF_EXPORT std::string getCategory() const { return "geometry processing"; } }; class Polygons2linesProxy : public ConditionerCreator { REF_EXPORT std::string getBaseName() const { return "polygons2lines"; } REF_EXPORT std::string getDescription() const { return "turn all polygons to lines"; } REF_EXPORT std::string getCategory() const { return "geometry processing"; } REF_EXPORT Conditioner *create() const { return new Polygons2lines(); } }; #endif //__POLYGONS2LINES_H__
[ "alorino@7d79dae2-2c22-0410-a73c-a02ad39e49d4", "sceahklaw@7d79dae2-2c22-0410-a73c-a02ad39e49d4" ]
[ [ [ 1, 1 ], [ 23, 55 ] ], [ [ 2, 22 ] ] ]
57b9cd6a7ebee09bc0e888672756137b8093f3df
4ecb7e18f351ee920a6847c7ebd9010b6a5d34ce
/HD/trunk/HuntingDragon/gametutor/source/CCharacter.cpp
875dcd270d82ac3df5ce3745bba245a40bcbe8a7
[]
no_license
dogtwelve/bkiter08-gameloft-internship-2011
505141ea314c234d99652600db5165a22cf041c3
0efc9f009bf12fe4ed36e1abfeb34f346a8c4198
refs/heads/master
2021-01-10T12:16:51.540936
2011-10-27T13:30:50
2011-10-27T13:30:50
46,549,117
0
0
null
null
null
null
UTF-8
C++
false
false
2,513
cpp
#include "CCharacter.h" CCharacter::CCharacter() { Init(); } CCharacter::~CCharacter() { } void CCharacter::Init() { m_Velocity = 1; m_vecDir = Vector3(1, 0, 0); m_vecNormal = Vector3(0, 0, 1); m_Acceleration = Vector3(0, 0, 0); m_Position = Vector3(0, 0, 0); m_CurAction = ACTION_RUN; m_iCurFrames = 0; xangle = 0; m_matWorld.LoadIdentity(); } void CCharacter::Update() { // normalize all vectors m_vecDir = m_vecDir.normalize(); m_vecNormal = m_vecNormal.normalize(); // update character's current frame m_iCurFrames++; if(m_iCurFrames < m_Frames[m_CurAction][START_FRAME] || m_iCurFrames > m_Frames[m_CurAction][END_FRAME]) { m_iCurFrames = m_Frames[m_CurAction][START_FRAME]; } // update position float dt = 0.1f; m_Position = m_Position + dt * m_Velocity * m_vecDir; //// fix camera //m_Camera.Perspective(45, 4.0f/3.0f, 1.0f, 100.0f); //m_Camera.Lookat( // 0, 0, 5.0f, // 0, 0, 0, // 1.0f, 0, 0); //m_Camera.BuildViewMatrix(); // update z-rotation angle xangle = -atan(m_vecDir[1] / m_vecDir[0]) * RAD_2_DEG; if(m_vecDir[0] < 0) xangle += 180.0f; // update world matrix m_matWorld.LoadIdentity(); m_matWorld.Translate(m_Position[0], m_Position[1], m_Position[2]); m_matWorld.Rotate(xangle, Z_AXIS); } void CCharacter::LoadActions(const char* strCfgName) { FILE* f; char buf[100]; char action[20]; int startFrame, endFrame; f = fopen(strCfgName, "r"); while(!feof(f)) { //get action fgets(buf, 100, f); sscanf(buf, "%s %d %d", action, &startFrame, &endFrame); // load frames of action if(strcmp(action, "STAND") == 0) { m_Frames[ACTION_STAND][START_FRAME] = startFrame; m_Frames[ACTION_STAND][END_FRAME] = endFrame; } if(strcmp(action, "RUN") == 0) { m_Frames[ACTION_RUN][START_FRAME] = startFrame; m_Frames[ACTION_RUN][END_FRAME] = endFrame; } if(strcmp(action, "ATTACK") == 0) { m_Frames[ACTION_ATTACK][START_FRAME] = startFrame; m_Frames[ACTION_ATTACK][END_FRAME] = endFrame; } if(strcmp(action, "DIE") == 0) { m_Frames[ACTION_DIE][START_FRAME] = startFrame; m_Frames[ACTION_DIE][END_FRAME] = endFrame; } } fclose(f); } void CCharacter::Render(Matrix* vpMatrix) { Matrix mvpMatrix = *vpMatrix * m_matWorld; CGraphics3D::GetInstance()->SetMVPMatrix(mvpMatrix.GetData()); CModel::Render(m_iCurFrames); Sleep(50); } void CCharacter::Release() { }
[ [ [ 1, 123 ] ] ]
6d14160dde35f1a24390bfecd09c412990a991bc
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEFoundation/SEDistance/SEDistTriangle3Triangle3.cpp
b0fdcd1248985496c6c6ac7c53861a80a8f5923d
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
GB18030
C++
false
false
6,820
cpp
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #include "SEFoundationPCH.h" #include "SEDistTriangle3Triangle3.h" #include "SEDistSegment3Triangle3.h" using namespace Swing; //---------------------------------------------------------------------------- SEDistTriangle3Triangle3f::SEDistTriangle3Triangle3f(const SETriangle3f& rTriangle0, const SETriangle3f& rTriangle1) : m_pTriangle0(&rTriangle0), m_pTriangle1(&rTriangle1) { } //---------------------------------------------------------------------------- const SETriangle3f& SEDistTriangle3Triangle3f::GetTriangle0() const { return *m_pTriangle0; } //---------------------------------------------------------------------------- const SETriangle3f& SEDistTriangle3Triangle3f::GetTriangle1() const { return *m_pTriangle1; } //---------------------------------------------------------------------------- float SEDistTriangle3Triangle3f::Get() { float fSqrDist = GetSquared(); return SEMath<float>::Sqrt(fSqrDist); } //---------------------------------------------------------------------------- float SEDistTriangle3Triangle3f::GetSquared() { // ๆŠŠtriangle0็š„ๅ„่พนๅ’Œtriangle1่ฟ›่กŒๆฏ”่พƒ. float fSqrDist = SEMath<float>::MAX_REAL, fSqrDistTmp; SESegment3f tempSeg; float fRatio; int i0, i1; for( i0 = 2, i1 = 0; i1 < 3; i0 = i1++ ) { tempSeg.Origin = 0.5f*(m_pTriangle0->V[i0] + m_pTriangle0->V[i1]); tempSeg.Direction = m_pTriangle0->V[i1] - m_pTriangle0->V[i0]; tempSeg.Extent = 0.5f*tempSeg.Direction.Normalize(); SEDistSegment3Triangle3f tempSTDist(tempSeg, *m_pTriangle1); fSqrDistTmp = tempSTDist.GetSquared(); if( fSqrDistTmp < fSqrDist ) { m_ClosestPoint0 = tempSTDist.GetClosestPoint0(); m_ClosestPoint1 = tempSTDist.GetClosestPoint1(); fSqrDist = fSqrDistTmp; fRatio = tempSTDist.GetSegmentParameter()/tempSeg.Extent; m_afTriangleBary0[i0] = 0.5f*(1.0f - fRatio); m_afTriangleBary0[i1] = 1.0f - m_afTriangleBary0[i0]; m_afTriangleBary0[3 - i0 - i1] = 0.0f; m_afTriangleBary1[0] = tempSTDist.GetTriangleBary(0); m_afTriangleBary1[1] = tempSTDist.GetTriangleBary(1); m_afTriangleBary1[2] = tempSTDist.GetTriangleBary(2); if( fSqrDist <= SEMath<float>::ZERO_TOLERANCE ) { return 0.0f; } } } // ๆŠŠtriangle1็š„ๅ„่พนๅ’Œtriangle0่ฟ›่กŒๆฏ”่พƒ. for( i0 = 2, i1 = 0; i1 < 3; i0 = i1++ ) { tempSeg.Origin = 0.5f*(m_pTriangle1->V[i0] + m_pTriangle1->V[i1]); tempSeg.Direction = m_pTriangle1->V[i1] - m_pTriangle1->V[i0]; tempSeg.Extent = 0.5f*tempSeg.Direction.Normalize(); SEDistSegment3Triangle3f tempSTDist(tempSeg, *m_pTriangle0); fSqrDistTmp = tempSTDist.GetSquared(); if( fSqrDistTmp < fSqrDist ) { m_ClosestPoint0 = tempSTDist.GetClosestPoint0(); m_ClosestPoint1 = tempSTDist.GetClosestPoint1(); fSqrDist = fSqrDistTmp; fRatio = tempSTDist.GetSegmentParameter()/tempSeg.Extent; m_afTriangleBary1[i0] = 0.5f*(1.0f - fRatio); m_afTriangleBary1[i1] = 1.0f - m_afTriangleBary1[i0]; m_afTriangleBary1[3 - i0 - i1] = 0.0f; m_afTriangleBary0[0] = tempSTDist.GetTriangleBary(0); m_afTriangleBary0[1] = tempSTDist.GetTriangleBary(1); m_afTriangleBary0[2] = tempSTDist.GetTriangleBary(2); if( fSqrDist <= SEMath<float>::ZERO_TOLERANCE ) { return 0.0f; } } } return fSqrDist; } //---------------------------------------------------------------------------- float SEDistTriangle3Triangle3f::Get(float fT, const SEVector3f& rVelocity0, const SEVector3f& rVelocity1) { SEVector3f vec3fMV00 = m_pTriangle0->V[0] + fT*rVelocity0; SEVector3f vec3fMV01 = m_pTriangle0->V[1] + fT*rVelocity0; SEVector3f vec3fMV02 = m_pTriangle0->V[2] + fT*rVelocity0; SEVector3f vec3fMV10 = m_pTriangle1->V[0] + fT*rVelocity1; SEVector3f vec3fMV11 = m_pTriangle1->V[1] + fT*rVelocity1; SEVector3f vec3fMV12 = m_pTriangle1->V[2] + fT*rVelocity1; SETriangle3f tempMTriangle0(vec3fMV00, vec3fMV01, vec3fMV02); SETriangle3f tempMTriangle1(vec3fMV10, vec3fMV11, vec3fMV12); return SEDistTriangle3Triangle3f(tempMTriangle0, tempMTriangle1).Get(); } //---------------------------------------------------------------------------- float SEDistTriangle3Triangle3f::GetSquared(float fT, const SEVector3f& rVelocity0, const SEVector3f& rVelocity1) { SEVector3f vec3fMV00 = m_pTriangle0->V[0] + fT*rVelocity0; SEVector3f vec3fMV01 = m_pTriangle0->V[1] + fT*rVelocity0; SEVector3f vec3fMV02 = m_pTriangle0->V[2] + fT*rVelocity0; SEVector3f vec3fMV10 = m_pTriangle1->V[0] + fT*rVelocity1; SEVector3f vec3fMV11 = m_pTriangle1->V[1] + fT*rVelocity1; SEVector3f vec3fMV12 = m_pTriangle1->V[2] + fT*rVelocity1; SETriangle3f tempMTriangle0(vec3fMV00, vec3fMV01, vec3fMV02); SETriangle3f tempMTriangle1(vec3fMV10, vec3fMV11, vec3fMV12); return SEDistTriangle3Triangle3f(tempMTriangle0, tempMTriangle1).GetSquared(); } //---------------------------------------------------------------------------- float SEDistTriangle3Triangle3f::GetTriangleBary0(int i) const { SE_ASSERT( 0 <= i && i < 3 ); return m_afTriangleBary0[i]; } //---------------------------------------------------------------------------- float SEDistTriangle3Triangle3f::GetTriangleBary1(int i) const { SE_ASSERT( 0 <= i && i < 3 ); return m_afTriangleBary1[i]; } //----------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 164 ] ] ]
2067c15e1a7606e1cff8a26611dae6b2c5fdb479
6f7850c90ed97967998033df615d06eacfabd5fa
/common/my_karma.h
8f57d88b0f4686a29c1221f0050fc104e27f9ae2
[]
no_license
vi-k/whoisalive
1145b0af6a2a18e951533b00a2103b000abd570a
ae86c1982c1e97eeebc50ba54bf53b9b694078b6
refs/heads/master
2021-01-10T02:00:28.585126
2010-08-23T01:58:45
2010-08-23T01:58:45
44,526,120
0
0
null
null
null
null
UTF-8
C++
false
false
139
h
๏ปฟ#ifndef MY_KARMA_H #define MY_KARMA_H #include <boost/spirit/include/karma.hpp> namespace karma=boost::spirit::karma; #endif
[ "victor dunaev ([email protected])" ]
[ [ [ 1, 8 ] ] ]
98fc0152aef2225794ab42d5b699cefa947b5627
48a185f4f05cc5dff3a6253b2e73664554a64a25
/src/parser.cpp
d37da1c5c7f87ddac379e340a44b9cbf71bbfdfc
[]
no_license
flice/QQ2005
b2a6ef6b7827c3c5ebee5b2acf00d792b360d5f3
df90907fb209f8d4cd61e3dd94755ee051a22f5f
refs/heads/master
2020-03-27T03:07:13.390666
2011-11-17T17:52:09
2011-11-18T14:59:03
145,839,766
0
0
null
null
null
null
UTF-8
C++
false
false
7,269
cpp
/* * parser.cpp * * Created on: Mar 17, 2009 * Author: Phoebus Veiz <[email protected]> */ #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <cstdlib> #include <cstdio> #include <cstring> #include "def.h" #include "util.h" #include "parser.h" static char forbidden[][3] = { {-52, -41, 0}, // ๅฅ— {-44, -95, 0}, // ๆตด {-48, -44, 0}, // ๆ€ง {-53, -64, 0}, // ๆญป {-26, -50, 0}, // ๅซ– {-46, -7, 0}, // ๆทซ {-59, -82, 0}, // ๅฅณ {-68, -23, 0}, // ๅฅธ {-60, -48, 0}, // ็”ท {-50, -57, 0}, // ๅป {-79, -89, 0}, // ๆŠฑ {-58, -34, 0}, // ๅฆป {-80, -82, 0}, // ็ˆฑ {-69, -23, 0}, // ๅฉš {-55, -89, 0}, // ้ชš {-68, -6, 0}, // ่ดฑ {-51, -47, 0}, // ่„ฑ {-51, -10, 0}, // ไบก {-72, -66, 0}, // ๅฆ‡ {-56, -94, 0}, // ๅจถ {-68, -34, 0}, // ๅซ {-55, -79, 0}, // ๆ€ {-55, -19, 0}, // ่บซ {-52, -27, 0}, // ไฝ“ {-56, -23, 0}, // ไนณ {-51, -50, 0}, // ่‡€ {-55, -85, 0}, // ่‰ฒ {-45, -43, 0}, // ่ฏฑ {-58, -83, 0}, // ้ช— {-46, -62, 0}, // ่กฃ {-48, -40, 0}, // ่ƒธ {-60, -93, 0}, // ๆจก {-71, -85, 0}, // ๅ…ฌ {-47, -4, 0}, // ่…ฐ {-52, -91, 0}, // ่ƒŽ {-57, -23, 0}, // ๆƒ… {-68, -92, 0}, // ๆฟ€ {-76, -14, 0}, // ๆ‰“ {-79, -87, 0}, // ๆšด {-78, -48, 0}, // ๆฎ‹ {-77, -79, 0}, // ๆฝฎ {-69, -74, 0}, // ๆฌข {-62, -74, 0}, // ้œฒ {-68, -95, 0}, // ่‚Œ {-74, -66, 0}, // ๆฏ’ {-63, -75, 0}, // ๆ‹ {-73, -24, 0}, // ็–ฏ {-60, -72, 0}, // ๆฏ {-58, -83, 0}, // ้ช— {-51, -64, 0}, // ๅฑ  {-47, -86, 0}, // ่ก€ {-60, -90, 0}, // ๆ‘ฉ {-71, -85, 0}, // ๅ…ฌ {-47, -4, 0}, // ่…ฐ {-76, -91, 0}, // ่งฆ {-25, -77, 0}, // ็ปฏ {-56, -30, 0}, // ่‚‰ {-59, -83, 0}, // ๆ€’ {-45, -5, 0}, // ๆฌฒ {-50, -24, 0}, // ่ˆž {-62, -18, 0}, // ้ช‚ {-57, -82, 0}, // ้’ฑ {-62, -29, 0}, // ่ฃธ {-52, -69, 0}, // ่ข’ {-44, -48, 0}, // ๅญ• {-41, -77, 0}, // ๅฃฎ {-55, -10, 0}, // ่‚พ {-61, -61, 0}, // ๅฆน {-64, -79, 0}, // ่พฃ {-46, -11, 0}, // ้˜ด {-71, -38, 0}, // ๅ†  {-67, -61, 0}, // ็Ÿซ {-61, -91, 0}, // ๆฐ“ {-76, -42, 0}, // ็ฒ— {-48, -71, 0}, // ๆณ„ {-53, -3, 0}, // ๅฅน {-62, -47, 0}, // ๅต {-66, -85, 0}, // ็ฒพ {-76, -67, 0}, // ๅ”‡ {-41, -84, 0}, // ่ตš {-64, -53, 0}, // ๆตช {-53, -89, 0}, // ๅธ… {-58, -40, 0}, // ๆ› {-41, -79, 0}, // ๅฆ† {-67, -29, 0}, // ๅง {-67, -32, 0}, // ๆด {-15, -79, 0}, // ็™– {-65, -31, 0}, // ้…ท {-61, -40, 0}, // ็ง˜ {-58, -75, 0}, // ้ข‘ {-63, -60, 0}, // ่Š {-59, -6, 0}, // ๆ‰น {-51, -76, 0}, // ็—› {-77, -76, 0}, // ็‚’ {-64, -10, 0}, // ไธฝ {-45, -75, 0}, // ๆ‹ฅ {-46, -71, 0}, // ๅคœ {-76, -78, 0}, // ๅบŠ {-61, -33, 0}, // ็œ  {-61, -44, 0}, // ่ฟท {-77, -24, 0}, // ๅฎ  {-44, -75, 0}, // ็ผ˜ {-56, -31, 0}, // ๆŸ” {-53, -81, 0}, // ็ก {-74, -57, 0}, // ่‚š {-49, -75, 0}, // ็ณป {-72, -48, 0}, // ๆ„Ÿ {-73, -12, 0}, // ่‚ค {-61, -37, 0}, // ่œœ {-54, -20, 0}, // ็†Ÿ {-61, -32, 0}, // ็ปต {-78, -8, 0}, // ็ผ  {-57, -41, 0}, // ไบฒ {-52, -46, 0}, // ๆกƒ {-26, -62, 0}, // ๅช› {-47, -37, 0}, // ็œผ {-27, -48, 0}, // ้€ {-28, -20, 0}, // ๆฝ‡ {-49, -89, 0}, // ๆƒœ {-61, -4, 0}, // ๅ‘ฝ {-68, -78, 0}, // ็–พ {-78, -95, 0}, // ็—… {-65, -77, 0}, // ็  {-75, -74, 0}, // ๅˆ€ {-44, -41, 0}, // ๅฎฐ {-70, -64, 0}, // ่ฑช {-71, -13, 0}, // ่ดต {-72, -69, 0}, // ๅฏŒ {-78, -58, 0}, // ่ดข {-53, -5, 0}, // ไป– {-22, -45, 0}, // ๆšง {-61, -63, 0}, // ๆ˜ง {-71, -20, 0}, // ่ฝจ {-73, -14, 0}, // ๅคซ {-72, -18, 0}, // ๅ‰ฒ {-72, -89, 0}, // ๆŠš {-60, -52, 0}, // ๅฅถ {-33, -28, 0}, // ๅ’ช {-47, -34, 0}, // ่‰ณ {-47, -43, 0}, // ้ขœ {-61, -78, 0}, // ่ฒŒ {-74, -23, 0}, // ๅ • {-54, -84, 0}, // ๅฐธ {-60, -71, 0}, // ๅข“ {-68, -64, 0}, // ็ฅญ {-75, -63, 0}, // ็›— {-57, -64, 0}, // ๆŠข {-67, -39, 0}, // ๅŠซ {-58, -37, 0}, // ๆฌบ {-62, -66, 0}, // ๆˆฎ {-56, -92, 0}, // ่ถฃ {-71, -10, 0}, // ๆปš {-62, -24, 0}, // ๅฆˆ {-51, -75, 0}, // ๅท {-16, -79, 0}, // ้ธจ {-68, -90, 0}, // ้ธก {-46, -80, 0}, // ้‡Ž {-59, -71, 0}, // ๆฎด {-51, -79, 0}, // ๆ… {-80, -13, 0}, // ็ป‘ {-34, -49, 0}, // ๅฐด {-48, -80, 0}, // ้‚ช {-78, -39, 0}, // ๆ“ {-53, -84, 0}, // ็ˆฝ {-30, -85, 0}, // ็Œฅ {-39, -12, 0}, // ไบต {-69, -58, 0}, // ้ป„ {-69, -20, 0}, // ๆทท {-50, -22, 0}, // ไพฎ {-56, -24, 0}, // ่พฑ {-27, -30, 0}, // ้‚‚ {-27, -53, 0}, // ้€… {-65, -15, 0}, // ็‹‚ {-78, -71, 0}, // ่กฅ {-71, -76, 0}, // ๅ‹พ {-41, -80, 0}, // ่ฃ… {-45, -23, 0}, // ๅจฑ {-76, -63, 0}, // ๆˆณ {-78, -27, 0}, // ๆ’ {-58, -14, 0}, // ไนž {-48, -41, 0}, // ๅ‡ถ {-71, -19, 0}, // ้ฌผ {-41, -23, 0}, // ็ป„ {-67, -5, 0}, // ็ฆ {-57, -44, 0}, // ็ชƒ {-77, -44, 0}, // ๅƒ {-70, -56, 0}, // ๅ– {-75, -33, 0}, // ้ข  {-65, -29, 0}, // ่ฃค {-56, -71, 0}, // ่ฃ™ {-65, -6, 0}, // ็ชฅ {-70, -34, 0}, // ๆจ {-74, -25, 0}, // ๅ‰ {-48, -33, 0}, // ็พž {0, 0, 0}, }; bool filter(const string& str) { string::size_type pos; size_t kanji_sum = 0; for (int i = 0; strlen(forbidden[i]); i++) { kanji_sum = 0; pos = str.find(forbidden[i]); if (pos < str.length()) { for (size_t j = 0; j < pos; j++) { if (str[j] < 0) kanji_sum++; } if (kanji_sum % 2 == 0) { return false; } } } return true; } int parser::parse_xml_group(const vector<string>& urls, vector<string>& vec) { const char* local_filename = "title.xml"; int ret = 0; vec.clear(); for (size_t i = 0; i < urls.size(); i++) { download(urls.at(i).c_str(), local_filename); ret += parser::parse_xml(local_filename, vec); } std::sort(vec.begin(), vec.end()); return ret; } int parser::parse_xml(const char* xml_file, vector<string>& vec) { const string prefix = "<title><![CDATA["; const string suffix = "]]></title>"; char rm[5] = {40, -51, -68, 41, 0}; // (ๅ›พ) const string drop_str = rm; const uint32_t len_min = 20; ifstream ifs; string line; string::size_type pos; uint32_t mode = 1; uint32_t nloop = 0; ifs.open(xml_file, ios::in | ios::binary); if (!ifs) { cout << xml_file << ": file not found." << endl; } start: ifs.seekg(0); for (; ;) { nloop++; if (nloop > 1024) { return -1; } line.clear(); if (mode == 1) { ifs >> line; } else if (mode == 2) { getline(ifs, line); } if (line.size() <= 0) { break; } pos = line.find(prefix); if (pos < line.length()) { line = line.substr(pos + prefix.length(), line.length() - prefix.length() - suffix.length() - pos); pos = line.find(drop_str); if (pos < line.length()) { line.erase(pos, drop_str.length()); } if (line.length() > len_min) { if (filter(line) == true) vec.push_back(line); } } } if (mode == 1 && vec.empty()) { mode = 2; goto start; } ifs.close(); return 0; }
[ [ [ 1, 340 ] ] ]
06f016c7121d097201d99eb8c5fb1aeb38458708
8b506bf34b36af04fa970f2749e0c8033f1a9d7a
/Code/Win32/dx/dxEngine.h
ca119a25bed25a65ec6a5d343eab02a350d60255
[]
no_license
gunstar/Prototype
a5155e25d7d54a1991425e7be85bfc7da42c634f
a4448b5f6d18048ecaedf26c71e2b107e021ea6e
refs/heads/master
2021-01-10T21:42:24.221750
2011-11-06T10:16:26
2011-11-06T10:16:26
2,708,481
0
0
null
null
null
null
UTF-8
C++
false
false
744
h
/* dxEngine For max speed: while(true) { drawBegin(); drawEnd(); (ticking) drawFlush(); } */ #ifndef _dxEngine #define _dxEngine #include "dxBoot.h" class dxEngine { public: dxEngine (); ~dxEngine (); bool open (const char* windowTitle); void close (); void drawBegin (); void drawEnd (); void drawFlush (); // Important: Do game ticking AFTER drawEnd() and BEFORE drawFlush() => max concurrency with GPU. dxCamera* makeCamera (); dxLines* makeLines (); dxRenderState* makeRenderState (); dxTransformer* makeTransformer (); dxTriangles* makeTriangles (); private: dxBoot* Boot; dxDevice* Device; dxWindow* Window; }; #endif
[ [ [ 1, 45 ] ] ]
f8f09caed706438385509322e6d4ca51a82096e9
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/DirectDownloadDlg.h
18075bf02b83df2485cb2604b7423212968e06ee
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
1,736
h
//this file is part of eMule //Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #pragma once #include "ResizableLib/ResizableDialog.h" #include "IconStatic.h" #include "ButtonsTabCtrl.h" class CDirectDownloadDlg : public CResizableDialog { DECLARE_DYNAMIC(CDirectDownloadDlg) public: CDirectDownloadDlg(CWnd* pParent = NULL); // standard constructor virtual ~CDirectDownloadDlg(); // Dialog Data enum { IDD = IDD_DIRECT_DOWNLOAD }; protected: HICON m_icnWnd; CIconStatic m_ctrlDirectDlFrm; CButtonsTabCtrl m_cattabs; void UpdateControls(); void UpdateCatTabs(); virtual BOOL OnInitDialog(); virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual void OnOK(); DECLARE_MESSAGE_MAP() afx_msg void OnEnKillfocusElink(); afx_msg void OnEnUpdateElink(); afx_msg void OnNMClickCats(NMHDR *pNMHDR, LRESULT *pResult); // Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle };
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 50 ] ] ]
1e9bb247ea65bd9744e8565f3e6184fb00615d61
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/spot_graphics_native_Microsoft_SPOT_Bitmap_mshl.cpp
40f373d99344f6fb065caf094153f22dcedc56c1
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,830
cpp
//----------------------------------------------------------------------------- // // ** DO NOT EDIT THIS FILE! ** // This file was generated by a tool // re-running the tool will overwrite this file. // //----------------------------------------------------------------------------- #include "spot_graphics_native.h" #include "spot_graphics_native_Microsoft_SPOT_Bitmap.h" using namespace Microsoft::SPOT; HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::_ctor___VOID__I4__I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); Bitmap::_ctor( pMngObj, param0, param1, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::_ctor___VOID__SZARRAY_U1__MicrosoftSPOTBitmapBitmapImageType( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); CLR_RT_TypedArray_UINT8 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT8_ARRAY( stack, 1, param0 ) ); UINT8 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT8( stack, 2, param1 ) ); Bitmap::_ctor( pMngObj, param0, param1, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::Flush___VOID( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); Bitmap::Flush( pMngObj, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::Flush___VOID__I4__I4__I4__I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); INT32 param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 3, param2 ) ); INT32 param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 4, param3 ) ); Bitmap::Flush( pMngObj, param0, param1, param2, param3, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::Clear___VOID( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); Bitmap::Clear( pMngObj, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::DrawTextInRect___BOOLEAN__BYREF_STRING__BYREF_I4__BYREF_I4__I4__I4__I4__I4__U4__MicrosoftSPOTPresentationMediaColor__MicrosoftSPOTFont( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); LPCSTR * param0; UINT8 heapblock0[CLR_RT_HEAP_BLOCK_SIZE]; TINYCLR_CHECK_HRESULT( Interop_Marshal_LPCSTR_ByRef( stack, heapblock0, 1, param0 ) ); INT32 * param1; UINT8 heapblock1[CLR_RT_HEAP_BLOCK_SIZE]; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32_ByRef( stack, heapblock1, 2, param1 ) ); INT32 * param2; UINT8 heapblock2[CLR_RT_HEAP_BLOCK_SIZE]; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32_ByRef( stack, heapblock2, 3, param2 ) ); INT32 param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 4, param3 ) ); INT32 param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 5, param4 ) ); INT32 param5; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 6, param5 ) ); INT32 param6; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 7, param6 ) ); UINT32 param7; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 8, param7 ) ); UINT32 param8; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 9, param8 ) ); UNSUPPORTED_TYPE param9; TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 10, param9 ) ); INT8 retVal = Bitmap::DrawTextInRect( pMngObj, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9, hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_INT8( stack, retVal ); TINYCLR_CHECK_HRESULT( Interop_Marshal_StoreRef( stack, heapblock0, 1 ) ); TINYCLR_CHECK_HRESULT( Interop_Marshal_StoreRef( stack, heapblock1, 2 ) ); TINYCLR_CHECK_HRESULT( Interop_Marshal_StoreRef( stack, heapblock2, 3 ) ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::SetClippingRectangle___VOID__I4__I4__I4__I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); INT32 param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 3, param2 ) ); INT32 param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 4, param3 ) ); Bitmap::SetClippingRectangle( pMngObj, param0, param1, param2, param3, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::get_Width___I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 retVal = Bitmap::get_Width( pMngObj, hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_INT32( stack, retVal ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::get_Height___I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 retVal = Bitmap::get_Height( pMngObj, hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_INT32( stack, retVal ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::DrawEllipse___VOID__MicrosoftSPOTPresentationMediaColor__I4__I4__I4__I4__I4__MicrosoftSPOTPresentationMediaColor__I4__I4__MicrosoftSPOTPresentationMediaColor__I4__I4__U2( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); UINT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); INT32 param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 3, param2 ) ); INT32 param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 4, param3 ) ); INT32 param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 5, param4 ) ); INT32 param5; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 6, param5 ) ); UINT32 param6; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 7, param6 ) ); INT32 param7; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 8, param7 ) ); INT32 param8; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 9, param8 ) ); UINT32 param9; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 10, param9 ) ); INT32 param10; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 11, param10 ) ); INT32 param11; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 12, param11 ) ); UINT16 param12; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT16( stack, 13, param12 ) ); Bitmap::DrawEllipse( pMngObj, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11, param12, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::DrawImage___VOID__I4__I4__MicrosoftSPOTBitmap__I4__I4__I4__I4__U2( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); UNSUPPORTED_TYPE param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 3, param2 ) ); void param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_void( stack, 4, param3 ) ); INT32 param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 5, param4 ) ); INT32 param5; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 6, param5 ) ); INT32 param6; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 7, param6 ) ); INT32 param7; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 8, param7 ) ); Bitmap::DrawImage( pMngObj, param0, param1, param2, param3, param4, param5, param6, param7, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::RotateImage___VOID__I4__I4__I4__MicrosoftSPOTBitmap__I4__I4__I4__I4__U2( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); INT32 param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 3, param2 ) ); UNSUPPORTED_TYPE param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 4, param3 ) ); void param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_void( stack, 5, param4 ) ); INT32 param5; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 6, param5 ) ); INT32 param6; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 7, param6 ) ); INT32 param7; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 8, param7 ) ); INT32 param8; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 9, param8 ) ); Bitmap::RotateImage( pMngObj, param0, param1, param2, param3, param4, param5, param6, param7, param8, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::MakeTransparent___VOID__MicrosoftSPOTPresentationMediaColor( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); UINT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 1, param0 ) ); Bitmap::MakeTransparent( pMngObj, param0, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::StretchImage___VOID__I4__I4__MicrosoftSPOTBitmap__I4__I4__U2( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); UNSUPPORTED_TYPE param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 3, param2 ) ); void param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_void( stack, 4, param3 ) ); INT32 param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 5, param4 ) ); INT32 param5; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 6, param5 ) ); Bitmap::StretchImage( pMngObj, param0, param1, param2, param3, param4, param5, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::DrawLine___VOID__MicrosoftSPOTPresentationMediaColor__I4__I4__I4__I4__I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); UINT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); INT32 param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 3, param2 ) ); INT32 param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 4, param3 ) ); INT32 param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 5, param4 ) ); INT32 param5; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 6, param5 ) ); Bitmap::DrawLine( pMngObj, param0, param1, param2, param3, param4, param5, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::DrawRectangle___VOID__MicrosoftSPOTPresentationMediaColor__I4__I4__I4__I4__I4__I4__I4__MicrosoftSPOTPresentationMediaColor__I4__I4__MicrosoftSPOTPresentationMediaColor__I4__I4__U2( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); UINT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); INT32 param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 3, param2 ) ); INT32 param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 4, param3 ) ); INT32 param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 5, param4 ) ); INT32 param5; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 6, param5 ) ); INT32 param6; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 7, param6 ) ); INT32 param7; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 8, param7 ) ); UINT32 param8; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 9, param8 ) ); INT32 param9; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 10, param9 ) ); INT32 param10; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 11, param10 ) ); UINT32 param11; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 12, param11 ) ); INT32 param12; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 13, param12 ) ); INT32 param13; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 14, param13 ) ); UINT16 param14; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT16( stack, 15, param14 ) ); Bitmap::DrawRectangle( pMngObj, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11, param12, param13, param14, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::DrawText___VOID__STRING__MicrosoftSPOTFont__MicrosoftSPOTPresentationMediaColor__I4__I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); LPCSTR param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_LPCSTR( stack, 1, param0 ) ); UNSUPPORTED_TYPE param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 2, param1 ) ); UINT32 param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 3, param2 ) ); UINT32 param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 4, param3 ) ); INT32 param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 5, param4 ) ); Bitmap::DrawText( pMngObj, param0, param1, param2, param3, param4, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::SetPixel___VOID__I4__I4__MicrosoftSPOTPresentationMediaColor( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); UINT32 param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 3, param2 ) ); Bitmap::SetPixel( pMngObj, param0, param1, param2, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::GetPixel___MicrosoftSPOTPresentationMediaColor__I4__I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); UINT32 retVal = Bitmap::GetPixel( pMngObj, param0, param1, hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_UINT32( stack, retVal ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::GetBitmap___SZARRAY_U1( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); UINT8 retVal = Bitmap::GetBitmap( pMngObj, hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_UINT8( stack, retVal ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::StretchImage___VOID__I4__I4__I4__I4__MicrosoftSPOTBitmap__I4__I4__I4__I4__U2( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); INT32 param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 3, param2 ) ); INT32 param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 4, param3 ) ); UNSUPPORTED_TYPE param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 5, param4 ) ); void param5; TINYCLR_CHECK_HRESULT( Interop_Marshal_void( stack, 6, param5 ) ); INT32 param6; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 7, param6 ) ); INT32 param7; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 8, param7 ) ); INT32 param8; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 9, param8 ) ); INT32 param9; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 10, param9 ) ); Bitmap::StretchImage( pMngObj, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::TileImage___VOID__I4__I4__MicrosoftSPOTBitmap__I4__I4__U2( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); UNSUPPORTED_TYPE param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 3, param2 ) ); void param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_void( stack, 4, param3 ) ); INT32 param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 5, param4 ) ); INT32 param5; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 6, param5 ) ); Bitmap::TileImage( pMngObj, param0, param1, param2, param3, param4, param5, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::Scale9Image___VOID__I4__I4__I4__I4__MicrosoftSPOTBitmap__I4__I4__I4__I4__U2( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 1, param0 ) ); INT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 2, param1 ) ); INT32 param2; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 3, param2 ) ); INT32 param3; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 4, param3 ) ); UNSUPPORTED_TYPE param4; TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 5, param4 ) ); void param5; TINYCLR_CHECK_HRESULT( Interop_Marshal_void( stack, 6, param5 ) ); INT32 param6; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 7, param6 ) ); INT32 param7; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 8, param7 ) ); INT32 param8; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 9, param8 ) ); INT32 param9; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 10, param9 ) ); Bitmap::Scale9Image( pMngObj, param0, param1, param2, param3, param4, param5, param6, param7, param8, param9, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_graphics_native_Microsoft_SPOT_Bitmap::Dispose___VOID__BOOLEAN( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { CLR_RT_HeapBlock* pMngObj = Interop_Marshal_RetrieveManagedObject( stack ); FAULT_ON_NULL(pMngObj); INT8 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT8( stack, 1, param0 ) ); Bitmap::Dispose( pMngObj, param0, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); }
[ [ [ 1, 717 ] ] ]
e8c2aefac4841de2734d8ae1d76ca8c7efdc5a1b
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Client/Dimensions/FireBall.cpp
7dfb0f89711275e02c609fae9665f880f18159f6
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
850
cpp
#include "StdAfx.h" #include "FireBall.h" #include "PlayerCharacter.h" FireBall::FireBall(void) { } FireBall::~FireBall(void) { } bool FireBall::Update(PlayerCharacter *pSkillOwner, float fDeltaTime) { //Go on animation if( true ) { float fRadius = m_fMinRadius + (m_iSkillRank / m_fRadiusMod); int iRankMultiple = m_iRankMultipleMin + ( rand() % (int)(m_iRankMultipleMax - m_iRankMultipleMin) ); int iDamage = iRankMultiple * m_iSkillRank; int iResistStr = m_iMinResist + m_iSkillRank * m_iResistMod; //shoot fireball Projectile* pArrow = new Projectile(Projectile::ePT_Spell, iDamage, GetRange(), m_eDamageType, pSkillOwner, pSkillOwner->GetLocation(), pSkillOwner->GetHeading(), fRadius, iResistStr); g_pGameState->AddActor(pArrow); m_bExecuted = true; return true; } return false; }
[ "bflassing@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 33 ] ] ]
e899626cb0b6211b101b9395ae674ab60b0a3c59
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
/tags/pyplusplus_dev_0.9.5/unittests/data/cppexceptions_to_be_exported.hpp
e7c55df3b10936ddd85f544d174f41fccdb02dfb
[ "BSL-1.0" ]
permissive
gatoatigrado/pyplusplusclone
30af9065fb6ac3dcce527c79ed5151aade6a742f
a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede
refs/heads/master
2016-09-05T23:32:08.595261
2010-05-16T10:53:45
2010-05-16T10:53:45
700,369
4
2
null
null
null
null
UTF-8
C++
false
false
740
hpp
// Copyright 2004-2008 Roman Yakovenko. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef __cppexceptions_to_be_exported_hpp__ #define __cppexceptions_to_be_exported_hpp__ #include <string> namespace cppexceptions{ struct custom_exception_t{ custom_exception_t( const std::string& error ) : m_error( error ) {} const std::string& what() const{ return m_error; } private: const std::string m_error; }; inline void throw_custom_exception(){ throw custom_exception_t( "profe of concept" ); } } #endif//__cppexceptions_to_be_exported_hpp__
[ "roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76" ]
[ [ [ 1, 32 ] ] ]
d3df683c368676afb1bb5068f25afc6b38aae94f
155c4955c117f0a37bb9481cd1456b392d0e9a77
/Tessa/TessaVisitors/TypePropagator.cpp
f8a55f17eee1b20941d4aad85073765fea57073d
[]
no_license
zwetan/tessa
605720899aa2eb4207632700abe7e2ca157d19e6
940404b580054c47f3ced7cf8995794901cf0aaa
refs/heads/master
2021-01-19T19:54:00.236268
2011-08-31T00:18:24
2011-08-31T00:18:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,873
cpp
#include "TessaVisitors.h" /*** * Iterates over the instructions in a given function and tries to resolve the types of each instruction. * This has the side effect of setting the type of result field in each instruction. * At the moment, this also assumes that the function accepts parameters as Atoms only and therefore can only do * analysis on local variables. Every instruction shall have a value for typeOfResult. * The types we analyze are currently only the ActionScript primitive types. If we don't know the type of a value, * the type is set to ANY, which corresponds to an Atom. * * This means any TYPE we set in here, is a CONCRETE type that we KNOW is correct. It is not * a guess, the type becomes fact */ namespace TessaVisitors { using namespace TessaVM; using namespace TessaInstructions; using namespace avmplus; TypePropagator::TypePropagator(AvmCore* core, MMgc::GC* gc) { this->_core = core; this->_gc = gc; _typeFactory = TypeFactory::getInstance(); _specializedIntegerBinaryInstructions = new (_gc) List<BinaryInstruction*, LIST_GCObjects>(_gc); _verifierTypes = new (_gc) avmplus::GCSortedMap<TessaInstruction*, Type*, avmplus::LIST_GCObjects>(_gc); } Type* TypePropagator::getVerifierType(TessaInstruction* value) { Type* verifierType = _verifierTypes->get(value); AvmAssert(verifierType != NULL); return verifierType; } void TypePropagator::visit(TessaInstruction* tessaInstruction) { TessaAssert(false); } void TypePropagator::visit(FindPropertyInstruction* findPropertyInstruction) { // This will always be this type if (findPropertyInstruction->isFindDefinition()) { findPropertyInstruction->setType(_typeFactory->scriptObjectType()); } else { findPropertyInstruction->setType(_typeFactory->anyType()); } } void TypePropagator::visit(ConstantValueInstruction* constantValueInstruction) { // Already have the type information when the instruction was created } void TypePropagator::visit(ArrayOfInstructions* arrayOfInstructions) { } void TypePropagator::visit(NewObjectInstruction* newObjectInstruction) { // Already have the type information when the instruction was created newObjectInstruction->setType(_typeFactory->scriptObjectType()); } void TypePropagator::visit(ConstructInstruction* constructInstruction) { } void TypePropagator::visit(ConstructPropertyInstruction* constructPropertyInstruction) { } void TypePropagator::visit(ConstructSuperInstruction* constructSuperInstruction) { } void TypePropagator::visit(CallInstruction* callInstruction) { } void TypePropagator::visit(CallVirtualInstruction* callVirtualInstruction) { } void TypePropagator::visit(CallStaticInstruction* callStaticInstruction) { } void TypePropagator::visit(LoadVirtualMethodInstruction* loadVirtualMethodInstruction) { } void TypePropagator::visit(CallInterfaceInstruction* callInterfaceInstruction) { } void TypePropagator::visit(CallSuperInstruction* callSuperInstruction) { } void TypePropagator::visit(CallPropertyInstruction* callPropertyInstruction) { } void TypePropagator::visit(ReturnInstruction* returnInstruction) { } bool TypePropagator::canPrecomputeBinaryOperation(BinaryInstruction* binaryInstruction) { TessaValue* leftOperand = binaryInstruction->getLeftOperand(); TessaValue* rightOperand = binaryInstruction->getRightOperand(); return (leftOperand->isInteger() && rightOperand->isInteger() && leftOperand->isConstantValue() && rightOperand->isConstantValue()); } /*** * A direct instruction is one that is resolved to it's original source. * For example, parameter instructions will be resolved to their forwareded instruction. * Coerce instructions get pushed through to the actual instruction they need to coerce. * This goes up through any chain to find the original value, not a coerced/indirect value */ TessaInstruction* TypePropagator::getDirectInstruction(TessaInstruction* instruction) { instruction = instruction->resolve(); while (instruction->isCoerce()) { CoerceInstruction* coerceInstruction = reinterpret_cast<CoerceInstruction*>(instruction); Type* coercedType = coerceInstruction->getType(); Type* originalType = coerceInstruction->getInstructionToCoerce()->getType(); if (originalType->isDownCast(coercedType) || coercedType->isHorizontalType(originalType)) { return coerceInstruction; } instruction = coerceInstruction->getInstructionToCoerce()->resolve(); } return instruction; } /*** * A properly typed direct instruction may return an actual instruction or a COERCE to the typeToFind * For example, we may have a paramter that points to a coerce instruction C. The coerce may point to * another BinaryInstruction that returns a number. The Coerce C coerces the Binary to Int. * If the typeToFind is the number, we return the number instruction. If the typeToFind is an int, we return * the Coerce instruction. */ TessaInstruction* TypePropagator::getProperlyTypedDirectInstruction(TessaInstruction* instruction, Type* typeToFind) { while ((instruction->getType() != typeToFind) || (instruction->isCoerce() || (instruction->isParameter()))) { if (instruction->isParameter()) { // Probably a method parameter if (instruction == instruction->resolve()) { return instruction; } instruction = instruction->resolve(); } else if (instruction->isCoerce()) { CoerceInstruction* coerceInstruction = reinterpret_cast<CoerceInstruction*>(instruction); instruction = coerceInstruction->getInstructionToCoerce(); Type* coerceType = coerceInstruction->getType(); Type* originalType = instruction->getType(); /*** * Sometimes we may specialize so much that the original type is the same as the coerce tyep * then the original type goes up the type lattice, so that the coerce becomes a downcast. * Keep the coerce around */ if (originalType->isDownCast(coerceType) || (originalType == coerceType)) { AvmAssert(typeToFind->isCompatibleType(coerceType)); return coerceInstruction; } // We have some crazy type stuff going on here //if (originalType->isHorizontalType(coerceType) && !originalType->isCompatibleType(typeToFind)) { //if (originalType->isHorizontalType(coerceType) && (originalType != typeToFind)) { if (originalType->isHorizontalType(coerceType)) { return coerceInstruction; } instruction = instruction->resolve(); } else { Type* instructionType = instruction->getType(); AvmAssert(typeToFind->isCompatibleType(instructionType)); return instruction; } } AvmAssert(instruction->getType() == typeToFind); return instruction; } bool TypePropagator::isConstantIntOne(TessaInstruction* constantValue) { if (constantValue->isConstantValue()) { ConstantValueInstruction* constantInstruction = reinterpret_cast<ConstantValueInstruction*>(constantValue); if (constantInstruction->isInteger()) { ConstantValue* constant = constantInstruction->getConstantValue(); if (constant->isInteger()) { ConstantInt* constInt = reinterpret_cast<ConstantInt*>(constant); int integerValue = constInt->getValue(); return integerValue == 1; } } } return false; } /*** * Look for the operand and see find the coerce instruction that coerces said operand into a number */ TessaInstruction* TypePropagator::findNumericOperand(BinaryInstruction* binaryInstruction, TessaInstruction* operand) { AvmAssert(!operand->isNumeric()); BasicBlock* parentBlock = operand->getInBasicBlock(); List<TessaInstruction*, LIST_GCObjects>* instructions = parentBlock->getInstructions(); int currentOperand = parentBlock->getInstructionIndex(operand); for (uint32_t i = currentOperand; i < instructions->size(); i++) { TessaInstruction* currentInstruction = instructions->get(i); if (currentInstruction->isCoerce()) { CoerceInstruction* coerceInstruction = reinterpret_cast<CoerceInstruction*>(currentInstruction); TessaInstruction* instructionToCoerce = coerceInstruction->getInstructionToCoerce(); if (instructionToCoerce == operand) { AvmAssert(instructionToCoerce->isNumeric()); return operand; } } } // Oh we're really lost, manually insert a coerce instruction. BasicBlock* binaryBlock = binaryInstruction->getInBasicBlock(); CoerceInstruction* coerceToNumber = new (_gc) CoerceInstruction(NULL, operand, _typeFactory->getInstance()->numberType(), binaryBlock); binaryBlock->removeInstruction(coerceToNumber); binaryBlock->addInstructionBefore(coerceToNumber, binaryInstruction); return coerceToNumber; } void TypePropagator::setBinaryType(BinaryInstruction* binaryInstruction, Type* strictestType) { TessaBinaryOp op = binaryInstruction->getOpcode(); TessaInstruction* leftOperand = binaryInstruction->getLeftOperand()->toInstruction(); TessaInstruction* rightOperand = binaryInstruction->getRightOperand()->toInstruction(); Type* leftType = leftOperand->getType(); Type* rightType = rightOperand->getType(); Type* newBinaryType = strictestType; switch (op) { case ADD: { if (leftType->isString() || rightType->isString()) { newBinaryType = _typeFactory->getInstance()->stringType(); } else if (leftType->isInteger() && (rightType->isInteger()) && (!newBinaryType->isInteger())) { newBinaryType = _typeFactory->getInstance()->numberType(); /* if (isConstantIntOne(leftOperand) || isConstantIntOne(rightOperand)) { // Means we have something++ newBinaryType = _typeFactory->getInstance()->integerType(); } else { newBinaryType = _typeFactory->getInstance()->numberType(); } */ } break; } case SUBTRACT: { if (leftType->isInteger() && (rightType->isInteger()) && (!newBinaryType->isInteger())) { newBinaryType = _typeFactory->getInstance()->numberType(); /* if (isConstantIntOne(leftOperand) || isConstantIntOne(rightOperand)) { // Means we have something-- newBinaryType = _typeFactory->getInstance()->integerType(); } else { newBinaryType = _typeFactory->getInstance()->numberType(); } */ break; } // Fall through to cases with mod, mul, div } case MOD: case MULTIPLY: case DIVIDE: { // Have to be a number if (!leftOperand->isNumeric()) { leftOperand = findNumericOperand(binaryInstruction, leftOperand); } if (!rightOperand->isNumeric()) { rightOperand = findNumericOperand(binaryInstruction, rightOperand); } AvmAssert(leftOperand->isNumeric()); AvmAssert(rightOperand->isNumeric()); newBinaryType = _typeFactory->numberType(); break; } case BITWISE_AND: case BITWISE_OR: case BITWISE_XOR: case BITWISE_LSH: case BITWISE_RSH: case BITWISE_URSH: newBinaryType = _typeFactory->integerType(); break; default: // Use strictest type break; } TessaInstruction* leftValue = getProperlyTypedDirectInstruction(leftOperand, newBinaryType); TessaInstruction* rightValue = getProperlyTypedDirectInstruction(rightOperand, newBinaryType); AvmAssert(binaryOperandsAreCompatible(binaryInstruction->getOpcode(), newBinaryType, leftValue->getType(), rightValue->getType())); binaryInstruction->setType(newBinaryType); binaryInstruction->setLeftOperand(leftValue); binaryInstruction->setRightOperand(rightValue); } bool TypePropagator::binaryOperandsAreCompatible(TessaBinaryOp op, Type* binaryType, Type* leftType, Type* rightType) { switch (op) { case MOD: case MULTIPLY: case DIVIDE: case BITWISE_AND: case BITWISE_OR: case BITWISE_XOR: case BITWISE_LSH: case BITWISE_RSH: case BITWISE_URSH: return leftType->isNumeric() && rightType->isNumeric(); default: return binaryType->isCompatibleType(leftType) && binaryType->isCompatibleType(rightType); } AvmAssert(false); return false; } void TypePropagator::visit(BinaryInstruction* binaryInstruction) { // Don't touch if (isSpecializedBinaryInteger(binaryInstruction)) { return; } TessaValue* leftOperand = binaryInstruction->getLeftOperand(); TessaValue* rightOperand = binaryInstruction->getRightOperand(); if (leftOperand->isInstruction() && rightOperand->isInstruction()) { List<TessaInstruction*, LIST_GCObjects>* binaryOperands = binaryInstruction->getOperandsAsInstructions(_gc); Type* strictestType = getStrictestType(binaryInstruction, binaryOperands); setBinaryType(binaryInstruction, strictestType); } // Otherwise we really can't do anything } void TypePropagator::visit(ConditionInstruction* conditionInstruction) { this->visit(reinterpret_cast<BinaryInstruction*>(conditionInstruction)); conditionInstruction->setType(_typeFactory->boolType()); } void TypePropagator::visit(UnaryInstruction* unaryInstruction) { // By specification, these are the results of the operation switch (unaryInstruction->getOpcode()) { case BITWISE_NOT: unaryInstruction->setType(_typeFactory->integerType()); break; case NEGATE: unaryInstruction->setType(_typeFactory->numberType()); break; case NOT: unaryInstruction->setType(_typeFactory->boolType()); break; } } void TypePropagator::visit(ConditionalBranchInstruction* conditionalBranchInstruction) { } void TypePropagator::visit(UnconditionalBranchInstruction* unconditionalBranchInstruction) { } void TypePropagator::visit(PhiInstruction* phiInstruction) { int numberOfOperands = phiInstruction->numberOfOperands(); Type* phiType = getStrictestType(phiInstruction, phiInstruction->getOperandsAsInstructions(_gc)); phiInstruction->setType(phiType); for (int i = 0; i < numberOfOperands; i++) { BasicBlock* incomingBlock = phiInstruction->getIncomingEdge(i); TessaInstruction* incomingOperand = phiInstruction->getOperand(incomingBlock); TessaInstruction* properlyTypedValue = getProperlyTypedDirectInstruction(incomingOperand, phiType); Type* operandType = properlyTypedValue->getType(); AvmAssert(phiType->isCompatibleType(operandType)); if ((properlyTypedValue != phiInstruction) && (properlyTypedValue->getInBasicBlock() == incomingBlock)) { phiInstruction->setOperand(incomingBlock, properlyTypedValue); } else { AvmAssert(incomingOperand->getInBasicBlock() == incomingBlock); //AvmAssert(incomingOperand->isParameter()); //AvmAssert(incomingOperand->resolve() == phiInstruction); //TessaInstruction* resolvedInstruction = incomingOperand->resolve(); //AvmAssert(resolvedInstruction == properlyTypedValue); } } } void TypePropagator::visit(ParameterInstruction* parameterInstruction) { TessaInstruction* resolvedInstruction = parameterInstruction->resolve(); parameterInstruction->setType(resolvedInstruction->getType()); } /*** * The ABC verifier automatically assumes that the result of an addition, subtract, and multiply * are the number type. A conversion is then required to convert it back to an integer when assigning * those operations to an integer variable. * * It's much faster to just do the binary operation as an integer, which we try to convert here */ bool TypePropagator::isCoercingToIntegerType(TessaValue* value) { if (value->isInstruction()) { TessaInstruction* instruction= static_cast<TessaInstruction*>(value); if (instruction->isCoerce()) { CoerceInstruction* coerceInstruction = static_cast<CoerceInstruction*>(instruction); TessaInstruction* instructionToCoerce = coerceInstruction->getInstructionToCoerce(); Type* originalType = instructionToCoerce->getType(); Type* convertedType = coerceInstruction ->getType(); if ((originalType->isInteger()) && (convertedType->isNumber())) { return true; } } else if (instruction->getType()->isInteger()) { return true; } } return false; } bool TypePropagator::canSpecializeIntegerBinaryOperation(CoerceInstruction* coerceInstruction) { TessaInstruction* instructionToCoerce = coerceInstruction->getInstructionToCoerce(); Type* typeOfOriginal = instructionToCoerce->getType(); Type* typeToConvert = coerceInstruction->getType(); if (instructionToCoerce->isBinary() && (typeOfOriginal->isNumber()) && (typeToConvert->isInteger())) { BinaryInstruction* binaryInstruction = static_cast<BinaryInstruction*>(instructionToCoerce); TessaValue* leftOperand = binaryInstruction->getLeftOperand(); TessaValue* rightOperand = binaryInstruction->getRightOperand(); if (isCoercingToIntegerType(leftOperand) && isCoercingToIntegerType(rightOperand)) { switch (binaryInstruction->getOpcode()) { case ADD: case MULTIPLY: case SUBTRACT: return true; default: break; } } } return false; } TessaValue* TypePropagator::getIntegerOperandToBinary(TessaValue* binaryOperand) { if (binaryOperand->getType()->isInteger()) { return binaryOperand; } else if (binaryOperand->isInstruction()) { TessaInstruction* binaryInstruction = static_cast<TessaInstruction*>(binaryOperand); if (binaryInstruction->isCoerce()) { CoerceInstruction* coerceInstruction = static_cast<CoerceInstruction*>(binaryOperand); TessaInstruction* instructionToCoerce = coerceInstruction->getInstructionToCoerce(); Type* originalType = instructionToCoerce->getType(); Type* convertedType = coerceInstruction->getType(); TessaAssert(originalType->isInteger()); TessaAssert(convertedType->isNumber()); return instructionToCoerce; } else { return binaryOperand; } } else { TessaAssertMessage(false, "Specializing binary operation with integers, but no integer operand"); return binaryOperand; } } bool TypePropagator::isSpecializedBinaryInteger(BinaryInstruction* binaryInstruction) { return _specializedIntegerBinaryInstructions->contains(binaryInstruction); } void TypePropagator::specializeIntegerBinaryOperation(CoerceInstruction* coerceInstruction) { TessaAssert(coerceInstruction->getInstructionToCoerce()->isBinary()); BinaryInstruction* binaryInstruction = static_cast<BinaryInstruction*>(coerceInstruction->getInstructionToCoerce()); TessaValue* leftIntegerOperand = getIntegerOperandToBinary(binaryInstruction->getLeftOperand()); TessaValue* rightIntegerOperand = getIntegerOperandToBinary(binaryInstruction->getRightOperand()); TessaAssert(leftIntegerOperand->getType()->isInteger()); TessaAssert(rightIntegerOperand->getType()->isInteger()); binaryInstruction->setLeftOperand(leftIntegerOperand); binaryInstruction->setRightOperand(rightIntegerOperand); binaryInstruction->setType(_typeFactory->integerType()); _specializedIntegerBinaryInstructions->add(binaryInstruction); } void TypePropagator::visit(ConvertInstruction* convertInstruction) { if (canSpecializeIntegerBinaryOperation(convertInstruction)) { specializeIntegerBinaryOperation(convertInstruction); } } void TypePropagator::visit(CoerceInstruction* coerceInstruction) { if (canSpecializeIntegerBinaryOperation(coerceInstruction)) { specializeIntegerBinaryOperation(coerceInstruction); } } bool TypePropagator::optimizeArrayGetAndSetProperty(PropertyAccessInstruction* propertyAccesss) { TessaInstruction* receiverInstruction = propertyAccesss->getReceiverInstruction(); if (receiverInstruction->isCoerce()) { CoerceInstruction* coerceInstruction = reinterpret_cast<CoerceInstruction*>(receiverInstruction); TessaInstruction* instructionToCoerce = coerceInstruction->getInstructionToCoerce(); Type* instructionType = instructionToCoerce->getType(); if (instructionToCoerce->isConstruct() && instructionType->isArray()) { propertyAccesss->setReceiverInstruction(instructionToCoerce); return true; } } return false; } bool TypePropagator::optimizeIntVectorGetAndSetProperty(PropertyAccessInstruction* propertyAccess) { Type* receiverType = propertyAccess->getReceiverInstruction()->getType(); if (receiverType->isVector()) { if (propertyAccess->getPropertyKey() != NULL) { TessaTypes::VectorType* vectorType = reinterpret_cast<TessaTypes::VectorType*>(receiverType); TessaTypes::Type* elementType = vectorType->getElementType(); bool isIntVector = elementType->isInteger() || elementType->isUnsignedInt(); propertyAccess->setType(elementType); return true; } } return false; } void TypePropagator::visit(GetPropertyInstruction* getPropertyInstruction) { if (!optimizeArrayGetAndSetProperty(getPropertyInstruction)) { optimizeIntVectorGetAndSetProperty(getPropertyInstruction); } } void TypePropagator::visit(SetPropertyInstruction* setPropertyInstruction) { if (!optimizeArrayGetAndSetProperty(setPropertyInstruction)) { optimizeIntVectorGetAndSetProperty(setPropertyInstruction); } } void TypePropagator::visit(InitPropertyInstruction* initPropertyInstruction) { } void TypePropagator::visit(GetSlotInstruction* getSlotInstruction) { } void TypePropagator::visit(SetSlotInstruction* setSlotInstruction) { } void TypePropagator::visit(NewArrayInstruction* newArrayInstruction) { newArrayInstruction->setType(_typeFactory->getInstance()->anyArrayType()); } void TypePropagator::visit(NextNameInstruction* nextNameInstruction) { } void TypePropagator::visit(PushScopeInstruction* pushScopeInstruction) { } void TypePropagator::visit(PopScopeInstruction* popScopeInstruction) { } void TypePropagator::visit(WithInstruction* withInstruction) { } void TypePropagator::visit(TypeOfInstruction* typeOfInstruction) { typeOfInstruction->setType(_typeFactory->anyType()); } void TypePropagator::visit(GetScopeObjectInstruction* getScopeObjectInstruction) { getScopeObjectInstruction->setType(_typeFactory->scriptObjectType()); } void TypePropagator::visit(GetGlobalScopeInstruction* getGlobalScopeInstruction) { getGlobalScopeInstruction->setType(_typeFactory->scriptObjectType()); } void TypePropagator::visit(HasMorePropertiesInstruction* hasMorePropertiesInstruction) { } void TypePropagator::visit(HasMorePropertiesObjectInstruction* hasMorePropertiesInstruction) { } void TypePropagator::visit(HasMorePropertiesRegisterInstruction* hasMorePropertiesRegisterInstruction) { } void TypePropagator::visit(SwitchInstruction* switchInstruction) { } void TypePropagator::visit(CaseInstruction* caseInstruction) { } void TypePropagator::visit(NewActivationInstruction* newActivationInstruction) { } void TypePropagator::visit(InlineBeginInstruction* inlineBeginInstruction) { } /*** * Go through all the operands and find the "strictest" type. * Strictness is defined as the type at which all operands can be coerced to. * For example, int and number, the strictest type is number since integer is a subtype of number. * Worst case scenario is the any type. * This in the formal term, is going UP the type lattice */ Type* TypePropagator::getStrictestType(TessaInstruction* originalInstruction, List<TessaInstruction*, LIST_GCObjects>* operands) { AvmAssert(operands->size() >= 1); Type* strictestType = getDirectInstruction(operands->get(0))->getType(); for (uint32_t i = 0; i < operands->size(); i++) { TessaInstruction* currentOperand = operands->get(i); Type* currentType = currentOperand->getType(); TessaInstruction* directInstruction = getDirectInstruction(currentOperand); Type* directType = directInstruction->getType(); if (directInstruction == originalInstruction) { AvmAssert(originalInstruction->isPhi()); } else { strictestType = strictestType->getStrictestType(directType); } } return strictestType; } /*** * Finds the lowest type on the type lattice, which is the inverse of getStrictestType */ Type* TypePropagator::getMostConcreteType(List<TessaValue*, LIST_GCObjects>* operands) { AvmAssert(operands != NULL); Type* mostConcreteType = _typeFactory->getInstance()->anyType(); //operands->get(0)->getType(); for (uint32_t i = 0; i < operands->size(); i++) { TessaValue* currentOperand = operands->get(i); Type* directType = currentOperand->getType(); if (currentOperand->isInstruction()) { TessaInstruction* instructionOperand = reinterpret_cast<TessaInstruction*>(currentOperand); TessaInstruction* directInstruction = getDirectInstruction(instructionOperand); directType = directInstruction->getType(); } mostConcreteType = mostConcreteType->getMostConcreteType(directType); } return mostConcreteType; } void TypePropagator::propagateTypes(ASFunction* function) { _isDone = true; List<BasicBlock*, avmplus::LIST_GCObjects>* basicBlocks = function->getBasicBlocksInReversePostOrder(); for (uint32_t basicBlockIndex = 0; basicBlockIndex < basicBlocks->size(); basicBlockIndex++) { BasicBlock* basicBlock = basicBlocks->get(basicBlockIndex); List<TessaInstruction*, avmplus::LIST_GCObjects>* instructions = basicBlock->getInstructions(); for (uint32_t i = 0; i < instructions->size(); i++) { TessaInstruction* currentInstruction = instructions->get(i); Type* originalType = currentInstruction->getType(); //currentInstruction->print(); currentInstruction->visit(this); Type* newType = currentInstruction->getType(); //currentInstruction->print(); if (newType != originalType) { _isDone = false; } } } } /*** * Only instructions that operate on local variables can change their types. Or instructions that exist on the stack. * Values that exist in the heap, field variables and get/set property, cannot change */ bool TypePropagator::canChangeTypes(TessaInstruction* instruction) { bool immuneInstruction = instruction->isCoerce() || instruction->isPropertyAccess() || instruction->isSlotAccess() || instruction->isReturn() || instruction->isNewActivation() || instruction->isNewArray() || instruction->isCall() || instruction->isArrayOfInstructions() || instruction->isBranch(); return !immuneInstruction; } void TypePropagator::initializeTypes(ASFunction* function) { List<BasicBlock*, avmplus::LIST_GCObjects>* basicBlocks = function->getBasicBlocksInReversePostOrder(); for (uint32_t basicBlockIndex = 0; basicBlockIndex < basicBlocks->size(); basicBlockIndex++) { BasicBlock* basicBlock = basicBlocks->get(basicBlockIndex); List<TessaInstruction*, avmplus::LIST_GCObjects>* instructions = basicBlock->getInstructions(); for (uint32_t i = 0; i < instructions->size(); i++) { TessaInstruction* currentInstruction = instructions->get(i); Type* verifierType = currentInstruction->getType(); _verifierTypes->put(currentInstruction, verifierType); //currentInstruction->print(); Type* currentType = getMostConcreteType(currentInstruction->getOperands(_gc)); // Can't do anything about field variables if (canChangeTypes(currentInstruction)) { currentInstruction->setType(currentType); } //currentInstruction->print(); //printf("Initialized\n\n"); } } } void TypePropagator::propagateTypeInformation(ASFunction* function) { #ifdef DEBUG if (_core->config.tessaVerbose) { printf("\n\n==== Type Propagation ====\n"); } #endif _isDone = false; initializeTypes(function); while (!_isDone) { propagateTypes(function); } #ifdef DEBUG if (_core->config.tessaVerbose) { function->printResults(); } #endif } /*** * Can only have an accurate phi type if ALL the phi operands are the same type. * Otherwise return any type */ Type* TypePropagator::conservativePhiType(PhiInstruction* phiInstruction) { int numberOfOperands = phiInstruction->numberOfOperands(); BasicBlock* firstBlock = phiInstruction->getIncomingEdge(0); TessaInstruction* firstOperand = phiInstruction->getOperand(firstBlock); Type* initialType = firstOperand->getType(); for (int i = 0; i < numberOfOperands; i++) { BasicBlock* comingFrom = phiInstruction->getIncomingEdge(i); TessaInstruction* operand = phiInstruction->getOperand(comingFrom); Type* operandType = operand->getType(); if (operandType != initialType) { return _typeFactory->anyType(); } } return initialType; } /*** * Leave the verifier types as is. Only set the type for phis */ void TypePropagator::resolvePhiTypesOnly(ASFunction* function) { List<BasicBlock*, avmplus::LIST_GCObjects>* basicBlocks = function->getBasicBlocksInReversePostOrder(); for (uint32_t basicBlockIndex = 0; basicBlockIndex < basicBlocks->size(); basicBlockIndex++) { BasicBlock* basicBlock = basicBlocks->get(basicBlockIndex); List<PhiInstruction*, avmplus::LIST_GCObjects>* phiInstructions = basicBlock->getPhiInstructions(); for (uint32_t i = 0; i < phiInstructions->size(); i++) { PhiInstruction* currentInstruction = phiInstructions->get(i); Type* phiType = conservativePhiType(currentInstruction); currentInstruction->setType(phiType); } } #ifdef DEBUG if (_core->config.tessaVerbose) { function->printResults(); } #endif } }
[ [ [ 1, 781 ] ] ]
069953c7f0b65534de276b5f6ba02f1233b2fc7d
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Graphics/VertexStructs.cpp
b7f2d4765afc13ebf091701ae875e11689bbe2a2
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
39,300
cpp
#include "VertexsStructs.h" #include "Texture.h" LPDIRECT3DVERTEXDECLARATION9 SDIFFUSEVERTEX::s_VertexDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SSIMPLEVERTEX::s_VertexDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SDIFFUSESCREENVERTEX::s_VertexDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 STEXTUREDSCREENVERTEX::s_VertexDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SDIFFUSETEXTUREDSCREENVERTEX::s_VertexDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 STEXTUREDVERTEX::s_VertexDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 STEXTURED2VERTEX::s_VertexDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SNORMALDIFFUSEVERTEX::s_VertexDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SNORMALTEXTUREDVERTEX::s_VertexDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SNORMALTEXTURED2VERTEX::s_VertexDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 TNORMALTANGENTBINORMALTEXTUREDVERTEX::s_VertexDeclaration=0; LPDIRECT3DVERTEXDECLARATION9 TNORMALTANGENTBINORMALTEXTURED2VERTEX::s_VertexDeclaration=0; LPDIRECT3DVERTEXDECLARATION9 TCAL3D_HW_VERTEX::s_VertexDeclaration=0; LPDIRECT3DVERTEXDECLARATION9 SPARTICLE_VERTEX::s_VertexDeclaration=0; // Instanced declarations ------------------------------------------------------ LPDIRECT3DVERTEXDECLARATION9 SDIFFUSEVERTEX::s_VertexInstancedDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SSIMPLEVERTEX::s_VertexInstancedDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SDIFFUSESCREENVERTEX::s_VertexInstancedDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 STEXTUREDSCREENVERTEX::s_VertexInstancedDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SDIFFUSETEXTUREDSCREENVERTEX::s_VertexInstancedDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 STEXTUREDVERTEX::s_VertexInstancedDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 STEXTURED2VERTEX::s_VertexInstancedDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SNORMALDIFFUSEVERTEX::s_VertexInstancedDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SNORMALTEXTUREDVERTEX::s_VertexInstancedDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 SNORMALTEXTURED2VERTEX::s_VertexInstancedDeclaration = 0; LPDIRECT3DVERTEXDECLARATION9 TNORMALTANGENTBINORMALTEXTUREDVERTEX::s_VertexInstancedDeclaration=0; LPDIRECT3DVERTEXDECLARATION9 TNORMALTANGENTBINORMALTEXTURED2VERTEX::s_VertexInstancedDeclaration=0; LPDIRECT3DVERTEXDECLARATION9 TCAL3D_HW_VERTEX::s_VertexInstancedDeclaration=0; LPDIRECT3DVERTEXDECLARATION9 SPARTICLE_VERTEX::s_VertexInstancedDeclaration=0; //--------------------------------------------------------------------------------------------- uint16 GetVertexSize(uint16 _usVertexType) { if(_usVertexType == SDIFFUSEVERTEX::GetVertexType()) { return sizeof(SDIFFUSEVERTEX); } else if(_usVertexType == SSIMPLEVERTEX::GetVertexType()) { return sizeof(SSIMPLEVERTEX); } else if(_usVertexType == STEXTUREDVERTEX::GetVertexType()) { return sizeof(STEXTUREDVERTEX); } else if(_usVertexType == STEXTURED2VERTEX::GetVertexType()) { return sizeof(STEXTURED2VERTEX); } else if(_usVertexType == STEXTUREDSCREENVERTEX::GetVertexType()) { return sizeof(STEXTUREDSCREENVERTEX); } else if(_usVertexType == SDIFFUSETEXTUREDSCREENVERTEX::GetVertexType()) { return sizeof(SDIFFUSETEXTUREDSCREENVERTEX); } else if(_usVertexType == SDIFFUSESCREENVERTEX::GetVertexType()) { return sizeof(SDIFFUSESCREENVERTEX); } else if(_usVertexType == SNORMALDIFFUSEVERTEX::GetVertexType()) { return sizeof(SNORMALDIFFUSEVERTEX); } else if(_usVertexType == SNORMALTEXTUREDVERTEX::GetVertexType()) { return sizeof(SNORMALTEXTUREDVERTEX); } else if(_usVertexType == SNORMALTEXTURED2VERTEX::GetVertexType()) { return sizeof(SNORMALTEXTURED2VERTEX); } else if(_usVertexType == TNORMALTANGENTBINORMALTEXTUREDVERTEX::GetVertexType()) { return sizeof(TNORMALTANGENTBINORMALTEXTUREDVERTEX); } else if(_usVertexType == TNORMALTANGENTBINORMALTEXTURED2VERTEX::GetVertexType()) { return sizeof(TNORMALTANGENTBINORMALTEXTURED2VERTEX); } else if(_usVertexType == SPARTICLE_VERTEX::GetVertexType()) { return sizeof(SPARTICLE_VERTEX); } else { return 0; } } uint16 GetTextureNum(uint16 _usVertexType) { /*uint16 num = 0; if(_usVertexType & VERTEX_TYPE_TEXTURE1) { num += 1; } else if(_usVertexType & VERTEX_TYPE_TEXTURE2) { num += 2; } if(_usVertexType & VERTEX_TYPE_TANGENT & VERTEX_TYPE_BINORMAL ) { num += 2; } return num;*/ if(_usVertexType == SDIFFUSEVERTEX::GetVertexType()) { return 1; } else if(_usVertexType == SSIMPLEVERTEX::GetVertexType()) { return 0; } else if(_usVertexType == STEXTUREDVERTEX::GetVertexType()) { return 2; } else if(_usVertexType == STEXTUREDSCREENVERTEX::GetVertexType()) { return 1; } else if(_usVertexType == SDIFFUSETEXTUREDSCREENVERTEX::GetVertexType()) { return 1; } else if(_usVertexType == SDIFFUSESCREENVERTEX::GetVertexType()) { return 0; } else if(_usVertexType == STEXTURED2VERTEX::GetVertexType()) { return 3; } else if(_usVertexType == SNORMALDIFFUSEVERTEX::GetVertexType()) { return 0; } else if(_usVertexType == SNORMALTEXTUREDVERTEX::GetVertexType()) { return 1; } else if(_usVertexType == SNORMALTEXTURED2VERTEX::GetVertexType()) { return 2; } else if(_usVertexType == TNORMALTANGENTBINORMALTEXTUREDVERTEX::GetVertexType()) { return 2; } else if(_usVertexType == TNORMALTANGENTBINORMALTEXTURED2VERTEX::GetVertexType()) { return 3; } else { return 0; } } // Diffuse Vertex ----------------------------------------------------------------------------------------------------------- unsigned short SDIFFUSEVERTEX::GetVertexType() { return VERTEX_TYPE_GEOMETRY|VERTEX_TYPE_DIFFUSE; } unsigned int SDIFFUSEVERTEX::GetFVF() { return D3DFVF_XYZ|D3DFVF_DIFFUSE; } LPDIRECT3DVERTEXDECLARATION9& SDIFFUSEVERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& SDIFFUSEVERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, //Buffer { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Simple Vertex ----------------------------------------------------------------------------------------------------------- unsigned short SSIMPLEVERTEX::GetVertexType() { return VERTEX_TYPE_GEOMETRY; } unsigned int SSIMPLEVERTEX::GetFVF() { return D3DFVF_XYZ; } LPDIRECT3DVERTEXDECLARATION9& SSIMPLEVERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& SSIMPLEVERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, //Buffer { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Diffuse Screen Vertex ----------------------------------------------------------------------------------------------------------- unsigned short SDIFFUSESCREENVERTEX::GetVertexType() { return VERTEX_TYPE_SCREENGEO|VERTEX_TYPE_DIFFUSE|VERTEX_TYPE_TEXTURE1; } unsigned int SDIFFUSESCREENVERTEX::GetFVF() { return D3DFVF_XYZRHW|D3DFVF_DIFFUSE; } LPDIRECT3DVERTEXDECLARATION9& SDIFFUSESCREENVERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT, 0 }, { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& SDIFFUSESCREENVERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT, 0 }, { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, //Buffer { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Textured Screen Vertex ----------------------------------------------------------------------------------------------------------- unsigned short STEXTUREDSCREENVERTEX::GetVertexType() { return VERTEX_TYPE_SCREENGEO|VERTEX_TYPE_TEXTURE1; } unsigned int STEXTUREDSCREENVERTEX::GetFVF() { return D3DFVF_XYZRHW|D3DFVF_TEX1; } LPDIRECT3DVERTEXDECLARATION9& STEXTUREDSCREENVERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT, 0 }, { 0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& STEXTUREDSCREENVERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT, 0 }, { 0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, //Buffer { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Diffuse Textured Screen Vertex ----------------------------------------------------------------------------------------------------------- unsigned short SDIFFUSETEXTUREDSCREENVERTEX::GetVertexType() { return VERTEX_TYPE_SCREENGEO|VERTEX_TYPE_DIFFUSE|VERTEX_TYPE_TEXTURE1; } unsigned int SDIFFUSETEXTUREDSCREENVERTEX::GetFVF() { return D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1; } LPDIRECT3DVERTEXDECLARATION9& SDIFFUSETEXTUREDSCREENVERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT, 0 }, { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, { 0, 12 + sizeof(uint32), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& SDIFFUSETEXTUREDSCREENVERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT, 0 }, { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, { 0, 12 + sizeof(uint32), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, //Buffer { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Normal Diffuse Vertex ----------------------------------------------------------------------------------------------------------- unsigned short SNORMALDIFFUSEVERTEX::GetVertexType() { return VERTEX_TYPE_GEOMETRY|VERTEX_TYPE_NORMAL|VERTEX_TYPE_DIFFUSE; } unsigned int SNORMALDIFFUSEVERTEX::GetFVF() { return D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_DIFFUSE; } LPDIRECT3DVERTEXDECLARATION9& SNORMALDIFFUSEVERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, 24, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& SNORMALDIFFUSEVERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, 24, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, //Buffer { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Normal Tangent Binormal Textured -------------------------------------------------------------------------------- unsigned short TNORMALTANGENTBINORMALTEXTUREDVERTEX::GetVertexType() { return VERTEX_TYPE_GEOMETRY | VERTEX_TYPE_NORMAL | VERTEX_TYPE_TANGENT | VERTEX_TYPE_BITANGENT | VERTEX_TYPE_TEXTURE1; } unsigned int TNORMALTANGENTBINORMALTEXTUREDVERTEX::GetFVF() { return D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1; //TODO? } LPDIRECT3DVERTEXDECLARATION9& TNORMALTANGENTBINORMALTEXTUREDVERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, sizeof(float)*7, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 }, { 0, sizeof(float)*11, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 }, { 0, sizeof(float)*15, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& TNORMALTANGENTBINORMALTEXTUREDVERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, sizeof(float)*7, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 }, { 0, sizeof(float)*11, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 }, { 0, sizeof(float)*15, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, //Buffer { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Normal Tangent Binormal Textured 2------------------------------------------------------------------------------- unsigned short TNORMALTANGENTBINORMALTEXTURED2VERTEX::GetVertexType() { return VERTEX_TYPE_GEOMETRY | VERTEX_TYPE_NORMAL | VERTEX_TYPE_TANGENT | VERTEX_TYPE_BITANGENT | VERTEX_TYPE_TEXTURE2; } unsigned int TNORMALTANGENTBINORMALTEXTURED2VERTEX::GetFVF() { return D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2; //TODO? } LPDIRECT3DVERTEXDECLARATION9& TNORMALTANGENTBINORMALTEXTURED2VERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3 , D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, sizeof(float)*7 , D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 }, { 0, sizeof(float)*11 , D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 }, { 0, sizeof(float)*15 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, sizeof(float)*17 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& TNORMALTANGENTBINORMALTEXTURED2VERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { //type sempre default (per meshes) //รบs de les dades { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3 , D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, sizeof(float)*7 , D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 }, { 0, sizeof(float)*11 , D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 }, { 0, sizeof(float)*15 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, sizeof(float)*17 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //Buffer // ----------------------------------------------------------------------------------------- //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Textured Vertex ------------------------------------------------------------------------------------------------- unsigned short STEXTUREDVERTEX::GetVertexType() { return VERTEX_TYPE_GEOMETRY|VERTEX_TYPE_TEXTURE1; } unsigned int STEXTUREDVERTEX::GetFVF() { return D3DFVF_XYZ|D3DFVF_TEX1; } LPDIRECT3DVERTEXDECLARATION9& STEXTUREDVERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& STEXTUREDVERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, //Buffer { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Textured 2 Vertex ----------------------------------------------------------------------------------------------- unsigned short STEXTURED2VERTEX::GetVertexType() { return VERTEX_TYPE_GEOMETRY|VERTEX_TYPE_TEXTURE2; } unsigned int STEXTURED2VERTEX::GetFVF() { return D3DFVF_XYZ|D3DFVF_TEX4; } LPDIRECT3DVERTEXDECLARATION9& STEXTURED2VERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, sizeof(float)*5 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& STEXTURED2VERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, sizeof(float)*5 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //Buffer //------------------------------------------------------------------------------------------------- //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Normal Textured Vertex ------------------------------------------------------------------------------------------ unsigned short SNORMALTEXTUREDVERTEX::GetVertexType() { return VERTEX_TYPE_GEOMETRY|VERTEX_TYPE_NORMAL|VERTEX_TYPE_TEXTURE1; } unsigned int SNORMALTEXTUREDVERTEX::GetFVF() { return D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX2; } LPDIRECT3DVERTEXDECLARATION9& SNORMALTEXTUREDVERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, sizeof(float)*6 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& SNORMALTEXTUREDVERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, sizeof(float)*6 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, //Buffer { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Normal Textured2 Vertex ----------------------------------------------------------------------------------------- unsigned short SNORMALTEXTURED2VERTEX::GetVertexType() { return VERTEX_TYPE_GEOMETRY|VERTEX_TYPE_NORMAL|VERTEX_TYPE_TEXTURE2; } unsigned int SNORMALTEXTURED2VERTEX::GetFVF() { return D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX4; } LPDIRECT3DVERTEXDECLARATION9& SNORMALTEXTURED2VERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, sizeof(float)*6 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, sizeof(float)*8 , D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& SNORMALTEXTURED2VERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, sizeof(float)*6, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, sizeof(float)*8, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Cal 3D Vertex --------------------------------------------------------------------------------------------------- LPDIRECT3DVERTEXDECLARATION9& TCAL3D_HW_VERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3 , D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 }, { 0, sizeof(float)*7 , D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 }, { 0, sizeof(float)*11, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, sizeof(float)*14, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, sizeof(float)*16, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 }, { 0, sizeof(float)*19, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& TCAL3D_HW_VERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, sizeof(float)*3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 }, { 0, sizeof(float)*7, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 }, { 0, sizeof(float)*11, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, sizeof(float)*14, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, sizeof(float)*16, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 }, { 0, sizeof(float)*19 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 }, //Buffer { 1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, //World matrix { 1, 16 * 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, 16 * 1, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 }, { 1, 16 * 2, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4 }, { 1, 16 * 3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 5 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; } // Particle Texture --------------------------------------------------------------------------------------------------- LPDIRECT3DVERTEXDECLARATION9& SPARTICLE_VERTEX::GetVertexDeclaration() { if(s_VertexDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { /* { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, D3DDECL_END() */ { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, //Buffer { 1, 0 , D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 1, sizeof(float)*4, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, { 1, sizeof(float)*8, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexDeclaration); assert(result == D3D_OK); } return s_VertexDeclaration; } LPDIRECT3DVERTEXDECLARATION9& SPARTICLE_VERTEX::GetInstancedVertexDeclaration() { if(s_VertexInstancedDeclaration==NULL) { D3DVERTEXELEMENT9 l_VertexDeclaration[] = { /* { 0, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, D3DDECL_END() */ { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, //Buffer { 1, 0 , D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 1, sizeof(float)*3, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, { 1, sizeof(float)*7, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, { 1, sizeof(float)*11, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, D3DDECL_END() }; HRESULT result = RENDER_MANAGER->GetDevice()->CreateVertexDeclaration(l_VertexDeclaration, &s_VertexInstancedDeclaration); assert(result == D3D_OK); } return s_VertexInstancedDeclaration; }
[ "atridas87@576ee6d0-068d-96d9-bff2-16229cd70485", "Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485", "edual1985@576ee6d0-068d-96d9-bff2-16229cd70485", "sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485" ]
[ [ [ 1, 5 ], [ 7, 17 ], [ 19, 28 ], [ 30, 56 ], [ 60, 69 ], [ 71, 74 ], [ 76, 117 ], [ 121, 200 ], [ 252, 870 ], [ 872, 886 ], [ 891, 892 ], [ 897, 903 ] ], [ [ 6, 6 ], [ 29, 29 ], [ 57, 59 ], [ 118, 120 ], [ 201, 251 ], [ 871, 871 ], [ 887, 890 ], [ 893, 896 ] ], [ [ 18, 18 ] ], [ [ 70, 70 ], [ 75, 75 ] ] ]
a9597d29f5612e7bd73a2a006969ba28b00ab345
6e8d3ce33ebaaf9895fdbc84ff8b4f99e4eccd50
/src/cpp/cpct_dll/cpct_dll/cpct_dll.cpp
0cb0f01f6f7b217f522f595dd2ea396e84b8e67f
[]
no_license
ssqre/cpct
b0b300c2800479628ff1e5d7b4729e35fa3bc7e3
65909bc28a8c742cbd512548a21b3c6cf1dcfb10
refs/heads/master
2020-04-10T15:50:27.560350
2011-09-19T07:45:39
2011-09-19T07:45:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,956
cpp
/* * Author : Copyright (c) Jie Deng * Author e-mail : [email protected] * * License : * cpct_dll processing library * Copyright (c) Jie Deng * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "stdafx.h" #include "cpct_dll.h" #include "../../cpct-mstftm/cpct-mstftm/CPCT_MSTFTM.h" #pragma comment(lib, "../Debug/cpct-mstftm.lib") using namespace CPCT; API_CPCT HANDLE createCpctByDefault() { CPCT_MSTFTM *cpct = new CPCT_MSTFTM(); return (HANDLE)cpct; } API_CPCT HANDLE createCpctByParams( int winlen, int hoplen, int nit ) { CPCT_MSTFTM *cpct = new CPCT_MSTFTM(winlen, hoplen, nit); return (HANDLE)cpct; } API_CPCT void setData( HANDLE h, const float* data, int datalength, int nChannels ) { CPCT_MSTFTM *cpct = (CPCT_MSTFTM*)h; cpct->setData(data, datalength, nChannels); } API_CPCT void setParams( HANDLE h, float tempo, float pitch ) { CPCT_MSTFTM *cpct = (CPCT_MSTFTM*)h; cpct->setParams(tempo, pitch); } API_CPCT void getData( HANDLE h, float* data, int& datalength ) { CPCT_MSTFTM *cpct = (CPCT_MSTFTM*)h; cpct->getData(data, datalength); } API_CPCT void destroyCpct( HANDLE h ) { CPCT_MSTFTM *cpct = (CPCT_MSTFTM*)h; delete cpct; }
[ "mr.dengjie@20198b2c-5f2b-bef7-f1b6-156c947877ec" ]
[ [ [ 1, 72 ] ] ]
898f92e8ebe2c3f0adbcbfa9a1228dbbb32d9b95
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Network/ggsrv.h
008dc4dbd31f356e136214c6cd808c4b69ca28e2
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
5,431
h
#ifndef _GG_AUTH_SERVER_H_ #define _GG_AUTH_SERVER_H_ #ifndef WIN32 typedef unsigned short WORD; typedef unsigned long DWORD; typedef void* LPVOID; typedef int BOOL; #endif #ifdef _EXPORT_DLL #define GGAUTHS_API extern "C" __declspec(dllexport) #define GGAUTHS_EXPORT __declspec(dllexport) #define __CDECL __cdecl #else #define GGAUTHS_API extern "C" //#define GGAUTHS_API <== ggsrv_cpp_c.h ์—์„œ ํ™œ์„ฑํ™”. extern "C" ๋Š” c ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ์ธ์‹๋ชปํ•จ. #define GGAUTHS_EXPORT #define __CDECL #endif #define NPGG_INFO_SUCCESS 0 //Get info success. #define NPGG_INFO_ERROR_NOTENOUGHFMEMORY 1 //Need more memory #define NPGG_CHECKUPDATED_VERIFIED 0 //csa.CheckUpdated() ํ•จ์ˆ˜ ๋ฆฌํ„ด๊ฐ’. ํ˜„์žฌ ๋ฒ„์ „ ์‚ฌ์šฉ์ž #define NPGG_CHECKUPDATED_NOTREADY 1 //csa.CheckUpdated() ํ•จ์ˆ˜ ๋ฆฌํ„ด๊ฐ’. ๋ฒ„์ „๊ฒ€์‚ฌ๋ฅผ ํ•˜๊ธฐ ์ „. ๋ฒ„์ „์— ๋Œ€ํ•œ ์ •๋ณด๊ฐ€ ์—†์Œ. #define NPGG_CHECKUPDATED_HIGH 2 //csa.CheckUpdated() ํ•จ์ˆ˜ ๋ฆฌํ„ด๊ฐ’. ํ˜„์žฌ ๋ฒ„์ „๋ณด๋‹ค ๋†’์€ ์‚ฌ์šฉ์ž #define NPGG_CHECKUPDATED_LOW 3 //csa.CheckUpdated() ํ•จ์ˆ˜ ๋ฆฌํ„ด๊ฐ’. ํ˜„์žฌ ๋ฒ„์ „๋ณด๋‹ค ๋‚ฎ์€ ์‚ฌ์šฉ์ž #define NPLOG_DEBUG 0x00000001 // ๋””๋ฒ„๊น… ๋ฉ”์„ธ์ง€ #define NPLOG_ERROR 0x00000002 // ์—๋Ÿฌ ๋ฉ”์„ธ์ง€ #define NPLOG_ENABLE_DEBUG 0x00000001 // ๋””๋ฒ„๊น… ๋ฉ”์„ธ์ง€ ์ƒ์„ฑํ•จ #define NPLOG_ENABLE_ERROR 0x00000002 // ์—๋Ÿฌ ๋ฉ”์„ธ์ง€ ์ƒ์„ฑํ•จ #define NPGG_USER_AUTH_QUERY 0x00000001 //GGAuthGetUserValue() ์˜ ์ „๋‹ฌ ํ”Œ๋ž˜๊ทธ Query #define NPGG_USER_AUTH_ANSWER 0x00000002 //GGAuthGetUserValue() ์˜ ์ „๋‹ฌ ํ”Œ๋ž˜๊ทธ Answer // #define NPGG_USER_AUTH_INDEX 0x00000010 //GGAuthGetUserValue() ์˜ ์ „๋‹ฌ ํ”Œ๋ž˜๊ทธ index #define NPGG_USER_AUTH_VALUE1 0x00000020 //GGAuthGetUserValue() ์˜ ์ „๋‹ฌ ํ”Œ๋ž˜๊ทธ Value1 #define NPGG_USER_AUTH_VALUE2 0x00000040 //GGAuthGetUserValue() ์˜ ์ „๋‹ฌ ํ”Œ๋ž˜๊ทธ Value2 #define NPGG_USER_AUTH_VALUE3 0x00000080 //GGAuthGetUserValue() ์˜ ์ „๋‹ฌ ํ”Œ๋ž˜๊ทธ Value3 // gameguard auth data typedef struct _GG_AUTH_DATA { DWORD dwIndex; DWORD dwValue1; DWORD dwValue2; DWORD dwValue3; } GG_AUTH_DATA, *PGG_AUTH_DATA; // gameguard version data typedef struct _GG_VERSION { DWORD dwGGVer; WORD wYear; WORD wMonth; WORD wDay; WORD wNum; } GG_VERSION, *PGG_VERSION; typedef struct _GG_AUTH_PROTOCOL *PGG_AUTH_PROTOCOL; // ggauth.dll์˜ Path GGAUTHS_API DWORD __CDECL InitGameguardAuth(char* sGGPath, DWORD dwNumActive, BOOL useTimer, int useLog); GGAUTHS_API void __CDECL CleanupGameguardAuth(); GGAUTHS_API DWORD __CDECL GGAuthUpdateTimer(); //useTimer ๊ฐ€ true ์ผ ๊ฒฝ์šฐ ํ˜ธ์ถœ. // protocol dll name GGAUTHS_API DWORD __CDECL AddAuthProtocol(char* sDllName); //Need for modify by gameserver engineer !!!!!!!!!!!!!!!! GGAUTHS_API void NpLog(int mode, char* msg); /* { if(mode & (NPLOG_DEBUG | NPLOG_ERROR)) //Select log mode. #ifdef WIN32 OutputDebugString(msg); #else printf(msg); #endif }; */ typedef struct _GG_UPREPORT { DWORD dwBefore; // Before version DWORD dwNext; // Now version int nType; // Update type 1 : gameguard version, 2 : protocol num } GG_UPREPORT, *PGG_UPREPORT; //Need for modify by gameserver engineer !!!!!!!!!!!!!!!! GGAUTHS_API void GGAuthUpdateCallback(PGG_UPREPORT report); /* { printf("GGAuth version update [%s] : [%ld] -> [%ld] \n", report->nType==1?"GameGuard Ver":"Protocol Num", report->dwBefore, report->dwNext); }; */ // protocol information GGAUTHS_API int ModuleInfo(char* dest, int length); // Class CSAuth2 class GGAUTHS_EXPORT CCSAuth2 { public: // Constructor CCSAuth2(); // Destructor ~CCSAuth2(); protected: PGG_AUTH_PROTOCOL m_pProtocol; DWORD m_bPrtcRef; DWORD m_dwUserFlag; GG_VERSION m_GGVer; //๊ฒŒ์ž„๊ฐ€๋“œ ๋ฒ„์ ผ GG_AUTH_DATA m_AuthQueryTmp; //m_AuthQuery ๊ฐ’์„ ๋ฐฑ์—…ํ•ด๋‘”๋‹ค. BOOL m_bNewProtocol; // ์ƒˆ๋กœ์šด ํ”„๋กœํ† ์ฝœ๋กœ ์ ‘์†ํ•˜๋ฉด true. ์ƒˆ๋กœ์šด ํ”„๋กœํ† ์ฝœ์ด ํ• ์„ฑํ™”๋˜๋ฉด false, ๋””ํดํŠธ false; BOOL m_bActive; //ํ˜„์žฌ ๊ฐ์ฒด๊ฐ€ ์‚ฌ์šฉ์ž์—๊ฒŒ ํ• ๋‹น๋˜์—ˆ๋Š”์ง€. Init ํ˜ธ์ถœํ›„ true, Close ํ˜ธ์ถœํ›„ false public: GG_AUTH_DATA m_AuthQuery; GG_AUTH_DATA m_AuthAnswer; void Init(); DWORD GetAuthQuery(); DWORD CheckAuthAnswer(); void Close(); int Info(char* dest, int length); // protocol information int CheckUpdated(); //ํ˜„์žฌ ์‚ฌ์šฉ์ž์˜ ์—…๋ฐ์ดํŠธ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•œ๋‹ค. }; // C type CSAuth2 typedef LPVOID LPGGAUTH; GGAUTHS_API LPGGAUTH __CDECL GGAuthCreateUser(); // CCSAuth2() GGAUTHS_API DWORD __CDECL GGAuthDeleteUser(LPGGAUTH pGGAuth); // ~CCSAuth2() GGAUTHS_API DWORD __CDECL GGAuthInitUser(LPGGAUTH pGGAuth); // Init() GGAUTHS_API DWORD __CDECL GGAuthCloseUser(LPGGAUTH pGGAuth); // Close() GGAUTHS_API DWORD __CDECL GGAuthGetQuery(LPGGAUTH pGGAuth, PGG_AUTH_DATA pAuthData); // GetAuthQuery() GGAUTHS_API DWORD __CDECL GGAuthCheckAnswer(LPGGAUTH pGGAuth, PGG_AUTH_DATA pAuthData); // CheckAuthAnswer() GGAUTHS_API int __CDECL GGAuthCheckUpdated(LPGGAUTH pGGAuth); // CheckAuthAnswer() GGAUTHS_API int __CDECL GGAuthUserInfo(LPGGAUTH pGGAuth, char* dest, int length); // CheckAuthAnswer() GGAUTHS_API DWORD __CDECL GGAuthGetUserValue(LPGGAUTH pGGAuth, int type); #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 154 ] ] ]