blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
sequencelengths
1
16
author_lines
sequencelengths
1
16
7a6036e96fd845ec37ca25c9aa9f71ddb1a0368c
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/persistence2/engine/core/src/GameAreaListener.cpp
aa1422e2d3feebea40a7ea9300216f714b44cccc
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,437
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 "GameAreaListener.h" #include "GameEventManager.h" #include "CoreSubsystem.h" #include "Exception.h" namespace rl { GameAreaListener::~GameAreaListener() { GameEventManager::getSingleton().removeAreaListener( this ); } bool GameAreaListener::eventRaised( GameAreaEvent* anEvent ) { switch( anEvent->getReason() ) { case GameAreaEvent::AREA_ENTERED: this->areaEntered( anEvent ); break; case GameAreaEvent::AREA_LEFT: this->areaLeft( anEvent ); break; } // consumed or not ;) return false; } }
[ "timm@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 50 ] ] ]
7e8ebf50b4cab70e0a58371c84215900f8d81968
37c757f24b674f67edd87b75b996d8d5015455cb
/Server/include/dataProcess.h
1f4dbe31a1e5d83d7d203ca5b3b02f72a0c9bbb1
[]
no_license
SakuraSinojun/cotalking
1118602313f85d1c49d73e1603cf6642bc15f36d
37354d99db6b7033019fd0aaccec84e68aee2adf
refs/heads/master
2021-01-10T21:20:50.269547
2011-04-07T06:15:04
2011-04-07T06:15:04
32,323,167
0
0
null
null
null
null
UTF-8
C++
false
false
877
h
/*************************************************** Project: grouptalk author: TaXueWuHen data Process; ***************************************************/ #ifndef __TALK_DATAPROCESS_H__ #define __TALK_DATAPROCESS_H__ #include <stdio.h> #include <map> #include "../include/def.h" #include "../include/defGroupTalk.h" #include "../include/publicOpt.h" #include "../include/dataManager.h" using namespace std; // data cache typedef struct st_scDataCache { int dataLength; char data[C_SCDATA_LENGTH * 2]; } scDataCache, *pscDataCache; class TS_dataProcess { private: int cachePoint; map<int, pscDataCache> m_dataCache; TS_dataManager *dataMng; public: TS_dataProcess(); ~TS_dataProcess(); public: void* getAddr(int key); bool dataAnalyse(int key, int size); void setDataManager(TS_dataManager *pdm); }; #endif
[ "SakuraSinojun@02eed91f-dd82-7cf9-bfd0-73567c4360d3" ]
[ [ [ 1, 41 ] ] ]
3c497426140ad1e4ebbbb1072d4cf9ba74b7fdc9
6188f1aaaf5508e046cde6da16b56feb3d5914bc
/branches/CamFighter 1.0/Source Files/MenuStates/EditModelState.h
0a5e2dff09eb1fc6b975fb1f5e4d42eb0e4c2539
[]
no_license
dogtwelve/fighter3d
7bb099f0dc396e8224c573743ee28c54cdd3d5a2
c073194989bc1589e4aa665714c5511f001e6400
refs/heads/master
2021-04-30T15:58:11.300681
2011-06-27T18:51:30
2011-06-27T18:51:30
33,675,635
1
0
null
null
null
null
UTF-8
C++
false
false
6,962
h
// included in MenuStates.h #include "../../Graphics/OGL/Button.h" #include "../SceneSkeleton.h" namespace Scenes { namespace Menu { class EditModelState : public BaseState { std::vector<Graphics::OGL::Button> Buttons; Filesystem::Vec_string Directories; Filesystem::Vec_string Files; std::string CurrentDirectory; std::string ModelGrFile; std::string ModelPhFile; HTexture backGround; virtual void Init(BaseState *parent) { BaseState::Init(parent); Name = "Model editor"; ModelGrFile.clear(); ModelPhFile.clear(); CurrentDirectory = Filesystem::GetFullPath("Data/models"); Buttons.clear(); GetFiles(); backGround = g_TextureMgr.GetTexture("Data/textures/menu/model_editor.tga"); } virtual void Clear() { BaseState::Clear(); g_TextureMgr.Release(backGround); backGround = HTexture(); } virtual void Enter() { ModelGrFile.clear(); ModelPhFile.clear(); } void GetFiles() { Directories = Filesystem::GetDirectories(CurrentDirectory); Files = Filesystem::GetFiles(CurrentDirectory, "*.3dx"); const Filesystem::Vec_string &f3ds = Filesystem::GetFiles(CurrentDirectory, "*.3ds"); Files.insert(Files.end(), f3ds.begin(), f3ds.end()); } virtual bool Update(xFLOAT T_time) { if (!BaseState::Update(T_time)) { if (g_InputMgr.InputDown_GetAndRaise(IC_LClick)) { xFLOAT mouseX = (xFLOAT)g_InputMgr.mouseX; xFLOAT mouseY = (xFLOAT)g_InputMgr.mouseY; for (size_t i = 0; i < Buttons.size(); ++i) { Graphics::OGL::Button &button = Buttons[i]; if (button.HitTest(mouseX, mouseY)) { if (button.Action == IC_BE_Move) { if (!strcmp(button.Text, "..")) CurrentDirectory = Filesystem::GetParentDir(CurrentDirectory); else { CurrentDirectory += "/"; CurrentDirectory += button.Text; } GetFiles(); } else if (button.Action == IC_BE_Select) { if (ModelGrFile.size()) { ModelPhFile = CurrentDirectory + "/" + button.Text; if (ModelPhFile != ModelGrFile) g_Application.Scene_Set(* new SceneSkeleton(ModelGrFile.c_str(), ModelPhFile.c_str()), false); else g_Application.Scene_Set(* new SceneSkeleton(ModelGrFile.c_str(), NULL), false); ModelGrFile.clear(); ModelPhFile.clear(); return true; } else ModelGrFile = CurrentDirectory + "/" + button.Text; } return true; } } } } return true; } virtual void Render(const Graphics::OGL::Font* pFont03, const Graphics::OGL::Font* pFont04, xDWORD Width, xDWORD Height) { if (!backGround.IsNull()) { glColor4f( 1.0f, 1.0f, 1.0f, 1.f ); glEnable (GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); xFLOAT scale = Height * 0.7f / 1024.f; xFLOAT iWidth = scale * g_TextureMgr.GetWidth(backGround); xFLOAT iHeight = scale * g_TextureMgr.GetHeight(backGround); xFLOAT left = Width - iWidth - 170.f*scale; xFLOAT top = Height - iHeight - 480.f*scale; g_TextureMgr.BindTexture(backGround); glBegin(GL_QUADS); { glTexCoord2f(0.01f,0.99f); glVertex2f(left, top); glTexCoord2f(0.99f,0.99f); glVertex2f(left+iWidth, top); glTexCoord2f(0.99f,0.01f); glVertex2f(left+iWidth, top+iHeight); glTexCoord2f(0.01f,0.01f); glVertex2f(left, top+iHeight); } glEnd(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); } xFLOAT lineHeight03 = pFont03->LineH(); xFLOAT top = lineHeight03-3, left = 5, width = Width*0.333f-10; Buttons.clear(); for (size_t i=0; i<Directories.size(); ++i) { top += lineHeight03+3; if (top > Height-lineHeight03) { top = lineHeight03*2.f; left += Width*0.333f; } Buttons.push_back(Graphics::OGL::Button(Directories[i].c_str(), left, top, width, lineHeight03*1.f, IC_BE_Move)); } for (size_t i=0; i<Files.size(); ++i) { top += lineHeight03+3; if (top > Height-lineHeight03) { top = lineHeight03*2.f; left += Width*0.333f; } Buttons.push_back(Graphics::OGL::Button(Files[i].c_str(), left, top, width, lineHeight03*1.f, IC_BE_Select)); Buttons.back().Background.init(0.35f,0.35f,0.35f,1.f); } int X = g_InputMgr.mouseX; int Y = g_InputMgr.mouseY; std::vector<Graphics::OGL::Button>::iterator begin = Buttons.begin(); std::vector<Graphics::OGL::Button>::iterator end = Buttons.end(); for (; begin != end; ++begin) { begin->Hover((xFLOAT)X, (xFLOAT)Y); begin->Down = ModelGrFile == CurrentDirectory + "/" + begin->Text; begin->Render(pFont03); } } }; } } // namespace Scenes::Menu
[ "dmaciej1@f75eed02-8a0f-11dd-b20b-83d96e936561" ]
[ [ [ 1, 175 ] ] ]
54d4af5b8e1032bdbfd9308dc662e92e056cc174
5e6ff9e6e8427078135a7b4d3b194bcbf631e9cd
/EngineSource/dpslim/dpslim/Database/Headers/MSDatabase.h
abe55790fac1b862a7fd587767617702d20aebf1
[]
no_license
karakots/dpresurrection
1a6f3fca00edd24455f1c8ae50764142bb4106e7
46725077006571cec1511f31d314ccd7f5a5eeef
refs/heads/master
2016-09-05T09:26:26.091623
2010-02-01T11:24:41
2010-02-01T11:24:41
32,189,181
0
0
null
null
null
null
UTF-8
C++
false
false
5,139
h
#pragma once #define _CRT_SECURE_NO_WARNINGS // Database accessing routines using MFC classes for ODBC // // Copyright 2003 by DecisionPower // // author: Vicki de Mey // creation data: 9/18/2003 // // #define __MSDATABASE__ #include <afxdb.h> // MFC ODBC database classes #include <stdafx.h> #include <string> #include "DBModel.h" #include "DBBrand.h" #include "DBChannel.h" #include "DBConsumerPrefs.h" #include "DBDistDisplay.h" #include "DBInitialConds.h" #include "DBMassMedia.h" #include "DBMarketUtility.h" #include "DBProdAttr.h" #include "DBProdAttrVal.h" #include "DBProdChan.h" #include "DBProduct.h" #include "DBProductTree.h" #include "DBSegChan.h" #include "DBSegment.h" #include "DBTask.h" #include "DBTaskProd.h" #include "DBTaskRates.h" #include "DBProdMatrix.h" #include "DBScenarioParams.h" #include "DBScenarioOutputSummary.h" #include "DBOptimizationPlan.h" #include "DBProductEvent.h" #include "DBTaskEvent.h" #include "DBSimQueue.h" #include "DBSimulation.h" #include "DBSocNetwork.h" #include "DBNetworkParams.h" #include "DBSimLog.h" #include "DBProdSize.h" // forward declare class ParameterRecordset; class ProductTreeRecordset; //#include "custrecord.h" //#include "employeerecord.h" // VdM 12/6/04 // wrapper for out results tables #ifndef __OUTPUTRESULTS__ #include "OutputResults.h" #endif using namespace std; enum { kText = 1, kNumber, kFloat }; class MSDatabase { public: // default preferences CDatabase iTheCurrentDB; CDatabase writeDataDB; // read only ModelRecordset* m_ModelInfo; ChannelRecordset* m_Channel; ConsumerPrefsRecordset* m_ConsumerPrefs; DistDisplayRecordset* m_DistDisplay; InitialCondsRecordset* m_InitalConds; MassMediaRecordset* m_MassMedia; MarketUtilityRecordset* m_MarketUtility; ProdAttrRecordset* m_ProdAttr; ProdAttrValRecordset* m_ProdAttrVal; ProdChanRecordset* m_ProdChan; ProductRecordset* m_Product; SegChanRecordset* m_SegChan; SegmentRecordset* m_Segment; ProductEventRecordset* m_ProductEvent; TaskEventRecordset* m_TaskEvent; TaskRecordset* m_Task; TaskProdRecordset* m_TaskProd; TaskRatesRecordset* m_TaskRates; ProductMatrixRecordset* m_ProdMatrix; ProductTreeRecordset* m_ProductTree; ProductSizeRecordset* m_product_size; // VdM 10/25/04 OptimizationParamsRecordset* m_OptimizationParams; OptimizationPlanRecordset* m_OptimizationPlan; // VdM 11/3/04 OptimizationOutSumRecordset* m_OptimizationOutputSummary; // VdM 12/6/04 OutputResults* theOutputResults; // SSN 1/11/2005 SimQueueRecordset* m_SimQueue; // SSN 4/15/2005 SimulationRecordset* m_Simulation; // SSN 4/26/2005 SocNetworkRecordset* m_SocNetwork; // SSN 4/26/2005 NetworkParamsRecordset* m_NetworkParams; SimLogRecordset* m_SimLog; string comma; string slash; string iConnectString; string iResultsTableName; string iOptResultsTableName; long iModelID; long iRunID; long iScenarioID; long iStartTime; int warningsLogged; int dayLastWrite; void ApplyParameters(); void RestoreValues(); void PreloadAllRecordsets(void); void FreeAllRecordsets(void); public: // methods // create & destroy MSDatabase(void); ~MSDatabase(void); int Open(const char* fname, int run_id); void InitOutput(void); void GetConnectInfo(string* str) { iConnectString = *str; } // read int SelectModel(int run_id); int Get(int paramID, int inTherecordNum); void Get(int paramID, int inTheRecordNum, string* outString); void GetBrandName(int brandID, string* brandName); void GetProductName(int productID, string* productName); void GetChannelName(int channelID, string* channelName); void GetSegmentName(int segmentID, string* segmentName); void GetTaskName(int taskID, string* taskName); void GetProdAttrName(int prodAttrID, string* prodAttrName, double& tau); // write // void SetResults(string* inString, int optResults, int trialNum, int runNum); void AddToString(string* outputString, CString str, int doComma); void AddToString(string* outputString, int val, int doComma); void AddToString(string* outputString, float val, int doComma); void AddToString(string* outputString, CTime val, int doComma); // VdM 10/25/04 // Scenarios /* void SelectOptimizationParams(int modelID, int scenarioID); void SelectOptimizationPlan(int modelID); void SelectOptimizationOutputSummary(int modelID, int scenarioID); */ //void SetOptimizationOutputSummary(string* inString); int GetOptimizationParam(int paramNum); int SimStart(); int SimDone(); void SimStatus(const string message); void SimStatus(CTime date, const string message); SegmentData* NewSegData(); void WriteSegData(); SimLogRecordset* NewLogEntry(); short SimSeed(); };
[ "Isaac.Noble@fd82578e-0ebe-11df-96d9-85c6b80b8d9c" ]
[ [ [ 1, 211 ] ] ]
f4a14f73e014616805ba2c97f5b717de25d44bcc
037faae47a5b22d3e283555e6b5ac2a0197faf18
/plugins/gs/zerogs/dx/Regs.cpp
30928d1fed2ceb67219b5e31b012386bfe9e7720
[]
no_license
isabella232/pcsx2-sourceforge
6e5aac8d0b476601bfc8fa83ded66c1564b8c588
dbb2c3a010081b105a8cba0c588f1e8f4e4505c6
refs/heads/master
2023-03-18T22:23:15.102593
2008-11-17T20:10:17
2008-11-17T20:10:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,409
cpp
/* ZeroGS * Copyright (C) 2005-2006 [email protected] * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if defined(_WIN32) || defined(__WIN32__) #include <d3dx9.h> #include <dxerr9.h> #endif #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "GS.h" #include "Mem.h" #include "Regs.h" #include "zerogs.h" #include "targets.h" #ifdef __MSCW32__ #pragma warning(disable:4244) #endif GIFRegHandler g_GIFPackedRegHandlers[16] = { GIFRegHandlerPRIM, GIFPackedRegHandlerRGBA, GIFPackedRegHandlerSTQ, GIFPackedRegHandlerUV, GIFPackedRegHandlerXYZF2, GIFPackedRegHandlerXYZ2, GIFRegHandlerTEX0_1, GIFRegHandlerTEX0_2, GIFRegHandlerCLAMP_1, GIFRegHandlerCLAMP_2, GIFPackedRegHandlerFOG, GIFPackedRegHandlerNull, GIFRegHandlerXYZF3, GIFRegHandlerXYZ3, GIFPackedRegHandlerA_D, GIFPackedRegHandlerNOP }; GIFRegHandler g_GIFRegHandlers[] = { GIFRegHandlerPRIM, GIFRegHandlerRGBAQ, GIFRegHandlerST, GIFRegHandlerUV, GIFRegHandlerXYZF2, GIFRegHandlerXYZ2, GIFRegHandlerTEX0_1, GIFRegHandlerTEX0_2, GIFRegHandlerCLAMP_1, GIFRegHandlerCLAMP_2, GIFRegHandlerFOG, GIFRegHandlerNull, GIFRegHandlerXYZF3, GIFRegHandlerXYZ3, GIFRegHandlerNOP, GIFRegHandlerNOP, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerTEX1_1, GIFRegHandlerTEX1_2, GIFRegHandlerTEX2_1, GIFRegHandlerTEX2_2, GIFRegHandlerXYOFFSET_1,GIFRegHandlerXYOFFSET_2,GIFRegHandlerPRMODECONT,GIFRegHandlerPRMODE, GIFRegHandlerTEXCLUT, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerSCANMSK, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerMIPTBP1_1, GIFRegHandlerMIPTBP1_2, GIFRegHandlerMIPTBP2_1, GIFRegHandlerMIPTBP2_2, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerTEXA, GIFRegHandlerNull, GIFRegHandlerFOGCOL, GIFRegHandlerNull, GIFRegHandlerTEXFLUSH, GIFRegHandlerSCISSOR_1, GIFRegHandlerSCISSOR_2, GIFRegHandlerALPHA_1, GIFRegHandlerALPHA_2, GIFRegHandlerDIMX, GIFRegHandlerDTHE, GIFRegHandlerCOLCLAMP, GIFRegHandlerTEST_1, GIFRegHandlerTEST_2, GIFRegHandlerPABE, GIFRegHandlerFBA_1, GIFRegHandlerFBA_2, GIFRegHandlerFRAME_1, GIFRegHandlerFRAME_2, GIFRegHandlerZBUF_1, GIFRegHandlerZBUF_2, GIFRegHandlerBITBLTBUF, GIFRegHandlerTRXPOS, GIFRegHandlerTRXREG, GIFRegHandlerTRXDIR, GIFRegHandlerHWREG, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerNull, GIFRegHandlerSIGNAL, GIFRegHandlerFINISH, GIFRegHandlerLABEL, GIFRegHandlerNull }; C_ASSERT(sizeof(g_GIFRegHandlers)/sizeof(g_GIFRegHandlers[0]) == 100 ); // values for keeping track of changes u32 s_uTex1Data[2][2] = {0}, s_uClampData[2] = {0}; void __fastcall GIFPackedRegHandlerNull(u32* data) { #ifdef _DEBUG printf("Unexpected packed reg handler %8.8lx_%8.8lx %x\n", data[0], data[1], data[2]); #endif } void __fastcall GIFPackedRegHandlerRGBA(u32* data) { gs.rgba = (data[0] & 0xff) | ((data[1] & 0xff) << 8) | ((data[2] & 0xff) << 16) | ((data[3] & 0xff) << 24); gs.vertexregs.rgba = gs.rgba; gs.vertexregs.q = gs.q; } void __fastcall GIFPackedRegHandlerSTQ(u32* data) { *(u32*)&gs.vertexregs.s = data[0]&0xffffff00; *(u32*)&gs.vertexregs.t = data[1]&0xffffff00; *(u32*)&gs.q = data[2]; } void __fastcall GIFPackedRegHandlerUV(u32* data) { gs.vertexregs.u = data[0] & 0x3fff; gs.vertexregs.v = data[1] & 0x3fff; } #define KICK_VERTEX2() { \ if( ++gs.primC >= (int)g_primmult[prim->prim]) { \ if( !(g_GameSettings&GAME_XENOSPECHACK) || !ZeroGS::vb[prim->ctxt].zbuf.zmsk ) \ (*ZeroGS::drawfn[prim->prim])(); \ gs.primC -= g_primsub[prim->prim]; \ } \ } \ #define KICK_VERTEX3() { \ if( ++gs.primC >= (int)g_primmult[prim->prim] ) { \ gs.primC -= g_primsub[prim->prim]; \ if( prim->prim == 5 ) { \ /* tri fans need special processing */ \ if( gs.nTriFanVert == gs.primIndex ) \ gs.primIndex = (gs.primIndex+1)%ARRAYSIZE(gs.gsvertex); \ } \ } \ } \ void __fastcall GIFPackedRegHandlerXYZF2(u32* data) { gs.vertexregs.x = (data[0] >> 0) & 0xffff; gs.vertexregs.y = (data[1] >> 0) & 0xffff; gs.vertexregs.z = (data[2] >> 4) & 0xffffff; gs.vertexregs.f = (data[3] >> 4) & 0xff; gs.gsvertex[gs.primIndex] = gs.vertexregs; gs.primIndex = (gs.primIndex+1)%ARRAYSIZE(gs.gsvertex); if( data[3] & 0x8000 ) { KICK_VERTEX3(); } else { KICK_VERTEX2(); } } void __fastcall GIFPackedRegHandlerXYZ2(u32* data) { gs.vertexregs.x = (data[0] >> 0) & 0xffff; gs.vertexregs.y = (data[1] >> 0) & 0xffff; gs.vertexregs.z = data[2]; gs.gsvertex[gs.primIndex] = gs.vertexregs; gs.primIndex = (gs.primIndex+1)%ARRAYSIZE(gs.gsvertex); if( data[3] & 0x8000 ) { KICK_VERTEX3(); } else { KICK_VERTEX2(); } } void __fastcall GIFPackedRegHandlerFOG(u32* data) { gs.vertexregs.f = (data[3]&0xff0)>>4; } void __fastcall GIFPackedRegHandlerA_D(u32* data) { if((data[2] & 0xff) < 100) g_GIFRegHandlers[data[2] & 0xff](data); else GIFRegHandlerNull(data); } void __fastcall GIFPackedRegHandlerNOP(u32* data) { } extern int g_PrevBitwiseTexX, g_PrevBitwiseTexY; void tex0Write(int i, u32 *data) { u32 psm = (data[0] >> 20) & 0x3f; if( psm == 9 ) psm = 1; // hmm..., ffx intro menu if( m_Blocks[psm].bpp == 0 ) { // kh and others return; } ZeroGS::vb[i].uNextTex0Data[0] = data[0]; ZeroGS::vb[i].uNextTex0Data[1] = data[1]; ZeroGS::vb[i].bNeedTexCheck = 1; // don't update unless necessary if( PSMT_ISCLUT(psm) ) { if( ZeroGS::CheckChangeInClut(data[1], psm) ) { // loading clut, so flush whole texture ZeroGS::vb[i].FlushTexData(); } // check if csa is the same!! (ffx bisaid island, grass) else if( (data[1]&0x1f780000) != (ZeroGS::vb[i].uCurTex0Data[1]&0x1f780000) ) { ZeroGS::Flush(i); // flush any previous entries } } } void tex2Write(int i, u32 *data) { tex0Info& tex0 = ZeroGS::vb[i].tex0; if( ZeroGS::vb[i].bNeedTexCheck ) ZeroGS::vb[i].FlushTexData(); u32 psm = (data[0] >> 20) & 0x3f; if( psm == 9 ) psm = 1; // hmm..., ffx intro menu u32* s_uTex0Data = ZeroGS::vb[i].uCurTex0Data; // don't update unless necessary if( (s_uTex0Data[0]&0x03f00000) == (data[0]&0x03f00000) ) { // psm is the same if( PSMT_ISCLUT(psm) ) { // have to write the CLUT again if changed if( (s_uTex0Data[1]&0x1fffffe0) == (data[1]&0x1fffffe0) ) { if( data[1]&0xe0000000 ) { tex0.cld = (data[1]>>29)&7; ZeroGS::texClutWrite(i); // invalidate to make sure target didn't change! ZeroGS::vb[i].bVarsTexSync = FALSE; } return; } // CSAs have to be the same! // if( (data[1]&0xe0000000) == 0 ) { // // if( (s_uTex0Data[1]&0x1f100000) != (data[1]&0x1f100000) ) // ZeroGS::Flush(i); // // // clut isn't going to be loaded so can ignore, but at least update CSA and CPSM! // ZeroGS::vb[i].uCurTex0Data[1] = (ZeroGS::vb[i].uCurTex0Data[1]&0xe087ffff)|(data[1]&0x1f780000); // // if( ZeroGS::vb[i].tex0.cpsm <= 1 ) ZeroGS::vb[i].tex0.csa = (data[1] >> 24) & 0xf; // else ZeroGS::vb[i].tex0.csa = (data[1] >> 24) & 0x1f; // // ZeroGS::vb[i].tex0.cpsm = (data[1] >> 19) & 0xe; // // ZeroGS::vb[i].bVarsTexSync = FALSE; // return; // } // fall through } else { //ZeroGS::vb[i].bVarsTexSync = FALSE; return; } } ZeroGS::Flush(i); ZeroGS::vb[i].bVarsTexSync = FALSE; ZeroGS::vb[i].bTexConstsSync = FALSE; s_uTex0Data[0] = (s_uTex0Data[0]&~0x03f00000)|(psm<<20); s_uTex0Data[1] = (s_uTex0Data[1]&0x1f)|(data[1]&~0x1f); tex0.psm = psm; if( PSMT_ISCLUT(tex0.psm) ) { tex0.cbp = (data[1] >> 5) & 0x3fff; tex0.cpsm = (data[1] >> 19) & 0xe; tex0.csm = (data[1] >> 23) & 0x1; if( tex0.cpsm <= 1 ) tex0.csa = (data[1] >> 24) & 0xf; else tex0.csa = (data[1] >> 24) & 0x1f; tex0.cld = (data[1] >> 29) & 0x7; ZeroGS::texClutWrite(i); } } __forceinline void frameWrite(int i, u32 *data) { frameInfo& gsfb = ZeroGS::vb[i].gsfb; if( (gsfb.fbp == ((data[0] ) & 0x1ff) * 32) && (gsfb.fbw == ((data[0] >> 16) & 0x3f) * 64) && gsfb.psm == ((data[0] >> 24) & 0x3f) && (gsfb.fbm == data[1]) ) { return; } ZeroGS::Flush(0); ZeroGS::Flush(1); gsfb.fbp = ((data[0] ) & 0x1ff) * 32; gsfb.fbw = ((data[0] >> 16) & 0x3f) * 64; gsfb.psm = (data[0] >> 24) & 0x3f; gsfb.fbm = data[1]; if (gsfb.fbw > 0) { gsfb.fbh = (1024*1024-64*gsfb.fbp) / gsfb.fbw; gsfb.fbh &= ~0x1f; if( gsfb.psm & 2 ) gsfb.fbh *= 2; if( gsfb.fbh > 1024 ) gsfb.fbh = 1024; } else gsfb.fbh = 0; if( gsfb.psm == 1 ) gsfb.fbm |= 0xff000000; else if( gsfb.psm & 2 ) { } ZeroGS::vb[i].bNeedFrameCheck = 1; } __forceinline void testWrite(int i, u32 *data) { pixTest* test = &ZeroGS::vb[i].test; if( (*(u32*)test & 0x0007ffff) == (data[0] & 0x0007ffff) ) return; ZeroGS::Flush(i); *(u32*)test = data[0]; // test.ate = (data[0] ) & 0x1; // test.atst = (data[0] >> 1) & 0x7; // test.aref = (data[0] >> 4) & 0xff; // test.afail = (data[0] >> 12) & 0x3; // test.date = (data[0] >> 14) & 0x1; // test.datm = (data[0] >> 15) & 0x1; // test.zte = (data[0] >> 16) & 0x1; // test.ztst = (data[0] >> 17) & 0x3; } __forceinline void clampWrite(int i, u32 *data) { clampInfo& clamp = ZeroGS::vb[i].clamp; if( s_uClampData[i] != data[0] || ((clamp.minv>>8)|(clamp.maxv<<2)) != (data[1]&0x0fff) ) { // if( ZeroGS::vb[i].bNeedTexCheck ) // ZeroGS::vb[i].FlushTexData(); ZeroGS::Flush(i); s_uClampData[i] = data[0]; clamp.wms = (data[0] ) & 0x3; clamp.wmt = (data[0] >> 2) & 0x3; clamp.minu = (data[0] >> 4) & 0x3ff; clamp.maxu = (data[0] >> 14) & 0x3ff; clamp.minv =((data[0] >> 24) & 0xff) | ((data[1] & 0x3) << 8); clamp.maxv = (data[1] >> 2) & 0x3ff; ZeroGS::vb[i].bTexConstsSync = FALSE; } } void __fastcall GIFRegHandlerNull(u32* data) { #ifdef _DEBUG if( (((uptr)&data[2])&0xffff) == 0 ) return; // 0x7f happens on a lot of games if( data[2] != 0x7f && (data[0] || data[1]) ) { printf("Unexpected reg handler %x %x %x\n", data[0], data[1], data[2]); } #endif } void __fastcall GIFRegHandlerPRIM(u32 *data) { if (data[0] & ~0x3ff) { #ifdef WARN_LOG //WARN_LOG("warning: unknown bits in prim %8.8lx_%8.8lx\n", data[1], data[0]); #endif } gs.nTriFanVert = gs.primIndex; gs.primC = 0; prim->prim = (data[0]) & 0x7; gs._prim[0].prim = (data[0]) & 0x7; gs._prim[1].prim = (data[0]) & 0x7; gs._prim[1]._val = (data[0]>>3)&0xff; ZeroGS::Prim(); } void __fastcall GIFRegHandlerRGBAQ(u32* data) { gs.rgba = data[0]; gs.vertexregs.rgba = data[0]; *(u32*)&gs.vertexregs.q = data[1]; } void __fastcall GIFRegHandlerST(u32* data) { *(u32*)&gs.vertexregs.s = data[0]&0xffffff00; *(u32*)&gs.vertexregs.t = data[1]&0xffffff00; //*(u32*)&gs.q = data[2]; } void __fastcall GIFRegHandlerUV(u32* data) { gs.vertexregs.u = (data[0]) & 0x3fff; gs.vertexregs.v = (data[0] >> 16) & 0x3fff; } void __fastcall GIFRegHandlerXYZF2(u32* data) { gs.vertexregs.x = (data[0]) & 0xffff; gs.vertexregs.y = (data[0] >> (16)) & 0xffff; gs.vertexregs.z = data[1] & 0xffffff; gs.vertexregs.f = data[1] >> 24; gs.gsvertex[gs.primIndex] = gs.vertexregs; gs.primIndex = (gs.primIndex+1)%ARRAYSIZE(gs.gsvertex); KICK_VERTEX2(); } void __fastcall GIFRegHandlerXYZ2(u32* data) { gs.vertexregs.x = (data[0]) & 0xffff; gs.vertexregs.y = (data[0] >> (16)) & 0xffff; gs.vertexregs.z = data[1]; gs.gsvertex[gs.primIndex] = gs.vertexregs; gs.primIndex = (gs.primIndex+1)%ARRAYSIZE(gs.gsvertex); KICK_VERTEX2(); } void __fastcall GIFRegHandlerTEX0_1(u32* data) { if( (g_GameSettings&GAME_XENOSPECHACK) && ZeroGS::vb[0].zbuf.zmsk ) { return; } tex0Write(0, data); } void __fastcall GIFRegHandlerTEX0_2(u32* data) { if( (g_GameSettings&GAME_XENOSPECHACK) && ZeroGS::vb[1].zbuf.zmsk ) { return; } tex0Write(1, data); } void __fastcall GIFRegHandlerCLAMP_1(u32* data) { if( (g_GameSettings&GAME_XENOSPECHACK) && ZeroGS::vb[0].zbuf.zmsk ) { return; } clampWrite(0, data); } void __fastcall GIFRegHandlerCLAMP_2(u32* data) { if( (g_GameSettings&GAME_XENOSPECHACK) && ZeroGS::vb[1].zbuf.zmsk ) { return; } clampWrite(1, data); } void __fastcall GIFRegHandlerFOG(u32* data) { //gs.gsvertex[gs.primIndex].f = (data[1] >> 24); // shift to upper bits gs.vertexregs.f = data[1]>>24; } void __fastcall GIFRegHandlerXYZF3(u32* data) { gs.vertexregs.x = (data[0]) & 0xffff; gs.vertexregs.y = (data[0] >> (16)) & 0xffff; gs.vertexregs.z = data[1] & 0xffffff; gs.vertexregs.f = data[1] >> 24; gs.gsvertex[gs.primIndex] = gs.vertexregs; gs.primIndex = (gs.primIndex+1)%ARRAYSIZE(gs.gsvertex); KICK_VERTEX3(); } void __fastcall GIFRegHandlerXYZ3(u32* data) { gs.vertexregs.x = (data[0]) & 0xffff; gs.vertexregs.y = (data[0] >> (16)) & 0xffff; gs.vertexregs.z = data[1]; gs.gsvertex[gs.primIndex] = gs.vertexregs; gs.primIndex = (gs.primIndex+1)%ARRAYSIZE(gs.gsvertex); KICK_VERTEX3(); } void __fastcall GIFRegHandlerNOP(u32* data) { } void tex1Write(int i, u32* data) { tex1Info& tex1 = ZeroGS::vb[i].tex1; if( conf.bilinear == 1 && (tex1.mmag != ((data[0] >> 5) & 0x1) || tex1.mmin != ((data[0] >> 6) & 0x7)) ) { ZeroGS::Flush(i); ZeroGS::vb[i].bVarsTexSync = FALSE; } tex1.lcm = (data[0] ) & 0x1; tex1.mxl = (data[0] >> 2) & 0x7; tex1.mmag = (data[0] >> 5) & 0x1; tex1.mmin = (data[0] >> 6) & 0x7; tex1.mtba = (data[0] >> 9) & 0x1; tex1.l = (data[0] >> 19) & 0x3; tex1.k = (data[1] >> 4) & 0xff; } void __fastcall GIFRegHandlerTEX1_1(u32* data) { if( (g_GameSettings&GAME_XENOSPECHACK) && ZeroGS::vb[0].zbuf.zmsk ) { return; } tex1Write(0, data); } void __fastcall GIFRegHandlerTEX1_2(u32* data) { if( (g_GameSettings&GAME_XENOSPECHACK) && ZeroGS::vb[1].zbuf.zmsk ) return; tex1Write(1, data); } void __fastcall GIFRegHandlerTEX2_1(u32* data) { tex2Write(0, data); } void __fastcall GIFRegHandlerTEX2_2(u32* data) { tex2Write(1, data); } void __fastcall GIFRegHandlerXYOFFSET_1(u32* data) { // eliminator low 4 bits for now ZeroGS::vb[0].offset.x = (data[0]) & 0xffff; ZeroGS::vb[0].offset.y = (data[1]) & 0xffff; // if( !conf.interlace ) { // ZeroGS::vb[0].offset.x &= ~15; // ZeroGS::vb[0].offset.y &= ~15; // } } void __fastcall GIFRegHandlerXYOFFSET_2(u32* data) { ZeroGS::vb[1].offset.x = (data[0]) & 0xffff; ZeroGS::vb[1].offset.y = (data[1]) & 0xffff; // if( !conf.interlace ) { // ZeroGS::vb[1].offset.x &= ~15; // ZeroGS::vb[1].offset.y &= ~15; // } } void __fastcall GIFRegHandlerPRMODECONT(u32* data) { gs.prac = data[0] & 0x1; prim = &gs._prim[gs.prac]; ZeroGS::Prim(); } void __fastcall GIFRegHandlerPRMODE(u32* data) { gs._prim[0]._val = (data[0]>>3)&0xff; if (gs.prac == 0) ZeroGS::Prim(); } void __fastcall GIFRegHandlerTEXCLUT(u32* data) { if( ZeroGS::vb[0].bNeedTexCheck ) ZeroGS::vb[0].FlushTexData(); if( ZeroGS::vb[1].bNeedTexCheck ) ZeroGS::vb[1].FlushTexData(); gs.clut.cbw = ((data[0] ) & 0x3f) * 64; gs.clut.cou = ((data[0] >> 6) & 0x3f) * 16; gs.clut.cov = (data[0] >> 12) & 0x3ff; } void __fastcall GIFRegHandlerSCANMSK(u32* data) { // ZeroGS::Flush(0); // ZeroGS::Flush(1); // ZeroGS::ResolveC(&ZeroGS::vb[0]); // ZeroGS::ResolveZ(&ZeroGS::vb[0]); gs.smask = data[0] & 0x3; } void __fastcall GIFRegHandlerMIPTBP1_1(u32* data) { miptbpInfo& miptbp0 = ZeroGS::vb[0].miptbp0; miptbp0.tbp[0] = (data[0] ) & 0x3fff; miptbp0.tbw[0] = (data[0] >> 14) & 0x3f; miptbp0.tbp[1] = ((data[0] >> 20) & 0xfff) | ((data[1] & 0x3) << 12); miptbp0.tbw[1] = (data[1] >> 2) & 0x3f; miptbp0.tbp[2] = (data[1] >> 8) & 0x3fff; miptbp0.tbw[2] = (data[1] >> 22) & 0x3f; } void __fastcall GIFRegHandlerMIPTBP1_2(u32* data) { miptbpInfo& miptbp0 = ZeroGS::vb[1].miptbp0; miptbp0.tbp[0] = (data[0] ) & 0x3fff; miptbp0.tbw[0] = (data[0] >> 14) & 0x3f; miptbp0.tbp[1] = ((data[0] >> 20) & 0xfff) | ((data[1] & 0x3) << 12); miptbp0.tbw[1] = (data[1] >> 2) & 0x3f; miptbp0.tbp[2] = (data[1] >> 8) & 0x3fff; miptbp0.tbw[2] = (data[1] >> 22) & 0x3f; } void __fastcall GIFRegHandlerMIPTBP2_1(u32* data) { miptbpInfo& miptbp1 = ZeroGS::vb[0].miptbp1; miptbp1.tbp[0] = (data[0] ) & 0x3fff; miptbp1.tbw[0] = (data[0] >> 14) & 0x3f; miptbp1.tbp[1] = ((data[0] >> 20) & 0xfff) | ((data[1] & 0x3) << 12); miptbp1.tbw[1] = (data[1] >> 2) & 0x3f; miptbp1.tbp[2] = (data[1] >> 8) & 0x3fff; miptbp1.tbw[2] = (data[1] >> 22) & 0x3f; } void __fastcall GIFRegHandlerMIPTBP2_2(u32* data) { miptbpInfo& miptbp1 = ZeroGS::vb[1].miptbp1; miptbp1.tbp[0] = (data[0] ) & 0x3fff; miptbp1.tbw[0] = (data[0] >> 14) & 0x3f; miptbp1.tbp[1] = ((data[0] >> 20) & 0xfff) | ((data[1] & 0x3) << 12); miptbp1.tbw[1] = (data[1] >> 2) & 0x3f; miptbp1.tbp[2] = (data[1] >> 8) & 0x3fff; miptbp1.tbw[2] = (data[1] >> 22) & 0x3f; } void __fastcall GIFRegHandlerTEXA(u32* data) { texaInfo newinfo; newinfo.aem = (data[0] >> 15) & 0x1; newinfo.ta[0] = data[0] & 0xff; newinfo.ta[1] = data[1] & 0xff; if( *(u32*)&newinfo != *(u32*)&gs.texa ) { ZeroGS::Flush(0); ZeroGS::Flush(1); *(u32*)&gs.texa = *(u32*)&newinfo; gs.texa.fta[0] = newinfo.ta[0]/255.0f; gs.texa.fta[1] = newinfo.ta[1]/255.0f; ZeroGS::vb[0].bTexConstsSync = FALSE; ZeroGS::vb[1].bTexConstsSync = FALSE; } } void __fastcall GIFRegHandlerFOGCOL(u32* data) { ZeroGS::SetFogColor(data[0]&0xffffff); } void __fastcall GIFRegHandlerTEXFLUSH(u32* data) { ZeroGS::SetTexFlush(); } void __fastcall GIFRegHandlerSCISSOR_1(u32* data) { Rect2& scissor = ZeroGS::vb[0].scissor; Rect2 newscissor; newscissor.x0 = ((data[0] ) & 0x7ff) << 3; newscissor.x1 = ((data[0] >> 16) & 0x7ff) << 3; newscissor.y0 = ((data[1] ) & 0x7ff) << 3; newscissor.y1 = ((data[1] >> 16) & 0x7ff) << 3; if( newscissor.x1 != scissor.x1 || newscissor.y1 != scissor.y1 || newscissor.x0 != scissor.x0 || newscissor.y0 != scissor.y0 ) { ZeroGS::Flush(0); scissor = newscissor; ZeroGS::vb[0].bNeedFrameCheck = 1; } } void __fastcall GIFRegHandlerSCISSOR_2(u32* data) { Rect2& scissor = ZeroGS::vb[1].scissor; Rect2 newscissor; newscissor.x0 = ((data[0] ) & 0x7ff) << 3; newscissor.x1 = ((data[0] >> 16) & 0x7ff) << 3; newscissor.y0 = ((data[1] ) & 0x7ff) << 3; newscissor.y1 = ((data[1] >> 16) & 0x7ff) << 3; if( newscissor.x1 != scissor.x1 || newscissor.y1 != scissor.y1 || newscissor.x0 != scissor.x0 || newscissor.y0 != scissor.y0 ) { ZeroGS::Flush(1); scissor = newscissor; // flush everything ZeroGS::vb[1].bNeedFrameCheck = 1; } } void __fastcall GIFRegHandlerALPHA_1(u32* data) { alphaInfo newalpha; newalpha.abcd = *(u8*)data; newalpha.fix = *(u8*)(data+1); if( *(WORD*)&newalpha != *(WORD*)&ZeroGS::vb[0].alpha ) { ZeroGS::Flush(0); if( newalpha.a == 3 ) newalpha.a = 0; if( newalpha.b == 3 ) newalpha.b = 0; if( newalpha.c == 3 ) newalpha.c = 0; if( newalpha.d == 3 ) newalpha.d = 0; *(WORD*)&ZeroGS::vb[0].alpha = *(WORD*)&newalpha; } } void __fastcall GIFRegHandlerALPHA_2(u32* data) { alphaInfo newalpha; newalpha.abcd = *(u8*)data; newalpha.fix = *(u8*)(data+1); if( *(WORD*)&newalpha != *(WORD*)&ZeroGS::vb[1].alpha ) { ZeroGS::Flush(1); if( newalpha.a == 3 ) newalpha.a = 0; if( newalpha.b == 3 ) newalpha.b = 0; if( newalpha.c == 3 ) newalpha.c = 0; if( newalpha.d == 3 ) newalpha.d = 0; *(WORD*)&ZeroGS::vb[1].alpha = *(WORD*)&newalpha; } } void __fastcall GIFRegHandlerDIMX(u32* data) { } void __fastcall GIFRegHandlerDTHE(u32* data) { gs.dthe = data[0] & 0x1; } void __fastcall GIFRegHandlerCOLCLAMP(u32* data) { gs.colclamp = data[0] & 0x1; } void __fastcall GIFRegHandlerTEST_1(u32* data) { testWrite(0, data); } void __fastcall GIFRegHandlerTEST_2(u32* data) { testWrite(1, data); } void __fastcall GIFRegHandlerPABE(u32* data) { //ZeroGS::SetAlphaChanged(0, GPUREG_PABE); //ZeroGS::SetAlphaChanged(1, GPUREG_PABE); ZeroGS::Flush(0); ZeroGS::Flush(1); gs.pabe = *data & 0x1; } void __fastcall GIFRegHandlerFBA_1(u32* data) { ZeroGS::Flush(0); ZeroGS::Flush(1); ZeroGS::vb[0].fba.fba = *data & 0x1; } void __fastcall GIFRegHandlerFBA_2(u32* data) { ZeroGS::Flush(0); ZeroGS::Flush(1); ZeroGS::vb[1].fba.fba = *data & 0x1; } void __fastcall GIFRegHandlerFRAME_1(u32* data) { frameWrite(0, data); } void __fastcall GIFRegHandlerFRAME_2(u32* data) { frameWrite(1, data); } void __fastcall GIFRegHandlerZBUF_1(u32* data) { zbufInfo& zbuf = ZeroGS::vb[0].zbuf; int psm = (0x30|((data[0] >> 24) & 0xf)); if( zbuf.zbp == (data[0] & 0x1ff) * 32 && zbuf.psm == psm && zbuf.zmsk == (data[1] & 0x1) ) { return; } // error detection if( m_Blocks[psm].bpp == 0 ) return; ZeroGS::Flush(0); ZeroGS::Flush(1); zbuf.zbp = (data[0] & 0x1ff) * 32; zbuf.psm = 0x30|((data[0] >> 24) & 0xf); zbuf.zmsk = data[1] & 0x1; ZeroGS::vb[0].zprimmask = 0xffffffff; if( zbuf.psm > 0x31 ) ZeroGS::vb[0].zprimmask = 0xffff; ZeroGS::vb[0].bNeedZCheck = 1; } void __fastcall GIFRegHandlerZBUF_2(u32* data) { zbufInfo& zbuf = ZeroGS::vb[1].zbuf; int psm = (0x30|((data[0] >> 24) & 0xf)); if( zbuf.zbp == (data[0] & 0x1ff) * 32 && zbuf.psm == psm && zbuf.zmsk == (data[1] & 0x1) ) { return; } // error detection if( m_Blocks[psm].bpp == 0 ) return; ZeroGS::Flush(0); ZeroGS::Flush(1); zbuf.zbp = (data[0] & 0x1ff) * 32; zbuf.psm = 0x30|((data[0] >> 24) & 0xf); zbuf.zmsk = data[1] & 0x1; ZeroGS::vb[1].bNeedZCheck = 1; ZeroGS::vb[1].zprimmask = 0xffffffff; if( zbuf.psm > 0x31 ) ZeroGS::vb[1].zprimmask = 0xffff; } void __fastcall GIFRegHandlerBITBLTBUF(u32* data) { gs.srcbufnew.bp = ((data[0] ) & 0x3fff);// * 64; gs.srcbufnew.bw = ((data[0] >> 16) & 0x3f) * 64; gs.srcbufnew.psm = (data[0] >> 24) & 0x3f; gs.dstbufnew.bp = ((data[1] ) & 0x3fff);// * 64; gs.dstbufnew.bw = ((data[1] >> 16) & 0x3f) * 64; gs.dstbufnew.psm = (data[1] >> 24) & 0x3f; if (gs.dstbufnew.bw == 0) gs.dstbufnew.bw = 64; } void __fastcall GIFRegHandlerTRXPOS(u32* data) { gs.trxposnew.sx = (data[0] ) & 0x7ff; gs.trxposnew.sy = (data[0] >> 16) & 0x7ff; gs.trxposnew.dx = (data[1] ) & 0x7ff; gs.trxposnew.dy = (data[1] >> 16) & 0x7ff; gs.trxposnew.dir = (data[1] >> 27) & 0x3; } void __fastcall GIFRegHandlerTRXREG(u32* data) { gs.imageWtemp = data[0]&0xfff; gs.imageHtemp = data[1]&0xfff; } void __fastcall GIFRegHandlerTRXDIR(u32* data) { // terminate any previous transfers switch( gs.imageTransfer ) { case 0: // host->loc gs.imageTransfer = -1; break; case 1: // loc->host ZeroGS::TerminateLocalHost(); break; } gs.srcbuf = gs.srcbufnew; gs.dstbuf = gs.dstbufnew; gs.trxpos = gs.trxposnew; gs.imageTransfer = data[0] & 0x3; gs.imageWnew = gs.imageWtemp; gs.imageHnew = gs.imageHtemp; if( gs.imageWnew > 0 && gs.imageHnew > 0 ) { switch(gs.imageTransfer) { case 0: // host->loc ZeroGS::InitTransferHostLocal(); break; case 1: // loc->host ZeroGS::InitTransferLocalHost(); break; case 2: ZeroGS::TransferLocalLocal(); break; case 3: gs.imageTransfer = -1; break; default: assert(0); } } else { #ifndef RELEASE_TO_PUBLIC //WARN_LOG("ZeroGS: dummy transfer\n"); #endif gs.imageTransfer = -1; } } static u32 oldhw[4]; void __fastcall GIFRegHandlerHWREG(u32* data) { if( gs.imageTransfer == 0 ) { ZeroGS::TransferHostLocal(data, 2); } else { #ifndef RELEASE_TO_PUBLIC ERROR_LOG("ZeroGS: HWREG!? %8.8x_%8.8x\n", data[0], data[1]); //assert(0); #endif } } extern int g_GSMultiThreaded; void __fastcall GIFRegHandlerSIGNAL(u32* data) { if(!g_GSMultiThreaded) { SIGLBLID->SIGID = (SIGLBLID->SIGID&~data[1])|(data[0]&data[1]); // if (gs.CSRw & 0x1) CSR->SIGNAL = 1; // if (!IMR->SIGMSK && GSirq) // GSirq(); if (gs.CSRw & 0x1) { CSR->SIGNAL = 1; //gs.CSRw &= ~1; } if (!IMR->SIGMSK && GSirq) GSirq(); } } void __fastcall GIFRegHandlerFINISH(u32* data) { if(!g_GSMultiThreaded) { if (gs.CSRw & 0x2) CSR->FINISH = 1; if (!IMR->FINISHMSK && GSirq) GSirq(); // if( gs.CSRw & 2 ) { // //gs.CSRw &= ~2; // //CSR->FINISH = 0; // // // } // CSR->FINISH = 1; // // if( !IMR->FINISHMSK && GSirq ) // GSirq(); } } void __fastcall GIFRegHandlerLABEL(u32* data) { if(!g_GSMultiThreaded) { SIGLBLID->LBLID = (SIGLBLID->LBLID&~data[1])|(data[0]&data[1]); } } // special execute buffers //ExecuteBufferXeno g_ebXeno; // //ExecuteBufferXeno::ExecuteBufferXeno() //{ // clampdata[0] = clampdata[1] = 0; // tex0data[0] = tex0data[1] = 0; // tex1data[0] = tex1data[1] = 0; // bCanExecute = true; // curprim._val = 0; //} // //void ExecuteBufferXeno::Execute() //{ // if( vertices.size() == 0 || !bCanExecute) // return; // // bCanExecute = false; // ZeroGS::Flush(0); // ZeroGS::Flush(1); // // int oldC = gs.primC; // int ctx = curprim.ctxt; // // Vertex oldverts[3]; // oldverts[0] = gs.gsvertex[0]; // oldverts[1] = gs.gsvertex[1]; // oldverts[2] = gs.gsvertex[2]; // // u32 oldtex0[2]; // tex1Info oldtex1 = ZeroGS::vb[ctx].tex1; // clampInfo oldclamp = ZeroGS::vb[ctx].clamp; // oldtex0[0] = ZeroGS::vb[ctx].uNextTex0Data[0]; // oldtex0[1] = ZeroGS::vb[ctx].uNextTex0Data[1]; // // int oldmask = ZeroGS::vb[ctx].zbuf.zmsk; // ZeroGS::vb[ctx].zbuf.zmsk = 1; // tex0Write(0, tex0data); // tex1Write(0, tex1data); // clampWrite(0, clampdata); // ZeroGS::vb[ctx].bTexConstsSync = FALSE; // gs.primC = 3; // u32 oldprim = prim->_val; // prim->_val = curprim._val; // for(int i = 0; i < (int)vertices.size(); i += 3) { // gs.gsvertex[0] = vertices[i]; // gs.gsvertex[1] = vertices[i+1]; // gs.gsvertex[2] = vertices[i+2]; // (*ZeroGS::drawfn[4])(); // draw a triangle // } // vertices.resize(0); // // ZeroGS::Flush(ctx); // // ZeroGS::vb[ctx].zbuf.zmsk = oldmask; // gs.primC = oldC; // gs.gsvertex[0] = oldverts[0]; // gs.gsvertex[1] = oldverts[1]; // gs.gsvertex[2] = oldverts[2]; // ZeroGS::vb[ctx].clamp = oldclamp; // ZeroGS::vb[ctx].tex1 = oldtex1; // tex0Write(0, oldtex0); // ZeroGS::vb[ctx].bTexConstsSync = FALSE; // prim->_val = oldprim; // bCanExecute = true; //} // //void ExecuteBufferXeno::SetTex0(u32* data) //{ // if( data[0] != tex0data[0] || (data[1]&0x1fffffff) != (tex0data[1]&0x1fffffff) ) // Execute(); // // tex0data[0] = data[0]; // tex0data[1] = data[1]; //} // //void ExecuteBufferXeno::SetTex1(u32* data) //{ // if( data[0] != tex1data[0] ) // Execute(); // // tex1data[0] = data[0]; // tex1data[1] = data[1]; //} // //void ExecuteBufferXeno::SetClamp(u32* data) //{ // if( data[0] != clampdata[0] || (data[1]&0xfff) != clampdata[1] ) // Execute(); // // clampdata[0] = data[0]; // clampdata[1] = data[1]&0xfff; //} // //void ExecuteBufferXeno::SetTri() //{ // if( prim->_val != curprim._val ) // Execute(); // curprim._val = prim->_val; // vertices.push_back(gs.gsvertex[0]); // vertices.push_back(gs.gsvertex[1]); // vertices.push_back(gs.gsvertex[2]); //}
[ "zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84" ]
[ [ [ 1, 1113 ] ] ]
ecc758e0be2803a8d168107666369f4c6baeb07c
7e68ef369eff945f581e22595adecb6b3faccd0e
/code/minifw/connector.h
e7edc00fb6aff51225b3b075c658e88219702768
[]
no_license
kimhmadsen/mini-framework
700bb1052227ba18eee374504ff90f41e98738d2
d1983a68c6b1d87e24ef55ca839814ed227b3956
refs/heads/master
2021-01-01T05:36:55.074091
2008-12-16T00:33:10
2008-12-16T00:33:10
32,415,758
0
0
null
null
null
null
UTF-8
C++
false
false
925
h
/** @file */ #pragma once #include "eventhandler.h" #include "reactor.h" #include "sockconnector.h" /** Implements the Connector class from POSA2 page 290 Responsibility: - Actively connects and initializes an associated Service Handler. Collaborator: - ServiceHandler - Dispatcher - TransportEndPoint */ template <class SERVICE_HANDLER> // The <SERVICE_HANDLER> is the type of concrete // service handler activated when a connection. class Connector : public EventHandler { public: Connector( Reactor* reactor): reactor(reactor){} ~Connector(void); private: SOCK_Connector connector; /// Reactor used for asynchronous connection /// completion event notifications. Reactor* reactor; /// Inherited from EventHandler to allow the /// Reactor to notify the Connnector when events /// complete asynchronously virtual void HandleEvent(HANDLE handle, Event_Type et ); };
[ "[email protected]@77f6bdef-6155-0410-8b08-fdea0229669f" ]
[ [ [ 1, 40 ] ] ]
df43a8a60ecb2183acc565fd03ba37390fdb41d1
e9944cc3f8c362cd0314a2d7a01291ed21de19ee
/ xcommon/自由拼音输入法IME/source/HZmodenormal.cpp
57185f1d8e30e1e348a33b7bce0d5f3c678d5d58
[]
no_license
wermanhme1990/xcommon
49d7185a28316d46992ad9311ae9cdfe220cb586
c9b1567da1f11e7a606c6ed638a9fde1f6ece577
refs/heads/master
2016-09-06T12:43:43.593776
2008-12-05T04:24:11
2008-12-05T04:24:11
39,864,906
2
0
null
null
null
null
UTF-8
C++
false
false
18,827
cpp
/* * Copyright (C) 1999.4 Li ZhenChun * * 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 is 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, M A 02139, USA. * * Author: Li ZhenChun email: [email protected] or [email protected] * */ #include "stdafx.h" #include "freepy.h" BOOL CharHandleNormal( HIMC hIMC,WORD wParam,LONG lParam) { if( (wParam >= _T('a') && wParam <= _T('z')) || wParam == _T('\'') ) { return AddChar(hIMC,wParam, EDIT_ADD); } else if( wParam == _T('=') || wParam == _T('.') || wParam == _T('>')) { return ForwardPage(hIMC); } else if( wParam == _T('-') || wParam == _T(',') || wParam == _T('<')) { return BackwardPage(hIMC); } else if( wParam >= _T('0') && wParam <= _T('9') ) { return SelectCand(hIMC,wParam); } switch ( wParam ) { case _T('!'): case _T('@'): case _T('#'): case _T('$'): case _T('%'): case _T('^'): case _T('&'): case _T('*'): case _T('('): case _T(')'): return DeletePhrase(hIMC,wParam); default: break; } return FALSE; } BOOL AddChar( HIMC hIMC, WORD wCode, WORD wEditMode) { LPINPUTCONTEXT lpIMC; LPCOMPOSITIONSTRING lpCompStr; LPCANDIDATEINFO lpCandInfo; LPCANDIDATELIST lpCandList; LPFREEPYCAND lpPYCand; LPTSTR lpStr; LPTSTR lpConvStr; LPTSTR lpPaintStr; TCHAR szTemp[150]; GENEMSG GnMsg; LPTSTR lpPYArray; WORD *lpwPYArrayLen; WORD *lpwPYArrayCurPos; SHORT *lpwUnConvPos; SHORT *lpwEditCaret; TCHAR cTempChar; WORD wPYCount; int i; BOOL fRet = FALSE; TCHAR szPreStr[150]; WORD wPreUnConvPos; WORD wPreEditCaret; lpIMC = ImmLockIMC(hIMC); lpCompStr = (LPCOMPOSITIONSTRING)ImmLockIMCC(lpIMC->hCompStr); lpStr = GETLPCOMPSTR(lpCompStr); lpConvStr = ((LPMYCOMPSTR)lpCompStr)->FreePYComp.szConvCompStr; lpPaintStr = ((LPMYCOMPSTR)lpCompStr)->FreePYComp.szPaintCompStr; lpPYArray = (LPTSTR)(((LPMYCOMPSTR)lpCompStr)->FreePYComp.szPYArray); lpwPYArrayLen = &(((LPMYCOMPSTR)lpCompStr)->FreePYComp.wPYArrayLen); lpwPYArrayCurPos = &(((LPMYCOMPSTR)lpCompStr)->FreePYComp.wPYArrayCurPos); lpwUnConvPos = &(((LPMYCOMPSTR)lpCompStr)->FreePYComp.wUnConvPos); lpwEditCaret = &(((LPMYCOMPSTR)lpCompStr)->FreePYComp.wEditCaret); _tcscpy(szPreStr,lpStr); wPreUnConvPos = *lpwUnConvPos; wPreEditCaret = *lpwEditCaret; if( wEditMode == EDIT_BACK ) { if(!_tcslen(lpStr) || (*lpwEditCaret) < 1 ) { MessageBeep(0xFFFFFFFF ); fRet = TRUE; goto my_exit; } else if(*lpwEditCaret <= *lpwUnConvPos) { *lpConvStr = _T('\0'); *lpwUnConvPos = 0; } else { _tcscpy(szTemp, lpStr + *lpwEditCaret); _tcscpy(lpStr + *lpwEditCaret -1,szTemp); *lpwEditCaret -= 1; if( !_tcslen(lpStr)) { MakeResultString(hIMC, FALSE); fRet = TRUE; goto my_exit; } } } else if( wEditMode == EDIT_DELETE ) { if(!_tcslen(lpStr) || (*lpwEditCaret) == (SHORT)_tcslen(lpStr) ) { MessageBeep(0xFFFFFFFF ); fRet = TRUE; goto my_exit; } else { _tcscpy(szTemp,lpStr + *lpwEditCaret + 1); _tcscpy(lpStr + *lpwEditCaret,szTemp); if( !_tcslen(lpStr)) { MakeResultString(hIMC, FALSE); fRet = TRUE; goto my_exit; } } } else if( wEditMode == EDIT_ADD ) { _tcscpy(szTemp,lpStr + *lpwEditCaret); *(lpStr + *lpwEditCaret) = (TCHAR)wCode; _tcscpy(lpStr + *lpwEditCaret +1,szTemp); *lpwEditCaret += 1; } else { MessageBeep(0xFFFFFFFF ); fRet = TRUE; goto my_exit; } lpCompStr->dwCompStrLen = _tcslen(lpStr); if(!_tcslen(lpConvStr)) { *lpwPYArrayCurPos = 0; } wPYCount=ParsePY(lpStr + *lpwUnConvPos,lpPYArray + (*lpwPYArrayCurPos)*MAX_PY_LEN,MAX_PY_LEN); *lpwPYArrayLen = *lpwPYArrayCurPos + wPYCount; i = *lpwPYArrayLen; while(i--) { if((cTempChar = *(lpPYArray + i*MAX_PY_LEN)) == _T('i') || cTempChar == _T('u') || cTempChar == _T('v') ) { _tcscpy(lpStr,szPreStr); *lpwEditCaret = wPreEditCaret; *lpwUnConvPos = wPreUnConvPos; *lpwPYArrayLen = *lpwPYArrayLen - 1; MessageBeep(0xFFFFFFFF ); fRet = TRUE; goto my_exit; } } if(EffectPYArrayLen(lpPYArray,MAX_PY_LEN,*lpwPYArrayLen) > MAX_PHRASE_LEN) { _tcscpy(lpStr,szPreStr); *lpwEditCaret = wPreEditCaret; *lpwUnConvPos = wPreUnConvPos; *lpwPYArrayLen = *lpwPYArrayLen - 1; MessageBeep(0xFFFFFFFF ); fRet = TRUE; goto my_exit; } lpCandInfo = (LPCANDIDATEINFO)ImmLockIMCC(lpIMC->hCandInfo); lpCandList = (LPCANDIDATELIST)((LPBYTE)lpCandInfo + lpCandInfo->dwOffset[0]); lpPYCand = (LPFREEPYCAND)(&((LPMYCAND)lpCandInfo)->FreePYCand); ConvertPY( lpPYArray + (*lpwPYArrayCurPos)*MAX_PY_LEN, MAX_PY_LEN, wPYCount, lpPYCand); lpPYCand->awBeforePos[1] = 0; lpPYCand->awBeforePos[0] = 0; lpPYCand->awCurrentPos[1] = 0; lpPYCand->awCurrentPos[0] = 0; lpPYCand->wSelectDirect = SELECT_FORWARD; lpPYCand->wSelectStatus = 1; lpCandList->dwCount = CreateCandStr(lpPYCand, SELECT_FORWARD, (LPTSTR)(((LPMYCAND)lpCandInfo)->szCandStr),MAXCANDSTRSIZE); lpCandList->dwPageStart = 2; lpCandList->dwPageSize = 10; CreatePaintStr( lpPYArray + (*lpwPYArrayCurPos) * MAX_PY_LEN, MAX_PY_LEN,(WORD)((*lpwPYArrayLen)-(*lpwPYArrayCurPos)),lpConvStr,lpPaintStr); GnMsg.msg = WM_IME_COMPOSITION; GnMsg.wParam = 0; GnMsg.lParam = GCS_COMPSTR; TRACE(TEXT("AddChar GenerateMessage")); GenerateMessage(hIMC, (LPGENEMSG)&GnMsg); ImmUnlockIMCC(lpIMC->hCandInfo); fRet = TRUE; my_exit: ImmUnlockIMCC(lpIMC->hCompStr); ImmUnlockIMC(hIMC); return fRet; } BOOL ForwardPage(HIMC hIMC) { LPINPUTCONTEXT lpIMC; LPCANDIDATEINFO lpCandInfo; LPCANDIDATELIST lpCandList; LPFREEPYCAND lpPYCand; GENEMSG GnMsg; DWORD dwCount; if( !IsCompStr(hIMC) ) return FALSE; lpIMC = ImmLockIMC(hIMC); lpCandInfo = (LPCANDIDATEINFO)ImmLockIMCC(lpIMC->hCandInfo); lpCandList = (LPCANDIDATELIST)((LPBYTE)lpCandInfo + lpCandInfo->dwOffset[0]); lpPYCand = (LPFREEPYCAND)(&((LPMYCAND)lpCandInfo)->FreePYCand); dwCount = CreateCandStr(lpPYCand, SELECT_FORWARD, (LPTSTR)(((LPMYCAND)lpCandInfo)->szCandStr), MAXCANDSTRSIZE); if (dwCount > 0) { lpCandList->dwCount = dwCount; } lpCandList->dwPageStart = 2; lpCandList->dwPageSize = 10; if(lpCandList->dwCount) { GnMsg.msg = WM_IME_COMPOSITION; GnMsg.wParam = 0; GnMsg.lParam = GCS_COMPSTR; GenerateMessage(hIMC, (LPGENEMSG)&GnMsg); } ImmUnlockIMCC(lpIMC->hCandInfo); ImmUnlockIMC(hIMC); return TRUE; } BOOL BackwardPage(HIMC hIMC) { LPINPUTCONTEXT lpIMC; LPCANDIDATEINFO lpCandInfo; LPCANDIDATELIST lpCandList; LPFREEPYCAND lpPYCand; GENEMSG GnMsg; DWORD dwCount; if( !IsCompStr(hIMC) ) { return FALSE; } lpIMC = ImmLockIMC(hIMC); lpCandInfo = (LPCANDIDATEINFO)ImmLockIMCC(lpIMC->hCandInfo); lpCandList = (LPCANDIDATELIST)((LPBYTE)lpCandInfo + lpCandInfo->dwOffset[0]); lpPYCand = (LPFREEPYCAND)(&((LPMYCAND)lpCandInfo)->FreePYCand); dwCount = CreateCandStr(lpPYCand, SELECT_BACKWARD, (LPTSTR)(((LPMYCAND)lpCandInfo)->szCandStr),MAXCANDSTRSIZE); if (dwCount > 0) { lpCandList->dwCount = dwCount; } lpCandList->dwPageStart = 2; lpCandList->dwPageSize = 10; if(lpCandList->dwCount) { GnMsg.msg = WM_IME_COMPOSITION; GnMsg.wParam = 0; GnMsg.lParam = GCS_COMPSTR; GenerateMessage(hIMC, (LPGENEMSG)&GnMsg); } ImmUnlockIMCC(lpIMC->hCandInfo); ImmUnlockIMC(hIMC); return TRUE; } BOOL SelectCand(HIMC hIMC,WORD wParam) { LPINPUTCONTEXT lpIMC; LPCOMPOSITIONSTRING lpCompStr; LPCANDIDATEINFO lpCandInfo; LPCANDIDATELIST lpCandList; LPFREEPYCAND lpPYCand; LPTSTR lpStr; LPTSTR lpConvStr; LPTSTR lpPaintStr; LPTSTR lpPYArray; SHORT *lpwUnConvPos; SHORT *lpwEditCaret; WORD *lpwPYArrayLen; WORD *lpwPYArrayCurPos; GENEMSG GnMsg; WORD wIdx,awLen[2],wPosSpan,wTotal,wCount; TCHAR szTempStr[(MAX_PHRASE_LEN + 1)*2]; int i; DWORD dwAttrib; if( !IsCompStr(hIMC) ) return FALSE; lpIMC = ImmLockIMC(hIMC); lpCandInfo = (LPCANDIDATEINFO)ImmLockIMCC(lpIMC->hCandInfo); lpCandList = (LPCANDIDATELIST)((LPBYTE)lpCandInfo + lpCandInfo->dwOffset[0]); lpPYCand = (LPFREEPYCAND)(&((LPMYCAND)lpCandInfo)->FreePYCand); lpCompStr = (LPCOMPOSITIONSTRING)ImmLockIMCC(lpIMC->hCompStr); lpStr = GETLPCOMPSTR(lpCompStr); lpConvStr = ((LPMYCOMPSTR)lpCompStr)->FreePYComp.szConvCompStr; lpPaintStr = ((LPMYCOMPSTR)lpCompStr)->FreePYComp.szPaintCompStr; lpPYArray = (LPTSTR)(((LPMYCOMPSTR)lpCompStr)->FreePYComp.szPYArray); lpwPYArrayLen = &(((LPMYCOMPSTR)lpCompStr)->FreePYComp.wPYArrayLen); lpwPYArrayCurPos = &(((LPMYCOMPSTR)lpCompStr)->FreePYComp.wPYArrayCurPos); lpwUnConvPos = &(((LPMYCOMPSTR)lpCompStr)->FreePYComp.wUnConvPos); lpwEditCaret = &(((LPMYCOMPSTR)lpCompStr)->FreePYComp.wEditCaret); TRACE(TEXT("lpStr : %s"), lpStr); TRACE(TEXT("lpConvStr : %s"), lpConvStr); TRACE(TEXT("lpPaintStr : %s"), lpPaintStr); if( wParam == (WORD)_T('0') ) wIdx = 9; else wIdx = wParam - (WORD)_T('1'); if(wIdx >= lpCandList->dwCount) return FALSE; wTotal = wIdx + 1; switch(lpPYCand->wSelectDirect) { case SELECT_FORWARD: if(wConversionSet & CONVERSION_SET_GBK) { wIdx += lpPYCand->awBeforePos[lpPYCand->wSelectStatus]; } else { if(lpPYCand->wSelectStatus) { wIdx += lpPYCand->awBeforePos[lpPYCand->wSelectStatus]; } else { wIdx = lpPYCand->awBeforePos[lpPYCand->wSelectStatus]; wCount = 0; while( wCount != wTotal) { for(i=0;i < lpPYCand->wHZNum;i++) { if((lpPYCand->aHanZi + i)->wLen > wIdx) break; } #ifdef _UNICODE if(i) _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ + (wIdx - (lpPYCand->aHanZi+i-1)->wLen),1); else _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ + wIdx,1); szTempStr[1] = _T('\0'); #else if(i) _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ + 2*(wIdx - (lpPYCand->aHanZi+i-1)->wLen),2); else _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ+2*wIdx,2); szTempStr[2] = _T('\0'); #endif if( (*((LPBYTE)szTempStr) >= GB_QUFIRST && *((LPBYTE)szTempStr) <= GB_QULAST) && (*((LPBYTE)szTempStr+1) >= GB_WEIFIRST && *((LPBYTE)szTempStr+1) <= GB_WEILAST) ) { wCount++; } wIdx++; } wIdx--; } } break; case SELECT_BACKWARD: if(wConversionSet & CONVERSION_SET_GBK) { wIdx += lpPYCand->awCurrentPos[lpPYCand->wSelectStatus]+1; } else { if(lpPYCand->wSelectStatus) { wIdx += lpPYCand->awCurrentPos[lpPYCand->wSelectStatus]+1; } else { wIdx = lpPYCand->awBeforePos[lpPYCand->wSelectStatus]; wTotal--; wCount = 10; while( wCount != wTotal) { for(i=0;i < lpPYCand->wHZNum;i++) { if((lpPYCand->aHanZi+i)->wLen > wIdx) break; } #ifdef _UNICODE if(i) _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ + (wIdx - (lpPYCand->aHanZi+i-1)->wLen),1); else _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ + wIdx,1); szTempStr[1] = _T('\0'); #else if(i) _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ + 2*(wIdx - (lpPYCand->aHanZi+i-1)->wLen),2); else _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ+2*wIdx,2); szTempStr[2] = _T('\0'); #endif if( (*((LPBYTE)szTempStr) >= GB_QUFIRST && *((LPBYTE)szTempStr) <= GB_QULAST) && (*((LPBYTE)szTempStr+1) >= GB_WEIFIRST && *((LPBYTE)szTempStr+1) <= GB_WEILAST) ) { wCount--; } wIdx--; } wIdx++; } } break; default: break; } awLen[1] = lpPYCand->wPhraseNum; awLen[0] = (lpPYCand->aHanZi + lpPYCand->wHZNum - 1)->wLen; if(0 < wIdx < awLen[lpPYCand->wSelectStatus]) { if(lpPYCand->wSelectStatus) { _tcscpy(szTempStr,(lpPYCand->aPhrase+wIdx)->lpHZPH->szHZ); _tcscat(lpConvStr,szTempStr); lpPYCand ->abKey[0] |= (lpPYCand->aPhrase+wIdx)->lpKeyPH->abKey[0] << lpPYCand->wKeyLen; for(i=1;i<=(lpPYCand->aPhrase+wIdx)->lpKeyPH->wLen;i++) { lpPYCand ->abKey[(lpPYCand->wKeyLen++) + 1] = (lpPYCand->aPhrase+wIdx)->lpKeyPH->abKey[i]; } } else { for(i=0;i < lpPYCand->wHZNum;i++) { if((lpPYCand->aHanZi+i)->wLen > wIdx ) { break; } } #ifdef _UNICODE if(i) { _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ + (wIdx - (lpPYCand->aHanZi+i-1)->wLen), 1); } else { _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ + wIdx,1); } szTempStr[1] = _T('\0'); #else if(i) { _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ + 2*(wIdx - (lpPYCand->aHanZi+i-1)->wLen),2); } else { _tcsncpy(szTempStr,(lpPYCand->aHanZi+i)->lpHZ + 2 * wIdx,2); } szTempStr[2] = _T('\0'); #endif _tcscat(lpConvStr,szTempStr); lpPYCand ->abKey[0] |= ((lpPYCand->aHanZi+i)->wKey & 0x0100) >>(8 - lpPYCand->wKeyLen); lpPYCand ->abKey[(lpPYCand->wKeyLen++) + 1] = (BYTE)(lpPYCand->aHanZi+i)->wKey & 0xff; } #ifdef _UNICODE if( EffectPYArrayLen(lpPYArray,MAX_PY_LEN,*lpwPYArrayLen) == _tcslen(lpConvStr) ) { if(_tcslen(szTempStr) == _tcslen(lpConvStr) && lpPYCand->wSelectStatus) { (lpPYCand->aPhrase + wIdx)->lpHZPH->dwAttrib++; } else if(_tcslen(lpConvStr) > 1) { dwAttrib=dwCurPhraseAttrib; if(dwAttrib <= 1) { dwAttrib = 1; } else { dwAttrib --; } SavePhToMapFile(lpConvStr,lpPYCand->abKey,(WORD)(_tcslen(lpConvStr)),dwAttrib,1); } #else if( EffectPYArrayLen(lpPYArray,MAX_PY_LEN,*lpwPYArrayLen) == _tcslen(lpConvStr)/2 ) { if(_tcslen(szTempStr) == _tcslen(lpConvStr) && lpPYCand->wSelectStatus) { ((lpPYCand->aPhrase + wIdx)->lpHZPH->dwAttrib)++; } else if(_tcslen(lpConvStr) > 2) { dwAttrib=dwCurPhraseAttrib; if(dwAttrib <= 1) { dwAttrib=1; } else { dwAttrib--; } SavePhToMapFile(lpConvStr,lpPYCand->abKey,(WORD)(_tcslen(lpConvStr)/2),dwAttrib,1); } #endif MakeResultString(hIMC,TRUE); goto my_exit; } else { #ifdef _UNICODE wPosSpan = CalculatePosSpan(lpPYArray+(*lpwPYArrayCurPos)*MAX_PY_LEN, MAX_PY_LEN,(WORD)((*lpwPYArrayLen)-(*lpwPYArrayCurPos)),(WORD)_tcslen(szTempStr)); #else wPosSpan = CalculatePosSpan(lpPYArray+(*lpwPYArrayCurPos)*MAX_PY_LEN, MAX_PY_LEN,(WORD)((*lpwPYArrayLen)-(*lpwPYArrayCurPos)),(WORD)(_tcslen(szTempStr)/2)); #endif *lpwPYArrayCurPos += wPosSpan; *lpwUnConvPos = CalculateUnConvPos(lpPYArray + (*lpwPYArrayCurPos)*MAX_PY_LEN, MAX_PY_LEN,(WORD)((*lpwPYArrayLen)-(*lpwPYArrayCurPos)),lpStr); *lpwEditCaret = (SHORT)_tcslen(lpStr); ConvertPY( lpPYArray + (*lpwPYArrayCurPos)*MAX_PY_LEN, MAX_PY_LEN,(WORD)((*lpwPYArrayLen)-(*lpwPYArrayCurPos)),lpPYCand); lpPYCand->awBeforePos[1] = 0; lpPYCand->awBeforePos[0] = 0; lpPYCand->awCurrentPos[1] = 0; lpPYCand->awCurrentPos[0] = 0; lpPYCand->wSelectDirect = SELECT_FORWARD; lpPYCand->wSelectStatus = 1; lpCandList->dwCount = CreateCandStr(lpPYCand, SELECT_FORWARD, (LPTSTR)(((LPMYCAND)lpCandInfo)->szCandStr),MAXCANDSTRSIZE); lpCandList->dwPageStart = 2; lpCandList->dwPageSize = 10; CreatePaintStr( lpPYArray + (*lpwPYArrayCurPos)*MAX_PY_LEN, MAX_PY_LEN,(WORD)((*lpwPYArrayLen)-(*lpwPYArrayCurPos)),lpConvStr,lpPaintStr); } } GnMsg.msg = WM_IME_COMPOSITION; GnMsg.wParam = 0; GnMsg.lParam = GCS_COMPSTR; GenerateMessage(hIMC, (LPGENEMSG)&GnMsg); my_exit: ImmUnlockIMCC(lpIMC->hCandInfo); ImmUnlockIMCC(lpIMC->hCompStr); ImmUnlockIMC(hIMC); return TRUE; } BOOL DeletePhrase(HIMC hIMC,WORD wParam) { LPINPUTCONTEXT lpIMC; LPCANDIDATEINFO lpCandInfo; LPCANDIDATELIST lpCandList; LPFREEPYCAND lpPYCand; LPKEYPH lpKPh; LPHZPH lpHZPh,lpCurHZPh,lpPreHZPh; WORD wLen,wIdx; WORD wRet = 0; if( !IsCompStr(hIMC) ) { return FALSE; } lpIMC = ImmLockIMC(hIMC); lpCandInfo = (LPCANDIDATEINFO)ImmLockIMCC(lpIMC->hCandInfo); lpCandList = (LPCANDIDATELIST)((LPBYTE)lpCandInfo + lpCandInfo->dwOffset[0]); lpPYCand = (LPFREEPYCAND)(&((LPMYCAND)lpCandInfo)->FreePYCand); if( ! lpPYCand->wSelectStatus ) { ImmUnlockIMCC(lpIMC->hCandInfo); ImmUnlockIMC(hIMC); return FALSE; } switch( wParam ) { case _T('!'): wIdx = 0; break; case _T('@'): wIdx = 1; break; case _T('#'): wIdx = 2; break; case _T('$'): wIdx = 3; break; case _T('%'): wIdx = 4; break; case _T('^'): wIdx = 5; break; case _T('&'): wIdx = 6; break; case _T('*'): wIdx = 7; break; case _T('('): wIdx = 8; break; case _T(')'): wIdx = 9; break; default: wIdx = 0; break; } switch(lpPYCand->wSelectDirect) { case SELECT_FORWARD: wIdx += lpPYCand->awBeforePos[lpPYCand->wSelectStatus]; break; case SELECT_BACKWARD: wIdx += lpPYCand->awCurrentPos[lpPYCand->wSelectStatus]+1; break; default: break; } wLen = lpPYCand->wPhraseNum; if(0 < wIdx < wLen ) { lpKPh = (lpPYCand->aPhrase+wIdx)->lpKeyPH; lpHZPh = (lpPYCand->aPhrase+wIdx)->lpHZPH; if( ((LPBYTE)lpKPh >= (LPBYTE)lpMapFileBase && (LPBYTE)lpKPh < (LPBYTE)lpMapFileBase + MAX_PY_NUM*sizeof(KEYPH) ) || ((LPBYTE)lpKPh >= (LPBYTE)lpMapFileBase + 2*MAX_PY_NUM*sizeof(KEYPH) &&(LPBYTE)lpKPh < (LPBYTE)lpMapFileBase + dwMapFileUsrOffset ) ) { lpHZPh->dwAttrib = 0; wRet = 1; } else { lpCurHZPh = lpKPh->lpHZPH; if( lpCurHZPh == lpHZPh) { if(lpHZPh->lpNext == NULL) { lpKPh->wLen = -1; } lpKPh->lpHZPH = lpHZPh->lpNext; wRet = 1; } else { lpPreHZPh = lpCurHZPh; do { lpCurHZPh = lpCurHZPh->lpNext; if(lpCurHZPh == lpHZPh) { lpPreHZPh->lpNext = lpCurHZPh->lpNext; wRet = 1; break; } lpPreHZPh = lpCurHZPh; } while(lpCurHZPh->lpNext != NULL); } } } if( wRet ) { MakeResultString(hIMC,FALSE); } ImmUnlockIMCC(lpIMC->hCandInfo); ImmUnlockIMC(hIMC); return TRUE; }
[ [ [ 1, 733 ] ] ]
4af9b1a09b66c8270a7d1b53bccf07e2cb963141
3856c39683bdecc34190b30c6ad7d93f50dce728
/LastProject/Source/Cube.cpp
1e618efa92ba7957ce0b746f967e2592fc0b9241
[]
no_license
yoonhada/nlinelast
7ddcc28f0b60897271e4d869f92368b22a80dd48
5df3b6cec296ce09e35ff0ccd166a6937ddb2157
refs/heads/master
2021-01-20T09:07:11.577111
2011-12-21T22:12:36
2011-12-21T22:12:36
34,231,967
0
0
null
null
null
null
UHC
C++
false
false
4,015
cpp
/** @file Cube.cpp @date 2011/09/17 @author 백경훈 @brief 큐브 클래스 */ #include "stdafx.h" #include "Cube.h" #ifdef _CELLCUBE CCube::CCube() { Clear(); } CCube::~CCube() { Release(); } VOID CCube::Clear() { m_pD3dDevice = NULL ; m_pTexture = NULL; m_iStartVB = 0; m_iStartIB = 0; m_fCubeSize = 0.0f; m_pCell = NULL; } HRESULT CCube::Create( LPDIRECT3DDEVICE9 a_pD3dDevice, LPDIRECT3DVERTEXBUFFER9 &a_pVB, LPDIRECT3DINDEXBUFFER9 &a_pIB, INT a_iStartVB, INT a_iStartIB, FLOAT a_fCubeSize ) { m_pD3dDevice = a_pD3dDevice; m_iStartVB = a_iStartVB; m_iStartIB = a_iStartIB; m_fCubeSize = a_fCubeSize; //_InitVB( a_pVB ); //_InitIB( a_pIB ); m_pCell = new CCell[6]; for(INT Loop=0; Loop<6; ++Loop) { m_pCell[Loop].Create( m_pD3dDevice, a_pVB, a_pIB, m_iStartVB + ( Loop * 4 ), 0, m_fCubeSize, Loop ); } return S_OK; } HRESULT CCube::Release() { /*if(m_pVB != NULL) { m_pVB->Release(); m_pVB=NULL; } if(m_pIB != NULL) { m_pIB->Release(); m_pIB=NULL; }*/ if(m_pTexture != NULL) { m_pTexture->Release(); m_pTexture=NULL; } SAFE_DELETE_ARRAY( m_pCell ); return S_OK; } HRESULT CCube::InitTexture( DWORD a_Color, DWORD a_OutLineColor ) { /*if( FAILED( D3DXCreateTextureFromFile( GD3D9DEVICE, L"Media/TerrainTexture/test.bmp", &m_pTexture ) ) ) { return E_FAIL; }*/ LPBYTE pData; LPDWORD pDWord; D3DLOCKED_RECT Texture_Locked; INT TextureSize = 8; if( m_pTexture != NULL ) { m_pTexture->Release(); m_pTexture=NULL; } if( FAILED( m_pD3dDevice->CreateTexture( TextureSize, TextureSize, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &m_pTexture, NULL ) ) ) { return E_FAIL; } memset( &Texture_Locked, 0, sizeof(D3DLOCKED_RECT) ); if( FAILED(m_pTexture->LockRect(0, &Texture_Locked, NULL, 0)) ) { return E_FAIL; } pData = (LPBYTE)Texture_Locked.pBits; for(INT iLoopY=0; iLoopY<TextureSize; ++iLoopY) { pDWord = LPDWORD(pData + iLoopY * Texture_Locked.Pitch); for(INT iLoopX=0; iLoopX<TextureSize; ++iLoopX) { //외곽선 처리 if( iLoopX == 0 || iLoopX == TextureSize-1 || iLoopY == 0 || iLoopY == TextureSize-1 ) { *(pDWord + iLoopX) = a_OutLineColor; } else { *(pDWord + iLoopX) = a_Color; } } } if( FAILED(m_pTexture->UnlockRect(0)) ) { return E_FAIL; } return S_OK; } VOID CCube::Update() { } VOID CCube::Render() { //m_pD3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE); //m_pD3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); //m_pD3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); //m_pD3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW); //m_pD3dDevice->SetTexture( 0, m_pTexture ); //m_pD3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 0 ); //m_pD3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); //m_pD3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); //m_pD3dDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); //m_pD3dDevice->SetRenderState(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL); //m_pD3dDevice->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1); //m_pD3dDevice->SetRenderState(D3DRS_COLORVERTEX, TRUE); //m_pD3dDevice->SetStreamSource( 0, m_pVB, 0, sizeof( CUBEVERTEX ) ); //m_pD3dDevice->SetFVF( CUBEVERTEX::FVF ); //m_pD3dDevice->SetIndices( m_pIB ); //m_pD3dDevice->SetTexture( 0, m_pTexture ); for(INT Loop=0; Loop<6; ++Loop) { //CMatrices::GetInstance()->SetupModeltoWorld( m_pCell[Loop].Get_MatWorld() ); if( m_pCell[Loop].Get_FaceVisble() == TRUE ) { m_pCell[Loop].Render(); } } //m_pD3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, m_iStartVB, 0, CUBEVERTEX::VertexNum, 0, 12 ); //m_pD3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE); //m_pD3dDevice->SetTexture( 0, NULL ); } #endif
[ "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0" ]
[ [ [ 1, 181 ] ] ]
23c0012024f3d3d38284a5a78b279dec8c35dc8b
65a392af0450708ed4fa26f66393e12bdf387634
/Kernel/initialize.cpp
7c550993bab0ca7772116e9244fc7fbd95458d83
[]
no_license
zhouxs1023/mU
d5abea6e883cb746aa28ff6ee2b3902babb053d8
c9ecc5f0a4fd13567b3c9ca24ff05ba149af743e
refs/heads/master
2021-05-27T11:37:59.464639
2011-06-17T22:39:25
2011-06-17T22:39:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,566
cpp
#include <mU/Number.h> #include <mU/String.h> #include <mU/Pattern.h> #include <mU/Kernel.h> #include <mU/Interface.h> namespace mU { namespace { Wrap(CompoundExpression) { var r; size_t n = Size(x); for(size_t i = 0; i < n; ++i) { r = Eval(At(x,i)); if(ExQ(r)) { var h = Head(r); if(h == TAG(Return)) { var b = Body(r); return Size(b) == 0 ? r : Eval(At(b,0)); } else if(h == TAG(Break) || h == TAG(Continue)) break; } } return r; } Wrap(Flatten) { var c = At(x,0); if(VecQ(c)) { var r = Vec(); Flatten(r,c); return r; } else if(ExQ(c)) { var r = Vec(); var h = Head(c); var b = Body(c); Flatten(r,h,b); return Ex(h,r); } return 0; } Wrap(FlattenAll) { var c = At(x,0); if(VecQ(c)) { var r = Vec(); FlattenAll(r,c); return r; } else if(ExQ(c)) { var r = Vec(); var h = Head(c); var b = Body(c); FlattenAll(r,h,b); return Ex(h,r); } return 0; } Wrap(And) { var r = Vec(); size_t n = Size(x); for(size_t i = 0; i < n; ++i) { var c = Eval(At(x,i)); if(c == False) return False; if(c == True) continue; Push(r,c); } if(Size(r) == 0) return True; return 0; } Wrap(Or) { var r = Vec(); size_t n = Size(x); for(size_t i = 0; i < n; ++i) { var c = Eval(At(x,i)); if(c == True) return True; if(c == False) continue; Push(r,c); } if(Size(r) == 0) return False; return 0; } Wrap(Not) { return At(x,0) == True ? False : At(x,0) == False ? True : 0; } Wrap(If) { return At(x,0) == True ? Eval(At(x,1)) : At(x,0) == False && Size(x) == 3 ? Eval(At(x,2)) : Null; } Wrap(For) { var r; for(Eval(At(x,0)); Eval(At(x,1)) == True; Eval(At(x,2))) { r = Eval(At(x,3)); if(ExQ(r)) { var h = Head(r); if(h == TAG(Return)) return r; if(h == TAG(Break)) break; if(h == TAG(Continue)) continue; } } return Null; } Wrap(While) { var r; while(Eval(At(x,0)) == True) { r = Eval(At(x,1)); if(ExQ(r)) { var h = Head(r); if(h == TAG(Return)) return r; if(h == TAG(Break)) break; if(h == TAG(Continue)) continue; } } return Null; } Wrap(SameQ) { return Same(At(x,0),At(x,1)) ? True : False; } Wrap(Less) { return Less(At(x,0),At(x,1)) ? True : False; } Wrap(Equal) { return Equal(At(x,0),At(x,1)) ? True : False; } Wrap(Greater) { return Greater(At(x,0),At(x,1)) ? True : False; } Wrap(UnsameQ) { return !Same(At(x,0),At(x,1)) ? True : False; } Wrap(GreaterEqual) { return !Less(At(x,0),At(x,1)) ? True : False; } Wrap(Unequal) { return !Equal(At(x,0),At(x,1)) ? True : False; } Wrap(LessEqual) { return !Greater(At(x,0),At(x,1)) ? True : False; } Wrap(FreeQ) { return FreeQ(At(x,0),At(x,1)) ? True : False; } Wrap(With) { var a = At(x,0); size_t n = Size(a); map_t m; for(size_t i = 0; i < n; ++i) if(ExQ(At(a,i),TAG(Set))) m[Left(At(a,i))] = Eval(Right(At(a,i))); return Eval(Subs(m,At(x,1))); } Wrap(Block) { var a = At(x,0); size_t n = Size(a); std::vector<Var> locals(n); std::vector<var> local_values(n); for(size_t i = 0; i < n; ++i) { var c = At(a,i); if(ExQ(c,TAG(Set))) { locals[i] = Left(c); local_values[i] = Eval(Left(c)); Set(Left(c),Eval(Right(c))); } else if(SymQ(At(a,i))) { locals[i] = c; local_values[i] = Eval(c); } } var r = Eval(At(x,1)); for(size_t i = 0; i < n; ++i) Set(locals[i],local_values[i]); return r; } Wrap(Module) { wstring s = Unique(); var a = At(x,0); size_t n = Size(a); map_t m; for(size_t i = 0; i < n; ++i) { var c = At(a,i); if(ExQ(c,TAG(Set))) { var t = Sym(Name(Left(c)) + s); m[Left(c)] = t; Set(t,Eval(Right(c))); } else if(SymQ(At(a,i))) { var t = Sym(Name(c) + s); m[c] = t; } } var r = Eval(Subs(m,At(x,1))); map_t::const_iterator iter = m.begin(); while(iter != m.end()) { Unset(iter->second); ++iter; } return r; } Wrap(MatchQ) { map_t m; return MatchQ(m,Pat(At(x,1)),At(x,0)) ? True : False; } Wrap(MemberQ) { return MemberQ(At(x,0),At(x,1)) ? True : False; } Wrap(Dispatch) { if(VecQ(At(x,0))) return Dispatch(At(x,0)); return Dispatch(x); } Wrap(Replace) { var a = At(x,0); var b = At(x,1); if(VecQ(b)) { size_t n = Size(b); for(size_t i = 0; i < n; ++i) a = Replace(a,At(b,i)); return a; } return Replace(a,b); } Wrap(ReplaceAll) { var a = At(x,0); var b = At(x,1); if(VecQ(b)) { size_t n = Size(b); for(size_t i = 0; i < n; ++i) a = ReplaceAll(a,At(b,i)); return a; } return ReplaceAll(a,b); } Wrap(ReplaceRepeated) { var r = WRAP(ReplaceAll)(x); while(!Same(r,At(x,0))) { At(x,0) = r; r = WRAP(ReplaceAll)(x); } return r; } Wrap(OddQ) { return OddQ(At(x,0)) ? True : False; } Wrap(EvenQ) { return EvenQ(At(x,0)) ? True : False; } Wrap(SetAttributes) { var a = At(x,0); var b = At(x,1); if(VecQ(b)) { size_t n = Size(b); for(size_t i = 0; i < n; ++i) Attributes[a].insert(At(b,i)); } else Attributes[a].insert(b); return Null; } Wrap(StringJoin) { size_t n = Size(x); var c = At(x,0); if(StrQ(c)) { var r = Str(); CStr(r) = CStr(c); for(size_t i = 1; i < n; ++i) S::AddTo(r,At(x,i)); return r; } return 0; } Wrap(Join) { size_t n = Size(x); var c = At(x,0); if(VecQ(c)) { size_t m = Size(c); for(size_t i = 1; i < n; ++i) m += Size(At(x,i)); var r = Vec(m); vec_t::rep_t::iterator iter = CVec(r).begin(); std::copy(CVec(c).begin(),CVec(c).end(),iter); for(size_t i = 1; i < n; ++i) std::copy(CVec(At(x,i)).begin(),CVec(At(x,i)).end(),iter += Size(At(x,i - 1))); return r; } return 0; } Wrap(Get) { if(StrQ(At(x,0))) { var r = ParseFile(CStr(At(x,0))); return r ? r : Nil; } return 0; } Wrap(Put) { var a = At(x,0); var b = At(x,1); if(StrQ(b)) { wofstream f(string(CStr(b).begin(),CStr(b).end()).c_str()); if(f) { Println(a,f); f.close(); return True; } } return False; } Wrap(PutAppend) { var a = At(x,0); var b = At(x,1); if(StrQ(b)) { wofstream f(string(CStr(b).begin(),CStr(b).end()).c_str(),wios::app); if(f) { Println(a,f); f.close(); return True; } } return False; } Wrap(Attributes) { var r = Vec(); std::map<Var,attr_t>::const_iterator iter = Attributes.find(At(x,0)); if(iter != Attributes.end()) CVec(r).assign(iter->second.begin(),iter->second.end()); return r; } Wrap(Timing) { return Timing(At(x,0)); } Wrap(Path) { return Size(x) ? Str(Path() + CStr(At(x,0))) : Str(Path()); } Wrap(Install) { return Install(CStr(At(x,0)).c_str()); } Wrap(Uninstall) { return Uninstall(At(x,0)) ? True : False; } Wrap(Run) { return Run(CStr(At(x,0))) ? True : False; } //Wrap(Task) //{ // return Task(At(x,0)); //} //Wrap(Kill) //{ // return Kill(At(x,0)) ? True : False; //} Wrap(NumberQ) { return NumQ(At(x,0)) ? True : False; } Wrap(AtomQ) { return AtomQ(At(x,0)) ? True : False; } Wrap(IntegerQ) { return IntQ(At(x,0)) ? True : False; } Wrap(SymbolQ) { return SymQ(At(x,0)) ? True : False; } Wrap(StringQ) { return StrQ(At(x,0)) ? True : False; } Wrap(Input) { var r = Size(x) > 0 ? Read(wcin,At(x,0)) : Read(wcin); return r ? r : Nil; } Wrap(Print) { Write(wcout,Size(x) == 1 ? static_cast<Var>(At(x,0)) : x); return Null; } Wrap(Pretty) { return Pretty(At(x,0)); } Wrap(Unset) { Unset(At(x,0)); return Null; } Wrap(Clear) { size_t n = Size(x); for(size_t i = 0; i < n; ++i) Clear(At(x,i)); return Null; } Wrap(Evaluate) { return Eval(At(x,0)); } Wrap(Part) { var c = At(x,0); size_t n = Size(x); for(size_t i = 1; i < n; ++i) { int j = Z::SI(At(x,i)); if(j == 0) return Tag(c); if(ExQ(c)) c = Body(c); if(VecQ(c)) { j < 0 ? j += Size(c) : --j; if(j < 0 || j >= Size(c)) return c; c = At(c,j); } } return c; } Wrap(Length) { var c = At(x,0); size_t n = 0; if(VecQ(c)) n = Size(c); else if(ExQ(c)) n = Size(Body(c)); return Int((uint)n); } Wrap(Head) { return Tag(At(x,0)); } Wrap(Context) { var r; if(Size(x)) r = Context(At(x,0)); else r = Context(); return Str(ContextName[r]); } Wrap(Contexts) { size_t n = CTab(Contexts).size(); var r = Vec(n); tab_t::rep_t::const_iterator iter = CTab(Contexts).begin(); for(size_t i = 0; i < n; ++i) { At(r,i) = Str(iter->first); ++iter; } return r; } Wrap(ContextPath) { size_t n = ContextPath.top().size(); var r = Vec(n); std::list<Var>::const_iterator iter = ContextPath.top().begin(); for(size_t i = 0; i < n; ++i) { At(r,i) = Str(ContextName[*iter]); ++iter; } return r; } Wrap(Begin) { var r = Ctx2(CStr(At(x,0)).c_str()); Begin(r); return Str(ContextName[r]); } Wrap(End) { var r = Context(); End(); return Str(ContextName[r]); } Wrap(BeginPackage) { var r = Ctx2(CStr(At(x,0)).c_str()); BeginPackage(r); return Null; } Wrap(EndPackage) { EndPackage(); return Null; } Wrap(Unevaluated) { return At(x,0); } Wrap(Apply) { if(VecQ(At(x,1))) return Eval(Ex(At(x,0),At(x,1))); return 0; } Wrap(Map) { if(VecQ(At(x,1))) { var a = At(x,0); var b = At(x,1); size_t n = Size(b); var r = Vec(n); for(size_t i = 0; i < n; ++i) At(r,i) = Eval(Ex(a,Vec(At(b,i)))); return r; } return 0; } Wrap(Property) { std::map<Var,map_t>::const_iterator iter = Properties.find(At(x,0)); if(iter != Properties.end()) { map_t::const_iterator iter2 = iter->second.find(At(x,1)); if(iter2 != iter->second.end()) return iter2->second; } return 0; } Wrap(Full) { wostringstream t; FullPrint(At(x,0),t); return Str(t.str()); } Wrap(ToString) { wostringstream t; Print(Pretty(At(x,0)),t); return Str(t.str()); } Wrap(ToExpression) { if(StrQ(At(x,0))) { var r = ParseString(CStr(At(x,0))); return r ? r : Nil; } return 0; } Wrap(Exit) { if(Size(x) && IntQ(At(x,0))) exit(Z::SI(At(x,0))); exit(-1); return Null; } Wrap(Quit) { exit(-1); return Null; } Wrap(Set) { Set(At(x,0),At(x,1)); return At(x,1); } Wrap(SetDelayed) { Set(At(x,0),At(x,1)); return Null; } Wrap(Hold) { return 0; } Wrap(Array) { size_t n = Size(x); var h = At(x,0); var b = Vec(); size_t m = Size(At(x,1)); if(n == 2) return Array(h,b,m,&At(At(x,1),0)); if(n == 3) return Array(h,b,m,&At(At(x,1),0),&At(At(x,2),0)); return 0; } Wrap(Table) { return Table(At(x,0),Size(x) - 1,&At(x,1)); } Wrap(Do) { Do(At(x,0),Size(x) - 1,&At(x,1)); return Null; } Wrap(N) { size_t n = Size(x); if(n == 1) return Evalf(At(x,0)); if(n == 2 && IntQ(At(x,1))) return Evalf(At(x,0),Z::UI(At(x,1))); return 0; } Wrap(IntegerPart) { return IntegerPart(At(x,0)); } Wrap(Floor) { return Floor(At(x,0)); } Wrap(Ceiling) { return Ceiling(At(x,0)); } Wrap(Round) { return Round(At(x,0)); } Wrap(Expand) { return Expand(At(x,0)); } Wrap(Variables) { return Variables(At(x,0)); } Wrap(Coefficient) { return Coefficient(At(x,0),At(x,1)); } Wrap(Exponent) { return Exponent(At(x,0),At(x,1)); } Wrap(Deg) { return Deg(At(x,0),At(x,1)); } Wrap(CoefficientList) { var c = At(x,1); if(VecQ(c)) return CoefficientList(At(x,0),c); return Coefficients(At(x,0),c); } Wrap(FromCoefficientList) { var c = At(x,1); if(VecQ(c)) return FromCoefficientList(At(x,0),c); return FromCoefficients(At(x,0),c); } Wrap(Power) { return Power(At(x,0),At(x,1)); } Wrap(Mod) { return Mod(At(x,0),At(x,1)); } Wrap(StringLength) { if(StrQ(At(x,0))) return Int(S::Length(At(x,0))); return 0; } Wrap(StringInsert) { var c = At(x,0); if(StrQ(c)) { uint n = S::Length(c); var r = Str(); CStr(r) = CStr(c); if(Size(x) > 2 && StrQ(At(x,1)) && IntQ(At(x,2))) { int a = Z::SI(At(x,2)); a < 0 ? a += n : --a; if(a < 0 || a >= n) return r; S::Insert(r,At(x,1),a); return r; } } return 0; } Wrap(StringTake) { var c = At(x,0); if(StrQ(c)) { uint n = S::Length(c); var d = At(x,1); if(VecQ(d)) { int a = Z::SI(At(d,0)); a < 0 ? a += n : --a; if(a < 0 || a >= n) return c; if(Size(d) > 1) { int b = Z::SI(At(d,1)); b < 0 ? b += n : --b; if(b < 0 || b >= n) return c; return S::Substr(c,a,b < a ? 0 : b - a + 1); } else return S::Substr(c,a,1); } else if(IntQ(d)) { int a = Z::SI(d); return a < 0 ? S::Substr(c,a + n,-a) : S::Substr(c,0,a); } } return 0; } Wrap(StringDrop) { var c = At(x,0); if(StrQ(c)) { uint n = S::Length(c); var r = Str(); CStr(r) = CStr(c); var d = At(x,1); if(VecQ(d)) { int a = Z::SI(At(d,0)); a < 0 ? a += n : --a; if(a < 0 || a >= n) return r; if(Size(d) > 1) { int b = Z::SI(At(d,1)); b < 0 ? b += n : --b; if(b < 0 || b >= n) return r; S::Erase(r,a,b < a ? 0 : b - a + 1); } else S::Erase(r,a,1); } else if(IntQ(d)) { int a = Z::SI(d); a < 0 ? S::Erase(r,a + n,-a) : S::Erase(r,0,a); } return r; } return 0; } Wrap2(Function) { var c = At(x,0); if(Size(x) == 1) return Eval(Supply(Ex(TAG(Function),c),c,y)); map_t m; if(VecQ(c)) { size_t n = Size(c); for(size_t i = 0; i < n; ++i) m[At(c,i)] = At(y,i); } else m[c] = At(y,0); return Eval(Subs(m,At(x,1))); } } //void(*Types[TYPE_SIZE])(Var); var Contexts; stdext::hash_map<Var,const wchar*> ContextName; std::stack<Var> ContextStack; std::stack<std::list<Var> > ContextPath; map_t OwnValues; std::map<Var,dict_t> FactValues; std::map<Var,def_t> DownValues; std::map<Var,def_t> SubValues; std::map<Var,map_t> Properties; std::map<Var,attr_t> Attributes; stdext::hash_map<Var,CProc> CProcs; stdext::hash_map<Var,COper> COpers; var Global, System, Null, True, False, Nil, Constant, Flat, HoldAll, HoldAllComplete, HoldFirst, HoldRest, Listable, Locked, NHoldAll, NHoldFirst, NHoldRest, NumericFunction, OneIdentity, Orderless, Protected, ReadProtected, SequenceHold, Stub, Temporary, TAG(Symbol), TAG(List), TAG(String), TAG(Integer), TAG(Rational), TAG(Real), TAG(Postfix), TAG(Prefix), TAG(Differential), TAG(Minus), TAG(Divide), TAG(Plus), TAG(Times), TAG(Power), TAG(Return), TAG(Continue), TAG(Break), TAG(Set), TAG(Rule), TAG(Pattern), TAG(Blank), TAG(Optional), TAG(Condition), TAG(PatternTest), TAG(Unevaluated), TAG(Derivative), TAG(Function), TAG(Slot), TAG(BlankSequence), TAG(SlotSequence), TAG(Part), TAG(Property), TAG(Sequence), TAG(Sqrt), TAG(Radical), TAG(RuleDelayed), TAG(SetDelayed), TAG(CompoundExpression), TAG(Integrate), TAG(D), TAG(Sum), TAG(Limit), TAG(Infinity), TAG(Pi), TAG(E), TAG(I), TAG(Mod), TAG(Dot), TAG(Pow), TAG(Timing), TAG(And), TAG(Or), TAG(Not), TAG(If), TAG(For), TAG(While), TAG(Flatten), TAG(FlattenAll), TAG(SameQ), TAG(Less), TAG(Equal), TAG(Greater), TAG(UnsameQ), TAG(GreaterEqual), TAG(Unequal), TAG(LessEqual), TAG(FreeQ), TAG(MatchQ), TAG(MemberQ), TAG(With), TAG(Block), TAG(Module), TAG(ReplaceRepeated), TAG(Replace), TAG(ReplaceAll), TAG(OddQ), TAG(EvenQ), TAG(SetAttributes), TAG(StringJoin), TAG(Join), TAG(Attributes), TAG(Get), TAG(Put), TAG(PutAppend), TAG(Install), TAG(Uninstall), TAG(NumberQ), TAG(AtomQ), TAG(IntegerQ), TAG(SymbolQ), TAG(StringQ), TAG(Pretty), TAG(Input), TAG(Print), TAG(Clear), TAG(BeginPackage), TAG(EndPackage), TAG(Begin), TAG(End), TAG(Evaluate), TAG(Dispatch), TAG(Length), TAG(Path), TAG(Head), TAG(Context), TAG(Contexts), TAG(ContextPath), TAG(Apply), TAG(Map), TAG(Unset), TAG(Full), TAG(ToString), TAG(ToExpression), TAG(Exit), TAG(Quit), TAG(Hold), TAG(Run), /*TAG(Task), TAG(Kill),*/ TAG(Array), TAG(Table), TAG(Do), TAG(Box), TAG(N), TAG(IntegerPart), TAG(Floor), TAG(Ceiling), TAG(Round), TAG(Expand), TAG(Variables), TAG(Coefficient), TAG(Exponent), TAG(Deg), TAG(CoefficientList), TAG(FromCoefficientList), TAG(Graphics2D), TAG(Graphics3D), TAG(Options), TAG(StringLength), TAG(StringInsert), TAG(StringTake), TAG(StringDrop); void Initialize() { static bool Initialized = false; if (Initialized) return; Contexts = Tab(); Global = Ctx(L"Global`"); System = Ctx(L"System`"); DEF_SYSTEM_SYM(Null) DEF_SYSTEM_SYM(True) DEF_SYSTEM_SYM(False) DEF_SYSTEM_SYM(Nil) DEF_SYSTEM_SYM(Constant) DEF_SYSTEM_SYM(Flat) DEF_SYSTEM_SYM(HoldAll) DEF_SYSTEM_SYM(HoldAllComplete) DEF_SYSTEM_SYM(HoldFirst) DEF_SYSTEM_SYM(HoldRest) DEF_SYSTEM_SYM(Listable) DEF_SYSTEM_SYM(Locked) DEF_SYSTEM_SYM(NHoldAll) DEF_SYSTEM_SYM(NHoldFirst) DEF_SYSTEM_SYM(NHoldRest) DEF_SYSTEM_SYM(NumericFunction) DEF_SYSTEM_SYM(OneIdentity) DEF_SYSTEM_SYM(Orderless) DEF_SYSTEM_SYM(Protected) DEF_SYSTEM_SYM(ReadProtected) DEF_SYSTEM_SYM(SequenceHold) DEF_SYSTEM_SYM(Stub) DEF_SYSTEM_SYM(Temporary) DEF_SYSTEM_TAG_SYM(Symbol) DEF_SYSTEM_TAG_SYM(List) DEF_SYSTEM_TAG_SYM(String) DEF_SYSTEM_TAG_SYM(Integer) DEF_SYSTEM_TAG_SYM(Rational) DEF_SYSTEM_TAG_SYM(Real) DEF_SYSTEM_TAG_SYM(Return) DEF_SYSTEM_TAG_SYM(Continue) DEF_SYSTEM_TAG_SYM(Break) DEF_SYSTEM_TAG_SYM(Set) DEF_SYSTEM_TAG_SYM(Rule) DEF_SYSTEM_TAG_SYM(Minus) DEF_SYSTEM_TAG_SYM(Divide) DEF_SYSTEM_TAG_SYM(Plus) DEF_SYSTEM_TAG_SYM(Times) DEF_SYSTEM_TAG_SYM(Power) DEF_SYSTEM_TAG_SYM(Integrate) DEF_SYSTEM_TAG_SYM(D) DEF_SYSTEM_TAG_SYM(Postfix) DEF_SYSTEM_TAG_SYM(Prefix) DEF_SYSTEM_TAG_SYM(Differential) DEF_SYSTEM_TAG_SYM(Pattern) DEF_SYSTEM_TAG_SYM(Blank) DEF_SYSTEM_TAG_SYM(Optional) DEF_SYSTEM_TAG_SYM(Condition) DEF_SYSTEM_TAG_SYM(PatternTest) DEF_SYSTEM_TAG_SYM(Unevaluated) DEF_SYSTEM_TAG_SYM(Derivative) DEF_SYSTEM_TAG_SYM(Function) DEF_SYSTEM_TAG_SYM(Slot) DEF_SYSTEM_TAG_SYM(BlankSequence) DEF_SYSTEM_TAG_SYM(SlotSequence) DEF_SYSTEM_TAG_SYM(Part) DEF_SYSTEM_TAG_SYM(Property) DEF_SYSTEM_TAG_SYM(Sequence) DEF_SYSTEM_TAG_SYM(RuleDelayed) DEF_SYSTEM_TAG_SYM(SetDelayed) DEF_SYSTEM_TAG_SYM(CompoundExpression) DEF_SYSTEM_TAG_SYM(Sum) DEF_SYSTEM_TAG_SYM(Limit) DEF_SYSTEM_TAG_SYM(Infinity) DEF_SYSTEM_TAG_SYM(Pi) DEF_SYSTEM_TAG_SYM(E) DEF_SYSTEM_TAG_SYM(I) DEF_SYSTEM_TAG_SYM(Sqrt) DEF_SYSTEM_TAG_SYM(Radical) DEF_SYSTEM_TAG_SYM(Mod) DEF_SYSTEM_TAG_SYM(Dot) DEF_SYSTEM_TAG_SYM(Pow) DEF_SYSTEM_TAG_SYM(Timing) DEF_SYSTEM_TAG_SYM(And) DEF_SYSTEM_TAG_SYM(Or) DEF_SYSTEM_TAG_SYM(Not) DEF_SYSTEM_TAG_SYM(If) DEF_SYSTEM_TAG_SYM(For) DEF_SYSTEM_TAG_SYM(While) DEF_SYSTEM_TAG_SYM(Flatten) DEF_SYSTEM_TAG_SYM(FlattenAll) DEF_SYSTEM_TAG_SYM(SameQ) DEF_SYSTEM_TAG_SYM(Less) DEF_SYSTEM_TAG_SYM(Equal) DEF_SYSTEM_TAG_SYM(Greater) DEF_SYSTEM_TAG_SYM(UnsameQ) DEF_SYSTEM_TAG_SYM(GreaterEqual) DEF_SYSTEM_TAG_SYM(Unequal) DEF_SYSTEM_TAG_SYM(LessEqual) DEF_SYSTEM_TAG_SYM(FreeQ) DEF_SYSTEM_TAG_SYM(MatchQ) DEF_SYSTEM_TAG_SYM(MemberQ) DEF_SYSTEM_TAG_SYM(With) DEF_SYSTEM_TAG_SYM(Block) DEF_SYSTEM_TAG_SYM(Module) DEF_SYSTEM_TAG_SYM(ReplaceRepeated) DEF_SYSTEM_TAG_SYM(Replace) DEF_SYSTEM_TAG_SYM(ReplaceAll) DEF_SYSTEM_TAG_SYM(OddQ) DEF_SYSTEM_TAG_SYM(EvenQ) DEF_SYSTEM_TAG_SYM(SetAttributes) DEF_SYSTEM_TAG_SYM(StringJoin) DEF_SYSTEM_TAG_SYM(Join) DEF_SYSTEM_TAG_SYM(Attributes) DEF_SYSTEM_TAG_SYM(Get) DEF_SYSTEM_TAG_SYM(Put) DEF_SYSTEM_TAG_SYM(PutAppend) DEF_SYSTEM_TAG_SYM(Install) DEF_SYSTEM_TAG_SYM(Uninstall) DEF_SYSTEM_TAG_SYM(NumberQ) DEF_SYSTEM_TAG_SYM(AtomQ) DEF_SYSTEM_TAG_SYM(IntegerQ) DEF_SYSTEM_TAG_SYM(SymbolQ) DEF_SYSTEM_TAG_SYM(StringQ) DEF_SYSTEM_TAG_SYM(Pretty) DEF_SYSTEM_TAG_SYM(Input) DEF_SYSTEM_TAG_SYM(Print) DEF_SYSTEM_TAG_SYM(Clear) DEF_SYSTEM_TAG_SYM(BeginPackage) DEF_SYSTEM_TAG_SYM(EndPackage) DEF_SYSTEM_TAG_SYM(Begin) DEF_SYSTEM_TAG_SYM(End) DEF_SYSTEM_TAG_SYM(Evaluate) DEF_SYSTEM_TAG_SYM(Dispatch) DEF_SYSTEM_TAG_SYM(Length) DEF_SYSTEM_TAG_SYM(Path) DEF_SYSTEM_TAG_SYM(Head) DEF_SYSTEM_TAG_SYM(Context) DEF_SYSTEM_TAG_SYM(Contexts) DEF_SYSTEM_TAG_SYM(ContextPath) DEF_SYSTEM_TAG_SYM(Apply) DEF_SYSTEM_TAG_SYM(Map) DEF_SYSTEM_TAG_SYM(Unset) DEF_SYSTEM_TAG_SYM(Full) DEF_SYSTEM_TAG_SYM(ToString) DEF_SYSTEM_TAG_SYM(ToExpression) DEF_SYSTEM_TAG_SYM(Exit) DEF_SYSTEM_TAG_SYM(Quit) DEF_SYSTEM_TAG_SYM(Hold) DEF_SYSTEM_TAG_SYM(Run) //DEF_SYSTEM_TAG_SYM(Task) //DEF_SYSTEM_TAG_SYM(Kill) DEF_SYSTEM_TAG_SYM(Array) DEF_SYSTEM_TAG_SYM(Table) DEF_SYSTEM_TAG_SYM(Do) DEF_SYSTEM_TAG_SYM(Box) DEF_SYSTEM_TAG_SYM(N) DEF_SYSTEM_TAG_SYM(IntegerPart) DEF_SYSTEM_TAG_SYM(Floor) DEF_SYSTEM_TAG_SYM(Ceiling) DEF_SYSTEM_TAG_SYM(Round) DEF_SYSTEM_TAG_SYM(Expand) DEF_SYSTEM_TAG_SYM(Variables) DEF_SYSTEM_TAG_SYM(Coefficient) DEF_SYSTEM_TAG_SYM(Exponent) DEF_SYSTEM_TAG_SYM(Deg) DEF_SYSTEM_TAG_SYM(CoefficientList) DEF_SYSTEM_TAG_SYM(FromCoefficientList) DEF_SYSTEM_TAG_SYM(Graphics2D) DEF_SYSTEM_TAG_SYM(Graphics3D) DEF_SYSTEM_TAG_SYM(Options) DEF_SYSTEM_TAG_SYM(StringLength) DEF_SYSTEM_TAG_SYM(StringInsert) DEF_SYSTEM_TAG_SYM(StringTake) DEF_SYSTEM_TAG_SYM(StringDrop) DEF_CPROC(Plus) DEF_CPROC(Times) DEF_CPROC(Dot) DEF_WRAPPED_CPROC(Timing) DEF_WRAPPED_CPROC(And) DEF_WRAPPED_CPROC(Or) DEF_WRAPPED_CPROC(Not) DEF_WRAPPED_CPROC(If) DEF_WRAPPED_CPROC(For) DEF_WRAPPED_CPROC(While) DEF_WRAPPED_CPROC(Flatten) DEF_WRAPPED_CPROC(FlattenAll) DEF_WRAPPED_CPROC(SameQ) DEF_WRAPPED_CPROC(Less) DEF_WRAPPED_CPROC(Equal) DEF_WRAPPED_CPROC(Greater) DEF_WRAPPED_CPROC(UnsameQ) DEF_WRAPPED_CPROC(GreaterEqual) DEF_WRAPPED_CPROC(Unequal) DEF_WRAPPED_CPROC(LessEqual) DEF_WRAPPED_CPROC(FreeQ) DEF_WRAPPED_CPROC(MatchQ) DEF_WRAPPED_CPROC(MemberQ) DEF_WRAPPED_CPROC(With) DEF_WRAPPED_CPROC(Block) DEF_WRAPPED_CPROC(Module) DEF_WRAPPED_CPROC(ReplaceRepeated) DEF_WRAPPED_CPROC(Replace) DEF_WRAPPED_CPROC(ReplaceAll) DEF_WRAPPED_CPROC(OddQ) DEF_WRAPPED_CPROC(EvenQ) DEF_WRAPPED_CPROC(SetAttributes) DEF_WRAPPED_CPROC(StringJoin) DEF_WRAPPED_CPROC(Join) DEF_WRAPPED_CPROC(Attributes) DEF_WRAPPED_CPROC(Get) DEF_WRAPPED_CPROC(Put) DEF_WRAPPED_CPROC(PutAppend) DEF_WRAPPED_CPROC(Install) DEF_WRAPPED_CPROC(Uninstall) DEF_WRAPPED_CPROC(NumberQ) DEF_WRAPPED_CPROC(AtomQ) DEF_WRAPPED_CPROC(IntegerQ) DEF_WRAPPED_CPROC(SymbolQ) DEF_WRAPPED_CPROC(StringQ) DEF_WRAPPED_CPROC(Pretty) DEF_WRAPPED_CPROC(Input) DEF_WRAPPED_CPROC(Print) DEF_WRAPPED_CPROC(Clear) DEF_WRAPPED_CPROC(BeginPackage) DEF_WRAPPED_CPROC(EndPackage) DEF_WRAPPED_CPROC(Begin) DEF_WRAPPED_CPROC(End) DEF_WRAPPED_CPROC(Evaluate) DEF_WRAPPED_CPROC(Unevaluated) DEF_WRAPPED_CPROC(Dispatch) DEF_WRAPPED_CPROC(Length) DEF_WRAPPED_CPROC(Path) DEF_WRAPPED_CPROC(Head) DEF_WRAPPED_CPROC(Context) DEF_WRAPPED_CPROC(Contexts) DEF_WRAPPED_CPROC(ContextPath) DEF_WRAPPED_CPROC(Apply) DEF_WRAPPED_CPROC(Map) DEF_WRAPPED_CPROC(Unset) DEF_WRAPPED_CPROC(Full) DEF_WRAPPED_CPROC(ToString) DEF_WRAPPED_CPROC(ToExpression) DEF_WRAPPED_CPROC(Exit) DEF_WRAPPED_CPROC(Quit) DEF_WRAPPED_CPROC(Set) DEF_WRAPPED_CPROC(SetDelayed) DEF_WRAPPED_CPROC(Hold) DEF_WRAPPED_CPROC(Run) //DEF_WRAPPED_CPROC(Task) //DEF_WRAPPED_CPROC(Kill) DEF_WRAPPED_CPROC(Array) DEF_WRAPPED_CPROC(Table) DEF_WRAPPED_CPROC(Do) DEF_WRAPPED_CPROC(N) DEF_WRAPPED_CPROC(IntegerPart) DEF_WRAPPED_CPROC(Floor) DEF_WRAPPED_CPROC(Ceiling) DEF_WRAPPED_CPROC(Round) DEF_WRAPPED_CPROC(Expand) DEF_WRAPPED_CPROC(Variables) DEF_WRAPPED_CPROC(Coefficient) DEF_WRAPPED_CPROC(Exponent) DEF_WRAPPED_CPROC(Deg) DEF_WRAPPED_CPROC(CoefficientList) DEF_WRAPPED_CPROC(FromCoefficientList) DEF_WRAPPED_CPROC(StringLength) DEF_WRAPPED_CPROC(Set) DEF_WRAPPED_CPROC(Part) DEF_WRAPPED_CPROC(Property) DEF_WRAPPED_CPROC(SetDelayed) DEF_WRAPPED_CPROC(CompoundExpression) DEF_WRAPPED_CPROC(Power) DEF_WRAPPED_CPROC(Mod) DEF_WRAPPED_COPER(Function) SET_ATTR(CompoundExpression,HoldAll) SET_ATTR(Timing,HoldAll) SET_ATTR(For,HoldAll) SET_ATTR(While,HoldAll) SET_ATTR(Plus,OneIdentity) SET_ATTR(Plus,Flat) SET_ATTR(Plus,Orderless) SET_ATTR(Plus,Listable) SET_ATTR(Times,OneIdentity) SET_ATTR(Times,Flat) SET_ATTR(Times,Orderless) SET_ATTR(Times,Listable) SET_ATTR(Power,OneIdentity) SET_ATTR(Power,Listable) SET_ATTR(Pi,Constant) SET_ATTR(E,Constant) SET_ATTR(Set,HoldFirst) SET_ATTR(SetDelayed,HoldAll) SET_ATTR(Hold,HoldAll) SET_ATTR(And,OneIdentity) SET_ATTR(And,Flat) SET_ATTR(And,HoldAll) SET_ATTR(Or,OneIdentity) SET_ATTR(Or,Flat) SET_ATTR(Or,HoldAll) SET_ATTR(If,HoldRest) SET_ATTR(Pattern,HoldFirst) SET_ATTR(Condition,HoldAll) SET_ATTR(PatternTest,HoldRest) SET_ATTR(With,HoldAll) SET_ATTR(Block,HoldAll) SET_ATTR(Module,HoldAll) SET_ATTR(SetAttributes,HoldFirst) SET_ATTR(StringJoin,Flat) SET_ATTR(StringJoin,OneIdentity) SET_ATTR(Join,Flat) SET_ATTR(Join,OneIdentity) SET_ATTR(Attributes,HoldAll) SET_ATTR(Clear,HoldAll) SET_ATTR(Unevaluated,HoldAll) SET_ATTR(Function,HoldAll) SET_ATTR(Context,HoldFirst) SET_ATTR(Property,HoldAll) SET_ATTR(RuleDelayed,HoldRest) SET_ATTR(Unset,HoldFirst) //SET_ATTR(Task,HoldAll) SET_ATTR(Table,HoldAll) SET_ATTR(Do,HoldAll) ContextPath.push(std::list<Var>()); ContextPath.top().push_back(System); ContextPath.top().push_back(Global); ContextStack.push(Global); Initialized = true; } } DLLMAIN(mU::Initialize) using namespace mU; #define SYS(x) Sym(_W(#x),System) CAPI void Install() { CProcs[SYS(CProc)] = (CProc)cfunc(cnoload("kernel"), SYS(CProc)); Begin(System); ParseFile(Path() + _W("Kernel/Kernel.u")); End(); } CAPI void Uninstall() { wcout << "#Kernel# Uninstall Successfully!" << std::endl; }
[ [ [ 1, 423 ], [ 432, 852 ], [ 854, 872 ], [ 881, 881 ], [ 906, 908 ], [ 910, 913 ], [ 1234, 1252 ] ], [ [ 424, 431 ], [ 853, 853 ], [ 873, 880 ], [ 882, 905 ], [ 909, 909 ], [ 914, 1233 ], [ 1253, 1253 ] ] ]
67042873d6f1b0eadc8badd38240aab8bf5c2c37
15730792376cc6ffa986d6bcb88ba9fd7acf9369
/raytracer3.0.06.no_rec.samp/surface.cpp
7362e28ce76a3feec514e4a6e0f7d61e8f333486
[]
no_license
markrosoft/se-195-project-ray-tracer
0b8c14422e52aa5ede17a158c6ef7521934ce029
0712d443be8c0da986ab1315a257740fbb3a653d
refs/heads/master
2021-01-10T07:14:00.513175
2011-11-18T06:42:15
2011-11-18T06:42:15
43,331,160
0
0
null
null
null
null
UTF-8
C++
false
false
5,375
cpp
#define _CRT_SECURE_NO_WARNINGS 1 #include "common.h" #include "surface.h" #include "stdio.h" #include "string.h" // ----------------------------------------------------------- // Hicolor surface class implementation // ----------------------------------------------------------- Surface * Surface_Create( int a_Width, int a_Height ) { Surface *s = (Surface *)malloc(sizeof(Surface)); s->m_Width = a_Width; s->m_Height = a_Height; s->m_Buffer = (Pixel *)malloc(a_Width*a_Height*sizeof(Pixel)); return s; } void Surface_Clear( Surface * s, Pixel a_Color ) { int z = s->m_Width * s->m_Height; for ( int i = 0; i < z; i++ ) s->m_Buffer[i] = a_Color; } void Surface_Print( Surface * s, char* a_String, int x1, int y1, Pixel color ) { Pixel* t = s->m_Buffer + x1 + y1 * s->m_Width; int i; for ( i = 0; i < (int)(strlen( a_String )); i++ ) { long pos = 0; if ((a_String[i] >= 'A') && (a_String[i] <= 'Z')) pos = s->s_Transl[a_String[i] - ('A' - 'a')]; else pos = s->s_Transl[a_String[i]]; Pixel* a = t; char* c = (char*)s->s_Font[pos]; int h, v; for ( v = 0; v < 5; v++ ) { for ( h = 0; h < 5; h++ ) if (*c++ == 'o') *(a + h) = color; a += s->m_Width; } t += 6; } } void Surface_SetChar( Surface * s, int c, char* c1, char* c2, char* c3, char* c4, char* c5 ) { strcpy( s->s_Font[c][0], c1 ); strcpy( s->s_Font[c][1], c2 ); strcpy( s->s_Font[c][2], c3 ); strcpy( s->s_Font[c][3], c4 ); strcpy( s->s_Font[c][4], c5 ); } void Surface_InitCharset(Surface * s) { Surface_SetChar(s, 0, ":ooo:", "o:::o", "ooooo", "o:::o", "o:::o" ); Surface_SetChar(s, 1, "oooo:", "o:::o", "oooo:", "o:::o", "oooo:" ); Surface_SetChar(s, 2, ":oooo", "o::::", "o::::", "o::::", ":oooo" ); Surface_SetChar(s, 3, "oooo:", "o:::o", "o:::o", "o:::o", "oooo:" ); Surface_SetChar(s, 4, "ooooo", "o::::", "oooo:", "o::::", "ooooo" ); Surface_SetChar(s, 5, "ooooo", "o::::", "ooo::", "o::::", "o::::" ); Surface_SetChar(s, 6, ":oooo", "o::::", "o:ooo", "o:::o", ":ooo:" ); Surface_SetChar(s, 7, "o:::o", "o:::o", "ooooo", "o:::o", "o:::o" ); Surface_SetChar(s, 8, "::o::", "::o::", "::o::", "::o::", "::o::" ); Surface_SetChar(s, 9, ":::o:", ":::o:", ":::o:", ":::o:", "ooo::" ); Surface_SetChar(s, 10, "o::o:", "o:o::", "oo:::", "o:o::", "o::o:" ); Surface_SetChar(s, 11, "o::::", "o::::", "o::::", "o::::", "ooooo" ); Surface_SetChar(s, 12, "oo:o:", "o:o:o", "o:o:o", "o:::o", "o:::o" ); Surface_SetChar(s, 13, "o:::o", "oo::o", "o:o:o", "o::oo", "o:::o" ); Surface_SetChar(s, 14, ":ooo:", "o:::o", "o:::o", "o:::o", ":ooo:" ); Surface_SetChar(s, 15, "oooo:", "o:::o", "oooo:", "o::::", "o::::" ); Surface_SetChar(s, 16, ":ooo:", "o:::o", "o:::o", "o::oo", ":oooo" ); Surface_SetChar(s, 17, "oooo:", "o:::o", "oooo:", "o:o::", "o::o:" ); Surface_SetChar(s, 18, ":oooo", "o::::", ":ooo:", "::::o", "oooo:" ); Surface_SetChar(s, 19, "ooooo", "::o::", "::o::", "::o::", "::o::" ); Surface_SetChar(s, 20, "o:::o", "o:::o", "o:::o", "o:::o", ":oooo" ); Surface_SetChar(s, 21, "o:::o", "o:::o", ":o:o:", ":o:o:", "::o::" ); Surface_SetChar(s, 22, "o:::o", "o:::o", "o:o:o", "o:o:o", ":o:o:" ); Surface_SetChar(s, 23, "o:::o", ":o:o:", "::o::", ":o:o:", "o:::o" ); Surface_SetChar(s, 24, "o:::o", "o:::o", ":oooo", "::::o", ":ooo:" ); Surface_SetChar(s, 25, "ooooo", ":::o:", "::o::", ":o:::", "ooooo" ); Surface_SetChar(s, 26, ":ooo:", "o::oo", "o:o:o", "oo::o", ":ooo:" ); Surface_SetChar(s, 27, "::o::", ":oo::", "::o::", "::o::", ":ooo:" ); Surface_SetChar(s, 28, ":ooo:", "o:::o", "::oo:", ":o:::", "ooooo" ); Surface_SetChar(s, 29, "oooo:", "::::o", "::oo:", "::::o", "oooo:" ); Surface_SetChar(s, 30, "o::::", "o::o:", "ooooo", ":::o:", ":::o:" ); Surface_SetChar(s, 31, "ooooo", "o::::", "oooo:", "::::o", "oooo:" ); Surface_SetChar(s, 32, ":oooo", "o::::", "oooo:", "o:::o", ":ooo:" ); Surface_SetChar(s, 33, "ooooo", "::::o", ":::o:", "::o::", "::o::" ); Surface_SetChar(s, 34, ":ooo:", "o:::o", ":ooo:", "o:::o", ":ooo:" ); Surface_SetChar(s, 35, ":ooo:", "o:::o", ":oooo", "::::o", ":ooo:" ); Surface_SetChar(s, 36, "::o::", "::o::", "::o::", ":::::", "::o::" ); Surface_SetChar(s, 37, ":ooo:", "::::o", ":::o:", ":::::", "::o::" ); Surface_SetChar(s, 38, ":::::", ":::::", "::o::", ":::::", "::o::" ); Surface_SetChar(s, 39, ":::::", ":::::", ":ooo:", ":::::", ":ooo:" ); Surface_SetChar(s, 40, ":::::", ":::::", ":::::", ":::o:", "::o::" ); Surface_SetChar(s, 41, ":::::", ":::::", ":::::", ":::::", "::o::" ); Surface_SetChar(s, 42, ":::::", ":::::", ":ooo:", ":::::", ":::::" ); Surface_SetChar(s, 43, ":::o:", "::o::", "::o::", "::o::", ":::o:" ); Surface_SetChar(s, 44, "::o::", ":::o:", ":::o:", ":::o:", "::o::" ); Surface_SetChar(s, 45, ":::::", ":::::", ":::::", ":::::", ":::::" ); Surface_SetChar(s, 46, "ooooo", "ooooo", "ooooo", "ooooo", "ooooo" ); Surface_SetChar(s, 47, "::o::", "::o::", ":::::", ":::::", ":::::" ); // Tnx Ferry Surface_SetChar(s, 48, "o:o:o", ":ooo:", "ooooo", ":ooo:", "o:o:o" ); Surface_SetChar(s, 49, "::::o", ":::o:", "::o::", ":o:::", "o::::" ); char c[] = "abcdefghijklmnopqrstuvwxyz0123456789!?:=,.-() #'*/"; int i; for ( i = 0; i < 256; i++ ) s->s_Transl[i] = 45; for ( i = 0; i < 50; i++ ) s->s_Transl[(unsigned char)c[i]] = i; }
[ [ [ 1, 114 ] ] ]
7dfc4fc2fb7135fc29ba0a38497fc82a49f33dfc
61bcb936a14064e2a819269d25b5c09b92dad45f
/Winter2011/Final Project/Final Project.cpp
7e339f27144ee977d238016556811b1872891b51
[]
no_license
lanxinwoaini/robotic-vision-631
47fe73588a5b51296b9ac7fbacd4a553e4fd8e34
fdb160a8498ec668a32116c655368d068110aba7
refs/heads/master
2021-01-10T08:06:58.829618
2011-04-20T15:19:06
2011-04-20T15:19:06
47,861,917
1
0
null
null
null
null
UTF-8
C++
false
false
2,190
cpp
// Final Project.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "Final Project.h" #include "Final ProjectDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CFinalProjectApp BEGIN_MESSAGE_MAP(CFinalProjectApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CFinalProjectApp construction CFinalProjectApp::CFinalProjectApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CFinalProjectApp object CFinalProjectApp theApp; // CFinalProjectApp initialization BOOL CFinalProjectApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); CFinalProjectDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. cvDestroyAllWindows(); return FALSE; }
[ [ [ 1, 79 ] ] ]
9256a879e20b030093ba858690888f71d52c0ace
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-10-27/eeschema/libfield.cpp
629a6deda044d22e5a9b8d1d035b9f820fba6f59
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
UTF-8
C++
false
false
10,674
cpp
/*********************************************************************/ /* EESchema - edition des librairies: Edition des champs ( Fields ) */ /*********************************************************************/ /* Fichier libfield.cpp */ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "program.h" #include "libcmp.h" #include "general.h" #include "protos.h" #include "wx/spinctrl.h" /* Routines locales */ static void ShowMoveField(WinEDA_DrawPanel * panel, wxDC *DC, bool erase); /* Variables locales */ extern int CurrentUnit; static wxPoint StartCursor, LastTextPosition; /***********************************************************/ static void ExitMoveField(WinEDA_DrawFrame * frame, wxDC * DC) /***********************************************************/ { frame->m_CurrentScreen->ManageCurseur = NULL; frame->m_CurrentScreen->ForceCloseManageCurseur = NULL; if(CurrentDrawItem == NULL) return; wxPoint curpos; curpos = frame->m_CurrentScreen->m_Curseur; frame->m_CurrentScreen->m_Curseur = StartCursor; ShowMoveField(frame->DrawPanel, DC, TRUE); frame->m_CurrentScreen->m_Curseur = curpos; CurrentDrawItem->m_Flags = 0; CurrentDrawItem = NULL; } /****************************************************************************/ void WinEDA_LibeditFrame::StartMoveField(wxDC * DC, LibDrawField *field) /****************************************************************************/ /* Initialise le deplacement d'un champ ( ref ou Name) */ { if( (CurrentLibEntry == NULL) || ( field == NULL ) ) return; CurrentDrawItem = field; LastTextPosition = field->m_Pos; CurrentDrawItem->m_Flags |= IS_MOVED; m_CurrentScreen->ManageCurseur = ShowMoveField; m_CurrentScreen->ForceCloseManageCurseur = ExitMoveField; m_CurrentScreen->ManageCurseur(DrawPanel, DC, TRUE); StartCursor = m_CurrentScreen->m_Curseur; } /*****************************************************************/ /* Routine d'affichage du texte 'Field' en cours de deplacement. */ /* Routine normalement attachee au curseur */ /*****************************************************************/ static void ShowMoveField(WinEDA_DrawPanel * panel, wxDC *DC, bool erase) { int color; LibDrawField *Field = (LibDrawField *)CurrentDrawItem; if( (CurrentLibEntry == NULL) || (Field == NULL) ) return; GRSetDrawMode(DC, XOR_MODE); switch (Field->m_FieldId) { case VALUE: color = ReturnLayerColor(LAYER_VALUEPART); break; case REFERENCE: color = ReturnLayerColor(LAYER_REFERENCEPART); break; default: color = ReturnLayerColor(LAYER_FIELDS); break; } if( Field->m_Attributs & TEXT_NO_VISIBLE ) color = DARKGRAY; if( erase ) DrawGraphicText(panel, DC, wxPoint(LastTextPosition.x, - LastTextPosition.y), color, Field->m_Text, Field->m_Orient ? TEXT_ORIENT_VERT : TEXT_ORIENT_HORIZ, Field->m_Size, Field->m_HJustify, Field->m_VJustify); LastTextPosition.x = panel->GetScreen()->m_Curseur.x; LastTextPosition.y = - panel->GetScreen()->m_Curseur.y; if ( (Field->m_Flags & IS_NEW) ) Field->m_Pos = LastTextPosition; DrawGraphicText(panel, DC, wxPoint(LastTextPosition.x, - LastTextPosition.y), color, Field->m_Text, Field->m_Orient ? TEXT_ORIENT_VERT : TEXT_ORIENT_HORIZ, Field->m_Size, Field->m_HJustify, Field->m_VJustify); } /*******************************************************************/ void WinEDA_LibeditFrame::PlaceField(wxDC * DC, LibDrawField *Field) /*******************************************************************/ { int color; if(Field == NULL ) return; GRSetDrawMode(DC, GR_DEFAULT_DRAWMODE); switch (Field->m_FieldId) { case REFERENCE: color = ReturnLayerColor(LAYER_REFERENCEPART); break; case VALUE: color = ReturnLayerColor(LAYER_VALUEPART); break; default: color = ReturnLayerColor(LAYER_FIELDS); break; } if( Field->m_Attributs & TEXT_NO_VISIBLE ) color = DARKGRAY; Field->m_Pos.x = GetScreen()->m_Curseur.x; Field->m_Pos.y = - GetScreen()->m_Curseur.y; DrawGraphicText(DrawPanel, DC, wxPoint(Field->m_Pos.x, - Field->m_Pos.y), color, Field->m_Text, Field->m_Orient ? TEXT_ORIENT_VERT : TEXT_ORIENT_HORIZ, Field->m_Size, Field->m_HJustify, Field->m_VJustify); Field->m_Flags = 0; m_CurrentScreen->SetModify(); m_CurrentScreen->ManageCurseur = NULL; m_CurrentScreen->ForceCloseManageCurseur = NULL; CurrentDrawItem = NULL; } /******************************************************************/ void WinEDA_LibeditFrame::EditField(wxDC * DC, LibDrawField *Field) /******************************************************************/ { wxString Text; int color; char * title = "Text:"; if( Field == NULL) return; switch (Field->m_FieldId) { case REFERENCE: title ="Reference:"; color = ReturnLayerColor(LAYER_REFERENCEPART); break; case VALUE: title ="Value:"; color = ReturnLayerColor(LAYER_VALUEPART); break; default: color = ReturnLayerColor(LAYER_FIELDS); break; } if( Field->m_Attributs & TEXT_NO_VISIBLE ) color = DARKGRAY; Text = Field->m_Text; Get_Message(title,Text, this); Text.Replace(" ", "_"); GRSetDrawMode(DC, XOR_MODE); DrawGraphicText(DrawPanel, DC, wxPoint(Field->m_Pos.x, - Field->m_Pos.y), color, Field->m_Text, Field->m_Orient ? TEXT_ORIENT_VERT : TEXT_ORIENT_HORIZ, Field->m_Size, Field->m_HJustify, Field->m_VJustify); if( ! Text .IsEmpty() ) { SaveCopyInUndoList(); Field->m_Text = Text; } else DisplayError(this, _("No new text: no change") ); if( Field->m_Flags == 0 ) GRSetDrawMode(DC, GR_DEFAULT_DRAWMODE); DrawGraphicText(DrawPanel, DC, wxPoint(Field->m_Pos.x, - Field->m_Pos.y), color, Field->m_Text, Field->m_Orient ? TEXT_ORIENT_VERT : TEXT_ORIENT_HORIZ, Field->m_Size, Field->m_HJustify, Field->m_VJustify); m_CurrentScreen->SetModify(); if ( Field->m_FieldId == VALUE ) ReCreateHToolbar(); } /********************************************************************/ void WinEDA_LibeditFrame::RotateField(wxDC * DC, LibDrawField *Field) /********************************************************************/ /* Routine de modification de l'orientation ( Horiz ou Vert. ) du champ. si un champ est en cours d'edition, modif de celui ci. sinon Modif du champ pointe par la souris */ { int color; if( Field == NULL) return; m_CurrentScreen->SetModify(); switch (Field->m_FieldId) { case REFERENCE: color = ReturnLayerColor(LAYER_REFERENCEPART); break; case VALUE: color = ReturnLayerColor(LAYER_VALUEPART); break; default: color = ReturnLayerColor(LAYER_FIELDS); break; } if( Field->m_Attributs & TEXT_NO_VISIBLE ) color = DARKGRAY; GRSetDrawMode(DC, XOR_MODE); DrawGraphicText(DrawPanel, DC, wxPoint(Field->m_Pos.x, - Field->m_Pos.y), color, Field->m_Text, Field->m_Orient ? TEXT_ORIENT_VERT : TEXT_ORIENT_HORIZ, Field->m_Size, Field->m_HJustify, Field->m_VJustify); if( Field->m_Orient) Field->m_Orient = 0; else Field->m_Orient = 1; if( Field->m_Flags == 0 ) GRSetDrawMode(DC, GR_DEFAULT_DRAWMODE); DrawGraphicText(DrawPanel, DC, wxPoint(Field->m_Pos.x, - Field->m_Pos.y), color, Field->m_Text, Field->m_Orient ? TEXT_ORIENT_VERT : TEXT_ORIENT_HORIZ, Field->m_Size, Field->m_HJustify, Field->m_VJustify); } /****************************************************************************/ LibDrawField * WinEDA_LibeditFrame::LocateField(EDA_LibComponentStruct *LibEntry) /****************************************************************************/ /* Localise le champ (ref ou name) pointe par la souris retourne: pointeur sur le champ (NULL= Pas de champ) */ { int x0, y0, x1, y1; /* Rectangle d'encadrement des textes a localiser */ int dx, dy; /* Dimensions du texte */ LibDrawField *Field; int hjustify, vjustify; /* Localisation du Nom */ x0 = LibEntry->m_Name.m_Pos.x; y0 = - LibEntry->m_Name.m_Pos.y; dx = LibEntry->m_Name.m_Size.x * strlen(LibEntry->m_Name.m_Text), dy = LibEntry->m_Name.m_Size.y; hjustify = LibEntry->m_Name.m_HJustify; vjustify = LibEntry->m_Name.m_VJustify; if (LibEntry->m_Name.m_Orient) EXCHG(dx, dy); if ( hjustify == GR_TEXT_HJUSTIFY_CENTER ) x0 -= dx/2; else if ( hjustify == GR_TEXT_HJUSTIFY_RIGHT ) x0 -= dx; if ( vjustify == GR_TEXT_VJUSTIFY_CENTER ) y0 -= dy/2; else if ( vjustify == GR_TEXT_VJUSTIFY_BOTTOM ) y0 += dy; x1 = x0 + dx; y1 = y0 + dy; if( (m_CurrentScreen->m_Curseur.x >= x0) && ( m_CurrentScreen->m_Curseur.x <= x1) && (m_CurrentScreen->m_Curseur.y >= y0) && ( m_CurrentScreen->m_Curseur.y <= y1) ) return &LibEntry->m_Name; /* Localisation du Prefix */ x0 = LibEntry->m_Prefix.m_Pos.x; y0 = - LibEntry->m_Prefix.m_Pos.y; dx = LibEntry->m_Prefix.m_Size.x * strlen(LibEntry->m_Prefix.m_Text), dy = LibEntry->m_Prefix.m_Size.y; hjustify = LibEntry->m_Prefix.m_HJustify; vjustify = LibEntry->m_Prefix.m_VJustify; if (LibEntry->m_Prefix.m_Orient) EXCHG(dx, dy); if ( hjustify == GR_TEXT_HJUSTIFY_CENTER ) x0 -= dx/2; else if ( hjustify == GR_TEXT_HJUSTIFY_RIGHT ) x0 -= dx; if ( vjustify == GR_TEXT_VJUSTIFY_CENTER ) y0 -= dy/2; else if ( vjustify == GR_TEXT_VJUSTIFY_BOTTOM ) y0 -= dy; x1 = x0 + dx; y1 = y0 + dy; if( (m_CurrentScreen->m_Curseur.x >= x0) && ( m_CurrentScreen->m_Curseur.x <= x1) && (m_CurrentScreen->m_Curseur.y >= y0) && ( m_CurrentScreen->m_Curseur.y <= y1) ) return &LibEntry->m_Prefix; /* Localisation des autres fields */ for (Field = LibEntry->Fields; Field != NULL; Field = (LibDrawField*)Field->Pnext) { if ( Field->m_Text == "") continue; x0 = Field->m_Pos.x; y0 = - Field->m_Pos.y; dx = Field->m_Size.x * strlen(Field->m_Text), dy = Field->m_Size.y; hjustify = Field->m_HJustify; vjustify = Field->m_VJustify; if (Field->m_Orient) EXCHG(dx, dy); if (LibEntry->m_Prefix.m_Orient) EXCHG(dx, dy); if ( hjustify == GR_TEXT_HJUSTIFY_CENTER ) x0 -= dx/2; else if ( hjustify == GR_TEXT_HJUSTIFY_RIGHT ) x0 -= dx; if ( vjustify == GR_TEXT_VJUSTIFY_CENTER ) y0 -= dy/2; else if ( vjustify == GR_TEXT_VJUSTIFY_BOTTOM ) y0 -= dy; x1 = x0 + dx; y1 = y0 + dy; if( (m_CurrentScreen->m_Curseur.x >= x0) && ( m_CurrentScreen->m_Curseur.x <= x1) && (m_CurrentScreen->m_Curseur.y >= y0) && ( m_CurrentScreen->m_Curseur.y <= y1) ) return(Field); } return NULL; }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 339 ] ] ]
44ab621450525a72ef6562ed96b69e60917a4940
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/samples/list_includes/list_includes_version.hpp
303bc911f440795459e2386c12b66eb0a5eb511a
[ "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
965
hpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library Sample: List include dependencies of a given source file version number http://www.boost.org/ Copyright (c) 2001-2007 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(LIST_INCLUDES_VERSION_HPP_FF662D6C_C3E6_4BEC_A062_5D9BD7415EBF_INCLUDED) #define LIST_INCLUDES_VERSION_HPP_FF662D6C_C3E6_4BEC_A062_5D9BD7415EBF_INCLUDED #define LIST_INCLUDES_VERSION_MAJOR 0 #define LIST_INCLUDES_VERSION_MINOR 3 #define LIST_INCLUDES_VERSION_SUBMINOR 0 #endif // !defined(LIST_INCLUDES_VERSION_HPP_FF662D6C_C3E6_4BEC_A062_5D9BD7415EBF_INCLUDED)
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 20 ] ] ]
4ab64db77dda1872d9816b72d9061c4f4a5db666
406b4b18f5c58c689d2324f49db972377fe8feb6
/ANE/Include/StlCustomize/ane_string.h
6ef03e1eac041755ce72cf67cf5d82fcf0ebea34
[]
no_license
Mobiwoom/ane
e17167de36699c451ed92eab7bf733e7d41fe847
ec20667c556a99351024f3ae9c8880e944c5bfbd
refs/heads/master
2021-01-17T13:09:57.966141
2010-03-23T16:30:17
2010-03-23T16:30:17
33,132,357
0
1
null
null
null
null
UTF-8
C++
false
false
354
h
#pragma once #include <xstring> namespace Ane { typedef std::basic_string<char, std::char_traits<char>, std::allocator<char>> string; typedef std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>> wstring; #ifdef _DEBUG typedef Ane::string _tstring; #else typedef Ane::wstring _tstring; #endif }//namespace Ane
[ "inthejm@5abed23c-1faa-11df-9e62-c93c6248c2ac" ]
[ [ [ 1, 16 ] ] ]
435bdba381c163c105b91a2675cb5a6141c3200e
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleRenderers/ParticleUniverseBillboardRenderer.h
0df7e028c57f9a7fb0e87620e14a42ac55b81df2
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
4,087
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. 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. ----------------------------------------------------------------------------- */ #ifndef __PU_BILLBOARD_RENDERER_H__ #define __PU_BILLBOARD_RENDERER_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseRenderer.h" #include "ParticleUniverseTechnique.h" namespace ParticleUniverse { /** The BillboardRenderer class is responsible to render particles as a billboard. */ class _ParticleUniverseExport BillboardRenderer : public ParticleRenderer { public: /** Alternative billboard type. @remarks This is an extended version of Ogre's billboard type. It has BBT_ORIENTED_SHAPE added which basicly means that the billboard orientation is derived from the particle orientation. */ enum BillboardType { BBT_POINT, BBT_ORIENTED_COMMON, BBT_ORIENTED_SELF, BBT_ORIENTED_SHAPE, BBT_PERPENDICULAR_COMMON, BBT_PERPENDICULAR_SELF }; BillboardRenderer(void); virtual ~BillboardRenderer(void); /** @copydoc ParticleRenderer::_prepare */ virtual void _prepare(ParticleTechnique* technique); /** */ void setBillboardType(BillboardType bbt); /** */ BillboardType getBillboardType(void) const; /** */ void setUseAccurateFacing(bool acc); /** */ bool isUseAccurateFacing(void) const; /** */ void setBillboardOrigin(Ogre::BillboardOrigin origin) { mBillboardSet->setBillboardOrigin(origin); } /** */ Ogre::BillboardOrigin getBillboardOrigin(void) const { return mBillboardSet->getBillboardOrigin(); } /** */ void setBillboardRotationType(Ogre::BillboardRotationType rotationType); /** */ Ogre::BillboardRotationType getBillboardRotationType(void) const; /** */ void setCommonDirection(const Ogre::Vector3& vec); /** */ const Ogre::Vector3& getCommonDirection(void) const; /** */ void setCommonUpVector(const Ogre::Vector3& vec); /** */ const Ogre::Vector3& getCommonUpVector(void) const; /** */ void setPointRenderingEnabled(bool enabled); /** */ bool isPointRenderingEnabled(void) const; /** */ virtual void _updateRenderQueue(Ogre::RenderQueue* queue, ParticlePool* pool); /** */ virtual void _notifyAttached(Ogre::Node* parent, bool isTagPoint = false); /** @copydoc ParticleRenderer::_setMaterialName */ virtual void _setMaterialName(const Ogre::String& materialName); /** */ virtual void _notifyCurrentCamera(Ogre::Camera* cam); /** */ virtual void _notifyParticleQuota(size_t quota); /** */ virtual void _notifyDefaultDimensions(Ogre::Real width, Ogre::Real height, Ogre::Real depth); /** */ virtual void _notifyParticleResized(void); /** */ virtual void _notifyParticleZRotated(void); /** */ virtual void setRenderQueueGroup(Ogre::uint8 queueId); /** */ virtual Ogre::SortMode _getSortMode(void) const; /** */ virtual void copyAttributesTo (ParticleRenderer* renderer); /** */ Ogre::BillboardSet* getBillboardSet(void) const { return mBillboardSet; } /** @copydoc ParticleRenderer::setVisible */ virtual void setVisible(bool visible); protected: /** */ Ogre::BillboardSet* mBillboardSet; /** */ BillboardType mBillboardType; }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 171 ] ] ]
843fcdc530734c9683720431a75f920eed35feed
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/INC/AppModel.h
2155cdbfc75282b04debfa4cfd624f4e8b58e3b3
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
GB18030
C++
false
false
5,276
h
//Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu) //All rights reserved. // //PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM //BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF //THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO //NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // //This License allows you to: //1. Make copies and distribute copies of the Program's source code provide that any such copy // clearly displays any and all appropriate copyright notices and disclaimer of warranty as set // forth in this License. //2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)"). // Modifications may be copied and distributed under the terms and conditions as set forth above. // Any and all modified files must be affixed with prominent notices that you have changed the // files and the date that the changes occurred. //Termination: // If at anytime you are unable to comply with any portion of this License you must immediately // cease use of the Program and all distribution activities involving the Program or any portion // thereof. //Statement: // In this program, part of the code is from the GTNetS project, The Georgia Tech Network // Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in // computer networks to study the behavior of moderate to large scale networks, under a variety of // conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from // Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage: // http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/ // //File Information: // // //File Name: //File Purpose: //Original Author: //Author Organization: //Construct Data: //Modify Author: //Author Organization: //Modify Data: #ifndef __appmodel_h__ #define __appmodel_h__ #include "node.h" #include "ElementCustom.h" #include "FileScript.h" #include "ErrorHandler.h" #include <map> #define ERROR_MODEL_SUCCESS ERROR_NO_ERROR #define ERROR_MODEL_INSERT_EXIST 0x00050201 #define ERROR_MODEL_DELETE_NOT_EXIST 0x00050202 #define ERROR_MODEL_GET_NOT_EXIST 0x00050203 #define ERROR_MODEL_WHEN_INIT_CUSTOMELEMENT 0x00050204 class AppModel:public CErrorHandler{ ////////////////////////////////////////////////////////////////////////// //基础方法 ////////////////////////////////////////////////////////////////////////// public: //构造函数及析构函数 AppModel(void); ~AppModel(void); AppModel(CFileScript &f):pScriptCache(&f){ SetLastError(ERROR_MODEL_SUCCESS); }//直接指定配置缓存对象 AppModel(string StrScriptCache); //根据ConfigCachePath路径构造配置缓存,指针赋给pConfigCache virtual AppModel* Copy() const = 0;//描述:返回当前对象的拷贝,纯虚函数,所有派生类需给出实现 virtual bool GetModelValue(void **p) = 0;//描述:计算模型的值,纯虚函数,所有派生类需给出实现 virtual void Initialize(void *p) = 0;//描述:初始化模型相关参数,纯虚函数,所有派生类需给出实现 private: CFileScript *pScriptCache; //模型存取配置文件用的配置缓存对象,经构造函数传入赋值 bool bprivateCache; //如果是Model类自己构造的配置缓存,则为true;否则为false ////////////////////////////////////////////////////////////////////////// //和结点绑定 ////////////////////////////////////////////////////////////////////////// protected: Node *node;//绑定的结点指针,有的子类不需要 public: virtual void AttachNode(Node *n);//所有继承该方法的子类应先实现这个方法 ////////////////////////////////////////////////////////////////////////// //自定义部件相关 ////////////////////////////////////////////////////////////////////////// private: struct ElementStruct { int ID;//子类指定的该自定义部件的id bool RevelantToNode;//该自定义部件是否和结点相关 CElementCustom thisElement;//自定义部件对象 };//一个自定义部件 map<int, ElementStruct> ElementIndex;//存储自定义部件及相关信息 protected: //Size_t GetElementSize() { return ElementIndex.size(); } //描述:增加一个自定义部件到ElementIndex,返回当前ElementIndex中的Element个数 Size_t AddElement(int id, bool revelantToNode, string strSectionName); //描述:删除ID为id的自定义部件,返回当前ElementIndex中剩余的Element个数 Size_t DeleteElement(int id); //描述:调用自定义部件类的相关方法,获得ID为id的自定义部件的值,并返回 double GetElementValueById(int id); ////////////////////////////////////////////////////////////////////////// ///错误处理相关 ////////////////////////////////////////////////////////////////////////// virtual Error_str GetLastErrorEx(); }; #endif
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 147 ] ] ]
e016e631f675b172a6a61670d41095e35f4e8137
a699a508742a0fd3c07901ab690cdeba2544a5d1
/RailwayDetection/KellService/KellService/IOCP/MemoryPool.cpp
a25c2cc109ea75273fdfd9624e76a795bb9d1b42
[]
no_license
xiaomailong/railway-detection
2bf92126bceaa9aebd193b570ca6cd5556faef5b
62e998f5de86ee2b6282ea71b592bc55ee25fe14
refs/heads/master
2021-01-17T06:04:48.782266
2011-09-27T15:13:55
2011-09-27T15:13:55
42,157,845
0
1
null
2015-09-09T05:24:10
2015-09-09T05:24:09
null
UTF-8
C++
false
false
4,427
cpp
#include "StdAfx.h" #include "MemoryPool.h" #include "GobalConfig.h" CMemoryPool::CMemoryPool() { m_pGobalConfig = NULL; m_hEvent = NULL; m_vecPrepOverKeyPire.clear(); m_vecUsedOverKeyPire.clear(); } CMemoryPool::~CMemoryPool() { ClearMemoryPool(); } LPOverKeyPire CMemoryPool::GetNewOverKeyPire() { LPOverKeyPire pOverKeyPire = NULL; CListOverKeyPire::iterator iterBack; m_scMemoryCriticalSection.Lock(); if(MemoryPoolAutoManage()) { iterBack = m_vecPrepOverKeyPire.begin(); pOverKeyPire = (LPOverKeyPire)(*iterBack); m_vecPrepOverKeyPire.erase(iterBack); m_vecUsedOverKeyPire.push_back(pOverKeyPire); } m_scMemoryCriticalSection.Unlock(); return pOverKeyPire; } void CMemoryPool::ReleaseOverKeyPire(LPOverKeyPire pPire) { if(pPire) { CListOverKeyPire::iterator iterTemp; m_scMemoryCriticalSection.Lock(); for (iterTemp = m_vecUsedOverKeyPire.begin(); iterTemp != m_vecUsedOverKeyPire.end(); ++iterTemp) { if(pPire == (LPOverKeyPire)(*iterTemp)) { m_vecUsedOverKeyPire.erase(iterTemp); m_vecPrepOverKeyPire.push_back(pPire); break; } } m_scMemoryCriticalSection.Unlock(); } } bool CMemoryPool::InitMemoryPool(CGobalConfig * pGobalConfig) { ASSERT(pGobalConfig); if(!pGobalConfig) return false; m_pGobalConfig = pGobalConfig; unsigned int nMemoryPoolSize = pGobalConfig->GetMemoryPoolSize();; unsigned int nPrepMemoryPoolSize = m_vecPrepOverKeyPire.size(); if(nPrepMemoryPoolSize < nMemoryPoolSize) { LPOverKeyPire pPire; for(unsigned int nIndex = nPrepMemoryPoolSize; nIndex < nMemoryPoolSize; ++nIndex) { pPire = (LPOverKeyPire)::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(OverKeyPire)); if(pPire) { m_vecPrepOverKeyPire.push_back(pPire); continue; } return false; } } return true; } void CMemoryPool::ClearMemoryPool() { CListOverKeyPire::iterator iterTemp; m_scMemoryCriticalSection.Lock(); if(!m_vecUsedOverKeyPire.empty()) { for (iterTemp = m_vecUsedOverKeyPire.begin(); iterTemp != m_vecUsedOverKeyPire.end(); ++iterTemp) { ::HeapFree(::GetProcessHeap(), 0, (LPVOID)(*iterTemp)); } m_vecUsedOverKeyPire.clear(); } if(!m_vecPrepOverKeyPire.empty()) { for (iterTemp = m_vecPrepOverKeyPire.begin(); iterTemp != m_vecPrepOverKeyPire.end(); ++iterTemp) { ::HeapFree(::GetProcessHeap(), 0, (LPVOID)(*iterTemp)); } m_vecPrepOverKeyPire.clear(); } m_scMemoryCriticalSection.Unlock(); } void CMemoryPool::RecycleMemory() { unsigned int nMemoryPoolSize = 0; m_scMemoryCriticalSection.Lock(); nMemoryPoolSize = m_vecPrepOverKeyPire.size(); if(nMemoryPoolSize > m_pGobalConfig->GetMemoryRecycleSize()) { DecrescenceMemoryPoolSize(nMemoryPoolSize); } m_scMemoryCriticalSection.Unlock(); } bool CMemoryPool::MemoryPoolAutoManage() { ASSERT(m_pGobalConfig); if(!m_pGobalConfig) return false; unsigned int nPrepOverKeyPireSize = m_vecPrepOverKeyPire.size(); if(nPrepOverKeyPireSize < m_pGobalConfig->GetMemoryDownLine()) { return IncrementMemoryPoolSize(nPrepOverKeyPireSize); } else if(nPrepOverKeyPireSize > m_pGobalConfig->GetMemoryRecycleSize()) { return DecrescenceMemoryPoolSize(nPrepOverKeyPireSize); } return true; } bool CMemoryPool::IncrementMemoryPoolSize(unsigned int nCurrentSize) { ASSERT(m_pGobalConfig); if(!m_pGobalConfig) return false; if(nCurrentSize >= m_pGobalConfig->GetMemoryPoolSize()) return true; LPOverKeyPire pPire; for( ; nCurrentSize < m_pGobalConfig->GetMemoryPoolSize(); ++nCurrentSize) { pPire = (LPOverKeyPire)::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(OverKeyPire)); if(pPire) { m_vecPrepOverKeyPire.push_back(pPire); continue; } return false; } return true; } bool CMemoryPool::DecrescenceMemoryPoolSize(unsigned int nCurrentSize) { ASSERT(m_pGobalConfig); if(!m_pGobalConfig) return false; unsigned int nMemorySize = m_pGobalConfig->GetMemoryPoolSize(); if(nCurrentSize > nMemorySize) { CListOverKeyPire::iterator iterPire; for (; nCurrentSize > nMemorySize; --nCurrentSize) { iterPire = m_vecPrepOverKeyPire.end(); --iterPire; ::HeapFree(::GetProcessHeap(), 0, (LPVOID)(*iterPire)); m_vecPrepOverKeyPire.erase(iterPire); } } return true; }
[ "[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3" ]
[ [ [ 1, 191 ] ] ]
9c451e762cf55849de081d6b63075715b50470f2
6f2d9e6d1f0dcb3a00f2885e99a0f566571034c8
/server/src/frmServer.h
79c97afebb37013e06b3d11e223feccc0a9f4795
[]
no_license
crawford/HoIP
bfd7547bd64fe0739e706fcdce4e5b1d6a5ce796
3c14f29375431aad7688444fa1f88201093b398b
refs/heads/master
2021-01-21T22:29:37.296440
2010-09-04T21:27:59
2010-09-04T21:27:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
484
h
#ifndef FRMSERVER_H #define FRMSERVER_H #include "ui_server.h" #include "serialPort.h" #include <QDialog> #include <QTcpServer> #include <QTcpSocket> class FrmServer : public QDialog, Ui::Server { Q_OBJECT public: FrmServer(QWidget *parent = 0, Qt::WindowFlags f = 0); ~FrmServer(); private: QTcpServer *server; QTcpSocket *socket; SerialPort *port; private slots: void handleNewConnection(); void lostClient(); void handleCommand(); }; #endif
[ [ [ 1, 27 ] ] ]
ac64156b1b3090ddac5305d2fc2c9ce6e08fc5cb
66581a883c3eab4c6c7b7c1d5850892485a5cab8
/Action Bros Now/EntityManager.h
06bbf032703975ccece50ca70f5909d8325e01c2
[]
no_license
nrolando/d-m-seniorprojectgsp
9457841f43697a73d956b202541064022dd4a189
503f311142bf4995f3e5c6fc6110317babde08f9
refs/heads/master
2021-01-10T05:49:14.926897
2010-02-17T03:29:10
2010-02-17T03:29:10
49,738,324
0
0
null
null
null
null
UTF-8
C++
false
false
1,436
h
//a singleton class that will contain all the entities in the game //accesses a txt file to load all the enemies for a given lvl //uses the entity's char id to search spriteContainer and set entity's //imgptr to proper sprite sheet #ifndef ENTITYMANAGER_H #define ENTITYMANAGER_H #include "Boss.h" #include "Enemy.h" #include "Player.h" #include "spriteContainer.h" #include <fstream> #include <vector> #include <string> class EntityManager { private: std::vector<BaseGameEntity*> entityVector; public: EntityManager(); ~EntityManager(); BaseGameEntity* getEntVec(int i) { return entityVector[i];} std::vector<BaseGameEntity*> getEntVec() { return entityVector; } bool update(clock_t); void moveEnemies(clock_t); void UpdateEnemyState(Player*); //creates the entity vector for the enemies for this level bool loadFromFile(int); //progress void loadFromFile(char* fileName); void setImgPtrs(); bool isVectorEmpty() { return entityVector.empty();} bool isEnemiesDead(); int getVecSize() { return entityVector.size(); } int getStateByKey(char); int getHealthByKey(char); int getMaxHealthByKey(char); int getSpecialByKey(char); int getMaxSpecialByKey(char); void stunEnt(int i, int a) { entityVector[i]->stun(a); } int getHealth(int i) { return entityVector[i]->getHealth(); } //update the entities //void entiyUpdate(Player* player); }; #endif
[ "nicklamort@2c89e556-c775-11de-bfbd-4d0f0f27293a", "dheardjr@2c89e556-c775-11de-bfbd-4d0f0f27293a", "DHeardjr@2c89e556-c775-11de-bfbd-4d0f0f27293a" ]
[ [ [ 1, 23 ], [ 25, 26 ], [ 28, 31 ], [ 33, 37 ], [ 39, 54 ] ], [ [ 24, 24 ], [ 38, 38 ] ], [ [ 27, 27 ], [ 32, 32 ] ] ]
f2f3492b73aa82f7cc46567655b61364bcbc143d
d2996420f8c3a6bbeef63a311dd6adc4acc40436
/src/net/UdpSocket.cpp
38b7c492c8279c82134bc7feb0d2804eb5a3a4cf
[]
no_license
aruwen/graviator
4d2e06e475492102fbf5d65754be33af641c0d6c
9a881db9bb0f0de2e38591478429626ab8030e1d
refs/heads/master
2021-01-19T00:13:10.843905
2011-03-13T13:15:25
2011-03-13T13:15:25
32,136,578
0
0
null
null
null
null
UTF-8
C++
false
false
2,353
cpp
#include "UdpSocket.h" using namespace net; UdpSocket::UdpSocket() { mSocket = 0; mPort = 0; } UdpSocket::~UdpSocket() { close(); } bool UdpSocket::open( unsigned short port ) { assert( !isOpen() ); // create socket mSocket = ::socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); if ( mSocket <= 0 ) { printf( "failed to create socket\n" ); mSocket = 0; return false; } // bind to port sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( (unsigned short) port ); if ( bind( mSocket, (const sockaddr*) &address, sizeof(sockaddr_in) ) < 0 ) { close(); return false; } // set non-blocking io DWORD nonBlocking = 1; if ( ioctlsocket( mSocket, FIONBIO, &nonBlocking ) != 0 ) { close(); return false; } mPort = port; return true; } void UdpSocket::close() { if ( mSocket != 0 ) { closesocket( mSocket ); mSocket = 0; } } bool UdpSocket::isOpen() const { return mSocket != 0; } unsigned short UdpSocket::getPort() { return mPort; } bool UdpSocket::send( const Address & destination, const void * data, int size) { assert( data ); assert( size > 0 ); if ( mSocket == 0 ) return false; sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = htonl( destination.getAddress() ); address.sin_port = htons( (unsigned short) destination.getPort() ); int sent_bytes = sendto( mSocket, (const char*)data, size, 0, (sockaddr*)&address, sizeof(sockaddr_in) ); return sent_bytes == size; } int UdpSocket::receive( Address & sender, void * data, int size ) { assert( data ); assert( size > 0 ); if ( mSocket == 0 ) return false; typedef int socklen_t; sockaddr_in from; socklen_t fromLength = sizeof( from ); int received_bytes = recvfrom( mSocket, (char*)data, size, 0, (sockaddr*)&from, &fromLength ); if ( received_bytes <= 0 ) return 0; unsigned int address = ntohl( from.sin_addr.s_addr ); unsigned int port = ntohs( from.sin_port ); sender = Address( address, port ); return received_bytes; }
[ "[email protected]@c8d5bfcc-1391-a108-90e5-e810ef6ef867" ]
[ [ [ 1, 122 ] ] ]
8238df9a046b234589c029765cf68773ad3ecfa6
2acd91cf2dfe87f4c78fba230de2c2ffc90350ea
/ salad-bar-in-space-game/edge/bouncibility/third_party/irrklang/include/ik_ISoundStopEventReceiver.h
e0723e14fbbdaf2706eaaae2012f5e45296d40f6
[]
no_license
Joshvanburen/salad-bar-in-space-game
5f410a06be475edee1ab85950c667e6a6f970763
b23a35c832258f4fc1a921a45ab4238c734ef1f0
refs/heads/master
2016-09-01T18:46:29.672326
2008-05-07T18:40:30
2008-05-07T18:40:30
32,195,299
0
0
null
null
null
null
UTF-8
C++
false
false
3,017
h
// Copyright (C) 2002-2007 Nikolaus Gebhardt // This file is part of the "irrKlang" library. // For conditions of distribution and use, see copyright notice in irrKlang.h #ifndef __I_IRRKLANG_SOUND_STOP_EVENT_RECEIVER_H_INCLUDED__ #define __I_IRRKLANG_SOUND_STOP_EVENT_RECEIVER_H_INCLUDED__ #include "ik_IRefCounted.h" #include "ik_SAudioStreamFormat.h" namespace irrklang { //! An enumeration listing all reasons for a fired sound stop event enum E_STOP_EVENT_CAUSE { //! The sound stop event was fired because the sound finished playing ESEC_SOUND_FINISHED_PLAYING = 0, //! The sound stop event was fired because the sound was stopped by the user, calling ISound::stop(). ESEC_SOUND_STOPPED_BY_USER, //! The sound stop event was fired because the source of the sound was removed, for example //! because irrKlang was shut down or the user called ISoundEngine::removeSoundSource(). ESEC_SOUND_STOPPED_BY_SOURCE_REMOVAL, //! This enumeration literal is never used, it only forces the compiler to //! compile these enumeration values to 32 bit. ESEC_FORCE_32_BIT = 0x7fffffff }; //! Interface to be implemented by the user, which recieves sound stop events. /** The interface has only one method to be implemented by the user: OnSoundStopped(). Implement this interface and set it via ISound::setSoundStopEventReceiver(). The sound stop event is guaranteed to be called when a sound or sound stream is finished, either because the sound reached its playback end, its sound source was removed, ISoundEngine::stopAllSounds() has been called or the whole engine was deleted. */ class ISoundStopEventReceiver { public: //! destructor virtual ~ISoundStopEventReceiver() {}; //! Called when a sound has stopped playing. /** This is the only method to be implemented by the user. The sound stop event is guaranteed to be called when a sound or sound stream is finished, either because the sound reached its playback end, its sound source was removed, ISoundEngine::stopAllSounds() has been called or the whole engine was deleted. Please note: Sound events will occur in a different thread when the engine runs in multi threaded mode (default). In single threaded mode, the event will happen while the user thread is calling ISoundEngine::update(). \param sound: Sound which has been stopped. \param reason: The reason why the sound stop event was fired. Usually, this will be ESEC_SOUND_FINISHED_PLAYING. When the sound was aborded by calling ISound::stop() or ISoundEngine::stopAllSounds();, this would be ESEC_SOUND_STOPPED_BY_USER. If irrKlang was deleted or the sound source was removed, the value is ESEC_SOUND_STOPPED_BY_SOURCE_REMOVAL. \param userData: userData pointer set by the user when registering the interface via ISound::setSoundStopEventReceiver(). */ virtual void OnSoundStopped(ISound* sound, E_STOP_EVENT_CAUSE reason, void* userData) = 0; }; } // end namespace irrklang #endif
[ "[email protected]@1a2710a4-8244-0410-8b66-391840787a9e" ]
[ [ [ 1, 72 ] ] ]
8250f1f30a688c7395e9142b099dcc818b81a439
ac559231a41a5833220a1319456073365f13d484
/src/old/server-jaus/jaus/mobility/drivers/globalwaypointdriver.h
f7c3b1c2559ae08dd980862e8275475ddf1eb9ba
[]
no_license
mtboswell/mtboswell-auvc2
6521002ca12f9f7e1ec5df781ed03419129b8f56
02bb0dd47936967a7b9fa7d091398812f441c1dc
refs/heads/master
2020-04-01T23:02:15.282160
2011-07-17T16:48:34
2011-07-17T16:48:34
32,832,956
0
0
null
null
null
null
UTF-8
C++
false
false
11,193
h
//////////////////////////////////////////////////////////////////////////////////// /// /// \file globalwaypointdriver.h /// \brief This file contains the definition of the GlobalWaypointDriver class, /// used as an interface for the driving of platform to a target waypoint. /// /// <br>Author(s): Bo Sun /// <br>Created: 10 February 2010 /// <br>Copyright (c) 2010 /// <br>Applied Cognition and Training in Immersive Virtual Environments /// <br>(ACTIVE) Laboratory /// <br>Institute for Simulation and Training (IST) /// <br>University of Central Florida (UCF) /// <br>All rights reserved. /// <br>Email: [email protected] /// <br>Web: http://active.ist.ucf.edu /// /// 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 ACTIVE LAB, IST, UCF, 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 ACTIVE LAB''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 UCF 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 __JAUS_MOBILITY_GLOBAL_WAYPOINT_DRIVER__H #define __JAUS_MOBILITY_GLOBAL_WAYPOINT_DRIVER__H #include "jaus/core/management/management.h" #include "jaus/mobility/drivers/settravelspeed.h" #include "jaus/mobility/drivers/setglobalwaypoint.h" #include "jaus/mobility/drivers/querytravelspeed.h" #include "jaus/mobility/drivers/queryglobalwaypoint.h" #include "jaus/mobility/drivers/reporttravelspeed.h" #include "jaus/mobility/drivers/reportglobalwaypoint.h" #include "jaus/mobility/sensors/globalposesensor.h" #include "jaus/mobility/sensors/velocitystatesensor.h" namespace JAUS { typedef JAUS::ReportGlobalWaypoint GlobalWaypoint; typedef JAUS::ReportTravelSpeed TravelSpeed; //////////////////////////////////////////////////////////////////////////////////// /// /// \class GlobalWaypointDriver /// \brief The Global Waypoint Driver allows for the driving of platform to a /// target waypoint. /// // The function of the Global Waypoint Driver is to move the platform given a /// single target waypoint, desired travel speed, current platform pose and /// current velocity state. A single waypoint is provided via the Set Global /// Waypoint message. The waypoint remains unchanged until a new Set Global /// Waypoint message is received. A waypoint consists of the desired position /// and orientation of the platform. The second input consists of the desired /// travel speed. The travel speed remains unchanged unless a new Set Travel /// Speed Message is received. The travel speed may then be changed at any time /// during waypoint navigation. The travel speed is reset to zero for all /// transitions from the Ready State. /// /// <b>This implmentation of this service requires at a minimum a Global Pose /// and Velocity State sensor service on the same component that this /// service belongs to. The sensor services can be synchronizing versions /// of the services also (see example_synchronize.cpp for how to do this).</b> /// //////////////////////////////////////////////////////////////////////////////////// class JAUS_MOBILITY_DLL GlobalWaypointDriver : public Management::Child { public: const static std::string Name; ///< String name of the Service. GlobalWaypointDriver(); virtual ~GlobalWaypointDriver(); // Overloaded by the inheriting class to generate commands for the controlled driver. virtual Message* GenerateDriveCommand(const Byte status) = 0; // Overloaded by the inheriting class to generate default commands for the controlled driver. virtual Message* GenerateIdleDriveCommand(const Byte status) const = 0; // Returns true if target waypoint is achieved. virtual bool IsWaypointAchieved(const GlobalPose& currentPose, const JAUS::SetGlobalWaypoint& desiredWaypoint) const = 0; // Virtual method called whenever waypoint driver updates, overload to add additional behaviors/checks needed. virtual void WaypointDriverUpdateEvent(const unsigned int timeSinceLastUpdateMs) {} // Method is called when desired waypoint is achieved. virtual void WaypointAchieved(const JAUS::SetGlobalWaypoint& waypoint) = 0; // Method called whenever a Set Global Waypoint command is received by service. virtual bool SetGlobalWaypoint(const JAUS::SetGlobalWaypoint* command); // Method called whenever a Set Travel Speed command is received by service, overload for extra functionality. virtual bool SetDesiredTravelSpeed(const JAUS::SetTravelSpeed* command) {return true;} // Change the Desired Travel Speed without sending a SetTravelSpeed command virtual bool SetDesiredTravelSpeed(const double speed); // Try to take control of lower-level (e.g. primitive) driver, in order to move to waypoint. virtual bool SetDriverToControl(const Address& driver); // Gets the current GlobalWaypoint command. virtual JAUS::SetGlobalWaypoint GetGlobalWaypoint() const; // Gets the current GlobalPoseSensor report. virtual GlobalPose GetGlobalPose() const; // Gets the current velocity state report. virtual VelocityState GetVelocityState() const; // Gets the current travel speed command. virtual JAUS::SetTravelSpeed GetDesiredTravelSpeed() const; // Gets the time when the last wrench effort command was received. virtual Time GetGlobalWaypointTime() const; // Gets the time when the last travel speed command was received. virtual Time GetTravelSpeedTime() const; // Gets the address of the lower-level (e.g. primitive) driver being controlled. virtual Address GetControlledDriverID() const; // Generates Global Waypoint Driver related events. virtual bool GenerateEvent(const Events::Subscription& info) const; // Adds support for Report Global Waypoint events. virtual bool IsEventSupported(const Events::Type type, const double requestedPeriodicRate, const Message* queryMessage, double& confirmedPeriodicRate, std::string& errorMessage) const; // By default, the Global Waypoint Driver is discoverable to other components (overload to hide). virtual bool IsDiscoverable() const { return true; } // Method called whenever a message is received. virtual void Receive(const Message* message); // Creates messages associated with this service. virtual Message* CreateMessage(const UShort messageCode) const; // Prints information about the service. virtual void PrintStatus() const; // Method called when transitioning to a ready state. virtual bool Resume(); // Method called to transition due to reset. virtual bool Reset(); // Method called when transitioning to a standby state. virtual bool Standby(); // Method called when transitioning to an emergency state. virtual bool SetEmergency(); // Method called when leaving the emergency state. virtual bool ClearEmergency(); // Method called when control is released. virtual bool ReleaseControl(); private: // In this method, drive commands are generated. virtual void CheckServiceStatus(const unsigned int timeSinceLastCheckMs); // Creates a ReportGlobalWaypoint from QueryGlobalWaypoint. void CreateReportFromQuery(const QueryGlobalWaypoint* query, GlobalWaypoint& report) const; // Creates a ReportTravelSpeed from QueryTravelSpeed. void CreateReportFromQuery(const QueryTravelSpeed* query, TravelSpeed& report) const; // Checks if Driver is controlled, acquire control if necessary. bool CheckDriver(); // Checks if Sensor data is availabe, acquire subscriptions if necessary. bool CheckSensors(); // Removes Control of driver and stops subscriptions. bool ReleaseResources(); bool mWaypointAchievedFlag; ///< Flag indicating whether a Waypoint is achieved after being set. Mutex mGlobalWaypointDriverMutex; ///< Mutex for thread protection of data. Address mControlledDriverID; ///< Address of the controlled driver used for waypoint driving. GlobalPoseSensor* mpGlobalPoseSensor; ///< Pointer to the Velocity State Sensor if service is directly accessible. VelocityStateSensor* mpVelocityStateSensor; ///< Pointer to the Velocity State Sensor if service is directly accessible. Time mGlobalWaypointTime; ///< Time when the last target waypoint was received. Time mTravelSpeedTime; ///< Time when the last travel speed was received. JAUS::SetGlobalWaypoint mGlobalWaypoint; ///< The last target waypoint received. JAUS::SetTravelSpeed mDesiredTravelSpeed; ///< The last travel speed received. GlobalPose mGlobalPose; ///< The last global pose reported by the Global Pose Sensor. VelocityState mVelocityState; ///< The last Velocity State reported by the Velocity State Sensor. }; } #endif /* End of File */
[ [ [ 1, 179 ] ] ]
a82e25a6ea893c5b21b2d17ee818a9ce05366de6
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testwideapis/src/twideapisserver.cpp
8fde57ac6c25e69e5af6def398b405b03acf871c
[]
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,318
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 <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 "twideapisserver.h" #include "twideapis.h" _LIT(KServerName, "twideapis"); CWideApiTestServer* CWideApiTestServer::NewL() { CWideApiTestServer *server = new(ELeave) CWideApiTestServer(); 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); CWideApiTestServer* server = NULL; // Create the CTestServer derived server TRAPD(err, server = CWideApiTestServer::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* CWideApiTestServer::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 == Kwfreopen_val) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kwfreopen_valm) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kwfreopen_valinv) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kwfdopen_val) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kwfdopen_ivalm) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kgetws_null) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kgetws_val) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kputws_null) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kputws_val1) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kputws_val2) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kwremove_val1) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kwremove_val2) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kwremove_val3) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kwremove_null) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kwfdopen_ivalm1) { testStep = new CTestWideApi(aStepName); } else if(aStepName == Kwpopen_1) { testStep = new CTestWideApi(aStepName); } return testStep; }
[ "none@none" ]
[ [ [ 1, 188 ] ] ]
938e680e6446e224916086e3210e192989d99706
06ff805f168597297a87642c951867b453e401f7
/Algorithm/boost/boost/mpl/aux_/config/eti.hpp
10917b2a5165e6ef68d5d25119329bdff67cd33d
[]
no_license
fredska/algorithms
58459720295f8cf36edc88f68e4b37962235e533
10538d9677894b450f359db9301108b459b604ca
refs/heads/master
2021-01-02T09:38:34.466733
2011-11-09T17:32:57
2011-11-09T17:32:57
2,652,603
1
0
null
null
null
null
UTF-8
C++
false
false
1,356
hpp
#ifndef BOOST_MPL_AUX_CONFIG_ETI_HPP_INCLUDED #define BOOST_MPL_AUX_CONFIG_ETI_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: eti.hpp,v 1.1 2010-07-13 06:44:24 egraf Exp $ // $Date: 2010-07-13 06:44:24 $ // $Revision: 1.1 $ #include <boost/mpl/aux_/config/msvc.hpp> #include <boost/mpl/aux_/config/workaround.hpp> // flags for MSVC 6.5's so-called "early template instantiation bug" #if !defined(BOOST_MPL_CFG_MSVC_60_ETI_BUG) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) \ && BOOST_WORKAROUND(BOOST_MSVC, < 1300) # define BOOST_MPL_CFG_MSVC_60_ETI_BUG #endif #if !defined(BOOST_MPL_CFG_MSVC_70_ETI_BUG) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) \ && BOOST_WORKAROUND(BOOST_MSVC, == 1300) # define BOOST_MPL_CFG_MSVC_70_ETI_BUG #endif #if !defined(BOOST_MPL_CFG_MSVC_ETI_BUG) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) \ && ( defined(BOOST_MPL_CFG_MSVC_60_ETI_BUG) \ || defined(BOOST_MPL_CFG_MSVC_70_ETI_BUG) \ ) # define BOOST_MPL_CFG_MSVC_ETI_BUG #endif #endif // BOOST_MPL_AUX_CONFIG_ETI_HPP_INCLUDED
[ [ [ 1, 47 ] ] ]
b01fa5ec11d0bb72d450e9806b47eb0d2f9d3218
540b8836343eb1d7343f86847f57a1033b9158d5
/Problem_011.cpp
2169bd10c58046622cb6373a46b177c142f32edb
[]
no_license
Haynesy/Euler
2503160385f45e17e422a6176806b25264aafcb2
1525c8a334e3b1029e6afe5ed3b6e013a77e9c29
refs/heads/master
2020-12-30T10:23:41.879117
2009-10-05T06:21:04
2009-10-05T06:21:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,645
cpp
/** Problem 11 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 The product of these numbers is 26 63 78 14 = 1788696. What is the greatest product of four adjacent numbers in any direction (up, down, left, right, or diagonally) in the 2020 grid? **/ #include <iostream> #include "Level.h" using namespace std; int prob_011(void) { // Arrays via Variables int myArray[20][20] = {}; system("pause"); return 0; }
[ [ [ 1, 43 ] ] ]
63986f872bf47e7c1e20b696856efc2361eaf0a1
898dce1d28c7996db934d74c61d2690048b2bfb3
/rayTracer/Camera.h
675b50f23ab7200bfcc93994cde4ef3603292477
[]
no_license
claudiahwong/cs184-an-eh-sp10
8fa79a2aba7a917e18f393a150fc1183ba7f82a5
d13f992bcb779411e11b1af62e9228246ed62dbd
refs/heads/master
2016-09-05T20:06:52.877441
2010-10-29T04:51:15
2010-10-29T04:51:15
32,365,296
0
0
null
null
null
null
UTF-8
C++
false
false
800
h
/* #pragma once #include "Ray.h" #include "Sample.h" #include "nv_math.h" #include "nv_algebra.h" #include <math.h> class Camera { public: vec3 myEye, myCenter, myUp; float myFov; int mySizex, mySizey; Camera(int sizex, int sizey, vec3 eye, vec3 center, vec3 up, float fov); ~Camera(void); void generateRay(Sample &sample, Ray *ray); }; */ #include "Ray.h" #include "Sample.h" #include "Point.h" #include "nv_math.h" #include "nv_algebra.h" #include <math.h> #include <stdio.h> class Camera { public: vec3 eye, center, up; float fovx, fovy; int screenWidth, screenHeight; Camera(vec3 lookFrom, vec3 lookAt, vec3 upv, float fovY, float znear, int width, int height); Camera(void); ~Camera(void); void generateRay(Sample &sample, Ray *ray); };
[ "victoria.c.chiu@9a492283-e4e1-9893-cc0f-88d6fa45db55" ]
[ [ [ 1, 40 ] ] ]
c8b6e11c029396ccba51c2a7a78dbf344a4b3ef9
b8fbe9079ce8996e739b476d226e73d4ec8e255c
/src/engine/rb_logic/jifprop.cpp
e62b54f1fe6280b294efcae3a0fc007e14ddaaa7
[]
no_license
dtbinh/rush
4294f84de1b6e6cc286aaa1dd48cf12b12a467d0
ad75072777438c564ccaa29af43e2a9fd2c51266
refs/heads/master
2021-01-15T17:14:48.417847
2011-06-16T17:41:20
2011-06-16T17:41:20
41,476,633
1
0
null
2015-08-27T09:03:44
2015-08-27T09:03:44
null
UTF-8
C++
false
false
2,010
cpp
//****************************************************************************/ // File: JIfProp.cpp // Desc: //****************************************************************************/ #include "stdafx.h" #include "JAnimation.h" #include "JIfVar.h" #include "JIfProp.h" //****************************************************************************/ /* JIfProp implementation //****************************************************************************/ decl_class(JIfProp); JIfProp::JIfProp() { m_pObject = NULL; m_Cmp = Cmp_Equal; m_bStatic = false; m_bAlwaysTrue = false; } // JIfProp::JIfProp void JIfProp::Render() { if (!m_pObject) Init(); if (!m_pObject) return; if (m_bStatic && !m_bAlwaysTrue) { JString val; if (m_pObject->GetProperty( m_Prop.c_str(), val )) { SetVisible( IsTrue( val.c_str(), m_Value.c_str(), m_Cmp ) ); } } } // JIfProp::Render void JIfProp::OnPlay() { if (!m_pObject) Init(); if (m_pObject) { JString val; if (m_pObject->GetProperty( m_Prop.c_str(), val )) { if (IsTrue( val.c_str(), m_Value.c_str(), m_Cmp ) || m_bAlwaysTrue) { return; } } } } // JIfProp::OnPlay void JIfProp::Init() { m_pObject = g_pObjectServer->FindObject( m_Object.c_str(), NULL, this ); // check whether we have connected properly static JString path; if (!m_pObject) { GetPath( path ); rlog.err( "JIfProp at path <%s>: Could not find object <%s>", path.c_str(), m_Object.c_str() ); } if (!GetProperty( m_Prop.c_str(), path )) { GetPath( path ); rlog.err( "JIfProp at path <%s>: Could not find property <%s> for object <%s>.", path.c_str(), m_Prop.c_str(), m_Object.c_str() ); } } // JIfProp::Init
[ [ [ 1, 74 ] ] ]
16e6e6b04444be42d101aec701ffe22f7b9aa583
52bc0a7397161736d9be2b27e734c9c637740c39
/src/messages.hpp
b6a98ae63c736b69b5253bafc1e6b9745ebfc8ba
[]
no_license
shestakovg/cro2sql
261454b74dcf29153b74cd879987daae650ca2c9
ba678cb18d061fef3431508bc72e67bcd1067d4f
refs/heads/master
2020-04-23T15:22:24.314384
2010-09-01T16:52:09
2010-09-01T16:52:09
33,734,878
0
0
null
null
null
null
IBM866
C++
false
false
23,130
hpp
/****************************************************************************** ProjectName: cro2sql FileName: messages.hpp Subj: ╤юфхЁцшЄ ёююс∙хэш , т√фртрхь√х юёэютэ√ь ьюфєыхь яЁюуЁрьь√. Author: Nosov Yuri ******************************************************************************* (c) Copyright 2008 Nosov Yuri ([email protected]) The contents of this file are subject to the cro2sql License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the 'LICENSE' file which must have been distributed along with this file. This 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. ******************************************************************************/ #ifndef __MESSAGES__ #define __MESSAGES__ 1 #include <string> // OD - Option description const char * OD_MODE = "Установить путь к конфигурационному файлу (см. Конфигурационный файл)."; const char * OD_AUTO = "Установить путь к файлу экспорта списка банков данных ИСУБД CronosPlus и имя транслируемого банка данных, разделенные \";\"."; const char * OD_OUTPUT = "Сохранить файлы с SQL-выражениями в указанную папку."; const char * OD_SILENT = "Не выдавать ничего в стандартный поток вывода."; const char * I_HEADER = "cro2sql - транслятор банков данных из экспорта ИСУБД CronosPlus в SQL\nВсе права защищены (c) Носов Юрий ([email protected])"; const char * I_FOOTER = "Воспользуйтесь -h или --help для получения справки"; const char * E_AUTO_MANUAL = "Использование ключей -m (--manual) и -a (--auto) одновременно запрещено"; const char * E_UNKNOWN_OPT = "Неизвестная опция"; const char * E_OPT = "Не все обязательные параметры были заполнены."; const char * E_WRONG_ARG = "Неверный агрумент опции"; const char * E_PARSE_ERROR = "Возникла ошибка при разборе файла, содержащего информацию о структуре транслируемого банка данных.\nСообщение парсера: "; const char * E_DATA_PARSE = "Возникла ошибка при разборе файла данных. Сообщение парсера данных : "; const char * E_FILE_NOT_FOUND = "Файл не найден."; const char * E_FILE_OPEN_ERROR ="Ошибка при открытии файла настройки под СУБД"; const char * E_TUNE_FILE = "Файл настройки СУБД имеет неправильную структуру"; const char * E_EXT_LINES_RANGE ="Неверное значение параметра -m (--extended)."; const char * E_LIST_ERROR = "Обнаружена ошибка в файле, содержащим информацию о структуре транслируемого банка данных:\n"; const char * E_PREFIX = "ERROR : "; const char * W_PREFIX = "WARNING: "; const char * M_PREFIX = " "; string GetFullHelp() { stringstream output; output << "CRO2SQL(1) CRO2SQL(1)\n\ \n\ (c) 2008 Носов Юрий Александрович ([email protected])\n\ Все вопросы по работе приложения направлять [email protected]\n\ \n\ NAME\n\ cro2sql - транслятор банков данных из экспорта ИСУБД CronosPlus в SQL\n\ \n\ SYNOPSIS\n\ cro2sql [-d<sep>|-t<conf>|-m<count>|-s] -c<struct_file>[;<bank_name>] \n\ -e<data> -o<path>\n\ struct_file - Путь к файлу, содержащему описание структуры банка данных.\n\ Подробней смотри ниже, в разделе \"Файл, содержащий структуру\n\ банка данных\".\n\ bank_name - В случае, если файл, содержащий структуру банка данных\n\ описывает несколько банков данных (является экспортом списка\n\ банков данных из ИСУБД CronosPlus), необходимо указыть имя\n\ банка, который собираемся транслировать.\n\ data_exp - Путь к папке, содержащей файлы экспорта данных из ИСУБД\n\ CronosPlus.\n\ \n\ DESCRIPTION\n\ Общие сведения \n\ Транслятор cro2sql служит для быстрого преобразования банка данных ИСУБД\n\ CronosPlus в реляционную базу данных формата SQL. На вход cro2sql подается\n\ информация о структуре банка данных формата ИСУБД CronosPlus и файлы\n\ экспорта данных (полученные с помощью функциональности \"экспорт в текст\"\n\ ИСУБД). Транслятор на основе информации о структуре генерирует SQL\n\ инструкции, с помощью которых в реляционной СУБД можно восстановить базу\n\ данных.\n\ \n\ Файл, содержащий структуру банка данных.\n\ Представляет собой txt-файл в кодировке windows-1251, содержащий сведения\n\ о структуре банка данных. Формат файла соответствует формату экспорта\n\ списка банков из ИСУБД CronosPlus, содержащего как минимум:\n\ Наименование банка, \n\ Перечень баз, их свойства,\n\ Перечень полей, их свойства.\n\ Для получения подобного файла, следует в ИСУБД CronosPlus выбрать меню:\n\ Банк=>\"Список файлов\". В появившемся окне нажать кнопку \"В текст ...\". В\n\ появившемся окне, отметить галочками сответствующие пункты, указать адрес\n\ в поле \"Файл отчета\" и нажать выполнить. Файл, содержащий структуру банка\n\ данных будет сгенерирован. Транслятор для именования таблиц и полей будет\n\ использовать названия соответствующих баз и полей ИСУБД CronosPlus.\n\ Существует возможность задать свои названия баз и полей - см раздел\n\ \"Управление трансляцией\".\n\ \n\ Пример файла структуры:\n\ ******************Содержание файла структуры банка***********************\n\ Наименование банка: Тестовый банк\n\ \n\ \n\ Список баз:\n\ N|Название базы|Имя|Тип|Кол-во наборов|Поле кода|Кол-во записей\n\ 1|Лицо|ЛЦ|1|0||223\n\ 2|Адрес|АД|1|0||142\n\ \n\ База :Лицо\n\ Состав полей базы\n\ N поля| Название поля|Тип|Длина поля|Словарь|Статус|Связь с базами\n\ 0|Системный номер|Ц|10|||\n\ 6|Пол|С||Пол||\n\ 1|Фамилия|Т|100000|||\n\ 2|Имя|Т|100000|||\n\ 3|Отчество|Т|100000|||\n\ 4|Место жительства|П|||МН|АД2\n\ \n\ \n\ ==========================\n\ \n\ База :Адрес\n\ Состав полей базы\n\ N поля| Название поля|Тип|Длина поля|Словарь|Статус|Связь с базами\n\ 0|Системный номер|Ц|10|||\n\ 1|Город|Т|100000|||\n\ 2|Проживает|О|||МН|ЛЦ4\n\ *************************************************************************\n\ \n\ Трансляция.\n\ 1. Преобразование идентификаторов.\n\ - приведение к нижнему регистру\n\ - замена всех символов, отличных от цифр, символов нижнего регистра \n\ латинского алфавита и символа \"_\" на символы \"_\"\n\ - сворачивание повторяющихся символов \"_\"\n\ - замена символов кириллицы латинницей по правилам:\n\ 'а'=\"a\" 'ё'=\"e\" 'м'=\"m\" 'т'=\"t\" 'ш'=\"sh\" 'ю'=\"yu\"\n\ 'б'=\"b\" 'ж'=\"zh\" 'н'=\"n\" 'у'=\"u\" 'щ'=\"sh\" 'я'=\"ya\"\n\ 'в'=\"v\" 'з'=\"z\" 'о'=\"o\" 'ф'=\"f\" 'ъ'=\"j\"\n\ 'г'=\"g\" 'и'=\"i\" 'п'=\"p\" 'х'=\"h\" 'ы'=\"i\"\n\ 'д'=\"d\" 'к'=\"k\" 'р'=\"r\" 'ц'=\"c\" 'ь'=\"j\"\n\ 'е'=\"e\" 'л'=\"l\" 'с'=\"s\" 'ч'=\"ch\" 'э'=\"e\"\n\ - удаление (от начала) всех символов, отличных от символов латинского\n\ алфавита.\n\ - в случае, если преобразование невозможно, используем \"invalid_name\"\n\ ЗАМЕЧАНИЕ:\n\ В тех случаях, когда необходимо добиться уникальности имен, применяется\n\ следующий метод:\n\ Если позволяет длина, дописываем вконец _N или N.\n\ Если длина не позволяет,меняем последние символы идентификатора на N.\n\ В случае, если получившийся идентификатор уже используется, \n\ увеличиваем N.\n\ N - строка символов,содержащая цифры и символы латинского алфавита.\n\ Меняется по увеличивается образом:\n\ 0, 1, ... , 9, a, b, ..., z, 10, 11, ..., 19, 1a, ..., 1z, 2z, ...\n\ 2. Преобразование типов\n\ Существуют существенные различия между реализациями стандарта SQL'99.\n\ Поумолчанию был выбран стандарт, используемый MySQL. Преобразование типа\n\ неоднозначно и зависит от данных.\n\ Т - VARCHAR или TEXT\n\ Ц - INTEGER или FLOAT\n\ Для множественных полей строится дополнительная таблица, следующего вида:\n\ имя: mv_<имя таблицы>_<имя поля>\n\ имеет два поля: id - числовой тип и value - тип множественного поля\n\ ИСУБД CronosPlus. Каждое из значений множественного поля заносится\n\ в рассмотренную выше дополнительную таблицу, id этих записей вносится\n\ в таблицу SQL.\n\ Например:\n\ Лицо person\n\ Имя: Иванов name: Иванов\n\ Гражданство: Россия;Германия citizenship: 1\n\ Дополнительная таблица:\n\ mv_person_citizenship\n\ id: 1 value: Россия\n\ id: 1 value: Германия\n\ 3. Преобразование связей\n\ Все связи ИСУБД CronosPlus, по рекомендациям разработчика, должны быть\n\ множественными, поэтому все соответствующие связи SQL будут \"многие ко\n\ многим\". Будьте внимательны. Транслятор может некорректно работать с\n\ базами, мнемокоды которых содержат символы \"|\".\n\ \n\ Управление трансляцией.\n\ В случаях, когда необходимо определить названия или типы таблиц и полей\n\ вручную, можно изменить файл структуры следующим образом:\n\ В описании баз добавить в заголовок \"SQL имя\", и изменить описания. \n\ Пример:\n\ N|Название базы|Имя|Тип|Кол-во наборов|Поле кода|Кол-во записей|SQL имя\n\ 1|Лицо|ЛЦ|1|0||223|person\n\ 2|Адрес|АД|1|0||142|\n\ В данном случае, соответствующая таблица для базы \"Лицо\" будет иметь имя\n\ \"person\", а для базы \"Адрес\" имя будет получено в автоматическом режиме.\n\ Аналогично для полей.:\n\ База :Лицо\n\ Состав полей базы\n\ N поля| Название по ... зами|SQL имя|SQL тип\n\ 0|Системный номер|Ц|10|||ID|INTEGER\n\ 6|Пол|С||Пол||SEX|\n\ 1|Фамилия|Т|100000||||VARCHAR(80)\n\ 2|Имя|Т|100000||||VARCHAR(50)\n\ 3|Отчество|Т|100000||||VARCHAR(80)\n\ 4|Место жительства|П|||МН|АД2|LIVING|\n\ Как видно из примера, для полей существует возможность жестко задавать тип\n\ данных. При этом контроль соответствия файлов экспорта типам возлагается\n\ на пользователя.\n\ Для ссылочных полей задание типа данных невозможно и будет проигнорировано.\n\ При задании типа данных учитывайте длину. Если данные окажутся длиннее,\n\ чем длина заданного для этого поля типа, они будут усечены. Если данные\n\ и тип несогласуются, данные игнорируются. Кроме того, приложение не\n\ осуществляет проверку на правильность указания SQL типа.\n\ Если в заголовок были добавлены \"SQL имя|SQL тип\" вы должны добавить\n\ дополнительные разделители \"|\" всем полям, даже если \"SQL имя\" или\n\ \"SQL тип\" не указаны.\n\ \n\ Файл настройки базы данных\n\ Стандарт SQL'99 различным образом реализован в современных СУБД. Например,\n\ длинные символьные строки в ORACLE будут иметь тип CLOB, а в MySQL - TEXT.\n\ Для точной корректировки работы транслятора для данной СУБД используются\n\ файлы настройки базы данных. Файл настройки - текстовый файл, кодировки\n\ windows-1251 следующей структуры (в скобках указаны значения поумолчанию):\n\ 1 строка - максимальное количество символов в названии таблицы (20)\n\ 2 строка - максимальное количество символов в названии поля (30)\n\ 3 строка - максимальное количество символов в поле типа VARCHAR (VARCHAR)\n\ 4 строка - символ, отвечающий за экранирование (чаще всего \"'\") (\"'\")\n\ 5 строка - символы, которые должны бать экранированы (\"'\")\n\ 6 cтрока - тип, отвечающий за хранение данных INTEGER (INTEGER)\n\ 7 cтрока - тип, отвечающий за хранение данных LONG (LONG)\n\ 8 cтрока - тип, отвечающий за хранение данных FLOAT (FLOAT)\n\ 9 cтрока - тип, отвечающий за хранение данных CLOB (TEXT)\n\ 10 cтрока - тип, отвечающий за хранение данных VARCHAR (VARCHAR)\n\ 11 cтрока - тип, отвечающий за хранение данных DATE (DATE)\n\ 12 cтрока - тип, отвечающий за хранение данных TIME (TIME) \n\ Например файл настройки для СУБД ORACLE может выглядить, так:\n\ ***************************************************************************\n\ 20\n\ 30\n\ 4000\n\ '\n\ '\n\ NUMBER(11)\n\ NUMBER(38)\n\ NUMBER\n\ CLOB\n\ VARCHAR2\n\ DATE\n\ VARCHAR2(5)\n\ ***************************************************************************\n\ \n\ OPTIONS\n\ -c, --config<=struct_file> - Указывает приложению путь к файлу, содержащему\n\ сведения о структуре банка данных. В случае,\n\ если файл, содержащий структуру банка данных\n\ описывает несколько банков данных (является\n\ экспортом списка банков данных ИСУБД\n\ CronosPlus), необходимо через точку с запятой\n\ указыть имя банка, который собираемся\n\ транслировать.\n\ -d, --delimiter<=sep> - Установить разделитель строк в файлах экспорта\n\ данных ИСУБД CronosPlus. Поумолчанию \"|\".\n\ -e, --export<data_export> - Указывает путь к папке с файлами экспорта данных\n\ ИСУБД CronosPlus.\n\ -o, --output<=path> - Сохранить файлы с SQL-выражениями в указанную\n\ папку.\n\ -t, --tune<conf> - Использовать файл настроки базы данных. См.\n\ раздел \"Файл настройки базы данных\".\n\ -m, --extended<count> - Сообщает транслятору о возможности использовать\n\ расширенные вставки (метод сокращения sql\n\ insert-выражений). \n\ Например:\n\ INSERT INTO Tab(a, b) VALUES\\\n\ (1, 2),\n\ (2, 3),\n\ (3, 4);\n\ <count> - сообщает какое количество строк можно\n\ вставить с одним заголовком (поумолчанию 50).\n\ Параметр count должен быть ненулевым\n\ положительным числом.\n\ -s, --silent - Не выдавать ничего в консоль.\n\ -h, --help - Показать это сообщение.\n\ \n\ EXAMPLES\n\ cro2sql -с\"C:\\BankList.txt\";\"Тестовый банк\" -eC:\\EXPORT -s -oC:\\SQL\n\ На основе файла описания структуры \"Список банков.txt\" осуществит\n\ трансляцию банка данных \"Тестовый банк\" ИСУБД CronosPlus, экспорт данных\n\ которого расположен по адресу C:\\EXPORT. SQL файлы будут сохранены в папке\n\ C:\\SQL, в stdout выдано ничего не будет.\n\ "; return output.str(); } string GetErrorMsg(string err_message) { stringstream output; output << I_HEADER << endl << endl << E_PREFIX << err_message << endl << endl << I_FOOTER; return output.str(); } string GetWarningMsg(string warn_message) { return ""; } #endif // __MESSAGES__
[ "cro2sql@f00a9db0-22bd-11df-99a1-e5276f3be39f" ]
[ [ [ 1, 304 ] ] ]
996418bbe2931feb15f0dc700accdfd864d02b10
e635ba5e4aa70e346a5d15e3e2d6c9625a27763e
/src/NoExit.cpp
6c096c6c779b93b3b17ad7bc81fdba6471cd9c5d
[]
no_license
aruwen/noexit
8d701c40837e3be4308c20a8939c4676c3e118ca
bbd6938b9dfbd125177545d3f38a22c1f7d9865b
refs/heads/master
2020-05-17T02:32:30.255482
2011-03-10T09:18:28
2011-03-10T09:18:28
32,136,559
0
0
null
null
null
null
UTF-8
C++
false
false
21,193
cpp
/* * QPT1 * Stefan Ebner * 2.Semester MMT * * FH-Salzburg * * @ The game itself */ #include "NoExit.h" NoExit::~NoExit() { resetAll(); deleteAll(); } NoExit::NoExit() { initializeNoExit(); } void NoExit::update() { if (counter<300) counter++; playerPositioning(); if(!collisionDetected() && !rotationStarted && counter >210) { rotateCube(); moveCube(); player1Score+=currentPoints; } //keeps the rotationangle of the cube between 0 <-> 360 if(rotatedAngle<0) rotatedAngle+=360; if(rotatedAngle%360>=1) rotatedAngle-=360; } void NoExit::draw() { // set viewport int width, height; width = ofGetWidth(); height = ofGetHeight(); glViewport(0, 0, width, height); glClearColor(1.0, 1.0, 1.0, 0.0); glClearDepth(1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // set perspective projection glMatrixMode(GL_PROJECTION); glPushMatrix(); glEnable(GL_DEPTH_TEST); // glDisable(GL_DEPTH); glLoadIdentity(); glOrtho(0, width, height, 0, 0.0f, 30.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); ofSetColor(255,0,0, 1); glColor3f(1, 1, 1); //countdown and short instruction if(counter<210) inGameFont.drawString("Goal:\n-reach the exit\n-dont touch the walls", width-330, 30); if(counter<60) { inGameFont2.drawString("3", width/2-26, 50); } if(counter>60 && counter <120) { inGameFont2.drawString("2", width/2-26, 50); } if(counter>120 && counter <180) { inGameFont2.drawString("1", width/2-26, 50); } if(counter>180 && counter <210) { inGameFont2.drawString("Begin", width/2-115, 50); } else if(counter > 210) { inGameFont.setLineHeight(30); string points = "Current Points: "; inGameFont.drawString(points, width/2-150, 20); itoa(player1Score, scoreBuffer, 10); inGameFont.drawString(scoreBuffer, width/2+150, 20); } // ofSetColor(255,255,255); glPopMatrix(); glPopMatrix(); // clear viewport glClearColor(0.0, 0.0, 0.5, 1.0); glClearDepth(1.0); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(65, (float)width / height, 0.1, 100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // set camera position float time = ofGetElapsedTimef(); gluLookAt(4.0 , 0.2 , 0.2 , 0.0, 0.0, 0.0, 0.0, 0.0, 0.1); glEnable(GL_CULL_FACE); glEnable(GL_LIGHTING); setLights(); // place the player in the world glPushMatrix(); glColor3f(1,0,0); setLight(2,0.5,0,0); glutSolidSphere(0.02,30,30); glPopMatrix(); //check if an exit has been successfully reached bool needToSetExits = false; if(checkForExit() || rotationStarted) { rotation+=3; glRotatef(rotation,0,1,0); } { //draw mainscene glPushMatrix(); { if(rotateCCW==true) { glRotatef(rotatedLeft+rotatedAngle,1,0,0); } else if(rotateCW==true) { glRotatef(rotatedRight+rotatedAngle,1,0,0); } else { glRotatef(rotatedAngle,1,0,0); } glPushMatrix(); { if(rotation==90) { increasingMoveSpeed+=0.002; rotationStarted=false; setNewMazes(); rotation=0; currentPoints++; glTranslatef(0, moveY, moveZ); } else glTranslatef(0, moveY,moveZ); setMatteMaterial(); drawCube(); glColor3f(0.15, 0.15, 0.15); drawMaze(current, 0, -1.2, 1.2, true, moveZ, moveY); if((rotationStarted && rotatedAngle == 0) || !rotationStarted) { glPushMatrix(); //North maze glRotatef(-90,0,1,0); glTranslatef(1.2,0,1.2); drawCube(); glColor3f(0.15, 0.15, 0.15); drawMaze(up, 0, -1.2, 1.2); glPopMatrix(); } //south maze if((rotationStarted && rotatedAngle == -180) || !rotationStarted) { glPushMatrix(); glRotatef(90,0,1,0); glTranslatef(1.2,0, -1.2); drawCube(); glColor3f(0.15, 0.15, 0.15); drawMaze(down, 0, -1.2, 1.2); glPopMatrix(); } //EAST maze if((rotationStarted && rotatedAngle == -270) || !rotationStarted) { glPushMatrix(); glRotatef(90,0,0,1); glTranslatef(1.2,1.2,0); drawCube(); glColor3f(0.15, 0.15, 0.15); drawMaze(right, 0, -1.2, 1.2); glPopMatrix(); } if((rotationStarted && rotatedAngle == -90) || !rotationStarted) { glPushMatrix(); glRotatef(-90,0,0,1); glTranslatef(1.2, -1.2 ,0); drawCube(); glColor3f(0.15, 0.15, 0.15); drawMaze(left, 0, -1.2, 1.2); glPopMatrix(); } } glPopMatrix(); } glPopMatrix(); } } void NoExit::rotateCube() { //rotates the cube when the button is pressed if(rotateCCW==true && rotatedLeft >=-90) { rotatedLeft-=10; } if(rotatedLeft==-90) { rotatedLeft=0; rotateCCW=false; rotatedAngle-=90; } if(rotateCW== true && rotatedRight <=90) { rotatedRight+=10; } if(rotatedRight==90) { rotateCW=false; rotatedRight=0; rotatedAngle+=90; } } int NoExit::returnScore() { return player1Score; } void NoExit::keyPressedGame(int key) { switch (key) { case OF_KEY_LEFT: playerPositioning(); if(!gameStopped && (positionY != 0 || positionY != 12 || positionZ != 0 || positionZ != 12)) rotateCCW= true; else rotateCCW = false; break; case OF_KEY_RIGHT: if(!gameStopped && (positionY != 0 || positionY != 12 || positionZ != 0 || positionZ != 12)) rotateCW = true; else rotateCW = false; break; case OF_KEY_BACKSPACE: if(!restart) { resetAll(); } break; } } void NoExit::setCurrentExits() { westExit=current->getExit(WEST); eastExit=current->getExit(EAST); northExit=current->getExit(NORTH); southExit=current->getExit(SOUTH); } void NoExit::resetAll() //resets all the values to standard values { player.y=6.5; player.z=6.5; increasingMoveSpeed=0.0; player1Score=player2Score=0; counter=0; delete current; delete left; delete up; delete down; delete right; current = new Maze(13); left = new Maze(13); up = new Maze(13); down = new Maze(13); right = new Maze(13); current->generateMaze(1,0,NONE); current->generateExit(NONE); setCurrentExits(); generateMazes(NONE,NONE);; rotatedLeft=rotatedRight=rotatedAngle=0; rotateCCW=rotateCW=false; moveDown=moveTemp=moveY=moveZ=rotation=0; exitRotation=false; restart = false; gameStopped = false; currentPoints=1; } void NoExit::generateMazes(directions dir, directions dir2) //creates the mazes depending on which stay { setCurrentExits(); if(dir != NORTH || dir2 != NORTH) { up->generateMaze(2,northExit,SOUTH); up->generateExit(SOUTH); } if(dir != EAST || dir2 !=EAST) { right->generateMaze(2,eastExit,WEST); right->generateExit(WEST); } if(dir != SOUTH || dir2 !=SOUTH) { down->generateMaze(2,southExit,NORTH); down->generateExit(NORTH); } if(dir != WEST || dir2 != WEST) { left->generateMaze(2,westExit,EAST); left->generateExit(EAST); } } void NoExit::setNewMazes() //deletes the old mazes and creates new ones accordingly { switch((int)rotatedAngle) { case ROTATEDEAST: player.y-=11.0; playerPositioning(); moveY=1.1; delete left; left=new Maze(*current); delete down; delete up; delete current; current=new Maze(*right); down=new Maze(13); up=new Maze(13); delete right; right=new Maze(13); generateMazes(EAST, WEST); break; case ROTATEDWEST: player.y+=11.0; playerPositioning(); moveY=-1.1; delete right; right=new Maze(*current); delete down; delete up; delete current; current=new Maze(*left); down=new Maze(13); up=new Maze(13); delete left; left=new Maze(13); generateMazes(WEST, EAST); break; case ROTATEDNORTH: player.z+=11.0; playerPositioning(); moveZ = 1.1; delete down; down = new Maze(*current); delete left; delete right; delete current; current = new Maze(*up); left = new Maze(13); right = new Maze(13); delete up; up = new Maze(13); generateMazes(NORTH, SOUTH); break; case ROTATEDSOUTH: player.z-=11.0; playerPositioning(); moveZ = -1.1; delete up; up = new Maze(*current); delete left; delete right; delete current; current = new Maze(*down); left = new Maze(13); right = new Maze(13); delete down; down = new Maze(13); generateMazes(SOUTH, NORTH); break; } } void NoExit::moveCube() { //moves the cube downwards if there is no rotation going on if(rotateCW==false && rotateCCW==false) moveDown=0.01+increasingMoveSpeed; else moveDown=0; switch(rotatedAngle) { case -270: moveY-=moveDown; player.y+=moveDown*5; break; case -180: moveZ+=moveDown; player.z+=moveDown*5; break; case -90: moveY+=moveDown; player.y-=moveDown*5; break; case 0: moveZ-=moveDown; player.z-=moveDown*5; break; } } void NoExit::drawMaze(Maze *mazeDraw, float x, float y, float z, bool doBoundingBox, float moveZ, float moveY) { //draws the maze for (float a=0;a<13;a++) { for (float b=0;b<13;b++) { if (mazeDraw->getWallf(b, a)==true) { glPushMatrix(); glTranslatef(x, y+(b/5), z-(a/5)); if (a==0 || b== 0 || a== 12 || b==12) glColor3f(0.1, 0.1, 0.1); else glColor3f(0.3, 0.3, 0.3); drawMazeWall(); glPopMatrix(); } else continue; } } } bool NoExit::collisionDetected() //collision detections, checks if one of the 4 sides //of the player is inside a wall { for (int i=1; i<5; i++) { switch(i) { case 1: playerPositioning(-0.08, +0.08); if (current->getWalli(positionY, positionZ) == true) { playerPositioning(); gameStopped=true; return true; } else playerPositioning(); break; case 2: playerPositioning(+0.08, +0.08); if (current->getWalli(positionY, positionZ) == true) { playerPositioning(); gameStopped=true; return true; } else playerPositioning(); break; case 3: playerPositioning(+0.08, -0.08); if (current->getWalli(positionY, positionZ) == true) { playerPositioning(); gameStopped=true; return true; } else playerPositioning(); break; case 4: playerPositioning(-0.08, -0.08); if (current->getWalli(positionY, positionZ) == true) { playerPositioning(); gameStopped=true; return true; } else playerPositioning(); break; } } return false; } bool NoExit::getGameStopped() { return gameStopped; } void NoExit::setGameStopped() { gameStopped = false; } bool NoExit::checkForExit() //if the player reaches an exit, the rotation start towards a new maze { if(rotationStarted==true) return false; playerPositioning(); assert(positionY >= 0 || positionY <= 12 || positionZ <= 12 || positionZ >= 0); if( positionY<=11 && positionY>=1 && positionZ<=11 && positionZ>=1) { rotationStarted=false; return false; } else if (positionY == 0 || positionY == 12 || positionZ == 12 || positionZ == 0) { if(current->getWalli(positionY, positionZ) == false) { rotationStarted=true; return true; } return false; } } void NoExit::playerPositioning(float z, float y) //converts the current player position in the maze //to the correct maze field { positionZ=(int)floor(player.z+z); positionY=(int)floor(player.y+y); } void NoExit::setLights() { //light 1 glPushMatrix(); glColor3f(1.0, 0.0, 0.0); glTranslatef(1.0, 0.0, 0.0); setLight(0, 1.0, 1.0, 1.0); glPopMatrix(); //light 2 glPushMatrix(); glColor3f(0.0, 0.0, 1.0); glTranslatef(1.0, 1.0, -1.0); setLight(1, 1.0, 1.0, 1.0); glPopMatrix(); } void NoExit::setEmissionMaterial(float r , float g , float b ) { float specular[] = { 1.0, 1.0, 1.0, 0.0 }; float emission[] = { r, g, b, 1.0 }; glMaterialfv(GL_FRONT, GL_SPECULAR, specular); glMaterialfv(GL_FRONT, GL_EMISSION, emission); glMaterialf(GL_FRONT, GL_SHININESS, 40.0); glEnable(GL_COLOR_MATERIAL); } void NoExit::drawMazeWall() { float z; z=0.1; glBegin(GL_QUADS); // bottom glTexCoord2f(0.0, 0.0); glNormal3f(0.0, 0.0, -1.0); glVertex3f(-0.1, -0.1, -z); glTexCoord2f(1.0, 0.0); glNormal3f(0.0, 0.0, -1.0); glVertex3f(-0.1, +0.1, -z); glTexCoord2f(1.0, 1.0); glNormal3f(0.0, 0.0, -1.0); glVertex3f(+0.1, +0.1, -z); glTexCoord2f(0.0, 1.0); glNormal3f(0.0, 0.0, -1.0); glVertex3f(+0.1, -0.1, -z); // top glTexCoord2f(0.0, 0.0); glNormal3f(0.0, 0.0, +1.0); glVertex3f(-0.1, -0.1, +z); glTexCoord2f(1.0, 0.0); glNormal3f(0.0, 0.0, +1.0); glVertex3f(+0.1, -0.1, +z); glTexCoord2f(1.0, 1.0); glNormal3f(0.0, 0.0, +1.0); glVertex3f(+0.1, +0.1, +z); glTexCoord2f(0.0, 1.0); glNormal3f(0.0, 0.0, +1.0); glVertex3f(-0.1, +0.1, +z); // front glTexCoord2f(0.0, 0.0); glNormal3f(0.0, -1.0, 0.0); glVertex3f(-0.1, -0.1, -z); glTexCoord2f(1.0, 0.0); glNormal3f(0.0, -1.0, 0.0); glVertex3f(+0.1, -0.1, -z); glTexCoord2f(1.0, 1.0); glNormal3f(0.0, -1.0, 0.0); glVertex3f(+0.1, -0.1, +z); glTexCoord2f(0.0, 1.0); glNormal3f(0.0, -1.0, 0.0); glVertex3f(-0.1, -0.1, +z); // back glTexCoord2f(0.0, 0.0); glNormal3f(0.0, +1.0, 0.0); glVertex3f(-0.1, +0.1, -z); glTexCoord2f(1.0, 0.0); glNormal3f(0.0, +1.0, 0.0); glVertex3f(-0.1, +0.1, +z); glTexCoord2f(1.0, 1.0); glNormal3f(0.0, +1.0, 0.0); glVertex3f(+0.1, +0.1, +z); glTexCoord2f(0.0, 1.0); glNormal3f(0.0, +1.0, 0.0); glVertex3f(+0.1, +0.1, -z); // top glTexCoord2f(0.0, 0.0); glNormal3f(+1.0, 0.0, 0.0); //original x,y value bottom left glVertex3f(+0.1, -0.1, -z); glTexCoord2f(1.0, 0.0); glNormal3f(+1.0, 0.0, 0.0); glVertex3f(+0.1, +0.1, -z); glTexCoord2f(1.0, 1.0); glNormal3f(+1.0, 0.0, 0.0); glVertex3f(+0.1, +0.1, +z); glTexCoord2f(0.0, 1.0); glNormal3f(+1.0, 0.0, 0.0); glVertex3f(+0.1, -0.1, +z); glEnd(); } void NoExit::deleteAll() { delete current; delete left; delete right; delete up; delete down; } void NoExit::drawCube() { //only draws the ground but no adjacent cube sides float x=-0.1; glBegin(GL_QUADS); // front glColor3f(0.75, 0.75, 0.75); glNormal3f(+1.0, 0.0, 0.0); glTexCoord2f(0,0); glVertex3f(x, -1.1, -1.1); glTexCoord2f(1,0); glNormal3f(+1.0, 0.0, 0.0); glVertex3f(x, +1.1, -1.1); glTexCoord2f(1,1); glNormal3f(+1.0, 0.0, 0.0); glVertex3f(x, +1.1, +1.1); glTexCoord2f(0,1); glNormal3f(+1.0, 0.0, 0.0); glVertex3f(x, -1.1, +1.1); glEnd(); } void NoExit::setLight(int i, float r, float g, float b) { glEnable(GL_LIGHT0 + i); float diffuse[] = { r, g, b, 1.0 }; float specular[] = { r, g, b, 1.0 }; float ambient[] = { 0.1 * r, 0.1 * g, 0.1 * b, 1.0 }; float position[] = { 0.0, 0.0, 0.0, 1.0 }; glLightfv(GL_LIGHT0 + i, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0 + i, GL_SPECULAR, specular); glLightfv(GL_LIGHT0 + i, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0 + i, GL_POSITION, position); glLightf(GL_LIGHT0 + i, GL_CONSTANT_ATTENUATION, 0.8); glLightf(GL_LIGHT0 + i, GL_LINEAR_ATTENUATION, 0.0); glLightf(GL_LIGHT0 + i, GL_QUADRATIC_ATTENUATION, 0.2); glMaterialfv(GL_FRONT, GL_EMISSION, diffuse); } void NoExit::setShinyMaterial() { float specular[] = { 1.0, 1.0, 1.0, 1.0 }; float emission[] = { 0.0, 0.0, 0.0, 1.0 }; glMaterialfv(GL_FRONT, GL_SPECULAR, specular); glMaterialfv(GL_FRONT, GL_EMISSION, emission); glMaterialf(GL_FRONT, GL_SHININESS, 40); glEnable(GL_COLOR_MATERIAL); } void NoExit::setMatteMaterial() { float specular[] = { 0.0, 0.0, 0.0, 1.0 }; float emission[] = { 0.0, 0.0, 0.0, 1.0 }; glMaterialfv(GL_FRONT, GL_SPECULAR, specular); glMaterialfv(GL_FRONT, GL_EMISSION, emission); glMaterialf(GL_FRONT, GL_SHININESS, 1); // material diffuse & ambient color should track current vertex color glEnable(GL_COLOR_MATERIAL); } void NoExit::initializeNoExit() { ofSetVerticalSync(true); //generate Mazes current = new Maze(13); left = new Maze(13); up = new Maze(13); down = new Maze(13); right = new Maze(13); current->generateMaze(1,0,NONE); current->generateExit(NONE); setCurrentExits(); generateMazes(NONE, NONE); player.y=6.5; player.z=6.5; rotatedLeft=rotatedRight=rotatedAngle=0; moveDown=moveTemp=moveY=moveZ=0; exitRotation=restart=false; rotation=0; gameStopped=false; inGameFont.loadFont("rou.ttf", 18, true, true); inGameFont2.loadFont("rou.ttf", 52, true, true); }
[ "[email protected]@dbebec47-8437-1be3-c343-d412ef630ae2" ]
[ [ [ 1, 783 ] ] ]
29a19cd4d14998b3e6253c9a70e552971fc3a3c4
16d8b25d0d1c0f957c92f8b0d967f71abff1896d
/obse/obse/Commands_AI.cpp
7a8ca4fbd210e070ef6f6f56ac154c70ff54ff25
[]
no_license
wlasser/oonline
51973b5ffec0b60407b63b010d0e4e1622cf69b6
fd37ee6985f1de082cbc9f8625d1d9307e8801a6
refs/heads/master
2021-05-28T23:39:16.792763
2010-05-12T22:35:20
2010-05-12T22:35:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
36,175
cpp
#include "Commands_AI.h" #include "GameObjects.h" #include "GameExtraData.h" #include "GameAPI.h" #include "GameForms.h" #include "GameProcess.h" #include "ParamInfos.h" #if OBLIVION #include "InternalSerialization.h" static bool Cmd_GetNumFollowers_Execute(COMMAND_ARGS) { *result = 0; if (!thisObj) return true; BSExtraData* xData = thisObj->baseExtraList.GetByType(kExtraData_Follower); if (!xData) return true; ExtraFollower* xFollower = (ExtraFollower*)Oblivion_DynamicCast(xData, 0, RTTI_BSExtraData, RTTI_ExtraFollower, 0); if (xFollower) *result = ExtraFollowerVisitor(xFollower->followers).Count(); return true; } static bool Cmd_GetNthFollower_Execute(COMMAND_ARGS) { UInt32 idx = 0; UInt32* refResult = (UInt32*)result; *refResult = 0; if (!ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &idx)) return true; else if (!thisObj) return true; BSExtraData* xData = thisObj->baseExtraList.GetByType(kExtraData_Follower); if (!xData) return true; ExtraFollower* xFollowers = (ExtraFollower*)Oblivion_DynamicCast(xData, 0, RTTI_BSExtraData, RTTI_ExtraFollower, 0); if (xFollowers) { Character* follower = ExtraFollowerVisitor(xFollowers->followers).GetNthInfo(idx); if (follower) *refResult = follower->refID; } return true; } static bool Cmd_GetNumDetectedActors_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = NULL; Actor* actor = (Actor*)Oblivion_DynamicCast(thisObj, 0, RTTI_TESObjectREFR, RTTI_Actor, 0); if (actor) hiProc = (HighProcess*)Oblivion_DynamicCast(actor->process, 0, RTTI_BaseProcess, RTTI_HighProcess, 0); if (hiProc && hiProc->detectionList) *result = HighProcess::DetectionListVisitor(hiProc->detectionList).Count(); if (IsConsoleMode()) Console_Print("Num Detected Actors: %.0f", *result); return true; } static bool Cmd_GetNthDetectedActor_Execute(COMMAND_ARGS) { UInt32 whichN = 0; HighProcess* hiProc = NULL; UInt32* refResult = (UInt32*)result; *refResult = 0; if (!ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &whichN)) return true; Actor* actor = (Actor*)Oblivion_DynamicCast(thisObj, 0, RTTI_TESObjectREFR, RTTI_Actor, 0); if (actor) hiProc = (HighProcess*)Oblivion_DynamicCast(actor->process, 0, RTTI_BaseProcess, RTTI_HighProcess, 0); if (hiProc && hiProc->detectionList) { HighProcess::DetectionList::Data* data = HighProcess::DetectionListVisitor(hiProc->detectionList).GetNthInfo(whichN); if (data && data->actor) { *refResult = data->actor->refID; if (IsConsoleMode()) PrintItemType(data->actor->baseForm); } } return true; } class DetectedActorFinder { public: Actor* m_actorToFind; DetectedActorFinder(Actor* actor) : m_actorToFind(actor) { } bool Accept(HighProcess::DetectionList::Data* data) { if (data->actor && data->actor->refID == m_actorToFind->refID) return true; return false; } }; static bool Cmd_SetDetectionState_Execute(COMMAND_ARGS) { HighProcess* hiProc = NULL; Actor* actor = NULL; UInt32 detectLevel = 0; *result = 0; if (!ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &actor, &detectLevel)) return true; Actor* callingActor = (Actor*)Oblivion_DynamicCast(thisObj, 0, RTTI_TESObjectREFR, RTTI_Actor, 0); if (callingActor) hiProc = (HighProcess*)Oblivion_DynamicCast(callingActor->process, 0, RTTI_BaseProcess, RTTI_HighProcess, 0); if (hiProc && hiProc->detectionList && detectLevel < HighProcess::kDetectionState_Max) { const HighProcess::DetectionList* dList = HighProcess::DetectionListVisitor(hiProc->detectionList).Find(DetectedActorFinder(actor)); if (dList) dList->data->detectionState = detectLevel; } return true; } static bool GetServiceFlag_Execute(COMMAND_ARGS, UInt32 whichService) { TESNPC* npc = NULL; if (!ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &npc)) return false; if (!npc && thisObj) npc = (TESNPC*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESNPC, 0); if (npc) return npc->aiForm.OffersServices(whichService); else return false; } static bool Cmd_OffersWeapons_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Weapons) ? 1 : 0; return true; } static bool Cmd_OffersArmor_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Armor) ? 1 : 0; return true; } static bool Cmd_OffersBooks_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Books) ? 1 : 0; return true; } static bool Cmd_OffersClothing_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Clothing) ? 1 : 0; return true; } static bool Cmd_OffersIngredients_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Ingredients) ? 1 : 0; return true; } static bool Cmd_OffersLights_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Lights) ? 1 : 0; return true; } static bool Cmd_OffersApparatus_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Apparatus) ? 1 : 0; return true; } static bool Cmd_OffersMiscItems_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Misc) ? 1 : 0; return true; } static bool Cmd_OffersSpells_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Spells) ? 1 : 0; return true; } static bool Cmd_OffersMagicItems_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_MagicItems) ? 1 : 0; return true; } static bool Cmd_OffersPotions_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Potions) ? 1 : 0; return true; } static bool Cmd_OffersTraining_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Training) ? 1 : 0; return true; } static bool Cmd_OffersRecharging_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Recharge) ? 1 : 0; return true; } static bool Cmd_OffersRepair_Execute(COMMAND_ARGS) { *result = GetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Repair) ? 1 : 0; return true; } static bool Cmd_GetTrainerSkill_Execute(COMMAND_ARGS) { TESNPC* npc = NULL; if (!ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &npc)) return true; if (!npc && thisObj) npc = (TESNPC*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESNPC, 0); if (npc && npc->aiForm.OffersServices(TESAIForm::kService_Training)) *result = npc->aiForm.trainingSkill + kActorVal_Armorer; return true; } static bool Cmd_GetTrainerLevel_Execute(COMMAND_ARGS) { TESNPC* npc = NULL; if (!ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &npc)) return true; if (!npc && thisObj) npc = (TESNPC*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESNPC, 0); if (npc && npc->aiForm.OffersServices(TESAIForm::kService_Training)) *result = npc->aiForm.trainingLevel; return true; } static bool Cmd_OffersServicesC_Execute(COMMAND_ARGS) { TESNPC* npc = NULL; UInt32 serviceMask = 0; if (!ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &serviceMask, &npc)) return true; if (!npc && thisObj) npc = (TESNPC*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESNPC, 0); if (serviceMask && npc && npc->aiForm.OffersServices(serviceMask)) *result = 1; else *result = 0; return true; } static void SetServiceFlag_Execute(COMMAND_ARGS, UInt32 whichService) { TESNPC* npc = NULL; UInt32 bSetFlag = 0; if (ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &bSetFlag, &npc)) { if (!npc && thisObj) npc = (TESNPC*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESNPC, 0); if (npc) { npc->aiForm.SetOffersServices(whichService, bSetFlag ? true : false); } } } static bool Cmd_SetOffersWeapons_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Weapons); return true; } static bool Cmd_SetOffersArmor_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Armor); return true; } static bool Cmd_SetOffersClothing_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Clothing); return true; } static bool Cmd_SetOffersBooks_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Books); return true; } static bool Cmd_SetOffersIngredients_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Ingredients); return true; } static bool Cmd_SetOffersLights_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Lights); return true; } static bool Cmd_SetOffersApparatus_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Apparatus); return true; } static bool Cmd_SetOffersMiscItems_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Misc); return true; } static bool Cmd_SetOffersPotions_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Potions); return true; } static bool Cmd_SetOffersSpells_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Spells); return true; } static bool Cmd_SetOffersMagicItems_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_MagicItems); return true; } static bool Cmd_SetOffersTraining_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Training); return true; } static bool Cmd_SetOffersRecharging_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Recharge); return true; } static bool Cmd_SetOffersRepair_Execute(COMMAND_ARGS) { SetServiceFlag_Execute(PASS_COMMAND_ARGS, TESAIForm::kService_Repair); return true; } static bool Cmd_GetServicesMask_Execute(COMMAND_ARGS) { TESNPC* npc = NULL; *result = 0; if (ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &npc)) { if (!npc && thisObj) npc = (TESNPC*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESNPC, 0); if (npc) *result = npc->aiForm.serviceFlags; } return true; } static bool Cmd_SetServicesMask_Execute(COMMAND_ARGS) { TESNPC* npc = NULL; UInt32 serviceMask = 0; *result = 0; if (ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &serviceMask, &npc)) { if (!npc && thisObj) npc = (TESNPC*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESNPC, 0); if (npc) { npc->aiForm.SetOffersServices(serviceMask, true, true); } } return true; } static bool Cmd_SetTrainerSkill_Execute(COMMAND_ARGS) { TESNPC* npc = NULL; UInt32 actorVal = 0; *result = 0; if (ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &actorVal, &npc)) { if (!npc && thisObj) npc = (TESNPC*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESNPC, 0); if (npc && actorVal >= kActorVal_Armorer && actorVal <= kActorVal_Speechcraft) { FormChangeInfo info(kChangeForm_TrainerSkill, npc, scriptObj); g_FormChangesMap.Add(info); npc->aiForm.trainingSkill = actorVal - kActorVal_Armorer; } } return true; } static bool Cmd_SetTrainerLevel_Execute(COMMAND_ARGS) { TESNPC* npc = NULL; UInt32 nuLevel = 0; *result = 0; if (ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &nuLevel, &npc)) { if (!npc && thisObj) npc = (TESNPC*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESNPC, 0); if (npc) { FormChangeInfo info(kChangeForm_TrainerLevel, npc, scriptObj); g_FormChangesMap.Add(info); npc->aiForm.trainingLevel = nuLevel; } } return true; } static bool Cmd_GetNumPackages_Execute(COMMAND_ARGS) { TESActorBase* actorBase = NULL; *result = 0; if (ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &actorBase)) { if (!actorBase && thisObj) actorBase = (TESActorBase*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESActorBase, 0); if (actorBase) *result = PackageListVisitor(&actorBase->aiForm.packageList).Count(); } return true; } static bool Cmd_GetNthPackage_Execute(COMMAND_ARGS) { TESActorBase* actorBase = NULL; UInt32 whichPackage = 0; UInt32* refResult = (UInt32*)result; *refResult = 0; if (ExtractArgs(paramInfo, arg1, opcodeOffsetPtr, thisObj, arg3, scriptObj, eventList, &whichPackage, &actorBase)) { if (!actorBase && thisObj) actorBase = (TESActorBase*)Oblivion_DynamicCast(thisObj->baseForm, 0, RTTI_TESForm, RTTI_TESActorBase, 0); if (actorBase) { TESPackage* pkg = PackageListVisitor(&actorBase->aiForm.packageList).GetNthInfo(whichPackage); if (pkg) *refResult = pkg->refID; } } return true; } static HighProcess* ExtractHighProcess(TESObjectREFR* thisObj) { HighProcess* hiProc = NULL; MobileObject* mob = (MobileObject*)Oblivion_DynamicCast(thisObj, 0, RTTI_TESObjectREFR, RTTI_MobileObject, 0); if (mob) hiProc = (HighProcess*)Oblivion_DynamicCast(mob->process, 0, RTTI_BaseProcess, RTTI_HighProcess, 0); return hiProc; } static bool Cmd_IsAttacking_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc) *result = hiProc->IsAttacking() ? 1 : 0; return true; } static bool Cmd_IsBlocking_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc) *result = hiProc->IsBlocking() ? 1 : 0; return true; } static bool Cmd_IsRecoiling_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc) *result = hiProc->IsRecoiling() ? 1 : 0; return true; } static bool Cmd_IsDodging_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc) *result = hiProc->IsDodging() ? 1 : 0; return true; } static bool Cmd_IsStaggered_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc) *result = hiProc->IsStaggered() ? 1 : 0; return true; } static bool IsMovementFlagSet_Execute(TESObjectREFR* thisObj, UInt32 flag) { HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc && hiProc->IsMovementFlagSet(flag)) return true; else return false; } static bool Cmd_IsMovingForward_Execute(COMMAND_ARGS) { *result = IsMovementFlagSet_Execute(thisObj, HighProcess::kMovement_Forward) ? 1 : 0; return true; } static bool Cmd_IsMovingBackward_Execute(COMMAND_ARGS) { *result = IsMovementFlagSet_Execute(thisObj, HighProcess::kMovement_Backward) ? 1 : 0; return true; } static bool Cmd_IsMovingLeft_Execute(COMMAND_ARGS) { *result = IsMovementFlagSet_Execute(thisObj, HighProcess::kMovement_Left) ? 1 : 0; return true; } static bool Cmd_IsMovingRight_Execute(COMMAND_ARGS) { *result = IsMovementFlagSet_Execute(thisObj, HighProcess::kMovement_Right) ? 1 : 0; return true; } static bool Cmd_IsTurningLeft_Execute(COMMAND_ARGS) { *result = IsMovementFlagSet_Execute(thisObj, HighProcess::kMovement_TurnLeft) ? 1 : 0; return true; } static bool Cmd_IsTurningRight_Execute(COMMAND_ARGS) { *result = IsMovementFlagSet_Execute(thisObj, HighProcess::kMovement_TurnRight) ? 1 : 0; return true; } static bool Cmd_IsInAir_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc) { bhkCharacterController* ctrlr = hiProc->GetCharacterController(); if (ctrlr) { if (ctrlr->baseObject.IsInAir()) *result = 1; } } return true; } static bool Cmd_IsJumping_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc) { bhkCharacterController* ctrlr = hiProc->GetCharacterController(); if (ctrlr && ctrlr->baseObject.IsJumping()) *result = 1; } return true; } static bool Cmd_IsOnGround_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc) { bhkCharacterController* ctrlr = hiProc->GetCharacterController(); if (ctrlr && ctrlr->baseObject.IsOnGround()) *result = 1; } return true; } static bool Cmd_IsFlying_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc) { bhkCharacterController* ctrlr = hiProc->GetCharacterController(); if (ctrlr && ctrlr->baseObject.IsFlying()) *result = 1; } return true; } static bool Cmd_GetFallTimer_Execute(COMMAND_ARGS) { *result = 0; HighProcess* hiProc = ExtractHighProcess(thisObj); if (hiProc) { bhkCharacterController* ctrlr = hiProc->GetCharacterController(); if (ctrlr) *result = ctrlr->fallDamageTimer; } return true; } static MiddleHighProcess* ExtractMiddleHighProcess(TESObjectREFR* thisObj) { MiddleHighProcess* proc = NULL; MobileObject* mob = (MobileObject*)Oblivion_DynamicCast(thisObj, 0, RTTI_TESObjectREFR, RTTI_MobileObject, 0); if (mob) proc = (MiddleHighProcess*)Oblivion_DynamicCast(mob->process, 0, RTTI_BaseProcess, RTTI_MiddleHighProcess, 0); return proc; } ActorAnimData* GetActorAnimData(TESObjectREFR* callingObj) { if (callingObj == *g_thePlayer && (*g_thePlayer)->isThirdPerson == 0) return (*g_thePlayer)->firstPersonAnimData; else { MiddleHighProcess* proc = ExtractMiddleHighProcess(callingObj); if (proc) return proc->animData; } return NULL; } static bool Cmd_IsPowerAttacking_Execute(COMMAND_ARGS) { *result = 0; ActorAnimData* animData = GetActorAnimData(thisObj); if (animData) { if (animData->FindAnimInRange(TESAnimGroup::kAnimGroup_AttackPower, TESAnimGroup::kAnimGroup_AttackRightPower)) *result = 1; } return true; } static bool Cmd_IsCasting_Execute(COMMAND_ARGS) { *result = 0; ActorAnimData* animData = GetActorAnimData(thisObj); if (animData) { if (animData->FindAnimInRange(TESAnimGroup::kAnimGroup_CastSelf, TESAnimGroup::kAnimGroup_CastTargetAlt)) *result = 1; } return true; } static bool Cmd_IsAnimGroupPlaying_Execute(COMMAND_ARGS) { UInt32 whichGroup = -1; *result = 0; if (!ExtractArgs(EXTRACT_ARGS, &whichGroup)) return true; else if (whichGroup > TESAnimGroup::kAnimGroup_Max) return true; ActorAnimData* animData = GetActorAnimData(thisObj); if (animData) *result = (animData->FindAnimInRange(whichGroup)) ? 1 : 0; return true; } static bool Cmd_AnimPathIncludes_Execute(COMMAND_ARGS) { char subStr[512] = { 0 }; *result = 0; if (!ExtractArgs(EXTRACT_ARGS, &subStr)) return true; ActorAnimData* animData = GetActorAnimData(thisObj); if (animData) *result = (animData->PathsInclude(subStr)) ? 1 : 0; return true; } static bool Cmd_GetProcessLevel_Execute(COMMAND_ARGS) { *result = -1; if (thisObj) { MobileObject* mob = (MobileObject*)Oblivion_DynamicCast(thisObj, 0, RTTI_TESObjectREFR, RTTI_MobileObject, 0); if (mob && mob->process) *result = mob->process->GetProcessLevel(); } return true; } #endif static ParamInfo kParams_OneNPC[1] = { { "NPC", kParamType_NPC, 1 }, }; static ParamInfo kParams_OneIntOneOptionalNPC[2] = { { "RGB value", kParamType_Integer, 0 }, { "NPC", kParamType_NPC, 1 }, }; CommandInfo kCommandInfo_GetNumFollowers = { "GetNumFollowers", "", 0, "returns the number of characters following the calling actor", 1, 0, NULL, HANDLER(Cmd_GetNumFollowers_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_GetNthFollower = { "GetNthFollower", "", 0, "returns the nth actor following the calling actor", 1, 1, kParams_OneInt, HANDLER(Cmd_GetNthFollower_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_GetNthDetectedActor = { "GetNthDetectedActor", "", 0, "returns the nth actor detected by the calling actor", 1, 1, kParams_OneInt, HANDLER(Cmd_GetNthDetectedActor_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_GetNumDetectedActors = { "GetNumDetectedActors", "", 0, "returns the number of actors detected by the calling actor", 1, 0, NULL, HANDLER(Cmd_GetNumDetectedActors_Execute), Cmd_Default_Parse, NULL, 0 }; static ParamInfo kParams_SetDetectionState[2] = { { "actor", kParamType_Actor, 0 }, { "level", kParamType_Integer, 0 }, }; CommandInfo kCommandInfo_SetDetectionState = { "SetDetectionState", "", 0, "sets the level at which the calling actor detects the specified actor", 1, 2, kParams_SetDetectionState, HANDLER(Cmd_SetDetectionState_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersWeapons = { "OffersWeapons", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersWeapons_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersArmor = { "OffersArmor", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersArmor_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersBooks = { "OffersBooks", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersBooks_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersClothing = { "OffersClothing", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersClothing_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersIngredients = { "OffersIngredients", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersIngredients_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersLights = { "OffersLights", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersLights_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersApparatus = { "OffersApparatus", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersApparatus_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersMiscItems = { "OffersMiscItems", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersMiscItems_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersMagicItems = { "OffersMagicItems", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersMagicItems_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersSpells = { "OffersSpells", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersSpells_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersRecharging = { "OffersRecharging", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersRecharging_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersTraining = { "OffersTraining", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersTraining_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersPotions = { "OffersPotions", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersPotions_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersRepair = { "OffersRepair", "", 0, "returns 1 if the calling actor offers the specified service", 0, 1, kParams_OneNPC, HANDLER(Cmd_OffersRepair_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_GetTrainerSkill = { "GetTrainerSkill", "", 0, "returns the skill in which the actor offers training", 0, 1, kParams_OneNPC, HANDLER(Cmd_GetTrainerSkill_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_GetTrainerLevel = { "GetTrainerLevel", "", 0, "returns the level at which the actor offers training", 0, 1, kParams_OneNPC, HANDLER(Cmd_GetTrainerLevel_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_OffersServicesC = { "OffersServicesC", "", 0, "returns 1 if the calling actor offers the specified services", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_OffersServicesC_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersWeapons = { "SetOffersWeapons", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersWeapons_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersArmor = { "SetOffersArmor", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersArmor_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersClothing = { "SetOffersClothing", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersClothing_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersBooks = { "SetOffersBooks", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersBooks_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersLights = { "SetOffersLights", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersLights_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersPotions = { "SetOffersPotions", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersPotions_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersSpells = { "SetOffersSpells", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersSpells_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersIngredients = { "SetOffersIngredients", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersIngredients_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersApparatus = { "SetOffersApparatus", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersApparatus_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersMiscItems = { "SetOffersMiscItems", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersMiscItems_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersMagicItems = { "SetOffersMagicItems", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersMagicItems_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersTraining = { "SetOffersTraining", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersTraining_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersRepair = { "SetOffersRepair", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersRepair_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersRecharging = { "SetOffersRecharging", "", 0, "sets the specified offers services flag for the NPC", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetOffersRecharging_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetTrainerLevel = { "SetTrainerLevel", "", 0, "sets the level at which the NPC offers training", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetTrainerLevel_Execute), Cmd_Default_Parse, NULL, 0 }; static ParamInfo kParams_SetTrainerSkill[2] = { { "skill", kParamType_ActorValue, 0 }, { "npc", kParamType_NPC, 1 }, }; CommandInfo kCommandInfo_SetTrainerSkill = { "SetTrainerSkill", "", 0, "sets the skill in which the NPC offers training", 0, 2, kParams_SetTrainerSkill, HANDLER(Cmd_SetTrainerSkill_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_SetOffersServicesC = { "SetServicesMask", "SetOffersServicesC", 0, "sets the services offered by the npc", 0, 2, kParams_OneIntOneOptionalNPC, HANDLER(Cmd_SetServicesMask_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_GetServicesMask = { "GetServicesMask", "GetServicesC", 0, "returns the code for all services offered by the npc", 0, 1, kParams_OneNPC, HANDLER(Cmd_GetServicesMask_Execute), Cmd_Default_Parse, NULL, 0 }; static ParamInfo kParams_OneOptionalActorBase[1] = { { "actor", kParamType_ActorBase, 1 }, }; static ParamInfo kParams_OneIntOneOptionalActorBase[2] = { { "int", kParamType_Integer, 0 }, { "actor", kParamType_ActorBase, 1 }, }; CommandInfo kCommandInfo_GetNumPackages = { "GetNumPackages", "", 0, "returns the number of packages in the actor's package list", 0, 1, kParams_OneOptionalActorBase, HANDLER(Cmd_GetNumPackages_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_GetNthPackage = { "GetNthPackage", "", 0, "returns the nth package in the actor's package list", 0, 2, kParams_OneIntOneOptionalActorBase, HANDLER(Cmd_GetNthPackage_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsAttacking = { "IsAttacking", "", 0, "returns true if the calling actor is attacking", 1, 0, NULL, HANDLER(Cmd_IsAttacking_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsBlocking = { "IsBlocking", "", 0, "returns true if the calling actor is Blocking", 1, 0, NULL, HANDLER(Cmd_IsBlocking_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsDodging = { "IsDodging", "", 0, "returns true if the calling actor is Dodging", 1, 0, NULL, HANDLER(Cmd_IsDodging_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsRecoiling = { "IsRecoiling", "", 0, "returns true if the calling actor is Recoiling", 1, 0, NULL, HANDLER(Cmd_IsRecoiling_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsStaggered = { "IsStaggered", "", 0, "returns true if the calling actor is Staggered", 1, 0, NULL, HANDLER(Cmd_IsStaggered_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsMovingForward = { "IsMovingForward", "", 0, "returns 1 if the calling actor is performing the specified movement", 1, 0, NULL, HANDLER(Cmd_IsMovingForward_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsMovingBackward = { "IsMovingBackward", "", 0, "returns 1 if the calling actor is performing the specified movement", 1, 0, NULL, HANDLER(Cmd_IsMovingBackward_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsMovingLeft = { "IsMovingLeft", "", 0, "returns 1 if the calling actor is performing the specified movement", 1, 0, NULL, HANDLER(Cmd_IsMovingLeft_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsMovingRight = { "IsMovingRight", "", 0, "returns 1 if the calling actor is performing the specified movement", 1, 0, NULL, HANDLER(Cmd_IsMovingRight_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsTurningLeft = { "IsTurningLeft", "", 0, "returns 1 if the calling actor is performing the specified movement", 1, 0, NULL, HANDLER(Cmd_IsTurningLeft_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsTurningRight = { "IsTurningRight", "", 0, "returns 1 if the calling actor is performing the specified movement", 1, 0, NULL, HANDLER(Cmd_IsTurningRight_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsInAir = { "IsInAir", "", 0, "returns 1 if the calling actor is in the air", 1, 0, NULL, HANDLER(Cmd_IsInAir_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsJumping = { "IsJumping", "", 0, "returns 1 if the calling actor is jumping", 1, 0, NULL, HANDLER(Cmd_IsJumping_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsOnGround = { "IsOnGround", "", 0, "returns 1 if the calling actor is on the ground", 1, 0, NULL, HANDLER(Cmd_IsOnGround_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsFlying = { "IsFlying", "", 0, "returns 1 if the calling actor is flying", 1, 0, NULL, HANDLER(Cmd_IsFlying_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_GetFallTimer = { "GetFallTimer", "GetFallDamageTimer", 0, "returns the length of time for which the calling actor has been falling", 1, 0, NULL, HANDLER(Cmd_GetFallTimer_Execute), Cmd_Default_Parse, NULL, 0 }; CommandInfo kCommandInfo_IsCasting = { "IsCasting", "", 0, "returns true if the calling actor is casting a spell", 1, 0, NULL, HANDLER(Cmd_IsCasting_Execute), Cmd_Default_Parse, NULL, 0 }; static ParamInfo kParams_OneAnimGroup[1] = { { "anim group", kParamType_AnimationGroup, 0 }, }; DEFINE_COMMAND(IsPowerAttacking, returns true if the calling actor is executing a power attack, 1, 0, NULL); DEFINE_COMMAND(IsAnimGroupPlaying, returns true if the actor is playing the specified anim group, 1, 1, kParams_OneAnimGroup); DEFINE_COMMAND(AnimPathIncludes, returns true if the actor is playing an anim containing the substring, 1, 1, kParams_OneString); static ParamInfo kParams_Package[1] = { { "package", kParamType_AIPackage, 0 }, }; DEFINE_COMMAND(GetProcessLevel, returns the process level of the calling reference, 1, 0, NULL);
[ "masterfreek64@2644d07b-d655-0410-af38-4bee65694944" ]
[ [ [ 1, 1708 ] ] ]
6b68e973a849a4cb9f693cf0cea53ab8c3d1d35c
2bcfdc7adc9d794391e0f79e4dab5c481ca5a09b
/applications/hac-widgets/designer/src/customwidgetinterface.h
ea4f2d72449beced622e6844bb731cef5cf72702
[]
no_license
etop-wesley/hac
592912a7c4023ba8bd2c25ae5de9c18d90c79b0b
ab82cb047ed15346c25ce01faff00815256b00b7
refs/heads/master
2021-01-02T22:45:32.603368
2010-09-01T08:38:01
2010-09-01T08:38:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,659
h
#ifndef _CUSTOMWIDGETINTERFACE_H_ #define _CUSTOMWIDGETINTERFACE_H_ #include <QDesignerCustomWidgetInterface> /* * Note: That the only part of the class definition * that is specific to this particular custom widget is the class name. */ class CustomWidgetInterface : public QObject, public QDesignerCustomWidgetInterface { /* * The Q_OBJECT macro must appear in the private section of a class definition * that declares its own signals and slots or that uses other services * provided by Qt's meta-object system. */ Q_OBJECT /* * since we are implementing an interface, * we must ensure that it's made known to the meta object system * using the Q_INTERFACES( ) macro. * This enables Qt Designer to use the qobject_cast( ) function * to query for supported interfaces using nothing but a QObject pointer. */ Q_INTERFACES(QDesignerCustomWidgetInterface) public: CustomWidgetInterface(QObject *parent = 0); virtual bool isContainer() const; virtual bool isInitialized() const; virtual QIcon icon() const; virtual QString domXml() const; virtual QString group() const; virtual QString includeFile() const; virtual QString name() const; virtual QString toolTip() const; virtual QString whatsThis() const; virtual QWidget *createWidget(QWidget *parent); virtual void initialize(QDesignerFormEditorInterface *core); protected: bool m_isContainer; QString m_group; QString m_name; QString m_include; QString m_toolTip; QString m_whatsThis; QString m_domXml; QIcon m_icon; private: bool m_initialized; }; #endif // _CUSTOMWIDGETINTERFACE_H_
[ "wesley@debian.(none)" ]
[ [ [ 1, 57 ] ] ]
eca9aee75b2d1cd6a27345f0ef04d0e9b597022e
24bc1634133f5899f7db33e5d9692ba70940b122
/extlibs/RakNet/include/DS_BPlusTree.h
210cbd61314c01975a2a8df7611b61026a6d0450
[]
no_license
deft-code/ammo
9a9cd9bd5fb75ac1b077ad748617613959dbb7c9
fe4139187dd1d371515a2d171996f81097652e99
refs/heads/master
2016-09-05T08:48:51.786465
2009-10-09T05:49:00
2009-10-09T05:49:00
32,252,326
0
0
null
null
null
null
UTF-8
C++
false
false
34,572
h
#ifndef __B_PLUS_TREE_CPP #define __B_PLUS_TREE_CPP #include "DS_MemoryPool.h" #include "DS_Queue.h" #include <stdio.h> #include "Export.h" // Java // http://www.seanster.com/BplusTree/BplusTree.html // Overview // http://babbage.clarku.edu/~achou/cs160/B+Trees/B+Trees.htm // Deletion // http://dbpubs.stanford.edu:8090/pub/1995-19 #ifdef _MSC_VER #pragma warning( push ) #endif #include "RakMemoryOverride.h" /// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures /// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. namespace DataStructures { /// Used in the BPlusTree. Used for both leaf and index nodes. /// Don't use a constructor or destructor, due to the memory pool I am using template <class KeyType, class DataType, int order> struct RAK_DLL_EXPORT Page { // We use the same data structure for both leaf and index nodes. It uses a little more memory for index nodes but reduces // memory fragmentation, allocations, and deallocations. bool isLeaf; // Used for both leaf and index nodes. // For a leaf it means the number of elements in data // For an index it means the number of keys and is one less than the number of children pointers. int size; // Used for both leaf and index nodes. KeyType keys[order]; // Used only for leaf nodes. Data is the actual data, while next is the pointer to the next leaf (for B+) DataType data[order]; Page<KeyType, DataType, order> *next; Page<KeyType, DataType, order> *previous; // Used only for index nodes. Pointers to the children of this node. Page *children[order+1]; }; /// A BPlus tree /// Written with efficiency and speed in mind. template <class KeyType, class DataType, int order> class RAK_DLL_EXPORT BPlusTree { public: struct ReturnAction { KeyType key1; KeyType key2; enum { NO_ACTION, REPLACE_KEY1_WITH_KEY2, PUSH_KEY_TO_PARENT, SET_BRANCH_KEY, } action; // 0=none, 1=replace key1 with key2 }; BPlusTree(); ~BPlusTree(); void SetPoolPageSize(int size); // Set the page size for the memory pool. Optionsl bool Get(const KeyType key, DataType &out) const; bool Delete(const KeyType key); bool Delete(const KeyType key, DataType &out); bool Insert(const KeyType key, const DataType &data); void Clear(void); unsigned Size(void) const; bool IsEmpty(void) const; Page<KeyType, DataType, order> *GetListHead(void) const; DataType GetDataHead(void) const; void PrintLeaves(void); void ForEachLeaf(void (*func)(Page<KeyType, DataType, order> * leaf, int index)); void ForEachData(void (*func)(DataType input, int index)); void PrintGraph(void); void ValidateTree(void); protected: void ValidateTreeRecursive(Page<KeyType, DataType, order> *cur); void DeleteFromPageAtIndex(const int index, Page<KeyType, DataType, order> *cur); static void PrintLeaf(Page<KeyType, DataType, order> * leaf, int index); void FreePages(void); bool GetIndexOf(const KeyType key, Page<KeyType, DataType, order> *page, int *out) const; void ShiftKeysLeft(Page<KeyType, DataType, order> *cur); bool CanRotateLeft(Page<KeyType, DataType, order> *cur, int childIndex); bool CanRotateRight(Page<KeyType, DataType, order> *cur, int childIndex); void RotateRight(Page<KeyType, DataType, order> *cur, int childIndex, ReturnAction *returnAction); void RotateLeft(Page<KeyType, DataType, order> *cur, int childIndex, ReturnAction *returnAction); Page<KeyType, DataType, order>* InsertIntoNode(const KeyType key, const DataType &childData, int insertionIndex, Page<KeyType, DataType, order> *nodeData, Page<KeyType, DataType, order> *cur, ReturnAction* returnAction); Page<KeyType, DataType, order>* InsertBranchDown(const KeyType key, const DataType &data,Page<KeyType, DataType, order> *cur, ReturnAction* returnAction, bool *success); Page<KeyType, DataType, order>* GetLeafFromKey(const KeyType key) const; bool FindDeleteRebalance(const KeyType key, Page<KeyType, DataType, order> *cur, bool *underflow, KeyType rightRootKey, ReturnAction *returnAction, DataType &out); bool FixUnderflow(int branchIndex, Page<KeyType, DataType, order> *cur, KeyType rightRootKey, ReturnAction *returnAction); void ShiftNodeLeft(Page<KeyType, DataType, order> *cur); void ShiftNodeRight(Page<KeyType, DataType, order> *cur); MemoryPool<Page<KeyType, DataType, order> > pagePool; Page<KeyType, DataType, order> *root, *leftmostLeaf; }; template<class KeyType, class DataType, int order> BPlusTree<KeyType, DataType, order>::BPlusTree () { assert(order>1); root=0; leftmostLeaf=0; } template<class KeyType, class DataType, int order> BPlusTree<KeyType, DataType, order>::~BPlusTree () { Clear(); } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::SetPoolPageSize(int size) { pagePool.SetPageSize(size); } template<class KeyType, class DataType, int order> bool BPlusTree<KeyType, DataType, order>::Get(const KeyType key, DataType &out) const { if (root==0) return false; Page<KeyType, DataType, order>* leaf = GetLeafFromKey(key); int childIndex; if (GetIndexOf(key, leaf, &childIndex)) { out=leaf->data[childIndex]; return true; } return false; } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::DeleteFromPageAtIndex(const int index, Page<KeyType, DataType, order> *cur) { int i; for (i=index; i < cur->size-1; i++) cur->keys[i]=cur->keys[i+1]; if (cur->isLeaf) { for (i=index; i < cur->size-1; i++) cur->data[i]=cur->data[i+1]; } else { for (i=index; i < cur->size-1; i++) cur->children[i+1]=cur->children[i+2]; } cur->size--; } template<class KeyType, class DataType, int order> bool BPlusTree<KeyType, DataType, order>::Delete(const KeyType key) { DataType temp; return Delete(key, temp); } template<class KeyType, class DataType, int order> bool BPlusTree<KeyType, DataType, order>::Delete(const KeyType key, DataType &out) { if (root==0) return false; ReturnAction returnAction; returnAction.action=ReturnAction::NO_ACTION; int childIndex; bool underflow=false; if (root==leftmostLeaf) { if (GetIndexOf(key, root, &childIndex)==false) return false; out=root->data[childIndex]; DeleteFromPageAtIndex(childIndex,root); if (root->size==0) { pagePool.Release(root); root=0; leftmostLeaf=0; } return true; } else if (FindDeleteRebalance(key, root, &underflow,root->keys[0], &returnAction, out)==false) return false; // assert(returnAction.action==ReturnAction::NO_ACTION); if (underflow && root->size==0) { // Move the root down. Page<KeyType, DataType, order> *oldRoot=root; root=root->children[0]; pagePool.Release(oldRoot); // memset(oldRoot,0,sizeof(root)); } return true; } template<class KeyType, class DataType, int order> bool BPlusTree<KeyType, DataType, order>::FindDeleteRebalance(const KeyType key, Page<KeyType, DataType, order> *cur, bool *underflow, KeyType rightRootKey, ReturnAction *returnAction, DataType &out) { // Get index of child to follow. int branchIndex, childIndex; if (GetIndexOf(key, cur, &childIndex)) branchIndex=childIndex+1; else branchIndex=childIndex; // If child is not a leaf, call recursively if (cur->children[branchIndex]->isLeaf==false) { if (branchIndex<cur->size) rightRootKey=cur->keys[branchIndex]; // Shift right to left else rightRootKey=cur->keys[branchIndex-1]; // Shift center to left if (FindDeleteRebalance(key, cur->children[branchIndex], underflow, rightRootKey, returnAction, out)==false) return false; // Call again in case the root key changed if (branchIndex<cur->size) rightRootKey=cur->keys[branchIndex]; // Shift right to left else rightRootKey=cur->keys[branchIndex-1]; // Shift center to left if (returnAction->action==ReturnAction::SET_BRANCH_KEY && branchIndex!=childIndex) { returnAction->action=ReturnAction::NO_ACTION; cur->keys[childIndex]=returnAction->key1; if (branchIndex<cur->size) rightRootKey=cur->keys[branchIndex]; // Shift right to left else rightRootKey=cur->keys[branchIndex-1]; // Shift center to left } } else { // If child is a leaf, get the index of the key. If the item is not found, cancel delete. if (GetIndexOf(key, cur->children[branchIndex], &childIndex)==false) return false; // Delete: // Remove childIndex from the child at branchIndex out=cur->children[branchIndex]->data[childIndex]; DeleteFromPageAtIndex(childIndex, cur->children[branchIndex]); if (childIndex==0) { if (branchIndex>0) cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; if (branchIndex==0) { returnAction->action=ReturnAction::SET_BRANCH_KEY; returnAction->key1=cur->children[0]->keys[0]; } } if (cur->children[branchIndex]->size < order/2) *underflow=true; else *underflow=false; } // Fix underflow: if (*underflow) { *underflow=FixUnderflow(branchIndex, cur, rightRootKey, returnAction); } return true; } template<class KeyType, class DataType, int order> bool BPlusTree<KeyType, DataType, order>::FixUnderflow(int branchIndex, Page<KeyType, DataType, order> *cur, KeyType rightRootKey, ReturnAction *returnAction) { // Borrow from a neighbor that has excess. Page<KeyType, DataType, order> *source; Page<KeyType, DataType, order> *dest; if (branchIndex>0 && cur->children[branchIndex-1]->size > order/2) { dest=cur->children[branchIndex]; source=cur->children[branchIndex-1]; // Left has excess ShiftNodeRight(dest); if (dest->isLeaf) { dest->keys[0]=source->keys[source->size-1]; dest->data[0]=source->data[source->size-1]; } else { dest->children[0]=source->children[source->size]; dest->keys[0]=cur->keys[branchIndex-1]; } // Update the parent key for the child (middle) cur->keys[branchIndex-1]=source->keys[source->size-1]; source->size--; // if (branchIndex==0) // { // returnAction->action=ReturnAction::SET_BRANCH_KEY; // returnAction->key1=dest->keys[0]; // } // No underflow return false; } else if (branchIndex<cur->size && cur->children[branchIndex+1]->size > order/2) { dest=cur->children[branchIndex]; source=cur->children[branchIndex+1]; // Right has excess if (dest->isLeaf) { dest->keys[dest->size]=source->keys[0]; dest->data[dest->size]=source->data[0]; // The first key in the leaf after shifting is the parent key for the right branch cur->keys[branchIndex]=source->keys[1]; #ifdef _MSC_VER #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant #endif if (order<=3 && dest->size==0) { if (branchIndex==0) { returnAction->action=ReturnAction::SET_BRANCH_KEY; returnAction->key1=dest->keys[0]; } else cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; } } else { if (returnAction->action==ReturnAction::NO_ACTION) { returnAction->action=ReturnAction::SET_BRANCH_KEY; returnAction->key1=dest->keys[0]; } dest->keys[dest->size]=rightRootKey; dest->children[dest->size+1]=source->children[0]; // The shifted off key is the leftmost key for a node cur->keys[branchIndex]=source->keys[0]; } dest->size++; ShiftNodeLeft(source); //cur->keys[branchIndex]=source->keys[0]; // returnAction->action=ReturnAction::SET_BRANCH_KEY; // returnAction->key1=dest->keys[dest->size-1]; // No underflow return false; } else { int sourceIndex; // If no neighbors have excess, merge two branches. // // To merge two leaves, just copy the data and keys over. // // To merge two branches, copy the pointers and keys over, using rightRootKey as the key for the extra pointer if (branchIndex<cur->size) { // Merge right child to current child and delete right child. dest=cur->children[branchIndex]; source=cur->children[branchIndex+1]; } else { // Move current child to left and delete current child dest=cur->children[branchIndex-1]; source=cur->children[branchIndex]; } // Merge if (dest->isLeaf) { for (sourceIndex=0; sourceIndex<source->size; sourceIndex++) { dest->keys[dest->size]=source->keys[sourceIndex]; dest->data[dest->size++]=source->data[sourceIndex]; } } else { // We want the tree root key of the source, not the current. dest->keys[dest->size]=rightRootKey; dest->children[dest->size++ + 1]=source->children[0]; for (sourceIndex=0; sourceIndex<source->size; sourceIndex++) { dest->keys[dest->size]=source->keys[sourceIndex]; dest->children[dest->size++ + 1]=source->children[sourceIndex + 1]; } } #ifdef _MSC_VER #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant #endif if (order<=3 && branchIndex>0 && cur->children[branchIndex]->isLeaf) // With order==2 it is possible to delete data[0], which is not possible with higher orders. cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; if (branchIndex<cur->size) { // Update the parent key, removing the source (right) DeleteFromPageAtIndex(branchIndex, cur); } else { if (branchIndex>0) { // Update parent key, removing the source (current) DeleteFromPageAtIndex(branchIndex-1, cur); } } if (branchIndex==0 && dest->isLeaf) { returnAction->action=ReturnAction::SET_BRANCH_KEY; returnAction->key1=dest->keys[0]; } if (source==leftmostLeaf) leftmostLeaf=source->next; if (source->isLeaf) { if (source->previous) source->previous->next=source->next; if (source->next) source->next->previous=source->previous; } // Free the source node pagePool.Release(source); // memset(source,0,sizeof(root)); // Return underflow or not of parent. return cur->size < order/2; } } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::ShiftNodeRight(Page<KeyType, DataType, order> *cur) { int i; for (i=cur->size; i>0; i--) cur->keys[i]=cur->keys[i-1]; if (cur->isLeaf) { for (i=cur->size; i>0; i--) cur->data[i]=cur->data[i-1]; } else { for (i=cur->size+1; i>0; i--) cur->children[i]=cur->children[i-1]; } cur->size++; } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::ShiftNodeLeft(Page<KeyType, DataType, order> *cur) { int i; for (i=0; i < cur->size-1; i++) cur->keys[i]=cur->keys[i+1]; if (cur->isLeaf) { for (i=0; i < cur->size; i++) cur->data[i]=cur->data[i+1]; } else { for (i=0; i < cur->size; i++) cur->children[i]=cur->children[i+1]; } cur->size--; } template<class KeyType, class DataType, int order> Page<KeyType, DataType, order>* BPlusTree<KeyType, DataType, order>::InsertIntoNode(const KeyType key, const DataType &leafData, int insertionIndex, Page<KeyType, DataType, order> *nodeData, Page<KeyType, DataType, order> *cur, ReturnAction* returnAction) { int i; if (cur->size < order) { for (i=cur->size; i > insertionIndex; i--) cur->keys[i]=cur->keys[i-1]; if (cur->isLeaf) { for (i=cur->size; i > insertionIndex; i--) cur->data[i]=cur->data[i-1]; } else { for (i=cur->size+1; i > insertionIndex+1; i--) cur->children[i]=cur->children[i-1]; } cur->keys[insertionIndex]=key; if (cur->isLeaf) cur->data[insertionIndex]=leafData; else cur->children[insertionIndex+1]=nodeData; cur->size++; } else { Page<KeyType, DataType, order>* newPage = pagePool.Allocate(); newPage->isLeaf=cur->isLeaf; if (cur->isLeaf) { newPage->next=cur->next; if (cur->next) cur->next->previous=newPage; newPage->previous=cur; cur->next=newPage; } int destIndex, sourceIndex; if (insertionIndex>=(order+1)/2) { destIndex=0; sourceIndex=order/2; for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++) { newPage->keys[destIndex]=cur->keys[sourceIndex]; } newPage->keys[destIndex++]=key; for (; sourceIndex < order; sourceIndex++, destIndex++) { newPage->keys[destIndex]=cur->keys[sourceIndex]; } destIndex=0; sourceIndex=order/2; if (cur->isLeaf) { for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++) { newPage->data[destIndex]=cur->data[sourceIndex]; } newPage->data[destIndex++]=leafData; for (; sourceIndex < order; sourceIndex++, destIndex++) { newPage->data[destIndex]=cur->data[sourceIndex]; } } else { for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++) { newPage->children[destIndex]=cur->children[sourceIndex+1]; } newPage->children[destIndex++]=nodeData; // sourceIndex+1 is sort of a hack but it works - because there is one extra child than keys // skip past the last child for cur for (; sourceIndex+1 < cur->size+1; sourceIndex++, destIndex++) { newPage->children[destIndex]=cur->children[sourceIndex+1]; } // the first key is the middle key. Remove it from the page and push it to the parent returnAction->action=ReturnAction::PUSH_KEY_TO_PARENT; returnAction->key1=newPage->keys[0]; for (int i=0; i < destIndex-1; i++) newPage->keys[i]=newPage->keys[i+1]; } cur->size=order/2; } else { destIndex=0; sourceIndex=(order+1)/2-1; for (; sourceIndex < order; sourceIndex++, destIndex++) newPage->keys[destIndex]=cur->keys[sourceIndex]; destIndex=0; if (cur->isLeaf) { sourceIndex=(order+1)/2-1; for (; sourceIndex < order; sourceIndex++, destIndex++) newPage->data[destIndex]=cur->data[sourceIndex]; } else { sourceIndex=(order+1)/2; for (; sourceIndex < order+1; sourceIndex++, destIndex++) newPage->children[destIndex]=cur->children[sourceIndex]; // the first key is the middle key. Remove it from the page and push it to the parent returnAction->action=ReturnAction::PUSH_KEY_TO_PARENT; returnAction->key1=newPage->keys[0]; for (int i=0; i < destIndex-1; i++) newPage->keys[i]=newPage->keys[i+1]; } cur->size=(order+1)/2-1; if (cur->size) { bool b = GetIndexOf(key, cur, &insertionIndex); (void) b; assert(b==false); } else insertionIndex=0; InsertIntoNode(key, leafData, insertionIndex, nodeData, cur, returnAction); } newPage->size=destIndex; return newPage; } return 0; } template<class KeyType, class DataType, int order> bool BPlusTree<KeyType, DataType, order>::CanRotateLeft(Page<KeyType, DataType, order> *cur, int childIndex) { return childIndex>0 && cur->children[childIndex-1]->size<order; } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::RotateLeft(Page<KeyType, DataType, order> *cur, int childIndex, ReturnAction *returnAction) { Page<KeyType, DataType, order> *dest = cur->children[childIndex-1]; Page<KeyType, DataType, order> *source = cur->children[childIndex]; returnAction->key1=source->keys[0]; dest->keys[dest->size]=source->keys[0]; dest->data[dest->size]=source->data[0]; dest->size++; for (int i=0; i < source->size-1; i++) { source->keys[i]=source->keys[i+1]; source->data[i]=source->data[i+1]; } source->size--; cur->keys[childIndex-1]=source->keys[0]; returnAction->key2=source->keys[0]; } template<class KeyType, class DataType, int order> bool BPlusTree<KeyType, DataType, order>::CanRotateRight(Page<KeyType, DataType, order> *cur, int childIndex) { return childIndex < cur->size && cur->children[childIndex+1]->size<order; } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::RotateRight(Page<KeyType, DataType, order> *cur, int childIndex, ReturnAction *returnAction) { Page<KeyType, DataType, order> *dest = cur->children[childIndex+1]; Page<KeyType, DataType, order> *source = cur->children[childIndex]; returnAction->key1=dest->keys[0]; for (int i= dest->size; i > 0; i--) { dest->keys[i]=dest->keys[i-1]; dest->data[i]=dest->data[i-1]; } dest->keys[0]=source->keys[source->size-1]; dest->data[0]=source->data[source->size-1]; dest->size++; source->size--; cur->keys[childIndex]=dest->keys[0]; returnAction->key2=dest->keys[0]; } template<class KeyType, class DataType, int order> Page<KeyType, DataType, order>* BPlusTree<KeyType, DataType, order>::GetLeafFromKey(const KeyType key) const { Page<KeyType, DataType, order>* cur = root; int childIndex; while (cur->isLeaf==false) { // When searching, if we match the exact key we go down the pointer after that index if (GetIndexOf(key, cur, &childIndex)) childIndex++; cur = cur->children[childIndex]; } return cur; } template<class KeyType, class DataType, int order> Page<KeyType, DataType, order>* BPlusTree<KeyType, DataType, order>::InsertBranchDown(const KeyType key, const DataType &data,Page<KeyType, DataType, order> *cur, ReturnAction *returnAction, bool *success) { int childIndex; int branchIndex; if (GetIndexOf(key, cur, &childIndex)) branchIndex=childIndex+1; else branchIndex=childIndex; Page<KeyType, DataType, order>* newPage; if (cur->isLeaf==false) { if (cur->children[branchIndex]->isLeaf==true && cur->children[branchIndex]->size==order) { if (branchIndex==childIndex+1) { *success=false; return 0; // Already exists } if (CanRotateLeft(cur, branchIndex)) { returnAction->action=ReturnAction::REPLACE_KEY1_WITH_KEY2; if (key > cur->children[branchIndex]->keys[0]) { RotateLeft(cur, branchIndex, returnAction); int insertionIndex; GetIndexOf(key, cur->children[branchIndex], &insertionIndex); InsertIntoNode(key, data, insertionIndex, 0, cur->children[branchIndex], 0); } else { // Move head element to left and replace it with key,data Page<KeyType, DataType, order>* dest=cur->children[branchIndex-1]; Page<KeyType, DataType, order>* source=cur->children[branchIndex]; returnAction->key1=source->keys[0]; returnAction->key2=key; dest->keys[dest->size]=source->keys[0]; dest->data[dest->size]=source->data[0]; dest->size++; source->keys[0]=key; source->data[0]=data; } cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; return 0; } else if (CanRotateRight(cur, branchIndex)) { returnAction->action=ReturnAction::REPLACE_KEY1_WITH_KEY2; if (key < cur->children[branchIndex]->keys[cur->children[branchIndex]->size-1]) { RotateRight(cur, branchIndex, returnAction); int insertionIndex; GetIndexOf(key, cur->children[branchIndex], &insertionIndex); InsertIntoNode(key, data, insertionIndex, 0, cur->children[branchIndex], 0); } else { // Insert to the head of the right leaf instead and change our key returnAction->key1=cur->children[branchIndex+1]->keys[0]; InsertIntoNode(key, data, 0, 0, cur->children[branchIndex+1], 0); returnAction->key2=key; } cur->keys[branchIndex]=cur->children[branchIndex+1]->keys[0]; return 0; } } newPage=InsertBranchDown(key,data,cur->children[branchIndex], returnAction, success); if (returnAction->action==ReturnAction::REPLACE_KEY1_WITH_KEY2) { if (branchIndex>0 && cur->keys[branchIndex-1]==returnAction->key1) cur->keys[branchIndex-1]=returnAction->key2; } if (newPage) { if (newPage->isLeaf==false) { assert(returnAction->action==ReturnAction::PUSH_KEY_TO_PARENT); newPage->size--; return InsertIntoNode(returnAction->key1, data, branchIndex, newPage, cur, returnAction); } else { return InsertIntoNode(newPage->keys[0], data, branchIndex, newPage, cur, returnAction); } } } else { if (branchIndex==childIndex+1) { *success=false; return 0; // Already exists } else { return InsertIntoNode(key, data, branchIndex, 0, cur, returnAction); } } return 0; } template<class KeyType, class DataType, int order> bool BPlusTree<KeyType, DataType, order>::Insert(const KeyType key, const DataType &data) { if (root==0) { // Allocate root and make root a leaf root = pagePool.Allocate(); root->isLeaf=true; leftmostLeaf=root; root->size=1; root->keys[0]=key; root->data[0]=data; root->next=0; root->previous=0; } else { bool success=true; ReturnAction returnAction; returnAction.action=ReturnAction::NO_ACTION; Page<KeyType, DataType, order>* newPage = InsertBranchDown(key, data, root, &returnAction, &success); if (success==false) return false; if (newPage) { KeyType newKey; if (newPage->isLeaf==false) { // One key is pushed up through the stack. I store that at keys[0] but it has to be removed for the page to be correct assert(returnAction.action==ReturnAction::PUSH_KEY_TO_PARENT); newKey=returnAction.key1; newPage->size--; } else newKey = newPage->keys[0]; // propagate the root Page<KeyType, DataType, order>* newRoot = pagePool.Allocate(); newRoot->isLeaf=false; newRoot->size=1; newRoot->keys[0]=newKey; newRoot->children[0]=root; newRoot->children[1]=newPage; root=newRoot; } } return true; } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::ShiftKeysLeft(Page<KeyType, DataType, order> *cur) { int i; for (i=0; i < cur->size; i++) cur->keys[i]=cur->keys[i+1]; } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::Clear(void) { if (root) { FreePages(); leftmostLeaf=0; root=0; } pagePool.Clear(); } template<class KeyType, class DataType, int order> unsigned BPlusTree<KeyType, DataType, order>::Size(void) const { int count=0; DataStructures::Page<KeyType, DataType, order> *cur = GetListHead(); while (cur) { count+=cur->size; cur=cur->next; } return count; } template<class KeyType, class DataType, int order> bool BPlusTree<KeyType, DataType, order>::IsEmpty(void) const { return root==0; } template<class KeyType, class DataType, int order> bool BPlusTree<KeyType, DataType, order>::GetIndexOf(const KeyType key, Page<KeyType, DataType, order> *page, int *out) const { assert(page->size>0); int index, upperBound, lowerBound; upperBound=page->size-1; lowerBound=0; index = page->size/2; #ifdef _MSC_VER #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant #endif while (1) { if (key==page->keys[index]) { *out=index; return true; } else if (key<page->keys[index]) upperBound=index-1; else lowerBound=index+1; index=lowerBound+(upperBound-lowerBound)/2; if (lowerBound>upperBound) { *out=lowerBound; return false; // No match } } } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::FreePages(void) { DataStructures::Queue<DataStructures::Page<KeyType, DataType, order> *> queue; DataStructures::Page<KeyType, DataType, order> *ptr; int i; queue.Push(root); while (queue.Size()) { ptr=queue.Pop(); if (ptr->isLeaf==false) { for (i=0; i < ptr->size+1; i++) queue.Push(ptr->children[i]); } pagePool.Release(ptr); // memset(ptr,0,sizeof(root)); }; } template<class KeyType, class DataType, int order> Page<KeyType, DataType, order> *BPlusTree<KeyType, DataType, order>::GetListHead(void) const { return leftmostLeaf; } template<class KeyType, class DataType, int order> DataType BPlusTree<KeyType, DataType, order>::GetDataHead(void) const { return leftmostLeaf->data[0]; } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::ForEachLeaf(void (*func)(Page<KeyType, DataType, order> * leaf, int index)) { int count=0; DataStructures::Page<KeyType, DataType, order> *cur = GetListHead(); while (cur) { func(cur, count++); cur=cur->next; } } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::ForEachData(void (*func)(DataType input, int index)) { int count=0,i; DataStructures::Page<KeyType, DataType, order> *cur = GetListHead(); while (cur) { for (i=0; i < cur->size; i++) func(cur->data[i], count++); cur=cur->next; } } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::PrintLeaf(Page<KeyType, DataType, order> * leaf, int index) { int i; RAKNET_DEBUG_PRINTF("%i] SELF=%p\n", index+1, leaf); for (i=0; i < leaf->size; i++) RAKNET_DEBUG_PRINTF(" %i. %i\n", i+1, leaf->data[i]); } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::PrintLeaves(void) { ForEachLeaf(PrintLeaf); } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::ValidateTree(void) { int i, last=-9999; DataStructures::Page<KeyType, DataType, order> *cur = GetListHead(); while (cur) { assert(cur->size>0); for (i=0; i < cur->size; i++) { assert(cur->data[i]==cur->keys[i]); if (last!=-9999) { assert(cur->data[i]>last); } last=cur->data[i]; } cur=cur->next; } if (root && root->isLeaf==false) ValidateTreeRecursive(root); } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::ValidateTreeRecursive(Page<KeyType, DataType, order> *cur) { assert(cur==root || cur->size>=order/2); if (cur->children[0]->isLeaf) { assert(cur->children[0]->keys[0] < cur->keys[0]); for (int i=0; i < cur->size; i++) { assert(cur->children[i+1]->keys[0]==cur->keys[i]); } } else { for (int i=0; i < cur->size+1; i++) ValidateTreeRecursive(cur->children[i]); } } template<class KeyType, class DataType, int order> void BPlusTree<KeyType, DataType, order>::PrintGraph(void) { DataStructures::Queue<DataStructures::Page<KeyType, DataType, order> *> queue; queue.Push(root); queue.Push(0); DataStructures::Page<KeyType, DataType, order> *ptr; int i,j; if (root) { RAKNET_DEBUG_PRINTF("%p(", root); for (i=0; i < root->size; i++) { RAKNET_DEBUG_PRINTF("%i ", root->keys[i]); } RAKNET_DEBUG_PRINTF(") "); RAKNET_DEBUG_PRINTF("\n"); } while (queue.Size()) { ptr=queue.Pop(); if (ptr==0) RAKNET_DEBUG_PRINTF("\n"); else if (ptr->isLeaf==false) { for (i=0; i < ptr->size+1; i++) { RAKNET_DEBUG_PRINTF("%p(", ptr->children[i]); //RAKNET_DEBUG_PRINTF("(", ptr->children[i]); for (j=0; j < ptr->children[i]->size; j++) RAKNET_DEBUG_PRINTF("%i ", ptr->children[i]->keys[j]); RAKNET_DEBUG_PRINTF(") "); queue.Push(ptr->children[i]); } queue.Push(0); RAKNET_DEBUG_PRINTF(" -- "); } } RAKNET_DEBUG_PRINTF("\n"); } } #ifdef _MSC_VER #pragma warning( pop ) #endif #endif // Code to test this hellish data structure. /* #include "DS_BPlusTree.h" #include <stdio.h> // Handle underflow on root. If there is only one item left then I can go downwards. // Make sure I keep the leftmost pointer valid by traversing it // When I free a leaf, be sure to adjust the pointers around it. #include "Rand.h" void main(void) { DataStructures::BPlusTree<int, int, 16> btree; DataStructures::List<int> haveList, removedList; int temp; int i, j, index; int testSize; bool b; for (testSize=0; testSize < 514; testSize++) { RAKNET_DEBUG_PRINTF("TestSize=%i\n", testSize); for (i=0; i < testSize; i++) haveList.Insert(i); for (i=0; i < testSize; i++) { index=i+randomMT()%(testSize-i); temp=haveList[index]; haveList[index]=haveList[i]; haveList[i]=temp; } for (i=0; i<testSize; i++) { btree.Insert(haveList[i], haveList[i]); btree.ValidateTree(); } for (i=0; i < testSize; i++) { index=i+randomMT()%(testSize-i); temp=haveList[index]; haveList[index]=haveList[i]; haveList[i]=temp; } for (i=0; i<testSize; i++) { btree.Delete(haveList[0]); // Asserts on 8th call. Fails on going to remove 8 (7th call) removedList.Insert(haveList[0]); haveList.RemoveAtIndex(0); for (j=0; j < removedList.Size(); j++) { b=btree.Get(removedList[j], temp); assert(b==false); } for (j=0; j < haveList.Size(); j++) { b=btree.Get(haveList[j], temp); assert(b==true); assert(haveList[j]==temp); } assert(btree.Size()==haveList.Size()); btree.ValidateTree(); } btree.Clear(); removedList.Clear(); haveList.Clear(); } RAKNET_DEBUG_PRINTF("Done. %i\n", btree.Size()); char ch[256]; fgets(ch, sizeof(ch), stdin); } */
[ "PhillipSpiess@d8b90d80-bb63-11dd-bed2-db724ec49875" ]
[ [ [ 1, 1162 ] ] ]
c150d4bbf376f954012c051ebf81756109833b73
22b6d8a368ecfa96cb182437b7b391e408ba8730
/engine/include/qvIElementViewFactory.h
6fc430e108281709f19f7a80a082f057a7fc5ec0
[ "MIT" ]
permissive
drr00t/quanticvortex
2d69a3e62d1850b8d3074ec97232e08c349e23c2
b780b0f547cf19bd48198dc43329588d023a9ad9
refs/heads/master
2021-01-22T22:16:50.370688
2010-12-18T12:06:33
2010-12-18T12:06:33
85,525,059
0
0
null
null
null
null
UTF-8
C++
false
false
1,946
h
/************************************************************************************************** //This code is part of QuanticVortex for latest information, see http://www.quanticvortex.org // //Copyright (c) 2009-2010 QuanticMinds Software Ltda. // //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 __I_ELEMENT_VIEW_FACTORY_H_ #define __I_ELEMENT_VIEW_FACTORY_H_ #include "qvIElementView.h" namespace qv { class IEngineManager; namespace views { class IElementViewFactory { public: virtual IElementView* addElementView( const c8* name, u32 elementViewHashType) = 0; virtual u32 getCreatableElementViewTypeCount() const = 0; virtual bool getCreateableElementViewType( u32 elementViewHashType) const = 0; }; } } #endif
[ [ [ 1, 54 ] ] ]
0cec9fa02c0c9413d09a34256ef51bd8548426c9
3977ae61b891f7e8ae7d75b8e22bcb63dedc3c1c
/Base/RecordManager.cpp
c8fee8daf918039c1a4cfb77ea000c0a854a0337
[]
no_license
jayrulez/ourprs
9734915b69207e7c3382412ca8647b051a787bb1
9d10f7a6edb06483015ed11dcfc9785f63b7204b
refs/heads/master
2020-05-17T11:40:55.001049
2010-03-25T05:20:04
2010-03-25T05:20:04
40,554,502
0
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
/* @Group: BSC2D @Group Members: <ul> <li>Robert Campbell: 0701334</li> <li>Audley Gordon: 0802218</li> <li>Dale McFarlane: 0801042</li> <li>Dyonne Duberry: 0802189</li> </ul> @ */ #ifndef _RECORDMANAGER_H #include "./RecordManager.h" #endif using namespace std; template <class T> RecordManager<T>::RecordManager() {} template <class T> RecordManager<T>::~RecordManager() {} template <class T> T* RecordManager<T>::findByPk(int pKey, int model) { if(model == TYPE_DEPARTMENT) { } if(model == TYPE_EMPLOYEE) { } return NULL; } template <class T> bool RecordManager<T>::create(T &object) { return false; } template <class T> T* RecordManager<T>::list() { return NULL; }
[ [ [ 1, 49 ] ] ]
abe4190270048ec24edf2e0bf71023a4cd2175cb
e776dbbd4feab1ce37ad62e5608e22a55a541d22
/luadbg/LuaEdit.cpp
cc326bfbf735c859d677bd2dd0f170835a13e77c
[]
no_license
EmuxEvans/sailing
80f2e2b0ae0f821ce6da013c3f67edabc8ca91ec
6d3a0f02732313f41518839376c5c0067aea4c0f
refs/heads/master
2016-08-12T23:47:57.509147
2011-04-06T03:39:19
2011-04-06T03:39:19
43,952,647
0
0
null
null
null
null
UTF-8
C++
false
false
2,267
cpp
// LuaEdit.cpp : main source file for LuaEdit.exe // #include "stdafx.h" #include "resource.h" #include <skates/skates.h> #include "LuaDebugClient.h" #include "AboutDlg.h" #include "DropFileHandler.h" #include "FileManager.h" #include "DialogWindow.h" #include "DebugHostWindow.h" #include "CommandWindow.h" #include "MainFrm.h" CAppModule _Module; int Run(LPTSTR /*lpstrCmdLine*/ = NULL, int nCmdShow = SW_SHOWDEFAULT) { CMessageLoop theLoop; _Module.AddMessageLoop(&theLoop); CMainFrame wndMain; if(wndMain.CreateEx() == NULL) { ATLTRACE(_T("Main window creation failed!\n")); return 0; } wndMain.ShowWindow(nCmdShow); int nRet = theLoop.Run(); _Module.RemoveMessageLoop(); return nRet; } TCHAR g_szLuaHostPath[MAX_PATH] = _T(".\\"); TCHAR g_szLuaHostArgs[200] = "127.0.0.1:1980"; //ILuaDebugClient* CreateLuaDebugClient(); int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow) { if(!InitializeLuaDebugClient("127.0.0.1:1980")) { ::MessageBox(NULL, _T("InitializeLuaDebugClient"), _T("ERROR"), MB_OK); return 0; } HRESULT hRes = ::CoInitialize(NULL); // If you are running on NT 4.0 or higher you can use the following call instead to // make the EXE free threaded. This means that calls come in on a random RPC thread. // HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED); ATLASSERT(SUCCEEDED(hRes)); Scintilla_RegisterClasses(hInstance); // this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used ::DefWindowProc(NULL, 0, 0, 0L); AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES); // add flags to support other controls hRes = _Module.Init(NULL, hInstance); ATLASSERT(SUCCEEDED(hRes)); int nRet = Run(lpstrCmdLine, nCmdShow); _Module.Term(); Scintilla_ReleaseResources(); ::CoUninitialize(); FinalizeLuaDebugClient(); return nRet; } #include "..\framework_dep\WTL\Controls\DockImpl.cpp" #include "..\framework_dep\WTL\Controls\DialogItemTemplate.cpp" #include "..\framework_dep\WTL\Controls\DialogTemplate.cpp" #include "..\framework_dep\WTL\Controls\DialogLayout.cpp" #include "..\framework_dep\WTL\Controls\Draw.cpp"
[ "gamemake@74c81372-9d52-0410-afc2-f743258a769a" ]
[ [ [ 1, 83 ] ] ]
1788c6c6e848ed552d4c35784515732ced99e2f8
1cc5720e245ca0d8083b0f12806a5c8b13b5cf98
/uva/src/cinco/p524/p524.cpp
2128b68da8e3f2e88b7492229ae424edcac9ccf1
[]
no_license
Emerson21/uva-problems
399d82d93b563e3018921eaff12ca545415fd782
3079bdd1cd17087cf54b08c60e2d52dbd0118556
refs/heads/master
2021-01-18T09:12:23.069387
2010-12-15T00:38:34
2010-12-15T00:38:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,084
cpp
#include <stdio.h> #define ehPrimo(soma) (soma==3 || soma==5 || soma==7 || soma==11 || soma==13 || soma==17 || soma==19 || soma==23 || soma==29 || soma==31) long maxV; char lista[10000000]; long passado[17]; long posNalista; long inicioUltimaCarreira; void geraCopia() { long zi; lista[inicioUltimaCarreira-1] = '\n'; //cout << "inicioUltima: " << inicioUltimaCarreira << "-" << (posNalista-1) << endl; for(zi=inicioUltimaCarreira;zi<posNalista-1;zi++) { //cout << (zi+posNalista-inicioUltimaCarreira) << "=" << zi << endl; lista[(zi-inicioUltimaCarreira)+posNalista] = lista[zi]; } //posNalista+=posNalista+1-(novo<10)?2:3; zi = posNalista; posNalista+=posNalista - inicioUltimaCarreira; inicioUltimaCarreira = zi; //std::cout << "(" << lista << ")" << std::endl; } void tenta(int nivel, int novo) { int zi; passado[novo] = 1; if(novo<10) { lista[posNalista] = (novo + '1' - 1); lista[posNalista+1] = ' '; posNalista+=2; } else { lista[posNalista] = ((novo/10) + '1' - 1); lista[posNalista+1] = ((novo%10) + '1' - 1); lista[posNalista+2] = ' '; posNalista+=3; } nivel++; if(nivel==maxV) { lista[posNalista-1] = 0; geraCopia(); posNalista-=(novo<10)?2:3; passado[novo] = 0; return; } for(zi=1;zi!=maxV+1;zi++) { if(passado[zi]==0 && ehPrimo(zi+novo)) { if(nivel==maxV-1) { if(ehPrimo(zi+1)) { tenta(nivel,zi); } } else { tenta(nivel,zi); } } } passado[novo] = 0; posNalista-=(novo<10)?2:3; } int main(int argc, char **argv) { int counter = 0; int i; //long zi; while(scanf("%d",&maxV)==1) { posNalista = 0; counter++; inicioUltimaCarreira = 0; if(counter!=1) printf("\n"); for(i=0;i!=maxV+1;i++) { passado[i]=0; } printf("Case %d: \n",counter); tenta(0,1); lista[posNalista-1] = 0; //for(zi=0;zi!=posNalista-1;zi++) { // if(lista[zi]==0) lista[zi]='-'; //} printf("%s\n",lista); //cout << posNalista << endl; } return 0; }
[ [ [ 1, 102 ] ] ]
8e7a2309ee3a872be9ef730635dcdc3e520d93a9
465943c5ffac075cd5a617c47fd25adfe496b8b4
/AIRPORT.H
8ad93f705762dda3cb228ee06f81ae1dbaa7beca
[]
no_license
paulanthonywilson/airtrafficcontrol
7467f9eb577b24b77306709d7b2bad77f1b231b7
6c579362f30ed5f81cabda27033f06e219796427
refs/heads/master
2016-08-08T00:43:32.006519
2009-04-09T21:33:22
2009-04-09T21:33:22
172,292
1
0
null
null
null
null
UTF-8
C++
false
false
796
h
/* Class to describe an airport as being a destination where planes can enter the simulation or exit it. Simon Hall ver 0.2 derived from Destination ver 0.2 01/04/96 7/4/96 PW ver 0.3 19/4/96 ID changed from char * to int PW ver 0.4 4/5/96 PW Safe landing direction reversed (Specification error) */ # ifndef _AIRPORT_H # define _AIRPORT_H # include "stdatc.h" # include "destinat.h" # include "atlandma.h" # define TAKEOFF_ALTITUDE 0 # define LANDING_ALTITUDE 0 class Airport : public Destination, public AtLandmark { public: Airport (Position, int , const Heading &); Boolean IsSafeCoords (Vector3D); Vector3D NewPlaneCoords (); PlaneState NewPlaneState (); virtual LandmarkTypeId LandmarkType(); }; # endif _AIRPORT_H
[ [ [ 1, 51 ] ] ]
ba41bcd6a77ed1f5c9b4ef0a97ae1d85a3809972
59f1959abb023c7e0a7ce2a347c250d799339fd8
/Engine/Core/Vector.h
7640aec5e139917811a240812c02097da6a68e56
[]
no_license
ghsoftco/scenegallery
78580a8aaf02a0c7ccc2687bc4a40c1873da5715
965fabdb39cbdd7c9735aaa5daab9f617bf020cf
refs/heads/master
2021-01-10T11:18:30.032732
2011-10-14T20:56:27
2011-10-14T20:56:27
47,763,913
0
0
null
null
null
null
UTF-8
C++
false
false
9,409
h
/* Vector.h Written by Matthew Fisher Template vector library. Extends functionality of std::vector */ #pragma once #include "Asserts.h" // // Intellisense for custom types // //http://thejefffiles.com/blog/autoexpdat-your-key-to-better-debugging-part-1/ #pragma warning(disable : 4700) template <class T> class Vector { public: Vector() { _Data = NULL; _Length = 0; _Capacity = 0; } explicit Vector(unsigned int Size) { _Data = new T[Size]; _Length = Size; _Capacity = Size; } Vector(const Vector<T> &V) { const unsigned int Length = V._Length; _Length = Length; _Capacity = Length; if(Length == 0) { _Data = NULL; } else { _Data = new T[Length]; for(unsigned int Index = 0; Index < Length; Index++) { _Data[Index] = V._Data[Index]; } } } ~Vector() { if(_Data != NULL) { delete[] _Data; } } // // Memory // void FreeMemory() { if(_Data != NULL) { delete[] _Data; _Data = NULL; } _Length = 0; _Capacity = 0; } void DeleteMemory() { if(_Data != NULL) { for(UINT Index = 0; Index < _Length; Index++) { delete _Data[Index]; } delete[] _Data; _Data = NULL; } _Length = 0; _Capacity = 0; } // // Windows has claimed the nice name "ZeroMemory" for its own uses // void ZeroMem() { if(_Length > 0) { memset(_Data, 0, _Length * sizeof(T)); } } void operator = (const Vector<T> &V) { const unsigned int Length = V._Length; _Length = Length; _Capacity = Length; if(_Data != NULL) { delete[] _Data; } if(Length == 0) { _Data = NULL; } else { _Data = new T[Length]; for(unsigned int Index = 0; Index < Length; Index++) { _Data[Index] = V._Data[Index]; } } } void Allocate(unsigned int Size) { if(Size == 0) { FreeMemory(); } /*else if(_Length == Size) { if(typeid(T) != typeid(int) && typeid(T) != typeid(unsigned int) && typeid(T) != typeid(double) && typeid(T) != typeid(float) && typeid(T) != typeid(char) && typeid(T) != typeid(unsigned char)) { T Value; for(unsigned int Index = 0; Index < Size; Index++) { _Data[Index] = Value; } } }*/ else { if(_Data != NULL) { delete[] _Data; } _Data = new T[Size]; _Length = Size; _Capacity = Size; } } void Allocate(unsigned int Size, const T &ClearValue) { Allocate(Size); Clear(ClearValue); } void ReSize(unsigned int Size) { if(Size == 0) { FreeMemory(); } else if(Size <= _Capacity) { _Length = Size; if(Size == 0) { if(_Data != NULL) { delete[] _Data; _Capacity = 0; } } } else { unsigned int NewCapacity = Size * 3 / 2 + 4; T *NewData = new T[NewCapacity]; const unsigned int Length = _Length; for(unsigned int Index = 0; Index < Length; Index++) { NewData[Index] = _Data[Index]; } if(_Data) { delete[] _Data; } _Data = NewData; _Length = Size; _Capacity = NewCapacity; } } void Reserve(unsigned int Size) { if(Size > _Capacity) { T *NewData = new T[Size]; if(_Data != NULL) { memcpy(NewData, _Data, sizeof(T) * _Length); for(UINT index = 0; index < _Length; index++) { new (_Data + index) T; } delete[] _Data; } _Data = NewData; _Capacity = Size; } } // // Accessors // __forceinline T& operator [] (unsigned int k) { #ifdef VECTOR_DEBUG if(k >= _Length) { SignalError("Out-of-bounds vector access"); } #endif return _Data[k]; } __forceinline T& operator [] (int k) { #ifdef VECTOR_DEBUG if(k < 0 || k >= int(_Length)) { SignalError("Out-of-bounds vector access"); } #endif return _Data[k]; } __forceinline const T& operator [] (unsigned int k) const { #ifdef VECTOR_DEBUG if(k >= _Length) { SignalError("Out-of-bounds vector access"); } #endif return _Data[k]; } __forceinline const T& operator [] (int k) const { #ifdef VECTOR_DEBUG if(k < 0 || k >= int(_Length)) { SignalError("Out-of-bounds vector access"); } #endif return _Data[k]; } __forceinline unsigned int Length() const { return _Length; } __forceinline T* CArray() { #ifdef VECTOR_DEBUG if(_Length == 0) { SignalError("CArray called on zero-length vector"); } #endif return _Data; } __forceinline const T* CArray() const { #ifdef VECTOR_DEBUG if(_Length == 0) { SignalError("CArray called on zero-length vector"); } #endif return _Data; } __forceinline T& RandomElement() { Assert(_Length > 0, "RandomElement called with no elements"); return _Data[rand() % _Length]; } __forceinline const T& RandomElement() const { Assert(_Length > 0, "RandomElement called with no elements"); return _Data[rand() % _Length]; } __forceinline T& Last() { Assert(_Length > 0, "Last called with no elements"); return _Data[_Length - 1]; } __forceinline const T& Last() const { Assert(_Length > 0, "Last called with no elements"); return _Data[_Length - 1]; } __forceinline T& First() { Assert(_Length > 0, "First called with no elements"); return _Data[0]; } __forceinline const T& First() const { Assert(_Length > 0, "First called with no elements"); return _Data[0]; } __forceinline T* Begin() { return _Data; } __forceinline const T* Begin() const { return _Data; } __forceinline T* End() { return _Data + _Length; } __forceinline const T* End() const { return _Data + _Length; } // // Modifiers // void Append(const Vector<T> &V); void PushEnd(const T &t); void PushEnd(); void PopEnd(); void PopFront(); void RemoveSlow(unsigned int Index); void RemoveSwap(unsigned int Index); void Randomize(); void Sort(); void Scale(const T &t); template<class orderingType> void Sort(orderingType Function) { if(_Length >= 2) { std::sort(_Data, _Data + _Length, Function); } } void Clear(const T &T); // // Query // T Sum() const; const T& MaxValue() const; unsigned int MaxIndex() const; const T& MinValue() const; unsigned int MinIndex() const; bool Contains(const T &t) const; int FindFirstIndex(const T &t) const; unsigned int Hash32() const; unsigned __int64 Hash64() const; // // File // void SaveToASCIIFile(const String &Filename) { ofstream File(Filename.CString()); PersistentAssert(!File.fail(), "Failed to open file"); File << _Length << endl; for(unsigned int Index = 0; Index < _Length; Index++) { File << _Data[Index] << '\n'; } } void LoadFromASCIIFile(const String &Filename) { ifstream File(Filename.CString()); PersistentAssert(!File.fail(), "Failed to open file"); unsigned int Length; File >> Length; Allocate(Length); for(unsigned int Index = 0; Index < Length; Index++) { File >> _Data[Index]; } } protected: //vector<T> Data; T *_Data; unsigned int _Length; unsigned int _Capacity; }; #pragma warning(default : 4700) #include "Vector.cpp"
[ [ [ 1, 407 ] ] ]
ad12a17972d0225970480f4b0fadbd8e986361fa
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/test/actor/clear_test.cpp
0fb068117834f5fb57bb7aa9573b7f8c3e2df7ab
[ "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
1,482
cpp
/*============================================================================= Copyright (c) 2003 Jonathan de Halleux ([email protected]) http://spirit.sourceforge.net/ 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) =============================================================================*/ /////////////////////////////////////////////////////////////////////////////// // Test suite for clear_actor /////////////////////////////////////////////////////////////////////////////// #include "action_tests.hpp" #include <boost/spirit/core.hpp> #include <vector> #include <boost/spirit/actor/clear_actor.hpp> void clear_action_test() { using namespace boost::spirit; BOOST_MESSAGE("clear_test"); const char* cp = "63"; const char* cp_first = cp; const char* cp_last = cp + test_impl::string_length(cp); std::vector<int> c; c.push_back(1); scanner<char const*> scan( cp_first, cp_last ); match<> hit; hit = int_p[ clear_a(c)].parse(scan); BOOST_CHECK(hit); BOOST_CHECK_EQUAL(scan.first, scan.last); BOOST_CHECK( c.empty() ); scan.first = cp; c.push_back(1); hit = str_p("63")[ clear_a(c)].parse(scan); BOOST_CHECK(hit); BOOST_CHECK_EQUAL(scan.first, scan.last); BOOST_CHECK( c.empty() ); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 47 ] ] ]
3e71c5e8cff2d4ce9f210f19693cfec8c006b96e
ce28ec891a0d502e7461fd121b4d96a308c9dab7
/dbmerge/AttributeMergeItem.cc
dbc59512354a302f295b393681673af2fcc1d52a
[]
no_license
aktau/Tangerine
fe84f6578ce918d1fa151138c0cc5780161b3b8f
179ac9901513f90b17c5cd4add35608a7101055b
refs/heads/master
2020-06-08T17:07:53.860642
2011-08-14T09:41:41
2011-08-14T09:41:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,336
cc
#include "AttributeMergeItem.h" #include <QtGui> #define MERGE_DEBUG 2 struct HistoryLessThan { bool operator()(const HistoryRecord& lhs, const HistoryRecord& rhs) const { return lhs.timestamp < rhs.timestamp; } }; AttributeMergeItem::AttributeMergeItem(int matchId, const QList<HistoryRecord>& masterHistory, const QList<HistoryRecord>& slaveHistory, const QString& attributeName) : mMatchId(matchId), mMasterHistory(masterHistory), mSlaveHistory(slaveHistory), mMergeIn(false), mAttributeName(attributeName) { } void AttributeMergeItem::accept(const SimpleMergeAction *action) { MergeAction *newAction = NULL; qDebug() << "AttributeMergeItem::accept: accepting" << action; switch (action->type()) { case Merge::CHOOSE_SLAVE: { chooseSlave(); } break; case Merge::MOST_RECENT: { chooseMostRecent(); } break; case Merge::CHOOSE_HISTORY: { newAction = chooseHistory(); } break; case Merge::DONT_MERGE: mMessage = QObject::tr("User chose not to merge"); break; default: qDebug() << "MatchMergeItem::accept: received unacceptable action"; return; } store((newAction) ? newAction : action); delete newAction; } bool AttributeMergeItem::execute(SQLDatabase *db, MergeMapper *mapper) { bool success = true; if (currentActionType() == Merge::ASSIGN_NEW_ID) { } //mapper->addMapping(MergeMapper::MATCH_ID, mOldId, mNewId); setDone(true); return true; } MergeAction *AttributeMergeItem::chooseMostRecent() { qDebug() << "Choosing most recent!!!!"; MergeAction *newAction = NULL; if (newAction = decideForInvalidHistories()) { return newAction; } const HistoryRecord& leftMostRecent = mMasterHistory.last(); const HistoryRecord& rightMostRecent = mSlaveHistory.last(); HistoryLessThan hLess; if (hLess(leftMostRecent, rightMostRecent)) { // pick right mMessage = "Slave was edited more recently than master"; newAction = new ChooseSlaveAction; } else { mMessage = "Master was edited more recently than slave"; newAction = new DontMergeAction; } return newAction; } MergeAction *AttributeMergeItem::chooseSlave() { qDebug() << "Choosing slave!!!!"; MergeAction *newAction = NULL; if (newAction = decideForInvalidHistories()) { return newAction; } mMessage = "Chose slave"; newAction = new ChooseSlaveAction; return newAction; } MergeAction *AttributeMergeItem::chooseHistory() { MergeAction *newAction = NULL; if (newAction = decideForInvalidHistories()) { return newAction; } const HistoryRecord& leftMostRecent = mMasterHistory.last(); const HistoryRecord& rightMostRecent = mSlaveHistory.last(); if (leftMostRecent == rightMostRecent) { #ifdef MERGE_DEBUG qDebug() << "RESULT: Both were equal, not doing anything: " << leftMostRecent.toString(); qDebug() << "----------------------------------"; #endif mMessage = "No action required, both histories are the same"; return new DontMergeAction; } #if MERGE_DEBUG >= 2 qDebug() << "Master history"; int i = 0; foreach (const HistoryRecord& r, mMasterHistory) { qDebug() << ++i << "-" << r.toString(); } qDebug() << "Slave history"; i = 0; foreach (const HistoryRecord& r, mSlaveHistory) { qDebug() << ++i << "-" << r.toString(); } #endif HistoryLessThan hLess; QList<HistoryRecord>::const_iterator found = qBinaryFind(mSlaveHistory.begin(), mSlaveHistory.end(), leftMostRecent, hLess); // look for shared history, conflict, resolve if (found != mSlaveHistory.end()) { if (leftMostRecent == *found) { qDebug() << "RESULT: Found master history inside of slave: supposed to merge!"; mMessage = QString("Slave is more current than master, merging"); } else { qDebug() << "RESULT: Freak accident #1: exactly the same timestamp but not the same, what to do?:" << leftMostRecent.toString() << "vs" << found->toString(); newAction = new NoAction; mMessage = QString("Couldn't verify history agreement, manual action required"); //while (++found != rightHistory.end()) { ... } } } else { qDebug() << "RESULT: Did NOT find master history inside of slave"; found = qBinaryFind(mMasterHistory.begin(), mMasterHistory.end(), rightMostRecent, hLess); if (found != mMasterHistory.end()) { if (rightMostRecent == *found) { qDebug() << "RESULT: Found last slave update inside of master history: do not merge, master is more recent!"; mMessage = QString("Master is more current than slave, not merging"); } else { qDebug() << "RESULT: Freak accident #2: exactly the same timestamp but not the same, what to do?:" << rightMostRecent.toString() << "vs" << found->toString(); newAction = new NoAction; mMessage = QString("Couldn't verify history agreement, manual action required"); } } else { qDebug() << "RESULT: Histories diverged or were never the same in the first place: conflict resolution magic here"; mMessage = QString("Histories diverged or were never the same in the first place, manual action required"); newAction = new NoAction; } } qDebug() << "----------------------------------"; return newAction; } MergeAction *AttributeMergeItem::decideForInvalidHistories() { if (mSlaveHistory.isEmpty()) { // pick master no matter what mMessage = QString("Slave history wasn't available, picking master"); return new DontMergeAction; } if (mMasterHistory.isEmpty()) { // pick slave now (because slave hist is not empty) mMessage = QString("Master history wasn't available, picking slave"); return new ChooseSlaveAction; } return NULL; } QWidget *AttributeMergeItem::informationWidget() const { QTableWidget *masterTable = createTableWidget(mMasterHistory); QTableWidget *slaveTable = createTableWidget(mSlaveHistory); QLabel *title = new QLabel(QString("Showing data for attribute '<b>%1</b>' on match <b>%2<b>").arg(mAttributeName).arg(mMatchId)); title->setTextFormat(Qt::RichText); //QHBoxLayout *layout = new QHBoxLayout; QGridLayout *layout = new QGridLayout; layout->addWidget(title, 0, 0); layout->addWidget(new QLabel("Master table:"), 1, 0); layout->addWidget(masterTable, 2, 0); layout->addWidget(new QLabel("Slave table:"), 1, 1); layout->addWidget(slaveTable, 2, 1); QWidget *widget = new QWidget(); widget->setLayout(layout); return widget; } QTableWidget *AttributeMergeItem::createTableWidget(const QList<HistoryRecord>& history) const { QTableWidget *table = new QTableWidget(0, 3); table->setHorizontalHeaderLabels(QStringList() << QObject::tr("Time") << QObject::tr("User") << QObject::tr("Value")); //table->setColumnWidth(0, 50); //table->setColumnWidth(1, 50); //mItemList->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents); //mItemList->horizontalHeader()->setResizeMode(QHeaderView::Stretch); table->horizontalHeader()->setStretchLastSection(true); table->verticalHeader()->setDefaultSectionSize(20); table->setEditTriggers(QAbstractItemView::NoEditTriggers); table->setAlternatingRowColors(true); table->setSelectionBehavior(QAbstractItemView::SelectRows); /* QTableWidgetItem *actionDescription = new QTableWidgetItem(action->description()); actionDescription->setForeground(!item->isResolved() ? QBrush(Qt::red) : QBrush(Qt::green)); actionDescription->setData(Qt::UserRole, qVariantFromValue((void *) item)); */ table->setRowCount(history.size()); int row = 0; foreach (const HistoryRecord& record, history) { qDebug() << "Filling up" << record.timestamp.toString() << record.userId << record.matchId << record.value.toString(); QTableWidgetItem *time = new QTableWidgetItem(record.timestamp.toString("hh:mm dd/MM/yy")); time->setForeground(QBrush(Qt::white)); time->setBackgroundColor(Qt::black); table->setItem(row, 0, time); table->setItem(row, 1, new QTableWidgetItem(QString::number(record.userId))); //table->setItem(row, 2, new QTableWidgetItem(QString::number(record.matchId))); table->setItem(row, 2, new QTableWidgetItem(record.value.toString())); ++row; } table->resizeColumnsToContents(); //mItemList->resizeColumnToContents(1); return table; }
[ [ [ 1, 262 ] ] ]
23471ac4e62c9828b10d6b63bdcf2d91d9bba7b9
967868cbef4914f2bade9ef8f6c300eb5d14bc57
/Tree/Tree.cpp
d7018df45c46432376adf81bb03e034f357dde71
[]
no_license
saminigod/baseclasses-001
159c80d40f69954797f1c695682074b469027ac6
381c27f72583e0401e59eb19260c70ee68f9a64c
refs/heads/master
2023-04-29T13:34:02.754963
2009-10-29T11:22:46
2009-10-29T11:22:46
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
7,948
cpp
/* © Vestris Inc., Geneva, Switzerland http://www.vestris.com, 1994-1999 All Rights Reserved ______________________________________________ written by Daniel Doubrovkine - [email protected] */ #include <baseclasses.hpp> #include "Tree.hpp" template <class T> void CTreeElement<T>::Show(ostream& Stream, int Depth) const { for (register int i=0;i<Depth;i++) Stream << ' '; Stream << m_Element << endl; if (m_Child) m_Child->Show(Stream, Depth+1); if (m_Next) m_Next->Show(Stream, Depth); } template <class T> CTree<T>::CTree(bool Sorted, bool Unique) : CObject() { m_Head = NULL; m_Sorted = Sorted; m_Unique = Unique; } template <class T> CTree<T>::~CTree(void) { RemoveAll(m_Head); } template <class T> void CTree<T>::RemoveAll(CTreeElement<T> *& Node) { if (!Node) return; if (Node->m_Child) { RemoveAll(Node->m_Child); Node->m_LastChild = NULL; } if (Node->m_Next) RemoveAll(Node->m_Next); delete Node; Node = NULL; } template <class T> void CTree<T>::Remove(CTreeElement<T> *& Node) { if (!Node) return; if (Node->m_Child) { RemoveAll(Node->m_Child); Node->m_LastChild = NULL; } if (Node->m_Prev) Node->m_Prev->m_Next = Node->m_Next; else if (Node->m_Parent && (Node->m_Parent->m_Child == Node)) Node->m_Parent->m_Child = Node->m_Next; delete Node; Node = NULL; } /* add child on top of list */ template <class T> CTreeElement<T> * CTree<T>::AddChildFirst(CTreeElement<T> * Node, const T& Element) { CTreeElement<T> * NewElement = new CTreeElement<T>(Element); if (!Node) Node = m_Head; if (!Node) m_Head = NewElement; else { NewElement->m_Parent = Node; NewElement->m_Next = Node->m_Child; if (Node->m_Child) Node->m_Child->m_Prev = Node; else Node->m_LastChild = NewElement; Node->m_Child = NewElement; } return NewElement; } /* add child on bottom of list */ template <class T> CTreeElement<T> * CTree<T>::AddChildLast(CTreeElement<T> * Node, const T& Element) { CTreeElement<T> * NewElement = new CTreeElement<T>(Element); if (!Node) Node = m_Head; if (!Node) m_Head = NewElement; else { NewElement->m_Parent = Node; if (!Node->m_Child) { Node->m_Child = NewElement; Node->m_LastChild = NewElement; } else { Node->m_LastChild->m_Next = NewElement; NewElement->m_Prev = Node->m_LastChild; Node->m_LastChild = NewElement; } } return NewElement; } /* add at the same level, uses m_Sorted and m_Unique */ template <class T> CTreeElement<T> * CTree<T>::Add(CTreeElement<T> * Node, const T& Element, bool * Added) { if (Added) (* Added) = true; if (!Node) Node = m_Head; if (!Node) { m_Head = new CTreeElement<T>(Element); return m_Head; } /* hack: try to add to parent's last element */ if (Node->m_Parent) { if (m_Sorted) { if (Greater(Element, Node->m_Parent->m_LastChild->m_Element)) { return AddAfter(Node->m_Parent->m_LastChild, Element); } else if (m_Unique && (Equal(Node->m_Parent->m_LastChild->m_Element, Element))) { if (Added) (* Added) = false; return Node->m_Parent->m_LastChild; } } Node = Node->m_Parent->m_Child; } else Node = m_Head; /* classic insertion */ while(1) { if (m_Unique && Equal(Node->m_Element, Element)) { if (Added) (* Added) = false; return Node; } else if (m_Sorted && (Greater(Node->m_Element, Element))) return AddBefore(Node, Element); if (Node->m_Next) Node = Node->m_Next; else break; } return AddAfter(Node, Element); } /* add a child, uses m_Sorted and m_Unique */ template <class T> CTreeElement<T> * CTree<T>::AddChild(CTreeElement<T> * Node, const T& Element, bool * Added) { if (Added) (* Added) = true; if (!Node) Node = m_Head; if (!Node) { m_Head = new CTreeElement<T>(Element); return m_Head; } /* hack: check the last element first */ if (m_Sorted && Node->m_LastChild) { if (Greater(Element, Node->m_LastChild->m_Element)) { return AddAfter(Node->m_LastChild, Element); } else if (m_Unique && (Equal(Node->m_LastChild->m_Element, Element))) { if (Added) (* Added) = false; return Node->m_LastChild; } } /* classic add to the tree */ CTreeElement<T> * Current = Node->m_Child; if (!Current) return AddChildFirst(Node, Element); while(1) { if (m_Unique && Equal(Current->m_Element, Element)) { if (Added) (* Added) = false; return Current; } else if (m_Sorted && (Greater(Current->m_Element, Element))) { return AddBefore(Current, Element); } if (Current->m_Next) Current = Current->m_Next; else break; } return AddAfter(Current, Element); } /* insert before an element */ template <class T> CTreeElement<T> * CTree<T>::AddBefore(CTreeElement<T> * Node, const T& Element) { if (!Node) Node = m_Head; if (!Node) { m_Head = new CTreeElement<T>(Element); return m_Head; } CTreeElement<T> * NewElement = new CTreeElement<T>(Element); NewElement->m_Next = Node; NewElement->m_Prev = Node->m_Prev; NewElement->m_Parent = Node->m_Parent; if (Node->m_Prev) Node->m_Prev->m_Next = NewElement; if (Node->m_Parent && (Node->m_Parent->m_Child == Node)) Node->m_Parent->m_Child = NewElement; Node->m_Prev = NewElement; if (Node == m_Head) m_Head = NewElement; return NewElement; } /* insert after an element */ template <class T> CTreeElement<T> * CTree<T>::AddAfter(CTreeElement<T> * Node, const T& Element) { if (!Node) Node = m_Head; if (!Node) { m_Head = new CTreeElement<T>(Element); return m_Head; } CTreeElement<T> * NewElement = new CTreeElement<T>(Element); NewElement->m_Next = Node->m_Next; if (Node->m_Next) Node->m_Next->m_Prev = NewElement; if (Node->m_Parent && (Node->m_Parent->m_LastChild == Node)) Node->m_Parent->m_LastChild = NewElement; NewElement->m_Parent = Node->m_Parent; NewElement->m_Prev = Node; Node->m_Next = NewElement; return NewElement; } template <class T> CTreeElement<T> * CTree<T>::Find(const CVector<T>& EltVector) const { unsigned int CurrentIndex = 0; CTreeElement<T> * Current = m_Head; while (Current) { if (CurrentIndex >= EltVector.GetSize()) return NULL; if (Equal(Current->m_Element, EltVector[CurrentIndex])) { CurrentIndex++; if (CurrentIndex == EltVector.GetSize()) return Current; else Current = Current->m_Child; } else Current = Current->m_Next; } return NULL; } template <class T> CTreeElement<T> * CTree<T>::Add(const CVector<T>& EltVector, bool * Added) { if (Added) (* Added) = false; if (!EltVector.GetSize()) return NULL; CTreeElement<T> * Current = Add(m_Head, EltVector[0], Added); for (register int i=1;i<(int) EltVector.GetSize();i++) Current = AddChild(Current, EltVector[i], Added); return Current; } template <class T> void CTree<T>::MoveAsChildLast(CTree<T>& Source, CTreeElement<T> * Node, CTreeElement<T> * TargetNode) { // break the parent link if (Source.m_Head == Node) Source.m_Head = NULL; if (Node->m_Parent && Node->m_Parent->m_Child == Node) Node->m_Parent->m_Child = Node->m_Prev ? Node->m_Prev : Node->m_Next; if (Node->m_Parent && Node->m_Parent->m_LastChild == Node) Node->m_Parent->m_LastChild = Node->m_Next ? Node->m_Next : Node->m_Prev; if (Node->m_Prev) Node->m_Prev->m_Next = Node->m_Next; // attach to the new tree if (!TargetNode) TargetNode = m_Head; if (!TargetNode) m_Head = Node; else { Node->m_Parent = TargetNode; if (!TargetNode->m_Child) { TargetNode->m_Child = Node; TargetNode->m_LastChild = Node; } else { TargetNode->m_LastChild->m_Next = Node; Node->m_Prev = TargetNode->m_LastChild; TargetNode->m_LastChild = Node; } } }
[ [ [ 1, 251 ] ] ]
c5f895b04894b1601ac745b8e1ccf97eeda163de
00b979f12f13ace4e98e75a9528033636dab021d
/branches/ziis/src/core/main.cc
ced8cdb1ae0809f1468f7e73a9c7fd8ae8b36781
[]
no_license
BackupTheBerlios/ziahttpd-svn
812e4278555fdd346b643534d175546bef32afd5
8c0b930d3f4a86f0622987776b5220564e89b7c8
refs/heads/master
2016-09-09T20:39:16.760554
2006-04-13T08:44:28
2006-04-13T08:44:28
40,819,288
0
0
null
null
null
null
UTF-8
C++
false
false
1,368
cc
// // main.cc for in // // Made by texane // Login <[email protected]> // // Started on Tue Feb 14 01:04:58 2006 texane // Last update Mon Apr 03 21:54:00 2006 texane // #include <list> #include <ziafs.hh> #include <iostream> using namespace std; int main(int ac, char** av) { core_t core; net::server* srv; net::config* curr_config; list<net::config::server*>::iterator curr_server; // Bootstrap the core sysapi::insock::init_subsystem(); core.config = new net::config(ac == 2 ? av[1] : "conf/ziafs.xml"); core.thr_pool = new thr::pool(core.config->get_system()->nb_thread); // core.thr_pool->assign_task(thr::pool::system_entry, (void*)&core); // Create the servers core.config->get_server(curr_server); while (core.config->end_server(curr_server) == false) { // Build a new server srv = new net::server(&core); curr_config = new net::config; curr_config->generate_config(*curr_server, *core.config); srv->reload_config(curr_config); // release the server config list // delete curr_config; core.srv_list.push_front(srv); srv->run(); ++curr_server; } // Main loop while (1) Sleep(999999); // Release (?) delete core.config; delete core.thr_pool; sysapi::insock::release_subsystem(); }
[ "texane@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
[ [ [ 1, 57 ] ] ]
66e1c6386e0341b27039841c99303840f854adca
da48afcbd478f79d70767170da625b5f206baf9a
/nnstock/nnstock/TestDlg.cpp
9f496de79f46ceec17e5238014383996b3eda9b4
[]
no_license
haokeyy/fahister
5ba50a99420dbaba2ad4e5ab5ee3ab0756563d04
c71dc56a30b862cc4199126d78f928fce11b12e5
refs/heads/master
2021-01-10T19:09:22.227340
2010-05-06T13:17:35
2010-05-06T13:17:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,462
cpp
// TestDlg.cpp : implementation file // #include "stdafx.h" #include "nnstock.h" #include "TestDlg.h" #include "WndHelper.h" #include "MsgHelper.h" #include "BatchMsg.h" #include "Utility.h" #include "stockPrice.h" // CTestDlg dialog IMPLEMENT_DYNAMIC(CTestDlg, CDialog) CTestDlg::CTestDlg(CWnd* pParent /*=NULL*/) : CDialog(CTestDlg::IDD, pParent) { } CTestDlg::~CTestDlg() { } void CTestDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CTestDlg, CDialog) ON_BN_CLICKED(IDC_BUTTON1, &CTestDlg::OnBnClickedButton1) ON_BN_CLICKED(IDC_BUTTON2, &CTestDlg::OnBnClickedButton2) END_MESSAGE_MAP() // CTestDlg message handlers void CTestDlg::OnBnClickedButton1() { CString szMainWnd; this->GetDlgItemText(IDC_EDIT2, szMainWnd); HWND hMainWnd = CWndHelper::FindTopWindowBlur(szMainWnd.GetBuffer(), ""); CString szCommands; this->GetDlgItemText(IDC_EDIT3, szCommands); char* lpstrCmds = szCommands.GetBuffer(); NameValuePair parameters[] = { NameValuePair("{STC}", "159901"), NameValuePair("{PRC}", "4.010"), NameValuePair("{QTY}", "1200"), NameValuePair("END", "") }; CBatchMsg::ProcessBatchCommand(hMainWnd, lpstrCmds, NULL); } void CTestDlg::OnBnClickedButton2() { double cur_price = CStockPrice::GetCurrentPrice("600036"); CString str; str.Format("600036:%.2f", cur_price); MessageBox(str); }
[ "[email protected]@d41c10be-1f87-11de-a78b-a7aca27b2395" ]
[ [ [ 1, 70 ] ] ]
4b6bff5c9805c69e4dd3931f22d4b14bb5785ca2
119ba245bea18df8d27b84ee06e152b35c707da1
/unreal/branches/robots/qrgui/interpreters/robots/details/robotImplementations/brickImplementations/nullBrickImplementation.h
0ecfccf21e96a455b2180085898db6562cc121a1
[]
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
449
h
#pragma once #include "abstractBrickImplementation.h" namespace qReal { namespace interpreters { namespace robots { namespace details { namespace robotImplementations { namespace brickImplementations { class NullBrickImplementation : public AbstractBrickImplementation { Q_OBJECT public: NullBrickImplementation(); virtual void beep(unsigned time); virtual void playTone(unsigned freq, unsigned time); }; } } } } } }
[ [ [ 1, 25 ] ] ]
5a30a6a2111c6e7766c9b9fab1f6520590901db9
ffe0a7d058b07d8f806d610fc242d1027314da23
/V3e/mc/src/irc/Socket.h
c83a626e903f7b3911e0c26ee0d6a1ba588d5e16
[]
no_license
Cybie/mangchat
27bdcd886894f8fdf2c8956444450422ea853211
2303d126245a2b4778d80dda124df8eff614e80e
refs/heads/master
2016-09-11T13:03:57.386786
2009-12-13T22:09:37
2009-12-13T22:09:37
32,145,077
0
0
null
null
null
null
UTF-8
C++
false
false
1,386
h
#ifndef _SOCKET_H_ #define _SOCKET_H_ #include "common.h" #ifdef WIN32 #include <winsock.h> typedef SOCKET SOCK_TYPE; typedef int socklen_t; typedef char raw_type; #else #include <sys/types.h> // For data types #include <sys/socket.h> // For socket(), connect(), send(), and recv() #include <netdb.h> // For gethostbyname() #include <arpa/inet.h> // For inet_addr() #include <unistd.h> // For close() #include <netinet/in.h> // For sockaddr_in typedef int SOCK_TYPE; typedef void raw_type; // Type used for raw data on this platform #endif #define BUFFER_SIZE 1024 const int RCVBUFSIZE = 512; class BaseSocket { public: BaseSocket(void); ~BaseSocket(void); public: std::string RemoteAddr(); unsigned short RemotePort(); int _Recv(void *buffer, int bufferLen); void _Send(const char *buffer); private: void _fillAddr(const std::string &address, unsigned short port, sockaddr_in &addr); protected: SOCK_TYPE sock_id; protected: void _Create(int _type, int _protocol); void _Bind(const std::string &_address, unsigned short _port); void _Listen(int _max); bool _Connect(const char *addr, int port); void _Close(); void _SetOptions(int nOptions); void _SetBlocking(bool bBlock); }; #endif
[ "cybraxcyberspace@dfcbb000-c142-0410-b1aa-f54c88fa44bd" ]
[ [ [ 1, 57 ] ] ]
3eb5b980f547e9e4662a3de220515e8902590156
677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f
/SolidSBCTestSDK/PerformanceCounter.h
1fd55a96385ed733e4df888b9895f8a2136e7527
[]
no_license
M0WA/SolidSBC
0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419
3e9682e90a22650e12338785c368ed69a9cac18b
refs/heads/master
2020-04-19T14:40:36.625222
2011-12-02T01:50:05
2011-12-02T01:50:05
168,250,374
0
0
null
null
null
null
UTF-8
C++
false
false
286
h
#pragma once #include "SolidSBCTestSDK.h" class SOLIDSBCTESTSDK_API CPerformanceCounter { public: CPerformanceCounter(void); ~CPerformanceCounter(void); void Start(void); double Stop(void); private: LARGE_INTEGER m_liStart; LARGE_INTEGER m_liFrequency; };
[ "admin@bd7e3521-35e9-406e-9279-390287f868d3" ]
[ [ [ 1, 17 ] ] ]
404864f54b2b4eb2bed0be1d2f55701a57857246
58ef4939342d5253f6fcb372c56513055d589eb8
/ScheduleKiller/source/ImageLib/inc/LMSvgUtil.h
17ef93f0d35e127d02d64473ebb2a21bd7e4b930
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
741
h
#ifndef YICHAUTILE_H_ #define YICHAUTILE_H_ #ifdef EKA2 #include <akniconutils.h> #endif #include <e32std.h> #include <e32base.h> #include <FBS.H> class LMSvgUtil { public: ~LMSvgUtil(); LMSvgUtil(); static TInt SetIconSize(CFbsBitmap* aBitmap, const TSize& aSize); static CFont* GetFontFromId(TInt aId); static CFbsBitmap* GetImageFromResourceL(TInt aId); static void GetImageAndMaskFormResourceL(CFbsBitmap*& aBitmap, CFbsBitmap*& aBitmapMask,TInt aBitmapId, TInt aMaskId); static CGulIcon* GetIconFormResourceL(TInt aBitmapId, TInt aMaskId); static void GetImageAndMaskFormResourcePathL(CFbsBitmap*& aBitmap, CFbsBitmap*& aBitmapMask,TInt aBitmapId, TInt aMaskId); }; #endif /*YICHAUTILE_H_*/
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 27 ] ] ]
bc67bb5f0bedd13dd738918976044701d7dfd804
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Common/network/udp_connection.h
8220b6b43d0174649e9cd130949495b3bf064429
[]
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
6,183
h
#ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif // this is crazy: MSVS.net needs winsock2 to be included before windows.h so that winsock.h doesn't get included // while MSVS6 needs the opposite ordering because its winsock2 depends on types defines in windows.h... // using the common PSDK version doesnt help cause PSDK no longer supports MSVS6... #ifndef UDP_MSVS6_COMPAT #include <winsock2.h> #include <windows.h> #else #include <windows.h> #include <winsock2.h> #endif #include <iostream> #include <map> #include <list> #include <ws2tcpip.h> #include <mswsock.h> #ifndef UDP_MSVS6_COMPAT #include "../utility/fastdelegate.h" using namespace fastdelegate; #endif #ifndef _UDP_CONNECTION_H #define _UDP_CONNECTION_H #ifdef __cplusplus_cli #pragma managed(push,off) #endif #define MAX_PACKET_SIZE 65467 // UDP protocol max message size using namespace std; class udp_connection; class udp_params { private: void init(); void init(unsigned long local_ip, unsigned short local_port, bool find_qos, FLOWSPEC flowspec); void init(unsigned long local_ip, unsigned short local_port, WSAPROTOCOL_INFO& protocol_info, FLOWSPEC flowspec); void init(unsigned long local_ip, unsigned short local_port, unsigned long remote_ip, unsigned short remote_port, bool find_qos, FLOWSPEC flowspec); void init(unsigned long local_ip, unsigned short local_port, unsigned long remote_ip, unsigned short remote_port, WSAPROTOCOL_INFO& protocol_info, FLOWSPEC flowspec); public: const static FLOWSPEC def_flowspec; // general notes: // - local_ip, remote_ip are in network byte order (same as return by inet_addr) // - local_port, remote_port are in host byte order // - if find_qos is specified and there is no QoS protocol installed, the socket // initialization will fail // - if not specifying a remote_ip, remote_port, you must call sendMessageTo, // sendMessage will fail // - if the QoS protocol cannot satisy the QoS (flowspec) request, the socket initialization will fail // - both send_flowspec and recv_flowspec are set to the same values by the constructors // - process_sep_thread is always initialized to false by these constructors, you must // set it after calling the constructor if you want it to be true // - for information on QoS, WSAPROTOCOL_INFO, and FLOWSPEC, see the Winsock2 documentation udp_params(); udp_params(unsigned short local_port, bool find_qos = false, FLOWSPEC flowspec = def_flowspec); udp_params(unsigned long local_ip, unsigned short local_port, bool find_qos = false, FLOWSPEC flowspec = def_flowspec); udp_params(const char* local_ip, unsigned short local_port, bool find_qos = false, FLOWSPEC flowspec = def_flowspec); udp_params(unsigned short local_port, WSAPROTOCOL_INFO& protocol_info, FLOWSPEC flowspec = def_flowspec); udp_params(unsigned long local_ip, unsigned short local_port, WSAPROTOCOL_INFO& protocol_info, FLOWSPEC flowspec = def_flowspec); udp_params(const char* local_ip, unsigned short local_port, WSAPROTOCOL_INFO& protocol_info, FLOWSPEC flowspec = def_flowspec); udp_params(unsigned short local_port, unsigned long remote_ip, unsigned short remote_port, bool find_qos = false, FLOWSPEC flowspec = def_flowspec); udp_params(unsigned short local_port, const char* remote_ip, unsigned short remote_port, bool find_qos = false, FLOWSPEC flowspec = def_flowspec); udp_params(unsigned long local_ip, unsigned short local_port, unsigned long remote_ip, unsigned short remote_port, bool find_qos = false, FLOWSPEC flowspec = def_flowspec); udp_params(const char* local_ip, unsigned short local_port, const char* remote_ip, unsigned short remote_port, bool find_qos = false, FLOWSPEC flowspec = def_flowspec); udp_params(unsigned short local_port, unsigned long remote_ip, unsigned short remote_port, WSAPROTOCOL_INFO& protocol_info, FLOWSPEC flowspec = def_flowspec); udp_params(unsigned short local_port, const char* remote_ip, unsigned short remote_port, WSAPROTOCOL_INFO& protocol_info, FLOWSPEC flowspec = def_flowspec); udp_params(unsigned long local_ip, unsigned short local_port, unsigned long remote_ip, unsigned short remote_port, WSAPROTOCOL_INFO& protocol_info, FLOWSPEC flowspec = def_flowspec); udp_params(const char* local_ip, unsigned short local_port, const char* remote_ip, unsigned short remote_port, WSAPROTOCOL_INFO& protocol_info, FLOWSPEC flowspec = def_flowspec); unsigned long local_ip; unsigned short local_port; unsigned long remote_ip; unsigned short remote_port; bool do_connect; int multicast_ttl; bool multicast_loopback; int reuse_addr; WSAPROTOCOL_INFO protocol_info; bool use_protocol_info; bool find_qos; FLOWSPEC send_flowspec; FLOWSPEC recv_flowspec; bool use_flowspec; bool no_listen; DWORD listener_thread_affinity; int listener_thread_priority; }; bool operator == (const FLOWSPEC& lhs, const FLOWSPEC& rhs); bool operator != (const FLOWSPEC& lhs, const FLOWSPEC& rhs); #include "udp_message.h" #ifndef UDP_MSVS6_COMPAT typedef FastDelegate3<udp_message&, udp_connection*, void*> udp_msg_handler; #else typedef void(*udp_msg_handler)(udp_message&, udp_connection*, void*); #endif class udp_connection { static DWORD WINAPI udp_listener(LPVOID lp_param); private: SOCKET sock; udp_params create_params; WSADATA wsadata; bool did_connect; HANDLE listener_thread; volatile bool running; udp_msg_handler cbk; void* cbk_arg; bool init_wsa(); bool find_QOS_protocol(); bool init_socket(); bool connect_remote(); bool create_listener(); public: udp_connection(const udp_params& create_params); ~udp_connection(void); bool init_failed() const; void set_callback(udp_msg_handler handler, void* arg); bool send_message(const void* d, size_t len); bool send_message(const void* d, size_t len, const char* remote_ip, unsigned short remote_port) ; bool send_message(const void* d, size_t len, unsigned long remote_ip, unsigned short remote_port) ; }; #ifdef __cplusplus_cli #pragma managed(pop) #endif #endif //_udp_connection_H
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 158 ] ] ]
84c745d0d61492fe2f21a5d33582be31aea66011
0f67f4b756d4618c470f9c940d5bb7b902c98585
/UiModule/Inworld/View/UiProxyWidget.h
b55a6a2fe79162147389c45369c7ac4a634d3a1b
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
jonnenauha/naali
8dc7e5a9802f0206c97b067d8675f49e602f6488
50060338255e9e5f6427b2f57b93bb884954d14b
refs/heads/master
2020-12-25T08:38:09.291039
2010-03-20T13:22:58
2010-03-20T13:22:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,724
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_UiModule_UiProxyWidget_h #define incl_UiModule_UiProxyWidget_h #include "UiModuleApi.h" #include "UiWidgetProperties.h" #include <QGraphicsProxyWidget> class QTimeLine; class QParallelAnimationGroup; class QPropertyAnimation; namespace CoreUi { class MainPanelButton; } namespace UiServices { /*************** UiProxyWidget : QGraphicsProxyWidget -> QGraphicsWidget -> QGraphicsItem ***************/ class UI_MODULE_API UiProxyWidget : public QGraphicsProxyWidget { Q_OBJECT public: //! Constructor. //! \param widget //! \param in_widget_properties UiProxyWidget(QWidget *widget, const UiWidgetProperties &in_widget_properties); //! Destructor. ~UiProxyWidget(); //! Get this proxys widget properties /// \return UiWidgetProperties. UiWidgetProperties GetWidgetProperties() const { return widget_properties_; } //! Set control button for this proxy void SetControlButton(CoreUi::MainPanelButton *control_button); //! Get control button for this proxy CoreUi::MainPanelButton *GetControlButton() const { return control_button_; } //! Set new opacity void SetUnfocusedOpacity(int new_opacity); //! Set new show animation speed void SetShowAnimationSpeed(int new_speed); //! Brings to front in the scene, sets focus and shows this proxy widget. //! \todo Seems that isn't working properly. void BringToFront(); public slots: void AnimatedHide(); protected: //! QGraphicsProxyWidget override functions void showEvent(QShowEvent *show_event); void hideEvent(QHideEvent *hide_event); void closeEvent(QCloseEvent *close_event); void focusInEvent(QFocusEvent *focus_event); void focusOutEvent(QFocusEvent *focus_event); QVariant itemChange(GraphicsItemChange change, const QVariant &value); private slots: void InitWidgetAndProxy(QWidget *widget); void InitEffectsAndAnimations(); void FinishHide(); private: UiWidgetProperties widget_properties_; CoreUi::MainPanelButton *control_button_; QParallelAnimationGroup *animations_; QPropertyAnimation *fade_animation_; qreal unfocus_opacity_; bool show_animation_enabled_; signals: void Closed(); void Visible(bool); void BringProxyToFrontRequest(UiProxyWidget*); }; } #endif // incl_UiModule_UiProxyWidget_h
[ "jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3", "Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3", "[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3", "loorni@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 8 ], [ 14, 14 ], [ 20, 25 ], [ 27, 28 ], [ 32, 32 ], [ 35, 36 ], [ 61, 63 ], [ 68, 68 ], [ 73, 73 ], [ 75, 75 ], [ 81, 82 ], [ 84, 84 ], [ 86, 90 ] ], [ [ 9, 11 ], [ 26, 26 ], [ 29, 31 ], [ 33, 34 ], [ 39, 39 ], [ 43, 43 ], [ 53, 56 ], [ 60, 60 ], [ 64, 64 ], [ 83, 83 ] ], [ [ 12, 13 ], [ 15, 19 ], [ 37, 38 ], [ 40, 42 ], [ 44, 44 ], [ 46, 52 ], [ 57, 59 ], [ 65, 67 ], [ 69, 72 ], [ 74, 74 ], [ 76, 80 ], [ 85, 85 ] ], [ [ 45, 45 ] ] ]
1fd4a7dae35bf35bfcc17336c27c8b31997e886c
1bd75b9c45c3d5d5af3a9c9ba84ab0d4ec1bfd8f
/SpectrumGraph.h
9ea9b874da9a4ad002c4b63ad55fb23d3dfbd8cb
[]
no_license
nadernt/whistle-recognizer
168634eda147752fada31d1b4e073971a053b4bf
7f260f7ee38d9445e2f0806566bbc0ceb45d3986
refs/heads/master
2020-04-06T04:26:13.138539
2010-01-12T17:11:08
2017-02-23T12:22:25
82,922,754
1
0
null
null
null
null
UTF-8
C++
false
false
2,627
h
#if !defined(AFX_SPECTRUMGRAPH_H__D00FAB3B_95DC_433A_B106_D507409E1A0F__INCLUDED_) #define AFX_SPECTRUMGRAPH_H__D00FAB3B_95DC_433A_B106_D507409E1A0F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // SpectrumGraph.h : header file // ///////////////////////////////////////////////////////////////////////////// // CFrequencyGraph window enum FrequencyGraphType{ FG_OSCILLOSCOPE }; class CFrequencyGraph : public CWnd { // Construction public: CFrequencyGraph(); void SetNumberOfSteps(WORD nSteps) { m_wSteps = nSteps; } void SetLowColor(COLORREF clrLow) { m_clrLow = clrLow; } void SetMediumColor(COLORREF clrMedium) { m_clrMedium = clrMedium; } void SetHighColor(COLORREF clrHigh) { m_clrHigh = clrHigh; } void SetMediumLevel(int nLevel) { m_nMediumLevel = nLevel; } void SetHighLevel(int nLevel) { m_nHighLevel = nLevel; } void SetGrid(BOOL bGridOn=TRUE) { m_bGrid = bGridOn; } WORD GetNumberOfSteps() { return m_wSteps; } COLORREF GetLowColor() { return m_clrLow; } COLORREF GetMediumColor() { return m_clrMedium; } COLORREF GetHighColor() { return m_clrHigh; } int GetMediumLevel() { return m_nMediumLevel; } int GetHighLevel() { return m_nHighLevel; } BOOL GetGrid() { return m_bGrid; } /*void SetYRange(int nMin, int nMax) { m_nMinValue=nMin; m_nMaxValue=nMax; }*/ FrequencyGraphType GetGraphType() { return m_graphType; } void SetGraphType(FrequencyGraphType gType) { m_graphType = gType; } void Update(int nNumber, double* dArray);//Takes Intensity after FFT is performed on Wave Data protected: int m_nLength; int m_nMinValue; int m_nMaxValue; int m_nHighLevel; int m_nMediumLevel; WORD m_wSteps; COLORREF m_clrLow; COLORREF m_clrMedium; COLORREF m_clrHigh; BOOL m_bGrid; FrequencyGraphType m_graphType; void Point(HDC hDC, int x, int y, COLORREF color); BOOL Line(HDC hDC, int x1, int y1, int x2, int y2); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFrequencyGraph) //}}AFX_VIRTUAL // Implementation public: virtual ~CFrequencyGraph(); // Generated message map functions protected: //{{AFX_MSG(CFrequencyGraph) afx_msg void OnPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_SPECTRUMGRAPH_H__D00FAB3B_95DC_433A_B106_D507409E1A0F__INCLUDED_)
[ [ [ 1, 87 ] ] ]
da462dc7f924cf913f8f83ad8c4fb660f5b18cdb
b4d726a0321649f907923cc57323942a1e45915b
/CODE/HUD/hudtarget.cpp
17d8990a56e8c9d2b588ee076c6155555360f8e7
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
189,047
cpp
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ /* * $Logfile: /Freespace2/code/Hud/HUDtarget.cpp $ * $Revision: 1.1.1.1 $ * $Date: 2004/08/13 22:47:41 $ * $Author: Spearhawk $ * * C module to provide HUD targeting functions * * $Log: hudtarget.cpp,v $ * Revision 1.1.1.1 2004/08/13 22:47:41 Spearhawk * no message * * Revision 1.1.1.1 2004/08/13 20:49:33 Darkhill * no message * * Revision 2.30 2004/05/10 10:51:53 Goober5000 * made primary and secondary banks quite a bit more friendly... added error-checking * and reorganized a bunch of code * --Goober5000 * * Revision 2.29 2004/05/10 08:03:30 Goober5000 * fixored the handling of no lasers and no engines... the tests should check the ship, * not the object * --Goober5000 * * Revision 2.28 2004/05/07 19:06:45 Goober5000 * added Righteous1's Y bug hack * --Goober5000 * * Revision 2.27 2004/03/31 04:24:49 Goober5000 * got rid of Bobboau's SAFEPOINTs in hudtarget.cpp * --Goober5000 * * Revision 2.26 2004/03/06 23:28:23 bobboau * fixed motion debris * animated laser textures * and added a new error check called a safepoint, mostly for tracking the 'Y bug' * * Revision 2.25 2004/03/05 09:02:04 Goober5000 * Uber pass at reducing #includes * --Goober5000 * * Revision 2.24 2004/01/30 07:39:07 Goober5000 * whew - I just went through all the code I ever added (or at least, that I could * find that I commented with a Goober5000 tag) and added a bunch of Asserts * and error-checking * --Goober5000 * * Revision 2.23 2003/12/16 21:06:21 phreak * disabled tertiary weapons support pending a rewrite of critical code * * Revision 2.22 2003/09/13 06:02:05 Goober5000 * clean rollback of all of argv's stuff * --Goober5000 * * Revision 2.19 2003/09/09 05:51:14 Goober5000 * if player has primitive sensors, hud will not display shield icons or message sender brackets * --Goober5000 * * Revision 2.18 2003/08/22 07:35:08 bobboau * specular code should be bugless now, * cell shadeing has been added activated via the comand line '-cell', * 3D shockwave models, and a transparency method I'm calling edge and center alpha that could be usefull for other things, ask for details * * Revision 2.17 2003/08/21 06:31:19 Goober5000 * ships that have no afterburners will no longer have the afterburner gauge drawn * --Goober5000 * * Revision 2.16 2003/08/21 06:18:52 Goober5000 * primary weapons will now truncate properly at a '#' symbol, just like secondaries * --Goober5000 * * Revision 2.15 2003/08/06 17:44:20 phreak * changed the weapon ammo gauges to show additional ammo if a tertiary ammo pod is being used * * Revision 2.14 2003/06/11 02:59:47 phreak * local ssm stuff for hud. * they are always in lock range due to the subspace drive on them * they also can't be targeted when in stage 3. * * Revision 2.13 2003/04/29 01:03:23 Goober5000 * implemented the custom hitpoints mod * --Goober5000 * * Revision 2.12 2003/01/17 07:59:09 Goober5000 * fixed some really strange behavior with strings not being truncated at the * # symbol * --Goober5000 * * Revision 2.11 2003/01/03 21:58:08 Goober5000 * Fixed some minor bugs, and added a primitive-sensors flag, where if a ship * has primitive sensors it can't target anything and objects don't appear * on radar if they're outside a certain range. This range can be modified * via the sexp primitive-sensors-set-range. * --Goober5000 * * Revision 2.10 2002/12/31 19:18:41 Goober5000 * if it ain't broke, don't fix it * --Goober5000 * * Revision 2.8 2002/12/22 21:31:01 Goober5000 * tweaked positioning of the new HUD graphics * --Goober5000 * * Revision 2.7 2002/12/21 18:03:49 Goober5000 * commented out the warning if you don't have the new ballistic HUD graphics - it would probably get annoying (just use the old ones without comment) * --Goober5000 * * Revision 2.6 2002/12/19 10:54:37 Goober5000 * oops - squashed a bug :) * --Goober5000 * * Revision 2.5 2002/12/19 10:46:14 Goober5000 * implemented the revised HUD weapon display for ballistic primaries * --Goober5000 * * Revision 2.4 2002/12/13 08:13:30 Goober5000 * small tweaks and bug fixes for the ballistic primary conversion * ~Goober5000~ * * Revision 2.3 2002/12/10 05:42:42 Goober5000 * Full-fledged ballistic primary support added! Try it and see! :) * * Fixed lead indicator behavior; Phreak's version didn't work properly. * * Revision 2.2 2002/09/20 20:02:00 phreak * lead indicator for dumbfire missiles * * Revision 2.1 2002/08/01 01:41:05 penguin * The big include file move * * Revision 2.0 2002/06/03 04:02:23 penguin * Warpcore CVS sync * * Revision 1.6 2002/05/28 20:24:12 mharris * Changed alphacolor (in hud_auto_speed_match_icon) to static * * Revision 1.5 2002/05/26 14:12:03 mharris * Changed alphacolors from automatic to static * * Revision 1.4 2002/05/13 21:09:28 mharris * I think the last of the networking code has ifndef NO_NETWORK... * * Revision 1.3 2002/05/13 15:11:03 mharris * More NO_NETWORK ifndefs added * * Revision 1.2 2002/05/03 22:07:08 mharris * got some stuff to compile * * Revision 1.1 2002/05/02 18:03:08 mharris * Initial checkin - converted filenames and includes to lower case * * * 43 11/01/99 11:22a Jefff * some weapon name translations * * 42 9/15/99 1:59p Mikek * Fix bug in targeting due to Alt-Y (target last ship sending * transmission). Was just bogus code in the call to * hud_restore_subsystem_target().pm. * * 41 9/08/99 11:42p Andsager * Remove maximum target distance check when finding enemy target * * 40 9/07/99 11:26p Andsager * Fix "r" targeting key, making evaluate_ship_as_closest_target() and * hud_target_live_turret() consider if turret is targeting player * * 39 9/01/99 12:58a Andsager * Make all targeting keys able to choose turret on BIG|HUGE ships * * 38 8/24/99 2:55p Andsager * Add new prioritized turret selection code. * * 37 8/18/99 10:59p Andsager * Enable "b" key to target bombers. * * 36 8/17/99 8:32p Jefff * fixes to auto-speed/target so it looks much better in the nebula * * 35 8/17/99 7:15p Jefff * auto-target & auto-speed text drawn in code * * 34 8/04/99 9:54a Andsager * Auto target turrets on big ships. * * 33 8/02/99 4:03p Andsager * target closest favors beams and flak * * 32 8/01/99 12:39p Dave * Added HUD contrast control key (for nebula). * * 31 7/30/99 11:10a Andsager * Modify hud_target_closest() to consider turrets against all ships, not * just player * * 30 7/15/99 5:41p Andsager * Clean up demo build * * 29 7/15/99 9:20a Andsager * FS2_DEMO initial checkin * * 28 7/09/99 12:00a Andsager * Added target box with distance for remote detonate weapons * * 27 7/07/99 4:31p Andsager * Make closest_attacking_hostile guage respect stealth. Kill a bunch of * goto's. * * 26 7/01/99 11:44a Dave * Updated object sound system to allow multiple obj sounds per ship. * Added hit-by-beam sound. Added killed by beam sound. * * 25 6/17/99 9:04a Andsager * Fix hack * * 24 6/16/99 5:32p Andsager * HACK temp fix * * 23 6/15/99 9:24a Andsager * Make hotkeys work with stealth * * 22 6/10/99 3:43p Dave * Do a better job of syncing text colors to HUD gauges. * * 21 6/09/99 2:55p Andsager * Allow multiple asteroid subtypes (of large, medium, small) and follow * family. * * 20 6/08/99 8:35a Jasenw * new coords for new lead indicator * * 19 6/07/99 4:20p Andsager * Add HUD color for tagged object. Apply to target and radar. * * 18 6/02/99 3:23p Andsager * Make AI aware of team visibility. Allow player targeting with team * visibility info. Make stealth ships not targetable by AI in nebula * unless tagged. * * 17 5/24/99 9:00a Andsager * modify target next/prev live turret only when turret has a weapon * * 16 4/20/99 6:39p Dave * Almost done with artillery targeting. Added support for downloading * images on the PXO screen. * * 15 2/25/99 4:19p Dave * Added multiplayer_beta defines. Added cd_check define. Fixed a few * release build warnings. Added more data to the squad war request and * response packets. * * 14 1/27/99 3:02p Anoop * Fixed 640 HUD afterburner and weapon energy gauge. * * 13 1/25/99 5:03a Dave * First run of stealth, AWACS and TAG missile support. New mission type * :) * * 12 1/07/99 10:07a Jasen * coords * * 11 1/07/99 9:06a Jasen * coords * * 10 1/06/99 2:24p Dave * Stubs and release build fixes. * * 9 12/29/98 7:21p Dave * Put in a bunch of missing hi-res coord globalizations. * * 8 12/29/98 2:29p Jasen * added new coords for some 1024 HUD stuff. * * 7 12/28/98 3:17p Dave * Support for multiple hud bitmap filenames for hi-res mode. * * 5 12/21/98 5:03p Dave * Modified all hud elements to be multi-resolution friendly. * * 4 11/05/98 4:18p Dave * First run nebula support. Beefed up localization a bit. Removed all * conditional compiles for foreign versions. Modified mission file * format. * * 3 10/13/98 9:28a Dave * Started neatening up freespace.h. Many variables renamed and * reorganized. Added AlphaColors.[h,cpp] * * 2 10/07/98 10:53a Dave * Initial checkin. * * 1 10/07/98 10:49a Dave * * 407 9/21/98 9:27a Dave * Special case code to draw Cluster Bomb as Cluster on the HUD. * * 406 8/28/98 3:28p Dave * EMP effect done. AI effects may need some tweaking as required. * * 405 8/25/98 1:48p Dave * First rev of EMP effect. Player side stuff basically done. Next comes * AI code. * * 404 6/12/98 4:52p Hoffoss * Added support for special characters in in forgeign languages. * * 403 6/09/98 5:17p Lawrance * French/German localization * * 402 6/09/98 10:31a Hoffoss * Created index numbers for all xstr() references. Any new xstr() stuff * added from here on out should be added to the end if the list. The * current list count can be found in FreeSpace.cpp (search for * XSTR_SIZE). * * 401 5/27/98 1:24p Allender * make targeting dots work (as well as other targeting features) properly * in multiplayer. Don't query for CD when entering debrief in * multiplayer * * 400 5/27/98 1:20p Mike * Fix bug in target nearest ship attacking target. * */ #include "hud/hud.h" #include "hud/hudartillery.h" #include "hud/hudlock.h" #include "hud/hudmessage.h" #include "hud/hudtarget.h" #include "hud/hudreticle.h" #include "hud/hudbrackets.h" #include "object/object.h" #include "ship/ship.h" #include "render/3dinternal.h" #include "globalincs/linklist.h" #include "weapon/weapon.h" #include "playerman/player.h" #include "freespace2/freespace.h" // for flFrametime #include "io/timer.h" #include "gamesnd/gamesnd.h" #include "debris/debris.h" #include "mission/missionmessage.h" #include "hud/hudtargetbox.h" #include "ship/subsysdamage.h" #include "hud/hudshield.h" #include "mission/missionhotkey.h" #include "asteroid/asteroid.h" #include "jumpnode/jumpnode.h" #include "network/multi.h" #include "weapon/emp.h" #include "globalincs/alphacolors.h" #include "localization/localize.h" #include "ship/awacs.h" #include "parse/parselo.h" #include "Cmdline/cmdline.h" // If any of these bits in the ship->flags are set, ignore this ship when targetting int TARGET_SHIP_IGNORE_FLAGS = (SF_EXPLODED|SF_DEPART_WARP|SF_DYING|SF_ARRIVING_STAGE_1|SF_HIDDEN_FROM_SENSORS); // Global values for the target bracket width and height, used for debugging int Hud_target_w, Hud_target_h; // offscreen triangle that point the the off-screen target float Offscreen_tri_base[GR_NUM_RESOLUTIONS] = { 6.0f, 9.5f }; float Offscreen_tri_height[GR_NUM_RESOLUTIONS] = { 7.0f, 11.0f }; float Max_offscreen_tri_seperation[GR_NUM_RESOLUTIONS] = { 10.0f, 16.0f }; float Max_front_seperation[GR_NUM_RESOLUTIONS] = { 10.0f, 16.0f }; // The following variables are global to this file, and do not need to be persistent from frame-to-frame // This means the variables are not player-specific static int Target_in_reticle = 0; static int ballistic_hud_index = 0; // Goober5000 extern object obj_used_list; // dummy node in linked list of active objects extern char *Cargo_names[]; // shader is used to shade the target box shader Training_msg_glass; // the target triangle (that orbits the reticle) dimensions float Target_triangle_base[GR_NUM_RESOLUTIONS] = { 6.0f, 9.5f }; float Target_triangle_height[GR_NUM_RESOLUTIONS] = { 7.0f, 11.0f }; // stuff for hotkey targeting lists htarget_list htarget_items[MAX_HOTKEY_TARGET_ITEMS]; htarget_list htarget_free_list; // coordinates and widths used to render the HUD afterburner energy gauge int Aburn_coords[GR_NUM_RESOLUTIONS][4] = { { // GR_640 252,344, 60, 60 //171, 265, 60, 60 }, { // GR_1024 274, 424, 86, 96 } }; // coordinates and widths used to render the HUD weapons energy gauge int Wenergy_coords[GR_NUM_RESOLUTIONS][4] = { { // GR_640 326,344, 60, 60 //416, 265, 60, 60 }, { // GR_1024 666, 424, 86, 96 } }; #define MIN_DISTANCE_TO_CONSIDER_THREAT 1500 // min distance to show hostile warning triangle ////////////////////////////////////////////////////////////////////////// // lists for target in reticle cycling ////////////////////////////////////////////////////////////////////////// #define RL_USED (1<<0) #define RL_USE_DOT (1<<1) // use dot product result, not distance typedef struct _reticle_list { _reticle_list *next, *prev; object *objp; float dist, dot; int flags; } reticle_list; #define RESET_TARGET_IN_RETICLE 750 int Reticle_save_timestamp; reticle_list Reticle_cur_list; reticle_list Reticle_save_list; #define MAX_RETICLE_TARGETS 50 reticle_list Reticle_list[MAX_RETICLE_TARGETS]; ////////////////////////////////////////////////////////////////////////// // used for closest target cycling ////////////////////////////////////////////////////////////////////////// #define TL_RESET 1500 #define TURRET_RESET 1000 static int Tl_hostile_reset_timestamp; static int Tl_friendly_reset_timestamp; static int Target_next_uninspected_object_timestamp; static int Target_newest_ship_timestamp; static int Target_next_turret_timestamp; // animation frames for the hud targeting gauges // frames: 0 => out of range lead // 1 => in range lead float Lead_indicator_half[GR_NUM_RESOLUTIONS][2] = { { // GR_640 8.0f, // half-width 8.0f // half-height }, { // GR_1024 13.0f, // half-width 13.0f // half-height } }; hud_frames Lead_indicator_gauge; int Lead_indicator_gauge_loaded = 0; char Lead_fname[GR_NUM_RESOLUTIONS][MAX_FILENAME_LEN] = { "lead1", "2_lead1" }; // animation frames for the afterburner gauge and the weapon energy gauge // frames: 0 => afterburner dark // 1 => afterburner light // 2 => gun energy dark // 3 => gun energy light hud_frames Energy_bar_gauges; int Energy_bar_gauges_loaded = 0; char Energy_fname[GR_NUM_RESOLUTIONS][MAX_FILENAME_LEN] = { "energy2", "2_energy2" }; int Weapon_energy_text_coords[GR_NUM_RESOLUTIONS][2] = { { // GR_640 326,344//439, 318 }, { // GR_1024 708, 509 } }; // animation frames for the countermeasures gauge // frames: 0 => background /*hud_frames Cmeasure_gauge; int Cmeasure_gauge_loaded = 0; int Cm_coords[GR_NUM_RESOLUTIONS][2] = { { // GR_640 497, 343 }, { // GR_1024 880, 602 } };*/ int Cm_text_coords[GR_NUM_RESOLUTIONS][2] = { { // GR_640 533, 347 }, { // GR_1024 916, 606 } }; int Cm_text_val_coords[GR_NUM_RESOLUTIONS][2] = { { // GR_640 362,12//506, 347 }, { // GR_1024 889, 606 } }; /*char Cm_fname[GR_NUM_RESOLUTIONS][MAX_FILENAME_LEN] = { "countermeasure1", "countermeasure1" };*/ // animation frames for the auto-target and auto-match_speed icons // frames: 0 => auto-target off // 1 => auto-target on // 2 => auto-match-speed on // 3 => auto-match-speed off //hud_frames Toggle_gauge; //int Toggle_gauge_loaded = 0; int Toggle_target_gauge_coords[GR_NUM_RESOLUTIONS][2] = { { // GR_640 577, 380 }, { // GR_1024 960, 648 } }; int Toggle_speed_gauge_coords[GR_NUM_RESOLUTIONS][2] = { { // GR_640 577, 404 }, { // GR_1024 960, 672 } }; /*char Toggle_fname[GR_NUM_RESOLUTIONS][MAX_FILENAME_LEN] = { "toggle1", "toggle1" };*/ #define TOGGLE_TEXT_AUTOT 0 #define TOGGLE_TEXT_TARGET 1 #define TOGGLE_TEXT_AUTOS 2 #define TOGGLE_TEXT_SPEED 3 static int Hud_toggle_coords[GR_NUM_RESOLUTIONS][4][2] = { { // GR_640 // auto target {394,448},//{ 590, 382 }, {388,456},//{ 584, 390 }, // auto speed {273,10},//{ 590, 406 }, {270,18}//{ 587, 414 } }, { // GR_1024 { 973, 650 }, { 967, 658 }, { 973, 674 }, { 970, 682 } } }; static int Toggle_text_alpha = 255; // animation files for the weapons gauge #define NUM_WEAPON_GAUGES 5 #define NUM_HUD_SETTINGS 2 hud_frames Weapon_gauges[NUM_HUD_SETTINGS][NUM_WEAPON_GAUGES]; int Weapon_gauges_loaded = 0; // for primaries /*int Weapon_gauge_primary_coords[NUM_HUD_SETTINGS][GR_NUM_RESOLUTIONS][3][2] = { { // normal HUD { // GR_640 // based on the # of primaries {509, 273}, // top of weapon gauge, first frame, always {497, 293}, // for the first primary {497, 305} // for the second primary }, { // GR_1024 // based on the # of primaries {892, 525}, // top of weapon gauge, first frame, always {880, 545}, // for the first primary {880, 557} // for the second primary } }, { // ballistic HUD - slightly different alignment { // GR_640 // based on the # of primaries {485, 273}, // top of weapon gauge, first frame, always {485, 293}, // for the first primary {485, 305} // for the second primary }, { // GR_1024 // based on the # of primaries {868, 525}, // top of weapon gauge, first frame, always {868, 545}, // for the first primary {868, 557} // for the second primary } } }; int Weapon_gauge_secondary_coords[NUM_HUD_SETTINGS][GR_NUM_RESOLUTIONS][5][2] = { { // normal HUD { // GR_640 // based on the # of secondaries {497, 318}, // bottom of gauge, 0 secondaries {497, 318}, // bottom of gauge, 1 secondaries {497, 317}, // middle of gauge, 2 secondaries AND middle of gauge, 3 secondaries {497, 326}, // bottom of gauge, 2 secondaries AND middle of gauge, 3 secondaries {497, 335} // bottom of gauge, 3 secondaries }, { // GR_1024 // based on the # of secondaries {880, 570}, // bottom of gauge, 0 secondaries {880, 570}, // bottom of gauge, 1 secondaries {880, 569}, // middle of gauge, 2 secondaries AND middle of gauge, 3 secondaries {880, 578}, // bottom of gauge, 2 secondaries AND middle of gauge, 3 secondaries {880, 587} // bottom of gauge, 3 secondaries } }, { // ballistic HUD - slightly different alignment { // GR_640 // based on the # of secondaries {485, 318}, // bottom of gauge, 0 secondaries {485, 318}, // bottom of gauge, 1 secondaries {485, 317}, // middle of gauge, 2 secondaries AND middle of gauge, 3 secondaries {485, 326}, // bottom of gauge, 2 secondaries AND middle of gauge, 3 secondaries {485, 335} // bottom of gauge, 3 secondaries }, { // GR_1024 // based on the # of secondaries {868, 570}, // bottom of gauge, 0 secondaries {868, 570}, // bottom of gauge, 1 secondaries {868, 569}, // middle of gauge, 2 secondaries AND middle of gauge, 3 secondaries {868, 578}, // bottom of gauge, 2 secondaries AND middle of gauge, 3 secondaries {868, 587} // bottom of gauge, 3 secondaries } } };*/ int Weapon_title_coords[NUM_HUD_SETTINGS][GR_NUM_RESOLUTIONS][2] = { { // normal HUD { // GR_640 50, 372 // 518, 274 -diff- x = subtract 468 y = add 98 }, { // GR_1024 901, 527 } }, { // ballistic HUD - slightly different alignment { // GR_640 487, 274 }, { // GR_1024 870, 527 } } }; int Weapon_plink_coords[GR_NUM_RESOLUTIONS][2][2] = { { // GR_640 {50, 383},//{530, 285}, // fire-linked thingie, for the first primary {50, 393},//{530, 295} // fire-linked thingie, for the second primary }, { // GR_1024 {913, 537}, // fire-linked thingie, for the first primary {913, 547} // fire-linked thingie, for the second primary } }; int Weapon_pname_coords[GR_NUM_RESOLUTIONS][2][2] = { { // GR_640 {56, 383}, // {536, 285}// weapon name, first primary {56, 393} //{536,295}, // weapon name, second primary }, { // GR_1024 {919, 537}, // weapon name, first primary {919, 547} // weapon name, second primary } }; int Weapon_slinked_x[GR_NUM_RESOLUTIONS] = { 52,//525, // where to draw the second thingie if this weapon is fire-linked 908 }; int Weapon_sunlinked_x[GR_NUM_RESOLUTIONS] = { 50, //62, //530, // where to draw the first thingie if this weapon is selected at all (fire-linked or not) 913 }; int Weapon_secondary_y[GR_NUM_RESOLUTIONS][3] = { { // GR_640 407,//309, // y location of where to draw text for the first secondary 416,//318, // y location of where to draw text for the second secondary 425//327 // y location of where to draw text for the third secondary }, { // GR_1024 561, // y location of where to draw text for the third secondary 570, // y location of where to draw text for the third secondary 579 // y location of where to draw text for the third secondary } }; int Weapon_primary_y[GR_NUM_RESOLUTIONS][2] = { { // GR_640 383,//285, // y location of where to draw text for the first primary 295 // y location of where to draw text for the second primary }, { // GR_1024 537, // y location of where to draw text for the first primary 547 // y location of where to draw text for the second primary } }; int Weapon_secondary_name_x[GR_NUM_RESOLUTIONS] = { 56,//68, //536, // x location of where to draw weapon name 919 }; int Weapon_secondary_ammo_x[GR_NUM_RESOLUTIONS] = { 45, //57, //525, // x location of where to draw weapon ammo count 908 }; int Weapon_primary_ammo_x[GR_NUM_RESOLUTIONS] = { 45, //57, //525, // x location of where to draw primary weapon ammo count 908 }; int Weapon_secondary_reload_x[GR_NUM_RESOLUTIONS] = { 135, //615, // x location of where to draw the weapon reload time 998 }; /*char *Weapon_gauge_fnames[NUM_HUD_SETTINGS][GR_NUM_RESOLUTIONS][NUM_WEAPON_GAUGES] = { //XSTR:OFF { // normal HUD { // GR_640 "weapons1", "weapons2", "weapons3", "weapons4", "weapons5" }, { // GR_1024 "weapons1", "weapons2", "weapons3", "weapons4", "weapons5" } }, { // ballistic HUD - slightly different alignment { // GR_640 "weapons1_b", "weapons2_b", "weapons3_b", "weapons4_b", "weapons5_b" }, { // GR_1024 "weapons1_b", "weapons2_b", "weapons3_b", "weapons4_b", "weapons5_b" } } //XSTR:ON };*/ // Flash the line for a weapon. This normally occurs when the player tries to fire that // weapon, but the firing fails (due to lack of energy or damaged weapons subsystem). #define MAX_WEAPON_FLASH_LINES 7 // 3 primary and 4 secondary typedef struct weapon_flash { int flash_duration[MAX_WEAPON_FLASH_LINES]; int flash_next[MAX_WEAPON_FLASH_LINES]; int is_bright; } weapon_flash; weapon_flash Weapon_flash_info; // Data used for the proximity warning typedef struct homing_beep_info { int snd_handle; // sound handle for last played beep fix last_time_played; // time beep was last played int min_cycle_time; // time (in ms) for fastest cycling of the sound int max_cycle_time; // time (in ms) for slowest cycling of the sound float min_cycle_dist; // distance at which fastest cycling occurs float max_cycle_dist; // distance at which slowest cycling occurs float precalced_interp; // a precalculated value used in a linear interpretation } homing_beep_info; homing_beep_info Homing_beep = { -1, 0, 150, 1000, 30.0f, 1500.0f }; // Set at the start of a mission, used to decide how to draw the separation for the warning missile indicators float Min_warning_missile_dist; float Max_warning_missile_dist; void hud_maybe_flash_weapon(int index); // if a given object should be ignored because of AWACS effects int hud_target_invalid_awacs(object *objp) { // if objp is ship object, first check if can be targeted with team info if (objp->type == OBJ_SHIP) { if (Player_ship != NULL) { if (ship_is_visible_by_team_new(objp, Player_ship)) { return 0; } } } // check for invalid status if((Player_ship != NULL) && (awacs_get_level(objp, Player_ship) < 1.0f)){ return 1; } // valid return 0; } ship_subsys *advance_subsys(ship_subsys *cur, int next_flag) { if (next_flag) { return GET_NEXT(cur); } else { return GET_LAST(cur); } } // select a sorted turret subsystem on a ship if no other subsys has been selected void hud_maybe_set_sorted_turret_subsys(ship *shipp) { Assert((Player_ai->target_objnum >= 0) && (Player_ai->target_objnum < MAX_OBJECTS)); if (!((Player_ai->target_objnum >= 0) && (Player_ai->target_objnum < MAX_OBJECTS))) { return; } Assert(Objects[Player_ai->target_objnum].type == OBJ_SHIP); if (Objects[Player_ai->target_objnum].type != OBJ_SHIP) { return; } if (Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) { if (shipp->last_targeted_subobject[Player_num] == NULL) { hud_target_live_turret(1, 1); } } } // ----------------------------------------------------------------------- // clear out the linked list of targets in the reticle void hud_reticle_clear_list(reticle_list *rlist) { reticle_list *cur; for ( cur = GET_FIRST(rlist); cur != END_OF_LIST(rlist); cur = GET_NEXT(cur) ) { cur->flags = 0; } list_init(rlist); } // -------------------------------------------------------------------------------------- // hud_reticle_list_init() void hud_reticle_list_init() { int i; for ( i = 0; i < MAX_RETICLE_TARGETS; i++ ) { Reticle_list[i].flags = 0; } Reticle_save_timestamp = 1; list_init(&Reticle_save_list); list_init(&Reticle_cur_list); } // -------------------------------------------------------------------------------------- // hud_check_reticle_list() // // void hud_check_reticle_list() { reticle_list *rl, *temp; // cull dying objects from reticle list rl = GET_FIRST(&Reticle_cur_list); while( rl !=END_OF_LIST(&Reticle_cur_list) ) { temp = GET_NEXT(rl); if ( rl->objp->flags & OF_SHOULD_BE_DEAD ) { list_remove( &Reticle_cur_list, rl ); rl->flags = 0; } rl = temp; } if ( timestamp_elapsed(Reticle_save_timestamp) ) { hud_reticle_clear_list(&Reticle_save_list); Reticle_save_timestamp = timestamp(RESET_TARGET_IN_RETICLE); } } // -------------------------------------------------------------------------------------- // hud_reticle_list_find_free() // // int hud_reticle_list_find_free() { int i; // find a free reticle_list element for ( i = 0; i < MAX_RETICLE_TARGETS; i++ ) { if ( !(Reticle_list[i].flags & RL_USED) ) { break; } } if ( i == MAX_RETICLE_TARGETS ) { // nprintf(("Warning","Warning ==> Ran out of reticle target elements...\n")); return -1; } return i; } // -------------------------------------------------------------------------------------- // hud_stuff_reticle_list() // // #define RETICLE_DEFAULT_DIST 100000.0f #define RETICLE_DEFAULT_DOT 1.0f void hud_stuff_reticle_list(reticle_list *rl, object *objp, float measure, int dot_flag) { if ( dot_flag ) { rl->dot = measure; rl->dist = RETICLE_DEFAULT_DIST; rl->flags |= RL_USE_DOT; } else { rl->dist = measure; rl->dot = RETICLE_DEFAULT_DOT; } rl->objp = objp; } // -------------------------------------------------------------------------------------- // hud_reticle_list_update() // // Update Reticle_cur_list with an object that lies in the reticle // // parmeters: objp => object pointer to target // measure => distance or dot product, depending on dot_flag // dot_flag => if 0, measure is distance, if 1 measure is dot // void hud_reticle_list_update(object *objp, float measure, int dot_flag) { reticle_list *rl, *new_rl; int i; for ( rl = GET_FIRST(&Reticle_cur_list); rl != END_OF_LIST(&Reticle_cur_list); rl = GET_NEXT(rl) ) { if ( rl->objp == objp ) return; } i = hud_reticle_list_find_free(); if ( i == -1 ) return; new_rl = &Reticle_list[i]; new_rl->flags |= RL_USED; hud_stuff_reticle_list(new_rl, objp, measure, dot_flag); int was_inserted = 0; if ( EMPTY(&Reticle_cur_list) ) { list_insert(&Reticle_cur_list, new_rl); was_inserted = 1; } else { for ( rl = GET_FIRST(&Reticle_cur_list); rl != END_OF_LIST(&Reticle_cur_list); rl = GET_NEXT(rl) ) { if ( !dot_flag ) { // compare based on distance if ( measure < rl->dist ) { list_insert_before(rl, new_rl); was_inserted = 1; break; } } else { // compare based on dot if ( measure > rl->dot ) { list_insert_before(rl, new_rl); was_inserted = 1; break; } } } // end for } if ( !was_inserted ) { list_append(&Reticle_cur_list, new_rl); } } // -------------------------------------------------------------------------------------- // hud_reticle_pick_target() // // Pick a target from Reticle_cur_list, based on what is in Reticle_save_list // // object *hud_reticle_pick_target() { reticle_list *cur_rl, *save_rl, *new_rl; object *return_objp; int in_save_list, i; return_objp = NULL; // As a first step, see if both ships and debris are in the list. If so, cull the debris. int debris_in_list = 0; int ship_in_list = 0; for ( cur_rl = GET_FIRST(&Reticle_cur_list); cur_rl != END_OF_LIST(&Reticle_cur_list); cur_rl = GET_NEXT(cur_rl) ) { if ( (cur_rl->objp->type == OBJ_SHIP) || (cur_rl->objp->type == OBJ_JUMP_NODE) ) { ship_in_list = 1; continue; } if ( cur_rl->objp->type == OBJ_WEAPON ) { if ( Weapon_info[Weapons[cur_rl->objp->instance].weapon_info_index].subtype == WP_MISSILE ) { ship_in_list = 1; continue; } } if ( (cur_rl->objp->type == OBJ_DEBRIS) || (cur_rl->objp->type == OBJ_ASTEROID) ) { debris_in_list = 1; continue; } } // Commented out to correct 'Y' bug. Current theory is that // debris gets targeted during the previous pass. When the // command is executed again, the target is culled. // if ( ship_in_list && debris_in_list ) { // // cull debris // reticle_list *rl, *next; // // rl = GET_FIRST(&Reticle_cur_list); // while ( rl != &Reticle_cur_list ) { // next = rl->next; // if ( (rl->objp->type == OBJ_DEBRIS) || (rl->objp->type == OBJ_ASTEROID) ){ // list_remove(&Reticle_cur_list,rl); // rl->flags = 0; // } // rl = next; // } // } for ( cur_rl = GET_FIRST(&Reticle_cur_list); cur_rl != END_OF_LIST(&Reticle_cur_list); cur_rl = GET_NEXT(cur_rl) ) { // The following was added to replace the culling method used above. Rather than // cull the debris, just skip to the next object if there's ships in the FOV. if ( ship_in_list && debris_in_list ) { if ( (cur_rl->objp->type == OBJ_DEBRIS) || (cur_rl->objp->type == OBJ_ASTEROID) ){ continue; } } in_save_list = 0; for ( save_rl = GET_FIRST(&Reticle_save_list); save_rl != END_OF_LIST(&Reticle_save_list); save_rl = GET_NEXT(save_rl) ) { if ( cur_rl->objp == save_rl->objp ) { in_save_list = 1; break; } } if ( !in_save_list ) { return_objp = cur_rl->objp; i = hud_reticle_list_find_free(); if ( i == -1 ) break; new_rl = &Reticle_list[i]; new_rl->flags |= RL_USED; if ( cur_rl->flags & RL_USE_DOT ) { hud_stuff_reticle_list(new_rl, cur_rl->objp, cur_rl->dot, 1); } else { hud_stuff_reticle_list(new_rl, cur_rl->objp, cur_rl->dist, 0); } list_append(&Reticle_save_list, new_rl); break; } } // end for if ( return_objp == NULL && !EMPTY(&Reticle_cur_list) ) { i = hud_reticle_list_find_free(); if ( i == -1 ) return NULL; new_rl = &Reticle_list[i]; // if there are ships and debris present, loop through to find the ship(s) // otherwise, pick the first object if ( ship_in_list && debris_in_list ) { for ( cur_rl = GET_FIRST(&Reticle_cur_list); cur_rl != END_OF_LIST(&Reticle_cur_list); cur_rl = GET_NEXT(cur_rl) ) { if ( (cur_rl->objp->type == OBJ_DEBRIS) || (cur_rl->objp->type == OBJ_ASTEROID) ){ continue; } else { break; } } } else { cur_rl = GET_FIRST(&Reticle_cur_list); } *new_rl = *cur_rl; return_objp = cur_rl->objp; hud_reticle_clear_list(&Reticle_save_list); list_append(&Reticle_save_list, new_rl); } return return_objp; } // hud_target_hotkey_add_remove takes as its parameter which hotkey (1-0) to add/remove the current // target from. This function behaves like the Shift-<selection> does in Windows -- using shift # will toggle // the current target in and out of the selection set. void hud_target_hotkey_add_remove( int k, object *ctarget, int how_to_add ) { htarget_list *hitem, *plist; #ifndef NO_NETWORK // don't do anything if a standalone multiplayer server if ( MULTIPLAYER_STANDALONE ) return; #endif if ( k < 0 || k > 7 ) { nprintf(("Warning", "Bogus hotkey %d sent to hud_target_hotkey_add_remove\n")); return; } plist = &(Players[Player_num].keyed_targets[k]); // we must operate only on ships if ( ctarget->type != OBJ_SHIP ) return; // don't allow player into hotkey set if ( ctarget == Player_obj ) return; // don't put dying or departing if ( Ships[ctarget->instance].flags & (SF_DYING|SF_DEPARTING) ) return; // don't add mission file added hotkey assignments if there are player added assignments // already in the list if ( (how_to_add == HOTKEY_MISSION_FILE_ADDED) && NOT_EMPTY(plist) ) { for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { if ( hitem->how_added == HOTKEY_USER_ADDED ) return; } } // determine if the current target is currently in the set or not for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { if ( hitem->objp == ctarget ) break; } // if hitem == end of the list, then the target should be added, else it should be removed if ( hitem == END_OF_LIST(plist) ) { if ( EMPTY(&htarget_free_list) ) { Int3(); // get Allender -- no more free hotkey target items return; } nprintf(("network", "Hotkey: Adding %s\n", Ships[ctarget->instance].ship_name)); hitem = GET_FIRST( &htarget_free_list ); list_remove( &htarget_free_list, hitem ); list_append( plist, hitem ); hitem->objp = ctarget; hitem->how_added = how_to_add; } else { nprintf(("network", "Hotkey: Removing %s\n", Ships[ctarget->instance].ship_name)); list_remove( plist, hitem ); list_append( &htarget_free_list, hitem ); hitem->objp = NULL; // for safety } } // the following function clears the hotkey set given by parameter passed in void hud_target_hotkey_clear( int k ) { htarget_list *hitem, *plist, *temp; plist = &(Players[Player_num].keyed_targets[k]); hitem = GET_FIRST(plist); while ( hitem != END_OF_LIST(plist) ) { temp = GET_NEXT(hitem); list_remove( plist, hitem ); list_append( &htarget_free_list, hitem ); hitem->objp = NULL; hitem = temp; } if ( Players[Player_num].current_hotkey_set == k ) // clear this variable if we removed the bindings Players[Player_num].current_hotkey_set = -1; } // the next function sets the current selected set to be N. If there is just one ship in the selection // set, this ship will become the new target. If there is more than one ship in the selection set, // then the current_target will remain what it was. void hud_target_hotkey_select( int k ) { int visible_count = 0; htarget_list *hitem, *plist, *target, *next_target, *first_target; int target_objnum; plist = &(Players[Player_num].keyed_targets[k]); if ( EMPTY( plist ) ) // no items in list, then do nothing return; // a simple walk of the list to get the count for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ){ if (awacs_get_level(hitem->objp, Player_ship, 1) > 1) { visible_count++; } } // no visible ships in list if (visible_count == 0) { return; } // set the current target to be the "next" ship in the list. Scan the list to see if our // current target is in the set. If so, target the next ship in the list, otherwise target // the first // set first_target - first visible item in list // target - item in list that is the player's currently selected target // next_target - next visible item in list following target target_objnum = Player_ai->target_objnum; target = NULL; next_target = NULL; first_target = NULL; for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { if (awacs_get_level(hitem->objp, Player_ship, 1) > 1) { // get the first valid target if (first_target == NULL) { first_target = hitem; } // get the next target in the list following the player currently selected target if (target != NULL) { next_target = hitem; break; } } // mark the player currently selected target if ( OBJ_INDEX(hitem->objp) == target_objnum ) { target = hitem; } } // if current target is not in list, then target and next_target will be NULL // so we use the first found target if (target == NULL) { Assert(first_target != NULL); if (first_target != NULL) { target = first_target; next_target = first_target; } else { // this should not happen return; } } // update target if more than 1 is visible if (visible_count > 1) { // next already found (after current target in list) if (next_target != NULL) { target = next_target; } else { // next is before current target, so search from start of list for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { if (awacs_get_level(hitem->objp, Player_ship, 1) > 1) { target = hitem; break; } } } } Assert( target != END_OF_LIST(plist) ); if ( Player_obj != target->objp ){ set_target_objnum( Player_ai, OBJ_INDEX(target->objp) ); } Players[Player_num].current_hotkey_set = k; } // hud_init_targeting_colors() will initalize the shader and gradient objects used // on the HUD // color HUD_color_homing_indicator; void hud_make_shader(shader *sh, int r, int g, int b, float dimmer = 1000.0f) { float rf,gf,bf,cf; // The m matrix converts all colors to shades of green float tmp = 0.0015625f * i2fl(HUD_color_alpha+1.0f) / 16.0f; rf = tmp*r; gf = tmp*r; bf = tmp*r; cf = (i2fl(r) / dimmer)*(i2fl(HUD_color_alpha) / 15.0f); gr_create_shader( sh, rf, gf, bf, cf ); } void hud_init_targeting_colors() { gr_init_color( &HUD_color_homing_indicator, 0x7f, 0x7f, 0 ); // yellow hud_make_shader(&Training_msg_glass, 61, 61, 85, 500.0f); hud_init_brackets(); } void hud_keyed_targets_clear() { int i; // clear out the keyed target list for (i = 0; i < MAX_KEYED_TARGETS; i++ ) list_init( &(Players[Player_num].keyed_targets[i]) ); Players[Player_num].current_hotkey_set = -1; // place all of the hoykey target items back onto the free list list_init( &htarget_free_list ); for ( i = 0; i < MAX_HOTKEY_TARGET_ITEMS; i++ ) list_append( &htarget_free_list, &htarget_items[i] ); } // Init data used for the weapons display on the HUD void hud_weapons_init() { // int i, j, k, hud_index, gauge_index, hud_warned; Weapon_flash_info.is_bright = 0; for (int i = 0; i < MAX_WEAPON_FLASH_LINES; i++ ) { Weapon_flash_info.flash_duration[i] = 1; Weapon_flash_info.flash_next[i] = 1; } /*if ( !Weapon_gauges_loaded ) { hud_warned = 0; for (hud_index = 0; hud_index < NUM_HUD_SETTINGS; hud_index++) { for ( gauge_index = 0; gauge_index < NUM_WEAPON_GAUGES; gauge_index++ ) { Weapon_gauges[hud_index][gauge_index].first_frame = bm_load_animation(Weapon_gauge_fnames[hud_index][gr_screen.res][gauge_index], &Weapon_gauges[hud_index][gauge_index].num_frames); // file not found? if ( Weapon_gauges[hud_index][gauge_index].first_frame < 0 ) { // if this is the ballistic hud setting, load the conventional ani if (hud_index) { // give a single warning if (!hud_warned) { // commented because it gets annoying, and the warning really isn't needed anyway - Goober5000 //Warning(LOCATION, "Warning: Ballistic HUD graphics not found. Defaulting to original graphics.\n"); hud_warned = 1; } Weapon_gauges[hud_index][gauge_index].first_frame = bm_load_animation(Weapon_gauge_fnames[0][gr_screen.res][gauge_index], &Weapon_gauges[hud_index][gauge_index].num_frames); // and test again if ( Weapon_gauges[hud_index][gauge_index].first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n",Weapon_gauge_fnames[hud_index][gr_screen.res][gauge_index]); } } // otherwise, display the regular warning else { Warning(LOCATION,"Cannot load hud ani: %s\n",Weapon_gauge_fnames[hud_index][gr_screen.res][gauge_index]); } } } } // reset the old coordinates if hud_warned if (hud_warned) { // don't reset the first one, but reset all others for (hud_index = 1; hud_index < NUM_HUD_SETTINGS; hud_index++) { for (i = 0; i < GR_NUM_RESOLUTIONS; i++) { for (k = 0; k < 2; k++) { for (j = 0; j < 3; j++) { Weapon_gauge_primary_coords[hud_index][i][j][k] = Weapon_gauge_primary_coords[0][i][j][k]; } for (j = 0; j < 5; j++) { Weapon_gauge_secondary_coords[hud_index][i][j][k] = Weapon_gauge_secondary_coords[0][i][j][k]; } Weapon_title_coords[hud_index][i][k] = Weapon_title_coords[0][i][k]; } } } }*/ // Weapon_gauges_loaded = 1; //} } // init data used to play the homing "proximity warning" sound void hud_init_homing_beep() { Homing_beep.snd_handle = -1; Homing_beep.last_time_played = 0; Homing_beep.precalced_interp = (Homing_beep.max_cycle_dist-Homing_beep.min_cycle_dist) / (Homing_beep.max_cycle_time - Homing_beep.min_cycle_time ); } // hud_init_targeting() will set the current target to point to the dummy node // in the object used list // void hud_init_targeting() { Assert(Player_ai != NULL); int i; // decide whether to realign HUD for ballistic primaries ballistic_hud_index = 0; for (i = 0; i < Player_ship->weapons.num_primary_banks; i++) { if (Weapon_info[Player_ship->weapons.primary_bank_weapons[i]].wi_flags2 & WIF2_BALLISTIC) { ballistic_hud_index = 1; break; } } // make sure there is no current target set_target_objnum( Player_ai, -1 ); Player_ai->last_target = -1; Player_ai->last_subsys_target = NULL; Player_ai->last_dist = 0.0f; Player_ai->last_speed = 0.0f; hud_keyed_targets_clear(); hud_init_missile_lock(); hud_init_artillery(); // Init the lists that hold targets in reticle (to allow cycling of targets in reticle) hud_reticle_list_init(); hud_init_homing_beep(); // Load in the frames need for the lead indicator if (!Lead_indicator_gauge_loaded) { Lead_indicator_gauge.first_frame = bm_load_animation(Lead_fname[gr_screen.res], &Lead_indicator_gauge.num_frames); if ( Lead_indicator_gauge.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", Lead_fname[gr_screen.res]); } Lead_indicator_gauge_loaded = 1; } if (!Energy_bar_gauges_loaded) { Energy_bar_gauges.first_frame = bm_load_animation(Energy_fname[gr_screen.res], &Energy_bar_gauges.num_frames); if ( Energy_bar_gauges.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", Energy_fname[gr_screen.res]); } Energy_bar_gauges_loaded = 1; } /* if (!Toggle_gauge_loaded) { Toggle_gauge.first_frame = bm_load_animation(Toggle_fname[gr_screen.res], &Toggle_gauge.num_frames); if ( Toggle_gauge.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", Toggle_fname[gr_screen.res]); } Toggle_gauge_loaded = 1; }*/ /*if (!Cmeasure_gauge_loaded) { Cmeasure_gauge.first_frame = bm_load_animation(Cm_fname[gr_screen.res], &Cmeasure_gauge.num_frames); if ( Cmeasure_gauge.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", Cm_fname[gr_screen.res]); } Cmeasure_gauge_loaded = 1; }*/ hud_weapons_init(); Min_warning_missile_dist = 2.5f*Player_obj->radius; Max_warning_missile_dist = 1500.0f; Tl_hostile_reset_timestamp = timestamp(0); Tl_friendly_reset_timestamp = timestamp(0); Target_next_uninspected_object_timestamp = timestamp(0); Target_newest_ship_timestamp = timestamp(0); Target_next_turret_timestamp = timestamp(0); if(The_mission.flags & MISSION_FLAG_FULLNEB) { Toggle_text_alpha = 127; } else { Toggle_text_alpha = 160; } } // Target the next or previous subobject on the currently selected ship, based on next_flag. void hud_target_subobject_common(int next_flag) { if (Player_ai->target_objnum == -1) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "No target selected.", 322)); snd_play( &Snds[SND_TARGET_FAIL] ); return; } if (Objects[Player_ai->target_objnum].type != OBJ_SHIP) { snd_play( &Snds[SND_TARGET_FAIL]); return; } ship_subsys *start, *start2, *A; ship_subsys *subsys_to_target=NULL; ship *target_shipp; target_shipp = &Ships[Objects[Player_ai->target_objnum].instance]; if (!Player_ai->targeted_subsys) { start = GET_FIRST(&target_shipp->subsys_list); } else { start = Player_ai->targeted_subsys; } start2 = advance_subsys(start, next_flag); for ( A = start2; A != start; A = advance_subsys(A, next_flag) ) { if ( A == &target_shipp->subsys_list ) { continue; } // ignore turrets if ( A->system_info->type == SUBSYSTEM_TURRET ) { continue; } // ignore s-foil wings if (A->system_info->type == SUBSYSTEM_SFOIL) { continue; } // if the craft doesn't have a pod system installed then we // don't want the player to be able to select it if (A->system_info->type == SUBSYSTEM_POD) { if (target_shipp->pod_weapon == -1) continue; } subsys_to_target = A; break; } // end for if ( subsys_to_target == NULL ) { snd_play( &Snds[SND_TARGET_FAIL]); } else { set_targeted_subsys(Player_ai, subsys_to_target, Player_ai->target_objnum); target_shipp->last_targeted_subobject[Player_num] = Player_ai->targeted_subsys; } } object *advance_fb(object *objp, int next_flag) { if (next_flag) return GET_NEXT(objp); else return GET_LAST(objp); } // Target the previous subobject on the currently selected ship. // void hud_target_prev_subobject() { hud_target_subobject_common(0); } void hud_target_next_subobject() { hud_target_subobject_common(1); } // hud_target_next() will set the Players[Player_num].current_target to the next target in the object // used list whose team matches the team parameter. The player is NOT included in the target list. // // parameters: team => team of ship to target next. Default value is -1, if team doesn't matter. // void hud_target_common(int team, int next_flag) { object *A, *start, *start2; ship *shipp; int is_ship, target_found = FALSE; if (Player_ai->target_objnum == -1) start = &obj_used_list; else start = &Objects[Player_ai->target_objnum]; start2 = advance_fb(start, next_flag); for ( A = start2; A != start; A = advance_fb(A, next_flag) ) { is_ship=0; //if (Ships[A->instance].flags2 & SF2_NO_RADAR) // continue; if ( A == &obj_used_list ) { continue; } if (A == Player_obj || ( A->type != OBJ_SHIP && A->type != OBJ_WEAPON && A->type != OBJ_JUMP_NODE) ){ continue; } if(hud_target_invalid_awacs(A)){ continue; } if (A->type == OBJ_JUMP_NODE) { if (Jump_nodes[A->instance].iff != Ships[Player_obj->instance].iff) continue; } if ( A->type == OBJ_WEAPON ) { if (Weapon_info[Weapons[A->instance].weapon_info_index].subtype == WP_LASER) //if ( !(Weapon_info[Weapons[A->instance].weapon_info_index].wi_flags & WIF_BOMB) ){ continue; //} if (Weapons[A->instance].lssm_stage==3){ continue; } } if ( A->type == OBJ_SHIP ) { if ( Ships[A->instance].flags & TARGET_SHIP_IGNORE_FLAGS ){ continue; } // if ship is cloaked on decoy beam can't target if (Ships[A->instance].flags2 & SF2_NO_RADAR) { continue; } is_ship=1; } if ( vm_vec_same( &A->pos, &Eye_position ) ) { continue; } if ( is_ship ) { shipp = &Ships[A->instance]; // get a pointer to the ship information if ( !hud_team_matches_filter(team, shipp->team) ) { // if we're in multiplayer dogfight, ignore this #ifndef NO_NETWORK if(!((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_DOGFIGHT))) #endif { continue; } } if ( A == Player_obj || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ){ continue; } // if we've reached here, it is a valid next target if ( Player_ai->target_objnum != A-Objects ) { target_found = TRUE; set_target_objnum( Player_ai, OBJ_INDEX(A) ); // if ship is BIG|HUGE and last subsys is NULL, get turret hud_maybe_set_sorted_turret_subsys(shipp); hud_restore_subsystem_target(shipp); } } else { target_found = TRUE; set_target_objnum( Player_ai, OBJ_INDEX(A) ); } break; } if ( target_found == FALSE ) { snd_play( &Snds[SND_TARGET_FAIL] ); } } void hud_target_next(int team) { hud_target_common(team, 1); } void hud_target_prev(int team) { hud_target_common(team, 0); } // ------------------------------------------------------------------- // advance_missile_obj() // missile_obj *advance_missile_obj(missile_obj *mo, int next_flag) { if (next_flag){ return GET_NEXT(mo); } return GET_LAST(mo); } ship_obj *advance_ship(ship_obj *so, int next_flag) { if (next_flag){ return GET_NEXT(so); } return GET_LAST(so); } ship_obj *get_ship_obj_ptr_from_index(int index); // ------------------------------------------------------------------- // hud_target_missile() // // Target the closest locked missile that is locked on locked_obj // // input: source_obj => pointer to object that fired weapon // next_flag => 0 -> previous 1 -> next // // NOTE: this function is only allows targeting bombs void hud_target_missile(object *source_obj, int next_flag) { missile_obj *end, *start, *mo; object *A, *target_objp; ai_info *aip; weapon *wp; weapon_info *wip; int target_found = 0; if ( source_obj->type != OBJ_SHIP ) return; Assert( Ships[source_obj->instance].ai_index != -1 ); aip = &Ai_info[Ships[source_obj->instance].ai_index]; end = &Missile_obj_list; if (aip->target_objnum != -1) { target_objp = &Objects[aip->target_objnum]; if ( target_objp->type == OBJ_WEAPON && Weapon_info[Weapons[target_objp->instance].weapon_info_index].subtype == WP_MISSILE ) { // must be a missile end = missile_obj_return_address(Weapons[target_objp->instance].missile_list_index); } } start = advance_missile_obj(end, next_flag); for ( mo = start; mo != end; mo = advance_missile_obj(mo, next_flag) ) { if ( mo == &Missile_obj_list ){ continue; } Assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS); A = &Objects[mo->objnum]; Assert(A->type == OBJ_WEAPON); Assert((A->instance >= 0) && (A->instance < MAX_WEAPONS)); wp = &Weapons[A->instance]; wip = &Weapon_info[wp->weapon_info_index]; // only allow targeting of bombs // what you talkin' about willis? lets target any warhead if (Weapon_info[Weapons[A->instance].weapon_info_index].subtype == WP_LASER) { //if ( !(wip->wi_flags & WIF_BOMB) ) { continue; } if (wp->lssm_stage==3){ continue; } // only allow targeting of hostile bombs if ( (obj_team(A) == Player_ship->team) && (Player_ship->team != TEAM_TRAITOR) ) { continue; } if(hud_target_invalid_awacs(A)){ continue; } // if we've reached here, got a new target target_found = TRUE; set_target_objnum( aip, OBJ_INDEX(A) ); break; } // end for if ( !target_found ) { // if no bomb is found, search for bombers ship_obj *start, *so; extern ship_obj *Ship_objs; if ( (aip->target_objnum != -1) && (Objects[aip->target_objnum].type == OBJ_SHIP) && (Ship_info[Ships[Objects[aip->target_objnum].instance].ship_info_index].flags & SIF_BOMBER) ) { int index = Ships[Objects[aip->target_objnum].instance].ship_list_index; start = get_ship_obj_ptr_from_index(index); } else { start = GET_FIRST(&Ship_obj_list); } for (so=advance_ship(start, next_flag); so!=start; so=advance_ship(so, next_flag)) { object *ship_obj = &Objects[so->objnum]; // don't look at header if (so == &Ship_obj_list) { continue; } // only allow targeting of hostile bombs if ( (obj_team(ship_obj) == Player_ship->team) && (Player_ship->team != TEAM_TRAITOR) ) { continue; } if(hud_target_invalid_awacs(ship_obj)){ continue; } // check if ship type is bomber if ( !(Ship_info[Ships[ship_obj->instance].ship_info_index].flags & SIF_BOMBER) ) { continue; } // check if ignore if ( Ships[ship_obj->instance].flags & TARGET_SHIP_IGNORE_FLAGS ){ continue; } // found a good one target_found = TRUE; set_target_objnum( aip, OBJ_INDEX(ship_obj) ); break; } } if ( !target_found ) { snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); } } // Return !0 if shipp can be scanned, otherwise return 0 int hud_target_ship_can_be_scanned(ship *shipp) { ship_info *sip; sip = &Ship_info[shipp->ship_info_index]; // ignore cargo that has already been scanned if ( shipp->flags & SF_CARGO_REVEALED ) { return 0; } // allow ships with scannable flag set if ( shipp->flags & SF_SCANNABLE ) { return 1; } // ignore ships that don't carry cargo if ( !(sip->flags & (SIF_CARGO|SIF_FREIGHTER)) ) { return 0; } return 1; } // target the next/prev uninspected cargo container void hud_target_uninspected_cargo(int next_flag) { object *A, *start, *start2; ship *shipp; int target_found = 0; if (Player_ai->target_objnum == -1) { start = &obj_used_list; } else { start = &Objects[Player_ai->target_objnum]; } start2 = advance_fb(start, next_flag); for ( A = start2; A != start; A = advance_fb(A, next_flag) ) { if ( A == &obj_used_list ) { continue; } if (A == Player_obj || (A->type != OBJ_SHIP) ) { continue; } shipp = &Ships[A->instance]; // get a pointer to the ship information if ( shipp->flags & TARGET_SHIP_IGNORE_FLAGS ) { continue; } // ignore all non-cargo carrying craft if ( !hud_target_ship_can_be_scanned(shipp) ) { continue; } if(hud_target_invalid_awacs(A)){ continue; } // if we've reached here, it is a valid next target if ( Player_ai->target_objnum != OBJ_INDEX(A) ) { target_found = TRUE; set_target_objnum( Player_ai, OBJ_INDEX(A) ); } } if ( target_found == FALSE ) { snd_play( &Snds[SND_TARGET_FAIL]); } } // target the newest ship in the area void hud_target_newest_ship() { object *A, *player_target_objp; object *newest_obj=NULL; ship *shipp; ship_obj *so; uint current_target_arrived_time = 0xffffffff, newest_time = 0; if ( Player_ai->target_objnum >= 0 ) { player_target_objp = &Objects[Player_ai->target_objnum]; if ( player_target_objp->type == OBJ_SHIP ) { current_target_arrived_time = Ships[player_target_objp->instance].create_time; } } else { player_target_objp = NULL; } // If no target is selected, then simply target the closest uninspected cargo if ( Player_ai->target_objnum == -1 || timestamp_elapsed(Target_newest_ship_timestamp) ) { current_target_arrived_time = 0xffffffff; } Target_newest_ship_timestamp = timestamp(TL_RESET); for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information if ( (A == Player_obj) || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ) continue; // no target if cloaked or decoy if ( Ships[A->instance].flags2 & SF2_NO_RADAR) { continue; } // ignore navbuoys if ( Ship_info[shipp->ship_info_index].flags & SIF_NAVBUOY ) { continue; } if ( A == player_target_objp ) { continue; } if(hud_target_invalid_awacs(A)){ continue; } if ( (shipp->create_time >= newest_time) && (shipp->create_time <= current_target_arrived_time) ) { newest_time = shipp->create_time; newest_obj = A; } } if (newest_obj) { set_target_objnum( Player_ai, OBJ_INDEX(newest_obj) ); // if BIG|HUGE and no selected subsystem, get sorted turret hud_maybe_set_sorted_turret_subsys(&Ships[newest_obj->instance]); hud_restore_subsystem_target(&Ships[newest_obj->instance]); } else { snd_play( &Snds[SND_TARGET_FAIL]); } } #define TYPE_NONE 0 #define TYPE_FACING_BEAM 1 #define TYPE_FACING_FLAK 2 #define TYPE_FACING_MISSILE 3 #define TYPE_FACING_LASER 4 #define TYPE_NONFACING_BEAM 5 #define TYPE_NONFACING_FLAK 6 #define TYPE_NONFACING_MISSILE 7 #define TYPE_NONFACING_LASER 8 #define TYPE_NONFACING_INC 4 typedef struct eval_next_turret { ship_subsys *ss; int type; float dist; } eval_next_turret; int sort_turret_func(const void *e1, const void *e2) { eval_next_turret *p1 = (eval_next_turret*)e1; eval_next_turret *p2 = (eval_next_turret*)e2; Assert(p1->type != TYPE_NONE); Assert(p2->type != TYPE_NONE); if (p1->type != p2->type) { return (p1->type - p2->type); } else { float delta_dist = p1->dist - p2->dist; if (delta_dist < 0) { return -1; } else if (delta_dist > 0) { return 1; } else { return 0; } } } // target the next/prev live turret on the current target // auto_advance from hud_update_closest_turret void hud_target_live_turret(int next_flag, int auto_advance, int only_player_target) { ship_subsys *A; ship_subsys *live_turret=NULL; ship *target_shipp; object *objp; eval_next_turret ent[MAX_MODEL_SUBSYSTEMS]; int num_live_turrets = 0; // make sure we're targeting a ship if (Player_ai->target_objnum == -1 && !auto_advance) { snd_play(&Snds[SND_TARGET_FAIL]); return; } // only targeting subsystems on ship if ((Objects[Player_ai->target_objnum].type != OBJ_SHIP) && (!auto_advance)) { snd_play( &Snds[SND_TARGET_FAIL]); return; } // set some pointers objp = &Objects[Player_ai->target_objnum]; target_shipp = &Ships[objp->instance]; // set timestamp int timestamp_val = 0; if (!auto_advance) { timestamp_val = Target_next_turret_timestamp; Target_next_turret_timestamp = timestamp(TURRET_RESET); } // If no target is selected, then simply target the closest (or facing) turret int last_subsys_turret = FALSE; if (Player_ai->targeted_subsys != NULL) { if (Player_ai->targeted_subsys->system_info->type == SUBSYSTEM_TURRET) { if (Player_ai->targeted_subsys->system_info->turret_weapon_type >= 0) { last_subsys_turret = TRUE; } } } // do we want the closest turret (or the one our ship is pointing at) int get_closest_turret = (auto_advance || !last_subsys_turret || timestamp_elapsed(timestamp_val)); // initialize eval struct memset(ent,0, sizeof(ent)); int use_straigh_ahead_turret = FALSE; // go through list of turrets for (A=GET_FIRST(&target_shipp->subsys_list); A!=END_OF_LIST(&target_shipp->subsys_list); A=GET_NEXT(A)) { // get a turret if (A->system_info->type == SUBSYSTEM_TURRET) { // check turret has hit points and has a weapon if ( (A->current_hits > 0) && (A->system_info->turret_weapon_type >= 0) ) { if ( !only_player_target || (A->turret_enemy_objnum == OBJ_INDEX(Player_obj)) ) { vector gsubpos, vec_to_subsys; float distance, dot; // get world pos of subsystem and its distance get_subsystem_world_pos(objp, A, &gsubpos); distance = vm_vec_normalized_dir(&vec_to_subsys, &gsubpos, &View_position); // check if facing and in view int facing = ship_subsystem_in_sight(objp, A, &View_position, &gsubpos, 0); if (!auto_advance && get_closest_turret && !only_player_target) { // if within 3 degrees and not previous subsys, use subsys in front dot = vm_vec_dotprod(&vec_to_subsys, &Player_obj->orient.vec.fvec); if ((dot > 0.9986) && facing) { use_straigh_ahead_turret = TRUE; break; } } // set weapon_type to allow sort of ent on type if (Weapon_info[A->system_info->turret_weapon_type].wi_flags & WIF_BEAM) { ent[num_live_turrets].type = TYPE_FACING_BEAM; } else if (Weapon_info[A->system_info->turret_weapon_type].wi_flags & WIF_FLAK) { ent[num_live_turrets].type = TYPE_FACING_FLAK; } else { if (Weapon_info[A->system_info->turret_weapon_type].subtype == WP_MISSILE) { ent[num_live_turrets].type = TYPE_FACING_MISSILE; } else if (Weapon_info[A->system_info->turret_weapon_type].subtype == WP_LASER) { ent[num_live_turrets].type = TYPE_FACING_LASER; } else { Int3(); ent[num_live_turrets].type = TYPE_FACING_LASER; } } // fill out ent struct ent[num_live_turrets].ss = A; ent[num_live_turrets].dist = distance; if (!facing) { ent[num_live_turrets].type += TYPE_NONFACING_INC; } num_live_turrets++; } } } } // sort the list if we're not using turret straigh ahead of us if (!use_straigh_ahead_turret) { qsort(ent, num_live_turrets, sizeof(eval_next_turret), sort_turret_func); } if (use_straigh_ahead_turret) { // use the straight ahead turret live_turret = A; } else { // check if we have a currently targeted turret and find its position after the sort int i, start_index, next_index; if (get_closest_turret) { start_index = 0; } else { start_index = -1; for (i=0; i<num_live_turrets; i++) { if (ent[i].ss == Player_ai->targeted_subsys) { start_index = i; break; } } // check that we started with a turret if (start_index == -1) { start_index = 0; } } // set next live turret if (num_live_turrets == 0) { // no live turrets live_turret = NULL; } else if (num_live_turrets == 1 || get_closest_turret) { // only 1 live turret, so set it live_turret = ent[0].ss; } else { if (next_flag) { // advance to next closest turret next_index = start_index + 1; if (next_index == num_live_turrets) { next_index = 0; } } else { // go to next farther turret next_index = start_index - 1; if (next_index == -1) { next_index = num_live_turrets - 1; } } // set the next turret to be targeted based on next_index live_turret = ent[next_index].ss; } //if (live_turret) { // debug info // mprintf(("name %s, index: %d, type: %d\n", live_turret->system_info->subobj_name, next_index, ent[next_index].type)); //} } if ( live_turret != NULL ) { set_targeted_subsys(Player_ai, live_turret, Player_ai->target_objnum); target_shipp->last_targeted_subobject[Player_num] = Player_ai->targeted_subsys; } else { if (!auto_advance) { snd_play( &Snds[SND_TARGET_FAIL]); } } } // ------------------------------------------------------------------- // hud_target_closest_locked_missile() // // Target the closest locked missile that is locked on locked_obj // // input: locked_obj => pointer to object that you want to find // closest missile to // void hud_target_closest_locked_missile(object *locked_obj) { object *A, *nearest_obj=NULL; weapon *wp; weapon_info *wip; float nearest_dist, dist; int target_found = FALSE; missile_obj *mo; nearest_dist = 10000.0f; for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) { Assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS); A = &Objects[mo->objnum]; if (A->type != OBJ_WEAPON){ continue; } Assert((A->instance >= 0) && (A->instance < MAX_WEAPONS)); wp = &Weapons[A->instance]; wip = &Weapon_info[wp->weapon_info_index]; if ( wip->subtype != WP_MISSILE ){ continue; } if ( !(wip->wi_flags & (WIF_HOMING_ASPECT|WIF_HOMING_HEAT) ) ){ continue; } if (wp->lssm_stage==3){ continue; } if(hud_target_invalid_awacs(A)){ continue; } if (wp->homing_object == locked_obj) { dist = vm_vec_dist_quick(&A->pos, &locked_obj->pos); // Find distance! if (dist < nearest_dist) { nearest_obj = A; nearest_dist = dist; } } } // end for if (nearest_dist < 10000.0f) { Assert(nearest_obj); set_target_objnum( Player_ai, OBJ_INDEX(nearest_obj) ); target_found = TRUE; } if ( !target_found ){ snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); } } // Return bitmask of all opponents. int opposing_team_mask(int team_mask) { return ((TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_HOSTILE) & ~team_mask) | TEAM_TRAITOR; } // select a new target, by auto-targeting void hud_target_auto_target_next() { if ( Framecount < 2 ) { return; } // No auto-targeting after dead. if (Game_mode & (GM_DEAD | GM_DEAD_BLEW_UP)) return; int valid_team; valid_team = opposing_team_mask(Player_ship->team); // try target closest ship attacking player hud_target_closest(valid_team, OBJ_INDEX(Player_obj), FALSE, TRUE ); // if none, try targeting closest hostile fighter/bomber if ( Player_ai->target_objnum == -1 ){ hud_target_closest(valid_team, -1, FALSE, TRUE); } // No fighter/bombers exists, so go ahead an target the closest hostile if ( Player_ai->target_objnum == -1 ){ hud_target_closest(valid_team, -1, FALSE); } // um, ok. Try targeting asteroids that are on a collision course for an escort ship if ( Player_ai->target_objnum == -1 ) { asteroid_target_closest_danger(); } } // Given that object 'targeter' is targetting object 'targetee', // how far are they? This uses the point closest to the targeter // object on the targetee's bounding box. So if targeter is inside // targtee's bounding box, the distance is 0. float hud_find_target_distance( object *targetee, object *targeter ) { vector tmp_pnt; int model_num = -1; // Which model is it? switch( targetee->type ) { case OBJ_SHIP: model_num = Ships[targetee->instance].modelnum; break; case OBJ_DEBRIS: // model_num = Debris[targetee->instance].model_num; break; case OBJ_WEAPON: // Don't find model_num since circles would work better //model_num = Weapon_info[Weapons[targetee->instance].weapon_info_index].model_num; break; case OBJ_ASTEROID: // Don't find model_num since circles would work better //model_num = Asteroid_info[Asteroids[targetee->instance].type].model_num; break; case OBJ_JUMP_NODE: // Don't find model_num since circles would work better //model_num = Jump_nodes[targetee->instance].modelnum; break; } float dist = 0.0f; // New way, that uses bounding box. if ( model_num > -1 ) { dist = model_find_closest_point( &tmp_pnt, model_num, -1, &targetee->orient, &targetee->pos, &targeter->pos ); } else { // Old way, that uses radius. dist = vm_vec_dist_quick(&targetee->pos, &targeter->pos) - targetee->radius; if ( dist < 0.0f ) { dist = 0.0f; } } return dist; } // hud_target_closest() will set the Players[Player_num].current_target to the closest // ship to the player that matches the team passed as a paramater // // The current algorithm is to simply iterate through the objects and calculate the // magnitude of the vector that connects the player to the target. The smallest magnitude // is tracked, and then used to locate the closest hostile ship. Note only the square of the // magnitude is required, since we are only comparing magnitudes // // parameters: team => team of closest ship that should be targeted. // Default value is -1, if team doesn't matter. // // attacked_objnum => object number of ship that is being attacked // play_fail_snd => boolean, whether to play SND_TARGET_FAIL // (needed, since function called repeatedly when auto-targeting is // enabled, and we don't want a string of fail sounds playing). // This is a default parameter with a value of TRUE // filter => OPTIONAL parameter (default value 0): when set to TRUE, only // fighters and bombers are considered for new targets // // returns: TRUE ==> a target was acquired // FALSE ==> no target was acquired // // eval target as closest struct typedef struct esct { int team; int filter; ship* shipp; float min_distance; int check_nearest_turret; int attacked_objnum; int check_all_turrets; int turret_attacking_target; // check that turret is actually attacking the attacked_objnum } esct; // evaluate a ship (and maybe turrets) as a potential target // check if shipp (or its turrets) is attacking attacked_objnum // special case for player trying to select target (don't check if turrets are aimed at player) void evaluate_ship_as_closest_target(esct *esct) { int targeting_player, turret_is_attacking; ship_subsys *ss; float new_distance; // initialize esct->min_distance = FLT_MAX; esct->check_nearest_turret = FALSE; turret_is_attacking = FALSE; object *objp = &Objects[esct->shipp->objnum]; Assert(objp->type == OBJ_SHIP); if (objp->type != OBJ_SHIP) { return; } // player being targeted, so we will want closest distance from player targeting_player = (esct->attacked_objnum == OBJ_INDEX(Player_obj)); // filter on team, except in multiplayer if ( !hud_team_matches_filter(esct->team, esct->shipp->team) ) { // if we're in multiplayer dogfight, ignore this #ifndef NO_NETWORK if(!((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_DOGFIGHT))) #endif { return; } } // check if player or ignore ship if ( (esct->shipp->objnum == OBJ_INDEX(Player_obj)) || (esct->shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ) { return; } // can't target if cloaked or using decoy if (esct->shipp->flags2 & SF2_NO_RADAR) return; // bail if harmless if ( Ship_info[esct->shipp->ship_info_index].flags & SIF_HARMLESS ) { return; } // only look at targets that are AWACS valid if (hud_target_invalid_awacs(&Objects[esct->shipp->objnum])) { return; } // If filter is set, only target fighters and bombers if ( esct->filter ) { if ( !(Ship_info[esct->shipp->ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) ) { return; } } // find closest turret to player if BIG or HUGE ship if (Ship_info[esct->shipp->ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) { for (ss=GET_FIRST(&esct->shipp->subsys_list); ss!=END_OF_LIST(&esct->shipp->subsys_list); ss=GET_NEXT(ss)) { if ( (ss->system_info->type == SUBSYSTEM_TURRET) && (ss->current_hits > 0) ) { if (esct->check_all_turrets || (ss->turret_enemy_objnum == esct->attacked_objnum)) { turret_is_attacking = 1; esct->check_nearest_turret = TRUE; if ( !esct->turret_attacking_target || (esct->turret_attacking_target && (ss->turret_enemy_objnum == esct->attacked_objnum)) ) { vector gsubpos; // get world pos of subsystem vm_vec_unrotate(&gsubpos, &ss->system_info->pnt, &objp->orient); vm_vec_add2(&gsubpos, &objp->pos); new_distance = vm_vec_dist_quick(&gsubpos, &Player_obj->pos); /* // GET TURRET TYPE, FAVOR BEAM, FLAK, OTHER int turret_type = ss->system_info->turret_weapon_type; if (Weapon_info[turret_type].wi_flags & WIF_BEAM) { new_distance *= 0.3f; } else if (Weapon_info[turret_type].wi_flags & WIF_FLAK) { new_distance *= 0.6f; } */ // get the closest distance if (new_distance <= esct->min_distance) { esct->min_distance = new_distance; } } } } } } // If no turret is attacking, check if objp is actually targetting attacked_objnum // dont bail if targeting is for player if ( !targeting_player && !turret_is_attacking ) { ai_info *aip = &Ai_info[esct->shipp->ai_index]; if (aip->target_objnum != esct->attacked_objnum) { return; } if ( (Game_mode & GM_NORMAL) && ( aip->mode != AIM_CHASE ) && (aip->mode != AIM_STRAFE) && (aip->mode != AIM_EVADE) && (aip->mode != AIM_EVADE_WEAPON) && (aip->mode != AIM_AVOID)) { return; } } // consider the ship alone if there are no attacking turrets if ( !turret_is_attacking ) { //new_distance = hud_find_target_distance(objp, Player_obj); new_distance = vm_vec_dist_quick(&objp->pos, &Player_obj->pos); if (new_distance <= esct->min_distance) { esct->min_distance = new_distance; esct->check_nearest_turret = FALSE; } } } int hud_target_closest(int team, int attacked_objnum, int play_fail_snd, int filter, int get_closest_turret_attacking_player) { object *A; object *nearest_obj = &obj_used_list; ship *shipp; ship_obj *so; int check_nearest_turret = FALSE; // evaluate ship closest target struct esct esct; float min_distance = FLT_MAX; int target_found = FALSE; int player_obj_index = OBJ_INDEX(Player_obj); ship_subsys *ss; //*nearest_turret_subsys = NULL, *ss; if ( (attacked_objnum >= 0) && (attacked_objnum != player_obj_index) ) { // bail if player does not have target if ( Player_ai->target_objnum == -1) { if ( Objects[attacked_objnum].type != OBJ_SHIP ) { goto Target_closest_done; } // bail if ship is to be ignored if (!(Ships[Objects[attacked_objnum].instance].flags & TARGET_SHIP_IGNORE_FLAGS)) { goto Target_closest_done; } } } if (attacked_objnum == -1) { attacked_objnum = player_obj_index; } // check all turrets if for player. esct.check_all_turrets = (attacked_objnum == player_obj_index); esct.filter = filter; esct.team = team; esct.attacked_objnum = attacked_objnum; esct.turret_attacking_target = get_closest_turret_attacking_player; for ( so=GET_FIRST(&Ship_obj_list); so!=END_OF_LIST(&Ship_obj_list); so=GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information // fill in rest of esct esct.shipp = shipp; // check each shipp on list and update nearest obj and subsys evaluate_ship_as_closest_target(&esct); if (esct.min_distance < min_distance) { target_found = TRUE; min_distance = esct.min_distance; nearest_obj = A; check_nearest_turret = esct.check_nearest_turret; } } Target_closest_done: // maybe ignore target if too far away // DKA 9/8/99 Remove distance check /* if (target_found) { // get distance to nearest attacker float dist = vm_vec_dist_quick(&Objects[attacked_objnum].pos, &nearest_obj->pos); // no distance limit for player obj if ((attacked_objnum != player_obj_index) && (dist > MIN_DISTANCE_TO_CONSIDER_THREAT)) { target_found = FALSE; } } */ if (target_found) { set_target_objnum(Player_ai, OBJ_INDEX(nearest_obj)); if ( check_nearest_turret ) { // if former subobject was not a turret do, not change subsystem ss = Ships[nearest_obj->instance].last_targeted_subobject[Player_num]; if (ss == NULL || get_closest_turret_attacking_player) { // set_targeted_subsys(Player_ai, nearest_turret_subsys, OBJ_INDEX(nearest_obj)); // update nearest turret with later func hud_target_live_turret(1, 1, get_closest_turret_attacking_player); Ships[nearest_obj->instance].last_targeted_subobject[Player_num] = Player_ai->targeted_subsys; } } else { hud_restore_subsystem_target(&Ships[nearest_obj->instance]); } } else { // no target found, maybe play fail sound if (play_fail_snd == TRUE) { snd_play(&Snds[SND_TARGET_FAIL]); } } return target_found; } // auto update closest turret to attack on big or huge ships void hud_update_closest_turret() { hud_target_live_turret(1, 1); /* float nearest_distance, new_distance; ship_subsys *ss, *closest_subsys; ship *shipp; object *objp; nearest_distance = FLT_MAX; objp = &Objects[Player_ai->target_objnum]; shipp = &Ships[objp->instance]; closest_subsys = NULL; Assert(Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)); for (ss=GET_FIRST(&shipp->subsys_list); ss!=END_OF_LIST(&shipp->subsys_list); ss=GET_NEXT(ss)) { if ( (ss->system_info->type == SUBSYSTEM_TURRET) && (ss->current_hits > 0) ) { // make sure turret is not "unused" if (ss->system_info->turret_weapon_type >= 0) { vector gsubpos; // get world pos of subsystem vm_vec_unrotate(&gsubpos, &ss->system_info->pnt, &objp->orient); vm_vec_add2(&gsubpos, &objp->pos); new_distance = vm_vec_dist_quick(&gsubpos, &Player_obj->pos); // GET TURRET TYPE, FAVOR BEAM, FLAK, OTHER int turret_type = ss->system_info->turret_weapon_type; if (Weapon_info[turret_type].wi_flags & WIF_BEAM) { new_distance *= 0.3f; } else if (Weapon_info[turret_type].wi_flags & WIF_FLAK) { new_distance *= 0.6f; } // check if facing and in view int facing = ship_subsystem_in_sight(objp, ss, &View_position, &gsubpos, 0); if (facing) { new_distance *= 0.5f; } // get the closest distance if (new_distance <= nearest_distance) { nearest_distance = new_distance; closest_subsys = ss; } } } } // check if new subsys to target if (Player_ai->targeted_subsys != NULL) { set_targeted_subsys(Player_ai, closest_subsys, Player_ai->target_objnum); shipp->last_targeted_subobject[Player_num] = Player_ai->targeted_subsys; } */ } // -------------------------------------------------------------------- // hud_target_targets_target() // // Target your target's target. Your target is specified by objnum passed // as a parameter. // void hud_target_targets_target() { object *objp; int tt_objnum; if ( Player_ai->target_objnum < 0 || Player_ai->target_objnum >= MAX_OBJECTS ) { goto ttt_fail; } objp = &Objects[Player_ai->target_objnum]; if ( objp->type != OBJ_SHIP ) { goto ttt_fail; } if (hud_target_invalid_awacs(objp)) { goto ttt_fail; } if ( Ships[objp->instance].flags & TARGET_SHIP_IGNORE_FLAGS ) { goto ttt_fail; } // no target if cloaked or decoy if ( Ships[objp->instance].flags2 & SF2_NO_RADAR) { goto ttt_fail; } tt_objnum = Ai_info[Ships[objp->instance].ai_index].target_objnum; if ( tt_objnum < 0 || tt_objnum >= MAX_OBJECTS ) { goto ttt_fail; } if ( tt_objnum == OBJ_INDEX(Player_obj) ) { goto ttt_fail; } // if we've reached here, found player target's target set_target_objnum( Player_ai, tt_objnum ); if (Objects[tt_objnum].type == OBJ_SHIP) { hud_maybe_set_sorted_turret_subsys(&Ships[Objects[tt_objnum].instance]); } hud_restore_subsystem_target(&Ships[Objects[tt_objnum].instance]); return; ttt_fail: snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); } // Return !0 if target_objp is a valid object type for targeting in reticle, otherwise return 0 int object_targetable_in_reticle(object *target_objp) { int obj_type; if (target_objp == Player_obj ) { return 0; } obj_type = target_objp->type; if ( (obj_type == OBJ_SHIP) || (obj_type == OBJ_DEBRIS) || (obj_type == OBJ_WEAPON) || (obj_type == OBJ_ASTEROID) || (obj_type == OBJ_JUMP_NODE) ) { return 1; } return 0; } // hud_target_in_reticle_new() will target the object that is closest to the player, and who is // intersected by a ray passed from the center of the reticle out along the forward vector of the // player. // // targeting of objects of type OBJ_SHIP and OBJ_DEBRIS are supported // // Method: A ray is cast from the center of the reticle, and we keep track of any eligible object // the ray intersects. We take the ship closest to us that intersects an object. // // Since this method may work poorly with objects that are far away, hud_target_in_reticle_old() // is called if no intersections are found. // // #define TARGET_IN_RETICLE_DISTANCE 10000.0f void hud_target_in_reticle_new() { vector terminus; object *A; mc_info mc; float dist; hud_reticle_clear_list(&Reticle_cur_list); Reticle_save_timestamp = timestamp(RESET_TARGET_IN_RETICLE); // Get 3d vector through center of reticle vm_vec_scale_add(&terminus, &Eye_position, &Player_obj->orient.vec.fvec, TARGET_IN_RETICLE_DISTANCE); mc.model_num = 0; for ( A = GET_FIRST(&obj_used_list); A !=END_OF_LIST(&obj_used_list); A = GET_NEXT(A) ) { if ( !object_targetable_in_reticle(A) ) { continue; } if ( A->type == OBJ_WEAPON ) { if (Weapon_info[Weapons[A->instance].weapon_info_index].subtype == WP_LASER) //if ( !(Weapon_info[Weapons[A->instance].weapon_info_index].wi_flags & WIF_BOMB) ){ continue; //} if (Weapons[A->instance].lssm_stage==3){ continue; } } if ( A->type == OBJ_SHIP ) { if ( Ships[A->instance].flags & TARGET_SHIP_IGNORE_FLAGS ){ continue; } // no target if cloaked or decoy if ( Ships[A->instance].flags2 & SF2_NO_RADAR) { continue; } } if(hud_target_invalid_awacs(A)){ continue; } switch (A->type) { case OBJ_SHIP: mc.model_num = Ships[A->instance].modelnum; break; case OBJ_DEBRIS: mc.model_num = Debris[A->instance].model_num; break; case OBJ_WEAPON: mc.model_num = Weapon_info[Weapons[A->instance].weapon_info_index].model_num; break; case OBJ_ASTEROID: { #ifndef FS2_DEMO int subtype = 0; subtype = Asteroids[A->instance].asteroid_subtype; mc.model_num = Asteroid_info[Asteroids[A->instance].type].model_num[subtype]; #endif } break; case OBJ_JUMP_NODE: mc.model_num = Jump_nodes[A->instance].modelnum; break; default: Int3(); // Illegal object type. } model_clear_instance( mc.model_num ); mc.orient = &A->orient; // The object's orient mc.pos = &A->pos; // The object's position mc.p0 = &Eye_position; // Point 1 of ray to check mc.p1 = &terminus; // Point 2 of ray to check mc.flags = MC_CHECK_MODEL; // | MC_ONLY_BOUND_BOX; // check the model, but only its bounding box model_collide(&mc); if ( mc.num_hits ) { dist = vm_vec_dist_squared(&mc.hit_point_world, &Eye_position); hud_reticle_list_update(A, dist, 0); } } // end for (go to next object) hud_target_in_reticle_old(); // try the old method (works well with ships far away) } // hud_target_in_reticle_old() will target the object that is closest to the reticle center and inside // the reticle // // targeting of objects of type OBJ_SHIP and OBJ_DEBRIS are supported // // // Method: take the dot product of the foward vector and the vector to target. Take // the one that is closest to 1 and at least MIN_DOT_FOR_TARGET // // IMPORTANT: The MIN_DOT_FOR_TARGET value was arrived at by trial and error and // is only valid for the HUD reticle in use at that time. #define MIN_DOT_FOR_TARGET 0.9726// fov for targeting in reticle void hud_target_in_reticle_old() { object *A, *target_obj; float dist, dot; vector vec_to_target; for ( A = GET_FIRST(&obj_used_list); A !=END_OF_LIST(&obj_used_list); A = GET_NEXT(A) ) { if ( !object_targetable_in_reticle(A) ) { continue; } if ( A->type == OBJ_WEAPON ) { if (Weapon_info[Weapons[A->instance].weapon_info_index].subtype == WP_LASER) //if ( !(Weapon_info[Weapons[A->instance].weapon_info_index].wi_flags & WIF_BOMB) ){ continue; //} if (Weapons[A->instance].lssm_stage==3){ continue; } } if ( A->type == OBJ_SHIP ) { if ( Ships[A->instance].flags & TARGET_SHIP_IGNORE_FLAGS ){ continue; } // no target if cloaked or decoy if ( Ships[A->instance].flags2 & SF2_NO_RADAR) { continue; } } if(hud_target_invalid_awacs(A)){ continue; } if ( vm_vec_same( &A->pos, &Eye_position ) ) { continue; } dist = vm_vec_normalized_dir(&vec_to_target, &A->pos, &Eye_position); dot = vm_vec_dot(&Player_obj->orient.vec.fvec, &vec_to_target); if ( dot > MIN_DOT_FOR_TARGET ) { hud_reticle_list_update(A, dot, 1); } } target_obj = hud_reticle_pick_target(); if ( target_obj != NULL ) { set_target_objnum( Player_ai, OBJ_INDEX(target_obj) ); if ( target_obj->type == OBJ_SHIP ) { // if BIG|HUGE, maybe set subsys to turret hud_maybe_set_sorted_turret_subsys(&Ships[target_obj->instance]); hud_restore_subsystem_target(&Ships[target_obj->instance]); } } else { snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); } } // hud_target_subsystem_in_reticle() will target the subsystem that is within the reticle and // is closest to the reticle center. The current target is the only object that is searched for // subsystems // // Method: take the dot product of the foward vector and the vector to target. Take // the one that is closest to 1 and at least MIN_DOT_FOR_TARGET // // IMPORTANT: The MIN_DOT_FOR_TARGET value was arrived at by trial and error and // is only valid for the HUD reticle in use at that time. // void hud_target_subsystem_in_reticle() { object* targetp; ship_subsys *subsys; ship_subsys *nearest_subsys = NULL; vector subobj_pos; float dist, dot, best_dot; vector vec_to_target; best_dot = -1.0f; if ( Player_ai->target_objnum == -1){ hud_target_in_reticle_old(); } if ( Player_ai->target_objnum == -1) { snd_play( &Snds[SND_TARGET_FAIL]); return; } targetp = &Objects[Player_ai->target_objnum]; if ( targetp->type != OBJ_SHIP ){ // only targeting subsystems on ship return; } int shipnum = targetp->instance; for (subsys = GET_FIRST(&Ships[shipnum].subsys_list); subsys != END_OF_LIST(&Ships[shipnum].subsys_list) ; subsys = GET_NEXT( subsys ) ) { get_subsystem_world_pos(targetp, subsys, &subobj_pos); dist = vm_vec_normalized_dir(&vec_to_target, &subobj_pos, &Eye_position); dot = vm_vec_dot(&Player_obj->orient.vec.fvec, &vec_to_target); if ( dot > best_dot ) { best_dot = dot; if ( best_dot > MIN_DOT_FOR_TARGET ) nearest_subsys = subsys; } Assert(best_dot <= 1.0f); } // end for if ( nearest_subsys != NULL ) { set_targeted_subsys(Player_ai, nearest_subsys, Player_ai->target_objnum); HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "Targeting subsystem %s.", 323), Player_ai->targeted_subsys->system_info->name); Ships[shipnum].last_targeted_subobject[Player_num] = Player_ai->targeted_subsys; } else { snd_play( &Snds[SND_TARGET_FAIL]); } } #define T_LENGTH 8 #define T_OFFSET_FROM_CIRCLE -13 #define T_BASE_LENGTH 4 // On entry: // color set void hud_render_orientation_tee(object *from_objp, object *to_objp, matrix *from_orientp) { float dot_product; vector target_to_obj; float x1,y1,x2,y2,x3,y3,x4,y4; vm_vec_sub(&target_to_obj, &from_objp->pos, &to_objp->pos); vm_vec_normalize(&target_to_obj); // calculate the dot product between the target_to_player vector and the targets forward vector // // 0 - vectors are perpendicular // 1 - vectors are collinear and in the same direction (target is facing player) // -1 - vectors are collinear and in the opposite direction (target is facing away from player) dot_product = vm_vec_dotprod(&from_orientp->vec.fvec, &target_to_obj); if (vm_vec_dotprod(&from_orientp->vec.rvec, &target_to_obj) >= 0) { if (dot_product >= 0){ dot_product = -PI/2*dot_product + PI; } else { dot_product = -PI/2*dot_product - PI; } } else { dot_product *= PI/2; //(range is now -PI/2 => PI/2) } y1 = (float)sin(dot_product) * (Outer_circle_radius[gr_screen.res] - T_OFFSET_FROM_CIRCLE); x1 = (float)cos(dot_product) * (Outer_circle_radius[gr_screen.res] - T_OFFSET_FROM_CIRCLE); y1 += Hud_reticle_center[gr_screen.res][1]; x1 += Hud_reticle_center[gr_screen.res][0]; x1 += HUD_offset_x; y1 += HUD_offset_y; y2 = (float)sin(dot_product) * (Outer_circle_radius[gr_screen.res] - T_OFFSET_FROM_CIRCLE - T_LENGTH); x2 = (float)cos(dot_product) * (Outer_circle_radius[gr_screen.res] - T_OFFSET_FROM_CIRCLE - T_LENGTH); y2 += Hud_reticle_center[gr_screen.res][1]; x2 += Hud_reticle_center[gr_screen.res][0]; x2 += HUD_offset_x; y2 += HUD_offset_y; x3 = x1 - T_BASE_LENGTH * (float)sin(dot_product); y3 = y1 + T_BASE_LENGTH * (float)cos(dot_product); x4 = x1 + T_BASE_LENGTH * (float)sin(dot_product); y4 = y1 - T_BASE_LENGTH * (float)cos(dot_product); // HACK! Should be antialiased! gr_line(fl2i(x3),fl2i(y3),fl2i(x4),fl2i(y4)); // bottom of T gr_line(fl2i(x1),fl2i(y1),fl2i(x2),fl2i(y2)); // part of T pointing towards center } void hud_tri(float x1,float y1,float x2,float y2,float x3,float y3) { int i; // Make the triangle always be the correct handiness so // the tmapper won't think its back-facing and throw it out. float det = (y2-y1)*(x3-x1) - (x2-x1)*(y3-y1); if ( det >= 0.0f ) { float tmp; // swap y1 & y3 tmp = y1; y1 = y3; y3 = tmp; // swap x1 & x3 tmp = x1; x1 = x3; x3 = tmp; } vertex * vertlist[3]; vertex verts[3]; for (i=0; i<3; i++ ) vertlist[i] = &verts[i]; verts[0].sx = x1; verts[0].sy = y1; verts[1].sx = x2; verts[1].sy = y2; verts[2].sx = x3; verts[2].sy = y3; verts[0].spec_r = 0; verts[1].spec_b = 0; verts[2].spec_g = 0; uint saved_mode = gr_zbuffer_get(); gr_zbuffer_set( GR_ZBUFF_NONE ); gr_tmapper( 3, vertlist, 0 ); gr_zbuffer_set( saved_mode ); } void hud_tri_empty(float x1,float y1,float x2,float y2,float x3,float y3) { gr_line(fl2i(x1),fl2i(y1),fl2i(x2),fl2i(y2)); gr_line(fl2i(x2),fl2i(y2),fl2i(x3),fl2i(y3)); gr_line(fl2i(x3),fl2i(y3),fl2i(x1),fl2i(y1)); } // Render a missile warning triangle that has a tail on it to indicate distance void hud_render_tail_missile_triangle(float ang, float xpos, float ypos, float cur_dist, int draw_solid, int draw_inside) { float x1=0.0f; float x2=0.0f; float y1=0.0f; float y2=0.0f; float xtail=0.0f; float ytail=0.0f; float sin_ang, cos_ang, tail_len; float max_tail_len=20.0f; sin_ang=(float)sin(ang); cos_ang=(float)cos(ang); if ( cur_dist < Min_warning_missile_dist ) { tail_len = 0.0f; } else if ( cur_dist > Max_warning_missile_dist ) { tail_len = max_tail_len; } else { tail_len = cur_dist/Max_warning_missile_dist * max_tail_len; } if ( draw_inside ) { x1 = xpos - Target_triangle_base[gr_screen.res] * -sin_ang; y1 = ypos + Target_triangle_base[gr_screen.res] * cos_ang; x2 = xpos + Target_triangle_base[gr_screen.res] * -sin_ang; y2 = ypos - Target_triangle_base[gr_screen.res] * cos_ang; xpos -= Target_triangle_height[gr_screen.res] * cos_ang; ypos += Target_triangle_height[gr_screen.res] * sin_ang; if ( tail_len > 0 ) { xtail = xpos - tail_len * cos_ang; ytail = ypos + tail_len * sin_ang; } } else { x1 = xpos - Target_triangle_base[gr_screen.res] * -sin_ang; y1 = ypos + Target_triangle_base[gr_screen.res] * cos_ang; x2 = xpos + Target_triangle_base[gr_screen.res] * -sin_ang; y2 = ypos - Target_triangle_base[gr_screen.res] * cos_ang; xpos += Target_triangle_height[gr_screen.res] * cos_ang; ypos -= Target_triangle_height[gr_screen.res] * sin_ang; if ( tail_len > 0 ) { xtail = xpos + tail_len * cos_ang; ytail = ypos - tail_len * sin_ang; } } if (draw_solid) { hud_tri(xpos,ypos,x1,y1,x2,y2); } else { hud_tri_empty(xpos,ypos,x1,y1,x2,y2); } // draw the tail indicating length if ( tail_len > 0 ) { gr_line(fl2i(xpos), fl2i(ypos), fl2i(xtail), fl2i(ytail)); } } // Render a missile warning triangle, that splits apart to indicate distance void hud_render_split_missile_triangle(float ang, float xpos, float ypos, float cur_dist, int draw_solid, int draw_inside) { // points to draw triangles float x1=0.0f; float y1=0.0f; float x2=0.0f; float y2=0.0f; float x3=0.0f; float y3=0.0f; float x4=0.0f; float y4=0.0f; float x5=0.0f; float y5=0.0f; float x6=0.0f; float y6=0.0f; float triangle_sep, half_triangle_sep,sin_ang,cos_ang; sin_ang=(float)sin(ang); cos_ang=(float)cos(ang); if ( cur_dist < Min_warning_missile_dist ) { triangle_sep = 0.0f; } else if ( cur_dist > Max_warning_missile_dist ) { triangle_sep = Max_offscreen_tri_seperation[gr_screen.res]+Max_front_seperation[gr_screen.res]; } else { triangle_sep = (cur_dist/Max_warning_missile_dist) * (Max_offscreen_tri_seperation[gr_screen.res]+Max_front_seperation[gr_screen.res]); } // calculate these values only once, since it will be used in several places half_triangle_sep = 0.5f * triangle_sep; xpos = (float)floor(xpos); ypos = (float)floor(ypos); if ( triangle_sep == 0 ) { x1 = xpos - Target_triangle_base[gr_screen.res] * -sin_ang; y1 = ypos + Target_triangle_base[gr_screen.res] * cos_ang; x2 = xpos + Target_triangle_base[gr_screen.res] * -sin_ang; y2 = ypos - Target_triangle_base[gr_screen.res] * cos_ang; if ( draw_inside ) { } else { xpos += Target_triangle_height[gr_screen.res] * cos_ang; ypos -= Target_triangle_height[gr_screen.res] * sin_ang; } if (draw_solid) { hud_tri(xpos,ypos,x1,y1,x2,y2); } else { hud_tri_empty(xpos,ypos,x1,y1,x2,y2); } } else { // calc left side points x5 = xpos - half_triangle_sep * -sin_ang; y5 = ypos + half_triangle_sep * cos_ang; x6 = x5 - Target_triangle_base[gr_screen.res] * -sin_ang; y6 = y5 + Target_triangle_base[gr_screen.res] * cos_ang; x4=x5; y4=y5; if ( draw_inside ) { x4 -= Target_triangle_height[gr_screen.res] * cos_ang; y4 += Target_triangle_height[gr_screen.res] * sin_ang; } else { x4 += Target_triangle_height[gr_screen.res] * cos_ang; y4 -= Target_triangle_height[gr_screen.res] * sin_ang; } // calc right side points x2 = xpos + half_triangle_sep * -sin_ang; y2 = ypos - half_triangle_sep * cos_ang; x3 = x2 + Target_triangle_base[gr_screen.res] * -sin_ang; y3 = y2 - Target_triangle_base[gr_screen.res] * cos_ang; x1=x2; y1=y2; if ( draw_inside ) { x1 -= Target_triangle_height[gr_screen.res] * cos_ang; y1 += Target_triangle_height[gr_screen.res] * sin_ang; } else { x1 += Target_triangle_height[gr_screen.res] * cos_ang; y1 -= Target_triangle_height[gr_screen.res] * sin_ang; } // draw both tris with a line connecting them if ( draw_solid ) { hud_tri(x3,y3,x2,y2,x1,y1); hud_tri(x4,y4,x5,y5,x6,y6); } else { hud_tri_empty(x3,y3,x2,y2,x1,y1); hud_tri_empty(x4,y4,x5,y5,x6,y6); } gr_line(fl2i(x2+0.5f),fl2i(y2+0.5f),fl2i(x5+0.5f),fl2i(y5+0.5f)); } } // Render a triangle on the outside of the targeting circle. // Must be inside a g3_start_frame(). // If aspect_flag !0, then render filled, indicating aspect lock. // If show_interior !0, then point inwards to positions inside reticle void hud_render_triangle(vector *hostile_pos, int aspect_flag, int show_interior, int split_tri) { vertex hostile_vertex; float ang; float xpos,ypos,cur_dist,sin_ang,cos_ang; int draw_inside=0; // determine if the closest firing object is within the targeting reticle (which means the triangle // is not drawn) cur_dist = vm_vec_dist_quick(&Player_obj->pos, hostile_pos); g3_rotate_vertex(&hostile_vertex, hostile_pos); if (hostile_vertex.codes == 0) {// on screen float projected_x, projected_y; g3_project_vertex(&hostile_vertex); if (!(hostile_vertex.flags & PF_OVERFLOW)) { // make sure point projected float mag_squared; projected_x = hostile_vertex.sx; projected_y = hostile_vertex.sy; mag_squared = (projected_x-Hud_reticle_center[gr_screen.res][0])*(projected_x-Hud_reticle_center[gr_screen.res][0]) + (projected_y-Hud_reticle_center[gr_screen.res][1])*(projected_y-Hud_reticle_center[gr_screen.res][1]); if ( mag_squared < Outer_circle_radius[gr_screen.res]*Outer_circle_radius[gr_screen.res] ) { if ( !show_interior ) { return; } else { draw_inside=1; } } } } ang = atan2_safe(hostile_vertex.y,hostile_vertex.x); sin_ang=(float)sin(ang); cos_ang=(float)cos(ang); if ( draw_inside ) { xpos = Hud_reticle_center[gr_screen.res][0] + cos_ang*(Outer_circle_radius[gr_screen.res]-7); ypos = Hud_reticle_center[gr_screen.res][1] - sin_ang*(Outer_circle_radius[gr_screen.res]-7); } else { xpos = Hud_reticle_center[gr_screen.res][0] + cos_ang*(Outer_circle_radius[gr_screen.res]+4); ypos = Hud_reticle_center[gr_screen.res][1] - sin_ang*(Outer_circle_radius[gr_screen.res]+4); } xpos += HUD_offset_x; ypos += HUD_offset_y; if ( split_tri ) { // hud_render_split_missile_triangle(ang, xpos, ypos, cur_dist, aspect_flag, draw_inside); hud_render_tail_missile_triangle(ang, xpos, ypos, cur_dist, aspect_flag, draw_inside); } else { float x1=0.0f; float x2=0.0f; float y1=0.0f; float y2=0.0f; if ( draw_inside ) { x1 = xpos - Target_triangle_base[gr_screen.res] * -sin_ang; y1 = ypos + Target_triangle_base[gr_screen.res] * cos_ang; x2 = xpos + Target_triangle_base[gr_screen.res] * -sin_ang; y2 = ypos - Target_triangle_base[gr_screen.res] * cos_ang; xpos -= Target_triangle_height[gr_screen.res] * cos_ang; ypos += Target_triangle_height[gr_screen.res] * sin_ang; } else { x1 = xpos - Target_triangle_base[gr_screen.res] * -sin_ang; y1 = ypos + Target_triangle_base[gr_screen.res] * cos_ang; x2 = xpos + Target_triangle_base[gr_screen.res] * -sin_ang; y2 = ypos - Target_triangle_base[gr_screen.res] * cos_ang; xpos += Target_triangle_height[gr_screen.res] * cos_ang; ypos -= Target_triangle_height[gr_screen.res] * sin_ang; } if (aspect_flag) { hud_tri(xpos,ypos,x1,y1,x2,y2); } else { hud_tri_empty(xpos,ypos,x1,y1,x2,y2); } } } // Show all homing missiles locked onto the player. // Also, play the beep! void hud_show_homing_missiles() { object *A; missile_obj *mo; weapon *wp; float dist, nearest_dist; int closest_is_aspect=0; gr_set_color_fast(&HUD_color_homing_indicator); nearest_dist = Homing_beep.max_cycle_dist; for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) { A = &Objects[mo->objnum]; Assert((A->instance >= 0) && (A->instance < MAX_WEAPONS)); wp = &Weapons[A->instance]; if (wp->homing_object == Player_obj) { hud_render_triangle(&A->pos, Weapon_info[wp->weapon_info_index].wi_flags & WIF_HOMING_ASPECT, 1, 1); dist = vm_vec_dist_quick(&A->pos, &Player_obj->pos); if (dist < nearest_dist) { nearest_dist = dist; if ( Weapon_info[wp->weapon_info_index].wi_flags & WIF_HOMING_ASPECT ) { closest_is_aspect=1; } else { closest_is_aspect=0; } } } } // See if need to play warning beep. if (nearest_dist < Homing_beep.max_cycle_dist ) { float delta_time; float cycle_time; delta_time = f2fl(Missiontime - Homing_beep.last_time_played); // figure out the cycle time by doing a linear interpretation cycle_time = Homing_beep.min_cycle_time + (nearest_dist-Homing_beep.min_cycle_dist) * Homing_beep.precalced_interp; // play a new 'beep' if cycle time has elapsed if ( (delta_time*1000) > cycle_time ) { Homing_beep.last_time_played = Missiontime; if ( snd_is_playing(Homing_beep.snd_handle) ) { snd_stop(Homing_beep.snd_handle); } if ( closest_is_aspect ) { Homing_beep.snd_handle = snd_play(&Snds[SND_PROXIMITY_ASPECT_WARNING]); } else { Homing_beep.snd_handle = snd_play(&Snds[SND_PROXIMITY_WARNING]); } } } } // hud_show_orientation_tee() will draw the orientation gauge that orbits the inside of the // outer reticle ring. If the T is at 12 o'clock, the target is facing the player, if the T // is at 6 o'clock the target is facing away from the player. If the T is at 3 or 9 o'clock // the target is facing 90 away from the player. void hud_show_orientation_tee() { object* targetp; if (Player_ai->target_objnum == -1) return; targetp = &Objects[Player_ai->target_objnum]; if ( hud_gauge_maybe_flash(HUD_ORIENTATION_TEE) == 1 ) { hud_set_iff_color( targetp ); } else { hud_set_iff_color( targetp, 1); } hud_render_orientation_tee(targetp, Player_obj, &targetp->orient); } // routine to draw a bounding box around a remote detonate missile and distance to void hud_show_remote_detonate_missile() { missile_obj *mo; object *mobjp; float distance; vertex target_point; int x1, x2, y1, y2; // check for currently locked missiles (highest precedence) for ( mo = GET_FIRST(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) { Assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS); mobjp = &Objects[mo->objnum]; if ((Player_obj != NULL) && (mobjp->parent_sig == Player_obj->parent_sig)) { if (Weapon_info[Weapons[mobjp->instance].weapon_info_index].wi_flags & WIF_REMOTE) { // get distance distance = hud_find_target_distance(mobjp, Player_obj); // get box center point g3_rotate_vertex(&target_point,&mobjp->pos); // project vertex g3_project_vertex(&target_point); if (!(target_point.flags & PF_OVERFLOW)) { // make sure point projected int modelnum, bound_rval; switch ( mobjp->type ) { case OBJ_WEAPON: modelnum = Weapon_info[Weapons[mobjp->instance].weapon_info_index].model_num; bound_rval = model_find_2d_bound_min( modelnum, &mobjp->orient, &mobjp->pos,&x1,&y1,&x2,&y2 ); break; default: Int3(); // should never happen return; } if ( bound_rval == 0 ) { // draw brackets and distance int color; color = hud_brackets_get_iff_color(MESSAGE_SENDER); gr_set_color_fast(&IFF_colors[color][1]); draw_bounding_brackets(x1-5,y1-5,x2+5,y2+5,0,0, distance, OBJ_INDEX(mobjp)); } // do only for the first remote detonate missile break; } } } } } // routine to possibly draw a bounding box around a ship sending a message to the player void hud_show_message_sender() { object *targetp; vertex target_point; // temp vertex used to find screen position for 3-D object; ship *target_shipp; int x1,x2,y1,y2; // don't draw brackets if no ship sending a message if ( Message_shipnum == -1 ) return; targetp = &Objects[Ships[Message_shipnum].objnum]; Assert ( targetp != NULL ); Assert ( targetp->type == OBJ_SHIP ); // Don't do this for the ship you're flying! if ( targetp == Player_obj ) { return; } // Goober5000 - don't draw if primitive sensors if ( Ships[Player_obj->instance].flags2 & SF2_PRIMITIVE_SENSORS ) { return; } Assert ( targetp->instance >=0 && targetp->instance < MAX_SHIPS ); target_shipp = &Ships[Message_shipnum]; // check the object flags to see if this ship is gone. If so, then don't do this stuff anymore if ( targetp->flags & OF_SHOULD_BE_DEAD ) { Message_shipnum = -1; return; } // find the current target vertex // g3_rotate_vertex(&target_point,&targetp->pos); hud_set_iff_color( targetp, 1); g3_project_vertex(&target_point); if (!(target_point.flags & PF_OVERFLOW)) { // make sure point projected int modelnum, bound_rval; switch ( targetp->type ) { case OBJ_SHIP: modelnum = target_shipp->modelnum; bound_rval = model_find_2d_bound_min( modelnum, &targetp->orient, &targetp->pos,&x1,&y1,&x2,&y2 ); break; default: Int3(); // should never happen return; } if ( bound_rval == 0 ) { int color; color = hud_brackets_get_iff_color(MESSAGE_SENDER); gr_set_color_fast(&IFF_colors[color][1]); draw_bounding_brackets(x1-5,y1-5,x2+5,y2+5,10,10); } } if ( hud_gauge_active(HUD_OFFSCREEN_INDICATOR) ) { if (target_point.codes != 0) { // target center is not on screen // draw the offscreen indicator at the edge of the screen where the target is closest to // AL 11-19-97: only show offscreen indicator if player sensors are functioning if ( (OBJ_INDEX(targetp) != Player_ai->target_objnum) || (Message_shipnum == Objects[Player_ai->target_objnum].instance) ) { if ( hud_sensors_ok(Player_ship, 0) ) { float dist; gr_set_color_fast(&IFF_colors[IFF_COLOR_MESSAGE][1]); //dist = vm_vec_dist_quick(&Player_obj->pos, &targetp->pos); dist = hud_find_target_distance( targetp, Player_obj ); hud_draw_offscreen_indicator(&target_point, &targetp->pos, dist); } } } } } // hud_prune_hotkeys() // // Check for ships that are dying, departed or dead. These should be removed from the player's // hotkey lists. void hud_prune_hotkeys() { int i; htarget_list *hitem, *plist; object *objp; ship *sp; for ( i = 0; i < MAX_KEYED_TARGETS; i++ ) { plist = &(Players[Player_num].keyed_targets[i]); if ( EMPTY( plist ) ) // no items in list, then do nothing continue; hitem = GET_FIRST(plist); while ( hitem != END_OF_LIST(plist) ) { int remove_item; remove_item = 0; objp = hitem->objp; Assert ( objp != NULL ); if ( objp->type == OBJ_SHIP ) { Assert ( objp->instance >=0 && objp->instance < MAX_SHIPS ); sp = &Ships[objp->instance]; } else { // if the object isn't a ship, it shouldn't be on the list, so remove it without question remove_item = 1; sp = NULL; } // check to see if the object is dying -- if so, remove it from the list // check to see if the ship is departing -- if so, remove it from the list if ( remove_item || (objp->flags & OF_SHOULD_BE_DEAD) || (sp->flags & (SF_DEPARTING|SF_DYING)) ) { if ( sp != NULL ) { nprintf(("Network", "Hotkey: Pruning %s\n", sp->ship_name)); } htarget_list *temp; temp = GET_NEXT(hitem); list_remove( plist, hitem ); list_append( &htarget_free_list, hitem ); hitem->objp = NULL; hitem = temp; continue; } hitem = GET_NEXT( hitem ); } // end while } // end for // save the hotkey sets with mission time reaches a certain point. Code was put here because this // function always called for both single/multiplayer. Maybe not the best location, but whatever. mission_hotkey_maybe_save_sets(); } int HUD_drew_selection_bracket_on_target; // hud_show_selection_set draws some indicator around all the ships in the current selection set. No // indicators will be drawn if there is only 1 ship in the set. void hud_show_selection_set() { htarget_list *hitem, *plist; object *targetp; int set, count; vertex target_point; // temp vertex used to find screen position for 3-D object; vector target_vec; HUD_drew_selection_bracket_on_target = 0; set = Players[Player_num].current_hotkey_set; if ( set == -1 ) return; Assert ( (set >= 0) && (set < MAX_KEYED_TARGETS) ); plist = &(Players[Player_num].keyed_targets[set]); count = 0; for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) count++; if ( count == 0 ) { // only one ship, do nothing Players[Player_num].current_hotkey_set = -1; return; } for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { targetp = hitem->objp; Assert ( targetp != NULL ); ship *target_shipp = NULL; Assert ( targetp->type == OBJ_SHIP ); Assert ( targetp->instance >=0 && targetp->instance < MAX_SHIPS ); target_shipp = &Ships[targetp->instance]; if ( (Game_mode & GM_MULTIPLAYER) && (target_shipp == Player_ship) ) { continue; } // find the current target vertex // g3_rotate_vertex(&target_point,&targetp->pos); vm_vec_sub(&target_vec,&targetp->pos,&Player_obj->pos); int x1,x2,y1,y2; hud_set_iff_color( targetp, 1 ); g3_project_vertex(&target_point); if (!(target_point.flags & PF_OVERFLOW)) { // make sure point projected int modelnum, bound_rval; switch ( targetp->type ) { case OBJ_SHIP: modelnum = target_shipp->modelnum; bound_rval = model_find_2d_bound_min( modelnum, &targetp->orient, &targetp->pos,&x1,&y1,&x2,&y2 ); break; default: Int3(); // should never happen return; } if ( bound_rval == 0 ) { gr_set_color_fast(&IFF_colors[IFF_COLOR_SELECTION][1]); draw_bounding_brackets(x1-5,y1-5,x2+5,y2+5,5,5); if ( OBJ_INDEX(targetp) == Player_ai->target_objnum ) { HUD_drew_selection_bracket_on_target = 1; } } } if ( hud_gauge_active(HUD_OFFSCREEN_INDICATOR) ) { if (target_point.codes != 0) { // target center is not on screen // draw the offscreen indicator at the edge of the screen where the target is closest to // AL 11-19-97: only show offscreen indicator if player sensors are functioning if ( OBJ_INDEX(targetp) != Player_ai->target_objnum ) { if ( hud_sensors_ok(Player_ship, 0) ) { float dist; gr_set_color_fast(&IFF_colors[IFF_COLOR_SELECTION][1]); //dist = vm_vec_dist_quick(&Player_obj->pos, &targetp->pos); dist = hud_find_target_distance( targetp, Player_obj ); hud_draw_offscreen_indicator(&target_point, &targetp->pos, dist); } } } } } } void hud_show_brackets(object *targetp, vertex *projected_v) { int x1,x2,y1,y2; int draw_box = TRUE; int iff, bound_rc; if ( Player->target_is_dying <= 0 ) { int modelnum; switch ( targetp->type ) { case OBJ_SHIP: modelnum = Ships[targetp->instance].modelnum; bound_rc = model_find_2d_bound_min( modelnum, &targetp->orient, &targetp->pos,&x1,&y1,&x2,&y2 ); if ( bound_rc != 0 ) { draw_box = FALSE; } break; case OBJ_DEBRIS: modelnum = Debris[targetp->instance].model_num; bound_rc = submodel_find_2d_bound_min( modelnum, Debris[targetp->instance].submodel_num, &targetp->orient, &targetp->pos,&x1,&y1,&x2,&y2 ); if ( bound_rc != 0 ) { draw_box = FALSE; } break; case OBJ_WEAPON: Assert(Weapon_info[Weapons[targetp->instance].weapon_info_index].subtype == WP_MISSILE); modelnum = Weapon_info[Weapons[targetp->instance].weapon_info_index].model_num; bound_rc = model_find_2d_bound_min( modelnum, &targetp->orient, &targetp->pos,&x1,&y1,&x2,&y2 ); break; #ifndef FS2_DEMO case OBJ_ASTEROID: { int subtype = 0; subtype = Asteroids[targetp->instance].asteroid_subtype; modelnum = Asteroid_info[Asteroids[targetp->instance].type].model_num[subtype]; bound_rc = model_find_2d_bound_min( modelnum, &targetp->orient, &targetp->pos,&x1,&y1,&x2,&y2 ); } break; #endif case OBJ_JUMP_NODE: modelnum = Jump_nodes[targetp->instance].modelnum; bound_rc = model_find_2d_bound_min( modelnum, &targetp->orient, &targetp->pos,&x1,&y1,&x2,&y2 ); break; default: Int3(); // should never happen return; } Hud_target_w = x2-x1+1; if ( Hud_target_w > gr_screen.clip_width ) { Hud_target_w = gr_screen.clip_width; } Hud_target_h = y2-y1+1; if ( Hud_target_h > gr_screen.clip_height ) { Hud_target_h = gr_screen.clip_height; } if ( targetp->type == OBJ_ASTEROID ) { if ( OBJ_INDEX(targetp) == Player_ai->target_objnum ) { iff = IFF_COLOR_RED; //team = TEAM_TRAITOR; } else { iff = IFF_COLOR_SELECTION; //team = SELECTION_SET; } } else { iff = obj_iff(targetp); //team = obj_team(targetp); } if ( draw_box == TRUE ) { float distance; int color; color = hud_brackets_get_iff_color(iff); // maybe color as tagged if ( ship_is_tagged(targetp) ) { color = IFF_COLOR_TAGGED; } distance = hud_find_target_distance( targetp, Player_obj ); gr_set_color_fast(&IFF_colors[color][1]); draw_bounding_brackets(x1-5,y1-5,x2+5,y2+5,0,0,distance, OBJ_INDEX(targetp)); } if ( targetp->type == OBJ_SHIP ) { draw_bounding_brackets_subobject(); } } } void hud_update_target_in_reticle(vertex *projected_v) { float mag_squared; mag_squared = (projected_v->sx-Hud_reticle_center[gr_screen.res][0])*(projected_v->sx-Hud_reticle_center[gr_screen.res][0]) + (projected_v->sy-Hud_reticle_center[gr_screen.res][1])*(projected_v->sy-Hud_reticle_center[gr_screen.res][1]); if (mag_squared < Outer_circle_radius[gr_screen.res]*Outer_circle_radius[gr_screen.res]) { // this information can be used elsewhere Target_in_reticle = 1; } else { // this information can be used elsewhere Target_in_reticle = 0; } } // hud_show_targeting_gauges() will display the targeting information on the HUD. Called once per frame. // // Must be inside a g3_start_frame() // input: frametime => time in seconds since last update // in_cockpit => flag (default value 1) indicating whether viewpoint is from cockpit or external void hud_show_targeting_gauges(float frametime, int in_cockpit) { vertex target_point; // temp vertex used to find screen position for 3-D object; vector target_pos; // draw the triangle that points to the closest hostile ship that is firing on the player // This is always drawn, even if there is no current target. There is also a hook that will // maybe warn the player via a voice message of an attacking ship. if ( in_cockpit ) { hud_show_hostile_triangle(); } if (Player_ai->target_objnum == -1) return; object * targetp = &Objects[Player_ai->target_objnum]; Players[Player_num].lead_indicator_active = 0; // check to see if there is even a current target if ( targetp == &obj_used_list ) { return; } Target_in_reticle = 0; // AL 1/20/97: Point to targted subsystem if one exists if ( Player_ai->targeted_subsys != NULL ) { get_subsystem_world_pos(targetp, Player_ai->targeted_subsys, &target_pos); Player_ai->current_target_distance = vm_vec_dist_quick(&target_pos,&Player_obj->pos); } else { target_pos = targetp->pos; Player_ai->current_target_distance = hud_find_target_distance(targetp,Player_obj); } // find the current target vertex // // The 2D screen pos depends on the current viewer position and orientation. g3_rotate_vertex(&target_point,&target_pos); hud_set_iff_color( targetp, 1 ); g3_project_vertex(&target_point); if (!(target_point.flags & PF_OVERFLOW)) { // make sure point projected if (target_point.codes == 0) { // target center is not on screen hud_show_brackets(targetp, &target_point); } hud_update_target_in_reticle(&target_point); } else { Hud_target_w = 0; Hud_target_h = 0; } // show the leading target indicator if ((hud_gauge_active(HUD_LEAD_INDICATOR)) && (!Player->target_is_dying)) { hud_show_lead_indicator(&target_pos); } if ( in_cockpit ) { // show the indicator that orbits the outer reticle and points in the direction of the target hud_show_target_triangle_indicator(&target_point); // draw the orientation tee that orbits the inside of the outer circle of the reticle if ((hud_gauge_active(HUD_ORIENTATION_TEE)) && (!Player->target_is_dying)) { hud_show_orientation_tee(); } // display the information about the target if ( hud_gauge_active(HUD_TARGET_MONITOR) ){ if ( !hud_targetbox_static_maybe_blit(frametime) ) hud_show_target_data(frametime); } // update cargo scanning hud_cargo_scan_update(targetp, frametime); // draw the shield icon for the current target if ( hud_gauge_active(HUD_TARGET_SHIELD_ICON) ) { hud_shield_show(targetp); } // draw the mini target+shield gauge that sits near the bottom of the retcle if ( hud_gauge_active(HUD_TARGET_MINI_ICON) ) { int show_gauge_flag=1; // is gauge configured as a popup? if ( hud_gauge_is_popup(HUD_TARGET_MINI_ICON) ) { if ( !hud_gauge_popup_active(HUD_TARGET_MINI_ICON) ) { show_gauge_flag=0; } } if ( show_gauge_flag ) { // hud_shield_show_mini(targetp); } } } else { Player->cargo_inspect_time = 0; player_stop_cargo_scan_sound(); } // display the lock indicator if (!Player->target_is_dying) { hud_update_lock_indicator(frametime); hud_show_lock_indicator(frametime); // update and render artillery hud_artillery_update(); hud_artillery_render(); } // Point to offscreen target if ( hud_gauge_active(HUD_OFFSCREEN_INDICATOR) ) { if (target_point.codes != 0) { // target center is not on screen // draw the offscreen indicator at the edge of the screen where the target is closest to Assert(Player_ai->target_objnum != -1); // AL 11-11-97: don't draw the indicator if the ship is messaging, the indicator is drawn // in the message sending color in hud_show_message_sender() if ( Message_shipnum != Objects[Player_ai->target_objnum].instance ) { if ( hud_gauge_maybe_flash(HUD_OFFSCREEN_INDICATOR) != 1) { float dist; hud_set_iff_color( targetp, 1 ); //dist = vm_vec_dist_quick(&Player_obj->pos, &target_pos); dist = hud_find_target_distance( targetp, Player_obj ); hud_draw_offscreen_indicator(&target_point, &target_pos, dist); } } } } } // hud_show_hostile_triangle() will draw an empty triangle that oribits around the outer // circle of the reticle. It will point to the closest enemy that is firing on the player. // Currently, it points to the closest enemy that has the player as its target_objnum and has // SM_ATTACK or SM_SUPER_ATTACK as its ai submode. void hud_show_hostile_triangle() { object* A; float min_distance=1e20f; float new_distance=0.0f; object* hostile_obj = &obj_used_list; object* nearest_obj = &obj_used_list; ai_info *aip; ship_obj *so; ship *sp; ship_subsys *ss, *nearest_turret_subsys = NULL; int player_obj_index = OBJ_INDEX(Player_obj); int turret_is_attacking = 0; so = GET_FIRST(&Ship_obj_list); for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; sp = &Ships[A->instance]; // only look at ships on other team if ( (A == Player_obj) || (Ships[A->instance].team & Player_ship->team) ) { continue; } aip = &Ai_info[Ships[A->instance].ai_index]; // dont look at ignore ships if ( sp->flags & TARGET_SHIP_IGNORE_FLAGS ) { continue; } // always ignore cargo containers and navbuoys if ( Ship_info[sp->ship_info_index].flags & SIF_HARMLESS ) { continue; } // check if ship is stealthy if (awacs_get_level(&Objects[sp->objnum], Player_ship, 1) < 1) { continue; } turret_is_attacking = 0; // check if any turrets on ship are firing at the player (only on non fighter-bombers) if ( !(Ship_info[sp->ship_info_index].flags & (SIF_FIGHTER|SIF_BOMBER)) ) { for (ss = GET_FIRST(&sp->subsys_list); ss != END_OF_LIST(&sp->subsys_list); ss = GET_NEXT(ss) ) { if ( (ss->system_info->type == SUBSYSTEM_TURRET) && (ss->current_hits > 0) ) { if ( ss->turret_enemy_objnum == player_obj_index ) { turret_is_attacking = 1; vector gsubpos; // get world pos of subsystem vm_vec_unrotate(&gsubpos, &ss->system_info->pnt, &A->orient); vm_vec_add2(&gsubpos, &A->pos); new_distance = vm_vec_dist_quick(&gsubpos, &Player_obj->pos); if (new_distance <= min_distance) { min_distance=new_distance; nearest_obj = A; nearest_turret_subsys = ss; } } } } } if ( !turret_is_attacking ) { // check for ships attacking the player if ( aip->target_objnum != Player_ship->objnum ) { continue; } // ignore enemy if not in chase mode if ( (Game_mode & GM_NORMAL) && (aip->mode != AIM_CHASE) ) { continue; } new_distance = vm_vec_dist_quick(&A->pos, &Player_obj->pos); if (new_distance <= min_distance) { min_distance=new_distance; nearest_obj = A; nearest_turret_subsys = NULL; } } } if ( nearest_obj == &obj_used_list ) { return; } if ( min_distance > MIN_DISTANCE_TO_CONSIDER_THREAT ) { return; } hostile_obj = nearest_obj; // hook to maybe warn player about this attacking ship ship_maybe_warn_player(&Ships[nearest_obj->instance], min_distance); // check if the closest firing hostile is the current target, if so return if (OBJ_INDEX(hostile_obj) == Player_ai->target_objnum) return; if ( hud_gauge_active(HUD_HOSTILE_TRIANGLE) ) { if ( hud_gauge_maybe_flash(HUD_HOSTILE_TRIANGLE) != 1 ) { // hud_set_iff_color( TEAM_HOSTILE, 1 ); // Note: This should really be TEAM_HOSTILE, not opposite of Player_ship->team. hud_set_iff_color( hostile_obj, 1 ); hud_render_triangle(&hostile_obj->pos, 0, 1, 0); } } } // Return the bank number for the primary weapon that can fire the farthest, from // the number of active primary weapons // input: range => output parameter... it is the range of the selected bank int hud_get_best_primary_bank(float *range) { int i, best_bank, bank_to_fire, num_to_test; float weapon_range, farthest_weapon_range; ship_weapon *swp; weapon_info *wip; swp = &Player_ship->weapons; farthest_weapon_range = 0.0f; best_bank = -1; if ( Player_ship->flags & SF_PRIMARY_LINKED ) { num_to_test = swp->num_primary_banks; } else { num_to_test = min(1, swp->num_primary_banks); } for ( i = 0; i < num_to_test; i++ ) { bank_to_fire = (swp->current_primary_bank + i) % MAX_PLAYER_PRIMARY_BANKS; // calculate the range of the weapon, and only display the lead target indicator // if the weapon can actually hit the target Assert(bank_to_fire >= 0 && bank_to_fire < swp->num_primary_banks); Assert(swp->primary_bank_weapons[bank_to_fire] >= 0 && swp->primary_bank_weapons[bank_to_fire] < MAX_WEAPON_TYPES); wip = &Weapon_info[swp->primary_bank_weapons[bank_to_fire]]; weapon_range = wip->max_speed * wip->lifetime; // don't consider this primary if it's a ballistic that's out of ammo - Goober5000 if ( wip->wi_flags2 & WIF2_BALLISTIC ) { if ( swp->primary_bank_ammo[bank_to_fire] <= 0) { continue; } } if ( weapon_range > farthest_weapon_range ) { best_bank = bank_to_fire; farthest_weapon_range = weapon_range; } } *range = farthest_weapon_range; return best_bank; } // ----------------------------------------------------------------------------- // polish_predicted_target_pos() // // Called by the draw lead indicator code to predict where the enemy is going to be // void polish_predicted_target_pos(vector *enemy_pos, vector *predicted_enemy_pos, float dist_to_enemy, vector *last_delta_vec, int num_polish_steps) { int iteration; vector player_pos = Player_obj->pos; float time_to_enemy; vector last_predicted_enemy_pos = *predicted_enemy_pos; ship *shipp; shipp = &Ships[Player_obj->instance]; Assert(shipp->weapons.current_primary_bank < shipp->weapons.num_primary_banks); weapon_info *wip = &Weapon_info[shipp->weapons.primary_bank_weapons[shipp->weapons.current_primary_bank]]; float weapon_speed = wip->max_speed; vm_vec_zero(last_delta_vec); for (iteration=0; iteration < num_polish_steps; iteration++) { dist_to_enemy = vm_vec_dist_quick(predicted_enemy_pos, &player_pos); time_to_enemy = dist_to_enemy/weapon_speed; // vm_vec_scale_add(predicted_enemy_pos, enemy_pos, &Objects[Player_ai->target_objnum].orient.vec.fvec, en_physp->speed * time_to_enemy); vm_vec_scale_add(predicted_enemy_pos, enemy_pos, &Objects[Player_ai->target_objnum].phys_info.vel, time_to_enemy); vm_vec_sub(last_delta_vec, predicted_enemy_pos, &last_predicted_enemy_pos); last_predicted_enemy_pos= *predicted_enemy_pos; } } // determine the correct frame to draw for the lead indicator // 0 -> center only (in secondary range only) // 1 -> full (in secondary and primary range) // 2 -> oustide only (in primary range only) // // input: prange => range of current primary weapon // srange => range of current secondary weapon // dist_to_target => current dist to target // // exit: 0-2 => frame offset // -1 => don't draw anything int hudtarget_lead_indicator_pick_frame(float prange, float srange, float dist_to_target) { int frame_offset=-1; int in_prange=0, in_srange=0; if ( dist_to_target < prange ) { in_prange=1; } if ( dist_to_target < srange ) { in_srange=1; } if ( in_prange && in_srange ) { frame_offset=1; } else if ( in_prange && !in_srange ) { frame_offset=2; } else if ( !in_prange && in_srange ) { frame_offset=0; } else { frame_offset=-1; } return frame_offset; } // decide what frame of lead indicator to draw // hud_show_lead_indicator() determine where to draw the lead target box and display it void hud_show_lead_indicator(vector *target_world_pos) { vector target_moving_direction, last_delta_vector, source_pos; vector *rel_pos; vertex lead_target_vertex; object *targetp; polymodel *po; ship_weapon *swp; weapon_info *wip; weapon_info *tmp=NULL; float dist_to_target, time_to_target, target_moved_dist, prange, srange; int bank_to_fire, indicator_frame, frame_offset; if (Player_ai->target_objnum == -1) return; targetp = &Objects[Player_ai->target_objnum]; if ( (targetp->type != OBJ_SHIP) && (targetp->type != OBJ_WEAPON) && (targetp->type != OBJ_ASTEROID) ) { return; } // don't display lead for ship if its cloaked if (Ships[targetp->instance].flags2 & SF2_CLOAK_ON) return; // only allow bombs to have lead indicator displayed /*if ( targetp->type == OBJ_WEAPON ) { if ( !(Weapon_info[Weapons[targetp->instance].weapon_info_index].wi_flags & WIF_BOMB) ) { return; } }*/ // If the target is out of range, then draw the correct frame for the lead indicator if ( Lead_indicator_gauge.first_frame == -1 ) { Int3(); return; } po = model_get( Player_ship->modelnum ); swp = &Player_ship->weapons; // Added to take care of situation where there are no primary banks on the player ship // (this may not be possible, depending on what we decide for the weapons loadout rules) if ( swp->num_primary_banks == 0 ) return; bank_to_fire = hud_get_best_primary_bank(&prange); if ( bank_to_fire < 0 ) return; wip = &Weapon_info[swp->primary_bank_weapons[bank_to_fire]]; if (po->n_guns && bank_to_fire != -1 ) { rel_pos = &po->gun_banks[bank_to_fire].pnt[0]; } else { rel_pos = NULL; } // source_pos will contain the world coordinate of where to base the lead indicator prediction // from. Normally, this will be the world pos of the gun turret of the currently selected primary // weapon. source_pos = Player_obj->pos; if (rel_pos != NULL) { vector gun_point; vm_vec_unrotate(&gun_point, rel_pos, &Player_obj->orient); vm_vec_add2(&source_pos, &gun_point); } // Determine "accurate" distance to target. This is the distance from the player ship // to the closest point on the bounding box of the target dist_to_target = hud_find_target_distance(targetp, Player_obj); srange = ship_get_secondary_weapon_range(Player_ship); if ( swp->current_secondary_bank >= 0 ) { int bank = swp->current_secondary_bank; tmp = &Weapon_info[swp->secondary_bank_weapons[bank]]; if ( tmp->wi_flags & WIF_HOMING_ASPECT ) { if ( !Player->target_in_lock_cone ) { srange = -1.0f; } } } frame_offset = hudtarget_lead_indicator_pick_frame(prange, srange, dist_to_target); /* Commented out by Goober5000, because it's a bit buggy. The original Volition code // is A-1 SUPAR and ought to work for dumbfires as well. O_o --------------- Phreak's Non-Working Code (TM) ------------ if (dist_to_target < prange) { frame_offset=2; if (tmp) { if ((dist_to_target < srange) && (tmp->wi_flags & WIF_HOMING_HEAT)) { frame_offset=1; } } } else { frame_offset=-1; if (tmp) { if((dist_to_target < srange) && (tmp->wi_flags & WIF_HOMING_HEAT)) { frame_offset=0; // and this probably should be 2 - Goober5000 } } } ----------------------------------------------------------- */ if ( frame_offset < 0 ) { return; } indicator_frame = Lead_indicator_gauge.first_frame + frame_offset; Assert(wip->max_speed != 0); time_to_target = dist_to_target / wip->max_speed; target_moved_dist = targetp->phys_info.speed * time_to_target; target_moving_direction = targetp->phys_info.vel; // if we've reached here, the lead target indicator will be displayed Players[Player_num].lead_indicator_active = 1; // test if the target is moving at all if ( vm_vec_mag_quick(&targetp->phys_info.vel) < 0.1f) // Find distance! Players[Player_num].lead_target_pos = *target_world_pos; else { vm_vec_normalize(&target_moving_direction); vm_vec_scale(&target_moving_direction,target_moved_dist); vm_vec_add(&Players[Player_num].lead_target_pos, target_world_pos, &target_moving_direction ); polish_predicted_target_pos(target_world_pos, &Players[Player_num].lead_target_pos, dist_to_target, &last_delta_vector, 1); // Not used:, float time_to_enemy) } g3_rotate_vertex(&lead_target_vertex,&Players[Player_num].lead_target_pos); if (lead_target_vertex.codes == 0) { // on screen g3_project_vertex(&lead_target_vertex); if (!(lead_target_vertex.flags & PF_OVERFLOW)) { if ( hud_gauge_maybe_flash(HUD_LEAD_INDICATOR) == 1 ) { hud_set_iff_color(targetp, 0); } else { hud_set_iff_color(targetp, 1); } if ( indicator_frame >= 0 ) { GR_AABITMAP(indicator_frame, fl2i(lead_target_vertex.sx - Lead_indicator_half[gr_screen.res][0]), fl2i(lead_target_vertex.sy - Lead_indicator_half[gr_screen.res][1])); } } } //do dumbfire lead indicator - color is orange (255,128,0) - bright, (192,96,0) - dim //phreak changed 9/01/02 if(swp->current_secondary_bank>=0) { int bank=swp->current_secondary_bank; wip=&Weapon_info[swp->secondary_bank_weapons[bank]]; //get out of here if the secondary weapon is a homer or if its out of range if ( (wip->wi_flags & WIF_HOMING_HEAT) || (wip->wi_flags & WIF_HOMING_ASPECT)) return; double max_dist=wip->lifetime*wip->max_speed; if (dist_to_target > max_dist) return; } //give it the "in secondary range frame indicator_frame = Lead_indicator_gauge.first_frame; Assert(wip->max_speed != 0); time_to_target = dist_to_target / wip->max_speed; target_moved_dist = targetp->phys_info.speed * time_to_target; target_moving_direction = targetp->phys_info.vel; // if we've reached here, the lead target indicator will be displayed Players[Player_num].lead_indicator_active = 1; // test if the target is moving at all if ( vm_vec_mag_quick(&targetp->phys_info.vel) < 0.1f) // Find distance! Players[Player_num].lead_target_pos = *target_world_pos; else { vm_vec_normalize(&target_moving_direction); vm_vec_scale(&target_moving_direction,target_moved_dist); vm_vec_add(&Players[Player_num].lead_target_pos, target_world_pos, &target_moving_direction ); polish_predicted_target_pos(target_world_pos, &Players[Player_num].lead_target_pos, dist_to_target, &last_delta_vector, 1); // Not used:, float time_to_enemy) } g3_rotate_vertex(&lead_target_vertex,&Players[Player_num].lead_target_pos); if (lead_target_vertex.codes == 0) { // on screen g3_project_vertex(&lead_target_vertex); if (!(lead_target_vertex.flags & PF_OVERFLOW)) { if ( hud_gauge_maybe_flash(HUD_LEAD_INDICATOR) == 1 ) { hud_set_iff_color(targetp, 0); } else { hud_set_iff_color(targetp, 1); } if ( indicator_frame >= 0 ) { GR_AABITMAP(indicator_frame, fl2i(lead_target_vertex.sx - Lead_indicator_half[gr_screen.res][0]), fl2i(lead_target_vertex.sy - Lead_indicator_half[gr_screen.res][1])); } } } } // hud_cease_subsystem_targeting() will cease targeting the current targets subsystems // void hud_cease_subsystem_targeting(int print_message) { int ship_index; ship_index = Objects[Player_ai->target_objnum].instance; if ( ship_index < 0 ) return; Ships[ship_index].last_targeted_subobject[Player_num] = NULL; Player_ai->targeted_subsys = NULL; Player_ai->targeted_subsys_parent = -1; if ( print_message ) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "Deactivating sub-system targeting", 324)); } hud_stop_looped_locking_sounds(); hud_lock_reset(); } // hud_cease_targeting() will cease all targeting (main target and subsystem) // void hud_cease_targeting() { set_target_objnum( Player_ai, -1 ); Players[Player_num].flags &= ~PLAYER_FLAGS_AUTO_TARGETING; hud_cease_subsystem_targeting(0); HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "Deactivating targeting system", 325)); hud_lock_reset(); } // hud_restore_subsystem_target() will remember the last targeted subsystem // on a target. // void hud_restore_subsystem_target(ship* shipp) { // check if there was a previously targeted sub-system for this target if ( shipp->last_targeted_subobject[Player_num] != NULL ) { Player_ai->targeted_subsys = shipp->last_targeted_subobject[Player_num]; Player_ai->targeted_subsys_parent = Player_ai->target_objnum; } else { Player_ai->targeted_subsys = NULL; Player_ai->targeted_subsys_parent = -1; } } // -------------------------------------------------------------------------------- // get_subsystem_world_pos() returns the world position for a given subobject on a ship // vector* get_subsystem_world_pos(object* parent_obj, ship_subsys* subsys, vector* world_pos) { if (subsys == NULL) { *world_pos = parent_obj->pos; return world_pos; } vm_vec_unrotate(world_pos, &subsys->system_info->pnt, &parent_obj->orient); vm_vec_add2(world_pos, &parent_obj->pos); return world_pos; } // If Pl_objp is docking, see if it (or the dockee) are in the target view. If so, flash dock // text on the HUD. void hud_maybe_flash_docking_text(object *objp) { ai_info *aip; int docker_objnum, dockee_objnum; if ( Player_ai->target_objnum < 0 ) { return; } if ( objp->type != OBJ_SHIP ) { return; } aip = &Ai_info[Ships[objp->instance].ai_index]; docker_objnum = -1; dockee_objnum = -1; if ( aip->ai_flags & AIF_DOCKED ) { docker_objnum = OBJ_INDEX(objp); dockee_objnum = aip->dock_objnum; } if ( (Player_ai->target_objnum == docker_objnum) || (Player_ai->target_objnum == dockee_objnum) ) { hud_targetbox_start_flash(TBOX_FLASH_DOCKED, 2000); } } // ---------------------------------------------------------------------------- // hud_target_change_check() // // called once per frame to account for when the target changes // void hud_target_change_check() { float current_speed=0.0f; // Check if player subsystem target has changed, and reset necessary player flag if ( Player_ai->targeted_subsys != Player_ai->last_subsys_target ) { Player->subsys_in_view=-1; } // check if the main target has changed if (Player_ai->last_target != Player_ai->target_objnum) { if ( Player_ai->target_objnum != -1){ snd_play( &Snds[SND_TARGET_ACQUIRE], 0.0f ); } // if we have a hotkey set active, see if new target is in set. If not in // set, deselect the current hotkey set. if ( Player->current_hotkey_set != -1 ) { htarget_list *hitem, *plist; plist = &(Player->keyed_targets[Player->current_hotkey_set]); for ( hitem = GET_FIRST(plist); hitem != END_OF_LIST(plist); hitem = GET_NEXT(hitem) ) { if ( OBJ_INDEX(hitem->objp) == Player_ai->target_objnum ){ break; } } if ( hitem == END_OF_LIST(plist) ){ Player->current_hotkey_set = -1; } } player_stop_cargo_scan_sound(); hud_shield_hit_reset(); hud_targetbox_init_flash(); hud_targetbox_start_flash(TBOX_FLASH_NAME); hud_gauge_popup_start(HUD_TARGET_MINI_ICON); Player->cargo_inspect_time=0; Player->locking_subsys=NULL; Player->locking_on_center=0; Player->locking_subsys_parent=-1; Player_ai->current_target_dist_trend = NO_CHANGE; Player_ai->current_target_speed_trend = NO_CHANGE; if ( Players[Player_num].flags & PLAYER_FLAGS_AUTO_MATCH_SPEED ) { Players[Player_num].flags &= ~PLAYER_FLAGS_MATCH_TARGET; // player_match_target_speed("", "", XSTR("Matching speed of newly acquired target",-1)); player_match_target_speed(); } else { if ( Players[Player_num].flags & PLAYER_FLAGS_MATCH_TARGET ) Players[Player_num].flags &= ~PLAYER_FLAGS_MATCH_TARGET; // no more target matching. } hud_lock_reset(); if ( Player_ai->target_objnum != -1) { if ( Objects[Player_ai->target_objnum].type == OBJ_SHIP ) { hud_restore_subsystem_target(&Ships[Objects[Player_ai->target_objnum].instance]); } } // if this target is docked, then flash DOCKING on the hud for a couple of seconds hud_targetbox_end_flash(TBOX_FLASH_DOCKED); if ( Player_ai->target_objnum >= 0 ) { hud_maybe_flash_docking_text(&Objects[Player_ai->target_objnum]); } } else { if (Player_ai->current_target_distance < Player_ai->last_dist-0.01){ Player_ai->current_target_dist_trend = DECREASING; } else if (Player_ai->current_target_distance > Player_ai->last_dist+0.01){ Player_ai->current_target_dist_trend = INCREASING; } else { Player_ai->current_target_dist_trend = NO_CHANGE; } current_speed = Objects[Player_ai->target_objnum].phys_info.speed; if (current_speed < Player_ai->last_speed-0.01){ Player_ai->current_target_speed_trend = DECREASING; } else if (current_speed > Player_ai->last_speed+0.01) { Player_ai->current_target_speed_trend = INCREASING; } else { Player_ai->current_target_speed_trend = NO_CHANGE; } if ( Players[Player_num].flags & PLAYER_FLAGS_AUTO_MATCH_SPEED ) { if ( !(Players[Player_num].flags & PLAYER_FLAGS_MATCH_TARGET) ) { // player_match_target_speed("", "", XSTR("Matching target speed",-1)); player_match_target_speed(); } } } Player_ai->last_dist = Player_ai->current_target_distance; Player_ai->last_speed = current_speed; Player_ai->last_target = Player_ai->target_objnum; Player_ai->last_subsys_target = Player_ai->targeted_subsys; } // --------------------------------------------------------------------- // hud_draw_offscreen_indicator() // // draws the offscreen target indicator // void hud_draw_offscreen_indicator(vertex* target_point, vector *tpos, float distance) { char buf[32]; int w = 0, h = 0; int on_top, on_right, on_left, on_bottom; float target_x, target_y; float xpos,ypos; // points to draw triangles float x1=0.0f; float y1=0.0f; float x2=0.0f; float y2=0.0f; float x3=0.0f; float y3=0.0f; float x4=0.0f; float y4=0.0f; float x5=0.0f; float y5=0.0f; float x6=0.0f; float y6=0.0f; vector targ_to_player; float dist_behind; float triangle_sep; float half_gauge_length, half_triangle_sep; int in_front; // calculate the dot product between the players forward vector and the vector connecting // the player to the target. Normalize targ_to_player since we want the dot product // to range between 0 -> 1. vm_vec_sub(&targ_to_player, &Player_obj->pos, tpos); vm_vec_normalize(&targ_to_player); dist_behind = vm_vec_dot(&Player_obj->orient.vec.fvec, &targ_to_player); in_front = 0; if (dist_behind < 0) { // still in front of player, but not in view in_front = 1; dist_behind = dist_behind + 1.0f; if (dist_behind > 0.2 ){ triangle_sep = ( dist_behind ) * Max_front_seperation[gr_screen.res]; } else { triangle_sep = 0.0f; } } else { triangle_sep = dist_behind * Max_offscreen_tri_seperation[gr_screen.res] + Max_offscreen_tri_seperation[gr_screen.res]; } if ( triangle_sep > Max_offscreen_tri_seperation[gr_screen.res] + Max_front_seperation[gr_screen.res]){ triangle_sep = Max_offscreen_tri_seperation[gr_screen.res] + Max_front_seperation[gr_screen.res]; } // calculate these values only once, since it will be used in several places half_triangle_sep = 0.5f * triangle_sep; half_gauge_length = half_triangle_sep + Offscreen_tri_base[gr_screen.res]; target_x = target_point->x; target_y = target_point->y; // We need to find the screen (x,y) for where to draw the offscreen indicator // // The best way I've found is to draw a line from the eye_pos to the target, and // then use clip_line() to find the screen (x,y) for where the line hits the edge // of the screen. // // The weird thing about clip_line() is that is flips around the two verticies, // so I use eye_vertex->sx and eye_vertex->sy for the off-screen indicator (x,y) // vertex *eye_vertex = NULL; vertex real_eye_vertex; eye_vertex = &real_eye_vertex; // this is needed since clip line takes a **vertex vector eye_pos; vm_vec_add( &eye_pos, &Eye_position, &View_matrix.vec.fvec); g3_rotate_vertex(eye_vertex, &eye_pos); ubyte codes_or; codes_or = (ubyte)(target_point->codes | eye_vertex->codes); clip_line(&target_point,&eye_vertex,codes_or,0); if (!(target_point->flags&PF_PROJECTED)) g3_project_vertex(target_point); if (!(eye_vertex->flags&PF_PROJECTED)) g3_project_vertex(eye_vertex); if (eye_vertex->flags&PF_OVERFLOW) { Int3(); // This is unlikely to happen, but can if a clip goes through the player's eye. Player_ai->target_objnum = -1; return; } if (target_point->flags & PF_TEMP_POINT) free_temp_point(target_point); if (eye_vertex->flags & PF_TEMP_POINT) free_temp_point(eye_vertex); xpos = eye_vertex->sx; ypos = eye_vertex->sy; on_left = on_right = on_top = on_bottom = 0; xpos = (xpos<1) ? 0 : xpos; ypos = (ypos<1) ? 0 : ypos; if ( xpos <= gr_screen.clip_left ) { xpos = i2fl(gr_screen.clip_left); on_left = TRUE; if ( ypos < (half_gauge_length - gr_screen.clip_top) ) ypos = half_gauge_length; if ( ypos > (gr_screen.clip_bottom - half_gauge_length) ) ypos = gr_screen.clip_bottom - half_gauge_length; } else if ( xpos >= gr_screen.clip_right) { xpos = i2fl(gr_screen.clip_right); on_right = TRUE; if ( ypos < (half_gauge_length - gr_screen.clip_top) ) ypos = half_gauge_length; if ( ypos > (gr_screen.clip_bottom - half_gauge_length) ) ypos = gr_screen.clip_bottom - half_gauge_length; } else if ( ypos <= gr_screen.clip_top ) { ypos = i2fl(gr_screen.clip_top); on_top = TRUE; if ( xpos < ( half_gauge_length - gr_screen.clip_left) ) xpos = half_gauge_length; if ( xpos > (gr_screen.clip_right - half_gauge_length) ) xpos = gr_screen.clip_right - half_gauge_length; } else if ( ypos >= gr_screen.clip_bottom ) { ypos = i2fl(gr_screen.clip_bottom); on_bottom = TRUE; if ( xpos < ( half_gauge_length - gr_screen.clip_left) ) xpos = half_gauge_length; if ( xpos > (gr_screen.clip_right - half_gauge_length) ) xpos = gr_screen.clip_right - half_gauge_length; } else { Int3(); return; } // The offscreen target triangles are drawn according the the diagram below // // // // x3 x3 // / | | \. // / | | \. // x1___x2 x2___x1 // | | // ......|...........|...............(xpos,ypos) // | | // x4___x5 x5___x4 // \ | | / // \ | | / // x6 x6 // // xpos = (float)floor(xpos); ypos = (float)floor(ypos); if ( hud_gauge_active(HUD_OFFSCREEN_RANGE) && (distance > 0) ) { sprintf(buf,"%d",fl2i(distance+0.5f)); hud_num_make_mono(buf); gr_get_string_size(&w, &h, buf); } else { buf[0] = 0; } if (on_right) { x1 = x4 = (xpos+2); x2 = x3 = x5 = x6 = x1 - Offscreen_tri_height[gr_screen.res]; y1 = y2 = ypos - half_triangle_sep; y3 = y2 - Offscreen_tri_base[gr_screen.res]; y4 = y5 = ypos + half_triangle_sep; y6 = y5 + Offscreen_tri_base[gr_screen.res]; if ( buf[0] ) { gr_string( fl2i(xpos - w - 10), fl2i(ypos - h/2.0f+0.5f), buf); } } else if (on_left) { x1 = x4 = (xpos-1); x2 = x3 = x5 = x6 = x1 + Offscreen_tri_height[gr_screen.res]; y1 = y2 = ypos - half_triangle_sep; y3 = y2 - Offscreen_tri_base[gr_screen.res]; y4 = y5 = ypos + half_triangle_sep; y6 = y5 + Offscreen_tri_base[gr_screen.res]; if ( buf[0] ) { gr_string(fl2i(xpos + 10), fl2i(ypos - h/2.0f+0.5f), buf); } } else if (on_top) { y1 = y4 = (ypos-1); y2 = y3 = y5 = y6 = y1 + Offscreen_tri_height[gr_screen.res]; x1 = x2 = xpos - half_triangle_sep; x3 = x2 - Offscreen_tri_base[gr_screen.res]; x4 = x5 = xpos + half_triangle_sep; x6 = x5 + Offscreen_tri_base[gr_screen.res]; if ( buf[0] ) { gr_string(fl2i(xpos - w/2.0f+0.5f), fl2i(ypos+10), buf); } } else if (on_bottom) { y1 = y4 = (ypos+2); y2 = y3 = y5 = y6 = y1 - Offscreen_tri_height[gr_screen.res]; x1 = x2 = xpos - half_triangle_sep; x3 = x2 - Offscreen_tri_base[gr_screen.res]; x4 = x5 = xpos + half_triangle_sep; x6 = x5 + Offscreen_tri_base[gr_screen.res]; if ( buf[0] ) { gr_string(fl2i(xpos - w/2.0f+0.5f), fl2i(ypos-h-10), buf); } } hud_tri(x3,y3,x2,y2,x1,y1); hud_tri(x4,y4,x5,y5,x6,y6); if (on_right || on_bottom){ gr_line(fl2i(x2),fl2i(y2),fl2i(x5),fl2i(y5)); } else if (on_left) { gr_line(fl2i(x2-1),fl2i(y2),fl2i(x5-1),fl2i(y5)); } else { gr_line(fl2i(x2),fl2i(y2-1),fl2i(x5),fl2i(y5-1)); } } // Render the HUD afterburner energy gauge void hud_show_afterburner_gauge() { float percent_left; int clip_w,w,h; // if ( Energy_bar_gauges.first_frame == -1 ){ // return; // } Assert(Player_ship); if ( !(Player_ship->pod_weapon == TWT_SLAM) ) { // Goober5000 - instead of drawing an empty burner gauge, don't draw the gauge at all return; //percent_left = 0.0f; } else { percent_left = Player_ship->afterburner_fuel/Player_ship->afterburner_fuel_capacity; //Ship_info[Player_ship->ship_info_index].afterburner_fuel_capacity; } clip_w = fl2i( (1.0f - percent_left) * Aburn_coords[gr_screen.res][3] + 0.5f ); bm_get_info(Energy_bar_gauges.first_frame,&w,&h); //if ( clip_h > 0) { GR_AABITMAP_EX(Energy_bar_gauges.first_frame, Aburn_coords[gr_screen.res][0], Aburn_coords[gr_screen.res][1],w,clip_w,0,0); //} //if ( clip_h <= Aburn_coords[gr_screen.res][3] ) { // GR_AABITMAP_EX(Energy_bar_gauges.first_frame+1, Aburn_coords[gr_screen.res][0], Aburn_coords[gr_screen.res][1]+clip_w,w,h-clip_w,0,clip_w); //} GR_AABITMAP_EX(Energy_bar_gauges.first_frame+3, Aburn_coords[gr_screen.res][0], Aburn_coords[gr_screen.res][1], w-clip_w,h,clip_w, 0); } void hud_show_pod_gauge() { float percent_left; int clip_w,w,h; if ( Energy_bar_gauges.first_frame == -1 ){ return; } //if (Player_ship->flags2 Assert(Player_ship); if ( !(Player_ship->flags2 & SF2_POD_INSTALLED) ) { // instead of drawing an empty burner gauge, don't draw the gauge at all return; //percent_left = 0.0f; // don't display gauge if solid booster rocket installed } else if (Player_ship->pod_weapon == TWT_BOOST_POD) { return; // don't display if ship has got sweet turbocharger fitted. } else if (Player_ship->pod_weapon == TWT_TURBOCHARGER) { return; } else if (Player_ship->pod_weapon == TWT_SLAM) { return; } else { percent_left = Player_ship->pod_energy/Player_ship->pod_energy_capacity; } if ( percent_left > 1 ) { percent_left = 1.0f; } clip_w = fl2i( (1.0f - percent_left) * Aburn_coords[gr_screen.res][3] + 0.5f ); //bm_get_info(Energy_bar_gauges.first_frame,&w,&h); bm_get_info(Energy_bar_gauges.first_frame+2,&w,&h); GR_AABITMAP_EX(Energy_bar_gauges.first_frame, Aburn_coords[gr_screen.res][0], Aburn_coords[gr_screen.res][1],w,clip_w,0,0); //if ( clip_h <= Aburn_coords[gr_screen.res][3] ) { // GR_AABITMAP_EX(Energy_bar_gauges.first_frame+1, Aburn_coords[gr_screen.res][0], Aburn_coords[gr_screen.res][1]+clip_h,w,h-clip_h,0,clip_h); //} GR_AABITMAP_EX(Energy_bar_gauges.first_frame+3, Aburn_coords[gr_screen.res][0], Aburn_coords[gr_screen.res][1], w-clip_w,h,clip_w, 0); } // Render the player weapon energy on the HUD void hud_show_weapon_energy_gauge() { float percent_left; int clip_w, i, w, h; if ( Energy_bar_gauges.first_frame == -1 ) { return; } if ( Player_ship->weapons.num_primary_banks <= 0 ) { return; } // also leave if no energy can be stored for weapons - Goober5000 if (!ship_has_energy_weapons(Player_ship)) return; percent_left = Player_ship->weapon_energy/Ship_info[Player_ship->ship_info_index].max_weapon_reserve; if ( percent_left > 1 ) { percent_left = 1.0f; } if ( percent_left <= 0.3 ) { char buf[32]; if ( percent_left < 0.1 ) { gr_set_color_fast(&Color_bright_red); } sprintf(buf,XSTR( "%d%%", 326), fl2i(percent_left*100+0.5f)); hud_num_make_mono(buf); //gr_string(Weapon_energy_text_coords[gr_screen.res][0], Weapon_energy_text_coords[gr_screen.res][1], buf); } hud_set_gauge_color(HUD_WEAPONS_ENERGY); for ( i = 0; i < Player_ship->weapons.num_primary_banks; i++ ) { if ( !timestamp_elapsed(Weapon_flash_info.flash_duration[i]) ) { if ( Weapon_flash_info.is_bright & (1<<i) ) { // hud_set_bright_color(); hud_set_gauge_color(HUD_WEAPONS_ENERGY, HUD_C_BRIGHT); break; } } } clip_w = fl2i( (1.0f - percent_left) * Wenergy_coords[gr_screen.res][3] + 0.5f ); bm_get_info(Energy_bar_gauges.first_frame+2,&w,&h); //if ( clip_w > 0 ) { GR_AABITMAP_EX(Energy_bar_gauges.first_frame+2, Wenergy_coords[gr_screen.res][0], Wenergy_coords[gr_screen.res][1], w, h,0,0); // w, clip+h //} // if ( clip_w <= Wenergy_coords[gr_screen.res][3] ) { //GR_AABITMAP_EX(Energy_bar_gauges.first_frame+3, Wenergy_coords[gr_screen.res][0], (Wenergy_coords[gr_screen.res][1]+20), w+clip_w,h,-clip_w, 0); //GR_AABITMAP_EX(Energy_bar_gauges.first_frame+3, Wenergy_coords[gr_screen.res][0], Wenergy_coords[gr_screen.res][1], w+clip_w,h,clip_w, 0); // old //GR_AABITMAP_EX(Energy_bar_gauges.first_frame+3, Wenergy_coords[gr_screen.res][0], Wenergy_coords[gr_screen.res][1] + clip_h, w,h-clip_h,0,clip_h); // drains left to right GR_AABITMAP_EX(Energy_bar_gauges.first_frame+3, Wenergy_coords[gr_screen.res][0]+clip_w, Wenergy_coords[gr_screen.res][1], w-clip_w,h,clip_w, 0); //GR_AABITMAP_EX(Energy_bar_gauges.first_frame+3, Wenergy_coords[gr_screen.res][0], Wenergy_coords[gr_screen.res][1], w-clip_w,h,clip_w, 0); //} // hud_set_default_color(); } // -------------------------------------------------------------------------------------- // hud_show_target_triangle_indicator() // // Draw the solid triangle that orbits the reticle and points to the nearest target // void hud_show_target_triangle_indicator(vertex *projected_v) { float x3,y3,x4,y4; float xpos,ypos,ang; if ( Player_ai->target_objnum == -1) return; object *targetp = &Objects[Player_ai->target_objnum]; // draw the targeting triangle that orbits the outside of the outer circle of the reticle if ((hud_gauge_active(HUD_TARGET_TRIANGLE)) && !Player->target_is_dying && !Target_in_reticle) { if ( hud_gauge_maybe_flash(HUD_TARGET_TRIANGLE) == 1 ) { return; } hud_set_iff_color(targetp, 1); ang = atan2_safe(projected_v->y,projected_v->x); xpos = Hud_reticle_center[gr_screen.res][0] + (float)cos(ang)*(Outer_circle_radius[gr_screen.res]+4); ypos = Hud_reticle_center[gr_screen.res][1] - (float)sin(ang)*(Outer_circle_radius[gr_screen.res]+4); xpos += HUD_offset_x; ypos += HUD_offset_y; x3 = xpos - Target_triangle_base[gr_screen.res] * (float)sin(-ang); y3 = ypos + Target_triangle_base[gr_screen.res] * (float)cos(-ang); x4 = xpos + Target_triangle_base[gr_screen.res] * (float)sin(-ang); y4 = ypos - Target_triangle_base[gr_screen.res] * (float)cos(-ang); xpos += Target_triangle_height[gr_screen.res] * (float)cos(ang); ypos -= Target_triangle_height[gr_screen.res] * (float)sin(ang); hud_tri(xpos,ypos,x3,y3,x4,y4); } } // called from hud_show_weapons() to plot out the secondary weapon name and ammo void hud_show_secondary_weapon(int count, ship_weapon *sw, int dual_fire) { char ammo_str[32]; char weapon_name[NAME_LENGTH + 10]; int i, w, h, np; weapon_info *wip; np = 1; if ( sw->num_primary_banks == 2 ) { np = 0; } for ( i = 0; i < count; i++ ) { hud_maybe_flash_weapon(sw->num_primary_banks+i); wip = &Weapon_info[sw->secondary_bank_weapons[i]]; // HACK - make Cluster Bomb fit on the HUD. if(!stricmp(wip->name,"cluster bomb")){ strcpy(weapon_name, NOX("Cluster")); } else { strcpy(weapon_name, wip->name); } // get rid of # end_string_at_first_hash_symbol(weapon_name); if ( sw->current_secondary_bank == i ) { emp_hud_printf(Weapon_sunlinked_x[gr_screen.res], Weapon_secondary_y[gr_screen.res][i] - np*12, EG_NULL, "%c", Lcl_special_chars + 2); if ( dual_fire ) { emp_hud_printf(Weapon_slinked_x[gr_screen.res], Weapon_secondary_y[gr_screen.res][i] - np*12, EG_NULL, "%c", Lcl_special_chars + 2); } emp_hud_string(Weapon_secondary_name_x[gr_screen.res], Weapon_secondary_y[gr_screen.res][i] - np*12, i ? EG_WEAPON_S1 : EG_WEAPON_S2, weapon_name); if ( (sw->secondary_bank_ammo[i] > 0) && (sw->current_secondary_bank >= 0) ) { int ms_till_fire = timestamp_until(sw->next_secondary_fire_stamp[sw->current_secondary_bank]); if ( (ms_till_fire >= 500) && ((wip->fire_wait >= 1 ) || (ms_till_fire > wip->fire_wait*1000)) ) { emp_hud_printf(Weapon_secondary_reload_x[gr_screen.res], Weapon_secondary_y[gr_screen.res][i] - np*12, EG_NULL, "%d", fl2i(ms_till_fire/1000.0f +0.5f)); } } } else { emp_hud_string(Weapon_secondary_name_x[gr_screen.res], Weapon_secondary_y[gr_screen.res][i] - np*12, i ? EG_WEAPON_S1 : EG_WEAPON_S2, weapon_name); } int ammo=sw->secondary_bank_ammo[i]; /*if ((Tertiary_weapon_info[Player_ship->tertiary_weapon_info_idx].type == TWT_AMMO_POD) && (i == Player_ship->ammopod_current_secondary)) { ammo+=Player_ship->ammopod_current_ammo; }*/ // print out the ammo right justified sprintf(ammo_str, "%d", ammo); hud_num_make_mono(ammo_str); gr_get_string_size(&w, &h, ammo_str); emp_hud_string(Weapon_secondary_ammo_x[gr_screen.res] - w, Weapon_secondary_y[gr_screen.res][i] - np*12, EG_NULL, ammo_str); hud_set_gauge_color(HUD_WEAPONS_GAUGE); } } // called from hud_show_weapons() to plot out the primary weapon ammo - Goober5000 void hud_show_primary_weapon_ammo(int count, ship_weapon *sw) { char ammo_str[32]; int i, w, h; for ( i = 0; i < count; i++ ) { // for all ballistic weapons if (Weapon_info[sw->primary_bank_weapons[i]].wi_flags2 & WIF2_BALLISTIC) { // print out the ammo right justified sprintf(ammo_str, "%d", sw->primary_bank_ammo[i]); // get rid of # end_string_at_first_hash_symbol(ammo_str); hud_num_make_mono(ammo_str); gr_get_string_size(&w, &h, ammo_str); emp_hud_string(Weapon_primary_ammo_x[gr_screen.res] - w, Weapon_primary_y[gr_screen.res][i], EG_NULL, ammo_str); hud_set_gauge_color(HUD_WEAPONS_GAUGE); } } } // start the weapon line (on the HUD) flashing void hud_start_flash_weapon(int index) { if ( index >= MAX_WEAPON_FLASH_LINES ) { Int3(); // Get Alan return; } if ( timestamp_elapsed(Weapon_flash_info.flash_duration[index]) ) { Weapon_flash_info.flash_next[index] = timestamp(TBOX_FLASH_INTERVAL); Weapon_flash_info.is_bright &= ~(1<<index); } Weapon_flash_info.flash_duration[index] = timestamp(TBOX_FLASH_DURATION); } // maybe change the text color for the weapon line indicated by index void hud_maybe_flash_weapon(int index) { if ( index >= MAX_WEAPON_FLASH_LINES ) { Int3(); // Get Alan return; } // hud_set_default_color(); hud_set_gauge_color(HUD_WEAPONS_GAUGE); if ( !timestamp_elapsed(Weapon_flash_info.flash_duration[index]) ) { if ( timestamp_elapsed(Weapon_flash_info.flash_next[index]) ) { Weapon_flash_info.flash_next[index] = timestamp(TBOX_FLASH_INTERVAL); Weapon_flash_info.is_bright ^= (1<<index); } if ( Weapon_flash_info.is_bright & (1<<index) ) { hud_set_gauge_color(HUD_WEAPONS_GAUGE, HUD_C_BRIGHT); // hud_set_bright_color(); } else { hud_set_gauge_color(HUD_WEAPONS_GAUGE, HUD_C_DIM); // hud_set_dim_color(); } } } // render the coutermeasure HUD gauge void hud_show_cmeasure_gague() { /*if ( Cmeasure_gauge.first_frame == -1 ) { Int3(); // failed to load coutermeasure gauge background return; }*/ // hud_set_default_color(); hud_set_gauge_color(HUD_THROTTLE_GAUGE); //HUD_CMEASURE_GAUGE part of top console // blit the background //GR_AABITMAP(Cmeasure_gauge.first_frame, Cm_coords[gr_screen.res][0], Cm_coords[gr_screen.res][1]); // blit text /*gr_string(Cm_text_coords[gr_screen.res][0], Cm_text_coords[gr_screen.res][1], XSTR( "cm.", 327)); if ( !Player_ship ) { Int3(); // player ship doesn't exist? return; }*/ gr_printf(Cm_text_val_coords[gr_screen.res][0], Cm_text_val_coords[gr_screen.res][1], NOX("%02d"),Player_ship->cmeasure_count); } // ------------------------------------------------------------------ // hud_show_weapons() // // Show the player's primary and secondary weapons, along with ammo and % energy // void hud_show_weapons() { ship_weapon *sw; int ship_is_ballistic; int np, ns; // np == num primary, ns == num secondary char name[NAME_LENGTH]; if(Player_obj->type == OBJ_OBSERVER) return; Assert(Player_obj->type == OBJ_SHIP); Assert(Player_obj->instance >= 0 && Player_obj->instance < MAX_SHIPS); sw = &Ships[Player_obj->instance].weapons; ship_is_ballistic = (Ship_info[Ships[Player_obj->instance].ship_info_index].flags & SIF_BALLISTIC_PRIMARIES); np = sw->num_primary_banks; ns = sw->num_secondary_banks; // NOTE: I hate to hard-code numbers, but there is no clean way to organize these coords... they // are all over the place. UGLY. // BAH. You're a moron, above guy. :) hud_set_gauge_color(HUD_WEAPONS_GAUGE); // draw top of primary display // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][0].first_frame, Weapon_gauge_primary_coords[ballistic_hud_index][gr_screen.res][0][0], Weapon_gauge_primary_coords[ballistic_hud_index][gr_screen.res][0][1]); emp_hud_string(Weapon_title_coords[ballistic_hud_index][gr_screen.res][0], Weapon_title_coords[ballistic_hud_index][gr_screen.res][1], EG_WEAPON_TITLE, XSTR( "weapons", 328)); if (np == 0) { // draw bottom of border // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][2].first_frame, Weapon_gauge_primary_coords[ballistic_hud_index][gr_screen.res][1][0], Weapon_gauge_primary_coords[ballistic_hud_index][gr_screen.res][1][1]); emp_hud_string(Weapon_pname_coords[gr_screen.res][0][0], Weapon_pname_coords[gr_screen.res][0][1], EG_WEAPON_P1, XSTR( "<none>", 329)); np = 1; } else if (np == 1) { // draw bottom of border // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][2].first_frame, Weapon_gauge_primary_coords[ballistic_hud_index][gr_screen.res][1][0], Weapon_gauge_primary_coords[ballistic_hud_index][gr_screen.res][1][1]); strcpy(name, Weapon_info[sw->primary_bank_weapons[0]].name); if (Lcl_gr) { lcl_translate_wep_name(name); } // maybe modify name here to fit if ( hud_gauge_maybe_flash(HUD_WEAPONS_GAUGE) == 1 ) { // hud_set_bright_color(); hud_set_gauge_color(HUD_WEAPONS_GAUGE, HUD_C_BRIGHT); } else { hud_maybe_flash_weapon(0); } emp_hud_printf(Weapon_plink_coords[gr_screen.res][0][0], Weapon_plink_coords[gr_screen.res][0][1], EG_NULL, "%c", Lcl_special_chars + 2); emp_hud_printf(Weapon_pname_coords[gr_screen.res][0][0], Weapon_pname_coords[gr_screen.res][0][1], EG_WEAPON_P2, "%s", name); // check ballistic - Goober5000 if (ship_is_ballistic) { hud_show_primary_weapon_ammo(1, sw); } } else if (np == 2) { // draw border to accomodate second primary weapon // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][1].first_frame, Weapon_gauge_primary_coords[ballistic_hud_index][gr_screen.res][1][0], Weapon_gauge_primary_coords[ballistic_hud_index][gr_screen.res][1][1]); // draw bottom of border // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][2].first_frame, Weapon_gauge_primary_coords[ballistic_hud_index][gr_screen.res][2][0], Weapon_gauge_primary_coords[ballistic_hud_index][gr_screen.res][2][1]); strcpy(name, Weapon_info[sw->primary_bank_weapons[0]].name); if (Lcl_gr) { lcl_translate_wep_name(name); } // maybe modify name here to fit if ( hud_gauge_maybe_flash(HUD_WEAPONS_GAUGE) == 1 ) { // hud_set_bright_color(); hud_set_gauge_color(HUD_WEAPONS_GAUGE, HUD_C_BRIGHT); } else { hud_maybe_flash_weapon(0); } if ( (sw->current_primary_bank == 0) || (Player_ship->flags & SF_PRIMARY_LINKED) ) { emp_hud_printf(Weapon_plink_coords[gr_screen.res][0][0], Weapon_plink_coords[gr_screen.res][0][1], EG_NULL, "%c", Lcl_special_chars + 2); } emp_hud_printf(Weapon_pname_coords[gr_screen.res][0][0], Weapon_pname_coords[gr_screen.res][0][1], EG_WEAPON_P1, "%s", name); strcpy(name, Weapon_info[sw->primary_bank_weapons[1]].name); if (Lcl_gr) { lcl_translate_wep_name(name); } // maybe modify name here to fit if ( hud_gauge_maybe_flash(HUD_WEAPONS_GAUGE) == 1 ) { // hud_set_bright_color(); hud_set_gauge_color(HUD_WEAPONS_GAUGE, HUD_C_BRIGHT); } else { hud_maybe_flash_weapon(1); } if ( sw->current_primary_bank == 1 || (Player_ship->flags & SF_PRIMARY_LINKED) ) { emp_hud_printf(Weapon_plink_coords[gr_screen.res][1][0], Weapon_plink_coords[gr_screen.res][1][1], EG_NULL, "%c", Lcl_special_chars + 2); } emp_hud_printf(Weapon_pname_coords[gr_screen.res][1][0], Weapon_pname_coords[gr_screen.res][1][1], EG_WEAPON_P2, "%s", name); np = 0; // check ballistic - Goober5000 if (ship_is_ballistic) { hud_show_primary_weapon_ammo(2, sw); } } else // Goober5000 - too many primary weapons on player ship { Int3(); // can't happen - get Alan return; } hud_set_gauge_color(HUD_WEAPONS_GAUGE); if (ns == 0) { // draw the bottom of the secondary weapons // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][4].first_frame, Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][0][0], Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][0][1] - 12*np - 1); emp_hud_string(Weapon_pname_coords[gr_screen.res][0][0], Weapon_secondary_y[gr_screen.res][0] - np*12, EG_WEAPON_S1, XSTR( "<none>", 329)); } else if (ns == 1) { // draw the bottom of the secondary weapons // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][4].first_frame, Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][1][0], Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][1][1] - 12*np - 1); hud_show_secondary_weapon(1, sw, Player_ship->flags & SF_SECONDARY_DUAL_FIRE); } else if (ns == 2) { // draw the middle border, only present when there are 2 or more secondaries // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][3].first_frame, Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][2][0], Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][2][1] - np*12); // draw the bottom of the secondary weapons // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][4].first_frame, Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][3][0], Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][3][1] - 12*np); hud_show_secondary_weapon(2, sw, Player_ship->flags & SF_SECONDARY_DUAL_FIRE); } else if (ns == 3) { // draw the middle border, only present when there are 2 or more secondaries // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][3].first_frame, Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][2][0], Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][2][1] - np*12); // draw the bottm border, only present when there are 3 secondaries // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][3].first_frame, Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][3][0], Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][3][1] - np*12); // draw the bottom of the secondary weapons // GR_AABITMAP(Weapon_gauges[ballistic_hud_index][4].first_frame, Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][4][0], Weapon_gauge_secondary_coords[ballistic_hud_index][gr_screen.res][4][1] - 12*np); hud_show_secondary_weapon(3, sw, Player_ship->flags & SF_SECONDARY_DUAL_FIRE); } else // Goober5000 - too many player secondaries { Int3(); // can't happen - get Alan return; } } // check if targeting is possible based on sensors strength int hud_sensors_ok(ship *sp, int show_msg) { float sensors_str; // If playing on lowest skill level, sensors don't affect targeting // If dead, still allow player to target, despite any subsystem damage // If i'm a multiplayer observer, allow me to target #ifndef NO_NETWORK if ( (Game_skill_level == 0) || (Game_mode & GM_DEAD) || ((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_OBSERVER)) ) { #else if ( (Game_skill_level == 0) || (Game_mode & GM_DEAD) ) { #endif return 1; } // if the ship is currently being affected by EMP if(emp_active_local()){ return 0; } // ensure targeting functions are not disabled through damage sensors_str = ship_get_subsystem_strength( sp, SUBSYSTEM_SENSORS ); if ( (sensors_str < MIN_SENSOR_STR_TO_TARGET) || (ship_subsys_disrupted(sp, SUBSYSTEM_SENSORS)) ) { if ( show_msg ) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "Targeting is disabled due to sensors damage", 330)); snd_play(&Snds[SND_TARGET_FAIL]); } return 0; } else { return 1; } } int hud_communications_state(ship *sp, int show_msg) { float str; int comm_state = COMM_OK; // If playing on the lowest skill level, communications always ok // If dead, still allow player to communicate, despite any subsystem damage if ( Game_skill_level == 0 || (Game_mode & GM_DEAD) ) { return comm_state; } str = ship_get_subsystem_strength( sp, SUBSYSTEM_COMMUNICATION ); // str = 1.0f; // DEBUG CODE! MK, change, 11/12/97, comm system could be taken out by one laser, too frustrating. // Change this back when comm systems have been better placed. if ( (str <= 0.01) || ship_subsys_disrupted(sp, SUBSYSTEM_COMMUNICATION) ) { if ( show_msg ) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "Messaging is restricted due to communications damage", 331)); } comm_state = COMM_DESTROYED; } else if ( str < MIN_COMM_STR_TO_MESSAGE ) { comm_state = COMM_DAMAGED; } return comm_state; } // target the next or previous hostile/friendly ship void hud_target_next_list(int hostile, int next_flag) { object *A, *min_obj, *max_obj, *nearest_obj; ship *shipp; ship_obj *so; // vector target_vec; float cur_dist, min_dist, max_dist, new_dist, nearest_dist, diff; int timestamp_val, valid_team; if ( hostile ) { timestamp_val = Tl_hostile_reset_timestamp; Tl_hostile_reset_timestamp = timestamp(TL_RESET); valid_team = opposing_team_mask(Player_ship->team); } else { timestamp_val = Tl_friendly_reset_timestamp; Tl_friendly_reset_timestamp = timestamp(TL_RESET); valid_team = Player_ship->team; } // If no target is selected, then simply target the closest ship if ( Player_ai->target_objnum == -1 || timestamp_elapsed(timestamp_val) ) { hud_target_closest(valid_team); return; } cur_dist = hud_find_target_distance(&Objects[Player_ai->target_objnum],Player_obj); min_obj = max_obj = nearest_obj = NULL; min_dist = 1e20f; max_dist = 0.0f; if ( next_flag ) { nearest_dist = 1e20f; } else { nearest_dist = 0.0f; } for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information if ( (A == Player_obj) || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ) continue; // no target if cloaked or decoy if ( shipp->flags2 & SF2_NO_RADAR) { continue; } // choose from the correct team if ( !hud_team_matches_filter(valid_team, shipp->team) ) { #ifndef NO_NETWORK // if we're in multiplayer dogfight, ignore this if(!((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_DOGFIGHT))) #endif { continue; } } // always ignore navbuoys and cargo if ( Ship_info[shipp->ship_info_index].flags & (SIF_CARGO | SIF_NAVBUOY) ) { continue; } // don't use object if it is already a target if ( OBJ_INDEX(A) == Player_ai->target_objnum ) { continue; } if(hud_target_invalid_awacs(A)){ continue; } new_dist = hud_find_target_distance(A,Player_obj); if (new_dist <= min_dist) { min_dist = new_dist; min_obj = A; } if (new_dist >= max_dist) { max_dist = new_dist; max_obj = A; } if ( next_flag ) { diff = new_dist - cur_dist; if ( diff > 0 ) { if ( diff < ( nearest_dist - cur_dist ) ) { nearest_dist = new_dist; nearest_obj = A; } } } else { diff = cur_dist - new_dist; if ( diff > 0 ) { if ( diff < ( cur_dist - nearest_dist ) ) { nearest_dist = new_dist; nearest_obj = A; } } } } if ( nearest_obj == NULL ) { if ( next_flag ) { if ( min_obj != NULL ) { nearest_obj = min_obj; } } else { if ( max_obj != NULL ) { nearest_obj = max_obj; } } } if (nearest_obj != NULL) { // set new target set_target_objnum( Player_ai, OBJ_INDEX(nearest_obj) ); // maybe set new turret subsystem hud_maybe_set_sorted_turret_subsys(&Ships[nearest_obj->instance]); hud_restore_subsystem_target(&Ships[nearest_obj->instance]); } else { snd_play( &Snds[SND_TARGET_FAIL], 0.0f ); } } // draw auto-target icon void hud_auto_target_icon() { int frame_offset; if ( Players[Player_num].flags & PLAYER_FLAGS_AUTO_TARGETING ) { frame_offset = 1; } else { frame_offset = 0; } // draw the box background hud_set_gauge_color(HUD_TARGET_MONITOR); // HUD_AUTO_TARGET part of C.M.D. //GR_AABITMAP(Toggle_gauge.first_frame+frame_offset, Toggle_target_gauge_coords[gr_screen.res][0], Toggle_target_gauge_coords[gr_screen.res][1]); // draw the text on top if (frame_offset == 1) { static color text_color; gr_init_alphacolor(&text_color, 0, 0, 0, Toggle_text_alpha); gr_set_color_fast(&text_color); } gr_string(Hud_toggle_coords[gr_screen.res][TOGGLE_TEXT_AUTOT][0], Hud_toggle_coords[gr_screen.res][TOGGLE_TEXT_AUTOT][1], XSTR("auto", 1463)); gr_string(Hud_toggle_coords[gr_screen.res][TOGGLE_TEXT_TARGET][0], Hud_toggle_coords[gr_screen.res][TOGGLE_TEXT_TARGET][1], XSTR("target", 1465)); } // draw auto-speed match icon void hud_auto_speed_match_icon() { int frame_offset; if ( Players[Player_num].flags & PLAYER_FLAGS_AUTO_MATCH_SPEED ) { frame_offset = 3; } else { frame_offset = 2; } hud_set_gauge_color(HUD_THROTTLE_GAUGE); //HUD_AUTO_SPEED part of top console //GR_AABITMAP(Toggle_gauge.first_frame+frame_offset, Toggle_speed_gauge_coords[gr_screen.res][0], Toggle_speed_gauge_coords[gr_screen.res][1]); // draw the text on top if (frame_offset == 3) { static color text_color; gr_init_alphacolor(&text_color, 0, 0, 0, Toggle_text_alpha); gr_set_color_fast(&text_color); } gr_string(Hud_toggle_coords[gr_screen.res][TOGGLE_TEXT_AUTOS][0], Hud_toggle_coords[gr_screen.res][TOGGLE_TEXT_AUTOS][1], XSTR("auto", 1463)); gr_string(Hud_toggle_coords[gr_screen.res][TOGGLE_TEXT_SPEED][0], Hud_toggle_coords[gr_screen.res][TOGGLE_TEXT_SPEED][1], XSTR("speed", 1464)); } // display the auto-targeting and auto-speed-matching icons on the HUD void hud_show_auto_icons() { int show_flag; /*if ( Toggle_gauge.first_frame == -1 ) return;*/ // don't draw auto icons if we have primitive sensors - Goober5000 if (Player_ship->flags2 & SF2_PRIMITIVE_SENSORS) return; // display auto target icon if ( hud_gauge_active(HUD_AUTO_TARGET) ) { show_flag=1; // is gauge configured as a popup? if ( hud_gauge_is_popup(HUD_AUTO_TARGET) ) { if ( !hud_gauge_popup_active(HUD_AUTO_TARGET) ) { show_flag=0; } } if ( show_flag ) { hud_auto_target_icon(); } } // display auto speed match icon if ( hud_gauge_active(HUD_AUTO_SPEED) ) { show_flag=1; // is gauge configured as a popup? if ( hud_gauge_is_popup(HUD_AUTO_SPEED) ) { if ( !hud_gauge_popup_active(HUD_AUTO_SPEED) ) { show_flag=0; } } if ( show_flag ) { hud_auto_speed_match_icon(); } } } // Set the player target to the closest friendly repair ship // input: goal_objnum => Try to find repair ship where aip->goal_objnum matches this // output: 1 => A repair ship was targeted // 0 => No targeting change int hud_target_closest_repair_ship(int goal_objnum) { object *A; object *nearest_obj=&obj_used_list; ship *shipp; ship_obj *so; float min_distance=1e20f; float new_distance=0.0f; int rval=0; for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information // ignore all ships that aren't repair ships if ( !(Ship_info[shipp->ship_info_index].flags & SIF_SUPPORT) ) { continue; } if ( (A == Player_obj) || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ) continue; // no target if cloaked or decoy if ( Ships[A->instance].flags2 & SF2_NO_RADAR) { continue; } // only consider friendly ships if ( !hud_team_matches_filter(Player_ship->team, shipp->team)) { #ifndef NO_NETWORK // if we're in multiplayer dogfight, ignore this if(!((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_DOGFIGHT))) #endif { continue; } } if(hud_target_invalid_awacs(A)){ continue; } if ( goal_objnum >= 0 ) { if ( Ai_info[shipp->ai_index].goal_objnum != goal_objnum ) { continue; } } new_distance = hud_find_target_distance(A,Player_obj); if (new_distance <= min_distance) { min_distance=new_distance; nearest_obj = A; } } if (nearest_obj != &obj_used_list) { set_target_objnum( Player_ai, OBJ_INDEX(nearest_obj) ); hud_restore_subsystem_target(&Ships[nearest_obj->instance]); rval=1; } else { // inform player how to get a support ship if ( goal_objnum == -1 ) { HUD_sourced_printf(HUD_SOURCE_HIDDEN, XSTR( "No support ships in area. Use messaging to call one in.", 332)); } rval=0; } return rval; } void hud_target_toggle_hidden_from_sensors() { if ( TARGET_SHIP_IGNORE_FLAGS & SF_HIDDEN_FROM_SENSORS ) { TARGET_SHIP_IGNORE_FLAGS &= ~SF_HIDDEN_FROM_SENSORS; HUD_sourced_printf(HUD_SOURCE_HIDDEN, NOX("Target hiding from sensors disabled")); } else { TARGET_SHIP_IGNORE_FLAGS |= SF_HIDDEN_FROM_SENSORS; HUD_sourced_printf(HUD_SOURCE_HIDDEN, NOX("Target hiding from sensors enabled")); } } // target the closest uninspected object void hud_target_closest_uninspected_object() { object *A, *nearest_obj = NULL; ship *shipp; ship_obj *so; float min_distance = 1e20f; float new_distance = 0.0f; for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information if ( (A == Player_obj) || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ){ continue; } if(hud_target_invalid_awacs(A)){ continue; } // ignore all non-cargo carrying craft if ( !hud_target_ship_can_be_scanned(shipp) ) { continue; } new_distance = hud_find_target_distance(A,Player_obj); if (new_distance <= min_distance) { min_distance=new_distance; nearest_obj = A; } } if (nearest_obj != NULL) { set_target_objnum( Player_ai, OBJ_INDEX(nearest_obj) ); hud_restore_subsystem_target(&Ships[nearest_obj->instance]); } else { snd_play( &Snds[SND_TARGET_FAIL] ); } } // target the next or previous uninspected/unscanned object void hud_target_uninspected_object(int next_flag) { object *A, *min_obj, *max_obj, *nearest_obj; ship *shipp; ship_obj *so; float cur_dist, min_dist, max_dist, new_dist, nearest_dist, diff; // If no target is selected, then simply target the closest uninspected cargo if ( Player_ai->target_objnum == -1 || timestamp_elapsed(Target_next_uninspected_object_timestamp) ) { Target_next_uninspected_object_timestamp = timestamp(TL_RESET); hud_target_closest_uninspected_object(); return; } Target_next_uninspected_object_timestamp = timestamp(TL_RESET); cur_dist = hud_find_target_distance(&Objects[Player_ai->target_objnum], Player_obj); min_obj = max_obj = nearest_obj = NULL; min_dist = 1e20f; max_dist = 0.0f; if ( next_flag ) { nearest_dist = 1e20f; } else { nearest_dist = 0.0f; } for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) { A = &Objects[so->objnum]; shipp = &Ships[A->instance]; // get a pointer to the ship information if ( (A == Player_obj) || (shipp->flags & TARGET_SHIP_IGNORE_FLAGS) ) continue; // no target if cloaked or decoy if ( Ships[A->instance].flags2 & SF2_NO_RADAR) { continue; } // ignore all non-cargo carrying craft if ( !hud_target_ship_can_be_scanned(shipp) ) { continue; } // don't use object if it is already a target if ( OBJ_INDEX(A) == Player_ai->target_objnum ) { continue; } if(hud_target_invalid_awacs(A)){ continue; } new_dist = hud_find_target_distance(A, Player_obj); if (new_dist <= min_dist) { min_dist = new_dist; min_obj = A; } if (new_dist >= max_dist) { max_dist = new_dist; max_obj = A; } if ( next_flag ) { diff = new_dist - cur_dist; if ( diff > 0 ) { if ( diff < ( nearest_dist - cur_dist ) ) { nearest_dist = new_dist; nearest_obj = A; } } } else { diff = cur_dist - new_dist; if ( diff > 0 ) { if ( diff < ( cur_dist - nearest_dist ) ) { nearest_dist = new_dist; nearest_obj = A; } } } } if ( nearest_obj == NULL ) { if ( next_flag ) { if ( min_obj != NULL ) { nearest_obj = min_obj; } } else { if ( max_obj != NULL ) { nearest_obj = max_obj; } } } if (nearest_obj != NULL) { set_target_objnum( Player_ai, OBJ_INDEX(nearest_obj) ); hud_restore_subsystem_target(&Ships[nearest_obj->instance]); } else { snd_play( &Snds[SND_TARGET_FAIL] ); } } // ---------------------------------------------------------------- // // Target Last Transmission Sender code START // // ---------------------------------------------------------------- typedef struct transmit_target { int objnum; int objsig; } transmit_target; static int Transmit_target_next_slot = 0; static int Transmit_target_current_slot = -1; static int Transmit_target_reset_timer = timestamp(0); #define MAX_TRANSMIT_TARGETS 10 static transmit_target Transmit_target_list[MAX_TRANSMIT_TARGETS]; // called once per level to initialize the target last transmission sender list void hud_target_last_transmit_level_init() { int i; for ( i = 0; i < MAX_TRANSMIT_TARGETS; i++ ) { Transmit_target_list[i].objnum = -1; Transmit_target_list[i].objsig = -1; } Transmit_target_next_slot = 0; Transmit_target_current_slot = 0; Transmit_target_reset_timer = timestamp(0); } // internal function only.. used to find index for last recorded ship transmission int hud_target_last_transmit_newest() { int latest_slot; latest_slot = Transmit_target_next_slot - 1; if ( latest_slot < 0 ) { latest_slot = MAX_TRANSMIT_TARGETS - 1; } return latest_slot; } // called externally to set the player target to the last ship which sent a tranmission to the player void hud_target_last_transmit() { int i; if ( Transmit_target_current_slot < 0 ) { Transmit_target_current_slot = hud_target_last_transmit_newest(); } // If timed out, then simply target the last ship to transmit if ( timestamp_elapsed(Transmit_target_reset_timer) ) { Transmit_target_current_slot = hud_target_last_transmit_newest(); } Transmit_target_reset_timer = timestamp(TL_RESET); int play_fail_sound = 1; int transmit_index = Transmit_target_current_slot; Assert(transmit_index >= 0); for ( i = 0; i < MAX_TRANSMIT_TARGETS; i++ ) { if ( Transmit_target_list[transmit_index].objnum >= 0 ) { int transmit_objnum = Transmit_target_list[transmit_index].objnum; if ( Player_ai->target_objnum == transmit_objnum ) { play_fail_sound = 0; } else { if ( Transmit_target_list[transmit_index].objsig == Objects[Transmit_target_list[transmit_index].objnum].signature ) { if ( !(Ships[Objects[transmit_objnum].instance].flags & TARGET_SHIP_IGNORE_FLAGS) ) { Transmit_target_current_slot = transmit_index-1; if ( Transmit_target_current_slot < 0 ) { Transmit_target_current_slot = MAX_TRANSMIT_TARGETS - 1; } break; } } } } transmit_index--; if ( transmit_index < 0 ) { transmit_index = MAX_TRANSMIT_TARGETS - 1; } } if ( i == MAX_TRANSMIT_TARGETS ) { if ( play_fail_sound ) { snd_play( &Snds[SND_TARGET_FAIL] ); } Transmit_target_current_slot = -1; return; } if(hud_target_invalid_awacs(&Objects[Transmit_target_list[transmit_index].objnum])){ return; } // target new ship! // Fix bug in targeting due to Alt-Y (target last ship sending transmission). // Was just bogus code in the call to hud_restore_subsystem_target(). -- MK, 9/15/99, 1:59 pm. int targeted_objnum; targeted_objnum = Transmit_target_list[transmit_index].objnum; Assert((targeted_objnum >= 0) && (targeted_objnum < MAX_OBJECTS)); if ((targeted_objnum >= 0) && (targeted_objnum < MAX_OBJECTS)) { set_target_objnum( Player_ai, Transmit_target_list[transmit_index].objnum ); hud_restore_subsystem_target(&Ships[Objects[Transmit_target_list[transmit_index].objnum].instance]); } } // called externally to add a message sender to the list void hud_target_last_transmit_add(int ship_num) { object *ship_objp; int ship_objnum; ship_objnum = Ships[ship_num].objnum; Assert(ship_objnum >= 0 && ship_objnum < MAX_OBJECTS); ship_objp = &Objects[ship_objnum]; Assert(ship_objp->type == OBJ_SHIP); Transmit_target_list[Transmit_target_next_slot].objnum = ship_objnum; Transmit_target_list[Transmit_target_next_slot].objsig = ship_objp->signature; Transmit_target_next_slot++; if ( Transmit_target_next_slot >= MAX_TRANSMIT_TARGETS ) { Transmit_target_next_slot = 0; } } // target a random ship (useful for EMP stuff) void hud_target_random_ship() { int shipnum; int objnum; shipnum = ship_get_random_ship(); if((shipnum < 0) || (Ships[shipnum].objnum < 0)){ return; } objnum = Ships[shipnum].objnum; if((objnum >= 0) && (Player_ai != NULL) && !hud_target_invalid_awacs(&Objects[objnum])){ // never target yourself if(objnum == OBJ_INDEX(Player_obj)){ set_target_objnum(Player_ai, -1); } else if (Ships[shipnum].flags2 & SF2_NO_RADAR) { set_target_objnum(Player_ai, -1); } else { set_target_objnum(Player_ai, objnum); } } } // ---------------------------------------------------------------- // // Target Last Transmission Sender code END // // ---------------------------------------------------------------- void hudtarget_page_in() { int i; for ( i = 0; i < NUM_WEAPON_GAUGES; i++ ) { bm_page_in_aabitmap( Weapon_gauges[ballistic_hud_index][i].first_frame, Weapon_gauges[ballistic_hud_index][i].num_frames); } bm_page_in_aabitmap( Lead_indicator_gauge.first_frame, Lead_indicator_gauge.num_frames); bm_page_in_aabitmap( Energy_bar_gauges.first_frame, Energy_bar_gauges.num_frames); //bm_page_in_aabitmap( Toggle_gauge.first_frame, Toggle_gauge.num_frames); //bm_page_in_aabitmap( Cmeasure_gauge.first_frame, Cmeasure_gauge.num_frames); }
[ [ [ 1, 6210 ] ] ]
7cca4cf4ae8cda68142b659e71d6240040ce4a25
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/auxiliary/mathematics/rect3d.h
070197a8fa1025a2fc55641d26167a77dfe02d5e
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
1,278
h
/*! @file @brief 3次元矩形テンプレート */ #ifndef maid2_auxiliary_mathematics_rect3d_h #define maid2_auxiliary_mathematics_rect3d_h #include"../../config/define.h" #include"point3d.h" #include"size3d.h" namespace Maid { /*! @brief 直方体をあらわす構造体 */ template<typename TYPE> struct RECT3D_TEMPLATE { TYPE x; // 基準点 TYPE y; TYPE z; TYPE w; // 幅 TYPE h; TYPE d; RECT3D_TEMPLATE(){} RECT3D_TEMPLATE( TYPE _x, TYPE _y, TYPE _z, TYPE _w, TYPE _h, TYPE _d ) //!< コンストラクタ : x(_x),y(_y),z(_z),w(_w),h(_h),d(_d) { } template<typename TYPE2> RECT3D_TEMPLATE( const RECT3D_TEMPLATE<TYPE2>& rha ) //!< コンストラクタ { x = (TYPE)rha.x; y = (TYPE)rha.y; z = (TYPE)rha.z; w = (TYPE)rha.w; h = (TYPE)rha.h; d = (TYPE)rha.d; } TYPE GetRight() const { return x + w; } TYPE GetBottom()const { return y + h; } TYPE GetBack() const { return z + d; } POINT3D_TEMPLATE<TYPE> GetPoint()const{ return POINT3D_TEMPLATE<TYPE>(x,y,z); } SIZE3D_TEMPLATE<TYPE> GetSize() const{ return SIZE3D_TEMPLATE<TYPE>(w,h,d); } }; } #endif
[ [ [ 1, 56 ] ] ]
8659b1942bf4214b121fdd4a97f5c085e3990c3d
51febe6598848c79ffa36890655e25ed05652d7d
/MarioBros/MarioBros/Sign.h
7cdb209bc9cfe9ad22cd50f35dbdefda5e51bb5d
[]
no_license
vohoangviet/game-mario-directx
d6db92457ad10fa97d2241394a2c46457fdbe2c3
e7ad07e7335cd7a2c0cb6b3d1a02af36798cafc4
refs/heads/master
2021-01-10T01:33:15.453400
2011-12-08T14:15:39
2011-12-08T14:15:39
43,821,369
0
0
null
null
null
null
UTF-8
C++
false
false
290
h
#pragma once #include "GAnimation.h" #include "GSprite.h" #include "GObject.h" #include <list> using namespace std; class Sign:public GObject { public: Sign(); Sign(float _x, float _y,float width,float height,int _ID); void Save(fstream *fs); void Load(fstream *fs); };
[ [ [ 1, 16 ] ] ]
0474e1f50a1e45d9cedd447a106273385fc64b53
0c84ebd32a2646b5582051216d6e7c8283bb4f23
/wxFileTextDialog.h
fe949fa5ae7a20769a0d49fa536ec40d60b1bc14
[]
no_license
AudioAnecdotes/wxWizApp
97932d2e6fd2c38934c16629a5e3d6023e0978ac
129dfad68be44581c97249d2975efca2fa7578b7
refs/heads/master
2021-01-18T06:36:29.316270
2007-01-02T06:02:13
2007-01-02T06:02:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
637
h
// wxFileTextDialog.h: interface for the wxFileTextDialog class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_WXFILETEXTDIALOG_H__4FEDDE32_FFDA_4494_B491_0734BA61CE87__INCLUDED_) #define AFX_WXFILETEXTDIALOG_H__4FEDDE32_FFDA_4494_B491_0734BA61CE87__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "wxWizBaseDlg.h" class wxFileTextDialog : public wxWizBaseDlg { public: wxFileTextDialog(WizAppData* data); virtual ~wxFileTextDialog(); }; #endif // !defined(AFX_WXFILETEXTDIALOG_H__4FEDDE32_FFDA_4494_B491_0734BA61CE87__INCLUDED_)
[ "gsilber" ]
[ [ [ 1, 22 ] ] ]
a265763dae66d9964428054971c59846d06e4b78
26706a661c23f5c2c1f97847ba09f44b7b425cf6
/TaskManager/UsagesCtl.h
2a080c3a128094bd1e29df0fe4e98e79a6dd6ae5
[]
no_license
124327288/nativetaskmanager
96a54dbe150f855422d7fd813d3631eaac76fadd
e75b3d9d27c902baddbb1bef975c746451b1b8bb
refs/heads/master
2021-05-29T05:18:26.779900
2009-02-10T13:23:28
2009-02-10T13:23:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,393
h
#ifndef _CCPUUSGESCTL_H_ #define _CCPUUSGESCTL_H_ #ifdef __cplusplus extern "C" { #endif ///////////////////////////////////////////////////////////////////////////// // CUsageCtrl window class CUsageCtrl : public CWnd { // Construction public: CUsageCtrl(); virtual ~CUsageCtrl(); // Attributes public: BOOL Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID); // Operations public: // Implementation public: void SetStringExtend(CString strExtend); void SetGridHeight(double dNewCounts); void SetGridCount(double dNewHeight); void Refresh(); private: void DrawCpuUsges(CDC *pDC); private: CFont m_font; COLORREF m_LableColor; COLORREF m_ForeFontColor; COLORREF m_ForeColor; COLORREF m_BackColor; COLORREF m_FreeColor; COLORREF m_UsedColor; COLORREF m_clrFrameLeftTop; COLORREF m_clrFrameRightBottom; double m_dGridCount; double m_dNewUsges; CString m_strExtend; CRect m_rectClient; CRect m_rectGraph; // Generated message map functions protected: DECLARE_MESSAGE_MAP() afx_msg void OnPaint(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnShowWindow(BOOL bShow, UINT nStatus); afx_msg BOOL OnEraseBkgnd(CDC* pDC); }; #ifdef __cplusplus } #endif #endif
[ "[email protected]@97a26042-f463-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 69 ] ] ]
959866da02fb36cea278d6cce642795a3d4237a6
1c4a1cd805be8bc6f32b0a616de751ad75509e8d
/jacknero/src/pku_src/1528/.svn/text-base/3573343_CE.cpp.svn-base
0e31bad14978dbf12c66d853a567e3e6bcd07d71
[]
no_license
jacknero/mycode
30313261d7e059832613f26fa453abf7fcde88a0
44783a744bb5a78cee403d50eb6b4a384daccf57
refs/heads/master
2016-09-06T18:47:12.947474
2010-05-02T10:16:30
2010-05-02T10:16:30
180,950
1
0
null
null
null
null
UTF-8
C++
false
false
464
#include <iostream> #include <cstdio> #include <cmath> using namespace std; int main() { int n,sum,i; puts("PERFECTION OUTPUT"); for(;;) { cin >> n; if(n==0) break; printf("%5d ", n); sum=0; i=(int)sqrt(n); if(i*i==n) sum-=i; for(i;i>1;i--) if(n%i==0) sum += i + n/i; sum++; if(sum==n) puts("PERFECT"); else if(sum<n) puts("DEFICIENT"); else puts("ABUNDANT"); } puts("END OF OUTPUT"); return 0; }
[ [ [ 1, 29 ] ] ]
1f88bd09b7c79e6caec95c1900c9eda372843689
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/fbxcmd/Plugins/fbxdao/exporter/writer.h
2f2ca0fa2939ef5b8df8533d559551ce0c8e46bb
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
code-google-com/fbx4eclipse
110766ee9760029d5017536847e9f3dc09e6ebd2
cc494db4261d7d636f8c4d0313db3953b781e295
refs/heads/master
2016-09-08T01:55:57.195874
2009-12-03T20:35:48
2009-12-03T20:35:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,171
h
#pragma once #include "fbxdao.h" #include <fbxsdk.h> #include "../Common/ResourceManager.h" #include "daolog.h" #include "../fbxcmn/KFbxLog.h" class DAOWriter : public KFbxWriter { typedef class KFbxWriter base; public: void *operator new(size_t count) { return k_pAllocator->mMallocHandler(count); } void operator delete(void* _Ptr) throw( ) { k_pAllocator->mFreeHandler(_Ptr); } DAOWriter(KFbxSdkManager &manager, KFbxExporter &exporter, int SubID, int ID); //VERY important to put the file close in the destructor virtual ~DAOWriter() ; virtual bool FileCreate(char* pFileName) ; virtual bool FileClose() ; virtual bool IsFileOpen(); virtual KFbxStreamOptions* GetWriteOptions() ; virtual bool Write(KFbxDocument* pDocument, KFbxStreamOptions* pStreamOptions) ; virtual bool PreprocessScene(KFbxScene &pScene); virtual bool PostprocessScene(KFbxScene &pScene); // Implementation bool WriteMMH( KFbxDocument* pDocument, KFbxStreamOptions* pStreamOptions, LPCTSTR fname ); public: KFbxSdkManager *mManager; KFbxExporter *mExporter; int mSubID; int mID; FixedString<CHAR, 260> filepath; };
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 45 ] ] ]
88ce27ae0aaa435dd37ac8894a7de23d98423fcb
a84b013cd995870071589cefe0ab060ff3105f35
/webdriver/branches/chrome/chrome/src/cpp/include/v8/src/cpu.h
4fac0ec91acf7973646a1a0ced99646b9374f5b5
[ "Apache-2.0" ]
permissive
vdt/selenium
137bcad58b7184690b8785859d77da0cd9f745a0
30e5e122b068aadf31bcd010d00a58afd8075217
refs/heads/master
2020-12-27T21:35:06.461381
2009-08-18T15:56:32
2009-08-18T15:56:32
13,650,409
1
0
null
null
null
null
UTF-8
C++
false
false
2,830
h
// Copyright 2006-2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This module contains the architecture-specific code. This make the rest of // the code less dependent on differences between different processor // architecture. // The classes have the same definition for all architectures. The // implementation for a particular architecture is put in cpu_<arch>.cc. // The build system then uses the implementation for the target architecture. // #ifndef V8_CPU_H_ #define V8_CPU_H_ namespace v8 { namespace internal { // ---------------------------------------------------------------------------- // CPU // // This class has static methods for the architecture specific functions. Add // methods here to cope with differences between the supported architectures. // // For each architecture the file cpu_<arch>.cc contains the implementation of // these functions. class CPU : public AllStatic { public: // Initializes the cpu architecture support. Called once at VM startup. static void Setup(); // Flush instruction cache. static void FlushICache(void* start, size_t size); // Try to activate a system level debugger. static void DebugBreak(); }; } } // namespace v8::internal #endif // V8_CPU_H_
[ "noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9" ]
[ [ [ 1, 64 ] ] ]
e2ebcd65247a219301bc7d3a44ef76c3e1c51561
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/uavobjects/velocityactual.cpp
5e4e6fdaec7ca26fd32d5fdf7054cbac5e80e302
[]
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
4,561
cpp
/** ****************************************************************************** * * @file velocityactual.cpp * @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: velocityactual.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 */ #include "velocityactual.h" #include "uavobjectfield.h" const QString VelocityActual::NAME = QString("VelocityActual"); /** * Constructor */ VelocityActual::VelocityActual(): UAVDataObject(OBJID, ISSINGLEINST, ISSETTINGS, NAME) { // Create fields QList<UAVObjectField*> fields; QStringList NorthElemNames; NorthElemNames.append("0"); fields.append( new UAVObjectField(QString("North"), QString("cm/s"), UAVObjectField::INT32, NorthElemNames, QStringList()) ); QStringList EastElemNames; EastElemNames.append("0"); fields.append( new UAVObjectField(QString("East"), QString("cm/s"), UAVObjectField::INT32, EastElemNames, QStringList()) ); QStringList DownElemNames; DownElemNames.append("0"); fields.append( new UAVObjectField(QString("Down"), QString("cm/s"), UAVObjectField::INT32, DownElemNames, QStringList()) ); // Initialize object initializeFields(fields, (quint8*)&data, NUMBYTES); // Set the default field values setDefaultFieldValues(); } /** * Get the default metadata for this object */ UAVObject::Metadata VelocityActual::getDefaultMetadata() { UAVObject::Metadata metadata; metadata.flightAccess = ACCESS_READWRITE; metadata.gcsAccess = ACCESS_READWRITE; metadata.gcsTelemetryAcked = 0; metadata.gcsTelemetryUpdateMode = UAVObject::UPDATEMODE_MANUAL; metadata.gcsTelemetryUpdatePeriod = 0; metadata.flightTelemetryAcked = 0; metadata.flightTelemetryUpdateMode = UAVObject::UPDATEMODE_PERIODIC; metadata.flightTelemetryUpdatePeriod = 1000; metadata.loggingUpdateMode = UAVObject::UPDATEMODE_PERIODIC; metadata.loggingUpdatePeriod = 1000; return metadata; } /** * Initialize object fields with the default values. * If a default value is not specified the object fields * will be initialized to zero. */ void VelocityActual::setDefaultFieldValues() { } /** * Get the object data fields */ VelocityActual::DataFields VelocityActual::getData() { QMutexLocker locker(mutex); return data; } /** * Set the object data fields */ void VelocityActual::setData(const DataFields& data) { QMutexLocker locker(mutex); // Get metadata Metadata mdata = getMetadata(); // Update object if the access mode permits if ( mdata.gcsAccess == ACCESS_READWRITE ) { this->data = data; emit objectUpdatedAuto(this); // trigger object updated event emit objectUpdated(this); } } /** * Create a clone of this object, a new instance ID must be specified. * Do not use this function directly to create new instances, the * UAVObjectManager should be used instead. */ UAVDataObject* VelocityActual::clone(quint32 instID) { VelocityActual* obj = new VelocityActual(); obj->initialize(instID, this->getMetaObject()); return obj; } /** * Static function to retrieve an instance of the object. */ VelocityActual* VelocityActual::GetInstance(UAVObjectManager* objMngr, quint32 instID) { return dynamic_cast<VelocityActual*>(objMngr->getObject(VelocityActual::OBJID, instID)); }
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 134 ] ] ]
fcb9c5d0f4caaa51271f0c724ef72dd5284fd762
7aa5cd977756e067e96d48585db1ec4a35c4c962
/antilander/ALTimer.h
b0836531e103f44a6150dbe834bd7048ad9e36a1
[]
no_license
zzyzxr99/antilander
15faf715fe9248286d375e9f8e8af08260df7fa4
c1c9b05d0d869c251e19f9c31e6c223f63104e54
refs/heads/master
2021-01-19T14:10:00.561194
2008-08-02T17:18:27
2008-08-02T17:18:27
34,579,640
0
0
null
null
null
null
UTF-8
C++
false
false
639
h
#ifndef _ALTIMER_H #define _ALTIMER_H // Class prototypes class ALTimer; #include "Windows.h" #include "Mmsystem.h" #include <ctime> // Timer class to count of game step and for special attacks/delays class ALTimer { private: unsigned long mLastTick; unsigned long mLastDiff; float mLastInterval; public: ALTimer(); ~ALTimer(); unsigned long ElapsedMS(void); void Mark(void); unsigned long CurrentTimeMS(); bool CheckElapsedMS(unsigned long ms); unsigned long TimerMinMS(); unsigned long LastStamp(); unsigned long LastDiff(); float LastInterval(); }; #endif /*_ALTIMER_H*/
[ "eric.riel@12e01eeb-bf4d-0410-af2a-23d671325bb1" ]
[ [ [ 1, 33 ] ] ]
47ccdccadd77b73a5b6a17f076bc3224ea624825
e620d7b5f7050500b874decef414cb2416951d30
/bullet/src/LinearMath/btSerializer.h
023cb86f7606a4f09754e2ae3ec079899d6e642c
[ "MIT" ]
permissive
svn2github/3d-editor-toolkit
9bf3829404b639f35311b540f9a2a7c8b592a153
baf132a47e1d03272efdf65a8a87c6976156d51b
refs/heads/master
2021-01-25T08:48:48.815860
2010-02-13T19:40:18
2010-02-13T19:40:18
30,482,260
2
3
null
null
null
null
UTF-8
C++
false
false
10,791
h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_SERIALIZER_H #define BT_SERIALIZER_H #include "btScalar.h" // has definitions like SIMD_FORCE_INLINE #include "btStackAlloc.h" #include "btHashMap.h" #if !defined( __CELLOS_LV2__) && !defined(__MWERKS__) #include <memory.h> #endif #include <string.h> ///only the 32bit versions for now extern unsigned char sBulletDNAstr[]; extern int sBulletDNAlen; extern unsigned char sBulletDNAstr64[]; extern int sBulletDNAlen64; SIMD_FORCE_INLINE int btStrLen(const char* str) { if (!str) return(0); int len = 0; while (*str != 0) { str++; len++; } return len; } class btChunk { public: int m_chunkCode; int m_length; void *m_oldPtr; int m_dna_nr; int m_number; }; class btSerializer { public: virtual ~btSerializer() {} virtual const unsigned char* getBufferPointer() const = 0; virtual int getCurrentBufferSize() const = 0; virtual btChunk* allocate(size_t size, int numElements) = 0; virtual void finalizeChunk(btChunk* chunk, const char* structType, int chunkCode,void* oldPtr)= 0; virtual void* findPointer(void* oldPtr) = 0; virtual void startSerialization() = 0; virtual void finishSerialization() = 0; virtual const char* findNameForPointer(const void* ptr) const = 0; virtual void registerNameForPointer(const void* ptr, const char* name) = 0; virtual void serializeName(const char* ptr) = 0; }; #define BT_HEADER_LENGTH 12 #if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__) # define MAKE_ID(a,b,c,d) ( (int)(a)<<24 | (int)(b)<<16 | (c)<<8 | (d) ) #else # define MAKE_ID(a,b,c,d) ( (int)(d)<<24 | (int)(c)<<16 | (b)<<8 | (a) ) #endif #define BT_COLLISIONOBJECT_CODE MAKE_ID('C','O','B','J') #define BT_RIGIDBODY_CODE MAKE_ID('R','B','D','Y') #define BT_CONSTRAINT_CODE MAKE_ID('C','O','N','S') #define BT_BOXSHAPE_CODE MAKE_ID('B','O','X','S') #define BT_SHAPE_CODE MAKE_ID('S','H','A','P') #define BT_ARRAY_CODE MAKE_ID('A','R','A','Y') class btDefaultSerializer : public btSerializer { btAlignedObjectArray<char*> mTypes; btAlignedObjectArray<short*> mStructs; btAlignedObjectArray<short> mTlens; btHashMap<btHashInt, int> mStructReverse; btHashMap<btHashString,int> mTypeLookup; btHashMap<btHashPtr,void*> m_chunkP; btHashMap<btHashPtr,const char*> m_nameMap; int m_totalSize; unsigned char* m_buffer; int m_currentSize; void* m_dna; int m_dnaLength; btAlignedObjectArray<btChunk*> m_chunkPtrs; protected: virtual void* findPointer(void* oldPtr) { void** ptr = m_chunkP.find(oldPtr); if (ptr && *ptr) return *ptr; return 0; } void writeDNA() { unsigned char* dnaTarget = m_buffer+m_currentSize; memcpy(dnaTarget,m_dna,m_dnaLength); m_currentSize += m_dnaLength; } int getReverseType(const char *type) const { btHashString key(type); const int* valuePtr = mTypeLookup.find(key); if (valuePtr) return *valuePtr; return -1; } void initDNA(const char* bdnaOrg,int dnalen) { ///was already initialized if (m_dna) return; int littleEndian= 1; littleEndian= ((char*)&littleEndian)[0]; m_dna = btAlignedAlloc(dnalen,16); memcpy(m_dna,bdnaOrg,dnalen); m_dnaLength = dnalen; int *intPtr=0; short *shtPtr=0; char *cp = 0;int dataLen =0;long nr=0; intPtr = (int*)m_dna; /* SDNA (4 bytes) (magic number) NAME (4 bytes) <nr> (4 bytes) amount of names (int) <string> <string> */ if (strncmp((const char*)m_dna, "SDNA", 4)==0) { // skip ++ NAME intPtr++; intPtr++; } // Parse names if (!littleEndian) *intPtr = btSwapEndian(*intPtr); dataLen = *intPtr; intPtr++; cp = (char*)intPtr; int i; for ( i=0; i<dataLen; i++) { while (*cp)cp++; cp++; } { nr= (long)cp; // long mask=3; nr= ((nr+3)&~3)-nr; while (nr--) { cp++; } } /* TYPE (4 bytes) <nr> amount of types (int) <string> <string> */ intPtr = (int*)cp; assert(strncmp(cp, "TYPE", 4)==0); intPtr++; if (!littleEndian) *intPtr = btSwapEndian(*intPtr); dataLen = *intPtr; intPtr++; cp = (char*)intPtr; for (i=0; i<dataLen; i++) { mTypes.push_back(cp); while (*cp)cp++; cp++; } { nr= (long)cp; // long mask=3; nr= ((nr+3)&~3)-nr; while (nr--) { cp++; } } /* TLEN (4 bytes) <len> (short) the lengths of types <len> */ // Parse type lens intPtr = (int*)cp; assert(strncmp(cp, "TLEN", 4)==0); intPtr++; dataLen = (int)mTypes.size(); shtPtr = (short*)intPtr; for (i=0; i<dataLen; i++, shtPtr++) { if (!littleEndian) shtPtr[0] = btSwapEndian(shtPtr[0]); mTlens.push_back(shtPtr[0]); } if (dataLen & 1) shtPtr++; /* STRC (4 bytes) <nr> amount of structs (int) <typenr> <nr_of_elems> <typenr> <namenr> <typenr> <namenr> */ intPtr = (int*)shtPtr; cp = (char*)intPtr; assert(strncmp(cp, "STRC", 4)==0); intPtr++; if (!littleEndian) *intPtr = btSwapEndian(*intPtr); dataLen = *intPtr ; intPtr++; shtPtr = (short*)intPtr; for (i=0; i<dataLen; i++) { mStructs.push_back (shtPtr); if (!littleEndian) { shtPtr[0]= btSwapEndian(shtPtr[0]); shtPtr[1]= btSwapEndian(shtPtr[1]); int len = shtPtr[1]; shtPtr+= 2; for (int a=0; a<len; a++, shtPtr+=2) { shtPtr[0]= btSwapEndian(shtPtr[0]); shtPtr[1]= btSwapEndian(shtPtr[1]); } } else { shtPtr+= (2*shtPtr[1])+2; } } // build reverse lookups for (i=0; i<(int)mStructs.size(); i++) { short *strc = mStructs.at(i); mStructReverse.insert(strc[0], i); mTypeLookup.insert(btHashString(mTypes[strc[0]]),i); } } public: btDefaultSerializer(int totalSize) :m_totalSize(totalSize), m_currentSize(0), m_dna(0), m_dnaLength(0) { m_buffer = (unsigned char*)btAlignedAlloc(totalSize, 16); const bool VOID_IS_8 = ((sizeof(void*)==8)); #ifdef BT_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES if (VOID_IS_8) { #if _WIN64 initDNA((const char*)sBulletDNAstr64,sBulletDNAlen64); #else btAssert(0); #endif } else { #ifndef _WIN64 initDNA((const char*)sBulletDNAstr,sBulletDNAlen); #else btAssert(0); #endif } #else //BT_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES if (VOID_IS_8) { initDNA((const char*)sBulletDNAstr64,sBulletDNAlen64); } else { initDNA((const char*)sBulletDNAstr,sBulletDNAlen); } #endif //BT_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES } virtual ~btDefaultSerializer() { if (m_buffer) btAlignedFree(m_buffer); if (m_dna) btAlignedFree(m_dna); } virtual void startSerialization() { m_currentSize = BT_HEADER_LENGTH; #ifdef BT_USE_DOUBLE_PRECISION memcpy(m_buffer, "BULLETd", 7); #else memcpy(m_buffer, "BULLETf", 7); #endif //BT_USE_DOUBLE_PRECISION int littleEndian= 1; littleEndian= ((char*)&littleEndian)[0]; if (sizeof(void*)==8) { m_buffer[7] = '-'; } else { m_buffer[7] = '_'; } if (littleEndian) { m_buffer[8]='v'; } else { m_buffer[8]='V'; } m_buffer[9] = '2'; m_buffer[10] = '7'; m_buffer[11] = '6'; } virtual void finishSerialization() { writeDNA(); } virtual const unsigned char* getBufferPointer() const { return m_buffer; } virtual int getCurrentBufferSize() const { return m_currentSize; } virtual void finalizeChunk(btChunk* chunk, const char* structType, int chunkCode,void* oldPtr) { btAssert(!findPointer(oldPtr)); chunk->m_dna_nr = getReverseType(structType); chunk->m_chunkCode = chunkCode; m_chunkP.insert(oldPtr,chunk->m_oldPtr); chunk->m_oldPtr = oldPtr; } virtual btChunk* allocate(size_t size, int numElements) { unsigned char* ptr = m_buffer+m_currentSize; m_currentSize += int(size)*numElements+sizeof(btChunk); btAssert(m_currentSize<m_totalSize); unsigned char* data = ptr + sizeof(btChunk); btChunk* chunk = (btChunk*)ptr; chunk->m_chunkCode = 0; chunk->m_oldPtr = data; chunk->m_length = int(size)*numElements; chunk->m_number = numElements; m_chunkPtrs.push_back(chunk); return chunk; } virtual const char* findNameForPointer(const void* ptr) const { const char*const * namePtr = m_nameMap.find(ptr); if (namePtr && *namePtr) return *namePtr; return 0; } virtual void registerNameForPointer(const void* ptr, const char* name) { m_nameMap.insert(ptr,name); } virtual void serializeName(const char* name) { if (name) { int len = btStrLen(name); if (len) { int newLen = len+1; int padding = ((newLen+3)&~3)-newLen; newLen += padding; //serialize name string now btChunk* chunk = allocate(sizeof(char),newLen); char* destinationName = (char*)chunk->m_oldPtr; for (int i=0;i<len;i++) { destinationName[i] = name[i]; } destinationName[len] = 0; finalizeChunk(chunk,"char",BT_ARRAY_CODE,(void*)name); } } } }; #endif //BT_SERIALIZER_H
[ "kunc.filip@77665838-ecdd-11de-a5fe-b7516cc0fd57" ]
[ [ [ 1, 520 ] ] ]
d152e13ddc791a29269c25b77e9d4f1d1fdb5667
b4bff7f61d078e3dddeb760e21174a781ed7f985
/Source/Contrib/UserInterface/src/Component/List/OSGListSelectionModel.h
9e1611a1a831e1e1d686bf6d4eefae19e215c9b6
[]
no_license
Langkamp/OpenSGToolbox
8283edb6074dffba477c2c4d632e954c3c73f4e3
5a4230441e68f001cdf3e08e9f97f9c0f3c71015
refs/heads/master
2021-01-16T18:15:50.951223
2010-05-19T20:24:52
2010-05-19T20:24:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,908
h
/*---------------------------------------------------------------------------*\ * OpenSG ToolBox UserInterface * * * * * * * * * * www.vrac.iastate.edu * * * * Authors: David Kabala, Alden Peterson, Lee Zaniewski, Jonathan Flory * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ #ifndef _OSG_UI_LIST_SELECTION_MODEL_H_ #define _OSG_UI_LIST_SELECTION_MODEL_H_ #ifdef __sgi #pragma once #endif #include "OSGConfig.h" #include "OSGContribUserInterfaceDef.h" #include "OSGListSelectionListener.h" #include "OSGFieldContainer.h" #include <boost/shared_ptr.hpp> #include "OSGEventConnection.h" OSG_BEGIN_NAMESPACE class OSG_CONTRIBUSERINTERFACE_DLLMAPPING ListSelectionModel { private: protected: public: enum ListSelectionMode {MULTIPLE_INTERVAL_SELECTION, SINGLE_INTERVAL_SELECTION, SINGLE_SELECTION}; //Add a listener to the list that's notified each time a change to the selection occurs. virtual EventConnection addListSelectionListener(ListSelectionListenerPtr x) = 0; virtual bool isListSelectionListenerAttached(ListSelectionListenerPtr x) const = 0; //Change the selection to be the set union of the current selection and the indices between index0 and index1 inclusive. virtual void addSelectionInterval(UInt32 index0, UInt32 index1) = 0; //Change the selection to the empty set. virtual void clearSelection(void) = 0; //Return the first index argument from the most recent call to setSelectionInterval(), addSelectionInterval() or removeSelectionInterval(). virtual Int32 getAnchorSelectionIndex(void) const = 0; //Return the second index argument from the most recent call to setSelectionInterval(), addSelectionInterval() or removeSelectionInterval(). virtual Int32 getLeadSelectionIndex(void) const = 0; //Returns the last selected index or -1 if the selection is empty. virtual Int32 getMaxSelectionIndex(void) const = 0; //Returns the first selected index or -1 if the selection is empty. virtual Int32 getMinSelectionIndex(void) const = 0; //Returns the current selection mode. virtual UInt32 getSelectionMode(void) const = 0; //Returns true if the value is undergoing a series of changes. virtual bool getValueIsAdjusting(void) const = 0; //Insert length indices beginning before/after index. virtual void insertIndexInterval(UInt32 index, UInt32 length, bool before) = 0; //Returns true if the specified index is selected. virtual bool isSelectedIndex(UInt32 index) const = 0; //Returns true if no indices are selected. virtual bool isSelectionEmpty(void) const = 0; //Remove the indices in the interval index0,index1 (inclusive) from the selection model. virtual void removeIndexInterval(UInt32 index0, UInt32 index1) = 0; //Remove a listener from the list that's notified each time a change to the selection occurs. virtual void removeListSelectionListener(ListSelectionListenerPtr x) = 0; //Change the selection to be the set difference of the current selection and the indices between index0 and index1 inclusive. virtual void removeSelectionInterval(UInt32 index0, UInt32 index1) = 0; //Set the anchor selection index. virtual void setAnchorSelectionIndex(UInt32 index) = 0; //Set the lead selection index. virtual void setLeadSelectionIndex(UInt32 index) = 0; //Change the selection to be between index0 and index1 inclusive. virtual void setSelectionInterval(UInt32 index0, UInt32 index1) = 0; //Set the selection mode. virtual void setSelectionMode(UInt32 selectionMode) = 0; //This property is true if upcoming changes to the value of the model should be considered a single event. virtual void setValueIsAdjusting(bool valueIsAdjusting) = 0; virtual void incrementValuesAboveIndex(const UInt32& index, const UInt32& NumberToIncrement) = 0; virtual void decrementValuesAboveIndex(const UInt32& index, const UInt32& NumberToDecrement) = 0; }; typedef boost::shared_ptr<ListSelectionModel> ListSelectionModelPtr; OSG_END_NAMESPACE #endif /* _OSG_UI_LIST_SELECTION_MODEL_H_ */
[ [ [ 1, 1 ], [ 3, 6 ], [ 10, 136 ] ], [ [ 2, 2 ], [ 7, 9 ] ] ]
e03557d0c0fafe7017c67e2fc1eef5a23f7ca66b
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlIKGoal.h
b31cff9e272c462d4f9fa874a5cf89aaac75bea8
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
1,090
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 WMLIKGOAL_H #define WMLIKGOAL_H #include "WmlObject.h" #include "WmlVector3.h" namespace Wml { class Spatial; class WML_ITEM IKGoal : public Object { WmlDeclareRTTI; WmlDeclareStream; public: IKGoal (Spatial* pkTarget, Spatial* pkEffector, float fWeight); Spatial*& Target (); Spatial*& Effector (); float& Weight (); Vector3f GetPosition () const; Vector3f GetEffectorPosition () const; float GetNorm () const; protected: IKGoal (); Spatial* m_pkTarget; Spatial* m_pkEffector; float m_fWeight; }; WmlSmartPointer(IKGoal); WmlRegisterStream(IKGoal); #include "WmlIKGoal.inl" } #endif
[ [ [ 1, 52 ] ] ]
0e94ea45038ee626ab83d78715a16c13e4ccac00
718dc2ad71e8b39471b5bf0c6d60cbe5f5c183e1
/soft micros/Codigo/codigo portable/Vista/Frente8SegTeclasYLeds/Frentes/FrenteDH.hpp
ed18491b841a874d4a820306e77b33b8faf6af63
[]
no_license
jonyMarino/microsdhacel
affb7a6b0ea1f4fd96d79a04d1a3ec3eaa917bca
66d03c6a9d3a2d22b4d7104e2a38a2c9bb4061d3
refs/heads/master
2020-05-18T19:53:51.301695
2011-05-30T20:40:24
2011-05-30T20:40:24
34,532,512
0
0
null
null
null
null
UTF-8
C++
false
false
696
hpp
#ifndef _FRENTE_DH_HPP #define _FRENTE_DH_HPP #include "Vista/Frente8SegTeclasYLeds/FrenteCustom.hpp" #define CANTIDAD_DISPLAYS 2 class FrenteDH:public FrenteCustom{ public: static FrenteDH* getInstancia(); virtual Display* getDisplay(byte numDisplay); protected: FrenteDH(); virtual void seleccionarDigito(byte barrido); virtual void encenderLeds(byte leds); virtual bool isTeclaPresionada(); virtual byte getTeclaPosicion(byte barrido); private: Display display1; Display display2; static const byte codigoSelectorDigito[8]; static const byte codigoTecla[8]; static FrenteDH * instancia; }; #endif
[ "nicopimen@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549" ]
[ [ [ 1, 29 ] ] ]
d51a337f5d6e62c196c9e04144d0f10db7acf5a7
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/DSDK/include/writers/GeoTIFFImageWriter.h
5ee79c0ee3f1f57359b066b53148cd9fe4d2064e
[]
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
1,683
h
/* $Id: GeoTIFFImageWriter.h 5124 2006-10-27 11:40:40Z lubia $ */ /* ////////////////////////////////////////////////////////////////////////// // // // This code is Copyright (c) 2004 LizardTech, Inc, 1008 Western Avenue, // // Suite 200, Seattle, WA 98104. Unauthorized use or distribution // // prohibited. Access to and use of this code is permitted only under // // license from LizardTech, Inc. Portions of the code are protected by // // US and foreign patents and other filings. All Rights Reserved. // // // ////////////////////////////////////////////////////////////////////////// */ /* PUBLIC */ #ifndef GEOTIFFIMAGEWRITER_H #define GEOTIFFIMAGEWRITER_H // lt_lib_mrsid_imageWriters #include "TIFFImageWriter.h" #if defined(LT_COMPILER_MS) #pragma warning(push,4) #endif LT_BEGIN_NAMESPACE(LizardTech) /** * writes an image stage to a GeoTIFF file * * This class writes an image stage to a GeoTIFF file. */ class GeoTIFFImageWriter : public TIFFImageWriter { public: /** * constructor * * Creates a writer for GeoTIFF images. * * @param image the image to write from */ GeoTIFFImageWriter(LTIImageStage* image); private: typedef TIFFImageWriter Super; // nope GeoTIFFImageWriter(GeoTIFFImageWriter&); GeoTIFFImageWriter& operator=(const GeoTIFFImageWriter&); }; LT_END_NAMESPACE(LizardTech) #if defined(LT_COMPILER_MS) #pragma warning(pop) #endif #endif // GEOTIFFIMAGEWRITER_H
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 57 ] ] ]
e9a1605d6e082446eaca1c5ba7c08f9be33380ab
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/samples/DOMCount/DOMCount.hpp
fe95bca7f07eb4a48c73e132ab2601163bf0c774
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
5,756
hpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: DOMCount.hpp,v $ * Revision 1.11 2004/09/08 13:55:31 peiyongz * Apache License Version 2.0 * * Revision 1.10 2003/05/30 09:36:35 gareth * Use new macros for iostream.h and std:: issues. * * Revision 1.9 2003/02/05 18:53:22 tng * [Bug 11915] Utility for freeing memory. * * Revision 1.8 2002/11/05 21:46:19 tng * Explicit code using namespace in application. * * Revision 1.7 2002/06/18 16:19:40 knoaman * Replace XercesDOMParser with DOMBuilder for parsing XML documents. * * Revision 1.6 2002/02/01 22:35:01 peiyongz * sane_include * * Revision 1.5 2000/10/20 22:00:35 andyh * DOMCount sample Minor cleanup - rename error handler class to say that it is an error handler. * * Revision 1.4 2000/03/02 19:53:39 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.3 2000/02/11 02:43:55 abagchi * Removed StrX::transcode * * Revision 1.2 2000/02/06 07:47:17 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:09:52 twl * Initial checkin * * Revision 1.5 1999/11/08 20:43:35 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/dom/DOMErrorHandler.hpp> #include <xercesc/util/XMLString.hpp> #if defined(XERCES_NEW_IOSTREAMS) #include <iostream> #else #include <iostream.h> #endif XERCES_CPP_NAMESPACE_USE // --------------------------------------------------------------------------- // Simple error handler deriviative to install on parser // --------------------------------------------------------------------------- class DOMCountErrorHandler : public DOMErrorHandler { public: // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- DOMCountErrorHandler(); ~DOMCountErrorHandler(); // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- bool getSawErrors() const; // ----------------------------------------------------------------------- // Implementation of the DOM ErrorHandler interface // ----------------------------------------------------------------------- bool handleError(const DOMError& domError); void resetErrors(); private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- DOMCountErrorHandler(const DOMCountErrorHandler&); void operator=(const DOMCountErrorHandler&); // ----------------------------------------------------------------------- // Private data members // // fSawErrors // This is set if we get any errors, and is queryable via a getter // method. Its used by the main code to suppress output if there are // errors. // ----------------------------------------------------------------------- bool fSawErrors; }; // --------------------------------------------------------------------------- // This is a simple class that lets us do easy (though not terribly efficient) // trancoding of XMLCh data to local code page for display. // --------------------------------------------------------------------------- class StrX { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- StrX(const XMLCh* const toTranscode) { // Call the private transcoding method fLocalForm = XMLString::transcode(toTranscode); } ~StrX() { XMLString::release(&fLocalForm); } // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- const char* localForm() const { return fLocalForm; } private : // ----------------------------------------------------------------------- // Private data members // // fLocalForm // This is the local code page form of the string. // ----------------------------------------------------------------------- char* fLocalForm; }; inline XERCES_STD_QUALIFIER ostream& operator<<(XERCES_STD_QUALIFIER ostream& target, const StrX& toDump) { target << toDump.localForm(); return target; } inline bool DOMCountErrorHandler::getSawErrors() const { return fSawErrors; }
[ [ [ 1, 167 ] ] ]
74f36f02bb17ef43754d49c4d1951b4d45c98feb
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/input/ninput_log.cc
3b1a70d45d030e50c7bcba215fd21c2e05573170
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
3,835
cc
//------------------------------------------------------------------------------ // ninput_log.cc // (C) 2002 RadonLabs GmbH //------------------------------------------------------------------------------ #include "kernel/nkernelserver.h" #include "kernel/nenv.h" #include "input/ninputserver.h" #include "input/ninputevent.h" //------------------------------------------------------------------------------ /** */ void nInputServer::StartLogging() { if (this->log_events) { n_printf("already logging\n"); } else { this->log_events = true; } } //------------------------------------------------------------------------------ /** */ void nInputServer::StopLogging() { if (this->log_events) { this->log_events = false; } else { n_printf("not logging!\n"); } } //------------------------------------------------------------------------------ /** */ bool nInputServer::IsLogging() { return this->log_events; } //------------------------------------------------------------------------------ /** */ void nInputServer::LogSingleEvent(nInputEvent *ie) { char *dev_type; int dev_num = ie->GetDeviceId() & 0xffff; char *e_type; if (ie->GetDeviceId() & N_IDEV_KEYBOARD) dev_type = "keyb"; else if (ie->GetDeviceId() & N_IDEV_MOUSE) dev_type = "mouse"; else if (ie->GetDeviceId() & N_IDEV_JOYSTICK) dev_type = "joy"; else if (ie->GetDeviceId() & N_IDEV_JOYMOUSE) dev_type = "joymouse"; else if (ie->GetDeviceId() & N_IDEV_PADMOUSE) dev_type = "padmouse"; else dev_type = "unknown"; switch (ie->GetType()) { case N_INPUT_KEY_DOWN: e_type = "key_down"; break; case N_INPUT_KEY_UP: e_type = "key_up"; break; case N_INPUT_KEY_CHAR: e_type = "char"; break; case N_INPUT_MOUSE_MOVE: e_type = "mouse_move"; break; case N_INPUT_AXIS_MOVE: e_type = "axis_move"; break; case N_INPUT_BUTTON_DOWN: e_type = "button_down"; break; case N_INPUT_BUTTON_UP: e_type = "button_up"; break; default: e_type = "unknown"; break; } switch (ie->GetType()) { case N_INPUT_KEY_DOWN: case N_INPUT_KEY_UP: n_printf("dev=%s%d type=%s key=%d\n",dev_type,dev_num,e_type,(int)ie->GetKey()); break; case N_INPUT_KEY_CHAR: n_printf("dev=%s%d type=%s key=%d\n",dev_type,dev_num,e_type,ie->GetChar()); break; case N_INPUT_BUTTON_DOWN: case N_INPUT_BUTTON_UP: n_printf("dev=%s%d type=%s btn=%d xy=[%d,%d]\n", dev_type, dev_num, e_type, ie->GetButton(), ie->GetAbsXPos(), ie->GetAbsYPos()); break; case N_INPUT_MOUSE_MOVE: n_printf("dev=%s%d type=%s abs=[%d,%d] rel=[%f,%f]\n", dev_type, dev_num, e_type, ie->GetAbsXPos(), ie->GetAbsYPos(), ie->GetRelXPos(), ie->GetRelYPos()); break; case N_INPUT_AXIS_MOVE: n_printf("dev=%s%d type=%s axis=%d val=%f\n", dev_type, dev_num, e_type, ie->GetAxis(), ie->GetAxisValue()); break; default: n_printf("unknown event!\n"); break; } } //------------------------------------------------------------------------------ /** */ void nInputServer::LogEvents() { nInputEvent *ie; for (ie = (nInputEvent *) this->events.GetHead(); ie; ie = (nInputEvent *) ie->GetSucc()) { this->LogSingleEvent(ie); } } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 120 ] ] ]
e427ee4baa5bc819e8ce644f97c5b106b8b7cd51
a7109719291d3fb1e3dabfed9405d2b340ad8a89
/Gandhi-Prototype/lib/cGSGameOver.cpp
f78a9d4df76251edb8b4dac1a4f1354dbf5456e7
[]
no_license
edufg88/gandhi-prototype
0ea3c6a7bbe72b6d382fa76f23c40b4a0280c666
947f2c6d8a63421664eb5018d5d01b8da71f46a2
refs/heads/master
2021-01-01T17:32:40.791045
2011-12-19T20:10:34
2011-12-19T20:10:34
32,288,341
0
0
null
null
null
null
UTF-8
C++
false
false
670
cpp
#include "cGSGameOver.h" #include "cGSMenu.h" #include "cMouse.h" #include "cGame.h" #include "cGSIngame.h" void cGSGameOver::Enter() { cGame::GetInstance()->GetSound()->stopCancion(); cGame::GetInstance()->GetSound()->pausar(30); cGame::GetInstance()->GetSound()->playEfecto("over"); } bool cGSGameOver::Process() { cGame *Game = cGame::GetInstance(); cKeyboard *KeyBoard = cInputLayer::GetInstance()->GetKeyboard(); if (KeyBoard->KeyDown(DIK_SPACE)) { Game->ChangeState(Game->menu); } return true; } bool cGSGameOver::Render() { return cGraphicsLayer::GetInstance()->RenderGameOver(); } void cGSGameOver::Exit() { }
[ "[email protected]@5f958858-fb9a-a521-b75c-3c5ff6351dd8", "[email protected]@5f958858-fb9a-a521-b75c-3c5ff6351dd8" ]
[ [ [ 1, 4 ], [ 6, 8 ], [ 12, 20 ], [ 22, 35 ] ], [ [ 5, 5 ], [ 9, 11 ], [ 21, 21 ] ] ]
5ea1b3dbb2767d75e3ce4e77aed8fd0d58fbfd25
f8403b6b1005f80d2db7fad9ee208887cdca6aec
/JuceLibraryCode/modules/juce_core/streams/juce_InputStream.cpp
1fd2994d110bb0d3431cc0439b7a1ff7036eba18
[]
no_license
sonic59/JuceText
25544cb07e5b414f9d7109c0826a16fc1de2e0d4
5ac010ffe59c2025d25bc0f9c02fc829ada9a3d2
refs/heads/master
2021-01-15T13:18:11.670907
2011-10-29T19:03:25
2011-10-29T19:03:25
2,507,112
0
0
null
null
null
null
UTF-8
C++
false
false
5,811
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ BEGIN_JUCE_NAMESPACE //============================================================================== char InputStream::readByte() { char temp = 0; read (&temp, 1); return temp; } bool InputStream::readBool() { return readByte() != 0; } short InputStream::readShort() { char temp[2]; if (read (temp, 2) == 2) return (short) ByteOrder::littleEndianShort (temp); return 0; } short InputStream::readShortBigEndian() { char temp[2]; if (read (temp, 2) == 2) return (short) ByteOrder::bigEndianShort (temp); return 0; } int InputStream::readInt() { char temp[4]; if (read (temp, 4) == 4) return (int) ByteOrder::littleEndianInt (temp); return 0; } int InputStream::readIntBigEndian() { char temp[4]; if (read (temp, 4) == 4) return (int) ByteOrder::bigEndianInt (temp); return 0; } int InputStream::readCompressedInt() { const uint8 sizeByte = (uint8) readByte(); if (sizeByte == 0) return 0; const int numBytes = (sizeByte & 0x7f); if (numBytes > 4) { jassertfalse; // trying to read corrupt data - this method must only be used // to read data that was written by OutputStream::writeCompressedInt() return 0; } char bytes[4] = { 0, 0, 0, 0 }; if (read (bytes, numBytes) != numBytes) return 0; const int num = (int) ByteOrder::littleEndianInt (bytes); return (sizeByte >> 7) ? -num : num; } int64 InputStream::readInt64() { union { uint8 asBytes[8]; uint64 asInt64; } n; if (read (n.asBytes, 8) == 8) return (int64) ByteOrder::swapIfBigEndian (n.asInt64); return 0; } int64 InputStream::readInt64BigEndian() { union { uint8 asBytes[8]; uint64 asInt64; } n; if (read (n.asBytes, 8) == 8) return (int64) ByteOrder::swapIfLittleEndian (n.asInt64); return 0; } float InputStream::readFloat() { // the union below relies on these types being the same size... static_jassert (sizeof (int32) == sizeof (float)); union { int32 asInt; float asFloat; } n; n.asInt = (int32) readInt(); return n.asFloat; } float InputStream::readFloatBigEndian() { union { int32 asInt; float asFloat; } n; n.asInt = (int32) readIntBigEndian(); return n.asFloat; } double InputStream::readDouble() { union { int64 asInt; double asDouble; } n; n.asInt = readInt64(); return n.asDouble; } double InputStream::readDoubleBigEndian() { union { int64 asInt; double asDouble; } n; n.asInt = readInt64BigEndian(); return n.asDouble; } String InputStream::readString() { MemoryBlock buffer (256); char* data = static_cast<char*> (buffer.getData()); size_t i = 0; while ((data[i] = readByte()) != 0) { if (++i >= buffer.getSize()) { buffer.setSize (buffer.getSize() + 512); data = static_cast<char*> (buffer.getData()); } } return String::fromUTF8 (data, (int) i); } String InputStream::readNextLine() { MemoryBlock buffer (256); char* data = static_cast<char*> (buffer.getData()); size_t i = 0; while ((data[i] = readByte()) != 0) { if (data[i] == '\n') break; if (data[i] == '\r') { const int64 lastPos = getPosition(); if (readByte() != '\n') setPosition (lastPos); break; } if (++i >= buffer.getSize()) { buffer.setSize (buffer.getSize() + 512); data = static_cast<char*> (buffer.getData()); } } return String::fromUTF8 (data, (int) i); } int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes) { MemoryOutputStream mo (block, true); return mo.writeFromInputStream (*this, numBytes); } String InputStream::readEntireStreamAsString() { MemoryOutputStream mo; mo << *this; return mo.toString(); } //============================================================================== void InputStream::skipNextBytes (int64 numBytesToSkip) { if (numBytesToSkip > 0) { const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384); HeapBlock<char> temp ((size_t) skipBufferSize); while (numBytesToSkip > 0 && ! isExhausted()) numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize)); } } END_JUCE_NAMESPACE
[ [ [ 1, 228 ] ] ]
0879830afe63b73c7370075c62a60ee22107bd4a
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_1_023.cpp
4a926b5a5554d6851c96dfadf0eccc4d5de573e2
[ "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
769
cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2006 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // Tests, if function-like macros buried deep inside a macro expansion of the // same name as an object-like macro do not eat up more tokens, than expected. #define PRIMITIVE_CAT(a, b) a ## b #define EAT(n) PRIMITIVE_CAT(EAT_, n) #define EAT_1(a) //R #line 20 "t_1_023.cpp" //R EAT_1... EAT(1)...
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 20 ] ] ]
6c59dd88206eaf95f96a0b67cf14b5409378b6ea
113b284df51a798c943e36aaa21273e7379391a9
/RecycleBinGadget/RecycleBinDLL/XWinVer.cpp
66b005a0e6d295a50f960ba5e7b46f0af3e4fc0f
[]
no_license
ccMatrix/desktopgadgets
bf171b75b446faf16443202c06e98c0a4b5eef7c
f5fa36e042ce274910f62e5d3510072ae07acf5e
refs/heads/master
2020-12-25T19:26:10.514144
2010-03-01T23:24:15
2010-03-01T23:24:15
32,254,664
1
1
null
null
null
null
UTF-8
C++
false
false
9,900
cpp
// XWinVer.cpp Version 1.1 // // Author: Hans Dietrich // [email protected] // // Description: // XWinVer implements CXWinVersion, a singleton class to retrieve // the Windows OS version. Please see article at // www.codeproject.com. // // History // Version 1.1 - 2005 March 14 // - Initial public release // // Public APIs: // NAME DESCRIPTION // --------------------- ------------------------------------------------- // GetMajorVersion() Get major version number // GetMinorVersion() Get minor version number // GetBuildNumber() Get build number (ANDed with 0xFFFF for Win9x) // GetServicePackNT() Get service pack number // GetServicePackString() Get service pack string // GetWinVersion() Get windows version (CXWinVersion code) // GetWinVersionString() Get windows version as string // IsWin2KorLater() TRUE = Win2000 or later // IsWin2003() TRUE = Win2003 // IsXP() TRUE = XP // IsXPorLater() TRUE = XP or later // IsXPHome() TRUE = XP Home // IsXPPro() TRUE = XP Pro // IsXPSP2() TRUE = XP SP2 // // License: // This software is released into the public domain. You are free to use // it in any way you like, except that you may not sell this source code. // // 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" #define XWINVER_CPP #include "XWinVer.h" // from winbase.h #ifndef VER_PLATFORM_WIN32_WINDOWS #define VER_PLATFORM_WIN32_WINDOWS 1 #endif #ifndef VER_PLATFORM_WIN32_NT #define VER_PLATFORM_WIN32_NT 2 #endif #ifndef VER_PLATFORM_WIN32_CE #define VER_PLATFORM_WIN32_CE 3 #endif // from winnt.h #ifndef VER_NT_WORKSTATION #define VER_NT_WORKSTATION 0x0000001 #endif #ifndef VER_SUITE_PERSONAL #define VER_SUITE_PERSONAL 0x00000200 #endif /////////////////////////////////////////////////////////////////////////////// /* This table has been assembled from Usenet postings, personal observations, and reading other people's code. Please feel free to add to it or correct it. dwPlatFormID dwMajorVersion dwMinorVersion dwBuildNumber 95 1 4 0 950 95 SP1 1 4 0 >950 && <=1080 95 OSR2 1 4 <10 >1080 98 1 4 10 1998 98 SP1 1 4 10 >1998 && <2183 98 SE 1 4 10 >=2183 ME 1 4 90 3000 NT 3.51 2 3 51 1057 NT 4 2 4 0 1381 2000 2 5 0 2195 XP 2 5 1 2600 2003 2 5 2 3790 CE 1.0 3 1 0 CE 2.0 3 2 0 CE 2.1 3 2 1 CE 3.0 3 3 0 */ /////////////////////////////////////////////////////////////////////////////// // per process data BOOL CXWinVersion::m_bInitialized = FALSE; CXWinVersion::OSVERSIONINFOEXX CXWinVersion::m_osinfo = { 0 }; /////////////////////////////////////////////////////////////////////////////// // Init void CXWinVersion::Init() { TRACE(_T("in CXWinVersion::Init\n")); ZeroMemory(&m_osinfo, sizeof(m_osinfo)); m_osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (GetVersionEx((LPOSVERSIONINFO) &m_osinfo)) { m_bInitialized = TRUE; if ((m_osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) && (m_osinfo.dwMajorVersion >= 5)) { // get extended version info for 2000 and later ZeroMemory(&m_osinfo, sizeof(m_osinfo)); m_osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); GetVersionEx((LPOSVERSIONINFO) &m_osinfo); } } } /////////////////////////////////////////////////////////////////////////////// // GetWinVersionString CString CXWinVersion::GetWinVersionString() { CString strVersion = WUNKNOWNSTR; int nVersion = GetWinVersion(); switch (nVersion) { default: case WUNKNOWN: break; case W95: strVersion = W95STR; break; case W95SP1: strVersion = W95SP1STR; break; case W95OSR2: strVersion = W95OSR2STR; break; case W98: strVersion = W98STR; break; case W98SP1: strVersion = W98SP1STR; break; case W98SE: strVersion = W98SESTR; break; case WME: strVersion = WMESTR; break; case WNT351: strVersion = WNT351STR; break; case WNT4: strVersion = WNT4STR; break; case W2K: strVersion = W2KSTR; break; case WXP: strVersion = WXPSTR; break; case W2003: strVersion = W2003STR; break; case WCE: strVersion = WCESTR; break; } return strVersion; } /////////////////////////////////////////////////////////////////////////////// // GetWinVersion int CXWinVersion::GetWinVersion() { int nVersion = WUNKNOWN; DWORD dwPlatformId = m_osinfo.dwPlatformId; DWORD dwMinorVersion = m_osinfo.dwMinorVersion; DWORD dwMajorVersion = m_osinfo.dwMajorVersion; DWORD dwBuildNumber = m_osinfo.dwBuildNumber & 0xFFFF; // Win 9x needs this if ((dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) && (dwMajorVersion == 4)) { if ((dwMinorVersion < 10) && (dwBuildNumber == 950)) { nVersion = W95; } else if ((dwMinorVersion < 10) && ((dwBuildNumber > 950) && (dwBuildNumber <= 1080))) { nVersion = W95SP1; } else if ((dwMinorVersion < 10) && (dwBuildNumber > 1080)) { nVersion = W95OSR2; } else if ((dwMinorVersion == 10) && (dwBuildNumber == 1998)) { nVersion = W98; } else if ((dwMinorVersion == 10) && ((dwBuildNumber > 1998) && (dwBuildNumber < 2183))) { nVersion = W98SP1; } else if ((dwMinorVersion == 10) && (dwBuildNumber >= 2183)) { nVersion = W98SE; } else if (dwMinorVersion == 90) { nVersion = WME; } } else if (dwPlatformId == VER_PLATFORM_WIN32_NT) { if ((dwMajorVersion == 3) && (dwMinorVersion == 51)) { nVersion = WNT351; } else if ((dwMajorVersion == 4) && (dwMinorVersion == 0)) { nVersion = WNT4; } else if ((dwMajorVersion == 5) && (dwMinorVersion == 0)) { nVersion = W2K; } else if ((dwMajorVersion == 5) && (dwMinorVersion == 1)) { nVersion = WXP; } else if ((dwMajorVersion == 5) && (dwMinorVersion == 2)) { nVersion = W2003; } } else if (dwPlatformId == VER_PLATFORM_WIN32_CE) { nVersion = WCE; } return nVersion; } /////////////////////////////////////////////////////////////////////////////// // GetServicePackNT - returns a valid service pack number only for NT platform int CXWinVersion::GetServicePackNT() { int nServicePack = 0; for (int i = 0; (m_osinfo.szCSDVersion[i] != _T('\0')) && (i < (sizeof(m_osinfo.szCSDVersion)/sizeof(TCHAR))); i++) { if (_istdigit(m_osinfo.szCSDVersion[i])) { nServicePack = _ttoi(&m_osinfo.szCSDVersion[i]); break; } } return nServicePack; } /////////////////////////////////////////////////////////////////////////////// // IsXP BOOL CXWinVersion::IsXP() { if (GetWinVersion() == WXP) { return TRUE; } return FALSE; } /////////////////////////////////////////////////////////////////////////////// // IsXPHome BOOL CXWinVersion::IsXPHome() { if (GetWinVersion() == WXP) { if (m_osinfo.wSuiteMask & VER_SUITE_PERSONAL) return TRUE; } return FALSE; } /////////////////////////////////////////////////////////////////////////////// // IsXPPro BOOL CXWinVersion::IsXPPro() { if (GetWinVersion() == WXP) { if ((m_osinfo.wProductType == VER_NT_WORKSTATION) && !IsXPHome()) return TRUE; } return FALSE; } /////////////////////////////////////////////////////////////////////////////// // IsXPSP2 BOOL CXWinVersion::IsXPSP2() { if (GetWinVersion() == WXP) { if (GetServicePackNT() == 2) return TRUE; } return FALSE; } /////////////////////////////////////////////////////////////////////////////// // IsWin2003 BOOL CXWinVersion::IsWin2003() { if ((m_osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) && (m_osinfo.dwMajorVersion == 5) && (m_osinfo.dwMinorVersion == 2)) return TRUE; return FALSE; } /////////////////////////////////////////////////////////////////////////////// // IsWin2KorLater BOOL CXWinVersion::IsWin2KorLater() { if ((m_osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) && (m_osinfo.dwMajorVersion >= 5)) return TRUE; return FALSE; } /////////////////////////////////////////////////////////////////////////////// // IsXPorLater BOOL CXWinVersion::IsXPorLater() { if ((m_osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) && (((m_osinfo.dwMajorVersion == 5) && (m_osinfo.dwMinorVersion > 0)) || (m_osinfo.dwMajorVersion > 5))) return TRUE; return FALSE; } /////////////////////////////////////////////////////////////////////////////// // IsVistaOrLater BOOL CXWinVersion::IsVistaOrLater() { if ((m_osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) && (((m_osinfo.dwMajorVersion == 6) && (m_osinfo.dwMinorVersion > 0)) || (m_osinfo.dwMajorVersion > 6))) return TRUE; return FALSE; }
[ "codename.matrix@e00a1d1f-563d-0410-a555-bbce3309907e" ]
[ [ [ 1, 349 ] ] ]
08458e505138f3b9db20bee148c48b130fe2442a
6fd162d2cade2db745e68f11d7e9722a3855f033
/Include/S3UT/S3UTskybox.h
d3357aaf431c3cde1a17a134879237bbe5b75243
[]
no_license
SenichiFSeiei/oursavsm
8f418325bc9883bcb245e139dbd0249e72c18d78
379e77cab67b3b1423a4c6f480b664f79b03afa9
refs/heads/master
2021-01-10T21:00:52.797565
2010-04-27T13:18:19
2010-04-27T13:18:19
41,737,615
0
0
null
null
null
null
UTF-8
C++
false
false
2,465
h
//---------------------------------------------------------------------------------- // File: S3UTSkybox.h // Email: [email protected] // // Copyright (c) 2007 S3Graphics Corporation. All rights reserved. // // TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED // *AS IS* AND S3Graphics AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS // OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL S3Graphics OR ITS SUPPLIERS // BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES // WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, // BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) // ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF S3Graphics HAS // BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. // // //---------------------------------------------------------------------------------- // Desc: Encapsulation of skybox geometry and textures #pragma once #ifndef S3UTSKYBOX_H #define S3UTSKYBOX_H #include <DXUT.h> #include <SDKmisc.h> class S3UTSkybox { public: S3UTSkybox(); ~S3UTSkybox(); HRESULT OnCreateDevice( ID3D10Device* pd3dDevice ); void OnResizedSwapChain( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC *pBackBufferSurfaceDesc ); void OnReleasingSwapChain(); void OnFrameRender( const D3DXMATRIX &mWVP ); void OnFrameRender( const D3DXMATRIX &mWVP, float SkyboxIntensity, const D3DXVECTOR4& FloorColor ); void OnDestroyDevice(); void SetTexture( ID3D10ShaderResourceView* ppEnvCubeRV ); protected: // Texture resource views ID3D10ShaderResourceView * m_EnvTex; // The device ID3D10Device * m_d3dDevice; // Vertex layout ID3D10InputLayout * m_VertexLayout; ID3D10Buffer * m_VertexBuffer, * m_IndexBuffer; // The effects and rendering techniques ID3D10Effect * m_Effect; ID3D10EffectTechnique * m_Technique, *m_TechniqueWithColor; ID3D10ShaderResourceView * m_EnvMap; // Effect variable pointers ID3D10EffectMatrixVariable * m_VarInvWVP; ID3D10EffectShaderResourceVariable * m_VarEnvMap; ID3D10EffectVectorVariable * m_VarFloorColor; ID3D10EffectScalarVariable * m_VarSkyboxIntensity; }; #endif
[ [ [ 1, 70 ] ] ]
3d7021da7a225163daddc14073251840ad6411a3
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/validators/DTD/DTDAttDefList.cpp
16236c7be2f78e47ed9266b657c245a8c9f81954
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
5,532
cpp
/* * 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: DTDAttDefList.cpp 191054 2005-06-17 02:56:35Z jberry $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/validators/DTD/DTDAttDefList.hpp> #include <xercesc/internal/XTemplateSerializer.hpp> #include <xercesc/util/ArrayIndexOutOfBoundsException.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // DTDAttDefList: Constructors and Destructor // --------------------------------------------------------------------------- DTDAttDefList::DTDAttDefList(RefHashTableOf<DTDAttDef>* const listToUse, MemoryManager* const manager) : XMLAttDefList(manager) ,fEnum(0) ,fList(listToUse) ,fArray(0) ,fSize(0) ,fCount(0) { fEnum = new (getMemoryManager()) RefHashTableOfEnumerator<DTDAttDef>(listToUse, false, manager); fArray = (DTDAttDef **)(manager->allocate( sizeof(DTDAttDef*) << 1)); fSize = 2; } DTDAttDefList::~DTDAttDefList() { delete fEnum; (getMemoryManager())->deallocate(fArray); } // --------------------------------------------------------------------------- // DTDAttDefList: Implementation of the virtual interface // --------------------------------------------------------------------------- bool DTDAttDefList::hasMoreElements() const { return fEnum->hasMoreElements(); } bool DTDAttDefList::isEmpty() const { return fList->isEmpty(); } XMLAttDef* DTDAttDefList::findAttDef(const unsigned long , const XMLCh* const attName) { // We don't use the URI, so we just look up the name return fList->get(attName); } const XMLAttDef* DTDAttDefList::findAttDef( const unsigned long , const XMLCh* const attName) const { // We don't use the URI, so we just look up the name return fList->get(attName); } XMLAttDef* DTDAttDefList::findAttDef( const XMLCh* const , const XMLCh* const attName) { // We don't use the URI, so we just look up the name return fList->get(attName); } const XMLAttDef* DTDAttDefList::findAttDef( const XMLCh* const , const XMLCh* const attName) const { // We don't use the URI, so we just look up the name return fList->get(attName); } XMLAttDef& DTDAttDefList::nextElement() { return fEnum->nextElement(); } void DTDAttDefList::Reset() { fEnum->Reset(); } /** * return total number of attributes in this list */ unsigned int DTDAttDefList::getAttDefCount() const { return fCount; } /** * return attribute at the index-th position in the list. */ XMLAttDef &DTDAttDefList::getAttDef(unsigned int index) { if(index >= fCount) ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex, getMemoryManager()); return *(fArray[index]); } /** * return attribute at the index-th position in the list. */ const XMLAttDef &DTDAttDefList::getAttDef(unsigned int index) const { if(index >= fCount) ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex, getMemoryManager()); return *(fArray[index]); } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(DTDAttDefList) void DTDAttDefList::serialize(XSerializeEngine& serEng) { XMLAttDefList::serialize(serEng); if (serEng.isStoring()) { /*** * * Serialize RefHashTableOf<DTDAttDef> * ***/ XTemplateSerializer::storeObject(fList, serEng); serEng << fCount; // do not serialize fEnum } else { /*** * * Deserialize RefHashTableOf<DTDAttDef> * ***/ XTemplateSerializer::loadObject(&fList, 29, true, serEng); // assume empty so we can size fArray just right serEng >> fSize; if (!fEnum && fList) { fEnum = new (getMemoryManager()) RefHashTableOfEnumerator<DTDAttDef>(fList, false, getMemoryManager()); } if(fSize) { (getMemoryManager())->deallocate(fArray); fArray = (DTDAttDef **)((getMemoryManager())->allocate( sizeof(DTDAttDef*) * fSize)); fCount = 0; while(fEnum->hasMoreElements()) { fArray[fCount++] = &fEnum->nextElement(); } } } } DTDAttDefList::DTDAttDefList(MemoryManager* const manager) : XMLAttDefList(manager) ,fEnum(0) ,fList(0) ,fArray(0) ,fSize(0) ,fCount(0) { } XERCES_CPP_NAMESPACE_END
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 205 ] ] ]
11ac47346fea6a045fe673b155e8400384e42254
e9944cc3f8c362cd0314a2d7a01291ed21de19ee
/ xcommon/btnexgenipl/examples/Codecs/BTCEncoderYUV.cpp
574494200c3f799a0398c9ef2e4bdc8e9d8ce89e
[]
no_license
wermanhme1990/xcommon
49d7185a28316d46992ad9311ae9cdfe220cb586
c9b1567da1f11e7a606c6ed638a9fde1f6ece577
refs/heads/master
2016-09-06T12:43:43.593776
2008-12-05T04:24:11
2008-12-05T04:24:11
39,864,906
2
0
null
null
null
null
UTF-8
C++
false
false
2,786
cpp
#include "stdafx.h" #include "BTDefines.h" #include "BTCEncoderYUV.h" BTCEncoderYUV::BTCEncoderYUV() { } BTCEncoderYUV::~BTCEncoderYUV() { } ///////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////// const bt_char *BTCEncoderYUV::GetFormat() { return _BTTEXT("YUV"); } const bt_char *BTCEncoderYUV::GetDescription() { return _BTTEXT("ITU-R BT 601 (CCIR 601) 4:2:2"); } const bt_char *BTCEncoderYUV::GetExtension() { return _BTTEXT("yuv"); } ///////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////// bool BTCEncoderYUV::Save(BTCOStream* pOStream, BTCImageData* pImageData, BTINotification* pNotification, BTCEncoderOptions* pOptions) { if(!pOStream || !pImageData) return false; int nWidth = pImageData->GetWidth(); int nHeight = pImageData->GetHeight(); // Check whether the image has the correct image size. if(!((nHeight == 576 || nHeight == 486) && (nWidth == 360 || nWidth == 720))) return false; BTCOLORREF col; unsigned char uyvy[4]; double r, g, b, Y1, Cb1, Cr1, Y2, Cb2, Cr2; for( register int y = 0; y < nHeight; y++) { for( register int x = 0; x < nWidth;) { col = pImageData->GetColorFromPixel( x++, y); r = BTGetRValue( col); g = BTGetGValue( col); b = BTGetBValue( col); /* Rec 601-1: Y = 0.299 * r + 0.587 * g + 0.114 * b; Cb = (b - Y) / (2 - 2 * 0.114); Cr = (r - Y) / (2 - 2 * 0.299); Rec 709: Y = 0.2125 * r + 0.7154 * g + 0.0721 * b; Cb = (b - Y) / (2 - 2 * 0.0721); Cr = (r - Y) / (2 - 2 * 0.2125); */ Y1 = 0.299 * r + 0.587 * g + 0.114 * b; Cb1 = (b - Y1) / (2. - 2. * 0.114); Cr1 = (r - Y1) / (2. - 2. * 0.299); col = pImageData->GetColorFromPixel( x++, y); r = BTGetRValue( col); g = BTGetGValue( col); b = BTGetBValue( col); Y2 = 0.299 * r + 0.587 * g + 0.114 * b; Cb2 = (b - Y2) / (2. - 2. * 0.114); Cr2 = (r - Y2) / (2. - 2. * 0.299); uyvy[0] = (unsigned char)((128. + (Cb1 + Cb2) / 2) * 224./255.+ 16.); // u uyvy[1] = (unsigned char)(Y1 * 219./255. + 16.); // y1 uyvy[2] = (unsigned char)((128. + (Cr1 + Cr2) / 2) * 224./255.+ 16.); // v uyvy[3] = (unsigned char)(Y2 * 219./255. + 16.); // y2 pOStream->Write( &uyvy, 4); } if( pNotification) // Step progress. pNotification->OnProgress( (int)((100.0 / nHeight) * y) + 1); } return true; }
[ [ [ 1, 94 ] ] ]
1f84dbe60f25f0d82f6c4c8cb3bf0a0fb7c9b26a
c3ae23286c2e8268355241f8f06cd1309922a8d6
/rateracerlib/shapes/Plane.h
10cdaffb6ed65602da573bc2de85770e9bd06193
[]
no_license
BackupTheBerlios/rateracer-svn
2f43f020ecdd8a3528880d474bec1c0464879597
838ad3f326962028ce8d493d2c06f6af6ea4664c
refs/heads/master
2020-06-04T03:31:51.633612
2005-05-30T06:38:01
2005-05-30T06:38:01
40,800,078
0
0
null
null
null
null
UTF-8
C++
false
false
1,440
h
#pragma once #include "Shape.h" #include "Stratification.h" class Plane : public Shape { public: Plane(Vec3 Normal, float Offset) { N = Normal; offset = Offset; } virtual ~Plane() {} Vec3 N; float offset; float collideRay(const Ray& r) { float divider = dot(r.dir, N); if (fabsf(divider) < cEpsilon) return -1; return (offset - dot(r.ori, N)) / divider; } Vec3 getNormal(const Vec3& p) { return N; } /* Vec3 getTangent(const Vec3& p) { // TODO: make something better here? return cross( N, p ).normalizeSafely(); } */ Vec2 getUV(const Vec3& p) { //if (fabsf(p[0]) < 0.5f && fabsf(p[2]) < 0.5f) { return Vec2(p[0] + 0.5f, p[2] + 0.5f); } } void drawPreview() { material->setPreviewMaterial(); glPushMatrix(); Vec3 T = offset * N; glTranslatef(T[0], T[1], T[2]); glMultMatrixf(&createONBasis(N)[0][0]); glDisable(GL_LIGHTING); const float size = 100; // TODO: calc transform to orient the plane in space /* const int slices = 30, loops = 10; GLUquadricObj *q = gluNewQuadric(); gluDisk(q, 0, size, slices, loops); gluDeleteQuadric(q); */ glNormal3fv(&N[0]); glBegin(GL_QUADS); glVertex3f(-size, -size, 0); glVertex3f( size, -size, 0); glVertex3f( size, size, 0); glVertex3f(-size, size, 0); glEnd(); glEnable(GL_LIGHTING); glPopMatrix(); } };
[ "gweronimo@afd64b18-8dda-0310-837d-b02fe5df315d" ]
[ [ [ 1, 82 ] ] ]
8a3bcf6df6244b7c87f7b1a6f9edf0c54a93f73c
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Models/CONTROL1/SchedTsk.cpp
287af9d2ad8f3fe2e8dfcff9c14963a4815c81fa
[]
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
24,581
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #include "sc_defs.h" #include "pgm_e.h" #include "schedtsk.h" #include "scd_wm.h" //#include "optoff.h" //========================================================================== const byte MT_Macro = SUB_REPORT_MACRO; const byte MT_TagRep = SUB_REPORT_GETVALUES; const byte MT_TrendRep = SUB_REPORT_TREND; const byte MT_SetTags = SUB_REPORT_SETVALUES; const byte STT_None = 0; const byte STT_Count = 1; const byte STT_Time = 2; const int MaxRepTags = 10; const word idmScrFolder = 1050; const word idmScrEditBtn = 1051; const word idmScrBrowseBtn = 1052; const word idmScrExecBtn = 1053; const word idmMcrFolder = 1060; const word idmMcrEditBtn = 1061; const word idmMcrBrowseBtn = 1062; const word idmMcrExecBtn = 1063; const word idmRepFolder = 1070; const word idmRepEditBtn = 1071; const word idmRepBrowseBtn = 1072; const word idmRepExecBtn = 1073; const word idmRepEndTime = 1074; const word idmRepTagCnt = 1075; const word idmRepTag = 1076; //leave MaxRepTags free after this ScheduleTask::ScheduleTask() { bScrOn = 0; sScrPath = PrjFiles(); iScrSchedType = STT_Count; iScrExecCnt = 100; iScrIterCnt = 0; dScrExecTime = 3600.0; dScrIterTime = 0.0; hScrProcess = NULL; bMcrOn = 0; sMcrPath = PrjFiles(); iMcrSchedType = STT_None; iMcrExecCnt = 100; iMcrIterCnt = 0; dMcrExecTime = 3600.0; dMcrIterTime = 0.0; iMcrType = MT_Macro; sMcrName = "*"; bRepOn = 0; sRepPath = PrjFiles(); iRepSchedType = STT_None; iRepExecCnt = 100; iRepIterCnt = 0; dRepExecTime = 3600.0; dRepIterTime = 0.0; sRepTblName = "History"; iRepTagCnt = 4; RepTags.SetSize(iRepTagCnt); iRepPtsCnt = 61; dRepDuration= 3600.0; sRepEndTime = "*"; } //-------------------------------------------------------------------------- void ScheduleTask::BuildDataDefn(DataDefnBlk & DDB, TaggedObject* pObj) { //DDB.Page("SchedTask", DDB_RqdPage); static DDBValueLst DDBSchedType[]= { {STT_None, "None" }, {STT_Count, "Iter Count" }, {STT_Time, "Sim Time" }, {0} }; if (DDB.BeginStruct(pObj, "Scr", NULL, DDB_NoPage)) { DDB.Text(""); DDB.Text("Schedule SysCAD Script..."); DDB.CheckBoxBtn("On", "", DC_, "", &bScrOn, pObj, isParm, DDBYesNo); DDB.String("Status", "", DC_, "", &sScrStatus, pObj, isResult|noFileAtAll); DDB.String("Folder", "", DC_, "", idmScrFolder, pObj, isResult); DDB.String("File", "", DC_, "", &sScrFile, pObj, isParm); DDB.Button("Edit_ssc", "", DC_, "", idmScrEditBtn, pObj, isParm); DDB.Button("Browse_ssc", "", DC_, "", idmScrBrowseBtn, pObj, isParm); DDB.Button("Execute_Now", "", DC_, "", idmScrExecBtn, pObj, isParm); DDB.Byte ("SchedType", "", DC_, "", &iScrSchedType, pObj, isParm, DDBSchedType); DDB.Visibility(NSHM_All, iScrSchedType==STT_Count); DDB.Long ("ExecCnt", "", DC_, "", &iScrExecCnt, pObj, isParm); DDB.Long ("IterCnt", "", DC_, "", &iScrIterCnt, pObj, isParm); DDB.Visibility(NSHM_All, iScrSchedType==STT_Time); DDB.Double("ExecTime", "", DC_Time, "s", &dScrExecTime, pObj, isParm); DDB.Double("SimTime", "", DC_Time, "s", &dScrIterTime, pObj, isParm); DDB.Visibility(); DDB.Text(""); } DDB.EndStruct(); static DDBValueLst DDBMcrType[]= { {MT_Macro, "Macro" }, {MT_TagRep, "Tag Report" }, {MT_TrendRep, "Trend Report" }, {MT_SetTags, "Set Tags" }, {0} }; if (DDB.BeginStruct(pObj, "Mcr", NULL, DDB_NoPage)) { DDB.Text(""); DDB.Text("Schedule Excel Report or Macro..."); DDB.CheckBoxBtn("On", "", DC_, "", &bMcrOn, pObj, isParm, DDBYesNo); DDB.String("Status", "", DC_, "", &sMcrStatus, pObj, isResult|noFileAtAll); DDB.String("Folder", "", DC_, "", idmMcrFolder, pObj, isResult); DDB.String("File", "", DC_, "", &sMcrFile, pObj, isParm); DDB.Byte ("Type", "", DC_, "", &iMcrType, pObj, isParm, DDBMcrType); DDB.String("Name", "", DC_, "", &sMcrName, pObj, isParm); DDB.Button("Edit_xls", "", DC_, "", idmMcrEditBtn, pObj, isParm); DDB.Button("Browse_xls", "", DC_, "", idmMcrBrowseBtn, pObj, isParm); DDB.Button("Execute_Now", "", DC_, "", idmMcrExecBtn, pObj, isParm); DDB.Byte ("SchedType", "", DC_, "", &iMcrSchedType, pObj, isParm, DDBSchedType); DDB.Visibility(NSHM_All, iMcrSchedType==STT_Count); DDB.Long ("ExecCnt", "", DC_, "", &iMcrExecCnt, pObj, isParm); DDB.Long ("IterCnt", "", DC_, "", &iMcrIterCnt, pObj, isParm); DDB.Visibility(NSHM_All, iMcrSchedType==STT_Time); DDB.Double("ExecTime", "", DC_Time, "s", &dMcrExecTime, pObj, isParm); DDB.Double("SimTime", "", DC_Time, "s", &dMcrIterTime, pObj, isParm); DDB.Visibility(); DDB.Text(""); } DDB.EndStruct(); DDB.Page("MDB_Trend", DDB_RqdPage); if (DDB.BeginStruct(pObj, "Rep", NULL, DDB_NoPage)) { DDB.Text(""); DDB.Text("Trend MDB Report..."); DDB.CheckBoxBtn("On", "", DC_, "", &bRepOn, pObj, isParmStopped, DDBYesNo); DDB.String("Status", "", DC_, "", &sRepStatus, pObj, isResult|noFileAtAll); DDB.String("Folder", "", DC_, "", idmRepFolder, pObj, isResult); DDB.String("File", "", DC_, "", &sRepFile, pObj, isParm); DDB.String("TableName", "", DC_, "", &sRepTblName, pObj, isParm); DDB.Long ("NoOfPoints", "", DC_, "", &iRepPtsCnt, pObj, isParm); DDB.Double("Duration", "", DC_Time, "s", &dRepDuration, pObj, isParm); DDB.String("EndTime", "", DC_, "", idmRepEndTime, pObj, isParm); DDB.Long ("NoOfTags", "", DC_, "", idmRepTagCnt, pObj, isParm); char Buff[16]; for (int i=0; i<iRepTagCnt; i++) { sprintf(Buff, "Tag%d", i); DDB.String(Buff, "", DC_, "", idmRepTag+i, pObj, isParm|isTag); } DDB.Button("Browse_mdb", "", DC_, "", idmRepBrowseBtn, pObj, isParm); DDB.Button("Execute_Now", "", DC_, "", idmRepExecBtn, pObj, isParm); DDB.Byte ("SchedType", "", DC_, "", &iRepSchedType, pObj, isParm, DDBSchedType); DDB.Visibility(NSHM_All, iRepSchedType==STT_Count); DDB.Long ("ExecCnt", "", DC_, "", &iRepExecCnt, pObj, isParm); DDB.Long ("IterCnt", "", DC_, "", &iRepIterCnt, pObj, isParm); DDB.Visibility(NSHM_All, iRepSchedType==STT_Time); DDB.Double("ExecTime", "", DC_Time, "s", &dRepExecTime, pObj, isParm); DDB.Double("SimTime", "", DC_Time, "s", &dRepIterTime, pObj, isParm); DDB.Visibility(); DDB.Text(""); } DDB.EndStruct(); } //-------------------------------------------------------------------------- flag ScheduleTask::DataXchg(DataChangeBlk & DCB, TaggedObject* pObj) { switch (DCB.lHandle) { case idmScrFolder: if (DCB.rpC!=NULL) { // Dont Set if coming from snapshot ??? sScrPath = DCB.rpC; sScrPath.FnContract(); } if (DCB.ForView()) { if (SymbolicPaths()) sScrPath.FnContract(); else sScrPath.FnExpand(); DCB.pC = sScrPath(); } else { sScrPath.FnContract(); DCB.pC = sScrPath(); } return 1; case idmScrEditBtn: if (DCB.rB && (*DCB.rB!=0)) DCB.DoEditBtn(hScrProcess, dwScrProcessId, sScrPath(), sScrFile(), "ssc"); DCB.B=0; return 1; case idmScrBrowseBtn: if (DCB.rB && (*DCB.rB!=0)) DCB.DoBrowseBtn("ssc", "SysCAD Script", sScrPath, sScrFile); DCB.B=0; return 1; case idmScrExecBtn: if (DCB.rB && (*DCB.rB!=0)) ExecScr(); DCB.B=0; return 1; case idmMcrFolder: if (DCB.rpC!=NULL) { // Dont Set if coming from snapshot ??? sMcrPath = DCB.rpC; sMcrPath.FnContract(); } if (DCB.ForView()) { if (SymbolicPaths()) sMcrPath.FnContract(); else sMcrPath.FnExpand(); DCB.pC = sMcrPath(); } else { sMcrPath.FnContract(); DCB.pC = sMcrPath(); } return 1; case idmMcrEditBtn: if (DCB.rB && (*DCB.rB!=0)) { if (sMcrFile.Len()>0) { Strng Fn(sMcrPath); Fn.FnExpand(); Fn.FnCheckEndBSlash(); Fn += sMcrFile; CXM_OleExcelReport* pXB = new CXM_OleExcelReport(NULL, Fn(), "", SUB_REPORT_OPEN); AfxGetMainWnd()->SendMessage(WMU_CMD, SUB_CMD_GENERATEOLEREPORT, (LPARAM)pXB); } } DCB.B=0; return 1; case idmMcrBrowseBtn: if (DCB.rB && (*DCB.rB!=0)) DCB.DoBrowseBtn("xls", "Excel", sMcrPath, sMcrFile); DCB.B=0; return 1; case idmMcrExecBtn: if (DCB.rB && (*DCB.rB!=0)) ExecMcr(); DCB.B=0; return 1; case idmRepFolder: if (DCB.rpC!=NULL) { // Dont Set if coming from snapshot ??? sRepPath = DCB.rpC; sRepPath.FnContract(); } if (DCB.ForView()) { if (SymbolicPaths()) sRepPath.FnContract(); else sRepPath.FnExpand(); DCB.pC = sRepPath(); } else { sRepPath.FnContract(); DCB.pC = sRepPath(); } return 1; case idmRepEndTime: if (DCB.rpC) { flag EndTimeErr = false; sRepEndTime = DCB.rpC; if (sRepEndTime.Len()==0) sRepEndTime = "*"; if (_stricmp(sRepEndTime(), "*")!=0) { CTimeValue EndTime; if (!EndTime.Parse(sRepEndTime())) { EndTimeErr = true; } else { sRepEndTime = EndTime.Format(TD_TimeDate); if (_stricmp(sRepEndTime(), "?")==0) EndTimeErr = true; } } //pObj->SetCI(1, EndTimeErr); } DCB.pC = sRepEndTime(); return 1; case idmRepEditBtn: //if (DCB.rB) // ??? DCB.B=0; return 1; case idmRepBrowseBtn: if (DCB.rB && (*DCB.rB!=0)) DCB.DoBrowseBtn("mdb", "Access", sRepPath, sRepFile); DCB.B=0; return 1; case idmRepExecBtn: if (DCB.rB && (*DCB.rB!=0)) ExecRep(); DCB.B=0; return 1; case idmRepTagCnt: if (DCB.rL) { flag Chng = (*DCB.rL!=iRepTagCnt); iRepTagCnt = Range(0L, *DCB.rL, (long)MaxRepTags); RepTags.SetSize(iRepTagCnt); if (Chng) pObj->StructureChanged(pObj); } DCB.L = iRepTagCnt; return 1; default: if (DCB.lHandle>=idmRepTag)// && DCB.lHandle<idmRepTag+MaxRepTags) { ASSERT(DCB.lHandle<idmRepTag+MaxRepTags); const int index = DCB.lHandle-idmRepTag; /*if (index>=iRepTagCnt) {//for safety... iRepTagCnt = index+1; RepTags.SetSize(iRepTagCnt); }*/ if (DCB.rpC) RepTags[index] = DCB.rpC; DCB.pC = RepTags[index](); return 1; } } return false; } //-------------------------------------------------------------------------- void ScheduleTask::EvalDiscrete() { const double dT = ICGetTimeInc(); //script... iScrExecCnt = max(iScrExecCnt, 10L); dScrExecTime = max(dScrExecTime, 5.0); if (bScrOn) { if ((iScrSchedType==STT_Count) && iScrIterCnt>0) { sScrStatus = "Execute"; ldiv_t div_result; div_result = ldiv(iScrIterCnt, iScrExecCnt); if (div_result.rem==0) ExecScr(); } else if ((iScrSchedType==STT_Time) && dScrIterTime>0.0) { sScrStatus = "Execute"; const double d = dScrIterTime/dScrExecTime; if (d-(dScrIterTime*floor(d))<dT) ExecScr(); } else sScrStatus = "On"; } else sScrStatus = "Off"; iScrIterCnt++; dScrIterTime += dT; //excel macro... iMcrExecCnt = max(iMcrExecCnt, 10L); dMcrExecTime = max(dMcrExecTime, 5.0); if (bMcrOn) { if ((iMcrSchedType==STT_Count) && iMcrIterCnt>0) { sMcrStatus = "Execute"; ldiv_t div_result; div_result = ldiv(iMcrIterCnt, iMcrExecCnt); if (div_result.rem==0) ExecMcr(); } else if ((iMcrSchedType==STT_Time) && dMcrIterTime>0.0) { sMcrStatus = "Execute"; const double d = dMcrIterTime/dMcrExecTime; if (d-(dMcrIterTime*floor(d))<dT) ExecMcr(); } else sMcrStatus = "On"; } else sMcrStatus = "Off"; iMcrIterCnt++; dMcrIterTime += dT; //Report... iRepExecCnt = max(iRepExecCnt, 10L); dRepExecTime = max(dRepExecTime, 5.0); if (bRepOn) { if ((iRepSchedType==STT_Count) && iRepIterCnt>0) { sRepStatus = "Execute"; ldiv_t div_result; div_result = ldiv(iRepIterCnt, iRepExecCnt); if (div_result.rem==0) ExecRep(); } else if ((iRepSchedType==STT_Time) && dRepIterTime>0.0) { sRepStatus = "Execute"; const double d = dRepIterTime/dRepExecTime; if (d-(dRepIterTime*floor(d))<dT) ExecRep(); } else sRepStatus = "On"; } else sRepStatus = "Off"; iRepIterCnt++; dRepIterTime += dT; } //-------------------------------------------------------------------------- void ScheduleTask::ExecScr() { Strng Fn(sScrPath); Fn.FnExpand(); Fn.FnCheckEndBSlash(); Fn += sScrFile; if (FileExists(Fn())) { sScrStatus = "Ok"; char* pTxt = new char[Fn.Len()+1]; strcpy(pTxt, Fn()); //AfxGetMainWnd()->SendMessage(WMU_CMD, SUB_CMD_RUNSCRIPT, (LPARAM)pTxt); ScdMainWnd()->PostMessage(WMU_CMD, SUB_CMD_RUNSCRIPT, (LPARAM)pTxt); } else sScrStatus = "Specified file not found!"; } //-------------------------------------------------------------------------- void ScheduleTask::ExecMcr() { Strng Fn(sMcrPath); Fn.FnExpand(); Fn.FnCheckEndBSlash(); Fn += sMcrFile; if (FileExists(Fn())) { sMcrStatus = "Ok"; gs_Exec.AddReportRequest(new CXM_OleExcelReport(NULL, Fn(), sMcrName(), iMcrType, TRUE)); //CXM_OleExcelReport* pXB = new CXM_OleExcelReport(NULL, Fn(), sMcrName(), iMcrType); ////AfxGetMainWnd()->SendMessage(WMU_CMD, SUB_CMD_GENERATEOLEREPORT, (LPARAM)pXB); //ScdMainWnd()->PostMessage(WMU_CMD, SUB_CMD_GENERATEOLEREPORT, (LPARAM)pXB); } else sMcrStatus = "Specified file not found!"; } //-------------------------------------------------------------------------- void ScheduleTask::ExecRep() { Strng Fn(sRepPath); Fn.FnExpand(); Fn.FnCheckEndBSlash(); Fn += sRepFile; flag OK = true; if (!FileExists(Fn())) { OK = false; sRepStatus = "Specified file not found!"; } if (sRepTblName.Len()==0) { OK = false; sRepStatus = "Table Name not specified!"; } flag GotOne = false; for (int i=0; i<iRepTagCnt && !GotOne; i++) { if (RepTags[i].Len()==0) GotOne = true; } if (!GotOne) { OK = false; sRepStatus = "No tags specified!"; } CTimeValue EndTime; if (sRepEndTime.Len()==0 || _stricmp(sRepEndTime(), "*")==0) EndTime = gs_Exec.TheTime; else { if (!EndTime.Parse(sRepEndTime())) { OK = false; sRepStatus = "Invalid end time!"; } else { sRepEndTime = EndTime.Format(TD_TimeDate); if (_stricmp(sRepEndTime(), "?")==0) { OK = false; sRepStatus = "Invalid end time!"; } } } if (OK) { sRepStatus = "Ok"; dRepDuration = Max(dRepDuration, 1.0); iRepPtsCnt = Max(iRepPtsCnt, 3L); CXM_RepTrendDB* pXB = new CXM_RepTrendDB(Fn(), sRepTblName(), EndTime, dRepDuration, iRepPtsCnt); for (int i=0; i<iRepTagCnt; i++) { RepTags[i].LRTrim(" \t'\"\r\n"); if (RepTags[i].Len()) pXB->xAddTag(RepTags[i]()); } //AfxGetMainWnd()->SendMessage(WMU_REPORT, SUB_REPACTION_GENERATE, (LPARAM)pXB); ScdMainWnd()->PostMessage(WMU_REPORT, SUB_REPACTION_GENERATE, (LPARAM)pXB); } else sRepStatus = "Specified file not found!"; } //-------------------------------------------------------------------------- int ScheduleTask::FilesUsed(CFilesUsedArray & Files) { int Cnt = 0; Strng Fn; if (sScrFile.Len()>0) { Fn = sScrPath; Fn.FnExpand(); Fn += sScrFile; Files.AddFile(Fn(), FU_CopyFile|FU_EditTxt); Cnt++; } if (sMcrFile.Len()>0) { Fn = sMcrPath; Fn.FnExpand(); Fn += sMcrFile; Files.AddFile(Fn(), FU_CopyFile|FU_EditExcel); Cnt++; } if (sRepFile.Len()>0) { Fn = sRepPath; Fn.FnExpand(); Fn += sRepFile; Files.AddFile(Fn(), FU_CopyFile|FU_EditMDB); Cnt++; } return Cnt; } //-------------------------------------------------------------------------- int ScheduleTask::ChangeTag(pchar pOldTag, pchar pNewTag) { for (int i=0; i<iRepTagCnt; i++) CTgFnIoVar::ChangeTag(RepTags[i], pOldTag, pNewTag); return EOCT_DONE; } //-------------------------------------------------------------------------- int ScheduleTask::DeleteTag(pchar pDelTag, BOOL & FoundOne) { FoundOne = FALSE; for (int i=0; i<iRepTagCnt; i++) { if (CTgFnIoVar::ContainsTag(RepTags[i], pDelTag)) FoundOne = TRUE; } return EODT_DONE; } //-------------------------------------------------------------------------- //========================================================================== // // Schedule Task // //========================================================================== double Drw_SchedTask[] = { DD_Arc, 0,0, 3.2, DD_Poly, 0.0,2.4, 0.0,0.0, 1.6,0.0, DD_TagPos, 0, -6.7, DD_End }; IMPLEMENT_MODELUNIT(CScheduleTask, "SchedTask", "", Drw_SchedTask, "Control", "TSK", TOC_ALL|TOC_DYNAMICFLOW|TOC_GRP_GENERAL|TOC_STD_KENWALT, "Control:Task", "Schedule Task model.") CScheduleTask::CScheduleTask(pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach) : FlwNode(pClass_, TagIn, pAttach, eAttach) { fHasFiles=1; AttachClassInfo(nc_Control, NULL, NULL, &NullFlwGroup); bAboutToStart = 0; } //-------------------------------------------------------------------------- CScheduleTask::~CScheduleTask() { } //-------------------------------------------------------------------------- void CScheduleTask::BuildDataDefn(DataDefnBlk & DDB) { DDB.BeginStruct(this, "CScheduleTask", NULL, DDB_NoPage); DDB.Text(""); ST.BuildDataDefn(DDB, this); DDB.EndStruct(); } //-------------------------------------------------------------------------- flag CScheduleTask::DataXchg(DataChangeBlk & DCB) { if (FlwNode::DataXchg(DCB)) return 1; if (ST.DataXchg(DCB, this)) return 1; return False; } //-------------------------------------------------------------------------- flag CScheduleTask::PreStartCheck() { bAboutToStart = 1; return FlwNode::PreStartCheck(); } //-------------------------------------------------------------------------- void CScheduleTask::EvalDiscrete() { if (ICGetTimeInc()>0.0) ST.EvalDiscrete(); bAboutToStart = 0; } //-------------------------------------------------------------------------- int CScheduleTask::FilesUsed(CFilesUsedArray & Files) { ST.FilesUsed(Files); FlwNode::FilesUsed(Files); return Files.GetCount(); } //-------------------------------------------------------------------------- int CScheduleTask::ChangeTag(pchar pOldTag, pchar pNewTag) { ST.ChangeTag(pOldTag, pNewTag); return FlwNode::ChangeTag(pOldTag, pNewTag); } //-------------------------------------------------------------------------- int CScheduleTask::DeleteTag(pchar pDelTag) { BOOL FoundOne; int RetCode = ST.DeleteTag(pDelTag, FoundOne); if (FoundOne) { LogNote(Tag(), 0, "Delete tag '%s' affects Schedule Task model '%s'.", pDelTag, Tag()); } return FlwNode::DeleteTag(pDelTag); } //-------------------------------------------------------------------------- dword CScheduleTask::ModelStatus() { dword Status=FlwNode::ModelStatus(); //Status|=bOn ? FNS_On : FNS_Off; return Status; } //-------------------------------------------------------------------------- flag CScheduleTask::CIStrng(int No, pchar & pS) { // NB check CBCount is large enough. switch (No-CBContext()) { case 1: pS="E\tInvalid trend report end time"; return 1; default: return FlwNode::CIStrng(No, pS); } } //========================================================================== /* byte data[16384]; memset(data, 0, sizeof(data)); CFileStatus Stat; BOOL b = CFile::GetStatus("c:\\print.dat", Stat); if (b) { DWORD dwCount=Stat.m_size; ASSERT(dwCount<sizeof(data)); FILE* f = fopen("c:\\print.dat", "r"); size_t ss = fread(data, 1, dwCount, f); b = RawDataToPrinter("\\\\PERPRINT\\PER0658", data, dwCount); fclose(f); } BOOL RawDataToPrinter(LPSTR szPrinterName, LPBYTE lpData, DWORD dwCount) { HANDLE hPrinter; DOC_INFO_1 DocInfo; DWORD dwJob; DWORD dwBytesWritten; // Need a handle to the printer. if( ! OpenPrinter( szPrinterName, &hPrinter, NULL ) ) return FALSE; // Fill in the structure with info about this "document." DocInfo.pDocName = "My Document"; DocInfo.pOutputFile = NULL; DocInfo.pDatatype = "RAW"; // Inform the spooler the document is beginning. if( (dwJob = StartDocPrinter( hPrinter, 1, (/*LPSTR*//*LPBYTE)&DocInfo )) == 0 ) { ClosePrinter( hPrinter ); return FALSE; } // Start a page. if( ! StartPagePrinter( hPrinter ) ) { EndDocPrinter( hPrinter ); ClosePrinter( hPrinter ); return FALSE; } // Send the data to the printer. if( ! WritePrinter( hPrinter, lpData, dwCount, &dwBytesWritten ) ) { EndPagePrinter( hPrinter ); EndDocPrinter( hPrinter ); ClosePrinter( hPrinter ); return FALSE; } // End the page. if( ! EndPagePrinter( hPrinter ) ) { EndDocPrinter( hPrinter ); ClosePrinter( hPrinter ); return FALSE; } // Inform the spooler that the document is ending. if( ! EndDocPrinter( hPrinter ) ) { ClosePrinter( hPrinter ); return FALSE; } // Tidy up the printer handle. ClosePrinter( hPrinter ); // Check to see if correct number of bytes were written. if( dwBytesWritten != dwCount ) return FALSE; return TRUE; } */
[ [ [ 1, 82 ], [ 85, 87 ], [ 111, 112 ], [ 115, 118 ], [ 144, 146 ], [ 148, 148 ], [ 177, 298 ], [ 300, 300 ], [ 303, 307 ], [ 310, 374 ], [ 377, 402 ], [ 405, 430 ], [ 433, 465 ], [ 467, 482 ], [ 487, 521 ], [ 525, 526 ], [ 528, 533 ], [ 536, 554 ], [ 556, 623 ], [ 630, 691 ], [ 695, 700 ], [ 703, 714 ], [ 716, 811 ] ], [ [ 83, 84 ], [ 88, 110 ], [ 113, 114 ], [ 119, 143 ], [ 147, 147 ], [ 149, 176 ], [ 299, 299 ], [ 301, 302 ], [ 308, 309 ], [ 375, 376 ], [ 403, 404 ], [ 431, 432 ], [ 466, 466 ], [ 522, 524 ], [ 527, 527 ], [ 534, 535 ], [ 555, 555 ], [ 692, 694 ], [ 701, 702 ], [ 715, 715 ] ], [ [ 483, 486 ], [ 624, 629 ] ] ]
71dcc4d603fee53b943cc81e8344151382b4e649
675c51ababd86281b91263c17ac35f189927d4e4
/EP1/trabalho.cpp
f83df92f675ce0eaf163a18017b8c64c1e56d9dd
[]
no_license
CrociDB/EP-AED
4401a605fa63ba03385a208a50b7318eba77fab5
7cfb035b1873a476032ef9d3882b69ee88afc666
refs/heads/master
2021-01-15T17:45:42.203724
2010-11-07T20:45:43
2010-11-07T20:45:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,326
cpp
#include "palavras.h" // crie neste arquivo as funcoes solicitadas e todas as demais rotinas necessarias para sua execucao // tendo em mente que apenas o que esta implementado neste arquivo sera testado para fins de avaliacao // do seu trabalho. Nao modifique as assinaturas destas funcoes, nem o conteudo de palavras.h, ou seu // programa nao passara nos testes. char *aluno1() { return ("Filipe Marques Pereira"); // escreva aqui o seu nome } char *aluno2() { return ("Bruno Croci de Oliveira"); // escreva aqui o seu nome } char *nrousp1() { return ("6777105"); // escreva aqui o seu nro USP } char *nrousp2() { return ("6907392"); // escreva aqui o seu nro USP } char *turma() { return ("94"); // escreva aqui o nro da sua turma com 2 digitos } // somente para turma 04 void excluirPalavra(NO *frase, NO *palavra) { // implemente aqui a funcao solicitada ou deixe como esta (sem apagar) } int numNaoVogal(NO *no) { NO *p = no; int num = 0; while (p) { if (p->letra == 'a' || p->letra == 'e' || p->letra == 'i' || p->letra == 'o' || p->letra == 'u' || p->letra == 'A' || p->letra == 'E' || p->letra == 'I' || p->letra == 'O' || p->letra == 'U' || p->letra == '\r') { break; } p = p->prox; num++; } return num; } NO *copiar(NO* no){ NO* novo = (NO*) malloc(sizeof(NO)); novo->letra = no->letra; if(!no->prox){ novo->letra = no->letra; } else{ novo->prox = copiar(no->prox); } return novo; } NO *adicionaNoCabeca(NO *lista) { int num = numNaoVogal(lista); if (num > 1) { NO *head = (NO*) malloc(sizeof(NO)); head->letra = '\r'; head->prox = lista; return head; } return lista; } NO *removeNoCabeca(NO *lista) { if (lista->letra == '\r') { NO *p = lista; lista = lista->prox; free(p); } return lista; } void inverterTudo(NO **lista) { NO *atual = (*lista)->prox; NO *ant = *lista; NO *prox = NULL; if (atual) prox = atual->prox; while (atual) { atual->prox = ant; ant = atual; atual = prox; if (prox) { prox = prox->prox; } } (*lista)->prox = NULL; *lista = ant; } void inverteLista(NO **p_inicio, NO **p_ant, int num) { NO *atual = (*p_inicio)->prox; NO *ant = *p_inicio; NO *prox = atual->prox; int i = 0; //printf("--Num: %d\n", num); //print_test(*p_inicio, num+1); while (i < num-1) { atual->prox = ant; ant = atual; atual = prox; if (prox) { prox = prox->prox; } i++; } if ((*p_ant)) { (*p_ant)->prox = ant; } (*p_inicio)->prox = atual; //print_test(*p_inicio, num+1); } void inverterNaoVogal(NO *lista) { NO *p = lista; NO *ant = NULL; while (p) { int num = numNaoVogal(p); //printf("Out: %d\n", num); if (num > 1) { inverteLista(&p, &ant, num); } ant = p; p = p->prox; } } // somente para turma 94 NO *codificar (NO *frase){ // implemente aqui a funcao solicitada ou deixe como esta (sem apagar) //Copia do NO frase passado por parametro NO* copia = copiar(frase); // Gambiarra =D copia = adicionaNoCabeca(copia); //1ª etapa: inverterNaoVogal(copia); // Gambiarra (parte II) =D copia = removeNoCabeca(copia); //2ª etapa: inverterTudo(&copia); return copia; }
[ [ [ 1, 205 ] ] ]
d67edd8ec055bcc4414e7de8758be90811f5571c
22438bd0a316b62e88380796f0a8620c4d129f50
/fft_test/powers.h
b2ba6e323cecab30ccf9503a0efe6a3e2acffb82
[ "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
318
h
template < int size> struct log2 { enum {value = log2<size/2>::value + 1}; }; struct log2<1> { enum {value = 0}; }; struct log2<0> { enum {value = 0}; }; template< int size> struct power2 { enum {value = power2< size -1>::value * 2}; }; struct power2<0> { enum { value = 1 }; };
[ [ [ 1, 27 ] ] ]
0c178d825a66a41d51d7f97e8d035dece38526eb
dcff0f39e83ecab2ddcd482f3952ba317ee98f6c
/class-c-java/proj3/queue.cpp
f7e5ec48d363158afdedaab94654c7da69504cb5
[]
no_license
omgmovieslol/Code
f64048bc173e56538bb5f6164cce5d447cd7bd64
d5083b416469507b685a81d07a78fec1868644b1
refs/heads/master
2021-01-01T18:49:25.480158
2010-03-08T09:25:01
2010-03-08T09:25:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,181
cpp
#include <iostream> #include <cstdlib> using namespace std; //---------------------------// struct node { char name[20]; int age; float height; node *nxt; }; class Queue { public: Queue (void) { start_ptr=NULL; } void pop() { node *temp1,*temp2; if(start_ptr==NULL) cout<<"The list is empty\n"; else { temp1=start_ptr; temp2=temp1; while(temp1->nxt!=NULL) { temp2=temp1; temp1=temp1->nxt; } if(temp1==temp2) { cout<<temp1->name<<", "; cout<<temp1->age<<", "; cout<<temp1->height<<" \n";; start_ptr=NULL; } else { cout<<temp1->name<<", "; cout<<temp1->age<<", "; cout<<temp1->height<<" \n";; temp2->nxt=NULL; delete temp1; } } } int isEmpty() { if(start_ptr==NULL) { return 1; } else { return 0; } } //----------------------------// void push () { node *temp; temp = new node; cout << "Please enter the name of the person: \n"; cin >> temp->name; cout << "Please enter the age of the person: \n"; cin >> temp->age; cout << "Please enter the height of the person: \n"; cin >> temp->height; if (start_ptr == NULL) { temp->nxt=NULL; start_ptr = temp; } else { temp->nxt=start_ptr; start_ptr=temp; } } private: node *start_ptr; }; int main() { //void push (); //void pop(); Queue s; char ch; //clrscr(); cout<<"-----Queue-----\n"; //cout<<"-----"; do { cout<<"Type in P, P2 or E for the operation to be done.\n"; cout<<"P-Push\n"; cout<<"O-Pop\n"; cout<<"E-Exit\n"; cin>>ch; switch(ch) { case 'P': s.push(); break; case 'O': s.pop(); break; case 'E': while(!s.isEmpty()) { s.pop(); } system("PAUSE"); exit(0); } } while(ch!='E'); //return 0; system("PAUSE"); return EXIT_SUCCESS; }
[ [ [ 1, 133 ] ] ]
d338f7ebe4e82c236e2a7e7354a940ade9788449
7a8153e3fde0807462b6b6696b796d772639fa74
/src/system/Object.h
b23894109ea4a74bed33eb7582da319eb0e6c86d
[]
no_license
qaze/violetland
7183f9670676d05da3970cd2fbd8cf7e5f5197c2
9f0fc9aff4ca1a4111b45fb105fc33fd9ae97dad
refs/heads/master
2021-01-02T22:38:01.687080
2011-10-10T12:35:36
2011-10-10T12:35:36
32,754,552
2
0
null
null
null
null
UTF-8
C++
false
false
1,418
h
#ifndef OBJECT_H_ #define OBJECT_H_ #ifdef _WIN32 #define _USE_MATH_DEFINES #endif //_WIN32W #include <cmath> class Object { protected: int m_width, m_height; float m_left, m_right, m_top, m_bottom; public: Object(float x, float y, int width, int height); virtual ~Object(); void move(int deltaTime); static float fixAngle(float angle); static float calc_angle(float x1, float y1, float x2, float y2); static float calc_dist(float x1, float y1, float x2, float y2); void turn(float targetAngle, float angleSpeed, int deltaTime); const float getWidth() const { return m_width; } const float getHeight() const { return m_width; } const float getLeft() const { return X + m_left * Scale; } const float getRight() const { return X + m_right * Scale; } const float getTop() const { return Y + m_top * Scale; } const float getBottom() const { return Y + m_bottom * Scale; } const bool detectCollide(Object *refObj); const bool detectCollide(float x, float y); const bool detectCollide(float x1, float y1, float x2, float y2); const bool detectCollide(float x1, float y1, float x2, float y2, float* ix, float* iy); void setMask(float _RMask, float _GMask, float _BMask, float _AMask); float X, Y; float Scale; float Angle; float RMask, GMask, BMask, AMask; float HitR; float Acceleration, Speed; }; #endif /* OBJECT_H_ */
[ "5253450@c5058ba8-c010-11de-a759-a54c9d3330c2", "[email protected]@c5058ba8-c010-11de-a759-a54c9d3330c2", "[email protected]@c5058ba8-c010-11de-a759-a54c9d3330c2" ]
[ [ [ 1, 13 ], [ 16, 20 ], [ 39, 53 ] ], [ [ 14, 15 ] ], [ [ 21, 38 ] ] ]
dd5c15a62c39b397de4ce22e471fe21daf6acecb
f51d91cab39fd1f5bd5d676a008825f2e2671667
/8/source/bho.cpp
2cfac11b61f975f346135f16ffab2a24de0396c2
[]
no_license
s7ephen/CSAW_2009
ae803c6a2e2d07958487686fe1100fe34293a468
b6da6ecfdff2bbb9aad283ba847362e3a3214716
refs/heads/master
2021-01-04T14:06:07.141152
2009-11-16T15:13:41
2009-11-16T15:13:41
334,397
24
11
null
null
null
null
UTF-8
C++
false
false
9,615
cpp
// ------------------- /* CSAW 2009 Reversing Challenge #8 S.A. Ridley [email protected] */ // ------------------ #include <windows.h> #include <tchar.h> #include <exdisp.h> #include <exdispid.h> #include <mshtml.h> #include <mshtmdid.h> #include <shlwapi.h> #include <string.h> HINSTANCE hInstance; LONG gref=0; const CLSID BhoCLSID = {0xC9C42510,0x9B41,0x42c1,0x9D,0xCD,0x72,0x82,0xA2,0xD0,0x7C,0x61}; #define BhoCLSIDs _T("{C9C42510-9B41-42c1-9DCD-7282A2D07C61}") class BHO : public IObjectWithSite, public IDispatch { long ref; IWebBrowser2* webBrowser; IHTMLDocument* doc; IHTMLDocument2 *doc2; IHTMLWindow2 *win2; public: // IUnknown... HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv) {if (riid==IID_IUnknown) *ppv=static_cast<BHO*>(this); else if (riid==IID_IObjectWithSite) *ppv=static_cast<IObjectWithSite*>(this); else if (riid==IID_IDispatch) *ppv=static_cast<IDispatch*>(this); else return E_NOINTERFACE; AddRef(); return S_OK;} ULONG STDMETHODCALLTYPE AddRef() {InterlockedIncrement(&gref); return InterlockedIncrement(&ref);} ULONG STDMETHODCALLTYPE Release() {int tmp=InterlockedDecrement(&ref); if (tmp==0) delete this; InterlockedDecrement(&gref); return tmp;} // IDispatch... HRESULT STDMETHODCALLTYPE GetTypeInfoCount(unsigned int FAR* pctinfo) {*pctinfo=1; return NOERROR;} HRESULT STDMETHODCALLTYPE GetTypeInfo(unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo) {return NOERROR;} HRESULT STDMETHODCALLTYPE GetIDsOfNames(REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId) {return NOERROR;} __inline void tumbler1(char *buf){ short counter; for(counter = 0; counter < strlen(buf); counter ++){ buf[counter] ^= 0x4e; //N }; }; __inline void tumbler2(char *buf){ short counter; for(counter = 0; counter < strlen(buf); counter ++){ buf[counter] ^= 0x49; //I }; }; __inline void tumbler3(char *buf){ short counter; for(counter = 0; counter < strlen(buf); counter ++){ buf[counter] ^= 0x41; //A }; }; __inline void tumbler4(char *buf){ short counter; for(counter = 0; counter < strlen(buf); counter ++){ buf[counter] ^= 0x56; //V }; }; __inline void tumbler5(char *buf){ short counter; for(counter = 0; counter < strlen(buf); counter ++){ buf[counter] ^= 0x55; //U }; }; HRESULT STDMETHODCALLTYPE Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr) { char ciphertext[]="\x16\x2d\x20\x65\x36\x20\x29\x29\x36\x65\x06\x16\x04\x12\x36\x65\x27\x3c\x65\x31\x2d\x20\x65\x36\x20\x24\x36\x2d\x2a\x37\x20\x6b"; // DISPID_DOCUMENTCOMPLETE: This is the earliest point we can obtain the "document" interface if (dispIdMember==DISPID_DOCUMENTCOMPLETE){ if (!webBrowser) return E_FAIL; IDispatch *idisp; webBrowser->get_Document(&idisp); if (idisp && !doc) idisp->QueryInterface(IID_IHTMLDocument, (void**)&doc); if (idisp && !doc2) idisp->QueryInterface(IID_IHTMLDocument2, (void**)&doc2); if (doc2 && !win2) doc2->get_parentWindow(&win2); IConnectionPointContainer *cpc=0; if (doc) doc->QueryInterface(IID_IConnectionPointContainer, (void**) &cpc); IConnectionPoint* cp=0; if (cpc) cpc->FindConnectionPoint(DIID_HTMLDocumentEvents2, &cp); DWORD cookie; HRESULT hr; if (cp) hr=cp->Advise(static_cast<IDispatch*>(this), &cookie); if (cp) cp->Release(); if (cpc) cpc->Release(); if (idisp) idisp->Release(); if (!doc || !doc2 || !win2 || hr!=S_OK) { release(); return E_FAIL; } return NOERROR; } if (dispIdMember==DISPID_HTMLDOCUMENTEVENTS_ONKEYDOWN) { // This shows how to respond to simple events. MessageBox(0,_T("Challenge #8 is watching you!"),_T("Challenge #8"),MB_OK); return NOERROR; } /* if (dispIdMember==DISPID_HTMLDOCUMENTEVENTS_ONCLICK) { // This shows how to examine the "event object" of an event IDispatch *param1=0; if (pDispParams->cArgs==1 && (pDispParams->rgvarg)[0].vt==VT_DISPATCH) param1=(pDispParams->rgvarg)[0].pdispVal; IHTMLEventObj *pEvtObj=0; if (param1) param1->QueryInterface(IID_IHTMLEventObj, (void**)&pEvtObj); long keycode; HRESULT hr; if (pEvtObj) hr=pEvtObj->get_keyCode(&keycode); if (pEvtObj) pEvtObj->Release(); if (!pEvtObj || hr!=S_OK) return E_FAIL; // This shows how to manipulate the CSS style of an element int i=keycode-32; if (i<0) i=0; if (i>63) i=63; i*=4; wchar_t buf[100]; wsprintfW(buf,L"rgb(%i,%i,%i)",i,255-i,i/2); IHTMLElement *body=0; doc2->get_body(&body); IHTMLStyle *style=0; if (body) body->get_style(&style); VARIANT v; v.vt=VT_BSTR; v.bstrVal=buf; if (style) style->put_backgroundColor(v); if (style) style->Release(); if (body) body->Release(); if (!body || !style) return E_FAIL; return NOERROR; }*/ if (dispIdMember==DISPID_HTMLDOCUMENTEVENTS_ONCLICK){ IDispatch *param1=0; if (pDispParams->cArgs==1 && (pDispParams->rgvarg)[0].vt==VT_DISPATCH) param1=(pDispParams->rgvarg)[0].pdispVal; IHTMLEventObj *pEvtObj=0; if (param1) param1->QueryInterface(IID_IHTMLEventObj, (void**)&pEvtObj); HRESULT hr; // This shows how to manipulate the CSS style of an element IHTMLElement *body=0; doc2->get_body(&body); BSTR URL, site; site = SysAllocString(L"dontstuffbeansupyournose"); doc2->get_URL(&URL); tumbler5((char *)&ciphertext); tumbler3((char *)&ciphertext); tumbler4((char *)&ciphertext); tumbler2((char *)&ciphertext); tumbler1((char *)&ciphertext); if (wcsstr(URL,site) != NULL){//it's in there. //MessageBox(0,URL,_T("Challenge #8"),MB_OK); MessageBoxA(0,(LPCSTR)&ciphertext,"Challenge #8",MB_OK); } } return NOERROR; } // IObjectWithSite... HRESULT STDMETHODCALLTYPE GetSite(REFIID riid, void** ppvSite) {return E_NOINTERFACE;} HRESULT STDMETHODCALLTYPE SetSite(IUnknown* iunk) { // This is called by IE to plug us into the current web window release(); iunk->QueryInterface(IID_IWebBrowser2, (void**)&webBrowser); IConnectionPointContainer *cpc=0; iunk->QueryInterface(IID_IConnectionPointContainer, (void**)&cpc); IConnectionPoint* cp=0; if (cpc) cpc->FindConnectionPoint(DIID_DWebBrowserEvents2, &cp); DWORD cookie; HRESULT hr; if (cp) hr=cp->Advise(static_cast<IDispatch*>(this), &cookie); if (!webBrowser || !cpc || !cp || hr!=S_OK) {if (cp) cp->Release(); if (cpc) cpc->Release(); release(); return E_FAIL;} return S_OK; } // BHO... BHO() : ref(0), webBrowser(0), doc(0), doc2(0), win2(0) {}; ~BHO() {release();} void release() {if (webBrowser) webBrowser->Release(); webBrowser=0; if (doc) doc->Release(); doc=0; if (doc2) doc2->Release(); doc2=0; if (win2) win2->Release(); win2=0;} }; class MyClassFactory : public IClassFactory { long ref; public: // IUnknown... (nb. this class is instantiated statically, which is why Release() doesn't delete it.) HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv) {if (riid==IID_IUnknown || riid==IID_IClassFactory) {*ppv=this; AddRef(); return S_OK;} else return E_NOINTERFACE;} ULONG STDMETHODCALLTYPE AddRef() {InterlockedIncrement(&gref); return InterlockedIncrement(&ref);} ULONG STDMETHODCALLTYPE Release() {int tmp = InterlockedDecrement(&ref); InterlockedDecrement(&gref); return tmp;} // IClassFactory... HRESULT STDMETHODCALLTYPE LockServer(BOOL b) {if (b) InterlockedIncrement(&gref); else InterlockedDecrement(&gref); return S_OK;} HRESULT STDMETHODCALLTYPE CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, LPVOID *ppvObj) {*ppvObj = NULL; if (pUnkOuter) return CLASS_E_NOAGGREGATION; BHO *bho=new BHO(); bho->AddRef(); HRESULT hr=bho->QueryInterface(riid, ppvObj); bho->Release(); return hr;} // MyClassFactory... MyClassFactory() : ref(0) {} }; STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppvOut) { static MyClassFactory factory; *ppvOut = NULL; if (rclsid==BhoCLSID) {return factory.QueryInterface(riid,ppvOut);} else return CLASS_E_CLASSNOTAVAILABLE; } STDAPI DllCanUnloadNow(void) { return (gref>0)?S_FALSE:S_OK; } STDAPI DllRegisterServer(void) { TCHAR fn[MAX_PATH]; GetModuleFileName(hInstance,fn,MAX_PATH); SHSetValue(HKEY_CLASSES_ROOT,_T("CLSID\\")BhoCLSIDs,_T(""),REG_SZ,_T("BHO"),4*sizeof(TCHAR)); SHSetValue(HKEY_CLASSES_ROOT,_T("CLSID\\")BhoCLSIDs _T("\\InProcServer32"),_T(""),REG_SZ,fn,((int)_tcslen(fn)+1)*sizeof(TCHAR)); SHSetValue(HKEY_CLASSES_ROOT,_T("CLSID\\")BhoCLSIDs _T("\\InProcServer32"),_T("ThreadingModel"),REG_SZ,_T("Apartment"),10*sizeof(TCHAR)); SHSetValue(HKEY_LOCAL_MACHINE,_T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects\\")BhoCLSIDs,_T(""),REG_SZ,_T(""),sizeof(TCHAR)); return S_OK; } STDAPI DllUnregisterServer() { SHDeleteKey(HKEY_CLASSES_ROOT,_T("CLSID\\") BhoCLSIDs); SHDeleteKey(HKEY_LOCAL_MACHINE,_T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects\\")BhoCLSIDs); return S_OK; } BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if (fdwReason==DLL_PROCESS_ATTACH) hInstance=hinstDLL; return TRUE; }
[ [ [ 1, 227 ] ] ]
e1a0210b988036266b494c4c4d864cba1aec467e
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/ngeomipmap/src/ngeomipmap/nbytemap_cmds.cc
b6957559e3722ed3d127dd91c1b391ab82981e8b
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,379
cc
#include "precompiled/pchngeomipmap.h" //------------------------------------------------------------------------------ // nbytemap_cmds.cc // (C) 2004 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "ngeomipmap/nbytemap.h" //------------------------------------------------------------------------------ static void n_setsize(void * o, nCmd * cmd); static void n_fillvalue(void * o, nCmd * cmd); //------------------------------------------------------------------------------ /** Nebula class scripting initialization */ void n_initcmds_nByteMap(nClass* cl) { cl->BeginCmds(); cl->AddCmd("v_setsize_i", 'SESI', n_setsize); cl->AddCmd("v_fillvalue_i", 'FIHE', n_fillvalue); cl->EndCmds(); } //------------------------------------------------------------------------------ /** */ static void n_setsize(void * o, nCmd * cmd) { nByteMap * self = static_cast<nByteMap *> (o); self->SetSize( cmd->In()->GetI() ); } //------------------------------------------------------------------------------ /** */ static void n_fillvalue(void * o, nCmd * cmd) { nByteMap * self = static_cast<nByteMap *> (o); self->FillValue( nuint8(cmd->In()->GetI()) ); } //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 47 ] ] ]
1c3800d0c5b18369ce96d87edec80f35d98a613a
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/regx/RangeFactory.cpp
e452a8e0060860c6b91c411a4d9da397bd9433b8
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
2,689
cpp
/* * Copyright 2001,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: RangeFactory.cpp,v $ * Revision 1.3 2004/09/08 13:56:47 peiyongz * Apache License Version 2.0 * * Revision 1.2 2002/11/04 15:17:00 tng * C++ Namespace Support. * * Revision 1.1.1.1 2002/02/01 22:22:29 peiyongz * sane_include * * Revision 1.4 2001/05/11 13:26:45 tng * Copyright update. * * Revision 1.3 2001/05/03 18:17:33 knoaman * Some design changes: * o Changed the TokenFactory from a single static instance, to a * normal class. Each RegularExpression object will have its own * instance of TokenFactory, and that instance will be passed to * other classes that need to use a TokenFactory to create Token * objects (with the exception of RangeTokenMap). * o Added a new class RangeTokenMap to map a the different ranges * in a given category to a specific RangeFactory object. In the old * design RangeFactory had dual functionality (act as a Map, and as * a factory for creating RangeToken(s)). The RangeTokenMap will * have its own copy of the TokenFactory. There will be only one * instance of the RangeTokenMap class, and that instance will be * lazily deleted when XPlatformUtils::Terminate is called. * * Revision 1.2 2001/03/22 13:23:32 knoaman * Minor modifications to eliminate compiler warnings. * * Revision 1.1 2001/03/02 19:26:44 knoaman * Schema: Regular expression handling part II * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/regx/RangeFactory.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // RangeFactory: Constructors and Destructor // --------------------------------------------------------------------------- RangeFactory::RangeFactory() { } RangeFactory::~RangeFactory() { } XERCES_CPP_NAMESPACE_END /** * End of file RangeFactory.cpp */
[ [ [ 1, 76 ] ] ]
1b44df9b23b1438a49435d23c78c41a1581c3f7a
d249c8f9920b1267752342f77d6f12592cb32636
/moteurGraphique/src/Ressource/Mesh/Sphere.cpp
915a3f521d70b21fa20b54dd8a2b58649afb4828
[]
no_license
jgraulle/stage-animation-physique
4c9fb0f96b9f4626420046171ff60f23fe035d5d
f1b0c69c3ab48f256d5ac51b4ffdbd48b1c001ae
refs/heads/master
2021-12-23T13:46:07.677761
2011-03-08T22:47:53
2011-03-08T22:47:53
33,616,188
0
0
null
2021-10-05T10:41:29
2015-04-08T15:41:32
C++
UTF-8
C++
false
false
493
cpp
/* * Sphere.cpp * * Created on: 9 f�vr. 2009 * Author: jeremie GRAULLE */ #include "Sphere.h" #include <GL/glu.h> Sphere::Sphere(int slices, int stacks) : slices(slices), stacks(stacks) { GLUquadric * quadric = gluNewQuadric(); gluQuadricTexture(quadric, GL_TRUE); idDisplayList = glGenLists(1); glNewList(idDisplayList, GL_COMPILE); gluSphere(quadric, 1.0, slices, stacks); glEndList(); gluDeleteQuadric(quadric); } Sphere::~Sphere() {}
[ "jgraulle@74bb1adf-7843-2a67-e58d-b22fe9da3ebb" ]
[ [ [ 1, 27 ] ] ]
abd29fb361f764a6679f4e4065cd43e986caa4a9
2eda21938786de13a565903d8b2feab25ac9ccb8
/EconomyManager.cpp
4eb14838646a470918b8739009dad43b5b0d18ce
[]
no_license
gbougard/NBK
d2ed27fc825a8919c716e7011e1a7631a6bc3be1
e8155adec2da3f333230b050fccc164e1e3c04fe
refs/heads/master
2021-01-15T21:39:58.541842
2011-11-21T20:36:38
2011-11-21T20:36:38
3,157,757
0
0
null
null
null
null
UTF-8
C++
false
false
7,717
cpp
#include "commons.h" #include "EconomyManager.h" #include "Block.h" #include "BlockObject.h" #include "Trap.h" using namespace control; using namespace cml; using namespace game_objects; using namespace game_objects::block_objects; namespace game_utils { namespace managers { GLint CEconomyManager::roomTypes[]= { CV_BLOCK_TYPE_TREASURE_ROOM_ID, CV_BLOCK_TYPE_LAIR_ID, CV_BLOCK_TYPE_HATCHERY_ID, CV_BLOCK_TYPE_TRAINING_ROOM_ID, CV_BLOCK_TYPE_LIBRARY_ID, CV_BLOCK_TYPE_BRIDGE_ID, CV_BLOCK_TYPE_GUARD_POST_ID, CV_BLOCK_TYPE_WORKSHOP_ID, CV_BLOCK_TYPE_PRISON_ID, CV_BLOCK_TYPE_TORTURE_CHAMBER_ID, CV_BLOCK_TYPE_BARRACKS_ID, CV_BLOCK_TYPE_TEMPLE_ID, CV_BLOCK_TYPE_GRAVEYARD_ID }; GLint CEconomyManager::trapTypes[]= { CTrap::TT_BOULDER, CTrap::TT_ALARM, CTrap::TT_POISON, CTrap::TT_LIGHTNING, CTrap::TT_WORD_OF_POWER, CTrap::TT_LAVA }; CEconomyManager::CEconomyManager(): CManager(), CInputListener() { // register to handle input CV_GAME_MANAGER->getControlManager()->getInput()->registerListener(this); } CEconomyManager::~CEconomyManager() { } bool CEconomyManager::init() { return true; } bool CEconomyManager::update() { return true; } bool CEconomyManager::shutdown() { return true; } void CEconomyManager::onKeyDown(int key) { } void CEconomyManager::onKeyUp(int key) { } void CEconomyManager::onMouseClicked(int button) { CBlock *pickedBlock = CV_GAME_MANAGER->getPickingManager()->getLastPickedBlock(); ACTION_EVENT *ae = CV_GAME_MANAGER->getGUIManager()->getLastActionEvent(); if (CV_GAME_MANAGER->getGUIManager()->getPlayGUI()->is_mouse_over_gui()) { return; } if (button==1) { // reset ae->reset(); } if (button==0) { if (pickedBlock) { GLint group = ae->message_group; GLint msg = ae->message; vector2i mousePos = CV_GAME_MANAGER->getControlManager()->getInput()->getMousePos(); if(group==AEMG_EXECUTE_SPELL) { CV_GAME_MANAGER->getSpellManager()->castSpell(ae->message,pickedBlock->getLogicalPosition(),CV_CURRENT_PLAYER_ID); return; } // If you have clicked on a rock, mark it for mining. if (CV_GAME_MANAGER->getLevelManager()->isFullBlock(pickedBlock)) { if (!pickedBlock->getType()==CV_BLOCK_TYPE_ROCK_ID) pickedBlock->setMarked(!pickedBlock->isMarked()); } else if (group==AEMG_BUILD_ROOMS || group==AEMG_BUILD_DOORS || group==AEMG_BUILD_TRAPS) { // selling comes with the message group AEMG_BUILD_ROOMS if (msg==AEM_SELL) { // the flag tells us that we have to sell stuff if (pickedBlock->isSellable(CV_CURRENT_PLAYER_ID)) { // actual selling procedure if (pickedBlock->getType() == CV_BLOCK_TYPE_CLAIMED_LAND_ID) { // selling traps CV_GAME_MANAGER->getConsole()->writeLine("Trying to sell a trap"); for (std::vector<CBlockObject*>::iterator rmIter = pickedBlock->getBlockObjects()->begin(); rmIter != pickedBlock->getBlockObjects()->end(); rmIter++) { CBlockObject *bObject = *rmIter; if (bObject->getClassName() == "TRAP") { pickedBlock->removeBlockObject(bObject); break; } } } else { // generate the room cost (divide by 2 because were selling) int k, position; bool found = false; // find target's position if present k = 0; while (k < sizeof(roomTypes) && !found) { if (roomTypes[k] == pickedBlock->getType()) { position = k; found = true; } else k++; } GLint room_cost = GLOBAL_CREATURE_TXT_READER->get_room_propery(room_class_names[position],PROPERTY_ROOM_COST)/2; // we built somethig so we have to lower the money PLAYER0_MONEY+=room_cost; // spawn the jumping label CV_GAME_MANAGER->getGUIManager()->getPlayGUI()->spawnJumpingLabel(mousePos[0],mousePos[1],room_cost); // selling rooms pickedBlock->setType(CV_BLOCK_TYPE_CLAIMED_LAND_ID); pickedBlock->init(); // fix the neighbours GLint sx = pickedBlock->getLogicalPosition()[0]; GLint sy = pickedBlock->getLogicalPosition()[1]; for (GLint y=sy-1; y<=sy+1; y++) { for (GLint x=sx-1; x<=sx+1; x++) { CV_GAME_MANAGER->getLevelManager()->getBlock(x,y)->finalize(); } } } } } else if (group==AEMG_BUILD_ROOMS) { GLint room_cost = GLOBAL_CREATURE_TXT_READER->get_room_propery(room_class_names[msg],PROPERTY_ROOM_COST); if(PLAYER0_MONEY-room_cost>=0) { // the flag tells us that we have to build some stuff (traps, doors, rooms) if (!pickedBlock->isBuildable(CV_CURRENT_PLAYER_ID)) { return; } // sanity check: we cant build bridge on dry land ans we cant build rooms on water or lava if (roomTypes[msg] != CV_BLOCK_TYPE_BRIDGE_ID && (pickedBlock->isLava() || pickedBlock->isWater())) { // tryint to build room on water or lava return; } if (roomTypes[msg] == CV_BLOCK_TYPE_BRIDGE_ID && !(pickedBlock->isLava() || pickedBlock->isWater())) { // tryint to build bridge on dry land return; } // we built somethig so we have to lower the money PLAYER0_MONEY-=room_cost; // spawn the jumping label CV_GAME_MANAGER->getGUIManager()->getPlayGUI()->spawnJumpingLabel(mousePos[0],mousePos[1],room_cost); pickedBlock->setType(roomTypes[msg]); pickedBlock->init(); // fix the neighbours GLint sx = pickedBlock->getLogicalPosition()[0]; GLint sy = pickedBlock->getLogicalPosition()[1]; for (GLint y=sy-1; y<=sy+1; y++) { for (GLint x=sx-1; x<=sx+1; x++) { CV_GAME_MANAGER->getLevelManager()->getBlock(x,y)->finalize(); } } } } else if (group==AEMG_BUILD_TRAPS) { // the flag tells us that we have to build some stuff (traps, doors, rooms) if (!pickedBlock->isBuildable(CV_CURRENT_PLAYER_ID)) { return; } GLint tt = ae->message - AEM_BUILD_TRAP_BOULDER; pickedBlock->addModel(new CTrap(tt==0?"MODEL_BOULDER":"MODEL_TRAP",pickedBlock->getRealPosition()+vector3f(CV_BLOCK_WIDTH/2.0f,0.0f,CV_BLOCK_DEPTH/2.0f),(CTrap::TRAP_TYPE)trapTypes[tt])); } // if we're building a hatchery then we must lower the models by 1/4 of height for (std::vector<CBlockObject*>::iterator rmIter = pickedBlock->getBlockObjects()->begin(); rmIter != pickedBlock->getBlockObjects()->end(); rmIter++) { CBlockObject *bObject = *rmIter; vector3f bPos = bObject->getPosition(); if (bPos[1]>=CV_BLOCK_HEIGHT/2.0f) { // exclude torches continue; } bPos[1] = CV_BLOCK_HEIGHT/4.0f; GLint bType = pickedBlock->getType(); if (bType == CV_BLOCK_TYPE_HATCHERY_ID) { bPos[1] = 0.0f; } bObject->setPosition(bPos); } } } } } }; };
[ [ [ 1, 59 ], [ 99, 99 ], [ 139, 139 ], [ 179, 179 ], [ 193, 193 ], [ 200, 200 ], [ 209, 209 ], [ 212, 212 ], [ 215, 215 ], [ 228, 228 ], [ 238, 238 ], [ 241, 241 ], [ 246, 246 ], [ 269, 272 ] ], [ [ 60, 74 ], [ 77, 78 ], [ 83, 83 ], [ 88, 88 ], [ 91, 98 ], [ 103, 103 ], [ 126, 126 ], [ 132, 132 ], [ 135, 137 ], [ 143, 143 ], [ 147, 147 ], [ 160, 160 ], [ 163, 163 ], [ 175, 175 ], [ 185, 185 ], [ 199, 199 ], [ 202, 202 ], [ 206, 206 ], [ 219, 219 ], [ 223, 223 ], [ 225, 225 ], [ 227, 227 ], [ 268, 268 ] ], [ [ 75, 76 ], [ 79, 82 ], [ 84, 87 ], [ 89, 90 ], [ 100, 102 ], [ 104, 125 ], [ 127, 131 ], [ 133, 134 ], [ 138, 138 ], [ 140, 142 ], [ 144, 146 ], [ 148, 159 ], [ 161, 162 ], [ 164, 174 ], [ 176, 178 ], [ 180, 184 ], [ 186, 192 ], [ 194, 198 ], [ 201, 201 ], [ 203, 205 ], [ 207, 208 ], [ 210, 211 ], [ 213, 214 ], [ 216, 218 ], [ 220, 222 ], [ 224, 224 ], [ 226, 226 ], [ 229, 237 ], [ 239, 240 ], [ 242, 245 ], [ 247, 267 ] ] ]
dcdd39a7cf32e367c7afcfcc3d06d315174ff5c5
37c757f24b674f67edd87b75b996d8d5015455cb
/Server/sources/sendThread.cpp
ca858ac77a5fe740d35e33d16a4ad29f5581e827
[]
no_license
SakuraSinojun/cotalking
1118602313f85d1c49d73e1603cf6642bc15f36d
37354d99db6b7033019fd0aaccec84e68aee2adf
refs/heads/master
2021-01-10T21:20:50.269547
2011-04-07T06:15:04
2011-04-07T06:15:04
32,323,167
0
0
null
null
null
null
UTF-8
C++
false
false
1,535
cpp
#include "../include/sendThread.h" TS_SendThread::TS_SendThread() { pthread_mutex_init(&mutex_sock , NULL); intTemp = 0; } TS_SendThread::~TS_SendThread() { pthread_mutex_destroy(&mutex_sock); } void TS_SendThread::addSock(int sock) { if (sock < 1) return; pthread_mutex_lock(&mutex_sock); listSock.push_back(sock); pthread_mutex_unlock(&mutex_sock); } int TS_SendThread::sendData(int sock, void *data, int datalen) { if (sock < 1) return false; int intRet = 0; while (true) { intRet = send(sock, data, datalen, MSG_NOSIGNAL); if (intRet == 0) // the connect is closed; { return -1; } else if (intRet < 0) { if(errno == EINTR) { continue; } break; } break; } return intRet; } void TS_SendThread::run() { list<int>::iterator it = listSock.begin(); void* dataSend; int intDataLen; while (isRunning) { if (it == listSock.end()) { it = listSock.begin(); sleep(1); continue; } dataSend = dataMng->getSendData(*it,intDataLen); if (dataSend == NULL) { it ++; continue; } if (sendData(*it, dataSend, intDataLen) == -1) { pthread_mutex_lock(&mutex_sock); it = listSock.erase(it); pthread_mutex_unlock(&mutex_sock); } else { it ++; } } } void TS_SendThread::setDataManager(TS_dataManager *pdm) { dataMng = pdm; }
[ "SakuraSinojun@02eed91f-dd82-7cf9-bfd0-73567c4360d3" ]
[ [ [ 1, 86 ] ] ]
5a55d308cd8e66a78b1cf6f20e776a6f402eebe4
164ad25eca017ebc51ae72d46dd1f19f722c0c21
/src/Viewer/PickHandler.cpp
fcf271de77947540c3609a05fe4967b87fee35cc
[]
no_license
jaro-prokop/3dsoftviz
5cdcaa15158acdb335a441073ca2d26e1cd5b46d
77332ef847529a8617247754c94621ebc6a90d2c
refs/heads/master
2021-01-16T20:23:24.894745
2011-05-02T09:00:39
2011-05-02T09:00:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,602
cpp
#include "Viewer/PickHandler.h" #include "Viewer/DataHelper.h" #include "Util/ElementSelector.h" #include <osg/MatrixTransform> #include <osg/Projection> #include "Manager/Manager.h" #include "Math/CameraMath.h" using namespace Vwr; PickHandler::PickHandler(Vwr::CameraManipulator * cameraManipulator, Vwr::CoreGraph * coreGraph) { //vytvorenie timera a vynulovanie premennych timer = new QTimer(); connect(timer,SIGNAL(timeout()), this, SLOT(mouseTimerTimeout())); eaPush = NULL; eaRel = NULL; aaPush = NULL; aaRel = NULL; this->cameraManipulator = cameraManipulator; this->coreGraph = coreGraph; this->appConf = Util::ApplicationConfig::get(); _mX = _mY = 0; isCtrlPressed = false; isShiftPressed = false; isAltPressed = false; isDrawingSelectionQuad = false; isDragging = false; isManipulatingNodes = false; pickMode = PickMode::NONE; selectionType = SelectionType::ALL; }; bool PickHandler::handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { switch( ea.getEventType() ) { case osgGA::GUIEventAdapter::PUSH: { //vynulovanie premennej pre ulozenie release eventu eaRel = NULL; // ak dojde push a nie je zapnuty timer tak spusti sa timer a ulozia eventy if (!timer->isActive()) { Util::ApplicationConfig * appConf = Util::ApplicationConfig::get(); timer->start(appConf->getValue("Mouse.DoubleClickTime").toInt()); eaPush = &ea; aaPush = &aa; return false; } return handlePush(ea, aa); } case osgGA::GUIEventAdapter::DOUBLECLICK: { //ak dosiel double click tak vypnut timer timer->stop(); eaRel = NULL; return handleDoubleclick(ea, aa); } case osgGA::GUIEventAdapter::MOVE: { return handleMove(ea, aa); } case osgGA::GUIEventAdapter::DRAG: { //ak je drag a ide timer tak vypnut timer a vyvolat push //zaruci sa tak spravne spracovany drag if (timer->isActive()) { timer->stop(); handlePush(*eaPush, *aaPush); } //uz kvoli dalsiemu pokracovaniu dragu return handleDrag(ea, aa); } case osgGA::GUIEventAdapter::RELEASE: { //ak je release a je timer aktivny tak sa ulozi event a nevyvola sa if (timer->isActive()) { eaRel = &ea; aaRel = &aa; return false; } return handleRelease(ea, aa); } case osgGA::GUIEventAdapter::KEYDOWN: { return handleKeyDown(ea, aa); } case::osgGA::GUIEventAdapter::KEYUP: { return handleKeyUp(ea, aa); } default: return false; } } void PickHandler::mouseTimerTimeout() { //ak dobehne timer tak pouzivatel len klikol //takze sa zastavi timer timer->stop(); //vyvola sa push event handlePush(*eaPush, *aaPush); //v pripade ze bol aj release tak sa vyvola aj release if (eaRel != NULL) handleRelease(*eaRel, *aaRel); } bool PickHandler::handleMove( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { // Record mouse location for the button press // and move events. _mX = ea.getX(); _mY = ea.getY(); return false; } bool PickHandler::handleDoubleclick( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { return false; } bool PickHandler::handleKeyUp( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { if(ea.getKey() == osgGA::GUIEventAdapter::KEY_Control_R || ea.getKey() == osgGA::GUIEventAdapter::KEY_Control_L) { isCtrlPressed = false; } else if(ea.getKey() == osgGA::GUIEventAdapter::KEY_Shift_L || ea.getKey() == osgGA::GUIEventAdapter::KEY_Shift_R) { isShiftPressed = false; } else if(ea.getKey() == osgGA::GUIEventAdapter::KEY_Alt_L || ea.getKey() == osgGA::GUIEventAdapter::KEY_Alt_R) { isAltPressed = false; } return false; } bool PickHandler::handleKeyDown( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { if(ea.getKey() == osgGA::GUIEventAdapter::KEY_Control_R || ea.getKey() == osgGA::GUIEventAdapter::KEY_Control_L) { isCtrlPressed = true; } else if(ea.getKey() == osgGA::GUIEventAdapter::KEY_Shift_L || ea.getKey() == osgGA::GUIEventAdapter::KEY_Shift_R) { isShiftPressed = true; } else if(ea.getKey() == osgGA::GUIEventAdapter::KEY_Alt_L || ea.getKey() == osgGA::GUIEventAdapter::KEY_Alt_R) { isAltPressed = true; } else if(ea.getKey() == 'q') { Data::Graph * currentGraph = Manager::GraphManager::getInstance()->getActiveGraph(); Util::ElementSelector::randomElementSelector(currentGraph->getNodes(), currentGraph->getEdges(), appConf->getValue("Viewer.PickHandler.AutopickedNodes").toInt(), this); } else if(ea.getKey() == 'w') { Data::Graph * currentGraph = Manager::GraphManager::getInstance()->getActiveGraph(); Util::ElementSelector::weightedElementSelector(currentGraph->getNodes(), appConf->getValue("Viewer.PickHandler.AutopickedNodes").toInt(), this); } return false; } bool PickHandler::handleRelease( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>( &aa ); if (!viewer) return false; // If the mouse hasn't moved since the last // button press or move event, perform a // pick. (Otherwise, the trackball // manipulator will handle it.) leftButtonPressed = false; if (pickMode == PickMode::MULTI && isDrawingSelectionQuad) { float x, y, w, h; if (origin_mX_normalized < ea.getXnormalized()) { x = origin_mX_normalized; w = ea.getXnormalized(); } else { x = ea.getXnormalized(); w = origin_mX_normalized ; } if (origin_mY_normalized < ea.getYnormalized()) { y = origin_mY_normalized; h = ea.getYnormalized(); } else { y = ea.getYnormalized(); h = origin_mY_normalized; } pick( x, y, w, h, viewer ); if (coreGraph->getCustomNodeList()->contains(group)) { coreGraph->getCustomNodeList()->removeOne(group); } isDrawingSelectionQuad = false; return true; } if(isManipulatingNodes) { isManipulatingNodes = false; setSelectedNodesInterpolation(true); } return false; } bool PickHandler::handleDrag( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { _mX = ea.getX(); _mY = ea.getY(); if (pickMode == PickMode::MULTI && isDrawingSelectionQuad) { osg::ref_ptr<osg::Vec3Array> coordinates = new osg::Vec3Array; coordinates->push_back(osg::Vec3(origin_mX, origin_mY, -1)); coordinates->push_back(osg::Vec3(origin_mX, _mY, -1)); coordinates->push_back(osg::Vec3( _mX, _mY, -1)); coordinates->push_back(osg::Vec3( _mX, origin_mY, -1)); selectionQuad->getDrawable(0)->asGeometry()->setVertexArray(coordinates); } else if (pickMode == PickMode::NONE && leftButtonPressed) { if(!isManipulatingNodes) { isManipulatingNodes = true; setSelectedNodesInterpolation(false); toggleSelectedNodesFixedState(true); } osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>( &aa ); if (!viewer) return false; return dragNode(viewer); } return false; } bool PickHandler::handlePush( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { if (ea.getButtonMask() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) { leftButtonPressed = true; origin_mX = ea.getX(); origin_mY = ea.getY(); origin_mX_normalized = ea.getXnormalized(); origin_mY_normalized = ea.getYnormalized(); if (pickMode != PickMode::NONE && !isShiftPressed && !isCtrlPressed) { unselectPickedNodes(); unselectPickedEdges(); } osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>( &aa ); if (!viewer) return false; if (pickMode == PickMode::MULTI) { isDrawingSelectionQuad = true; drawSelectionQuad(origin_mX, origin_mY, viewer); } else { return pick(ea.getXnormalized() - 0.00005f, ea.getYnormalized() - 0.00005f, ea.getXnormalized() + 0.00005f, ea.getYnormalized() + 0.00005f, viewer ); } } _mX = ea.getX(); _mY = ea.getY(); return false; } bool PickHandler::pick( const double xMin, const double yMin, const double xMax, const double yMax, osgViewer::Viewer* viewer ) { if (!viewer->getSceneData()) // Nothing to pick. return false; osgUtil::PolytopeIntersector* picker = new osgUtil::PolytopeIntersector(osgUtil::Intersector::PROJECTION, xMin, yMin, xMax, yMax); osgUtil::IntersectionVisitor iv( picker ); viewer->getCamera()->accept( iv ); bool result = false; if (picker->containsIntersections()) { osgUtil::PolytopeIntersector::Intersections intersections = picker->getIntersections(); for(osgUtil::PolytopeIntersector::Intersections::iterator hitr = intersections.begin(); hitr != intersections.end(); hitr++) { if (!hitr->nodePath.empty()) { osg::NodePath nodePath = hitr->nodePath; if (nodePath.size() > 1) { if (!isDrawingSelectionQuad) { result = doSinglePick(nodePath, hitr->primitiveIndex); break; } else { bool nodePicked = false; bool edgePicked = false; if (selectionType == SelectionType::NODE || selectionType == SelectionType::ALL) nodePicked = doNodePick(nodePath); if ((selectionType == SelectionType::EDGE || selectionType == SelectionType::ALL) && !nodePicked) edgePicked = doEdgePick(nodePath, hitr->primitiveIndex); result = result || nodePicked || edgePicked; } } } } } return result; } bool PickHandler::doSinglePick(osg::NodePath nodePath, unsigned int primitiveIndex) { if (selectionType == SelectionType::NODE) return doNodePick(nodePath); else if (selectionType == SelectionType::EDGE) return doEdgePick(nodePath, primitiveIndex); else return (doNodePick(nodePath) || doEdgePick(nodePath, primitiveIndex)); } bool PickHandler::doNodePick(osg::NodePath nodePath) { Data::Node * n = dynamic_cast<Data::Node *>(nodePath[nodePath.size() - 1]); if (n != NULL) { if (isAltPressed && pickMode == PickMode::NONE && !isShiftPressed) { cameraManipulator->setCenter(n->getTargetPosition()); } else if (isAltPressed && pickMode == PickMode::NONE && isShiftPressed) { if (appConf->getValue("Viewer.PickHandler.SelectInterestPoints").toInt() == 1) { Data::Graph * currentGraph = Manager::GraphManager::getInstance()->getActiveGraph(); Util::ElementSelector::weightedElementSelector(currentGraph->getNodes(), appConf->getValue("Viewer.PickHandler.AutopickedNodes").toInt(), this); } bool wasEmpty = false; if (pickedNodes.isEmpty()) { pickedNodes.append(n); wasEmpty = true; } if (appConf->getValue("Viewer.Display.CameraPositions").toInt() == 1) { n->setColor(osg::Vec4(0, 1, 0, 1)); } cameraManipulator->setNewPosition(n->getCurrentPosition(), getSelectionCenter(false), getSelectedNodes()->toStdList(), getSelectedEdges()->toStdList()); if (wasEmpty) pickedNodes.removeFirst(); } else if (pickMode != PickMode::NONE) { if (!pickedNodes.contains(n)) { pickedNodes.append(n); n->setSelected(true); } if (isCtrlPressed) unselectPickedNodes(n); return true; } } return false; } bool PickHandler::doEdgePick(osg::NodePath nodePath, unsigned int primitiveIndex) { osg::Geode * geode = dynamic_cast<osg::Geode *>(nodePath[nodePath.size() - 1]); if (geode != 0) { osg::Drawable * d = geode->getDrawable(0); osg::Geometry * geometry = d->asGeometry(); if (geometry != NULL) { Data::Edge * e = dynamic_cast<Data::Edge *>(geometry->getPrimitiveSet(primitiveIndex)); if (e != NULL) { if (isAltPressed && pickMode == PickMode::NONE && !isShiftPressed) { osg::ref_ptr<osg::Vec3Array> coords = e->getCooridnates(); cameraManipulator->setCenter(DataHelper::getMassCenter(coords)); cameraManipulator->setDistance(Util::ApplicationConfig::get()->getValue("Viewer.PickHandler.PickedEdgeDistance").toFloat()); } else if (isAltPressed && pickMode == PickMode::NONE && isShiftPressed) { if (appConf->getValue("Viewer.PickHandler.SelectInterestPoints").toInt() == 1) { Data::Graph * currentGraph = Manager::GraphManager::getInstance()->getActiveGraph(); Util::ElementSelector::weightedElementSelector(currentGraph->getNodes(), appConf->getValue("Viewer.PickHandler.AutopickedNodes").toInt(), this); } bool wasEmpty = false; if (pickedEdges.isEmpty()) { pickedEdges.append(e); wasEmpty = true; } osg::Vec3f edgeCenter = (e->getSrcNode()->getCurrentPosition() + e->getDstNode()->getCurrentPosition()) / 2; cameraManipulator->setNewPosition(edgeCenter, getSelectionCenter(false), getSelectedNodes()->toStdList(), getSelectedEdges()->toStdList()); if (wasEmpty) pickedEdges.removeFirst(); } else if (pickMode != PickMode::NONE) { if (!pickedEdges.contains(e)) { pickedEdges.append(e); e->setSelected(true); } if (isCtrlPressed) unselectPickedEdges(e); return true; } return true; } } } return false; } bool PickHandler::dragNode(osgViewer::Viewer * viewer) { QLinkedList<osg::ref_ptr<Data::Node> >::const_iterator i = pickedNodes.constBegin(); osg::Matrixd& viewM = viewer->getCamera()->getViewMatrix(); osg::Matrixd& projM = viewer->getCamera()->getProjectionMatrix(); osg::Matrixd screenM = viewer->getCamera()->getViewport()->computeWindowMatrix(); osg::Matrixd compositeM = viewM*projM*screenM; osg::Matrixd compositeMi = compositeMi.inverse(compositeM); float scale = appConf->getValue("Viewer.Display.NodeDistanceScale").toFloat(); while (i != pickedNodes.constEnd()) { osg::Vec3f screenPoint = (*i)->getTargetPosition() * compositeM; osg::Vec3f newPosition = osg::Vec3f(screenPoint.x() - (origin_mX - _mX) / scale, screenPoint.y() - (origin_mY - _mY) / scale, screenPoint.z()); (*i)->setTargetPosition(newPosition * compositeMi); ++i; } origin_mX = _mX; origin_mY = _mY; AppCore::Core::getInstance()->getLayoutThread()->wakeUp(); return (pickedNodes.size() > 0); } void PickHandler::drawSelectionQuad(float origin_mX, float origin_mY, osgViewer::Viewer * viewer) { osg::ref_ptr<osg::StateSet> quadStateSet = new osg::StateSet; quadStateSet->setMode(GL_BLEND,osg::StateAttribute::ON); quadStateSet->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); quadStateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF); quadStateSet->setAttributeAndModes(new osg::BlendFunc, osg::StateAttribute::ON); quadStateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); quadStateSet->setRenderBinDetails( 11, "RenderBin"); osg::ref_ptr<osg::Vec3Array> coordinates = new osg::Vec3Array; osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array; osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry; coordinates->push_back(osg::Vec3(origin_mX, origin_mY, -1)); coordinates->push_back(osg::Vec3(origin_mX, origin_mY, -1)); coordinates->push_back(osg::Vec3(origin_mX, origin_mY, -1)); coordinates->push_back(osg::Vec3(origin_mX, origin_mY, -1)); colors->push_back(osg::Vec4(1,1,1,0.1f)); geometry->setVertexArray(coordinates); geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4)); geometry->setColorArray(colors); geometry->setStateSet(quadStateSet); geometry->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE); selectionQuad = new osg::Geode; selectionQuad->addDrawable(geometry); osgViewer::ViewerBase::Windows win; viewer->getWindows(win); int x, y, w, h; win.at(0)->getWindowRectangle(x, y, w, h); osg::ref_ptr<osg::Projection> projectionMatrix = new osg::Projection; projectionMatrix->setMatrix(osg::Matrix::ortho2D(x, w, y, h)); osg::ref_ptr<osg::MatrixTransform> modelViewMatrix = new osg::MatrixTransform; modelViewMatrix->setMatrix(osg::Matrix::identity()); modelViewMatrix->setReferenceFrame(osg::Transform::ABSOLUTE_RF); group = new osg::Group; group->addChild(projectionMatrix); projectionMatrix->addChild(modelViewMatrix); modelViewMatrix->addChild(selectionQuad); coreGraph->getCustomNodeList()->push_back(group); } void PickHandler::toggleSelectedNodesFixedState(bool isFixed) { QLinkedList<osg::ref_ptr<Data::Node> >::const_iterator i = pickedNodes.constBegin(); while (i != pickedNodes.constEnd()) { (*i)->setFixed(isFixed); ++i; } } void PickHandler::unselectPickedNodes(osg::ref_ptr<Data::Node> node) { if (node == NULL) { QLinkedList<osg::ref_ptr<Data::Node> >::const_iterator i = pickedNodes.constBegin(); while (i != pickedNodes.constEnd()) { (*i)->setSelected(false); ++i; } pickedNodes.clear(); } else { node->setSelected(false); pickedNodes.removeOne(node); } } void PickHandler::unselectPickedEdges(osg::ref_ptr<Data::Edge> edge) { if (edge == NULL) { QLinkedList<osg::ref_ptr<Data::Edge> >::const_iterator i = pickedEdges.constBegin(); while (i != pickedEdges.constEnd()) { (*i)->setSelected(false); ++i; } pickedEdges.clear(); } else { edge->setSelected(false); pickedEdges.removeOne(edge); } } osg::Vec3 PickHandler::getSelectionCenter(bool nodesOnly) { osg::ref_ptr<osg::Vec3Array> coordinates = new osg::Vec3Array; float scale = appConf->getValue("Viewer.Display.NodeDistanceScale").toFloat(); if (!nodesOnly) { QLinkedList<osg::ref_ptr<Data::Edge> >::const_iterator ei = pickedEdges.constBegin(); while (ei != pickedEdges.constEnd()) { coordinates->push_back(DataHelper::getMassCenter((*ei)->getCooridnates())); ++ei; } } QLinkedList<osg::ref_ptr<Data::Node> >::const_iterator ni = pickedNodes.constBegin(); while (ni != pickedNodes.constEnd()) { coordinates->push_back((*ni)->getCurrentPosition()); ++ni; } osg::Vec3 center; if (coordinates->size() > 0) center = Vwr::DataHelper::getMassCenter(coordinates); return center * scale; } void PickHandler::setSelectedNodesInterpolation(bool state) { QLinkedList<osg::ref_ptr<Data::Node> >::const_iterator i = pickedNodes.constBegin(); while (i != pickedNodes.constEnd()) { (*i)->setUsingInterpolation(state); ++i; } }
[ "kapec@genepool.(none)", "[email protected]" ]
[ [ [ 1, 2 ], [ 4, 7 ], [ 9, 14 ], [ 16, 164 ], [ 175, 382 ], [ 384, 384 ], [ 411, 444 ], [ 446, 451 ], [ 474, 651 ], [ 653, 660 ], [ 662, 673 ] ], [ [ 3, 3 ], [ 8, 8 ], [ 15, 15 ], [ 165, 174 ], [ 383, 383 ], [ 385, 410 ], [ 445, 445 ], [ 452, 473 ], [ 652, 652 ], [ 661, 661 ] ] ]
24bac8d8ca788fb01123766f2b98acaca762fd62
58ef4939342d5253f6fcb372c56513055d589eb8
/ScheduleMessage/Client/source/Views/inc/LogoContainer.h
25eeb519a8a2f087abe0638afd900a1400468c7d
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,558
h
/* ============================================================================ Name : LogoContainer.h Author : Version : 1.0 Copyright : Your copyright notice Description : CLogoContainer declaration ============================================================================ */ #ifndef LOGOCONTAINER_H #define LOGOCONTAINER_H // INCLUDES #include <coecntrl.h> // CLASS DECLARATION class CFbsBitmap; /** * CLogoContainer * */ class CLogoContainer : public CCoeControl, MCoeControlObserver { public: // Constructors and destructor /** * Destructor. */ ~CLogoContainer(); /** * Two-phased constructor. */ static CLogoContainer* NewL(const TRect& aRect); /** * Two-phased constructor. */ static CLogoContainer* NewLC(const TRect& aRect); private: /** * Constructor for performing 1st stage construction */ CLogoContainer(); /** * EPOC default constructor for performing 2nd stage construction */ void ConstructL(const TRect& aRect); public: // Functions from base classes TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType); private: // Functions from base classes void SizeChanged(); TInt CountComponentControls() const; CCoeControl* ComponentControl(TInt aIndex) const; void Draw(const TRect& aRect) const; void HandleControlEventL(CCoeControl* aControl, TCoeEvent aEventType); void HandleResourceChange( TInt aType ); private: //data CFbsBitmap* iLogo; }; #endif // LOGOCONTAINER_H
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 74 ] ] ]
2fdee9e2bfbc9ef7b3a2f0dfbf485c3ddd0dfd16
cd3cb866cf33bdd9584d08f4d5904123c7d93da6
/filtersdialog.h
4a53ce0f043271681997b3bcfb2c03602ea897f7
[]
no_license
benkopolis/conflict-resolver
d910aa0e771be2a1108203a3fd6da06ebdca5680
d4185a15e5c2ac42034931913ca97714b21a977c
refs/heads/master
2021-01-01T17:16:59.418070
2011-01-29T17:49:27
2011-01-29T17:49:27
32,231,168
0
0
null
null
null
null
UTF-8
C++
false
false
883
h
#ifndef FILTERSDIALOG_H #define FILTERSDIALOG_H #include <QDialog> #include <QDateTime> #include "contentmodel.h" namespace Ui { class FiltersDialog; } class FiltersDialog : public QDialog { Q_OBJECT public: FiltersDialog(ContentModel* c, QWidget *parent = 0); ~FiltersDialog(); inline bool isOkClicked() const {return _ok; } inline QDateTime dateTime() const { return _dateTime; } inline bool isAscending() const { return _ascending; } inline bool isDontFilterConflicts() const { return _dontFilterConf; }; protected: void changeEvent(QEvent *e); private: Ui::FiltersDialog *ui; ContentModel* _model; bool _ok; QDateTime _dateTime; bool _ascending; bool _dontFilterConf; private slots: void on__cancel_clicked(); void on__ok_clicked(); }; #endif // FILTERSDIALOG_H
[ "benkopolis@ce349ab3-abbd-076b-ff20-4646c42d6692" ]
[ [ [ 1, 40 ] ] ]
9438e6cfd08d24ee127215507b0fc0fcc8b60810
f95341dd85222aa39eaa225262234353f38f6f97
/DesktopX/Plugins/DXSystemEx/DXSystemEx/DXSystemEx.cpp
a6d1bb65dc44168bc97e52ee3359e69e3543dbdb
[]
no_license
Templier/threeoaks
367b1a0a45596b8fe3607be747b0d0e475fa1df2
5091c0f54bd0a1b160ddca65a5e88286981c8794
refs/heads/master
2020-06-03T11:08:23.458450
2011-10-31T04:33:20
2011-10-31T04:33:20
32,111,618
0
0
null
null
null
null
UTF-8
C++
false
false
20,711
cpp
/////////////////////////////////////////////////////////////////////////////////////////////// // // DXSystemEx - Extended System Information // // Copyright (c) 2009-2010, Julien Templier // All rights reserved. // /////////////////////////////////////////////////////////////////////////////////////////////// // * $LastChangedRevision$ // * $LastChangedDate$ // * $LastChangedBy$ /////////////////////////////////////////////////////////////////////////////////////////////// // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. The name of the author may not be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <SDPlugin.h> #include <SDScriptedPlugin.h> #include <time.h> #include "DXSystemEx.h" #include "dlldatax.h" #include "SystemEx.h" #include "Utils/VersionCheck.h" #include "Volume/VistaCallBackSetup.h" ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Configuration Dialog ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Size of the version text #define VERSION_SIZE 30 #define MAX_NUMBER_SIZE 5 INT_PTR CALLBACK ConfigurePlugin(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam) { CSystemEx::Config* config = (CSystemEx::Config*) GetProp(hDlg, "config"); switch(iMsg) { case WM_INITDIALOG: { // Set the version text char version[VERSION_SIZE]; sprintf_s(version, VERSION_SIZE*sizeof(char), "v%i.%i Build %i",VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD); SetDlgItemText(hDlg, IDC_BUILD,version); // Get Data SetProp(hDlg, "config", (HANDLE) lParam); config = (CSystemEx::Config*) GetProp(hDlg, "config"); if(!config) { MessageBox(hDlg, "Error initializing Dialog: config not present", "Initialization Error", MB_OK|MB_ICONERROR); EndDialog(hDlg, 0); break; } // Init & fill the controls CheckDlgButton(hDlg, IDC_DRAGANDDROP, config->enableDnD); CheckDlgButton(hDlg, IDC_MONITORS, config->enableMonitors); CheckDlgButton(hDlg, IDC_INSTANCE, config->enableInstance); #ifdef DEBUG SetDlgItemText(hDlg, IDC_BETA, "BETA - DO NOT REDISTRIBUTE"); #endif break; } case WM_COMMAND: switch(LOWORD(wParam)) { case IDOK: { if(!config) break; // Input boxes are set to number, so no need to check for conversion (famous last words :P) IsDlgButtonChecked(hDlg, IDC_DRAGANDDROP) ? config->enableDnD = true : config->enableDnD = false; IsDlgButtonChecked(hDlg, IDC_MONITORS) ? config->enableMonitors = true : config->enableMonitors = false; IsDlgButtonChecked(hDlg, IDC_INSTANCE) ? config->enableInstance = true : config->enableInstance = false; } case IDCANCEL: EndDialog(hDlg, 0); return TRUE; break; } break; case WM_DESTROY: RemoveProp(hDlg, "config"); break; case WM_CLOSE: EndDialog(hDlg, 0); return FALSE; } return FALSE; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // DesktopX Plugin ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOL (__stdcall *SDHostMessage)(UINT, DWORD, DWORD) = NULL; HINSTANCE g_hInstance = NULL; static HANDLE processHandle = NULL; DECLARE_DXPLUGIN_READTYPEINFO(ReadSystemExTypeInfo, IID_ISystemEx); int WritePrivateProfileInt(LPCTSTR lpAppName, LPCTSTR lpKeyName, int iValue, LPCTSTR lpFileName); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Plugin-specific data ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define WHEEL_DEFAULT_VALUE 3 #define WHEEL_PAGE_LINES 10 // Dragging struct MouseWheelData { DWORD objID; POINTS current; bool isMouseDragging; bool ignoreNext; MouseWheelData() : objID(NULL), isMouseDragging(false) {} ~MouseWheelData() {} void Reset() { objID = NULL; isMouseDragging = false; } }; static MouseWheelData mouseWheelData; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SDMessage ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///<summary> /// Main function ///</summary> BOOL SDMessage(DWORD objID, DWORD *pluginIndex, UINT messageID, DWORD param1, DWORD param2) { switch (messageID) { // Query info about this plugin case SD_QUERY_PLUGIN_INFO: { SD_PLUGIN_INFO *pi = (SD_PLUGIN_INFO*) param1; lstrcpy(pi->plugin_name, PLUGIN_NAME); lstrcpy(pi->plugin_author, PLUGIN_AUTHOR); lstrcpy(pi->plugin_capability, PLUGIN_CAPABILITY); pi->plugin_version = VERSION_MAJOR*100 + VERSION_MINOR; pi->supported_platforms = PLUGIN_PLATFORM; pi->supported_hosts = PLUGIN_HOSTS; return TRUE; } // Initialize the plugin DLL case SD_INITIALIZE_MODULE: { g_hInstance = (HINSTANCE) param2; SDHostMessage = (BOOL (__stdcall *)(UINT, DWORD, DWORD)) param1; if (Is_WinVista_or_Later()) RegisterCallBack(); OleInitialize(NULL); return TRUE; } // Create a new instance of the plugin case SD_CREATE_PLUGIN: { *pluginIndex = NULL; #ifdef DEBUG // Check for expiration date struct tm now; __time64_t nowTime; errno_t err; _time64(&nowTime); // get current time err = _localtime64_s(&now, &nowTime); // convert time to structure if (err) // there is no bugs in the program, only features goto label_expiration; if (now.tm_year + 1900 > EXPIRATION_YEAR) goto label_expiration; if (now.tm_year + 1900 == EXPIRATION_YEAR) if (now.tm_mon > EXPIRATION_MONTH-1) goto label_expiration; if (now.tm_year + 1900 == EXPIRATION_YEAR) if (now.tm_mon == EXPIRATION_MONTH-1) if (now.tm_mday > EXPIRATION_DAY) goto label_expiration; #endif DWORD *flags = (DWORD *) param1; *flags = SD_FLAG_SUBCLASS | SD_FLAG_NO_USER_CONFIG; CComObject<CSystemEx>* pSystemEx; CComObject<CSystemEx>::CreateInstance(&pSystemEx); *pluginIndex = (DWORD)pSystemEx; SCRIPTABLEPLUGIN sp; strcpy_s(sp.szName, "SystemEx"); pSystemEx->QueryInterface(IID_IUnknown, (void**)&sp.pUnk); sp.pTI = ReadSystemExTypeInfo(g_hInstance); SDHostMessage(SD_REGISTER_SCRIPTABLE_PLUGIN, objID, (DWORD)&sp); return TRUE; #ifdef DEBUG label_expiration: char message[2000]; sprintf_s(message, "This beta version of DXSystemEx expired on %d/%d/%d.\n\n Please check http://julien.wincustomize.com or http://www.templier.info for new versions.", EXPIRATION_MONTH, EXPIRATION_DAY, EXPIRATION_YEAR); MessageBox(NULL, (char *)message, "Beta version expiration!", MB_ICONERROR|MB_OK); return FALSE; #endif } // Load saved plugin data case SD_LOAD_DATA: { CComObject<CSystemEx>* pSystemEx = (CComObject<CSystemEx>*) *pluginIndex; if (pSystemEx == NULL) return FALSE; // Get our ini file char objectDirectory[MAX_PATH]; char iniFile[MAX_PATH]; SDHostMessage(SD_GET_OBJECT_DIRECTORY, (DWORD) objectDirectory, 0); sprintf_s(iniFile, "%s\\DXSystemEx-%s.ini", objectDirectory, (char *) param1); // Save configuration pSystemEx->config->enableDnD = (GetPrivateProfileInt("Config", "EnableDnd", 1, iniFile) == 1); pSystemEx->config->enableMonitors = (GetPrivateProfileInt("Config", "EnableMonitors", 1, iniFile) == 1); pSystemEx->config->enableInstance = (GetPrivateProfileInt("Config", "EnableInstance", 1, iniFile) == 1); return TRUE; } // Configure this instance case SD_CONFIGURE: { CComObject<CSystemEx>* pSystemEx = (CComObject<CSystemEx>*) *pluginIndex; if (pSystemEx == NULL) return FALSE; // Show the config for the current instance DialogBoxParam(g_hInstance, MAKEINTRESOURCE(IDD_CONFIG), (HWND)param2, ConfigurePlugin, (LPARAM)pSystemEx->config); return TRUE; } // Duplicate this instance data case SD_DUPLICATE_PLUGIN: { CComObject<CSystemEx>* pSystemEx = (CComObject<CSystemEx>*) *pluginIndex; CComObject<CSystemEx>* pOriginalSystemEx = (CComObject<CSystemEx>*) param2; if (pSystemEx == NULL) return FALSE; pSystemEx->config->enableDnD = pOriginalSystemEx->config->enableDnD; pSystemEx->config->enableMonitors = pOriginalSystemEx->config->enableMonitors; pSystemEx->config->enableInstance = pOriginalSystemEx->config->enableInstance; return TRUE; } // Start running this instance of the plugin case SD_INITIALIZE_PLUGIN: { CComObject<CSystemEx>* pSystemEx = (CComObject<CSystemEx>*) *pluginIndex; SD_PLUGIN_INIT* pluginInit = (SD_PLUGIN_INIT*)param1; if (pSystemEx == NULL) return FALSE; // Get object GUIID (used to compute lock name) char guiid[100]; SDHostMessage(SD_GUIID_FROM_OBJID, objID, (DWORD)&guiid); pSystemEx->Init(objID, string(guiid), pluginInit->hwnd); if (Is_WinVista_or_Later()) pVistaVolumeCallback->addID(objID); return TRUE; } case SD_WINDOW_MESSAGE: { CComObject<CSystemEx>* pSystemEx = (CComObject<CSystemEx>*) *pluginIndex; if (pSystemEx == NULL) return FALSE; LPMSG msg = reinterpret_cast<LPMSG>(param1); switch(msg->message) { // Monitor information case WM_DISPLAYCHANGE: pSystemEx->EnableMonitorInfo(pSystemEx->config->enableMonitors); break; ////////////////////////////////////////////////////////////////////////// // Middle button drag case WM_MOUSEMOVE: { // FIXME: BROKEN AT THE MOMENT: DISABLE //// Check if we are dragging with the middle mouse button //if (!((msg->wParam & MK_MBUTTON) == MK_MBUTTON)) // return FALSE; //// Ignore any movement from child objects //if (objID != mouseWheelData.objID) // return FALSE; //// Get delta since last move //int delta_x = GET_X_LPARAM(msg->lParam) - mouseWheelData.current.x; //int delta_y = GET_Y_LPARAM(msg->lParam) - mouseWheelData.current.y; //if (delta_x == 0 && delta_y == 0) // return FALSE; //// Get the object position //RECT position; //SDHostMessage(SD_GET_ABSOLUTE_RECT, objID, (DWORD)&position); //// Move the object //SD_SOP_INFO positionInfo; //positionInfo.x = position.left + delta_x; //positionInfo.y = position.top + delta_y; //positionInfo.flags = SD_SOP_MOVE; //SDHostMessage(SD_SET_OBJECT_POS, objID, (DWORD)&positionInfo); //// Save position //mouseWheelData.current = MAKEPOINTS(msg->lParam); //mouseWheelData.isMouseDragging = true; //return TRUE; // break; } case WM_MOUSELEAVE: { // Stop mouse dragging mouseWheelData.Reset(); break; } // Middle Button Up case WM_MBUTTONUP: { SD_SCRIPTABLE_EVENT se; se.cbSize = sizeof(SD_SCRIPTABLE_EVENT); se.flags=0; lstrcpy(se.szEventName, PLUGIN_PREFIX "OnMButtonUp"); // Message parameters memset(&se.dp, 0, sizeof(DISPPARAMS)); se.dp.cArgs = 3; VARIANT* lpvt = (VARIANT*)malloc(sizeof(VARIANT)*3); VariantInit(&lpvt[0]); VariantInit(&lpvt[1]); VariantInit(&lpvt[2]); lpvt[0].vt = VT_BOOL; lpvt[0].lVal = mouseWheelData.isMouseDragging ? VARIANT_TRUE : VARIANT_FALSE; lpvt[1].vt = VT_I4; lpvt[1].lVal = GET_Y_LPARAM(msg->lParam); lpvt[2].vt = VT_I4; lpvt[2].lVal = GET_X_LPARAM(msg->lParam); se.dp.rgvarg = lpvt; SDHostMessage(SD_SCRIPTABLE_PLUGIN_EVENT, objID, (DWORD) &se); free(se.dp.rgvarg); // Stop mouse dragging mouseWheelData.Reset(); break; } // Middle button down case WM_MBUTTONDOWN: { // Start dragging on next MOUSE_MOVE if we do not get a WM_MBUTTONUP mouseWheelData.objID = objID; mouseWheelData.current = MAKEPOINTS(msg->lParam); SD_SCRIPTABLE_EVENT se; se.cbSize = sizeof(SD_SCRIPTABLE_EVENT); se.flags=0; lstrcpy(se.szEventName, PLUGIN_PREFIX "OnMButtonDown"); // Message parameters memset(&se.dp, 0, sizeof(DISPPARAMS)); se.dp.cArgs = 2; VARIANT* lpvt = (VARIANT*)malloc(sizeof(VARIANT)*2); VariantInit(&lpvt[0]); VariantInit(&lpvt[1]); lpvt[0].vt = VT_I4; lpvt[0].lVal = GET_Y_LPARAM(msg->lParam); lpvt[1].vt = VT_I4; lpvt[1].lVal = GET_X_LPARAM(msg->lParam); se.dp.rgvarg = lpvt; SDHostMessage(SD_SCRIPTABLE_PLUGIN_EVENT, objID, (DWORD) &se); free(se.dp.rgvarg); break; } ////////////////////////////////////////////////////////////////////////// // Mouse wheel case WM_MOUSEWHEEL: { // Get wheel delta int wheel_delta = GET_WHEEL_DELTA_WPARAM(msg->wParam); // Compute scroll delta // http://blogs.msdn.com/oldnewthing/archive/2003/08/07/54615.aspx static int wheel_carryover = 0; UINT scroll_lines; if (!SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &scroll_lines, 0)) { scroll_lines = WHEEL_DEFAULT_VALUE; } // If user specified no wheel scrolling, then don't do wheel scrolling. if (scroll_lines == 0) return FALSE; // If user specified scrolling by pages, do so. if (scroll_lines == WHEEL_PAGESCROLL) scroll_lines = WHEEL_PAGE_LINES; // Accumulate wheel motion wheel_delta += wheel_carryover; // See how many lines we should scroll. This relies on round-towards-zero. int delta_lines = wheel_delta * (int)scroll_lines / WHEEL_DELTA; // Record the unused portion as the next carryover. wheel_carryover = wheel_delta - delta_lines * WHEEL_DELTA / (int)scroll_lines; // Send the message to the object SD_SCRIPTABLE_EVENT se; se.cbSize = sizeof(SD_SCRIPTABLE_EVENT); lstrcpy(se.szEventName, PLUGIN_PREFIX "OnMouseWheel"); se.flags=0; memset(&se.dp, 0, sizeof(DISPPARAMS)); se.dp.cArgs = 1; VARIANT* lpvt = (VARIANT*)malloc(sizeof(VARIANT)*1); VariantInit(&lpvt[0]); lpvt[0].vt = VT_I4; lpvt[0].lVal = delta_lines; se.dp.rgvarg = lpvt; SDHostMessage(SD_SCRIPTABLE_PLUGIN_EVENT, objID, (DWORD) &se); free(se.dp.rgvarg); return TRUE; } case WM_COPYDATA: { if (!pSystemEx->config->enableInstance) return TRUE; COPYDATASTRUCT* pCDS = reinterpret_cast<COPYDATASTRUCT*>(msg->lParam); char* commandLine = static_cast<char*>(pCDS->lpData); // Call script: Instance_OnNewInstance SD_SCRIPTABLE_EVENT se; memset(&se.dp, 0, sizeof(DISPPARAMS)); se.cbSize = sizeof(SD_SCRIPTABLE_EVENT); se.flags=0; lstrcpy(se.szEventName, PLUGIN_PREFIX "OnNewInstance"); se.dp.cArgs = 1; VARIANT* lpvt = (VARIANT*)malloc(sizeof(VARIANT)); // Get command line arguments USES_CONVERSION; pSystemEx->ExtractCommandLine(A2W(commandLine), &lpvt[0], true); se.dp.rgvarg = lpvt; SDHostMessage(SD_SCRIPTABLE_PLUGIN_EVENT, objID, (DWORD) &se); free(se.dp.rgvarg); return TRUE; } } return FALSE; } // Save the plugin data before unload case SD_SAVE_DATA: { // We need to come up with an instance ID and register our config file // we don't care whether we are in export mode or not CComObject<CSystemEx>* pSystemEx = (CComObject<CSystemEx>*) *pluginIndex; if (pSystemEx == NULL) return FALSE; // Use the object ID pointer as our instance ID char instanceID[20]; _ltoa_s((long) objID, instanceID, 10); lstrcpy((char *) param1, instanceID); char path[MAX_PATH], iniFile[MAX_PATH]; SDHostMessage(SD_GET_OBJECT_DIRECTORY, (DWORD) path, 0); sprintf_s(iniFile, "%s\\DXSystemEx-%s.ini", path, instanceID); // Save configuration WritePrivateProfileInt("Config", "EnableDnd", pSystemEx->config->enableDnD ? 1 : 0, iniFile); WritePrivateProfileInt("Config", "EnableMonitors", pSystemEx->config->enableMonitors ? 1 : 0, iniFile); WritePrivateProfileInt("Config", "EnableInstance", pSystemEx->config->enableInstance ? 1 : 0, iniFile); SDHostMessage(SD_REGISTER_FILE, (DWORD) iniFile, 0); return TRUE; } // Stop running this instance of the plugin case SD_TERMINATE_PLUGIN: { if (Is_WinVista_or_Later()) pVistaVolumeCallback->removeID(objID); CComObject<CSystemEx>* pSystemEx = (CComObject<CSystemEx>*) *pluginIndex; if (pSystemEx != NULL) pSystemEx->Terminate(); return TRUE; } // Destroy this instance of the plugin case SD_DESTROY_PLUGIN: { CComObject<CSystemEx>* pSystemEx = (CComObject<CSystemEx>*) *pluginIndex; if (pSystemEx != NULL) pSystemEx->Destroy(); SAFE_RELEASE(pSystemEx); return TRUE; } // Unload the plugin dll case SD_TERMINATE_MODULE: { if (Is_WinVista_or_Later()) UnregisterCallBack(); // Shutdown COM OleUninitialize(); return TRUE; } } return FALSE; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // COM ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CComModule _Module; BEGIN_OBJECT_MAP(ObjectMap) OBJECT_ENTRY(CLSID_SystemEx, CSystemEx) OBJECT_ENTRY(CLSID_MonitorInfo, CMonitorInfo) END_OBJECT_MAP() ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // DLL ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DECLARE_DXPLUGIN_DLLFUNCTIONS(LIBID_DXSystemExLib, "DXSystemEx.dll", "{65C94091-C8AE-4423-99A2-CEAE94F91E62}", // class "DXSystemEx.SystemEx.1", "{9F3FB81B-658E-4853-82BA-1A263630CFA5}", // type library "DXSystemEx.SystemEx", "1.0", "DXSystemEx 1.0 Type Library") ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Registry ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int WritePrivateProfileInt(LPCTSTR lpAppName, LPCTSTR lpKeyName, int iValue, LPCTSTR lpFileName) { ////////////////////////////////////////////////////////////////////////// ///Helper function included to quickly & easily save integers to an Ini char szNumber[100]; strcpy_s(szNumber, 100, ""); _itoa_s(iValue, szNumber, 100, 10); return WritePrivateProfileString(lpAppName, lpKeyName, szNumber, lpFileName); }
[ "julien.templier@ab80709b-eb45-0410-bb3a-633ce738720d" ]
[ [ [ 1, 675 ] ] ]
9605d90ba005937b19b9743e3c08e1f7916f11f3
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/LuaPlus/Src/Modules/COM/tLuaCOMTypeHandler.h
410034e3ebde155c6adc6a9543359e1be3484fb4
[ "MIT" ]
permissive
15831944/bastionlandscape
e1acc932f6b5a452a3bd94471748b0436a96de5d
c8008384cf4e790400f9979b5818a5a3806bd1af
refs/heads/master
2023-03-16T03:28:55.813938
2010-05-21T15:00:07
2010-05-21T15:00:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,165
h
// tLuaCOMTypeHandler.h: interface for the tLuaCOMTypeHandler class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_TLUACOMTYPEHANDLER_H__2CAF122C_E09B_11D3_BD2F_444553540000__INCLUDED_) #define AFX_TLUACOMTYPEHANDLER_H__2CAF122C_E09B_11D3_BD2F_444553540000__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include <ole2.h> #include "luabeans.h" #include "tLuaObjList.h" #include "LuaAux.h" class tLuaCOM; class tLuaCOMTypeHandler { public: void setOutValues(FUNCDESC* pFuncDesc, DISPPARAMS* pDispParams, stkIndex outvalue); void pushLuaArgs( DISPPARAMS* pDispParams, const ELEMDESC* pElemDesc ); void fillDispParams( DISPPARAMS& rDispParams, FUNCDESC *pfuncdesc, tLuaObjList& params, int invkind ); void releaseVariants(DISPPARAMS *pDispParams); int pushOutValues(const DISPPARAMS& dispparams); bool setRetval(const FUNCDESC *funcdesc, stkIndex luaval, VARIANTARG *pvarg); void lua2com(stkIndex luaval, VARIANTARG& varg); void com2lua(VARIANTARG varg); tLuaCOMTypeHandler(ITypeInfo *ptypeinfo, LuaBeans *lbeans); virtual ~tLuaCOMTypeHandler(); static TYPEDESC processTYPEDESC( ITypeInfo* typeinfo, TYPEDESC tdesc); protected: long * dimensionsFromBounds(SAFEARRAYBOUND* bounds, long num_bounds); void put_in_array(SAFEARRAY* safearray, VARIANT var_value, long* indices, VARTYPE vt); void inc_indices(long *indices, SAFEARRAYBOUND *bounds, unsigned long dimensions); SAFEARRAYBOUND* getRightOrderedBounds(SAFEARRAYBOUND *bounds, unsigned long num_dimensions); void Coerce(VARIANTARG& dest, VARIANTARG src, VARTYPE vt); long VariantSize(VARTYPE vt); static TYPEDESC processSAFEARRAY(ITypeInfo* typeinfo, TYPEDESC& tdesc); void toByRefParam(VARIANT& var_source, VARIANTARG * pvarg_dest); void initByRefParam(VARIANTARG* pvarg, VARTYPE vt); void pushIUnknown(IUnknown *punk); bool isIUnknown(stkIndex value); static TYPEDESC processAliases( ITypeInfo* typeinfo, const TYPEDESC& tdesc); void releaseVariant(VARIANTARG *pvarg, bool release_memory=true); static TYPEDESC processUSERDEFINED( ITypeInfo* typeinfo, const TYPEDESC& tdesc); static TYPEDESC processPTR( ITypeInfo* typeinfo, const TYPEDESC& tdesc); lua_State *L; tLuaCOM * from_lua(int index); stkIndex get_from_array( SAFEARRAY* safearray, long *indices, const VARTYPE& vt); void safearray_com2lua(VARIANTARG& varg); void safearray_lua2com( stkIndex luaval, VARIANTARG& varg, VARTYPE vt, bool from_stack = false ); void string2safearray(const char* str, long len, VARIANTARG& varg); void safearray2string(VARIANTARG & varg); ITypeInfo * m_typeinfo; LuaBeans *lbeans; }; #define LUACOM_IUNKNOWN_TAGNAME "_LuaCOM_IUnknown_tag" #endif // !defined(AFX_TLUACOMTYPEHANDLER_H__2CAF122C_E09B_11D3_BD2F_444553540000__INCLUDED_)
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
[ [ [ 1, 108 ] ] ]
b940584ec6ffe9fd4e0698497955063a7d18642c
65dee2b7ed8a91f952831525d78bfced5abd713f
/winmob/XfMobile_WM5/Gamepe/FriendsPane.h
992f04bb436572b7dcd5460f3a4708265f4bec40
[]
no_license
felixnicitin1968/XFMobile
0249f90f111f0920a423228691bcbef0ecb0ce23
4a442d0127366afa9f80bdcdaaa4569569604dac
refs/heads/master
2016-09-06T05:02:18.589338
2011-07-05T17:25:39
2011-07-05T17:25:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,855
h
#pragma once // CFriendsPane dialog #include "VividTree.h" #include "XPropertyPage.h" #include "ImageButton.h" struct XfireContact; class CFriendsPane : public CXPropertyPage { DECLARE_DYNAMIC(CFriendsPane) public: LRESULT OnAddFriend(WPARAM, LPARAM); // a connection has been closed LRESULT OnRemoveFriend(WPARAM wParam, LPARAM); // received new message LRESULT OnAddClans(WPARAM wParam, LPARAM lParam); LRESULT OnFriendStatus(WPARAM wParam, LPARAM lParam); LRESULT OnClanMembers(WPARAM wParam, LPARAM lParam); LRESULT OnConnectionStatus(WPARAM wParam, LPARAM lParam); LRESULT OnAddConversation(WPARAM wParam, LPARAM lParam); LRESULT OnRecvIM(WPARAM wParam, LPARAM lParam); BOOL CreateHtmlWindow(RECT rect); //To use images in HTML you should register them before. //strHtmlImageName should be a string that will be //used in HTML in "src" attribute of "img" tag. //This function adds image from bitmap resource with //the given id. void RegisterHtmlImage(int nResourceId, const CString& strHtmlImageName); //To use images in HTML you should register them before. //strHtmlImageName should be a string that will be //used in HTML in "src" attribute of "img" tag. //This function adds the given bitmap image. void RegisterHtmlImage(CBitmap *pBitmap, const CString& strHtmlImageName); BOOL CreateADWindow(RECT rect); //This function deletes all images virtual void DeleteHtmlImages(); //List of images that will be accessible from HTML CMapStringToOb m_imagesCache; CImageButton m_adImage; XfireContact * getClanMember(long userid); BOOL removeClanMember(long userid); BOOL addClanMember(long userid); HTREEITEM m_hOnlineFriendsSection; HTREEITEM m_hConvSection; void ResizeTreeCtrl(); void OnInlineImage(const CString &strHref, DWORD dwCookie); void OnLink(const CString &strHref); void SetHtml(const CString &strHtml); LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam) ; //LRESULT WindowProc(UINT message, WPARAM wParam, // LPARAM lParam); HICON m_OnlineIcon,m_AwayIcon,m_PersonIcon; VividTree *m_pFriendsTreeCtrl; HWND m_hwndHtml; //Instance of dll to support HTML view control HINSTANCE m_HtmlViewInstance; public: CFriendsPane(CWnd* pParent = NULL); // standard constructor virtual ~CFriendsPane(); // Dialog Data enum { IDD = IDD_CONTACTS_PANE }; virtual BOOL PreTranslateMessage(MSG* pMsg) ; protected: virtual BOOL OnInitDialog(); virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection); afx_msg void OnMenuInvite(); afx_msg void OnAdClick(); };
[ [ [ 1, 89 ] ] ]
421ff39bbfa1d182c7c0cd9cccbbea90be5c9c86
8a074a6cd0613f86f215642def7c3b578b2afb71
/B+ Tree/include/heappage.h
d42863e788adcc76c868ef87fd3fc0cb219c15bf
[]
no_license
tdw44/CS-4321-B--Tree
0a79b8387791bd8cf7681d496e7389667ea2bd1f
d8f766bf666274e7ce518fb124399ecc644cb419
refs/heads/master
2020-04-14T19:27:27.763005
2011-10-25T17:05:58
2011-10-25T17:05:58
2,644,775
0
0
null
null
null
null
UTF-8
C++
false
false
3,090
h
#ifndef HFPAGE_H #define HFPAGE_H #include "minirel.h" #include "page.h" const int INVALID_SLOT = -1; // Size of the data array in the class HeapPage const int HEAPPAGE_DATA_SIZE = MAX_SPACE - 3 * sizeof(PageID) - 4 * sizeof(short); class HeapPage { protected : struct Slot { short offset; // Offset of record from the start of data area. short length; // Length of the record. }; short numOfSlots; // Number of slots available (maybe filled or empty). short freePtr; // Offset from start of data area, where begins the free space for adding new records. short freeSpace; // Amount of free space in bytes in this page. short type; // Not used for HeapFile assignment, but will be used in B+-tree assignment. PageID pid; // Page ID of this page PageID nextPage; // Page ID of the next page. PageID prevPage; // Page ID of the prev page. char data[HEAPPAGE_DATA_SIZE]; // Data area for this page. Actual records // grow from start towards the end of a page. // Check if the slot is empty. bool SlotIsEmpty(Slot *slot) { return slot->length == INVALID_SLOT; } // Fill the slot with the given <offset, length> pair. void FillSlot(Slot *slot, int offset, int length) { slot->offset = offset; slot->length = length; } // Set the slot to be empty. void SetSlotEmpty(Slot *slot) { slot->length = INVALID_SLOT; } // Get the first slot pointer, which is lcoated in the end of data area. Slot* GetFirstSlotPointer() { return (Slot*)(data + HEAPPAGE_DATA_SIZE - sizeof(Slot)); } public: // Inialize the page with given PageID. void Init(PageID pageNo); // Insert a record into the page. Status InsertRecord(const char* recPtr, int recLen, RecordID& rid); // Delete a record from the page. Status DeleteRecord(RecordID rid); // To find the first record on a page. Status FirstRecord(RecordID& firstRid); // To find the next record on a page. Status NextRecord (RecordID curRid, RecordID& nextRid); // To retrieve a COPY of a record with ID rid from a page. Status GetRecord(RecordID rid, char* recPtr, int& len); // To retrieve a POINTER to the record. Status ReturnRecord(RecordID rid, char*& recPtr, int& len); // To return the amount of available space. int AvailableSpace(); // Check if there is any record in the page. bool IsEmpty(); // Counts the number of records in the page. int GetNumOfRecords(); // Get the PageID of next page. PageID GetNextPage(); // Get the PageID of previous page. PageID GetPrevPage(); // Set the PageID for next page. void SetNextPage(PageID pageNo); // Set the PageID for previous page. void SetPrevPage(PageID pageNo); // Get the PageID of this page. PageID PageNo(); void PrintSlotArray(); }; //#define SLOT_IS_EMPTY(s) ((s).length == INVALID_SLOT) //#define SLOT_FILL(s, o, l) do { (s).offset = (o); (s).length = (l);} while (0) //#define SLOT_SET_EMPTY(s) (s).length = INVALID_SLOT #endif
[ [ [ 1, 114 ] ] ]
8a742cec7a997b58057a6a23d9925662aa094d04
115c6a1371464f59f4e29fdc9202e082d4e9f18a
/3ba3/OS/Assignments/Deadlock/1/BankersController.h
b7de80d95d952756dcc24e074a5417bb5e040406
[]
no_license
conallob/college-notes
a371152fade819801e9d1454287ea0e06526d27a
57d29cc8e4100eba9c07c12b3c48c741799d1d27
refs/heads/master
2021-02-25T06:19:29.955774
2011-01-15T16:56:02
2011-01-15T16:56:02
245,449,579
0
0
null
null
null
null
UTF-8
C++
false
false
647
h
// $Id: BankersController.h 382 2004-11-27 18:42:37Z conall $ #ifndef BANKERSCONTROLLER_H #define BANKERSCONTROLLER_H #include "General.h" class CBankersController { public: CBankersController( CMessageQueue* message_queue, int total_resources[RESOURCE_TYPES], tProcessData process_data[NUMBER_PROCESSES] ); ~CBankersController(); bool AllocationIsPossible( int process_id, int request[RESOURCE_TYPES] ); // Implement the Bankers algorithm. void AllocateResources( int process_id, int request[RESOURCE_TYPES] ); void FreeResources( int process_id, int request[RESOURCE_TYPES] ); void Run(); }; #endif
[ [ [ 1, 18 ] ] ]
eb3cc82614b3c6470890d1046786450cb9b3e4c4
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Collide/Shape/Query/hkpShapeRayCastInput.h
aa456f730de1734f86716cc689a09ddd3db9e5df
[]
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,680
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_SHAPE_RAY_CAST_INPUT #define HK_SHAPE_RAY_CAST_INPUT #include <Common/Base/hkBase.h> class hkpRayShapeCollectionFilter; /// This is the input structure you need to fill out in order to call any hkpShape::castRay() function struct hkpShapeRayCastInput { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_COLLIDE, hkpShapeRayCastInput ); HK_DECLARE_REFLECTION(); /// The constructor initializes the filter pointer to HK_NULL, which means that no shape collection filtering /// will be performed by default. inline hkpShapeRayCastInput(); /// The start position of the ray in local space hkVector4 m_from; /// The end position of the ray in local space hkVector4 m_to; /// Filter information associated with this ray. /// You only need to set this if you supply a filter (by setting the m_rayShapeCollectionFilter) which /// accesses this value. For example, the supplied filter, hkpGroupFilter, uses this value, so if you use /// this the hkpGroupFilter as the m_rayShapeCollectionFilter you must set this value. hkUint32 m_filterInfo; /// This is the filter which will be used to decide whether to hit or not hit. /// Note: this variable will normally be set automatically by the engine if you /// call hkpWorld::castRay / hkpAabbPhantom::castRay const hkpRayShapeCollectionFilter* m_rayShapeCollectionFilter; }; #include <Physics/Collide/Shape/Query/hkpShapeRayCastInput.inl> #endif // HK_SHAPE_RAY_CAST_INPUT /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 64 ] ] ]
760906af1fcceeb7bd7a27482e9145b2d98ee337
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEAudio/SEAudioRendering/SEAudioBindable.h
374be605c08660c3849b19477a3ff003fd463ffb
[]
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
3,937
h
// 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 #ifndef Swing_AudioBindable_H #define Swing_AudioBindable_H #include "SEAudioLIB.h" #include "SEAudioRenderer.h" namespace Swing { //---------------------------------------------------------------------------- // Description: // Author:Sun Che // Date:20090619 //---------------------------------------------------------------------------- class SE_AUDIO_API SEAudioResourceIdentifier { public: // 虚基类,注意析构函数不是虚函数, // 因此被派生后,基类析构行为是未定义的, // 由于此类没有任何数据成员,也没有虚函数, // 从而避免了虚函数表指针的存在, // 这将允许派生类首先存储自己的成员变量, // 并且安全的进行如下所示的类型转换操作: // // class SubClassResourceIdentifier : public SEAudioResourceIdentifier // { // public: DataType SubClassMember; // } // SubClassResourceIdentifier* pID = <some identifier>; // Type& rSubClassMember = *(DataType*)pID; ~SEAudioResourceIdentifier(void){} protected: SEAudioResourceIdentifier(void){} }; //---------------------------------------------------------------------------- // 名称:音频资源绑定信息类 // Description: // Author:Sun Che // Date:20090619 //---------------------------------------------------------------------------- class SE_AUDIO_API SEAudioBindable { public: SEAudioBindable(void); ~SEAudioBindable(void); // 当资源在音频设备中有唯一表示时使用. SEAudioResourceIdentifier* GetIdentifier(SEAudioRenderer* pUser) const; // 当资源在音频设备中有多个表示时使用. int GetInfoCount(void) const; SEAudioResourceIdentifier* GetIdentifier(int i, SEAudioRenderer* pUser) const; void Release(void); // 用于音频资源在世界体系下的空间姿态以及其他相关音频参数的动态更新. // 由SESound对象在UpdateWorldDate函数中调用. void UpdateParams(void); private: friend class SEAudioRenderer; void OnLoad(SEAudioRenderer* pUser, SEAudioRenderer::ReleaseFunction oRelease, SEAudioRenderer::UpdateParamsFunction oUpdateParams, SEAudioResourceIdentifier* pID); void OnRelease(SEAudioRenderer* pUser, SEAudioResourceIdentifier* pID); struct Info { // 资源所绑定的audio renderer. SEAudioRenderer* User; // 释放资源时所需的audio renderer释放函数. SEAudioRenderer::ReleaseFunction Release; // 更新资源参数时所需的audio renderer更新函数. SEAudioRenderer::UpdateParamsFunction UpdateParams; // 资源在该audio renderer上的ID. SEAudioResourceIdentifier* ID; }; // 可以同时绑定给多个audio renderer, // 主要用于绑定一个audio renderer的多个不同实例. std::vector<Info> m_InfoArray; }; } #endif
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 114 ] ] ]
3456b99f9b687eab7113699c05b4e9e4d562e81d
9ad9345e116ead00be7b3bd147a0f43144a2e402
/NoCompression_AdvansedDB_Project/Operations-AND_OR_NOT-WithoutCompression/GenerateBitSet.h
189f580ea5dd876da1458978bfe9dab4b9be15c4
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
449
h
#pragma once #include <stdlib.h> #include <iostream> #include <boost/dynamic_bitset/dynamic_bitset.hpp> #include <cstdlib> #include <ctime> using namespace boost; using namespace std; class GenerateBitSet { public: GenerateBitSet(void); ~GenerateBitSet(void); dynamic_bitset<> getBitSet(int iSize, int iInterval, bool bInverse); dynamic_bitset<> getBitSet(int iSize);//generate dynamic bitset with 1 in random positions };
[ "buddhi.1986@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 19 ] ] ]
041a033b0645e10a87ab6e0975ba42770e25c5a0
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/FileBrowse/uiq/FileBrowse/src/filebrowseappui.cpp
b968aaacf43a19bdb2d821ac281f1fbbf76af2cb
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
625
cpp
// FileBrowseAppUi.cpp // // Copyright (c) 2006 Symbian Software Ltd. All rights reserved. // #include "FileBrowseAppUi.h" #include "FileBrowseDocument.h" #include "FileBrowseBaseView.h" void CFileBrowseAppUi::ConstructL() { BaseConstructL(); // Get the model from the document class CFileBrowseDocument* document = static_cast<CFileBrowseDocument*>(iDocument); CRFsEngine& engine(document->RFsEngine()); CFileBrowseBaseView* baseView = CFileBrowseBaseView::NewLC(*this,engine); AddViewL(*baseView); CleanupStack::Pop(baseView); } CFileBrowseAppUi::~CFileBrowseAppUi() {}
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 24 ] ] ]
2150303f00622dfb5242044838fae211cdddef6c
252e638cde99ab2aa84922a2e230511f8f0c84be
/reflib/src/CityEditForm.h
8994444fa88fb327f8c02774bb0ce450b51d9de2
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,024
h
//--------------------------------------------------------------------------- #ifndef CityEditFormH #define CityEditFormH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include "CityProcessForm.h" #include "VStringStorage.h" #include <Db.hpp> #include <DBCtrls.hpp> #include <Mask.hpp> #include "DBLookupComboBoxExt.h" //--------------------------------------------------------------------------- class TTourRefBookCityEditForm : public TTourRefBookCityProcessForm { __published: // IDE-managed Components private: // User declarations public: // User declarations __fastcall TTourRefBookCityEditForm(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TTourRefBookCityEditForm *TourRefBookCityEditForm; //--------------------------------------------------------------------------- #endif
[ [ [ 1, 27 ] ] ]
0f2d4504517310904f300864330d3e75012b45c1
8a3fce9fb893696b8e408703b62fa452feec65c5
/AutoBall/AutoBall/App/StateAi/TeamStates.cpp
d745ce0cb04d5aaacac3f6fcedfcb0a81900c6fc
[]
no_license
win18216001/tpgame
bb4e8b1a2f19b92ecce14a7477ce30a470faecda
d877dd51a924f1d628959c5ab638c34a671b39b2
refs/heads/master
2021-04-12T04:51:47.882699
2011-03-08T10:04:55
2011-03-08T10:04:55
42,728,291
0
2
null
null
null
null
GB18030
C++
false
false
2,952
cpp
#include "Stdafx.h" #include "State.h" #include "StateMachine.h" #include "../FootBallTeam.h" #include "../Entity/BasePlayer.h" #include "../FootBallPitch.h" #include "../Messageing/MessageDispatcher.h" #include "../../Config.h" extern FootBallPitch* g_FootBallPitch; void ChangePlayerHomeRegions(FootBallTeam* team, const int NewRegions[TeamSize]) { for (int plyr=0; plyr<TeamSize; ++plyr) { team->SetPlayerHomeRegion(plyr, NewRegions[plyr]); } } EmptyMsg(bool,Attacking,OnMessage,FootBallTeam); void Attacking::Enter(FootBallTeam* team) { const int BlueRegions[TeamSize] = {1,22,19,16,11,8,6}; const int RedRegions[TeamSize] = {45,25,28,31,32,35,41}; if (team->Color() == FootBallTeam::blue) { ChangePlayerHomeRegions(team, BlueRegions); } else { ChangePlayerHomeRegions(team, RedRegions); } team->UpdateWaitingPlayers(); } void Attacking::Execute(FootBallTeam* team) { /// 如果队伍不在控球,改变状态 if (!team->InControl()) { team->GetFSM()->ChangeState(&GetInstObj(Defending)); return; } /// 给接应队员计算最佳位置 team->BestSupportingPosition(); } void Attacking::Exit(FootBallTeam* team) { team->SetSupportingPlayer(NULL); } EmptyMsg(bool,Defending,OnMessage,FootBallTeam); void Defending::Enter(FootBallTeam* team) { const int BlueRegions[TeamSize] = {1,22,19,16,11,8,6}; const int RedRegions[TeamSize] = {45,25,28,31,32,35,41}; if (team->Color() == FootBallTeam::blue) { ChangePlayerHomeRegions(team, BlueRegions); } else { ChangePlayerHomeRegions(team, RedRegions); } team->UpdateWaitingPlayers(); } void Defending::Execute(FootBallTeam* team) { if (team->InControl()) { team->GetFSM()->ChangeState(&GetInstObj(Attacking)); return; } } void Defending::Exit(FootBallTeam* team){} EmptyMsg(bool,PrepareForKickOff,OnMessage,FootBallTeam); void PrepareForKickOff::Enter(FootBallTeam* team) { /// 重置关键队伍的指针 team->SetControllingPlayer(NULL); team->SetSupportingPlayer(NULL); team->SetReceiver(NULL); team->SetPlayerClosestToBall(NULL); team->ReturnAllFootBallerToHome(); } void PrepareForKickOff::Execute(FootBallTeam* team) { if (team->AllPlayersAtHome() && team->Opponents()->AllPlayersAtHome()) { team->GetFSM()->ChangeState(&GetInstObj(Defending)); } } void PrepareForKickOff::Exit(FootBallTeam* team) { team->Pitch()->SetGameOn(); } EmptyMsg(bool,Throw_In,OnMessage,FootBallTeam); void Throw_In::Enter(FootBallTeam* team) { team->SetThrowIn(true); } void Throw_In::Execute(FootBallTeam* team) { if ( !team->IsThrowIn() ) { team->GetFSM()->ChangeState(&GetInstObj(Attacking)); } } void Throw_In::Exit(FootBallTeam* team) { g_FootBallPitch->m_pBlueTeam->SetChaseBall(true); g_FootBallPitch->m_pRedTeam->SetChaseBall(true); team->SetThrowIn(false); }
[ [ [ 1, 139 ] ] ]