blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e9418405634d63da1361b5bd3a4904930b699a4e | c0bd82eb640d8594f2d2b76262566288676b8395 | /src/game/MapThreads.cpp | 0816f7f48a8eb83634d20e069ec5ce308715b97d | [
"FSFUL"
]
| permissive | vata/solution | 4c6551b9253d8f23ad5e72f4a96fc80e55e583c9 | 774fca057d12a906128f9231831ae2e10a947da6 | refs/heads/master | 2021-01-10T02:08:50.032837 | 2007-11-13T22:01:17 | 2007-11-13T22:01:17 | 45,352,930 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,936 | cpp | //////////////////////////////////////////////////
// Copyright (C) 2006 Burlex for WoWd Project
//////////////////////////////////////////////////
// Class WowdThread - Base class for all threads in the
// server, and allows for easy management by ThreadMgr.
#include "StdAfx.h"
void ThreadMgr::OnMapMgrCreated(MapMgr *mapMgr)
{
launch_thread(new ObjectUpdaterThread(mapMgr, mapMgr->GetInstanceID()));
if(mapMgr->GetMapId() < 2 || mapMgr->GetMapId() == 530) // Main continents
launch_thread(new UpdateObjectThread(mapMgr));
}
ObjectUpdaterThread::ObjectUpdaterThread(MapMgr *mapMgr, int32 instance_id) : WowdThread()
{
ThreadType = WOWD_THREADTYPE_OBJECTUPDATER;
m_MapMgr = mapMgr;
m_MapMgr->_objectUpdaterThread = this;
mInstance = instance_id;
eventholder = new EventableObjectHolder(instance_id);
}
ObjectUpdaterThread::~ObjectUpdaterThread()
{
m_MapMgr->_objectUpdaterThread = NULL;
delete eventholder;
}
template<>
void ObjectUpdaterThread::AddObject<Creature>(Creature* obj)
{
ASSERT(obj->GetTypeId() == TYPEID_UNIT);
ASSERT(obj->IsInWorld() && obj->GetMapMgr() && obj->GetMapCell() && obj->GetNewGUID().GetNewGuidLen());
Guard guard(creatureLock);
creatures.insert(obj);
sWorld.mLoadedCreatures[0]--;
sWorld.mLoadedCreatures[1]++;
}
template<>
void ObjectUpdaterThread::RemoveObject<Creature>(Creature* obj)
{
ASSERT(obj->GetTypeId() == TYPEID_UNIT);
Guard guard(creatureLock);
creatures.erase(obj);
sWorld.mLoadedCreatures[1]--;
sWorld.mLoadedCreatures[0]++;
}
template<>
void ObjectUpdaterThread::AddObject<GameObject>(GameObject* obj)
{
ASSERT(obj->GetTypeId() == TYPEID_GAMEOBJECT);
ASSERT(obj->IsInWorld() && obj->GetMapMgr() && obj->GetMapCell() && obj->GetNewGUID().GetNewGuidLen());
Guard guard(gameobjectLock);
gameobjects.insert(obj);
sWorld.mLoadedGameObjects[0]--;
sWorld.mLoadedGameObjects[1]++;
}
template<>
void ObjectUpdaterThread::RemoveObject<GameObject>(GameObject* obj)
{
ASSERT(obj->GetTypeId() == TYPEID_GAMEOBJECT);
Guard guard(gameobjectLock);
gameobjects.erase(obj);
sWorld.mLoadedGameObjects[1]--;
sWorld.mLoadedGameObjects[0]++;
}
void ObjectUpdaterThread::Do()
{
uint32 last_time = getMSTime();
uint32 last_cTime = getMSTime();
uint32 last_gTime = getMSTime();
uint32 diff = 0;
uint32 mstime = getMSTime();
uint32 cFlipper = 1;
uint32 gFlipper = 3;
uint32 mapid = m_MapMgr->GetMapId();
Creature * pCreature;
GameObject * pGameObject;
int result;
int objectUpdate = 1;
UpdateableCreaturesSet::iterator citr, citr_end, citr_last;
UpdateableGameobjectsSet::iterator gitr, gitr_end, gitr_last;
PlayerSet::iterator pitr, pitr_end;
Player * pPlayer;
SessionSet::iterator itr, it2;
WorldSession *session;
while(ThreadState != WOWD_THREADSTATE_TERMINATE)
{
// Provision for pausing this thread.
if(ThreadState == WOWD_THREADSTATE_PAUSED)
{
while(ThreadState == WOWD_THREADSTATE_PAUSED)
{
Sleep(200);
}
}
mstime = getMSTime();
last_time = mstime;
if(cFlipper == 1)
{
citr_end = creatures.end();
// possible uint32 overflow ~50days
if(last_cTime > mstime)
diff = 100;
else
diff = mstime - last_cTime;
citr_end = creatures.end();
for(citr = creatures.begin(); citr != citr_end;)
{
pCreature = (*citr);
citr_last = citr;
++citr;
if(!pCreature->IsInWorld() || !pCreature->GetMapCell()->IsActive())
{
creatureLock.Acquire();
creatures.erase(citr_last);
creatureLock.Release();
}
else
pCreature->Update(diff);
}
cFlipper = 0; // 2 loops away now. :)
// update event holder
eventholder->Update(diff);
// update players
pitr_end = m_MapMgr->_players.end();
pitr = m_MapMgr->_players.begin();
for(; pitr != pitr_end;)
{
pPlayer = (*pitr);
++pitr;
pPlayer->Update(diff);
}
last_cTime = mstime;
} else {
cFlipper = 1; // Next loop we can have our cake. :)
}
if(gFlipper == 3)
{
if(last_gTime > mstime)
diff = 300;
else
diff = mstime - last_gTime;
gitr_end = gameobjects.end();
for(gitr = gameobjects.begin(); gitr != gitr_end;)
{
pGameObject = (*gitr);
gitr_last = gitr;
++gitr;
if(!pGameObject->IsInWorld() || !pGameObject->GetMapCell()->IsActive())
{
gameobjectLock.Acquire();
gameobjects.erase(gitr_last);
gameobjectLock.Release();
}
else
pGameObject->Update(diff);
}
gFlipper = 0;
last_gTime = mstime;
} else {
++gFlipper;
}
for(itr = m_MapMgr->Sessions.begin(); itr != m_MapMgr->Sessions.end();)
{
session = (*itr);
it2 = itr;
++itr;
if(result = session->Update(50, m_MapMgr->GetMapId()))
{
if(result == 1)
{
// complete deletion
sWorld.DeleteSession(session);
}
m_MapMgr->Sessions.erase(it2);
}
}
// instance thread object updates are done here
if(mapid > 1 && mapid != 530)
m_MapMgr->_UpdateObjects();
// Execution time compensation. :)
mstime = getMSTime();
if(last_time > mstime)
{
Sleep(MAPMGR_SESSION_UPDATE_DELAY); // uint32 overflow
}
else
{
mstime = mstime - last_time;
if(mstime < MAPMGR_SESSION_UPDATE_DELAY)
{
mstime = MAPMGR_SESSION_UPDATE_DELAY - mstime;
if(mstime > 20)
Sleep(mstime);
}
}
}
}
void ObjectUpdaterThread::run()
{
SetThreadName("Object Updater - M%u|I%u", m_MapMgr->GetMapId(), m_MapMgr->GetInstanceID());
WOWD_THREAD_TRY_EXECUTION2
Do();
WOWD_THREAD_HANDLE_CRASH2
}
/* Update Object Thread */
// Purpose: Collect updates from MapMgr and flush them to clients
// every 100ms
UpdateObjectThread::UpdateObjectThread(MapMgr *mapMgr) : WowdThread()
{
ThreadType = WOWD_THREADTYPE_UDPATEOBJECT;
m_MapMgr = mapMgr;
m_MapMgr->_updateObjectThread = this;
}
UpdateObjectThread::~UpdateObjectThread()
{
m_MapMgr->_updateObjectThread = NULL;
}
void UpdateObjectThread::run()
{
SetThreadName("Update Object - Map %u Instance %u", m_MapMgr->GetMapId(), m_MapMgr->GetInstanceID());
WOWD_THREAD_TRY_EXECUTION2
WowdThread::run();
uint32 last_time = getMSTime();
uint32 diff, start_execute;
uint32 execution_time;
while(ThreadState != WOWD_THREADSTATE_TERMINATE)
{
// Provision for pausing this thread.
if(ThreadState == WOWD_THREADSTATE_PAUSED)
{
while(ThreadState == WOWD_THREADSTATE_PAUSED)
{
Sleep(200);
}
}
diff = getMSTime() - last_time;
start_execute = getMSTime();
last_time = start_execute;
if(ThreadState == WOWD_THREADSTATE_TERMINATE)
break;
ThreadState = WOWD_THREADSTATE_BUSY;
// now i'm just lazy
m_MapMgr->_UpdateObjects();
// end of body
if(ThreadState == WOWD_THREADSTATE_TERMINATE)
break;
ThreadState = WOWD_THREADSTATE_SLEEPING;
execution_time = getMSTime() - start_execute;
if(execution_time >= MAPMGR_UPDATE_DELAY)
{
// this _shouldn't_ really happen.. :D
sLog.outString("*** ThreadMgr: PUpdater lagging due to stress. Map=%u Cnt=%u Etm=%u", m_MapMgr->GetMapId(), m_MapMgr->GetObjectCount(), execution_time );
// no need to sleep here.
} else {
Sleep(MAPMGR_UPDATE_DELAY - execution_time);
}
}
WOWD_THREAD_HANDLE_CRASH2
}
| [
"[email protected]"
]
| [
[
[
1,
301
]
]
]
|
dee5350adc825b614bdc834a83428b09b0a431ea | 282057a05d0cbf9a0fe87457229f966a2ecd3550 | /EIBStdLib/src/GenericServer.cpp | c04a1251d90b2d45327d7c417deeaa5d1817e402 | []
| no_license | radtek/eibsuite | 0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd | 4504fcf4fa8c7df529177b3460d469b5770abf7a | refs/heads/master | 2021-05-29T08:34:08.764000 | 2011-12-06T20:42:06 | 2011-12-06T20:42:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,287 | cpp | #include "GenericServer.h"
using namespace EibStack;
CGenericServer::CGenericServer(char network_id) :
_network_id(network_id),
_status(STATUS_DISCONNECTED),
_thread(NULL),
_log(NULL),
_ifc_mode(UNDEFINED_MODE)
{
_thread = new CHeartBeatThread();
}
CGenericServer::~CGenericServer()
{
_thread->join();
}
void CGenericServer::Init(CLogFile* log)
{
_log = log;
}
/*
void CGenericServer::SetConnectionParams(const CString& network_name,
const CString& eib_server_adress,
int eib_server_port,
const CString& initial_key,
const CString& local_ip,
const CString& user_name,
const CString& password)
{
}
*/
bool CGenericServer::IsConnected()
{
return (_status == STATUS_CONNECTED);
}
int CGenericServer::SendEIBNetwork(const CCemi_L_Data_Frame& frame, BlockingMode mode)
{
if (!IsConnected()){
//write error to log file
GetLog()->Log(LOG_LEVEL_ERROR, "Cannot Send Data while not connected to EIBServer.");
return 0;
}
if(_ifc_mode == MODE_BUSMONITOR){
GetLog()->Log(LOG_LEVEL_ERROR, "Cannot Send Data while EIBServer is in BusMonitor mode. this is Read-Only mode");
return 0;
}
InternalRelayMsg msg;
//header
msg._header._client_type = _network_id;
msg._header._msg_type = EIB_MSG_TYPE_RELAY;
msg._header._mode = (char)mode;
//data
int max_len = sizeof(msg._cemi_l_data_msg);
max_len += sizeof(msg._addil);
frame.FillBuffer((unsigned char*)&msg._cemi_l_data_msg, max_len);
//encrypt the data using the shared key
CDataBuffer::Encrypt(&msg,sizeof(msg),&_encryptor.GetSharedKey());
START_TRY
//send the data to the network
_data_sock.SendTo(&msg,sizeof(msg),_eib_address,_eib_port);
END_TRY_START_CATCH_ANY
//log error
return 0;
END_CATCH
return sizeof(InternalRelayMsg);
}
int CGenericServer::SendEIBNetwork(const CEibAddress& address, unsigned char* value, int value_len, BlockingMode mode)
{
if (!IsConnected()){
//write error to log file
GetLog()->Log(LOG_LEVEL_ERROR, "Cannot Send Data while not connected to EIBServer.");
return 0;
}
if(_ifc_mode == MODE_BUSMONITOR){
GetLog()->Log(LOG_LEVEL_ERROR, "Cannot Send Data while EIBServer is in BusMonitor mode. this is Read-Only mode");
return 0;
}
ASSERT_ERROR(value_len <= MAX_EIB_VALUE_LEN,"Max Length of value exceeded. Data Cannot be sent.");
EIBInternalNetMsg msg;
//local network header
msg._header._client_type = _network_id;
msg._header._msg_type = EIB_MSG_TYPE_EIB_CMD;
msg._header._mode = (char)mode;
//msg data
msg._is_logical = address.IsGroupAddress();
msg._function = address.ToByteArray();
msg._value_len = value_len;
memcpy(&msg._value,value,value_len);
//encrypt the data using the shared key
CDataBuffer::Encrypt(&msg,sizeof(msg),&_encryptor.GetSharedKey());
START_TRY
//send the data to the network
_data_sock.SendTo(&msg,sizeof(msg),_eib_address,_eib_port);
END_TRY_START_CATCH_ANY
//log error
return 0;
END_CATCH
return sizeof(InternalNetMsg);
}
int CGenericServer::ReceiveEIBNetwork(CCemi_L_Data_Frame& frame, int timeout)
{
if (!IsConnected()){
return 0;
}
int s_port;
CString s_address;
char buffer[100];
START_TRY
int len = _data_sock.RecvFrom(buffer,sizeof(buffer),s_address,s_port,timeout);
if(len == 0){
return 0;
}
if(s_port != _eib_port || s_address != _eib_address){
//faked message
return 0;
}
CDataBuffer::Decrypt(buffer,len,&_encryptor.GetSharedKey());
EIBInternalRelayMsg* msg = (EIBInternalRelayMsg*)buffer;
if (msg->_header._client_type == _network_id && msg->_header._msg_type == EIB_MSG_TYPE_RELAY )
{
unsigned char* temp = (unsigned char*)&(msg->_cemi_l_data_msg);
frame.Parse(temp);
return len;
}
END_TRY_START_CATCH_SOCKET(e)
GetLog()->SetConsoleColor(RED);
GetLog()->Log(LOG_LEVEL_ERROR,e.what());
return 0;
END_CATCH
return 0;
}
int CGenericServer::ReceiveEIBNetwork(CEibAddress& function, unsigned char* value, unsigned char& value_len, int timeout)
{
if (!IsConnected()){
return 0;
}
int s_port;
CString s_address;
char buffer[100];
START_TRY
int len = _data_sock.RecvFrom(buffer,sizeof(buffer),s_address,s_port,timeout);
if(len == 0){
return 0;
}
if(s_port != _eib_port || s_address != _eib_address){
//faked message
return 0;
}
CDataBuffer::Decrypt(buffer,len,&_encryptor.GetSharedKey());
EIBInternalNetMsg* msg = (EIBInternalNetMsg*)buffer;
if (msg->_header._client_type == _network_id && msg->_header._msg_type == EIB_MSG_TYPE_EIB_STATUS )
{
bool is_logical = msg->_is_logical == 0 ? false : true;
function.Set((unsigned char*)&msg->_function,is_logical);
value_len = msg->_value_len;
memcpy(value,msg->_value,value_len);
return len;
}
END_TRY_START_CATCH_SOCKET(e)
GetLog()->SetConsoleColor(RED);
GetLog()->Log(LOG_LEVEL_ERROR,e.what());
return 0;
END_CATCH
return 0;
}
bool CGenericServer::Authenticate(const CString& user_name,const CString& password,const CString* key)
{
char buff[MAX_URL_LENGTH];
CDataBuffer raw_data;
int len,s_port;
CString s_address;
//create request
CHttpRequest request;
request.SetMethod(GET_M);
request.SetRequestURI(EIB_CLIENT_AUTHENTICATE);
request.SetVersion(HTTP_1_0);
request.AddHeader(USER_NAME_HEADER,user_name);
request.AddHeader(PASSWORD_HEADER,password);
request.Finalize(raw_data);
raw_data.Encrypt(key);
//send the request
_data_sock.SendTo(raw_data.GetBuffer(),raw_data.GetLength(),_eib_address,_eib_port);
GetLog()->SetConsoleColor(YELLOW);
GetLog()->Log(LOG_LEVEL_INFO,"[%s] [Send] Client Authentication",GetUserName().GetBuffer());
//wait for reply
len = _data_sock.RecvFrom(buff,MAX_URL_LENGTH,s_address,s_port,2000);
CDataBuffer raw_reply(buff,len);
raw_reply.Decrypt(key);
CHttpReply reply;
CHttpParser parser(reply,raw_reply);
if(!parser.IsLegalRequest() || reply.GetStatusCode() != STATUS_OK){
return false;
}
CHttpHeader mode_h;
if(!reply.GetHeader(EIB_INTERFACE_MODE, mode_h)){
GetLog()->Log(LOG_LEVEL_ERROR, "Missing header from reply: %s", EIB_INTERFACE_MODE);
return false;
}
_ifc_mode = (EIB_DEVICE_MODE)mode_h.GetValue().ToInt();
CString mode;
switch(_ifc_mode)
{
case MODE_TUNNELING: mode = "Tunneling";
break;
case MODE_BUSMONITOR: mode = "Bus Monitor";
break;
case MODE_ROUTING: mode = "Routing";
break;
case UNDEFINED_MODE: mode = "Undefined";
break;
}
GetLog()->SetConsoleColor(YELLOW);
GetLog()->Log(LOG_LEVEL_DEBUG, "Remote EIB Device Mode: %s", mode.GetBuffer());
GetLog()->Log(LOG_LEVEL_INFO,"[EIB] [Received] Client Authentication OK");
return true;
}
void CGenericServer::Close()
{
if (IsConnected()){
//Send disconnect msg
EIBInternalNetMsg msg;
memset(&msg,0,sizeof(msg));
//local network header
msg._header._client_type = _network_id;
msg._header._msg_type = EIB_MSG_TYPE_CLINET_DISCONNECT;
//encrypt the data using the shared key
CDataBuffer::Encrypt(&msg,sizeof(msg),&_encryptor.GetSharedKey());
START_TRY
//send the data to the network
_data_sock.SendTo(&msg,sizeof(msg),_eib_address,_eib_port);
END_TRY_START_CATCH_ANY
//do nothing in case of socket error
END_CATCH
}
if(_thread->isAlive()){
_thread->Close();
_thread->join();
}
}
bool CGenericServer::DiscoverEIBServer(const char* localIpAddr, const char* initialKey, CString& ipAddr, int& port)
{
if(this->IsConnected()){
GetLog()->Log(LOG_LEVEL_ERROR, "Error: Cannot open connection - Already connected.");
return false;
}
_status = STATUS_DURING_CONNECT;
CString ini_key(initialKey);
//Send discovery reuqest
UDPSocket discovery_sock;
//Bind to some random port
discovery_sock.SetLocalAddressAndPort(localIpAddr, 0);
//Generate the actual request
CHttpRequest discovery_req(GET_M, EIB_SERVER_AUTO_DISCOVERY_REQ, HTTP_1_0, EMPTY_STRING);
discovery_req.AddHeader(ADDRESS_HEADER, localIpAddr);
discovery_req.AddHeader(DATA_PORT_HEADER, discovery_sock.GetLocalPort());
CDataBuffer raw_req;
discovery_req.Finalize(raw_req);
//encrypt request using the key
raw_req.Encrypt(&ini_key);
//send the request
discovery_sock.SendTo(raw_req.GetBuffer(), raw_req.GetLength(), AUTO_DISCOVERY_SERVICE_ADDRESS, AUTO_DISCOVERY_SERVICE_PORT);
//wait (max 10 seconds) to response
char buffer[MAX_URL_LENGTH];
CString tmp_addr;
int tmp_port;
int len = discovery_sock.RecvFrom(buffer, sizeof(buffer), tmp_addr, tmp_port,5000);
if(len == 0){
GetLog()->Log(LOG_LEVEL_ERROR,"No data received. timeout.");
return false;
}
CDataBuffer dbf(buffer,len);
dbf.Decrypt(&ini_key);
CHttpReply reply;
CHttpParser parser(reply, dbf);
if(!parser.IsLegalRequest()) {
return false;
}
if(reply.GetStatusCode() != STATUS_OK){
return false;
}
CHttpHeader header;
if(!reply.GetHeader(ADDRESS_HEADER, header)){
GetLog()->Log(LOG_LEVEL_ERROR, "Missing header from reply: %s", ADDRESS_HEADER);
return false;
}
CString eibserveraddr = header.GetValue();
if(!reply.GetHeader(DATA_PORT_HEADER, header)){
GetLog()->Log(LOG_LEVEL_ERROR, "Missing header from reply: %s", DATA_PORT_HEADER);
return false;
}
int eibserverport = header.GetValue().ToInt();
//set values and return
ipAddr = eibserveraddr;
port = eibserverport;
return true;
}
ConnectionResult CGenericServer::OpenConnection(const CString& network_name, const CString& eib_server_adress,
int eib_server_port,const CString& initial_key,const CString& local_ip,
const CString& user_name, const CString& password)
{
int num_tries = 3;
ConnectionResult result = STATUS_NO_REPLY;
if (result != STATUS_CONN_OK && num_tries > 0){
result = OpenConnection(network_name.GetBuffer(),eib_server_adress.GetBuffer(),eib_server_port,
initial_key.GetBuffer(),local_ip.GetBuffer(), user_name.GetBuffer(),password.GetBuffer());
JTCThread::sleep(500);
num_tries--;
}
return result;
}
ConnectionResult CGenericServer::OpenConnection(const char* network_name, const char* eib_server_adress,
int eib_server_port,const char* initial_key,const char* local_ip,
const char* user_name, const char* password)
{
if(IsConnected()) {
return STATUS_ALREADY_CONNECTED;
}
_status = STATUS_DURING_CONNECT;
CString ini_key(initial_key);
CString s_address;
int len = 0,s_port;
CDataBuffer raw_data;
char buff[MAX_URL_LENGTH];
_network_name = network_name;
_eib_address = eib_server_adress;
_eib_port = eib_server_port;
_user_name = user_name;
_data_sock.SetLocalAddressAndPort(local_ip,0);
int num_tries = 1;
ConnectionResult res;
while ((res = FirstPhaseConnection(ini_key, local_ip, buff, MAX_URL_LENGTH, len)) != STATUS_CONN_OK && num_tries > 0){
--num_tries;
}
if(num_tries == 0){
return res;
}
CDataBuffer raw_reply(buff,len);
raw_reply.Decrypt(&ini_key);
CHttpReply reply;
CHttpParser parser(reply,raw_reply);
if(!parser.IsLegalRequest() || reply.GetStatusCode() != STATUS_OK){
_status = STATUS_DISCONNECTED;
return STATUS_INRERNAL_ERR;
}
CHttpHeader header;
int64 s_interim,g,n,r_interim,key;
if(!reply.GetHeader(NETWORK_SESSION_ID_HEADER, header)){
_status = STATUS_DISCONNECTED;
GetLog()->Log(LOG_LEVEL_ERROR, "Missing header from reply: %s", NETWORK_SESSION_ID_HEADER);
return STATUS_INRERNAL_ERR;
}
_session_id = header.GetValue().ToInt();
if(!reply.GetHeader(DIFFIE_HELLAM_MODULUS,header)){
_status = STATUS_DISCONNECTED;
GetLog()->Log(LOG_LEVEL_ERROR, "Missing header from reply: %s", DIFFIE_HELLAM_MODULUS);
return STATUS_INRERNAL_ERR;
}
n = header.GetValue().ToInt64();
if(!reply.GetHeader(DIFFIE_HELLAM_INTERIM, header)){
_status = STATUS_DISCONNECTED;
GetLog()->Log(LOG_LEVEL_ERROR, "Missing header from reply: %s", DIFFIE_HELLAM_INTERIM);
return STATUS_INRERNAL_ERR;
}
s_interim = header.GetValue().ToInt64();
if(!reply.GetHeader(DIFFIE_HELLAM_GENERATOR, header)){
_status = STATUS_DISCONNECTED;
GetLog()->Log(LOG_LEVEL_ERROR, "Missing header from reply: %s", DIFFIE_HELLAM_GENERATOR);
return STATUS_INRERNAL_ERR;
}
g = header.GetValue().ToInt64();
if(!reply.GetHeader(DATA_PORT_HEADER, header)){
_status = STATUS_DISCONNECTED;
GetLog()->Log(LOG_LEVEL_ERROR, "Missing header from reply: %s", DATA_PORT_HEADER);
return STATUS_INRERNAL_ERR;
}
_eib_port = header.GetValue().ToInt();
if(!reply.GetHeader(KEEPALIVE_PORT_HEADER, header)){
_status = STATUS_DISCONNECTED;
GetLog()->Log(LOG_LEVEL_ERROR, "Missing header from reply: %s", KEEPALIVE_PORT_HEADER);
return STATUS_INRERNAL_ERR;
}
GetLog()->SetConsoleColor(YELLOW);
GetLog()->Log(LOG_LEVEL_INFO,"[EIB] [Received] Server Public key");
int eib_ka_port = header.GetValue().ToInt();
_encryptor.CreateRecipientInterKey(r_interim,g,n);
_encryptor.CreateRecipientEncryptionKey(key,s_interim);
CHttpRequest http_request;
http_request.SetMethod(GET_M);
http_request.SetRequestURI(DIFFIE_HELLMAN_CLIENT_PUBLIC_DATA);
http_request.SetVersion(HTTP_1_0);
http_request.AddHeader(DIFFIE_HELLAM_INTERIM,r_interim);
http_request.AddHeader(CLIENT_TYPE_HEADER,(int)GetNetworkID());
http_request.Finalize(raw_data);
raw_data.Encrypt(&ini_key);
_data_sock.SendTo(raw_data.GetBuffer(),raw_data.GetLength(),_eib_address,_eib_port);
GetLog()->SetConsoleColor(YELLOW);
GetLog()->Log(LOG_LEVEL_INFO,"[%s] [Send] Client Public key",GetUserName().GetBuffer());
len = _data_sock.RecvFrom(buff,sizeof(buff),s_address,s_port);
raw_data.Clear();
raw_data.Add(buff,len);
raw_data.Decrypt(&_encryptor.GetSharedKey());
parser.SetData(reply,raw_data);
if(!parser.IsLegalRequest() || reply.GetStatusCode() != STATUS_OK){
_status = STATUS_DISCONNECTED;
return STATUS_INRERNAL_ERR;
}
GetLog()->SetConsoleColor(YELLOW);
GetLog()->Log(LOG_LEVEL_INFO,"[EIB] [Received] Keys exchanged succesfuly.");
if(!Authenticate(user_name, password, &_encryptor.GetSharedKey())){
_status = STATUS_DISCONNECTED;
return STATUS_INCORRECT_CREDENTIALS;
}
//set marker
_status = STATUS_CONNECTED;
//start keep alive thread here
_thread->Init(eib_ka_port,_eib_address, this);
_thread->start();
return STATUS_CONN_OK;
}
ConnectionResult CGenericServer::FirstPhaseConnection(const CString& key,const char* local_ip,
char* buff, int buf_len,int& reply_length)
{
CString s_address;
int s_port;
CDataBuffer request;
//request line
CHttpRequest http_request(GET_M,DIFFIE_HELLMAN_CLIENT_HELLO,HTTP_1_0,EMPTY_STRING);
//headers
http_request.AddHeader(NETWORK_NAME_HEADER,_network_name);
http_request.AddHeader(DATA_PORT_HEADER,_data_sock.GetLocalPort());
http_request.AddHeader(KEEPALIVE_PORT_HEADER,_thread->GetHeartBeatPort());
http_request.AddHeader(ADDRESS_HEADER,local_ip);
//end
http_request.Finalize(request);
CDataBuffer::Encrypt(request.GetBuffer(),request.GetLength(),&key);
START_TRY
GetLog()->SetConsoleColor(YELLOW);
GetLog()->Log(LOG_LEVEL_INFO,"[%s] [Send] Client Hello [%s:%d --> %s:%d]",GetUserName().GetBuffer(),
local_ip,_data_sock.GetLocalPort(),_eib_address.GetBuffer(),_eib_port);
_data_sock.SendTo(request.GetBuffer(),request.GetLength(),_eib_address,_eib_port);
reply_length = _data_sock.RecvFrom(buff,buf_len,s_address,s_port,5000);
END_TRY_START_CATCH(ex)
GetLog()->SetConsoleColor(RED);
GetLog()->Log(LOG_LEVEL_ERROR,"[%s] Cannot connect to eib server: %s",GetUserName().GetBuffer(),ex.what());
return STATUS_INRERNAL_ERR;
END_TRY_START_CATCH_SOCKET(e)
GetLog()->SetConsoleColor(RED);
GetLog()->Log(LOG_LEVEL_ERROR,"[%s] Socket Error: Reason: %s",GetUserName().GetBuffer(),e.what());
return STATUS_INRERNAL_ERR;
END_TRY_START_CATCH_ANY
GetLog()->SetConsoleColor(RED);
GetLog()->Log(LOG_LEVEL_ERROR,"[%s] Cannot connect to eib server... Unknown Exception.",GetUserName().GetBuffer());
return STATUS_INRERNAL_ERR;
END_CATCH
if (reply_length > 0){
return STATUS_CONN_OK;
}
//no reply from EIB...
GetLog()->SetConsoleColor(RED);
GetLog()->Log(LOG_LEVEL_ERROR,"No reply from EIB Server. maybe EIBServer is down?");
return STATUS_NO_REPLY;
}
const CString& CGenericServer::GetSharedKey()
{
return _encryptor.GetSharedKey();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CHeartBeatThread::CHeartBeatThread() :
_sock(0),
_parent(NULL),
_stop(false)
{
}
CHeartBeatThread::~CHeartBeatThread()
{
}
void CHeartBeatThread::Init(int server_port,const CString& server_address, CGenericServer* parent)
{
_server_port = server_port;
_server_address = server_address;
_heartbeat_interval = 10 * 1000; //[YGYG] Default heart beat interval - 10 seconds
//Parent
_parent = parent;
this->setName("HeartBeat Thread");
}
void CHeartBeatThread::Close()
{
JTCSynchronized sync(*this);
_stop = true;
this->notify();
}
void CHeartBeatThread::run()
{
ASSERT_ERROR(_parent != NULL,"Parent pointer is NULL!");
JTCSynchronized sync(*this);
CGenericServer& server = *_parent;
const CString* key = &server.GetSharedKey();
ClientHeartBeatMsg msg;
while (!_stop)
{
msg._header._client_type = server.GetNetworkID();
msg._header._msg_type = EIB_MSG_TYPE_KEEP_ALIVE;
msg._session_id = server.GetSessionID();
CDataBuffer::Encrypt(&msg,sizeof(ClientHeartBeatMsg),key);
START_TRY
_sock.SendTo(&msg,sizeof(ClientHeartBeatMsg),_server_address,_server_port);
//server.GetLog()->SetConsoleColor(BLUE);
//server.GetLog()->Log(LOG_LEVEL_DEBUG,"[%s] Heart Beat sent.",server.GetUserName().GetBuffer());
time_t start = time(NULL);
int len = _sock.RecvFrom(&msg,sizeof(ClientHeartBeatMsg),_server_address,_server_port, _heartbeat_interval);
time_t end = time(NULL);
if(len == 0){
server.GetLog()->Log(LOG_LEVEL_ERROR,"[EIB] Heart beat Ack Timeout. EIB Server is probably dead. Exit");
break;
}
CDataBuffer::Decrypt(&msg,sizeof(ClientHeartBeatMsg),key);
if(msg._header._msg_type == EIB_MSG_TYPE_KEEP_ALIVE_ACK && msg._header._client_type == EIB_TYPE_EIB_SERVER){
static int pcount = 0;
if(++pcount % 5 == 0){
server.GetLog()->SetConsoleColor(YELLOW);
server.GetLog()->Log(LOG_LEVEL_DEBUG,"[EIB] Heart beat --> [OK].");
}
this->wait((int)(_heartbeat_interval - difftime(end,start)));
}
else if(msg._header._msg_type == EIB_MSG_TYPE_SERVER_DISCONNECT && msg._header._client_type == EIB_TYPE_EIB_SERVER){
server.GetLog()->Log(LOG_LEVEL_ERROR,"[EIB] EIB Server closed the connection. Exit.");
break;
}
else{
server.GetLog()->Log(LOG_LEVEL_ERROR,"[EIB] Incorrect Heart beat Ack received. Exit.");
break;
}
END_TRY_START_CATCH_SOCKET(e)
server.GetLog()->Log(LOG_LEVEL_ERROR,"Socket Error at Client Heartbeat Thread: %s",e.what());
break;
END_CATCH
}
server.SetStatus(STATUS_DISCONNECTED);
}
| [
"[email protected]"
]
| [
[
[
1,
634
]
]
]
|
03b18525d4a55213f5ca2a0e87484545922ac264 | cb621dee2a0f09a9a2d5d14ffaac7df0cad666a0 | /http/basic_async_server.hpp | d91cadeebce596bd343d5b58700c43f7bf85c416 | [
"BSL-1.0"
]
| permissive | ssiloti/http | a15fb43c94c823779f11fb02e147f023ca77c932 | 9cdeaa5cf2ef2848238c6e4c499ebf80e136ba7e | refs/heads/master | 2021-01-01T19:10:36.886248 | 2011-11-07T19:29:22 | 2011-11-07T19:29:22 | 1,021,325 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,782 | hpp | //
// basic_async_server.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2011 Steven Siloti ([email protected])
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef HTTP_BASIC_ASYNC_SERVER_HPP
#define HTTP_BASIC_ASYNC_SERVER_HPP
#include <http/async_server_connection.hpp>
#include <boost/bind/protect.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <boost/signals2/signal.hpp>
namespace http {
template <typename Headers, typename Body>
class basic_async_server : public boost::enable_shared_from_this<basic_async_server<Headers, Body> >
{
typedef boost::signals2::signal<void()> shutdown_sig_t;
public:
typedef async_server_connection<boost::asio::ip::tcp::socket, Headers, Body> connection_type;
basic_async_server(boost::asio::io_service& io, ip::tcp::endpoint listen)
: acceptor_(io, listen)
{}
void start()
{
accepting_con_ =
boost::make_shared<connection_type>(
boost::ref(acceptor_),
boost::bind(
&basic_async_server<Headers, Body>::handle_accepted,
this->shared_from_this(),
placeholders::error
)
);
shutdown_sig_.connect(
shutdown_sig_t::slot_type(
boost::bind(&connection_type::lowest_layer_type::close,
&accepting_con_->lowest_layer())
).track(accepting_con_)
);
}
void stop()
{
shutdown_sig_();
acceptor_.close();
}
protected:
struct context_type
{
context_type(
boost::shared_ptr<basic_async_server<Headers, Body> > serv,
boost::shared_ptr<const connection_type> con,
const typename connection_type::request_type& req)
: server_(serv), connection(con), request(req)
{}
boost::shared_ptr<const connection_type> connection;
const typename connection_type::request_type& request;
template <typename Response>
void write_response(Response response)
{
connection_type& con(*boost::const_pointer_cast<connection_type>(connection));
con.write_response(response);
con.read_request(
boost::protect(boost::bind(
&basic_async_server<Headers, Body>::incoming_request,
server_,
placeholders::error,
_2
))
);
}
private:
boost::shared_ptr<basic_async_server<Headers, Body> > server_;
};
virtual void incoming_request(typename context_type ctx) = 0;
private:
void handle_accepted(const boost::system::error_code& error)
{
if (!error) {
accepting_con_->read_request(
boost::protect(boost::bind(
&basic_async_server::incoming_request,
this->shared_from_this(),
placeholders::error,
_2
))
);
}
accepting_con_.reset();
if (acceptor_.is_open())
start();
}
void incoming_request(const boost::system::error_code& error, typename connection_type::context_type ctx)
{
if (error)
return;
incoming_request(context_type(this->shared_from_this(), ctx.connection, ctx.request));
}
boost::shared_ptr<connection_type> accepting_con_;
ip::tcp::acceptor acceptor_;
shutdown_sig_t shutdown_sig_;
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
127
]
]
]
|
c183440392ff5bf34355a6b01f6f5dcdeba2bcf6 | b86d7c8f28a0c243b4c578821e353d5efcaf81d2 | /clearcasehelper/ResizeLib/ResizableState.h | 7b65a85a10eff5ff1d6c2fdd69bdea9a87a8a5c6 | []
| no_license | nk39/mototool | dd4998d38348e0e2d010098919f68cf2c982f26a | 34a0698fd274ae8b159fc8032f3065877ba2114d | refs/heads/master | 2021-01-10T19:26:23.675639 | 2008-01-04T04:47:54 | 2008-01-04T04:47:54 | 34,927,428 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,167 | h | // ResizableState.h: interface for the CResizableState class.
//
/////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2000-2001 by Paolo Messina
// (http://www.geocities.com/ppescher - [email protected])
//
// The contents of this file are subject to the Artistic License (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.opensource.org/licenses/artistic-license.html
//
// If you find this code useful, credits would be nice!
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_RESIZABLESTATE_H__INCLUDED_)
#define AFX_RESIZABLESTATE_H__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CResizableState
{
protected:
// non-zero if successful
BOOL LoadWindowRect(LPCTSTR pszSection, BOOL bRectOnly);
BOOL SaveWindowRect(LPCTSTR pszSection, BOOL bRectOnly);
virtual CWnd* GetResizableWnd() = 0;
public:
CResizableState();
virtual ~CResizableState();
};
#endif // !defined(AFX_RESIZABLESTATE_H__INCLUDED_)
| [
"netnchen@631d5421-cb3f-0410-96e9-8590a48607ad"
]
| [
[
[
1,
38
]
]
]
|
c892536326c448ba92e5b8076652885c15742bac | d1fd6f07f149aac37069b95326a97e4110b7166c | /CVDAW/CVDAW/AudioDrivers.h | b6f427066ec81c63c3ae827c657569c5d148887f | []
| no_license | JosephWu/programowaniedzwieku | 0b7324f8ff219cffcf2fad56aaad8fc06642cd18 | 3d1eef45b1efc4dfd2d39f105e71b5ceebdfda9e | refs/heads/master | 2016-08-12T19:59:03.205343 | 2009-12-04T11:13:53 | 2009-12-04T11:13:53 | 44,655,154 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | h | #pragma once
#include "inc\fmod.hpp"
#include "inc\fmod_errors.h"
#include <iostream>
#include "Form1.h"
ref class AudioDrivers
{
public:
FMOD::System *system;
FMOD_RESULT result;
unsigned int handle;
Form1 form1;
AudioDrivers();
AudioDrivers(Form1 *form1);
void AudioDrivers::setOutputByPlugin(int num);
void AudioDrivers::playSound();
void AudioDrivers::getPlugins(FMOD_PLUGINTYPE pluginType);
private:
void ERRCHECK(FMOD_RESULT result);
};
| [
"[email protected]"
]
| [
[
[
1,
21
]
]
]
|
981b54274908374798e8536bac2cb73db080ea63 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-03/eeschema/tool_viewlib.cpp | 7714b67b95c917deb6537cc7e4699ae97f93c2f5 | []
| 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 | 4,681 | cpp | /****************************************************************/
/* tool_viewlib.cpp: Build the toolbars for the library browser */
/****************************************************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "program.h"
#include "libcmp.h"
#include "general.h"
#include "wx/spinctrl.h"
#include "protos.h"
#define BITMAP wxBitmap
#include "bitmaps.h"
#include "id.h"
#include "Lib_previous.xpm"
#include "Lib_next.xpm"
/****************************************************/
void WinEDA_ViewlibFrame::ReCreateHToolbar(void)
/****************************************************/
{
int ii;
EDA_LibComponentStruct * RootLibEntry = NULL, * CurrentLibEntry = NULL;
bool asdeMorgan = FALSE, state;
if ( (g_CurrentViewLibraryName != wxEmptyString) && (g_CurrentViewComponentName != wxEmptyString) )
{
RootLibEntry = FindLibPart(g_CurrentViewComponentName.GetData(),
g_CurrentViewLibraryName.GetData(), FIND_ROOT);
if ( RootLibEntry && LookForConvertPart(RootLibEntry) > 1 )
asdeMorgan = TRUE;
CurrentLibEntry = FindLibPart(g_CurrentViewComponentName.GetData(),
g_CurrentViewLibraryName.GetData(), FIND_ALIAS);
}
if ( m_HToolBar == NULL )
{
m_HToolBar = new WinEDA_Toolbar(TOOLBAR_MAIN, this, ID_H_TOOLBAR, TRUE);
SetToolBar(m_HToolBar);
// Set up toolbar
m_HToolBar->AddTool(ID_LIBVIEW_SELECT_LIB, wxEmptyString,
BITMAP(library_xpm),
_("Select library to browse"));
m_HToolBar->AddTool(ID_LIBVIEW_SELECT_PART, wxEmptyString,
BITMAP(add_component_xpm),
_("Select part to browse"));
m_HToolBar->AddSeparator();
m_HToolBar->AddTool(ID_LIBVIEW_PREVIOUS, wxEmptyString,
BITMAP(lib_previous_xpm),
_("Display previous part"));
m_HToolBar->AddTool(ID_LIBVIEW_NEXT, wxEmptyString,
BITMAP(lib_next_xpm),
_("Display next part"));
m_HToolBar->AddSeparator();
m_HToolBar->AddTool(ID_ZOOM_PLUS_BUTT, wxEmptyString,
BITMAP(zoom_in_xpm),
_("zoom + (F1)"));
m_HToolBar->AddTool(ID_ZOOM_MOINS_BUTT, wxEmptyString,
BITMAP(zoom_out_xpm),
_("zoom - (F2)"));
m_HToolBar->AddTool(ID_ZOOM_REDRAW_BUTT, wxEmptyString,
BITMAP(repaint_xpm),
_("redraw (F3)"));
m_HToolBar->AddTool(ID_ZOOM_PAGE_BUTT, wxEmptyString,
BITMAP(zoom_optimal_xpm),
_("1:1 zoom"));
m_HToolBar->AddSeparator();
m_HToolBar->AddTool(ID_LIBVIEW_DE_MORGAN_NORMAL_BUTT, wxEmptyString,
BITMAP(morgan1_xpm),
_("Show as \"De Morgan\" normal part"), wxITEM_CHECK);
m_HToolBar->AddTool(ID_LIBVIEW_DE_MORGAN_CONVERT_BUTT, wxEmptyString,
BITMAP(morgan2_xpm),
_("Show as \"De Morgan\" convert part"), wxITEM_CHECK);
m_HToolBar->AddSeparator();
SelpartBox = new wxComboBox(m_HToolBar, ID_LIBVIEW_SELECT_PART_NUMBER,wxEmptyString,
wxDefaultPosition, wxSize(150,-1), 0, NULL, wxCB_READONLY);
m_HToolBar->AddControl(SelpartBox);
m_HToolBar->AddSeparator();
m_HToolBar->AddTool(ID_LIBVIEW_VIEWDOC, wxEmptyString, BITMAP(datasheet_xpm),
_("View component documents") );
m_HToolBar->EnableTool(ID_LIBVIEW_VIEWDOC, FALSE);
if ( m_IsModal ) // The lib browser is called from a "load component" command
{
m_HToolBar->AddSeparator();
m_HToolBar->AddTool(ID_LIBVIEW_CMP_EXPORT_TO_SCHEMATIC, wxEmptyString,
BITMAP(export_xpm),
_("Export to schematic") );
}
// after adding the buttons to the toolbar, must call Realize() to reflect
// the changes
m_HToolBar->Realize();
}
// Must be AFTER Realize():
m_HToolBar->ToggleTool(ID_LIBVIEW_DE_MORGAN_NORMAL_BUTT,
(g_ViewConvert <= 1) ? TRUE : FALSE);
m_HToolBar->ToggleTool(ID_LIBVIEW_DE_MORGAN_CONVERT_BUTT,
(g_ViewConvert >= 2) ? TRUE : FALSE );
m_HToolBar->EnableTool(ID_LIBVIEW_DE_MORGAN_CONVERT_BUTT, asdeMorgan);
m_HToolBar->EnableTool(ID_LIBVIEW_DE_MORGAN_NORMAL_BUTT, asdeMorgan);
int jj = 1;
if( RootLibEntry ) jj = MAX(RootLibEntry->m_UnitCount, 1);
SelpartBox->Clear();
for ( ii = 0; ii < jj ; ii ++ )
{
wxString msg;
msg.Printf( _("Part %c"), 'A' + ii);
SelpartBox->Append(msg);
}
SelpartBox->SetSelection(0);
state = FALSE;
if ( CurrentLibEntry && jj > 1 ) state = TRUE;
SelpartBox->Enable(state);
state = FALSE;
if( CurrentLibEntry && (CurrentLibEntry->m_DocFile != wxEmptyString) )
state = TRUE;
m_HToolBar->EnableTool(ID_LIBVIEW_VIEWDOC, state);
}
/****************************************************/
void WinEDA_ViewlibFrame::ReCreateVToolbar(void)
/****************************************************/
{
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
152
]
]
]
|
27c6641a4f955d4a11acf9f3018bc5df4ced7a2f | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/SourceSaver.cpp | 5246d7192d97d44791586ddbe781151ce7b342ab | []
| no_license | mikezhoubill/emule-gifc | e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60 | 46979cf32a313ad6d58603b275ec0b2150562166 | refs/heads/master | 2021-01-10T20:37:07.581465 | 2011-08-13T13:58:37 | 2011-08-13T13:58:37 | 32,465,033 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 12,743 | cpp | #include "StdAfx.h"
#include "sourcesaver.h"
#include "PartFile.h"
#include "emule.h"
#include "Log.h"
#include "updownclient.h"
#include "urlclient.h" //DolphinX :: Save URL Source
#include "preferences.h"
#include "downloadqueue.h"
#include "log.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define RELOADTIME 3600000 //60 minutes
#define RESAVETIME 600000 //10 minutes
CSourceSaver::CSourceSaver(CPartFile* file)
{
m_dwLastTimeLoaded = 0;
m_dwLastTimeSaved = 0;
m_pFile = file;
}
CSourceSaver::~CSourceSaver(void)
{
}
CSourceSaver::CSourceData::CSourceData(CUpDownClient* client, const CString& expiration90mins, const CString& expiration3days)
: sourceID(client->GetUserIDHybrid()),
sourcePort(client->GetUserPort()),
partsavailable(client->GetAvailablePartCount()),
expiration90mins(expiration90mins),
expiration3days(expiration3days)
{
if(client->IsKindOf(RUNTIME_CLASS(CUrlClient))) //DolphinX :: Save URL Source
URL = client->GetUserName();
}
bool CSourceSaver::Process() // return false if sources not saved
{
// Load only one time the list and keep it in memory (=> reduce CPU load)
if (m_dwLastTimeLoaded == 0){
m_dwLastTimeLoaded = ::GetTickCount();
m_dwLastTimeSaved = ::GetTickCount() + (rand() * 30000 / RAND_MAX) - 15000; // Don't save all files at the same time
//Xman 6.0.1 skip loading if obfuscation only
if(!thePrefs.IsClientCryptLayerRequired())
{
// Load sources from the file
CString slsfilepath;
slsfilepath.Format(_T("%s\\%s.txtsrc"), m_pFile->GetTempPath(), m_pFile->GetPartMetFileName());
LoadSourcesFromFile(slsfilepath);
// Try to add the sources
AddSourcesToDownload();
}
}
// Save the list every n minutes (default 10 minutes)
else if ((int)(::GetTickCount() - m_dwLastTimeSaved) > RESAVETIME) {
m_dwLastTimeSaved = ::GetTickCount() + (rand() * 30000 / RAND_MAX) - 15000; // Don't save all files at the same time
// Save sources to the file
CString slsfilepath;
slsfilepath.Format(_T("%s\\%s.txtsrc"), m_pFile->GetTempPath(), m_pFile->GetPartMetFileName());
SaveSources(slsfilepath);
// Try to reload the unsuccessfull source
// if ((int)(::GetTickCount() - m_dwLastTimeLoaded) > RELOADTIME) {
// m_dwLastTimeLoaded = ::GetTickCount() + (rand() * 30000 / RAND_MAX) - 15000;
// AddSourcesToDownload(false);
// }
return true;
}
return false;
}
void CSourceSaver::DeleteFile()
{
m_sourceList.RemoveAll(); //Xman x4.1
CString slsfilepath;
slsfilepath.Format(_T("%s\\%s.txtsrc"), m_pFile->GetTempPath(), m_pFile->GetPartMetFileName());
if (_tremove(slsfilepath)) if (errno != ENOENT)
AddLogLine(true, _T("Failed to delete %s, you will need to do this by hand"), slsfilepath);
}
void CSourceSaver::LoadSourcesFromFile(const CString& slsfile)
{
CString strLine;
CStdioFile f;
if (!f.Open(slsfile, CFile::modeRead | CFile::typeText))
return;
while(f.ReadString(strLine)) {
// Skip comment (e.g. title)
if (strLine.GetAt(0) == '#')
continue;
// Load IP
int pos = strLine.Find(':');
if (pos == -1)
continue;
CStringA strIP(strLine.Left(pos));
//DolphinX :: Save URL Source :: Start
uint32 dwID = 0;
uint16 wPort = 0;
if(strIP.CompareNoCase("http")){
//DolphinX :: Save URL Source :: End
strLine = strLine.Mid(pos+1);
dwID = inet_addr(strIP);
if (dwID == INADDR_NONE)
continue;
// Load Port
pos = strLine.Find(',');
if (pos == -1)
continue;
CString strPort = strLine.Left(pos);
strLine = strLine.Mid(pos+1);
wPort = (uint16)_tstoi(strPort);
if (!wPort)
continue;
//DolphinX :: Save URL Source :: Start
strIP.Empty();
}
else{
pos = strLine.Find(' ');
if (pos == -1)
continue;
strIP = strLine.Left(pos);
strLine = strLine.Mid(pos+1);
}
//DolphinX :: Save URL Source :: End
// Load expiration time (short version => usualy for 3 days)
pos = strLine.Find(';');
if (pos == -1)
continue;
CString expiration3days = strLine.Left(pos);
strLine = strLine.Mid(pos+1);
// Load expiration time (short version => usualy for 1.5 hours)
pos = strLine.Find(';');
CString expiration90mins;
if (pos != -1){
expiration90mins = strLine.Left(pos);
strLine = strLine.Mid(pos+1);
}
if (IsExpired(expiration3days) == true && IsExpired(expiration90mins) == true)
continue;
else if (IsExpired(expiration90mins) == true)
expiration90mins.Empty(); // Erase
// Add source to list
//DolphinX :: Save URL Source :: Start
if(strIP.IsEmpty())
m_sourceList.AddTail(CSourceData(dwID, wPort, expiration90mins, expiration3days));
else
m_sourceList.AddTail(CSourceData(strIP, expiration90mins, expiration3days));
//DolphinX :: Save URL Source :: End
}
f.Close();
}
void CSourceSaver::AddSourcesToDownload(){
uint16 count = 0;
for(POSITION pos = m_sourceList.GetHeadPosition(); pos != NULL; ){
// Check if the limit of allowed source was reached
if(m_pFile->GetMaxSources() <= m_pFile->GetSourceCount())
break;
// Try to add new sources
// within 3 days => load only 10
// within 1.5 hours => load all
const CSourceData& cur_src = m_sourceList.GetNext(pos);
if(count < 10 || IsExpired(cur_src.expiration90mins) == false){
count++;
if(cur_src.URL.IsEmpty()){ //DolphinX :: Save URL Source
CUpDownClient* newclient = new CUpDownClient(m_pFile, cur_src.sourcePort, cur_src.sourceID, 0, 0, false);
newclient->SetSourceFrom(SF_SLS);
theApp.downloadqueue->CheckAndAddSource(m_pFile, newclient);
//DolphinX :: Save URL Source :: Start
}
else{
CUrlClient* newclient = new CUrlClient();
if (!newclient->SetUrl(cur_src.URL, 0))
{
LogError(LOG_STATUSBAR, _T("Failed to process URL source \"%s\""), cur_src.URL);
delete newclient;
continue; //return;
}
newclient->SetRequestFile(m_pFile);
newclient->SetSourceFrom(SF_SLS);
theApp.downloadqueue->CheckAndAddSource(m_pFile, newclient);
}
//DolphinX :: Save URL Source :: End
}
}
AddDebugLogLine(false, _T("%u %s loaded for the file '%s'"),
count, (count>1) ? _T("sources") : _T("source"), m_pFile->GetFileName());
}
void CSourceSaver::SaveSources(const CString& slsfile)
{
const CString expiration90mins = CalcExpiration();
const CString expiration3days = CalcExpirationLong();
//Xman keep old sources only for rar files
//the old version of the sourcesaver had a big bug if we have many sources per file
int validsources=m_pFile->GetValidSourcesCount();
if (validsources>25)
{
//keep only current sources, remove the old one
m_sourceList.RemoveAll();
}
//Xman x4.1
//remove expired for rare files
POSITION pos=m_sourceList.GetTailPosition();
while(pos!=NULL && m_sourceList.GetCount()>10 )
{
POSITION cur_pos = pos;
m_sourceList.GetPrev(pos);
if(IsExpired(m_sourceList.GetAt(cur_pos).expiration90mins))
m_sourceList.RemoveAt(cur_pos);
}
//Xman end
// Update sources list for the file
for(POSITION pos1 = m_pFile->srclist.GetHeadPosition(); pos1 != NULL; ){
CUpDownClient* cur_src = m_pFile->srclist.GetNext(pos1);
// Skip lowID source
if (cur_src->HasLowID())
continue;
// Skip also Required Obfuscation, because we don't save the userhash (and we don't know if all settings are still valid on next restart)
if (cur_src->RequiresCryptLayer())
continue;
CSourceData sourceData(cur_src, expiration90mins, expiration3days);
// Update or add a source
if (validsources<=25)
for(POSITION pos2 = m_sourceList.GetHeadPosition(); pos2 != NULL;) {
POSITION cur_pos = pos2;
const CSourceData& cur_sourcedata = m_sourceList.GetNext(pos2);
if(cur_sourcedata.Compare(sourceData) == true){
m_sourceList.RemoveAt(cur_pos);
break; // exit loop for()
}
}
// Add source to the list
if(m_sourceList.IsEmpty() == TRUE){
m_sourceList.AddHead(sourceData);
}
else{
for(POSITION pos2 = m_sourceList.GetHeadPosition(); pos2 != NULL;) {
POSITION cur_pos = pos2;
const CSourceData& cur_sourcedata = m_sourceList.GetNext(pos2);
if((cur_src->GetDownloadState() == DS_ONQUEUE || cur_src->GetDownloadState() == DS_DOWNLOADING) &&
(sourceData.partsavailable >= cur_sourcedata.partsavailable)){
// Use the state and the number of available part to sort the list
m_sourceList.InsertBefore(cur_pos, sourceData);
break; // Exit loop
}
else if(cur_sourcedata.partsavailable == 0){
// Use the number of available part to sort the list
m_sourceList.InsertBefore(cur_pos, sourceData);
break; // Exit loop
}
else if(pos2 == NULL){
m_sourceList.AddTail(sourceData);
break; // Exit loop
}
}
}
}
CString strLine;
CStdioFile f;
if (!f.Open(slsfile, CFile::modeCreate | CFile::modeWrite | CFile::typeText))
return;
f.WriteString(_T("#format: a.b.c.d:port,expirationdate-3day(yymmdd);expirationdate-1.5hour(yymmddhhmm);\r\n"));
uint16 counter = 0;
for(POSITION pos = m_sourceList.GetHeadPosition(); pos != NULL; ){
//POSITION cur_pos = pos;
const CSourceData& cur_src = m_sourceList.GetNext(pos);
//if(cur_src.partsavailable > 0){
//DolphinX :: Save URL Source :: Start
if(!cur_src.URL.IsEmpty()){
strLine.Format(_T("%s %s;%s;\r\n"),
cur_src.URL,
(counter < 10) ? cur_src.expiration3days : _T("000101"),
cur_src.expiration90mins);
}
else
//DolphinX :: Save URL Source :: End
if(counter < 10){
strLine.Format(_T("%i.%i.%i.%i:%i,%s;%s;\r\n"),
(uint8)cur_src.sourceID, (uint8)(cur_src.sourceID>>8), (uint8)(cur_src.sourceID>>16), (uint8)(cur_src.sourceID>>24),
cur_src.sourcePort,
cur_src.expiration3days,
cur_src.expiration90mins);
}
else {
strLine.Format(_T("%i.%i.%i.%i:%i,%s;%s;\r\n"),
(uint8)cur_src.sourceID, (uint8)(cur_src.sourceID>>8), (uint8)(cur_src.sourceID>>16), (uint8)(cur_src.sourceID>>24),
cur_src.sourcePort,
_T("000101"),
cur_src.expiration90mins);
}
++counter;
f.WriteString(strLine);
/*
}
else if(counter < 10){
strLine.Format(_T("%i.%i.%i.%i:%i,%s;%s;\r\n"),
(uint8)cur_src.sourceID, (uint8)(cur_src.sourceID>>8), (uint8)(cur_src.sourceID>>16), (uint8)(cur_src.sourceID>>24),
cur_src.sourcePort,
cur_src.expiration3days,
_T(""));
++counter;
f.WriteString(strLine);
}
else
{
m_sourceList.RemoveAt(cur_pos);
}*/
}
f.Close();
}
CString CSourceSaver::CalcExpiration()
{
CTime expiration90mins = CTime::GetCurrentTime();
CTimeSpan timediff(0, 1, 0, 0); //Xman 1 hour
expiration90mins += timediff;
CString strExpiration;
strExpiration.Format(_T("%02i%02i%02i%02i%02i"),
(expiration90mins.GetYear() % 100),
expiration90mins.GetMonth(),
expiration90mins.GetDay(),
expiration90mins.GetHour(),
expiration90mins.GetMinute());
return strExpiration;
}
CString CSourceSaver::CalcExpirationLong()
{
CTime expiration3days = CTime::GetCurrentTime();
CTimeSpan timediff(2, 0, 0, 0); //Xman 2 days
expiration3days += timediff;
CString strExpiration;
strExpiration.Format(_T("%02i%02i%02i"),
(expiration3days.GetYear() % 100),
expiration3days.GetMonth(),
expiration3days.GetDay());
return strExpiration;
}
bool CSourceSaver::IsExpired(const CString& expiration) const
{
// example: "yymmddhhmm"
if(expiration.GetLength() == 10 || expiration.GetLength() == 6){
int year = _tstoi(expiration.Mid(0, 2)) + 2000;
int month = _tstoi(expiration.Mid(2, 2));
int day = _tstoi(expiration.Mid(4, 2));
int hour = (expiration.GetLength() == 10) ? _tstoi(expiration.Mid(6, 2)) : 0;
int minute = (expiration.GetLength() == 10) ? _tstoi(expiration.Mid(8, 2)) : 0;
CTime date(year, month, day, hour, minute, 0);
return (date < CTime::GetCurrentTime());
}
return true;
}
| [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b",
"[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b"
]
| [
[
[
1,
6
],
[
8,
38
],
[
41,
52
],
[
60,
106
],
[
116,
116
],
[
137,
158
],
[
165,
181
],
[
201,
295
],
[
306,
311
],
[
313,
387
]
],
[
[
7,
7
],
[
39,
40
],
[
53,
59
],
[
107,
115
],
[
117,
136
],
[
159,
164
],
[
182,
200
],
[
296,
305
],
[
312,
312
]
]
]
|
7e82187e67bd6fc22060115ac081c364ad7c6f04 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/util/XMLDouble.hpp | af85fe211c1c3e4ee3f3b4d59c57efa7fe22dfa1 | [
"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,126 | hpp | /*
* Copyright 2001,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: XMLDouble.hpp,v 1.9 2004/09/08 13:56:24 peiyongz Exp $
* $Log: XMLDouble.hpp,v $
* Revision 1.9 2004/09/08 13:56:24 peiyongz
* Apache License Version 2.0
*
* Revision 1.8 2003/12/17 00:18:35 cargilld
* Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
*
* Revision 1.7 2003/12/01 23:23:27 neilg
* fix for bug 25118; thanks to Jeroen Witmond
*
* Revision 1.6 2003/09/23 18:16:07 peiyongz
* Inplementation for Serialization/Deserialization
*
* Revision 1.5 2003/05/16 06:01:53 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.4 2002/12/11 00:20:02 peiyongz
* Doing businesss in value space. Converting out-of-bound value into special values.
*
* Revision 1.3 2002/11/04 15:22:05 tng
* C++ Namespace Support.
*
* Revision 1.2 2002/02/20 18:17:02 tng
* [Bug 5977] Warnings on generating apiDocs.
*
* Revision 1.1.1.1 2002/02/01 22:22:15 peiyongz
* sane_include
*
* Revision 1.11 2001/11/28 15:39:26 peiyongz
* return Type& for operator=
*
* Revision 1.10 2001/11/22 20:23:00 peiyongz
* _declspec(dllimport) and inline warning C4273
*
* Revision 1.9 2001/11/19 21:33:42 peiyongz
* Reorganization: Double/Float
*
* Revision 1.8 2001/10/26 16:37:46 peiyongz
* Add thread safe code
*
* Revision 1.6 2001/09/27 14:54:20 peiyongz
* DTV Reorganization: derived from XMLAbstractDoubleFloat
*
* Revision 1.5 2001/08/29 19:03:03 peiyongz
* Bugzilla# 2816:on AIX 4.2, xlC 3 r ev.1, Compilation error on inline method
*
* Revision 1.4 2001/07/31 13:48:29 peiyongz
* fValue removed
*
* Revision 1.3 2001/07/26 18:21:15 peiyongz
* Boundary Checking
*
* Revision 1.2 2001/07/24 21:52:27 peiyongz
* XMLDouble: move fg...String to XMLUni
*
* Revision 1.1 2001/07/24 13:58:11 peiyongz
* XMLDouble and related supporting methods from XMLBigInteger/XMLBigDecimal
*
*/
#ifndef XML_DOUBLE_HPP
#define XML_DOUBLE_HPP
#include <xercesc/util/XMLAbstractDoubleFloat.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLUTIL_EXPORT XMLDouble : public XMLAbstractDoubleFloat
{
public:
/**
* Constructs a newly allocated <code>XMLDouble</code> object that
* represents the value represented by the string.
*
* @param strValue the <code>String</code> to be converted to an
* <code>XMLDouble</code>.
* @param manager Pointer to the memory manager to be used to
* allocate objects.
* @exception NumberFormatException if the <code>String</code> does not
* contain a parsable XMLDouble.
*/
XMLDouble(const XMLCh* const strValue,
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
~XMLDouble();
/**
* Compares this object to the specified object.
* The result is <code>true</code> if and only if the argument is not
* <code>null</code> and is an <code>XMLDouble</code> object that contains
* the same <code>int</code> value as this object.
*
* @param lValue the object to compare with.
* @param rValue the object to compare against.
* @return <code>true</code> if the objects are the same;
* <code>false</code> otherwise.
*/
inline static int compareValues(const XMLDouble* const lValue
, const XMLDouble* const rValue);
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(XMLDouble)
XMLDouble(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
protected:
void checkBoundary(const XMLCh* const strValue);
private:
//
// Unimplemented
//
// copy ctor
// assignment ctor
//
XMLDouble(const XMLDouble& toCopy);
XMLDouble& operator=(const XMLDouble& toAssign);
};
inline int XMLDouble::compareValues(const XMLDouble* const lValue
, const XMLDouble* const rValue)
{
return XMLAbstractDoubleFloat::compareValues((const XMLAbstractDoubleFloat* const) lValue,
(const XMLAbstractDoubleFloat* const) rValue
, ((XMLAbstractDoubleFloat*)lValue)->getMemoryManager());
}
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
]
| [
[
[
1,
156
]
]
]
|
ab9b3b31ff28942ad1d54027fe4db22a8c4726d4 | d0e3e591986c27ea73575a5b88f8326ab319816b | /fsets.cpp | ed28052e5521d57dbb955874bbb85c04f391818b | []
| no_license | codegooglecom/wtfu | f8851940908ddad141dffd471b66552583f48728 | 3eaaa969588799a5fb4d6a66851e00193fc1c6af | refs/heads/master | 2016-08-11T16:10:59.543826 | 2010-11-24T07:51:14 | 2010-11-24T07:51:14 | 43,666,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,387 | cpp | #include "fsets.h"
IMPLEMENT_ABSTRACT_CLASS(FilesSets, wxObject)
FilesSets::FilesSets()
{
m_error = 0;
NextId = 1;
}
FilesSets::FilesSets(const wxString& filename)
{
FilesSets();
Load(filename);
}
FilesSets::~FilesSets()
{
DeleteAllSets();
}
int FilesSets::Error()
{
return m_error;
}
FilesSet* FilesSets::GetFirstFS(int *id)
{
int it_id = 1;
while ( (it_id < NextId) && ( !fsets.count(it_id) ) )
{
it_id++;
}
if (it_id >= NextId)
{
*id = 0;
return NULL;
}
*id = it_id;
return fsets[it_id];
}
FilesSet* FilesSets::GetLastFS(int *id)
{
int it_id = NextId - 1;
while ( (it_id > 0) && ( !fsets.count(it_id) ) )
{
it_id--;
}
if (it_id <= 0)
{
*id = 0;
return NULL;
}
*id = it_id;
return fsets[it_id];
}
FilesSet* FilesSets::GetNextFS(int *id)
{
if (*id <= 0)
{
*id = 0;
return fsets[*id];
}
int it_id = *id;
it_id++;
while ( (it_id < NextId) && ( !fsets.count(it_id) ) )
{
it_id++;
}
if (it_id >= NextId)
{
*id = 0;
return NULL;
}
*id = it_id;
return fsets[it_id];
}
FilesSet* FilesSets::GetPrevFS(int *id)
{
if (*id >= NextId)
{
*id = 0;
return fsets[*id];
}
int it_id = *id;
it_id--;
while ( (it_id > 0) && ( !fsets.count(it_id) ) )
{
it_id--;
}
if (it_id <= 0)
{
*id = 0;
return NULL;
}
*id = it_id;
return fsets[it_id];
}
int FilesSets::CheckNamesSet(wxXmlNode *set, NamesSet *nset, const wxString& filename)
{
wxXmlNode *node = set->GetChildren();
wxXmlNode *node2;
wxString name;
int count1 = 0;
int count2 = 0;
long lid;
wxString value;
while (node != NULL)
{
if ( node->GetType() != wxXML_ELEMENT_NODE )
{
node = node->GetNext();
continue;
}
name = node->GetName();
if ( name.Cmp(wxT("title")) == 0 )
{
node2 = node->GetChildren();
while (node2 != NULL)
{
if (( node2->GetType() != wxXML_TEXT_NODE ) || (count1 > 0))
{
wxLogError(filename + wxT(": 'title' element's content must be text only."));
return 9;
}
nset->SetTitle( node2->GetContent() );
count1++;
node2 = node2->GetNext();
}
} else if ( name.Cmp(wxT("path")) == 0 ) {
node2 = node->GetChildren();
while (node2 != NULL)
{
if (( node2->GetType() != wxXML_TEXT_NODE ) || (count2 > 0))
{
wxLogError(filename + wxT(": 'path' element's content must be text only."));
return 10;
}
nset->SetDir( node2->GetContent() );
count2++;
node2 = node2->GetNext();
}
} else if ( name.Cmp(wxT("item")) == 0 ) {
if (( !node->GetPropVal(wxT("id"), &value) ) ||
( !value.ToLong(&lid) ) ||
(lid <= 0))
{
wxLogError(filename + wxT(": Attribute 'id' having positive numeric value must be specified for each element 'item'."));
return 11;
}
node2 = node->GetChildren();
while (node2 != NULL)
{
if ( node2->GetType() != wxXML_TEXT_NODE )
{
wxLogError(filename + wxT(": 'item' element's content must be text only."));
return 14;
}
if ( !nset->AddName( (int) lid, node2->GetContent() ) )
{
wxLogError(filename + wxT(": Duplicate name for (%d, %d)."), nset->GetId(), lid);
return -1;
}
node2 = node2->GetNext();
}
// } else {
// return 15;
}
node = node->GetNext();
}
return 0;
}
int FilesSets::CheckFilesSet(wxXmlNode *set, FilesSet *fset, const wxString& filename)
{
wxXmlNode *node = set->GetChildren();
wxXmlNode *node2;
int count1 = 0;
int count2 = 0;
int error;
long lid;
NamesSet *ns;
wxString value;
wxString name;
while (node != NULL)
{
if ( node->GetType() != wxXML_ELEMENT_NODE )
{
node = node->GetNext();
continue;
}
name = node->GetName();
if ( name.Cmp(wxT("title")) == 0 )
{
node2 = node->GetChildren();
while (node2 != NULL)
{
if (( node2->GetType() != wxXML_TEXT_NODE ) || (count1 > 0))
{
wxLogError(filename + wxT(": 'title' element's content must be text only."));
return 4;
}
fset->SetTitle( node2->GetContent() );
count1++;
node2 = node2->GetNext();
}
} else if ( name.Cmp(wxT("files-set")) == 0 ) {
node2 = node->GetChildren();
while (node2 != NULL)
{
if (( count2 > 0 ) || ( node2->GetType() != wxXML_TEXT_NODE ) ||
( !node2->GetContent().ToLong(&lid) ) || ( lid <= 0 ))
{
wxLogError(filename + wxT(": 'files-set' element's content must be text only representing positive number."));
return 5;
}
fset->SetMainId((int) lid);
count2++;
node2 = node2->GetNext();
}
} else if ( name.Cmp(wxT("names-set")) == 0 ) {
if (( !node->GetPropVal(wxT("id"), &value) ) ||
( !value.ToLong(&lid) ) || ( lid <= 0 ))
{
wxLogError(filename + wxT(": Attribute 'id' having positive numeric value must be specified for each element 'names-set'."));
return 6;
}
ns = WXDEBUG_NEW NamesSet();
ns->SetId((int) lid);
error = CheckNamesSet(node, ns, filename);
if (error)
{
delete(ns);
return error;
}
if ( !fset->AddNamesSet(ns) )
{
delete(ns);
wxLogError(filename + wxT(": Duplicate names set for (%d, %d)."), fset->GetId(), lid);
return -2;
}
// } else {
// return 7;
}
node = node->GetNext();
}
return 0;
}
bool FilesSets::Load(const wxString& filename)
{
DeleteAllSets();
wxXmlDocument *xmldoc = WXDEBUG_NEW wxXmlDocument(filename);
wxXmlNode *root;
if ( !xmldoc->IsOk() )
{
m_error = 100;
delete(xmldoc);
return false;
}
// checking data
root = xmldoc->GetRoot();
if (( root->GetType() != wxXML_ELEMENT_NODE ) ||
( root->GetName().Cmp(wxT("sets")) != 0 ))
{
m_error = 1;
delete(xmldoc);
wxLogError(filename + wxT(": Invalid document type. The root node must be 'sets'."));
return false;
}
wxXmlNode *set = root->GetChildren();
wxString value;
long lid;
FilesSet *fset;
while (set != NULL)
{
if (( set->GetType() == wxXML_ELEMENT_NODE ) &&
( set->GetName().Cmp(wxT("set")) == 0 ) &&
(( !set->GetPropVal(wxT("id"), &value) ) ||
( !value.ToLong(&lid) ) || ( lid <= 0 )))
{
m_error = 2;
delete(xmldoc);
wxLogError(filename + wxT(": Attribute 'id' having positive numeric value must be specified for each element 'set'."));
return false;
}
if (( set->GetType() != wxXML_ELEMENT_NODE ) ||
( set->GetName().Cmp(wxT("set")) != 0 ))
{
set = set->GetNext();
continue;
}
fset = WXDEBUG_NEW FilesSet();
fset->SetId( (int) lid );
m_error = CheckFilesSet(set, fset, filename);
if (m_error)
{
delete(fset);
delete(xmldoc);
return false;
}
if ( !AddSet(fset) )
{
m_error = -3;
delete(fset);
delete(xmldoc);
wxLogError(filename + wxT(": Duplicate set for id = %d."), lid);
return false;
}
set = set->GetNext();
}
delete(xmldoc);
return true;
}
bool FilesSets::Save(const wxString& filename)
{
wxXmlDocument *xmldoc = WXDEBUG_NEW wxXmlDocument();
wxXmlNode *root = WXDEBUG_NEW wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("sets"));
wxXmlNode *set, *node, *set2;
wxString value;
wxString eol = wxT("\012");
int id1, id2, id3;
FilesSet *fset;
NamesSet *nset;
// root->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, eol));
fset = GetLastFS(&id1);
while ( (id1 > 0) && (id1 < GetNextId()) )
{
value.Empty();
value.Printf(wxT("%d"), id1);
set = WXDEBUG_NEW wxXmlNode(root, wxXML_ELEMENT_NODE, wxT("set"), wxEmptyString, WXDEBUG_NEW wxXmlProperty(wxT("id"), value));
// set->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, eol));
nset = fset->GetLastNS(&id2);
while ( (id2 > 0) && (id2 < fset->GetNextNSId()) )
{
value.Empty();
value.Printf(wxT("%d"), id2);
set2 = WXDEBUG_NEW wxXmlNode(set, wxXML_ELEMENT_NODE, wxT("names-set"), wxEmptyString, WXDEBUG_NEW wxXmlProperty(wxT("id"), value));
// set2->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, eol));
value = nset->GetLastName(&id3);
while ( (id3 > 0) && (id3 < nset->GetNextId()) )
{
node = WXDEBUG_NEW wxXmlNode(set2, wxXML_ELEMENT_NODE, wxT("item"));
node->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, value));
value.Empty();
value.Printf(wxT("%d"), id3);
node->SetProperties(WXDEBUG_NEW wxXmlProperty(wxT("id"), value));
// set2->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, eol));
value = nset->GetPrevName(&id3);
}
node = WXDEBUG_NEW wxXmlNode(set2, wxXML_ELEMENT_NODE, wxT("path"));
node->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, nset->GetDir()));
// set2->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, eol));
node = WXDEBUG_NEW wxXmlNode(set2, wxXML_ELEMENT_NODE, wxT("title"));
node->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, nset->GetTitle()));
// set2->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, eol));
nset = fset->GetPrevNS(&id2);
}
// set->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, eol));
node = WXDEBUG_NEW wxXmlNode(set, wxXML_ELEMENT_NODE, wxT("files-set"));
value.Empty();
value.Printf(wxT("%d"), fset->GetMainId());
node->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, value));
// set->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, eol));
node = WXDEBUG_NEW wxXmlNode(set, wxXML_ELEMENT_NODE, wxT("title"));
node->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, fset->GetTitle()));
// set->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, eol));
// root->AddChild(WXDEBUG_NEW wxXmlNode(NULL, wxXML_TEXT_NODE, wxEmptyString, eol));
fset = GetPrevFS(&id1);
}
xmldoc->SetRoot(root);
bool rv = xmldoc->Save(filename, 1);
delete(xmldoc);
return rv;
}
int FilesSets::GetNextId()
{
return NextId;
}
bool FilesSets::AddSet(FilesSet *fset)
{
int id = fset->GetId();
if (id <= 0)
{
id = NextId;
fset->SetId(id);
}
// check exists
if ( fsets.count(id) )
{
return false;
}
// adding
fsets[id] = fset;
// updating NextId
if (id >= NextId)
{
NextId = id + 1;
}
return true;
}
FilesSet *FilesSets::GetSet(int id)
{
if ( !fsets.count(id) )
{
return NULL;
}
return fsets[id];
}
bool FilesSets::DeleteSet(int id)
{
if ( !fsets.count(id) )
{
return false;
}
fsets.erase(id);
return true;
}
bool FilesSets::DeleteAllSets()
{
FilesSetsH::iterator it;
FilesSet *fset;
for (it = fsets.begin(); it != fsets.end(); ++it)
{
fset = it->second;
delete(fset);
}
fsets.clear();
NextId = 1;
return true;
}
| [
"JupMoon.Io@b849ae62-46ad-11de-9b56-810ca157e297"
]
| [
[
[
1,
460
]
]
]
|
917edcc9dd5a8eb1cdb0639f1372bff2d3a14722 | a84b013cd995870071589cefe0ab060ff3105f35 | /webdriver/branches/chrome/chrome/src/cpp/include/breakpad/src/common/windows/http_upload.h | 247d02636a06aa9b8eac8c8c7ab224ea7f2a46fd | [
"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 | 5,408 | h | // Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of 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.
// HTTPUpload provides a "nice" API to send a multipart HTTP(S) POST
// request using wininet. It currently supports requests that contain
// a set of string parameters (key/value pairs), and a file to upload.
#ifndef COMMON_WINDOWS_HTTP_UPLOAD_H__
#define COMMON_WINDOWS_HTTP_UPLOAD_H__
#pragma warning( push )
// Disable exception handler warnings.
#pragma warning( disable : 4530 )
#include <Windows.h>
#include <WinInet.h>
#include <map>
#include <string>
#include <vector>
namespace google_breakpad {
using std::string;
using std::wstring;
using std::map;
using std::vector;
class HTTPUpload {
public:
// Sends the given set of parameters, along with the contents of
// upload_file, as a multipart POST request to the given URL.
// file_part_name contains the name of the file part of the request
// (i.e. it corresponds to the name= attribute on an <input type="file">.
// Parameter names must contain only printable ASCII characters,
// and may not contain a quote (") character.
// Only HTTP(S) URLs are currently supported. Returns true on success.
// If the request is successful and response_body is non-NULL,
// the response body will be returned in response_body.
// If response_code is non-NULL, it will be set to the HTTP response code
// received (or 0 if the request failed before getting an HTTP response).
static bool SendRequest(const wstring &url,
const map<wstring, wstring> ¶meters,
const wstring &upload_file,
const wstring &file_part_name,
wstring *response_body,
int *response_code);
private:
class AutoInternetHandle;
// Retrieves the HTTP response. If NULL is passed in for response,
// this merely checks (via the return value) that we were successfully
// able to retrieve exactly as many bytes of content in the response as
// were specified in the Content-Length header.
static bool HTTPUpload::ReadResponse(HINTERNET request, wstring* response);
// Generates a new multipart boundary for a POST request
static wstring GenerateMultipartBoundary();
// Generates a HTTP request header for a multipart form submit.
static wstring GenerateRequestHeader(const wstring &boundary);
// Given a set of parameters, an upload filename, and a file part name,
// generates a multipart request body string with these parameters
// and minidump contents. Returns true on success.
static bool GenerateRequestBody(const map<wstring, wstring> ¶meters,
const wstring &upload_file,
const wstring &file_part_name,
const wstring &boundary,
string *request_body);
// Fills the supplied vector with the contents of filename.
static void GetFileContents(const wstring &filename, vector<char> *contents);
// Converts a UTF8 string to UTF16.
static wstring UTF8ToWide(const string &utf8);
// Converts a UTF16 string to UTF8.
static string WideToUTF8(const wstring &wide);
// Checks that the given list of parameters has only printable
// ASCII characters in the parameter name, and does not contain
// any quote (") characters. Returns true if so.
static bool CheckParameters(const map<wstring, wstring> ¶meters);
// No instances of this class should be created.
// Disallow all constructors, destructors, and operator=.
HTTPUpload();
explicit HTTPUpload(const HTTPUpload &);
void operator=(const HTTPUpload &);
~HTTPUpload();
};
} // namespace google_breakpad
#pragma warning( pop )
#endif // COMMON_WINDOWS_HTTP_UPLOAD_H__
| [
"noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9"
]
| [
[
[
1,
125
]
]
]
|
242a94140aaf9bfb06b1db22333072b7f331070a | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/src/file/nsharedmemory.cc | f9a53213deb9083985f67c5d24d234a1d225957d | []
| 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 | 11,879 | cc | //------------------------------------------------------------------------------
// nsharedmemory.cc
// (C) 2004 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "precompiled/pchnnebula.h"
#define N_IMPLEMENTS nSharedMemory
#include "kernel/nkernelserver.h"
#include "file/nsharedmemory.h"
#if defined(__LINUX__) || defined(__MACOSX__)
#include <sys/types.h>
#include <sys/mman.h>
#include <unistd.h>
#endif
nNebulaClass(nSharedMemory, "nroot");
/// Initialize static members.
const int nSharedMemory::InitialReadBufferCapacity = 1024;
/// Header size in bytes.
const int nSharedMemory::HeaderSize = 9;
//------------------------------------------------------------------------------
/**
*/
nSharedMemory::nSharedMemory() :
readBuffer(0),
readBufferCapacity(0),
capacity(0),
count(0),
mapHandle(0),
mapHeader(0),
mapBody(0),
isOpen(false),
writable(false)
{
this->SetupReadBuffer(InitialReadBufferCapacity);
}
//------------------------------------------------------------------------------
/**
*/
nSharedMemory::~nSharedMemory()
{
if (this->mapHandle != 0)
{
this->DestroyMapping();
}
if (this->IsOpen())
{
this->Close();
}
delete [] this->readBuffer;
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::Create()
{
if (this->mapHandle != 0)
{
this->DestroyMapping();
}
if (this->IsOpen())
{
this->Close();
}
this->writeBuffer.Reset();
this->isOpen = true;
this->writable = true;
this->capacity = this->writeBuffer.Capacity();
this->count = 0;
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::Resize(int n)
{
n_assert(n > 0);
n_assert(this->Writable(0, this->Capacity() - 1));
this->writeBuffer.Resize(n);
this->capacity = this->writeBuffer.Capacity();
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::Open()
{
n_assert(!this->IsOpen());
#ifdef __WIN32__
// Open existing file mapping.
this->mapHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, // Read+write access.
FALSE, // Don't inherit handle.
this->GetName());
if (this->mapHandle == NULL)
{
n_printf("Failed to open file mapping (Error: %d).\n", GetLastError());
return;
}
// Map view of file.
this->mapHeader = MapViewOfFile(this->mapHandle, // Map handle.
FILE_MAP_ALL_ACCESS, // Read+write access.
0,
0,
0);
if (this->mapHeader == NULL)
{
CloseHandle(this->mapHandle);
n_printf("Failed to map view of file (Error: %d).\n", GetLastError());
return;
}
#elif defined(__LINUX__) || defined(__MACOSX__)
#else
#error "nSharedMemory::Open() is not implemented yet!"
#endif
this->mapBody = (char*)this->mapHeader;
this->mapBody += HeaderSize;
this->isOpen = true;
this->writable = false;
this->LockMemory();
this->ReadHeader();
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::Close()
{
n_assert(IsOpen());
if (this->writable)
{
n_assert(this->mapHandle == 0);
if (this->Count() > 0)
{
#ifdef __WIN32__
// Create mapping.
this->mapHandle = CreateFileMapping(INVALID_HANDLE_VALUE,// Page file.
NULL, // Handle cannot be inherited.
PAGE_READWRITE, // Read+write access.
0, // ??
this->Count(), // Size in bytes.
this->GetName()); // Mapping's name.
if (this->mapHandle == NULL)
{
n_printf("Failed to create file mapping (Error: %d).\n", GetLastError());
n_assert_always();
return;
}
// Create view of file in current process's address space.
this->mapHeader = MapViewOfFile(this->mapHandle, // Map handle.
FILE_MAP_ALL_ACCESS, // Read+write access.
0, // ?
0, // ?
0); // Map entire file.
if (this->mapHeader == NULL)
{
CloseHandle(this->mapHandle);
n_printf("Failed to map view of file (Error: %d).\n", GetLastError());
n_assert_always();
return;
}
#elif defined(__LINUX__) || defined(__MACOSX__)
#else
#error "nSharedMemory::Close() is not implemented yet!"
#endif
this->mapBody = (char*)this->mapHeader;
this->mapBody += HeaderSize;
this->LockMemory();
this->WriteHeader();
this->WriteBody();
this->UnlockMemory();
}
}
else
{
n_assert(this->mapHandle != 0);
this->UnlockMemory();
this->DestroyMapping();
}
this->isOpen = false;
this->writable = false;
}
//------------------------------------------------------------------------------
/**
*/
bool
nSharedMemory::IsOpen() const
{
return this->isOpen;
}
//------------------------------------------------------------------------------
/**
*/
int
nSharedMemory::Capacity() const
{
return this->capacity;
}
//------------------------------------------------------------------------------
/**
*/
int
nSharedMemory::Count() const
{
return this->count;
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::ResizeReadBuffer(int n)
{
n_assert(n > 0);
delete [] this->readBuffer;
this->readBuffer = 0;
this->SetupReadBuffer(n);
}
//------------------------------------------------------------------------------
/**
*/
int
nSharedMemory::ReadBufferCapacity() const
{
return this->readBufferCapacity;
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::Write(const char* v, int start, int end)
{
n_assert(this->Writable(start, end));
n_assert(v != 0);
this->writeBuffer.Write(v, start, end);
if (this->count <= end)
{
this->count = end + 1;
}
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::Read(int start, int end)
{
n_assert(this->Readable(start, end));
n_assert(this->ReadBufferCapacity() >= end - start + 1);
if (this->writable)
{
this->writeBuffer.Read(this->readBuffer, start, end);
}
else
{
char* address = this->mapBody;
address += start;
memcpy(this->readBuffer, address, end - start + 1);
}
}
//------------------------------------------------------------------------------
/**
*/
const char*
nSharedMemory::LastRead() const
{
n_assert(this->readBuffer != 0);
return this->readBuffer;
}
//------------------------------------------------------------------------------
/**
*/
bool
nSharedMemory::Readable(int start, int end) const
{
return this->IsOpen() &&
(0 <= start && start <= Count() - 1) &&
(0 <= end && end <= Count() - 1) &&
(end >= start);
}
//------------------------------------------------------------------------------
/**
*/
bool
nSharedMemory::Writable(int start, int end) const
{
return this->IsOpen() &&
this->writable &&
(0 <= start && start <= Capacity() - 1) &&
(0 <= end && end <= Capacity() - 1) &&
(end >= start);
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::SetupReadBuffer(int n)
{
n_assert(this->readBuffer == 0);
this->readBuffer = new char[n];
this->readBufferCapacity = n;
n_assert(this->readBuffer != 0);
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::DestroyMapping()
{
#ifdef __WIN32__
// Unmap view of file.
if (!UnmapViewOfFile(this->mapHeader))
{
n_printf("Failed to unmap view of file (Error: %d).\n", GetLastError());
return;
}
// Close map handle.
if (!CloseHandle(this->mapHandle))
{
n_printf("Failed to close map handle. (Error: %d)\n", GetLastError());
return;
}
#elif defined(__LINUX__) || defined(__MACOSX__)
if (-1 == munmap(this->mapHeader, this->capacity))
{
n_printf("Failed to unmap view of file (Error: %d).\n", errno);
return;
}
if (-1 == close(this->mapHandle))
{
n_printf("Failed to close mapped file. (Error: %d).\n", errno);
return;
}
if (-1 == remove(this->mapFileName.Get()))
{
n_printf("Failed to delete mapped file. (Error: %d).\n", errno);
return;
}
if (-1 == remove(this->mapFileName.Get()))
this->mapFileName.Clear();
#else
#error "nSharedMemory::DestroyMapping() not implemented yet!"
#endif
this->capacity = 0;
this->count = 0;
this->mapBody = 0;
this->mapHeader = 0;
this->mapHandle = 0;
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::ReadHeader()
{
n_assert(this->IsOpen());
n_assert(this->mapHeader != 0);
char* p = (char*)this->mapHeader;
// 1 Byte = `lock'.
p += 1;
// 4 Byte = `capacity'.
memcpy(&this->capacity, p, 4);
p += 4;
// 4 Byte = `count'.
memcpy(&this->count, p, 4);
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::WriteHeader()
{
n_assert(this->IsOpen());
n_assert(this->mapHeader != 0);
char* p = (char*)this->mapHeader;
// 1 Byte = `lock'.
p += 1;
// 4 Byte = `capacity'.
memcpy(p, &this->capacity, 4);
p += 4;
// 4 Byte = `count'.
memcpy(p, &this->count, 4);
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::WriteBody()
{
n_assert(this->mapBody != 0);
memcpy(this->mapBody, this->writeBuffer.Get(), this->writeBuffer.Count());
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::LockMemory()
{
n_assert(this->IsOpen());
n_assert(this->mapHeader != 0);
char* p = (char*)this->mapHeader;
while (*p != 0); // Wait for unlock.
*p = 0;
}
//------------------------------------------------------------------------------
/**
*/
void
nSharedMemory::UnlockMemory()
{
n_assert(this->IsOpen());
n_assert(this->mapHeader != 0);
char* p = (char*)this->mapHeader;
*p = 0;
}
//------------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
470
]
]
]
|
2542dbb9962073281a29285b59133814c2dde125 | a35389bfb109a645e3442038d0ed94a7b82182f5 | /src/VideoPartitioner.hpp | 369ea2dcd6c2f73303020747cf471c33f6cefb50 | [
"X11",
"MIT"
]
| permissive | mszubart/Find-FireBalls | 91226c67260635aae069c48bd05da04433eb822b | 6df9e179e763cbbc1fad16e883689224c22f0f3b | refs/heads/master | 2021-01-10T19:59:34.647168 | 2011-11-01T16:05:49 | 2011-11-01T16:05:49 | 2,604,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,000 | hpp | /*
* Find FireBalls
* Copyright (c) 2011 Mateusz Szubart
*
* 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 VIDEOPARTITIONER_HPP
#define VIDEOPARTITIONER_HPP
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include "CmdOpt.hpp"
#include "FireballFinder.hpp"
#include "VideoPartition.hpp"
class VideoPartitioner {
public:
VideoPartitioner(CmdOptions opt) : _opt(opt) {
}
virtual ~VideoPartitioner();
bool partition_file(int parts);
bool partition_file(boost::thread_group &worker_group, boost::ptr_vector<FireballFinder> &fb_finders, int parts);
boost::ptr_vector<VideoPartition>* get_partitions();
private:
CmdOptions _opt;
cv::VideoCapture _cap;
boost::ptr_vector<VideoPartition> _partitions;
long int _partition_length;
};
#endif /* VIDEOPARTITIONER_HPP */
| [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
b5b1dad8afcef060c6d49e1cf66820fe0e80da65 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/fusion/test/single_view_tests.cpp | 1ac1a9e232ddf076eea0279bba7b348121b6dedf | [
"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,392 | cpp | /*=============================================================================
Copyright (c) 2003 Joel de Guzman
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/fusion/sequence/io.hpp>
#include <boost/spirit/fusion/sequence/single_view.hpp>
#include <boost/spirit/fusion/sequence/begin.hpp>
#include <boost/spirit/fusion/iterator/deref.hpp>
struct X {};
template <typename OS>
OS& operator<<(OS& os, X const&)
{
os << "<X-object>";
return os;
}
int
main()
{
using namespace boost::fusion;
std::cout << tuple_open('[');
std::cout << tuple_close(']');
std::cout << tuple_delimiter(", ");
/// Testing single_view
{
single_view<int> view1(3);
std::cout << view1 << std::endl;
// allow single_view element to be modified
*begin(view1) += 4;
std::cout << view1 << std::endl;
BOOST_TEST(*begin(view1) == 7);
BOOST_TEST(view1.val == 7);
single_view<X> view2;
std::cout << view2 << std::endl;
}
return boost::report_errors();
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
50
]
]
]
|
68bfa868b2736e3eb24bddf5fe6defa21044ac60 | d2996420f8c3a6bbeef63a311dd6adc4acc40436 | /src/client/ClientObjectManager.h | ddc16705fe0e422c0af8b7c016445b8f3669101b | []
| 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 | 1,787 | h | //*********************************************************
// Graviator - QPT2a - FH Salzburg
// Stefan Ebner - Malte Langkabel - Christian Winkler
//
// ClientObjectManager
// Handles everything that comes in at the ClientNetworkHandler.
// Manages the objects (create, move, destroy...).
//
//*********************************************************
#ifndef CLIENT_OBJECT_MANAGER
#define CLIENT_OBJECT_MANAGER
#include "ClientObject.h"
#include "..\GraviatorSimpleTypes.h"
#include <map>
#include <vector>
#define NO_OBJECTS_AVAILABLE -1
struct RenderObjectInformation
{
int id;
char type;
vec3f position, alignment;
};
using namespace std;
class ClientObjectManager
{
public:
ClientObjectManager(void);
~ClientObjectManager(void);
void handleInput(int id, char type, vec3f position, vec3f alignment);
void setPlayerId(unsigned int id);
void makeObjectStatesOlder();
void cleanUpObjectStates();
bool getQuitWithConnectionFailure();
void setQuitWithConnectionFailure(bool value);
vec3f getOwnPlayerPosition();
vec3f getOwnPlayerAlignment();
float getOwnPlayerEnergy();
float getOwnPlayerPoints();
float getEnemyPlayerPoints();
RenderObjectInformation pullNextUnpulledState();
int pullNextUnpulledDeletion();
private:
int getNextUnupdatedObjectId();
void deleteObject(int id);
pthread_mutex_t mObjectStateMutex;
pthread_mutex_t mObjectDeletionMutex;
int mMaxObjectAge;
unsigned int mOwnPlayerId;
vec3f mOwnPlayerPosition;
vec3f mOwnPlayerAlignment;
float mOwnPlayerEnergy;
float mOwnPlayerPoints;
float mEnemyPlayerPoints;
map<int,ClientObject *> mObjectStateMap;
vector<int> mObjectDeletionList;
bool mQuitWithConnectionFailure;
};
#endif
| [
"[email protected]@c8d5bfcc-1391-a108-90e5-e810ef6ef867"
]
| [
[
[
1,
77
]
]
]
|
f3d9fac7c776b74c9459cd5d4580ed3c166c463d | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Com/ScdSlv/ScdDynamic.cpp | b3d78b458c9e546dd118e8b07340def232c01686 | []
| 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 | 6,358 | cpp | // ScdDynamic.cpp : Implementation of CScdDynamic
#include "stdafx.h"
#include "ScdSlv.h"
#include "ScdDynamic.h"
/////////////////////////////////////////////////////////////////////////////
// CScdDynamic
STDMETHODIMP CScdDynamic::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_IScdDynamic
};
for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
void CScdDynamic::FireTheEvent(long Evt, long Data)
{
switch (Evt)
{
case ComCmd_NULL : /*Fire_On...*/ ; break;
};
};
STDMETHODIMP CScdDynamic::get_IsStopped(VARIANT_BOOL *pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
* pVal=gs_TheRunMngr.Stopped();
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::get_IsIdling(VARIANT_BOOL *pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
* pVal=gs_TheRunMngr.Idling();
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::get_IsRunning(VARIANT_BOOL *pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
* pVal=gs_TheRunMngr.Running();
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::get_StepSize(double *pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
* pVal=gs_Exec.StepSizeMax.Seconds;
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::put_StepSize(double newVal)
{
dllSCD_COMENTRY(long)
{
gs_Exec.StepSizeMax=newVal;
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::get_RealTime(VARIANT_BOOL *pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
* pVal=gs_Exec.RealTime();
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::put_RealTime(VARIANT_BOOL newVal)
{
dllSCD_COMENTRY(long)
{
gs_Exec.SetRealTime(newVal!=0);
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::get_RealTimeMultiplier(double *pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
* pVal=gs_Exec.RealTimeMult();
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::put_RealTimeMultiplier(double newVal)
{
dllSCD_COMENTRY(long)
{
gs_Exec.SetRealTimeMult(newVal);
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::Start()
{
dllSCD_COMENTRY(long)
{
long Evts[]={ComState_Stop, ComState_StepDynamic};
switch (PostComCmd(ComCmd_StartDynamicSolve, Evts, sizeof(Evts)/sizeof(Evts[0]), 0))//(long)Info.lParam))
{
case CScdCOCmdBase::SS_CallTimeout:
Scd.Return(HRESULT_ERR(2), "Async Call Timeout");
break;
case CScdCOCmdBase::SS_CallReturned:
case CScdCOCmdBase::SS_CallASync:
break;
}
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::Step(long IterMark, double WaitForNext)
{
dllSCD_COMENTRY(long)
{
gs_TheRunMngr.SetDynamicMode();
CDoOneStepInfo Info;
Info.bHoldAdv=false;
Info.lWaitForNextMS=(long)(WaitForNext*1000.0);
long Evts[]={ComState_Idle, ComState_Stop, ComState_StepProbal, ComState_StepDynamic};
switch (PostComCmd(ComCmd_Step, Evts, sizeof(Evts)/sizeof(Evts[0]), (long)Info.lParam))
{
case CScdCOCmdBase::SS_CallTimeout:
Scd.Return(HRESULT_ERR(2), "Async Call Timeout");
break;
case CScdCOCmdBase::SS_CallReturned:
case CScdCOCmdBase::SS_CallASync:
break;
}
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::Stop()
{
dllSCD_COMENTRY(long)
{
long Evts[]={ComState_Stop};
switch (PostComCmd(ComCmd_Stop, Evts, sizeof(Evts)/sizeof(Evts[0]), 0))
{
case CScdCOCmdBase::SS_CallTimeout:
Scd.Return(HRESULT_ERR(2), "Async Call Timeout");
break;
case CScdCOCmdBase::SS_CallReturned:
case CScdCOCmdBase::SS_CallASync:
break;
}
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::Idle()
{
dllSCD_COMENTRY(long)
{
long Evts[]={ComState_Idle, ComState_Stop, ComState_StepProbal, ComState_StepDynamic};
switch (PostComCmd(ComCmd_Idle, Evts, sizeof(Evts)/sizeof(Evts[0]), 0))
{
case CScdCOCmdBase::SS_CallTimeout:
Scd.Return(HRESULT_ERR(2), "Async Call Timeout");
break;
case CScdCOCmdBase::SS_CallReturned:
case CScdCOCmdBase::SS_CallASync:
break;
}
}
SCD_COMEXIT
};
STDMETHODIMP CScdDynamic::RunToSteadyState()
{
dllSCD_COMENTRY(long)
{
long Evts[]={ComState_Stop, ComState_StepDynamic};
switch (PostComCmd(ComCmd_RunToSteadyState, Evts, sizeof(Evts)/sizeof(Evts[0]), 0))//(long)Info.lParam))
{
case CScdCOCmdBase::SS_CallTimeout:
Scd.Return(HRESULT_ERR(2), "Async Call Timeout");
break;
case CScdCOCmdBase::SS_CallReturned:
case CScdCOCmdBase::SS_CallASync:
break;
}
}
SCD_COMEXIT
};
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
61
],
[
63,
70
],
[
72,
187
]
],
[
[
62,
62
],
[
71,
71
],
[
188,
205
]
]
]
|
f6b1008617139dba31872537349565713d8dbcac | 3532ae25961855b20635decd1481ed7def20c728 | /app/ClientLib/bconnection.cpp | 2f738e69ff9a2a442bb4447a1192b292ea4e410e | []
| no_license | mcharmas/Bazinga | 121645a0c7bc8bd6a91322c2a7ecc56a5d3f71b7 | 1d35317422c913f28710b3182ee0e03822284ba3 | refs/heads/master | 2020-05-18T05:48:32.213937 | 2010-03-22T17:13:09 | 2010-03-22T17:13:09 | 577,323 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,651 | cpp | #include "bconnection.h"
#include "bconnectionexception.h"
#include <QDateTime>
#include <QThread>
#include <QDebug>
CLIENTLIBSHARED_EXPORT BConnection::BConnection(unsigned char clientType)
: sessid(0), clientType(clientType), confirmed(false)
{
startTimer(B_INTERVAL_ACK_MS);
}
void BConnection::connect(const QString & serverAddress,
quint16 serverPort,
const QString & login,
const QString & password,
quint16 listeningPort,
const QString & token) {
qDebug() << "Sending SREQ";
hostAddress.setAddress(serverAddress);
hostPort = serverPort;
this->listeningPort = listeningPort;
socket.bind(listeningPort);
QByteArray arr((login + ":" + password
+ ":" + QString::number(listeningPort)
+ (token.isEmpty() ? QString() : QString(":") + token)).toAscii());
sendData(B_TYPE_SREQ, arr);
}
void BConnection::disconnectFromHost() {
qDebug() << "Disconnecting";
sendData(B_TYPE_CLOSE);
socket.disconnectFromHost();
hostAddress.setAddress("A-S-D-F");
hostPort = 0;
listeningPort = 0;
sessid = 0;
}
QByteArray * BConnection::newTMPdatagram(unsigned char command, QByteArray & data) {
BDatagram gram(sessid, clientType,
(quint32) QDateTime::currentDateTime().toTime_t(),
command, data);
return gram.getAllData();
}
int BConnection::sendData(BDatagram &data) {
QByteArray * datagram = data.getAllData();
int status = socket.writeDatagram(*datagram, hostAddress, hostPort);
delete datagram;
return status;
}
int BConnection::sendData(unsigned char command, QByteArray & data) {
QByteArray * tmpGram = newTMPdatagram(command, data);
int status = socket.writeDatagram(*tmpGram, hostAddress, hostPort);
delete tmpGram;
return status;
}
int BConnection::sendData(unsigned char command) {
QByteArray empty;
return sendData(command, empty);
}
void BConnection::sendObjects(BObList *list) {
if(list && ! list->empty()) {
//qDebug() << list->toString();
QByteArray * packed = list->pack();
sendData(B_TYPE_OBJECT, *packed);
delete packed;
}
}
void BConnection::timerEvent(QTimerEvent * e) {
if(isSessionAlive()) {
if(confirmed) {
qDebug() << "Sending CHECK";
sendData(B_TYPE_CHECK);
confirmed = false;
} else {
qDebug() << "Server lost.";
disconnectFromHost();
emit disconnected();
}
}
}
BDatagram * BConnection::getData() {
if(socket.state() != QUdpSocket::BoundState
|| !socket.hasPendingDatagrams()) {
return NULL;
}
if(socket.waitForReadyRead(1)) {
int size = socket.pendingDatagramSize();
if(size > 0) {
char * data = new char[size];
QHostAddress senderAddr;
quint16 senderPort;
socket.readDatagram(data, size, &senderAddr, &senderPort);
if (senderAddr != hostAddress && senderPort != hostPort) {
qDebug() << "Bad sender: " << senderAddr << ":" << senderPort
<< "; expected: " << hostAddress << ":" << hostPort;
delete data;
throw new BConnectionException("Bad sender");
} else {
BDatagram * datagram = new BDatagram(data, size);
delete data; // moze powodowac segfault jesli BDataArray nie kopiuje tego. powinno sie okazac po pierwszym odpaleniu
if(datagram->source != B_SOURCE_SERVER) {
delete datagram;
throw new BConnectionException("Packet not from server!");
}
switch (datagram->type) {
case B_TYPE_SACK:
if(this->sessid == 0 && datagram->sessid != 0) {
qDebug() << "Logged in. Got session ID: " << datagram->sessid;
sessid = datagram->sessid;
confirmed = true;
delete datagram;
emit connected(sessid);
} else if(datagram->sessid == 0) {
throw new BConnectionException("ACK with session ID 0? WTF.");
} else if(datagram->sessid == this->sessid) {
// ok
} else {
delete datagram;
throw new BConnectionException("Someone tried to inject different sessionid");
}
break;
case B_TYPE_SDEN:
sessid = 0;
confirmed = false;
delete datagram;
disconnectFromHost();
emit disconnected();
// throw new BConnectionException("Server disconnected.");
break;
case B_TYPE_CONFIRM:
delete datagram;
confirmed = true;
qDebug() << "GOT CONFIRM";
break;
case B_TYPE_ERROR:
throw new BConnectionException("ERROR", datagram);
break;
case B_TYPE_OBJECT:
default:
confirmed = true;
return datagram;
}
}
}
}
return NULL;
}
bool BConnection::isSessionAlive() {
return sessid != 0;
}
| [
"santamon@ffdda973-792b-4bce-9e62-2343ac01ffa1"
]
| [
[
[
1,
176
]
]
]
|
56526e7bff6a43a4711015312f08d07a7cbbf09a | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/TreeWalkerImpl.hpp | 17f2f1c9d58459e89c0f217d81fa45dbc260e5e5 | [
"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,329 | hpp | /*
* Copyright 1999-2002,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: TreeWalkerImpl.hpp,v 1.6 2004/09/08 13:55:44 peiyongz Exp $
*/
//
// This file is part of the internal implementation of the C++ XML DOM.
// It should NOT be included or used directly by application programs.
//
// Applications should include the file <xercesc/dom/deprecated/DOM.hpp> for the entire
// DOM API, or DOM_*.hpp for individual DOM classes, where the class
// name is substituded for the *.
//
#ifndef TreeWalkerImpl_HEADER_GUARD_
#define TreeWalkerImpl_HEADER_GUARD_
#include <xercesc/util/XMemory.hpp>
#include "DOM_TreeWalker.hpp"
#include "RefCountedImpl.hpp"
XERCES_CPP_NAMESPACE_BEGIN
class DEPRECATED_DOM_EXPORT TreeWalkerImpl : public RefCountedImpl {
public:
// Implementation Note: No state is kept except the data above
// (fWhatToShow, fNodeFilter, fCurrentNode, fRoot) such that
// setters could be created for these data values and the
// implementation will still work.
/** Public constructor */
TreeWalkerImpl (
DOM_Node root,
unsigned long whatToShow,
DOM_NodeFilter* nodeFilter,
bool expandEntityRef);
TreeWalkerImpl (const TreeWalkerImpl& twi);
TreeWalkerImpl& operator= (const TreeWalkerImpl& twi);
// Return the root DOM_Node.
DOM_Node getRoot ();
// Return the whatToShow value.
unsigned long getWhatToShow ();
// Return the NodeFilter.
DOM_NodeFilter* getFilter ();
// Return the current DOM_Node.
DOM_Node getCurrentNode ();
// Return the current Node.
void setCurrentNode (DOM_Node node);
// Return the parent Node from the current node,
// after applying filter, whatToshow.
// If result is not null, set the current Node.
DOM_Node parentNode ();
// Return the first child Node from the current node,
// after applying filter, whatToshow.
// If result is not null, set the current Node.
DOM_Node firstChild ();
// Return the last child Node from the current node,
// after applying filter, whatToshow.
// If result is not null, set the current Node.
DOM_Node lastChild ();
// Return the previous sibling Node from the current node,
// after applying filter, whatToshow.
// If result is not null, set the current Node.
DOM_Node previousSibling ();
// Return the next sibling Node from the current node,
// after applying filter, whatToshow.
// If result is not null, set the current Node.
DOM_Node nextSibling ();
// Return the previous Node from the current node,
// after applying filter, whatToshow.
// If result is not null, set the current Node.
DOM_Node previousNode ();
// Return the next Node from the current node,
// after applying filter, whatToshow.
// If result is not null, set the current Node.
DOM_Node nextNode ();
void unreferenced ();
// Get the expandEntity reference flag.
bool getExpandEntityReferences();
protected:
// Internal function.
// Return the parent Node, from the input node
// after applying filter, whatToshow.
// The current node is not consulted or set.
DOM_Node getParentNode (DOM_Node node);
// Internal function.
// Return the nextSibling Node, from the input node
// after applying filter, whatToshow.
// The current node is not consulted or set.
DOM_Node getNextSibling (DOM_Node node);
// Internal function.
// Return the previous sibling Node, from the input node
// after applying filter, whatToshow.
// The current node is not consulted or set.
DOM_Node getPreviousSibling (DOM_Node node);
// Internal function.
// Return the first child Node, from the input node
// after applying filter, whatToshow.
// The current node is not consulted or set.
DOM_Node getFirstChild (DOM_Node node);
// Internal function.
// Return the last child Node, from the input node
// after applying filter, whatToshow.
// The current node is not consulted or set.
DOM_Node getLastChild (DOM_Node node);
// The node is accepted if it passes the whatToShow and the filter.
short acceptNode (DOM_Node node);
private:
// The whatToShow mask.
unsigned long fWhatToShow;
// The NodeFilter reference.
DOM_NodeFilter* fNodeFilter;
// The current Node.
DOM_Node fCurrentNode;
// The root Node.
DOM_Node fRoot;
// The expandEntity reference flag.
bool fExpandEntityReferences;
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
]
| [
[
[
1,
167
]
]
]
|
d8ef131f4b74c4cedc283ceb29becc9c789a27d7 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/EnemyEntity.h | d9338b22332378fb36dac160baf7940cc63f759a | []
| no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 964 | h | #include "RigidModelEntity.h"
class EnemyEntity : public RigidModelEntity {
public:
EnemyEntity(GameServices *gs, OgreNewt::World *collisionWorld, Ogre::SceneNode* parentNode, const Ogre::Vector3 &pos, const Ogre::Vector3 &size, const Ogre::String &name, const Ogre::String &modelFile);
virtual ~EnemyEntity();
//called when force is ready to be applied. Put all
//force related code in here
virtual void forceCallback(OgreNewt::Body* b);
virtual void transformCallback(OgreNewt::Body *b, const Ogre::Quaternion&, const Ogre::Vector3&);
virtual void onCollisionEntered(RigidModelEntity *colEntity);
void kill();
float attackDamage();
bool isWaitingToDie();
void setTargetNode(Ogre::SceneNode *targetNode);
void update();
private:
bool mWaitingToDie;
float mMass;
float mMaxSpeed;
Ogre::SceneNode *mTargetNode;
Ogre::AnimationState *mAnimationState;
float mDamage;
float mLifeSpan;
Ogre::Timer *mLifeClock;
}; | [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
]
| [
[
[
1,
30
]
]
]
|
5cb5ac64607025b499288205017cce3b35fd9a01 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/inc/gfx/ngfxtypes.h | 83697ddf578372672efa8ccea286ce7b54e29b1b | []
| no_license | DSPNerd/m-nebula | 76a4578f5504f6902e054ddd365b42672024de6d | 52a32902773c10cf1c6bc3dabefd2fd1587d83b3 | refs/heads/master | 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,955 | h | #ifndef N_GFXTYPES_H
#define N_GFXTYPES_H
//-------------------------------------------------------------------
// OVERVIEW
// Gfx related typedefs and low level classes.
//
// 21-Oct-00 floh + new vertex components: weight and joint index
//
// (C) 1999 A.Weissflog
//-------------------------------------------------------------------
#ifndef N_TYPES_H
#include "kernel/ntypes.h"
#endif
//-- convert float color components to rgba or bgra color -----------
inline ulong n_f2rgba(float r, float g, float b, float a)
{
return (ulong(((ulong((a)*255.0f)<<24)|(ulong((b)*255.0f)<<16)|(ulong((g)*255.0f)<<8)|(ulong((r)*255.0f)))));
}
inline ulong n_f2bgra(float r, float g, float b, float a)
{
return (ulong(((ulong((a)*255.0f)<<24)|(ulong((r)*255.0f)<<16)|(ulong((g)*255.0f)<<8)|(ulong((b)*255.0f)))));
}
inline long n_ucrgb2i(uchar r, uchar g, uchar b, uchar a)
{
return (long((long(a)<<24)|(long(b)<<16)|(long(g)<<8)|(long(r))));
}
inline long n_ucrgb2i(uchar* c)
{
return n_ucrgb2i(c[0], c[1], c[2], c[3]);
}
inline void n_i2ucrgba(long i, uchar& r, uchar& g, uchar& b, uchar& a)
{
r = (uchar)i; i >>= 8;
g = (uchar)i; i >>= 8;
b = (uchar)i; i >>= 8;
a = (uchar)i;
}
inline void n_i2frgba(long i, float& fr, float& fg, float& fb, float& fa)
{
uchar r = (uchar)i; i >>= 8;
uchar g = (uchar)i; i >>= 8;
uchar b = (uchar)i; i >>= 8;
uchar a = (uchar)i;
fr = ((float)r)/255.0f;
fg = ((float)g)/255.0f;
fb = ((float)b)/255.0f;
fa = ((float)a)/255.0f;
}
inline uchar n_i2r(long i)
{
return (uchar)i;
}
inline uchar n_i2g(long i)
{
return (uchar)(i>>8);
}
inline uchar n_i2b(long i)
{
return (uchar)(i>>16);
}
inline uchar n_i2a(long i)
{
return (uchar)(i>>24);
}
//-- matrix modes ---------------------------------------------------
enum nMatrixMode {
N_MXM_VIEWER,
N_MXM_MODELVIEW,
N_MXM_PROJECTION,
N_MXM_INVVIEWER, // only GetMatrix()!
};
//-- primitive types ------------------------------------------------
enum nPrimType {
N_PTYPE_POINT_LIST=0x0000,
N_PTYPE_LINE_LIST, // 0x0001
N_PTYPE_LINE_LOOP, // 0x0002
N_PTYPE_LINE_STRIP, // 0x0003
N_PTYPE_TRIANGLE_LIST, // 0x0004
N_PTYPE_TRIANGLE_STRIP, // 0x0005
N_PTYPE_TRIANGLE_FAN, // 0x0006
N_PTYPE_QUADS_LIST, // 0x0007
N_PTYPE_QUADS_STRIP, // 0x0008
N_PTYPE_CONVEX_POLY, // 0x0009
};
//-- light types ----------------------------------------------------
enum nLightType {
N_LIGHT_AMBIENT,
N_LIGHT_POINT,
N_LIGHT_SPOT,
N_LIGHT_DIRECTIONAL,
};
//-- fog modes ------------------------------------------------------
enum nFogMode {
N_FOGMODE_OFF,
N_FOGMODE_LINEAR,
N_FOGMODE_EXP,
N_FOGMODE_EXP2,
};
//-- font types ------------------------------------------------------
enum nFontType
{
N_FONT_NONE = 0,
N_FONT_PIXMAP,
N_FONT_BITMAP,
N_FONT_TEXTURE,
N_FONT_POLYGON,
N_FONT_EXTRUDED,
N_FONT_OUTLINE
};
enum nVerticalAlign
{
N_VA_NONE,
N_VA_CENTER,
N_VA_TOP,
N_VA_BOTTOM,
};
enum nHorizontalAlign
{
N_HA_NONE,
N_HA_CENTER,
N_HA_LEFT,
N_HA_RIGHT
};
enum nShaderType
{
N_VERTEX_SHADER,
N_FRAGMENT_SHADER
};
enum nFrameBufferType {
N_BUFFER_NONE = 0x0,
N_BUFFER_FRONT = 0x1,
N_BUFFER_BACK = 0x2,
N_BUFFER_SELECT = 0x4,
};
//-- vertex components ----------------------------------------------
enum nVertexType {
N_VT_VOID = 0, // undefined
N_VT_COORD = (1<<0), // has xyz
N_VT_NORM = (1<<1), // has normals
N_VT_RGBA = (1<<2), // has color
N_VT_UV0 = (1<<3), // has texcoord set 0
N_VT_UV1 = (1<<4), // has texcoord set 1
N_VT_UV2 = (1<<5), // has texcoord set 2
N_VT_UV3 = (1<<6), // has texcoord set 3
N_VT_JW = (1<<7), // has up to 4 joint weights per vertex
};
enum {
N_MAXNUM_TEXCOORDS = 4,
N_MAXNUM_WEIGHTSETS = 4,
N_MAXNUM_JOINTSETS = 4,
N_MAXNUM_TEXSTAGES = 4,
};
//-- platform specific color format ----------------------------------
enum nColorFormat {
N_COLOR_RGBA,
N_COLOR_BGRA,
};
//-- vertex buffer types --------------------------------------------
enum nVBufType {
N_VBTYPE_STATIC = 0, // vbuffer is written once and never touched again
N_VBTYPE_READONLY = 1, // this vbuffer is never rendered
N_VBTYPE_WRITEONLY = 2, // this vbuffer is only written to
N_NUM_VBTYPES = 3,
};
//-- index buffer types ---------------------------------------------
enum nIBufType {
N_IBTYPE_STATIC = 0, // index buffer is written once never touched again
N_IBTYPE_WRITEONLY = 1, // index buffer will only be written
N_NUM_IBTYPES = 2,
};
enum nClearBufType {
N_COLOR_BUFFER = 0x1,
N_DEPTH_BUFFER = 0x2,
N_STENCIL_BUFFER = 0x4,
N_ACCUM_BUFFER = 0x8
};
//-- render states --------------------------------------------------
enum nRStateType {
N_RS_VOID = 0,
// texturing
N_RS_TEXTURESTAGE = 1, // 0..n
N_RS_TEXTUREHANDLE = 2, // nTexture *
N_RS_TEXTUREADDRESSU = 3, // N_TADDR_*
N_RS_TEXTUREADDRESSV = 4, // N_TADDR_*
N_RS_TEXTUREBLEND = 5, // N_TBLEND_*
N_RS_TEXTUREMINFILTER = 6, // N_TFILTER_*
N_RS_TEXTUREMAGFILTER = 7, // N_TFILTER_*
// z buffer
N_RS_ZWRITEENABLE = 8, // N_TRUE/N_FALSE
N_RS_ZFUNC = 9, // N_CMP_*
N_RS_ZBIAS = 10, // float
// alpha blending
N_RS_ALPHABLENDENABLE = 11, // N_TRUE/N_FALSE
N_RS_ALPHASRCBLEND = 12, // N_ABLEND_*
N_RS_ALPHADESTBLEND = 13, // N_ABLEND_*
// lighting and material
N_RS_LIGHTING = 14, // N_TRUE/N_FALSE
N_RS_COLORMATERIAL = 15, // N_CMAT_*
// textur coord generation
N_RS_TEXGENMODE = 16, // N_TEXGEN_*
N_RS_TEXGENPARAMU = 17, // float[4] *
N_RS_TEXGENPARAMV = 18, // float[4] *
// fog
N_RS_FOGMODE = 20, // N_FOGMODE_*
N_RS_FOGSTART = 21, // float
N_RS_FOGEND = 22, // float
N_RS_FOGDENSITY = 23, // float
N_RS_FOGCOLOR = 24, // float[4] *
// misc
N_RS_MATERIALHANDLE = 25, // nMaterial *
N_RS_DONTCLIP = 26, // == ClipVolumeHint
N_RS_CLIPPLANEENABLE = 27, // int
N_RS_CLIPPLANEDISABLE = 28, // int
N_RS_CULLMODE = 29, // N_CULL_*
N_RS_NORMALIZENORMALS = 30, // N_TRUE/N_FALSE
// alpha test
N_RS_ALPHATESTENABLE = 31, // N_TRUE/N_FALSE
N_RS_ALPHAREF = 32, // int
N_RS_ALPHAFUNC = 33, // N_CMP_*
// stencil buffer
N_RS_STENCILENABLE = 34, // N_TRUE/N_FALSE
N_RS_STENCILFAIL = 35, // N_STENCILOP_*
N_RS_STENCILZFAIL = 36, // N_STENCILOP_*
N_RS_STENCILPASS = 37, // N_STENCILOP_*
N_RS_STENCILFUNC = 38, // N_CMP_*
N_RS_STENCILREF = 39, // int
N_RS_STENCILMASK = 40, // int
N_RS_STENCILCLEAR = 41, // int
N_RS_COLORWRITEENABLE = 42, // N_TRUE/N_FALSE
N_RS_NUM = 43,
};
//-- renderstate parameters -----------------------------------------
enum nRStateParam {
N_FALSE = 0,
N_TRUE = 1,
N_TFILTER_NEAREST,
N_TFILTER_LINEAR,
N_TFILTER_NEAREST_MIPMAP_NEAREST,
N_TFILTER_LINEAR_MIPMAP_NEAREST,
N_TFILTER_NEAREST_MIPMAP_LINEAR,
N_TFILTER_LINEAR_MIPMAP_LINEAR,
N_TADDR_WRAP,
N_TADDR_CLAMP,
N_TADDR_CLAMP_TO_EDGE,
N_TBLEND_DECAL, // cPix=(cSrc*(1.0-aTex))+(aTex*cTex), aPix=aSrc
N_TBLEND_MODULATE, // cPix=cSrc*cTex, aPix=aSrc*aTex
N_TBLEND_REPLACE, // cPix=cTex, aPix=aTex
N_TBLEND_BLEND, // cPix=cSrc*(1.0-cTex)+(cTex), aPix=aSrc*aTex
// z, alpha stencil compare function
N_CMP_NEVER,
N_CMP_LESS,
N_CMP_EQUAL,
N_CMP_LESSEQUAL,
N_CMP_GREATER,
N_CMP_NOTEQUAL,
N_CMP_GREATEREQUAL,
N_CMP_ALWAYS,
N_ABLEND_ZERO, // (0,0,0,0)
N_ABLEND_ONE, // (1,1,1,1)
N_ABLEND_SRCCOLOR, // (Rs,Gs,Bs,As)
N_ABLEND_INVSRCCOLOR, // (1-Rs,1-Gs,1-Bs,1-As)
N_ABLEND_SRCALPHA, // (As,As,As,As)
N_ABLEND_INVSRCALPHA, // (1-As,1-As,1-As,1-As)
N_ABLEND_DESTALPHA, // (Ad,Ad,Ad,Ad)
N_ABLEND_INVDESTALPHA, // (1-Ad,1-Ad,1-Ad,1-Ad)
N_ABLEND_DESTCOLOR, // (Rd,Gd,Bd,Ad)
N_ABLEND_INVDESTCOLOR, // (1-Rd,1-Gd,1-Bd,1-Ad)
N_TEXGEN_OFF,
N_TEXGEN_OBJECTLINEAR, // == GL_OBJECT_LINEAR
N_TEXGEN_EYELINEAR, // == GL_EYE_LINEAR
N_TEXGEN_SPHEREMAP, // == GL_SPHERE_MAP
N_CULL_NONE,
N_CULL_CW,
N_CULL_CCW,
N_CMAT_MATERIAL, // material completely defines light parameters
N_CMAT_DIFFUSE, // vertex color defines diffuse component
N_CMAT_EMISSIVE, // vertex color defines emissive component
N_CMAT_AMBIENT, // vertex color defines ambient component
N_TCOORDSRC_UV0, // the texture coordinate source
N_TCOORDSRC_UV1,
N_TCOORDSRC_UV2,
N_TCOORDSRC_UV3,
N_TCOORDSRC_OBJECTSPACE,
N_TCOORDSRC_EYESPACE,
N_TCOORDSRC_SPHEREMAP,
N_TCOORDSRC_REFLECTION,
// stencil op
N_STENCILOP_KEEP,
N_STENCILOP_ZERO,
N_STENCILOP_REPLACE,
N_STENCILOP_INVERT,
N_STENCILOP_INCR, // increment with saturate
N_STENCILOP_DECR, // decrement with saturate
};
//-- render state class ---------------------------------------------
class nRState {
public:
nRStateType rtype;
union {
void *p;
int i;
float f;
nRStateParam r;
} rstate;
inline nRState() { rtype=N_RS_VOID; };
inline nRState(nRStateType t, void *p) { rtype=t; rstate.p=p; };
inline nRState(nRStateType t, int i) { rtype=t; rstate.i=i; };
inline nRState(nRStateType t, nRStateParam r) { rtype=t; rstate.r=r; };
inline nRState(nRStateType t, float f) { rtype=t; rstate.f=f; };
inline void Set(nRStateType t, void *p) { rtype=t; rstate.p=p; };
inline void Set(nRStateType t, int i) { rtype=t; rstate.i=i; };
inline void Set(nRStateType t, nRStateParam r) { rtype=t; rstate.r=r; };
inline void Set(nRStateType t, float f) { rtype=t; rstate.f=f; };
inline bool Cmp(nRState *rs) {
if ((rs->rtype==rtype) && (rs->rstate.i==rstate.i)) return true;
else return false;
};
};
//-------------------------------------------------------------------
#endif
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
378
]
]
]
|
c1056b425d98f94b047705b0189d108a7e904574 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/mrflea.h | 947a9868d5660bab487ef1a9346d08fee7d53811 | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 896 | h | /*************************************************************************
Mr. Flea
*************************************************************************/
class mrflea_state : public driver_device
{
public:
mrflea_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
/* memory pointers */
UINT8 * m_videoram;
UINT8 * m_spriteram;
// UINT8 * paletteram; // currently this uses generic palette handling
/* video-related */
int m_gfx_bank;
/* misc */
int m_io;
int m_main;
int m_status;
int m_select1;
/* devices */
device_t *m_maincpu;
device_t *m_subcpu;
};
/*----------- defined in video/mrflea.c -----------*/
WRITE8_HANDLER( mrflea_gfx_bank_w );
WRITE8_HANDLER( mrflea_videoram_w );
WRITE8_HANDLER( mrflea_spriteram_w );
SCREEN_UPDATE( mrflea );
| [
"Mike@localhost"
]
| [
[
[
1,
39
]
]
]
|
a573007a8150f915c4de5ec6d1890783260ee0cf | 2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4 | /OUAN/OUAN/Src/Game/GameObject/GameObjectWoodBox.cpp | 9308435ed1167fac60b1299b47af2fce6fd039df | []
| no_license | juanjmostazo/once-upon-a-night | 9651dc4dcebef80f0475e2e61865193ad61edaaa | f8d5d3a62952c45093a94c8b073cbb70f8146a53 | refs/heads/master | 2020-05-28T05:45:17.386664 | 2010-10-06T12:49:50 | 2010-10-06T12:49:50 | 38,101,059 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,552 | cpp | #include "OUAN_Precompiled.h"
#include "GameObjectWoodBox.h"
#include "../GameWorldManager.h"
#include "../../Logic/LogicSubsystem.h"
#include "../../Graphics/RenderComponent/RenderComponentParticleSystem.h"
#include "../../Audio/AudioComponent/AudioComponent.h"
using namespace OUAN;
GameObjectWoodBox::GameObjectWoodBox(const std::string& name)
:GameObject(name,GAME_OBJECT_TYPE_WOODBOX)
{
}
GameObjectWoodBox::~GameObjectWoodBox()
{
}
RenderComponentEntityPtr GameObjectWoodBox::getRenderComponentEntityDreams() const
{
return mRenderComponentEntityDreams;
}
void GameObjectWoodBox::setRenderComponentEntityDreams(RenderComponentEntityPtr pRenderComponentEntityDreams)
{
mRenderComponentEntityDreams=pRenderComponentEntityDreams;
}
RenderComponentEntityPtr GameObjectWoodBox::getRenderComponentEntityNightmares() const
{
return mRenderComponentEntityNightmares;
}
void GameObjectWoodBox::setRenderComponentEntityNightmares(RenderComponentEntityPtr pRenderComponentEntityNightmares)
{
mRenderComponentEntityNightmares=pRenderComponentEntityNightmares;
}
void GameObjectWoodBox::setRenderComponentPositional(RenderComponentPositionalPtr pRenderComponentPositional)
{
mRenderComponentPositional=pRenderComponentPositional;
}
AudioComponentPtr GameObjectWoodBox::getAudioComponent() const
{
return mAudioComponent;
}
void GameObjectWoodBox::setAudioComponent(AudioComponentPtr audioComponent)
{
mAudioComponent=audioComponent;
}
void GameObjectWoodBox::setRenderComponentInitial(RenderComponentInitialPtr pRenderComponentInitial)
{
mRenderComponentInitial=pRenderComponentInitial;
}
RenderComponentPositionalPtr GameObjectWoodBox::getRenderComponentPositional() const
{
return mRenderComponentPositional;
}
RenderComponentInitialPtr GameObjectWoodBox::getRenderComponentInitial() const
{
return mRenderComponentInitial;
}
void GameObjectWoodBox::setRenderComponentParticleSystemDust(RenderComponentParticleSystemPtr pRenderComponentParticleSystemDust)
{
mRenderComponentParticleSystemDust = pRenderComponentParticleSystemDust;
}
RenderComponentParticleSystemPtr GameObjectWoodBox::getRenderComponentParticleSystemDust() const
{
return mRenderComponentParticleSystemDust;
}
void GameObjectWoodBox::setPhysicsComponentSimpleBox(PhysicsComponentSimpleBoxPtr pPhysicsComponentSimpleBox)
{
mPhysicsComponentSimpleBox=pPhysicsComponentSimpleBox;
}
PhysicsComponentSimpleBoxPtr GameObjectWoodBox::getPhysicsComponentSimpleBox() const
{
return mPhysicsComponentSimpleBox;
}
void GameObjectWoodBox::setDreamsRender()
{
if (!isEnabled()) return;
if(mLogicComponentBreakable->existsInDreams())
{
mRenderComponentEntityDreams->setVisible(true);
mRenderComponentEntityDreams->setDreamsMaterials();
}
if(mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityNightmares->setVisible(false);
}
}
void GameObjectWoodBox::setNightmaresRender()
{
if (!isEnabled()) return;
if(mLogicComponentBreakable->existsInDreams())
{
mRenderComponentEntityDreams->setVisible(false);
}
if(mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityNightmares->setVisible(true);
mRenderComponentEntityNightmares->setNightmaresMaterials();
}
}
void GameObjectWoodBox::setChangeWorldFactor(double factor)
{
if (!isEnabled()) return;
if(mLogicComponentBreakable->existsInDreams())
{
mRenderComponentEntityDreams->setChangeWorldFactor(factor);
}
if(mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityNightmares->setChangeWorldFactor(factor);
}
}
void GameObjectWoodBox::setChangeWorldRender()
{
if (!isEnabled()) return;
switch(mWorld)
{
case DREAMS:
if(mLogicComponentBreakable->existsInDreams() && mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityDreams->setVisible(true);
mRenderComponentEntityDreams->setChangeWorldMaterials();
mRenderComponentEntityNightmares->setVisible(false);
}
else if(!mLogicComponentBreakable->existsInDreams() && mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityNightmares->setVisible(true);
mRenderComponentEntityNightmares->setChangeWorldMaterials();
}
else if(mLogicComponentBreakable->existsInDreams() && !mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityDreams->setVisible(true);
mRenderComponentEntityDreams->setChangeWorldMaterials();
}
break;
case NIGHTMARES:
if(mLogicComponentBreakable->existsInDreams() && mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityNightmares->setVisible(true);
mRenderComponentEntityNightmares->setChangeWorldMaterials();
mRenderComponentEntityDreams->setVisible(false);
}
else if(!mLogicComponentBreakable->existsInDreams() && mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityNightmares->setVisible(true);
mRenderComponentEntityNightmares->setChangeWorldMaterials();
}
else if(mLogicComponentBreakable->existsInDreams() && !mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityDreams->setVisible(true);
mRenderComponentEntityDreams->setChangeWorldMaterials();
}
break;
default:break;
}
}
void GameObjectWoodBox::changeWorldFinished(int newWorld)
{
if (!isEnabled()) return;
switch(newWorld)
{
case DREAMS:
setDreamsRender();
break;
case NIGHTMARES:
setNightmaresRender();
break;
default:break;
}
switch(newWorld)
{
case DREAMS:
if(mLogicComponentBreakable->existsInDreams() && mLogicComponentBreakable->existsInNightmares())
{
if (mPhysicsComponentSimpleBox.get() && !mPhysicsComponentSimpleBox->isInUse())
{
mPhysicsComponentSimpleBox->create();
}
}
else if(mLogicComponentBreakable->existsInDreams()&& !mLogicComponentBreakable->existsInNightmares())
{
if (mPhysicsComponentSimpleBox.get() && !mPhysicsComponentSimpleBox->isInUse())
{
mPhysicsComponentSimpleBox->create();
}
}
else if(!mLogicComponentBreakable->existsInDreams()&& mLogicComponentBreakable->existsInNightmares())
{
if (mPhysicsComponentSimpleBox.get() && mPhysicsComponentSimpleBox->isInUse())
{
mPhysicsComponentSimpleBox->destroy();
}
}
break;
case NIGHTMARES:
if(mLogicComponentBreakable->existsInDreams() && mLogicComponentBreakable->existsInNightmares())
{
if (mPhysicsComponentSimpleBox.get() && !mPhysicsComponentSimpleBox->isInUse())
{
mPhysicsComponentSimpleBox->create();
}
}
else if(mLogicComponentBreakable->existsInDreams()&& !mLogicComponentBreakable->existsInNightmares())
{
if (mPhysicsComponentSimpleBox.get() && mPhysicsComponentSimpleBox->isInUse())
{
mPhysicsComponentSimpleBox->destroy();
}
}
else if(!mLogicComponentBreakable->existsInDreams()&& mLogicComponentBreakable->existsInNightmares())
{
if (mPhysicsComponentSimpleBox.get() && !mPhysicsComponentSimpleBox->isInUse())
{
mPhysicsComponentSimpleBox->create();
}
}
break;
default:break;
}
}
void GameObjectWoodBox::changeWorldStarted(int newWorld)
{
if (!isEnabled()) return;
switch(newWorld)
{
case DREAMS:
break;
case NIGHTMARES:
break;
default:
break;
}
}
void GameObjectWoodBox::changeToWorld(int newWorld, double perc)
{
if (!isEnabled()) return;
switch(newWorld)
{
case DREAMS:
break;
case NIGHTMARES:
break;
default:
break;
}
}
void GameObjectWoodBox::reset()
{
GameObject::reset();
mLogicComponentBreakable->setIsBroken(false);
if (mPhysicsComponentSimpleBox.get())
{
if(!mPhysicsComponentSimpleBox->isInUse())
{
mPhysicsComponentSimpleBox->create();
}
mPhysicsComponentSimpleBox->setPosition(mRenderComponentInitial->getPosition());
mPhysicsComponentSimpleBox->setOrientation(mRenderComponentInitial->getOrientation());
mRenderComponentPositional->setPosition(mRenderComponentInitial->getPosition());
mRenderComponentPositional->setOrientation(mRenderComponentInitial->getOrientation());
}
if (mRenderComponentEntityAdditional.get())
{
mRenderComponentEntityAdditional->setVisible(false);
}
}
bool GameObjectWoodBox::hasPositionalComponent() const
{
return true;
}
RenderComponentPositionalPtr GameObjectWoodBox::getPositionalComponent() const
{
return getRenderComponentPositional();
}
bool GameObjectWoodBox::hasPhysicsComponent() const
{
return true;
}
PhysicsComponentPtr GameObjectWoodBox::getPhysicsComponent() const
{
return mPhysicsComponentSimpleBox;
}
/// Set logic component
void GameObjectWoodBox::setLogicComponentBreakable(LogicComponentBreakablePtr logicComponentBreakable)
{
mLogicComponentBreakable=logicComponentBreakable;
}
/// return logic component
LogicComponentBreakablePtr GameObjectWoodBox::getLogicComponentBreakable()
{
return mLogicComponentBreakable;
}
void GameObjectWoodBox::processCollision(GameObjectPtr pGameObject, Ogre::Vector3 pNormal)
{
if (mLogicComponentBreakable.get())
{
mLogicComponentBreakable->processCollision(pGameObject, pNormal);
}
}
void GameObjectWoodBox::processEnterTrigger(GameObjectPtr pGameObject)
{
if (mLogicComponentBreakable.get())
{
mLogicComponentBreakable->processEnterTrigger(pGameObject);
}
}
void GameObjectWoodBox::processExitTrigger(GameObjectPtr pGameObject)
{
if (mLogicComponentBreakable.get())
{
mLogicComponentBreakable->processExitTrigger(pGameObject);
}
}
void GameObjectWoodBox::update(double elapsedSeconds)
{
GameObject::update(elapsedSeconds);
RenderComponentEntityPtr entityToUpdate = (mWorld==DREAMS)
? mRenderComponentEntityDreams
: mRenderComponentEntityNightmares;
if (mRenderComponentEntityAdditional->isVisible())
{
entityToUpdate=mRenderComponentEntityAdditional;
}
if (entityToUpdate.get())
{
entityToUpdate->update(elapsedSeconds);
}
}
void GameObjectWoodBox::releaseItem()
{
}
//TODO DO IT PROPERLY WHEN THERE ARE TWO RENDER COMPONENT ENTITIES
void GameObjectWoodBox::updateLogic(double elapsedSeconds)
{
if (mLogicComponentBreakable->isStateChanged())
{
if (mLogicComponentBreakable->getState()==STATE_BREAKABLE_BROKEN)
{
if (mPhysicsComponentSimpleBox->isInUse())
{
mPhysicsComponentSimpleBox->destroy();
releaseItem();
}
if (mLogicComponentBreakable->getIsBroken() && mLogicComponentBreakable->isStateChanged())
{
mRenderComponentEntityAdditional->setVisible(true);
mRenderComponentParticleSystemDust->start();
mAudioComponent->playSound("box_break");
if (!mRenderComponentEntityAdditional->hasAnimationBlender())
{
mRenderComponentEntityAdditional->initAnimationBlender("broken");
}
else
{
mRenderComponentEntityAdditional->changeAnimation("broken");
}
}
if (mLogicComponentBreakable->existsInDreams())
{
mRenderComponentEntityDreams->setVisible(false);
if (mRenderComponentEntityNightmares.get())
{
mRenderComponentEntityNightmares->setVisible(false);
}
}
if (mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityNightmares->setVisible(false);
if (mRenderComponentEntityDreams.get())
{
mRenderComponentEntityDreams->setVisible(false);
}
}
}
}
GameObject::updateLogic(elapsedSeconds);
}
bool GameObjectWoodBox::hasRenderComponentEntity() const
{
return true;
}
RenderComponentEntityPtr GameObjectWoodBox::getEntityComponent() const
{
return (mWorld==DREAMS)?mRenderComponentEntityDreams:mRenderComponentEntityNightmares;
}
void GameObjectWoodBox::updatePhysicsComponents(double elapsedSeconds)
{
GameObject::updatePhysicsComponents(elapsedSeconds);
}
RenderComponentEntityPtr GameObjectWoodBox::getRenderComponentEntityAdditional() const
{
return mRenderComponentEntityAdditional;
}
void GameObjectWoodBox::setRenderComponentEntityAdditional(RenderComponentEntityPtr pRenderComponentEntityAdditional)
{
mRenderComponentEntityAdditional=pRenderComponentEntityAdditional;
}
void GameObjectWoodBox::setVisible(bool visible)
{
if(!mLogicComponentBreakable->getState()==STATE_BREAKABLE_BROKEN)
{
switch(mWorld)
{
case DREAMS:
if(mLogicComponentBreakable->existsInDreams())
{
mRenderComponentEntityDreams->setVisible(visible);
}
break;
case NIGHTMARES:
if(mLogicComponentBreakable->existsInNightmares())
{
mRenderComponentEntityNightmares->setVisible(visible);
}
break;
default:
break;
}
}
}
bool GameObjectWoodBox::hasLogicComponent() const
{
return true;
}
LogicComponentPtr GameObjectWoodBox::getLogicComponent() const
{
return mLogicComponentBreakable;
}
void GameObjectWoodBox::processAnimationEnded(const std::string& animationName)
{
if (animationName.compare("broken")==0)
{
mRenderComponentEntityAdditional->setVisible(false);
disable();
}
}
//-------------------------------------------------------------------------------------------
TGameObjectWoodBoxParameters::TGameObjectWoodBoxParameters() : TGameObjectParameters()
{
}
TGameObjectWoodBoxParameters::~TGameObjectWoodBoxParameters()
{
} | [
"ithiliel@1610d384-d83c-11de-a027-019ae363d039",
"juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039",
"wyern1@1610d384-d83c-11de-a027-019ae363d039"
]
| [
[
[
1,
2
],
[
283,
283
],
[
285,
285
],
[
287,
287
],
[
289,
289
],
[
298,
298
],
[
300,
300
],
[
321,
321
],
[
368,
373
],
[
375,
375
],
[
396,
398
],
[
402,
402
],
[
404,
404
],
[
406,
406
],
[
408,
408
],
[
410,
411
],
[
418,
418
],
[
424,
425
],
[
427,
427
],
[
433,
433
],
[
445,
449
],
[
451,
454
],
[
456,
459
],
[
485,
488
],
[
491,
501
]
],
[
[
3,
7
],
[
9,
47
],
[
58,
92
],
[
183,
183
],
[
198,
198
],
[
201,
201
],
[
206,
206
],
[
208,
208
],
[
213,
213
],
[
215,
215
],
[
224,
224
],
[
229,
229
],
[
231,
231
],
[
236,
236
],
[
238,
238
],
[
246,
248
],
[
280,
282
],
[
284,
284
],
[
286,
286
],
[
288,
288
],
[
290,
291
],
[
296,
297
],
[
299,
299
],
[
301,
320
],
[
322,
363
],
[
365,
367
],
[
374,
374
],
[
376,
378
],
[
384,
393
],
[
395,
395
],
[
399,
399
],
[
401,
401
],
[
403,
403
],
[
405,
405
],
[
407,
407
],
[
409,
409
],
[
412,
417
],
[
419,
423
],
[
426,
426
],
[
428,
432
],
[
434,
442
],
[
444,
444
],
[
450,
450
],
[
455,
455
],
[
484,
484
],
[
489,
489
],
[
502,
512
]
],
[
[
8,
8
],
[
48,
57
],
[
93,
182
],
[
184,
197
],
[
199,
200
],
[
202,
205
],
[
207,
207
],
[
209,
212
],
[
214,
214
],
[
216,
223
],
[
225,
228
],
[
230,
230
],
[
232,
235
],
[
237,
237
],
[
239,
245
],
[
249,
279
],
[
292,
295
],
[
364,
364
],
[
379,
383
],
[
394,
394
],
[
400,
400
],
[
443,
443
],
[
460,
483
],
[
490,
490
]
]
]
|
69a4d9774e8b0507951a44ddf6274af86dd0d9f1 | a51ac532423cf58c35682415c81aee8e8ae706ce | /Settings/Settings.cpp | 9d1cb6199c3bba1bae92716d1c50e685c6eb2e87 | []
| no_license | anderslindmark/PickNPlace | b9a89fb2a6df839b2b010b35a0c873af436a1ab9 | 00ca4f6ce2ecfeddfea7db5cb7ae8e9d0023a5e1 | refs/heads/master | 2020-12-24T16:59:20.515351 | 2008-05-25T01:32:31 | 2008-05-25T01:32:31 | 34,914,321 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,390 | cpp | #include "Settings.h"
#include <qdom.h>
#include <QFile>
#include <iostream>
using namespace std;
namespace PicknPlaceGui
{
Settings::Settings(QString file) : m_file(file)
{
m_intEntry = NULL;
m_skip = false;
}
Settings::~Settings(void)
{
}
bool Settings::Read()
{
bool returnVal;
QFile file(m_file);
QXmlInputSource src(&file);
QXmlSimpleReader xmlReader;
xmlReader.setFeature( "http://xml.org/sax/features/namespaces",
true );
xmlReader.setFeature( "http://xml.org/sax/features/namespace-prefixes",
true );
xmlReader.setContentHandler(this);
xmlReader.setErrorHandler(this);
returnVal = xmlReader.parse(&src);
return returnVal;
}
PickStateStruct Settings::GetPNPSettings()
{
return m_pickSettings;
}
void Settings::SetPNPSettings(PickStateStruct pnp)
{
m_pickSettings = pnp;
}
DispenceStateStruct Settings::GetDispenceSettings()
{
return m_dispenceSettings;
}
void Settings::SetDispenceSettings(DispenceStateStruct dis)
{
m_dispenceSettings = dis;
}
void Settings::SetFile(QString file)
{
m_file = file;
}
bool Settings::Save()
{
QString value;
QDomDocument doc;
// create root
QDomElement root = doc.createElement( "settings" );
doc.appendChild( root );
QDomElement mc = doc.createElement( "machinecontroller" );
root.appendChild(mc);
// create pickandplace
QDomElement pnp = doc.createElement("pnp:pickandplace");
mc.appendChild( pnp );
QDomElement e = doc.createElement("pnp:offsetX");
pnp.appendChild(e);
QDomText t = doc.createTextNode(QString::number(m_pickSettings.offsetX));
e.appendChild( t );
e = doc.createElement("pnp:offsetY");
pnp.appendChild(e);
t = doc.createTextNode(QString::number(m_pickSettings.offsetY));
e.appendChild( t );
e = doc.createElement("pnp:headHeight");
pnp.appendChild(e);
t = doc.createTextNode(QString::number(m_pickSettings.headHeight));
e.appendChild( t );
e = doc.createElement("pnp:pickHeight");
pnp.appendChild(e);
t = doc.createTextNode(QString::number(m_pickSettings.pickHeight));
e.appendChild( t );
e = doc.createElement("pnp:placeHeight");
pnp.appendChild(e);
t = doc.createTextNode(QString::number(m_pickSettings.placeHeight));
e.appendChild( t );
e = doc.createElement("pnp:afterPickTime");
pnp.appendChild(e);
t = doc.createTextNode(QString::number(m_pickSettings.afterPickTime));
e.appendChild( t );
e = doc.createElement("pnp:pickPressDownTime");
pnp.appendChild(e);
t = doc.createTextNode(QString::number(m_pickSettings.pickPressDownTime));
e.appendChild( t );
e = doc.createElement("pnp:placePressDownTime");
pnp.appendChild(e);
t = doc.createTextNode(QString::number(m_pickSettings.placePressDownTime));
e.appendChild( t );
e = doc.createElement("pnp:afterPlaceTime");
pnp.appendChild(e);
t = doc.createTextNode(QString::number(m_pickSettings.afterPlaceTime));
e.appendChild( t );
// create dispence settings
QDomElement dis = doc.createElement("d:dispence");
mc.appendChild( dis );
e = doc.createElement("d:offsetX");
dis.appendChild(e);
t = doc.createTextNode(QString::number(m_dispenceSettings.offsetY));
e.appendChild( t );
e = doc.createElement("d:offsetY");
dis.appendChild(e);
t = doc.createTextNode(QString::number(m_dispenceSettings.offsetX));
e.appendChild( t );
e = doc.createElement("d:offsetZ");
dis.appendChild(e);
t = doc.createTextNode(QString::number(m_dispenceSettings.offsetZ));
e.appendChild( t );
e = doc.createElement("d:offsetZs");
dis.appendChild(e);
t = doc.createTextNode(QString::number(m_dispenceSettings.offsetZs));
e.appendChild( t );
e = doc.createElement("d:offsetTurn");
dis.appendChild(e);
t = doc.createTextNode(QString::number(m_dispenceSettings.offsetTurn));
e.appendChild( t );
e = doc.createElement("d:speed");
dis.appendChild(e);
t = doc.createTextNode(QString::number(m_dispenceSettings.speed));
e.appendChild( t );
e = doc.createElement("d:beforeTime");
dis.appendChild(e);
t = doc.createTextNode(QString::number(m_dispenceSettings.beforeTime));
e.appendChild( t );
e = doc.createElement("d:afterTime");
dis.appendChild(e);
t = doc.createTextNode(QString::number(m_dispenceSettings.afterTime));
e.appendChild( t );
e = doc.createElement("d:suckBackTime");
dis.appendChild(e);
t = doc.createTextNode(QString::number(m_dispenceSettings.suckBackTime));
e.appendChild( t );
// save information to file
QString xml = doc.toString();
QFile file(m_file);
file.open(QIODevice::WriteOnly);
file.write(xml.toStdString().c_str(), xml.length());
file.close();
return true;
}
//READER FUNCTIONS
bool Settings::characters ( const QString & ch )
{
bool ok = true;
if (!m_skip)
{
ok = false;
switch (m_type) {
case XMLDATA_INT: *m_intEntry = ch.toInt(&ok);
break;
default:
break;
}
m_skip = true;
}
if (!ok)
{
this->error(QXmlParseException(QString("Error when parsing an value!")));
return false;
}
//cout << "IN CHARACTERS" << endl;
//cout << ch.toStdString() << endl;
return true;
}
bool Settings::startElement ( const QString & namespaceURI, const QString & localName, const QString & qName, const QXmlAttributes & atts )
{
m_skip = false;
//PICK AND PLACE SETTINGS
if (qName == "pnp:offsetX")
{
m_type = XMLDATA_INT;
m_intEntry = &m_pickSettings.offsetX;
}
else if (qName == "pnp:offsetY")
{
m_type = XMLDATA_INT;
m_intEntry = &m_pickSettings.offsetY;
}
else if (qName == "pnp:headHeight")
{
m_type = XMLDATA_INT;
m_intEntry = &m_pickSettings.headHeight;
}
else if (qName == "pnp:pickHeight")
{
m_type = XMLDATA_INT;
m_intEntry = &m_pickSettings.pickHeight;
}
else if (qName == "pnp:placeHeight")
{
m_type = XMLDATA_INT;
m_intEntry = &m_pickSettings.placeHeight;
}
else if (qName == "pnp:afterPickTime")
{
m_type = XMLDATA_INT;
m_intEntry = &m_pickSettings.afterPickTime;
}
else if (qName == "pnp:pickPressDownTime")
{
m_type = XMLDATA_INT;
m_intEntry = &m_pickSettings.pickPressDownTime;
}
else if (qName == "pnp:placePressDownTime")
{
m_type = XMLDATA_INT;
m_intEntry = &m_pickSettings.placePressDownTime;
}
else if (qName == "pnp:afterPlaceTime")
{
m_type = XMLDATA_INT;
m_intEntry = &m_pickSettings.afterPlaceTime;
}
// DISPENCE SETTINGS
else if (qName == "d:offsetX")
{
m_type = XMLDATA_INT;
m_intEntry = &m_dispenceSettings.offsetX;
}
else if (qName == "d:offsetY")
{
m_type = XMLDATA_INT;
m_intEntry = &m_dispenceSettings.offsetY;
}
else if (qName == "d:offsetZ")
{
m_type = XMLDATA_INT;
m_intEntry = &m_dispenceSettings.offsetZ;
}
else if (qName == "d:offsetZs")
{
m_type = XMLDATA_INT;
m_intEntry = &m_dispenceSettings.offsetZs;
}
else if (qName == "d:offsetTurn")
{
m_type = XMLDATA_INT;
m_intEntry = &m_dispenceSettings.offsetTurn;
}
else if (qName == "d:speed")
{
m_type = XMLDATA_INT;
m_intEntry = &m_dispenceSettings.speed;
}
else if (qName == "d:beforeTime")
{
m_type = XMLDATA_INT;
m_intEntry = &m_dispenceSettings.beforeTime;
}
else if (qName == "d:afterTime")
{
m_type = XMLDATA_INT;
m_intEntry = &m_dispenceSettings.afterTime;
}
else if (qName == "d:suckBackTime")
{
m_type = XMLDATA_INT;
m_intEntry = &m_dispenceSettings.suckBackTime;
}
else
{
m_skip = true;
}
//cout << "IN startElement" << endl;
//cout << "NAMESPACE : \"" << namespaceURI.toStdString() <<"\""<< endl;
//cout << "LOCALNAME : " << localName.toStdString() << endl;
//cout << "QNAME : \"" << qName.toStdString() << "\""<<endl;
//cout << "QXMLATTRIBUTES : " << atts.count() << endl;
return true;
}
bool Settings::endElement ( const QString & namespaceURI, const QString & localName, const QString & qName )
{
//cout << "IN endElement" << endl;
return true;
}
} | [
"henmak-4@f672c3ff-8b41-4f22-a4ab-2adcb4f732c7"
]
| [
[
[
1,
298
]
]
]
|
082216944d8a5fe43ae6c8fba09ac86a7366f0ff | 6477cf9ac119fe17d2c410ff3d8da60656179e3b | /Projects/openredalert/src/game/InfantryGroup.cpp | 7ad22d8a3f6d08dc0eef68cc5eadf34a08b9ec10 | []
| no_license | crutchwalkfactory/motocakerteam | 1cce9f850d2c84faebfc87d0adbfdd23472d9f08 | 0747624a575fb41db53506379692973e5998f8fe | refs/heads/master | 2021-01-10T12:41:59.321840 | 2010-12-13T18:19:27 | 2010-12-13T18:19:27 | 46,494,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,925 | cpp | // InfantryGroup.cpp
// 1.0
// This file is part of OpenRedAlert.
//
// OpenRedAlert 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, version 2 of the License.
//
// OpenRedAlert 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 OpenRedAlert. If not, see <http://www.gnu.org/licenses/>.
#include "InfantryGroup.h"
#include <cstdlib>
#include <cstring>
#include <string>
#include <math.h>
#include "SDL/SDL_timer.h"
#include "CnCMap.h"
#include "weaponspool.h"
#include "misc/INIFile.h"
#include "include/Logger.h"
#include "PlayerPool.h"
#include "audio/SoundEngine.h"
#include "UnitAndStructurePool.h"
#include "Unit.h"
using std::string;
using std::vector;
InfantryGroup::InfantryGroup()
{
//logger->debug("Setting up infgroup %p\n", this);
for (int i=0;i<5;i++){
positions[i] = NULL;
}
numinfantry = 0;
}
InfantryGroup::~InfantryGroup()
{
//logger->debug("Destructing infgroup %p\n", this);
// printf ("%s line %i: Destroying infgroup\n", __FILE__, __LINE__);
}
const Sint8 InfantryGroup::unitoffsets[10] = {
// Theses values have been heavily tested, do NOT change them unless you're
// _really_ sure of what you are doing
// X value
-13, -19, -7, -19, -7,
// Y value
-3, -7, -7, 1, 1
};
bool InfantryGroup::AddInfantry(Unit* inf, Uint8 subpos)
{
assert(subpos < 5);
assert(numinfantry < 5);
positions[subpos] = inf;
++numinfantry;
return true;
}
bool InfantryGroup::RemoveInfantry(Uint8 subpos)
{
assert(subpos < 5);
assert(numinfantry > 0);
positions[subpos] = NULL;
--numinfantry;
return true;
}
bool InfantryGroup::IsClear(Uint8 subpos)
{
assert(subpos < 5);
return (positions[subpos] == NULL);
}
Uint8 InfantryGroup::GetNumInfantry() const
{
return numinfantry;
}
bool InfantryGroup::IsAvailable() const
{
return (numinfantry < 5);
}
Uint8 InfantryGroup::GetFreePos() const
{
for (int i = 0; i < 5; ++i) {
if (0 == positions[i]) {
return i;
}
}
return (Uint8)-1;
}
Unit* InfantryGroup::UnitAt(Uint8 subpos)
{
assert(subpos < 5);
return positions[subpos];
}
Uint8 InfantryGroup::GetImageNums(Uint32** inums, Sint8** xoffsets, Sint8** yoffsets)
{
(*inums) = new Uint32[numinfantry];
(*xoffsets) = new Sint8[numinfantry];
(*yoffsets) = new Sint8[numinfantry];
int j = 0;
for (int i = 0; i < 5; ++i) {
if (0 != positions[i]) {
(*inums)[j]=positions[i]->getImageNum(0);
(*xoffsets)[j]=positions[i]->getXoffset()+unitoffsets[i];
(*yoffsets)[j]=positions[i]->getYoffset()+unitoffsets[i+5];
//printf ("%s line %i: pos = %i, offset = %i\n", __FILE__, __LINE__, positions[i]->getXoffset(), unitoffsets[i+5]);
j++;
}
}
return numinfantry;
}
void InfantryGroup::GetSubposOffsets(Uint8 oldsp, Uint8 newsp, Sint8* xoffs, Sint8* yoffs)
{
*xoffs = unitoffsets[oldsp] - unitoffsets[newsp];
*yoffs = unitoffsets[oldsp+5] - unitoffsets[newsp+5];
}
const Sint8* InfantryGroup::GetUnitOffsets()
{
return unitoffsets;
}
Unit * InfantryGroup::GetNearest(Uint8 subpos)
{
static const Uint8 lut[20] = {
1,2,3,4,
3,0,2,4,
1,0,4,3,
1,0,4,2,
3,0,2,1
};
Uint8 x;
// The compiler will optimise this nicely with -funroll-loops,
// leaving it like this to keep it readable.
for (x = 0; x < 4; ++x)
if (0 != positions[lut[x + subpos * 4]]) return positions[lut[x + subpos * 4]];
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
158
]
]
]
|
27958a8767a1570a4c19d6a397e8d38a98c4f0c6 | 3ec03fa7bb038ea10801d09a685b9561f827928b | /js_xdeploy/progressdlg.cpp | 0fdc1c75f0bbe5eddba8c7a5233083381b182d80 | []
| no_license | jbreams/njord | e2354f2013af0d86390ae7af99a419816ee417cb | ef7ff45fa4882fe8d2c6cabfa7691e2243fe8341 | refs/heads/master | 2021-01-24T17:56:32.048502 | 2009-12-15T18:57:32 | 2009-12-15T18:57:32 | 38,331,688 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,838 | cpp | #include "stdafx.h"
#include <commctrl.h>
#include "resource.h"
#pragma comment(lib, "comctl32.lib")
void finalizeUI(JSContext * cx, JSObject * uiObj)
{
HWND myWnd = (HWND)JS_GetPrivate(cx, uiObj);
if(myWnd != NULL)
SendMessage(myWnd, WM_DESTROY, 0, 0);
}
JSClass xDriverUI = { "xDriverUI", /* name */
JSCLASS_HAS_PRIVATE, /* flags */
JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, finalizeUI,
JSCLASS_NO_OPTIONAL_MEMBERS
};
JSObject * xDriverUIProto = NULL;
extern HMODULE myModule;
BOOL xDriver_DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_INITDIALOG:
return 1;
case WM_DESTROY:
PostQuitMessage(0);
}
return 0;
}
DWORD xDriverUIThread(LPVOID param)
{
HWND * myWindow = (HWND*)param;
INITCOMMONCONTROLSEX icce;
icce.dwSize = sizeof(icce);
icce.dwICC = ICC_PROGRESS_CLASS;
BOOL ok = InitCommonControlsEx(&icce);
if(!ok)
{
MessageBox(NULL, TEXT("Error initialzing common controls. Cannot continue."), TEXT("xDriver"), MB_OK);
return 1;
}
*myWindow = CreateDialogW(myModule, MAKEINTRESOURCE(IDD_DIALOG), NULL, (DLGPROC)xDriver_DlgProc);
if(*myWindow == NULL)
{
MessageBox(NULL, TEXT("Error creating window. Cannot continue."), TEXT("xDriver"), MB_OK);
return 1;
}
DWORD errorCode = GetLastError();
ShowWindow(*myWindow, SW_SHOW);
MSG msg;
while(GetMessage(&msg, NULL, 0, 0))
{
if(!IsDialogMessage(*myWindow, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
JSBool create_ui(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
{
HWND myWnd = NULL;
HANDLE uiThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)xDriverUIThread, &myWnd, 0, NULL);
CloseHandle(uiThread);
while(myWnd == NULL)
Sleep(5);
JS_BeginRequest(cx);
JSObject * retObj = JS_NewObject(cx, &xDriverUI, xDriverUIProto, obj);
*rval = OBJECT_TO_JSVAL(retObj);
JS_SetPrivate(cx, retObj, myWnd);
JS_EndRequest(cx);
return JS_TRUE;
}
JSBool set_static_text(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
{
LPWSTR message;
JS_BeginRequest(cx);
if(!JS_ConvertArguments(cx, argc, argv, "W", &message))
{
JS_ReportError(cx, "Error parsing arguments in SetStaticText");
JS_EndRequest(cx);
return JS_FALSE;
}
JS_EndRequest(cx);
HWND myWnd = (HWND)JS_GetPrivate(cx, obj);
SetDlgItemText(myWnd, IDC_STATICTEXT, message);
return JS_TRUE;
}
JSBool set_progress(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
{
WORD pos;
BOOL max = FALSE;
JS_BeginRequest(cx);
JS_ConvertArguments(cx, argc, argv, "c /b", &pos, &max);
JS_EndRequest(cx);
HWND myWnd = (HWND)JS_GetPrivate(cx, obj);
if(max)
SendDlgItemMessage(myWnd, IDC_PROGRESS, PBM_SETRANGE, 0, MAKELPARAM(0, pos));
else
SendDlgItemMessage(myWnd, IDC_PROGRESS, PBM_SETPOS, pos, 0);
return JS_TRUE;
}
JSBool show_or_hide(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval)
{
int cmd = SW_SHOW;
JS_BeginRequest(cx);
if(argc > 0 && JSVAL_IS_BOOLEAN(*argv) && !JSVAL_TO_BOOLEAN(*argv))
cmd = SW_HIDE;
HWND myWnd = (HWND)JS_GetPrivate(cx, obj);
*rval = ShowWindow(myWnd, cmd) ? JSVAL_TRUE : JSVAL_FALSE;
JS_EndRequest(cx);
return JS_TRUE;
}
void InitProgressDlg(JSContext * cx, JSObject * obj)
{
JSFunctionSpec ui_funcs[] = {
{ "SetStaticText", set_static_text, 1, 0, 0 },
{ "SetProgress", set_progress, 2, 0, 0 },
{ "Show", show_or_hide, 1, 0, 0 },
{ 0 }
};
xDriverUIProto = JS_InitClass(cx, obj, NULL, &xDriverUI, NULL, 0, NULL, ui_funcs, NULL, NULL);
JS_DefineFunction(cx, obj, "CreateProgressDlg", (JSNative)create_ui, 0, 0);
} | [
"jbreams@1c42f586-7543-11de-ba67-499d525147dd"
]
| [
[
[
1,
139
]
]
]
|
cebd6c81672fe3e8073debe927037f52a46b815b | 74e7667ad65cbdaa869c6e384fdd8dc7e94aca34 | /MicroFrameworkPK_v4_1/BuildOutput/public/Release/Client/stubs/spot_graphics_native_Microsoft_SPOT_Font.h | 452cc4b390a070180c02b6f8fb6a3f70b54350af | [
"BSD-3-Clause",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | gezidan/NETMF-LPC | 5093ab223eb9d7f42396344ea316cbe50a2f784b | db1880a03108db6c7f611e6de6dbc45ce9b9adce | refs/heads/master | 2021-01-18T10:59:42.467549 | 2011-06-28T08:11:24 | 2011-06-28T08:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,172 | h | //-----------------------------------------------------------------------------
//
// ** WARNING! **
// This file was generated automatically by a tool.
// Re-running the tool will overwrite this file.
// You should copy this file to a custom location
// before adding any customization in the copy to
// prevent loss of your changes when the tool is
// re-run.
//
//-----------------------------------------------------------------------------
#ifndef _SPOT_GRAPHICS_NATIVE_MICROSOFT_SPOT_FONT_H_
#define _SPOT_GRAPHICS_NATIVE_MICROSOFT_SPOT_FONT_H_
namespace Microsoft
{
namespace SPOT
{
struct Font
{
// Helper Functions to access fields of managed object
static UNSUPPORTED_TYPE& Get_m_font( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_UNSUPPORTED_TYPE( pMngObj, Library_spot_graphics_native_Microsoft_SPOT_Font::FIELD__m_font ); }
// Declaration of stubs. These functions are implemented by Interop code developers
static INT32 CharWidth( CLR_RT_HeapBlock* pMngObj, CHAR param0, HRESULT &hr );
static INT32 get_Height( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT32 get_AverageWidth( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT32 get_MaxWidth( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT32 get_Ascent( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT32 get_Descent( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT32 get_InternalLeading( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT32 get_ExternalLeading( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static void ComputeExtent( CLR_RT_HeapBlock* pMngObj, LPCSTR param0, INT32 * param1, INT32 * param2, INT32 param3, HRESULT &hr );
static void ComputeTextInRect( CLR_RT_HeapBlock* pMngObj, LPCSTR param0, INT32 * param1, INT32 * param2, INT32 param3, INT32 param4, INT32 param5, INT32 param6, UINT32 param7, HRESULT &hr );
};
}
}
#endif //_SPOT_GRAPHICS_NATIVE_MICROSOFT_SPOT_FONT_H_
| [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
3e04e8f8a25645b6d530abe70fe0d8fccdac70c4 | 97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a | /3dc/avp/missions.hpp | 24dbe245ae9da990435ac19f3e72c007e80529cf | [
"LicenseRef-scancode-warranty-disclaimer"
]
| no_license | SR-dude/AvP-Wine | 2875f7fd6b7914d03d7f58e8f0ec4793f971ad23 | 41a9c69a45aacc2c345570ba0e37ec3dc89f4efa | refs/heads/master | 2021-01-23T02:54:33.593334 | 2011-09-17T11:10:07 | 2011-09-17T11:10:07 | 2,375,686 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,609 | hpp | /*
missions.hpp
*/
#ifndef _missions
#define _missions 1
#if ( defined( __WATCOMC__ ) || defined( _MSC_VER ) )
#pragma once
#endif
#ifndef _scstring
#include "scstring.hpp"
#endif
#ifndef _langenum_h_
#include "langenum.h"
#endif
#ifndef _strtab
#include "strtab.hpp"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Version settings *****************************************************/
#define WithinTheGame Yes
// as opposed to within the editor
/* Constants ***********************************************************/
/* Macros ***************************************************************/
/* Type definitions *****************************************************/
// Enum for what can happen when a mission event is triggered; these
// effects are "meta-events" e.g. the levels is completed. These are
// post-processing after the rest of the mission event processing occurs.
enum MissionEffects
{
MissionFX_None = 0,
MissionFX_UncoversNext,
MissionFX_CompletesLevel,
// Possibility of:
// MissionFX_CompletesLevelSpecial
// which takes you to a hidden level for power-ups?
MissionFX_FailsLevel,
NUM_MISSION_EFFECTS
}; // suggested naming: MissionFX
enum MissionObjectiveState
{
MOS_JustAHint = 0,
MOS_HiddenUnachieved,
MOS_HiddenUnachievedNotPossible,
MOS_VisibleUnachieved,
MOS_VisibleUnachievedNotPossible,
MOS_VisibleAndAchieved,
NUM_MOS
};
class MissionHint
{
// Friends
// Public methods:
public:
MissionHint
(
enum TEXTSTRING_ID I_TextString_Description,
OurBool bVisible_New
);
virtual ~MissionHint();
SCString* GetDesc(void) const;
OurBool bVisible(void) const;
void SetVisibility
(
OurBool bVisible_New
);
static const List<MissionHint*>& GetAll(void);
// Protected methods:
protected:
// Private methods:
private:
// Private data:
private:
enum TEXTSTRING_ID I_TextString_Description_Val;
OurBool bVisible_Val;
static List<MissionHint*> List_pMissionHint;
};
// Inline methods:
inline SCString* MissionHint::GetDesc(void) const
{
return &StringTable :: GetSCString
(
I_TextString_Description_Val
);
}
inline OurBool MissionHint::bVisible(void) const
{
return bVisible_Val;
}
inline void MissionHint::SetVisibility
(
OurBool bVisible_New
)
{
bVisible_Val = bVisible_New;
}
inline /*static*/ const List<MissionHint*>& MissionHint::GetAll(void)
{
return List_pMissionHint;
}
#if 0
class MissionEvent
{
public:
virtual void OnTriggering(void) = 0;
virtual ~MissionEvent();
protected:
MissionEvent
(
enum TEXTSTRING_ID I_TextString_TriggeringFeedback,
enum MissionEffects MissionFX
);
protected:
enum MissionEffects MissionFX_Val;
private:
enum TEXTSTRING_ID I_TextString_TriggeringFeedback_Val;
static List<MissionEvent*> List_pMissionEvent;
};
#endif
class MissionObjective;
#define MissionAlteration_MakeVisible 0x00000001
#define MissionAlteration_MakePossible 0x00000002
//when a mission is achieved it can alter the visibility and doability of other mission objectives
struct MissionAlteration
{
MissionObjective* mission_objective;
int alteration_to_mission;
};
class MissionObjective
{
public:
void OnTriggering(void);
MissionObjective
(
enum TEXTSTRING_ID I_TextString_Description,
enum MissionObjectiveState MOS,
enum TEXTSTRING_ID I_TextString_TriggeringFeedback,
enum MissionEffects MissionFX
);
~MissionObjective();
static void TestCompleteNext(void);
int bAchieved(void) const;
void AddMissionAlteration(MissionObjective* mission_objective,int alteration_to_mission);
void MakeVisible();
void MakePossible();
void ResetMission(); //restores objective to start of level state
MissionObjectiveState GetMOS() {return MOS_Val;};
void SetMOS_Public(MissionObjectiveState MOS_New) {SetMOS(MOS_New);} ;
private:
void SetMOS( MissionObjectiveState MOS_New );
private:
#if WithinTheGame
MissionHint aMissionHint_Incomplete;
MissionHint aMissionHint_Complete;
#endif
enum TEXTSTRING_ID I_TextString_Description_Val;
enum TEXTSTRING_ID I_TextString_TriggeringFeedback_Val;
enum MissionEffects MissionFX_Val;
enum MissionObjectiveState MOS_Val;
enum MissionObjectiveState initial_MOS_Val;
static List<MissionObjective*> List_pMissionObjective;
List<MissionAlteration*> List_pMissionAlteration;
public:
int bAchievable(void) const
{
return ( MOS_Val != MOS_HiddenUnachievedNotPossible &&
MOS_Val != MOS_VisibleUnachievedNotPossible);
}
private:
static int bVisible
(
enum MissionObjectiveState MOS_In
)
{
return ( MOS_In != MOS_HiddenUnachieved &&
MOS_In != MOS_HiddenUnachievedNotPossible);
}
static int bComplete
(
enum MissionObjectiveState MOS_In
)
{
return ( MOS_In == MOS_VisibleAndAchieved );
}
};
inline int MissionObjective::bAchieved(void) const
{
return bComplete( MOS_Val );
}
/* Exported globals *****************************************************/
/* Function prototypes **************************************************/
namespace MissionHacks
{
void TestInit(void);
};
/* End of the header ****************************************************/
#ifdef __cplusplus
};
#endif
#endif
| [
"a_jagers@ANTHONYJ.(none)"
]
| [
[
[
1,
272
]
]
]
|
da71a7d7c4d13cd93085f78a991c7601b7bc3626 | 215fd760efb591ab13e10c421686fef079d826e1 | /lib/p4api/include/p4/msgclient.h | 5e3e513ba00d2323a738e448ee3d20f0a4b46085 | []
| no_license | jairbubbles/P4.net | 2021bc884b9940f78e94b950e22c0c4e9ce8edca | 58bbe79b30593134a9306e3e37b0b1aab8135ed0 | refs/heads/master | 2020-12-02T16:21:15.361000 | 2011-02-15T19:28:31 | 2011-02-15T19:28:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,235 | h | /*
* Copyright 1995, 2000 Perforce Software. All rights reserved.
*
* This file is part of Perforce - the FAST SCM System.
*/
/*
* msgclient.h - definitions of errors for client subsystem.
*/
class MsgClient {
public:
static ErrorId Connect;
static ErrorId ZCResolve;
static ErrorId BadFlag;
static ErrorId Fatal;
static ErrorId ClobberFile;
static ErrorId MkDir;
static ErrorId Eof;
static ErrorId CantEdit;
static ErrorId NoMerger;
static ErrorId ToolServer2;
static ErrorId ToolServer;
static ErrorId ToolCmdCreate;
static ErrorId ToolCmdSend;
static ErrorId Memory;
static ErrorId CantFindApp;
static ErrorId BadSignature;
static ErrorId BadMarshalInput;
static ErrorId ResolveManually;
static ErrorId NonTextFileMerge;
static ErrorId MergeMsg2;
static ErrorId MergeMsg3;
static ErrorId MergeMsg32;
static ErrorId MergePrompt;
static ErrorId MergePrompt2;
static ErrorId MergePrompt2Edit;
static ErrorId ConfirmMarkers;
static ErrorId ConfirmEdit;
static ErrorId Confirm;
static ErrorId CheckFileAssume;
static ErrorId CheckFileSubst;
static ErrorId CheckFileCant;
static ErrorId FileExists;
static ErrorId NoSuchFile;
} ;
| [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
5e77eda6cb0e27e4ce1c845358d41cc977feccd8 | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/plugins/GSdx/GSCapture.cpp | 24cdbcc4d4341109cf38f0e83338b56d5b6bd6c9 | []
| no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,266 | cpp | /*
* Copyright (C) 2007-2009 Gabest
* http://www.gabest.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "StdAfx.h"
#include "GSCapture.h"
#include "GSVector.h"
//
// GSSource
//
#ifdef __INTEL_COMPILER
interface __declspec(uuid("59C193BB-C520-41F3-BC1D-E245B80A86FA"))
#else
[uuid("59C193BB-C520-41F3-BC1D-E245B80A86FA")] interface
#endif
IGSSource : public IUnknown
{
STDMETHOD(DeliverNewSegment)() PURE;
STDMETHOD(DeliverFrame)(const void* bits, int pitch, bool rgba) PURE;
STDMETHOD(DeliverEOS)() PURE;
};
#ifdef __INTEL_COMPILER
class __declspec(uuid("F8BB6F4F-0965-4ED4-BA74-C6A01E6E6C77"))
#else
[uuid("F8BB6F4F-0965-4ED4-BA74-C6A01E6E6C77")] class
#endif
GSSource : public CBaseFilter, private CCritSec, public IGSSource
{
GSVector2i m_size;
REFERENCE_TIME m_atpf;
REFERENCE_TIME m_now;
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
return
riid == __uuidof(IGSSource) ? GetInterface((IGSSource*)this, ppv) :
__super::NonDelegatingQueryInterface(riid, ppv);
}
class GSSourceOutputPin : public CBaseOutputPin
{
GSVector2i m_size;
vector<CMediaType> m_mts;
public:
GSSourceOutputPin(const GSVector2i& size, REFERENCE_TIME atpf, CBaseFilter* pFilter, CCritSec* pLock, HRESULT& hr)
: CBaseOutputPin("GSSourceOutputPin", pFilter, pLock, &hr, L"Output")
, m_size(size)
{
CMediaType mt;
mt.majortype = MEDIATYPE_Video;
mt.formattype = FORMAT_VideoInfo;
VIDEOINFOHEADER vih;
memset(&vih, 0, sizeof(vih));
vih.AvgTimePerFrame = atpf;
vih.bmiHeader.biSize = sizeof(vih.bmiHeader);
vih.bmiHeader.biWidth = m_size.x;
vih.bmiHeader.biHeight = m_size.y;
// YUY2
mt.subtype = MEDIASUBTYPE_YUY2;
mt.lSampleSize = m_size.x * m_size.y * 2;
vih.bmiHeader.biCompression = '2YUY';
vih.bmiHeader.biPlanes = 1;
vih.bmiHeader.biBitCount = 16;
vih.bmiHeader.biSizeImage = m_size.x * m_size.y * 2;
mt.SetFormat((uint8*)&vih, sizeof(vih));
m_mts.push_back(mt);
// RGB32
mt.subtype = MEDIASUBTYPE_RGB32;
mt.lSampleSize = m_size.x * m_size.y * 4;
vih.bmiHeader.biCompression = BI_RGB;
vih.bmiHeader.biPlanes = 1;
vih.bmiHeader.biBitCount = 32;
vih.bmiHeader.biSizeImage = m_size.x * m_size.y * 4;
mt.SetFormat((uint8*)&vih, sizeof(vih));
m_mts.push_back(mt);
}
HRESULT GSSourceOutputPin::DecideBufferSize(IMemAllocator* pAlloc, ALLOCATOR_PROPERTIES* pProperties)
{
ASSERT(pAlloc && pProperties);
HRESULT hr;
pProperties->cBuffers = 1;
pProperties->cbBuffer = m_mt.lSampleSize;
ALLOCATOR_PROPERTIES Actual;
if(FAILED(hr = pAlloc->SetProperties(pProperties, &Actual)))
{
return hr;
}
if(Actual.cbBuffer < pProperties->cbBuffer)
{
return E_FAIL;
}
ASSERT(Actual.cBuffers == pProperties->cBuffers);
return S_OK;
}
HRESULT CheckMediaType(const CMediaType* pmt)
{
for(vector<CMediaType>::iterator i = m_mts.begin(); i != m_mts.end(); i++)
{
if(i->majortype == pmt->majortype && i->subtype == pmt->subtype)
{
return S_OK;
}
}
return E_FAIL;
}
HRESULT GetMediaType(int i, CMediaType* pmt)
{
CheckPointer(pmt, E_POINTER);
if(i < 0) return E_INVALIDARG;
if(i > 1) return VFW_S_NO_MORE_ITEMS;
*pmt = m_mts[i];
return S_OK;
}
STDMETHODIMP Notify(IBaseFilter* pSender, Quality q)
{
return E_NOTIMPL;
}
const CMediaType& CurrentMediaType()
{
return m_mt;
}
};
GSSourceOutputPin* m_output;
public:
GSSource(int w, int h, int fps, IUnknown* pUnk, HRESULT& hr)
: CBaseFilter(NAME("GSSource"), pUnk, this, __uuidof(this), &hr)
, m_output(NULL)
, m_size(w, h)
, m_atpf(10000000i64 / fps)
, m_now(0)
{
m_output = new GSSourceOutputPin(m_size, m_atpf, this, this, hr);
// FIXME
if(fps == 60) m_atpf = 166834; // = 10000000i64 / 59.94
}
virtual ~GSSource()
{
delete m_output;
}
DECLARE_IUNKNOWN;
int GetPinCount()
{
return 1;
}
CBasePin* GetPin(int n)
{
return n == 0 ? m_output : NULL;
}
// IGSSource
STDMETHODIMP DeliverNewSegment()
{
m_now = 0;
return m_output->DeliverNewSegment(0, _I64_MAX, 1.0);
}
STDMETHODIMP DeliverFrame(const void* bits, int pitch, bool rgba)
{
if(!m_output || !m_output->IsConnected())
{
return E_UNEXPECTED;
}
CComPtr<IMediaSample> sample;
if(FAILED(m_output->GetDeliveryBuffer(&sample, NULL, NULL, 0)))
{
return E_FAIL;
}
REFERENCE_TIME start = m_now;
REFERENCE_TIME stop = m_now + m_atpf;
sample->SetTime(&start, &stop);
sample->SetSyncPoint(TRUE);
const CMediaType& mt = m_output->CurrentMediaType();
uint8* src = (uint8*)bits;
uint8* dst = NULL;
sample->GetPointer(&dst);
int w = m_size.x;
int h = m_size.y;
int srcpitch = pitch;
if(mt.subtype == MEDIASUBTYPE_YUY2)
{
int dstpitch = ((VIDEOINFOHEADER*)mt.Format())->bmiHeader.biWidth * 2;
GSVector4 ys(0.257f, 0.504f, 0.098f, 0.0f);
GSVector4 us(-0.148f / 2, -0.291f / 2, 0.439f / 2, 0.0f);
GSVector4 vs(0.439f / 2, -0.368f / 2, -0.071f / 2, 0.0f);
const GSVector4 offset(16, 128, 16, 128);
if (!rgba)
ys = ys.zyxw(), us = us.zyxw(), vs = vs.zyxw();
for(int j = 0; j < h; j++, dst += dstpitch, src += srcpitch)
{
uint32* s = (uint32*)src;
uint16* d = (uint16*)dst;
for(int i = 0; i < w; i += 2)
{
GSVector4 c0 = GSVector4(s[i + 0]);
GSVector4 c1 = GSVector4(s[i + 1]);
GSVector4 c2 = c0 + c1;
GSVector4 lo = (c0 * ys).hadd(c2 * us);
GSVector4 hi = (c1 * ys).hadd(c2 * vs);
GSVector4 c = lo.hadd(hi) + offset;
*((uint32*)&d[i]) = GSVector4i(c).rgba32();
}
}
}
else if(mt.subtype == MEDIASUBTYPE_RGB32)
{
int dstpitch = ((VIDEOINFOHEADER*)mt.Format())->bmiHeader.biWidth * 4;
dst += dstpitch * (h - 1);
dstpitch = -dstpitch;
for(int j = 0; j < h; j++, dst += dstpitch, src += srcpitch)
{
if(rgba)
{
#if _M_SSE >= 0x301
GSVector4i* s = (GSVector4i*)src;
GSVector4i* d = (GSVector4i*)dst;
GSVector4i mask(2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15);
for(int i = 0, w4 = w >> 2; i < w4; i++)
{
d[i] = s[i].shuffle8(mask);
}
#else
GSVector4i* s = (GSVector4i*)src;
GSVector4i* d = (GSVector4i*)dst;
for(int i = 0, w4 = w >> 2; i < w4; i++)
{
d[i] = ((s[i] & 0x00ff0000) >> 16) | ((s[i] & 0x000000ff) << 16) | (s[i] & 0x0000ff00);
}
#endif
}
else
{
memcpy(dst, src, w * 4);
}
}
}
else
{
return E_FAIL;
}
if(FAILED(m_output->Deliver(sample)))
{
return E_FAIL;
}
m_now = stop;
return S_OK;
}
STDMETHODIMP DeliverEOS()
{
return m_output->DeliverEndOfStream();
}
};
//
// GSCapture
//
GSCapture::GSCapture()
: m_capturing(false)
{
}
GSCapture::~GSCapture()
{
EndCapture();
}
#define BeginEnumPins(pBaseFilter, pEnumPins, pPin) \
{CComPtr<IEnumPins> pEnumPins; \
if(pBaseFilter && SUCCEEDED(pBaseFilter->EnumPins(&pEnumPins))) \
{ \
for(CComPtr<IPin> pPin; S_OK == pEnumPins->Next(1, &pPin, 0); pPin = NULL) \
{ \
#define EndEnumPins }}}
static IPin* GetFirstPin(IBaseFilter* pBF, PIN_DIRECTION dir)
{
if(!pBF) return(NULL);
BeginEnumPins(pBF, pEP, pPin)
{
PIN_DIRECTION dir2;
pPin->QueryDirection(&dir2);
if(dir == dir2)
{
IPin* pRet = pPin.Detach();
pRet->Release();
return(pRet);
}
}
EndEnumPins
return(NULL);
}
bool GSCapture::BeginCapture(int fps)
{
CAutoLock cAutoLock(this);
ASSERT(fps != 0);
EndCapture();
GSCaptureDlg dlg;
if(IDOK != dlg.DoModal()) return false;
m_size.x = (dlg.m_width + 7) & ~7;
m_size.y = (dlg.m_height + 7) & ~7;
wstring fn(dlg.m_filename.begin(), dlg.m_filename.end());
//
HRESULT hr;
CComPtr<ICaptureGraphBuilder2> cgb;
CComPtr<IBaseFilter> mux;
if(FAILED(hr = m_graph.CoCreateInstance(CLSID_FilterGraph))
|| FAILED(hr = cgb.CoCreateInstance(CLSID_CaptureGraphBuilder2))
|| FAILED(hr = cgb->SetFiltergraph(m_graph))
|| FAILED(hr = cgb->SetOutputFileName(&MEDIASUBTYPE_Avi, fn.c_str(), &mux, NULL)))
{
return false;
}
m_src = new GSSource(m_size.x, m_size.y, fps, NULL, hr);
if (dlg.m_enc==0)
{
if (FAILED(hr = m_graph->AddFilter(m_src, L"Source")))
return false;
if (FAILED(hr = m_graph->ConnectDirect(GetFirstPin(m_src, PINDIR_OUTPUT), GetFirstPin(mux, PINDIR_INPUT), NULL)))
return false;
}
else
{
if(FAILED(hr = m_graph->AddFilter(m_src, L"Source"))
|| FAILED(hr = m_graph->AddFilter(dlg.m_enc, L"Encoder")))
{
return false;
}
if(FAILED(hr = m_graph->ConnectDirect(GetFirstPin(m_src, PINDIR_OUTPUT), GetFirstPin(dlg.m_enc, PINDIR_INPUT), NULL))
|| FAILED(hr = m_graph->ConnectDirect(GetFirstPin(dlg.m_enc, PINDIR_OUTPUT), GetFirstPin(mux, PINDIR_INPUT), NULL)))
{
return false;
}
}
BeginEnumFilters(m_graph, pEF, pBF)
{
CFilterInfo fi;
pBF->QueryFilterInfo(&fi);
wstring s(fi.achName);
printf("Filter [%p]: %s\n", pBF.p, string(s.begin(), s.end()).c_str());
BeginEnumPins(pBF, pEP, pPin)
{
CComPtr<IPin> pPinTo;
pPin->ConnectedTo(&pPinTo);
CPinInfo pi;
pPin->QueryPinInfo(&pi);
wstring s(pi.achName);
printf("- Pin [%p - %p]: %s (%s)\n", pPin.p, pPinTo.p, string(s.begin(), s.end()).c_str(), pi.dir ? "out" : "in");
BeginEnumMediaTypes(pPin, pEMT, pmt)
{
}
EndEnumMediaTypes(pmt)
}
EndEnumPins
}
EndEnumFilters
hr = CComQIPtr<IMediaControl>(m_graph)->Run();
CComQIPtr<IGSSource>(m_src)->DeliverNewSegment();
m_capturing = true;
return true;
}
bool GSCapture::DeliverFrame(const void* bits, int pitch, bool rgba)
{
CAutoLock cAutoLock(this);
if(bits == NULL || pitch == 0)
{
ASSERT(0);
return false;
}
if(m_src)
{
CComQIPtr<IGSSource>(m_src)->DeliverFrame(bits, pitch, rgba);
return true;
}
return false;
}
bool GSCapture::EndCapture()
{
CAutoLock cAutoLock(this);
if(m_src)
{
CComQIPtr<IGSSource>(m_src)->DeliverEOS();
m_src = NULL;
}
if(m_graph)
{
CComQIPtr<IMediaControl>(m_graph)->Stop();
m_graph = NULL;
}
m_capturing = false;
return true;
}
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
]
| [
[
[
1,
514
]
]
]
|
823b36646a378fc64e25cb29ec8630b4b9485f7c | cfad0abe8d02cc052bf22997ba2670573563abff | /xkeymacsdll/xkeymacsdll.h | c081f67a6808a7a4465fc4519f2c3cab06c8a470 | []
| no_license | kikairoya/xkeymacs | 0b4a2812f044276d9d6eb6589e4f474ae9ec4142 | 420cc0649c990e43fb5f9579321c28df78bdc1f7 | refs/heads/master | 2021-01-17T21:24:07.576264 | 2011-06-08T04:59:59 | 2011-06-08T04:59:59 | 1,858,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,530 | h | // xkeymacs.h: interface for the CXkeymacsDll class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_XKEYMACS_H__88552DEC_1233_4A0A_BE62_9EF7BC618EC6__INCLUDED_)
#define AFX_XKEYMACS_H__88552DEC_1233_4A0A_BE62_9EF7BC618EC6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "ClipboardSnap.h"
enum { MAX_APP = 64 };
enum { NONE = 0x0, SHIFT = 0x1, CONTROL = 0x2, META = 0x4, CONTROLX = 0x8,
MAX_COMMAND_TYPE = NONE + SHIFT + CONTROL + META + CONTROLX + 1 };
enum { /* WIN_SHIFT = 0x100, */ WIN_CTRL = 0x200, WIN_ALT = 0x400, WIN_WIN = 0x800 };
enum { MAX_KEY = 256 };
enum { MAX_FUNCTION = 64 };
enum { MAX_DEFINITION = 256 };
enum { WINDOW_NAME_LENGTH = 128 };
enum { CLASS_NAME_LENGTH = 128 };
enum { SUB_KEY_NAME_LENGTH = 128 };
enum { WINDOW_TEXT_LENGTH = 128 + 128 + 3};
enum ICON_TYPE { MAIN_ICON, CX_ICON, MX_ICON, META_ICON, SHIFT_ICON, CTRL_ICON, ALT_ICON, MAX_ICON_TYPE };
enum XKEYMACS_STATUS { STATUS_ENABLE, STATUS_DISABLE_TMP, STATUS_DISABLE_WOCQ, STATUS_DISABLE, MAX_STATUS };
enum { ON_ICON, OFF_ICON }; // alias of status
enum GOTO { GOTO_DO_NOTHING, GOTO_HOOK, GOTO_RECURSIVE, GOTO_HOOKX, GOTO_HOOK0_9, CONTINUE };
enum SETTING_STYLE { SETTING_DEFAULT, SETTING_SPECIFIC, SETTING_DISABLE, SETTING_UNDEFINED };
enum { EXTENDED_KEY = 0x01000000 };
enum { REPEATED_KEY = 0x40000000 };
enum { BEING_RELEASED = 0x80000000 };
#include "ipc.h"
struct KeyBind
{
int nCommandType;
BYTE bVk;
int nControlID;
};
struct KeyName
{
BYTE bVk;
LPCTSTR name;
};
class AFX_EXT_CLASS CXkeymacsDll
{
public:
static BOOL SaveConfig();
static BOOL LoadConfig();
static void SetM_xTip(const TCHAR *const szPath);
static void SetHookAltRelease();
static BOOL Get326Compatible();
static void Set326Compatible(int nApplicationID, BOOL b326Compatible);
static void SetCursorData(HCURSOR hEnable, HCURSOR hDisableTMP, HCURSOR hDisableWOCQ, HICON hDisable, BOOL bEnable);
static unsigned int GetMaxKeyInterval(void);
static void SetKeyboardSpeed(int nKeyboardSpeed);
static int GetAccelerate(void);
static void SetAccelerate(int nAccelerate);
static void SetWindowText(int nApplicationID, CString szWindowText);
static void SetKillRingMax(int nApplicationID, int nKillRingMax);
static void Clear(int nApplicationID);
static BOOL IsKeyboardHook();
static void SetCommandID(int nApplicationID, int nCommandType, int nKey, int nCommandID);
static void SetAtIbeamCursorOnly(int nApplicationID, int nCommandType, int nKey, BOOL bAtIbeamCursorOnly);
static void SetApplicationName(int nApplicationID, CString szApplicationName);
static void ReleaseHooks();
static void SetEnableCUA(int nApplicationID, BOOL bEnableCUA);
static void SetIgnoreUndefinedC_x(int nApplicationID, BOOL bIgnoreUndefinedC_x);
static void SetIgnoreUndefinedMetaCtrl(int nApplicationID, BOOL bIgnoreUndefinedMetaCtrl);
static void SetHooks();
static void EnableKeyboardHook();
static void ResetHook();
static void SetSettingStyle(int nApplicationID, int nSettingStyle);
static void SetUseDialogSetting(int nApplicationID, BOOL bUseDialogSetting);
static void AddKillRing(BOOL bNewData = TRUE);
static void CallMacro();
static void ClearFunctionDefinition();
static void DefiningMacro(BOOL bDefiningMacro);
static void DepressKey(BYTE bVk, BOOL bOriginal = TRUE);
static BOOL GetEnableCUA();
static CClipboardSnap* GetKillRing(CClipboardSnap *pSnap, BOOL bForce = TRUE);
static void IncreaseKillRingIndex(int nKillRing = 1);
static BOOL IsDown(BYTE bVk, BOOL bPhysicalKey = TRUE);
static void Kdu(BYTE bVk, DWORD n = 1, BOOL bOriginal = TRUE);
static void ReleaseKey(BYTE bVk);
static void SetFunctionDefinition(int nFunctionID, CString szDefinition);
static void SetFunctionKey(int nFunctionID, int nApplicationID, int nCommandType, int nKey);
static void SetKeyboardHookFlag();
static void SetKeyboardHookFlag(BOOL bFlag);
static BOOL Is106Keyboard();
static void Set106Keyboard(BOOL b106Keyboard);
static BOOL SendIconMessage(ICONMSG *pMsg, DWORD num);
CXkeymacsDll();
virtual ~CXkeymacsDll();
private:
static BOOL m_bHookAltRelease;
static TCHAR m_M_xTip[128];
static void InvokeM_x(const TCHAR* const szPath);
static void LogCallWndProcMessage(WPARAM wParam, LPARAM lParam);
static void DoSetCursor();
static HCURSOR m_hCurrentCursor;
static BOOL m_bCursor;
static HCURSOR m_hCursor[MAX_STATUS];
static int m_nKeyboardSpeed;
static int m_nAccelerate;
static HHOOK m_hHookCallWndRet;
static LRESULT CALLBACK CallWndRetProc(int nCode, WPARAM wParam, LPARAM lParam);
static BOOL IsMatchWindowText(CString szWindowText);
static BOOL m_bEnableKeyboardHook;
static HHOOK m_hHookCallWnd;
static HHOOK m_hHookGetMessage;
static HHOOK m_hHookShell;
static BOOL DefiningMacro();
static BOOL IsControl();
static BOOL IsMeta();
static void SetModifierIcons();
static void DoKeybd_event(BYTE bVk, DWORD dwFlags);
static LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK CallWndProc(int nCode, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK ShellProc(int nCode, WPARAM wParam, LPARAM lParam);
static KeyBind ParseKey(const int nFunctionID, unsigned int &i);
static BYTE a2v(TCHAR nAscii);
static BOOL IsShift(TCHAR nAscii);
static void CallFunction(int nFunctionID);
static int IsPassThrough(BYTE nKey);
static BOOL IsDepressedShiftKeyOnly(BYTE nKey);
static BOOL IsDepressedModifier(int Modifier(), BOOL bPhysicalKey = TRUE);
static BOOL IsValidKey(BYTE bVk);
static CObList m_Macro;
static BOOL m_bDefiningMacro;
static void Original(int nCommandType, BYTE bVk, int nOriginal);
static int Original(int nCommandType, BYTE bVk);
static void InitKeyboardProc(BOOL bImeComposition);
static int m_nApplicationID;
static int m_nOriginal[MAX_COMMAND_TYPE][MAX_KEY];
static int m_nKillRing;
static CList<CClipboardSnap *, CClipboardSnap *> m_oKillRing;
static int GetMickey(int nDifferential, int nThreshold1, int nThreshold2, int nAcceleration, int nSpeed);
static BOOL m_bHook;
static BOOL m_bRightShift;
static BOOL m_bRightAlt;
static BOOL m_bRightControl;
static CONFIG m_Config;
};
extern UINT g_ImeManipulationMessage;
#endif // !defined(AFX_XKEYMACS_H__88552DEC_1233_4A0A_BE62_9EF7BC618EC6__INCLUDED_)
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
79
],
[
81,
154
],
[
157,
157
]
],
[
[
80,
80
],
[
155,
156
]
]
]
|
7246c6f781bb6fa63af7e1a80e601754ed59c681 | 6b570e095f8eea42c8114ef6be1ee62cd4ec3c8f | /thu-remap/grid.cxx | 74da44672e7516d0c28628a36e08dcefd7204a07 | []
| no_license | pinewall/RemapTest | 6a89cf96640a52b9e3accb13eead76976ba77f38 | 0ca05f95b183cc5a556c0e607980257644e46392 | refs/heads/master | 2016-09-02T09:33:09.348387 | 2011-07-31T02:28:04 | 2011-07-31T02:28:04 | 2,070,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,767 | cxx | #include "grid.h"
#include <stdio.h>
#include <string.h>
#include "io.h"
#include "models_cfg.h"
#include <netcdf.h>
#include <stdlib.h>
#include <math.h>
#define NC_ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(2);}
#define MAX(a,b) ((a)>(b) ? (a) : (b))
#define MIN(a,b) ((a)<(b) ? (a) : (b))
#define ZERO 0.0
#define TWO 2
#define HALF 0.5
#define PI2 TWO*PI
#define PIH HALF*PI
#define MAX_VALUE 9999
#define MIN_VALUE -9999
#define LATITUDE 1
#define LATLON 2
grid::grid(char *filename, char *grid_name, int model_set_id, int file_type)
{
double last_lat;
double last_lon;
double *tmp_lon_array1;
double *tmp_lon_array2;
double *tmp_double;
int i, j, k, m, n, count, indx;
int *tmp_nlat_each_lon1;
int *tmp_nlat_each_lon2;
int *tmp_int;
int *tmp_current_indx_each_lon;
FILE *fp_grid;
int rcode;
int fid;
int did;
int vid;
unsigned int value;
int grid_dims[3];
unsigned long start[2];
unsigned long size[2];
int *temp_mask;
double max_lat;
double min_lat;
my_model_set_id = model_set_id;
/*input is binary file*/
strcpy(my_name, grid_name);
if (file_type == BINARY_FILE) {
if ((fp_grid = fopen(filename, "rb")) == NULL)
printf("cannot open the file of grid\n");
fseek(fp_grid, 0, SEEK_SET);
fread(&ndim, sizeof(int), 1, fp_grid);
fread(&npnts, sizeof(int), 1, fp_grid);
fread(&nlons, sizeof(int), 1, fp_grid);
fread(&nlats, sizeof(int), 1, fp_grid);
if (ndim == 3)
fread(&nhghts, sizeof(int), 1, fp_grid);
else nhghts = -1;
fread(&nvertexes, sizeof(int), 1, fp_grid);
center_lon_coords = new double [npnts];
center_lat_coords = new double [npnts];
fread(center_lat_coords, sizeof(double), npnts, fp_grid);
fread(center_lon_coords, sizeof(double), npnts, fp_grid);
if (ndim == 3) {
center_heights = new double [npnts];
fread(center_heights, sizeof(double), npnts, fp_grid);
}
else center_heights = NULL;
vertex_lat_coords = new double [nvertexes * npnts];
vertex_lon_coords = new double [nvertexes * npnts];
fread(vertex_lat_coords, sizeof(double), nvertexes * npnts, fp_grid);
fread(vertex_lon_coords, sizeof(double), nvertexes * npnts, fp_grid);
if (ndim == 3) {
vertex_heights = new double [nvertexes * npnts];
fread(vertex_heights, sizeof(double), nvertexes * npnts, fp_grid);
}
else vertex_heights = NULL;
area_in = new double [npnts];
areas = new double [npnts];
// fread(area_in, sizeof(double), npnts, fp_grid);
mask = new bool *[num_model_set];
model_frac = new double * [num_model_set];
for (i = 0; i < num_model_set; i ++) {
mask[i] = NULL;
model_frac[i] = NULL;
}
mask[model_set_id] = new bool [npnts];
model_frac[model_set_id] = new double [npnts];
fread(mask[model_set_id], sizeof(bool), npnts, fp_grid);
}
if (file_type == NETCDF_FILE) {
if((rcode = nc_open(filename, NC_NOWRITE, &fid)))
NC_ERR(rcode);
if((rcode = nc_inq_dimid(fid, "grid_rank", &did)))
NC_ERR(rcode);
if((rcode = nc_inq_dimlen(fid, did, &value)))
NC_ERR(rcode);
ndim = value;
if((rcode = nc_inq_dimid(fid, "grid_size", &did)))
NC_ERR(rcode);
if((rcode = nc_inq_dimlen(fid, did, &value)))
NC_ERR(rcode);
npnts = value;
if((rcode = nc_inq_dimid(fid, "grid_corners", &did)))
NC_ERR(rcode);
if((rcode = nc_inq_dimlen(fid, did, &value)))
NC_ERR(rcode);
nvertexes = value;
if((rcode = nc_inq_varid(fid, "grid_dims", &vid)))
NC_ERR(rcode);
value = ndim;
if((rcode = nc_get_var_int(fid, vid, grid_dims)))
NC_ERR(rcode);
nlons = grid_dims[0];
nlats = grid_dims[1];
nhghts = grid_dims[2];
if (ndim < 3)
nhghts = -1;
center_lon_coords = new double [npnts];
center_lat_coords = new double [npnts];
vertex_lat_coords = new double [nvertexes * npnts];
vertex_lon_coords = new double [nvertexes * npnts];
area_in = new double [npnts];
areas = new double [npnts];
mask = new bool *[num_model_set];
model_frac = new double * [num_model_set];
for (i = 0; i < num_model_set; i ++) {
mask[i] = NULL;
model_frac[i] = NULL;
}
mask[model_set_id] = new bool [npnts];
model_frac[model_set_id] = new double [npnts];
if((rcode = nc_inq_varid(fid, "grid_center_lat", &vid)))
NC_ERR(rcode);
if((rcode = nc_get_var_double(fid, vid, center_lat_coords)))
NC_ERR(rcode);
if((rcode = nc_inq_varid(fid,"grid_center_lon",&vid)))
NC_ERR(rcode);
if((rcode = nc_get_var_double(fid, vid, center_lon_coords)))
NC_ERR(rcode);
if((rcode = nc_inq_varid(fid, "grid_imask", &vid)))
NC_ERR(rcode);
temp_mask = new int [npnts];
if((rcode = nc_get_var_int(fid, vid, temp_mask)))
NC_ERR(rcode);
for (i = 0; i < npnts; i ++)
mask[model_set_id][i] = (temp_mask[i] == 1);
delete [] temp_mask;
if((rcode = nc_inq_varid(fid, "grid_corner_lat", &vid)))
NC_ERR(rcode);
if((rcode = nc_get_var_double(fid, vid, vertex_lat_coords)))
NC_ERR(rcode);
if((rcode = nc_inq_varid(fid, "grid_corner_lon", &vid)))
NC_ERR(rcode);
if((rcode = nc_get_var_double(fid, vid, vertex_lon_coords)))
NC_ERR(rcode);
center_heights = NULL;
vertex_heights = NULL;
}
#ifdef DEBUG_GRID
check_grid_info(0);
#endif
/*calculate the maximum and minimum latitudes of each row*/
max_lat_each_row = new double [nlats];
min_lat_each_row = new double [nlats];
nlon_each_lat = new int [nlats];
nlat_each_lon = new int [nlons];
different_lons = new double [nlons];
different_lats = new double [nlats];
reverse_indx = new int [npnts];
if (npnts == nlats * nlons) { // logical rectangular grid
for (i = 0; i < nlats; i ++) {
nlon_each_lat[i] = nlons;
max_lat = -100000;
min_lat = 100000;
for (j = 0; j < nlons; j ++) {
if (center_lat_coords[i * nlons + j] > max_lat)
max_lat = center_lat_coords[i * nlons + j];
if (center_lat_coords[i * nlons + j] < min_lat)
min_lat = center_lat_coords[i * nlons + j];
}
max_lat_each_row[i] = max_lat;
min_lat_each_row[i] = min_lat;
}
for (i = 0; i < nlats; i ++)
if (max_lat_each_row[i] != min_lat_each_row[i])
break;
if (i != nlats) {
type_grid = 1;
printf("irregular grid\n");
}
else {
type_grid = 0;
printf("regular grid\n");
}
}
else {
/*calculate the number of longitudes in each latitude*/
for (i = 0; i < nlats; i ++)
nlon_each_lat[i] = 0;
last_lat = center_lat_coords[0];
indx = 0;
for (i = 0, count = 0; i < npnts; i ++) {
if (last_lat == center_lat_coords[i])
count ++;
else {
nlon_each_lat[indx ++] = count;
last_lat = center_lat_coords[i];
count = 1;
}
}
nlon_each_lat[indx ++] = count;
/*calculate the different latitudes in the grid*/
for (i = 0, count = 0; i < nlats; i ++) {
different_lats[i] = center_lat_coords[count];
count += nlon_each_lat[i];
}
/*calculate the number of latitudes in each longitude and the different longitudes in the grid*/
tmp_lon_array1 = new double [nlons];
tmp_lon_array2 = new double [nlons];
tmp_nlat_each_lon1 = new int [nlons];
tmp_nlat_each_lon2 = new int [nlons];
for (i = 0; i < nlons; i ++)
tmp_nlat_each_lon1[i] = 0;
for (i = 0; i < nlon_each_lat[0]; i ++) {
tmp_nlat_each_lon1[i] = 1;
tmp_lon_array1[i] = center_lon_coords[i];
}
count = nlon_each_lat[0];
for (i = 1, j = nlon_each_lat[0]; i < nlats; i ++) {
k = 0;
m = 0;
n = 0;
while (k < nlon_each_lat[i] && m < count) {
if (tmp_lon_array1[m] == center_lon_coords[j + k]) {
tmp_nlat_each_lon2[n] = tmp_nlat_each_lon1[m] + 1;
tmp_lon_array2[n ++] = tmp_lon_array1[m];
m ++;
k ++;
}
else if (tmp_lon_array1[m] < center_lon_coords[j + k]) {
tmp_nlat_each_lon2[n] = tmp_nlat_each_lon1[m];
tmp_lon_array2[n ++] = tmp_lon_array1[m];
m ++;
}
else {
tmp_nlat_each_lon2[n] = 1;
tmp_lon_array2[n ++] = center_lon_coords[j + k];
k ++;
}
}
for (; k < nlon_each_lat[i]; k ++) {
tmp_nlat_each_lon2[n] = 1;
tmp_lon_array2[n ++] = center_lon_coords[j + k];
}
for (; m < count; m ++) {
tmp_nlat_each_lon2[n] = tmp_nlat_each_lon1[m];
tmp_lon_array2[n ++] = tmp_lon_array1[m];
}
count = n;
tmp_double = tmp_lon_array1;
tmp_lon_array1 = tmp_lon_array2;
tmp_lon_array2 = tmp_double;
tmp_int = tmp_nlat_each_lon1;
tmp_nlat_each_lon1 = tmp_nlat_each_lon2;
tmp_nlat_each_lon2 = tmp_int;
j += nlon_each_lat[i];
}
for (i = 0; i < nlons; i ++) {
nlat_each_lon[i] = tmp_nlat_each_lon1[i];
different_lons[i] = tmp_lon_array1[i];
}
/*check whether the grid is retangular*/
is_rect = true;
for (i = 0; i < nlats; i ++)
if (nlons != nlon_each_lat[i])
is_rect = false;
for (i = 0; i < nlons; i ++)
if (nlats != nlat_each_lon[i])
is_rect = false;
/*calculate the reverse index of each point when transforming the lat-major matrix into lon-major matrix*/
tmp_current_indx_each_lon = new int [nlons];
tmp_current_indx_each_lon[0] = 0;
for (i = 1; i < nlons; i ++)
tmp_current_indx_each_lon[i] = tmp_current_indx_each_lon[i - 1] + nlat_each_lon[i];
for (i = 0, j = 0; i < nlats; i ++) {
k = 0;
m = 0;
n = 0;
while (k < nlon_each_lat[i] && m < nlons) {
if (tmp_lon_array1[m] == center_lon_coords[j + k]) {
reverse_indx[j + k] = tmp_current_indx_each_lon[m];
tmp_current_indx_each_lon[m] ++;
m ++;
k ++;
}
else if (tmp_lon_array1[m] < center_lon_coords[j + k])
m ++;
else {
printf("never happen case when building reverse indexes for grid\n");
}
}
j += nlon_each_lat[i];
}
delete [] tmp_current_indx_each_lon;
delete [] tmp_lon_array1;
delete [] tmp_lon_array2;
delete [] tmp_nlat_each_lon1;
delete [] tmp_nlat_each_lon2;
}
#ifdef DEBUG_GRID
check_grid_info(1);
#endif
}
void grid::test_bug()
{
delete [] areas;
}
grid::~grid()
{
delete [] center_lon_coords;
delete [] center_lat_coords;
if (center_heights != NULL)
delete [] center_heights;
delete [] vertex_lat_coords;
delete [] vertex_lon_coords;
if (vertex_heights != NULL)
delete [] vertex_heights;
delete [] area_in;
delete [] areas;
for (int i = 0; i < num_model_set; i ++)
if (mask[i] != NULL) {
delete [] mask[i];
delete [] model_frac[i];
}
delete [] mask;
delete [] model_frac;
delete [] nlat_each_lon;
delete [] nlon_each_lat;
delete [] reverse_indx;
delete [] different_lats;
delete [] max_lat_each_row;
delete [] min_lat_each_row;
delete [] different_lons;
//adding
delete [] bound_box;
delete [] dims;
delete [] bin_addr;
delete [] bin_lats;
delete [] bin_lons;
}
#ifdef DEBUG_GRID
void grid::check_grid_info(int check_type)
{
int i, j;
double *tmp_lat_coords;
double *tmp_lon_coords;
/*check whether the grid is lat-major and sorted after loading it*/
if (check_type == 0) {
for (i = 1; i < npnts; i ++) {
if (center_lat_coords[i] < center_lat_coords[i - 1]) {
printf("grid is not lat-major and sorted: case 1\n");
break;
}
if (center_lat_coords[i] == center_lat_coords[i - 1] &&
center_lon_coords[i] < center_lon_coords[i - 1]) {
printf("grid is not lat-major and sorted: case 2 %d\n", i);
break;
}
}
}
/*check the correctness of nlats, nlons and reverse matrix*/
if (check_type == 1) {
if (!is_rect)
printf("%s is not a rect grid\n", my_name);
tmp_lat_coords = new double [npnts];
tmp_lon_coords = new double [npnts];
for (i = 0; i < nlats; i ++)
if (nlon_each_lat[i] == 0) {
printf("nlats of grid is wrong\n");
break;
}
for (i = 0; i < nlons; i ++)
if (nlat_each_lon[i] == 0) {
printf("nlons of grid is wrong\n");
break;
}
for (i = 0; i < npnts; i ++) {
tmp_lat_coords[reverse_indx[i]] = tmp_lat_coords[i];
tmp_lon_coords[reverse_indx[i]] = tmp_lon_coords[i];
}
/*check whether the reversed grid is lon-major and sorted*/
for (i = 1; i < npnts; i ++) {
if (tmp_lon_coords[i] < tmp_lon_coords[i - 1]) {
printf("the reversed grid is not lon-major and sorted: case 1\n");
break;
}
if (tmp_lon_coords[i] == tmp_lon_coords[i - 1] &&
tmp_lat_coords[i] < tmp_lat_coords[i - 1]) {
printf("the reversed grid is not lon-major and sorted: case 2\n");
break;
}
}
delete [] tmp_lat_coords;
delete [] tmp_lon_coords;
}
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
431
]
]
]
|
78af56f7f5729fdf5e3a0909a16206ba17a3c54c | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/serialization/src/codecvt_null.cpp | e4f6be2e154032705063c3deae3e9eb952073e78 | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,863 | cpp | /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// codecvt_null.cpp
// Copyright © 2001 Ronald Garcia, Indiana University ([email protected])
// Andrew Lumsdaine, Indiana University ([email protected]).
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/archive/codecvt_null.hpp>
// codecvt implementation for passing wchar_t objects to char output
// without any translation whatever. Used to implement binary output
// of wchar_t objects.
namespace boost {
namespace archive {
std::codecvt_base::result
codecvt_null<wchar_t>::do_out(
std::mbstate_t & state,
const wchar_t * first1,
const wchar_t * last1,
const wchar_t * & next1,
char * first2,
char * last2,
char * & next2
) const {
for(;first1 != last1; ++first1){
// Per std::22.2.1.5.2/2, we can store no more that
// last2-first2 characters. If we need to more encode
// next internal char type, return 'partial'.
if(static_cast<int>(sizeof(wchar_t)) > (last2 - first2)){
next1 = first1;
next2 = first2;
return std::codecvt_base::partial;
}
unsigned int i;
for(i = sizeof(wchar_t); i > 0;)
*first2++ = (* first1 >> (8 * --i)) & 0xff;
}
next1 = first1;
next2 = first2;
return std::codecvt_base::ok;
}
std::codecvt_base::result
codecvt_null<wchar_t>::do_in(
std::mbstate_t & state,
const char * first1,
const char * last1,
const char * & next1,
wchar_t * first2,
wchar_t * last2,
wchar_t * & next2
) const {
// Process input characters until we've run of them,
// or the number of remaining characters is not
// enough to construct another output character,
// or we've run out of place for output characters.
while(first2 != last2){
// Have we converted all input characters?
// Return with 'ok', if so.
if (first1 == last1)
break;
// Do we have less input characters than needed
// for a single output character?
if(static_cast<int>(sizeof(wchar_t)) > (last1 - first1)){
next1 = first1;
next2 = first2;
return std::codecvt_base::partial;
}
*first2 = static_cast<unsigned char>(*first1++);
int i = sizeof(wchar_t) - 1;
do{
*first2 <<= 8;
*first2 |= static_cast<unsigned char>(*first1++);
}while(--i > 0);
++first2;
}
next1 = first1;
next2 = first2;
return std::codecvt_base::ok;
}
} // namespace archive
} // namespace boost
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
87
]
]
]
|
8d8fce1ce8b14fa6a3c3667e313eee0c0da08fea | 93eac58e092f4e2a34034b8f14dcf847496d8a94 | /ncl30-cpp/ncl30-generator/include/generables/CompoundActionGenerator.h | e35a685c29e2d740304c2ef07a6ef0a9b5433dcb | []
| no_license | lince/ginga-srpp | f8154049c7e287573f10c472944315c1c7e9f378 | 5dce1f7cded43ef8486d2d1a71ab7878c8f120b4 | refs/heads/master | 2020-05-27T07:54:24.324156 | 2011-10-17T13:59:11 | 2011-10-17T13:59:11 | 2,576,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,794 | h | /******************************************************************************
Este arquivo eh parte da implementacao do ambiente declarativo do middleware
Ginga (Ginga-NCL).
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob
os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free
Software Foundation.
Este programa eh distribuido na expectativa de que seja util, porem, SEM
NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU
ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do
GNU versao 2 para mais detalhes.
Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto
com este programa; se nao, escreva para a Free Software Foundation, Inc., no
endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
Para maiores informacoes:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
******************************************************************************
This file is part of the declarative environment of middleware Ginga (Ginga-NCL)
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License version 2 for more
details.
You should have received a copy of the GNU General Public License version 2
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
For further information contact:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
*******************************************************************************/
/**
* @file CompoundActionGenerator.h
* @author Caio Viel
* @date 29-01-10
*/
#ifndef _COMPOUNDACTIONGENERATOR_H
#define _COMPOUNDACTIONGENERATOR_H
#include <vector>
#include "ncl/connectors/CompoundAction.h"
using namespace ::br::pucrio::telemidia::ncl::connectors;
#include "Generable.h"
#include "SimpleActionGenerator.h"
namespace br {
namespace ufscar {
namespace lince {
namespace ncl {
namespace generator {
class CompoundActionGenerator : public CompoundAction {
public:
/**
* Gera o código XML da entidade NCL CompoundAction.
* @return Uma string contendo o código NCL gerado.
*/
string generateCode();
};
}
}
}
}
}
#endif /* _COMPOUNDACTIONGENERATOR_H */
| [
"[email protected]"
]
| [
[
[
1,
92
]
]
]
|
668ee21b3c6502875b0969142c6656935614df4f | 1ab9457b2e2183ec8275a9713d8c7cbb48c835d1 | /Source/Common/BWAPI/include/BWAPI/UnitCommandType.h | ffaa33b1480d2ef0161717216a6ec7560990ea96 | []
| no_license | ianfinley89/emapf-starcraft-ai | 0f6ca09560092e798873b6b5dda01d463fa71518 | b1bf992dff681a7feb618b7a781bacc61d2d477d | refs/heads/master | 2020-05-19T20:52:17.080667 | 2011-03-04T11:59:46 | 2011-03-04T11:59:46 | 32,126,953 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,474 | h | #pragma once
#include <string>
#include <set>
#define BWAPI_UNIT_COMMAND_TYPE_COUNT 46
namespace BWAPI
{
class UnitCommandType
{
public:
UnitCommandType();
UnitCommandType(int id);
UnitCommandType(const UnitCommandType& other);
UnitCommandType& operator=(const UnitCommandType& other);
bool operator==(const UnitCommandType& other) const;
bool operator!=(const UnitCommandType& other) const;
bool operator<(const UnitCommandType& other) const;
bool operator>(const UnitCommandType& other) const;
/** Returns a unique ID for this UnitCommandType. */
int getID() const;
/** Returns the string corresponding to the UnitCommandType object. For example,
* UnitCommandTypes::Set_Rally_Position.getName() returns std::string("Set Rally Position")*/
std::string getName() const;
private:
int id;
};
namespace UnitCommandTypes
{
/** Given a string, this function returns the command type it refers to. For example,
* UnitCommandTypes::getUnitCommandType("Attack Position") returns UnitCommandTypes::Attack_Position. */
UnitCommandType getUnitCommandType(std::string name);
/** Returns the set of all the sizes, which are listed below: */
std::set<UnitCommandType>& allUnitCommandTypes();
void init();
extern const UnitCommandType Attack_Move;
extern const UnitCommandType Attack_Unit;
extern const UnitCommandType Build;
extern const UnitCommandType Build_Addon;
extern const UnitCommandType Train;
extern const UnitCommandType Morph;
extern const UnitCommandType Research;
extern const UnitCommandType Upgrade;
extern const UnitCommandType Set_Rally_Position;
extern const UnitCommandType Set_Rally_Unit;
extern const UnitCommandType Move;
extern const UnitCommandType Patrol;
extern const UnitCommandType Hold_Position;
extern const UnitCommandType Stop;
extern const UnitCommandType Follow;
extern const UnitCommandType Gather;
extern const UnitCommandType Return_Cargo;
extern const UnitCommandType Repair;
extern const UnitCommandType Burrow;
extern const UnitCommandType Unburrow;
extern const UnitCommandType Cloak;
extern const UnitCommandType Decloak;
extern const UnitCommandType Siege;
extern const UnitCommandType Unsiege;
extern const UnitCommandType Lift;
extern const UnitCommandType Land;
extern const UnitCommandType Load;
extern const UnitCommandType Unload;
extern const UnitCommandType Unload_All;
extern const UnitCommandType Unload_All_Position;
extern const UnitCommandType Right_Click_Position;
extern const UnitCommandType Right_Click_Unit;
extern const UnitCommandType Halt_Construction;
extern const UnitCommandType Cancel_Construction;
extern const UnitCommandType Cancel_Addon;
extern const UnitCommandType Cancel_Train;
extern const UnitCommandType Cancel_Train_Slot;
extern const UnitCommandType Cancel_Morph;
extern const UnitCommandType Cancel_Research;
extern const UnitCommandType Cancel_Upgrade;
extern const UnitCommandType Use_Tech;
extern const UnitCommandType Use_Tech_Position;
extern const UnitCommandType Use_Tech_Unit;
extern const UnitCommandType Place_COP;
extern const UnitCommandType None;
extern const UnitCommandType Unknown;
}
} | [
"[email protected]@26a4d94b-85da-9150-e52c-6e401ef01510"
]
| [
[
[
1,
86
]
]
]
|
dfee7988b10e7c74fb629ce0d55dc79a68e505ae | 4d3983366ea8a2886629d9a39536f0cd05edd001 | /src/squirrel/sqstate.cpp | 5d6c748f01f358dfc970c55861436a7d5fddd240 | []
| no_license | clteng5316/rodents | 033a06d5ad11928425a40203a497ea95e98ce290 | 7be0702d0ad61d9a07295029ba77d853b87aba64 | refs/heads/master | 2021-01-10T13:05:13.757715 | 2009-08-07T14:46:13 | 2009-08-07T14:46:13 | 36,857,795 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,052 | cpp | /*
see copyright notice in squirrel.h
*/
#include "sqpcheader.h"
#include "sqopcodes.h"
#include "sqvm.h"
#include "sqfuncproto.h"
#include "sqclosure.h"
#include "sqstring.h"
#include "sqtable.h"
#include "sqarray.h"
#include "squserdata.h"
#include "sqclass.h"
SQObjectPtr _null_;
SQObjectPtr _true_(true);
SQObjectPtr _false_(false);
SQObjectPtr _one_((SQInteger)1);
SQObjectPtr _minusone_((SQInteger)-1);
SQSharedState::SQSharedState()
{
_compilererrorhandler = NULL;
_printfunc = NULL;
_errorfunc = NULL;
_debuginfo = false;
_notifyallexceptions = false;
}
#define newsysstring(s) { \
_systemstrings->push_back(SQString::Create(this,s)); \
}
#define newmetamethod(s) { \
_metamethods->push_back(SQString::Create(this,s)); \
_table(_metamethodsmap)->NewSlot(_metamethods->back(),(SQInteger)(_metamethods->size()-1)); \
}
bool CompileTypemask(SQIntVec &res,const SQChar *typemask)
{
SQInteger i = 0;
SQInteger mask = 0;
while(typemask[i] != 0) {
switch(typemask[i]){
case 'o': mask |= _RT_NULL; break;
case 'i': mask |= _RT_INTEGER; break;
case 'f': mask |= _RT_FLOAT; break;
case 'n': mask |= (_RT_FLOAT | _RT_INTEGER); break;
case 's': mask |= _RT_STRING; break;
case 't': mask |= _RT_TABLE; break;
case 'a': mask |= _RT_ARRAY; break;
case 'u': mask |= _RT_USERDATA; break;
case 'c': mask |= (_RT_CLOSURE | _RT_NATIVECLOSURE); break;
case 'b': mask |= _RT_BOOL; break;
case 'g': mask |= _RT_GENERATOR; break;
case 'p': mask |= _RT_USERPOINTER; break;
case 'v': mask |= _RT_THREAD; break;
case 'x': mask |= _RT_INSTANCE; break;
case 'y': mask |= _RT_CLASS; break;
case 'r': mask |= _RT_WEAKREF; break;
case '.': mask = -1; res.push_back(mask); i++; mask = 0; continue;
case ' ': i++; continue; //ignores spaces
default:
return false;
}
i++;
if(typemask[i] == '|') {
i++;
if(typemask[i] == 0)
return false;
continue;
}
res.push_back(mask);
mask = 0;
}
return true;
}
SQTable *CreateDefaultDelegate(SQSharedState *ss,SQRegFunction *funcz)
{
SQInteger i=0;
SQTable *t=SQTable::Create(ss,0);
while(funcz[i].name!=0){
SQNativeClosure *nc = SQNativeClosure::Create(ss,funcz[i].f);
nc->_nparamscheck = funcz[i].nparamscheck;
nc->_name = SQString::Create(ss,funcz[i].name);
if(funcz[i].typemask && !CompileTypemask(nc->_typecheck,funcz[i].typemask))
return NULL;
t->NewSlot(SQString::Create(ss,funcz[i].name),nc);
i++;
}
return t;
}
void SQSharedState::Init()
{
_scratchpad=NULL;
_scratchpadsize=0;
#ifndef NO_GARBAGE_COLLECTOR
_gc_chain=NULL;
#endif
_stringtable = (StringTable*)SQ_MALLOC(sizeof(StringTable));
new (_stringtable) StringTable(this);
sq_new(_metamethods,SQObjectPtrVec);
sq_new(_systemstrings,SQObjectPtrVec);
sq_new(_types,SQObjectPtrVec);
_metamethodsmap = SQTable::Create(this,MT_LAST-1);
//adding type strings to avoid memory trashing
//types names
newsysstring(_SC("null"));
newsysstring(_SC("table"));
newsysstring(_SC("array"));
newsysstring(_SC("closure"));
newsysstring(_SC("string"));
newsysstring(_SC("userdata"));
newsysstring(_SC("integer"));
newsysstring(_SC("float"));
newsysstring(_SC("userpointer"));
newsysstring(_SC("function"));
newsysstring(_SC("generator"));
newsysstring(_SC("thread"));
newsysstring(_SC("class"));
newsysstring(_SC("instance"));
newsysstring(_SC("bool"));
//meta methods
newmetamethod(MM_ADD);
newmetamethod(MM_SUB);
newmetamethod(MM_MUL);
newmetamethod(MM_DIV);
newmetamethod(MM_UNM);
newmetamethod(MM_MODULO);
newmetamethod(MM_SET);
newmetamethod(MM_GET);
newmetamethod(MM_TYPEOF);
newmetamethod(MM_NEXTI);
newmetamethod(MM_CMP);
newmetamethod(MM_CALL);
newmetamethod(MM_CLONED);
newmetamethod(MM_NEWSLOT);
newmetamethod(MM_DELSLOT);
newmetamethod(MM_TOSTRING);
newmetamethod(MM_NEWMEMBER);
newmetamethod(MM_INHERITED);
_constructoridx = SQString::Create(this,_SC("constructor"));
_registry = SQTable::Create(this,0);
_consts = SQTable::Create(this,0);
_table_default_delegate = CreateDefaultDelegate(this,_table_default_delegate_funcz);
_array_default_delegate = CreateDefaultDelegate(this,_array_default_delegate_funcz);
_string_default_delegate = CreateDefaultDelegate(this,_string_default_delegate_funcz);
_number_default_delegate = CreateDefaultDelegate(this,_number_default_delegate_funcz);
_closure_default_delegate = CreateDefaultDelegate(this,_closure_default_delegate_funcz);
_generator_default_delegate = CreateDefaultDelegate(this,_generator_default_delegate_funcz);
_thread_default_delegate = CreateDefaultDelegate(this,_thread_default_delegate_funcz);
_class_default_delegate = CreateDefaultDelegate(this,_class_default_delegate_funcz);
_instance_default_delegate = CreateDefaultDelegate(this,_instance_default_delegate_funcz);
_weakref_default_delegate = CreateDefaultDelegate(this,_weakref_default_delegate_funcz);
}
SQSharedState::~SQSharedState()
{
_constructoridx = _null_;
_table(_registry)->Finalize();
_table(_consts)->Finalize();
_table(_metamethodsmap)->Finalize();
_registry = _null_;
_consts = _null_;
_metamethodsmap = _null_;
while(!_systemstrings->empty()) {
_systemstrings->back()=_null_;
_systemstrings->pop_back();
}
_thread(_root_vm)->Finalize();
_root_vm = _null_;
_table_default_delegate = _null_;
_array_default_delegate = _null_;
_string_default_delegate = _null_;
_number_default_delegate = _null_;
_closure_default_delegate = _null_;
_generator_default_delegate = _null_;
_thread_default_delegate = _null_;
_class_default_delegate = _null_;
_instance_default_delegate = _null_;
_weakref_default_delegate = _null_;
_refs_table.Finalize();
#ifndef NO_GARBAGE_COLLECTOR
SQCollectable *t = _gc_chain;
SQCollectable *nx = NULL;
while(t) {
t->_uiRef++;
t->Finalize();
nx = t->_next;
if(--t->_uiRef == 0)
t->Release();
t=nx;
}
assert(_gc_chain==NULL); //just to proove a theory
while(_gc_chain){
_gc_chain->_uiRef++;
_gc_chain->Release();
}
#endif
sq_delete(_types,SQObjectPtrVec);
sq_delete(_systemstrings,SQObjectPtrVec);
sq_delete(_metamethods,SQObjectPtrVec);
sq_delete(_stringtable,StringTable);
if(_scratchpad)SQ_FREE(_scratchpad,_scratchpadsize);
}
SQInteger SQSharedState::GetMetaMethodIdxByName(const SQObjectPtr &name)
{
if(type(name) != OT_STRING)
return -1;
SQObjectPtr ret;
if(_table(_metamethodsmap)->Get(name,ret)) {
return _integer(ret);
}
return -1;
}
#ifndef NO_GARBAGE_COLLECTOR
void SQSharedState::MarkObject(SQObjectPtr &o,SQCollectable **chain)
{
switch(type(o)){
case OT_TABLE:_table(o)->Mark(chain);break;
case OT_ARRAY:_array(o)->Mark(chain);break;
case OT_USERDATA:_userdata(o)->Mark(chain);break;
case OT_CLOSURE:_closure(o)->Mark(chain);break;
case OT_NATIVECLOSURE:_nativeclosure(o)->Mark(chain);break;
case OT_GENERATOR:_generator(o)->Mark(chain);break;
case OT_THREAD:_thread(o)->Mark(chain);break;
case OT_CLASS:_class(o)->Mark(chain);break;
case OT_INSTANCE:_instance(o)->Mark(chain);break;
default: break; //shutup compiler
}
}
SQInteger SQSharedState::CollectGarbage(SQVM *vm)
{
SQInteger n=0;
SQCollectable *tchain=NULL;
SQVM *vms = _thread(_root_vm);
vms->Mark(&tchain);
SQInteger x = _table(_thread(_root_vm)->_roottable)->CountUsed();
_refs_table.Mark(&tchain);
MarkObject(_registry,&tchain);
MarkObject(_consts,&tchain);
MarkObject(_metamethodsmap,&tchain);
MarkObject(_table_default_delegate,&tchain);
MarkObject(_array_default_delegate,&tchain);
MarkObject(_string_default_delegate,&tchain);
MarkObject(_number_default_delegate,&tchain);
MarkObject(_generator_default_delegate,&tchain);
MarkObject(_thread_default_delegate,&tchain);
MarkObject(_closure_default_delegate,&tchain);
MarkObject(_class_default_delegate,&tchain);
MarkObject(_instance_default_delegate,&tchain);
MarkObject(_weakref_default_delegate,&tchain);
SQCollectable *t = _gc_chain;
SQCollectable *nx = NULL;
while(t) {
t->_uiRef++;
t->Finalize();
nx = t->_next;
if(--t->_uiRef == 0)
t->Release();
t = nx;
n++;
}
t = tchain;
while(t) {
t->UnMark();
t = t->_next;
}
_gc_chain = tchain;
SQInteger z = _table(_thread(_root_vm)->_roottable)->CountUsed();
assert(z == x);
return n;
}
#endif
#ifndef NO_GARBAGE_COLLECTOR
void SQCollectable::AddToChain(SQCollectable **chain,SQCollectable *c)
{
c->_prev = NULL;
c->_next = *chain;
if(*chain) (*chain)->_prev = c;
*chain = c;
}
void SQCollectable::RemoveFromChain(SQCollectable **chain,SQCollectable *c)
{
if(c->_prev) c->_prev->_next = c->_next;
else *chain = c->_next;
if(c->_next)
c->_next->_prev = c->_prev;
c->_next = NULL;
c->_prev = NULL;
}
#endif
SQChar* SQSharedState::GetScratchPad(SQInteger size)
{
SQInteger newsize;
if(size>0) {
if(_scratchpadsize < size) {
newsize = size + (size>>1);
_scratchpad = (SQChar *)SQ_REALLOC(_scratchpad,_scratchpadsize,newsize);
_scratchpadsize = newsize;
}else if(_scratchpadsize >= (size<<5)) {
newsize = _scratchpadsize >> 1;
_scratchpad = (SQChar *)SQ_REALLOC(_scratchpad,_scratchpadsize,newsize);
_scratchpadsize = newsize;
}
}
return _scratchpad;
}
RefTable::RefTable()
{
AllocNodes(4);
}
void RefTable::Finalize()
{
RefNode *nodes = _nodes;
for(SQUnsignedInteger n = 0; n < _numofslots; n++) {
nodes->obj = _null_;
nodes++;
}
}
RefTable::~RefTable()
{
SQ_FREE(_buckets,(_numofslots * sizeof(RefNode *)) + (_numofslots * sizeof(RefNode)));
}
#ifndef NO_GARBAGE_COLLECTOR
void RefTable::Mark(SQCollectable **chain)
{
RefNode *nodes = (RefNode *)_nodes;
for(SQUnsignedInteger n = 0; n < _numofslots; n++) {
if(type(nodes->obj) != OT_NULL) {
SQSharedState::MarkObject(nodes->obj,chain);
}
nodes++;
}
}
#endif
void RefTable::AddRef(SQObject &obj)
{
SQHash mainpos;
RefNode *prev;
RefNode *ref = Get(obj,mainpos,&prev,true);
ref->refs++;
}
SQBool RefTable::Release(SQObject &obj)
{
SQHash mainpos;
RefNode *prev;
RefNode *ref = Get(obj,mainpos,&prev,false);
if(ref) {
if(--ref->refs == 0) {
SQObjectPtr o = ref->obj;
if(prev) {
prev->next = ref->next;
}
else {
_buckets[mainpos] = ref->next;
}
ref->next = _freelist;
_freelist = ref;
_slotused--;
ref->obj = _null_;
//<<FIXME>>test for shrink?
return SQTrue;
}
}
else {
assert(0);
}
return SQFalse;
}
void RefTable::Resize(SQUnsignedInteger size)
{
RefNode **oldbucks = _buckets;
RefNode *t = _nodes;
SQUnsignedInteger oldnumofslots = _numofslots;
AllocNodes(size);
//rehash
SQUnsignedInteger nfound = 0;
for(SQUnsignedInteger n = 0; n < oldnumofslots; n++) {
if(type(t->obj) != OT_NULL) {
//add back;
assert(t->refs != 0);
RefNode *nn = Add(::HashObj(t->obj)&(_numofslots-1),t->obj);
nn->refs = t->refs;
t->obj = _null_;
nfound++;
}
t++;
}
assert(nfound == oldnumofslots);
SQ_FREE(oldbucks,(oldnumofslots * sizeof(RefNode *)) + (oldnumofslots * sizeof(RefNode)));
}
RefTable::RefNode *RefTable::Add(SQHash mainpos,SQObject &obj)
{
RefNode *t = _buckets[mainpos];
RefNode *newnode = _freelist;
newnode->obj = obj;
_buckets[mainpos] = newnode;
_freelist = _freelist->next;
newnode->next = t;
assert(newnode->refs == 0);
_slotused++;
return newnode;
}
RefTable::RefNode *RefTable::Get(SQObject &obj,SQHash &mainpos,RefNode **prev,bool add)
{
RefNode *ref;
mainpos = ::HashObj(obj)&(_numofslots-1);
*prev = NULL;
for (ref = _buckets[mainpos]; ref; ) {
if(_rawval(ref->obj) == _rawval(obj) && type(ref->obj) == type(obj))
break;
*prev = ref;
ref = ref->next;
}
if(ref == NULL && add) {
if(_numofslots == _slotused) {
assert(_freelist == 0);
Resize(_numofslots*2);
mainpos = ::HashObj(obj)&(_numofslots-1);
}
ref = Add(mainpos,obj);
}
return ref;
}
void RefTable::AllocNodes(SQUnsignedInteger size)
{
RefNode **bucks;
RefNode *nodes;
bucks = (RefNode **)SQ_MALLOC((size * sizeof(RefNode *)) + (size * sizeof(RefNode)));
nodes = (RefNode *)&bucks[size];
RefNode *temp = nodes;
SQUnsignedInteger n;
for(n = 0; n < size - 1; n++) {
bucks[n] = NULL;
temp->refs = 0;
new (&temp->obj) SQObjectPtr;
temp->next = temp+1;
temp++;
}
bucks[n] = NULL;
temp->refs = 0;
new (&temp->obj) SQObjectPtr;
temp->next = NULL;
_freelist = nodes;
_nodes = nodes;
_buckets = bucks;
_slotused = 0;
_numofslots = size;
}
//////////////////////////////////////////////////////////////////////////
//StringTable
/*
* The following code is based on Lua 4.0 (Copyright 1994-2002 Tecgraf, PUC-Rio.)
* http://www.lua.org/copyright.html#4
* http://www.lua.org/source/4.0.1/src_lstring.c.html
*/
StringTable::StringTable(SQSharedState *ss)
{
_sharedstate = ss;
AllocNodes(4);
_slotused = 0;
}
StringTable::~StringTable()
{
SQ_FREE(_strings,sizeof(SQString*)*_numofslots);
_strings = NULL;
}
void StringTable::AllocNodes(SQInteger size)
{
_numofslots = size;
_strings = (SQString**)SQ_MALLOC(sizeof(SQString*)*_numofslots);
memset(_strings,0,sizeof(SQString*)*_numofslots);
}
SQString *StringTable::Add(const SQChar *news,SQInteger len)
{
if(len<0)
len = (SQInteger)scstrlen(news);
SQHash h = ::_hashstr(news,len)&(_numofslots-1);
SQString *s;
for (s = _strings[h]; s; s = s->_next){
if(s->_len == len && (!memcmp(news,s->_val,rsl(len))))
return s; //found
}
SQString *t=(SQString *)SQ_MALLOC(rsl(len)+sizeof(SQString));
new (t) SQString;
t->_sharedstate = _sharedstate;
memcpy(t->_val,news,rsl(len));
t->_val[len] = _SC('\0');
t->_len = len;
t->_hash = ::_hashstr(news,len);
t->_next = _strings[h];
_strings[h] = t;
_slotused++;
if (_slotused > _numofslots) /* too crowded? */
Resize(_numofslots*2);
return t;
}
void StringTable::Resize(SQInteger size)
{
SQInteger oldsize=_numofslots;
SQString **oldtable=_strings;
AllocNodes(size);
for (SQInteger i=0; i<oldsize; i++){
SQString *p = oldtable[i];
while(p){
SQString *next = p->_next;
SQHash h = p->_hash&(_numofslots-1);
p->_next = _strings[h];
_strings[h] = p;
p = next;
}
}
SQ_FREE(oldtable,oldsize*sizeof(SQString*));
}
void StringTable::Remove(SQString *bs)
{
SQString *s;
SQString *prev=NULL;
SQHash h = bs->_hash&(_numofslots - 1);
for (s = _strings[h]; s; ){
if(s == bs){
if(prev)
prev->_next = s->_next;
else
_strings[h] = s->_next;
_slotused--;
SQInteger slen = s->_len;
s->~SQString();
SQ_FREE(s,sizeof(SQString) + rsl(slen));
return;
}
prev = s;
s = s->_next;
}
assert(0);//if this fail something is wrong
}
| [
"itagaki.takahiro@fad0b036-4cad-11de-8d8d-752d95cf3e3c"
]
| [
[
[
1,
576
]
]
]
|
918c8abf4b32bbeaa2e8f565aa1a8d9576712d89 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SETools/SEWavToSewf/SEWaveParser.h | b899208e5ebd48c7e1f65e8026170fb11eb14389 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,614 | 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
/*
* Copyright (c) 2006, Creative Labs Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Creative Labs Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*/
#ifndef Swing_WaveParser_H
#define Swing_WaveParser_H
#include <windows.h>
#include <stdio.h>
#include "SEWave.h"
#define MAX_NUM_WAVEID 1024
//----------------------------------------------------------------------------
enum WAVEFILETYPE
{
WF_EX = 1,
WF_EXT = 2
};
//----------------------------------------------------------------------------
enum WAVERESULT
{
WR_OK = 0,
WR_INVALIDFILENAME = - 1,
WR_BADWAVEFILE = - 2,
WR_INVALIDPARAM = - 3,
WR_INVALIDWAVEID = - 4,
WR_NOTSUPPORTEDYET = - 5,
WR_WAVEMUSTBEMONO = - 6,
WR_WAVEMUSTBEWAVEFORMATPCM = - 7,
WR_WAVESMUSTHAVESAMEBITRESOLUTION = - 8,
WR_WAVESMUSTHAVESAMEFREQUENCY = - 9,
WR_WAVESMUSTHAVESAMEBITRATE = -10,
WR_WAVESMUSTHAVESAMEBLOCKALIGNMENT = -11,
WR_OFFSETOUTOFDATARANGE = -12,
WR_FILEERROR = -13,
WR_OUTOFMEMORY = -14,
WR_INVALIDSPEAKERPOS = -15,
WR_INVALIDWAVEFILETYPE = -16,
WR_NOTWAVEFORMATEXTENSIBLEFORMAT = -17
};
//----------------------------------------------------------------------------
#ifndef _WAVEFORMATEX_
#define _WAVEFORMATEX_
typedef struct tWAVEFORMATEX
{
WORD wFormatTag;
WORD nChannels;
DWORD nSamplesPerSec;
DWORD nAvgBytesPerSec;
WORD nBlockAlign;
WORD wBitsPerSample;
WORD cbSize;
} WAVEFORMATEX;
#endif /* _WAVEFORMATEX_ */
//----------------------------------------------------------------------------
#ifndef _WAVEFORMATEXTENSIBLE_
#define _WAVEFORMATEXTENSIBLE_
typedef struct {
WAVEFORMATEX Format;
union {
WORD wValidBitsPerSample; /* bits of precision */
WORD wSamplesPerBlock; /* valid if wBitsPerSample==0 */
WORD wReserved; /* If neither applies, set to zero. */
} Samples;
DWORD dwChannelMask; /* which channels are */
/* present in stream */
GUID SubFormat;
} WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;
#endif // !_WAVEFORMATEXTENSIBLE_
//----------------------------------------------------------------------------
typedef struct
{
WAVEFILETYPE wfType;
// for non-WAVEFORMATEXTENSIBLE wavefiles,
// the header is stored in the Format member of wfEXT.
WAVEFORMATEXTENSIBLE wfEXT;
char *pData;
unsigned int uiDataSize;
FILE *pFile;
unsigned int uiDataOffset;
} WAVEFILEINFO, *LPWAVEFILEINFO;
//----------------------------------------------------------------------------
// OpenAL提供的回调函数指针类型定义.
typedef int (__cdecl *PFNALGETENUMVALUE)( const char *szEnumName );
// wave id类型定义.
typedef int WAVEID;
//----------------------------------------------------------------------------
// 说明:
// 作者:Sun Che
// 时间:20090622
//----------------------------------------------------------------------------
class WaveParser
{
public:
WaveParser(void);
virtual ~WaveParser(void);
WAVERESULT LoadWaveFile(const char* acFileName, WAVEID* pWaveID);
WAVERESULT OpenWaveFile(const char* acFileName, WAVEID* pWaveID);
WAVERESULT ReadWaveData(WAVEID WaveID, void* pData,
unsigned int uiDataSize, unsigned int* puiBytesWritten);
WAVERESULT SetWaveDataOffset(WAVEID WaveID, unsigned int uiOffset);
WAVERESULT GetWaveDataOffset(WAVEID WaveID, unsigned int* puiOffset);
WAVERESULT GetWaveType(WAVEID WaveID, WAVEFILETYPE* pwfType);
WAVERESULT GetWaveFormatExHeader(WAVEID WaveID, WAVEFORMATEX* pWFEX);
WAVERESULT GetWaveFormatExtensibleHeader(WAVEID WaveID,
WAVEFORMATEXTENSIBLE* pWFEXT);
WAVERESULT GetWaveData(WAVEID WaveID, void** ppAudioData);
WAVERESULT GetWaveSize(WAVEID WaveID, unsigned int* puiDataSize);
WAVERESULT GetWaveFrequency(WAVEID WaveID, unsigned int* puiFrequency);
// support for OpenAL wave format.
WAVERESULT GetWaveALBufferFormat(WAVEID WaveID,
PFNALGETENUMVALUE pfnGetEnumValue, unsigned int* puiFormat);
// support for Swing Engine wave format.
WAVERESULT GetWaveSEWaveFormat(WAVEID WaveID,
Swing::SEWave::FormatMode* peFormat);
WAVERESULT DeleteWaveFile(WAVEID WaveID);
char* GetErrorString(WAVERESULT wr, char* acErrorString,
unsigned int uiSizeOfErrorString);
bool IsWaveID(WAVEID WaveID);
private:
WAVERESULT ParseFile(const char* acFileName, LPWAVEFILEINFO pWaveInfo);
WAVEID InsertWaveID(LPWAVEFILEINFO pWaveFileInfo);
LPWAVEFILEINFO m_WaveIDs[MAX_NUM_WAVEID];
};
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
170
]
]
]
|
a56b8056a5ff6d5e0ca4230f9b860f446f74825a | 842997c28ef03f8deb3422d0bb123c707732a252 | /src/moaicore/MOAIProp2D.cpp | f4a6faafd05f1d4f29383a7addc91670324fa56b | []
| no_license | bjorn/moai-beta | e31f600a3456c20fba683b8e39b11804ac88d202 | 2f06a454d4d94939dc3937367208222735dd164f | refs/heads/master | 2021-01-17T11:46:46.018377 | 2011-06-10T07:33:55 | 2011-06-10T07:33:55 | 1,837,561 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,754 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <moaicore/MOAIDeck.h>
#include <moaicore/MOAIDeckRemapper.h>
#include <moaicore/MOAIDebugLines.h>
#include <moaicore/MOAIGrid.h>
#include <moaicore/MOAILayoutFrame.h>
#include <moaicore/MOAILogMessages.h>
#include <moaicore/MOAIPartition.h>
#include <moaicore/MOAIProp2D.h>
#include <moaicore/MOAIShader.h>
#include <moaicore/MOAISurfaceSampler2D.h>
//================================================================//
// local
//================================================================//
//----------------------------------------------------------------//
/** @name getGrid
@text Get the grid currently connected to the prop.
@in MOAIProp2D self
@out MOAIGrid grid Current grid or nil.
*/
int MOAIProp2D::_getGrid ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "U" )
if ( self->mGrid ) {
self->mGrid->PushLuaUserdata ( state );
return 1;
}
return 0;
}
//----------------------------------------------------------------//
/** @name getIndex
@text Gets the value of the deck indexer.
@in MOAIProp2D self
@out number index
*/
int MOAIProp2D::_getIndex ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "U" )
lua_pushnumber ( state, self->mIndex );
return 1;
}
//----------------------------------------------------------------//
/** @name inside
@text Returns true if this prop is under the given world space point.
@in MOAIProp2D self
@in number x
@in number y
@out boolean isInside
*/
int MOAIProp2D::_inside ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "UNN" )
USVec2D vec;
vec.mX = state.GetValue < float >( 2, 0.0f );
vec.mY = state.GetValue < float >( 3, 0.0f );
bool result = self->Inside ( vec );
lua_pushboolean ( state, result );
return 1;
}
//----------------------------------------------------------------//
/** @name setDeck
@text Sets or clears the deck to be indexed by the prop.
@in MOAIProp2D self
@opt MOAIDeck deck Default value is nil.
@out nil
*/
int MOAIProp2D::_setDeck ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "U" )
self->mDeck = state.GetLuaObject < MOAIDeck >( 2 );
if ( self->mDeck ) {
self->SetMask ( self->mDeck->GetContentMask ());
}
else {
self->SetMask ( 0 );
}
return 0;
}
//----------------------------------------------------------------//
/** @name setFrame
@text Sets the fitting frame of the prop.
@overload Clear the fitting frame.
@in MOAIProp2D self
@out nil
@overload Set the fitting frame.
@in MOAIProp2D self
@in number xMin
@in number yMin
@in number xMax
@in number yMax
@out nil
*/
int MOAIProp2D::_setFrame ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "UNNNN" )
if ( state.CheckParams ( 2, "NNNN" )) {
float x0 = state.GetValue < float >( 2, 0.0f );
float y0 = state.GetValue < float >( 3, 0.0f );
float x1 = state.GetValue < float >( 4, 0.0f );
float y1 = state.GetValue < float >( 5, 0.0f );
self->mFrame.Init ( x0, y0, x1, y1 );
self->mFitToFrame = true;
}
else {
self->mFitToFrame = false;
}
self->ScheduleUpdate ();
return 0;
}
//----------------------------------------------------------------//
/** @name setGrid
@text Sets or clears the prop's grid indexer. The grid indexer (if any)
will override the standard indexer.
@in MOAIProp2D self
@opt MOAIGrid grid Default value is nil.
@out nil
*/
int MOAIProp2D::_setGrid ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "U" )
MOAIGrid* grid = state.GetLuaObject < MOAIGrid >( 2 );
if ( !grid ) return 0;
self->mGrid = grid;
return 0;
}
//----------------------------------------------------------------//
/** @name setGridScale
@text Scale applied to deck items before rendering to grid cell.
@in MOAIProp2D self
@opt number xScale Default value is 1.
@opt number yScale Default value is 1.
@out nil
*/
int MOAIProp2D::_setGridScale ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "U" )
self->mGridScale.mX = state.GetValue < float >( 2, 1.0f );
self->mGridScale.mY = state.GetValue < float >( 3, 1.0f );
return 0;
}
//----------------------------------------------------------------//
/** @name setIndex
@text Set the prop's index into its deck.
@in MOAIProp2D self
@opt number index Default value is 1.
@out nil
*/
int MOAIProp2D::_setIndex ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "U" )
self->mIndex = state.GetValue < u32 >( 2, 1 );
self->ScheduleUpdate ();
return 0;
}
//----------------------------------------------------------------//
// TODO: doxygen
int MOAIProp2D::_setRemapper ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "U" )
MOAIDeckRemapper* remapper = state.GetLuaObject < MOAIDeckRemapper >( 2 );
self->SetDependentMember < MOAIDeckRemapper >( self->mRemapper, remapper );
return 0;
}
//----------------------------------------------------------------//
/** @name setRepeat
@text Repeats a grid indexer along X or Y. Only used when a grid
is attached.
@in MOAIProp2D self
@opt boolean repeatX Default value is true.
@opt boolean repeatY Default value is repeatX.
@out nil
*/
int MOAIProp2D::_setRepeat ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "U" )
bool repeatX = state.GetValue < bool >( 2, true );
bool repeatY = state.GetValue < bool >( 3, repeatX );
self->mRepeat = 0;
self->mRepeat |= repeatX ? REPEAT_X : 0;
self->mRepeat |= repeatY ? REPEAT_Y : 0;
return 0;
}
//----------------------------------------------------------------//
/** @name setShader
@text Sets or clears the prop's shader. The prop's shader takes
precedence over any shader specified by the deck or its
elements.
@in MOAIProp2D self
@opt MOAIShader shader Default value is nil.
@out nil
*/
int MOAIProp2D::_setShader ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "U" )
MOAIShader* shader = state.GetLuaObject < MOAIShader >( 2 );
self->SetDependentMember < MOAIShader >( self->mShader, shader );
return 0;
}
//----------------------------------------------------------------//
/** @name setUVTransform
@text Sets or clears the prop's UV transform.
@in MOAIProp2D self
@opt MOAITransformBase transform Default value is nil.
@out nil
*/
int MOAIProp2D::_setUVTransform ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIProp2D, "U" )
MOAITransformBase* transform = state.GetLuaObject < MOAITransformBase >( 2 );
self->SetDependentMember < MOAITransformBase >( self->mUVTransform, transform );
return 0;
}
//================================================================//
// MOAIProp2D
//================================================================//
//----------------------------------------------------------------//
bool MOAIProp2D::ApplyAttrOp ( u32 attrID, USAttrOp& attrOp ) {
if ( MOAIProp2DAttr::Check ( attrID )) {
attrID = UNPACK_ATTR ( attrID );
if ( attrID == ATTR_INDEX ) {
this->mIndex = attrOp.Op ( this->mIndex );
return true;
}
}
if ( MOAIColor::ApplyAttrOp ( attrID, attrOp )) return true;
return MOAITransform::ApplyAttrOp ( attrID, attrOp );
}
//----------------------------------------------------------------//
bool MOAIProp2D::BindDeck () {
if ( this->mDeck ) {
return this->mDeck->Bind ();
}
return false;
}
//----------------------------------------------------------------//
void MOAIProp2D::Draw () {
if ( !this->BindDeck ()) return;
USDrawBuffer& drawbuffer = USDrawBuffer::Get ();
if ( this->mUVTransform ) {
USAffine2D uvMtx = this->mUVTransform->GetLocalToWorldMtx ();
drawbuffer.SetUVTransform ( uvMtx );
}
this->LoadShader ();
if ( this->mGrid ) {
USCellCoord c0;
USCellCoord c1;
this->GetBoundsInView ( c0, c1 );
this->mDeck->Draw ( this->GetLocalToWorldMtx (), *this->mGrid, this->mRemapper, this->mGridScale, c0, c1 );
}
else {
this->mDeck->Draw ( this->GetLocalToWorldMtx (), this->mIndex, this->mRemapper );
}
// TODO
//MOAILayoutFrame* parentFrame = USCast < MOAILayoutFrame >( this->mParent );
//if ( parentFrame ) {
// drawbuffer.SetScissorRect ();
//}
}
//----------------------------------------------------------------//
void MOAIProp2D::DrawDebug () {
MOAIDebugLines& debugLines = MOAIDebugLines::Get ();
if ( this->mDeck ) {
if ( debugLines.Bind ( MOAIDebugLines::PROP_MODEL_BOUNDS )) {
debugLines.SetWorldMtx ( this->GetLocalToWorldMtx ());
debugLines.SetPenSpace ( MOAIDebugLines::MODEL_SPACE );
USRect bounds = this->mDeck->GetBounds ( this->mIndex, this->mRemapper );
debugLines.DrawRect ( bounds );
if ( this->mGrid ) {
debugLines.SetPenColor ( 0x40ffffff );
debugLines.SetPenWidth ( 2 );
USCellCoord c0;
USCellCoord c1;
this->GetBoundsInView ( c0, c1 );
this->mDeck->DrawDebug ( this->GetLocalToWorldMtx (), *this->mGrid, this->mRemapper, this->mGridScale, c0, c1 );
}
}
}
if ( debugLines.Bind ( MOAIDebugLines::PROP_WORLD_BOUNDS )) {
debugLines.SetPenSpace ( MOAIDebugLines::WORLD_SPACE );
debugLines.DrawRect ( this->GetBounds ());
}
debugLines.SetPenColor ( 0x40ffffff );
debugLines.SetPenWidth ( 2 );
if ( this->mDeck ) {
this->mDeck->DrawDebug ( this->GetLocalToWorldMtx (), this->mIndex, this->mRemapper );
}
if ( debugLines.IsVisible ( MOAIDebugLines::PARTITION_CELLS ) || debugLines.IsVisible ( MOAIDebugLines::PARTITION_PADDED_CELLS )) {
debugLines.SetWorldMtx ();
USRect cellRect;
USRect paddedRect;
if ( this->GetCellRect ( &cellRect, &paddedRect )) {
if ( cellRect.Area () != 0.0f ) {
if ( debugLines.Bind ( MOAIDebugLines::PARTITION_CELLS )) {
debugLines.SetPenSpace ( MOAIDebugLines::PARTITION_CELLS );
debugLines.DrawRect ( cellRect );
}
}
if ( paddedRect.Area () != 0.0f ) {
if ( debugLines.Bind ( MOAIDebugLines::PARTITION_PADDED_CELLS )) {
debugLines.SetPenSpace ( MOAIDebugLines::PARTITION_PADDED_CELLS );
debugLines.DrawRect ( paddedRect );
}
}
}
}
}
//----------------------------------------------------------------//
void MOAIProp2D::GatherSurfaces ( MOAISurfaceSampler2D& sampler ) {
if ( !this->mDeck ) return;
sampler.SetSourcePrim ( this );
if ( this->mGrid ) {
USRect localRect = sampler.GetLocalRect ();
USCellCoord c0;
USCellCoord c1;
this->GetBoundsInRect ( localRect, c0, c1 );
this->mDeck->GatherSurfaces ( *this->mGrid, this->mRemapper, this->mGridScale, c0, c1, sampler );
}
else {
this->mDeck->GatherSurfaces ( this->mIndex, this->mRemapper, sampler );
}
}
//----------------------------------------------------------------//
void MOAIProp2D::GetBoundsInRect ( const USRect& rect, USCellCoord& c0, USCellCoord& c1 ) {
if ( this->mGrid ) {
c0 = this->mGrid->GetCellCoord ( rect.mXMin, rect.mYMin );
c1 = this->mGrid->GetCellCoord ( rect.mXMax, rect.mYMax );
if ( !( this->mRepeat & REPEAT_X )) {
c0 = this->mGrid->ClampX ( c0 );
c1 = this->mGrid->ClampX ( c1 );
}
if ( !( this->mRepeat & REPEAT_Y )) {
c0 = this->mGrid->ClampY ( c0 );
c1 = this->mGrid->ClampY ( c1 );
}
}
else {
c0.Init ( 0, 0 );
c1.Init ( 0, 0 );
}
}
//----------------------------------------------------------------//
void MOAIProp2D::GetBoundsInView ( USCellCoord& c0, USCellCoord& c1 ) {
const USAffine2D& invWorldMtx = this->GetWorldToLocalMtx ();
// view quad in world space
USViewQuad viewQuad;
viewQuad.Init ();
viewQuad.Transform ( invWorldMtx );
USRect viewRect = viewQuad.mBounds;
viewRect.Bless ();
this->GetBoundsInRect ( viewRect, c0, c1 );
}
//----------------------------------------------------------------//
USColorVec MOAIProp2D::GetColorTrait () {
return this->mColor;
}
//----------------------------------------------------------------//
USRect* MOAIProp2D::GetFrameTrait () {
return &this->mFrame;
}
//----------------------------------------------------------------//
MOAIShader* MOAIProp2D::GetShaderTrait () {
return this->mShader;
}
//----------------------------------------------------------------//
u32 MOAIProp2D::GetLocalFrame ( USRect& frame ) {
if ( this->mGrid ) {
frame = this->mGrid->GetBounds ();
return this->mRepeat ? BOUNDS_GLOBAL : BOUNDS_OK;
}
else if ( this->mDeck ) {
frame = this->mDeck->GetBounds ( this->mIndex, this->mRemapper );
return BOUNDS_OK;
}
return BOUNDS_EMPTY;
}
//----------------------------------------------------------------//
bool MOAIProp2D::Inside ( USVec2D vec ) {
const USAffine2D& worldToLocal = this->GetWorldToLocalMtx ();
worldToLocal.Transform ( vec );
if ( this->mFitToFrame ) {
return this->mFrame.Contains ( vec );
}
USRect rect;
u32 status = this->GetLocalFrame ( rect );
if ( status == BOUNDS_GLOBAL ) return true;
if ( status == BOUNDS_EMPTY ) return false;
return rect.Contains ( vec );
}
//----------------------------------------------------------------//
MOAIOverlapPrim2D* MOAIProp2D::IsOverlapPrim2D () {
return 0;
}
//----------------------------------------------------------------//
void MOAIProp2D::LoadShader () {
USDrawBuffer& drawbuffer = USDrawBuffer::Get ();
if ( this->mShader ) {
this->mShader->Bind ();
USColorVec color = drawbuffer.GetPenColor ();
color.Modulate ( this->mColor );
drawbuffer.SetPenColor ( color );
}
else {
drawbuffer.SetPenColor ( this->mColor );
drawbuffer.SetBlendMode ( GL_ONE, GL_ONE_MINUS_SRC_ALPHA );
}
// TODO
//MOAILayoutFrame* parent = USCast < MOAILayoutFrame >( this->mParent );
//if ( parent ) {
// USRect scissorRect = parent->GetScissorRect ();
// drawbuffer.SetScissorRect ( scissorRect );
//}
//else {
drawbuffer.SetScissorRect ();
//}
}
//----------------------------------------------------------------//
MOAIProp2D::MOAIProp2D () :
mIndex( 1 ),
mRepeat ( 0 ),
mGridScale ( 1.0f, 1.0f ),
mFitToFrame ( false ) {
RTTI_BEGIN
RTTI_EXTEND ( MOAIProp )
RTTI_EXTEND ( MOAIColor )
RTTI_END
this->mColor.Set ( 1.0f, 1.0f, 1.0f, 1.0f );
this->mFrame.Init ( 0.0f, 0.0f, 0.0f, 0.0f );
}
//----------------------------------------------------------------//
MOAIProp2D::~MOAIProp2D () {
}
//----------------------------------------------------------------//
void MOAIProp2D::OnDepNodeUpdate () {
this->mColor = *this;
USRect rect;
rect.Init ( 0.0f, 0.0f, 0.0f, 0.0f );
u32 frameStatus = this->GetLocalFrame ( rect );
if ( rect.Area () == 0.0f ) {
frameStatus = BOUNDS_EMPTY;
}
USVec2D offset ( 0.0f, 0.0f );
USVec2D stretch ( 1.0f, 1.0f );
// select the frame
USRect frame = this->mFrame;
if ( this->mTraitSource ) {
if ( this->mTraitMask & INHERIT_COLOR ) {
this->mColor.Modulate ( this->mTraitSource->GetColorTrait ());
}
if ( this->mTraitMask & INHERIT_FRAME ) {
USRect* frameTrait = this->mTraitSource->GetFrameTrait ();
if ( frameTrait ) {
frame = *frameTrait;
}
}
if ( this->mTraitMask & INHERIT_PARTITION ) {
MOAIPartition* partition = this->mTraitSource->GetPartitionTrait ();
if ( partition ) {
partition->InsertProp ( *this );
}
}
if ( this->mTraitMask & INHERIT_SHADER ) {
this->mShader = this->mTraitSource->GetShaderTrait ();
}
}
if (( this->mTraitMask & INHERIT_FRAME ) || this->mFitToFrame ) {
// and check if the target frame is empty, too
if ( frame.Area () == 0.0f ) {
frameStatus = BOUNDS_EMPTY;
}
// compute the scale and offset (if any)
if ( frameStatus != BOUNDS_EMPTY ) {
stretch.mX = frame.Width () / rect.Width ();
stretch.mY = frame.Height () / rect.Height ();
offset.mX = frame.mXMin - ( rect.mXMin * stretch.mX );
offset.mY = frame.mYMin - ( rect.mYMin * stretch.mY );
}
}
// inherit parent and offset transforms (and compute the inverse)
this->BuildTransforms ( offset.mX, offset.mY, stretch.mX, stretch.mY );
// update the prop location in the partition
// use the local frame; world transform will match it to target frame
switch ( frameStatus ) {
case BOUNDS_EMPTY:
case BOUNDS_GLOBAL: {
this->UpdateBounds ( frameStatus );
break;
}
case BOUNDS_OK: {
this->mLocalToWorldMtx.Transform ( rect );
this->UpdateBounds ( rect, frameStatus );
break;
}
}
}
//----------------------------------------------------------------//
void MOAIProp2D::RegisterLuaClass ( USLuaState& state ) {
MOAIProp::RegisterLuaClass ( state );
MOAIColor::RegisterLuaClass ( state );
state.SetField ( -1, "INHERIT_COLOR", ( u32 )INHERIT_COLOR );
state.SetField ( -1, "INHERIT_FRAME", ( u32 )INHERIT_FRAME );
state.SetField ( -1, "INHERIT_PARTITION", ( u32 )INHERIT_PARTITION );
state.SetField ( -1, "ATTR_INDEX", MOAIProp2DAttr::Pack ( ATTR_INDEX ));
}
//----------------------------------------------------------------//
void MOAIProp2D::RegisterLuaFuncs ( USLuaState& state ) {
MOAIProp::RegisterLuaFuncs ( state );
MOAIColor::RegisterLuaFuncs ( state );
luaL_Reg regTable [] = {
{ "getGrid", _getGrid },
{ "getIndex", _getIndex },
{ "inside", _inside },
{ "setDeck", _setDeck },
{ "setFrame", _setFrame },
{ "setGrid", _setGrid },
{ "setGridScale", _setGridScale },
{ "setIndex", _setIndex },
{ "setRemapper", _setRemapper },
{ "setRepeat", _setRepeat },
{ "setShader", _setShader },
{ "setUVTransform", _setUVTransform },
{ NULL, NULL }
};
luaL_register ( state, 0, regTable );
}
//----------------------------------------------------------------//
void MOAIProp2D::SerializeIn ( USLuaState& state, USLuaSerializer& serializer ) {
this->mDeck = serializer.GetRefField < MOAIDeck >( state, -1, "mDeck" );
this->mGrid = serializer.GetRefField < MOAIGrid >( state, -1, "mGrid" );
}
//----------------------------------------------------------------//
void MOAIProp2D::SerializeOut ( USLuaState& state, USLuaSerializer& serializer ) {
serializer.SetRefField ( state, -1, "mDeck", this->mDeck );
serializer.SetRefField ( state, -1, "mGrid", this->mGrid );
}
//----------------------------------------------------------------//
STLString MOAIProp2D::ToString () {
return "";
}
| [
"[email protected]",
"Patrick@agile.(none)",
"[email protected]"
]
| [
[
[
1,
5
],
[
7,
10
],
[
12,
82
],
[
84,
98
],
[
100,
100
],
[
114,
117
],
[
119,
119
],
[
131,
131
],
[
133,
145
],
[
147,
155
],
[
174,
190
],
[
202,
237
],
[
241,
248
],
[
250,
253
],
[
257,
265
],
[
267,
267
],
[
272,
272
],
[
275,
275
],
[
279,
305
],
[
308,
309
],
[
311,
312
],
[
314,
315
],
[
321,
328
],
[
330,
333
],
[
335,
341
],
[
344,
345
],
[
347,
350
],
[
352,
352
],
[
354,
359
],
[
361,
364
],
[
367,
398
],
[
401,
402
],
[
404,
405
],
[
407,
410
],
[
412,
414
],
[
417,
418
],
[
421,
423
],
[
426,
435
],
[
437,
450
],
[
469,
478
],
[
480,
490
],
[
503,
516
],
[
521,
522
],
[
524,
526
],
[
534,
534
],
[
536,
541
],
[
544,
546
],
[
548,
549
],
[
551,
560
],
[
566,
566
],
[
568,
574
],
[
582,
582
],
[
604,
604
],
[
609,
609
],
[
619,
632
],
[
635,
643
],
[
649,
649
],
[
651,
656
],
[
658,
665
],
[
667,
667
],
[
669,
697
]
],
[
[
6,
6
],
[
11,
11
],
[
83,
83
],
[
99,
99
],
[
101,
113
],
[
118,
118
],
[
120,
130
],
[
132,
132
],
[
146,
146
],
[
191,
201
],
[
238,
240
],
[
249,
249
],
[
254,
256
],
[
266,
266
],
[
268,
271
],
[
273,
274
],
[
276,
278
],
[
310,
310
],
[
313,
313
],
[
316,
320
],
[
334,
334
],
[
346,
346
],
[
360,
360
],
[
403,
403
],
[
406,
406
],
[
451,
468
],
[
479,
479
],
[
492,
493
],
[
495,
502
],
[
517,
520
],
[
523,
523
],
[
527,
533
],
[
535,
535
],
[
543,
543
],
[
547,
547
],
[
550,
550
],
[
561,
565
],
[
567,
567
],
[
575,
581
],
[
583,
603
],
[
605,
608
],
[
610,
618
],
[
633,
634
],
[
644,
648
],
[
650,
650
],
[
657,
657
],
[
668,
668
]
],
[
[
156,
173
],
[
306,
307
],
[
329,
329
],
[
342,
343
],
[
351,
351
],
[
353,
353
],
[
365,
366
],
[
399,
400
],
[
411,
411
],
[
415,
416
],
[
419,
420
],
[
424,
425
],
[
436,
436
],
[
491,
491
],
[
494,
494
],
[
542,
542
],
[
666,
666
]
]
]
|
5d2c134f6aa8741c86f00ab13e39b02bef5c8853 | 482233d327d836dcd4b105d239b17b22e863831c | /bsp/board/lib/menu/MenuAlarm.h | 52fc419cb9599bc4590121a4e519d19a59871d3b | []
| no_license | kurtis99/Elecon | 11de08bba113b658c73dbef0325d0ab268546bad | 673c89e7b0d0f30c4599425f3148073a661b5fde | refs/heads/master | 2016-09-05T20:15:17.826180 | 2010-02-15T17:14:57 | 2010-02-15T17:14:57 | 518,968 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,173 | h | #ifndef MENUALARM
#define MENUALARM
#include "MenuBaseClass.h"
/*
квалификатор virtual на самом деле наследуется и тут он только для визуальности.
*/
namespace Menu {
class AlarmItem : public BaseClass
{
private:
void (*ShowCurrenMenu)(void);
virtual void showMenuItems();
virtual void checkPushButtons();
public:
virtual void showMenu()
{
if ( pNextMenu != pCurrentMenu) {
returnItem = pNextMenu;
pNextMenu = pCurrentMenu;
}
showMenuItems();
checkPushButtons();
};
AlarmItem(void (*_ShowCurrenMenu)(void), const char * _MenuName)
: ShowCurrenMenu ( _ShowCurrenMenu )
{
MenuName = _MenuName;
};
virtual ~AlarmItem() {};
};
} //namespace Menu
#endif /* MENUALARM */ | [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
f39c44dae5932a6a50e75a5cfc76cf092bf620a5 | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/Qt/qcdestyle.h | 2dd256162f985a13220fc751d9cb644d9a1eb5af | [
"BSD-2-Clause"
]
| permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,048 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QCDESTYLE_H
#define QCDESTYLE_H
#include <QtGui/qmotifstyle.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
#if !defined(QT_NO_STYLE_CDE)
class Q_GUI_EXPORT QCDEStyle : public QMotifStyle
{
Q_OBJECT
public:
explicit QCDEStyle(bool useHighlightCols = false);
virtual ~QCDEStyle();
int pixelMetric(PixelMetric metric, const QStyleOption *option = 0,
const QWidget *widget = 0) const;
void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
const QWidget *w = 0) const;
void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
const QWidget *w = 0) const;
QPalette standardPalette() const;
protected Q_SLOTS:
QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt = 0,
const QWidget *widget = 0) const;
};
#endif // QT_NO_STYLE_CDE
QT_END_NAMESPACE
QT_END_HEADER
#endif // QCDESTYLE_H
| [
"alon@rogue.(none)"
]
| [
[
[
1,
82
]
]
]
|
d3c80663f4928ffc864bdb9114402e526ccab113 | 4d01363b089917facfef766868fb2b1a853605c7 | /src/Physics/Path.h | e73644a6751385445fcea045e3e7190f1e6bdebb | []
| no_license | FardMan69420/aimbot-57 | 2bc7075e2f24dc35b224fcfb5623083edcd0c52b | 3f2b86a1f86e5a6da0605461e7ad81be2a91c49c | refs/heads/master | 2022-03-20T07:18:53.690175 | 2009-07-21T22:45:12 | 2009-07-21T22:45:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | h | #ifndef path_h
#define path_h
#include "../Utils/Structures/BezierCurve.h"
class Path
{
};
#endif
| [
"daven.hughes@92c3b6dc-493d-11de-82d9-516ade3e46db"
]
| [
[
[
1,
12
]
]
]
|
474020369f81c6863e0cd856b329d4aa512d2862 | 9399383d7e227c4812e19f08a2d2c20cf66a0031 | /CustomEdit.h | 486db692a283a5a45d51101afbe9bfc171e0acc4 | []
| no_license | mattttttttsu/Edit-Engine-Test | bf5bf22c2b1a8937bc4ed062616d422153b7cb65 | e3f74ba821a7ddb2f235c0cc519f899cc0b045ae | refs/heads/master | 2021-01-10T19:11:27.119238 | 2011-11-29T18:52:40 | 2011-11-29T18:52:40 | 2,877,257 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 35,990 | h | #ifndef _CUSTOMEDIT_H_
#define _CUSTOMEDIT_H_
#include <stdio.h>
#include "Buffer.h"
#include "Point.h"
#include "Selection.h"
#include "CharacterBorderIterator.h"
#include "Longline.h"
#include "WtlHelper.h"
namespace EditTest {
using namespace Longline;
/**
* 改行の扱い方の列挙。
*/
enum LineEndRules {
LINE_END_AUTO = 0,
LINE_END_CR,
LINE_END_LF,
LINE_END_CRLF,
LINE_END_NONE,
LINE_END_COUNT
};
/**
* サンプルのエディットボックス
*
*/
class CustomEdit : public CWindowImpl<CustomEdit>
// public COwnerDraw<CustomEdit>
{
private:
/**
* バッファ
*/
Buffer buffer;
/**
* 1行の高さ
*/
DWORD lineHeight;
/**
* フォントサイズ
*/
DWORD fontSize;
/**
* 垂直ルーラーの幅
*/
DWORD rulerWidth;
/**
* 現在の縦方向のスクロール位置
*/
DWORD vPosition;
/**
* 現在の横方向のスクロール位置
*/
DWORD hPosition;
/**
* キャレットの表示場所
*/
PhysicalPoint caretPosition;
/**
* 選択範囲
*/
Selection* selection;
/**
* IMEの状態
*/
BOOL imeStarted;
/**
* マウスがキャプチャーされているか
*/
BOOL mouseCaptured;
/**
* マウスキャプチャ中に呼び出されるタイマーのID
*/
UINT_PTR mouseCaptureTimer;
/**
* デフォルトのテキスト用のブラシ
*/
CBrush* defaultBrush;
/**
* 選択中のテキストのブラシ
*/
CBrush* selectedBrush;
public:
/**
* コンストラクタ
*/
CustomEdit()
{
/*
buffer.SetText(_T("ABCあいうえおDEF\nかきくけこ 123456\nテストテスト 123漢字テストかきくけこここここ\nテストテストテスト")
_T("ABCDEFG。\nHIJKLMN\nOPQRSTU\nVWXYZ\nテストテスト。あいうえお\nかきくけこ\nさしすせそ\nたちつてと\n")
_T("日本語。記号\nabcdfghjkdf\n,./;:]@["));
*/
BYTE* fileData = new BYTE[500000];
DWORD bufferLen = 0;
HANDLE file = CreateFile(_T("test.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, 0);
ReadFile(file, fileData, 500000, &bufferLen, 0);
CloseHandle(file);
FilterMbFilter* filter = new FilterMbFilter();
filter->SetInputString(fileData, bufferLen);
DWORD unicodeBufferLen = 0;
LPWSTR unicodeBuffer = NULL;
unicodeBuffer = (LPWSTR)filter->convert(NULL, &unicodeBufferLen, Encodings::UTF16_LE);
buffer.SetText(unicodeBuffer);
lineHeight = 20;
fontSize = 14;
rulerWidth = 40;
vPosition = 0;
hPosition = 0;
caretPosition.SetX(0);
caretPosition.SetY(0);
imeStarted = false;
mouseCaptured = false;
mouseCaptureTimer = 100; //マウスのキャプチャー中に実行されるタイマーのID
//描画用ブラシの作成
defaultBrush = new CBrush();
defaultBrush->CreateSolidBrush(RGB(0xFF, 0xFF, 0xFF));
selectedBrush = new CBrush();
selectedBrush->CreateSolidBrush(RGB(0x44, 0x44, 0xAA));
selection = new Selection();
delete[] fileData;
delete filter;
}
public:
/**
* コンポーネント作成直後に実行される処理
* @param LPCREATESTRUCT createStruct コンポーネントの情報を含んだ配列
*
* コンストラクタの時点ではウィンドウが生成されず、m_hWnd等が
* 初期化されていないため、この辺りの値を必要とする処理は
* コンストラクタではなくこのメソッドに記述する。
*/
LRESULT OnCreate(LPCREATESTRUCT createStruct)
{
if(m_hWnd == NULL) {
::MessageBox(NULL, _T("NULL"), NULL, 0);
}
UpdateScrollBars();
return 0;
}
/**
* コンポーネントのサイズが変更された時に呼び出される処理
* @param UINT type 不明
* @param CSize size 変更後のサイズ情報
*/
void OnSize(UINT type, CSize size)
{
UpdateScrollBars();
}
/**
* コンポーネント上でスクロールが発生した場合に呼び出される処理
*/
void OnVScroll(UINT scrollCode, UINT position, CScrollBar scrollBar)
{
DWORD docLineCount = buffer.GetLineCount(),
viewLineCount = GetViewLineCount();
DWORD maxScroll = docLineCount;// - viewLineCount;
switch(scrollCode)
{
case SB_LINEDOWN:
vPosition = min(maxScroll, vPosition+1);
break;
case SB_LINEUP:
vPosition = max(0, (int)vPosition-1);
break;
case SB_PAGEDOWN:
vPosition = min((int)maxScroll, (int)vPosition+15);
break;
case SB_PAGEUP:
vPosition = max(0, (int)vPosition-15);
break;
case SB_THUMBTRACK:
case SB_THUMBPOSITION:
vPosition = position;
vPosition = min((int)maxScroll, (int)vPosition);
vPosition = max(0, (int)vPosition);
break;
}
UpdateImeWindowPosition();
SetScrollPos(SB_VERT, vPosition, TRUE);
Invalidate();
}
/**
* コンポーネント上でスクロールが発生した場合に呼び出される処理
*/
void OnHScroll(UINT scrollCode, UINT position, CScrollBar scrollBar)
{
switch(scrollCode)
{
case SB_LINERIGHT:
hPosition = min(1000, hPosition+1);
break;
case SB_LINELEFT:
hPosition = max(0, (int)hPosition-1);
break;
case SB_PAGERIGHT:
hPosition = min((int)1000, (int)hPosition+15);
break;
case SB_PAGELEFT:
hPosition = max(0, (int)hPosition-15);
break;
case SB_THUMBTRACK:
case SB_THUMBPOSITION:
hPosition = max(0, (int)position);
break;
}
UpdateImeWindowPosition();
SetScrollPos(SB_HORZ, hPosition, TRUE);
Invalidate();
}
/**
* キーダウンが発生した時に呼び出される処理
* @param UINT charCode 押されたキーのコード
* @param UINT repeatCount リピート数?
* @param UINT flags ???
*/
void OnKeyDown(UINT charCode, UINT repeatCount, UINT flags)
{
if(imeStarted) {
return;
}
//改行
if(charCode == 0x0D) {
InsertLine();
Invalidate();
}
if(charCode == VK_DELETE) {
DeleteText(1);
Invalidate();
}
if(charCode == VK_BACK)
{
DeleteText(-1);
Invalidate();
}
MoveCaret(charCode);
}
/**
* 文字をタイプした際に呼び出される処理。
* @param UINT character キャラクタコード
*/
void OnChar(UINT character, UINT repeatCount, UINT flags)
{
/*
wchar_t w[2];
w[0]=(wchar_t)character;
w[1]=0;
wchar_t msg[100];
wsprintf(msg, _T("%d"), w[0]);
MessageBox(msg, NULL, 0);
*/
if(imeStarted) {
Invalidate();
return;
}
switch((wchar_t)character)
{
case 0x08: //Backspace
case 0x0D: //Return
return;
default:
wchar_t text[2];
text[0] = (wchar_t)character;
text[1] = 0;
InsertText(text);
}
Invalidate();
}
/**
* IMEの入力を開始した時に呼び出される処理
*/
void OnImeStartComposition()
{
UpdateImeWindowPosition();
imeStarted = true;
}
/**
* IMEの状態が変化した時に呼び出される
* @param DWORD dbcsChar 入力文字?
* @param DWORD flags 現在の状態を表すフラグ
*/
BOOL OnImeComposition(DWORD dbcsChar, DWORD flags)
{
if(flags != 0 && (flags & GCS_RESULTSTR) == 0) {
return false;
}
HIMC imc = ::ImmGetContext(m_hWnd);
if(!imc) {
return false;
}
int len = ::ImmGetCompositionStringW(imc, GCS_RESULTSTR, 0, 0) / sizeof(wchar_t);
if(len <= 0) {
return false;
}
wchar_t* insertion = new wchar_t[len+1];
::ImmGetCompositionStringW(imc, GCS_RESULTSTR, insertion, len * sizeof(wchar_t));
insertion[len] = 0;
InsertText(insertion);
delete[] insertion;
UpdateImeWindowPosition();
::ImmReleaseContext(m_hWnd, imc);
SetMsgHandled(true);
Invalidate();
return true;
}
/**
* IMEの入力が完了した時に呼び出される。
*/
void OnImeEndComposition()
{
imeStarted = false;
}
/**
* 左ボタンのクリックの処理
* @param UINT nFlags
*/
void OnLButtonDown(UINT flags, CPoint point)
{
//マウスカーソルのキャプチャ開始
::SetCapture(m_hWnd);
mouseCaptured = true;
::SetTimer(m_hWnd, mouseCaptureTimer, 100, NULL);
PhysicalPoint pPoint;
pPoint.SetX(point.x);
pPoint.SetY(point.y);
SetCaretPositionByPPoint(pPoint, flags & MK_SHIFT);
Invalidate();
}
/**
* マウスカーソルが移動した時の処理を行う
* @param UINT flags Control、Shift等が押されているかの情報
* @param CPoint point 座標情報
*/
void OnMouseMove(UINT flags, CPoint point)
{
if(!mouseCaptured) {
return;
}
PhysicalPoint pPoint;
pPoint.SetX(point.x);
pPoint.SetY(point.y);
SetCaretPositionByPPoint(pPoint, true);
}
/**
* マウスの左ボタンが離された時の処理
* @param UINT flags Control、Shift等が押されているかの情報
* @param CPoint point 座標情報
*/
void OnLButtonUp(UINT flags, CPoint point)
{
::ReleaseCapture();
mouseCaptured = false;
::KillTimer(m_hWnd, mouseCaptureTimer);
}
/**
* マウスのホイール入力に対する処理
* @param UINT flags CONTROLやShiftが押されているかなどのフラグ
* @param short zDelta ホイールをどれだけ回転させたか
* @param CPoint point カーソル位置
*/
BOOL OnMouseWheel(UINT flags, short zDelta, CPoint point)
{
int scrollLines = 0;
if(!::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &scrollLines, 0)) {
scrollLines = 5;
}
//wchar_t msg[100];
//wsprintf(msg, _T("Delta:%d"), zDelta);
//MessageBox(msg, NULL, 0);
zDelta *= scrollLines;
OnVScroll(SB_THUMBPOSITION, vPosition - (zDelta / WHEEL_DELTA), NULL);
return false;
}
/**
* タイマーを更新する時に呼び出される処理
* @param UINT_PTR timerId タイマーID
*/
void OnTimer(UINT_PTR timerId)
{
if(timerId == mouseCaptureTimer) {
OnMouseCaptureTimer();
}
}
/**
* 自分自身を描画する時に呼び出される処理。
* @param CHandleDC pdc 描画先デバイスコンテキスト。
*/
void OnPaint(CDCHandle pdc)
{
PAINTSTRUCT ps;
CDCHandle dc = CDCHandle(BeginPaint(&ps));
CRect rcPaint = CRect(ps.rcPaint);
if(rcPaint.IsRectEmpty()) {
EndPaint(&ps);
return;
}
CRect rect(10, 10, 100, 100);
CBrush brush;
CBrush frameBrush;
brush.CreateSolidBrush(RGB(255,255,255));
frameBrush.CreateSolidBrush(RGB(0,0,0));
GetClientRect(&rect);
dc.FillRect(rect, brush);
DWORD lineCount = buffer.GetLineCount();
DWORD viewLineCount = GetViewLineCount();
for(DWORD i=vPosition, loopCount=0; i < lineCount && loopCount <= viewLineCount; i++, loopCount++) {
DrawLine(dc, buffer.GetLine(i), loopCount * lineHeight, i);
}
GetClientRect(&rect);
DrawCaret(&dc);
//ルーラーを描画
DrawRuler(&dc, rect.Height());
dc.FrameRect(&rect, frameBrush);
EndPaint(&ps);
}
/**
* 現在選択中のテキストをコピーする。
*/
void CopyText()
{
Clipboard clip(m_hWnd);
LPWSTR text = GetSelectionText(LINE_END_CRLF);
//::MessageBox(NULL, text, NULL, 0);
if(text != NULL) {
clip.Clear();
clip.SetText(text);
delete[] text;
}
}
/**
* 選択テキストをカットする。
*/
void CutText()
{
Clipboard clip(m_hWnd);
LPWSTR text = GetSelectionText(LINE_END_CRLF);
if(text != NULL) {
clip.Clear();
clip.SetText(text);
delete[] text;
}
DeleteSelection();
Invalidate();
}
/**
* クリップボードのテキストを貼り付ける。
*/
void PasteText()
{
Clipboard clip(m_hWnd);
LPWSTR text = clip.GetText();
if(text != NULL) {
Buffer pasteBuffer;
pasteBuffer.SetText(text);
int lineCount = pasteBuffer.GetLineCount();
LPWSTR line = NULL;
for(int i=0; i < lineCount; i++)
{
line = pasteBuffer.GetLine(i);
InsertText(line);
if(i < lineCount -1) {
InsertLine();
}
}
//改行のイテレータを作る必要がある?
delete[] text;
}
Invalidate();
}
/**
* 1行を描画する。
* @param HDC hDc デバイスコンテキスト
* @param LPWSTR line 描画しようとしている1行分の文字列
* @param int y 描画先のY座標。
* @param int lineY テキスト上のY座標。
*/
void DrawLine(HDC hDc, LPWSTR line, int y, int lineY)
{
int length = wcslen(line);
CDCHandle dc = hDc;
int current = 0;
DWORD next = 0;
DWORD len = wcslen(line);
DWORD stopper = 1000;
DWORD drawLength = 0;
//X座標はデフォルトでルーラーの隣からスタート
int x=rulerWidth;
CSize size;
BOOL selected;
RangeI* position = new RangeI();
RangeI* selectionRange = new RangeI();
LogicalPoint logicalPoint;
CharacterBorderIterator itor = CharacterBorderIterator();
int hScrollBorder = hPosition * fontSize;
//TODO: イテレータの初期化時はRangeIではなく
//Selectionを渡すように修正する。
GetSelectionRangeOnLine(lineY, selectionRange);
itor.Initialize(line, selectionRange);
while(!itor.IsEnd() && stopper-- > 0) {
itor.GetCurrent(position);
current = position->GetFirst();
logicalPoint.SetX(position->GetFirst());
logicalPoint.SetY(lineY);
if(selectionRange->GetRange() > 0 && current >= selectionRange->GetFirst() &&
current < selectionRange->GetSecond()) {
//選択領域内
dc.SetBkMode(OPAQUE);
dc.SetBkColor(RGB(0x44, 0x44, 0xAA));
dc.SetTextColor(RGB(0xEE, 0xEE, 0xEE));
dc.SelectBrush(*selectedBrush);
selected = true;
} else {
//選択領域外
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(RGB(0x00, 0x00, 0x00));
dc.SelectBrush(*defaultBrush);
selected = false;
}
if(line[position->GetFirst()] == _T(' ')) {
if( x >= hScrollBorder || (x+fontSize) >= hScrollBorder) {
DrawSpace(&dc, x - hScrollBorder, y, selected);
}
x += fontSize;
} else if(line[position->GetFirst()] == _T('\t')) {
if( x >= hScrollBorder || (x+fontSize*4) >= hScrollBorder) {
DrawTab(&dc, x - hScrollBorder, y, selected);
}
x += fontSize * 4;
} else {
dc.GetTextExtent(&line[position->GetFirst()], position->GetRange(), &size);
if( x >= hScrollBorder || (x+size.cx) >= hScrollBorder) {
dc.TextOut(x - hScrollBorder, y, &line[position->GetFirst()], position->GetRange());
}
x += size.cx;
}
itor.Next();
}
delete position;
delete selectionRange;
}
/**
* 1文字分のスペースを描画する
* @param CDCHandle* dc デバイスコンテキスト
* @param int x X座標
* @param int y Y座標
*/
void DrawSpace(CDCHandle* dc, int x, int y, BOOL selected)
{
COLORREF bgColor;
if(selected) {
bgColor = RGB(0x44, 0x44, 0xAA);
} else {
bgColor = RGB(0xFF, 0xFF, 0xFF);
}
dc->FillSolidRect(new CRect(x, y, x+fontSize, y+lineHeight-2), bgColor);
CPen pen;
pen.CreatePen(PS_SOLID, 1, RGB(0xCC, 0xCC, 0xCC));
dc->SelectPen(pen);
dc->Rectangle(new CRect(x, y + (lineHeight * 2 / 3), x+(fontSize / 2), y+lineHeight-2));
}
/**
* 1文字分のタブを描画する
* @param CDCHandle* dc デバイスコンテキスト
* @param int x X座標
* @param int y Y座標
*/
void DrawTab(CDCHandle* dc, int x, int y, BOOL selected)
{
COLORREF bgColor;
if(selected) {
bgColor = RGB(0x44, 0x44, 0xAA);
} else {
bgColor = RGB(0xFF, 0xFF, 0xFF);
}
dc->FillSolidRect(new CRect(x, y, x+(fontSize * 4), y+lineHeight-2), bgColor);
CPen pen;
pen.CreatePen(PS_SOLID, 1, RGB(0xCC, 0xCC, 0xCC));
dc->SelectPen(pen);
dc->MoveTo(x+2, y + lineHeight / 4);
dc->LineTo(x+10, y + lineHeight / 2);
dc->MoveTo(x+10, y + lineHeight / 2);
dc->LineTo(x+2, y + lineHeight * 2 / 3);
dc->MoveTo(x+2, y + lineHeight * 2 / 3);
dc->LineTo(x+2, y + lineHeight / 4);
}
/**
* 垂直ルーラーを描画する
* @param CDCHandle* dc 描画先のデバイスコンテキスト
* @param int コンポーネントの高さ
*/
void DrawRuler(CDCHandle* dc, int h)
{
DWORD maxLines = buffer.GetLineCount();
CBrush brush;
brush.CreateSolidBrush(RGB(228,228,228));
//背景の描画
dc->Rectangle(0, 0, rulerWidth, h);
//1行ずつ行番号を出力
wchar_t digit[10];
for(DWORD i=0; i < maxLines; i++)
{
wsprintf(digit, _T("%04d"), vPosition+i+1);
dc->TextOutW(0, i * lineHeight, digit);
}
}
/**
* キャレットを描画する。
* @param CDCHandle* dc 描画先のデバイスコンテキスト
*
*/
void DrawCaret(CDCHandle* dc)
{
int x=0, y=0;
int hScrollBorder = hPosition * fontSize;
y = caretPosition.GetY();
x = caretPosition.GetX() - hScrollBorder;
CRect rect;
rect.left = rulerWidth + x;
rect.bottom = y+lineHeight - (vPosition * lineHeight);
rect.right = rect.left + fontSize - 5;
rect.top = rect.bottom - 5;
CBrush brush;
brush.CreateSolidBrush(RGB(200,200,240));
dc->FillRect(rect, brush);
}
/**
* コンポーネント内に何行表示できるかを返す。
* @return DWORD 表示できる行数
*
* 完全に表示できる行数のみを返します。
* 2.5行等、中途半端な行数の場合は2を返します。
*/
DWORD GetViewLineCount()
{
CRect rect;
GetClientRect(&rect);
return rect.Height() / lineHeight;
}
/**
* 指定した行の選択領域のサイズを返す
* @param int line 行番号
* @param RangeI* out 選択領域の幅を格納する変数
*/
void GetSelectionRangeOnLine(int line, RangeI* out)
{
LogicalPoint beginPoint, endPoint;
selection->GetBeginPoint(&beginPoint);
selection->GetEndPoint(&endPoint);
if(line < beginPoint.GetY() || line > endPoint.GetY()) {
out->SetFirst(0);
out->SetSecond(0);
return;
}
CClientDC* dc = new CClientDC(m_hWnd);
//選択領域の左上,右下座標を一度実座標に変換する。
//その後、現在の行の何文字目なのかを調べる
int physicalLeft = 0, physicalRight = 0;
int curLeft = 0, curRight = 0;
LogicalPoint logical;
PhysicalPoint physical;
logical.SetX(beginPoint.GetX());
logical.SetY(beginPoint.GetY());
GetPPointFromLPoint(*dc, &logical, &physical);
physicalLeft = physical.GetX();
logical.SetX(endPoint.GetX());
logical.SetY(endPoint.GetY());
GetPPointFromLPoint(*dc, &logical, &physical);
physicalRight = physical.GetX();
//上で調べた物理座標のLeft, Rightが現在の行の
//何文字目なのかを調べる。
physical.SetX(physicalLeft);
physical.SetY(line * lineHeight);
GetLPointFromPPoint(*dc, &physical, &logical);
curLeft = logical.GetX();
physical.SetX(physicalRight);
physical.SetY(line * lineHeight);
GetLPointFromPPoint(*dc, &physical, &logical);
curRight = logical.GetX();
LPWSTR lineText = buffer.GetLine(line);
out->SetFirst((line == beginPoint.GetY()) ? curLeft : 0);
out->SetSecond((line == endPoint.GetY()) ? curRight : wcslen(lineText));
delete dc;
}
/**
* 現在選択中のテキストを返す。
* @param LineEndRules lineEndRule 改行の扱い方。(EditTest::LineEndRulesの値)
* @return LPWSTR 選択中の文字列を含んだバッファのポインタ。
* - この関数で取得したバッファは呼び出し側で解放する必要がある。
*/
LPWSTR GetSelectionText(int lienEndRule)
{
if(selection->IsEmpty()) {
return NULL;
}
LogicalPoint start, end;
selection->GetBeginPoint(&start);
selection->GetEndPoint(&end);
LPWSTR line = NULL;
LPWSTR copyBuffer = NULL;
DWORD buffLen = 0;
if(start.GetY() == end.GetY()) {
line = buffer.GetLine(start.GetY());
buffLen = end.GetX() - start.GetX();
copyBuffer = new wchar_t[buffLen + 1];
wcsncpy(copyBuffer, &line[start.GetX()], buffLen);
copyBuffer[buffLen] = 0;
} else {
//複数行の場合はまず全体の長さを予測する。
buffLen = 0;
int cur = 0, lineLen = 0, startPos=0;
for(int i = start.GetY(); i <= end.GetY(); i++)
{
line = buffer.GetLine(i);
lineLen = wcslen(line);
startPos = 0;
if(i == start.GetY()) {
startPos = start.GetX();
lineLen -= startPos;
} else if(i == end.GetY()) {
lineLen = end.GetX();
}
buffLen += lineLen;
if(i < end.GetY()) {
buffLen += wcslen(_T("\r\n"));
}
}
copyBuffer = new wchar_t[buffLen + 1];
for(int i = start.GetY(); i <= end.GetY(); i++)
{
line = buffer.GetLine(i);
lineLen = wcslen(line);
startPos = 0;
if(i == start.GetY()) {
startPos = start.GetX();
lineLen -= startPos;
} else if(i == end.GetY()) {
lineLen = end.GetX();
}
wcsncpy(©Buffer[cur], &line[startPos], lineLen);
cur += lineLen;
if(i < end.GetY()) {
line = _T("\r\n");
lineLen = wcslen(line);
wcsncpy(©Buffer[cur], line, lineLen);
cur += lineLen;
}
}
copyBuffer[buffLen] = 0;
}
return copyBuffer;
}
/**
* タイマーで呼び出される、マウスキャプチャー中の処理
*/
void OnMouseCaptureTimer()
{
//AutoFixScrollPosition();
CRect rect;
GetClientRect(rect);
POINT mousePoint;
::GetCursorPos(&mousePoint);
ScreenToClient(&mousePoint);
if(mousePoint.y <= 0) {
OnVScroll(SB_THUMBPOSITION, vPosition - 3, NULL);
}
if(mousePoint.y >= rect.bottom) {
OnVScroll(SB_THUMBPOSITION, vPosition + 3, NULL);
}
if(mousePoint.x <= rect.left) {
OnHScroll(SB_THUMBPOSITION, hPosition - 3, NULL);
}
if(mousePoint.x >= rect.right) {
OnHScroll(SB_THUMBPOSITION, hPosition + 3, NULL);
}
PhysicalPoint pPoint;
pPoint.SetX(mousePoint.x);
pPoint.SetY(mousePoint.y);
SetCaretPositionByPPoint(pPoint, true);
Invalidate();
}
private:
/**
* キャレットの移動を行う。
* @param keyCode キーコード
*/
void MoveCaret(UINT keyCode)
{
LogicalPoint lPosition, oldPosition;
CClientDC *dc = new CClientDC(m_hWnd);
int len = 0;
//移動前の座標を記憶しておく
buffer.GetCaretPosition(&oldPosition);
//キーに応じてキャレットを移動
switch(keyCode)
{
case VK_LEFT:
buffer.GetCaretPosition(&lPosition);
lPosition.SetX(max(0, (int)lPosition.GetX() - 1));
GetPPointFromLPoint(dc->m_hDC, &lPosition, &caretPosition);
buffer.SetCaretPosition(&lPosition);
break;
case VK_RIGHT:
buffer.GetCaretPosition(&lPosition);
lPosition.SetX(min(buffer.GetLineLength(lPosition.GetY()), lPosition.GetX() + 1));
GetPPointFromLPoint(dc->m_hDC, &lPosition, &caretPosition);
buffer.SetCaretPosition(&lPosition);
break;
case VK_UP:
caretPosition.SetY(max(1, (int)(caretPosition.GetY() - lineHeight)));
GetLPointFromPPoint(dc->m_hDC, &caretPosition, &lPosition);
buffer.SetCaretPosition(&lPosition);
break;
case VK_DOWN:
caretPosition.SetY(min((buffer.GetLineCount()-1) * lineHeight, caretPosition.GetY() + lineHeight));
GetLPointFromPPoint(dc->m_hDC, &caretPosition, &lPosition);
buffer.SetCaretPosition(&lPosition);
break;
default:
delete dc;
return;
}
//Shiftキーに応じて選択範囲を更新
if(::GetAsyncKeyState(VK_SHIFT) < 0) {
if(selection->IsEmpty()) {
selection->SetAnchorPoint(&oldPosition);
}
selection->SetActivePoint(&lPosition);
} else {
selection->SetActivePoint(&lPosition);
selection->SetAnchorPoint(&lPosition);
}
delete dc;
Invalidate();
AutoFixScrollPosition();
}
/**
* 指定したPhysicalPointの座標にキャレットを移動させる。
* @param PhysicalPoint point
* @param BOOL extend 選択領域を拡大するか
*/
void SetCaretPositionByPPoint(PhysicalPoint point, BOOL extend)
{
PhysicalPoint pPoint;
pPoint.SetX(point.GetX() - rulerWidth + (hPosition * fontSize));
pPoint.SetY(point.GetY() + (vPosition * lineHeight));
CDCHandle dc = GetDC();
LogicalPoint activePoint, anchorPoint;
if(extend) {
//領域選択
if(selection->IsEmpty()) {
GetLPointFromPPoint(dc, &caretPosition, &anchorPoint);
selection->SetAnchorPoint(&anchorPoint);
}
GetLPointFromPPoint(dc, &pPoint, &activePoint);
selection->SetActivePoint(&activePoint);
} else {
//カーソル移動
GetLPointFromPPoint(dc, &pPoint, &activePoint);
selection->SetAnchorPoint(&activePoint);
selection->SetActivePoint(&activePoint);
}
buffer.SetCaretPosition(&activePoint);
GetPPointFromLPoint(dc, &activePoint, &pPoint);
caretPosition.SetX(pPoint.GetX());
caretPosition.SetY(pPoint.GetY());
}
/**
* スクロールバーを更新する。
*/
void UpdateScrollBars()
{
DWORD docLineCount = buffer.GetLineCount(),
viewLineCount = GetViewLineCount();
int maxScroll = docLineCount;//-viewLineCount;
SetScrollRange(SB_VERT, 0, maxScroll, true);
SetScrollRange(SB_HORZ, 0, 1000, true);
if(maxScroll <= 0) {
EnableScrollBar(SB_VERT, ESB_DISABLE_BOTH);
vPosition = 0;
return;
} else {
EnableScrollBar(SB_VERT, ESB_ENABLE_BOTH);
}
EnableScrollBar(SB_HORZ, ESB_ENABLE_BOTH);
}
/**
* 論理座標(文字数単位)から物理座標(ピクセル単位)の座標を計算して返す
* @param HDC dc 描画先デバイスコンテキスト
* @param logical 論理座標。
* @param out 結果を格納するPhysicalPointクラス。
*/
inline void GetPPointFromLPoint(HDC dc, LogicalPoint* logical, PhysicalPoint* out)
{
CDCHandle* dcHandle = new CDCHandle(dc);
LPWSTR line = buffer.GetLine(logical->GetY());
int x=0, lineLength = wcslen(line);
CSize size;
for(int i=0; i < logical->GetX() && i < lineLength; i++)
{
if(line[i] == _T(' ')) {
x += (int)fontSize;
} else if(line[i] == _T('\t')) {
x += (int)fontSize * 4;
} else {
dcHandle->GetTextExtent(&line[i], 1, &size);
x += size.cx;
}
}
out->SetX(x);
out->SetY(logical->GetY() * lineHeight);
delete dcHandle;
}
/**
* 物理座標(ピクセル単位)から論理座標(文字数単位)の座標を計算して返す
* @param HDC dc 描画先デバイスコンテキスト
* @param physical 物理座標。
* @param out 結果を格納するlogicalPointクラス。
*/
inline void GetLPointFromPPoint(HDC dc, PhysicalPoint* physical, LogicalPoint* out)
{
CDCHandle* dcHandle = new CDCHandle(dc);
int y = max(0, (int)physical->GetY() / (int)lineHeight);
LPWSTR line = buffer.GetLine(y);
int i=0, x=0, len=wcslen(line), inc=0, inc2=0;
CSize size;
for(i=0; i < len; i++, x += inc)
{
if(line[i] == _T(' ')) {
inc = (int)fontSize;
} else if(line[i] == _T('\t')) {
inc = (int)fontSize * 4;
} else {
dcHandle->GetTextExtent(&line[i], 1, &size);
inc = size.cx;
}
if(x+inc > physical->GetX()) {
break;
}
}
if(i+1 < len) {
if(line[i] == _T(' ')) {
inc2 = (int)fontSize;
} else if(line[i] == _T('\t')) {
inc2 = (int)fontSize * 4;
} else {
inc2 = dcHandle->GetTextExtent(&line[i+1], 1, &size);
inc2 = size.cx;
}
if(abs(x - physical->GetX()) > abs(x + inc2 - physical->GetX())) {
x += inc;
i++;
}
}
physical->SetX(x);
out->SetX(i);
out->SetY(y);
delete dcHandle;
}
/**
* 文字を挿入する。
* @param LPWSTR text 文字列
* - 改行や削除、バックスペース等も文字として挿入します。
*/
void InsertText(LPWSTR text)
{
if(!selection->IsEmpty()) {
DeleteSelection();
}
CDCHandle dc = GetDC();
LogicalPoint lPoint;
//LPWSTR w = new wchar_t[2];
//w[0] = (wchar_t)character;
//w[1] = _T('\0');
buffer.GetCaretPosition(&lPoint);
buffer.InsertText(lPoint.GetY(), lPoint.GetX(), text);
//通常の文字の場合
lPoint.SetX(lPoint.GetX()+wcslen(text));
buffer.SetCaretPosition(&lPoint);
GetPPointFromLPoint(dc, &lPoint, &caretPosition);
}
/**
* 改行を挿入する
*/
void InsertLine()
{
if(!selection->IsEmpty()) {
DeleteSelection();
}
LogicalPoint lPoint;
buffer.GetCaretPosition(&lPoint);
buffer.InsertLine(lPoint.GetY(), lPoint.GetX());
lPoint.SetX(0);
lPoint.SetY(lPoint.GetY()+1);
buffer.SetCaretPosition(&lPoint);
CDCHandle dc = GetDC();
GetPPointFromLPoint(dc, &lPoint, &caretPosition);
}
/**
* 文字を削除する
*/
void DeleteText(int dim)
{
int start = 0,
length = 0;
LogicalPoint lPoint;
buffer.GetCaretPosition(&lPoint);
if(!selection->IsEmpty()) {
DeleteSelection();
return;
}
else if(dim >= 0) {
start = lPoint.GetX();
length = 1;
int lineEnd = buffer.GetLineLength(lPoint.GetY());
if(lPoint.GetX() == lineEnd) {
buffer.ConcatLine(lPoint.GetY());
} else {
buffer.DeleteText(lPoint.GetY(), start, length);
}
} else {
start = lPoint.GetX() - 1;
length = 1;
if(lPoint.GetX() == 0 && lPoint.GetY() > 0) {
lPoint.SetY(lPoint.GetY() - 1);
lPoint.SetX(buffer.GetLineLength(lPoint.GetY()));
buffer.ConcatLine(lPoint.GetY());
} else if(buffer.GetLineLength(lPoint.GetY()) > 0) {
lPoint.SetX(start);
buffer.DeleteText(lPoint.GetY(), start, length);
}
}
buffer.SetCaretPosition(&lPoint);
CDCHandle dc = GetDC();
GetPPointFromLPoint(dc, &lPoint, &caretPosition);
}
/**
* 選択中のテキストを削除する。
*/
void DeleteSelection()
{
LogicalPoint startPoint;
LogicalPoint endPoint;
selection->GetBeginPoint(&startPoint);
selection->GetEndPoint(&endPoint);
//完全に削除してしまう行の数
for(int i = startPoint.GetY() + 1; i < endPoint.GetY(); i++)
{
buffer.DeleteLine(startPoint.GetY() + 1);
}
if(startPoint.GetY() != endPoint.GetY()) {
//終了点から手前は全て削除
if(endPoint.GetX() > 0) {
buffer.DeleteText(startPoint.GetY()+1, 0, endPoint.GetX());
}
//開始点から後ろは全て削除
int lineLength = buffer.GetLineLength(startPoint.GetY());
if(startPoint.GetX() < lineLength) {
buffer.DeleteText(startPoint.GetY(), startPoint.GetX(), lineLength - startPoint.GetX());
}
buffer.ConcatLine(startPoint.GetY());
} else {
buffer.DeleteText(endPoint.GetY(), startPoint.GetX(), endPoint.GetX() - startPoint.GetX());
}
selection->SetActivePoint(&startPoint);
selection->SetAnchorPoint(&startPoint);
CDCHandle dc = GetDC();
buffer.SetCaretPosition(&startPoint);
GetPPointFromLPoint(dc, &startPoint, &caretPosition);
}
/**
* キャレットの位置にスクロールを移動させる
*
*/
void AutoFixScrollPosition()
{
//完全に表示されている行のみを対象にするため-1する。
int viewLineCount = GetViewLineCount() - 1;
LogicalPoint lPoint;
buffer.GetCaretPosition(&lPoint);
if(lPoint.GetY() > vPosition + viewLineCount) {
OnVScroll(SB_THUMBPOSITION, lPoint.GetY() - viewLineCount, NULL);
}
if(lPoint.GetY() < vPosition)
{
OnVScroll(SB_THUMBPOSITION, lPoint.GetY(), NULL);
}
CRect rcClient;
GetClientRect(&rcClient);
rcClient.left += rulerWidth;
rcClient.right -= 18;
if(caretPosition.GetX() > (hPosition-1) * fontSize + rcClient.Width()) {
//一気に1/3画面分スクロール
OnHScroll(SB_THUMBPOSITION, (caretPosition.GetX() - (rcClient.Width() / 3)) / fontSize+1, NULL);
}
if(caretPosition.GetX() < (hPosition) * fontSize)
{
OnHScroll(SB_THUMBPOSITION, caretPosition.GetX() / fontSize, NULL);
}
}
/**
* IMEの入力文字をキャレットの位置に移動させる。
*/
void UpdateImeWindowPosition()
{
COMPOSITIONFORM cf;
HIMC imc = ::ImmGetContext(m_hWnd);
if(imc) {
cf.dwStyle = CFS_POINT;
cf.ptCurrentPos.x = caretPosition.GetX() + rulerWidth - (hPosition * fontSize);
cf.ptCurrentPos.y = caretPosition.GetY() - (vPosition * lineHeight);
//cf.ptCurrentPos.x -= 1;
//cf.ptCurrentPos.y -= 1;
::ImmSetCompositionWindow(imc, &cf);
::ImmReleaseContext(m_hWnd, imc);
}
}
public:
DECLARE_WND_CLASS(_T("CustomEdit"));
BEGIN_MSG_MAP_EX(CustomEdit);
MSG_WM_CREATE(OnCreate);
MSG_WM_SIZE(OnSize);
MSG_WM_VSCROLL(OnVScroll);
MSG_WM_HSCROLL(OnHScroll);
//MSG_WM_KEYDOWN(OnKeyDown);
MSG_WM_PAINT(OnPaint);
MSG_WM_IME_STARTCOMPOSITION(OnImeStartComposition);
MSG_WM_IME_COMPOSITION(OnImeComposition);
MSG_WM_IME_ENDCOMPOSITION(OnImeEndComposition);
MSG_WM_LBUTTONDOWN(OnLButtonDown);
MSG_WM_MOUSEMOVE(OnMouseMove);
MSG_WM_LBUTTONUP(OnLButtonUp);
MSG_WM_MOUSEWHEEL(OnMouseWheel);
MSG_WM_TIMER(OnTimer);
//CHAIN_MSG_MAP_ALT(COwnerDraw<CustomEdit>, 1);
DEFAULT_REFLECTION_HANDLER();
END_MSG_MAP();
/**
* デストラクタ
*/
~CustomEdit()
{
delete defaultBrush;
delete selectedBrush;
delete selection;
}
};
};
#endif | [
"[email protected]"
]
| [
[
[
1,
1406
]
]
]
|
035b0325cd9969a20e1dd10629835540e1aa4133 | a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561 | /SlonEngine/src/Log/Detail/LogManager.cpp | 18b8dd898265b20a5b172ba498bb4fe2919c6a4f | []
| no_license | BackupTheBerlios/slon | e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6 | dc10b00c8499b5b3966492e3d2260fa658fee2f3 | refs/heads/master | 2016-08-05T09:45:23.467442 | 2011-10-28T16:19:31 | 2011-10-28T16:19:31 | 39,895,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,717 | cpp | #include "stdafx.h"
#include "Detail/Engine.h"
namespace {
using namespace slon::log::detail;
std::string extractNextLevel(const std::string& baseName, const std::string& fullName)
{
using namespace std;
size_t index = fullName.find_first_of( ".", baseName.length() + 1 );
if (index == string::npos) {
return fullName;
}
return fullName.substr(0, index);
}
logger_output* findNode(logger_output& loggerOutput, const std::string& name)
{
if (loggerOutput.name == name) {
return &loggerOutput;
}
for(size_t i = 0; i<loggerOutput.children.size(); ++i)
{
logger_output* childFound = findNode(*loggerOutput.children[i], name);
if (childFound) {
return childFound;
}
}
return 0;
}
void redirectChildrenOutput(logger_output& loggerOutput, const logger_output::ostream_ptr& os)
{
loggerOutput.os = os;
for (size_t i = 0; i<loggerOutput.children.size(); ++i) {
redirectChildrenOutput(*loggerOutput.children[i], os);
}
}
} // anonymous namespace
namespace slon {
namespace log {
namespace detail {
LogManager::LogManager()
: mainLogger( new detail::Logger(logger_output_ptr(new logger_output)) )
{
}
LogManager::~LogManager()
{
releaseSignal(*this);
}
bool LogManager::redirectOutput(const std::string& loggerName, const std::string& fileName)
{
logger_output_ptr loggerOutput = findNode(*mainLogger->getLoggerOutput(), loggerName);
if (!loggerOutput)
{
(*mainLogger) << log::S_ERROR << "Can't find requested logger: " << loggerName << std::endl;
return false;
}
// create output
loggerOutput->fb.reset(new std::filebuf);
loggerOutput->fb->open( fileName.c_str(), std::ios::out );
if ( !loggerOutput->fb->is_open() )
{
(*mainLogger) << log::S_ERROR << "Can't open output for logger: " << fileName << std::endl;
return false;
}
logger_output::ostream_ptr os( new ostream( logger_sink(loggerOutput->fb.get()) ) );
redirectChildrenOutput(*loggerOutput, os);
if ( loggerName.empty() ) {
(*mainLogger) << log::S_NOTICE << "Output for loggers redirected to file '"
<< fileName << "'" << std::endl;
}
else {
(*mainLogger) << log::S_NOTICE << "Output for loggers '" << loggerName << "' redirected to file '"
<< fileName << "'" << std::endl;
}
return true;
}
bool LogManager::redirectOutputToConsole(const std::string& loggerName)
{
logger_output_ptr loggerOutput = findNode(*mainLogger->getLoggerOutput(), loggerName);
if (!loggerOutput)
{
(*mainLogger) << log::S_ERROR << "Can't find requested logger: " << loggerName << std::endl;
return false;
}
// redirect output
loggerOutput->fb.reset();
logger_output::ostream_ptr os( new ostream( logger_sink(std::cout.rdbuf())) );
redirectChildrenOutput(*loggerOutput, os);
if ( loggerName.empty() ) {
(*mainLogger) << log::S_NOTICE << "Output for loggers redirected to console" << std::endl;
}
else {
(*mainLogger) << log::S_NOTICE << "Output for loggers '" << loggerName << "' redirected to console" << std::endl;
}
return true;
}
log::logger_ptr LogManager::createLogger(const std::string& name)
{
return logger_ptr( new detail::Logger( getLoggerOutput(name) ) );
}
logger_output_ptr LogManager::getLoggerOutput(const std::string& name)
{
logger_output_ptr mainOutput = mainLogger->getLoggerOutput();
logger_output_ptr parentOutput = mainOutput;
logger_output_ptr loggerOutput;
// create hierarchy until requested logger
if ( logger_output* loggerOutputNode = findNode(*parentOutput, name) ) {
loggerOutput.reset(loggerOutputNode);
}
else
{
std::string baseLevel, nextLevel;
while ( ( nextLevel = extractNextLevel(baseLevel, name) ) != name )
{
logger_output* loggerOutput = findNode(*parentOutput, nextLevel);
if (!loggerOutput) {
parentOutput = logger_output_ptr( new logger_output(parentOutput.get(), nextLevel) );
}
else {
parentOutput = loggerOutput;
}
baseLevel = nextLevel;
}
loggerOutput.reset( new logger_output(parentOutput.get(), name) );
}
return loggerOutput;
}
} // namespace detail
LogManager& currentLogManager()
{
return Engine::Instance()->getLogManager();
}
} // namespace slon
} // namespace log
| [
"devnull@localhost"
]
| [
[
[
1,
165
]
]
]
|
fca869162ec45fa10d064418cd818ec0982b68f8 | 54a14b8a8aba56ae9c982d17836a56da95ff7d0a | /EyeCam/ECap/ECap.h | 1858a8c2af5966709bf284bfbbb343ece90bd535 | []
| no_license | bolitt/ecv | d75045be99835bf703034667ce6dc1f793b5a5ec | 5c4ef74c84549462067aa8212ed8f28182d4d2e8 | refs/heads/master | 2021-01-25T07:27:34.758939 | 2011-06-02T14:18:59 | 2011-06-02T14:18:59 | 32,119,820 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,297 | h | // ECap.h : main header file for the ECap application
//
#if !defined(AFX_ECAP_H__26F7522B_4704_4C9F_8577_5C617CD05CA6__INCLUDED_)
#define AFX_ECAP_H__26F7522B_4704_4C9F_8577_5C617CD05CA6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// ECapApp:
// See ECap.cpp for the implementation of this class
//
class ECapApp : public CWinApp
{
public:
ECapApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(ECapApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(ECapApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_ECAP_H__26F7522B_4704_4C9F_8577_5C617CD05CA6__INCLUDED_)
| [
"[email protected]@3b49327d-b249-8546-83ad-21544eab179a"
]
| [
[
[
1,
49
]
]
]
|
43c39ef332969bcc60e97089c087fec69018f2ee | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/Wrappers/MyGUI.Managed/Marshaling.h | 9a2d28c0d728e14a6bd7aed2a4858817c7b9aa48 | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,236 | h | /*!
@file
@author Albert Semenov
@date 01/2009
@module
*/
#pragma once
#include <MyGUI.h>
#include "Utility.h"
namespace MyGUI
{
namespace Managed
{
class ObjectHolder
{
public:
ObjectHolder() : object() { }
ObjectHolder(System::Object ^ _obj) : object(_obj) { }
~ObjectHolder() { }
System::Object ^ toObject()
{
return object;
}
private:
gcroot < System::Object ^ > object;
};
// базовые шаблоны для конвертации переменных и типов
template <typename T> struct Convert
{
typedef T Type;
static inline Type To(T _value)
{
return _value;
}
static inline T From(Type _value)
{
return _value;
}
};
// перегрузка для базовых типов
template <> struct Convert<size_t>
{
typedef System::UInt32 Type;
inline static System::UInt32 To(size_t _value)
{
return System::UInt32(_value);
}
inline static size_t From(System::UInt32 _value)
{
return size_t(_value);
}
};
template <> struct Convert<bool&>
{
typedef bool % Type;
inline static bool % To(bool& _value)
{
return reinterpret_cast<bool&>(_value);
}
};
// перегрузка для строк
template <> struct Convert<const std::string&>
{
typedef System::String ^ Type;
inline static System::String ^ To(const std::string& _value)
{
return string_utility::utf8_to_managed(_value);
}
inline static std::string From(System::String ^ _value)
{
return string_utility::managed_to_utf8(_value);
}
};
template <> struct Convert<const MyGUI::UString&>
{
typedef System::String ^ Type;
inline static System::String ^ To(const MyGUI::UString& _value)
{
return string_utility::utf16_to_managed(_value);
}
inline static MyGUI::UString From(System::String ^ _value)
{
return string_utility::managed_to_utf16(_value);
}
};
template <> struct Convert<MyGUI::UString>
{
typedef System::String ^ Type;
inline static System::String ^ To(const MyGUI::UString& _value)
{
return string_utility::utf16_to_managed(_value);
}
inline static MyGUI::UString From(System::String ^ _value)
{
return string_utility::managed_to_utf16(_value);
}
};
// прегрузка для Any
template <> struct Convert<MyGUI::Any>
{
typedef System::Object ^ Type;
inline static System::Object ^ To(MyGUI::Any _value)
{
ObjectHolder* data = _value.castType< ObjectHolder >(false);
return data ? data->toObject() : nullptr;
}
inline static MyGUI::Any From(System::Object ^ _value)
{
ObjectHolder data = _value;
return data;
}
};
template <> struct Convert<const MyGUI::Guid&>
{
typedef System::Guid Type;
inline static const System::Guid& To(const MyGUI::Guid& _value)
{
return reinterpret_cast<const System::Guid&>(_value);
}
inline static const MyGUI::Guid& From(System::Guid& _value)
{
return reinterpret_cast<const MyGUI::Guid&>(_value);
}
};
} // namespace Managed
} // namespace MyGUI
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
136
]
]
]
|
d3c42c8fd009033fe0dde9c7da9aa40bc641bd2b | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_core/threads/juce_ChildProcess.h | 721ab8eb3425a4ddded93776b2d93cf66b4fb375 | []
| no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,253 | h | /*
==============================================================================
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.
==============================================================================
*/
#ifndef __JUCE_CHILDPROCESS_JUCEHEADER__
#define __JUCE_CHILDPROCESS_JUCEHEADER__
//==============================================================================
/**
Launches and monitors a child process.
This class lets you launch an executable, and read its output. You can also
use it to check whether the child process has finished.
*/
class JUCE_API ChildProcess
{
public:
//==============================================================================
/** Creates a process object.
To actually launch the process, use start().
*/
ChildProcess();
/** Destructor.
Note that deleting this object won't terminate the child process.
*/
~ChildProcess();
/** Attempts to launch a child process command.
The command should be the name of the executable file, followed by any arguments
that are required.
If the process has already been launched, this will launch it again. If a problem
occurs, the method will return false.
*/
bool start (const String& command);
/** Returns true if the child process is alive. */
bool isRunning() const;
/** Attempts to read some output from the child process.
This will attempt to read up to the given number of bytes of data from the
process. It returns the number of bytes that were actually read.
*/
int readProcessOutput (void* destBuffer, int numBytesToRead);
/** Blocks until the process has finished, and then returns its complete output
as a string.
*/
String readAllProcessOutput();
/** Blocks until the process is no longer running. */
bool waitForProcessToFinish (int timeoutMs) const;
private:
//==============================================================================
class ActiveProcess;
friend class ScopedPointer<ActiveProcess>;
ScopedPointer<ActiveProcess> activeProcess;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcess);
};
#endif // __JUCE_CHILDPROCESS_JUCEHEADER__
| [
"ow3nskip"
]
| [
[
[
1,
88
]
]
]
|
88901ff81b5c22056c6109056bcbd718e17cf5c2 | dba70d101eb0e52373a825372e4413ed7600d84d | /RendererComplement/include/Any.h | 13496be8d95091711909debcfef0cb249311918f | []
| no_license | nustxujun/simplerenderer | 2aa269199f3bab5dc56069caa8162258e71f0f96 | 466a43a1e4f6e36e7d03722d0d5355395872ad86 | refs/heads/master | 2021-03-12T22:38:06.759909 | 2010-10-02T03:30:26 | 2010-10-02T03:30:26 | 32,198,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,296 | h | #ifndef _Any_H_
#define _Any_H_
#include "Prerequisites.h"
#include <typeinfo>
namespace RCP
{
class Any
{
public:
class Content
{
public:
virtual ~Content()
{}
virtual Content* clone() const = 0;
virtual size_t getSize()const = 0;
virtual void* getContentPtr() = 0;
virtual const type_info& getType() = 0;
};
template<typename Type>
class RealContent:public Content
{
public:
RealContent(const Type& value):
mValue(value)
{
}
virtual RealContent* clone() const
{
return new RealContent(mValue);
}
virtual size_t getSize()const
{
return sizeof(mValue);
}
virtual void* getContentPtr()
{
return &mValue;
}
const type_info& getType()
{
return typeid(Type);
}
Type mValue;
};
public:
Any():
mContent(NULL)
{}
template<typename T>
Any(const T& value):
mContent(new RealContent<T>(value))
{
}
Any(const Any& any):
mContent(any.mContent?any.mContent->clone():NULL)
{
}
~Any()
{
SAFE_DELETE(mContent);
}
public:
Any& swap(Any& any)
{
std::swap(mContent,any.mContent);
return *this;
}
Any& operator=(const Any& any)
{
Any(any).swap(*this);
return *this;
}
template<typename T>
Any& operator=(const T& t)
{
Any(t).swap(*this);
return *this;
}
bool isEmpty()const
{
return mContent == NULL;
}
void setEmpty()
{
SAFE_DELETE(mContent);
}
size_t getSize()const
{
return mContent->getSize();
}
void* getContentPtr()const
{
return mContent?mContent->getContentPtr():NULL;
}
Content* mContent;
};
template<typename T>
T* any_cast(Any* any)
{
assert(any);
const type_info& info = any->mContent->getType();
if (info == typeid(T))
return &static_cast<Any::RealContent<T>*>(any->mContent)->mValue;
else
return NULL;
}
template<typename T>
const T* any_cast(const Any* any)
{
return any_cast<T>(const_cast<Any*>(any));
}
template<typename T>
T any_cast(const Any& any)
{
const T* result = any_cast<T>(&any);
if (result == NULL)
assert(0);
return *result;
}
}
#endif//_Any_H_
| [
"[email protected]@c2606ca0-2ebb-fda8-717c-293879e69bc3"
]
| [
[
[
1,
150
]
]
]
|
1cc655191c389d9b67d0bd99a18dc17fc45afaed | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /开发项目/4Test/AddDlg.h | 0068f42e9ab1d444447fece029c52f26282c7a80 | []
| no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,272 | h | #if !defined(AFX_ADDDLG_H__5F01AA39_4048_44DF_9550_111CB24451A1__INCLUDED_)
#define AFX_ADDDLG_H__5F01AA39_4048_44DF_9550_111CB24451A1__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// AddDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// AddDlg dialog
class AddDlg : public CDialog
{
// Construction
public:
BOOL SaveQA( CString strQ, CString strA);
CFile theFile;
AddDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(AddDlg)
enum { IDD = IDD_DIALOG1 };
CString m_path;
CString m_strA;
CString m_strQ;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(AddDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(AddDlg)
afx_msg void OnButtonSelect();
afx_msg void OnSave();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_ADDDLG_H__5F01AA39_4048_44DF_9550_111CB24451A1__INCLUDED_)
| [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
]
| [
[
[
1,
51
]
]
]
|
921fa7eee282167eb4c14047115e207915143505 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Scd/ScExec/COPYBLK.CPP | 45b65456ddae609cbb682e85c6a17f21f2f88d94 | []
| 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 | 12,348 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#define __COPYBLK_CPP
#include "sc_defs.h"
#include "execlib.h"
#include "executiv.h"
#include "copyblk.h"
#include "sfe_base.h"
//===========================================================================
const char* CCopyBlock::CopyBlkFileName = "Scd_CBk.ini";
const char* CCopyBlock::TempBlockName = "TempTag_$$";
const int CopyBlockVerNo = 1; //KGA 2/12/97 major error in stored data, delete old copyblks.ini if ver < 1
//---------------------------------------------------------------------------
//FixFileName()
// {
// Strng OldCBKFile(PrjDatalibDirectory());
// OldCBKFile+="copyblks.ini";
//
// struct _finddata_t c_file;
// long hFile;
// if((hFile = _findfirst( OldCBKFile(), &c_file )) != -1L )
// {
// Strng NewCBKFile(PrjDatalibDirectory());
// NewCBKFile+=CopyBlkFileName;
// rename(OldCBKFile(), NewCBKFile());
// }
// };
//---------------------------------------------------------------------------
CCopyBlock::CCopyBlock(char* ModelClass, CExecObj* EO)
{
sModelClass = ModelClass;
pEO = EO;
eSrc = CB_SelectedTag;
eDst = CB_TagList;
bSrcDatalib = TRUE;
bDstDatalib = TRUE;
}
//---------------------------------------------------------------------------
//enum CopyBlkTypes { CB_Tag, CB_Block, CB_List };
void CCopyBlock::SetSrcTag(char* Src)
{
sSrc = Src;
eSrc = CB_SelectedTag;
bSrcDatalib = TRUE;
}
//---------------------------------------------------------------------------
void CCopyBlock::SetSrcBlock(char* Src, BOOL FromDatalib/*=TRUE*/)
{
sSrc = Src;
eSrc = CB_Block;
bSrcDatalib = FromDatalib;
}
//---------------------------------------------------------------------------
void CCopyBlock::SetDstList()
{
sDst = "";
eDst = CB_TagList;
TagList.SetSize(0);
}
//---------------------------------------------------------------------------
void CCopyBlock::SetDstList(CSVector& List)
{
sDst = "";
eDst = CB_TagList;
TagList = List;
}
//---------------------------------------------------------------------------
void CCopyBlock::SetDstBlock(char* Dst, BOOL FromDatalib/*=TRUE*/)
{
sDst = Dst;
eDst = CB_Block;
bDstDatalib = FromDatalib;
}
//---------------------------------------------------------------------------
int CCopyBlock::WriteTagValues(CSVector& Tags)
{
ASSERT(pEO && bSrcDatalib && eSrc==CB_SelectedTag);
CProfINIFile PF(CfgFiles(), (char*)CopyBlkFileName);
if (!CheckCopyBlockVer(PF, true))
return 0;
Strng_List sStrList;
int WriteCnt = 0;
char Buff[2];
Buff[0] = 0;
Buff[1] = 0;
PF.WrSection(TempBlockName, Buff);
char* p = Buff;
for (int i=0; i<Tags.GetSize(); i++)
{
CXM_ObjectData ObjData;
CXM_Route Route;
CXM_ObjectTag ObjTag(Tags[i](), TABOpt_AllInfoOnce);//TABOpt_Parms);
if (pEO->XReadTaggedItem(ObjTag, ObjData, Route))
{
CPkDataItem * pItem = ObjData.FirstItem();
byte cType = pItem->Type();
if (IsData(cType))
{
WriteCnt++;
if (IsIntData(cType) && pItem->Contains(PDI_StrList))
{
const long strIndex = pItem->Value()->GetLong();
pItem->GetStrList(sStrList);
pStrng pS = (sStrList.Length()>0) ? sStrList.AtIndexVal(strIndex) : NULL;
if (pS)
PF.WrStr(TempBlockName, Tags[i](), pS->Str());
else
PF.WrLong(TempBlockName, Tags[i](), strIndex);
}
else if (IsStrng(cType))
PF.WrStr(TempBlockName, Tags[i](), pItem->Value()->GetString());
else if (IsFloatData(cType))
PF.WrDouble(TempBlockName, Tags[i](), pItem->Value()->GetDouble());
else
PF.WrLong(TempBlockName, Tags[i](), pItem->Value()->GetLong());
}
}
}
return WriteCnt;
}
//---------------------------------------------------------------------------
BOOL CCopyBlock::CheckCopyBlockVer(CProfINIFile& PF, BOOL TestReadOnly/*=FALSE*/)
{
if (TestReadOnly)
{
WIN32_FIND_DATA fd;
if (FileExists(PF.Filename(), fd))
{
if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
{
LogError("SysCAD", LF_Exclamation, "Cannot write to read-only file '%s'", PF.Filename());
return false;
}
}
}
if (PF.RdInt("General", "CopyBlockVerNo", 0)<1)
{
//old data is likely to be wrong DELETE old file!
DeleteFile(PF.Filename());
LogNote("SysCAD", 0, "Old style 'copy data block' file deleted (%s)", PF.Filename());
}
PF.WrInt("General", "CopyBlockVerNo", CopyBlockVerNo);
return true;
}
//---------------------------------------------------------------------------
void CCopyBlock::BuildBlockList(char* ModelClass, CSVector& List, CWordArray& FlagList, int& DefaultIndex)
{
DefaultIndex = -1;
Strng s,Block;
s.Set("(%s)", ModelClass);
List.SetSize(16);
FlagList.SetSize(16);
int Cnt = 0;
char Buff[16384];
char Buff1[16];
for (int i=0; i<2; i++)
{
CProfINIFile PF(i==0 ? CfgFiles() : PrjFiles(), (char*)CopyBlkFileName);
CheckCopyBlockVer(PF);
DWORD dw = PF.RdSectionNames(Buff, sizeof(Buff));
ASSERT(dw<sizeof(Buff)-2); //section too large!!!
char* p = Buff;
while (p[0])
{
int len = strlen(p);
char* Nextp = p;
Nextp += (len + 1);
char* pp = strstr(p, s());
if (pp)
{
if (PF.RdSection(p, Buff1, sizeof(Buff1))>0)
{
Block = p;
Block.SetLength((int)(pp-p));
if (i==0 || List.Find(Block())<0)
{
if (Cnt>=List.GetSize())
{
List.SetSize(List.GetSize()+8);
FlagList.SetSize(FlagList.GetSize()+8);
}
List[Cnt] = Block;
FlagList[Cnt] = (i==0 ? 1 : 0);
Cnt++;
}
}
}
p = Nextp;
}
}
List.SetSize(Cnt);
FlagList.SetSize(Cnt);
}
//---------------------------------------------------------------------------
void CCopyBlock::BuildBlockTagsList(char* ModelClass, char* BlockName, BOOL FromDatalib, CSVector& List)
{
int Cnt = 0;
List.SetSize(16);
Strng Section;
Section.Set("%s(%s)", BlockName, ModelClass);
char Buff[16384];
CProfINIFile PF(FromDatalib ? CfgFiles() : PrjFiles(), (char*)CopyBlkFileName);
CheckCopyBlockVer(PF);
DWORD dw = PF.RdSection(Section(), Buff, sizeof(Buff));
ASSERT(dw<sizeof(Buff)-2); //section too large!!!
char* p = Buff;
while (p[0])
{
int len = strlen(p);
char* Nextp = p;
Nextp += (len + 1);
char* pp = strchr(p, '=');
if (pp)
{
if (Cnt>=List.GetSize())
List.SetSize(List.GetSize()+8);
pp[0] = 0;
char* pValue = &pp[1];
char* ppp = strchr(p, '.');
if (ppp)
List[Cnt].Set("x%s (%s)", ppp, pValue);
else
List[Cnt].Set("%s (%s)", p, pValue);
Cnt++;
}
p = Nextp;
}
List.SetSize(Cnt);
}
//---------------------------------------------------------------------------
void CCopyBlock::RemoveBlock(char* ModelClass, char* BlockName)
{
Strng s;
s.Set("%s(%s)", BlockName, ModelClass);
char Buff[16];
for (int i=0; i<2; i++)
{
CProfINIFile PF(i==0 ? CfgFiles() : PrjFiles(), (char*)CopyBlkFileName);
if (CheckCopyBlockVer(PF, true) && PF.RdSection(s(), Buff, sizeof(Buff))>0)
{
Buff[0] = 0;
Buff[1] = 0;
PF.WrSection(s(), Buff);
}
}
}
//---------------------------------------------------------------------------
void CCopyBlock::MoveBlockLocation(char* ModelClass, char* BlockName, BOOL ToDatalib)
{
Strng s;
s.Set("%s(%s)", BlockName, ModelClass);
char Buff1[16];
CProfINIFile SrcPF(ToDatalib ? CfgFiles() : PrjFiles(), (char*)CopyBlkFileName);
if (!CheckCopyBlockVer(SrcPF, true))
return;
if (SrcPF.RdSection(s(), Buff1, sizeof(Buff1))>0)
{
char Buff[16384];
DWORD dw = SrcPF.RdSection(s(), Buff, sizeof(Buff));
ASSERT(dw<sizeof(Buff)-2); //section too large!!!
CProfINIFile DstPF(ToDatalib ? PrjFiles() : CfgFiles(), (char*)CopyBlkFileName);
if (!CheckCopyBlockVer(DstPF, true))
return;
DstPF.WrSection(s(), Buff);
Buff1[0] = 0;
Buff1[1] = 0;
SrcPF.WrSection(s(), Buff1);
}
}
//---------------------------------------------------------------------------
int CCopyBlock::CopyTagBlocks()
{
CWaitCursor Wait;
// ASSERT(eSrc!=CB_List); //this src type not allowed
// ASSERT(eDst!=CB_Tag); //this dst type not allowed
ASSERT(pEO);
CProfINIFile SrcPF(bSrcDatalib ? CfgFiles() : PrjFiles(), (char*)CopyBlkFileName);
CheckCopyBlockVer(SrcPF);
CProfINIFile DstPF(bDstDatalib ? CfgFiles() : PrjFiles(), (char*)CopyBlkFileName);
if (!CheckCopyBlockVer(DstPF, true))
return 0;
int Cnt = 0;
//gs_pTheSFELib->FE_SetHoldGlobalLinks(true);
//gs_Exec.SetHoldValidateData(true, true, true);
gs_Exec.BeginBulkChange();
Strng Section;
if (eSrc==CB_SelectedTag)
Section = TempBlockName;
else
Section.Set("%s(%s)", sSrc(), sModelClass());
char Buff[16384];
DWORD dw = SrcPF.RdSection(Section(), Buff, sizeof(Buff));
ASSERT(dw<sizeof(Buff)-2); //section too large!!!
if (eDst==CB_Block)
{
Strng DstSection;
DstSection.Set("%s(%s)", sDst(), sModelClass());
DstPF.WrSection(DstSection(), Buff);
}
else
{
Strng_List sStrList;
CXM_Route Route;
CXM_ObjectData ObjData;
char* p = Buff;
while (p[0])
{
int len = strlen(p);
char* Nextp = p;
Nextp += (len + 1);
char* pp = strchr(p, '=');
if (pp)
{
pp[0] = 0;
char* pValue = &pp[1];
char* ppp = strchr(p, '.');
Strng PartTag;
PartTag = (ppp==NULL ? p : ppp);
for (int i=0; i<TagList.GetSize(); i++)
{
Strng WrkTag(TagList[i]());
WrkTag += PartTag;
//CXM_ObjectTag ObjTag(WrkTag(), 0);
//need to use TABOpt_AllInfoOnce because of tags that contain a strList!
CXM_ObjectTag ObjTag(WrkTag(), TABOpt_AllInfoOnce);//0);//TABOpt_Exists);//TABOpt_Parms);//TABOpt_ValCnvsOnce);
Route.Clear();
if (pEO->XReadTaggedItem(ObjTag, ObjData, Route))
{
CPkDataItem * pItem = ObjData.FirstItem();
byte cType = pItem->Type();
PkDataUnion DU;
if (IsStrng(cType))
DU.SetTypeString(cType, pValue);
else if (IsFloatData(cType))
DU.SetTypeDouble(cType, SafeAtoF(pValue));
else if (IsIntData(cType) && pItem->Contains(PDI_StrList))
{
pItem->GetStrList(sStrList);
pStrng pS = sStrList.Find(pValue);
//const int Indx = (pS==NULL ? 0 : sStrList.Index(pS));
const int Indx = (pS==NULL ? 0 : pS->Index());
DU.SetTypeLong(cType, Indx);
}
else
DU.SetTypeLong(cType, SafeAtoL(pValue));
CXM_ObjectData OD(0, 0, WrkTag(), 0, DU);
if (pEO->XWriteTaggedItem(OD, Route)==TOData_NotFound)
LogWarning(WrkTag(), 0, "Write tag failed");
else
Cnt++;
//if (pEO->XWriteTaggedItem(OD, Route)!=TOData_OK)
// LogWarning(WrkTag(), 0, "Write tag failed (possibly invalid data)");
}
else
LogWarning(WrkTag(), 0, "Unable to read tag");
}
}
p = Nextp;
}
}
//TaggedObject::SetHoldValidateData(false);
//gs_Exec.SetHoldValidateData(false, true, true);
//gs_pTheSFELib->FE_SetHoldGlobalLinks(false);
gs_Exec.EndBulkChange();
//TaggedObject::SetXWritesBusy(false);
return Cnt;
}
//===========================================================================
| [
"[email protected]"
]
| [
[
[
1,
408
]
]
]
|
41c2fdb2d2f3fd57251801ab76caa014644f2ca3 | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/GumpEditor-0.32/diagram/DiagramEditor/DiagramLine.h | f4b42417a8c2425e6f1ccd9b1248979642d869b0 | []
| no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 773 | h | #ifndef _DIAGRAMLINE_H_
#define _DIAGRAMLINE_H_
#include "DiagramEntity.h"
typedef struct {
int x;
int y;
BOOL hit;
} hitParams;
typedef struct {
CRect rect;
BOOL hit;
} hitParamsRect;
class CDiagramLine : public CDiagramEntity
{
public:
CDiagramLine();
virtual ~CDiagramLine() {};
virtual CDiagramEntity* Clone();
static CDiagramEntity* CreateFromString( XML::Node* node );
virtual void Draw( CDC* dc, CRect rect );
virtual int GetHitCode( CPoint point ) const;
virtual HCURSOR GetCursor( int hit ) const;
virtual void SetRect( CRect rect );
virtual BOOL BodyInRect( CRect rect ) const;
protected:
virtual void DrawSelectionMarkers( CDC* dc, CRect rect ) const;
};
#endif // _DIAGRAMLINE_H_
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
]
| [
[
[
1,
41
]
]
]
|
c8caf40178e72113135ef073e7e37825aa6b6d1a | 5dc6c87a7e6459ef8e832774faa4b5ae4363da99 | /vis_avs/r_unkn.cpp | 1550988fe2545c1a398cfb7e75d29de38a652e41 | []
| no_license | aidinabedi/avs4unity | 407603d2fc44bc8b075b54cd0a808250582ee077 | 9b6327db1d092218e96d8907bd14d68b741dcc4d | refs/heads/master | 2021-01-20T15:27:32.449282 | 2010-12-24T03:28:09 | 2010-12-24T03:28:09 | 90,773,183 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,812 | cpp | /*
LICENSE
-------
Copyright 2005 Nullsoft, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Nullsoft nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h"
#include <windows.h>
#include <commctrl.h>
#include "r_defs.h"
#include "resource.h"
#define MOD_NAME "Unknown Render Object"
#include "r_unkn.h"
char *C_UnknClass::get_desc() { return MOD_NAME; }
void C_UnknClass::SetID(int d, char *dString) { id=d; memset(idString,0,sizeof(idString)); strcpy(idString,dString); }
#define PUT_INT(y) data[pos]=(y)&255; data[pos+1]=(y>>8)&255; data[pos+2]=(y>>16)&255; data[pos+3]=(y>>24)&255
#define GET_INT() (data[pos]|(data[pos+1]<<8)|(data[pos+2]<<16)|(data[pos+3]<<24))
void C_UnknClass::load_config(unsigned char *data, int len)
{
if (configdata) GlobalFree(configdata);
configdata=(char *)GlobalAlloc(GMEM_FIXED,len);
memcpy(configdata,data,len);
configdata_len=len;
// char s[1024]="";
// for (int x = 0 ;x < configdata_len; x ++)
// wsprintf(s+strlen(s),"%X,",configdata[x]);
// MessageBox(NULL,s,"loaded config",0);
}
int C_UnknClass::save_config(unsigned char *data)
{
int pos=0;
// char s[1024]="";
// for (int x = 0 ;x < configdata_len; x ++)
// wsprintf(s+strlen(s),"%X,",configdata[x]);
// MessageBox(NULL,s,"saving config",0);
memcpy(data+pos,configdata,configdata_len);
pos+=configdata_len;
return pos;
}
C_UnknClass::C_UnknClass()
{
configdata=0;
configdata_len=0;
id=0;
idString[0]=0;
}
C_UnknClass::~C_UnknClass()
{
if (configdata) GlobalFree(configdata);
configdata=0;
}
int C_UnknClass::render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h)
{
return 0;
}
static C_UnknClass *g_this;
BOOL CALLBACK C_UnknClass::g_DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam,LPARAM lParam)
{
switch (uMsg)
{
case WM_INITDIALOG:
{
char s[512]="";
if (g_this->idString[0]) wsprintf(s,"APE: %s\r\n",g_this->idString);
else wsprintf(s,"Built-in ID: %d\r\n",g_this->id);
wsprintf(s+strlen(s),"Config size: %d\r\n",g_this->configdata_len);
SetDlgItemText(hwndDlg,IDC_EDIT1,s);
}
return 1;
}
return 0;
}
HWND C_UnknClass::conf(HINSTANCE hInstance, HWND hwndParent)
{
g_this = this;
return CreateDialog(hInstance,MAKEINTRESOURCE(IDD_CFG_UNKN),hwndParent,g_DlgProc);
} | [
"[email protected]"
]
| [
[
[
1,
111
]
]
]
|
05733488e04d1ac47135e3d5209b2cec20c14cac | 3d0021b222ddd65b36e61207a8382e841d13e3df | /PathName.h | e629bef75586c9c194f1348534189e1dd90ab4ce | []
| no_license | default0/zeldablackmagic | 1273f5793c4d5bbb594b6da07cf70b52de499392 | f12078b4c3b22d80077e485657538398e8db3b0f | refs/heads/master | 2021-01-10T11:54:31.897192 | 2010-02-10T19:23:04 | 2010-02-10T19:23:04 | 51,330,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,333 | h |
#ifndef PATH_NAME_H
#define PATH_NAME_H
class PathName
{
private:
bool unixStyle;
bool onNetwork;
char separator;
char drive[512];
char dir[512];
char name[512];
char ext[512];
char fullPath[513];
public:
PathName(const char *pathName);
void Init(const char *pathName);
char* ParseDrive(char *pathName);
char* ParseDir(char *pathName);
char* ParseName(char *pathName);
void SetNetwork(bool onNetwork);
void SetUnix(bool onUnix);
void SetSeparator(char newSeparator);
char* GetDrive();
void SetDrive(const char *newDrive);
char* GetDir();
void SetDir(const char *newDir);
char* GetName();
void SetName(const char *newName);
char* GetExt();
void SetExt(const char *newExt);
void MakeDirectory();
void MakePath();
char* GetDirectory();
char* GetFullPath();
PathName* Duplicate();
};
#endif | [
"MathOnNapkins@99ff0a3e-ee68-11de-8de6-035db03795fd"
]
| [
[
[
1,
56
]
]
]
|
61d25071bd2c00f9ba3df1eb9314fe455d4ee48e | 3920e5fc5cbc2512701a3d2f52e072fd50debb83 | /Source/Common/itkManagedParametricPath.cxx | 56967216bb84c5b9733ad332ecc4c4bb8f3733d9 | [
"MIT"
]
| permissive | amirsalah/manageditk | 4063a37d7370dcbcd08bfe9d24d22015d226ceaf | 1ca3a8ea7db221a3b6a578d3c75e3ed941ef8761 | refs/heads/master | 2016-08-12T05:38:03.377086 | 2010-08-02T08:17:32 | 2010-08-02T08:17:32 | 52,595,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,943 | cxx | /*=============================================================================
NOTE: THIS FILE IS A HANDMADE WRAPPER FOR THE ManagedITK PROJECT.
Project: ManagedITK
Program: Insight Segmentation & Registration Toolkit
Module: itkManagedPath.cxx
Language: C++/CLI
Author: Dan Mueller
Date: $Date: 2008-03-09 19:29:02 +0100 (Sun, 09 Mar 2008) $
Revision: $Revision: 8 $
Portions of this code are covered under the ITK and VTK copyright.
See http://www.itk.org/HTML/Copyright.htm for details.
See http://www.vtk.org/copyright.php for details.
Copyright (c) 2007-2008 Daniel Mueller
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.
=============================================================================*/
#pragma once
#pragma warning( disable : 4635 ) // Disable warnings about XML doc comments
#ifndef __itkManagedPath_cxx
#define __itkManagedPath_cxx
// Include some useful ManagedITK files
#include "itkManagedDataObject.cxx"
#include "itkManagedIndex.cxx"
#include "itkManagedContinuousIndex.cxx"
// Use some managed namespaces
#using <mscorlib.dll>
#using <System.dll>
using namespace System;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Diagnostics;
using namespace System::Collections::Generic;
namespace itk
{
#define itkParametricPathInputType System::Double
#define itkParametricPathOutputType itkContinuousIndex
///<summary>
///This abstract class is a managed replacement for itk::ParametricPath.
///</summary>
///<remarks>
///Represent a path through ND image space.
///</remarks>
public ref class itkParametricPath abstract : itkDataObject
{
public:
///<summary>Get the number of dimensions this path contains.</summary>
property unsigned int Dimension
{
virtual unsigned int get( ) = 0;
}
///<summary>
///Get/set the start of the path.
///For most types of paths, the path will begin at zero.
///This value can be overridden in children, and is necessary for
///iterators to know how to go to the beginning of a path.
///</summary>
property itkParametricPathInputType StartOfInput
{
virtual itkParametricPathInputType get( ) = 0;
}
///<summary>
///Get/set the end of the path.
///This value is sometimes used by IncrementInput() to go to the end of a path.
///</summary>
property itkParametricPathInputType EndOfInput
{
virtual itkParametricPathInputType get( ) = 0;
}
///<summary>Evaluate the path at specified location along the path.</summary>
virtual itkParametricPathOutputType^ Evaluate ( itkParametricPathInputType input ) = 0;
///<summary>Evaluate the path at specified location along the path.</summary>
virtual itkIndex^ EvaluateToIndex ( itkParametricPathInputType input ) = 0;
}; // end ref class
} // end namespace itk
#endif | [
"dan.muel@a4e08166-d753-0410-af4e-431cb8890a25"
]
| [
[
[
1,
111
]
]
]
|
3d31fa487a40ac1218a64334a7eea1365ab36add | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Ngllib/src/FileInputBinary.cpp | d81cc7647b69aed8867fbfe3d223091f9243f967 | []
| no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 8,955 | cpp | /*******************************************************************************/
/**
* @file FileInputBinary.cpp.
*
* @brief バイナリファイル入力クラスソースファイル.
*
* @date 2008/07/29.
*
* @version 1.00.
*
* @author Kentarou Nishimura.
*/
/******************************************************************************/
#include "Ngl/FileInputBinary.h"
using namespace Ngl;
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] なし.
*/
FileInputBinary::FileInputBinary()
{}
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] fileName 開くファイル名.
*/
FileInputBinary::FileInputBinary( const std::string& fileName )
{
open( fileName );
}
/*=========================================================================*/
/**
* @brief ファイルを開く
*
* @param[in] fileName 開くファイル名.
* @return なし.
* @throw Ngl::FileOpenEception ファイルオープン例外.
*/
void FileInputBinary::open( const std::string& fileName )
{
// ファイル名を保存
fileName_ = fileName;
// 例外を有効にする
ifStream_.exceptions( std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit );
try{
ifStream_.open( fileName.c_str(), std::ios::in | std::ios::binary );
}
catch( std::ios::failure& e ){
throw Ngl::FileOpenException( e.what() );
}
}
/*=========================================================================*/
/**
* @brief ファイルを閉じる
*
* @param[in] なし.
* @return なし.
*/
void FileInputBinary::close()
{
ifStream_.close();
}
/*=========================================================================*/
/**
* @brief データを読み込む ( char型データを読み込む )
*
* @param[out] data データを設定する変数.
* @return 読み込んだデータ.
* @throw Ngl::FileReadException ファイル読み込み例外.
*/
void FileInputBinary::read( char& data )
{
ifStream_.read( reinterpret_cast< char* >( &data ), sizeof( char ) );
}
/*=========================================================================*/
/**
* @brief データを読み込む ( string型データを読み込む )
*
* @param[out] data データを設定する変数.
* @return 読み込んだデータ.
* @throw Ngl::FileReadException ファイル読み込み例外.
*/
void FileInputBinary::read( std::string& data )
{
}
/*=========================================================================*/
/**
* @brief データを読み込む ( short型データを読み込む )
*
* @param[out] data データを設定する変数.
* @return 読み込んだデータ.
* @throw Ngl::FileReadException ファイル読み込み例外.
*/
void FileInputBinary::read( short& data )
{
ifStream_.read( reinterpret_cast< char* >( &data ), sizeof( short ) );
}
/*=========================================================================*/
/**
* @brief データを読み込む ( unsigned short型データを読み込む )
*
* @param[out] data データを設定する変数.
* @return 読み込んだデータ.
* @throw Ngl::FileReadException ファイル読み込み例外.
*/
void FileInputBinary::read( unsigned short& data )
{
ifStream_.read( reinterpret_cast< char* >( &data ), sizeof( unsigned short ) );
}
/*=========================================================================*/
/**
* @brief データを読み込む ( int型データを読み込む )
*
* @param[out] data データを設定する変数.
* @return 読み込んだデータ.
* @throw Ngl::FileReadException ファイル読み込み例外.
*/
void FileInputBinary::read( int& data )
{
ifStream_.read( reinterpret_cast< char* >( &data ), sizeof( data ) );
}
/*=========================================================================*/
/**
* @brief データを読み込む ( unsigned int型データを読み込む )
*
* @param[out] data データを設定する変数.
* @return 読み込んだデータ.
* @throw Ngl::FileReadException ファイル読み込み例外.
*/
void FileInputBinary::read( unsigned int& data )
{
ifStream_.read( reinterpret_cast< char* >( &data ), sizeof( unsigned int ) );
}
/*=========================================================================*/
/**
* @brief データを読み込む ( long型データを読み込む )
*
* @param[out] data データを設定する変数.
* @return 読み込んだデータ.
* @throw Ngl::FileReadException ファイル読み込み例外.
*/
void FileInputBinary::read( long& data )
{
ifStream_.read( reinterpret_cast< char* >( &data ), sizeof( long ) );
}
/*=========================================================================*/
/**
* @brief データを読み込む ( unsigned long型データを読み込む )
*
* @param[out] data データを設定する変数.
* @return 読み込んだデータ.
* @throw Ngl::FileReadException ファイル読み込み例外.
*/
void FileInputBinary::read( unsigned long& data )
{
ifStream_.read( reinterpret_cast< char* >( &data ), sizeof( unsigned long ) );
}
/*=========================================================================*/
/**
* @brief データを読み込む ( float型データを読み込む )
*
* @param[out] data データを設定する変数.
* @return 読み込んだデータ.
* @throw Ngl::FileReadException ファイル読み込み例外.
*/
void FileInputBinary::read( float& data )
{
ifStream_.read( reinterpret_cast< char* >( &data ), sizeof( float ) );
}
/*=========================================================================*/
/**
* @brief データを読み込む ( double型データを読み込む )
*
* @param[out] data データを設定する変数.
* @return 読み込んだデータ.
* @throw Ngl::FileReadException ファイル読み込み例外.
*/
void FileInputBinary::read( double& data )
{
ifStream_.read( reinterpret_cast< char* >( &data ), sizeof( double ) );
}
/*=========================================================================*/
/**
* @brief >> 演算子オーバーロード ( マニピュレータ用 )
*
* @param[out] func マニピュレータの関数ポインタ.
* @return 入力ストリームの参照.
*/
IInputStream& FileInputBinary::operator >> ( IInputStream& (*func)(IInputStream&) )
{
return (*func)(*this);
}
/*=========================================================================*/
/**
* @brief 指定バイト数分読み込む
*
* @param[in] dest 読み込んだデータを格納するデータ.
* @param[in] size 読み込むサイズ.
* @return なし.
*/
void FileInputBinary::read( char* dest, unsigned int size )
{
ifStream_.read( dest, size );
}
/*=========================================================================*/
/**
* @brief 指定位置にシークする
*
* @param[in] offset 移動する位置.
* @param[in] flag シークフラグ.
* @return なし.
*/
void FileInputBinary::seek( unsigned int offset, SeekFlug flag )
{
std::ios_base::seek_dir way = std::ios::beg;
switch( flag )
{
case SEEKFLUG_BEG:
way = std::ios::beg;
break;
case SEEKFLUG_CUR:
way = std::ios::cur;
break;
case SEEKFLUG_END:
way = std::ios::end;
break;
}
ifStream_.seekg( offset, way );
}
/*=========================================================================*/
/**
* @brief 現在位置を取得する
*
* @param[in] なし.
* @return 現在位置のバイト数.
*/
unsigned int FileInputBinary::tell()
{
return ifStream_.tellg();
}
/*=========================================================================*/
/**
* @brief ストリーム読み込みタイプを設定する
*
* @param[out] type 設定する読み込みタイプ.
* @return なし.
*/
void FileInputBinary::readType( StreamReadType type )
{
readType_ = type;
}
/*=========================================================================*/
/**
* @brief ストリーム読み込みタイプを取得する
*
* @param[out] なし.
* @return ストリームタイプ.
*/
StreamReadType FileInputBinary::readType()
{
return readType_;
}
/*=========================================================================*/
/**
* @brief ストリーム名を取得する
*
* @param[in] なし.
* @return ストリーム名.
*/
const std::string& FileInputBinary::streamName() const
{
return fileName_;
}
/*===== EOF ==================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
]
| [
[
[
1,
341
]
]
]
|
42f471b149db169eebd5827da4415ccb2e1fadae | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /StopModeDebugger/edebugger.h | 107182d803bde86174b6e0d850b4b8ad857f000a | []
| 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 | 3,039 | h | // edebugger.h
//
// Copyright (c) 1998-1999 Symbian Ltd. All rights reserved.
//
#ifndef __EDEBUGGER_H__
#define __EDEBUGGER_H__
#include "epoc.h"
#include "ddebugger.h"
// global source control
#define __TRACE TRACE
#define __DEBUG_NEW
#define __HALT_NOTIFICATION__ // host debugger supports halt notification
#define __SHADOW_ROM_PAGES__ // target allows ROM pages to be shadowed
// #define __DEBUG_CHUNKS__
// #define __DEBUG_THREADS__
//
// Class for accessing the target's debugger
//
struct TShadowPage
{
int iAge;
//
TLinAddr iRomPage;
TLinAddr iRamPage;
TUint32 iRomPte;
};
enum TRegister
{
R0, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, R13, R14, R15, // CPU registers
R8_FIQ, R9_FIQ, R10_FIQ, R11_FIQ, R12_FIQ, R13_FIQ, R14_FIQ, // FIQ mode shadowed registers
R13_IRQ, R14_IRQ, // IRQ mode shadowed registers
R13_SVC, R14_SVC, // SVC mode shadowed registers
CP15_DACR, CP15_R0, CP15_R1, CP15_R2, // CP15 (MMU) registers
// etc... etc...
}
class EpocDebugger
{
public:
EpocDebugger(const Hardware &aHardware);
~EpocDebugger();
int Create();
// target accessors
TLinAddr Debugger();
bool IsRomAddress(TLinAddr aAddress);
bool ReadWord(TLinAddr address, TUint32 * word);
bool WriteWord(TLinAddr address, TUint32 word);
bool ReadMemory(TLinAddr address, int count, TUint32 * buffer);
bool WriteMemory(TLinAddr address, int count, TUint32 * buffer);
bool ReadDes(TLinAddr address, char * buffer);
bool ReadRegister(TRegister reg, TUint32 * value);
bool WriteRegister(TRegister reg, TUint32 * value);
// object handling
TLinAddr FindLibrary(const char *aLibName);
TLinAddr FindProcess(const char *aLibName);
bool ReadChunks();
// thread and process handing
TLinAddr CurrentThread();
TLinAddr CurrentProcess();
TLinAddr OwningProcess(TLinAddr aThread);
TUint32 Handle(TLinAddr aObject);
int NumberOfProcesses();
int NumberOfThreads();
TPhysAddr LinearToPhysical(TLinAddr aLinAddr);
// breakpoint handing
bool SetBreakPoint(TLinAddr address);
bool ClearBreakPoint(TLinAddr address);
bool Copy(TLinAddr dest, TLinAddr src, int count);
// MMU handling
bool Flush();
bool UnlockDomains(TUint32 &dacr);
bool LockDomains(TUint32 dacr);
private:
int NextFreeBreakPointIndex();
int BreakPointIndex(TLinAddr address);
int BreakPointCount(TLinAddr page);
void FreeShadowPage(int aShadowPageIndex);
int NextFreeShadowPage();
TLinAddr ShadowChunkBase();
int ShadowPageIndex(TLinAddr page);
TLinAddr ShadowPageAddress(TLinAddr aRomAddress);
bool ShadowPage(TLinAddr page);
bool ThawShadowPage(TLinAddr address);
bool FreezeShadowPage(TLinAddr address);
public:
Hardware *iHardware; // the target hardware interface
TLinAddr iDebugger; // the address of the DPassiveDebugger structure on the target
//
TLinAddr *iBreakPoints;
TUint32 *iBreakInstruction;
TShadowPage *iShadowPages;
TDebugEntryChunk *iChunks;
TInt iChunkCount;
};
#endif | [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
]
| [
[
[
1,
110
]
]
]
|
3ce2d167b45732a511924337088ccf44411a6ba0 | 6520b2b1c45e5a9e5996a9205142de6e2e2cb7ea | /AHL/wolfilair/src/lib/font/CustomFont.cpp | 77cd4560705e82e7bb39b959d226c1f5eb5c1780 | []
| no_license | xpierro/ahl | 6207bc2c309a7f2e4bf659e86fcbf4d889250d82 | 8efd98a6ecc32d794a1e957b0b91eb017546fdf1 | refs/heads/master | 2020-06-04T00:59:13.590942 | 2010-10-21T04:09:48 | 2010-10-21T04:09:48 | 41,411,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,579 | cpp | /*
* CustomFont.cpp
*
* Created on: 19 oct. 2010
* Author: Pierre
*/
#include "CustomFont.h"
#include <cell/sysmodule.h>
namespace PS3 {
CustomFont::CustomFont(string path) : Font() {
fontPath = path;
load();
}
CustomFont::~CustomFont() { }
void CustomFont::load() {
cellFontOpenFontFile(getLibrary(), (uint8_t*) fontPath.c_str(), 0,
getFontId(), getFontDescriptor());
cellFontSetResolutionDpi(getFontDescriptor(), 72, 72);
cellFontSetScalePoint(getFontDescriptor(), 60, 60);
}
void CustomFont::unload() { }
}
/*
void Font::getTextDimensions(string str, float& width, float& height) {
CellFontHorizontalLayout layout;
CellFontGlyphMetrics metrics;
cellFontGetHorizontalLayout(&font, &layout);
// Specify write position
float x = 0.0f;
float y = layout.baseLineY; // Base line position (spacing from top line)
int charsInLine = 0; // count
int lineNb = 0;
string::iterator it = str.begin();
char c = *it;
while (it != str.end()) {
if (c == '\n') {
charsInLine = 0;
} else if (c >= ' ') {
cellFontGetCharGlyphMetrics(&font, c, &metrics);
if (charsInLine == 0) {
//!\ may be Vertical or X bearing
x = - metrics.Horizontal.bearingY; // Align first character of each line at the left side
y += layout.lineHeight; // Line feed
lineNb += 1;
}
x += metrics.Horizontal.advance; // Add advance
charsInLine += 1;
}
c = *(++it);
}
width = x - metrics.Horizontal.advance + metrics.width;
height = lineNb * layout.lineHeight;
}*/
| [
"[email protected]"
]
| [
[
[
1,
67
]
]
]
|
354f5f3adcaa3fc3ba37370cb35ba6005a9bb436 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Framework/NodeClouds.cpp | dd24b1f49435a07da8a204e1828c841c083ba26a | []
| 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 | 25,480 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: NodeClouds.cpp
Version: 0.13
---------------------------------------------------------------------------
*/
#define NOMINMAX
#include "NodeClouds.h"
#include "Camera.h"
#include "ITexture.h"
#include "LightStage.h"
#include "Material.h"
#include "MaterialLibrary.h"
#include "MaterialManager.h"
#include "PerlinNoise.h"
#include "PostStage.h"
#include "Shader.h"
#include "ShaderConstant.h"
#include "ShaderInstance.h"
#include "TextureManager.h"
#include "TextureSampler.h"
#include "TimeDate.h"
#include "Timer.h"
#include "VertexBufferManager.h"
namespace nGENE
{
namespace Nature
{
// Initialize static members
TypeInfo NodeClouds::Type(L"NodeClouds", &NodeVisible::Type);
NodeClouds::NodeClouds():
m_pCloudsMat(NULL),
m_pCloudsMatHDR(NULL),
m_pCloudsDensityMat(NULL),
m_fDayLength(360.0f),
m_fCover(0.5f),
m_fSharpness(0.94f),
m_fDensity(0.02f),
m_fHorizonLevel(0.0f),
m_fHorizonHeight(10.0f),
m_fTextureScaling(1.0f),
m_bSimulate(true),
m_bFixed(false),
m_SunAngle(0.0f),
m_dwPassedTime(0),
m_dwUpdateFrequency(1000)
{
m_SunRise.hours = 8;
m_Sunset.hours = 22;
}
//----------------------------------------------------------------------
NodeClouds::NodeClouds(const CLOUDS_DESC& _desc):
m_Desc(_desc),
m_pCloudsMat(NULL),
m_pCloudsMatHDR(NULL),
m_pCloudsDensityMat(NULL),
m_fDayLength(360.0f),
m_fCover(0.45f),
m_fDensity(0.02f),
m_fSharpness(0.94f),
m_fHorizonLevel(0.0f),
m_fHorizonHeight(10.0f),
m_fTextureScaling(1.0f),
m_bSimulate(true),
m_bFixed(false),
m_SunAngle(0.0f),
m_dwPassedTime(0),
m_dwUpdateFrequency(10000)
{
m_SunRise.hours = 8;
m_Sunset.hours = 22;
}
//----------------------------------------------------------------------
NodeClouds::~NodeClouds()
{
}
//----------------------------------------------------------------------
void NodeClouds::init()
{
createCloudsPlane();
initTextures();
// Add clouds material
m_PostCloudsDensity.priority = 0;
m_PostCloudsDensity.material = m_pCloudsDensityMat;
((PostStage*)Renderer::getSingleton().getRenderStage(L"PostProcess"))->addToRender(&m_PostCloudsDensity);
m_PostClouds.priority = 1;
m_PostClouds.material = m_pCloudsMatHDR;
((PostStage*)Renderer::getSingleton().getRenderStage(L"PostProcess"))->addToRender(&m_PostClouds);
Surface* surf = getSurface(L"Base");
surf->setMaterial(m_pCloudsMat);
surf->flipWindingOrder();
surf->setPickable(false);
// Set default parameters for shaders
setCloudCover(m_fCover);
setCloudSharpness(m_fSharpness);
setCloudDensity(m_fDensity);
setTextureScaling(m_fTextureScaling);
setHorizonLevel(m_fHorizonLevel);
setHorizonHeight(m_fHorizonHeight);
// Simulate at least once
updateColours();
updateClouds();
m_dwLastTime = Engine::getSingleton().getTimer().getMilliseconds();
}
//----------------------------------------------------------------------
void NodeClouds::initTextures()
{
// Create textures
ITexture* pCloudsSrc = TextureManager::getSingleton().createTexture(L"cloud_cover_source",
m_Desc.textureSize,
m_Desc.textureSize,
TT_2D,
TU_DYNAMIC,
TF_A8);
ITexture* pCloudsDest = TextureManager::getSingleton().createTexture(L"cloud_cover_destination",
m_Desc.textureSize,
m_Desc.textureSize,
TT_2D,
TU_DYNAMIC,
TF_A8);
// Generate Perlin noise
nGENE::byte* pCloudMap = createCloudNoise();
pCloudsSrc->setData(pCloudMap);
NGENE_DELETE_ARRAY(pCloudMap);
pCloudMap = createCloudNoise();
pCloudsDest->setData(pCloudMap);
NGENE_DELETE_ARRAY(pCloudMap);
// Set non HDR version
m_pCloudsMat = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"clouds_NON_HDR");
if(m_pCloudsMat)
{
TextureSampler sampler;
sampler.setTexture(pCloudsSrc);
sampler.setTextureUnit(1);
sampler.setAddressingMode(TAM_MIRROR);
RenderPass& pass = m_pCloudsMat->getActiveRenderTechnique()->getRenderPass(0);
pass.addTextureSampler(sampler);
sampler.setTexture(pCloudsDest);
sampler.setTextureUnit(2);
sampler.setAddressingMode(TAM_MIRROR);
pass.addTextureSampler(sampler);
}
// Same goes for HDR version
m_pCloudsMatHDR = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"clouds_HDR");
if(m_pCloudsMatHDR)
{
TextureSampler sampler;
sampler.setTexture(pCloudsSrc);
sampler.setTextureUnit(1);
sampler.setAddressingMode(TAM_WRAP);
RenderPass& pass = m_pCloudsMatHDR->getActiveRenderTechnique()->getRenderPass(0);
pass.addTextureSampler(sampler);
sampler.setTexture(pCloudsDest);
sampler.setTextureUnit(2);
sampler.setAddressingMode(TAM_WRAP);
pass.addTextureSampler(sampler);
}
// And cloud map generator
m_pCloudsDensityMat = MaterialManager::getSingleton().getLibrary(L"default")->getMaterial(L"clouds_density");
if(m_pCloudsDensityMat)
{
TextureSampler sampler;
sampler.setTexture(pCloudsSrc);
sampler.setTextureUnit(1);
sampler.setAddressingMode(TAM_WRAP);
RenderPass& pass = m_pCloudsDensityMat->getActiveRenderTechnique()->getRenderPass(0);
pass.addTextureSampler(sampler);
sampler.setTexture(pCloudsDest);
sampler.setTextureUnit(2);
sampler.setAddressingMode(TAM_WRAP);
pass.addTextureSampler(sampler);
}
}
//----------------------------------------------------------------------
void NodeClouds::updateTextures()
{
dword delta = static_cast<float>(Engine::getSingleton().getTimer().getMilliseconds() - m_dwLastTime);
Timer time = Engine::getSingleton().getTimer();
m_dwLastTime = time.getMilliseconds();
bool bHDR = ((LightStage*)Renderer::getSingleton().getRenderStage(L"Light"))->isUsingHDR();
Material* pMat = bHDR ? m_pCloudsMatHDR : m_pCloudsMat;
if(bHDR)
{
getSurface(L"Base")->setEnabled(false);
m_pCloudsMatHDR->setEnabled(true);
}
else
{
bool prev = getSurface(L"Base")->isEnabled();
if(!prev)
{
ITexture* pTexture = TextureManager::getSingleton().getTexture(L"cloud_cover_map");
pTexture->clearRenderTarget();
getSurface(L"Base")->setEnabled(true);
m_pCloudsMatHDR->setEnabled(false);
}
}
m_dwPassedTime += delta;
if(m_dwPassedTime > m_dwUpdateFrequency && m_dwUpdateFrequency)
{
m_dwPassedTime -= m_dwUpdateFrequency;
// Create textures
ITexture* pCloudsSrc = TextureManager::getSingleton().getTexture(L"cloud_cover_source");
ITexture* pCloudsDest = TextureManager::getSingleton().getTexture(L"cloud_cover_destination");
// Generate Perlin noise
void* pCloudMap = pCloudsDest->getData();
pCloudsSrc->setData(pCloudMap);
NGENE_DELETE_ARRAY(pCloudMap);
pCloudMap = createCloudNoise();
pCloudsDest->setData(pCloudMap);
NGENE_DELETE_ARRAY(pCloudMap);
}
if(pMat)
{
RenderPass& pass = pMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("timer");
float t = 0.0f;
if(m_dwUpdateFrequency)
t = (float)m_dwPassedTime / (float)m_dwUpdateFrequency;
if(pConstant)
pConstant->setDefaultValue(&t);
}
if(m_pCloudsDensityMat)
{
RenderPass& pass = m_pCloudsDensityMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("timer");
float t = 0.0f;
if(m_dwUpdateFrequency)
t = (float)m_dwPassedTime / (float)m_dwUpdateFrequency;
if(pConstant)
pConstant->setDefaultValue(&t);
}
}
//----------------------------------------------------------------------
void NodeClouds::reset()
{
initTextures();
}
//----------------------------------------------------------------------
nGENE::byte* NodeClouds::createCloudNoise()
{
uint nSize = m_Desc.textureSize;
// 2-dimensional Perlin noise
PerlinNoise <2> clouds(nSize);
clouds.setup();
// Generate Perlin noise
nGENE::byte* pCloudMap = new nGENE::byte[nSize * nSize];
memset(pCloudMap, 0, sizeof(nGENE::byte) * nSize * nSize);
for(uint i = 0; i < nSize; ++i)
{
for(uint j = 0; j < nSize; ++j)
{
vector <uint> inds;
inds.push_back(i);
inds[0] %= nSize;
Maths::clamp <uint> (inds[0], 1, nSize - 2);
inds.push_back(j);
inds[1] %= nSize;
Maths::clamp <uint> (inds[1], 1, nSize - 2);
pCloudMap[i * nSize + j] += (nSize + clouds.smooth(inds) * static_cast<float>((int)nSize - 1));
}
}
return pCloudMap;
}
//----------------------------------------------------------------------
void NodeClouds::createCloudsPlane()
{
// Set vertices
uint verticesRow = m_Desc.verticesCount;
dword dwNumVertices = verticesRow * verticesRow;
SVertex* pVertices = new SVertex[dwNumVertices];
memset(pVertices, 0, dwNumVertices * sizeof(SVertex));
float b = -m_Desc.domeHeight;
float fRadius = m_Desc.domeRadius;
float fRadiusDouble = fRadius * 2.0f;
float fRadiusPerIter = fRadiusDouble / static_cast<float>(verticesRow - 1);
uint index = 0;
for(uint z = 0; z < verticesRow; ++z)
{
for(uint x = 0; x < verticesRow; ++x)
{
float X = x * fRadiusPerIter - fRadius;
float Z = z * fRadiusPerIter - fRadius;
pVertices[index].vecPosition.x = X;
pVertices[index].vecPosition.z = Z;
pVertices[index].vecPosition.y = b * (X * X + Z * Z);
pVertices[index].vecTexCoord = Vector2((X + fRadius) / fRadiusDouble,
(Z + fRadius) / fRadiusDouble);
++index;
}
}
// Set indices
dword dwNumIndices = (verticesRow - 1) * (verticesRow - 1) * 6;
short* pIndices = new short[dwNumIndices];
uint begin = 0;
for(uint i = 0; i < dwNumIndices; i += 6)
{
pIndices[i + 0] = begin;
pIndices[i + 1] = begin + 1;
pIndices[i + 2] = begin + verticesRow + 1;
pIndices[i + 3] = begin;
pIndices[i + 4] = begin + verticesRow + 1;
pIndices[i + 5] = begin + verticesRow;
if((++begin + 1) % verticesRow == 0)
++begin;
}
VertexBuffer* vb;
IndexedBuffer* ivb;
VertexBufferManager& manager = VertexBufferManager::getSingleton();
INDEXEDBUFFER_DESC ivbDesc;
ivbDesc.indices = pIndices;
ivbDesc.indicesNum = dwNumIndices;
ivb = manager.createIndexedBuffer(ivbDesc);
VERTEXBUFFER_DESC vbDesc;
vbDesc.vertices = pVertices;
vbDesc.verticesNum = dwNumVertices;
vbDesc.primitivesNum = dwNumIndices / 3;
vbDesc.primitivesType = PT_TRIANGLELIST;
vbDesc.indices = ivb;
vbDesc.vertexDeclaration = manager.getVertexDeclaration(L"Default");
vb = manager.createVertexBuffer(vbDesc);
Surface temp;
temp.setVertexBuffer(vb);
addSurface(L"Base", temp);
NGENE_DELETE_ARRAY(pIndices);
NGENE_DELETE_ARRAY(pVertices);
}
//----------------------------------------------------------------------
void NodeClouds::setDayTime(const TimeDate& _time)
{
m_Time = _time;
float fPassed = _time.hours * 3600.0f + _time.minutes * 60.0f + _time.seconds;
float fSunRise = m_SunRise.hours * 3600.0f + m_SunRise.minutes * 60.0f + m_SunRise.seconds;
float fSunset = m_Sunset.hours * 3600.0f + m_Sunset.minutes * 60.0f + m_Sunset.seconds;
float fDayLength = fSunset - fSunRise;
m_SunAngle = (fPassed - fSunRise) / (fDayLength) * 180.0f;
Maths::clamp <float> (m_SunAngle, 0.0f, 180.0f);
updateColours();
updateClouds();
}
//----------------------------------------------------------------------
void NodeClouds::onUpdate()
{
if(!m_bFixed)
{
Camera* pCamera = Engine::getSingleton().getActiveCamera();
if(pCamera)
{
Vector3& cameraPos = pCamera->getPositionLocal();
setPosition(cameraPos.x,
getPositionLocal().y,
cameraPos.z);
Node::applyTransform();
}
}
NodeVisible::onUpdate();
// Update textures
updateTextures();
// No need to run simulation
if(!m_bSimulate)
return;
dword delta = static_cast<float>(Engine::getSingleton().getTimer().getMilliseconds() - m_dwLastTime);
Timer time = Engine::getSingleton().getTimer();
m_dwLastTime = time.getMilliseconds();
m_SunAngle += (float)delta * 0.18f / m_fDayLength;
Maths::clamp_roll <float> (m_SunAngle, 0.0f, 180.0f);
updateColours();
updateClouds();
}
//----------------------------------------------------------------------
void NodeClouds::updateColours()
{
if(m_SunAngle <= 105.0f)
{
float fPassed = m_SunAngle / 75.0f;
Maths::clamp(fPassed, 0.0f, 1.0f);
m_SunColour.setRed(Maths::lerp <int>(205, 255, fPassed));
m_SunColour.setGreen(Maths::lerp <int>(92, 255, fPassed));
m_SunColour.setBlue(Maths::lerp <int>(92, 255, fPassed));
}
else if(m_SunAngle > 105.0f)
{
float fPassed = (m_SunAngle - 105.0f) / 75.0f;
m_SunColour.setRed(Maths::lerp <int>(255, 255, fPassed));
m_SunColour.setGreen(Maths::lerp <int>(255, 85, fPassed));
m_SunColour.setBlue(Maths::lerp <int>(255, 20, fPassed));
}
}
//----------------------------------------------------------------------
void NodeClouds::updateClouds()
{
float angle = m_SunAngle * Maths::PI / 180.0;
bool bHDR = ((LightStage*)Renderer::getSingleton().getRenderStage(L"Light"))->isUsingHDR();
Material* pMat = bHDR ? m_pCloudsMatHDR : m_pCloudsMat;
if(bHDR)
{
getSurface(L"Base")->setEnabled(false);
m_pCloudsMatHDR->setEnabled(true);
}
else
{
bool prev = getSurface(L"Base")->isEnabled();
if(!prev)
{
ITexture* pTexture = TextureManager::getSingleton().getTexture(L"cloud_cover_map");
pTexture->clearRenderTarget();
getSurface(L"Base")->setEnabled(true);
m_pCloudsMatHDR->setEnabled(false);
}
}
if(pMat)
{
RenderPass& pass = pMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
Vector3 dir = Vector3(-cos(angle), -sin(angle), 0.0f);
pConstant = pShader->getConstant("lightDir");
if(pConstant)
pConstant->setDefaultValue(dir.getData());
float colour[3] = {(float)m_SunColour.getRed() / 255.0f,
(float)m_SunColour.getGreen() / 255.0f,
(float)m_SunColour.getBlue() / 255.0f};
pConstant = pShader->getConstant("SunColor");
if(pConstant)
pConstant->setDefaultValue(colour);
}
}
//----------------------------------------------------------------------
void NodeClouds::setCloudCover(float _value)
{
m_fCover = _value;
if(m_pCloudsMat)
{
RenderPass& pass = m_pCloudsMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
float cover = _value;
pConstant = pShader->getConstant("cloudCover");
if(pConstant)
pConstant->setDefaultValue(&cover);
}
if(m_pCloudsMatHDR)
{
RenderPass& pass = m_pCloudsMatHDR->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
float cover = _value;
pConstant = pShader->getConstant("cloudCover");
if(pConstant)
pConstant->setDefaultValue(&cover);
}
if(m_pCloudsDensityMat)
{
RenderPass& pass = m_pCloudsDensityMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
float cover = _value;
pConstant = pShader->getConstant("cloudCover");
if(pConstant)
pConstant->setDefaultValue(&cover);
}
}
//----------------------------------------------------------------------
void NodeClouds::setCloudSharpness(float _value)
{
m_fSharpness = _value;
if(m_pCloudsMat)
{
RenderPass& pass = m_pCloudsMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
float sharpness = _value;
pConstant = pShader->getConstant("cloudSharpness");
if(pConstant)
pConstant->setDefaultValue(&sharpness);
}
if(m_pCloudsMatHDR)
{
RenderPass& pass = m_pCloudsMatHDR->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
float sharpness = _value;
pConstant = pShader->getConstant("cloudSharpness");
if(pConstant)
pConstant->setDefaultValue(&sharpness);
}
if(m_pCloudsDensityMat)
{
RenderPass& pass = m_pCloudsDensityMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
float sharpness = _value;
pConstant = pShader->getConstant("cloudSharpness");
if(pConstant)
pConstant->setDefaultValue(&sharpness);
}
}
//----------------------------------------------------------------------
void NodeClouds::setTextureScaling(float _value)
{
m_fTextureScaling = _value;
if(m_pCloudsMat)
{
RenderPass& pass = m_pCloudsMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("textureScaling");
if(pConstant)
pConstant->setDefaultValue(&m_fTextureScaling);
}
if(m_pCloudsMatHDR)
{
RenderPass& pass = m_pCloudsMatHDR->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("textureScaling");
if(pConstant)
pConstant->setDefaultValue(&m_fTextureScaling);
}
if(m_pCloudsDensityMat)
{
RenderPass& pass = m_pCloudsDensityMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("textureScaling");
if(pConstant)
pConstant->setDefaultValue(&m_fTextureScaling);
}
}
//----------------------------------------------------------------------
void NodeClouds::setCloudDensity(float _value)
{
m_fDensity = _value;
if(m_pCloudsMat)
{
RenderPass& pass = m_pCloudsMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("cloudDensity");
if(pConstant)
pConstant->setDefaultValue(&m_fDensity);
}
if(m_pCloudsMatHDR)
{
RenderPass& pass = m_pCloudsMatHDR->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("cloudDensity");
if(pConstant)
pConstant->setDefaultValue(&m_fDensity);
}
}
//----------------------------------------------------------------------
void NodeClouds::setHorizonLevel(float _value)
{
m_fHorizonLevel = _value;
if(m_pCloudsMat)
{
RenderPass& pass = m_pCloudsMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("horizonLevel");
if(pConstant)
pConstant->setDefaultValue(&m_fHorizonLevel);
}
if(m_pCloudsMatHDR)
{
RenderPass& pass = m_pCloudsMatHDR->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("horizonLevel");
if(pConstant)
pConstant->setDefaultValue(&m_fHorizonLevel);
}
}
//----------------------------------------------------------------------
void NodeClouds::setHorizonHeight(float _value)
{
m_fHorizonHeight = _value;
if(m_pCloudsMat)
{
RenderPass& pass = m_pCloudsMat->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("horizonHeight");
if(pConstant)
pConstant->setDefaultValue(&m_fHorizonHeight);
}
if(m_pCloudsMatHDR)
{
RenderPass& pass = m_pCloudsMatHDR->getActiveRenderTechnique()->getRenderPass(0);
Shader* pShader = pass.getPixelShader()->getShader();
ShaderConstant* pConstant = NULL;
pConstant = pShader->getConstant("horizonHeight");
if(pConstant)
pConstant->setDefaultValue(&m_fHorizonHeight);
}
}
//----------------------------------------------------------------------
void NodeClouds::serialize(ISerializer* _serializer, bool _serializeType, bool _serializeChildren)
{
if(_serializeType) _serializer->addObject(this->Type);
Node::serialize(_serializer, false, true);
Property <float> prDomeRadius(m_Desc.domeRadius);
_serializer->addProperty("DomeRadius", prDomeRadius);
Property <float> prDomeHeight(m_Desc.domeHeight);
_serializer->addProperty("DomeHeight", prDomeHeight);
Property <float> prDayLength(m_fDayLength);
_serializer->addProperty("DayLength", prDayLength);
Property <float> prCover(m_fCover);
_serializer->addProperty("Cover", prCover);
Property <float> prSharpness(m_fSharpness);
_serializer->addProperty("Sharpness", prSharpness);
Property <float> prDensity(m_fDensity);
_serializer->addProperty("Density", prDensity);
Property <float> prHorizonLevel(m_fHorizonLevel);
_serializer->addProperty("HorizonLevel", prHorizonLevel);
Property <float> prHorizonHeight(m_fHorizonHeight);
_serializer->addProperty("HorizonHeight", prHorizonHeight);
Property <float> prTexScale(m_fTextureScaling);
_serializer->addProperty("TextureScaling", prTexScale);
Property <bool> prSimulate(m_bSimulate);
_serializer->addProperty("Simulated", prSimulate);
Property <bool> prFixed(m_bFixed);
_serializer->addProperty("Fixed", prFixed);
Property <uint> prTexSize(m_Desc.textureSize);
_serializer->addProperty("TextureSize", prTexSize);
Property <uint> prVertsCount(m_Desc.verticesCount);
_serializer->addProperty("VerticesCount", prVertsCount);
Property <dword> prFrequency(m_dwUpdateFrequency);
_serializer->addProperty("UpdateFrequency", prFrequency);
Property <TimeDate> prTime(m_Time);
_serializer->addProperty("Time", prTime);
Property <TimeDate> prSunRise(m_SunRise);
_serializer->addProperty("SunRise", prSunRise);
Property <TimeDate> prSunset(m_Sunset);
_serializer->addProperty("Sunset", prSunset);
if(_serializeType) _serializer->endObject(this->Type);
}
//----------------------------------------------------------------------
void NodeClouds::deserialize(ISerializer* _serializer)
{
Property <float> prDomeRadius(m_Desc.domeRadius);
_serializer->getProperty("DomeRadius", prDomeRadius);
Property <float> prDomeHeight(m_Desc.domeHeight);
_serializer->getProperty("DomeHeight", prDomeHeight);
Property <float> prDayLength(m_fDayLength);
_serializer->getProperty("DayLength", prDayLength);
Property <float> prCover(m_fCover);
_serializer->getProperty("Cover", prCover);
Property <float> prSharpness(m_fSharpness);
_serializer->getProperty("Sharpness", prSharpness);
Property <float> prDensity(m_fDensity);
_serializer->getProperty("Density", prDensity);
Property <float> prHorizonLevel(m_fHorizonLevel);
_serializer->getProperty("HorizonLevel", prHorizonLevel);
Property <float> prHorizonHeight(m_fHorizonHeight);
_serializer->getProperty("HorizonHeight", prHorizonHeight);
Property <float> prTexScale(m_fTextureScaling);
_serializer->getProperty("TextureScaling", prTexScale);
Property <bool> prSimulate(m_bSimulate);
_serializer->getProperty("Simulated", prSimulate);
Property <bool> prFixed(m_bFixed);
_serializer->getProperty("Fixed", prFixed);
Property <uint> prTexSize(m_Desc.textureSize);
_serializer->getProperty("TextureSize", prTexSize);
Property <uint> prVertsCount(m_Desc.verticesCount);
_serializer->getProperty("VerticesCount", prVertsCount);
Property <dword> prFrequency(m_dwUpdateFrequency);
_serializer->getProperty("UpdateFrequency", prFrequency);
Property <TimeDate> prTime(m_Time);
_serializer->getProperty("Time", prTime);
Property <TimeDate> prSunRise(m_SunRise);
_serializer->getProperty("SunRise", prSunRise);
Property <TimeDate> prSunset(m_Sunset);
_serializer->getProperty("Sunset", prSunset);
Property <bool> prLightable(m_bLightable);
_serializer->getProperty("Lightable", prLightable);
Node::deserialize(_serializer);
}
//----------------------------------------------------------------------
}
} | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
815
]
]
]
|
84d657c3470eb29c05aa537e747e901fc9748429 | 22fb52fc26ab1da21ab837a507524f111df5b694 | /voxelbrain/undo.h | 3869d00819b9660fcdfc8d5bd914bbbdf98483b7 | []
| no_license | yangguang-ecnu/voxelbrain | b343cec00e7b76bc46cc12723f750185fa84e6d2 | 82e1912ff69998077a5d7ecca9b5b1f9d7c1b948 | refs/heads/master | 2021-01-10T01:21:59.902255 | 2009-02-10T05:24:40 | 2009-02-10T05:24:40 | 52,189,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | #ifndef UNDO_H_
#define UNDO_H_
//#include "v3sets.h"
#include <vector>
using namespace std;
struct undo {
undo(){ clear(); };
typedef std::vector<unsigned int> undo_step;
typedef std::vector<undo_step> undo_buffer;
undo_buffer the_undo;
undo_step cur_step;
void clear(); //reset the undo stack
void add_point(size_t); //add a point to the current step
void save(); //save current step in the stack
void restore(undo_step &); //pop the step from stack.
bool empty();
};
#endif /*UNDO_H_*/
| [
"konstantin.levinski@04f5dad0-e037-0410-8c28-d9c1d3725aa7"
]
| [
[
[
1,
24
]
]
]
|
4fa6a2ca8b10c856486e90adcd89bffaee07e35c | d6a28d9d845a20463704afe8ebe644a241dc1a46 | /source/Irrlicht/CSoftwareDriver.cpp | 6671dec1564ce4d715a53218fb67346dd9a57154 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive",
"Zlib"
]
| permissive | marky0720/irrlicht-android | 6932058563bf4150cd7090d1dc09466132df5448 | 86512d871eeb55dfaae2d2bf327299348cc5202c | refs/heads/master | 2021-04-30T08:19:25.297407 | 2010-10-08T08:27:33 | 2010-10-08T08:27:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,777 | cpp | // Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#include "CSoftwareDriver.h"
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
#include "CSoftwareTexture.h"
#include "os.h"
#include "S3DVertex.h"
namespace irr
{
namespace video
{
//! constructor
CSoftwareDriver::CSoftwareDriver(const core::dimension2d<u32>& windowSize, bool fullscreen, io::IFileSystem* io, video::IImagePresenter* presenter)
: CNullDriver(io, windowSize), BackBuffer(0), Presenter(presenter), WindowId(0),
SceneSourceRect(0), RenderTargetTexture(0), RenderTargetSurface(0),
CurrentTriangleRenderer(0), ZBuffer(0), Texture(0)
{
#ifdef _DEBUG
setDebugName("CSoftwareDriver");
#endif
// create backbuffer
BackBuffer = new CImage(ECF_A1R5G5B5, windowSize);
if (BackBuffer)
{
BackBuffer->fill(SColor(0));
// create z buffer
ZBuffer = video::createZBuffer(BackBuffer->getDimension());
}
DriverAttributes->setAttribute("MaxTextures", 1);
DriverAttributes->setAttribute("MaxIndices", 1<<16);
DriverAttributes->setAttribute("MaxTextureSize", 1024);
DriverAttributes->setAttribute("Version", 1);
// create triangle renderers
TriangleRenderers[ETR_FLAT] = createTriangleRendererFlat(ZBuffer);
TriangleRenderers[ETR_FLAT_WIRE] = createTriangleRendererFlatWire(ZBuffer);
TriangleRenderers[ETR_GOURAUD] = createTriangleRendererGouraud(ZBuffer);
TriangleRenderers[ETR_GOURAUD_WIRE] = createTriangleRendererGouraudWire(ZBuffer);
TriangleRenderers[ETR_TEXTURE_FLAT] = createTriangleRendererTextureFlat(ZBuffer);
TriangleRenderers[ETR_TEXTURE_FLAT_WIRE] = createTriangleRendererTextureFlatWire(ZBuffer);
TriangleRenderers[ETR_TEXTURE_GOURAUD] = createTriangleRendererTextureGouraud(ZBuffer);
TriangleRenderers[ETR_TEXTURE_GOURAUD_WIRE] = createTriangleRendererTextureGouraudWire(ZBuffer);
TriangleRenderers[ETR_TEXTURE_GOURAUD_NOZ] = createTriangleRendererTextureGouraudNoZ();
TriangleRenderers[ETR_TEXTURE_GOURAUD_ADD] = createTriangleRendererTextureGouraudAdd(ZBuffer);
// select render target
setRenderTarget(BackBuffer);
// select the right renderer
selectRightTriangleRenderer();
}
//! destructor
CSoftwareDriver::~CSoftwareDriver()
{
// delete Backbuffer
if (BackBuffer)
BackBuffer->drop();
// delete triangle renderers
for (s32 i=0; i<ETR_COUNT; ++i)
if (TriangleRenderers[i])
TriangleRenderers[i]->drop();
// delete zbuffer
if (ZBuffer)
ZBuffer->drop();
// delete current texture
if (Texture)
Texture->drop();
if (RenderTargetTexture)
RenderTargetTexture->drop();
if (RenderTargetSurface)
RenderTargetSurface->drop();
}
//! switches to a triangle renderer
void CSoftwareDriver::switchToTriangleRenderer(ETriangleRenderer renderer)
{
video::IImage* s = 0;
if (Texture)
s = ((CSoftwareTexture*)Texture)->getTexture();
CurrentTriangleRenderer = TriangleRenderers[renderer];
CurrentTriangleRenderer->setBackfaceCulling(Material.BackfaceCulling == true);
CurrentTriangleRenderer->setTexture(s);
CurrentTriangleRenderer->setRenderTarget(RenderTargetSurface, ViewPort);
}
//! void selects the right triangle renderer based on the render states.
void CSoftwareDriver::selectRightTriangleRenderer()
{
ETriangleRenderer renderer = ETR_FLAT;
if (Texture)
{
if (!Material.GouraudShading)
renderer = (!Material.Wireframe) ? ETR_TEXTURE_FLAT : ETR_TEXTURE_FLAT_WIRE;
else
{
if (Material.Wireframe)
renderer = ETR_TEXTURE_GOURAUD_WIRE;
else
{
if (Material.MaterialType == EMT_TRANSPARENT_ADD_COLOR ||
Material.MaterialType == EMT_TRANSPARENT_ALPHA_CHANNEL ||
Material.MaterialType == EMT_TRANSPARENT_VERTEX_ALPHA)
{
// simply draw all transparent stuff with the same renderer. at
// least it is transparent then.
renderer = ETR_TEXTURE_GOURAUD_ADD;
}
else
if ((Material.ZBuffer==ECFN_NEVER) && !Material.ZWriteEnable)
renderer = ETR_TEXTURE_GOURAUD_NOZ;
else
{
renderer = ETR_TEXTURE_GOURAUD;
}
}
}
}
else
{
if (!Material.GouraudShading)
renderer = (!Material.Wireframe) ? ETR_FLAT : ETR_FLAT_WIRE;
else
renderer = (!Material.Wireframe) ? ETR_GOURAUD : ETR_GOURAUD_WIRE;
}
switchToTriangleRenderer(renderer);
}
//! queries the features of the driver, returns true if feature is available
bool CSoftwareDriver::queryFeature(E_VIDEO_DRIVER_FEATURE feature) const
{
switch (feature)
{
case EVDF_RENDER_TO_TARGET:
case EVDF_TEXTURE_NSQUARE:
return FeatureEnabled[feature];
default:
return false;
};
}
//! sets transformation
void CSoftwareDriver::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat)
{
TransformationMatrix[state] = mat;
}
//! sets the current Texture
bool CSoftwareDriver::setActiveTexture(u32 stage, video::ITexture* texture)
{
if (texture && texture->getDriverType() != EDT_SOFTWARE)
{
os::Printer::log("Fatal Error: Tried to set a texture not owned by this driver.", ELL_ERROR);
return false;
}
if (Texture)
Texture->drop();
Texture = texture;
if (Texture)
Texture->grab();
selectRightTriangleRenderer();
return true;
}
//! sets a material
void CSoftwareDriver::setMaterial(const SMaterial& material)
{
Material = material;
OverrideMaterial.apply(Material);
for (u32 i = 0; i < 1; ++i)
{
setActiveTexture(i, Material.getTexture(i));
setTransform ((E_TRANSFORMATION_STATE) ( ETS_TEXTURE_0 + i ),
material.getTextureMatrix(i));
}
}
//! clears the zbuffer
bool CSoftwareDriver::beginScene(bool backBuffer, bool zBuffer, SColor color,
const SExposedVideoData& videoData, core::rect<s32>* sourceRect)
{
CNullDriver::beginScene(backBuffer, zBuffer, color, videoData, sourceRect);
WindowId=videoData.D3D9.HWnd;
SceneSourceRect = sourceRect;
if (backBuffer && BackBuffer)
BackBuffer->fill(color);
if (ZBuffer && zBuffer)
ZBuffer->clear();
return true;
}
//! presents the rendered scene on the screen, returns false if failed
bool CSoftwareDriver::endScene()
{
CNullDriver::endScene();
return Presenter->present(BackBuffer, WindowId, SceneSourceRect);
}
//! returns a device dependent texture from a software surface (IImage)
//! THIS METHOD HAS TO BE OVERRIDDEN BY DERIVED DRIVERS WITH OWN TEXTURES
ITexture* CSoftwareDriver::createDeviceDependentTexture(IImage* surface, const io::path& name, void* mipmapData)
{
return new CSoftwareTexture(surface, name, false, mipmapData);
}
//! sets a render target
bool CSoftwareDriver::setRenderTarget(video::ITexture* texture, bool clearBackBuffer,
bool clearZBuffer, SColor color)
{
if (texture && texture->getDriverType() != EDT_SOFTWARE)
{
os::Printer::log("Fatal Error: Tried to set a texture not owned by this driver.", ELL_ERROR);
return false;
}
if (RenderTargetTexture)
RenderTargetTexture->drop();
RenderTargetTexture = texture;
if (RenderTargetTexture)
{
RenderTargetTexture->grab();
setRenderTarget(((CSoftwareTexture*)RenderTargetTexture)->getTexture());
}
else
{
setRenderTarget(BackBuffer);
}
if (RenderTargetSurface && (clearBackBuffer || clearZBuffer))
{
if (clearZBuffer)
ZBuffer->clear();
if (clearBackBuffer)
((video::CImage*)RenderTargetSurface)->fill( color );
}
return true;
}
//! sets a render target
void CSoftwareDriver::setRenderTarget(video::CImage* image)
{
if (RenderTargetSurface)
RenderTargetSurface->drop();
RenderTargetSurface = image;
RenderTargetSize.Width = 0;
RenderTargetSize.Height = 0;
Render2DTranslation.X = 0;
Render2DTranslation.Y = 0;
if (RenderTargetSurface)
{
RenderTargetSurface->grab();
RenderTargetSize = RenderTargetSurface->getDimension();
}
setViewPort(core::rect<s32>(0,0,RenderTargetSize.Width,RenderTargetSize.Height));
if (ZBuffer)
ZBuffer->setSize(RenderTargetSize);
}
//! sets a viewport
void CSoftwareDriver::setViewPort(const core::rect<s32>& area)
{
ViewPort = area;
//TODO: the clipping is not correct, because the projection is affected.
// to correct this, ViewPortSize and Render2DTranslation will have to be corrected.
core::rect<s32> rendert(0,0,RenderTargetSize.Width,RenderTargetSize.Height);
ViewPort.clipAgainst(rendert);
ViewPortSize = core::dimension2du(ViewPort.getSize());
Render2DTranslation.X = (ViewPortSize.Width / 2) + ViewPort.UpperLeftCorner.X;
Render2DTranslation.Y = ViewPort.UpperLeftCorner.Y + ViewPortSize.Height - (ViewPortSize.Height / 2);// + ViewPort.UpperLeftCorner.Y;
if (CurrentTriangleRenderer)
CurrentTriangleRenderer->setRenderTarget(RenderTargetSurface, ViewPort);
}
void CSoftwareDriver::drawVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType)
{
switch (iType)
{
case (EIT_16BIT):
{
drawVertexPrimitiveList16(vertices, vertexCount, (const u16*)indexList, primitiveCount, vType, pType);
break;
}
case (EIT_32BIT):
{
os::Printer::log("Software driver can not render 32bit buffers", ELL_ERROR);
break;
}
}
}
//! draws a vertex primitive list
void CSoftwareDriver::drawVertexPrimitiveList16(const void* vertices, u32 vertexCount, const u16* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType)
{
const u16* indexPointer=0;
core::array<u16> newBuffer;
switch (pType)
{
case scene::EPT_LINE_STRIP:
{
switch (vType)
{
case EVT_STANDARD:
{
for (u32 i=0; i < primitiveCount-1; ++i)
draw3DLine(((S3DVertex*)vertices)[indexList[i]].Pos,
((S3DVertex*)vertices)[indexList[i+1]].Pos,
((S3DVertex*)vertices)[indexList[i]].Color);
}
break;
case EVT_2TCOORDS:
{
for (u32 i=0; i < primitiveCount-1; ++i)
draw3DLine(((S3DVertex2TCoords*)vertices)[indexList[i]].Pos,
((S3DVertex2TCoords*)vertices)[indexList[i+1]].Pos,
((S3DVertex2TCoords*)vertices)[indexList[i]].Color);
}
break;
case EVT_TANGENTS:
{
for (u32 i=0; i < primitiveCount-1; ++i)
draw3DLine(((S3DVertexTangents*)vertices)[indexList[i]].Pos,
((S3DVertexTangents*)vertices)[indexList[i+1]].Pos,
((S3DVertexTangents*)vertices)[indexList[i]].Color);
}
break;
}
}
return;
case scene::EPT_LINE_LOOP:
drawVertexPrimitiveList16(vertices, vertexCount, indexList, primitiveCount-1, vType, scene::EPT_LINE_STRIP);
switch (vType)
{
case EVT_STANDARD:
draw3DLine(((S3DVertex*)vertices)[indexList[primitiveCount-1]].Pos,
((S3DVertex*)vertices)[indexList[0]].Pos,
((S3DVertex*)vertices)[indexList[primitiveCount-1]].Color);
break;
case EVT_2TCOORDS:
draw3DLine(((S3DVertex2TCoords*)vertices)[indexList[primitiveCount-1]].Pos,
((S3DVertex2TCoords*)vertices)[indexList[0]].Pos,
((S3DVertex2TCoords*)vertices)[indexList[primitiveCount-1]].Color);
break;
case EVT_TANGENTS:
draw3DLine(((S3DVertexTangents*)vertices)[indexList[primitiveCount-1]].Pos,
((S3DVertexTangents*)vertices)[indexList[0]].Pos,
((S3DVertexTangents*)vertices)[indexList[primitiveCount-1]].Color);
break;
}
return;
case scene::EPT_LINES:
{
switch (vType)
{
case EVT_STANDARD:
{
for (u32 i=0; i < 2*primitiveCount; i+=2)
draw3DLine(((S3DVertex*)vertices)[indexList[i]].Pos,
((S3DVertex*)vertices)[indexList[i+1]].Pos,
((S3DVertex*)vertices)[indexList[i]].Color);
}
break;
case EVT_2TCOORDS:
{
for (u32 i=0; i < 2*primitiveCount; i+=2)
draw3DLine(((S3DVertex2TCoords*)vertices)[indexList[i]].Pos,
((S3DVertex2TCoords*)vertices)[indexList[i+1]].Pos,
((S3DVertex2TCoords*)vertices)[indexList[i]].Color);
}
break;
case EVT_TANGENTS:
{
for (u32 i=0; i < 2*primitiveCount; i+=2)
draw3DLine(((S3DVertexTangents*)vertices)[indexList[i]].Pos,
((S3DVertexTangents*)vertices)[indexList[i+1]].Pos,
((S3DVertexTangents*)vertices)[indexList[i]].Color);
}
break;
}
}
return;
case scene::EPT_TRIANGLE_FAN:
{
// TODO: don't convert fan to list
newBuffer.reallocate(primitiveCount*3);
for( u32 t=0; t<primitiveCount; ++t )
{
newBuffer.push_back(indexList[0]);
newBuffer.push_back(indexList[t+1]);
newBuffer.push_back(indexList[t+2]);
}
indexPointer = newBuffer.pointer();
}
break;
case scene::EPT_TRIANGLES:
indexPointer=indexList;
break;
default:
return;
}
switch (vType)
{
case EVT_STANDARD:
drawClippedIndexedTriangleListT((S3DVertex*)vertices, vertexCount, indexPointer, primitiveCount);
break;
case EVT_2TCOORDS:
drawClippedIndexedTriangleListT((S3DVertex2TCoords*)vertices, vertexCount, indexPointer, primitiveCount);
break;
case EVT_TANGENTS:
drawClippedIndexedTriangleListT((S3DVertexTangents*)vertices, vertexCount, indexPointer, primitiveCount);
break;
}
}
template<class VERTEXTYPE>
void CSoftwareDriver::drawClippedIndexedTriangleListT(const VERTEXTYPE* vertices,
s32 vertexCount, const u16* indexList, s32 triangleCount)
{
if (!RenderTargetSurface || !ZBuffer || !triangleCount)
return;
if (!checkPrimitiveCount(triangleCount))
return;
// arrays for storing clipped vertices
core::array<VERTEXTYPE> clippedVertices;
core::array<u16> clippedIndices;
// calculate inverse world transformation
core::matrix4 worldinv(TransformationMatrix[ETS_WORLD]);
worldinv.makeInverse();
// calculate view frustum planes
scene::SViewFrustum frustum(TransformationMatrix[ETS_PROJECTION] * TransformationMatrix[ETS_VIEW]);
// copy and transform clipping planes ignoring far plane
core::plane3df planes[5]; // ordered by near, left, right, bottom, top
for (int p=0; p<5; ++p)
worldinv.transformPlane(frustum.planes[p+1], planes[p]);
core::EIntersectionRelation3D inout[3]; // is point in front or back of plane?
// temporary buffer for vertices to be clipped by all planes
core::array<VERTEXTYPE> tClpBuf;
int t;
int i;
for (i=0; i<triangleCount; ++i) // for all input triangles
{
// add next triangle to tempClipBuffer
for (t=0; t<3; ++t)
tClpBuf.push_back(vertices[indexList[(i*3)+t]]);
for (int p=0; p<5; ++p) // for all clip planes
for (int v=0; v<(int)tClpBuf.size(); v+=3) // for all vertices in temp clip buffer
{
int inside = 0;
int outside = 0;
// test intersection relation of the current vertices
for (t=0; t<3; ++t)
{
inout[t] = planes[p].classifyPointRelation(tClpBuf[v+t].Pos);
if (inout[t] != core::ISREL3D_FRONT)
++inside;
else
if (inout[t] == core::ISREL3D_FRONT)
++outside;
}
if (!outside)
{
// add all vertices to new buffer, this triangle needs no clipping.
// so simply don't change this part of the temporary triangle buffer
continue;
}
if (!inside)
{
// all vertices are outside, don't add this triangle, so erase this
// triangle from the tClpBuf
tClpBuf.erase(v,3);
v -= 3;
continue;
}
// this vertex has to be clipped by this clipping plane.
// The following lines represent my try to implement some real clipping.
// There is a bug somewhere, and after some time I've given up.
// So now it is commented out, resulting that triangles which would need clipping
// are simply taken out (in the next two lines).
#ifndef __SOFTWARE_CLIPPING_PROBLEM__
tClpBuf.erase(v,3);
v -= 3;
#endif
/*
// my idea is the following:
// current vertex to next vertex relation:
// out - out : add nothing
// out - in : add middle point
// in - out : add first and middle point
// in - in : add both
// now based on the number of intersections, create new vertices
// into tClpBuf (at the front for not letting them be clipped again)
int added = 0;
int prev = v+2;
for (int index=v; index<v+3; ++index)
{
if (inout[prev] == core::ISREL3D_BACK)
{
if (inout[index] != core::ISREL3D_BACK)
{
VERTEXTYPE& vt1 = tClpBuf[prev];
VERTEXTYPE& vt2 = tClpBuf[index];
f32 fact = planes[p].getKnownIntersectionWithLine(vt1.Pos, vt2.Pos);
VERTEXTYPE nvt;
nvt.Pos = vt1.Pos.getInterpolated(vt2.Pos, fact);
nvt.Color = vt1.Color.getInterpolated(vt2.Color, fact);
nvt.TCoords = vt1.TCoords.getInterpolated(vt2.TCoords, fact);
tClpBuf.push_front(nvt); ++index; ++prev; ++v;
++added;
}
}
else
{
if (inout[index] != core::ISREL3D_BACK)
{
VERTEXTYPE vt1 = tClpBuf[index];
VERTEXTYPE vt2 = tClpBuf[prev];
tClpBuf.push_front(vt1); ++index; ++prev; ++v;
tClpBuf.push_front(vt2); ++index; ++prev; ++v;
added+= 2;
}
else
{
// same as above, but other way round.
VERTEXTYPE vt1 = tClpBuf[index];
VERTEXTYPE vt2 = tClpBuf[prev];
f32 fact = planes[p].getKnownIntersectionWithLine(vt1.Pos, vt2.Pos);
VERTEXTYPE nvt;
nvt.Pos = vt1.Pos.getInterpolated(vt2.Pos, fact);
nvt.Color = vt1.Color.getInterpolated(vt2.Color, fact);
nvt.TCoords = vt1.TCoords.getInterpolated(vt2.TCoords, fact);
tClpBuf.push_front(vt2); ++index; ++prev; ++v;
tClpBuf.push_front(nvt); ++index; ++prev; ++v;
added += 2;
}
}
prev = index;
}
// erase original vertices
tClpBuf.erase(v,3);
v -= 3;
*/
} // end for all clip planes
// now add all remaining triangles in tempClipBuffer to clippedIndices
// and clippedVertices array.
if (clippedIndices.size() + tClpBuf.size() < 65535)
for (t=0; t<(int)tClpBuf.size(); ++t)
{
clippedIndices.push_back(clippedVertices.size());
clippedVertices.push_back(tClpBuf[t]);
}
tClpBuf.clear();
} // end for all input triangles
// draw newly created triangles.
// -----------------------------------------------------------
// here all triangles are being drawn. I put this in a separate
// method, but the visual studio 6 compiler has great problems
// with templates and didn't accept two template methods in this
// class.
// draw triangles
CNullDriver::drawVertexPrimitiveList(clippedVertices.pointer(), clippedVertices.size(),
clippedIndices.pointer(), clippedIndices.size()/3, EVT_STANDARD, scene::EPT_TRIANGLES, EIT_16BIT);
if (TransformedPoints.size() < clippedVertices.size())
TransformedPoints.set_used(clippedVertices.size());
if (TransformedPoints.empty())
return;
const VERTEXTYPE* currentVertex = clippedVertices.pointer();
S2DVertex* tp = &TransformedPoints[0];
core::dimension2d<u32> textureSize(0,0);
f32 zDiv;
if (Texture)
textureSize = ((CSoftwareTexture*)Texture)->getTexture()->getDimension();
f32 transformedPos[4]; // transform all points in the list
core::matrix4 matrix(TransformationMatrix[ETS_PROJECTION]);
matrix *= TransformationMatrix[ETS_VIEW];
matrix *= TransformationMatrix[ETS_WORLD];
s32 ViewTransformWidth = (ViewPortSize.Width>>1);
s32 ViewTransformHeight = (ViewPortSize.Height>>1);
for (i=0; i<(int)clippedVertices.size(); ++i)
{
transformedPos[0] = currentVertex->Pos.X;
transformedPos[1] = currentVertex->Pos.Y;
transformedPos[2] = currentVertex->Pos.Z;
transformedPos[3] = 1.0f;
matrix.multiplyWith1x4Matrix(transformedPos);
zDiv = transformedPos[3] == 0.0f ? 1.0f : (1.0f / transformedPos[3]);
tp->Pos.X = (s32)(ViewTransformWidth * (transformedPos[0] * zDiv) + (Render2DTranslation.X));
tp->Pos.Y = (Render2DTranslation.Y - (s32)(ViewTransformHeight * (transformedPos[1] * zDiv)));
tp->Color = currentVertex->Color.toA1R5G5B5();
tp->ZValue = (TZBufferType)(32767.0f * zDiv);
tp->TCoords.X = (s32)(currentVertex->TCoords.X * textureSize.Width);
tp->TCoords.X <<= 8;
tp->TCoords.Y = (s32)(currentVertex->TCoords.Y * textureSize.Height);
tp->TCoords.Y <<= 8;
++currentVertex;
++tp;
}
// draw all transformed points from the index list
CurrentTriangleRenderer->drawIndexedTriangleList(&TransformedPoints[0],
clippedVertices.size(), clippedIndices.pointer(), clippedIndices.size()/3);
}
//! Draws a 3d line.
void CSoftwareDriver::draw3DLine(const core::vector3df& start,
const core::vector3df& end, SColor color)
{
core::vector3df vect = start.crossProduct(end);
vect.normalize();
vect *= Material.Thickness*0.3f;
S3DVertex vtx[4];
vtx[0].Color = color;
vtx[1].Color = color;
vtx[2].Color = color;
vtx[3].Color = color;
vtx[0].Pos = start;
vtx[1].Pos = end;
vtx[2].Pos = start + vect;
vtx[3].Pos = end + vect;
u16 idx[12] = {0,1,2, 0,2,1, 0,1,3, 0,3,1};
drawIndexedTriangleList(vtx, 4, idx, 4);
}
//! clips a triangle against the viewing frustum
void CSoftwareDriver::clipTriangle(f32* transformedPos)
{
}
//! Only used by the internal engine. Used to notify the driver that
//! the window was resized.
void CSoftwareDriver::OnResize(const core::dimension2d<u32>& size)
{
// make sure width and height are multiples of 2
core::dimension2d<u32> realSize(size);
if (realSize.Width % 2)
realSize.Width += 1;
if (realSize.Height % 2)
realSize.Height += 1;
if (ScreenSize != realSize)
{
if (ViewPort.getWidth() == (s32)ScreenSize.Width &&
ViewPort.getHeight() == (s32)ScreenSize.Height)
{
ViewPort = core::rect<s32>(core::position2d<s32>(0,0),
core::dimension2di(realSize));
}
ScreenSize = realSize;
bool resetRT = (RenderTargetSurface == BackBuffer);
if (BackBuffer)
BackBuffer->drop();
BackBuffer = new CImage(ECF_A1R5G5B5, realSize);
if (resetRT)
setRenderTarget(BackBuffer);
}
}
//! returns the current render target size
const core::dimension2d<u32>& CSoftwareDriver::getCurrentRenderTargetSize() const
{
return RenderTargetSize;
}
//! draws an 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted.
void CSoftwareDriver::draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos,
const core::rect<s32>& sourceRect,
const core::rect<s32>* clipRect, SColor color,
bool useAlphaChannelOfTexture)
{
if (texture)
{
if (texture->getDriverType() != EDT_SOFTWARE)
{
os::Printer::log("Fatal Error: Tried to copy from a surface not owned by this driver.", ELL_ERROR);
return;
}
if (useAlphaChannelOfTexture)
((CSoftwareTexture*)texture)->getImage()->copyToWithAlpha(
RenderTargetSurface, destPos, sourceRect, color, clipRect);
else
((CSoftwareTexture*)texture)->getImage()->copyTo(
RenderTargetSurface, destPos, sourceRect, clipRect);
}
}
//! Draws a 2d line.
void CSoftwareDriver::draw2DLine(const core::position2d<s32>& start,
const core::position2d<s32>& end,
SColor color)
{
RenderTargetSurface->drawLine(start, end, color );
}
//! Draws a pixel
void CSoftwareDriver::drawPixel(u32 x, u32 y, const SColor & color)
{
BackBuffer->setPixel(x, y, color, true);
}
//! draw a 2d rectangle
void CSoftwareDriver::draw2DRectangle(SColor color, const core::rect<s32>& pos,
const core::rect<s32>* clip)
{
if (clip)
{
core::rect<s32> p(pos);
p.clipAgainst(*clip);
if(!p.isValid())
return;
RenderTargetSurface->drawRectangle(p, color);
}
else
{
if(!pos.isValid())
return;
RenderTargetSurface->drawRectangle(pos, color);
}
}
//!Draws an 2d rectangle with a gradient.
void CSoftwareDriver::draw2DRectangle(const core::rect<s32>& pos,
SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown,
const core::rect<s32>* clip)
{
// TODO: implement
draw2DRectangle(colorLeftUp, pos, clip);
}
//! \return Returns the name of the video driver. Example: In case of the Direct3D8
//! driver, it would return "Direct3D8.1".
const wchar_t* CSoftwareDriver::getName() const
{
return L"Irrlicht Software Driver 1.0";
}
//! Returns type of video driver
E_DRIVER_TYPE CSoftwareDriver::getDriverType() const
{
return EDT_SOFTWARE;
}
//! returns color format
ECOLOR_FORMAT CSoftwareDriver::getColorFormat() const
{
if (BackBuffer)
return BackBuffer->getColorFormat();
else
return CNullDriver::getColorFormat();
}
//! Returns the transformation set by setTransform
const core::matrix4& CSoftwareDriver::getTransform(E_TRANSFORMATION_STATE state) const
{
return TransformationMatrix[state];
}
//! Creates a render target texture.
ITexture* CSoftwareDriver::addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name,
const ECOLOR_FORMAT format)
{
CImage* img = new CImage(video::ECF_A1R5G5B5, size);
ITexture* tex = new CSoftwareTexture(img, name, true);
img->drop();
addTexture(tex);
tex->drop();
return tex;
}
//! Clears the ZBuffer.
void CSoftwareDriver::clearZBuffer()
{
if (ZBuffer)
ZBuffer->clear();
}
//! Returns an image created from the last rendered frame.
IImage* CSoftwareDriver::createScreenShot()
{
if (BackBuffer)
{
CImage* tmp = new CImage(BackBuffer->getColorFormat(), BackBuffer->getDimension());
BackBuffer->copyTo(tmp);
return tmp;
}
else
return 0;
}
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
u32 CSoftwareDriver::getMaximalPrimitiveCount() const
{
return 0x00800000;
}
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_SOFTWARE_
namespace irr
{
namespace video
{
//! creates a video driver
IVideoDriver* createSoftwareDriver(const core::dimension2d<u32>& windowSize, bool fullscreen, io::IFileSystem* io, video::IImagePresenter* presenter)
{
#ifdef _IRR_COMPILE_WITH_SOFTWARE_
return new CSoftwareDriver(windowSize, fullscreen, io, presenter);
#else
return 0;
#endif
}
} // end namespace video
} // end namespace irr
| [
"Rogerborg@dfc29bdd-3216-0410-991c-e03cc46cb475",
"hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475",
"monstrobishi@dfc29bdd-3216-0410-991c-e03cc46cb475",
"bitplane@dfc29bdd-3216-0410-991c-e03cc46cb475"
]
| [
[
[
1,
4
],
[
6,
40
],
[
46,
140
],
[
142,
183
],
[
185,
208
],
[
210,
212
],
[
214,
221
],
[
223,
223
],
[
226,
246
],
[
255,
335
],
[
337,
356
],
[
358,
808
],
[
810,
811
],
[
813,
819
],
[
822,
822
],
[
824,
825
],
[
827,
829
],
[
831,
846
],
[
848,
853
],
[
855,
872
],
[
874,
901
],
[
905,
926
],
[
932,
968
]
],
[
[
5,
5
],
[
41,
45
],
[
141,
141
],
[
209,
209
],
[
222,
222
],
[
224,
225
],
[
247,
254
],
[
336,
336
],
[
357,
357
],
[
809,
809
],
[
812,
812
],
[
820,
821
],
[
823,
823
],
[
826,
826
],
[
830,
830
],
[
847,
847
],
[
854,
854
],
[
903,
903
],
[
927,
931
],
[
969,
969
]
],
[
[
184,
184
],
[
213,
213
],
[
902,
902
],
[
904,
904
]
],
[
[
873,
873
]
]
]
|
ef7479986af1116cdadee030fa9feb55c2f495f4 | 6b75de27b75015e5622bfcedbee0bf65e1c6755d | /link-list/LinkedList.cpp | a7cde47ac545e3007810ce38366ef3fae0c81a45 | []
| no_license | xhbang/data_structure | 6e4ac9170715c0e45b78f8a1b66c838f4031a638 | df2ff9994c2d7969788f53d90291608ac5b1ef2b | refs/heads/master | 2020-04-04T02:07:18.620014 | 2011-12-05T09:39:34 | 2011-12-05T09:39:34 | 2,393,408 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,121 | cpp | /*实验六
实验名称:泛型程序设计和STL编程
实验类型:验证型
实验目的:了解C++标准模板STL的容器类的
使用方法;应用标准C++模板库(STL)通用算
法和函数对象实现查找和排序。
实验原理:数组类、链表、栈类和队列类以
及查找、排序算法的使用技术;C++标准模板库(STL)的
使用方法,泛型程序设计的机制。
实验内容:
(1) 使用C++标准模板库(STL)中的双向对
列类(deque)编写程序实现链表类(LinkedList)。
在测试程序中声明两个整型队列A和B,分别插入5个元素,
然后把B中的元素加入A的尾部;
(2) 声明一个整型数组,使用C++标准模板库(STL)
中的查找算法find()进行数据的查找,然后应用排序算法Sort(),
并配合使用标准函数对象Greater<T>对数据进行升序和降序排序。
*/
#include<iostream>
#include<deque>
#include<string>
using namespace std;
template<typename T>
class LinkedList{
private:
deque<T> head;
public:
LinkedList()
{
}
LinkedList(deque<T> de)
{
head = de;
}
/*
~LinkedList(){
destroy head;
}
*/
void push_back(const T& ele)
{
head.push_back(ele);
}
void push_front(const T& ele)
{
head.push_front(ele);
}
void push_mid(const int loc,const T& ele)
{
deque<T>::iterator iter;
int i;
if(loc>head.size()+1 || loc<=0)
throw 1;
T tem=ele;
T tem1;
for(i=1,iter=head.begin();iter!=head.end();i++,iter++)
if(i>=loc)
if(i==loc)
{
tem=*iter;
*iter=ele;
}
else
{
tem1=tem;
tem=*iter;
*iter=tem1;
/*tem=tem+*iter;
*iter=tem-*iter;
tem=tem-*iter;*/
}
head.push_back(tem);
}
LinkedList<T> operator + (LinkedList<T>& L)
{
deque<T>::iterator iter;
for(iter=L.head.begin();iter!=L.head.end();iter++)
{
head.push_back(*iter);
}
return *this;
}
friend ostream& operator <<(ostream& os,LinkedList<T>& L)
{
deque<T>::iterator iter;
for(iter=L.head.begin();iter!=L.head.end();iter++)
{
os<<*iter;
if(iter!=L.head.end()-1)
os<<"->";
}
return os;
}
};
int main()
{
int loc;
bool isOk=false;
string ele;
deque<string> A(5,"99");
deque<string> B(5,"abc");
LinkedList<string> list1(A);
LinkedList<string> list2(B);
cout<<list1<<endl;
cout<<list2<<endl;
cout<<"====================================="<<endl;
list1.push_front("A");
list2.push_front("B");
cout<<list1<<endl;
cout<<list2<<endl;
cout<<"====================================="<<endl;
cout<<"请输入插入的元素值:";
cin>>ele;
while(!isOk){
try{
cout<<"请输入插入位置:";
cin>>loc;
list2.push_mid(loc,ele);
isOk=true;
}catch(int x){
cout<<"不是一个合适的位置!"<<endl;
isOk=false;
}
}
cout<<list2<<endl;
cout<<"====================================="<<endl;
list1+list2;
cout<<"list1+list2 = "<<list1+list2<<endl;
return 0;
} | [
"[email protected]"
]
| [
[
[
1,
151
]
]
]
|
faea2b8f538282a76591ee5f0724378faba84424 | 1585c7e187eec165138edbc5f1b5f01d3343232f | /СПиОС/PiChat/PiChat/PiChatServer/PiChatServerDlg.h | 96729ba8bb574051aca4d0f55769872b52b87ee5 | []
| no_license | a-27m/vssdb | c8885f479a709dd59adbb888267a03fb3b0c3afb | d86944d4d93fd722e9c27cb134256da16842f279 | refs/heads/master | 2022-08-05T06:50:12.743300 | 2011-06-23T08:35:44 | 2011-06-23T08:35:44 | 82,612,001 | 1 | 0 | null | 2021-03-29T08:05:33 | 2017-02-20T23:07:03 | C# | UTF-8 | C++ | false | false | 846 | h |
// PiChatServerDlg.h : header file
//
#pragma once
#include "afxwin.h"
#include "mylist.h"
#define MAX_CLIENT 100
// CPiSrvDlg dialog
class CPiSrvDlg : public CDialog
{
// Construction
public:
CPiSrvDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_PICHATSERVER_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
CWinThread* srvMainThread;
CMyList<CString> listText;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CListBox m_log;
CListBox m_usr;
void WriteLine(CString str) { listText.AddFirst(str); }
};
| [
"Axell@bf672a44-3a04-1d4a-850b-c2a239875c8c"
]
| [
[
[
1,
42
]
]
]
|
a6e59d77cb0d1210d6be72090d49fcd2ed050d3f | b8fe0ddfa6869de08ba9cd434e3cf11e57d59085 | /ouan-tests/TestInput/main.cpp | 2bc2aca0e6f2c9f3e2f27c245d64bf0dcb325362 | []
| no_license | juanjmostazo/ouan-tests | c89933891ed4f6ad48f48d03df1f22ba0f3ff392 | eaa73fb482b264d555071f3726510ed73bef22ea | refs/heads/master | 2021-01-10T20:18:35.918470 | 2010-06-20T15:45:00 | 2010-06-20T15:45:00 | 38,101,212 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 499 | cpp | /* OGREUPC 05 - ANIMATIONS */
#include <iostream>
#include "Application.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char **argv)
#endif
{
try
{
Application app;
app.initialise();
app.go();
}
catch ( std::exception& e )
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| [
"ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde"
]
| [
[
[
1,
27
]
]
]
|
94437a1a3f8d3e8cc80652c62079f7f004b16b1b | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/I18n.cpp | 07845805bc546375251f972c86a04f6cee41e1dc | []
| no_license | mikezhoubill/emule-gifc | e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60 | 46979cf32a313ad6d58603b275ec0b2150562166 | refs/heads/master | 2021-01-10T20:37:07.581465 | 2011-08-13T13:58:37 | 2011-08-13T13:58:37 | 32,465,033 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 17,353 | cpp | #include "stdafx.h"
#include <locale.h>
#include "emule.h"
#include "OtherFunctions.h"
#include "Preferences.h"
#include "langids.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static HINSTANCE s_hLangDLL = NULL;
CString GetResString(UINT uStringID, WORD wLanguageID)
{
CString resString;
if (s_hLangDLL)
(void)resString.LoadString(s_hLangDLL, uStringID, wLanguageID);
if (resString.IsEmpty())
(void)resString.LoadString(GetModuleHandle(NULL), uStringID, LANGID_EN_US);
return resString;
}
CString GetResString(UINT uStringID)
{
CString resString;
if (s_hLangDLL)
resString.LoadString(s_hLangDLL, uStringID);
if (resString.IsEmpty())
resString.LoadString(GetModuleHandle(NULL), uStringID);
return resString;
}
struct SLanguage {
LANGID lid;
LPCTSTR pszLocale;
BOOL bSupported;
LPCTSTR pszISOLocale;
UINT uCodepage;
LPCTSTR pszHtmlCharset;
};
// Codepages (Windows)
// ---------------------------------------------------------------------
// 1250 ANSI - Central European
// 1251 ANSI - Cyrillic
// 1252 ANSI - Latin I
// 1253 ANSI - Greek
// 1254 ANSI - Turkish
// 1255 ANSI - Hebrew
// 1256 ANSI - Arabic
// 1257 ANSI - Baltic
// 1258 ANSI/OEM - Vietnamese
// 932 ANSI/OEM - Japanese, Shift-JIS
// 936 ANSI/OEM - Simplified Chinese (PRC, Singapore)
// 949 ANSI/OEM - Korean (Unified Hangeul Code)
// 950 ANSI/OEM - Traditional Chinese (Taiwan; Hong Kong SAR, PRC)
// HTML charsets CodePg
// -------------------------------------------
// windows-1250 1250 Central European (Windows)
// windows-1251 1251 Cyrillic (Windows)
// windows-1252 1252 Western European (Windows)
// windows-1253 1253 Greek (Windows)
// windows-1254 1254 Turkish (Windows)
// windows-1255 1255 Hebrew (Windows)
// windows-1256 1256 Arabic (Windows)
// windows-1257 1257 Baltic (Windows)
//
// NOTE: the 'iso-...' charsets are more backward compatible than the 'windows-...' charsets.
// NOTE-ALSO: some of the 'iso-...' charsets are by default *not* installed by IE6 (e.g. Arabic (ISO)) or show up
// with wrong chars - so, better use the 'windows-' charsets..
//
// iso-8859-1 1252 Western European (ISO)
// iso-8859-2 1250 Central European (ISO)
// iso-8859-3 1254 Latin 3 (ISO)
// iso-8859-4 1257 Baltic (ISO)
// iso-8859-5 1251 Cyrillic (ISO) does not show up correctly in IE6
// iso-8859-6 1256 Arabic (ISO) not installed (by default) with IE6
// iso-8859-7 1253 Greek (ISO)
// iso-8859-8 1255 Hebrew (ISO-Visual)
// iso-8859-9 1254 Turkish (ISO)
// iso-8859-15 1252 Latin 9 (ISO)
// iso-2022-jp 932 Japanese (JIS)
// iso-2022-kr 949 Korean (ISO)
static SLanguage s_aLanguages[] =
{
{LANGID_AR_AE, _T(""), FALSE, _T("ar_AE"), 1256, _T("windows-1256")}, // Arabic (UAE)
{LANGID_BA_BA, _T(""), FALSE, _T("ba_BA"), 1252, _T("windows-1252")}, // Basque
{LANGID_BG_BG, _T("hun"), FALSE, _T("bg_BG"), 1251, _T("windows-1251")}, // Bulgarian
{LANGID_CA_ES, _T(""), FALSE, _T("ca_ES"), 1252, _T("windows-1252")}, // Catalan
{LANGID_CZ_CZ, _T("czech"), FALSE, _T("cz_CZ"), 1250, _T("windows-1250")}, // Czech
{LANGID_DA_DK, _T("danish"), FALSE, _T("da_DK"), 1252, _T("windows-1252")}, // Danish
{LANGID_DE_DE, _T("german"), FALSE, _T("de_DE"), 1252, _T("windows-1252")}, // German (Germany)
{LANGID_EL_GR, _T("greek"), FALSE, _T("el_GR"), 1253, _T("windows-1253")}, // Greek
{LANGID_EN_US, _T("english"), TRUE, _T("en_US"), 1252, _T("windows-1252")}, // English
{LANGID_ES_ES_T,_T("spanish"), FALSE, _T("es_ES_T"), 1252, _T("windows-1252")}, // Spanish (Castilian)
{LANGID_ES_AS, _T("spanish"), FALSE, _T("es_AS"), 1252, _T("windows-1252")}, // Asturian
{LANGID_VA_ES, _T(""), FALSE, _T("va_ES"), 1252, _T("windows-1252")}, // Valencian AVL
{LANGID_VA_ES_RACV, _T(""), FALSE, _T("va_ES_RACV"), 1252, _T("windows-1252")}, // Valencian RACV
{LANGID_ET_EE, _T(""), FALSE, _T("et_EE"), 1257, _T("windows-1257")}, // Estonian
{LANGID_FA_IR, _T("farsi"), FALSE, _T("fa_IR"), 1256, _T("windows-1256")}, // Farsi
{LANGID_FI_FI, _T("finnish"), FALSE, _T("fi_FI"), 1252, _T("windows-1252")}, // Finnish
{LANGID_FR_FR, _T("french"), FALSE, _T("fr_FR"), 1252, _T("windows-1252")}, // French (France)
{LANGID_FR_BR, _T("french"), FALSE, _T("fr_BR"), 1252, _T("windows-1252")}, // French (Breton)
{LANGID_GL_ES, _T(""), FALSE, _T("gl_ES"), 1252, _T("windows-1252")}, // Galician
{LANGID_HE_IL, _T(""), FALSE, _T("he_IL"), 1255, _T("windows-1255")}, // Hebrew
{LANGID_HU_HU, _T("hungarian"), FALSE, _T("hu_HU"), 1250, _T("windows-1250")}, // Hungarian
{LANGID_IT_IT, _T("italian"), FALSE, _T("it_IT"), 1252, _T("windows-1252")}, // Italian (Italy)
{LANGID_JP_JP, _T("japanese"), FALSE, _T("jp_JP"), 932, _T("shift_jis")}, // Japanese
{LANGID_KO_KR, _T("korean"), FALSE, _T("ko_KR"), 949, _T("euc-kr")}, // Korean
{LANGID_LT_LT, _T(""), FALSE, _T("lt_LT"), 1257, _T("windows-1257")}, // Lithuanian
{LANGID_LV_LV, _T(""), FALSE, _T("lv_LV"), 1257, _T("windows-1257")}, // Latvian
{LANGID_MT_MT, _T("mt"), FALSE, _T("mt_MT"), 1254, _T("windows-1254")}, // Maltese
{LANGID_NB_NO, _T("nor"), FALSE, _T("nb_NO"), 1252, _T("windows-1252")}, // Norwegian (Bokmal)
{LANGID_NN_NO, _T("non"), FALSE, _T("nn_NO"), 1252, _T("windows-1252")}, // Norwegian (Nynorsk)
{LANGID_NL_NL, _T("dutch"), FALSE, _T("nl_NL"), 1252, _T("windows-1252")}, // Dutch (Netherlands)
{LANGID_PL_PL, _T("polish"), FALSE, _T("pl_PL"), 1250, _T("windows-1250")}, // Polish
{LANGID_PT_BR, _T("ptb"), FALSE, _T("pt_BR"), 1252, _T("windows-1252")}, // Portuguese (Brazil)
{LANGID_PT_PT, _T("ptg"), FALSE, _T("pt_PT"), 1252, _T("windows-1252")}, // Portuguese (Portugal)
{LANGID_RO_RO, _T(""), FALSE, _T("ro_RO"), 1250, _T("windows-1250")}, // Romanian
{LANGID_RU_RU, _T("russian"), FALSE, _T("ru_RU"), 1251, _T("windows-1251")}, // Russian
{LANGID_SL_SI, _T("slovak"), FALSE, _T("sl_SI"), 1250, _T("windows-1250")}, // Slovenian
{LANGID_SQ_AL, _T(""), FALSE, _T("sq_AL"), 1252, _T("windows-1252")}, // Albanian (Albania)
{LANGID_SV_SE, _T("swedish"), FALSE, _T("sv_SE"), 1252, _T("windows-1252")}, // Swedish
{LANGID_TR_TR, _T("turkish"), FALSE, _T("tr_TR"), 1254, _T("windows-1254")}, // Turkish
{LANGID_UA_UA, _T(""), FALSE, _T("ua_UA"), 1251, _T("windows-1251")}, // Ukrainian
{LANGID_ZH_CN, _T("chs"), FALSE, _T("zh_CN"), 936, _T("gb2312")}, // Chinese (P.R.C.)
{LANGID_ZH_TW, _T("cht"), FALSE, _T("zh_TW"), 950, _T("big5")}, // Chinese (Taiwan)
{LANGID_VI_VN, _T(""), FALSE, _T("vi_VN"), 1258, _T("windows-1258")}, // Vietnamese
{LANGID_UG_CN, _T(""), FALSE, _T("ug_CN"), 1256, _T("windows-1256")}, // Uighur
{0, NULL, 0, 0}
};
static void InitLanguages(const CString& rstrLangDir1, const CString& rstrLangDir2, bool bReInit = false)
{
static BOOL _bInitialized = FALSE;
if (_bInitialized && !bReInit)
return;
_bInitialized = TRUE;
CFileFind ff;
bool bEnd = !ff.FindFile(rstrLangDir1 + _T("*.dll"), 0);
bool bFirstDir = rstrLangDir1.CompareNoCase(rstrLangDir2) != 0;
while (!bEnd)
{
bEnd = !ff.FindNextFile();
if (ff.IsDirectory())
continue;
TCHAR szLandDLLFileName[_MAX_FNAME];
_tsplitpath(ff.GetFileName(), NULL, NULL, szLandDLLFileName, NULL);
SLanguage* pLangs = s_aLanguages;
if (pLangs){
while (pLangs->lid){
if (_tcsicmp(pLangs->pszISOLocale, szLandDLLFileName) == 0){
pLangs->bSupported = TRUE;
break;
}
pLangs++;
}
}
if (bEnd && bFirstDir){
ff.Close();
bEnd = !ff.FindFile(rstrLangDir2 + _T("*.dll"), 0);
bFirstDir = false;
}
}
ff.Close();
}
static void FreeLangDLL()
{
if (s_hLangDLL != NULL && s_hLangDLL != GetModuleHandle(NULL)){
VERIFY( FreeLibrary(s_hLangDLL) );
s_hLangDLL = NULL;
}
}
void CPreferences::GetLanguages(CWordArray& aLanguageIDs)
{
const SLanguage* pLang = s_aLanguages;
while (pLang->lid){
//if (pLang->bSupported)
//show all languages, offer download if not supported ones later
aLanguageIDs.Add(pLang->lid);
pLang++;
}
}
WORD CPreferences::GetLanguageID()
{
return m_wLanguageID;
}
void CPreferences::SetLanguageID(WORD lid)
{
m_wLanguageID = lid;
}
static bool CheckLangDLLVersion(const CString& rstrLangDLL)
{
bool bResult = false;
DWORD dwUnused;
DWORD dwVerInfSize = GetFileVersionInfoSize(const_cast<LPTSTR>((LPCTSTR)rstrLangDLL), &dwUnused);
if (dwVerInfSize != 0)
{
LPBYTE pucVerInf = (LPBYTE)calloc(dwVerInfSize, 1);
if (pucVerInf)
{
if (GetFileVersionInfo(const_cast<LPTSTR>((LPCTSTR)rstrLangDLL), 0, dwVerInfSize, pucVerInf))
{
VS_FIXEDFILEINFO* pFileInf = NULL;
UINT uLen = 0;
if (VerQueryValue(pucVerInf, _T("\\"), (LPVOID*)&pFileInf, &uLen) && pFileInf && uLen)
{
bResult = (pFileInf->dwProductVersionMS == theApp.m_dwProductVersionMS &&
pFileInf->dwProductVersionLS == theApp.m_dwProductVersionLS);
}
}
free(pucVerInf);
}
}
return bResult;
}
static bool LoadLangLib(const CString& rstrLangDir1, const CString& rstrLangDir2, LANGID lid)
{
const SLanguage* pLangs = s_aLanguages;
if (pLangs){
while (pLangs->lid){
if (pLangs->bSupported && pLangs->lid == lid){
FreeLangDLL();
bool bLoadedLib = false;
if (pLangs->lid == LANGID_EN_US){
s_hLangDLL = NULL;
bLoadedLib = true;
}
else{
CString strLangDLL = rstrLangDir1;
strLangDLL += pLangs->pszISOLocale;
strLangDLL += _T(".dll");
if (CheckLangDLLVersion(strLangDLL)){
s_hLangDLL = LoadLibrary(strLangDLL);
if (s_hLangDLL)
bLoadedLib = true;
}
if (rstrLangDir1.CompareNoCase(rstrLangDir2) != 0){
strLangDLL = rstrLangDir2;
strLangDLL += pLangs->pszISOLocale;
strLangDLL += _T(".dll");
if (CheckLangDLLVersion(strLangDLL)){
s_hLangDLL = LoadLibrary(strLangDLL);
if (s_hLangDLL)
bLoadedLib = true;
}
}
}
if (bLoadedLib)
return true;
break;
}
pLangs++;
}
}
return false;
}
void CPreferences::SetLanguage()
{
InitLanguages(GetMuleDirectory(EMULE_INSTLANGDIR), GetMuleDirectory(EMULE_ADDLANGDIR, false));
bool bFoundLang = false;
if (m_wLanguageID)
bFoundLang = LoadLangLib(GetMuleDirectory(EMULE_INSTLANGDIR), GetMuleDirectory(EMULE_ADDLANGDIR, false), m_wLanguageID);
if (!bFoundLang){
LANGID lidLocale = (LANGID)::GetThreadLocale();
//LANGID lidLocalePri = PRIMARYLANGID(::GetThreadLocale());
//LANGID lidLocaleSub = SUBLANGID(::GetThreadLocale());
bFoundLang = LoadLangLib(GetMuleDirectory(EMULE_INSTLANGDIR), GetMuleDirectory(EMULE_ADDLANGDIR, false), lidLocale);
if (!bFoundLang){
LoadLangLib(GetMuleDirectory(EMULE_INSTLANGDIR), GetMuleDirectory(EMULE_ADDLANGDIR, false), LANGID_EN_US);
m_wLanguageID = LANGID_EN_US;
CString strLngEnglish = GetResString(IDS_MB_LANGUAGEINFO);
AfxMessageBox(strLngEnglish, MB_ICONASTERISK);
}
else
m_wLanguageID = lidLocale;
}
// if loading a string fails, set language to English
if (GetResString(IDS_MB_LANGUAGEINFO).IsEmpty()) {
LoadLangLib(GetMuleDirectory(EMULE_INSTLANGDIR), GetMuleDirectory(EMULE_ADDLANGDIR, false), LANGID_EN_US);
m_wLanguageID = LANGID_EN_US;
}
InitThreadLocale();
}
bool CPreferences::IsLanguageSupported(LANGID lidSelected, bool bUpdateBefore){
InitLanguages(GetMuleDirectory(EMULE_INSTLANGDIR), GetMuleDirectory(EMULE_ADDLANGDIR, false), bUpdateBefore);
if (lidSelected == LANGID_EN_US)
return true;
const SLanguage* pLang = s_aLanguages;
for (;pLang->lid;pLang++){
if (pLang->lid == lidSelected && pLang->bSupported){
bool bResult = CheckLangDLLVersion(GetMuleDirectory(EMULE_INSTLANGDIR) + CString(pLang->pszISOLocale) + _T(".dll"));
return bResult || CheckLangDLLVersion(GetMuleDirectory(EMULE_ADDLANGDIR, false) + CString(pLang->pszISOLocale) + _T(".dll"));
}
}
return false;
}
CString CPreferences::GetLangDLLNameByID(LANGID lidSelected){
const SLanguage* pLang = s_aLanguages;
for (;pLang->lid;pLang++){
if (pLang->lid == lidSelected)
return CString(pLang->pszISOLocale) + _T(".dll");
}
ASSERT ( false );
return CString(_T(""));
}
void CPreferences::SetRtlLocale(LCID lcid)
{
const SLanguage* pLangs = s_aLanguages;
while (pLangs->lid)
{
if (pLangs->lid == LANGIDFROMLCID(lcid))
{
if (pLangs->uCodepage)
{
CString strCodepage;
strCodepage.Format(_T(".%u"), pLangs->uCodepage);
_tsetlocale(LC_CTYPE, strCodepage);
}
break;
}
pLangs++;
}
}
void CPreferences::InitThreadLocale()
{
ASSERT( m_wLanguageID != 0 );
// NOTE: This function is for testing multi language support only.
// NOTE: This function is *NOT* to be enabled in release builds nor to be offered by any Mod!
if (theApp.GetProfileInt(_T("eMule"), _T("SetLanguageACP"), 0) != 0)
{
//LCID lcidUser = GetUserDefaultLCID(); // Installation, or altered by user in control panel (WinXP)
// get the ANSI code page which is to be used for all non-Unicode conversions.
LANGID lidSystem = m_wLanguageID;
// get user's sorting preferences
//UINT uSortIdUser = SORTIDFROMLCID(lcidUser);
//UINT uSortVerUser = SORTVERSIONFROMLCID(lcidUser);
// we can't use the same sorting paramters for 2 different Languages..
UINT uSortIdUser = SORT_DEFAULT;
UINT uSortVerUser = 0;
// set thread locale, this is used for:
// - MBCS->Unicode conversions (e.g. search results).
// - Unicode->MBCS conversions (e.g. publishing local files (names) in network, or savint text files on local disk)...
LCID lcid = MAKESORTLCID(lidSystem, uSortIdUser, uSortVerUser);
SetThreadLocale(lcid);
// if we set the thread locale (see comments above) we also have to specify the proper
// code page for the C-RTL, otherwise we may not be able to store some strings as MBCS
// (Unicode->MBCS conversion may fail)
SetRtlLocale(lcid);
}
}
void InitThreadLocale()
{
thePrefs.InitThreadLocale();
}
CString GetCodePageNameForLocale(LCID lcid)
{
CString strCodePage;
int iResult = GetLocaleInfo(lcid, LOCALE_IDEFAULTANSICODEPAGE, strCodePage.GetBuffer(6), 6);
strCodePage.ReleaseBuffer();
if (iResult > 0 && !strCodePage.IsEmpty())
{
UINT uCodePage = _tcstoul(strCodePage, NULL, 10);
if (uCodePage != ULONG_MAX)
{
CPINFOEXW CPInfoEx = {0};
BOOL (WINAPI *pfnGetCPInfoEx)(UINT, DWORD, LPCPINFOEXW);
(FARPROC&)pfnGetCPInfoEx = GetProcAddress(GetModuleHandle(_T("kernel32")), "GetCPInfoExW");
if (pfnGetCPInfoEx&& (*pfnGetCPInfoEx)(uCodePage, 0, &CPInfoEx))
strCodePage = CPInfoEx.CodePageName;
}
}
return strCodePage;
}
CString CPreferences::GetHtmlCharset()
{
ASSERT( m_wLanguageID != 0 );
LPCTSTR pszHtmlCharset = NULL;
const SLanguage* pLangs = s_aLanguages;
while (pLangs->lid)
{
if (pLangs->lid == m_wLanguageID)
{
pszHtmlCharset = pLangs->pszHtmlCharset;
break;
}
pLangs++;
}
if (pszHtmlCharset == NULL || pszHtmlCharset[0] == _T('\0'))
{
ASSERT(0); // should never come here
// try to get charset from code page
LPCTSTR pszLcLocale = _tsetlocale(LC_CTYPE, NULL);
if (pszLcLocale)
{
TCHAR szLocaleID[128];
UINT uCodepage = 0;
if (_stscanf(pszLcLocale, _T("%[a-zA-Z_].%u"), szLocaleID, &uCodepage) == 2 && uCodepage != 0)
{
CString strHtmlCodepage;
strHtmlCodepage.Format(_T("windows-%u"), uCodepage);
return strHtmlCodepage;
}
}
}
return pszHtmlCharset;
}
static HHOOK s_hRTLWindowsLayoutOldCbtFilterHook = NULL;
LRESULT CALLBACK RTLWindowsLayoutCbtFilterHook(int code, WPARAM wParam, LPARAM lParam)
{
if (code == HCBT_CREATEWND)
{
//LPCREATESTRUCT lpcs = ((LPCBT_CREATEWND)lParam)->lpcs;
//if ((lpcs->style & WS_CHILD) == 0)
// lpcs->dwExStyle |= WS_EX_LAYOUTRTL; // doesn't seem to have any effect, but shouldn't hurt
HWND hWnd = (HWND)wParam;
if ((GetWindowLong(hWnd, GWL_STYLE) & WS_CHILD) == 0) {
SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYOUTRTL);
}
}
return CallNextHookEx(s_hRTLWindowsLayoutOldCbtFilterHook, code, wParam, lParam);
}
void CemuleApp::EnableRTLWindowsLayout()
{
BOOL (WINAPI *pfnSetProcessDefaultLayout)(DWORD dwFlags);
(FARPROC&)pfnSetProcessDefaultLayout = GetProcAddress(GetModuleHandle(_T("user32")), "SetProcessDefaultLayout");
if (pfnSetProcessDefaultLayout)
(*pfnSetProcessDefaultLayout)(LAYOUT_RTL);
s_hRTLWindowsLayoutOldCbtFilterHook = SetWindowsHookEx(WH_CBT, RTLWindowsLayoutCbtFilterHook, NULL, GetCurrentThreadId());
}
void CemuleApp::DisableRTLWindowsLayout()
{
if (s_hRTLWindowsLayoutOldCbtFilterHook)
{
VERIFY( UnhookWindowsHookEx(s_hRTLWindowsLayoutOldCbtFilterHook) );
s_hRTLWindowsLayoutOldCbtFilterHook = NULL;
BOOL (WINAPI *pfnSetProcessDefaultLayout)(DWORD dwFlags);
(FARPROC&)pfnSetProcessDefaultLayout = GetProcAddress(GetModuleHandle(_T("user32")), "SetProcessDefaultLayout");
if (pfnSetProcessDefaultLayout)
(*pfnSetProcessDefaultLayout)(0);
}
}
| [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b"
]
| [
[
[
1,
490
]
]
]
|
373435dfd2750f95d434b3cac75b955949bd4609 | 5c84c243bdb74cdd41d712a98c421ef9005a1c98 | /fixed/fixed.hpp | 09bbc794d774ed659d6bcb1ad91d25a5385aa123 | []
| no_license | graveljp/fixed | 02f2357c4d26378e90162419a3daa9506fa85679 | 10d10adad149fa1f3df3b9e516ebbb92aee6f564 | refs/heads/master | 2020-05-02T12:01:10.224857 | 2011-08-13T03:48:19 | 2011-08-13T03:48:19 | 33,949,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,158 | hpp |
#ifndef FIXED_FIXED_HPP_INCLUDED
#define FIXED_FIXED_HPP_INCLUDED
// Copyright Joel Riendeau 2008
// Jean-Philippe Gravel 2008
// Jean-Olivier Racine 2008
//
// Distributed under the New BSD License.
// (See accompanying file NewBSDLicense.txt or copy at
// http://www.opensource.org/licenses/bsd-license.php)
#define USING_XPR_OPTIMIZER 1
#include "integer_types.hpp"
#include "QXpr.hpp"
#include <boost/mpl/if.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/type_traits/is_float.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/static_assert.hpp>
#include <boost/assert.hpp>
#ifdef FIXED_DEBUG_MODE
#include <boost/lexical_cast.hpp>
#endif //FIXED_DEBUG_MODE
// A template to select the smallest integer type for a given amount of bits
template <uint8_t Bits, bool Signed> struct FixedInteger
{
typedef typename boost::mpl::if_c<(Bits <= 8 && Signed), sint32_t
, typename boost::mpl::if_c<(Bits <= 8 && !Signed), uint32_t
, typename boost::mpl::if_c<(Bits <= 16 && Signed), sint32_t
, typename boost::mpl::if_c<(Bits <= 16 && !Signed), uint32_t
, typename boost::mpl::if_c<(Bits <= 32 && Signed), sint32_t
, typename boost::mpl::if_c<(Bits <= 32 && !Signed), uint32_t
, typename boost::mpl::if_c<(Bits <= 64 && Signed), sint64_t
, typename boost::mpl::if_c<(Bits <= 64 && !Signed), uint64_t
, void>::type >::type >::type >::type >::type >::type >::type >::type type;
};
template<uint8_t Bits> struct BitMask
{
typedef typename FixedInteger<Bits, false>::type type;
static const type value = static_cast<type>(-1) >> (sizeof(type)*8-Bits);
};
template <sint8_t Mag, uint8_t Fract>
class Q : public QXpr<Q<Mag, Fract> >
{
public:
enum
{
Magnitude = Mag,
Fractional = Fract,
NBits_Magn = (Magnitude < 0 ? -Magnitude : Magnitude),
NBits_Frac = Fractional,
NBits = NBits_Magn + NBits_Frac
};
typedef Q<Magnitude, Fractional> this_type;
typedef void op_type;
typedef typename FixedInteger<NBits, (Magnitude < 0)>::type MagnType;
typedef typename FixedInteger<NBits, false>::type FracType;
typedef typename FixedInteger<NBits*2, (Magnitude < 0)>::type MultiplyType;
typedef typename FixedInteger<(NBits > sizeof(float) ? NBits : sizeof(float)), false>::type FloatCastType;
template<int bitAdjustment>
struct AdjustType
{
enum { magnBoost = bitAdjustment * Magnitude / NBits };
enum { fracBoost = bitAdjustment * Fractional / NBits };
typedef Q<Magnitude + magnBoost, Fractional + fracBoost> type;
};
static double epsilon()
{
return 1.0 / ((uint64_t)1 << Q::Fractional);
}
__forceinline Q() :
m_CompFast()
{
#ifdef FIXED_DEBUG_MODE
typeStr = "Q" + boost::lexical_cast<std::string>(Magnitude) + "," + boost::lexical_cast<std::string>(Fractional);
valueStr = boost::lexical_cast<std::string>(m_Magn) + "," + boost::lexical_cast<std::string>(m_Frac);
floatStr = boost::lexical_cast<std::string>((float)*this);
floatValue = (double)*this;
cumulativeEpsilon = 0;
#endif //FIXED_DEBUG_MODE
}
__forceinline Q(const Q& val) :
#ifdef FIXED_DEBUG_MODE
typeStr(val.typeStr),
valueStr(val.valueStr),
floatStr(val.floatStr),
floatValue(val.floatValue),
cumulativeEpsilon(val.cumulativeEpsilon ),
#endif //FIXED_DEBUG_MODE
m_CompFast(val.m_CompFast & BitMask<NBits>::value )
{
}
__forceinline Q(int iMagn, int iFrac)
{
m_CompFast = 0;
m_Magn = iMagn;
m_Frac = iFrac;
#ifdef FIXED_DEBUG_MODE
typeStr = "Q" + boost::lexical_cast<std::string>(Magnitude) + "," + boost::lexical_cast<std::string>(Fractional) + "";
valueStr = boost::lexical_cast<std::string>(m_Magn) + "," + boost::lexical_cast<std::string>(m_Frac);
floatStr = boost::lexical_cast<std::string>((float)*this);
floatValue = (double)*this;
cumulativeEpsilon = 0;
#endif //FIXED_DEBUG_MODE
}
template<typename E>
Q(const QXpr<E>& roRight)
{
*this = roRight().value<this_type>();
}
template <typename T>
__forceinline Q( const T& val, typename boost::enable_if<boost::is_integral<T>, int >::type dummy = 0 )
{
m_CompFast = 0;
m_Magn = static_cast<MagnType>(val);
m_Frac = 0;
#ifdef FIXED_DEBUG_MODE
typeStr = "Q" + boost::lexical_cast<std::string>(Magnitude) + "," + boost::lexical_cast<std::string>(Fractional) + "";
valueStr = boost::lexical_cast<std::string>(m_Magn) + "," + boost::lexical_cast<std::string>(m_Frac);
floatStr = boost::lexical_cast<std::string>((float)*this);
floatValue = (double)*this;
cumulativeEpsilon = fabs((double)*this - floatValue);
#endif //FIXED_DEBUG_MODE
}
template <typename T>
__forceinline Q( const T& val, typename boost::enable_if<boost::is_float<T>, int >::type dummy = 0 )
{
m_CompFast = static_cast<MagnType>(val * (1 << Fractional)) & BitMask<NBits>::value;
#ifdef FIXED_DEBUG_MODE
typeStr = "Q" + boost::lexical_cast<std::string>(Magnitude) + "," + boost::lexical_cast<std::string>(Fractional) + "";
valueStr = boost::lexical_cast<std::string>(m_Magn) + "," + boost::lexical_cast<std::string>(m_Frac);
floatStr = boost::lexical_cast<std::string>((float)*this);
floatValue = val;
cumulativeEpsilon = fabs((double)*this - floatValue);
#endif //FIXED_DEBUG_MODE
}
template <sint8_t M, uint8_t F>
__forceinline Q( const Q<M,F>& val )
{
*this = val;
}
template <sint8_t M, uint8_t F>
__forceinline typename boost::enable_if_c<(Fractional>F), this_type& >::type
operator=( const Q<M,F>& val )
{
enum { shift = Fractional - F };
m_CompFast = static_cast<MagnType>(val.m_CompFast << shift) & BitMask<NBits>::value;
#ifdef FIXED_DEBUG_MODE
typeStr = "(" + val.typeStr + " << " + boost::lexical_cast<std::string>(shift) + " [Q" + boost::lexical_cast<std::string>(Magnitude) + "," + boost::lexical_cast<std::string>(Fractional) + "] )";
valueStr = "(" + val.valueStr + " << " + boost::lexical_cast<std::string>(shift) + " [" + boost::lexical_cast<std::string>(m_Magn) + "," + boost::lexical_cast<std::string>(m_Frac) + "] )";
floatStr = "(" + val.floatStr + " << " + boost::lexical_cast<std::string>(shift) + " [" + boost::lexical_cast<std::string>((float)*this) + "] )";
floatValue = val.floatValue;
cumulativeEpsilon = val.cumulativeEpsilon;
#endif //FIXED_DEBUG_MODE
return *this;
}
template <sint8_t M, uint8_t F>
__forceinline typename boost::enable_if_c<(Fractional<F), this_type& >::type
operator=( const Q<M,F>& val )
{
enum { shift = F - Fractional };
m_CompFast = static_cast<MagnType>(val.m_CompExact >> shift) & BitMask<NBits>::value;
#ifdef FIXED_DEBUG_MODE
typeStr = "(" + val.typeStr + " >> " + boost::lexical_cast<std::string>(shift) + " [Q" + boost::lexical_cast<std::string>(Magnitude) + "," + boost::lexical_cast<std::string>(Fractional) + "] )";
valueStr = "(" + val.valueStr + " >> " + boost::lexical_cast<std::string>(shift) + " [" + boost::lexical_cast<std::string>(m_Magn) + "," + boost::lexical_cast<std::string>(m_Frac) + "] )";
floatStr = "(" + val.floatStr + " >> " + boost::lexical_cast<std::string>(shift) + " [" + boost::lexical_cast<std::string>((float)*this) + "] )";
floatValue = val.floatValue;
cumulativeEpsilon = val.cumulativeEpsilon + epsilon();
#endif //FIXED_DEBUG_MODE
return *this;
}
template<typename E>
__forceinline Q& operator=(const QXpr<E>& roRight);
template<typename T>
__forceinline typename boost::enable_if<boost::is_integral<T>, T>::type
cast() const
{
return static_cast<T>(m_Magn);
}
template<typename T>
__forceinline typename boost::enable_if<boost::is_float<T>, T>::type
cast() const
{
T result = static_cast<T>(m_CompExact);
((FloatFormat<T>*)&result)->exponent -= Fractional;
return (0 == m_CompExact) ? (T)0.0 : result;
}
template<typename T>
__forceinline operator T() const
{
// enable_if is not possible on cast operators without C++0x support
return cast<T>();
}
template <sint8_t M, uint8_t F>
__forceinline bool operator==(const Q<M,F>& val) const
{
return (m_Magn == val.m_Magn) && (m_Frac == val.m_Frac);
}
__forceinline bool operator==(const Q& val) const {return m_CompExact == val.m_CompExact;}
__forceinline bool operator!=(const Q& val) const {return m_CompExact != val.m_CompExact;}
__forceinline bool operator< (const Q& val) const {return m_CompExact < val.m_CompExact;}
__forceinline bool operator<=(const Q& val) const {return m_CompExact <= val.m_CompExact;}
__forceinline bool operator> (const Q& val) const {return m_CompExact > val.m_CompExact;}
__forceinline bool operator>=(const Q& val) const {return m_CompExact >= val.m_CompExact;}
__forceinline FracType Frac() {return m_Frac;}
union
{
struct
{
FracType m_Frac : NBits_Frac;
MagnType m_Magn : NBits_Magn;
};
struct
{
MagnType m_CompExact: NBits;
};
struct
{
MagnType m_CompFast;
};
};
#ifdef FIXED_DEBUG_MODE
std::string typeStr;
std::string valueStr;
std::string floatStr;
double floatValue;
double cumulativeEpsilon;
#endif //FIXED_DEBUG_MODE
private:
template<typename T>
struct FloatFormat;
template<>
struct FloatFormat<float>
{
union
{
struct
{
uint32_t mantissa : 23;
uint32_t exponent : 8;
uint32_t sign : 1;
};
uint32_t full;
};
};
template<>
struct FloatFormat<double>
{
union
{
struct
{
uint64_t mantissa : 52;
uint64_t exponent : 11;
uint64_t sign : 1;
};
uint64_t full;
};
};
};
template <sint8_t Magnitude, uint8_t Fractional>
Q<Magnitude, Fractional> sqrt(const Q<Magnitude, Fractional>& val)
{
//if (Magnitude < 0)
// return MAX_VAL
typename Q<Magnitude, Fractional>::MultiplyType temp = val.m_CompExact << Fractional;
typename Q<Magnitude, Fractional>::InternalType root = 0, test;
for (sint8_t i= Q<Magnitude, Fractional>::NBits - 1; i >= 0; i--)
{
test = root + (1 << i);
if (temp >= test << i)
{ temp -= test << i;
root |= 2 << i;
}
}
return root >> 1;
}
template <sint8_t Magnitude, uint8_t Fractional>
Q<Magnitude, Fractional> floor(const Q<Magnitude, Fractional>& val)
{
Q<Magnitude, Fractional> ret = val;
ret.m_Frac = 0;
return ret;
}
template <sint8_t Magnitude, uint8_t Fractional>
Q<Magnitude, Fractional> ceil(const Q<Magnitude, Fractional>& val)
{
Q<Magnitude, Fractional> ret = val;
if (0 != ret.m_Frac)
++ret.m_Magn;
ret.m_Frac = 0;
return ret;
}
/*
fixed pow(fixed fixedPower);
fixed log10(void);
fixed log(void);
fixed exp(void);
fixed cos(void);
fixed sin(void);
fixed tan(void);*/
#include "SimpleFiPU.hpp"
#if USING_XPR_OPTIMIZER
#include "XprOptimizer.hpp"
#else
#include "SimpleOptimizer.hpp"
#endif
#endif
| [
"joel.riendeau@8301e2df-3e56-0410-bad7-75797df71324",
"[email protected]@8301e2df-3e56-0410-bad7-75797df71324",
"jpgravel@8301e2df-3e56-0410-bad7-75797df71324",
"joracine@8301e2df-3e56-0410-bad7-75797df71324"
]
| [
[
[
1,
12
],
[
15,
15
],
[
50,
50
],
[
53,
54
],
[
56,
56
],
[
144,
144
],
[
146,
146
],
[
162,
162
],
[
164,
165
],
[
186,
186
],
[
199,
200
],
[
220,
221
],
[
224,
224
],
[
227,
229
],
[
231,
233
],
[
240,
241
],
[
243,
250
],
[
261,
262
],
[
271,
271
],
[
277,
277
],
[
294,
294
],
[
302,
302
],
[
304,
310
],
[
314,
342
],
[
350,
350
]
],
[
[
13,
13
],
[
23,
23
],
[
25,
25
],
[
29,
49
],
[
55,
55
],
[
57,
59
],
[
62,
71
],
[
86,
86
],
[
88,
88
],
[
108,
109
],
[
124,
128
],
[
130,
130
],
[
132,
132
],
[
134,
135
],
[
145,
145
],
[
166,
166
],
[
169,
169
],
[
181,
183
],
[
201,
201
],
[
203,
203
],
[
230,
230
],
[
242,
242
],
[
343,
349
],
[
352,
356
]
],
[
[
14,
14
],
[
16,
22
],
[
24,
24
],
[
26,
28
],
[
51,
52
],
[
60,
61
],
[
72,
85
],
[
87,
87
],
[
89,
107
],
[
110,
123
],
[
131,
131
],
[
133,
133
],
[
136,
143
],
[
147,
161
],
[
163,
163
],
[
167,
168
],
[
170,
180
],
[
184,
185
],
[
187,
198
],
[
202,
202
],
[
204,
219
],
[
222,
223
],
[
225,
226
],
[
234,
239
],
[
251,
260
],
[
263,
270
],
[
272,
276
],
[
278,
293
],
[
295,
301
],
[
303,
303
],
[
311,
313
],
[
351,
351
],
[
357,
359
]
],
[
[
129,
129
]
]
]
|
0aaf786d452322cbe0957518a91c1604b70725ed | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/interfaces/map_pair.h | 58ebfa2695e594100754d751b5056066846b1385 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
]
| permissive | athulan/cppagent | 58f078cee55b68c08297acdf04a5424c2308cfdc | 9027ec4e32647e10c38276e12bcfed526a7e27dd | refs/heads/master | 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,020 | h | // Copyright (C) 2003 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_MAP_PAIr_INTERFACE_
#define DLIB_MAP_PAIr_INTERFACE_
namespace dlib
{
// ----------------------------------------------------------------------------------------
template <
typename T1,
typename T2
>
class map_pair
{
/*!
POINTERS AND REFERENCES TO INTERNAL DATA
None of the functions in map_pair will invalidate
pointers or references to internal data when called.
WHAT THIS OBJECT REPRESENTS
this object is used to return the key/value pair used in the
map and hash_map containers when using the enumerable interface.
note that the enumerable interface is defined in
interfaces/enumerable.h
!*/
public:
typedef T1 key_type;
typedef T2 value_type;
virtual ~map_pair(
)=0;
virtual const T1& key(
) const =0;
/*!
ensures
- returns a const reference to the key
!*/
virtual const T2& value(
) const =0;
/*!
ensures
- returns a const reference to the value associated with key
!*/
virtual T2& value(
)=0;
/*!
ensures
- returns a non-const reference to the value associated with key
!*/
protected:
// restricted functions
map_pair<T1,T2>& operator=(const map_pair<T1,T2>&) {return *this;} // no assignment operator
};
// destructor does nothing
template <typename T1,typename T2>
map_pair<T1,T2>::~map_pair () {}
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_MAP_PAIr_INTERFACE_
| [
"jimmy@DGJ3X3B1.(none)"
]
| [
[
[
1,
74
]
]
]
|
09d5bb4ef5ecf93dd93cb87af9dc279e59ef8993 | 971b000b9e6c4bf91d28f3723923a678520f5bcf | /PaperSizeScroll/Layer_CommandStorage.h | 71ca923f3d87532b4ba5a972a59102cb7666f49b | []
| no_license | google-code-export/fop-miniscribus | 14ce53d21893ce1821386a94d42485ee0465121f | 966a9ca7097268c18e690aa0ea4b24b308475af9 | refs/heads/master | 2020-12-24T17:08:51.551987 | 2011-09-02T07:55:05 | 2011-09-02T07:55:05 | 32,133,292 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,077 | h | #ifndef _COMMAND_STORAGE_H_
#define _COMMAND_STORAGE_H_
class QAction;
#include <QtCore/QMap>
#include <QtCore/QString>
#include <QtGui/QIcon>
#include <QtGui/QKeySequence>
/*
Command storage instance to close all current action static to
fast report on toolbar or other ......
*/
/*
command to reload if cursor change.!
*/
typedef enum {
D_NONE = 0,
D_SEPARATOR = 1,
D_SUBMENUS = 5001,
TXTM_COPY = 10,
TXTM_PASTE = 11,
TXTM_SELECTALL = 12,
TXTM_REDO = 13,
TXTM_UNDO = 14,
TXTM_CUT = 15,
TXT_COLOR = 400,
TXT_BG_COLOR = 401,
TXT_BOLD = 402,
TXT_UNDERLINE = 403,
TXT_STRIKOUT = 404,
TXT_OVERLINE = 405,
TXT_NOBREAKLINE = 406,
TXT_SPAN_FONTS = 1650,
FONT_LETTER_SPACING = 1204,
LAYER_BG = 500,
BLOCK_BGCOLOR = 707,
BLOCK_ALIGN_LEFT = 1200,
BLOCK_ALIGN_RIGHT = 1201,
BLOCK_ALIGN_CENTER = 1202,
BLOCK_ALIGN_JUSTIFY = 1203,
BLOCK_MARGINS = 1500,
LAYER_BORDER_COLOR = 502,
FRAME_BGCOLOR = 407,
TABLE_BGCOLOR = 408,
TABLE_FORMATS = 409,
TABLE_CELLBGCOLOR = 410,
TABLE_APPENDCOOL = 411,
TABLE_APPENDROW = 412,
TABLE_REMCOOL = 414,
TABLE_REMROW = 415,
TABLE_MERGECELL = 416,
TABLE_COOLWIDHT = 417
} DynamicCommandID;
/*
Static action no checked no icon swap
live forever on application instance!
*/
typedef enum {
S_NONE = 0,
S_SEPARATOR = 1,
S_SUBMENUS = 5000,
/* open doc */
DOC_SAVE_FOP = 2,
DOC_SAVE_RTF = 3,
DOC_SAVE_HTML = 4,
DOC_SAVE_PAGE = 5,
DOC_SAVE_TXT = 6,
/* open doc */
/* open open */
DOC_OPEN_FOP = 20,
DOC_OPEN_HTML = 22,
DOC_OPEN_PAGE = 23,
DOC_OPEN_TXT = 24,
/* open open */
/* create fop from xsl + xml */
DOC_COMPOSE_XSLT_FOP = 8,
/* scene clear same as new blank page */
CLEAR_PAGE = 103,
/* TXT group layer */
TXT_GLOBALFONTS = 400,
FRAME_PARAMS = 450,
PARA_BREACK_PAGE_POLICY = 451,
LINK_TEXT = 1702,
/* TXT group layer */
/* Page group layer */
LAYER_BORDER_WI = 501,
LAYER_OPEN_FILE = 503,
LAYER_SAVE_FILE = 504,
LAYER_Z_UP = 505,
LAYER_Z_DOWN = 506,
LAYER_COPY_I = 507,
LAYER_CLONE_I = 508,
LAYER_REMOVE = 509,
NEW_LAYER_ABS = 510,
NEW_LAYER_OOO = 511,
PRINT_PAGE = 512,
PASTE_LAYER = 513,
INSERT_TABLE = 700,
INSERT_FRAME = 701,
INSERT_IMAGE = 702,
SHOW_SOURCE_HTML = 703,
SHOW_SOURCE_SCRIBE = 704,
SHOW_SOURCE_FOP = 705,
MARGIN_CURRENT_ELEMENT = 950,
/* Page group layer */
ID_ABOUT_QT = 1403
} StaticCommandID;
/* command from absolute Layer */
typedef enum {
F_NONE = 0,
F_SEPARATOR = 1,
F_SUBMENUS = 5001,
FTXTM_COPY = 10,
FTXTM_PASTE = 11,
FTXTM_SELECTALL = 12,
FTXTM_REDO = 13,
FTXTM_UNDO = 14,
FTXTM_CUT = 15,
FTXT_COLOR = 400,
FTXT_BG_COLOR = 401,
FBLOCK_BGCOLOR = 707,
FBLOCK_ALIGN_LEFT = 1200,
FBLOCK_ALIGN_RIGHT = 1201,
FBLOCK_ALIGN_CENTER = 1202,
FBLOCK_ALIGN_JUSTIFY = 1203,
FBLOCK_MARGINS = 1500,
ZINDEX_MAX = 1700,
ZINDEX_MIN = 1701,
FLINK_TEXT = 1702,
FTXT_BOLD = 402,
FTXT_UNDERLINE = 403,
FTXT_STRIKOUT = 404,
FTXT_OVERLINE = 405,
FTXT_NOBREAKLINE = 406,
FTXT_FONTS = 407,
FLAYER_BG = 500,
FFONT_LETTER_SPACING = 1204,
FLAYER_BORDER_COLOR = 502,
FINSERT_TABLE = 700,
FFRAME_BGCOLOR = 407,
FTABLE_BGCOLOR = 408,
FTABLE_FORMATS = 409,
FTABLE_CELLBGCOLOR = 410,
FTABLE_APPENDCOOL = 411,
FTABLE_APPENDROW = 412,
FTABLE_REMCOOL = 414,
FTABLE_REMROW = 415,
FTABLE_MERGECELL = 416,
FTABLE_COOLWIDHT = 417
} AbsCommandID;
struct DinamicCmd {
DinamicCmd() {
id = D_NONE;
}
DinamicCmd(DynamicCommandID Id, bool e , bool s , QString Name, QIcon Icon,
QKeySequence Seq, QObject* Reciever, const QString& Slot , bool f = true ) {
id = Id;
name = Name;
icon = Icon;
shortcut = Seq;
reciever = Reciever;
slot = Slot;
checkaBle_ = e;
enables = f;
status = s;
}
DynamicCommandID id;
QString name;
bool checkaBle_;
bool status;
bool enables;
QIcon icon;
QKeySequence shortcut;
QObject* reciever;
QString slot;
};
struct StaticCmd {
StaticCmd() {
id = S_NONE;
}
StaticCmd(StaticCommandID Id, QString Name, QIcon Icon, QKeySequence Seq, QObject* Reciever, const QString& Slot) {
id = Id;
name = Name;
icon = Icon;
shortcut = Seq;
reciever = Reciever;
slot = Slot;
}
StaticCommandID id;
QString name;
QIcon icon;
QKeySequence shortcut;
QObject* reciever;
QString slot;
};
struct AbsoluteCmd {
AbsoluteCmd() {
id = F_NONE;
}
AbsoluteCmd(AbsCommandID Id, bool e , bool s , QString Name, QIcon Icon,
QKeySequence Seq, QObject* Reciever, const QString& Slot , bool f = true ) {
id = Id;
name = Name;
icon = Icon;
shortcut = Seq;
reciever = Reciever;
slot = Slot;
checkaBle_ = e;
enables = f;
status = s;
}
AbsCommandID id;
QString name;
bool checkaBle_;
bool status;
bool enables;
QIcon icon;
QKeySequence shortcut;
QObject* reciever;
QString slot;
};
class CommandStorage {
public:
static CommandStorage* instance();
void registerCommand_S(const StaticCmd&);
void registerCommand_D(const DinamicCmd&);
void registerCommand_F(const AbsoluteCmd&);
QAction* actS(StaticCommandID);
QAction* actD(DynamicCommandID);
QAction* actF(AbsCommandID);
inline void clearS() { Scmd_.clear(); }
inline void clearD() { Dcmd_.clear(); }
inline void clearF() { Fcmd_.clear(); }
inline int countD() { return Dcmd_.size(); }
inline int countS() { return Scmd_.size(); }
inline int countF() { return Fcmd_.size(); }
private:
CommandStorage() { }
static CommandStorage* st_;
QMap<AbsCommandID, QAction*> Fcmd_;
QMap<StaticCommandID, QAction*> Scmd_;
QMap<DynamicCommandID, QAction*> Dcmd_;
};
#endif
| [
"ppkciz@9af58faf-7e3e-0410-b956-55d145112073"
]
| [
[
[
1,
294
]
]
]
|
5cabc68dab9a972f97044d790e6d7f8b941e1fcc | 12203ea9fe0801d613bbb2159d4f69cab3c84816 | /Export/cpp/windows/obj/include/nme/display/JointStyle.h | 909571208b72bb54de0d8388eed3a3eeea219892 | []
| no_license | alecmce/haxe_game_of_life | 91b5557132043c6e9526254d17fdd9bcea9c5086 | 35ceb1565e06d12c89481451a7bedbbce20fa871 | refs/heads/master | 2016-09-16T00:47:24.032302 | 2011-10-10T12:38:14 | 2011-10-10T12:38:14 | 2,547,793 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,061 | h | #ifndef INCLUDED_nme_display_JointStyle
#define INCLUDED_nme_display_JointStyle
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS2(nme,display,JointStyle)
namespace nme{
namespace display{
class JointStyle_obj : public hx::EnumBase_obj
{
typedef hx::EnumBase_obj super;
typedef JointStyle_obj OBJ_;
public:
JointStyle_obj() {};
HX_DO_ENUM_RTTI;
static void __boot();
static void __register();
::String GetEnumName( ) const { return HX_CSTRING("nme.display.JointStyle"); }
::String __ToString() const { return HX_CSTRING("JointStyle.") + tag; }
static ::nme::display::JointStyle BEVEL;
static inline ::nme::display::JointStyle BEVEL_dyn() { return BEVEL; }
static ::nme::display::JointStyle MITER;
static inline ::nme::display::JointStyle MITER_dyn() { return MITER; }
static ::nme::display::JointStyle ROUND;
static inline ::nme::display::JointStyle ROUND_dyn() { return ROUND; }
};
} // end namespace nme
} // end namespace display
#endif /* INCLUDED_nme_display_JointStyle */
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
fe4d73f45881d4c28147cdd0236a2a391e17be6c | d6eba554d0c3db3b2252ad34ffce74669fa49c58 | /Source/Helpers/bitFont.cpp | deb86a8b8be7e8f8cbd1998ef96fb9cc729ac9ed | []
| no_license | nbucciarelli/Polarity-Shift | e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10 | 8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017 | refs/heads/master | 2016-09-11T00:24:32.906933 | 2008-09-26T18:01:01 | 2008-09-26T18:01:01 | 3,408,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,844 | cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File: "bitFont.cpp"
// Author: Scott Smallback (SS) / Jared Hamby (JH)
// Purpose: This file is necessary to render bitmap fonts onto the screen.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "datatypes.h"
#include "bitFont.h"
#include "..\Wrappers\viewManager.h"
#include "physics.h"
#include <windows.h>
#define CHARSET "Resource/Images/PS_bitfont.png"
#define CHARWIDTH 32
#define CHARHEIGHT 32
bitFont::bitFont(void)
{
}
bitFont::~bitFont(void)
{
}
bitFont* bitFont::getInstance()
{
static bitFont Deckard_Cain;
return &Deckard_Cain;
}
void bitFont::initialize(viewManager* _VM, char* fontImg, int char_width, int char_height)
{
VM = _VM;
csId = VM->loadTexture(fontImg);
charWidth = char_width;
charHeight = char_height;
pt dim = VM->getTextureDimensions(csId);
columns = 10;
}
void bitFont::shutdown()
{
VM->releaseTexture(csId);
}
void bitFont::drawText(char* text, int x, int y, unsigned int color, float scale, float depth)
{
vector3 pos(float(x), float(y), depth);
matrix scaling;
calc::matrixScale(scaling, vector3(scale,scale,scale));
for(int c = 0; text[c] != '\0'; c++)
{
if(text[c] != ' ') //Don't bother calling render on a space.
VM->drawTexture(csId, &pos, &scaling, &charRect(toupper(text[c])), NULL, color);
pos.x += charWidth;
}
}
rect bitFont::charRect(char ch)
{
rect holder;
ch -= 32;
holder.top = (ch / columns) * charHeight + 1;
holder.bottom = holder.top + charHeight - 2;
holder.left = (ch % columns) * charWidth;
holder.right = holder.left + charWidth;
return holder;
} | [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
2
],
[
4,
10
],
[
12,
12
],
[
14,
14
],
[
16,
40
],
[
42,
58
],
[
60,
69
],
[
72,
76
]
],
[
[
3,
3
],
[
11,
11
],
[
13,
13
],
[
15,
15
],
[
41,
41
],
[
59,
59
],
[
70,
71
]
]
]
|
c91bd2d684d8f439d95128a09b55e53f6bddbb37 | 8a4f175db665a326bcc322e3ffe6f4eac4d324da | /client/Platform.cpp | dd3b30548a3698e754b7583d5e7865a49c82c309 | []
| no_license | quocble/cubes | 51547b3913c477b46d51e5b99ad7592c8199343f | 5d071d7c11fb6c337d34716105197ee254f020dd | refs/heads/master | 2020-12-25T20:30:55.974889 | 2011-11-15T07:16:59 | 2011-11-15T07:16:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,560 | cpp | /*
Networked Physics Demo
Copyright © 2008-2011 Glenn Fiedler
http://www.gafferongames.com/networking-for-game-programmers
*/
#include "PreCompiled.h"
#include "shared/Config.h"
#include "client/Platform.h"
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#if PLATFORM == PLATFORM_MAC
#include "CoreServices/CoreServices.h"
#include <stdint.h>
#include <mach/mach_time.h>
#include <pthread.h>
#include <OpenGl/gl.h>
#include <OpenGl/glu.h>
#include <OpenGL/glext.h>
#include <OpenGL/OpenGL.h>
#include <Carbon/Carbon.h>
#endif
#if PLATFORM == PLATFORM_UNIX || PLATFORM == PLATFORM_LINUX
#include <time.h>
#include <errno.h>
#include <math.h>
#ifdef TIMER_RDTSC
#include <stdint.h>
#include <stdio.h>
#endif
#endif
namespace platform
{
#if PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_LINUX
WorkerThread::WorkerThread()
{
#ifdef MULTITHREADED
thread = 0;
#endif
}
WorkerThread::~WorkerThread()
{
#ifdef MULTITHREADED
thread = 0;
#endif
}
bool WorkerThread::Start()
{
#ifdef MULTITHREADED
pthread_attr_t attr;
pthread_attr_init( &attr );
pthread_attr_setstacksize( &attr, THREAD_STACK_SIZE );
if ( pthread_create( &thread, &attr, StaticRun, (void*)this ) != 0 )
{
printf( "error: pthread_create failed\n" );
return false;
}
#else
Run();
#endif
return true;
}
bool WorkerThread::Join()
{
#ifdef MULTITHREADED
if ( thread )
pthread_join( thread, NULL );
#endif
return true;
}
void * WorkerThread::StaticRun( void * data )
{
WorkerThread * self = (WorkerThread*) data;
self->Run();
return NULL;
}
#endif
// platform independent wait for n seconds
#if PLATFORM == PLATFORM_WINDOWS
void wait_seconds( float seconds )
{
Sleep( (int) ( seconds * 1000.0f ) );
}
#else
void wait_seconds( float seconds )
{
usleep( (int) ( seconds * 1000000.0f ) );
}
#endif
#if PLATFORM == PLATFORM_MAC
// high resolution timer (mac)
double subtractTimes( uint64_t endTime, uint64_t startTime )
{
uint64_t difference = endTime - startTime;
static double conversion = 0.0;
if ( conversion == 0.0 )
{
mach_timebase_info_data_t info;
kern_return_t err = mach_timebase_info( &info );
if( err == 0 )
conversion = 1e-9 * (double) info.numer / (double) info.denom;
}
return conversion * (double) difference;
}
Timer::Timer()
{
reset();
}
void Timer::reset()
{
_startTime = mach_absolute_time();
_deltaTime = _startTime;
}
float Timer::time()
{
uint64_t counter = mach_absolute_time();
float time = subtractTimes( counter, _startTime );
return time;
}
float Timer::delta()
{
uint64_t counter = mach_absolute_time();
float dt = subtractTimes( counter, _deltaTime );
_deltaTime = counter;
return dt;
}
float Timer::resolution()
{
static double conversion = 0.0;
if ( conversion == 0.0 )
{
mach_timebase_info_data_t info;
kern_return_t err = mach_timebase_info( &info );
if( err == 0 )
conversion = 1e-9 * (double) info.numer / (double) info.denom;
}
return conversion;
}
#endif
#if 0
// todo - convert timers for other platforms
#if PLATFORM == PLATFORM_UNIX
namespace internal
{
void wait( double seconds )
{
const double floorSeconds = ::floor(seconds);
const double fractionalSeconds = seconds - floorSeconds;
timespec timeOut;
timeOut.tv_sec = static_cast<time_t>(floorSeconds);
timeOut.tv_nsec = static_cast<long>(fractionalSeconds * 1e9);
// nanosleep may return earlier than expected if there's a signal
// that should be handled by the calling thread. If it happens,
// sleep again. [Bramz]
//
timespec timeRemaining;
while (true)
{
const int ret = nanosleep(&timeOut, &timeRemaining);
if (ret == -1 && errno == EINTR)
{
// there was only an sleep interruption, go back to sleep.
timeOut.tv_sec = timeRemaining.tv_sec;
timeOut.tv_nsec = timeRemaining.tv_nsec;
}
else
{
// we're done, or error =)
return;
}
}
}
}
#ifdef TIMER_RDTSC
class Timer
{
public:
Timer():
resolution_(determineResolution())
{
reset();
}
void reset()
{
deltaStart_ = start_ = tick();
}
double time()
{
const uint64_t now = tick();
return resolution_ * (now - start_);
}
double delta()
{
const uint64_t now = tick();
const double dt = resolution_ * (now - deltaStart_);
deltaStart_ = now;
return dt;
}
double resolution()
{
return resolution_;
}
void wait( double seconds )
{
internal::wait(seconds);
}
private:
static inline uint64_t tick()
{
#ifdef TIMER_64BIT
uint32_t a, d;
__asm__ __volatile__("rdtsc": "=a"(a), "=d"(d));
return (static_cast<uint64_t>(d) << 32) | static_cast<uint64_t>(a);
#else
uint64_t val;
__asm__ __volatile__("rdtsc": "=A"(val));
return val;
#endif
}
static double determineResolution()
{
FILE* f = fopen("/proc/cpuinfo", "r");
if (!f)
{
return 0.;
}
const int bufferSize = 256;
char buffer[bufferSize];
while (fgets(buffer, bufferSize, f))
{
float frequency;
if (sscanf(buffer, "cpu MHz : %f", &frequency) == 1)
{
fclose(f);
return 1e-6 / static_cast<double>(frequency);
}
}
fclose(f);
return 0.;
}
uint64_t start_;
uint64_t deltaStart_;
double resolution_;
};
#else
class Timer
{
public:
Timer()
{
reset();
}
void reset()
{
deltaStart_ = start_ = realTime();
}
double time()
{
return realTime() - start_;
}
double delta()
{
const double now = realTime();
const double dt = now - deltaStart_;
deltaStart_ = now;
return dt;
}
double resolution()
{
timespec res;
if (clock_getres(CLOCK_REALTIME, &res) != 0)
{
return 0.;
}
return res.tv_sec + res.tv_nsec * 1e-9;
}
void wait( double seconds )
{
internal::wait(seconds);
}
private:
static inline double realTime()
{
timespec time;
if (clock_gettime(CLOCK_REALTIME, &time) != 0)
{
return 0.;
}
return time.tv_sec + time.tv_nsec * 1e-9;
}
double start_;
double deltaStart_;
};
#endif
#endif
#endif
#if PLATFORM == PLATFORM_MAC
// display and input
#if __LP64__
static pascal OSErr quitEventHandler( const AppleEvent *appleEvt, AppleEvent *reply, void * stuff )
#else
static pascal OSErr quitEventHandler( const AppleEvent *appleEvt, AppleEvent *reply, SInt32 refcon )
#endif
{
CloseDisplay();
exit( 0 );
return false;
}
#define QZ_ESCAPE 0x35
#define QZ_TAB 0x30
#define QZ_PAGEUP 0x74
#define QZ_PAGEDOWN 0x79
#define QZ_RETURN 0x24
#define QZ_BACKSLASH 0x2A
#define QZ_DELETE 0x33
#define QZ_UP 0x7E
#define QZ_SPACE 0x31
#define QZ_LEFT 0x7B
#define QZ_DOWN 0x7D
#define QZ_RIGHT 0x7C
#define QZ_Q 0x0C
#define QZ_W 0x0D
#define QZ_E 0x0E
#define QZ_A 0x00
#define QZ_S 0x01
#define QZ_D 0x02
#define QZ_Z 0x06
#define QZ_TILDE 0x32
#define QZ_ONE 0x12
#define QZ_TWO 0x13
#define QZ_THREE 0x14
#define QZ_FOUR 0x15
#define QZ_FIVE 0x17
#define QZ_SIX 0x16
#define QZ_SEVEN 0x1A
#define QZ_EIGHT 0x1C
#define QZ_NINE 0x19
#define QZ_ZERO 0x1D
#define QZ_F1 0x7A
#define QZ_F2 0x78
#define QZ_F3 0x63
#define QZ_F4 0x76
#define QZ_F5 0x60
#define QZ_F6 0x61
#define QZ_F7 0x62
#define QZ_F8 0x64
static bool spaceKeyDown = false;
static bool backSlashKeyDown = false;
static bool enterKeyDown = false;
static bool delKeyDown = false;
static bool escapeKeyDown = false;
static bool tabKeyDown = false;
static bool pageUpKeyDown = false;
static bool pageDownKeyDown = false;
static bool upKeyDown = false;
static bool downKeyDown = false;
static bool leftKeyDown = false;
static bool rightKeyDown = false;
static bool qKeyDown = false;
static bool wKeyDown = false;
static bool eKeyDown = false;
static bool aKeyDown = false;
static bool sKeyDown = false;
static bool dKeyDown = false;
static bool zKeyDown = false;
static bool tildeKeyDown = false;
static bool oneKeyDown = false;
static bool twoKeyDown = false;
static bool threeKeyDown = false;
static bool fourKeyDown = false;
static bool fiveKeyDown = false;
static bool sixKeyDown = false;
static bool sevenKeyDown = false;
static bool eightKeyDown = false;
static bool nineKeyDown = false;
static bool zeroKeyDown = false;
static bool f1KeyDown = false;
static bool f2KeyDown = false;
static bool f3KeyDown = false;
static bool f4KeyDown = false;
static bool f5KeyDown = false;
static bool f6KeyDown = false;
static bool f7KeyDown = false;
static bool f8KeyDown = false;
static bool controlKeyDown = false;
static bool altKeyDown = false;
pascal OSStatus keyboardEventHandler( EventHandlerCallRef nextHandler, EventRef event, void * userData )
{
UInt32 eventClass = GetEventClass( event );
UInt32 eventKind = GetEventKind( event );
if ( eventClass == kEventClassKeyboard )
{
char macCharCodes;
UInt32 macKeyCode;
UInt32 macKeyModifiers;
GetEventParameter( event, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(macCharCodes), NULL, &macCharCodes );
GetEventParameter( event, kEventParamKeyCode, typeUInt32, NULL, sizeof(macKeyCode), NULL, &macKeyCode );
GetEventParameter( event, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(macKeyModifiers), NULL, &macKeyModifiers );
controlKeyDown = ( macKeyModifiers & (1<<controlKeyBit) ) != 0 ? true : false;
altKeyDown = ( macKeyModifiers & (1<<optionKeyBit) ) != 0 ? true : false;
if ( eventKind == kEventRawKeyDown )
{
switch ( macKeyCode )
{
case QZ_SPACE: spaceKeyDown = true; break;
case QZ_RETURN: enterKeyDown = true; break;
case QZ_BACKSLASH: backSlashKeyDown = true; break;
case QZ_DELETE: delKeyDown = true; break;
case QZ_ESCAPE: escapeKeyDown = true; break;
case QZ_TAB: tabKeyDown = true; break;
case QZ_PAGEUP: pageUpKeyDown = true; break;
case QZ_PAGEDOWN: pageDownKeyDown = true; break;
case QZ_UP: upKeyDown = true; break;
case QZ_DOWN: downKeyDown = true; break;
case QZ_LEFT: leftKeyDown = true; break;
case QZ_RIGHT: rightKeyDown = true; break;
case QZ_Q: qKeyDown = true; break;
case QZ_W: wKeyDown = true; break;
case QZ_E: eKeyDown = true; break;
case QZ_A: aKeyDown = true; break;
case QZ_S: sKeyDown = true; break;
case QZ_D: dKeyDown = true; break;
case QZ_Z: zKeyDown = true; break;
case QZ_TILDE: tildeKeyDown = true; break;
case QZ_ONE: oneKeyDown = true; break;
case QZ_TWO: twoKeyDown = true; break;
case QZ_THREE: threeKeyDown = true; break;
case QZ_FOUR: fourKeyDown = true; break;
case QZ_FIVE: fiveKeyDown = true; break;
case QZ_SIX: sixKeyDown = true; break;
case QZ_SEVEN: sevenKeyDown = true; break;
case QZ_EIGHT: eightKeyDown = true; break;
case QZ_NINE: nineKeyDown = true; break;
case QZ_ZERO: zeroKeyDown = true; break;
case QZ_F1: f1KeyDown = true; break;
case QZ_F2: f2KeyDown = true; break;
case QZ_F3: f3KeyDown = true; break;
case QZ_F4: f4KeyDown = true; break;
case QZ_F5: f5KeyDown = true; break;
case QZ_F6: f6KeyDown = true; break;
case QZ_F7: f7KeyDown = true; break;
case QZ_F8: f8KeyDown = true; break;
default:
{
#ifdef DISCOVER_KEY_CODES
// note: for "discovering" keycodes for new keys :)
char title[] = "Message";
char text[64];
sprintf( text, "key=%x", (int) macKeyCode );
Str255 msg_title;
Str255 msg_text;
c2pstrcpy( msg_title, title );
c2pstrcpy( msg_text, text );
StandardAlert( kAlertStopAlert, (ConstStr255Param) msg_title, (ConstStr255Param) msg_text, NULL, NULL);
#endif
return eventNotHandledErr;
}
}
}
else if ( eventKind == kEventRawKeyUp )
{
switch ( macKeyCode )
{
case QZ_SPACE: spaceKeyDown = false; break;
case QZ_BACKSLASH: backSlashKeyDown = false; break;
case QZ_RETURN: enterKeyDown = false; break;
case QZ_DELETE: delKeyDown = false; break;
case QZ_ESCAPE: escapeKeyDown = false; break;
case QZ_TAB: tabKeyDown = false; break;
case QZ_PAGEUP: pageUpKeyDown = false; break;
case QZ_PAGEDOWN: pageDownKeyDown = false; break;
case QZ_UP: upKeyDown = false; break;
case QZ_DOWN: downKeyDown = false; break;
case QZ_LEFT: leftKeyDown = false; break;
case QZ_RIGHT: rightKeyDown = false; break;
case QZ_Q: qKeyDown = false; break;
case QZ_W: wKeyDown = false; break;
case QZ_E: eKeyDown = false; break;
case QZ_A: aKeyDown = false; break;
case QZ_S: sKeyDown = false; break;
case QZ_D: dKeyDown = false; break;
case QZ_Z: zKeyDown = false; break;
case QZ_TILDE: tildeKeyDown = false; break;
case QZ_ONE: oneKeyDown = false; break;
case QZ_TWO: twoKeyDown = false; break;
case QZ_THREE: threeKeyDown = false; break;
case QZ_FOUR: fourKeyDown = false; break;
case QZ_FIVE: fiveKeyDown = false; break;
case QZ_SIX: sixKeyDown = false; break;
case QZ_SEVEN: sevenKeyDown = false; break;
case QZ_EIGHT: eightKeyDown = false; break;
case QZ_NINE: nineKeyDown = false; break;
case QZ_ZERO: zeroKeyDown = false; break;
case QZ_F1: f1KeyDown = false; break;
case QZ_F2: f2KeyDown = false; break;
case QZ_F3: f3KeyDown = false; break;
case QZ_F4: f4KeyDown = false; break;
case QZ_F5: f5KeyDown = false; break;
case QZ_F6: f6KeyDown = false; break;
case QZ_F7: f7KeyDown = false; break;
case QZ_F8: f8KeyDown = false; break;
default: return eventNotHandledErr;
}
}
}
return noErr;
}
CGLContextObj contextObj;
void HideMouseCursor()
{
CGDisplayHideCursor( kCGNullDirectDisplay );
CGAssociateMouseAndMouseCursorPosition( false );
CGDisplayMoveCursorToPoint( kCGDirectMainDisplay, CGPointZero );
}
void ShowMouseCursor()
{
CGAssociateMouseAndMouseCursorPosition( true );
CGDisplayShowCursor( kCGNullDirectDisplay );
}
CGDirectDisplayID GetDisplayId()
{
CGDirectDisplayID displayId = kCGDirectMainDisplay;
#ifdef USE_SECONDARY_DISPLAY_IF_EXISTS
const CGDisplayCount maxDisplays = 2;
CGDirectDisplayID activeDisplayIds[maxDisplays];
CGDisplayCount displayCount;
CGGetActiveDisplayList( maxDisplays, activeDisplayIds, &displayCount );
if ( displayCount == 2 )
displayId = activeDisplayIds[1];
#endif
return displayId;
}
void GetDisplayResolution( int & width, int & height )
{
CGDirectDisplayID displayId = GetDisplayId();
width = CGDisplayPixelsWide( displayId );
height = CGDisplayPixelsHigh( displayId );
}
static CGDisplayModeRef originalDisplayMode;
bool OpenDisplay( const char title[], int width, int height, int refresh )
{
// install keyboard handler
EventTypeSpec eventTypes[2];
eventTypes[0].eventClass = kEventClassKeyboard;
eventTypes[0].eventKind = kEventRawKeyDown;
eventTypes[1].eventClass = kEventClassKeyboard;
eventTypes[1].eventKind = kEventRawKeyUp;
EventHandlerUPP handlerUPP = NewEventHandlerUPP( keyboardEventHandler );
InstallApplicationEventHandler( handlerUPP, 2, eventTypes, NULL, NULL );
// capture the display and save the original display mode so we can restore it
CGDirectDisplayID displayId = GetDisplayId();
CGDisplayErr err = CGDisplayCapture( displayId );
if ( err != kCGErrorSuccess )
{
printf( "error: CGDisplayCapture failed\n" );
return false;
}
originalDisplayMode = CGDisplayCopyDisplayMode( displayId );
// search for a display mode matching the resolution and refresh rate requested
CFArrayRef allModes = CGDisplayCopyAllDisplayModes( kCGDirectMainDisplay, NULL );
CGDisplayModeRef matchingMode = NULL;
for ( int i = 0; i < CFArrayGetCount(allModes); i++ )
{
CGDisplayModeRef mode = (CGDisplayModeRef) CFArrayGetValueAtIndex( allModes, i );
const int mode_width = CGDisplayModeGetWidth( mode );
const int mode_height = CGDisplayModeGetHeight( mode );
const int mode_refresh = CGDisplayModeGetRefreshRate( mode );
//printf( "width = %d, height = %d, refresh = %d\n", mode_width, mode_height, mode_refresh );
if ( mode_width == width && mode_height == height && ( mode_refresh == refresh || mode_refresh == 0 ) )
{
matchingMode = mode;
break;
}
}
if ( matchingMode == NULL )
{
printf( "error: could not find a matching display mode\n" );
return false;
}
// actually set the display mode
CGDisplayConfigRef displayConfig;
CGBeginDisplayConfiguration( &displayConfig );
CGConfigureDisplayWithDisplayMode( displayConfig, displayId, matchingMode, NULL );
CGConfigureDisplayFadeEffect( displayConfig, 0.15f, 0.1f, 0.0f, 0.0f, 0.0f );
CGCompleteDisplayConfiguration( displayConfig, NULL );
// initialize fullscreen CGL
if ( err != kCGErrorSuccess )
{
printf( "error: CGCaptureAllDisplays failed\n" );
return false;
}
GLuint displayMask = CGDisplayIDToOpenGLDisplayMask( displayId );
CGLPixelFormatAttribute attribs[] =
{
kCGLPFANoRecovery,
kCGLPFADoubleBuffer,
kCGLPFAFullScreen,
#ifdef MULTISAMPLING
kCGLPFAMultisample,
kCGLPFASampleBuffers, ( CGLPixelFormatAttribute ) 1,
#endif
kCGLPFAStencilSize, ( CGLPixelFormatAttribute ) 8,
kCGLPFADisplayMask, ( CGLPixelFormatAttribute ) displayMask,
( CGLPixelFormatAttribute ) NULL
};
CGLPixelFormatObj pixelFormatObj;
GLint numPixelFormats;
err = CGLChoosePixelFormat( attribs, &pixelFormatObj, &numPixelFormats );
if ( err != kCGErrorSuccess )
{
printf( "error: CGLChoosePixelFormat failed\n" );
return false;
}
err = CGLCreateContext( pixelFormatObj, NULL, &contextObj );
if ( err != kCGErrorSuccess )
{
printf( "error: CGLCreateContext failed\n" );
return false;
}
CGLDestroyPixelFormat( pixelFormatObj );
err = CGLSetCurrentContext( contextObj );
if ( err != kCGErrorSuccess )
{
printf( "error: CGL set current context failed\n" );
return false;
}
err = CGLSetFullScreenOnDisplay( contextObj, displayMask );
if ( err != kCGErrorSuccess )
{
printf( "error: CGLSetFullScreenOnDisplay failed\n" );
return false;
}
// install quit handler (via apple events)
AEInstallEventHandler( kCoreEventClass, kAEQuitApplication, NewAEEventHandlerUPP(quitEventHandler), 0, false );
return true;
}
void UpdateDisplay( int interval )
{
// set swap interval
CGLSetParameter( contextObj, kCGLCPSwapInterval, &interval );
CGLFlushDrawable( contextObj );
// process events
EventRef event = 0;
OSStatus status = ReceiveNextEvent( 0, NULL, 0.0f, kEventRemoveFromQueue, &event );
if ( status == noErr && event )
{
bool sendEvent = true;
if ( sendEvent )
SendEventToEventTarget( event, GetEventDispatcherTarget() );
ReleaseEvent( event );
}
}
void CloseDisplay()
{
printf( "close display\n" );
CGReleaseAllDisplays();
CGRestorePermanentDisplayConfiguration();
CGLSetCurrentContext( NULL );
CGLDestroyContext( contextObj );
}
// basic keyboard input
Input Input::Sample()
{
Input input;
input.left = leftKeyDown;
input.right = rightKeyDown;
input.up = upKeyDown;
input.down = downKeyDown;
input.space = spaceKeyDown;
input.escape = escapeKeyDown;
input.tab = tabKeyDown;
input.backslash = backSlashKeyDown;
input.enter = enterKeyDown;
input.del = delKeyDown;
input.pageUp = pageUpKeyDown;
input.pageDown = pageDownKeyDown;
input.q = qKeyDown;
input.w = wKeyDown;
input.e = eKeyDown;
input.a = aKeyDown;
input.s = sKeyDown;
input.d = dKeyDown;
input.z = zKeyDown;
input.tilde = tildeKeyDown;
input.one = oneKeyDown;
input.two = twoKeyDown;
input.three = threeKeyDown;
input.four = fourKeyDown;
input.five = fiveKeyDown;
input.six = sixKeyDown;
input.seven = sevenKeyDown;
input.eight = eightKeyDown;
input.nine = nineKeyDown;
input.zero = zeroKeyDown;
input.f1 = f1KeyDown;
input.f2 = f2KeyDown;
input.f3 = f3KeyDown;
input.f4 = f4KeyDown;
input.f5 = f5KeyDown;
input.f6 = f6KeyDown;
input.f7 = f7KeyDown;
input.f8 = f8KeyDown;
input.control = controlKeyDown;
input.alt = altKeyDown;
return input;
}
#endif
}
| [
"[email protected]"
]
| [
[
[
1,
833
]
]
]
|
0bc1f0816ac165d2c1e8c6d3c0122061127bba46 | f9351a01f0e2dec478e5b60c6ec6445dcd1421ec | /itl/boost/itl/rational.hpp | 7433876a69a363a821ae9958548b8beddfdec9b8 | [
"BSL-1.0"
]
| permissive | WolfgangSt/itl | e43ed68933f554c952ddfadefef0e466612f542c | 6609324171a96565cabcf755154ed81943f07d36 | refs/heads/master | 2016-09-05T20:35:36.628316 | 2008-11-04T11:44:44 | 2008-11-04T11:44:44 | 327,076 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 960 | hpp | /*----------------------------------------------------------------------------+
Copyright (c) 2008-2008: Joachim Faulhaber
+-----------------------------------------------------------------------------+
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENCE.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
+----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
itl_ptime provides adapter code for boost::posix_time::ptime.
It implements incrementation (++) decrementation (--) and a neutral element
w.r.t. addition (neutron()).
-----------------------------------------------------------------------------*/
#ifndef __itl_rational_JOFA_080913_H__
#define __itl_rational_JOFA_080913_H__
#include <boost/rational.hpp>
#define ITL_NEEDS_RATIONAL_IS_CONTINUOUS
#endif
| [
"jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a"
]
| [
[
[
1,
24
]
]
]
|
677883410aeb0aaf006eb57fc71cd8f57e407b66 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/conjurer/conjurer/src/conjurer/ninguitoolscale_cmds.cc | 8919450c21de906c9d12bb42321de8963724fa30 | []
| 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 | 863 | cc | #include "precompiled/pchconjurerapp.h"
//------------------------------------------------------------------------------
// ninguitoolscale_cmds.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "conjurer/ninguitoolscale.h"
#include "kernel/npersistserver.h"
//------------------------------------------------------------------------------
/**
Nebula class scripting initialization
*/
NSCRIPT_INITCMDS_BEGIN( nInguiToolScale )
NSCRIPT_ADDCMD('JGCS', float, GetCurrentScaling, 0, (), 0, ());
NSCRIPT_ADDCMD('JSSF', void, SetScaleFactor, 1, (float), 0, ());
NSCRIPT_INITCMDS_END()
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
20
]
]
]
|
638cecedfe81611ab327b6e5b052803ab786557d | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/app/messaging/plugin_bio_control_api/inc/EdwinTestControl.h | 8b749c364367ea34bf992adb20e2a912148be00a | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,350 | h | /*
* 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:
*
*/
#ifndef EDWINTESTCONTROL_H_
#define EDWINTESTCONTROL_H_
#include <eikedwin.h>
class CAknsBasicBackgroundControlContext;
class CEdwinTestControl : public CCoeControl, public MCoeControlObserver
{
public:
static CEdwinTestControl* NewL(void);
virtual ~CEdwinTestControl();
protected:
TTypeUid::Ptr MopSupplyObject(TTypeUid aId); //
private:
virtual void SizeChanged();
virtual void HandleResourceChange(TInt aType);
virtual TInt CountComponentControls() const;
virtual CCoeControl* ComponentControl(TInt aIndex) const;
void ConstructL(void);
void Draw(const TRect& aRect) const;
void HandleControlEventL( CCoeControl* aControl, TCoeEvent aEventType);
TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType );
private:
CAknsBasicBackgroundControlContext* iBgContext;
CEikEdwin* iEditWin;
};
#endif /*EDWINTESTCONTROL_H_*/
| [
"none@none"
]
| [
[
[
1,
47
]
]
]
|
39d263ca8a2b6b0408a7675cefddb3693fec6312 | 0ee189afe953dc99825f55232cd52b94d2884a85 | /psql/psql.cpp | 6abb7882c00e0853ce1a01bd69f5b1f82665e09f | []
| no_license | spolitov/lib | fed99fa046b84b575acc61919d4ef301daeed857 | 7dee91505a37a739c8568fdc597eebf1b3796cf9 | refs/heads/master | 2016-09-11T02:04:49.852151 | 2011-08-11T18:00:44 | 2011-08-11T18:00:44 | 2,192,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,766 | cpp | #if defined(_MSC_VER)
#pragma warning(disable: 4996)
#include <WinSock2.h>
#endif
#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <mstd/hton.hpp>
#include <mstd/null.hpp>
#include <mstd/pointer_cast.hpp>
#include <mlog/Logging.h>
#include "psql.h"
MLOG_DECLARE_LOGGER(psql);
namespace psql {
namespace {
void write2(char *& pos, boost::int16_t value)
{
*mstd::pointer_cast<boost::int16_t*>(pos) = mstd::hton(value);
pos += 2;
}
void write4(char *& pos, boost::int32_t value)
{
*mstd::pointer_cast<boost::int32_t*>(pos) = mstd::hton(value);
pos += 4;
}
void write8(char *& pos, boost::int64_t value)
{
*mstd::pointer_cast<boost::int64_t*>(pos) = mstd::hton(value);
pos += 8;
}
}
PGConnHolder::PGConnHolder(const std::string & cmd)
{
conn_ = PQconnectStart(cmd.c_str());
}
PGConnHolder::~PGConnHolder()
{
if(conn_)
PQfinish(conn_);
}
PGconn * PGConnHolder::conn()
{
return conn_;
}
////////////////////////////////////////////////////////////////////////////////
// class Connection
////////////////////////////////////////////////////////////////////////////////
Connection::Connection(const std::string & cmd)
: PGConnHolder(cmd)
{
if(!conn() || PQstatus(conn()) == CONNECTION_BAD)
BOOST_THROW_EXCEPTION(ConnectionException());
int socket = PQsocket(conn());
PostgresPollingStatusType status = PGRES_POLLING_WRITING;
while(status != PGRES_POLLING_OK)
{
fd_set sockets;
FD_ZERO(&sockets);
FD_SET(socket, &sockets);
int result = 0;
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 100000;
if(status == PGRES_POLLING_READING)
{
result = select(socket + 1, &sockets, 0, 0, &timeout);
} else if(status == PGRES_POLLING_WRITING)
{
result = select(socket + 1, 0, &sockets, 0, &timeout);
}
if(result > 0)
{
status = PQconnectPoll(conn());
MLOG_MESSAGE(Debug, "Poll result: " << status << ", conn: " << conn());
if(status == PGRES_POLLING_FAILED)
{
ConnStatusType connStatus = PQstatus(conn());
BOOST_THROW_EXCEPTION(ConnectionException() << mstd::error_message(PQerrorMessage(conn())) << ConnStatus(connStatus));
}
} else if(result < 0)
MLOG_MESSAGE(Warning, "Select failed: " << result);
}
MLOG_MESSAGE(Notice, "DB Connected: " << conn());
}
Connection::~Connection()
{
}
const boost::posix_time::time_duration timeout = boost::posix_time::seconds(15);
void Connection::checkResult(const char * query, Result & result, bool canHaveErrors, const boost::posix_time::ptime & start)
{
boost::posix_time::ptime stop = boost::posix_time::microsec_clock::universal_time();
boost::posix_time::time_duration passed = stop - start;
if(passed > timeout)
MLOG_MESSAGE(Error, "slow query: " << query << ", passed: " << passed);
if(!result.success())
{
if(!canHaveErrors)
MLOG_MESSAGE(Error, "exec failed: " << result.status() << ", msg: " << result.error() << ", query: " << query);
else
MLOG_MESSAGE(Notice, "exec failed: " << result.status() << ", msg: " << result.error() << ", query: " << query);
BOOST_THROW_EXCEPTION(ExecException() << mstd::error_message(result.error()));
}
}
Result Connection::exec(const char * query, bool canHaveErrors)
{
MLOG_MESSAGE(Debug, "exec(" << query << ")");
boost::posix_time::ptime start = boost::posix_time::microsec_clock::universal_time();
Result result(PQexecParams(conn(), query, 0, 0, 0, 0, 0, 1));
checkResult(query, result, canHaveErrors, start);
MLOG_MESSAGE(Debug, "exec succeeded");
return move(result);
}
Result Connection::exec(const std::string & query, bool canHaveErrors)
{
return exec(query.c_str(), canHaveErrors);
}
void Connection::execVoid(const char * query, bool canHaveErrors)
{
MLOG_MESSAGE(Debug, "execVoid(" << query << ")");
boost::posix_time::ptime start = boost::posix_time::microsec_clock::universal_time();
Result result(PQexecParams(conn(), query, 0, 0, 0, 0, 0, 0));
checkResult(query, result, canHaveErrors, start);
MLOG_MESSAGE(Debug, "exec succeeded");
}
void Connection::execVoid(const std::string & query, bool canHaveErrors)
{
execVoid(query.c_str(), canHaveErrors);
}
Result Connection::exec(const char * query, size_t size, const char * const * values, int * lengths, bool canHaveErrors)
{
MLOG_MESSAGE(Debug, "exec(" << query << ", " << size << ")");
int * formats = static_cast<int*>(alloca(size * sizeof(int)));
std::fill_n(formats, size, 1);
boost::posix_time::ptime start = boost::posix_time::microsec_clock::universal_time();
Result result(PQexecParams(conn(), query, size, 0,
values, lengths, formats, 1));
checkResult(query, result, canHaveErrors, start);
MLOG_MESSAGE(Debug, "exec succeeded");
return move(result);
}
void Connection::execVoid(const char * query, size_t size, const char * const * values, int * lengths, bool canHaveErrors)
{
MLOG_MESSAGE(Debug, "execVoid(" << query << ", " << size << ")");
int * formats = static_cast<int*>(alloca(size * sizeof(int)));
std::fill_n(formats, size, 1);
boost::posix_time::ptime start = boost::posix_time::microsec_clock::universal_time();
Result result(PQexecParams(conn(), query, size, 0,
values, lengths, formats, 0));
checkResult(query, result, canHaveErrors, start);
MLOG_MESSAGE(Debug, "exec succeeded");
}
////////////////////////////////////////////////////////////////////////////////
// class Transaction
////////////////////////////////////////////////////////////////////////////////
Transaction::Transaction(psql::Connection & conn, IsolationLevel level)
: conn_(conn), commited_(boost::indeterminate)
{
switch(level) {
case ilSerializable:
conn_.exec("begin isolation level serializable", false);
break;
case ilReadCommitted:
conn_.exec("begin isolation level read committed", false);
break;
default:
conn_.exec("begin", false);
break;
}
}
void Transaction::commit()
{
conn_.exec("commit", false);
commited_ = true;
}
void Transaction::rollback()
{
conn_.exec("rollback", false);
commited_ = false;
}
Transaction::~Transaction()
{
if(indeterminate(commited_))
conn_.exec("rollback", false);
}
////////////////////////////////////////////////////////////////////////////////
// class Result
////////////////////////////////////////////////////////////////////////////////
ParametricExecution::ParametricExecution(Connection & conn)
: conn_(conn) {}
ParametricExecution::~ParametricExecution()
{
for(std::vector<char*>::const_iterator i = buffers_.begin(), end = buffers_.end(); i != end; ++i)
delete [] *i;
}
void ParametricExecution::clear()
{
longInts_.clear();
ints_.clear();
smallInts_.clear();
values_.clear();
lengths_.clear();
for(std::vector<char*>::const_iterator i = buffers_.begin(), end = buffers_.end(); i != end; ++i)
delete [] *i;
buffers_.clear();
}
Result ParametricExecution::exec(const char * query, bool canHaveErrors)
{
MLOG_MESSAGE(Debug, "param exec: " << query);
size_t size = values_.size();
return conn_.exec(query, size, !size ? 0 : &values_[0], !size ? 0 : &lengths_[0], canHaveErrors);
}
Result ParametricExecution::exec(const std::string & query, bool canHaveErrors)
{
return exec(query.c_str(), canHaveErrors);
}
void ParametricExecution::execVoid(const char * query, bool canHaveErrors)
{
MLOG_MESSAGE(Debug, "param exec: " << query);
size_t size = values_.size();
conn_.execVoid(query, size, !size ? 0 : &values_[0], !size ? 0 : &lengths_[0], canHaveErrors);
}
void ParametricExecution::execVoid(const std::string & query, bool canHaveErrors)
{
execVoid(query.c_str(), canHaveErrors);
}
size_t ParametricExecution::size() const
{
return values_.size();
}
void ParametricExecution::addParam(boost::int64_t value)
{
longInts_.push_back(mstd::hton(value));
addImpl(&longInts_.back());
}
void ParametricExecution::addParam(boost::int32_t value)
{
ints_.push_back(mstd::hton(value));
addImpl(&ints_.back());
}
void ParametricExecution::addParam(boost::int16_t value)
{
smallInts_.push_back(mstd::hton(value));
addImpl(&smallInts_.back());
}
void ParametricExecution::addParam(const char *value, size_t length)
{
values_.push_back(value);
lengths_.push_back(length);
}
void ParametricExecution::addArray(const std::pair<const char*, const char*> * value, size_t size)
{
typedef const std::pair<const char*, const char*> * iterator;
iterator end = value + size;
size_t bufferSize = 20 + 4 * size;
for(iterator i = value; i != end; ++i)
bufferSize += i->second - i->first;
char * temp = new char[bufferSize]; // TODO
buffers_.push_back(temp);
char * out = temp;
write4(out, 1);
write4(out, 1);
write4(out, psql::oidText);
write4(out, size);
write4(out, 1);
for(; value != end; ++value)
{
size_t len = value->second - value->first;
write4(out, len);
memcpy(out, value->first, len);
out += len;
}
addParam(temp, out - temp);
}
void ParametricExecution::addArray(const std::string * value, size_t size)
{
typedef const std::string * iterator;
iterator end = value + size;
size_t bufferSize = 20 + 4 * size;
for(iterator i = value; i != end; ++i)
bufferSize += i->length();
char * temp = new char[bufferSize]; // TODO
buffers_.push_back(temp);
char * out = temp;
write4(out, 1);
write4(out, 1);
write4(out, psql::oidText);
write4(out, size);
write4(out, 1);
for(; value != end; ++value)
{
size_t len = value->length();
write4(out, len);
memcpy(out, value->c_str(), len);
out += len;
}
addParam(temp, out - temp);
}
void ParametricExecution::addArray(const boost::int64_t * value, size_t size)
{
char * temp = new char[size * 12 + 20]; // TODO
buffers_.push_back(temp);
char * out = temp;
write4(out, 1);
write4(out, 1);
write4(out, psql::oidInt64);
write4(out, size);
write4(out, 1);
for(const boost::int64_t * end = value + size; value != end; ++value)
{
write4(out, 8);
write8(out, *value);
}
addParam(temp, out - temp);
}
void ParametricExecution::addArray(const boost::int32_t * value, size_t size)
{
char * temp = new char[size * 8 + 20]; // TODO
buffers_.push_back(temp);
char * out = temp;
write4(out, 1);
write4(out, 1);
write4(out, psql::oidInt32);
write4(out, size);
write4(out, 1);
for(const boost::int32_t * end = value + size; value != end; ++value)
{
write4(out, 4);
write4(out, *value);
}
addParam(temp, out - temp);
}
void ParametricExecution::addArray(const boost::int16_t * value, size_t size)
{
char * temp = new char[size * 6 + 20]; // TODO
buffers_.push_back(temp);
char * out = temp;
write4(out, 1);
write4(out, 1);
write4(out, psql::oidInt16);
write4(out, size);
write4(out, 1);
for(const boost::int16_t * end = value + size; value != end; ++value)
{
write4(out, 2);
write2(out, *value);
}
addParam(temp, out - temp);
}
////////////////////////////////////////////////////////////////////////////////
// class Result
////////////////////////////////////////////////////////////////////////////////
Result::Result(PGresult * value)
: value_(value), width_(0) {}
Result::Result()
: value_(0), width_(0) {}
Result::~Result()
{
if(value_)
PQclear(value_);
}
bool Result::success() const
{
ExecStatusType status = PQresultStatus(value_);
return status == PGRES_COMMAND_OK || status == PGRES_TUPLES_OK;
}
ExecStatusType Result::status() const
{
return PQresultStatus(value_);
}
const char * Result::error() const
{
return PQresultErrorMessage(value_);
}
size_t Result::size() const
{
return PQntuples(value_);
}
Result::reference Result::at(size_t index) const
{
return ResultRowRef(value_, index, columns());
}
Oid Result::type(size_t index) const
{
return PQftype(value_, index);
}
size_t Result::columns() const
{
if(!width_)
width_ = PQnfields(value_);
return width_;
}
Result::reference Result::operator[](size_t index) const
{
return at(index);
}
////////////////////////////////////////////////////////////////////////////////
// class ResultRowRef
////////////////////////////////////////////////////////////////////////////////
ResultRowRef::ResultRowRef(PGresult *result, size_t index, size_t size)
: result_(result), index_(index), size_(size) {}
const void * ResultRowRef::raw(size_t index) const
{
return PQgetvalue(result_, index_, index);
}
boost::int16_t ResultRowRef::asInt16(size_t index) const
{
const void * data = PQgetvalue(result_, index_, index);
Oid oid = PQftype(result_, index);
if(oid != oidInt16)
BOOST_THROW_EXCEPTION(InvalidTypeException() << OidInfo(oid) << ExpectedOidInfo(oidInt16));
return mstd::ntoh(*static_cast<const boost::int16_t*>(data));
}
boost::int32_t ResultRowRef::asInt32(size_t index) const
{
const void * data = PQgetvalue(result_, index_, index);
Oid oid = PQftype(result_, index);
if(oid != oidInt32)
BOOST_THROW_EXCEPTION(InvalidTypeException() << OidInfo(oid) << ExpectedOidInfo(oidInt32));
return mstd::ntoh(*static_cast<const boost::int32_t*>(data));
}
boost::int64_t ResultRowRef::asInt64(size_t index) const
{
const void * data = PQgetvalue(result_, index_, index);
Oid oid = PQftype(result_, index);
if(oid != oidInt64)
BOOST_THROW_EXCEPTION(InvalidTypeException() << OidInfo(oid) << ExpectedOidInfo(oidInt64));
return mstd::ntoh(*static_cast<const boost::int64_t*>(data));
}
const char * ResultRowRef::asCString(size_t index) const
{
const void * data = PQgetvalue(result_, index_, index);
Oid oid = PQftype(result_, index);
if(oid != oidText && oid != oidVarChar)
BOOST_THROW_EXCEPTION(InvalidTypeException() << OidInfo(oid) << ExpectedOidInfo(oidText));
return static_cast<const char*>(data);
}
ByteArray ResultRowRef::asArray(size_t index) const
{
const void * data = PQgetvalue(result_, index_, index);
Oid oid = PQftype(result_, index);
if(oid != oidByteArray)
BOOST_THROW_EXCEPTION(InvalidTypeException() << OidInfo(oid) << ExpectedOidInfo(oidByteArray));
return ByteArray(PQgetlength(result_, index_, index), static_cast<const char*>(data));
}
size_t ResultRowRef::length(size_t index) const
{
return PQgetlength(result_, index_, index);
}
bool ResultRowRef::null(size_t index) const
{
return PQgetisnull(result_, index_, index) != 0;
}
size_t ResultRowRef::size() const
{
return size_;
}
}
| [
"[email protected]"
]
| [
[
[
1,
569
]
]
]
|
5684533fd31b0a07df6126c4fec29a11226e51c3 | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Engine/Utilities/ComponentOmni.cpp | cb4e33770d473c1dc95ef0441a56b4c6c8dfe303 | []
| no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 4,256 | cpp | #define __DONT_INCLUDE_MEM_LEAKS__
#include "ComponentOmni.h"
#include "ComponentObject3D.h"
#include "LightManager.h"
#include "OmniLight.h"
#include "ScriptManager.h"
#include "Core.h"
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#include <luabind/luabind.hpp>
#include <luabind/function.hpp>
#include <luabind/class.hpp>
#include <luabind/operator.hpp>
#include "Utils\MemLeaks.h"
#include "Utils\Logger.h"
CComponentOmni* CComponentOmni::AddToEntity(CGameEntity* _pEntity, const Vect3f& _vOffsetPosition, const CColor& _vColor, float _fStartRangeAtt, float _fEndRangeAtt, const string& _szScript)
{
CComponentOmni *l_pComp = new CComponentOmni();
assert(_pEntity && _pEntity->IsOk());
if(l_pComp->Init(_pEntity, _vOffsetPosition, _vColor, _fStartRangeAtt, _fEndRangeAtt, _szScript))
{
l_pComp->SetEntity(_pEntity);
return l_pComp;
}
else
{
delete l_pComp;
return 0;
}
}
CComponentOmni* CComponentOmni::AddToEntityFromResource(CGameEntity* _pEntity, const string& _szResource, const string& _szScript)
{
CComponentOmni *l_pComp = new CComponentOmni();
assert(_pEntity && _pEntity->IsOk());
if(l_pComp->InitFromResource(_pEntity, _szResource, _szScript))
{
l_pComp->SetEntity(_pEntity);
return l_pComp;
}
else
{
delete l_pComp;
return 0;
}
}
bool CComponentOmni::Init(CGameEntity* _pEntity, const Vect3f& _vOffsetPosition, const CColor& _vColor, float _fStartRangeAtt, float _fEndRangeAtt, const string& _szScript)
{
m_bFromResource = false;
m_vOffset = _vOffsetPosition;
m_pObject3D = _pEntity->GetComponent<CComponentObject3D>();
m_szScript = _szScript;
if(!m_pObject3D)
{
LOGGER->AddNewLog(ELL_ERROR, "CComponentOmni::Init no s'ha trobat el component Object3D");
SetOk(false);
return IsOk();
}
m_pOmni = CORE->GetLightManager()->CreateOmniLight(_pEntity->GetName().append("omni"), m_pObject3D->GetPosition() + _vOffsetPosition, _vColor, _fStartRangeAtt, _fEndRangeAtt);
if(!m_pOmni)
{
LOGGER->AddNewLog(ELL_ERROR, "CComponentOmni::Init no s'ha pogut crear la omni \"%s\"", _pEntity->GetName().c_str());
SetOk(false);
return IsOk();
}
m_pOmni->SetActive(true);
SetOk(true);
return IsOk();
}
bool CComponentOmni::InitFromResource(CGameEntity* _pEntity, const string& _szResource, const string& _szScript)
{
CLight* l_pLight = CORE->GetLightManager()->GetResource(_szResource);
m_szScript = _szScript;
if(l_pLight)
{
if(l_pLight->GetType() == CLight::OMNI)
{
m_pOmni = (COmniLight*) l_pLight;
}
else
{
LOGGER->AddNewLog(ELL_ERROR, "CComponentOmni::InitFromResource la llum \"%s\" no Ús del tipus omni.", _szResource);
SetOk(false);
return IsOk();
}
}
else
{
LOGGER->AddNewLog(ELL_ERROR, "CComponentOmni::InitFromResource no s'ha trobat la llum \"%s\".", _szResource);
SetOk(false);
return IsOk();
}
SetOk(true);
return IsOk();
}
void CComponentOmni::RunScript(float _fDeltaTime)
{
if(m_szScript != "")
{
CScriptManager* m_pSM = CORE->GetScriptManager();
lua_State *l_pLUA = m_pSM->GetLuaState();
try {
luabind::call_function<void>(l_pLUA, m_szScript.c_str(), GetEntity(), _fDeltaTime);
} catch(const luabind::error& _TheError)
{
CScriptManager::PrintError(_TheError);
LOGGER->AddNewLog(ELL_ERROR,"\tEntity \"%s\" has launched script \"%s\" has failed with error \"%s\"",
GetEntity()->GetName().c_str(), m_szScript.c_str(), _TheError.what());
}
}
}
void CComponentOmni::Enable(void)
{
m_pOmni->SetActive(true);
}
void CComponentOmni::Disable(void)
{
m_pOmni->SetActive(false);
}
void CComponentOmni::Update(float _fDeltaTime)
{
m_pOmni->SetPosition(m_pObject3D->GetPosition() + m_vOffset);
RunScript(_fDeltaTime);
}
void CComponentOmni::Release()
{
if(!m_bFromResource)
{
CORE->GetLightManager()->Remove(m_pOmni->GetName());
}
else
{
m_pOmni->SetActive(false);
}
}
COmniLight* CComponentOmni::GetOmniLight()
{
return m_pOmni;
} | [
"sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485"
]
| [
[
[
1,
170
]
]
]
|
d52df290802e1df78710a922a6f4e05dbfa35bdd | 2982a765bb21c5396587c86ecef8ca5eb100811f | /util/wm5/LibMathematics/Algebra/Wm5HPoint.h | 68d921166fbffc7818e8a99f3f69e644ba5442da | []
| no_license | evanw/cs224final | 1a68c6be4cf66a82c991c145bcf140d96af847aa | af2af32732535f2f58bf49ecb4615c80f141ea5b | refs/heads/master | 2023-05-30T19:48:26.968407 | 2011-05-10T16:21:37 | 2011-05-10T16:21:37 | 1,653,696 | 27 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 1,697 | h | // Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.2 (2011/03/27)
#ifndef WM5HPOINT_H
#define WM5HPOINT_H
#include "Wm5MathematicsLIB.h"
namespace Wm5
{
class WM5_MATHEMATICS_ITEM HPoint
{
public:
// Construction and destruction. HPoint represents a homogeneous point
// of the form (x,y,z,w). Affine points are characterized by w = 1
// (see class APoint) and affine vectors are characterized by w = 0
// (see class AVector).
HPoint (); // uninitialized
HPoint (const HPoint& pnt);
HPoint (float x, float y, float z, float w);
~HPoint ();
// Coordinate access.
inline operator const float* () const;
inline operator float* ();
inline const float& operator[] (int i) const;
inline float& operator[] (int i);
inline float X () const;
inline float& X ();
inline float Y () const;
inline float& Y ();
inline float Z () const;
inline float& Z ();
inline float W () const;
inline float& W ();
// Assignment.
HPoint& operator= (const HPoint& pnt);
// Comparison (for use by STL containers).
bool operator== (const HPoint& pnt) const;
bool operator!= (const HPoint& pnt) const;
bool operator< (const HPoint& pnt) const;
bool operator<= (const HPoint& pnt) const;
bool operator> (const HPoint& pnt) const;
bool operator>= (const HPoint& pnt) const;
protected:
float mTuple[4];
};
#include "Wm5HPoint.inl"
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
12d8d5254223434dc59aa5c9313444ae210baad3 | 942b88e59417352fbbb1a37d266fdb3f0f839d27 | /src/argss/audio.hxx | 4d5cc3096208e6e4fcd893078b248e4a9e0b2c0f | [
"BSD-2-Clause"
]
| permissive | take-cheeze/ARGSS... | 2c1595d924c24730cc714d017edb375cfdbae9ef | 2f2830e8cc7e9c4a5f21f7649287cb6a4924573f | refs/heads/master | 2016-09-05T15:27:26.319404 | 2010-12-13T09:07:24 | 2010-12-13T09:07:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,577 | hxx | //////////////////////////////////////////////////////////////////////////////////
/// ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf)
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright
/// notice, this list of conditions and the following disclaimer in the
/// documentation and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
/// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
/// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
/// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
/// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
/// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
/// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
/// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
/// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
/// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////////////////////////////
#ifndef _ARGSS_AUDIO_HXX_
#define _ARGSS_AUDIO_HXX_
////////////////////////////////////////////////////////////
/// Headers
////////////////////////////////////////////////////////////
#include <argss/ruby.hxx>
////////////////////////////////////////////////////////////
/// ARGSS Audio namespace
////////////////////////////////////////////////////////////
namespace ARGSS
{
namespace AAudio
{
VALUE& getID();
void Init();
VALUE rbgm_play(int argc, VALUE *argv, VALUE self);
VALUE rbgm_stop(VALUE self);
VALUE rbgm_fade(VALUE self, VALUE fade);
VALUE rbgs_play(int argc, VALUE *argv, VALUE self);
VALUE rbgs_stop(VALUE self);
VALUE rbgs_fade(VALUE self, VALUE fade);
VALUE rme_play(int argc, VALUE *argv, VALUE self);
VALUE rme_stop(VALUE self);
VALUE rme_fade(VALUE self, VALUE fade);
VALUE rse_play(int argc, VALUE *argv, VALUE self);
VALUE rse_stop(VALUE self);
} // namespace AAudio
} // namespace ARGSS
#endif // _ARGSS_AUDIO_HXX_
| [
"takeshi@takeshi-laptop.(none)",
"[email protected]"
]
| [
[
[
1,
24
],
[
27,
30
],
[
32,
32
],
[
57,
57
]
],
[
[
25,
26
],
[
31,
31
],
[
33,
56
],
[
58,
58
]
]
]
|
a93ede75010bba2e67f8285decc347b1ec1c570c | 12d2d19ae9e12973a7d25b97b5bc530b82dd9519 | /deliciousServer/DBResult.h | cf1f0e3c1946d34942f5780860e817b89e70c1df | []
| no_license | gaoxiaojun/delicacymap | fe82b228e89d3fad48262e03bd097a9041c2a252 | aceabb664bbd6f7b87b0c9b8ffdad55bc6310c68 | refs/heads/master | 2021-01-10T11:11:51.412815 | 2010-05-05T02:36:14 | 2010-05-05T02:36:14 | 47,736,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,215 | h | #pragma once
#include <utility>
#include <vector>
#include <map>
#include <boost/lexical_cast.hpp>
class DBResult;
class DBRow;
class DBexception : public std::exception
{
public:
explicit DBexception(const char* s=NULL, int code=0) : errmsg(s), errcode(code) {}
virtual const char* what() const throw(){return errmsg;};
private:
const char* errmsg;
int errcode;
};
class RowModifier
{
public:
RowModifier(std::string &valuetomodified, int index, DBRow& belongto)
: value(valuetomodified), row(belongto), indx(index)
{
}
operator const std::string&(){return value;}
template <typename CompareType>
bool operator==(const CompareType& other) const
{
return value == boost::lexical_cast<std::string>(other);
}
template <typename CompareType>
bool operator!=(const CompareType& other) const
{
return value != boost::lexical_cast<std::string>(other);
}
template <typename ValueType>
const std::string& operator=(const ValueType& val)
{
std::string newvalue = boost::lexical_cast<std::string>(val);
if (newvalue != value)
{
value = newvalue;
row.colmodified.push_back(indx);
}
return value;
}
private:
std::string& value;
DBRow& row;
const int indx;
};
class DBRow
{
public:
friend class DBResult;
friend class RowModifier;
const std::string& operator[](int index) const;
const std::string& operator[](const std::string& colname) const;
RowModifier operator[](int index);
RowModifier operator[](const std::string& colname);
template <typename To>
To GetValueAs(const std::string& colname) const
{
const std::string& ret = operator[](colname);
return boost::lexical_cast<To>(ret);
}
template <typename To>
To GetValueAs(int index) const
{
const std::string& ret = operator[](index);
return boost::lexical_cast<To>(ret);
}
const std::vector<int>& ColumnModified() const { return colmodified; }
void ResetState();
//void swap(const DBRow& other);
private:
DBRow(DBResult*);
std::vector<std::string> values;
std::vector<int> colmodified;
DBResult* result;
};
class DBResult
{
public:
friend class DBContext;
friend class DBRow;
DBResult(void);
DBResult(size_t);
~DBResult(void);
void SetColumnName(size_t index, const std::string& colname);
const std::string& ColumnName(size_t index) const;
size_t RowsCount() const;
size_t ColCount() const;
const std::string& Value(size_t Row, size_t Col) const;
const DBRow& operator[](int index) const;
const DBRow& GetRow(size_t index) const;
DBRow& operator[](int index);
DBRow& GetRow(size_t index);
DBRow& AddRow();
private:
size_t ResolveColumnName(const std::string& colname);
void AppendData(int argc, char** argv, char** colname);
typedef std::map<std::string, size_t> ResolveCachesCont;
ResolveCachesCont resolvecache;
std::vector<DBRow> data;
std::vector<std::string> colnames;
};
| [
"colprog@d4fe8cd8-f54c-11dd-8c4e-4bbb75a408b7"
]
| [
[
[
1,
128
]
]
]
|
d5d7849593da2c96106b2b77e36d16c73efc8ff9 | e5f7a02c92c5a60c924e07813bc0b7b8944c2ce8 | /8-event_serialization/8.6/Window.h | 5b53bbb71fa03cdf5b2bb5135c1f5410e220bab3 | []
| no_license | 7shi/thunkben | b8fe8f29b43c030721e8a08290c91275c9f455fe | 9bc99c5a957e087bb41bd6f87cf7dfa44e7b55f6 | refs/heads/main | 2022-12-27T19:53:39.322464 | 2011-11-30T16:57:45 | 2011-11-30T16:57:45 | 303,163,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,229 | h | #pragma once
#include <list>
#include <functional>
#include <string>
#include <windows.h>
#include "xbyak/xbyak.h"
template <class T, class TA1, class TA2, class TA3, class TA4, class TR>
struct StdCallThunk : public Xbyak::CodeGenerator {
void init(T *t, TR(T::*p)(TA1, TA2, TA3, TA4)) {
mov(ecx, reinterpret_cast<intptr_t>(t));
jmp(*reinterpret_cast<void **>(&p));
}
};
typedef std::basic_string<TCHAR> tstring;
class Window {
protected:
HINSTANCE hInst;
tstring windowClass;
StdCallThunk<Window, HWND, UINT, WPARAM, LPARAM, LRESULT> wndProc;
void OnMouseDown(int button, WPARAM wParam, LPARAM lParam);
void OnMouseUp(int button, WPARAM wParam, LPARAM lParam);
public:
HWND hWnd;
ATOM MyRegisterClass(HINSTANCE hInstance, const tstring &windowClass);
BOOL InitInstance(const tstring &title, int nCmdShow);
LRESULT WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
std::list<std::function<bool(int, int)>> Command;
std::list<std::function<void(HDC)>> Paint;
std::list<std::function<void(int, int, int, WPARAM)>> MouseDown, MouseUp;
std::list<std::function<void(int, int, WPARAM)>> MouseMove;
};
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
ec457072076298fdfd81d71a9909a0300fa7f614 | 15f5ea95f75eebb643a9fa4d31592b2537a33030 | /src/main/MainWidget.h | b93221cf93d56fb1f579953ff6a76137086edebe | []
| no_license | festus-onboard/graphics | 90aaf323e188b205661889db2c9ac59ed43bfaa7 | fdd195cd758ef95147d2d02160062d2014e50e04 | refs/heads/master | 2021-05-26T14:38:54.088062 | 2009-05-10T16:59:28 | 2009-05-10T16:59:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | h | #ifndef __MainWidget_h__
#define __MainWidget_h__
#include <qwidget>
#include <qpushbutton>
class MainWidget : public QPushButton
{
public:
MainWidget(QWidget *parent = 0, Qt::WFlags flags = 0);
QSizePolicy sizePolicy();
void resizeEvent(QResizeEvent * event);
};
#endif | [
"[email protected]"
]
| [
[
[
1,
16
]
]
]
|
0b56949b45ac0be8b877210e2805facc60add300 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/InputSystemDX9.cpp | b7068bd96c1802deecddbccd7d195470b978b949 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,692 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: InputSystemDX9.cpp
Version: 0.05
---------------------------------------------------------------------------
*/
#include "PrecompiledHeaders.h"
#include "DeviceKeyboardDX9.h"
#include "InputDeviceEnumerator.h"
#include "InputSystemDX9.h"
namespace nGENE
{
// Initialize static member
TypeInfo InputSystemDX9::Type(L"InputSystemDX9", &InputSystem::Type);
InputSystemDX9::InputSystemDX9():
m_pDInput(NULL)
{
}
//----------------------------------------------------------------------
InputSystemDX9::~InputSystemDX9()
{
cleanup();
}
//----------------------------------------------------------------------
void InputSystemDX9::init()
{
// Create DirectInput interface
#ifdef _DEBUG
HINSTANCE hInstance = static_cast<HINSTANCE>(GetModuleHandle("nGENE_d"));
#else
HINSTANCE hInstance = static_cast<HINSTANCE>(GetModuleHandle("nGENE"));
#endif
if(FAILED(DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDInput, NULL)))
{
Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__,
L"Creating DirectInput8 failed");
return;
}
// Create enumerator
m_pInputEnumerator = new InputDeviceEnumerator();
}
//----------------------------------------------------------------------
void InputSystemDX9::cleanup()
{
NGENE_DELETE(m_pInputEnumerator);
NGENE_RELEASE(m_pDInput);
}
//----------------------------------------------------------------------
} | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
62
]
]
]
|
887e4d7a68e0f4e69757cc72131b008f98736a57 | 611fc0940b78862ca89de79a8bbeab991f5f471a | /src/Collision/CollisionShape.cpp | 75e63bda30e9f43da41409bf6d6d82361bb90c78 | []
| no_license | LakeIshikawa/splstage2 | df1d8f59319a4e8d9375b9d3379c3548bc520f44 | b4bf7caadf940773a977edd0de8edc610cd2f736 | refs/heads/master | 2021-01-10T21:16:45.430981 | 2010-01-29T08:57:34 | 2010-01-29T08:57:34 | 37,068,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 124 | cpp | #include ".\CollisionShape.h"
CollisionShape::CollisionShape(void)
{
}
CollisionShape::~CollisionShape(void)
{
}
| [
"lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b"
]
| [
[
[
1,
9
]
]
]
|
d7e9cb5d576f9cb134022a2f5a3343a27a053a83 | 460d5c0a45d3d377bfc4ce71de99f4abc517e2b6 | /Proj3/orderedCircularList.h | f25f6cd03091ac7f5485e325ae6ac8603b362077 | []
| no_license | wilmer/CS211 | 3ba910e9cc265ca7e3ecea2c71cf1246d430f269 | 1b0191c4ab7ebbe873fc5a09b9da2441a28d93d0 | refs/heads/master | 2020-12-25T09:38:34.633541 | 2011-03-06T04:53:54 | 2011-03-06T04:53:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,271 | h | #ifndef H_orderedCircularList
#define H_orderedCircularList
#include "circularList.h"
using namespace std;
template<class Type>
class orderedCircularList:public circularList<Type>
{
public:
orderedCircularList();
bool search(const Type& searchItem);
//Function to determine whether searchItem is in
//the list.
//Postcondition: Returns true if searchItem is found
// in the list; otherwise, it returns
// false.
void insertNode(const Type& newItem);
void deleteNode(const Type& deleteItem);
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing
// deleteItem is deleted from the
// list and count is decremented by 1.
};
template<class Type>
bool orderedCircularList<Type>::search(const Type& searchItem)
{
nodeType<Type> *current; //pointer to traverse the list
bool found;
found = false;
if(first != NULL)
{
current = first->link;
while(current != first && !found)
if(current->info >= searchItem)
found = true;
else
current = current->link;
if(found)
found = (current->info == searchItem);
}
return found;
}//end search
template<class Type>
void orderedCircularList<Type>::insertNode(const Type& newItem)
{
nodeType<Type> *current;
nodeType<Type> *beforeCurrent;
nodeType<Type> *newNode;
bool found;
newNode = new nodeType<Type>;
assert(newNode != NULL);
newNode->info = newItem;
newNode->link = NULL;
if(first == NULL)
{
first = newNode;
first->link = newNode;//?
count++;
}
else
{
if(newItem >= first->info)
{
newNode->link = first->link;
first->link = newNode;
first = newNode;
}
else
{
beforeCurrent = first;
current = first->link;
found = false;
while(current != first && !found)
if(current->info >= newItem)
found = true;
else
{
beforeCurrent = current;
current = current->link;
}
beforeCurrent->link = newNode;
newNode->link = current;
}
count++;
}
}
template<class Type>
void orderedCircularList<Type>::deleteNode(const Type& deleteItem)
{
nodeType<Type> *current;
nodeType<Type> *beforeCurrent;
bool found;
if(first == NULL)
cout << "Empty list.\n";
else
{
found = false;
beforeCurrent = first;
current = first->link;
while(current != first && !found)
if(current->info >= deleteItem)
found = true;
else
{
beforeCurrent = current;
current = current->link;
}
if(current == first)
{
if(first->info == deleteItem)
{
if(first == first->link)
first = NULL;
else
{
beforeCurrent->link = current->link;
first = beforeCurrent;
}
delete current;
count--;
}
else
cout << "The item is not in the list." << endl;
}
else
if(current->info == deleteItem)
{
beforeCurrent->link = current->link;
count--;
delete current;
}
else
cout << "Item is not in the list." << endl;
}
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
162
]
]
]
|
c9f93510b6a6c3ee1486dca2e0a862d0fc2d3889 | 9277f8b966db2bc75acaf12a75f620853be4ffa4 | /cpp/crbm_loirey_convert.cpp | b106d52f8a3ddecf6ca102aab18426cb43a6848f | []
| no_license | guochao1/apex-dbn | 3e6ad9de12564fc206ed08e563ecea1976edfff5 | d95a606a55ba80687e730b78bd4579f20d616eec | refs/heads/master | 2021-01-22T13:42:09.752260 | 2010-09-29T09:13:39 | 2010-09-29T09:13:39 | 40,700,204 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,153 | cpp | #define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#include "../utils/apex_utils.h"
#include "../tensor/apex_tensor.h"
#include "../crbm/apex_crbm_model.h"
int main( int argc, char *argv[] ){
if( argc < 4 ){
printf("Usage: <model in> <model out> <loirey in>\n");
return 0;
}
apex_rbm::CDBNModel model;
FILE *fi = apex_utils::fopen_check( argv[1] , "rb" );
model.load_from_file( fi );
fclose( fi );
fi = apex_utils::fopen_check( argv[3] , "r");
apex_rbm::CRBMModel &m = model.layers.back();
m.d_h_bias = 0.0f;
m.d_v_bias = 0.0f;
m.d_W = 0.0f;
fscanf(fi,"%*d%*d%f" , &m.v_bias[0] );
fscanf(fi,"%*d");
for( int i = 0 ; i < 40 ; i ++ )
fscanf(fi,"%f" , &m.h_bias[i] );
fscanf(fi,"%*d");
for( int i = 0 ; i < 40 ; i ++ )
for( int y = 0 ; y < m.W.y_max ; y ++ )
for( int x = 0 ; x < m.W.x_max ; x ++ )
fscanf(fi,"%f", &m.W[0][i][y][x] );
fclose( fi );
FILE *fo = apex_utils::fopen_check( argv[2] , "wb" );
model.save_to_file( fo );
fclose( fo );
return 0;
}
| [
"workcrow@b861ab8a-2dba-11df-8e64-fd3be38ee323"
]
| [
[
[
1,
43
]
]
]
|
5471aa03f8527690cb291ce0b1f2b8ad373915a4 | 0f40e36dc65b58cc3c04022cf215c77ae31965a8 | /src/apps/vis/tasks/vis_single_snapshot.h | 4b3b782e69ce5599b46556776e564360add7e78f | [
"MIT",
"BSD-3-Clause"
]
| permissive | venkatarajasekhar/shawn-1 | 08e6cd4cf9f39a8962c1514aa17b294565e849f8 | d36c90dd88f8460e89731c873bb71fb97da85e82 | refs/heads/master | 2020-06-26T18:19:01.247491 | 2010-10-26T17:40:48 | 2010-10-26T17:40:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,683 | h | /************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) **
** and SWARMS (www.swarms.de) **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the GNU General Public License, version 2. **
************************************************************************/
#ifndef __SHAWN_TUBSAPPS_VIS_TASK_SINGLE_SNAPSHOT_H
#define __SHAWN_TUBSAPPS_VIS_TASK_SINGLE_SNAPSHOT_H
#include "../buildfiles/_apps_enable_cmake.h"
#ifdef ENABLE_VIS
#include "apps/vis/base/vis_task.h"
namespace vis
{
/** \brief Creates a single output image.
*
* This task creates an output image. You can set the writer by using the
* 'writer' parameter (PDF default).
*
* @sa ExternalAnimationTask
*/
class SingleSnapshotTask
: public VisualizationTask
{
public:
///@name Constructor/Destructor
///@{
SingleSnapshotTask();
virtual ~SingleSnapshotTask();
///@}
///@name Getter
///@{
/**
* The name of the task.
*/
virtual std::string name( void ) const throw();
/**
* A short description of the task.
*/
virtual std::string description( void ) const throw();
///@}
/**
* Runs the task. This ist the task main method.
*/
virtual void run( shawn::SimulationController& sc )
throw( std::runtime_error );
};
}
#endif
#endif
| [
"[email protected]"
]
| [
[
[
1,
56
]
]
]
|
cf8b339ddbfb0dfe3de97940ad00775707dbed23 | 8a816dc2da5158e8d4f2081e6086575346869a16 | /CSMExporter/CrowdSimulationModel.cpp | d30ca968e99eadae8c53585c3798aabfcf7df499 | []
| no_license | yyzreal/3ds-max-exporter-plugin | ca43f9193afd471581075528b27d8a600fd2b7fa | 249f24c29dcfd6dd072c707f7642cf56cba06ef0 | refs/heads/master | 2020-04-10T14:50:13.717379 | 2011-06-12T15:10:54 | 2011-06-12T15:10:54 | 50,292,994 | 0 | 1 | null | 2016-01-24T15:07:28 | 2016-01-24T15:07:28 | null | GB18030 | C++ | false | false | 39,355 | cpp | #include "CrowdSimulationModel.h"
//////////////////////////////ExportManager//////////////////////////////////
ExportManager::ExportManager()
{
m_numAnimFrames = 0;
m_bSplitMode = FALSE;
}
ExportManager::~ExportManager()
{
for ( CSMList::iterator i = m_vpCSM.begin(); i != m_vpCSM.end(); i ++ )
{
SAFE_DELETE( *i );
}
}
/*! \param outFile[] 输出文件流
* \param fileName 文件名
* \param binary 是否是二进制格式写出
* \return 打开文件流失败返回FALSE
*/
BOOL ExportManager::BeginWriting( ofstream &outFile, const string &fileName, BOOL binary )
{
if ( binary == TRUE )
{
outFile.open( fileName.c_str(), ofstream::out | ofstream::trunc | ofstream::binary );
}
else
{
outFile.open( fileName.c_str(), ofstream::out | ofstream::trunc );
}
return outFile.fail() ? FALSE : TRUE;
}
/*! \param outFile[] 输出文件流 */
void ExportManager::EndWriting( ofstream &outFile )
{
if ( outFile )
{
outFile.close();
}
}
/*! \param pNode 场景中开始寻找的节点
* \param nodeName 寻找节点的名称
*/
INode * ExportManager::FindNodeByName( INode *pNode, string nodeName )
{
if ( nodeName == pNode->GetName() )
{
return pNode;
}
else
{
int numChildren = pNode->NumberOfChildren();
for ( int i = 0; i < numChildren; i++ )
{
INode *childNode = pNode->GetChildNode( i );
INode *resNode = NULL;
resNode = FindNodeByName( childNode, nodeName );
if ( resNode != NULL )
{
return resNode;
}
}
return NULL;
}
}
/*! \param pRootNode 3dmax场景的根节点
* \param bExportAnim 是否导出动画
* \param bTag 是否导出TAG
* \param headNode 头部节点名称
* \param upperNode 上半身节点名称
* \param lowerNode 下半身节点名称
* \param bProp 是否导出道具
* \param propNode 道具节点名称
* \param logFile 输出的日志文件名
*/
void ExportManager::Gather3DSMAXSceneData( INode *pRootNode,
BOOL bExportAnim,
BOOL bTag, string headNodeName, string upperNodeName, string lowerNodeName,
BOOL bProp, string propNodeName, string mountTo,
const string &logFile /* = */ )
{
#ifdef LOG
//! 设置输出log
m_ofLog.open( logFile.c_str(), ofstream::out | ofstream::trunc );
#endif
//! 搜集场景的帧信息
if ( bExportAnim == TRUE )
{
Interval ivAnimRange = GetCOREInterface()->GetAnimRange();
m_numAnimFrames = ( ivAnimRange.End() - ivAnimRange.Start() ) / GetTicksPerFrame() + 1;
}
else
{
// 没有动画则场景只有1帧
m_numAnimFrames = 1;
}
vector< string > suffix( NUM_PART_IDENTITY );
//! (根据模型拆分)搜集CSM所需数据
if ( bTag == TRUE )
{
m_bSplitMode = TRUE;
// 会导出多个CSM文件,*_lower.CSM, *_upper.CSM, *_head.CSM, *_property.CSM
// suffix是导出文件名需要添加的内容
suffix[LOWER] = "_lower";
suffix[UPPER] = "_upper";
suffix[HEAD] = "_head";
suffix[PROPERTY] = "_property";
for ( int id = LOWER; id <= HEAD; id ++ )
{
CSMInfo *csm = new CSMInfo( static_cast< PartIdentity >( id ) );
csm->strAppend = suffix[id];
m_vpCSM.push_back( csm );
}
// 找到场景中相应的节点
INode *pLowerNode = FindNodeByName( pRootNode, lowerNodeName );
INode *pUpperNode = FindNodeByName( pRootNode, upperNodeName );
INode *pHeadNode = FindNodeByName( pRootNode, headNodeName );
assert( pHeadNode != NULL && pUpperNode != NULL && pLowerNode != NULL );
vector< INode* > nodeList( 4 );
nodeList[LOWER] = pLowerNode;
nodeList[UPPER] = pUpperNode;
nodeList[HEAD] = pHeadNode;
// 将各节点对应到CSM文件
for ( int id = LOWER; id <= HEAD; id ++ )
{
m_vpCSM[id]->pNode = nodeList[id];
}
// 处理道具
INode *pPropNode = NULL;
if ( bProp == TRUE )
{
CSMInfo *csm = new CSMInfo( PROPERTY );
csm->strAppend = suffix[PROPERTY];
m_vpCSM.push_back( csm );
pPropNode = FindNodeByName( pRootNode, propNodeName );
assert( pPropNode != NULL );
nodeList.push_back( pPropNode );
m_vpCSM[PROPERTY]->pNode = nodeList[PROPERTY];
}
// 搜集这些特定节点的信息
GatherSpecifiedNodeData( m_vpCSM.begin(), m_vpCSM.end(), bExportAnim );
// 将Lower转换到世界空间
MaxTriObjData *pLowerObj = m_vpCSM[LOWER]->maxObjList[0];
UTILITY->TransformToWorld( pLowerObj, pLowerObj->worldMat );
// 搜集TAG信息
GenTag( pLowerNode, pUpperNode, m_vpCSM[LOWER], "Tag_Torso" );
GenTag( pUpperNode, pHeadNode, m_vpCSM[UPPER], "Tag_Head" );
if ( bProp == TRUE )
{
if ( mountTo == "Head" )
{
GenTag( pHeadNode, pPropNode, m_vpCSM[PROPERTY], "Tag_Property" );
}
else if ( mountTo == "Upper" )
{
GenTag( pUpperNode, pPropNode, m_vpCSM[PROPERTY], "Tag_Property" );
}
else if ( mountTo == "Lower" )
{
GenTag( pLowerNode, pPropNode, m_vpCSM[PROPERTY], "Tag_Property" );
}
else
{
// should never be here
assert( FALSE && "unknown mount type" );
}
}
}
else
{
m_bSplitMode = FALSE;
// 只导出一个CSM文件
suffix[ENTIRETY] = "";
CSMInfo *csm = new CSMInfo( ENTIRETY );
csm->strAppend = suffix[ENTIRETY];
m_vpCSM.push_back( csm );
// 搜集所有节点信息
GatherRecursiveNodeData( pRootNode, bExportAnim );
csm->maxObjList = m_vpMaxObjs;
// 所有Mesh转换到世界空间
for ( MaxTriObjList::iterator i = m_vpMaxObjs.begin(); i != m_vpMaxObjs.end(); i ++ )
{
MaxTriObjData *pMaxObj = *i;
UTILITY->TransformToWorld( pMaxObj, pMaxObj->worldMat );
}
}
//! 搜集动画数据
if ( bExportAnim == TRUE )
{
//! 生成骨骼树结构
GenBoneTree();
//! 搜集骨骼蒙皮信息
for ( SubMeshBoneList::iterator i = m_submeshBones.begin(); i != m_submeshBones.end(); i ++ )
{
MaxTriObjData *pMaxObjData = i->pMaxObjData;
ISkinContextData *pSkinContext = i->pSkinContext;
ISkin *pSkin = i->pSkin;
GatherSkinData( pSkinContext, pSkin, pMaxObjData );
}
//! 搜集骨骼动画信息
for ( BoneList::iterator i = m_boneList.begin(); i != m_boneList.end(); i ++ )
{
GatherBoneFrames( &( i->second ) );
}
}
//! 将Max数据转为CSM数据
for ( MaxTriObjList::iterator i = m_vpMaxObjs.begin(); i != m_vpMaxObjs.end(); i ++ )
{
MaxTriObjData *pTriData = *i;
UTILITY->MaxDataToCSMData( pTriData );
}
#ifdef LOG
m_ofLog.close();
#endif
}
/*! \param pNode 场景中的节点
* \param bExportAnim 是否导出动画
*/
void ExportManager::GatherRecursiveNodeData( INode *pNode, BOOL bExportAnim )
{
GatherNodeData( pNode, bExportAnim );
// 递归搜集场景树中的节点
int numChildren = pNode->NumberOfChildren();
for ( int i = 0; i < numChildren; i++ )
{
INode *childNode = pNode->GetChildNode( i );
GatherRecursiveNodeData( childNode, bExportAnim );
}
}
/*! \param pNode 场景中的节点
* \param beg Node列表的begin
* \param end Node列表的end
* \param bExportAnim 是否导出动画
*/
void ExportManager::GatherSpecifiedNodeData( CSMList::iterator beg, CSMList::iterator end, BOOL bExportAnim )
{
for ( CSMList::iterator i = beg; i != end; i ++ )
{
CSMInfo *csm = *i;
assert( GatherNodeData( csm->pNode, bExportAnim ) );
csm->maxObjList.push_back( m_vpMaxObjs.back() );
}
}
/*! \param pNode 场景中的节点
* \param bExportAnim 是否导出动画
* \return 如果该节点是本插件所需的节点,则返回TRUE,否则返回FALSE
*/
BOOL ExportManager::GatherNodeData( INode *pNode, BOOL bExportAnim )
{
// 获得BaseObject
ObjectState os = pNode->EvalWorldState( 0 );
Object *pObj = os.obj;
// 在本export插件中,只输出未隐藏的triObject
if ( pObj != NULL &&
FALSE == pNode->IsNodeHidden() &&
FALSE == IsBone( pNode ) && // 不是骨骼
pObj->CanConvertToType( triObjectClassID ) )
{
TriObject* pTriObj = static_cast< TriObject* >( pObj->ConvertToType( 0, triObjectClassID ) );
if ( pTriObj != NULL )
{
#ifdef LOG
m_ofLog << "=>搜集Node" << pNode->GetName() << endl;
#endif
MaxTriObjData *pMaxTriData = new MaxTriObjData();
memset( pMaxTriData, 0, sizeof( MaxTriObjData ) );
// 名称
pMaxTriData->objName = pNode->GetName();
// Mesh的世界矩阵
Matrix3 worldMat = pNode->GetNodeTM( 0 );
pMaxTriData->worldMat = UTILITY->TransformToDXMatrix( worldMat );
// 搜集Mesh数据
Mesh &lMesh = pTriObj->GetMesh();
GatherMeshData( lMesh, pMaxTriData );
// 搜集材质数据
Mtl* pMtl = pNode->GetMtl();
if ( pMtl != NULL )
{
GatherMaterialData( pMtl, pMaxTriData );
if ( pMaxTriData->numTextures > 0 )
{
for ( vector< MaxTriangleData >::iterator i = pMaxTriData->vTriangleData.begin(); i != pMaxTriData->vTriangleData.end(); i ++ )
{
int faceID = i - pMaxTriData->vTriangleData.begin();
// 获得该三角形面的Material ID
i->materialID = lMesh.getFaceMtlIndex( faceID ) % pMaxTriData->numTextures;
}
}
}
else
{
#ifdef LOG
m_ofLog << "\t=>没有材质" << endl;
#endif
// 添加一个空材质
string texName = "";
pMaxTriData->vTexNames.push_back( texName );
pMaxTriData->numTextures ++;
}
// 计算顶点法线(必须在搜集材质之后,因为法线分组与材质相关)
UTILITY->ComputeVertexNormalsOpt( pMaxTriData );
if ( bExportAnim == TRUE )
{
// 搜集骨骼动画
Modifier *pMf = GetSkinMode( pNode );
if ( pMf != NULL )
{
ISkin* pSkin = static_cast< ISkin* > ( pMf->GetInterface( I_SKIN ) );
ISkinContextData* pContext = pSkin->GetContextInterface( pNode );
// 先存储起来,待会再搜集该Node的骨骼蒙皮信息(这么做是要等待所有的骨骼索引被最终确定)
SubMeshBones pSubMeshBones;
pSubMeshBones.pMaxObjData = pMaxTriData;
pSubMeshBones.pSkinContext = pContext;
pSubMeshBones.pSkin = pSkin;
m_submeshBones.push_back( pSubMeshBones );
// 搜集骨骼
GatherBones( pSkin );
// 有动画
pMaxTriData->numAnimFrames = m_numAnimFrames;
}
else
{
#ifdef LOG
m_ofLog << "\t=>没有骨骼" << endl;
#endif
// 没有动画
pMaxTriData->numAnimFrames = 1;
}
}
m_vpMaxObjs.push_back( pMaxTriData );
if ( pTriObj != pObj )
{
pTriObj->DeleteMe();
}
}
return TRUE;
}
return FALSE;
}
/*! \param lMesh 3dmax网格
\param worldMat 网格的世界坐标
\param pMaxTriData 存储搜集到的网格数据
*/
void ExportManager::GatherMeshData( Mesh &lMesh, MaxTriObjData *pMaxTriData )
{
//! 搜集顶点信息
int nVerts = lMesh.getNumVerts();
pMaxTriData->vVertexData.clear();
for ( int i = 0; i < nVerts; i++ )
{
MaxVertexData vd;
Point3 &pts = lMesh.getVert( i );
/*! 3Dmax9是Z-up的右手坐标系,而DX是Y-up的左手坐标系,所以需要调整坐标(交换y坐标和z坐标) */
vd.position[0] = pts.x;
vd.position[1] = pts.z;
vd.position[2] = pts.y;
pMaxTriData->vVertexData.push_back( vd );
}
#ifdef LOG
m_ofLog << "\t=>搜集顶点" << nVerts << "个" << endl;
#endif
//! 搜集纹理坐标信息
int nTVerts = lMesh.getNumTVerts();
pMaxTriData->vTexCoordData.clear();
for ( int i = 0; i < nTVerts; i++ )
{
MaxTexCoordData tcd;
UVVert &lTVert = lMesh.getTVert( i );
/*! 3dmax的u,v坐标系是这样 \n
(0,1) ----- (1,1) \n
| | \n
| | \n
(0,0) ----- (1,0) \n
而dx的u,v坐标系是这样 \n
(0,0) ----- (1,0) \n
| | \n
| | \n
(0,1) ----- (1,1) \n
所以,需要调整v坐标 */
tcd.u = lTVert.x;
tcd.v = 1 - lTVert.y;
pMaxTriData->vTexCoordData.push_back( tcd );
}
#ifdef LOG
m_ofLog << "\t=>搜集纹理坐标" << nTVerts << "个" << endl;
#endif
//! 建立法线信息
lMesh.buildNormals();
//! 搜集三角形面信息
int nTris = lMesh.getNumFaces();
#ifdef LOG
m_ofLog << "\t=>搜集三角形面" << nTris << "个" << endl;
#endif
for ( int i = 0; i < nTris; i++ )
{
MaxTriangleData td;
//! 顶点坐标索引
if ( nVerts > 0 )
{
Face& lFace = lMesh.faces[i];
DWORD* pVIndices = lFace.getAllVerts();
/*! 3Dmax9中三角形是逆时针,而DX是顺时针,所以需要调换顺序 */
td.vertexIndices[0] = pVIndices[0];
td.vertexIndices[1] = pVIndices[2];
td.vertexIndices[2] = pVIndices[1];
}
else
{
#ifdef LOG
m_ofLog << "\t\t=>搜集顶点索引失败" << endl;
#endif
}
//! 纹理坐标索引
if ( nTVerts > 0 )
{
TVFace& lTVFace = lMesh.tvFace[i];
DWORD* pUVIndices = lTVFace.getAllTVerts();
/*! 3Dmax9中三角形是逆时针,而DX是顺时针,所以需要调换顺序 */
td.texCoordIndices[0] = pUVIndices[0];
td.texCoordIndices[1] = pUVIndices[2];
td.texCoordIndices[2] = pUVIndices[1];
}
else
{
#ifdef LOG
m_ofLog << "\t\t=>搜集纹理索引失败" << endl;
#endif
}
//! 法线
Point3& nvtx = Normalize( lMesh.getFaceNormal( i ) );
/*! 3Dmax9是Z-up的右手坐标系,而DX是Y-up的左手坐标系,所以需要调整坐标(交换y坐标和z坐标) */
td.normal[0] = nvtx.x;
td.normal[1] = nvtx.z;
td.normal[2] = nvtx.y;
//! Smoothing Group
td.smoothGroup = lMesh.faces[i].smGroup;
pMaxTriData->vTriangleData.push_back( td );
}
}
/*! \param pMtl 3dmax材质
\param pSubMesh 存储搜集到的网格数据
*/
void ExportManager::GatherMaterialData( Mtl *pMtl, MaxTriObjData *pMaxTriData )
{
if ( pMtl == NULL )
{
return;
}
//! 检测是否是一个标准的Material
if ( pMtl->ClassID() == Class_ID( DMTL_CLASS_ID, 0 ) )
{
StdMat *pStdMtl = ( StdMat * )pMtl;
BOOL bTwoSided = pStdMtl->GetTwoSided();
Texmap *pTex = pMtl->GetSubTexmap( ID_DI );
//! 如果材质是一个图像文件,则
if ( pTex != NULL && pTex->ClassID() == Class_ID( BMTEX_CLASS_ID, 0 ) )
{
BitmapTex* pBmpTex = static_cast< BitmapTex* >( pTex );
string texName = TruncatePath( pBmpTex->GetMapName() );
//! 存储纹理名称
pMaxTriData->vTexNames.push_back( texName );
pMaxTriData->numTextures ++;
#ifdef LOG
m_ofLog << "\t=>获取纹理材质" << texName << endl;
StdUVGen *uv = pBmpTex->GetUVGen();
float utile = uv->GetUScl( 0 );
float vtile = uv->GetVScl( 0 );
m_ofLog << "\t\tuTile=" << utile << ", vTile=" << vtile << endl;
#endif
}
else //! 材质不是一个图像文件,留空
{
string texName = "";
pMaxTriData->vTexNames.push_back( texName );
pMaxTriData->numTextures ++;
}
}
for ( int i = 0; i < pMtl->NumSubMtls(); i ++ )
{
Mtl *pSubMtl = pMtl->GetSubMtl( i );
GatherMaterialData( pSubMtl, pMaxTriData );
}
}
/*! \param pTagedNode 提供TAG信息的节点
* \param pNode 节点绑定到pTagedNode的节点。\n
比如,pTagedNode是一个Lower,提供一个叫Torso的TAG,pNode是一个Upper,它绑定到Torso
* \param pCSM 存储Tag信息的CSM,它的identity必须不是ENTIRETY,且pCSM中存储的Node应该与pTagedNode相一致
* \param tagName 该TAG的名称
*/
void ExportManager::GenTag( INode *pTagedNode, INode *pNode, CSMInfo *pCSM, string tagName )
{
if ( pCSM->identity == ENTIRETY || pCSM->pNode != pTagedNode )
{
return;
}
CSMTagData tag;
strcpy( tag.name, tagName.c_str() );
tag.numAnimFrames = m_numAnimFrames;
for ( int i = 0; i < tag.numAnimFrames; i ++ )
{
TimeValue t = GetTicksPerFrame() * i;
Matrix3 matA = pTagedNode->GetNodeTM( t );
Matrix3 matB = pNode->GetNodeTM( t );
Matrix3 mountMat = matB * Inverse( matA );
tag.vFrameData.push_back( UTILITY->TransformToDXMatrix( mountMat ) );
}
pCSM->vpTags.push_back( tag );
#ifdef LOG
m_ofLog << "\t=>获取TAG--" << tagName << ", 帧数为" << m_numAnimFrames << endl;
#endif
}
/*! \param pNode 3dmax场景节点
\return 包含蒙皮信息的Modifier
*/
Modifier* ExportManager::GetSkinMode( INode *pNode )
{
Object* pObj = pNode->GetObjectRef();
if( !pObj )
{
return NULL;
}
while( pObj->SuperClassID() == GEN_DERIVOB_CLASS_ID )
{
IDerivedObject *pDerivedObj = dynamic_cast< IDerivedObject* >( pObj );
int modStackIndex = 0;
while( modStackIndex < pDerivedObj->NumModifiers() )
{
Modifier* mod = pDerivedObj->GetModifier( modStackIndex );
if( mod->ClassID() == SKIN_CLASSID )
{
return mod;
}
modStackIndex++;
}
pObj = pDerivedObj->GetObjRef();
}
return NULL;
}
void ExportManager::GenBoneTree()
{
vector< INode* > freshBoneNodes; // 存储需要新加入到BoneList中的骨骼节点
//! 寻找到所有的骨骼
for ( BoneList::iterator i = m_boneList.begin(); i != m_boneList.end(); i ++ )
{
INode *boneNode = i->second.pBoneNode;
INode *parentNode = boneNode->GetParentNode();
if ( FALSE == parentNode->IsRootNode() && parentNode != NULL )
{
string parentBoneName = parentNode->GetName();
BoneList::iterator k = m_boneList.find( parentBoneName );
if ( k == m_boneList.end() ) // 该父骨骼节点不在模型的蒙皮骨骼列表中
{
// 加入到待搜索列表中
freshBoneNodes.push_back( parentNode );
}
}
}
//! 加入所有新找到的骨骼到骨骼列表
for ( vector< INode* >::iterator i = freshBoneNodes.begin(); i != freshBoneNodes.end(); i ++ )
{
INode *pBoneNode = *i;
while ( TRUE )
{
string boneName = pBoneNode->GetName();
BoneList::iterator k = m_boneList.find( boneName );
if ( k == m_boneList.end() )
{
Bone newBone;
newBone.pBoneNode = pBoneNode;
m_boneList.insert( BoneList::value_type( boneName, newBone ) );
pBoneNode = pBoneNode->GetParentNode();
if ( TRUE == pBoneNode->IsRootNode() || pBoneNode == NULL )
{
break;
}
}
else
{
break;
}
}
}
//! 生成骨骼索引
int realIndex = 0;
for ( BoneList::iterator i = m_boneList.begin(); i != m_boneList.end(); i ++, realIndex ++ )
{
i->second.index = realIndex;
}
//! 建立骨骼的父子关系
for ( BoneList::iterator i = m_boneList.begin(); i != m_boneList.end(); i ++ )
{
INode *boneNode = i->second.pBoneNode;
INode *parentBoneNode = boneNode->GetParentNode();
if ( FALSE == parentBoneNode->IsRootNode() && parentBoneNode != NULL )
{
string parentBoneName = parentBoneNode->GetName();
BoneList::iterator k = m_boneList.find( parentBoneName );
assert( k != m_boneList.end() );
i->second.pParentBone = &( k->second );
}
}
//! 建立与父骨骼的相对矩阵
for ( BoneList::iterator i = m_boneList.begin(); i != m_boneList.end(); i ++ )
{
i->second.relativeMat = GetRelativeBoneMatrix( &( i->second ) );
#ifdef DEBUG
Matrix3 relMat = i->second.relativeMat;
FilterData( relMat );
m_ofLog << "\t" << i->first << "的相对矩阵:" << endl;
m_ofLog << "\t\t" << relMat.GetRow( 0 ).x << " " << relMat.GetRow( 0 ).y << " " << relMat.GetRow( 0 ).z << endl;
m_ofLog << "\t\t" << relMat.GetRow( 1 ).x << " " << relMat.GetRow( 1 ).y << " " << relMat.GetRow( 1 ).z << endl;
m_ofLog << "\t\t" << relMat.GetRow( 2 ).x << " " << relMat.GetRow( 2 ).y << " " << relMat.GetRow( 2 ).z << endl;
m_ofLog << "\t\t" << relMat.GetRow( 3 ).x << " " << relMat.GetRow( 3 ).y << " " << relMat.GetRow( 3 ).z << endl;
#endif
}
//! 建立所有骨骼相对于父骨骼的动画帧
for ( BoneList::iterator i = m_boneList.begin(); i != m_boneList.end(); i ++ )
{
#ifdef LOG
m_ofLog << "\t骨骼" << i->first << ": " << endl;
#endif
for ( int j = 0; j < m_numAnimFrames; j ++ )
{
//! 第j帧的时刻time
int time = j * GetTicksPerFrame();
Matrix3 relTraMatT = GetLocalBoneTranMatrix( &( i->second ), time );
i->second.localFrames.push_back( relTraMatT );
#ifdef DEBUG
FilterData( relTraMatT );
m_ofLog << "\tFrame" << j << ": " << endl;
m_ofLog << "\t\t" << relTraMatT.GetRow( 0 ).x << " " << relTraMatT.GetRow( 0 ).y << " " << relTraMatT.GetRow( 0 ).z << endl;
m_ofLog << "\t\t" << relTraMatT.GetRow( 1 ).x << " " << relTraMatT.GetRow( 1 ).y << " " << relTraMatT.GetRow( 1 ).z << endl;
m_ofLog << "\t\t" << relTraMatT.GetRow( 2 ).x << " " << relTraMatT.GetRow( 2 ).y << " " << relTraMatT.GetRow( 2 ).z << endl;
m_ofLog << "\t\t" << relTraMatT.GetRow( 3 ).x << " " << relTraMatT.GetRow( 3 ).y << " " << relTraMatT.GetRow( 3 ).z << endl;
#endif
}
}
}
/*! 这个函数很诡异,对于Bone都返回FALSE,对于Biped,footstep返回FALSE,其余的Biped则返回TRUE
\param pNode 3dmax场景节点
\return 判断结果
*/
BOOL ExportManager::IsBone( INode *pNode )
{
if( pNode == NULL )
{
return FALSE;
}
ObjectState os = pNode->EvalWorldState( 0 );
if ( !os.obj )
{
return FALSE;
}
//! 检测是否是Bone
if( os.obj->ClassID() == Class_ID( BONE_CLASS_ID, 0 ) )
{
return TRUE;
}
//! dummy节点也算为骨骼
if( os.obj->ClassID() == Class_ID( DUMMY_CLASS_ID, 0 ) )
{
return TRUE;
}
//! 检测是否是Biped
Control *cont = pNode->GetTMController();
if( cont->ClassID() == BIPSLAVE_CONTROL_CLASS_ID || //others biped parts
cont->ClassID() == BIPBODY_CONTROL_CLASS_ID ) //biped root "Bip01"
{
return TRUE;
}
return FALSE;
}
/*! \param pContext 3dmax蒙皮信息
\param pSkin 与mesh所相关联的骨骼息
\param pSubMesh 存储搜集到的网格数据
*/
void ExportManager::GatherSkinData( ISkinContextData* pContext, ISkin *pSkin, MaxTriObjData *pMaxTriData )
{
//! 将存储在单个Sub Mesh中的Bone索引对应到“搜集完场景中所有的Bone”之后的索引
map< int, int > oriToRealMap;
int iBoneCnt = pSkin->GetNumBones();
for ( int oriIndex = 0; oriIndex < iBoneCnt; oriIndex ++ )
{
string boneName = pSkin->GetBone( oriIndex )->GetName();
//! 寻找到真正的索引并存储到映射表
BoneList::iterator iter = m_boneList.find( boneName );
int realIndex = iter->second.index;
if ( iter != m_boneList.end() )
{
oriToRealMap.insert( map<int, int>::value_type( oriIndex, realIndex ) );
}
else
{
throw std::runtime_error( "Couldn't find bone!" );
}
}
//! 更新索引,并存储蒙皮信息
int numVtx = pContext->GetNumPoints();
for ( int iVtx = 0; iVtx < numVtx; iVtx++ )
{
int num = pContext->GetNumAssignedBones( iVtx );
assert( num <= 4 &&
"本插件最多一个顶点只能绑定4个骨骼,你超过了,现在将失败退出" );
for ( int iVBone = 0; iVBone < num; iVBone++ )
{
int oriBoneIdx = pContext->GetAssignedBone( iVtx, iVBone );
float weight = pContext->GetBoneWeight( iVtx, iVBone );
int realBoneIdx = oriToRealMap.find( oriBoneIdx )->second;
pMaxTriData->vVertexData[iVtx].bones[iVBone] = realBoneIdx;
pMaxTriData->vVertexData[iVtx].boneWeights[iVBone] = UTILITY->FilterData( weight );
}
}
}
/*! \param pSkin 包含与mesh所相关联的骨骼列表 */
void ExportManager::GatherBones( ISkin *pSkin )
{
int iBoneCnt = pSkin->GetNumBones();
#ifdef LOG
m_ofLog << "\t=>获取骨骼" << iBoneCnt << "个" << endl;
#endif
for ( int i = 0; i < iBoneCnt; i ++ )
{
Bone bone;
bone.pBoneNode = pSkin->GetBone( i );
string boneName = bone.pBoneNode->GetName();
m_boneList.insert( BoneList::value_type( boneName, bone ) );
}
}
/*! \param pBone 骨骼 */
void ExportManager::GatherBoneFrames( Bone *pBone )
{
INode *pBoneNode = pBone->pBoneNode;
#ifdef LOG
m_ofLog << "=>获取骨骼" << pBoneNode->GetName() << "动画" << endl;
#endif
// 获得节点的transform control
Control *c = pBoneNode->GetTMController();
//! 测试是否是一个biped controller(关于代码的解释请参见3dmax SDK Document)
if ( ( c->ClassID() == BIPSLAVE_CONTROL_CLASS_ID ) ||
( c->ClassID() == BIPBODY_CONTROL_CLASS_ID ) ||
( c->ClassID() == FOOTPRINT_CLASS_ID ) )
{
//! Get the Biped Export Interface from the controller
IBipedExport *BipIface = ( IBipedExport * ) c->GetInterface( I_BIPINTERFACE );
//! Remove the non uniform scale
BipIface->RemoveNonUniformScale( TRUE );
//! Release the interface when you are done with it
c->ReleaseInterface( I_BIPINTERFACE, BipIface );
}
vector< Bone* > tempList;
//! 遍历骨骼的父节点,直到根节点,加入到列表
Bone *pRootBone = pBone;
tempList.push_back( pRootBone );
while ( pRootBone->pParentBone != NULL )
{
pRootBone = pRootBone->pParentBone;
tempList.push_back( pRootBone );
}
//! baseMat是将Vworld转为Vlocal
Matrix3 baseMat;
baseMat.IdentityMatrix();
//! 从根节点遍历,直到当前节点
for ( vector< Bone* >::reverse_iterator riter = tempList.rbegin(); riter != tempList.rend(); riter ++ )
{
Bone *pB = *riter;
baseMat = baseMat * Inverse( pB->relativeMat );
}
#ifdef DEBUG
FilterData( baseMat );
m_ofLog << "\t" << "Base矩阵:" << endl;
m_ofLog << "\t\t" << baseMat.GetRow( 0 ).x << " " << baseMat.GetRow( 0 ).y << " " << baseMat.GetRow( 0 ).z << endl;
m_ofLog << "\t\t" << baseMat.GetRow( 1 ).x << " " << baseMat.GetRow( 1 ).y << " " << baseMat.GetRow( 1 ).z << endl;
m_ofLog << "\t\t" << baseMat.GetRow( 2 ).x << " " << baseMat.GetRow( 2 ).y << " " << baseMat.GetRow( 2 ).z << endl;
m_ofLog << "\t\t" << baseMat.GetRow( 3 ).x << " " << baseMat.GetRow( 3 ).y << " " << baseMat.GetRow( 3 ).z << endl;
#endif
//! 逐帧搜集
for ( int i = 0; i < m_numAnimFrames; i ++ )
{
Matrix3 frame = baseMat;
//! 第i帧的时刻time
int time = i * GetTicksPerFrame();
//! 从当前节点开始,向父节点遍历,直到根节点停止
for ( vector< Bone* >::iterator iter = tempList.begin(); iter != tempList.end(); iter ++ )
{
Bone *pB = *iter;
//! 乘以第i帧的子骨骼相对于本地坐标系的变换
frame = frame * pB->localFrames[i];
//! 变换至父坐标系
frame = frame * pB->relativeMat;
}
//! 至此获得了时刻time的关键帧矩阵
pBone->boneFrames.push_back( frame );
#ifdef DEBUG
FilterData( frame );
m_ofLog << "\tFrame" << i << ": " << endl;
m_ofLog << "\t\t" << frame.GetRow( 0 ).x << " " << frame.GetRow( 0 ).y << " " << frame.GetRow( 0 ).z << endl;
m_ofLog << "\t\t" << frame.GetRow( 1 ).x << " " << frame.GetRow( 1 ).y << " " << frame.GetRow( 1 ).z << endl;
m_ofLog << "\t\t" << frame.GetRow( 2 ).x << " " << frame.GetRow( 2 ).y << " " << frame.GetRow( 2 ).z << endl;
m_ofLog << "\t\t" << frame.GetRow( 3 ).x << " " << frame.GetRow( 3 ).y << " " << frame.GetRow( 3 ).z << endl;
#endif
}
#ifdef LOG
m_ofLog << "\t=>获取动画" << m_numAnimFrames << "帧" << endl;
#endif
}
/*! \param numAnimFrames 动画帧数 */
void ExportManager::GenCSMHeaderInfo( int numAnimFrames )
{
for ( CSMList::iterator i = m_vpCSM.begin(); i != m_vpCSM.end(); i ++ )
{
CSMInfo *csm = *i;
CSMHeader *pHeader = &( csm->header );
memset( pHeader, 0, sizeof( CSMHeader ) );
pHeader->ident = CSM_MAGIC_NUMBER;
pHeader->numTags = static_cast< int >( csm->vpTags.size() );
pHeader->numBones = static_cast< int >( m_boneList.size() );
pHeader->numAnimFrames = numAnimFrames;
pHeader->numSubMesh = 0;
for ( MaxTriObjList::iterator j = csm->maxObjList.begin(); j != csm->maxObjList.end(); j ++ )
{
MaxTriObjData *pMaxObj = *j;
int numSubMesh = static_cast< int >( pMaxObj->vSubMeshes.size() );
pHeader->numSubMesh += numSubMesh;
}
pHeader->nHeaderSize = sizeof( CSMHeader );
pHeader->nOffBones = pHeader->nHeaderSize;
for ( TagList::iterator j = csm->vpTags.begin(); j != csm->vpTags.end(); j ++ )
{
CSMTagData pTag = *j;
pHeader->nOffBones += sizeof( MAX_STRING_LENGTH );
pHeader->nOffBones += sizeof( int );
pHeader->nOffBones += sizeof( D3DXMATRIX ) * pTag.numAnimFrames;
}
pHeader->nOffSubMesh = pHeader->nOffBones + sizeof( CSMBoneData ) * pHeader->numBones;
pHeader->nFileSize = pHeader->nOffSubMesh;
for ( MaxTriObjList::iterator j = csm->maxObjList.begin(); j != csm->maxObjList.end(); j ++ )
{
MaxTriObjData *pMaxObj = *j;
for ( SubMeshList::iterator k = pMaxObj->vSubMeshes.begin(); k != pMaxObj->vSubMeshes.end(); k ++ )
{
CSMSubMesh *pSubMesh = *k;
pHeader->nFileSize += pSubMesh->subMeshHeader.nOffEnd;
}
}
}
}
/*! \param fileName 输出文件名
\return 打开文件失败,返回FALSE
*/
BOOL ExportManager::WriteAllCSMFile( const string &fileName )
{
size_t token = fileName.find_last_of( "CSM" );
string strFore = fileName.substr( 0, token - 3 );
for ( CSMList::iterator i = m_vpCSM.begin(); i != m_vpCSM.end(); i ++ )
{
CSMInfo *csm = *i;
string strAppend = csm->strAppend + ".CSM";
csm->strCSMFile = strFore + strAppend;
if ( WriteCSMFile( csm ) == FALSE )
{
return FALSE;
}
}
if ( TRUE == m_bSplitMode && m_vpCSM.size() > 1 )
{
WriteCSM_PACFile( fileName );
}
return TRUE;
}
/*! \param pCSM 需要输出的CSM信息
* \return 打开文件失败,返回FALSE
*/
BOOL ExportManager::WriteCSMFile( CSMInfo *pCSM )
{
string fileName = pCSM->strCSMFile;
size_t token = fileName.find_last_of( '\\' );
string path = fileName.substr( 0, token );
ofstream &ofFileCSM = pCSM->ofCSMFile;
CSMHeader *pHeader = &( pCSM->header );
if ( BeginWriting( ofFileCSM, fileName, TRUE ) )
{
//! 统计CSM信息,填充CSM的Header
GenCSMHeaderInfo( m_numAnimFrames );
//! 将Header写入文件
ofFileCSM.write( reinterpret_cast< char* >( pHeader ), sizeof( CSMHeader ) );
int offset = pHeader->nHeaderSize;
//! 将Tag Data写入文件
for ( TagList::iterator i =pCSM->vpTags.begin(); i != pCSM->vpTags.end(); i ++ )
{
CSMTagData pTag = *i;
ofFileCSM.seekp( offset, ofstream::beg );
ofFileCSM.write( reinterpret_cast< char* >( pTag.name ), MAX_STRING_LENGTH );
offset += MAX_STRING_LENGTH;
ofFileCSM.seekp( offset, ofstream::beg );
ofFileCSM.write( reinterpret_cast< char* >( &pTag.numAnimFrames ), sizeof( int ) );
offset += sizeof( int );
for ( int j = 0; j < pTag.numAnimFrames; j ++ )
{
D3DXMATRIX mtx = pTag.vFrameData[j];
ofFileCSM.seekp( offset, ofstream::beg );
ofFileCSM.write( reinterpret_cast< char* >( &mtx ), sizeof( MATRIX ) );
offset += sizeof( MATRIX );
}
}
//! 将Bones写入文件
int n = 0;
for ( BoneList::iterator i = m_boneList.begin(); i != m_boneList.end(); i++, n++ )
{
CSMBoneData CSMBone;
string boneName = i->first;
strcpy( CSMBone.name, boneName.c_str() );
CSMBone.ID = i->second.index;
if ( i->second.pParentBone != NULL )
{
CSMBone.parentID = i->second.pParentBone->index;
}
else
{
CSMBone.parentID = -1;
}
CSMBone.relativeMat = UTILITY->TransformToDXMatrix( i->second.relativeMat );
ofFileCSM.seekp( pHeader->nOffBones + n * sizeof( CSMBone ), ofstream::beg );
ofFileCSM.write( reinterpret_cast< const char* >( &CSMBone ), sizeof( CSMBone ) );
}
//! 将Sub Mesh写入文件
int lastOffSet = pHeader->nOffSubMesh;
for ( MaxTriObjList::iterator i = pCSM->maxObjList.begin(); i != pCSM->maxObjList.end(); i ++ )
{
MaxTriObjData *pMaxObj = *i;
for ( SubMeshList::iterator j = pMaxObj->vSubMeshes.begin(); j != pMaxObj->vSubMeshes.end(); j ++ )
{
CSMSubMesh *pSubMesh = *j;
//! 写入Sub Mesh Header
ofFileCSM.seekp( lastOffSet, ofstream::beg );
ofFileCSM.write( reinterpret_cast< char* >( &pSubMesh->subMeshHeader ), pSubMesh->subMeshHeader.nHeaderSize );
//! 写入Texture File
string oldTexFile = pSubMesh->textureFile;
string texName;
if ( oldTexFile != "" )
{
//! 将texture文件拷贝到目录下
token = oldTexFile.find_last_of( '\\' );
texName = oldTexFile.substr( token + 1 );
string newTexFile = path + "\\" + texName;
CopyFile( pSubMesh->textureFile, newTexFile.c_str(), FALSE );
}
char texFile[ MAX_STRING_LENGTH ];
strcpy( texFile, texName.c_str() );
ofFileCSM.seekp( lastOffSet + pSubMesh->subMeshHeader.nHeaderSize, ofstream::beg );
ofFileCSM.write( reinterpret_cast< char* >( texFile ), MAX_STRING_LENGTH );
//! 写入Vertex Data
for ( int k = 0; k < pSubMesh->subMeshHeader.numVertices; k ++ )
{
CSMVertexData *pVertex = &pSubMesh->vVertexData[k];
#ifdef FILTER
UTILITY->FilterData( *pVertex );
#endif
ofFileCSM.seekp( lastOffSet + pSubMesh->subMeshHeader.nOffVertices + k * sizeof( CSMVertexData ), ofstream::beg );
ofFileCSM.write( reinterpret_cast< char* >( pVertex ), sizeof( CSMVertexData ) );
}
//! 写入Skin Data
int numSkinData;
if ( pSubMesh->subMeshHeader.numAnimFrames > 1 )
{
numSkinData = pSubMesh->subMeshHeader.numVertices;
}
else
{
numSkinData = 0;
}
for ( int k = 0; k < numSkinData; k ++ )
{
CSMSkinData *pSkinData = &pSubMesh->vSkinData[k];
#ifdef FILTER
UTILITY->FilterData( *pSkinData );
#endif
ofFileCSM.seekp( lastOffSet + pSubMesh->subMeshHeader.nOffSkin + k * sizeof( CSMSkinData ), ofstream::beg );
ofFileCSM.write( reinterpret_cast< char* >( pSkinData ), sizeof( CSMSkinData ) );
}
//! 写入Triangle Data
for ( int k = 0; k < pSubMesh->subMeshHeader.numFaces; k ++ )
{
CSMTriangleData *pTriData = &pSubMesh->vTriangleData[k];
ofFileCSM.seekp( lastOffSet + pSubMesh->subMeshHeader.nOffFaces + k * sizeof( CSMTriangleData ), ofstream::beg );
ofFileCSM.write( reinterpret_cast< char* >( pTriData ), sizeof( CSMTriangleData ) );
}
lastOffSet = lastOffSet + pSubMesh->subMeshHeader.nOffEnd;
}
}
EndWriting( ofFileCSM );
return TRUE;
}
return FALSE;
}
/*! \param fileName 输出文件名
\return 打开文件失败,返回FALSE
*/
BOOL ExportManager::WriteAMFile( const string &fileName )
{
//! 先写入动画配置文件
if ( FALSE == WriteCFGFile( fileName ) )
{
return FALSE;
}
size_t token = fileName.find_last_of( ".CSM" );
string animFile = fileName.substr( 0, token - 3 ) + ".AM";
if ( BeginWriting( m_ofFileAM, animFile, TRUE ) )
{
//! 逐骨骼写入
for ( BoneList::iterator i = m_boneList.begin(); i != m_boneList.end(); i ++ )
{
Bone bone = i->second;
int boneSeek = bone.index * m_numAnimFrames * sizeof( MATRIX );
//! 逐帧写入
for ( BoneFrames::iterator j = bone.boneFrames.begin(); j != bone.boneFrames.end(); j++ )
{
MATRIX m = UTILITY->TransformToDXMatrix( *j );
#ifdef FILTER
UTILITY->FilterData( m );
#endif
int frameIndex = j - bone.boneFrames.begin();
int frameSeek = boneSeek + frameIndex * sizeof( MATRIX );
m_ofFileAM.seekp( frameSeek, ofstream::beg );
m_ofFileAM.write( reinterpret_cast< char* >( &m ), sizeof( MATRIX ) );
}
}
EndWriting( m_ofFileAM );
return TRUE;
}
return FALSE;
}
/*! \param fileName 输出文件名
\return 打开文件失败,返回FALSE
*/
BOOL ExportManager::WriteCFGFile( const string& fileName )
{
size_t token = fileName.find_last_of( ".CSM" );
string cfgFile = fileName.substr( 0, token - 3 ) + ".CFG";
if ( BeginWriting( m_ofFileCFG, cfgFile, FALSE ) )
{
//! 输出场景的动画帧数
m_ofFileCFG << "SceneFrame: " << m_numAnimFrames << endl;
//! 骨骼数
m_ofFileCFG << "NumberOfBone: " << m_boneList.size() << endl;
//! 输出动画个数
m_ofFileCFG << "NumberOfAnimation: " << m_animList.size() << endl;
//! 逐动画输出动画信息
for ( AnimList::iterator i = m_animList.begin(); i != m_animList.end(); i ++ )
{
m_ofFileCFG << i->animName << "\t"
<< i->firstFrame << "\t"
<< i->numFrames << "\t"
<< i->numLoops << "\t"
<< i->fps << endl;
}
EndWriting( m_ofFileCFG );
return TRUE;
}
return FALSE;
}
BOOL ExportManager::WriteCSM_PACFile( const string &fileName )
{
size_t token = fileName.find_last_of( ".CSM" );
string pacFile = fileName.substr( 0, token - 3 ) + ".CSM_PAC";
if ( BeginWriting( m_ofFileCSM_PAC, pacFile, FALSE ) )
{
//! 输出总共的CSM数量
int num = static_cast< int >( m_vpCSM.size() );
m_ofFileCSM_PAC << num << endl;
vector< string > vID( 4 );
vID[ LOWER ] = "lower";
vID[ UPPER ] = "upper";
vID[ HEAD ] = "head";
vID[ PROPERTY ] = "property";
//! 逐个输出所有的CSM信息
for ( CSMList::iterator i = m_vpCSM.begin(); i != m_vpCSM.end(); i ++ )
{
CSMInfo *csm = *i;
assert( csm->identity < ENTIRETY &&
"导出单个CSM不应该导出csm_pac文件" );
string id = vID[ csm->identity ];
string csmFile = csm->strCSMFile;
token = csmFile.find_last_of( "\\" );
if ( token != string::npos )
{
csmFile = csmFile.substr( token + 1 );
}
m_ofFileCSM_PAC << id << "\t" << csmFile << endl;
}
return TRUE;
}
return FALSE;
}
/*! \param pNode 3dmax场景节点
\param t 时间点
\return 骨骼矩阵
*/
Matrix3 ExportManager::GetBoneTM( INode *pNode, TimeValue t )
{
Matrix3 tm = pNode->GetNodeTM( t );
tm.NoScale();
return tm;
}
/*! \param pNode 3dmax场景中的节点
\param t 时间
\return 在时刻t节点相对于其父节点的矩阵
*/
Matrix3 ExportManager::GetRelativeMatrix( INode *pNode, TimeValue t /* = 0 */ )
{
Matrix3 worldMat = pNode->GetNodeTM( t );
Matrix3 parentMat = pNode->GetParentTM( t );
//! 因为NodeWorldTM = NodeLocalTM * ParentWorldTM(注意:3dmax9中的矩阵是右乘)\n
//! 所以NodeLocalTM = NodeWorldTM * Inverse( ParentWorldTM )
Matrix3 relativeMat = worldMat * Inverse( parentMat );
return relativeMat;
}
/*! 根骨骼的节点可能在场景中还有父节点(比如Scene Root)
\param pBone 骨骼
\param t 时间
\return 在时刻t骨骼相对于其父骨骼的矩阵
*/
Matrix3 ExportManager::GetRelativeBoneMatrix( Bone *pBone, TimeValue t /* = 0 */ )
{
if ( pBone->pParentBone == NULL )
{
Matrix3 worldMat = pBone->pBoneNode->GetNodeTM( t );
return worldMat;
}
else
{
return GetRelativeMatrix( pBone->pBoneNode, t );
}
}
/*! \param pBone 3dmax场景中的节点
\param t 时间
\return 骨骼在时刻t在本地空间内的变换
*/
Matrix3 ExportManager::GetLocalBoneTranMatrix( Bone *pBone, TimeValue t )
{
Matrix3 relMatT0 = GetRelativeBoneMatrix( pBone, 0 );
Matrix3 relMatTN = GetRelativeBoneMatrix( pBone, t );
//! 因为relMatT = transformMatT * relMat0
//! 所以transformMatT = relMatT * Inverse( relMat0 )
Matrix3 transformMatT = relMatTN * Inverse( relMatT0 );
return transformMatT;
} | [
"[email protected]@4008efc8-90d6-34c1-d252-cb7169c873e6"
]
| [
[
[
1,
1319
]
]
]
|
9e915522e6d86f8feda87a7e510203223f8e2a14 | 94c1c7459eb5b2826e81ad2750019939f334afc8 | /source/CTaiKlineExportExecel.h | dd71cbe8d3603deb45d8a92596f3b3722fcbc9ab | []
| no_license | wgwang/yinhustock | 1c57275b4bca093e344a430eeef59386e7439d15 | 382ed2c324a0a657ddef269ebfcd84634bd03c3a | refs/heads/master | 2021-01-15T17:07:15.833611 | 2010-11-27T07:06:40 | 2010-11-27T07:06:40 | 37,531,026 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,387 | h | //{{AFX_INCLUDES()
#include "msflexgrid.h"
//}}AFX_INCLUDES
#if !defined(AFX_TECHEXPORTEXECEL_H__C54E43A2_67B1_11D4_970B_0080C8D6450E__INCLUDED_)
#define AFX_TECHEXPORTEXECEL_H__C54E43A2_67B1_11D4_970B_0080C8D6450E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// CTaiKlineExportExecel.h : header file
class CTaiShanKlineShowView;
class CTaiKlineExportExecel : public CDialog
{
public:
CTaiKlineExportExecel(CWnd* pParent = NULL); // standard constructor
CTaiShanKlineShowView* pView;
int m_nFiguer;
// Dialog Data
//{{AFX_DATA(CTaiKlineExportExecel)
enum { IDD = IDD_OUT_DATA };
CButtonST m_ok;
CButtonST m_cancel;
BOOL m_bShowExcel;
CMSFlexGrid m_gridDataOut;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTaiKlineExportExecel)
protected:
virtual void DoDataExchange(CDataExchange* pDX);
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CTaiKlineExportExecel)
virtual BOOL OnInitDialog();
afx_msg void OnExport();
afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_TECHEXPORTEXECEL_H__C54E43A2_67B1_11D4_970B_0080C8D6450E__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
53
]
]
]
|
2eb96d8c08eafedce292455e15cbf239c91f2b81 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/crypto++/5.2.1/randpool.cpp | e83a9dcf43383a47db300b8c4a2911c27b7b013c | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-cryptopp"
]
| 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,108 | cpp | // randpool.cpp - written and placed in the public domain by Wei Dai
// The algorithm in this module comes from PGP's randpool.c
#include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "randpool.h"
#include "mdc.h"
#include "sha.h"
#include "modes.h"
NAMESPACE_BEGIN(CryptoPP)
typedef MDC<SHA> RandomPoolCipher;
RandomPool::RandomPool(unsigned int poolSize)
: pool(poolSize), key(RandomPoolCipher::DEFAULT_KEYLENGTH)
{
assert(poolSize > key.size());
addPos=0;
getPos=poolSize;
memset(pool, 0, poolSize);
memset(key, 0, key.size());
}
void RandomPool::Stir()
{
CFB_Mode<RandomPoolCipher>::Encryption cipher;
for (int i=0; i<2; i++)
{
cipher.SetKeyWithIV(key, key.size(), pool.end()-cipher.IVSize());
cipher.ProcessString(pool, pool.size());
memcpy(key, pool, key.size());
}
addPos = 0;
getPos = key.size();
}
unsigned int RandomPool::Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking)
{
unsigned t;
while (length > (t = pool.size() - addPos))
{
xorbuf(pool+addPos, inString, t);
inString += t;
length -= t;
Stir();
}
if (length)
{
xorbuf(pool+addPos, inString, length);
addPos += length;
getPos = pool.size(); // Force stir on get
}
return 0;
}
unsigned int RandomPool::TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel, bool blocking)
{
if (!blocking)
throw NotImplemented("RandomPool: nonblocking transfer is not implemented by this object");
unsigned int t;
unsigned long size = transferBytes;
while (size > (t = pool.size() - getPos))
{
target.ChannelPut(channel, pool+getPos, t);
size -= t;
Stir();
}
if (size)
{
target.ChannelPut(channel, pool+getPos, size);
getPos += size;
}
return 0;
}
byte RandomPool::GenerateByte()
{
if (getPos == pool.size())
Stir();
return pool[getPos++];
}
void RandomPool::GenerateBlock(byte *outString, unsigned int size)
{
ArraySink sink(outString, size);
TransferTo(sink, size);
}
NAMESPACE_END
#endif
| [
"[email protected]"
]
| [
[
[
1,
105
]
]
]
|
8420c5031210a1d656e87cd0480401748c1a6786 | 3e90c3ae1f36cddff1735575c92ea25c7f285b0a | /gsdx/GSState.cpp | 12439b8880c3a0155f68da5a5904e41431d09355 | []
| no_license | PCSX2/gsdx-sourceforge | 59625dc5af8e9f9e5116dff6126473b7739a258e | 1f509adde00c266505673d4197b3769d5360654f | refs/heads/master | 2021-04-10T01:46:21.360559 | 2009-01-31T01:16:24 | 2009-01-31T01:16:24 | 248,901,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 53,237 | cpp | /*
* Copyright (C) 2007-2009 Gabest
* http://www.gabest.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "stdafx.h"
#include "GSState.h"
GSState::GSState(BYTE* base, bool mt, void (*irq)(), int nloophack)
: m_mt(mt)
, m_irq(irq)
, m_nloophack_org(nloophack)
, m_nloophack(nloophack == 1)
, m_crc(0)
, m_options(0)
, m_path3hack(0)
, m_q(1.0f)
, m_vprim(1)
, m_version(5)
, m_frameskip(0)
, m_vkf(NULL)
{
m_sssize = 0;
m_sssize += sizeof(m_version);
m_sssize += sizeof(m_env.PRIM);
m_sssize += sizeof(m_env.PRMODE);
m_sssize += sizeof(m_env.PRMODECONT);
m_sssize += sizeof(m_env.TEXCLUT);
m_sssize += sizeof(m_env.SCANMSK);
m_sssize += sizeof(m_env.TEXA);
m_sssize += sizeof(m_env.FOGCOL);
m_sssize += sizeof(m_env.DIMX);
m_sssize += sizeof(m_env.DTHE);
m_sssize += sizeof(m_env.COLCLAMP);
m_sssize += sizeof(m_env.PABE);
m_sssize += sizeof(m_env.BITBLTBUF);
m_sssize += sizeof(m_env.TRXDIR);
m_sssize += sizeof(m_env.TRXPOS);
m_sssize += sizeof(m_env.TRXREG);
m_sssize += sizeof(m_env.TRXREG2);
for(int i = 0; i < 2; i++)
{
m_sssize += sizeof(m_env.CTXT[i].XYOFFSET);
m_sssize += sizeof(m_env.CTXT[i].TEX0);
m_sssize += sizeof(m_env.CTXT[i].TEX1);
m_sssize += sizeof(m_env.CTXT[i].TEX2);
m_sssize += sizeof(m_env.CTXT[i].CLAMP);
m_sssize += sizeof(m_env.CTXT[i].MIPTBP1);
m_sssize += sizeof(m_env.CTXT[i].MIPTBP2);
m_sssize += sizeof(m_env.CTXT[i].SCISSOR);
m_sssize += sizeof(m_env.CTXT[i].ALPHA);
m_sssize += sizeof(m_env.CTXT[i].TEST);
m_sssize += sizeof(m_env.CTXT[i].FBA);
m_sssize += sizeof(m_env.CTXT[i].FRAME);
m_sssize += sizeof(m_env.CTXT[i].ZBUF);
}
m_sssize += sizeof(m_v.RGBAQ);
m_sssize += sizeof(m_v.ST);
m_sssize += sizeof(m_v.UV);
m_sssize += sizeof(m_v.XYZ);
m_sssize += sizeof(m_v.FOG);
m_sssize += sizeof(m_x);
m_sssize += sizeof(m_y);
m_sssize += m_mem.m_vmsize;
m_sssize += (sizeof(m_path[0].tag) + sizeof(m_path[0].nreg)) * 3;
m_sssize += sizeof(m_q);
ASSERT(base);
PMODE = (GSRegPMODE*)(base + GS_PMODE);
SMODE1 = (GSRegSMODE1*)(base + GS_SMODE1);
SMODE2 = (GSRegSMODE2*)(base + GS_SMODE2);
// SRFSH = (GSRegPMODE*)(base + GS_SRFSH);
// SYNCH1 = (GSRegPMODE*)(base + GS_SYNCH1);
// SYNCH2 = (GSRegPMODE*)(base + GS_SYNCH2);
// SYNCV = (GSRegPMODE*)(base + GS_SYNCV);
DISPFB[0] = (GSRegDISPFB*)(base + GS_DISPFB1);
DISPFB[1] = (GSRegDISPFB*)(base + GS_DISPFB2);
DISPLAY[0] = (GSRegDISPLAY*)(base + GS_DISPLAY1);
DISPLAY[1] = (GSRegDISPLAY*)(base + GS_DISPLAY2);
EXTBUF = (GSRegEXTBUF*)(base + GS_EXTBUF);
EXTDATA = (GSRegEXTDATA*)(base + GS_EXTDATA);
EXTWRITE = (GSRegEXTWRITE*)(base + GS_EXTWRITE);
BGCOLOR = (GSRegBGCOLOR*)(base + GS_BGCOLOR);
CSR = (GSRegCSR*)(base + GS_CSR);
IMR = (GSRegIMR*)(base + GS_IMR);
BUSDIR = (GSRegBUSDIR*)(base + GS_BUSDIR);
SIGLBLID = (GSRegSIGLBLID*)(base + GS_SIGLBLID);
PRIM = &m_env.PRIM;
// CSR->rREV = 0x20;
m_env.PRMODECONT.AC = 1;
m_x = m_y = 0;
m_bytes = 0;
m_maxbytes = 1024 * 1024 * 4;
m_buff = (BYTE*)_aligned_malloc(m_maxbytes, 16);
Reset();
ResetHandlers();
}
GSState::~GSState()
{
_aligned_free(m_buff);
}
void GSState::Reset()
{
memset(&m_path[0], 0, sizeof(m_path[0]) * 3);
memset(&m_v, 0, sizeof(m_v));
// PRIM = &m_env.PRIM;
// m_env.PRMODECONT.AC = 1;
m_env.Reset();
m_context = &m_env.CTXT[0];
InvalidateTextureCache();
}
void GSState::ResetHandlers()
{
for(int i = 0; i < countof(m_fpGIFPackedRegHandlers); i++)
{
m_fpGIFPackedRegHandlers[i] = &GSState::GIFPackedRegHandlerNull;
}
m_fpGIFPackedRegHandlers[GIF_REG_PRIM] = &GSState::GIFPackedRegHandlerPRIM;
m_fpGIFPackedRegHandlers[GIF_REG_RGBA] = &GSState::GIFPackedRegHandlerRGBA;
m_fpGIFPackedRegHandlers[GIF_REG_STQ] = &GSState::GIFPackedRegHandlerSTQ;
m_fpGIFPackedRegHandlers[GIF_REG_UV] = &GSState::GIFPackedRegHandlerUV;
m_fpGIFPackedRegHandlers[GIF_REG_XYZF2] = &GSState::GIFPackedRegHandlerXYZF2;
m_fpGIFPackedRegHandlers[GIF_REG_XYZ2] = &GSState::GIFPackedRegHandlerXYZ2;
m_fpGIFPackedRegHandlers[GIF_REG_TEX0_1] = &GSState::GIFPackedRegHandlerTEX0<0>;
m_fpGIFPackedRegHandlers[GIF_REG_TEX0_2] = &GSState::GIFPackedRegHandlerTEX0<1>;
m_fpGIFPackedRegHandlers[GIF_REG_CLAMP_1] = &GSState::GIFPackedRegHandlerCLAMP<0>;
m_fpGIFPackedRegHandlers[GIF_REG_CLAMP_2] = &GSState::GIFPackedRegHandlerCLAMP<1>;
m_fpGIFPackedRegHandlers[GIF_REG_FOG] = &GSState::GIFPackedRegHandlerFOG;
m_fpGIFPackedRegHandlers[GIF_REG_XYZF3] = &GSState::GIFPackedRegHandlerXYZF3;
m_fpGIFPackedRegHandlers[GIF_REG_XYZ3] = &GSState::GIFPackedRegHandlerXYZ3;
m_fpGIFPackedRegHandlers[GIF_REG_A_D] = &GSState::GIFPackedRegHandlerA_D;
m_fpGIFPackedRegHandlers[GIF_REG_NOP] = &GSState::GIFPackedRegHandlerNOP;
for(int i = 0; i < countof(m_fpGIFRegHandlers); i++)
{
m_fpGIFRegHandlers[i] = &GSState::GIFRegHandlerNull;
}
m_fpGIFRegHandlers[GIF_A_D_REG_PRIM] = &GSState::GIFRegHandlerPRIM;
m_fpGIFRegHandlers[GIF_A_D_REG_RGBAQ] = &GSState::GIFRegHandlerRGBAQ;
m_fpGIFRegHandlers[GIF_A_D_REG_ST] = &GSState::GIFRegHandlerST;
m_fpGIFRegHandlers[GIF_A_D_REG_UV] = &GSState::GIFRegHandlerUV;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZF2] = &GSState::GIFRegHandlerXYZF2;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZ2] = &GSState::GIFRegHandlerXYZ2;
m_fpGIFRegHandlers[GIF_A_D_REG_TEX0_1] = &GSState::GIFRegHandlerTEX0<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_TEX0_2] = &GSState::GIFRegHandlerTEX0<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_CLAMP_1] = &GSState::GIFRegHandlerCLAMP<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_CLAMP_2] = &GSState::GIFRegHandlerCLAMP<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_FOG] = &GSState::GIFRegHandlerFOG;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZF3] = &GSState::GIFRegHandlerXYZF3;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZ3] = &GSState::GIFRegHandlerXYZ3;
m_fpGIFRegHandlers[GIF_A_D_REG_NOP] = &GSState::GIFRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_TEX1_1] = &GSState::GIFRegHandlerTEX1<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_TEX1_2] = &GSState::GIFRegHandlerTEX1<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_TEX2_1] = &GSState::GIFRegHandlerTEX2<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_TEX2_2] = &GSState::GIFRegHandlerTEX2<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_XYOFFSET_1] = &GSState::GIFRegHandlerXYOFFSET<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_XYOFFSET_2] = &GSState::GIFRegHandlerXYOFFSET<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_PRMODECONT] = &GSState::GIFRegHandlerPRMODECONT;
m_fpGIFRegHandlers[GIF_A_D_REG_PRMODE] = &GSState::GIFRegHandlerPRMODE;
m_fpGIFRegHandlers[GIF_A_D_REG_TEXCLUT] = &GSState::GIFRegHandlerTEXCLUT;
m_fpGIFRegHandlers[GIF_A_D_REG_SCANMSK] = &GSState::GIFRegHandlerSCANMSK;
m_fpGIFRegHandlers[GIF_A_D_REG_MIPTBP1_1] = &GSState::GIFRegHandlerMIPTBP1<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_MIPTBP1_2] = &GSState::GIFRegHandlerMIPTBP1<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_MIPTBP2_1] = &GSState::GIFRegHandlerMIPTBP2<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_MIPTBP2_2] = &GSState::GIFRegHandlerMIPTBP2<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_TEXA] = &GSState::GIFRegHandlerTEXA;
m_fpGIFRegHandlers[GIF_A_D_REG_FOGCOL] = &GSState::GIFRegHandlerFOGCOL;
m_fpGIFRegHandlers[GIF_A_D_REG_TEXFLUSH] = &GSState::GIFRegHandlerTEXFLUSH;
m_fpGIFRegHandlers[GIF_A_D_REG_SCISSOR_1] = &GSState::GIFRegHandlerSCISSOR<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_SCISSOR_2] = &GSState::GIFRegHandlerSCISSOR<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_ALPHA_1] = &GSState::GIFRegHandlerALPHA<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_ALPHA_2] = &GSState::GIFRegHandlerALPHA<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_DIMX] = &GSState::GIFRegHandlerDIMX;
m_fpGIFRegHandlers[GIF_A_D_REG_DTHE] = &GSState::GIFRegHandlerDTHE;
m_fpGIFRegHandlers[GIF_A_D_REG_COLCLAMP] = &GSState::GIFRegHandlerCOLCLAMP;
m_fpGIFRegHandlers[GIF_A_D_REG_TEST_1] = &GSState::GIFRegHandlerTEST<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_TEST_2] = &GSState::GIFRegHandlerTEST<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_PABE] = &GSState::GIFRegHandlerPABE;
m_fpGIFRegHandlers[GIF_A_D_REG_FBA_1] = &GSState::GIFRegHandlerFBA<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_FBA_2] = &GSState::GIFRegHandlerFBA<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_FRAME_1] = &GSState::GIFRegHandlerFRAME<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_FRAME_2] = &GSState::GIFRegHandlerFRAME<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_ZBUF_1] = &GSState::GIFRegHandlerZBUF<0>;
m_fpGIFRegHandlers[GIF_A_D_REG_ZBUF_2] = &GSState::GIFRegHandlerZBUF<1>;
m_fpGIFRegHandlers[GIF_A_D_REG_BITBLTBUF] = &GSState::GIFRegHandlerBITBLTBUF;
m_fpGIFRegHandlers[GIF_A_D_REG_TRXPOS] = &GSState::GIFRegHandlerTRXPOS;
m_fpGIFRegHandlers[GIF_A_D_REG_TRXREG] = &GSState::GIFRegHandlerTRXREG;
m_fpGIFRegHandlers[GIF_A_D_REG_TRXDIR] = &GSState::GIFRegHandlerTRXDIR;
m_fpGIFRegHandlers[GIF_A_D_REG_HWREG] = &GSState::GIFRegHandlerHWREG;
m_fpGIFRegHandlers[GIF_A_D_REG_SIGNAL] = &GSState::GIFRegHandlerSIGNAL;
m_fpGIFRegHandlers[GIF_A_D_REG_FINISH] = &GSState::GIFRegHandlerFINISH;
m_fpGIFRegHandlers[GIF_A_D_REG_LABEL] = &GSState::GIFRegHandlerLABEL;
}
CPoint GSState::GetDisplayPos(int i)
{
ASSERT(i >= 0 && i < 2);
CPoint p;
p.x = DISPLAY[i]->DX / (DISPLAY[i]->MAGH + 1);
p.y = DISPLAY[i]->DY / (DISPLAY[i]->MAGV + 1);
return p;
}
CSize GSState::GetDisplaySize(int i)
{
ASSERT(i >= 0 && i < 2);
CSize s;
s.cx = (DISPLAY[i]->DW + 1) / (DISPLAY[i]->MAGH + 1);
s.cy = (DISPLAY[i]->DH + 1) / (DISPLAY[i]->MAGV + 1);
return s;
}
CRect GSState::GetDisplayRect(int i)
{
return CRect(GetDisplayPos(i), GetDisplaySize(i));
}
CSize GSState::GetDisplayPos()
{
return GetDisplayPos(IsEnabled(1) ? 1 : 0);
}
CSize GSState::GetDisplaySize()
{
return GetDisplaySize(IsEnabled(1) ? 1 : 0);
}
CRect GSState::GetDisplayRect()
{
return GetDisplayRect(IsEnabled(1) ? 1 : 0);
}
CPoint GSState::GetFramePos(int i)
{
ASSERT(i >= 0 && i < 2);
return CPoint(DISPFB[i]->DBX, DISPFB[i]->DBY);
}
CSize GSState::GetFrameSize(int i)
{
CSize s = GetDisplaySize(i);
if(SMODE2->INT && SMODE2->FFMD && s.cy > 1) s.cy >>= 1;
return s;
}
CRect GSState::GetFrameRect(int i)
{
return CRect(GetFramePos(i), GetFrameSize(i));
}
CSize GSState::GetFramePos()
{
return GetFramePos(IsEnabled(1) ? 1 : 0);
}
CSize GSState::GetFrameSize()
{
return GetFrameSize(IsEnabled(1) ? 1 : 0);
}
CRect GSState::GetFrameRect()
{
return GetFrameRect(IsEnabled(1) ? 1 : 0);
}
CSize GSState::GetDeviceSize(int i)
{
// TODO: other params of SMODE1 should affect the true device display size
// TODO2: pal games at 60Hz
CSize s = GetDisplaySize(i);
if(s.cy == 2*416 || s.cy == 2*448 || s.cy == 2*512)
{
s.cy /= 2;
}
else
{
s.cy = (SMODE1->CMOD & 1) ? 512 : 448;
}
return s;
}
CSize GSState::GetDeviceSize()
{
return GetDeviceSize(IsEnabled(1) ? 1 : 0);
}
bool GSState::IsEnabled(int i)
{
ASSERT(i >= 0 && i < 2);
if(i == 0 && PMODE->EN1)
{
return DISPLAY[0]->DW || DISPLAY[0]->DH;
}
else if(i == 1 && PMODE->EN2)
{
return DISPLAY[1]->DW || DISPLAY[1]->DH;
}
return false;
}
int GSState::GetFPS()
{
return ((SMODE1->CMOD & 1) ? 50 : 60) / (SMODE2->INT ? 1 : 2);
}
// GIFPackedRegHandler*
void GSState::GIFPackedRegHandlerNull(GIFPackedReg* r)
{
// ASSERT(0);
}
void GSState::GIFPackedRegHandlerPRIM(GIFPackedReg* r)
{
// ASSERT(r->r.PRIM.PRIM < 7);
GIFRegHandlerPRIM(&r->r);
}
void GSState::GIFPackedRegHandlerRGBA(GIFPackedReg* r)
{
#if _M_SSE >= 0x301
GSVector4i mask = GSVector4i::load(0x0c080400);
GSVector4i v = GSVector4i::load<false>(r).shuffle8(mask);
m_v.RGBAQ.ai32[0] = (UINT32)GSVector4i::store(v);
#elif _M_SSE >= 0x200
GSVector4i v = GSVector4i::load<false>(r) & GSVector4i::x000000ff();
m_v.RGBAQ.ai32[0] = v.rgba32();
#else
m_v.RGBAQ.R = r->RGBA.R;
m_v.RGBAQ.G = r->RGBA.G;
m_v.RGBAQ.B = r->RGBA.B;
m_v.RGBAQ.A = r->RGBA.A;
#endif
m_v.RGBAQ.Q = m_q;
}
void GSState::GIFPackedRegHandlerSTQ(GIFPackedReg* r)
{
#if defined(_M_AMD64)
m_v.ST.i64 = r->ai64[0];
#elif _M_SSE >= 0x200
GSVector4i v = GSVector4i::loadl(r);
GSVector4i::storel(&m_v.ST.i64, v);
#else
m_v.ST.S = r->STQ.S;
m_v.ST.T = r->STQ.T;
#endif
m_q = r->STQ.Q;
}
void GSState::GIFPackedRegHandlerUV(GIFPackedReg* r)
{
#if _M_SSE >= 0x200
GSVector4i v = GSVector4i::loadl(r) & GSVector4i::x00003fff();
m_v.UV.ai32[0] = (UINT32)GSVector4i::store(v.ps32(v));
#else
m_v.UV.U = r->UV.U;
m_v.UV.V = r->UV.V;
#endif
}
void GSState::GIFPackedRegHandlerXYZF2(GIFPackedReg* r)
{
m_v.XYZ.X = r->XYZF2.X;
m_v.XYZ.Y = r->XYZF2.Y;
m_v.XYZ.Z = r->XYZF2.Z;
m_v.FOG.F = r->XYZF2.F;
VertexKick(r->XYZF2.ADC);
}
void GSState::GIFPackedRegHandlerXYZ2(GIFPackedReg* r)
{
m_v.XYZ.X = r->XYZ2.X;
m_v.XYZ.Y = r->XYZ2.Y;
m_v.XYZ.Z = r->XYZ2.Z;
VertexKick(r->XYZ2.ADC);
}
template<int i> void GSState::GIFPackedRegHandlerTEX0(GIFPackedReg* r)
{
GIFRegHandlerTEX0<i>((GIFReg*)&r->ai64[0]);
}
template<int i> void GSState::GIFPackedRegHandlerCLAMP(GIFPackedReg* r)
{
GIFRegHandlerCLAMP<i>((GIFReg*)&r->ai64[0]);
}
void GSState::GIFPackedRegHandlerFOG(GIFPackedReg* r)
{
m_v.FOG.F = r->FOG.F;
}
void GSState::GIFPackedRegHandlerXYZF3(GIFPackedReg* r)
{
GIFRegHandlerXYZF3((GIFReg*)&r->ai64[0]);
}
void GSState::GIFPackedRegHandlerXYZ3(GIFPackedReg* r)
{
GIFRegHandlerXYZ3((GIFReg*)&r->ai64[0]);
}
void GSState::GIFPackedRegHandlerA_D(GIFPackedReg* r)
{
(this->*m_fpGIFRegHandlers[(BYTE)r->A_D.ADDR])(&r->r);
}
void GSState::GIFPackedRegHandlerA_D(GIFPackedReg* r, int size)
{
for(int i = 0; i < size; i++)
{
(this->*m_fpGIFRegHandlers[(BYTE)r[i].A_D.ADDR])(&r[i].r);
}
}
void GSState::GIFPackedRegHandlerNOP(GIFPackedReg* r)
{
}
// GIFRegHandler*
void GSState::GIFRegHandlerNull(GIFReg* r)
{
// ASSERT(0);
}
void GSState::GIFRegHandlerPRIM(GIFReg* r)
{
// ASSERT(r->PRIM.PRIM < 7);
if(GSUtil::GetPrimClass(m_env.PRIM.PRIM) == GSUtil::GetPrimClass(r->PRIM.PRIM))
{
if(((m_env.PRIM.i64 ^ r->PRIM.i64) & ~7) != 0)
{
Flush();
}
}
else
{
Flush();
}
m_env.PRIM = (GSVector4i)r->PRIM;
m_env.PRMODE._PRIM = r->PRIM.PRIM;
m_context = &m_env.CTXT[PRIM->CTXT];
UpdateVertexKick();
ResetPrim();
}
void GSState::GIFRegHandlerRGBAQ(GIFReg* r)
{
m_v.RGBAQ = (GSVector4i)r->RGBAQ;
}
void GSState::GIFRegHandlerST(GIFReg* r)
{
m_v.ST = (GSVector4i)r->ST;
}
void GSState::GIFRegHandlerUV(GIFReg* r)
{
m_v.UV.ai32[0] = r->UV.ai32[0] & 0x3fff3fff;
}
void GSState::GIFRegHandlerXYZF2(GIFReg* r)
{
/*
m_v.XYZ.X = r->XYZF.X;
m_v.XYZ.Y = r->XYZF.Y;
m_v.XYZ.Z = r->XYZF.Z;
m_v.FOG.F = r->XYZF.F;
*/
m_v.XYZ.ai32[0] = r->XYZF.ai32[0];
m_v.XYZ.ai32[1] = r->XYZF.ai32[1] & 0x00ffffff;
m_v.FOG.ai32[1] = r->XYZF.ai32[1] & 0xff000000;
VertexKick(false);
}
void GSState::GIFRegHandlerXYZ2(GIFReg* r)
{
m_v.XYZ = (GSVector4i)r->XYZ;
VertexKick(false);
}
template<int i> void GSState::GIFRegHandlerTEX0(GIFReg* r)
{
// even if TEX0 did not change, a new palette may have been uploaded and will overwrite the currently queued for drawing
bool wt = m_mem.m_clut.WriteTest(r->TEX0, m_env.TEXCLUT);
if(wt || PRIM->CTXT == i && !(m_env.CTXT[i].TEX0 == (GSVector4i)r->TEX0).alltrue())
{
Flush();
}
m_env.CTXT[i].TEX0 = (GSVector4i)r->TEX0;
if(m_env.CTXT[i].TEX0.TW > 10) m_env.CTXT[i].TEX0.TW = 10;
if(m_env.CTXT[i].TEX0.TH > 10) m_env.CTXT[i].TEX0.TH = 10;
m_env.CTXT[i].TEX0.CPSM &= 0xa; // 1010b
if((m_env.CTXT[i].TEX0.TBW & 1) && (m_env.CTXT[i].TEX0.PSM == PSM_PSMT8 || m_env.CTXT[i].TEX0.PSM == PSM_PSMT4))
{
m_env.CTXT[i].TEX0.TBW &= ~1; // GS User 2.6
}
if(wt)
{
m_mem.m_clut.Write(m_env.CTXT[i].TEX0, m_env.TEXCLUT);
}
}
template<int i> void GSState::GIFRegHandlerCLAMP(GIFReg* r)
{
if(PRIM->CTXT == i && !(m_env.CTXT[i].CLAMP == (GSVector4i)r->CLAMP).alltrue())
{
Flush();
}
m_env.CTXT[i].CLAMP = (GSVector4i)r->CLAMP;
}
void GSState::GIFRegHandlerFOG(GIFReg* r)
{
m_v.FOG = (GSVector4i)r->FOG;
}
void GSState::GIFRegHandlerXYZF3(GIFReg* r)
{
/*
m_v.XYZ.X = r->XYZF.X;
m_v.XYZ.Y = r->XYZF.Y;
m_v.XYZ.Z = r->XYZF.Z;
m_v.FOG.F = r->XYZF.F;
*/
m_v.XYZ.ai32[0] = r->XYZF.ai32[0];
m_v.XYZ.ai32[1] = r->XYZF.ai32[1] & 0x00ffffff;
m_v.FOG.ai32[1] = r->XYZF.ai32[1] & 0xff000000;
VertexKick(true);
}
void GSState::GIFRegHandlerXYZ3(GIFReg* r)
{
m_v.XYZ = (GSVector4i)r->XYZ;
VertexKick(true);
}
void GSState::GIFRegHandlerNOP(GIFReg* r)
{
}
template<int i> void GSState::GIFRegHandlerTEX1(GIFReg* r)
{
if(PRIM->CTXT == i && !(m_env.CTXT[i].TEX1 == (GSVector4i)r->TEX1).alltrue())
{
Flush();
}
m_env.CTXT[i].TEX1 = (GSVector4i)r->TEX1;
}
template<int i> void GSState::GIFRegHandlerTEX2(GIFReg* r)
{
// m_env.CTXT[i].TEX2 = r->TEX2; // not used
UINT64 mask = 0xFFFFFFE003F00000ui64; // TEX2 bits
r->i64 = (r->i64 & mask) | (m_env.CTXT[i].TEX0.i64 & ~mask);
GIFRegHandlerTEX0<i>(r);
}
template<int i> void GSState::GIFRegHandlerXYOFFSET(GIFReg* r)
{
GSVector4i o = (GSVector4i)r->XYOFFSET & GSVector4i::x0000ffff();
if(!(m_env.CTXT[i].XYOFFSET == o).alltrue())
{
Flush();
}
m_env.CTXT[i].XYOFFSET = o;
m_env.CTXT[i].UpdateScissor();
}
void GSState::GIFRegHandlerPRMODECONT(GIFReg* r)
{
if(!(m_env.PRMODECONT == (GSVector4i)r->PRMODECONT).alltrue())
{
Flush();
}
m_env.PRMODECONT.AC = r->PRMODECONT.AC;
PRIM = m_env.PRMODECONT.AC ? &m_env.PRIM : (GIFRegPRIM*)&m_env.PRMODE;
if(PRIM->PRIM == 7) TRACE(_T("Invalid PRMODECONT/PRIM\n"));
m_context = &m_env.CTXT[PRIM->CTXT];
UpdateVertexKick();
}
void GSState::GIFRegHandlerPRMODE(GIFReg* r)
{
if(!m_env.PRMODECONT.AC)
{
Flush();
}
UINT32 _PRIM = m_env.PRMODE._PRIM;
m_env.PRMODE = (GSVector4i)r->PRMODE;
m_env.PRMODE._PRIM = _PRIM;
m_context = &m_env.CTXT[PRIM->CTXT];
UpdateVertexKick();
}
void GSState::GIFRegHandlerTEXCLUT(GIFReg* r)
{
if(!(m_env.TEXCLUT == (GSVector4i)r->TEXCLUT).alltrue())
{
Flush();
}
m_env.TEXCLUT = (GSVector4i)r->TEXCLUT;
}
void GSState::GIFRegHandlerSCANMSK(GIFReg* r)
{
if(!(m_env.SCANMSK == (GSVector4i)r->SCANMSK).alltrue())
{
Flush();
}
m_env.SCANMSK = (GSVector4i)r->SCANMSK;
}
template<int i> void GSState::GIFRegHandlerMIPTBP1(GIFReg* r)
{
if(PRIM->CTXT == i && !(m_env.CTXT[i].MIPTBP1 == (GSVector4i)r->MIPTBP1).alltrue())
{
Flush();
}
m_env.CTXT[i].MIPTBP1 = (GSVector4i)r->MIPTBP1;
}
template<int i> void GSState::GIFRegHandlerMIPTBP2(GIFReg* r)
{
if(PRIM->CTXT == i && !(m_env.CTXT[i].MIPTBP2 == (GSVector4i)r->MIPTBP2).alltrue())
{
Flush();
}
m_env.CTXT[i].MIPTBP2 = (GSVector4i)r->MIPTBP2;
}
void GSState::GIFRegHandlerTEXA(GIFReg* r)
{
if(!(m_env.TEXA == (GSVector4i)r->TEXA).alltrue())
{
Flush();
}
m_env.TEXA = (GSVector4i)r->TEXA;
}
void GSState::GIFRegHandlerFOGCOL(GIFReg* r)
{
if(!(m_env.FOGCOL == (GSVector4i)r->FOGCOL).alltrue())
{
Flush();
}
m_env.FOGCOL = (GSVector4i)r->FOGCOL;
}
void GSState::GIFRegHandlerTEXFLUSH(GIFReg* r)
{
// TRACE(_T("TEXFLUSH\n"));
// InvalidateTextureCache();
}
template<int i> void GSState::GIFRegHandlerSCISSOR(GIFReg* r)
{
if(PRIM->CTXT == i && !(m_env.CTXT[i].SCISSOR == (GSVector4i)r->SCISSOR).alltrue())
{
Flush();
}
m_env.CTXT[i].SCISSOR = (GSVector4i)r->SCISSOR;
m_env.CTXT[i].UpdateScissor();
}
template<int i> void GSState::GIFRegHandlerALPHA(GIFReg* r)
{
ASSERT(r->ALPHA.A != 3);
ASSERT(r->ALPHA.B != 3);
ASSERT(r->ALPHA.C != 3);
ASSERT(r->ALPHA.D != 3);
if(PRIM->CTXT == i && !(m_env.CTXT[i].ALPHA == (GSVector4i)r->ALPHA).alltrue())
{
Flush();
}
m_env.CTXT[i].ALPHA = (GSVector4i)r->ALPHA;
// A/B/C/D == 3? => 2
m_env.CTXT[i].ALPHA.ai32[0] = ((~m_env.CTXT[i].ALPHA.ai32[0] >> 1) | 0xAA) & m_env.CTXT[i].ALPHA.ai32[0];
}
void GSState::GIFRegHandlerDIMX(GIFReg* r)
{
if(!(m_env.DIMX == (GSVector4i)r->DIMX).alltrue())
{
Flush();
}
m_env.DIMX = (GSVector4i)r->DIMX;
}
void GSState::GIFRegHandlerDTHE(GIFReg* r)
{
if(!(m_env.DTHE == (GSVector4i)r->DTHE).alltrue())
{
Flush();
}
m_env.DTHE = (GSVector4i)r->DTHE;
}
void GSState::GIFRegHandlerCOLCLAMP(GIFReg* r)
{
if(!(m_env.COLCLAMP == (GSVector4i)r->COLCLAMP).alltrue())
{
Flush();
}
m_env.COLCLAMP = (GSVector4i)r->COLCLAMP;
}
template<int i> void GSState::GIFRegHandlerTEST(GIFReg* r)
{
if(PRIM->CTXT == i && !(m_env.CTXT[i].TEST == (GSVector4i)r->TEST).alltrue())
{
Flush();
}
m_env.CTXT[i].TEST = (GSVector4i)r->TEST;
}
void GSState::GIFRegHandlerPABE(GIFReg* r)
{
if(!(m_env.PABE == (GSVector4i)r->PABE).alltrue())
{
Flush();
}
m_env.PABE = (GSVector4i)r->PABE;
}
template<int i> void GSState::GIFRegHandlerFBA(GIFReg* r)
{
if(PRIM->CTXT == i && !(m_env.CTXT[i].FBA == (GSVector4i)r->FBA).alltrue())
{
Flush();
}
m_env.CTXT[i].FBA = (GSVector4i)r->FBA;
}
template<int i> void GSState::GIFRegHandlerFRAME(GIFReg* r)
{
if(PRIM->CTXT == i && !(m_env.CTXT[i].FRAME == (GSVector4i)r->FRAME).alltrue())
{
Flush();
}
m_env.CTXT[i].FRAME = (GSVector4i)r->FRAME;
}
template<int i> void GSState::GIFRegHandlerZBUF(GIFReg* r)
{
if(r->ZBUF.ai32[0] == 0)
{
// during startup all regs are cleared to 0 (by the bios or something), so we mask z until this register becomes valid
r->ZBUF.ZMSK = 1;
}
r->ZBUF.PSM |= 0x30;
if(PRIM->CTXT == i && !(m_env.CTXT[i].ZBUF == (GSVector4i)r->ZBUF).alltrue())
{
Flush();
}
m_env.CTXT[i].ZBUF = (GSVector4i)r->ZBUF;
if(m_env.CTXT[i].ZBUF.PSM != PSM_PSMZ32
&& m_env.CTXT[i].ZBUF.PSM != PSM_PSMZ24
&& m_env.CTXT[i].ZBUF.PSM != PSM_PSMZ16
&& m_env.CTXT[i].ZBUF.PSM != PSM_PSMZ16S)
{
m_env.CTXT[i].ZBUF.PSM = PSM_PSMZ32;
}
}
void GSState::GIFRegHandlerBITBLTBUF(GIFReg* r)
{
if(!(m_env.BITBLTBUF == (GSVector4i)r->BITBLTBUF).alltrue())
{
FlushWrite();
}
m_env.BITBLTBUF = (GSVector4i)r->BITBLTBUF;
if((m_env.BITBLTBUF.SBW & 1) && (m_env.BITBLTBUF.SPSM == PSM_PSMT8 || m_env.BITBLTBUF.SPSM == PSM_PSMT4))
{
m_env.BITBLTBUF.SBW &= ~1;
}
if((m_env.BITBLTBUF.DBW & 1) && (m_env.BITBLTBUF.DPSM == PSM_PSMT8 || m_env.BITBLTBUF.DPSM == PSM_PSMT4))
{
m_env.BITBLTBUF.DBW &= ~1; // namcoXcapcom: 5, 11, refered to as 4, 10 in TEX0.TBW later
}
}
void GSState::GIFRegHandlerTRXPOS(GIFReg* r)
{
if(!(m_env.TRXPOS == (GSVector4i)r->TRXPOS).alltrue())
{
FlushWrite();
}
m_env.TRXPOS = (GSVector4i)r->TRXPOS;
}
void GSState::GIFRegHandlerTRXREG(GIFReg* r)
{
if(!(m_env.TRXREG == (GSVector4i)r->TRXREG).alltrue() || !(m_env.TRXREG2 == (GSVector4i)r->TRXREG).alltrue())
{
FlushWrite();
}
m_env.TRXREG = (GSVector4i)r->TRXREG;
m_env.TRXREG2 = (GSVector4i)r->TRXREG;
}
void GSState::GIFRegHandlerTRXDIR(GIFReg* r)
{
Flush();
m_env.TRXDIR = (GSVector4i)r->TRXDIR;
switch(m_env.TRXDIR.XDIR)
{
case 0: // host -> local
m_x = m_env.TRXPOS.DSAX;
m_y = m_env.TRXPOS.DSAY;
m_env.TRXREG.RRW = m_x + m_env.TRXREG2.RRW;
m_env.TRXREG.RRH = m_y + m_env.TRXREG2.RRH;
break;
case 1: // local -> host
m_x = m_env.TRXPOS.SSAX;
m_y = m_env.TRXPOS.SSAY;
m_env.TRXREG.RRW = m_x + m_env.TRXREG2.RRW;
m_env.TRXREG.RRH = m_y + m_env.TRXREG2.RRH;
break;
case 2: // local -> local
Move();
break;
case 3:
ASSERT(0);
break;
}
}
void GSState::GIFRegHandlerHWREG(GIFReg* r)
{
ASSERT(m_env.TRXDIR.XDIR == 0); // host => local
Write((BYTE*)r, 8); // hunting ground
}
void GSState::GIFRegHandlerSIGNAL(GIFReg* r)
{
if(m_mt) return;
SIGLBLID->SIGID = (SIGLBLID->SIGID & ~r->SIGNAL.IDMSK) | (r->SIGNAL.ID & r->SIGNAL.IDMSK);
if(CSR->wSIGNAL) CSR->rSIGNAL = 1;
if(!IMR->SIGMSK && m_irq) m_irq();
}
void GSState::GIFRegHandlerFINISH(GIFReg* r)
{
if(m_mt) return;
if(CSR->wFINISH) CSR->rFINISH = 1;
if(!IMR->FINISHMSK && m_irq) m_irq();
}
void GSState::GIFRegHandlerLABEL(GIFReg* r)
{
if(m_mt) return;
SIGLBLID->LBLID = (SIGLBLID->LBLID & ~r->LABEL.IDMSK) | (r->LABEL.ID & r->LABEL.IDMSK);
}
//
void GSState::Flush()
{
FlushWrite();
FlushPrim();
}
void GSState::FlushWrite()
{
FlushWrite(m_buff, m_bytes);
m_bytes = 0;
}
void GSState::FlushWrite(BYTE* mem, int len)
{
if(len > 0)
{
/*
CSize bs = GSLocalMemory::m_psm[m_env.BITBLTBUF.DPSM].bs;
if((m_x & (bs.cx - 1)) || (m_env.TRXREG.RRW & (bs.cx - 1))
|| (m_y & (bs.cy - 1)) || (m_env.TRXREG.RRH & (bs.cy - 1))
|| m_x != m_env.TRXPOS.DSAX)
{
printf("*** [%d]: %d %d, %d %d %d %d\n", m_env.BITBLTBUF.DPSM, m_env.TRXPOS.DSAX, m_env.TRXPOS.DSAY, m_x, m_y, m_env.TRXREG.RRW, m_env.TRXREG.RRH);
}
if((len % ((m_env.TRXREG.RRW - m_x) * GSLocalMemory::m_psm[m_env.BITBLTBUF.DPSM].trbpp / 8)) != 0)
{
printf("*** [%d]: %d %d\n", m_env.BITBLTBUF.DPSM, len, ((m_env.TRXREG.RRW - m_x) * GSLocalMemory::m_psm[m_env.BITBLTBUF.DPSM].trbpp / 8));
}
*/
int y = m_y;
GSLocalMemory::writeImage wi = GSLocalMemory::m_psm[m_env.BITBLTBUF.DPSM].wi;
(m_mem.*wi)(m_x, m_y, mem, len, m_env.BITBLTBUF, m_env.TRXPOS, m_env.TRXREG);
m_perfmon.Put(GSPerfMon::Swizzle, len);
//ASSERT(m_env.TRXREG.RRH >= m_y - y);
CRect r;
r.left = m_env.TRXPOS.DSAX;
r.top = y;
r.right = m_env.TRXREG.RRW;
r.bottom = min(m_x == m_env.TRXPOS.DSAX ? m_y : m_y + 1, m_env.TRXREG.RRH);
InvalidateVideoMem(m_env.BITBLTBUF, r);
/*
static int n = 0;
CString str;
str.Format(_T("c:\\temp1\\[%04d]_%05x_%d_%d_%d_%d_%d_%d.bmp"),
n++, (int)m_env.BITBLTBUF.DBP, (int)m_env.BITBLTBUF.DBW, (int)m_env.BITBLTBUF.DPSM,
r.left, r.top, r.right, r.bottom);
m_mem.SaveBMP(str, m_env.BITBLTBUF.DBP, m_env.BITBLTBUF.DBW, m_env.BITBLTBUF.DPSM, r.Width(), r.Height());
*/
}
}
//
void GSState::Write(BYTE* mem, int len)
{
/*
TRACE(_T("Write len=%d DBP=%05x DBW=%d DPSM=%d DSAX=%d DSAY=%d RRW=%d RRH=%d\n"),
len, (int)m_env.BITBLTBUF.DBP, (int)m_env.BITBLTBUF.DBW, (int)m_env.BITBLTBUF.DPSM,
(int)m_env.TRXPOS.DSAX, (int)m_env.TRXPOS.DSAY,
(int)m_env.TRXREG.RRW, (int)m_env.TRXREG.RRH);
*/
if(len == 0) return;
if(m_y >= m_env.TRXREG.RRH) return; // TODO: handle overflow during writing data too (just chop len below somewhere)
// TODO: hmmmm
if(PRIM->TME && (m_env.BITBLTBUF.DBP == m_context->TEX0.TBP0 || m_env.BITBLTBUF.DBP == m_context->TEX0.CBP))
{
FlushPrim();
}
int bpp = GSLocalMemory::m_psm[m_env.BITBLTBUF.DPSM].trbpp;
int pitch = (m_env.TRXREG.RRW - m_env.TRXPOS.DSAX) * bpp >> 3;
if(pitch <= 0) {ASSERT(0); return;}
int height = len / pitch;
if(height > m_env.TRXREG.RRH - m_env.TRXPOS.DSAY)
{
height = m_env.TRXREG.RRH - m_env.TRXPOS.DSAY;
len = height * pitch;
}
if(m_bytes > 0 || height < m_env.TRXREG.RRH - m_env.TRXPOS.DSAY)
{
ASSERT(len <= m_maxbytes); // more than 4mb into a 4mb local mem doesn't make sense
len = min(m_maxbytes, len);
if(m_bytes + len > m_maxbytes)
{
FlushWrite();
}
memcpy(&m_buff[m_bytes], mem, len);
m_bytes += len;
}
else
{
FlushWrite(mem, len);
}
m_mem.m_clut.Invalidate();
}
void GSState::Read(BYTE* mem, int len)
{
/*
TRACE(_T("Read len=%d SBP=%05x SBW=%d SPSM=%d SSAX=%d SSAY=%d RRW=%d RRH=%d\n"),
len, (int)m_env.BITBLTBUF.SBP, (int)m_env.BITBLTBUF.SBW, (int)m_env.BITBLTBUF.SPSM,
(int)m_env.TRXPOS.SSAX, (int)m_env.TRXPOS.SSAY,
(int)m_env.TRXREG.RRW, (int)m_env.TRXREG.RRH);
*/
if(m_y >= (int)m_env.TRXREG.RRH) {ASSERT(0); return;}
if(m_x == m_env.TRXPOS.SSAX && m_y == m_env.TRXPOS.SSAY)
{
CRect r(m_env.TRXPOS.SSAX, m_env.TRXPOS.SSAY, m_env.TRXREG.RRW, m_env.TRXREG.RRH);
InvalidateLocalMem(m_env.BITBLTBUF, r);
}
// TODO
m_mem.ReadImageX(m_x, m_y, mem, len, m_env.BITBLTBUF, m_env.TRXPOS, m_env.TRXREG);
}
void GSState::Move()
{
// ffxii uses this to move the top/bottom of the scrolling menus offscreen and then blends them back over the text to create a shading effect
// guitar hero copies the far end of the board to do a similar blend too
GSLocalMemory::readPixel rp = GSLocalMemory::m_psm[m_env.BITBLTBUF.SPSM].rp;
GSLocalMemory::writePixel wp = GSLocalMemory::m_psm[m_env.BITBLTBUF.DPSM].wp;
int sx = m_env.TRXPOS.SSAX;
int dx = m_env.TRXPOS.DSAX;
int sy = m_env.TRXPOS.SSAY;
int dy = m_env.TRXPOS.DSAY;
int w = m_env.TRXREG.RRW;
int h = m_env.TRXREG.RRH;
int xinc = 1;
int yinc = 1;
if(sx < dx) sx += w-1, dx += w-1, xinc = -1;
if(sy < dy) sy += h-1, dy += h-1, yinc = -1;
InvalidateLocalMem(m_env.BITBLTBUF, CRect(CPoint(sx, sy), CSize(w, h)));
InvalidateVideoMem(m_env.BITBLTBUF, CRect(CPoint(dx, dy), CSize(w, h)));
// TODO: use rowOffset
for(int y = 0; y < h; y++, sy += yinc, dy += yinc, sx -= xinc*w, dx -= xinc*w)
for(int x = 0; x < w; x++, sx += xinc, dx += xinc)
(m_mem.*wp)(dx, dy, (m_mem.*rp)(sx, sy, m_env.BITBLTBUF.SBP, m_env.BITBLTBUF.SBW), m_env.BITBLTBUF.DBP, m_env.BITBLTBUF.DBW);
}
void GSState::SoftReset(BYTE mask)
{
if(mask & 1) memset(&m_path[0], 0, sizeof(GIFPath));
if(mask & 2) memset(&m_path[1], 0, sizeof(GIFPath));
if(mask & 4) memset(&m_path[2], 0, sizeof(GIFPath));
m_env.TRXDIR.XDIR = 3; //-1 ; set it to invalid value
m_q = 1;
}
void GSState::ReadFIFO(BYTE* mem, int size)
{
GSPerfMonAutoTimer pmat(m_perfmon);
Flush();
size *= 16;
Read(mem, size);
if(m_dump)
{
m_dump.ReadFIFO(size);
}
}
template void GSState::Transfer<0>(BYTE* mem, UINT32 size);
template void GSState::Transfer<1>(BYTE* mem, UINT32 size);
template void GSState::Transfer<2>(BYTE* mem, UINT32 size);
template<int index> void GSState::Transfer(BYTE* mem, UINT32 size)
{
GSPerfMonAutoTimer pmat(m_perfmon);
BYTE* start = mem;
GIFPath& path = m_path[index];
while(size > 0)
{
bool eop = false;
if(path.tag.NLOOP == 0)
{
path.SetTag(mem);
mem += sizeof(GIFTag);
size--;
m_q = 1.0f;
if(index == 2 && path.tag.EOP)
{
m_path3hack = 1;
}
if(path.tag.PRE)
{
ASSERT(path.tag.FLG != GIF_FLG_IMAGE); // kingdom hearts, ffxii, tales of abyss, berserk
if((path.tag.FLG & 2) == 0)
{
GIFReg r;
r.i64 = path.tag.PRIM;
(this->*m_fpGIFRegHandlers[GIF_A_D_REG_PRIM])(&r);
}
}
if(path.tag.EOP)
{
eop = true;
}
else if(path.tag.NLOOP == 0)
{
if(index == 0 && m_nloophack)
{
continue;
}
eop = true;
}
}
if(path.tag.NLOOP > 0)
{
switch(path.tag.FLG)
{
case GIF_FLG_PACKED:
// first try a shortcut for a very common case
if(path.nreg == 0 && path.tag.NREG == 1 && size >= path.tag.NLOOP && path.GetReg() == GIF_REG_A_D)
{
int n = path.tag.NLOOP;
GIFPackedRegHandlerA_D((GIFPackedReg*)mem, n);
mem += n * sizeof(GIFPackedReg);
size -= n;
path.tag.NLOOP = 0;
}
else
{
while(size > 0)
{
(this->*m_fpGIFPackedRegHandlers[path.GetReg()])((GIFPackedReg*)mem);
size--;
mem += sizeof(GIFPackedReg);
if((++path.nreg & 0xf) == path.tag.NREG)
{
path.nreg = 0;
path.tag.NLOOP--;
if(path.tag.NLOOP == 0)
{
break;
}
}
}
}
break;
case GIF_FLG_REGLIST:
size *= 2;
while(size > 0)
{
(this->*m_fpGIFRegHandlers[path.GetReg()])((GIFReg*)mem);
size--;
mem += sizeof(GIFReg);
if((++path.nreg & 0xf) == path.tag.NREG)
{
path.nreg = 0;
path.tag.NLOOP--;
if(path.tag.NLOOP == 0)
{
break;
}
}
}
if(size & 1) mem += sizeof(GIFReg);
size /= 2;
break;
case GIF_FLG_IMAGE2: // hmmm
ASSERT(0);
path.tag.NLOOP = 0;
break;
case GIF_FLG_IMAGE:
{
int len = (int)min(size, path.tag.NLOOP);
//ASSERT(!(len&3));
switch(m_env.TRXDIR.XDIR)
{
case 0:
Write(mem, len * 16);
break;
case 1:
Read(mem, len * 16);
break;
case 2:
Move();
break;
case 3:
ASSERT(0);
break;
default:
__assume(0);
}
mem += len * 16;
path.tag.NLOOP -= len;
size -= len;
}
break;
default:
__assume(0);
}
}
if(eop && ((int)size <= 0 || index == 0))
{
break;
}
}
// FIXME: dq8, pcsx2 error probably
if(index == 0)
{
if(!path.tag.EOP && path.tag.NLOOP > 0)
{
path.tag.NLOOP = 0;
TRACE(_T("path1 hack\n"));
}
}
if(m_dump && mem > start)
{
m_dump.Transfer(index, start, mem - start);
}
}
template<class T> static void WriteState(BYTE*& dst, T* src, size_t len = sizeof(T))
{
memcpy(dst, src, len);
dst += len;
}
template<class T> static void ReadState(T* dst, BYTE*& src, size_t len = sizeof(T))
{
memcpy(dst, src, len);
src += len;
}
int GSState::Freeze(GSFreezeData* fd, bool sizeonly)
{
if(sizeonly)
{
fd->size = m_sssize;
return 0;
}
if(!fd->data || fd->size < m_sssize)
{
return -1;
}
Flush();
BYTE* data = fd->data;
WriteState(data, &m_version);
WriteState(data, &m_env.PRIM);
WriteState(data, &m_env.PRMODE);
WriteState(data, &m_env.PRMODECONT);
WriteState(data, &m_env.TEXCLUT);
WriteState(data, &m_env.SCANMSK);
WriteState(data, &m_env.TEXA);
WriteState(data, &m_env.FOGCOL);
WriteState(data, &m_env.DIMX);
WriteState(data, &m_env.DTHE);
WriteState(data, &m_env.COLCLAMP);
WriteState(data, &m_env.PABE);
WriteState(data, &m_env.BITBLTBUF);
WriteState(data, &m_env.TRXDIR);
WriteState(data, &m_env.TRXPOS);
WriteState(data, &m_env.TRXREG);
WriteState(data, &m_env.TRXREG2);
for(int i = 0; i < 2; i++)
{
WriteState(data, &m_env.CTXT[i].XYOFFSET);
WriteState(data, &m_env.CTXT[i].TEX0);
WriteState(data, &m_env.CTXT[i].TEX1);
WriteState(data, &m_env.CTXT[i].TEX2);
WriteState(data, &m_env.CTXT[i].CLAMP);
WriteState(data, &m_env.CTXT[i].MIPTBP1);
WriteState(data, &m_env.CTXT[i].MIPTBP2);
WriteState(data, &m_env.CTXT[i].SCISSOR);
WriteState(data, &m_env.CTXT[i].ALPHA);
WriteState(data, &m_env.CTXT[i].TEST);
WriteState(data, &m_env.CTXT[i].FBA);
WriteState(data, &m_env.CTXT[i].FRAME);
WriteState(data, &m_env.CTXT[i].ZBUF);
}
WriteState(data, &m_v.RGBAQ);
WriteState(data, &m_v.ST);
WriteState(data, &m_v.UV);
WriteState(data, &m_v.XYZ);
WriteState(data, &m_v.FOG);
WriteState(data, &m_x);
WriteState(data, &m_y);
WriteState(data, m_mem.m_vm8, m_mem.m_vmsize);
for(int i = 0; i < 3; i++)
{
WriteState(data, &m_path[i].tag);
WriteState(data, &m_path[i].nreg);
}
WriteState(data, &m_q);
return 0;
}
int GSState::Defrost(const GSFreezeData* fd)
{
if(!fd || !fd->data || fd->size == 0)
{
return -1;
}
if(fd->size < m_sssize)
{
return -1;
}
BYTE* data = fd->data;
int version;
ReadState(&version, data);
if(version > m_version)
{
return -1;
}
Flush();
Reset();
ReadState(&m_env.PRIM, data);
ReadState(&m_env.PRMODE, data);
ReadState(&m_env.PRMODECONT, data);
ReadState(&m_env.TEXCLUT, data);
ReadState(&m_env.SCANMSK, data);
ReadState(&m_env.TEXA, data);
ReadState(&m_env.FOGCOL, data);
ReadState(&m_env.DIMX, data);
ReadState(&m_env.DTHE, data);
ReadState(&m_env.COLCLAMP, data);
ReadState(&m_env.PABE, data);
ReadState(&m_env.BITBLTBUF, data);
ReadState(&m_env.TRXDIR, data);
ReadState(&m_env.TRXPOS, data);
ReadState(&m_env.TRXREG, data);
ReadState(&m_env.TRXREG2, data);
for(int i = 0; i < 2; i++)
{
ReadState(&m_env.CTXT[i].XYOFFSET, data);
ReadState(&m_env.CTXT[i].TEX0, data);
ReadState(&m_env.CTXT[i].TEX1, data);
ReadState(&m_env.CTXT[i].TEX2, data);
ReadState(&m_env.CTXT[i].CLAMP, data);
ReadState(&m_env.CTXT[i].MIPTBP1, data);
ReadState(&m_env.CTXT[i].MIPTBP2, data);
ReadState(&m_env.CTXT[i].SCISSOR, data);
ReadState(&m_env.CTXT[i].ALPHA, data);
ReadState(&m_env.CTXT[i].TEST, data);
ReadState(&m_env.CTXT[i].FBA, data);
ReadState(&m_env.CTXT[i].FRAME, data);
ReadState(&m_env.CTXT[i].ZBUF, data);
m_env.CTXT[i].XYOFFSET.OFX &= 0xffff;
m_env.CTXT[i].XYOFFSET.OFY &= 0xffff;
if(version <= 4)
{
data += sizeof(DWORD) * 7; // skip
}
}
ReadState(&m_v.RGBAQ, data);
ReadState(&m_v.ST, data);
ReadState(&m_v.UV, data);
ReadState(&m_v.XYZ, data);
ReadState(&m_v.FOG, data);
ReadState(&m_x, data);
ReadState(&m_y, data);
ReadState(m_mem.m_vm8, data, m_mem.m_vmsize);
for(int i = 0; i < 3; i++)
{
ReadState(&m_path[i].tag, data);
ReadState(&m_path[i].nreg, data);
m_path[i].SetTag(&m_path[i].tag); // expand regs
}
ReadState(&m_q, data);
PRIM = !m_env.PRMODECONT.AC ? (GIFRegPRIM*)&m_env.PRMODE : &m_env.PRIM;
m_context = &m_env.CTXT[PRIM->CTXT];
UpdateVertexKick();
m_env.CTXT[0].UpdateScissor();
m_env.CTXT[1].UpdateScissor();
m_perfmon.SetFrame(5000);
return 0;
}
void GSState::SetGameCRC(DWORD crc, int options)
{
m_crc = crc;
m_options = options;
m_game = CRC::Lookup(crc);
if(m_nloophack_org == 2)
{
m_nloophack = m_game.nloophack;
}
}
void GSState::SetFrameSkip(int frameskip)
{
if(m_frameskip != frameskip)
{
m_frameskip = frameskip;
if(frameskip)
{
m_fpGIFPackedRegHandlers[GIF_REG_PRIM] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFPackedRegHandlers[GIF_REG_RGBA] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFPackedRegHandlers[GIF_REG_STQ] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFPackedRegHandlers[GIF_REG_UV] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFPackedRegHandlers[GIF_REG_XYZF2] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFPackedRegHandlers[GIF_REG_XYZ2] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFPackedRegHandlers[GIF_REG_CLAMP_1] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFPackedRegHandlers[GIF_REG_CLAMP_2] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFPackedRegHandlers[GIF_REG_FOG] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFPackedRegHandlers[GIF_REG_XYZF3] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFPackedRegHandlers[GIF_REG_XYZ3] = &GSState::GIFPackedRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_PRIM] = &GSState::GIFRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_RGBAQ] = &GSState::GIFRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_ST] = &GSState::GIFRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_UV] = &GSState::GIFRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZF2] = &GSState::GIFRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZ2] = &GSState::GIFRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZF3] = &GSState::GIFRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZ3] = &GSState::GIFRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_PRMODECONT] = &GSState::GIFRegHandlerNOP;
m_fpGIFRegHandlers[GIF_A_D_REG_PRMODE] = &GSState::GIFRegHandlerNOP;
}
else
{
m_fpGIFPackedRegHandlers[GIF_REG_PRIM] = &GSState::GIFPackedRegHandlerPRIM;
m_fpGIFPackedRegHandlers[GIF_REG_RGBA] = &GSState::GIFPackedRegHandlerRGBA;
m_fpGIFPackedRegHandlers[GIF_REG_STQ] = &GSState::GIFPackedRegHandlerSTQ;
m_fpGIFPackedRegHandlers[GIF_REG_UV] = &GSState::GIFPackedRegHandlerUV;
m_fpGIFPackedRegHandlers[GIF_REG_XYZF2] = &GSState::GIFPackedRegHandlerXYZF2;
m_fpGIFPackedRegHandlers[GIF_REG_XYZ2] = &GSState::GIFPackedRegHandlerXYZ2;
m_fpGIFPackedRegHandlers[GIF_REG_CLAMP_1] = &GSState::GIFPackedRegHandlerCLAMP<0>;
m_fpGIFPackedRegHandlers[GIF_REG_CLAMP_2] = &GSState::GIFPackedRegHandlerCLAMP<1>;
m_fpGIFPackedRegHandlers[GIF_REG_FOG] = &GSState::GIFPackedRegHandlerFOG;
m_fpGIFPackedRegHandlers[GIF_REG_XYZF3] = &GSState::GIFPackedRegHandlerXYZF3;
m_fpGIFPackedRegHandlers[GIF_REG_XYZ3] = &GSState::GIFPackedRegHandlerXYZ3;
m_fpGIFRegHandlers[GIF_A_D_REG_PRIM] = &GSState::GIFRegHandlerPRIM;
m_fpGIFRegHandlers[GIF_A_D_REG_RGBAQ] = &GSState::GIFRegHandlerRGBAQ;
m_fpGIFRegHandlers[GIF_A_D_REG_ST] = &GSState::GIFRegHandlerST;
m_fpGIFRegHandlers[GIF_A_D_REG_UV] = &GSState::GIFRegHandlerUV;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZF2] = &GSState::GIFRegHandlerXYZF2;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZ2] = &GSState::GIFRegHandlerXYZ2;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZF3] = &GSState::GIFRegHandlerXYZF3;
m_fpGIFRegHandlers[GIF_A_D_REG_XYZ3] = &GSState::GIFRegHandlerXYZ3;
m_fpGIFRegHandlers[GIF_A_D_REG_PRMODECONT] = &GSState::GIFRegHandlerPRMODECONT;
m_fpGIFRegHandlers[GIF_A_D_REG_PRMODE] = &GSState::GIFRegHandlerPRMODE;
}
}
}
// hacks
struct GSFrameInfo
{
DWORD FBP;
DWORD FPSM;
bool TME;
DWORD TBP0;
DWORD TPSM;
};
typedef bool (*GetSkipCount)(const GSFrameInfo& fi, int& skip);
bool GSC_Okami(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x00e00 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x00000 && fi.TPSM == PSM_PSMCT32)
{
skip = 1000;
}
}
else
{
if(fi.TME && fi.FBP == 0x00e00 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x03800 && fi.TPSM == PSM_PSMT4)
{
skip = 0;
}
}
return true;
}
bool GSC_MetalGearSolid3(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x02000 && fi.FPSM == PSM_PSMCT32 && (fi.TBP0 == 0x00000 || fi.TBP0 == 0x01000) && fi.TPSM == PSM_PSMCT24)
{
skip = 1000; // 76, 79
}
else if(fi.TME && fi.FBP == 0x02800 && fi.FPSM == PSM_PSMCT24 && (fi.TBP0 == 0x00000 || fi.TBP0 == 0x01000) && fi.TPSM == PSM_PSMCT32)
{
skip = 1000; // 69
}
}
else
{
if(!fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x01000) && fi.FPSM == PSM_PSMCT32)
{
skip = 0;
}
}
return true;
}
bool GSC_DBZBT2(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && /*fi.FBP == 0x00000 && fi.FPSM == PSM_PSMCT16 &&*/ fi.TBP0 == 0x02000 && fi.TPSM == PSM_PSMZ16)
{
skip = 27;
}
else if(!fi.TME && fi.FBP == 0x03000 && fi.FPSM == PSM_PSMCT16)
{
skip = 10;
}
}
return true;
}
bool GSC_DBZBT3(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x01c00 && fi.FPSM == PSM_PSMCT32 && (fi.TBP0 == 0x00000 || fi.TBP0 == 0x00e00) && fi.TPSM == PSM_PSMT8H)
{
skip = 24; // blur
}
else if(fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x00e00) && fi.FPSM == PSM_PSMCT32 && fi.TPSM == PSM_PSMT8H)
{
skip = 28; // outline
}
}
return true;
}
bool GSC_SFEX3(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x00f00 && fi.FPSM == PSM_PSMCT16 && (fi.TBP0 == 0x00500 || fi.TBP0 == 0x00000) && fi.TPSM == PSM_PSMCT32)
{
skip = 4;
}
}
return true;
}
bool GSC_Bully(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x01180) && (fi.TBP0 == 0x00000 || fi.TBP0 == 0x01180) && fi.FBP == fi.TBP0 && fi.FPSM == PSM_PSMCT32 && fi.FPSM == fi.TPSM)
{
return false; // allowed
}
if(fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x01180) && fi.FPSM == PSM_PSMCT16S && fi.TBP0 == 0x02300 && fi.TPSM == PSM_PSMZ16S)
{
skip = 6;
}
}
else
{
if(!fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x01180) && fi.FPSM == PSM_PSMCT32)
{
skip = 0;
}
}
return true;
}
bool GSC_BullyCC(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x01180) && (fi.TBP0 == 0x00000 || fi.TBP0 == 0x01180) && fi.FBP == fi.TBP0 && fi.FPSM == PSM_PSMCT32 && fi.FPSM == fi.TPSM)
{
return false; // allowed
}
if(!fi.TME && fi.FBP == 0x02800 && fi.FPSM == PSM_PSMCT24)
{
skip = 9;
}
}
return true;
}
bool GSC_SoTC(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x02b80 && fi.FPSM == PSM_PSMCT24 && fi.TBP0 == 0x01e80 && fi.TPSM == PSM_PSMCT24)
{
skip = 9;
}
else if(fi.TME && fi.FBP == 0x01c00 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x03800 && fi.TPSM == PSM_PSMCT32)
{
skip = 8;
}
else if(fi.TME && fi.FBP == 0x01e80 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x03880 && fi.TPSM == PSM_PSMCT32)
{
skip = 8;
}
}
return true;
}
bool GSC_OnePieceGrandAdventure(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x02d00 && fi.FPSM == PSM_PSMCT16 && (fi.TBP0 == 0x00000 || fi.TBP0 == 0x00e00) && fi.TPSM == PSM_PSMCT16)
{
skip = 3;
}
}
return true;
}
bool GSC_ICO(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x00800 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x03d00 && fi.TPSM == PSM_PSMCT32)
{
skip = 3;
}
else if(fi.TME && fi.FBP == 0x00800 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x02800 && fi.TPSM == PSM_PSMT8H)
{
skip = 1;
}
}
else
{
if(fi.TME && fi.TBP0 == 0x00800 && fi.TPSM == PSM_PSMCT32)
{
skip = 0;
}
}
return true;
}
bool GSC_GT4(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && (fi.FBP == 0x03440 || fi.FBP >= 0x03e00) && fi.FPSM == PSM_PSMCT32 && (fi.TBP0 == 0x00000 || fi.TBP0 == 0x01400) && fi.TPSM == PSM_PSMT8)
{
skip = 880;
}
else if(fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x01400) && fi.FPSM == PSM_PSMCT24 && fi.TBP0 >= 0x03420 && fi.TPSM == PSM_PSMT8)
{
// TODO: removes gfx from where it is not supposed to (garage)
// skip = 58;
}
}
return true;
}
bool GSC_WildArms5(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x03100 && fi.FPSM == PSM_PSMZ32 && fi.TBP0 == 0x01c00 && fi.TPSM == PSM_PSMZ32)
{
skip = 100;
}
}
else
{
if(fi.TME && fi.FBP == 0x00e00 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x02a00 && fi.TPSM == PSM_PSMCT32)
{
skip = 1;
}
}
return true;
}
bool GSC_Manhunt2(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x03c20 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x01400 && fi.TPSM == PSM_PSMT8)
{
skip = 640;
}
}
return true;
}
bool GSC_CrashBandicootWoC(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x00a00) && (fi.TBP0 == 0x00000 || fi.TBP0 == 0x00a00) && fi.FBP == fi.TBP0 && fi.FPSM == PSM_PSMCT32 && fi.FPSM == fi.TPSM)
{
return false; // allowed
}
if(fi.TME && fi.FBP == 0x02200 && fi.FPSM == PSM_PSMZ24 && fi.TBP0 == 0x01400 && fi.TPSM == PSM_PSMZ24)
{
skip = 41;
}
}
else
{
if(fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x00a00) && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x03c00 && fi.TPSM == PSM_PSMCT32)
{
skip = 0;
}
else if(!fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x00a00))
{
skip = 0;
}
}
return true;
}
bool GSC_ResidentEvil4(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x03100 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x01c00 && fi.TPSM == PSM_PSMZ24)
{
skip = 176;
}
}
return true;
}
bool GSC_Spartan(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x02000 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x00000 && fi.TPSM == PSM_PSMCT32)
{
skip = 107;
}
}
return true;
}
bool GSC_AceCombat4(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x02a00 && fi.FPSM == PSM_PSMZ24 && fi.TBP0 == 0x01600 && fi.TPSM == PSM_PSMZ24)
{
skip = 71; // clouds (z, 16-bit)
}
else if(fi.TME && fi.FBP == 0x02900 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x00000 && fi.TPSM == PSM_PSMCT24)
{
skip = 28; // blur
}
}
return true;
}
bool GSC_Drakengard2(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x026c0 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x00a00 && fi.TPSM == PSM_PSMCT32)
{
skip = 64;
}
}
return true;
}
bool GSC_Tekken5(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x02ea0 && fi.FPSM == PSM_PSMCT32 && fi.TBP0 == 0x00000 && fi.TPSM == PSM_PSMCT32)
{
skip = 95;
}
}
return true;
}
bool GSC_IkkiTousen(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x00a80 && fi.FPSM == PSM_PSMZ24 && fi.TBP0 == 0x01180 && fi.TPSM == PSM_PSMZ24)
{
skip = 1000; // shadow (result is broken without depth copy, also includes 16 bit)
}
else if(fi.TME && fi.FBP == 0x00700 && fi.FPSM == PSM_PSMZ24 && fi.TBP0 == 0x01180 && fi.TPSM == PSM_PSMZ24)
{
skip = 11; // blur
}
}
else if(skip > 7)
{
if(fi.TME && fi.FBP == 0x00700 && fi.FPSM == PSM_PSMCT16 && fi.TBP0 == 0x00700 && fi.TPSM == PSM_PSMCT16)
{
skip = 7; // the last steps of shadow drawing
}
}
return true;
}
bool GSC_GodOfWar(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x00000 && fi.FPSM == PSM_PSMCT16 && fi.TBP0 == 0x00000 && fi.TPSM == PSM_PSMCT16)
{
skip = 30;
}
}
else
{
}
return true;
}
bool GSC_GiTS(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && fi.FBP == 0x01400 && fi.FPSM == PSM_PSMCT16 && fi.TBP0 == 0x02e40 && fi.TPSM == PSM_PSMCT16)
{
skip = 1315;
}
}
else
{
}
return true;
}
bool GSC_Onimusha3(const GSFrameInfo& fi, int& skip)
{
if(fi.TME /*&& (fi.FBP == 0x00000 || fi.FBP == 0x00700)*/ && (fi.TBP0 == 0x01180 || fi.TBP0 == 0x00e00 || fi.TBP0 == 0x01000 || fi.TBP0 == 0x01200) && (fi.TPSM == PSM_PSMCT32 || fi.TPSM == PSM_PSMCT24))
{
skip = 1;
}
return true;
}
bool GSC_TalesOfAbyss(const GSFrameInfo& fi, int& skip)
{
if(skip == 0)
{
if(fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x00e00) && fi.TBP0 == 0x01c00 && fi.TPSM == PSM_PSMT8) // copies the z buffer to the alpha channel of the fb
{
skip = 1000;
}
else if(fi.TME && (fi.FBP == 0x00000 || fi.FBP == 0x00e00) && (fi.TBP0 == 0x03560 || fi.TBP0 == 0x038e0) && fi.TPSM == PSM_PSMCT32)
{
skip = 1;
}
}
else
{
if(fi.TME && fi.TPSM != PSM_PSMT8)
{
skip = 0;
}
}
return true;
}
bool GSState::IsBadFrame(int& skip)
{
GSFrameInfo fi;
fi.FBP = m_context->FRAME.Block();
fi.FPSM = m_context->FRAME.PSM;
fi.TME = PRIM->TME;
fi.TBP0 = m_context->TEX0.TBP0;
fi.TPSM = m_context->TEX0.PSM;
static GetSkipCount map[CRC::TitleCount];
static bool inited = false;
if(!inited)
{
inited = true;
memset(map, 0, sizeof(map));
map[CRC::Okami] = GSC_Okami;
map[CRC::MetalGearSolid3] = GSC_MetalGearSolid3;
map[CRC::DBZBT2] = GSC_DBZBT2;
map[CRC::DBZBT3] = GSC_DBZBT3;
map[CRC::SFEX3] = GSC_SFEX3;
map[CRC::Bully] = GSC_Bully;
map[CRC::BullyCC] = GSC_BullyCC;
map[CRC::SoTC] = GSC_SoTC;
map[CRC::OnePieceGrandAdventure] = GSC_OnePieceGrandAdventure;
map[CRC::ICO] = GSC_ICO;
map[CRC::GT4] = GSC_GT4;
map[CRC::WildArms5] = GSC_WildArms5;
map[CRC::Manhunt2] = GSC_Manhunt2;
map[CRC::CrashBandicootWoC] = GSC_CrashBandicootWoC;
map[CRC::ResidentEvil4] = GSC_ResidentEvil4;
map[CRC::Spartan] = GSC_Spartan;
map[CRC::AceCombat4] = GSC_AceCombat4;
map[CRC::Drakengard2] = GSC_Drakengard2;
map[CRC::Tekken5] = GSC_Tekken5;
map[CRC::IkkiTousen] = GSC_IkkiTousen;
map[CRC::GodOfWar] = GSC_GodOfWar;
map[CRC::GodOfWar2] = GSC_GodOfWar;
map[CRC::GiTS] = GSC_GiTS;
map[CRC::Onimusha3] = GSC_Onimusha3;
map[CRC::TalesOfAbyss] = GSC_TalesOfAbyss;
}
// TODO: just set gsc in SetGameCRC once
GetSkipCount gsc = map[m_game.title];
if(gsc && !gsc(fi, skip))
{
return false;
}
if(skip == 0)
{
if(fi.TME)
{
if(GSUtil::HasSharedBits(fi.FBP, fi.FPSM, fi.TBP0, fi.TPSM))
{
// skip = 1;
}
// depth textures (bully, mgs3s1 intro)
if(fi.TPSM == PSM_PSMZ32 || fi.TPSM == PSM_PSMZ24 || fi.TPSM == PSM_PSMZ16 || fi.TPSM == PSM_PSMZ16S)
{
skip = 1;
}
}
}
if(skip > 0)
{
skip--;
return true;
}
return false;
}
| [
"gabest@627e133f-a60d-0410-aeef-a778af760ea1"
]
| [
[
[
1,
2179
]
]
]
|
30dc4edada09034b1b09ee74af066dad5dda95cd | f90b1358325d5a4cfbc25fa6cccea56cbc40410c | /src/GUI/proRataMassSpectrumData.h | 263fe46e0a1f077e8c837e4d6205f9430ed90764 | []
| no_license | ipodyaco/prorata | bd52105499c3fad25781d91952def89a9079b864 | 1f17015d304f204bd5f72b92d711a02490527fe6 | refs/heads/master | 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | h |
#ifndef PRORATAMASSSPECTRUMDATA_H
#define PRORATAMASSSPECTRUMDATA_H
#include "peptideRatio.h"
#include "directoryStructure.h"
#include "mzReader.h"
class ProRataMassSpectrumData
{
public:
ProRataMassSpectrumData();
~ProRataMassSpectrumData();
bool getScan( string sFilename, unsigned long int iScan,
vector< double > & vdMZ, vector< double > & vdRelativeIntensity );
bool getScan( string sFilename, unsigned long int iScan,
vector< double > & vdMZ, vector< double > & vdRelativeIntensity, double & dPrecursorMZ );
private:
map<string, mzReader*> mapReaderFileMappings;
};
#endif //PRORATAMASSSPECTRUMDATA_H
| [
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
]
| [
[
[
1,
24
]
]
]
|
9257bc1bc087eebad004602ff3eb03362fcbc133 | 00b979f12f13ace4e98e75a9528033636dab021d | /branches/ziis/src/include/http_helper.hh | c2564aa5f2fb9de5f43cf806011ec9a28cbc2c0d | []
| 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 | 316 | hh | #include <ziafs_buffer.hh>
#include <zia_stringmanager.hh>
namespace net
{
typedef enum
{
CHUNK_FIRST = 0,
CHUNK_MIDDLE,
CHUNK_LAST
} chunk_pos_t;
bool generate_chunk_header(buffer& data, size_t sz, chunk_pos_t chunk);
bool split_accept_encoding(std::string&, std::vector<std::string>&);
}
| [
"zapoutix@754ce95b-6e01-0410-81d0-8774ba66fe44",
"texane@754ce95b-6e01-0410-81d0-8774ba66fe44"
]
| [
[
[
1,
13
]
],
[
[
14,
14
]
]
]
|
d9e736c0eddf9599b00e71de580805f9fed7b9cb | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Graphics/WS/Direct/CLifeEngine.h | 33152756bacf17c8ea73abcb9456a5eb3e18e88e | []
| 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 | 1,109 | h | // CLifeEngine.h
//
// Copyright (c) 2005 Symbian Softwares Ltd. All rights reserved.
//
#if !defined(__CLIFEENGINE_H__)
#define __CLIFEENGINE_H__
#include <e32base.h>
// Cell array dimensions
const TInt ROWS_NUM = 16;
const TInt COLS_NUM = 8;
// Cell array type
typedef TBool TCellArray[ROWS_NUM][COLS_NUM];
// A "Game of Life" engine
// After John Conway, Scientific American 223 (October 1970): 120-123
class CLifeEngine : public CBase
{
public:
// Initalise engine with random seed
CLifeEngine(const TInt64& aSeed);
// Moves forward one generation
void AddGeneration();
// Gets cell array
const TCellArray& GetCellArray() const
{
return iCellArray;
}
// Resets all cells to random state
void Reset();
private:
// Gets number of neighbors for cell row,col
TInt NumNeighbors(TInt row, TInt col);
private:
// Random num generator seed
TInt64 iSeed;
// Cell array
TCellArray iCellArray;
// Temporary working cell array
TCellArray iTempCellArray;
};
#endif
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
]
| [
[
[
1,
48
]
]
]
|
8e0c6081c73586fee6f96196b0461a812c386564 | 191d4160cba9d00fce9041a1cc09f17b4b027df5 | /ZeroLag2/ZeroLag/SignScan.h | a5b8c015f5095b8ba81cfc59283f77fa9b081118 | []
| no_license | zapline/zero-lag | f71d35efd7b2f884566a45b5c1dc6c7eec6577dd | 1651f264c6d2dc64e4bdcb6529fb6280bbbfbcf4 | refs/heads/master | 2021-01-22T16:45:46.430952 | 2011-05-07T13:22:52 | 2011-05-07T13:22:52 | 32,774,187 | 3 | 2 | null | null | null | null | GB18030 | C++ | false | false | 849 | h | #pragma once
#include "Public/BrowseDir.h"
class CSignScan :
public CBrowseDir
{
public:
CSignScan(void);
public:
~CSignScan(void);
//返回子目录个数
int GetSubdirCount()
{
return m_nSubdirCount;
}
//返回文件个数
int GetFileCount()
{
return m_nFileCount;
}
void SetSubdirCount(int n)
{
m_nSubdirCount = n;
}
void SetFileCount(int n)
{
m_nFileCount = n;
m_DisplayCount = n;
}
CKuiRealListCtrl *pList;
BOOL HideHave;
protected:
int m_nFileCount; //保存文件个数
int m_nSubdirCount; //保存子目录个数
int m_DisplayCount; //顯示文件個數
virtual bool ProcessFile(const char *filename);
virtual void ProcessDir(const char *currentdir,const char *parentdir);
BOOL InitFunc();
BOOL CheckFileTrust( LPCWSTR lpFileName );
};
| [
"Administrator@PC-200201010241"
]
| [
[
[
1,
47
]
]
]
|
ff67360780db9ffdd479fc5151b4897efea06421 | b887b5999a912513e7b9be35abe48da50f83650e | /Projekt/src/logic/hitTest/Collision.h | cdc133eaa9564f4e9004b269d7fa8a1a29f15165 | []
| no_license | ryba616/Projekt | e39ce225ce725262f50f2b89b44f7a97bed383dc | ddc3c0a078e261e0e1d1278a5d1ff19930cc10b2 | refs/heads/master | 2021-01-22T22:56:50.420462 | 2010-05-16T22:55:53 | 2010-05-16T22:55:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 273 | h | #ifndef COLLISION_H
#define COLLISION_H
#include <Allegro.h>
#include "HTObj.h"
#include <vector>
class Collision
{
public:
Collision(HTObj *p_obj1, HTObj *p_obj2);
HTObj *getObj1();
HTObj *getObj2();
private:
HTObj *obj1;
HTObj *obj2;
};
#endif | [
"ryba@ryb-520fb58ee61.(none)"
]
| [
[
[
1,
20
]
]
]
|
762c3c0c62e76333879c935ca0b00fcdd59a3ef3 | fceff9260ff49d2707060241b6f9b927b97db469 | /ZombieGentlemen_SeniorProject/troll.cpp | 1f09048f54db49fbca6b7e4c0fc354a07dafd9ad | []
| no_license | EddyReyes/gentlemen-zombies-senior-project | 9f5a6be90f0459831b3f044ed17ef2f085bec679 | d88458b716c6eded376b3d44b5385c80deeb9a16 | refs/heads/master | 2021-05-29T12:13:47.506314 | 2011-07-04T17:20:38 | 2011-07-04T17:20:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,493 | cpp | #include "troll.h"
troll::troll(void)
{
type = entityTroll;
m_object = NULL;
timer = 0;
state = trollIdle;
srand(((unsigned int)time(0)));
}
troll::~troll(void)
{
// destructor does not create or destroy data
}
void troll::update(float timePassed)
{
timer += timePassed;
if(timer >= maxTime)
{
maxTime = (rand() % 2000)/1000.0f;
randNum = rand() % 4;
state = (enum trollStates)randNum;
timer = 0;
}
switch(state)
{
case trollIdle:
m_object->getPhysics()->setXVelocity(0);
break;
case trollWalkingLeft: m_object->getPhysics()->setXVelocity(-3);
break;
case trollWalkingRight: m_object->getPhysics()->setXVelocity(3);
break;
case trollJumping: m_object->getPhysics()->setYVelocity(30);
break;
}
animate();
}
void troll::animate()
{
switch(state)
{
case trollIdle: m_object->setSprite(0,0);
break;
case trollWalkingLeft: m_object->setSprite(0,0);
break;
case trollWalkingRight: m_object->setSprite(0,1);
break;
case trollJumping: //m_object->setSprite(0,0);
break;
}
}
void troll::reset()
{
alive = true;
armor = false;
}
void troll::flip()
{
switch(state)
{
case trollWalkingLeft: state = trollWalkingRight;
break;
case trollWalkingRight: state = trollWalkingLeft;
break;
}
}
void troll::setDirection(char dir)
{
switch(dir)
{
case 'l': state = trollWalkingLeft;
break;
case 'r': state = trollWalkingRight;
break;
default:
break;
}
} | [
"[email protected]@66a8e42f-0ee8-26ea-976e-e3172d02aab5"
]
| [
[
[
1,
83
]
]
]
|
239f2d400fed0d3a18f2a5cf383cc3166d24f0f7 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian-r6/CSCategoryResultView.h | 4385674be462da53191b9bc0c577fd4597d7e41a | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,716 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CS_CATEGORY_RESULT_VIEW_H
#define CS_CATEGORY_RESULT_VIEW_H
#include "ViewBase.h"
#include "EventGenerator.h"
enum TCSState {
EAreaMatchSelected,
EAreaMatchCancelled
};
class CWayFinderAppUi;
/**
* Avkon view class for STestResultListBoxView. It is register with the view server
* by the AppUi. It owns the container control.
* @class CCSCategoryResultView STestResultListBoxView.h
*/
class CCSCategoryResultView : public CViewBase
{
public:
// constructors and destructor
CCSCategoryResultView(CWayFinderAppUi* aWayfinderAppUi);
static CCSCategoryResultView* NewL(CWayFinderAppUi* aWayfinderAppUi);
static CCSCategoryResultView* NewLC(CWayFinderAppUi* aWayfinderAppUi);
void ConstructL();
virtual ~CCSCategoryResultView();
public:
// from base class CAknView
TUid Id() const;
void HandleCommandL( TInt aCommand );
void DynInitMenuPaneL( TInt aResourceId, CEikMenuPane* aMenuPane );
protected:
// from base class CAknView
void DoActivateL( const TVwsViewId& aPrevViewId,
TUid aCustomMessageId,
const TDesC8& aCustomMessage );
void DoDeactivate();
public:
/**
* Returns the path to the directory holding all images
* for the combined search.
* @return A string containing the correct path.
*/
TPtrC GetCSIconPath();
/**
* Returns the the name of the mbm file.
* @return The name of the mbm file.
*/
TPtrC GetMbmName();
/**
* Adds all the categories from the search.
*/
void AddCategories();
/**
* Adds all the categories from the search.
*
* @param aCategoryVec The vector of categories to be added to listbox
*/
void AddCategories(const std::vector<class CombinedSearchCategory*>& categories);
/**
* Called from the event generator when we're ready to add more categories.
*/
void RetryAddCategories();
/**
* Returns the currently selected index from the listbox, compensates
* for top hits.
*
* @return The currently selected index
*/
TInt GetCurrentIndex();
/**
* Checks if gps is connected and allowed to use.
* @return ETrue if connected and allowed to use.
* EFalse if not connected or not allowed to use.
*/
TBool IsGpsAllowed();
/**
* Checks if user came from the route planner and
* is going to set the search res as origin.
* @return ETrue if coming from route planner and setting origin.
*/
TBool SettingOrigin();
/**
* Checks if user came from the route planner and
* is going to set the search res as destination.
* @return ETrue if coming from route planner and setting destination.
*/
TBool SettingDestination();
/**
* Generates av event.
* @param aEvent The event to be generated.
*/
void GenerateEvent(enum TCSState aEvent);
/**
* Handles the generated event.
* @param eEvent The event to be handled.
*/
void HandleGeneratedEventL(enum TCSState aEvent);
/**
* Called when an area match search result is received.
* Updates the category that made the area match search and
* switches to detailed result view if aSwitchToResultView is true.
* @param aSwitchToResultView, if true we automatically switches to
* CCSDetailedResultView.
*/
void AreaMatchSearchResultReceived(TBool aSwitchToResultView);
/**
* A static wrapper as a callback to be able to call the real
* NavigateToCallback() function from appui
* by a function pointer to this wrapper. This is used in the gps wizard
* to be able to know if/when lbs connected to the gps so it is okay
* to order the route.
* This is necessary since we have different objects with different
* member functions that can call the gps wizard.
*/
static void WrapperToNavigateToCallback(void* pt2Object);
private:
/**
* Checks to see if the selected category is empty or not.
* @return ETrue if the selected category is empty.
*/
TBool SelectedCategoryEmpty();
/**
* Returns the type of hits in the selected category.
* @return, 0 if the selected category contains search hits
* 1 if containing area matches.
*/
TInt TypeOfHitsInSelectedCategory();
/**
* Displayes a listbox containing all the area matches received
* in the search result for the selected category.
*/
void DisplayAreaMatchesListL();
/**
* Show search hit on map.
*/
void ShowOnMap();
/**
* Shows more information about this top hit. We send the position
* and the id of the search item to appui that then displays
* the information in the service window.
*/
void ShowMoreInformation();
/**
* Gets the name and desc from the listbox for the
* selected index. Get the searcItem object for this
* index
*/
void NavigateTo();
/**
* NavigateToCallback() function from called form appui via the
* static WrapperToNavigateToCallback() function.
*/
void NavigateToCallback();
/**
* Does the same as NavigateTo but instead of calling
* WayFinderAppUi::NavigateToSearchRes we call
* WayFinderAppUi::SetOrigin wich calls route planner
* to set the origin.
*/
void SetAsOrigin();
/**
* Does the same as NavigateTo but instead of calling
* WayFinderAppUi::NavigateToSearchRes we call
* WayFinderAppUi::SetDestination wich calls route planner
* to set the destination.
*/
void SetAsDestination();
/**
* Gets called when user wants to save a search item as a
* favorite. Gets the selected search item and calls
* WayFinderAppUi::AddFavoriteFromSearch which
* stores this search item as a favorite.
*/
void SaveAsFavorite();
/**
* Gets called when user wants to send a search resykt by
* email or sms. Gets the selected search item and calls
* WayFinderAppUi::SendFavoriteL which starts the
* CCommunicationWizard.
* Transfer ownership of the newly created favorite.
*/
void SendAsFavoriteL();
private:
/// The container containing the listbox.
class CCSCategoryResultContainer* iContainer;
/// The current index, compensated for top hits.
/// This index will match the vector in the
/// CombinedSearchDataHolder holding all the
/// categories.
TInt iCurrIndex;
/// Holds the current selected index in the listbox.
TInt iCurrentListBoxIndex;
/// Typedef for the eventgenerator
typedef CEventGenerator<CCSCategoryResultView, enum TCSState> CSCatGenerator;
/// Event generator, used to generate event
CSCatGenerator* iEventGenerator;
/// Keeps track of the index from which the area match search was triggered.
TInt iAreaMatchHeadingIndex;
/// The selected index from the selection list dialog
TInt iSelectedIndex;
};
#endif // STESTRESULTLISTBOXVIEW_H
| [
"[email protected]"
]
| [
[
[
1,
246
]
]
]
|
aa50e2423a258da2a7e8d87a37a470c41f4ead78 | 2ca3ad74c1b5416b2748353d23710eed63539bb0 | /Pilot/Lokapala_Observe/Raptor/ObserveBI.h | f785cee1409a46d6b61230a80ac5b38e5a8796bc | []
| no_license | sjp38/lokapala | 5ced19e534bd7067aeace0b38ee80b87dfc7faed | dfa51d28845815cfccd39941c802faaec9233a6e | refs/heads/master | 2021-01-15T16:10:23.884841 | 2009-06-03T14:56:50 | 2009-06-03T14:56:50 | 32,124,140 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 640 | h | /**@file ObserveBI.h
* @brief OSM의 BI 정의.
* @author siva
*/
#ifndef OBSERVE_BI_H
#define OBSERVE_BI_H
/**@ingroup GroupOSM
* @class CObserveBI
* @brief Observe Manager 의 Button Interface.
* @remarks 인터페이다.
*/
class CObserveBI
{
public :
/**@brief 프로세스 실행 감시를 시작한다. */
virtual void StartProcessObservation() = 0;
/**@brief 프로세스 실행 감시를 중지한다. */
virtual void StopProcessObservation() = 0;
/**@brief 실행된 프로세스 이름을 OSM에게 알린다. */
virtual void ReceiveExecutedProcess(CString a_executedProcess) = 0;
};
#endif | [
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
]
| [
[
[
1,
25
]
]
]
|
b927dead5200d5a0d6fd58742472b4ae136afc1e | 06cd635b4405c890cdf2d71f2138f632737ca4f9 | /tp2/src/main.cpp | 8a898aceb1d4ffdb5abe8fb13c3e66d47be0de40 | []
| no_license | MatiasJAco/sg6671-tp1-g2 | 7a84311b9d2ab6f7678cfeeacdc97ea71e55c701 | 59ed875a6d1e36c7e33e6a00fdbb7c9a6be26cbb | refs/heads/master | 2020-04-01T23:12:06.859230 | 2011-06-17T11:10:44 | 2011-06-17T11:10:44 | 32,540,156 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 23,393 | cpp | //#include <GL/gl.h>
//#include <GL/glu.h>
#define GLUT_DISABLE_ATEXIT_HACK
#include <GL/glut.h>
#include <math.h>
#include "spline_test/spline.h"
#include "bezier_test/bezier.h"
#include "globals.h"
#include <cstdio>
//Testing 3D:
#define SSOLID_H 1
GLuint dl_3D;
GLfloat window_size[2];
#define W_WIDTH window_size[0]
#define W_HEIGHT window_size[1]
int textureRepeatX=1;
int textureRepeatY=1;
//Algunas variables globales usadas para bezier
int puntos = 0;
bool primera=false;
vector <tVertice> controlBezier; // puntos de control Bezier
int contControl = 0; //Contadores
int cuentaTramos = 0;
GLfloat ctrlpointsBez[4][3];
//Puntos de control de la spline.
//vector<float> ctlVectorSpline;
// Variables que controlan la ubicación de la cámara en la Escena 3D
float eye[3] = {3.0, -1.2, 2};
float at[3] = { 0.0, 0.0, 0.0};
float up[3] = { 0.0, 0.0, 1.0};
// Variables asociadas a única fuente de luz de la escena
float light_color[4] = {1.0f, 1.0f, 1.0f, 1.0f};
float light_position[4] = {1.5f, 0.0f, 0.0f,0.0f};
float light_ambient[4] = {0.05f, 0.05f, 0.05f, 1.0f};
// Variables de control
bool view_grid = true;
bool view_axis = true;
bool edit_panelA = true;
bool edit_panelB = true;
bool superficieBezier=false;
// Handle para el control de las Display Lists
GLuint dl_handle;
#define DL_AXIS (dl_handle+0)
#define DL_GRID (dl_handle+1)
#define DL_AXIS2D_TOP (dl_handle+2)
//#define DL_SBEZIER (dl_handle+3)
// Tamaño de la ventana
#define TOP_VIEWA_POSX ((int)((float)W_WIDTH-W_HEIGHT*0.40f))
#define TOP_VIEWA_W ((int)((float)W_HEIGHT*0.35f))
#define TOP_VIEWA_POSY ((int)((float)W_HEIGHT*0.60f))
#define TOP_VIEWA_H ((int)((float)W_HEIGHT*0.35f))
#define TOP_VIEWB_POSX ((int)((float)W_WIDTH-W_HEIGHT*0.40f))
#define TOP_VIEWB_W ((int)((float)W_HEIGHT*0.35f))
#define TOP_VIEWB_POSY ((int)((float)W_HEIGHT*0.20f))
#define TOP_VIEWB_H ((int)((float)W_HEIGHT*0.35f))
//TEXTURA
void makeCheckImage(void)
{
int i, j, c;
for (i = 0; i < checkImageHeight; i++) {
for (j = 0; j < checkImageWidth; j++) {
c = ((((i&0x8)==0)^((j&0x8))==0))*255;
if ((i&0x8)==0){
if ((j&0x8)==0){
checkImage[i][j][0] = (GLubyte) 0;
checkImage[i][j][1] = (GLubyte) 0;
checkImage[i][j][2] = (GLubyte) 0;
checkImage[i][j][3] = (GLubyte) 255;
}
else{
checkImage[i][j][0] = (GLubyte) 0;
checkImage[i][j][1] = (GLubyte) 0;
checkImage[i][j][2] = (GLubyte) 255;
checkImage[i][j][3] = (GLubyte) 255;
}
}
else{
if ((j&0x8)==0){
checkImage[i][j][0] = (GLubyte) 255;
checkImage[i][j][1] = (GLubyte) 0;
checkImage[i][j][2] = (GLubyte) 0;
checkImage[i][j][3] = (GLubyte) 255;
}
else{
checkImage[i][j][0] = (GLubyte) 255;
checkImage[i][j][1] = (GLubyte) 255;
checkImage[i][j][2] = (GLubyte) 255;
checkImage[i][j][3] = (GLubyte) 255;
}
}
}
}
}
/*void OnIdle (void)
{
rotate += 0.1;
if(rotate > 360.0) rotate_sphere = 0.0;
glutPostRedisplay();
}
*/
void Avanzar(int value) {
float displacement_error;
rotation = (rotation + ROTATION_STEP) % 360;
displacement_error=at[1]-target*SOLIDS_SEPARATION;
if(fabsf(displacement_error)>DISPLACEMENT_TOLERANCE)
if (displacement_error < 0){
at[1]+=DISPLACEMENT_STEP;
eye[1]+=DISPLACEMENT_STEP;
}
else{
at[1]-=DISPLACEMENT_STEP;
eye[1]-=DISPLACEMENT_STEP;
}
if (animation == true)
glutTimerFunc(MS,Avanzar,1);
glutPostRedisplay();
}
bool isInRangeA(int x, int y){
bool result = false;
if((x >= TOP_VIEWA_POSX)&&(x <= TOP_VIEWA_POSX+TOP_VIEWA_W)&&(y >= TOP_VIEWA_POSY)&&(y <=(TOP_VIEWA_POSY+TOP_VIEWA_H)))
result=true;
return result;
}
bool isInRangeB(int x, int y){
bool result = false;
if((x >= TOP_VIEWB_POSX)&&(x <= TOP_VIEWB_POSX+TOP_VIEWB_W)&&(y >= TOP_VIEWB_POSY)&&(y <=(TOP_VIEWB_POSY+TOP_VIEWB_H)))
result=true;
return result;
}
bool isInRange(int x, int y){
bool result=false;
if( isInRangeA(x,y) || isInRangeB(x,y) )
result = true;
return result;
}
float convCoorXPanelA(GLint xMouse){
float valor;
valor=((float)(xMouse-TOP_VIEWA_POSX))/TOP_VIEWA_W;
return valor;
}
float convCoorXPanelB(GLint xMouse){
float valor;
valor=((float)(xMouse-TOP_VIEWB_POSX))/TOP_VIEWB_W;
return valor;
}
float convCoorYPanelA(GLint yMouse){
float valor;
valor=((float)(yMouse-TOP_VIEWA_POSY))/TOP_VIEWA_H;
return valor;
}
float convCoorYPanelB(GLint yMouse){
float valor;
valor=((float)(yMouse-TOP_VIEWB_POSY))/TOP_VIEWB_H;
return valor;
}
void curvaBezier(){
if(!controlBezier.empty()){
if(contControl >3 ||(primera && contControl>2)){
cuentaTramos++;
contControl=0;
primera=true;
}
for(int t=0;t<cuentaTramos;t++){
for (int j=0;j<4; j++){
ctrlpointsBez[j][0]=controlBezier[(j+t*3)].x;
ctrlpointsBez[j][1]=controlBezier[(j+t*3)].y;
ctrlpointsBez[j][2]=0.0;
}
glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, 3, 4, &ctrlpointsBez[0][0]);
glMapGrid1f(600, 0.0, 1.0);
glEnable(GL_MAP1_VERTEX_3);
glColor3f(1.0, 1.0, 0.0);
glEvalMesh1(GL_LINE, 0, 600);
/* Dibuja puntos de control*/
glPointSize(5.0);
glBegin(GL_POINTS);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(controlBezier[0+t*3].x,controlBezier[0+t*3].y,0);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(controlBezier[1+t*3].x,controlBezier[1+t*3].y,0);
glVertex3f(controlBezier[2+t*3].x,controlBezier[2+t*3].y,0);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(controlBezier[3+t*3].x,controlBezier[3+t*3].y,0);
glEnd();
};
};
}
void drawSolidRevolution(){
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
// glDisable(GL_LIGHTING);
glColor3f(1.0,1.0,0.5);
glPushMatrix();
// glScalef(2.0,2.0,2.0);
dibujaSupBezier(&controlBezier[0],0.125,10,cuentaTramos);
glPopMatrix();
// glEnable(GL_LIGHTING);
}
void drawSolidSweep(vector<float> & ctlVector){
vector<float> pointsVector;
float * coordsArray;
size_t i;
float step=0.1;
vector<float> ultimoPunto; //xcoord,ycoord
vector<float> penultimoPunto; //xcoord,ycoord
float textureStep;
pointsVector=calcularPuntosSplineEquiespaciados2D(ctlVector,step);
coordsArray=new float[pointsVector.size()/4*16];//3Coord,3Norm,2Text
//coeficiente de texturas:
ultimoPunto.push_back(pointsVector[pointsVector.size()-4]);
ultimoPunto.push_back(pointsVector[pointsVector.size()-3]);
penultimoPunto.push_back(pointsVector[pointsVector.size()-8]);
penultimoPunto.push_back(pointsVector[pointsVector.size()-7]);
textureStep=step*textureRepeatX/((pointsVector.size()/4 -2) * step + distancia2D(ultimoPunto,penultimoPunto));
for (i=0; i < pointsVector.size()/4; i++){
//CoordInferior
coordsArray[i*16+0]=pointsVector[i*4];
coordsArray[i*16+1]=pointsVector[i*4+1];
coordsArray[i*16+2]=0;
//Normal
coordsArray[i*16+3]=pointsVector[i*4+2];
coordsArray[i*16+4]=pointsVector[i*4+3];
coordsArray[i*16+5]=0;
//TexCoord
coordsArray[i*16+6]=i*textureStep;
coordsArray[i*16+7]=0;
//CoordSuperior
coordsArray[i*16+8]=pointsVector[i*4];
coordsArray[i*16+9]=pointsVector[i*4+1];
coordsArray[i*16+10]=SSOLID_H;
//Normal
coordsArray[i*16+11]=pointsVector[i*4+2];
coordsArray[i*16+12]=pointsVector[i*4+3];
coordsArray[i*16+13]=0;
//TexCoord
coordsArray[i*16+14]=i*textureStep;
coordsArray[i*16+15]=textureRepeatY;
}
//Corrijo la ultima textura:
--i;
coordsArray[i*16+6]=textureRepeatX;
coordsArray[i*16+14]=textureRepeatX;
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
// glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, texName);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3,GL_FLOAT,8*sizeof(float),coordsArray);
glNormalPointer(GL_FLOAT,8*sizeof(float),&coordsArray[3]);
glTexCoordPointer(2,GL_FLOAT,8*sizeof(float),&coordsArray[6]);
glColor3f(1,1,1);
glPushMatrix();
glTranslatef(-0.5,-0.5,0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, pointsVector.size()/4*2);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
delete coordsArray;
}
void dibujaSupBezier(tVertice* ptosControl, float paso, float angulo, int tramos){
vector<float> Vertices ;
float* coordsArray;
tVertice ptosControlUsados [4];
tPunto planoNormal;
planoNormal.x = 1;
planoNormal.y = 0;
planoNormal.z = 0;
angulo=10;
float textureStepX = (angulo/360)*textureRepeatX;
float textureStepY = (paso/tramos)*textureRepeatY;
float posTexturestepX = 0;
for(float giro =angulo;giro <= 360;giro+=angulo){
for(int j=0;j<tramos;j++){
//Carga puntos del tramo
ptosControlUsados[0] = ptosControl[0+(j*3)];
ptosControlUsados[1] = ptosControl[1+(j*3)];
ptosControlUsados[2] = ptosControl[2+(j*3)];
ptosControlUsados[3] = ptosControl[3+(j*3)];
for(float u=0.0;u<= 1.0 ;u+=paso){
//Primer punto para dibujar
tPunto punto0 =calcularPuntoDeBezier(u, ptosControlUsados);
punto0=rotarPunto((giro-angulo), punto0);
//Calculo normal del punto
tPunto normal0 = calcularNormal(u,ptosControlUsados,planoNormal);
normal0=rotarPunto((giro-angulo), normal0);
//Primer punto rotado
tPunto punto2 = rotarPunto(giro, punto0);
tPunto normal2 = rotarPunto(giro, normal0);
//Guardo los puntos
Vertices.push_back(punto0.x);
Vertices.push_back(punto0.y);
Vertices.push_back(punto0.z);
Vertices.push_back(normal0.x);
Vertices.push_back(normal0.y);
Vertices.push_back(normal0.z);
Vertices.push_back(punto2.x);
Vertices.push_back(punto2.y);
Vertices.push_back(punto2.z);
Vertices.push_back(normal2.x);
Vertices.push_back(normal2.y);
Vertices.push_back(normal2.z);
}
}
//Graficar
coordsArray=new float[(Vertices.size()/6)*8];//3Coord,3Norm,2Text
for(size_t i=0;i<Vertices.size()/12;i++){
//Punto
coordsArray[0+(i*16)] = Vertices[0+(i*12)];
coordsArray[1+(i*16)] = Vertices[1+(i*12)];
coordsArray[2+(i*16)] = Vertices[2+(i*12)];
//Normal
coordsArray[3+(i*16)] = Vertices[3+(i*12)];
coordsArray[4+(i*16)] = Vertices[4+(i*12)];
coordsArray[5+(i*16)] = Vertices[5+(i*12)];
//Coordenada Textura.
coordsArray[6+(i*16)] = posTexturestepX;
coordsArray[7+(i*16)] = i*textureStepY;
//Punto
coordsArray[8+(i*16)] = Vertices[6+(i*12)];
coordsArray[9+(i*16)] = Vertices[7+(i*12)];
coordsArray[10+(i*16)] = Vertices[8+(i*12)];
//Normal
coordsArray[11+(i*16)] = Vertices[9+(i*12)];
coordsArray[12+(i*16)] = Vertices[10+(i*12)];
coordsArray[13+(i*16)] = Vertices[11+(i*12)];
//Coordenada Textura.
coordsArray[14+(i*16)] = posTexturestepX + textureStepX;
coordsArray[15+(i*16)] = i*textureStepY;
}
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
// glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, texName);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3,GL_FLOAT,8*sizeof(float),coordsArray);
glNormalPointer(GL_FLOAT,8*sizeof(float),&coordsArray[3]);
glTexCoordPointer(2,GL_FLOAT,8*sizeof(float),&coordsArray[6]);
glColor3f(1,1,1);
glPushMatrix();
// glTranslatef(-0.5,-0.5,0);
glDrawArrays(GL_TRIANGLE_STRIP,0,Vertices.size()/6);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
Vertices.clear();
posTexturestepX+=textureStepX;
}
glDisableClientState(GL_VERTEX_ARRAY);
delete coordsArray;
}
void normalsTest(vector<float> & ctlVector){
vector<float> base;
vector<float> normal;
size_t i;
glPushMatrix();
glTranslatef(-0.5,-0.5,0);
glBegin(GL_LINES);
for(i=0;i<ctlVector.size()/2;i++){
base=splinePoint2D(i,ctlVector);
normal=splineNormal2D(i,ctlVector);
glVertex2fv(&base[0]);
glVertex2f(base[0]+normal[0],base[1]+normal[1]);
}
glEnd();
glPopMatrix();
}
void drawPanelACurve(){
vector<float> panelASpline;
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPointSize(5.0);
glColor3f(0, 0.8, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2,GL_FLOAT,0,&ctlVectorSpline[0]);
glDrawArrays(GL_POINTS,0,ctlVectorSpline.size()/2);
panelASpline=calcularPuntosSpline(ctlVectorSpline);
glColor3f(1, 1, 0.5);
glVertexPointer(2,GL_FLOAT,0,&panelASpline[0]);
glDrawArrays(GL_LINE_LOOP,0,panelASpline.size()/2);
}
void puntosDeBezier(int x, int y){
int limit;
if(!primera)
limit=4;
else
limit=3;
if (contControl <limit){
tVertice nuevoPunto;
nuevoPunto.x = convCoorXPanelB(x);
nuevoPunto.y = convCoorYPanelB(y);
controlBezier.push_back(nuevoPunto);
contControl++;
}
}
void DrawAxis()
{
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
// X
glColor3f(1.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(15.0, 0.0, 0.0);
// Y
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 15.0, 0.0);
// Z
glColor3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 0.0, 0.0);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 15.0);
glEnd();
glEnable(GL_LIGHTING);
}
void DrawAxis2DTopView()
{
glDisable(GL_LIGHTING);
glBegin(GL_LINE_LOOP);
// X
glColor3f(0.0, 0.5, 1.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glBegin(GL_QUADS);
glColor3f(0.1, 0.1, 0.1);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glEnable(GL_LIGHTING);
}
void DrawXYGrid()
{
int i;
glDisable(GL_LIGHTING);
glColor3f(0.15, 0.1, 0.1);
glBegin(GL_LINES);
for(i=-20; i<21; i++)
{
glVertex3f(i, -20.0, 0.0);
glVertex3f(i, 20.0, 0.0);
glVertex3f(-20.0, i, 0.0);
glVertex3f( 20.0, i, 0.0);
}
glEnd();
glEnable(GL_LIGHTING);
}
void Set3DEnv()
{
glViewport (0, 0, (GLsizei) W_WIDTH, (GLsizei) W_HEIGHT);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(60.0, (GLfloat) W_WIDTH/(GLfloat) W_HEIGHT, 0.10, 100.0);
}
void SetPanelTopEnvA()
{
glViewport (TOP_VIEWA_POSX, TOP_VIEWA_POSY, (GLsizei) TOP_VIEWA_W, (GLsizei) TOP_VIEWA_H);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluOrtho2D(0, 1, 0, 1);
}
void SetPanelTopEnvB()
{
glViewport (TOP_VIEWB_POSX, TOP_VIEWB_POSY,
(GLsizei) TOP_VIEWB_W, (GLsizei) TOP_VIEWB_H);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluOrtho2D(0, 1, 0, 1);
}
void init(void)
{
//Iniciacion de Textura
makeCheckImage();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &texName);
glBindTexture(GL_TEXTURE_2D, texName);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth,
checkImageHeight,0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage);
//Asignacion de las listas:
dl_handle = glGenLists(3);
dl_curvaSpline=glGenLists(1);
dl_curvaBezier=glGenLists(1);
// dl_3D=glGenLists(1);//XXX:VARIABLE DE PRUEBA
glClearColor (0.02, 0.02, 0.04, 0.0);
glShadeModel (GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_ambient);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
// Generación de las Display Lists
glNewList(DL_AXIS, GL_COMPILE);
DrawAxis();
glEndList();
glNewList(DL_GRID, GL_COMPILE);
DrawXYGrid();
glEndList();
glNewList(DL_AXIS2D_TOP, GL_COMPILE);
DrawAxis2DTopView();
glEndList();
// glNewList(DL_SBEZIER, GL_COMPILE);
// DrawSupBezier();
// glEndList();
}
void display(void)
{
deque<GLuint>::iterator it;
deque<GLuint>::iterator itEnd;
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
///////////////////////////////////////////////////
// Escena 3D
Set3DEnv();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt (eye[0], eye[1], eye[2], at[0], at[1], at[2], up[0], up[1], up[2]);
if (view_axis)
glCallList(DL_AXIS);
if (view_grid)
glCallList(DL_GRID);
//
///////////////////////////////////////////////////
///
///Spline 3D
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_DIFFUSE);
glCallList(dl_3D);
glPushMatrix();
for (it=solidsList.begin(), itEnd=solidsList.end(); it!=itEnd; it++){
glPushMatrix();
glRotatef(rotation,0,0,1);
glCallList(*it);
glPopMatrix();
glTranslatef(0,SOLIDS_SEPARATION,0);
}
glPopMatrix();
////////////////////////////////////////////////////
//light:
glBegin(GL_POINTS);
glVertex3fv(light_position);
glEnd();
///////////////////////////////////////////////////
// Panel 2D para la vista superior
if (edit_panelA)
{
glDisable(GL_COLOR_MATERIAL);
SetPanelTopEnvA();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt (0, 0, 0.5, 0, 0, 0, 0, 1, 0);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
// glColorMaterial(GL_FRONT, GL_DIFFUSE);
/*Round Points??*/
glDisable(GL_LIGHTING);
glCallList(dl_curvaSpline);
glEnable(GL_LIGHTING);
glCallList(DL_AXIS2D_TOP);
}
if (edit_panelB)
{
glEnable(GL_COLOR_MATERIAL);
// glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
SetPanelTopEnvB();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt (0, 0, 0.5, 0, 0, 0, 0, 1, 0);
glDisable(GL_LIGHTING);
curvaBezier();
glEnable(GL_LIGHTING);
glCallList(DL_AXIS2D_TOP);
}
//
///////////////////////////////////////////////////
glutSwapBuffers();
}
void reshape (int w, int h)
{
W_WIDTH = w;
W_HEIGHT = h;
}
void keyboard (unsigned char key, int x, int y)
{
switch (key) {
case 'q':
exit(0);
break;
case 'u':
view_grid = !view_grid;
glutPostRedisplay();
break;
case 'r':
view_axis = !view_axis;
glutPostRedisplay();
break;
case '4':
dl_3D=glGenLists(1);
if (!ctlVectorSpline.empty()){
solidsList.push_back(glGenLists(1));
glNewList(solidsList.back(), GL_COMPILE);
drawSolidSweep(ctlVectorSpline);
//normalsTest(ctlVectorSpline);
glEndList();
ctlVectorSpline.clear();
drawPanelACurve();
target=solidsList.size()-1;
}
glutPostRedisplay();
break;
case '3':
dl_3D=glGenLists(1);
if ( !controlBezier.empty() ){
solidsList.push_back(glGenLists(1));
glNewList(solidsList.back(), GL_COMPILE);
drawSolidRevolution();
glEndList();
cuentaTramos = 0;
contControl=0;
primera=false;
controlBezier.clear();
curvaBezier();
target=solidsList.size()-1;
}
glutPostRedisplay();
break;
case '1':
edit_panelA = !edit_panelA;
glutPostRedisplay();
break;
case '2':
edit_panelB = !edit_panelB;
glutPostRedisplay();
break;
case '5':
textureRepeatX++;
printf("Horizontal : %i\n",textureRepeatX);
break;
case '6':
if(textureRepeatX>1)
textureRepeatX--;
printf("Horizontal : %i\n",textureRepeatX);
break;
case '7':
textureRepeatY++;
printf("Vertical : %i\n",textureRepeatY);
break;
case 'y':
if(textureRepeatY>1)
textureRepeatY--;
printf("Vertical : %i\n",textureRepeatY);
break;
case '8':
if (animation == true)
animation=false;
else{
animation=true;
eye[0] = 3.0;
eye[1] = -1.2;
eye[2] = 3.0;
at[0] = 0.0;
at[1] = 0.0;
at[2] = 0.0;
up[0] = 0.0;
up[1] = 0.0;
up[2] = 1.0;
}
case '9':
if(target>0){
target--;
}
break;
case '0':
if(target<solidsList.size()-1 && !solidsList.empty()){
target++;
}
break;
case 'w':
eye[0]+=1;
glutPostRedisplay();
break;
case 's':
eye[0]-=1;
glutPostRedisplay();
break;
case 'a':
eye[1]-=1;
glutPostRedisplay();
break;
case 'd':
eye[1]+=1;
glutPostRedisplay();
break;
case 'z':
eye[2]-=1;
glutPostRedisplay();
break;
case 'x':
eye[2]+=1;
glutPostRedisplay();
break;
case 't':
at[0]+=1;
glutPostRedisplay();
break;
case 'g':
at[0]-=1;
glutPostRedisplay();
break;
case 'f':
at[1]-=1;
glutPostRedisplay();
break;
case 'h':
at[1]+=1;
glutPostRedisplay();
break;
case 'c':
at[2]-=1;
glutPostRedisplay();
break;
case 'v':
at[2]+=1;
glutPostRedisplay();
break;
case 'i':
up[0]+=1;
glutPostRedisplay();
break;
case 'k':
up[0]-=1;
glutPostRedisplay();
break;
case 'j':
up[1]-=1;
glutPostRedisplay();
break;
case 'l':
up[1]+=1;
glutPostRedisplay();
break;
case 'n':
up[2]-=1;
glutPostRedisplay();
break;
case 'm':
up[2]+=1;
glutPostRedisplay();
break;
default:
break;
}
}
void mousePtPlot (GLint button, GLint action, GLint xMouse, GLint yMouse) {
int coorY=W_HEIGHT-yMouse;
if(button == GLUT_LEFT_BUTTON && action == GLUT_DOWN){
//Si esta en el panel B,almacena puntos para Bezier
if(isInRangeB(xMouse,coorY)){
puntosDeBezier(xMouse,coorY);
}
else if(isInRangeA(xMouse,coorY)){
//Cargo el punto;
ctlVectorSpline.push_back(convCoorXPanelA(xMouse));
ctlVectorSpline.push_back(convCoorYPanelA(coorY));
//Rehago la display list
glNewList(dl_curvaSpline, GL_COMPILE);
drawPanelACurve();
glEndList();
}
else{/*posible funcion para 3Dviewport*/}
}
glutPostRedisplay();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
W_WIDTH=glutGet(GLUT_SCREEN_WIDTH);
W_HEIGHT=glutGet(GLUT_SCREEN_HEIGHT);
glutInitWindowSize (W_WIDTH, W_HEIGHT);
glutInitWindowPosition (0, 0);
glutCreateWindow (argv[0]);
glutFullScreen();
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMouseFunc(mousePtPlot);
// glutIdleFunc(OnIdle);
glutTimerFunc(MS,Avanzar,1);
glutMainLoop();
return 0;
}
| [
"[email protected]@8c9cdbba-f223-9568-bec3-c68b3cb6d8cf",
"matiasJA@8c9cdbba-f223-9568-bec3-c68b3cb6d8cf"
]
| [
[
[
1,
2
],
[
4,
18
],
[
30,
48
],
[
50,
55
],
[
57,
58
],
[
60,
140
],
[
142,
144
],
[
226,
228
],
[
230,
232
],
[
234,
234
],
[
236,
258
],
[
260,
310
],
[
312,
318
],
[
424,
425
],
[
427,
427
],
[
429,
464
],
[
478,
502
],
[
504,
552
],
[
554,
567
],
[
569,
610
],
[
614,
630
],
[
632,
633
],
[
635,
638
],
[
640,
642
],
[
644,
654
],
[
656,
661
],
[
663,
688
],
[
691,
694
],
[
698,
701
],
[
703,
718
],
[
720,
744
],
[
747,
748
],
[
750,
752
],
[
759,
760
],
[
764,
771
],
[
790,
892
],
[
895,
895
],
[
900,
910
],
[
912,
912
],
[
915,
920
],
[
922,
922
],
[
924,
926
],
[
928,
929
],
[
931,
936
]
],
[
[
3,
3
],
[
19,
29
],
[
49,
49
],
[
56,
56
],
[
59,
59
],
[
141,
141
],
[
145,
225
],
[
229,
229
],
[
233,
233
],
[
235,
235
],
[
259,
259
],
[
311,
311
],
[
319,
423
],
[
426,
426
],
[
428,
428
],
[
465,
477
],
[
503,
503
],
[
553,
553
],
[
568,
568
],
[
611,
613
],
[
631,
631
],
[
634,
634
],
[
639,
639
],
[
643,
643
],
[
655,
655
],
[
662,
662
],
[
689,
690
],
[
695,
697
],
[
702,
702
],
[
719,
719
],
[
745,
746
],
[
749,
749
],
[
753,
758
],
[
761,
763
],
[
772,
789
],
[
893,
894
],
[
896,
899
],
[
911,
911
],
[
913,
914
],
[
921,
921
],
[
923,
923
],
[
927,
927
],
[
930,
930
]
]
]
|
f695e84ec1945270f504ba37116109338a920e2d | 6465630c9428b9ac8edfd64c317304555714f26f | /VS2008Projs/TrungNew/NetworkTesting/ClientTest/echoClient.cpp | fe0f4ad197cf16a42c41743137c113deeae57e23 | []
| no_license | vchu/ee125 | 738f51cd0b9ab41b936dbc1ce9da803acd35c1c2 | 59f9a1f84c08cfbe18bc844364c8df24294e8c1e | refs/heads/master | 2021-01-13T01:49:00.218357 | 2008-11-20T23:49:03 | 2008-11-20T23:49:03 | 34,265,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | cpp | #include "..\Socket\_Socket.h"
#include <iostream>
using namespace std;
int main() {
try {
SocketClient s("localhost", 2000);
while (1) {
string l ;//= s.ReceiveLine();
std::cin>>l;
s.SendLine(l);
// if (l.empty()) break;
//cout << l;
// cout.flush();
}
}
catch (const char* s) {
cerr << s << endl;
}
catch (std::string s) {
cerr << s << endl;
}
catch (...) {
cerr << "unhandled exception\n";
}
int blah;
std::cin>> blah;
return 0;
}
| [
"[email protected]@c7e5bc68-916c-11dd-99c3-0167725eca9f"
]
| [
[
[
1,
34
]
]
]
|
5421468fa37ab1ad10385dbcab2371da97707f51 | 116e286b7d451d30fd5d9a3ce9b3013b8d2c1a0c | /programui/ProgramUI.cpp | 8b07c752e7dbc021431cbc3a640fc85329d2781b | []
| no_license | savfod/robolang | 649f2db0f773e3ad5be58c433920dff7aadfafd0 | f97446db5405d3e17b29947fc5b61ab05ef1fa24 | refs/heads/master | 2021-01-10T04:07:06.895016 | 2009-11-17T19:54:23 | 2009-11-17T19:54:23 | 48,452,157 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 4,373 | cpp | // ProgramUI.cpp: implementation of the CProgramUI class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ProgramUI.h"
#include "../Program/Program.h"
#include "..\control\Control.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
CProgramUI::CProgramUI( IEditWindow *p_iw )
: iw( p_iw )
{
procedure = NULL;
isProcessUpdates = true;
}
CProgramUI::~CProgramUI()
{
}
void CProgramUI::skipUpdates()
{
isProcessUpdates = false;
}
void CProgramUI::restoreUpdates()
{
isProcessUpdates = true;
}
/*#########################################################################*/
/*#########################################################################*/
void CProgramUI::onControlProcActivated( CString name )
{
procName = name;
//finding CProgram, "singleton"
CProgram *program = IControl::getInstance() -> getCProgram();
// refresh view
iw -> removeAllCommands();
procedure = program -> getProcedureByName( procName );
iw -> setProcedure( procedure );
}
/*#########################################################################*/
/*#########################################################################*/
void CProgramUI::onProgramNew()
{
if( !isProcessUpdates )
return;
//finding CProgram, "singleton"
CProgram *program = IControl::getInstance() -> getCProgram();
// refresh view
iw -> removeAllCommands();
procedure = program -> getMainProcedure();
iw -> setProcedure( procedure );
}
void CProgramUI::onProgramChanged()
{
if( !isProcessUpdates )
return;
//finding CProgram, "singleton"
CProgram *program = IControl::getInstance() -> getCProgram();
// refresh view
iw -> removeAllCommands();
procedure = program -> getMainProcedure();
iw -> setProcedure( procedure );
//notify Doc
onSmthChanged();
}
void CProgramUI::onProgramProcRenamed( CProcedure *p )
{
if( !isProcessUpdates )
return;
if( procedure == p )
{
procName = p -> name;
iw -> notifyProcRenamed( p );
}
//notify Doc
onSmthChanged();
}
void CProgramUI::onProgramProcDeleted( CString name )
{
if(name == procName)
{
CProgram *program = IControl::getInstance() -> getCProgram();
procedure = program -> getMainProcedure();
procName = procedure -> name;
iw -> removeAllCommands();
iw -> setProcedure( procedure );
}
//notify Doc
onSmthChanged();
}
/*#########################################################################*/
/*#########################################################################*/
void CProgramUI::onEditAdd( CCommand *cmd , CCommand *parent , CCommand *before )
{
skipUpdates();
procedure -> addCommand( cmd , parent , before );
restoreUpdates();
iw -> setProcedure( procedure );
//notify Doc
onSmthChanged();
}
void CProgramUI::onEditUpdate( CCommand *cmd , CCommand *cmdData )
{
// cannot update compound to simple if have childs
if( cmd -> isCompound() && cmdData -> isCompound() == false && cmd -> childCommands.GetSize() > 0 )
{
IControl::getInstance() -> messageBox( "Нельзя изменить составной оператор на обычный, если созданы вложенные команды" );
return;
}
// copy props
skipUpdates();
cmd -> setProps( cmdData );
restoreUpdates();
// refresh view
iw -> setProcedure( procedure );
//notify Doc
onSmthChanged();
}
void CProgramUI::onEditDelete( CCommand *cmd )
{
skipUpdates();
procedure -> deleteCommand( cmd );
restoreUpdates();
// refresh view
iw -> setProcedure( procedure );
//notify Doc
onSmthChanged();
}
/*#########################################################################*/
/*#########################################################################*/
void CProgramUI::onProgramOpened(bool successful)
{
CControl* control = IControl::getInstance() -> getCControl();
if(successful)
control -> onProgNewProgram();
else
{
IControl::getInstance() -> messageBox( "Ошибка. Не удалось прочесть файл." );
control -> onAppNewProgram();
}
onProgramChanged();
}
void CProgramUI::onSmthChanged()
{
IControl::getInstance() -> onSmthChanged();
}
| [
"SAVsmail@11fe8b10-5191-11de-bc8f-bda5044519d4",
"savsmail@11fe8b10-5191-11de-bc8f-bda5044519d4",
"vsavchik@11fe8b10-5191-11de-bc8f-bda5044519d4"
]
| [
[
[
1,
8
],
[
10,
37
],
[
45,
45
],
[
54,
77
],
[
79,
84
],
[
95,
97
],
[
111,
113
],
[
116,
130
],
[
132,
132
],
[
147,
153
],
[
160,
166
],
[
180,
184
]
],
[
[
9,
9
],
[
167,
179
]
],
[
[
38,
44
],
[
46,
53
],
[
78,
78
],
[
85,
94
],
[
98,
110
],
[
114,
115
],
[
131,
131
],
[
133,
146
],
[
154,
159
]
]
]
|
db98da596f6806dd1ebf3046a1376ccfc2db736c | c1996db5399aecee24d81cd9975937d3c960fa6c | /src/treeitem.cpp | 5b55c2290ed6234c8a369466125d7d88e6371076 | []
| no_license | Ejik/Life-organizer | 7069a51a4a0dc1112b018f162c00f0292c718334 | 1954cecab75ffd4ce3e7ff87606eb11975ab872d | refs/heads/master | 2020-12-24T16:50:25.616728 | 2009-10-28T06:30:18 | 2009-10-28T06:30:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,629 | cpp | /*
treeitem.cpp
A container for items of data supplied by the simple tree model.
*/
#include <QStringList>
#include "treeitem.h"
//! [0]
TreeItem::TreeItem(const QVector<QVariant> &data, TreeItem *parent)
{
parentItem = parent;
itemData = data;
}
//! [0]
//! [1]
TreeItem::~TreeItem()
{
qDeleteAll(childItems);
}
//! [1]
//! [2]
TreeItem *TreeItem::child(int number)
{
return childItems.value(number);
}
//! [2]
//! [3]
int TreeItem::childCount() const
{
return childItems.count();
}
//! [3]
//! [4]
int TreeItem::childNumber() const
{
if (parentItem)
return parentItem->childItems.indexOf(const_cast<TreeItem*>(this));
return 0;
}
//! [4]
//! [5]
int TreeItem::columnCount() const
{
return itemData.count();
}
//! [5]
//! [6]
QVariant TreeItem::data(int column) const
{
return itemData.value(column);
}
//! [6]
//! [7]
bool TreeItem::insertChildren(int position, int count, int columns)
{
if (position < 0 || position > childItems.size())
return false;
for (int row = 0; row < count; ++row) {
QVector<QVariant> data(columns);
TreeItem *item = new TreeItem(data, this);
childItems.insert(position, item);
}
return true;
}
//! [7]
//! [8]
bool TreeItem::insertColumns(int position, int columns)
{
if (position < 0 || position > itemData.size())
return false;
for (int column = 0; column < columns; ++column)
itemData.insert(position, QVariant());
foreach (TreeItem *child, childItems)
child->insertColumns(position, columns);
return true;
}
//! [8]
//! [9]
TreeItem *TreeItem::parent()
{
return parentItem;
}
//! [9]
//! [10]
bool TreeItem::removeChildren(int position, int count)
{
if (position < 0 || position + count > childItems.size())
return false;
for (int row = 0; row < count; ++row)
delete childItems.takeAt(position);
return true;
}
//! [10]
bool TreeItem::removeColumns(int position, int columns)
{
if (position < 0 || position + columns > itemData.size())
return false;
for (int column = 0; column < columns; ++column)
itemData.remove(position);
foreach (TreeItem *child, childItems)
child->removeColumns(position, columns);
return true;
}
//! [11]
bool TreeItem::setData(int column, const QVariant &value)
{
if (column < 0 || column >= itemData.size())
return false;
itemData[column] = value;
return true;
}
//! [11]
| [
"[email protected]"
]
| [
[
[
1,
139
]
]
]
|
e19081d603fc75f432f9958e457660173cfff18f | 188058ec6dbe8b1a74bf584ecfa7843be560d2e5 | /GodDK/util/concurrent/locks/ReentrantLock.cxx | 72f9f545f699a339d6b15ac417c7adbc8241f28c | []
| no_license | mason105/red5cpp | 636e82c660942e2b39c4bfebc63175c8539f7df0 | fcf1152cb0a31560af397f24a46b8402e854536e | refs/heads/master | 2021-01-10T07:21:31.412996 | 2007-08-23T06:29:17 | 2007-08-23T06:29:17 | 36,223,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,943 | cxx | #ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "lang/Thread.h"
using goddk::lang::Thread;
#include "util/concurrent/locks/ReentrantLock.h"
using namespace goddk::util::concurrent::locks;
ReentrantLock::Cond::Cond(Object* lock) : lock(lock)
{
}
void ReentrantLock::Cond::await() throw (InterruptedExceptionPtr)
{
lock->wait(0);
}
void ReentrantLock::Cond::awaitUninterruptibly()
{
while (true)
{
try
{
lock->wait(0);
return;
}
catch (InterruptedException&)
{
}
}
}
void ReentrantLock::Cond::signal()
{
lock->notify();
}
void ReentrantLock::Cond::signalAll()
{
lock->notifyAll();
}
ReentrantLock::ReentrantLock(bool fair)
{
monitor = Monitor::getInstance(fair);
}
void ReentrantLock::lock()
{
Thread* t = Thread::currentThread();
if (t)
{
t->_state = Thread::BLOCKED;
t->_monitoring = monitor;
}
monitor->lock();
if (t)
{
t->_state = Thread::RUNNABLE;
t->_monitoring = t->monitor;
}
}
void ReentrantLock::lockInterruptibly() throw (InterruptedExceptionPtr)
{
bool interrupted = false;
Thread* t = Thread::currentThread();
if (t)
{
t->_state = Thread::BLOCKED;
t->_monitoring = monitor;
}
try
{
monitor->lockInterruptibly();
}
catch (InterruptedException&)
{
interrupted = true;
}
if (t)
{
t->_state = Thread::RUNNABLE;
t->_monitoring = t->monitor;
}
if (interrupted)
throw InterruptedException();
}
Condition* ReentrantLock::newCondition()
{
return new Cond(this);
}
bool ReentrantLock::tryLock()
{
bool result;
Thread* t = Thread::currentThread();
if (t)
{
t->_state = Thread::BLOCKED;
t->_monitoring = monitor;
}
result = monitor->tryLock();
if (t)
{
t->_state = Thread::RUNNABLE;
t->_monitoring = t->monitor;
}
return result;
}
void ReentrantLock::unlock()
{
monitor->unlock();
}
| [
"soaris@46205fef-a337-0410-8429-7db05d171fc8"
]
| [
[
[
1,
133
]
]
]
|
79cc8cb75c1811ea2e37e1c8613f359601406264 | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXNotesEditView.h | 2a3c0744f189c54c65f59e2514c56c6d0eb20935 | []
| no_license | weimingtom/sls | 7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8 | d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd | refs/heads/master | 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 12,535 | h | /////////////////////////////////////////////////////////////////////////////
// ==========================================================================
// Class Specification : COXNotesEditView
// ==========================================================================
// Header file : OXNotesEditView.h
// Version: 9.3
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at [email protected], or by calling 416-849-8900.
// //////////////////////////////////////////////////////////////////////////
// Desciption : Class COXNotesEditView is derived from CEditView
// and can have on the right or on the left side
// of the view an area to set bookmarks like we can set
// breakpoints in Visual Studio. The breakpoints can be
// of different type, so, every type has own image
// representation. The bookmarks is set on a char, not
// on the line. There are possibility to have up to 256
// types (images) of bookmarks. Bookmarks can be added,
// removed, updated. Some virtual functions provide additional
// customization. While the cursor is moving from client
// area to notes area or vicewersa, OnChangeCursor() virtual
// function called, so there is a possibility to get a position
// of the cursor and change the cursor to another one.
// Also when new bookmark is adding it calls OnSetBookmark()
// virtual function that can update the type of the book
// mark and must return TRUE, if the bookmark should be added,
// or FALSE to prevent adding of the bookmark.
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(_OXNOTESEDITVIEW_H__)
#define _OXNOTESEDITVIEW_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "OXMainRes.h"
#include "oxDllExt.h"
#include "UTB64Bit.h"
#define OX_NOTES_ALL -1
#ifndef OX_NOTES_BRUSH
#define OX_NOTES_BRUSH IDB_OX_NOTES
#endif
#ifndef OX_NOTES_WIDTH_DEFAULT
#define OX_NOTES_WIDTH_DEFAULT -1
#endif
#ifndef OX_NOTES_BOOKMARKS
#define OX_NOTES_BOOKMARKS IDB_OX_BOOKMARKS
#endif
#ifndef OX_NOTES_BOOKMARKS_SIZE
#define OX_NOTES_BOOKMARKS_SIZE 16
#endif
#ifndef OX_CURSOR_NOTES
#define OX_CURSOR_NOTES IDC_OX_CURSOR_NOTES
#endif
class OX_CLASS_DECL COXNotesEditView : public CEditView
{
protected:
// create from serialization only
// --- In :
// --- Out :
// --- Returns :
// --- Effect : Constructs the object
COXNotesEditView(UINT nSide=SIDE_LEFT,
UINT nWidth=OX_NOTES_WIDTH_DEFAULT, UINT nMode=MODE_BKMARKS);
DECLARE_DYNCREATE(COXNotesEditView)
public:
enum {MODE_BKMARKS, MODE_LINES};
enum {SIDE_NONE, SIDE_LEFT, SIDE_RIGHT};
enum {NONE, NOTES, EDIT};
enum {LENGTH_THESAME, LENGTH_MORE, LENGTH_LESS};
//functions
// --- In : clrText - new text color to be set
// --- Out :
// --- Returns :
// --- Effect : Call this function to set new text color
inline void SetTextColor(COLORREF clrText)
{
m_clrFont=clrText;
}
// --- In :
// --- Out :
// --- Returns : Current text color
// --- Effect : Call this function to get current text color
inline COLORREF GetTextColor() const
{
return m_clrFont;
}
// --- In : clrBkgnd - new background color of the client area to be set
// --- Out :
// --- Returns :
// --- Effect : Call this function to set new background color for the client area
inline void SetBackground(COLORREF clrBkgnd)
{
if (m_bshClient.m_hObject)
m_bshClient.DeleteObject();
VERIFY(m_bshClient.CreateSolidBrush(clrBkgnd));
}
// --- In :
// --- Out :
// --- Returns : Current background color of the client area
// --- Effect : Call this function to get background color of the client area
inline COLORREF GetBackground()
{
LOGBRUSH LogBrush;
m_bshClient.GetLogBrush(&LogBrush);
return LogBrush.lbColor;
}
// --- In : nSide - side where notes will be, either SIDE_LEFT or SIDE_RIGHT
// --- Out :
// --- Returns :
// --- Effect : Call this function to set side for the notes area
inline void SetNotesSide(UINT nSide=SIDE_LEFT)
{
m_nSide=nSide;
RedrawWindow();
}
// --- In : nWidth - width of the notes area in pixels,
// if the value is OX_NOTES_WIDTH_DEFAULT,
// the width will be equal of the width of
// vertical scrollbar
// --- Out :
// --- Returns :
// --- Effect : Call this function to set width of the notes area
inline void SetNotesWidth(UINT nWidth=OX_NOTES_WIDTH_DEFAULT)
{
m_nNotesWidth=nWidth;
RedrawWindow();
}
// --- In :
// --- Out :
// --- Returns : Side where notes area is located
// --- Effect : Call this function to get the area where the notes are located
inline UINT GetNotesSide() const
{
return m_nSide;
}
// --- In :
// --- Out :
// --- Returns : Width of the notes area
// --- Effect : Gets the notes width
inline UINT GetNotesWidth() const
{
return m_nNotesWidth;
}
// --- In : nSide - side where the notes will be inserted
// nWidth - width of the notes area
// --- Out :
// --- Returns :
// --- Effect : Inserts notes area
BOOL InsertNotes(UINT nSide=SIDE_LEFT, UINT nWidth=OX_NOTES_WIDTH_DEFAULT);
// --- In :
// --- Out :
// --- Returns :
// --- Effect : Deletes notes area and the bookmarks
void DeleteNotes();
// --- In :
// --- Out :
// --- Returns : Number of the bookmarks
// --- Effect : Returns number of the bookmarks
inline int GetBookmarksCount() const
{
return PtrToInt(m_arBookmarks.GetSize());
}
// --- In :
// --- Out :
// --- Returns : Bookmark by number
// --- Effect : Call this function to get the bookmark by number.
// The bookmark represents 32 bit value where 24 least
// significant bits means number of the character and
// 8 most significant bits represents type (number of the
// image in imagelist)
inline int GetBookmark(UINT nNumber) const
{
if (nNumber<(UINT) m_arBookmarks.GetSize())
return (int) m_arBookmarks.GetAt(nNumber);
else
return -1;
}
// --- In :
// --- Out :
// --- Returns : TRUE if the char is marked, FALSE otherwise
// --- Effect : Call this function to determine if the char is bookmarked.
BOOL IsMarked(UINT nChar) const;
// --- In :
// --- Out :
// --- Returns :
// --- Effect : Removes bookmarks
inline void ClearBookmarks()
{
m_arBookmarks.RemoveAll();
}
// --- In : nChar - bookmarked char to show
// --- Out :
// --- Returns :
// --- Effect : Makes scrolling to show the bookmark of the char
BOOL ShowBookmark(UINT nChar);
// --- In : nChar - number of the char from the beginig of
// the view to set bookmark
// nType - type of the bookmark
// --- Out :
// --- Returns :
// --- Effect : Sets bookmark
void SetBookmark(UINT nChar, BYTE nType=NULL);
// --- In : clrNotesBkgnd - color to be used for painting
// background area of the notes
// --- Out :
// --- Returns :
// --- Effect : Sets new background color for the notes
void SetNotesBackground(COLORREF clrNotesBkgnd);
// --- In : pBrush - a pointer to a brush object,
// a logical brush will be used to paint the background
// of the notes
// --- Out :
// --- Returns :
// --- Effect : Sets new background brush for the notes area
void SetNotesBackground(CBrush* pBrush);
// --- In :
// --- Out :
// --- Returns : a pointer to the brush that is used
// to paint the background of the notes
// --- Effect : Retrieves current background brush of the notes
inline const CBrush* GetNotesBackground() const
{
return &m_bshNotes;
}
// --- In :
// --- Out :
// --- Returns : A pointer to the image list that is used for
// drawing bookmarks
// --- Effect : Gets the bookmarks image list
inline CImageList* GetNotesImageList()
{
return &m_imgBookmarks;
}
// Operations
protected:
afx_msg LRESULT OnSetText(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnSetMargins(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnGetMargins(WPARAM wParam, LPARAM lParam);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(COXNotesEditView)
protected:
//}}AFX_VIRTUAL
// Implementation
public:
COLORREF GetLinesColor() const;
void SetLinesColor(COLORREF clr, BOOL bRedraw=TRUE);
const CFont* GetLinesFont() const;
BOOL SetLinesFont(CFont* pFont=NULL, BOOL bRedraw=TRUE);
UINT GetMode() const;
void SetMode(UINT nMode, BOOL bRedraw=TRUE);
virtual ~COXNotesEditView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
//functions
// --- In :
// --- Out :
// --- Returns :
// --- Effect : Initializes image list. Override this function if
// you want to load your own images.
virtual void LoadNotesImageList()
{
if (m_imgBookmarks.GetSafeHandle())
m_imgBookmarks.DeleteImageList();
m_imgBookmarks.Create(OX_NOTES_BOOKMARKS,
OX_NOTES_BOOKMARKS_SIZE,1,CLR_DEFAULT);
}
// --- In : nLine - line image will be searched for
// --- Out :
// --- Returns : Index of the image for the first bookmarked
// character in the line, if any.
// --- Effect : Returns image index for the first bookmarked
// character in the line if any
virtual int ImageFromLine(UINT nLine) const;
// --- In :
// --- Out :
// --- Returns :
// --- Effect : Draw bookmarks
virtual void DrawBookmarks(CDC* pDC);
// --- In : phCursor - a handle of the cursor will be set on
// nPosition - where the cursor is, either, NOTES or EDIT
// --- Out :
// --- Returns :
// --- Effect : The class calls this member every time the cursor
// has moved from the client area to the notes or vicewersa
// It is possible to change cursor handle at this time
virtual void OnChangeCursor(HCURSOR* phCursor, UINT nPosition);
// --- In : nChar - index of the char to set bookmark
// pType - a pointer to the type of bookmark will
// be set on
// --- Out :
// --- Returns :
// --- Effect : This function is called every time new bookmark will
// be set. You can change the type of the bookmark at this
// moment. Return TRUE to set bookmark, or FALSE to prevent it.
virtual BOOL OnSetBookmark(UINT nChar, DWORD* pType);
CSize GetBookmarkImageSize();
void GetNotesRect(LPRECT pRect);
int GetLineHeight();
int GetLastVisibleLine();
void RemoveBookmarks( UINT nStartChar, UINT nEndChar);
void OffsetBookmarks(UINT nStart, int nOffset);
protected:
//member variables
CString m_sCopy;
CBrush m_bshClient;
CImageList m_imgBookmarks;
CDWordArray m_arBookmarks;
CBrush m_bshNotes;
HCURSOR m_hNotesCursor;
COLORREF m_clrFont;
UINT m_nNotesWidth;
UINT m_nSide;
UINT m_nPosition;
UINT m_nMargins;
BOOL m_bUpdatingMargins;
// Generated message map functions
protected:
COLORREF m_clrLines;
CFont* m_pLinesFont;
UINT m_nMode;
//{{AFX_MSG(COXNotesEditView)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnChange();
afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(_OXNOTESEDITVIEW_H__)
| [
"[email protected]"
]
| [
[
[
1,
401
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.