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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
93cd351ae3556d962e00b35107252ccc9406d482 | 2f77d5232a073a28266f5a5aa614160acba05ce6 | /01.DevelopLibrary/04.SmsCode/InfoCenterOfSmartPhone_shiyong/MainWnd.h | 5d1cea8b1b792b392917656057bc8049cde0205e | [] | no_license | radtek/mobilelzz | 87f2d0b53f7fd414e62c8b2d960e87ae359c81b4 | 402276f7c225dd0b0fae825013b29d0244114e7d | refs/heads/master | 2020-12-24T21:21:30.860184 | 2011-03-26T02:19:47 | 2011-03-26T02:19:47 | 58,142,323 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,232 | h | #ifndef __MainWnd_h__
#define __MainWnd_h__
#include"NewSmsWnd.h"
// 按钮控件的ID
#define MZ_IDC_NewSmsBtn 101
// 从 CMzWndEx 派生的主窗口类
class CMainWnd: public CMzWndEx
{
MZ_DECLARE_DYNAMIC(CMainWnd);
public:
// 窗口中的按钮控件
UiButton m_btn;
CNewSmsWnd m_NewSmsWnd;
protected:
// 窗口的初始化
virtual BOOL OnInitDialog()
{
// 必须先调用基类的初始化
if (!CMzWndEx::OnInitDialog())
{
return FALSE;
}
// 初始化窗口中的控件
m_btn.SetButtonType(MZC_BUTTON_GREEN);
m_btn.SetPos(100,250,280,100);
m_btn.SetID(MZ_IDC_NewSmsBtn);
m_btn.SetText(L"发送短信");
m_btn.SetTextColor(RGB(255,255,255));
// 把控件添加到窗口中
AddUiWin(&m_btn);
return TRUE;
}
// 重载命令消息的处理函数
virtual void OnMzCommand(WPARAM wParam, LPARAM lParam)
{
UINT_PTR id = LOWORD(wParam);
switch(id)
{
case MZ_IDC_NewSmsBtn:
{
RECT rcWork = MzGetWorkArea();
m_NewSmsWnd.Create(rcWork.left,rcWork.top,RECT_WIDTH(rcWork),RECT_HEIGHT(rcWork), 0, 0, 0);
m_NewSmsWnd.Show();
}
break;
}
}
};
#endif //__MainWnd_h__ | [
"[email protected]"
] | [
[
[
1,
55
]
]
] |
c0695110be9394586be3a1d1979e11899f94cba2 | 740ed7e8d98fc0af56ee8e0832e3bd28f08cf362 | /src/game/megaman_demo/states/MegamanSlidingRight.cpp | c52c6cc4da813915b154b8a54e1ee5323561ba92 | [] | no_license | fgervais/armconsoledemogame | 420c53f926728b30fe1723733de2f32961a6a6d9 | 9158c0e684db16c4327b51aec45d1e4eed96b2d4 | refs/heads/master | 2021-01-10T11:27:43.912609 | 2010-07-29T18:53:06 | 2010-07-29T18:53:06 | 44,270,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,695 | cpp | /*
* MegamanSlidingLeft.cpp
*
* Created on: 2010-05-30
* Author: Basse
*/
#include "MegamanRunningRight.h"
#include "MegamanJumpingRight.h"
#include "MegamanSlidingRight.h"
#include "MegamanSlidingLeft.h"
#include "MegamanStandingRight.h"
#include "MegamanHitRight.h"
#include "Bitmap.h"
#include "Megaman.h"
#include "Physics.h"
#include "Environment.h"
#include <iostream>
using namespace std;
MegamanState* MegamanSlidingRight::instance = 0;
MegamanSlidingRight::MegamanSlidingRight(uint32_t animationWidth, uint32_t animationHeight, Bitmap** animationanimationFrames, uint32_t numberOfFrame, Bitmap** animationMasks)
: MegamanState(animationWidth, animationHeight, animationanimationFrames, numberOfFrame, animationMasks) {
}
MegamanSlidingRight::~MegamanSlidingRight() {
}
MegamanState* MegamanSlidingRight::getInstance() {
if(instance == 0) {
Bitmap** animationFrames = new Bitmap*[1];
animationFrames[0] = new Bitmap("src/display/state/MegamanSlidingRight/1.bmp");
Bitmap** animationMasks = new Bitmap*[1];
animationMasks[0] = new Bitmap("src/display/state/MegamanSlidingRight/mask1.bmp");
instance = new MegamanSlidingRight(38, 26, animationFrames, 1, animationMasks);
}
//instance->reset();
return instance;
}
/* BASE CLASS FUNCTION OVERRIDE */
void MegamanSlidingRight::jump(Megaman* sprite) {
sprite->setVelocityY(-sprite->getCurrentJumpPower());
sprite->setState(MegamanJumpingRight::getInstance());
}
//void MegamanSlidingRight::slide(Megaman* sprite) {
//sprite->setState(MegamanSlidingLeft::getInstance());
//}
//void MegamanSlidingRight::runRight(Megaman* sprite) {
//sprite->setState(MegamanRunningRight::getInstance());
//}
void MegamanSlidingRight::stopSliding(Megaman* sprite) {
sprite->setState(MegamanStandingRight::getInstance());
}
void MegamanSlidingRight::hit(Megaman* sprite) {
sprite->setState(MegamanHitRight::getInstance());
}
/*void MegamanSlidingRight::shot(Megaman* sprite) {
sprite->setState(MegamanRunningRightShot::getInstance());
}*/
void MegamanSlidingRight::initialize(Megaman* sprite) {
sprite->setVelocity(sprite->getCurrentSpeed()*2, 0);
}
void MegamanSlidingRight::update(Megaman* sprite) {
// If we loose contact with the ground, then we are falling
// In our case, falling and jumping is handled by the same state
if(!sprite->isOnGround()) {
sprite->setState(MegamanJumpingRight::getInstance());
}
else if(sprite->getCounter(this) >= 10) {
//sprite->setState(MegamanRunningRight::getInstance());
sprite->setState(MegamanStandingRight::getInstance());
}
else {
sprite->incCounter(this);
}
}
| [
"fournierseb2@051cbfc0-75b8-dce1-6088-688cefeb9347"
] | [
[
[
1,
91
]
]
] |
bb655a4d74ba56573494a6e3245a8b53ea3b88cf | 49b6646167284329aa8644c8cf01abc3d92338bd | /SEP2_RELEASE/Controller/Communication.cpp | 4129549816580a789ea9a93ec2a5dcd1584fab5d | [] | no_license | StiggyB/javacodecollection | 9d017b87b68f8d46e09dcf64650bd7034c442533 | bdce3ddb7a56265b4df2202d24bf86a06ecfee2e | refs/heads/master | 2020-08-08T22:45:47.779049 | 2011-10-24T12:10:08 | 2011-10-24T12:10:08 | 32,143,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,426 | cpp | /**
* Communication
*
* SE2 (+ SY and PL) Project SoSe 2011
*
* Authors: Rico Flaegel,
* Tell Mueller-Pettenpohl,
* Torsten Krane,
* Jan Quenzel
*
* Capsulates many functions for the direct
* connection of components via Messages.
*/
#include "Communication.h"
volatile int Communication::serverChannelId = 0;
int Communication::uniqueIDCounter = 1;
Communication::Communication() : lst(),rcvid(0) {
uniqueID = uniqueIDCounter++;
}
Communication::~Communication() {
}
int Communication::getChannelIdForObject(CommunicatorType c){
return getChannelIdForObject(c,0);
}
int Communication::getChannelIdForObject(CommunicatorType c, int number) {
return getIdForObject(c,number,CHANNEL);
}
int Communication::getIdForObject(CommunicatorType c, int number,int mode) {
std::list<Communicator>::iterator it;
for (it = lst.begin(); it != lst.end(); it++) {
if ((*it).getCom() == c) {
if (number == 0) {
switch(mode){
case CHANNEL: return (*it).getChannelID();break;
case CONNECT: return (*it).getConnectID();break;
case UNIQUE: return (*it).getUniqueID();break;
default: return -1;break;
}
} else {
number--;
}
}
}
return -1;
}
int Communication::getConnectIdForObject(CommunicatorType c){
return getConnectIdForObject(c,0);
}
int Communication::getConnectIdForObject(CommunicatorType c, int number) {
return getIdForObject(c,number,CONNECT);
}
int Communication::getUniqueIdForObject(CommunicatorType c){
return getUniqueIdForObject(c,0);
}
int Communication::getUniqueIdForObject(CommunicatorType c, int number){
return getIdForObject(c,number,UNIQUE);
}
std::list<Communication::Communicator>::iterator Communication::getCommunicatorForObject(int ci,int co){
std::list<Communicator>::iterator it;
for(it = lst.begin(); it != lst.end();it++){
if((*it).getChannelID() == ci && (*it).getConnectID() == co ){
return it;
}
}
return NULL;
}
std::list<Communication::Communicator>::iterator Communication::getCommunicatorForObject(int uni){
std::list<Communicator>::iterator it;
for(it = lst.begin(); it != lst.end();it++){
if((*it).getUniqueID() == uni){
return it;
}
}
return NULL;
}
bool Communication::requestChannelIDForObject(CommunicatorType c){
return requestChannelIDForObject(c,0);
}
bool Communication::addCommunicator(int ch, int cod, int uni, CommunicatorType ct){
Communicator *com = new Communicator(ch,cod,uni,ct);
lst.insert(lst.begin(),*com);
return true;
}
bool Communication::removeCommunicator(int uni){
std::list<Communicator>::iterator it;
for (it = lst.begin(); it != lst.end(); it++) {
if ((*it).getUniqueID() == uni) {
lst.erase(it);
return true;
}
}
return false;
}
void Communication::printList(){
std::list<Communicator>::iterator it;
std::cout << "List begin:" << std::endl;
for (it = lst.begin(); it != lst.end(); it++) {
std::cout << "UID: " << (*it).getUniqueID() << "Com: " << (*it).getCom() << " ChID: " << (*it).getChannelID() << " CoID: " << (*it).getConnectID() << std::endl;
}
}
bool Communication::setUpChannel(){
//std::cout << "trying setUpChannel" << std::endl;
chid = ChannelCreate(0);
//std::cout << "setUpChannel: chid: "<< chid << std::endl;
if (chid == -1) {
perror("Communication: failed to create Channel\n");
return false;
}
//std::cout << "setUpChannel done" << std::endl;
return true;
}
bool Communication::cleanUp(int coid){
return cleanUp(coid,NULL,NULL);
}
bool Communication::cleanUp(int coid,Message *m,Message *r){
if(m != NULL) free(m);
if(r != NULL) free(r);
if(coid != 0 && coid != -1){ return (-1 != ConnectDetach(coid));}
return true;
}
bool Communication::destroyChannel(int id){
if (ChannelDestroy(id) == -1) {
perror("Communication: failed to destroy Channel\n");
return false;
}
return true;
}
void Communication::buildMessage(void *s, int chid, int coid, MsgType activity,CommunicatorType c){
buildMessage(s,chid,coid,activity,c,0);
}
void Communication::buildMessage(void *s, int chid, int coid, MsgType activity,CommunicatorType c, int val){
Message *m = (Message*) s;
m->m.chid = chid;
m->m.coid = coid;
m->m.ca = activity;
m->m.comtype = c;
m->m.wert = val;
}
bool Communication::allocMessages() {
return allocMessages((void**)&m, (void**)&r_msg);
}
bool Communication::allocMessages(void ** msg, void ** rmsg) {
Message * ms = ( Message *) malloc(sizeof(Message));
Message * rm = ( Message *) malloc(sizeof(Message));
if (rm == NULL) {
perror("Communication: failed to get Space for Receive Message.");
free(ms);
return false;
}
if (ms == NULL) {
perror("Communication: failed to get Space for Message.");
free(rm);
return false;
}
(*rmsg) = rm;
(*msg) = ms;
return true;
}
bool Communication::prepareCommunication(CommunicatorType c){
if (!setUpChannel()) {
perror("Communication: channel setup failed " + c );
return false;
} else {
cout << "Communication: channel setup successful " << chid << " for "<< c << endl;
}
if (!registerChannel(c,uniqueID)) {
perror("Communication: register channel failed" + c);
destroyChannel(chid);
return false;
} else {
cout << "Communication: register channel successful : " << c << endl;
}
return true;
}
void Communication::handleMessage() {
switch (rcvid) {
case 0:
handlePulsMessage();
break;
case -1:
perror("Communication: failed to get Message\n");
break;
default:
handleNormalMessage();
break;
}
}
bool Communication::connectWithCommunicator(CommunicatorType c, CommunicatorType my){
return connectWithCommunicator(c,0,my);
}
bool Communication::connectWithCommunicator(CommunicatorType c, int number, CommunicatorType my){
int id = getChannelIdForObject(c,number);
if ( -1 == id ) {
perror("Communication: failed to get ChannelId!");
return false;
}
if (!attachConnection(id, c)) {
perror("Communication: failed to AttachConnection!");
return false;
}
if(c != my){
coid = getConnectIdForObject(c,number);
buildMessage(m, chid, coid, startConnection, my,uniqueID);
if (-1 == MsgSend(coid, m, sizeof(Message), r_msg, sizeof(Message))) {
perror("Communication: failed to send message to Communicator!");
return false;
}
}
return true;
}
bool Communication::sendPulses(CommunicatorType target, int code, int value){
return sendPulses(target,0,code,value);
}
bool Communication::sendPulses(CommunicatorType target, int number, int code, int value){
int coid = 0;
if(-1 != (coid = getConnectIdForObject(target,number))){
if(-1 == MsgSendPulse(coid, PULSE_MIN_PRIO, code, value)){
perror("Communication: Failed to send target a pulse!");
return false;
}
return true;
}
perror("Communication: Failed to getConnect Id for target object pulse!");
return false;
}
bool Communication::settingUpCommunicatorDevice(CommunicatorType target){
if (prepareCommunication(mine)) {
if (target != NONE && !requestChannelIDForObject(target)) {
perror("Communicator: request failed");
unregisterChannel(mine,uniqueID);
return false;
}
if (!allocMessages()) {
perror("Communicator: alloc Messages failed");
cleanCommunication();
return false;
}
if(target != NONE && !connectWithCommunicator(target,mine)){
perror("Communicator: connect with communicator failed");
cleanCommunication();
return false;
}
}
return true;
}
void Communication::cleanCommunication(){
if(mine != COMMUNICATIONCONTROLLER){
unregisterChannel(mine,uniqueID);
}
cleanUp(0, m, r_msg);
destroyChannel(chid);
}
void Communication::endCommunication(){
if (!detachConnection(coid, mine,uniqueID)) {
perror("Communication: failed to detach Channel\n");
cleanCommunication();
return;
}
if (!unregisterChannel(mine,uniqueID)) {
perror("Communication: unregister channel failed!");
}
cleanCommunication();
}
int Communication::getCodeFromPulse(Message *ptr){
return ptr->pulse.code;
}
int Communication::getValueFromPulse(Message *ptr){
return ptr->pulse.value.sival_int;
}
int Communication::getCodeFromReceivePulse(){
return getCodeFromPulse(r_msg);
}
int Communication::getValueFromReceivePulse(){
return getValueFromPulse(r_msg);
}
bool Communication::handleConnectionMessage() {
if (r_msg->m.ca == startConnection) {
getConnectionAttached();
} else if (r_msg->m.ca == closeConnection) {
if (removeCommunicator( r_msg->m.wert)) {
perror("Communication: remove Communicator.");
}
} else {
return false;
}
return true;
}
void Communication::getConnectionAttached(){
if (addCommunicator(r_msg->m.chid, r_msg->m.coid, r_msg->m.wert, r_msg->m.comtype)) {
buildMessage(m, r_msg->m.chid, r_msg->m.coid, OK, mine,uniqueID);
if (-1 == MsgReply(rcvid, 0, m, sizeof(Message))) {
perror("Communication: failed to send reply message to Communicator!");
}
if ((coid = ConnectAttach(0, 0, r_msg->m.chid, _NTO_SIDE_CHANNEL, 0)) == -1) {
perror("Communication: failed to attach Channel to other Instance\n");
}
getCommunicatorForObject(r_msg->m.wert)->setConnectID(coid);
} else {
perror("Communication: failed to addCommunicator");
}
}
bool Communication::requestChannelIDForObject(CommunicatorType c,int number){
int coid = ConnectAttach(0, 0, serverChannelId, _NTO_SIDE_CHANNEL, 0);
if (coid == -1) {
perror("Communication: failed to attach Channel for ID Request\n");
return false;
}
Message * msg_s, *r_msg;
if (!allocMessages((void**) &msg_s,(void**) &r_msg)) {
perror("Communication: failed to get Space for Message.");
cleanUp(coid,msg_s,r_msg);
return false;
}
buildMessage(msg_s, serverChannelId, coid, getIDforCom, c, number);
if (-1 == MsgSend(coid, msg_s, sizeof(Message), r_msg, sizeof(Message))) {
perror("Communication: failed to send Message to server!");
cleanUp(coid,msg_s,r_msg);
return false;
}
if (-1 == ConnectDetach(coid)) {
perror("Communication: failed to detach client from server!");
cleanUp(0,msg_s,r_msg);
return false;
}
addCommunicator(r_msg->m.chid,0,r_msg->m.wert,c);
cleanUp(0,msg_s,r_msg);
return true;
}
bool Communication::attachConnection(int id, CommunicatorType c){
coid = ConnectAttach(0, 0, id, _NTO_SIDE_CHANNEL, 0);
if (coid == -1) {
perror("Communication: failed to attach Channel.");
return false;
}
if(c != mine){
Message * msg_s, * r_msg;
if(!allocMessages((void**)&msg_s,(void**)&r_msg)){
ConnectDetach(coid);
return false;
}
buildMessage(msg_s,id, coid, startConnection, c,uniqueID);
if (-1 == MsgSend(coid, msg_s, sizeof(Message), r_msg, sizeof(Message))) {
perror("Communication: failed to send Message to server.");
cleanUp(coid,msg_s,r_msg);
return false;
}
if (r_msg->m.ca != OK) {
perror("Communication: no OK from Receiver! ");
cleanUp(coid,msg_s,r_msg);
return false;
}
cleanUp(0,msg_s,r_msg);
}
std::list<Communicator>::iterator it = getCommunicatorForObject(id,0);
return (it == NULL ? false : (*it).setConnectID(coid));
}
bool Communication::detachConnection(int coid,CommunicatorType c,int unique){
Message ** msg_s=NULL, **r_msg=NULL;
int id = getChannelIdForObject(c,unique);
if(!doInternalExchange(msg_s,r_msg,c, coid, id, unique, closeConnection)){
perror("Communication: failed to do internal exchange\n");
cleanUp(coid);
return false;
}
if((*r_msg)->m.ca != OK){
perror("Communication: _Detach_Communication_ no OK from Receiver!");
cleanUp(0,*msg_s,*r_msg);
return false;
}
cleanUp(0,*msg_s,*r_msg);
return true;
}
bool Communication::registerChannel(CommunicatorType c, int unique){
return regEditChannel(c,unique,addToServer);
}
bool Communication::unregisterChannel(CommunicatorType c, int unique) {
return regEditChannel(c,unique,removeFromServer);
}
bool Communication::regEditChannel(CommunicatorType c, int unique, MsgType m){
Message * msg_s, *r_msg;
int coid = ConnectAttach(0, 0, serverChannelId, _NTO_SIDE_CHANNEL, 0);
if (coid == -1) {
perror("Communication: failed to attach channel\n");
cleanUp(coid);
return false;
}
if(!doInternalExchange(&msg_s,&r_msg,c, coid, chid, unique, m)){
perror("Communication: failed to do internal exchange\n");
cleanUp(coid);
return false;
}
cleanUp(coid, msg_s, r_msg);
return true;
}
bool Communication::doInternalExchange(Message ** ptrM,Message ** ptrR,
CommunicatorType c, int coid, int chid, int unique, MsgType m) {
Message * msg_s, *r_msg;
if (!allocMessages((void**) &msg_s, (void**) &r_msg)) {
perror("Communication: failed to get Space for Message.");
cleanUp(coid, msg_s, r_msg);
return false;
}
(*ptrM) = msg_s;(*ptrR) = r_msg;
buildMessage(msg_s, chid, coid, m, c, unique);
if (-1 == MsgSend(coid, msg_s, sizeof(Message), r_msg, sizeof(Message))) {
perror("Communication: failed to send Message to server,");
cleanUp(coid, msg_s, r_msg);
return false;
}
if (-1 == ConnectDetach(coid)) {
perror("Communication: failed to unregister client from server");
cleanUp(coid, msg_s, r_msg);
return false;
}
return true;
}
| [
"[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1",
"[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1"
] | [
[
[
1,
226
],
[
231,
236
],
[
238,
238
],
[
240,
379
],
[
381,
468
]
],
[
[
227,
230
],
[
237,
237
],
[
239,
239
],
[
380,
380
]
]
] |
29a2c23c378e2fe4fd6229671fee1b0910b7c8c6 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/serialization/example/demo_shared_ptr.cpp | 87fb20798b22dd4c81f9076d2199a004e7426844 | [
"BSL-1.0"
] | permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,633 | cpp | // demo_shared_ptr.cpp : demonstrates adding serialization to a template
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . Polymorphic
// derived pointer example by David Tonge.
// 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)
//
// See http://www.boost.org for updates, documentation, and revision history.
#include <iomanip>
#include <iostream>
#include <cstddef> // NULL
#include <fstream>
#include <string>
#include <cstdio> // remove
#include <boost/config.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::remove;
}
#endif
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/tmpdir.hpp>
#include <boost/serialization/shared_ptr.hpp>
///////////////////////////
// test shared_ptr serialization
class A
{
private:
friend class boost::serialization::access;
int x;
template<class Archive>
void serialize(Archive & ar, const unsigned int /* file_version */){
ar & x;
}
public:
static int count;
A(){++count;} // default constructor
virtual ~A(){--count;} // default destructor
};
BOOST_SERIALIZATION_SHARED_PTR(A)
/////////////////
// ADDITION BY DT
class B : public A
{
private:
friend class boost::serialization::access;
int x;
template<class Archive>
void serialize(Archive & ar, const unsigned int /* file_version */){
ar & boost::serialization::base_object<A>(*this);
}
public:
static int count;
B() : A() {};
virtual ~B() {};
};
BOOST_SERIALIZATION_SHARED_PTR(B)
/////////////////
int A::count = 0;
void display(boost::shared_ptr<A> &spa, boost::shared_ptr<A> &spa1)
{
std::cout << "a = 0x" << std::hex << spa.get() << " ";
if (spa.get()) std::cout << "is a " << typeid(*(spa.get())).name() << "* ";
std::cout << "use count = " << std::dec << spa.use_count() << std::endl;
std::cout << "a1 = 0x" << std::hex << spa1.get() << " ";
if (spa1.get()) std::cout << "is a " << typeid(*(spa1.get())).name() << "* ";
std::cout << "use count = " << std::dec << spa1.use_count() << std::endl;
std::cout << "unique element count = " << A::count << std::endl;
}
int main(int /* argc */, char /* *argv[] */)
{
std::string filename(boost::archive::tmpdir());
filename += "/testfile";
// create a new shared pointer to ta new object of type A
boost::shared_ptr<A> spa(new A);
boost::shared_ptr<A> spa1;
spa1 = spa;
display(spa, spa1);
// serialize it
{
std::ofstream ofs(filename.c_str());
boost::archive::text_oarchive oa(ofs);
oa << spa;
oa << spa1;
}
// reset the shared pointer to NULL
// thereby destroying the object of type A
spa.reset();
spa1.reset();
display(spa, spa1);
// restore state to one equivalent to the original
// creating a new type A object
{
// open the archive
std::ifstream ifs(filename.c_str());
boost::archive::text_iarchive ia(ifs);
// restore the schedule from the archive
ia >> spa;
ia >> spa1;
}
display(spa, spa1);
spa.reset();
spa1.reset();
std::cout << std::endl;
std::cout << std::endl;
std::cout << "New tests" << std::endl;
/////////////////
// ADDITION BY DT
// create a new shared pointer to ta new object of type A
spa = boost::shared_ptr<A>(new B);
spa1 = spa;
display(spa, spa1);
// serialize it
{
std::ofstream ofs(filename.c_str());
boost::archive::text_oarchive oa(ofs);
oa.register_type(static_cast<B *>(NULL));
oa << spa;
oa << spa1;
}
// reset the shared pointer to NULL
// thereby destroying the object of type B
spa.reset();
spa1.reset();
display(spa, spa1);
// restore state to one equivalent to the original
// creating a new type B object
{
// open the archive
std::ifstream ifs(filename.c_str());
boost::archive::text_iarchive ia(ifs);
// restore the schedule from the archive
ia.register_type(static_cast<B *>(NULL));
ia >> spa;
ia >> spa1;
}
display(spa, spa1);
///////////////
std::remove(filename.c_str());
// obj of type A gets destroyed
// as smart_ptr goes out of scope
return 0;
}
| [
"metrix@Blended.(none)"
] | [
[
[
1,
164
]
]
] |
1b0c46acdcc2a2c27d953584a3e17404b238ec90 | 4d01363b089917facfef766868fb2b1a853605c7 | /src/SceneObjects/Primitives/Box.h | 56ba9e10fbc9e12257f2ca1a53ab0c229ebb5d41 | [] | 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 | 1,093 | h | #ifndef box_h
#define box_h
#include "../Meshes/Mesh.h"
class Dimension3
{
private:
public:
float x, y, z;
Dimension3(float a, float b, float c) : x(a), y(b), z(c)
{
}
Dimension3 operator*(float scale)
{
return Dimension3(x * scale, y * scale, z * scale);
}
};
class Box : public Mesh
{
Dimension3 d;
public:
Box(Dimension3 dim, Position3 centre) :
Mesh(centre),
d(dim * 0.5f)
{
vertices.push_back(Position3( d.x, d.y, d.z));
vertices.push_back(Position3( d.x, -d.y, d.z));
vertices.push_back(Position3(-d.x, -d.y, d.z));
vertices.push_back(Position3(-d.x, d.y, d.z));
vertices.push_back(Position3( d.x, d.y, -d.z));
vertices.push_back(Position3( d.x, -d.y, -d.z));
vertices.push_back(Position3(-d.x, -d.y, -d.z));
vertices.push_back(Position3(-d.x, d.y, -d.z));
faces.push_back(Face(0, 1, 2, 3));
faces.push_back(Face(3, 2, 6, 7));
faces.push_back(Face(7, 4, 5, 6));
faces.push_back(Face(4, 0, 1, 5));
faces.push_back(Face(0, 3, 7, 4));
faces.push_back(Face(1, 2, 6, 5));
}
};
#endif
| [
"daven.hughes@92c3b6dc-493d-11de-82d9-516ade3e46db"
] | [
[
[
1,
48
]
]
] |
edd7ace7244d39424a63c4699bd39675c0a78fa4 | f9774f8f3c727a0e03c170089096d0118198145e | /传奇mod/Mir2ExCode/Mir2/GameProcess/ChatPopWnd.cpp | 82f27c96df026862ebfa45907178e1cf55f9419c | [] | no_license | sdfwds4/fjljfatchina | 62a3bcf8085f41d632fdf83ab1fc485abd98c445 | 0503d4aa1907cb9cf47d5d0b5c606df07217c8f6 | refs/heads/master | 2021-01-10T04:10:34.432964 | 2010-03-07T09:43:28 | 2010-03-07T09:43:28 | 48,106,882 | 1 | 1 | null | null | null | null | UHC | C++ | false | false | 4,944 | cpp | /******************************************************************************************************************
모듈명:
작성자:
작성일:
[일자][수정자] : 수정 내용
*******************************************************************************************************************/
#include "StdAfx.h"
CChatPopWnd::CChatPopWnd()
{
Init();
}
CChatPopWnd::~CChatPopWnd()
{
Destroy();
}
VOID CChatPopWnd::Init()
{
CGameWnd::Init();
m_nCanScrlCnt = 0;
m_nCurrStartChatLine = 0;
SetRect(&m_rcChatPopFrame, 0, 0, 0, 0);
SetRect(&m_rcEditBoxFrame, 0, 0, 0, 0);
m_xChatPopBtn.Init();
}
VOID CChatPopWnd::Destroy()
{
m_xstrDividedChat.ClearAllNodes();
Init();
}
VOID CChatPopWnd::CreateChatPopWnd(INT nID, CWHWilImageData* pxWndImage, INT nFrameImgIdx, INT nStartX, INT nStartY, INT nWidth, INT nHeight, BOOL bCanMove)
{
CreateGameWnd(nID, pxWndImage, nFrameImgIdx, bCanMove, nStartX, nStartY, nWidth, nHeight);
SetRect(&m_rcChatPopFrame, 40, 29, 531, 308);
SetRect(&m_rcEditBoxFrame, 36, 312, 535, 328);
m_xChatPopBtn.CreateGameBtn(pxWndImage, 372, 373, nStartX+542, nStartY+353);
}
BOOL CChatPopWnd::MsgAdd(DWORD dwFontColor, DWORD dwFontBackColor, CHAR* szMsg)
{
CHAR szChatMsg[MAX_PATH];
if ( szMsg != NULL )
{
strcpy(szChatMsg, szMsg);
if ( szChatMsg[0] != NULL )
{
INT nLineCnt;
CHAR szDivied[MAX_PATH*2];
CHAR szArg[5][MAX_PATH];
ZeroMemory(szDivied, MAX_PATH*2);
ZeroMemory(&szArg[0], MAX_PATH*5);
g_xMainWnd.StringDivide(m_rcChatPopFrame.right-m_rcChatPopFrame.left, nLineCnt, szChatMsg, szDivied);
sscanf(szDivied, "%[^`]%*c %[^`]%*c %[^`]%*c %[^`]%*c %[^`]%*c", szArg[0], szArg[1], szArg[2], szArg[3], szArg[4]);
if ( nLineCnt > 5 ) nLineCnt = 5;
for ( INT nCnt = 0; nCnt < nLineCnt; nCnt++ )
{
if ( m_nCanScrlCnt )
m_nCurrStartChatLine = m_nCanScrlCnt;
if ( m_xstrDividedChat.GetCounter() >= _MAX_CHATLINE_POPUP )
{
m_nCurrStartChatLine++;
m_nCanScrlCnt++;
}
CHATSTRING stChatStr;
stChatStr.dwFontColor = dwFontColor;
stChatStr.dwFontBackColor = dwFontBackColor;
stChatStr.strChat = szArg[nCnt];
m_xstrDividedChat.AddNode(stChatStr);
}
}
return TRUE;
}
return FALSE;
}
VOID CChatPopWnd::ShowChatPopWnd()
{
ShowGameWnd();
// 채팅 리스트를 보여준다.
if ( !m_xstrDividedChat.CheckEmpty() )
{
m_xstrDividedChat.MoveCurrentToTop();
m_xstrDividedChat.MoveNode(m_nCurrStartChatLine);
INT nLine = 0;
INT nMaxLine;
if ( !m_nCurrStartChatLine )
{
if ( !m_nCanScrlCnt )
nMaxLine = m_xstrDividedChat.GetCounter();
else
nMaxLine = _MAX_CHATLINE_POPUP;
}
else
nMaxLine = (m_nCurrStartChatLine+_MAX_CHATLINE_POPUP) > m_xstrDividedChat.GetCounter() ?
m_xstrDividedChat.GetCounter() : m_nCurrStartChatLine+_MAX_CHATLINE_POPUP;
for ( INT nCnt = m_nCurrStartChatLine; nCnt < nMaxLine; nCnt++ )
{
LPCHATSTRING pstChatString;
pstChatString = m_xstrDividedChat.GetCurrentData();
g_xMainWnd.PutsHan(g_xMainWnd.GetBackBuffer(),
m_rcWnd.left+m_rcChatPopFrame.left, m_rcWnd.top+m_rcChatPopFrame.top+nLine*14,
pstChatString->dwFontBackColor, pstChatString->dwFontColor, pstChatString->strChat.begin());
m_xstrDividedChat.MoveNextNode();
nLine++;
}
}
m_xChatPopBtn.ShowGameBtn();
}
BOOL CChatPopWnd::OnLButtonUp(POINT ptMouse)
{
MoveWindow(g_xChatEditBox.GetSafehWnd(), g_xMainWnd.m_rcWindow.left + m_rcWnd.left + m_rcEditBoxFrame.left,
g_xMainWnd.m_rcWindow.top + m_rcWnd.top + m_rcEditBoxFrame.top,
m_rcEditBoxFrame.right - m_rcEditBoxFrame.left,
m_rcEditBoxFrame.bottom - m_rcEditBoxFrame.top, TRUE);
if ( m_xChatPopBtn.OnLButtonUp(ptMouse) ) return TRUE;
return FALSE;
}
BOOL CChatPopWnd::OnLButtonDown(POINT ptMouse)
{
if ( m_xChatPopBtn.OnLButtonDown(ptMouse) ) return TRUE;
return FALSE;
}
VOID CChatPopWnd::OnMouseMove(POINT ptMouse)
{
m_xChatPopBtn.ChangeRect(m_rcWnd.left+542, m_rcWnd.top+353);
m_xChatPopBtn.OnMouseMove(ptMouse);
}
VOID CChatPopWnd::OnScrollDown()
{
if ( m_nCurrStartChatLine > 0 ) m_nCurrStartChatLine--;
}
VOID CChatPopWnd::OnScrollUp()
{
if ( m_nCurrStartChatLine < m_xstrDividedChat.GetCounter()-_MAX_CHATLINE_POPUP ) m_nCurrStartChatLine++;
}
VOID CChatPopWnd::SetStatusBtnInit()
{
m_xChatPopBtn.SetBtnState(_BTN_STATE_NORMAL);
}
| [
"fjljfat@4a88d1ba-22b1-11df-8001-4f4b503b426e"
] | [
[
[
1,
178
]
]
] |
026b1d3e6d7f2f39d0e6f53d2c5c0e54e3649138 | 2e5fd1fc05c0d3b28f64abc99f358145c3ddd658 | /deps/quickfix/src/.NET/Messages.h | 6a49c0dd806d6d77459f83f923e9c156f2ddc080 | [
"BSD-2-Clause"
] | permissive | indraj/fixfeed | 9365c51e2b622eaff4ce5fac5b86bea86415c1e4 | 5ea71aab502c459da61862eaea2b78859b0c3ab3 | refs/heads/master | 2020-12-25T10:41:39.427032 | 2011-02-15T13:38:34 | 2011-02-15T20:50:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | h | /* -*- C++ -*- */
/****************************************************************************
** Copyright (c) quickfixengine.org All rights reserved.
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/
#pragma once
#include "FIX40_Messages.h"
#include "FIX41_Messages.h"
#include "FIX42_Messages.h"
#include "FIX43_Messages.h"
| [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
8312a8cc919f175a3a43953d2760953a165f752c | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/libs/uavobjgenerator/uavobjectparser.cpp | 090625b60c4981903b5c54abf73da5eea40a5c75 | [] | no_license | caichunyang2007/my_OpenPilot_mods | 8e91f061dc209a38c9049bf6a1c80dfccb26cce4 | 0ca472f4da7da7d5f53aa688f632b1f5c6102671 | refs/heads/master | 2023-06-06T03:17:37.587838 | 2011-02-28T10:25:56 | 2011-02-28T10:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,377 | cpp | /**
******************************************************************************
*
* @file uavobjectparser.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @brief Parses XML files and extracts object information.
*
* @see The GNU Public License (GPL) Version 3
*
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "uavobjectparser.h"
#include <QByteArray>
/**
* Constructor
*/
UAVObjectParser::UAVObjectParser()
{
fieldTypeStrC << QString("int8_t") << QString("int16_t") << QString("int32_t") <<
QString("uint8_t") << QString("uint16_t") << QString("uint32_t") <<
QString("float") << QString("uint8_t");
fieldTypeStrCPP << QString("qint8") << QString("qint16") << QString("qint32") <<
QString( "quint8") << QString("quint16") << QString("quint32") <<
QString("float") << QString("quint8");
fieldTypeStrPython << QString("b") << QString("h") << QString("i") <<
QString( "B") << QString("H") << QString("I") <<
QString("f") << QString("b");
fieldTypeStrCPPClass << QString("INT8") << QString("INT16") << QString("INT32") <<
QString( "UINT8") << QString("UINT16") << QString("UINT32") <<
QString("FLOAT32") << QString("ENUM");
fieldTypeStrXML << QString("int8") << QString("int16") << QString("int32") <<
QString("uint8") << QString("uint16") << QString("uint32") <<
QString("float") << QString("enum");
updateModeStr << QString("UPDATEMODE_PERIODIC") << QString("UPDATEMODE_ONCHANGE") <<
QString("UPDATEMODE_MANUAL") << QString("UPDATEMODE_NEVER");
updateModeStrXML << QString("periodic") << QString("onchange") <<
QString("manual") << QString("never");
accessModeStr << QString("ACCESS_READWRITE") << QString("ACCESS_READONLY");
accessModeStrXML << QString("readwrite") << QString("readonly");
}
/**
* Get number of objects
*/
int UAVObjectParser::getNumObjects()
{
return objInfo.length();
}
/**
* Get the detailed object information
*/
QList<UAVObjectParser::ObjectInfo*> UAVObjectParser::getObjectInfo()
{
return objInfo;
}
/**
* Get the name of the object
*/
QString UAVObjectParser::getObjectName(int objIndex)
{
ObjectInfo* info = objInfo[objIndex];
if (info == NULL)
{
return QString();
}
else
{
return info->name;
}
}
/**
* Get the ID of the object
*/
quint32 UAVObjectParser::getObjectID(int objIndex)
{
ObjectInfo* info = objInfo[objIndex];
if (info == NULL)
{
return 0;
}
else
{
return info->id;
}
}
/**
* Parse supplied XML file
* @param xml The xml text
* @param filename The xml filename
* @returns Null QString() on success, error message on failure
*/
QString UAVObjectParser::parseXML(QString& xml, QString& filename)
{
this->filename = filename;
// Create DOM document and parse it
QDomDocument doc("UAVObjects");
bool parsed = doc.setContent(xml);
if (!parsed) return QString("Improperly formated XML file");
// Read all objects contained in the XML file, creating an new ObjectInfo for each
QDomElement docElement = doc.documentElement();
QDomNode node = docElement.firstChild();
while ( !node.isNull() )
{
// Create new object entry
ObjectInfo* info = new ObjectInfo;
// Process object attributes
QString status = processObjectAttributes(node, info);
if (!status.isNull())
{
return status;
}
// Process child elements (fields and metadata)
QDomNode childNode = node.firstChild();
bool fieldFound = false;
bool accessFound = false;
bool telGCSFound = false;
bool telFlightFound = false;
bool logFound = false;
bool descriptionFound = false;
while ( !childNode.isNull() )
{
// Process element depending on its type
if ( childNode.nodeName().compare(QString("field")) == 0 )
{
QString status = processObjectFields(childNode, info);
if (!status.isNull())
{
return status;
}
fieldFound = true;
}
else if ( childNode.nodeName().compare(QString("access")) == 0 )
{
QString status = processObjectAccess(childNode, info);
if (!status.isNull())
{
return status;
}
accessFound = true;
}
else if ( childNode.nodeName().compare(QString("telemetrygcs")) == 0 )
{
QString status = processObjectMetadata(childNode, &info->gcsTelemetryUpdateMode,
&info->gcsTelemetryUpdatePeriod, &info->gcsTelemetryAcked);
if (!status.isNull())
{
return status;
}
telGCSFound = true;
}
else if ( childNode.nodeName().compare(QString("telemetryflight")) == 0 )
{
QString status = processObjectMetadata(childNode, &info->flightTelemetryUpdateMode,
&info->flightTelemetryUpdatePeriod, &info->flightTelemetryAcked);
if (!status.isNull())
{
return status;
}
telFlightFound = true;
}
else if ( childNode.nodeName().compare(QString("logging")) == 0 )
{
QString status = processObjectMetadata(childNode, &info->loggingUpdateMode,
&info->loggingUpdatePeriod, NULL);
if (!status.isNull())
{
return status;
}
logFound = true;
}
else if ( childNode.nodeName().compare(QString("description")) == 0 )
{
QString status = processObjectDescription(childNode, &info->description);
if (!status.isNull())
{
return status;
}
descriptionFound = true;
}
else
{
return QString("Unknown object element");
}
// Get next element
childNode = childNode.nextSibling();
}
// Make sure that required elements were found
if ( !accessFound )
{
return QString("Object::access element is missing");
}
else if ( !telGCSFound )
{
return QString("Object::telemetrygcs element is missing");
}
else if ( !telFlightFound )
{
return QString("Object::telemetryflight element is missing");
}
else if ( !logFound )
{
return QString("Object::logging element is missing");
}
// TODO: Make into error once all objects updated
if ( !descriptionFound )
{
return QString("Object::description element is missing");
}
// Calculate ID
calculateID(info);
// Add object
objInfo.append(info);
// Get next object
node = node.nextSibling();
}
// Done, return null string
return QString();
}
/**
* Calculate the unique object ID based on the object information.
* The ID will change if the object definition changes, this is intentional
* and is used to avoid connecting objects with incompatible configurations.
*/
void UAVObjectParser::calculateID(ObjectInfo* info)
{
// Hash object name
quint32 hash = updateHash(info->name, 0);
// Hash object attributes
hash = updateHash(info->isSettings, hash);
hash = updateHash(info->isSingleInst, hash);
// Hash field information
for (int n = 0; n < info->fields.length(); ++n)
{
hash = updateHash(info->fields[n]->name, hash);
hash = updateHash(info->fields[n]->numElements, hash);
hash = updateHash(info->fields[n]->type, hash);
}
// Done
info->id = hash;
}
/**
* Shift-Add-XOR hash implementation. LSB is set to zero, it is reserved
* for the ID of the metaobject.
*
* http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx
*/
quint32 UAVObjectParser::updateHash(quint32 value, quint32 hash)
{
return (hash ^ ((hash<<5) + (hash>>2) + value)) & 0xFFFFFFFE;
}
/**
* Update the hash given a string
*/
quint32 UAVObjectParser::updateHash(QString& value, quint32 hash)
{
QByteArray bytes = value.toAscii();
quint32 hashout = hash;
for (int n = 0; n < bytes.length(); ++n)
{
hashout = updateHash(bytes[n], hashout);
}
return hashout;
}
/**
* Process the metadata part of the XML
*/
QString UAVObjectParser::processObjectMetadata(QDomNode& childNode, UpdateMode* mode, int* period, bool* acked)
{
// Get updatemode attribute
QDomNamedNodeMap elemAttributes = childNode.attributes();
QDomNode elemAttr = elemAttributes.namedItem("updatemode");
if ( elemAttr.isNull() )
{
return QString("Object:telemetrygcs:updatemode attribute is missing");
}
else
{
int index = updateModeStrXML.indexOf( elemAttr.nodeValue() );
if (index >= 0)
{
*mode = (UpdateMode)index;
}
else
{
return QString("Object:telemetrygcs:updatemode attribute value is invalid");
}
}
// Get period attribute
elemAttr = elemAttributes.namedItem("period");
if ( elemAttr.isNull() )
{
return QString("Object:telemetrygcs:period attribute is missing");
}
else
{
*period = elemAttr.nodeValue().toInt();
}
// Get acked attribute (only if acked parameter is not null, not applicable for logging metadata)
if ( acked != NULL)
{
elemAttr = elemAttributes.namedItem("acked");
if ( elemAttr.isNull())
{
return QString("Object:telemetrygcs:acked attribute is missing");
}
else
{
if ( elemAttr.nodeValue().compare(QString("true")) == 0 )
{
*acked = true;
}
else if ( elemAttr.nodeValue().compare(QString("false")) == 0 )
{
*acked = false;
}
else
{
return QString("Object:telemetrygcs:acked attribute value is invalid");
}
}
}
// Done
return QString();
}
/**
* Process the object access tag of the XML
*/
QString UAVObjectParser::processObjectAccess(QDomNode& childNode, ObjectInfo* info)
{
// Get gcs attribute
QDomNamedNodeMap elemAttributes = childNode.attributes();
QDomNode elemAttr = elemAttributes.namedItem("gcs");
if ( elemAttr.isNull() )
{
return QString("Object:access:gcs attribute is missing");
}
else
{
int index = accessModeStrXML.indexOf( elemAttr.nodeValue() );
if (index >= 0)
{
info->gcsAccess = (AccessMode)index;
}
else
{
return QString("Object:access:gcs attribute value is invalid");
}
}
// Get flight attribute
elemAttr = elemAttributes.namedItem("flight");
if ( elemAttr.isNull() )
{
return QString("Object:access:flight attribute is missing");
}
else
{
int index = accessModeStrXML.indexOf( elemAttr.nodeValue() );
if (index >= 0)
{
info->flightAccess = (AccessMode)index;
}
else
{
return QString("Object:access:flight attribute value is invalid");
}
}
// Done
return QString();
}
/**
* Process the object fields of the XML
*/
QString UAVObjectParser::processObjectFields(QDomNode& childNode, ObjectInfo* info)
{
// Create field
FieldInfo* field = new FieldInfo;
// Get name attribute
QDomNamedNodeMap elemAttributes = childNode.attributes();
QDomNode elemAttr = elemAttributes.namedItem("name");
if ( elemAttr.isNull() )
{
return QString("Object:field:name attribute is missing");
}
else
{
field->name = elemAttr.nodeValue();
}
// Get units attribute
elemAttr = elemAttributes.namedItem("units");
if ( elemAttr.isNull() )
{
return QString("Object:field:units attribute is missing");
}
else
{
field->units = elemAttr.nodeValue();
}
// Get type attribute
elemAttr = elemAttributes.namedItem("type");
if ( elemAttr.isNull() )
{
return QString("Object:field:type attribute is missing");
}
else
{
int index = fieldTypeStrXML.indexOf(elemAttr.nodeValue());
if (index >= 0)
{
field->type = (FieldType)index;
}
else
{
return QString("Object:field:type attribute value is invalid");
}
}
// Get numelements or elementnames attribute
elemAttr = elemAttributes.namedItem("elementnames");
if ( !elemAttr.isNull() )
{
// Get element names
QStringList names = elemAttr.nodeValue().split(",", QString::SkipEmptyParts);
for (int n = 0; n < names.length(); ++n)
{
names[n] = names[n].trimmed();
}
field->elementNames = names;
field->numElements = names.length();
field->defaultElementNames = false;
}
else
{
elemAttr = elemAttributes.namedItem("elements");
if ( elemAttr.isNull() )
{
return QString("Object:field:elements and Object:field:elementnames attribute is missing");
}
else
{
field->numElements = elemAttr.nodeValue().toInt();
for (int n = 0; n < field->numElements; ++n)
{
field->elementNames.append(QString("%1").arg(n));
}
field->defaultElementNames = true;
}
}
// Get options attribute (only if an enum type)
if (field->type == FIELDTYPE_ENUM)
{
// Get options attribute
elemAttr = elemAttributes.namedItem("options");
if ( elemAttr.isNull() )
{
return QString("Object:field:options attribute is missing");
}
else
{
QStringList options = elemAttr.nodeValue().split(",", QString::SkipEmptyParts);
for (int n = 0; n < options.length(); ++n)
{
options[n] = options[n].trimmed();
}
field->options = options;
}
}
// Get the default value attribute (required for settings objects, optional for the rest)
elemAttr = elemAttributes.namedItem("defaultvalue");
if ( elemAttr.isNull() )
{
if ( info->isSettings )
{
return QString("Object:field:defaultvalue attribute is missing (required for settings objects)");
}else
{
field->defaultValues = QStringList();
}
}
else
{
QStringList defaults = elemAttr.nodeValue().split(",", QString::SkipEmptyParts);
for (int n = 0; n < defaults.length(); ++n)
{
defaults[n] = defaults[n].trimmed();
}
if(defaults.length() != field->numElements)
{
if(defaults.length() != 1)
{
return QString("Object:field:incorrect number of default values");
}
/*support legacy single default for multiple elements
We sould really issue a warning*/
for(int ct=1; ct< field->numElements; ct++)
{
defaults.append(defaults[0]);
}
}
field->defaultValues = defaults;
}
// Add field to object
info->fields.append(field);
// Done
return QString();
}
/**
* Process the object attributes from the XML
*/
QString UAVObjectParser::processObjectAttributes(QDomNode& node, ObjectInfo* info)
{
// Get name attribute
QDomNamedNodeMap attributes = node.attributes();
QDomNode attr = attributes.namedItem("name");
if ( attr.isNull() )
{
return QString("Object:name attribute is missing");
}
else
{
info->name = attr.nodeValue();
}
// Get singleinstance attribute
attr = attributes.namedItem("singleinstance");
if ( attr.isNull() )
{
return QString("Object:singleinstance attribute is missing");
}
else
{
if ( attr.nodeValue().compare(QString("true")) == 0 )
{
info->isSingleInst = true;
}
else if ( attr.nodeValue().compare(QString("false")) == 0 )
{
info->isSingleInst = false;
}
else
{
return QString("Object:singleinstance attribute value is invalid");
}
}
// Get settings attribute
attr = attributes.namedItem("settings");
if ( attr.isNull() )
{
return QString("Object:settings attribute is missing");
}
else
{
if ( attr.nodeValue().compare(QString("true")) == 0 )
{
info->isSettings = true;
}
else if ( attr.nodeValue().compare(QString("false")) == 0 )
{
info->isSettings = false;
}
else
{
return QString("Object:settings attribute value is invalid");
}
}
// Settings objects can only have a single instance
if ( info->isSettings && !info->isSingleInst )
{
return QString("Object: Settings objects can not have multiple instances");
}
// Done
return QString();
}
/**
* Process the description field from the XML file
*/
QString UAVObjectParser::processObjectDescription(QDomNode& childNode, QString * description)
{
description->append(childNode.firstChild().nodeValue());
return QString();
}
/**
* Replace all the common tags from the template file with actual object
* information.
*/
void UAVObjectParser::replaceCommonTags(QString& out, ObjectInfo* info)
{
QString value;
// Replace $(XMLFILE) tag
out.replace(QString("$(XMLFILE)"), filename);
// Replace $(NAME) tag
out.replace(QString("$(NAME)"), info->name);
// Replace $(NAMELC) tag
out.replace(QString("$(NAMELC)"), info->name.toLower());
// Replace $(DESCRIPTION) tag
out.replace(QString("$(DESCRIPTION)"), info->description);
// Replace $(NAMEUC) tag
out.replace(QString("$(NAMEUC)"), info->name.toUpper());
// Replace $(OBJID) tag
out.replace(QString("$(OBJID)"), QString().setNum(info->id));
// Replace $(ISSINGLEINST) tag
value = boolToString( info->isSingleInst );
out.replace(QString("$(ISSINGLEINST)"), value);
// Replace $(ISSETTINGS) tag
value = boolToString( info->isSettings );
out.replace(QString("$(ISSETTINGS)"), value);
// Replace $(GCSACCESS) tag
value = accessModeStr[info->gcsAccess];
out.replace(QString("$(GCSACCESS)"), value);
// Replace $(FLIGHTACCESS) tag
value = accessModeStr[info->flightAccess];
out.replace(QString("$(FLIGHTACCESS)"), value);
// Replace $(FLIGHTTELEM_ACKED) tag
value = boolToString( info->flightTelemetryAcked );
out.replace(QString("$(FLIGHTTELEM_ACKED)"), value);
// Replace $(FLIGHTTELEM_UPDATEMODE) tag
value = updateModeStr[info->flightTelemetryUpdateMode];
out.replace(QString("$(FLIGHTTELEM_UPDATEMODE)"), value);
// Replace $(FLIGHTTELEM_UPDATEPERIOD) tag
out.replace(QString("$(FLIGHTTELEM_UPDATEPERIOD)"), QString().setNum(info->flightTelemetryUpdatePeriod));
// Replace $(GCSTELEM_ACKED) tag
value = boolToString( info->gcsTelemetryAcked );
out.replace(QString("$(GCSTELEM_ACKED)"), value);
// Replace $(GCSTELEM_UPDATEMODE) tag
value = updateModeStr[info->gcsTelemetryUpdateMode];
out.replace(QString("$(GCSTELEM_UPDATEMODE)"), value);
// Replace $(GCSTELEM_UPDATEPERIOD) tag
out.replace(QString("$(GCSTELEM_UPDATEPERIOD)"), QString().setNum(info->gcsTelemetryUpdatePeriod));
// Replace $(LOGGING_UPDATEMODE) tag
value = updateModeStr[info->loggingUpdateMode];
out.replace(QString("$(LOGGING_UPDATEMODE)"), value);
// Replace $(LOGGING_UPDATEPERIOD) tag
out.replace(QString("$(LOGGING_UPDATEPERIOD)"), QString().setNum(info->loggingUpdatePeriod));
}
/**
* Convert a boolean to string
*/
QString UAVObjectParser::boolToString(bool value)
{
if ( value )
{
return QString("1");
}
else
{
return QString("0");
}
}
/**
* Generate the flight object files
*/
bool UAVObjectParser::generateFlightObject(int objIndex, const QString& templateInclude, const QString& templateCode,
QString& outInclude, QString& outCode)
{
// Get object
ObjectInfo* info = objInfo[objIndex];
if (info == NULL) return false;
// Prepare output strings
outInclude = templateInclude;
outCode = templateCode;
// Replace common tags
replaceCommonTags(outInclude, info);
replaceCommonTags(outCode, info);
// Replace the $(DATAFIELDS) tag
QString type;
QString fields;
for (int n = 0; n < info->fields.length(); ++n)
{
// Determine type
type = fieldTypeStrC[info->fields[n]->type];
// Append field
if ( info->fields[n]->numElements > 1 )
{
fields.append( QString(" %1 %2[%3];\n").arg(type)
.arg(info->fields[n]->name).arg(info->fields[n]->numElements) );
}
else
{
fields.append( QString(" %1 %2;\n").arg(type).arg(info->fields[n]->name) );
}
}
outInclude.replace(QString("$(DATAFIELDS)"), fields);
// Replace the $(DATAFIELDINFO) tag
QString enums;
for (int n = 0; n < info->fields.length(); ++n)
{
enums.append(QString("// Field %1 information\n").arg(info->fields[n]->name));
// Only for enum types
if (info->fields[n]->type == FIELDTYPE_ENUM)
{
enums.append(QString("/* Enumeration options for field %1 */\n").arg(info->fields[n]->name));
enums.append("typedef enum { ");
// Go through each option
QStringList options = info->fields[n]->options;
for (int m = 0; m < options.length(); ++m)
{
QString s = (m == (options.length()-1)) ? "%1_%2_%3=%4" : "%1_%2_%3=%4, ";
enums.append( s
.arg( info->name.toUpper() )
.arg( info->fields[n]->name.toUpper() )
.arg( options[m].toUpper() )
.arg(m) );
}
enums.append( QString(" } %1%2Options;\n")
.arg( info->name )
.arg( info->fields[n]->name ) );
}
// Generate element names (only if field has more than one element)
if (info->fields[n]->numElements > 1 && !info->fields[n]->defaultElementNames)
{
enums.append(QString("/* Array element names for field %1 */\n").arg(info->fields[n]->name));
enums.append("typedef enum { ");
// Go through the element names
QStringList elemNames = info->fields[n]->elementNames;
for (int m = 0; m < elemNames.length(); ++m)
{
QString s = (m != (elemNames.length()-1)) ? "%1_%2_%3=%4, " : "%1_%2_%3=%4";
enums.append( s
.arg( info->name.toUpper() )
.arg( info->fields[n]->name.toUpper() )
.arg( elemNames[m].toUpper() )
.arg(m) );
}
enums.append( QString(" } %1%2Elem;\n")
.arg( info->name )
.arg( info->fields[n]->name ) );
}
// Generate array information
if (info->fields[n]->numElements > 1)
{
enums.append(QString("/* Number of elements for field %1 */\n").arg(info->fields[n]->name));
enums.append( QString("#define %1_%2_NUMELEM %3\n")
.arg( info->name.toUpper() )
.arg( info->fields[n]->name.toUpper() )
.arg( info->fields[n]->numElements ) );
}
}
outInclude.replace(QString("$(DATAFIELDINFO)"), enums);
// Replace the $(INITFIELDS) tag
QString initfields;
for (int n = 0; n < info->fields.length(); ++n)
{
if (!info->fields[n]->defaultValues.isEmpty() )
{
// For non-array fields
if ( info->fields[n]->numElements == 1)
{
if ( info->fields[n]->type == FIELDTYPE_ENUM )
{
initfields.append( QString("\tdata.%1 = %2;\n")
.arg( info->fields[n]->name )
.arg( info->fields[n]->options.indexOf( info->fields[n]->defaultValues[0] ) ) );
}
else if ( info->fields[n]->type == FIELDTYPE_FLOAT32 )
{
initfields.append( QString("\tdata.%1 = %2;\n")
.arg( info->fields[n]->name )
.arg( info->fields[n]->defaultValues[0].toFloat() ) );
}
else
{
initfields.append( QString("\tdata.%1 = %2;\n")
.arg( info->fields[n]->name )
.arg( info->fields[n]->defaultValues[0].toInt() ) );
}
}
else
{
// Initialize all fields in the array
for (int idx = 0; idx < info->fields[n]->numElements; ++idx)
{
if ( info->fields[n]->type == FIELDTYPE_ENUM )
{
initfields.append( QString("\tdata.%1[%2] = %3;\n")
.arg( info->fields[n]->name )
.arg( idx )
.arg( info->fields[n]->options.indexOf( info->fields[n]->defaultValues[idx] ) ) );
}
else if ( info->fields[n]->type == FIELDTYPE_FLOAT32 )
{
initfields.append( QString("\tdata.%1[%2] = %3;\n")
.arg( info->fields[n]->name )
.arg( idx )
.arg( info->fields[n]->defaultValues[idx].toFloat() ) );
}
else
{
initfields.append( QString("\tdata.%1[%2] = %3;\n")
.arg( info->fields[n]->name )
.arg( idx )
.arg( info->fields[n]->defaultValues[idx].toInt() ) );
}
}
}
}
}
outCode.replace(QString("$(INITFIELDS)"), initfields);
// Done
return true;
}
/**
* Generate the GCS object files
*/
bool UAVObjectParser::generateGCSObject(int objIndex, const QString& templateInclude, const QString& templateCode,
QString& outInclude, QString& outCode)
{
// Get object
ObjectInfo* info = objInfo[objIndex];
if (info == NULL) return false;
// Prepare output strings
outInclude = templateInclude;
outCode = templateCode;
// Replace common tags
replaceCommonTags(outInclude, info);
replaceCommonTags(outCode, info);
// Replace the $(DATAFIELDS) tag
QString type;
QString fields;
for (int n = 0; n < info->fields.length(); ++n)
{
// Determine type
type = fieldTypeStrCPP[info->fields[n]->type];
// Append field
if ( info->fields[n]->numElements > 1 )
{
fields.append( QString(" %1 %2[%3];\n").arg(type).arg(info->fields[n]->name)
.arg(info->fields[n]->numElements) );
}
else
{
fields.append( QString(" %1 %2;\n").arg(type).arg(info->fields[n]->name) );
}
}
outInclude.replace(QString("$(DATAFIELDS)"), fields);
// Replace the $(FIELDSINIT) tag
QString finit;
for (int n = 0; n < info->fields.length(); ++n)
{
// Setup element names
QString varElemName = info->fields[n]->name + "ElemNames";
finit.append( QString(" QStringList %1;\n").arg(varElemName) );
QStringList elemNames = info->fields[n]->elementNames;
for (int m = 0; m < elemNames.length(); ++m)
{
finit.append( QString(" %1.append(\"%2\");\n")
.arg(varElemName)
.arg(elemNames[m]) );
}
// Only for enum types
if (info->fields[n]->type == FIELDTYPE_ENUM)
{
QString varOptionName = info->fields[n]->name + "EnumOptions";
finit.append( QString(" QStringList %1;\n").arg(varOptionName) );
QStringList options = info->fields[n]->options;
for (int m = 0; m < options.length(); ++m)
{
finit.append( QString(" %1.append(\"%2\");\n")
.arg(varOptionName)
.arg(options[m]) );
}
finit.append( QString(" fields.append( new UAVObjectField(QString(\"%1\"), QString(\"%2\"), UAVObjectField::ENUM, %3, %4) );\n")
.arg(info->fields[n]->name)
.arg(info->fields[n]->units)
.arg(varElemName)
.arg(varOptionName) );
}
// For all other types
else
{
finit.append( QString(" fields.append( new UAVObjectField(QString(\"%1\"), QString(\"%2\"), UAVObjectField::%3, %4, QStringList()) );\n")
.arg(info->fields[n]->name)
.arg(info->fields[n]->units)
.arg(fieldTypeStrCPPClass[info->fields[n]->type])
.arg(varElemName) );
}
}
outCode.replace(QString("$(FIELDSINIT)"), finit);
// Replace the $(DATAFIELDINFO) tag
QString name;
QString enums;
for (int n = 0; n < info->fields.length(); ++n)
{
enums.append(QString(" // Field %1 information\n").arg(info->fields[n]->name));
// Only for enum types
if (info->fields[n]->type == FIELDTYPE_ENUM)
{
enums.append(QString(" /* Enumeration options for field %1 */\n").arg(info->fields[n]->name));
enums.append(" typedef enum { ");
// Go through each option
QStringList options = info->fields[n]->options;
for (int m = 0; m < options.length(); ++m)
{
QString s = (m != (options.length()-1)) ? "%1_%2=%3, " : "%1_%2=%3";
enums.append( s
.arg( info->fields[n]->name.toUpper() )
.arg( options[m].toUpper() )
.arg(m) );
}
enums.append( QString(" } %1Options;\n")
.arg( info->fields[n]->name ) );
}
// Generate element names (only if field has more than one element)
if (info->fields[n]->numElements > 1 && !info->fields[n]->defaultElementNames)
{
enums.append(QString(" /* Array element names for field %1 */\n").arg(info->fields[n]->name));
enums.append(" typedef enum { ");
// Go through the element names
QStringList elemNames = info->fields[n]->elementNames;
for (int m = 0; m < elemNames.length(); ++m)
{
QString s = (m != (elemNames.length()-1)) ? "%1_%2=%3, " : "%1_%2=%3";
enums.append( s
.arg( info->fields[n]->name.toUpper() )
.arg( elemNames[m].toUpper() )
.arg(m) );
}
enums.append( QString(" } %1Elem;\n")
.arg( info->fields[n]->name ) );
}
// Generate array information
if (info->fields[n]->numElements > 1)
{
enums.append(QString(" /* Number of elements for field %1 */\n").arg(info->fields[n]->name));
enums.append( QString(" static const quint32 %1_NUMELEM = %2;\n")
.arg( info->fields[n]->name.toUpper() )
.arg( info->fields[n]->numElements ) );
}
}
outInclude.replace(QString("$(DATAFIELDINFO)"), enums);
// Replace the $(INITFIELDS) tag
QString initfields;
for (int n = 0; n < info->fields.length(); ++n)
{
if (!info->fields[n]->defaultValues.isEmpty() )
{
// For non-array fields
if ( info->fields[n]->numElements == 1)
{
if ( info->fields[n]->type == FIELDTYPE_ENUM )
{
initfields.append( QString(" data.%1 = %2;\n")
.arg( info->fields[n]->name )
.arg( info->fields[n]->options.indexOf( info->fields[n]->defaultValues[0] ) ) );
}
else if ( info->fields[n]->type == FIELDTYPE_FLOAT32 )
{
initfields.append( QString(" data.%1 = %2;\n")
.arg( info->fields[n]->name )
.arg( info->fields[n]->defaultValues[0].toFloat() ) );
}
else
{
initfields.append( QString(" data.%1 = %2;\n")
.arg( info->fields[n]->name )
.arg( info->fields[n]->defaultValues[0].toInt() ) );
}
}
else
{
// Initialize all fields in the array
for (int idx = 0; idx < info->fields[n]->numElements; ++idx)
{
if ( info->fields[n]->type == FIELDTYPE_ENUM )
{
initfields.append( QString(" data.%1[%2] = %3;\n")
.arg( info->fields[n]->name )
.arg( idx )
.arg( info->fields[n]->options.indexOf( info->fields[n]->defaultValues[idx] ) ) );
}
else if ( info->fields[n]->type == FIELDTYPE_FLOAT32 )
{
initfields.append( QString(" data.%1[%2] = %3;\n")
.arg( info->fields[n]->name )
.arg( idx )
.arg( info->fields[n]->defaultValues[idx].toFloat() ) );
}
else
{
initfields.append( QString(" data.%1[%2] = %3;\n")
.arg( info->fields[n]->name )
.arg( idx )
.arg( info->fields[n]->defaultValues[idx].toInt() ) );
}
}
}
}
}
outCode.replace(QString("$(INITFIELDS)"), initfields);
// Done
return true;
}
/**
* Generate the Python object files
*/
bool UAVObjectParser::generatePythonObject(int objIndex, const QString& templateCode, QString& outCode)
{
// Get object
ObjectInfo* info = objInfo[objIndex];
if (info == NULL) return false;
// Prepare output strings
outCode = templateCode;
// Replace common tags
replaceCommonTags(outCode, info);
// Replace the $(DATAFIELDS) tag
QString fields;
fields.append(QString("[ \\\n"));
for (int n = 0; n < info->fields.length(); ++n)
{
fields.append(QString("\tuavobject.UAVObjectField(\n"));
fields.append(QString("\t\t'%1',\n").arg(info->fields[n]->name));
fields.append(QString("\t\t'%1',\n").arg(fieldTypeStrPython[info->fields[n]->type]));
fields.append(QString("\t\t%1,\n").arg(info->fields[n]->numElements));
QStringList elemNames = info->fields[n]->elementNames;
fields.append(QString("\t\t[\n"));
for (int m = 0; m < elemNames.length(); ++m)
{
fields.append(QString("\t\t\t'%1',\n").arg(elemNames[m]));
}
fields.append(QString("\t\t],\n"));
fields.append(QString("\t\t{\n"));
if (info->fields[n]->type == FIELDTYPE_ENUM)
{
// Go through each option
QStringList options = info->fields[n]->options;
for (int m = 0; m < options.length(); ++m)
{
fields.append( QString("\t\t\t'%1' : '%2',\n")
.arg(m)
.arg( options[m] ) );
}
}
fields.append(QString("\t\t}\n"));
fields.append(QString("\t),\n"));
}
fields.append(QString("]\n"));
outCode.replace(QString("$(DATAFIELDS)"), fields);
// Done
return true;
}
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
] | [
[
[
1,
1112
]
]
] |
86c9d92b9db6f97045b99d009a7253031495ece7 | a381a69db3bd4f37266bf0c7129817ebb999e7b8 | /Common/AtgFrame.cpp | 80a6a2140945197c053b64bde65ead6d4034068e | [] | no_license | oukiar/vdash | 4420d6d6b462b7a833929b59d1ca232bd410e632 | d2bff3090c7d1c081d5b7ab41abb963f03d6118b | refs/heads/master | 2021-01-10T06:00:03.653067 | 2011-12-29T10:19:01 | 2011-12-29T10:19:01 | 49,607,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,545 | cpp | //-----------------------------------------------------------------------------
// AtgFrame.cpp
//
// Xbox Advanced Technology Group.
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "AtgFrame.h"
#include <float.h>
namespace ATG
{
CONST StringID Frame::TypeID( L"Frame" );
//-----------------------------------------------------------------------------
// Name: Frame::Frame()
//-----------------------------------------------------------------------------
Frame::Frame()
{
m_pParent = NULL;
m_pNextSibling = NULL;
m_pFirstChild = NULL;
SetCachedWorldTransformDirty();
m_LocalTransform = XMMatrixIdentity();
}
//-----------------------------------------------------------------------------
// Name: Frame::Frame()
//-----------------------------------------------------------------------------
Frame::Frame( const StringID& Name, CXMMATRIX matLocalTransform )
{
m_pParent = NULL;
m_pNextSibling = NULL;
m_pFirstChild = NULL;
SetCachedWorldTransformDirty();
m_LocalTransform = matLocalTransform;
SetName( Name );
}
//-----------------------------------------------------------------------------
// Name: Frame::~Frame()
//-----------------------------------------------------------------------------
Frame::~Frame()
{
SetParent( NULL );
}
//-----------------------------------------------------------------------------
// Name: Frame::AddChild()
//-----------------------------------------------------------------------------
VOID Frame::AddChild( Frame* pChild )
{
assert( pChild );
pChild->SetParent( this );
}
//-----------------------------------------------------------------------------
// Name: Frame::SetParent()
//-----------------------------------------------------------------------------
VOID Frame::SetParent( Frame* pParent )
{
Frame* pSrch, *pLast;
UpdateCachedWorldTransformIfNeeded();
if( m_pParent )
{
pLast = NULL;
for( pSrch = m_pParent->m_pFirstChild; pSrch; pSrch = pSrch->m_pNextSibling )
{
if( pSrch == this )
break;
pLast = pSrch;
}
// If we can't find this frame in the old parent's list, assert
assert( pSrch );
// Remove us from the list
if( pLast )
{
pLast->m_pNextSibling = m_pNextSibling;
}
else // at the beginning of the list
{
m_pParent->m_pFirstChild = m_pNextSibling;
}
m_pNextSibling = NULL;
m_pParent = NULL;
}
// Add us to the new parent's list
if( pParent )
{
m_pParent = pParent;
m_pNextSibling = pParent->m_pFirstChild;
pParent->m_pFirstChild = this;
}
// now we update our local transform to match the old world transform
// (i.e. move under our new parent's frame with no detectable change)
XMMATRIX worldMatrix = m_CachedWorldTransform;
SetWorldTransform( worldMatrix );
}
//-----------------------------------------------------------------------------
// Name: Frame::IsAncestor()
// Desc: Returns TRUE if the specified frame is an ancestor of this frame
// ancestor = parent, parent->parent, etc.
// Also returns TRUE if specified frame is NULL.
//-----------------------------------------------------------------------------
BOOL Frame::IsAncestor( Frame* pOtherFrame )
{
if( pOtherFrame == NULL )
return TRUE;
if( pOtherFrame == this )
return FALSE;
Frame* pFrame = GetParent();
while( pFrame != NULL )
{
if( pFrame == pOtherFrame )
return TRUE;
pFrame = pFrame->GetParent();
}
return FALSE;
}
//-----------------------------------------------------------------------------
// Name: Frame::IsChild()
// Desc: Returns TRUE if the specified frame is a direct child of this frame
//-----------------------------------------------------------------------------
BOOL Frame::IsChild( Frame* pOtherFrame )
{
if( pOtherFrame == NULL )
return FALSE;
Frame* pChild = GetFirstChild();
while( pChild != NULL )
{
if( pChild == pOtherFrame )
return TRUE;
pChild = pChild->GetNextSibling();
}
return FALSE;
}
//-----------------------------------------------------------------------------
// Name: Frame::GetWorldPosition()
//-----------------------------------------------------------------------------
XMVECTOR Frame::GetWorldPosition()
{
UpdateCachedWorldTransformIfNeeded();
return m_CachedWorldTransform.r[3];
}
//-----------------------------------------------------------------------------
// Name: Frame::SetWorldPosition()
//-----------------------------------------------------------------------------
VOID Frame::SetWorldPosition( CONST XMVECTOR &NewPosition )
{
UpdateCachedWorldTransformIfNeeded();
XMMATRIX ModifiedWorldTransform = m_CachedWorldTransform;
ModifiedWorldTransform.r[3] = NewPosition;
SetWorldTransform( ModifiedWorldTransform );
}
//-----------------------------------------------------------------------------
// Name: Frame::GetWorldTransform()
//-----------------------------------------------------------------------------
const XMMATRIX& Frame::GetWorldTransform()
{
UpdateCachedWorldTransformIfNeeded();
return m_CachedWorldTransform;
}
//-----------------------------------------------------------------------------
// Name: Frame::GetWorldRight()
//-----------------------------------------------------------------------------
XMVECTOR Frame::GetWorldRight()
{
UpdateCachedWorldTransformIfNeeded();
return m_CachedWorldTransform.r[0];
}
//-----------------------------------------------------------------------------
// Name: Frame::GetWorldUp()
//-----------------------------------------------------------------------------
XMVECTOR Frame::GetWorldUp()
{
UpdateCachedWorldTransformIfNeeded();
return m_CachedWorldTransform.r[1];
}
//-----------------------------------------------------------------------------
// Name: Frame::GetWorldDirection()
//-----------------------------------------------------------------------------
XMVECTOR Frame::GetWorldDirection()
{
UpdateCachedWorldTransformIfNeeded();
return m_CachedWorldTransform.r[2];
}
//-----------------------------------------------------------------------------
// Name: Frame::SetWorldTransform()
//-----------------------------------------------------------------------------
VOID Frame::SetWorldTransform( CONST XMMATRIX& WorldTransform )
{
XMMATRIX ParentInverse;
XMVECTOR vDeterminant;
if ( m_pParent )
{
m_pParent->UpdateCachedWorldTransformIfNeeded();
ParentInverse = XMMatrixInverse( &vDeterminant, m_pParent->m_CachedWorldTransform );
// Parent's matrix should be invertible
assert( XMVectorGetX( vDeterminant ) != 0.0f );
m_LocalTransform = XMMatrixMultiply( WorldTransform, ParentInverse );
}
else
{
m_LocalTransform = WorldTransform;
}
SetCachedWorldTransformDirty();
}
//-----------------------------------------------------------------------------
// Name: Frame::UpdateCachedWorldTransformIfNeeded()
//-----------------------------------------------------------------------------
VOID Frame::UpdateCachedWorldTransformIfNeeded()
{
if( IsCachedWorldTransformDirty() )
{
if( m_pParent )
{
m_pParent->UpdateCachedWorldTransformIfNeeded();
m_CachedWorldTransform = XMMatrixMultiply( m_LocalTransform, m_pParent->m_CachedWorldTransform );
m_CachedWorldBound = m_LocalBound * m_CachedWorldTransform;
}
else
{
m_CachedWorldTransform = m_LocalTransform;
m_CachedWorldBound = m_LocalBound * m_CachedWorldTransform;
}
}
}
//-----------------------------------------------------------------------------
// Name: Frame::SetCachedWorldTransformDirty()
//-----------------------------------------------------------------------------
VOID Frame::SetCachedWorldTransformDirty()
{
Frame* pChild;
SetCachedWorldTransformDirtyLocal();
for( pChild = m_pFirstChild; pChild; pChild = pChild->m_pNextSibling )
{
pChild->SetCachedWorldTransformDirty();
}
}
//-----------------------------------------------------------------------------
// Name: Frame::DisconnectFromParent
// Desc: Removes parent link from the object, and converts world transform
// to local transform. This method is only to be used on clones of
// scene objects, since the parent is not notified of the disconnection.
//-----------------------------------------------------------------------------
VOID Frame::DisconnectFromParent()
{
// Debug check to make sure the parent really isn't the parent of this clone
#ifdef _DEBUG
if( m_pParent != NULL )
{
assert( !m_pParent->IsChild( this ) );
}
#endif
UpdateCachedWorldTransformIfNeeded();
m_pParent = NULL;
SetWorldTransform( m_CachedWorldTransform );
}
} // namespace ATG
| [
"[email protected]"
] | [
[
[
1,
308
]
]
] |
ed5e99c355bc680b02f6451b02259503f3276635 | 828c44fe5fd08218b857677ffb9f4545803e7112 | /cob_utilities/common/src/TimeStamp.cpp | 6ee367fc8d17e3e2ccfc1b38eee3eb49cb2da2f4 | [] | no_license | attilaachenbach/cob_common | aabb3163997a32921f3a8ecc08c95ce09070e270 | 8b96f4987e972c9c0e897793dbd69062cd769d8d | refs/heads/master | 2020-05-30T23:24:18.044158 | 2011-05-17T07:38:46 | 2011-05-17T07:38:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,634 | cpp | /****************************************************************
*
* Copyright (c) 2010
*
* Fraunhofer Institute for Manufacturing Engineering
* and Automation (IPA)
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Project name: care-o-bot
* ROS stack name: cob3_common
* ROS package name: generic_can
* Description:
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* Author: Christian Connette, email:[email protected]
* Supervised by: Christian Connette, email:[email protected]
*
* Date of creation: Feb 2009
* ToDo: Check if this is still neccessary. Can we use the ROS-Infrastructure within the implementation?
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* 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 Fraunhofer Institute for Manufacturing
* Engineering and Automation (IPA) nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License LGPL for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
****************************************************************/
#include <cob_utilities/TimeStamp.h>
//-----------------------------------------------------------------------------
TimeStamp::TimeStamp()
{
m_TimeStamp.tv_sec = 0;
m_TimeStamp.tv_nsec = 0;
}
void TimeStamp::SetNow()
{
::clock_gettime(CLOCK_REALTIME, &m_TimeStamp);
}
double TimeStamp::TimespecToDouble(const ::timespec& LargeInt)
{
return double(LargeInt.tv_sec) + double(LargeInt.tv_nsec) / 1e9;
}
::timespec TimeStamp::DoubleToTimespec(double TimeS)
{
::timespec DeltaTime;
if (! ( TimeS < 4e9 && TimeS > 0.0 ))
{
DeltaTime.tv_sec = 0;
DeltaTime.tv_nsec = 0;
return DeltaTime;
}
DeltaTime.tv_sec = ::time_t(TimeS);
DeltaTime.tv_nsec
= static_cast<long int>((TimeS - double(DeltaTime.tv_sec)) * 1e9);
return DeltaTime;
}
double TimeStamp::operator-(const TimeStamp& EarlierTime) const
{
::timespec Res;
Res.tv_sec = m_TimeStamp.tv_sec - EarlierTime.m_TimeStamp.tv_sec;
Res.tv_nsec = m_TimeStamp.tv_nsec - EarlierTime.m_TimeStamp.tv_nsec;
if (Res.tv_nsec < 0) {
Res.tv_sec--;
Res.tv_nsec += 1000000000;
}
return TimespecToDouble(Res);
}
void TimeStamp::operator+=(double TimeS)
{
::timespec Dbl = DoubleToTimespec(TimeS);
m_TimeStamp.tv_sec += Dbl.tv_sec;
m_TimeStamp.tv_nsec += Dbl.tv_nsec;
if (m_TimeStamp.tv_nsec > 1000000000)
{
m_TimeStamp.tv_sec++;
m_TimeStamp.tv_nsec -= 1000000000;
}
}
void TimeStamp::operator-=(double TimeS)
{
::timespec Dbl = DoubleToTimespec(TimeS);
m_TimeStamp.tv_sec -= Dbl.tv_sec;
m_TimeStamp.tv_nsec -= Dbl.tv_nsec;
if (m_TimeStamp.tv_nsec < 0.0)
{
m_TimeStamp.tv_sec--;
m_TimeStamp.tv_nsec += 1000000000;
}
}
bool TimeStamp::operator>(const TimeStamp& Time)
{
if (m_TimeStamp.tv_sec > Time.m_TimeStamp.tv_sec) return true;
if ((m_TimeStamp.tv_sec == Time.m_TimeStamp.tv_sec) &&
(m_TimeStamp.tv_nsec > Time.m_TimeStamp.tv_nsec)) return true;
return false;
}
bool TimeStamp::operator<(const TimeStamp& Time)
{
if (m_TimeStamp.tv_sec < Time.m_TimeStamp.tv_sec) return true;
if ((m_TimeStamp.tv_sec == Time.m_TimeStamp.tv_sec) &&
(m_TimeStamp.tv_nsec < Time.m_TimeStamp.tv_nsec)) return true;
return false;
}
void TimeStamp::getTimeStamp(long& lSeconds, long& lNanoSeconds)
{
lSeconds = m_TimeStamp.tv_sec;
lNanoSeconds = m_TimeStamp.tv_nsec;
};
void TimeStamp::setTimeStamp(const long& lSeconds, const long& lNanoSeconds)
{
m_TimeStamp.tv_sec = lSeconds;
m_TimeStamp.tv_nsec = lNanoSeconds;
};
std::string TimeStamp::CurrentToString()
{
# define TIME_SIZE 400
const struct tm *tm;
size_t len;
time_t now;
char pres[TIME_SIZE];
std::string s;
now = time ( NULL );
tm = localtime ( &now );
len = strftime ( pres, TIME_SIZE, "%Y-%m-%d %H:%M:%S.", tm );
s = (std::string)pres + NumToString(m_TimeStamp.tv_nsec / 1000);
return s;
# undef TIME_SIZE
}
std::string TimeStamp::ToString()
{
# define TIME_SIZE 4000
const struct tm *tm;
size_t len;
time_t now;
char pres[TIME_SIZE];
std::string s;
tm = localtime ( &m_TimeStamp.tv_sec );
len = strftime ( pres, TIME_SIZE, "%Y-%m-%d %H:%M:%S.", tm );
s = (std::string)pres + NumToString(m_TimeStamp.tv_nsec / 1000);
return s;
# undef TIME_SIZE
}
| [
"[email protected]",
"cpc@cob3-2-pc1.(none)"
] | [
[
[
1,
53
],
[
55,
195
]
],
[
[
54,
54
]
]
] |
6f3009088f8b0e22b071bfe5063e74e78a0c1987 | 3532ae25961855b20635decd1481ed7def20c728 | /app/Idiot/idiotwindow.cpp | 61d517279e01fa04863458be8b1da118c00757e8 | [] | 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 | 1,217 | cpp | #include "idiotwindow.h"
#include "ui_idiotwindow.h"
IdiotWindow::IdiotWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::IdiotWindow),
connection(B_SOURCE_APP)
{
ui->setupUi(this);
ui->connectionWidget->setSettingsObject(&settings);
ui->connectionWidget->setConnectionObject(&connection);
startTimer(10);
}
IdiotWindow::~IdiotWindow()
{
connection.disconnectFromHost();
ui->connectionWidget->saveSettings();
delete ui;
}
void IdiotWindow::timerEvent(QTimerEvent *ev) {
BDatagram * datagram = NULL;
try {
datagram = connection.getData();
if(datagram) {
BObList * bobjects = new BObList(datagram->data);
ui->imageWidget->setBObs(datagram->sessid, bobjects);
ui->imageWidget->update();
delete datagram;
}
} catch (BConnectionException *e) {
qDebug() << e->toString();
datagram = e->getDatagram();
if(datagram) {
qDebug() << "DATAGRAM" << datagram->getAllData();
}
delete e;
}
}
void IdiotWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
| [
"santamon@ffdda973-792b-4bce-9e62-2343ac01ffa1"
] | [
[
[
1,
55
]
]
] |
d0dff1719fd02fb9fedde7b76ccd2ae6c845b48a | 698f3c3f0e590424f194a4c138ed9706eb28b34f | /Classes/GameOverScene.h | 7227becd5ef3ebb2922f4e64283b03f60269709a | [] | no_license | nghepop/super-fashion-puzzle-cocos2d-x | 16b3a86072a6758fc2547b9e177bbfeebed82681 | 5e8d8637e3cf70b4ec45256347ccf7b350c11bce | refs/heads/master | 2021-01-10T06:28:10.028735 | 2011-12-03T23:49:16 | 2011-12-03T23:49:16 | 44,685,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,121 | h |
#include "cocos2d.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
class GameOverScene : public cocos2d::CCScene
{
public:
GameOverScene(void){};
~GameOverScene(void);
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommand to return the exactly class pointer
static cocos2d::CCScene* scene();
// implement the "static node()" method manually
LAYER_NODE_FUNC(GameOverScene);
void goToMainMenu(void);
void goToPlayAgain(void);
// button handlers
void playAgainButtonPressed(CCObject* pSender);
void menuButtonPressed(CCObject* pSender);
#ifdef FREE_VERSION
void buyFullVersionButtonPressed(CCObject* pSender);
#endif
// modify lables information
void setHighScore(unsigned int highScore);
void setCurrentScore(unsigned int currentScore);
bool m_playedTooMuch;
PlayingScene* m_playingScene;
protected:
unsigned int m_level;
bool m_scoreWasSentProperly;
bool m_facebookWallWasWrittenProperly;
};
| [
"[email protected]"
] | [
[
[
1,
44
]
]
] |
9cac76c9bf79ebe257f1dbf2f16e50a7dac7f012 | d752d83f8bd72d9b280a8c70e28e56e502ef096f | /FugueDLL/Virtual Machine/Core Entities/Types/CompositeType.h | 45c39bfebbfd3d05bb4946eb94e7fe314b53913c | [] | no_license | apoch/epoch-language.old | f87b4512ec6bb5591bc1610e21210e0ed6a82104 | b09701714d556442202fccb92405e6886064f4af | refs/heads/master | 2021-01-10T20:17:56.774468 | 2010-03-07T09:19:02 | 2010-03-07T09:19:02 | 34,307,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,380 | h | //
// The Epoch Language Project
// FUGUE Virtual Machine
//
// Base class for all composite data types in Epoch.
// A composite data type is any construct which contains
// multiple members that are bound together in memory.
// Tuples and structures (records) are the primary kinds
// of composite type in Epoch.
//
#pragma once
// Dependencies
#include "Utility/Types/EpochTypeIDs.h"
// Forward declarations
namespace Serialization { class SerializationTraverser; }
namespace VM
{
// Forward declarations
class ScopeDescription;
class StructureType;
class TupleType;
class FunctionSignature;
//
// Base class for a composite type definition
//
class CompositeType
{
// Construction and destruction
public:
CompositeType()
: StorageSize(0)
{ }
virtual ~CompositeType()
{ }
// Member setup interface
public:
void AddMember(const std::wstring& name, EpochVariableTypeID type);
void AddMember(const std::wstring& name, const StructureType& structtype, IDType typehint);
void AddMember(const std::wstring& name, const TupleType& type, IDType typehint);
void AddFunctionMember(const std::wstring& name, const std::wstring& hint);
// Member query interface
public:
EpochVariableTypeID GetMemberType(const std::wstring& name) const;
IDType GetMemberTypeHint(const std::wstring& name) const;
const std::wstring& GetMemberTypeHintString(const std::wstring& name) const;
const std::vector<std::wstring>& GetMemberOrder() const
{ return MemberOrder; }
bool HasMember(const std::wstring& member) const
{ return (MemberInfoMap.find(member) != MemberInfoMap.end()); }
// Helpers for reading/writing members on the stack/heap
public:
virtual void ComputeOffsets(const ScopeDescription& scope) = 0;
size_t GetMemberOffset(const std::wstring& name) const;
virtual size_t GetMemberStorageSize() const = 0;
virtual size_t GetTotalSize() const = 0;
// Internal tracking
protected:
struct MemberInfo
{
EpochVariableTypeID Type;
size_t Offset;
IDType TypeHint;
std::wstring StringHint;
};
std::map<std::wstring, MemberInfo> MemberInfoMap;
std::vector<std::wstring> MemberOrder;
size_t StorageSize;
// Helper access to serializer
public:
friend class Serialization::SerializationTraverser;
};
}
| [
"[email protected]"
] | [
[
[
1,
94
]
]
] |
244582e6dc3293b5527d50b1021f09c28536c57a | c9630df0e019e54a19edd09e0ae2736102709d62 | /jacobi/trunk/jacobiMPI/io.cpp | ecb09f3b9142062b6e6a693fe402413b7e365b95 | [] | no_license | shaowei-su/jacobi-in-parallel | 45df2fdab6e32083b486ac088e1036fd085d4c1c | 8c772afd412945735d15f771f200c6cff30bdae3 | refs/heads/master | 2021-01-13T01:31:07.625534 | 2010-04-13T10:46:20 | 2010-04-13T10:46:20 | 33,940,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,848 | cpp | //input & output
#include "stdafx.h"
//********************************************************************************
//input
//********************************************************************************
//********************************************************************************
//get input arguments. there is 3 ways -
// way 1: read arguments from default .txt file named "input.txt";(no arguments)
// way 2: read arguments from certain .txt file whose name is the first arguments
// after command;(1 argument)
// way 3: read atguments directly from arguments.(9 arguments)
int input(int argc, char* argv[],
int *n, double *epsilon, long *step, struct boundary *b,
char *outFile)
{
if (argc == 1)
{
char *filename = DEFAULT_INPUT_FILE;
FILE *fp;
if ((fp = fopen(filename, "r")) == NULL)
{
printf("Cannot open defalut input file - %s.\n", filename);
return 1;
}
else
{
fscanf(fp, "%lf %lf %lf %lf\n",
&(*b).left, &(*b).up, &(*b).right, &(*b).down);
fscanf(fp, "%d\n", n);
fscanf(fp, "%lf\n", epsilon);
fscanf(fp, "%d\n", step);
fscanf(fp, "%s\n", outFile);
fclose(fp);
}
}
else if (argc == 2)
{
FILE *fp;
if ((fp = fopen(argv[1], "r")) == NULL)
{
printf("Cannot open given input file - %s.\n", argv[1]);
return 2;
}
else
{
fscanf(fp, "%lf %lf %lf %lf\n",
&(*b).left, &(*b).up, &(*b).right, &(*b).down);
fscanf(fp, "%d\n", n);
fscanf(fp, "%lf\n", epsilon);
fscanf(fp, "%d\n", step);
fscanf(fp, "%s\n", outFile);
fclose(fp);
}
}
else if (argc == 9)
{
*n = atoi(argv[1]);
*epsilon = atof(argv[2]);
printf("%s", argv[3]);
*step = atoi(argv[3]);
(*b).left = atof(argv[4]);
(*b).up = atof(argv[5]);
(*b).right = atof(argv[6]);
(*b).down = atof(argv[7]);
strcpy(outFile, argv[8]);
}
else
{
printf("The count of arguments is wrong. Check it. \n");
return 3;
}
return 0;
//000000
}
//********************************************************************************
//output
//********************************************************************************
//********************************************************************************
//get output directory name and creat the directory
char* getOutDir(int n, double epsilon, struct boundary b,
long step, char *outFile)
{
char *s = (char *)malloc(sizeof(char) * 128);
sprintf(s, "%s_n%de%.2lfs%dlurd%.2lf%.2lf%.2lf%.2lf",
outFile, n, epsilon, step, b.left, b.up, b.right, b.down);
mkdir(s);
return s;
}
//********************************************************************************
//
void outMatrix1DtoF(const double *m, const int n, const char *dir)
{
char *filename = (char *)malloc(sizeof(char) * 256);
sprintf(filename, "%s\\%s_m.txt", dir, dir);
FILE *fp;
if((fp = fopen(filename, "at")) == NULL)
{
printf("cannot open %s \n", filename);
return;
}
else
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
fprintf(fp, "%lf ", m[i * n + j]);
fprintf(fp, "\n");
}
fclose(fp);
}
return;
}
//********************************************************************************
//
void outMatrix2DtoF(double **m, const int n, const char *dir)
{
char *filename = (char *)malloc(sizeof(char) * 256);
sprintf(filename, "%s\\%s_m.txt", dir, dir);
FILE *fp;
if((fp = fopen(filename, "at")) == NULL)
{
printf("cannot open %s \n", filename);
return;
}
else
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
fprintf(fp, "%lf ", m[i][j]);
fprintf(fp, "\n");
}
fclose(fp);
}
return;
}
//********************************************************************************
//
void outLog(int n, double epsilon,
long step, struct boundary b,
double nTime1, double nTime2, double nTime3,
char *outFile, char *dir)
{
char *filename = (char *)malloc(sizeof(char) * 256);
sprintf(filename, "%s\\%s_log.txt", dir, dir);
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime ( &rawtime );
FILE *fp;
if((fp = fopen(filename, "at")) == NULL)
{
printf("cannot open %s \n", filename);
return;
}
else
{
fprintf(fp, "Jacobi - %s\n", outFile);
fprintf(fp, "--%s", asctime (timeinfo));
fprintf(fp, "--N = %d, Epsilon = %lf, Step = %ld\n", n, epsilon, step);
fprintf(fp, "--Boundary - left = %lf, right = %lf, up = %lf, down = %lf\n",
b.left, b.right, b.up, b.down);
fprintf(fp, "--(Time/s)Init=%lf, Computing=%lf, Data-saving=%lf, Total=%lf\n",
nTime1, nTime2, nTime3, nTime1 + nTime2 + nTime3);
fprintf(fp, "--data file - %s_m.txt\n\n", dir);
fclose(fp);
}
return;
}
| [
"Snigoal@aed88cc7-7f53-aada-5582-5968519015a4"
] | [
[
[
1,
183
]
]
] |
48b6c790506ba298f47ab6bf18f9f1a7365fb34b | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/nebula2/src/kernel/nipcclient.cc | 406bced8d4b69eb16ee0519c4fec66c2ff4db644 | [] | no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,738 | cc | //------------------------------------------------------------------------------
// nipcclient.cc
// (C) 2003 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "kernel/nipcclient.h"
//------------------------------------------------------------------------------
/**
*/
nIpcClient::nIpcClient() :
sock(INVALID_SOCKET),
isConnected(false),
blocking(true)
{
#if __WIN32__
struct WSAData wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
#endif
}
//------------------------------------------------------------------------------
/**
*/
nIpcClient::~nIpcClient()
{
if (this->isConnected)
{
this->Disconnect();
}
#if __WIN32__
WSACleanup();
#endif
}
//------------------------------------------------------------------------------
/**
*/
void
nIpcClient::DestroySocket()
{
if (this->sock != INVALID_SOCKET)
{
shutdown(this->sock, 2);
closesocket(this->sock);
this->sock = INVALID_SOCKET;
}
}
//------------------------------------------------------------------------------
/**
*/
void
nIpcClient::ApplyBlocking(bool b)
{
if (b)
{
// enable blocking
#ifdef __WIN32__
u_long falseAsUlong = 0;
int res = ioctlsocket(this->sock, FIONBIO, &falseAsUlong);
#elif defined(__LINUX__) || defined(__MACOSX__)
int flags;
flags = fcntl(this->sock, F_GETFL);
flags &= ~O_NONBLOCK;
int res = fcntl(this->sock, F_SETFL, flags);
#endif
n_assert(0 == res);
}
else
{
// disable blocking
#ifdef __WIN32__
u_long trueAsUlong = 1;
int res = ioctlsocket(this->sock, FIONBIO, &trueAsUlong);
#elif defined(__LINUX__) || defined(__MACOSX__)
int flags;
flags = fcntl(this->sock, F_GETFL);
flags |= O_NONBLOCK;
int res = fcntl(this->sock, F_SETFL, flags);
#endif
n_assert(0 == res);
}
}
//------------------------------------------------------------------------------
/**
*/
void
nIpcClient::SetBlocking(bool b)
{
this->blocking = b;
if (this->isConnected)
{
this->ApplyBlocking(b);
}
}
//------------------------------------------------------------------------------
/**
*/
bool
nIpcClient::GetBlocking() const
{
return this->blocking;
}
//------------------------------------------------------------------------------
/**
Establish a connection to the ipc server identified by the nIpcAddress
object.
*/
bool
nIpcClient::Connect(nIpcAddress& addr)
{
if (!this->isConnected)
{
this->serverAddr = addr;
// create socket (in blocking mode)
this->sock = socket(AF_INET, SOCK_STREAM, 0);
n_assert(this->sock != INVALID_SOCKET);
// configure the socket
int trueAsInt = 1;
int res = setsockopt(this->sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&trueAsInt, sizeof(trueAsInt));
n_assert(res != -1);
// try connection
n_printf("nIpcClient: trying host %s port %d...\n", addr.GetHostName(), addr.GetPortNum());
res = connect(this->sock, (const sockaddr*) &(addr.GetAddrStruct()), sizeof(addr.GetAddrStruct()));
if (res == -1)
{
// connection failed.
n_printf("nIpcClient: failed to connect to host %s port %d!\n", addr.GetHostName(), addr.GetPortNum());
this->DestroySocket();
return false;
}
// send handshake
char msg[256];
sprintf(msg, "~handshake %s", addr.GetPortName());
res = send(this->sock, msg, strlen(msg) + 1, 0);
if (res == -1)
{
// initial send failed!
n_printf("nIpcClient: failed to send handshake to host %s port %d!\n", addr.GetHostName(), addr.GetPortNum());
this->DestroySocket();
return false;
}
// put socket into nonblocking mode?
this->ApplyBlocking(this->blocking);
// all ok
this->isConnected = true;
n_printf("\nConnected.");
}
return true;
}
//------------------------------------------------------------------------------
/**
Disconnect from the server.
*/
void
nIpcClient::Disconnect()
{
if (this->isConnected)
{
n_assert(INVALID_SOCKET != this->sock);
// send a close message to the server
const char* cmd = "~close";
int res = send (this->sock, cmd, strlen(cmd) + 1, 0);
if (res == -1)
{
n_printf("nIpcClient: failed to send close msg to host %s port %s\n",
this->serverAddr.GetHostName(), this->serverAddr.GetPortName());
}
this->DestroySocket();
this->isConnected = false;
}
}
//------------------------------------------------------------------------------
/**
*/
bool
nIpcClient::IsConnected() const
{
return this->isConnected;
}
//------------------------------------------------------------------------------
/**
*/
bool
nIpcClient::Send(const nIpcBuffer& msg)
{
if (this->isConnected)
{
n_assert(INVALID_SOCKET != this->sock);
int res = send(this->sock, msg.GetPointer(), msg.GetSize(), 0);
if (-1 == res)
{
n_printf("nIpcClient: Send() failed!\n");
this->Disconnect();
return false;
}
return true;
}
return false;
}
//------------------------------------------------------------------------------
/**
Receive a message. This method may block if the connection has been
created with blocking on.
*/
bool
nIpcClient::Receive(nIpcBuffer& msg)
{
n_assert(INVALID_SOCKET != this->sock);
int res = recv(this->sock, msg.GetPointer(), msg.GetMaxSize(), 0);
if (res == 0 || N_SOCKET_LAST_ERROR == N_ECONNRESET)
{
// the connection has been closed
n_printf("connection lost!\n");
this->DestroySocket();
this->isConnected = false;
}
if (res > 0)
{
msg.SetSize(res);
return true;
}
else
{
// either an error occured, or the method would block
if (N_SOCKET_LAST_ERROR == N_EWOULDBLOCK)
{
msg.SetSize(0);
}
else
{
// FIXME: some other error then WouldBlock
n_printf("nIpcClient::Receive(): failed!\n");
}
return false;
}
}
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
253
]
]
] |
dec974da0690b1db061a89fe5c84bf7bb964689f | 499b07b3c6d0efcb726d24958b8491dac15ccdc2 | /Clock/clock.cpp | 52d215cc9954b8a20e80b847ef41d996918fec96 | [] | no_license | opu-yokotalab/learn-capture | df8486eb50567e3638b1990be687f971915c10d7 | 64fd8227f756659102b40ff318654138e90be351 | refs/heads/master | 2021-01-10T06:00:19.337245 | 2009-11-26T13:02:43 | 2009-11-26T13:02:43 | 43,799,808 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,428 | cpp | // Clock.cpp : アプリケーション用クラスの定義を行います。
//
#include "stdafx.h"
#include "Clock.h"
#include "ClockDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CClockApp
BEGIN_MESSAGE_MAP(CClockApp, CWinApp)
//{{AFX_MSG_MAP(CClockApp)
// メモ - ClassWizard はこの位置にマッピング用のマクロを追加または削除します。
// この位置に生成されるコードを編集しないでください。
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CClockApp クラスの構築
CClockApp::CClockApp()
{
// TODO: この位置に構築用のコードを追加してください。
// ここに InitInstance 中の重要な初期化処理をすべて記述してください。
}
/////////////////////////////////////////////////////////////////////////////
// 唯一の CClockApp オブジェクト
CClockApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CClockApp クラスの初期化
BOOL CClockApp::InitInstance()
{
// 標準的な初期化処理
// もしこれらの機能を使用せず、実行ファイルのサイズを小さくしたけ
// れば以下の特定の初期化ルーチンの中から不必要なものを削除して
// ください。
#ifdef _AFXDLL
Enable3dControls(); // 共有 DLL 内で MFC を使う場合はここをコールしてください。
#else
Enable3dControlsStatic(); // MFC と静的にリンクする場合はここをコールしてください。
#endif
CClockDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: ダイアログが <OK> で消された時のコードを
// 記述してください。
}
else if (nResponse == IDCANCEL)
{
// TODO: ダイアログが <キャンセル> で消された時のコードを
// 記述してください。
}
// ダイアログが閉じられてからアプリケーションのメッセージ ポンプを開始するよりは、
// アプリケーションを終了するために FALSE を返してください。
return FALSE;
}
| [
"learn@771d582f-26de-40c8-865b-cc2b4e630f49"
] | [
[
[
1,
72
]
]
] |
9238d09d32153c3ed5298d42d3a70938961c57b2 | 1cc5720e245ca0d8083b0f12806a5c8b13b5cf98 | /archive/a3125/c.cpp | 330e5783c6c19a8dd31326b39f8cf8a9f5ec739b | [] | no_license | Emerson21/uva-problems | 399d82d93b563e3018921eaff12ca545415fd782 | 3079bdd1cd17087cf54b08c60e2d52dbd0118556 | refs/heads/master | 2021-01-18T09:12:23.069387 | 2010-12-15T00:38:34 | 2010-12-15T00:38:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,191 | cpp | #include <iostream>
#define FOR(a,b) for(a=0;a<b;a++)
using namespace std;
int p[100][2];
bool hat[50][50];
int s,h;
void le() {
int a,b,c;
cin >> s >> h;
FOR(a,s+1) FOR(b,s+1) hat[a][b] = false;
FOR(c,h) {
cin >> a >> b;
p[c][0] = a;
p[c][1] = b;
hat[b][a] = true;
}
}
int min(int a,int b) {
return a<b?a:b;
}
int DIST(int x,int y,int pt) {
return (x-p[pt][0])*(x-p[pt][0]) + (y-p[pt][1])*(y-p[pt][1]);
}
bool st() {
le();
int mx,my,x,y,i,j,k,pt;
int menor=-1,dist,maior,temp;
FOR(x,s) {
FOR(y,s) {
if(hat[y][x]) continue;
maior = min(min(x,s-x),min(y,s-y));
maior *= maior;
cout << x << " " << y << " " << maior << endl;
temp = -1;
FOR(pt,h) {
dist = DIST(x,y,pt);
if(dist>maior) break;
if(dist>temp) temp = dist;
}
cout << "t: " << pt << " " << dist << endl;
if(pt!=h) continue;
if(menor==-1 || temp<menor) {
menor = temp;
mx = x; my = y;
}
}
}
if(menor==-1) return false;
cout << mx << " " << my << endl;
return true;
}
int main() {
int t;
cin >> t;
while(t--) {
if(!st()) cout << "poodle" << endl;
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
73
]
]
] |
2b6a204fe5bd228b8a668830d48719c81c319f24 | 49340251ce63c14e953a82fd7d7f06de458f25b3 | /vm2/mstr/mstr.h | 008869601ed0d13149158f82bb3bdf1bfb194afe | [] | no_license | umegaya/pfm | aa104fc9ec04a60d5096fdafd9f20d4e4f735343 | 40d40bd6346dc9dccb20558e69b64a90f591bae4 | refs/heads/master | 2021-01-25T12:09:25.296418 | 2010-09-06T21:25:33 | 2010-09-06T21:25:33 | 86,939 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,662 | h | #if !defined(__MSTR_H__)
#define __MSTR_H__
#include "common.h"
#include "fiber.h"
#include "dbm.h"
#include "proto.h"
#include "connector.h"
#include "world.h"
namespace pfm {
using namespace sfc;
namespace mstr {
class fiber : public rpc::basic_fiber {
public:
struct account_info {
UUID m_uuid;
world_id m_login_wid;
account_info() : m_uuid(), m_login_wid(NULL) {}
bool is_login() const { return m_login_wid != NULL; }
bool login(world_id wid) {
return __sync_bool_compare_and_swap(&m_login_wid, NULL, wid);
}
const UUID &uuid() const { return m_uuid; }
int save(char *&p, int &l, void *) {
int thissz = (int)sizeof(*this);
if (l <= thissz) {
ASSERT(false);
if (!(p = (char *)nbr_malloc(thissz))) {
return NBR_EMALLOC;
}
l = thissz;
}
memcpy(p, (void *)&m_uuid, sizeof(UUID));
return sizeof(UUID);
}
int load(const char *p, int l, void *) {
m_uuid = *(UUID *)p;
return NBR_OK;
}
};
typedef pmap<account_info,
char[rpc::login_request::max_account]> account_list;
typedef rpc::basic_fiber super;
static account_list m_al;
public: /* master quorum base replication */
typedef super::quorum_context quorum_context;
int quorum_vote_commit(world *w, MSGID msgid, quorum_context *ctx, serializer &sr);
int quorum_global_commit(world *w, quorum_context *ctx, int result);
quorum_context *init_context(world *w);
static int quorum_vote_callback(rpc::response &r, class conn *c, void *ctx);
public:
static int init_global(int max_account, const char *dbpath);
static void fin_global() { m_al.fin(); }
public:
int respond(bool err, serializer &sr) {
return basic_fiber::respond<mstr::fiber>(err, sr);
}
int send_error(int r) { return basic_fiber::send_error<mstr::fiber>(r); }
int call_login(rpc::request &req);
int resume_login(rpc::response &res);
int call_logout(rpc::request &req);
int resume_logout(rpc::response &res);
int call_replicate(rpc::request &req, char *, int)
{ ASSERT(false); return NBR_ENOTSUPPORT; }
int resume_replicate(rpc::response &res) {
ASSERT(false); return NBR_ENOTSUPPORT; }
int call_node_inquiry(rpc::request &req);
int resume_node_inquiry(rpc::response &res);
public:
int node_ctrl_add(class world *, rpc::node_ctrl_cmd::add &, serializer &);
int node_ctrl_add_resume(class world *, rpc::response &, serializer &);
int node_ctrl_del(class world *, rpc::node_ctrl_cmd::del &, serializer &);
int node_ctrl_del_resume(class world *, rpc::response &, serializer &);
int node_ctrl_list(class world *, rpc::node_ctrl_cmd::list &, serializer &);
int node_ctrl_list_resume(class world *, rpc::response &, serializer &);
int node_ctrl_deploy(class world *, rpc::node_ctrl_cmd::deploy &, serializer &);
int node_ctrl_deploy_resume(class world *, rpc::response &, serializer &);
int call_node_regist(rpc::request &);
};
}
class pfmm : public app::daemon {
protected:
fiber_factory<mstr::fiber> &m_ff;
class connector_factory &m_cf;
dbm m_db;
serializer m_sr;
public:
pfmm(fiber_factory<mstr::fiber> &ff,
class connector_factory &cf) :
m_ff(ff), m_cf(cf), m_db(), m_sr() {}
fiber_factory<mstr::fiber> &ff() { return m_ff; }
serializer &sr() { return m_sr; }
base::factory *create_factory(const char *sname);
int create_config(config* cl[], int size);
int boot(int argc, char *argv[]);
void shutdown();
int initlib(CONFIG &c) { return NBR_OK; }
};
namespace mstr {
/* session */
class session : public conn {
public:
static class pfmm *m_daemon;
static bool m_test_mode;
public:
typedef conn super;
session() : super() {}
~session() {}
static class pfmm &app() { return *m_daemon; }
static int node_delete_cb(serializer &) { return NBR_OK; }
public:
pollret poll(UTIME ut, bool from_worker) {
/* check timeout */
if (from_worker) {
app().ff().poll(time(NULL));
}
return super::poll(ut, from_worker);
}
void fin() {}
int on_open(const config &cfg) { return super::on_open(cfg); }
int on_close(int reason) {
if (has_node_data()) {
session::app().ff().wf().remove_node(addr());
world_factory::iterator wit =
session::app().ff().wf().begin(), tmp;
for (; wit != session::app().ff().wf().end(); ) {
if (wit->nodes().use() == 0) {
/* FIXME : need to notice other master nodes? */
TRACE("World destroy (%s)\n", wit->id());
tmp = wit;
wit = session::app().ff().wf().next(wit);
session::app().ff().wf().unload(tmp->id(),
session::app().ff().vm());
continue;
}
int r;
serializer *psr = &(app().ff().sr());
if (!psr) {
/* from main thread (shutdown case) so nothing to do */
wit = session::app().ff().wf().next(wit);
continue;
}
serializer &sr = app().ff().sr();
PREPARE_PACK(sr);
if ((r = rpc::node_ctrl_cmd::del::pack_header(
sr, app().ff().new_msgid(),
wit->id(), nbr_str_length(wit->id(), max_wid),
node_data()->iden,
nbr_str_length(node_data()->iden, address::SIZE))) < 0) {
ASSERT(false);
wit = session::app().ff().wf().next(wit);
continue;
}
if ((r = app().ff().run_fiber(node_delete_cb, sr.p(), sr.len())) < 0) {
ASSERT(false);
wit = session::app().ff().wf().next(wit);
continue;
}
wit = session::app().ff().wf().next(wit);
}
}
return super::on_close(reason);
}
int on_recv(char *p, int l) {
app().ff().recv((class conn *)this, p, l, true);
return NBR_OK;
}
int on_event(char *p, int l) {
return app().ff().recv((class conn *)this, p, l, true);
}
};
class msession : public session {
public:
static int node_regist_cb(serializer &sr) {
rpc::response res;
PREPARE_UNPACK(sr);
if (sr.unpack(res, sr.p(), sr.len()) > 0 && res.success()) {
TRACE("node regist success\n");
}
return NBR_OK;
}
int on_open(const config &cfg) {
if (!app().ff().ffutil::initialized() && !app().ff().init_tls()) {
ASSERT(false);
return NBR_EINVAL;
}
int r;
serializer &sr = app().ff().sr();
PREPARE_PACK(sr);
factory *f = app().find_factory<factory>("mstr");
if (!f) { return NBR_ENOTFOUND; }
if ((r = rpc::node_ctrl_cmd::regist::pack_header(
sr, app().ff().new_msgid(),
f->ifaddr(), f->ifaddr().len(), master_node)) < 0) {
ASSERT(false);
return r;
}
if ((r = app().ff().run_fiber(node_regist_cb, sr.p(), sr.len())) < 0) {
ASSERT(false);
return r;
}
return super::on_open(cfg);
}
int on_close(int reason) { return super::on_close(reason); }
};
}
}
#endif
| [
"[email protected]"
] | [
[
[
1,
214
]
]
] |
68f2c471d01a3f3c01b83ec260a167d6414b5b84 | 95e051bc96bd3f765ce1cec4868535b667be81b6 | /ExplodedView_old/src/TriangleVertexVisitor.h | d1e177c785fb0a69f8e74ad998525a499dc9e8c5 | [] | no_license | fabio-miranda/exploded | 6aacdb5ca1250b676990572ef028fcbc0af93b1a | 12ca185b161b78d0b903c86fb5a08cee3ed87362 | refs/heads/master | 2021-05-29T09:06:03.007813 | 2010-02-26T04:40:32 | 2010-02-26T04:40:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | h | #ifndef TRIANGLEVERTEXVISITOR_H
#define TRIANGLEVERTEXVISITOR_H
//#include "PQP.H"
//#include "VCollide.H"
#include <osg/NodeVisitor>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Geometry>
#include <osgSim/DOFTransform>
#include <iostream>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
class TriangleVertexVisitor
{
public:
vector<double*>* m_verticesArray;
TriangleVertexVisitor(){
m_verticesArray = new vector<double*>();
}
void operator() (const osg::Vec3& v1, const osg::Vec3& v2, const osg::Vec3& v3, bool)
{
double* vertice1 = new double[3];
double* vertice2 = new double[3];
double* vertice3 = new double[3];
vertice1[0] = v1.x(); vertice1[1] = v1.y(); vertice1[2] = v1.z();
vertice2[0] = v2.x(); vertice2[1] = v2.y(); vertice2[2] = v2.z();
vertice3[0] = v3.x(); vertice3[1] = v3.y(); vertice3[2] = v3.z();
m_verticesArray->push_back(vertice1);
m_verticesArray->push_back(vertice2);
m_verticesArray->push_back(vertice3);
}
};
#endif
| [
"fabiom@2fa1dc7e-98ce-11de-bff5-93fd3790126f"
] | [
[
[
1,
48
]
]
] |
536877edbb43d2f9ac0478999a3d9f6c59a55c56 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/math/test/common_factor_test.cpp | d636d64e933dac6b573472e9fdbbd2caf637b862 | [] | no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,149 | cpp | // Boost GCD & LCM common_factor.hpp test program --------------------------//
// (C) Copyright Daryle Walker 2001.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version including documentation.
// Revision History
// 07 Nov 2001 Initial version (Daryle Walker)
#define BOOST_INCLUDE_MAIN
#include <boost/config.hpp> // for BOOST_MSVC
#include <boost/cstdlib.hpp> // for boost::exit_success
#include <boost/math/common_factor.hpp> // for boost::math::gcd, etc.
#include <boost/test/test_tools.hpp> // for main, BOOST_TEST
#include <iostream> // for std::cout (std::endl indirectly)
// Control to determine what kind of built-in integers are used
#ifndef CONTROL_INT_TYPE
#define CONTROL_INT_TYPE int
#endif
// Main testing function
int
test_main
(
int , // "argc" is unused
char * [] // "argv" is unused
)
{
using std::cout;
using std::endl;
#ifndef BOOST_MSVC
using boost::math::gcd;
using boost::math::static_gcd;
using boost::math::lcm;
using boost::math::static_lcm;
#else
using namespace boost::math;
#endif
typedef CONTROL_INT_TYPE int_type;
typedef unsigned CONTROL_INT_TYPE uint_type;
// GCD tests
cout << "Doing tests on gcd." << endl;
BOOST_TEST( gcd<int_type>( 1, -1) == 1 );
BOOST_TEST( gcd<int_type>( -1, 1) == 1 );
BOOST_TEST( gcd<int_type>( 1, 1) == 1 );
BOOST_TEST( gcd<int_type>( -1, -1) == 1 );
BOOST_TEST( gcd<int_type>( 0, 0) == 0 );
BOOST_TEST( gcd<int_type>( 7, 0) == 7 );
BOOST_TEST( gcd<int_type>( 0, 9) == 9 );
BOOST_TEST( gcd<int_type>( -7, 0) == 7 );
BOOST_TEST( gcd<int_type>( 0, -9) == 9 );
BOOST_TEST( gcd<int_type>( 42, 30) == 6 );
BOOST_TEST( gcd<int_type>( 6, -9) == 3 );
BOOST_TEST( gcd<int_type>(-10, -10) == 10 );
BOOST_TEST( gcd<int_type>(-25, -10) == 5 );
BOOST_TEST( gcd<int_type>( 3, 7) == 1 );
BOOST_TEST( gcd<int_type>( 8, 9) == 1 );
BOOST_TEST( gcd<int_type>( 7, 49) == 7 );
// GCD tests
cout << "Doing tests on unsigned-gcd." << endl;
BOOST_TEST( gcd<uint_type>( 1u, 1u) == 1u );
BOOST_TEST( gcd<uint_type>( 0u, 0u) == 0u );
BOOST_TEST( gcd<uint_type>( 7u, 0u) == 7u );
BOOST_TEST( gcd<uint_type>( 0u, 9u) == 9u );
BOOST_TEST( gcd<uint_type>( 42u, 30u) == 6u );
BOOST_TEST( gcd<uint_type>( 3u, 7u) == 1u );
BOOST_TEST( gcd<uint_type>( 8u, 9u) == 1u );
BOOST_TEST( gcd<uint_type>( 7u, 49u) == 7u );
cout << "Doing tests on static_gcd." << endl;
BOOST_TEST( (static_gcd< 1, 1>::value) == 1 );
BOOST_TEST( (static_gcd< 0, 0>::value) == 0 );
BOOST_TEST( (static_gcd< 7, 0>::value) == 7 );
BOOST_TEST( (static_gcd< 0, 9>::value) == 9 );
BOOST_TEST( (static_gcd<42, 30>::value) == 6 );
BOOST_TEST( (static_gcd< 3, 7>::value) == 1 );
BOOST_TEST( (static_gcd< 8, 9>::value) == 1 );
BOOST_TEST( (static_gcd< 7, 49>::value) == 7 );
// LCM tests
cout << "Doing tests on lcm." << endl;
BOOST_TEST( lcm<int_type>( 1, -1) == 1 );
BOOST_TEST( lcm<int_type>( -1, 1) == 1 );
BOOST_TEST( lcm<int_type>( 1, 1) == 1 );
BOOST_TEST( lcm<int_type>( -1, -1) == 1 );
BOOST_TEST( lcm<int_type>( 0, 0) == 0 );
BOOST_TEST( lcm<int_type>( 6, 0) == 0 );
BOOST_TEST( lcm<int_type>( 0, 7) == 0 );
BOOST_TEST( lcm<int_type>( -5, 0) == 0 );
BOOST_TEST( lcm<int_type>( 0, -4) == 0 );
BOOST_TEST( lcm<int_type>( 18, 30) == 90 );
BOOST_TEST( lcm<int_type>( -6, 9) == 18 );
BOOST_TEST( lcm<int_type>(-10, -10) == 10 );
BOOST_TEST( lcm<int_type>( 25, -10) == 50 );
BOOST_TEST( lcm<int_type>( 3, 7) == 21 );
BOOST_TEST( lcm<int_type>( 8, 9) == 72 );
BOOST_TEST( lcm<int_type>( 7, 49) == 49 );
cout << "Doing tests on unsigned-lcm." << endl;
BOOST_TEST( lcm<uint_type>( 1u, 1u) == 1u );
BOOST_TEST( lcm<uint_type>( 0u, 0u) == 0u );
BOOST_TEST( lcm<uint_type>( 6u, 0u) == 0u );
BOOST_TEST( lcm<uint_type>( 0u, 7u) == 0u );
BOOST_TEST( lcm<uint_type>( 18u, 30u) == 90u );
BOOST_TEST( lcm<uint_type>( 3u, 7u) == 21u );
BOOST_TEST( lcm<uint_type>( 8u, 9u) == 72u );
BOOST_TEST( lcm<uint_type>( 7u, 49u) == 49u );
cout << "Doing tests on static_lcm." << endl;
BOOST_TEST( (static_lcm< 1, 1>::value) == 1 );
BOOST_TEST( (static_lcm< 0, 0>::value) == 0 );
BOOST_TEST( (static_lcm< 6, 0>::value) == 0 );
BOOST_TEST( (static_lcm< 0, 7>::value) == 0 );
BOOST_TEST( (static_lcm<18, 30>::value) == 90 );
BOOST_TEST( (static_lcm< 3, 7>::value) == 21 );
BOOST_TEST( (static_lcm< 8, 9>::value) == 72 );
BOOST_TEST( (static_lcm< 7, 49>::value) == 49 );
return boost::exit_success;
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
138
]
]
] |
d7d27400ce3c0ffe46e2bd79b072d0e2abc7d55b | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/TrayMenuBtn.cpp | 0a8ae3ee3953b60af10ae4af65fb3f31828494e6 | [] | 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 | 3,394 | cpp | #include "stdafx.h"
#include "TrayMenuBtn.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CTrayMenuBtn
BEGIN_MESSAGE_MAP(CTrayMenuBtn, CWnd)
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONUP()
ON_WM_PAINT()
END_MESSAGE_MAP()
CTrayMenuBtn::CTrayMenuBtn()
{
m_bBold = false;
m_bMouseOver = false;
m_bNoHover = false;
m_bUseIcon = false;
m_bParentCapture = false;
m_nBtnID = rand();
m_sIcon.cx = 0;
m_sIcon.cy = 0;
m_hIcon = NULL;
(void)m_strText;
(void)m_cfFont;
}
CTrayMenuBtn::~CTrayMenuBtn()
{
if (m_hIcon)
DestroyIcon(m_hIcon);
}
void CTrayMenuBtn::OnMouseMove(UINT nFlags, CPoint point)
{
CRect rClient;
GetClientRect(rClient);
if (point.x >= rClient.left && point.x <= rClient.right &&
point.y >= rClient.top && point.y <= rClient.bottom)
{
SetCapture();
if (!m_bNoHover)
m_bMouseOver = true;
Invalidate();
}
else
{
if (m_bParentCapture)
{
CWnd *pParent = GetParent();
if (pParent)
pParent->SetCapture();
else
ReleaseCapture();
}
else
ReleaseCapture();
m_bMouseOver = false;
Invalidate();
}
CWnd::OnMouseMove(nFlags, point);
}
void CTrayMenuBtn::OnLButtonUp(UINT nFlags, CPoint point)
{
CRect rClient;
GetClientRect(rClient);
if (point.x >= rClient.left && point.x <= rClient.right &&
point.y >= rClient.top && point.y <= rClient.bottom)
{
CWnd *pParent = GetParent();
if (pParent)
pParent->PostMessage(WM_COMMAND, MAKEWPARAM(m_nBtnID, BN_CLICKED), (long)m_hWnd);
}
else
{
ReleaseCapture();
m_bMouseOver = false;
Invalidate();
}
CWnd::OnLButtonUp(nFlags, point);
}
void CTrayMenuBtn::OnPaint()
{
CPaintDC dc(this); // device context for painting
CRect rClient;
GetClientRect(rClient);
CDC MemDC;
MemDC.CreateCompatibleDC(&dc);
CBitmap MemBMP, *pOldBMP;
MemBMP.CreateCompatibleBitmap(&dc, rClient.Width(), rClient.Height());
pOldBMP = MemDC.SelectObject(&MemBMP);
CFont *pOldFONT = NULL;
if (m_cfFont.GetSafeHandle())
pOldFONT = MemDC.SelectObject(&m_cfFont);
BOOL bEnabled = IsWindowEnabled();
if (m_bMouseOver && bEnabled)
{
FillRect(MemDC.m_hDC, rClient, GetSysColorBrush(COLOR_HIGHLIGHT));
MemDC.SetTextColor(GetSysColor(COLOR_HIGHLIGHTTEXT));
}
else
{
FillRect(MemDC.m_hDC, rClient, GetSysColorBrush(COLOR_BTNFACE));
MemDC.SetTextColor(GetSysColor(COLOR_BTNTEXT));
}
int iLeftOffset = 0;
if (m_bUseIcon)
{
MemDC.DrawState(CPoint(2, rClient.Height()/2 - m_sIcon.cy/2), CSize(16, 16), m_hIcon, DST_ICON | DSS_NORMAL, (CBrush *)NULL);
iLeftOffset = m_sIcon.cx + 4;
}
MemDC.SetBkMode(TRANSPARENT);
CRect rText(0, 0, 0, 0);
MemDC.DrawText(m_strText, rText, DT_CALCRECT | DT_SINGLELINE | DT_LEFT);
CPoint pt(rClient.left + 2 + iLeftOffset, rClient.Height()/2 - rText.Height()/2);
CPoint sz(rText.Width(), rText.Height());
MemDC.DrawState(pt, sz, m_strText, DST_TEXT | (bEnabled ? DSS_NORMAL : DSS_DISABLED),
FALSE, m_strText.GetLength(), (CBrush*)NULL);
dc.BitBlt(0, 0, rClient.Width(), rClient.Height(), &MemDC, 0, 0, SRCCOPY);
MemDC.SelectObject(pOldBMP);
MemBMP.DeleteObject(); //Xman Code Improvement
if (pOldFONT)
MemDC.SelectObject(pOldFONT);
}
| [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b"
] | [
[
[
1,
145
]
]
] |
9e325313cc475301238f75441f8a9f051bc17d67 | f177993b13e97f9fecfc0e751602153824dfef7e | /ImPro/OtherLib/OpenCV2.1/vs2008/include/opencv2/ml/ml.hpp | 1c8067fc8936c42bbd17a576630125e98b5b0269 | [] | no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74,724 | hpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef __OPENCV_ML_HPP__
#define __OPENCV_ML_HPP__
// disable deprecation warning which appears in VisualStudio 8.0
#if _MSC_VER >= 1400
#pragma warning( disable : 4996 )
#endif
#ifndef SKIP_INCLUDES
#include "opencv2/core/core.hpp"
#include <limits.h>
#if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
#include <windows.h>
#endif
#else // SKIP_INCLUDES
#if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
#define CV_CDECL __cdecl
#define CV_STDCALL __stdcall
#else
#define CV_CDECL
#define CV_STDCALL
#endif
#ifndef CV_EXTERN_C
#ifdef __cplusplus
#define CV_EXTERN_C extern "C"
#define CV_DEFAULT(val) = val
#else
#define CV_EXTERN_C
#define CV_DEFAULT(val)
#endif
#endif
#ifndef CV_EXTERN_C_FUNCPTR
#ifdef __cplusplus
#define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; }
#else
#define CV_EXTERN_C_FUNCPTR(x) typedef x
#endif
#endif
#ifndef CV_INLINE
#if defined __cplusplus
#define CV_INLINE inline
#elif (defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __GNUC__
#define CV_INLINE __inline
#else
#define CV_INLINE static
#endif
#endif /* CV_INLINE */
#if (defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && defined CVAPI_EXPORTS
#define CV_EXPORTS __declspec(dllexport)
#else
#define CV_EXPORTS
#endif
#ifndef CVAPI
#define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL
#endif
#endif // SKIP_INCLUDES
#ifdef __cplusplus
// Apple defines a check() macro somewhere in the debug headers
// that interferes with a method definiton in this header
#undef check
/****************************************************************************************\
* Main struct definitions *
\****************************************************************************************/
/* log(2*PI) */
#define CV_LOG2PI (1.8378770664093454835606594728112)
/* columns of <trainData> matrix are training samples */
#define CV_COL_SAMPLE 0
/* rows of <trainData> matrix are training samples */
#define CV_ROW_SAMPLE 1
#define CV_IS_ROW_SAMPLE(flags) ((flags) & CV_ROW_SAMPLE)
struct CvVectors
{
int type;
int dims, count;
CvVectors* next;
union
{
uchar** ptr;
float** fl;
double** db;
} data;
};
#if 0
/* A structure, representing the lattice range of statmodel parameters.
It is used for optimizing statmodel parameters by cross-validation method.
The lattice is logarithmic, so <step> must be greater then 1. */
typedef struct CvParamLattice
{
double min_val;
double max_val;
double step;
}
CvParamLattice;
CV_INLINE CvParamLattice cvParamLattice( double min_val, double max_val,
double log_step )
{
CvParamLattice pl;
pl.min_val = MIN( min_val, max_val );
pl.max_val = MAX( min_val, max_val );
pl.step = MAX( log_step, 1. );
return pl;
}
CV_INLINE CvParamLattice cvDefaultParamLattice( void )
{
CvParamLattice pl = {0,0,0};
return pl;
}
#endif
/* Variable type */
#define CV_VAR_NUMERICAL 0
#define CV_VAR_ORDERED 0
#define CV_VAR_CATEGORICAL 1
#define CV_TYPE_NAME_ML_SVM "opencv-ml-svm"
#define CV_TYPE_NAME_ML_KNN "opencv-ml-knn"
#define CV_TYPE_NAME_ML_NBAYES "opencv-ml-bayesian"
#define CV_TYPE_NAME_ML_EM "opencv-ml-em"
#define CV_TYPE_NAME_ML_BOOSTING "opencv-ml-boost-tree"
#define CV_TYPE_NAME_ML_TREE "opencv-ml-tree"
#define CV_TYPE_NAME_ML_ANN_MLP "opencv-ml-ann-mlp"
#define CV_TYPE_NAME_ML_CNN "opencv-ml-cnn"
#define CV_TYPE_NAME_ML_RTREES "opencv-ml-random-trees"
#define CV_TRAIN_ERROR 0
#define CV_TEST_ERROR 1
class CV_EXPORTS CvStatModel
{
public:
CvStatModel();
virtual ~CvStatModel();
virtual void clear();
virtual void save( const char* filename, const char* name=0 ) const;
virtual void load( const char* filename, const char* name=0 );
virtual void write( CvFileStorage* storage, const char* name ) const;
virtual void read( CvFileStorage* storage, CvFileNode* node );
protected:
const char* default_model_name;
};
/****************************************************************************************\
* Normal Bayes Classifier *
\****************************************************************************************/
/* The structure, representing the grid range of statmodel parameters.
It is used for optimizing statmodel accuracy by varying model parameters,
the accuracy estimate being computed by cross-validation.
The grid is logarithmic, so <step> must be greater then 1. */
class CvMLData;
struct CV_EXPORTS CvParamGrid
{
// SVM params type
enum { SVM_C=0, SVM_GAMMA=1, SVM_P=2, SVM_NU=3, SVM_COEF=4, SVM_DEGREE=5 };
CvParamGrid()
{
min_val = max_val = step = 0;
}
CvParamGrid( double _min_val, double _max_val, double log_step )
{
min_val = _min_val;
max_val = _max_val;
step = log_step;
}
//CvParamGrid( int param_id );
bool check() const;
double min_val;
double max_val;
double step;
};
class CV_EXPORTS CvNormalBayesClassifier : public CvStatModel
{
public:
CvNormalBayesClassifier();
virtual ~CvNormalBayesClassifier();
CvNormalBayesClassifier( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _var_idx=0, const CvMat* _sample_idx=0 );
virtual bool train( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _var_idx = 0, const CvMat* _sample_idx=0, bool update=false );
virtual float predict( const CvMat* _samples, CvMat* results=0 ) const;
virtual void clear();
#ifndef SWIG
CvNormalBayesClassifier( const cv::Mat& _train_data, const cv::Mat& _responses,
const cv::Mat& _var_idx=cv::Mat(), const cv::Mat& _sample_idx=cv::Mat() );
virtual bool train( const cv::Mat& _train_data, const cv::Mat& _responses,
const cv::Mat& _var_idx = cv::Mat(), const cv::Mat& _sample_idx=cv::Mat(),
bool update=false );
virtual float predict( const cv::Mat& _samples, cv::Mat* results=0 ) const;
#endif
virtual void write( CvFileStorage* storage, const char* name ) const;
virtual void read( CvFileStorage* storage, CvFileNode* node );
protected:
int var_count, var_all;
CvMat* var_idx;
CvMat* cls_labels;
CvMat** count;
CvMat** sum;
CvMat** productsum;
CvMat** avg;
CvMat** inv_eigen_values;
CvMat** cov_rotate_mats;
CvMat* c;
};
/****************************************************************************************\
* K-Nearest Neighbour Classifier *
\****************************************************************************************/
// k Nearest Neighbors
class CV_EXPORTS CvKNearest : public CvStatModel
{
public:
CvKNearest();
virtual ~CvKNearest();
CvKNearest( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _sample_idx=0, bool _is_regression=false, int max_k=32 );
virtual bool train( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _sample_idx=0, bool is_regression=false,
int _max_k=32, bool _update_base=false );
virtual float find_nearest( const CvMat* _samples, int k, CvMat* results=0,
const float** neighbors=0, CvMat* neighbor_responses=0, CvMat* dist=0 ) const;
#ifndef SWIG
CvKNearest( const cv::Mat& _train_data, const cv::Mat& _responses,
const cv::Mat& _sample_idx=cv::Mat(), bool _is_regression=false, int max_k=32 );
virtual bool train( const cv::Mat& _train_data, const cv::Mat& _responses,
const cv::Mat& _sample_idx=cv::Mat(), bool is_regression=false,
int _max_k=32, bool _update_base=false );
virtual float find_nearest( const cv::Mat& _samples, int k, cv::Mat* results=0,
const float** neighbors=0,
cv::Mat* neighbor_responses=0,
cv::Mat* dist=0 ) const;
#endif
virtual void clear();
int get_max_k() const;
int get_var_count() const;
int get_sample_count() const;
bool is_regression() const;
protected:
virtual float write_results( int k, int k1, int start, int end,
const float* neighbor_responses, const float* dist, CvMat* _results,
CvMat* _neighbor_responses, CvMat* _dist, Cv32suf* sort_buf ) const;
virtual void find_neighbors_direct( const CvMat* _samples, int k, int start, int end,
float* neighbor_responses, const float** neighbors, float* dist ) const;
int max_k, var_count;
int total;
bool regression;
CvVectors* samples;
};
/****************************************************************************************\
* Support Vector Machines *
\****************************************************************************************/
// SVM training parameters
struct CV_EXPORTS CvSVMParams
{
CvSVMParams();
CvSVMParams( int _svm_type, int _kernel_type,
double _degree, double _gamma, double _coef0,
double Cvalue, double _nu, double _p,
CvMat* _class_weights, CvTermCriteria _term_crit );
int svm_type;
int kernel_type;
double degree; // for poly
double gamma; // for poly/rbf/sigmoid
double coef0; // for poly/sigmoid
double C; // for CV_SVM_C_SVC, CV_SVM_EPS_SVR and CV_SVM_NU_SVR
double nu; // for CV_SVM_NU_SVC, CV_SVM_ONE_CLASS, and CV_SVM_NU_SVR
double p; // for CV_SVM_EPS_SVR
CvMat* class_weights; // for CV_SVM_C_SVC
CvTermCriteria term_crit; // termination criteria
};
struct CV_EXPORTS CvSVMKernel
{
typedef void (CvSVMKernel::*Calc)( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
CvSVMKernel();
CvSVMKernel( const CvSVMParams* _params, Calc _calc_func );
virtual bool create( const CvSVMParams* _params, Calc _calc_func );
virtual ~CvSVMKernel();
virtual void clear();
virtual void calc( int vcount, int n, const float** vecs, const float* another, float* results );
const CvSVMParams* params;
Calc calc_func;
virtual void calc_non_rbf_base( int vec_count, int vec_size, const float** vecs,
const float* another, float* results,
double alpha, double beta );
virtual void calc_linear( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
virtual void calc_rbf( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
virtual void calc_poly( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
virtual void calc_sigmoid( int vec_count, int vec_size, const float** vecs,
const float* another, float* results );
};
struct CvSVMKernelRow
{
CvSVMKernelRow* prev;
CvSVMKernelRow* next;
float* data;
};
struct CvSVMSolutionInfo
{
double obj;
double rho;
double upper_bound_p;
double upper_bound_n;
double r; // for Solver_NU
};
class CV_EXPORTS CvSVMSolver
{
public:
typedef bool (CvSVMSolver::*SelectWorkingSet)( int& i, int& j );
typedef float* (CvSVMSolver::*GetRow)( int i, float* row, float* dst, bool existed );
typedef void (CvSVMSolver::*CalcRho)( double& rho, double& r );
CvSVMSolver();
CvSVMSolver( int count, int var_count, const float** samples, schar* y,
int alpha_count, double* alpha, double Cp, double Cn,
CvMemStorage* storage, CvSVMKernel* kernel, GetRow get_row,
SelectWorkingSet select_working_set, CalcRho calc_rho );
virtual bool create( int count, int var_count, const float** samples, schar* y,
int alpha_count, double* alpha, double Cp, double Cn,
CvMemStorage* storage, CvSVMKernel* kernel, GetRow get_row,
SelectWorkingSet select_working_set, CalcRho calc_rho );
virtual ~CvSVMSolver();
virtual void clear();
virtual bool solve_generic( CvSVMSolutionInfo& si );
virtual bool solve_c_svc( int count, int var_count, const float** samples, schar* y,
double Cp, double Cn, CvMemStorage* storage,
CvSVMKernel* kernel, double* alpha, CvSVMSolutionInfo& si );
virtual bool solve_nu_svc( int count, int var_count, const float** samples, schar* y,
CvMemStorage* storage, CvSVMKernel* kernel,
double* alpha, CvSVMSolutionInfo& si );
virtual bool solve_one_class( int count, int var_count, const float** samples,
CvMemStorage* storage, CvSVMKernel* kernel,
double* alpha, CvSVMSolutionInfo& si );
virtual bool solve_eps_svr( int count, int var_count, const float** samples, const float* y,
CvMemStorage* storage, CvSVMKernel* kernel,
double* alpha, CvSVMSolutionInfo& si );
virtual bool solve_nu_svr( int count, int var_count, const float** samples, const float* y,
CvMemStorage* storage, CvSVMKernel* kernel,
double* alpha, CvSVMSolutionInfo& si );
virtual float* get_row_base( int i, bool* _existed );
virtual float* get_row( int i, float* dst );
int sample_count;
int var_count;
int cache_size;
int cache_line_size;
const float** samples;
const CvSVMParams* params;
CvMemStorage* storage;
CvSVMKernelRow lru_list;
CvSVMKernelRow* rows;
int alpha_count;
double* G;
double* alpha;
// -1 - lower bound, 0 - free, 1 - upper bound
schar* alpha_status;
schar* y;
double* b;
float* buf[2];
double eps;
int max_iter;
double C[2]; // C[0] == Cn, C[1] == Cp
CvSVMKernel* kernel;
SelectWorkingSet select_working_set_func;
CalcRho calc_rho_func;
GetRow get_row_func;
virtual bool select_working_set( int& i, int& j );
virtual bool select_working_set_nu_svm( int& i, int& j );
virtual void calc_rho( double& rho, double& r );
virtual void calc_rho_nu_svm( double& rho, double& r );
virtual float* get_row_svc( int i, float* row, float* dst, bool existed );
virtual float* get_row_one_class( int i, float* row, float* dst, bool existed );
virtual float* get_row_svr( int i, float* row, float* dst, bool existed );
};
struct CvSVMDecisionFunc
{
double rho;
int sv_count;
double* alpha;
int* sv_index;
};
// SVM model
class CV_EXPORTS CvSVM : public CvStatModel
{
public:
// SVM type
enum { C_SVC=100, NU_SVC=101, ONE_CLASS=102, EPS_SVR=103, NU_SVR=104 };
// SVM kernel type
enum { LINEAR=0, POLY=1, RBF=2, SIGMOID=3 };
// SVM params type
enum { C=0, GAMMA=1, P=2, NU=3, COEF=4, DEGREE=5 };
CvSVM();
virtual ~CvSVM();
CvSVM( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _var_idx=0, const CvMat* _sample_idx=0,
CvSVMParams _params=CvSVMParams() );
virtual bool train( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _var_idx=0, const CvMat* _sample_idx=0,
CvSVMParams _params=CvSVMParams() );
virtual bool train_auto( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _var_idx, const CvMat* _sample_idx, CvSVMParams _params,
int k_fold = 10,
CvParamGrid C_grid = get_default_grid(CvSVM::C),
CvParamGrid gamma_grid = get_default_grid(CvSVM::GAMMA),
CvParamGrid p_grid = get_default_grid(CvSVM::P),
CvParamGrid nu_grid = get_default_grid(CvSVM::NU),
CvParamGrid coef_grid = get_default_grid(CvSVM::COEF),
CvParamGrid degree_grid = get_default_grid(CvSVM::DEGREE) );
virtual float predict( const CvMat* _sample, bool returnDFVal=false ) const;
#ifndef SWIG
CvSVM( const cv::Mat& _train_data, const cv::Mat& _responses,
const cv::Mat& _var_idx=cv::Mat(), const cv::Mat& _sample_idx=cv::Mat(),
CvSVMParams _params=CvSVMParams() );
virtual bool train( const cv::Mat& _train_data, const cv::Mat& _responses,
const cv::Mat& _var_idx=cv::Mat(), const cv::Mat& _sample_idx=cv::Mat(),
CvSVMParams _params=CvSVMParams() );
virtual bool train_auto( const cv::Mat& _train_data, const cv::Mat& _responses,
const cv::Mat& _var_idx, const cv::Mat& _sample_idx, CvSVMParams _params,
int k_fold = 10,
CvParamGrid C_grid = get_default_grid(CvSVM::C),
CvParamGrid gamma_grid = get_default_grid(CvSVM::GAMMA),
CvParamGrid p_grid = get_default_grid(CvSVM::P),
CvParamGrid nu_grid = get_default_grid(CvSVM::NU),
CvParamGrid coef_grid = get_default_grid(CvSVM::COEF),
CvParamGrid degree_grid = get_default_grid(CvSVM::DEGREE) );
virtual float predict( const cv::Mat& _sample, bool returnDFVal=false ) const;
#endif
virtual int get_support_vector_count() const;
virtual const float* get_support_vector(int i) const;
virtual CvSVMParams get_params() const { return params; };
virtual void clear();
static CvParamGrid get_default_grid( int param_id );
virtual void write( CvFileStorage* storage, const char* name ) const;
virtual void read( CvFileStorage* storage, CvFileNode* node );
int get_var_count() const { return var_idx ? var_idx->cols : var_all; }
protected:
virtual bool set_params( const CvSVMParams& _params );
virtual bool train1( int sample_count, int var_count, const float** samples,
const void* _responses, double Cp, double Cn,
CvMemStorage* _storage, double* alpha, double& rho );
virtual bool do_train( int svm_type, int sample_count, int var_count, const float** samples,
const CvMat* _responses, CvMemStorage* _storage, double* alpha );
virtual void create_kernel();
virtual void create_solver();
virtual float predict( const float* row_sample, int row_len, bool returnDFVal=false ) const;
virtual void write_params( CvFileStorage* fs ) const;
virtual void read_params( CvFileStorage* fs, CvFileNode* node );
CvSVMParams params;
CvMat* class_labels;
int var_all;
float** sv;
int sv_total;
CvMat* var_idx;
CvMat* class_weights;
CvSVMDecisionFunc* decision_func;
CvMemStorage* storage;
CvSVMSolver* solver;
CvSVMKernel* kernel;
};
/****************************************************************************************\
* Expectation - Maximization *
\****************************************************************************************/
struct CV_EXPORTS CvEMParams
{
CvEMParams() : nclusters(10), cov_mat_type(1/*CvEM::COV_MAT_DIAGONAL*/),
start_step(0/*CvEM::START_AUTO_STEP*/), probs(0), weights(0), means(0), covs(0)
{
term_crit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, FLT_EPSILON );
}
CvEMParams( int _nclusters, int _cov_mat_type=1/*CvEM::COV_MAT_DIAGONAL*/,
int _start_step=0/*CvEM::START_AUTO_STEP*/,
CvTermCriteria _term_crit=cvTermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, FLT_EPSILON),
const CvMat* _probs=0, const CvMat* _weights=0, const CvMat* _means=0, const CvMat** _covs=0 ) :
nclusters(_nclusters), cov_mat_type(_cov_mat_type), start_step(_start_step),
probs(_probs), weights(_weights), means(_means), covs(_covs), term_crit(_term_crit)
{}
int nclusters;
int cov_mat_type;
int start_step;
const CvMat* probs;
const CvMat* weights;
const CvMat* means;
const CvMat** covs;
CvTermCriteria term_crit;
};
class CV_EXPORTS CvEM : public CvStatModel
{
public:
// Type of covariation matrices
enum { COV_MAT_SPHERICAL=0, COV_MAT_DIAGONAL=1, COV_MAT_GENERIC=2 };
// The initial step
enum { START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0 };
CvEM();
CvEM( const CvMat* samples, const CvMat* sample_idx=0,
CvEMParams params=CvEMParams(), CvMat* labels=0 );
//CvEM (CvEMParams params, CvMat * means, CvMat ** covs, CvMat * weights, CvMat * probs, CvMat * log_weight_div_det, CvMat * inv_eigen_values, CvMat** cov_rotate_mats);
virtual ~CvEM();
virtual bool train( const CvMat* samples, const CvMat* sample_idx=0,
CvEMParams params=CvEMParams(), CvMat* labels=0 );
virtual float predict( const CvMat* sample, CvMat* probs ) const;
#ifndef SWIG
CvEM( const cv::Mat& samples, const cv::Mat& sample_idx=cv::Mat(),
CvEMParams params=CvEMParams(), cv::Mat* labels=0 );
virtual bool train( const cv::Mat& samples, const cv::Mat& sample_idx=cv::Mat(),
CvEMParams params=CvEMParams(), cv::Mat* labels=0 );
virtual float predict( const cv::Mat& sample, cv::Mat* probs ) const;
#endif
virtual void clear();
int get_nclusters() const;
const CvMat* get_means() const;
const CvMat** get_covs() const;
const CvMat* get_weights() const;
const CvMat* get_probs() const;
inline double get_log_likelihood () const { return log_likelihood; };
// inline const CvMat * get_log_weight_div_det () const { return log_weight_div_det; };
// inline const CvMat * get_inv_eigen_values () const { return inv_eigen_values; };
// inline const CvMat ** get_cov_rotate_mats () const { return cov_rotate_mats; };
protected:
virtual void set_params( const CvEMParams& params,
const CvVectors& train_data );
virtual void init_em( const CvVectors& train_data );
virtual double run_em( const CvVectors& train_data );
virtual void init_auto( const CvVectors& samples );
virtual void kmeans( const CvVectors& train_data, int nclusters,
CvMat* labels, CvTermCriteria criteria,
const CvMat* means );
CvEMParams params;
double log_likelihood;
CvMat* means;
CvMat** covs;
CvMat* weights;
CvMat* probs;
CvMat* log_weight_div_det;
CvMat* inv_eigen_values;
CvMat** cov_rotate_mats;
};
/****************************************************************************************\
* Decision Tree *
\****************************************************************************************/\
struct CvPair16u32s
{
unsigned short* u;
int* i;
};
#define CV_DTREE_CAT_DIR(idx,subset) \
(2*((subset[(idx)>>5]&(1 << ((idx) & 31)))==0)-1)
struct CvDTreeSplit
{
int var_idx;
int condensed_idx;
int inversed;
float quality;
CvDTreeSplit* next;
union
{
int subset[2];
struct
{
float c;
int split_point;
}
ord;
};
};
struct CvDTreeNode
{
int class_idx;
int Tn;
double value;
CvDTreeNode* parent;
CvDTreeNode* left;
CvDTreeNode* right;
CvDTreeSplit* split;
int sample_count;
int depth;
int* num_valid;
int offset;
int buf_idx;
double maxlr;
// global pruning data
int complexity;
double alpha;
double node_risk, tree_risk, tree_error;
// cross-validation pruning data
int* cv_Tn;
double* cv_node_risk;
double* cv_node_error;
int get_num_valid(int vi) { return num_valid ? num_valid[vi] : sample_count; }
void set_num_valid(int vi, int n) { if( num_valid ) num_valid[vi] = n; }
};
struct CV_EXPORTS CvDTreeParams
{
int max_categories;
int max_depth;
int min_sample_count;
int cv_folds;
bool use_surrogates;
bool use_1se_rule;
bool truncate_pruned_tree;
float regression_accuracy;
const float* priors;
CvDTreeParams() : max_categories(10), max_depth(INT_MAX), min_sample_count(10),
cv_folds(10), use_surrogates(true), use_1se_rule(true),
truncate_pruned_tree(true), regression_accuracy(0.01f), priors(0)
{}
CvDTreeParams( int _max_depth, int _min_sample_count,
float _regression_accuracy, bool _use_surrogates,
int _max_categories, int _cv_folds,
bool _use_1se_rule, bool _truncate_pruned_tree,
const float* _priors ) :
max_categories(_max_categories), max_depth(_max_depth),
min_sample_count(_min_sample_count), cv_folds (_cv_folds),
use_surrogates(_use_surrogates), use_1se_rule(_use_1se_rule),
truncate_pruned_tree(_truncate_pruned_tree),
regression_accuracy(_regression_accuracy),
priors(_priors)
{}
};
struct CV_EXPORTS CvDTreeTrainData
{
CvDTreeTrainData();
CvDTreeTrainData( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
const CvDTreeParams& _params=CvDTreeParams(),
bool _shared=false, bool _add_labels=false );
virtual ~CvDTreeTrainData();
virtual void set_data( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
const CvDTreeParams& _params=CvDTreeParams(),
bool _shared=false, bool _add_labels=false,
bool _update_data=false );
virtual void do_responses_copy();
virtual void get_vectors( const CvMat* _subsample_idx,
float* values, uchar* missing, float* responses, bool get_class_idx=false );
virtual CvDTreeNode* subsample_data( const CvMat* _subsample_idx );
virtual void write_params( CvFileStorage* fs ) const;
virtual void read_params( CvFileStorage* fs, CvFileNode* node );
// release all the data
virtual void clear();
int get_num_classes() const;
int get_var_type(int vi) const;
int get_work_var_count() const {return work_var_count;}
virtual const float* get_ord_responses( CvDTreeNode* n, float* values_buf, int* sample_indices_buf );
virtual const int* get_class_labels( CvDTreeNode* n, int* labels_buf );
virtual const int* get_cv_labels( CvDTreeNode* n, int* labels_buf );
virtual const int* get_sample_indices( CvDTreeNode* n, int* indices_buf );
virtual const int* get_cat_var_data( CvDTreeNode* n, int vi, int* cat_values_buf );
virtual void get_ord_var_data( CvDTreeNode* n, int vi, float* ord_values_buf, int* sorted_indices_buf,
const float** ord_values, const int** sorted_indices, int* sample_indices_buf );
virtual int get_child_buf_idx( CvDTreeNode* n );
////////////////////////////////////
virtual bool set_params( const CvDTreeParams& params );
virtual CvDTreeNode* new_node( CvDTreeNode* parent, int count,
int storage_idx, int offset );
virtual CvDTreeSplit* new_split_ord( int vi, float cmp_val,
int split_point, int inversed, float quality );
virtual CvDTreeSplit* new_split_cat( int vi, float quality );
virtual void free_node_data( CvDTreeNode* node );
virtual void free_train_data();
virtual void free_node( CvDTreeNode* node );
int sample_count, var_all, var_count, max_c_count;
int ord_var_count, cat_var_count, work_var_count;
bool have_labels, have_priors;
bool is_classifier;
int tflag;
const CvMat* train_data;
const CvMat* responses;
CvMat* responses_copy; // used in Boosting
int buf_count, buf_size;
bool shared;
int is_buf_16u;
CvMat* cat_count;
CvMat* cat_ofs;
CvMat* cat_map;
CvMat* counts;
CvMat* buf;
CvMat* direction;
CvMat* split_buf;
CvMat* var_idx;
CvMat* var_type; // i-th element =
// k<0 - ordered
// k>=0 - categorical, see k-th element of cat_* arrays
CvMat* priors;
CvMat* priors_mult;
CvDTreeParams params;
CvMemStorage* tree_storage;
CvMemStorage* temp_storage;
CvDTreeNode* data_root;
CvSet* node_heap;
CvSet* split_heap;
CvSet* cv_heap;
CvSet* nv_heap;
CvRNG rng;
};
class CvDTree;
class CvForestTree;
namespace cv
{
struct DTreeBestSplitFinder;
struct ForestTreeBestSplitFinder;
}
class CV_EXPORTS CvDTree : public CvStatModel
{
public:
CvDTree();
virtual ~CvDTree();
virtual bool train( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
CvDTreeParams params=CvDTreeParams() );
virtual bool train( CvMLData* _data, CvDTreeParams _params=CvDTreeParams() );
virtual float calc_error( CvMLData* _data, int type , std::vector<float> *resp = 0 ); // type in {CV_TRAIN_ERROR, CV_TEST_ERROR}
virtual bool train( CvDTreeTrainData* _train_data, const CvMat* _subsample_idx );
virtual CvDTreeNode* predict( const CvMat* _sample, const CvMat* _missing_data_mask=0,
bool preprocessed_input=false ) const;
#ifndef SWIG
virtual bool train( const cv::Mat& _train_data, int _tflag,
const cv::Mat& _responses, const cv::Mat& _var_idx=cv::Mat(),
const cv::Mat& _sample_idx=cv::Mat(), const cv::Mat& _var_type=cv::Mat(),
const cv::Mat& _missing_mask=cv::Mat(),
CvDTreeParams params=CvDTreeParams() );
virtual CvDTreeNode* predict( const cv::Mat& _sample, const cv::Mat& _missing_data_mask=cv::Mat(),
bool preprocessed_input=false ) const;
#endif
virtual const CvMat* get_var_importance();
virtual void clear();
virtual void read( CvFileStorage* fs, CvFileNode* node );
virtual void write( CvFileStorage* fs, const char* name ) const;
// special read & write methods for trees in the tree ensembles
virtual void read( CvFileStorage* fs, CvFileNode* node,
CvDTreeTrainData* data );
virtual void write( CvFileStorage* fs ) const;
const CvDTreeNode* get_root() const;
int get_pruned_tree_idx() const;
CvDTreeTrainData* get_data();
protected:
friend struct cv::DTreeBestSplitFinder;
virtual bool do_train( const CvMat* _subsample_idx );
virtual void try_split_node( CvDTreeNode* n );
virtual void split_node_data( CvDTreeNode* n );
virtual CvDTreeSplit* find_best_split( CvDTreeNode* n );
virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_cat_class( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_surrogate_split_ord( CvDTreeNode* n, int vi, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_surrogate_split_cat( CvDTreeNode* n, int vi, uchar* ext_buf = 0 );
virtual double calc_node_dir( CvDTreeNode* node );
virtual void complete_node_dir( CvDTreeNode* node );
virtual void cluster_categories( const int* vectors, int vector_count,
int var_count, int* sums, int k, int* cluster_labels );
virtual void calc_node_value( CvDTreeNode* node );
virtual void prune_cv();
virtual double update_tree_rnc( int T, int fold );
virtual int cut_tree( int T, int fold, double min_alpha );
virtual void free_prune_data(bool cut_tree);
virtual void free_tree();
virtual void write_node( CvFileStorage* fs, CvDTreeNode* node ) const;
virtual void write_split( CvFileStorage* fs, CvDTreeSplit* split ) const;
virtual CvDTreeNode* read_node( CvFileStorage* fs, CvFileNode* node, CvDTreeNode* parent );
virtual CvDTreeSplit* read_split( CvFileStorage* fs, CvFileNode* node );
virtual void write_tree_nodes( CvFileStorage* fs ) const;
virtual void read_tree_nodes( CvFileStorage* fs, CvFileNode* node );
CvDTreeNode* root;
CvMat* var_importance;
CvDTreeTrainData* data;
public:
int pruned_tree_idx;
};
/****************************************************************************************\
* Random Trees Classifier *
\****************************************************************************************/
class CvRTrees;
class CV_EXPORTS CvForestTree: public CvDTree
{
public:
CvForestTree();
virtual ~CvForestTree();
virtual bool train( CvDTreeTrainData* _train_data, const CvMat* _subsample_idx, CvRTrees* forest );
virtual int get_var_count() const {return data ? data->var_count : 0;}
virtual void read( CvFileStorage* fs, CvFileNode* node, CvRTrees* forest, CvDTreeTrainData* _data );
/* dummy methods to avoid warnings: BEGIN */
virtual bool train( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
CvDTreeParams params=CvDTreeParams() );
virtual bool train( CvDTreeTrainData* _train_data, const CvMat* _subsample_idx );
virtual void read( CvFileStorage* fs, CvFileNode* node );
virtual void read( CvFileStorage* fs, CvFileNode* node,
CvDTreeTrainData* data );
/* dummy methods to avoid warnings: END */
protected:
friend struct cv::ForestTreeBestSplitFinder;
virtual CvDTreeSplit* find_best_split( CvDTreeNode* n );
CvRTrees* forest;
};
struct CV_EXPORTS CvRTParams : public CvDTreeParams
{
//Parameters for the forest
bool calc_var_importance; // true <=> RF processes variable importance
int nactive_vars;
CvTermCriteria term_crit;
CvRTParams() : CvDTreeParams( 5, 10, 0, false, 10, 0, false, false, 0 ),
calc_var_importance(false), nactive_vars(0)
{
term_crit = cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 50, 0.1 );
}
CvRTParams( int _max_depth, int _min_sample_count,
float _regression_accuracy, bool _use_surrogates,
int _max_categories, const float* _priors, bool _calc_var_importance,
int _nactive_vars, int max_num_of_trees_in_the_forest,
float forest_accuracy, int termcrit_type ) :
CvDTreeParams( _max_depth, _min_sample_count, _regression_accuracy,
_use_surrogates, _max_categories, 0,
false, false, _priors ),
calc_var_importance(_calc_var_importance),
nactive_vars(_nactive_vars)
{
term_crit = cvTermCriteria(termcrit_type,
max_num_of_trees_in_the_forest, forest_accuracy);
}
};
class CV_EXPORTS CvRTrees : public CvStatModel
{
public:
CvRTrees();
virtual ~CvRTrees();
virtual bool train( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
CvRTParams params=CvRTParams() );
virtual bool train( CvMLData* data, CvRTParams params=CvRTParams() );
virtual float predict( const CvMat* sample, const CvMat* missing = 0 ) const;
virtual float predict_prob( const CvMat* sample, const CvMat* missing = 0 ) const;
#ifndef SWIG
virtual bool train( const cv::Mat& _train_data, int _tflag,
const cv::Mat& _responses, const cv::Mat& _var_idx=cv::Mat(),
const cv::Mat& _sample_idx=cv::Mat(), const cv::Mat& _var_type=cv::Mat(),
const cv::Mat& _missing_mask=cv::Mat(),
CvRTParams params=CvRTParams() );
virtual float predict( const cv::Mat& sample, const cv::Mat& missing = cv::Mat() ) const;
virtual float predict_prob( const cv::Mat& sample, const cv::Mat& missing = cv::Mat() ) const;
#endif
virtual void clear();
virtual const CvMat* get_var_importance();
virtual float get_proximity( const CvMat* sample1, const CvMat* sample2,
const CvMat* missing1 = 0, const CvMat* missing2 = 0 ) const;
virtual float calc_error( CvMLData* _data, int type , std::vector<float> *resp = 0 ); // type in {CV_TRAIN_ERROR, CV_TEST_ERROR}
virtual float get_train_error();
virtual void read( CvFileStorage* fs, CvFileNode* node );
virtual void write( CvFileStorage* fs, const char* name ) const;
CvMat* get_active_var_mask();
CvRNG* get_rng();
int get_tree_count() const;
CvForestTree* get_tree(int i) const;
protected:
virtual bool grow_forest( const CvTermCriteria term_crit );
// array of the trees of the forest
CvForestTree** trees;
CvDTreeTrainData* data;
int ntrees;
int nclasses;
double oob_error;
CvMat* var_importance;
int nsamples;
CvRNG rng;
CvMat* active_var_mask;
};
/****************************************************************************************\
* Extremely randomized trees Classifier *
\****************************************************************************************/
struct CV_EXPORTS CvERTreeTrainData : public CvDTreeTrainData
{
virtual void set_data( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
const CvDTreeParams& _params=CvDTreeParams(),
bool _shared=false, bool _add_labels=false,
bool _update_data=false );
virtual void get_ord_var_data( CvDTreeNode* n, int vi, float* ord_values_buf, int* missing_buf,
const float** ord_values, const int** missing, int* sample_buf = 0 );
virtual const int* get_sample_indices( CvDTreeNode* n, int* indices_buf );
virtual const int* get_cv_labels( CvDTreeNode* n, int* labels_buf );
virtual const int* get_cat_var_data( CvDTreeNode* n, int vi, int* cat_values_buf );
virtual void get_vectors( const CvMat* _subsample_idx, float* values, uchar* missing,
float* responses, bool get_class_idx=false );
virtual CvDTreeNode* subsample_data( const CvMat* _subsample_idx );
const CvMat* missing_mask;
};
class CV_EXPORTS CvForestERTree : public CvForestTree
{
protected:
virtual double calc_node_dir( CvDTreeNode* node );
virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_cat_class( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual void split_node_data( CvDTreeNode* n );
};
class CV_EXPORTS CvERTrees : public CvRTrees
{
public:
CvERTrees();
virtual ~CvERTrees();
virtual bool train( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
CvRTParams params=CvRTParams());
#ifndef SWIG
virtual bool train( const cv::Mat& _train_data, int _tflag,
const cv::Mat& _responses, const cv::Mat& _var_idx=cv::Mat(),
const cv::Mat& _sample_idx=cv::Mat(), const cv::Mat& _var_type=cv::Mat(),
const cv::Mat& _missing_mask=cv::Mat(),
CvRTParams params=CvRTParams());
#endif
virtual bool train( CvMLData* data, CvRTParams params=CvRTParams() );
protected:
virtual bool grow_forest( const CvTermCriteria term_crit );
};
/****************************************************************************************\
* Boosted tree classifier *
\****************************************************************************************/
struct CV_EXPORTS CvBoostParams : public CvDTreeParams
{
int boost_type;
int weak_count;
int split_criteria;
double weight_trim_rate;
CvBoostParams();
CvBoostParams( int boost_type, int weak_count, double weight_trim_rate,
int max_depth, bool use_surrogates, const float* priors );
};
class CvBoost;
class CV_EXPORTS CvBoostTree: public CvDTree
{
public:
CvBoostTree();
virtual ~CvBoostTree();
virtual bool train( CvDTreeTrainData* _train_data,
const CvMat* subsample_idx, CvBoost* ensemble );
virtual void scale( double s );
virtual void read( CvFileStorage* fs, CvFileNode* node,
CvBoost* ensemble, CvDTreeTrainData* _data );
virtual void clear();
/* dummy methods to avoid warnings: BEGIN */
virtual bool train( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
CvDTreeParams params=CvDTreeParams() );
virtual bool train( CvDTreeTrainData* _train_data, const CvMat* _subsample_idx );
virtual void read( CvFileStorage* fs, CvFileNode* node );
virtual void read( CvFileStorage* fs, CvFileNode* node,
CvDTreeTrainData* data );
/* dummy methods to avoid warnings: END */
protected:
virtual void try_split_node( CvDTreeNode* n );
virtual CvDTreeSplit* find_surrogate_split_ord( CvDTreeNode* n, int vi, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_surrogate_split_cat( CvDTreeNode* n, int vi, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_ord_class( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_cat_class( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_ord_reg( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual CvDTreeSplit* find_split_cat_reg( CvDTreeNode* n, int vi,
float init_quality = 0, CvDTreeSplit* _split = 0, uchar* ext_buf = 0 );
virtual void calc_node_value( CvDTreeNode* n );
virtual double calc_node_dir( CvDTreeNode* n );
CvBoost* ensemble;
};
class CV_EXPORTS CvBoost : public CvStatModel
{
public:
// Boosting type
enum { DISCRETE=0, REAL=1, LOGIT=2, GENTLE=3 };
// Splitting criteria
enum { DEFAULT=0, GINI=1, MISCLASS=3, SQERR=4 };
CvBoost();
virtual ~CvBoost();
CvBoost( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
CvBoostParams params=CvBoostParams() );
virtual bool train( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
CvBoostParams params=CvBoostParams(),
bool update=false );
virtual bool train( CvMLData* data,
CvBoostParams params=CvBoostParams(),
bool update=false );
virtual float predict( const CvMat* _sample, const CvMat* _missing=0,
CvMat* weak_responses=0, CvSlice slice=CV_WHOLE_SEQ,
bool raw_mode=false, bool return_sum=false ) const;
#ifndef SWIG
CvBoost( const cv::Mat& _train_data, int _tflag,
const cv::Mat& _responses, const cv::Mat& _var_idx=cv::Mat(),
const cv::Mat& _sample_idx=cv::Mat(), const cv::Mat& _var_type=cv::Mat(),
const cv::Mat& _missing_mask=cv::Mat(),
CvBoostParams params=CvBoostParams() );
virtual bool train( const cv::Mat& _train_data, int _tflag,
const cv::Mat& _responses, const cv::Mat& _var_idx=cv::Mat(),
const cv::Mat& _sample_idx=cv::Mat(), const cv::Mat& _var_type=cv::Mat(),
const cv::Mat& _missing_mask=cv::Mat(),
CvBoostParams params=CvBoostParams(),
bool update=false );
virtual float predict( const cv::Mat& _sample, const cv::Mat& _missing=cv::Mat(),
cv::Mat* weak_responses=0, CvSlice slice=CV_WHOLE_SEQ,
bool raw_mode=false, bool return_sum=false ) const;
#endif
virtual float calc_error( CvMLData* _data, int type , std::vector<float> *resp = 0 ); // type in {CV_TRAIN_ERROR, CV_TEST_ERROR}
virtual void prune( CvSlice slice );
virtual void clear();
virtual void write( CvFileStorage* storage, const char* name ) const;
virtual void read( CvFileStorage* storage, CvFileNode* node );
virtual const CvMat* get_active_vars(bool absolute_idx=true);
CvSeq* get_weak_predictors();
CvMat* get_weights();
CvMat* get_subtree_weights();
CvMat* get_weak_response();
const CvBoostParams& get_params() const;
const CvDTreeTrainData* get_data() const;
protected:
virtual bool set_params( const CvBoostParams& _params );
virtual void update_weights( CvBoostTree* tree );
virtual void trim_weights();
virtual void write_params( CvFileStorage* fs ) const;
virtual void read_params( CvFileStorage* fs, CvFileNode* node );
CvDTreeTrainData* data;
CvBoostParams params;
CvSeq* weak;
CvMat* active_vars;
CvMat* active_vars_abs;
bool have_active_cat_vars;
CvMat* orig_response;
CvMat* sum_response;
CvMat* weak_eval;
CvMat* subsample_mask;
CvMat* weights;
CvMat* subtree_weights;
bool have_subsample;
};
/****************************************************************************************\
* Artificial Neural Networks (ANN) *
\****************************************************************************************/
/////////////////////////////////// Multi-Layer Perceptrons //////////////////////////////
struct CV_EXPORTS CvANN_MLP_TrainParams
{
CvANN_MLP_TrainParams();
CvANN_MLP_TrainParams( CvTermCriteria term_crit, int train_method,
double param1, double param2=0 );
~CvANN_MLP_TrainParams();
enum { BACKPROP=0, RPROP=1 };
CvTermCriteria term_crit;
int train_method;
// backpropagation parameters
double bp_dw_scale, bp_moment_scale;
// rprop parameters
double rp_dw0, rp_dw_plus, rp_dw_minus, rp_dw_min, rp_dw_max;
};
class CV_EXPORTS CvANN_MLP : public CvStatModel
{
public:
CvANN_MLP();
CvANN_MLP( const CvMat* _layer_sizes,
int _activ_func=SIGMOID_SYM,
double _f_param1=0, double _f_param2=0 );
virtual ~CvANN_MLP();
virtual void create( const CvMat* _layer_sizes,
int _activ_func=SIGMOID_SYM,
double _f_param1=0, double _f_param2=0 );
virtual int train( const CvMat* _inputs, const CvMat* _outputs,
const CvMat* _sample_weights, const CvMat* _sample_idx=0,
CvANN_MLP_TrainParams _params = CvANN_MLP_TrainParams(),
int flags=0 );
virtual float predict( const CvMat* _inputs, CvMat* _outputs ) const;
#ifndef SWIG
CvANN_MLP( const cv::Mat& _layer_sizes,
int _activ_func=SIGMOID_SYM,
double _f_param1=0, double _f_param2=0 );
virtual void create( const cv::Mat& _layer_sizes,
int _activ_func=SIGMOID_SYM,
double _f_param1=0, double _f_param2=0 );
virtual int train( const cv::Mat& _inputs, const cv::Mat& _outputs,
const cv::Mat& _sample_weights, const cv::Mat& _sample_idx=cv::Mat(),
CvANN_MLP_TrainParams _params = CvANN_MLP_TrainParams(),
int flags=0 );
virtual float predict( const cv::Mat& _inputs, cv::Mat& _outputs ) const;
#endif
virtual void clear();
// possible activation functions
enum { IDENTITY = 0, SIGMOID_SYM = 1, GAUSSIAN = 2 };
// available training flags
enum { UPDATE_WEIGHTS = 1, NO_INPUT_SCALE = 2, NO_OUTPUT_SCALE = 4 };
virtual void read( CvFileStorage* fs, CvFileNode* node );
virtual void write( CvFileStorage* storage, const char* name ) const;
int get_layer_count() { return layer_sizes ? layer_sizes->cols : 0; }
const CvMat* get_layer_sizes() { return layer_sizes; }
double* get_weights(int layer)
{
return layer_sizes && weights &&
(unsigned)layer <= (unsigned)layer_sizes->cols ? weights[layer] : 0;
}
protected:
virtual bool prepare_to_train( const CvMat* _inputs, const CvMat* _outputs,
const CvMat* _sample_weights, const CvMat* _sample_idx,
CvVectors* _ivecs, CvVectors* _ovecs, double** _sw, int _flags );
// sequential random backpropagation
virtual int train_backprop( CvVectors _ivecs, CvVectors _ovecs, const double* _sw );
// RPROP algorithm
virtual int train_rprop( CvVectors _ivecs, CvVectors _ovecs, const double* _sw );
virtual void calc_activ_func( CvMat* xf, const double* bias ) const;
virtual void calc_activ_func_deriv( CvMat* xf, CvMat* deriv, const double* bias ) const;
virtual void set_activ_func( int _activ_func=SIGMOID_SYM,
double _f_param1=0, double _f_param2=0 );
virtual void init_weights();
virtual void scale_input( const CvMat* _src, CvMat* _dst ) const;
virtual void scale_output( const CvMat* _src, CvMat* _dst ) const;
virtual void calc_input_scale( const CvVectors* vecs, int flags );
virtual void calc_output_scale( const CvVectors* vecs, int flags );
virtual void write_params( CvFileStorage* fs ) const;
virtual void read_params( CvFileStorage* fs, CvFileNode* node );
CvMat* layer_sizes;
CvMat* wbuf;
CvMat* sample_weights;
double** weights;
double f_param1, f_param2;
double min_val, max_val, min_val1, max_val1;
int activ_func;
int max_count, max_buf_sz;
CvANN_MLP_TrainParams params;
CvRNG rng;
};
#if 0
/****************************************************************************************\
* Convolutional Neural Network *
\****************************************************************************************/
typedef struct CvCNNLayer CvCNNLayer;
typedef struct CvCNNetwork CvCNNetwork;
#define CV_CNN_LEARN_RATE_DECREASE_HYPERBOLICALLY 1
#define CV_CNN_LEARN_RATE_DECREASE_SQRT_INV 2
#define CV_CNN_LEARN_RATE_DECREASE_LOG_INV 3
#define CV_CNN_GRAD_ESTIM_RANDOM 0
#define CV_CNN_GRAD_ESTIM_BY_WORST_IMG 1
#define ICV_CNN_LAYER 0x55550000
#define ICV_CNN_CONVOLUTION_LAYER 0x00001111
#define ICV_CNN_SUBSAMPLING_LAYER 0x00002222
#define ICV_CNN_FULLCONNECT_LAYER 0x00003333
#define ICV_IS_CNN_LAYER( layer ) \
( ((layer) != NULL) && ((((CvCNNLayer*)(layer))->flags & CV_MAGIC_MASK)\
== ICV_CNN_LAYER ))
#define ICV_IS_CNN_CONVOLUTION_LAYER( layer ) \
( (ICV_IS_CNN_LAYER( layer )) && (((CvCNNLayer*) (layer))->flags \
& ~CV_MAGIC_MASK) == ICV_CNN_CONVOLUTION_LAYER )
#define ICV_IS_CNN_SUBSAMPLING_LAYER( layer ) \
( (ICV_IS_CNN_LAYER( layer )) && (((CvCNNLayer*) (layer))->flags \
& ~CV_MAGIC_MASK) == ICV_CNN_SUBSAMPLING_LAYER )
#define ICV_IS_CNN_FULLCONNECT_LAYER( layer ) \
( (ICV_IS_CNN_LAYER( layer )) && (((CvCNNLayer*) (layer))->flags \
& ~CV_MAGIC_MASK) == ICV_CNN_FULLCONNECT_LAYER )
typedef void (CV_CDECL *CvCNNLayerForward)
( CvCNNLayer* layer, const CvMat* input, CvMat* output );
typedef void (CV_CDECL *CvCNNLayerBackward)
( CvCNNLayer* layer, int t, const CvMat* X, const CvMat* dE_dY, CvMat* dE_dX );
typedef void (CV_CDECL *CvCNNLayerRelease)
(CvCNNLayer** layer);
typedef void (CV_CDECL *CvCNNetworkAddLayer)
(CvCNNetwork* network, CvCNNLayer* layer);
typedef void (CV_CDECL *CvCNNetworkRelease)
(CvCNNetwork** network);
#define CV_CNN_LAYER_FIELDS() \
/* Indicator of the layer's type */ \
int flags; \
\
/* Number of input images */ \
int n_input_planes; \
/* Height of each input image */ \
int input_height; \
/* Width of each input image */ \
int input_width; \
\
/* Number of output images */ \
int n_output_planes; \
/* Height of each output image */ \
int output_height; \
/* Width of each output image */ \
int output_width; \
\
/* Learning rate at the first iteration */ \
float init_learn_rate; \
/* Dynamics of learning rate decreasing */ \
int learn_rate_decrease_type; \
/* Trainable weights of the layer (including bias) */ \
/* i-th row is a set of weights of the i-th output plane */ \
CvMat* weights; \
\
CvCNNLayerForward forward; \
CvCNNLayerBackward backward; \
CvCNNLayerRelease release; \
/* Pointers to the previous and next layers in the network */ \
CvCNNLayer* prev_layer; \
CvCNNLayer* next_layer
typedef struct CvCNNLayer
{
CV_CNN_LAYER_FIELDS();
}CvCNNLayer;
typedef struct CvCNNConvolutionLayer
{
CV_CNN_LAYER_FIELDS();
// Kernel size (height and width) for convolution.
int K;
// connections matrix, (i,j)-th element is 1 iff there is a connection between
// i-th plane of the current layer and j-th plane of the previous layer;
// (i,j)-th element is equal to 0 otherwise
CvMat *connect_mask;
// value of the learning rate for updating weights at the first iteration
}CvCNNConvolutionLayer;
typedef struct CvCNNSubSamplingLayer
{
CV_CNN_LAYER_FIELDS();
// ratio between the heights (or widths - ratios are supposed to be equal)
// of the input and output planes
int sub_samp_scale;
// amplitude of sigmoid activation function
float a;
// scale parameter of sigmoid activation function
float s;
// exp2ssumWX = exp(2<s>*(bias+w*(x1+...+x4))), where x1,...x4 are some elements of X
// - is the vector used in computing of the activation function in backward
CvMat* exp2ssumWX;
// (x1+x2+x3+x4), where x1,...x4 are some elements of X
// - is the vector used in computing of the activation function in backward
CvMat* sumX;
}CvCNNSubSamplingLayer;
// Structure of the last layer.
typedef struct CvCNNFullConnectLayer
{
CV_CNN_LAYER_FIELDS();
// amplitude of sigmoid activation function
float a;
// scale parameter of sigmoid activation function
float s;
// exp2ssumWX = exp(2*<s>*(W*X)) - is the vector used in computing of the
// activation function and it's derivative by the formulae
// activ.func. = <a>(exp(2<s>WX)-1)/(exp(2<s>WX)+1) == <a> - 2<a>/(<exp2ssumWX> + 1)
// (activ.func.)' = 4<a><s>exp(2<s>WX)/(exp(2<s>WX)+1)^2
CvMat* exp2ssumWX;
}CvCNNFullConnectLayer;
typedef struct CvCNNetwork
{
int n_layers;
CvCNNLayer* layers;
CvCNNetworkAddLayer add_layer;
CvCNNetworkRelease release;
}CvCNNetwork;
typedef struct CvCNNStatModel
{
CV_STAT_MODEL_FIELDS();
CvCNNetwork* network;
// etalons are allocated as rows, the i-th etalon has label cls_labeles[i]
CvMat* etalons;
// classes labels
CvMat* cls_labels;
}CvCNNStatModel;
typedef struct CvCNNStatModelParams
{
CV_STAT_MODEL_PARAM_FIELDS();
// network must be created by the functions cvCreateCNNetwork and <add_layer>
CvCNNetwork* network;
CvMat* etalons;
// termination criteria
int max_iter;
int start_iter;
int grad_estim_type;
}CvCNNStatModelParams;
CVAPI(CvCNNLayer*) cvCreateCNNConvolutionLayer(
int n_input_planes, int input_height, int input_width,
int n_output_planes, int K,
float init_learn_rate, int learn_rate_decrease_type,
CvMat* connect_mask CV_DEFAULT(0), CvMat* weights CV_DEFAULT(0) );
CVAPI(CvCNNLayer*) cvCreateCNNSubSamplingLayer(
int n_input_planes, int input_height, int input_width,
int sub_samp_scale, float a, float s,
float init_learn_rate, int learn_rate_decrease_type, CvMat* weights CV_DEFAULT(0) );
CVAPI(CvCNNLayer*) cvCreateCNNFullConnectLayer(
int n_inputs, int n_outputs, float a, float s,
float init_learn_rate, int learning_type, CvMat* weights CV_DEFAULT(0) );
CVAPI(CvCNNetwork*) cvCreateCNNetwork( CvCNNLayer* first_layer );
CVAPI(CvStatModel*) cvTrainCNNClassifier(
const CvMat* train_data, int tflag,
const CvMat* responses,
const CvStatModelParams* params,
const CvMat* CV_DEFAULT(0),
const CvMat* sample_idx CV_DEFAULT(0),
const CvMat* CV_DEFAULT(0), const CvMat* CV_DEFAULT(0) );
/****************************************************************************************\
* Estimate classifiers algorithms *
\****************************************************************************************/
typedef const CvMat* (CV_CDECL *CvStatModelEstimateGetMat)
( const CvStatModel* estimateModel );
typedef int (CV_CDECL *CvStatModelEstimateNextStep)
( CvStatModel* estimateModel );
typedef void (CV_CDECL *CvStatModelEstimateCheckClassifier)
( CvStatModel* estimateModel,
const CvStatModel* model,
const CvMat* features,
int sample_t_flag,
const CvMat* responses );
typedef void (CV_CDECL *CvStatModelEstimateCheckClassifierEasy)
( CvStatModel* estimateModel,
const CvStatModel* model );
typedef float (CV_CDECL *CvStatModelEstimateGetCurrentResult)
( const CvStatModel* estimateModel,
float* correlation );
typedef void (CV_CDECL *CvStatModelEstimateReset)
( CvStatModel* estimateModel );
//-------------------------------- Cross-validation --------------------------------------
#define CV_CROSS_VALIDATION_ESTIMATE_CLASSIFIER_PARAM_FIELDS() \
CV_STAT_MODEL_PARAM_FIELDS(); \
int k_fold; \
int is_regression; \
CvRNG* rng
typedef struct CvCrossValidationParams
{
CV_CROSS_VALIDATION_ESTIMATE_CLASSIFIER_PARAM_FIELDS();
} CvCrossValidationParams;
#define CV_CROSS_VALIDATION_ESTIMATE_CLASSIFIER_FIELDS() \
CvStatModelEstimateGetMat getTrainIdxMat; \
CvStatModelEstimateGetMat getCheckIdxMat; \
CvStatModelEstimateNextStep nextStep; \
CvStatModelEstimateCheckClassifier check; \
CvStatModelEstimateGetCurrentResult getResult; \
CvStatModelEstimateReset reset; \
int is_regression; \
int folds_all; \
int samples_all; \
int* sampleIdxAll; \
int* folds; \
int max_fold_size; \
int current_fold; \
int is_checked; \
CvMat* sampleIdxTrain; \
CvMat* sampleIdxEval; \
CvMat* predict_results; \
int correct_results; \
int all_results; \
double sq_error; \
double sum_correct; \
double sum_predict; \
double sum_cc; \
double sum_pp; \
double sum_cp
typedef struct CvCrossValidationModel
{
CV_STAT_MODEL_FIELDS();
CV_CROSS_VALIDATION_ESTIMATE_CLASSIFIER_FIELDS();
} CvCrossValidationModel;
CVAPI(CvStatModel*)
cvCreateCrossValidationEstimateModel
( int samples_all,
const CvStatModelParams* estimateParams CV_DEFAULT(0),
const CvMat* sampleIdx CV_DEFAULT(0) );
CVAPI(float)
cvCrossValidation( const CvMat* trueData,
int tflag,
const CvMat* trueClasses,
CvStatModel* (*createClassifier)( const CvMat*,
int,
const CvMat*,
const CvStatModelParams*,
const CvMat*,
const CvMat*,
const CvMat*,
const CvMat* ),
const CvStatModelParams* estimateParams CV_DEFAULT(0),
const CvStatModelParams* trainParams CV_DEFAULT(0),
const CvMat* compIdx CV_DEFAULT(0),
const CvMat* sampleIdx CV_DEFAULT(0),
CvStatModel** pCrValModel CV_DEFAULT(0),
const CvMat* typeMask CV_DEFAULT(0),
const CvMat* missedMeasurementMask CV_DEFAULT(0) );
#endif
/****************************************************************************************\
* Auxilary functions declarations *
\****************************************************************************************/
/* Generates <sample> from multivariate normal distribution, where <mean> - is an
average row vector, <cov> - symmetric covariation matrix */
CVAPI(void) cvRandMVNormal( CvMat* mean, CvMat* cov, CvMat* sample,
CvRNG* rng CV_DEFAULT(0) );
/* Generates sample from gaussian mixture distribution */
CVAPI(void) cvRandGaussMixture( CvMat* means[],
CvMat* covs[],
float weights[],
int clsnum,
CvMat* sample,
CvMat* sampClasses CV_DEFAULT(0) );
#define CV_TS_CONCENTRIC_SPHERES 0
/* creates test set */
CVAPI(void) cvCreateTestSet( int type, CvMat** samples,
int num_samples,
int num_features,
CvMat** responses,
int num_classes, ... );
#endif
/****************************************************************************************\
* Data *
\****************************************************************************************/
#include <map>
#include <string>
#include <iostream>
#define CV_COUNT 0
#define CV_PORTION 1
struct CV_EXPORTS CvTrainTestSplit
{
public:
CvTrainTestSplit();
CvTrainTestSplit( int _train_sample_count, bool _mix = true);
CvTrainTestSplit( float _train_sample_portion, bool _mix = true);
union
{
int count;
float portion;
} train_sample_part;
int train_sample_part_mode;
union
{
int *count;
float *portion;
} *class_part;
int class_part_mode;
bool mix;
};
class CV_EXPORTS CvMLData
{
public:
CvMLData();
virtual ~CvMLData();
// returns:
// 0 - OK
// 1 - file can not be opened or is not correct
int read_csv(const char* filename);
const CvMat* get_values(){ return values; };
const CvMat* get_responses();
const CvMat* get_missing(){ return missing; };
void set_response_idx( int idx ); // old response become predictors, new response_idx = idx
// if idx < 0 there will be no response
int get_response_idx() { return response_idx; }
const CvMat* get_train_sample_idx() { return train_sample_idx; };
const CvMat* get_test_sample_idx() { return test_sample_idx; };
void mix_train_and_test_idx();
void set_train_test_split( const CvTrainTestSplit * spl);
const CvMat* get_var_idx();
void chahge_var_idx( int vi, bool state ); // state == true to set vi-variable as predictor
const CvMat* get_var_types();
int get_var_type( int var_idx ) { return var_types->data.ptr[var_idx]; };
// following 2 methods enable to change vars type
// use these methods to assign CV_VAR_CATEGORICAL type for categorical variable
// with numerical labels; in the other cases var types are correctly determined automatically
void set_var_types( const char* str ); // str examples:
// "ord[0-17],cat[18]", "ord[0,2,4,10-12], cat[1,3,5-9,13,14]",
// "cat", "ord" (all vars are categorical/ordered)
void change_var_type( int var_idx, int type); // type in { CV_VAR_ORDERED, CV_VAR_CATEGORICAL }
void set_delimiter( char ch );
char get_delimiter() { return delimiter; };
void set_miss_ch( char ch );
char get_miss_ch() { return miss_ch; };
protected:
virtual void clear();
void str_to_flt_elem( const char* token, float& flt_elem, int& type);
void free_train_test_idx();
char delimiter;
char miss_ch;
//char flt_separator;
CvMat* values;
CvMat* missing;
CvMat* var_types;
CvMat* var_idx_mask;
CvMat* response_out; // header
CvMat* var_idx_out; // mat
CvMat* var_types_out; // mat
int response_idx;
int train_sample_count;
bool mix;
int total_class_count;
std::map<std::string, int> *class_map;
CvMat* train_sample_idx;
CvMat* test_sample_idx;
int* sample_idx; // data of train_sample_idx and test_sample_idx
CvRNG rng;
};
namespace cv
{
typedef CvStatModel StatModel;
typedef CvParamGrid ParamGrid;
typedef CvNormalBayesClassifier NormalBayesClassifier;
typedef CvKNearest KNearest;
typedef CvSVMParams SVMParams;
typedef CvSVMKernel SVMKernel;
typedef CvSVMSolver SVMSolver;
typedef CvSVM SVM;
typedef CvEMParams EMParams;
typedef CvEM ExpectationMaximization;
typedef CvDTreeParams DTreeParams;
typedef CvMLData TrainData;
typedef CvDTree DecisionTree;
typedef CvForestTree ForestTree;
typedef CvRTParams RandomTreeParams;
typedef CvRTrees RandomTrees;
typedef CvERTreeTrainData ERTreeTRainData;
typedef CvForestERTree ERTree;
typedef CvERTrees ERTrees;
typedef CvBoostParams BoostParams;
typedef CvBoostTree BoostTree;
typedef CvBoost Boost;
typedef CvANN_MLP_TrainParams ANN_MLP_TrainParams;
typedef CvANN_MLP NeuralNet_MLP;
}
#endif
/* End of file. */
| [
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
] | [
[
[
1,
1943
]
]
] |
468432bccfe3217ed20f39352d05132989fc2478 | 519a3884c80f7a3926880b28df5755935ec7aa57 | /DicomShell/DicomTagList.h | 7e8776cafeab6f2958384928edfec9f462cc2a46 | [] | no_license | Jeffrey2008/dicomshell | 71ef9844ed83c38c2529a246b6efffdd5645ed92 | 14c98fcd9238428e1541e50b7d0a67878cf8add4 | refs/heads/master | 2020-10-01T17:39:11.786479 | 2009-09-02T17:49:27 | 2009-09-02T17:49:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 355 | h | #pragma once
#include <vector>
#include <string>
class DicomTagList
{
public:
DicomTagList(LPCTSTR key);
~DicomTagList(void);
typedef std::vector<DcmTagKey> TagCollection;
TagCollection const& getTags();
private:
std::vector<DcmTagKey> m_tags;
bool m_valid;
std::wstring m_dicPath;
FILETIME m_dicTime;
std::wstring m_key;
};
| [
"andreas.grimme@715416e8-819e-11dd-8f04-175a6ebbc832"
] | [
[
[
1,
19
]
]
] |
41384b1b3496cdeee89e7dae74c61858d177e420 | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/GameDLL/VehicleMovementTank.cpp | 449e242c2b3c787c56a70babf70486e2355c68e6 | [] | no_license | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05T14:32:01.782047 | 2008-01-01T13:13:39 | 2008-01-01T13:13:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,047 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2005.
-------------------------------------------------------------------------
$Id$
$DateTime$
Description: Implements movement type for tracked vehicles
-------------------------------------------------------------------------
History:
- 13:06:2005: Created by MichaelR
*************************************************************************/
#include "StdAfx.h"
#include "Game.h"
#include "GameCVars.h"
#include <GameUtils.h>
#include "IVehicleSystem.h"
#include "VehicleMovementTank.h"
#define THREAD_SAFE 1
//------------------------------------------------------------------------
CVehicleMovementTank::CVehicleMovementTank()
{
m_pedalSpeed = 1.5f;
m_pedalThreshold = 0.2f;
m_steerSpeed = 0.f;
m_steerSpeedRelax = 0.f;
m_steerLimit = 1.f;
m_latFricMin = m_latFricMinSteer = m_latFricMax = m_currentFricMin = 1.f;
m_latSlipMin = m_currentSlipMin = 0.f;
m_latSlipMax = 5.f;
m_currPedal = 0;
m_currSteer = 0;
m_boostEndurance = 5.f;
m_boostRegen = m_boostEndurance;
m_boostStrength = 4.f;
m_drivingWheels[0] = m_drivingWheels[1] = 0;
m_steeringImpulseMin = 0.f;
m_steeringImpulseMax = 0.f;
m_steeringImpulseRelaxMin = 0.f;
m_steeringImpulseRelaxMax = 0.f;
}
//------------------------------------------------------------------------
CVehicleMovementTank::~CVehicleMovementTank()
{
}
//------------------------------------------------------------------------
bool CVehicleMovementTank::Init(IVehicle* pVehicle, const SmartScriptTable &table)
{
if (!CVehicleMovementStdWheeled::Init(pVehicle, table))
return false;
MOVEMENT_VALUE("pedalSpeed", m_pedalSpeed);
MOVEMENT_VALUE_OPT("pedalThreshold", m_pedalThreshold, table);
MOVEMENT_VALUE("steerSpeed", m_steerSpeed);
MOVEMENT_VALUE_OPT("steerSpeedRelax", m_steerSpeedRelax, table);
MOVEMENT_VALUE_OPT("steerLimit", m_steerLimit, table);
MOVEMENT_VALUE("latFricMin", m_latFricMin);
MOVEMENT_VALUE("latFricMinSteer", m_latFricMinSteer);
MOVEMENT_VALUE("latFricMax", m_latFricMax);
MOVEMENT_VALUE("latSlipMin", m_latSlipMin);
MOVEMENT_VALUE("latSlipMax", m_latSlipMax);
MOVEMENT_VALUE_OPT("steeringImpulseMin", m_steeringImpulseMin, table);
MOVEMENT_VALUE_OPT("steeringImpulseMax", m_steeringImpulseMax, table);
MOVEMENT_VALUE_OPT("steeringImpulseRelaxMin", m_steeringImpulseRelaxMin, table);
MOVEMENT_VALUE_OPT("steeringImpulseRelaxMax", m_steeringImpulseRelaxMax, table);
m_movementTweaks.Init(table);
m_maxSoundSlipSpeed = 10.f;
return true;
}
//------------------------------------------------------------------------
void CVehicleMovementTank::PostInit()
{
CVehicleMovementStdWheeled::PostInit();
for (int i=0; i<m_wheelParts.size(); ++i)
{
if (m_wheelParts[i]->GetIWheel()->GetCarGeomParams()->bDriving)
m_drivingWheels[m_wheelParts[i]->GetLocalTM(false).GetTranslation().x > 0.f] = m_wheelParts[i];
}
assert(m_drivingWheels[0] && m_drivingWheels[1]);
m_treadParts.clear();
int nParts = m_pVehicle->GetPartCount();
for (int i=0; i<nParts; ++i)
{
IVehiclePart* pPart = m_pVehicle->GetPart(i);
if (pPart->GetType() == IVehiclePart::eVPT_Tread)
{
m_treadParts.push_back(pPart);
}
}
}
//------------------------------------------------------------------------
void CVehicleMovementTank::Reset()
{
CVehicleMovementStdWheeled::Reset();
}
//------------------------------------------------------------------------
void CVehicleMovementTank::SetLatFriction(float latFric)
{
// todo: do calculation per-wheel?
IPhysicalEntity* pPhysics = GetPhysics();
int numWheels = m_pVehicle->GetWheelCount();
pe_params_wheel params;
params.kLatFriction = latFric;
for (int i=0; i<numWheels; ++i)
{
params.iWheel = i;
pPhysics->SetParams(¶ms, THREAD_SAFE);
}
m_latFriction = latFric;
}
//////////////////////////////////////////////////////////////////////////
// NOTE: This function must be thread-safe. Before adding stuff contact MarcoC.
void CVehicleMovementTank::ProcessMovement(const float deltaTime)
{
FUNCTION_PROFILER( gEnv->pSystem, PROFILE_GAME );
m_netActionSync.UpdateObject(this);
CryAutoLock<CryFastLock> lk(m_lock);
CVehicleMovementBase::ProcessMovement(deltaTime);
if (!(m_actorId && m_isEnginePowered))
{
IPhysicalEntity* pPhysics = GetPhysics();
if (m_latFriction != 1.3f)
SetLatFriction(1.3f);
if (m_axleFriction != m_axleFrictionMax)
UpdateAxleFriction(0.f, false, deltaTime);
m_action.bHandBrake = 1;
m_action.pedal = 0;
m_action.steer = 0;
pPhysics->Action(&m_action, 1);
return;
}
IPhysicalEntity* pPhysics = GetPhysics();
MARK_UNUSED m_action.clutch;
Matrix34 worldTM( m_PhysPos.q );
worldTM.AddTranslation( m_PhysPos.pos );
Vec3 localVel = worldTM.GetInvertedFast().TransformVector(m_PhysDyn.v);
Vec3 localW = worldTM.GetInvertedFast().TransformVector(m_PhysDyn.w);
float speed = m_PhysDyn.v.len();
float speedRatio = min(1.f, speed/m_maxSpeed);
float actionPedal = abs(m_movementAction.power) > 0.001f ? m_movementAction.power : 0.f;
// tank specific:
// avoid steering input around 0.5 (ask Anton)
float actionSteer = m_movementAction.rotateYaw;
float absSteer = abs(actionSteer);
float steerSpeed = (absSteer < 0.01f && abs(m_currSteer) > 0.01f) ? m_steerSpeedRelax : m_steerSpeed;
if (steerSpeed == 0.f)
{
m_currSteer = sgn(actionSteer);
}
else
{
if (m_movementAction.isAI)
{
m_currSteer = actionSteer;
}
else
{
m_currSteer += min(abs(actionSteer-m_currSteer), deltaTime*steerSpeed) * sgn(actionSteer-m_currSteer);
}
}
Limit(m_currSteer, -m_steerLimit, m_steerLimit);
if (abs(m_currSteer) > 0.0001f)
{
// if steering, apply full throttle to have enough turn power
actionPedal = sgn(actionPedal);
if (actionPedal == 0.f)
{
// allow steering-on-teh-spot only above maxReverseSpeed (to avoid sudden reverse of controls)
const float maxReverseSpeed = -1.5f;
actionPedal = max(0.f, min(1.f, 1.f-(localVel.y/maxReverseSpeed)));
// todo
float steerLim = 0.8f;
Limit(m_currSteer, -steerLim*m_steerLimit, steerLim*m_steerLimit);
}
}
if (!pPhysics->GetStatus(&m_vehicleStatus))
return;
int currGear = m_vehicleStatus.iCurGear - 1; // indexing for convenience: -1,0,1,2,..
UpdateAxleFriction(m_movementAction.power, true, deltaTime);
UpdateSuspension(deltaTime);
float absPedal = abs(actionPedal);
// pedal ramping
if (m_pedalSpeed == 0.f)
m_currPedal = actionPedal;
else
{
m_currPedal += deltaTime * m_pedalSpeed * sgn(actionPedal - m_currPedal);
m_currPedal = clamp_tpl(m_currPedal, -absPedal, absPedal);
}
// only apply pedal after threshold is exceeded
if (currGear == 0 && fabs_tpl(m_currPedal) < m_pedalThreshold)
m_action.pedal = 0;
else
m_action.pedal = m_currPedal;
// change pedal amount based on damages
float damageMul = 0.0f;
{
if (m_movementAction.isAI)
{
damageMul = 1.0f - 0.30f * m_damage;
m_action.pedal *= damageMul;
}
else
{
m_action.pedal *= GetWheelCondition();
damageMul = 1.0f - 0.7f*m_damage;
m_action.pedal *= damageMul;
}
}
// reverse steering value for backward driving
float effSteer = m_currSteer * sgn(actionPedal);
// update lateral friction
float latSlipMinGoal = 0.f;
float latFricMinGoal = m_latFricMin;
if (abs(effSteer) > 0.01f && !m_movementAction.brake)
{
latSlipMinGoal = m_latSlipMin;
// use steering friction, but not when countersteering
if (sgn(effSteer) != sgn(localW.z))
latFricMinGoal = m_latFricMinSteer;
}
Interpolate(m_currentSlipMin, latSlipMinGoal, 3.f, deltaTime);
if (latFricMinGoal < m_currentFricMin)
m_currentFricMin = latFricMinGoal;
else
Interpolate(m_currentFricMin, latFricMinGoal, 3.f, deltaTime);
float fractionSpeed = min(1.f, max(0.f, m_avgLateralSlip-m_currentSlipMin) / (m_latSlipMax-m_currentSlipMin));
float latFric = fractionSpeed * (m_latFricMax-m_currentFricMin) + m_currentFricMin;
if ( m_movementAction.brake && m_movementAction.isAI )
{
// it is natural for ai, apply differnt friction value while handbreaking
latFric = m_latFricMax;
}
if (latFric != m_latFriction)
{
SetLatFriction(latFric);
}
const static float maxSteer = gf_PI/4.f; // fix maxsteer, shouldn't change
m_action.steer = m_currSteer * maxSteer;
if (m_steeringImpulseMin > 0.f && m_wheelContactsLeft != 0 && m_wheelContactsRight != 0)
{
const float maxW = 0.3f*gf_PI;
float steer = abs(m_currSteer)>0.001f ? m_currSteer : 0.f;
float desired = steer * maxW;
float curr = -localW.z;
float err = desired - curr; // err>0 means correction to right
Limit(err, -maxW, maxW);
if (abs(err) > 0.01f)
{
float amount = m_steeringImpulseMin + speedRatio*(m_steeringImpulseMax-m_steeringImpulseMin);
// bigger correction for relaxing
if (desired == 0.f || (desired*curr>0 && abs(desired)<abs(curr)))
amount = m_steeringImpulseRelaxMin + speedRatio*(m_steeringImpulseRelaxMax-m_steeringImpulseRelaxMin);
float corr = -err * amount * m_PhysDyn.mass * deltaTime;
pe_action_impulse imp;
imp.iApplyTime = 0;
imp.angImpulse = worldTM.GetColumn2() * corr;
pPhysics->Action(&imp, THREAD_SAFE);
}
}
m_action.bHandBrake = (m_movementAction.brake) ? 1 : 0;
if (currGear > 0 && m_vehicleStatus.iCurGear < m_currentGear)
{
// when shifted down, disengage clutch immediately to avoid power/speed dropdown
m_action.clutch = 1.f;
}
pPhysics->Action(&m_action, 1);
if (Boosting())
ApplyBoost(speed, 1.2f*m_maxSpeed*GetWheelCondition()*damageMul, m_boostStrength, deltaTime);
if (m_wheelContacts <= 1 && speed > 5.f)
{
ApplyAirDamp(DEG2RAD(20.f), DEG2RAD(10.f), deltaTime, THREAD_SAFE);
UpdateGravity(-9.81f * 1.4f);
}
if (m_netActionSync.PublishActions( CNetworkMovementStdWheeled(this) ))
m_pVehicle->GetGameObject()->ChangedNetworkState( eEA_GameClientDynamic );
}
//////////////////////////////////////////////////////////////////////////
void CVehicleMovementTank::OnEvent(EVehicleMovementEvent event, const SVehicleMovementEventParams& params)
{
CVehicleMovementStdWheeled::OnEvent(event,params);
if (event == eVME_TireBlown || event == eVME_TireRestored)
{
// tracked vehicles don't have blowable tires, these events are sent on track destruction
int numTreads = m_treadParts.size();
int treadsPrev = m_blownTires;
m_blownTires = max(0, min(numTreads, event==eVME_TireBlown ? m_blownTires+1 : m_blownTires-1));
// reduce speed based on number of destroyed treads
if (m_blownTires != treadsPrev)
{
SetEngineRPMMult(GetWheelCondition());
}
}
}
//------------------------------------------------------------------------
void CVehicleMovementTank::OnAction(const TVehicleActionId actionId, int activationMode, float value)
{
CryAutoLock<CryFastLock> lk(m_lock);
CVehicleMovementBase::OnAction(actionId, activationMode, value);
}
//------------------------------------------------------------------------
float CVehicleMovementTank::GetWheelCondition() const
{
if (0 == m_blownTires)
return 1.0f;
int numTreads = m_treadParts.size();
float treadCondition = (numTreads > 0) ? 1.0f - ((float)m_blownTires / numTreads) : 1.0f;
// for a 2-tread vehicle, want to reduce speed by 40% for each tread shot out.
return 1.0f - (0.8f * (1.0f - treadCondition));
}
//----------------------------------------------------------------------------------
void CVehicleMovementTank::DebugDrawMovement(const float deltaTime)
{
if (!IsProfilingMovement())
return;
CVehicleMovementStdWheeled::DebugDrawMovement(deltaTime);
IPhysicalEntity* pPhysics = GetPhysics();
IRenderer* pRenderer = gEnv->pRenderer;
float color[4] = {1,1,1,1};
float green[4] = {0,1,0,1};
ColorB colRed(255,0,0,255);
float y = 50.f, step1 = 15.f, step2 = 20.f, size=1.3f, sizeL=1.5f;
if (g_pGameCVars->v_dumpFriction)
{
if (m_avgLateralSlip > 0.01f)
{
CryLog("%4.2f, %4.2f, %4.2f", m_currSteer, m_avgLateralSlip, m_latFriction);
}
}
}
//------------------------------------------------------------------------
bool CVehicleMovementTank::RequestMovement(CMovementRequest& movementRequest)
{
FUNCTION_PROFILER( gEnv->pSystem, PROFILE_GAME );
m_movementAction.isAI = true;
if (!m_isEnginePowered)
return false;
CryAutoLock<CryFastLock> lk(m_lock);
if (movementRequest.HasLookTarget())
m_aiRequest.SetLookTarget(movementRequest.GetLookTarget());
else
m_aiRequest.ClearLookTarget();
if (movementRequest.HasMoveTarget())
{
Vec3 entityPos = m_pEntity->GetWorldPos();
Vec3 start(entityPos);
Vec3 end( movementRequest.GetMoveTarget() );
Vec3 pos = ( end - start ) * 100.0f;
pos +=start;
m_aiRequest.SetMoveTarget( pos );
}
else
m_aiRequest.ClearMoveTarget();
if (movementRequest.HasDesiredSpeed())
m_aiRequest.SetDesiredSpeed(movementRequest.GetDesiredSpeed());
else
m_aiRequest.ClearDesiredSpeed();
if (movementRequest.HasForcedNavigation())
{
Vec3 entityPos = m_pEntity->GetWorldPos();
m_aiRequest.SetForcedNavigation(movementRequest.GetForcedNavigation());
m_aiRequest.SetDesiredSpeed(movementRequest.GetForcedNavigation().GetLength());
m_aiRequest.SetMoveTarget(entityPos+movementRequest.GetForcedNavigation().GetNormalizedSafe()*100.0f);
}
else
m_aiRequest.ClearForcedNavigation();
return true;
}
//////////////////////////////////////////////////////////////////////////
// NOTE: This function must be thread-safe. Before adding stuff contact MarcoC.
void CVehicleMovementTank::ProcessAI(const float deltaTime)
{
FUNCTION_PROFILER( GetISystem(), PROFILE_GAME );
float dt = max( deltaTime, 0.005f);
m_movementAction.brake = false;
m_movementAction.rotateYaw = 0.0f;
m_movementAction.power = 0.0f;
float inputSpeed = 0.0f;
{
if (m_aiRequest.HasDesiredSpeed())
inputSpeed = m_aiRequest.GetDesiredSpeed();
Limit(inputSpeed, -m_maxSpeed, m_maxSpeed);
}
Vec3 vMove(ZERO);
{
if (m_aiRequest.HasMoveTarget())
vMove = ( m_aiRequest.GetMoveTarget() - m_PhysPos.pos ).GetNormalizedSafe();
}
//start calculation
if ( fabsf( inputSpeed ) < 0.0001f || m_tireBlownTimer > 1.5f )
{
// only the case to use a hand break
m_movementAction.brake = true;
}
else
{
Matrix33 entRotMatInvert( m_PhysPos.q );
entRotMatInvert.Invert();
float currentAngleSpeed = RAD2DEG(-m_PhysDyn.w.z);
const static float maxSteer = RAD2DEG(gf_PI/4.f); // fix maxsteer, shouldn't change
Vec3 vVel = m_PhysDyn.v;
Vec3 vVelR = entRotMatInvert * vVel;
float currentSpeed =vVel.GetLength();
vVelR.NormalizeSafe();
if ( vVelR.Dot( FORWARD_DIRECTION ) < 0 )
currentSpeed *= -1.0f;
// calculate pedal
static float accScale = 0.5f;
m_movementAction.power = (inputSpeed - currentSpeed) * accScale;
Limit( m_movementAction.power, -1.0f, 1.0f);
// calculate angles
Vec3 vMoveR = entRotMatInvert * vMove;
Vec3 vFwd = FORWARD_DIRECTION;
vMoveR.z =0.0f;
vMoveR.NormalizeSafe();
if ( inputSpeed < 0.0 ) // when going back
{
vFwd *= -1.0f;
vMoveR *= -1.0f;
currentAngleSpeed *=-1.0f;
}
float cosAngle = vFwd.Dot(vMoveR);
float angle = RAD2DEG( acos_tpl(cosAngle));
if ( vMoveR.Dot( Vec3( 1.0f,0.0f,0.0f ) )< 0 )
angle = -angle;
int step =0;
m_movementAction.rotateYaw = angle * 1.75f/ maxSteer;
// implementation 1. if there is enough angle speed, we don't need to steer more
if ( fabsf(currentAngleSpeed) > fabsf(angle) && angle*currentAngleSpeed > 0.0f )
{
m_movementAction.rotateYaw = m_currSteer*0.995f; step =1;
}
// implementation 2. if we can guess we reach the distination angle soon, start counter steer.
float predictDelta = inputSpeed < 0.0f ? 0.1f : 0.07f;
float dict = angle + predictDelta * ( angle - m_prevAngle) / dt ;
if ( dict*currentAngleSpeed<0.0f )
{
if ( fabsf( angle ) < 2.0f )
{
m_movementAction.rotateYaw = angle* 1.75f/ maxSteer; ; step =3;
}
else
{
m_movementAction.rotateYaw = currentAngleSpeed < 0.0f ? 1.0f : -1.0f; step =2;
}
}
// implementation 3. tank can rotate at a point
if ( fabs( angle )> 20.0f )
{
m_movementAction.power *=0.1f;
step =4;
}
// char buf[1024];
// sprintf(buf, "steering %4.2f %4.2f %4.2f %d\n", deltaTime,currentAngleSpeed, angle - m_prevAngle, step);
// OutputDebugString( buf );
m_prevAngle = angle;
}
}
//------------------------------------------------------------------------
void CVehicleMovementTank::Update(const float deltaTime)
{
CVehicleMovementStdWheeled::Update(deltaTime);
if (IsProfilingMovement())
{
if (m_steeringImpulseMin > 0.f && m_wheelContactsLeft != 0 && m_wheelContactsRight != 0)
{
const Matrix34& worldTM = m_pVehicle->GetEntity()->GetWorldTM();
Vec3 localVel = worldTM.GetInvertedFast().TransformVector(m_statusDyn.v);
Vec3 localW = worldTM.GetInvertedFast().TransformVector(m_statusDyn.w);
float speed = m_statusDyn.v.len();
float speedRatio = min(1.f, speed/m_maxSpeed);
const float maxW = 0.3f*gf_PI;
float steer = abs(m_currSteer)>0.001f ? m_currSteer : 0.f;
float desired = steer * maxW;
float curr = -localW.z;
float err = desired - curr; // err>0 means correction to right
Limit(err, -maxW, maxW);
if (abs(err) > 0.01f)
{
float amount = m_steeringImpulseMin + speedRatio*(m_steeringImpulseMax-m_steeringImpulseMin);
float corr = -err * amount * m_statusDyn.mass * deltaTime;
pe_action_impulse imp;
imp.iApplyTime = 1;
imp.angImpulse = worldTM.GetColumn2() * corr;
float color[] = {1,1,1,1};
gEnv->pRenderer->Draw2dLabel(300,300,1.5f,color,false,"err: %.2f ", err);
gEnv->pRenderer->Draw2dLabel(300,320,1.5f,color,false,"corr: %.3f", corr/m_statusDyn.mass);
IRenderAuxGeom* pGeom = gEnv->pRenderer->GetIRenderAuxGeom();
float len = 4.f * imp.angImpulse.len() / deltaTime / m_statusDyn.mass;
Vec3 dir = -sgn(corr) * worldTM.GetColumn0(); //imp.angImpulse.GetNormalized();
pGeom->DrawCone(worldTM.GetTranslation()+Vec3(0,0,5)-(dir*len), dir, 0.5f, len, ColorB(128,0,0,255));
}
}
}
DebugDrawMovement(deltaTime);
}
//------------------------------------------------------------------------
void CVehicleMovementTank::UpdateSounds(const float deltaTime)
{
CVehicleMovementStdWheeled::UpdateSounds(deltaTime);
}
//------------------------------------------------------------------------
void CVehicleMovementTank::UpdateSpeedRatio(const float deltaTime)
{
float speedSqr = max(sqr(m_avgWheelRot), m_statusDyn.v.len2());
Interpolate(m_speedRatio, min(1.f, speedSqr/sqr(m_maxSpeed)), 5.f, deltaTime);
}
//------------------------------------------------------------------------
void CVehicleMovementTank::StopEngine()
{
CVehicleMovementStdWheeled::StopEngine();
}
void CVehicleMovementTank::GetMemoryStatistics(ICrySizer * s)
{
s->Add(*this);
s->AddContainer(m_treadParts);
CVehicleMovementStdWheeled::GetMemoryStatistics(s);
} | [
"[email protected]",
"kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31"
] | [
[
[
1,
96
],
[
114,
135
],
[
138,
141
],
[
145,
147
],
[
165,
167
],
[
170,
170
],
[
174,
191
],
[
193,
212
],
[
214,
217
],
[
221,
222
],
[
226,
242
],
[
259,
283
],
[
291,
298
],
[
300,
315
],
[
317,
318
],
[
320,
324
],
[
326,
335
],
[
337,
337
],
[
343,
347
],
[
391,
418
],
[
423,
424
],
[
426,
426
],
[
433,
433
],
[
440,
441
],
[
450,
450
],
[
455,
455
],
[
458,
458
],
[
476,
476
],
[
569,
575
],
[
620,
644
],
[
646,
647
]
],
[
[
97,
113
],
[
136,
137
],
[
142,
144
],
[
148,
164
],
[
168,
169
],
[
171,
173
],
[
192,
192
],
[
213,
213
],
[
218,
220
],
[
223,
225
],
[
243,
258
],
[
284,
290
],
[
299,
299
],
[
316,
316
],
[
319,
319
],
[
325,
325
],
[
336,
336
],
[
338,
342
],
[
348,
390
],
[
419,
422
],
[
425,
425
],
[
427,
432
],
[
434,
439
],
[
442,
449
],
[
451,
454
],
[
456,
457
],
[
459,
475
],
[
477,
568
],
[
576,
619
],
[
645,
645
]
]
] |
a9178d9afd9ecbe76b1af15eb543df712076c31d | 1a307d4d512751c548e21acf8924162910be1bb9 | /quadremote/sonar.cpp | 22e9b0273d9e0a0f0354f524e49102f86018942f | [] | no_license | krchan/uvicquad | 4d2c944b36e7cf2aee446c019d509656785ea455 | 1bdeed79d4f9903a1c5a6b59aa775f0dd1743e76 | refs/heads/master | 2021-01-10T08:34:44.208309 | 2011-02-10T03:20:07 | 2011-02-10T03:20:07 | 51,811,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,625 | cpp | #include "sonar.h"
#include "common.h"
#include "WProgram.h"
#include <avr/delay.h>
#include <math.h>
static void sonarEcho1();
static void sonarEcho2();
//static void sonarEcho3();
static uint16_t averageValue(uint8_t offset, uint8_t range, uint16_t* sonarBuffer);
//static uint16_t minValue(uint8_t offset, uint8_t range, uint16_t* sonarBuffer);
//static uint16_t maxValue(uint8_t offset, uint8_t range, uint16_t* sonarBuffer);
static uint16_t leftSonarTickCount;
static uint16_t rightSonarTickCount;
//static uint16_t frontSonarTickCount;
/*
* Index to the sonar buffer array that is used to store the data
*/
static volatile uint8_t sonarBufferIndex = 0;
/*
* xxxSonarBufer[20] holds 20 sonar readings for the
* control module to use. sonarBufferPointer points
* to the buffer location that should be used to store
* the next sonar reading data
*/
static uint16_t frontSonarBuffer[SONAR_BUFFER_SIZE];
static uint16_t leftFrontSonarBuffer[SONAR_BUFFER_SIZE];
static uint16_t leftBackSonarBuffer[SONAR_BUFFER_SIZE];
void sonarInit() {
/*
* CS32 CS31 CS30 = 011
* Set clock prescaler factor to 64
* ICNC3 = noise canceler => enabled
*/
TCCR3B &= ~_BV(CS32);
TCCR3B |= (_BV(CS30) | _BV(CS31));
TCCR3B |= _BV(ICNC3);
//Set timer 3 to Normal Mode
TCCR3A &= ~(_BV(WGM30) | _BV(WGM31));
TCCR3B &= ~(_BV(WGM32) | _BV(WGM33));
/*
* CS42 CS41 CS40 = 011
* Set clock prescaler factor to 64
* ICNC4 = noise canceler => enabled
*/
TCCR4B &= ~_BV(CS42);
TCCR4B |= (_BV(CS40) | _BV(CS41));
TCCR4B |= _BV(ICNC4);
//Set timer 4 to Normal Mode
TCCR4A &= ~(_BV(WGM40) | _BV(WGM41));
TCCR4B &= ~(_BV(WGM42) | _BV(WGM43));
// /*
// * CS52 CS51 CS50 = 011
// * Set clock prescaler factor to 64
// * ICNC5 = noise canceler => enabled
// */
// TCCR5B &= ~_BV(CS52);
// TCCR5B |= (_BV(CS50) | _BV(CS51));
// TCCR5B |= _BV(ICNC5);
//
// //Set timer 5 to Normal Mode
// TCCR5A &= ~(_BV(WGM50) | _BV(WGM51));
// TCCR5B &= ~(_BV(WGM52) | _BV(WGM53));
sonarBufferIndex = 0;
/*
* Initialize the PW pin as input and all the
* RX pins of the sonar sensors as output
*/
pinMode(LEFTFRONT_SONAR_RX, OUTPUT);
pinMode(LEFTBACK_SONAR_RX, OUTPUT);
pinMode(FRONT_SONAR_RX, OUTPUT);
/*
* Assuming sonarInit() gets called immediately after
* power up, then a period of 250 ms must be passed
* before the RX pin is ready to receive command.
*/
_delay_ms(250);
//Enable each sonar when they are first initialized
digitalWrite(LEFTFRONT_SONAR_RX, LOW);
digitalWrite(LEFTBACK_SONAR_RX, LOW);
digitalWrite(FRONT_SONAR_RX, LOW);
return;
}
void sonarMeasureDistance() {
/*
* sonarBufferIndex should always be between
* 0 and 19 since only 20 data readings should
* be kept.
*/
++sonarBufferIndex;
if (sonarBufferIndex >= 20) {
sonarBufferIndex = 0;
}
/*
* Clock is 16MHz, with a prescaler of 64, that means
* each timer tick is 4us. For the sonar, 147 us = 1 inch
* so we need to divide by 147 / 4 = 36.75.
*/
/*
* Left Sonar Reading
*/
sonarEcho1();
_delay_ms(40);
leftFrontSonarBuffer[sonarBufferIndex] = leftSonarTickCount / 36.75;
// leftFrontSonarBuffer[sonarBufferIndex] = analogRead(LEFTFRONT_SONAR_AN) / 2;
// Serial.print("Left Front: ");
// Serial.println(leftFrontSonarBuffer[sonarBufferIndex]);
/*
* Right Sonar Reading
*/
sonarEcho2();
_delay_ms(40);
leftBackSonarBuffer[sonarBufferIndex] = rightSonarTickCount / 36.75;
// leftBackSonarBuffer[sonarBufferIndex] = analogRead(LEFTBACK_SONAR_AN) / 2;
// Serial.print("Left Back: ");
// Serial.println(leftBackSonarBuffer[sonarBufferIndex]);
/*
* Front Sonar Reading
*/
digitalWrite(FRONT_SONAR_RX, HIGH);
_delay_ms(50);
frontSonarBuffer[sonarBufferIndex] = analogRead(FRONT_SONAR_AN) / 2;
// sonarEcho3();
// _delay_ms(38);
// frontSonarBuffer[sonarBufferIndex] = frontSonarTickCount / 36.75;
// frontSonarBuffer[sonarBufferIndex] = analogRead(FRONT_SONAR_AN) / 2;
// Serial.print("Left Sonar: ");
// Serial.print((int) leftSonarBuffer[sonarBufferIndex]);
// Serial.println();
//
// Serial.print("Right Sonar: ");
// Serial.print((int) rightSonarBuffer[sonarBufferIndex]);
// Serial.println();
//
// Serial.print("Front Sonar: ");
// Serial.print((int) frontSonarBuffer[sonarBufferIndex]);
// Serial.println();
return;
}
/*
* This function processes the sonarBuffer and returns
* the distance. It also rejects incorrect values by
* analyzing the trend in which the distance is changing.
*/
uint16_t sonarGetDistance(int sonarID) {
uint8_t currentIndex = sonarBufferIndex;
uint16_t result = 0;
switch (sonarID) {
case LEFTFRONT_SONAR:
result = leftFrontSonarBuffer[currentIndex];
break;
case LEFTBACK_SONAR:
result = leftBackSonarBuffer[currentIndex];
break;
case FRONT_SONAR:
result = averageValue(currentIndex, 4, frontSonarBuffer);
break;
default:
break;
}
return result;
}
static uint16_t averageValue(uint8_t offset, uint8_t range, uint16_t* sonarBuffer) {
uint8_t counter = 0;
uint16_t sum = 0;
for (counter = 0; counter < range; ++counter) {
sum += *(sonarBuffer + offset);
if (offset == 0) {
offset = SONAR_BUFFER_SIZE - 1;
}
else {
--offset;
}
}
return sum / range;
}
//static uint16_t minValue(uint8_t offset, uint8_t range, uint16_t* sonarBuffer) {
// uint8_t counter = 0;
// uint16_t min = *(sonarBuffer + offset);
//
// for (counter = 0; counter < range; ++counter) {
// if (*(sonarBuffer + offset) < min) {
// min = *(sonarBuffer + offset);
// }
//
// if (offset == 0) {
// offset = SONAR_BUFFER_SIZE - 1;
// }
// else {
// --offset;
// }
// }
// return min;
//}
//
//static uint16_t maxValue(uint8_t offset, uint8_t range, uint16_t* sonarBuffer) {
// uint8_t counter = 0;
// uint16_t max = *(sonarBuffer + offset);
//
// for (counter = 0; counter < range; ++counter) {
// if (*(sonarBuffer + offset) < max) {
// max = *(sonarBuffer + offset);
// }
//
// if (offset == 0) {
// offset = SONAR_BUFFER_SIZE - 1;
// }
// else {
// --offset;
// }
// }
// return max;
//}
/**
* Set Input Capture to look for a rising edge, clear
* the interrupt flag and then enable Input Capture.
* After that, set RX to HIGH to enable the sonar.
*/
static void sonarEcho1() {
SET_RISING_EDGE3();
CLEAR_IC_FLAG3();
SET_IC_ENABLE3();
digitalWrite(LEFTFRONT_SONAR_RX, HIGH);
return;
}
/**
* Set Input Capture to look for a rising edge, clear
* the interrupt flag and then enable Input Capture.
* After that, set RX to HIGH to enable the sonar.
*/
static void sonarEcho2() {
SET_RISING_EDGE4();
CLEAR_IC_FLAG4();
SET_IC_ENABLE4();
digitalWrite(LEFTBACK_SONAR_RX, HIGH);
return;
}
///**
// * Set Input Capture to look for a rising edge, clear
// * the interrupt flag and then enable Input Capture.
// * After that, set RX to HIGH to enable the sonar.
// */
//static void sonarEcho3() {
// SET_RISING_EDGE5();
// CLEAR_IC_FLAG5();
// SET_IC_ENABLE5();
//
// digitalWrite(FRONT_SONAR_RX, HIGH);
//
// return;
//}
ISR(TIMER3_CAPT_vect)
{
Disable_Interrupt();
/*
* Once the rising edge of PW is detected, it means
* RX has been staying HIGH long enough. Set it to
* LOW now to disable sonar.
*/
digitalWrite(LEFTFRONT_SONAR_RX, LOW);
/*
* Reset Timer 3 when the rising edge of PW is
* detected, then change the Input Capture configuration
* to detect the falling edge and clear the interrupt flag.
*/
if (IS_RISING_EDGE3()) {
TCNT3 = 0;
SET_FALLING_EDGE3();
CLEAR_IC_FLAG3();
} else {
/*
* Store the ICR3 value and disable Input Capture
* so it does not interfere with other components.
*/
leftSonarTickCount = ICR3;
SET_RISING_EDGE3();
CLEAR_IC_FLAG3();
SET_IC_DISABLE3();
}
Enable_Interrupt();
}
ISR(TIMER4_CAPT_vect)
{
Disable_Interrupt();
/*
* Once the rising edge of PW is detected, it means
* RX has been staying HIGH long enough. Set it to
* LOW now to disable sonar.
*/
digitalWrite(LEFTBACK_SONAR_RX, LOW);
/*
* Reset Timer 4 when the rising edge of PW is
* detected, then change the Input Capture configuration
* to detect the falling edge and clear the interrupt flag.
*/
if (IS_RISING_EDGE4()) {
TCNT4 = 0;
SET_FALLING_EDGE4();
CLEAR_IC_FLAG4();
} else {
/*
* Store the ICR4 value and disable Input Capture
* so it does not interfere with other components.
*/
rightSonarTickCount = ICR4;
SET_RISING_EDGE4();
CLEAR_IC_FLAG4();
SET_IC_DISABLE4();
}
Enable_Interrupt();
}
//ISR(TIMER5_CAPT_vect)
//{
// Disable_Interrupt();
//
// /*
// * Once the rising edge of PW is detected, it means
// * RX has been staying HIGH long enough. Set it to
// * LOW now to disable sonar.
// */
//// digitalWrite(FRONT_SONAR_RX, LOW);
//
// /*
// * Reset Timer 4 when the rising edge of PW is
// * detected, then change the Input Capture configuration
// * to detect the falling edge and clear the interrupt flag.
// */
// if (IS_RISING_EDGE5()) {
// TCNT5 = 0;
// SET_FALLING_EDGE5();
// CLEAR_IC_FLAG5();
// } else {
// /*
// * Store the ICR5 value and disable Input Capture
// * so it does not interfere with other components.
// */
// frontSonarTickCount = ICR5;
// SET_RISING_EDGE5();
// CLEAR_IC_FLAG5();
// SET_IC_DISABLE5();
// }
//
// Enable_Interrupt();
//}
| [
"derekja@fd5db217-9b08-7f95-a5b0-360522c52a06"
] | [
[
[
1,
394
]
]
] |
e5d45bc6c86a8ed2c4262c9efede0c1aada11c67 | 0e0559fe0cc92e4896d21929df9f1b60ad3353f1 | /pictureshow/FolderDialog.hpp | 33ee15473cbd2e69707334aff56dad92c48f787f | [] | no_license | chadaustin/PictureShow | be88450780536be2fd6c2251db6cac9648128ff7 | 075958755e65bfc124c80b1bcbf6036da1aa3eba | refs/heads/master | 2021-01-10T13:34:28.519724 | 2002-09-09T22:37:55 | 2002-09-09T22:37:55 | 36,420,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 193 | hpp | #ifndef FOLDER_DIALOG_H
#define FOLDER_DIALOG_H
#include <windows.h>
extern bool BrowseForFolderDialog(
HWND parent,
const char* title,
char folder[MAX_PATH]);
#endif
| [
"aegis@b5df0b54-75e4-4cee-80fc-53d2cfe8f84a"
] | [
[
[
1,
14
]
]
] |
f88cd36e5570140c9a5244b4fe5f7fb09485bc1d | a30b091525dc3f07cd7e12c80b8d168a0ee4f808 | /EngineAll/Math/Graph.h | a51a52a55aa61da29b43d59e300b3ce816d5dfbc | [] | no_license | ghsoftco/basecode14 | f50dc049b8f2f8d284fece4ee72f9d2f3f59a700 | 57de2a24c01cec6dc3312cbfe200f2b15d923419 | refs/heads/master | 2021-01-10T11:18:29.585561 | 2011-01-23T02:25:21 | 2011-01-23T02:25:21 | 47,255,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,018 | h | #pragma once
struct GraphEdge
{
__forceinline UINT GetOtherVertex(UINT V0) const
{
if(V[0] == V0)
{
return V[1];
}
else
{
return V[0];
}
}
UINT V[2];
float Weight;
};
struct GraphVertex
{
Vector<UINT> Edges;
//
// Internal values used by Dijkstra's algorithm
//
float Dist;
int PredecessorEdgeIndex;
bool Visited;
};
class Graph
{
public:
Graph();
Graph(const Vector<GraphEdge> &Edges);
void FreeMemory();
//void LoadFromEdgeMesh(const EdgeMesh &M);
void LoadEdges(const Vector<GraphEdge> &Edges);
void ShortestPath(UINT StartVertex, UINT EndVertex, Vector<UINT> &PathEdgeIndices);
__forceinline const Vector<GraphEdge>& Edges()
{
return _Edges;
}
private:
void GenerateAdjacencyList();
UINT HighestVertexIndex();
Vector<GraphEdge> _Edges;
Vector<GraphVertex> _Vertices;
};
| [
"zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2"
] | [
[
[
1,
55
]
]
] |
9a540f49073bf76baf29c3f2804a922f528ff7c3 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/arcemu-world/QuestMgr.h | a726bfd8de5f355ad6903f4b6e1df2c47b6c833a | [] | no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,269 | h | /*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __QUESTMGR_H
#define __QUESTMGR_H
struct QuestRelation
{
Quest *qst;
uint8 type;
};
struct QuestAssociation
{
Quest *qst;
uint8 item_count;
};
class Item;
typedef std::list<QuestRelation *> QuestRelationList;
typedef std::list<QuestAssociation *> QuestAssociationList;
class SERVER_DECL QuestMgr : public Singleton < QuestMgr >
{
public:
~QuestMgr();
uint32 PlayerMeetsReqs(Player* plr, Quest* qst, bool skiplevelcheck);
uint32 CalcStatus(Object* quest_giver, Player* plr);
uint32 CalcQuestStatus(Object* quest_giver, Player* plr, QuestRelation* qst);
uint32 CalcQuestStatus(Object* quest_giver, Player* plr, Quest* qst, uint8 type, bool skiplevelcheck);
uint32 CalcQuestStatus(Player* plr, uint32 qst);
uint32 ActiveQuestsCount(Object* quest_giver, Player* plr);
//Packet Forging...
void BuildOfferReward(WorldPacket* data,Quest* qst, Object* qst_giver, uint32 menutype, uint32 language, Player * plr);
void BuildQuestDetails(WorldPacket* data, Quest* qst, Object* qst_giver, uint32 menutype, uint32 language, Player * plr);
void BuildRequestItems(WorldPacket* data, Quest* qst, Object* qst_giver, uint32 status, uint32 language);
void BuildQuestComplete(Player*, Quest* qst);
void BuildQuestList(WorldPacket* data, Object* qst_giver, Player* plr, uint32 language);
bool OnActivateQuestGiver(Object *qst_giver, Player *plr);
bool isRepeatableQuestFinished(Player *plr, Quest *qst);
void SendQuestUpdateAddKill(Player* plr, uint32 questid, uint32 entry, uint32 count, uint32 tcount, uint64 guid);
void BuildQuestUpdateAddItem(WorldPacket* data, uint32 itemid, uint32 count);
void BuildQuestUpdateComplete(WorldPacket* data, Quest* qst);
void BuildQuestFailed(WorldPacket* data, uint32 questid);
void SendPushToPartyResponse(Player *plr, Player* pTarget, uint32 response);
bool OnGameObjectActivate(Player *plr, GameObject *go);
void OnPlayerKill(Player* plr, Creature* victim);
void OnPlayerCast(Player* plr, uint32 spellid, uint64& victimguid);
void OnPlayerItemPickup(Player* plr, Item* item);
void OnPlayerExploreArea(Player* plr, uint32 AreaID);
void AreaExplored(Player* plr, uint32 QuestID);// scriptdev2
void OnQuestAccepted(Player* plr, Quest* qst, Object *qst_giver);
void OnQuestFinished(Player* plr, Quest* qst, Object *qst_giver, uint32 reward_slot);
void GiveQuestRewardReputation(Player* plr, Quest* qst, Object *qst_giver);
uint32 GenerateQuestXP(Player *plr, Quest *qst);
uint32 GenerateRewardMoney( Player * plr, Quest * qst );
void SendQuestInvalid( INVALID_REASON reason, Player *plyr);
void SendQuestFailed(FAILED_REASON failed, Quest *qst, Player *plyr);
void SendQuestUpdateFailed(Quest *pQuest, Player *plyr);
void SendQuestUpdateFailedTimer(Quest *pQuest, Player *plyr);
void SendQuestLogFull(Player *plyr);
void LoadNPCQuests(Creature *qst_giver);
void LoadGOQuests(GameObject *go);
QuestRelationList* GetCreatureQuestList(uint32 entryid);
QuestRelationList* GetGOQuestList(uint32 entryid);
QuestAssociationList* GetQuestAssociationListForItemId (uint32 itemId);
uint32 GetGameObjectLootQuest(uint32 GO_Entry);
void SetGameObjectLootQuest(uint32 GO_Entry, uint32 Item_Entry);
ARCEMU_INLINE bool IsQuestRepeatable(Quest *qst) { return (qst->is_repeatable==1 ? true : false); }
ARCEMU_INLINE bool IsQuestDaily(Quest *qst) { return (qst->is_repeatable==2 ? true : false); }
bool CanStoreReward(Player *plyr, Quest *qst, uint32 reward_slot);
ARCEMU_INLINE int32 QuestHasMob(Quest* qst, uint32 mob)
{
for(uint32 i = 0; i < 4; ++i)
if(qst->required_mob[i] == mob)
return qst->required_mobcount[i];
return -1;
}
ARCEMU_INLINE int32 GetOffsetForMob(Quest *qst, uint32 mob)
{
for(uint32 i = 0; i < 4; ++i)
if(qst->required_mob[i] == mob)
return i;
return -1;
}
ARCEMU_INLINE int32 GetOffsetForItem(Quest *qst, uint32 itm)
{
for(uint32 i = 0; i < 4; ++i)
if(qst->required_item[i] == itm)
return i;
return -1;
}
void LoadExtraQuestStuff();
private:
HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* > m_npc_quests;
HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* > m_obj_quests;
HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* > m_itm_quests;
HM_NAMESPACE::hash_map<uint32, list<QuestAssociation *>* > m_quest_associations;
ARCEMU_INLINE HM_NAMESPACE::hash_map<uint32, list<QuestAssociation *>* >& GetQuestAssociationList()
{return m_quest_associations;}
HM_NAMESPACE::hash_map<uint32, uint32> m_ObjectLootQuestList;
template <class T> void _AddQuest(uint32 entryid, Quest *qst, uint8 type);
template <class T> HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* >& _GetList();
void AddItemQuestAssociation( uint32 itemId, Quest *qst, uint8 item_count);
// Quest Loading
void _RemoveChar(char* c, std::string *str);
void _CleanLine(std::string *str);
};
template<> ARCEMU_INLINE HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* >& QuestMgr::_GetList<Creature>()
{return m_npc_quests;}
template<> ARCEMU_INLINE HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* >& QuestMgr::_GetList<GameObject>()
{return m_obj_quests;}
template<> ARCEMU_INLINE HM_NAMESPACE::hash_map<uint32, list<QuestRelation *>* >& QuestMgr::_GetList<Item>()
{return m_itm_quests;}
#define sQuestMgr QuestMgr::getSingleton()
#endif
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
] | [
[
[
1,
1
],
[
5,
51
],
[
53,
55
],
[
58,
71
],
[
73,
74
],
[
77,
81
],
[
84,
98
],
[
101,
103
],
[
105,
111
],
[
113,
120
],
[
122,
137
],
[
139,
153
],
[
155,
155
],
[
157,
157
],
[
159,
164
]
],
[
[
2,
4
],
[
52,
52
],
[
56,
57
],
[
72,
72
],
[
75,
76
],
[
82,
83
],
[
99,
100
],
[
104,
104
],
[
112,
112
],
[
121,
121
],
[
138,
138
],
[
154,
154
],
[
156,
156
],
[
158,
158
]
]
] |
76085665a8c8a8fbb12ca2ebecb789a99073c1b7 | f9774f8f3c727a0e03c170089096d0118198145e | /传奇mod/Mir2ExCode/Mir2/Sound/MirSound.cpp | 0194611224f775f7b2b7c9b0245ead84ca5722a0 | [] | no_license | sdfwds4/fjljfatchina | 62a3bcf8085f41d632fdf83ab1fc485abd98c445 | 0503d4aa1907cb9cf47d5d0b5c606df07217c8f6 | refs/heads/master | 2021-01-10T04:10:34.432964 | 2010-03-07T09:43:28 | 2010-03-07T09:43:28 | 48,106,882 | 1 | 1 | null | null | null | null | UHC | C++ | false | false | 25,169 | cpp | // MirSound.cpp: implementation of the CMirSound class.
//
//////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#define MAX_KINDS_OF_WAVE 50
//#define MAX_DUPLE_COUNT 5
#define MAX_LIM_TIME 60000
#define MAX_MP3_WAR -1000
#define MAX_MP3_PEACE -100
#define _PI 3.1415927
#define MAKEPOS(a1,a2,a3) {a1.x = a2;a1.y = a3;}
void CALLBACK AmbianceTimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime );
void CALLBACK FadeInTimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime );
void CALLBACK FadeOutTimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime );
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// Name : CMirSound
// Destination : Constructor
//
// Parameter : none
//
// Return Value: void
// Update :
///////////////////////////////////////////////////////////////////////
CMirSound::CMirSound()
{
m_ppWavList = NULL;
m_pWavListHeader = NULL;
m_ppBuffer = NULL;
m_3DEnable = FALSE;
m_bPlay = TRUE;
m_bBGMPlay = TRUE; // 임시
ReadWavFileList("SoundList.wwl");
m_ppBuffer = new CSBuffer*[MAX_KINDS_OF_WAVE];
for(int i = 0 ; i < MAX_KINDS_OF_WAVE ; i++)
{
m_ppBuffer[i] = new CSBuffer;
}
m_pMp3 = new CBMMp3;
m_lWavMaxVol = -100;
m_lMp3MaxVol = -1000;
m_nUseCount = 0;
m_bRunningTimer = FALSE;
m_bIsWarMode = FALSE;
}
///////////////////////////////////////////////////////////////////////
// Name : ~CMirSound
// Destination : Destructor
//
// Parameter : none
//
// Return Value: void
// Update :
///////////////////////////////////////////////////////////////////////
CMirSound::~CMirSound()
{
unsigned int i;
if(m_ppWavList != NULL)
{
for(i=0;i<m_pWavListHeader->FieldCount;i++)
{
delete m_ppWavList[i];
}
delete[] m_ppWavList;
}
if(m_bAmbiance)
{
KillTimer(g_xMainWnd.GetSafehWnd(),ID_AMBIANCE_TIMER);
for(i = 0 ; i < MAX_AMBIANCE_COUNT ; i++)
{
m_pAmbianceBuffer[i]->Release();
delete m_pAmbianceBuffer[i];
}
}
m_CommonWavBuffer.Release();
if(m_ppBuffer!=NULL)
{
for(int j =0;j<m_nUseCount;j++) // Buffer Class
{
m_ppBuffer[j]->Release();
delete m_ppBuffer[j];
}
delete[] m_ppBuffer;
}
if(m_pWavListHeader != NULL) delete m_pWavListHeader;
if(m_pMp3!=NULL) delete m_pMp3;
if(m_pSound!=NULL) delete m_pSound; // Sound Class
}
///////////////////////////////////////////////////////////////////////
// Name : CalsDistance
// Destination : Calculate Distance from User to Sound Source
//
// Parameter : Position Src
// Position Chr
//
// Return Value: int Distance
// Update :
///////////////////////////////////////////////////////////////////////
float CMirSound::CalsDistanceX(POINT Src,POINT Chr) // 소리 발생 위치와 현재 케릭터간의 거리 조사
{
float l_Result;
l_Result = (float)((Chr.x - Src.x)%13); // 거리는 12 이상일수 없다.
l_Result = (float)(1.0-(float)sqrt(1.0 - l_Result/(float)12.0))*((float)-1.0);
return l_Result;
}
float CMirSound::CalsDistanceY(POINT Src,POINT Chr) // 소리 발생 위치와 현재 케릭터간의 거리 조사
{
float l_Result;
l_Result = (float)((Chr.y- Src.y)%13); // 거리는 12 이상일수 없다.
l_Result =float(1.0-(float)sqrt(1.0 - (double)(l_Result)/12.0))*((float)-1.0);
return l_Result;
}
INT CMirSound::CalsDistance(POINT Src,POINT Chr)
{
INT Cx,Cy;
INT nResult;
Cx = Src.x - Chr.x;
Cy = Src.y - Chr.y;
Cx = Cx<0 ? Cx*(-1) : Cx;
Cy = Cy<0 ? Cy*(-1) : Cy;
nResult = Cx >Cy ? Cx : Cy;
return nResult;
}
///////////////////////////////////////////////////////////////////////
// Name : CalsPan
// Destination : Calculate Pans value
//
// Parameter : int Direction
// int Distance
//
// Return Value: int Pans
// Update :
///////////////////////////////////////////////////////////////////////
int CMirSound::CalsPan(int Dir,int Dis)
{
int pans;
pans = Dir*(int)(5000.0*(sin(_PI*(Dis/26.0))));
return pans;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
int CMirSound::CalsVolume(int Dis) // 수정 요망
{
int l_Result;
if(Dis!=0)
{
l_Result = (int)((cos(_PI*(Dis/26.0)))*100);
l_Result = (101 - l_Result); // 최대 볼룸 0 최소 볼륨 (-1)*x : 현제의 100-(x)%
l_Result = m_lWavMaxVol+l_Result*(-20); // 최소음량 -2000 ~ 최대음량 0
return l_Result;
}
else
{
return m_lWavMaxVol; // 겹쳐 져 있거나 본인의 소리 최대 음량으로
}
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
void CMirSound::ReadWavFileList(char* fName)
{
unsigned int i;
int Count;
DWORD dwReadSize;
DWORD dwError;
WAVELIST* l_WavList;
HANDLE hFile = ::CreateFile(fName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL, NULL);
dwError = GetLastError();
if(dwError==ERROR_SUCCESS)
{
// Header Reading
m_pWavListHeader = new WAVELISTHEADER;
ReadFile(hFile,m_pWavListHeader,sizeof(WAVELISTHEADER),&dwReadSize,NULL);
// fclose(hFile);
m_ppWavList = new WAVELIST*[m_pWavListHeader->FieldCount];
// List Reading
Count = 0;
for(i=0;i<m_pWavListHeader->ListCount ; i++)
{
l_WavList = new WAVELIST;
ZeroMemory(l_WavList,sizeof(WAVELIST));
ReadFile(hFile,l_WavList,sizeof(WAVELIST),&dwReadSize,NULL);
if(l_WavList->ID != 0)
{
for(unsigned int j=0; j<strlen(l_WavList->Des);j++)
{
char temp[4];
int cmpResult;
strncpy(temp,l_WavList->Des+j,3);
temp[3] = NULL;
cmpResult = strcmp(temp,"wav");
if(cmpResult==0)
{
*(l_WavList->Des+j+3)=NULL;
}
}
l_WavList->Des;
m_ppWavList[Count] = l_WavList;
Count++;
}
else
{
delete l_WavList;
}
}
CloseHandle(hFile);
}
else
{
m_bPlay = FALSE;
}
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
void CMirSound::PlayMagicEffect(POINT Target, POINT Chr, int Wavnum)
{
if(m_bPlay)
{
FreeNotUseBuffer();
}
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
void CMirSound::PlayAmbianceWav(int WavNum)
{
if(m_bAmbiance)
{
FreeNotUseBuffer();
m_pAmbianceBuffer[WavNum]->SetVolume(m_lWavMaxVol);
m_pAmbianceBuffer[WavNum]->Play(0);
}
}
///////////////////////////////////////////////////////////////////////
// Name : PlayBkMusic
// Destination : Play Wave File with stream
//
// Parameter : bool looped
//
// Return Value: void
// Update :
///////////////////////////////////////////////////////////////////////
void CMirSound::PlayBkMusicMp3(BOOL Looped,INT nIndex)
{
if(m_bBGMPlay)
{
CHAR szMp3FileName[MAX_PATH];
ZeroMemory(szMp3FileName,MAX_PATH);
if(m_pMp3->IsPlaying())
{
// Play중
m_pMp3->OnStop();
}
// FindBGMFileName(nIndex,szMp3FileName);
strcpy(szMp3FileName,"1.mp3"); // 임시
if(szMp3FileName[0]!=NULL)
{
m_pMp3->LoadMp3(szMp3FileName,g_xMainWnd.GetSafehWnd());
m_pMp3->OnPlay(-5000,Looped);
BGMFadeIn();
}
else
{
}
}
}
///////////////////////////////////////////////////////////////////////
// Name : StopBkMusic
// Destination : Stop play BackGround Sound
//
// Parameter : none
//
// Return Value: void
// Update :
///////////////////////////////////////////////////////////////////////
void CMirSound::StopBkMusicMp3(void)
{
BGMFadeOut();
}
///////////////////////////////////////////////////////////////////////
// Name : PlayActorWav
// Destination : Play Wave File with any effect
//
// Parameter : Position Mon
// Position Chr
// int WavNum
//
// Return Value: void
// Update :
///////////////////////////////////////////////////////////////////////
INT CMirSound::PlayActorWav(INT Sx,INT Sy,INT Dx,INT Dy,int Wavnum,INT lVolume,BOOL bLooping)
{
CSBuffer* pBuffer;
char* fname;
POINT Mon,Chr;
INT Dis;
INT Dir;
MAKEPOS(Mon,Sx,Sy);
MAKEPOS(Chr,Dx,Sy);
if(m_bPlay)
{
FreeNotUseBuffer();
fname = SeekFileName(Wavnum);
if(fname != NULL)
{
pBuffer= FindBuffer(Wavnum,TRUE);
if(pBuffer!=NULL)
{
if(m_3DEnable)
{
pBuffer->PlayExtended((float)CalsDistanceX(Mon,Chr),(float)CalsDistanceY(Mon,Chr),(float)0.1,0); // 3D pan
}
else
{
Dis = CalsDistance(Mon,Chr);
Dir = CalsDirection(Mon,Chr);
if(bLooping)
{
pBuffer->PlayExtended(DSBPLAY_LOOPING,CalsPan(Dir,Dis),CalsVolume(Dis),0); // 2D pan
}
else
{
lVolume = CalsVolume(Dis)*((100-lVolume==0)?1:(100-lVolume)/5);
pBuffer->PlayExtended(0,CalsPan(Dir,Dis),lVolume,0); // 2D pan
}
return pBuffer->nBufferIdx;
}
}
}
}
return MAX_DUPLE_COUNT;
}
///////////////////////////////////////////////////////////////////////
// Name : StopAllSound
// Destination : Stop All playing Sound
//
// Parameter : none
//
// Return Value: void
// Update :
///////////////////////////////////////////////////////////////////////
void CMirSound::StopAllSound(void)
{
for(int i = 0;i<m_nUseCount;i++)
{
m_ppBuffer[i]->Stop();
}
}
///////////////////////////////////////////////////////////////////////
// Name : StopSound
// Destination : Stop play Sound
//
// Parameter : int nNum
//
// Return Value: void
// Update :
///////////////////////////////////////////////////////////////////////
void CMirSound::StopSound(int nNum)
{
CSBuffer* pBuffer;
pBuffer = NULL;
pBuffer = FindBuffer(nNum,FALSE);
if(pBuffer != NULL)
pBuffer->Stop();
}
void CMirSound::StopSound(int nNum,int BufIdx)
{
CSBuffer* pBuffer;
pBuffer = NULL;
pBuffer = FindBuffer(nNum,FALSE);
if(pBuffer != NULL)
pBuffer->Stop(BufIdx);
}
///////////////////////////////////////////////////////////////////////
// Name : SeekFileName
// Destination : Find File name with Wave number
//
// Parameter : int wavnum
//
// Return Value: char*
// Update :
///////////////////////////////////////////////////////////////////////
char* CMirSound::SeekFileName(int wavnum)
{
unsigned int i;
if(m_bPlay)
{
for(i=0;i<m_pWavListHeader->FieldCount;i++)
{
if(wavnum == m_ppWavList[i]->ID)
return m_ppWavList[i]->Des;
}
}
return NULL;
}
///////////////////////////////////////////////////////////////////////
// Name : FindBuffer
// Destination :
//
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
CSBuffer* CMirSound::FindBuffer(int nNum,BOOL ForLoad) // 없을때 Load하는 것이면 TRUE 아니면 FASLE
{
if(m_nUseCount>0)
{
for(int i=0 ; i<MAX_KINDS_OF_WAVE;i++)
{
if(m_ppBuffer[i]->m_ID==nNum) // 읽어 놓은 것들중에 있냐?
{
return m_ppBuffer[i];
}
}
}
// 읽어 놓은것중에 없단말이냐?
if(ForLoad)
{
if(m_nUseCount<MAX_KINDS_OF_WAVE)
{
char* fname;
// 그럼 읽자!
fname = SeekFileName(nNum);
if(m_3DEnable) m_ppBuffer[m_nUseCount]->Enable3d();
if(m_ppBuffer[m_nUseCount]->Load(m_pSound,fname,5)!=E_FAIL)
{
m_ppBuffer[m_nUseCount]->m_ID = nNum;
m_nUseCount++;
return m_ppBuffer[m_nUseCount-1];
}
}
else
{ // 헉! 읽을 공간 마저 없단 말이냐?
// 그럼 말자!
return NULL;
}
}
return NULL;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
BOOL CMirSound::InitMirSound(HWND hWnd)
{
if(hWnd != NULL)
{
m_hWnd = hWnd;
m_pSound = new CSound;
m_pSound->Create(m_hWnd,TRUE);
return TRUE;
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
VOID CMirSound::Enable3D(VOID)
{
m_3DEnable = TRUE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
INT CMirSound::CalsDirection(POINT Src,POINT Chr)
{
return Src.x>Chr.x ? 1 :Src.x<Chr.x ?-1:0;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
BOOL CMirSound::FreeNotUseBuffer(VOID)
{
DWORD dwCurrentTime;
DWORD dwTempTime;
CSBuffer* pxTempBuffer;
int i=0;
dwCurrentTime = timeGetTime(); // 현재 시간을 구한다.
do
{
dwTempTime = m_ppBuffer[i]->GetLastUsedTime();
if(dwTempTime!=0)
{
dwTempTime = dwCurrentTime - dwTempTime;
if(dwTempTime > MAX_LIM_TIME) // 1분 이상 안쓴것을 날려라
{
m_ppBuffer[i]->Release();
pxTempBuffer = m_ppBuffer[i];
m_nUseCount--;
for(int j = i; j<m_nUseCount;j++)
{
m_ppBuffer[j] = m_ppBuffer[j+1];
}
m_ppBuffer[m_nUseCount] = pxTempBuffer;
i--;
}
i++;
}
}
while(i<m_nUseCount);
return FALSE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
VOID CMirSound::SetEnableBGM(VOID)
{
m_bBGMPlay = TRUE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
VOID CMirSound::SetDisableBGM(VOID)
{
m_bBGMPlay = FALSE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
VOID CMirSound::SetEnablePlay(VOID)
{
m_bPlay = TRUE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
VOID CMirSound::SetDisablePlay(VOID)
{
m_bPlay = FALSE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
VOID CMirSound::SetDisableAmbiance(VOID)
{
if(m_bAmbiance)
{
m_bAmbiance = FALSE;
for(INT i = 0 ; i < MAX_AMBIANCE_COUNT ; i++)
{
m_pAmbianceBuffer[i]->Release();
delete m_pAmbianceBuffer[i];
}
// m_CommonWavBuffer.Release();
if(m_CommonWavBuffer.Load(m_pSound,"10.wav",1)!=E_FAIL)
{
m_CommonWavBuffer.m_ID = 1;
m_CommonWavBuffer.SetVolume(m_lWavMaxVol);
m_CommonWavBuffer.Play(0);
}
KillTimer(g_xMainWnd.GetSafehWnd(),ID_AMBIANCE_TIMER);
}
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
VOID CMirSound::SetEnableAmbiance(INT nMapNum,INT nCount)
{
CHAR szPname[MAX_PATH];
CHAR szFname[MAX_PATH];
CHAR szTname[MAX_PATH];
if(!m_bAmbiance)
{
m_nAmbienceNum = nMapNum;
m_nAmbianceCount = nCount;
// _itoa(m_nAmbienceNum,szFname,10);
ZeroMemory(szPname,MAX_PATH);
// strcat(szPname,szFname);
if(m_CommonWavBuffer.Load(m_pSound,"00.wav",1)!=E_FAIL) // FadeIn
{
m_CommonWavBuffer.SetVolume(m_lWavMaxVol);
m_CommonWavBuffer.m_ID = 1; // 엠비언스일경우에만 1로 해준다.
m_CommonWavBuffer.Play(0);
}
for(INT i = 0 ; i < MAX_AMBIANCE_COUNT ; i++)
{
_itoa(i,szTname,10);
strcat(szTname,".wav");
strcpy(szFname,szPname);
strcat(szFname,szTname);
m_pAmbianceBuffer[i] = new CSBuffer;
if(m_3DEnable) m_pAmbianceBuffer[i]->Enable3d();
m_pAmbianceBuffer[i]->Load(m_pSound,szFname,2);
m_pAmbianceBuffer[i]->m_ID = 1; // 엠비언스일경우에만 1로 해준다.
}
m_bAmbiance = TRUE;
SetTimer(m_hWnd,ID_AMBIANCE_TIMER,1000,(TIMERPROC)(AmbianceTimerProc));
}
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
BOOL CMirSound::BGMFadeIn(LONG lMaxVol)
{
if(!m_bRunningTimer)
{
if(m_pMp3->IsPlaying())
{
m_lMp3MaxVol = lMaxVol;
SetTimer(m_hWnd,ID_TIMER_1,100,(TIMERPROC)(FadeInTimerProc));
m_bRunningTimer = TRUE;
return TRUE;
}
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
BOOL CMirSound::BGMFadeOut(LONG lTime,LONG lMinVol)
{
if(!m_bRunningTimer)
{
if(m_pMp3->IsPlaying())
{
lTime = (lTime*2)/100;
m_lMp3MaxVol = lMinVol;
SetTimer(m_hWnd,ID_TIMER_1,lTime,(TIMERPROC)(FadeOutTimerProc));
m_bRunningTimer = TRUE;
return TRUE;
}
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
HRESULT CMirSound::MessageProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DSHOW_NOTIFY:
{
m_pMp3->MessageProcess();
break;
}
}
return 0l;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
VOID CMirSound::EndFading(INT nState)
{
if(nState==0)
{
// End of Fade in
KillTimer(g_xMainWnd.GetSafehWnd(),ID_TIMER_1);
//
}
else
{
// End of Fade out
if(m_lMp3MaxVol<=(-5000)) m_pMp3->OnStop();
KillTimer(g_xMainWnd.GetSafehWnd(),ID_TIMER_1);
//
}
m_bRunningTimer = FALSE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
VOID CMirSound::SetInWarMode(VOID)
{
if(!m_bIsWarMode)
{
m_lMp3MaxVol =(-2000);
BGMFadeOut(m_lMp3MaxVol);
m_bIsWarMode = TRUE;
}
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
VOID CMirSound::SetInPeaceMode(VOID)
{
if(m_bIsWarMode)
{
m_lMp3MaxVol =(0);
BGMFadeIn(m_lMp3MaxVol);
m_bIsWarMode = FALSE;
}
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
// MAX = 100 Min = 1
BOOL CMirSound::SetMasterVol(INT nVolume)
{
if(nVolume>=1 && nVolume<=100)
{
m_lWavMaxVol = (nVolume-101)*(50); // 100 -> -50 0 -> -5000
m_lMp3MaxVol = (m_lWavMaxVol-1)*(10); // Wav volume의 -10db
return TRUE;
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
// MAX = 100 Min = 1
BOOL CMirSound::SetBGMVol(INT nVolume)
{
if(nVolume>=0 && nVolume<=100)
{
m_lMp3MaxVol = (m_lWavMaxVol-1)*(10)*(nVolume+1); // Wav volume의 -10dB의 몇%?
return TRUE;
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
BOOL CMirSound::SetWavVol(INT nVolume)
{
return SetMasterVol(nVolume);
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
void CALLBACK FadeInTimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime)
{
LONG lVolume;
lVolume = g_xSound.m_pMp3->GetVolume();
// if End of Fade-out SendMessage to Window WM_USER_ENDTIMER
if(lVolume>=(g_xSound.m_lMp3MaxVol))
SendMessage(g_xMainWnd.GetSafehWnd(),WM_USER_ENDTIMER,(WPARAM)0,NULL);
lVolume = lVolume + 100;
g_xSound.m_pMp3->SetVolume(lVolume);
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
void CALLBACK FadeOutTimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime )
{
LONG lVolume;
lVolume = g_xSound.m_pMp3->GetVolume();
// if End of Fade-out SendMessage to Window WM_USER_ENDTIMER
if(lVolume<(g_xSound.m_lMp3MaxVol))
SendMessage(g_xMainWnd.GetSafehWnd(),WM_USER_ENDTIMER,(WPARAM)1,NULL);
lVolume = lVolume - 100;
g_xSound.m_pMp3->SetVolume(lVolume);
}
///////////////////////////////////////////////////////////////////////
// Name :
// Destination :
//
// Parameter :
//
// Return Value:
// Update :
///////////////////////////////////////////////////////////////////////
void CALLBACK AmbianceTimerProc(HWND hwnd,UINT uMsg,UINT idEvent,DWORD dwTime )
{
static INT nCount = 11;
static INT nReply = 0;
INT nNum;
INT Fact_1,Fact_2;
Fact_1 = (rand())%10+1;
Fact_2 = (rand())%10+1;
nCount++;
if((Fact_1+Fact_2)<=6) // 15%이상의 확률로 Play 1~15% = 15%
nNum = 1;
else
if((Fact_1+Fact_2)<=8) // 28%이상의 확률로 Play 16~28% = 12%
nNum = 2;
else
if((Fact_1+Fact_2)<=10) // 45%이상의 확률로 Play 27~45% = 18%
nNum = 3;
else
if((Fact_1+Fact_2)<=11) // 55%이상의 확률로 Play 46~55% = 10%
nNum = 4;
else
if((Fact_1+Fact_2)<=13) // 72%이상의 확률로 Play 56~72% = 16%
nNum = 5;
else
if((Fact_1+Fact_2)<=16) // 90%이상의 확률로 Play 72~90 = 18%
nNum = 7;
else
nNum = 8; // 10%
if(nCount>=13)
{
nNum = 0;
nCount = 0;
nReply++;
}
if(nNum >= 0 && nNum <= 8)
{
g_xSound.PlayAmbianceWav(nNum); // 원래
}
if(nReply>=g_xSound.m_nAmbianceCount)
{
nReply = 0;
g_xSound.SetDisableAmbiance();
return;
}
}
BOOL CMirSound::ChgPlayingSet(INT nWavIdx,INT nBufferIdx,INT Sx,INT Sy,INT Dx,INT Dy)
{
POINT Mon,Chr;
INT Dis;
INT Dir;
CSBuffer* pBuffer;
MAKEPOS(Mon,Sx,Sy);
MAKEPOS(Chr,Dx,Sy);
pBuffer= FindBuffer(nWavIdx,FALSE);
if(pBuffer!=NULL)
{
Dis = CalsDistance(Mon,Chr);
Dir = CalsDirection(Mon,Chr);
pBuffer->Pause(nBufferIdx);
pBuffer->SetPan(nBufferIdx,CalsPan(Dir,Dis));
pBuffer->SetVolume(nBufferIdx,CalsVolume(Dis));
pBuffer->Continue(nBufferIdx);
return TRUE;
}
else
{
return FALSE;
}
} | [
"fjljfat@4a88d1ba-22b1-11df-8001-4f4b503b426e"
] | [
[
[
1,
1101
]
]
] |
7788fa4113b29005589ff6b38ace5409abe75047 | 85cb4316ad809bca086cc3221946090443c0424c | /Piehelper/PIEHlprObj.h | 0243e6df3a960b7b8e2817d148b80005d823ffc9 | [
"MIT"
] | permissive | AurangZ/windrider | 7f2a5d3ffd1d9e293ab4d1ea093f6d788227adeb | 01f9f7d2361cd8b039e7370b730fb9e17c206c06 | refs/heads/master | 2020-05-18T18:10:44.542729 | 2010-03-11T01:26:24 | 2010-03-11T01:26:24 | 42,451,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,756 | h | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
//
// IEHlprObj.h : Declaration of the CIEHlprObj
#ifndef __IEHLPROBJ_H_
#define __IEHLPROBJ_H_
#include "resource.h" // main symbols
#include "EventsDlg.h"
#ifdef _CE_DCOM
#pragma message ( "The threading model for this object has been set to 'Free' in the .rgs file. Because you are compiling against an SDK which supports DCOM, you may wish to change this." )
#endif
#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)
#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms."
#endif
const UINT ID_BROWSER = 1;
/////////////////////////////////////////////////////////////////////////////
// CIEHlprObj
class ATL_NO_VTABLE CIEHlprObj :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CIEHlprObj, &CLSID_IEHlprObj>,
public IObjectWithSiteImpl<CIEHlprObj>,
public IDispEventSimpleImpl<ID_BROWSER, CIEHlprObj, &DIID_DWebBrowserEvents2>,
public IIEHlprObj
{
public:
DECLARE_REGISTRY_RESOURCEID(IDR_IEHLPROBJ)
DECLARE_NOT_AGGREGATABLE(CIEHlprObj)
BEGIN_COM_MAP(CIEHlprObj)
COM_INTERFACE_ENTRY(IIEHlprObj)
COM_INTERFACE_ENTRY_IMPL(IObjectWithSite)
END_COM_MAP()
// IIEHlprObj
public:
// IOleObjectWithSite
STDMETHOD(SetSite)(IUnknown *pUnkSite);
// Events
public:
BEGIN_SINK_MAP(CIEHlprObj)
SINK_ENTRY_INFO(ID_BROWSER, DIID_DWebBrowserEvents2, DISPID_DOCUMENTCOMPLETE, OnDocumentComplete, &OnDocumentCompleteInfo)
SINK_ENTRY_INFO(ID_BROWSER, DIID_DWebBrowserEvents2, DISPID_TITLECHANGE, OnTitleChange, &OnTitleChangeInfo)
SINK_ENTRY_INFO(ID_BROWSER, DIID_DWebBrowserEvents2, DISPID_BEFORENAVIGATE2, OnBeforeNavigate2, &OnBeforeNavigate2Info)
SINK_ENTRY_INFO(ID_BROWSER, DIID_DWebBrowserEvents2, DISPID_NAVIGATECOMPLETE2, OnNavigateComplete2, &OnNavigateComplete2Info)
END_SINK_MAP()
private:
static _ATL_FUNC_INFO OnDocumentCompleteInfo;
static _ATL_FUNC_INFO OnTitleChangeInfo;
static _ATL_FUNC_INFO OnBeforeNavigate2Info;
static _ATL_FUNC_INFO OnNavigateComplete2Info;
void __stdcall OnDocumentComplete(IDispatch * pDisp, VARIANT * pvtURL);
void __stdcall OnTitleChange(BSTR bstrTitleText);
void __stdcall OnBeforeNavigate2(IDispatch* pDisp,
VARIANT * URL,
VARIANT * pvtFlags,
VARIANT * pvtTargetFrameName,
VARIANT * pvtPostData,
VARIANT * pvtHeaders,
VARIANT_BOOL * pvbCancel);
void __stdcall OnNavigateComplete2(IDispatch * pDisp, VARIANT * pvtURL);
private:
CEventsDlg m_dlgEvents;
CComQIPtr<IWebBrowser2, &__uuidof(IWebBrowser2)> m_spWebBrowser2;
};
OBJECT_ENTRY_AUTO(__uuidof(IEHlprObj), CIEHlprObj)
#endif //__IEHLPROBJ_H_
| [
"ionut.trestian@ee5ef0fc-2c67-11df-b580-1f2e1e9a714e"
] | [
[
[
1,
85
]
]
] |
6b20473565f414c7fbe0b56020b414fc0a11966e | bf9ca8636584e8112c392d6ca5cd85b6be4f6ebf | /src/Bucket.h | 90e0127d47c7497031f64d559bf832b98f5f3c29 | [] | no_license | RileyA/LD19_Aquatic | 34e8e08a450ee9f53365d98ebef505341869dfb5 | c30e1f8e3304428e7077cb2042b4169450a35db9 | refs/heads/master | 2020-05-18T08:49:05.084811 | 2011-02-17T07:36:14 | 2011-02-17T07:36:14 | 1,377,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 746 | h | #ifndef BUCKET_H
#define BUCKET_H
#include "stdafx.h"
#include "GameObject.h"
class Bucket
{
public:
Bucket(String name)
{
mName = name;
}
~Bucket()
{
std::map<String,GameObject*>::iterator i = mObjects.begin();
for(i;i!=mObjects.end();++i)
delete i->second;
}
void update(Real delta)
{
std::map<String,GameObject*>::iterator i = mObjects.begin();
for(i;i!=mObjects.end();++i)
i->second->update(delta);
}
void pushObject(GameObject* obj,String name)
{
mObjects[name] = obj;
}
GameObject* getObject(String name)
{
if(mObjects.find(name)==mObjects.end())
return 0;
return mObjects[name];
}
String mName;
std::map<String,GameObject*> mObjects;
};
#endif | [
"[email protected]"
] | [
[
[
1,
46
]
]
] |
83b581badf1c0880413853f1bedbdb5fc14a4d97 | 0b79fbac1b2e0816e3923b30393cf3db3afbf821 | /omap3530/beagle_drivers/medstaticrd/beagle_medstaticrd.cpp | 03dd286724e11e4fa6ef13350881ab8bb79fc22d | [] | no_license | SymbianSource/oss.FCL.sf.adapt.beagleboard | d8f378ffff2092cd3f9826c2e1db32e5b59b76d1 | bc11555ace01edea88f2ed753d4938fae4c61295 | refs/heads/master | 2020-12-25T14:22:54.807108 | 2010-11-29T13:27:18 | 2010-11-29T13:27:18 | 65,622,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,833 | cpp | /*
* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - contribution.
*
* Contributors:
* Gareth Long - Symbian Foundation
*
* Description: Minimalistic non volatile memory driver
*
*/
#include "locmedia.h"
#include "platform.h"
#include "variantmediadef.h"
#include "beagle_medstaticrd.h"
//#include "syborg.h"
#define NVMEM1_DRIVENAME "STATICRD"
#define NVMEM1_DRIVECOUNT 1
#define NVMEM1_DRIVELIST 1
#define NVMEM1_NUMMEDIA 1
_LIT(KNVMemPddName, "Media.MEDTATICRD");
_LIT(KNVMemDriveName,NVMEM1_DRIVENAME);
class DPhysicalDeviceMediaStaticRD : public DPhysicalDevice
{
public:
DPhysicalDeviceMediaStaticRD();
public:
// Implementing the interface
virtual TInt Install();
virtual void GetCaps(TDes8& aDes) const;
virtual TInt Create(DBase*& aChannel, TInt aMediaId, const TDesC8* anInfo, const TVersion& aVer);
virtual TInt Validate(TInt aDeviceType, const TDesC8* anInfo, const TVersion& aVer);
virtual TInt Info(TInt aFunction, TAny* a1);
};
class DMediaDriverStaticRD : public DMediaDriver
{
public:
DMediaDriverStaticRD(TInt aMediaId);
public:
// Implementing the interface
virtual TInt Request(TLocDrvRequest& aRequest);
virtual void Disconnect(DLocalDrive* aLocalDrive, TThreadMessage* aMsg);
virtual TInt PartitionInfo(TPartitionInfo &anInfo);
virtual void NotifyPowerDown();
virtual void NotifyEmergencyPowerDown();
public:
void CompleteRequest(TInt aReason);
TInt DoCreate(TInt aMediaId);
TInt Caps(TLocDrvRequest& aRequest);
TInt Read();
TInt Write();
TInt Format();
static void TransactionLaunchDfc(TAny* aMediaDriver);
void DoTransactionLaunchDfc();
static void SessionEndDfc(TAny* aMediaDriver);
void DoSessionEndDfc();
TUint32 GetNVMemSize( void );
public:
TUint32 iLatestTransferSectorCount;
TDfc iSessionEndDfc;
private:
TInt ContinueTransaction( TUint32 aTransactionSectorOffset, TUint32 aTransactionSectorCount, TUint32 aDirection );
static void Isr(TAny* aPtr);
private:
TLocDrvRequest* iCurrentRequest; // Current Request
Int64 iTotalLength;
Int64 iProsessedLength;
Int64 iPos;
TPhysAddr iTransferBufferPhys;
TUint8* iTransferBufferLin;
TUint8* iDiscBufferLin;
TUint32 iHead;
TUint32 iTail;
TUint32 iSplitted;
TUint32 iAlignmentOverhead;
TBool iReadModifyWrite;
TDfc iTransactionLaunchDfc;
};
DPhysicalDeviceMediaStaticRD::DPhysicalDeviceMediaStaticRD()
//
// Constructor
//
{
__DEBUG_PRINT(">DPhysicalDeviceMediaStaticRD::DPhysicalDeviceMediaStaticRD");
iUnitsMask=0x1;
iVersion=TVersion(KMediaDriverInterfaceMajorVersion,KMediaDriverInterfaceMinorVersion,KMediaDriverInterfaceBuildVersion);
}
TInt DPhysicalDeviceMediaStaticRD::Install()
//
// Install the Internal NVMem PDD.
//
{
__DEBUG_PRINT("DPhysicalDeviceMediaStaticRD::Install()");
return SetName(&KNVMemPddName);
}
void DPhysicalDeviceMediaStaticRD::GetCaps(TDes8& /*aDes*/) const
//
// Return the media drivers capabilities.
//
{
__DEBUG_PRINT("DPhysicalDeviceMediaStaticRD::GetCaps()");
}
TInt DPhysicalDeviceMediaStaticRD::Create(DBase*& aChannel, TInt aMediaId, const TDesC8* /* anInfo */,const TVersion &aVer)
//
// Create an Internal Ram media driver.
//
{
__DEBUG_PRINT("DPhysicalDeviceMediaStaticRD::Create()");
if (!Kern::QueryVersionSupported(iVersion,aVer))
return KErrNotSupported;
TInt r=KErrNoMemory;
DMediaDriverStaticRD* pD=new DMediaDriverStaticRD(aMediaId);
aChannel=pD;
if (pD)
{
r=pD->DoCreate(aMediaId);
}
if( r==KErrNone )
{
pD->OpenMediaDriverComplete(KErrNone);
}
return r;
}
TInt DPhysicalDeviceMediaStaticRD::Validate(TInt aDeviceType, const TDesC8* /*anInfo*/, const TVersion& aVer)
{
__DEBUG_PRINT("DPhysicalDeviceMediaStaticRD::Validate()");
if (!Kern::QueryVersionSupported(iVersion,aVer))
return KErrNotSupported;
if (aDeviceType!=EFixedMedia1)
return KErrNotSupported;
return KErrNone;
}
TInt DPhysicalDeviceMediaStaticRD::Info(TInt aFunction, TAny*)
//
// Return the priority of this media driver
//
{
__DEBUG_PRINT("DPhysicalDeviceMediaStaticRD::Info()");
if (aFunction==EPriority)
return KMediaDriverPriorityNormal;
return KErrNotSupported;
}
DMediaDriverStaticRD::DMediaDriverStaticRD(TInt aMediaId)
//
// Constructor.
//
: DMediaDriver(aMediaId),
iSessionEndDfc(DMediaDriverStaticRD::SessionEndDfc, this, 1),
iTransferBufferPhys(0),
iTransactionLaunchDfc(DMediaDriverStaticRD::TransactionLaunchDfc, this, KMaxDfcPriority)
{
__DEBUG_PRINT("DMediaDriverStaticRD::DMediaDriverStaticRD()");
}
TInt DMediaDriverStaticRD::DoCreate(TInt /*aMediaId*/)
//
// Create the media driver.
//
{
__DEBUG_PRINT(">DMediaDriverStaticRD::DoCreate");
TInt r = KErrNone;
// Inform our size
Int64 size=GetNVMemSize()<<KDiskSectorShift;
if( size<=0 )
{
Kern::Fault("DMediaDriverStaticRD zero size nv memory array", 0);
}
SetTotalSizeInBytes(size);
// Some dfc initialization
if( r==KErrNone )
{
iSessionEndDfc.SetDfcQ( this->iPrimaryMedia->iDfcQ );
iTransactionLaunchDfc.SetDfcQ( this->iPrimaryMedia->iDfcQ );
}
// Create our piece of physically contiguous transfer buffer.
r = Epoc::AllocPhysicalRam( KNVMemTransferBufferSize, iTransferBufferPhys );
if( r != KErrNone )
{
Kern::Fault("DMediaDriverStaticRD Allocate Ram %d",r);
}
DPlatChunkHw* bufChunk = NULL;
DPlatChunkHw* bufChunk2 = NULL;
// Create HW Memory Chunk
r = DPlatChunkHw::New( bufChunk, iTransferBufferPhys, KNVMemTransferBufferSize, EMapAttrUserRw | EMapAttrFullyBlocking );
if( r != KErrNone )
{
// Check Physical Memory
if( iTransferBufferPhys )
{
// Free Physical Memory
Epoc::FreePhysicalRam( iTransferBufferPhys, KNVMemTransferBufferSize );
}
Kern::Fault("DMediaDriverStaticRD error in creating transfer buffer", r);
}
// Set Main Buffer Pointer
iTransferBufferLin = reinterpret_cast<TUint8*>(bufChunk->LinearAddress());
// Create HW Memory Chunk for drive image
r = DPlatChunkHw::New( bufChunk2, 0x81000000, 0x1000000, EMapAttrUserRw | EMapAttrFullyBlocking );
if( r != KErrNone )
{
Kern::Fault("DMediaDriverStaticRD error in creating disc image linear address", r);
}
// Set Main Buffer Pointer
iDiscBufferLin = reinterpret_cast<TUint8*>(bufChunk2->LinearAddress());
// Inform "hardware" about the shared memory
//WriteReg( KHwNVMemoryDevice, R_NVMEM_SHARED_MEMORY_BASE, iTransferBufferPhys );
//WriteReg( KHwNVMemoryDevice, R_NVMEM_SHARED_MEMORY_SIZE, KNVMemTransferBufferSize );
//WriteReg( KHwNVMemoryDevice, R_NVMEM_ENABLE, 1 );
// Set up interrupt service
//r = Interrupt::Bind( EIntNVMemoryDevice, Isr, this );
//Interrupt::Enable( EIntNVMemoryDevice );
__DEBUG_PRINT("<DMediaDriverStaticRD::DoCreate %d", r);
return(r);
}
TInt DMediaDriverStaticRD::Request(TLocDrvRequest& m)
{
TInt request=m.Id();
__DEBUG_PRINT(">DMediaDriverStaticRD::Request %d",request);
TInt r=KErrNone;
// Requests that can be handled synchronously
if( request == DLocalDrive::ECaps )
{
r=Caps(m);
return r;
}
// All other requests must be deferred if a request is currently in progress
if (iCurrentRequest)
{
// a request is already in progress, so hold on to this one
r = KMediaDriverDeferRequest;
}
else
{
iCurrentRequest=&m;
iProsessedLength = 0;
iHead = 0;
iTail = 0;
iSplitted = 0;
iAlignmentOverhead = 0;
iPos = m.Pos();
iTotalLength = m.Length();
__DEBUG_PRINT(">DMediaDriverStaticRD::Request pos:0x%lx len:0x%lx", iPos, iTotalLength);
if( iTotalLength<0 || iPos<0 )
{
Kern::Fault("DMediaDriverStaticRD::Request: illegal access!", 0);
}
// Handle unaligned operations
iHead = iPos % KDiskSectorSize;
TUint32 tailAlignment = ((iHead + iTotalLength) % KDiskSectorSize);
if( tailAlignment )
{
iTail = KDiskSectorSize - tailAlignment;
}
iSplitted = (iTotalLength + iHead + iTail) / KNVMemTransferBufferSize;
__DEBUG_PRINT(">DMediaDriverStaticRD::Request head: %d tail: %d splitted: %d\n", iHead, iTail, iSplitted );
__DEBUG_PRINT(">DMediaDriverStaticRD::Request partitionlen: %lx", iCurrentRequest->Drive()->iPartitionLen );
if( (iTotalLength + iPos) > iCurrentRequest->Drive()->iPartitionLen )
{
Kern::Fault("DMediaDriverStaticRD::Request: Access over partition boundary!", 0);
}
if( iTotalLength > KMaxTInt32 )
{
Kern::Fault("DMediaDriverStaticRD::Request: Access length overflow!", 0);
}
switch (request)
{
case DLocalDrive::ERead:
case DLocalDrive::EWrite:
case DLocalDrive::EFormat:
__DEBUG_PRINT("DMediaDriverStaticRD::Request iTransactionLaunchDfc.Enque()>");
iTransactionLaunchDfc.Enque();
__DEBUG_PRINT("DMediaDriverStaticRD::Request iTransactionLaunchDfc.Enque()<");
break;
case DLocalDrive::EEnlarge:
case DLocalDrive::EReduce:
default:
r=KErrNotSupported;
break;
}
}
__DEBUG_PRINT("<DMediaDriverStaticRD::Request %d",r);
return r;
}
void DMediaDriverStaticRD::CompleteRequest(TInt aReason)
//
// completes the request which is being currently processed
//
{
__DEBUG_PRINT("DMediaDriverStaticRD::CompleteRequest() reason: %d", aReason);
TLocDrvRequest* pR=iCurrentRequest;
if (pR)
{
iCurrentRequest=NULL;
DMediaDriver::Complete(*pR,aReason);
}
}
void DMediaDriverStaticRD::Disconnect( DLocalDrive* aLocalDrive, TThreadMessage* aMsg )
{
__DEBUG_PRINT(">DMediaDriverStaticRD::Disconnect()");
// Complete using the default implementation
DMediaDriver::Disconnect(aLocalDrive, aMsg);
__DEBUG_PRINT("<DMediaDriverStaticRD::Disconnect()");
}
void DMediaDriverStaticRD::NotifyPowerDown()
{
__DEBUG_PRINT("DMediaDriverStaticRD::NotifyPowerDown()");
// no action required
}
void DMediaDriverStaticRD::NotifyEmergencyPowerDown()
{
__DEBUG_PRINT("DMediaDriverStaticRD::NotifyEmergencyPowerDown()");
// no action required
}
TInt DMediaDriverStaticRD::Caps(TLocDrvRequest& m)
{
__DEBUG_PRINT("DMediaDriverStaticRD::Caps()");
TLocalDriveCapsV6& caps=*(TLocalDriveCapsV6*)m.RemoteDes();
caps.iType=EMediaHardDisk;
caps.iConnectionBusType=EConnectionBusInternal;
caps.iDriveAtt=KDriveAttLocal|KDriveAttInternal;
caps.iMediaAtt=KMediaAttFormattable;
caps.iFileSystemId=KDriveFileSysFAT;
caps.iPartitionType=KPartitionTypeFAT16;
caps.iSize=m.Drive()->iPartitionLen;
caps.iHiddenSectors=0;
caps.iEraseBlockSize = KNVMemTransferBufferSize;
caps.iBlockSize=KDiskSectorSize;
caps.iMaxBytesPerFormat = KNVMemTransferBufferSize;
return KErrCompletion;
}
TInt DMediaDriverStaticRD::Read()
{
__DEBUG_PRINT(">DMediaDriverStaticRD::Read() pos: %lx, size: %lx", iPos, iTotalLength);
// Set our sector offset
TUint32 transactionSectorOffset = (TUint32)(iPos / KDiskSectorSize);
TUint32 transactionLength = 0;
TUint32 transactionDirection = NVMEM_TRANSACTION_READ;
// Do we have an operation longer than our shared memory?
if( iSplitted > 0 )
{
transactionLength = KNVMemTransferBufferSize;
}
else
{
// Do the whole operation in one go since we have enough room in our memory
transactionLength = I64LOW(iTotalLength);
// Read the "broken" tail sector
if( iTail )
{
transactionLength += iTail;
iAlignmentOverhead += iTail;
}
}
// Read the "broken" head sector
if( iHead > 0 )
{
transactionLength += iHead;
iAlignmentOverhead += iHead;
}
// We should be ok to continue
ContinueTransaction( transactionSectorOffset, transactionLength/KDiskSectorSize, transactionDirection );
__DEBUG_PRINT("<DMediaDriverStaticRD::Read()");
return KErrNone;
}
TInt DMediaDriverStaticRD::Write()
{
__DEBUG_PRINT("DMediaDriverStaticRD::Write() pos: 0x%lx, size: 0x%lx", iPos, iTotalLength);
TInt r = KErrNone;
// Set our sector offset
TUint32 transactionSectorOffset = (TUint32)(iPos / KDiskSectorSize);
TUint32 transactionLength = 0;
TUint32 transactionDirection = NVMEM_TRANSACTION_WRITE;
// Do we have an operation longer than our shared memory?
if( iSplitted > 0 )
{
transactionLength = KNVMemTransferBufferSize;
}
else
{
// Do the whole operation in one go since we have enough room in our memory
transactionLength = I64LOW(iTotalLength);
if( iTail )
{
iReadModifyWrite = ETrue;
// Read the "broken" tail sector
transactionLength += iTail;
iAlignmentOverhead += iTail;
}
}
// Is there a need to read modify write the "broken" head sector of the operation
if( iHead > 0 )
{
iReadModifyWrite = ETrue;
// If splitted operation we only need the broken sector
if( iSplitted > 0 )
{
transactionLength = KDiskSectorSize;
iAlignmentOverhead += iHead;
}
else
{
// Read the "broken" head sector in addition to everything else
transactionLength += iHead;
iAlignmentOverhead += iHead;
}
}
// Was there a need to read-modify before writing
if( iReadModifyWrite )
{
transactionDirection = NVMEM_TRANSACTION_READ;
}
else
{
// Handle format here
if( iCurrentRequest->Id() == DLocalDrive::EFormat )
{
// Not much handling just flow through since we have filled the shared memory with zeroes already
}
else
{
// Read from client
TPtr8 targetDescriptor(iTransferBufferLin, transactionLength);
r = iCurrentRequest->ReadRemote(&targetDescriptor,0);
}
}
// We should be ok to continue
ContinueTransaction( transactionSectorOffset, transactionLength/KDiskSectorSize, transactionDirection );
return r;
}
TInt DMediaDriverStaticRD::Format()
{
__DEBUG_PRINT("DMediaDriverStaticRD::Format() pos: 0x%lx, size: 0x%lx", iPos, iTotalLength);
memset( iTransferBufferLin, 0x00, KNVMemTransferBufferSize );
// Stop the nonsense here. Write operations should be used for partial sector data removal operations
if( iHead > 0 || iTail > 0 )
{
Kern::Fault("DMediaDriverStaticRD::Format: alignment violation!", 0);
}
Write();
// DoTransaction( m, NVMEM_TRANSACTION_WRITE );
return KErrNone;
}
TInt DMediaDriverStaticRD::ContinueTransaction( TUint32 aTransactionSectorOffset, TUint32 aTransactionSectorCount, TUint32 aTransactionDirection )
{
__DEBUG_PRINT("DMediaDriverStaticRD::ContinueTransaction() sectoroffset: %d, sectorcount: %d, direction: %d", aTransactionSectorOffset, aTransactionSectorCount, aTransactionDirection);
if( aTransactionDirection != NVMEM_TRANSACTION_UNDEFINED )
{
//WriteReg( KHwNVMemoryDevice, R_NVMEM_TRANSACTION_OFFSET, aTransactionSectorOffset );
//WriteReg( KHwNVMemoryDevice, R_NVMEM_TRANSACTION_SIZE, aTransactionSectorCount );
//WriteReg( KHwNVMemoryDevice, R_NVMEM_TRANSACTION_DIRECTION, aTransactionDirection );
//WriteReg( KHwNVMemoryDevice, R_NVMEM_TRANSACTION_EXECUTE, aTransactionDirection );
if ( aTransactionDirection == NVMEM_TRANSACTION_WRITE )
{
memcpy( (TAny *)(iDiscBufferLin+(aTransactionSectorOffset<<9)), iTransferBufferLin, aTransactionSectorCount*512 );
}
else if ( aTransactionDirection == NVMEM_TRANSACTION_READ )
{
memcpy( iTransferBufferLin, (TAny *)(iDiscBufferLin+(aTransactionSectorOffset<<9)), aTransactionSectorCount*512 );
}
iLatestTransferSectorCount = aTransactionSectorCount;
// Isr(this); // terrible hack, we've yransferred all the sectors and now we pretend to generate an interrupt
iSessionEndDfc.Enque();
}
else
{
Kern::Fault("DMediaDriverStaticRD::ContinueTransaction: Undefined transaction!", 0);
}
return KErrNone;
}
TInt DMediaDriverStaticRD::PartitionInfo(TPartitionInfo& anInfo)
//
// Return partition information on the media.
//
{
__DEBUG_PRINT("DMediaDriverStaticRD::PartitionInfo()");
anInfo.iPartitionCount=1;
anInfo.iEntry[0].iPartitionBaseAddr=0;
anInfo.iEntry[0].iPartitionLen=anInfo.iMediaSizeInBytes=TotalSizeInBytes();
anInfo.iEntry[0].iPartitionType=KPartitionTypeFAT16;
return KErrCompletion;
}
void DMediaDriverStaticRD::TransactionLaunchDfc(TAny* aMediaDriver)
{
static_cast<DMediaDriverStaticRD*>(aMediaDriver)->DoTransactionLaunchDfc();
}
void DMediaDriverStaticRD::DoTransactionLaunchDfc()
{
__DEBUG_PRINT(">DMediaDriverStaticRD::DoTransactionLaunchDfc()");
TInt request = iCurrentRequest->Id();
TInt r(KErrNone);
switch (request)
{
case DLocalDrive::ERead:
r=Read();
break;
case DLocalDrive::EWrite:
r=Write();
break;
case DLocalDrive::EFormat:
r=Format();
break;
case DLocalDrive::EEnlarge:
case DLocalDrive::EReduce:
default:
r=KErrNotSupported;
break;
}
if( r != KErrNone )
{
// TODO some proper error handling here
}
__DEBUG_PRINT("<MediaDriverStaticRD::DoTransactionLaunchDfc %d",r);
}
void DMediaDriverStaticRD::SessionEndDfc(TAny* aMediaDriver)
{
static_cast<DMediaDriverStaticRD*>(aMediaDriver)->DoSessionEndDfc();
}
void DMediaDriverStaticRD::DoSessionEndDfc()
{
__DEBUG_PRINT(">DMediaDriverStaticRD::DoSessionEndDfc()");
TInt r = KErrNone;
// Check that we have a request in process
if( iCurrentRequest )
{
// Transaction variables
TUint32 transactionSectorOffset(0);
TUint32 transactionLength(0);
TUint32 transactionDirection( NVMEM_TRANSACTION_UNDEFINED );
// How much did we actually transfer?
TUint32 latestTransferSize = (iLatestTransferSectorCount * KDiskSectorSize);
__DEBUG_PRINT("DMediaDriverStaticRD::DoSessionEndDfc() latestTransferSize: %d", latestTransferSize );
// Subtract alignment overhead
latestTransferSize = latestTransferSize - iAlignmentOverhead;
// For decision whether the buffer is ready for operation already
TBool bufferReady(EFalse);
// For decision whether we have finished the latest request
TBool sessionComplete(EFalse);
// Was there a read-modify-write (RWM) for which we need to do some buffer manipulation before proceeding?
// Note that in case of format we triggered to alignment violation in earlier method already and can not enter to following
// condition when there is a format operation going on
if( iReadModifyWrite )
{
bufferReady = ETrue;
iReadModifyWrite = EFalse;
// Was it a splitted operation for which we only need to take care of the broken head sector.
if( iSplitted > 0 )
{
// We have a sector here here filled with data from mass memory. Modify with client data.
__DEBUG_PRINT("DMediaDriverStaticRD::DoSessionEndDfc() readremote splitted: %d head: %d", latestTransferSize, iHead );
TPtr8 targetDescriptor(&iTransferBufferLin[iHead], KNVMemTransferBufferSize - iHead);
r = iCurrentRequest->ReadRemote(&targetDescriptor,0);
}
// Else we need to take care of both head and tail
else
{
// We have a piece of data read from mass memory. Modify with client data.
__DEBUG_PRINT("DMediaDriverStaticRD::DoSessionEndDfc() readremote: %d head: %d", I64LOW(iTotalLength - iProsessedLength), iHead );
TPtr8 targetDescriptor(&iTransferBufferLin[iHead], I64LOW(iTotalLength - iProsessedLength));
r = iCurrentRequest->ReadRemote(&targetDescriptor,0);
// latestTransferSize -= (KDiskSectorSize - iTail);
iTail = 0;
}
}
else
{
// Overhead is processed when we enter here
iAlignmentOverhead = 0;
// Update position
iPos += latestTransferSize;
// Save the information on how many bytes we transferred already
iProsessedLength += latestTransferSize;
// Update the splitted information. We don't take head into account here anymore since it is already taken care of
iSplitted = (iTotalLength - iProsessedLength + iTail) / KNVMemTransferBufferSize;
// Check if we have done already
if( iProsessedLength >= iTotalLength )
{
// If this was the final transfer for this request let's take tail into account as well (if not taken already)
// iProsessedLength -= iTail;
// latestTransferSize -= iTail;
if( iProsessedLength > iTotalLength )
{
Kern::Fault("DMediaDriverStaticRD: Illegal transfer operation!", 0);
}
sessionComplete = ETrue;
}
}
TInt request = iCurrentRequest->Id();
// Set our sector offset
transactionSectorOffset = (TUint32)(iPos / KDiskSectorSize);
if( bufferReady )
{
// Write as much as we read in RMW operation
transactionLength = (iLatestTransferSectorCount * KDiskSectorSize);
}
else
{
// Do we have an operation longer than our shared memory?
if( iSplitted > 0 )
{
transactionLength = KNVMemTransferBufferSize;
}
else
{
// Do the whole operation in one go since we have enough room in our memory
transactionLength = I64LOW(iTotalLength - iProsessedLength);
// Read the "broken" tail sector
if( iTail > 0 && request == DLocalDrive::EWrite )
{
iReadModifyWrite = ETrue;
// Read the "broken" tail sector
transactionLength += iTail;
iAlignmentOverhead = iTail;
}
}
}
// Was there a need to read-modify before writing
if( iReadModifyWrite )
{
transactionDirection = NVMEM_TRANSACTION_READ;
}
else
{
if( request == DLocalDrive::ERead )
{
transactionDirection = NVMEM_TRANSACTION_READ;
// Write to client
__DEBUG_PRINT("DMediaDriverStaticRD::DoSessionEndDfc() WriteRemote: %d head: %d", latestTransferSize, iHead );
TPtrC8 sourceDescriptor(&iTransferBufferLin[iHead], latestTransferSize);
r = iCurrentRequest->WriteRemote( &sourceDescriptor, 0 );
}
// Head is processed
iHead = 0;
if( request == DLocalDrive::EWrite && !sessionComplete )
{
transactionDirection = NVMEM_TRANSACTION_WRITE;
if( bufferReady )
{
// Actually no need for any actions here
}
else
{
// Prepare a buffer for transfer
__DEBUG_PRINT("DMediaDriverStaticRD::DoSessionEndDfc() ReadRemote: %d head: %d", latestTransferSize, iHead );
TPtr8 targetDescriptor(iTransferBufferLin, transactionLength);
r = iCurrentRequest->ReadRemote(&targetDescriptor,0);
}
}
if( request == DLocalDrive::EFormat )
{
transactionDirection = NVMEM_TRANSACTION_WRITE;
}
}
if( sessionComplete )
{
CompleteRequest( r );
}
else
{
ContinueTransaction( transactionSectorOffset, transactionLength/KDiskSectorSize, transactionDirection );
}
}
else
{
// Let's just flow through for now
}
__DEBUG_PRINT("<DMediaDriverStaticRD::DoSessionEndDfc()" );
}
TUint32 DMediaDriverStaticRD::GetNVMemSize( void )
{
__DEBUG_PRINT("DMediaDriverStaticRD::GetNVMemSize()");
TUint32 sizeInSectors = 32768;//ReadReg( KHwNVMemoryDevice, R_NVMEM_NV_MEMORY_SIZE );
return sizeInSectors;
}
void DMediaDriverStaticRD::Isr(TAny* aPtr)
{
__DEBUG_PRINT(">DMediaDriverStaticRD::Isr");
DMediaDriverStaticRD* nvMem = reinterpret_cast<DMediaDriverStaticRD*>(aPtr);
// Save the amount of transferred sectors. This clears the interrupt from HW as well
//nvMem->iLatestTransferSectorCount = ReadReg( KHwNVMemoryDevice, R_NVMEM_STATUS );
// Clear from framework
//Interrupt::Clear( EIntNVMemoryDevice );
nvMem->iSessionEndDfc.Add();
}
DECLARE_EXTENSION_PDD()
{
__DEBUG_PRINT(">MediaDriverStaticRD create device");
return new DPhysicalDeviceMediaStaticRD;
}
static const TInt NVMemDriveNumbers[NVMEM1_DRIVECOUNT]={NVMEM1_DRIVELIST};
DECLARE_STANDARD_EXTENSION()
{
__DEBUG_PRINT("Registering STATICRD drive");
TInt r=KErrNoMemory;
DPrimaryMediaBase* pM=new DPrimaryMediaBase;
TDynamicDfcQue* NVMemoryDfcQ;
r = Kern::DynamicDfcQCreate( NVMemoryDfcQ, KNVMemDfcThreadPriority, KNVMemDriveName );
if( r == KErrNone )
{
pM->iDfcQ = NVMemoryDfcQ;
}
else
{
__DEBUG_PRINT("NVMEM DFCQ initialization failed");
}
if (pM)
{
r=LocDrv::RegisterMediaDevice(EFixedMedia1,NVMEM1_DRIVECOUNT,&NVMemDriveNumbers[0],pM,NVMEM1_NUMMEDIA,KNVMemDriveName);
}
pM->iMsgQ.Receive();
__DEBUG_PRINT("Registering NVMEM drive - return %d",r);
return r;
}
| [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
21
],
[
23,
524
],
[
528,
809
]
],
[
[
22,
22
]
],
[
[
525,
527
]
]
] |
3516df7bdd6d41404b6f629003a3d7ee154123e5 | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Common/Base/Types/Geometry/Aabb/hkAabb.inl | 1d181e882b96ddd1b29d42d335f89d3ecfc51f5a | [] | no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,323 | inl | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
inline hkAabb::hkAabb(const hkVector4& min, const hkVector4& max)
: m_min(min), m_max(max)
{
}
hkBool hkAabb::overlaps( const hkAabb& other ) const
{
HK_ASSERT2(0x3f5578fc, isValid(), "Invalid aabb in hkAabb::overlaps." );
HK_ASSERT2(0x76dd800a, other.isValid(), "Invalid aabb in hkAabb::overlaps.");
hkVector4Comparison mincomp = m_min.compareLessThanEqual4(other.m_max);
hkVector4Comparison maxcomp = other.m_min.compareLessThanEqual4(m_max);
hkVector4Comparison both; both.setAnd( mincomp, maxcomp );
return both.allAreSet(hkVector4Comparison::MASK_XYZ) != 0;
}
hkBool hkAabb::contains(const hkAabb& other) const
{
hkVector4Comparison mincomp = m_min.compareLessThanEqual4(other.m_min);
hkVector4Comparison maxcomp = other.m_max.compareLessThanEqual4(m_max);
hkVector4Comparison both; both.setAnd( mincomp, maxcomp );
return both.allAreSet(hkVector4Comparison::MASK_XYZ) != 0;
}
hkBool hkAabb::containsPoint(const hkVector4& other) const
{
hkVector4Comparison mincomp = m_min.compareLessThanEqual4(other);
hkVector4Comparison maxcomp = other.compareLessThanEqual4(m_max);
hkVector4Comparison both; both.setAnd( mincomp, maxcomp );
return both.allAreSet(hkVector4Comparison::MASK_XYZ) != 0;
}
void hkAabb::includePoint (const hkVector4& point)
{
m_min.setMin4(m_min, point);
m_max.setMax4(m_max, point);
}
void hkAabb::setEmpty()
{
m_min.setAll(HK_REAL_MAX);
#if !defined(HK_PLATFORM_SPU)
m_max.setAll(-HK_REAL_MAX);
#else
m_max.setNeg4( m_min );
#endif
}
inline void hkAabbUint32::setInvalid()
{
const int ma = 0x7fffffff;
// SNC warning workaround
hkUint32* minP = m_min;
hkUint32* maxP = m_max;
minP[0] = ma;
minP[1] = ma;
minP[2] = ma;
minP[3] = 0;
maxP[0] = 0;
maxP[1] = 0;
maxP[2] = 0;
maxP[3] = 0;
}
inline void hkAabbUint32::setInvalidY()
{
const int ma = 0x7fff0000;
hkUint32* minP = m_min;
hkUint32* maxP = m_max;
minP[1] = ma;
minP[2] = ma;
minP[3] = 0;
maxP[1] = 0;
maxP[2] = 0;
}
void hkAabbUint32::operator=( const hkAabbUint32& other )
{
hkString::memCpy16<sizeof(hkAabbUint32)>( this, &other );
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] | [
[
[
1,
106
]
]
] |
20f180e04c91e445eca3546f7a55e410e99bf543 | f177993b13e97f9fecfc0e751602153824dfef7e | /ImProSln/MyLib/LEADTOOL/Include/Filters/ILEncCMW3.h | 399bad2630025e8a79b38294a68770bccc9d1a5f | [] | no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,634 | h |
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 7.00.0500 */
/* at Thu Nov 05 12:44:01 2009
*/
/* Compiler settings for .\ILEncCMW2.idl:
Oicf, W1, Zp8, env=Win32 (32b run)
protocol : dce , ms_ext, c_ext, robust
error checks: allocation ref bounds_check enum stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
//@@MIDL_FILE_HEADING( )
#pragma warning( disable: 4049 ) /* more than 64k source lines */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif // __RPCNDR_H_VERSION__
#ifndef __ILEncCMW3_h__
#define __ILEncCMW3_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifndef __ILMCMW2Encoder_FWD_DEFINED__
#define __ILMCMW2Encoder_FWD_DEFINED__
typedef interface ILMCMW2Encoder ILMCMW2Encoder;
#endif /* __ILMCMW2Encoder_FWD_DEFINED__ */
#ifndef __LMCMW2Encoder_FWD_DEFINED__
#define __LMCMW2Encoder_FWD_DEFINED__
#ifdef __cplusplus
typedef class LMCMW2Encoder LMCMW2Encoder;
#else
typedef struct LMCMW2Encoder LMCMW2Encoder;
#endif /* __cplusplus */
#endif /* __LMCMW2Encoder_FWD_DEFINED__ */
/* header files for imported files */
#include "oaidl.h"
#include "ocidl.h"
#ifdef __cplusplus
extern "C"{
#endif
#ifndef __LMCMW2EncoderLib_LIBRARY_DEFINED__
#define __LMCMW2EncoderLib_LIBRARY_DEFINED__
/* library LMCMW2EncoderLib */
/* [helpstring][version][uuid] */
#ifndef __ILMCMW2ENCODER_H__
#define __ILMCMW2ENCODER_H__
static const GUID CLSID_LMCMW2Encoder = { 0xe2b7dccc, 0x38c5, 0x11d5, {0x91, 0xf6, 0x00, 0x10, 0x4b, 0xdb, 0x8f, 0xf9 }};
static const GUID CLSID_LMCMW2EncoderProperty = { 0xe2b7dccd, 0x38c5, 0x11d5, {0x91, 0xf6, 0x00, 0x10, 0x4b, 0xdb, 0x8f, 0xf9 }};
static const GUID LIBID_LMCMW2EncoderLib = { 0xe2b7dcce, 0x38c5, 0x11d5, {0x91, 0xf6, 0x00, 0x10, 0x4b, 0xdb, 0x8f, 0xf9 }};
static const GUID IID_ILMCMW2Encoder = { 0xe2b7dccf, 0x38c5, 0x11d5, {0x91, 0xf6, 0x00, 0x10, 0x4b, 0xdb, 0x8f, 0xf9 }};
static const GUID CLSID_LMCMW2Decoder = { 0xe2b7dcd0, 0x38c5, 0x11d5, {0x91, 0xf6, 0x00, 0x10, 0x4b, 0xdb, 0x8f, 0xf9 }};
static const GUID CLSID_LMCMW2DecoderProperty = { 0xe2b7dcd1, 0x38c5, 0x11d5, {0x91, 0xf6, 0x00, 0x10, 0x4b, 0xdb, 0x8f, 0xf9 }};
#endif
typedef /* [public][public][public] */
enum __MIDL___MIDL_itf_ILEncCMW2_0000_0000_0001
{ PerfectQuality_1 = 18,
PerfectQuality_2 = 24,
QualityFarMoreImportantThanSize = 30,
QualityMoreImportantThanSize = 40,
QualityAndSizeAreEquallyImportant = 55,
SizeMoreImportantThanQuality_1 = 70,
SizeMoreImportantThanQuality_2 = 90,
HighCompressionKeepQuality = 110,
HighCompression = 140,
HighcompressionFast = 180,
HypercompressionFast = 220,
Custom = 18
} CMWQUALITYFACTOR;
EXTERN_C const IID LIBID_LMCMW2EncoderLib;
#ifndef __ILMCMW2Encoder_INTERFACE_DEFINED__
#define __ILMCMW2Encoder_INTERFACE_DEFINED__
/* interface ILMCMW2Encoder */
/* [unique][helpstring][uuid][local][object] */
EXTERN_C const IID IID_ILMCMW2Encoder;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("E2B7DCCF-38C5-11D5-91F6-00104BDB8FF9")
ILMCMW2Encoder : public IDispatch
{
public:
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_QualityFactor(
/* [retval][out] */ CMWQUALITYFACTOR *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_QualityFactor(
/* [in] */ CMWQUALITYFACTOR newVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_CompressionRatio(
/* [retval][out] */ DWORD *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_CompressionRatio(
/* [in] */ DWORD newVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_AvgTimePerFrame(
/* [retval][out] */ DWORD *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_FrameWidth(
/* [retval][out] */ DWORD *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_FrameHeight(
/* [retval][out] */ DWORD *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_BitsPerPixel(
/* [retval][out] */ DWORD *pVal) = 0;
};
#else /* C style interface */
typedef struct ILMCMW2EncoderVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
ILMCMW2Encoder * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */
__RPC__deref_out void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
ILMCMW2Encoder * This);
ULONG ( STDMETHODCALLTYPE *Release )(
ILMCMW2Encoder * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
ILMCMW2Encoder * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
ILMCMW2Encoder * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
ILMCMW2Encoder * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [range][in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
ILMCMW2Encoder * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_QualityFactor )(
ILMCMW2Encoder * This,
/* [retval][out] */ CMWQUALITYFACTOR *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_QualityFactor )(
ILMCMW2Encoder * This,
/* [in] */ CMWQUALITYFACTOR newVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CompressionRatio )(
ILMCMW2Encoder * This,
/* [retval][out] */ DWORD *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_CompressionRatio )(
ILMCMW2Encoder * This,
/* [in] */ DWORD newVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_AvgTimePerFrame )(
ILMCMW2Encoder * This,
/* [retval][out] */ DWORD *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_FrameWidth )(
ILMCMW2Encoder * This,
/* [retval][out] */ DWORD *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_FrameHeight )(
ILMCMW2Encoder * This,
/* [retval][out] */ DWORD *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BitsPerPixel )(
ILMCMW2Encoder * This,
/* [retval][out] */ DWORD *pVal);
END_INTERFACE
} ILMCMW2EncoderVtbl;
interface ILMCMW2Encoder
{
CONST_VTBL struct ILMCMW2EncoderVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define ILMCMW2Encoder_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define ILMCMW2Encoder_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define ILMCMW2Encoder_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define ILMCMW2Encoder_GetTypeInfoCount(This,pctinfo) \
( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) )
#define ILMCMW2Encoder_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) )
#define ILMCMW2Encoder_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) )
#define ILMCMW2Encoder_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) )
#define ILMCMW2Encoder_get_QualityFactor(This,pVal) \
( (This)->lpVtbl -> get_QualityFactor(This,pVal) )
#define ILMCMW2Encoder_put_QualityFactor(This,newVal) \
( (This)->lpVtbl -> put_QualityFactor(This,newVal) )
#define ILMCMW2Encoder_get_CompressionRatio(This,pVal) \
( (This)->lpVtbl -> get_CompressionRatio(This,pVal) )
#define ILMCMW2Encoder_put_CompressionRatio(This,newVal) \
( (This)->lpVtbl -> put_CompressionRatio(This,newVal) )
#define ILMCMW2Encoder_get_AvgTimePerFrame(This,pVal) \
( (This)->lpVtbl -> get_AvgTimePerFrame(This,pVal) )
#define ILMCMW2Encoder_get_FrameWidth(This,pVal) \
( (This)->lpVtbl -> get_FrameWidth(This,pVal) )
#define ILMCMW2Encoder_get_FrameHeight(This,pVal) \
( (This)->lpVtbl -> get_FrameHeight(This,pVal) )
#define ILMCMW2Encoder_get_BitsPerPixel(This,pVal) \
( (This)->lpVtbl -> get_BitsPerPixel(This,pVal) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __ILMCMW2Encoder_INTERFACE_DEFINED__ */
EXTERN_C const CLSID CLSID_LMCMW2Encoder;
#ifdef __cplusplus
class DECLSPEC_UUID("E2B7DCCC-38C5-11D5-91F6-00104BDB8FF9")
LMCMW2Encoder;
#endif
#endif /* __LMCMW2EncoderLib_LIBRARY_DEFINED__ */
/* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
| [
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
] | [
[
[
1,
316
]
]
] |
c48275bfc7d80fd362563bb078dd0b8cbb94ba6c | 2e6bb5ab6f8ad09f30785c386ce5ac66258df252 | /project/HappyHunter/Core/Effect.cpp | 6e78ada2dcc4507705981277dda6005f529f3b47 | [] | no_license | linfuqing/happyhunter | 961061f84947a91256980708357b583c6ad2c492 | df38d8a0872b3fd2ea0e1545de3ed98434c12c5e | refs/heads/master | 2016-09-06T04:00:30.779303 | 2010-08-26T15:41:09 | 2010-08-26T15:41:09 | 34,051,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,582 | cpp | #include "StdAfx.h"
#include "Effect.h"
#include "Camera.h"
#include "safefunction.h"
#include <string>
using namespace zerO;
CEffect::CEffect(void) :
CResource(RESOURCE_EFFECT),
m_pEffect(NULL),
m_pSurface(NULL),
m_bIsBegin(false),
m_bIsBeginPass(false)
{
}
CEffect::~CEffect(void)
{
Destroy();
}
void CEffect::Clone(CEffect& Effect)const
{
Effect.m_pSurface = m_pSurface;
Effect.m_pEffect = m_pEffect;
Effect.m_hTechnique = m_hTechnique;
memcpy( &Effect.m_EffectDesc , &m_EffectDesc , sizeof(Effect.m_EffectDesc ) );
memcpy( &Effect.m_TechniqueDesc , &m_TechniqueDesc , sizeof(Effect.m_TechniqueDesc ) );
memcpy( Effect.m_MatrixHandles , m_MatrixHandles , sizeof(Effect.m_MatrixHandles ) );
memcpy( Effect.m_MatrixArrayHandles , m_MatrixArrayHandles , sizeof(Effect.m_MatrixArrayHandles ) );
memcpy( Effect.m_TextureHandles , m_TextureHandles , sizeof(Effect.m_TextureHandles ) );
memcpy( Effect.m_TextureMatrixHandles, m_TextureMatrixHandles, sizeof(Effect.m_TextureMatrixHandles) );
memcpy( Effect.m_ParameterHandles , m_ParameterHandles , sizeof(Effect.m_ParameterHandles ) );
Effect.m_bIsBegin = m_bIsBegin;
Effect.m_bIsBeginPass = m_bIsBeginPass;
}
bool CEffect::Destroy()
{
DEBUG_RELEASE(m_pEffect);
m_pEffect = NULL;
return true;
}
bool CEffect::Disable()
{
HRESULT hr = m_pEffect->OnLostDevice();
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
return true;
}
bool CEffect::Restore()
{
HRESULT hr = m_pEffect->OnResetDevice();
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
return true;
}
bool CEffect::Load(const PBASICCHAR pcFileName)
{
LPD3DXBUFFER pBufferErrors = NULL;
HRESULT hr = D3DXCreateEffectFromFile(&DEVICE, pcFileName, NULL, NULL, D3DXSHADER_DEBUG, NULL, &m_pEffect, &pBufferErrors);
if( FAILED(hr) )
{
DEBUG_ERROR( pBufferErrors->GetBufferPointer() );
DEBUG_RELEASE(pBufferErrors);
return false;
}
DEBUG_RELEASE(pBufferErrors);
hr = m_pEffect->GetDesc( &m_EffectDesc );
if( FAILED(hr) )
{
DEBUG_ERROR(hr);
DEBUG_RELEASE(m_pEffect);
return false;
}
hr = m_pEffect->FindNextValidTechnique(NULL, &m_hTechnique);
if( FAILED(hr) )
{
DEBUG_ERROR(hr);
DEBUG_RELEASE(m_pEffect);
return false;
}
hr = m_pEffect->GetTechniqueDesc(m_hTechnique, &m_TechniqueDesc);
if( FAILED(hr) )
{
DEBUG_ERROR(hr);
DEBUG_RELEASE(m_pEffect);
return false;
}
hr = m_pEffect->SetTechnique(m_hTechnique);
if( FAILED(hr) )
{
DEBUG_ERROR(hr);
DEBUG_RELEASE(m_pEffect);
return false;
}
__ParseParameters();
if(m_pSurface)
return __ApplySurface();
return true;
}
void CEffect::__ParseParameters()
{
memset( m_MatrixHandles, 0, sizeof(m_MatrixHandles) );
memset( m_MatrixArrayHandles, 0, sizeof(m_MatrixArrayHandles) );
memset( m_TextureHandles, 0, sizeof(m_TextureHandles) );
memset( m_TextureMatrixHandles, 0, sizeof(m_TextureMatrixHandles) );
memset( m_ParameterHandles, 0, sizeof(m_ParameterHandles) );
static CHAR s_Numerals[] = "0123456789";
D3DXHANDLE hParameter;
D3DXPARAMETER_DESC ParameterDesc;
std::basic_string< CHAR, std::char_traits<CHAR> > Semantic;
UINT32 uNumberPosition, uIndex;
for(UINT32 i = 0; i < m_EffectDesc.Parameters; i ++)
{
hParameter = m_pEffect->GetParameter(NULL, i);
m_pEffect->GetParameterDesc(hParameter, &ParameterDesc);
if(ParameterDesc.Semantic != NULL)
{
if(ParameterDesc.Class == D3DXPC_MATRIX_ROWS || ParameterDesc.Class == D3DXPC_MATRIX_COLUMNS)
{
if(STRCMP(ParameterDesc.Semantic, "WORLDMATRIXARRAY") == 0)
m_MatrixArrayHandles[WORLD_MATRIX_ARRAY] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "WORLDVIEWPROJECTION") == 0)
m_MatrixHandles[WORLD_VIEW_PROJECTION] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "VIEWPROJECTION") == 0)
m_MatrixHandles[VIEW_PROJECTION] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "WORLDVIEW") == 0)
m_MatrixHandles[WORLD_VIEW] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "WORLD") == 0)
m_MatrixHandles[WORLD] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "VIEW") == 0)
m_MatrixHandles[VIEW] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "PROJECTION") == 0)
m_MatrixHandles[PROJECTION] = hParameter;
else if(STRNICMP(ParameterDesc.Semantic, "TEXTURE", 3) == 0)
{
Semantic.assign(ParameterDesc.Semantic);
uNumberPosition = Semantic.find_first_of(s_Numerals);
if(uNumberPosition != std::basic_string<CHAR, std::char_traits<CHAR> >::npos)
{
uIndex = atoi(&ParameterDesc.Semantic[uNumberPosition]);
if(uIndex < MAXINUM_TEXTURE_HANDLES)
m_TextureMatrixHandles[uIndex] = hParameter;
}
}
}
else if(ParameterDesc.Class == D3DXPC_VECTOR)
{
if( STRCMP(ParameterDesc.Semantic, "MATERIALAMBIENT") == 0)
m_ParameterHandles[AMBIENT_MATERIAL_COLOR] = hParameter;
else if( STRCMP(ParameterDesc.Semantic, "MATERIALDIFFUSE") == 0 )
m_ParameterHandles[DIFFUSE_MATERIAL_COLOR] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "MATERIALEMISSIVE") == 0)
m_ParameterHandles[EMISSIVE_MATERIAL_COLOR] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "MATERIALSPECULAR") == 0)
m_ParameterHandles[SPECULAR_MATERIAL_COLOR] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "LIGHTAMBIENT") == 0)
m_ParameterHandles[AMBIENT_LIGHT_COLOR] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "POSITIONOFFSET") == 0)
m_ParameterHandles[POSITION_OFFSET] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "UVOFFSET") == 0)
m_ParameterHandles[UV_OFFSET] = hParameter;
else if(STRCMP(ParameterDesc.Semantic, "EYEPOSITION") == 0 || STRCMP(ParameterDesc.Semantic, "CAMERAPOSITION") == 0)
m_ParameterHandles[EYE_POSITION] = hParameter;
}
else if(ParameterDesc.Class == D3DXPC_SCALAR)
{
if( STRCMP(ParameterDesc.Semantic, "MATERIALPOWER") == 0 )
m_ParameterHandles[SPECULAR_MATERIAL_POWER] = hParameter;
else if( STRCMP(ParameterDesc.Semantic, "BONEINFLUENCESNUMBER") == 0 )
m_ParameterHandles[BONE_INFLUENCES_NUMBER] = hParameter;
}
else if(ParameterDesc.Class == D3DXPC_OBJECT)
{
if(ParameterDesc.Type == D3DXPT_TEXTURE
|| ParameterDesc.Type == D3DXPT_TEXTURE2D
|| ParameterDesc.Type == D3DXPT_TEXTURE3D
|| ParameterDesc.Type == D3DXPT_TEXTURECUBE)
{
Semantic.assign(ParameterDesc.Semantic);
uNumberPosition = Semantic.find_first_of(s_Numerals);
if(uNumberPosition != std::basic_string<CHAR, std::char_traits<CHAR> >::npos)
{
uIndex = atoi(&ParameterDesc.Semantic[uNumberPosition]);
if(uIndex < MAXINUM_TEXTURE_HANDLES)
m_TextureHandles[uIndex] = hParameter;
}
}
}
}
}
}
bool CEffect::BeginPass(zerO::UINT uPass)
{
DEBUG_ASSERT(m_pEffect, "This Effect is not valid");
if(m_bIsBeginPass)
EndPass();
m_bIsBeginPass = true;
HRESULT hr = m_pEffect->BeginPass(uPass);
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
return true;
}
bool CEffect::EndPass()
{
DEBUG_ASSERT(m_pEffect, "This Effect is not valid");
m_bIsBeginPass = false;
HRESULT hr = m_pEffect->EndPass();
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
return true;
}
bool CEffect::Begin()
{
DEBUG_ASSERT(m_pEffect, "This Effect is not valid");
if(m_bIsBegin)
End();
HRESULT hr = m_pEffect->Begin(NULL, D3DXFX_DONOTSAVESTATE|D3DXFX_DONOTSAVESHADERSTATE);
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
SetMatrix(VIEW, CAMERA.GetViewMatrix() );
SetMatrix(PROJECTION, CAMERA.GetProjectionMatrix() );
SetMatrix(VIEW_PROJECTION, CAMERA.GetViewProjectionMatrix() );
D3DXVECTOR4 RGBA;
LIGHTMANAGER.GetAmbientRGBA(RGBA);
SetParameter(AMBIENT_LIGHT_COLOR, &RGBA);
SetParameter( EYE_POSITION, &CAMERA.GetWorldPosition() );
m_bIsBegin = true;
return true;
}
bool CEffect::End()
{
DEBUG_ASSERT(m_pEffect, "This Effect is not valid");
if(!m_bIsBeginPass)
EndPass();
m_bIsBegin = false;
HRESULT hr = m_pEffect->End();
if( FAILED(hr) )
{
DEBUG_WARNING(hr);
return false;
}
DEVICE.SetVertexShader(NULL);
DEVICE.SetPixelShader(NULL);
return true;
}
bool CEffect::Active(zerO::UINT uPass)
{
return Begin() && BeginPass(uPass);
}
bool CEffect::SetSurface(CSurface* const pSurface)
{
m_pSurface = pSurface;
if(m_pEffect)
return __ApplySurface();
return true;
}
bool CEffect::__ApplySurface()
{
const D3DMATERIAL9& MATERIAL = m_pSurface->GetMaterial();
SetParameter(AMBIENT_MATERIAL_COLOR, &MATERIAL.Ambient);
SetParameter(DIFFUSE_MATERIAL_COLOR, &MATERIAL.Diffuse);
SetParameter(EMISSIVE_MATERIAL_COLOR, &MATERIAL.Emissive);
SetParameter(SPECULAR_MATERIAL_COLOR, &MATERIAL.Specular);
SetParameter(SPECULAR_MATERIAL_POWER, &MATERIAL.Power);
for(UINT32 i = 0; i< MAXINUM_TEXTURE_HANDLES; i++)
{
if( TEST_BIT(m_pSurface->GetTextureFlag(), i) )
SetTexture( i, *m_pSurface->GetTexture(i) );
}
return true;
} | [
"linfuqing0@c6a4b443-94a6-74e8-d042-0855a5ab0aac"
] | [
[
[
1,
360
]
]
] |
3585dcd195a506bd2222df3c5bac051d5d97566d | 8f5d0d23e857e58ad88494806bc60c5c6e13f33d | /Math/cCatmullRomSpline.cpp | 35dacc4170691d1ec9a43cef8ea405973ebdf021 | [] | no_license | markglenn/projectlife | edb14754118ec7b0f7d83bd4c92b2e13070dca4f | a6fd3502f2c2713a8a1a919659c775db5309f366 | refs/heads/master | 2021-01-01T15:31:30.087632 | 2011-01-30T16:03:41 | 2011-01-30T16:03:41 | 1,704,290 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,054 | cpp | #include "ccatmullromspline.h"
// Include Paul Nettle's memory manager
#include "../Memory/mmgr.h"
#define CATMULL_STEPS 100.f
/////////////////////////////////////////////////////////////////////////////////////
cCatmullRomSpline::cCatmullRomSpline(void)
/////////////////////////////////////////////////////////////////////////////////////
{
}
/////////////////////////////////////////////////////////////////////////////////////
cCatmullRomSpline::~cCatmullRomSpline(void)
/////////////////////////////////////////////////////////////////////////////////////
{
}
/////////////////////////////////////////////////////////////////////////////////////
cVector cCatmullRomSpline::CalculatePoint ( float t )
/////////////////////////////////////////////////////////////////////////////////////
{
cVector out;
float t1, t2, t3;
int pos = int(t);
t = t - float(pos);
t2 = t * t;
t3 = t * t * t;
t1 = (1-t) * (1-t);
out.x = (-t*t1*m_pointList[pos].x + (2-5*t2+3*t3)*m_pointList[pos + 1].x + t*(1+4*t-3*t2)*m_pointList[pos + 2].x - t2*(1-t)*m_pointList[pos + 3].x)/2;
out.y = (-t*t1*m_pointList[pos].y + (2-5*t2+3*t3)*m_pointList[pos + 1].y + t*(1+4*t-3*t2)*m_pointList[pos + 2].y - t2*(1-t)*m_pointList[pos + 3].y)/2;
out.z = (-t*t1*m_pointList[pos].z + (2-5*t2+3*t3)*m_pointList[pos + 1].z + t*(1+4*t-3*t2)*m_pointList[pos + 2].z - t2*(1-t)*m_pointList[pos + 3].z)/2;
return out;
}
/////////////////////////////////////////////////////////////////////////////////////
void cCatmullRomSpline::PrecalculateLength()
/////////////////////////////////////////////////////////////////////////////////////
{
float length;
m_lengthList.clear();
for (float i = 0.f; i < (float)m_pointList.size() - 3; i += 1.f)
{
length = 0.f;
for (float j = 0.f; j < CATMULL_STEPS; j += 1.f)
{
cVector first = CalculatePoint (i + j / CATMULL_STEPS);
cVector second = CalculatePoint (i + (j + 1) / CATMULL_STEPS);
length += !(first - second);
}
m_lengthList.push_back(length);
}
} | [
"[email protected]"
] | [
[
[
1,
59
]
]
] |
deddd29f82a6315856bc6c78dab24cd092f89a8f | 3187b0dd0d7a7b83b33c62357efa0092b3943110 | /src/dlib/base64/base64_kernel_1.cpp | ab99466f27cd0f5db79be0df811029794594a835 | [
"BSL-1.0"
] | permissive | exi/gravisim | 8a4dad954f68960d42f1d7da14ff1ca7a20e92f2 | 361e70e40f58c9f5e2c2f574c9e7446751629807 | refs/heads/master | 2021-01-19T17:45:04.106839 | 2010-10-22T09:11:24 | 2010-10-22T09:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,266 | cpp | // Copyright (C) 2006 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_BASE64_KERNEL_1_CPp_
#define DLIB_BASE64_KERNEL_1_CPp_
#include "base64_kernel_1.h"
#include <iostream>
#include <sstream>
#include <climits>
namespace dlib
{
// ----------------------------------------------------------------------------------------
base64_kernel_1::
base64_kernel_1 (
) :
encode_table(0),
decode_table(0),
bad_value(100)
{
try
{
encode_table = new char[64];
decode_table = new unsigned char[UCHAR_MAX];
}
catch (...)
{
if (encode_table) delete [] encode_table;
if (decode_table) delete [] decode_table;
throw;
}
// now set up the tables with the right stuff
encode_table[0] = 'A';
encode_table[17] = 'R';
encode_table[34] = 'i';
encode_table[51] = 'z';
encode_table[1] = 'B';
encode_table[18] = 'S';
encode_table[35] = 'j';
encode_table[52] = '0';
encode_table[2] = 'C';
encode_table[19] = 'T';
encode_table[36] = 'k';
encode_table[53] = '1';
encode_table[3] = 'D';
encode_table[20] = 'U';
encode_table[37] = 'l';
encode_table[54] = '2';
encode_table[4] = 'E';
encode_table[21] = 'V';
encode_table[38] = 'm';
encode_table[55] = '3';
encode_table[5] = 'F';
encode_table[22] = 'W';
encode_table[39] = 'n';
encode_table[56] = '4';
encode_table[6] = 'G';
encode_table[23] = 'X';
encode_table[40] = 'o';
encode_table[57] = '5';
encode_table[7] = 'H';
encode_table[24] = 'Y';
encode_table[41] = 'p';
encode_table[58] = '6';
encode_table[8] = 'I';
encode_table[25] = 'Z';
encode_table[42] = 'q';
encode_table[59] = '7';
encode_table[9] = 'J';
encode_table[26] = 'a';
encode_table[43] = 'r';
encode_table[60] = '8';
encode_table[10] = 'K';
encode_table[27] = 'b';
encode_table[44] = 's';
encode_table[61] = '9';
encode_table[11] = 'L';
encode_table[28] = 'c';
encode_table[45] = 't';
encode_table[62] = '+';
encode_table[12] = 'M';
encode_table[29] = 'd';
encode_table[46] = 'u';
encode_table[63] = '/';
encode_table[13] = 'N';
encode_table[30] = 'e';
encode_table[47] = 'v';
encode_table[14] = 'O';
encode_table[31] = 'f';
encode_table[48] = 'w';
encode_table[15] = 'P';
encode_table[32] = 'g';
encode_table[49] = 'x';
encode_table[16] = 'Q';
encode_table[33] = 'h';
encode_table[50] = 'y';
// we can now fill out the decode_table by using the encode_table
for (int i = 0; i < UCHAR_MAX; ++i)
{
decode_table[i] = bad_value;
}
for (unsigned char i = 0; i < 64; ++i)
{
decode_table[encode_table[i]] = i;
}
}
// ----------------------------------------------------------------------------------------
base64_kernel_1::
~base64_kernel_1 (
)
{
delete [] encode_table;
delete [] decode_table;
}
// ----------------------------------------------------------------------------------------
void base64_kernel_1::
encode (
std::istream& in_,
std::ostream& out_
) const
{
using namespace std;
streambuf& in = *in_.rdbuf();
streambuf& out = *out_.rdbuf();
unsigned char inbuf[3];
unsigned char outbuf[4];
streamsize status = in.sgetn(reinterpret_cast<char*>(&inbuf),3);
unsigned char c1, c2, c3, c4, c5, c6;
int counter = 19;
const char newline = '\n';
// while we haven't hit the end of the input stream
while (status != 0)
{
if (counter == 0)
{
counter = 19;
// write a newline
if (out.sputn(reinterpret_cast<const char*>(&newline),1)!=1)
{
throw std::ios_base::failure("error occured in the base64 object");
}
}
--counter;
if (status == 3)
{
// encode the bytes in inbuf to base64 and write them to the output stream
c1 = inbuf[0]&0xfc;
c2 = inbuf[0]&0x03;
c3 = inbuf[1]&0xf0;
c4 = inbuf[1]&0x0f;
c5 = inbuf[2]&0xc0;
c6 = inbuf[2]&0x3f;
outbuf[0] = c1>>2;
outbuf[1] = (c2<<4)|(c3>>4);
outbuf[2] = (c4<<2)|(c5>>6);
outbuf[3] = c6;
outbuf[0] = encode_table[outbuf[0]];
outbuf[1] = encode_table[outbuf[1]];
outbuf[2] = encode_table[outbuf[2]];
outbuf[3] = encode_table[outbuf[3]];
// write the encoded bytes to the output stream
if (out.sputn(reinterpret_cast<char*>(&outbuf),4)!=4)
{
throw std::ios_base::failure("error occured in the base64 object");
}
// get 3 more input bytes
status = in.sgetn(reinterpret_cast<char*>(&inbuf),3);
continue;
}
else if (status == 2)
{
// we are at the end of the input stream and need to add some padding
// encode the bytes in inbuf to base64 and write them to the output stream
c1 = inbuf[0]&0xfc;
c2 = inbuf[0]&0x03;
c3 = inbuf[1]&0xf0;
c4 = inbuf[1]&0x0f;
c5 = 0;
outbuf[0] = c1>>2;
outbuf[1] = (c2<<4)|(c3>>4);
outbuf[2] = (c4<<2)|(c5>>6);
outbuf[3] = '=';
outbuf[0] = encode_table[outbuf[0]];
outbuf[1] = encode_table[outbuf[1]];
outbuf[2] = encode_table[outbuf[2]];
// write the encoded bytes to the output stream
if (out.sputn(reinterpret_cast<char*>(&outbuf),4)!=4)
{
throw std::ios_base::failure("error occured in the base64 object");
}
break;
}
else // in this case status must be 1
{
// we are at the end of the input stream and need to add some padding
// encode the bytes in inbuf to base64 and write them to the output stream
c1 = inbuf[0]&0xfc;
c2 = inbuf[0]&0x03;
c3 = 0;
outbuf[0] = c1>>2;
outbuf[1] = (c2<<4)|(c3>>4);
outbuf[2] = '=';
outbuf[3] = '=';
outbuf[0] = encode_table[outbuf[0]];
outbuf[1] = encode_table[outbuf[1]];
// write the encoded bytes to the output stream
if (out.sputn(reinterpret_cast<char*>(&outbuf),4)!=4)
{
throw std::ios_base::failure("error occured in the base64 object");
}
break;
}
} // while (status != 0)
// make sure the stream buffer flushes to its I/O channel
out.pubsync();
}
// ----------------------------------------------------------------------------------------
void base64_kernel_1::
decode (
std::istream& in_,
std::ostream& out_
) const
{
using namespace std;
streambuf& in = *in_.rdbuf();
streambuf& out = *out_.rdbuf();
unsigned char inbuf[4];
unsigned char outbuf[3];
int inbuf_pos = 0;
streamsize status = in.sgetn(reinterpret_cast<char*>(inbuf),1);
// only count this character if it isn't some kind of filler
if (status == 1 && decode_table[inbuf[0]] != bad_value )
++inbuf_pos;
unsigned char c1, c2, c3, c4, c5, c6;
streamsize outsize;
// while we haven't hit the end of the input stream
while (status != 0)
{
// if we have 4 valid characters
if (inbuf_pos == 4)
{
inbuf_pos = 0;
// this might be the end of the encoded data so we need to figure out if
// there was any padding applied.
outsize = 3;
if (inbuf[3] == '=')
{
if (inbuf[2] == '=')
outsize = 1;
else
outsize = 2;
}
// decode the incoming characters
inbuf[0] = decode_table[inbuf[0]];
inbuf[1] = decode_table[inbuf[1]];
inbuf[2] = decode_table[inbuf[2]];
inbuf[3] = decode_table[inbuf[3]];
// now pack these guys into bytes rather than 6 bit chunks
c1 = inbuf[0]<<2;
c2 = inbuf[1]>>4;
c3 = inbuf[1]<<4;
c4 = inbuf[2]>>2;
c5 = inbuf[2]<<6;
c6 = inbuf[3];
outbuf[0] = c1|c2;
outbuf[1] = c3|c4;
outbuf[2] = c5|c6;
// write the encoded bytes to the output stream
if (out.sputn(reinterpret_cast<char*>(&outbuf),outsize)!=outsize)
{
throw std::ios_base::failure("error occured in the base64 object");
}
}
// get more input characters
status = in.sgetn(reinterpret_cast<char*>(inbuf + inbuf_pos),1);
// only count this character if it isn't some kind of filler
if ((decode_table[inbuf[inbuf_pos]] != bad_value || inbuf[inbuf_pos] == '=') &&
status != 0)
++inbuf_pos;
} // while (status != 0)
if (inbuf_pos != 0)
{
ostringstream sout;
sout << inbuf_pos << " extra characters were found at the end of the encoded data."
<< " This may indicate that the data stream has been truncated.";
// this happens if we hit EOF in the middle of decoding a 24bit block.
throw decode_error(sout.str());
}
// make sure the stream buffer flushes to its I/O channel
out.pubsync();
}
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_BASE64_KERNEL_1_CPp_
| [
"[email protected]"
] | [
[
[
1,
364
]
]
] |
c50e0a8c80c96b351eeb7f9bd0d573b873414ab9 | 30a1e1c0c95239e5fa248fbb1b4ed41c6fe825ff | /c/conv.cpp | 5301adca874c636a9fba69fefc69782095534232 | [] | no_license | inspirer/history | ed158ef5c04cdf95270821663820cf613b5c8de0 | 6df0145cd28477b23748b1b50e4264a67441daae | refs/heads/master | 2021-01-01T17:22:46.101365 | 2011-06-12T00:58:37 | 2011-06-12T00:58:37 | 1,882,931 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,543 | cpp | /* conv.cpp
*
* C Compiler project (cc)
* Copyright (C) 2002-03 Eugeniy Gryaznov ([email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "cc.h"
//
// returns 1 if type if convertible to the target type
//
int type::can_convert_to( Type t, Compiler *cc ) const
{
ASSERT( SCALAR(this) && ( SCALAR(t) || VOIDTYPE(t) ) );
//TODO();
return 1;
}
/*
6.2.7 Compatible type and composite type
qualif - 1 means to process qualification
*/
Type type::compatible( Type t1, Type t2, int qualif, Compiler *cc )
{
// 6.7.3.9 For two qualified types to be compatible, both shall have the
// identically qualified version of a compatible type; the order of type
// qualifiers within a list of specifiers or qualifiers does not affect the
// specified type.
if( T(t1) != T(t2) || qualif == 0 && Q(t1) != Q(t2) )
return NULL;
Type t, result = t1;
switch( T(t1) ) {
// 6.7.5.1.2 For two pointer types to be compatible, both shall be identically
// qualified and both shall be pointers to compatible types.
case t_pointer:
t = type::compatible( t1->parent, t2->parent, qualif, cc );
result = t == t1->parent ? t1 : t == t2->parent ? t2 : NULL;
if( t && (!result || Q(t1) != Q(t2) ) ) {
result = t1->clone(cc);
TYPE(result)->parent = t;
Q(TYPE(result)) |= Q(t2);
}
break;
// 6.7.5.2.6
// For two array types to be compatible, both shall have compatible element types, and if
// both size specifiers are present, and are integer constant expressions, then both size
// specifiers shall have the same constant value. If the two array types are used in a context
// which requires them to be compatible, it is undefined behavior if the two size specifiers
// evaluate to unequal values.
case t_array:
TODO();
// 6.7.5.3.15
// For two function types to be compatible, both shall specify compatible return types.125)
// Moreover, the parameter type lists, if both are present, shall agree in the number of
// parameters and in use of the ellipsis terminator; corresponding parameters shall have
// compatible types. If one type has a parameter type list and the other type is specified by a
// function declarator that is not part of a function definition and that contains an empty
// identifier list, the parameter list shall not have an ellipsis terminator and the type of each
// parameter shall be compatible with the type that results from the application of the
// default argument promotions. If one type has a parameter type list and the other type is
// specified by a function definition that contains a (possibly empty) identifier list, both shall
// agree in the number of parameters, and the type of each prototype parameter shall be
// compatible with the type that results from the application of the default argument
// promotions to the type of the corresponding identifier. (In the determination of type
// compatibility and of a composite type, each parameter declared with function or array
// type is taken as having the adjusted type and each parameter declared with qualified type
// is taken as having the unqualified version of its declared type.)
case t_func:
TODO();
// 6.2.7 two structure, union, or enumerated types declared in separate translation units are
// compatible if their tags and members satisfy the following requirements: If one is
// declared with a tag, the other shall be declared with the same tag. If both are completed
// types, then the following additional requirements apply: there shall be a one-to-one
// correspondence between their members such that each pair of corresponding members are
// declared with compatible types, and such that if one member of a corresponding pair is
// declared with a name, the other member is declared with the same name. For two
// structures, corresponding members shall be declared in the same order. For two structures
// or unions, corresponding bit-fields shall have the same widths.
case t_struct: case t_union:
TODO();
// 6.2.7 For two enumerations, corresponding members shall have the same values.
case t_enum:
TODO();
// check qualification
default:
if( Q(t1) != Q(t2) ) {
result = t1->clone(cc);
Q(TYPE(result)) |= Q(t2);
}
}
return result;
}
Type type::integer_promotion( Compiler *cc ) const
{
// TODO bittype
if( INTTYPE(this) && RANK(this) < INTRANK )
return type::get_basic_type( t_int, cc );
return this;
}
/*
Returns the common type for two arithmetic subexpressions and applies
cast operator to each of them if needed.
*/
const static int dom_to_type[3][3] = {
{ t_float, t_double, t_ldouble }, { t_fimg, t_dimg, t_limg }, { t_fcompl, t_dcompl, t_lcompl } };
const static int dom_x_dom_mul[3][3] = {
{ 0, 1, 2 }, { 1, 0, 2 }, { 2, 2, 2 } };
Type expr::usual_conversions( Expr *x1, Expr *x2, int action, Compiler *cc )
{
Type p1, p2, res;
Expr e1 = *x1, e2 = *x2;
ASSERT( ARITHMETIC(e1->restype) && ARITHMETIC(e1->restype) );
// float types
if( FLOATTYPE(e1->restype) || FLOATTYPE(e2->restype) ) {
int d1 = tdescr[T(e1->restype)].domain, d2 = tdescr[T(e2->restype)].domain;
int type = F_TYPE(d1) > F_TYPE(d2) ? F_TYPE(d1) : F_TYPE(d2);
int domain = 2, dom1 = F_DOMAIN(d1), dom2 = F_DOMAIN(d2);
switch( action ) {
case e_mult:
domain = dom_x_dom_mul[dom1][dom2];
break;
case e_div:
TODO();
case e_tripl: case e_plus: case e_minus:
case e_gt: case e_lt: case e_le: case e_ge:
if( dom1 == dom2 )
domain = dom1;
else
dom1 = dom2 = domain;
break;
default:
TODO();
}
ASSERT( type < 3 && domain < 3 );
res = type::get_basic_type( dom_to_type[domain][type], cc );
p1 = type::get_basic_type( dom_to_type[dom1][type], cc );
p2 = type::get_basic_type( dom_to_type[dom2][type], cc );
goto exit;
}
// integer types
p1 = e1->restype->integer_promotion(cc);
p2 = e2->restype->integer_promotion(cc);
// 6.5.7.3 (Bitwise shift operators) The integer promotions are performed
// on each of the operands. The type of the result is that of the promoted left operand.
if( action == e_shl || action == e_shr ) {
res = p1;
goto exit;
}
// 6.3.8.1 If both operands have the same type, then no further conversion is needed.
if( T(p1) == T(p2) ) {
res = p1;
goto exit;
}
// If both operands have signed integer types or both have unsigned
// integer types, the operand with the type of lesser integer conversion rank is
// converted to the type of the operand with greater rank.
if( SIGNED(p1) == SIGNED(p2) ) {
res = RANK(p1) >= RANK(p2) ? p1 : p2;
goto exit;
}
// if the operand that has unsigned integer type has rank greater or
// equal to the rank of the type of the other operand, then the operand with
// signed integer type is converted to the type of the operand with unsigned
// integer type.
if( !SIGNED(p1) && SIGNED(p2) && RANK(p1) >= RANK(p2) ) {
res = p1;
goto exit;
}
if( SIGNED(p1) && !SIGNED(p2) && RANK(p1) <= RANK(p2) ) {
res = p2;
goto exit;
}
// If the type of the operand with signed integer type can represent
// all of the values of the type of the operand with unsigned integer type, then
// the operand with unsigned integer type is converted to the type of the
// operand with signed integer type.
res = RANK(p1) > RANK(p2) ? p1 : p2;
exit:
if( T(e1->restype) != T(p1) ) {
Expr e = create( e_cast, p1, cc );
e->op[0] = e1;
*x1 = e;
}
if( T(e2->restype) != T(p2) ) {
Expr e = create( e_cast, p2, cc );
e->op[0] = e2;
*x2 = e;
}
return res;
}
| [
"[email protected]"
] | [
[
[
1,
241
]
]
] |
5b35db3675154bce0e235af757a45b923d99ba53 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/markham.h | f64c5cd1f016e651f5c32abe2cf3cb1436b50c6c | [] | 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 | 760 | h | /*************************************************************************
Markham
*************************************************************************/
class markham_state : public driver_device
{
public:
markham_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
/* memory pointers */
UINT8 * m_videoram;
UINT8 * m_spriteram;
UINT8 * m_xscroll;
size_t m_spriteram_size;
/* video-related */
tilemap_t *m_bg_tilemap;
};
/*----------- defined in video/markham.c -----------*/
WRITE8_HANDLER( markham_videoram_w );
WRITE8_HANDLER( markham_flipscreen_w );
PALETTE_INIT( markham );
VIDEO_START( markham );
SCREEN_UPDATE( markham );
| [
"Mike@localhost"
] | [
[
[
1,
31
]
]
] |
f40253219b868d085ee1b55c9878a01a5bfa1d72 | 6a2f859a41525c5512f9bf650db68bcd7d95748d | /TP2/ex2/R0/src/TypeInteger.cpp | 3ed72a3807f345fb38e541023682b2b355d42b74 | [] | no_license | Bengrunt/mif12-2009 | 21df06941a6a1e844372eb01f4911b1ef232b306 | d4f02f1aab82065c8184facf859fe80233bc46b5 | refs/heads/master | 2021-01-23T13:48:47.238211 | 2009-12-04T22:52:25 | 2009-12-04T22:52:25 | 32,153,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 170 | cpp | #include "TypeInteger.hpp"
/**
* Constructeur.
*/
TypeInteger::TypeInteger() {
_name = (char*) "integer";
}
/**
* Destructeur.
*/
TypeInteger::~TypeInteger() {}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
]
],
[
[
2,
13
]
]
] |
b2b9c4ef521359c20c4ea2d5274bd630099014eb | b2b5c3694476d1631322a340c6ad9e5a9ec43688 | /Baluchon/FrameCube.cpp | bc7818b6d45a9dc2bfe4ce007406d7d356f5306c | [] | no_license | jpmn/rough-albatross | 3c456ea23158e749b029b2112b2f82a7a5d1fb2b | eb2951062f6c954814f064a28ad7c7a4e7cc35b0 | refs/heads/master | 2016-09-05T12:18:01.227974 | 2010-12-19T08:03:25 | 2010-12-19T08:03:25 | 32,195,707 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,524 | cpp | #include "FrameCube.h"
namespace baluchon { namespace core { namespace services { namespace positioning {
FrameCube::FrameCube(CvPoint3D32f pt1, float size, CvScalar color)
{
mInitialPoints.push_back(cvPoint3D32f(pt1.x, pt1.y, pt1.z + size));
mTransformedPoints.push_back(cvPoint3D32f(pt1.x, pt1.y, pt1.z + size));
mInitialPoints.push_back(cvPoint3D32f(pt1.x + size, pt1.y, pt1.z + size));
mTransformedPoints.push_back(cvPoint3D32f(pt1.x + size, pt1.y, pt1.z + size));
mInitialPoints.push_back(cvPoint3D32f(pt1.x + size, pt1.y + size, pt1.z + size));
mTransformedPoints.push_back(cvPoint3D32f(pt1.x + size, pt1.y + size, pt1.z + size));
mInitialPoints.push_back(cvPoint3D32f(pt1.x, pt1.y + size, pt1.z + size));
mTransformedPoints.push_back(cvPoint3D32f(pt1.x, pt1.y + size, pt1.z + size));
mInitialPoints.push_back(pt1);
mTransformedPoints.push_back(pt1);
mInitialPoints.push_back(cvPoint3D32f(pt1.x + size, pt1.y, pt1.z));
mTransformedPoints.push_back(cvPoint3D32f(pt1.x + size, pt1.y, pt1.z));
mInitialPoints.push_back(cvPoint3D32f(pt1.x + size, pt1.y + size, pt1.z));
mTransformedPoints.push_back(cvPoint3D32f(pt1.x + size, pt1.y + size, pt1.z));
mInitialPoints.push_back(cvPoint3D32f(pt1.x, pt1.y + size, pt1.z));
mTransformedPoints.push_back(cvPoint3D32f(pt1.x, pt1.y + size, pt1.z));
mColor = color;
}
FrameCube::~FrameCube(void) {
}
void FrameCube::accept(IVisitor* v)
{
v->visit(this);
}
}}}};
| [
"[email protected]@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5",
"jpmorin196@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5"
] | [
[
[
1,
27
],
[
30,
37
]
],
[
[
28,
29
]
]
] |
1490f5c4d165c1d0a8f512a046dee5bf9f9186fd | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /C++Primer中文版(第4版)/第一次-代码集合-20090414/第十五章 面向对象编程/20090308_Basket.cpp | ee45817861cce1a09c740759510b38b9a35c4d5a | [] | 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 | 258 | cpp | #include "20090308_Basket.hpp"
double Basket::total() const
{
double sum = 0.0;
for (const_iter iter = items.begin(); iter != items.end(); iter = items.upper_bound(*iter))
{
sum += (*iter)->net_price(items.count(*iter));
}
return sum;
} | [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
] | [
[
[
1,
13
]
]
] |
db1dbf001f9d6216d9829ba3686c1a3081f3e1c2 | 77aa13a51685597585abf89b5ad30f9ef4011bde | /dep/src/boost/boost/function/function_fwd.hpp | 08792631993db01731a8ac2ffccf6200b8881745 | [] | no_license | Zic/Xeon-MMORPG-Emulator | 2f195d04bfd0988a9165a52b7a3756c04b3f146c | 4473a22e6dd4ec3c9b867d60915841731869a050 | refs/heads/master | 2021-01-01T16:19:35.213330 | 2009-05-13T18:12:36 | 2009-05-14T03:10:17 | 200,849 | 8 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 2,730 | hpp | // Boost.Function library
// Copyright (C) Douglas Gregor 2008
//
// Use, modification and distribution is subject to the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org
#ifndef BOOST_FUNCTION_FWD_HPP
#define BOOST_FUNCTION_FWD_HPP
#include <boost/config.hpp>
#if defined(__sgi) && defined(_COMPILER_VERSION) && _COMPILER_VERSION <= 730 && !defined(BOOST_STRICT_CONFIG)
// Work around a compiler bug.
// boost::python::objects::function has to be seen by the compiler before the
// boost::function class template.
namespace boost { namespace python { namespace objects {
class function;
}}}
#endif
#if defined (BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
|| defined(BOOST_BCB_PARTIAL_SPECIALIZATION_BUG) \
|| !(BOOST_STRICT_CONFIG || !defined(__SUNPRO_CC) || __SUNPRO_CC > 0x540)
# define BOOST_FUNCTION_NO_FUNCTION_TYPE_SYNTAX
#endif
namespace boost {
class bad_function_call;
#if !defined(BOOST_FUNCTION_NO_FUNCTION_TYPE_SYNTAX)
// Preferred syntax
template<typename Signature> class function;
template<typename Signature>
inline void swap(function<Signature>& f1, function<Signature>& f2)
{
f1.swap(f2);
}
#endif // have partial specialization
// Portable syntax
template<typename R> class function0;
template<typename R, typename T1> class function1;
template<typename R, typename T1, typename T2> class function2;
template<typename R, typename T1, typename T2, typename T3> class function3;
template<typename R, typename T1, typename T2, typename T3, typename T4>
class function4;
template<typename R, typename T1, typename T2, typename T3, typename T4,
typename T5>
class function5;
template<typename R, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6>
class function6;
template<typename R, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7>
class function7;
template<typename R, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7, typename T8>
class function8;
template<typename R, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7, typename T8, typename T9>
class function9;
template<typename R, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7, typename T8, typename T9,
typename T10>
class function10;
}
#endif
| [
"pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88"
] | [
[
[
1,
70
]
]
] |
98ae440c1094f55218c86e738a6bee86a5064992 | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /source/RenderSystemD3D/OED3DUtil.h | bd63bca8a291f3aa17fdd30fadb04e8067335afe | [] | no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,966 | h | /*!
* \file OED3DUtil.h
* \date 24-5-2009 18:03:21
*
*
* \author zjhlogo ([email protected])
*/
#ifndef __OED3DUTIL_H__
#define __OED3DUTIL_H__
#include <OECore/IOEVertDecl.h>
#include <OECore/IOERenderSystem.h>
#include <OECore/IOETexture.h>
#include <libOEMath/OEMath.h>
#include <d3dx9.h>
class COED3DUtil
{
public:
static void ToD3DXMatrix(D3DXMATRIX& matOut, const CMatrix4x4& matIn);
static void ToOEMatrix(CMatrix4x4& matOut, const D3DXMATRIX& matIn);
static void ToD3DVector3(D3DXVECTOR3& vOut, const CVector3& vIn);
static void ToOEVector3(CVector3& vOut, const D3DXVECTOR3& vIn);
static void ToD3DVector4(D3DXVECTOR4& vOut, const CVector4& vIn);
static void ToOEVector4(CVector4& vOut, const D3DXVECTOR4& vIn);
static D3DDECLTYPE ToD3DVertType(VERT_DECL_TYPE eType);
static VERT_DECL_TYPE ToOEVertType(D3DDECLTYPE eType);
static D3DDECLUSAGE ToD3DVertUsage(VERT_DECL_USAGE eUsage);
static VERT_DECL_USAGE ToOEVertUsage(D3DDECLUSAGE eUsage);
static int GetVertTypeSize(VERT_DECL_TYPE eType);
static D3DTRANSFORMSTATETYPE ToD3DTransformType(TRANSFORM_TYPE eType);
static TRANSFORM_TYPE ToOETransformType(D3DTRANSFORMSTATETYPE eType);
static D3DCULL ToD3DCullMode(CULL_MODE_TYPE eType);
static CULL_MODE_TYPE ToOECullMode(D3DCULL eType);
static D3DFILLMODE ToD3DFillMode(FILL_MODE eType);
static FILL_MODE ToOEFillMode(D3DFILLMODE eType);
//static D3DTEXTUREFILTERTYPE ToD3DSampleFilter(OE_SAMPLE_FILTER eType);
//static OE_SAMPLE_FILTER ToOESampleFilter(D3DTEXTUREFILTERTYPE eType);
static D3DFORMAT ToD3DTexFmt(TEXTURE_FORMAT eFormat);
static TEXTURE_FORMAT ToOETexFmt(D3DFORMAT eFormat);
static uint ToD3DColorWriteChannel(uint nColorWriteChannel);
static uint ToOEColorWriteChannel(uint nColorWriteChannel);
static uint ToD3DClearScreenMask(uint nClearScreenMask);
static uint ToOEClearScreenMask(uint nClearScreenMask);
};
#endif // __OED3DUTIL_H__
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
] | [
[
[
1,
59
]
]
] |
de9a329b3bca2b255ce54e1034bea098b18bd8c7 | 5e72c94a4ea92b1037217e31a66e9bfee67f71dd | /old/src/TestDetailDialog.h | 38ae3b3a70252e4d49a3bd1f138a18202d66084c | [] | no_license | stein1/bbk | 1070d2c145e43af02a6df14b6d06d9e8ed85fc8a | 2380fc7a2f5bcc9cb2b54f61e38411468e1a1aa8 | refs/heads/master | 2021-01-17T23:57:37.689787 | 2011-05-04T14:50:01 | 2011-05-04T14:50:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 565 | h | #pragma once
#include "includes.h"
#include <wx/gbsizer.h>
class ResultLog;
class TestDetailDialog : public wxDialog
{
public:
TestDetailDialog(wxWindow* parent,
wxWindowID id,
const wxString title,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxDEFAULT_DIALOG_STYLE,
const wxString name = wxT("dialogBox"));
~TestDetailDialog(void);
virtual void RefreshList(int row) = 0;
protected:
wxGridBagSizer *m_SizerMain;
wxListCtrl *m_List;
ResultLog *m_rl;
};
| [
"[email protected]"
] | [
[
[
1,
24
]
]
] |
6591a54ee800b314843082bac26d0de53f9f9cfc | 444a151706abb7bbc8abeb1f2194a768ed03f171 | /trunk/CompilerSource/parser/parser_components.h | 74ff0405e32cb8a1b3ed1f03a82681d31fdcca53 | [] | no_license | amorri40/Enigma-Game-Maker | 9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6 | c6b701201b6037f2eb57c6938c184a5d4ba917cf | refs/heads/master | 2021-01-15T11:48:39.834788 | 2011-11-22T04:09:28 | 2011-11-22T04:09:28 | 1,855,342 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,771 | h | /********************************************************************************\
** **
** Copyright (C) 2008 Josh Ventura **
** **
** This file is a part of the ENIGMA Development Environment. **
** **
** **
** ENIGMA 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 3 of the license or any later version. **
** **
** This application and its source code is distributed AS-IS, 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 recieved a copy of the GNU General Public License along **
** with this code. If not, see <http://www.gnu.org/licenses/> **
** **
** ENIGMA is an environment designed to create games and other programs with a **
** high-level, fully compilable language. Developers of ENIGMA or anything **
** associated with ENIGMA are in no way responsible for its users or **
** applications created by its users, or damages caused by the environment **
** or programs made in the environment. **
** **
\********************************************************************************/
typedef size_t pt; //Use size_t as our pos type; this will prevent errors with size_t's like std::string::npos
#include "../general/darray.h"
extern map<string,char> edl_tokens;
int parser_ready_input(string&,string&,unsigned int&,varray<string>&);
int parser_fix_templates(string &code,pt pos,pt spos,string *synt);
void parser_add_semicolons(string &code,string &synt);
void print_the_fucker(string code,string synt);
int parser_reinterpret(string&,string&);
int dropscope();
int quickscope();
int initscope(string name);
int quicktype(unsigned flags, string name);
| [
"[email protected]"
] | [
[
[
1,
44
]
]
] |
004e7600888fc5a0a13d143fa4c7fade4360a50f | bfe8eca44c0fca696a0031a98037f19a9938dd26 | /libjingle-0.4.0/talk/base/diskcache_win32.h | a084f9b678e4b85d4a8f8e6a3981fbaea86bd329 | [
"BSD-3-Clause"
] | permissive | luge/foolject | a190006bc0ed693f685f3a8287ea15b1fe631744 | 2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c | refs/heads/master | 2021-01-10T07:41:06.726526 | 2011-01-21T10:25:22 | 2011-01-21T10:25:22 | 36,303,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | h | //
// DiskCacheWin32.h
// Macshroom
//
// Created by Moishe Lettvin on 11/7/06.
// Copyright (C) 2006 Google Inc. All rights reserved.
//
//
#ifndef TALK_BASE_DISKCACHEWIN32_H__
#define TALK_BASE_DISKCACHEWIN32_H__
#include "talk/base/diskcache.h"
namespace talk_base {
class DiskCacheWin32 : public DiskCache {
protected:
virtual bool InitializeEntries();
virtual bool PurgeFiles();
virtual bool FileExists(const std::string& filename) const;
virtual bool DeleteFile(const std::string& filename) const;
};
}
#endif // TALK_BASE_DISKCACHEWIN32_H__
| [
"[email protected]@756bb6b0-a119-0410-8338-473b6f1ccd30"
] | [
[
[
1,
28
]
]
] |
3039f5fd22484d163afbbd48f5c88350c4efab14 | 3276915b349aec4d26b466d48d9c8022a909ec16 | /c++/数组和指针,引用/动态定义数组.cpp | 5251424dfd5cbf183f01cb2d0e8e88a4d608c779 | [] | no_license | flyskyosg/3dvc | c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82 | 0279b1a7ae097b9028cc7e4aa2dcb67025f096b9 | refs/heads/master | 2021-01-10T11:39:45.352471 | 2009-07-31T13:13:50 | 2009-07-31T13:13:50 | 48,670,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 176 | cpp | #include<iostream.h>
void main( )
{
int *p;
p=new int;
cout<<"shuru";
cin>>*p;
int *a=new int[*p];
delete p;
a[0]=1;cout<<a[0];
delete a;
}
| [
"[email protected]"
] | [
[
[
1,
14
]
]
] |
235a31c9e9f512d132084f0d17c87e0487845bf8 | bd89d3607e32d7ebb8898f5e2d3445d524010850 | /connectivitylayer/isce/isirouter_dll/src/isithreadcontainer.cpp | 944c3252274adda249b17fcc8a101cdd1a0b1c17 | [] | no_license | wannaphong/symbian-incubation-projects.fcl-modemadaptation | 9b9c61ba714ca8a786db01afda8f5a066420c0db | 0e6894da14b3b096cffe0182cedecc9b6dac7b8d | refs/heads/master | 2021-05-30T05:09:10.980036 | 2010-10-19T10:16:20 | 2010-10-19T10:16:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,143 | cpp | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#include <kernel.h> // For Kern
#include "isiroutertrace.h" // For C_TRACE, ASSERT_RESET.. and fault codes
#include "isiinternaldefs.h" // For KAmountOfKernelThreads...
#include "isithreadcontainer.h" // For DISIThreadContainer
// Faults
enum TISIThreadContainerFaults
{
EISIThreadContainerDfcQAllocFailure = 0x01,
EISIThreadContainerDfcQAllocFailure1,
EISIThreadContainerUnknownThreadType,
EISIThreadContainerNULLThreadPtr,
EISIThreadContainerThreadNotFound,
EISIThreadContainerOverflow,
EISIThreadContainerOverflow1,
EISIThreadContainerUnderflow,
EISIThreadContainerUnderflow1,
};
_LIT8( KISIKernelClientThread, "ISIKernelClientThread" );
_LIT8( KISIUserClientThread, "ISIUserClientThread" );
const TInt KDefaultDfcThreadPriority( 27 );
const TUint8 KMaxThreadUsers( 255 );
const TUint8 KMaxThreadNameLength( 25 );
DISIThreadContainer::DISIThreadContainer()
{
C_TRACE( ( _T( "DISIThreadContainer::DISIThreadContainer>" ) ) );
TUint8 nameIndex = 0;
for( TUint8 i( 0 ); i < KAmountOfKernelThreads; i++ )
{
iNameTable[ nameIndex ] = HBuf8::New( KMaxThreadNameLength );
iNameTable[ nameIndex ]->Append( (&KISIKernelClientThread)->Ptr(), (&KISIKernelClientThread)->Length() );
iNameTable[ nameIndex ]->AppendNum( i, EDecimal );
Kern::DfcQCreate( iKClientDfcQueList[ i ], KDefaultDfcThreadPriority, iNameTable[ nameIndex ] );
ASSERT_RESET_ALWAYS( iKClientDfcQueList[ i ], ( EISIThreadContainerDfcQAllocFailure | EDISIThreadContainerTraceId << KClassIdentifierShift ) );
nameIndex++;
}
for( TUint8 i( 0 ); i < KAmountOfUserThreads; i++ )
{
iNameTable[ nameIndex ] = HBuf8::New( KMaxThreadNameLength );
iNameTable[ nameIndex ]->Append( (&KISIUserClientThread)->Ptr(), (&KISIUserClientThread)->Length() );
iNameTable[ nameIndex ]->AppendNum( i, EDecimal );
Kern::DfcQCreate( iUClientDfcQueList[ i ], KDefaultDfcThreadPriority, iNameTable[ nameIndex ] );
ASSERT_RESET_ALWAYS( iUClientDfcQueList[ i ], ( EISIThreadContainerDfcQAllocFailure1 | EDISIThreadContainerTraceId << KClassIdentifierShift ) );
nameIndex++;
}
C_TRACE( ( _T( "DISIThreadContainer::DISIThreadContainer<" ) ) );
}
DISIThreadContainer::~DISIThreadContainer()
{
C_TRACE( ( _T( "DISIThreadContainer::~DISIThreadContainer>" ) ) );
for( TUint8 i( 0 ); i < ( KAmountOfKernelThreads + KAmountOfUserThreads ); i++ )
{
if( iNameTable[ i ] )
{
delete iNameTable[ i ];
iNameTable[ i ] = NULL;
}
}
for( TUint8 i( 0 ); i < KAmountOfKernelThreads; i++ )
{
if( iKClientDfcQueList[ i ] )
{
delete iKClientDfcQueList[ i ];
iKClientDfcQueList[ i ] = NULL;
}
}
for( TUint8 i( 0 ); i < KAmountOfUserThreads; i++ )
{
if( iUClientDfcQueList[ i ] )
{
delete iUClientDfcQueList[ i ];
iUClientDfcQueList[ i ] = NULL;
}
}
C_TRACE( ( _T( "DISIThreadContainer::~DISIThreadContainer<" ) ) );
}
TDfcQue* DISIThreadContainer::AllocateThread( const MISIObjectRouterIf::TISIDfcQThreadType aType )
{
C_TRACE( ( _T( "DISIThreadContainer::AllocateThread %d>" ), aType ) );
TDfcQue* tmpPtr( NULL );
switch( aType )
{
case MISIObjectRouterIf::EISIKernelMainThread:
case MISIObjectRouterIf::EISIKernelRequestCompletionThread:
{
tmpPtr = ReserveKernelThread();
break;
}
case MISIObjectRouterIf::EISIUserMainThread:
case MISIObjectRouterIf::EISIUserRequestCompletionThread:
{
tmpPtr = ReserveUserThread();
break;
}
default:
{
ASSERT_RESET_ALWAYS( 0, ( EISIThreadContainerUnknownThreadType | EDISIThreadContainerTraceId << KClassIdentifierShift ) );
break;
}
}
ASSERT_RESET_ALWAYS( tmpPtr, ( EISIThreadContainerNULLThreadPtr | EDISIThreadContainerTraceId << KClassIdentifierShift ) );
C_TRACE( ( _T( "DISIThreadContainer::AllocateThread %d 0x%x<" ), aType, tmpPtr ) );
return tmpPtr;
}
TDfcQue* DISIThreadContainer::ReserveKernelThread()
{
C_TRACE( ( _T( "DISIThreadContainer::ReservekernelThread>" ) ) );
TUint8 clientCount = iKThreadOccupation[ 0 ];
TUint8 index = 0;
for( TUint8 i( 0 ) ; i < KAmountOfKernelThreads; i++ )
{
if( clientCount > iKThreadOccupation[ i ] )
{
clientCount = iKThreadOccupation[ i ];
index = i;
}
}
++iKThreadOccupation[ index ];
ASSERT_RESET_ALWAYS( iKThreadOccupation[ index ] <= KMaxThreadUsers, ( EISIThreadContainerOverflow | EDISIThreadContainerTraceId << KClassIdentifierShift ) );
C_TRACE( ( _T( "DISIThreadContainer::ReserveKernelThread 0x%x %d %d<" ), iKClientDfcQueList[ index ], iKThreadOccupation[ index ], index ) );
return iKClientDfcQueList[ index ];
}
TDfcQue* DISIThreadContainer::ReserveUserThread()
{
C_TRACE( ( _T( "DISIThreadContainer::ReserveUserThread>" ) ) );
TUint8 clientCount = iUThreadOccupation[ 0 ];
TUint8 index = 0;
for( TUint8 i( 0 ); i < KAmountOfUserThreads; i++ )
{
if( clientCount > iUThreadOccupation[ i ] )
{
clientCount = iUThreadOccupation[ i ];
index = i;
}
}
++iUThreadOccupation[ index ];
ASSERT_RESET_ALWAYS( iUThreadOccupation[ index ] <= KMaxThreadUsers, ( EISIThreadContainerOverflow1 | EDISIThreadContainerTraceId << KClassIdentifierShift ) );
C_TRACE( ( _T( "DISIThreadContainer::ReserveUserThread 0x%x %d %d<" ), iUClientDfcQueList[ index ], iUThreadOccupation[ index ], index ) );
return iUClientDfcQueList[ index ];
}
void DISIThreadContainer::DeallocateThread( TDfcQue* aThread )
{
C_TRACE( ( _T( "DISIThreadContainer::DeallocateThread 0x%x>" ), aThread ) );
TBool found( EFalse );
for( TUint8 i( 0 ) ; i < KAmountOfKernelThreads; i++ )
{
if( aThread == iKClientDfcQueList[ i ] )
{
--iKThreadOccupation[ i ];
ASSERT_RESET_ALWAYS( iKThreadOccupation[ i ] != KMaxThreadUsers, ( EISIThreadContainerUnderflow | EDISIThreadContainerTraceId << KClassIdentifierShift ) );
C_TRACE( ( _T( "DISIThreadContainer DeallocKThread 0x%x %d %d>" ), aThread, iKThreadOccupation[ i ], i ) );
found = ETrue;
break;
}
}
if( !found )
{
for( TUint8 i( 0 ) ; i < KAmountOfUserThreads; i++ )
{
if( aThread == iUClientDfcQueList[ i ] )
{
--iUThreadOccupation[ i ];
ASSERT_RESET_ALWAYS( iUThreadOccupation[ i ] != KMaxThreadUsers, ( EISIThreadContainerUnderflow1 | EDISIThreadContainerTraceId << KClassIdentifierShift ) );
C_TRACE( ( _T( "DISIThreadContainer DeallocUThread 0x%x %d %d>" ), aThread, iUThreadOccupation[ i ], i ) );
found = ETrue;
break;
}
}
}
ASSERT_RESET_ALWAYS( found, ( EISIThreadContainerThreadNotFound | EDISIThreadContainerTraceId << KClassIdentifierShift ) );
C_TRACE( ( _T( "DISIThreadContainer::DeallocateThread 0x%x<" ), aThread ) );
}
| [
"dalarub@localhost",
"mikaruus@localhost"
] | [
[
[
1,
101
],
[
103,
107
],
[
110,
113
],
[
116,
201
]
],
[
[
102,
102
],
[
108,
109
],
[
114,
115
]
]
] |
7ea6f355c8322b4701ba491ecceec0fb5aa94bd4 | bd89d3607e32d7ebb8898f5e2d3445d524010850 | /adaptationlayer/tsy/nokiatsy_dll/src/tssparser.cpp | 3412a6dc4f23f44a11d2a3dffcc6a999d237218c | [] | no_license | wannaphong/symbian-incubation-projects.fcl-modemadaptation | 9b9c61ba714ca8a786db01afda8f5a066420c0db | 0e6894da14b3b096cffe0182cedecc9b6dac7b8d | refs/heads/master | 2021-05-30T05:09:10.980036 | 2010-10-19T10:16:20 | 2010-10-19T10:16:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,613 | cpp | /*
* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
// INCLUDE FILES
#include "tssparser.h" // class definition file
#include "tsylogger.h"
#include "OstTraceDefinitions.h"
#ifdef OST_TRACE_COMPILER_IN_USE
#include "tssparserTraces.h"
#endif
// for TSY logging
// ============================ MEMBER FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// TSsParser::TSsParser()
// C++ default constructor can NOT contain any code, that
// might leave.
// -----------------------------------------------------------------------------
//
TSsParser::TSsParser()
{
TFLOGSTRING( "TSY: TSsParser::TSsParser" );
OstTrace0( TRACE_NORMAL, TSSPARSER_TSSPARSER_TD, "TSsParser::TSsParser" );
iSsOperation = SS_OPERATION_UNDEFINED;
iServiceCode = SS_UNKNOWN_SERVICE;
}
// -----------------------------------------------------------------------------
// TSsParser::Parse
// Parses a SS string
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt TSsParser::Parse( const TDesC& aServiceString )
{
TFLOGSTRING2( "TSY: TSsParser::Parse, servicestring: %S", &aServiceString );
OstTraceExt1( TRACE_NORMAL, TSSPARSER_PARSE_TD, "TSsParser::Parse;aServiceString=%S", aServiceString );
TInt error( KErrNone );
// at first check that service string is not too long
if( MAX_LENGTH_OF_SERVICE_STRING < aServiceString.Length( ) ||
0 >= aServiceString.Length( ) )
{
TFLOGSTRING( "TSY: TSsParser::Parse, error: service string too long or does not exist!" );
OstTrace0( TRACE_NORMAL, DUP1_TSSPARSER_PARSE_TD, "TSsParser::Parse, error: service string too long or does not exist!" );
error = KErrArgument;
}
else
{
// copy service string to member variable for parsing
iServiceString.Set( aServiceString );
// operation type: activation, deactivation, interrogation,
// registration or erasure
error = ExtractSsOperation( );
}
// If operation was parsed successfully, extract service code
if( KErrNone == error )
{
TPtrC tempBuffer;
ExtractPart( tempBuffer );
// convert service code to integer
iServiceCode = GetInt( tempBuffer );
TFLOGSTRING2( "TSY: TSsParser::Parse, service code: %d", iServiceCode );
OstTraceExt1( TRACE_NORMAL, DUP2_TSSPARSER_PARSE_TD, "TSsParser::Parse;iServiceCode=%hu", iServiceCode );
if( SS_UNKNOWN_SERVICE == iServiceCode )
{
error = KErrArgument;
TFLOGSTRING( "TSY: TSsParser::Parse, error: illegal sevice code!" );
OstTrace0( TRACE_NORMAL, DUP3_TSSPARSER_PARSE_TD, "TSsParser::Parse, error: illegal sevice code!" );
}
}
// service code was parsed successfully, extract supplementary infos a,b,c
if( KErrNone == error )
{
TPtrC tempSiBuffer[MAX_NUM_OF_SUPPLEMENTARY_INFOS];
TInt i( 0 );
TCharacter character( ECharacterIllegal );
// 3 supplementary info fields may exists, separated by '*'
// and ended by '#'.
// possible combinations for supplementary info:
// *SIA*SIB*SIC#, *SIA*SIB#, *SIA**SIC#, *SIA#, **SIB*SIC#,
// **SIB#, ***SIC#, # (from 3GPP TS 22.030)
for( i = 0; i <= MAX_NUM_OF_SUPPLEMENTARY_INFOS; i++ )
{
character = ExtractSeparator( );
if( ECharacterSeparator == character &&
i < MAX_NUM_OF_SUPPLEMENTARY_INFOS ) // last mark can't be '*'
{
ExtractPart( tempSiBuffer[i] );
}
else if( ECharacterEndMark == character
&& !iServiceString.Length() )
{
// this was the end of string, and there's no more to be parsed
break;
}
else
{
error = KErrArgument;
TFLOGSTRING( "TSY: TSsParser::Parse, error: illegal end mark!" );
OstTrace0( TRACE_NORMAL, DUP4_TSSPARSER_PARSE_TD, "TSsParser::Parse, error: illegal end mark!" );
break;
}
}
iSupplementaryInfoA.Set( tempSiBuffer[0] );
iSupplementaryInfoB.Set( tempSiBuffer[1] );
iSupplementaryInfoC.Set( tempSiBuffer[2] );
}
TFLOGSTRING2( "TSY: TSsParser::Parse, SS code: %d", iSsOperation );
OstTraceExt1( TRACE_NORMAL, DUP5_TSSPARSER_PARSE_TD, "TSsParser::Parse;iSsOperation=%hhu", iSsOperation );
TFLOGSTRING2( "TSY: TSsParser::Parse, SS code: %d", iServiceCode );
OstTraceExt1( TRACE_NORMAL, DUP6_TSSPARSER_PARSE_TD, "TSsParser::Parse;iServiceCode=%hu", iServiceCode );
TFLOGSTRING2( "TSY: TSsParser::Parse, SS info A: %S", &iSupplementaryInfoA );
OstTraceExt1( TRACE_NORMAL, DUP7_TSSPARSER_PARSE_TD, "TSsParser::Parse;iSupplementaryInfoA=%S", iSupplementaryInfoA );
TFLOGSTRING2( "TSY: TSsParser::Parse, SS info B: %S", &iSupplementaryInfoB );
OstTraceExt1( TRACE_NORMAL, DUP8_TSSPARSER_PARSE_TD, "TSsParser::Parse;iSupplementaryInfoB=%S", iSupplementaryInfoB );
TFLOGSTRING2( "TSY: TSsParser::Parse, SS info C: %S", &iSupplementaryInfoC );
OstTraceExt1( TRACE_NORMAL, DUP9_TSSPARSER_PARSE_TD, "TSsParser::Parse;iSupplementaryInfoC=%S", iSupplementaryInfoC );
TFLOGSTRING2( "TSY: TSsParser::Parse, SS string left: %S", &iServiceString );
OstTraceExt1( TRACE_NORMAL, DUP10_TSSPARSER_PARSE_TD, "TSsParser::Parse;iServiceString=%S", iServiceString );
return error;
}
// -----------------------------------------------------------------------------
// TSsParser::GetSsOperation
// Gets ss operation type
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
void TSsParser::GetSsOperation( TUint8& aSsOperation ) const
{
TFLOGSTRING( "TSY: TSsParser::GetSsOperation" );
OstTrace0( TRACE_NORMAL, TSSPARSER_GETSSOPERATION_TD, "TSsParser::GetSsOperation" );
aSsOperation = iSsOperation;
}
// -----------------------------------------------------------------------------
// TSsParser::GetServiceCode
// Gets ss code
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
void TSsParser::GetServiceCode( TUint16& aServiceCode ) const
{
TFLOGSTRING("TSY: TSsParser::GetServiceCode" );
OstTrace0( TRACE_NORMAL, TSSPARSER_GETSERVICECODE_TD, "TSsParser::GetServiceCode" );
aServiceCode = iServiceCode;
}
// -----------------------------------------------------------------------------
// TSsParser::GetServiceInfo
// Gets SS infos a,b and c. If does not exist, empty descriptor is returned
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
void TSsParser::GetServiceInfo(
TPtrC& aSupplementaryInfoA,
TPtrC& aSupplementaryInfoB,
TPtrC& aSupplementaryInfoC ) const
{
TFLOGSTRING( "TSY: TSsParser::GetServiceInfo" );
OstTrace0( TRACE_NORMAL, TSSPARSER_GETSERVICEINFO_TD, "TSsParser::GetServiceInfo" );
aSupplementaryInfoA.Set( iSupplementaryInfoA );
aSupplementaryInfoB.Set( iSupplementaryInfoB );
aSupplementaryInfoC.Set( iSupplementaryInfoC );
}
// -----------------------------------------------------------------------------
// TSsParser::ExtractSsOperation
// Parses operation type ( 1 or 2 first elements from service string )
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TUint8 TSsParser::ExtractSsOperation( )
{
TFLOGSTRING( "TSY: TSsParser::ExtractSsOperation" );
OstTrace0( TRACE_NORMAL, TSSPARSER_EXTRACTSSOPERATION_TD, "TSsParser::ExtractSsOperation" );
TInt error( KErrNone );
// SS operation is one or two first characters in the service string
if( iServiceString.Left( 2 ) == KSsOperationErasure )
{
iSsOperation = SS_ERASURE; // unregister and deactivate
iServiceString.Set( iServiceString.Mid( 2 ) ); // extract remaining part
TFLOGSTRING2( "TSY: TSsParser::ExtractSsOperation, SS operation: erasure (%d)", iSsOperation );
OstTraceExt1( TRACE_NORMAL, DUP1_TSSPARSER_EXTRACTSSOPERATION_TD, "TSsParser::ExtractSsOperation;SS operation: erasure (%hhu)", iSsOperation );
}
else if( iServiceString.Left( 2 ) == KSsOperationInterrogation )
{
iSsOperation = SS_INTERROGATION; // check status
iServiceString.Set( iServiceString.Mid ( 2 ) );
TFLOGSTRING2( "TSY: TSsParser::ExtractSsOperation, SS operation: interrogation (%d)", iSsOperation );
OstTraceExt1( TRACE_NORMAL, DUP2_TSSPARSER_EXTRACTSSOPERATION_TD, "TSsParser::ExtractSsOperation;SS operation: interrogation (%hhu)", iSsOperation );
}
else if( iServiceString.Left( 2 ) == KSsOperationRegistration )
{
iSsOperation = SS_REGISTRATION; // register and activate
iServiceString.Set( iServiceString.Mid( 2 ) );
TFLOGSTRING2( "TSY: TSsParser::ExtractSsOperation, SS operation: registration (%d)", iSsOperation );
OstTraceExt1( TRACE_NORMAL, DUP3_TSSPARSER_EXTRACTSSOPERATION_TD, "TSsParser::ExtractSsOperation;SS operation: registration (%hhu)", iSsOperation );
}
else if( iServiceString.Left( 1 ) == KSsOperationActivation )
{
iSsOperation = SS_ACTIVATION; // activate
iServiceString.Set( iServiceString.Mid( 1 ) );
TFLOGSTRING2( "TSY: TSsParser::ExtractSsOperation, SS operation: activation (%d)", iSsOperation );
OstTraceExt1( TRACE_NORMAL, DUP4_TSSPARSER_EXTRACTSSOPERATION_TD, "TSsParser::ExtractSsOperation;SS operation: activation (%hhu)", iSsOperation );
}
else if( iServiceString.Left( 1 ) == KSsOperationDeactivation )
{
iSsOperation = SS_DEACTIVATION; // unregister
iServiceString.Set( iServiceString.Mid( 1 ) );
TFLOGSTRING2( "TSY: TSsParser::ExtractSsOperation, SS operation: deactivation (%d)", iSsOperation );
OstTraceExt1( TRACE_NORMAL, DUP5_TSSPARSER_EXTRACTSSOPERATION_TD, "TSsParser::ExtractSsOperation;SS operation: deactivation (%hhu)", iSsOperation );
}
else
{
iSsOperation = SS_OPERATION_UNDEFINED;
TFLOGSTRING2( "TSY: TSsParser::ExtractSsOperation, SS operation: undefined (%d)", iSsOperation );
OstTraceExt1( TRACE_NORMAL, DUP6_TSSPARSER_EXTRACTSSOPERATION_TD, "TSsParser::ExtractSsOperation;SS operation: undefined (%hhu)", iSsOperation );
error = KErrArgument;
}
return error;
}
// -----------------------------------------------------------------------------
// TSsParser::ExtractPart
// Extras individual parts from service string
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
void TSsParser::ExtractPart( TPtrC& aPart )
{
TFLOGSTRING( "TSY: TSsParser::ExtractPart" );
OstTrace0( TRACE_NORMAL, TSSPARSER_EXTRACTPART_TD, "TSsParser::ExtractPart" );
TUint i( 0 );
// service code and supplementary info ends to '*' or '#'
// if there is no data to be extracted, empty buffer is returned.
while( i < iServiceString.Length( ) &&
iServiceString[i] != '*' &&
iServiceString[i] != '#' )
{
i++;
}
// extracted part is returned as reference variable
aPart.Set( iServiceString.Left( i ) );
TFLOGSTRING2( "TSY: TSsParser::ExtractPart, extracted string: %S", &aPart );
OstTraceExt1( TRACE_NORMAL, DUP1_TSSPARSER_EXTRACTPART_TD, "TSsParser::ExtractPart;aPart=%S", aPart );
// set remaining part of service string
iServiceString.Set( iServiceString.Mid( i ) );
}
// -----------------------------------------------------------------------------
// TSsParser::ExtractSeparator
// Extracts separator marks from service string
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TCharacter TSsParser::ExtractSeparator( )
{
TFLOGSTRING( "TSY: TSsParser::ExtractSeparator" );
OstTrace0( TRACE_NORMAL, TSSPARSER_EXTRACTSEPARATOR_TD, "TSsParser::ExtractSeparator" );
TCharacter mark( ECharacterIllegal );
// There should be at least the end mark '#' left in string
if( iServiceString.Length() > 0 )
{
if( '#' == iServiceString[0] )
{
TFLOGSTRING( "TSY: TSsParser::ExtractSeparator: end mark '#'" );
OstTrace0( TRACE_NORMAL, DUP1_TSSPARSER_EXTRACTSEPARATOR_TD, "TSsParser::ExtractSeparator, end mark '#'" );
mark = ECharacterEndMark;
}
else if( '*' == iServiceString[0] )
{
TFLOGSTRING( "TSY: TSsParser::ExtractSeparator: separator mark '*'" );
OstTrace0( TRACE_NORMAL, DUP2_TSSPARSER_EXTRACTSEPARATOR_TD, "TSsParser::ExtractSeparator, separator mark '*'" );
mark = ECharacterSeparator;
}
// no else
iServiceString.Set( iServiceString.Mid( 1 ) );
}
else // end mark was missing
{
TFLOGSTRING( "TSY: TSsParser::ExtractSeparator: illegal ss string, no end mark!" );
OstTrace0( TRACE_NORMAL, DUP3_TSSPARSER_EXTRACTSEPARATOR_TD, "TSsParser::ExtractSeparator, illegal ss string, no end mark!" );
}
return mark;
}
// -----------------------------------------------------------------------------
// TSsParser::GetInt
// Convert descriptor to integer
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt TSsParser::GetInt( const TDesC& aString )
{
TFLOGSTRING( "TSY: TSsParser::GetInt" );
OstTrace0( TRACE_NORMAL, TSSPARSER_GETINT_TD, "TSsParser::GetInt" );
TInt code;
if( TLex( aString ).Val( code ) != KErrNone)
{
code = SS_ALL_TELE_AND_BEARER;
}
return code;
}
// End of File
| [
"dalarub@localhost",
"[email protected]",
"mikaruus@localhost"
] | [
[
[
1,
22
],
[
24,
24
],
[
26,
39
],
[
41,
54
],
[
56,
63
],
[
65,
84
],
[
86,
90
],
[
92,
123
],
[
125,
133
],
[
135,
135
],
[
137,
137
],
[
139,
139
],
[
141,
141
],
[
143,
143
],
[
145,
158
],
[
160,
172
],
[
174,
189
],
[
191,
205
],
[
207,
214
],
[
216,
221
],
[
223,
228
],
[
230,
235
],
[
237,
242
],
[
244,
248
],
[
250,
265
],
[
267,
278
],
[
280,
293
],
[
295,
301
],
[
303,
307
],
[
309,
316
],
[
318,
331
],
[
333,
344
]
],
[
[
23,
23
],
[
25,
25
]
],
[
[
40,
40
],
[
55,
55
],
[
64,
64
],
[
85,
85
],
[
91,
91
],
[
124,
124
],
[
134,
134
],
[
136,
136
],
[
138,
138
],
[
140,
140
],
[
142,
142
],
[
144,
144
],
[
159,
159
],
[
173,
173
],
[
190,
190
],
[
206,
206
],
[
215,
215
],
[
222,
222
],
[
229,
229
],
[
236,
236
],
[
243,
243
],
[
249,
249
],
[
266,
266
],
[
279,
279
],
[
294,
294
],
[
302,
302
],
[
308,
308
],
[
317,
317
],
[
332,
332
]
]
] |
ee534032fd85bfe2797f67fe2753fc1287e5d062 | fceff9260ff49d2707060241b6f9b927b97db469 | /ZombieGentlemen_SeniorProject/player.cpp | ca4ae71327a6d2829d25560323a71d996a70ce7e | [] | 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 | 7,786 | cpp | #include "player.h"
player::player()
{
m_object = NULL;
soundMgr = NULL;
type = entityPlayer;
timer = 0;
randomIdle = 0;
jumpCounter = 0;
armorBlink = false;
keyBlink =false;
hasKey = false;
}
player::~player()
{
}
void player::move(float x, float y)
{
if(alive)
{
m_object->getPhysics()->walkingOn();
if(x)
if((x < 0 && m_object->getPhysics()->canMoveLeft())
|| (x > 0 && m_object->getPhysics()->canMoveRight()))
{
m_object->getPhysics()->setXVelocity(x);
soundMgr->playSound(soundWalk);
}
if(y)
{
m_object->getPhysics()->setYVelocity(y);
if(m_object->getPhysics()->isjumpingAllowed())
{
jumpCounter++;
if(jumpCounter >= jumpInterval)
{
if(armor)
soundMgr->playSound(soundArmorJump2);
else
soundMgr->playSound(soundJump2);
jumpCounter = 0;
jumpInterval = 4 + rand()%4;
}
else
{
if(armor)
soundMgr->playSound(soundArmorJump1);
else
soundMgr->playSound(soundJump1);
}
}
}
}
}
void player::animate()
{
switch(state)
{
case walkingRight:
switch(sprites)
{
case playerSprite1:
if(!armor)
m_object->setSprite(0, 0);
else
m_object->setSprite(2, 0);
sprites = playerSprite2;
break;
case playerSprite2:
if(!armor)
m_object->setSprite(0, 1);
else
m_object->setSprite(2, 1);
sprites = playerSprite3;
break;
case playerSprite3:
if(!armor)
m_object->setSprite(0, 2);
else
m_object->setSprite(2, 2);
sprites = playerSprite4;
break;
case playerSprite4:
if(!armor)
m_object->setSprite(0, 3);
else
m_object->setSprite(2, 3);
sprites = playerSprite1;
break;
}
break;
case walkingLeft:
switch(sprites)
{
case playerSprite1:
if(!armor)
m_object->setSprite(1, 0);
else
m_object->setSprite(3, 0);
sprites = playerSprite2;
break;
case playerSprite2:
if(!armor)
m_object->setSprite(1, 1);
else
m_object->setSprite(3, 1);
sprites = playerSprite3;
break;
case playerSprite3:
if(!armor)
m_object->setSprite(1, 2);
else
m_object->setSprite(3, 2);
sprites = playerSprite4;
break;
case playerSprite4:
if(!armor)
m_object->setSprite(1, 3);
else
m_object->setSprite(3, 3);
sprites = playerSprite1;
break;
}
break;
case jumping:
if(m_object->getPhysics()->getXVelocity() > 0)
{
if(!armor)
m_object->setSprite(0,4);
else
m_object->setSprite(2,4);
}
else if(m_object->getPhysics()->getXVelocity() < 0)
{
if(!armor)
m_object->setSprite(1,4);
else
m_object->setSprite(3,4);
}
break;
case idle:
if(randomIdle <= 0)
{
randomIdle = 1 + ( (float)rand( ) / (float)RAND_MAX ) * 3;
sprites = (enum playerSprite)(rand() % 5);
}
switch(sprites)
{
case playerSprite1:
if(!armor)
m_object->setSprite(4, 0);
else
m_object->setSprite(5, 0);
break;
case playerSprite2:
if(!armor)
m_object->setSprite(4, 1);
else
m_object->setSprite(5, 1);
break;
case playerSprite3:
if(!armor)
m_object->setSprite(4, 2);
else
m_object->setSprite(5, 2);
break;
case playerSprite4:
if(!armor)
m_object->setSprite(4, 3);
else
m_object->setSprite(5, 3);
break;
case playerSprite5:
if(!armor)
m_object->setSprite(4, 4);
else
m_object->setSprite(5, 4);
break;
}
break;
case dying:
if(timer < 0.1f)
sprites = playerSprite1;
else if(timer < 0.2f)
sprites = playerSprite2;
else if(timer < 0.5f)
sprites = playerSprite3;
else sprites = playerSprite4;
switch(sprites)
{
case playerSprite1:
m_object->setSprite(6, 0);
break;
case playerSprite2:
m_object->setSprite(6, 1);
break;
case playerSprite3:
m_object->setSprite(6, 2);
break;
case playerSprite4:
m_object->setSprite(6, 3);
break;
}
break;
case dead:
m_object->setSprite(6, 4);
break;
}
}
void player::update(float timePassed)
{
bool spriteChange = false;
if(!alive)
{
if(state != dead)
{
timer += timePassed;
if(timer < 1.2f)
{
if(state != dying && state != dead)
{
bounce();
}
if(state != dying)
{
state = dying;
soundMgr->playSound(soundDeath1 + (rand()%3));
spriteChange = true;
}
}
else
{
if(state != dead)
{
state = dead;
spriteChange = true;
}
timer = 0;
}
}
}
else
{
timer += timePassed;
if(randomIdle > 0)
{
randomIdle -= timePassed;
}
if(m_object->getPhysics()->isWalking())
{
if(m_object->getPhysics()->getXVelocity() > 0)
{
if(state != walkingRight)
{
state = walkingRight;
spriteChange = true;
}
}
else
{
if(state != walkingLeft)
{
state = walkingLeft;
spriteChange = true;
}
}
}
else
{
if(state != idle)
{
state = idle;
spriteChange = true;
}
}
if(m_object->getPhysics()->getYVelocity() > 0)
{
if(state != jumping)
{
state = jumping;
spriteChange = true;
}
}
}
if(spriteChange || timer >= 0.15f)
{
if(spriteChange)
sprites = playerSprite1;
animate();
if(state != dying)
timer = 0;
}
if(armorBlink)
{
armorTimeout -= timePassed;
if(armorTimeout < 0) // armorTimeout has expired
{
if(armorLoss)
armor = false;
armorBlink = false;
armorTimeout = 0;
}
}
if(keyBlink)
{
keyTimeout -= timePassed;
if(keyTimeout < 0) // armorTimeout has expired
{
keyBlink = false;
keyTimeout = 0;
}
}
}
void player::reset()
{
timer = 0;
state = idle;
m_object->setSprite(0,0);
m_object->getCollHistory()->resetList();
alive = true;
armor = false;
hasKey = false;
jumpCounter = 0;
}
void player::bounce()
{
float deathXVel = m_object->getPhysics()->getXVelocity();
float deathYVel = m_object->getPhysics()->getYVelocity();
m_object->getPhysics()->setXVelocity(deathXVel * -3);
m_object->getPhysics()->setYVelocity(10);
}
void player::removeArmor()
{
if(armor)
{
if(!armorBlink)
{
armorBlink = true;
armorLoss = true;
armorTimeout = 2.0f;
soundMgr->playSound(soundArmorLose1);
jumpCounter = 0;
}
}
}
void player::armorPickup()
{
if(!armor)
{
if(!armorBlink)
{
armorBlink = true;
armorLoss = false;
armor = true;
armorTimeout = 2.0f;
soundMgr->playSound(soundArmorPickup1 + (rand()%2));
jumpCounter = 0;
}
}
}
bool player::getAmorBlink(){return armorBlink;}
void player::flip()
{
switch(state)
{
case walkingRight:
state = walkingLeft;
break;
case walkingLeft:
state = walkingRight;
break;
}
}
void player::setSound(sound * a_soundMgr){soundMgr = a_soundMgr;}
void player::keyPickup()
{
if(!hasKey)
{
hasKey = true;
if(!keyBlink)
{
keyBlink = true;
keyTimeout = 2.0f;
// TODO: play key pickup sound
//soundMgr->playSound(soundArmorPickup1 + (rand()%2));
}
}
}
void player::removeKey()
{
if(hasKey)
{
hasKey = false;
if(!keyBlink)
{
keyBlink = true;
keyTimeout = 2.0f;
// TODO: play door open sound
//soundMgr->playSound(soundArmorLose1);
}
}
}
bool player::getKeyBlink(){return keyBlink;}
bool player::playerHasKey(){return hasKey;}
void player::setDirection(char dir)
{
switch(dir)
{
case 'l': state = walkingLeft;
break;
case'r': state = walkingRight;
break;
default:
break;
}
} | [
"[email protected]@66a8e42f-0ee8-26ea-976e-e3172d02aab5",
"[email protected]@66a8e42f-0ee8-26ea-976e-e3172d02aab5"
] | [
[
[
1,
62
],
[
67,
67
],
[
75,
75
],
[
83,
83
],
[
91,
91
],
[
100,
101
],
[
106,
106
],
[
114,
114
],
[
122,
122
],
[
130,
130
],
[
139,
156
],
[
158,
162
],
[
166,
166
],
[
172,
172
],
[
178,
178
],
[
184,
184
],
[
190,
190
],
[
199,
206
],
[
223,
223
],
[
225,
225
],
[
227,
227
],
[
229,
441
]
],
[
[
63,
66
],
[
68,
74
],
[
76,
82
],
[
84,
90
],
[
92,
99
],
[
102,
105
],
[
107,
113
],
[
115,
121
],
[
123,
129
],
[
131,
138
],
[
157,
157
],
[
163,
165
],
[
167,
171
],
[
173,
177
],
[
179,
183
],
[
185,
189
],
[
191,
198
],
[
207,
222
],
[
224,
224
],
[
226,
226
],
[
228,
228
]
]
] |
4e010c435654b2859ff6807f2d97f5ff9ccf2cd2 | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /aluminizerFPGA/Al/voltagesAl.h | 124253dd7e4d836694eff4fba2b8094218ac2a16 | [
"LicenseRef-scancode-public-domain"
] | permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,463 | h | #ifndef VOLTAGESAL_H_
#define VOLTAGESAL_H_
#include "../voltagesI.h"
#define NUM_OUT_VOLTAGES (11)
class rp_ao;
//! Interface to control trap voltages and E-fields
class voltagesAl : public voltagesI
{
public:
voltagesAl(list_t* exp_list, const std::string& name);
virtual ~voltagesAl() {}
virtual void rampDownXtallize();
virtual void rampUpXtallize();
//! called after parameters have been updated
virtual void updateParams();
virtual void set_voltage(unsigned iChannel, double V);
virtual double get_voltage(unsigned iChannel);
virtual unsigned remote_action(const char* s);
virtual void voltagesForSetting(unsigned iSetting, bool bHV, my_matrix& ao_new);
virtual void set_voltages(const my_matrix& ao_new);
void updateGUI();
//! ramps from current voltages to those specified by the current_settings column
bool updateVoltages(bool bForceUpdate, unsigned ramp_steps=1, unsigned dwell=0, unsigned cooling=0);
void updateInverseMatrices();
virtual void rampTo(unsigned settings_id, unsigned come_back, bool bUpdateGUI);
void dump();
protected:
rp_bool NoUpdates, Debug;
rp_bool XtallizeReorder;
rp_unsigned XtallizeSettings;
rp_matrix VcerfExy, VcerfEhv;
rp_matrix Eall;
std::vector<rp_ao*> ao_lcd;
my_matrix ao, Vcerf_old;
unsigned current_settings; //column # of current voltage settings
};
#endif /*VOLTAGESAL_H_*/
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
] | [
[
[
1,
54
]
]
] |
8f6b5fefe1098a8c7b1e89f34e3974b5f56a7af2 | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /cryptopp/factory.h | 5b5d189ebc0e6728f25334a30df130c60f117e03 | [
"LicenseRef-scancode-cryptopp",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | 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 | 4,360 | h | #ifndef CRYPTOPP_OBJFACT_H
#define CRYPTOPP_OBJFACT_H
#include "cryptlib.h"
#include <map>
#include <vector>
NAMESPACE_BEGIN(CryptoPP)
//! _
template <class AbstractClass>
class ObjectFactory
{
public:
virtual AbstractClass * CreateObject() const =0;
};
//! _
template <class AbstractClass, class ConcreteClass>
class DefaultObjectFactory : public ObjectFactory<AbstractClass>
{
public:
AbstractClass * CreateObject() const
{
return new ConcreteClass;
}
};
//! _
template <class AbstractClass, int instance=0>
class ObjectFactoryRegistry
{
public:
class FactoryNotFound : public Exception
{
public:
FactoryNotFound(const char *name) : Exception(OTHER_ERROR, std::string("ObjectFactoryRegistry: could not find factory for algorithm ") + name) {}
};
~ObjectFactoryRegistry()
{
for (CPP_TYPENAME Map::iterator i = m_map.begin(); i != m_map.end(); ++i)
{
delete (ObjectFactory<AbstractClass> *)i->second;
i->second = NULL;
}
}
void RegisterFactory(const std::string &name, ObjectFactory<AbstractClass> *factory)
{
m_map[name] = factory;
}
const ObjectFactory<AbstractClass> * GetFactory(const char *name) const
{
CPP_TYPENAME Map::const_iterator i = m_map.find(name);
return i == m_map.end() ? NULL : (ObjectFactory<AbstractClass> *)i->second;
}
AbstractClass *CreateObject(const char *name) const
{
const ObjectFactory<AbstractClass> *factory = GetFactory(name);
if (!factory)
throw FactoryNotFound(name);
return factory->CreateObject();
}
// Return a vector containing the factory names. This is easier than returning an iterator.
// from Andrew Pitonyak
std::vector<std::string> GetFactoryNames() const
{
std::vector<std::string> names;
CPP_TYPENAME Map::const_iterator iter;
for (iter = m_map.begin(); iter != m_map.end(); ++iter)
names.push_back(iter->first);
return names;
}
CRYPTOPP_NOINLINE static ObjectFactoryRegistry<AbstractClass, instance> & Registry(CRYPTOPP_NOINLINE_DOTDOTDOT);
private:
// use void * instead of ObjectFactory<AbstractClass> * to save code size
typedef std::map<std::string, void *> Map;
Map m_map;
};
template <class AbstractClass, int instance>
ObjectFactoryRegistry<AbstractClass, instance> & ObjectFactoryRegistry<AbstractClass, instance>::Registry(CRYPTOPP_NOINLINE_DOTDOTDOT)
{
static ObjectFactoryRegistry<AbstractClass, instance> s_registry;
return s_registry;
}
template <class AbstractClass, class ConcreteClass, int instance = 0>
struct RegisterDefaultFactoryFor {
RegisterDefaultFactoryFor(const char *name=NULL)
{
// BCB2006 workaround
std::string n = name ? std::string(name) : std::string(ConcreteClass::StaticAlgorithmName());
ObjectFactoryRegistry<AbstractClass, instance>::Registry().
RegisterFactory(n, new DefaultObjectFactory<AbstractClass, ConcreteClass>);
}};
template <class SchemeClass>
void RegisterAsymmetricCipherDefaultFactories(const char *name=NULL, SchemeClass *dummy=NULL)
{
RegisterDefaultFactoryFor<PK_Encryptor, CPP_TYPENAME SchemeClass::Encryptor>((const char *)name);
RegisterDefaultFactoryFor<PK_Decryptor, CPP_TYPENAME SchemeClass::Decryptor>((const char *)name);
}
template <class SchemeClass>
void RegisterSignatureSchemeDefaultFactories(const char *name=NULL, SchemeClass *dummy=NULL)
{
RegisterDefaultFactoryFor<PK_Signer, CPP_TYPENAME SchemeClass::Signer>((const char *)name);
RegisterDefaultFactoryFor<PK_Verifier, CPP_TYPENAME SchemeClass::Verifier>((const char *)name);
}
template <class SchemeClass>
void RegisterSymmetricCipherDefaultFactories(const char *name=NULL, SchemeClass *dummy=NULL)
{
RegisterDefaultFactoryFor<SymmetricCipher, CPP_TYPENAME SchemeClass::Encryption, ENCRYPTION>((const char *)name);
RegisterDefaultFactoryFor<SymmetricCipher, CPP_TYPENAME SchemeClass::Decryption, DECRYPTION>((const char *)name);
}
template <class SchemeClass>
void RegisterAuthenticatedSymmetricCipherDefaultFactories(const char *name=NULL, SchemeClass *dummy=NULL)
{
RegisterDefaultFactoryFor<AuthenticatedSymmetricCipher, CPP_TYPENAME SchemeClass::Encryption, ENCRYPTION>((const char *)name);
RegisterDefaultFactoryFor<AuthenticatedSymmetricCipher, CPP_TYPENAME SchemeClass::Decryption, DECRYPTION>((const char *)name);
}
NAMESPACE_END
#endif
| [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b",
"[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b"
] | [
[
[
1,
125
],
[
133,
135
]
],
[
[
126,
132
]
]
] |
a7e748b7b447bc2173d5586c69548ede9953c91b | 2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4 | /OUAN/OUAN/Src/Game/GameObject/GameObjectWater.h | ae425abbfe146a9195fdc7f2b33f344392f0e8f7 | [] | 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 | 5,414 | h | #ifndef GameObjectWaterH_H
#define GameObjectWaterH_H
#include "GameObject.h"
#include "../../Graphics/RenderComponent/RenderComponentWater.h"
#include "../../Graphics/RenderComponent/RenderComponentInitial.h"
#include "../../Graphics/RenderComponent/RenderComponentPositional.h"
#include "../../Physics/PhysicsComponent/PhysicsComponentVolumeConvex.h"
#include "../../Logic/LogicComponent/LogicComponentProp.h"
namespace OUAN
{
const std::string WATER_SOUND_SPLASH="splash";
/// Class to hold terrain information
class GameObjectWater : public GameObject, public boost::enable_shared_from_this<GameObjectWater>
{
private:
/// Visual information
RenderComponentWaterPtr mRenderComponentWaterDreams;
RenderComponentWaterPtr mRenderComponentWaterNightmares;
/// Position information
RenderComponentInitialPtr mRenderComponentInitial;
RenderComponentPositionalPtr mRenderComponentPositional;
/// Physics information
PhysicsComponentVolumeConvexPtr mPhysicsComponentVolumeConvex;
/// Logic component: it'll represent the 'brains' of the game object
/// containing information on its current state, its life and health(if applicable),
/// or the world(s) the object belongs to
LogicComponentPropPtr mLogicComponent;
//TODO: think what happens when world changes with the rendercomponent
/// Audio component
AudioComponentPtr mAudioComponent;
public:
//Constructor
GameObjectWater(const std::string& name);
//Destructor
~GameObjectWater();
/// Return render component entity
/// @return render component entity
RenderComponentWaterPtr getRenderComponentWaterDreams() const;
RenderComponentWaterPtr getRenderComponentWaterNightmares() const;
/// Set logic component
void setLogicComponentProp(LogicComponentPropPtr logicComponent);
/// return logic component
LogicComponentPropPtr getLogicComponent();
/// Set render component
/// @param pRenderComponentWater
void setRenderComponentWaterDreams(RenderComponentWaterPtr pRenderComponentWaterDreams);
void setRenderComponentWaterNightmares(RenderComponentWaterPtr pRenderComponentWaterNightmares);
/// Set audio component
/// @param pRenderComponentEntity
AudioComponentPtr getAudioComponent() const;
void setAudioComponent(AudioComponentPtr audioComponent);
void gameObjectInsideWater(GameObjectPtr pGameObject);
void gameObjectOutsideWater(GameObjectPtr pGameObject);
/// Set positional component
/// @param pRenderComponentPositional the component containing the positional information
void setRenderComponentPositional(RenderComponentPositionalPtr pRenderComponentPositional);
/// Set initial component
void setRenderComponentInitial(RenderComponentInitialPtr pRenderComponentInitial);
/// Return positional component
/// @return positional component
RenderComponentPositionalPtr getRenderComponentPositional() const;
/// Return initial component
/// @return initial component
RenderComponentInitialPtr getRenderComponentInitial() const;
void setVisible(bool visible);
/// Set physics component
void setPhysicsComponentVolumeConvex(PhysicsComponentVolumeConvexPtr pPhysicsComponentVolumeConvex);
/// Get physics component
PhysicsComponentVolumeConvexPtr getPhysicsComponentVolumeConvex() const;
/// React to a world change to the one given as a parameter
/// @param world world to change to
void changeToWorld(int newWorld, double perc);
void changeWorldFinished(int newWorld);
void changeWorldStarted(int newWorld);
void setDreamsRender();
void setNightmaresRender();
void setChangeWorldRender();
void setChangeWorldFactor(double factor);
/// Reset object
virtual void reset();
bool hasPositionalComponent() const;
RenderComponentPositionalPtr getPositionalComponent() const;
bool hasPhysicsComponent() const;
PhysicsComponentPtr getPhysicsComponent() const;
//bool hasRenderComponentEntity() const;
//RenderComponentEntityPtr getEntityComponent() const;
/// Process collision event
/// @param gameObject which has collision with
void processCollision(GameObjectPtr pGameObject, Ogre::Vector3 pNormal);
/// Process collision event
/// @param gameObject which has collision with
void processEnterTrigger(GameObjectPtr pGameObject);
/// Process collision event
/// @param gameObject which has collision with
void processExitTrigger(GameObjectPtr pGameObject);
void postUpdate();
void update(double elapsedSeconds);
bool hasLogicComponent() const;
LogicComponentPtr getLogicComponent() const;
};
class TGameObjectWaterParameters: public TGameObjectParameters
{
public:
TGameObjectWaterParameters();
~TGameObjectWaterParameters();
///Parameters specific to an Ogre Entity
TRenderComponentWaterParameters tRenderComponentWaterDreamsParameters;
TRenderComponentWaterParameters tRenderComponentWaterNightmaresParameters;
///Positional parameters
TRenderComponentPositionalParameters tRenderComponentPositionalParameters;
///Physics parameters
TPhysicsComponentVolumeConvexParameters tPhysicsComponentVolumeConvexParameters;
/// Audio component params
TAudioComponentMap tAudioComponentParameters;
///Logic parameters
TLogicComponentPropParameters tLogicComponentPropParameters;
};
}
#endif | [
"wyern1@1610d384-d83c-11de-a027-019ae363d039",
"juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039",
"ithiliel@1610d384-d83c-11de-a027-019ae363d039"
] | [
[
[
1,
108
],
[
110,
121
],
[
123,
149
]
],
[
[
109,
109
]
],
[
[
122,
122
]
]
] |
7320fadeee71fd40cebad7a2c57c8ddc43585e3b | a01b67b20207e2d31404262146763d3839ee833d | /trunk/Projet/tags/Monofin_20090407_0.1a/Drawing/paintingview.h | e79142672d5064483719c13a4003e8c927463a59 | [] | no_license | BackupTheBerlios/qtfin-svn | 49b59747b6753c72a035bf1e2e95601f91f5992c | ee18d9eb4f80a57a9121ba32dade96971196a3a2 | refs/heads/master | 2016-09-05T09:42:14.189410 | 2010-09-21T17:34:43 | 2010-09-21T17:34:43 | 40,801,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 471 | h | #ifndef PAINTINGVIEW_H
#define PAINTINGVIEW_H
#include <QGraphicsView>
#include <QWidget>
#include <QWheelEvent>
#include "paintingscene.h"
class PaintingView: public QGraphicsView{
public:
PaintingView(PaintingScene* scene, QWidget* parent = 0);
protected:
PaintingScene* _scene;
virtual void drawBackground(QPainter* painter, const QRectF& rect);
virtual void wheelEvent(QWheelEvent* event);
};
#endif // PAINTINGVIEW_H
| [
"kryptos@314bda93-af5c-0410-b653-d297496769b1"
] | [
[
[
1,
24
]
]
] |
60e4d88379f00ec4060750e6345cf239ea0621f5 | 9566086d262936000a914c5dc31cb4e8aa8c461c | /EnigmaTransmission/ServerTransmissionManager.hpp | 78d8c7cc1e9fab08808db3e63e959ba5fb2a52eb | [] | no_license | pazuzu156/Enigma | 9a0aaf0cd426607bb981eb46f5baa7f05b66c21f | b8a4dfbd0df206e48072259dbbfcc85845caad76 | refs/heads/master | 2020-06-06T07:33:46.385396 | 2011-12-19T03:14:15 | 2011-12-19T03:14:15 | 3,023,618 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,184 | hpp | #ifndef SERVERTRANSMISSIONMANAGER_HPP_INCLUDED
#define SERVERTRANSMISSIONMANAGER_HPP_INCLUDED
/*
Copyright © 2009 Christopher Joseph Dean Schaefer (disks86)
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "IServerTransmissionManager.hpp"
#include "ServerSessionManager.hpp"
#include "std_map.hpp"
#include "std_vector.hpp"
#include "enet.hpp"
#include "ThreadedManager.hpp"
#include <boost/thread.hpp>
namespace Enigma
{
class DllExport ServerTransmissionManager : public IServerTransmissionManager, public ThreadedManager
{
private:
bool mIsStopped;
bool mIsUnloaded;
int mClientLimit;
int mUpstreamLimit;
int mDownstreamLimit;
int mPollTimeout;
std::map<std::string,_ENetPeer*> mPeers;
ENetAddress mAddress;
ENetHost* mServer;
boost::mutex mHostMutex;
//Send a message to a client.
virtual void ReallySendMessageToPeer(const std::string& peerId, MessageContainer& message);
//Send a message to a client.
virtual void ReallySendMessageToPeer(ENetPeer* peer, enet_uint8 channel, ENetPacket* packet);
//Send a message to all clients.
virtual void ReallySendMessageToWorld(const std::string& peerId, MessageContainer& message);
//Poll Enet for more packets.
int Poll(ENetEvent* event);
protected:
ServerSessionManager mServerSessionManager;
public:
ServerTransmissionManager();
~ServerTransmissionManager();
//Performs any tasks needed before init can fire.
void PreInit();
//Initializes needed variables.
void Init();
//Loads resources.
void Load();
void Unload();
//Does one Iteration of the main loop.
void PollUnsafely();
//Does one Iteration of the main loop.
void Poll();
//Send a message to a client.
virtual void SendMessageToPeer(const std::string& peerId, MessageContainer& message);
//Send a message to a client.
virtual void SendMessageToPeers(std::vector< std::string > peers, MessageContainer& message);
//Send a message to all clients.
virtual void SendMessageToWorld(const std::string& peerId, MessageContainer& message);
ServerSessionManager& GetServerSessionManager(){return mServerSessionManager;}
};
};
#endif // SERVERTRANSMISSIONMANAGER_HPP_INCLUDED | [
"[email protected]"
] | [
[
[
1,
96
]
]
] |
9186e1ddcb7a51908ef1a6fec90d7b8eb2d6f12d | b4d726a0321649f907923cc57323942a1e45915b | /Launcher/TabHelp.h | c487dc8427f99361d4b5f420e875eb65b69b3764 | [] | no_license | chief1983/Imperial-Alliance | f1aa664d91f32c9e244867aaac43fffdf42199dc | 6db0102a8897deac845a8bd2a7aa2e1b25086448 | refs/heads/master | 2016-09-06T02:40:39.069630 | 2010-10-06T22:06:24 | 2010-10-06T22:06:24 | 967,775 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,301 | h | #if !defined(AFX_TABHELP_H__48E3367A_08C5_4B51_8F02_45E3055CFC2D__INCLUDED_)
#define AFX_TABHELP_H__48E3367A_08C5_4B51_8F02_45E3055CFC2D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// TabHelp.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CTabHelp dialog
class CTabHelp : public CDialog
{
// Construction
public:
CTabHelp(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CTabHelp)
enum { IDD = IDD_HELP };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTabHelp)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CTabHelp)
afx_msg void OnReadme();
afx_msg void OnGotoForum();
afx_msg void OnReportBug();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
void OpenInternetPage(char *page);
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_TABHELP_H__48E3367A_08C5_4B51_8F02_45E3055CFC2D__INCLUDED_)
| [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
36ff9a88a99a804625b87d85617c9ce93e32114a | a9afa168fac234c3b838dd29af4a5966a6acb328 | /CppUTest/include/CppUTest/Extensions/SimpleStringExtensions.h | 296ae3d69e40b56bce97ab9d70bb9b77a3005851 | [] | no_license | unclebob/tddrefcpp | 38a4170c38f612c180a8b9e5bdb2ec9f8971832e | 9124a6fad27349911658606392ba5730ff0d1e15 | refs/heads/master | 2021-01-25T07:34:57.626817 | 2010-05-10T20:01:39 | 2010-05-10T20:01:39 | 659,579 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,332 | h | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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.
*/
///////////////////////////////////////////////////////////////////////////////
//
// One of the design goals of CppUTest is to compilation with very old C++
// compilers. For that reason, the simple string class that provides
// only the operations needed in UnitTestHarness. If you want to extend
// SimpleString for your types, you can write a StringFrom function like these
//
///////////////////////////////////////////////////////////////////////////////
#ifndef D_SimpleStringExtensions_H
#define D_SimpleStringExtensions_H
#include <string>
#include "CppUTest/TestHarness.h"
#include "CppUTest/SimpleString.h"
SimpleString StringFrom(const std::string& other);
#endif
| [
"[email protected]"
] | [
[
[
1,
46
]
]
] |
7a8b8253cf6bd096aa5cec1d15b65154c8afd919 | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Engine/Graphics/RenderManager.cpp | 46552346652d29f954ecc3fe7de621abac7401e3 | [] | no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 50,880 | cpp | #include "Utils/Logger.h"
#include "Utils/Exception.h"
#include "RenderManager.h"
#include "Camera.h"
#include "params.h"
#include "VertexsStructs.h"
#include "Texture.h"
#include "EffectManager.h"
#include "IndexedVertexs.h"
#include "VertexsStructs.h"
#include "VertexCalculations.h"
bool CRenderManager::Init(HWND _hWnd, const SRenderManagerParams& _params)
{
LOGGER->AddNewLog(ELL_INFORMATION, "RenderManager:: Inicializando la libreria Direct3D");
// Create the D3D object.
m_pD3D = Direct3DCreate9( D3D_SDK_VERSION );
SetOk(m_pD3D != NULL);
if (IsOk())
{
// Set up the structure used to create the D3DDevice
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
//if(fullscreenMode)
if(_params.bFullscreen)
{
d3dpp.Windowed = FALSE;
d3dpp.BackBufferWidth = _params.v2iResolution.x;
d3dpp.BackBufferHeight = _params.v2iResolution.y;
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
}
else
{
d3dpp.Windowed = TRUE;
//d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
}
d3dpp.SwapEffect = D3DSWAPEFFECT_FLIP;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
d3dpp.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
m_iStencilBits = 8;
// Create the D3DDevice
SetOk(!FAILED( m_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, _hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &m_pD3DDevice ) ));
if (!IsOk())
{
SetOk(!FAILED( m_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, _hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &m_pD3DDevice ) ));
if (IsOk())
{
LOGGER->AddNewLog(ELL_INFORMATION, "RenderManager:: D3DCREATE_SOFTWARE_VERTEXPROCESSING");
}
}
else
{
LOGGER->AddNewLog(ELL_INFORMATION, "RenderManager:: D3DCREATE_HARDWARE_VERTEXPROCESSING");
}
if (IsOk())
{
// Turn off culling, so we see the front and back of the triangle
m_pD3DDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetSamplerState(1, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
m_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );
m_pD3DDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
m_pD3DDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
m_pD3DDevice->SetRenderState( D3DRS_ZFUNC, D3DCMP_LESSEQUAL );
m_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW);
m_pD3DDevice->SetRenderState( D3DRS_ZENABLE,D3DZB_TRUE);
m_pD3DDevice->SetRenderState( D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
m_pD3DDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE);
// Turn off D3D lighting, since we are providing our own vertex colors
m_pD3DDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
//if (fullscreenMode)
if(_params.bFullscreen)
{
m_uWidth = _params.v2iResolution.x;
m_uHeight = _params.v2iResolution.y;
}
else
{
GetWindowRect(_hWnd);
}
LOGGER->AddNewLog(ELL_INFORMATION, "RenderManager:: La resolucion de pantalla es (%dx%d)",m_uWidth,m_uHeight);
}
}
if (!IsOk())
{
std::string msg_error = "Rendermanager::Init-> Error al inicializar Direct3D";
LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str());
Release();
throw CException(__FILE__, __LINE__, msg_error);
}
STEXTUREDVERTEX::GetVertexDeclaration();
STEXTURED2VERTEX::GetVertexDeclaration();
SNORMALTEXTUREDVERTEX::GetVertexDeclaration();
SNORMALTEXTURED2VERTEX::GetVertexDeclaration();
SDIFFUSEVERTEX::GetVertexDeclaration();
SNORMALDIFFUSEVERTEX::GetVertexDeclaration();
TNORMALTANGENTBINORMALTEXTUREDVERTEX::GetVertexDeclaration();
TNORMALTANGENTBINORMALTEXTURED2VERTEX::GetVertexDeclaration();
TCAL3D_HW_VERTEX::GetVertexDeclaration();
SPARTICLE_VERTEX::GetVertexDeclaration();
if(IsOk())
{
m_pD3DDevice->GetRenderTarget(0,&m_pBackBuffer);
m_pD3DDevice->GetDepthStencilSurface(&m_pDefaultDepthStencilBuffer);
m_pSettedBackBuffer=0;
m_pSettedDepthStencilBuffer=0;
}
#ifdef _DEBUG // Clear the backbuffer to magenta color in a Debug mode
m_cClearColor = colBLUE;
#else // Clear the backbuffer to black color in a Release mode
m_cClearColor = colBLACK;
#endif
return IsOk();
}
#define SPHERE_STACKS 10
#define SPHERE_SLICES 10
bool CRenderManager::InitPostRenderTargets()
{
SPARTICLE_VERTEX l_ParticleVertexBuffer[4];
l_ParticleVertexBuffer[0].x = -1;
l_ParticleVertexBuffer[0].y = -1;
l_ParticleVertexBuffer[0].z = 0;
l_ParticleVertexBuffer[1].x = 1;
l_ParticleVertexBuffer[1].y = -1;
l_ParticleVertexBuffer[1].z = 0;
l_ParticleVertexBuffer[2].x = -1;
l_ParticleVertexBuffer[2].y = 1;
l_ParticleVertexBuffer[2].z = 0;
l_ParticleVertexBuffer[3].x = 1;
l_ParticleVertexBuffer[3].y = 1;
l_ParticleVertexBuffer[3].z = 0;
uint16 l_iParticleIndex[6] = {0,2,1,1,2,3};
m_pParticleVertex = new CIndexedVertexs<SPARTICLE_VERTEX>( this,
(char*)l_ParticleVertexBuffer,
l_iParticleIndex,
4,
6);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
const int vertexnum = SPHERE_STACKS*SPHERE_SLICES + 2;
SSIMPLEVERTEX l_SphereVertexBuffer[vertexnum];
l_SphereVertexBuffer[SPHERE_STACKS*SPHERE_SLICES + 0].x = 0;
l_SphereVertexBuffer[SPHERE_STACKS*SPHERE_SLICES + 0].y = -1;
l_SphereVertexBuffer[SPHERE_STACKS*SPHERE_SLICES + 0].z = 0;
l_SphereVertexBuffer[SPHERE_STACKS*SPHERE_SLICES + 1].x = 0;
l_SphereVertexBuffer[SPHERE_STACKS*SPHERE_SLICES + 1].y = 1;
l_SphereVertexBuffer[SPHERE_STACKS*SPHERE_SLICES + 1].z = 0;
for(uint32 l_iStack = 0; l_iStack < SPHERE_STACKS; ++l_iStack)
{
for(uint32 l_iSlice = 0; l_iSlice < SPHERE_SLICES; ++l_iSlice)
{
int cont = l_iStack * SPHERE_SLICES + l_iSlice;
float theta = (l_iStack + 1.f) / (SPHERE_STACKS + 1.f);
theta = (theta - .5f) * FLOAT_PI_VALUE;
float phi = (float)l_iSlice / SPHERE_SLICES;
phi *= 2 * FLOAT_PI_VALUE;
float sinTheta = sin(theta);
float sinPhi = sin(phi);
float cosTheta = cos(theta);
float cosPhi = cos(phi);
l_SphereVertexBuffer[cont].x = cosPhi * cosTheta;
l_SphereVertexBuffer[cont].y = sinTheta;
l_SphereVertexBuffer[cont].z = sinPhi * cosTheta;
}
}
const int indexnum = (SPHERE_STACKS-1) * SPHERE_SLICES * 6 + SPHERE_SLICES * 6;
uint16 l_iSphereIndexBuffer[indexnum];
for(uint32 l_iStack = 0; l_iStack < SPHERE_STACKS-1; ++l_iStack)
{
for(uint32 l_iSlice = 0; l_iSlice < SPHERE_SLICES; ++l_iSlice)
{
int cont = l_iStack * SPHERE_SLICES + l_iSlice;
int p0 = l_iStack * SPHERE_SLICES + l_iSlice;
int p1 = (l_iStack + 1) * SPHERE_SLICES + l_iSlice;
int p2 = (l_iStack + 1) * SPHERE_SLICES + ((l_iSlice + 1) % SPHERE_SLICES);
int p3 = l_iStack * SPHERE_SLICES + ((l_iSlice + 1) % SPHERE_SLICES);
l_iSphereIndexBuffer[cont * 6 + 0] = p0;
l_iSphereIndexBuffer[cont * 6 + 1] = p1;
l_iSphereIndexBuffer[cont * 6 + 2] = p2;
l_iSphereIndexBuffer[cont * 6 + 3] = p0;
l_iSphereIndexBuffer[cont * 6 + 4] = p2;
l_iSphereIndexBuffer[cont * 6 + 5] = p3;
}
}
//tapa i cul
for(uint32 l_iSlice = 0; l_iSlice < SPHERE_SLICES; ++l_iSlice)
{
int cont = (SPHERE_STACKS-1) * SPHERE_SLICES + l_iSlice;
int p0 = l_iSlice;
int p1 = ((l_iSlice + 1) % SPHERE_SLICES);
int p2 = SPHERE_STACKS*SPHERE_SLICES + 0;
l_iSphereIndexBuffer[cont * 6 + 0] = p0;
l_iSphereIndexBuffer[cont * 6 + 1] = p1;
l_iSphereIndexBuffer[cont * 6 + 2] = p2;
p0 = (SPHERE_STACKS-1) * SPHERE_SLICES + l_iSlice;
p1 = (SPHERE_STACKS-1) * SPHERE_SLICES + ((l_iSlice + 1) % SPHERE_SLICES);
p2 = SPHERE_STACKS*SPHERE_SLICES + 1;
l_iSphereIndexBuffer[cont * 6 + 3] = p0;
l_iSphereIndexBuffer[cont * 6 + 4] = p2;
l_iSphereIndexBuffer[cont * 6 + 5] = p1;
}
VertexCacheOptimisation( l_SphereVertexBuffer, l_iSphereIndexBuffer,
vertexnum,
indexnum,
sizeof(SSIMPLEVERTEX) );
m_pSphereVertex = new CIndexedVertexs<SSIMPLEVERTEX>( this,
(char*)l_SphereVertexBuffer,
l_iSphereIndexBuffer,
vertexnum,
indexnum);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
SSIMPLEVERTEX l_ConeVertexBuffer[5];
l_ConeVertexBuffer[0].x = 0;
l_ConeVertexBuffer[0].y = 0;
l_ConeVertexBuffer[0].z = 0;
l_ConeVertexBuffer[1].x = 1;
l_ConeVertexBuffer[1].y = 1;
l_ConeVertexBuffer[1].z = 1;
l_ConeVertexBuffer[2].x = -1;
l_ConeVertexBuffer[2].y = 1;
l_ConeVertexBuffer[2].z = 1;
l_ConeVertexBuffer[3].x = -1;
l_ConeVertexBuffer[3].y = 1;
l_ConeVertexBuffer[3].z = -1;
l_ConeVertexBuffer[4].x = 1;
l_ConeVertexBuffer[4].y = 1;
l_ConeVertexBuffer[4].z = -1;
uint16 l_iConeIndexBuffer[] = {
0, 1, 2,
0, 2, 3,
0, 3, 4,
0, 4, 1,
1, 4, 3,
1, 3, 2
};
m_pConeVertex = new CIndexedVertexs<SPARTICLE_VERTEX>( this,
(char*)l_ConeVertexBuffer,
l_iConeIndexBuffer,
5,
18);
return true;
}
void CRenderManager::GetWindowRect( HWND hwnd )
{
assert(IsOk());
RECT rec_window;
GetClientRect( hwnd, &rec_window);
m_uWidth = rec_window.right - rec_window.left;
m_uHeight = rec_window.bottom - rec_window.top;
}
void CRenderManager::Release(void)
{
assert(IsOk());
LOGGER->AddNewLog(ELL_INFORMATION, "RenderManager::Release",m_uWidth,m_uHeight);
CHECKED_RELEASE(m_pBackBuffer);
CHECKED_RELEASE(m_pDefaultDepthStencilBuffer);
CHECKED_DELETE(m_pConeVertex);
CHECKED_DELETE(m_pParticleVertex);
CHECKED_DELETE(m_pSphereVertex);
STEXTUREDVERTEX::ReleaseVertexDeclaration();
STEXTURED2VERTEX::ReleaseVertexDeclaration();
SNORMALTEXTUREDVERTEX::ReleaseVertexDeclaration();
SNORMALTEXTURED2VERTEX::ReleaseVertexDeclaration();
SDIFFUSEVERTEX::ReleaseVertexDeclaration();
SNORMALDIFFUSEVERTEX::ReleaseVertexDeclaration();
TNORMALTANGENTBINORMALTEXTUREDVERTEX::ReleaseVertexDeclaration();
TNORMALTANGENTBINORMALTEXTURED2VERTEX::ReleaseVertexDeclaration();
TCAL3D_HW_VERTEX::ReleaseVertexDeclaration();
SPARTICLE_VERTEX::ReleaseVertexDeclaration();
//Release main devices of render
CHECKED_RELEASE(m_pD3DDevice)
CHECKED_RELEASE(m_pD3D)
}
// RENDERING STUFF:
void CRenderManager::BeginRendering()
{
assert(IsOk());
uint32 red = (uint32) (m_cClearColor.GetRed() * 255);
uint32 green = (uint32) (m_cClearColor.GetGreen() * 255);
uint32 blue = (uint32) (m_cClearColor.GetBlue() * 255);
//m_pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, red, green, blue), 1.0f, 0);
// Begin the scene
HRESULT hr = m_pD3DDevice->BeginScene();
assert( SUCCEEDED( hr ) );
m_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW);
m_pD3DDevice->SetRenderState( D3DRS_ZENABLE,D3DZB_TRUE);
m_pD3DDevice->SetRenderState( D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
m_pD3DDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE);
m_pD3DDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
m_pD3DDevice->SetRenderState( D3DRS_DITHERENABLE, TRUE );
m_pD3DDevice->SetRenderState( D3DRS_SPECULARENABLE, FALSE );
//if(m_bPaintSolid)
//if(true)
//{
m_pD3DDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );
//}
//else
//{
// m_pD3DDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_WIREFRAME );
//}
}
void CRenderManager::EndRendering()
{
assert(IsOk());
m_pD3DDevice->EndScene();
}
void CRenderManager::Present()
{
// Present the backbuffer contents to the display
m_pD3DDevice->Present( NULL, NULL, NULL, NULL );
}
void CRenderManager::SetRenderTarget(int _iIndex, LPDIRECT3DSURFACE9 _pRenderTarget)
{
//if(_iIndex == 0)
//{
// if(_pRenderTarget != m_pSettedBackBuffer)
// {
// m_pD3DDevice->SetRenderTarget(0, _pRenderTarget);
// m_pSettedBackBuffer = _pRenderTarget;
// }
//}
//else
//{
m_pD3DDevice->SetRenderTarget(_iIndex, _pRenderTarget);
//}
}
void CRenderManager::SetDepthStencilBuffer (LPDIRECT3DSURFACE9 _pDepthStencilBuffer)
{
if(_pDepthStencilBuffer != m_pSettedDepthStencilBuffer)
{
m_pD3DDevice->SetDepthStencilSurface(_pDepthStencilBuffer);
m_pSettedDepthStencilBuffer = _pDepthStencilBuffer;
}
}
void CRenderManager::SetViewMatrix(Mat44f& _matView)
{
m_pD3DDevice->SetTransform(D3DTS_VIEW, &_matView.GetD3DXMatrix());
}
void CRenderManager::SetProjectionMatrix(Mat44f& _matProjection)
{
m_pD3DDevice->SetTransform(D3DTS_PROJECTION, &_matProjection.GetD3DXMatrix());
}
Mat44f CRenderManager::GetLookAtMatrix(Vect3f& _vEye,Vect3f& _vLookAt,Vect3f& _vUp)
{
D3DXVECTOR3 l_vEyeD3D(_vEye.x, _vEye.y, _vEye.z);
D3DXVECTOR3 l_vLookAtD3D(_vLookAt.x,_vLookAt.y,_vLookAt.z);
D3DXVECTOR3 l_vUpD3D(_vUp.x,_vUp.y,_vUp.z);
D3DXMATRIX l_matViewD3D;
D3DXMatrixLookAtLH( &l_matViewD3D, &l_vEyeD3D, &l_vLookAtD3D, &l_vUpD3D);
return Mat44f(l_matViewD3D._11,l_matViewD3D._21,l_matViewD3D._31,l_matViewD3D._41,
l_matViewD3D._12,l_matViewD3D._22,l_matViewD3D._32,l_matViewD3D._42,
l_matViewD3D._13,l_matViewD3D._23,l_matViewD3D._33,l_matViewD3D._43,
l_matViewD3D._14,l_matViewD3D._24,l_matViewD3D._34,l_matViewD3D._44);
}
Mat44f CRenderManager::GetPerspectiveFOVMatrix(float _fFOV, float _fAspectRatio, float _fNear, float _fFar)
{
D3DXMATRIX l_matProjectionD3D;
D3DXMatrixPerspectiveFovLH( &l_matProjectionD3D, _fFOV, _fAspectRatio, _fNear, _fFar);
return Mat44f(l_matProjectionD3D._11,l_matProjectionD3D._21,l_matProjectionD3D._31,l_matProjectionD3D._41,
l_matProjectionD3D._12,l_matProjectionD3D._22,l_matProjectionD3D._32,l_matProjectionD3D._42,
l_matProjectionD3D._13,l_matProjectionD3D._23,l_matProjectionD3D._33,l_matProjectionD3D._43,
l_matProjectionD3D._14,l_matProjectionD3D._24,l_matProjectionD3D._34,l_matProjectionD3D._44);
}
void CRenderManager::SetupMatrices(CCamera* _pCamera, bool _bOrtho, bool _bSaveCamera)
{
assert(IsOk());
D3DXMATRIX l_matView;
D3DXMATRIX l_matProject;
Vect3f eye, up, right;
if(_bSaveCamera)
m_pCamera = _pCamera;
if(!_pCamera)
{
//Set default view and projection matrix
//Setup Matrix view
eye=Vect3f(0.0f,0.0f,-1.0f);
up=Vect3f(0.0f,1.0f,0.0f);
right = (up ^ Vect3f(0.0f,0.0f,1.0f)).GetNormalized();
D3DXVECTOR3 l_Eye(eye.x, eye.y, eye.z), l_LookAt(0.0f,0.0f,0.0f), l_VUP(0.0f,1.0f,0.0f);
D3DXMatrixLookAtLH( &l_matView, &l_Eye, &l_LookAt, &l_VUP);
//Setup Matrix projection
if(_bOrtho)
{
D3DXMatrixOrthoLH(
&l_matProject,
(float)m_uWidth,
(float)m_uHeight,
0.0f,
1.0f);
} else {
D3DXMatrixPerspectiveFovLH(
&l_matProject,
45.0f * D3DX_PI / 180.0f, //angle de visió
((float)m_uWidth)/((float)m_uHeight), //aspect ratio
1.0f, //z near
100.0f //z far
);
}
}
else
{
eye = _pCamera->GetEye();
up = _pCamera->GetVecUp().GetNormalized();
D3DXVECTOR3 l_Eye(eye.x, eye.y, eye.z);
Vect3f lookat = _pCamera->GetLookAt();
right = (up ^ (lookat - eye)).GetNormalized();
D3DXVECTOR3 l_LookAt(lookat.x, lookat.y, lookat.z);
Vect3f vup = _pCamera->GetVecUp();
D3DXVECTOR3 l_VUP(vup.x, vup.y, vup.z);
//Setup Matrix view
D3DXMatrixLookAtLH( &l_matView, &l_Eye, &l_LookAt, &l_VUP);
//Setup Matrix projection
if(_bOrtho)
{
D3DXMatrixOrthoLH(
&l_matProject,
(float)m_uWidth,
(float)m_uHeight,
_pCamera->GetZn(),
_pCamera->GetZf());
} else {
D3DXMatrixPerspectiveFovLH( &l_matProject, _pCamera->GetFov(), _pCamera->GetAspectRatio(),
_pCamera->GetZn(), _pCamera->GetZf());
}
}
m_pD3DDevice->SetTransform( D3DTS_VIEW, &l_matView );
m_pD3DDevice->SetTransform( D3DTS_PROJECTION, &l_matProject );
CORE->GetEffectManager()->ActivateCamera(l_matView, l_matProject, eye, up, right);
if(_bSaveCamera)
{
if(_pCamera)
{
m_Frustum.Update(_pCamera);
}
else
{
m_Frustum.Update(l_matView * l_matProject);
}
}
/*m_pEffectManager->SetProjectionMatrix(m_matProject);
m_pEffectManager->SetViewMatrix(m_matView);
*/
}
void CRenderManager::Setup2DCamera()
{
assert(IsOk());
D3DXMATRIX m_matView;
D3DXMATRIX m_matProject;
Vect3f eye, right, up;
//Set default view and projection matrix
float l_fCenterW = m_uWidth /2.0f;
float l_fCenterH = m_uHeight/2.0f;
//Setup Matrix view
eye= Vect3f(l_fCenterW,l_fCenterH,-1.0f);
up = Vect3f(0.f,1.f,0.f);
right = (up ^ (Vect3f(l_fCenterW,l_fCenterH,0.0f) - eye)).GetNormalized();
D3DXVECTOR3 l_Eye(eye.x, eye.y, eye.z), l_LookAt(l_fCenterW,l_fCenterH,0.0f), l_VUP(0.0f,1.0f,0.0f);
D3DXMatrixLookAtLH( &m_matView, &l_Eye, &l_LookAt, &l_VUP);
//Setup Matrix projection
D3DXMatrixOrthoLH(
&m_matProject,
(float)m_uWidth,
(float)m_uHeight,
0.0f,
2.0f);
m_pD3DDevice->SetTransform( D3DTS_VIEW, &m_matView );
m_pD3DDevice->SetTransform( D3DTS_PROJECTION, &m_matProject );
CORE->GetEffectManager()->ActivateCamera(m_matView, m_matProject, eye, up, right);
/*m_pEffectManager->SetProjectionMatrix(m_matProject);
m_pEffectManager->SetViewMatrix(m_matView);
*/
}
void CRenderManager::SetTransform(D3DXMATRIX& matrix)
{
assert(IsOk());
assert(!"Method not supported setworldmatrix needs mat44f no d3dxmatrix");
m_pD3DDevice->SetTransform(D3DTS_WORLD, &matrix);
CORE->GetEffectManager()->SetWorldMatrix(matrix);
}
void CRenderManager::SetTransform(Mat44f& m)
{
assert(IsOk());
D3DXMATRIX matrix(m.m00, m.m10, m.m20, m.m30,
m.m01, m.m11, m.m21, m.m31,
m.m02, m.m12, m.m22, m.m32,
m.m03, m.m13, m.m23, m.m33);
m_pD3DDevice->SetTransform(D3DTS_WORLD, &matrix);
//CORE->GetEffectManager()->SetWorldMatrix(m);
}
void CRenderManager::EnableAlphaBlend ()
{
m_pD3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
// render el quad de difuminacion....
m_pD3DDevice->SetRenderState ( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
m_pD3DDevice->SetRenderState ( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
//// render el quad de difuminacion....
m_pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
m_pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
m_pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
}
void CRenderManager::DisableAlphaBlend ()
{
m_pD3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
}
void CRenderManager::CalculateAlignment (uint32 _uiW, uint32 _uiH, ETypeAlignment _Alignment, Vect2i& _vfinalPos)
{
assert(IsOk());
switch (_Alignment)
{
case CENTER:
{
_vfinalPos.x -= (uint32)(_uiW*0.5f);
_vfinalPos.y -= (uint32)(_uiH*0.5f);
}
break;
case UPPER_LEFT:
{
//Por defecto ya est alienado de esta manera :)
}
break;
case UPPER_RIGHT:
{
_vfinalPos.x -= _uiW;
}
break;
case LOWER_RIGHT:
{
_vfinalPos.x -= _uiW;
_vfinalPos.y -= _uiH;
}
break;
case LOWER_LEFT:
{
_vfinalPos.y -= _uiH;
}
break;
default:
{
LOGGER->AddNewLog(ELL_ERROR, "RenderManager::CalculateAlignment Se está intentado renderizar un quad2d con una alineacion desconocida");
}
break;
}
}
void CRenderManager::DrawLine ( const Vect3f &_PosA, const Vect3f &_PosB, const CColor& _Color)
{
assert(IsOk());
DWORD l_color_aux = _Color.GetUint32Argb();
SDIFFUSEVERTEX v[2] =
{
{_PosA.x, _PosA.y, _PosA.z, l_color_aux},
{_PosB.x, _PosB.y, _PosB.z, l_color_aux},
};
m_pD3DDevice->SetTexture(0,NULL);
m_pD3DDevice->SetFVF(SDIFFUSEVERTEX::GetFVF());
m_pD3DDevice->DrawPrimitiveUP( D3DPT_LINELIST,1, v,sizeof(SDIFFUSEVERTEX));
}
void CRenderManager::DrawAxis ()
{
assert(IsOk());
DWORD color_red = colRED.GetUint32Argb();
DWORD color_green = colGREEN.GetUint32Argb();
DWORD color_blue = colBLUE.GetUint32Argb();
SDIFFUSEVERTEX v[6] =
{
{0.f,0.f,0.f, color_red},
{1.f,0.f,0.f, color_red},
{0.f,0.f,0.f, color_green},
{0.f,1.f,0.f, color_green},
{0.f,0.f,0.f, color_blue},
{0.f,0.f,1.f, color_blue}
};
m_pD3DDevice->SetTexture(0,NULL);
m_pD3DDevice->SetFVF(SDIFFUSEVERTEX::GetFVF());
m_pD3DDevice->DrawPrimitiveUP( D3DPT_LINELIST,3, v,sizeof(SDIFFUSEVERTEX));
}
void CRenderManager::DrawCube(float _fSize, const CColor& _Color)
{
assert(IsOk());
DrawCube(Vect3f(0.0f,0.0f,0.0f),_fSize,_Color);
}
void CRenderManager::DrawCube(Vect3f &_fSize, const CColor& _Color)
{
assert(IsOk());
DrawCube(Vect3f(0.0f,0.0f,0.0f),_fSize,_Color);
}
void CRenderManager::DrawCube(const Vect3f &_Pos, float _fSize, const CColor& _Color)
{
assert(IsOk());
float l_fC = _fSize/2.f;
DWORD l_Color = _Color.GetUint32Argb();
SDIFFUSEVERTEX v[24] =
{
{_Pos.x - l_fC,_Pos.y - l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x + l_fC,_Pos.y - l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x - l_fC,_Pos.y - l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x - l_fC,_Pos.y + l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x - l_fC,_Pos.y - l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x - l_fC,_Pos.y - l_fC,_Pos.z + l_fC, l_Color},
//---------------------------------------------------
{_Pos.x + l_fC,_Pos.y - l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x + l_fC,_Pos.y + l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x + l_fC,_Pos.y - l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x + l_fC,_Pos.y - l_fC,_Pos.z + l_fC, l_Color},
//---------------------------------------------------
{_Pos.x - l_fC,_Pos.y + l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x + l_fC,_Pos.y + l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x - l_fC,_Pos.y + l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x - l_fC,_Pos.y + l_fC,_Pos.z + l_fC, l_Color},
//---------------------------------------------------
{_Pos.x - l_fC,_Pos.y - l_fC,_Pos.z + l_fC, l_Color},
{_Pos.x + l_fC,_Pos.y - l_fC,_Pos.z + l_fC, l_Color},
{_Pos.x - l_fC,_Pos.y - l_fC,_Pos.z + l_fC, l_Color},
{_Pos.x - l_fC,_Pos.y + l_fC,_Pos.z + l_fC, l_Color},
//---------------------------------------------------
{_Pos.x + l_fC,_Pos.y + l_fC,_Pos.z - l_fC, l_Color},
{_Pos.x + l_fC,_Pos.y + l_fC,_Pos.z + l_fC, l_Color},
//---------------------------------------------------
{_Pos.x + l_fC,_Pos.y - l_fC,_Pos.z + l_fC, l_Color},
{_Pos.x + l_fC,_Pos.y + l_fC,_Pos.z + l_fC, l_Color},
//---------------------------------------------------
{_Pos.x - l_fC,_Pos.y + l_fC,_Pos.z + l_fC, l_Color},
{_Pos.x + l_fC,_Pos.y + l_fC,_Pos.z + l_fC, l_Color},
};
m_pD3DDevice->SetTexture(0,NULL);
m_pD3DDevice->SetFVF(SDIFFUSEVERTEX::GetFVF());
m_pD3DDevice->DrawPrimitiveUP( D3DPT_LINELIST,12, v,sizeof(SDIFFUSEVERTEX));
}
void CRenderManager::DrawCube(const Vect3f &_Pos, const Vect3f &_Size, const CColor& _Color)
{
assert(IsOk());
Vect3f l_fC = _Size/2.f;
DWORD l_Color = _Color.GetUint32Argb();
SDIFFUSEVERTEX v[24] =
{
{_Pos.x - l_fC.x,_Pos.y - l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x + l_fC.x,_Pos.y - l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x - l_fC.x,_Pos.y - l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x - l_fC.x,_Pos.y + l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x - l_fC.x,_Pos.y - l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x - l_fC.x,_Pos.y - l_fC.y,_Pos.z + l_fC.z, l_Color},
//----------------------------------------l_fC.z-------
{_Pos.x + l_fC.x,_Pos.y - l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x + l_fC.x,_Pos.y + l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x + l_fC.x,_Pos.y - l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x + l_fC.x,_Pos.y - l_fC.y,_Pos.z + l_fC.z, l_Color},
//----------------------------------------l_fC.z-------
{_Pos.x - l_fC.x,_Pos.y + l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x + l_fC.x,_Pos.y + l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x - l_fC.x,_Pos.y + l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x - l_fC.x,_Pos.y + l_fC.y,_Pos.z + l_fC.z, l_Color},
//----------------------------------------l_fC.z-------
{_Pos.x - l_fC.x,_Pos.y - l_fC.y,_Pos.z + l_fC.z, l_Color},
{_Pos.x + l_fC.x,_Pos.y - l_fC.y,_Pos.z + l_fC.z, l_Color},
{_Pos.x - l_fC.x,_Pos.y - l_fC.y,_Pos.z + l_fC.z, l_Color},
{_Pos.x - l_fC.x,_Pos.y + l_fC.y,_Pos.z + l_fC.z, l_Color},
//----------------------------------------l_fC.z-------
{_Pos.x + l_fC.x,_Pos.y + l_fC.y,_Pos.z - l_fC.z, l_Color},
{_Pos.x + l_fC.x,_Pos.y + l_fC.y,_Pos.z + l_fC.z, l_Color},
//----------------------------------------l_fC.z-------
{_Pos.x + l_fC.x,_Pos.y - l_fC.y,_Pos.z + l_fC.z, l_Color},
{_Pos.x + l_fC.x,_Pos.y + l_fC.y,_Pos.z + l_fC.z, l_Color},
//----------------------------------------l_fC.z-------
{_Pos.x - l_fC.x,_Pos.y + l_fC.y,_Pos.z + l_fC.z, l_Color},
{_Pos.x + l_fC.x,_Pos.y + l_fC.y,_Pos.z + l_fC.z, l_Color},
};
m_pD3DDevice->SetTexture(0,NULL);
m_pD3DDevice->SetFVF(SDIFFUSEVERTEX::GetFVF());
m_pD3DDevice->DrawPrimitiveUP( D3DPT_LINELIST,12, v,sizeof(SDIFFUSEVERTEX));
}
void CRenderManager::DrawCamera(const CCamera* camera)
{
assert(IsOk());
D3DXMATRIX matrix;
D3DXMATRIX translation;
if (camera->GetTypeCamera() == CCamera::TC_THPS)
{
Vect3f camera_CenterPos = camera->GetObject3D()->GetPosition();
D3DXMatrixTranslation( &translation, camera_CenterPos.x ,camera_CenterPos.y ,camera_CenterPos.z );
m_pD3DDevice->SetTransform( D3DTS_WORLD, &translation );
DrawCube(0.5f,colCYAN);
D3DXMatrixTranslation( &matrix, 0, 0, 0 );
m_pD3DDevice->SetTransform( D3DTS_WORLD, &matrix );
}
//---------PINTAMOS EL FRUSTUM-------------//
D3DXMATRIX translation2;
Vect3f eye_aux = camera->GetEye();
D3DXVECTOR3 eye(eye_aux.x, eye_aux.y, eye_aux.z);
D3DXMatrixTranslation( &translation, eye.x ,eye.y ,eye.z );
D3DXMATRIX rotation;
D3DXMATRIX rotation2;
float yaw = camera->GetObject3D()->GetYaw();
float pitch = camera->GetObject3D()->GetPitch();
D3DXMatrixRotationY ( &rotation, -yaw);
D3DXMatrixRotationZ ( &rotation2, +pitch);
matrix = rotation2 * rotation * translation;
// Cambiar el sistema de coordenadas
m_pD3DDevice->SetTransform( D3DTS_WORLD, &matrix );
SDIFFUSEVERTEX pts[9];
float fov = camera->GetFov();
float aspect = camera->GetAspectRatio();
float d = camera->GetViewD();
float zNear = camera->GetZn();
float zFar = camera->GetZf();
float h_near = zNear * tan ( fov * 0.5f );
float k_near = h_near * aspect;
float h_far = d * tan ( fov * 0.5f );
float k_far = h_far * aspect;
pts[ 0 ].x = pts[ 0 ].y = pts[ 0 ].z = 0;
pts[ 0 ].color = 0xffffffff;
pts[ 1 ].x = d;
pts[ 1 ].y = h_far;
pts[ 1 ].z = k_far;
pts[ 1 ].color = 0xffffffff;
pts[ 2 ].x = d;
pts[ 2 ].y = h_far;
pts[ 2 ].z = -k_far;
pts[ 2 ].color = 0xffffffff;
pts[ 3 ].x = d;
pts[ 3 ].y = -h_far;
pts[ 3 ].z = -k_far;
pts[ 3 ].color = 0xffffffff;
pts[ 4 ].x = d;
pts[ 4 ].y = -h_far;
pts[ 4 ].z = k_far;
pts[ 4 ].color = 0xffffffff;
pts[ 5 ].x = zNear;
pts[ 5 ].y = h_near;
pts[ 5 ].z = k_near;
pts[ 5 ].color = 0xffffffff;
pts[ 6 ].x = zNear;
pts[ 6 ].y = h_near;
pts[ 6 ].z = -k_near;
pts[ 6 ].color = 0xffffffff;
pts[ 7 ].x = zNear;
pts[ 7 ].y = -h_near;
pts[ 7 ].z = -k_near;
pts[ 7 ].color = 0xffffffff;
pts[ 8 ].x = zNear;
pts[ 8 ].y = -h_near;
pts[ 8 ].z = k_near;
pts[ 8 ].color = 0xffffffff;
// Decimos el tipo de vertice que vamos a proporcionar...
m_pD3DDevice->SetFVF( SDIFFUSEVERTEX::GetFVF() );
// Desactivar la textura
m_pD3DDevice->SetTexture (0, NULL);
m_pD3DDevice->DrawPrimitiveUP( D3DPT_POINTLIST, 9, pts, sizeof( SDIFFUSEVERTEX ) );
static short int indexes[] = {
0,1, 0,2, 0,3, 0,4,
1,2, 2,3, 3,4, 4,1,
5,6, 6,7, 7,8, 8,5
};
m_pD3DDevice->DrawIndexedPrimitiveUP( D3DPT_LINELIST, 0, 9, 12, indexes, D3DFMT_INDEX16, pts, sizeof( SDIFFUSEVERTEX ) );
D3DXMatrixTranslation( &matrix, 0, 0, 0 );
m_pD3DDevice->SetTransform( D3DTS_WORLD, &matrix );
//---------PINTAMOS LA BOX Y LOS EJES------------------//
D3DXMatrixTranslation( &translation2, -1.0f, 0.0f, 0.0f );
matrix = translation2 * rotation2 * rotation * translation;
m_pD3DDevice->SetTransform( D3DTS_WORLD, &matrix );
SDIFFUSEVERTEX v[6] =
{
//EJE X
{0, 0, 0, 0xffff0000},
{3, 0, 0, 0xffff0000},
//EJE Y
{0, 0, 0, 0xff00ff00},
{0, 3, 0, 0xff00ff00},
//EJE Z
{0, 0, 0, 0xff0000ff},
{0, 0, 3, 0xff0000ff},
};
m_pD3DDevice->SetTexture(0,NULL);
m_pD3DDevice->SetFVF(SDIFFUSEVERTEX::GetFVF());
m_pD3DDevice->DrawPrimitiveUP( D3DPT_LINELIST, 3, v,sizeof(SDIFFUSEVERTEX));
DrawCube(0.5f,colWHITE);
D3DXMatrixTranslation( &matrix, 0, 0, 0 );
m_pD3DDevice->SetTransform( D3DTS_WORLD, &matrix );
}
void CRenderManager::DrawFrustum(const CFrustum* frustum, const CColor& _Color)
{
Vect3f l_vPoints[8];
frustum->GetPoints(l_vPoints);
//bottom
DrawLine(l_vPoints[0],l_vPoints[1],_Color);
DrawLine(l_vPoints[1],l_vPoints[3],_Color);
DrawLine(l_vPoints[3],l_vPoints[2],_Color);
DrawLine(l_vPoints[2],l_vPoints[0],_Color);
//top
DrawLine(l_vPoints[4],l_vPoints[5],_Color);
DrawLine(l_vPoints[5],l_vPoints[7],_Color);
DrawLine(l_vPoints[7],l_vPoints[6],_Color);
DrawLine(l_vPoints[6],l_vPoints[4],_Color);
//arestes
DrawLine(l_vPoints[0],l_vPoints[4],_Color);
DrawLine(l_vPoints[1],l_vPoints[5],_Color);
DrawLine(l_vPoints[2],l_vPoints[6],_Color);
DrawLine(l_vPoints[3],l_vPoints[7],_Color);
}
void CRenderManager::DrawGrid(float Size, CColor Color, int GridX, int32 GridZ )
{
assert(IsOk());
D3DXMATRIX matrix;
D3DXMatrixIdentity(&matrix);
m_pD3DDevice->SetTransform(D3DTS_WORLD, &matrix);
if(GridX <= 0)
GridX = 1;
if(GridZ <= 0)
GridZ = 1;
float l_fSliceX = Size/(float)GridX;
float l_fSliceZ = Size/(float)GridZ;
Vect3f l_vTopLeft = Vect3f(-Size/2,0,-Size/2);
Vect3f l_vTopRight = Vect3f(Size/2,0,-Size/2);
Vect3f l_vBottomLeft = Vect3f(-Size/2,0,Size/2);
Vect3f l_vIncX = Vect3f(l_fSliceX,0,0);
Vect3f l_vIncZ = Vect3f(0,0,l_fSliceZ);
Vect3f l_vCurrentLeft = l_vTopLeft;
Vect3f l_vCurrentRight = l_vTopRight;
int l_iCount = 0;
for(l_iCount = 0; l_iCount <= GridZ;l_iCount++)
{
DrawLine(l_vCurrentLeft,l_vCurrentRight,Color);
l_vCurrentLeft += l_vIncZ;
l_vCurrentRight += l_vIncZ;
}
l_vCurrentLeft = l_vTopLeft;
l_vCurrentRight = l_vBottomLeft;
for(l_iCount = 0; l_iCount <= GridX;l_iCount++)
{
DrawLine(l_vCurrentLeft,l_vCurrentRight,Color);
l_vCurrentLeft += l_vIncX;
l_vCurrentRight += l_vIncX;
}
}
void CRenderManager::DrawQuad2D (const Vect2i& _vPos, uint32 _uiW, uint32 _uiH, ETypeAlignment _Alignment, CColor _Color, ETypeFlip _bFlip)
{
assert(IsOk());
DWORD l_Color = _Color.GetUint32Argb(); //si no va, usar: D3DCOLOR_COLORVALUE(_Color.GetRed(), _Color.GetGreen(), _Color.GetBlue(), _Color.GetAlpha())
Vect2i l_vFinalPos = _vPos;
CalculateAlignment(_uiW, _uiH, _Alignment, l_vFinalPos);
// finalPos = [0]
//
// [0]------[2]
// | |
// | |
// | |
// [1]------[3]
unsigned short _usIndices[6]={0,2,1,1,2,3};
SDIFFUSESCREENVERTEX l_Vtx[4] =
{
{ (float)l_vFinalPos.x, (float)l_vFinalPos.y, 0, 1, l_Color} //(x,y) sup_esq.
,{ (float)l_vFinalPos.x, (float)l_vFinalPos.y+_uiH, 0, 1, l_Color} //(x,y) inf_esq.
,{ (float)l_vFinalPos.x+_uiW, (float)l_vFinalPos.y, 0, 1, l_Color} //(x,y) sup_dr.
,{ (float)l_vFinalPos.x+_uiW, (float)l_vFinalPos.y+_uiH, 0, 1, l_Color} //(x,y) inf_dr.
};
m_pD3DDevice->SetFVF( SDIFFUSESCREENVERTEX::GetFVF() );
m_pD3DDevice->SetTexture(0, NULL);
m_pD3DDevice->DrawIndexedPrimitiveUP( D3DPT_TRIANGLELIST,0, 4, 2, _usIndices, D3DFMT_INDEX16, l_Vtx, sizeof( SDIFFUSESCREENVERTEX ) );
}
void CRenderManager::DrawTexturedQuad2D (const Vect2i& _vPos, uint32 _uiW, uint32 _uiH, ETypeAlignment _Alignment, CTexture* _pTexture, ETypeFlip _bFlip)
{
assert(IsOk());
Vect2i l_vFinalPos = _vPos;
CalculateAlignment(_uiW, _uiH, _Alignment, l_vFinalPos);
// finalPos = [0]
//
// [0]------[2]
// | |
// | |
// | |
// [1]------[3]
unsigned short _usIndices[6]={0,2,1,1,2,3};
STEXTUREDSCREENVERTEX l_Vtx[4] =
{
{ (float)l_vFinalPos.x -0.5f, (float)l_vFinalPos.y -0.5f, 0, 1, 0.0f, 0.0f } //(x,y) sup_esq.
,{ (float)l_vFinalPos.x -0.5f, (float)l_vFinalPos.y+_uiH -0.5f, 0, 1, 0.0f, 1.0f } //(x,y) inf_esq.
,{ (float)l_vFinalPos.x+_uiW -0.5f, (float)l_vFinalPos.y -0.5f, 0, 1, 1.0f, 0.0f } //(x,y) sup_dr.
,{ (float)l_vFinalPos.x+_uiW -0.5f, (float)l_vFinalPos.y+_uiH -0.5f, 0, 1, 1.0f, 1.0f } //(x,y) inf_dr.
};
m_pD3DDevice->SetFVF( STEXTUREDSCREENVERTEX::GetFVF() );
if(_pTexture)
_pTexture->Activate(0);
m_pD3DDevice->DrawIndexedPrimitiveUP( D3DPT_TRIANGLELIST,0, 4, 2, _usIndices, D3DFMT_INDEX16, l_Vtx, sizeof( STEXTUREDSCREENVERTEX ) );
}
void CRenderManager::DrawColoredTexturedQuad2D (const Vect2i& _vPos, uint32 _uiW, uint32 _uiH, ETypeAlignment _Alignment, CColor _Color, CTexture* _pTexture, ETypeFlip _bFlip)
{
assert(IsOk());
DWORD l_Color = _Color.GetUint32Argb(); //si no va, usar: D3DCOLOR_COLORVALUE(_Color.GetRed(), _Color.GetGreen(), _Color.GetBlue(), _Color.GetAlpha())
Vect2i l_vFinalPos = _vPos;
CalculateAlignment(_uiW, _uiH, _Alignment, l_vFinalPos);
// finalPos = [0]
//
// [0]------[2]
// | |
// | |
// | |
// [1]------[3]
unsigned short _usIndices[6]={0,2,1,1,2,3};
SDIFFUSETEXTUREDSCREENVERTEX l_Vtx[4] =
{
{ (float)l_vFinalPos.x -0.5f, (float)l_vFinalPos.y -0.5f, 0, 1, l_Color, 0.0f, 0.0f } //(x,y) sup_esq.
,{ (float)l_vFinalPos.x -0.5f, (float)l_vFinalPos.y+_uiH -0.5f, 0, 1, l_Color, 0.0f, 1.0f } //(x,y) inf_esq.
,{ (float)l_vFinalPos.x+_uiW -0.5f, (float)l_vFinalPos.y -0.5f, 0, 1, l_Color, 1.0f, 0.0f } //(x,y) sup_dr.
,{ (float)l_vFinalPos.x+_uiW -0.5f, (float)l_vFinalPos.y+_uiH -0.5f, 0, 1, l_Color, 1.0f, 1.0f } //(x,y) inf_dr.
};
m_pD3DDevice->SetFVF( SDIFFUSETEXTUREDSCREENVERTEX::GetFVF() );
if(_pTexture)
_pTexture->Activate(0);
m_pD3DDevice->DrawIndexedPrimitiveUP( D3DPT_TRIANGLELIST,0, 4, 2, _usIndices, D3DFMT_INDEX16, l_Vtx, sizeof( SDIFFUSETEXTUREDSCREENVERTEX ) );
}
void CRenderManager::GetRay (const Vect2i& mousePos, Vect3f& posRay, Vect3f& dirRay)
{
assert(IsOk());
D3DXMATRIX projectionMatrix, viewMatrix, worldViewInverse, worldMatrix;
m_pD3DDevice->GetTransform(D3DTS_PROJECTION, &projectionMatrix);
m_pD3DDevice->GetTransform(D3DTS_VIEW, &viewMatrix);
m_pD3DDevice->GetTransform(D3DTS_WORLD, &worldMatrix);
float angle_x = (((2.0f * mousePos.x) / m_uWidth) - 1.0f) / projectionMatrix(0,0);
float angle_y = (((-2.0f * mousePos.y) / m_uHeight) + 1.0f) / projectionMatrix(1,1);
D3DXVECTOR3 ray_org = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 ray_dir = D3DXVECTOR3(angle_x, angle_y, 1.0f);
D3DXMATRIX m = worldMatrix * viewMatrix;
D3DXMatrixInverse(&worldViewInverse, 0, &m);
D3DXVec3TransformCoord(&ray_org, &ray_org, &worldViewInverse);
D3DXVec3TransformNormal(&ray_dir, &ray_dir, &worldViewInverse);
D3DXVec3Normalize(&ray_dir, &ray_dir);
posRay.x = ray_org.x;
posRay.y = ray_org.y;
posRay.z = ray_org.z;
dirRay.x = ray_dir.x;
dirRay.y = ray_dir.y;
dirRay.z = ray_dir.z;
}
void CRenderManager::DrawRectangle2D (const Vect2i& pos, uint32 w, uint32 h, CColor& backGroundColor, uint32 edge_w, uint32 edge_h, CColor& edgeColor)
{
assert(IsOk());
//Draw background quad2D:
DrawQuad2D(pos, w, h, UPPER_LEFT, backGroundColor);
//Draw the four edges:
//2 Horizontal:
Vect2i pos_aux = pos;
pos_aux.y -= edge_h;
DrawQuad2D(pos_aux, w, edge_h, UPPER_LEFT, edgeColor);
pos_aux = pos;
pos_aux.y += h;
DrawQuad2D(pos_aux, w, edge_h, UPPER_LEFT, edgeColor);
//2 Vertical:
pos_aux = pos;
pos_aux.x -= edge_w;
pos_aux.y -= edge_h;
DrawQuad2D(pos_aux, edge_w, h + (2*edge_w), UPPER_LEFT, edgeColor);
pos_aux.x = pos.x + w;
DrawQuad2D(pos_aux, edge_w, h + (2*edge_w), UPPER_LEFT, edgeColor);
}
void CRenderManager::RenderBoundingBox(CBoundingBox* _pBBox)
{
assert(IsOk());
const Vect3f *l_pVectBox = _pBBox->GetBox();
//DrawLine(l_pVectBox[0],_pBBox->GetMiddlePoint(),colGREEN);
/* 4 5
_____________________
/| /|
/ | / |
/ | / |
/ | / |
/ | / |
/ | / |
6 /___________________/ 7 |
| | 0 | | 1
| |___________ |______|
| / | /
| / | /
| / | /
| / | /
| / | /
2 |/__________________|/ 3
*/
DrawLine(l_pVectBox[0],l_pVectBox[1],colBLUE);
DrawLine(l_pVectBox[0],l_pVectBox[2],colBLUE);
DrawLine(l_pVectBox[0],l_pVectBox[4],colBLUE);
DrawLine(l_pVectBox[3],l_pVectBox[1],colBLUE);
DrawLine(l_pVectBox[3],l_pVectBox[2],colBLUE);
DrawLine(l_pVectBox[3],l_pVectBox[7],colBLUE);
DrawLine(l_pVectBox[4],l_pVectBox[5],colBLUE);
DrawLine(l_pVectBox[4],l_pVectBox[6],colBLUE);
DrawLine(l_pVectBox[5],l_pVectBox[1],colBLUE);
DrawLine(l_pVectBox[5],l_pVectBox[7],colBLUE);
DrawLine(l_pVectBox[6],l_pVectBox[2],colBLUE);
DrawLine(l_pVectBox[6],l_pVectBox[7],colBLUE);
}
void CRenderManager::RenderBoundingSphere(CBoundingSphere* _pBSphere)
{
assert(IsOk());
//Traslladar al centre de l'esfera
D3DMATRIX l_matD3d;
m_pD3DDevice->GetTransform(D3DTS_WORLD,&l_matD3d);
Mat44f l_matWorld(l_matD3d);
Mat44f l_matTranslation;
l_matTranslation.SetIdentity();
l_matTranslation.Translate(_pBSphere->GetMiddlePoint());
SetTransform(l_matWorld*l_matTranslation);
DrawSphere(_pBSphere->GetRadius(),colBLUE, 10);
SetTransform(l_matWorld);
}
//void CRenderManager::DrawSphere (float Radius, CColor Color, uint32 Aristas, ETypeModePaint mode, EtypeSphere typeSphere)
//{
// float l_fAngle = 180.f;
// float l_fAngle2 = 180.f;
//
// for(uint32 t=0;t<Aristas;++t)
// {
// float l_fLambda = ((float)t)/((float)Aristas);
// float l_fLambda2 = ((float)(t+1))/((float)Aristas);
// switch (typeSphere)
// {
// case HALF_TOP:
// l_fAngle = mathUtils::Deg2Rad(mathUtils::Lerp(0.f, 90.f, l_fLambda));
// l_fAngle2 = mathUtils::Deg2Rad(mathUtils::Lerp(0.f, 90.f, l_fLambda2));
// break;
// case HALF_BOTTOM:
// l_fAngle = mathUtils::Deg2Rad(mathUtils::Lerp(90.f, 180.f, l_fLambda));
// l_fAngle2 = mathUtils::Deg2Rad(mathUtils::Lerp(90.f, 180.f, l_fLambda2));
// break;
// case COMPLETE:
// l_fAngle = mathUtils::Deg2Rad(mathUtils::Lerp(0.f, 180.f, l_fLambda));
// l_fAngle2 = mathUtils::Deg2Rad(mathUtils::Lerp(0.f, 180.f, l_fLambda2));
// break;
// }
//
// std::vector<Vect3f> l_ring;
// float l_RadiusRing=Radius*sin(l_fAngle);
// Vect3f l_PosAux = v3fZERO;
// Vect3f l_PosAux2, l_PosAux3;
// for(uint32 b=0;b<Aristas;++b)
// {
// Vect3f l_PosA( l_RadiusRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))),
// Radius*cos(l_fAngle),
// l_RadiusRing*sin(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))));
//
// Vect3f l_PosB( l_RadiusRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)(b+1))/((float)Aristas))),
// Radius*cos(l_fAngle),
// l_RadiusRing*sin(mathUtils::Deg2Rad((float)(360.0f*(float)(b+1))/((float)Aristas))));
//
//
//
// float l_RadiusNextRing=Radius*sin(l_fAngle2);
//
// Vect3f l_PosC( l_RadiusRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))),
// Radius*cos(l_fAngle),
// l_RadiusRing*sin(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))));
//
// Vect3f l_PosD( l_RadiusNextRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))),
// Radius*cos(l_fAngle2),
// l_RadiusNextRing*sin(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))));
//
// if (mode != PAINT_WIREFRAME)
// {
// DrawTriangle3D(l_PosA, l_PosD, l_PosB, Color);
// if(l_PosAux != v3fZERO )
// {
// DrawTriangle3D(l_PosA, l_PosAux, l_PosD,Color);
// }
// else
// {
// l_PosAux2 = l_PosA;
// l_PosAux3 = l_PosD;
// }
//
// if(b == Aristas-1)
// {
// DrawTriangle3D(l_PosAux2, l_PosD, l_PosAux3,Color);
// }
// l_PosAux = l_PosD;
// }
//
// if( mode != PAINT_SOLID)
// {
// CColor color_aux = Color;
// if (mode == PAINT_BOTH)
// {
// color_aux = colWHITE;
// }
// DrawLine(l_PosA,l_PosB,color_aux);
// DrawLine(l_PosC,l_PosD,color_aux);
// }
// }
// }
//}
void CRenderManager::DrawPlane(float size, const Vect3f& normal, float distance, CColor Color, int GridX, int GridZ )
{
assert(IsOk());
D3DXMATRIX matrix;
D3DXMatrixIdentity(&matrix);
m_pD3DDevice->SetTransform(D3DTS_WORLD, &matrix);
//Ax + By + Cz + D = 0
//if (x,y) = (0,0) then z = -D/C
//if (x,y) = (1,1) then z = (-D-A-B)/C
//With two points we have a vector-->
float A,B,C,D;
A = normal.x;
B = normal.y;
C = normal.z;
D = distance;
//float pointAz;
//float pointBz;
Vect3f pointA, pointB;
if( C!= 0)
{
pointA = Vect3f(0.f,0.f, -D/C);
pointB = Vect3f(1.f,1.f, (D-A-B)/C);
}
else if( B!= 0)
{
pointA = Vect3f(0.f,-D/B, 0.f);
pointB = Vect3f(1.f,(-D-A-C)/B,1.f);
}
else if( A != 0)
{
pointA = Vect3f(-D/A,0.f, 0.f);
pointB = Vect3f((-D-B-C)/A,1.f,1.f);
}
else
{
//error.
}
Vect3f vectorA = pointB - pointA;
vectorA.Normalize();
Vect3f vectorB;
vectorB = normal^vectorA;
vectorB.Normalize();
Vect3f initPoint = normal*distance;
assert(GridX>0);
assert(GridZ>0);
//LINEAS EN Z
Vect3f initPointA = initPoint - vectorB*size*0.5;
for(int b=0;b<=GridX;++b)
{
DrawLine(initPointA + vectorA*size*0.5, initPointA - vectorA*size*0.5, Color );
initPointA += vectorB*size/(float)GridX;
}
initPointA = initPoint - vectorA*size*0.5;
for(int b=0;b<=GridX;++b)
{
DrawLine(initPointA + vectorB*size*0.5, initPointA - vectorB*size*0.5, Color);
initPointA += vectorA*size/(float)GridX;
}
}
void CRenderManager::DrawSphere( float Radius, const CColor& Color, int Aristas)
{
assert(IsOk());
for(int t=0;t<Aristas;++t)
{
float l_RadiusRing=Radius*sin(mathUtils::Deg2Rad(180.0f*((float)t))/((float)Aristas));
for(int b=0;b<Aristas;++b)
{
Vect3f l_PosA( l_RadiusRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))),
Radius*cos(mathUtils::Deg2Rad((180.0f*((float)t))/((float)Aristas))),
l_RadiusRing*sin(mathUtils::Deg2Rad(((float)(360.0f*(float)b)/((float)Aristas)))));
Vect3f l_PosB( l_RadiusRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)(b+1))/((float)Aristas))),
Radius*cos(mathUtils::Deg2Rad((180.0f*((float)t))/((float)Aristas))),
l_RadiusRing*sin(mathUtils::Deg2Rad(((float)(360.0f*(float)(b+1))/((float)Aristas)))));
DrawLine(l_PosA,l_PosB,Color);
float l_RadiusNextRing=Radius*sin(mathUtils::Deg2Rad(180.0f*((float)(t+1)))/((float)Aristas));
Vect3f l_PosC( l_RadiusRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))),
Radius*cos(mathUtils::Deg2Rad((180.0f*((float)t))/((float)Aristas))),
l_RadiusRing*sin(mathUtils::Deg2Rad(((float)(360.0f*(float)b)/((float)Aristas)))));
Vect3f l_PosD( l_RadiusNextRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))),
Radius*cos(mathUtils::Deg2Rad((180.0f*((float)(t+1)))/((float)Aristas))),
l_RadiusNextRing*sin(mathUtils::Deg2Rad(((float)(360.0f*(float)b)/((float)Aristas)))));
DrawLine(l_PosC,l_PosD,Color);
}
}
}
void CRenderManager::DrawSphere(const Vect3f &_Pos, float Radius, const CColor& Color, int Aristas)
{
assert(IsOk());
for(int t=0;t<Aristas;++t)
{
float l_RadiusRing=Radius*sin(mathUtils::Deg2Rad(180.0f*((float)t))/((float)Aristas));
for(int b=0;b<Aristas;++b)
{
Vect3f l_PosA( l_RadiusRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))),
Radius*cos(mathUtils::Deg2Rad((180.0f*((float)t))/((float)Aristas))),
l_RadiusRing*sin(mathUtils::Deg2Rad(((float)(360.0f*(float)b)/((float)Aristas)))));
Vect3f l_PosB( l_RadiusRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)(b+1))/((float)Aristas))),
Radius*cos(mathUtils::Deg2Rad((180.0f*((float)t))/((float)Aristas))),
l_RadiusRing*sin(mathUtils::Deg2Rad(((float)(360.0f*(float)(b+1))/((float)Aristas)))));
DrawLine(_Pos + l_PosA, _Pos + l_PosB, Color);
float l_RadiusNextRing=Radius*sin(mathUtils::Deg2Rad(180.0f*((float)(t+1)))/((float)Aristas));
Vect3f l_PosC( l_RadiusRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))),
Radius*cos(mathUtils::Deg2Rad((180.0f*((float)t))/((float)Aristas))),
l_RadiusRing*sin(mathUtils::Deg2Rad(((float)(360.0f*(float)b)/((float)Aristas)))));
Vect3f l_PosD( l_RadiusNextRing*cos(mathUtils::Deg2Rad((float)(360.0f*(float)b)/((float)Aristas))),
Radius*cos(mathUtils::Deg2Rad((180.0f*((float)(t+1)))/((float)Aristas))),
l_RadiusNextRing*sin(mathUtils::Deg2Rad(((float)(360.0f*(float)b)/((float)Aristas)))));
DrawLine(_Pos + l_PosC, _Pos + l_PosD, Color);
}
}
}
void CRenderManager::DrawShadedSphere(const Vect3f &_vPos, float _fRadius, CEffect* _pEffect)
{
CEffectManager* l_pEM = CORE->GetEffectManager();
Mat44f m;
m.SetIdentity();
m.Scale(_fRadius,_fRadius,_fRadius);
m.Translate(_vPos);
//SetTransform(m);
l_pEM->SetWorldMatrix(m);
l_pEM->LoadShaderData(_pEffect);
m_pSphereVertex->Render(this, _pEffect);
}
| [
"[email protected]",
"sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485",
"atridas87@576ee6d0-068d-96d9-bff2-16229cd70485",
"edual1985@576ee6d0-068d-96d9-bff2-16229cd70485",
"Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485",
"galindix@576ee6d0-068d-96d9-bff2-16229cd70485",
"mudarra@576ee6d0-068d-96d9-bff2-16229cd70485"
] | [
[
[
1,
3
],
[
12,
13
],
[
15,
34
],
[
39,
42
],
[
45,
46
],
[
48,
52
],
[
55,
55
],
[
57,
60
],
[
62,
105
],
[
108,
110
],
[
112,
125
],
[
153,
155
],
[
324,
326
],
[
328,
336
],
[
338,
338
],
[
358,
358
],
[
361,
364
],
[
366,
366
],
[
368,
368
],
[
372,
372
],
[
374,
386
],
[
395,
396
],
[
398,
398
],
[
400,
400
],
[
406,
408
],
[
473,
473
],
[
478,
478
],
[
483,
486
],
[
492,
493
],
[
511,
513
],
[
538,
540
],
[
589,
590
],
[
595,
596
],
[
680,
680
],
[
683,
683
],
[
685,
685
],
[
688,
690
],
[
693,
696
],
[
698,
701
],
[
703,
714
]
],
[
[
4,
4
],
[
8,
8
],
[
38,
38
],
[
47,
47
],
[
146,
147
],
[
149,
152
],
[
357,
357
],
[
365,
365
],
[
369,
371
],
[
387,
394
],
[
397,
397
],
[
401,
405
],
[
412,
423
],
[
436,
471
],
[
482,
482
],
[
516,
517
],
[
519,
522
],
[
524,
525
],
[
601,
601
],
[
603,
603
],
[
616,
617
],
[
719,
720
],
[
722,
723
],
[
785,
786
],
[
845,
845
],
[
847,
879
],
[
881,
895
],
[
897,
897
],
[
902,
902
],
[
906,
906
],
[
910,
910
],
[
914,
915
],
[
919,
919
],
[
923,
923
],
[
927,
927
],
[
931,
933
],
[
935,
938
],
[
940,
944
],
[
946,
956
],
[
958,
970
],
[
973,
979
],
[
1004,
1005
],
[
1007,
1047
],
[
1191,
1193
],
[
1195,
1196
],
[
1198,
1230
],
[
1237,
1249
],
[
1252,
1254
]
],
[
[
5,
5
],
[
7,
7
],
[
14,
14
],
[
35,
36
],
[
56,
56
],
[
61,
61
],
[
106,
107
],
[
111,
111
],
[
131,
131
],
[
133,
133
],
[
135,
135
],
[
327,
327
],
[
337,
337
],
[
352,
352
],
[
354,
354
],
[
356,
356
],
[
367,
367
],
[
399,
399
],
[
474,
477
],
[
481,
481
],
[
487,
491
],
[
494,
510
],
[
514,
515
],
[
518,
518
],
[
523,
523
],
[
526,
537
],
[
541,
544
],
[
546,
546
],
[
555,
588
],
[
591,
594
],
[
597,
600
],
[
602,
602
],
[
604,
608
],
[
613,
615
],
[
618,
618
],
[
637,
637
],
[
639,
639
],
[
679,
679
],
[
681,
682
],
[
684,
684
],
[
686,
687
],
[
691,
692
],
[
697,
697
],
[
702,
702
],
[
715,
718
],
[
721,
721
],
[
724,
724
],
[
731,
784
],
[
846,
846
],
[
880,
880
],
[
896,
896
],
[
898,
901
],
[
903,
905
],
[
907,
909
],
[
911,
913
],
[
916,
918
],
[
920,
922
],
[
924,
926
],
[
928,
930
],
[
934,
934
],
[
939,
939
],
[
945,
945
],
[
957,
957
],
[
971,
972
],
[
1006,
1006
],
[
1048,
1049
],
[
1051,
1051
],
[
1065,
1065
],
[
1067,
1070
],
[
1073,
1073
],
[
1075,
1075
],
[
1078,
1107
],
[
1109,
1109
],
[
1123,
1123
],
[
1125,
1128
],
[
1131,
1134
],
[
1136,
1165
],
[
1167,
1167
]
],
[
[
6,
6
],
[
126,
130
],
[
132,
132
],
[
134,
134
],
[
136,
136
],
[
339,
339
],
[
347,
351
],
[
353,
353
],
[
355,
355
],
[
1190,
1190
]
],
[
[
9,
11
],
[
37,
37
],
[
43,
44
],
[
53,
54
],
[
137,
145
],
[
148,
148
],
[
156,
323
],
[
340,
346
],
[
373,
373
],
[
409,
411
],
[
424,
435
],
[
472,
472
],
[
479,
480
],
[
545,
545
],
[
547,
554
],
[
844,
844
],
[
980,
1003
],
[
1443,
1490
]
],
[
[
359,
360
],
[
725,
730
],
[
787,
843
],
[
1231,
1231
],
[
1258,
1344
],
[
1346,
1412
],
[
1414,
1442
]
],
[
[
609,
612
],
[
619,
636
],
[
638,
638
],
[
640,
678
],
[
1050,
1050
],
[
1052,
1064
],
[
1066,
1066
],
[
1071,
1072
],
[
1074,
1074
],
[
1076,
1077
],
[
1108,
1108
],
[
1110,
1122
],
[
1124,
1124
],
[
1129,
1130
],
[
1135,
1135
],
[
1166,
1166
],
[
1168,
1189
],
[
1194,
1194
],
[
1197,
1197
],
[
1232,
1236
],
[
1250,
1251
],
[
1255,
1257
],
[
1345,
1345
],
[
1413,
1413
]
]
] |
de0d20450982ca83a389855440702385c8ce0795 | 4146d9298ac7407af57ac4c8b1381b99ad67fdc2 | /animator.cpp | eabb4447502d3c5d0ebdd9dfe9c057373b3edb76 | [] | no_license | keithfancher/Alien-vs.-Sephiroth | b0749b3b409dbc258f11c36847462ed85eb88153 | 3747408409b3af2cf7bcdb6d2ee4fbfad97b014f | refs/heads/master | 2020-04-13T18:03:46.462586 | 2011-07-24T02:57:31 | 2011-07-24T02:57:31 | 2,304,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,310 | cpp | // File : animator.cpp
// Program: CS4465, Final Project
// Author : Keith T. Fancher
// Date : 04/13/2006
// Purpose: A fight scene between an Alien and Sephiroth, utilizing
// the .md2 model file format.
#include <GL/glut.h>
#include <time.h>
#include "animator.h"
#include "md2.h"
#include "scene.h"
// time variables
unsigned long initTime = 0;
unsigned long timeElapsed = 0;
// model data
CMD2Data * alienModel = NULL;
CMD2Data * sephirothModel = NULL;
CMD2Instance * alienInstance = NULL;
CMD2Instance * sephirothInstance = NULL;
GLfloat sceneRotation = 0.0f;
void loadAlienModel()
{
if(alienModel)
{
delete alienModel;
alienModel = NULL;
}
alienModel = new CMD2Data;
alienModel->Load("alien\\tris.md2", "alien\\alien.tga", NULL, NULL, 1.5);
if(alienInstance)
{
delete alienInstance;
alienInstance = NULL;
}
alienInstance = alienModel->GetInstance();
}
void loadAlienModelArmed()
{
if(alienModel)
{
delete alienModel;
alienModel = NULL;
}
alienModel = new CMD2Data;
alienModel->Load("alien\\tris.md2", "alien\\alien.tga", "alien\\weapon.md2", "alien\\weapon.tga", 1.5);
if(alienInstance)
{
delete alienInstance;
alienInstance = NULL;
}
alienInstance = alienModel->GetInstance();
}
void loadSephirothModel()
{
if(sephirothModel)
{
delete sephirothModel;
sephirothModel = NULL;
}
sephirothModel = new CMD2Data;
sephirothModel->Load("sephiroth\\tris.md2", "sephiroth\\sephiroth.tga", NULL, NULL, 1.5);
if(sephirothInstance)
{
delete sephirothInstance;
sephirothInstance = NULL;
}
sephirothInstance = sephirothModel->GetInstance();
}
void loadSephirothModelArmed()
{
if(sephirothModel)
{
delete sephirothModel;
sephirothModel = NULL;
}
sephirothModel = new CMD2Data;
sephirothModel->Load("sephiroth\\tris.md2", "sephiroth\\sephiroth.tga", "sephiroth\\weapon.md2", "sephiroth\\weapon.tga", 1.5);
if(sephirothInstance)
{
delete sephirothInstance;
sephirothInstance = NULL;
}
sephirothInstance = sephirothModel->GetInstance();
}
void init()
{
// set up window
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-140, 140, -70, 70, -250, 250);
//glFrustum(-500, 500, -500, 500, -500, 500);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
// load models
glEnable(GL_TEXTURE_2D);
loadAlienModel();
loadSephirothModel();
// set timer
initTime = time(NULL);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
animateScene(timeElapsed, sephirothInstance, alienInstance);
glFlush();
glutSwapBuffers();
}
void idle()
{
timeElapsed = time(NULL) - initTime;
sceneRotation += 0.1f;
if(sceneRotation >= 360.0f)
sceneRotation = 0.0f;
glutPostRedisplay();
}
int main(int argc, char ** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(1000, 500);
glutCreateWindow("Alien vs. Sephiroth");
glutDisplayFunc(display);
glutIdleFunc(idle);
init();
glutMainLoop();
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
162
]
]
] |
060b96994a1901943cd0126ac3ab470186c9034e | 40b507c2dde13d14bb75ee1b3c16b4f3f82912d1 | /extensions/bintools/extension.cpp | be88bb09f455ce194a5cb80009f4f7d1808c3eae | [] | no_license | Nephyrin/-furry-octo-nemesis | 5da2ef75883ebc4040e359a6679da64ad8848020 | dd441c39bd74eda2b9857540dcac1d98706de1de | refs/heads/master | 2016-09-06T01:12:49.611637 | 2008-09-14T08:42:28 | 2008-09-14T08:42:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,020 | cpp | /**
* vim: set ts=4 :
* =============================================================================
* SourceMod BinTools Extension
* Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, 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 for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include "extension.h"
#include "CallMaker.h"
/**
* @file extension.cpp
* @brief Implements BinTools extension code.
*/
BinTools g_BinTools; /**< Global singleton for extension's main interface */
CallMaker g_CallMaker;
ISourcePawnEngine *g_SPEngine;
SMEXT_LINK(&g_BinTools);
bool BinTools::SDK_OnLoad(char *error, size_t maxlength, bool late)
{
g_SPEngine = g_pSM->GetScriptingEngine();
g_pShareSys->AddInterface(myself, &g_CallMaker);
return true;
}
| [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
2
],
[
7,
7
],
[
28,
36
],
[
38,
39
],
[
41,
45
],
[
47,
52
]
],
[
[
3,
4
],
[
6,
6
],
[
8,
10
],
[
12,
15
],
[
17,
18
],
[
20,
27
],
[
37,
37
],
[
40,
40
],
[
46,
46
]
],
[
[
5,
5
],
[
11,
11
],
[
16,
16
],
[
19,
19
]
]
] |
46a88aa5293624d424a82821fe9f580350fadb59 | 990daa26d6ab2c756927bce8d962c41fa7a8cdad | /jpeg/MfcApp.h | cc8854cd0d1464161a2010806944a12e9cb8e5d4 | [] | no_license | goebish/VfxAviPlayer | 1e7bcbc5bd620f0ed08b99328d5f42f84c16982c | 74ef7e09eb9ea0961a81bc0a41c18ffd1941d922 | refs/heads/master | 2020-05-26T12:38:32.289356 | 2009-05-02T16:31:23 | 2009-05-02T16:31:23 | 188,234,834 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,366 | h | // MfcApp.h : main header file for the MFCAPP application
//
#if !defined(AFX_MFCAPP_H__7B4DD987_945B_11D2_815A_444553540000__INCLUDED_)
#define AFX_MFCAPP_H__7B4DD987_945B_11D2_815A_444553540000__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
/////////////////////////////////////////////////////////////////////////////
// CMfcAppApp:
// See MfcApp.cpp for the implementation of this class
//
class CMfcAppApp : public CWinApp
{
public:
CMfcAppApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMfcAppApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CMfcAppApp)
afx_msg void OnAppAbout();
// 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 Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MFCAPP_H__7B4DD987_945B_11D2_815A_444553540000__INCLUDED_)
| [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
05a623f4dad108be2bc2f273ed004e4dab87f34e | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctesteh/inc/bctestehdocument.h | 463b8bb48e3d87b469979c4488c3d01a69038e53 | [] | 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,661 | h | /*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#ifndef C_BCTESTEHDOCUMENT_H
#define C_BCTESTEHDOCUMENT_H
// INCLUDES
#include <eikdoc.h>
// CONSTANTS
// FORWARD DECLARATIONS
class CEikAppUi;
// CLASS DECLARATION
/**
* CBCTestEHDocument application class.
*/
class CBCTestEHDocument : public CEikDocument
{
public: // Constructors and destructor
/**
* Symbian OS two-phased constructor.
* @return Pointer to created Document class object.
* @param aApp Reference to Application class object.
*/
static CBCTestEHDocument* NewL( CEikApplication& aApp );
/**
* Destructor.
*/
virtual ~CBCTestEHDocument();
private: // Constructors
/**
* Overload constructor.
* @param aApp Reference to Application class object.
*/
CBCTestEHDocument( CEikApplication& aApp );
private: // From CEikDocument
/**
* From CEikDocument, CreateAppUiL.
* Creates CBCTestEHAppUi "App UI" object.
* @return Pointer to created AppUi class object.
*/
CEikAppUi* CreateAppUiL();
};
#endif // C_BCTESTEHDOCUMENT_H
// End of File
| [
"none@none"
] | [
[
[
1,
72
]
]
] |
973602b41d42d304e1ccd45cf363095179cef348 | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/core/command/command_adder.cpp | 9340dcc204fab0eab9f8669d06d93c231ce0999f | [] | no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null | UTF-8 | C++ | false | false | 2,235 | cpp | #include "config.hpp"
#include "command_adder.hpp"
#include "command_manager.hpp"
#include <functional>
cmd_id_t command_add(std::string const& sys_name, std::string const& section, std::string const& name, std::string const& params, std::string const& short_desc, std::string const& full_desc, command_handler_t command, command_type type /*= cmd_game*/, command_access_checker_t const& access_checker, bool is_hidden) {
return command_manager::instance()->add_command(command_t(sys_name, section, name, params, short_desc, full_desc, command, type, access_checker, is_hidden));
}
cmd_id_t command_add(std::string const& sys_name, command_handler_t command, command_type type, command_access_checker_t const& access_checker, bool is_hidden) {
return command_manager::instance()->add_command(command_t(sys_name, "$(cmd_" + sys_name + "_section)", "$(cmd_" + sys_name + "_name)", "$(cmd_" + sys_name + "_params)", "$(cmd_" + sys_name + "_short)", "$(cmd_" + sys_name + "_full)", command, type, access_checker, is_hidden));
}
cmd_id_t command_add_text(std::string const& sys_name, std::string const& section, std::string const& name, std::string const& params, std::string const& short_desc, std::string const& text, command_access_checker_t const& access_checker, bool is_hidden) {
return command_add(sys_name, section, name, params, short_desc, "", bind(&command_manager::cmd_print_text, command_manager::instance().get(), std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5, text), cmd_info_only, access_checker, is_hidden);
}
cmd_id_t command_add_text(std::string const& sys_name, command_access_checker_t const& access_checker, bool is_hidden) {
return command_add(sys_name, "$(cmd_" + sys_name + "_section)", "$(cmd_" + sys_name + "_name)", "$(cmd_" + sys_name + "_params)", "$(cmd_" + sys_name + "_short)", "", bind(&command_manager::cmd_print_text, command_manager::instance().get(), std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5, "$(cmd_" + sys_name + "_text)"), cmd_info_only, access_checker, is_hidden);
}
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
] | [
[
[
1,
20
]
]
] |
4bbefec7c4739dbdcf6399724f6a05e3eb662c70 | 2c1e5a69ca68fe185cc04c5904aa104b0ba42e32 | /src/game/GWorldMap.h | 16dc5bb8cce68703fd76e3d848d22ab0ecdb2bb1 | [] | no_license | dogtwelve/newsiderpg | e3f8284a7cd9938156ef8d683dca7bcbd928c593 | 303566a034dca3e66cf0f29cf9eaea1d54d63e4a | refs/heads/master | 2021-01-10T13:03:31.986204 | 2010-06-27T05:36:33 | 2010-06-27T05:36:33 | 46,550,247 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 467 | h | #include "VBaseState.h"
#include "SUtil.h"
#ifndef __GWORLDMAP_
#define __GWORLDMAP_
class GWorldMap : public VBaseState
{
public:
GWorldMap();
~GWorldMap();
void Initialize(int nDummy1, int nDummy2);
void Release();
void Process();
void Paint();
void KeyEvent(int m_keyCode, int m_keyRepeat);
int m_nEventIndex;
class ASprite* m_pWorldMapAs;
class ASpriteInstance* m_pWorldMapAsIns;
};
#endif //__GWORLDMAP
| [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
3303a737157327b4f20b05138530491683d13e8c | 6e4f9952ef7a3a47330a707aa993247afde65597 | /PROJECTS_ROOT/SmartWires/SystemUtils/myspell/myspell.hxx | 7e534ca5ed6bb96e17639e1aac8c3c90ed1d89d4 | [
"BSD-2-Clause"
] | permissive | meiercn/wiredplane-wintools | b35422570e2c4b486c3aa6e73200ea7035e9b232 | 134db644e4271079d631776cffcedc51b5456442 | refs/heads/master | 2021-01-19T07:50:42.622687 | 2009-07-07T03:34:11 | 2009-07-07T03:34:11 | 34,017,037 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 737 | hxx | #ifndef _MYSPELLMGR_HXX_
#define _MYSPELLMGR_HXX_
#include "hashmgr.hxx"
#include "affixmgr.hxx"
#include "suggestmgr.hxx"
#include "csutil.hxx"
#define NOCAP 0
#define INITCAP 1
#define ALLCAP 2
#define HUHCAP 3
class MySpell
{
AffixMgr* pAMgr;
HashMgr* pHMgr;
SuggestMgr* pSMgr;
char * encoding;
struct cs_info * csconv;
int maxSug;
public:
MySpell(const char * affpath, const char * dpath);
~MySpell();
int suggest(char*** slst, const char * word);
int spell(const char *);
char * get_dic_encoding();
bool isvalid();
private:
int cleanword(char *, const char *, int *, int *);
char * check(const char *);
};
#endif
| [
"wplabs@3fb49600-69e0-11de-a8c1-9da277d31688"
] | [
[
[
1,
37
]
]
] |
44233d58f7b484b5eb6ed28d3beaefd657c74188 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/contrib/nluaserver/src/luaserver/nluarun.cc | 3e8b98d7108cca2a1be15a38b392278730825f74 | [] | no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,785 | cc | //--------------------------------------------------------------------
// nluarun.cc -- Command processing
//
// Derived from npythonrun.cc by Jason Asbahr
// Derived from ntclrun.cc by Andre Weissflog
// (c) 2003 Matthew T. Welker
//
// nLuaServer is licensed under the terms of the Nebula License
//--------------------------------------------------------------------
#include "luaserver/nluaserver.h"
#include "kernel/nfileserver2.h"
#include "kernel/nfile.h"
#ifdef __VC__
// VC6 warning ignorance
#pragma warning(push)
#pragma warning(disable:4800)
#endif
//--------------------------------------------------------------------
/**
@brief Executes the chunk at the top of the Lua stack.
*/
bool nLuaServer::ExecuteLuaChunk(nString& result, int errfunc)
{
n_assert2(errfunc > 0, "Error function stack index must be absolute!");
// call chunk main
int status = lua_pcall(this->L,
0 /* no args */,
LUA_MULTRET,
errfunc /* stack index of error handler */);
if (0 != status) // error occurred
{
result = this->outputStr; // contains the error info
n_message(result.Get());
lua_settop(this->L, 0); // clear stack
}
else
{
result.Clear();
this->StackToString(this->L, 0, result);
}
return (0 == status);
}
//--------------------------------------------------------------------
/**
@brief Empties the Lua stack and returns a string representation
of the contents.
@param L Pointer to the Lua state.
@param bottom Absolute index of the bottom stack item.
Only items between the bottom index and the stack top
(excluding the bottom index) will be crammed into the
string, passing 0 for the bottom will dump all the
items in the stack.
*/
void nLuaServer::StackToString(lua_State* L, int bottom, nString& result)
{
while (bottom < lua_gettop(L))
{
switch (lua_type(L, -1))
{
case LUA_TBOOLEAN:
{
if (lua_toboolean(L, -1))
result.Append("true");
else
result.Append("false");
break;
}
case LUA_TNUMBER:
case LUA_TSTRING:
{
result.Append(lua_tostring(L, -1));
break;
}
case LUA_TUSERDATA:
case LUA_TLIGHTUSERDATA:
{
result.Append("<userdata>");
break;
}
case LUA_TNIL:
{
result.Append("<nil>");
break;
}
case LUA_TTABLE:
{
// check if it's a thunk
lua_pushstring(L, "_");
lua_rawget(L, -2);
if (lua_isuserdata(L, -1))
{
// assume it's a thunk
result.Append("<thunk>");
}
else
{
result.Append("{ ");
lua_pushnil(L);
lua_gettable(L, -2);
bool firstItem = true;
while (lua_next(L, -2) != 0)
{
if (!firstItem)
result.Append(", ");
else
firstItem = false;
nLuaServer::StackToString(L, lua_gettop(L) - 1, result);
}
lua_pop(L, 1);
result.Append(" }");
}
break;
}
default:
//result.Append("???");
break;
}
lua_pop(L, -1);
}
}
//--------------------------------------------------------------------
// Prompt()
//--------------------------------------------------------------------
nString nLuaServer::Prompt()
{
nString prompt = kernelServer->GetCwd()->GetFullName();
prompt.Append("> ");
return prompt;
}
//--------------------------------------------------------------------
/**
@brief Execute a chunk of Lua code and provide a string
representation of the result.
@param cmdStr A null-terminated string of Lua code.
@param result The result (if any) of the execution of the Lua code.
@return true if Lua code ran without any errors, false otherwise.
*/
bool nLuaServer::Run(const char* cmdStr, nString& result)
{
n_assert(cmdStr);
// push the error handler on stack
lua_pushstring(this->L, "_LUASERVER_STACKDUMP");
lua_gettable(this->L, LUA_GLOBALSINDEX);
n_assert2(lua_isfunction(this->L, -1), "Error handler not registered!");
int errfunc = lua_gettop(this->L);
// load chunk
int status = luaL_loadbuffer(this->L, cmdStr, strlen(cmdStr), cmdStr);
if (0 == status) // parse OK?
{
return this->ExecuteLuaChunk(result, errfunc);
}
// pop error message from the stack
result.Clear();
this->StackToString(this->L, lua_gettop(this->L) - 1, result);
return false;
}
//--------------------------------------------------------------------
/**
@brief Read in Lua code from a file and execute it.
@param filename The name of the file to be read and executed.
@param result Result (if any) of executing the Lua code.
@return true if Lua code ran without any errors, false otherwise.
This function will allow explicit return statements from the
file - and requires it for output.
*/
bool nLuaServer::RunScript(const char* filename, nString& result)
{
n_assert(filename);
int filesize;
char* cmdbuf;
bool retval;
nFile* nfile = nFileServer2::Instance()->NewFileObject();
nString path = nFileServer2::Instance()->ManglePath(filename);
if (!nfile->Open(path, "r"))
{
result.Clear();
nfile->Release();
return false;
}
nfile->Seek(0, nFile::END);
filesize = nfile->Tell();
nfile->Seek(0, nFile::START);
cmdbuf = (char*)n_malloc(filesize + 1);
n_assert2(cmdbuf, "Failed to allocate command buffer!");
nfile->Read(cmdbuf, filesize + 1);
cmdbuf[filesize] = 0;
nfile->Close();
nfile->Release();
retval = this->Run(cmdbuf, result);
if (!retval)
{
if (!result.IsEmpty())
{
n_message("nLuaServer::RunScript failed:\nfile: %s\nmessage:\n%s\n",
path.Get(), result.Get());
}
else
{
n_message("nLuaServer::RunScript failed:\nfile: %s\n", path.Get());
}
}
n_free(cmdbuf);
return retval;
}
//--------------------------------------------------------------------
/**
@brief Invoke a Lua function.
*/
bool nLuaServer::RunFunction(const char* funcName, nString& result)
{
nString cmdStr = funcName;
cmdStr.Append("()");
return this->Run(cmdStr.Get(), result);
}
//--------------------------------------------------------------------
// Trigger()
//--------------------------------------------------------------------
bool nLuaServer::Trigger()
{
// The Trigger, she does nothing...
return nScriptServer::Trigger();
}
#ifdef __VC__
// VC6 thing
#pragma warning(pop)
#endif
//--------------------------------------------------------------------
// EOF
//--------------------------------------------------------------------
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
252
]
]
] |
f10226f943904739c31570fe359c6a5ff2fdac54 | 7dd2dbb15df45024e4c3f555da6d9ca6fc2c4d8b | /maelstrom/Forms/splashscreen.h | ce60c00e99c1c779c774cedb3c12eefeeff45995 | [] | no_license | wangscript/maelstrom-editor | c9f761e1f9e5f4e64d7e37834a7a63e04f57ae31 | 5bfab31bf444f44b9f8209f4deaed8715c305426 | refs/heads/master | 2021-01-10T01:37:00.619456 | 2011-11-21T23:17:08 | 2011-11-21T23:17:08 | 50,160,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 398 | h | #ifndef SPLASHSCREEN_H
#define SPLASHSCREEN_H
#include<QSplashScreen>
namespace Ui {
class SplashScreen;
}
class SplashScreen : public QSplashScreen
{
Q_OBJECT
public:
explicit SplashScreen(QWidget *parent = 0);
~SplashScreen();
public slots:
void showMessage(const QString &message);
private:
Ui::SplashScreen *ui;
};
#endif // SPLASHSCREEN_H
| [
"[email protected]"
] | [
[
[
1,
24
]
]
] |
841bbfd7e29979f18b063d38bec9962f1660d502 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SEMath/SEConvexPolyhedron3.h | e365a42923bba3d2d7aef8cc6ebf1c6c48ea65c2 | [] | 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 | 4,478 | h | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_ConvexPolyhedron3_H
#define Swing_ConvexPolyhedron3_H
#include "SEFoundationLIB.h"
#include "SEPolyhedron3.h"
#include "SEPlane3.h"
namespace Swing
{
//----------------------------------------------------------------------------
// Description:
// Author:Sun Che
// Date:20081124
//----------------------------------------------------------------------------
class SE_FOUNDATION_API SEConvexPolyhedron3f : public SEPolyhedron3f
{
public:
// 调用者有责任确保传入的数据构成凸多面体.
// 从外侧观看mesh时,三角面的索引顺序应为顺时针方向.
// bOwner为true时,convex polyhedron拥有传入数组的所有权.
// 否则为false时,由调用者负责删除传入数组.
//
// 本类存储与三角面对应的平面数组,平面法线指向多面体内部.
// 可以通过构造函数传入平面数组,从而bOwner也决定该数组所有权.
// 如果没有传入平面数组,则本类对象自己负责创建该数组,从而不受bOwner影响.
SEConvexPolyhedron3f(int iVCount, SEVector3f* aVertex,
int iTCount, int* aiIndex, SEPlane3f* aPlane, bool bOwner);
// 如果传入的polyhedron拥有其数组数据,则为'this'对象复制其数组数据,
// 从而使'this'对象也拥有其数组数据.
// 如果传入的polyhedron不拥有其数组数据,则'this'对象也不拥有.只进行指针共享.
SEConvexPolyhedron3f(const SEConvexPolyhedron3f& rPoly);
virtual ~SEConvexPolyhedron3f(void);
// 如果传入的polyhedron拥有其数组数据,则为'this'对象复制其数组数据,
// 从而使'this'对象也拥有其数组数据.
// 如果传入的polyhedron不拥有其数组数据,则'this'对象也不拥有.只进行指针共享.
SEConvexPolyhedron3f& operator = (const SEConvexPolyhedron3f& rPoly);
const SEPlane3f* GetPlanes(void) const;
const SEPlane3f& GetPlane(int i) const;
// 允许对顶点进行修改.
// 调用者必须确保mesh仍为convex ployhedron.
// 修改顶点后需要调用UpdatePlanes()函数.
// 如果所有修改顶点操作都是通过SetVertex函数完成的,
// 则只有受到影响的三角面的plane会被重新计算.
// 否则如果有通过GetVertices函数修改的顶点,
// 则本类将无法得知具体修改的信息,从而使UpdatePlanes()函数更新全部plane.
virtual void SetVertex(int i, const SEVector3f& rV);
void UpdatePlanes(void);
// 凸面体性检测.
// 函数将迭代多面体的所有三角面,
// 并验证所有多面体顶点都必须在该三角面的非负空间.
// 使用带符号的距离测试,从而当一个顶点处在三角面负半空间时,
// 其距离满足d < 0.
// 同时为了避免数值误差造成的错误判断,允许使用一个负数临界值t,
// 从而使距离判断成为 d < t < 0.
bool IsConvex(float fThreshold = 0.0f) const;
// Point-in-polyhedron测试.
// 临界值t与IsConvex函数中的用途一样.
bool ContainsPoint(const SEVector3f& rP, float fThreshold = 0.0f)
const;
protected:
SEPlane3f* m_aPlane;
bool m_bPlaneOwner;
// 支持高效更新平面数组.
// set存储了更改顶点数据时所影响到的三角面的索引.
// 从而允许只针对修改过的三角面进行更新.
void UpdatePlane(int i, const SEVector3f& rAverage);
std::set<int> m_TModified;
};
}
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
102
]
]
] |
2600e8e84c41952f4f8437d40130afc9cbb46cf9 | 7ee1bcc17310b9f51c1a6be0ff324b6e297b6c8d | /AppData/Sources/VS 2005 WinCE WTL 8.0 SDI/Source/MainFrame.h | bfb9ce417d3d1b72dfd642d756419b5c832e2779 | [] | no_license | SchweinDeBurg/afx-scratch | 895585e98910f79127338bdca5b19c5e36921453 | 3181b779b4bb36ef431e5ce39e297cece1ca9cca | refs/heads/master | 2021-01-19T04:50:48.770595 | 2011-06-18T05:14:22 | 2011-06-18T05:14:22 | 32,185,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,376 | h | // $PROJECT$ application.
// Copyright (c) $YEAR$ by $AUTHOR$,
// All rights reserved.
// MainFrame.h - interface of the CMainFrame class
// initially generated by $GENERATOR$ on $DATE$ at $TIME$
// visit http://zarezky.spb.ru/projects/afx_scratch.html for more info
#if !defined(__MainFrame_h)
#define __MainFrame_h
#if defined(_MSC_VER) && (_MSC_VER > 1000)
#pragma once
#endif // _MSC_VER
class CMainFrame:
// ancestors
public WTL::CFrameWindowImpl<CMainFrame>,
public WTL::CMessageFilter,
public WTL::CAppWindow<CMainFrame>
{
// internal short aliases
private:
typedef WTL::CFrameWindowImpl<CMainFrame> TBaseFrame;
typedef WTL::CAppWindow<CMainFrame> TBaseAppWindow;
// construction/destruction
public:
CMainFrame(void);
virtual ~CMainFrame(void);
// overridables
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
// message handlers
protected:
LRESULT OnCreate(CREATESTRUCT* lpCS);
void OnAppExit(UINT uCode, int nID, HWND hWndCtrl);
// window class definition
public:
DECLARE_FRAME_WND_CLASS(_T("WC_$PROJECT$_MainFrame"), IDR_MAIN_FRAME)
// message map
protected:
BEGIN_MSG_MAP(CMainFrame)
MSG_WM_CREATE(OnCreate)
COMMAND_ID_HANDLER_EX(ID_APP_EXIT, OnAppExit)
CHAIN_MSG_MAP(TBaseAppWindow)
CHAIN_MSG_MAP(TBaseFrame)
END_MSG_MAP()
};
#endif // __MainFrame_h
// end of file
| [
"Elijah@9edebcd1-9b41-0410-8d36-53a5787adf6b",
"Elijah Zarezky@9edebcd1-9b41-0410-8d36-53a5787adf6b",
"elijah@9edebcd1-9b41-0410-8d36-53a5787adf6b"
] | [
[
[
1,
14
],
[
16,
16
],
[
22,
22
],
[
25,
27
],
[
42,
55
],
[
57,
58
]
],
[
[
15,
15
],
[
18,
21
],
[
23,
24
],
[
28,
41
],
[
56,
56
]
],
[
[
17,
17
]
]
] |
6c29bd62072d2fa9440d5f1c75cea4eacdf46ed6 | 3bfc30f7a07ce0f6eabcd526e39ba1030d84c1f3 | /BlobbyWarriors/Source/BlobbyWarriors/Logic/ContactListener.h | 012aadd7da189f4279636dcff41140ba2fc0be50 | [] | no_license | visusnet/Blobby-Warriors | b0b70a0b4769b60d96424b55ad7c47b256e60061 | adec63056786e4e8dfcb1ed7f7fe8b09ce05399d | refs/heads/master | 2021-01-19T14:09:32.522480 | 2011-11-29T21:53:25 | 2011-11-29T21:53:25 | 2,850,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,083 | h | #ifndef CONTACTLISTENER_H
#define CONTACTLISTENER_H
#include <Box2D.h>
#include "../PublishSubscribe.h"
enum ContactType
{
CONTACT_TYPE_UNKNOWN = 0,
CONTACT_TYPE_BEGIN = 1,
CONTACT_TYPE_END = 2,
CONTACT_TYPE_PRESOLVE = 3,
CONTACT_TYPE_POSTSOLVE = 4
};
class ContactEventArgs : public UpdateData
{
public:
int type;
b2Contact *contact;
b2Manifold *oldManifold;
b2ContactImpulse *impulse;
};
class ContactListener : public b2ContactListener, public Publisher
{
public:
static ContactListener* getInstance();
void BeginContact(b2Contact *contact);
void EndContact(b2Contact *contact);
void PreSolve(b2Contact *contact, const b2Manifold *oldManifold);
void PostSolve(b2Contact *contact, const b2ContactImpulse *impulse);
private:
ContactListener();
ContactListener(const ContactListener&);
~ContactListener();
static ContactListener *instance;
class Guard
{
public:
~Guard()
{
if (ContactListener::instance != 0) {
delete ContactListener::instance;
}
}
};
friend class Guard;
};
#endif | [
"[email protected]"
] | [
[
[
1,
55
]
]
] |
064972dbdbf3b83344dfed5b6e3d2359b8ebbd5d | cf58ec40b7ea828aba01331ee3ab4c7f2195b6ca | /Nestopia/core/board/NstBoardBandaiDatach.cpp | 54e735c3107bf429590e2974f82c819f35a16076 | [] | no_license | nicoya/OpenEmu | e2fd86254d45d7aa3d7ef6a757192e2f7df0da1e | dd5091414baaaddbb10b9d50000b43ee336ab52b | refs/heads/master | 2021-01-16T19:51:53.556272 | 2011-08-06T18:52:40 | 2011-08-06T18:52:40 | 2,131,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,885 | cpp | ////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Nestopia 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 Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#include <cstring>
#include "../NstClock.hpp"
#include "NstBoard.hpp"
#include "NstBoardBandai.hpp"
namespace Nes
{
namespace Core
{
namespace Boards
{
namespace Bandai
{
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("s", on)
#endif
Datach::Datach(const Context& c)
:
Lz93d50Ex (c),
barcodeReader (*c.cpu)
{
}
Datach::Reader::Reader(Cpu& c)
: cpu(c)
{
Reset( false );
}
Datach::Device Datach::QueryDevice(DeviceType devType)
{
if (devType == DEVICE_BARCODE_READER)
return static_cast<BarcodeReader*>(&barcodeReader);
else
return Lz93d50Ex::QueryDevice( devType );
}
void Datach::SubReset(const bool hard)
{
Lz93d50Ex::SubReset( hard );
barcodeReader.Reset();
p6000 = cpu.Map( 0x6000 );
for (uint i=0x6000; i < 0x8000; i += 0x100)
Map( i, &Datach::Peek_6000 );
}
void Datach::SubLoad(State::Loader& state,const dword baseChunk)
{
if (baseChunk == AsciiId<'B','D','A'>::V)
{
while (const dword chunk = state.Begin())
{
if (chunk == AsciiId<'B','R','C'>::V)
barcodeReader.LoadState( state );
state.End();
}
}
else
{
Lz93d50Ex::SubLoad( state, baseChunk );
}
}
void Datach::SubSave(State::Saver& state) const
{
Lz93d50Ex::SubSave( state );
state.Begin( AsciiId<'B','D','A'>::V );
barcodeReader.SaveState( state, AsciiId<'B','R','C'>::V );
state.End();
}
void Datach::Reader::Reset(bool initHook)
{
cycles = Cpu::CYCLE_MAX;
output = 0x00;
stream = data;
std::memset( data, END, MAX_DATA_LENGTH );
if (initHook)
cpu.AddHook( Hook(this,&Reader::Hook_Fetcher) );
}
bool Datach::Reader::IsTransferring() const
{
return *stream != END;
}
bool Datach::Reader::IsDigitsSupported(uint count) const
{
return count == MIN_DIGITS || count == MAX_DIGITS;
}
void Datach::Reader::LoadState(State::Loader& state)
{
Reset( false );
while (const dword chunk = state.Begin())
{
switch (chunk)
{
case AsciiId<'P','T','R'>::V:
stream = data + (state.Read8() & (MAX_DATA_LENGTH-1));
break;
case AsciiId<'D','A','T'>::V:
state.Uncompress( data );
data[MAX_DATA_LENGTH-1] = END;
break;
case AsciiId<'C','Y','C'>::V:
cycles = state.Read16();
break;
}
state.End();
}
if (Reader::IsTransferring())
{
output = (stream != data) ? stream[-1] : 0x00;
if (cycles > CC_INTERVAL)
cycles = CC_INTERVAL;
cycles = cpu.GetCycles() + cpu.GetClock() * cycles;
}
else
{
cycles = Cpu::CYCLE_MAX;
output = 0x00;
}
}
void Datach::Reader::SaveState(State::Saver& state,const dword baseChunk) const
{
if (Reader::IsTransferring())
{
NST_ASSERT( cycles != Cpu::CYCLE_MAX );
state.Begin( baseChunk );
state.Begin( AsciiId<'P','T','R'>::V ).Write8( stream - data ).End();
state.Begin( AsciiId<'D','A','T'>::V ).Compress( data ).End();
uint next;
if (cycles > cpu.GetCycles())
next = (cycles - cpu.GetCycles()) / cpu.GetClock();
else
next = 0;
state.Begin( AsciiId<'C','Y','C'>::V ).Write16( next ).End();
state.End();
}
}
bool Datach::Reader::Transfer(cstring const string,const uint length)
{
Reset( false );
if (!string || (length != MAX_DIGITS && length != MIN_DIGITS))
return false;
static const byte prefixParityType[10][6] =
{
{8,8,8,8,8,8}, {8,8,0,8,0,0},
{8,8,0,0,8,0}, {8,8,0,0,0,8},
{8,0,8,8,0,0}, {8,0,0,8,8,0},
{8,0,0,0,8,8}, {8,0,8,0,8,0},
{8,0,8,0,0,8}, {8,0,0,8,0,8}
};
static const byte dataLeftOdd[10][7] =
{
{8,8,8,0,0,8,0}, {8,8,0,0,8,8,0},
{8,8,0,8,8,0,0}, {8,0,0,0,0,8,0},
{8,0,8,8,8,0,0}, {8,0,0,8,8,8,0},
{8,0,8,0,0,0,0}, {8,0,0,0,8,0,0},
{8,0,0,8,0,0,0}, {8,8,8,0,8,0,0}
};
static const byte dataLeftEven[10][7] =
{
{8,0,8,8,0,0,0}, {8,0,0,8,8,0,0},
{8,8,0,0,8,0,0}, {8,0,8,8,8,8,0},
{8,8,0,0,0,8,0}, {8,0,0,0,8,8,0},
{8,8,8,8,0,8,0}, {8,8,0,8,8,8,0},
{8,8,8,0,8,8,0}, {8,8,0,8,0,0,0}
};
static const byte dataRight[10][7] =
{
{0,0,0,8,8,0,8}, {0,0,8,8,0,0,8},
{0,0,8,0,0,8,8}, {0,8,8,8,8,0,8},
{0,8,0,0,0,8,8}, {0,8,8,0,0,0,8},
{0,8,0,8,8,8,8}, {0,8,8,8,0,8,8},
{0,8,8,0,8,8,8}, {0,0,0,8,0,8,8}
};
byte code[16];
for (uint i=0; i < length; ++i)
{
if (string[i] >= '0' && string[i] <= '9')
code[i] = string[i] - '0';
else
return false;
}
byte* NST_RESTRICT output = data;
for (uint i=0; i < 1+32; ++i)
*output++ = 8;
*output++ = 0;
*output++ = 8;
*output++ = 0;
uint sum = 0;
if (length == MAX_DIGITS)
{
for (uint i=0; i < 6; ++i)
{
if (prefixParityType[code[0]][i])
{
for (uint j=0; j < 7; ++j)
*output++ = dataLeftOdd[code[i+1]][j];
}
else
{
for (uint j=0; j < 7; ++j)
*output++ = dataLeftEven[code[i+1]][j];
}
}
*output++ = 8;
*output++ = 0;
*output++ = 8;
*output++ = 0;
*output++ = 8;
for (uint i=7; i < 12; ++i)
{
for (uint j=0; j < 7; ++j)
*output++ = dataRight[code[i]][j];
}
for (uint i=0; i < 12; ++i)
sum += (i & 1) ? (code[i] * 3) : (code[i] * 1);
}
else
{
for (uint i=0; i < 4; ++i)
{
for (uint j=0; j < 7; ++j)
*output++ = dataLeftOdd[code[i]][j];
}
*output++ = 8;
*output++ = 0;
*output++ = 8;
*output++ = 0;
*output++ = 8;
for (uint i=4; i < 7; ++i)
{
for (uint j=0; j < 7; ++j)
*output++ = dataRight[code[i]][j];
}
for (uint i=0; i < 7; ++i)
sum += (i & 1) ? (code[i] * 1) : (code[i] * 3);
}
sum = (10 - (sum % 10)) % 10;
for (uint i=0; i < 7; ++i)
*output++ = dataRight[sum][i];
*output++ = 0;
*output++ = 8;
*output++ = 0;
for (uint i=0; i < 32; ++i)
*output++ = 8;
cycles = cpu.GetCycles() + cpu.GetClock() * CC_INTERVAL;
return true;
}
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("", on)
#endif
NES_HOOK(Datach::Reader,Fetcher)
{
while (cycles <= cpu.GetCycles())
{
output = *stream;
stream += (output != END);
if (output != END)
{
cycles += cpu.GetClock() * CC_INTERVAL;
}
else
{
output = 0x00;
cycles = Cpu::CYCLE_MAX;
break;
}
}
}
inline uint Datach::Reader::GetOutput() const
{
return output;
}
NES_PEEK_A(Datach,6000)
{
return barcodeReader.GetOutput() | p6000.Peek( address );
}
inline void Datach::Reader::Sync()
{
if (cycles != Cpu::CYCLE_MAX)
{
if (cycles >= cpu.GetFrameCycles())
cycles -= cpu.GetFrameCycles();
else
cycles = 0;
}
}
void Datach::Sync(Event event,Input::Controllers* controllers)
{
if (event == EVENT_END_FRAME)
barcodeReader.Sync();
Lz93d50Ex::Sync( event, controllers );
}
}
}
}
}
| [
"[email protected]"
] | [
[
[
1,
381
]
]
] |
bbbb0e3eb579b98f94c38606204fa17b7f12822c | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/UrbanExtreme/src/physics/playerentity.cc | fea6fd0049f9b14f88912ee11416e259e3cf2f5c | [] | no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,540 | cc | //------------------------------------------------------------------------------
// physics/playerentity.cc
// (C) 2007 Kim Hyoun Woo
//------------------------------------------------------------------------------
#include "physics/playerentity.h"
#include "physics/server.h"
#include "physics/rigidbody.h"
#include "physics/shape.h"
#include "physics/boxshape.h"
#include "physics/composite.h"
#include "physics/level.h"
#include "physics/physicsutil.h"
#include "physics/compositeloader.h"
namespace Physics
{
ImplementRtti(Physics::PlayerEntity, Physics::Entity);
ImplementFactory(Physics::PlayerEntity);
//------------------------------------------------------------------------------
/**
*/
PlayerEntity::PlayerEntity() :
radius(0.3f),
height(1.75f),
hover(0.2f),
nebCharacter(0)
{
}
//------------------------------------------------------------------------------
/**
*/
PlayerEntity::~PlayerEntity()
{
n_assert(this->baseBody == 0);
}
//------------------------------------------------------------------------------
/**
*/
void
PlayerEntity::OnActivate()
{
n_assert(this->baseBody == 0);
Server* physicsServer = Physics::Server::Instance();
this->active = true;
// create a composite with a spherical rigid body and an angular motor
this->defaultComposite = physicsServer->CreateComposite();
// create capsule for a shape which to be used for a player.
float capsuleLength = this->height - 2.0f * this->radius - this->hover;
matrix44 upRight;
upRight.rotate_x(n_deg2rad(90.0f));
upRight.translate(vector3(0.0f, capsuleLength * 0.5f, 0.0f));
Ptr<Shape> shape = (Physics::Shape*) physicsServer->CreateCapsuleShape(upRight,
MaterialTable::StringToMaterialType("Character"), this->radius, capsuleLength);
// create a base rigid body object
this->baseBody = physicsServer->CreateRigidBody();
this->baseBody->SetName("PlayerEntityBody");
this->baseBody->BeginShapes(1);
this->baseBody->AddShape(shape);
this->baseBody->EndShapes();
this->defaultComposite->BeginBodies(1);
this->defaultComposite->AddBody(this->baseBody);
this->defaultComposite->EndBodies();
this->SetComposite(this->defaultComposite);
this->defaultComposite->Attach(physicsServer->GetOdeWorldId(),
physicsServer->GetOdeDynamicSpaceId(), physicsServer->GetOdeStaticSpaceId());
this->active = true;
// NOTE: do NOT call parent class
}
//------------------------------------------------------------------------------
/**
*/
void
PlayerEntity::OnDeactivate()
{
n_assert(this->baseBody != 0);
Level* level = Physics::Server::Instance()->GetLevel();
n_assert(level);
Entity::OnDeactivate();
this->baseBody = 0;
this->defaultComposite = 0;
this->SetCharacter(0);
}
//------------------------------------------------------------------------------
/**
This function checks if the character is currently touching the ground
by doing a vertical ray check.
*/
bool
PlayerEntity::CheckGround(float& dist, float& depth)
{
Physics::Server* physicsServer = Physics::Server::Instance();
vector3 pos = this->GetTransform().pos_component();
vector3 from(pos.x, pos.y + this->radius * 2.0f, pos.z);
vector3 dir(0.0f, -this->radius * 4.0f, 0.0f);
FilterSet excludeSet = this->groundExcludeSet;
excludeSet.AddEntityId(this->GetUniqueId());
const ContactPoint* contact = Physics::Server::Instance()->GetClosestContactAlongRay(from, dir, excludeSet);
if (contact)
{
dist = vector3(contact->GetPosition() - from).len() - this->radius * 2.0f;
this->groundMaterial = contact->GetMaterial();
depth = contact->GetDepth();
return true;
}
else
{
dist = 2.0f * this->radius;
this->groundMaterial = InvalidMaterial;
return false;
}
}
//------------------------------------------------------------------------------
/**
*/
void
PlayerEntity::OnStepBefore()
{
Physics::Server* physicsServer = Physics::Server::Instance();
RigidBody* body = this->baseBody;
dBodyID odeBodyId = body->GetOdeBodyId();
float rTurn = 0;
//float fForce = 0;
//float lForce = 0;
float uForce = 0;
bool damp = true;
vector3 up(0, 1, 0);
vector3 lvel = body->GetLinearVelocity();//obj_->lVel();
vector3 avel = body->GetAngularVelocity();//obj_->aVel();
const matrix44 &bodyTM = body->GetTransform();
// bosy position.
vector3 pos = bodyTM.pos_component();//obj_->pos();
// bosy rotation.
vector3 actual_right, actual_up, actual_front;
actual_right = bodyTM.x_component();
actual_up = bodyTM.y_component();
actual_front = bodyTM.z_component();
//obj_->ori( &actual_right, &actual_up, &actual_front );
vector3 front( actual_front.x, 0, actual_front.z );
front.norm();//D3DXVec3Normalize( &front, &front );
float m = body->GetMass();
vector3 curVel = body->GetLinearVelocity();
float actualVel = curVel.len();
vector3 nVel = curVel;
if (actualVel > 1e-1)
{
nVel.norm();
}
else
{
actualVel = 0;
nVel = vector3(0.0f, 0.0f, 0.0f);
}
float const mass = m;
float const kneeForce = 30 * mass;
float const lBrakeForce = 10 * mass;
float const aBrakeForce = 3 * mass;
float const sideBrakeForce = 9 * mass;
float runForce = 7 * mass;
float const jumpForce = 500 * mass; // it's a very short impulse
float const turnTorque = 7 * mass;
float const maxVel = 4;
float const legLength = 0.9f;
float const kneeExtend = 0.31f; // how much to "push" to extend the knees
float const rightTorque = 15 * mass;
if( actualVel > maxVel ) {
runForce = (actualVel > maxVel+1) ? 0 : (actualVel - maxVel) * runForce;
}
if (touched)
{
//touched on the upper part
this->floorContact = true;
touched = false;
}
else
{
}
// check ground
float distGround, depth;
if (this->CheckGround(distGround, depth))
{
float heightSoon = depth + 0.5f * lvel.y;
float kneeScale = legLength - heightSoon + kneeExtend;
if( kneeScale < 0 )
{
kneeScale = 0;
}
else
if( kneeScale > 1 )
{
kneeScale = 1;
}
uForce += kneeForce * kneeScale;
this->floorContact = true;
}
if (this->jump)
{
this->upForce += jumpForce;//const;
this->timeToJump = 1.0f;
}
if (floorContact)
{
if(damp)
{
if (actualVel > 0)
{
float forceToStop = m * actualVel / 0.01f; // step size
if( forceToStop > lBrakeForce/*const*/ )
forceToStop = lBrakeForce;
// don't dampen Y as much as the others
dBodyAddForce(odeBodyId, -nVel.x * forceToStop, -nVel.y * forceToStop * 0.25f, -nVel.z * forceToStop);
}
else
{
dBodySetLinearVel(odeBodyId, 0, 0, 0);
}
}
else
{
dBodyAddRelForce(odeBodyId, -actual_right.dot(lvel) * sideBrakeForce * (1 - strafing), 0, 0 );
}
dBodyAddTorque(odeBodyId, -avel.x, -avel.y, -avel.z );
dBodyAddRelForce(odeBodyId, -this->leftwardForce, uForce, this->forwardForce );
dBodyAddRelTorque(odeBodyId, 0, rTurn, 0 );
}
// calculate rightening forces, even if not floor contacted
vector3 rt;
// point is relative, vel is global
dBodyGetRelPointVel(odeBodyId, 1, 0, 0, &rt.x );
rt *= 0.02f; // how far into the future to look
rt += actual_right;
float turnLeft = -up.dot(rt);//-D3DXVec3Dot( &up, &rt );
vector3 fw;
dBodyGetRelPointVel(odeBodyId, 0, 0, 1, &fw.x );
fw *= 0.02f;
fw += actual_front;
float turnForward = up.dot(fw);//D3DXVec3Dot( &up, &fw );
dBodyAddRelTorque(odeBodyId, turnForward * rightTorque, 0, turnLeft * rightTorque );
this->floorContact = false;
}
//------------------------------------------------------------------------------
/**
*/
bool
PlayerEntity::OnCollide(Shape* collidee)
{
bool validCollision = Entity::OnCollide(collidee);
validCollision &= !this->groundExcludeSet.CheckShape(collidee);
return validCollision;
}
//------------------------------------------------------------------------------
/**
*/
void
PlayerEntity::SetTransform(const matrix44& m)
{
matrix44 offsetMatrix(m);
offsetMatrix.M42 += this->radius + this->hover;
Entity::SetTransform(offsetMatrix);
this->lookatDirection = -m.z_component();
}
//------------------------------------------------------------------------------
/**
*/
matrix44
PlayerEntity::GetTransform() const
{
matrix44 tmp = Entity::GetTransform();
static vector3 upVector(0.0f, 1.0f, 0.0f);
matrix44 fixedTransform;
fixedTransform.lookatRh(this->lookatDirection, upVector);
fixedTransform.translate(tmp.pos_component());
fixedTransform.M42 -= this->radius + this->hover;
return fixedTransform;
}
//------------------------------------------------------------------------------
/**
*/
bool
PlayerEntity::HasTransformChanged() const
{
// compare current look direction and desired lookat direction
vector3 curLookAt = -Entity::GetTransform().z_component();
if (!this->lookatDirection.isequal(curLookAt, 0.01f))
{
return true;
}
else
{
return Entity::HasTransformChanged();
}
}
} // namespace Physics
| [
"ldw9981@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
339
]
]
] |
ae321270b07746db7c3fd000cfc28320b74bb79a | 830c7a4afeb2ac3f63ffbc18827b4b235c6e1588 | /md5class.cpp | 34b4ca8b3f45630ed2e1243c5c4a29fb73beeac5 | [] | no_license | tzafrir/Security-1 | 10ac997cc309b367b93a3b73d09db06bd993426d | 540cd659bae54e61d2225b2c54283ac67f1f7c58 | refs/heads/master | 2016-09-11T02:32:13.385475 | 2010-11-24T20:06:15 | 2010-11-24T20:06:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,916 | cpp | // md5class.cpp: implementation of the CMD5 class.
//See internet RFC 1321, "The MD5 Message-Digest Algorithm"
//
//Use this code as you see fit. It is provided "as is"
//without express or implied warranty of any kind.
//////////////////////////////////////////////////////////////////////
#include "md5class.h"
#include "md5.h" //declarations from RFC 1321
#include <string.h>
#include <stdio.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMD5::CMD5()
{
m_digestValid = false; //we don't have a plaintext string yet
m_digestString[32]=0; //the digest string is always 32 characters, so put a null in position 32
}
CMD5::~CMD5()
{
}
CMD5::CMD5(const char* plainText)
{
m_plainText = const_cast<char*>(plainText); //get a pointer to the plain text. If casting away the const-ness worries you,
//you could make a local copy of the plain text string.
m_digestString[32]=0;
m_digestValid = calcDigest();
}
//////////////////////////////////////////////////////////////////////
// Implementation
//////////////////////////////////////////////////////////////////////
void CMD5::setPlainText(const char* plainText)
{
//set plaintext with a mutator, it's ok to
//to call this multiple times. If casting away the const-ness of plainText
//worries you, you could either make a local copy of the plain
//text string instead of just pointing at the user's string, or
//modify the RFC 1321 code to take 'const' plaintext, see example below.
m_plainText = const_cast<char*>(plainText);
m_digestValid = calcDigest();
}
/* Use a function of this type with your favorite string class
if casting away the const-ness of the user's text buffer violates you
coding standards.
void CMD5::setPlainText(CString& strPlainText)
{
static CString plaintext(strPlainText);
m_plainText = strPlainText.GetBuffer();
m_digestValid = calcDigest();
}
*/
const char* CMD5::toString()
{ //access message digest (aka hash), return 0 if plaintext has not been set
if(m_digestValid)
{
return m_digestString;
} else return 0;
}
bool CMD5::calcDigest()
{
//See RFC 1321 for details on how MD5Init, MD5Update, and MD5Final
//calculate a digest for the plain text
MD5_CTX context;
MD5Init(&context);
//the alternative to these ugly casts is to go into the RFC code and change the declarations
MD5Update(&context, reinterpret_cast<unsigned char *>(m_plainText), ::strlen(m_plainText));
MD5Final(reinterpret_cast <unsigned char *>(m_digest),&context);
//make a string version of the numeric digest value
int p=0;
for (int i = 0; i<16; i++)
{
::sprintf(&m_digestString[p],"%02x", m_digest[i]);
p+=2;
}
return true;
}
| [
"[email protected]"
] | [
[
[
1,
97
]
]
] |
3e6a15ffa36fa0806e370efde9bbc32e11666866 | 55196303f36aa20da255031a8f115b6af83e7d11 | /private/external/gameswf/gameswf/gameswf_as_classes/as_date.h | c3ca24d280b847997dc80123b7daa9e33eb4454e | [] | no_license | Heartbroken/bikini | 3f5447647d39587ffe15a7ae5badab3300d2a2ff | fe74f51a3a5d281c671d303632ff38be84d23dd7 | refs/heads/master | 2021-01-10T19:48:40.851837 | 2010-05-25T19:58:52 | 2010-05-25T19:58:52 | 37,190,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | h | // as_date.h -- Vitaly Alexeev <[email protected]> 2007
// This source code has been donated to the Public Domain. Do
// whatever you want with it.
// The Date class lets you retrieve date and time values relative to universal time
// (Greenwich mean time, now called universal time or UTC)
// or relative to the operating system on which Flash Player is running
#ifndef GAMESWF_AS_DATE_H
#define GAMESWF_AS_DATE_H
#include "gameswf/gameswf_action.h" // for as_object
#include "base/tu_timer.h"
namespace gameswf
{
void as_global_date_ctor(const fn_call& fn);
struct as_date : public as_object
{
// Unique id of a gameswf resource
enum { m_class_id = AS_DATE };
virtual bool is(int class_id) const
{
if (m_class_id == class_id) return true;
else return as_object::is(class_id);
}
as_date(const fn_call& fn);
Uint64 get_time() const;
private:
Uint64 m_time;
};
} // end namespace gameswf
#endif // GAMESWF_AS_DATE_H
// Local Variables:
// mode: C++
// c-basic-offset: 8
// tab-width: 8
// indent-tabs-mode: t
// End:
| [
"viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587"
] | [
[
[
1,
51
]
]
] |
042572af762a1c3b713769f069443ee111f2fb43 | 698ea8ebae4fb57899293ed99775d3b486f6a026 | /craw/debug_registers.hpp | 68d1a41aba8cb84932099d24a0d865d2ad7250c7 | [] | no_license | binrapt/craw_module | 7d1557ef91297367d06097524c8593c1fd41944c | 70b615ebbc6e1c108c20093bd7a18eecfc230167 | refs/heads/master | 2020-07-08T09:05:12.816498 | 2009-07-11T02:32:26 | 2009-07-11T02:32:26 | 247,535 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 273 | hpp | #pragma once
#include <vector>
#include <windows.h>
void set_debug_registers(CONTEXT & thread_context, unsigned address);
void set_debug_registers(CONTEXT & thread_context, std::vector<unsigned> & addresses);
void print_debug_registers(CONTEXT & thread_context);
| [
"[email protected]"
] | [
[
[
1,
8
]
]
] |
4ab28fe0396b146d9b3a1cc55f824a143be417ef | 5659e71d1a8f7c3733ff3d4296fe9bcce8bdc8d7 | /modelfitting/common/opengl.cpp | 38d1843670256afbc7f91214cc8207e1a89bdd51 | [] | no_license | davidsansome/gait-modelfitting | 92733c4cd71751b33952820015504a19d4a76a7d | 699f79237768be91cc431c68601a626dd08259a7 | refs/heads/master | 2016-09-05T09:37:11.185040 | 2008-07-17T13:04:29 | 2008-07-17T13:04:29 | 4,369,004 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,278 | cpp | #include "opengl.h"
#ifndef _WIN32
void setupWinGLFunctions()
{
}
#else
PFNGLBINDBUFFERPROC pglBindBuffer = NULL;
PFNGLGENBUFFERSPROC pglGenBuffers = NULL;
PFNGLBUFFERDATAPROC pglBufferData = NULL;
PFNGLDELETEBUFFERSPROC pglDeleteBuffers = NULL;
PFNGLDRAWRANGEELEMENTSPROC pglDrawRangeElements = NULL;
PFNGLUSEPROGRAMPROC pglUseProgram = NULL;
PFNGLATTACHSHADERPROC pglAttachShader = NULL;
PFNGLGETSHADERINFOLOGPROC pglGetShaderInfoLog = NULL;
PFNGLGETSHADERIVPROC pglGetShaderiv = NULL;
PFNGLCOMPILESHADERPROC pglCompileShader = NULL;
PFNGLSHADERSOURCEPROC pglShaderSource = NULL;
PFNGLISSHADERPROC pglIsShader = NULL;
PFNGLLINKPROGRAMPROC pglLinkProgram = NULL;
PFNGLCREATEPROGRAMPROC pglCreateProgram = NULL;
PFNGLDELETESHADERPROC pglDeleteShader = NULL;
PFNGLISPROGRAMPROC pglIsProgram = NULL;
PFNGLACTIVETEXTUREPROC pglActiveTexture = NULL;
PFNGLUNIFORM1IPROC pglUniform1i = NULL;
PFNGLUNIFORM1FPROC pglUniform1f = NULL;
PFNGLUNIFORM2FPROC pglUniform2f = NULL;
PFNGLDELETEPROGRAMPROC pglDeleteProgram = NULL;
PFNGLCREATESHADERPROC pglCreateShader = NULL;
PFNGLGETUNIFORMLOCATIONPROC pglGetUniformLocation = NULL;
PFNGLMULTITEXCOORD2FPROC pglMultiTexCoord2f = NULL;
void setupWinGLFunctions()
{
static bool alreadySetup = false;
if (alreadySetup)
return;
alreadySetup = true;
pglBindBuffer = (PFNGLBINDBUFFERPROC) wglGetProcAddress("glBindBuffer");
pglGenBuffers = (PFNGLGENBUFFERSPROC) wglGetProcAddress("glGenBuffers");
pglBufferData = (PFNGLBUFFERDATAPROC) wglGetProcAddress("glBufferData");
pglDeleteBuffers = (PFNGLDELETEBUFFERSPROC) wglGetProcAddress("glDeleteBuffers");
pglDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC) wglGetProcAddress("glDrawRangeElements");
pglUseProgram = (PFNGLUSEPROGRAMPROC) wglGetProcAddress("glUseProgram");
pglAttachShader = (PFNGLATTACHSHADERPROC) wglGetProcAddress("glAttachShader");
pglGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC) wglGetProcAddress("glGetShaderInfoLog");
pglGetShaderiv = (PFNGLGETSHADERIVPROC) wglGetProcAddress("glGetShaderiv");
pglCompileShader = (PFNGLCOMPILESHADERPROC) wglGetProcAddress("glCompileShader");
pglShaderSource = (PFNGLSHADERSOURCEPROC) wglGetProcAddress("glShaderSource");
pglIsShader = (PFNGLISSHADERPROC) wglGetProcAddress("glIsShader");
pglLinkProgram = (PFNGLLINKPROGRAMPROC) wglGetProcAddress("glLinkProgram");
pglCreateProgram = (PFNGLCREATEPROGRAMPROC) wglGetProcAddress("glCreateProgram");
pglDeleteShader = (PFNGLDELETESHADERPROC) wglGetProcAddress("glDeleteShader");
pglIsProgram = (PFNGLISPROGRAMPROC) wglGetProcAddress("glIsProgram");
pglActiveTexture = (PFNGLACTIVETEXTUREPROC) wglGetProcAddress("glActiveTexture");
pglUniform1i = (PFNGLUNIFORM1IPROC) wglGetProcAddress("glUniform1i");
pglUniform1f = (PFNGLUNIFORM1FPROC) wglGetProcAddress("glUniform1f");
pglUniform2f = (PFNGLUNIFORM2FPROC) wglGetProcAddress("glUniform2f");
pglDeleteProgram = (PFNGLDELETEPROGRAMPROC) wglGetProcAddress("glDeleteProgram");
pglCreateShader = (PFNGLCREATESHADERPROC) wglGetProcAddress("glCreateShader");
pglGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) wglGetProcAddress("glGetUniformLocation");
pglMultiTexCoord2f = (PFNGLMULTITEXCOORD2FPROC) wglGetProcAddress("glMultiTexCoord2f");
}
#endif
| [
"[email protected]"
] | [
[
[
1,
67
]
]
] |
9656dadebce0e4f6d204c87c49caf759ae80c139 | 27bde5e083cf5a32f75de64421ba541b3a23dd29 | /source/AllArrows.cpp | 51a14018ffeaa6f8704b302e5885ba5d9115a7f9 | [] | no_license | jbsheblak/fatal-inflation | 229fc6111039aff4fd00bb1609964cf37e4303af | 5d6c0a99e8c4791336cf529ed8ce63911a297a23 | refs/heads/master | 2021-03-12T19:22:31.878561 | 2006-10-20T21:48:17 | 2006-10-20T21:48:17 | 32,184,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 887 | cpp | //---------------------------------------------------
// Name: Game : BaseArrow
// Desc: fills in properties, flies straight
// Author: John Sheblak
// Contact: [email protected]
//---------------------------------------------------
#include "AllArrows.h"
namespace Game
{
TimedArrow::TimedArrow( EntityDesc* desc ) : Arrow(desc)
{
mLifetime = -1.0f;
if( desc )
{
EntityDesc::iterator itr;
for( itr = desc->begin(); itr != desc->end(); ++itr )
{
switch( itr->mFlag )
{
case kArrowProp_Lifetime:
{
memcpy( &mLifetime, itr->mData, sizeof(F32) );
break;
}
}
}
}
UpdateBBox();
}
void TimedArrow::Update( F32 curTime )
{
Arrow::Update(curTime);
if( mLifetime != -1.0f )
{
if( curTime >= mStartTime + mLifetime )
Kill();
}
}
}; //end Game
| [
"jbsheblak@5660b91f-811d-0410-8070-91869aa11e15"
] | [
[
[
1,
48
]
]
] |
6b89f8115f110d9663c0b48c3ff4c8b968fa060c | 6253ab92ce2e85b4db9393aa630bde24655bd9b4 | /Common/network/icmp.cpp | b17beda35c380cf376759ee4371da1add3d705b2 | [] | no_license | Aand1/cornell-urban-challenge | 94fd4df18fd4b6cc6e12d30ed8eed280826d4aed | 779daae8703fe68e7c6256932883de32a309a119 | refs/heads/master | 2021-01-18T11:57:48.267384 | 2008-10-01T06:43:18 | 2008-10-01T06:43:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,463 | cpp | #include "icmp.h"
icmp::icmp() {
// initialize windows sockets
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) {
this->sock = INVALID_SOCKET;
throw std::exception("error initializing Winsock");
}
// Create the socket
sd = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, WSA_FLAG_OVERLAPPED);
if (sd == INVALID_SOCKET) {
throw std::exception("error creating socket");
}
// Initialize the destination host info block
memset(&dest, 0, sizeof(dest));
// Turn first passed parameter into an IP address to ping
unsigned int addr = inet_addr(host);
if (addr != INADDR_NONE) {
// It was a dotted quad number, so save result
dest.sin_addr.s_addr = addr;
dest.sin_family = AF_INET;
}
else {
// Not in dotted quad form, so try and look it up
hostent* hp = gethostbyname(host);
if (hp != 0) {
// Found an address for that host, so save it
memcpy(&(dest.sin_addr), hp->h_addr, hp->h_length);
dest.sin_family = hp->h_addrtype;
}
else {
// Not a recognized hostname either!
cerr << "Failed to resolve " << host << endl;
return -1;
}
}
return 0;
}
icmp::~icmp() {
}
bool icmp::send_ping(int addr, int ttl, int size) {
if (setsockopt(sd, IPPROTO_IP, IP_TTL, (const char*)&ttl, sizeof(ttl)) == SOCKET_ERROR) {
return false;
}
sockaddr_in dest;
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = addr;
dest.sin_port = 0;
size_t packet_size = sizeof(icmp_header) + size;
char* buf = new char[packet_size];
icmp_header* icmp_msg = (icmp_header*)buf;
icmp_msg->type = ICMP_ECHO_REQUEST;
icmp_msg->code = 0;
icmp_msg->checksum = 0;
icmp_msg->id = GetProcessId();
icmp_msg->seq = ++seq_no;
icmp_msg->timestamp = GetTickCount();
char* data = buf + sizeof(icmp_header);
memset(data, 0xDA, size);
icmp_msg->checksum = ip_checksum((unsigned short*)buf, packet_size);
if (sendto(sock, buf, packet_size, 0, (sockaddr*)&dest, sizeof(dest)) == SOCKET_ERROR) {
return false;
}
return true;
}
bool icmp::send_ping(const char* addr, int ttl, int size) {
return send_ping(inet_addr(), ttl, size);
}
timespan icmp::get_ping_reply(int addr, timespan timeout) {
}
timespan icmp::get_ping_reply(const char* addr, timespan timeout) {
}
unsigned short icmp::ip_checksum(unsigned short* buf, int size) {
} | [
"anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5"
] | [
[
[
1,
93
]
]
] |
1e00844099391abbac048d0bce4a11203bf28f49 | d9f1cc8e697ae4d1c74261ae6377063edd1c53f8 | /src/orders/FireOrder.h | 144fac72d4233cb8ee1b8548fa8887c4e96869e5 | [] | no_license | commel/opencombat2005 | 344b3c00aaa7d1ec4af817e5ef9b5b036f2e4022 | d72fc2b0be12367af34d13c47064f31d55b7a8e0 | refs/heads/master | 2023-05-19T05:18:54.728752 | 2005-12-01T05:11:44 | 2005-12-01T05:11:44 | 375,630,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 307 | h | #pragma once
#include <orders\order.h>
#include <objects\Target.h>
class Object;
class FireOrder :
public Order
{
public:
FireOrder(Object *target, Target::Type targetType);
FireOrder(int x, int y);
virtual ~FireOrder(void);
Object *Target;
Target::Type TargetType;
int X, Y;
};
| [
"opencombat"
] | [
[
[
1,
18
]
]
] |
b00244d4aea128f5da09c5b791f14b03a8e2a4ac | cf58ec40b7ea828aba01331ee3ab4c7f2195b6ca | /Nestopia/core/board/NstBoardBtlMarioBaby.hpp | c5ee2c641ba7d90418f4d85ca74ae60e3d5a6d55 | [] | no_license | nicoya/OpenEmu | e2fd86254d45d7aa3d7ef6a757192e2f7df0da1e | dd5091414baaaddbb10b9d50000b43ee336ab52b | refs/heads/master | 2021-01-16T19:51:53.556272 | 2011-08-06T18:52:40 | 2011-08-06T18:52:40 | 2,131,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,879 | hpp | ////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Nestopia 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 Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#ifndef NST_BOARD_BTL_MARIOBABY_H
#define NST_BOARD_BTL_MARIOBABY_H
#ifdef NST_PRAGMA_ONCE
#pragma once
#endif
namespace Nes
{
namespace Core
{
namespace Boards
{
namespace Btl
{
class MarioBaby : public Board
{
public:
explicit MarioBaby(const Context&);
private:
void SubReset(bool);
void SubSave(State::Saver&) const;
void SubLoad(State::Loader&,dword);
void Sync(Event,Input::Controllers*);
NES_DECL_PEEK( 6000 );
NES_DECL_POKE( E000 );
NES_DECL_POKE( E001 );
NES_DECL_POKE( E002 );
struct Irq
{
void Reset(bool);
bool Clock();
uint count;
Cpu& cpu;
explicit Irq(Cpu& c)
: cpu(c) {}
};
ClockUnits::M2<Irq> irq;
};
}
}
}
}
#endif
| [
"[email protected]"
] | [
[
[
1,
77
]
]
] |
cb8c33dce005c20c086b8238589e5aaefe4b45a7 | 23017336d25e6ec49c4a51f11c1b3a3aa10acf22 | /csc3750/prog8/AffineTransforms.h | 273058ce2dc1c7b32eb7e64c65a8f4226fd171a2 | [] | no_license | tjshaffer21/School | 5e7681c96e0c10966fc7362931412c4244507911 | 4aa5fc3a8bbbbb8d46d045244e8a7f84e71c768f | refs/heads/master | 2020-05-27T19:05:06.422314 | 2011-05-17T19:55:40 | 2011-05-17T19:55:40 | 1,681,224 | 1 | 1 | null | 2017-07-29T13:35:54 | 2011-04-29T15:36:55 | C++ | UTF-8 | C++ | false | false | 827 | h | #if !defined (AFFINETRANSFORMS_H)
#define AFFINETRANSFORMS_H
#include "Matrix.h"
#include "Vertex.h"
#include <math.h>
#define RADIANS 0.0174532925
class AffineTransforms
{
private:
public:
static Matrix* scale(double x, double y, double z);
static Matrix* translate( double ax, double ay, double az);
static Matrix* rotateX( double degrees );
static Matrix* rotateY( double degrees );
static Matrix* rotateZ( double degrees );
static Matrix* windowingTransform( double width, double height );
static Matrix* aspectRatio( int width, int height, double fov );
static Matrix* perspectiveNorm( double fovx, double ratio,
double z_max, double z_min );
static Matrix* buildCamera( Vertex* eye, Vertex* at, Vector* up );
};
#endif
| [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
d2b960c0daeec9c982d86b25f63e133b8387bcde | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/GUICheckBox.h | 2f5604377ca641fbeae64b887fc3acb621ab0407 | [] | 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,445 | h | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: GUICheckBox.h
Version: 0.03
---------------------------------------------------------------------------
*/
#pragma once
#ifndef __INC_GUICHECKBOX_H_
#define __INC_GUICHECKBOX_H_
#include "GUIControl.h"
#include "Prerequisities.h"
namespace nGENE
{
/** Check box control.
*/
class nGENEDLL GUICheckBox: public GUIControl
{
private:
bool m_bValue; ///< Value of the check box
public:
ON_PAINT_DELEGATE onChange;
public:
GUICheckBox();
~GUICheckBox();
void render(ScreenOverlay* _overlay, Vector2& _position);
void setValue(bool _value);
bool getValue() const;
void mouseClick(uint _x, uint _y);
};
inline void GUICheckBox::setValue(bool _value)
{
m_bValue = _value;
}
//----------------------------------------------------------------------
inline bool GUICheckBox::getValue() const
{
return m_bValue;
}
//----------------------------------------------------------------------
inline void GUICheckBox::mouseClick(uint _x, uint _y)
{
GUIControl::mouseClick(_x, _y);
m_bValue = (m_bValue ? false : true);
if(onChange)
onChange();
}
//----------------------------------------------------------------------
}
#endif | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
71
]
]
] |
b46a9a33d20fca0b1be227dc32832401dc8d0625 | 1caba14ec096b36815b587f719dda8c963d60134 | /branches/smxgroup/smx/libsmx/dbpset.cpp | dce391b0fbc3d1fc1ccf324ff3e450fcf8d896ce | [] | no_license | BackupTheBerlios/smx-svn | 0502dff1e494cffeb1c4a79ae8eaa5db647e5056 | 7955bd611e88b76851987338b12e47a97a327eaf | refs/heads/master | 2021-01-10T19:54:39.450497 | 2009-03-01T12:24:56 | 2009-03-01T12:24:56 | 40,749,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,968 | cpp | #define MAP_THRESH_N 5
#define MAP_THRESH_D 6
#include <memory.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <iostream>
#ifdef WIN32
#include <process.h>
#define STDCALL _stdcall
#endif
#include "dbpset.h"
#include "crit.h"
#include "util.h"
static CMutex gEnvLock("smx-dbpset.cpp-gEnvLock");
#ifndef HAVE_LIBTDB
bool gEnvOpen = false;
#endif
#ifndef HAVE_LIBTDB
class DestroyableDBEnv {
HANDLE myTH;
DbEnv *myEnv;
bool myDetector;
u_int32_t myFlags;
public:
CStr Dir;
DbEnv *Env() {
if (!myEnv) {
myEnv = new DbEnv(myFlags);
myEnv->set_error_stream(&std::cerr);
if (myDetector) {
#ifdef WIN32
unsigned tid;
myTH = (HANDLE) _beginthreadex(0, 0, LockDetectLoop, this, CREATE_SUSPENDED, &tid);
ResumeThread(myTH);
#endif
}
}
return myEnv;
}
DestroyableDBEnv(u_int32_t flags, bool detector = false) {
myTH = (HANDLE) 0;
myEnv = NULL;
myDetector = detector;
myFlags = flags;
}
~DestroyableDBEnv() {
try {
#ifdef WIN32
if (myTH != 0)
TerminateThread(myTH, 0);
#endif
if (myEnv) {
if (gEnvOpen) {
myEnv->close(0);
gEnvOpen = false;
}
/* win32 debug mode gets exceptions here. probably should find out why */
#if !(defined(WIN32) && defined(_DEBUG))
try {
delete myEnv;
} catch (...) {
smx_log_pf(SMXLOGLEVEL_WARNING, 0, "DbEnvDelete", "Unhandled error");
}
#endif
myEnv = NULL;
}
} catch (DbException x) {
if (x.get_errno() != 22 && x.get_errno() != 16) {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbEnvClose", x.what());
}
} catch (...) {
}
try {
DbEnv tmp(myFlags);
tmp.remove(Dir, 0);
} catch (DbException x) {
if (x.get_errno() != 2) {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbEnvRemove", x.what());
}
} catch (...) {
}
}
static unsigned STDCALL LockDetectLoop(void *parm) {
#ifdef WIN32
((DestroyableDBEnv *)parm)->LockDetectLoop();
#endif
return 0;
}
void LockDetectLoop() {
while (0 && this) {
if (gEnvOpen) {
Sleep(500);
int abr = 0;
try {
if (myEnv)
myEnv->lock_detect(0, DB_LOCK_DEFAULT, &abr);
} catch (...) {
}
if (abr > 0) {
smx_log_pf(SMXLOGLEVEL_WARNING, abr, "Locks aborted");
}
}
}
}
};
static DestroyableDBEnv gEnv(0, true);
extern "C" {
int bt_ci_compare(DB *pdb, const DBT *a, const DBT *b) {
if (a->size == b->size) {
return memicmp(a->data, b->data, a->size);
} else {
return stricmp((const char *)a->data, (const char *)b->data);
}
}
};
bool CDBHash::Repair()
{
smx_log_pf(SMXLOGLEVEL_WARNING, 0,"DBRepair");
bool ok = false;
CMutexLock lock(gEnvLock);
try {
smx_log_pf(SMXLOGLEVEL_WARNING, 0, "DBRepairClose", m_path);
Close();
Sleep(200);
} catch (...) {
smx_log_pf(SMXLOGLEVEL_WARNING, 0, "DBRepairClose", "Unhandled Exception", m_path);
}
ok = Open();
lock.Leave();
return ok;
}
#endif // #ifndef HAVE_LIBTDB
bool CDBHash::SetPath(const char *path)
{
if (path && *path) {
if (strlen(path) >= MAX_PATH)
return false ;
strncpy(m_path, path, MAX_PATH);
m_path[MAX_PATH-1] = '\0';
m_triedthispath = 0;
}
return Close();
}
bool CDBHash::Open()
{
if (m_db) return true;
if (!*m_path) return false;
smx_log_pf(SMXLOGLEVEL_DEBUG, 0, "DbOpenStart", m_path);
if (++m_triedthispath > 5) {
smx_log_pf(SMXLOGLEVEL_WARNING, 0, "Giving up on this db", m_path);
return false;
}
#ifdef HAVE_LIBTDB
TDB_CONTEXT *t;
t = tdb_open(m_path, 0, 0, O_CREAT|O_RDWR, 0666);
if (!t) {
smx_log_pf(SMXLOGLEVEL_WARNING, errno, "TDB Open Failed", m_path, strerror(errno));
}
#else
if (m_path) {
if (!gEnvOpen) {
CMutexLock lock(gEnvLock);
CStr env_dir = getenv("SMXHOME");
if (env_dir.IsEmpty()) {
#ifdef WIN32
env_dir = getenv("TEMP");
if (env_dir.IsEmpty()) {
env_dir = getenv("HOMEDRIVE");
if (env_dir.IsEmpty())
env_dir = ".";
else
env_dir += getenv("HOMEPATH");
}
env_dir.RTrim('/'); env_dir.RTrim('\\');
env_dir = env_dir + "\\.smx";
CreateDirectory(env_dir,NULL);
char c; for (c = '1'; c < '9'; ++c)
remove(((env_dir + "\\__db.00") + c).c_str());
#else
env_dir = getenv("HOME");
if (env_dir.IsEmpty())
env_dir = "/tmp";
env_dir = env_dir + "/.smx";
mkdir(env_dir,0775);
#endif
}
smx_log_pf(SMXLOGLEVEL_DEBUG, 0, "EnvOpen", env_dir);
int i;
for (i = 0; !gEnvOpen && i < 3; ++i) {
// try join
try {
if (!gEnv.Env()->open(env_dir, DB_JOINENV,0)) {
gEnvOpen = true;
gEnv.Dir = env_dir;
}
} catch (DbException x) {
if (x.get_errno() != 2)
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbEnvJoin", x.what());
} catch (...) {
smx_log_pf(SMXLOGLEVEL_ERROR, 0, "DbEnvJoin", "Unhandled exception", env_dir);
}
if (!gEnvOpen) {
try {
if (!gEnv.Env()->open(env_dir, DB_CREATE | DB_THREAD | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_TXN | DB_INIT_MPOOL, 0666)) {
gEnvOpen = true;
gEnv.Dir = env_dir;
}
} catch (DbException x) {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbEnvOpen", x.what());
if (x.get_errno() == DB_RUNRECOVERY) {
try {
DestroyableDBEnv tEnv(0);
tEnv.Env()->open(env_dir, DB_CREATE | DB_THREAD | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_TXN | DB_INIT_MPOOL | DB_RECOVER_FATAL, 0666);
tEnv.Env()->lock_detect(0, DB_LOCK_DEFAULT, NULL);
tEnv.Env()->close(0);
} catch (...) {
}
} else {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "EnvOpen", x.what(), env_dir);
gEnvOpen = false;
}
Sleep(100);
} catch (...) {
smx_log_pf(SMXLOGLEVEL_ERROR, 0, "DbEnvOpen", "Unhandled exception", env_dir);
Sleep(100);
}
}
}
}
}
m_oktxn = (gEnvOpen && m_path);
smx_log_pf(SMXLOGLEVEL_DEBUG, m_oktxn, "DBOKTxn", m_path);
Db *t = new Db(m_oktxn ? gEnv.Env() : NULL, 0);
try {
t->set_bt_compare(bt_ci_compare);
} catch (DbException x) {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbSetCompare", x.what());
}
#ifndef DB_DIRTY_READ
#define DB_DIRTY_READ 0
#endif
try {
#if DB_VERSION_MAJOR == 3 || (DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR == 0)
t->open((m_path && *m_path) ? m_path : NULL, NULL, DB_BTREE, DB_CREATE, 0);
#else
t->open(NULL, (m_path && *m_path) ? m_path : NULL, NULL, DB_BTREE, DB_CREATE, 0);
#endif
} catch (DbException x) {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbOpen", x.what(), m_path);
m_oktxn = false;
return false;
delete t;
} catch (...) {
smx_log_pf(SMXLOGLEVEL_ERROR, 0, "DbOpen", "unknown exception", m_path);
m_oktxn = false;
return false;
delete t;
}
smx_log_pf(SMXLOGLEVEL_DEBUG, m_oktxn, "DBDoneOpen",m_path);
#endif // HAVE_LIBTDB
if (t) {
m_db = t;
return true;
} else {
return false;
}
}
CStr CDBHash::Get(const char *path, HTRANS txn) {
if (!Open()) return (const char *) NULL;
const char *b = path ? path : "";
const char *p = b;
while (*p == '/' || isspace(*p))
++p;
b = p;
p = b + strlen(b);
if ((p-b) <= 0) return "";
#ifdef HAVE_LIBTDB
CStr str;
TDB_DATA key;
TDB_DATA data;
key.dptr=(char *)b;
key.dsize=p-b;
int retry = 0;
do {
data=tdb_fetch(m_db, key);
if (data.dptr) {
str.Grow(data.dsize);
memcpy(str.GetBuffer(),data.dptr,data.dsize);
free(data.dptr);
return str;
} else {
if (tdb_error(m_db) != TDB_ERR_NOEXIST)
smx_log_pf(SMXLOGLEVEL_WARNING, (int) m_db, "TDB Get", path, tdb_errorstr(m_db));
if (tdb_error(m_db) == TDB_ERR_CORRUPT) {
CMutexLock lock(gEnvLock);
rename(m_path, CStr(m_path) + ".bak");
//Close();
if (Open()) {++retry;}
}
}
} while (retry && (retry < 4));
#else
CStr str(16);
Dbt key((void *)b,p-b);
key.set_flags(DB_DBT_USERMEM);
Dbt data;
data.set_data(str.GetBuffer());
data.set_ulen(str.Length());
data.set_flags(DB_DBT_USERMEM);
int ret;
try {
ret = m_db->get((DbTxn*)txn, &key, &data, 0);
} catch (DbException x) {
DBTYPE t = (DBTYPE) 0;
try{m_db->get_type(&t);}catch(...){};
if (x.get_errno() != ENOMEM) {
smx_log_pf(SMXLOGLEVEL_WARNING, t, "DbGet", x.what(), b);
ret = -1;
} else {
ret = 0;
}
if (x.get_errno() == DB_RUNRECOVERY && Repair())
try {
ret = m_db->get((DbTxn*)txn, &key, &data, 0);
} catch (DbException x) {
if (x.get_errno() == DB_RUNRECOVERY)
exit(0);
if (x.get_errno() != ENOMEM)
throw x;
}
else if (x.get_errno() != ENOMEM)
throw x;
} catch (...) {
ret = -1;
smx_log_pf(SMXLOGLEVEL_WARNING, 0, "DbGet", "Unhandled exception", b);
}
if (ret == 0) {
if (data.get_size() > (unsigned int) str.Length()) {
str.Grow(data.get_size());
data.set_data(str.GetBuffer());
data.set_ulen(str.Length());
if ((ret = m_db->get(NULL, &key, &data, 0)) == 0) {
return str;
}
} else {
str.Grow(data.get_size());
return str;
}
}
#endif
return (const char *) NULL;
}
HTRANS CDBHash::BeginTrans() {
if (!Open()) return NULL;
#ifndef HAVE_LIBTDB
DbTxn * txn;
try {
if (m_oktxn && gEnvOpen && gEnv.Env()->txn_begin(NULL, &txn, DB_TXN_NOSYNC) == 0) {
return (HTRANS) txn;
}
} catch (DbException x) {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbBeginTrans", x.what());
} catch (...) {
}
#endif
return NULL;
}
bool CDBHash::Commit(HTRANS txn) {
if (!Open()) return false;
#ifndef HAVE_LIBTDB
if (txn) {
try {
int ret = ((DbTxn *)txn)->commit(DB_TXN_NOSYNC);
return 0 == ret;
} catch (DbException x) {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbCommit", x.what());
} catch (...) {
}
}
#endif
return false;
}
bool CDBHash::Rollback(HTRANS txn) {
if (!Open()) return false;
#ifndef HAVE_LIBTDB
if (txn) {
int ret = ((DbTxn *)txn)->abort();
return 0 == ret;
}
#endif
return false;
}
bool CDBHash::Exists(const char *path) {
if (!Open()) return false;
if (!path) return false;
const char *b = path ? path : "";
const char *p = b;
while (*p == '/' || isspace(*p))
++p;
b = p;
p = b + strlen(b);
#ifdef HAVE_LIBTDB
TDB_DATA key;
key.dptr=(char *)b;
key.dsize=p-b;
return tdb_exists(m_db, key);
#else
Dbt key((void *)b,p-b);
key.set_flags(DB_DBT_USERMEM);
Dbt data;
CStr str(16);
data.set_data(str.GetBuffer());
data.set_ulen(str.Length());
data.set_flags(DB_DBT_USERMEM);
int ret=-1;
try {
ret = m_db->get(NULL, &key, &data, 0);
} catch (DbException x) {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbExists", x.what());
if (x.get_errno() == DB_RUNRECOVERY && Repair())
try {
ret = m_db->get(NULL, &key, &data, 0);
} catch (DbException x) {
if (x.get_errno() == DB_RUNRECOVERY)
exit(0);
if (x.get_errno() != ENOMEM)
throw x;
}
else if (x.get_errno() != ENOMEM)
throw x;
}
return (ret == 0);
#endif
}
int CDBHash::Enum(void *obj, const char *path, int mode, bool (*EnumCallback)(void *obj, char *key, int klen, char *val, int vlen))
{
if (!Open()) return false;
#ifndef HAVE_LIBTDB
int n, ret, flag;
char *b = (char *) (path ? path : ""),
*p = b,
*k;
while (*p == '/' || isspace(*p))
++p;
b = p;
p = b + strlen(b);
Dbc *dbc;
m_db->cursor(NULL, &dbc, 0);
try {
CStr str(16);
CStr kstr(b, p-b + 16);
CStr prev;
Dbt data;
data.set_data(str.GetBuffer());
data.set_ulen(str.Length());
data.set_flags(DB_DBT_USERMEM);
Dbt key;
key.set_data(kstr.GetBuffer());
key.set_ulen(kstr.Length());
key.set_size(p-b);
key.set_flags(DB_DBT_USERMEM);
if (p-b>0) {
flag = DB_SET_RANGE;
} else {
flag = DB_FIRST;
}
try {
ret = dbc->get(&key, &data, flag);
} catch (DbException x) {
if (x.get_errno() != ENOMEM)
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbEnum", x.what());
if (x.get_errno() == DB_RUNRECOVERY && Repair()) {
try {
ret = m_db->get(NULL, &key, &data, 0);
} catch (DbException x) {
if (x.get_errno() == DB_RUNRECOVERY)
exit(0);
if (x.get_errno() != ENOMEM)
throw x;
}
} else if (x.get_errno() != ENOMEM)
throw x;
if ((unsigned int) data.get_size() > (unsigned int) str.Length()) {
str.Grow(data.get_size());
data.set_data(str.GetBuffer());
data.set_ulen(str.Length());
}
if ((unsigned int) key.get_size() > (unsigned int) kstr.Length()) {
kstr.Grow(key.get_size());
key.set_data(kstr.GetBuffer());
key.set_ulen(kstr.Length());
}
try {
ret = dbc->get(&key, &data, flag);
} catch (DbException x) {
if ((unsigned int) data.get_size() > (unsigned int) str.Length()) {
str.Grow(data.get_size());
data.set_data(str.GetBuffer());
data.set_ulen(str.Length());
}
if ((unsigned int) key.get_size() > (unsigned int) kstr.Length()) {
kstr.Grow(key.get_size());
key.set_data(kstr.GetBuffer());
key.set_ulen(kstr.Length());
}
}
ret = dbc->get(&key, &data, flag);
}
const char *ke;
n = 0;
while (ret == 0) {
++n;
k = (char *) key.get_data();
ke = k + key.get_size();
p = b;
while (k < ke && *p) {
if (*k != *p) {
goto enum_done;
}
++k;
++p;
}
if (*p) {
dbc->close();
goto enum_done;
}
if (mode == HENUM_VALUES) {
++k;
while (k < ke) {
if (*k == '/') {
goto next_key;
}
++k;
}
} else if (mode == HENUM_KEYS) {
if (k >= ke || *k != '/') {
goto next_key;
}
bool ok = false;
++k;
while (k < ke) {
if (*k == '/') {
ok = true;
break;
}
++k;
}
if (!ok)
goto next_key;
*k = '\0';
key.set_size((k - (char *) key.get_data()) - (p-b) - 1);
key.set_data((char *) key.get_data() + (p-b) + 1);
if (prev.GetBuffer()) {
if (!strnicmp(prev, (char*)key.get_data(), prev.Length())) {
goto next_key;
}
}
prev.Grow(key.get_size());
memcpy(prev.GetBuffer(), key.get_data(), key.get_size());
data.set_size(0);
}
((char *) data.get_data())[data.get_size()] = '\0';
((char *) key.get_data())[key.get_size()] = '\0';
if (!EnumCallback(obj, (char *)key.get_data(), key.get_size(), (char *)data.get_data(), data.get_size())) {
dbc->close();
goto enum_done;
}
next_key:
try {
ret = dbc->get(&key, &data, DB_NEXT);
} catch (DbException x) {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbEnum", x.what());
if (x.get_errno() == DB_RUNRECOVERY && Repair()) {
try {
ret = m_db->get(NULL, &key, &data, 0);
} catch (DbException x) {
if (x.get_errno() == DB_RUNRECOVERY)
exit(0);
if (x.get_errno() != ENOMEM)
throw x;
}
} else if (x.get_errno() != ENOMEM)
throw x;
if ((unsigned int) data.get_size() > (unsigned int)str.Length()) {
str.Grow(data.get_size());
data.set_data(str.GetBuffer());
data.set_ulen(str.Length());
}
if ((unsigned int)key.get_size() > (unsigned int)kstr.Length()) {
kstr.Grow(key.get_size());
key.set_data(kstr.GetBuffer());
key.set_ulen(kstr.Length());
}
ret = dbc->get(&key, &data, DB_NEXT);
}
}
} catch (...) {
smx_log_pf(SMXLOGLEVEL_WARNING, -1, "DbEnum", "Unhandled exception");
}
enum_done:
if (dbc)
dbc->close();
return n;
#else
return 0;
#endif
}
bool CDBHash::Del(const char *path, HTRANS txn) {
if (!Open()) return false;
if (!path) return false;
const char *b = (path ? path : "");
const char *p = b;
while (*p == '/' || isspace(*p))
++p;
b = p;
p = b + strlen(b);
#ifdef HAVE_LIBTDB
CStr str;
TDB_DATA key;
key.dptr=(char *)b;
key.dsize=p-b;
return tdb_delete(m_db, key) == 0;
#else
Dbt key((void *)b,p-b);
key.set_flags(DB_DBT_USERMEM);
Dbt data;
data.set_flags(DB_DBT_USERMEM);
try {
if (m_db->del((DbTxn*)txn, &key, 0) == 0) {
return true;
} else {
return false;
}
} catch (...) {
return false;
}
#endif
}
bool CDBHash::Set(const char *path, const char *val, int vlen, HTRANS txn) {
if (!Open()) return false;
if (!path) return false;
const char *b = path ? path : "";
const char *p = b;
while (*p == '/' || isspace(*p))
++p;
b = p;
p = b + strlen(b);
#ifdef HAVE_LIBTDB
int retry = 0;
do {
CStr str;
TDB_DATA key;
TDB_DATA data;
key.dptr=(char *)b;
key.dsize=p-b;
data.dptr=(char *)val;
data.dsize=vlen;
if (tdb_store(m_db, key, data, TDB_REPLACE) == 0) {
return true;
} else {
smx_log_pf(SMXLOGLEVEL_WARNING, (int) m_db, "TDB Set", path, tdb_errorstr(m_db));
if (tdb_error(m_db) == TDB_ERR_CORRUPT) {
CMutexLock lock(gEnvLock);
rename(m_path, CStr(m_path) + ".bak");
//Close();
if (Open()) {++retry;}
}
}
} while (retry && (retry < 4));
return false;
#else
Dbt key((void *)b,p-b);
key.set_flags(DB_DBT_USERMEM);
Dbt data((void *)val, vlen);
data.set_flags(DB_DBT_USERMEM);
try {
if ((m_db->put((DbTxn*)txn, &key, &data, 0)) == 0) {
return true;
} else {
// m_db->err(ret, "%s", path);
return false;
}
} catch (...) {
return false;
}
#endif
}
bool CDBHash::Close()
{
if (!m_db) return true;
smx_log_pf(SMXLOGLEVEL_DEBUG, 0, "DBClose", m_path);
#ifdef HAVE_LIBTDB
TDB_CONTEXT *t = m_db;
m_db = NULL;
bool ret;
ret = tdb_close(t);
delete t;
#else
Db *t = m_db;
m_db = NULL;
m_triedthispath=0;
bool ret = false;
try {
ret = (t->close(0) == 0);
} catch (DbException x) {
smx_log_pf(SMXLOGLEVEL_WARNING, x.get_errno(), "DbClose", x.what());
} catch (...) {
smx_log_pf(SMXLOGLEVEL_WARNING, -1, "DbClose","Unhandled Exception");
}
/* win32 debug mode gets exceptions here. probably should find out why */
#if !(defined(WIN32) && defined(_DEBUG))
try {
delete t;
} catch (...) {
smx_log_pf(SMXLOGLEVEL_WARNING, 0, "DbDelete", "Unhandled error");
}
#endif
#endif
return ret;
}
| [
"simul@407f561b-fe63-0410-8234-8332a1beff53"
] | [
[
[
1,
877
]
]
] |
4d974850ca93485600b61ea902c7d7131a6849df | 44e10950b3bf454080553a5da36bf263e6a62f8f | /src/GeneticAlg/GAManager.cpp | e62c80c58bb3288cbfda197bd7cafd2a141b3a46 | [] | no_license | ptrefall/ste6246tradingagent | a515d88683bf5f55f862c0b3e539ad6144a260bb | 89c8e5667aec4c74aef3ffe47f19eb4a1b17b318 | refs/heads/master | 2020-05-18T03:50:47.216489 | 2011-12-20T19:02:32 | 2011-12-20T19:02:32 | 32,448,454 | 1 | 0 | null | null | null | null | IBM852 | C++ | false | false | 9,959 | cpp | #include "GAManager.h"
#include "ProsumerGeneticAlg.h"
#include "SupplierGeneticAlg.h"
GAManager::GAManager(irr::scene::ISceneManager *smgr, EntityManager &entityMgr, Totem::ComponentFactory &componentFactory)
: smgr(smgr), entityMgr(entityMgr), componentFactory(componentFactory), prosumerGA(0x0), SupplierGA(0x0)
{
prosumerGA = new ProsumerGeneticAlg(*this,
100, //Population Size
0.0, //Fitness threshold
0.05, //Chance for crossover
1, //Max children from crossover
0.05, //Chance for mutation
0.1, //Start saldo
1.01, //ěk
1.0, //Ep
24000.0, //Ef
0.1, //Flex
0); //Policy
SupplierGA = new SupplierGeneticAlg(*this,
10, //Population Size
0.0, //Fitness threshold
0.05, //Chance for crossover
1, //Max children from crossover
0.15, //Chance for mutation
0.1, //Start saldo
0.12, //Price Offer
8.0, //Supply capacity
0.04, //Participation cost
0.4, //Hybrid Spot Percentage of Spot Price
0.75); //Hybrid Fixed Percentage of Fixed Price
}
GAManager::~GAManager()
{
if(prosumerGA) delete prosumerGA;
if(SupplierGA) delete SupplierGA;
}
void GAManager::initialize()
{
if(prosumerGA) prosumerGA->initialize();
if(SupplierGA) SupplierGA->initialize();
}
void GAManager::trade()
{
//Register all suppliers for trade, this is to mark any new-born suppliers as having a valid fitness
for(unsigned int i = 0; i < SupplierGA->generation->population->individuals.size(); i++)
SupplierGA->generation->population->individuals[i]->trade();
std::vector<Prosumer*> customers;
getCustomersInRandomOrder(customers);
for(unsigned int i = 0; i < customers.size(); i++)
{
const double avg_per_hour_factor = customers[i]->avg_per_hour_cost_factor;
double economic_capacity = customers[i]->economic_capacity;
double energy_consumption_this_hour = customers[i]->energy_consumption / avg_per_hour_factor; //We need it per hour/generation
double price;
unsigned int index_in_supplier;
int supplier_type = findBestPriceOffer(economic_capacity, energy_consumption_this_hour, price, index_in_supplier);
//Could we afford the best price offered to us?
if(supplier_type == 0)
{
//Kill the poor lad
customers[i]->saldo = 0.0;
}
//Best price from a fixed price supplier
else if(supplier_type == 1)
{
customers[i]->genome->makePurchace(price);
SupplierGA->generation->population->individuals[index_in_supplier]->reserveEnergySupply(energy_consumption_this_hour);
}
//Best price from a spot price supplier
else if(supplier_type == 2)
{
}
//Best price from a hybrid price supplier
else if(supplier_type == 3)
{
}
}
}
void GAManager::getCustomersInRandomOrder(std::vector<Prosumer*> &customers)
{
if(prosumerGA)
{
std::vector<Prosumer*> temp;
//Copy all individuals into a temp list
for(unsigned int i = 0; i < prosumerGA->generation->population->individuals.size(); i++)
{
Prosumer *customer = &prosumerGA->generation->population->individuals[i]->chromosomeValue();
temp.push_back(customer);
}
//Randomly pick an index from temp until it's empty
while(!temp.empty())
{
int rand_index = std::rand() % temp.size();
customers.push_back(temp[rand_index]);
//then erase index from temp
temp[rand_index] = temp.back();
temp.pop_back();
}
}
}
bool GAManager::evolve()
{
bool finished = false;
finished = prosumerGA->evolve();
//std::cout << *prosumerGA;
if(finished)
return finished;
finished = SupplierGA->evolve();
//std::cout << *SupplierGA;
if(finished)
return finished;
//Genearation ProsumerSaldo EconomicCapacity EnergyConsumption ProsumerPopulationSize ProsumerDeaths SupplierSaldo PriceOffer CustomerCount PriceStrategy SupplierPopulationSize SupplierDeaths
std::cout << prosumerGA->generation->id << "\t";
if(prosumerGA->generation->bestGenome)
{
std::cout << prosumerGA->generation->bestGenome->chromosomeValue().saldo << "\t";
std::cout << prosumerGA->generation->bestGenome->chromosomeValue().economic_capacity << "\t";
std::cout << prosumerGA->generation->bestGenome->chromosomeValue().energy_consumption << "\t";
std::cout << prosumerGA->generation->population->individuals.size() << "\t";
std::cout << prosumerGA->generation->deaths << "\t";
}
if(SupplierGA->generation->bestGenome)
{
std::cout << SupplierGA->generation->bestGenome->chromosomeValue().saldo << "\t";
std::cout << SupplierGA->generation->bestGenome->chromosomeValue().actual_price_offer << "\t";
std::cout << SupplierGA->generation->bestGenome->chromosomeValue().customer_count << "\t";
std::cout << SupplierGA->generation->bestGenome->chromosomeValue().price_strategy << "\t";
std::cout << SupplierGA->generation->population->individuals.size() << "\t";
std::cout << SupplierGA->generation->deaths << "\t";
}
std::cout << std::endl;
return false;
}
////////////////////////////////////////////////////
// PROSUMER HELPERS
////////////////////////////////////////////////////
unsigned int GAManager::getProsumerPopulationSize() const
{
if(prosumerGA) return prosumerGA->generation->population->individuals.size();
else return 0;
}
double GAManager::getProsumerEconomicCapacity(unsigned int individual) const
{
if(prosumerGA) return prosumerGA->generation->population->individuals[individual]->chromosomeValue().economic_capacity;
else return 0.0;
}
double GAManager::getProsumerEnergyConsumption(unsigned int individual) const
{
if(prosumerGA) return prosumerGA->generation->population->individuals[individual]->chromosomeValue().energy_consumption;
else return 0.0;
}
////////////////////////////////////////////////////
// GENERAL ALL SUPPLIERS HELPERS
////////////////////////////////////////////////////
unsigned int GAManager::getSuppliersPopulationSize() const
{
unsigned int population_size = 0;
population_size += getSupplierPopulationSize();
//population_size += getSpotSupplierPopulationSize();
//population_size += getHybridSupplierPopulationSize();
return population_size;
}
double GAManager::getSuppliersSupplyCapacity() const
{
double supply_capacity = 0;
supply_capacity += getSupplierSupplyCapacitySUM();
//supply_capacity += getSpotSupplierSupplyCapacitySUM();
//supply_capacity += getHybridSupplierSupplyCapacitySUM();
return supply_capacity;
}
int GAManager::findBestPriceOffer(double economic_capacity, double energy_consumption, double &price, unsigned int &index) const
{
double best_price = 9999999999999999.0;
int best_at_index = -1;
int index_is_from = 0;
//Check best price from all fixed price suppliers
if(SupplierGA)
{
for(unsigned int i = 0; i < getSupplierPopulationSize(); i++)
{
//If supplier can meet the energy consumption requirement
if(getSupplierUnreservedSupplyCapacity(i) >= energy_consumption)
{
double price_offer = getSupplierPriceOffer(i);
if(best_price > price_offer)
{
best_price = price_offer;
best_at_index = i;
index_is_from = 1; //1 is fixed, 2 is spot and 3 is hybrid
}
}
}
}
//Check best price from all spot price suppliers
//Check best price from all hybrid price suppliers
//Run this last
if(best_at_index >= 0)
{
//If customer can't afford the best price offered, he's dead!
if(best_price > economic_capacity)
return 0;
//is fixed price
if(index_is_from == 1)
{
price = best_price;
index = best_at_index;
return 1;
}
//is spot price
else if(index_is_from == 2)
{
price = best_price;
index = best_at_index;
return 2;
}
//is hybrid price
else if(index_is_from == 3)
{
price = best_price;
index = best_at_index;
return 3;
}
}
return 0;
}
double GAManager::findWorstPriceOffer() const
{
double worst_price = 0.0;
//Check best price from all fixed price suppliers
if(SupplierGA)
{
for(unsigned int i = 0; i < getSupplierPopulationSize(); i++)
{
double price_offer = getSupplierPriceOffer(i);
if(worst_price < price_offer)
worst_price = price_offer;
}
}
return worst_price;
}
////////////////////////////////////////////////////
// FIXED SUPPLIER HELPERS
////////////////////////////////////////////////////
unsigned int GAManager::getSupplierPopulationSize() const
{
if(SupplierGA) return SupplierGA->generation->population->individuals.size();
else return 0;
}
double GAManager::getSupplierPriceOffer(unsigned int individual) const
{
if(SupplierGA) return SupplierGA->generation->population->individuals[individual]->chromosomeValue().actual_price_offer;
return 0.0;
}
double GAManager::getSupplierUnreservedSupplyCapacity(unsigned int individual) const
{
if(SupplierGA) return getSupplierSupplyCapacity(individual) - SupplierGA->generation->population->individuals[individual]->chromosomeValue().reserved_energy;
return 0.0;
}
double GAManager::getSupplierSupplyCapacity(unsigned int individual) const
{
if(SupplierGA) return SupplierGA->generation->population->individuals[individual]->chromosomeValue().supply_capacity;
return 0.0;
}
double GAManager::getSupplierSupplyCapacitySUM() const
{
double capacity = 0.0;
for(unsigned int i = 0; i < getSupplierPopulationSize(); i++)
{
capacity += getSupplierSupplyCapacity(i);
}
return capacity;
}
unsigned int GAManager::getSupplierCustomerCount(unsigned int individual) const
{
if(SupplierGA) return SupplierGA->generation->population->individuals[individual]->chromosomeValue().customer_count_ref;
return 0;
}
////////////////////////////////////////////////////
// SPOT SUPPLIER HELPERS
////////////////////////////////////////////////////
| [
"[email protected]@92bc644c-bee7-7203-82ab-e16328aa9dbe"
] | [
[
[
1,
319
]
]
] |
d15e6de206acda5b5449b82323cc30a0e66d2df1 | 188058ec6dbe8b1a74bf584ecfa7843be560d2e5 | /GodDK/lang/IllegalMonitorStateException.h | 1fb4e4a08e536c3a1bd6df19386a84d1baa01d39 | [] | 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 | 798 | h |
#ifndef _CLASS_GOD_LANG_ILLEGALMONITORSTATEEXCEPTION_H
#define _CLASS_GOD_LANG_ILLEGALMONITORSTATEEXCEPTION_H
#ifdef __cplusplus
#include "lang/RuntimeException.h"
using namespace goddk::lang;
namespace goddk {
namespace lang {
/* \ingroup CXX_LANG_m
*/
class IllegalMonitorStateException : public virtual RuntimeException
{
public:
inline IllegalMonitorStateException()
{
}
inline IllegalMonitorStateException(const char* message) : RuntimeException(message)
{
}
inline IllegalMonitorStateException(const String* message) : RuntimeException(message)
{
}
inline ~IllegalMonitorStateException()
{
}
};
typedef CSmartPtr<IllegalMonitorStateException> IllegalMonitorStateExceptionPtr;
}
}
#endif
#endif
| [
"soaris@46205fef-a337-0410-8429-7db05d171fc8"
] | [
[
[
1,
37
]
]
] |
46c09543257186b3c0e3a8692c3b2c4cc371193f | a473bf3be1f1cda62b1d0dc23292fbf7ec00dcee | /inc/transimpl.h | 31349afc149af3f56d617bd2767f22836d42b9b4 | [] | no_license | SymbiSoft/htmlcontrol-for-symbian | 23821e9daa50707b1d030960e1c2dcf59633a335 | 504ca3cb3cf4baea3adc5c5b44e8037e0d73c3bb | refs/heads/master | 2021-01-10T15:04:51.760462 | 2009-08-14T05:40:14 | 2009-08-14T05:40:14 | 48,186,784 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,117 | h | #ifndef TRANSIMPL_H
#define TRANSIMPL_H
#include <e32base.h>
#include "htmlcontrol.hrh"
#include "transition.h"
class CHtmlElement;
class CHtmlElementImpl;
class CWritableBitmap;
class CTransition : public CActive, public MTransition
{
public:
static CTransition* NewL();
virtual ~CTransition();
virtual void Perform(CHtmlElement* aElement,
TTransitionType aType,
TTimeIntervalMicroSeconds32 aDuration,
TInt aFrames,
EasingFunction aEasingFunc=&TEasingLinear::EaseNone);
private:
CTransition();
void ConstructL();
void RunL();
TInt RunError(TInt aError);
void DoCancel();
void DoTransition();
void DoSlideLeft();
void DoSlideRight();
void DoSlideUp();
void DoSlideDown();
void DoFade();
void DoFly();
void DoScale();
void DoFlyAndScale();
private:
CHtmlElementImpl* iElement;
TTransitionType iType;
TInt iFrames;
TTimeIntervalMicroSeconds32 iDuration;
EasingFunction iEasingFunc;
TInt iCurrentFrame;
TRect iOriginRect;
TRect iTargetRect;
RTimer iTimer;
TInt iPos;
CWritableBitmap* iHelperBitmap;
};
#endif
| [
"gzytom@0e8b9480-e87f-11dd-80ed-bda8ba2650cd"
] | [
[
[
1,
56
]
]
] |
3de637dadb95b1cc12d75b3dde1f303f601590f5 | d6e0f648d63055d6576de917de8d6f0f3fcb2989 | /ddv/win/src/mwnd.h | f8f14f11a27c97b1b6448851e6edaab95dda1299 | [] | no_license | lgosha/ssd | 9b4a0ade234dd192ef30274377787edf1244b365 | 0b97a39fd7edabca44c4ac19178a5c626d1efea3 | refs/heads/master | 2020-05-19T12:41:32.060017 | 2011-09-27T12:43:06 | 2011-09-27T12:43:06 | 2,428,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,381 | h | #ifndef __MWND_H__
#define __MWND_H__
#include <QTreeWidget>
#include "udp_panswer.h"
class UTreeWidget : public QTreeWidget {
Q_OBJECT
public:
UTreeWidget( QWidget * );
void setData( pAnswer & );
void find( const QString & );
void hideItems();
private:
void createItem( uint );
private:
static uint getParId( uint, uint, uint );
static QString getParStrId( uint, uint, uint );
QColor itemBackgroundColor( QTreeWidgetItem *, uint );
void setItemBackgroundColor( QTreeWidgetItem *, uint );
private slots:
void itemChanged( QTreeWidgetItem *, QTreeWidgetItem * );
private:
QMap<uint, QTreeWidgetItem *> m_mItems;
QMap<uint, uint> m_mIds;
QMap<uint, QString> m_mStrIds;
uint m_uiCount;
QTreeWidgetItem * m_pEmpty;
};
#include <QtGui/QDialog>
#include "xmlconfig.h"
class QTabWidget;
class UDPClient;
class CMainWnd : public QDialog {
Q_OBJECT
public:
CMainWnd( XMLConfig *pXMLConfig );
~CMainWnd();
void setData( uint, pAnswer & );
void setConnectStatus( uint, uint );
protected slots:
void keyPressEvent ( QKeyEvent * );
private:
void createView( XMLConfig *, const DOMNode * );
private:
QTabWidget * m_pTabContainer;
QMap<uint, UTreeWidget*> m_mViews;
QMap<uint, UTreeWidget *> m_mItemsByIndex;
QMap<uint, int> m_mTabs;
UDPClient * m_pClient;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
62
]
]
] |
c240e6b93e70a5e5d64e9933b7a8537b4dd5bbae | 0045750d824d633aba04e1d92987e91fb87e0ee7 | /audioinfo.cpp | 346ba59f57bcaaee334c71d96b8f53efa7051ade | [] | no_license | mirelon/vlaciky | eaab3cbae7d7438c4fcb87d2b5582b0492676efc | 30f5155479a3f3556199aa2d845fcac0c9a2d225 | refs/heads/master | 2020-05-23T15:05:26.370548 | 2010-06-16T18:55:52 | 2010-06-16T18:55:52 | 33,381,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,099 | cpp | #include "audioinfo.h"
#include <cmath>
#include <cstdlib>
AudioInfo::AudioInfo(QAudioInput* device)
:QIODevice()
{
input = device;
m_maxValue = 0;
}
AudioInfo::~AudioInfo()
{
}
void AudioInfo::start()
{
open(QIODevice::WriteOnly);
}
void AudioInfo::stop()
{
close();
}
qint64 AudioInfo::readData(char *data, qint64 maxlen)
{
Q_UNUSED(data)
Q_UNUSED(maxlen)
return 0;
}
qint64 AudioInfo::writeData(const char *data, qint64 len)
{
int samples = len/2; // 2 bytes per sample
int maxAmp = 32768; // max for S16 samples
bool clipping = false;
m_maxValue = 0;
qint16* s = (qint16*)data;
// sample format is S16LE, only!
for(int i=0;i<samples;i++) {
qint16 sample = *s;
s++;
if(abs(sample) > m_maxValue) m_maxValue = abs(sample);
}
// check for clipping
if(m_maxValue>=(maxAmp-1)) clipping = true;
float value = ((float)m_maxValue/(float)maxAmp);
if(clipping) m_maxValue = 100.0;
else m_maxValue = value*100.0;
emit update();
return len;
}
qreal AudioInfo::LinearMax()
{
return m_maxValue;
}
| [
"mirelon@a6d88fff-da04-0f23-7c93-28760c376c6a"
] | [
[
[
1,
67
]
]
] |
9f7b5081076ec621f6e37329dcc8d99ab068dfb4 | 85c91b680d74357b379204ecf7643ae1423f8d1e | /branches/pre_mico_2_3-12/examples/general/philosopher/dinner_CutleryImpl/dinner_CutleryImpl.h | 944df4c14f9a5009afd98e151711f7c4dcc80e8d | [] | no_license | BackupTheBerlios/qedo-svn | 6fdec4ca613d24b99a20b138fb1488f1ae9a80a2 | 3679ffe8ac7c781483b012dbef70176e28fea174 | refs/heads/master | 2020-11-26T09:42:37.603285 | 2010-07-02T10:00:26 | 2010-07-02T10:00:26 | 40,806,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,485 | h | //
// generated by Qedo
//
#ifndef _dinner_CutleryImpl_H_
#define _dinner_CutleryImpl_H_
// BEGIN USER INSERT SECTION file_pre
// END USER INSERT SECTION file_pre
#include <CORBA.h>
#include "dinner_CutleryImpl_BUSINESS.h"
#include "component_valuetypes.h"
#include "RefCountBase.h"
#include <string>
// BEGIN USER INSERT SECTION file_post
using namespace std;
// END USER INSERT SECTION file_post
namespace dinner
{
//
// executor
//
class CutlerySessionImpl
: public virtual CORBA::LocalObject
, public virtual ::dinner::CCM_CutlerySessionImpl
#ifndef MICO_ORB
, public virtual Qedo::RefCountLocalObject
#endif
// BEGIN USER INSERT SECTION INHERITANCE_CutlerySessionImpl
// END USER INSERT SECTION INHERITANCE_CutlerySessionImpl
{
private:
::dinner::CCM_Cutlery_ContextImpl_var context_;
public:
CutlerySessionImpl();
virtual ~CutlerySessionImpl();
void set_context(::dinner::CCM_Cutlery_ContextImpl_ptr context)
throw (CORBA::SystemException, Components::CCMException);
void configuration_complete()
throw (CORBA::SystemException, Components::InvalidConfiguration);
void remove()
throw (CORBA::SystemException);
//
// IDL:dinner/Named/name:1.0
//
void name(const char* param)
throw(CORBA::SystemException);
char* name()
throw(CORBA::SystemException);
// BEGIN USER INSERT SECTION CutlerySessionImpl
private:
string id_;
// END USER INSERT SECTION CutlerySessionImpl
};
//
// segment
//
class Seg
: public virtual CORBA::LocalObject
, public virtual ::dinner::CCM_Seg
#ifndef MICO_ORB
, public virtual Qedo::RefCountLocalObject
#endif
// BEGIN USER INSERT SECTION INHERITANCE_Seg
// END USER INSERT SECTION INHERITANCE_Seg
{
private:
::dinner::CCM_Cutlery_ContextImpl_var context_;
public:
Seg();
virtual ~Seg();
void set_context(::dinner::CCM_Cutlery_ContextImpl_ptr context)
throw (CORBA::SystemException, Components::CCMException);
void configuration_complete()
throw (CORBA::SystemException, Components::InvalidConfiguration);
//
// IDL:dinner/Fork/obtain_fork:1.0
//
virtual Components::Cookie* obtain_fork()
throw(CORBA::SystemException, ::dinner::ForkNotAvailable);
//
// IDL:dinner/Fork/release_fork:1.0
//
virtual void release_fork(Components::Cookie* ck)
throw(CORBA::SystemException, ::dinner::NotTheEater);
// BEGIN USER INSERT SECTION Seg
private:
bool in_use_;
// END USER INSERT SECTION Seg
};
//
// executor locator
//
class CutleryImpl
: public virtual CORBA::LocalObject
, public virtual Components::SessionExecutorLocator
#ifndef MICO_ORB
, public virtual Qedo::RefCountLocalObject
#endif
// BEGIN USER INSERT SECTION INHERITANCE_CutleryImpl
// END USER INSERT SECTION INHERITANCE_CutleryImpl
{
private:
::dinner::CCM_Cutlery_ContextImpl_var context_;
CutlerySessionImpl* component_;
Seg* Seg_;
public:
CutleryImpl();
virtual ~CutleryImpl();
//
// IDL:Components/ExecutorLocator/obtain_executor:1.0
//
virtual CORBA::Object_ptr obtain_executor(const char* name)
throw(CORBA::SystemException);
//
// IDL:Components/ExecutorLocator/release_executor:1.0
//
virtual void release_executor(CORBA::Object_ptr exc)
throw(CORBA::SystemException);
//
// IDL:Components/ExecutorLocator/configuration_complete:1.0
//
virtual void configuration_complete()
throw(CORBA::SystemException, ::Components::InvalidConfiguration);
//
// IDL:Components/SessionComponent/set_session_context:1.0
//
virtual void set_session_context(Components::SessionContext_ptr ctx)
throw(CORBA::SystemException, ::Components::CCMException);
//
// IDL:Components/SessionComponent/ccm_activate:1.0
//
virtual void ccm_activate()
throw(CORBA::SystemException, ::Components::CCMException);
//
// IDL:Components/SessionComponent/ccm_passivate:1.0
//
virtual void ccm_passivate()
throw(CORBA::SystemException, ::Components::CCMException);
//
// IDL:Components/SessionComponent/ccm_remove:1.0
//
virtual void ccm_remove()
throw(CORBA::SystemException, ::Components::CCMException);
// BEGIN USER INSERT SECTION CutleryImpl
// END USER INSERT SECTION CutleryImpl
};
//
// home executor
//
class CutleryHomeImpl
: public virtual CORBA::LocalObject
, public virtual ::dinner::CCM_CutleryHome
#ifndef MICO_ORB
, public virtual Qedo::RefCountLocalObject
#endif
// BEGIN USER INSERT SECTION INHERITANCE_CutleryHomeImpl
// END USER INSERT SECTION INHERITANCE_CutleryHomeImpl
{
private:
Components::HomeContext_var context_;
public:
CutleryHomeImpl();
virtual ~CutleryHomeImpl();
//
// IDL:Components/HomeExecutorBase/set_context:1.0
//
virtual void set_context (Components::HomeContext_ptr ctx)
throw (CORBA::SystemException, Components::CCMException);
//
// IDL:.../create:1.0
//
virtual ::Components::EnterpriseComponent_ptr create()
throw (CORBA::SystemException, Components::CreateFailure);
// BEGIN USER INSERT SECTION CutleryHomeImpl
// END USER INSERT SECTION CutleryHomeImpl
};
};
//
// entry point
//
extern "C" {
#ifdef _WIN32
__declspec(dllexport)
#else
#endif
::Components::HomeExecutorBase_ptr create_CutleryHomeE(void);
}
#endif
| [
"tom@798282e8-cfd4-0310-a90d-ae7fb11434eb"
] | [
[
[
1,
251
]
]
] |
cc178fc4f0f5470e2d357f85ef544101416d78f3 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/sun/src/InstanceScripts/Instance_Botanica.cpp | 45ea9806a65a584056a4b952710c10036dcb4c17 | [] | no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,353 | cpp | /*
* Moon++ Scripts for Ascent MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "StdAfx.h"
#include "Setup.h"
/************************************************************************/
/* Instance_Botanica.cpp Script */
/************************************************************************/
// Bloodwarder Protector AI
#define CN_BLOOD_PROTECTOR 17993
#define CRYSTAL_STRIKE 29765 // 1 target
class BloodProtectorAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(BloodProtectorAI);
SP_AI_Spell spells[1];
bool m_spellcheck[1];
BloodProtectorAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
// -- Number of spells to add --
nrspells = 1;
// --- Initialization ---
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
// ----------------------
// Create basic info for spells here, and play with it later , fill always the info, targettype and if is instant or not!
spells[0].info = dbcSpell.LookupEntry(CRYSTAL_STRIKE);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = false;
spells[0].perctrigger = 10.0f;
spells[0].attackstoptimer = 1000; // 1sec
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
// Bloodwarder Mender AI
#define CN_BLOOD_MENDER
/* * Healer
* Casts Shadow Word: Pain and Mind Blast
* Mind Control these for Holy Fury buff (+295 spell damage for 30 minutes, shows as DIVINE fury on the pet bar). Can be spellstolen.
*/
// Bloodwarder Greenkeeper AI
#define CN_BLOOD_GREENKEEPER 18419
#define GREENKEEPER_FURY 39121
class BloodGreenkeeperAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(BloodGreenkeeperAI);
SP_AI_Spell spells[1];
bool m_spellcheck[1];
BloodGreenkeeperAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
// -- Number of spells to add --
nrspells = 1;
// --- Initialization ---
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
// ----------------------
// Create basic info for spells here, and play with it later , fill always the info, targettype and if is instant or not!
spells[0].info = dbcSpell.LookupEntry(GREENKEEPER_FURY);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = false;
spells[0].perctrigger = 10.0f;
spells[0].attackstoptimer = 1000; // 1sec
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
// Sunseeker Chemist AI
#define CN_SUN_CHEMIST 19486
#define FLAME_BREATH 18435
#define POISON_CLOUD 37469
class SunchemistAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(SunchemistAI);
SP_AI_Spell spells[2];
bool m_spellcheck[2];
SunchemistAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
// -- Number of spells to add --
nrspells = 2;
// --- Initialization ---
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
// ----------------------
// Create basic info for spells here, and play with it later , fill always the info, targettype and if is instant or not!
spells[0].info = dbcSpell.LookupEntry(FLAME_BREATH);
spells[0].targettype = TARGET_VARIOUS;
spells[0].instant = false;
spells[0].perctrigger = 10.0f;
spells[0].attackstoptimer = 3000; // 1sec
spells[1].info = dbcSpell.LookupEntry(POISON_CLOUD);
spells[1].targettype = TARGET_VARIOUS;
spells[1].instant = false;
spells[1].perctrigger = 5.0f;
spells[1].attackstoptimer = 2000; // 1sec
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
// Sunseeker Researcher AI
#define CN_SUN_RESEARCHER 18421
#define POISON_SHIELD 34355 // self
#define MIND_SHOCK 34352 // 1 target
#define FROST_SHOCK 39062 // 1 target
#define FLAME_SHOCK 22423 // 1 target
class SunResearcherAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(SunResearcherAI);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
SunResearcherAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
// -- Number of spells to add --
nrspells = 4;
// --- Initialization ---
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
// ----------------------
// Create basic info for spells here, and play with it later , fill always the info, targettype and if is instant or not!
spells[0].info = dbcSpell.LookupEntry(POISON_SHIELD);
spells[0].targettype = TARGET_SELF;
spells[0].instant = false;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000; // 1sec
spells[1].info = dbcSpell.LookupEntry(MIND_SHOCK);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = false;
spells[1].perctrigger = 5.0f;
spells[1].attackstoptimer = 2000; // 1sec
spells[2].info = dbcSpell.LookupEntry(FROST_SHOCK);
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = false;
spells[2].perctrigger = 5.0f;
spells[2].attackstoptimer = 2000; // 1sec
spells[3].info = dbcSpell.LookupEntry(FLAME_SHOCK);
spells[3].targettype = TARGET_ATTACKING;
spells[3].instant = false;
spells[3].perctrigger = 10.0f;
spells[3].attackstoptimer = 2000; // 1sec
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
_unit->CastSpell(_unit, spells[0].info, spells[0].instant);
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
/**************************/
/* */
/* Boss AIs */
/* */
/**************************/
// Commander Sarannis AI
#define CN_COMMANDER_SARANNIS 17976 // spawn adds (or maybe write spell which will be harder)
#define ARCANE_RESONANCE 34794
#define ARCANE_DEVASTATION 34799
#define SUMMON_REINFORCEMENTS 34803 // it's dummy (sss) and must be scripted separately
class CommanderSarannisAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CommanderSarannisAI);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
CommanderSarannisAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
GuardAdds = false;
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(ARCANE_RESONANCE);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].cooldown = -1;
spells[0].perctrigger = 7.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(ARCANE_DEVASTATION);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].cooldown = -1;
spells[1].perctrigger = 15.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(SUMMON_REINFORCEMENTS);
spells[2].targettype = TARGET_SELF;
spells[2].instant = true;
spells[2].cooldown = -1;
spells[2].perctrigger = 0.0f;
spells[2].attackstoptimer = 1000;
}
void OnCombatStart(Unit* mTarget)
{
GuardAdds = false;
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Step forward! I will see that you are appropriately welcomed."); // needs checks!
_unit->PlaySoundToSet(11071);
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnCombatStop(Unit *mTarget)
{
GuardAdds = false;
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnTargetDied(Unit* mTarget)
{
if (_unit->GetHealthPct() > 0) // Hack to prevent double yelling (OnDied and OnTargetDied when creature is dying)
{
int RandomSpeach;
RandomUInt(1000);
RandomSpeach=rand()%2;
switch (RandomSpeach)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Oh stop your whimpering."); // :|
_unit->PlaySoundToSet(11072);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Mission accomplished!");
_unit->PlaySoundToSet(11073);
break;
}
}
}
void OnDied(Unit * mKiller)
{
GuardAdds = false;
CastTime();
RemoveAIUpdateEvent();
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I have not yet... begun to..."); // ??
_unit->PlaySoundToSet(11079);
}
void AIUpdate()
{
if (_unit->GetHealthPct() <= 50 && GuardAdds == false)
{
GuardAdds = true; // need to add guard spawning =/
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Guards, rally! Cut these invaders down!"); // not sure
_unit->PlaySoundToSet(11078);
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void ArcaneSound()
{
int RandomArcane;
RandomArcane=rand()%30;
switch (RandomArcane)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You are no longer dealing with some underling.");
_unit->PlaySoundToSet(11076);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Band'or shorel'aran!");
_unit->PlaySoundToSet(11077);
break;
}
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
ArcaneSound();
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
bool GuardAdds;
int nrspells;
};
// High Botanist Freywinn AI
#define CN_HIGH_BOTANIST_FREYWINN 17975
#define PLANT_RED_SEEDLING 34763
#define PLANT_GREEN_SEEDLING 34761
#define PLANT_WHITE_SEEDLING 34759
#define PLANT_BLUE_SEEDLING 34762
#define SUMMON_FRAYER_PROTECTOR 34557
#define TREE_FORM 34551
#define TRANQUILITY 34550
class HighBotanistFreywinnAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(HighBotanistFreywinnAI);
SP_AI_Spell spells[7];
bool m_spellcheck[7];
HighBotanistFreywinnAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
PlantTimer = 10;
nrspells = 7;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(PLANT_RED_SEEDLING);
spells[0].targettype = TARGET_SELF;
spells[0].instant = true;
spells[0].cooldown = -1;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(PLANT_GREEN_SEEDLING);
spells[1].targettype = TARGET_SELF;
spells[1].instant = true;
spells[1].cooldown = -1;
spells[1].perctrigger = 0.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(PLANT_WHITE_SEEDLING);
spells[2].targettype = TARGET_SELF;
spells[2].instant = true;
spells[2].cooldown = -1;
spells[2].perctrigger = 0.0f;
spells[2].attackstoptimer = 1000;
spells[3].info = dbcSpell.LookupEntry(PLANT_BLUE_SEEDLING);
spells[3].targettype = TARGET_SELF;
spells[3].instant = true;
spells[3].cooldown = -1;
spells[3].perctrigger = 0.0f;
spells[3].attackstoptimer = 1000;
spells[4].info = dbcSpell.LookupEntry(SUMMON_FRAYER_PROTECTOR);
spells[4].targettype = TARGET_SELF;
spells[4].instant = true;
spells[4].cooldown = -1;
spells[4].perctrigger = 5.0f;
spells[4].attackstoptimer = 1000;
spells[5].info = dbcSpell.LookupEntry(TREE_FORM);
spells[5].targettype = TARGET_SELF;
spells[5].instant = true;
spells[5].cooldown = 40;
spells[5].perctrigger = 0.0f;
spells[5].attackstoptimer = 1000;
spells[6].info = dbcSpell.LookupEntry(TRANQUILITY);
spells[6].targettype = TARGET_VARIOUS;
spells[6].instant = false;
spells[6].cooldown = -1;
spells[6].perctrigger = 0.0f;
spells[6].attackstoptimer = 1000;
}
void OnCombatStart(Unit* mTarget)
{
PlantTimer = 10;
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "What are you doin'? These <missing_word> are very delicate!"); // needs checks!
_unit->PlaySoundToSet(11144);
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnCombatStop(Unit *mTarget)
{
PlantTimer = 10;
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnTargetDied(Unit* mTarget)
{
if (_unit->GetHealthPct() > 0) // Hack to prevent double yelling (OnDied and OnTargetDied when creature is dying)
{
int RandomSpeach;
RandomUInt(1000);
RandomSpeach=rand()%2;
switch (RandomSpeach)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Your life circle is now concluded!");
_unit->PlaySoundToSet(11145);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You will feed the worms!");
_unit->PlaySoundToSet(11146);
break;
}
}
}
void OnDied(Unit * mKiller)
{
PlantTimer = 10;
CastTime();
RemoveAIUpdateEvent();
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Those <missing_word> must be preserved!"); // ??
_unit->PlaySoundToSet(11149);
}
void AIUpdate()
{
PlantTimer--;
if (!PlantTimer)
{
PlantColorSeedling();
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void PlantColorSeedling()
{
PlantTimer=rand()%6+5; //5-10 sec (as in my DB attack time is 1000)
uint32 RandomPlant;
RandomPlant=rand()%4;
switch (RandomPlant)
{
case 0:
{
_unit->CastSpell(_unit, spells[0].info, spells[0].instant);
}break;
case 1:
{
_unit->CastSpell(_unit, spells[1].info, spells[1].instant);
}break;
case 2:
{
_unit->CastSpell(_unit, spells[2].info, spells[2].instant);
}break;
case 4:
{
_unit->CastSpell(_unit, spells[3].info, spells[3].instant);
}break;
}
}
void TreeSound()
{
uint32 RandomTree;
RandomTree=rand()%2;
switch (RandomTree)
{
case 0:
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "<missing_text>");
_unit->PlaySoundToSet(11147);
}break;
case 1:
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Nature bends to my will!");
_unit->PlaySoundToSet(11148);
}break;
}
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (m_spellcheck[5] == true)
{
TreeSound();
m_spellcheck[6] = true;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
uint32 PlantTimer;
int nrspells;
};
// Thorngrin the Tender AI
#define CN_THORNGRIN_THE_TENDER 17978
#define HELLFIRE 34659 // DBC: 34659, 34660
#define SACRIFICE 34661
#define ENRAGE 34670
class ThorngrinTheTenderAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(ThorngrinTheTenderAI);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
ThorngrinTheTenderAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
Enraged = false;
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(HELLFIRE);
spells[0].targettype = TARGET_VARIOUS;
spells[0].instant = false;
spells[0].cooldown = -1;
spells[0].perctrigger = 9.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(SACRIFICE);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = false;
spells[1].cooldown = -1;
spells[1].perctrigger = 6.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(ENRAGE);
spells[2].targettype = TARGET_SELF;
spells[2].instant = true;
spells[2].cooldown = -1;
spells[2].perctrigger = 0.0f;
spells[2].attackstoptimer = 1000;
}
void OnCombatStart(Unit* mTarget)
{
Enraged = false;
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "What aggravation is this? You will die!");
_unit->PlaySoundToSet(11205);
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnCombatStop(Unit *mTarget)
{
Enraged = false;
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnTargetDied(Unit* mTarget)
{
if (_unit->GetHealthPct() > 0) // Hack to prevent double yelling (OnDied and OnTargetDied when creature is dying)
{
int RandomSpeach;
RandomUInt(1000);
RandomSpeach=rand()%2;
switch (RandomSpeach)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You seek a prize, eh? How about death?");
_unit->PlaySoundToSet(11206);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I hate to say I told you so...");
_unit->PlaySoundToSet(11207);
break;
}
}
}
void OnDied(Unit * mKiller)
{
Enraged = false;
CastTime();
RemoveAIUpdateEvent();
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You won't... get far.");
_unit->PlaySoundToSet(11212);
}
void AIUpdate()
{
if (_unit->GetHealthPct() <= 20 && Enraged == false)
{
Enraged = true;
_unit->CastSpell(_unit, spells[2].info, spells[2].instant);
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void HellfireSound()
{
int RandomHellfire;
RandomHellfire=rand()%2;
switch (RandomHellfire)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I'll incinerate you!");
_unit->PlaySoundToSet(11210);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Scream while you burn!");
_unit->PlaySoundToSet(11211);
break;
}
}
void SacrificeSound()
{
int RandomSacrifice;
RandomSacrifice=rand()%2;
switch (RandomSacrifice)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Your life will be mine!");
_unit->PlaySoundToSet(11208);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "I revel in your pain!");
_unit->PlaySoundToSet(11209);
break;
}
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (m_spellcheck[1] == true)
{
SacrificeSound();
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
if (m_spellcheck[0] == true) // Hellfire
{
HellfireSound();
}
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
bool Enraged;
int nrspells;
};
// Laj AI
#define CN_LAJ 17980
#define ALERGIC_REACTION 34697
#define SUMMON_THORN_LASHER 34684 // DBC: 34684, 34681
#define SUMMON_THORN_FLAYER 34682 // DBC: 34685, 34682 // they should be spawned on platforms
#define TELEPORT_SELF 34673
class LajAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(LajAI);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
LajAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
TeleportTimer = 20; // It's sth about that
nrspells = 4;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(ALERGIC_REACTION);
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = false;
spells[0].cooldown = -1;
spells[0].perctrigger = 10.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(SUMMON_THORN_LASHER);
spells[1].targettype = TARGET_SELF;
spells[1].instant = true;
spells[1].cooldown = -1;
spells[1].perctrigger = 6.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(SUMMON_THORN_FLAYER);
spells[2].targettype = TARGET_SELF;
spells[2].instant = true;
spells[2].cooldown = -1;
spells[2].perctrigger = 6.0f;
spells[2].attackstoptimer = 1000;
spells[3].info = dbcSpell.LookupEntry(TELEPORT_SELF);
spells[3].targettype = TARGET_SELF;
spells[3].instant = true;
spells[3].cooldown = -1; // will take this spell separately as it needs additional coding for changing position
spells[3].perctrigger = 0.0f;
spells[3].attackstoptimer = 1000;
}
void OnCombatStart(Unit* mTarget)
{
TeleportTimer = 20;
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnCombatStop(Unit *mTarget)
{
TeleportTimer = 20;
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnTargetDied(Unit* mTarget)
{
}
void OnDied(Unit * mKiller)
{
TeleportTimer = 20;
CastTime();
RemoveAIUpdateEvent();
}
void AIUpdate()
{
TeleportTimer--;
if (!TeleportTimer)
{
_unit->SetPosition(-204.125000f, 391.248993f, -11.194300f, 0.017453f); // hmm doesn't work :S
_unit->CastSpell(_unit, spells[3].info, spells[3].instant);
TeleportTimer = 20;
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
uint32 TeleportTimer;
int nrspells;
};
// Warp Splinter AI
#define CN_WARP_SPLINTER 17977
#define STOMP 34716
#define SUMMON_SAPLINGS 34727 // DBC: 34727, 34731, 34733, 34734, 34736, 34739, 34741 (with Ancestral Life spell 34742) // won't work (guardian summon)
#define ARCANE_VOLLEY 34785 //37078, 34785 // must additional script them (because Splinter eats them after 20 sec ^)
// ^ Doesn't work somehow when used by mob :O
class WarpSplinterAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(WarpSplinterAI);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
WarpSplinterAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
SummonTimer = 20; // It's sth about that
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(STOMP);
spells[0].targettype = TARGET_VARIOUS;
spells[0].instant = true;
spells[0].cooldown = -1;
spells[0].perctrigger = 8.0f;
spells[0].attackstoptimer = 1000;
spells[1].info = dbcSpell.LookupEntry(SUMMON_SAPLINGS);
spells[1].targettype = TARGET_SELF;
spells[1].instant = true;
spells[1].cooldown = -1;
spells[1].perctrigger = 0.0f;
spells[1].attackstoptimer = 1000;
spells[2].info = dbcSpell.LookupEntry(ARCANE_VOLLEY);
spells[2].targettype = TARGET_VARIOUS; // VARIOUS
spells[2].instant = false;
spells[2].cooldown = -1;
spells[2].perctrigger = 12.0f;
spells[2].attackstoptimer = 1000;
}
void OnCombatStart(Unit* mTarget)
{
SummonTimer = 20;
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Who disturbs this sanctuary?");
_unit->PlaySoundToSet(11230);
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnCombatStop(Unit *mTarget)
{
SummonTimer = 20;
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnTargetDied(Unit* mTarget)
{
if (_unit->GetHealthPct() > 0) // Hack to prevent double yelling (OnDied and OnTargetDied when creature is dying)
{
int RandomSpeach;
RandomUInt(1000);
RandomSpeach=rand()%2;
switch (RandomSpeach)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "You must die! But wait: this does not-- No, no... you must die!");
_unit->PlaySoundToSet(11231);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "What am I doing? Why do I...");
_unit->PlaySoundToSet(11232);
break;
}
}
}
void OnDied(Unit * mKiller)
{
SummonTimer = 20;
CastTime();
RemoveAIUpdateEvent();
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "So... confused. Do not... belong here!");
_unit->PlaySoundToSet(11235);
}
void AIUpdate()
{
SummonTimer--;
if (!SummonTimer) // it will need more work on this spell in future (when this kind of spell will work)
{
/*for(int i=0;i<5;i++)
{
_unit->CastSpell(_unit, spells[1].info, spells[1].instant);
}*/
_unit->CastSpell(_unit, spells[1].info, spells[1].instant);
SummonTimer = 20;
SummonSound();
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SummonSound()
{
int RandomSummon;
RandomSummon=rand()%2;
switch (RandomSummon)
{
case 0:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Children, come to me!");
_unit->PlaySoundToSet(11233);
break;
case 1:
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Maybe this is not-- No, we fight! Come to my aid!");
_unit->PlaySoundToSet(11234);
break;
}
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
uint32 SummonTimer;
int nrspells;
};
void SetupBotanica(ScriptMgr * mgr)
{
mgr->register_creature_script(CN_BLOOD_PROTECTOR, &BloodProtectorAI::Create);
mgr->register_creature_script(CN_BLOOD_GREENKEEPER, &BloodGreenkeeperAI::Create);
mgr->register_creature_script(CN_SUN_CHEMIST, &SunchemistAI::Create);
mgr->register_creature_script(CN_SUN_RESEARCHER, &SunResearcherAI::Create);
mgr->register_creature_script(CN_COMMANDER_SARANNIS, &CommanderSarannisAI::Create);
mgr->register_creature_script(CN_HIGH_BOTANIST_FREYWINN, &HighBotanistFreywinnAI::Create);
mgr->register_creature_script(CN_THORNGRIN_THE_TENDER, &ThorngrinTheTenderAI::Create);
mgr->register_creature_script(CN_LAJ, &LajAI::Create);
mgr->register_creature_script(CN_WARP_SPLINTER, &WarpSplinterAI::Create);
}
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
] | [
[
[
1,
1461
]
]
] |
15285c3470793da5b02bd2bc4ad739d30f8556fb | 91ba1dc7ac2d753c7b73822b75d6b0c55d9ed52b | /rtppacket.h | d4eaf38848d044c93521f26ff366a5bd243e4f74 | [] | no_license | joshualant/rtpreceive | 35c326a218d1709f6505d2f1df05a1190ad87923 | f93d8eec1d3013fb95e77534f6bcb3927cd2d6ad | refs/heads/master | 2021-01-10T09:21:13.393217 | 2011-02-23T00:49:04 | 2011-02-23T00:49:04 | 43,960,631 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,393 | h | /*
* Copyright (c) 2011, Jim Hollinger
* 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 Jim Hollinger 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.
*
*/
#ifndef RTPPACKET_H_
#define RTPPACKET_H_
#include <stdio.h>
#define RTP_MAX_CSCR_COUNT (16)
class RtpPacket {
public:
char version;
char padding;
char extension;
char cscr_count;
char marker;
short payload_type;
unsigned short sequence_number;
unsigned int timestamp;
unsigned int ssrc;
unsigned int cscr[RTP_MAX_CSCR_COUNT];
const void *payload_data;
public:
RtpPacket();
~RtpPacket();
void clear();
int parse(const void *data, int len);
int store(void *data, int len);
int print();
int fprint(FILE *fp);
bool checkOrder(const RtpPacket *prev_rtp);
};
#endif // RTPPACKET_H_
| [
"[email protected]"
] | [
[
[
1,
65
]
]
] |
7b54752f828f218c22c30f36f3d53f293afb4dd2 | e8fab7f64d01d63f439ec6a98aff2a1d30b648b4 | /process/datastore/constructions/swz_mols_comp.cpp | 38ead924492f03459218557c2c750e8fa142e106 | [] | no_license | robbywalker/phftables | 387452301aace677cb345909704967e8390d1be9 | e00afc683025cfb3abced5721f3449783e4a9023 | refs/heads/master | 2021-01-21T00:52:09.945550 | 2011-04-24T18:20:38 | 2011-04-24T18:20:38 | 1,657,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,001 | cpp | #include "construction.h"
#include "../datastore.h"
#include "../util/math.h"
class c_swz_mols_comp : public construction {
public:
c_swz_mols_comp() : construction( "swz_mols_comp", 32 ) {
}
void process( array * base ) {
if ( base->k <= MAXV )
return;
if ( base->k >= MAXK )
return;
array * prev = getPreviousArray( base );
int t2 = (base->t * ( base->t - 1 )) / 2;
int min = (prev != NULL ? prev->k : (base->t - 1));
int k = base->k;
if ( k > 9999 ) {
k = 9999;
}
for ( ; k > min; k-- ) {
int m = mols[ k ];
if ( m > (t2 - 1) ) {
array * arr = new array();
arr->N = base->N * (t2 + 1);
arr->k = k * k;
arr->v = base->v;
arr->t = base->t;
arr->type = 'C';
arr->source = id;
arr->ingredients.push_back( base );
insertArray( arr );
return;
}
}
}
};
// declare the construction object
construction * mcomp = new c_swz_mols_comp(); | [
"[email protected]"
] | [
[
[
1,
48
]
]
] |
ad78d71b5b189fb645ec3cfb2fa5b73d97f55ecd | 105cc69f4207a288be06fd7af7633787c3f3efb5 | /HovercraftUniverse/HovercraftUniverse/Asteroid.h | 2741474989618255097d8accff71f3b3c92dbb4f | [] | no_license | allenjacksonmaxplayio/uhasseltaacgua | 330a6f2751e1d6675d1cf484ea2db0a923c9cdd0 | ad54e9aa3ad841b8fc30682bd281c790a997478d | refs/heads/master | 2020-12-24T21:21:28.075897 | 2010-06-09T18:05:23 | 2010-06-09T18:05:23 | 56,725,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,989 | h | #ifndef ASTEROID_H
#define ASTEROID_H
#include "HovercraftUniverseEntity.h"
#include <tinyxml/tinyxml.h>
#include "Exception.h"
namespace HovUni {
/**
* The asteroid is an entity on which the characters will race and on which the track will be placed. Every asteroid has a gravitational field
* that exercises forces on the entities that are placed onto it.
*
* @author PJ
*/
class Asteroid : public HovercraftUniverseEntity {
public:
/**
* The type of asteroid on which the race will take place.
*/
enum AsteroidType {
UNKNOWN = -1,
ICE,
FIRE,
JUNGLE,
STONE,
DESERT
};
private:
/** The name of the asteroid */
Ogre::String mDisplayName;
/** The force of the gravitational field of the asteroid */
Ogre::Real mGravity;
/** The type of asteroid */
AsteroidType mAsteroidType;
public:
/**
* The category used for asteroids
*/
static const Ogre::String CATEGORY;
/**
* Constructor.
*
* @param name The name of the asteroid
* @param position
* @param quaternion
* @param processInterval The process interval
*/
Asteroid(const Ogre::String& name, const Ogre::Vector3& position, const Ogre::Quaternion& orientation, const Ogre::String& ogreentity, float processInterval);
/**
* Constructor.
*
* @param announcedata
*/
Asteroid( ZCom_BitStream* announcedata );
/**
* Load
* @param data, xml element that descripes the asteroid
* @throws ParseException
*/
void load(TiXmlElement * data) throw(ParseException);
/**
* Destructor
*/
~Asteroid(void);
/**
* Get the name.
*
* @return name
*/
inline Ogre::String getDisplayName() const {
return mDisplayName;
}
/**
* Set the name.
*
* @param name the name
*/
inline void setDisplayName( const Ogre::String& name ) {
mDisplayName = name;
}
/**
* Get the gravity.
*
* @return the gravity
*/
inline Ogre::Real getGravity() const {
return mGravity;
}
/**
* Set the gravity.
*
* @param gravity the gravity
*/
inline void setGravity( const Ogre::Real& gravity ) {
mGravity = gravity;
}
/**
* Get the AsteroidData type.
*
* @return type the type
*/
inline AsteroidType getAsteroidType() const {
return mAsteroidType;
}
/**
* Set the AsteroidData type.
*
* @param type the type
*/
inline void setAsteroidType( AsteroidType type ) {
mAsteroidType = type;
}
/**
* Callback to process this entity. This allows to do entity specific processing
* (e.g. intermediate actions).
*
* @param timeSince the time since the last processing of the entity
*/
virtual void process(float timeSince){
}
/**
* Callback to process a controller event at the server that got processed by the
* controller. Must be overriden since this class in itself has no clue which
* controller properties there are.
*
* @param event a controller event
*/
virtual void processEventsServer(ControllerEvent* cEvent){
}
/**
* Callback to process a controller event at the owner that got processed by the
* controller. Must be overriden since this class in itself has no clue which
* controller properties there are.
*
* @param event a controller event
*/
virtual void processEventsOwner(ControllerEvent* cEvent){
}
/**
* Callback to process a controller event at other clients that got processed by the controller. Must
* be overriden since this class in itself has no clue which controller properties
* there are.
*
* @param event a controller event
*/
virtual void processEventsOther(ControllerEvent* cEvent){
}
/**
* @see NetworkEntity
*/
void setupReplication();
/**
* Get the class name for this class. This is used for registering
* the class with the network
*
* @return the class name
*/
static std::string getClassName();
};
}
#endif | [
"pintens.pieterjan@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"[email protected]",
"kristof.overdulve@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"tobias.vanbladel@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"dirk.delahaye@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c"
] | [
[
[
1,
5
],
[
7,
10
],
[
14,
18
],
[
22,
32
],
[
34,
35
],
[
37,
38
],
[
40,
49
],
[
53,
54
],
[
56,
56
],
[
58,
70
],
[
72,
78
],
[
81,
87
],
[
91,
96
],
[
100,
105
],
[
109,
114
],
[
118,
123
],
[
127,
147
],
[
149,
157
],
[
159,
167
],
[
169,
174
],
[
183,
187
]
],
[
[
6,
6
],
[
71,
71
],
[
175,
182
]
],
[
[
11,
13
],
[
19,
21
],
[
33,
33
],
[
36,
36
],
[
39,
39
],
[
50,
52
],
[
55,
55
],
[
79,
80
],
[
88,
90
],
[
97,
99
],
[
106,
108
],
[
115,
117
],
[
124,
126
]
],
[
[
57,
57
]
],
[
[
148,
148
],
[
158,
158
],
[
168,
168
]
]
] |
50d5bd6fed6877cc03a2c2606efd174b11a89c5d | df2224596a6b24f9a320fc8313c0ed6f161970db | /hSphere.cpp | cf46b488ccd5245ee8df292c16749fb412ce8b1d | [] | no_license | arnaringib/uni-iceland-haptic | d38f463c3c15792a6184f1136670eeb5edd787c2 | 57ac9d79a15d4da53082d3504b1f99457604bbaa | refs/heads/master | 2021-01-01T16:25:08.104447 | 2010-05-20T21:20:18 | 2010-05-20T21:20:18 | 32,108,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 776 | cpp | #include "hSphere.h"
using namespace std;
using namespace H3D;
using namespace H3DUtil::ArithmeticTypes;
hSphere::hSphere() : Shapes(){
sphere = new Sphere;
}
hSphere::~hSphere(){
delete sphere;
}
void hSphere::setRadius(const float &radius){
sphere->radius->setValue(radius);
}
void hSphere::setSolid(const bool &solid){
sphere->solid->setValue(solid);
}
Node* hSphere::getNode(void){
shape->appearance->setValue(appearance);
appearance->material->setValue(material);
shape->geometry->setValue(sphere);
transform->children->push_back(shape);
resultNode->children->push_back(transform);
if(enableMagnetic)
{
magnetic->geometry->setValue(sphere);
resultNode->children->push_back(magnetic);
}
return resultNode;
} | [
"arnaringib@cfee87e8-01ee-11df-bfb3-7781b9cb07ea"
] | [
[
[
1,
39
]
]
] |
66e7fd923c373865c4e2036234b8f2a035d29a92 | f13f46fbe8535a7573d0f399449c230a35cd2014 | /JelloMan/Engine.cpp | 568ed0c847d86fb42db2530e064a3930cf482d63 | [] | no_license | fangsunjian/jello-man | 354f1c86edc2af55045d8d2bcb58d9cf9b26c68a | 148170a4834a77a9e1549ad3bb746cb03470df8f | refs/heads/master | 2020-12-24T16:42:11.511756 | 2011-06-14T10:16:51 | 2011-06-14T10:16:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,436 | cpp | #include "Engine.h"
#include "MainGame.h"
#include "ContentManager.h"
#include "GameConfig.h"
LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static Engine* app = 0;
switch( msg )
{
case WM_CREATE:
{
// Get the 'this' pointer we passed to CreateWindow via the lpParam parameter.
CREATESTRUCT* cs = (CREATESTRUCT*)lParam;
app = (Engine*)cs->lpCreateParams;
return 0;
}
}
// Don't start processing messages until after WM_CREATE.
if( app )
return app->MsgProc(msg, wParam, lParam);
else
return DefWindowProc(hwnd, msg, wParam, lParam);
}
Engine::Engine(HINSTANCE hInstance)
:m_hAppInst(hInstance)
,m_hMainWnd(0)
,m_AppPaused(false)
,m_Minimized(false)
,m_Maximized(false)
,m_Resizing(false)
,m_pGame(0)
,m_pDXDevice(0)
,m_pSwapChain(0)
,m_pDepthStencilBuffer(0)
,m_pRenderTargetView(0)
,m_pDepthStencilView(0)
,m_d3dDriverType( D3D10_DRIVER_TYPE_HARDWARE)
,m_ClearColor( D3DXCOLOR(0.0f, 0.0f, 0.4f, 1.0f))
,m_ClientWidth( 800)
,m_ClientHeight( 600)
,m_CurrentBackbufferWidth(0)
,m_CurrentBackbufferHeight(0)
,m_pContentManager(0)
,m_pD2DFactory(0)
,m_pBackBufferRT(0)
,m_bInitialized(false)
,m_Angle(0)
,m_bResize(false)
,m_pPhysXEngine(0)
{
m_GameTimer.Reset();
}
Engine::~Engine()
{
delete m_pGameConfig;
delete CONTROLS;
delete BX2D;
SafeDelete(m_pContentManager);
SafeDelete(m_pPhysXEngine);
if(m_pDXDevice != 0)
m_pDXDevice->ClearState();
SafeRelease(m_pRenderTargetView);
SafeRelease(m_pDepthStencilView);
SafeRelease(m_pSwapChain);
SafeRelease(m_pDepthStencilBuffer);
SafeRelease(m_pDXDevice);
SafeRelease(m_pD2DFactory);
SafeRelease(m_pBackBufferRT);
}
HINSTANCE Engine::GetAppInst()
{
return m_hAppInst;
}
HWND Engine::GetMainWnd()
{
return m_hMainWnd;
}
int Engine::Run()
{
MSG msg = {0};
while(msg.message != WM_QUIT)
{
// If there are Window messages then process them.
if(PeekMessage( &msg, 0, 0, 0, PM_REMOVE ))
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
// Otherwise, do animation/game stuff.
else
{
if( !m_AppPaused )
{
m_GameTimer.Tick();
OnRender();
if (!m_bInitialized)
{
m_LoadResourcesThread = boost::thread(&MainGame::LoadResources, m_pGame, m_pDXDevice);
m_bInitialized = true;
}
}
else
Sleep(50);
}
}
return static_cast<int>(msg.wParam);
}
void Engine::Initialize()
{
// init main game
m_pGameConfig = new GameConfig();
m_pGame->Initialize(*m_pGameConfig);
CONTROLS->SetKeyboardLayout(m_pGameConfig->GetKeyboardLayout());
m_ClientWidth = static_cast<int>(m_pGameConfig->GetWindowSize().width);
m_ClientHeight = static_cast<int>(m_pGameConfig->GetWindowSize().height);
// init DirectX & Direct2D & open window
CreateDeviceIndependentResources();
InitMainWindow(m_pGameConfig->GetGameTitle());
CreateDeviceResources();
#if defined DEBUG || _DEBUG
cout << "-Direct2D & DirectX initialized\n";
#endif
// init D2D engine
BX2D->Initialize( m_pBackBufferRT,
m_pD2DFactory );
BX2D->SetWindowHandle(m_hMainWnd);
BX2D->SetWindowInstance(m_hAppInst);
#if defined DEBUG || _DEBUG
cout << "-Blox2DEngine Engine initialized\n";
#endif
Content->Init(m_pDXDevice);
}
void Engine::OnRender()
{
CreateDeviceResources();
if (m_bResize)
{
RecreateSizedResources();
m_bResize = false;
}
// main game cycle
if (m_pBackBufferRT)
{
m_pBackBufferRT->BeginDraw();
if (!m_pGame->ResourcesLoaded())
{
m_pGame->LoadScreen();
}
else
{
m_pGame->UpdateScene(m_GameTimer.GetDeltaTime());
m_pGame->DrawScene();
}
m_pBackBufferRT->EndDraw();
}
// displaying backbuffer - vsync on
//m_pSwapChain->Present(1, 0);
// displaying backbuffer - vsync off
m_pSwapChain->Present(0, 0);
}
LRESULT Engine::MsgProc(UINT msg, WPARAM wParam, LPARAM lParam)
{
POINTS currentpos;
short zPos=0;
switch( msg )
{
// WM_ACTIVATE is sent when the window is activated or deactivated.
// We pause the game when the window is deactivated and unpause it
// when it becomes active.
case WM_ACTIVATE:
if( LOWORD(wParam) == WA_INACTIVE )
{
m_AppPaused = true;
m_GameTimer.Stop();
}
else
{
m_AppPaused = false;
m_GameTimer.Start();
}
return 0;
// WM_SIZE is sent when the user resizes the window.
case WM_SIZE:
// Save the new client area dimensions.
m_ClientWidth = LOWORD(lParam);
m_ClientHeight = HIWORD(lParam);
if( m_pDXDevice )
{
if( wParam == SIZE_MINIMIZED )
{
m_AppPaused = true;
m_Minimized = true;
m_Maximized = false;
}
else if( wParam == SIZE_MAXIMIZED )
{
m_AppPaused = false;
m_Minimized = false;
m_Maximized = true;
//RecreateSizedResources();
m_bResize = true;
}
else if( wParam == SIZE_RESTORED )
{
// Restoring from minimized state?
if( m_Minimized )
{
m_AppPaused = false;
m_Minimized = false;
//RecreateSizedResources();
m_bResize = true;
}
// Restoring from maximized state?
else if( m_Maximized )
{
m_AppPaused = false;
m_Maximized = false;
//RecreateSizedResources();
m_bResize = true;
}
else if( m_Resizing )
{
// If user is dragging the resize bars, we do not resize
// the buffers here because as the user continuously
// drags the resize bars, a stream of WM_SIZE messages are
// sent to the window, and it would be pointless (and slow)
// to resize for each WM_SIZE message received from dragging
// the resize bars. So instead, we reset after the user is
// done resizing the window and releases the resize bars, which
// sends a WM_EXITSIZEMOVE message.
}
else // API call such as SetWindowPos or mSwapChain->SetFullscreenState.
{
//RecreateSizedResources();
m_bResize = true;
}
}
}
return 0;
// WM_EXITSIZEMOVE is sent when the user grabs the resize bars.
case WM_ENTERSIZEMOVE:
m_AppPaused = true;
m_Resizing = true;
m_GameTimer.Stop();
return 0;
// WM_EXITSIZEMOVE is sent when the user releases the resize bars.
// Here we reset everything based on the new window dimensions.
case WM_EXITSIZEMOVE:
m_AppPaused = false;
m_Resizing = false;
m_GameTimer.Start();
//RecreateSizedResources();
m_bResize = true;
return 0;
// WM_DESTROY is sent when the window is being destroyed.
case WM_DESTROY:
PostQuitMessage(0);
return 0;
// The WM_MENUCHAR message is sent when a menu is active and the user presses
// a key that does not correspond to any mnemonic or accelerator key.
case WM_MENUCHAR:
// Don't beep when we alt-enter.
return MAKELRESULT(0, MNC_CLOSE);
// Catch this message so to prevent the window from becoming too small.
case WM_GETMINMAXINFO:
((MINMAXINFO*)lParam)->ptMinTrackSize.x = 200;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = 200;
return 0;
//mousemoves for input state
case WM_MOUSEMOVE:
currentpos = MAKEPOINTS(lParam);
CONTROLS->SetMousePos(Point2F(currentpos.x,currentpos.y));
m_bMouseMoving = true;
return 0;
case WM_LBUTTONDOWN:
CONTROLS->SetOldMousePos(CONTROLS->GetMousePos());
CONTROLS->SetLeftMBDown(true);
CONTROLS->SetLeftMBClicked(false);
//ShowCursor(false);
return 0;
case WM_LBUTTONUP:
CONTROLS->SetLeftMBClicked(true);
CONTROLS->SetLeftMBDown(false);
//ShowCursor(true);
return 0;
case WM_RBUTTONDOWN:
CONTROLS->SetOldMousePos(CONTROLS->GetMousePos());
CONTROLS->SetRightMBDown(true);
CONTROLS->SetRightMBClicked(false);
return 0;
case WM_RBUTTONUP:
CONTROLS->SetRightMBClicked(true);
CONTROLS->SetRightMBDown(false);
return 0;
case WM_MOUSEWHEEL:
zPos = GET_WHEEL_DELTA_WPARAM(wParam);
CONTROLS->SetMouseWheelPos(zPos);
return 0;
}
m_bMouseMoving = false;
return DefWindowProc(m_hMainWnd, msg, wParam, lParam);
}
void Engine::InitMainWindow(const tstring* pTitle)
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = MainWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = m_hAppInst;
wc.hIcon = LoadIcon(0, IDI_APPLICATION);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = L"D3DWndClassName";
if( !RegisterClass(&wc) )
{
MessageBox(0, L"RegisterClass FAILED", 0, 0);
PostQuitMessage(0);
}
// Compute window rectangle dimensions based on requested client area dimensions.
RECT R = { 0, 0, m_ClientWidth, m_ClientHeight };
AdjustWindowRect(&R, WS_POPUPWINDOW | WS_CAPTION | WS_CLIPCHILDREN | WS_MINIMIZEBOX, false);
int width = R.right - R.left;
int height = R.bottom - R.top;
m_hMainWnd = CreateWindow(L"D3DWndClassName", pTitle->c_str(),
WS_POPUPWINDOW | WS_CAPTION | WS_CLIPCHILDREN | WS_MINIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, width, height, 0, 0, m_hAppInst, this);
if( !m_hMainWnd )
{
MessageBox(0, L"CreateWindow FAILED", 0, 0);
PostQuitMessage(0);
}
ShowWindow(m_hMainWnd, SW_SHOW);
UpdateWindow(m_hMainWnd);
}
HRESULT Engine::CreateDeviceIndependentResources()
{
static const WCHAR msc_fontName[] = L"Verdana";
static const FLOAT msc_fontSize = 12;
HRESULT hr;
ID2D1GeometrySink *pSink = NULL;
// Create a Direct2D factory.
hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory);
SafeRelease(pSink);
return hr;
}
HRESULT Engine::CreateDeviceResources()
{
HRESULT hr = S_OK;
// If we don't have a device, need to create one now and all
// accompanying D3D resources.
if (!m_pDXDevice)
{
RECT rcClient;
ID3D10Device1 *pDevice = NULL;
IDXGIDevice *pDXGIDevice = NULL;
IDXGIFactory *pDXGIFactory = NULL;
IDXGISurface *pSurface = NULL;
IDXGIAdapter *pSelectedAdapter = NULL;
ASSERT(m_hMainWnd != 0, "");
GetClientRect(m_hMainWnd, &rcClient);
UINT nWidth = abs(rcClient.right - rcClient.left);
UINT nHeight = abs(rcClient.bottom - rcClient.top);
cout << "Start creating device!\n";
UINT nDeviceFlags = D3D10_CREATE_DEVICE_BGRA_SUPPORT;
#if _DEBUG
nDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
#endif
IDXGIAdapter *pAdapter = NULL;
D3D10_DRIVER_TYPE driverType = D3D10_DRIVER_TYPE_HARDWARE;
cout << "Creating Factory!\n";
HRESULT hRes(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&pDXGIFactory));
cout << "Done creating Factory!\n";
ASSERT(SUCCEEDED(hRes), "Failed to create factory");
UINT nAdapter = 0;
while (pDXGIFactory->EnumAdapters(nAdapter, &pAdapter) != DXGI_ERROR_NOT_FOUND)
{
if (pAdapter != 0)
{
DXGI_ADAPTER_DESC adaptDesc;
if (SUCCEEDED(pAdapter->GetDesc(&adaptDesc)))
{
cout << "EnumAdapters " << adaptDesc.DeviceId << "\n";
const bool isPerfHUD = wcscmp(adaptDesc.Description, L"NVIDIA PerfHUD") == 0;
// Select the first adapter in normal circumstances or the PerfHUD one if it exists.
if(nAdapter == 0 || isPerfHUD)
{
if (pSelectedAdapter != 0)
SafeRelease(pSelectedAdapter);
pSelectedAdapter = pAdapter;
}
else
SafeRelease(pAdapter);
if(isPerfHUD)
{
driverType = D3D10_DRIVER_TYPE_REFERENCE;
//nDeviceFlags |= D3D10_CREATE_DEVICE_SWITCH_TO_REF;
#if _DEBUG
cout << "NVIDIA PerfHUD found!\n";
#endif
}
}
}
++nAdapter;
}
cout << "Got adapter!\n";
// Create device
hr = CreateD3DDevice(
pSelectedAdapter,
driverType,
nDeviceFlags,
&pDevice
);
cout << "CreatedD3DDevice!\n";
if (FAILED(hr))
{
hr = CreateD3DDevice(
NULL,
D3D10_DRIVER_TYPE_WARP,
nDeviceFlags,
&pDevice
);
#if _DEBUG
cout << "Failed to create hardware device, making D3D10_DRIVER_TYPE_WARP\n";
#endif
}
if (SUCCEEDED(hr))
{
hr = pDevice->QueryInterface(&m_pDXDevice);
}
if (SUCCEEDED(hr))
{
hr = pDevice->QueryInterface(&pDXGIDevice);
}
/*if (SUCCEEDED(hr))
{
hr = pDXGIDevice->GetAdapter(&pAdapter);
}
if (SUCCEEDED(hr))
{
hr = pAdapter->GetParent(IID_PPV_ARGS(&pDXGIFactory));
}*/
if (SUCCEEDED(hr))
{
DXGI_SWAP_CHAIN_DESC swapDesc;
::ZeroMemory(&swapDesc, sizeof(swapDesc));
swapDesc.BufferDesc.Width = nWidth;
swapDesc.BufferDesc.Height = nHeight;
swapDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapDesc.BufferDesc.RefreshRate.Numerator = 0;
swapDesc.BufferDesc.RefreshRate.Denominator = 0;
swapDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
swapDesc.SampleDesc.Count = 1;
swapDesc.SampleDesc.Quality = 0;
swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapDesc.BufferCount = 1;
swapDesc.OutputWindow = m_hMainWnd;
swapDesc.Windowed = TRUE;
swapDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapDesc.Flags = 0;
hr = pDXGIFactory->CreateSwapChain(m_pDXDevice, &swapDesc, &m_pSwapChain);
}
if (SUCCEEDED(hr))
{
hr = RecreateSizedResources();
m_pGame->OnResize(m_pRenderTargetView);
}
if (SUCCEEDED(hr))
{
// anti-aliasing for direct2D
if (m_pGameConfig->Blox2DAntiAliasing())
m_pBackBufferRT->SetAntialiasMode(D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
else
m_pBackBufferRT->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED);
}
SafeRelease(pDevice);
SafeRelease(pSelectedAdapter);
SafeRelease(pDXGIDevice);
SafeRelease(pDXGIFactory);
SafeRelease(pSurface);
}
return hr;
}
HRESULT Engine::RecreateSizedResources()
{
m_pGame->Release();
UINT nWidth = m_ClientWidth;
UINT nHeight = m_ClientHeight;
HRESULT hr = S_OK;
IDXGISurface1 *pBackBuffer = NULL;
ID3D10Resource *pBackBufferResource = NULL;
ID3D10RenderTargetView *viewList[1] = {NULL};
// Ensure that nobody is holding onto one of the old resources
SafeRelease(m_pBackBufferRT);
SafeRelease(m_pRenderTargetView);
m_pDXDevice->OMSetRenderTargets(1, viewList, NULL);
// Resize render target buffers
hr = m_pSwapChain->ResizeBuffers(1, nWidth, nHeight, DXGI_FORMAT_R8G8B8A8_UNORM, 0);
if (SUCCEEDED(hr))
{
D3D10_TEXTURE2D_DESC texDesc;
texDesc.Width = nWidth;
texDesc.Height = nHeight;
texDesc.Format = DXGI_FORMAT_R32_TYPELESS;
texDesc.ArraySize = 1;
texDesc.MipLevels = 1;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D10_USAGE_DEFAULT;
texDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = 0;
SafeRelease(m_pDepthStencilBuffer);
hr = m_pDXDevice->CreateTexture2D(&texDesc, NULL, &m_pDepthStencilBuffer);
}
if (SUCCEEDED(hr))
{
// Create the render target view and set it on the device
hr = m_pSwapChain->GetBuffer(
0,
IID_PPV_ARGS(&pBackBufferResource)
);
}
if (SUCCEEDED(hr))
{
D3D10_RENDER_TARGET_VIEW_DESC renderDesc;
renderDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
renderDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
renderDesc.Texture2D.MipSlice = 0;
SafeRelease(m_pRenderTargetView);
hr = m_pDXDevice->CreateRenderTargetView(pBackBufferResource, &renderDesc, &m_pRenderTargetView);
}
if (SUCCEEDED(hr))
{
D3D10_DEPTH_STENCIL_VIEW_DESC depthViewDesc;
depthViewDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthViewDesc.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
depthViewDesc.Texture2D.MipSlice = 0;
SafeRelease(m_pDepthStencilView);
hr = m_pDXDevice->CreateDepthStencilView(m_pDepthStencilBuffer, &depthViewDesc, &m_pDepthStencilView);
}
if (SUCCEEDED(hr))
{
viewList[0] = m_pRenderTargetView;
m_pDXDevice->OMSetRenderTargets(1, viewList, m_pDepthStencilView);
// Set a new viewport based on the new dimensions
D3D10_VIEWPORT viewport;
viewport.Width = nWidth;
viewport.Height = nHeight;
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
m_pDXDevice->RSSetViewports(1, &viewport);
// Get a surface in the swap chain
hr = m_pSwapChain->GetBuffer(
0,
IID_PPV_ARGS(&pBackBuffer)
);
}
if (SUCCEEDED(hr))
{
// Create the DXGI Surface Render Target.
FLOAT dpiX = 96;
FLOAT dpiY = 96;
//m_pD2DFactory->GetDesktopDpi(&dpiX, &dpiY);
D2D1_RENDER_TARGET_PROPERTIES props =
D2D1::RenderTargetProperties(
D2D1_RENDER_TARGET_TYPE_HARDWARE,
D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED),
dpiX,
dpiY
);
// Create a Direct2D render target which can draw into the surface in the swap chain
SafeRelease(m_pBackBufferRT);
hr = m_pD2DFactory->CreateDxgiSurfaceRenderTarget(
pBackBuffer,
&props,
&m_pBackBufferRT
);
ASSERT(SUCCEEDED(hr), "");
// anti-aliasing for direct2D
if (m_pGameConfig->Blox2DAntiAliasing())
m_pBackBufferRT->SetAntialiasMode(D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
else
m_pBackBufferRT->SetAntialiasMode(D2D1_ANTIALIAS_MODE_ALIASED);
// sending new rendertarget to Blox2DEngine
BX2D->OnResize(m_pBackBufferRT);
m_pGame->OnResize(m_pRenderTargetView);
}
SafeRelease(pBackBuffer);
SafeRelease(pBackBufferResource);
return hr;
}
HRESULT Engine::CreateD3DDevice(
IDXGIAdapter *pAdapter,
D3D10_DRIVER_TYPE driverType,
UINT flags,
ID3D10Device1 **ppDevice
)
{
HRESULT hr = S_OK;
static const D3D10_FEATURE_LEVEL1 levelAttempts[] =
{
D3D10_FEATURE_LEVEL_10_1,
D3D10_FEATURE_LEVEL_10_0,
D3D10_FEATURE_LEVEL_9_3,
D3D10_FEATURE_LEVEL_9_2,
D3D10_FEATURE_LEVEL_9_1
};
for (UINT level = 0; level < ARRAYSIZE(levelAttempts); level++)
{
ID3D10Device1 *pDevice = NULL;
hr = D3D10CreateDevice1(
pAdapter,
driverType,
NULL,
flags,
levelAttempts[level],
D3D10_1_SDK_VERSION,
&pDevice
);
if (SUCCEEDED(hr))
{
cout << "D3D10CreateDevice1 success";
// transfer reference
*ppDevice = pDevice;
pDevice = NULL;
break;
}
else
{
cout << "D3D10CreateDevice1 failed";
}
}
return hr;
} | [
"[email protected]",
"bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6"
] | [
[
[
1,
67
],
[
70,
111
],
[
113,
187
],
[
191,
412
],
[
429,
429
],
[
474,
475
],
[
478,
478
],
[
480,
480
],
[
482,
485
],
[
494,
503
],
[
505,
510
],
[
512,
518
],
[
520,
521
],
[
524,
531
],
[
534,
549
],
[
555,
567
],
[
569,
577
],
[
579,
583
],
[
587,
590
],
[
594,
598
],
[
600,
610
],
[
612,
620
],
[
622,
652
],
[
656,
658
],
[
660,
671
],
[
673,
702
],
[
704,
706
],
[
708,
717
],
[
719,
724
],
[
726,
730
],
[
735,
739
]
],
[
[
68,
69
],
[
112,
112
],
[
188,
190
],
[
413,
428
],
[
430,
473
],
[
476,
477
],
[
479,
479
],
[
481,
481
],
[
486,
493
],
[
504,
504
],
[
511,
511
],
[
519,
519
],
[
522,
523
],
[
532,
533
],
[
550,
554
],
[
568,
568
],
[
578,
578
],
[
584,
586
],
[
591,
593
],
[
599,
599
],
[
611,
611
],
[
621,
621
],
[
653,
655
],
[
659,
659
],
[
672,
672
],
[
703,
703
],
[
707,
707
],
[
718,
718
],
[
725,
725
],
[
731,
734
]
]
] |
fc947e8b99b6e61b70f0096ca9dbd7152c84ea1e | ae0b041a5fb2170a3d1095868a7535cc82d6661f | /MFCHash/MFCHash.h | 71ae690816d1db0a92e12ab7682aa4e83610ee20 | [] | no_license | hexonxons/6thSemester | 59c479a1bb3cd715744543f4c2e0f8fdbf336f4a | c3c8fdea6eef49de629a7f454b91ceabd58d15d8 | refs/heads/master | 2016-09-15T17:45:13.433434 | 2011-06-08T20:57:25 | 2011-06-08T20:57:25 | 1,467,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | h | // MFCHash.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CMFCHashApp:
// See MFCHash.cpp for the implementation of this class
//
class CMFCHashApp : public CWinApp
{
public:
CMFCHashApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CMFCHashApp theApp; | [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
4b56c681a13d83777e5f9a45e46726344d6a9a34 | b4bff7f61d078e3dddeb760e21174a781ed7f985 | /Source/Contrib/UserInterface/src/Component/Spinner/OSGAbstractSpinnerModel.cpp | 9eeef13c84ca80d901885c6d3bec3daa8187e436 | [] | no_license | Langkamp/OpenSGToolbox | 8283edb6074dffba477c2c4d632e954c3c73f4e3 | 5a4230441e68f001cdf3e08e9f97f9c0f3c71015 | refs/heads/master | 2021-01-16T18:15:50.951223 | 2010-05-19T20:24:52 | 2010-05-19T20:24:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,915 | cpp | /*---------------------------------------------------------------------------*\
* OpenSG ToolBox UserInterface *
* *
* *
* *
* *
* www.vrac.iastate.edu *
* *
* Authors: David Kabala, Alden Peterson, Lee Zaniewski, Jonathan Flory *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#define OSG_COMPILEUSERINTERFACELIB
#include "OSGConfig.h"
#include "OSGAbstractSpinnerModel.h"
#include <boost/bind.hpp>
OSG_BEGIN_NAMESPACE
/***************************************************************************\
* Description *
\***************************************************************************/
/*! \class OSG::AbstractSpinnerModel
A AbstractSpinnerModel.
*/
/***************************************************************************\
* Class variables *
\***************************************************************************/
/***************************************************************************\
* Class methods *
\***************************************************************************/
/***************************************************************************\
* Instance methods *
\***************************************************************************/
EventConnection AbstractSpinnerModel::addChangeListener(ChangeListenerPtr l)
{
_ChangeListeners.insert(l);
return EventConnection(
boost::bind(&AbstractSpinnerModel::isChangeListenerAttached, this, l),
boost::bind(&AbstractSpinnerModel::removeChangeListener, this, l));
}
bool AbstractSpinnerModel::isChangeListenerAttached(ChangeListenerPtr l) const
{
return _ChangeListeners.find(l) != _ChangeListeners.end();
}
void AbstractSpinnerModel::removeChangeListener(ChangeListenerPtr l)
{
ChangeListenerSetItor EraseIter(_ChangeListeners.find(l));
if(EraseIter != _ChangeListeners.end())
{
_ChangeListeners.erase(EraseIter);
}
}
void AbstractSpinnerModel::produceStateChanged(void)
{
const ChangeEventUnrecPtr TheEvent = ChangeEvent::create(NULL, getSystemTime());
ChangeListenerSet ModelListenerSet(_ChangeListeners);
for(ChangeListenerSetConstItor SetItor(ModelListenerSet.begin()) ; SetItor != ModelListenerSet.end() ; ++SetItor)
{
(*SetItor)->stateChanged(TheEvent);
}
}
/*-------------------------------------------------------------------------*\
- private -
\*-------------------------------------------------------------------------*/
/*----------------------- constructors & destructors ----------------------*/
/*----------------------------- class specific ----------------------------*/
OSG_END_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
119
]
]
] |
c6700d63e8cac3bfa82be6ae8c32716c6d4b46bf | 9c05239052fbbd9144cadeb34a3bf66fc845a305 | /src/IOMgmt.h | f02fb46752383103960f7b333a3b18dfaf7cabf6 | [] | no_license | Steve132/solongsucker | 91e856bb05528c8560b0a5d8012618083a19c67f | c7c1d57082dea4bcf629e59fe416d1dac64dea47 | refs/heads/master | 2016-09-06T15:56:38.487323 | 2009-05-04T18:34:46 | 2009-05-04T18:34:46 | 32,110,628 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,660 | h | #ifndef _IOMGMT
#define _IOMGMT
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
#include "AppError.h"
#define MARGINSIZE 20
namespace IOMgmt
{
class IOError: public AppError
{
public:
IOError(); //default constructor
IOError(string Msg); //constructor
IOError(string Msg, string Org); //constructor
//INHERITED:
//string getMsg();
//string getOrigin();
//void appendMsg(string Msg);
//void appendOrg(string Org);
private:
static const string IOERROR;
}; //IOError
class TokenError: public AppError
{
public:
TokenError(); //default constructor
TokenError(string Msg); //constructor
TokenError(string Msg, string Org); //constructor
//INHERITED:
//string getMsg();
//string getOrigin();
//void appendMsg(string Msg);
//void appendOrg(string Org);
private:
static const string TOKENERROR;
}; //TokenError
bool IsIn(char x, string s); //Does (x) occur in (s)?
bool Allwsp(string s); //Is (s) all whitespace?
bool IsWSP (char ch ); //Is (ch) whitespace?
class InMgr
{
public:
InMgr( string Prompt ) throw( IOError );
string getFileName() const;
ifstream& getStream() throw( IOError );
void close() throw( IOError );
void setFilePos() throw( IOError );
void resetFilePos() throw( IOError );
private:
ifstream fin;
long finpos;
string fileName;
};//InMgr
class OutMgr
{
public:
OutMgr( string Prompt ) throw( IOError );
string getFileName() const;
ostream& getStream() throw( IOError );
void close() throw( IOError );
void pushMargin() throw( IOError ); //push cur
void popMargin() throw( IOError ); //pop cur
void newLine() throw( IOError );
void deltaMargin(int delta) throw( IOError );
void toMargin() throw( IOError );
void pushToMargin(int delta) throw( IOError );
void popToMargin() throw( IOError );
void advToMargin() throw( IOError );
void pushAdvMargin() throw( IOError );
void popAdvMargin() throw( IOError );
void clearMargins();
private:
string fileName;
ofstream fout;
long lineorg;
long curpos;
long margin[MARGINSIZE];
int idx;
};//OutMgr
class Tokenizer
{
public:
Tokenizer( string Prompt) throw (IOError); //Constructor uses InMgr
bool More(); //"false" if EOF
string Scan(); //delivers next token:
//!found => returns null string
// found => next token
void SetDelims(string symbols) throw (TokenError);
//sets new delimiters (not null)
string GetDelims(); //returns current delimiters
string GetDiscard(); //returns discarded delimiters
//before token returned by Scan()
void Reset(); //Revert to DELIMS
void Putback(string token); //"undo" token
private:
static const string DELIMS; //Blank,Tab,Newline
InMgr FinMgr;
ifstream& fin; //encapsulated input stream
string delims; //active delimiters
string backbuff; //pushback buffer
string discard; //string discarded before next token
char NextChar(); //returns next character
bool IsDelim(char x); //tests for a delimiter
};//Tokenizer
class StringTokenizer
{
public:
StringTokenizer();
StringTokenizer(string astr);
bool More(); //"false" if no more tokens
string Scan(); //delivers next token:
//!found => returns null string
// found => next token
void SetDelims(string symbols) throw (TokenError); //sets new delimiters (not null)
string GetDelims(); //returns current delimiters
string GetDiscard(); //returns discarded delimiters
//before token returned by Scan()
void Reset(); //Revert to DELIMS
void Putback(string token); //"undo" token
void CatBuff(string astr ); //append to string buffere
private:
string strbuff; //encapsulated input string buffer
static const string DELIMS; //Blank,Tab
string delims; //active delimiters
string backbuff; //pushback buffer
string discard; //string discarded before next token
char NextChar(); //returns next character
bool IsDelim(char x); //tests for a delimiter
};//StringTokenizer
}//namespace
#endif
| [
"sarahloewy@0cb4d474-18c1-11de-989c-57ac4e9a12f8",
"[email protected]@0cb4d474-18c1-11de-989c-57ac4e9a12f8"
] | [
[
[
1,
12
],
[
156,
160
]
],
[
[
13,
155
]
]
] |
58ed605c26b4c23cd1ccc8f8158cf4eb44f1d996 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/AIGoalSearch.h | 7c5cd1dd7fdfd599c021d8492c8212b645944f19 | [] | no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,086 | h | // ----------------------------------------------------------------------- //
//
// MODULE : AIGoalSearch.h
//
// PURPOSE : AIGoalSearch class definition
//
// CREATED : 1/11/02
//
// (c) 2002 Monolith Productions, Inc. All Rights Reserved
// ----------------------------------------------------------------------- //
#ifndef __AIGOAL_SEARCH_H__
#define __AIGOAL_SEARCH_H__
#include "AIGoalAbstractSearch.h"
#include "AISenseRecorderAbstract.h"
class CAIGoalSearch : public CAIGoalAbstractSearch
{
typedef CAIGoalAbstractSearch super;
public:
DECLARE_AI_FACTORY_CLASS_SPECIFIC(Goal, CAIGoalSearch, kGoal_Search);
CAIGoalSearch( );
// Save / Load
virtual void Save(ILTMessage_Write *pMsg);
virtual void Load(ILTMessage_Read *pMsg);
// Activation.
virtual void ActivateGoal();
// Updating.
void UpdateGoal();
// Command Handling.
virtual LTBOOL HandleNameValuePair(const char *szName, const char *szValue);
protected:
// State Setting.
virtual void SetStateSearch();
};
#endif
| [
"[email protected]"
] | [
[
[
1,
54
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.