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
351614b100d056d79337a56232ec3489e85986c5
508bfb3220be28811600a2cbf0aabae382f78775
/AcademicCrawler-sdk/Qt/Qt-4.6.2/include/Qt/qaudioformat.h
00a8a964ca0bafd20cd8c9ef2a2a03eeeb1cc7d8
[]
no_license
darkbtf/academic-crawler
295f3bd74b18e700402bc2be59f15694d6195471
5dfcb0f1b88b93aa7545ef233344a41570011532
refs/heads/master
2021-01-01T19:21:00.162442
2011-03-10T16:29:25
2011-03-10T16:29:25
42,468,175
0
0
null
null
null
null
UTF-8
C++
false
false
3,363
h
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtMultimedia module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QAUDIOFORMAT_H #define QAUDIOFORMAT_H #include <QtCore/qobject.h> #include <QtCore/qglobal.h> #include <QtCore/qshareddata.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Multimedia) class QAudioFormatPrivate; class Q_MULTIMEDIA_EXPORT QAudioFormat { public: enum SampleType { Unknown, SignedInt, UnSignedInt, Float }; enum Endian { BigEndian = QSysInfo::BigEndian, LittleEndian = QSysInfo::LittleEndian }; QAudioFormat(); QAudioFormat(const QAudioFormat &other); ~QAudioFormat(); QAudioFormat& operator=(const QAudioFormat &other); bool operator==(const QAudioFormat &other) const; bool operator!=(const QAudioFormat &other) const; bool isValid() const; void setFrequency(int frequency); int frequency() const; void setChannels(int channels); int channels() const; void setSampleSize(int sampleSize); int sampleSize() const; void setCodec(const QString &codec); QString codec() const; void setByteOrder(QAudioFormat::Endian byteOrder); QAudioFormat::Endian byteOrder() const; void setSampleType(QAudioFormat::SampleType sampleType); QAudioFormat::SampleType sampleType() const; private: QSharedDataPointer<QAudioFormatPrivate> d; }; QT_END_NAMESPACE QT_END_HEADER #endif // QAUDIOFORMAT_H
[ "ulmonkey1987@7c5ce3f8-edad-37de-be84-b98c484540b5" ]
[ [ [ 1, 103 ] ] ]
5ba93286253401083ed1914c358d863180898ba0
55196303f36aa20da255031a8f115b6af83e7d11
/private/external/gameswf/base/tu_timer.h
819efe8a4740c8a228a77478cb75f0215b2cd717
[]
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
2,340
h
// tu_timer.h -- by Thatcher Ulrich <[email protected]> // This source code has been donated to the Public Domain. Do // whatever you want with it. // Utility/profiling timer. #ifndef TU_TIMER_H #define TU_TIMER_H #include "base/tu_types.h" namespace tu_timer { // General-purpose wall-clock timer. May not be hi-res enough // for profiling. exported_module uint64 get_ticks(); exported_module double ticks_to_seconds(uint64 ticks); // current ticks to seconds exported_module double ticks_to_seconds(); // Sleep the current thread for the given number of // milliseconds. Don't rely on the sleep period being very // accurate. exported_module void sleep(int milliseconds); // Hi-res timer for CPU profiling. // Return a hi-res timer value. Time 0 is arbitrary, so // generally you want to call this at the start and end of an // operation, and pass the difference to // profile_ticks_to_seconds() to find out how long the // operation took. exported_module uint64 get_profile_ticks(); // Convert a hi-res ticks value into seconds. exported_module double profile_ticks_to_seconds(uint64 profile_ticks); exported_module double profile_ticks_to_milliseconds(uint64 ticks); // Returns the systime exported_module Uint64 get_systime(); // Returns the day of the month (an integer from 1 to 31) int get_date(Uint64 t); // Returns the day of the week (0 for Sunday, 1 for Monday, and so on) int get_day(Uint64 t); // Returns the hour (an integer from 0 to 23) int get_hours(Uint64 t); // Returns the full year (a four-digit number, such as 2000) int get_fullyear(Uint64 t); // Returns the year - 1900 int get_year(Uint64 t); // Returns the milliseconds (an integer from 0 to 999) int get_milli(Uint64 t); // Returns the month (0 for January, 1 for February, and so on) int get_month(Uint64 t); // Returns the minutes (an integer from 0 to 59) int get_minutes(Uint64 t); // Returns the seconds (an integer from 0 to 59) int get_seconds(Uint64 t); // Returns the number of milliseconds since midnight January 1, 1970, universal time Uint64 get_time(Uint64 t); }; #endif // TU_TIMER_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, 88 ] ] ]
4dd95b36bc99714ccbad143cd9ab868cce7ff2e5
5e6ff9e6e8427078135a7b4d3b194bcbf631e9cd
/ClientApps/MarketSimClient/Apps/Math Utility/Math Utility/Math Utility.h
e1e23779fb22246b30b750cde867176f43273b47
[]
no_license
karakots/dpresurrection
1a6f3fca00edd24455f1c8ae50764142bb4106e7
46725077006571cec1511f31d314ccd7f5a5eeef
refs/heads/master
2016-09-05T09:26:26.091623
2010-02-01T11:24:41
2010-02-01T11:24:41
32,189,181
0
0
null
null
null
null
UTF-8
C++
false
false
2,496
h
// Math Utility.h #pragma once #using <mscorlib.dll> using namespace System; using namespace System::Collections::Generic; namespace MathUtility { public ref class Solver { public: delegate double Saturation(double persuasion, int numDerives); static double tol = 0.00001; static int max_iter = 100; static List<double>^ Solve(List< List<double>^ >^ S, List< List<double>^ >^ R, List<double>^ W, List< List< List<double>^ >^ >^ A); static List<double>^ Solve_Sequential(List< List<double>^ >^ S, List< List<double>^ >^ R, List<double>^ W, List< List< List<double>^ >^ >^ A); static List<double>^ SolveWithSaturation(Saturation^ fcn, List<List<double>^ >^ S, List< List<double>^ >^ R, List<double>^ W, List<List<double>^>^ totalVal, List< List< List<double>^ >^ >^ A); private: static List< List<double>^ >^ UpdateShare(List< List<double>^ >^ S, List< List< List<double>^ >^ >^ A, int i, double d_pref); static List< List<double>^ >^ UpdateShare(List< List<double>^ >^ S, List< List< List<double>^ >^ >^ A, List< double >^ DP); static double Evaluate(List< List<double>^ >^ S, List< List<double>^ >^ R, List<double>^ W, List< List< List<double>^ >^ >^ A, int i, double d_pref); static double Derivative( List< List<double>^ >^ S, List< List<double>^ >^ R, List<double>^ W, List< List< List<double>^ >^ >^ A, int i, double pref); static List<double>^ Evaluate(List< List<double>^ >^ S, List< List<double>^ >^ R, List<double>^ W, List< List< List<double>^ >^ >^ A); static List< List<double>^ >^ Jacobian(List< List<double>^ >^ S, List< List<double>^ >^ R, List<double>^ W, List< List< List<double>^ >^ >^ A); static double Sum_of_Squares(List<double>^ F); static List<double>^ Vector_Multiply(List<double>^ V, double a); static List<double>^ Vector_Add(List<double>^ V1, List<double>^ V2); static List<double>^ Gradient(List<double>^ F, List< List<double>^ >^ J); static double AttributeSqrNorm(List<double>^ W, List< List< List<double>^ >^ >^ A); static List< List<double>^ >^ JacobianWithSaturation(Saturation^ fcn, List< List<double>^ >^ S, List< List<double>^ >^ R, List<double>^ W, List< List<double>^ >^ totalVal, List< List< List<double>^ >^ >^ A); static List< List< double >^ >^ UpdateShareWithSaturation(Saturation^ fcn, List< List< double >^ >^ S, List< List<double>^ >^ totalVal, List< List< List< double >^ >^ >^ A, List< double >^ DP); }; }
[ "Isaac.Noble@fd82578e-0ebe-11df-96d9-85c6b80b8d9c" ]
[ [ [ 1, 57 ] ] ]
b82a47bfed31971f88254685a650aea481e10645
b414a8f5b425617f897b5d97bbede96507e17d96
/agdevku/src/utils/util.h
08c9a07f2d0fe7ce4f96bfd48cc7e89c38d2d2b5
[]
no_license
agenthunt/agdevku
e7ce02e6f936a6980839fc538f158160c2060d05
c6f6c8e9fbbb71f2b0288b8ab3ebd001aac6d5d7
refs/heads/master
2016-08-02T23:22:21.985871
2010-01-24T01:00:36
2010-01-24T01:00:36
32,114,047
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
h
/* * util.h * * Created on: Oct 8, 2009 * Author: shailesh */ #ifndef UTIL_H_ #define UTIL_H_ #include <iostream> using std::string; #include <sstream> #include <vector> using namespace std; class Util{ public: static vector<string> split(string str, string splitter) { vector<string> res; for (unsigned int i = 0; i < str.length();) { int pos = str.find(splitter, i); res.push_back(str.substr(i, pos - i)); //cout << "i,pos=" << i << "," << pos << endl; //cout << str.substr(i, pos - i) << endl; i = pos + splitter.length(); if (pos < 0) { break; } } return res; } static int string_to_int(std::string var){ int res = 0; istringstream mystream(var); mystream >> res; return res; } static string int_to_string(int var){ ostringstream mystream; mystream<<var; return mystream.str(); } static string char_to_string(char *var){ string res(var); return res; } }; #endif /* UTIL_H_ */
[ "[email protected]@1dbec2b6-b029-11de-8bdf-3374eb5c7316" ]
[ [ [ 1, 58 ] ] ]
007594004583430e7db51eae12094fa9f20ca3c6
716208a4d023bb185868991735d14cd53747fc12
/jobbie/src/cpp/InternetExplorerDriver/IEThreadExplorer.cpp
dc934040a0194c57f5a57e29cbc461f5b567be97
[]
no_license
JLLeitschuh/webdriver
e7447c1c10e01577644dbcd2ffafc2beb8164f2c
95c904083736adc45e5356b1b2f470272b123e86
refs/heads/master
2021-01-02T21:10:03.580526
2008-10-14T10:35:46
2008-10-14T10:35:46
239,802,416
0
0
null
2020-11-17T19:25:54
2020-02-11T15:55:22
null
UTF-8
C++
false
false
11,084
cpp
// IEThread.cpp : implementation file // #include "stdafx.h" #include <comdef.h> #include "IEThread.h" #include "utils.h" #include "InternalCustomMessage.h" extern wchar_t* XPATHJS[]; using namespace std; void IeThread::OnGetVisible(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) VARIANT_BOOL visible; pBody->ieThreaded->get_Visible(&visible); data.output_bool_ = (visible == VARIANT_TRUE); } void IeThread::OnSetVisible(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) const long& isVisible = data.input_long_; if (isVisible) pBody->ieThreaded->put_Visible(VARIANT_TRUE); else pBody->ieThreaded->put_Visible(VARIANT_FALSE); } void IeThread::OnGetCurrentUrl(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) std::wstring& ret = data.output_string_; CComPtr<IHTMLDocument2> doc; getDocument(&doc); if (!doc) { ret = L""; return; } CComBSTR url; doc->get_URL(&url); ret = combstr2cw(url); } void IeThread::OnGetUrl(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) const wchar_t* url = data.input_string_; CComVariant spec(url); CComVariant dummy; tryTransferEventReleaserToNotifyNavigCompleted(&SC); HRESULT hr = pBody->ieThreaded->Navigate2(&spec, &dummy, &dummy, &dummy, &dummy); pBody->pathToFrame = L""; try{ if(FAILED(hr)) { _com_issue_error( hr ); }} catch (_com_error &e) { cerr << "COM Error" << " J[" << hex << GetCurrentThreadId() << "]" << endl; cerr << "Message = " << e.ErrorMessage() << endl; if ( e.ErrorInfo() ) cerr << e.Description() << endl; tryTransferEventReleaserToNotifyNavigCompleted(&SC, false); } // In the nominal case, the next part of the code to be traversed is: // IeSink::DocumentComplete() // then IeThread::waitForNavigateToFinish() } void IeThread::OnGetTitle(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) getTitle(data.output_string_); } void IeThread::getTitle(std::wstring& res) { CComPtr<IHTMLDocument2> doc; getDocument(&doc); CComBSTR title; doc->get_title(&title); res = combstr2cw(title); } void IeThread::OnGoForward(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) tryTransferEventReleaserToNotifyNavigCompleted(&SC); HRESULT hr = pBody->ieThreaded->GoForward(); if (!SUCCEEDED(hr)) { tryTransferEventReleaserToNotifyNavigCompleted(&SC, false); } } void IeThread::OnGoBack(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) tryTransferEventReleaserToNotifyNavigCompleted(&SC); HRESULT hr = pBody->ieThreaded->GoBack(); if (!SUCCEEDED(hr)) { tryTransferEventReleaserToNotifyNavigCompleted(&SC, false); } } void IeThread::OnGetActiveElement(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) IHTMLElement* &pDom = data.output_html_element_; pDom = NULL; CComPtr<IHTMLDocument2> doc; getDocument(&doc); if (!doc) { return; } CComPtr<IHTMLElement> element; doc->get_activeElement(&element); if (!element) { // Grab the body instead doc->get_body(&element); } if (element) element.CopyTo(&pDom); } void IeThread::OnGetCookies(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) std::wstring& ret = data.output_string_; CComPtr<IHTMLDocument2> doc; getDocument(&doc); if (!doc) { ret = L""; return; } CComBSTR cookie; doc->get_cookie(&cookie); ret = combstr2cw(cookie); } void IeThread::OnAddCookie(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) CComBSTR cookie(data.input_string_); CComPtr<IHTMLDocument2> doc; getDocument(&doc); doc->put_cookie(cookie); } void IeThread::OnWaitForNavigationToFinish(WPARAM w, LPARAM lp) { SCOPETRACER waitForNavigateToFinish(); } void IeThread::OnExecuteScript(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) // TODO/MAYBE // the input WebElement(s) may need to have their IHTMLElement QI-converted into IHTMLDOMNode executeScript(data.input_string_, data.input_safe_array_, &(data.output_variant_)); if( VT_DISPATCH == data.output_variant_.vt ) { CComQIPtr<IHTMLElement> element(data.output_variant_.pdispVal); if(element) { IHTMLElement* &pDom = * (IHTMLElement**) &(data.output_variant_.pdispVal); element.CopyTo(&pDom); } } } void IeThread::OnSelectElementByXPath(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) long &errorKind = data.output_long_; IHTMLElement* &pDom = data.output_html_element_; CComPtr<IHTMLElement> inputElement(data.input_html_element_); pDom = NULL; errorKind = 0; const bool inputElementWasNull = (!inputElement); /// Start from root DOM by default if(inputElementWasNull) { CComPtr<IHTMLDocument3> root_doc; getDocument3(&root_doc); if (!root_doc) { errorKind = 1; return; } root_doc->get_documentElement(&inputElement); } CComQIPtr<IHTMLDOMNode> node(inputElement); if (!node) { errorKind = 1; return; } //////////////////////////////////////////////////// bool evalToDocument = addEvaluateToDocument(node, 0); if (!evalToDocument) { errorKind = 2; return; } std::wstring expr; if (!inputElementWasNull) expr += L"(function() { return function() {var res = document.__webdriver_evaluate(arguments[0], arguments[1], null, 7, null); return res.snapshotItem(0);};})();"; else expr += L"(function() { return function() {var res = document.__webdriver_evaluate(arguments[0], document, null, 7, null); return res.snapshotItem(0);};})();"; CComVariant result; CComBSTR expression = CComBSTR(data.input_string_); SAFEARRAY* args = NULL; if (!inputElementWasNull) { args = SafeArrayCreateVector(VT_VARIANT, 0, 2); long index = 1; CComVariant dest2; CComQIPtr<IHTMLElement> element(const_cast<IHTMLDOMNode*>((IHTMLDOMNode*)node)); dest2.vt = VT_DISPATCH; dest2.pdispVal = element; SafeArrayPutElement(args, &index, &dest2); } else { args = SafeArrayCreateVector(VT_VARIANT, 0, 2); } long index = 0; CComVariant dest; dest.vt = VT_BSTR; dest.bstrVal = expression; SafeArrayPutElement(args, &index, &dest); executeScript(expr.c_str(), args, &result); if (result.vt == VT_DISPATCH) { CComQIPtr<IHTMLElement> e(result.pdispVal); if (e && isOrUnder(node, e)) { e.CopyTo(&pDom); return; } } } void IeThread::OnSelectElementsByXPath(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) CComPtr<IHTMLElement> inputElement(data.input_html_element_); long &errorKind = data.output_long_; std::vector<IHTMLElement*> &allElems = data.output_list_html_element_; errorKind = 0; const bool inputElementWasNull = (!inputElement); /// Start from root DOM by default if(inputElementWasNull) { CComPtr<IHTMLDocument3> root_doc; getDocument3(&root_doc); if (!root_doc) { errorKind = 1; return; } root_doc->get_documentElement(&inputElement); } CComQIPtr<IHTMLDOMNode> node(inputElement); if (!node) { errorKind = 1; return; } //////////////////////////////////////////////////// bool evalToDocument = addEvaluateToDocument(node, 0); if (!evalToDocument) { errorKind = 2; return; } std::wstring expr; if (!inputElementWasNull) expr += L"(function() { return function() {var res = document.__webdriver_evaluate(arguments[0], arguments[1], null, 7, null); return res;};})();"; else expr += L"(function() { return function() {var res = document.__webdriver_evaluate(arguments[0], document, null, 7, null); return res;};})();"; CComVariant result; CComBSTR expression = CComBSTR(data.input_string_); SAFEARRAY* args = SafeArrayCreateVector(VT_VARIANT, 0, 2); long index = 1; CComVariant dest2; CComQIPtr<IHTMLElement> element(const_cast<IHTMLDOMNode*>((IHTMLDOMNode*)node)); dest2.vt = VT_DISPATCH; dest2.pdispVal = element; SafeArrayPutElement(args, &index, &dest2); index = 0; CComVariant dest; dest.vt = VT_BSTR; dest.bstrVal = expression; SafeArrayPutElement(args, &index, &dest); executeScript(expr.c_str(), args, &result); // At this point, the result should contain a JS array of nodes. if (result.vt != VT_DISPATCH) { errorKind = 3; return; } CComPtr<IHTMLDocument2> doc; getDocument2(node, &doc); CComPtr<IDispatch> scriptEngine; doc->get_Script(&scriptEngine); CComPtr<IDispatch> jsArray = result.pdispVal; DISPID shiftId; OLECHAR FAR* szMember = L"iterateNext"; result.pdispVal->GetIDsOfNames(IID_NULL, &szMember, 1, LOCALE_USER_DEFAULT, &shiftId); DISPID lengthId; szMember = L"snapshotLength"; result.pdispVal->GetIDsOfNames(IID_NULL, &szMember, 1, LOCALE_USER_DEFAULT, &lengthId); DISPPARAMS parameters = {0}; parameters.cArgs = 0; EXCEPINFO exception; CComVariant lengthResult; result.pdispVal->Invoke(lengthId, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &parameters, &lengthResult, &exception, 0); long length = lengthResult.lVal; for (int i = 0; i < length; i++) { CComVariant shiftResult; result.pdispVal->Invoke(shiftId, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &parameters, &shiftResult, &exception, 0); if (shiftResult.vt == VT_DISPATCH) { CComQIPtr<IHTMLElement> elem(shiftResult.pdispVal); IHTMLElement *pDom = NULL; elem.CopyTo(&pDom); allElems.push_back(pDom); } } } void IeThread::getDocument3(const IHTMLDOMNode* extractFrom, IHTMLDocument3** pdoc) { if (!extractFrom) { getDocument3(pdoc); return; } CComQIPtr<IHTMLDOMNode2> element(const_cast<IHTMLDOMNode*>(extractFrom)); CComPtr<IDispatch> dispatch; element->get_ownerDocument(&dispatch); CComQIPtr<IHTMLDocument3> doc(dispatch); *pdoc = doc.Detach(); } void IeThread::getDocument2(const IHTMLDOMNode* extractFrom, IHTMLDocument2** pdoc) { if (!extractFrom) { getDocument(pdoc); return; } CComQIPtr<IHTMLDOMNode2> element(const_cast<IHTMLDOMNode*>(extractFrom)); CComPtr<IDispatch> dispatch; element->get_ownerDocument(&dispatch); CComQIPtr<IHTMLDocument2> doc(dispatch); *pdoc = doc.Detach(); } bool IeThread::isOrUnder(const IHTMLDOMNode* root, IHTMLElement* child) { CComQIPtr<IHTMLElement> parent(const_cast<IHTMLDOMNode*>(root)); VARIANT_BOOL toReturn; parent->contains(child, &toReturn); return toReturn == VARIANT_TRUE; } void IeThread::OnQuitIE(WPARAM w, LPARAM lp) { SCOPETRACER pBody->ieThreaded->Stop(); pBody->ieThreaded->Quit(); pBody->ieThreaded.Release(); } void IeThread::OnSwitchToFrame(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_COMMON(data) data.output_bool_ = true; LPCWSTR destFrame = data.input_string_; pBody->pathToFrame = destFrame; CComPtr<IHTMLDocument2> doc; getDocument(&doc); if (!doc) pBody->pathToFrame = L""; data.output_bool_ = (doc != NULL); }
[ [ [ 1, 478 ] ] ]
1f28cbf0fa55da2b61ab567b4bc41eac00a9fbb3
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/terralib/drivers/qt/TeQtCheckListItem.cpp
bb4dc541ad96152c58f471f0e3da455585b7deae
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,641
cpp
/************************************************************************************ TerraView - visualization and exploration of geographical databases using TerraLib. Copyright � 2001-2007 INPE and Tecgraf/PUC-Rio. This file is part of TerraView. TerraView 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. You should have received a copy of the GNU General Public License along with TerraView. The authors reassure the license terms regarding the warranties. They specifically disclaim any warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The software provided hereunder is on an "as is" basis, and the authors have no obligation to provide maintenance, support, updates, enhancements, or modifications. In no event shall INPE and Tecgraf / PUC-Rio be held liable to any party for direct, indirect, special, incidental, or consequential damages arising out of the use of this program and its documentation. *************************************************************************************/ #include <TeQtCheckListItem.h> #include <TeUtils.h> #include <vector> #include <cstdlib> int TeQtCheckListItem::compare (QListViewItem *i, int col, bool ascending) const { int order1 = atoi(key(col, ascending).latin1()); int order2 = atoi(i->key(col, ascending).latin1()); if (order1 < order2) return -1; else if (order1 == order2) return 0; else return 1; } QString TeQtCheckListItem::key ( int /* col */, bool /* ascending */ ) const { return Te2String(order_).c_str(); } vector<QListViewItem*> TeQtCheckListItem::getChildren() { vector<QListViewItem*> childrenVector; QListViewItem *child = firstChild(); while (child) { childrenVector.push_back(child); child = child->nextSibling(); } return childrenVector; } void TeQtCheckListItem::unselectChildren() { TeQtCheckListItem *item; int n = childCount(); int i = 0; if (n == 0) return; QListViewItemIterator it(this); ++it; item = (TeQtCheckListItem*)(it.current()); while(item) { if (item->parent() == this) { item->setSelected(false); item->repaint(); ++i; } if (i == n) break; ++it; item = (TeQtCheckListItem*)(it.current()); } } bool TeQtCheckListItem::isChild(QListViewItem *item) { if (item->parent() == this) return true; else return false; }
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 97 ] ] ]
29434e4e017fec26fb4069be6f9ccb4cdaa5fc57
20c74d83255427dd548def97f9a42112c1b9249a
/src/libsrc/game/stagemanager.cpp
89d45564b66b07525939f26d163b46605fbb5c48
[]
no_license
jonyzp/roadfighter
70f5c7ff6b633243c4ac73085685595189617650
d02cbcdcfda1555df836379487953ae6206c0703
refs/heads/master
2016-08-10T15:39:09.671015
2011-05-05T12:00:34
2011-05-05T12:00:34
54,320,171
0
0
null
null
null
null
UTF-8
C++
false
false
397
cpp
#include "stagemanager.h" StageManager::StageManager() { loaded = no; currentID = 0; } StageManager::~StageManager() { } void StageManager::setLoaded(Logical yesno) { loaded = yesno; } Logical StageManager::isLoaded() { return loaded; } void StageManager::setCurrentID(int id) { currentID = id; } int StageManager::getCurrentID() { return currentID; }
[ [ [ 1, 32 ] ] ]
7a57fce2489dca6037bef57acdfc1a4ccb3bf4d6
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-realmserver/QueryHandler.cpp
ddffc8125946d0f336dbb357476d0d21309a90da
[]
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,604
cpp
/* * ArcEmu MMORPG Server * 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/>. * */ #include "RStdAfx.h" void Session::HandleCreatureQueryOpcode(WorldPacket & pck) { WorldPacket data(SMSG_CREATURE_QUERY_RESPONSE, 150); CreatureInfo * ci; uint32 entry; pck >> entry; if(entry == 300000) { data << (uint32)entry; data << "WayPoint"; data << uint8(0) << uint8(0) << uint8(0); data << "Level is WayPoint ID"; for(uint32 i = 0; i < 8;i++) { data << uint32(0); } data << uint8(0); } else { ci = CreatureNameStorage.LookupEntry(entry); if(ci == NULL) return; Log.Debug("World", "CMSG_CREATURE_QUERY '%s'", ci->Name); data << (uint32)entry; data << ci->Name; data << uint8(0) << uint8(0) << uint8(0); data << ci->SubName; data << ci->Flags1; data << ci->Type; data << ci->Family; data << ci->Rank; data << ci->Unknown1; data << ci->SpellDataID; data << ci->DisplayID; data << ci->unk2; data << ci->unk3; data << ci->Civilian; data << ci->Leader; } SendPacket( &data ); } void Session::HandleGameObjectQueryOpcode(WorldPacket & pck) { WorldPacket data(SMSG_GAMEOBJECT_QUERY_RESPONSE, 300); uint32 entryID; GameObjectInfo *goinfo; pck >> entryID; Log.Debug("World", "CMSG_GAMEOBJECT_QUERY '%u'", entryID); goinfo = GameObjectNameStorage.LookupEntry(entryID); if(goinfo == 0) return; data << entryID; data << goinfo->Type; data << goinfo->DisplayID; data << goinfo->Name; data << uint8(0) << uint8(0) << uint8(0) << uint8(0) << uint8(0) << uint8(0); // new string in 1.12 data << goinfo->SpellFocus; data << goinfo->sound1; data << goinfo->sound2; data << goinfo->sound3; data << goinfo->sound4; data << goinfo->sound5; data << goinfo->sound6; data << goinfo->sound7; data << goinfo->sound8; data << goinfo->sound9; data << goinfo->Unknown1; data << goinfo->Unknown2; data << goinfo->Unknown3; data << goinfo->Unknown4; data << goinfo->Unknown5; data << goinfo->Unknown6; data << goinfo->Unknown7; data << goinfo->Unknown8; data << goinfo->Unknown9; data << goinfo->Unknown10; data << goinfo->Unknown11; data << goinfo->Unknown12; data << goinfo->Unknown13; data << goinfo->Unknown14; SendPacket( &data ); } void Session::HandleItemQuerySingleOpcode(WorldPacket & pck) { int i; uint32 itemid; pck >> itemid; Log.Debug("World", "CMSG_ITEM_QUERY_SINGLE for item id %d", itemid ); ItemPrototype *itemProto = ItemPrototypeStorage.LookupEntry(itemid); if(!itemProto) { return; } WorldPacket data(SMSG_ITEM_QUERY_SINGLE_RESPONSE, 600 + strlen(itemProto->Name1) + strlen(itemProto->Description) ); data << itemProto->ItemId; data << itemProto->Class; data << itemProto->SubClass; data << itemProto->unknown_bc; data << itemProto->Name1; /*data << itemProto->Name2; data << itemProto->Name3; data << itemProto->Name4;*/ data << uint8(0) << uint8(0) << uint8(0); // name 2,3,4 data << itemProto->DisplayInfoID; data << itemProto->Quality; data << itemProto->Flags; data << itemProto->BuyPrice; data << itemProto->SellPrice; data << itemProto->InventoryType; data << itemProto->AllowableClass; data << itemProto->AllowableRace; data << itemProto->ItemLevel; data << itemProto->RequiredLevel; data << itemProto->RequiredSkill; data << itemProto->RequiredSkillRank; data << itemProto->RequiredSkillSubRank; data << itemProto->RequiredPlayerRank1; data << itemProto->RequiredPlayerRank2; data << itemProto->RequiredFaction; data << itemProto->RequiredFactionStanding; data << itemProto->Unique; data << itemProto->MaxCount; data << itemProto->ContainerSlots; for(i = 0; i < 10; i++) { data << itemProto->Stats[i].Type; data << itemProto->Stats[i].Value; } for(i = 0; i < 5; i++) { data << itemProto->Damage[i].Min; data << itemProto->Damage[i].Max; data << itemProto->Damage[i].Type; } data << itemProto->Armor; data << itemProto->HolyRes; data << itemProto->FireRes; data << itemProto->NatureRes; data << itemProto->FrostRes; data << itemProto->ShadowRes; data << itemProto->ArcaneRes; data << itemProto->Delay; data << itemProto->AmmoType; data << itemProto->Range; for(i = 0; i < 5; i++) { data << itemProto->Spells[i].Id; data << itemProto->Spells[i].Trigger; data << itemProto->Spells[i].Charges; data << itemProto->Spells[i].Cooldown; data << itemProto->Spells[i].Category; data << itemProto->Spells[i].CategoryCooldown; } data << itemProto->Bonding; data << itemProto->Description; data << itemProto->PageId; data << itemProto->PageLanguage; data << itemProto->PageMaterial; data << itemProto->QuestId; data << itemProto->LockId; data << itemProto->LockMaterial; data << itemProto->Field108; data << itemProto->RandomPropId; data << itemProto->RandomSuffixId; data << itemProto->Block; data << itemProto->ItemSet; data << itemProto->MaxDurability; data << itemProto->ZoneNameID; data << itemProto->MapID; data << itemProto->BagFamily; data << itemProto->ToolCategory; data << itemProto->Sockets[0].SocketColor ; data << itemProto->Sockets[0].Unk; data << itemProto->Sockets[1].SocketColor ; data << itemProto->Sockets[1].Unk ; data << itemProto->Sockets[2].SocketColor ; data << itemProto->Sockets[2].Unk ; /* data << itemProto->SocketColor1; data << itemProto->Unk201_3; data << itemProto->SocketColor2; data << itemProto->Unk201_5; data << itemProto->SocketColor3; data << itemProto->Unk201_7;*/ data << itemProto->SocketBonus; data << itemProto->GemProperties; data << itemProto->ItemExtendedCost; data << itemProto->DisenchantReqSkill; data << itemProto->ArmorDamageModifier; //WPAssert(data.size() == 453 + itemProto->Name1.length() + itemProto->Description.length()); SendPacket( &data ); }
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 1 ], [ 4, 226 ] ], [ [ 2, 3 ] ] ]
81f98d0c69d80ce64e1d5ff690cb113c06969e41
2dc9ed7fc09dae24600edc4fa4c949f6eba3e339
/trunk/include/pyasynchio/apoll.hpp
3d8540b70aafed2ea3a2b8a146a4e12676f75c6e
[ "MIT" ]
permissive
BackupTheBerlios/pyasynchio-svn
e7f9e5043c828740599113f622fac17a6522fb4b
691051d6a6f6261e66263785f0ec2f1a30b854eb
refs/heads/master
2016-09-07T19:04:33.800780
2005-09-15T16:53:47
2005-09-15T16:53:47
40,805,133
0
0
null
null
null
null
UTF-8
C++
false
false
3,660
hpp
/* Copyright (c) 2005 Vladimir Sukhoy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef PYASYNCHIO_APOLL_HPP_INCLUDED_ #define PYASYNCHIO_APOLL_HPP_INCLUDED_ #pragma once #include <pyasynchio/config.hpp> #include <python.h> #include "socketmodule.h" #include "fileobject.h" #include <map> namespace pyasynchio { extern ::PyTypeObject apoll_Type; class apoll : public ::PyObject, public platform::apoll_impl { public: apoll(::PyObject *args, ::PyObject *kwargs); ~apoll(); bool accept(::PySocketSockObject *listen_socket , ::PySocketSockObject *accept_socket , ::PyObject *lsock_ref_obj , ::PyObject *asock_ref_obj , ::PyObject *act); bool connect(::PySocketSockObject *so, ::PyObject *so_ref , ::PyObject *addro, ::PyObject *acto); bool send(::PySocketSockObject *so, ::PyObject *so_ref , ::PyObject *datao, unsigned long flags , ::PyObject *acto); bool sendto(::PySocketSockObject *so, ::PyObject *so_ref , ::PyObject *addro , ::PyObject *datao , unsigned long flags , ::PyObject *acto); bool recv(::PySocketSockObject *so, ::PyObject *so_ref , unsigned long bufsize , unsigned long flags , ::PyObject *acto); bool recvfrom(::PySocketSockObject *so, ::PyObject *so_ref , unsigned long bufsize , unsigned long flags , ::PyObject *acto); bool cancel(::PyObject *o); bool read(::PyFileObject *fo, unsigned long long offset, unsigned long size , ::PyObject *acto); bool write(::PyFileObject *fo, unsigned long long offset , ::PyObject *datao , ::PyObject *acto); ::PyObject* poll(long ms); static int init(PyObject *self, PyObject *args, PyObject *kwds); static void dealloc(apoll *self); static ::PyObject * accept_meth(apoll *self, ::PyObject *args); static ::PyObject * connect_meth(apoll *self, ::PyObject *args); static ::PyObject * send_meth(apoll *self, ::PyObject *args); static ::PyObject * sendto_meth(apoll *self, ::PyObject *args); static ::PyObject * recv_meth(apoll *self, ::PyObject *args); static ::PyObject * recvfrom_meth(apoll *self, ::PyObject *args); static ::PyObject * poll_meth(apoll *self, ::PyObject *args); static ::PyObject * cancel_meth(apoll *self, ::PyObject *args); static ::PyObject * read_meth(apoll *self, ::PyObject *args); static ::PyObject * write_meth(apoll *self, ::PyObject *args); }; } // namespace pyasynchio #endif // PYASYNCHIO_APOLL_HPP_INCLUDED_
[ "randolphu@1b988373-acfa-0310-9a85-c19025f466bc" ]
[ [ [ 1, 96 ] ] ]
f8b93a05b5293d1dc88a5f5214a4706f2513a727
bd89d3607e32d7ebb8898f5e2d3445d524010850
/adaptationlayer/dataport/dataport_csy/src/dptermdetect.cpp
f22204af1bd16879c74ed1ee71c12ca58fa9dfd4
[]
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
3,866
cpp
/* * Copyright (c) 2007-2008 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 "dpdef.h" // dataport definitions #include "dpdataport.h" // dataport main and c32 interface #include "dptermdetect.h" // terminator bytes detection #include "dpstd.h" // fault codes etc. #include "dpdataconfig.h" // configuration store #include "dplog.h" // dataport logging #include "OstTraceDefinitions.h" #ifdef OST_TRACE_COMPILER_IN_USE #include "dptermdetectTraces.h" #endif // EXTERNAL DATA STRUCTURES // none // EXTERNAL FUNCTION PROTOTYPES // none // CONSTANTS // none // MACROS // none // LOCAL CONSTANTS AND MACROS // none // MODULE DATA STRUCTURES // none // LOCAL FUNCTION PROTOTYPES // none // FORWARD DECLARATIONS // none // ============================= LOCAL FUNCTIONS =============================== // none // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CDpTermDetect::CDpTermDetect // C++ default constructor can NOT contain any code, that // might leave. // ----------------------------------------------------------------------------- // CDpTermDetect::CDpTermDetect( CDpDataConfig& aDataConfig ) : iDataConfig( aDataConfig ) { OstTrace0( TRACE_NORMAL, CDPTERMDETECT_CDPTERMDETECT, "CDpTermDetect::CDpTermDetect" ); LOGM("CDpTermDetect::CDpTermDetect"); } // ----------------------------------------------------------------------------- // CDpTermDetect::~CDpTermDetect // Destructor // ----------------------------------------------------------------------------- // CDpTermDetect::~CDpTermDetect() { OstTrace0( TRACE_NORMAL, DUP1_CDPTERMDETECT_CDPTERMDETECT, "CDpTermDetect::~CDpTermDetect" ); LOGM("CDpTermDetect::~CDpTermDetect"); DEBUG( "CDpTermDetect::~CDpTermDetect" ) } // ----------------------------------------------------------------------------- // CDpTermDetect::Scan // This methods scans terminator characters from descriptor. // ----------------------------------------------------------------------------- // TInt CDpTermDetect::Scan( const TPtr8& aDes ) { OstTrace0( TRACE_NORMAL, CDPTERMDETECT_SCAN, "CDpTermDetect::Scan" ); LOGM("CDpTermDetect::Scan"); FDEBUG("CDpTermDetect::Scan %d", 0) TInt termCount( iDataConfig.TerminatorCount() ); TInt ret( KErrNotFound ); TBool isTerminator (EFalse ); // The C32 client has set terminator array's characters. // Client may change terminators during data receive. // --> we must ask it from DataConfig. // Terminator array's terminator characters are scanned sequentially. for ( TInt j( 0 ); j < termCount; j++ ) //termCount is max 4 { TBuf8<1> terminator; terminator.Append(iDataConfig.Terminator(j)); ret = aDes.Find( terminator ); if ( 0 <= ret ) { isTerminator = ETrue; break; } //no else } if ( !isTerminator ) { ret = KErrNotFound; } //no else return ret; } // ========================== OTHER EXPORTED FUNCTIONS ========================= // none // End of File
[ "dalarub@localhost", "[email protected]" ]
[ [ [ 1, 26 ], [ 28, 28 ], [ 30, 139 ] ], [ [ 27, 27 ], [ 29, 29 ] ] ]
5bd3299b48809770f8c97f493dadc0a119c28273
7aa4ce1caae2aa555ba8d82628eca81be2584767
/src/util.cpp
63ac9b57ac41b1fa0a8c92d3a92f852be17809c0
[]
no_license
shayak/obj2ogl
02aeb01f3294fb046dc4271f34712d6f600d0c6c
5f1f72a80be0ad63bb27246f9bca031c330ed529
refs/heads/master
2021-01-01T18:03:22.166462
2011-04-26T01:56:02
2011-04-26T01:56:02
1,662,344
0
0
null
null
null
null
UTF-8
C++
false
false
8,816
cpp
/*********************************************************** Starter code for Assignment 3, CSCD18F (Fall, 2008) This code was originally written by Jack Wang for CSC418, SPRING 2005 implementations of util.h ***********************************************************/ #include <cmath> #include "util.h" Point3D::Point3D() { m_data[0] = 0.0; m_data[1] = 0.0; m_data[2] = 0.0; } Point3D::Point3D(double x, double y, double z) { m_data[0] = x; m_data[1] = y; m_data[2] = z; } Point3D::Point3D(const Point3D& other) { m_data[0] = other.m_data[0]; m_data[1] = other.m_data[1]; m_data[2] = other.m_data[2]; } Point3D& Point3D::operator =(const Point3D& other) { m_data[0] = other.m_data[0]; m_data[1] = other.m_data[1]; m_data[2] = other.m_data[2]; return *this; } double& Point3D::operator[](int i) { return m_data[i]; } double Point3D::operator[](int i) const { return m_data[i]; } Vector3D::Vector3D() { m_data[0] = 0.0; m_data[1] = 0.0; m_data[2] = 0.0; } Vector3D::Vector3D(double x, double y, double z) { m_data[0] = x; m_data[1] = y; m_data[2] = z; } Vector3D::Vector3D(const Vector3D& other) { m_data[0] = other.m_data[0]; m_data[1] = other.m_data[1]; m_data[2] = other.m_data[2]; } Vector3D& Vector3D::operator =(const Vector3D& other) { m_data[0] = other.m_data[0]; m_data[1] = other.m_data[1]; m_data[2] = other.m_data[2]; return *this; } double& Vector3D::operator[](int i) { return m_data[i]; } double Vector3D::operator[](int i) const { return m_data[i]; } double Vector3D::length() const { return sqrt(dot(*this)); } double Vector3D::normalize() { double denom = 1.0; double x = (m_data[0] > 0.0) ? m_data[0] : -m_data[0]; double y = (m_data[1] > 0.0) ? m_data[1] : -m_data[1]; double z = (m_data[2] > 0.0) ? m_data[2] : -m_data[2]; if(x > y) { if(x > z) { if(1.0 + x > 1.0) { y = y / x; z = z / x; denom = 1.0 / (x * sqrt(1.0 + y*y + z*z)); } } else { /* z > x > y */ if(1.0 + z > 1.0) { y = y / z; x = x / z; denom = 1.0 / (z * sqrt(1.0 + y*y + x*x)); } } } else { if(y > z) { if(1.0 + y > 1.0) { z = z / y; x = x / y; denom = 1.0 / (y * sqrt(1.0 + z*z + x*x)); } } else { /* x < y < z */ if(1.0 + z > 1.0) { y = y / z; x = x / z; denom = 1.0 / (z * sqrt(1.0 + y*y + x*x)); } } } if(1.0 + x + y + z > 1.0) { m_data[0] *= denom; m_data[1] *= denom; m_data[2] *= denom; return 1.0 / denom; } return 0.0; } double Vector3D::dot(const Vector3D& other) const { return m_data[0]*other.m_data[0] + m_data[1]*other.m_data[1] + m_data[2]*other.m_data[2]; } Vector3D Vector3D::cross(const Vector3D& other) const { return Vector3D( m_data[1]*other[2] - m_data[2]*other[1], m_data[2]*other[0] - m_data[0]*other[2], m_data[0]*other[1] - m_data[1]*other[0]); } Vector3D operator *(double s, const Vector3D& v) { return Vector3D(s*v[0], s*v[1], s*v[2]); } Vector3D operator +(const Vector3D& u, const Vector3D& v) { return Vector3D(u[0]+v[0], u[1]+v[1], u[2]+v[2]); } Point3D operator +(const Point3D& u, const Vector3D& v) { return Point3D(u[0]+v[0], u[1]+v[1], u[2]+v[2]); } Vector3D operator -(const Point3D& u, const Point3D& v) { return Vector3D(u[0]-v[0], u[1]-v[1], u[2]-v[2]); } Vector3D operator -(const Vector3D& u, const Vector3D& v) { return Vector3D(u[0]-v[0], u[1]-v[1], u[2]-v[2]); } Vector3D operator -(const Vector3D& u) { return Vector3D(-u[0], -u[1], -u[2]); } Point3D operator -(const Point3D& u, const Vector3D& v) { return Point3D(u[0]-v[0], u[1]-v[1], u[2]-v[2]); } Vector3D cross(const Vector3D& u, const Vector3D& v) { return u.cross(v); } std::ostream& operator <<(std::ostream& s, const Point3D& p) { return s << "p(" << p[0] << "," << p[1] << "," << p[2] << ")"; } std::ostream& operator <<(std::ostream& s, const Vector3D& v) { return s << "v(" << v[0] << "," << v[1] << "," << v[2] << ")"; } Colour::Colour() { m_data[0] = 0.0; m_data[1] = 0.0; m_data[2] = 0.0; } Colour::Colour(double r, double g, double b) { m_data[0] = r; m_data[1] = g; m_data[2] = b; } Colour::Colour(const Colour& other) { m_data[0] = other.m_data[0]; m_data[1] = other.m_data[1]; m_data[2] = other.m_data[2]; } Colour& Colour::operator =(const Colour& other) { m_data[0] = other.m_data[0]; m_data[1] = other.m_data[1]; m_data[2] = other.m_data[2]; return *this; } Colour Colour::operator *(const Colour& other) { return Colour(m_data[0]*other.m_data[0], m_data[1]*other.m_data[1], m_data[2]*other.m_data[2]); } double& Colour::operator[](int i) { return m_data[i]; } double Colour::operator[](int i) const { return m_data[i]; } void Colour::clamp() { for (int i = 0; i < 3; i++) { if (m_data[i] > 1.0) m_data[i] = 1.0; if (m_data[i] < 0.0) m_data[i] = 0.0; } } Colour operator *(double s, const Colour& c) { return Colour(s*c[0], s*c[1], s*c[2]); } Colour operator +(const Colour& u, const Colour& v) { return Colour(u[0]+v[0], u[1]+v[1], u[2]+v[2]); } std::ostream& operator <<(std::ostream& s, const Colour& c) { return s << "c(" << c[0] << "," << c[1] << "," << c[2] << ")"; } Vector4D::Vector4D() { m_data[0] = 0.0; m_data[1] = 0.0; m_data[2] = 0.0; m_data[3] = 0.0; } Vector4D::Vector4D(double w, double x, double y, double z) { m_data[0] = w; m_data[1] = x; m_data[2] = y; m_data[3] = z; } Vector4D::Vector4D(const Vector4D& other) { m_data[0] = other.m_data[0]; m_data[1] = other.m_data[1]; m_data[2] = other.m_data[2]; m_data[3] = other.m_data[3]; } Vector4D& Vector4D::operator =(const Vector4D& other) { m_data[0] = other.m_data[0]; m_data[1] = other.m_data[1]; m_data[2] = other.m_data[2]; m_data[3] = other.m_data[3]; return *this; } double& Vector4D::operator[](int i) { return m_data[i]; } double Vector4D::operator[](int i) const { return m_data[i]; } Matrix4x4::Matrix4x4() { for (int i = 0; i < 16; i++) m_data[i] = 0.0; m_data[0] = 1.0; m_data[5] = 1.0; m_data[10] = 1.0; m_data[15] = 1.0; } Matrix4x4::Matrix4x4(const Matrix4x4& other) { for (int i = 0; i < 16; i++) m_data[i] = other.m_data[i]; } Matrix4x4& Matrix4x4::operator=(const Matrix4x4& other) { for (int i = 0; i < 16; i++) m_data[i] = other.m_data[i]; return *this; } Vector4D Matrix4x4::getRow(int row) const { return Vector4D(m_data[4*row], m_data[4*row+1], m_data[4*row+2], m_data[4*row+3]); } double* Matrix4x4::getRow(int row) { return (double*)m_data + 4*row; } Vector4D Matrix4x4::getColumn(int col) const { return Vector4D(m_data[col], m_data[4+col], m_data[8+col], m_data[12+col]); } Vector4D Matrix4x4::operator[](int row) const { return getRow(row); } double* Matrix4x4::operator[](int row) { return getRow(row); } Matrix4x4 Matrix4x4::transpose() const { Matrix4x4 M; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { M[i][j] = (*this)[j][i]; } } return M; } Matrix4x4 operator *(const Matrix4x4& a, const Matrix4x4& b) { Matrix4x4 ret; for(size_t i = 0; i < 4; ++i) { Vector4D row = a.getRow(i); for(size_t j = 0; j < 4; ++j) { ret[i][j] = row[0] * b[0][j] + row[1] * b[1][j] + row[2] * b[2][j] + row[3] * b[3][j]; } } return ret; } Vector3D operator *(const Matrix4x4& M, const Vector3D& v) { return Vector3D( v[0] * M[0][0] + v[1] * M[0][1] + v[2] * M[0][2], v[0] * M[1][0] + v[1] * M[1][1] + v[2] * M[1][2], v[0] * M[2][0] + v[1] * M[2][1] + v[2] * M[2][2]); } Point3D operator *(const Matrix4x4& M, const Point3D& p) { return Point3D( p[0] * M[0][0] + p[1] * M[0][1] + p[2] * M[0][2] + M[0][3], p[0] * M[1][0] + p[1] * M[1][1] + p[2] * M[1][2] + M[1][3], p[0] * M[2][0] + p[1] * M[2][1] + p[2] * M[2][2] + M[2][3]); } Vector3D transNorm(const Matrix4x4& M, const Vector3D& n) { return Vector3D( n[0] * M[0][0] + n[1] * M[1][0] + n[2] * M[2][0], n[0] * M[0][1] + n[1] * M[1][1] + n[2] * M[2][1], n[0] * M[0][2] + n[1] * M[1][2] + n[2] * M[2][2]); } std::ostream& operator <<(std::ostream& os, const Matrix4x4& M) { return os << "[" << M[0][0] << " " << M[0][1] << " " << M[0][2] << " " << M[0][3] << "]" << std::endl << "[" << M[1][0] << " " << M[1][1] << " " << M[1][2] << " " << M[1][3] << "]" << std::endl << "[" << M[2][0] << " " << M[2][1] << " " << M[2][2] << " " << M[2][3] << "]" << std::endl << "[" << M[3][0] << " " << M[3][1] << " " << M[3][2] << " " << M[3][3] << "]"; }
[ [ [ 1, 391 ] ] ]
f20257b4f40853067efaeb2737f91b1d02e249df
021e8c48a44a56571c07dd9830d8bf86d68507cb
/build/vtk/vtkQtChartLegendModel.h
bfe3784bdde3d93eae0080eea95e2a58f8df1902
[ "BSD-3-Clause" ]
permissive
Electrofire/QdevelopVset
c67ae1b30b0115d5c2045e3ca82199394081b733
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
refs/heads/master
2021-01-18T10:44:01.451029
2011-05-01T23:52:15
2011-05-01T23:52:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,004
h
/*========================================================================= Program: Visualization Toolkit Module: vtkQtChartLegendModel.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ /// \file vtkQtChartLegendModel.h /// \date February 12, 2008 #ifndef _vtkQtChartLegendModel_h #define _vtkQtChartLegendModel_h #include "vtkQtChartExport.h" #include <QObject> #include <QPixmap> // Needed for return type #include <QString> // Needed for return type class vtkQtChartLegendModelInternal; class vtkQtPointMarker; class QPen; /// \class vtkQtChartLegendModel /// \brief /// The vtkQtChartLegendModel class stores the data for a chart legend. class VTKQTCHART_EXPORT vtkQtChartLegendModel : public QObject { Q_OBJECT public: /// \brief /// Creates a chart legend model. /// \param parent The parent object. vtkQtChartLegendModel(QObject *parent=0); virtual ~vtkQtChartLegendModel(); /// \brief /// Adds an entry to the chart legend. /// \param icon The series identifying image. /// \param text The series label. /// \return /// The id for the inserted entry or zero for failure. int addEntry(const QPixmap &icon, const QString &text, bool visible); /// \brief /// Inserts an entry into the chart legend. /// \param index Where to place the new entry. /// \param icon The series identifying image. /// \param text The series label. /// \return /// The id for the inserted entry or zero for failure. int insertEntry( int index, const QPixmap &icon, const QString &text, bool visible); /// \brief /// Removes an entry from the chart legend. /// \param index The index of the entry to remove. void removeEntry(int index); /// Removes all the entries from the legend. void removeAllEntries(); /// \brief /// Blocks the model modification signals. /// /// This method should be called before making multiple changes to /// the model. It will prevent the view from updating before the /// changes are complete. Once all the changes are made, the /// \c finishModifyingData method should be called to notify the /// view of the changes. /// /// \sa vtkQtChartLegendModel::finishModifyingData() void startModifyingData(); /// \brief /// Unblocks the model modification signals. /// /// The \c entriesReset signal is emitted to synchronize the view. /// /// \sa vtkQtChartLegendModel::startModifyingData() void finishModifyingData(); /// \brief /// Gets the number of entries in the legend. /// \return /// The number of entries in the legend. int getNumberOfEntries() const; /// \brief /// Gets the index for the given id. /// \param id The entry identifier. /// \return /// The index for the entry that matches the id or -1 if there is /// no matching entry. int getIndexForId(unsigned int id) const; /// \brief /// Gets the icon for the given index. /// \param index The index of the entry. /// \return /// The icon for the given index or a null pixmap if the index is /// out of bounds. QPixmap getIcon(int index) const; /// \brief /// Sets the icon for the given index. /// \param index The index of the entry. /// \param icon The new series icon. void setIcon(int index, const QPixmap &icon); /// \brief /// Gets the text for the given index. /// \param index The index of the entry. /// \return /// The text for the given index or a null string if the index is /// out of bounds. QString getText(int index) const; /// \brief /// Sets the text for the given index. /// \param index The index of the entry. /// \param text The new series label. void setText(int index, const QString &text); /// \brief /// Sets if the given entry is visible. /// \param index The index of the entry. /// \param visible The visibility of the entry. void setVisible(int index, bool visible); /// \brief /// Returns if the given entry is visible. bool getVisible(int index) const; signals: /// \brief /// Emitted when a new entry is added. /// \param index Where the entry was added. void entryInserted(int index); /// \brief /// Emitted before an entry is removed. /// \param index The index being removed. void removingEntry(int index); /// \brief /// Emitted after an entry is removed. /// \param index The index being removed. void entryRemoved(int index); /// Emitted when the legend entries are reset. void entriesReset(); /// \brief /// Emitted when the icon for an entry has changed. /// \param index The index of the entry that changed. void iconChanged(int index); /// \brief /// Emitted when the text for an entry has changed. /// \param index The index of the entry that changed. void textChanged(int index); /// \brief /// Emitted when the visibility of an entry changes. void visibilityChanged(int index); private: vtkQtChartLegendModelInternal *Internal; ///< Stores the legend items. bool InModify; ///< True when blocking signals. }; #endif
[ "ganondorf@ganondorf-VirtualBox.(none)" ]
[ [ [ 1, 188 ] ] ]
baa538b5487c9c39f4a987bcc172b8a35bcea5bf
dcede1e7958bd0d153fc83418a2ede4a41ebd6ab
/DesktopIconManager.h
ef70ad270ae03462be44c8ba4da6c888a1fd9a2d
[]
no_license
death/iconjesus
632666f3a713f4ddf8b25e9121969ce5ced5b49f
7ed3cec78ea73bf650164179543e193f1d96f1f7
refs/heads/master
2021-01-10T20:47:08.294713
2008-11-07T16:56:13
2008-11-07T16:56:13
72,886
4
1
null
null
null
null
UTF-8
C++
false
false
413
h
#pragma once class CDesktopIconManager { public: CDesktopIconManager(); ~CDesktopIconManager(); int GetNumIcons(void) const; bool GetIconText(int nIndex, LPTSTR pszText, int cchText) const; bool GetIconPosition(int nIndex, LPPOINT ppt) const; bool SetIconPosition(int nIndex, LPPOINT ppt); private: HWND m_hwnd; HANDLE m_hProcess; LPVOID m_lpMem; };
[ [ [ 1, 20 ] ] ]
c8383761745fd762ee4cd53493d7f2806862748f
f08e489d72121ebad042e5b408371eaa212d3da9
/TP1_v2/src/Persistencia/PersistorBTree.h
6fabab1040bdec87c543f3ff5ac239ebcad5a5d0
[]
no_license
estebaneze/datos022011-tp1-vane
627a1b3be9e1a3e4ab473845ef0ded9677e623e0
33f8a8fd6b7b297809a0feac14d10f9815f8388b
refs/heads/master
2021-01-20T03:35:36.925750
2011-12-04T18:19:55
2011-12-04T18:19:55
41,821,700
0
0
null
null
null
null
UTF-8
C++
false
false
597
h
/* * PersistorBTree.h * * Created on: 23/04/2010 * Author: daniel */ #ifndef PERSISTORBTREE_H_ #define PERSISTORBTREE_H_ #include "PersistorBase.h" #include "../utils/types.h" #include "../BPlusTree/BNode.h" class PersistorBTree : public PersistorBase { protected: //Sobreescribo este metodo para que cree un nodo raiz vacio void newFile(std::string fileName) ; public: PersistorBTree(std::string fileName, BlockSize size) ; virtual ~PersistorBTree(); BNode* getNodeInBlock(int blockNumber); BNode* getRoot(); }; #endif /* PERSISTORBTREE_H_ */
[ [ [ 1, 29 ] ] ]
51c1a05ed438eba15ce627af5158548f09bef1c5
7f6fe18cf018aafec8fa737dfe363d5d5a283805
/ntk/interface/src/menuwindow.h
00a820d13b786a245e4916f79cdb89297de809c7
[]
no_license
snori/ntk
4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba
86d1a32c4ad831e791ca29f5e7f9e055334e8fe7
refs/heads/master
2020-05-18T05:28:49.149912
2009-08-04T16:47:12
2009-08-04T16:47:12
268,861
2
0
null
null
null
null
UTF-8
C++
false
false
1,257
h
/****************************************************************************** The NTK Library Copyright (C) 1998-2003 Noritaka Suzuki $Id: menuwindow.h,v 1.5 2003/11/11 12:07:08 nsuzuki Exp $ ******************************************************************************/ #pragma once #ifndef __NTK_INTERFACE_MENUWINDOW_H__ #define __NTK_INTERFACE_MENUWINDOW_H__ #ifndef __NTK_DEFS_H__ #include <ntk/defs.h> #endif #ifndef __NTK_INTERFACE_WINDOW_H__ #include <ntk/interface/window.h> #endif namespace ntk { class Menu; class MenuWindow : public Window { public: // // methods // MenuWindow(Menu* menu, bool owner = false); virtual ~MenuWindow(); void go(const Point& point); // // message handler // bool quit_requested(); private: // // data // Menu* m_menu; bool m_owner; };// class MenuWindow #ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME typedef MenuWindow menu_window_t; #endif } namespace Ntk = ntk; #ifdef NTK_TYPEDEF_TYPES_AS_GLOBAL_TYPE #ifdef NTK_TYPEDEF_GLOBAL_NCLASS typedef ntk::MenuWindow NMenuWindow; #endif #ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME typedef ntk::MenuWindow ntk_menu_window; #endif #endif #endif//EOH
[ [ [ 1, 73 ] ] ]
a342714ca4aeb21916e5c95f4bd4f9c542557a06
b2b5c3694476d1631322a340c6ad9e5a9ec43688
/Baluchon/IColorDetectionService.h
ecbda6e1359da6cbe021b777d42c65428bc7b460
[]
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
334
h
#pragma once #include "IDetectionService.h" #include "IMarker.h" using namespace baluchon::core::datas::detection; namespace baluchon { namespace core { namespace services { namespace colordetection { class IColorDetectionService : public IDetectionService { public: virtual ~IColorDetectionService() {} }; }}}};
[ "jpmorin196@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5" ]
[ [ [ 1, 16 ] ] ]
117d985d556c858433ea4b1cefb935ebc5819dd3
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/src/OpenSteerUT/AbstractVehicleMath.cpp
0ae9e2556a5b81fd65de5ec869224306520d886c
[]
no_license
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
14,524
cpp
//----------------------------------------------------------------------------- // Copyright (c) 2009, Jan Fietz, Cyrus Preuss // 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 EduNetGames nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #include "AbstractVehicleMath.h" #include "EduNetCommon/TCompressed.h" #include "EduNetCommon/EduNetMath.h" namespace OpenSteer { //------------------------------------------------------------------------- using namespace OpenSteer; //------------------------------------------------------------------------- osVector3& getVector3( const btVector3& kSource, osVector3& kTarget ) { kTarget.x = kSource.getX(); kTarget.y = kSource.getY(); kTarget.z = kSource.getZ(); return kTarget; } //------------------------------------------------------------------------- btVector3& getVector3( const osVector3& kSource, btVector3& kTarget ) { kTarget.setX( kSource.x ); kTarget.setY( kSource.y ); kTarget.setZ( kSource.z ); return kTarget; } // test conversion // EduNet::EmptyVehicle v1, v2; // btTransform kWorldTransform; // btTransform kTargetWorldTransform; // kWorldTransform.setIdentity(); // writeTransformToLocalSpace( v2, kWorldTransform ); // writeLocalSpaceToTransform( v2, kTargetWorldTransform ); //------------------------------------------------------------------------- void writeRotationMatrixToLocalSpace( const btMatrix3x3& kWorldRotation, osLocalSpaceData& kLocalSpace ) { // calculate local coordinate system const btVector3& kRow0 = kWorldRotation.getRow(0); const btVector3& kRow1 = kWorldRotation.getRow(1); const btVector3& kRow2 = kWorldRotation.getRow(2); btVector3 kAxis[3]; kAxis[0].setX( kRow0.getX() ); kAxis[0].setY( kRow1.getX() ); kAxis[0].setZ( kRow2.getX() ); kAxis[1].setX( kRow0.getY() ); kAxis[1].setY( kRow1.getY() ); kAxis[1].setZ( kRow2.getY() ); kAxis[2].setX( kRow0.getZ() ); kAxis[2].setY( kRow1.getZ() ); kAxis[2].setZ( kRow2.getZ() ); #if OS_HAS_BULLET kLocalSpace._side = kAxis[0]; kLocalSpace._forward = kAxis[1]; kLocalSpace._up = kAxis[2]; #else osVector3 kTemp; #if OPENSTEER_Z_ISUP kLocalSpace._side = getVector3( kAxis[0], kTemp ); kLocalSpace._forward = getVector3( kAxis[1], kTemp ); kLocalSpace._up = getVector3( kAxis[2], kTemp ); #else kLocalSpace._side = -getVector3( kAxis[0], kTemp ); kLocalSpace._forward = getVector3( kAxis[2], kTemp ); kLocalSpace._up = getVector3( kAxis[1], kTemp ); #endif #endif } //------------------------------------------------------------------------- void writeTransformToLocalSpace( const btTransform& kWorldTransform, osLocalSpaceData& kLocalSpace ) { // const btTransform& kWorldTransform = pkRigidBody->getWorldTransform(); const btMatrix3x3& kWorldRotation = kWorldTransform.getBasis(); OpenSteer::writeRotationMatrixToLocalSpace( kWorldRotation, kLocalSpace ); #if OS_HAS_BULLET kLocalSpace._position = kWorldTransform.getOrigin(); #else osVector3 kTemp; kLocalSpace._position = getVector3( kWorldTransform.getOrigin(), kTemp ); #endif } //------------------------------------------------------------------------- void writeLocalSpaceToRotationMatrix( const osLocalSpaceData& kLocalSpace, btMatrix3x3& kWorldRotation ) { #if OS_HAS_BULLET const btVector3 kTargetRow[3] = { kVehicle.side(), kVehicle.forward(), kVehicle.up(), }; #else btVector3 kTemp; const btVector3 kTargetRow[3] = { #if OPENSTEER_Z_ISUP getVector3( kLocalSpace._side, kTemp ), getVector3( kLocalSpace._forward, kTemp ), getVector3( kLocalSpace._up, kTemp ), #else getVector3( -kLocalSpace._side, kTemp ), getVector3( kLocalSpace._up, kTemp ), getVector3( kLocalSpace._forward, kTemp ), #endif }; #endif kWorldRotation.setValue( kTargetRow[0].x(), kTargetRow[1].x(), kTargetRow[2].x(), kTargetRow[0].y(), kTargetRow[1].y(), kTargetRow[2].y(), kTargetRow[0].z(), kTargetRow[1].z(), kTargetRow[2].z()); } //------------------------------------------------------------------------- bool writeLocalSpaceToTransform( const osLocalSpaceData& kLocalSpace, btTransform& kWorldTransform ) { if( false == OpenSteer::isValidVector( kLocalSpace._forward ) ) { return false; } if( false == OpenSteer::isValidVector( kLocalSpace._side ) ) { return false; } if( false == OpenSteer::isValidVector( kLocalSpace._up ) ) { return false; } if( false == OpenSteer::isValidVector( kLocalSpace._position ) ) { return false; } #if OS_HAS_BULLET kWorldTransform.setOrigin( kLocalSpace._position ); #else btVector3 kTemp; kWorldTransform.setOrigin( getVector3( kLocalSpace._position, kTemp ) ); #endif btMatrix3x3& kWorldRotation = kWorldTransform.getBasis(); OpenSteer::writeLocalSpaceToRotationMatrix( kLocalSpace, kWorldRotation ); return true; } //------------------------------------------------------------------------- void writeTransformToLocalSpace( const btTransform& kWorldTransform, osAbstractLocalSpace& kLocalSpace ) { OpenSteer::writeTransformToLocalSpace( kWorldTransform, kLocalSpace.accessLocalSpaceData() ); } //------------------------------------------------------------------------- void writeTransformToLocalSpace( const btTransform& kWorldTransform, osAbstractVehicle& kVehicle ) { OpenSteer::writeTransformToLocalSpace( kWorldTransform, kVehicle.accessLocalSpaceData() ); } //------------------------------------------------------------------------- bool writeLocalSpaceToTransform( const osAbstractVehicle& kVehicle, btTransform& kWorldTransform ) { return OpenSteer::writeLocalSpaceToTransform( kVehicle.getLocalSpaceData(), kWorldTransform ); } //------------------------------------------------------------------------- void calculateVelocity( const btTransform& kWorldTransform0, const btTransform& kWorldTransform1, osScalar fDeltaTime, osVector3& kLinearVelocity, osVector3& kAngularVelocity ) { btVector3 _LinearVelocity, _AngularVelocity; btTransformUtil::calculateVelocity( kWorldTransform0, kWorldTransform1, fDeltaTime, _LinearVelocity, _AngularVelocity ); getVector3( _LinearVelocity, kLinearVelocity ); getVector3( _AngularVelocity, kAngularVelocity ); } //------------------------------------------------------------------------- void localToWorldSpace( const osAbstractVehicle& kVehicle, const osVector3& kSource, osVector3& kTarget ) { btTransform kWorldTransform; writeLocalSpaceToTransform( kVehicle, kWorldTransform ); btVector3 _kSource, _kWorld; getVector3( kSource, _kSource ); _kWorld = kWorldTransform.getBasis() * _kSource; getVector3( _kWorld, kTarget ); } //------------------------------------------------------------------------- osVector3 AbstractVehicleMath::worldDirectionToLocal( const osLocalSpaceData& kLocalSpaceData, const osVector3& kWorld ) { osVector3 kTarget; btTransform kWorldTransform; writeLocalSpaceToTransform( kLocalSpaceData, kWorldTransform ); btVector3 _kSource, _kLocal; getVector3( kWorld, _kSource ); _kLocal = kWorldTransform.getBasis().inverse() * _kSource; getVector3( _kLocal, kTarget ); return kTarget; } //------------------------------------------------------------------------- osVector3 AbstractVehicleMath::localDirectionToWorld( const osLocalSpaceData& kLocalSpaceData, const osVector3& kLocal ) { osVector3 kTarget; btTransform kWorldTransform; writeLocalSpaceToTransform( kLocalSpaceData, kWorldTransform ); btVector3 _kSource, _kWorld; getVector3( kLocal, _kSource ); _kWorld = kWorldTransform.getBasis() * _kSource; getVector3( _kWorld, kTarget ); return kTarget; } //------------------------------------------------------------------------- btQuaternion AbstractVehicleMath::computeQuaternionFromLocalSpace( const osLocalSpaceData& kLocalSpaceData ) { btMatrix3x3 kWorldRotation; OpenSteer::writeLocalSpaceToRotationMatrix( kLocalSpaceData, kWorldRotation ); btQuaternion kRotation; kWorldRotation.getRotation( kRotation ); kRotation.normalize(); return kRotation; } //------------------------------------------------------------------------- void AbstractVehicleMath::writeQuaternionToLocalSpace( const btQuaternion& kRotation, osLocalSpaceData& kLocalSpaceData ) { if( false == OpenSteer::isValidQuaterion( kRotation ) ) { return; } btMatrix3x3 kWorldRotation; kWorldRotation.setRotation( kRotation ); OpenSteer::writeRotationMatrixToLocalSpace( kWorldRotation, kLocalSpaceData ); } //------------------------------------------------------------------------- osVector3 AbstractVehicleMath::compressQuaternion( const btQuaternion& kRotation, char& wSign ) { btQuaternion kUnitRotation = kRotation.normalized(); osVector3 kCompressed( kUnitRotation.getX(), kUnitRotation.getY(), kUnitRotation.getZ() ); wSign = ( kUnitRotation.getW() < 0 ) ? -1 : 1; return kCompressed; } //------------------------------------------------------------------------- btQuaternion AbstractVehicleMath::expandQuaternion( const osVector3& kCompressed, float wSign ) { // A unit quaternion has the following property // w2 + x2 + y2 + z2 = 1 // -> // w2 = 1 - (x2 + y2 + z2) // w = sqrt( 1 - (x2 + y2 + z2) ) btQuaternion kUnitRotation( kCompressed.x, kCompressed.y, kCompressed.z, 0 ); kUnitRotation.setW( wSign * btSqrt( btScalar(1) - ( kUnitRotation.getX() * kUnitRotation.getX() + kUnitRotation.getY() * kUnitRotation.getY() + kUnitRotation.getZ() * kUnitRotation.getZ() ) ) ); return kUnitRotation; } //------------------------------------------------------------------------- void AbstractVehicleMath::compressUnitVector( const osVector3& kSource, char* kTarget ) { const osScalar x = ::etClamp( kSource.x, -1.0f, 1.0f ); const osScalar y = ::etClamp( kSource.y, -1.0f, 1.0f ); const osScalar z = ::etClamp( kSource.z, -1.0f, 1.0f ); kTarget[0] = TCompressedFixpoint<float,char,8>::writeCompress( x , -1.0f, 1.0f ); kTarget[1] = TCompressedFixpoint<float,char,8>::writeCompress( y , -1.0f, 1.0f ); kTarget[2] = TCompressedFixpoint<float,char,8>::writeCompress( z , -1.0f, 1.0f ); } //------------------------------------------------------------------------- void AbstractVehicleMath::expandUnitVector( const char* kSource, osVector3& kTarget ) { kTarget.x = TCompressedFixpoint<float,char,8>::readInflate( kSource[0] , -1.0f, 1.0f ); kTarget.y = TCompressedFixpoint<float,char,8>::readInflate( kSource[1] , -1.0f, 1.0f ); kTarget.z = TCompressedFixpoint<float,char,8>::readInflate( kSource[2] , -1.0f, 1.0f ); } //------------------------------------------------------------------------- void AbstractVehicleMath::compressFixedLengthVector( const osVector3& kSource, float fMaxLength, CompressedVector& kTarget ) { osVector3 kFixedSource = kSource; kFixedSource = kFixedSource.truncateLength( fMaxLength ); const float fLength = kFixedSource.length(); osVector3 kUnitSource = kFixedSource; float fUnitFactor; if( fLength > 0 ) { kUnitSource /= fLength; kUnitSource.x = etClamp( kUnitSource.x, -1.0f, 1.0f ); kUnitSource.y = etClamp( kUnitSource.y, -1.0f, 1.0f ); kUnitSource.z = etClamp( kUnitSource.z, -1.0f, 1.0f ); fUnitFactor = fLength / fMaxLength; fUnitFactor = etClamp( fUnitFactor, 0.0f, 1.0f ); } else { fUnitFactor = kUnitSource.x = kUnitSource.y = kUnitSource.z = 0; } kTarget.m_cValues[0] = TCompressedFixpoint<float,char,8>::writeCompress( kUnitSource.x , -1.0f, 1.0f ); kTarget.m_cValues[1] = TCompressedFixpoint<float,char,8>::writeCompress( kUnitSource.y , -1.0f, 1.0f ); kTarget.m_cValues[2] = TCompressedFixpoint<float,char,8>::writeCompress( kUnitSource.z , -1.0f, 1.0f ); kTarget.m_cUnitFactor = TCompressedFixpoint<float,short,16>::writeCompress( fUnitFactor, 0.0f, 1.0f ); } //------------------------------------------------------------------------- void AbstractVehicleMath::expandFixedLengthVector( const CompressedVector& kSource, float fMaxLength, osVector3& kTarget ) { // expand kTarget.x = TCompressedFixpoint<float,char,8>::readInflate( kSource.m_cValues[0] , -1.0f, 1.0f ); kTarget.y = TCompressedFixpoint<float,char,8>::readInflate( kSource.m_cValues[1] , -1.0f, 1.0f ); kTarget.z = TCompressedFixpoint<float,char,8>::readInflate( kSource.m_cValues[2] , -1.0f, 1.0f ); const float fLength = kTarget.length(); if( fLength > 0 ) { kTarget /= fLength; const float fUnitFactor = TCompressedFixpoint<float,short,16>::readInflate( kSource.m_cUnitFactor, 0.0f, 1.0f ); kTarget *= fUnitFactor; kTarget *= fMaxLength; } } } // end namespace OpenSteer
[ "janfietz@localhost" ]
[ [ [ 1, 368 ] ] ]
45d23e1d6c355b633ba91aff224aa17d9aeb3538
3699ee70db05a390ce86e64e09e779263510df6f
/branches/Login Server/loginserver.h
1806e9ffc2a24235dbff88a8918d949c60828533
[]
no_license
trebor57/osprosedev
4fbe6616382ccd98e45c8c24034832850054a4fc
71852cac55df1dbe6e5d6f4264a2a2e6fd3bb506
refs/heads/master
2021-01-13T01:50:47.003277
2008-05-14T17:48:29
2008-05-14T17:48:29
32,129,756
0
0
null
null
null
null
UTF-8
C++
false
false
2,586
h
/* Rose Online Server Emulator Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. depeloped with Main erose/hrose source server + some change from the original eich source */ #ifndef __ROSE_SERVER__ #define __ROSE_SERVER__ #include "../common/sockets.h" #include "datatype.h" // Player class class CLoginClient : public CClientSocket { public: CLoginClient ( ); // Constructor ~CLoginClient ( ); // destructor // Variables bool isLoggedIn; UINT userid; string username; string password; WORD accesslevel; }; // Server class class CLoginServer : public CServerSocket { public: CLoginServer ( string ); // Constructor ~CLoginServer( ); // Destructor //Functions CLoginClient* CreateClientSocket( ); // Create a client void DeleteClientSocket( CClientSocket* thisclient ); // Delete a client void LoadEncryption( ); bool OnReceivePacket( CClientSocket* thisclient, CPacket* P ); bool OnServerReady(void); void LoadConfigurations( char* ); // Packets bool pakEncryptionRequest( CLoginClient* thisclient, CPacket* P ); bool pakConnectToChar( CLoginClient* thisclient, CPacket *P ); bool pakUserLogin( CLoginClient* thisclient, CPacket* P ); bool pakGetServers( CLoginClient* thisclient, CPacket* P ); bool pakGetIP( CLoginClient* thisclient, CPacket* P ); // Variables string filename; vector<CServers*> ServerList; // list of channels; CDatabase *DB; }; void StartSignal( ); void StopSignal( ); void HandleSignal( int num ); extern class CLoginServer* GServer; #endif
[ "remichael@004419b5-314d-0410-88ab-2927961a341b" ]
[ [ [ 1, 76 ] ] ]
85aaf8f433c32c8c3d4d093a6dad8eb80d0fee3d
744e9a2bf1d0aee245c42ee145392d1f6a6f65c9
/tags/0.11.1-alpha/gui/main.cpp
e5a8acdaffb30c87f83737e630b3f3baa04a5441
[]
no_license
BackupTheBerlios/ttcut-svn
2b5d00c3c6d16aa118b4a58c7d0702cfcc0b051a
958032e74e8bb144a96b6eb7e1d63bc8ae762096
refs/heads/master
2020-04-22T12:08:57.640316
2009-02-08T16:14:00
2009-02-08T16:14:00
40,747,642
0
0
null
null
null
null
UTF-8
C++
false
false
2,914
cpp
/*----------------------------------------------------------------------------*/ /* COPYRIGHT: TriTime (c) 2003/2005 / www.tritime.org */ /*----------------------------------------------------------------------------*/ /* PROJEKT : TTCUT 2005 */ /* FILE : main.cpp */ /*----------------------------------------------------------------------------*/ /* AUTHOR : b. altendorf (E-Mail: [email protected]) DATE: 02/01/2005 */ /* MODIFIED: b. altendorf DATE: 02/23/2005 */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* 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. */ /*----------------------------------------------------------------------------*/ // Qt headers #include <QApplication> #include <QGLFormat> // class declaration for the main window class #include "ttcutmainwnd.h" int main( int argc, char **argv ) { QApplication::setColorSpec( QApplication::CustomColor ); QApplication a( argc, argv ); // OpenGL is required for the MPEG2 window if ( !QGLFormat::hasOpenGL() ) { qWarning( "This system has no OpenGL support. Exiting." ); return -1; } // Application main widget TTCutMainWnd* mainWnd = new TTCutMainWnd(); //QT3: a.setMainWidget( mainWnd ); // Caption text in applications title bar mainWnd->setWindowTitle( TTCut::versionString ); mainWnd->show(); // set initial size of applications main window mainWnd->resize( 800, 600 ); a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) ); // Execute application and start event loop return a.exec(); }
[ "tritime@7763a927-590e-0410-8f7f-dbc853b76eaa" ]
[ [ [ 1, 60 ] ] ]
125dc9842b6d6d94067a9042864270a22a885a81
a36d7a42310a8351aa0d427fe38b4c6eece305ea
/render_win32/SurfaceDX9Imp.cpp
5b1cea5aef95a5a2f556d1182d6ec49b10c22624
[]
no_license
newpolaris/mybilliard01
ca92888373c97606033c16c84a423de54146386a
dc3b21c63b5bfc762d6b1741b550021b347432e8
refs/heads/master
2020-04-21T06:08:04.412207
2009-09-21T15:18:27
2009-09-21T15:18:27
39,947,400
0
0
null
null
null
null
UTF-8
C++
false
false
1,545
cpp
#include "DXUT.h" #include "my_render_win32_dx9_imp.h" namespace my_render_win32_dx9_imp { SurfaceDX9Imp::SurfaceDX9Imp( IDirect3DSurface9Ptr surface ) : dx9Surface_( surface ) { if( NULL == surface ) throw exception(); surface->GetDesc( &desc_ ); } SurfaceLockedRectDX9 * SurfaceDX9Imp::lockRect( int left, int top, int right, int bottom, int flag ) { RECT * rect = NULL; if( false == ( left == right && top == bottom ) ) { rect = new RECT(); ::SetRect( rect, left, top, right, bottom ); } D3DLOCKED_RECT dxLockedRect; const HRESULT hr = dx9Surface_->LockRect( &dxLockedRect, rect, flag ); SAFE_DELETE( rect ); RETURN_NULL_IF_FAILED( hr, L"SurfaceDX9Imp::lockRect" ); lockedRect_ = SurfaceLockedRectDX9Ptr( new SurfaceLockedRectDX9Imp( dxLockedRect ), SurfaceDX9::Unlocker( this ) ); return lockedRect_.get(); } SurfaceLockedRectDX9 * SurfaceDX9Imp::lockWhole( int flag ) { return lockRect( 0, 0, 0, 0, flag ); } bool SurfaceDX9Imp::isLocked() { return NULL != lockedRect_; } void SurfaceDX9Imp::unlock( SurfaceLockedRectDX9 * lockedRect ) { const HRESULT hr = dx9Surface_->UnlockRect(); if( FAILED( hr ) ) DXUT_ERR( L"SurfaceDX9Imp::unlock", hr ); lockedRect_.reset(); } LPDIRECT3DSURFACE9 SurfaceDX9Imp::getSurfaceDX9() { return dx9Surface_.get(); } size_t SurfaceDX9Imp::getWidth() { return desc_.Width; } size_t SurfaceDX9Imp::getHeight() { return desc_.Height; } }
[ "wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635" ]
[ [ [ 1, 61 ] ] ]
79ce60830834bbe5c3a80d93bac2dad0fcf176ba
0c62a303659646fa06db4d5d09c44ecb53ce619a
/Kickapoo/Audio.h
bcd81726c20e00dc97be06c5cb10993bf3cc1c80
[]
no_license
gosuwachu/igk-game
60dcdd8cebf7a25faf60a5cc0f5acd6f698c1c25
faf2e6f3ec6cfe8ddc7cb1f3284f81753f9745f5
refs/heads/master
2020-05-17T21:51:18.433505
2010-04-12T12:42:01
2010-04-12T12:42:01
32,650,596
0
0
null
null
null
null
UTF-8
C++
false
false
565
h
#pragma once #include "Common.h" typedef FMOD::Sound Sound; class Audio : public Singleton<Audio> { public: Audio() : channel(NULL) {} ~Audio() {} void create(); void release(); void update(); void play(FMOD::Sound* sound, float volume = 1.0f, bool stop = false); void stopSoud(FMOD::Sound* sound); FMOD::Sound* loadSound(const char* filePath, bool loop = false); FMOD::Sound* loadStream(const char* filePath); private: FMOD::System *system; FMOD::Channel *channel; FMOD_RESULT result; }; DefineAccessToSingleton(Audio)
[ "[email protected]@d16c65a5-d515-2969-3ec5-0ec16041161d", "konrad.rodzik@d16c65a5-d515-2969-3ec5-0ec16041161d" ]
[ [ [ 1, 14 ], [ 16, 16 ], [ 20, 27 ] ], [ [ 15, 15 ], [ 17, 19 ] ] ]
019b95a734d38a6c4ef7c914d3af82c5ec3c6826
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/Code/Flosti Engine/Base/Math/LerpAnimator1D.cpp
f2783823e1bcba67854c9fb98ac442e58231a0d6
[]
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
954
cpp
#include "__PCH_Base.h" #include "LerpAnimator1D.h" #include <cmath> void CLerpAnimator1D::SetValues (float initValue, float endValue, float totalTime, ETypeFunction type) { assert( totalTime > 0); m_fInitValue = initValue; m_fEndValue = endValue; m_CDTimer.SetTime(totalTime); m_eFunction = type; } bool CLerpAnimator1D::Update (float deltaTime, float &value) { bool finish = m_CDTimer.Update(deltaTime); //mu [0-1] float mu = m_CDTimer.GetElapsedTimeInPercent()*0.01f; //En funcion del tiempo la siguiente funcion nos retorna un valor entre 0-1. switch(m_eFunction) { case FUNC_CONSTANT: { //Linear //nothing to do } break; case FUNC_INCREMENT: { mu = mathUtils::PowN(mu,m_uDegree); } break; case FUNC_DECREMENT: { mu = sqrt(mu);//pow(mu,(float)(1/m_uDegree)); } break; } value = mathUtils::Lerp(m_fInitValue, m_fEndValue, mu); return finish; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 47 ] ] ]
ae8f571353a45265766f3f2025449fb97b5a2fcd
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/noctree/src/octree/noctsphere_cmds.cc
91c8c6a68a5349e036f65d3b707a6adfa27e6e1c
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,423
cc
#include "precompiled/pchnoctree.h" //------------------------------------------------------------------- // (c)2004 Rafael Van Daele-Hunt //------------------------------------------------------------------- #include "octree/noctsphere.h" static void n_setsphere(void *, nCmd *); //------------------------------------------------------------------------------ /** @scriptclass noctsphere @superclass noctree @classinfo The nOctSphere class is used in conjunction with nOctree to cull all objects outside the given sphere. */ void n_initcmds_nOctSphere(nClass *cl) { cl->BeginCmds(); cl->AddCmd("v_setsphere_ffff",'SSDN',n_setsphere); cl->EndCmds(); } //------------------------------------------------------------------------------ /** @cmd setsphere @input fff (x,y,z position in worldspace), f (radius) @output v @info Defines the clipping sphere. */ static void n_setsphere(void *o, nCmd *cmd) { nOctSphere *self = (nOctSphere *) o; float xPos = cmd->In()->GetF(); float yPos = cmd->In()->GetF(); float zPos = cmd->In()->GetF(); float r = cmd->In()->GetF(); self->SetSphere( sphere( xPos, yPos, zPos, r ) ); } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 54 ] ] ]
f1ba7c652628716b4d55d02319c6bd3898dabdac
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/GUIStage.h
e2eece80c8c34547b21e55339c53c45bc44c4c9f
[]
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
876
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: GUIStage.h Version: 0.02 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_GUISTAGE_H_ #define __INC_GUISTAGE_H_ #include "Prerequisities.h" #include "RenderStage.h" namespace nGENE { /// Render stage for GUI. class nGENEDLL GUIStage: public RenderStage { private: GUIManager* m_pManager; public: GUIStage(); ~GUIStage(); void render(); void setManager(GUIManager* _manager); }; inline void GUIStage::setManager(GUIManager* _manager) { m_pManager = _manager; } //---------------------------------------------------------------------- } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 50 ] ] ]
deb19458a2bc56dec30ce3d7ccf5ce78ea9b680a
02ecaf771a1997379b7c0ab789b3c76fc84c42f8
/references/rrls/rrls.cpp
f575efba37725873d7469728085b1a9bd4ee2764
[]
no_license
tingyingwu2010/heuristicschallenge
b31a8f7dd8a2a0ca83ec5d77ecce394760fe512c
b69f534a3b641888e45f2466276743a7237e6bbb
refs/heads/master
2021-05-27T19:53:39.500569
2008-08-01T04:42:56
2008-08-01T04:42:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,989
cpp
/*************************************************************************** rrls.cpp - Implementation Random Restart Local Search for comparison with mmas. ------------------- begin : Sun Mar 10, 2002 copyright : (C) 2002 by Krzysztof Socha email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "defs.h" #include "Control.h" #include "Problem.h" #include "Solution.h" #include "Random.h" int main( int argc, char** argv) { // create a control object from the command line arguments Control control(argc, argv); // check if specific parameters have been passed // -ant int n_of_ants = control.getIntParameter("-ant"); if (n_of_ants<1) { n_of_ants = DEFAULT_N_OF_ANTS; cerr << "Warning: " << n_of_ants << " used as default number of random solutions generated" << endl; } Solution** solution = new Solution*[n_of_ants]; // create a problem, control tells you what input file stream to use Problem *problem = new Problem(control.getInputStream()); // create a Random object Random *rnd = new Random((unsigned) control.getSeed()); // create a buffer for holding iteration and global best solution Solution *best_solution = new Solution(problem, rnd); // run a number of tries, control knows how many tries there should be done while (control.triesLeft()) { // tell control we are starting a new try control.beginTry(); // initialize best solution with random value best_solution->RandomInitialSolution(); best_solution->computeFeasibility(); control.setCurrentCost(best_solution); while (control.timeLeft()) { // create a set of ants for (int i=0;i<n_of_ants;i++) solution[i] = new Solution(problem, rnd); // let the ants do the job - create some solutions for (int i=0;i<n_of_ants;i++) solution[i]->RandomInitialSolution(); // find the best solution int best_fitness = 99999; int ant_idx = -1; for (int i=0;i<n_of_ants;i++) { int fitness = solution[i]->computeHcv(); if (fitness<best_fitness) { best_fitness = fitness; ant_idx = i; } } // apply local search until local optimum reached or a time limit reached solution[ant_idx]->localSearch(DEFAULT_MAX_STEPS, control.getTimeLimit()-control.getTime()); solution[ant_idx]->computeFeasibility(); // output the new best solution, if found if (solution[ant_idx]->feasible) { solution[ant_idx]->computeScv(); if (solution[ant_idx]->scv<=best_solution->scv) { best_solution->copy(solution[ant_idx]); best_solution->hcv = 0; control.setCurrentCost(best_solution); } } else { solution[ant_idx]->computeHcv(); if (solution[ant_idx]->hcv<=best_solution->hcv) { best_solution->copy(solution[ant_idx]); control.setCurrentCost(best_solution); best_solution->scv = 99999; } } // destroy current solutions for(int i=0;i<n_of_ants;i++) delete solution[i]; } // output best feasible solution found control.endTry(best_solution); } delete problem; delete solution; delete best_solution; delete rnd; return 0; }
[ "pedro@pedro-laptop.(none)" ]
[ [ [ 1, 119 ] ] ]
aa48a516ef0ecfa2e2adab145490626073a4f071
ef8e875dbd9e81d84edb53b502b495e25163725c
/litewiz/src/items/item_collection.h
ac8579dd316d093b51716fd0da27e6119c65193d
[]
no_license
panone/litewiz
22b9d549097727754c9a1e6286c50c5ad8e94f2d
e80ed9f9d845b08c55b687117acb1ed9b6e9a444
refs/heads/master
2021-01-10T19:54:31.146153
2010-10-01T13:29:38
2010-10-01T13:29:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
998
h
/******************************************************************************* *******************************************************************************/ #ifndef ITEM_COLLECTION_H #define ITEM_COLLECTION_H /******************************************************************************/ #include "file_cluster_collection.h" /******************************************************************************/ class Item; class ItemInfo; /******************************************************************************* *******************************************************************************/ class ItemCollection : public FileClusterCollection { public: Item * addItem ( ItemInfo const & itemInfo ); Item * getItem ( int const index ) const; }; /******************************************************************************/ #endif /* ITEM_COLLECTION_H */
[ [ [ 1, 36 ] ] ]
2bf198f417fc454675c8fcf91834033206c8fc7c
9176b0fd29516d34cfd0b143e1c5c0f9e665c0ed
/CS_153_Data_Structures/assignment2/test_vector.h
df60d7d47c89dc14a6043facf3acdbbedc6d69e9
[]
no_license
Mr-Anderson/james_mst_hw
70dbde80838e299f9fa9c5fcc16f4a41eec8263a
83db5f100c56e5bb72fe34d994c83a669218c962
refs/heads/master
2020-05-04T13:15:25.694979
2011-11-30T20:10:15
2011-11-30T20:10:15
2,639,602
2
0
null
null
null
null
UTF-8
C++
false
false
2,681
h
#ifndef TEST_VECTOR_H #define TEST_VECTOR_H ////////////////////////////////////////////////////////////////////// /// @file test_vector.h /// @author James Anderson Section A /// @brief Heder file for test_vector class for assignment 1 ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @class test_vector /// @brief Used to test the various fetures and limits of the vector class ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn Test_vector::test_constructor () /// @brief function checks the functionality of the constructor in the /// vector class /// @post function will check the constructor of the vector class ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn Test_vector::test_push_back () /// @brief function checks the functionality of the pushback function in the /// array class checks the out of bounds error as well as the container full error /// @post function will check the push back as well as the container full and out /// of bounds errors ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn Test_vector::test_pop_back () /// @brief function checks the functionality of the popback function in the /// array class and also checks the container empty error /// @post function will check the popback function as well as the container /// empty error ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn Test_vector::test_clear () /// @brief function checks the functionality of the clear function in the /// vector class /// @post function will check the clear function ////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/config/SourcePrefix.h> #include "vector.h" #include "exception.h" #include "math.h" class Test_vector : public CPPUNIT_NS::TestFixture { private: CPPUNIT_TEST_SUITE (Test_vector); CPPUNIT_TEST (test_constructor); CPPUNIT_TEST (test_push_back); CPPUNIT_TEST (test_pop_back); CPPUNIT_TEST (test_clear); CPPUNIT_TEST_SUITE_END (); protected: void test_push_back (); void test_pop_back (); void test_constructor (); void test_clear (); }; #endif
[ [ [ 1, 63 ] ] ]
6ec6961b312d00ac9fd4bde84b8d39486aa552b9
ae144be89970a94c750180fb49d7defbcfc2334a
/01-LancaProcessosConsola/01-LancaProcessosConsola/LancaProcessosConsola/stdafx.cpp
fe88973529cc05abbad6dc0ff961320d75a6c304
[]
no_license
Netivski/iselso
cc0bad0df6088d184b67b8a9581abc81624fdc5f
accb63f3131aea1d42439d01b7fb59036c095849
refs/heads/master
2021-01-20T12:04:31.659869
2009-05-04T20:19:00
2009-05-04T20:19:00
32,590,806
0
0
null
null
null
null
UTF-8
C++
false
false
308
cpp
// stdafx.cpp : source file that includes just the standard includes // LancaProcessosConsola.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "ppires75@49016d5c-2abe-11de-b161-0f7b0ef88f65" ]
[ [ [ 1, 8 ] ] ]
610ddda327507e773d7280b35a8c179077890424
b22c254d7670522ec2caa61c998f8741b1da9388
/common/ActorCondition.h
c712a9213eda7f1373a93f7ef6a4f4bd5c964b4d
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
2,174
h
/* ------------------------[ Lbanet Source ]------------------------- Copyright (C) 2009 Author: Vivien Delage [Rincevent_123] Email : [email protected] -------------------------------[ GNU License ]------------------------------- 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, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- */ #if !defined(__LbaNetModel_1_ActorCondition_h) #define __LbaNetModel_1_ActorCondition_h #include "ConditionBase.h" #include "ActorHandlerBase.h" #include <string> /*********************************************************************** * Module: ActorActivatedCondition.h * Author: vivien * Modified: lundi 27 juillet 2009 14:53:50 * Purpose: Declaration of the class InventoryCondition *********************************************************************/ class ActorActivatedCondition : public ConditionBase { public: //! constructor //! activating group is the group that the actiavating agent belows: //! 0 -> everybody; 1 -> player; 2 -> other actors //! mapname gives the map where the actor should be located ActorActivatedCondition(long ActorId, int activatinggroup, const std::string & MapName, ActorHandlerBase * actH) : _ActorId(ActorId), _activatinggroup(activatinggroup), _MapName(MapName), _actH(actH) {} //! destructor virtual ~ActorActivatedCondition(){} //! check if the condition is true or not virtual bool Passed(); private: long _ActorId; int _activatinggroup; std::string _MapName; ActorHandlerBase * _actH; }; #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 65 ] ] ]
47e88b236a8ce8c0f8b0231ba1d13e6c00f09dc7
00eafce8d2102419062bf946b37f10bd884d6df4
/ZtringList.h
abd130b77265810fd436b4aaf889fd12944a941a
[]
no_license
bonya81/mediainfomac
d37e89b69a1f2e29785103e21297e05e8548a5ea
b0f6009e8dfe43d4a65693de4b7d94af7fe6c6ac
refs/heads/master
2021-01-10T19:16:41.878858
2008-01-31T00:46:42
2008-01-31T00:46:42
33,527,089
0
0
null
null
null
null
UTF-8
C++
false
false
4,361
h
// ZenLib::ZtringList - More methods for vector<std::(w)string> // Copyright (C) 2002-2008 Jerome Martinez, [email protected] // // 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. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // More methods for std::vector<std::(w)string> // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- #ifndef ZenLib_ZtringListH #define ZenLib_ZtringListH //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "ZenLib/Ztring.h" #include <vector> //--------------------------------------------------------------------------- namespace ZenLib { //*************************************************************************** /// @brief Vector of strings manipulation (based on std::vector<std::(w)string>) //*************************************************************************** class ZtringList : public std::vector<Ztring> { public : //Constructors/destructor ZtringList (); ZtringList (const ZtringList &Source); ZtringList (const Ztring &Source); ZtringList (const Char *Source); #ifdef _UNICODE ZtringList (const char *Source); //convert a UTF-8 string into Unicode #endif //Operators bool operator == (const ZtringList &Source) const; bool operator != (const ZtringList &Source) const; ZtringList &operator += (const ZtringList &Source); ZtringList &operator = (const ZtringList &Source); Ztring &operator () (size_type Pos); ///< Same as [], but write a empty string if Pos doesn't exist yet //In/out Ztring Read () const; /// Read all const Ztring &Read (size_type Pos) const; /// Read a string void Write (const Ztring &ToWrite); /// Write all void Write (const Ztring &ToWrite, size_type Pos); /// Write a string /// @brief Insert a string at position Pos0 void Insert (const Ztring &ToInsert, size_type Pos0) {insert(begin()+Pos0, ToInsert);}; /// @brief Delete a string at position Pos0 void Delete (size_type Pos0) {erase(begin()+Pos0);}; //Edition /// @brief Swap 2 positions void Swap (size_type Pos0_A, size_type Pos0_B); /// @brief Sort void Sort (ztring_t Options=Ztring_Nothing); //Information /// @brief Find the position of the string in the vector size_type Find (const Ztring &ToFind, size_type PosBegin=0, const Ztring &Comparator=_T("=="), ztring_t Options=Ztring_Nothing) const; /// @brief Return the length of the longest string in the list. size_type MaxStringLength_Get (); //Configuration /// @brief Set the Separator character void Separator_Set (size_type Level, const Ztring &NewSeparator); /// @brief Set the Quote character /// During Read() or Write() method, if Separator is in the sequence, we must quote it void Quote_Set (const Ztring &NewQuote); /// @brief Set the Maximum number of element to read /// During Read() or Write() method, if there is more elements, merge them with the last element void Max_Set (size_type Level, size_type Max_New); protected : Ztring Separator[1]; Ztring Quote; size_type Max[1]; }; } //namespace #endif
[ "[email protected]@cc249753-f944-0410-bbd9-9b9bab5a7bdc" ]
[ [ [ 1, 103 ] ] ]
cbec51601a65d5b8e80cd7291b5057bccd95b5d4
00b979f12f13ace4e98e75a9528033636dab021d
/ConfManager tmp (for test)/src/Getopt.cpp
ec9cc6d9fd01730feb5d2ddceb3444e23eedb8c6
[]
no_license
BackupTheBerlios/ziahttpd-svn
812e4278555fdd346b643534d175546bef32afd5
8c0b930d3f4a86f0622987776b5220564e89b7c8
refs/heads/master
2016-09-09T20:39:16.760554
2006-04-13T08:44:28
2006-04-13T08:44:28
40,819,288
0
0
null
null
null
null
UTF-8
C++
false
false
1,292
cpp
/* ** Getopt.c for in ** ** Made by Bigand Xavier ** Login <@epita.fr> ** ** Started on Sun Dec 18 12:44:33 2005 Bigand Xavier // Last update Sun Dec 18 13:40:01 2005 Bigand Xavier */ #include "Getopt.hh" char *optarg; // global argument pointer int optind = 0; // global argv index int getopt(int argc, char *argv[], char *optstring) { static char *next = NULL; char c; char *cp; if (optind == 0) next = NULL; optarg = NULL; if (next == NULL || *next == '\0') { if (optind == 0) optind++; if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0') { optarg = NULL; if (optind < argc) optarg = argv[optind]; return -1; } if (strcmp(argv[optind], "--") == 0) { optind++; optarg = NULL; if (optind < argc) optarg = argv[optind]; return -1; } next = argv[optind]; next++; // skip past - optind++; } c = *next++; cp = strchr(optstring, c); if (cp == NULL || c == ':') return '?'; cp++; if (*cp == ':') { if (*next != '\0') { optarg = next; next = NULL; } else if (optind < argc) { optarg = argv[optind]; optind++; } else return '?'; } return c; }
[ "ringo@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
[ [ [ 1, 69 ] ] ]
f79da86cefef3213242496bbd0a7a0bfc402decf
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Intersection/Wm4IntrSegment2Arc2.h
c74dd2f79f62d1a01e4084d268799b68927a464c
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
1,628
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4INTRSEGMENT2ARC2_H #define WM4INTRSEGMENT2ARC2_H #include "Wm4FoundationLIB.h" #include "Wm4Intersector.h" #include "Wm4Segment2.h" #include "Wm4Arc2.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM IntrSegment2Arc2 : public Intersector<Real,Vector2<Real> > { public: IntrSegment2Arc2 (const Segment2<Real>& rkSegment, const Arc2<Real>& rkCircle); // object access const Segment2<Real>& GetSegment () const; const Arc2<Real>& GetArc () const; // static intersection query virtual bool Find (); // the intersection set int GetQuantity () const; const Vector2<Real>& GetPoint (int i) const; private: using Intersector<Real,Vector2<Real> >::IT_EMPTY; using Intersector<Real,Vector2<Real> >::IT_POINT; using Intersector<Real,Vector2<Real> >::m_iIntersectionType; // the objects to intersect const Segment2<Real>& m_rkSegment; const Arc2<Real>& m_rkArc; // information about the intersection set int m_iQuantity; Vector2<Real> m_akPoint[2]; }; typedef IntrSegment2Arc2<float> IntrSegment2Arc2f; typedef IntrSegment2Arc2<double> IntrSegment2Arc2d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 60 ] ] ]
c1086df039dba6f1f58cfb357835c581f710b803
317f62189c63646f81198d1692bed708d8f18497
/common/network/components/router/performance/flow_control_scheme.h
0d81b701f2454313b9e26097682b600ecc20da2d
[ "MIT" ]
permissive
mit-carbon/Graphite-Cycle-Level
8fb41d5968e0a373fd4adbf0ad400a9aa5c10c90
db3f1e986ddc10f3e5f3a5d4b68bd6a9885969b3
refs/heads/master
2021-01-25T07:08:46.628355
2011-11-23T08:53:18
2011-11-23T08:53:18
1,930,686
1
0
null
null
null
null
UTF-8
C++
false
false
2,042
h
#pragma once #include <vector> #include <string> using namespace std; #include "buffer_management_scheme.h" #include "fixed_types.h" #include "network_msg.h" #include "flit.h" #include "buffer_management_msg.h" #include "buffer_model.h" class FlowControlScheme { public: enum Type { STORE_AND_FORWARD = 0, VIRTUAL_CUT_THROUGH, WORMHOLE, WORMHOLE_UNICAST__VIRTUAL_CUT_THROUGH_BROADCAST, NUM_SCHEMES }; FlowControlScheme(SInt32 num_input_channels, SInt32 num_output_channels): _num_input_channels(num_input_channels), _num_output_channels(num_output_channels) {} virtual ~FlowControlScheme() {}; static Type parse(string flow_control_scheme_str); static FlowControlScheme* create(Type flow_control_scheme, SInt32 num_input_channels, SInt32 num_output_channels, vector<SInt32>& num_input_endpoints_list, vector<SInt32>& num_output_endpoints_list, vector<BufferManagementScheme::Type>& input_buffer_management_schemes, vector<BufferManagementScheme::Type>& downstream_buffer_management_schemes, vector<SInt32>& input_buffer_size_list, vector<SInt32>& downstream_buffer_size_list); static void dividePacket(Type flow_control_scheme, NetPacket* net_packet, list<NetPacket*>& net_packet_list, SInt32 serialization_latency); static bool isPacketComplete(Type flow_control_scheme, Flit::Type flit_type); // Public Member Functions virtual void processDataMsg(Flit* flit, vector<NetworkMsg*>& network_msg_list) = 0; virtual void processBufferManagementMsg(BufferManagementMsg* buffer_management_msg, vector<NetworkMsg*>& network_msg_list) = 0; virtual BufferModel* getBufferModel(SInt32 input_channel_id) = 0; protected: SInt32 _num_input_channels; SInt32 _num_output_channels; };
[ [ [ 1, 56 ] ] ]
cc9409cd0cbbe3297785553b267e4bf0fc5b44f6
382b459563be90227848e5125f0d37f83c1e2a4f
/Schedule/src/obsolete/state.cpp
831a899dc0eb7d61cf6bc729075361287cc98570
[]
no_license
Maciej-Poleski/SchoolTools
516c9758dfa153440a816a96e3f05c7f290daf6c
e55099f77eb0f65b75a871d577cc4054221b9802
refs/heads/master
2023-07-02T09:07:31.185410
2010-07-11T20:56:59
2010-07-11T20:56:59
392,391,718
0
0
null
null
null
null
UTF-8
C++
false
false
33
cpp
#include "../include/state.h"
[ [ [ 1, 2 ] ] ]
4f46c058444993f07414f740cb20c55c616ef106
bba4af47e0aa55eb655c90d1bae0b6d466e750c0
/Editor/Editor_Box.cpp
822ac720db3b2398ea408cc0d2f8ed6b416a7150
[]
no_license
HourglassGame/Hourglass1_5
0afbfb4df32232c24a612790000fc18f52bc4b29
6f1505c26081d006e719ec78e98c1636acb50fea
refs/heads/master
2016-08-12T21:28:55.827316
2010-06-03T08:56:30
2010-06-03T08:56:30
46,439,522
0
0
null
null
null
null
UTF-8
C++
false
false
1,618
cpp
#include "Editor_Box.h" // class's header file extern BITMAP* buffer; extern BITMAP* box_sprite; Box::Box(const int newXPos, const int newYPos, const double newXSpeed, const double newYSpeed,const AbsoluteTimeDirectionEnum newATD) : timeDirectionObject(TimeDirectionObject(newATD)), mobileObject(MobileObject(newXSpeed,newYSpeed)), object(ObjectSkeleton(newXPos,newYPos,WIDTH,HEIGHT)) { } Box::~Box() { } void Box::SetPos(const int newXPos, const int newYPos) { object.SetPos(newXPos, newYPos); } void Box::DoGui() { InitGui(); UpdateGui(); } bool Box::DoSelectionCheck() { return object.DoSelectionCheck(); } void Box::SetSelected(const bool newSelected) { object.SetSelected(newSelected); } void Box::InitGui() { timeDirectionObject.InitGui(); object.InitGui(); mobileObject.InitGui(); } void Box::UpdateGui() { timeDirectionObject.UpdateGui(); object.UpdateGui(); mobileObject.UpdateGui(); } void Box::DoDraw() { draw_sprite(buffer, box_sprite, object.GetXPos(), object.GetYPos()); if(object.IsSelected()) { rect(buffer,object.GetXPos(),object.GetYPos(),object.GetXPos()+WIDTH,object.GetYPos()+HEIGHT,makecol(255,0,0)); } } int Box::GetXSize() { return(WIDTH); } int Box::GetYSize() { return(HEIGHT); } std::string Box::GetOutputString() { std::string returnString = "<BOX>"; returnString += object.GetOutputStringParts(); returnString += mobileObject.GetOutputStringParts(); returnString += timeDirectionObject.GetOutputStringParts(); returnString += "\n</BOX>"; return(returnString); }
[ [ [ 1, 66 ] ] ]
00605b468697b1e7738f549e6ae4cdb87fd01daf
e183ce20fbe6db6d7459375dad4992d0c8ddbb8f
/Client.cpp
c738afaa36592ee1787834e9b3ae099dab6fa601
[]
no_license
zinking/gedouyouxi
4303fc74c6e30cc1986bd216f0a190fa4788b085
25c07af3028aef1b11d5ada6180c871ce0f5406a
refs/heads/master
2021-01-23T06:35:39.166519
2008-08-05T09:09:03
2008-08-05T09:09:03
32,133,246
0
0
null
null
null
null
GB18030
C++
false
false
3,756
cpp
#include "Client.h" #include <iostream> using namespace std; Client::Client(void) { socket = NULL; IP = new char[100]; cout << "input the target IP address: " << endl; cin >> IP; cout << "input the target PORT: " << endl; cin >> PORT; /*IP = "127.0.0.1"; PORT = 1001;*/ //create the socket and socket2 through the IP and PORT while( !socket ) { try { socket = new MyCSocket(IP, PORT); } catch( MyCSocketException se) { cout << " : Exception => " << se.getText() << "\n"; return; } } cout << "Server Port " << PORT << " Connected." << endl; while( !socket2 ) { try { socket2 = new MyCSocket(IP, PORT + 1); } catch( MyCSocketException se) { cout << " : Exception => " << se.getText() << "\n"; return; } } cout << "Server Port " << PORT + 1 << " Connected." << endl; } //through the param to create the socket, socket2 Client::Client(char* IP, int PORT) { //this->IP = new char[100]; this->IP = IP; this->PORT = PORT; socket = NULL; socket2 = NULL; while( !socket ) { try { socket = new MyCSocket(this->IP, this->PORT); } catch( MyCSocketException se) { cout << " : Exception => " << se.getText() << "\n"; return; } } cout << "Server Port " << PORT << " Connected." << endl; while( !socket2 ) { try { socket2 = new MyCSocket(this->IP, this->PORT + 1); } catch( MyCSocketException se) { cout << " : Exception => " << se.getText() << "\n"; return; } } cout << "Server Port " << PORT + 1 << " Connected." << endl; } Client::~Client(void) { } void Client::write(char* str) { socket->Write(str, strlen(str)); } //void Client::write( void* stateCommand ) //{ // //char strCommand[10]; // //itoa(stateCommand,strCommand,10); // socket->Write( strCommand, strlen( strCommand )); //} //void Client::read( int stateCommand ) //{ // char strCommand[10]; // memset(strCommand,0,10); // socket->Read(strCommand //} void Client::read(char * str) { memset( str, 0, 100); socket->Read(str, 100); } //从SOCKET读出数据放入STR void Client::write2(char* str) { socket2->Write(str, strlen(str)); } //从SOCKET读出数据放入STR void Client::read2(char* str) { memset( str, 0, 100); socket2->Read(str, 100); } DataPackage Client::readDataPack(DataPackage* d) { char* str = new char[100]; for(int i = 0 ; i < 9 ; i++) { read2(str);//读出一个数据 if(!str) break; if(!strcmp(str, "EXIT")) exit(0); if(str[0] == 'a') { d->IsServer = d->castCharPtrToBool(str + 1); } else if(str[0] == 'b') { d->pos.x = d->castCharPtrToFloat(str + 1); } else if(str[0] == 'c') { d->pos.y = d->castCharPtrToFloat(str + 1); } else if(str[0] == 'd') { d->height = d->castCharPtrToFloat(str + 1); } else if(str[0] == 'e') { d->HorState = d->castCharPtrToInt(str + 1); } else if(str[0] == 'f') { d->VerState = d->castCharPtrToInt(str + 1); } else if(str[0] == 'g') { d->rotation = d->castCharPtrToFloat(str + 1); } else if(str[0] == 'h') { d->frame = d->castCharPtrToInt(str + 1); } else if(str[0] == 'i') { d->sequence = d->castCharPtrToInt(str + 1);//效率是相当....完全可以用HASHMAP } write2(str);//这个读出来,然后又写回去,是怎么一回事呢?STR并没有被修改 } delete str;//做什么 似乎是解析了一个Socket命令然后封回了DP //从设计上来讲这不应该是Client的方法,应该是DP的方法,DP去解析一个数据字节流么 return d;//居然没报错,和返回类型不匹配啊 }
[ "zinking3@a02204cc-6053-0410-81e9-d35f966e8b48" ]
[ [ [ 1, 193 ] ] ]
cc295f4a31c465c03dc08f8c05a1491c7a45391b
c70941413b8f7bf90173533115c148411c868bad
/core/src/vtxFile.cpp
71db0bcc21e7e6de950166022c33c2549015932b
[]
no_license
cnsuhao/vektrix
ac6e028dca066aad4f942b8d9eb73665853fbbbe
9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a
refs/heads/master
2021-06-23T11:28:34.907098
2011-03-27T17:39:37
2011-03-27T17:39:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,306
cpp
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "vtxFile.h" #include "vtxAtlasPacker.h" #include "vtxEventListener.h" #include "vtxFileEvent.h" #include "vtxFileManager.h" #include "vtxFileStream.h" #include "vtxFontManager.h" #include "vtxFontResource.h" #include "vtxImageResource.h" #include "vtxLogManager.h" #include "vtxMaterialResource.h" #include "vtxMovieClipResource.h" #include "vtxResource.h" #include "vtxShapeResource.h" #include "vtxSubshapeResource.h" namespace vtx { //----------------------------------------------------------------------- File::File(const String& filename) : mFilename(filename), mLoadingState(FLS_LOADING), mScriptEngineFactory(""), mMainMovieClip(NULL), mMainResource(NULL) { ShapeResource* black_box = new ShapeResource("BlackBox"); MaterialResource* material = new MaterialResource("BlackBox_Material", MaterialResource::MT_COLOR); material->setColor(Color(0.0f, 0.0f, 0.0f, 0.5f)); const float dimensions = 1.0f; BoundingBox box(Vector2::ZERO, Vector2(dimensions, dimensions)); black_box->setBoundingBox(box); SubshapeResource* subshape = new SubshapeResource(); subshape->setMaterial(material); black_box->_injectScale(Vector2(32, 32)); // counter-clockwise default rect // TOP-LEFT subshape->addShapeElement( ShapeElement(ShapeElement::SID_MOVE_TO, 0.0f, 0.0f)); // BOTTOM-LEFT subshape->addShapeElement( ShapeElement(ShapeElement::SID_LINE_TO, 0.0f, dimensions)); // BOTTOM-RIGHT subshape->addShapeElement( ShapeElement(ShapeElement::SID_LINE_TO, dimensions, dimensions)); // TOP-RIGHT subshape->addShapeElement( ShapeElement(ShapeElement::SID_LINE_TO, dimensions, 0.0f)); // TOP-LEFT subshape->addShapeElement( ShapeElement(ShapeElement::SID_LINE_TO, 0.0f, 0.0f)); black_box->addSubshapeResource(subshape); // add resources addResource(material); addResource(black_box); } //----------------------------------------------------------------------- File::~File() { // destroy internal resources ResourceMap::iterator it = mResources.begin(); ResourceMap::iterator end = mResources.end(); while(it != end) { if(it->second != mMainMovieClip) delete it->second; ++it; } delete mMainMovieClip; } //----------------------------------------------------------------------- const String& File::getFilename() const { return mFilename; } //----------------------------------------------------------------------- void File::setHeader(const FileHeader& header) { mHeader = header; } //----------------------------------------------------------------------- const File::FileHeader& File::getHeader() { return mHeader; } //----------------------------------------------------------------------- void File::setScriptEngine(const String& scriptEngineFactory) { mScriptEngineFactory = scriptEngineFactory; } //----------------------------------------------------------------------- const String& File::getScriptEngine() { return mScriptEngineFactory; } //----------------------------------------------------------------------- void File::setMainMovieClip(MovieClipResource* movieclip) { mMainMovieClip = movieclip; } //----------------------------------------------------------------------- MovieClipResource* File::getMainMovieClip() { return mMainMovieClip; } //----------------------------------------------------------------------- void File::addResource(Resource* res) { ResourceMap::iterator it = mResources.find(res->getID()); if(it != mResources.end()) { VTX_EXCEPT("\"%s\": Tried to add Resource with id \"%s\" twice!", mFilename.c_str(), res->getID().c_str()); return; } res->_setFile(this); mResources[res->getID()] = res; mResourcesByType[res->getType()].push_back(res); if(res->getType() == "Font") { FontResource* font = static_cast<FontResource*>(res); mFonts[font->getName()] = font; } FileEvent evt(FileEvent::RESOURCE_ADDED, res); for_each(it, ListenerMap, mListeners) it->second->eventFired(evt); #ifdef _DEBUG //VTX_LOG("\"%s\": Added resource with id \"%s\" of type \"%s\"", // mFilename.c_str(), // res->getID().c_str(), res->getType().c_str()); #endif } //----------------------------------------------------------------------- Resource* File::getResource(const String& id, const String& requested_type) { ResourceMap::iterator it = mResources.find(id); if(it != mResources.end()) { if(requested_type.length()) { if(it->second->getType() == requested_type) return it->second; } else return it->second; } if(requested_type == "Font") return FontManager::getSingletonPtr()->getFont(id); return NULL; } //----------------------------------------------------------------------- const ResourceList& File::getResourcesByType(const String& type) const { ResourceTypeMap::const_iterator it = mResourcesByType.find(type); if(it != mResourcesByType.end()) { return it->second; } static ResourceList empty; return empty; } //----------------------------------------------------------------------- const ResourceMap& File::getResources() const { return mResources; } //----------------------------------------------------------------------- FontResource* File::getFontByName(const String& font_name) { FontMap::iterator it = mFonts.find(font_name); if(it != mFonts.end() && it->second->getGlyphList().size()) return it->second; return FontManager::getSingletonPtr()->getFont(font_name); } //----------------------------------------------------------------------- bool File::addListener(EventListener* listener) { ListenerMap::iterator it = mListeners.find(listener); if(it == mListeners.end()) { mListeners.insert(std::make_pair(listener, listener)); return true; } return false; } //----------------------------------------------------------------------- bool File::removeListener(EventListener* listener) { ListenerMap::iterator it = mListeners.find(listener); if(it != mListeners.end()) { mListeners.erase(it); return true; } return false; } //----------------------------------------------------------------------- void File::_loadingCompleted() { FileEvent evt(FileEvent::LOADING_COMPLETED, this); for_each(it, ListenerMap, mListeners) it->second->eventFired(evt); } //----------------------------------------------------------------------- void File::_loadingFailed() { FileEvent evt(FileEvent::LOADING_FAILED, this); for_each(it, ListenerMap, mListeners) it->second->eventFired(evt); } //----------------------------------------------------------------------- }
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 273 ] ] ]
62bea40daa35b2a80d61bbe1040d7399fd98d079
cecdfda53e1c15e7bd667440cf5bf8db4b3d3e55
/Mini_STALKER/animation.h
3d68c1fc0b03568fdd8791745ab3f4dcc309d3fb
[]
no_license
omaskery/mini-stalker
f9f8713cf6547ccb9b5e51f78dfb65a4ae638cda
954e8fce9e16740431743f020c6ddbc866e69002
refs/heads/master
2021-01-23T13:29:26.557156
2007-08-04T12:44:52
2007-08-04T12:44:52
33,090,577
1
0
null
null
null
null
UTF-8
C++
false
false
1,319
h
class animation { std::vector<SDL_Surface *> frames; unsigned int timer, delay; int *bind_x, *bind_y; int x,y,current; SDL_Rect my_rect; public: animation(const std::string &file) : timer(clock()) { std::ifstream f(file.c_str()); if(!f) return; int count; f >> delay >> count; f.ignore(); for(int i = 0; i < count; ++i) { std::string buffer; std::getline(f,buffer); SDL_Surface *temp = SDL_LoadBMP(buffer.c_str()); if(temp) { SDL_SetColorKey(temp,SDL_SRCCOLORKEY|SDL_RLEACCEL,SDL_MapRGB(temp->format,255,0,255)); frames.push_back(temp); } else { printf("unable to load animation sprite %s for animation %s.\n",buffer.c_str(),file.c_str()); } } f.close(); } void draw(SDL_Surface *dest) { if(clock()-timer >= delay) { ++current; timer = clock(); if(current >= frames.size()) current = 0; } if(bind_x) my_rect.x = *bind_x; if(bind_y) my_rect.y = *bind_y; SDL_BlitSurface(frames[current],NULL,dest,&my_rect); } void setPosition(int X, int Y) { x = X; y = Y; my_rect.x = x; my_rect.y = y; } void setPosition(int *X, int *Y) { bind_x = X; bind_y = Y; my_rect.x = *X; my_rect.y = *Y; if(!X) my_rect.x = x; if(!Y) my_rect.y = Y; } };
[ "ollie.the.pie.lord@823218a8-ad34-0410-91fc-f9441fec9dcb" ]
[ [ [ 1, 69 ] ] ]
fa7946fd9ac09cb4fd772aca89ba8670dd1d5f54
0050b168757b3c0a0bac6ecdc6e7c3cc1e01201c
/MyRobot.cpp
51edddfd84a246d0861cdb422f9e13984153d396
[]
no_license
nerdherd/FRC-2011
91b962c69b498218a1fb544a41034164bcacb311
9c963e8defaa5925a485dbaa946d92175c23bc40
refs/heads/master
2021-01-22T05:00:38.754476
2011-11-22T04:47:34
2011-11-22T04:47:34
2,825,406
0
0
null
null
null
null
UTF-8
C++
false
false
16,554
cpp
#include "WPILib.h" #include <iostream> using namespace std; #define NDEBUG #ifndef NDEBUG #define debug(x) \ std::cerr << __LINE__ << ": " << x << std::endl; #else #define debug(x) {} #endif class lowPass { private: float lastValue; float change; float last; public: lowPass(float c):lastValue(0), change(c) {} float operator () (float value, CANJaguar* jag) { lastValue = lastValue + (value - lastValue) * change; if(jag) jag->Set(lastValue); return lastValue; } float operator () (float value) { return lastValue = lastValue + (value - lastValue) * change; } float geto (float value) { return lastValue = lastValue + (value - lastValue) * (abs(lastValue) - abs(value) > 0 ? .9 : change); } }; class SimplePID { private: double last_error; double integral; double P,I,D; //char count; public: SimplePID (double p, double i, double d): last_error(0), integral(0) ,P(p), I(i), D(d) {} float operator () (double target, double at) { double error = target - at; integral+= error; double derivative = error - last_error; last_error = error; // if(count++%30==0) cerr << error << '\t' << integral; if(integral < -25) integral = -25; if(integral > 25) integral = 25; return P*error + I*integral + D*derivative; } }; class RobotSystem : public SimpleRobot { //RobotDrive myRobot; // robot drive system bool robotInted; Joystick stick; // only joystick Joystick stick2; CANJaguar *Dlf, *Dlb, *Drf, *Drb, *arm1, *arm1_sec, *arm2; DigitalInput line1, line2, line3; Task updateCAN, cameraTask; Compressor compressor; Encoder EncArm, EncClaw; SimplePID PIDArm, PIDClaw; lowPass LowArm; Solenoid MiniBot1a, MiniBot1b, MiniBot2a, MiniBot2b, ClawOpen, ClawClose; //Relay MiniBot1, MiniBot2, ClawGrip; DigitalInput LimitClaw, LimitArm; Timer miniBotTime; float ShoulderArmCurrent; public: RobotSystem(void): robotInted(false) ,stick(1) // as they are declared above. ,stick2(2) ,line1(10) ,line2(11) ,line3(12) //,camera(AxisCamera::GetInstance()) ,updateCAN("CANUpdate",(FUNCPTR)UpdateCAN) ,cameraTask("CAMERA", (FUNCPTR)CameraTask) ,compressor(14,1) ,EncArm(2,3) ,EncClaw(5,6) ,PIDArm(.04,0,0) // .002, .033 ,PIDClaw(.014,.0000014,0) ,LowArm(.1) /* ,MiniBot1(4) ,MiniBot2(2) ,ClawGrip(3) */ ,MiniBot1a(8,1) ,MiniBot1b(8,2) ,MiniBot2a(8,3) ,MiniBot2b(8,4) ,ClawOpen(8, 8) ,ClawClose(8,7) ,LimitClaw(7) ,LimitArm(13) { // myRobot.SetExpiration(0.1); GetWatchdog().SetEnabled(false); GetWatchdog().SetExpiration(1); compressor.Start(); debug("Waiting to init CAN"); Wait(2); Dlf = new CANJaguar(6,CANJaguar::kSpeed); Dlb = new CANJaguar(3,CANJaguar::kSpeed); Drf = new CANJaguar(7,CANJaguar::kSpeed); Drb = new CANJaguar(2,CANJaguar::kSpeed); arm1 = new CANJaguar(5); arm1_sec = new CANJaguar(8); arm2 = new CANJaguar(4); EncArm.SetDistancePerPulse(.00025); EncClaw.SetDistancePerPulse(.00025); EncClaw.SetReverseDirection(false); EncArm.SetReverseDirection(true); EncArm.Reset(); EncClaw.Reset(); updateCAN.Start((int)this); //cameraTask.Start((int)this); EncArm.Start(); EncClaw.Start(); debug("done initing"); } ~RobotSystem() { debug("Deleting robot"); updateCAN.Stop(); cameraTask.Stop(); } static int UpdateCAN (RobotSystem *self) { char count=0; // runs at 28.5Hz double lastTime=0; while(true) { Wait(.035 - (GetClock() - lastTime)); lastTime = GetClock(); if(self->IsEnabled()) { CANJaguar::UpdateSyncGroup(2); CANJaguar::UpdateSyncGroup(3); } /* if(count++%10==0) { self->ShoulderArmCurrent = self->arm1->GetOutputCurrent(); } */ } return 0; } static int CameraTask (RobotSystem *self) { //AxisCamera &camera = AxisCamera::GetInstance(); while(true) { Wait(.08); //if(camera.IsFreshImage()) {} } return 0; } float range (float f) { if(f > 1.0) return 1.0; if(f < -1.0) return -1.0; if(f < .1 && f > -.1) return 0; return f; } void RobotInit(void) { debug("Robot init"); //AxisCamera &camera = AxisCamera::GetInstance(); //endTask(); //camera.WriteResolution(AxisCamera::kResolution_320x240); //camera.WriteCompression(20); //camera.WriteBrightness(0); //camera.WriteMaxFPS(15); } void initRobot () { cerr << "running init\n"; Dlf->EnableControl(0); Dlb->EnableControl(0); Drf->EnableControl(0); Drb->EnableControl(0); arm1->EnableControl(); arm1_sec->EnableControl(); arm2->EnableControl(); Dlf->ConfigEncoderCodesPerRev(250); Dlf->SetPID(1,0,0); Dlb->ConfigEncoderCodesPerRev(250); Dlb->SetPID(1,0,0); Drf->ConfigEncoderCodesPerRev(250); Drf->SetPID(1,0,0); Drb->ConfigEncoderCodesPerRev(250); Drb->SetPID(1,0,0); Wait(.1); if(robotInted==false) { int count=220; arm2->Set(-.3); while(count-->0 && LimitClaw.Get() == 1) Wait(.005); arm2->Set(.15); while(count-->0 && LimitClaw.Get() == 0) Wait(.005); arm2->Set(0); if(count>0) EncClaw.Reset(); arm1->Set(-.3); arm1_sec->Set(-.3); while(count-->0 && LimitArm.Get() == 1) Wait(.005); arm1->Set(.5); arm1_sec->Set(.5); while(count-->0 && LimitArm.Get() == 0) Wait(.005); if(count>0) EncArm.Reset(); arm1->Set(0); arm1_sec->Set(0); robotInted = true; } } void Disabled (void) { debug("disable"); Dlf->StopMotor(); Dlb->StopMotor(); Drf->StopMotor(); Drb->StopMotor(); } void Arm(double joy) { int location = EncArm.Get(); /* if(location < 10 && joy < 0) joy = 0; if(location > 110 && joy > 0) joy = 0; arm1->Set(joy); arm1_sec->Set(joy); return; */ if(joy < -10) joy = -10; if(joy > 110) joy = 110; double speed = PIDArm(joy, location); if(speed > .5) speed = .5; if(speed < -.3) speed = -.3; if(speed < 0 && location < 10) speed = 0; if(speed > 0 && location > 110) speed = 0; speed = LowArm(speed); if(speed < .01 && speed > -.01) speed = 0; arm1->Set(speed,3); arm1_sec->Set(speed,3); } void Claw(double joy) { if(joy < 10) joy = 10; if(joy > 230) joy = 230; int location = EncClaw.Get(); double speed = PIDClaw(joy, location); //if(location < 15) speed *= .2; if(speed > .32) speed = .32; if(speed < -.32) speed = -.32; if(speed < .1 && speed > -.1) speed = 0; arm2->Set(speed,2); } void Drive (float speed, float turn, float strafe) { Dlf->Set(range(speed + turn + strafe)*250, 2); Dlb->Set(range(speed + turn - strafe)*250, 2); Drf->Set(range(-speed + turn + strafe)*250, 2); Drb->Set(range(-speed + turn - strafe)*250, 2); //CANJaguar::UpdateSyncGroup(2); } void Autonomous(void) { GetWatchdog().SetEnabled(false); AxisCamera &camera = AxisCamera::GetInstance(); initRobot(); #ifdef NDEBUG //return; #endif debug("in auto"); Wait(1.0); int count=0; Wait(.5); Arm(0); Claw(0); /* Drive(.25, 0,0); Wait(3); Drive(0,0,0); return;*/ Drive(.25, 0, 0); while(IsAutonomous() && count++ < 280 && !IsDisabled()) { Arm(60); Claw(90); /* bool l1 = line1.Get(); bool l2 = line2.Get(); bool l3 = line3.Get(); cerr << l1 << '\t' << l2 << '\t' << l3 << endl; if(l1 && l2 && l3) { count=310; break; }else if(l1 && l2) { Drive(.1, -.25, 0); }else if(l3 && l2) { Drive(.1,.25, 0); }else if(l3 && l1) { count -= 100; Drive(.1, .6, 0); }else if(l2) { Drive(.25,0,0); }else if(l1) { Drive(0,0,-.3); }else if(l3) { Drive(0,0,.3); }else{ //Wait(.02); //Drive(.1,0,0); }*/ Wait(0.01); } while(IsAutonomous() && count++ < 310 && !IsDisabled()) { Drive(.001,0,0); Arm(60); Claw(95); Wait(.01); } ClawOpen.Set(true); ClawClose.Set(false); while(IsAutonomous() && count++ < 330 && !IsDisabled()) { Arm(55); Claw(95); Drive(0,0,0); Wait(.01); } while(IsAutonomous() && count++ < 600 && !IsDisabled()) { Arm(50); Claw(95); Drive(-.1,0,0); Wait(.01); } Wait(.1); ClawOpen.Set(false); ClawClose.Set(true); while(IsAutonomous() && count++ < 800 && !IsDisabled()) { Arm(0); Claw(0); Drive(-.1,0,0); Wait(.01); } while(IsAutonomous() && !IsDisabled()) { Drive(0,0,0); Claw(0); Arm(0); } } /** * Runs the motors with arcade steering. */ void OperatorControl(void) { AxisCamera &camera = AxisCamera::GetInstance(); miniBotTime.Start(); initRobot(); debug("in telop"); compressor.Start(); GetWatchdog().SetEnabled(true); /*int l1, l2, l3; while (IsOperatorControl()) { GetWatchdog().Feed(); //char val = (line1.Get() & 0x01) | (line2.Get() & 0x02) | (line3.Get() & 0x04); //if(l1 != line1.Get() || l2 != line2.Get() || l3 != line3.Get()) { // cerr << "change " << (l1 = line1.Get()) << "\t" << (l2 = line2.Get()) << "\t" << (l3 = line3.Get()) << endl; //} cerr << "Change "<< line1.Get() <<"\t" << line2.Get() << "\t" << line3.Get() << endl; Wait(0.2); }*/ char count=0, pneumaticCount=0; // was .125 when loop at .025 lowPass lowSpeed(.04), lowStrafe(.04), lowTurn(.04), lowClaw(.04), lowArm(.04), lowArmLoc(.05); double ClawLocation=0, ArmLocation=0, OldArmLocation=0; while (IsOperatorControl() && !IsDisabled()) { GetWatchdog().Feed(); float speed = -1*stick.GetRawAxis(2); float strafe = stick.GetRawAxis(1); float turn = stick.GetRawAxis(3); if(!stick.GetRawButton(7)) { speed /= 2; strafe /= 2; turn /= 2; } if(stick.GetRawButton(8)) { speed /= 2; strafe /= 2; turn /= 2; } if(stick.GetRawButton(2)) { speed = 0; turn = 0; } Drive(lowSpeed(speed), lowTurn(turn), lowStrafe(strafe)); #ifndef NDEBUG if(stick2.GetRawButton(10)) { robotInted = false; initRobot(); } #endif if(stick2.GetRawButton(7) && (miniBotTime.Get() >= 110 || (stick2.GetRawButton(9) && stick2.GetRawButton(10)))) { // launcher // the quick launcher MiniBot1a.Set(true); MiniBot1b.Set(false); } if(!stick2.GetRawButton(10) && stick2.GetRawButton(9)) { // deploy in MiniBot2a.Set(false); MiniBot2b.Set(true); //MiniBot2a.Set(false); //MiniBot2b.Set(true); } if(stick2.GetRawButton(5)) { // top deploy out MiniBot2a.Set(true); MiniBot2b.Set(false); } if(stick2.GetRawButton(6)) { // open ClawOpen.Set(true); ClawClose.Set(false); } if(stick2.GetRawButton(8)) { // closed ClawOpen.Set(false); ClawClose.Set(true); ClawLocation += 2; } /*156 straight * 56 90 angle * 10 back */ if(stick2.GetRawButton(1)) { // top peg ClawLocation = 156; ArmLocation = 105; } if(stick2.GetRawButton(2)) { ClawLocation = 111; // the 90angle / middle peg ArmLocation = 50; } if(stick2.GetRawButton(3)) { // off ground ClawLocation = 176; ArmLocation = 5; } if(stick2.GetRawButton(4)) { ClawLocation = 0; // back ArmLocation = 0; } double tmpClaw = .7*lowClaw(stick2.GetRawAxis(4)); if(tmpClaw < .2 && tmpClaw > -.2) tmpClaw = 0; double tmpArm = .4*lowArm(-1*stick2.GetRawAxis(2)); if(tmpArm < .2 && tmpArm > -.2) tmpArm = 0; if(tmpArm > .5) tmpArm = .5; if(tmpArm < -.5) tmpArm = -.5; ClawLocation += tmpClaw + tmpArm; // the right joy stick y if(ClawLocation < 10) ClawLocation = 10; if(ClawLocation > 230) ClawLocation = 230; Claw(ClawLocation); ArmLocation += tmpArm; if(ArmLocation > 110) ArmLocation = 110; if(ArmLocation < -10) ArmLocation = -10; Arm(lowArmLoc(ArmLocation)); OldArmLocation = ArmLocation; #ifndef NDEBUG if(count++%20==0){ cerr << EncClaw.Get() << '\t' << arm1->GetOutputCurrent() << '\t' << arm1_sec->GetOutputCurrent() << '\t' << ArmLocation << '\t' << EncArm.Get() << endl; // cerr << arm1->GetOutputCurrent() << '\t' << arm1_sec->GetOutputCurrent() << '\t' << arm2->GetOutputCurrent() << '\t' // << EncArm.Get () << '\t' << LimitArm.Get() << '\t' << EncClaw.Get() << '\t' << LimitClaw.Get() << '\t' << ClawLocation << endl; //cerr << '\t' << EncArm.Get() <<'\t' << arm1->Get() << endl; // cerr << Dlf->Get() << '\t' << Dlf->GetSpeed() << '\t' << Dlb->GetSpeed() <<'\t' << Drf->GetSpeed() <<'\t' << Drb->GetSpeed() <<endl;//'\t' << line1.Get() << "\t" << line2.Get() << "\t" << line3.Get() << endl; // cerr << '\t' << Dlb->GetSpeed() << '\t'; } #endif if(pneumaticCount++==0) { ClawOpen.Set(false); ClawClose.Set(false); MiniBot1a.Set(false); MiniBot1b.Set(false); MiniBot2a.Set(false); MiniBot2b.Set(false); } Wait(0.01); // wait for a motor update time } } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class PnumaticArmTest : public SimpleRobot { private: Joystick stick; Solenoid up, down; Encoder enc; SimplePID pid; lowPass low; public: PnumaticArmTest (void): stick(1) ,up(7,7) ,down(7,8) ,enc(1,2) ,pid(.045,.00000,.16) ,low(.05) { enc.SetReverseDirection(true); enc.Start(); } void OperatorControl(void) { char count=0; double target = 0, speed = 0; while(!IsDisabled()) { double tmpStick = -1*stick.GetRawAxis(2); if(tmpStick < .2 && tmpStick > -.2) tmpStick=0; target += tmpStick*1.5; int location = enc.GetRaw(); if(stick.GetRawButton(5)) { up.Set(true); down.Set(false); }else if(stick.GetRawButton(7) && location > 0) { down.Set(true); up.Set(false); }else if(stick.GetRawButton(8)) { down.Set(true); up.Set(false); }else if(stick.GetRawButton(9)){ speed = pid(target, location); if(speed > 1) { up.Set(true); down.Set(false); }else if(speed < -1) { up.Set(false); down.Set(true); }else{ up.Set(false); down.Set(false); } }else if(stick.GetRawButton(10)) { enc.Reset(); }else{ up.Set(false); down.Set(false); } if(stick.GetRawButton(1)) target = 2; if(stick.GetRawButton(4)) target = 400; if(stick.GetRawButton(3)) target = 200; if(stick.GetRawButton(2)) target = 70; Wait(.02); while(count++%30==0) cerr << location << '\t' << target << '\t' << speed << endl; } } }; class OldRobotDemo : public SimpleRobot { private: CANJaguar *Dlf, *Dlb, *Drb, *Drf; Joystick stick; lowPass speed, turn, strafe; public: OldRobotDemo (void) : stick(1), speed(.05), turn(.05), strafe(.05) { Wait(3.0); Dlf = new CANJaguar(4); Dlb = new CANJaguar(5); Drf = new CANJaguar(3); Drb = new CANJaguar(2); } void OperatorControl(void) { while(!IsDisabled()) { GetWatchdog().Feed(); float speed = stick.GetRawAxis(2); float strafe = -1*stick.GetRawAxis(1); float turn = -1*stick.GetRawAxis(3); Dlf->Set(speed + turn + strafe); Dlb->Set(speed + turn - strafe); Drf->Set(-speed + turn + strafe); Drb->Set(-speed + turn - strafe); Wait(.05); } } }; //START_ROBOT_CLASS(OldRobotDemo); START_ROBOT_CLASS(RobotSystem); //START_ROBOT_CLASS(PnumaticArmTest); extern "C" INT32 FRC_ROBOT_START () { return FRC_UserProgram_StartupLibraryInit(); }
[ [ [ 1, 666 ] ] ]
f7c8e493709568535c483948b85f8e207420b5a0
eec9d789e04bc81999ac748ca2c70f0a612dadb7
/testProject/testProject/LeftPanelView.cpp
bdb0ce3df30986070863ab831164e8654fee689f
[]
no_license
scriptkitz/myfirstpro-test
45d79d9a35fe5ee1e8f237719398d08d7d86b859
a3400413e3a7900657774a278006faea7d682955
refs/heads/master
2021-01-22T07:13:27.100583
2010-11-16T15:02:50
2010-11-16T15:02:50
38,792,869
0
0
null
null
null
null
UTF-8
C++
false
false
1,954
cpp
// LeftPanelView.cpp : implementation file // #include "stdafx.h" #include "testProject.h" #include "LeftPanelView.h" // CLeftPanelView IMPLEMENT_DYNCREATE(CLeftPanelView, CListView) CLeftPanelView::CLeftPanelView() { } CLeftPanelView::~CLeftPanelView() { } BEGIN_MESSAGE_MAP(CLeftPanelView, CListView) END_MESSAGE_MAP() // CLeftPanelView diagnostics #ifdef _DEBUG void CLeftPanelView::AssertValid() const { CListView::AssertValid(); } #ifndef _WIN32_WCE void CLeftPanelView::Dump(CDumpContext& dc) const { CListView::Dump(dc); } #endif #endif //_DEBUG // CLeftPanelView message handlers BOOL CLeftPanelView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Add your specialized code here and/or call the base class cs.style |= LVS_REPORT; return CListView::PreCreateWindow(cs); } BOOL CLeftPanelView::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext) { // TODO: Add your specialized code here and/or call the base class return CListView::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID, pContext); } void CLeftPanelView::OnUpdate(CView* /*pSender*/, LPARAM /*lHint*/, CObject* /*pHint*/) { // TODO: Add your specialized code here and/or call the base class ASSERT(GetStyle() & LVS_REPORT); CListCtrl& listCtrl = GetListCtrl(); // Insert a column. This override is the most convenient. listCtrl.InsertColumn(0, _T("Player Name"), LVCFMT_LEFT); // The other InsertColumn() override requires an initialized // LVCOLUMN structure. LVCOLUMN col; col.mask = LVCF_FMT | LVCF_TEXT; col.pszText = _T("Jersey Number"); col.fmt = LVCFMT_LEFT; listCtrl.InsertColumn(1, &col); // Set reasonable widths for our columns listCtrl.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER); listCtrl.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER); }
[ "scriptkitz@da890e6b-1f8b-8dbb-282d-e1a1f9b2274c" ]
[ [ [ 1, 83 ] ] ]
00c2293784f11a7febca0836060d4bec80ce33f0
9738ebb36adfaa6f06fe2ba452aec6fcb8a06a5e
/heimdall/source/EndFileTransferPacket.h
a67eeaa76339215f29fcf3c5ad7ca946f660105e
[ "MIT" ]
permissive
superweapons/Heimdall-fc
9f4ea33e4da6ffd209a7fb7afa51616eb2007832
73d77ddbf2f26c2d416b0ef4a57040e64ad86df2
refs/heads/master
2021-01-15T19:39:54.452631
2011-11-16T02:54:26
2011-11-16T02:54:26
2,785,073
1
1
null
null
null
null
UTF-8
C++
false
false
3,472
h
/* Copyright (c) 2010-2011 Benjamin Dobell, Glass Echidna Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #ifndef ENDFILETRANSFERPACKET_H #define ENDFILETRANSFERPACKET_H // Heimdall #include "FileTransferPacket.h" namespace Heimdall { class EndFileTransferPacket : public FileTransferPacket { public: enum { kDestinationPhone = 0x00, kDestinationModem = 0x01 }; protected: enum { kDataSize = FileTransferPacket::kDataSize + 16 }; private: unsigned int destination; // Chip identifier perhaps unsigned short partialPacketLength; // Length or (length - 65536) if lastFullPacket is odd. unsigned int lastFullPacketIndex; unsigned short unknown1; unsigned int unknown2; protected: EndFileTransferPacket(unsigned int destination, unsigned int partialPacketLength, unsigned int lastFullPacketIndex, unsigned short unknown1, unsigned int unknown2) : FileTransferPacket(FileTransferPacket::kRequestEnd) { this->destination = destination; if (partialPacketLength > 65535) { this->partialPacketLength = (partialPacketLength - 65536); this->lastFullPacketIndex = lastFullPacketIndex + 1; } else { this->partialPacketLength = partialPacketLength; this->lastFullPacketIndex = lastFullPacketIndex; } this->unknown1 = unknown1; this->unknown2 = unknown2; } public: unsigned int GetDestination(void) const { return (destination); } unsigned int GetPartialPacketLength(void) const { if (lastFullPacketIndex % 2 == 0) return (partialPacketLength); else return (partialPacketLength + 65536); } unsigned int GetLastFullPacketIndex(void) const { return (lastFullPacketIndex - lastFullPacketIndex % 2); } unsigned short GetUnknown1(void) const { return (unknown1); } unsigned int GetUnknown2(void) const { return (unknown2); } virtual void Pack(void) { FileTransferPacket::Pack(); PackInteger(FileTransferPacket::kDataSize, destination); PackShort(FileTransferPacket::kDataSize + 4, partialPacketLength); PackInteger(FileTransferPacket::kDataSize + 6, lastFullPacketIndex); PackShort(FileTransferPacket::kDataSize + 10, unknown1); PackInteger(FileTransferPacket::kDataSize + 12, unknown2); } }; } #endif
[ [ [ 1, 1 ] ], [ [ 2, 120 ] ] ]
dcec5ad66611254bf8670ab4ce9f2d9fa887968e
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
/core/jpeg_encoder_t.cpp
5b08288af919ff61c53df8c108d85ff0b9c60ba7
[]
no_license
chenbk85/alcordev
41154355a837ebd15db02ecaeaca6726e722892a
bdb9d0928c80315d24299000ca6d8c492808f1d5
refs/heads/master
2021-01-10T13:36:29.338077
2008-10-22T15:57:50
2008-10-22T15:57:50
44,953,286
0
1
null
null
null
null
UTF-8
C++
false
false
3,144
cpp
#include "alcor/core/jpeg_encoder_t.h" #include "alcor/core/core.h" #include "alcor/core/detail/jpeg_encoder_impl.cpp" //------------------------------------------------------------------------ #include <boost/bind.hpp> //------------------------------------------------------------------------ namespace all { namespace core { //------------------------------------------------------------------------ jpeg_encoder_t::jpeg_encoder_t() { } //------------------------------------------------------------------------ /// void jpeg_encoder_t::reset ( all::core::rgb_t , interleaved_t, int height, int width) { printf("Resetting dimensions to: H: %d W: %d\n", height, width); printf("Ordering: Interleaved\n"); impl.reset(new detail::jpeg_encoder_impl(height, width, 3)); encode = boost::bind(&jpeg_encoder_t::encode_interleaved, this, _1, _2); } //------------------------------------------------------------------------ /// void jpeg_encoder_t::reset(all::core::rgb_t, planar_t, int height, int width) { printf("Resetting dimensions to: H: %d W: %d\n", height, width); printf("Ordering: Planar\n"); impl.reset(new detail::jpeg_encoder_impl(height, width, 3)); encode = boost::bind(&jpeg_encoder_t::encode_planar, this, _1, _2); } //------------------------------------------------------------------------ /// void jpeg_encoder_t::reset(all::core::gray_t, int height, int width) { printf("Resetting dimensions to: H: %d W: %d\n", height, width); impl.reset(new detail::jpeg_encoder_impl(height, width, 1)); encode = boost::bind(&jpeg_encoder_t::encode_interleaved, this, _1, _2); } //------------------------------------------------------------------------ //------------------------------------------------------------------------ //------------------------------------------------------------------------ core::jpeg_data_t jpeg_encoder_t::encode_interleaved( all::core::uint8_sarr to_encode, int quality) { core::jpeg_data_t ret; impl->encode_interleaved_impl_(ret, to_encode, quality); return ret; } //------------------------------------------------------------------------ core::jpeg_data_t jpeg_encoder_t::encode_planar( all::core::uint8_sarr to_encode, int quality) { core::jpeg_data_t ret; impl->encode_planar_impl_(ret, to_encode, quality); return ret; } ////------------------------------------------------------------------------ //------------------------------------------------------------------------ }}//namespace all::core
[ "andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81" ]
[ [ [ 1, 85 ] ] ]
e628893b9c80aa84cc9a9f8f90a47b95432d96f1
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/SceneData/Attributes/hkxAnimatedFloat.h
99fcad6b03dbac820c42ed003b032d74900cb577
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
2,149
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_SCENEDATA_HKX_ANIMATED_FLOAT_H #define HK_SCENEDATA_HKX_ANIMATED_FLOAT_H #include <Common/SceneData/Attributes/hkxAttribute.h> extern const hkClass hkxAnimatedFloatClass; /// An hkxAnimatedFloat stores the values associated with an hkxAttribute of type float. class hkxAnimatedFloat : public hkReferencedObject { //+vtable(true) //+version(1) public: HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_SCENE_DATA ); HK_DECLARE_REFLECTION(); hkxAnimatedFloat() {} hkxAnimatedFloat(hkFinishLoadedObjectFlag f) : hkReferencedObject(f), m_floats(f) {} /// The array of sampled floats. Array can be of length 1 for not animated, /// or one per frame so assumes that the value is then fully sampled. hkArray<float> m_floats; /// Usage hint so that automatic transform filters can attempt /// to change the value in a sensible way. hkEnum< hkxAttribute::Hint,hkUint8> m_hint; }; #endif // HK_SCENEDATA_HKX_ANIMATED_FLOAT_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 53 ] ] ]
4942e5797f5bb7f2932b85397bba0cfb4c58e731
96e96a73920734376fd5c90eb8979509a2da25c0
/C3DE/Patch.cpp
a7b7d07af5bc8b3718f9ad14e8c1503657430371
[]
no_license
lianlab/c3de
9be416cfbf44f106e2393f60a32c1bcd22aa852d
a2a6625549552806562901a9fdc083c2cacc19de
refs/heads/master
2020-04-29T18:07:16.973449
2009-11-15T10:49:36
2009-11-15T10:49:36
32,124,547
0
0
null
null
null
null
UTF-8
C++
false
false
2,245
cpp
#include "Patch.h" Patch::Patch() { m_pDevice = NULL; m_pMesh = NULL; } Patch::~Patch() { Release(); } void Patch::Release() { if(m_pMesh != NULL) m_pMesh->Release(); m_pMesh = NULL; } void Patch::Render() { //Draw mesh if(m_pMesh != NULL) m_pMesh->DrawSubset(0); } HRESULT Patch::CreateMesh(HeightMap &hm, RECT source, IDirect3DDevice9 *Dev, int index) { m_pDevice = Dev; int width = source.right - source.left; int height = source.bottom - source.top; int nrVert = (width + 1) * (height + 1); int nrTri = width * height * 2; D3DXCreateMeshFVF( nrTri, nrVert, D3DXMESH_MANAGED, TerrainVertex::FVF, m_pDevice, &m_pMesh); TerrainVertex * ver = NULL; m_pMesh->LockVertexBuffer(0, (void**)&ver); for(int z = source.top, z0 = 0; z <= source.bottom; z++, z0++) { for(int x = source.left, x0 = 0; x <= source.right; x++, x0++) { //Calculate vertex color float prc = hm.m_pHeightMap[x + z * hm.m_size.x] / hm.m_maxHeight; int red = 255 * prc; int green = 255 * (1.0f - prc); D3DCOLOR col; if(index % 2 == 0) //Invert color depending on what patch it is... col = D3DCOLOR_ARGB(255, red, green, 0); else col = D3DCOLOR_ARGB(255, green, red, 0); //position D3DXVECTOR3 pos; pos = D3DXVECTOR3(x, hm.m_pHeightMap[x+z*hm.m_size.x], -z); ver[z0*(width+1)+x0] = TerrainVertex(pos, col); } } m_pMesh->UnlockVertexBuffer(); //calculate indices WORD *ind = 0; m_pMesh->LockIndexBuffer(0, (void**)&ind); index = 0; for(int z = source.top, z0 = 0; z < source.bottom; z++, z0++) { for(int x = source.left, x0 = 0; x < source.right; x++, x0++) { //Triangle 1 ind[index++] = z0 * (width+1) + x0; ind[index++] = z0 * (width+1) +x0 + 1; ind[index++] = (z0+1) * (width + 1) + x0; //Triangle 2 ind[index++] = (z0+1) * (width + 1) + x0; ind[index++] = z0 * (width+1) +x0 + 1; ind[index++] = (z0+1) * (width + 1) + x0 +1; } } m_pMesh->UnlockIndexBuffer(); DWORD *att = 0; m_pMesh->LockAttributeBuffer(0, &att); memset(att, 0, sizeof(DWORD)*nrTri); m_pMesh->UnlockAttributeBuffer(); //normals D3DXComputeNormals(m_pMesh, NULL); return 0; }
[ "caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158" ]
[ [ [ 1, 100 ] ] ]
0a0ef1839ea4eb834694ac4cc2246627b69cb84c
97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a
/3dc/avp/win95/Frontend/AvP_MenuGfx.cpp
ce059bb4b42ab37a2e27758c01e7b95c6883abbe
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
SR-dude/AvP-Wine
2875f7fd6b7914d03d7f58e8f0ec4793f971ad23
41a9c69a45aacc2c345570ba0e37ec3dc89f4efa
refs/heads/master
2021-01-23T02:54:33.593334
2011-09-17T11:10:07
2011-09-17T11:10:07
2,375,686
1
0
null
null
null
null
UTF-8
C++
false
false
45,252
cpp
#include "3dc.h" #include "inline.h" #include "tallfont.hpp" #include "strtab.hpp" #include "awTexLd.h" #include "alt_tab.h" #include "chnktexi.h" #include "hud_layout.h" #define UseLocalAssert Yes #include "ourasert.h" #include "ffstdio.h" extern void D3D_RenderHUDString(char *stringPtr,int x,int y,int colour); extern "C" { #include "AvP_Menus.h" extern unsigned char *ScreenBuffer; extern long BackBufferPitch; extern DDPIXELFORMAT DisplayPixelFormat; extern SCREENDESCRIPTORBLOCK ScreenDescriptorBlock; char AAFontWidths[256]; AVPMENUGFX AvPMenuGfxStorage[MAX_NO_OF_AVPMENUGFXS] = { {"Menus\\fractal.rim"}, {"Common\\aa_font.rim"},// Warning! Texture from common used {"Menus\\copyright.rim"}, {"Menus\\FIandRD.rim"}, {"Menus\\presents.rim"}, {"Menus\\AliensVPredator.rim"}, {"Menus\\sliderbar.rim"},//AVPMENUGFX_SLIDERBAR, {"Menus\\slider.rim"},//AVPMENUGFX_SLIDER, {"Menus\\starfield.rim"}, {"Menus\\aliens.rim"}, {"Menus\\Alien.rim"}, {"Menus\\Marine.rim"}, {"Menus\\Predator.rim"}, {"Menus\\glowy_left.rim"}, {"Menus\\glowy_middle.rim"}, {"Menus\\glowy_right.rim"}, // Marine level {"Menus\\MarineEpisode1.rim"}, {"Menus\\MarineEpisode2.rim"}, {"Menus\\MarineEpisode3.rim"}, {"Menus\\MarineEpisode4.rim"}, {"Menus\\MarineEpisode5.rim"}, {"Menus\\MarineEpisode6.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, // Predator level {"Menus\\PredatorEpisode1.rim"}, {"Menus\\PredatorEpisode2.rim"}, {"Menus\\PredatorEpisode3.rim"}, {"Menus\\PredatorEpisode4.rim"}, {"Menus\\PredatorEpisode5.rim"}, {"Menus\\PredatorEpisode5.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, // Alien level {"Menus\\AlienEpisode2.rim"}, {"Menus\\AlienEpisode4.rim"}, {"Menus\\AlienEpisode1.rim"}, {"Menus\\AlienEpisode3.rim"}, {"Menus\\AlienEpisode5.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, {"Menus\\bonus.rim"}, // Splash screens #if MARINE_DEMO {"MarineSplash\\splash00.rim"}, {"MarineSplash\\splash01.rim"}, {"MarineSplash\\splash02.rim"}, {"MarineSplash\\splash03.rim"}, {"MarineSplash\\splash04.rim"}, {"MarineSplash\\splash05.rim"}, #elif ALIEN_DEMO {"AlienSplash\\splash00.rim"}, {"AlienSplash\\splash01.rim"}, {"AlienSplash\\splash02.rim"}, {"AlienSplash\\splash03.rim"}, {"AlienSplash\\splash04.rim"}, {"AlienSplash\\splash05.rim"}, #else {"PredatorSplash\\splash00.rim"}, {"PredatorSplash\\splash01.rim"}, {"PredatorSplash\\splash02.rim"}, {"PredatorSplash\\splash03.rim"}, {"PredatorSplash\\splash04.rim"}, {"PredatorSplash\\splash05.rim"}, #endif }; static void LoadMenuFont(void); static void UnloadMenuFont(void); static int RenderSmallFontString(char *textPtr,int sx,int sy,int alpha, int red, int green, int blue); static void CalculateWidthsOfAAFont(void); extern void DrawAvPMenuGlowyBar(int topleftX, int topleftY, int alpha, int length); extern void DrawAvPMenuGlowyBar_Clipped(int topleftX, int topleftY, int alpha, int length, int topY, int bottomY); static void LoadMenuFont(void) { char buffer[100]; IndexedFont_Kerned_Column :: Create ( IntroFont_Light, // FontIndex I_Font_New, CL_GetImageFileName(buffer, 100, "Menus\\IntroFont.rim", LIO_RELATIVEPATH), 33,//21, // int HeightPerChar_New, 5, // int SpaceWidth_New, 32 // ASCIICodeForInitialCharacter ); } static void UnloadMenuFont(void) { IndexedFont :: UnloadFont( IntroFont_Light ); } extern int LengthOfMenuText(char *textPtr) { IndexedFont* pFont = IndexedFont :: GetFont(IntroFont_Light); return (pFont->CalcSize(textPtr).w); } extern int RenderMenuText(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format) { IndexedFont* pFont = IndexedFont :: GetFont(IntroFont_Light); r2pos R2Pos_StartOfRow; switch(format) { default: GLOBALASSERT("UNKNOWN TEXT FORMAT"==0); case AVPMENUFORMAT_LEFTJUSTIFIED: { // supplied x is correct break; } case AVPMENUFORMAT_RIGHTJUSTIFIED: { x -= (pFont->CalcSize(textPtr).w); break; } case AVPMENUFORMAT_CENTREJUSTIFIED: { x -= (pFont->CalcSize(textPtr).w)/2; break; } } LOCALASSERT(x>0); if (alpha >BRIGHTNESS_OF_DARKENED_ELEMENT) { int size = pFont->CalcSize(textPtr).w - 18; if (size<18) size = 18; DrawAvPMenuGfx(AVPMENUGFX_GLOWY_LEFT,x+18,y-8,alpha,AVPMENUFORMAT_RIGHTJUSTIFIED); DrawAvPMenuGlowyBar(x+18,y-8,alpha,size-18); // for (int i=18; i<size; i++) // DrawAvPMenuGfx(AVPMENUGFX_GLOWY_MIDDLE,x+i,y-8,alpha,AVPMENUFORMAT_LEFTJUSTIFIED); DrawAvPMenuGfx(AVPMENUGFX_GLOWY_RIGHT,x+size,y-8,alpha,AVPMENUFORMAT_LEFTJUSTIFIED); } R2Pos_StartOfRow = r2pos(x,y); { { SCString* pSCString_Name = new SCString(textPtr); pFont -> RenderString_Unclipped ( R2Pos_StartOfRow, // struct r2pos& R2Pos_Cursor, alpha, // int FixP_Alpha, *pSCString_Name // const SCString& SCStr ); pSCString_Name -> R_Release(); } } return R2Pos_StartOfRow.x; } extern int RenderMenuText_Clipped(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format, int topY, int bottomY) { IndexedFont* pFont = IndexedFont :: GetFont(IntroFont_Light); r2pos R2Pos_StartOfRow; switch(format) { default: GLOBALASSERT("UNKNOWN TEXT FORMAT"==0); case AVPMENUFORMAT_LEFTJUSTIFIED: { // supplied x is correct break; } case AVPMENUFORMAT_RIGHTJUSTIFIED: { x -= (pFont->CalcSize(textPtr).w); break; } case AVPMENUFORMAT_CENTREJUSTIFIED: { x -= (pFont->CalcSize(textPtr).w)/2; break; } } LOCALASSERT(x>0); if (alpha > BRIGHTNESS_OF_DARKENED_ELEMENT) { int size = pFont->CalcSize(textPtr).w - 18; if (size<18) size = 18; DrawAvPMenuGfx_Clipped(AVPMENUGFX_GLOWY_LEFT,x+18,y-8,alpha,AVPMENUFORMAT_RIGHTJUSTIFIED,topY,bottomY); DrawAvPMenuGlowyBar_Clipped(x+18,y-8,alpha,size-18,topY,bottomY); DrawAvPMenuGfx_Clipped(AVPMENUGFX_GLOWY_RIGHT,x+size,y-8,alpha,AVPMENUFORMAT_LEFTJUSTIFIED,topY,bottomY); } R2Pos_StartOfRow = r2pos(x,y); const struct r2rect R2Rect_Clip = r2rect(0,topY,0,bottomY); { { SCString* pSCString_Name = new SCString(textPtr); pFont -> RenderString_Clipped ( R2Pos_StartOfRow, // struct r2pos& R2Pos_Cursor, R2Rect_Clip, //const struct r2rect& R2Rect_Clip alpha, // int FixP_Alpha, *pSCString_Name // const SCString& SCStr ); pSCString_Name -> R_Release(); } } return R2Pos_StartOfRow.x; } extern int RenderSmallMenuText(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format) { switch(format) { default: GLOBALASSERT("UNKNOWN TEXT FORMAT"==0); case AVPMENUFORMAT_LEFTJUSTIFIED: { // supplied x is correct break; } case AVPMENUFORMAT_RIGHTJUSTIFIED: { int length = 0; char *ptr = textPtr; while(*ptr) { length+=AAFontWidths[*ptr++]; } x -= length; break; } case AVPMENUFORMAT_CENTREJUSTIFIED: { int length = 0; char *ptr = textPtr; while(*ptr) { length+=AAFontWidths[*ptr++]; } x -= length/2; break; } } LOCALASSERT(x>0); x = RenderSmallFontString(textPtr,x,y,alpha,ONE_FIXED,ONE_FIXED,ONE_FIXED); return x; } extern int RenderSmallMenuText_Coloured(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format, int red, int green, int blue) { switch(format) { default: GLOBALASSERT("UNKNOWN TEXT FORMAT"==0); case AVPMENUFORMAT_LEFTJUSTIFIED: { // supplied x is correct break; } case AVPMENUFORMAT_RIGHTJUSTIFIED: { int length = 0; char *ptr = textPtr; while(*ptr) { length+=AAFontWidths[*ptr++]; } x -= length; break; } case AVPMENUFORMAT_CENTREJUSTIFIED: { int length = 0; char *ptr = textPtr; while(*ptr) { length+=AAFontWidths[*ptr++]; } x -= length/2; break; } } LOCALASSERT(x>0); x = RenderSmallFontString(textPtr,x,y,alpha,red,green,blue); return x; } extern int Hardware_RenderSmallMenuText(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format) { switch(format) { default: GLOBALASSERT("UNKNOWN TEXT FORMAT"==0); case AVPMENUFORMAT_LEFTJUSTIFIED: { // supplied x is correct break; } case AVPMENUFORMAT_RIGHTJUSTIFIED: { int length = 0; char *ptr = textPtr; while(*ptr) { length+=AAFontWidths[*ptr++]; } x -= length; break; } case AVPMENUFORMAT_CENTREJUSTIFIED: { int length = 0; char *ptr = textPtr; while(*ptr) { length+=AAFontWidths[*ptr++]; } x -= length/2; break; } } LOCALASSERT(x>0); { unsigned int colour = alpha>>8; if (colour>255) colour = 255; colour = (colour<<24)+0xffffff; D3D_RenderHUDString(textPtr,x,y,colour); } return x; } extern int Hardware_RenderSmallMenuText_Coloured(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format, int red, int green, int blue) { switch(format) { default: GLOBALASSERT("UNKNOWN TEXT FORMAT"==0); case AVPMENUFORMAT_LEFTJUSTIFIED: { // supplied x is correct break; } case AVPMENUFORMAT_RIGHTJUSTIFIED: { int length = 0; char *ptr = textPtr; while(*ptr) { length+=AAFontWidths[*ptr++]; } x -= length; break; } case AVPMENUFORMAT_CENTREJUSTIFIED: { int length = 0; char *ptr = textPtr; while(*ptr) { length+=AAFontWidths[*ptr++]; } x -= length/2; break; } } LOCALASSERT(x>0); { unsigned int colour = alpha>>8; if (colour>255) colour = 255; colour = (colour<<24); colour += MUL_FIXED(red,255)<<16; colour += MUL_FIXED(green,255)<<8; colour += MUL_FIXED(blue,255); D3D_RenderHUDString(textPtr,x,y,colour); } return x; } extern void Hardware_RenderKeyConfigRectangle(int alpha) { extern void D3D_DrawRectangle(int x, int y, int w, int h, int alpha); D3D_DrawRectangle(10,ScreenDescriptorBlock.SDB_Height/2+25-115,ScreenDescriptorBlock.SDB_Width-20,250,alpha); } extern void RenderKeyConfigRectangle(int alpha) { int x1 = 10; int x2 = ScreenDescriptorBlock.SDB_Width-10; int y1 = ScreenDescriptorBlock.SDB_Height/2+25-115; int y2 = ScreenDescriptorBlock.SDB_Height/2+25-115+250; int x,y; int c; c = MUL_FIXED(DisplayPixelFormat.dwRBitMask,alpha) & DisplayPixelFormat.dwRBitMask; c |= MUL_FIXED(DisplayPixelFormat.dwGBitMask,alpha) & DisplayPixelFormat.dwGBitMask; c |= MUL_FIXED(DisplayPixelFormat.dwBBitMask,alpha) & DisplayPixelFormat.dwBBitMask; y=y1; { unsigned short *destPtr = (unsigned short *)(ScreenBuffer + x1*2 + y*BackBufferPitch); for (x=x1; x<=x2; x++) { *destPtr |= c; destPtr++; } } y=y2; { unsigned short *destPtr = (unsigned short *)(ScreenBuffer + x1*2 + y*BackBufferPitch); for (x=x1; x<=x2; x++) { *destPtr |= c; destPtr++; } } { for (y=y1+1; y<y2; y++) { unsigned short *destPtr = (unsigned short *)(ScreenBuffer + x1*2 + y*BackBufferPitch); *destPtr |= c; } } { for (y=y1+1; y<y2; y++) { unsigned short *destPtr = (unsigned short *)(ScreenBuffer + x2*2 + y*BackBufferPitch); *destPtr |= c; } } } extern void Hardware_RenderHighlightRectangle(int x1,int y1,int x2,int y2,int r, int g, int b) { r2rect rectangle ( x1, y1, x2, y2 ); rectangle . AlphaFill ( r, // unsigned char R, g,// unsigned char G, b,// unsigned char B, 255 // unsigned char translucency ); } extern void RenderHighlightRectangle(int x1,int y1,int x2,int y2, int r, int g, int b) { int x,y; short c; c = ((DisplayPixelFormat.dwRBitMask*r)/256)&(DisplayPixelFormat.dwRBitMask); c |= ((DisplayPixelFormat.dwGBitMask*g)/256)&(DisplayPixelFormat.dwGBitMask); c |= ((DisplayPixelFormat.dwBBitMask*b)/256)&(DisplayPixelFormat.dwBBitMask); for (y=y1; y<=y2; y++) { unsigned short *destPtr = (unsigned short *)(ScreenBuffer + x1*2 + y*BackBufferPitch); for (x=x1; x<=x2; x++) { *destPtr |= c; destPtr++; } } } static int RenderSmallFontString(char *textPtr,int sx,int sy,int alpha, int red, int green, int blue) { DDSURFACEDESC ddsdimage; unsigned short *destPtr; unsigned short *srcPtr; int extra = 0; int alphaR = MUL_FIXED(alpha,red); int alphaG = MUL_FIXED(alpha,green); int alphaB = MUL_FIXED(alpha,blue); AVPMENUGFX *gfxPtr; LPDIRECTDRAWSURFACE surface; gfxPtr = &AvPMenuGfxStorage[AVPMENUGFX_SMALL_FONT]; surface = gfxPtr->ImagePtr; memset(&ddsdimage, 0, sizeof(ddsdimage)); ddsdimage.dwSize = sizeof(ddsdimage); /* lock the image */ while (surface->Lock(NULL, &ddsdimage, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); while( *textPtr ) { char c = *textPtr++; if (c>=' ') { int topLeftU = 1+((c-32)&15)*16; int topLeftV = 1+((c-32)>>4)*16; srcPtr = (unsigned short *)(ddsdimage.lpSurface) + (topLeftU)+(topLeftV*ddsdimage.lPitch/2); int x,y; for (y=sy; y<HUD_FONT_HEIGHT+sy; y++) { destPtr = (unsigned short *)(ScreenBuffer + sx*2 + y*BackBufferPitch); for (x=0; x<HUD_FONT_WIDTH; x++) { if (*srcPtr) { unsigned int srcR,srcG,srcB; unsigned int destR,destG,destB; destR = (int)(*destPtr) & DisplayPixelFormat.dwRBitMask; destG = (int)(*destPtr) & DisplayPixelFormat.dwGBitMask; destB = (int)(*destPtr) & DisplayPixelFormat.dwBBitMask; srcR = (int)(*srcPtr) & DisplayPixelFormat.dwRBitMask; srcG = (int)(*srcPtr) & DisplayPixelFormat.dwGBitMask; srcB = (int)(*srcPtr) & DisplayPixelFormat.dwBBitMask; destR += MUL_FIXED(alphaR,srcR); if (destR>DisplayPixelFormat.dwRBitMask) destR = DisplayPixelFormat.dwRBitMask; else destR &= DisplayPixelFormat.dwRBitMask; destG += MUL_FIXED(alphaG,srcG); if (destG>DisplayPixelFormat.dwGBitMask) destG = DisplayPixelFormat.dwGBitMask; else destG &= DisplayPixelFormat.dwGBitMask; destB += MUL_FIXED(alphaB,srcB); if (destB>DisplayPixelFormat.dwBBitMask) destB = DisplayPixelFormat.dwBBitMask; else destB &= DisplayPixelFormat.dwBBitMask; *destPtr = (short)(destR|destG|destB); } destPtr++; srcPtr++; } srcPtr += (ddsdimage.lPitch/2) - HUD_FONT_WIDTH; } sx += AAFontWidths[c]; #if 0 if(c!=32) { extra += 8-AAFontWidths[c]; } else { sx+=extra+8-AAFontWidths[c]; extra=0; } #endif } } surface->Unlock((LPVOID)ddsdimage.lpSurface); return sx; } extern void RenderSmallFontString_Wrapped(char *textPtr,RECT* area,int alpha,int* output_x,int* output_y) { DDSURFACEDESC ddsdimage; unsigned short *destPtr; unsigned short *srcPtr; int extra = 0; AVPMENUGFX *gfxPtr; LPDIRECTDRAWSURFACE surface; int wordWidth; int sx=area->left; int sy=area->top; gfxPtr = &AvPMenuGfxStorage[AVPMENUGFX_SMALL_FONT]; surface = gfxPtr->ImagePtr; memset(&ddsdimage, 0, sizeof(ddsdimage)); ddsdimage.dwSize = sizeof(ddsdimage); /* lock the image */ while (surface->Lock(NULL, &ddsdimage, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); /* Determine area used by text , so we can draw it centrally */ { char* textPtr2=textPtr; while( *textPtr2) { //find the width of the next word int widthFromSpaces=0; int widthFromChars=0; // get width used by spaces before this word while(*textPtr2 && *textPtr2==' ') { widthFromSpaces+=AAFontWidths[*textPtr2++]; } //get width used by word while(*textPtr2 && *textPtr2!=' ') { widthFromChars+=AAFontWidths[*textPtr2++]; } wordWidth=widthFromSpaces+widthFromChars; if(wordWidth> area->right-sx) { if(wordWidth >area->right-area->left) { int extraLinesNeeded=0; //word is too long too fit on one line , so it will have to be split wordWidth-=(area->right-sx); //advance to the beginning of the next line sy+=HUD_FONT_HEIGHT; sx=area->left; //see how many extra whole lines are equired extraLinesNeeded=wordWidth/(area->right-area->left); sy+=HUD_FONT_HEIGHT*extraLinesNeeded; wordWidth %= (area->right-area->left); //make sure we haven't gone off the bottom if(sy+HUD_FONT_HEIGHT> area->bottom) break; } else { //word to long to fit on this line , so go to next line sy+=HUD_FONT_HEIGHT; sx=area->left; //make sure we haven't gone off the bottom if(sy+HUD_FONT_HEIGHT> area->bottom) break; //make sure the word will fit on a line anyway if(wordWidth> area->right-sx) break; //don't bother drawing spaces at the start of the new line wordWidth-=widthFromSpaces; } } sx+=wordWidth; } //if the string fits on one line , centre it horizontally if(sy==area->top) { sx=area->left+ (area->right-sx)/2; } else { sx=area->left; } //centre string vertically sy+=HUD_FONT_HEIGHT; if(sy<area->bottom) { sy=area->top + (area->bottom-sy)/2; } else { sy=area->top; } } while( *textPtr ) { //find the width of the next word char* textPtr2=textPtr; wordWidth=0; // get width used by spaces before this word while(*textPtr2 && *textPtr2==' ') { wordWidth+=AAFontWidths[*textPtr2++]; } //get width used by word while(*textPtr2 && *textPtr2!=' ') { wordWidth+=AAFontWidths[*textPtr2++]; } if(wordWidth> area->right-sx) { if(wordWidth>area->right - area->left) { //word is too long too fit on one line , so we'll just have to allow it to be split } else { //word to long to fit on this line , so go to next line sy+=HUD_FONT_HEIGHT; sx=area->left; //make sure we haven't gone off the bottom if(sy+HUD_FONT_HEIGHT> area->bottom) break; //make sure the word will fit on a line anyway if(wordWidth> area->right-sx) break; //don't bother drawing spaces at the start of the new line while(*textPtr && *textPtr==' ') { *textPtr++; } } } //'render' the spaces while(*textPtr && *textPtr==' ') { sx+=AAFontWidths[*textPtr++]; } if(sx>area->right) { //gone of the end of the line doing spaces while(sx>area->right) { sx-=(area->right-area->left); sy+=HUD_FONT_HEIGHT; } //make sure we haven't gone off the bottom if(sy+HUD_FONT_HEIGHT> area->bottom) break; } //render this word while(*textPtr && *textPtr!=' ') { char c = *textPtr++; int letterWidth = AAFontWidths[c]; if(sx+letterWidth>area->right) { //need to go on to the next line sx=area->left; sy+=HUD_FONT_HEIGHT; //make sure we haven't gone off the bottom if(sy+HUD_FONT_HEIGHT> area->bottom) break; } if (c>=' ' || c<='z') { int topLeftU = 1+((c-32)&15)*16; int topLeftV = 1+((c-32)>>4)*16; srcPtr = (unsigned short *)(ddsdimage.lpSurface) + (topLeftU)+(topLeftV*ddsdimage.lPitch/2); int x,y; for (y=sy; y<HUD_FONT_HEIGHT+sy; y++) { destPtr = (unsigned short *)(ScreenBuffer + sx*2 + y*BackBufferPitch); for (x=0; x<HUD_FONT_WIDTH; x++) { if (*srcPtr) { unsigned int srcR,srcG,srcB; unsigned int destR,destG,destB; destR = (int)(*destPtr) & DisplayPixelFormat.dwRBitMask; destG = (int)(*destPtr) & DisplayPixelFormat.dwGBitMask; destB = (int)(*destPtr) & DisplayPixelFormat.dwBBitMask; srcR = (int)(*srcPtr) & DisplayPixelFormat.dwRBitMask; srcG = (int)(*srcPtr) & DisplayPixelFormat.dwGBitMask; srcB = (int)(*srcPtr) & DisplayPixelFormat.dwBBitMask; destR += MUL_FIXED(alpha,srcR); if (destR>DisplayPixelFormat.dwRBitMask) destR = DisplayPixelFormat.dwRBitMask; else destR &= DisplayPixelFormat.dwRBitMask; destG += MUL_FIXED(alpha,srcG); if (destG>DisplayPixelFormat.dwGBitMask) destG = DisplayPixelFormat.dwGBitMask; else destG &= DisplayPixelFormat.dwGBitMask; destB += MUL_FIXED(alpha,srcB); if (destB>DisplayPixelFormat.dwBBitMask) destB = DisplayPixelFormat.dwBBitMask; else destB &= DisplayPixelFormat.dwBBitMask; *destPtr = (short)(destR|destG|destB); } destPtr++; srcPtr++; } srcPtr += (ddsdimage.lPitch/2) - HUD_FONT_WIDTH; } sx += AAFontWidths[c]; #if 0 if(c!=32) { extra += 8-AAFontWidths[c]; } else { sx+=extra+8-AAFontWidths[c]; extra=0; } #endif } } } surface->Unlock((LPVOID)ddsdimage.lpSurface); if(output_x) *output_x=sx; if(output_y) *output_y=sy; } extern void LoadAvPMenuGfx(enum AVPMENUGFX_ID menuGfxID) { AVPMENUGFX *gfxPtr; char buffer[100]; GLOBALASSERT(menuGfxID < MAX_NO_OF_AVPMENUGFXS); gfxPtr = &AvPMenuGfxStorage[menuGfxID]; CL_GetImageFileName(buffer, 100, gfxPtr->FilenamePtr, LIO_RELATIVEPATH); //see if graphic can be found in fast file unsigned int fastFileLength; void const * pFastFileData = ffreadbuf(buffer,&fastFileLength); if(pFastFileData) { //load from fast file #if 0 gfxPtr->ImagePtr = AwCreateSurface ( "pxfXYB", pFastFileData, fastFileLength, AW_TLF_TRANSP|AW_TLF_CHROMAKEY, &(gfxPtr->Width), &(gfxPtr->Height), &(gfxPtr->hBackup) ); #else gfxPtr->ImagePtr = AwCreateSurface ( "pxfXY", pFastFileData, fastFileLength, AW_TLF_TRANSP|AW_TLF_CHROMAKEY, &(gfxPtr->Width), &(gfxPtr->Height) ); #endif } else { //load graphic from rim file gfxPtr->ImagePtr = AwCreateSurface ( "sfXYB", buffer, AW_TLF_TRANSP|AW_TLF_CHROMAKEY, &(gfxPtr->Width), &(gfxPtr->Height), &(gfxPtr->hBackup) ); } GLOBALASSERT(gfxPtr->ImagePtr); // GLOBALASSERT(gfxPtr->hBackup); GLOBALASSERT(gfxPtr->Width>0); GLOBALASSERT(gfxPtr->Height>0); gfxPtr->hBackup=0; // ATIncludeSurface(gfxPtr->ImagePtr,gfxPtr->hBackup); } static void ReleaseAvPMenuGfx(enum AVPMENUGFX_ID menuGfxID) { AVPMENUGFX *gfxPtr; GLOBALASSERT(menuGfxID < MAX_NO_OF_AVPMENUGFXS); gfxPtr = &AvPMenuGfxStorage[menuGfxID]; GLOBALASSERT(gfxPtr); GLOBALASSERT(gfxPtr->ImagePtr); // ATRemoveSurface(gfxPtr->ImagePtr); ReleaseDDSurface(gfxPtr->ImagePtr); gfxPtr->ImagePtr = NULL; #if 0 if (gfxPtr->hBackup) { AwDestroyBackupTexture(gfxPtr->hBackup); gfxPtr->hBackup = NULL; } #endif } extern void LoadAllAvPMenuGfx(void) { int i = 0; while(i<AVPMENUGFX_WINNER_SCREEN) { LoadAvPMenuGfx((enum AVPMENUGFX_ID)i++); } LoadMenuFont(); { DDSURFACEDESC ddsdimage; unsigned short *srcPtr; AVPMENUGFX *gfxPtr = &AvPMenuGfxStorage[AVPMENUGFX_CLOUDY]; LPDIRECTDRAWSURFACE surface; surface = gfxPtr->ImagePtr; memset(&ddsdimage, 0, sizeof(ddsdimage)); ddsdimage.dwSize = sizeof(ddsdimage); /* lock the image */ while (surface->Lock(NULL, &ddsdimage, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); srcPtr = (unsigned short *)ddsdimage.lpSurface; { int x,y; for (y=0; y<gfxPtr->Height; y++) { for (x=0; x<gfxPtr->Width; x++) { extern int CloudTable[128][128]; int r = (int)(*srcPtr) & DisplayPixelFormat.dwRBitMask; // int g = (int)(*srcPtr) & DisplayPixelFormat.dwGBitMask; // int b = (int)(*srcPtr) & DisplayPixelFormat.dwBBitMask; r = DIV_FIXED(r,DisplayPixelFormat.dwRBitMask); // g = DIV_FIXED(g,DisplayPixelFormat.dwGBitMask); // b = DIV_FIXED(b,DisplayPixelFormat.dwBBitMask); CloudTable[x][y]=r; // CloudTable[x][y]=g; // CloudTable[x][y]=b; srcPtr++; } srcPtr += (ddsdimage.lPitch/2) - gfxPtr->Width; } } surface->Unlock((LPVOID)ddsdimage.lpSurface); } CalculateWidthsOfAAFont(); } extern void LoadAllSplashScreenGfx(void) { int i = AVPMENUGFX_SPLASH_SCREEN1; while(i<MAX_NO_OF_AVPMENUGFXS) { LoadAvPMenuGfx((enum AVPMENUGFX_ID)i++); } } extern void InitialiseMenuGfx(void) { int i=0; while(i<MAX_NO_OF_AVPMENUGFXS) { AvPMenuGfxStorage[i++].ImagePtr = 0; } } extern void ReleaseAllAvPMenuGfx(void) { int i=0; while(i<MAX_NO_OF_AVPMENUGFXS) { if (AvPMenuGfxStorage[i].ImagePtr) { ReleaseAvPMenuGfx((enum AVPMENUGFX_ID)i); } i++; } UnloadMenuFont(); } extern void DrawAvPMenuGfx(enum AVPMENUGFX_ID menuGfxID, int topleftX, int topleftY, int alpha,enum AVPMENUFORMAT_ID format) { LockSurfaceAndGetBufferPointer(); DDSURFACEDESC ddsdimage; unsigned short *destPtr; unsigned short *srcPtr; AVPMENUGFX *gfxPtr; LPDIRECTDRAWSURFACE surface; GLOBALASSERT(menuGfxID < MAX_NO_OF_AVPMENUGFXS); gfxPtr = &AvPMenuGfxStorage[menuGfxID]; surface = gfxPtr->ImagePtr; switch(format) { default: GLOBALASSERT("UNKNOWN TEXT FORMAT"==0); case AVPMENUFORMAT_LEFTJUSTIFIED: { // supplied x is correct break; } case AVPMENUFORMAT_RIGHTJUSTIFIED: { topleftX -= gfxPtr->Width; break; } case AVPMENUFORMAT_CENTREJUSTIFIED: { topleftX -= gfxPtr->Width/2; break; } } memset(&ddsdimage, 0, sizeof(ddsdimage)); ddsdimage.dwSize = sizeof(ddsdimage); /* lock the image */ while (surface->Lock(NULL, &ddsdimage, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); srcPtr = (unsigned short *)ddsdimage.lpSurface; int length = gfxPtr->Width; if (ScreenDescriptorBlock.SDB_Width - topleftX < length) { length = ScreenDescriptorBlock.SDB_Width - topleftX; } if (length<=0) return; if (alpha>ONE_FIXED) { int x,y; for (y=topleftY; y<gfxPtr->Height+topleftY; y++) { destPtr = (unsigned short *)(ScreenBuffer + topleftX*2 + y*BackBufferPitch); for (x=0; x<length; x++) { *destPtr = *srcPtr; destPtr++; srcPtr++; } srcPtr += (ddsdimage.lPitch/2) - length; } } else { int x,y; for (y=topleftY; y<gfxPtr->Height+topleftY; y++) { destPtr = (unsigned short *)(ScreenBuffer + topleftX*2 + y*BackBufferPitch); for (x=0; x<length; x++) { if (*srcPtr) { unsigned int srcR,srcG,srcB; unsigned int destR,destG,destB; destR = (int)(*destPtr) & DisplayPixelFormat.dwRBitMask; destG = (int)(*destPtr) & DisplayPixelFormat.dwGBitMask; destB = (int)(*destPtr) & DisplayPixelFormat.dwBBitMask; srcR = (int)(*srcPtr) & DisplayPixelFormat.dwRBitMask; srcG = (int)(*srcPtr) & DisplayPixelFormat.dwGBitMask; srcB = (int)(*srcPtr) & DisplayPixelFormat.dwBBitMask; destR += MUL_FIXED(alpha,srcR); if (destR>DisplayPixelFormat.dwRBitMask) destR = DisplayPixelFormat.dwRBitMask; else destR &= DisplayPixelFormat.dwRBitMask; destG += MUL_FIXED(alpha,srcG); if (destG>DisplayPixelFormat.dwGBitMask) destG = DisplayPixelFormat.dwGBitMask; else destG &= DisplayPixelFormat.dwGBitMask; destB += MUL_FIXED(alpha,srcB); if (destB>DisplayPixelFormat.dwBBitMask) destB = DisplayPixelFormat.dwBBitMask; else destB &= DisplayPixelFormat.dwBBitMask; *destPtr = (short)(destR|destG|destB); } destPtr++; srcPtr++; } srcPtr += (ddsdimage.lPitch/2) - length; } } surface->Unlock((LPVOID)ddsdimage.lpSurface); UnlockSurface(); } extern void DrawAvPMenuGlowyBar(int topleftX, int topleftY, int alpha, int length) { enum AVPMENUGFX_ID menuGfxID = AVPMENUGFX_GLOWY_MIDDLE; LockSurfaceAndGetBufferPointer(); DDSURFACEDESC ddsdimage; unsigned short *destPtr; unsigned short *srcPtr; AVPMENUGFX *gfxPtr; LPDIRECTDRAWSURFACE surface; GLOBALASSERT(menuGfxID < MAX_NO_OF_AVPMENUGFXS); gfxPtr = &AvPMenuGfxStorage[menuGfxID]; surface = gfxPtr->ImagePtr; memset(&ddsdimage, 0, sizeof(ddsdimage)); ddsdimage.dwSize = sizeof(ddsdimage); /* lock the image */ while (surface->Lock(NULL, &ddsdimage, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); srcPtr = (unsigned short *)ddsdimage.lpSurface; if (ScreenDescriptorBlock.SDB_Width - topleftX < length) { length = ScreenDescriptorBlock.SDB_Width - topleftX; } if (length<0) length = 0; if (alpha>ONE_FIXED) { int x,y; for (y=topleftY; y<gfxPtr->Height+topleftY; y++) { destPtr = (unsigned short *)(ScreenBuffer + topleftX*2 + y*BackBufferPitch); for (x=0; x<length; x++) { *destPtr = *srcPtr; destPtr++; } srcPtr += (ddsdimage.lPitch/2); } } else { int x,y; for (y=topleftY; y<gfxPtr->Height+topleftY; y++) { destPtr = (unsigned short *)(ScreenBuffer + topleftX*2 + y*BackBufferPitch); for (x=0; x<length; x++) { if (*srcPtr) { unsigned int srcR,srcG,srcB; unsigned int destR,destG,destB; destR = (int)(*destPtr) & DisplayPixelFormat.dwRBitMask; destG = (int)(*destPtr) & DisplayPixelFormat.dwGBitMask; destB = (int)(*destPtr) & DisplayPixelFormat.dwBBitMask; srcR = (int)(*srcPtr) & DisplayPixelFormat.dwRBitMask; srcG = (int)(*srcPtr) & DisplayPixelFormat.dwGBitMask; srcB = (int)(*srcPtr) & DisplayPixelFormat.dwBBitMask; destR += MUL_FIXED(alpha,srcR); if (destR>DisplayPixelFormat.dwRBitMask) destR = DisplayPixelFormat.dwRBitMask; else destR &= DisplayPixelFormat.dwRBitMask; destG += MUL_FIXED(alpha,srcG); if (destG>DisplayPixelFormat.dwGBitMask) destG = DisplayPixelFormat.dwGBitMask; else destG &= DisplayPixelFormat.dwGBitMask; destB += MUL_FIXED(alpha,srcB); if (destB>DisplayPixelFormat.dwBBitMask) destB = DisplayPixelFormat.dwBBitMask; else destB &= DisplayPixelFormat.dwBBitMask; *destPtr = (short)(destR|destG|destB); } destPtr++; } srcPtr += (ddsdimage.lPitch/2); } } surface->Unlock((LPVOID)ddsdimage.lpSurface); UnlockSurface(); } extern void DrawAvPMenuGlowyBar_Clipped(int topleftX, int topleftY, int alpha, int length, int topY, int bottomY) { enum AVPMENUGFX_ID menuGfxID = AVPMENUGFX_GLOWY_MIDDLE; LockSurfaceAndGetBufferPointer(); DDSURFACEDESC ddsdimage; unsigned short *destPtr; unsigned short *srcPtr; AVPMENUGFX *gfxPtr; LPDIRECTDRAWSURFACE surface; GLOBALASSERT(menuGfxID < MAX_NO_OF_AVPMENUGFXS); gfxPtr = &AvPMenuGfxStorage[menuGfxID]; surface = gfxPtr->ImagePtr; memset(&ddsdimage, 0, sizeof(ddsdimage)); ddsdimage.dwSize = sizeof(ddsdimage); /* lock the image */ while (surface->Lock(NULL, &ddsdimage, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); srcPtr = (unsigned short *)ddsdimage.lpSurface; if (length<0) length = 0; if (alpha>ONE_FIXED) { int x,y; for (y=topleftY; y<gfxPtr->Height+topleftY; y++) { if(y>=topY && y<=bottomY) { destPtr = (unsigned short *)(ScreenBuffer + topleftX*2 + y*BackBufferPitch); for (x=0; x<length; x++) { *destPtr = *srcPtr; destPtr++; } srcPtr += (ddsdimage.lPitch/2); } } } else { int x,y; for (y=topleftY; y<gfxPtr->Height+topleftY; y++) { if(y>=topY && y<=bottomY) { destPtr = (unsigned short *)(ScreenBuffer + topleftX*2 + y*BackBufferPitch); for (x=0; x<length; x++) { if (*srcPtr) { unsigned int srcR,srcG,srcB; unsigned int destR,destG,destB; destR = (int)(*destPtr) & DisplayPixelFormat.dwRBitMask; destG = (int)(*destPtr) & DisplayPixelFormat.dwGBitMask; destB = (int)(*destPtr) & DisplayPixelFormat.dwBBitMask; srcR = (int)(*srcPtr) & DisplayPixelFormat.dwRBitMask; srcG = (int)(*srcPtr) & DisplayPixelFormat.dwGBitMask; srcB = (int)(*srcPtr) & DisplayPixelFormat.dwBBitMask; destR += MUL_FIXED(alpha,srcR); if (destR>DisplayPixelFormat.dwRBitMask) destR = DisplayPixelFormat.dwRBitMask; else destR &= DisplayPixelFormat.dwRBitMask; destG += MUL_FIXED(alpha,srcG); if (destG>DisplayPixelFormat.dwGBitMask) destG = DisplayPixelFormat.dwGBitMask; else destG &= DisplayPixelFormat.dwGBitMask; destB += MUL_FIXED(alpha,srcB); if (destB>DisplayPixelFormat.dwBBitMask) destB = DisplayPixelFormat.dwBBitMask; else destB &= DisplayPixelFormat.dwBBitMask; *destPtr = (short)(destR|destG|destB); } destPtr++; } } srcPtr += (ddsdimage.lPitch/2); } } surface->Unlock((LPVOID)ddsdimage.lpSurface); UnlockSurface(); } extern void DrawAvPMenuGfx_CrossFade(enum AVPMENUGFX_ID menuGfxID,enum AVPMENUGFX_ID menuGfxID2,int alpha) { LockSurfaceAndGetBufferPointer(); DDSURFACEDESC ddsdimage,ddsdimage2; unsigned int *destPtr; unsigned int *srcPtr; unsigned int *srcPtr2; AVPMENUGFX *gfxPtr; AVPMENUGFX *gfxPtr2; LPDIRECTDRAWSURFACE surface; LPDIRECTDRAWSURFACE surface2; GLOBALASSERT(menuGfxID < MAX_NO_OF_AVPMENUGFXS); gfxPtr = &AvPMenuGfxStorage[menuGfxID]; surface = gfxPtr->ImagePtr; GLOBALASSERT(menuGfxID2 < MAX_NO_OF_AVPMENUGFXS); gfxPtr2 = &AvPMenuGfxStorage[menuGfxID2]; surface2 = gfxPtr2->ImagePtr; memset(&ddsdimage, 0, sizeof(ddsdimage)); ddsdimage.dwSize = sizeof(ddsdimage); /* lock the image */ while (surface->Lock(NULL, &ddsdimage, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); srcPtr = (unsigned int *)ddsdimage.lpSurface; memset(&ddsdimage2, 0, sizeof(ddsdimage2)); ddsdimage2.dwSize = sizeof(ddsdimage2); /* lock the image */ while (surface2->Lock(NULL, &ddsdimage2, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); srcPtr2 = (unsigned int *)ddsdimage2.lpSurface; if (alpha==ONE_FIXED) { int x,y; for (y=0; y<480; y++) { destPtr = (unsigned int *)(ScreenBuffer + y*BackBufferPitch); for (x=0; x<320; x++) { *destPtr = *srcPtr; destPtr++; srcPtr++; } srcPtr += (ddsdimage.lPitch/4) - 320; } } else { int x,y; for (y=0; y<480; y++) { destPtr = (unsigned int *)(ScreenBuffer + y*BackBufferPitch); for (x=0; x<320; x++) { int destination; int src1=*srcPtr,src2=*srcPtr2; { unsigned int srcR,srcG,srcB; unsigned int srcR2,srcG2,srcB2; srcR2 = (src2) & DisplayPixelFormat.dwRBitMask; srcG2 = (src2) & DisplayPixelFormat.dwGBitMask; srcB2 = (src2) & DisplayPixelFormat.dwBBitMask; srcR = (src1) & DisplayPixelFormat.dwRBitMask; srcG = (src1) & DisplayPixelFormat.dwGBitMask; srcB = (src1) & DisplayPixelFormat.dwBBitMask; srcR2 = MUL_FIXED(ONE_FIXED-alpha,srcR2)+MUL_FIXED(alpha,srcR); if (srcR2>DisplayPixelFormat.dwRBitMask) srcR2 = DisplayPixelFormat.dwRBitMask; else srcR2 &= DisplayPixelFormat.dwRBitMask; srcG2 = MUL_FIXED(ONE_FIXED-alpha,srcG2)+MUL_FIXED(alpha,srcG); if (srcG2>DisplayPixelFormat.dwGBitMask) srcG2 = DisplayPixelFormat.dwGBitMask; else srcG2 &= DisplayPixelFormat.dwGBitMask; srcB2 = MUL_FIXED(ONE_FIXED-alpha,srcB2)+MUL_FIXED(alpha,srcB); if (srcB2>DisplayPixelFormat.dwBBitMask) srcB2 = DisplayPixelFormat.dwBBitMask; else srcB2 &= DisplayPixelFormat.dwBBitMask; destination = (srcR2|srcG2|srcB2); } src1>>=16; src2>>=16; { unsigned int srcR,srcG,srcB; unsigned int srcR2,srcG2,srcB2; srcR2 = (src2) & DisplayPixelFormat.dwRBitMask; srcG2 = (src2) & DisplayPixelFormat.dwGBitMask; srcB2 = (src2) & DisplayPixelFormat.dwBBitMask; srcR = (src1) & DisplayPixelFormat.dwRBitMask; srcG = (src1) & DisplayPixelFormat.dwGBitMask; srcB = (src1) & DisplayPixelFormat.dwBBitMask; srcR2 = MUL_FIXED(ONE_FIXED-alpha,srcR2)+MUL_FIXED(alpha,srcR); if (srcR2>DisplayPixelFormat.dwRBitMask) srcR2 = DisplayPixelFormat.dwRBitMask; else srcR2 &= DisplayPixelFormat.dwRBitMask; srcG2 = MUL_FIXED(ONE_FIXED-alpha,srcG2)+MUL_FIXED(alpha,srcG); if (srcG2>DisplayPixelFormat.dwGBitMask) srcG2 = DisplayPixelFormat.dwGBitMask; else srcG2 &= DisplayPixelFormat.dwGBitMask; srcB2 = MUL_FIXED(ONE_FIXED-alpha,srcB2)+MUL_FIXED(alpha,srcB); if (srcB2>DisplayPixelFormat.dwBBitMask) srcB2 = DisplayPixelFormat.dwBBitMask; else srcB2 &= DisplayPixelFormat.dwBBitMask; destination |= (srcR2|srcG2|srcB2)<<16; } *destPtr++=destination; srcPtr++; srcPtr2++; } srcPtr += (ddsdimage.lPitch/4) - 320; srcPtr2 += (ddsdimage2.lPitch/4) - 320; } } surface2->Unlock((LPVOID)ddsdimage2.lpSurface); surface->Unlock((LPVOID)ddsdimage.lpSurface); UnlockSurface(); } extern void DrawAvPMenuGfx_Faded(enum AVPMENUGFX_ID menuGfxID, int topleftX, int topleftY, int alpha,enum AVPMENUFORMAT_ID format) { LockSurfaceAndGetBufferPointer(); DDSURFACEDESC ddsdimage; unsigned short *destPtr; unsigned short *srcPtr; AVPMENUGFX *gfxPtr; LPDIRECTDRAWSURFACE surface; GLOBALASSERT(menuGfxID < MAX_NO_OF_AVPMENUGFXS); gfxPtr = &AvPMenuGfxStorage[menuGfxID]; surface = gfxPtr->ImagePtr; switch(format) { default: GLOBALASSERT("UNKNOWN TEXT FORMAT"==0); case AVPMENUFORMAT_LEFTJUSTIFIED: { // supplied x is correct break; } case AVPMENUFORMAT_RIGHTJUSTIFIED: { topleftX -= gfxPtr->Width; break; } case AVPMENUFORMAT_CENTREJUSTIFIED: { topleftX -= gfxPtr->Width/2; break; } } memset(&ddsdimage, 0, sizeof(ddsdimage)); ddsdimage.dwSize = sizeof(ddsdimage); /* lock the image */ while (surface->Lock(NULL, &ddsdimage, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); srcPtr = (unsigned short *)ddsdimage.lpSurface; { int x,y; for (y=topleftY; y<gfxPtr->Height+topleftY; y++) { destPtr = (unsigned short *)(ScreenBuffer + topleftX*2 + y*BackBufferPitch); for (x=0; x<gfxPtr->Width; x++) { if (*srcPtr) { unsigned int srcR,srcG,srcB; srcR = (int)(*srcPtr) & DisplayPixelFormat.dwRBitMask; srcG = (int)(*srcPtr) & DisplayPixelFormat.dwGBitMask; srcB = (int)(*srcPtr) & DisplayPixelFormat.dwBBitMask; srcR = MUL_FIXED(alpha,srcR); srcR &= DisplayPixelFormat.dwRBitMask; srcG = MUL_FIXED(alpha,srcG); srcG &= DisplayPixelFormat.dwGBitMask; srcB = MUL_FIXED(alpha,srcB); srcB &= DisplayPixelFormat.dwBBitMask; *destPtr = (short)(srcR|srcG|srcB); } else { *destPtr = 0; } destPtr++; srcPtr++; } srcPtr += (ddsdimage.lPitch/2) - gfxPtr->Width; } } surface->Unlock((LPVOID)ddsdimage.lpSurface); UnlockSurface(); } extern void DrawAvPMenuGfx_Clipped(enum AVPMENUGFX_ID menuGfxID, int topleftX, int topleftY, int alpha,enum AVPMENUFORMAT_ID format, int topY, int bottomY) { LockSurfaceAndGetBufferPointer(); DDSURFACEDESC ddsdimage; unsigned short *destPtr; unsigned short *srcPtr; AVPMENUGFX *gfxPtr; LPDIRECTDRAWSURFACE surface; GLOBALASSERT(menuGfxID < MAX_NO_OF_AVPMENUGFXS); gfxPtr = &AvPMenuGfxStorage[menuGfxID]; surface = gfxPtr->ImagePtr; switch(format) { default: GLOBALASSERT("UNKNOWN TEXT FORMAT"==0); case AVPMENUFORMAT_LEFTJUSTIFIED: { // supplied x is correct break; } case AVPMENUFORMAT_RIGHTJUSTIFIED: { topleftX -= gfxPtr->Width; break; } case AVPMENUFORMAT_CENTREJUSTIFIED: { topleftX -= gfxPtr->Width/2; break; } } memset(&ddsdimage, 0, sizeof(ddsdimage)); ddsdimage.dwSize = sizeof(ddsdimage); /* lock the image */ while (surface->Lock(NULL, &ddsdimage, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); srcPtr = (unsigned short *)ddsdimage.lpSurface; if (alpha>ONE_FIXED) { int x,y; for (y=topleftY; y<gfxPtr->Height+topleftY; y++) { destPtr = (unsigned short *)(ScreenBuffer + topleftX*2 + y*BackBufferPitch); if(y>=topY && y<=bottomY) { for (x=0; x<gfxPtr->Width; x++) { *destPtr = *srcPtr; destPtr++; srcPtr++; } srcPtr += (ddsdimage.lPitch/2) - gfxPtr->Width; } else { srcPtr+=(ddsdimage.lPitch/2); } } } else { int x,y; for (y=topleftY; y<gfxPtr->Height+topleftY; y++) { destPtr = (unsigned short *)(ScreenBuffer + topleftX*2 + y*BackBufferPitch); if(y>=topY && y<=bottomY) { for (x=0; x<gfxPtr->Width; x++) { if (*srcPtr) { unsigned int srcR,srcG,srcB; unsigned int destR,destG,destB; destR = (int)(*destPtr) & DisplayPixelFormat.dwRBitMask; destG = (int)(*destPtr) & DisplayPixelFormat.dwGBitMask; destB = (int)(*destPtr) & DisplayPixelFormat.dwBBitMask; srcR = (int)(*srcPtr) & DisplayPixelFormat.dwRBitMask; srcG = (int)(*srcPtr) & DisplayPixelFormat.dwGBitMask; srcB = (int)(*srcPtr) & DisplayPixelFormat.dwBBitMask; destR += MUL_FIXED(alpha,srcR); if (destR>DisplayPixelFormat.dwRBitMask) destR = DisplayPixelFormat.dwRBitMask; else destR &= DisplayPixelFormat.dwRBitMask; destG += MUL_FIXED(alpha,srcG); if (destG>DisplayPixelFormat.dwGBitMask) destG = DisplayPixelFormat.dwGBitMask; else destG &= DisplayPixelFormat.dwGBitMask; destB += MUL_FIXED(alpha,srcB); if (destB>DisplayPixelFormat.dwBBitMask) destB = DisplayPixelFormat.dwBBitMask; else destB &= DisplayPixelFormat.dwBBitMask; *destPtr = (short)(destR|destG|destB); } destPtr++; srcPtr++; } srcPtr += (ddsdimage.lPitch/2) - gfxPtr->Width; } else { srcPtr += (ddsdimage.lPitch/2); } } } surface->Unlock((LPVOID)ddsdimage.lpSurface); UnlockSurface(); } extern int HeightOfMenuGfx(enum AVPMENUGFX_ID menuGfxID) { return AvPMenuGfxStorage[menuGfxID].Height; } extern void ClearScreenToBlack(void) { LockSurfaceAndGetBufferPointer(); { int x,y; for (y=0; y<480; y++) { unsigned int *destPtr = (unsigned int *)(ScreenBuffer + y*BackBufferPitch); for (x=0; x<320; x++) { *destPtr++=0; } } } UnlockSurface(); } extern void FadedScreen(int alpha) { LockSurfaceAndGetBufferPointer(); { int x,y; for (y=60; y<ScreenDescriptorBlock.SDB_Height-60; y++) { unsigned short *destPtr = (unsigned short *)(ScreenBuffer + y*BackBufferPitch); for (x=0; x<ScreenDescriptorBlock.SDB_Width; x++) { if (*destPtr) { unsigned int srcR,srcG,srcB; srcR = (int)(*destPtr) & DisplayPixelFormat.dwRBitMask; srcG = (int)(*destPtr) & DisplayPixelFormat.dwGBitMask; srcB = (int)(*destPtr) & DisplayPixelFormat.dwBBitMask; srcR = MUL_FIXED(alpha,srcR); srcR &= DisplayPixelFormat.dwRBitMask; srcG = MUL_FIXED(alpha,srcG); srcG &= DisplayPixelFormat.dwGBitMask; srcB = MUL_FIXED(alpha,srcB); srcB &= DisplayPixelFormat.dwBBitMask; *destPtr = (short)(srcR|srcG|srcB); } destPtr++; } } } UnlockSurface(); } static void CalculateWidthsOfAAFont(void) { DDSURFACEDESC ddsdimage; unsigned char *srcPtr; AVPMENUGFX *gfxPtr; LPDIRECTDRAWSURFACE surface; int c; gfxPtr = &AvPMenuGfxStorage[AVPMENUGFX_SMALL_FONT]; surface = gfxPtr->ImagePtr; memset(&ddsdimage, 0, sizeof(ddsdimage)); ddsdimage.dwSize = sizeof(ddsdimage); /* lock the image */ while (surface->Lock(NULL, &ddsdimage, DDLOCK_WAIT, NULL) == DDERR_WASSTILLDRAWING); srcPtr = (unsigned char *)ddsdimage.lpSurface; // special case for space AAFontWidths[32]=3; for (c=33; c<255; c++) { int x,y; int x1 = 1+((c-32)&15)*16; int y1 = 1+((c-32)>>4)*16; AAFontWidths[c]=17; for (x=x1+HUD_FONT_WIDTH; x>x1; x--) { int blank = 1; for (y=y1; y<y1+HUD_FONT_HEIGHT; y++) { unsigned short s = *(unsigned short *)(srcPtr + x*2 + y*ddsdimage.lPitch); if (s&DisplayPixelFormat.dwBBitMask == DisplayPixelFormat.dwBBitMask) { blank=0; break; } } if(blank) { AAFontWidths[c]--; } else { break; } } } surface->Unlock((LPVOID)ddsdimage.lpSurface); } };
[ "a_jagers@ANTHONYJ.(none)" ]
[ [ [ 1, 1852 ] ] ]
240c7091647dc892782640289ca2240f30a2cf8a
d1dc408f6b65c4e5209041b62cd32fb5083fe140
/src/gameobjects/structures/cPalace.cpp
8f0d55288c8803dc29392f3b9983ae22015d5987
[]
no_license
dmitrygerasimuk/dune2themaker-fossfriendly
7b4bed2dfb2b42590e4b72bd34bb0f37f6c81e37
89a6920b216f3964241eeab7cf1a631e1e63f110
refs/heads/master
2020-03-12T03:23:40.821001
2011-02-19T12:01:30
2011-02-19T12:01:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
#include "../../include/d2tmh.h" // Constructor cPalace::cPalace() { // other variables (class specific) } int cPalace::getType() { return PALACE; } cPalace::~cPalace() { } void cPalace::think() { cAbstractStructure::think(); } void cPalace::think_animation() { // a palace does not animate, so when set, set it back to false if (isAnimating()) { setAnimating(false); } cAbstractStructure::think_animation(); cAbstractStructure::think_flag(); } void cPalace::think_guard() { } /* STRUCTURE SPECIFIC FUNCTIONS */
[ "stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151" ]
[ [ [ 1, 38 ] ] ]
61e543e6da0301e8785d097045fb1c9c8a35d4ce
44890f9b95a8c77492bf38514d26c0da51d2fae5
/Gif/Gif/LZWEncoder.h
5d2c32d18e69952d2fa091177d2fadd9569713d5
[]
no_license
winnison/huang-cpp
fd9cd57bd0b97870ae1ca6427d2fc8191cf58a77
989fe1d3fdc1c9eae33e0f11fcd6d790e866e4c5
refs/heads/master
2021-01-19T18:07:38.882211
2008-04-14T16:42:48
2008-04-14T16:42:48
34,250,385
0
0
null
null
null
null
UTF-8
C++
false
false
8,083
h
#include "defines.h" #include <fstream> static int masks[17]={ 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; class CLZWEncoder { int imgW, imgH; byte* pixAry; int initCodeSize; int remaining; int curPixel; // GIFCOMPR.C - GIF Image compression routines // // Lempel-Ziv compression based on 'compress'. GIF modifications by // David Rowley ([email protected]) // General DEFINEs static const int BITS = 12; static const int HSIZE = 5003; // 80% occupancy // GIF Image compression - modified 'compress' // // Based on: compress.c - File compression ala IEEE Computer, June 1984. // // By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) // Jim McKie (decvax!mcvax!jim) // Steve Davies (decvax!vax135!petsd!peora!srd) // Ken Turkowski (decvax!decwrl!turtlevax!ken) // James A. Woods (decvax!ihnp4!ames!jaw) // Joe Orost (decvax!vax135!petsd!joe) int n_bits; // number of bits/code int maxbits; // user settable max # bits/code int maxcode; // maximum code, given n_bits int maxmaxcode; // should NEVER generate this code int htab[HSIZE]; int codetab[HSIZE]; int hsize; // for dynamic table sizing int free_ent; // first unused entry // block compression parameters -- after all codes are used up, // and compression rate changes, start over. bool clear_flg; // Algorithm: use open addressing double hashing (no chaining) on the // prefix code / next character combination. We do a variant of Knuth's // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime // secondary probe. Here, the modular division first probe is gives way // to a faster exclusive-or manipulation. Also do block compression with // an adaptive reset, whereby the code table is cleared when the compression // ratio decreases, but after the table fills. The variable-length output // codes are re-sized at this point, and a special CLEAR code is generated // for the decompressor. Late addition: construct the table according to // file size for noticeable speed improvement on small files. Please direct // questions about this implementation to ames!jaw. int g_init_bits; int ClearCode; int EOFCode; // Number of characters so far in this 'packet' int a_count; // Define the storage for the packet accumulator byte accum[256]; // output // // Output the given code. // Inputs: // code: A n_bits-bit integer. If == -1, then EOF. This assumes // that n_bits =< wordsize - 1. // Outputs: // Outputs code to the file. // Assumptions: // Chars are 8 bits long. // Algorithm: // Maintain a BITS character long buffer (so that 8 codes will // fit in it exactly). Use the VAX insv instruction to insert each // code in turn. When the buffer fills up empty it and start over. int cur_accum; int cur_bits; // Add a character to the end of the current packet, and if it is 254 // characters, flush the packet to disk. void Add(byte c, fstream* outs) { accum[a_count++] = c; if (a_count >= 254) Flush(outs); } // Clear out the hash table // table clear for block compress void ClearTable(fstream* outs) { ResetCodeTable(hsize); free_ent = ClearCode + 2; clear_flg = true; Output(ClearCode, outs); } // reset code table void ResetCodeTable(int hsize) { for (int i = 0; i < hsize; ++i) htab[i] = -1; } void Compress(int init_bits, fstream* outs) { int fcode; int i /* = 0 */; int c; int ent; int disp; int hsize_reg; int hshift; // Set up the globals: g_init_bits - initial number of bits g_init_bits = init_bits; // Set up the necessary values clear_flg = false; n_bits = g_init_bits; maxcode = MaxCode(n_bits); ClearCode = 1 << (init_bits - 1); EOFCode = ClearCode + 1; free_ent = ClearCode + 2; a_count = 0; // clear packet ent = NextPixel(); hshift = 0; for (fcode = hsize; fcode < 65536; fcode *= 2) ++hshift; hshift = 8 - hshift; // set hash code range bound hsize_reg = hsize; ResetCodeTable(hsize_reg); // clear hash table Output(ClearCode, outs); outer_loop : while ((c = NextPixel()) != EOF) { fcode = (c << maxbits) + ent; i = (c << hshift) ^ ent; // xor hashing if (htab[i] == fcode) { ent = codetab[i]; continue; } else if (htab[i] >= 0) // non-empty slot { disp = hsize_reg - i; // secondary hash (after G. Knott) if (i == 0) disp = 1; do { if ((i -= disp) < 0) i += hsize_reg; if (htab[i] == fcode) { ent = codetab[i]; goto outer_loop; } } while (htab[i] >= 0); } Output(ent, outs); ent = c; if (free_ent < maxmaxcode) { codetab[i] = free_ent++; // code -> hashtable htab[i] = fcode; } else ClearTable(outs); } // Put out the final code. Output(ent, outs); Output(EOFCode, outs); } // Flush the packet to disk, and reset the accumulator void Flush(fstream* outs) { if (a_count > 0) { outs->write((char*)&a_count, 1); outs->write((char*)&(accum[0]), a_count); a_count = 0; } } int MaxCode(int n_bits) { return (1 << n_bits) - 1; } //---------------------------------------------------------------------------- // Return the next pixel from the image //---------------------------------------------------------------------------- int NextPixel() { if (remaining == 0) return EOF; --remaining; int temp = curPixel + 1; if ( temp < imgW * imgH) { byte pix = pixAry[curPixel++]; return (int)pix & 0xff; } return 0xff; } void Output(int code, fstream* outs) { cur_accum &= masks[cur_bits]; if (cur_bits > 0) cur_accum |= (code << cur_bits); else cur_accum = code; cur_bits += n_bits; while (cur_bits >= 8) { Add(*((byte*) &cur_accum), outs); cur_accum >>= 8; cur_bits -= 8; } // If the next entry is going to be too big for the code size, // then increase it, if possible. if (free_ent > maxcode || clear_flg) { if (clear_flg) { maxcode = MaxCode(n_bits = g_init_bits); clear_flg = false; } else { ++n_bits; if (n_bits == maxbits) maxcode = maxmaxcode; else maxcode = MaxCode(n_bits); } } if (code == EOFCode) { // At EOF, write the rest of the buffer. while (cur_bits > 0) { Add(*((byte*) &cur_accum), outs); cur_accum >>= 8; cur_bits -= 8; } Flush(outs); } } public: //---------------------------------------------------------------------------- CLZWEncoder(int width, int height, byte* pixels, int color_depth) :imgW(width), imgH(height), pixAry(pixels), initCodeSize(max(2, color_depth)), remaining(0), curPixel(0), n_bits(0), maxbits(BITS), maxcode(0), maxmaxcode(1 << BITS), hsize(HSIZE), free_ent(0), clear_flg(false), g_init_bits(0), ClearCode(0), EOFCode(0), a_count(0), cur_accum(0), cur_bits(0) { memset(codetab, 0, sizeof(int)*HSIZE); } ~CLZWEncoder(){} //---------------------------------------------------------------------------- void Encode( fstream* os) { os->write((char*)&initCodeSize, 1); // write "initial code size" byte //os<<(byte) (initCodeSize & 0xff); remaining = imgW * imgH; // reset navigation variables curPixel = 0; Compress(initCodeSize + 1, os); // compress and write the pixel data int a = 0; os->write((char*)&a, 1); // write block terminator } };
[ "mr.huanghuan@48bf5850-ed27-0410-9317-b938f814dc16" ]
[ [ [ 1, 352 ] ] ]
8889bf0da5a78da7fa439e4481492ed6f0ff51c1
90aa2eebb1ab60a2ac2be93215a988e3c51321d7
/castor/branches/boost/libs/castor/test/test_permutation.cpp
729a13216778daac7cfa0e11411e4bb0c03945fd
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
roshannaik/castor
b9f4ea138a041fe8bccf2d8fc0dceeb13bcca5a6
e86e2bf893719bf3164f9da9590217c107cbd913
refs/heads/master
2021-04-18T19:24:38.612073
2010-08-18T05:10:39
2010-08-18T05:10:39
126,150,539
0
0
null
null
null
null
UTF-8
C++
false
false
650
cpp
#include <boost/castor.h> #include <boost/test/minimal.hpp> using namespace castor; int test_main(int, char * []) { { // test mode lref<std::string> s = "hello", ps = "olleh"; relation r = permutation(s, ps); BOOST_CHECK(r()); BOOST_CHECK(!r()); } { // generate mode lref<int> c = 0; lref<std::string> s = "hello", ps, ss = "helol"; relation r = permutation(s, ps) && eq(ps, ss) && eval(++c); BOOST_CHECK(r() || *c == 1); ss = "heoll"; BOOST_CHECK(r() || *c == 2); BOOST_CHECK(!r()); } return 0; }
[ [ [ 1, 33 ] ] ]
54943fd0d4582870aeeb50d524a5af64c960e62b
4d91ca4dcaaa9167928d70b278b82c90fef384fa
/OpenFolder/OpenFolder.h
c2a01a9d4f4fb1909f6bd692701ee8aea5ad9c56
[]
no_license
dannydraper/CedeCryptClassic
13ef0d5f03f9ff3a9a1fe4a8113e385270536a03
5f14e3c9d949493b2831710e0ce414a1df1148ec
refs/heads/master
2021-01-17T13:10:51.608070
2010-10-01T10:09:15
2010-10-01T10:09:15
63,413,327
0
0
null
null
null
null
UTF-8
C++
false
false
5,575
h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 6.00.0366 */ /* at Tue Dec 15 15:41:51 2009 */ /* Compiler settings for .\OpenFolder.idl: Oicf, W1, Zp8, env=Win64 (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 COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __OpenFolder_h__ #define __OpenFolder_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IOpenFolder_FWD_DEFINED__ #define __IOpenFolder_FWD_DEFINED__ typedef interface IOpenFolder IOpenFolder; #endif /* __IOpenFolder_FWD_DEFINED__ */ #ifndef __OpenFolder_FWD_DEFINED__ #define __OpenFolder_FWD_DEFINED__ #ifdef __cplusplus typedef class OpenFolder OpenFolder; #else typedef struct OpenFolder OpenFolder; #endif /* __cplusplus */ #endif /* __OpenFolder_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #include "ocidl.h" #ifdef __cplusplus extern "C"{ #endif void * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void * ); #ifndef __IOpenFolder_INTERFACE_DEFINED__ #define __IOpenFolder_INTERFACE_DEFINED__ /* interface IOpenFolder */ /* [unique][helpstring][dual][uuid][object] */ EXTERN_C const IID IID_IOpenFolder; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("90A7C85C-C7B7-4D83-81CD-E76A9CFAE412") IOpenFolder : public IDispatch { public: }; #else /* C style interface */ typedef struct IOpenFolderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IOpenFolder * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IOpenFolder * This); ULONG ( STDMETHODCALLTYPE *Release )( IOpenFolder * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( IOpenFolder * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( IOpenFolder * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( IOpenFolder * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IOpenFolder * 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); END_INTERFACE } IOpenFolderVtbl; interface IOpenFolder { CONST_VTBL struct IOpenFolderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IOpenFolder_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IOpenFolder_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IOpenFolder_Release(This) \ (This)->lpVtbl -> Release(This) #define IOpenFolder_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define IOpenFolder_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IOpenFolder_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IOpenFolder_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IOpenFolder_INTERFACE_DEFINED__ */ #ifndef __OPENFOLDERLib_LIBRARY_DEFINED__ #define __OPENFOLDERLib_LIBRARY_DEFINED__ /* library OPENFOLDERLib */ /* [helpstring][version][uuid] */ EXTERN_C const IID LIBID_OPENFOLDERLib; EXTERN_C const CLSID CLSID_OpenFolder; #ifdef __cplusplus class DECLSPEC_UUID("2DE2822E-4FFC-4DBC-B214-D94B8087C5BE") OpenFolder; #endif #endif /* __OPENFOLDERLib_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ "ddraper@f12373e4-23ff-6a4a-9817-e77f09f3faef" ]
[ [ [ 1, 216 ] ] ]
b655c99f13aba92beec5a2288931572ebbe5357a
21da454a8f032d6ad63ca9460656c1e04440310e
/src/net/worldscale/pimap/server/wsiPsUser.h
ccc1bb8bd7459888d9f22a0f59ed9d2536f21662
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
369
h
#pragma once #include <wcpp/lang/wsiObject.h> #define WS_IID_OF_wsiPsUser \ { 0x2b67adba, 0x67f, 0x4758, { 0xb1, 0xd7, 0x7, 0x25, 0xee, 0x44, 0x46, 0xa6 } } // {2B67ADBA-067F-4758-B1D7-0725EE4446A6} class wsiPsUser : public wsiObject { public: static const ws_iid sIID; public: WS_METHOD( ws_uint32 , GetUserId )(void) = 0; };
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 18 ] ] ]
a9cd2c6d090177d7a83d8a7a58d1ef2206ff0c37
c2abb873c8b352d0ec47757031e4a18b9190556e
/src/ogreIncludes/OgreAutoParamDataSource.h
dfb4605a81056bdd0f482711b5b8fcba5c64d8d1
[]
no_license
twktheainur/vortex-ee
70b89ec097cd1c74cde2b75f556448965d0d345d
8b8aef42396cbb4c9ce063dd1ab2f44d95e994c6
refs/heads/master
2021-01-10T02:26:21.913972
2009-01-30T12:53:21
2009-01-30T12:53:21
44,046,528
0
0
null
null
null
null
UTF-8
C++
false
false
12,873
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #ifndef __AutoParamDataSource_H_ #define __AutoParamDataSource_H_ #include "OgrePrerequisites.h" #include "OgreCommon.h" #include "OgreMatrix4.h" #include "OgreVector4.h" #include "OgreLight.h" #include "OgreColourValue.h" namespace Ogre { // forward decls struct VisibleObjectsBoundsInfo; /** This utility class is used to hold the information used to generate the matrices and other information required to automatically populate GpuProgramParameters. @remarks This class exercises a lazy-update scheme in order to avoid having to update all the information a GpuProgramParameters class could possibly want all the time. It relies on the SceneManager to update it when the base data has changed, and will calculate concatenated matrices etc only when required, passing back precalculated matrices when they are requested more than once when the underlying information has not altered. */ class _OgreExport AutoParamDataSource : public SceneMgtAlloc { protected: const Light& getLight(size_t index) const; mutable Matrix4 mWorldMatrix[256]; mutable size_t mWorldMatrixCount; mutable const Matrix4* mWorldMatrixArray; mutable Matrix4 mWorldViewMatrix; mutable Matrix4 mViewProjMatrix; mutable Matrix4 mWorldViewProjMatrix; mutable Matrix4 mInverseWorldMatrix; mutable Matrix4 mInverseWorldViewMatrix; mutable Matrix4 mInverseViewMatrix; mutable Matrix4 mInverseTransposeWorldMatrix; mutable Matrix4 mInverseTransposeWorldViewMatrix; mutable Vector4 mCameraPositionObjectSpace; mutable Matrix4 mTextureViewProjMatrix[OGRE_MAX_SIMULTANEOUS_LIGHTS]; mutable Matrix4 mTextureWorldViewProjMatrix[OGRE_MAX_SIMULTANEOUS_LIGHTS]; mutable Matrix4 mSpotlightViewProjMatrix[OGRE_MAX_SIMULTANEOUS_LIGHTS]; mutable Matrix4 mSpotlightWorldViewProjMatrix[OGRE_MAX_SIMULTANEOUS_LIGHTS]; mutable Vector4 mShadowCamDepthRanges[OGRE_MAX_SIMULTANEOUS_LIGHTS]; mutable Matrix4 mViewMatrix; mutable Matrix4 mProjectionMatrix; mutable Real mDirLightExtrusionDistance; mutable Vector4 mCameraPosition; mutable bool mWorldMatrixDirty; mutable bool mViewMatrixDirty; mutable bool mProjMatrixDirty; mutable bool mWorldViewMatrixDirty; mutable bool mViewProjMatrixDirty; mutable bool mWorldViewProjMatrixDirty; mutable bool mInverseWorldMatrixDirty; mutable bool mInverseWorldViewMatrixDirty; mutable bool mInverseViewMatrixDirty; mutable bool mInverseTransposeWorldMatrixDirty; mutable bool mInverseTransposeWorldViewMatrixDirty; mutable bool mCameraPositionObjectSpaceDirty; mutable bool mCameraPositionDirty; mutable bool mTextureViewProjMatrixDirty[OGRE_MAX_SIMULTANEOUS_LIGHTS]; mutable bool mTextureWorldViewProjMatrixDirty[OGRE_MAX_SIMULTANEOUS_LIGHTS]; mutable bool mSpotlightViewProjMatrixDirty[OGRE_MAX_SIMULTANEOUS_LIGHTS]; mutable bool mSpotlightWorldViewProjMatrixDirty[OGRE_MAX_SIMULTANEOUS_LIGHTS]; mutable bool mShadowCamDepthRangesDirty[OGRE_MAX_SIMULTANEOUS_LIGHTS]; mutable ColourValue mAmbientLight; mutable ColourValue mFogColour; mutable Vector4 mFogParams; mutable int mPassNumber; mutable Vector4 mSceneDepthRange; mutable bool mSceneDepthRangeDirty; const Renderable* mCurrentRenderable; const Camera* mCurrentCamera; bool mCameraRelativeRendering; Vector3 mCameraRelativePosition; const LightList* mCurrentLightList; const Frustum* mCurrentTextureProjector[OGRE_MAX_SIMULTANEOUS_LIGHTS]; const RenderTarget* mCurrentRenderTarget; const Viewport* mCurrentViewport; const SceneManager* mCurrentSceneManager; const VisibleObjectsBoundsInfo* mMainCamBoundsInfo; const Pass* mCurrentPass; Light mBlankLight; public: AutoParamDataSource(); virtual ~AutoParamDataSource(); /** Updates the current renderable */ virtual void setCurrentRenderable(const Renderable* rend); /** Sets the world matrices, avoid query from renderable again */ virtual void setWorldMatrices(const Matrix4* m, size_t count); /** Updates the current camera */ virtual void setCurrentCamera(const Camera* cam, bool useCameraRelative); /** Sets the light list that should be used, and it's base index from the global list */ virtual void setCurrentLightList(const LightList* ll); /** Sets the current texture projector for a index */ virtual void setTextureProjector(const Frustum* frust, size_t index); /** Sets the current render target */ virtual void setCurrentRenderTarget(const RenderTarget* target); /** Sets the current viewport */ virtual void setCurrentViewport(const Viewport* viewport); /** Sets the shadow extrusion distance to be used for point lights. */ virtual void setShadowDirLightExtrusionDistance(Real dist); /** Sets the main camera's scene bounding information */ virtual void setMainCamBoundsInfo(VisibleObjectsBoundsInfo* info); /** Set the current scene manager for enquiring on demand */ virtual void setCurrentSceneManager(const SceneManager* sm); /** Sets the current pass */ virtual void setCurrentPass(const Pass* pass); virtual const Matrix4& getWorldMatrix(void) const; virtual const Matrix4* getWorldMatrixArray(void) const; virtual size_t getWorldMatrixCount(void) const; virtual const Matrix4& getViewMatrix(void) const; virtual const Matrix4& getViewProjectionMatrix(void) const; virtual const Matrix4& getProjectionMatrix(void) const; virtual const Matrix4& getWorldViewProjMatrix(void) const; virtual const Matrix4& getWorldViewMatrix(void) const; virtual const Matrix4& getInverseWorldMatrix(void) const; virtual const Matrix4& getInverseWorldViewMatrix(void) const; virtual const Matrix4& getInverseViewMatrix(void) const; virtual const Matrix4& getInverseTransposeWorldMatrix(void) const; virtual const Matrix4& getInverseTransposeWorldViewMatrix(void) const; virtual const Vector4& getCameraPosition(void) const; virtual const Vector4& getCameraPositionObjectSpace(void) const; /** Get the light which is 'index'th closest to the current object */ virtual float getLightNumber(size_t index) const; virtual float getLightCount() const; virtual int getLightCastsShadows(size_t index) const; virtual const ColourValue& getLightDiffuseColour(size_t index) const; virtual const ColourValue& getLightSpecularColour(size_t index) const; virtual const ColourValue getLightDiffuseColourWithPower(size_t index) const; virtual const ColourValue getLightSpecularColourWithPower(size_t index) const; virtual const Vector3& getLightPosition(size_t index) const; virtual Vector4 getLightAs4DVector(size_t index) const; virtual const Vector3& getLightDirection(size_t index) const; virtual Real getLightPowerScale(size_t index) const; virtual Vector4 getLightAttenuation(size_t index) const; virtual Vector4 getSpotlightParams(size_t index) const; virtual void setAmbientLightColour(const ColourValue& ambient); virtual const ColourValue& getAmbientLightColour(void) const; virtual const ColourValue& getSurfaceAmbientColour(void) const; virtual const ColourValue& getSurfaceDiffuseColour(void) const; virtual const ColourValue& getSurfaceSpecularColour(void) const; virtual const ColourValue& getSurfaceEmissiveColour(void) const; virtual Real getSurfaceShininess(void) const; virtual ColourValue getDerivedAmbientLightColour(void) const; virtual ColourValue getDerivedSceneColour(void) const; virtual void setFog(FogMode mode, const ColourValue& colour, Real expDensity, Real linearStart, Real linearEnd); virtual const ColourValue& getFogColour(void) const; virtual const Vector4& getFogParams(void) const; virtual const Matrix4& getTextureViewProjMatrix(size_t index) const; virtual const Matrix4& getTextureWorldViewProjMatrix(size_t index) const; virtual const Matrix4& getSpotlightViewProjMatrix(size_t index) const; virtual const Matrix4& getSpotlightWorldViewProjMatrix(size_t index) const; virtual const Matrix4& getTextureTransformMatrix(size_t index) const; virtual const RenderTarget* getCurrentRenderTarget(void) const; virtual const Renderable* getCurrentRenderable(void) const; virtual const Pass* getCurrentPass(void) const; virtual Vector4 getTextureSize(size_t index) const; virtual Vector4 getInverseTextureSize(size_t index) const; virtual Vector4 getPackedTextureSize(size_t index) const; virtual Real getShadowExtrusionDistance(void) const; virtual const Vector4& getSceneDepthRange() const; virtual const Vector4& getShadowSceneDepthRange(size_t index) const; virtual const ColourValue& getShadowColour() const; virtual Matrix4 getInverseViewProjMatrix(void) const; virtual Matrix4 getInverseTransposeViewProjMatrix() const; virtual Matrix4 getTransposeViewProjMatrix() const; virtual Matrix4 getTransposeViewMatrix() const; virtual Matrix4 getInverseTransposeViewMatrix() const; virtual Matrix4 getTransposeProjectionMatrix() const; virtual Matrix4 getInverseProjectionMatrix() const; virtual Matrix4 getInverseTransposeProjectionMatrix() const; virtual Matrix4 getTransposeWorldViewProjMatrix() const; virtual Matrix4 getInverseWorldViewProjMatrix() const; virtual Matrix4 getInverseTransposeWorldViewProjMatrix() const; virtual Matrix4 getTransposeWorldViewMatrix() const; virtual Matrix4 getTransposeWorldMatrix() const; virtual Real getTime(void) const; virtual Real getTime_0_X(Real x) const; virtual Real getCosTime_0_X(Real x) const; virtual Real getSinTime_0_X(Real x) const; virtual Real getTanTime_0_X(Real x) const; virtual Vector4 getTime_0_X_packed(Real x) const; virtual Real getTime_0_1(Real x) const; virtual Real getCosTime_0_1(Real x) const; virtual Real getSinTime_0_1(Real x) const; virtual Real getTanTime_0_1(Real x) const; virtual Vector4 getTime_0_1_packed(Real x) const; virtual Real getTime_0_2Pi(Real x) const; virtual Real getCosTime_0_2Pi(Real x) const; virtual Real getSinTime_0_2Pi(Real x) const; virtual Real getTanTime_0_2Pi(Real x) const; virtual Vector4 getTime_0_2Pi_packed(Real x) const; virtual Real getFrameTime(void) const; virtual Real getFPS() const; virtual Real getViewportWidth() const; virtual Real getViewportHeight() const; virtual Real getInverseViewportWidth() const; virtual Real getInverseViewportHeight() const; virtual Vector3 getViewDirection() const; virtual Vector3 getViewSideVector() const; virtual Vector3 getViewUpVector() const; virtual Real getFOV() const; virtual Real getNearClipDistance() const; virtual Real getFarClipDistance() const; virtual int getPassNumber(void) const; virtual void setPassNumber(const int passNumber); virtual void incPassNumber(void); }; } #endif
[ "seb.owk@37e2baaa-b253-11dd-9381-bf584fb1fa83" ]
[ [ [ 1, 250 ] ] ]
eedfc04be436e1ef18e4125a174ba011a334c26d
718dc2ad71e8b39471b5bf0c6d60cbe5f5c183e1
/soft micros/Codigo/codigo portable/Timer/interrup_1ms_40ms/BaseTimers_1ms_40ms.cpp
c797a7ab8208089b1f7bfd3e0e61c5cb213f1c5a
[]
no_license
jonyMarino/microsdhacel
affb7a6b0ea1f4fd96d79a04d1a3ec3eaa917bca
66d03c6a9d3a2d22b4d7104e2a38a2c9bb4061d3
refs/heads/master
2020-05-18T19:53:51.301695
2011-05-30T20:40:24
2011-05-30T20:40:24
34,532,512
0
0
null
null
null
null
UTF-8
C++
false
false
959
cpp
#include "BaseTimers_1ms_40ms.hpp" #include "timer_interrupt.h" #include "Cpu.h" BaseTimers_1ms_40ms* BaseTimers_1ms_40ms::instance=NULL; BaseTimers_1ms_40ms::BaseTimers_1ms_40ms(){ on1ms.pmethod=inc1; on1ms.obj=this; add1msListener(&on1ms); on40ms.pmethod=inc40; on40ms.obj=this; add40msListener(&on40ms); } BaseTimers_1ms_40ms *BaseTimers_1ms_40ms::getInstance(void){ if(!instance) instance = new BaseTimers_1ms_40ms(); return instance; } void BaseTimers_1ms_40ms::lockInc(){ Cpu_DisableInt(); } void BaseTimers_1ms_40ms::unlockInc(){ Cpu_EnableInt(); } void BaseTimers_1ms_40ms::inc1(void * _self){ BaseTimers_1ms_40ms * self=(BaseTimers_1ms_40ms *)_self; self->incrementar(1); self->actualizarTimers(); } void BaseTimers_1ms_40ms::inc40(void * _self){ BaseTimers_1ms_40ms * self=(BaseTimers_1ms_40ms *)_self; self->incrementar(40); self->actualizarTimers(); }
[ "nicopimen@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549", "jonymarino@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549" ]
[ [ [ 1, 11 ], [ 13, 13 ], [ 16, 46 ] ], [ [ 12, 12 ], [ 14, 15 ] ] ]
1c9b903d6eb26e8c776694d0d83897779a13b0c4
f177993b13e97f9fecfc0e751602153824dfef7e
/ImPro/ImProBaseClass/MyLib/LEADTOOL/Include/Filters/ILMNetMux2.h
c0fe80e5b7f09ae276e784602ef9fc524eb10277
[]
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
14,911
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:54:48 2009 */ /* Compiler settings for .\LMNetMux.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 __ILMNetMux2_h__ #define __ILMNetMux2_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __ILMNetMux1_FWD_DEFINED__ #define __ILMNetMux1_FWD_DEFINED__ typedef interface ILMNetMux1 ILMNetMux1; #endif /* __ILMNetMux1_FWD_DEFINED__ */ #ifndef __ILMNetMux_FWD_DEFINED__ #define __ILMNetMux_FWD_DEFINED__ typedef interface ILMNetMux ILMNetMux; #endif /* __ILMNetMux_FWD_DEFINED__ */ #ifndef __LMNetMux_FWD_DEFINED__ #define __LMNetMux_FWD_DEFINED__ #ifdef __cplusplus typedef class LMNetMux LMNetMux; #else typedef struct LMNetMux LMNetMux; #endif /* __cplusplus */ #endif /* __LMNetMux_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #include "ocidl.h" #ifdef __cplusplus extern "C"{ #endif #ifndef __LMNetMuxLib_LIBRARY_DEFINED__ #define __LMNetMuxLib_LIBRARY_DEFINED__ /* library LMNetMuxLib */ /* [helpstring][helpfile][version][uuid] */ #ifndef __LMNetMux2_GUID__ #define __LMNetMux2_GUID__ static const IID LIBID_LMNetMuxLib = {0xe2b7de00,0x38c5,0x11d5,{0x91,0xf6,0x00,0x10,0x4b,0xdb,0x8f,0xf9}}; static const CLSID CLSID_LMNetMux = {0xe2b7de01,0x38c5,0x11d5,{0x91,0xf6,0x00,0x10,0x4b,0xdb,0x8f,0xf9}}; static const IID IID_ILMNetMux1 = {0xe2b7de02,0x38c5,0x11d5,{0x91,0xf6,0x00,0x10,0x4b,0xdb,0x8f,0xf9}}; static const IID IID_ILMNetMux = {0xe2b7db80,0x38c5,0x11d5,{0x91,0xf6,0x00,0x10,0x4b,0xdb,0x8f,0xf9}}; #endif DEFINE_GUID(LIBID_LMNetMuxLib,0xE2B7DE00,0x38C5,0x11D5,0x91,0xF6,0x00,0x10,0x4B,0xDB,0x8F,0xF9); #ifndef __ILMNetMux1_INTERFACE_DEFINED__ #define __ILMNetMux1_INTERFACE_DEFINED__ /* interface ILMNetMux1 */ /* [unique][helpstring][dual][uuid][object] */ DEFINE_GUID(IID_ILMNetMux1,0xE2B7DE02,0x38C5,0x11D5,0x91,0xF6,0x00,0x10,0x4B,0xDB,0x8F,0xF9); #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("E2B7DE02-38C5-11D5-91F6-00104BDB8FF9") ILMNetMux1 : public IDispatch { public: virtual /* [helpstring][helpcontext][id][propget] */ HRESULT STDMETHODCALLTYPE get_BitRate( /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][helpcontext][id][propget] */ HRESULT STDMETHODCALLTYPE get_BitRateLimit( /* [retval][out] */ long *pVal) = 0; virtual /* [helpstring][helpcontext][id][propput] */ HRESULT STDMETHODCALLTYPE put_BitRateLimit( /* [in] */ long newVal) = 0; virtual /* [helpstring][helpcontext][id][propget] */ HRESULT STDMETHODCALLTYPE get_LiveSource( /* [retval][out] */ VARIANT_BOOL *pVal) = 0; virtual /* [helpstring][helpcontext][id][propput] */ HRESULT STDMETHODCALLTYPE put_LiveSource( /* [in] */ VARIANT_BOOL newVal) = 0; virtual /* [helpstring][helpcontext][id] */ HRESULT STDMETHODCALLTYPE WriteMessage( /* [in] */ BSTR Message) = 0; }; #else /* C style interface */ typedef struct ILMNetMux1Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( ILMNetMux1 * This, /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( ILMNetMux1 * This); ULONG ( STDMETHODCALLTYPE *Release )( ILMNetMux1 * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( ILMNetMux1 * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( ILMNetMux1 * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( ILMNetMux1 * 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 )( ILMNetMux1 * 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][helpcontext][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BitRate )( ILMNetMux1 * This, /* [retval][out] */ long *pVal); /* [helpstring][helpcontext][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BitRateLimit )( ILMNetMux1 * This, /* [retval][out] */ long *pVal); /* [helpstring][helpcontext][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BitRateLimit )( ILMNetMux1 * This, /* [in] */ long newVal); /* [helpstring][helpcontext][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_LiveSource )( ILMNetMux1 * This, /* [retval][out] */ VARIANT_BOOL *pVal); /* [helpstring][helpcontext][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_LiveSource )( ILMNetMux1 * This, /* [in] */ VARIANT_BOOL newVal); /* [helpstring][helpcontext][id] */ HRESULT ( STDMETHODCALLTYPE *WriteMessage )( ILMNetMux1 * This, /* [in] */ BSTR Message); END_INTERFACE } ILMNetMux1Vtbl; interface ILMNetMux1 { CONST_VTBL struct ILMNetMux1Vtbl *lpVtbl; }; #ifdef COBJMACROS #define ILMNetMux1_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ILMNetMux1_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ILMNetMux1_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ILMNetMux1_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ILMNetMux1_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ILMNetMux1_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ILMNetMux1_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ILMNetMux1_get_BitRate(This,pVal) \ ( (This)->lpVtbl -> get_BitRate(This,pVal) ) #define ILMNetMux1_get_BitRateLimit(This,pVal) \ ( (This)->lpVtbl -> get_BitRateLimit(This,pVal) ) #define ILMNetMux1_put_BitRateLimit(This,newVal) \ ( (This)->lpVtbl -> put_BitRateLimit(This,newVal) ) #define ILMNetMux1_get_LiveSource(This,pVal) \ ( (This)->lpVtbl -> get_LiveSource(This,pVal) ) #define ILMNetMux1_put_LiveSource(This,newVal) \ ( (This)->lpVtbl -> put_LiveSource(This,newVal) ) #define ILMNetMux1_WriteMessage(This,Message) \ ( (This)->lpVtbl -> WriteMessage(This,Message) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ILMNetMux1_INTERFACE_DEFINED__ */ #ifndef __ILMNetMux_INTERFACE_DEFINED__ #define __ILMNetMux_INTERFACE_DEFINED__ /* interface ILMNetMux */ /* [unique][helpstring][dual][uuid][object] */ DEFINE_GUID(IID_ILMNetMux,0xE2B7DB80,0x38C5,0x11D5,0x91,0xF6,0x00,0x10,0x4B,0xDB,0x8F,0xF9); #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("E2B7DB80-38C5-11D5-91F6-00104BDB8FF9") ILMNetMux : public ILMNetMux1 { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_MaxQueueDuration( /* [retval][out] */ double *pVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_MaxQueueDuration( /* [in] */ double newVal) = 0; }; #else /* C style interface */ typedef struct ILMNetMuxVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( ILMNetMux * This, /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( ILMNetMux * This); ULONG ( STDMETHODCALLTYPE *Release )( ILMNetMux * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( ILMNetMux * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( ILMNetMux * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( ILMNetMux * 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 )( ILMNetMux * 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][helpcontext][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BitRate )( ILMNetMux * This, /* [retval][out] */ long *pVal); /* [helpstring][helpcontext][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BitRateLimit )( ILMNetMux * This, /* [retval][out] */ long *pVal); /* [helpstring][helpcontext][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BitRateLimit )( ILMNetMux * This, /* [in] */ long newVal); /* [helpstring][helpcontext][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_LiveSource )( ILMNetMux * This, /* [retval][out] */ VARIANT_BOOL *pVal); /* [helpstring][helpcontext][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_LiveSource )( ILMNetMux * This, /* [in] */ VARIANT_BOOL newVal); /* [helpstring][helpcontext][id] */ HRESULT ( STDMETHODCALLTYPE *WriteMessage )( ILMNetMux * This, /* [in] */ BSTR Message); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_MaxQueueDuration )( ILMNetMux * This, /* [retval][out] */ double *pVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_MaxQueueDuration )( ILMNetMux * This, /* [in] */ double newVal); END_INTERFACE } ILMNetMuxVtbl; interface ILMNetMux { CONST_VTBL struct ILMNetMuxVtbl *lpVtbl; }; #ifdef COBJMACROS #define ILMNetMux_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ILMNetMux_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ILMNetMux_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ILMNetMux_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ILMNetMux_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ILMNetMux_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ILMNetMux_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ILMNetMux_get_BitRate(This,pVal) \ ( (This)->lpVtbl -> get_BitRate(This,pVal) ) #define ILMNetMux_get_BitRateLimit(This,pVal) \ ( (This)->lpVtbl -> get_BitRateLimit(This,pVal) ) #define ILMNetMux_put_BitRateLimit(This,newVal) \ ( (This)->lpVtbl -> put_BitRateLimit(This,newVal) ) #define ILMNetMux_get_LiveSource(This,pVal) \ ( (This)->lpVtbl -> get_LiveSource(This,pVal) ) #define ILMNetMux_put_LiveSource(This,newVal) \ ( (This)->lpVtbl -> put_LiveSource(This,newVal) ) #define ILMNetMux_WriteMessage(This,Message) \ ( (This)->lpVtbl -> WriteMessage(This,Message) ) #define ILMNetMux_get_MaxQueueDuration(This,pVal) \ ( (This)->lpVtbl -> get_MaxQueueDuration(This,pVal) ) #define ILMNetMux_put_MaxQueueDuration(This,newVal) \ ( (This)->lpVtbl -> put_MaxQueueDuration(This,newVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ILMNetMux_INTERFACE_DEFINED__ */ DEFINE_GUID(CLSID_LMNetMux,0xE2B7DE01,0x38C5,0x11D5,0x91,0xF6,0x00,0x10,0x4B,0xDB,0x8F,0xF9); #ifdef __cplusplus class DECLSPEC_UUID("E2B7DE01-38C5-11D5-91F6-00104BDB8FF9") LMNetMux; #endif #endif /* __LMNetMuxLib_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 458 ] ] ]
a89e61014219f4cd0605a2ce9bc6197005bd1057
744e9a2bf1d0aee245c42ee145392d1f6a6f65c9
/tags/0.11.1-alpha/gui/ttcutlistview.cpp
fe467106d8b5c94b9ea7ae023b2b4124be9e717d
[]
no_license
BackupTheBerlios/ttcut-svn
2b5d00c3c6d16aa118b4a58c7d0702cfcc0b051a
958032e74e8bb144a96b6eb7e1d63bc8ae762096
refs/heads/master
2020-04-22T12:08:57.640316
2009-02-08T16:14:00
2009-02-08T16:14:00
40,747,642
0
0
null
null
null
null
UTF-8
C++
false
false
20,993
cpp
/*----------------------------------------------------------------------------*/ /* COPYRIGHT: TriTime (c) 2003/2005 / www.tritime.org */ /*----------------------------------------------------------------------------*/ /* PROJEKT : TTCUT 2005 */ /* FILE : ttcutlistview.cpp */ /*----------------------------------------------------------------------------*/ /* AUTHOR : b. altendorf (E-Mail: [email protected]) DATE: 02/24/2005 */ /* MODIFIED: b. altendorf DATE: 03/15/2005 */ /* MODIFIED: b. altendorf DATE: 06/20/2005 */ /* MODIFIED: b. altendorf DATE: 06/22/2005 */ /*----------------------------------------------------------------------------*/ // ---------------------------------------------------------------------------- // *** TTCUTLISTVIEW // ---------------------------------------------------------------------------- /*----------------------------------------------------------------------------*/ /* 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 "ttcutlistview.h" //Added by qt3to4: #include <QMouseEvent> #include <Q3PopupMenu> //#define TTCUTLISTVIEW_DEBUG const char c_name[] = "TTCUTLISTVIEW : "; // ///////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // TTCutListItem // ----------------------------------------------------------------------------- // ///////////////////////////////////////////////////////////////////////////// TTCutListItem::TTCutListItem( TTCutListView* parent ) : Q3ListViewItem( (Q3ListView*)parent ) { cut_order = (uint)0; setText( 0, " ---- " ); setText( 1, "00:00:00,000 (0)" ); setText( 2, "00:00:00,000 (0)" ); } TTCutListItem::TTCutListItem( TTCutListView* parent, TTCutListItem* after) : Q3ListViewItem( (Q3ListView*) parent, (Q3ListViewItem*)after ) { cut_order = (uint)0; setText( 0, " ---- " ); setText( 1, "00:00:00,000 (0)" ); setText( 2, "00:00:00,000 (0)" ); } // ///////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // TTCutListView // ----------------------------------------------------------------------------- // ///////////////////////////////////////////////////////////////////////////// // construct a list view object // ----------------------------------------------------------------------------- TTCutListView::TTCutListView( QWidget* parent, const char* name ) :Q3ListView( parent, name ) { // AV cut list object avcut_list = NULL; avcut_list = new TTAVCutList(); //no sorting setSorting( -1, false); setSelectionMode(Q3ListView::Single); setAllColumnsShowFocus(TRUE); setColumnWidth( 0, 450 ); setColumnWidth( 1, 250 ); setColumnWidth( 2, 250 ); // Item context menu // --------------------------------------------------------------------------- itemContextMenu = new Q3PopupMenu(this, "itemContextMenu"); itemContextMenu->insertItem("Goto cut &in", this, SLOT(gotoCutIn()), 0,0); itemContextMenu->insertItem("Goto cut &out", this, SLOT(gotoCutOut()), 0,1); itemContextMenu->insertSeparator(2); itemContextMenu->insertItem("Move &up", this, SLOT(itemUp()), 0,3); itemContextMenu->insertItem("Move d&own", this, SLOT(itemDown()), 0,4); itemContextMenu->insertItem("&Delete", this, SLOT(deleteItem()), 0,5); itemContextMenu->insertSeparator(6); itemContextMenu->insertItem("&Preview", this, SLOT(singleCutPreview()),0,7); itemContextMenu->insertSeparator(8); itemContextMenu->insertItem("&Edit", this, SLOT(editItem()), 0,9); // Listview context menue // --------------------------------------------------------------------------- //listContextMenu = new QPopupMenu(this, "listContextMenu"); //listContextMenu->insertItem("tiny", this, SLOT(setThumbsSize(int )), 0, 0); //listContextMenu->insertItem("small", this, SLOT(setThumbsSize(int )), 0, 1); //listContextMenu->insertItem("medium", this, SLOT(setThumbsSize(int )), 0, 2); //listContextMenu->insertItem("large", this, SLOT(setThumbsSize(int )), 0, 3); //listContextMenu->insertItem("huge", this, SLOT(setThumbsSize(int )), 0, 4); //listContextMenu->insertItem("gigantic", this, SLOT(setThumbsSize(int )), 0, 5); } // destructor // ----------------------------------------------------------------------------- TTCutListView::~TTCutListView() { // delete cut list object if( ttAssigned( avcut_list ) ) delete avcut_list; } // Processes the mouse press event e on behalf of the viewed widget // ----------------------------------------------------------------------------- void TTCutListView::contentsMousePressEvent( QMouseEvent *e ) { QPoint mousePressPos; // map mouse coordinates to viewport mousePressPos = contentsToViewport( e->pos()); // select listview item by mouse coordinates TTCutListItem* i = (TTCutListItem*)itemAt( mousePressPos ); // base class event handling; select item if( i && !isSelected(i) ) Q3ListView::contentsMousePressEvent(e); // item is selected and mouse button is left buttom; select current // cut-out frame if( i && e->button() == Qt::LeftButton ) { cut_position = avcut_list->entryAtOrder( i->cut_order ); //qDebug( "%sselect item at order: %d",c_name,i->cut_order ); // emit signal and pass reference of cut position to receiver emit selectCutOut( *cut_position ); return; } // ask for list view context menu if( !i && e->button() == Qt::RightButton ) { qDebug("list context menu not implemented (!)"); return; } // ask for item context menu if( i && e->button() == Qt::RightButton ) { itemContextMenu->exec(QCursor::pos()); } } // add a item at the end of the list view // ----------------------------------------------------------------------------- void TTCutListView::addItem( QString f_name, uint c_in_index, QTime c_in_time, uint c_out_index, QTime c_out_time ) { uint current_order; QString sz_temp; TTCutListItem* list_item; // current order is the lists entry count current_order = childCount(); //qDebug( "%sadd item at order: %d",c_name,current_order ); // new list item list_item = new TTCutListItem( this, (TTCutListItem*)lastItem() ); // set item text list_item->cut_order = current_order; list_item->setText( 0, f_name ); sz_temp.sprintf( "%s (%d)", c_in_time.toString("hh:mm:ss.zzz").ascii(), c_in_index ); list_item->setText( 1, sz_temp ); sz_temp.sprintf( "%s (%d)", c_out_time.toString("hh:mm:ss.zzz").ascii(), c_out_index ); list_item->setText( 2, sz_temp); // set column width setColumnWidth( 0, 250 ); setColumnWidth( 1, 150 ); setColumnWidth( 2, 150 ); deselectAll(); // add the new cut position to the av cut list avcut_list->addCutPosition( c_in_index, c_out_index, current_order ); // calculate the new resulting video length calcResultCutLen(); //testListView(); } // add a item at the end of the list view // ----------------------------------------------------------------------------- void TTCutListView::addItem( QString f_name, uint c_in_index, off64_t c_in_off, QTime c_in_time, uint c_out_index, off64_t c_out_off, QTime c_out_time ) { uint current_order; QString sz_temp; TTCutListItem* list_item; // current order is the lists entry count current_order = childCount(); //qDebug( "%sadd item at order: %d",c_name,current_order ); // new list item list_item = new TTCutListItem( this, (TTCutListItem*)lastItem() ); // set item text list_item->cut_order = current_order; list_item->setText( 0, f_name ); sz_temp.sprintf( "%s (%d)", c_in_time.toString("hh:mm:ss.zzz").ascii(), c_in_index ); list_item->setText( 1, sz_temp ); sz_temp.sprintf( "%s (%d)", c_out_time.toString("hh:mm:ss.zzz").ascii(), c_out_index ); list_item->setText( 2, sz_temp); // set column width setColumnWidth( 0, 250 ); setColumnWidth( 1, 150 ); setColumnWidth( 2, 150 ); deselectAll(); // add the new cut position to the av cut list avcut_list->addCutPosition( c_in_index, c_in_off, c_out_index, c_out_off, current_order ); // calculate the new resulting video length calcResultCutLen(); //testListView(); } // clear the list view; remove all items from the list // ----------------------------------------------------------------------------- void TTCutListView::clearList() { #if defined (TTCUTLISTVIEW_DEBUG) qDebug( "%sclearList: %d",c_name,childCount() ); #endif //list-view iterator Q3ListViewItemIterator cutIt( this ); // iterate trough the list while ( cutIt.current() ) { // remove the corresponding entry in avcut list TTCutListItem* list_item = (TTCutListItem*)cutIt.current(); #if defined (TTCUTLISTVIEW_DEBUG) qDebug( "%sremove entry: %d",c_name,list_item->cut_order ); #endif avcut_list->removeEntryAtOrder( list_item->cut_order ); delete cutIt.current(); } delete avcut_list; avcut_list = new TTAVCutList(); //testListView(); } // deselect all items // ----------------------------------------------------------------------------- void TTCutListView::deselectAll() { if ( currentItem() ) setSelected( currentItem(), false ); } // return true if currently one list item is selcted // ----------------------------------------------------------------------------- bool TTCutListView::isItemSelected() { if ( currentItem() ) return isSelected( currentItem() ); else return false; } // returns the number of parentless child (top-level) items in the list // ----------------------------------------------------------------------------- int TTCutListView::count() { return childCount(); } // delete the currently selected item // ----------------------------------------------------------------------------- void TTCutListView::deleteItem() { if ( currentItem() ) { // remove the corresponding entry in avcut list TTCutListItem* list_item = (TTCutListItem*)currentItem(); //qDebug( "%sremove item at order: %d",c_name,list_item->cut_order ); avcut_list->removeEntryAtOrder( list_item->cut_order ); // delete item from the list view delete currentItem(); // new order newOrder(); // select the next current item setSelected( currentItem(), true ); // new resulting video length calcResultCutLen(); //testListView(); } } // edit selected list view item data // ----------------------------------------------------------------------------- void TTCutListView::editItem() { // no item selected if ( !currentItem() ) return; // get pointer to current selected item TTCutListItem* current = (TTCutListItem*)currentItem(); // get according cut position from av cut list data //qDebug( "%sedit item at order: %d",c_name,current->cut_order ); cut_position = avcut_list->entryAtOrder( current->cut_order ); // create copy TTAVCutPosition temp_pos( cut_position->cutIn(), cut_position->cutOut(), cut_position->cutOrder() ); // remove the entry from the cut list avcut_list->removeEntryAtOrder( current->cut_order ); // remove the current item from list view delete current; // new order newOrder(); // new resulting length calcResultCutLen(); //testListView(); // emit signal an pass reference of cut position to receiver emit editCutListItem( temp_pos ); } // refresh the list's order void TTCutListView::newOrder() { uint old_order; uint new_order = (uint)0; TTCutListItem* list_item; //list-view iterator Q3ListViewItemIterator cutIt( this ); // iterate trough the list while ( cutIt.current() ) { list_item = (TTCutListItem*)cutIt.current(); old_order = list_item->cut_order; list_item->cut_order = new_order; new_order++; cutIt++; } //testListView(); } // move the selected item one step up in the list // ----------------------------------------------------------------------------- void TTCutListView::itemUp() { uint order_current; uint order_above; // no item selected if ( !currentItem() ) return; // pointer to current and above item (precursor) TTCutListItem* above = (TTCutListItem*)currentItem()->itemAbove(); TTCutListItem* current = (TTCutListItem*)currentItem(); // item have a precursor if ( above ) { // get the cut order order_current = current->cut_order; order_above = above->cut_order; // take item from list but don't delete it takeItem( above ); // create a new item after current position TTCutListItem* list_item = new TTCutListItem( this, current); // copy data from above item to new item list_item->setText( 0 , above->text( 0 ) ); list_item->setText( 1 , above->text( 1 ) ); list_item->setText( 2 , above->text( 2 ) ); // swap the cut order list_item->cut_order = order_current; current->cut_order = order_above; avcut_list->entryAtOrder( order_current )->setCutOrder( order_above ); avcut_list->entryAtOrder( order_above )->setCutOrder( order_current ); avcut_list->sort(); // remove above item from list delete above; //testListView(); } } // move the selected item one step down in the list // ----------------------------------------------------------------------------- void TTCutListView::itemDown() { uint order_current; uint order_below; // no item selected if ( !currentItem() ) return; // pointer to current and above item (precursor) TTCutListItem* below = (TTCutListItem*)currentItem()->itemBelow(); TTCutListItem* current = (TTCutListItem*)currentItem(); // item have a successor if ( below ) { // get the cut order order_current = current->cut_order; order_below = below->cut_order; // take current item from list but don't delete it takeItem( current ); // create a new item after below position TTCutListItem* list_item = new TTCutListItem( this, below ); // copy data from above item to new item list_item->setText( 0 , current->text( 0 ) ); list_item->setText( 1 , current->text( 1 ) ); list_item->setText( 2 , current->text( 2 ) ); setSelected( list_item, true ); // swap the cut order list_item->cut_order = order_below; below->cut_order = order_current; avcut_list->entryAtOrder( order_current )->setCutOrder( order_below ); avcut_list->entryAtOrder( order_below )->setCutOrder( order_current ); avcut_list->sort(); // remove current item from list delete current; //testListView(); } } // item context menu: goto cut-in position // ----------------------------------------------------------------------------- void TTCutListView::gotoCutIn() { // no item selected if ( !currentItem() ) return; // get pointer to current item TTCutListItem* current = (TTCutListItem*)currentItem(); cut_position = avcut_list->entryAtOrder( current->cut_order ); // emit signal and pass reference to selected cut position emit showCutIn( *cut_position ); } // item context menu: goto cut-out position // ----------------------------------------------------------------------------- void TTCutListView::gotoCutOut() { // no item selected if ( !currentItem() ) return; // get pointer to current item TTCutListItem* current = (TTCutListItem*)currentItem(); cut_position = avcut_list->entryAtOrder( current->cut_order ); // emit signal and pass reference to selected cut position emit showCutOut( *cut_position ); } // cut-out position changed // ----------------------------------------------------------------------------- void TTCutListView::cutOutIndexChanged( uint c_out_index, QTime c_out_time ) { QString sz_temp; // no item selected if ( !currentItem() ) return; // get pointer to current item TTCutListItem* current = (TTCutListItem*)currentItem(); avcut_list->entryAtOrder( current->cut_order )->setCutOut( c_out_index ); // set new item text sz_temp.sprintf( "%s (%d)", c_out_time.toString("hh:mm:ss.zzz").ascii(), c_out_index ); current->setText( 2, sz_temp ); // new resulting video length calcResultCutLen(); } // create cut position for single preview // ----------------------------------------------------------------------------- void TTCutListView::singleCutPreview() { // no item selected if ( !currentItem() ) return; // get pointer to current item TTCutListItem* current = (TTCutListItem*)currentItem(); emit previewSingleCut( current->cut_order ); } TTAVCutList* TTCutListView::cutList() { return avcut_list; } // calculate the resulting video length (in frames) // ----------------------------------------------------------------------------- void TTCutListView::calcResultCutLen() { uint i; uint start_pos; uint end_pos; off64_t start_off; off64_t end_off; // reset video cut length video_cut_length = (uint)0; video_cut_size = (off64_t)0; avcut_list->sortCutOrder(); // walk through the av cut list for ( i = (uint)0; i < (uint)avcut_list->count(); (uint)i++ ) { start_pos = avcut_list->cutInAt( (uint)i ); end_pos = avcut_list->cutOutAt( (uint)i ); start_off = avcut_list->cutInOffsetAt( (uint)i ); end_off = avcut_list->cutOutOffsetAt( (uint)i ); video_cut_length += end_pos - start_pos; video_cut_size += end_off - start_off; } //qDebug( "%snew cut length: %d %ld",c_name,video_cut_length,video_cut_size ); emit newCutLen( video_cut_length, video_cut_size ); } // return the resulting video cut length (in frames) // ----------------------------------------------------------------------------- uint TTCutListView::getResultFrames() { return video_cut_length; } void TTCutListView::testListView() { TTCutListItem* list_item; uint list_order = 0; qDebug( "%savcut_list count: %d",c_name,avcut_list->count() ); qDebug( "%slist view count: %d",c_name,count() ); qDebug( "%s----------------------------------------",c_name ); //list-view iterator Q3ListViewItemIterator cutIt( this ); // iterate trough the list while ( cutIt.current() ) { list_item = (TTCutListItem*)cutIt.current(); qDebug( "%slist / view order: %d - %d / %d",c_name,list_order, list_item->cut_order, avcut_list->entryAtOrder( list_item->cut_order )->cutOrder() ); list_order++; cutIt++; } } void TTCutListView::writeListToProject( TTCutProject* prj ) { int i; int start_pos; int end_pos; prj->writeCutSection( true ); avcut_list->sortCutOrder(); // walk through the av cut list for ( i = 0; i < avcut_list->count(); i++ ) { start_pos = avcut_list->cutInAt( (uint)i ); end_pos = avcut_list->cutOutAt( (uint)i ); prj->writeCutEntry( start_pos, end_pos ); } prj->writeCutSection( false ); }
[ "tritime@7763a927-590e-0410-8f7f-dbc853b76eaa" ]
[ [ [ 1, 670 ] ] ]
0b886245bf9c41c19ee2ff0d06e31ed0207befc0
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Graphics/RenderComponent/RenderComponent.h
e45f19e7463e3bc7cd5ca5ca87a7848d3e1d0333
[]
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
715
h
#ifndef RenderComponentH_H #define RenderComponentH_H #include "../../Component/Component.h" namespace OUAN { class RenderComponent: public Component { public: RenderComponent(const std::string& type=""); ~RenderComponent(); virtual void update(long elapsedTime); protected: virtual std::string setChangeWorldMaterialTransparentTextures(std::string changeWorldMaterial,bool existInDreams,bool existInNightmares); //Event handlers //void onDoSomething(EventData,emitter, ...); //void onDoSomethingElse(...); }; class TRenderComponentParameters: public TComponentParameters { public: TRenderComponentParameters(); ~TRenderComponentParameters(); }; } #endif
[ "juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039", "wyern1@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 13 ], [ 16, 30 ] ], [ [ 14, 15 ] ] ]
35352f63d8bced4c2298cf5ae0a85f18ffe9c961
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
/tags/pyplusplus_dev_1.0.0/unittests/data/smart_pointers_to_be_exported.hpp
5029ae4464bcfa939c11a6c19d1982192545a612
[ "BSL-1.0" ]
permissive
gatoatigrado/pyplusplusclone
30af9065fb6ac3dcce527c79ed5151aade6a742f
a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede
refs/heads/master
2016-09-05T23:32:08.595261
2010-05-16T10:53:45
2010-05-16T10:53:45
700,369
4
2
null
null
null
null
UTF-8
C++
false
false
2,253
hpp
// Copyright 2004-2008 Roman Yakovenko. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef __smart_pointers_to_be_exported_hpp__ #define __smart_pointers_to_be_exported_hpp__ #include <memory> #include "boost/shared_ptr.hpp" namespace smart_pointers{ struct base{ base() : base_value(19) {} int base_value; virtual int get_base_value(){ return base_value; } virtual int get_some_value() = 0; }; struct data : base{ data() : value(11){} int value; virtual int get_value(){ return value; } virtual int get_some_value(){ return 23; } }; typedef std::auto_ptr< base > base_a_ptr; typedef boost::shared_ptr< base > base_s_ptr; typedef std::auto_ptr< data > data_a_ptr; typedef boost::shared_ptr< data > data_s_ptr; data_a_ptr create_auto(); data_s_ptr create_shared(); int ref_auto( data_a_ptr& a ); int ref_shared( data_s_ptr& a ); int val_auto( data_a_ptr a ); int val_shared( data_s_ptr a ); int const_ref_auto( const data_a_ptr& a ); int const_ref_shared( const data_s_ptr& a ); int ref_auto_base_value( base_a_ptr& a ); int ref_shared_base_value( base_s_ptr& a ); int val_auto_base_value( base_a_ptr a ); int val_shared_base_value( base_s_ptr a ); int const_ref_auto_base_value( const base_a_ptr& a ); int const_ref_shared_base_value( const base_s_ptr& a ); int ref_auto_some_value( base_a_ptr& a ); int ref_shared_some_value( base_s_ptr& a ); int val_auto_some_value( base_a_ptr a ); int val_shared_some_value( base_s_ptr a ); int const_ref_auto_some_value( const base_a_ptr& a ); int const_ref_shared_some_value( const base_s_ptr& a ); struct shared_data_buffer_t{ shared_data_buffer_t() : size( 0 ) {} int size; }; struct shared_data_buffer_holder_t{ typedef boost::shared_ptr<shared_data_buffer_t> holder_impl_t; shared_data_buffer_holder_t() : buffer( new shared_data_buffer_t() ) , const_buffer( new shared_data_buffer_t() ) {} holder_impl_t buffer; const holder_impl_t const_buffer; }; } #endif//__smart_pointers_to_be_exported_hpp__
[ "roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76" ]
[ [ [ 1, 83 ] ] ]
1aa63c6287c85a33524e834294e1cd700e7cfe75
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Distance/Wm4DistSegment3Box3.h
eabb3ab871f6e11279364a5dd06d78c534338fdd
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
1,632
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4DISTSEGMENT3BOX3_H #define WM4DISTSEGMENT3BOX3_H #include "Wm4FoundationLIB.h" #include "Wm4Distance.h" #include "Wm4Segment3.h" #include "Wm4Box3.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM DistSegment3Box3 : public Distance<Real,Vector3<Real> > { public: DistSegment3Box3 (const Segment3<Real>& rkSegment, const Box3<Real>& rkBox); // object access const Segment3<Real>& GetSegment () const; const Box3<Real>& GetBox () const; // static distance queries virtual Real Get (); virtual Real GetSquared (); // function calculations for dynamic distance queries virtual Real Get (Real fT, const Vector3<Real>& rkVelocity0, const Vector3<Real>& rkVelocity1); virtual Real GetSquared (Real fT, const Vector3<Real>& rkVelocity0, const Vector3<Real>& rkVelocity1); private: using Distance<Real,Vector3<Real> >::m_kClosestPoint0; using Distance<Real,Vector3<Real> >::m_kClosestPoint1; const Segment3<Real>& m_rkSegment; const Box3<Real>& m_rkBox; }; typedef DistSegment3Box3<float> DistSegment3Box3f; typedef DistSegment3Box3<double> DistSegment3Box3d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 57 ] ] ]
9639766538d99e7d9ff8abbe18674e56e28f04a3
2112057af069a78e75adfd244a3f5b224fbab321
/branches/refactor/src_root/src/ireon_client/client_frame_listener.cpp
1b53f2e6ec298ffdfd46b74b74e0f8d1ad4f514a
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,150
cpp
/* Copyright (C) 2005 ireon.org developers council * $Id: client_frame_listener.cpp 433 2005-12-20 20:19:15Z zak $ * 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., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * @file client_frame_listener.cpp * Frame listener */ #include "stdafx.h" #include "client_frame_listener.h" #include "client_app.h" bool CClientFrameListener::frameStarted(const Ogre::FrameEvent &evt) { return CClientApp::instance()->pulse(evt.timeSinceLastFrame); };
[ [ [ 1, 32 ] ] ]
38edefd89256f8bce675c21cb040bacc3dd89792
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/gui/nguislideshow_main.cc
b4c00f4c7452e534ec0168b8bcef699aedd4f752
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,010
cc
#include "precompiled/pchngui.h" //------------------------------------------------------------------------------ // nguislideshow_main.cc // (C) 2005 RadonLabs GmbH //------------------------------------------------------------------------------ #include "gui/nguislideshow.h" #include "gui/nguislide.h" #include "gui/nguiwidget.h" #include "gui/nguiformlayout.h" #include "gui/nguiserver.h" #include "kernel/ntimeserver.h" #include "gui/nguiresource.h" nNebulaScriptClass(nGuiSlideShow, "nguiwidget"); //------------------------------------------------------------------------------ /** Constructor */ nGuiSlideShow::nGuiSlideShow() : loop(true), firstFrame(true), interval(2.0f), currentPicIndex(-1), nextPicIndex(0), numLevels(5), togglePics(false) { this->currentSlideColor = vector4(1.0f, 1.0f, 1.0f, 0.0f); this->nextSlideColor = vector4(1.0f, 1.0f, 1.0f, 0.0f); this->beginTime = nTimeServer::Instance()->GetTime(); this->time = nTimeServer::Instance()->GetTime(); } //------------------------------------------------------------------------------ /** Constructor which takes the interval between two pictures as an argument */ nGuiSlideShow::nGuiSlideShow(nTime seconds) { nGuiSlideShow(); this->interval = seconds; } //------------------------------------------------------------------------------ /** Destructor */ nGuiSlideShow::~nGuiSlideShow() { // empty } //------------------------------------------------------------------------------ /** */ void nGuiSlideShow::OnHide() { if(this->refSlides.At(0).isvalid()) { this->refSlides.At(0)->Release(); n_assert(!this->refSlides.At(0).isvalid()); } if(this->refSlides.At(1).isvalid()) { this->refSlides.At(1)->Release(); n_assert(!this->refSlides.At(1).isvalid()); } } //------------------------------------------------------------------------------ /** */ void nGuiSlideShow::OnShow() { n_assert(this->pictures.Size() > 0); this->firstFrame = true; // Assuming all slides have the same size vector2 size = nGuiServer::Instance()->ComputeScreenSpaceBrushSize(this->pictures.At(0).Get()); this->SetMinSize(size); this->SetMaxSize(size); // Create current slide label nGuiSlide* slide = (nGuiSlide*) kernelServer->New("nguislide", "currentslide"); n_assert(slide); slide->SetMinSize(size); slide->SetMaxSize(size); slide->SetRect( this->GetRect() ); slide->OnShow(); this->refSlides.At(0) = slide; // Create next slide label slide = (nGuiSlide*) kernelServer->New("nguislide", "nextslide"); n_assert(slide); slide->SetMinSize(size); slide->SetMaxSize(size); slide->SetRect( this->GetRect() ); slide->OnShow(); this->refSlides.At(1) = slide; this->currentSlideColor.set(1.0f, 1.0f, 1.0f, 1.0f); this->nextSlideColor.set(1.0f, 1.0f, 1.0f, 0.0f); } //------------------------------------------------------------------------------ /** */ void nGuiSlideShow::OnFrame() { if(this->pictures.Size() > 0) { if(this->firstFrame) { this->currentSlideColor.w = 1.0; this->nextSlideColor.w = 0.0; // this->pictures[this->currentPicIndex].Get() this->refSlides[0]->SetDefaultBrush( 0 ); this->refSlides[1]->SetDefaultBrush( this->pictures[this->nextPicIndex].Get() ); this->firstFrame = false; this->beginTime = nTimeServer::Instance()->GetTime(); } // Check if it's time for the next slide if(time > (this->beginTime + interval) || !this->refSlides[0]->HasPicture()) { // Set new picture indices if((this->currentPicIndex + 1) >= this->pictures.Size()) { if(this->loop) { this->currentPicIndex = 0; } } else { this->currentPicIndex += 1; } if((this->nextPicIndex + 1) >= this->pictures.Size()) { if(this->loop) { this->nextPicIndex = 0; } } else { this->nextPicIndex += 1; } this->UpdatePictureColor(); // Flip the brushes, if needed if(this->currentPicIndex != this->nextPicIndex && this->togglePics ) { this->refSlides.At(0).get()->SetDefaultBrush( this->pictures[this->currentPicIndex].Get() ); this->refSlides.At(1).get()->SetDefaultBrush( this->pictures[this->nextPicIndex].Get() ); this->currentSlideColor.w = 1.0f; this->nextSlideColor.w = 0.0f; this->togglePics=false; } } this->time = nTimeServer::Instance()->GetTime(); } } ////------------------------------------------------------------------------------ ///** //*/ bool nGuiSlideShow::Render() { if(this->IsShown() && this->pictures.Size() > 0) { this->refSlides[0]->SetRenderColor(this->currentSlideColor); this->refSlides[1]->SetRenderColor(this->nextSlideColor); return true; } return false; } //------------------------------------------------------------------------------ /** */ void nGuiSlideShow::UpdatePictureColor() { this->currentSlideColor.w = n_saturate( this->currentSlideColor.w -= 0.01f ); this->nextSlideColor.w = n_saturate( this->nextSlideColor.w += 0.01f ); if(this->nextSlideColor.w == 1.0f && this->currentSlideColor.w == 0.0f) { // flip the slides this->beginTime = nTimeServer::Instance()->GetTime(); this->togglePics = true; } }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 198 ] ] ]
4340318d22d639ebb90db0ef395f108eee7605de
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Intersection/Wm4IntrRay3Triangle3.cpp
546cb1833e04f4177b4772446742e7411abb810f
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
6,561
cpp
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "Wm4FoundationPCH.h" #include "Wm4IntrRay3Triangle3.h" namespace Wm4 { //---------------------------------------------------------------------------- template <class Real> IntrRay3Triangle3<Real>::IntrRay3Triangle3 (const Ray3<Real>& rkRay, const Triangle3<Real>& rkTriangle) : m_rkRay(rkRay), m_rkTriangle(rkTriangle) { } //---------------------------------------------------------------------------- template <class Real> const Ray3<Real>& IntrRay3Triangle3<Real>::GetRay () const { return m_rkRay; } //---------------------------------------------------------------------------- template <class Real> const Triangle3<Real>& IntrRay3Triangle3<Real>::GetTriangle () const { return m_rkTriangle; } //---------------------------------------------------------------------------- template <class Real> bool IntrRay3Triangle3<Real>::Test () { // compute the offset origin, edges, and normal Vector3<Real> kDiff = m_rkRay.Origin - m_rkTriangle.V[0]; Vector3<Real> kEdge1 = m_rkTriangle.V[1] - m_rkTriangle.V[0]; Vector3<Real> kEdge2 = m_rkTriangle.V[2] - m_rkTriangle.V[0]; Vector3<Real> kNormal = kEdge1.Cross(kEdge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) Real fDdN = m_rkRay.Direction.Dot(kNormal); Real fSign; if (fDdN > Math<Real>::ZERO_TOLERANCE) { fSign = (Real)1.0; } else if (fDdN < -Math<Real>::ZERO_TOLERANCE) { fSign = (Real)-1.0; fDdN = -fDdN; } else { // Ray and triangle are parallel, call it a "no intersection" // even if the ray does intersect. return false; } Real fDdQxE2 = fSign*m_rkRay.Direction.Dot(kDiff.Cross(kEdge2)); if (fDdQxE2 >= (Real)0.0) { Real fDdE1xQ = fSign*m_rkRay.Direction.Dot(kEdge1.Cross(kDiff)); if (fDdE1xQ >= (Real)0.0) { if (fDdQxE2 + fDdE1xQ <= fDdN) { // line intersects triangle, check if ray does Real fQdN = -fSign*kDiff.Dot(kNormal); if (fQdN >= (Real)0.0) { // ray intersects triangle return true; } // else: t < 0, no intersection } // else: b1+b2 > 1, no intersection } // else: b2 < 0, no intersection } // else: b1 < 0, no intersection return false; } //---------------------------------------------------------------------------- template <class Real> bool IntrRay3Triangle3<Real>::Find () { // compute the offset origin, edges, and normal Vector3<Real> kDiff = m_rkRay.Origin - m_rkTriangle.V[0]; Vector3<Real> kEdge1 = m_rkTriangle.V[1] - m_rkTriangle.V[0]; Vector3<Real> kEdge2 = m_rkTriangle.V[2] - m_rkTriangle.V[0]; Vector3<Real> kNormal = kEdge1.Cross(kEdge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) Real fDdN = m_rkRay.Direction.Dot(kNormal); Real fSign; if (fDdN > Math<Real>::ZERO_TOLERANCE) { fSign = (Real)1.0; } else if (fDdN < -Math<Real>::ZERO_TOLERANCE) { fSign = (Real)-1.0; fDdN = -fDdN; } else { // Ray and triangle are parallel, call it a "no intersection" // even if the ray does intersect. return false; } Real fDdQxE2 = fSign*m_rkRay.Direction.Dot(kDiff.Cross(kEdge2)); if (fDdQxE2 >= (Real)0.0) { Real fDdE1xQ = fSign*m_rkRay.Direction.Dot(kEdge1.Cross(kDiff)); if (fDdE1xQ >= (Real)0.0) { if (fDdQxE2 + fDdE1xQ <= fDdN) { // line intersects triangle, check if ray does Real fQdN = -fSign*kDiff.Dot(kNormal); if (fQdN >= (Real)0.0) { // ray intersects triangle Real fInv = ((Real)1.0)/fDdN; m_fRayT = fQdN*fInv; m_fTriB1 = fDdQxE2*fInv; m_fTriB2 = fDdE1xQ*fInv; m_fTriB0 = (Real)1.0 - m_fTriB1 - m_fTriB2; return true; } // else: t < 0, no intersection } // else: b1+b2 > 1, no intersection } // else: b2 < 0, no intersection } // else: b1 < 0, no intersection return false; } //---------------------------------------------------------------------------- template <class Real> Real IntrRay3Triangle3<Real>::GetRayT () const { return m_fRayT; } //---------------------------------------------------------------------------- template <class Real> Real IntrRay3Triangle3<Real>::GetTriB0 () const { return m_fTriB0; } //---------------------------------------------------------------------------- template <class Real> Real IntrRay3Triangle3<Real>::GetTriB1 () const { return m_fTriB1; } //---------------------------------------------------------------------------- template <class Real> Real IntrRay3Triangle3<Real>::GetTriB2 () const { return m_fTriB2; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- template WM4_FOUNDATION_ITEM class IntrRay3Triangle3<float>; template WM4_FOUNDATION_ITEM class IntrRay3Triangle3<double>; //---------------------------------------------------------------------------- }
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 193 ] ] ]
bf201c330fd9cd279958c65c204495773007ed89
3eae8bea68fd2eb7965cca5afca717b86700adb5
/Engine/Project/Core/GnMesh/Source/GnSQLiteTable.cpp
1cf1b2d0fa575882db38f7da1e3a9e72fec4ba71
[]
no_license
mujige77/WebGame
c0a218ee7d23609076859e634e10e29c92bb595b
73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd
refs/heads/master
2021-01-01T15:51:20.045414
2011-10-03T01:02:59
2011-10-03T01:02:59
455,950
3
1
null
null
null
null
UTF-8
C++
false
false
3,843
cpp
#include "GnMeshPCH.h" #include "GnSQLiteTable.h" #include "sqlite3.h" GnSQLiteTable::GnSQLiteTable() { mpaszResults = 0; mnRows = 0; mnCols = 0; mnCurrentRow = 0; } GnSQLiteTable::GnSQLiteTable(const GnSQLiteTable& rTable) { mpaszResults = rTable.mpaszResults; // Only one object can own the results const_cast<GnSQLiteTable&>(rTable).mpaszResults = 0; mnRows = rTable.mnRows; mnCols = rTable.mnCols; mnCurrentRow = rTable.mnCurrentRow; } GnSQLiteTable::GnSQLiteTable(char** paszResults, int nRows, int nCols) { mpaszResults = paszResults; mnRows = nRows; mnCols = nCols; mnCurrentRow = 0; } GnSQLiteTable::~GnSQLiteTable() { try { Finalize(); } catch (...) { } } GnSQLiteTable& GnSQLiteTable::operator=(const GnSQLiteTable& rTable) { try { Finalize(); } catch (...) { } mpaszResults = rTable.mpaszResults; // Only one object can own the results const_cast<GnSQLiteTable&>(rTable).mpaszResults = 0; mnRows = rTable.mnRows; mnCols = rTable.mnCols; mnCurrentRow = rTable.mnCurrentRow; return *this; } void GnSQLiteTable::Finalize() { if (mpaszResults) { sqlite3_free_table(mpaszResults); mpaszResults = 0; } } int GnSQLiteTable::NumFields() { CheckResults(); return mnCols; } int GnSQLiteTable::NumRows() { CheckResults(); return mnRows; } const char* GnSQLiteTable::FieldValue(int nField) { CheckResults(); if (nField < 0 || nField > mnCols-1) { return NULL; } int nIndex = ( mnCurrentRow * mnCols ) + mnCols + nField; return mpaszResults[nIndex]; } const char* GnSQLiteTable::FieldValue(const char* szField) { CheckResults(); if (szField) { for (int nField = 0; nField < mnCols; nField++) { if (strcmp(szField, mpaszResults[nField]) == 0) { int nIndex = ( mnCurrentRow * mnCols ) + mnCols + nField; return mpaszResults[nIndex]; } } } return NULL; } int GnSQLiteTable::GetIntField(int nField, int nNullValue/*=0*/) { if ( FieldIsNull( nField ) ) { return nNullValue; } else { return atoi( FieldValue( nField ) ); } } int GnSQLiteTable::GetIntField(const char* szField, int nNullValue/*=0*/) { if ( FieldIsNull( szField ) ) { return nNullValue; } else { return atoi( FieldValue( szField ) ); } } double GnSQLiteTable::GetFloatField(int nField, double fNullValue/*=0.0*/) { if ( FieldIsNull( nField ) ) { return fNullValue; } else { return atof( FieldValue( nField ) ); } } double GnSQLiteTable::GetFloatField(const char* szField, double fNullValue/*=0.0*/) { if ( FieldIsNull(szField) ) { return fNullValue; } else { return atof( FieldValue(szField) ); } } const char* GnSQLiteTable::GetStringField(int nField, const char* szNullValue/*=""*/) { if ( FieldIsNull(nField) ) { return szNullValue; } else { return FieldValue(nField); } } const char* GnSQLiteTable::GetStringField(const char* szField, const char* szNullValue/*=""*/) { if ( FieldIsNull(szField) ) { return szNullValue; } else { return FieldValue(szField); } } bool GnSQLiteTable::FieldIsNull(int nField) { CheckResults(); return ( FieldValue(nField) == 0 ); } bool GnSQLiteTable::FieldIsNull(const char* szField) { CheckResults(); return ( FieldValue(szField) == 0 ); } const char* GnSQLiteTable::FieldName(int nCol) { CheckResults(); if ( nCol < 0 || nCol > mnCols-1 ) { return NULL; } return mpaszResults[nCol]; } void GnSQLiteTable::SetRow(int nRow) { CheckResults(); if (nRow < 0 || nRow > mnRows-1) { return; } mnCurrentRow = nRow; } void GnSQLiteTable::CheckResults() { if (mpaszResults == 0) { return; } }
[ [ [ 1, 247 ] ] ]
45d5e9b9d9aeebe0277adcb817a41064ce35c709
28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc
/mytesgnikrow --username hotga2801/Project/MotionAdaboost/Develop/hbp/StdAfx.cpp
afdb70a597dc9be0c10483d632c110cfc9387f57
[]
no_license
taicent/mytesgnikrow
09aed8836e1297a24bef0f18dadd9e9a78ec8e8b
9264faa662454484ade7137ee8a0794e00bf762f
refs/heads/master
2020-04-06T04:25:30.075548
2011-02-17T13:37:16
2011-02-17T13:37:16
34,991,750
0
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
// stdafx.cpp : source file that includes just the standard includes // segment.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076" ]
[ [ [ 1, 8 ] ] ]
936bf356bcd6e311db53159a3d6bb84334d31c87
8174a17ebdc4fc1a873195e573103e444491f06e
/Babel/ABSNetwork.h
066f40600f23e0934a1f77e51fb4963e9fb8ee1c
[]
no_license
RemiGuillard/Troll-Babel
517c298469b40372162cea5101a5226612d8aa37
379156b3942f700df29d19ae47db324e61479308
refs/heads/master
2021-01-01T05:53:47.615138
2010-12-05T21:30:35
2010-12-05T21:30:35
32,143,730
0
0
null
null
null
null
UTF-8
C++
false
false
501
h
#ifndef ABSNETWORK # define ABSNETWORK #include <QString> #include <QAbstractSocket> class ABSNetwork { public: ABSNetwork(); virtual void createSocket() = 0; virtual void socketConnection(const QString &, quint16) = 0; virtual char* packetRcv() = 0; virtual void packetSend(const char *) = 0; virtual void disconnect() = 0; const bool& getSocketStatus() const; void setSocketStatus(const bool&); private: bool _sockState; }; #endif // !ABSNETWORK
[ [ [ 1, 25 ] ] ]
c9fb082440ad94d0c68fa879bb3e7984b6a3f904
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/SupportWFLib/symbian/DummySlaveAudio.h
f008b70267c5da61ee356b3612893bf88a06be1d
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,003
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef BLAAARGH_DUMMYSLAVEAUDIO_H #define BLAAARGH_DUMMYSLAVEAUDIO_H // I'm guessing here #include <e32base.h> #include "SlaveAudio.h" class MSlaveAudioListener; class RFs; /** * Operations in DummySlaveAudio used by WayFinderAppUI/WayfinderAppUi */ class CDummySlaveAudio : public CSlaveAudio { public: /// NewL:s a dummy slaveaudio static CDummySlaveAudio* NewL( MSlaveAudioListener& listener, RFs& fileServerSession, const TDesC& resourcePath ); /// Destructor ~CDummySlaveAudio(); /// Prepares playing of the sounds. Calls SoundReadyL when done. void PrepareSound( TInt aNumberSounds, const TInt* aSounds ); /// Starts playing the sounds void Play(); /// Stops converting or playing. void Stop(); /// Sets volume as soon as possible void SetVolume( TInt aVolume ); /// Sets mute on off void SetMute( TBool aMute ); /// Returns true if mute. TBool IsMute(); /// Returns the duration of the clips or upto SoundTimingMarker TInt32 GetDuration(); private: /// Constructor CDummySlaveAudio( MSlaveAudioListener& soundListener ); /// Sound listener to send updates to when sounds have been prepped etc. MSlaveAudioListener& m_soundListener; /// True if mute bool m_mute; }; #endif // End of File
[ [ [ 1, 82 ] ] ]
07aa7c4c58f44fb8ae9eaedc3c9a1f7a4f619bcd
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Pilot/Lokapala_Communication/Raptor/DharaniFacade.h
14f4a56c3fb020d9f8ab9a092d3749ea7c70af35
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UHC
C++
false
false
985
h
/**@file DharaniFacade.h * @brief Dharani component의 facade * @author siva */ #ifndef DHARANI_FACADE_H #define DHARANI_FACADE_H #include "DharaniInterface.h" #include "DharaniDTO.h" /**@ingroup GroupDharani * @class CDharaniFacade * @brief Dharani Component의 Facade. Interface를 상속받아 실질적인 행동을 한다. */ class CDharaniFacade : public CDharaniInterface { public : static CDharaniFacade *Instance() { if(!m_instance) { m_instance = new CDharaniFacade(); } return m_instance; } virtual void DharaniSendTextMessageTo(CDharaniDTO *a_sendData); virtual void DharaniBroadcastTextMessage(CDharaniDTO *a_sendData); virtual void DharaniSendTextToServer(CDharaniDTO *a_sendData); virtual void DharaniServerInitiallize(void); virtual void DharaniClientInitiallize(DWORD a_ServerAddress); CDharaniFacade(){} ~CDharaniFacade(){} protected : private : static CDharaniFacade *m_instance; }; #endif
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 42 ] ] ]
8184a3dd82b663535577d74a05fff4e6756e2e8d
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/resource/nmeshcopyresourceloader_main.cc
dd63a747938a1e15868783728e2a17995ba9915f
[]
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
4,229
cc
#define N_IMPLEMENTS nMeshCopyResourceLoader //------------------------------------------------------------------------------ // (C) 2006 RadonLabs GmbH //------------------------------------------------------------------------------ #include "resource/nmeshcopyresourceloader.h" nNebulaClass(nMeshCopyResourceLoader, "nresourceloader"); //------------------------------------------------------------------------------ /** */ nMeshCopyResourceLoader::nMeshCopyResourceLoader(): reloaded(false) { } //------------------------------------------------------------------------------ /** */ nMeshCopyResourceLoader::~nMeshCopyResourceLoader() { } //------------------------------------------------------------------------------ /** */ bool nMeshCopyResourceLoader::InitResource(const char* sFilename, nResource* callingResource) { n_assert(this->srcMesh.isvalid()); n_assert(callingResource); n_assert(callingResource->IsA("nmesh2")); nMesh2* dstMesh = (nMesh2*)callingResource; nMesh2* srcMesh = this->srcMesh.get(); if (!dstMesh->IsLoaded()) { dstMesh->SetNumVertices(srcMesh->GetNumVertices()); dstMesh->SetNumIndices(srcMesh->GetNumIndices()); dstMesh->SetNumEdges(srcMesh->GetNumEdges()); int numGroups = srcMesh->GetNumGroups(); dstMesh->SetNumGroups(numGroups); int groupIndex; for (groupIndex = 0; groupIndex < numGroups; groupIndex++) { dstMesh->Group(groupIndex) = srcMesh->Group(groupIndex); } return true; } return false; } //------------------------------------------------------------------------------ /** @param const char* path the full path to the to-be-loaded file @param const nResource* callingResource ptr to the nResource calling nResourceLoader::Load() @return bool success/failure */ bool nMeshCopyResourceLoader::Load(const char* sFilename, nResource* callingResource) { n_assert(this->srcMesh.isvalid()); n_assert(callingResource); n_assert(callingResource->IsA("nmesh2")); nMesh2* dstMesh = (nMesh2*)callingResource; nMesh2* srcMesh = this->srcMesh.get(); // transfer vertices from source mesh int numVertices = srcMesh->GetNumVertices(); int srcVertexWidth = srcMesh->GetVertexWidth(); int dstVertexWidth = dstMesh->GetVertexWidth(); float* srcVertices = srcMesh->LockVertices(); float* dstVertices = dstMesh->LockVertices(); int vertexWidth = dstMesh->GetVertexWidth(); int dstComponents = dstMesh->GetVertexComponents(); int srcComponents = srcMesh->GetVertexComponents(); int intComponents = dstComponents & srcComponents; int vertexIndex; for (vertexIndex = 0; vertexIndex < numVertices; vertexIndex++) { int srcOffset = vertexIndex * srcVertexWidth; int dstOffset = vertexIndex * dstVertexWidth; int compOffset = 0; int mask; for (mask = 1; mask != 0; mask = mask << 1) { int curComp = mask & intComponents; if (curComp) { int dstCompOffset = dstMesh->GetVertexComponentOffset((nMesh2::VertexComponent)curComp); int srcCompOffset = srcMesh->GetVertexComponentOffset((nMesh2::VertexComponent)curComp); int compWidth = dstMesh->GetVertexWidthFromMask(curComp); int i; for (i = 0; i < compWidth; i++) { dstVertices[dstOffset + dstCompOffset + i] = srcVertices[srcOffset + srcCompOffset + i]; } } } } srcMesh->UnlockVertices(); dstMesh->UnlockVertices(); // transfer indices from source mesh int numIndices = srcMesh->GetNumIndices(); ushort* srcIndices = srcMesh->LockIndices(); ushort* dstIndices = dstMesh->LockIndices(); int ii; for (ii = 0; ii < numIndices; ii++) { dstIndices[ii] = srcIndices[ii]; } srcMesh->UnlockIndices(); dstMesh->UnlockIndices(); this->reloaded = true; return true; }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 122 ] ] ]
a16aa6b294bc5069a5dfeba2588d24d842ea4315
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/PanicHandler.hpp
895810fed3490906fe07fd3ded7de41cc483645e
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
4,113
hpp
/* * Copyright 2003,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: PanicHandler.hpp,v $ * Revision 1.7 2004/09/08 13:56:22 peiyongz * Apache License Version 2.0 * * Revision 1.6 2003/12/24 17:12:21 cargilld * Memory management update. * * Revision 1.5 2003/12/24 15:24:13 cargilld * More updates to memory management so that the static memory manager. * * Revision 1.4 2003/05/22 18:15:16 neilg * The PanicHandler interface should not inherit from XMemory. * The reason for this is that the default implementation does not * allocate memory dynamically and if such an inheritance relation existed, * a user would have to be very careful about installing a memory * handler on their own PanicHandler before handing it to the * XMLPlatformUtils::Initialize() method, since otherwise * the (uninitialized) XMLPlatformUtils::fgMemoryManager would be used * upon construction of their PanicHandler implementation. * * Revision 1.3 2003/05/15 19:04:35 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.2 2003/03/10 16:05:11 peiyongz * assignment operator * * Revision 1.1 2003/03/09 17:06:16 peiyongz * PanicHandler * * $Id: PanicHandler.hpp,v 1.7 2004/09/08 13:56:22 peiyongz Exp $ * */ #ifndef PANICHANDLER_HPP #define PANICHANDLER_HPP #include <xercesc/util/XMemory.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * Receive notification of panic. * * <p>This is the interface, through which the Xercesc reports * a panic to the application. * </p> * * <p>Application may implement this interface, instantiate an * object of the derivative, and plug it to Xercesc in the * invocation to XMLPlatformUtils::Initialize(), if it prefers * to handling panic itself rather than Xercesc doing it. * </p> * */ class XMLUTIL_EXPORT PanicHandler { public: /** @name Public Types */ //@{ enum PanicReasons { Panic_NoTransService , Panic_NoDefTranscoder , Panic_CantFindLib , Panic_UnknownMsgDomain , Panic_CantLoadMsgDomain , Panic_SynchronizationErr , Panic_SystemInit , PanicReasons_Count }; //@} protected: /** @name hidden Constructors */ //@{ /** Default constructor */ PanicHandler(){}; public: /** Destructor */ virtual ~PanicHandler(){}; //@} /** @name The virtual panic handler interface */ //@{ /** * Receive notification of panic * * This method is called when an unrecoverable error has occurred in the Xerces library. * * This method must not return normally, otherwise, the results are undefined. * * Ways of handling this call could include throwing an exception or exiting the process. * * Once this method has been called, the results of calling any other Xerces API, * or using any existing Xerces objects are undefined. * * @param reason The reason of panic * */ virtual void panic(const PanicHandler::PanicReasons reason) = 0; //@} static const char* getPanicReasonString(const PanicHandler::PanicReasons reason); private: /* Unimplemented Constructors and operators */ /* Copy constructor */ PanicHandler(const PanicHandler&); /** Assignment operator */ PanicHandler& operator=(const PanicHandler&); }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 140 ] ] ]
456e05149886a1de7bc490f6c8471ea4bc4a5883
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/util/Platforms/Win32/Win32PlatformUtils.cpp
91d345b59f69f8ab59a72930df88c5b4ef9a53be
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
27,773
cpp
/* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: Win32PlatformUtils.cpp,v 1.25 2004/09/08 13:56:43 peiyongz Exp $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/Janitor.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/RuntimeException.hpp> #include <xercesc/util/XMLExceptMsgs.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/PanicHandler.hpp> #include <windows.h> #include <stdio.h> #include <stdlib.h> #ifdef _DEBUG #ifdef _MSC_VER #include <crtdbg.h> #else #include <assert.h> #endif #endif // // These control which transcoding service is used by the Win32 version. // They allow this to be controlled from the build process by just defining // one of these values. // #if defined (XML_USE_ICU_TRANSCODER) #include <xercesc/util/Transcoders/ICU/ICUTransService.hpp> #elif defined (XML_USE_WIN32_TRANSCODER) #include <xercesc/util/Transcoders/Win32/Win32TransService.hpp> #elif defined (XML_USE_CYGWIN_TRANSCODER) #include <xercesc/util/Transcoders/Cygwin/CygwinTransService.hpp> #else #error A transcoding service must be chosen #endif // // These control which message loading service is used by the Win32 version. // They allow this to be controlled from the build process by just defining // one of these values. // #if defined (XML_USE_INMEM_MESSAGELOADER) #include <xercesc/util/MsgLoaders/InMemory/InMemMsgLoader.hpp> #elif defined (XML_USE_WIN32_MSGLOADER) #include <xercesc/util/MsgLoaders/Win32/Win32MsgLoader.hpp> #elif defined(XML_USE_ICU_MESSAGELOADER) #include <xercesc/util/MsgLoaders/ICU/ICUMsgLoader.hpp> #else #error A message loading service must be chosen #endif // // These control which network access service is used by the Win32 version. // They allow this to be controlled from the build process by just defining // one of these values. // #if defined (XML_USE_NETACCESSOR_LIBWWW) #include <xercesc/util/NetAccessors/libWWW/LibWWWNetAccessor.hpp> #elif defined (XML_USE_NETACCESSOR_WINSOCK) #include <xercesc/util/NetAccessors/WinSock/WinSockNetAccessor.hpp> #endif XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Local data // // gOnNT // We figure out during init if we are on NT or not. If we are, then // we can avoid a lot of transcoding in our system services stuff. // --------------------------------------------------------------------------- static bool gOnNT; // --------------------------------------------------------------------------- // XMLPlatformUtils: The panic method // --------------------------------------------------------------------------- void XMLPlatformUtils::panic(const PanicHandler::PanicReasons reason) { fgUserPanicHandler? fgUserPanicHandler->panic(reason) : fgDefaultPanicHandler->panic(reason); } // --------------------------------------------------------------------------- // XMLPlatformUtils: File Methods // --------------------------------------------------------------------------- // // Functions to look for Unicode forward and back slashes. // This operation is complicated by the fact that some Japanese and Korean // encodings use the same encoding for both '\' and their currency symbol // (Yen or Won). In these encodings, which is meant is context dependent. // Unicode converters choose the currency symbols. But in the context // of a Windows file name, '\' is generally what was intended. // // So we make a leap of faith, and assume that if we get a Yen or Won // here, in the context of a file name, that it originated in one of // these encodings, and is really supposed to be a '\'. // static bool isBackSlash(XMLCh c) { return c == chBackSlash || c == chYenSign || c == chWonSign; } unsigned int XMLPlatformUtils::curFilePos(FileHandle theFile , MemoryManager* const manager) { // Get the current position const unsigned int curPos = ::SetFilePointer(theFile, 0, 0, FILE_CURRENT); if (curPos == 0xFFFFFFFF) ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos, manager); return curPos; } void XMLPlatformUtils::closeFile(FileHandle theFile , MemoryManager* const manager) { if (!::CloseHandle(theFile)) ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotCloseFile, manager); } unsigned int XMLPlatformUtils::fileSize(FileHandle theFile , MemoryManager* const manager) { // Get the current position const unsigned int curPos = ::SetFilePointer(theFile, 0, 0, FILE_CURRENT); if (curPos == 0xFFFFFFFF) ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos, manager); // Seek to the end and save that value for return const unsigned int retVal = ::SetFilePointer(theFile, 0, 0, FILE_END); if (retVal == 0xFFFFFFFF) ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotSeekToEnd, manager); // And put the pointer back if (::SetFilePointer(theFile, curPos, 0, FILE_BEGIN) == 0xFFFFFFFF) ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotSeekToPos, manager); return retVal; } FileHandle XMLPlatformUtils::openFile(const char* const fileName , MemoryManager* const manager) { FileHandle retVal = ::CreateFileA ( fileName , GENERIC_READ , FILE_SHARE_READ , 0 , OPEN_EXISTING , FILE_FLAG_SEQUENTIAL_SCAN , 0 ); if (retVal == INVALID_HANDLE_VALUE) return 0; return retVal; } FileHandle XMLPlatformUtils::openFile(const XMLCh* const fileName , MemoryManager* const manager) { // Watch for obvious wierdness if (!fileName) return 0; // // We have to play a little trick here. If its /x:..... // style fully qualified path, we have to toss the leading / // character. // const XMLCh* nameToOpen = fileName; if (*fileName == chForwardSlash) { if (XMLString::stringLen(fileName) > 3) { if (*(fileName + 2) == chColon) { const XMLCh chDrive = *(fileName + 1); if (((chDrive >= chLatin_A) && (chDrive <= chLatin_Z)) || ((chDrive >= chLatin_a) && (chDrive <= chLatin_z))) { nameToOpen = fileName + 1; } } // Similarly for UNC paths if ( *(fileName + 1) == *(fileName + 2) && (*(fileName + 1) == chForwardSlash || *(fileName + 1) == chBackSlash) ) { nameToOpen = fileName + 1; } } } // Ok, this might look stupid but its a semi-expedient way to deal // with a thorny problem. Shift-JIS and some other Asian encodings // are fundamentally broken and map both the backslash and the Yen // sign to the same code point. Transcoders have to pick one or the // other to map '\' to Unicode and tend to choose the Yen sign. // // Unicode Yen or Won signs as directory separators will fail. // // So, we will check this path name for Yen or won signs and, if they are // there, we'll replace them with slashes. // // A further twist: we replace Yen and Won with forward slashes rather // than back slashes. Either form of slash will work as a directory // separator. On Win 95 and 98, though, Unicode back-slashes may // fail to transode back to 8-bit 0x5C with some Unicode converters // to some of the problematic code pages. Forward slashes always // transcode correctly back to 8 bit char * form. // XMLCh *tmpUName = 0; const XMLCh* srcPtr = nameToOpen; while (*srcPtr) { if (*srcPtr == chYenSign || *srcPtr == chWonSign) break; srcPtr++; } // // If we found a yen, then we have to create a temp file name. Else // go with the file name as is and save the overhead. // if (*srcPtr) { tmpUName = XMLString::replicate(nameToOpen, manager); XMLCh* tmpPtr = tmpUName; while (*tmpPtr) { if (*tmpPtr == chYenSign || *tmpPtr == chWonSign) *tmpPtr = chForwardSlash; tmpPtr++; } nameToOpen = tmpUName; } FileHandle retVal = 0; if (gOnNT) { retVal = ::CreateFileW ( (LPCWSTR) nameToOpen , GENERIC_READ , FILE_SHARE_READ , 0 , OPEN_EXISTING , FILE_FLAG_SEQUENTIAL_SCAN , 0 ); } else { // // We are Win 95 / 98. Take the Unicode file name back to (char *) // so that we can open it. // char* tmpName = XMLString::transcode(nameToOpen, manager); retVal = ::CreateFileA ( tmpName , GENERIC_READ , FILE_SHARE_READ , 0 , OPEN_EXISTING , FILE_FLAG_SEQUENTIAL_SCAN , 0 ); manager->deallocate(tmpName);//delete [] tmpName; } if (tmpUName) manager->deallocate(tmpUName);//delete [] tmpUName; if (retVal == INVALID_HANDLE_VALUE) return 0; return retVal; } FileHandle XMLPlatformUtils::openFileToWrite(const char* const fileName , MemoryManager* const manager) { FileHandle retVal = ::CreateFileA ( fileName , GENERIC_WRITE , 0 // no shared write , 0 , CREATE_ALWAYS , FILE_ATTRIBUTE_NORMAL , 0 ); if (retVal == INVALID_HANDLE_VALUE) return 0; return retVal; } FileHandle XMLPlatformUtils::openFileToWrite(const XMLCh* const fileName , MemoryManager* const manager) { // Watch for obvious wierdness if (!fileName) return 0; // Ok, this might look stupid but its a semi-expedient way to deal // with a thorny problem. Shift-JIS and some other Asian encodings // are fundamentally broken and map both the backslash and the Yen // sign to the same code point. Transcoders have to pick one or the // other to map '\' to Unicode and tend to choose the Yen sign. // // Unicode Yen or Won signs as directory separators will fail. // // So, we will check this path name for Yen or won signs and, if they are // there, we'll replace them with slashes. // // A further twist: we replace Yen and Won with forward slashes rather // than back slashes. Either form of slash will work as a directory // separator. On Win 95 and 98, though, Unicode back-slashes may // fail to transode back to 8-bit 0x5C with some Unicode converters // to some of the problematic code pages. Forward slashes always // transcode correctly back to 8 bit char * form. // XMLCh *tmpUName = 0; const XMLCh *nameToOpen = fileName; const XMLCh* srcPtr = fileName; while (*srcPtr) { if (*srcPtr == chYenSign || *srcPtr == chWonSign) break; srcPtr++; } // // If we found a yen, then we have to create a temp file name. Else // go with the file name as is and save the overhead. // if (*srcPtr) { tmpUName = XMLString::replicate(fileName, manager); XMLCh* tmpPtr = tmpUName; while (*tmpPtr) { if (*tmpPtr == chYenSign || *tmpPtr == chWonSign) *tmpPtr = chForwardSlash; tmpPtr++; } nameToOpen = tmpUName; } FileHandle retVal = 0; if (gOnNT) { retVal = ::CreateFileW ( (LPCWSTR) nameToOpen , GENERIC_WRITE , 0 // no shared write , 0 , CREATE_ALWAYS , FILE_ATTRIBUTE_NORMAL , 0 ); } else { // // We are Win 95 / 98. Take the Unicode file name back to (char *) // so that we can open it. // char* tmpName = XMLString::transcode(nameToOpen, manager); retVal = ::CreateFileA ( tmpName , GENERIC_WRITE , 0 // no shared write , 0 , CREATE_ALWAYS , FILE_ATTRIBUTE_NORMAL , 0 ); manager->deallocate(tmpName);//delete [] tmpName; } if (tmpUName) manager->deallocate(tmpUName);//delete [] tmpUName; if (retVal == INVALID_HANDLE_VALUE) return 0; return retVal; } FileHandle XMLPlatformUtils::openStdInHandle(MemoryManager* const manager) { // // Get the standard input handle. Duplicate it and return that copy // since the outside world cannot tell the difference and will shut // down this handle when its done with it. If we gave out the orignal, // shutting it would prevent any further output. // HANDLE stdInOrg = ::GetStdHandle(STD_INPUT_HANDLE); if (stdInOrg == INVALID_HANDLE_VALUE) { XMLCh stdinStr[] = {chLatin_s, chLatin_t, chLatin_d, chLatin_i, chLatin_n, chNull}; ThrowXMLwithMemMgr1(XMLPlatformUtilsException, XMLExcepts::File_CouldNotOpenFile, stdinStr, manager); } HANDLE retHandle; if (!::DuplicateHandle ( ::GetCurrentProcess() , stdInOrg , ::GetCurrentProcess() , &retHandle , 0 , FALSE , DUPLICATE_SAME_ACCESS)) { ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotDupHandle, manager); } return retHandle; } unsigned int XMLPlatformUtils::readFileBuffer( FileHandle theFile , const unsigned int toRead , XMLByte* const toFill , MemoryManager* const manager) { unsigned long bytesRead = 0; if (!::ReadFile(theFile, toFill, toRead, &bytesRead, 0)) { // // Check specially for a broken pipe error. If we get this, it just // means no more data from the pipe, so return zero. // if (::GetLastError() != ERROR_BROKEN_PIPE) ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotReadFromFile, manager); } return (unsigned int)bytesRead; } void XMLPlatformUtils::writeBufferToFile( FileHandle const theFile , long toWrite , const XMLByte* const toFlush , MemoryManager* const manager) { if (!theFile || (toWrite <= 0 ) || !toFlush ) return; const XMLByte* tmpFlush = (const XMLByte*) toFlush; unsigned long bytesWritten = 0; while (true) { if (!::WriteFile(theFile, tmpFlush, toWrite, &bytesWritten, 0)) ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotWriteToFile, manager); if (bytesWritten < (unsigned long) toWrite) //incomplete write { tmpFlush+=bytesWritten; toWrite-=bytesWritten; bytesWritten=0; } else return; } return; } void XMLPlatformUtils::resetFile(FileHandle theFile , MemoryManager* const manager) { // Seek to the start of the file if (::SetFilePointer(theFile, 0, 0, FILE_BEGIN) == 0xFFFFFFFF) ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotResetFile, manager); } // --------------------------------------------------------------------------- // XMLPlatformUtils: File system methods // --------------------------------------------------------------------------- XMLCh* XMLPlatformUtils::getFullPath(const XMLCh* const srcPath, MemoryManager* const manager) { // // If we are on NT, then use wide character APIs, else use ASCII APIs. // We have to do it manually since we are only built in ASCII mode from // the standpoint of the APIs. // if (gOnNT) { // Use a local buffer that is big enough for the largest legal path const unsigned int bufSize = 1024; XMLCh tmpPath[bufSize + 1]; XMLCh* namePart = 0; if (!::GetFullPathNameW((LPCWSTR)srcPath, bufSize, (LPWSTR)tmpPath, (LPWSTR*)&namePart)) return 0; // Return a copy of the path return XMLString::replicate(tmpPath, manager); } else { // Transcode the incoming string char* tmpSrcPath = XMLString::transcode(srcPath, fgMemoryManager); ArrayJanitor<char> janSrcPath(tmpSrcPath, fgMemoryManager); // Use a local buffer that is big enough for the largest legal path const unsigned int bufSize = 511; char tmpPath[511 + 1]; char* namePart = 0; if (!::GetFullPathNameA(tmpSrcPath, bufSize, tmpPath, &namePart)) return 0; // Return a transcoded copy of the path return XMLString::transcode(tmpPath, manager); } } bool XMLPlatformUtils::isRelative(const XMLCh* const toCheck , MemoryManager* const manager) { // Check for pathological case of empty path if (!toCheck[0]) return false; // // If its starts with a drive, then it cannot be relative. Note that // we checked the drive not being empty above, so worst case its one // char long and the check of the 1st char will fail because its really // a null character. // if (toCheck[1] == chColon) { if (((toCheck[0] >= chLatin_A) && (toCheck[0] <= chLatin_Z)) || ((toCheck[0] >= chLatin_a) && (toCheck[0] <= chLatin_z))) { return false; } } // // If it starts with a double slash, then it cannot be relative since // it's a remote file. // if (isBackSlash(toCheck[0]) && isBackSlash(toCheck[1])) return false; // Else assume its a relative path return true; } XMLCh* XMLPlatformUtils::getCurrentDirectory(MemoryManager* const manager) { // // If we are on NT, then use wide character APIs, else use ASCII APIs. // We have to do it manually since we are only built in ASCII mode from // the standpoint of the APIs. // if (gOnNT) { // Use a local buffer that is big enough for the largest legal path const unsigned int bufSize = 1024; XMLCh tmpPath[bufSize + 1]; if (!::GetCurrentDirectoryW(bufSize, (LPWSTR)tmpPath)) return 0; // Return a copy of the path return XMLString::replicate(tmpPath, manager); } else { // Use a local buffer that is big enough for the largest legal path const unsigned int bufSize = 511; char tmpPath[511 + 1]; if (!::GetCurrentDirectoryA(bufSize, tmpPath)) return 0; // Return a transcoded copy of the path return XMLString::transcode(tmpPath, manager); } } inline bool XMLPlatformUtils::isAnySlash(XMLCh c) { return c == chBackSlash || c == chForwardSlash || c == chYenSign || c == chWonSign; } // --------------------------------------------------------------------------- // XMLPlatformUtils: Timing Methods // --------------------------------------------------------------------------- unsigned long XMLPlatformUtils::getCurrentMillis() { return (unsigned long)::GetTickCount(); } // --------------------------------------------------------------------------- // Mutex methods // --------------------------------------------------------------------------- void XMLPlatformUtils::closeMutex(void* const mtxHandle) { ::DeleteCriticalSection((LPCRITICAL_SECTION)mtxHandle); delete (CRITICAL_SECTION*)mtxHandle; } void XMLPlatformUtils::lockMutex(void* const mtxHandle) { ::EnterCriticalSection((LPCRITICAL_SECTION)mtxHandle); } void* XMLPlatformUtils::makeMutex() { CRITICAL_SECTION* newCS = new CRITICAL_SECTION; InitializeCriticalSection(newCS); return newCS; } void XMLPlatformUtils::unlockMutex(void* const mtxHandle) { ::LeaveCriticalSection((LPCRITICAL_SECTION)mtxHandle); } // --------------------------------------------------------------------------- // Miscellaneous synchronization methods // --------------------------------------------------------------------------- void* XMLPlatformUtils::compareAndSwap( void** toFill , const void* const newValue , const void* const toCompare) { #if defined WIN64 return ::InterlockedCompareExchangePointer(toFill, (void*)newValue, (void*)toCompare); #else // // InterlockedCompareExchange is only supported on Windows 98, // Windows NT 4.0, and newer -- not on Windows 95... // If you are willing to give up Win95 support change this to #if 0 // otherwise we are back to using assembler. // (But only if building with compilers that support inline assembler.) // #if (defined(_MSC_VER) || defined(__BCPLUSPLUS__)) && !defined(XERCES_NO_ASM) void* result; __asm { mov eax, toCompare; mov ebx, newValue; mov ecx, toFill lock cmpxchg [ecx], ebx; mov result, eax; } return result; #else // // Note we have to cast off the constness of some of these because // the system APIs are not C++ aware in all cases. // return (void*) ::InterlockedCompareExchange((LPLONG)toFill, (LONG)newValue, (LONG)toCompare); #endif #endif } // --------------------------------------------------------------------------- // Atomic increment and decrement methods // --------------------------------------------------------------------------- int XMLPlatformUtils::atomicIncrement(int &location) { return ::InterlockedIncrement(&(long &)location); } int XMLPlatformUtils::atomicDecrement(int &location) { return ::InterlockedDecrement(&(long &)location); } // --------------------------------------------------------------------------- // XMLPlatformUtils: Private Static Methods // --------------------------------------------------------------------------- // // This method is called by the platform independent part of this class // during initialization. We have to create the type of net accessor that // we want to use. If none, then just return zero. // XMLNetAccessor* XMLPlatformUtils::makeNetAccessor() { #if defined (XML_USE_NETACCESSOR_LIBWWW) return new LibWWWNetAccessor(); #elif defined (XML_USE_NETACCESSOR_WINSOCK) return new WinSockNetAccessor(); #else return 0; #endif } // // This method is called by the platform independent part of this class // when client code asks to have one of the supported message sets loaded. // In our case, we use the ICU based message loader mechanism. // XMLMsgLoader* XMLPlatformUtils::loadAMsgSet(const XMLCh* const msgDomain) { #if defined (XML_USE_INMEM_MESSAGELOADER) return new InMemMsgLoader(msgDomain); #elif defined (XML_USE_WIN32_MSGLOADER) return new Win32MsgLoader(msgDomain); #elif defined (XML_USE_ICU_MESSAGELOADER) return new ICUMsgLoader(msgDomain); #else #error You must provide a message loader #endif } // // This method is called very early in the bootstrapping process. This guy // must create a transcoding service and return it. It cannot use any string // methods, any transcoding services, throw any exceptions, etc... It just // makes a transcoding service and returns it, or returns zero on failure. // XMLTransService* XMLPlatformUtils::makeTransService() { // // Since we are going to use the ICU service, we have to tell it where // its converter files are. If the ICU_DATA environment variable is set, // then its been told. Otherwise, we tell it our default value relative // to our DLL. // #if defined (XML_USE_ICU_TRANSCODER) return new ICUTransService; #elif defined (XML_USE_WIN32_TRANSCODER) return new Win32TransService; #elif defined (XML_USE_CYGWIN_TRANSCODER) return new CygwinTransService; #else #error You must provide a transcoding service implementation #endif } // // This method handles the Win32 per-platform basic init functions. The // primary jobs here are getting the path to our DLL and to get the // stdout and stderr file handles setup. // void XMLPlatformUtils::platformInit() { #if 0 && defined(_DEBUG) // Enable this code for memeory leak testing // Send all reports to STDOUT _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT ); _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT ); int tmpDbgFlag; tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(tmpDbgFlag); #endif // Figure out if we are on NT and save that flag for later use OSVERSIONINFO OSVer; OSVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); ::GetVersionEx(&OSVer); gOnNT = (OSVer.dwPlatformId == VER_PLATFORM_WIN32_NT); } void XMLPlatformUtils::platformTerm() { // We don't have any temrination requirements for win32 at this time } #include <xercesc/util/LogicalPath.c> XERCES_CPP_NAMESPACE_END
[ [ [ 1, 852 ] ] ]
2fd4cd7f2828fa60c59c9adcb41fae3c77316f12
ca2395f4eec7e941d0d91d7e2913f8cc66b14472
/ConnectDialog.cpp
03cb0f02905be1bc7bafae5889127e38981ad7b0
[]
no_license
EmilHernvall/chatclient
21a27de2e44bb25dd2acb34a8d75a79d8e7bd46a
47e16866992e4dd4ce3e5538b32b09ed2dfaef06
refs/heads/master
2021-01-15T22:28:44.465662
2008-04-16T16:12:48
2008-04-16T16:12:48
1,697,523
0
0
null
null
null
null
UTF-8
C++
false
false
4,073
cpp
#include "stdafx.h" #include "ConnectDialog.h" #include "ChatClient.h" #include "Net.h" #include "IRC.h" // Declared in NetThread.cpp VOID NetworkThread(PVOID pvoid); ConnectDialog::ConnectDialog(HINSTANCE hInst, INT nResource, HWND hwndParent, ChatClient *bwChatClient) : Dialog(hInst, nResource, hwndParent) { m_bwChatClient = bwChatClient; m_net = bwChatClient->GetNet(); m_irc = bwChatClient->GetIRC(); } // Message handler for connect box. INT_PTR CALLBACK ConnectDialog::HandleMessage(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { int wmEvent; TCHAR szHost[200], szPort[200], szNick[200], szUser[200], szChannel[200], szInfo[1024]; LPTSTR szConnectHost, szConnectNick, szConnectUser, szConnectChannel; WORD wConnectPort; HWND hHost, hPort, hNick, hUser, hChannel; UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: hHost = GetDlgItem(hDlg, IDC_HOST_EDIT); hPort = GetDlgItem(hDlg, IDC_PORT_EDIT); hNick = GetDlgItem(hDlg, IDC_NICK_EDIT); hUser = GetDlgItem(hDlg, IDC_USER_EDIT); hChannel = GetDlgItem(hDlg, IDC_CHANNEL_EDIT); SendMessage(hHost, EM_SETLIMITTEXT, 30, 0); SendMessage(hPort, EM_SETLIMITTEXT, 5, 0); SendMessage(hNick, EM_SETLIMITTEXT, 30, 0); SendMessage(hUser, EM_SETLIMITTEXT, 30, 0); SendMessage(hChannel, EM_SETLIMITTEXT, 30, 0); Edit_SetText(hHost, TEXT("beppe.c0la.se")); Edit_SetText(hPort, TEXT("6667")); Edit_SetText(hNick, TEXT("Aderyn2")); Edit_SetText(hUser, TEXT("Emil")); Edit_SetText(hChannel, TEXT("#floodffs!")); return (INT_PTR)TRUE; case WM_COMMAND: wmEvent = LOWORD(wParam); switch (wmEvent) { case IDOK: hHost = GetDlgItem(hDlg, IDC_HOST_EDIT); hPort = GetDlgItem(hDlg, IDC_PORT_EDIT); hNick = GetDlgItem(hDlg, IDC_NICK_EDIT); hUser = GetDlgItem(hDlg, IDC_USER_EDIT); hChannel = GetDlgItem(hDlg, IDC_CHANNEL_EDIT); Edit_GetText(hHost, (LPTSTR)szHost, sizeof(szHost)/sizeof(TCHAR)); Edit_GetText(hPort, (LPTSTR)szPort, sizeof(szPort)/sizeof(TCHAR)); Edit_GetText(hNick, (LPTSTR)szNick, sizeof(szNick)/sizeof(TCHAR)); Edit_GetText(hUser, (LPTSTR)szUser, sizeof(szUser)/sizeof(TCHAR)); Edit_GetText(hChannel, (LPTSTR)szChannel, sizeof(szChannel)/sizeof(TCHAR)); if (_tcslen(szHost) == 0) { MessageBox(hDlg, TEXT("You have to specify a host!"), TEXT("Error!"), MB_ICONEXCLAMATION); SetFocus(hHost); return (INT_PTR)FALSE; } if (_tcslen(szPort) == 0) { MessageBox(hDlg, TEXT("You have to specify a port!"), TEXT("Error!"), MB_ICONEXCLAMATION); SetFocus(hPort); return (INT_PTR)FALSE; } if (_tcslen(szNick) == 0) { MessageBox(hDlg, TEXT("You have to specify a nick!"), TEXT("Error!"), MB_ICONEXCLAMATION); SetFocus(hNick); return (INT_PTR)FALSE; } if (_tcslen(szUser) == 0) { MessageBox(hDlg, TEXT("You have to specify a user!"), TEXT("Error!"), MB_ICONEXCLAMATION); SetFocus(hUser); return (INT_PTR)FALSE; } if (_tcslen(szChannel) == 0) { MessageBox(hDlg, TEXT("You have to specify a channel!"), TEXT("Error!"), MB_ICONEXCLAMATION); SetFocus(hChannel); return (INT_PTR)FALSE; } _stprintf_s(szInfo, sizeof(szInfo)/sizeof(TCHAR), TEXT("Connecting to %s:%s with nick \"%s\" and username \"%s\"."), szHost, szPort, szNick, szUser); szConnectHost = _tcsdup(szHost); wConnectPort = _tstoi(szPort); szConnectNick = _tcsdup(szNick); szConnectUser = _tcsdup(szUser); szConnectChannel = _tcsdup(szChannel); m_bwChatClient->AppendToBuffer(0, szInfo); m_net->Connect(szConnectHost, wConnectPort); m_irc->SetNick(szConnectNick); m_irc->SetUser(szConnectUser); m_irc->SetChannel(szConnectChannel); _beginthread (NetworkThread, 0, m_bwChatClient); EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; break; case IDCANCEL: EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; break; } break; } return (INT_PTR)FALSE; }
[ "emil@2d89dd5f-9cc0-461d-8d4c-555c0e271dc8" ]
[ [ [ 1, 129 ] ] ]
8e0e37dd606edefcdd7bfd1d323fbe90e0aec489
6c8c4728e608a4badd88de181910a294be56953a
/CommunicationModule/TelepathyIM/FriendRequest.h
178683862216c2ded2516e6dabcf183452f97cbe
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,015
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_Communication_TelepathyIM_FriendRequest_h #define incl_Communication_TelepathyIM_FriendRequest_h #include <TelepathyQt4/Contact> #include <TelepathyQt4/PendingOperation> //#include "interface.h" #include "ModuleLoggingFunctions.h" #include "FriendRequestInterface.h" namespace TelepathyIM { /** * This class is only used by CommunicationService object. Do not use this * directly! * * A received friend request. This can be accepted or rejected. If Accpet() methos is called1 * then Connection object emits NewContact signal. * * */ class FriendRequest : public Communication::FriendRequestInterface { Q_OBJECT MODULE_LOGGING_FUNCTIONS static const std::string NameStatic() { return "CommunicationModule"; } // for logging functionality public: FriendRequest(Tp::ContactPtr contact); virtual QString GetOriginatorName() const; virtual QString GetOriginatorID() const; virtual Communication::FriendRequestInterface::State GetState() const; virtual void Accept(); virtual void Reject(); virtual Tp::ContactPtr GetOriginatorTpContact(); protected slots: virtual void OnPresencePublicationAuthorized(Tp::PendingOperation* op); virtual void OnPresenceSubscriptionResult(Tp::PendingOperation* op); virtual void OnPresenceSubscriptionChanged(Tp::Contact::PresenceState state); protected: State state_; Tp::ContactPtr tp_contact_; signals: //! When both the user and the target contact have published their presence void Accepted(FriendRequest*request); void Canceled(FriendRequest*request); }; // typedef std::vector<FriendRequest*> FriendRequestVector; } // end of namespace: TelepathyIM #endif // incl_Communication_TelepathyIM_FriendRequest_h
[ "Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3", "mattiku@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 2 ], [ 13, 18 ], [ 20, 34 ], [ 36, 38 ], [ 42, 43 ], [ 49, 49 ] ], [ [ 3, 7 ], [ 11, 12 ], [ 19, 19 ], [ 35, 35 ], [ 39, 41 ], [ 44, 48 ], [ 51, 54 ] ], [ [ 8, 10 ], [ 50, 50 ] ] ]
a841298db1f875c97a5eedf36f5386272bf0d32f
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/crypto++/5.2.1/serpent.cpp
db5ff89ab9ef322c853f15b355d9164afa9b4b7c
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-cryptopp" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
11,376
cpp
// serpent.cpp - written and placed in the public domain by Wei Dai #include "pch.h" #include "serpent.h" #include "misc.h" NAMESPACE_BEGIN(CryptoPP) // linear transformation #define LT(i,a,b,c,d,e) {\ a = rotlFixed(a, 13); \ c = rotlFixed(c, 3); \ d = rotlFixed(d ^ c ^ (a << 3), 7); \ b = rotlFixed(b ^ a ^ c, 1); \ a = rotlFixed(a ^ b ^ d, 5); \ c = rotlFixed(c ^ d ^ (b << 7), 22);} // inverse linear transformation #define ILT(i,a,b,c,d,e) {\ c = rotrFixed(c, 22); \ a = rotrFixed(a, 5); \ c ^= d ^ (b << 7); \ a ^= b ^ d; \ b = rotrFixed(b, 1); \ d = rotrFixed(d, 7) ^ c ^ (a << 3); \ b ^= a ^ c; \ c = rotrFixed(c, 3); \ a = rotrFixed(a, 13);} // order of output from S-box functions #define beforeS0(f) f(0,a,b,c,d,e) #define afterS0(f) f(1,b,e,c,a,d) #define afterS1(f) f(2,c,b,a,e,d) #define afterS2(f) f(3,a,e,b,d,c) #define afterS3(f) f(4,e,b,d,c,a) #define afterS4(f) f(5,b,a,e,c,d) #define afterS5(f) f(6,a,c,b,e,d) #define afterS6(f) f(7,a,c,d,b,e) #define afterS7(f) f(8,d,e,b,a,c) // order of output from inverse S-box functions #define beforeI7(f) f(8,a,b,c,d,e) #define afterI7(f) f(7,d,a,b,e,c) #define afterI6(f) f(6,a,b,c,e,d) #define afterI5(f) f(5,b,d,e,c,a) #define afterI4(f) f(4,b,c,e,a,d) #define afterI3(f) f(3,a,b,e,c,d) #define afterI2(f) f(2,b,d,e,c,a) #define afterI1(f) f(1,a,b,c,e,d) #define afterI0(f) f(0,a,d,b,e,c) // The instruction sequences for the S-box functions // come from Dag Arne Osvik's paper "Speeding up Serpent". #define S0(i, r0, r1, r2, r3, r4) \ { \ r3 ^= r0; \ r4 = r1; \ r1 &= r3; \ r4 ^= r2; \ r1 ^= r0; \ r0 |= r3; \ r0 ^= r4; \ r4 ^= r3; \ r3 ^= r2; \ r2 |= r1; \ r2 ^= r4; \ r4 = ~r4; \ r4 |= r1; \ r1 ^= r3; \ r1 ^= r4; \ r3 |= r0; \ r1 ^= r3; \ r4 ^= r3; \ } #define I0(i, r0, r1, r2, r3, r4) \ { \ r2 = ~r2; \ r4 = r1; \ r1 |= r0; \ r4 = ~r4; \ r1 ^= r2; \ r2 |= r4; \ r1 ^= r3; \ r0 ^= r4; \ r2 ^= r0; \ r0 &= r3; \ r4 ^= r0; \ r0 |= r1; \ r0 ^= r2; \ r3 ^= r4; \ r2 ^= r1; \ r3 ^= r0; \ r3 ^= r1; \ r2 &= r3; \ r4 ^= r2; \ } #define S1(i, r0, r1, r2, r3, r4) \ { \ r0 = ~r0; \ r2 = ~r2; \ r4 = r0; \ r0 &= r1; \ r2 ^= r0; \ r0 |= r3; \ r3 ^= r2; \ r1 ^= r0; \ r0 ^= r4; \ r4 |= r1; \ r1 ^= r3; \ r2 |= r0; \ r2 &= r4; \ r0 ^= r1; \ r1 &= r2; \ r1 ^= r0; \ r0 &= r2; \ r0 ^= r4; \ } #define I1(i, r0, r1, r2, r3, r4) \ { \ r4 = r1; \ r1 ^= r3; \ r3 &= r1; \ r4 ^= r2; \ r3 ^= r0; \ r0 |= r1; \ r2 ^= r3; \ r0 ^= r4; \ r0 |= r2; \ r1 ^= r3; \ r0 ^= r1; \ r1 |= r3; \ r1 ^= r0; \ r4 = ~r4; \ r4 ^= r1; \ r1 |= r0; \ r1 ^= r0; \ r1 |= r4; \ r3 ^= r1; \ } #define S2(i, r0, r1, r2, r3, r4) \ { \ r4 = r0; \ r0 &= r2; \ r0 ^= r3; \ r2 ^= r1; \ r2 ^= r0; \ r3 |= r4; \ r3 ^= r1; \ r4 ^= r2; \ r1 = r3; \ r3 |= r4; \ r3 ^= r0; \ r0 &= r1; \ r4 ^= r0; \ r1 ^= r3; \ r1 ^= r4; \ r4 = ~r4; \ } #define I2(i, r0, r1, r2, r3, r4) \ { \ r2 ^= r3; \ r3 ^= r0; \ r4 = r3; \ r3 &= r2; \ r3 ^= r1; \ r1 |= r2; \ r1 ^= r4; \ r4 &= r3; \ r2 ^= r3; \ r4 &= r0; \ r4 ^= r2; \ r2 &= r1; \ r2 |= r0; \ r3 = ~r3; \ r2 ^= r3; \ r0 ^= r3; \ r0 &= r1; \ r3 ^= r4; \ r3 ^= r0; \ } #define S3(i, r0, r1, r2, r3, r4) \ { \ r4 = r0; \ r0 |= r3; \ r3 ^= r1; \ r1 &= r4; \ r4 ^= r2; \ r2 ^= r3; \ r3 &= r0; \ r4 |= r1; \ r3 ^= r4; \ r0 ^= r1; \ r4 &= r0; \ r1 ^= r3; \ r4 ^= r2; \ r1 |= r0; \ r1 ^= r2; \ r0 ^= r3; \ r2 = r1; \ r1 |= r3; \ r1 ^= r0; \ } #define I3(i, r0, r1, r2, r3, r4) \ { \ r4 = r2; \ r2 ^= r1; \ r1 &= r2; \ r1 ^= r0; \ r0 &= r4; \ r4 ^= r3; \ r3 |= r1; \ r3 ^= r2; \ r0 ^= r4; \ r2 ^= r0; \ r0 |= r3; \ r0 ^= r1; \ r4 ^= r2; \ r2 &= r3; \ r1 |= r3; \ r1 ^= r2; \ r4 ^= r0; \ r2 ^= r4; \ } #define S4(i, r0, r1, r2, r3, r4) \ { \ r1 ^= r3; \ r3 = ~r3; \ r2 ^= r3; \ r3 ^= r0; \ r4 = r1; \ r1 &= r3; \ r1 ^= r2; \ r4 ^= r3; \ r0 ^= r4; \ r2 &= r4; \ r2 ^= r0; \ r0 &= r1; \ r3 ^= r0; \ r4 |= r1; \ r4 ^= r0; \ r0 |= r3; \ r0 ^= r2; \ r2 &= r3; \ r0 = ~r0; \ r4 ^= r2; \ } #define I4(i, r0, r1, r2, r3, r4) \ { \ r4 = r2; \ r2 &= r3; \ r2 ^= r1; \ r1 |= r3; \ r1 &= r0; \ r4 ^= r2; \ r4 ^= r1; \ r1 &= r2; \ r0 = ~r0; \ r3 ^= r4; \ r1 ^= r3; \ r3 &= r0; \ r3 ^= r2; \ r0 ^= r1; \ r2 &= r0; \ r3 ^= r0; \ r2 ^= r4; \ r2 |= r3; \ r3 ^= r0; \ r2 ^= r1; \ } #define S5(i, r0, r1, r2, r3, r4) \ { \ r0 ^= r1; \ r1 ^= r3; \ r3 = ~r3; \ r4 = r1; \ r1 &= r0; \ r2 ^= r3; \ r1 ^= r2; \ r2 |= r4; \ r4 ^= r3; \ r3 &= r1; \ r3 ^= r0; \ r4 ^= r1; \ r4 ^= r2; \ r2 ^= r0; \ r0 &= r3; \ r2 = ~r2; \ r0 ^= r4; \ r4 |= r3; \ r2 ^= r4; \ } #define I5(i, r0, r1, r2, r3, r4) \ { \ r1 = ~r1; \ r4 = r3; \ r2 ^= r1; \ r3 |= r0; \ r3 ^= r2; \ r2 |= r1; \ r2 &= r0; \ r4 ^= r3; \ r2 ^= r4; \ r4 |= r0; \ r4 ^= r1; \ r1 &= r2; \ r1 ^= r3; \ r4 ^= r2; \ r3 &= r4; \ r4 ^= r1; \ r3 ^= r0; \ r3 ^= r4; \ r4 = ~r4; \ } #define S6(i, r0, r1, r2, r3, r4) \ { \ r2 = ~r2; \ r4 = r3; \ r3 &= r0; \ r0 ^= r4; \ r3 ^= r2; \ r2 |= r4; \ r1 ^= r3; \ r2 ^= r0; \ r0 |= r1; \ r2 ^= r1; \ r4 ^= r0; \ r0 |= r3; \ r0 ^= r2; \ r4 ^= r3; \ r4 ^= r0; \ r3 = ~r3; \ r2 &= r4; \ r2 ^= r3; \ } #define I6(i, r0, r1, r2, r3, r4) \ { \ r0 ^= r2; \ r4 = r2; \ r2 &= r0; \ r4 ^= r3; \ r2 = ~r2; \ r3 ^= r1; \ r2 ^= r3; \ r4 |= r0; \ r0 ^= r2; \ r3 ^= r4; \ r4 ^= r1; \ r1 &= r3; \ r1 ^= r0; \ r0 ^= r3; \ r0 |= r2; \ r3 ^= r1; \ r4 ^= r0; \ } #define S7(i, r0, r1, r2, r3, r4) \ { \ r4 = r2; \ r2 &= r1; \ r2 ^= r3; \ r3 &= r1; \ r4 ^= r2; \ r2 ^= r1; \ r1 ^= r0; \ r0 |= r4; \ r0 ^= r2; \ r3 ^= r1; \ r2 ^= r3; \ r3 &= r0; \ r3 ^= r4; \ r4 ^= r2; \ r2 &= r0; \ r4 = ~r4; \ r2 ^= r4; \ r4 &= r0; \ r1 ^= r3; \ r4 ^= r1; \ } #define I7(i, r0, r1, r2, r3, r4) \ { \ r4 = r2; \ r2 ^= r0; \ r0 &= r3; \ r2 = ~r2; \ r4 |= r3; \ r3 ^= r1; \ r1 |= r0; \ r0 ^= r2; \ r2 &= r4; \ r1 ^= r2; \ r2 ^= r0; \ r0 |= r2; \ r3 &= r4; \ r0 ^= r3; \ r4 ^= r1; \ r3 ^= r4; \ r4 |= r0; \ r3 ^= r2; \ r4 ^= r2; \ } // key xor #define KX(r, a, b, c, d, e) {\ a ^= k[4 * r + 0]; \ b ^= k[4 * r + 1]; \ c ^= k[4 * r + 2]; \ d ^= k[4 * r + 3];} void Serpent::Base::UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int keylen) { AssertValidKeyLength(keylen); word32 *k = m_key; GetUserKey(LITTLE_ENDIAN_ORDER, k, 8, userKey, keylen); if (keylen < 32) k[keylen/4] |= word32(1) << ((keylen%4)*8); k += 8; word32 t = k[-1]; signed int i; for (i = 0; i < 132; ++i) k[i] = t = rotlFixed(k[i-8] ^ k[i-5] ^ k[i-3] ^ t ^ 0x9e3779b9 ^ i, 11); k -= 20; #define LK(r, a, b, c, d, e) {\ a = k[(8-r)*4 + 0]; \ b = k[(8-r)*4 + 1]; \ c = k[(8-r)*4 + 2]; \ d = k[(8-r)*4 + 3];} #define SK(r, a, b, c, d, e) {\ k[(8-r)*4 + 4] = a; \ k[(8-r)*4 + 5] = b; \ k[(8-r)*4 + 6] = c; \ k[(8-r)*4 + 7] = d;} \ word32 a,b,c,d,e; for (i=0; i<4; i++) { afterS2(LK); afterS2(S3); afterS3(SK); afterS1(LK); afterS1(S2); afterS2(SK); afterS0(LK); afterS0(S1); afterS1(SK); beforeS0(LK); beforeS0(S0); afterS0(SK); k += 8*4; afterS6(LK); afterS6(S7); afterS7(SK); afterS5(LK); afterS5(S6); afterS6(SK); afterS4(LK); afterS4(S5); afterS5(SK); afterS3(LK); afterS3(S4); afterS4(SK); } afterS2(LK); afterS2(S3); afterS3(SK); } typedef BlockGetAndPut<word32, LittleEndian> Block; void Serpent::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const { word32 a, b, c, d, e; Block::Get(inBlock)(a)(b)(c)(d); const word32 *k = m_key + 8; unsigned int i=1; do { beforeS0(KX); beforeS0(S0); afterS0(LT); afterS0(KX); afterS0(S1); afterS1(LT); afterS1(KX); afterS1(S2); afterS2(LT); afterS2(KX); afterS2(S3); afterS3(LT); afterS3(KX); afterS3(S4); afterS4(LT); afterS4(KX); afterS4(S5); afterS5(LT); afterS5(KX); afterS5(S6); afterS6(LT); afterS6(KX); afterS6(S7); if (i == 4) break; ++i; c = b; b = e; e = d; d = a; a = e; k += 32; beforeS0(LT); } while (true); afterS7(KX); Block::Put(xorBlock, outBlock)(d)(e)(b)(a); } void Serpent::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const { word32 a, b, c, d, e; Block::Get(inBlock)(a)(b)(c)(d); const word32 *k = m_key + 104; unsigned int i=4; beforeI7(KX); goto start; do { c = b; b = d; d = e; k -= 32; beforeI7(ILT); start: beforeI7(I7); afterI7(KX); afterI7(ILT); afterI7(I6); afterI6(KX); afterI6(ILT); afterI6(I5); afterI5(KX); afterI5(ILT); afterI5(I4); afterI4(KX); afterI4(ILT); afterI4(I3); afterI3(KX); afterI3(ILT); afterI3(I2); afterI2(KX); afterI2(ILT); afterI2(I1); afterI1(KX); afterI1(ILT); afterI1(I0); afterI0(KX); } while (--i != 0); Block::Put(xorBlock, outBlock)(a)(d)(b)(e); } NAMESPACE_END
[ [ [ 1, 544 ] ] ]
21d5c78c8194d31ed07839c3875de205786b3214
3276915b349aec4d26b466d48d9c8022a909ec16
/c++/运算符重载/转换运算符重载.cpp
7831a4ee518db83aacbb765c9583242645617e73
[]
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
GB18030
C++
false
false
407
cpp
//转换运算符 #include<iostream> #include<string> using namespace std; class inter { string::size_type num; public: inter() : num(48){} operator int () const //没有返回值 没有参数 为const 必须return num { cout <<"调用转换操作符" << endl; return num; } }; int main() { inter minter; cout << char(minter) << endl; getchar(); }
[ [ [ 1, 29 ] ] ]
cbeda2db237180d738c23b6b55f4ba613b101b0e
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/packages/dGLW/dGLWButton.h
52fe8696490650ccf3a5e5cf0fa392db5b631940
[]
no_license
Naddiseo/Newton-Dynamics-fork
cb0b8429943b9faca9a83126280aa4f2e6944f7f
91ac59c9687258c3e653f592c32a57b61dc62fb6
refs/heads/master
2021-01-15T13:45:04.651163
2011-11-12T04:02:33
2011-11-12T04:02:33
2,759,246
0
0
null
null
null
null
UTF-8
C++
false
false
1,146
h
/* Copyright (c) <2010-2011> <Julio Jerez, Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #ifndef __dGLWButton_H_ #define __dGLWButton_H_ #include "dGLWWidget.h" class dGLWButton: public dGLWWidget { public: dGLWButton(dGLWWidget* const parent); virtual ~dGLWButton(void); }; #endif
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 34 ] ] ]
25c51dbcd4b2e994c214ec29b1b629c6a4daf567
19b8f2132768c8c52238180e15815cbd4243b41d
/EDA Fase II/EDA II Fase 11057 Exact Sum/11057/main.cpp
f0b01d9897fb4c124372ae4269dfee79de39b07c
[]
no_license
Greatfox/Programas-EDA
604ae99e2576ecfae8a0a2965834d1206f41fb02
73d5d5961e041c27aadea0314f066e21e6d87807
refs/heads/master
2016-09-03T02:23:10.221535
2011-12-16T04:44:39
2011-12-16T04:44:39
2,279,239
0
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
#include <iostream> #include <cstdio> #include <string> #include <vector> #include <sstream> #include <math.h> #include <algorithm> using namespace std; bool myfunction (int i,int j) { return (i<j); } int main() { int N,costo,T,sol1,sol2; vector <int> VC; while(cin>>N) { for(int i=0;i<N;i++) { cin>>costo; VC.push_back(costo); } sort(VC.begin(),VC.end(),myfunction); cin>>T; int i=0; int j=VC.size()-1; while(i<j) { if(VC[i]+VC[j]==T) { sol1=i; sol2=j; i++; j--; } if(VC[i]+VC[j]<T) i++; if(VC[i]+VC[j]>T) j--; } cout<<"Peter should buy books whose prices are "<<VC[sol1]<<" and "<<VC[sol2]<<"."<<endl<<endl; VC.clear(); } }
[ [ [ 1, 46 ] ] ]
385b701c458e60c8fd96a221c7095c77a4974f45
de98f880e307627d5ce93dcad1397bd4813751dd
/3libs/ut/include/OXDlgBar.h
2f02a5eb49554ae0df1de72d0af52fa607990997
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,245
h
// ========================================================================== // Class Specification : COXDialogBar // ========================================================================== // Header file : OXDlgBar.h // Version: 9.3 // This software along with its related components, documentation and files ("The Libraries") // is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is // governed by a software license agreement ("Agreement"). Copies of the Agreement are // available at The Code Project (www.codeproject.com), as part of the package you downloaded // to obtain this file, or directly from our office. For a copy of the license governing // this software, you may contact us at [email protected], or by calling 416-849-8900. // ////////////////////////////////////////////////////////////////////////// // Properties: // NO Abstract class (does not have any objects) // YES Derived from CControlBar // YES Is a Cwnd. // YES Two stage creation (constructor & Create()) // YES Has a message map // NO Needs a resource (template) // NO Persistent objects (saveable on disk) // YES Uses exceptions // ////////////////////////////////////////////////////////////////////////// // Desciption : // This class encapsulates a controlbar with a dialog created from a memory template // on top of it. ///////////////////////////////////////////////////////////////////////////// #ifndef __DIALOGBAR_H__ #define __DIALOGBAR_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "OXDllExt.h" class OX_CLASS_DECL COXDialogBar : public CControlBar { // Data Members public: //{{AFX_DATA(COXDockPropertySheet) //}}AFX_DATA protected: CSize m_sizeDefault; private: // Member Functions public: COXDialogBar(); // --- In : // --- Out : // --- Returns : // --- Effect : Contructor of object BOOL Create(CWnd* pParentWnd, UINT nStyle, UINT nID); // --- In : pParentWnd : parent window // nDlgStyle : styles for the 'memory' dialog // nID : ID of the dialog // --- Out : // --- Returns : successful or not // --- Effect : Creates Control bar with a dialog from a mem template on top of it virtual ~COXDialogBar(); // --- In : // --- Out : // --- Returns : // --- Effect : Destructor of object protected: virtual BOOL CreateMemDialog(CWnd* pParentWnd); virtual CSize CalcFixedLayout(BOOL bStretch, BOOL bHorz); // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(COXDialogBar) public: protected: void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler); //}}AFX_VIRTUAL // Generated message map functions //{{AFX_MSG(COXDialogBar) //}}AFX_MSG protected: #ifndef _AFX_NO_OCC_SUPPORT // data and functions necessary for OLE control containment _AFX_OCC_DIALOG_INFO* m_pOccDialogInfo; LPCTSTR m_lpszTemplateName; virtual BOOL SetOccDialogInfo(_AFX_OCC_DIALOG_INFO* pOccDialogInfo); afx_msg LRESULT HandleInitDialog(WPARAM, LPARAM); DECLARE_MESSAGE_MAP() #endif private: }; #endif //__DIALOGBAR_H__
[ [ [ 1, 111 ] ] ]
210af3c633673c8a54eab9472a4bfa77bfbfb5dc
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/GameDLL/VehicleMovementBase.cpp
f1d27f1b6c32b0ce1fc518924c37aed116df178d
[]
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
68,614
cpp
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2005. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: Implements a base class for vehicle movements ------------------------------------------------------------------------- History: - 09:28:2005: Created by Mathieu Pinard *************************************************************************/ #include "StdAfx.h" #include "Game.h" #include "GameCVars.h" #include "IVehicleSystem.h" #include "VehicleMovementBase.h" #include <IGameTokens.h> #include <IEffectSystem.h> #include "GameUtils.h" #define RUNSOUND_FADEIN_TIME 0.5f #define RUNSOUND_FADEOUT_TIME 0.5f #define WIND_MINSPEED 1.f #define WIND_MAXSPEED 50.f IGameTokenSystem* CVehicleMovementBase::m_pGameTokenSystem = 0; IVehicleSystem* CVehicleMovementBase::m_pVehicleSystem = 0; IActorSystem* CVehicleMovementBase::m_pActorSystem = 0; CVehicleMovementBase::TSurfaceSoundInfo CVehicleMovementBase::m_surfaceSoundInfo; float CVehicleMovementBase::m_sprintTime = 0.f; //------------------------------------------------------------------------ CVehicleMovementBase::CVehicleMovementBase() : m_actorId(0), m_pVehicle(0), m_pEntity(0), m_maxSpeed(0.f), m_enginePos(ZERO), m_runSoundDelay(0.f), m_rpmScale(0.f), m_rpmPitchSpeed(0.f), m_speedRatio(0.f), m_speedRatioUnit(0.f), m_isEngineDisabled(false), m_bMovementProcessingEnabled(true), m_aiTweaksId(-1), m_playerTweaksId(-1), m_playerBoostTweaksId(-1), m_multiplayerTweaksId(-1), m_maxSoundSlipSpeed(0.f), m_rpmScaleSgn(0.f), m_boost(false), m_wasBoosting(false), m_boostCounter(1.f), m_boostEndurance(10.f), m_boostStrength(1.f), m_boostRegen(10.f), m_lastMeasuredVel(ZERO), m_measureSpeedTimer(0.f), m_soundMasterVolume(1.f), m_dampAngle(ZERO), m_dampAngVel(ZERO), m_pPaParams(NULL) { m_pWind[0] = m_pWind[1] = NULL; } //------------------------------------------------------------------------ CVehicleMovementBase::~CVehicleMovementBase() { // environmental for (SEnvParticleStatus::TEnvEmitters::iterator it=m_paStats.envStats.emitters.begin(); it!=m_paStats.envStats.emitters.end(); ++it) { FreeEmitterSlot(it->slot); if (it->pGroundEffect) it->pGroundEffect->Stop(true); } if (m_pWind[0]) { gEnv->pPhysicalWorld->DestroyPhysicalEntity(m_pWind[0]); gEnv->pPhysicalWorld->DestroyPhysicalEntity(m_pWind[1]); } } //------------------------------------------------------------------------ bool CVehicleMovementBase::Init(IVehicle* pVehicle, const SmartScriptTable &table) { m_pVehicle = pVehicle; m_pEntity = pVehicle->GetEntity(); m_pGameTokenSystem = g_pGame->GetIGameFramework()->GetIGameTokenSystem(); m_pVehicleSystem = g_pGame->GetIGameFramework()->GetIVehicleSystem(); m_pActorSystem = g_pGame->GetIGameFramework()->GetIActorSystem(); // init particles m_pPaParams = m_pVehicle->GetParticleParams(); InitExhaust(); for (int i=0; i<eVMA_Max; ++i) m_animations[i] = 0; SmartScriptTable animsTable; if (table->GetValue("Animations", animsTable)) { const char* engineAnim = ""; if (animsTable->GetValue("engine", engineAnim)) m_animations[eVMA_Engine] = m_pVehicle->GetAnimation(engineAnim); } m_isEnginePowered = false; m_isEngineStarting = false; m_isEngineGoingOff = false; m_engineStartup = 0.0f; m_damage = 0.0f; if (!table->GetValue("engineIgnitionTime", m_engineIgnitionTime)) m_engineIgnitionTime = 1.6f; // Sound params const char* eventGroupName = m_pEntity->GetClass()->GetName(); SmartScriptTable soundParams; if (table->GetValue("SoundParams", soundParams)) { soundParams->GetValue("eventGroup", eventGroupName); const char* pEngineSoundPosName; if (soundParams->GetValue("engineSoundPosition", pEngineSoundPosName)) { if (IVehicleHelper* pHelper = m_pVehicle->GetHelper(pEngineSoundPosName)) m_enginePos = pHelper->GetVehicleTM().GetTranslation(); else m_enginePos.zero(); } soundParams->GetValue("rpmPitchSpeed", m_rpmPitchSpeed); soundParams->GetValue("runSoundDelay", m_runSoundDelay); soundParams->GetValue("maxSlipSpeed", m_maxSoundSlipSpeed); if (m_runSoundDelay > 0.f) { // if runDelay set, it determines the engineIgnitionTime m_engineIgnitionTime = m_runSoundDelay + RUNSOUND_FADEIN_TIME; } } // init sound names if (eventGroupName[0]) { string prefix("sounds/vehicles:"); prefix.append(eventGroupName); prefix.MakeLower(); m_soundNames[eSID_Start] = prefix + ":start"; m_soundNames[eSID_Run] = prefix + ":run"; m_soundNames[eSID_Stop] = prefix + ":stop"; m_soundNames[eSID_Ambience] = prefix + ":ambience"; m_soundNames[eSID_Bump] = prefix + ":bump_on_road"; m_soundNames[eSID_Splash] = prefix + ":bounce_on_waves"; m_soundNames[eSID_Gear] = prefix + ":gear"; m_soundNames[eSID_Slip] = prefix + ":slip"; m_soundNames[eSID_Acceleration] = prefix + ":acceleration"; m_soundNames[eSID_Boost] = prefix + ":boost"; m_soundNames[eSID_Damage] = prefix + ":damage"; } m_pEntitySoundsProxy = (IEntitySoundProxy*) m_pEntity->CreateProxy(ENTITY_PROXY_SOUND); assert(m_pEntitySoundsProxy); if (gEnv->pSoundSystem && !GetSoundName(eSID_Run).empty()) { gEnv->pSoundSystem->Precache(GetSoundName(eSID_Run).c_str(), FLAG_SOUND_DEFAULT_3D, FLAG_SOUND_PRECACHE_EVENT_DEFAULT); } // init static soundinfo map if (m_surfaceSoundInfo.empty()) { m_surfaceSoundInfo.insert(TSurfaceSoundInfo::value_type("soil", SSurfaceSoundInfo(1))); m_surfaceSoundInfo.insert(TSurfaceSoundInfo::value_type("gravel", SSurfaceSoundInfo(2))); m_surfaceSoundInfo.insert(TSurfaceSoundInfo::value_type("concrete", SSurfaceSoundInfo(3))); m_surfaceSoundInfo.insert(TSurfaceSoundInfo::value_type("metal", SSurfaceSoundInfo(4))); m_surfaceSoundInfo.insert(TSurfaceSoundInfo::value_type("vegetation", SSurfaceSoundInfo(5))); m_surfaceSoundInfo.insert(TSurfaceSoundInfo::value_type("water", SSurfaceSoundInfo(6))); m_surfaceSoundInfo.insert(TSurfaceSoundInfo::value_type("ice", SSurfaceSoundInfo(7))); ISurfaceType* pSurface = gEnv->p3DEngine->GetMaterialManager()->GetSurfaceTypeByName("mat_glass_vehicle"); m_pVehicle->SetVehicleGlassSurfaceType(pSurface); } if (IVehicleComponent* pComp = m_pVehicle->GetComponent("Hull")) m_damageComponents.push_back(pComp); if (IVehicleComponent* pComp = m_pVehicle->GetComponent("Engine")) m_damageComponents.push_back(pComp); SmartScriptTable boostTable; if (table->GetValue("Boost", boostTable)) { boostTable->GetValue("endurance", m_boostEndurance); boostTable->GetValue("regeneration", m_boostRegen); boostTable->GetValue("strength", m_boostStrength); } SmartScriptTable airDampTable; if (table->GetValue("AirDamp", airDampTable)) { airDampTable->GetValue("dampAngle", m_dampAngle); airDampTable->GetValue("dampAngVel", m_dampAngVel); } ResetBoost(); return true; } //------------------------------------------------------------------------ void CVehicleMovementBase::PostInit() { m_aiTweaksId = m_movementTweaks.GetGroupId("ai"); m_playerTweaksId = m_movementTweaks.GetGroupId("player"); m_playerBoostTweaksId = m_movementTweaks.GetGroupId("player_boost"); m_multiplayerTweaksId = m_movementTweaks.GetGroupId("multiplayer"); } //------------------------------------------------------------------------ void CVehicleMovementBase::Physicalize() { } //------------------------------------------------------------------------ void CVehicleMovementBase::PostPhysicalize() { if (!m_paStats.envStats.initalized) InitSurfaceEffects(); } //------------------------------------------------------------------------ void CVehicleMovementBase::ResetInput() { ResetBoost(); m_movementAction.Clear(); } //------------------------------------------------------------------------ void CVehicleMovementBase::InitExhaust() { if(!m_pPaParams) return; for (int i=0; i<m_pPaParams->GetExhaustParams()->GetExhaustCount(); ++i) { SExhaustStatus stat; stat.pHelper = m_pPaParams->GetExhaustParams()->GetHelper(i); if (stat.pHelper) m_paStats.exhaustStats.push_back(stat); } } //------------------------------------------------------------------------ void CVehicleMovementBase::Release() { } //------------------------------------------------------------------------ void CVehicleMovementBase::Reset() { m_damage = 0.0f; m_isEngineDisabled = false; m_isEngineGoingOff = false; m_isEngineStarting = false; m_engineStartup = 0.0f; m_rpmScale = m_rpmScaleSgn = 0.f; if (m_isEnginePowered) { m_isEnginePowered = false; OnEngineCompletelyStopped(); } if (m_movementTweaks.RevertValues()) OnValuesTweaked(); StopSounds(); ResetParticles(); ResetBoost(); for (int i=0; i<eVMA_Max; ++i) { if (m_animations[i]) m_animations[i]->Reset(); } if (m_pWind[0]) { gEnv->pPhysicalWorld->DestroyPhysicalEntity(m_pWind[0]); gEnv->pPhysicalWorld->DestroyPhysicalEntity(m_pWind[1]); m_pWind[0] = m_pWind[1] = 0; } //InitWind(); m_movementAction.Clear(); m_movementAction.brake = true; m_bMovementProcessingEnabled = true; m_lastMeasuredVel.zero(); } //------------------------------------------------------------------------ bool CVehicleMovementBase::RequestMovement(CMovementRequest& movementRequest) { return false; } ////////////////////////////////////////////////////////////////////////// // NOTE: This function must be thread-safe. Before adding stuff contact MarcoC. void CVehicleMovementBase::ProcessMovement(const float deltaTime) { FUNCTION_PROFILER( GetISystem(), PROFILE_GAME ); IPhysicalEntity* pPhysics = GetPhysics(); assert(pPhysics); m_movementAction.isAI = false; if (!pPhysics->GetStatus(&m_PhysDyn)) return; if (!pPhysics->GetStatus(&m_PhysPos)) return; if (IActor* pActor = m_pActorSystem->GetActor(m_actorId)) { if (pActor->IsPlayer()) { m_movementAction.isAI = false; ProcessActions(deltaTime); } else { m_movementAction.isAI = true; ProcessAI(deltaTime); } } } //------------------------------------------------------------------------ void CVehicleMovementBase::RequestActions(const SVehicleMovementAction& movementAction) { m_movementAction = movementAction; for (TVehicleMovementActionFilterList::iterator ite = m_actionFilters.begin(); ite != m_actionFilters.end(); ++ite) { IVehicleMovementActionFilter* pActionFilter = *ite; pActionFilter->OnProcessActions(m_movementAction); } } //------------------------------------------------------------------------ void CVehicleMovementBase::UpdateSpeedRatio(const float deltaTime) { float speed = m_statusDyn.v.len(); Interpolate(m_speedRatio, min(1.f, sqr( speed / m_maxSpeed ) ), 5.f, deltaTime); m_speedRatioUnit = speed / m_maxSpeed; } //------------------------------------------------------------------------ void CVehicleMovementBase::Update(const float deltaTime) { FUNCTION_PROFILER( GetISystem(), PROFILE_GAME ); IPhysicalEntity* pPhysics = GetPhysics(); if (!(pPhysics && pPhysics->GetStatus(&m_statusDyn))) return; const SVehicleStatus& status = m_pVehicle->GetStatus(); int firstperson = 0; IActor* pClientActor = 0; if (m_pVehicle->IsPlayerPassenger()) { pClientActor = g_pGame->GetIGameFramework()->GetClientActor(); if (!pClientActor->IsThirdPerson()) firstperson = 1; } UpdateDamage(deltaTime); UpdateBoost(deltaTime); UpdateSpeedRatio(deltaTime); if (gEnv->bClient) { if(!m_pVehicle->IsPlayerDriving(true)) { if(m_boost != m_wasBoosting) Boost(m_boost); } m_wasBoosting = m_boost; UpdateExhaust(deltaTime); UpdateSurfaceEffects(deltaTime); UpdateWind(deltaTime); } DebugDraw(deltaTime); if (m_isEngineStarting) { m_engineStartup += deltaTime; if (m_runSoundDelay>0.f && m_engineStartup >= m_runSoundDelay) { ISound* pRunSound = GetSound(eSID_Run); if (!pRunSound) { // start run pRunSound = PlaySound(eSID_Run, 0.f, m_enginePos); if (m_pVehicle->IsPlayerPassenger() && !GetSound(eSID_Ambience)) { PlaySound(eSID_Ambience); } } // "fade" in run and ambience float fadeInRatio = min(1.f, (m_engineStartup-m_runSoundDelay)/RUNSOUND_FADEIN_TIME); m_rpmScale = fadeInRatio * ENGINESOUND_IDLE_RATIO; SetSoundParam(eSID_Run, "rpm_scale", m_rpmScale); SetSoundParam(eSID_Ambience, "speed", m_rpmScale); SetSoundParam(eSID_Ambience, "rpm_scale", m_rpmScale); if(m_pVehicle->IsPlayerPassenger()) if (gEnv->pInput) gEnv->pInput->ForceFeedbackEvent( SFFOutputEvent(eDI_XI, eFF_Rumble_Basic, 0.2f, 0.8f, 0.4f) ); } if (m_engineStartup >= m_engineIgnitionTime) { m_isEngineStarting = false; m_isEnginePowered = true; } } else if (m_isEngineGoingOff) { m_engineStartup -= deltaTime; m_rpmScale = max(0.f, m_rpmScale - ENGINESOUND_IDLE_RATIO/RUNSOUND_FADEOUT_TIME*deltaTime); if (m_rpmScale <= ENGINESOUND_IDLE_RATIO && !GetSound(eSID_Stop)) { // start stop sound and stop start sound, for now without fading StopSound(eSID_Start); PlaySound(eSID_Stop, 0.f, m_enginePos); } // handle run sound if (m_rpmScale <= 0.f) { StopSound(eSID_Ambience); StopSound(eSID_Run); StopSound(eSID_Damage); } else { SetSoundParam(eSID_Run, "rpm_scale", m_rpmScale); } if (m_engineStartup <= 0.0f && m_rpmScale <= 0.f) { m_isEngineGoingOff = false; m_isEnginePowered = false; OnEngineCompletelyStopped(); } m_pVehicle->NeedsUpdate(); } else if (m_isEnginePowered) { if (gEnv->bClient) { if (!GetSound(eSID_Run)) PlaySound(eSID_Run, 0.f, m_enginePos); UpdateRunSound(deltaTime); if(m_pVehicle->IsPlayerPassenger()) if (gEnv->pInput) gEnv->pInput->ForceFeedbackEvent( SFFOutputEvent(eDI_XI, eFF_Rumble_Basic, 0.15f, 0.01f, clamp_tpl(m_rpmScale, 0.0f, 0.5f))); } } m_soundStats.inout = 1.f; if (firstperson) { if (IVehicleSeat* pSeat = m_pVehicle->GetSeatForPassenger(pClientActor->GetEntityId())) m_soundStats.inout = pSeat->GetSoundParams().inout; } SetSoundParam(eSID_Run, "in_out", m_soundStats.inout); SetSoundParam(eSID_Ambience, "thirdperson", 1.f-firstperson); UpdateGameTokens(deltaTime); } //------------------------------------------------------------------------ void CVehicleMovementBase::UpdateRunSound(const float deltaTime) { float radius = 200.0f; ISound* pEngineSound = GetSound(eSID_Run); if (pEngineSound) radius = MAX(radius, pEngineSound->GetMaxDistance()); // not needed... ambient sound is much quieter than the engine sound; code is here for reference // ISound* pAmbientSound = GetSound(eSID_Ambience); // if (pAmbientSound) // radius = std::max(radius, pAmbientSound->GetMaxDistance()); if (IActor * pActor = g_pGame->GetIGameFramework()->GetClientActor()) { // 1.1f is a small safety factor to get sound params updated before they're heard if (pActor->GetEntity()->GetWorldPos().GetDistance( m_pVehicle->GetEntity()->GetWorldPos() ) > radius*1.1f) return; } float soundSpeedRatio = ENGINESOUND_IDLE_RATIO + (1.f-ENGINESOUND_IDLE_RATIO) * m_speedRatio; SetSoundParam(eSID_Run, "speed", soundSpeedRatio); SetSoundParam(eSID_Ambience, "speed", soundSpeedRatio); float damage = GetSoundDamage(); if (damage > 0.1f) { if (ISound* pSound = GetOrPlaySound(eSID_Damage, 5.f, m_enginePos)) SetSoundParam(pSound, "damage", damage); } //SetSoundParam(eSID_Run, "boost", Boosting() ? 1.f : 0.f); if (m_rpmPitchSpeed>0.f) { // pitch rpm with pedal float delta = GetEnginePedal() - m_rpmScaleSgn; m_rpmScaleSgn = max(-1.f, min(1.f, m_rpmScaleSgn + sgn(delta)*min(abs(delta), m_rpmPitchSpeed*deltaTime))); // skip transition around 0 when on pedal if (GetEnginePedal() != 0.f && delta != 0.f && sgn(m_rpmScaleSgn) != sgn(delta) && abs(m_rpmScaleSgn) <= 0.3f) m_rpmScaleSgn = sgn(delta)*0.3f; m_rpmScale = max(ENGINESOUND_IDLE_RATIO, abs(m_rpmScaleSgn)); SetSoundParam(eSID_Run, "rpm_scale", m_rpmScale); SetSoundParam(eSID_Ambience, "rpm_scale", m_rpmScale); } } //------------------------------------------------------------------------ void CVehicleMovementBase::UpdateGameTokens(const float deltaTime) { if(m_pVehicle->IsPlayerDriving(true)||m_pVehicle->IsPlayerPassenger()) { m_pGameTokenSystem->SetOrCreateToken("vehicle.speedNorm", TFlowInputData(m_speedRatioUnit, true)); } } //------------------------------------------------------------------------ void CVehicleMovementBase::UpdateDamage(const float deltaTime) { const SVehicleStatus& status = m_pVehicle->GetStatus(); const SVehicleDamageParams& damageParams = m_pVehicle->GetDamageParams(); if (status.submergedRatio > damageParams.submergedRatioMax) { if (m_damage < 1.f) { SetDamage(m_damage + deltaTime*damageParams.submergedDamageMult, true); if(m_pVehicle) { IVehicleComponent* pEngine = m_pVehicle->GetComponent("Engine"); if(!pEngine) pEngine = m_pVehicle->GetComponent("engine"); if(pEngine) { pEngine->SetDamageRatio(m_damage); // also send a zero damage event, to ensure things like the HUD update correctly SVehicleEventParams params; m_pVehicle->BroadcastVehicleEvent(eVE_Damaged, params); } } } } } //------------------------------------------------------------------------ void CVehicleMovementBase::SetDamage(float damage, bool fatal) { if (m_damage == 1.f) return; m_damage = min(1.f, max(m_damage, damage)); if (m_damage == 1.f && fatal) { if (m_isEnginePowered || m_isEngineStarting) OnEngineCompletelyStopped(); m_isEngineDisabled = true; m_isEnginePowered = false; m_isEngineStarting = false; m_isEngineGoingOff = false; m_movementAction.Clear(); StopExhaust(); StopSounds(); } } //------------------------------------------------------------------------ float CVehicleMovementBase::GetSoundDamage() { float damage = 0.f; for (TComponents::const_iterator it=m_damageComponents.begin(),end=m_damageComponents.end(); it!=end; ++it) damage = max(damage, (*it)->GetDamageRatio()); return damage; } //------------------------------------------------------------------------ void CVehicleMovementBase::OnSoundEvent(ESoundCallbackEvent event,ISound *pSound) { } //------------------------------------------------------------------------ bool CVehicleMovementBase::StartEngine(EntityId driverId) { if (m_isEngineDisabled || m_isEngineStarting) return false; if (/*m_damage >= 1.0f || */ m_pVehicle->IsDestroyed()) return false; m_actorId = driverId; m_movementAction.Clear(); m_movementAction.brake = false; if (IActor* pActor = m_pActorSystem->GetActor(m_actorId)) { if (pActor->IsPlayer() && m_playerTweaksId > -1) { if (m_movementTweaks.UseGroup(m_playerTweaksId)) OnValuesTweaked(); } else if (!pActor->IsPlayer() && m_aiTweaksId > -1) { if (m_movementTweaks.UseGroup(m_aiTweaksId)) OnValuesTweaked(); } } if (gEnv->bMultiplayer && m_multiplayerTweaksId > -1) { if (m_movementTweaks.UseGroup(m_multiplayerTweaksId)) OnValuesTweaked(); } // WarmupEngine relies on this being done here! if (m_isEnginePowered && !m_isEngineGoingOff) { StartExhaust(false, false); if (m_pVehicle->IsPlayerPassenger()) GetOrPlaySound(eSID_Ambience); if (!m_isEngineGoingOff) return true; } m_isEngineGoingOff = false; m_isEngineStarting = true; m_engineStartup = 0.0f; m_rpmScale = 0.f; m_engineIgnitionTime = m_runSoundDelay + RUNSOUND_FADEIN_TIME; StopSound(eSID_Run); StopSound(eSID_Ambience); StopSound(eSID_Damage); StopSound(eSID_Stop); PlaySound(eSID_Start, 0.f, m_enginePos); StartExhaust(); StartAnimation(eVMA_Engine); InitWind(); m_pVehicle->GetGameObject()->EnableUpdateSlot(m_pVehicle, IVehicle::eVUS_EnginePowered); return true; } //------------------------------------------------------------------------ void CVehicleMovementBase::StopEngine() { m_actorId = 0; if (m_isEngineGoingOff || !m_isEngineStarting && !m_isEnginePowered) return; if (!m_isEngineStarting) m_engineStartup = m_engineIgnitionTime; m_isEngineStarting = false; m_isEngineGoingOff = true; m_movementAction.Clear(); m_movementAction.brake = true; m_pGameTokenSystem->SetOrCreateToken("vehicle.speedNorm", TFlowInputData(0.f, true)); if (m_movementTweaks.RevertValues()) OnValuesTweaked(); } //------------------------------------------------------------------------ void CVehicleMovementBase::OnEngineCompletelyStopped() { m_pVehicle->GetGameObject()->DisableUpdateSlot(m_pVehicle, IVehicle::eVUS_EnginePowered); SVehicleEventParams params; m_pVehicle->BroadcastVehicleEvent(eVE_EngineStopped, params); StopExhaust(); StopAnimation(eVMA_Engine); } //------------------------------------------------------------------------ void CVehicleMovementBase::DisableEngine(bool disable) { if (disable == m_isEngineDisabled) return; if (disable) { if (m_isEnginePowered || m_isEngineStarting) StopEngine(); m_isEngineDisabled = true; } else { m_isEngineDisabled = false; IVehicleSeat* pSeat = m_pVehicle->GetSeatById(1); if (pSeat && pSeat->GetPassenger() && pSeat->GetCurrentTransition()==IVehicleSeat::eVT_None) StartEngine(pSeat->GetPassenger()); } } //------------------------------------------------------------------------ void CVehicleMovementBase::OnAction(const TVehicleActionId actionId, int activationMode, float value) { if (actionId == eVAI_RotatePitch) m_movementAction.rotatePitch = value; else if (actionId == eVAI_RotateYaw) m_movementAction.rotateRoll = value; else if (actionId == eVAI_MoveForward) m_movementAction.power = value; else if (actionId == eVAI_MoveBack) m_movementAction.power = -value; else if (actionId == eVAI_TurnLeft) m_movementAction.rotateYaw = -value; else if (actionId == eVAI_TurnRight) m_movementAction.rotateYaw = value; else if (actionId == eVAI_Brake) m_movementAction.brake = (value > 0.0f); else if (actionId == eVAI_Boost) { if (!Boosting() && activationMode == eAAM_OnPress) Boost(true); else if (activationMode == eAAM_OnRelease) Boost(false); } if(g_pGameCVars->goc_enable) { /* Matrix34 camMat = gEnv->pRenderer->GetCamera().GetMatrix(); Vec3 viewDir = gEnv->pRenderer->GetCamera().GetViewdir(); Matrix34 vehicleMat = m_pVehicle->GetEntity()->GetWorldTM(); Vec3 vehicleDir = vehicleMat.GetColumn1(); float s = 1.0f; if (vehicleDir.Dot(camMat.GetColumn0())>0.0f) s = -1.0f; s*=m_movementAction.power; // get angle difference viewDir.z = 0; viewDir.Normalize(); vehicleDir.z = 0; vehicleDir.Normalize(); float amount = viewDir.Dot(vehicleDir); float minAngle = 0.9999f; float maxAngle = 0.0f; if (amount > minAngle) { m_movementAction.rotateYaw = 0.0f; } else { if (amount > maxAngle) { // soft range float scale = 1.0f - (amount - maxAngle)/(minAngle - maxAngle); m_movementAction.rotateYaw = s * scale; } else { m_movementAction.rotateYaw = s; } } */ } } //------------------------------------------------------------------------ void CVehicleMovementBase::ResetBoost() { Boost(false); m_boostCounter = 1.f; } //------------------------------------------------------------------------ void CVehicleMovementBase::Boost(bool enable) { if ((enable == m_boost && m_pVehicle && m_pVehicle->IsPlayerDriving(true)) || m_boostEndurance == 0.f) return; if (enable) { if (m_boostCounter < 0.25f || m_movementAction.power < -0.001f /*|| m_damage == 1.f*/) return; if ((m_statusDyn.submergedFraction > 0.75f) && (GetMovementType()!=IVehicleMovement::eVMT_Amphibious)) return; // can't boost if underwater and not amphibious } if (m_playerBoostTweaksId != -1) { bool tweaked = false; if (enable) tweaked = m_movementTweaks.UseGroup(m_playerBoostTweaksId); else tweaked = m_movementTweaks.RevertGroup(m_playerBoostTweaksId); if (tweaked) OnValuesTweaked(); } // NB: m_pPaParams *can* be null here (amphibious apc has two VehicleMovement objects and one isn't // initialised fully the first time we get here) if(m_pPaParams) { const char* boostEffect = m_pPaParams->GetExhaustParams()->GetBoostEffect(); if (IParticleEffect* pBoostEffect = gEnv->p3DEngine->FindParticleEffect(boostEffect)) { SEntitySlotInfo slotInfo; for (std::vector<SExhaustStatus>::iterator it=m_paStats.exhaustStats.begin(), end=m_paStats.exhaustStats.end(); it!=end; ++it) { if (enable) { it->boostSlot = m_pEntity->LoadParticleEmitter(it->boostSlot, pBoostEffect); if (m_pEntity->GetSlotInfo(it->boostSlot, slotInfo) && slotInfo.pParticleEmitter) { const Matrix34& tm = it->pHelper->GetVehicleTM(); m_pEntity->SetSlotLocalTM(it->boostSlot, tm); } } else { if (m_pEntity->GetSlotInfo(it->boostSlot, slotInfo) && slotInfo.pParticleEmitter) slotInfo.pParticleEmitter->Activate(false); FreeEmitterSlot(it->boostSlot); } } } } if (enable) PlaySound(eSID_Boost, 2.f, m_enginePos); m_boost = enable; } //------------------------------------------------------------------------ void CVehicleMovementBase::ApplyAirDamp(float angleMin, float angVelMin, float deltaTime, int threadSafe) { // This function need to be MT safe, called StdWeeled and Tank Hovercraft // flight stabilization, correct deviation from neutral orientation if (m_movementAction.isAI || m_PhysDyn.submergedFraction>0.01f || m_dampAngle.IsZero()) return; Matrix34 worldTM( m_PhysPos.q ); worldTM.AddTranslation( m_PhysPos.pos ); if (worldTM.GetColumn2().z < -0.05f) return; Ang3 angles(worldTM); Vec3 localW = worldTM.GetInverted().TransformVector(m_PhysDyn.w); Vec3 correction(ZERO); for (int i=0; i<3; ++i) { // angle correction if (i != 2) { bool increasing = sgn(localW[i])==sgn(angles[i]); if ((increasing || abs(angles[i]) > angleMin) && abs(angles[i]) < 0.45f*gf_PI) correction[i] += m_dampAngle[i] * -angles[i]; } // angular velocity if (abs(localW[i]) > angVelMin) correction[i] += m_dampAngVel[i] * -localW[i]; correction[i] *= m_PhysDyn.mass * deltaTime; } if (!correction.IsZero()) { // not thread-safe //if (IsProfilingMovement()) //{ // float color[] = {1,1,1,1}; // gEnv->pRenderer->Draw2dLabel(300,500,1.4f,color,false,"corr: %.1f, %.1f", correction.x, correction.y); //} pe_action_impulse imp; imp.angImpulse = worldTM.TransformVector(correction); GetPhysics()->Action(&imp, threadSafe); } } //------------------------------------------------------------------------ void CVehicleMovementBase::UpdateGravity(float grav) { // set increased freefall gravity when airborne // this needs to be set per-frame (otherwise one needs to set ignore_areas) // and from the immediate callback only pe_simulation_params params; if (GetPhysics()->GetParams(&params)) { pe_simulation_params paramsSet; paramsSet.gravityFreefall = params.gravityFreefall; paramsSet.gravityFreefall.z = min(paramsSet.gravityFreefall.z, grav); GetPhysics()->SetParams(&paramsSet, 1); } } //------------------------------------------------------------------------ void CVehicleMovementBase::UpdateBoost(const float deltaTime) { if (m_boost) { m_boostCounter = max(0.f, m_boostCounter - deltaTime/m_boostEndurance); if (m_boostCounter == 0.f || m_movementAction.power < -0.001f) Boost(false); } else { if (m_boostRegen != 0.f) m_boostCounter = min(1.f, m_boostCounter + deltaTime/m_boostRegen); } } //------------------------------------------------------------------------ void CVehicleMovementBase::OnEvent(EVehicleMovementEvent event, const SVehicleMovementEventParams& params) { if (event == eVME_Damage) { if (m_damage < 1.f && params.fValue > m_damage) SetDamage(params.fValue, params.bValue); } else if (eVME_Freeze == event) { if (params.fValue>0.0f) { DisableEngine(true); } else DisableEngine(false); } else if (event == eVME_Repair) { m_damage = max(0.f, min(params.fValue, m_damage)); if(m_damage < 1.0f) m_isEngineDisabled = false; } else if (event == eVME_PlayerEnterLeaveVehicle) { if (params.bValue) { if (!GetSound(eSID_Ambience) && (m_isEnginePowered||m_isEngineStarting)) { PlaySound(eSID_Ambience); // fade in ambience with rpmscale SetSoundParam(eSID_Ambience, "rpm_scale", m_rpmScale); } } else { StopSound(eSID_Ambience); } } else if (event == eVME_WarmUpEngine) { if (/*m_damage == 1.f || */m_pVehicle->IsDestroyed()) return; StopSound(eSID_Start); // This Update is called to get the Run sound starting, but this should // eventually be achieved in a nicer way m_isEnginePowered = true; m_engineStartup = 0.0f; m_isEngineStarting = false; GetOrPlaySound(eSID_Run, 0.f, m_enginePos); if (m_pVehicle->IsPlayerPassenger()) GetOrPlaySound(eSID_Ambience); StartExhaust(); StartAnimation(eVMA_Engine); m_pVehicle->GetGameObject()->EnableUpdateSlot(m_pVehicle, IVehicle::eVUS_EnginePowered); } else if (event == eVME_ToggleEngineUpdate) { if (!params.bValue && !IsPowered()) RemoveSurfaceEffects(); } } //------------------------------------------------------------------------ void CVehicleMovementBase::OnVehicleEvent(EVehicleEvent event, const SVehicleEventParams& params) { } //------------------------------------------------------------------------ tSoundID CVehicleMovementBase::GetSoundId(EVehicleMovementSound eSID) { if (eSID<0 || eSID>=eSID_Max) return INVALID_SOUNDID; return m_soundStats.sounds[eSID]; } //------------------------------------------------------------------------ ISound* CVehicleMovementBase::GetSound(EVehicleMovementSound eSID) { assert(eSID>=0 && eSID<eSID_Max); if (m_soundStats.sounds[eSID] == INVALID_SOUNDID) return 0; return m_pEntitySoundsProxy->GetSound(m_soundStats.sounds[eSID]); } //------------------------------------------------------------------------ void CVehicleMovementBase::StopSounds() { m_surfaceSoundStats.Reset(); for (int i=0; i<eSID_Max; ++i) { StopSound((EVehicleMovementSound)i); } } //------------------------------------------------------------------------ void CVehicleMovementBase::StopSound(EVehicleMovementSound eSID) { assert(eSID>=0 && eSID<eSID_Max); if (m_soundStats.sounds[eSID] != INVALID_SOUNDID) { m_pEntitySoundsProxy->StopSound(m_soundStats.sounds[eSID]); m_soundStats.sounds[eSID] = INVALID_SOUNDID; } } //------------------------------------------------------------------------ ISound* CVehicleMovementBase::PlaySound(EVehicleMovementSound eSID, float pulse, const Vec3& offset, int soundFlags) { assert(eSID>=0 && eSID<eSID_Max); // verify - make all vehicle sound use obstruction and culling uint32 nSoundFlags = soundFlags | FLAG_SOUND_DEFAULT_3D; CTimeValue currTime = gEnv->pTimer->GetFrameStartTime(); if ((currTime - m_soundStats.lastPlayed[eSID]).GetSeconds() >= pulse) { const string& soundName = GetSoundName(eSID); if (!soundName.empty()) m_soundStats.sounds[eSID] = m_pEntitySoundsProxy->PlaySound(soundName.c_str(), offset, Vec3Constants<float>::fVec3_OneY, nSoundFlags, eSoundSemantic_Vehicle); m_soundStats.lastPlayed[eSID] = currTime; if (g_pGameCVars->v_debugSounds && !soundName.empty()) CryLog("[%s] playing sound %s", m_pVehicle->GetEntity()->GetName(), soundName.c_str()); } ISound* pSound = GetSound(eSID); if (pSound) pSound->SetVolume(m_soundMasterVolume); return pSound; } //------------------------------------------------------------------------ ISound* CVehicleMovementBase::GetOrPlaySound(EVehicleMovementSound eSID, float pulse, const Vec3& offset, int soundFlags) { assert(eSID>=0 && eSID<eSID_Max); if (ISound* pSound = GetSound(eSID)) { if (pSound->IsPlaying()) return pSound; } return PlaySound(eSID, pulse, offset, soundFlags); } //------------------------------------------------------------------------ void CVehicleMovementBase::SetSoundMasterVolume(float vol) { if (vol == m_soundMasterVolume) return; m_soundMasterVolume = max(0.f, min(1.f, vol)); for (int i=0; i<eSID_Max; ++i) { if (ISound* pSound = GetSound((EVehicleMovementSound)i)) pSound->SetVolume(vol); } } //------------------------------------------------------------------------ void CVehicleMovementBase::StartExhaust(bool ignition/*=true*/, bool reload/*=true*/) { if(!m_pPaParams) return; SExhaustParams* exParams = m_pPaParams->GetExhaustParams(); if (!exParams->hasExhaust) return; // start effect if (ignition) { if (IParticleEffect* pEff = gEnv->p3DEngine->FindParticleEffect(exParams->GetStartEffect())) { for (std::vector<SExhaustStatus>::iterator it = m_paStats.exhaustStats.begin(); it != m_paStats.exhaustStats.end(); ++it) { if (GetWaterMod(*it)) { it->startStopSlot = m_pEntity->LoadParticleEmitter(it->startStopSlot, pEff); m_pEntity->SetSlotLocalTM(it->startStopSlot, it->pHelper->GetVehicleTM()); } } } } // load emitters for exhaust running effect if (IParticleEffect* pRunEffect = gEnv->p3DEngine->FindParticleEffect(exParams->GetRunEffect())) { SEntitySlotInfo slotInfo; SpawnParams spawnParams; spawnParams.fSizeScale = exParams->runBaseSizeScale; for (std::vector<SExhaustStatus>::iterator it = m_paStats.exhaustStats.begin(); it != m_paStats.exhaustStats.end(); ++it) { if (reload || it->runSlot == -1 || !m_pEntity->IsSlotValid(it->runSlot)) it->runSlot = m_pEntity->LoadParticleEmitter(it->runSlot, pRunEffect); if (m_pEntity->GetSlotInfo(it->runSlot, slotInfo) && slotInfo.pParticleEmitter) { const Matrix34& tm = it->pHelper->GetVehicleTM(); m_pEntity->SetSlotLocalTM(it->runSlot, tm); slotInfo.pParticleEmitter->SetSpawnParams(spawnParams); } } } } //------------------------------------------------------------------------ void CVehicleMovementBase::FreeEmitterSlot(int& slot) { if (slot > -1) { //CryLogAlways("[VehicleMovement]: Freeing slot %i", slot); m_pEntity->FreeSlot(slot); slot = -1; } } //------------------------------------------------------------------------ void CVehicleMovementBase::FreeEmitterSlot(const int& slot) { if (slot > -1) m_pEntity->FreeSlot(slot); } //------------------------------------------------------------------------ void CVehicleMovementBase::StopExhaust() { if(!m_pPaParams) return; SExhaustParams* exParams = m_pPaParams->GetExhaustParams(); if (!exParams->hasExhaust) return; for (std::vector<SExhaustStatus>::iterator it = m_paStats.exhaustStats.begin(); it != m_paStats.exhaustStats.end(); ++it) { FreeEmitterSlot(it->boostSlot); FreeEmitterSlot(it->runSlot); FreeEmitterSlot(it->startStopSlot); } // trigger stop effect if available if (0 != exParams->GetStopEffect()[0] && !m_pVehicle->IsDestroyed() /*&& m_damage < 1.f*/) { IParticleEffect* pEff = gEnv->p3DEngine->FindParticleEffect(exParams->GetStopEffect()); if (pEff) { for (std::vector<SExhaustStatus>::iterator it = m_paStats.exhaustStats.begin(); it != m_paStats.exhaustStats.end(); ++it) { if (GetWaterMod(*it)) { it->startStopSlot = m_pEntity->LoadParticleEmitter(it->startStopSlot, pEff); m_pEntity->SetSlotLocalTM(it->startStopSlot, it->pHelper->GetVehicleTM()); //CryLogAlways("[VehicleMovement::StopExhaust]: Loaded to slot %i..", it->startStopSlot); } } } } } //------------------------------------------------------------------------ void CVehicleMovementBase::ResetParticles() { // exhausts for (std::vector<SExhaustStatus>::iterator it = m_paStats.exhaustStats.begin(); it != m_paStats.exhaustStats.end(); ++it) { FreeEmitterSlot(it->startStopSlot); FreeEmitterSlot(it->runSlot); FreeEmitterSlot(it->boostSlot); it->enabled = 1; } RemoveSurfaceEffects(); if(m_pPaParams) { SEnvironmentParticles* pEnvParams = m_pPaParams->GetEnvironmentParticles(); SEnvParticleStatus::TEnvEmitters::iterator end = m_paStats.envStats.emitters.end(); for (SEnvParticleStatus::TEnvEmitters::iterator it=m_paStats.envStats.emitters.begin(); it!=end; ++it) { //FreeEmitterSlot(it->slot); if (it->group >= 0) { const SEnvironmentLayer& layer = pEnvParams->GetLayer(it->layer); it->active = layer.IsGroupActive(it->group); } } } //m_paStats.envStats.emitters.clear(); //m_paStats.envStats.initalized = false; } //------------------------------------------------------------------------ void CVehicleMovementBase::RemoveSurfaceEffects() { for (SEnvParticleStatus::TEnvEmitters::iterator it=m_paStats.envStats.emitters.begin(); it!=m_paStats.envStats.emitters.end(); ++it) EnableEnvEmitter(*it, false); } //------------------------------------------------------------------------ void CVehicleMovementBase::EnableEnvEmitter(TEnvEmitter& emitter, bool enable) { if (!enable) { if (emitter.slot > -1) { SEntitySlotInfo info; info.pParticleEmitter = 0; if (m_pEntity->GetSlotInfo(emitter.slot, info) && info.pParticleEmitter) { SpawnParams sp; sp.fCountScale = 0.f; info.pParticleEmitter->SetSpawnParams(sp); } } if (emitter.pGroundEffect) emitter.pGroundEffect->Stop(true); } } //------------------------------------------------------------------------ void CVehicleMovementBase::UpdateExhaust(const float deltaTime) { FUNCTION_PROFILER( GetISystem(), PROFILE_GAME ); if (!m_pVehicle->GetGameObject()->IsProbablyVisible() || m_pVehicle->GetGameObject()->IsProbablyDistant()) return; if(!m_pPaParams) return; SExhaustParams* exParams = m_pPaParams->GetExhaustParams(); if (exParams->hasExhaust && m_paStats.exhaustStats[0].runSlot > -1) { SEntitySlotInfo info; SpawnParams sp; float countScale = 1; float sizeScale = 1; float speedScale = 1; float vel = m_statusDyn.v.GetLength(); float absPower = abs(GetEnginePedal()); // disable running exhaust if requirements aren't met if (vel < exParams->runMinSpeed || absPower < exParams->runMinPower || absPower > exParams->runMaxPower) { countScale = 0; } else { // scale with engine power float powerDiff = max(0.f, exParams->runMaxPower - exParams->runMinPower); if (powerDiff) { float powerNorm = CLAMP(absPower, exParams->runMinPower, exParams->runMaxPower) / powerDiff; float countDiff = max(0.f, exParams->runMaxPowerCountScale - exParams->runMinPowerCountScale); if (countDiff) countScale *= (powerNorm * countDiff) + exParams->runMinPowerCountScale; float sizeDiff = max(0.f, exParams->runMaxPowerSizeScale - exParams->runMinPowerSizeScale); if (sizeDiff) sizeScale *= (powerNorm * sizeDiff) + exParams->runMinPowerSizeScale; float emitterSpeedDiff = max(0.f, exParams->runMaxPowerSpeedScale - exParams->runMinPowerSpeedScale); if(emitterSpeedDiff) speedScale *= (powerNorm * emitterSpeedDiff) + exParams->runMinPowerSpeedScale; } // scale with vehicle speed float speedDiff = max(0.f, exParams->runMaxSpeed - exParams->runMinSpeed); if (speedDiff) { float speedNorm = CLAMP(vel, exParams->runMinSpeed, exParams->runMaxSpeed) / speedDiff; float countDiff = max(0.f, exParams->runMaxSpeedCountScale - exParams->runMinSpeedCountScale); if (countDiff) countScale *= (speedNorm * countDiff) + exParams->runMinSpeedCountScale; float sizeDiff = max(0.f, exParams->runMaxSpeedSizeScale - exParams->runMinSpeedSizeScale); if (sizeDiff) sizeScale *= (speedNorm * sizeDiff) + exParams->runMinSpeedSizeScale; float emitterSpeedDiff = max(0.f, exParams->runMaxSpeedSpeedScale - exParams->runMinSpeedSpeedScale); if(emitterSpeedDiff) speedScale *= (speedNorm * emitterSpeedDiff) + exParams->runMinSpeedSpeedScale; } } sp.fSizeScale = sizeScale; sp.fSpeedScale = speedScale; if (exParams->disableWithNegativePower && GetEnginePedal() < 0.0f) { sp.fSizeScale *= 0.35f; } for (std::vector<SExhaustStatus>::iterator it = m_paStats.exhaustStats.begin(); it != m_paStats.exhaustStats.end(); ++it) { sp.fCountScale = (float)it->enabled * countScale * GetWaterMod(*it); const Matrix34& slotTM = it->pHelper->GetVehicleTM(); if (m_pEntity->GetSlotInfo(it->runSlot, info) && info.pParticleEmitter) { m_pVehicle->GetEntity()->SetSlotLocalTM(it->runSlot, slotTM); info.pParticleEmitter->SetSpawnParams(sp); } if (Boosting() && m_pEntity->GetSlotInfo(it->boostSlot, info) && info.pParticleEmitter) { m_pVehicle->GetEntity()->SetSlotLocalTM(it->boostSlot, slotTM); info.pParticleEmitter->SetSpawnParams(sp); } } if (DebugParticles()) { IRenderer* pRenderer = gEnv->pRenderer; float color[4] = {1,1,1,1}; float x = 200.f; pRenderer->Draw2dLabel(x, 80.0f, 1.5f, color, false, "Exhaust:"); pRenderer->Draw2dLabel(x, 105.0f, 1.5f, color, false, "countScale: %.2f", sp.fCountScale); pRenderer->Draw2dLabel(x, 120.0f, 1.5f, color, false, "sizeScale: %.2f", sp.fSizeScale); pRenderer->Draw2dLabel(x, 135.0f, 1.5f, color, false, "speedScale: %.2f", sp.fSpeedScale); } } } //------------------------------------------------------------------------ float CVehicleMovementBase::GetWaterMod(SExhaustStatus& exStatus) { // check water flag Vec3 vPos = exStatus.pHelper->GetWorldTM().GetTranslation(); //bool inWater = gEnv->p3DEngine->GetWaterLevel( &vPos ) > vPos.z; const SVehicleStatus& status = m_pVehicle->GetStatus(); bool inWater = status.submergedRatio > 0.05f; if ((inWater && !m_pPaParams->GetExhaustParams()->insideWater) || (!inWater && !m_pPaParams->GetExhaustParams()->outsideWater)) return 0; return 1; } //------------------------------------------------------------------------ void CVehicleMovementBase::RegisterActionFilter(IVehicleMovementActionFilter* pActionFilter) { if (pActionFilter) m_actionFilters.push_back(pActionFilter); } //------------------------------------------------------------------------ void CVehicleMovementBase::UnregisterActionFilter(IVehicleMovementActionFilter* pActionFilter) { if (pActionFilter) m_actionFilters.remove(pActionFilter); } //------------------------------------------------------------------------ void CVehicleMovementBase::GetMovementState(SMovementState& movementState) { movementState.minSpeed = 0.0f; movementState.normalSpeed = 15.0f; movementState.maxSpeed = 30.0f; } //------------------------------------------------------------------------ bool CVehicleMovementBase::GetStanceState(EStance stance, float lean, bool defaultPose, SStanceState& state) { return false; } //------------------------------------------------------------------------ bool CVehicleMovementBase::IsProfilingMovement() { if (!m_pVehicle || !m_pVehicle->GetEntity()) return false; static ICVar* pDebugVehicle = gEnv->pConsole->GetCVar("v_debugVehicle"); if (g_pGameCVars->v_profileMovement && (m_pVehicle->IsPlayerDriving() || 0 == strcmpi(pDebugVehicle->GetString(), m_pVehicle->GetEntity()->GetName()))) return true; return false; } //------------------------------------------------------------------------ SMFXResourceListPtr CVehicleMovementBase::GetEffectNode(int matId) { if (matId <= 0) return 0; IMaterialEffects *mfx = g_pGame->GetIGameFramework()->GetIMaterialEffects(); // maybe cache this CryFixedStringT<256> effCol = "vfx_"; effCol += m_pEntity->GetClass()->GetName(); TMFXEffectId effectId = mfx->GetEffectId(effCol.MakeLower().c_str(), matId); if (effectId != InvalidEffectId) { return mfx->GetResources(effectId); } else { if (DebugParticles()) CryLog("GetEffectString for %s -> %i failed", effCol.c_str(), matId); } return 0; } //------------------------------------------------------------------------ const char* CVehicleMovementBase::GetEffectByIndex(int matId, const char* username) { SMFXResourceListPtr pResourceList = GetEffectNode(matId); if (!pResourceList.get()) return 0; SMFXParticleListNode* pList = pResourceList->m_particleList; while (pList && 0 != strcmp(pList->m_particleParams.userdata, username)) pList = pList->pNext; if (pList) return pList->m_particleParams.name; return 0; } //------------------------------------------------------------------------ float CVehicleMovementBase::GetSurfaceSoundParam(int matId) { SMFXResourceListPtr pResourceList = GetEffectNode(matId); if (pResourceList.get() && pResourceList->m_soundList) { const char* soundType = pResourceList->m_soundList->m_soundParams.name; if (soundType[0]) { TSurfaceSoundInfo::const_iterator it=m_surfaceSoundInfo.find(CONST_TEMP_STRING(soundType)); if (it != m_surfaceSoundInfo.end()) { // param = index/10 return 0.1f * it->second.paramIndex; } } } return 0.f; } //------------------------------------------------------------------------ void CVehicleMovementBase::InitSurfaceEffects() { m_paStats.envStats.emitters.clear(); if(!m_pPaParams) return; SEnvironmentParticles* envParams = m_pPaParams->GetEnvironmentParticles(); for (int iLayer=0; iLayer<envParams->GetLayerCount(); ++iLayer) { const SEnvironmentLayer& layer = envParams->GetLayer(iLayer); int cnt = layer.GetHelperCount(); if (layer.alignGroundHeight>0 || layer.alignToWater) cnt = max(1, cnt); m_paStats.envStats.emitters.reserve( m_paStats.envStats.emitters.size() + cnt); for (int i=0; i<cnt; ++i) { TEnvEmitter emitter; emitter.layer = iLayer; if (layer.alignGroundHeight>0) { // create ground effect if height specified IGroundEffect* pGroundEffect = g_pGame->GetIGameFramework()->GetIEffectSystem()->CreateGroundEffect(m_pEntity); if (pGroundEffect) { pGroundEffect->SetHeight(layer.alignGroundHeight); pGroundEffect->SetHeightScale(layer.maxHeightSizeScale, layer.maxHeightCountScale); pGroundEffect->SetFlags(pGroundEffect->GetFlags() | IGroundEffect::eGEF_StickOnGround); string interaction("vfx_"); interaction.append(m_pEntity->GetClass()->GetName()).MakeLower(); pGroundEffect->SetInteraction(interaction.c_str()); emitter.pGroundEffect = pGroundEffect; m_paStats.envStats.emitters.push_back(emitter); if (DebugParticles()) CryLog("<%s> Ground effect loaded with height %f", m_pVehicle->GetEntity()->GetName(), layer.alignGroundHeight); } } else if (layer.alignToWater) { // else load emitter in slot Matrix34 tm(IDENTITY); if (layer.GetHelperCount()>i) { if (IVehicleHelper* pHelper = layer.GetHelper(i)) tm = pHelper->GetVehicleTM(); } emitter.slot = -1; emitter.quatT = QuatT(tm); m_paStats.envStats.emitters.push_back(emitter); if (DebugParticles()) { const Vec3 loc = tm.GetTranslation(); CryLog("<%s> water-aligned emitter %i, local pos: %.1f %.1f %.1f", m_pVehicle->GetEntity()->GetName(), i, loc.x, loc.y, loc.z); } } } } m_paStats.envStats.initalized = true; } //------------------------------------------------------------------------ void CVehicleMovementBase::GetParticleScale(const SEnvironmentLayer& layer, float speed, float power, float& countScale, float& sizeScale, float& speedScale) { if (speed < layer.minSpeed) { countScale = 0.f; return; } float speedDiff = max(0.f, layer.maxSpeed - layer.minSpeed); if (speedDiff) { float speedNorm = CLAMP(speed, layer.minSpeed, layer.maxSpeed) / speedDiff; float countDiff = max(0.f, layer.maxSpeedCountScale - layer.minSpeedCountScale); countScale *= (speedNorm * countDiff) + layer.minSpeedCountScale; float sizeDiff = max(0.f, layer.maxSpeedSizeScale - layer.minSpeedSizeScale); sizeScale *= (speedNorm * sizeDiff) + layer.minSpeedSizeScale; float emitterSpeedDiff = max(0.f, layer.maxSpeedSpeedScale - layer.minSpeedSpeedScale); speedScale *= (speedNorm * emitterSpeedDiff) + layer.minSpeedSpeedScale; } float countDiff = max(0.f, layer.maxPowerCountScale - layer.minPowerCountScale); countScale *= (power * countDiff) + layer.minPowerCountScale; float sizeDiff = max(0.f, layer.maxPowerSizeScale - layer.minPowerSizeScale); sizeScale *= (power * sizeDiff) + layer.minPowerSizeScale; float emitterSpeedDiff = max(0.f, layer.maxPowerSpeedScale - layer.minPowerSpeedScale); speedScale *= (power * emitterSpeedDiff) + layer.minPowerSpeedScale; } //------------------------------------------------------------------------ void CVehicleMovementBase::UpdateSurfaceEffects(const float deltaTime) { FUNCTION_PROFILER( GetISystem(), PROFILE_GAME ); if (0 == g_pGameCVars->v_pa_surface) { ResetParticles(); return; } const SVehicleStatus& status = m_pVehicle->GetStatus(); if (status.speed < 0.01f) return; float distSq = m_pVehicle->GetEntity()->GetWorldPos().GetSquaredDistance(gEnv->pRenderer->GetCamera().GetPosition()); if (distSq > sqr(300.f) || (distSq > sqr(50.f) && !m_pVehicle->GetGameObject()->IsProbablyVisible())) return; float powerNorm = CLAMP(abs(m_movementAction.power), 0.f, 1.f); SEnvironmentParticles* envParams = m_pPaParams->GetEnvironmentParticles(); SEnvParticleStatus::TEnvEmitters::iterator end = m_paStats.envStats.emitters.end(); for (SEnvParticleStatus::TEnvEmitters::iterator emitterIt = m_paStats.envStats.emitters.begin(); emitterIt!=end; ++emitterIt) { if (emitterIt->layer < 0) { assert(0); continue; } const SEnvironmentLayer& layer = envParams->GetLayer(emitterIt->layer); if (emitterIt->pGroundEffect) { float countScale = 1; float sizeScale = 1; float speedScale = 1; if (!(m_isEngineGoingOff || m_isEnginePowered)) { countScale = 0; } else { GetParticleScale(layer, status.speed, powerNorm, countScale, sizeScale, speedScale); } emitterIt->pGroundEffect->Stop(false); emitterIt->pGroundEffect->SetBaseScale(sizeScale, countScale, speedScale); emitterIt->pGroundEffect->Update(); } } } //------------------------------------------------------------------------ void CVehicleMovementBase::InitWind() { // disabled for now return; if(!GenerateWind()) return; if (!m_pWind[0]) { AABB bounds; m_pEntity->GetLocalBounds(bounds); primitives::box geomBox; geomBox.Basis.SetIdentity(); geomBox.bOriented = 0; geomBox.size = bounds.GetSize(); // doubles size of entity bbox geomBox.size.x *= 0.75f; geomBox.size.y = max(min(3.f, 0.5f*geomBox.size.y), 5.f); geomBox.size.z *= 0.75f; //geomBox.center.Set(0, -0.75f*geomBox.size.y, 0); // offset center to front geomBox.center.Set(0,0,0); IGeometry *pGeom1 = gEnv->pPhysicalWorld->GetGeomManager()->CreatePrimitive( primitives::box::type, &geomBox ); if (pGeom1) m_pWind[0] = gEnv->pPhysicalWorld->AddArea( pGeom1, m_pEntity->GetWorldPos(), m_pEntity->GetRotation(), 1.f); IGeometry *pGeom2 = gEnv->pPhysicalWorld->GetGeomManager()->CreatePrimitive( primitives::box::type, &geomBox ); if (pGeom2) m_pWind[1] = gEnv->pPhysicalWorld->AddArea( pGeom2, m_pEntity->GetWorldPos(), m_pEntity->GetRotation(), 1.f); } if (m_pWind[0]) { pe_params_area area; area.bUniform = 0; //area.falloff0 = 0.8f; m_pWind[0]->SetParams(&area); SetWind(Vec3(ZERO)); } } //------------------------------------------------------------------------ void CVehicleMovementBase::UpdateWind(const float deltaTime) { if (m_pVehicle->IsDestroyed()) return; if (!m_pWind[0]) return; if (m_statusDyn.v.len2() > sqr(WIND_MINSPEED) && m_pVehicle->GetGameObject()->IsProbablyVisible()) { Vec3 p1, p2; GetWindPos(p1, p2); pe_params_pos pos; pos.q = m_pEntity->GetWorldRotation(); pos.pos = p1; m_pWind[0]->SetParams(&pos); pos.pos = p2; m_pWind[1]->SetParams(&pos); } SetWind(m_statusDyn.v); } //------------------------------------------------------------------------ Vec3 CVehicleMovementBase::GetWindPos(Vec3& posRad, Vec3& posLin) { // wind area is shifted along -velocity by 2*distance from center to intersection with bounding box AABB bounds; m_pEntity->GetLocalBounds(bounds); Vec3 center = bounds.GetCenter(); Vec3 vlocal = m_pEntity->GetWorldRotation().GetInverted() * m_statusDyn.v; vlocal.NormalizeFast(); Ray ray; ray.origin = center - vlocal*(bounds.GetRadius()+0.1f); ray.direction = vlocal; Vec3 intersect; if (Intersect::Ray_AABB(ray, bounds, intersect)) { posRad = center + 1.5f*(intersect - center); posLin = posRad + 2.f*(intersect - center); if (IsProfilingMovement()) { IPersistantDebug* pDebug = g_pGame->GetIGameFramework()->GetIPersistantDebug(); pDebug->Begin("GetWindPos", false); pDebug->AddSphere(m_pEntity->GetWorldTM()*posRad, 0.25f, ColorF(0,1,0,0.8f), 0.1f); pDebug->AddSphere(m_pEntity->GetWorldTM()*posLin, 0.25f, ColorF(0.5,1,0,0.8f), 0.1f); } posRad = m_pEntity->GetWorldTM() * posRad; posLin = m_pEntity->GetWorldTM() * posLin; //return m_pEntity->GetWorldTM() * posRad; } return m_pEntity->GetWorldTM() * center; } //------------------------------------------------------------------------ void ClampWind(Vec3& wind) { float min = g_pGameCVars->v_wind_minspeed; float len2 = wind.len2(); if (len2 < min*min) wind.SetLength(min); else if (len2 <= WIND_MINSPEED*WIND_MINSPEED) wind.zero(); else if (len2 > WIND_MAXSPEED*WIND_MAXSPEED) wind *= WIND_MAXSPEED/wind.len(); } //------------------------------------------------------------------------ void CVehicleMovementBase::SetWind(const Vec3& wind) { pe_params_buoyancy buoy; buoy.iMedium = 1; buoy.waterDensity = buoy.waterResistance = 0; buoy.waterPlane.n.Set(0,0,-1); buoy.waterPlane.origin.Set(0,0,gEnv->p3DEngine->GetWaterLevel()); float min = g_pGameCVars->v_wind_minspeed; float radial = max(min, wind.len()); if (radial < WIND_MINSPEED) radial = 0.f; // radial wind buoy.waterFlow.Set(0,0,-radial); //ClampWind(buoy.waterFlow); m_pWind[0]->SetParams(&buoy); // linear wind buoy.waterFlow = 0.8f*wind; ClampWind(buoy.waterFlow); m_pWind[1]->SetParams(&buoy); } //------------------------------------------------------------------------ void CVehicleMovementBase::StartAnimation(EVehicleMovementAnimation eAnim) { IVehicleAnimation* pAnim = m_animations[eAnim]; if (pAnim) pAnim->StartAnimation(); } //------------------------------------------------------------------------ void CVehicleMovementBase::StopAnimation(EVehicleMovementAnimation eAnim) { IVehicleAnimation* pAnim = m_animations[eAnim]; if (pAnim) pAnim->StopAnimation(); } //------------------------------------------------------------------------ void CVehicleMovementBase::SetAnimationSpeed(EVehicleMovementAnimation eAnim, float speed) { IVehicleAnimation* pAnim = m_animations[eAnim]; if (pAnim) pAnim->SetSpeed(speed); } //------------------------------------------------------------------------ const string& CVehicleMovementBase::GetSoundName(EVehicleMovementSound eSID) { assert(eSID>=0 && eSID<eSID_Max); return m_soundNames[eSID]; } //------------------------------------------------------------------------ void CVehicleMovementBase::SetSoundParam(EVehicleMovementSound eSID, const char* param, float value) { if (ISound* pSound = GetSound(eSID)) { pSound->SetParam(param, value, false); } } //------------------------------------------------------------------------ void CVehicleMovementBase::SetSoundParam(ISound* pSound, const char* param, float value) { pSound->SetParam(param, value, false); } //------------------------------------------------------------------------ void CVehicleMovementBase::DebugDraw(const float deltaTime) { static float color[] = {1,1,1,1}; static float red[] = {1,0,0,1}; static ICVar* pDebugVehicle = gEnv->pConsole->GetCVar("v_debugVehicle"); float val = 0.f; float size = 1.4f; int y = 75; int step = 20; while (g_pGameCVars->v_debugSounds) { if (!m_pVehicle->IsPlayerPassenger() && 0!=strcmpi(m_pVehicle->GetEntity()->GetName(), pDebugVehicle->GetString())) break; gEnv->pRenderer->Draw2dLabel(500,y,1.5f,color,false,"vehicle rpm: %.2f", m_rpmScale); if (ISound* pSound = GetSound(eSID_Run)) { if (pSound->GetParam("rpm_scale", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":run rpm_scale: %.2f", val); if (pSound->GetParam("load", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":run load: %.2f", val); if (pSound->GetParam("speed", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":run speed: %.2f", val); if (pSound->GetParam("acceleration", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":run acceleration: %.1f", val); if (pSound->GetParam("surface", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":run surface: %.2f", val); if (pSound->GetParam("scratch", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":run scratch: %.0f", val); if (pSound->GetParam("slip", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":run slip: %.1f", val); if (pSound->GetParam("in_out", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":run in_out: %.1f", val); if (pSound->GetParam("damage", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":run damage: %.2f", val); if (pSound->GetParam("swim", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":run swim: %.2f", val); } if (ISound* pSound = GetSound(eSID_Ambience)) { gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,"-----------------------------"); if (pSound->GetParam("rpm_scale", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":ambience rpm_scale: %.2f", val); if (pSound->GetParam("speed", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":ambience speed: %.2f", val); if (pSound->GetParam("thirdperson", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":ambience thirdperson: %.1f", val); } if (ISound* pSound = GetSound(eSID_Slip)) { gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,"-----------------------------"); if (pSound->GetParam("slip_speed", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":slip slip_speed: %.2f", val); if (pSound->GetParam("surface", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":slip surface: %.2f", val); } if (ISound* pSound = GetSound(eSID_Bump)) { gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,"-----------------------------"); if (pSound->GetParam("intensity", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":bump intensity: %.2f", val); } if (ISound* pSound = GetSound(eSID_Splash)) { gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,"-----------------------------"); if (pSound->GetParam("intensity", &val, false) != -1) gEnv->pRenderer->Draw2dLabel(500,y+=step,size,color,false,":splash intensity: %.2f", val); } break; } while (g_pGameCVars->v_sprintSpeed != 0.f) { if (!m_pVehicle->IsPlayerPassenger() && 0!=strcmpi(m_pVehicle->GetEntity()->GetName(), pDebugVehicle->GetString())) break; float speed = m_pVehicle->GetStatus().speed; float* col = color; if (speed < 0.2f) m_sprintTime = 0.f; else if (speed*3.6f < g_pGameCVars->v_sprintSpeed) m_sprintTime += deltaTime; else col = red; gEnv->pRenderer->Draw2dLabel(400, 300, 1.5f, color, false, "t: %.2f", m_sprintTime); break; } } //------------------------------------------------------------------------ void CVehicleMovementBase::Serialize(TSerialize ser, unsigned aspects) { // SVehicleMovementAction m_movementAction; if (ser.GetSerializationTarget() != eST_Network) { ser.BeginGroup("MovementBase"); ser.Value("movementProcessingEnabled", m_bMovementProcessingEnabled); ser.Value("isEngineDisabled", m_isEngineDisabled); ser.Value("DriverId", m_actorId); ser.Value("damage", m_damage); ser.Value("engineStartup", m_engineStartup); ser.Value("isEngineGoingOff", m_isEngineGoingOff); ser.Value("boostCounter", m_boostCounter); ser.Value("soundMasterVol", m_soundMasterVolume); bool isEngineStarting = m_isEngineStarting; ser.Value("isEngineStarting", isEngineStarting); bool isEnginePowered = m_isEnginePowered; ser.Value("isEnginePowered", isEnginePowered); if (ser.IsReading()) { m_pEntity = m_pVehicle->GetEntity(); for (int i=0; i<eSID_Max; ++i) m_soundStats.lastPlayed[i].SetSeconds((int64)-100); if (!m_isEnginePowered && (isEnginePowered || (isEngineStarting && !m_isEngineStarting))) { m_pVehicle->GetGameObject()->EnableUpdateSlot(m_pVehicle, IVehicle::eVUS_EnginePowered); InitWind(); } else if (!isEnginePowered && !isEngineStarting && (m_isEnginePowered || m_isEngineStarting)) { m_pVehicle->GetGameObject()->DisableUpdateSlot(m_pVehicle, IVehicle::eVUS_EnginePowered); StopSound(eSID_Run); StopSound(eSID_Damage); } m_isEnginePowered = isEnginePowered; m_isEngineStarting = isEngineStarting; } m_paStats.Serialize(ser, aspects); m_surfaceSoundStats.Serialize(ser, aspects); m_movementTweaks.Serialize(ser, aspects); ser.EndGroup(); } } //------------------------------------------------------------------------ void CVehicleMovementBase::PostSerialize() { m_movementAction.Clear(); if (m_isEnginePowered || m_isEngineStarting) { PlaySound(eSID_Run, 0.f, m_enginePos); if (m_pVehicle->IsPlayerPassenger()) GetOrPlaySound(eSID_Ambience); } } //------------------------------------------------------------------------ void CVehicleMovementBase::ProcessEvent(SEntityEvent& event) { } DEFINE_VEHICLEOBJECT(CVehicleMovementBase) //------------------------------------------------------------------------ #if !defined(_LIB) //-------------------------------------------------------------------------------------------- SPID::SPID() : m_kP( 0 ), m_kD( 0 ), m_kI( 0 ), m_prevErr( 0 ), m_intErr( 0 ) { // empty } //-------------------------------------------------------------------------------------------- void SPID::Reset() { m_prevErr = 0; m_intErr = 0; } //-------------------------------------------------------------------------------------------- float SPID::Update( float inputVal, float setPoint, float clampMin, float clampMax ) { float pError = setPoint - inputVal; float output = m_kP * pError - m_kD * (pError - m_prevErr) + m_kI * m_intErr; m_prevErr = pError; // Accumulate integral, or clamp. if( output > clampMax ) output = clampMax; else if( output < clampMin ) output = clampMin; else m_intErr += pError; return output; } #endif // _LIB //-------------------------------------------------------------------------------------------- void SPID::Serialize(TSerialize ser) { ser.Value("m", m_intErr); ser.Value("m_kD", m_kD); ser.Value("m_kI", m_kI); ser.Value("m_prevErr", m_prevErr); }
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 47 ], [ 49, 57 ], [ 59, 63 ], [ 69, 126 ], [ 130, 131 ], [ 135, 154 ], [ 182, 209 ], [ 217, 244 ], [ 253, 255 ], [ 259, 325 ], [ 328, 331 ], [ 334, 334 ], [ 336, 336 ], [ 339, 339 ], [ 343, 345 ], [ 348, 348 ], [ 350, 350 ], [ 355, 372 ], [ 377, 384 ], [ 387, 387 ], [ 389, 406 ], [ 414, 424 ], [ 441, 441 ], [ 445, 446 ], [ 449, 458 ], [ 460, 460 ], [ 467, 467 ], [ 479, 479 ], [ 481, 489 ], [ 496, 496 ], [ 503, 519 ], [ 537, 571 ], [ 573, 573 ], [ 575, 588 ], [ 605, 621 ], [ 623, 655 ], [ 659, 684 ], [ 687, 687 ], [ 693, 693 ], [ 695, 753 ], [ 777, 808 ], [ 851, 862 ], [ 864, 864 ], [ 870, 870 ], [ 874, 878 ], [ 882, 882 ], [ 884, 887 ], [ 919, 924 ], [ 994, 1013 ], [ 1015, 1017 ], [ 1027, 1029 ], [ 1033, 1052 ], [ 1054, 1063 ], [ 1068, 1082 ], [ 1084, 1134 ], [ 1138, 1144 ], [ 1148, 1149 ], [ 1151, 1153 ], [ 1160, 1176 ], [ 1193, 1193 ], [ 1197, 1202 ], [ 1204, 1204 ], [ 1206, 1206 ], [ 1214, 1217 ], [ 1220, 1220 ], [ 1224, 1224 ], [ 1230, 1231 ], [ 1233, 1235 ], [ 1238, 1261 ], [ 1265, 1277 ], [ 1279, 1309 ], [ 1326, 1365 ], [ 1369, 1377 ], [ 1379, 1402 ], [ 1408, 1422 ], [ 1428, 1431 ], [ 1438, 1466 ], [ 1468, 1476 ], [ 1480, 1598 ], [ 1602, 1670 ], [ 1672, 1688 ], [ 1693, 1699 ], [ 1703, 1741 ], [ 1744, 1750 ], [ 1752, 1754 ], [ 1756, 1807 ], [ 1811, 2006 ], [ 2010, 2083 ], [ 2085, 2091 ], [ 2093, 2102 ], [ 2106, 2109 ], [ 2111, 2125 ], [ 2128, 2140 ], [ 2142, 2202 ] ], [ [ 48, 48 ], [ 58, 58 ], [ 64, 68 ], [ 127, 129 ], [ 132, 134 ], [ 155, 181 ], [ 210, 216 ], [ 245, 252 ], [ 256, 258 ], [ 326, 327 ], [ 332, 333 ], [ 335, 335 ], [ 337, 338 ], [ 340, 342 ], [ 346, 347 ], [ 349, 349 ], [ 351, 354 ], [ 373, 376 ], [ 385, 386 ], [ 388, 388 ], [ 407, 413 ], [ 425, 440 ], [ 442, 444 ], [ 447, 448 ], [ 459, 459 ], [ 461, 466 ], [ 468, 478 ], [ 480, 480 ], [ 490, 495 ], [ 497, 502 ], [ 520, 536 ], [ 572, 572 ], [ 574, 574 ], [ 589, 604 ], [ 622, 622 ], [ 656, 658 ], [ 685, 686 ], [ 688, 692 ], [ 694, 694 ], [ 754, 776 ], [ 809, 850 ], [ 863, 863 ], [ 865, 869 ], [ 871, 873 ], [ 879, 881 ], [ 883, 883 ], [ 888, 918 ], [ 925, 993 ], [ 1014, 1014 ], [ 1018, 1026 ], [ 1030, 1032 ], [ 1053, 1053 ], [ 1064, 1067 ], [ 1083, 1083 ], [ 1135, 1137 ], [ 1145, 1147 ], [ 1150, 1150 ], [ 1154, 1159 ], [ 1177, 1192 ], [ 1194, 1196 ], [ 1203, 1203 ], [ 1205, 1205 ], [ 1207, 1213 ], [ 1218, 1219 ], [ 1221, 1223 ], [ 1225, 1229 ], [ 1232, 1232 ], [ 1236, 1237 ], [ 1262, 1264 ], [ 1278, 1278 ], [ 1310, 1325 ], [ 1366, 1368 ], [ 1378, 1378 ], [ 1403, 1407 ], [ 1423, 1427 ], [ 1432, 1437 ], [ 1467, 1467 ], [ 1477, 1479 ], [ 1599, 1601 ], [ 1671, 1671 ], [ 1689, 1692 ], [ 1700, 1702 ], [ 1742, 1743 ], [ 1751, 1751 ], [ 1755, 1755 ], [ 1808, 1810 ], [ 2007, 2009 ], [ 2084, 2084 ], [ 2092, 2092 ], [ 2103, 2105 ], [ 2110, 2110 ], [ 2126, 2127 ], [ 2141, 2141 ] ] ]
b302b81d67bccf5015a72abc02b61ac5eefdb73f
df238aa31eb8c74e2c208188109813272472beec
/BCGInclude/BCGPSliderCtrl.h
953154381ff57e375054a8160ca98e66f5091b99
[]
no_license
myme5261314/plugin-system
d3166f36972c73f74768faae00ac9b6e0d58d862
be490acba46c7f0d561adc373acd840201c0570c
refs/heads/master
2020-03-29T20:00:01.155206
2011-06-27T15:23:30
2011-06-27T15:23:30
39,724,191
0
0
null
null
null
null
UTF-8
C++
false
false
2,278
h
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of BCGControlBar Library Professional Edition // Copyright (C) 1998-2008 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPSliderCtrl.h : header file // #if !defined(AFX_BCGPSLIDERCTRL_H__D54F6105_98FA_4CD8_B021_C6862EEE5968__INCLUDED_) #define AFX_BCGPSLIDERCTRL_H__D54F6105_98FA_4CD8_B021_C6862EEE5968__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "BCGCBPro.h" ///////////////////////////////////////////////////////////////////////////// // CBCGPSliderCtrl window class BCGCBPRODLLEXPORT CBCGPSliderCtrl : public CSliderCtrl { DECLARE_DYNAMIC(CBCGPSliderCtrl) // Construction public: CBCGPSliderCtrl(); // Attributes public: BOOL m_bOnGlass; BOOL m_bVisualManagerStyle; BOOL m_bDrawFocus; protected: BOOL m_bIsThumbHighligted; BOOL m_bIsThumPressed; BOOL m_bTracked; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBCGPSliderCtrl) //}}AFX_VIRTUAL // Implementation public: virtual ~CBCGPSliderCtrl(); // Generated message map functions protected: //{{AFX_MSG(CBCGPSliderCtrl) afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnCancelMode(); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnPaint(); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); //}}AFX_MSG afx_msg LRESULT OnBCGSetControlVMMode (WPARAM, LPARAM); afx_msg LRESULT OnBCGSetControlAero (WPARAM, LPARAM); afx_msg LRESULT OnMouseLeave(WPARAM,LPARAM); DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BCGPSLIDERCTRL_H__D54F6105_98FA_4CD8_B021_C6862EEE5968__INCLUDED_)
[ "myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5" ]
[ [ [ 1, 80 ] ] ]
aed1a40db45b04caf0bfe5828245b161d38afb73
7f30cb109e574560873a5eb8bb398c027f85eeee
/src/segmentationManager.h
aa7b85004befb6a6c0c9730d54e51908d5103913
[]
no_license
svn2github/MITO
e8fd0e0b6eebf26f2382f62660c06726419a9043
71d1269d7666151df52d6b5a98765676d992349a
refs/heads/master
2021-01-10T03:13:55.083371
2011-10-14T15:40:14
2011-10-14T15:40:14
47,415,786
1
0
null
null
null
null
ISO-8859-1
C++
false
false
3,091
h
/** * \file segmentationManager.h * \brief Gestione segmentazione * \author ICAR-CNR Napoli */ #ifndef _segmentationManager_h_ #define _segmentationManager_h_ #include "viewerHandler.h" #include "infoFilter.h" #include <vtkImageData.h> /** * \class segmentationManager * \brief Classe per la gestione della Segmentazione * * Questa classe si occupa di gestire tutte le funzionalità inerenti la segmentazione */ class segmentationManager { /** * \var viewerHandler* _viewerHandler * \brief Gestore dei visualizzatori */ viewerHandler* _viewerHandler; /** * \var int _idData * \brief identificativo del dato */ unsigned int _idData; /** * \var unsigned int _idViewer * \brief Identificativo del visualizzatore */ unsigned int _idViewer; /** * \var bool _verFlip * \brief Indica se è stato effettuato un flip verticale */ bool _verFlip; /** * \var bool _verFlip * \brief Indica se è stato effettuato un flip orizzontale */ bool _horFlip; /** * \var int _x * \brief Coordinata x del pixel */ int _x; /** * \var int _y * \brief Coordinata y del pixel */ int _y; /** * \var short _pixelValue * \brief Intensità del pixel */ short _pixelValue; /** * \var ImageType::IndexType _seed * \brief Seme */ ImageType::IndexType _seed; public: /** Costruttore con parametro viewerHandler */ segmentationManager(viewerHandler* viewerHandler); /** Distruttore */ ~segmentationManager(); /** * \fn void initializeSegmentationManager() * \brief Inizializza il gestore della segmentazione */ void initializeSegmentationManager(); /** * \fn bool computeConnectedThresholdAlgorithm() * \brief Effettua la segmentazione secondo la tecnica Connected Threshold * \return true se l'operazione è andata a buon fine */ bool computeConnectedThresholdAlgorithm(); /** * \fn bool computeNeighborhoodConnectedAlgorithm() * \brief Effettua la segmentazione secondo la tecnica Neighborhood Connected * \return true se l'operazione è andata a buon fine */ bool computeNeighborhoodConnectedAlgorithm(); /** * \fn bool computeConfidenceConnectedAlgorithm() * \brief Effettua la segmentazione secondo la tecnica Confidence Connected * \return true se l'operazione è andata a buon fine */ bool computeConfidenceConnectedAlgorithm(); /** * \fn void setFlipState(bool verFlip, bool horFlip) * \brief Setta lo stato del flip * \param verFlip Flip verticale * \param horFlip Flip orizzontale */ inline void setFlipState(bool verFlip, bool horFlip) { _verFlip = verFlip; _horFlip = horFlip; } private: /** * \fn void computeFlipping(vtkImageData* image, char axis) * \brief Effettua il flipping con VTK * \param image Immagine da flippare * \param axis Asse ripetto il quale effettuare il flipping: può essere 'x', 'y' o 'z' */ void computeFlipping(vtkImageData* image, char axis); }; #endif _segmentationManager_h_
[ "kg_dexterp37@fde90bc1-0431-4138-8110-3f8199bc04de" ]
[ [ [ 1, 131 ] ] ]
96494b0228f2c27e8f2ad9e3896078e62be1e814
a7109719291d3fb1e3dabfed9405d2b340ad8a89
/Gandhi-Prototype/src/Win32Main.cpp
fbbe00114a3279db240da3cadba34dd577ef1af3
[]
no_license
edufg88/gandhi-prototype
0ea3c6a7bbe72b6d382fa76f23c40b4a0280c666
947f2c6d8a63421664eb5018d5d01b8da71f46a2
refs/heads/master
2021-01-01T17:32:40.791045
2011-12-19T20:10:34
2011-12-19T20:10:34
32,288,341
0
0
null
null
null
null
UTF-8
C++
false
false
2,414
cpp
// ------------------------- // Windows 32 bit window init functions // ------------------------- #include <windows.h> #include "cGame.h" LRESULT CALLBACK WindowFunc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch(msg) { case WM_KEYDOWN: switch( wParam ) { case VK_ESCAPE: PostQuitMessage(0); break; } break; case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } bool InitWindow( HINSTANCE hInst, HWND *hWnd, bool *exclusive ) { WNDCLASSEX wcl; char szWinName[] = "Game Engine Window"; wcl.cbSize = sizeof( WNDCLASSEX ); wcl.hInstance = hInst; wcl.lpszClassName = szWinName; wcl.lpfnWndProc = WindowFunc; wcl.style = CS_HREDRAW | CS_VREDRAW; wcl.hIcon = LoadIcon (NULL, IDI_APPLICATION); wcl.hIconSm = LoadIcon (NULL, IDI_APPLICATION); wcl.hCursor = LoadCursor (NULL, IDC_ARROW); wcl.lpszMenuName = NULL; wcl.cbClsExtra = 0; wcl.cbWndExtra = 0; wcl.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH); if( !RegisterClassEx( &wcl ) ) return false; int fullscreen; fullscreen=MessageBox(0, "Would you like fullscreen mode?", "GANDHI Prototype", MB_YESNO ); if(fullscreen==IDYES) { *hWnd = CreateWindow( szWinName, szWinName, WS_POPUP, 0, 0, SCREEN_RES_X, //GetSystemMetrics(SM_CXSCREEN), SCREEN_RES_Y, //GetSystemMetrics(SM_CYSCREEN), HWND_DESKTOP, NULL, hInst, NULL ); *exclusive = true; } else { *hWnd = CreateWindow( szWinName, szWinName, WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, 0, 0, SCREEN_RES_X, SCREEN_RES_Y, HWND_DESKTOP, NULL, hInst, NULL ); *exclusive = false; } if( *hWnd == NULL ) return false; return true; } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevIntance, LPSTR lpszArgs, int nWinMode ) { bool exclusive,res; MSG msg; HWND hWnd; cGame* game = cGame::GetInstance(); res = InitWindow( hInstance, &hWnd, &exclusive ); res = game->Init(hWnd,hInstance,exclusive); if( res == true ) { while(1) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { if( msg.message == WM_QUIT ) break; TranslateMessage( &msg ); DispatchMessage( &msg ); } else { if(!game->Loop()) break; } } } game->Finalize(); return 0; }
[ "[email protected]@5f958858-fb9a-a521-b75c-3c5ff6351dd8", "[email protected]@5f958858-fb9a-a521-b75c-3c5ff6351dd8" ]
[ [ [ 1, 44 ], [ 46, 46 ], [ 65, 98 ] ], [ [ 45, 45 ], [ 47, 64 ] ] ]
c877d59aae925ee7e9723e6c6dcf7ca6f97e88f3
5424018aa2443f3ad7688fb27afc67ffb6172f81
/wajima/pss/src/pss/system/Process.cpp
3a93cb87f42903864ccbc152188d6e37c41c148a
[]
no_license
Amakata/wajima
f9ed0b980df70ca9738bac6d381948e0fa2b318f
6c58b04efa0c45eb0a2f21d67b79d5058c13f586
refs/heads/master
2021-01-17T06:24:37.237575
2005-01-09T08:24:04
2005-01-09T08:24:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
60
cpp
#define PSS_SYSTEM_PROCESS_COMPILE #include "Process.hpp"
[ "ama@0d65b87a-bfcd-0310-b916-82c895c6ade2" ]
[ [ [ 1, 2 ] ] ]
84af054459db55539379b55de05cf6340b187fa7
3276915b349aec4d26b466d48d9c8022a909ec16
/c++小作品/sony/pureflatcreate.h
c4d26a721edd9576c26d22e1487f64d13ccd98bd
[]
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
242
h
#ifndef PUREFLATCREATE_HEADER #define PUREFLATCREATE_HEADER #include<iostream.h> #include"createsony.h" class PureFlatCreate :public CreateSony { public: Sony * createinch29(); Sony * createinch43(); }; #endif
[ [ [ 1, 20 ] ] ]
1861783c0be8c3de97b37cedafafe8f78738ed42
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/teststring/src/teststring.cpp
878ad3729a90027ddb7f568a6de00e6246fde82e
[]
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
127,808
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ /* * ============================================================================== * Name : teststring.cpp * Part of : teststring * * Description : ?Description * Version: 0.5 * */ #include "teststring.h" #include <unistd.h> #include <errno.h> #include <string.h> #include <e32std.h> #include <locale.h> #include <stdlib.h> #include <sys/stdint.h> #include <sys/types.h> #include <sys/stat.h> #include <inttypes.h> #include <time.h> #include <stdio.h> #include <wchar.h> #define MIN_LEN 10 CTestString::~CTestString() { } CTestString::CTestString(const TDesC& aStepName) { // MANDATORY Call to base class method to set up the human readable name for logging. SetTestStepName(aStepName); } TVerdict CTestString::doTestStepPreambleL() { __UHEAP_MARK; SetTestStepResult(EPass); return TestStepResult(); } TVerdict CTestString::doTestStepPostambleL() { __UHEAP_MARKEND; return TestStepResult(); } TVerdict CTestString::doTestStepL() { int err; if(TestStepName() == KMemCpyTestZeroLengthCopy) { INFO_PRINTF1(_L("memcpyTestZeroLengthCopy():")); err = memcpyTestZeroLengthCopy(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMemCpyBasicTest) { INFO_PRINTF1(_L("memcpyBasicTest():")); err = memcpyBasicTest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //memmove else if(TestStepName() == KMemMoveBasicTest) { INFO_PRINTF1(_L("memmoveBasictest():")); err = memmoveBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMemMoveZeroLength) { INFO_PRINTF1(_L("memmoveZeroLength():")); err = memmoveZeroLength(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMemMoveOverlap) { INFO_PRINTF1(_L("memmoveOverlap():")); err = memmoveOverlap(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strcpy else if(TestStepName() == KStrcpyBasictest) { INFO_PRINTF1(_L("strcpyBasictest():")); err = strcpyBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrcpyWriteOver) { INFO_PRINTF1(_L("KStrcpyWriteOver():")); err = strcpyWriteOver(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrcpyBoundry) { INFO_PRINTF1(_L("strcpyBoundry():")); err = strcpyBoundry(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strncpy else if(TestStepName() == KStrncpyBasictest) { INFO_PRINTF1(_L("strncpyBasictest():")); err = strncpyBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrncpyCutCnt) { INFO_PRINTF1(_L("strncpyCutCnt():")); err = strncpyCutCnt(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrncpyCutNul) { INFO_PRINTF1(_L("strncpyCutNul():")); err = strncpyCutNul(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrncpyNulInc) { INFO_PRINTF1(_L("strncpyNulInc():")); err = strncpyNulInc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrncpyZeroLen) { INFO_PRINTF1(_L("strncpyZeroLen():")); err = strncpyZeroLen(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrncpyZeroSrc) { INFO_PRINTF1(_L("strncpyZeroSrc():")); err = strncpyZeroSrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strcat else if(TestStepName() == KStrcatBasictest) { INFO_PRINTF1(_L("strcatBasictest():")); err = strcatBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrcatBoundry) { INFO_PRINTF1(_L("strcatBoundry():")); err = strcatBoundry(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrcatMemset) { INFO_PRINTF1(_L("strcatMemset():")); err = strcatMemset(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strncat else if(TestStepName() == KStrncatBasictest) { INFO_PRINTF1(_L("strncatBasictest():")); err = strncatBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrncatBoundry) { INFO_PRINTF1(_L("strncatBoundry():")); err = strncatBoundry(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrncatMemset) { INFO_PRINTF1(_L("strncatMemset():")); err = strncatMemset(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //memcmp else if(TestStepName() == KMemcmpBasictest) { INFO_PRINTF1(_L("memcmpBasictest():")); err = memcmpBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMemcmpUnequal) { INFO_PRINTF1(_L("memcmpUnequal():")); err = memcmpUnequal(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMemcmpLtdCount) { INFO_PRINTF1(_L("memcmpLtdCount():")); err = memcmpLtdCount(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KMemcmpZeroCount) { INFO_PRINTF1(_L("memcmpZeroCount():")); err = memcmpZeroCount(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strcmp else if(TestStepName() == KStrcmpBasictest) { INFO_PRINTF1(_L("strcmpBasictest():")); err = strcmpBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrcmpMisMatchStrAndLen) { INFO_PRINTF1(_L("strcmpMisMatchStrAndLen():")); err = strcmpMisMatchStrAndLen(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strncmp else if(TestStepName() == KStrncmpBasictest) { INFO_PRINTF1(_L("strncmpBasictest():")); err = strncmpBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrncmpMisMatchStrAndLen) { INFO_PRINTF1(_L("strncmpMisMatchStrAndLen():")); err = strncmpMisMatchStrAndLen(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrncmpCountCheck) { INFO_PRINTF1(_L("strncmpCountCheck():")); err = strncmpCountCheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strcoll else if(TestStepName() == KStrcollBasictest) { INFO_PRINTF1(_L("strcollBasictest():")); err = strcollBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //srxfrm else if(TestStepName() == KSrxfrmBasictest) { INFO_PRINTF1(_L("srxfrmBasictest():")); err = srxfrmBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //memchr else if(TestStepName() == KmemchrNotFound) { INFO_PRINTF1(_L("memchrNotFound():")); err = memchrNotFound(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KmemchrBasictest) { INFO_PRINTF1(_L("memchrBasictest():")); err = memchrBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KmemchrFindNul) { INFO_PRINTF1(_L("memchrFindNul():")); err = memchrFindNul(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KmemchrZeroCount) { INFO_PRINTF1(_L("memchrZeroCount():")); err = memchrZeroCount(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strchr else if(TestStepName() == KstrchrNotFound) { INFO_PRINTF1(_L("strchrNotFound():")); err = strchrNotFound(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrchrBasicTest) { INFO_PRINTF1(_L("strchrBasicTest():")); err = strchrBasicTest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrchrFindNul) { INFO_PRINTF1(_L("strchrFindNul():")); err = strchrFindNul(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrchrFindFirst) { INFO_PRINTF1(_L("strchrFindFirst():")); err = strchrFindFirst(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrchrEmptyString) { INFO_PRINTF1(_L("strchrEmptyString():")); err = strchrEmptyString(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrchrNulEmptyStr) { INFO_PRINTF1(_L("strchrNulEmptyStr():")); err = strchrNulEmptyStr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strcspn else if(TestStepName() == KstrcspnWholeStr) { INFO_PRINTF1(_L("strcspnWholeStr():")); err = strcspnWholeStr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrcspnPartString) { INFO_PRINTF1(_L("strcspnPartString():")); err = strcspnPartString(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrcspnNone) { INFO_PRINTF1(_L("strcspnNone():")); err = strcspnNone(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrcspnNullString) { INFO_PRINTF1(_L("strcspnNullString():")); err = strcspnNullString(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrcspnNullSearch) { INFO_PRINTF1(_L("strcspnNullSearch():")); err = strcspnNullSearch(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strpbrk else if(TestStepName() == KstrpbrkNotFound) { INFO_PRINTF1(_L("strpbrkNotFound():")); err = strpbrkNotFound(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrpbrkBasictest) { INFO_PRINTF1(_L("strpbrkBasictest():")); err = strpbrkBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrpbrkEmptySearch) { INFO_PRINTF1(_L("strpbrkEmptySearch():")); err = strpbrkEmptySearch(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrpbrkEmptyString) { INFO_PRINTF1(_L("strpbrkEmptyString():")); err = strpbrkEmptyString(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrpbrkBothEmpty) { INFO_PRINTF1(_L("strpbrkBothEmpty():")); err = strpbrkBothEmpty(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrpbrkFindFirst) { INFO_PRINTF1(_L("strpbrkFindFirst():")); err = strpbrkFindFirst(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strrchr else if(TestStepName() == KstrrchrNotfound) { INFO_PRINTF1(_L("strrchrNotfound():")); err = strrchrNotfound(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrrchrBasictest) { INFO_PRINTF1(_L("strrchrBasictest():")); err = strrchrBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrrchrFindNul) { INFO_PRINTF1(_L("strrchrFindNul():")); err = strrchrFindNul(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrrchrFindLast) { INFO_PRINTF1(_L("strrchrFindLast():")); err = strrchrFindLast(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrrchrEmptyStr) { INFO_PRINTF1(_L("strrchrEmptyStr():")); err = strrchrEmptyStr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrrchrEmptyNul) { INFO_PRINTF1(_L("strrchrEmptyNul():")); err = strrchrEmptyNul(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strspn else if(TestStepName() == KstrspnWholeStr) { INFO_PRINTF1(_L("strspnWholeStr():")); err = strspnWholeStr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrspnPartial) { INFO_PRINTF1(_L("strspnPartial():")); err = strspnPartial(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrspnNone) { INFO_PRINTF1(_L("strspnNone():")); err = strspnNone(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrspnNulStr) { INFO_PRINTF1(_L("strspnNulStr():")); err = strspnNulStr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrspnNulSearch) { INFO_PRINTF1(_L("strspnNulSearch():")); err = strspnNulSearch(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strstr else if(TestStepName() == KstrstrNotFound) { INFO_PRINTF1(_L("strstrNotFound():")); err = strstrNotFound(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrstrBasictest) { INFO_PRINTF1(_L("strstrBasictest():")); err = strstrBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrstrLong) { INFO_PRINTF1(_L("strstrLong():")); err = strstrLong(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrstrFindEmpty) { INFO_PRINTF1(_L("strstrFindEmpty():")); err = strstrFindEmpty(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrstrEmptyStr) { INFO_PRINTF1(_L("strstrEmptyStr():")); err = strstrEmptyStr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrstrEmpty) { INFO_PRINTF1(_L("strstrEmpty():")); err = strstrEmpty(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strtok else if(TestStepName() == KstrtokBasictest) { INFO_PRINTF1(_L("strtokBasictest():")); err = strtokBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrtokDelim) { INFO_PRINTF1(_L("strtokDelim():")); err = strtokDelim(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrtokChangeDelim) { INFO_PRINTF1(_L("strtokChangeDelim():")); err = strtokChangeDelim(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrtokNewStr) { INFO_PRINTF1(_L("strtokNewStr():")); err = strtokNewStr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrtokDiffSap) { INFO_PRINTF1(_L("strtokDiffSap():")); err = strtokDiffSap(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrtokNoTok) { INFO_PRINTF1(_L("strtokNoTok():")); err = strtokNoTok(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrtokEmptyStr) { INFO_PRINTF1(_L("strtokEmptyStr():")); err = strtokEmptyStr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrtokNoDelim) { INFO_PRINTF1(_L("strtokNoDelim():")); err = strtokNoDelim(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrtokEmptyDelim) { INFO_PRINTF1(_L("strtokEmptyDelim():")); err = strtokEmptyDelim(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //memset else if(TestStepName() == KmemsetBasictest) { INFO_PRINTF1(_L("memsetBasictest():")); err = memsetBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KmemsetZeroLen) { INFO_PRINTF1(_L("memsetZeroLen():")); err = memsetZeroLen(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strerror else if(TestStepName() == KstrerrorBasictest) { INFO_PRINTF1(_L("strerrorBasictest():")); err = strerrorBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrerrorUnknown) { INFO_PRINTF1(_L("strerrorUnknown():")); err = strerrorUnknown(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strlen else if(TestStepName() == KstrlenEmpty) { INFO_PRINTF1(_L("strlenEmpty():")); err = strlenEmpty(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrlenSingleChar) { INFO_PRINTF1(_L("strlenSingleChar():")); err = strlenSingleChar(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KstrlenMultiChar) { INFO_PRINTF1(_L("strlenMultiChar():")); err = strlenMultiChar(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //bcmp else if(TestStepName() == Kbcmpsameargs) { INFO_PRINTF1(_L("bcmpsameargs():")); err = bcmpsameargs(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kbcmpdiffargs) { INFO_PRINTF1(_L("bcmpdiffargs():")); err = bcmpdiffargs(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kbcmpzerocnt) { INFO_PRINTF1(_L("bcmpzerocnt():")); err = bcmpzerocnt(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //bcopy else if(TestStepName() == Kbcopyfuncheck) { INFO_PRINTF1(_L("bcopyfuncheck():")); err = bcopyfuncheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kbcopybasic) { INFO_PRINTF1(_L("bcopybasic():")); err = bcopybasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kbcopyzerocopy) { INFO_PRINTF1(_L("bcopyzerocopy():")); err = bcopyzerocopy(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kbcopysrcconst) { INFO_PRINTF1(_L("bcopysrcconst():")); err = bcopysrcconst(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kbcopynullsrc) { INFO_PRINTF1(_L("bcopynullsrc():")); err = bcopynullsrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kbcopyoverlap) { INFO_PRINTF1(_L("bcopyoverlap():")); err = bcopyoverlap(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strsep else if(TestStepName() == Kstrsepbasic) { INFO_PRINTF1(_L("strsepbasic():")); err = strsepbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrsepsrccheck) { INFO_PRINTF1(_L("strsepsrccheck():")); err = strsepsrccheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //bzero else if(TestStepName() == Kbzerobasic) { INFO_PRINTF1(_L("bzerobasic():")); err = bzerobasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kbzeronocopy) { INFO_PRINTF1(_L("bzeronocopy():")); err = bzeronocopy(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //ffs else if(TestStepName() == Kffsbasic) { INFO_PRINTF1(_L("ffsbasic():")); err = ffsbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //index else if(TestStepName() == Kindexbasic) { INFO_PRINTF1(_L("indexbasic():")); err = indexbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kindexnotfound) { INFO_PRINTF1(_L("indexnotfound():")); err = indexnotfound(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kindexend) { INFO_PRINTF1(_L("indexend():")); err = indexend(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kindexbeginning) { INFO_PRINTF1(_L("indexbeginning():")); err = indexbeginning(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kindexfindnull) { INFO_PRINTF1(_L("indexfindnull():")); err = indexfindnull(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kindexnullsrc) { INFO_PRINTF1(_L("indexnullsrc():")); err = indexnullsrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //rindex else if(TestStepName() == Krindexbasic) { INFO_PRINTF1(_L("rindexbasic():")); err = rindexbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Krindexnotfound) { INFO_PRINTF1(_L("rindexnotfound():")); err = rindexnotfound(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Krindexend) { INFO_PRINTF1(_L("rindexend():")); err = rindexend(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Krindexbeginning) { INFO_PRINTF1(_L("rindexbeginning():")); err = rindexbeginning(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Krindexfindnull) { INFO_PRINTF1(_L("rindexfindnull():")); err = rindexfindnull(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Krindexnullsrc) { INFO_PRINTF1(_L("rindexnullsrc():")); err = rindexnullsrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //memcpy else if(TestStepName() == Kmemcpybasic) { INFO_PRINTF1(_L("memcpybasic():")); err = memcpybasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kmemcpyzerolength) { INFO_PRINTF1(_L("memcpyzerolength():")); err = memcpyzerolength(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kmemcpysrcconstantness) { INFO_PRINTF1(_L("memcpysrcconstantness():")); err = memcpysrcconstantness(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //stpcpy else if(TestStepName() == Kstpcpybasic) { INFO_PRINTF1(_L("indexend():")); err = indexend(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strcasecmp else if(TestStepName() == Kstrcasecmpcasecheck) { INFO_PRINTF1(_L("strcasecmpcasecheck():")); err = strcasecmpcasecheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrcasecmplargesrc) { INFO_PRINTF1(_L("strcasecmplargesrc():")); err = strcasecmplargesrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrcasecmpsmallsrc) { INFO_PRINTF1(_L("strcasecmpsmallsrc():")); err = strcasecmpsmallsrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strncmp else if(TestStepName() == Kstrncmpbasic) { INFO_PRINTF1(_L("strncmpbasic():")); err = strncmpbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrncmplargesrc) { INFO_PRINTF1(_L("strncmplargesrc():")); err = strncmplargesrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrncmpsmallsrc) { INFO_PRINTF1(_L("strncmpsmallsrc():")); err = strncmpsmallsrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strcoll else if(TestStepName() == Kstrcollbasic) { INFO_PRINTF1(_L("strcollbasic():")); err = strcollbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrcolllargesrc) { INFO_PRINTF1(_L("strcolllargesrc():")); err = strcolllargesrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrcollsmallsrc) { INFO_PRINTF1(_L("strcollsmallsrc():")); err = strcollsmallsrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strndup else if(TestStepName() == Kstrndupbasic) { INFO_PRINTF1(_L("strndupbasic():")); err = strndupbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrnduplargecnt) { INFO_PRINTF1(_L("strnduplargecnt():")); err = strnduplargecnt(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrndupequalcnt) { INFO_PRINTF1(_L("strndupequalcnt():")); err = strndupequalcnt(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrndupzerocnt) { INFO_PRINTF1(_L("strndupzerocnt():")); err = strndupzerocnt(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrndupnullsrc) { INFO_PRINTF1(_L("strndupnullsrc():")); err = strndupnullsrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strnlen else if(TestStepName() == Kstrnlenbasic) { INFO_PRINTF1(_L("strnlenbasic():")); err = strnlenbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrnlensmallstr) { INFO_PRINTF1(_L("strnlensmallstr():")); err = strnlensmallstr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrnlennullstr) { INFO_PRINTF1(_L("strnlennullstr():")); err = strnlennullstr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strtof else if(TestStepName() == Kstrtofbasic) { INFO_PRINTF1(_L("strtofbasic():")); err = strtofbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtofexpntn) { INFO_PRINTF1(_L("strtofexpntn():")); err = strtofexpntn(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtofsignedexpntn) { INFO_PRINTF1(_L("strtofsignedexpntn():")); err = strtofsignedexpntn(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtofinfinity) { INFO_PRINTF1(_L("strtofinfinity():")); err = strtofinfinity(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtofnan) { INFO_PRINTF1(_L("strtofnan():")); err = strtofnan(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strtoimax else if(TestStepName() == Kstrtoimaxbasic) { INFO_PRINTF1(_L("strtoimaxbasic():")); err = strtoimaxbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoimaxspacecheck) { INFO_PRINTF1(_L("strtoimaxspacecheck():")); err = strtoimaxspacecheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoimaxsignedsrc) { INFO_PRINTF1(_L("strtoimaxsignedsrc():")); err = strtoimaxsignedsrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoimaxoctalcheck) { INFO_PRINTF1(_L("strtoimaxoctalcheck():")); err = strtoimaxoctalcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoimaxhexcheck) { INFO_PRINTF1(_L("strtoimaxhexcheck():")); err = strtoimaxhexcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strtoumax else if(TestStepName() == Kstrtoumaxbasic) { INFO_PRINTF1(_L("strtoumaxbasic():")); err = strtoumaxbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoumaxspacecheck) { INFO_PRINTF1(_L("strtoumaxspacecheck():")); err = strtoumaxspacecheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoumaxoctalcheck) { INFO_PRINTF1(_L("strtoumaxoctalcheck():")); err = strtoumaxoctalcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoumaxhexcheck) { INFO_PRINTF1(_L("strtoumaxhexcheck():")); err = strtoumaxhexcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strtold else if(TestStepName() == Kstrtoldbasic) { INFO_PRINTF1(_L("strtoldbasic():")); err = strtoldbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoldexpntn) { INFO_PRINTF1(_L("strtoldexpntn():")); err = strtoldexpntn(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoldsignedexpntn) { INFO_PRINTF1(_L("strtoldsignedexpntn():")); err = strtoldsignedexpntn(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoldinfinity) { INFO_PRINTF1(_L("strtoldinfinity():")); err = strtoldinfinity(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoldnan) { INFO_PRINTF1(_L("strtoldnan():")); err = strtoldnan(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strtoll else if(TestStepName() == Kstrtollbasic) { INFO_PRINTF1(_L("strtollbasic():")); err = strtollbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtollspacecheck) { INFO_PRINTF1(_L("strtollspacecheck():")); err = strtollspacecheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtollsignedsrc) { INFO_PRINTF1(_L("strtollsignedsrc():")); err = strtollsignedsrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtolloctalcheck) { INFO_PRINTF1(_L("strtolloctalcheck():")); err = strtolloctalcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtollhexcheck) { INFO_PRINTF1(_L("strtollhexcheck():")); err = strtollhexcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //strtoull else if(TestStepName() == Kstrtoullbasic) { INFO_PRINTF1(_L("strtoullbasic():")); err = strtoullbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoullspacecheck) { INFO_PRINTF1(_L("strtoullspacecheck():")); err = strtoullspacecheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoulloctalcheck) { INFO_PRINTF1(_L("strtoulloctalcheck():")); err = strtoulloctalcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoullhexcheck) { INFO_PRINTF1(_L("strtoullhexcheck():")); err = strtoullhexcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } //swab else if(TestStepName() == Kswabbasic) { INFO_PRINTF1(_L("swabbasic():")); err = swabbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoqbasic) { INFO_PRINTF1(_L("strtoqbasic():")); err = strtoqbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoqspacecheck) { INFO_PRINTF1(_L("strtoqspacecheck():")); err = strtoqspacecheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoqsignedsrc) { INFO_PRINTF1(_L("strtoqsignedsrc():")); err = strtoqsignedsrc(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoqoctalcheck) { INFO_PRINTF1(_L("strtoqoctalcheck():")); err = strtoqoctalcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtoqhexcheck) { INFO_PRINTF1(_L("strtoqhexcheck():")); err = strtoqhexcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtouqbasic) { INFO_PRINTF1(_L("strtouqbasic():")); err = strtouqbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtouqspacecheck) { INFO_PRINTF1(_L("strtouqspacecheck():")); err = strtouqspacecheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtouqoctalcheck) { INFO_PRINTF1(_L("strtouqoctalcheck():")); err = strtouqoctalcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrtouqhexcheck) { INFO_PRINTF1(_L("strtouqhexcheck():")); err = strtouqhexcheck(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrxfrmbasic) { INFO_PRINTF1(_L("strxfrmbasic():")); err = strxfrmbasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrptimebasic) { INFO_PRINTF1(_L("strptimebasic():")); err = strptimebasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrftimebasic) { INFO_PRINTF1(_L("strftimebasic():")); err = strftimebasic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrptime_arabic) { INFO_PRINTF1(_L("strptime_arabic():")); err = strptime_arabic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrptime_heutf) { INFO_PRINTF1(_L("strptime_heutf():")); err = strptime_heutf(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrftime_arabic) { INFO_PRINTF1(_L("strftime_arabic():")); err = strftime_arabic(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrftime_heutf) { INFO_PRINTF1(_L("strftime_heutf():")); err = strftime_heutf(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrftime_timezone) { INFO_PRINTF1(_L("strftime_timezone():")); err = strftime_timezone(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrtok_r) { INFO_PRINTF1(_L("TestStrtok_r():")); err = TestStrtok_r(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrnstr) { INFO_PRINTF1(_L("TestStrnstr():")); err = TestStrnstr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrcasestr) { INFO_PRINTF1(_L("TestStrcasestr():")); err = TestStrcasestr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestMemccpy) { INFO_PRINTF1(_L("TestMemccpy():")); err = TestMemccpy(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStpcpy) { INFO_PRINTF1(_L("TestStpcpy():")); err = TestStpcpy(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestWcsColl) { INFO_PRINTF1(_L("TestWcsColl():")); err = TestWcsColl(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstWcsCollUnlikestr1) { INFO_PRINTF1(_L("TstWcsCollUnlikestr1():")); err = TstWcsCollUnlikestr1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstWcsCollUnlikestr2) { INFO_PRINTF1(_L("TstWcsCollUnlikestr2():")); err = TstWcsCollUnlikestr2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstWcsxfrm) { INFO_PRINTF1(_L("TstWcsxfrm():")); err = TstWcsxfrm(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstWcsxfrmErr) { INFO_PRINTF1(_L("TstWcsxfrmErr():")); err = TstWcsxfrmErr(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstStrdup) { INFO_PRINTF1(_L("TstStrdup():")); err = TstStrdup(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstStrndup) { INFO_PRINTF1(_L("TstStrndup():")); err = TstStrndup(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstWcsdup) { INFO_PRINTF1(_L("TstWcsdup():")); err = TstWcsdup(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstWcsdup) { INFO_PRINTF1(_L("TstWcsdup():")); err = TstWcsdup(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstStrsep) { INFO_PRINTF1(_L("TstStrsep():")); err = TstStrsep(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstldexp) { INFO_PRINTF1(_L("Tstldexp():")); err = Tstldexp(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrptimebasic1) { INFO_PRINTF1(_L("strptimebasic1():")); err = strptimebasic1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestmemchr_specialchars) { INFO_PRINTF1(_L("Testmemchr_specialchars():")); err = Testmemchr_specialchars(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrlcatBasictest) { INFO_PRINTF1(_L("strlcatBasictest():")); err = strlcatBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrcasestr1) { INFO_PRINTF1(_L("TestStrcasestr1():")); err = TestStrcasestr1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kffsbasic1) { INFO_PRINTF1(_L("ffsbasic1():")); err = ffsbasic1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrnstr1) { INFO_PRINTF1(_L("TestStrnstr1():")); err = TestStrnstr1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrnstr2) { INFO_PRINTF1(_L("TestStrnstr2():")); err = TestStrnstr2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrnstr3) { INFO_PRINTF1(_L("TestStrnstr3():")); err = TestStrnstr3(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrncasecmp) { INFO_PRINTF1(_L("TestStrncasecmp():")); err = TestStrncasecmp(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrncasecmp1) { INFO_PRINTF1(_L("TestStrncasecmp1():")); err = TestStrncasecmp1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestMemccpy1) { INFO_PRINTF1(_L("TestMemccpy1():")); err = TestMemccpy1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrncattest1) { INFO_PRINTF1(_L("strncattest1():")); err = strncattest1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kbcopyfuncheck1) { INFO_PRINTF1(_L("bcopyfuncheck1():")); err = bcopyfuncheck1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrlcpyBasictest) { INFO_PRINTF1(_L("strlcatBasictest():")); err = strlcpyBasictest(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrlcpyBasictest1) { INFO_PRINTF1(_L("strlcatBasictest1():")); err = strlcpyBasictest1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KStrlcatBasictest1) { INFO_PRINTF1(_L("strlcatBasictest1():")); err = strlcatBasictest1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstWcsxfrm1) { INFO_PRINTF1(_L("TstWcsxfrm1():")); err = TstWcsxfrm1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstWcsxfrm2) { INFO_PRINTF1(_L("TstWcsxfrm2():")); err = TstWcsxfrm2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstWcsxfrm3) { INFO_PRINTF1(_L("TstWcsxfrm3():")); err = TstWcsxfrm3(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstStrdup2) { INFO_PRINTF1(_L("TstStrdup2():")); err = TstStrdup2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstStrerr_r) { INFO_PRINTF1(_L("TstStrerr_r():")); err = TstStrerr_r(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTstStrerr_r1) { INFO_PRINTF1(_L("TstStrerr_r1():")); err = TstStrerr_r1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrcasestr2) { INFO_PRINTF1(_L("TestStrcasestr2():")); err = TestStrcasestr2(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrnstr4) { INFO_PRINTF1(_L("TestStrnstr4():")); err = TestStrnstr4(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kstrxfrmbasic1) { INFO_PRINTF1(_L("strxfrmbasic1():")); err = strxfrmbasic1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrptime_test) { INFO_PRINTF1(_L("TestStrptime_test():")); err = TestStrptime_test(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestStrptime_test1) { INFO_PRINTF1(_L("TestStrptime_test1():")); err = TestStrptime_test1(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } return TestStepResult(); } // ----------------------------------------------------------------------------- // CTestString::compare // CTestString::validate // are supporting function for the test // ----------------------------------------------------------------------------- // TInt CTestString::compare (const char *a, const char *b) { return validate(a != NULL && b != NULL && (strcmp((a), (b)) == 0)); } TInt CTestString::validate (int thing) { if (!thing) { return -1; } else { return KErrNone; } } // ----------------------------------------------------------------------------- // CTestString::Basictest // ----------------------------------------------------------------------------- // TInt CTestString::memcpyBasicTest() { char ch[50]; (void) strcpy(ch, "abcdefgh"); (void) memcpy(ch+1, "xyz", 2); return compare(ch, "axydefgh"); } // ----------------------------------------------------------------------------- // CTestString::TestString // ----------------------------------------------------------------------------- // TInt CTestString::memcpyTestZeroLengthCopy() { char ch[50]; (void) strcpy(ch, "abc"); (void) memcpy(ch, "xyz", 0); return compare(ch, "abc"); } // 2. memmove TInt CTestString::memmoveBasictest() { char ch[50]; //STEP 1 (void) strcpy(ch, "abcdefgh"); (void) memmove(ch+1, "xyz", 2); return compare(ch, "axydefgh"); /* Basic test. */ } TInt CTestString::memmoveZeroLength() { char ch[50]; //STEP 2 (void) strcpy(ch, "abc"); (void) memmove(ch, "xyz", 0); return compare(ch, "abc"); /* Zero-length copy. */ } TInt CTestString::memmoveOverlap() { char ch[50]; //STEP 3 (void) strcpy(ch, "abcdefgh"); (void) memmove(ch+1, ch, 9); return compare(ch, "aabcdefgh"); /* Overlap, right-to-left. */ } // 3. strcpy TInt CTestString::strcpyBasictest() { char ch[50]; int retval; //STEP 1 retval = validate (strcpy (ch, "abcd") == ch); /* Returned value. */ if (retval == KErrNone) { retval = compare (ch, "abcd"); /* Basic test. */ } return retval; } TInt CTestString::strcpyWriteOver() { char ch[50]; int retval; //STEP 2 (void) strcpy (ch, "abcd"); (void) strcpy (ch, "x"); retval = compare (ch, "x"); /* Writeover. */ if (retval == KErrNone) { retval = compare (ch+2, "cd"); /* Wrote too much? */ } return retval; } TInt CTestString::strcpyBoundry() { char ch[50]; //STEP 3 (void) strcpy (ch, ""); return compare (ch, ""); /* Boundary condition. */ } // 4. strncpy TInt CTestString::strncpyBasictest() { char ch[50]; int retval; //STEP 1 retval = validate (strncpy (ch, "abc", 4) == ch); /* Returned value. */ if (retval == KErrNone) { retval = compare (ch, "abc"); /* Did the copy go right? */ } return retval; } TInt CTestString::strncpyCutCnt() { char ch[50]; //STEP 2 (void) strcpy (ch, "abcdefgh"); (void) strncpy (ch, "xyz", 2); return compare (ch, "xycdefgh"); /* Copy cut by count. */ } TInt CTestString::strncpyCutNul() { char ch[50]; //STEP 3 (void) strcpy (ch, "abcdefgh"); (void) strncpy (ch, "xyz", 3); /* Copy cut just before NUL. */ return compare (ch, "xyzdefgh"); } TInt CTestString::strncpyNulInc() { char ch[50]; int retval; //STEP 4 (void) strcpy (ch, "abcdefgh"); (void) strncpy (ch, "xyz", 4); /* Copy just includes NUL. */ retval = compare (ch, "xyz"); if (retval == KErrNone) { retval = compare (ch+4, "efgh"); /* Wrote too much? */ } return retval; } TInt CTestString::strncpyZeroLen() { char ch[50]; //STEP 5 (void) strcpy (ch, "abc"); (void) strncpy (ch, "xyz", 0); /* Zero-length copy. */ return compare (ch, "abc"); } TInt CTestString::strncpyZeroSrc() { char ch[50]; int retval; //STEP 6 (void) strncpy (ch, "", 2); /* Zero-length source. */ retval = compare (ch, ""); if (retval == KErrNone) { retval = compare (ch+1, ""); } if (retval == KErrNone) { retval = compare (ch+2, "c"); if (retval<0) { retval = KErrNone; //This is a negative test case. So return Success } } return retval; } // 5. strcat TInt CTestString::strcatBasictest() { char ch[50]; int retval; //STEP 1 (void) strcpy (ch, "ijk"); retval = validate (strcat (ch, "lmn") == ch); /* Returned value. */ if (retval == KErrNone) { retval = compare (ch, "ijklmn"); /* Basic test. */ } return retval; } TInt CTestString::strcatBoundry() { char ch[50]; int retval; //STEP 2 (void) strcpy (ch, ""); (void) strcat (ch, ""); retval = compare (ch, ""); /* Boundary conditions. */ if (retval == KErrNone) { (void) strcpy (ch, "ab"); (void) strcat (ch, ""); retval = compare (ch, "ab"); if (retval == KErrNone) { (void) strcpy (ch, ""); (void) strcat (ch, "cd"); retval = compare (ch, "cd"); } } return retval; } TInt CTestString::strcatMemset() { char ch[50]; (void) strcpy (ch, "abcdefgh"); (void) memset(ch+3, 0, 1); (void) strcat(ch, "ijkl"); return compare(ch, "abcijkl"); } // 6. strncat TInt CTestString::strncatBasictest() { char ch[50]; int retval; //STEP 1 (void) strcpy (ch, "ijk"); retval = validate (strncat (ch, "lmn", 99) == ch); /* Returned value. */ if (retval == KErrNone) { retval = compare (ch, "ijklmn"); /* Basic test. */ } return retval; } TInt CTestString::strncatBoundry() { int retval; char ch[50]; //STEP 2 (void) strcpy (ch, ""); (void) strncat (ch, "", 99); retval = compare (ch, ""); /* Boundary conditions. */ if (retval == KErrNone) { (void) strcpy (ch, "ab"); (void) strncat (ch, "", 99); retval = compare (ch, "ab"); if (retval == KErrNone) { (void) strcpy (ch, ""); (void) strncat (ch, "cd", 99); retval = compare (ch, "cd"); } } return retval; } TInt CTestString::strncatMemset() { char ch[50]; (void) strcpy (ch, "abcdefgh"); (void) memset(ch+3, 0, 1); (void) strncat(ch, "ijkl", 100); return compare(ch, "abcijkl"); } // 7. memcmp TInt CTestString::memcmpBasictest() { int retval; //STEP 1 retval = validate(memcmp("a", "a", 1) == 0); /* Identity. */ if (retval == KErrNone) { retval = validate(memcmp("abc", "abc", 3) == 0); /* Multicharacter. */ } return retval; } TInt CTestString::memcmpUnequal() { int retval; //STEP 2 retval = validate(memcmp("abcd", "abce", 4) < 0); /* Honestly unequal. */ if (retval == KErrNone) { retval = validate(memcmp("abce", "abcd", 4) > 0); } return retval; } TInt CTestString::memcmpLtdCount() { //STEP 3 return validate(memcmp("abce", "abcd", 3) == 0); /* Count limited. */ } TInt CTestString::memcmpZeroCount() { //STEP 4 return validate(memcmp("abc", "def", 0) == 0); /* Zero count. */ } // 8. strcmp TInt CTestString::strcmpBasictest() { int retval; //STEP 1 retval = validate (strcmp ("a", "a") == 0); /* Identity. */ if (retval == KErrNone) { retval = validate (strcmp ("abc", "abc") == 0); /* Multicharacter. */ } return retval; } TInt CTestString::strcmpMisMatchStrAndLen() { int retval; //STEP 2 retval = validate (strcmp ("abc", "abcd") < 0); /* Length mismatches. */ if (retval == KErrNone) { retval = validate (strcmp ("abcd", "abc") > 0); } if (retval == KErrNone) { retval = validate (strcmp ("abcd", "abce") < 0); /* Honest miscompares. */ } if (retval == KErrNone) { retval = validate (strcmp ("abce", "abcd") > 0); } return retval; } // 9. strncmp TInt CTestString::strncmpBasictest() { int retval; //STEP 1 retval = validate (strncmp ("a", "a", 99) == 0); /* Identity. */ if (retval == KErrNone) { retval = validate (strncmp ("abc", "abc", 99) == 0); /* Multicharacter. */ } return retval; } TInt CTestString::strncmpMisMatchStrAndLen() { int retval; //STEP 2 retval = validate (strncmp ("abc", "abcd", 99) < 0); /* Length unequal. */ if (retval == KErrNone) { retval = validate (strncmp ("abcd", "abc", 99) > 0); } if (retval == KErrNone) { retval = validate (strncmp ("abcd", "abce", 99) < 0); /* Honestly unequal. */ } if (retval == KErrNone) { retval = validate (strncmp ("abce", "abcd", 99) > 0); } return retval; } TInt CTestString::strncmpCountCheck() { int retval; retval = validate (strncmp ("abce", "abcd", 3) == 0); /* Count limited. */ if (retval == KErrNone) { retval = validate (strncmp ("abce", "abc", 3) == 0); /* Count == length. */ } if (retval == KErrNone) { retval = validate (strncmp ("abc", "def", 0) == 0); /* Zero count. */ } return retval; } TInt CTestString::strcollBasictest() { int retval = KErrNone; retval = strcoll("Strasse", "Strasse"); if (retval) { INFO_PRINTF2(_L("FAILURE, error = %d"), retval); } return retval; } TInt CTestString::srxfrmBasictest() { char to1[8], to2[8]; int retval = 0; int maxsize = 100; strxfrm(to1, "Strasse", maxsize); to1[7] = '\0'; strxfrm(to2, "Strasse", maxsize); to2[7] = '\0'; retval = strcmp(to1, to2); if (retval) { INFO_PRINTF2(_L("FAILURE, error = %d"), retval); } return retval; } TInt CTestString::memchrNotFound() { return validate(memchr("abcd", 'z', 4) == NULL); /* Not found. */ } TInt CTestString::memchrBasictest() { char ch[50]; (void) strcpy(ch, "abcd"); return validate(memchr(ch, 'c', 4) == ch+2); /* Basic test. */ } TInt CTestString::memchrFindNul() { char ch[50]; (void) strcpy(ch, "abcd"); return validate(memchr(ch, '\0', 5) == ch+4); /* Finding NUL. */ } TInt CTestString::memchrZeroCount() { return validate(memchr("abcd", 'b', 0) == NULL); /* Zero count. */ } // 13. strchr TInt CTestString::strchrNotFound() { //STEP 1 return validate (strchr ("abcd", 'z') == NULL); /* Not found. */ } TInt CTestString::strchrBasicTest() { char ch[50]; //STEP 2 (void) strcpy (ch, "abcd"); return validate (strchr (ch, 'c') == ch+2); /* Basic test. */ } TInt CTestString::strchrFindNul() { char ch[50]; //STEP 3 (void) strcpy (ch, "abcd"); return validate (strchr (ch, '\0') == ch+4); /* Finding NUL. */ } TInt CTestString::strchrFindFirst() { char ch[50]; //STEP 4 (void) strcpy (ch, "ababa"); return validate (strchr (ch, 'b') == ch+1); /* Finding first. */ } TInt CTestString::strchrEmptyString() { char ch[50]; //STEP 5 (void) strcpy (ch, ""); return validate (strchr (ch, 'b') == NULL); /* Empty string. */ } TInt CTestString::strchrNulEmptyStr() { char ch[50]; //STEP 6 (void) strcpy (ch, ""); return validate (strchr (ch, '\0') == ch); /* NUL in empty string. */ } // 14. strcspn TInt CTestString::strcspnWholeStr() { //STEP 1 return validate(strcspn("abcba", "qx") == 5); /* Whole string. */ } TInt CTestString::strcspnPartString() { //STEP 2 return validate(strcspn("abcba", "cx") == 2); /* Partial. */ } TInt CTestString::strcspnNone() { //STEP 3 return validate(strcspn("abc", "abc") == 0); /* None. */ } TInt CTestString::strcspnNullString() { //STEP 4 return validate(strcspn("", "ab") == 0); /* Null string. */ } TInt CTestString::strcspnNullSearch() { //STEP 5 return validate(strcspn("abc", "") == 3); /* Null search list. */ } // 15. strpbrk TInt CTestString::strpbrkNotFound() { //STEP 1 return validate(strpbrk("abcd", "z") == NULL); /* Not found. */ } TInt CTestString::strpbrkBasictest() { char ch[50]; //STEP 2 (void) strcpy(ch, "abcd"); return validate(strpbrk(ch, "cb") == ch+1); /* Basic test. */ } TInt CTestString::strpbrkEmptySearch() { char ch[50]; //STEP 3 (void) strcpy(ch, "abcd"); return validate(strpbrk(ch, "") == NULL); /* Empty search list. */ } TInt CTestString::strpbrkEmptyString() { char ch[50]; //STEP 4 (void) strcpy(ch, ""); return validate(strpbrk(ch, "bcde") == NULL); /* Empty string. */ } TInt CTestString::strpbrkBothEmpty() { char ch[50]; //STEP 5 (void) strcpy(ch, ""); return validate(strpbrk(ch, "") == NULL); /* Both strings empty. */ } TInt CTestString::strpbrkFindFirst() { char ch[50]; //STEP 6 (void) strcpy(ch, "abcabdea"); return validate(strpbrk(ch, "befg") == ch+1); /* Finding first. */ } // 16. strrchr TInt CTestString::strrchrNotfound() { //STEP 1 return validate (strrchr ("abcd", 'z') == NULL); /* Not found. */ } TInt CTestString::strrchrBasictest() { char ch[50]; //STEP 2 (void) strcpy (ch, "abcd"); return validate (strrchr (ch, 'c') == ch+2); /* Basic test. */ } TInt CTestString::strrchrFindNul() { char ch[50]; (void) strcpy (ch, "abcd"); return validate (strrchr (ch, '\0') == ch+4); /* Finding NUL. */ } TInt CTestString::strrchrFindLast() { char ch[50]; //STEP 4 (void) strcpy (ch, "ababa"); return validate (strrchr (ch, 'b') == ch+3); /* Finding last. */ } TInt CTestString::strrchrEmptyStr() { char ch[50]; //STEP 5 (void) strcpy (ch, ""); return validate (strrchr (ch, 'b') == NULL); /* Empty string. */ } TInt CTestString::strrchrEmptyNul() { char ch[50]; //STEP 6 (void) strcpy (ch, ""); return validate (strrchr (ch, '\0') == ch); /* NUL in empty string. */ } // 17. strspn TInt CTestString::strspnWholeStr() { //STEP 1 return validate(strspn("abcba", "abc") == 5); /* Whole string. */ } TInt CTestString::strspnPartial() { return validate(strspn("abcba", "ab") == 2); /* Partial. */ } TInt CTestString::strspnNone() { return validate(strspn("abc", "qx") == 0); /* None. */ } TInt CTestString::strspnNulStr() { return validate(strspn("", "ab") == 0); /* Null string. */ } TInt CTestString::strspnNulSearch() { return validate(strspn("abc", "") == 0); /* Null search list. */ } // 18. strstr TInt CTestString::strstrNotFound() { return validate(strstr("abcd", "z") == NULL); /* Not found. */ } TInt CTestString::strstrBasictest() { char ch[50]; (void) strcpy(ch, "abcd"); return validate(strstr(ch, "bc") == ch+1); /* Basic test. */ } TInt CTestString::strstrLong() { char ch[50]; (void) strcpy(ch, "abcd"); return validate(strstr(ch, "abcde") == NULL); /* Too long. */ } TInt CTestString::strstrFindEmpty() { char ch[50]; (void) strcpy(ch, "abcd"); return validate(strstr(ch, "") == ch); /* Finding empty. */ } TInt CTestString::strstrEmptyStr() { char ch[50]; (void) strcpy(ch, ""); return validate(strstr(ch, "b") == NULL); /* Empty string. */ } TInt CTestString::strstrEmpty() { char ch[50]; (void) strcpy(ch, ""); return validate(strstr(ch, "") == ch); /* Empty in empty string. */ } // 19. strtok TInt CTestString::strtokBasictest() { char ch[50]; int retval; (void) strcpy(ch, "first, second, third"); retval = compare(strtok(ch, ", "), "first"); /* Basic test. */ if (retval == KErrNone) { retval = compare(ch, "first"); } if (retval == KErrNone) { retval = compare(strtok((char *)NULL, ", "), "second"); } if (retval == KErrNone) { retval = compare(strtok((char *)NULL, ", "), "third"); } if (retval == KErrNone) { retval = validate(strtok((char *)NULL, ", ") == NULL); } return retval; } TInt CTestString::strtokDelim() { char ch[50]; int retval; (void) strcpy(ch, ", first, "); retval = compare(strtok(ch, ", "), "first"); /* Extra delims, 1 tok. */ if (retval == KErrNone) { retval = validate(strtok((char *)NULL, ", ") == NULL); } return retval; } TInt CTestString::strtokChangeDelim() { char ch[50]; int retval; (void) strcpy(ch, "1a, 1b; 2a, 2b"); retval = compare(strtok(ch, ", "), "1a"); /* Changing delim lists. */ if (retval == KErrNone) { retval = compare(strtok((char *)NULL, "; "), "1b"); } if (retval == KErrNone) { retval = compare(strtok((char *)NULL, ", "), "2a"); } return retval; } TInt CTestString::strtokNewStr() { char ch[50]; int retval; (void) strcpy(ch, "x-y"); retval = compare(strtok(ch, "-"), "x"); /* New string before done. */ if (retval == KErrNone) { retval = compare(strtok((char *)NULL, "-"), "y"); } if (retval == KErrNone) { retval = validate(strtok((char *)NULL, "-") == NULL); } return retval; } TInt CTestString::strtokDiffSap() { char ch[50]; int retval; (void) strcpy(ch, "a,b, c,, ,d"); retval = compare(strtok(ch, ", "), "a"); /* Different separators. */ if (retval == KErrNone) { retval = compare(strtok((char *)NULL, ", "), "b"); } if (retval == KErrNone) { retval = compare(strtok((char *)NULL, " ,"), "c"); /* Permute list too. */ } if (retval == KErrNone) { retval = compare(strtok((char *)NULL, " ,"), "d"); } if (retval == KErrNone) { retval = validate(strtok((char *)NULL, ", ") == NULL); } if (retval == KErrNone) { retval = validate(strtok((char *)NULL, ", ") == NULL); /* Persistence. */ } return retval; } TInt CTestString::strtokNoTok() { char ch[50]; (void) strcpy(ch, ", "); return validate(strtok(ch, ", ") == NULL); /* No tokens. */ } TInt CTestString::strtokEmptyStr() { char ch[50]; (void) strcpy(ch, ""); return validate(strtok(ch, ", ") == NULL); /* Empty string. */ } TInt CTestString::strtokNoDelim() { char ch[50]; int retval; (void) strcpy(ch, "abc"); retval = compare(strtok(ch, ", "), "abc"); /* No delimiters. */ if (retval == KErrNone) { retval = validate(strtok((char *)NULL, ", ") == NULL); } return retval; } TInt CTestString::strtokEmptyDelim() { char ch[50]; int retval; (void) strcpy(ch, "abc"); retval = compare(strtok(ch, ""), "abc"); /* Empty delimiter list. */ if (retval == KErrNone) { retval = validate(strtok((char *)NULL, "") == NULL); } return retval; } // 20. memset TInt CTestString::memsetBasictest() { int retval; char ch[50]; //STEP 1 (void) strcpy(ch, "abcdefgh"); retval = validate(memset(ch+1, 'x', 3) == ch+1); /* Return value. */ if (retval == KErrNone) { retval = compare(ch, "axxxefgh"); /* Basic test. */ } return retval; } TInt CTestString::memsetZeroLen() { char ch[50]; //STEP 2 (void) strcpy(ch, "axxxefgh"); (void) memset(ch+2, 'y', 0); return compare(ch, "axxxefgh"); /* Zero-length set. */ } // 21. strerror TInt CTestString::strerrorBasictest() { return validate(strerror(ERANGE) != 0); } TInt CTestString::strerrorUnknown() { (void) strerror(-55555); //Don't know the outcome return KErrNone; } // 22. strlen TInt CTestString::strlenEmpty() { return validate (strlen ("") == 0); /* Empty. */ } TInt CTestString::strlenSingleChar() { return validate (strlen ("a") == 1); /* Single char. */ } TInt CTestString::strlenMultiChar() { return validate (strlen ("abcd") == 4); /* Multiple chars. */ } // ----------------------------------------------------------------------------- // CTestString::bcmpsameargs // <src file name : bcmp.c> // validate for byte comparison for same strings // ----------------------------------------------------------------------------- TInt CTestString::bcmpsameargs() { return validate (bcmp("a","a",1)==0); } // ----------------------------------------------------------------------------- // CTestString::bcmpdiffargs // <src file name : bcmp.c> // validate for byte comparison for different strings // ----------------------------------------------------------------------------- TInt CTestString::bcmpdiffargs() { return validate (bcmp("abcd","abce",4)!=0); } // ----------------------------------------------------------------------------- // CTestString::bcmpzerocnt // <src file name : bcmp.c> // validate for byte comparison for different strings but zero count // ----------------------------------------------------------------------------- TInt CTestString::bcmpzerocnt() { return validate (bcmp("abc","xyz",0)==0); } // ----------------------------------------------------------------------------- // CTestString::bcopyfuncheck // <src file name : bcopy.c> // validate for byte copy of known src string // ----------------------------------------------------------------------------- TInt CTestString::bcopyfuncheck() { char ch[50]; bcopy("abc",ch,4); return compare(ch,"abc"); } // ----------------------------------------------------------------------------- // CTestString::bcopybasic // <src file name : bcopy.c> // validate for byte copy of known src string in middle of another string // ----------------------------------------------------------------------------- TInt CTestString::bcopybasic() { char ch[50]; strcpy(ch, "abcdefgh"); bcopy("xyz", ch + 1, 2); return compare(ch, "axydefgh"); /* Basic test. */ } // ----------------------------------------------------------------------------- // CTestString::bcopyzerocopy // <src file name : bcopy.c> // validate for byte copy of known src string but with zero reference count // ----------------------------------------------------------------------------- TInt CTestString::bcopyzerocopy() { char ch[50]; strcpy(ch, "abc"); bcopy("xyz", ch, 0); return compare(ch, "abc"); } // ----------------------------------------------------------------------------- // CTestString::bcopysrcconst // <src file name : bcopy.c> // validate for byte copy of known src string and validate for src constantness // ----------------------------------------------------------------------------- TInt CTestString::bcopysrcconst() { char ch[50],two[50]; strcpy(ch, "hi there"); strcpy(two, "foo"); bcopy(ch, two, 9); return compare(ch, "hi there"); } // ----------------------------------------------------------------------------- // CTestString::bcopynullsrc // <src file name : bcopy.c> // validate for byte copy of null src string // ----------------------------------------------------------------------------- TInt CTestString::bcopynullsrc() { char ch[50]; strcpy(ch, "hi there"); bcopy("",ch,3); return compare(ch,""); } // ----------------------------------------------------------------------------- // CTestString::bcopyoverlap // <src file name : bcopy.c> // validate for byte copy of known overlapping string // ----------------------------------------------------------------------------- TInt CTestString::bcopyoverlap() { char ch[50], * two; strcpy(ch,"abcde"); two=ch+2; bcopy(ch,two,4); *(two+4)='\0'; if(strcmp(two,"abcd")) return KErrGeneral; if(strcmp(ch,"ababcd")) return KErrGeneral; return KErrNone; } // ----------------------------------------------------------------------------- // CTestString::strsepbasic // <src file name : strsep.c> // validate for finding tokens delimited by a delimiter list // ----------------------------------------------------------------------------- TInt CTestString::strsepbasic() { TInt tres=KErrNone; char *temp; char *ch=(char *)malloc (12); strcpy(ch,"hello,world"); temp = ch; char *res; res=strsep(&ch,","); if(strcmp(res,"hello")) tres=KErrGeneral; free(temp); return tres; } // ----------------------------------------------------------------------------- // CTestString::strsepsrccheck // <src file name : strsep.c> // validate for finding tokens delimited by a delimiter list and checking for src // ----------------------------------------------------------------------------- TInt CTestString::strsepsrccheck() { TInt tres=KErrNone; char *ch=(char *)User::Alloc(12); char *temp; strcpy(ch,"hello,world"); temp = ch; strsep(&ch,","); if(strcmp(ch,"world")) tres=KErrGeneral; User::Free(temp); return tres; } // ----------------------------------------------------------------------------- // CTestString::bzerobasic // <src file name : bzero.c> // validate for setting of zero's in known string for known locations // ----------------------------------------------------------------------------- TInt CTestString::bzerobasic() { TInt res=KErrNone; char ch[50]; strcpy(ch, "abcdef"); bzero(ch + 2, 2); if(strcmp(ch, "ab")) { res=KErrGeneral; } if(strcmp(ch+3, "")) { res=KErrGeneral; } if(strcmp(ch + 4, "ef")) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::bzeronocopy // <src file name : bzero.c> // validate for setting of zero's but with zero length specified // ----------------------------------------------------------------------------- TInt CTestString::bzeronocopy() { char ch[50]; strcpy(ch, "abcdef"); bzero(ch + 2, 0); return compare(ch, "abcdef"); } // ----------------------------------------------------------------------------- // CTestString::ffsbasic // <src file name : ffs.c> // validate for first bit which is set with a initialized number // ----------------------------------------------------------------------------- TInt CTestString::ffsbasic() { TInt res=KErrNone; int i=0x10; int j=ffs(i); if(j!=5) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::indexbasic // <src file name : index.c> // validate for index of first occurence of given character in a given string // ----------------------------------------------------------------------------- TInt CTestString::indexbasic() { char ch[50]; strcpy(ch,"abcd"); return validate(index(ch, 'c') == ch + 2); } // ----------------------------------------------------------------------------- // CTestString::indexnotfound // <src file name : index.c> // validate for index of first occurence of character not a present in a given string // ----------------------------------------------------------------------------- TInt CTestString::indexnotfound() { char ch[50]; strcpy(ch,"abcd"); return validate(index(ch, 'z') == NULL); } // ----------------------------------------------------------------------------- // CTestString::indexend // <src file name : index.c> // validate for index of last occurence of character present in a given string // ----------------------------------------------------------------------------- TInt CTestString::indexend() { char ch[50]; strcpy(ch,"abcd"); return validate(index(ch, 'd') == ch+3); } // ----------------------------------------------------------------------------- // CTestString::indexfindnull // <src file name : index.c> // validate for index of \0 present in a given string // ----------------------------------------------------------------------------- TInt CTestString::indexfindnull() { char ch[50]; strcpy(ch,"abcd"); return validate(index(ch, '\0') == ch+4); } // ----------------------------------------------------------------------------- // CTestString::indexbeginning // <src file name : index.c> // validate for index of first character present in a given string // ----------------------------------------------------------------------------- TInt CTestString::indexbeginning() { char ch[50]; strcpy(ch,"abcd"); return validate(index(ch, 'a') == ch); } // ----------------------------------------------------------------------------- // CTestString::indexnullsrc // <src file name : index.c> // validate for index of character present in a null string // ----------------------------------------------------------------------------- TInt CTestString::indexnullsrc() { char ch[50]; strcpy(ch,""); return validate(index(ch, 'a') == NULL); } // ----------------------------------------------------------------------------- // CTestString::rindexbasic // <src file name : rindex.c> // validate for index of character present in a given string fromm the end // ----------------------------------------------------------------------------- TInt CTestString::rindexbasic() { char ch[50]; strcpy(ch,"cdcab"); return validate(rindex(ch, 'c') == ch + 2); } // ----------------------------------------------------------------------------- // CTestString::rindexnotfound // <src file name : rindex.c> // validate for index of character not present in a given string fromm the end // ----------------------------------------------------------------------------- TInt CTestString::rindexnotfound() { char ch[50]; strcpy(ch,"dcab"); return validate(rindex(ch, 'z') == NULL); } // ----------------------------------------------------------------------------- // CTestString::rindexend // <src file name : rindex.c> // validate for index of last character in a given string fromm the end // ----------------------------------------------------------------------------- TInt CTestString::rindexend() { char ch[50]; strcpy(ch,"dcab"); return validate(rindex(ch, 'b') == ch+3); } // ----------------------------------------------------------------------------- // CTestString::rindexfindnull // <src file name : rindex.c> // validate for index of \0 character in a given string fromm the end // ----------------------------------------------------------------------------- TInt CTestString::rindexfindnull() { char ch[50]; strcpy(ch,"dcab"); return validate(rindex(ch, '\0') == ch+4); } // ----------------------------------------------------------------------------- // CTestString::rindexbeginning // <src file name : rindex.c> // validate for index of first character in a given string fromm the end // ----------------------------------------------------------------------------- TInt CTestString::rindexbeginning() { char ch[50]; strcpy(ch,"dcab"); return validate(rindex(ch, 'd') == ch); } // ----------------------------------------------------------------------------- // CTestString::rindexnullsrc // <src file name : rindex.c> // validate for index of given character in a null string fromm the end // ----------------------------------------------------------------------------- TInt CTestString::rindexnullsrc() { char ch[50]; strcpy(ch,""); return validate(rindex(ch, 'a') == NULL); } // ----------------------------------------------------------------------------- // CTestString::memcpybasic // <src file name : memcpy.c> // validate for copying of characters from ch string to another location // ----------------------------------------------------------------------------- TInt CTestString::memcpybasic() { char ch[50]; strcpy(ch, "abcdefgh"); memcpy(ch + 1, "xyz", 2); return compare(ch, "axydefgh"); } // ----------------------------------------------------------------------------- // CTestString::memcpyzerolength // <src file name : memcpy.c> // validate for copying of characters from ch string to another but with zero count // ----------------------------------------------------------------------------- TInt CTestString::memcpyzerolength() { char ch[50]; strcpy(ch, "abc"); memcpy(ch, "xyz", 0); return compare(ch, "abc"); } // ----------------------------------------------------------------------------- // CTestString::memcpysrcconstantness // <src file name : memcpy.c> // validate for constantness for source // ----------------------------------------------------------------------------- TInt CTestString::memcpysrcconstantness() { char ch[50],two[50]; strcpy(ch, "hi there"); strcpy(two, "foo"); memcpy(two, ch, 9); return compare(ch, "hi there"); } // ----------------------------------------------------------------------------- // CTestString::stpcpybasic // <src file name : stpcpy.c> // validate for appending of characters from ch string to another // ----------------------------------------------------------------------------- TInt CTestString::stpcpybasic() { TInt res=KErrNone; char *ch=new char[50] ,*buff=ch; ch=stpcpy(ch,"hello"); if(strcmp(buff,"hello")) { res=KErrGeneral; } stpcpy(ch," world"); if(strcmp(buff,"hello world")) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::strcasecmpcasecheck // <src file name : strcasecmp.c> // validate for comparison of two strings without regard of their case // ----------------------------------------------------------------------------- TInt CTestString::strcasecmpcasecheck() { TInt res=KErrNone; if(strcasecmp("ABC","abc")) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::strcasecmplargesrc // <src file name : strcasecmp.c> // validate for comparison of two strings without regard of their case with larger src // ----------------------------------------------------------------------------- TInt CTestString::strcasecmplargesrc() { TInt res=KErrNone; if(strcasecmp("abcde","abc")<=0) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::strcasecmpsmallsrc // <src file name : strcasecmp.c> // validate for comparison of two strings without regard of their case with smaller src // ----------------------------------------------------------------------------- TInt CTestString::strcasecmpsmallsrc() { TInt res=KErrNone; if(strcasecmp("abc","abcde")>=0) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::strncmpbasic // <src file name : strncmp.c> // validate for comparison of two strings with given count // ----------------------------------------------------------------------------- TInt CTestString::strncmpbasic() { TInt res=KErrNone; if(strncmp("abcde","abc",3)) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::strncmplargesrc // <src file name : strncmp.c> // validate for comparison of two strings with given count and larger src string // ----------------------------------------------------------------------------- TInt CTestString::strncmplargesrc() { TInt res=KErrNone; if(strncmp("abcde","abc",5)<=0) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::strncmpsmallsrc // <src file name : strncmp.c> // validate for comparison of two strings with given count and smaller src string // ----------------------------------------------------------------------------- TInt CTestString::strncmpsmallsrc() { TInt res=KErrNone; if(strncmp("abc","abcde",5)>=0) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::strcollbasic // <src file name : strcoll.c> // validate for comparison of two strings with particular locale set // ----------------------------------------------------------------------------- TInt CTestString::strcollbasic() { TInt res=KErrNone; setlocale(LC_ALL,"ar_AE.ISO-8859-6"); if(strcoll("abcde","abcde")) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::strcolllargesrc // <src file name : strcoll.c> // validate for comparison of two strings with particular locale set // ----------------------------------------------------------------------------- TInt CTestString::strcolllargesrc() { TInt res=KErrNone; setlocale(LC_ALL,"ar_AE.ISO-8859-6"); if(strcoll("abcde","abc")<=0) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::strcolllargesrc // <src file name : strcoll.c> // validate for comparison of two strings with particular locale set // ----------------------------------------------------------------------------- TInt CTestString::strcollsmallsrc() { TInt res=KErrNone; setlocale(LC_ALL,"ar_AE.ISO-8859-6"); if(strcoll("abc","abcde")>=0) { res=KErrGeneral; } return res; } // ----------------------------------------------------------------------------- // CTestString::strndupbasic // <src file name : strndup.c> // validate for duplication of given src string into another location with count specified // ----------------------------------------------------------------------------- TInt CTestString::strndupbasic() { int ret; char *dupbasic = strndup("abcde",3); if(!compare(dupbasic,"abc")) { ret = KErrNone; } else { ret = KErrGeneral; } free(dupbasic); return ret; } // ----------------------------------------------------------------------------- // CTestString::strnduplargecnt // <src file name : strndup.c> // validate for duplication of given src string into another location with count specified // and count is larger than length of src string // ----------------------------------------------------------------------------- TInt CTestString::strnduplargecnt() { int ret; char *duplarge = strndup("abcde",8); if(!compare(duplarge,"abcde")) { ret = KErrNone; } else { ret = KErrGeneral; } free(duplarge); return ret; } // ----------------------------------------------------------------------------- // CTestString::strndupequalcnt // <src file name : strndup.c> // validate for duplication of given src string into another location with count specified // and count is compare to length of src string // ----------------------------------------------------------------------------- TInt CTestString::strndupequalcnt() { int ret; char *dupeql = strndup("abcde",5); if(!compare(dupeql,"abcde")) { ret = KErrNone; } else { ret = KErrGeneral; } free(dupeql); return ret; } // ----------------------------------------------------------------------------- // CTestString::strndupzerocnt // <src file name : strndup.c> // validate for duplication of given src string into another location with count specified // and count is zero // ----------------------------------------------------------------------------- TInt CTestString::strndupzerocnt() { int ret; char *dupzero = strndup("abcde",0); if(!compare(dupzero,"")) { ret = KErrNone; } else { ret = KErrGeneral; } free(dupzero); return ret; } // ----------------------------------------------------------------------------- // CTestString::strndupnullsrc // <src file name : strndup.c> // validate for duplication of given src string into another location with null // src string // ----------------------------------------------------------------------------- TInt CTestString::strndupnullsrc() { int ret; char *dupnull = strndup("",2); if(!compare(dupnull,"")) { ret = KErrNone; } else { ret = KErrGeneral; } free(dupnull); return ret; } // ----------------------------------------------------------------------------- // CTestString::strnlenbasic // <src file name : strnlen.c> // validate for length of given string with max specified count // ----------------------------------------------------------------------------- TInt CTestString::strnlenbasic() { TInt res=KErrNone; char ch[50]; strcpy(ch,"abcdef"); if(strnlen(ch,5)!=5) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strnlensmallstr // <src file name : strnlen.c> // validate for length of given string with max specified count larger than string length // ----------------------------------------------------------------------------- TInt CTestString::strnlensmallstr() { TInt res=KErrNone; char ch[50]; strcpy(ch,"abcdef"); if(strnlen(ch,10)!=6) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strnlennullstr // <src file name : strnlen.c> // validate for length of given null string with max specified count // ----------------------------------------------------------------------------- TInt CTestString::strnlennullstr() { TInt res=KErrNone; char ch[50]; strcpy(ch,""); if(strnlen(ch,10)!=0) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtofbasic // <src file name : strtof.c> // validate for given decimal number in string to float value // ----------------------------------------------------------------------------- TInt CTestString::strtofbasic() { TInt res=KErrGeneral; char *endp; float i=strtof("12.12",&endp); if(i==12.12||*endp=='\0') { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtofexpntn // <src file name : strtof.c> // validate for given decimal number in exponential notation in string to float value // ----------------------------------------------------------------------------- TInt CTestString::strtofexpntn() { TInt res=KErrGeneral; char *endp; float i=strtof("12e1",&endp); if(i==120||*endp=='\0') { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtofsignedexpntn // <src file name : strtof.c> // validate for given signed decimal number in exponential notation in string to float // value // ----------------------------------------------------------------------------- TInt CTestString::strtofsignedexpntn() { TInt res=KErrGeneral; char *endp; float i=strtof("12e-1",&endp); if(i==1.2||*endp=='\0') { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtofinfinity // <src file name : strtof.c> // validate for "INF" or infinity to appropriate value // ----------------------------------------------------------------------------- TInt CTestString::strtofinfinity() { TInt res=KErrGeneral; char *endp; float i=strtof("INF",&endp); if(*endp=='\0') { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtofnan // <src file name : strtof.c> // validate for "NAN" or not a number to appropriate value // ----------------------------------------------------------------------------- TInt CTestString::strtofnan() { TInt res=KErrGeneral; char *endp; float i=strtof("NAN",&endp); if(*endp=='\0') { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoimaxbasic // <src file name : strtoimax.c> // validate for given integer in string to intmax_t value // ----------------------------------------------------------------------------- TInt CTestString::strtoimaxbasic() { TInt res=KErrGeneral; char *endp; intmax_t i=strtoimax("12",&endp,10); if(i==12) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoimaxspacecheck // <src file name : strtoimax.c> // validate for given integer in string with initial spaces to intmax_t value // ----------------------------------------------------------------------------- TInt CTestString::strtoimaxspacecheck() { TInt res=KErrGeneral; char *endp; intmax_t i=strtoimax(" 9000",&endp,10); if(i==9000) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoimaxsignedsrc // <src file name : strtoimax.c> // validate for given integer in string with initial spaces and sign to intmax_t value // ----------------------------------------------------------------------------- TInt CTestString::strtoimaxsignedsrc() { TInt res=KErrGeneral; char *endp; intmax_t i=strtoimax(" -9000",&endp,10); if(i==-9000) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoimaxoctalcheck // <src file name : strtoimax.c> // validate for given integer in string octal representation to intmax_t value // ----------------------------------------------------------------------------- TInt CTestString::strtoimaxoctalcheck() { TInt res=KErrGeneral; char *endp; intmax_t i=strtoimax("010",&endp,8); if(i==8) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoimaxhexcheck // <src file name : strtoimax.c> // validate for given integer in string hexadecimal representation to intmax_t value // ----------------------------------------------------------------------------- TInt CTestString::strtoimaxhexcheck() { TInt res=KErrGeneral; char *endp; intmax_t i=strtoimax("0xa",&endp,16); if(i==10) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoumaxbasic // <src file name : strtoumax.c> // validate for given integer in string to uintmax_t value // ----------------------------------------------------------------------------- TInt CTestString::strtoumaxbasic() { TInt res=KErrGeneral; char *endp; uintmax_t i=strtoumax("12",&endp,10); if(i==12) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoumaxspacecheck // <src file name : strtoumax.c> // validate for given integer in string with initial spaces to uintmax_t value // ----------------------------------------------------------------------------- TInt CTestString::strtoumaxspacecheck() { TInt res=KErrGeneral; char *endp; uintmax_t i=strtoumax(" 9000",&endp,10); if(i==9000) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoumaxoctalcheck // <src file name : strtoumax.c> // validate for given integer in octal notation in string to uintmax_t value // ----------------------------------------------------------------------------- TInt CTestString::strtoumaxoctalcheck() { TInt res=KErrGeneral; char *endp; uintmax_t i=strtoumax("010",&endp,8); if(i==8) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoumaxhexcheck // <src file name : strtoumax.c> // validate for given integer in hexadecimal notation in string to uintmax_t value // ----------------------------------------------------------------------------- TInt CTestString::strtoumaxhexcheck() { TInt res=KErrGeneral; char *endp; uintmax_t i=strtoumax("0xa",&endp,16); if(i==10) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoldbasic // <src file name : strtold.c> // validate for given decimal in string to double value // ----------------------------------------------------------------------------- TInt CTestString::strtoldbasic() { TInt res=KErrGeneral; char *endp; long double i=strtold("12.12",&endp); if(i==12.12||*endp=='\0') { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoldexpntn // <src file name : strtold.c> // validate for given decimal in string in exponential notation to double value // ----------------------------------------------------------------------------- TInt CTestString::strtoldexpntn() { TInt res=KErrGeneral; char *endp; long double i=strtold("12e1",&endp); if(i==120||*endp=='\0') { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoldsignedexpntn // <src file name : strtold.c> // validate for given decimal in string in signed exponential notation to double value // ----------------------------------------------------------------------------- TInt CTestString::strtoldsignedexpntn() { TInt res=KErrGeneral; char *endp; long double i=strtold("12e-1",&endp); if(i==1.2||*endp=='\0') { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoldinfinity // <src file name : strtold.c> // validate for given "INF" or infinity to corresponding value // ----------------------------------------------------------------------------- TInt CTestString::strtoldinfinity() { TInt res=KErrGeneral; char *endp; long double i=strtold("INF",&endp); if(*endp=='\0') { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoldnan // <src file name : strtold.c> // validate for given "NAN" or not a number to corresponding value // ----------------------------------------------------------------------------- TInt CTestString::strtoldnan() { TInt res=KErrGeneral; char *endp; long double i=strtold("NAN",&endp); if(*endp=='\0') { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtollbasic // <src file name : strtoll.c> // validate for given long int in string to long long // ----------------------------------------------------------------------------- TInt CTestString::strtollbasic() { TInt res=KErrGeneral; char *endp; long long i=strtoll("999999999999990000",&endp,10); if(i==999999999999990000) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtollspacecheck // <src file name : strtoll.c> // validate for given long int in string with initial spaces to long long // ----------------------------------------------------------------------------- TInt CTestString::strtollspacecheck() { TInt res=KErrGeneral; char *endp; long long i=strtoll(" 999999999999990000",&endp,10); if(i==999999999999990000) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtollsignedsrc // <src file name : strtoll.c> // validate for given long int in string with initial spaces and sign to long long // ----------------------------------------------------------------------------- TInt CTestString::strtollsignedsrc() { TInt res=KErrGeneral; char *endp; long long i=strtoll(" -999999999999990000",&endp,10); if(i==-999999999999990000) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtolloctalcheck // <src file name : strtoll.c> // validate for given long int in octal notaion in string to long long // ----------------------------------------------------------------------------- TInt CTestString::strtolloctalcheck() { TInt res=KErrGeneral; char *endp; long long i=strtoll("010",&endp,8); if(i==8) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtollhexcheck // <src file name : strtoll.c> // validate for given long int in hex notaion in string to long long // ----------------------------------------------------------------------------- TInt CTestString::strtollhexcheck() { TInt res=KErrGeneral; char *endp; long long i=strtoll("0xa",&endp,16); if(i==10) { res=KErrNone; } return res; } // ----------------------------------------------------------------------------- // CTestString::strtoullbasic // <src file name : strtoll.c> // validate for given long int in hex notaion in string to long long // ----------------------------------------------------------------------------- TInt CTestString::strtoullbasic() { TInt res=KErrGeneral; char *endp; long long i=strtoull("900000",&endp,10); if(i==900000) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtoullspacecheck() { TInt res=KErrGeneral; char *endp; long long i=strtoull(" 900000",&endp,10); if(i==900000) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtoulloctalcheck() { TInt res=KErrGeneral; char *endp; long long i=strtoull("010",&endp,8); if(i==8) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtoullhexcheck() { TInt res=KErrGeneral; char *endp; long long i=strtoull("0xa",&endp,16); if(i==10) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::swabbasic() { TInt res = KErrGeneral; int i=0x00003366,j=0x0; swab((void *)&i,(void *)&j,2); if(j==0x6633) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtoqbasic() { INFO_PRINTF1(_L("CTestString::strtoqbasic")); TInt res=KErrGeneral; char *endp; quad_t i=strtoq("900000",&endp,10); if(i==900000) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtoqspacecheck() { INFO_PRINTF1(_L("CTestString::strtoqspacecheck")); TInt res=KErrGeneral; char *endp; quad_t i=strtoq(" 900000",&endp,10); if(i==900000) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtoqsignedsrc() { INFO_PRINTF1(_L("CTestString::strtoqsignedsrc")); TInt res=KErrGeneral; char *endp; quad_t i=strtoq(" -900000",&endp,10); if(i==-900000) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtoqoctalcheck() { INFO_PRINTF1(_L("CTestString::strtoqoctalcheck")); TInt res=KErrGeneral; char *endp; quad_t i=strtoq("010",&endp,8); if(i==8) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtoqhexcheck() { INFO_PRINTF1(_L("CTestString::strtoqhexcheck")); TInt res=KErrGeneral; char *endp; quad_t i=strtoq("0xa",&endp,16); if(i==10) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtouqbasic() { INFO_PRINTF1(_L("CTestString::strtouqbasic")); TInt res=KErrGeneral; char *endp; quad_t i=strtouq("900000",&endp,10); if(i==900000) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtouqspacecheck() { INFO_PRINTF1(_L("CTestString::strtouqspacecheck")); TInt res=KErrGeneral; char *endp; long long i=strtoull(" 900000",&endp,10); if(i==900000) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtouqoctalcheck() { INFO_PRINTF1(_L("CTestString::strtouqoctalcheck")); TInt res=KErrGeneral; char *endp; quad_t i=strtouq("010",&endp,8); if(i==8) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strtouqhexcheck() { INFO_PRINTF1(_L("CTestString::strtouqhexcheck")); TInt res=KErrGeneral; char *endp; quad_t i=strtouq("0xa",&endp,16); if(i==10) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strxfrmbasic() { TInt res=KErrGeneral; char src2[20] = "abc"; char dst1[20] = {'\0'}; char src1[20] = "abc"; char dst2[20] = {'\0'}; int r = strxfrm(dst1,src1,strlen(src1)); if(r == strlen(src1)) { INFO_PRINTF1(_L("strxfrm successful")); } strxfrm(dst2,src2,strlen(src2)); if((strcmp(dst1,dst2))== 0) { res=KErrNone; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strptimebasic() { INFO_PRINTF1(_L("CTestString::strptimebasic")); TInt len=0; TPtrC string; _LIT( Kstring1, "Parameter1" ); TBool res = GetStringFromConfig(ConfigSection(), Kstring1, string); if(!res) { _LIT(Kerr , "Failed to time parameter from ini file.") ; INFO_PRINTF1(Kerr) ; return KErrGeneral ; } TBuf8<100> buf1,buf2,buf3,buf4,buf5; buf1.Copy(string); char* src = (char*) buf1.Ptr(); len=buf1.Length(); src[len]='\0'; _LIT( Kstring2, "Parameter2" ); res = GetStringFromConfig(ConfigSection(), Kstring2, string); if(!res) { _LIT(Kerr , "Failed to time parameter from ini file.") ; INFO_PRINTF1(Kerr) ; return KErrGeneral ; } buf2.Copy(string); char * fch=(char *)buf2.Ptr(); len=buf2.Length(); fch[len]='\0'; _LIT( Kstring3, "Parameter3" ); res = GetStringFromConfig(ConfigSection(), Kstring3, string); if(!res) { _LIT(Kerr , "Failed to time parameter from ini file.") ; INFO_PRINTF1(Kerr) ; return KErrGeneral ; } buf3.Copy(string); char * loc=(char *)buf3.Ptr(); len=buf3.Length(); loc[len]='\0'; _LIT( Kstring4, "Parameter4" ); res = GetStringFromConfig(ConfigSection(), Kstring4, string); if(!res) { _LIT(Kerr , "Failed to time parameter from ini file.") ; INFO_PRINTF1(Kerr) ; return KErrGeneral ; } buf4.Copy(string); char * ival=(char *)buf4.Ptr(); len=buf4.Length(); ival[len]='\0'; _LIT( Kstring5, "Parameter5" ); res = GetStringFromConfig(ConfigSection(), Kstring5, string); if(!res) { _LIT(Kerr , "Failed to time parameter from ini file.") ; INFO_PRINTF1(Kerr) ; return KErrGeneral ; } buf5.Copy(string); char * tmval=(char *)buf5.Ptr(); len=buf5.Length(); tmval[len]='\0'; char arg1[100] = {'\0'}; char arg2[100] = { '%'}; strcat(arg1,src); strcat(arg2,fch); int tm_item_val=atoi(ival); int tm_item=atoi(tmval); struct tm * t=(struct tm *) new tm; char * locale = setlocale(LC_TIME,loc); if(locale == NULL) { INFO_PRINTF1(_L("setlocale failed")); delete t; return KErrNone; } char * endp=strptime(arg1,arg2,t); switch(tm_item) { case 0: if(t->tm_sec==tm_item_val) { res=KErrNone; } break; case 1: if(t->tm_min==tm_item_val) { res=KErrNone; } break; case 2: if(t->tm_hour==tm_item_val) { res=KErrNone; } break; case 3: if(t->tm_mday==tm_item_val) { res=KErrNone; } break; case 4: if(t->tm_mon==tm_item_val) { res=KErrNone; } break; case 5: if(t->tm_year==tm_item_val) { res=KErrNone; } break; case 6: if(t->tm_wday==tm_item_val) { res=KErrNone; } break; case 7: if(t->tm_yday==tm_item_val) { res=KErrNone; } break; case 8: if(t->tm_isdst==tm_item_val) { res=KErrNone; } break; case 9: if(t->tm_gmtoff==tm_item_val) { res=KErrNone; } break; } if(t != NULL) { delete t; t = NULL; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strftimebasic( ) { INFO_PRINTF1(_L("CTestString::strftimebasic")); TInt ret=KErrGeneral; TInt len=0; TPtrC string; _LIT( Kstring1, "Parameter1" ); TBool res = GetStringFromConfig(ConfigSection(), Kstring1, string); if(!res) { _LIT(Kerr , "Failed to time parameter from ini file.") ; INFO_PRINTF1(Kerr) ; return ret ; } TBuf8<100> buf1,buf2,buf3,buf4,buf5; buf1.Copy(string); char* src = (char*) buf1.Ptr(); len=buf1.Length(); src[len]='\0'; _LIT( Kstring2, "Parameter2" ); res = GetStringFromConfig(ConfigSection(), Kstring2, string); if(!res) { _LIT(Kerr , "Failed to time parameter from ini file.") ; INFO_PRINTF1(Kerr) ; return ret ; } buf2.Copy(string); char * fch=(char *)buf2.Ptr(); len=buf2.Length(); fch[len]='\0'; _LIT( Kstring3, "Parameter3" ); res = GetStringFromConfig(ConfigSection(), Kstring3, string); if(!res) { _LIT(Kerr , "Failed to time parameter from ini file.") ; INFO_PRINTF1(Kerr) ; return ret ; } buf3.Copy(string); char * loc=(char *)buf3.Ptr(); len=buf3.Length(); loc[len]='\0'; _LIT( Kstring4, "Parameter4" ); res = GetStringFromConfig(ConfigSection(), Kstring4, string); if(!res) { _LIT(Kerr , "Failed to time parameter from ini file.") ; INFO_PRINTF1(Kerr) ; return ret ; } buf4.Copy(string); char * ival=(char *)buf4.Ptr(); len=buf4.Length(); ival[len]='\0'; _LIT( Kstring5, "Parameter5" ); res = GetStringFromConfig(ConfigSection(), Kstring5, string); if(!res) { _LIT(Kerr , "Failed to time parameter from ini file.") ; INFO_PRINTF1(Kerr) ; return ret ; } buf5.Copy(string); char * tmval=(char *)buf5.Ptr(); len=buf5.Length(); tmval[len]='\0'; char sol[100] = {'\0'}; char arg1[100]= {'\0'}; char arg2[100] = {'\0'}; arg2[0] = '%'; INFO_PRINTF1(_L("Arg successfully parsed")); strcat(arg1,src); strcat(arg2,fch); int tm_item_val=atoi(ival); int tm_item=atoi(tmval); struct tm * t=(struct tm *) new tm; if( t == NULL) { INFO_PRINTF1(_L("tm structure failed ")); return -1; } char * locale = setlocale(LC_TIME,loc); if(locale == NULL) { INFO_PRINTF1(_L("setlocale failed")); delete t; return KErrNone; } switch(tm_item) { case 0: t->tm_sec=tm_item_val; break; case 1: t->tm_min=tm_item_val; break; case 2: t->tm_hour=tm_item_val; break; case 3: t->tm_mday=tm_item_val; break; case 4: t->tm_mon=tm_item_val; break; case 5: t->tm_year=tm_item_val; break; case 6: t->tm_wday=tm_item_val; break; case 7: t->tm_yday=tm_item_val; break; case 8: t->tm_isdst=tm_item_val; break; case 9: t->tm_gmtoff=tm_item_val; break; } INFO_PRINTF1(_L("strftime called")); int cnt=strftime(sol,100,arg2,t); INFO_PRINTF2(_L("cnt = %d"),cnt); INFO_PRINTF1(_L("strcmp called")); if(!strcasecmp(sol,arg1)) { ret=KErrNone; } if(t != NULL) { delete t; t = NULL; } return ret; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strptime_arabic() { TInt res=KErrNone; char * locale = setlocale(LC_TIME,"ar_AE.UTF-8"); if(locale == NULL) { INFO_PRINTF1(_L("setlocale failed")); return KErrNone; } struct tm * t=(struct tm *) new tm; char * endp= strptime("\xd8\xa7\xd8\xab","%a",t); if(t->tm_wday!=1) { res=KErrGeneral; } if(t != NULL) { delete t; t = NULL; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strptime_heutf( ) { TInt res=KErrNone; char * locale = setlocale(LC_TIME,"he_IL.UTF-8"); if(locale == NULL) { INFO_PRINTF1(_L("setlocale failed")); return KErrNone; } struct tm * t=(struct tm *) new tm; char * endp= strptime("\xd7\x99\xd7\xa0\xd7\x95\x2e","%b",t); if(t->tm_mon!=0) { res=KErrGeneral; } if(t != NULL) { delete t; t = NULL; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strftime_arabic( ) { TInt res=KErrNone; char sol[100]; char * locale = setlocale(LC_TIME,"ar_AE.UTF-8"); if(locale == NULL) { INFO_PRINTF1(_L("setlocale failed")); return KErrNone; } struct tm * t=(struct tm *) new tm; t->tm_wday=1; int cnt= strftime(sol,100,"%a",t); if(strcmp(sol,"\xd8\xa7\xd8\xab")) { res=KErrGeneral; } if(t != NULL) { delete t; t = NULL; } return res; } //----------------------To Do Documentation--------------------------------------- TInt CTestString::strftime_heutf( ) { TInt res=KErrNone; char sol[100]; char * locale = setlocale(LC_TIME,"he_IL.UTF-8"); if(locale == NULL) { INFO_PRINTF1(_L("setlocale failed")); return KErrNone; } struct tm * t=(struct tm *) new tm; t->tm_mon=0; int cnt= strftime(sol,100,"%b",t); if(strcmp(sol,"\xd7\x99\xd7\xa0\xd7\x95\x2e")) { res=KErrGeneral; } if(t != NULL) { delete t; t = NULL; } return res; } TInt CTestString::strptimebasic1() { struct tm *t=(struct tm *) new tm; if (strptime("12:33:45", "%H:%M:%S", t) == NULL) { delete t; return KErrGeneral; } INFO_PRINTF4(_L("hour: %d min: %d sec %d"),t->tm_hour,t->tm_min,t->tm_sec); delete t; return KErrNone; } TInt CTestString::Testmemchr_specialchars() { char * pch; char str[] = "Hei p \xe5 deg"; int d = '\xe5';// special character to be looked for INFO_PRINTF2(_L("the character being looked for is %c"), d); pch = (char*) memchr ((void *)str, d, sizeof(str)); if (pch != NULL) { INFO_PRINTF2(_L("d found at position %d.\n"), pch-str+1); } else { INFO_PRINTF1(_L("d not found.\n")); return (NULL); } return KErrNone; } TInt CTestString :: strftime_timezone() { struct tm tm; int x; //initializing the time parameter. time_t t = time(NULL); if (t == (time_t)-1) { ERR_PRINTF1(_L("time() function failed")); return KErrGeneral; } char buf[1024]; memset((void*)buf,'\0',sizeof(buf)); tm = *localtime(&t); tm.tm_zone = NULL; x = strftime(buf, sizeof(buf), "%Z", &tm); INFO_PRINTF2(_L("value returned = %d\n"),x); if(x!=3) { return KErrGeneral; } return KErrNone; } TInt CTestString::strlcatBasictest() { char ch[50]; int retval; int ret= KErrNone; //STEP 1 (void) strcpy (ch, "ijk"); retval = strlcat(ch,"lmn",sizeof("lmn")); if(retval==6) { ret = KErrNone; } else { ret = KErrGeneral; } return ret; } TInt CTestString::ffsbasic1() { TInt res=KErrNone; int i=0; int j=ffs(i); if(j!=0) { res=KErrGeneral; } return res; } TInt CTestString::TestStrncasecmp() { TInt res=KErrNone; if(strncasecmp("ABC","abc",(size_t)0)) { res=KErrGeneral; } return res; } TInt CTestString::TestStrncasecmp1() { TInt res=KErrNone; if(strncasecmp("\0","\0",(size_t)5)) { res=KErrGeneral; } return res; } TInt CTestString::strncattest1() { char ch[50]; int retval; //STEP 1 (void) strcpy (ch, "ijk"); if(!strcmp(strncat (ch, "lmn", 0),ch)) /* Returned value. */ { retval = KErrNone; } else { retval = KErrGeneral; } return retval; } TInt CTestString::bcopyfuncheck1() { char ch[50]; strcpy(ch,"abc"); bcopy("abc",ch,3); return compare(ch,"abc"); } TInt CTestString::strlcpyBasictest() { char ch[50]; int retval; int ret= KErrNone; //STEP 1 (void) strcpy (ch, "ijk"); retval = strlcpy(ch,"lmn",(size_t)0); if(retval==3) { ret = KErrNone; } else { ret = KErrGeneral; } return ret; } TInt CTestString::strlcpyBasictest1() { char ch[50]; int retval; int ret= KErrNone; //STEP 1 (void) strcpy (ch, "ijk"); retval = strlcpy(ch,"lmn",(size_t)1); if(retval==3) { ret = KErrNone; } else { ret = KErrGeneral; } return ret; } TInt CTestString::strlcatBasictest1() { char ch[50]; int retval; int ret= KErrNone; //STEP 1 (void) strcpy (ch, "ijk"); retval = strlcat(ch,"lmn",(size_t)0); if(retval==3) { ret = KErrNone; } else { ret = KErrGeneral; } return ret; } TInt CTestString::strxfrmbasic1() { TInt res=KErrGeneral; char dst1[20] = {'\0'}; char src1[20] = "abc"; int r = strxfrm(dst1,src1,0); if(r == strlen(src1)) { INFO_PRINTF1(_L("strxfrm successful")); res = KErrNone; } return res; } TInt CTestString::TestStrcasestr1() { INFO_PRINTF1(_L("Test strcasestr1()")); char* str1 = "this is a string of characters"; char* str2 = ""; char* result = strcasestr( str1, str2 ); if( result == NULL ) { INFO_PRINTF1(_L("Test failed")); return KErrGeneral; } else { if(!strcmp(str1,result)) { INFO_PRINTF1(_L("Test passed")); return KErrNone; } return KErrGeneral; } } TInt CTestString::TestStrnstr1() { INFO_PRINTF1(_L("Test strnstr1()")); const char *largestring = "\0"; const char *smallstring = "Bar"; char *ptr; ptr = strnstr(largestring, smallstring,(size_t)3); if(ptr == NULL) { return KErrNone; } else { return KErrGeneral; } } TInt CTestString::TestStrnstr2() { INFO_PRINTF1(_L("Test strnstr2()")); const char *largestring = "This is an example String"; const char *smallstring = "revanth"; char *ptr; ptr = strnstr(largestring, smallstring,(size_t)27); if(ptr == NULL) { return KErrNone; } else { return KErrGeneral; } } TInt CTestString::TestStrnstr3() { INFO_PRINTF1(_L("Test strnstr3()")); const char *largestring = "This"; const char *smallstring = ""; char *ptr; ptr = strnstr(largestring, smallstring,(size_t)27); if(!strcmp(ptr,"This")) { return KErrNone; } else { return KErrGeneral; } } TInt CTestString::TestMemccpy1() { INFO_PRINTF1(_L("Test memccpy1()")); char string1[60] = "The quick brown dog jumps over the lazy fox"; char *buffer=NULL; int pdest; pdest = (int)memccpy( buffer, string1, 's', 0 ); if(pdest==0 && buffer==NULL) { return KErrNone; } else { return KErrGeneral; } } TInt CTestString::TstWcsxfrm1() { wchar_t str1[MIN_LEN]; wchar_t str3[MIN_LEN]; if (mbstowcs(str1, "\0", MIN_LEN) == (size_t)-1) { ERR_PRINTF1(_L("Error :mbstowcs()")); return KErrGeneral; } int result1 = wcsxfrm(str3, str1, MIN_LEN); if(result1==0) { return KErrNone; } else { return KErrGeneral; } } TInt CTestString::TstWcsxfrm2() { wchar_t str1[MIN_LEN]; wchar_t str3[MIN_LEN]; if (mbstowcs(str1, "\0", MIN_LEN) == (size_t)-1) { ERR_PRINTF1(_L("Error :mbstowcs()")); return KErrGeneral; } int result1 = wcsxfrm(str3, str1, (size_t)0); if(result1==0) { return KErrNone; } else { return KErrGeneral; } } TInt CTestString::TstWcsxfrm3() { wchar_t str1[MIN_LEN]; wchar_t str3[MIN_LEN]; if (mbstowcs(str1, "abc", MIN_LEN) == (size_t)-1) { ERR_PRINTF1(_L("Error :mbstowcs()")); return KErrGeneral; } int result1 = wcsxfrm(str3, str1, (size_t)2); if(result1==3) { return KErrNone; } else { return KErrGeneral; } } TInt CTestString::TstStrdup2() { char* dest; dest = strdup("Helloadjskl;jfklasdjfaklfjaklsfjaskldjfasklfjaklsjfklasfjaklsdjfaskdlfjklasdfjaklsjfklasjfkalsdjfklasdjfaklsdjfaklsfjaklsfjaklsjfaklsdfjaklsfjaklsdjkflasdjfklajsfklasjdfklajsdfkljasdklfjaslkfjakl;sdfjalskdfjaskl;dfjaskl;dfjaskld;fjadskl;fjas;jffjasdklfjaklsd;jfakl;sdHelloadjskl;jfklasdjfaklfjaklsfjaskldjfasklfjaklsjfklasfjaklsdjfaskdlfjklasdfjaklsjfklasjfkalsdjfklasdjfaklsdjfaklsfjaklsfjaklsjfaklsdfjaklsfjaklsdjkflasdjfklajsfklasjdfklajsdfkljasdklfjaslkfjakl;sdfjalskdfjaskl;dfjaskl;dfjaskld;fjadskl;fjas;jffjasdklfjaklsd;jfakl;sdHelloadjskl;jfklasdjfaklfjaklsfjaskldjfasklfjaklsjfklasfjaklsdjfaskdlfjklasdfjaklsjfklasjfkalsdjfklasdjfaklsdjfaklsfjaklsfjaklsjfaklsdfjaklsfjaklsdjkflasdjfklajsfklasjdfklajsdfkljasdklfjaslkfjakl;sdfjalskdfjaskl;dfjaskl;dfjaskld;fjadskl;fjas;jffjasdklfjaklsd;jfakl;sdHelloadjskl;jfklasdjfaklfjaklsfjaskldjfasklfjaklsjfklasfjaklsdjfaskdlfjklasdfjaklsjfklasjfkalsdjfklasdjfaklsdjfaklsfjaklsfjaklsjfaklsdfjaklsfjaklsdjkflasdjfklajsfklasjdfklajsdfkljasdklfjaslkfjakl;sdfjalskdfjaskl;dfjaskl;dfjaskld;fjadskl;fjas;jffjasdklfjaklsd;jfakl;sd"); int ret = validate(strcmp(dest,"Helloadjskl;jfklasdjfaklfjaklsfjaskldjfasklfjaklsjfklasfjaklsdjfaskdlfjklasdfjaklsjfklasjfkalsdjfklasdjfaklsdjfaklsfjaklsfjaklsjfaklsdfjaklsfjaklsdjkflasdjfklajsfklasjdfklajsdfkljasdklfjaslkfjakl;sdfjalskdfjaskl;dfjaskl;dfjaskld;fjadskl;fjas;jffjasdklfjaklsd;jfakl;sdHelloadjskl;jfklasdjfaklfjaklsfjaskldjfasklfjaklsjfklasfjaklsdjfaskdlfjklasdfjaklsjfklasjfkalsdjfklasdjfaklsdjfaklsfjaklsfjaklsjfaklsdfjaklsfjaklsdjkflasdjfklajsfklasjdfklajsdfkljasdklfjaslkfjakl;sdfjalskdfjaskl;dfjaskl;dfjaskld;fjadskl;fjas;jffjasdklfjaklsd;jfakl;sdHelloadjskl;jfklasdjfaklfjaklsfjaskldjfasklfjaklsjfklasfjaklsdjfaskdlfjklasdfjaklsjfklasjfkalsdjfklasdjfaklsdjfaklsfjaklsfjaklsjfaklsdfjaklsfjaklsdjkflasdjfklajsfklasjdfklajsdfkljasdklfjaslkfjakl;sdfjalskdfjaskl;dfjaskl;dfjaskld;fjadskl;fjas;jffjasdklfjaklsd;jfakl;sdHelloadjskl;jfklasdjfaklfjaklsfjaskldjfasklfjaklsjfklasfjaklsdjfaskdlfjklasdfjaklsjfklasjfkalsdjfklasdjfaklsdjfaklsfjaklsfjaklsjfaklsdfjaklsfjaklsdjkflasdjfklajsfklasjdfklajsdfkljasdklfjaslkfjakl;sdfjalskdfjaskl;dfjaskl;dfjaskld;fjadskl;fjas;jffjasdklfjaklsd;jfakl;sd")==0); if (dest == NULL) { if (errno == ENOMEM) { ERR_PRINTF1(_L("Insufficient memory")); } return KErrGeneral; } else if(ret==KErrNone) { INFO_PRINTF1(_L("strdup() success")); } free(dest); return ret; } TInt CTestString::TstStrerr_r() { char msgbuf[256]; int errnum=95; int ret = strerror_r(errnum, msgbuf, sizeof(msgbuf)); if (ret == EINVAL) { INFO_PRINTF1(_L("strerr_r() success")); return KErrNone; } else { INFO_PRINTF1(_L("strerr_r() failure")); return KErrGeneral; } } TInt CTestString::TstStrerr_r1() { char msgbuf[256]; int errnum=10; int ret = strerror_r(errnum, msgbuf, (size_t)0); if (ret == ERANGE) { INFO_PRINTF1(_L("strerr_r() success")); return KErrNone; } else { INFO_PRINTF1(_L("strerr_r() failure")); return KErrGeneral; } } TInt CTestString::TestStrcasestr2() { char ch[50]; (void) strcpy(ch, "abcd"); return validate(strcasestr(ch, "bc") == ch+1); /* Basic test. */ } TInt CTestString::TestStrnstr4() { char ch[50]; (void) strcpy(ch, "abcd"); return validate(strnstr(ch, "abcde",6) == NULL); /* Basic test. */ } TInt CTestString::TestStrptime_test() { char *ret = setlocale(LC_ALL,"en_GB.ISO-8859-1"); if(ret == NULL) { INFO_PRINTF1(_L("setlocale failed")); return KErrGeneral; } struct tm * t=(struct tm *) new tm; int err = 0; char * endp; endp=strptime("19","%C",t); if(t->tm_year!=0) { err += 1; } endp=strptime("mon","%c",t); endp=strptime("01/01/84","%D",t); if(t->tm_mday!=1 && t->tm_mon != 0 && t->tm_year != 84) { err += 1; } endp=strptime("1984","%EY",t); if(t->tm_year != 84) { err += 1; } endp=strptime("10","%OI",t); if(t->tm_hour != 10) { err += 1; } endp=strptime("1984-01-01","%F",t); if(t->tm_mday!=1 && t->tm_mon != 0 && t->tm_year != 84) { err += 1; } endp=strptime("10:10","%R",t); if(t->tm_hour != 10 && t->tm_min != 10) { err += 1; } endp=strptime("10:10:10","%T",t); if(t->tm_hour != 10 && t->tm_min != 10 && t->tm_sec != 10 ) { err += 1; } endp=strptime("100","%j",t); if(t->tm_yday != 99) { err += 1; } endp=strptime("mon","%A",t); if(t->tm_wday!=1) { err += 1; } endp=strptime("50","%U",t); if(endp == NULL) { err += 1; } endp=strptime("50","%W",t); if(endp == NULL) { err += 1; } endp=strptime("1","%w",t); if(t->tm_wday!=1) { err += 1; } endp=strptime("20","%e",t); if(t->tm_mday!=20) { err += 1; } endp=strptime("jan","%B",t); if(t->tm_mon!=0) { err += 1; } endp=strptime("mar","%h",t); if(t->tm_mon!=2) { err += 1; } endp=strptime("10","%s",t); if(endp==NULL) { err += 1; } endp=strptime("10","%I",t); if(t->tm_hour!=10) { err += 1; } endp=strptime("10","%k",t); if(t->tm_hour!=10) { err += 1; } endp=strptime("10","%l",t); if(t->tm_hour!=10) { err += 1; } endp=strptime("9:10:10 am","%r",t); if(t->tm_hour!=9 && t->tm_min!=10 && t->tm_sec!=10) { err += 1; } endp=strptime("10:10:10 am","%X",t); if(t->tm_hour!=10 && t->tm_min!=10 && t->tm_sec!=10) { err += 1; } endp=strptime("10/01/1990","%x",t); if(t->tm_mday!=1 && t->tm_mon!=9 && t->tm_year!=90) { err += 1; } endp=strptime("am","%p",t); if(endp == NULL) { err += 1; } endp=strptime("GMT","%Z",t); if(t->tm_yday!=364 && t->tm_isdst!=0 && t->tm_gmtoff!=0) { err += 1; } if(t != NULL) { delete t; t = NULL; } if(err != 0) return KErrGeneral; return KErrNone; } TInt CTestString::TestStrptime_test1() { TInt ret = KErrGeneral; INFO_PRINTF1(_L("TestStrptime_test1 begins")); struct tm buf; char outbuf[10]; time_t tt = time(NULL); if (tt == (time_t)-1) { ERR_PRINTF1(_L("time() function failed")); return ret; } buf = *localtime(&tt); buf.tm_zone = NULL;/*tm_zone set to NULL explicitly*/ if (strftime(outbuf, 10, "%Z", &buf) == 0) { ERR_PRINTF1(_L("strftime() function failed")); return ret; } ret = KErrNone; TPtrC8 outbufstring((TText8*)outbuf, strlen(outbuf)); TBuf16<100> outbufname; outbufname.Copy(outbufstring); INFO_PRINTF2(_L("strftime() sets default time zone as : %S"), &outbufname); INFO_PRINTF1(_L("TestStrptime_test1 ends")); return ret; }
[ "none@none" ]
[ [ [ 1, 4944 ] ] ]
4c4f6b2f9deb0760ba31d84f117a264584bc0155
8b506bf34b36af04fa970f2749e0c8033f1a9d7a
/Code/Engine2Linux/gwEngine.cpp
f36ebfac618eb1ec64fbb20a3841dfb6d73741e3
[]
no_license
gunstar/Prototype
a5155e25d7d54a1991425e7be85bfc7da42c634f
a4448b5f6d18048ecaedf26c71e2b107e021ea6e
refs/heads/master
2021-01-10T21:42:24.221750
2011-11-06T10:16:26
2011-11-06T10:16:26
2,708,481
0
0
null
null
null
null
UTF-8
C++
false
false
366
cpp
#include "gwEngine.h" #include "gwCamera.h" #include "gwEntity.h" #include "gwMesh.h" /*******************************************************************/ eiCamera* gwEngine::makeCamera() { return new gwCamera; } eiEntity* gwEngine::makeEntity(eiMesh* mesh) { return new gwEntity; } eiMesh* gwEngine::makeMesh() { return new gwMesh; }
[ [ [ 1, 22 ] ] ]
fa3cd405d13cdcced89294ed749a3754811c2274
a30b091525dc3f07cd7e12c80b8d168a0ee4f808
/EngineAll/Textures/D3D9Texture.cpp
73a1b8cf1ab8407cd0fdd5c2163cd7ef57d53c2d
[]
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
11,041
cpp
/* D3D9Texture.cpp Written by Matthew Fisher DirectX implementation of BaseTexture. See BaseTexture.h for a definiton of the base functions. */ #include "..\\..\\Main.h" #ifdef USE_D3D9 D3D9Texture::D3D9Texture() { _SurfaceTopLevel = NULL; _Texture = NULL; _SurfacePlain = NULL; _Device = NULL; _Width = 0; _Height = 0; _RenderTarget = false; } D3D9Texture::D3D9Texture(LPDIRECT3DDEVICE9 Device) { _SurfaceTopLevel = NULL; _Texture = NULL; _SurfacePlain = NULL; _Device = Device; _Width = 0; _Height = 0; _RenderTarget = false; } D3D9Texture::~D3D9Texture() { FreeMemory(); } void D3D9Texture::FreeMemory() { ReleaseMemory(); if(_SurfacePlain != NULL) { D3DValidateRelease(_SurfacePlain); _SurfacePlain = NULL; } _RenderTarget = false; } void D3D9Texture::ReleaseMemory() { if(_Texture != NULL) { ULONG References = _Texture->Release(); PersistentAssert(References == 1, String("Release reference count: ") + String(References)); _Texture = NULL; } if(_SurfaceTopLevel != NULL) { D3DValidateRelease(_SurfaceTopLevel); _SurfaceTopLevel = NULL; } _Width = 0; _Height = 0; } void D3D9Texture::Reset(LPDIRECT3DDEVICE9 Device) { SignalError("Fix"); //Associate(Device); //Load(_Bmp); } void D3D9Texture::UpdateMipMapLevels() { D3DXFilterTexture(_Texture, NULL, 0, D3DX_DEFAULT); } void D3D9Texture::Allocate(D3DFORMAT Format, UINT Width, UINT Height, bool RenderTarget) { if(_Width != Width || _Height != Height || _Format != Format || _RenderTarget != RenderTarget) { FreeMemory(); PersistentAssert(_Device != NULL, "D3D9Texture not associated"); //DWORD Usage = D3DUSAGE_AUTOGENMIPMAP; DWORD Usage = 0; D3DPOOL Pool = D3DPOOL_MANAGED; if(RenderTarget) { Usage |= D3DUSAGE_RENDERTARGET; Pool = D3DPOOL_DEFAULT; D3DAlwaysValidate(_Device->CreateOffscreenPlainSurface(Width, Height, Format, D3DPOOL_SYSTEMMEM, &_SurfacePlain, NULL), "CreateOffscreenPlainSurface"); } D3DAlwaysValidate(_Device->CreateTexture(Width, Height, 0, Usage, Format, Pool, &_Texture, NULL), "CreateTexture"); D3DValidate(_Texture->GetSurfaceLevel(0, &_SurfaceTopLevel), "GetSurfaceLevel"); _Width = Width; _Height = Height; _Format = Format; _RenderTarget = RenderTarget; } } void D3D9Texture::Clear() { // // requires D3DPOOL_DEFAULT // _Device->ColorFill(_SurfaceTopLevel, NULL, D3DCOLOR_ARGB(0, 0, 0, 0)); } void D3D9Texture::Load(const Bitmap &Bmp) { Allocate(D3DFMT_A8R8G8B8, Bmp.Width(), Bmp.Height(), false); D3DLOCKED_RECT Rect; D3DValidate(_Texture->LockRect(0, &Rect, NULL, 0), "LockRect"); BYTE *Bytes = (BYTE *)Rect.pBits; for(UINT y = 0; y < _Height; y++) { RGBColor *CurRow = (RGBColor *)(Bytes + y * Rect.Pitch); for(UINT x = 0; x < _Width; x++) { RGBColor Color = Bmp[y][x]; CurRow[x] = RGBColor(Color.b, Color.g, Color.r, Color.a); } } D3DValidate(_Texture->UnlockRect(0), "UnlockRect"); UpdateMipMapLevels(); } void D3D9Texture::Load(const Grid<float> &Data) { Allocate(D3DFMT_R32F, Data.Cols(), Data.Rows(), false); D3DLOCKED_RECT Rect; D3DValidate(_Texture->LockRect(0, &Rect, NULL, 0), "LockRect"); BYTE *Bytes = (BYTE *)Rect.pBits; for(UINT y = 0; y < _Height; y++) { float *CurRow = (float *)(Bytes + y * Rect.Pitch); for(UINT x = 0; x < _Width; x++) { CurRow[x] = Data.GetElement(y, x); } } D3DValidate(_Texture->UnlockRect(0), "UnlockRect"); } void D3D9Texture::Load(const Grid<Vec2f> &Data) { Allocate(D3DFMT_G32R32F, Data.Cols(), Data.Rows(), false); D3DLOCKED_RECT Rect; D3DValidate(_Texture->LockRect(0, &Rect, NULL, 0), "LockRect"); BYTE *Bytes = (BYTE *)Rect.pBits; for(UINT y = 0; y < _Height; y++) { Vec2f *CurRow = (Vec2f *)(Bytes + y * Rect.Pitch); for(UINT x = 0; x < _Width; x++) { CurRow[x] = Data.GetElement(y, x); } } D3DValidate(_Texture->UnlockRect(0), "UnlockRect"); } void D3D9Texture::Load(const Grid<Vec3f> &Data) { Allocate(D3DFMT_A32B32G32R32F, Data.Cols(), Data.Rows(), false); D3DLOCKED_RECT Rect; D3DValidate(_Texture->LockRect(0, &Rect, NULL, 0), "LockRect"); BYTE *Bytes = (BYTE *)Rect.pBits; for(UINT y = 0; y < _Height; y++) { Vec4f *CurRow = (Vec4f *)(Bytes + y * Rect.Pitch); for(UINT x = 0; x < _Width; x++) { CurRow[x] = Vec4f(Data.GetElement(y, x), 0.0f); } } D3DValidate(_Texture->UnlockRect(0), "UnlockRect"); } void D3D9Texture::Load(const Grid<Vec4f> &Data) { Allocate(D3DFMT_A32B32G32R32F, Data.Cols(), Data.Rows(), false); D3DLOCKED_RECT Rect; D3DValidate(_Texture->LockRect(0, &Rect, NULL, 0), "LockRect"); BYTE *Bytes = (BYTE *)Rect.pBits; for(UINT y = 0; y < _Height; y++) { Vec4f *CurRow = (Vec4f *)(Bytes + y * Rect.Pitch); for(UINT x = 0; x < _Width; x++) { CurRow[x] = Data.GetElement(y, x); } } D3DValidate(_Texture->UnlockRect(0), "UnlockRect"); } void D3D9Texture::Load(D3D9Texture &Tex) { D3DAlwaysValidate(_Device->StretchRect(Tex.SurfaceTopLevel(), NULL, _SurfaceTopLevel, NULL, D3DTEXF_POINT), "StretchRect"); } void D3D9Texture::ReadData(Bitmap &Bmp) { PersistentAssert(_Width != 0 && _Height != 0 && _Format == D3DFMT_A8R8G8B8 && _RenderTarget, "ReadData called on invalid surface"); Bmp.Allocate(_Width, _Height); D3DLOCKED_RECT Rect; D3DAlwaysValidate(_Device->GetRenderTargetData(_SurfaceTopLevel, _SurfacePlain), "GetRenderTargetData"); D3DAlwaysValidate(_SurfacePlain->LockRect(&Rect, NULL, D3DLOCK_READONLY), "LockRect"); BYTE *Bytes = (BYTE *)Rect.pBits; for(UINT y = 0; y < _Height; y++) { RGBColor *CurRow = (RGBColor *)(Bytes + y * Rect.Pitch); for(UINT x = 0; x < _Width; x++) { Bmp[y][x] = CurRow[x]; } } D3DValidate(_SurfacePlain->UnlockRect(), "UnlockRect"); } void D3D9Texture::ReadData(Grid<float> &Data) { PersistentAssert(_Width != 0 && _Height != 0 && _Format == D3DFMT_R32F, "ReadData called on invalid surface"); Data.Allocate(_Height, _Width); D3DLOCKED_RECT Rect; if(_RenderTarget) { D3DAlwaysValidate(_Device->GetRenderTargetData(_SurfaceTopLevel, _SurfacePlain), "GetRenderTargetData"); D3DAlwaysValidate(_SurfacePlain->LockRect(&Rect, NULL, D3DLOCK_READONLY), "LockRect"); } else { D3DAlwaysValidate(_SurfaceTopLevel->LockRect(&Rect, NULL, D3DLOCK_READONLY), "LockRect"); } BYTE *Bytes = (BYTE *)Rect.pBits; for(UINT y = 0; y < _Height; y++) { float *CurRow = (float *)(Bytes + y * Rect.Pitch); for(UINT x = 0; x < _Width; x++) { Data.GetElement(y, x) = CurRow[x]; } } if(_RenderTarget) { D3DValidate(_SurfacePlain->UnlockRect(), "UnlockRect"); } else { D3DValidate(_SurfaceTopLevel->UnlockRect(), "UnlockRect"); } } void D3D9Texture::ReadData(Grid<Vec2f> &Data) { PersistentAssert(_Width != 0 && _Height != 0 && _Format == D3DFMT_G32R32F && _RenderTarget, "ReadData called on invalid surface"); Data.Allocate(_Height, _Width); D3DLOCKED_RECT Rect; D3DAlwaysValidate(_Device->GetRenderTargetData(_SurfaceTopLevel, _SurfacePlain), "GetRenderTargetData"); D3DAlwaysValidate(_SurfacePlain->LockRect(&Rect, NULL, D3DLOCK_READONLY), "LockRect"); BYTE *Bytes = (BYTE *)Rect.pBits; for(UINT y = 0; y < _Height; y++) { Vec2f *CurRow = (Vec2f *)(Bytes + y * Rect.Pitch); for(UINT x = 0; x < _Width; x++) { Data.GetElement(y, x) = CurRow[x]; } } D3DValidate(_SurfacePlain->UnlockRect(), "UnlockRect"); } void D3D9Texture::ReadData(Grid<Vec3f> &Data) { PersistentAssert(_Width != 0 && _Height != 0 && _Format == D3DFMT_A32B32G32R32F && _RenderTarget, "ReadData called on invalid surface"); Data.Allocate(_Height, _Width); D3DLOCKED_RECT Rect; D3DAlwaysValidate(_Device->GetRenderTargetData(_SurfaceTopLevel, _SurfacePlain), "GetRenderTargetData"); D3DAlwaysValidate(_SurfacePlain->LockRect(&Rect, NULL, D3DLOCK_READONLY), "LockRect"); BYTE *Bytes = (BYTE *)Rect.pBits; for(UINT y = 0; y < _Height; y++) { Vec4f *CurRow = (Vec4f *)(Bytes + y * Rect.Pitch); for(UINT x = 0; x < _Width; x++) { Data.GetElement(y, x) = Vec3f(CurRow[x].x, CurRow[x].y, CurRow[x].z); } } D3DValidate(_SurfacePlain->UnlockRect(), "UnlockRect"); } void D3D9Texture::ReadData(Grid<Vec4f> &Data) { PersistentAssert(_Width != 0 && _Height != 0 && _Format == D3DFMT_A32B32G32R32F && _RenderTarget, "ReadData called on invalid surface"); Data.Allocate(_Height, _Width); D3DLOCKED_RECT Rect; D3DAlwaysValidate(_Device->GetRenderTargetData(_SurfaceTopLevel, _SurfacePlain), "GetRenderTargetData"); D3DAlwaysValidate(_SurfacePlain->LockRect(&Rect, NULL, D3DLOCK_READONLY), "LockRect"); BYTE *Bytes = (BYTE *)Rect.pBits; for(UINT y = 0; y < _Height; y++) { Vec4f *CurRow = (Vec4f *)(Bytes + y * Rect.Pitch); for(UINT x = 0; x < _Width; x++) { Data.GetElement(y, x) = CurRow[x]; } } D3DValidate(_SurfacePlain->UnlockRect(), "UnlockRect"); } void D3D9Texture::Flush() { PersistentAssert(_Width != 0 && _Height != 0 && _Format == D3DFMT_A32B32G32R32F && _RenderTarget, "ReadData called on invalid surface"); D3DLOCKED_RECT Rect; D3DAlwaysValidate(_Device->GetRenderTargetData(_SurfaceTopLevel, _SurfacePlain), "GetRenderTargetData"); D3DAlwaysValidate(_SurfacePlain->LockRect(&Rect, NULL, D3DLOCK_READONLY), "LockRect"); D3DValidate(_SurfacePlain->UnlockRect(), "UnlockRect"); } void D3D9Texture::Associate(GraphicsDevice &GD) { _Device = GD.CastD3D9().GetDevice(); } void D3D9Texture::Set(int Index) { Assert(_Texture != NULL, "SetTexture called on empty texture"); _Device->SetTexture(Index, _Texture); } void D3D9Texture::SetAsRenderTarget(int Index) { Assert(_Texture != NULL && _RenderTarget, "SetAsRenderTarget on invalid texture"); D3DValidate(_Device->SetRenderTarget(Index, _SurfaceTopLevel), "SetRenderTarget"); } void D3D9Texture::SetNull(int Index) { _Device->SetTexture(Index, NULL); } #endif
[ "zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2" ]
[ [ [ 1, 345 ] ] ]
21de274006f5bee56f733b211b5a7d26088afa45
b03c23324d8f048840ecf50875b05835dedc8566
/engin3d/src/Lua/LuaFunctions.cpp
633ae4ec4ac57fc892a4b2ed5277cc5b22d5cb48
[]
no_license
carlixyz/engin3d
901dc61adda54e6098a3ac6637029efd28dd768e
f0b671b1e75a02eb58a2c200268e539154cd2349
refs/heads/master
2018-01-08T16:49:50.439617
2011-06-16T00:13:26
2011-06-16T00:13:26
36,534,616
0
0
null
null
null
null
ISO-8859-10
C++
false
false
6,894
cpp
#include "LuaFunctions.h" #include "../Lua/LuaManager.h" #include "../Character/CharacterManager.h" #include "../Graphics/GraphicManager.h" #include "../Character/Behaviour/Patrol.h" int CreatePatrol( float posX, float posY, float posZ, float speed, float angSpeed, cVec3 colour, int liEnemyId, float lfAwareRadius) { cCharacter* lpCharacter = cCharacterManager::Get().CreateCharacter(); lpCharacter->SetSpeed( speed ); lpCharacter->SetAngSpeed( angSpeed ); lpCharacter->SetColour( colour ); cBehaviourBase* lpBehaviour = cBehaviourManager::Get().CreateBehaviour( ePATROL ); lpCharacter->SetActiveBehaviour( lpBehaviour, posX, posY, posZ ); cPatrol * lpPatrol = (cPatrol *)lpCharacter->GetActiveBehaviour(); lpPatrol->SetAwareRadius(lfAwareRadius); lpPatrol->SetEnemyID(liEnemyId); return lpCharacter->GetId() ; } int CreatePatrol( lua_State* lpLuaContext )// Foo for use C++ Foo in Lua { // check the context is right assert( lpLuaContext ); // Take the number of arguments from Lua Stack int liArgCount = lua_gettop( lpLuaContext ); // Check if the number of Arg is right assert( liArgCount == 10 ); // take the arguments from the stack //( use luaL_checkinteger for ints, luaL_checknumber for floats ) float lfArg1 = (float) luaL_checknumber( lpLuaContext, 1); float lfArg2 = (float) luaL_checknumber( lpLuaContext, 2); float lfArg3 = (float) luaL_checknumber( lpLuaContext, 3); float lfArg4 = (float) luaL_checknumber( lpLuaContext, 4); float lfArg5 = (float) luaL_checknumber( lpLuaContext, 5); float lfArg6 = (float) luaL_checknumber( lpLuaContext, 6); float lfArg7 = (float) luaL_checknumber( lpLuaContext, 7); float lfArg8 = (float) luaL_checknumber( lpLuaContext, 8); int liArg9 = (int) luaL_checkinteger( lpLuaContext, 9); float lfArg10 = (float) luaL_checknumber( lpLuaContext, 10); // Insert Here the code to create patrol int liRet = CreatePatrol( lfArg1, lfArg2, lfArg3, lfArg4, lfArg5, cVec3(lfArg6, lfArg7, lfArg8),liArg9, lfArg10 ); // Introducing the result in the Stack lua_pushinteger( lpLuaContext, liRet ); // sending back the numbers of returnīs values in the stack return liRet; } //Set the new target void SetPatrolTarget( int miCharacterId, float mfNextPosX, float mfNextPosY, float mfNextPosZ) { cCharacter * lcCharacter = cCharacterManager::Get().SearchCharacter( miCharacterId ); if (lcCharacter) { cBehaviourBase * lcBehaviour = lcCharacter->GetActiveBehaviour(); if (lcBehaviour) lcBehaviour->SetTarget(mfNextPosX, mfNextPosY, mfNextPosZ); } } //Set patrol target glue method int SetPatrolTarget( lua_State* lpLuaContext ) { // check the context is right assert( lpLuaContext ); // Take the number of arguments from Lua Stack int liArgCount = lua_gettop( lpLuaContext ); // Check if the number of Arg is right assert( liArgCount == 4 ); // take the arguments from the stack //( use luaL_checkinteger for ints, luaL_checknumber for floats ) int liArg1 = (int) luaL_checkinteger( lpLuaContext, 1); float lfArg2 = (float) luaL_checknumber( lpLuaContext, 2); float lfArg3 = (float) luaL_checknumber( lpLuaContext, 3); float lfArg4 = (float) luaL_checknumber( lpLuaContext, 4); // Call to set patrol SetPatrolTarget( liArg1, lfArg2, lfArg3, lfArg4 ); // Introducing the result in the Stack lua_pushinteger( lpLuaContext, 1 ); //return 1 return 1; } //Set patrol target glue method int DrawLine( lua_State* lpLuaContext ) { // check the context is right assert( lpLuaContext ); // Take the number of arguments from Lua Stack int liArgCount = lua_gettop( lpLuaContext ); // Check if the number of Arg is right assert( liArgCount == 9 ); // take the arguments from the stack //( use luaL_checkinteger for ints, luaL_checknumber for floats ) float lfArg1 = (float) luaL_checknumber( lpLuaContext, 1); float lfArg2 = (float) luaL_checknumber( lpLuaContext, 2); float lfArg3 = (float) luaL_checknumber( lpLuaContext, 3); float lfArg4 = (float) luaL_checknumber( lpLuaContext, 4); float lfArg5 = (float) luaL_checknumber( lpLuaContext, 5); float lfArg6 = (float) luaL_checknumber( lpLuaContext, 6); float lfArg7 = (float) luaL_checknumber( lpLuaContext, 7); float lfArg8 = (float) luaL_checknumber( lpLuaContext, 8); float lfArg9 = (float) luaL_checknumber( lpLuaContext, 9); // Draw Line cGraphicManager::Get().DrawLine(cVec3( lfArg1, lfArg2, lfArg3), cVec3( lfArg4, lfArg5, lfArg6), cVec3( lfArg7, lfArg8, lfArg9)); // Introducing the result in the Stack lua_pushinteger( lpLuaContext, 1 ); //return 1 return 1; } int CreatePlayer( float posX, float posY, float posZ, float speed, float angSpeed, cVec3 colour) { cCharacter* lpCharacter = cCharacterManager::Get().CreateCharacter(); lpCharacter->SetSpeed( speed ); lpCharacter->SetAngSpeed( angSpeed ); lpCharacter->SetColour( colour ); cBehaviourBase* lpBehaviour = cBehaviourManager::Get().CreateBehaviour( ePLAYER_CONTROLLER ); lpCharacter->SetActiveBehaviour( lpBehaviour, posX, posY, posZ ); lpCharacter->SetPosition(cVec3(posX, posY, posZ)); return lpCharacter->GetId() ; } int CreatePlayer( lua_State* lpLuaContext )// Foo for use C++ Foo in Lua { // check the context is right assert( lpLuaContext ); // Take the number of arguments from Lua Stack int liArgCount = lua_gettop( lpLuaContext ); // Check if the number of Arg is right assert( liArgCount == 8 ); // take the arguments from the stack //( use luaL_checkinteger for ints, luaL_checknumber for floats ) float lfArg1 = (float) luaL_checknumber( lpLuaContext, 1); float lfArg2 = (float) luaL_checknumber( lpLuaContext, 2); float lfArg3 = (float) luaL_checknumber( lpLuaContext, 3); float lfArg4 = (float) luaL_checknumber( lpLuaContext, 4); float lfArg5 = (float) luaL_checknumber( lpLuaContext, 5); float lfArg6 = (float) luaL_checknumber( lpLuaContext, 6); float lfArg7 = (float) luaL_checknumber( lpLuaContext, 7); float lfArg8 = (float) luaL_checknumber( lpLuaContext, 8); // Insert Here the code to Do something... int liRet = CreatePlayer( lfArg1, lfArg2, lfArg3, lfArg4, lfArg5, cVec3(lfArg6, lfArg7, lfArg8) ); // Introducing the result in the Stack lua_pushinteger( lpLuaContext, liRet ); // sending back the numbers of returnīs values in the stack return liRet; } void RegisterLuaFunctions() // C++ Foo Register in Lua { cLuaManager::Get().Register( "CreatePatrol", CreatePatrol ); cLuaManager::Get().Register( "CreatePlayer", CreatePlayer ); cLuaManager::Get().Register( "SetPatrolTarget", SetPatrolTarget ); cLuaManager::Get().Register( "DrawLine", DrawLine ); }
[ "[email protected]", "manolopm@8d52fbf8-9d52-835b-178e-190adb01ab0c" ]
[ [ [ 1, 4 ], [ 7, 8 ], [ 10, 13 ], [ 15, 15 ], [ 17, 17 ], [ 22, 34 ], [ 36, 43 ], [ 49, 49 ], [ 52, 56 ], [ 134, 136 ], [ 184, 186 ] ], [ [ 5, 6 ], [ 9, 9 ], [ 14, 14 ], [ 16, 16 ], [ 18, 21 ], [ 35, 35 ], [ 44, 48 ], [ 50, 51 ], [ 57, 133 ], [ 137, 183 ], [ 187, 191 ] ] ]
0fb5ce60f833b28e47ad9e6bca14ed055f961a0c
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/compatanalysercmd/headeranalyser/src/ReportGenerator.cpp
0dd42c907052c9e5b5bc1a2413897e0470252e09
[]
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
40,306
cpp
/* * Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include "CmdGlobals.h" #ifdef __WIN__ #pragma warning(disable:4786) #endif #include <xercesc/dom/DOM.hpp> #include <xercesc/framework/LocalFileFormatTarget.hpp> #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <time.h> #include "ReportGeneratorConstants.h" #include "CmdGlobals.h" #include "ReportIssue.h" #include "XMLModuleErrorHandler.h" #include "HAException.h" #include "Utils.h" #include "Issues.h" #include "BBCFileUtils.h" using namespace std; extern vector<pair<string,pair<string,string> > > HeaderInfoList; // vector<pair< headerfile name, pair<API name, API category>>> XERCES_CPP_NAMESPACE_USE const char* KXMLStyleSheet = "xml-stylesheet"; // Style sheet filename const char* KXMLXSL = "type=\"text/xsl\" href=\"BBCResults.xsl\""; // Base64 coding characters const char* KBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"; #include "ReportGenerator.h" // ---------------------------------------------------------------------------- // ReportGenerator::ReportGenerator // ---------------------------------------------------------------------------- // ReportGenerator::ReportGenerator(string aOutputFile) : iOutputFile(aOutputFile), iIssueId(0), iDOMDocument(0), iDOMRoot(0) { // START -- Support for file checksum and comments unsigned long crc; iCrcTable = new unsigned long[256]; for ( int i = 0; i <= 255 ; i++ ) { crc = i; for ( int j = 8 ; j > 0; j-- ) { if ( crc & 1 ) crc = ( crc >> 1 ) ^ 0xEDB88320L; else crc >>= 1; } iCrcTable[i] = crc; } // END -- Support for file checksum and comments } // ---------------------------------------------------------------------------- // ReportGenerator::~ReportGenerator // ---------------------------------------------------------------------------- // ReportGenerator::~ReportGenerator() { // START -- Support for file checksum and comments delete iCrcTable; iCrcTable = NULL; // END -- Support for file checksum and comments if( iDOMDocument ) { iDOMDocument->release(); } for( issueMap::iterator i = iIssueMap.begin(); i != iIssueMap.end(); ++i ) { delete i->second; i->second = 0; } } // ---------------------------------------------------------------------------- // ReportGenerator::setXSL // ---------------------------------------------------------------------------- // void ReportGenerator::setXSL(string aXSLFilename, bool aIncludeInXML) { iXSLFile = aXSLFilename; iEmbedXSL = aIncludeInXML; } // ---------------------------------------------------------------------------- // ReportGenerator::setDTD // ---------------------------------------------------------------------------- // void ReportGenerator::setDTD(string aDTDFilename, bool aIncludeInDTD) { iDTDFile = aDTDFilename; iEmbedDTD = aIncludeInDTD; } // ---------------------------------------------------------------------------- // ReportGenerator::startReport // ---------------------------------------------------------------------------- // void ReportGenerator::startReport() { initialiseDOM(); } // ---------------------------------------------------------------------------- // ReportGenerator::finishReport // ---------------------------------------------------------------------------- // void ReportGenerator::finishReport() { DOMElement* issuelist = createIssueListNode(); iDOMRoot->appendChild(issuelist); dumpDOMToFile(); } // ---------------------------------------------------------------------------- // ReportGenerator::loadStringTables // ---------------------------------------------------------------------------- // void ReportGenerator::loadStringTables(string aFilename) { } // ---------------------------------------------------------------------------- // ReportGenerator::setCmdLineParms // ---------------------------------------------------------------------------- // void ReportGenerator::setCmdLineParms(map<string, string> aParms) { map<string, string>::iterator begin = aParms.begin(); map<string, string>::iterator end = aParms.end(); while (begin != end) { iParams.insert(*begin); begin++; } } // ---------------------------------------------------------------------------- // ReportGenerator::getCmdLineParm // ---------------------------------------------------------------------------- // string ReportGenerator::getCmdLineParm(string aParm) { map<string, string>::iterator begin = iParams.find(aParm); if (begin != iParams.end()) { return (*begin).second; } else { return "Not specified"; } } // ---------------------------------------------------------------------------- // ReportGenerator::setVersions // ---------------------------------------------------------------------------- // void ReportGenerator::setVersions(string aBaseline, string aCurrent) { iBaselineVersion = aBaseline; iCurrentVersion = aCurrent; } // ---------------------------------------------------------------------------- // ReportGenerator::addIssue // ---------------------------------------------------------------------------- // int ReportGenerator::addIssue(ReportIssue* aIssue) { aIssue->iId = iIssueId++; string key = "<"; key += aIssue->HeaderFile(); key += "><"; key += aIssue->CompareFileName(); key += ">"; issueMapIterator it = iIssueMap.find(key); if (it != iIssueMap.end()) { bool lineInfoNeed = true; // header entry is present in the report. append the issue to the header issue list issueVector* v = it->second; issueVector::iterator iv_it=v->begin(); bool notAnalysed = false; for (; iv_it != v->end(); ++iv_it) { ReportIssue* issue = iv_it->second; TIssueIdentity id = issue->IdentityId(); TIssueType type = issue->TypeId(); } if( v->insert(pair<const ReportIssue*, ReportIssue*>(aIssue,aIssue)).second == false ) { return -1; } } else { // header entry is not present in the report. create an entry for the header with this issue issueVector* v = new issueVector(); v->insert(pair<const ReportIssue*, ReportIssue*>(aIssue,aIssue)); issueEntry entry(key,v); iIssueMap.insert(entry); } return iIssueId-1; } // ---------------------------------------------------------------------------- // ReportGenerator::addIssue // ---------------------------------------------------------------------------- // int ReportGenerator::addIssue(const string& aFile, const string& aFQName, const TIssueIdentity& aIdentityId, const TIssueType& aTypeId, const TBCSeverity& aBCSeverityId, const TSCSeverity& aSCSeverityId, const string& aIgnoreInformation, int aLineNumber, const string& aIssueLoc, const string& aCompareFileName, const string& aCompilationError ) { ReportIssue* issue; string fqName = aFQName; int loc = fqName.find(__FUN_MANGLED__); if(loc != -1) { fqName = fqName.substr(0,loc); } string::size_type dirSepInd = aIssueLoc.find_first_of("\\/"); string isslueloc(aIssueLoc); if( dirSepInd != string::npos && isslueloc.at(dirSepInd) != DIR_SEPARATOR ) { // We need to convert to proper dir-separator replaceChar(isslueloc, isslueloc.at(dirSepInd), DIR_SEPARATOR); } if(isslueloc == aCompareFileName) issue = new ReportIssue(0, aFile, fqName, aIdentityId, aTypeId, aBCSeverityId, aSCSeverityId, aIgnoreInformation, aLineNumber, "", aCompareFileName, aCompilationError); else issue = new ReportIssue(0, aFile, fqName, aIdentityId, aTypeId, aBCSeverityId, aSCSeverityId, aIgnoreInformation, aLineNumber, isslueloc, aCompareFileName, aCompilationError); /*return*/ int ret = addIssue(issue); if( ret == -1) { delete issue; } return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::dumpXSLToFile // ---------------------------------------------------------------------------- // void ReportGenerator::dumpXSLToFile() { } // ---------------------------------------------------------------------------- // ReportGenerator::dumpDTDToFile // ---------------------------------------------------------------------------- // void ReportGenerator::dumpDTDToFile() { } // ---------------------------------------------------------------------------- // ReportGenerator::dumpDOMToFile // ---------------------------------------------------------------------------- // void ReportGenerator::dumpDOMToFile() { XMLCh* features = _X("Core"); DOMImplementation* imp = DOMImplementationRegistry::getDOMImplementation(features); _XX(features); DOMWriter* writer = ((DOMImplementationLS*)imp)->createDOMWriter(); writer->setFeature( XMLUni::fgDOMWRTFormatPrettyPrint,true); DOMErrorHandler* errorHandler = new XMLModuleErrorHandler(); // Set error handler writer->setErrorHandler(errorHandler); XMLCh* tempfilename = XMLString::transcode(iOutputFile.c_str()); XMLFormatTarget* ft = new LocalFileFormatTarget(tempfilename); writer->writeNode(ft, *iDOMDocument); XMLString::release(&tempfilename); delete ft; writer->release(); delete errorHandler; } // ---------------------------------------------------------------------------- // ReportGenerator::generateVersionIdNodes // ---------------------------------------------------------------------------- // void ReportGenerator::generateVersionIdNodes() { } // ---------------------------------------------------------------------------- // ReportGenerator::initialiseDOM // ---------------------------------------------------------------------------- // void ReportGenerator::initialiseDOM() { XMLCh * features = _X("Core"); DOMImplementation* imp = DOMImplementationRegistry::getDOMImplementation(features); _XX(features); if (imp != NULL) { try { XMLCh * repRoot = _X(NODE_REPORTROOT); DOMDocument* doc = imp->createDocument(NULL, repRoot, NULL); _XX(repRoot); if( iDOMDocument ) { iDOMDocument->release(); iDOMDocument = 0; } iDOMDocument = doc; XMLCh * stylesheet = XMLString::transcode(KXMLStyleSheet); XMLCh * xsl = XMLString::transcode(KXMLXSL); // Style sheet is inserted to DOM document iDOMDocument->insertBefore( iDOMDocument->createProcessingInstruction( stylesheet, xsl ), iDOMDocument->getDocumentElement() ); XMLString::release(&stylesheet); XMLString::release(&xsl); iDOMRoot = iDOMDocument->getDocumentElement(); // Header node created DOMElement* header = createHeaderNode(); iDOMRoot->appendChild(header); } catch (const XMLException& /*e*/) { throw HAException("Error initialising the DOM Document"); } } } // ---------------------------------------------------------------------------- // ReportGenerator::uninitialiseDOM // ---------------------------------------------------------------------------- // void ReportGenerator::uninitialiseDOM() { } // ---------------------------------------------------------------------------- // ReportGenerator::createOpenNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createOpenNode(const char* aNodeName) { DOMElement* ret = NULL; XMLCh* ch = XMLString::transcode(aNodeName); ret = iDOMDocument->createElement(ch); XMLString::release(&ch); return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::createHeaderNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createHeaderNode() { DOMElement* ret = NULL; ret = createOpenNode(NODE_HEADER); vector<DOMElement*> childvec; childvec.push_back(createSimpleTextNode(NODE_HEADER_BASELINEVERSION, iBaselineVersion.c_str())); childvec.push_back(createSimpleTextNode(NODE_HEADER_CURRENTVERSION, iCurrentVersion.c_str())); childvec.push_back(createTimestampNode()); childvec.push_back(createSimpleTextNode(NODE_HEADER_HAVERSION, HEADER_ANALYSER_VERSION)); childvec.push_back(createSimpleTextNode(NODE_HEADER_FORMATVERSION, HEADER_ANALYSER_REPORT_VERSION)); childvec.push_back(createCmdLineNode()); appendChildrenToNode(ret, childvec); return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::removeRemovedSubClasses // ---------------------------------------------------------------------------- // void ReportGenerator::removeRemovedSubClasses() { issueMapIterator it = iIssueMap.begin(); for (; it != iIssueMap.end();++it) { issueVector* iv = it->second; issueVector::iterator iv_it=iv->begin(); for (; iv_it != iv->end(); ++iv_it) { ReportIssue* issue = iv_it->second; TIssueIdentity id = issue->IdentityId(); TIssueType type = issue->TypeId(); //Do not process macros or other than issues type "removed" if ( EIssueTypeRemoval == type && EIssueIdentityMacro != id ) { string fqname = issue->FQName(); fqname += "::"; issueVector::iterator iv_it2=iv_it; ++iv_it2; for (; iv_it2 != iv->end(); ++iv_it2) { ReportIssue* issue2 = iv_it2->second; string fqname2 = issue2->FQName(); //If the issue is inside removed class it can be removed from list if ( 0 == fqname2.compare(0, fqname.length(), fqname) ) { issueVector::iterator iv_it3 = iv_it2; --iv_it2; iv->erase(iv_it3); } else //No more issues inside removed class so break { break; } } } } } } // ---------------------------------------------------------------------------- // ReportGenerator::functionMapping // ---------------------------------------------------------------------------- // TIssueIdentity ReportGenerator::functionMapping(const vector<TIssueIdentity> & ids) { TIssueIdentity ret = EIssueIdentityExportedFunction; if (ids.size() == 1) { ret = ids[0]; } else if (ids.size() == 3) { ret = EIssueIdentityExportedVirtualInlineFunction; } else { if ( (EIssueIdentityExportedFunction == ids[0] && EIssueIdentityVirtualFunction == ids[1]) || (EIssueIdentityExportedFunction == ids[1] && EIssueIdentityVirtualFunction == ids[0]) ) { ret = EIssueIdentityExportedVirtualFunction; } else if ( (EIssueIdentityExportedFunction == ids[0] && EIssueIdentityInlineFunction == ids[1]) || (EIssueIdentityExportedFunction == ids[1] && EIssueIdentityInlineFunction == ids[0]) ) { ret = EIssueIdentityExportedInlineFunction; } else if ( (EIssueIdentityInlineFunction == ids[0] && EIssueIdentityVirtualFunction == ids[1]) || (EIssueIdentityInlineFunction == ids[1] && EIssueIdentityVirtualFunction == ids[0]) ) { ret = EIssueIdentityVirtualInlineFunction; } } return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::mergeFunctionIssues // ---------------------------------------------------------------------------- // void ReportGenerator::mergeFunctionIssues() { issueMapIterator it = iIssueMap.begin(); for (; it != iIssueMap.end();++it) { issueVector* iv = it->second; issueVector::iterator iv_it=iv->begin(); for (; iv_it != iv->end(); ++iv_it) { ReportIssue* issue = iv_it->second; TIssueIdentity id = issue->IdentityId(); TIssueType type = issue->TypeId(); //Process functions only if ( EIssueIdentityExportedFunction == id || EIssueIdentityInlineFunction == id || EIssueIdentityVirtualFunction == id ) { vector<TIssueIdentity> identities; identities.reserve(3); string fqname = issue->FQName(); identities.push_back(issue->IdentityId()); issueVector::iterator iv_it2=iv_it; ++iv_it2; TBCSeverity bcseverity = issue->BCSeverity(); TSCSeverity scseverity = issue->SCSeverity(); for (; iv_it2 != iv->end(); ++iv_it2) { ReportIssue* issue2 = iv_it2->second; string fqname2 = issue2->FQName(); TIssueType type2 = issue2->TypeId(); //If the issue has same type and it is for the same function if ( (fqname2 == fqname) && (type2 == type) ) { if ( issue2->BCSeverity() < bcseverity ) { bcseverity = issue2->BCSeverity(); } if ( issue2->SCSeverity() < scseverity ) { scseverity = issue2->SCSeverity(); } identities.push_back(issue2->IdentityId()); issueVector::iterator iv_it3 = iv_it2; --iv_it2; iv->erase(iv_it3); } } if (identities.size() > 0) { issue->SetIdentityId( functionMapping(identities) ); issue->SetBCSeverity(bcseverity); issue->SetSCSeverity(scseverity); } } } } } // ---------------------------------------------------------------------------- // ReportGenerator::preprocessIssueList // ---------------------------------------------------------------------------- // void ReportGenerator::preprocessIssueList() { removeRemovedSubClasses(); mergeFunctionIssues(); } // ---------------------------------------------------------------------------- // ReportGenerator::createIssueListNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createIssueListNode() { preprocessIssueList(); DOMElement* ret = NULL; bool apiFound = false; ret = createOpenNode(NODE_ISSUELIST); issueMapIterator it = iIssueMap.begin(); while (it != iIssueMap.end()) { apiFound = false; issueVector* iv = it->second; issueVector::const_iterator iv_it = iv->begin(); DOMElement* headerfilenode = createOpenNode(NODE_ISSUELIST_HEADERFILE); DOMElement* filenamenode = createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_FILENAME, iv_it->second->HeaderFile().c_str()); headerfilenode->appendChild(filenamenode); // Append compared file here, Check from first Report issue, what was compare file name DOMElement* compareFileNameNode = createSimpleTextNode( NODE_ISSUELIST_HEADERFILE_COMPARE_FILENAME, iv_it->second->CompareFileName().c_str()); headerfilenode->appendChild( compareFileNameNode ); // START -- Support for file checksum and comments DOMElement* statusNode = createSimpleTextNode( NODE_ISSUELIST_HEADERFILE_STATUS, "" ); headerfilenode->appendChild( statusNode ); DOMElement* commentNode = createSimpleTextNode( NODE_ISSUELIST_HEADERFILE_COMMENT, "" ); headerfilenode->appendChild( commentNode ); // If Global header list is found with API info, then fill those in report file. for(unsigned int i = 0; i < HeaderInfoList.size(); i++ ) { if(stricmp (HeaderInfoList.at(i).first.c_str(), iv_it->second->CompareFileName().c_str()) == 0) { DOMElement* apiNode = createAPIAttributeNode( NODE_ISSUELIST_HEADERFILE_ISSUE_APISTRING, HeaderInfoList.at(i).second.first.c_str(), HeaderInfoList.at(i).second.second.c_str() ); headerfilenode->appendChild(apiNode); apiFound = true; } else if (stricmp( HeaderInfoList.at(i).first.c_str(), iv_it->second->HeaderFile().c_str()) == 0) { DOMElement* apiNode = createAPIAttributeNode( NODE_ISSUELIST_HEADERFILE_ISSUE_APISTRING, HeaderInfoList.at(i).second.first.c_str(), HeaderInfoList.at(i).second.second.c_str() ); headerfilenode->appendChild(apiNode); apiFound = true; } if( apiFound == true ) break; } // Global list is present, but the header has not been found from the list, then add api info for the header as "Unknown" if( apiFound == false && HeaderInfoList.size() > 0) { DOMElement* apiNode = createAPIAttributeNode( NODE_ISSUELIST_HEADERFILE_ISSUE_APISTRING, NODE_ISSUELIST_HEADERFILE_APIINFO_UNKNOWN, NODE_ISSUELIST_HEADERFILE_APIINFO_UNKNOWN ); headerfilenode->appendChild(apiNode); } //else no API info will be available for any header. char checksum[14]; if ( strlen( iv_it->second->CompareFileName().c_str() ) > 0) getFileCRC( iv_it->second->CompareFileName().c_str(), checksum ); else getFileCRC( iv_it->second->HeaderFile().c_str(), checksum ); // END -- Support for file checksum and comments //START -- Support for shortname tag string fn; string directory; list<pair<string, string> > dirs; //select current filename to display if it is present, else select base filename if ( strlen( iv_it->second->CompareFileName().c_str() ) > 0) { fn = iv_it->second->CompareFileName().c_str(); dirs = BBCFileUtils::extractFilenames(getCmdLineParm("currentdir")); } else { fn = iv_it->second->HeaderFile().c_str(); dirs = BBCFileUtils::extractFilenames(getCmdLineParm("baselinedir")); } //select appropriate baseline/current dir from the list of baseline/current dirs list<pair<string, string> >::iterator dirbegin = dirs.begin(); int p; for(; dirbegin != dirs.end(); dirbegin++) { p = toLowerCaseWin(fn).find(toLowerCaseWin(dirbegin->first),0); if(p!= string::npos) { directory = dirbegin->first; break; } } // remove baseline/current dir part of the filename string shortfilename; shortfilename.reserve(256); shortfilename = removeBase(fn,directory); // remove any leading directory separators from the filename shortfilename=trimLeadingDirSeparator(shortfilename); shortfilename = toLowerCaseWin(shortfilename); //create the shortname node DOMElement* shortNameNode = createSimpleTextNode( NODE_ISSUELIST_HEADERFILE_SHORTNAME,shortfilename.c_str() ); //END -- Support for shortname tag vector<string> issueids; for (; iv_it != iv->end(); ++iv_it) { ReportIssue* issue = iv_it->second; DOMElement* issuenode = createIssueNode(*issue); headerfilenode->appendChild(issuenode); // START -- Support for file checksum and comments string issueid; char* text; text = _X( issuenode->getElementsByTagName( _X( "typeid" ) )->item(0)->getTextContent() ); issueid = text; _XX( text ); text = _X( issuenode->getElementsByTagName( _X( "identityid" ) )->item(0)->getTextContent() ); issueid += text; _XX( text ); text = _X( issuenode->getElementsByTagName( _X( "cause" ) )->item(0)->getTextContent() ); issueid += text; _XX( text ); issueids.push_back( issueid ); // END -- Support for file checksum and comments } ret->appendChild(headerfilenode); it++; // START -- Support for file checksum and comments sort( issueids.begin(), issueids.end() ); getIssuesCRC( issueids, &checksum[7] ); DOMElement* checksumNode = createSimpleTextNode( NODE_ISSUELIST_HEADERFILE_CHECKSUM, checksum ); headerfilenode->appendChild( checksumNode ); // END -- Support for file checksum and comments //START -- Support for shortname tag // insert the shortname node headerfilenode->appendChild( shortNameNode ); //END -- Support for shortname tag } return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::createHeaderFileNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createHeaderFileNode() { DOMElement* ret = NULL; ret = createOpenNode(NODE_ISSUELIST_HEADERFILE); return ret; } // START -- Support for file checksum and comments // ---------------------------------------------------------------------------- // ReportGenerator::getIssuesCRC // ---------------------------------------------------------------------------- // void ReportGenerator::getIssuesCRC( const vector<string>& aIssueIdsVector, char* aCrcResult ) { unsigned long crc = 0xFFFFFFFFL; vector<string>::const_iterator iter = aIssueIdsVector.begin(); for ( iter = aIssueIdsVector.begin(); iter != aIssueIdsVector.end(); iter++ ) for ( unsigned char* p = (unsigned char*) (*iter).c_str(); *p != '\0'; p++ ) crc = iCrcTable[ ( crc & 0xff ) ^ *p ] ^ ( crc >> 8 ); crc ^= 0xFFFFFFFFL; // The checksum is base64-encoded into 6 characters before it is returned. for ( int i = 0; i < 6; ++i ) aCrcResult[i] = KBase64[ ( crc >> ( 30 - 6 * i ) ) & 0x3f ]; aCrcResult[6] = '\0'; return; } // END -- Support for file checksum and comments // START -- Support for file checksum and comments // ---------------------------------------------------------------------------- // ReportGenerator::getFileCRC // ---------------------------------------------------------------------------- // void ReportGenerator::getFileCRC( const char* aFilename, char* aCrcResult ) { unsigned long crc; unsigned long previousCrc; unsigned long length = 0; unsigned char* buffer = new unsigned char[512]; unsigned char* p; int count; filebuf file; // Calculate CRC for file; all sequences of whitespace and/or comments // are replaced with _one_ space. // States: // 0 : "within star comment" : starts with "/*" and ends when // the next "*/" is encountered // 1 : "within line comment" : starts with "//" and ends when // the next "/n" or "\r" is encountered // 2 : "normal mode" : "normal" text if ( file.open( aFilename, ios::in ) == NULL ) { strcpy( aCrcResult, "*************"); return; } crc = 0xFFFFFFFFL; previousCrc = 0xFFFFFFFFL; int state = 2; char previousChar = ' '; char slashPreviousChar = ' '; for ( ; ; ) { count = (int) file.sgetn( (char*) buffer, 512 ); if ( count == 0 ) { break; } for ( p = buffer; count-- != 0; p++ ) { if ( state == 0 ) { if ( previousChar == '*' && *p == '/' ) { state = 2; previousChar = slashPreviousChar; *p = ' '; } } else if ( state == 1 ) { if ( *p == '\r' || *p == '\n' ) { state = 2; previousChar = slashPreviousChar; *p = ' '; } } if ( state == 2 ) { if ( *p == '/' && previousChar != '/' ) { slashPreviousChar = previousChar; } if ( previousChar == '/' && *p == '*' ) { state = 0; crc = previousCrc; // previous char should not be included in CRC --length; *p = ' '; // do not allow /*/ to be interpreted as a comment } else if ( previousChar == '/' && *p == '/' ) { state = 1; crc = previousCrc; // previous char should not be included in CRC --length; } else { if ( *p == '\t' || *p == '\r' || *p == '\n' ) { *p = ' '; } if ( *p != ' ' || previousChar != ' ' ) { previousCrc = crc; crc = iCrcTable[ ( crc & 0xff ) ^ *p ] ^ ( crc >> 8 ); ++length; } } } previousChar = *p; } } crc ^= 0xFFFFFFFFL; file.close(); delete buffer; // The 42-bit checksum is made up of // * bits 32-41 : length of file MOD 1024 (10 bits) // * bits 0-31 : the CRC-32 value // This checksum is base64-encoded into 7 characters (42 bits / 6 bits) before it is returned. int val; length &= 0x3ff; for ( int i = 0; i < 7; ++i ) { if ( i == 0 ) val = length >> 4; else if ( i == 1 ) val = ( ( length << 2 ) | ( crc >> 30 ) ) & 0x3f; else val = ( crc >> ( 30 - 6 * ( i - 1 ) ) ) & 0x3f; aCrcResult[i] = KBase64[val]; } aCrcResult[7] = '\0'; return; } // END -- Support for file checksum and comments // ---------------------------------------------------------------------------- // ReportGenerator::createTimestampNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createTimestampNode() { DOMElement* ret = NULL; int second, minute, hour, day, month, year; time_t ttime; time(&ttime); struct tm* time = localtime(&ttime); second = time->tm_sec; minute = time->tm_min; hour = time->tm_hour; day = time->tm_mday; month = time->tm_mon + 1; year = time->tm_year + 1900; ret = createOpenNode(NODE_HEADER_TIMESTAMP); vector<DOMElement*> childvec; childvec.push_back(createSimpleTextNode(NODE_HEADER_TIMESTAMP_DAY, day)); childvec.push_back(createSimpleTextNode(NODE_HEADER_TIMESTAMP_MONTH, month)); childvec.push_back(createSimpleTextNode(NODE_HEADER_TIMESTAMP_YEAR, year)); childvec.push_back(createSimpleTextNode(NODE_HEADER_TIMESTAMP_HOUR, hour)); childvec.push_back(createSimpleTextNode(NODE_HEADER_TIMESTAMP_MINUTE, minute)); childvec.push_back(createSimpleTextNode(NODE_HEADER_TIMESTAMP_SECOND, second)); appendChildrenToNode(ret, childvec); return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::appendChildrenToNode // ---------------------------------------------------------------------------- // void ReportGenerator::appendChildrenToNode(DOMElement* aParent, const vector<DOMElement*>& aChildren) { size_t count = aChildren.size(); for (unsigned int i = 0; i < count; i++) { aParent->appendChild(aChildren.at(i)); } } // ---------------------------------------------------------------------------- // ReportGenerator::createSimpleTextNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createSimpleTextNode(const char* aNodeName, const char* aNodeText) { DOMElement* ret = NULL; XMLCh* ch = XMLString::transcode(aNodeName); XMLCh* ch2 = XMLString::transcode(aNodeText); ret = iDOMDocument->createElement(ch); DOMText* tn = iDOMDocument->createTextNode(ch2); ret->appendChild(tn); XMLString::release(&ch); XMLString::release(&ch2); return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::createSimpleTextNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createSimpleTextNode(const char* aNodeName, const XMLCh* aNodeText) { DOMElement* ret = NULL; XMLCh* ch = XMLString::transcode(aNodeName); ret = iDOMDocument->createElement(ch); DOMText* tn = iDOMDocument->createTextNode(aNodeText); ret->appendChild(tn); XMLString::release(&ch); return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::createSimpleTextNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createSimpleTextNode(const char* aNodeName, const int aInteger) { DOMElement* ret = NULL; XMLCh* ch = XMLString::transcode(aNodeName); string temp; itoa(aInteger, temp, 10); XMLCh* ch2 = XMLString::transcode(temp.c_str()); ret = iDOMDocument->createElement(ch); DOMText* tn = iDOMDocument->createTextNode(ch2); ret->appendChild(tn); XMLString::release(&ch); XMLString::release(&ch2); return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::createAttributeNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createAPIAttributeNode(const char* aNodeName, const char* aNodeAPI,const char* aNodeCategory) { DOMElement* ret = NULL; XMLCh* ch = XMLString::transcode(aNodeName); XMLCh* apivalue = XMLString::transcode(aNodeAPI); XMLCh* apiName = XMLString::transcode(NODE_ISSUELIST_HEADERFILE_ISSUE_APINAME); XMLCh* apicategoryvalue = XMLString::transcode(aNodeCategory); XMLCh* apicategoryname = XMLString::transcode(NODE_ISSUELIST_HEADERFILE_ISSUE_APICATEGORY); ret = iDOMDocument->createElement(ch); ret->setAttribute(apiName,apivalue); ret->setAttribute(apicategoryname,apicategoryvalue); XMLString::release(&ch); XMLString::release(&apivalue); XMLString::release(&apiName); XMLString::release(&apicategoryvalue); XMLString::release(&apicategoryname); return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::createCmdLineNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createCmdLineNode() { DOMElement* ret = NULL; ret = createOpenNode(NODE_HEADER_CMDLINE); map<string, string>::iterator begin = iParams.begin(); while (begin != iParams.end()) { DOMElement* ParamNode = createParmNode((*begin).first.c_str(),(*begin).second.c_str()); ret->appendChild(ParamNode); begin++; } return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::createParmNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createParmNode(const char* aKey, const char* aValue) { DOMElement* ret = NULL; // value <parm> ** </parm> ret = createOpenNode(NODE_HEADER_CMDLINE_PARM); // <pname> ret->appendChild(createSimpleTextNode(NODE_HEADER_CMDLINE_PARM_PNAME, aKey)); // <pvalue> ret->appendChild(createSimpleTextNode(NODE_HEADER_CMDLINE_PARM_PVALUE, aValue)); return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::createDocumentationUrlString // ---------------------------------------------------------------------------- // string ReportGenerator::createDocumentationUrlString(string element) { string ret; if (getCmdLineParm(DOCURL) != "Not speciefied") { ret = getCmdLineParm(DOCURL) + element; } else { ret = ""; } return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::createIssueNode // ---------------------------------------------------------------------------- // DOMElement* ReportGenerator::createIssueNode(ReportIssue& aIssue) { // IssueNode field element to report file DOMElement* ret = NULL; // create file name here ret = createOpenNode(NODE_ISSUELIST_HEADERFILE_ISSUE); vector<DOMElement*> childvec; // issue identifier field childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_ISSUEID, aIssue.Id())); // issue type identifier field childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_TYPEID, aIssue.TypeId())); // issue identify ( entity ) identifier field childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_IDENTITYID, aIssue.IdentityId())); // identity description childvec.push_back(createSimpleTextNode( NODE_ISSUELIST_HEADERFILE_ISSUE_IDENTITYDESCRIPTION, aIssue.IdentityDescription())); // issue description field childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_TYPESTRING, aIssue.TypeDescription())); // issue cause description a.k.a FQName childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_CAUSE, aIssue.FQName().c_str())); // issue documentation finder field childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_DOCUMENTATION, createDocumentationUrlString(aIssue.FQName()).c_str())); // issue ignore finder field childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_IGNOREINFORMATION, aIssue.IgnoreInformationDescription().c_str())); // issue location field if(aIssue.IssueLocation().size() != 0) childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_ISSUELOC, aIssue.IssueLocation().c_str())); // issue linenumber field childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_LINENUMBER, aIssue.LineNumber())); // issue extrainformation field //childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_EXTRAINFORMATION, aIssue.ExtraInformationDescription().c_str())); // binary compatibility severity sub field for issue DOMElement* bcseverity = createOpenNode(NODE_ISSUELIST_HEADERFILE_ISSUE_SEVERITY); bcseverity->appendChild(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_SEVERITY_TYPEID, aIssue.BCSeverity())); bcseverity->appendChild(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_SEVERITY_TYPESTRING, aIssue.BCSeverityDescription())); // source compatibility severity sub field for issue DOMElement* scseverity = createOpenNode(NODE_ISSUELIST_HEADERFILE_ISSUE_SCSEVERITY); scseverity->appendChild(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_SEVERITY_TYPEID, aIssue.SCSeverity())); scseverity->appendChild(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_SEVERITY_TYPESTRING, aIssue.SCSeverityDescription())); // if iisue type is compilation error, description of compilation error if(aIssue.TypeId() == EIssueTypeCompilationError) childvec.push_back(createSimpleTextNode(NODE_ISSUELIST_HEADERFILE_ISSUE_COMPILATION_ERROR, aIssue.CompilationError().c_str())); appendChildrenToNode(ret, childvec); ret->appendChild(bcseverity); ret->appendChild(scseverity); return ret; } // ---------------------------------------------------------------------------- // ReportGenerator::createSeverityNode // ---------------------------------------------------------------------------- // //DOMElement* ReportGenerator::createSeverityNode(const int aId) DOMElement* ReportGenerator::createSeverityNode() { DOMElement* ret = NULL; ret = createOpenNode(NODE_ISSUELIST_HEADERFILE_ISSUE_SEVERITY); return ret; }
[ "none@none" ]
[ [ [ 1, 1173 ] ] ]
caf098671194ed0c6477d3b76835b32f541c0a5e
fe24c79c39afe2e8e3bcba87884f084ee4bf5d3b
/source/Raytracer.cpp
ca96b095feb35e35bf60c0608ca611c844279ed3
[]
no_license
chuckiesmals/Thesis
e4622898990fa4e2e4faa057cf4be273799e3b9e
d9288bbe1d7091fc542699337ead8ceaebfd51de
refs/heads/master
2016-08-02T20:30:37.260931
2010-12-19T00:05:09
2010-12-19T00:05:09
1,180,762
1
0
null
null
null
null
UTF-8
C++
false
false
14,696
cpp
#include "Raytracer.h" void check(float x) { if (x < 0) { int ohgod = 3498; } } Raytracer::Raytracer() { _defaultColor = Color3(0, 216.0f/255.0f, 1.0f); _photonMap = new PhotonGrid(0.1f); } int Raytracer::setScene(const Scene::Ref& scene) { _currentScene = scene; Array<Surface::Ref> surfaceArray; scene->onPose(surfaceArray); _triTree.setContents(surfaceArray, COPY_TO_CPU); return _triTree.size(); } void Raytracer::generatePhotonMap(const RenderSettings& settings) { _settings = settings; _photonMap->clear(); photonMapForwardTrace(); } int gStatus = 0; int gNumPixelsRendered = 0; Image3::Ref Raytracer::render(const RenderSettings& settings, const GCamera& camera, Vector2int16 pixel) { gStatus = 0; gNumPixelsRendered = 0; _renderedImage = Image3::createEmpty(); _renderedImage->resize(settings._width, settings._height); _currentCamera = camera; _settings = settings; _photonMap->clear(); if (settings._usePhotonMap) { if (_photonMap->size() == 0) { photonMapForwardTrace(); } } if (pixel.x == ALL && pixel.y == ALL) { if (settings._multiThreaded) { GThread::runConcurrently2D( Vector2int32(0,0), Vector2int32(settings._width, settings._height), this, &Raytracer::backwardTrace); } else { for (int y = 0; y < settings._height; ++y) { for (int x = 0; x < settings._width; ++x) { backwardTrace(x, y); } } } } else { backwardTrace(pixel.x, pixel.y); } return _renderedImage; } //================================= // Forward Trace //================================= void Raytracer::photonMapForwardTrace() { const int numberOfBounces = _settings._forwardBounces; const int numberOfPhotons = _settings._numberOfPhotons; // Go through all lights in scene for (int i = 0; i < _currentScene->lighting()->lightArray.length(); ++i) { GLight& light = _currentScene->lighting()->lightArray[i]; const bool isSpotLight = false; if (!isSpotLight) { // create hemisphere of light rays and bounce, bounce, bounce emitLightPhotons(light, numberOfBounces, numberOfPhotons); } } } void Raytracer::emitLightPhotons(const GLight& light, const int bouncesLeft, const int numberOfPhotons) { const Power3 powerPerPhoton = light.color / numberOfPhotons; for (int i = 0; i < numberOfPhotons; ++i) { // http://mathworld.wolfram.com/SpherePointPicking.html float x1 = _random.uniform(-1, 1); float x2 = _random.uniform(-1, 1); while (x1*x1 + x2*x2 >= 1) { x1 = _random.uniform(-1, 1); x2 = _random.uniform(-1, 1); } const float x = 2 * x1 * sqrt(1 - x1*x1 - x2*x2); // (9) const float y = 2 * x2 * sqrt(1 - x1*x1 - x2*x2); // (10) const float z = 1 - 2 * (x1*x1 + x2*x2); // (11) const Vector3 direction = Vector3(x,y,z).direction(); Photon* photon = new Photon(light.position.xyz(), -direction, powerPerPhoton); forwardTrace(photon, bouncesLeft, numberOfPhotons); } } void Raytracer::forwardTrace(Photon* photon, const int bouncesLeft, const int numberOfPhotons) { if (bouncesLeft > 0) { Tri::Intersector intersector; float distance = inf(); Ray photonRay(photon->position, photon->direction); if (_triTree.intersectRay(photonRay, intersector, distance)) { Color3 pixelColor; Vector3 position, normal; Vector2 texCoord; intersector.getResult(position, normal, texCoord); photon->position = position + normal * 0.0001f; Photon* photonCopy = new Photon(photon); //if (bouncesLeft != _settings._forwardBounces) { _photonMap->insert(photon); } SurfaceSample surfaceSample(intersector); if (scatter(intersector, photonCopy)) { forwardTrace(photonCopy, bouncesLeft - 1, numberOfPhotons); } } } } bool Raytracer::scatter(const SurfaceSample& s, Photon* p) const { bool scatter = false; float t = _random.uniform(0, 1); // Check Impulses SuperBSDF::Ref bsdf = s.material->bsdf(); SmallArray<SuperBSDF::Impulse, 3> impulseArray; bsdf->getImpulses(s.shadingNormal, s.texCoord, p->direction, impulseArray); // todo: check p.direction Color3 impulseSum; for (int i = 0; i < impulseArray.size(); ++i) { if (impulseArray[i].coefficient.average() < 0) { int sures = 234; } //t -= impulseArray[i].coefficient.average(); impulseSum += impulseArray[i].coefficient; if (t - impulseArray[i].coefficient.average() < 0) { scatter = true; p->direction = impulseArray[i].w; p->power = p->power * t / impulseArray[i].coefficient.average(); check(p->power.average()); break; } } // Check Diffuse if (!scatter) { const Component4 lambertian = bsdf->lambertian(); //t - (s.lambertianReflect * (1 - impulseSum.average())).average(); if (t - (s.lambertianReflect * (1 - impulseSum.average())).average() < 0) { scatter = true; p->direction = Vector3::cosHemiRandom(s.shadingNormal); //p->power = p->power * (t / (s.lambertianReflect * (1 - impulseSum.average())).average()); p->power = p->power * (t / (s.lambertianReflect.average()));// * (1 - impulseSum.average())).average()); check(p->power.average()); } } return scatter; } //================================= // Backward Trace - Shading //================================= void Raytracer::backwardTrace(int x, int y) { Color3 pixelColor = _defaultColor; Ray ray; if (_settings._debugPixelTrace) { ray = _currentCamera.worldRay(x+0.5f, y+0.5f, Rect2D::xywh(0, 0, 1440, 800)); } else { ray = _currentCamera.worldRay(x+0.5f, y+0.5f, Rect2D::xywh(0, 0, _settings._width, _settings._height)); } pixelColor = backwardTrace(ray, _settings._backwardBounces); if (!_settings._debugPixelTrace) { _renderedImage->set(x, y, pixelColor); } gNumPixelsRendered++; if (gNumPixelsRendered / (_settings._width * _settings._height) > 0.2f && gStatus < 2) { printf("20%%\n"); gStatus = 2; } else if (gNumPixelsRendered / (_settings._width * _settings._height) > 0.4f && gStatus < 4) { printf("40%%\n"); gStatus = 4; } else if (gNumPixelsRendered / (_settings._width * _settings._height) > 0.6f && gStatus < 6) { printf("60%%\n"); gStatus = 6; } else if (gNumPixelsRendered / (_settings._width * _settings._height) > 0.8f && gStatus < 8) { printf("80%%\n"); gStatus = 8; } } Radiance3 Raytracer::backwardTrace(const Ray& ray, int backwardBouncesLeft) const { Color3 pixelColor; Tri::Intersector intersector; float distance = inf(); // use tri tree if (_settings._useTriTree) { if (_triTree.intersectRay(ray, intersector, distance)) { pixelColor = shadePixel(intersector, ray, backwardBouncesLeft); } } // or just go through array else { distance = inf(); for (int i = 0; i < _triTree.size(); ++i) { intersector(ray, _triTree[i], distance); if (distance < inf()) { pixelColor = shadePixel(intersector, ray, backwardBouncesLeft); } } } return pixelColor; } Color3 Raytracer::shadePixel(const Tri::Intersector& intersector, const Ray& ray, int backwardBouncesLeft) const { Color3 pixelColor; Vector3 position, normal; Vector2 texCoord; intersector.getResult(position, normal, texCoord); SurfaceSample surfaceSample(intersector); if (_settings._useSuperBSDF) { if(_settings._useDirectShading) { pixelColor = shadeDirectBSDF(surfaceSample, ray); } pixelColor += shadeSpecularBSDF(surfaceSample, -ray.direction(), backwardBouncesLeft); if (_settings._usePhotonMap) { pixelColor += shadeIndirectIllumination(surfaceSample); } } else { pixelColor = myShadePixel(intersector, ray, backwardBouncesLeft); } return pixelColor; } bool Raytracer::isInSpotlight(const GLight& light, const Vector3 w_i) const { bool returnValue = false; // Spotlight const bool firstTerm = light.spotHalfAngle < halfPi(); const float lightIn_dot_spotDirection = -w_i.dot(light.spotDirection); const float cosSpotHalfAngle = cosf(light.spotHalfAngle); const bool secondTerm = lightIn_dot_spotDirection < cosSpotHalfAngle; const bool outsideSpotLight = firstTerm && secondTerm; if (!outsideSpotLight) { returnValue = true; } return returnValue; } bool Raytracer::isInShadow(const SurfaceSample& intersector, const Vector3 w_i, const float lightDistance) const { bool returnValue = false; if (_settings._shadowCast) { // Check if in Shadow, cast ray backwards, up to distance to light.... Ray rayToLight(intersector.shadingLocation + (intersector.shadingNormal * 0.0001f), (w_i.unit())); Tri::Intersector shadowIntersector; float shadowDistance = lightDistance; if (_triTree.intersectRay(rayToLight, shadowIntersector, shadowDistance)) { returnValue = true; } } return returnValue; } Color3 Raytracer::myShadePixel(const Tri::Intersector& intersector, const Ray& ray, int backwardBouncesLeft) const { ray; backwardBouncesLeft; Vector3 position, normal; Vector2 texCoord; intersector.getResult(position, normal, texCoord); SurfaceSample surfaceSample(intersector); Color3 lightContribution(0,0,0); for (int i = 0; i < _currentScene->lighting()->lightArray.length(); ++i) { GLight& light = _currentScene->lighting()->lightArray[i]; const float lightDistance = light.distance(position); const Power3 power = light.power().rgb(); check(power.average()); const float lightArea = 4 * pif() * lightDistance * lightDistance; const Color3 kx = surfaceSample.lambertianReflect; const Vector3 light_in = (light.position.xyz() - position).unit(); const float lightIn_dot_normal = light_in.dot(normal); // Spotlight if (!isInSpotlight(light, light_in)) { continue; } if (isInShadow(surfaceSample, light_in, lightDistance)) { continue; } Color3 fx(0, 0, 0); if (lightIn_dot_normal > 0) { fx = kx / pif(); } lightContribution += (power / lightArea) * lightIn_dot_normal * fx; } return lightContribution; } Radiance3 Raytracer::shadeSpecularBSDF(const SurfaceSample& intersector, const Vector3& w_o, int backwardBounces) const { Radiance3 L_r; if (backwardBounces > 1) { SuperBSDF::Ref bsdf = intersector.material->bsdf(); SmallArray<SuperBSDF::Impulse, 3> impulseArray; bsdf->getImpulses(intersector.shadingNormal, intersector.texCoord, w_o, impulseArray); for (int i = 0; i < impulseArray.size(); ++i) { const SuperBSDF::Impulse& impulse = impulseArray[i]; Ray ray(intersector.shadingLocation, impulse.w); Radiance3 L_in = backwardTrace(ray, backwardBounces-1); L_r += L_in * impulse.coefficient; } } return L_r; } Color3 Raytracer::shadeDirectBSDF(const SurfaceSample& intersector, const Ray& ray) const { Color3 lightContribution(0,0,0); for (int i = 0; i < _currentScene->lighting()->lightArray.length(); ++i) { GLight& light = _currentScene->lighting()->lightArray[i]; const Point3& X = intersector.shadingLocation; const Point3& n = intersector.shadingNormal; const Vector3& diff = light.position.xyz() - X; const Vector3 w_i = diff.direction(); const float distance = diff.length(); const Vector3 w_eye = -ray.direction(); const Power3& Phi = light.color.rgb(); if (!isInSpotlight(light, w_i)) { continue; } if (isInShadow(intersector, w_i, distance)) { continue; } // power area const Color3& E_i = w_i.dot(n) * Phi / (4 * pif() * (distance*distance)); const SuperBSDF::Ref bsdf = intersector.material->bsdf(); const Color3& bsdfColor = bsdf->evaluate(intersector.shadingNormal, intersector.texCoord, w_i, w_eye).rgb(); lightContribution += bsdfColor * E_i + intersector.emit; } return lightContribution; } float k (float x, float radius) { return (1 - (x / radius)); } Radiance3 Raytracer::shadeIndirectIllumination(const SurfaceSample& intersector) const { if (_settings._debugPixelTrace) { int suresh = 1374; } Radiance3 accumulatedPhotonRadiance; const Point3& X = intersector.shadingLocation; const Point3& n = intersector.shadingNormal; const float radius = _settings._photonGatherRadius; const SuperBSDF::Ref bsdf = intersector.material->bsdf(); static bool increaseGathering = true; if (increaseGathering) { const int gatheredPhotons = 5000; int numberOfPhotons = 0; float increasingRadius = 0.0f; static float increasingRate = 0.05f; while (numberOfPhotons < gatheredPhotons && increasingRadius < radius) { // Gather all photons within radius of intersection const Sphere sphere(X, increasingRadius); PhotonGrid::SphereIterator it = _photonMap->beginSphereIntersection(sphere); while (it.hasMore()) { numberOfPhotons++; ++it; } increasingRadius += increasingRate; } const Sphere sphere(X, increasingRadius); PhotonGrid::SphereIterator it = _photonMap->beginSphereIntersection(sphere); //printf("%4.2f\n", increasingRadius); while (it.hasMore()) { const Vector3& diff = it->position.xyz() - X; const Vector3 w_i = diff.direction(); const Vector3 w_eye = -(it->direction); const Color3& bsdfColor = bsdf->evaluate(intersector.shadingNormal, intersector.texCoord, w_i, w_eye).rgb(); Radiance3 photo_illum = (it->power / ((pif() * increasingRadius*increasingRadius)/3)) * k((it->position - X).magnitude(), increasingRadius); photo_illum = photo_illum * max(0.0f, (it->direction * -1).dot(n)); photo_illum = photo_illum * bsdfColor; accumulatedPhotonRadiance += photo_illum; ++it; } } else { // Gather all photons within radius of intersection const Sphere sphere(X, radius); PhotonGrid::SphereIterator it = _photonMap->beginSphereIntersection(sphere); while (it.hasMore()) { const Vector3& diff = it->position.xyz() - X; const Vector3 w_i = diff.direction(); const Vector3 w_eye = -(it->direction); const Color3& bsdfColor = bsdf->evaluate(intersector.shadingNormal, intersector.texCoord, w_i, w_eye).rgb(); Radiance3 photo_illum = (it->power / ((pif() * radius*radius)/3)) * k((it->position - X).magnitude(), radius); photo_illum = photo_illum * max(0.0f, (it->direction * -1).dot(n)); photo_illum = photo_illum * bsdfColor; accumulatedPhotonRadiance += photo_illum; ++it; } } // Sum their power return accumulatedPhotonRadiance; }
[ [ [ 1, 556 ] ] ]
f5e38730ba97987b17dfcfdb5a394e042d24734f
a0155e192c9dc2029b231829e3db9ba90861f956
/MailFilter/Main/MFMail.h++
184c86a7c0392b169719f2b944a09f69932266fa
[]
no_license
zeha/mailfilter
d2de4aaa79bed2073cec76c93768a42068cfab17
898dd4d4cba226edec566f4b15c6bb97e79f8001
refs/heads/master
2021-01-22T02:03:31.470739
2010-08-12T23:51:35
2010-08-12T23:51:35
81,022,257
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,970
/* + + MFMail.h++ + + Mail Data Structures + + This is MailFilter! + www.mailfilter.cc + + Copyright 2002 Christian Hofstädtler. + + + - Aug/2002 ; ch ; Initial Code + + */ //#include <string.h> #include "MailFilter.h" #include <iXList.h> #ifndef _MFMAIL_HPP_ #define _MFMAIL_HPP_ // This header is not for generic C! #ifdef __cplusplus typedef struct MailFilter_MailData { char* szFileName; char* szFileIn; char* szFileOut; char* szFileWork; char* szScanDirectory; int iMailSource; long iMailSize; // dont change for 64bit unless all functions are able to handle 64bit! long iTotalAttachmentSize; unsigned long iMailTimestamp; int iNumOfAttachments; char* szProblemMailDestination; char* szEnvelopeFrom; char* szEnvelopeRcpt; char* szMailFrom; char* szMailRcpt; char* szMailCC; char* szMailSubject; bool bHaveFrom; bool bHaveRcpt; bool bHaveCC; bool bHaveSubject; char* szErrorMessage; bool bFilterMatched; int iFilterNotify; int iFilterAction; int iFilterHandle; bool bSchedule; int iPriority; char* szReceivedFrom; bool bHaveReceivedFrom; bool bCopy; bool bBrokenMessage; bool bPartialMessage; // below only things we cannot copy to the MFS file iXList* lstAttachments; iXList* lstArchiveContents; iXList* lstCopies; } MailFilter_MailData; MailFilter_MailData* MailFilter_MailInit(const char* szFileName, int iMailSource); int MailFilter_MailDestroy(MailFilter_MailData* mail); int MailFilter_MailWrite(const char* szOutFile, MailFilter_MailData* m); MailFilter_MailData* MailFilter_MailRead(const char* szInFile); extern int MF_MailProblemReport(MailFilter_MailData* mMailInfo); extern int MF_Notification_Send2(const char messageType, const char* bounceRcpt, MailFilter_MailData* mMailInfo); extern int MF_ParseMail(MailFilter_MailData* m, bool bMiniMode); #endif #endif /*++eof++*/
[ [ [ 1, 81 ] ] ]
e0801dffa991b364997afbe8e71861bc17e7c32d
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-12-22/pcbnew/netlist.cpp
83fc0e406f26c29d1a8a7492ff222a298b0c070e
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
30,861
cpp
/************************************/ /* PCBNEW: traitement des netlistes */ /************************************/ /* Fichier NETLIST.CPP */ /* Fonction de lecture de la netliste pour: - Chargement modules et nouvelles connexions - Test des modules (modules manquants ou en trop - Recalcul du chevelu Remarque importante: Lors de la lecture de la netliste pour Chargement modules et nouvelles connexions, l'identification des modules peut se faire selon 2 criteres: - la reference (U2, R5 ..): c'est le mode normal - le Time Stamp (Signature Temporelle), a utiliser apres reannotation d'un schema, donc apres modification des references sans pourtant avoir reellement modifie le schema */ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "pcbnew.h" #include "autorout.h" #include "protos.h" #define TESTONLY 1 /* ctes utilisees lors de l'appel a */ #define READMODULE 0 /* ReadNetModuleORCADPCB */ /* Structures locales */ class MODULEtoLOAD : public EDA_BaseStruct { public: wxString m_LibName; wxString m_CmpName; public: MODULEtoLOAD(const wxString & libname, const wxString & cmpname, int timestamp); ~MODULEtoLOAD(void){}; MODULEtoLOAD * Next(void) { return (MODULEtoLOAD *) Pnext; } }; /* Fonctions locales : */ static void SortListModulesToLoadByLibname(int NbModules); /* Variables locales */ static int s_NbNewModules; static MODULEtoLOAD * s_ModuleToLoad_List; FILE * source; static bool ChangeExistantModule; static bool DisplayWarning = TRUE; static int DisplayWarningCount ; /*****************************/ /* class WinEDA_NetlistFrame */ /*****************************/ enum id_netlist_functions { ID_READ_NETLIST_FILE = 1900, ID_TEST_NETLIST, ID_CLOSE_NETLIST, ID_COMPILE_RATSNEST, ID_OPEN_NELIST }; class WinEDA_NetlistFrame: public wxDialog { private: WinEDA_PcbFrame * m_Parent; wxDC * m_DC; wxRadioBox * m_Select_By_Timestamp; wxRadioBox * m_DeleteBadTracks; wxRadioBox * m_ChangeExistantModuleCtrl; wxCheckBox * m_DisplayWarningCtrl; wxTextCtrl * m_MessageWindow; public: // Constructor and destructor WinEDA_NetlistFrame(WinEDA_PcbFrame *parent, wxDC * DC, const wxPoint & pos); ~WinEDA_NetlistFrame(void) { } private: void OnQuit(wxCommandEvent& event); void ReadPcbNetlist(wxCommandEvent& event); void Set_NetlisteName(wxCommandEvent& event); bool OpenNetlistFile(wxCommandEvent& event); int BuildListeNetModules(wxCommandEvent& event, wxArrayString & BufName); void ModulesControle(wxCommandEvent& event); void RecompileRatsnest(wxCommandEvent& event); int ReadListeModules(const wxString * RefCmp, long TimeStamp, wxString & NameModule); int SetPadNetName( char * Line, MODULE * Module); MODULE * ReadNetModule( char * Text, int * UseFichCmp, int TstOnly); void AddToList(const wxString & NameLibCmp, const wxString & NameCmp,int TimeStamp ); void LoadListeModules(wxDC *DC); DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(WinEDA_NetlistFrame, wxDialog) EVT_BUTTON(ID_READ_NETLIST_FILE, WinEDA_NetlistFrame::ReadPcbNetlist) EVT_BUTTON(ID_CLOSE_NETLIST, WinEDA_NetlistFrame::OnQuit) EVT_BUTTON(ID_OPEN_NELIST, WinEDA_NetlistFrame::Set_NetlisteName) EVT_BUTTON(ID_TEST_NETLIST, WinEDA_NetlistFrame::ModulesControle) EVT_BUTTON(ID_COMPILE_RATSNEST, WinEDA_NetlistFrame::RecompileRatsnest) END_EVENT_TABLE() /*************************************************************************/ void WinEDA_PcbFrame::InstallNetlistFrame( wxDC * DC, const wxPoint & pos) /*************************************************************************/ { WinEDA_NetlistFrame * frame = new WinEDA_NetlistFrame(this, DC, pos); frame->ShowModal(); frame->Destroy(); } /******************************************************************/ WinEDA_NetlistFrame::WinEDA_NetlistFrame(WinEDA_PcbFrame *parent, wxDC * DC, const wxPoint & framepos): wxDialog(parent, -1, wxEmptyString, framepos, wxSize(-1, -1), DIALOG_STYLE) /******************************************************************/ { wxPoint pos; wxString number; wxString title; wxButton * Button; m_Parent = parent; SetFont(*g_DialogFont); m_DC = DC; Centre(); /* Mise a jour du Nom du fichier NETLISTE correspondant */ NetNameBuffer = m_Parent->m_CurrentScreen->m_FileName; ChangeFileNameExt(NetNameBuffer, NetExtBuffer); title = _("Netlist: ") + NetNameBuffer; SetTitle(title); /* Creation des boutons de commande */ pos.x = 170; pos.y = 10; Button = new wxButton(this, ID_OPEN_NELIST, _("Select"), pos); Button->SetForegroundColour(*wxRED); pos.y += Button->GetDefaultSize().y + 10; Button = new wxButton(this, ID_READ_NETLIST_FILE, _("Read"), pos); Button->SetForegroundColour(wxColor(0,80,0) ); pos.y += Button->GetDefaultSize().y + 10; Button = new wxButton(this, ID_TEST_NETLIST, _("Module Test"), pos); Button->SetForegroundColour(wxColor(0,80,80) ); pos.y += Button->GetDefaultSize().y + 10; Button = new wxButton(this, ID_COMPILE_RATSNEST, _("Compile"), pos); Button->SetForegroundColour(wxColor(0,0,80) ); pos.y += Button->GetDefaultSize().y + 10; Button = new wxButton(this, ID_CLOSE_NETLIST, _("Close"), pos); Button->SetForegroundColour(*wxBLUE); // Options: wxString opt_select[2] = { _("Reference"), _("Timestamp") }; pos.x = 15; pos.y = 10; m_Select_By_Timestamp = new wxRadioBox( this, -1, _("Module Selection:"), pos, wxDefaultSize, 2, opt_select, 1); wxString track_select[2] = { _("Keep"), _("Delete") }; int x, y; m_Select_By_Timestamp->GetSize(&x, &y); pos.y += 5 + y; m_DeleteBadTracks = new wxRadioBox(this, -1, _("Bad Tracks Deletion:"), pos, wxDefaultSize, 2, track_select, 1); m_DeleteBadTracks->GetSize(&x, &y); pos.y += 5 + y; wxString change_module_select[2] = { _("Keep"), _("Change") }; m_ChangeExistantModuleCtrl = new wxRadioBox(this, -1, _("Exchange Module:"), pos, wxDefaultSize, 2, change_module_select, 1); m_ChangeExistantModuleCtrl->GetSize(&x, &y); pos.y += 15 + y; m_DisplayWarningCtrl = new wxCheckBox(this, -1, _("Display Warnings"), pos); m_DisplayWarningCtrl->SetValue(DisplayWarning); m_DisplayWarningCtrl->GetSize(&x, &y); pos.x = 5; pos.y += 10 + y; m_MessageWindow = new wxTextCtrl(this, -1, wxEmptyString, pos, wxSize(265, 120),wxTE_READONLY|wxTE_MULTILINE); m_MessageWindow->GetSize(&x, &y); pos.y += 10 + y; SetClientSize(280, pos.y); } /**********************************************************************/ void WinEDA_NetlistFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) /**********************************************************************/ { // true is to force the frame to close Close(true); } /*****************************************************************/ void WinEDA_NetlistFrame::RecompileRatsnest(wxCommandEvent& event) /*****************************************************************/ { m_Parent->Compile_Ratsnest(m_DC, TRUE); } /***************************************************************/ bool WinEDA_NetlistFrame::OpenNetlistFile(wxCommandEvent& event) /***************************************************************/ /* routine de selection et d'ouverture du fichier Netlist */ { wxString FullFileName; wxString msg; if( NetNameBuffer == wxEmptyString ) /* Pas de nom specifie */ Set_NetlisteName(event); if( NetNameBuffer == wxEmptyString ) return(FALSE); /* toujours Pas de nom specifie */ FullFileName = NetNameBuffer; source = wxFopen(FullFileName, wxT("rt") ); if (source == 0) { msg.Printf(_("Netlist file %s not found"),FullFileName.GetData()) ; DisplayError(this, msg) ; return FALSE ; } msg = wxT("Netlist "); msg << FullFileName; SetTitle(msg); return TRUE; } /**************************************************************/ void WinEDA_NetlistFrame::ReadPcbNetlist(wxCommandEvent& event) /**************************************************************/ /* mise a jour des empreintes : corrige les Net Names, les textes, les "TIME STAMP" Analyse les lignes: # EESchema Netlist Version 1.0 generee le 18/5/2005-12:30:22 ( ( 40C08647 $noname R20 4,7K {Lib=R} ( 1 VCC ) ( 2 MODB_1 ) ) ( 40C0863F $noname R18 4,7_k {Lib=R} ( 1 VCC ) ( 2 MODA_1 ) ) } #End */ { int LineNum, State, Comment; MODULE * Module = NULL; D_PAD * PtPad; char Line[256], *Text; int UseFichCmp = 1; wxString msg; ChangeExistantModule = m_ChangeExistantModuleCtrl->GetSelection() == 1 ? TRUE : FALSE; DisplayWarning = m_DisplayWarningCtrl->GetValue(); if ( DisplayWarning ) DisplayWarningCount = 8; else DisplayWarningCount = 0; if( ! OpenNetlistFile(event) ) return; msg = _("Read Netlist ") + NetNameBuffer; m_MessageWindow->AppendText(msg); m_Parent->m_CurrentScreen->SetModify(); m_Parent->m_Pcb->m_Status_Pcb = 0 ; State = 0; LineNum = 0; Comment = 0; s_NbNewModules = 0; /* Premiere lecture de la netliste: etablissement de la liste des modules a charger */ while( GetLine( source, Line, &LineNum) ) { Text = StrPurge(Line); if ( Comment ) /* Commentaires en cours */ { if( (Text = strchr(Text,'}') ) == NULL )continue; Comment = 0; } if ( *Text == '{' ) /* Commentaires */ { Comment = 1; if( (Text = strchr(Text,'}') ) == NULL ) continue; } if ( *Text == '(' ) State++; if ( *Text == ')' ) State--; if( State == 2 ) { Module = ReadNetModule(Text, & UseFichCmp, TESTONLY); continue; } if( State >= 3 ) /* la ligne de description d'un pad est ici non analysee */ { State--; } } /* Chargement des nouveaux modules */ if( s_NbNewModules ) { LoadListeModules(m_DC); // Free module list: MODULEtoLOAD * item, *next_item; for ( item = s_ModuleToLoad_List; item != NULL; item = next_item ) { next_item = item->Next(); delete item; } s_ModuleToLoad_List = NULL; } /* Relecture de la netliste, tous les modules sont ici charges */ fseek(source, 0, SEEK_SET); LineNum = 0; while( GetLine( source, Line, &LineNum) ) { Text = StrPurge(Line); if ( Comment ) /* Commentaires en cours */ { if( (Text = strchr(Text,'}') ) == NULL )continue; Comment = 0; } if ( *Text == '{' ) /* Commentaires */ { Comment = 1; if( (Text = strchr(Text,'}') ) == NULL ) continue; } if ( *Text == '(' ) State++; if ( *Text == ')' ) State--; if( State == 2 ) { Module = ReadNetModule(Text, & UseFichCmp, READMODULE ); if( Module == NULL ) { /* empreinte non trouvee dans la netliste */ continue ; } else /* Raz netnames sur pads */ { PtPad = Module->m_Pads; for( ; PtPad != NULL; PtPad = (D_PAD *)PtPad->Pnext ) { PtPad->m_Netname = wxEmptyString; } } continue; } if( State >= 3 ) { if ( Module ) { SetPadNetName( Text, Module); } State--; } } fclose(source); /* Mise a jour et Cleanup du circuit imprime: */ m_Parent->Compile_Ratsnest(m_DC, TRUE); if( m_Parent->m_Pcb->m_Track ) { if( m_DeleteBadTracks->GetSelection() == 1 ) { wxBeginBusyCursor();; Netliste_Controle_piste(m_Parent, m_DC, TRUE); m_Parent->Compile_Ratsnest(m_DC, TRUE); wxEndBusyCursor();; } } Affiche_Infos_Status_Pcb(m_Parent); } /****************************************************************************/ MODULE * WinEDA_NetlistFrame::ReadNetModule(char * Text, int * UseFichCmp, int TstOnly) /****************************************************************************/ /* charge la description d'une empreinte ,netliste type PCBNEW et met a jour le module correspondant Si TstOnly == 0 si le module n'existe pas, il est charge Si TstOnly != 0 si le module n'existe pas, il est ajoute a la liste des modules a charger Text contient la premiere ligne de la description * UseFichCmp est un flag si != 0, le fichier des composants .CMP sera utilise est remis a 0 si le fichier n'existe pas Analyse les lignes type: ( 40C08647 $noname R20 4,7K {Lib=R} ( 1 VCC ) ( 2 MODB_1 ) */ { MODULE * Module; char * text; wxString TextTimeStamp; wxString TextNameLibMod; wxString TextValeur; wxString TextCmpName; wxString NameLibCmp; long TimeStamp = -1; int Error = 0; char Line[1024]; bool Found; strcpy(Line,Text); if( (text = strtok(Line, " ()\t\n")) == NULL ) Error = 1; else TextTimeStamp = CONV_FROM_UTF8(text); if( ( text = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; else TextNameLibMod = CONV_FROM_UTF8(text); if( (text = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; else TextCmpName = CONV_FROM_UTF8(text); if( (text = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; else TextValeur = CONV_FROM_UTF8(text); if( Error ) return( NULL ); TextTimeStamp.ToLong( &TimeStamp); /* Tst si composant deja charge */ Module = (MODULE*) m_Parent->m_Pcb->m_Modules; MODULE * NextModule; for( Found = FALSE; Module != NULL; Module = NextModule ) { NextModule = (MODULE*)Module->Pnext; if( m_Select_By_Timestamp->GetSelection() == 1 ) /* Reconnaissance par signature temporelle */ { if( TimeStamp == Module->m_TimeStamp) Found = TRUE; } else /* Reconnaissance par Reference */ { if( TextCmpName.CmpNoCase(Module->m_Reference->m_Text) == 0 ) Found = TRUE; } if ( Found ) // Test si module (m_LibRef) et module specifie en netlist concordent { if( TstOnly != TESTONLY ) { NameLibCmp = TextNameLibMod; if( *UseFichCmp ) { if( m_Select_By_Timestamp->GetSelection() == 1 ) { /* Reconnaissance par signature temporelle */ *UseFichCmp = ReadListeModules(NULL, TimeStamp, NameLibCmp); } else /* Reconnaissance par Reference */ { *UseFichCmp = ReadListeModules(&TextCmpName, 0l, NameLibCmp); } } if (Module->m_LibRef.CmpNoCase(NameLibCmp) != 0 ) {// Module Mismatch: Current module and module specified in netlist are diff. if ( ChangeExistantModule ) { MODULE * NewModule = m_Parent->Get_Librairie_Module(this, wxEmptyString, NameLibCmp, TRUE); if( NewModule ) /* Nouveau module trouve : changement de module */ Module = m_Parent->Exchange_Module(this, Module, NewModule); } else { wxString msg; msg.Printf( _("Cmp %s: Mismatch! module is [%s] and netlist said [%s]\n"), TextCmpName.GetData(), Module->m_LibRef.GetData(), NameLibCmp.GetData()); m_MessageWindow->AppendText(msg); if ( DisplayWarningCount > 0) { DisplayError(this, msg, 2); DisplayWarningCount--; } } } } break; } } if( Module == NULL ) /* Module a charger */ { NameLibCmp = TextNameLibMod; if( *UseFichCmp ) { if( m_Select_By_Timestamp->GetSelection() == 1) { /* Reconnaissance par signature temporelle */ *UseFichCmp = ReadListeModules(NULL, TimeStamp, NameLibCmp); } else /* Reconnaissance par Reference */ { *UseFichCmp = ReadListeModules(&TextCmpName, 0l, NameLibCmp); } } if( TstOnly == TESTONLY) AddToList(NameLibCmp, TextCmpName, TimeStamp); else { wxString msg; msg.Printf( _("Component [%s] not found"), TextCmpName.GetData()); m_MessageWindow->AppendText( msg + wxT("\n")); if (DisplayWarningCount> 0) { DisplayError(this, msg, 2); DisplayWarningCount--; } } return(NULL); /* Le module n'avait pas pu etre charge */ } /* mise a jour des reperes ( nom et ref "Time Stamp") si module charge */ Module->m_Reference->m_Text = TextCmpName; Module->m_Value->m_Text = TextValeur; Module->m_TimeStamp = TimeStamp; return(Module) ; /* composant trouve */ } /********************************************************************/ int WinEDA_NetlistFrame::SetPadNetName( char * Text, MODULE * Module) /********************************************************************/ /* Met a jour le netname de 1 pastille, Netliste ORCADPCB entree : Text = ligne de netliste lue ( (pad = net) ) Module = adresse de la structure MODULE a qui appartient les pads */ { D_PAD * pad; char * TextPinName, * TextNetName; int Error = 0; bool trouve; char Line[256]; wxString Msg; if( Module == NULL ) return ( 0 ); strcpy( Line, Text); if( (TextPinName = strtok(Line, " ()\t\n")) == NULL ) Error = 1; if( (TextNetName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; if(Error) return(0); /* recherche du pad */ pad = Module->m_Pads; trouve = FALSE; for( ; pad != NULL; pad = (D_PAD *)pad->Pnext ) { if( strnicmp( TextPinName, pad->m_Padname, 4) == 0 ) { /* trouve */ trouve = TRUE; if( *TextNetName != '?' ) pad->m_Netname = CONV_FROM_UTF8(TextNetName); else pad->m_Netname.Empty(); } } if( !trouve && (DisplayWarningCount > 0) ) { Msg.Printf( _("Module [%s]: Pad [%s] not found"), Module->m_Reference->m_Text.GetData(), TextPinName); DisplayError(this, Msg, 1); DisplayWarningCount--; } return(trouve); } /*****************************************************/ MODULE * WinEDA_PcbFrame::ListAndSelectModuleName(void) /*****************************************************/ /* liste les noms des modules du PCB Retourne: un pointeur sur le module selectionne NULL si pas de selection */ { int ii, jj, nb_empr; MODULE * Module; WinEDAListBox * ListBox; const wxChar ** ListNames = NULL; if( m_Pcb->m_Modules == NULL ) { DisplayError(this, _("No Modules") ) ; return(0); } /* Calcul du nombre des modules */ nb_empr = 0; Module = (MODULE*)m_Pcb->m_Modules; for( ;Module != NULL; Module = (MODULE*)Module->Pnext) nb_empr++; ListNames = (const wxChar**) MyZMalloc( (nb_empr + 1) * sizeof(wxChar*) ); Module = (MODULE*) m_Pcb->m_Modules; for( ii = 0; Module != NULL; Module = (MODULE*)Module->Pnext, ii++) { ListNames[ii] = Module->m_Reference->m_Text.GetData(); } ListBox = new WinEDAListBox(this, _("Components"), ListNames, wxEmptyString); ii = ListBox->ShowModal(); ListBox->Destroy(); if( ii < 0 ) /* Pas de selection */ { Module = NULL; } else /* Recherche du module selectionne */ { Module = (MODULE*) m_Pcb->m_Modules; for( jj = 0; Module != NULL; Module = (MODULE*)Module->Pnext, jj++) { if( Module->m_Reference->m_Text.Cmp(ListNames[ii]) == 0 ) break; } } free(ListNames); return(Module); } /***************************************************************/ void WinEDA_NetlistFrame::ModulesControle(wxCommandEvent& event) /***************************************************************/ /* donne la liste : 1 - des empreintes doublées sur le PCB 2 - des empreintes manquantes par rapport a la netliste 3 - des empreintes supplémentaires par rapport a la netliste */ #define MAX_LEN_TXT 32 { int ii, NbModulesPcb; MODULE * Module, * pt_aux; int NbModulesNetListe ,nberr = 0 ; WinEDA_TextFrame * List; wxArrayString ModuleListFromNetlist; /* determination du nombre des modules du PCB*/ NbModulesPcb = 0; Module = (MODULE*) m_Parent->m_Pcb->m_Modules; for( ;Module != NULL; Module = (MODULE*)Module->Pnext) NbModulesPcb++; if( NbModulesPcb == 0 ) { DisplayError(this, _("No modules"), 10); return; } /* Construction de la liste des references des modules de la netliste */ NbModulesNetListe = BuildListeNetModules(event, ModuleListFromNetlist); if( NbModulesNetListe < 0 ) return; /* fichier non trouve */ if( NbModulesNetListe == 0 ) { DisplayError(this, _("No modules in NetList"), 10); return; } List = new WinEDA_TextFrame(this, _("Check Modules")); /* recherche des doubles */ List->Append(_("Duplicates")); Module = (MODULE*) m_Parent->m_Pcb->m_Modules; for( ;Module != NULL; Module = (MODULE*)Module->Pnext) { pt_aux = (MODULE*)Module->Pnext; for( ; pt_aux != NULL; pt_aux = (MODULE*)pt_aux->Pnext) { if( Module->m_Reference->m_Text.CmpNoCase(pt_aux->m_Reference->m_Text) == 0 ) { List->Append(Module->m_Reference->m_Text); nberr++ ; break; } } } /* recherche des manquants par rapport a la netliste*/ List->Append(_("Lack:") ); for ( ii = 0 ; ii < NbModulesNetListe ; ii++ ) { Module = (MODULE*) m_Parent->m_Pcb->m_Modules; for( ;Module != NULL; Module = (MODULE*)Module->Pnext) { if( Module->m_Reference->m_Text.CmpNoCase( ModuleListFromNetlist[ii]) == 0 ) { break; } } if( Module == NULL ) // Module missing, not found in board { List->Append(ModuleListFromNetlist[ii]); nberr++ ; } } /* recherche des modules supplementaires (i.e. Non en Netliste) */ List->Append( _("Not in Netlist:") ); Module = (MODULE*) m_Parent->m_Pcb->m_Modules; for( ;Module != NULL; Module = Module->Next()) { for (ii = 0; ii < NbModulesNetListe; ii++ ) { if( Module->m_Reference->m_Text.CmpNoCase( ModuleListFromNetlist[ii]) == 0 ) { break ;/* Module trouve en netliste */ } } if( ii == NbModulesNetListe ) /* Module not found in netlist */ { List->Append(Module->m_Reference->m_Text); nberr++ ; } } List->ShowModal(); List->Destroy(); } /**************************************************************************************************/ int WinEDA_NetlistFrame::BuildListeNetModules(wxCommandEvent& event, wxArrayString & BufName) /**************************************************************************************************/ /* charge en BufName la liste des noms des modules de la netliste, retourne le nombre des modules cités dans la netliste */ { int textlen; int nb_modules_lus ; int State, LineNum, Comment; char Line[1024], *Text, * LibModName; if( ! OpenNetlistFile(event) ) return -1; State = 0; LineNum = 0; Comment = 0; nb_modules_lus = 0; textlen = MAX_LEN_TXT; while( GetLine( source, Line, &LineNum) ) { Text = StrPurge(Line); if ( Comment ) /* Commentaires en cours */ { if( (Text = strchr(Text,'}') ) == NULL )continue; Comment = 0; } if ( *Text == '{' ) /* Commentaires */ { Comment = 1; if( (Text = strchr(Text,'}') ) == NULL ) continue; } if ( *Text == '(' ) State++; if ( *Text == ')' ) State--; if( State == 2 ) { int Error = 0; if( strtok(Line, " ()\t\n") == NULL ) Error = 1; /* TimeStamp */ if( ( LibModName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; /* nom Lib */ /* Lecture du nom (reference) du composant: */ if( (Text = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; nb_modules_lus++; BufName.Add(CONV_FROM_UTF8(Text)); continue; } if( State >= 3 ) { State--; /* Lecture 1 ligne relative au Pad */ } } fclose(source); return(nb_modules_lus); } /*****************************************************************************************/ int WinEDA_NetlistFrame::ReadListeModules(const wxString * RefCmp, long TimeStamp, wxString & NameModule) /*****************************************************************************************/ /* Lit le fichier .CMP donnant l'equivalence Modules / Composants Retourne: Si ce fichier existe: 1 et le nom module dans NameModule -1 si module non trouve en fichier sinon 0; parametres d'appel: RefCmp (NULL si selection par TimeStamp) TimeStamp (signature temporelle si elle existe, NULL sinon) pointeur sur le buffer recevant le nom du module Exemple de fichier: Cmp-Mod V01 Genere par PcbNew le 29/10/2003-13:11:6 BeginCmp TimeStamp = 322D3011; Reference = BUS1; ValeurCmp = BUSPC; IdModule = BUS_PC; EndCmp BeginCmp TimeStamp = 32307DE2; Reference = C1; ValeurCmp = 47uF; IdModule = CP6; EndCmp */ { wxString CmpFullFileName; wxString refcurrcmp, idmod; char ia[1024]; int timestamp; char *ptcar; FILE * FichCmp; if( (RefCmp == NULL) && (TimeStamp == 0) ) return(0); CmpFullFileName = NetNameBuffer; ChangeFileNameExt(CmpFullFileName,NetCmpExtBuffer) ; FichCmp = wxFopen(CmpFullFileName, wxT("rt") ); if (FichCmp == NULL) { wxString msg; msg.Printf( _("File <%s> not found, use Netlist for lib module selection"), CmpFullFileName.GetData()) ; DisplayError(this, msg, 20) ; return(0); } while( fgets(ia,sizeof(ia),FichCmp) != NULL ) { if( strnicmp(ia,"BeginCmp",8) != 0 ) continue; /* Ici une description de 1 composant commence */ refcurrcmp.Empty(); idmod.Empty(); timestamp = -1; while( fgets(ia,sizeof(ia),FichCmp) != NULL ) { if( strnicmp(ia,"EndCmp",6) == 0 ) break; if( strnicmp(ia,"Reference =",11) == 0 ) { ptcar = ia+11; ptcar = strtok(ptcar," =;\t\n"); if( ptcar ) refcurrcmp = CONV_FROM_UTF8(ptcar); continue; } if( strnicmp(ia,"IdModule =",11) == 0 ) { ptcar = ia+11; ptcar = strtok(ptcar," =;\t\n"); if( ptcar ) idmod = CONV_FROM_UTF8(ptcar); continue; } if( strnicmp(ia,"TimeStamp =",11) == 0 ) { ptcar = ia+11; ptcar = strtok(ptcar," =;\t\n"); if( ptcar ) sscanf(ptcar, "%X", &timestamp); } }/* Fin lecture 1 descr composant */ /* Test du Composant lu en fichier: est-il le bon */ if( RefCmp ) { if( RefCmp->CmpNoCase(refcurrcmp) == 0 ) { fclose(FichCmp); NameModule = idmod; return(1); } } else if( TimeStamp != -1 ) { if( TimeStamp == timestamp ) { fclose(FichCmp); NameModule = idmod; return(1); } } } fclose(FichCmp); return(-1); } /***************************************************************/ void WinEDA_NetlistFrame::Set_NetlisteName(wxCommandEvent& event) /***************************************************************/ /* Selection un nouveau nom de netliste Affiche la liste des fichiers netlistes pour selection sur liste */ { wxString fullfilename, mask( wxT("*")); mask += NetExtBuffer; fullfilename = EDA_FileSelector( _("Netlist Selection:"), wxEmptyString, /* Chemin par defaut */ NetNameBuffer, /* nom fichier par defaut */ NetExtBuffer, /* extension par defaut */ mask, /* Masque d'affichage */ this, 0, TRUE ); if ( fullfilename.IsEmpty()) return; NetNameBuffer = fullfilename; SetTitle(fullfilename); } /***********************************************************************************/ void WinEDA_NetlistFrame::AddToList(const wxString & NameLibCmp, const wxString & CmpName,int TimeStamp ) /************************************************************************************/ /* Fontion copiant en memoire de travail les caracteristiques des nouveaux modules */ { MODULEtoLOAD * NewMod; NewMod = new MODULEtoLOAD(NameLibCmp, CmpName, TimeStamp); NewMod->Pnext = s_ModuleToLoad_List; s_ModuleToLoad_List = NewMod; s_NbNewModules++; } /***************************************************************/ void WinEDA_NetlistFrame::LoadListeModules(wxDC * DC) /***************************************************************/ /* Routine de chargement des nouveaux modules en une seule lecture des librairies Si un module vient d'etre charge il est duplique, ce qui evite une lecture inutile de la librairie */ { MODULEtoLOAD * ref, *cmp; int ii; MODULE * Module = NULL; wxPoint OldPos = m_Parent->m_CurrentScreen->m_Curseur; if( s_NbNewModules == 0 ) return; SortListModulesToLoadByLibname(s_NbNewModules); ref = cmp = s_ModuleToLoad_List; // Calcul de la coordonnée de placement des modules: if ( m_Parent->SetBoardBoundaryBoxFromEdgesOnly() ) { m_Parent->m_CurrentScreen->m_Curseur.x = m_Parent->m_Pcb->m_BoundaryBox.GetRight() + 5000; m_Parent->m_CurrentScreen->m_Curseur.y = m_Parent->m_Pcb->m_BoundaryBox.GetBottom() + 10000; } else { m_Parent->m_CurrentScreen->m_Curseur = wxPoint(0,0); } for( ii = 0; ii < s_NbNewModules; ii++, cmp = cmp->Next() ) { if( (ii == 0) || ( ref->m_LibName != cmp->m_LibName) ) { /* Nouveau Module a charger */ Module = m_Parent->Get_Librairie_Module(this, wxEmptyString, cmp->m_LibName, TRUE ); ref = cmp; if ( Module == NULL ) continue; m_Parent->Place_Module(Module, DC); /* mise a jour des reperes ( nom et ref "Time Stamp") si module charge */ Module->m_Reference->m_Text = cmp->m_CmpName; Module->m_TimeStamp = cmp->m_TimeStamp; } else { /* module deja charge, on peut le dupliquer */ MODULE * newmodule; if ( Module == NULL ) continue; /* module non existant en libr */ newmodule = new MODULE(m_Parent->m_Pcb); newmodule->Copy(Module); newmodule->AddToChain(Module); Module = newmodule; Module->m_Reference->m_Text = cmp->m_CmpName; Module->m_TimeStamp = cmp->m_TimeStamp; } } m_Parent->m_CurrentScreen->m_Curseur = OldPos; } /* Routine utilisee par qsort pour le tri des modules a charger */ static int SortByLibName( MODULEtoLOAD ** ref, MODULEtoLOAD ** cmp ) { int ii = (*ref)->m_LibName.CmpNoCase((*cmp)->m_LibName); return ii; } /*************************************************/ void SortListModulesToLoadByLibname(int NbModules) /**************************************************/ /* Rearrage la liste des modules List par ordre alphabetique des noms lib des modules */ { MODULEtoLOAD ** base_list, * item; int ii; base_list = (MODULEtoLOAD **) MyMalloc( NbModules * sizeof(MODULEtoLOAD *) ); for ( ii = 0, item = s_ModuleToLoad_List; ii < NbModules; ii++ ) { base_list[ii] = item; item = item->Next(); } qsort( base_list, NbModules, sizeof(MODULEtoLOAD*), (int(*)(const void *, const void *) )SortByLibName); // Reconstruction du chainage: s_ModuleToLoad_List = *base_list; for ( ii = 0; ii < NbModules-1; ii++ ) { item = base_list[ii]; item->Pnext = base_list[ii + 1]; } // Dernier item: Pnext = NULL: item = base_list[ii]; item->Pnext = NULL; free(base_list); } /*****************************************************************************/ MODULEtoLOAD::MODULEtoLOAD(const wxString & libname, const wxString & cmpname, int timestamp) : EDA_BaseStruct(TYPE_NOT_INIT) /*****************************************************************************/ { m_LibName = libname; m_CmpName = cmpname; m_TimeStamp = timestamp; }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 1098 ] ] ]
3f308dc19323e2833658af784f5281918bcef7c2
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/dependencies/include/ParticleUniverse/ParticleAffectors/ParticleUniverseSphereColliderFactory.h
3c04306c6493272a443ae44233354172a7185a25
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,093
h
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #ifndef __PU_SPHERE_COLLIDER_FACTORY_H__ #define __PU_SPHERE_COLLIDER_FACTORY_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseSphereColliderTokens.h" #include "ParticleUniverseSphereCollider.h" #include "ParticleUniverseAffectorFactory.h" namespace ParticleUniverse { /** Factory class responsible for creating the SphereCollider. */ class _ParticleUniverseExport SphereColliderFactory : public ParticleAffectorFactory { public: SphereColliderFactory(void){}; virtual ~SphereColliderFactory(void){}; /** See ParticleAffectorFactory */ Ogre::String getAffectorType(void) const { return "SphereCollider"; } /** See ParticleAffectorFactory */ ParticleAffector* createAffector(void) { return _createAffector<SphereCollider>(); } /** See ScriptReader */ virtual bool translateChildProperty(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { return mSphereColliderTranslator.translateChildProperty(compiler, node); }; /** See ScriptReader */ virtual bool translateChildObject(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { return mSphereColliderTranslator.translateChildObject(compiler, node); }; /* */ virtual void write(ParticleScriptSerializer* serializer , const IElement* element) { // Delegate mSphereColliderWriter.write(serializer, element); } protected: SphereColliderWriter mSphereColliderWriter; SphereColliderTranslator mSphereColliderTranslator; }; } #endif
[ [ [ 1, 67 ] ] ]
9a4c3adad32a3888c3aeecc8a70f3e5c9f975607
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/BodyState.h
74b59b0b39eff2ae801ce875af431003fe0b3bc7
[]
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
7,372
h
// (c) 1997-2000 Monolith Productions, Inc. All Rights Reserved #ifndef __BODY_STATE_H__ #define __BODY_STATE_H__ #include "AIState.h" class Body; class CBodyState : public CAIClassAbstract { public : DECLARE_AI_FACTORY_CLASS_ABSTRACT_SPECIFIC(State); CBodyState( ); virtual void Init(Body* pBody); virtual void InitLoad(Body* pBody); virtual void Update() {} virtual void HandleTouch(HOBJECT hObject) {} virtual void Save(ILTMessage_Write *pMsg) {} virtual void Load(ILTMessage_Read *pMsg) {} virtual LTBOOL CanDeactivate() { return LTTRUE; } // Most of the time the ability to update dims is // also the same time we can deactivate. This is because // we can't deactivate as long as we're moving our body around, // and we also don't want to update the dims as long as we're moving // our body around. virtual LTBOOL CanUpdateDims() { return CanDeactivate( ); } protected : Body* m_pBody; }; class CBodyStateNormal : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateNormal, kState_BodyNormal); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); LTBOOL CanDeactivate(); // It's always ok to update dims for normal, because normal isn't // doing anything. virtual LTBOOL CanUpdateDims() { return true; } }; class CBodyStateStairs : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateStairs, kState_BodyStairs); CBodyStateStairs(); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); void HandleTouch(HOBJECT hObject); void Save(ILTMessage_Write *pMsg); void Load(ILTMessage_Read *pMsg); LTBOOL CanDeactivate() { return LTFALSE; } protected : LTVector m_vDir; AIVolume* m_pVolume; LTBOOL m_bFell; HMODELANIM m_hAniStart; HMODELANIM m_hAniLoop; HMODELANIM m_hAniStop; }; class CBodyStateLedge : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateLedge, kState_BodyLedge); CBodyStateLedge( ); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); void HandleTouch(HOBJECT hObject); void Save(ILTMessage_Write *pMsg); void Load(ILTMessage_Read *pMsg); LTBOOL CanDeactivate() { return LTFALSE; } protected : enum State { eLeaning, eFalling, eLanding, }; protected : State m_eState; LTFLOAT m_fTimer; LTVector m_vVelocity; AIVolume* m_pVolume; HMODELANIM m_hAniStart; HMODELANIM m_hAniLoop; HMODELANIM m_hAniStop; }; class CBodyStateLadder : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateLadder, kState_BodyLadder); CBodyStateLadder( ); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); void HandleTouch(HOBJECT hObject); void Save(ILTMessage_Write *pMsg); void Load(ILTMessage_Read *pMsg); LTBOOL CanDeactivate() { return LTFALSE; } protected : enum State { eLeaning, eFalling, eLanding, }; protected : State m_eState; LTFLOAT m_fTimer; AIVolume* m_pVolume; HMODELANIM m_hAniStart; HMODELANIM m_hAniLoop; HMODELANIM m_hAniStop; }; class CBodyStateUnderwater : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateUnderwater, kState_BodyUnderwater); CBodyStateUnderwater( ); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); void HandleTouch(HOBJECT hObject); void Save(ILTMessage_Write *pMsg); void Load(ILTMessage_Read *pMsg); LTBOOL CanDeactivate() { return LTFALSE; } protected : HMODELANIM m_hAniStart; HMODELANIM m_hAniLoop; HMODELANIM m_hAniStop; LTBOOL m_bStop; }; class CBodyStateLaser : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateLaser, kState_BodyLaser); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); void Save(ILTMessage_Write *pMsg); void Load(ILTMessage_Read *pMsg); LTBOOL CanDeactivate() { return LTFALSE; } protected : LTFLOAT m_fRemoveTime; }; class CBodyStateDecay : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateDecay, kState_BodyDecay); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); void Save(ILTMessage_Write *pMsg); void Load(ILTMessage_Read *pMsg); LTBOOL CanDeactivate() { return LTFALSE; } protected : LTFLOAT m_fRemoveTime; }; class CBodyStateFade : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateFade, kState_BodyFade); CBodyStateFade(); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); void Save(ILTMessage_Write *pMsg); void Load(ILTMessage_Read *pMsg); LTBOOL CanDeactivate() { return LTFALSE; } protected : LTFLOAT m_fRemoveTime; }; class CBodyStateCrush : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateCrush, kState_BodyCrush); void Init(Body* pBody); void InitLoad(Body* pBody); }; class CBodyStateChair : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateChair, kState_BodyChair); void Init(Body* pBody); void InitLoad(Body* pBody); }; class CBodyStatePoison : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStatePoison, kState_BodyPoison); void Init(Body* pBody); void InitLoad(Body* pBody); }; class CBodyStateAcid : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateAcid, kState_BodyAcid); void Init(Body* pBody); void InitLoad(Body* pBody); }; class CBodyStateArrow : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateArrow, kState_BodyArrow); void Init(Body* pBody); void InitLoad(Body* pBody); }; class CBodyStateExplode : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateExplode, kState_BodyExplode); CBodyStateExplode( ); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); void HandleTouch(HOBJECT hObject); void Save(ILTMessage_Write *pMsg); void Load(ILTMessage_Read *pMsg); LTBOOL CanDeactivate() { return LTFALSE; } protected : void SetRestingState(); LTBOOL m_bLand; LTVector m_vLandPos; HMODELANIM m_hAniStart; HMODELANIM m_hAniLoop; HMODELANIM m_hAniStop; }; class CBodyStateCarried : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateCarried, kState_BodyCarried); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); LTBOOL CanDeactivate() { return LTFALSE; } protected : HMODELANIM m_hAniStart; }; class CBodyStateDropped : public CBodyState { public : DECLARE_AI_FACTORY_CLASS_SPECIFIC(State, CBodyStateDropped, kState_BodyDropped); void Init(Body* pBody); void InitLoad(Body* pBody); void Update(); LTBOOL CanDeactivate() { return LTFALSE; } protected : HMODELANIM m_hAniStart; }; #endif
[ [ [ 1, 366 ] ] ]
cf2400bca340f77770710f9148f67c7a7dd7ffc2
e109ae97b8a43dbf4f4a42a40f8c8da0641237a5
/Lieutenant.cpp
ecd387b211889475d9158696d4b6a123145a5713
[]
no_license
mtturner/strategoo-code
8346d48e7b5c038d53843a5195fecd1dc0a4fec9
6bdd46fdbd8cc77eca1afdd0bc9e1d293e59e882
refs/heads/master
2016-09-06T15:57:20.713674
2011-05-06T03:36:15
2011-05-06T03:36:15
32,553,378
1
0
null
null
null
null
UTF-8
C++
false
false
1,189
cpp
/****************************************************** Lieutenant.cpp This is the implementation file for the Lieutenant class. ******************************************************/ #include "Lieutenant.h" Lieutenant::Lieutenant(int xPos, int yPos, int boardSpace) : Piece(xPos, yPos, "lieutenant.png", 0) { setBoardSpace(boardSpace); setRank(5); } //***************************************************** Lieutenant::Lieutenant(std::string filename) : Piece(0, 0, filename.c_str(), 1) { setBoardSpace(-1); setRank(5); } //***************************************************** Piece* Lieutenant::move(Piece* const destination) { //if the piece is an emptyspace if(destination->getRank() == 0) { swapLocation(destination); return destination; } //else if the piece is the flag else if(destination->getRank() == 12) { swapLocation(destination); return this; } //else need to battle pieces to the death else { if(*this > *destination) { swapLocation(destination); return this; } else if(*this < *destination) { return destination; } else { //draw return 0; } } }
[ "cakeeater07@28384a92-424b-c9e9-0b9a-6d5e880deeca", "[email protected]@28384a92-424b-c9e9-0b9a-6d5e880deeca" ]
[ [ [ 1, 7 ], [ 10, 10 ], [ 12, 13 ], [ 15, 59 ] ], [ [ 8, 9 ], [ 11, 11 ], [ 14, 14 ] ] ]
43f38a01326cb148e6f0312ccc39a924f6353615
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/WheelDirector/include/Logic/WheelLogic.h
a56d6bb5621a44f33e4625ef3eafe27a498d3d6e
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
GB18030
C++
false
false
1,653
h
#ifndef __Orz_WheelLogic_h__ #define __Orz_WheelLogic_h__ //#include "Engine.h" //#include "WheelUI.h" //#include "LogiEvent.h" #include "WheelDirectorStableHeaders.h" #include "WheelGame.h" #include "logic/LogicEvent.h" namespace Orz { class WheelGame; class GameLogic; class LogoLogic; class MenuLogic; class SetupLogic; //class LogiGame; //class LogiInfo; //class LogiMenu; //class LogiStart;//倒计时 //class LogiPreRun;//zxh装先河 //class LogiRun;//转动 // //class LogiWin;// 动作 //class LogiPlay;//动作一半 //class LogiEnd;//完毕 //class LogiLogo;//完毕 // //class LogiReady;//完毕 class WheelLogic: public FSM::MainLogic<WheelLogic, WheelGame, GameLogic/**/>//, public MyClockListener { public: typedef boost::mpl::list< sc::custom_reaction< LogicEvent::WheelStart >, sc::custom_reaction< LogicEvent::SetTime >, sc::custom_reaction< LogicEvent::ResetGame > /*, sc::custom_reaction< LogicEvent::SetTime >,sc::custom_reaction<LogicEvent::4rResetGame>*/ > reactions; sc::result react(const LogicEvent::WheelStart & evt); sc::result react(const LogicEvent::SetTime & evt); sc::result react(const LogicEvent::ResetGame & evt); /**/ // TutoriaLogic(); // void clockChanged(const MyClock & clock); // /* void setSec(int sec); // int getSec(void) const;*/ // MyClock & getClock(void); //private: // boost::scoped_ptr<MyClock> _clock; }; // class // class OTDFighterTouch; // class // class OTDFighterTouch; } //#include "logic/AllLogic.h" #endif
[ [ [ 1, 94 ] ] ]
2325c475a814d8a8aff87d8d49118f5468fadf55
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib/src/august/AugustEzGameFrame.cpp
d3245082546a30008fcb537c6b0781a1634eaa68
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
9,805
cpp
#include "stdafx.h" #include "AugustEzGameFrame.h" #include "MyuFunctions.h" int CAugustEzGameFrame::ms_nInstanceCount=0; // MainMethodを呼び出す /*DWORD CallMainThread( DWORD dwInstancePtr ) { CAugustEzGameFrame *pInstance = (CAugustEzGameFrame*)(dwInstancePtr); return (DWORD)( pInstance->PrivateMainMethod() ); }*/ // 自分自身のメインスレッドを呼び出す DWORD August_CallMainThread( CAugustEzGameFrame *pFrameInstance ) { return (DWORD)( pFrameInstance->PrivateMainMethod() ); } // 2008/01/22 ユーザパラメータ対応 typedef struct { CAugustEzGameFrame *pFrameInstance; DWORD dwUserParam; } AUGUST_CALL_THREAD_EX_PARAM; // DWORD August_CallMainThreadEx( AUGUST_CALL_THREAD_EX_PARAM *pParam ) { return (DWORD)( pParam->pFrameInstance->PrivateMainMethod(pParam->dwUserParam) ); } //////////////////////////////////////////////////////////////////////////// // コンストラクタ #ifdef _USE_INHERIT_AUGUST_GLOBAL_COMMON CAugustEzGameFrame::CAugustEzGameFrame() : m_nWidth(CAugustGlobalCommon::nWindowWidth), m_nHeight(CAugustGlobalCommon::nWindowHeight), #else CAugustEzGameFrame::CAugustEzGameFrame() : #endif m_mouse(input.mouse), m_grp(grp), m_input(input), m_audio(audio) { ms_nInstanceCount++; //m_strCaption = "MGL Apprication"; m_bBreak = FALSE; m_bEscEnd = FALSE; m_bFpsShow = FALSE; // 2007/01/02 無かったのだけれど… m_bFullscreen = FALSE; m_bEnabledAudio = FALSE; } // デストラクタ CAugustEzGameFrame::~CAugustEzGameFrame() { ms_nInstanceCount--; } // ウインドウの開始 int CAugustEzGameFrame::StartWindowEx( int nWinWidthSize, int nWinHeightSize, // MGL_EZGAME_FRAME_FUNCPTR mainThreadFuncPtr ) LPTHREAD_START_ROUTINE mainThreadFuncPtr, void* threadFuncParam, const char *szWindowTitle, BOOL bFullscreen ) { _MGL_DEBUGLOG("StartWindowEx() start." ); CMglStackInstance("CAugustEzGameFrame::StartWindowEx"); if ( ms_nInstanceCount >= 2 ) { ::MessageBox( NULL, "CAugustEzGameFrame のインスタンスが複数あります。", "MyuGameLibrary", MB_ICONERROR ); return -1; } #ifdef _USE_INHERIT_AUGUST_GLOBAL_COMMON CAugustGlobalCommon::nWindowWidth = nWinWidthSize; CAugustGlobalCommon::nWindowHeight = nWinHeightSize; #else m_nWidth = nWinWidthSize; m_nHeight = nWinHeightSize; #endif m_userMainThread = mainThreadFuncPtr; m_bFullscreen = bFullscreen; m_bBreak = FALSE; // 画面サイズ取得 int nScreenWidth=0; int nScreenHeight=0; int nWinStartPosX=100; int nWinStartPosY=150; if ( GetScreenSize( &nScreenWidth, &nScreenHeight ) == TRUE ) { nWinStartPosX = (nScreenWidth/2)-(m_nWidth/2); nWinStartPosY = (nScreenHeight/2)-(m_nHeight/2)-16; } if ( m_strWindowClassName == "" ){ // WindowClass名生成("MGL Appllication WindowClass"+タイトル) m_strWindowClassName = "MGL Appllication WindowClass"; m_strWindowClassName += szWindowTitle; /*string strWindowClassName = "MGL Appllication WindowClass"; strWindowClassName += szWindowTitle;*/ } AUGUST_CALL_THREAD_EX_PARAM param; param.pFrameInstance = this; param.dwUserParam = (DWORD)threadFuncParam; // 簡易Window処理呼び出し _MGL_DEBUGLOG("m_window.StartWindow()" ); return m_window.StartWindow( szWindowTitle, m_strWindowClassName.c_str(), nWinStartPosX, nWinStartPosY, m_nWidth, m_nHeight, WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, (LPTHREAD_START_ROUTINE)August_CallMainThreadEx, &param ); // (LPTHREAD_START_ROUTINE)CallMainThread, (DWORD)(this) ); } // スレッド int CAugustEzGameFrame::PrivateMainMethod(){ return PrivateMainMethod((DWORD)this); } //構造化例外が発生すると、この関数が呼ばれる void _MglAugust_se_translator_function(unsigned int code, struct _EXCEPTION_POINTERS* ep) { throw ep; //標準C++の例外を発生させる } // スレッド - 2008/01/22 int CAugustEzGameFrame::PrivateMainMethod(DWORD dwUserThreadParam) { _set_se_translator(_MglAugust_se_translator_function); //__try{ try // 例外処理受け付け開始 { _MGL_DEBUGLOG("+ CAugustEzGameFrame::PrivateMainMethod()" ); CMglStackInstance("CAugustEzGameFrame::PrivateMainMethod"); _MGL_DEBUGLOG("CoInitialize()..." ); CoInitialize(NULL); _MGL_DEBUGLOG("grp.Init()..." ); grp.Init( m_window.GetWindowHandle(), m_nWidth, m_nHeight, m_bFullscreen ); grp.Clear(); // 2008/10/14 OnGraphicInitializeEnded(); _MGL_DEBUGLOG("input.Init()..." ); input.Init( m_window.GetWindowHandle() ); _MGL_DEBUGLOG("input.Init() end." ); // 2008/11/29 if ( m_bEnabledAudio ){ _MGL_DEBUGLOG("audio.Init()..." ); InitAudio(); _MGL_DEBUGLOG("audio.Init() end." ); } _MGL_DEBUGLOG("Create Debug/FPS Fonts..." ); //m_txtDebug.InitAndEzCreate( &grp, 14 ); //m_txtFps.InitAndEzCreate( &grp, 14 ); m_txtDebug.Init( &grp ); m_txtFps.Init( &grp ); m_txtDebug.Create( 14 ); m_txtFps.Create( 14 ); //fps.SetFPS(60); <- 勝手に上書きしちゃだめ!てかデフォルト60なってるし //grp.Clear(); _MGL_DEBUGLOG("end." ); // 2009/01/23 CAugustWindow側のOnInit()呼び出し _MGL_DEBUGLOG("EzFrame_OnInit()..." ); EzFrame_OnInit(); // MGL S3.1からは呼び出すだけにする(ループはこの中でやってもらう)- 2006/11/25 _MGL_DEBUGLOG("Call User MainMethod." ); m_userMainThread((void*)dwUserThreadParam); //→ やっぱやめ -> ない!(どっちだよ:笑) /* // MGL 3.0まで for(;;) { // ユーザメソッドを呼び出す //if ( m_userMainThread() == 1 ) //if ( m_userMainThread(this) == FALSE ) if ( m_userMainThread(this) == TRUE ) break; // フレーム分待つよん if ( DoFpsWait() == FALSE ) break; } */ } // 例外処理 V3.0 catch( MglException exp ) { char work[1024]; snprintf( work, sizeof(work), "Myu Game Library Error :\r\n" " Location : %s::%s() Error Code : 0x%08X\r\n" "\r\n" "%s", exp.szClass, exp.szMethod, exp.nInternalCode, exp.szMsg ); ::MessageBox( NULL, work, NULL, MB_ICONERROR ); } // 例外処理 catch( MyuCommonException except ) { char work[512]; //snprintf( work,sizeof(work), "ErrNo : 0x%08X\r\n%s", except.nErrCode, except.szErrMsg ); snprintf( work,sizeof(work), "ErrNo : 0x%08X\r\n%s\r\n" "\r\n" "%s", except.nErrCode, except.szErrMsg, g_stackTrace.Dump().c_str() ); ::MessageBox( NULL, work, NULL, MB_ICONERROR ); } #ifndef _DEBUG // VC++の例外か catch(_EXCEPTION_POINTERS *ep) { //_EXCEPTION_POINTERS *ep = GetExceptionInformation(); PEXCEPTION_RECORD rec = ep->ExceptionRecord; switch(rec->ExceptionCode){ case 0xc0000094: ::MessageBox( NULL, "0 で除算されました。", NULL, MB_ICONERROR ); break; } char work[1024]; snprintf(work,sizeof(work), ("内部アクセス保護違反です。\r\n" "code:%x flag:%x addr:%p params:%d\n"), rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress, rec->NumberParameters ); ::MessageBox( NULL, work, NULL, MB_ICONERROR ); } // VC++の例外か catch(...) { ::MessageBox( NULL, "fdssdff", NULL, MB_ICONERROR ); } #endif//_DEBUG /*} __except(_EXCEPTION_POINTERS *ep = GetExceptionInformation()) { _EXCEPTION_POINTERS *ep = GetExceptionInformation(); PEXCEPTION_RECORD rec = ep->ExceptionRecord; char work[1024]; snprintf(work,sizeof(work), ("内部アクセス保護違反です。\r\n" "code:%x flag:%x addr:%p params:%d\n"), rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress, rec->NumberParameters ); ::MessageBox( NULL, work, NULL, MB_ICONERROR ); }*/ // ↓try-catch内でなくていいのか…? // ここで開放しとかないとスレッド外で開放されて落ちる //if ( m_bEnabledAudio ) <- 別にInitしてないならしてないでReleaseしても問題ないんでね・・・? audio.Release(); input.Release(); input.FinalRelease(); m_txtDebug.Release(); grp.Release(); CoUninitialize(); return 0; } // 有効かどうか復帰します(FALSEになったら終了すること!) BOOL CAugustEzGameFrame::DoFpsWait() { // ウインドウが生きてるかのチェック if ( m_window.IsAlive() != TRUE ) return FALSE; // 抜ける? if ( m_bBreak ) return FALSE; // FPS/デバッグ文字列出力 if ( m_bFpsShow == TRUE ) { char szFps[64]; sprintf( szFps, "FPS : %.01f", fps.GetAveFps() ); m_txtFps.Draw( szFps, 6, 6, D3DCOLORW_XRGB(0,0,0) ); m_txtFps.Draw( szFps, 5, 5, D3DCOLORW_XRGB(255,255,255) ); } m_txtDebug.Draw( m_strDebugText.c_str(), 6, 21, D3DCOLORW_XRGB(0,0,0) ); m_txtDebug.Draw( m_strDebugText.c_str(), 5, 20, D3DCOLORW_XRGB(255,255,255) ); // スプライト終了 grp.SpriteEnd(); // スクリーンのアップデート grp.UpdateScreen(); // 待つよん fps.Sleep(); // キーボード入力の更新 input.Update(); if ( m_bEscEnd ){ if ( input.GetOnKey(ASCII_ESC) ) return FALSE; } // スプライト開始 grp.SpriteBegin(); return TRUE; } // ウインドウタイトルの設定 //void CAugustEzGameFrame::SetWindowTitle( const char *szCaption ){ m_strCaption = szCaption; } // デバッグ出力 void CAugustEzGameFrame::PrintDebug( const char* szFormat, ... ) { char work[512]; va_list vl; va_start( vl, szFormat ); vsnprintf( work, sizeof(work), szFormat, vl ); va_end( vl ); m_strDebugText = work; }
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 339 ] ] ]
53d51a7e1bce69f84121fdc3dcc37c805cd2e262
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/misc/pre90s/d_mystston.cpp
d08eeccfc038aac9b1d1042fbeafb322e24ce083
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
18,074
cpp
// FB Alpha Mysterious Stones Driver Module // Based on MAME driver by Nicola Salmoria #include "tiles_generic.h" #include "m6502.h" #include "driver.h" extern "C" { #include "ay8910.h" } static unsigned char *Mem, *Rom, *Gfx0, *Gfx1, *Gfx2, *Prom; static unsigned char DrvJoy1[8], DrvJoy2[8], DrvReset, DrvDips[2]; static short *pAY8910Buffer[6], *pFMBuffer = NULL; static int *Palette; static int VBLK = 0x80; static int soundlatch; static unsigned char mystston_scroll_x = 0; static int mystston_fgcolor, mystston_flipscreen; //---------------------------------------------------------------------------------------------- // Input Handlers static struct BurnInputInfo DrvInputList[] = { {"P1 Coin" , BIT_DIGITAL , DrvJoy1 + 6, "p1 coin" }, {"P1 start" , BIT_DIGITAL , DrvJoy2 + 6, "p1 start" }, {"P1 Right" , BIT_DIGITAL , DrvJoy1 + 0, "p1 right" }, {"P1 Left" , BIT_DIGITAL , DrvJoy1 + 1, "p1 left" }, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 2, "p1 up", }, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 3, "p1 down", }, {"P1 Button 1" , BIT_DIGITAL , DrvJoy1 + 4, "p1 fire 1"}, {"P1 Button 2" , BIT_DIGITAL , DrvJoy1 + 5, "p1 fire 2"}, {"P2 Coin" , BIT_DIGITAL , DrvJoy1 + 7, "p2 coin" }, {"P2 start" , BIT_DIGITAL , DrvJoy2 + 7, "p2 start" }, {"P2 Right" , BIT_DIGITAL , DrvJoy2 + 0, "p2 right" }, {"P2 Left" , BIT_DIGITAL , DrvJoy2 + 1, "p2 left" }, {"P2 Up", BIT_DIGITAL, DrvJoy2 + 2, "p2 up", }, {"P2 Down", BIT_DIGITAL, DrvJoy2 + 3, "p2 down", }, {"P2 Button 1" , BIT_DIGITAL , DrvJoy2 + 4, "p2 fire 1"}, {"P2 Button 2" , BIT_DIGITAL , DrvJoy2 + 5, "p2 fire 2"}, {"Reset", BIT_DIGITAL , &DrvReset, "reset" }, {"Dip 1", BIT_DIPSWITCH, DrvDips + 0, "dip 1" }, {"Dip 2", BIT_DIPSWITCH, DrvDips + 1, "dip 2" }, }; STDINPUTINFO(Drv) static struct BurnDIPInfo DrvDIPList[]= { // Default Values {0x11, 0xff, 0xff, 0xfb, NULL }, {0 , 0xfe, 0 , 2 , "Lives" }, {0x11, 0x01, 0x01, 0x01, "3" }, {0x11, 0x01, 0x01, 0x00, "5" }, {0 , 0xfe, 0 , 2 , "Difficulty" }, {0x11, 0x01, 0x02, 0x02, "Easy" }, {0x11, 0x01, 0x02, 0x00, "Hard" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x11, 0x01, 0x04, 0x04, "Off" }, {0x11, 0x01, 0x04, 0x00, "On" }, // Default Values {0x12, 0xff, 0xff, 0x1f, NULL }, {0 , 0xfe, 0 , 4 , "Coin A" }, {0x12, 0x01, 0x03, 0x00, "2C 1C" }, {0x12, 0x01, 0x03, 0x03, "1C 1C" }, {0x12, 0x01, 0x03, 0x02, "1C 2C" }, {0x12, 0x01, 0x03, 0x01, "1C 3C" }, {0 , 0xfe, 0 , 4 , "Coin B" }, {0x12, 0x01, 0x0c, 0x00, "2C 1C" }, {0x12, 0x01, 0x0c, 0x0c, "1C 1C" }, {0x12, 0x01, 0x0c, 0x08, "1C 2C" }, {0x12, 0x01, 0x0c, 0x04, "1C 3C" }, {0 , 0xfe, 0 , 2 , "Flip Screen" }, {0x12, 0x01, 0x20, 0x00, "Off" }, {0x12, 0x01, 0x20, 0x20, "On" }, {0 , 0xfe, 0 , 2 , "Cabinet" }, {0x12, 0x01, 0x40, 0x00, "Upright" }, {0x12, 0x01, 0x40, 0x40, "Cocktail" }, }; STDDIPINFO(Drv) //---------------------------------------------------------------------------------------------- // Memory Read/Write Handlers static void mystston_soundcontrol_w(unsigned short, unsigned char data) { static int last; if ((last & 0x20) == 0x20 && (data & 0x20) == 0x00) { if (last & 0x10) AY8910Write(0, 0, soundlatch); else AY8910Write(0, 1, soundlatch); } if ((last & 0x80) == 0x80 && (data & 0x80) == 0x00) { if (last & 0x40) AY8910Write(1, 0, soundlatch); else AY8910Write(1, 1, soundlatch); } last = data; } unsigned char mystston_read_byte(unsigned short address) { unsigned char ret = 0; switch (address) { case 0x2000: { for (int i = 0; i < 8; i++) ret |= DrvJoy1[i] << i; return ~ret; } case 0x2010: { for (int i = 0; i < 8; i++) ret |= DrvJoy2[i] << i; return ~ret; } case 0x2020: return DrvDips[0]; case 0x2030: return DrvDips[1] | VBLK; } return 0; } void mystston_write_byte(unsigned short address, unsigned char data) { #define pal2bit(bits) (((bits & 3) << 6) | ((bits & 3) << 4) | ((bits & 3) << 2) | (bits & 3)) #define pal3bit(bits) (((bits & 7) << 5) | ((bits & 7) << 2) | ((bits & 7) >> 1)) switch (address) { case 0x2000: { mystston_fgcolor = ((data & 0x01) << 1) + ((data & 0x02) >> 1); mystston_flipscreen = (data & 0x80) ^ ((DrvDips[1] & 0x20) ? 0x80 : 0); } break; case 0x2010: m6502SetIRQ(M6502_CLEAR); break; case 0x2020: mystston_scroll_x = data; break; case 0x2030: soundlatch = data; break; case 0x2040: mystston_soundcontrol_w(0, data); break; } if (address >= 0x2060 && address <= 0x2077) { Palette[address & 0x1f] = (pal3bit(data) << 16) | (pal3bit(data >> 3) << 8) | pal2bit(data >> 6); } #undef pal2bit #undef pal3bit } //---------------------------------------------------------------------------------------------- // Initilization Routines static int DrvDoReset() { DrvReset = 0; memset (Rom, 0, 0x2000); VBLK = 0x80; soundlatch = 0; mystston_flipscreen = 0; mystston_scroll_x = 0; mystston_fgcolor = 0; AY8910Reset(0); AY8910Reset(1); m6502Open(0); m6502Reset(); m6502Close(); return 0; } static void mystston_palette_init() { for (int i = 0; i < 32; i++) { int bit0, bit1, bit2, r, g, b; bit0 = (Prom[i] >> 0) & 0x01; bit1 = (Prom[i] >> 1) & 0x01; bit2 = (Prom[i] >> 2) & 0x01; r = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; bit0 = (Prom[i] >> 3) & 0x01; bit1 = (Prom[i] >> 4) & 0x01; bit2 = (Prom[i] >> 5) & 0x01; g = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; bit1 = (Prom[i] >> 6) & 0x01; bit2 = (Prom[i] >> 7) & 0x01; b = 0x21 * 0 + 0x47 * bit1 + 0x97 * bit2; Palette[i + 24] = (r << 16) | (g << 8) | b; } } static int mystston_gfx_convert() { static int PlaneOffsets[3] = { 0x40000, 0x20000, 0 }; static int XOffsets[16] = { 128, 129, 130, 131, 132, 133, 134, 135, 0, 1, 2, 3, 4, 5, 6, 7 }; static int YOffsets[16] = { 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120 }; unsigned char *tmp = (unsigned char*)malloc(0x10000); if (tmp == NULL) { return 1; } memcpy (tmp, Gfx0, 0x10000); GfxDecode(0x800, 3, 8, 8, PlaneOffsets, XOffsets + 8, YOffsets, 0x040, tmp, Gfx0); GfxDecode(0x200, 3, 16, 16, PlaneOffsets, XOffsets + 0, YOffsets, 0x100, tmp, Gfx2); memcpy (tmp, Gfx1, 0x10000); GfxDecode(0x200, 3, 16, 16, PlaneOffsets, XOffsets + 0, YOffsets, 0x100, tmp, Gfx1); free (tmp); return 0; } static int DrvInit() { Mem = (unsigned char*)malloc(0x10000 + 0x20000 + 0x20000 + 0x20000 + 0x20 + 0x38 * sizeof(int)); if (Mem == NULL) { return 1; } memset (Mem, 0, 0x70000 + 0x20); pFMBuffer = (short *)malloc (nBurnSoundLen * 6 * sizeof(short)); if (pFMBuffer == NULL) { return 1; } Rom = Mem + 0x00000; Gfx0 = Mem + 0x10000; Gfx1 = Mem + 0x30000; Gfx2 = Mem + 0x50000; Prom = Mem + 0x70000; Palette = (int*)(Mem + 0x70020); // Load Roms { for (int i = 0; i < 6; i++) { if (BurnLoadRom(Rom + i * 0x2000 + 0x4000, i + 0, 1)) return 1; if (BurnLoadRom(Gfx0 + i * 0x2000 + 0x0000, i + 6, 1)) return 1; if (BurnLoadRom(Gfx1 + i * 0x2000 + 0x0000, i + 12, 1)) return 1; } if (BurnLoadRom(Prom, 18, 1)) return 1; if(mystston_gfx_convert()) return 1; mystston_palette_init(); } m6502Init(1); m6502Open(0); m6502MapMemory(Rom + 0x0000, 0x0000, 0x1fff, M6502_RAM); m6502MapMemory(Rom + 0x4000, 0x4000, 0xffff, M6502_ROM); m6502SetReadHandler(mystston_read_byte); m6502SetWriteHandler(mystston_write_byte); m6502Close(); pAY8910Buffer[0] = pFMBuffer + nBurnSoundLen * 0; pAY8910Buffer[1] = pFMBuffer + nBurnSoundLen * 1; pAY8910Buffer[2] = pFMBuffer + nBurnSoundLen * 2; pAY8910Buffer[3] = pFMBuffer + nBurnSoundLen * 3; pAY8910Buffer[4] = pFMBuffer + nBurnSoundLen * 4; pAY8910Buffer[5] = pFMBuffer + nBurnSoundLen * 5; AY8910Init(0, 1500000, nBurnSoundRate, NULL, NULL, NULL, NULL); AY8910Init(1, 1500000, nBurnSoundRate, NULL, NULL, NULL, NULL); DrvDoReset(); // BurnSetRefreshRate(57.445); return 0; } static int DrvExit() { m6502Exit(); AY8910Exit(0); AY8910Exit(1); free (Mem); free (pFMBuffer); pFMBuffer = NULL; Palette = NULL; Rom = Gfx0 = Gfx1 = Gfx2 = Prom = NULL; VBLK = 0x00; soundlatch = 0; mystston_scroll_x = 0; mystston_fgcolor = mystston_flipscreen = 0; return 0; } //---------------------------------------------------------------------------------------------- // Drawing Routines static inline void mystston_putpix(int x, int y, unsigned char src, int color, int transp) { int pos, pxl; if (y > 255 || x > 239 || x < 0 || (!src && transp)) return; if (mystston_flipscreen) pos = ((255 - y) * 240) + (239 - x); else pos = (y * 240) + x; pxl = Palette[color | src]; PutPix(pBurnDraw + pos * nBurnBpp, BurnHighCol(pxl >> 16, pxl >> 8, pxl, 0)); } static void draw_16x16(int sx, int sy, unsigned char *gfx_base, int code, int color, int flipx, int flipy, int transp) { unsigned char *src = gfx_base + code; if (flipx) { for (int x = sx + 15; x >= sx; x--) { if (flipy) { for (int y = sy; y < sy + 16; y++, src++) { mystston_putpix(x, y, *src, color, transp); } } else { for (int y = sy + 15; y >= sy; y--, src++) { mystston_putpix(x, y, *src, color, transp); } } } } else { for (int x = sx; x < sx + 16; x++) { if (flipy) { for (int y = sy; y < sy + 16; y++, src++) { mystston_putpix(x, y, *src, color, transp); } } else { for (int y = sy + 15; y >= sy; y--, src++) { mystston_putpix(x, y, *src, color, transp); } } } } } static int DrvDraw() { for (int offs = 0; offs < 0x200; offs++) { int code = (Rom[0x1800 + offs] + ((Rom[0x1a00 + offs] & 0x01) << 8)) << 8; int flipx = offs & 0x10; int sx = ((offs & 0x1f) << 4) - (mystston_scroll_x + 8); int sy = ((offs >> 5) << 4); draw_16x16(sx, sy, Gfx1, code, 0x10, flipx, 0, 0); } for (int offs = 0; offs < 0x60; offs += 4) { int attr = Rom[0x0780 + offs]; if (attr & 0x01) { int code = (Rom[0x0781 + offs] + ((attr & 0x10) << 4)) << 8; int color = attr & 0x08; int flipy = attr & 0x04; int flipx = attr & 0x02; int sy = Rom[0x0783 + offs]; int sx = (240 - Rom[0x0782 + offs]) - 9; draw_16x16(sx, sy, Gfx2, code, color, flipx, flipy, 1); } } for (int offs = 0; offs < 0x400; offs++) { int code = (Rom[0x1000 | offs] + ((Rom[0x1400 + offs] & 0x07) << 8)) << 6; int color = (mystston_fgcolor << 3) + 0x18; int sx = (offs & 0x1f) << 3; int sy = (offs >> 2) & 0xf8; if (sx >= 248 || sx < 8) continue; sx -= 8; unsigned char *src = Gfx0 + code; for (int x = sx; x < sx + 8; x++) { for (int y = sy + 7; y >= sy; y--, src++) { if (!*src) continue; int pos; if (mystston_flipscreen) pos = ((255 - y) * 240) + (239 - x); else pos = (y * 240) + x; int pxl = Palette[color | *src]; PutPix(pBurnDraw + pos * nBurnBpp, BurnHighCol(pxl >> 16, pxl >> 8, pxl, 0)); } } } return 0; } static void mystston_interrupt_handler(int scanline) { static int coin; int inp = (DrvJoy1[6] << 6) | (DrvJoy1[7] << 7); if ((~inp & 0xc0) != 0xc0) { if (coin == 0) { coin = 1; m6502SetIRQ(M6502_NMI); return; } } else coin = 0; if (scanline == 8) VBLK = 0; if (scanline == 248) VBLK = 0x80; if ((scanline & 0x0f) == 0) m6502SetIRQ(M6502_IRQ); } static int DrvFrame() { if (DrvReset) { DrvDoReset(); } int nTotalCycles = (int)((double)(1500000 / 57.45)); int nCyclesRun = 0; m6502Open(0); for (int i = 0; i < 272; i++) { nCyclesRun += m6502Run(nTotalCycles / 272); mystston_interrupt_handler(i); } m6502Close(); if (pBurnSoundOut) { int nSample; int nSegmentLength = nBurnSoundLen; short* pSoundBuf = pBurnSoundOut; if (nSegmentLength) { AY8910Update(0, &pAY8910Buffer[0], nSegmentLength); AY8910Update(1, &pAY8910Buffer[3], nSegmentLength); for (int n = 0; n < nSegmentLength; n++) { nSample = pAY8910Buffer[0][n] >> 2; nSample += pAY8910Buffer[1][n] >> 2; nSample += pAY8910Buffer[2][n] >> 2; nSample += pAY8910Buffer[3][n] >> 2; nSample += pAY8910Buffer[4][n] >> 2; nSample += pAY8910Buffer[5][n] >> 2; if (nSample < -32768) { nSample = -32768; } else { if (nSample > 32767) { nSample = 32767; } } pSoundBuf[(n << 1) + 0] = nSample; pSoundBuf[(n << 1) + 1] = nSample; } } } if (pBurnDraw) { DrvDraw(); } return 0; } //---------------------------------------------------------------------------------------------- // Save State static int DrvScan(int nAction,int *pnMin) { struct BurnArea ba; if (pnMin) { *pnMin = 0x029521; } if (nAction & ACB_VOLATILE) { memset(&ba, 0, sizeof(ba)); ba.Data = Rom + 0x0000; ba.nLen = 0x2000; ba.szName = "All Ram"; BurnAcb(&ba); memset(&ba, 0, sizeof(ba)); ba.Data = Mem + 0x70020; ba.nLen = 24 * sizeof(int); ba.szName = "Palette"; BurnAcb(&ba); m6502Scan(nAction); AY8910Scan(nAction, pnMin); // Scan critical driver variables SCAN_VAR(mystston_flipscreen); SCAN_VAR(mystston_scroll_x); SCAN_VAR(mystston_fgcolor); SCAN_VAR(soundlatch); SCAN_VAR(VBLK); } return 0; } //---------------------------------------------------------------------------------------------- // Game Drivers // Mysterious Stones - Dr. John's Adventure static struct BurnRomInfo myststonRomDesc[] = { { "rom6.bin", 0x2000, 0x7bd9c6cd, 1 | BRF_PRG | BRF_ESS }, // 0 M6205 Code { "rom5.bin", 0x2000, 0xa83f04a6, 1 | BRF_PRG | BRF_ESS }, // 1 { "rom4.bin", 0x2000, 0x46c73714, 1 | BRF_PRG | BRF_ESS }, // 2 { "rom3.bin", 0x2000, 0x34f8b8a3, 1 | BRF_PRG | BRF_ESS }, // 3 { "rom2.bin", 0x2000, 0xbfd22cfc, 1 | BRF_PRG | BRF_ESS }, // 4 { "rom1.bin", 0x2000, 0xfb163e38, 1 | BRF_PRG | BRF_ESS }, // 5 { "ms6", 0x2000, 0x85c83806, 2 | BRF_GRA }, // 6 Character + Sprite Tiles { "ms9", 0x2000, 0xb146c6ab, 2 | BRF_GRA }, // 7 { "ms7", 0x2000, 0xd025f84d, 2 | BRF_GRA }, // 8 { "ms10", 0x2000, 0xd85015b5, 2 | BRF_GRA }, // 9 { "ms8", 0x2000, 0x53765d89, 2 | BRF_GRA }, // 10 { "ms11", 0x2000, 0x919ee527, 2 | BRF_GRA }, // 11 { "ms12", 0x2000, 0x72d8331d, 3 | BRF_GRA }, // 12 Sprite Tiles { "ms13", 0x2000, 0x845a1f9b, 3 | BRF_GRA }, // 13 { "ms14", 0x2000, 0x822874b0, 3 | BRF_GRA }, // 14 { "ms15", 0x2000, 0x4594e53c, 3 | BRF_GRA }, // 15 { "ms16", 0x2000, 0x2f470b0f, 3 | BRF_GRA }, // 16 { "ms17", 0x2000, 0x38966d1b, 3 | BRF_GRA }, // 17 { "ic61", 0x0020, 0xe802d6cf, 4 | BRF_GRA }, // 18 Color Prom }; STD_ROM_PICK(mystston) STD_ROM_FN(mystston) struct BurnDriver BurnDrvmystston = { "mystston", NULL, NULL, "1984", "Mysterious Stones - Dr. John's Adventure\0", NULL, "Technos", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, myststonRomInfo, myststonRomName, DrvInputInfo, DrvDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, NULL, 240, 256, 3, 4 }; // Mysterious Stones - Dr. Kick in Adventure static struct BurnRomInfo myststonoRomDesc[] = { { "ms0", 0x2000, 0x6dacc05f, 1 | BRF_PRG | BRF_ESS }, // 0 M6205 Code { "ms1", 0x2000, 0xa3546df7, 1 | BRF_PRG | BRF_ESS }, // 1 { "ms2", 0x2000, 0x43bc6182, 1 | BRF_PRG | BRF_ESS }, // 2 { "ms3", 0x2000, 0x9322222b, 1 | BRF_PRG | BRF_ESS }, // 3 { "ms4", 0x2000, 0x47cefe9b, 1 | BRF_PRG | BRF_ESS }, // 4 { "ms5", 0x2000, 0xb37ae12b, 1 | BRF_PRG | BRF_ESS }, // 5 { "ms6", 0x2000, 0x85c83806, 2 | BRF_GRA }, // 6 Character + Sprite Tiles { "ms9", 0x2000, 0xb146c6ab, 2 | BRF_GRA }, // 7 { "ms7", 0x2000, 0xd025f84d, 2 | BRF_GRA }, // 8 { "ms10", 0x2000, 0xd85015b5, 2 | BRF_GRA }, // 9 { "ms8", 0x2000, 0x53765d89, 2 | BRF_GRA }, // 10 { "ms11", 0x2000, 0x919ee527, 2 | BRF_GRA }, // 11 { "ms12", 0x2000, 0x72d8331d, 3 | BRF_GRA }, // 12 Sprite Tiles { "ms13", 0x2000, 0x845a1f9b, 3 | BRF_GRA }, // 13 { "ms14", 0x2000, 0x822874b0, 3 | BRF_GRA }, // 14 { "ms15", 0x2000, 0x4594e53c, 3 | BRF_GRA }, // 15 { "ms16", 0x2000, 0x2f470b0f, 3 | BRF_GRA }, // 16 { "ms17", 0x2000, 0x38966d1b, 3 | BRF_GRA }, // 17 { "ic61", 0x0020, 0xe802d6cf, 4 | BRF_GRA }, // 18 Color Prom }; STD_ROM_PICK(myststono) STD_ROM_FN(myststono) struct BurnDriver BurnDrvmyststono = { "myststono", "mystston", NULL, "1984", "Mysterious Stones - Dr. Kick in Adventure\0", NULL, "Technos", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_MISC_MISC, NULL, myststonoRomInfo, myststonoRomName, DrvInputInfo, DrvDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, NULL, 240, 256, 3, 4 };
[ [ [ 1, 675 ] ] ]
4c169e7b3a8cab5582236863090516e965250bb4
6b75de27b75015e5622bfcedbee0bf65e1c6755d
/array-table/stdarg.h
e0cb1e2416214f4aca2d87caa930636b5b87ad19
[]
no_license
xhbang/data_structure
6e4ac9170715c0e45b78f8a1b66c838f4031a638
df2ff9994c2d7969788f53d90291608ac5b1ef2b
refs/heads/master
2020-04-04T02:07:18.620014
2011-12-05T09:39:34
2011-12-05T09:39:34
2,393,408
0
0
null
null
null
null
GB18030
C++
false
false
9,698
h
今天写数组的数据结构时,看到了函数参数不确定头文件stdarg.h的一些用法,典型的例子有大家熟悉的函数printf()、scanf()和系统调用execl()等,那么它们是怎样实现的呢? 现在先用一个使用过程讲解一下: ◎用法: func( Type para1, Type para2, Type para3, ... ) { /****** Step 1 ******/ va_list ap; va_start( ap, para3 ); //一定要“...”之前的那个参数 ,而且这个参数不能使引用类型,因为引用类型不能根据其地址获取后面参数的地址 /****** Step 2 ******/ //此时ap指向第一个可变参数 //调用va_arg取得里面的值 Type xx = va_arg( ap, Type ); //Type一定要相同,如: //char *p = va_arg( ap, char *); //int i = va_arg( ap, int ); //如果有多个参数继续调用va_arg /****** Step 3 ******/ va_end(ap); //For robust! } 然后写个小程序,大家看看就明白了stdarg.h的用法了 #include <iostream> #include <stdarg.h> const int N=5; using namespace std; void Stdarg(int a1,...) { va_list argp; int i; int ary[N]; va_start(argp,a1); ary[0]=a1; for(i=1;i< N;i++) ary[i]=va_arg(argp,int); va_end(argp); for(i=0;i< N;i++) cout<<ary[i]<<endl; } void main() { Stdarg(5,12,64,34,23); } 最后我们来分析一下stdarg.h这个头文件(呵呵,本人也是看的不太懂) typedef char * va_list; #define va_start _crt_va_start #define va_arg _crt_va_arg #define va_end _crt_va_end #define _crt_va_start(ap,v) ( ap = (va_list)_ADDRESSOF(v) + _INTSIZEOF(v) ) #define _crt_va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) ) #define _crt_va_end(ap) ( ap = (va_list)0 ) va_list argptr; C语言的函数是从右向左压入堆栈的,调用va_start后, 按定义的宏运算,_ADDRESSOF得到v所在的地址,然后这个 地址加上v的大小,则使ap指向第一个可变参数如图: 栈底 高地址 | ....... | 函数返回地址 | ....... | 函数最后一个参数 | .... | 函数第一个可变参数 <--va_start后ap指向 | 函数最后一个固定参数 | 函数第一个固定参数 栈顶 低地址 然后,用va_arg()取得类型t的可变参数值, 先是让ap指向下一个参数: ap += _INTSIZEOF(t),然后在减去_INTSIZEOF(t),使得表达式结果为 ap之前的值,即当前需要得到的参数的地址,强制转换成指向此参数的 类型的指针,然后用*取值 最后,用va_end(ap),给ap初始化,保持健壮性。 example:(chenguiming) #include <stdio.h> #include <ctype.h> #include<stdlib.h> #include <stdarg.h> int average( int first, ... ) //变参数函数,C++里也有 { int count=0,i=first,sum=0; va_list maker; //va_list 类型数据可以保存函数的所有参数,做为一个列表一样保存 va_start(maker,first); //设置列表的起始位置 while(i!=-1) { sum+=i; count++; i=va_arg(maker,int);//返回maker列表的当前值,并指向列表的下一个位置 } return sum/count; } void main(void) { printf( "Average is: %d\n", average( 2, 3, 4,4, -1 ) ); } Linux下的stdarg.h #ifndef _STDARG_H #define _STDARG_H typedef char *va_list; /* 定义va_list 是一个字符指针类型*/ /* Amount of space required in an argument list for an arg of type TYPE. TYPE may alternatively be an expression whose type is used. */ /* 下面给出了类型为TYPE 的arg 参数列表所要求的空间容量。 TYPE 也可以是使用该类型的一个表达式 */ // 下面这句定义了取整后的TYPE 类型的字节长度值。是int 长度(4)的倍数。 #define __va_rounded_size(TYPE) \ (((sizeof (TYPE) + sizeof (int) - 1) / sizeof (int)) * sizeof (int)) // 下面这个函数(用宏实现)使AP 指向传给函数的可变参数表的第一个参数。 // 在第一次调用va_arg 或va_end 之前,必须首先调用该函数。 // 17 行上的__builtin_saveregs()是在gcc 的库程序libgcc2.c 中定义的,用于保存寄存器。 // 它的说明可参见gcc 手册章节“Target Description Macros”中的 // “Implementing the Varargs Macros”小节。 #ifndef __sparc__ #define va_start(AP, LASTARG) \ (AP = ((char *) &(LASTARG) + __va_rounded_size (LASTARG))) #else #define va_start(AP, LASTARG) \ (__builtin_saveregs (), \ AP = ((char *) &(LASTARG) + __va_rounded_size (LASTARG))) #endif // 下面该宏用于被调用函数完成一次正常返回。va_end 可以修改AP 使其在重新调用 // va_start 之前不能被使用。va_end 必须在va_arg 读完所有的参数后再被调用。 void va_end (va_list); /* Defined in gnulib *//* 在gnulib 中定义 */ #define va_end(AP) // 下面该宏用于扩展表达式使其与下一个被传递参数具有相同的类型和值。 // 对于缺省值,va_arg 可以用字符、无符号字符和浮点类型。 // 在第一次使用va_arg 时,它返回表中的第一个参数,后续的每次调用都将返回表中的 // 下一个参数。这是通过先访问AP,然后把它增加以指向下一项来实现的。 // va_arg 使用TYPE 来完成访问和定位下一项,每调用一次va_arg,它就修改AP 以指示 // 表中的下一参数。 #define va_arg(AP, TYPE) \ (AP += __va_rounded_size (TYPE), \ *((TYPE *) (AP - __va_rounded_size (TYPE)))) #endif /* _STDARG_H */ 今天在写ini配置文件操作类时不小心遇到了标题中的几个宏,一时迷惑不解,花了半个钟左右才算是弄懂了它们。 当你的函数的参数个数不确定时,就可以使用上述宏进行动态处理,这无疑为你的程序增加了灵活性。 Example: CString AppendString(CString str1,...)//一个连接字符串的函数,参数个数可以动态变化 { LPCTSTR str=str1;//str需为指针类型,因为va_arg宏返回的是你的参数的指针,但是如果你的参数为int等简 //单类型,则不必为指针,因为变量名实际上即是指针。 CString res; va_list marker; //你的类型链表 va_start(marker,str1);//初始化你的marker链表 while(str!="ListEnd")//ListEnd:参数的结束标志,十分重要,在实际中需自行指定 { res+=str; str=va_arg(marker,CString);//取得下一个指针 } va_end(marker);//结束,与va_start合用 return res; } int main() { CString str=AppendString("xu","zhi","hong","ListEnd"); cout<<str.GetBuffer(str.GetLength())<<endl; return 0; } 输出 xuzhihong CString AppendString(CString str1,...),因为连接字符串的参数可以动态变化,你不知用户要进行连接的字符串个数是多少,所以你可以用…来代替。但是要注意的是你的函数要有一个参数作为标志来表示结束,否则会出错。在下例中用ListEnd作为结束符。还有va_arg返回的是你参数内容的指针。上例在支持MFC程序的console下运行通过。 MSDN是你最好的老师,如果你还不明白请参看MSDN并且编多几个例子进行尝试,当然顿感开怀,说明此时你已经明白,呵呵。 自写的ini配置文件操作类已经完成,接下来会对注册表的常用操作进行封装。 va_list 详解 VA_LIST 是在C语言中解决变参问题的一组宏 他有这么几个成员: 1) va_list型变量: #ifdef _M_ALPHA typedef struct { char *a0; /* pointer to first homed integer argument */ int offset; /* byte offset of next parameter */ } va_list; #else typedef char * va_list; #endif 2)_INTSIZEOF 宏,获取类型占用的空间长度,最小占用长度为int的整数倍: #define _INTSIZEOF(n) ( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1) ) 3)VA_START宏,获取可变参数列表的第一个参数的地址(ap是类型为va_list的指针,v是可变参数最左边的参数): #define va_start(ap,v) ( ap = (va_list)&v + _INTSIZEOF(v) ) 4)VA_ARG宏,获取可变参数的当前参数,返回指定类型并将指针指向下一参数(t参数描述了当前参数的类型): #define va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) ) 5)VA_END宏,清空va_list可变参数列表: #define va_end(ap) ( ap = (va_list)0 ) VA_LIST的用法: (1)首先在函数里定义一具VA_LIST型的变量,这个变量是指向参数的指针; (2)然后用VA_START宏初始化变量刚定义的VA_LIST变量; (3)然后用VA_ARG返回可变的参数,VA_ARG的第二个参数是你要返回的参数的类型(如果函数有多个可变参数的,依次调用VA_ARG获取各个参数); (4)最后用VA_END宏结束可变参数的获取。 使用VA_LIST应该注意的问题: (1)可变参数的类型和个数完全由程序代码控制,它并不能智能地识别不同参数的个数和类型; (2)如果我们不需要一一详解每个参数,只需要将可变列表拷贝至某个缓冲,可用vsprintf函数; (3)因为编译器对可变参数的函数的原型检查不够严格,对编程查错不利.不利于我们写出高质量的代码; 小结:可变参数的函数原理其实很简单,而VA系列是以宏定义来定义的,实现跟堆栈相关。我们写一个可变参数的C函数时,有利也有弊,所以在不必要的场合,我们无需用到可变参数,如果在C++里,我们应该利用C++多态性来实现可变参数的功能,尽量避免用C语言的方式来实现。
[ [ [ 1, 244 ] ] ]
266b3a00a378c6df3a9c66d917682b0f20b31f1d
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Source/Nuclex/Application.cpp
23aa998a94d414aca6b635eb3fe692f50e037889
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
14,837
cpp
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## Application.cpp - Platform abstraction of an application  // // ### # # ###  // // # ### # ### Manages interaction of the application with the operating system,  // // # ## # # ## ## eg. settings up and managing a window  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #include "Nuclex/Application.h" #include "Resource.h" using namespace Nuclex; #ifdef NUCLEX_WIN32 /** Stores the number of opened rendering windows. Useful to track when the window class needs to be registered and when it can be unregistered again. */ size_t Application::m_nOpenWindows = 0; #endif // NUCLEX_WIN32 // ############################################################################################# // // # Nuclex::Application::Application() # // // ############################################################################################# // /** Initializes an instance of Application @param sTitle Application title (used as window title) */ Application::Application(const string &sTitle) : #ifdef NUCLEX_WIN32 m_hInstance(::GetModuleHandle(NULL)), m_hWindow(NULL), m_bOwnWindow(false), m_bFocused(false), m_bClose(false), #endif m_sTitle(sTitle), m_bVisible(false) { createWindow(sTitle); } // ############################################################################################# // // # Nuclex::Application::~Application() # // // ############################################################################################# // /** Releases an instance of Application */ Application::~Application() { destroyWindow(); } // ############################################################################################# // // # Nuclex::Application::heartBeat() # // // ############################################################################################# // /** Regular update */ bool Application::heartBeat() { #ifdef NUCLEX_WIN32 MSG Message; while(::PeekMessage(&Message, NULL, 0, 0, PM_REMOVE)) { ::TranslateMessage(&Message); ::DispatchMessage(&Message); } #endif while(m_InputEvents.size()) { m_InputEvents.front()(); m_InputEvents.pop_front(); } bool bCloseRequested = m_bClose; return m_bClose = false, bCloseRequested; } // ############################################################################################# // // # Nuclex::Application::setSize() # // // ############################################################################################# // /** Resizes the application @param Size Size in pixels to resize the application to */ void Application::setSize(const Point2<size_t> &Size) { #ifdef NUCLEX_WIN32 RECT Rect = { 0, 0, Size.X, Size.Y }; if(!::AdjustWindowRectEx( &Rect, ::GetWindowLong(m_hWindow, GWL_STYLE), false, 0 )) throw UnexpectedException( "Nuclex::Application::resize()", "GetWindowLong() failed unexpectedly" ); if(!SetWindowPos( m_hWindow, HWND_TOP, Rect.left, Rect.top, Rect.right - Rect.left, Rect.bottom - Rect.top, SWP_NOMOVE | SWP_NOZORDER )) throw UnexpectedException( "Nuclex::Application::resize()", "SetWindowPos() failed unexpectedly" ); #endif // NUCLEX_WIN32 } // ############################################################################################# // // # Nuclex::Application::show() # // // ############################################################################################# // /** Shows or hides the application @param bShow Whether to show the application */ void Application::show(bool bShow) { #ifdef NUCLEX_WIN32 ::ShowWindow(m_hWindow, bShow ? SW_SHOW : SW_HIDE); #endif // NUCLEX_WIN32 } #ifdef NUCLEX_WIN32 // ############################################################################################# // // # Nuclex::Application::createWindow() # // // ############################################################################################# // /** Creates a new window @param sName Window name @param hWnd Existing window handle to use or NULL */ void Application::createWindow(const string &sName, HWND hWnd) { if(!hWnd) { if(m_nOpenWindows == 0) { WNDCLASSEX WindowClassEx; // Create and register our window class WindowClassEx.cbSize = sizeof(WindowClassEx); WindowClassEx.style = CS_BYTEALIGNCLIENT | CS_HREDRAW | CS_VREDRAW; WindowClassEx.lpfnWndProc = internalWindowProc; WindowClassEx.cbClsExtra = 0; WindowClassEx.cbWndExtra = 0; WindowClassEx.hInstance = m_hInstance; WindowClassEx.hIcon = ::LoadIcon(m_hInstance, MAKEINTRESOURCE(IDI_NUCLEX)); WindowClassEx.hCursor = ::LoadCursor(NULL, IDC_ARROW); WindowClassEx.hbrBackground = NULL; //reinterpret_cast<HBRUSH>(::GetStockObject(BLACK_BRUSH)); WindowClassEx.lpszMenuName = NULL; WindowClassEx.lpszClassName = "Nuclex"; WindowClassEx.hIconSm = NULL; if(!::RegisterClassEx(&WindowClassEx)) throw UnexpectedException("Nuclex::Application::createWindow()", "Unexpected API failure in RegisterClassEx()"); } ++m_nOpenWindows; // Create the window hWnd = ::CreateWindowEx( WS_EX_APPWINDOW, "Nuclex", sName.c_str(), WS_POPUPWINDOW | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | (m_bVisible ? WS_VISIBLE : DWORD(0)), CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, //::GetDesktopWindow(), NULL, m_hInstance, NULL ); if(!hWnd) throw UnexpectedException("Nuclex::Application::createWindow()", "Failed to create window"); m_bOwnWindow = true; } else { if(::GetProp(m_hWindow, "Nuclex::Application")) throw InvalidArgumentException("Nuclex::Application::createWindow()", "This window is already used by another instance!"); m_bOwnWindow = false; } m_hWindow = hWnd; ::SetProp(hWnd, "Nuclex::Application", reinterpret_cast<HANDLE>(this)); } // ############################################################################################# // // # Nuclex::Application::destroyWindow() # // // ############################################################################################# // /** Destroys the currently open window */ void Application::destroyWindow() { if(m_hWindow) { ::RemoveProp(m_hWindow, "Nuclex::Application"); if(m_bOwnWindow) { HINSTANCE hInstance = ::GetModuleHandle(NULL); ::DestroyWindow(m_hWindow); --m_nOpenWindows; if(m_nOpenWindows == 0) ::UnregisterClass("Nuclex", hInstance); m_bOwnWindow = false; } m_hWindow = NULL; } } // ############################################################################################# // // # Nuclex::Application::internalWindowProc() # // // ############################################################################################# // /** Internal window callback procedure. Delegates to the Application::windowProc() method. @param hWnd Window handle @param uMessage Message sent to the window @param wParam Word argument @param lParam Long argument @return Window message result */ LRESULT CALLBACK Application::internalWindowProc( HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam ) { // Get the pointer to the class owning this Window and give the // call on to the class's WindowProc() Application *pThis = reinterpret_cast<Application *>( ::GetProp(hWnd, "Nuclex::Application") ); if(pThis) return pThis->windowProc(uMessage, wParam, lParam); // This point should not be reached, all windows should have // the Nuclex::Application value set return ::DefWindowProc(hWnd, uMessage, wParam, lParam); } // ############################################################################################# // // # Nuclex::Application::windowProc() # // // ############################################################################################# // /** Window callback procedure @param uMessage Message sent to the window @param wParam Word argument @param lParam Long argument @return Window message result */ LRESULT CALLBACK Application::windowProc(UINT uMessage, WPARAM wParam, LPARAM lParam) { switch(uMessage) { // Window status changed case WM_ACTIVATE: { if(LOWORD(wParam) == WA_INACTIVE) m_bFocused = false; else m_bFocused = !HIWORD(wParam); break; } // Application status changed case WM_ACTIVATEAPP: { m_bFocused = !!wParam; break; } // Window close requested case WM_CLOSE: { m_bClose = true; return 0; // Prevent DefWindowProc from calling DestroyWindow() } // Window has been resized case WM_SIZE: { RECT Rect; ::GetClientRect(m_hWindow, &Rect); m_Size.set(Rect.right - Rect.left, Rect.bottom - Rect.top); break; } // Window has been moved case WM_PAINT: { ::ValidateRect(m_hWindow, NULL); // Validate everything return 0; // Prevent DefWindowProc from drawing } case WM_ERASEBKGND: { return TRUE; // Prevent DefWindowProc from erasing the background } // Cursor state set requested case WM_SETCURSOR: { if((m_Size.X > 0) && (m_Size.Y > 0)) { RECT Rect; POINT CursorPos; // All this code just to translate the ClientRect coordinates into // Screen coordinates... ::GetClientRect(m_hWindow, &Rect); CursorPos.x = Rect.left; CursorPos.y = Rect.top; ::ClientToScreen(m_hWindow, &CursorPos); Rect.left = CursorPos.x; Rect.top = CursorPos.y; CursorPos.x = Rect.right; CursorPos.y = Rect.bottom; ::ClientToScreen(m_hWindow, &CursorPos); Rect.right = CursorPos.x; Rect.bottom = CursorPos.y; // Obtain cursor position ::GetCursorPos(&CursorPos); // If it is inside the client area, hide the cursor if((CursorPos.x > Rect.left) && (CursorPos.x < Rect.right) && (CursorPos.y > Rect.top) && (CursorPos.y < Rect.bottom)) { ::SetCursor(NULL); return TRUE; // Prevent DefWindowProc from assigning the default cursor } } break; } // Character input case WM_CHAR: { m_InputEvents.push_back(MakeFunctorInvocation(OnChar, wParam)); break; } // Key pressed case WM_KEYDOWN: { m_InputEvents.push_back(MakeFunctorInvocation(OnKeyDown, LOBYTE(HIWORD(lParam)))); break; } // Key released case WM_KEYUP: { m_InputEvents.push_back(MakeFunctorInvocation(OnKeyUp, LOBYTE(HIWORD(lParam)))); break; } // Left mouse button pressed case WM_LBUTTONDOWN: { m_InputEvents.push_back(MakeFunctorInvocation( OnMouseButtonDown, Point2<long>(LOWORD(lParam), HIWORD(lParam)), 0 )); break; } // Left mouse button released case WM_LBUTTONUP: { m_InputEvents.push_back(MakeFunctorInvocation( OnMouseButtonUp, Point2<long>(LOWORD(lParam), HIWORD(lParam)), 0 )); break; } // Right mouse button pressed case WM_RBUTTONDOWN: { m_InputEvents.push_back(MakeFunctorInvocation( OnMouseButtonDown, Point2<long>(LOWORD(lParam), HIWORD(lParam)), 1 )); break; } // Right mouse button released case WM_RBUTTONUP: { m_InputEvents.push_back(MakeFunctorInvocation( OnMouseButtonUp, Point2<long>(LOWORD(lParam), HIWORD(lParam)), 1 )); break; } // Middle mouse button pressed case WM_MBUTTONDOWN: { m_InputEvents.push_back(MakeFunctorInvocation( OnMouseButtonDown, Point2<long>(LOWORD(lParam), HIWORD(lParam)), 2 )); break; } // Middle mouse button released case WM_MBUTTONUP: { m_InputEvents.push_back(MakeFunctorInvocation( OnMouseButtonUp, Point2<long>(LOWORD(lParam), HIWORD(lParam)), 2 )); break; } // Extended mouse button pressed case WM_XBUTTONDOWN: { m_InputEvents.push_back(MakeFunctorInvocation( OnMouseButtonDown, Point2<long>(LOWORD(lParam), HIWORD(lParam)), GET_XBUTTON_WPARAM(wParam) - XBUTTON1 + 3 )); break; } // Extended mouse button released case WM_XBUTTONUP: { m_InputEvents.push_back(MakeFunctorInvocation( OnMouseButtonUp, Point2<long>(LOWORD(lParam), HIWORD(lParam)), GET_XBUTTON_WPARAM(wParam) - XBUTTON1 + 3 )); break; } // Mouse moved case WM_MOUSEMOVE: { m_InputEvents.push_back(MakeFunctorInvocation( OnMouseMove, Point2<long>(LOWORD(lParam), HIWORD(lParam)) )); break; } // Mouse wheel rotated case WM_MOUSEWHEEL: { m_InputEvents.push_back(MakeFunctorInvocation(OnMouseWheel, HIWORD(wParam))); break; } } return ::DefWindowProc(m_hWindow, uMessage, wParam, lParam); } #endif // NUCLEX_WIN32
[ [ [ 1, 466 ] ] ]
c3501d08829373397fcf2a5d00e68afa7da8393f
60791ce953e9891f156b6862ad59ac4830a7cad2
/CATL/random.h
19e058dec6aff476e5310fa0db96c6b20575db26
[]
no_license
siavashmi/catl-code
05283c6e24a1d3aa9652421a93f094c46c477014
a668431b661c59f597c6f9408c371ec013bb9072
refs/heads/master
2021-01-10T03:17:38.898659
2011-06-30T10:27:35
2011-06-30T10:27:35
36,600,037
0
0
null
null
null
null
UTF-8
C++
false
false
6,920
h
#ifndef _RANDOM_H #define _RANDOM_H #include "stdio.h" #include "stdlib.h" #include "math.h" #ifndef MAXINT #define MAXINT 2147483647 #endif /* * random number generator * these codes are from ns-2 */ class RNG { public: RNG(){} RNG(int seed) { set_seed( seed); }; void set_seed(int seed = 1) {srand(seed);} inline static RNG* defaultrng() { return (default_); } inline double uniform() {return (double)rand()/(double)RAND_MAX;}// range [0.0, 1.0) inline unsigned long uniform32() {return (unsigned long)(uniform() * (unsigned long)0xffffffff); } inline double uniform(double r) { return (r * uniform());} inline double uniform(double a, double b) { return (a + uniform(b - a)); } inline double exponential() { double u = uniform(); while (u == 0.0) { u = uniform(); } return (-log(u)); } inline double exponential(double r) { return (r * exponential());} inline double pareto(double scale, double shape) { // When 1 < shape < 2, its mean is scale**shape, and its // variance is infinite. double u = uniform(); while (u == 0.0 || u == 1.0) { u = uniform(); } return (scale * (1.0/pow(u, 1.0/shape))); } //a- shape, k - scale, p - bound inline double paretoBd(double a, double k, double p) { double z; double rv; do { z = uniform(); } while(z == 0 || z == 1); rv = -(z * pow(p, a) - z * pow(k, a) - pow(p, a))/(pow(p, a) * pow(k, a)); rv = pow(rv, (-1/a)); return rv; } inline double paretoII(double scale, double shape) { double z; do { z = uniform(); } while(z == 0 ); return (scale * ((1.0/pow(uniform(), 1.0/shape)) - 1)); } double normal(double avg, double std) { static int parity = 0; static double nextresult; double sam1, sam2, rad; if (std == 0) return avg; if (parity == 0) { sam1 = 2*uniform() - 1; sam2 = 2*uniform() - 1; while ((rad = sam1*sam1 + sam2*sam2) >= 1) { sam1 = 2*uniform() - 1; sam2 = 2*uniform() - 1; } rad = sqrt((-2*log(rad))/rad); nextresult = sam2 * rad; parity = 1; return (sam1 * rad * std + avg); } else { parity = 0; return (nextresult * std + avg); } } inline double lognormal(double avg, double std) { return (exp (normal(avg, std))); } static RNG* default_; }; class RandomVariable { public: virtual double value() = 0; virtual double avg() = 0; RandomVariable(){ rng_ = RNG::defaultrng();}; protected: RNG* rng_; }; class UniformRandVar : public RandomVariable { public: UniformRandVar(double min = 0, double max = 1){ min_ = min; max_ = max; } virtual double value(){ return(rng_->uniform(min_, max_)); } virtual inline double avg() { return (max_-min_)/2; }; double* minp() { return &min_; }; double* maxp() { return &max_; }; double min() { return min_; }; double max() { return max_; }; void setmin(double d) { min_ = d; }; void setmax(double d) { max_ = d; }; private: double min_; double max_; }; class ExponentialRandVar : public RandomVariable { public: ExponentialRandVar(double avg = 1) {avg_ = avg; } virtual double value(){ return(rng_->exponential(avg_)); } double* avgp() { return &avg_; }; virtual inline double avg() { return avg_; }; void setavg(double d) { avg_ = d; }; private: double avg_; }; /* * It has infinite mean if a <= 1 and mean ab/(a-1) if a > 1. The variance is ab**2/(a-1)**2(a-2) if a > 2, infinite if 1 < a <= 2, and undefined if a <= 1. */ class ParetoRandVar : public RandomVariable { public: ParetoRandVar(double avg = 1, double shape = 0){ avg_ = avg; shape_ = shape; scale_ = avg_ * (shape_ -1)/shape_; }; ParetoRandVar(double scale, double shape, int dumb) { shape_ = shape; scale_= scale; avg_ = scale_ * shape_/(shape_ - 1); } virtual double value() { return(rng_->pareto(scale_, shape_));} double* avgp() { return &avg_; }; double* shapep() { return &shape_; }; virtual double avg() { return avg_; }; double shape() { return shape_; }; void setavg(double d) { avg_ = d; }; void setshape(double d) { shape_ = d; }; protected: double avg_; double shape_; double scale_; }; class ShiftedParetoRandVar : public RandomVariable { public: ShiftedParetoRandVar(double scale, double shape) { shape_ = shape; scale_= scale; avg_ = scale_ * shape_/(shape_ - 1); } virtual double value() { return(rng_->pareto(scale_, shape_) - scale_);} virtual double avg() { return avg_ - scale_; }; double shape() { return shape_; }; void setavg(double d) { avg_ = d; }; void setshape(double d) { shape_ = d; }; protected: double avg_; double shape_; double scale_; }; /* * Bounded Pareto Distribution */ class BdParetoRandVar : public ParetoRandVar { public: BdParetoRandVar(double shape, double scale, double bound) { shape_ = shape; scale_= scale; bound_ = bound; avg_ = pow(scale_, shape_)/(1-pow(scale_/bound_, shape_)); avg_ *= (shape_/(shape_-1)); avg_ *= (1/pow(scale_, shape_-1) - 1/pow(bound_, shape_-1)); } virtual double value() { double val = rng_->paretoBd(shape_, scale_, bound_); return val; } double bound() { return bound_; } double scale() { return scale_; } double shape() { return shape_; } void setscale(double scale) { scale_ = scale; } private: double bound_; }; class NormalRandVar : public RandomVariable { public: NormalRandVar(double avg = 1, double std = 0) {avg_ = avg; std_ = std;} virtual double value(){ return(rng_->normal(avg_, std_)); } inline double* avgp() { return &avg_; }; inline double* stdp() { return &std_; }; virtual double avg() { return avg_; }; inline double std() { return std_; }; inline void setavg(double d) { avg_ = d; }; inline void setstd(double d) { std_ = d; }; private: double avg_; double std_; }; class LogNormalRandVar : public RandomVariable { public: LogNormalRandVar(double logavg = 1, double logstd = 0) {logavg_ = logavg; logstd_ = logstd;} virtual double value() { return(rng_->lognormal(logavg_, logstd_)); }; //double* avgp() { return &avg_; }; //double* stdp() { return &std_; }; //virtual inline double avg() { return avg_; }; double std() { return logstd_; }; //void setavg(double d) { avg_ = d; }; //void setstd(double d) { std_ = d; }; //double mean() { return exp(avg_ + std_*std_/2); }; double avg() { return exp(logavg_ + logstd_*logstd_/2); }; private: double logavg_; double logstd_; }; double randouble(double low, double high); int randint(int low, int high); unsigned int rand32(); #endif
[ [ [ 1, 272 ] ] ]
ef1b8709216212deecd1e94eccf02bf0a8065d95
9566086d262936000a914c5dc31cb4e8aa8c461c
/EnigmaSession/ServerSessionManager.hpp
702072f056da422200440d3c9304a719ae7dc863
[]
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
12,871
hpp
#ifndef SERVERSESSIONMANAGER_HPP_INCLUDED #define SERVERSESSIONMANAGER_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 "EventManager.hpp" #include "Entities\Object.hpp" #include "IServerTransmissionManager.hpp" #include "Entities\Realm.hpp" #include "Messages\RequestMessages.hpp" #include "Messages\ResponseMessages.hpp" #include "DataAccess.hpp" namespace Enigma { class DllExport ServerSessionManager : public EventManager { private: IServerTransmissionManager* mServerTransmissionManager; Realm mRealm; DataAccess mDataAccess; protected: //Send a packet to a single peer. void SendMessageToPeer(const std::string& peerId,MessageContainer& message); //Send a packet to all the peers on a single map. void SendMessageToMap(const std::string& peerId,MessageContainer& message); //Send a packet to all the peers in a party. void SendMessageToParty(const std::string& peerId,MessageContainer& message); //Send a packet to all the peers in a guild. void SendMessageToGuild(const std::string& peerId,MessageContainer& message); //Send a packet to all connected peers. (Include those not logged in.) void SendMessageToWorld(const std::string& peerId,MessageContainer& message); void EnterMap(const std::string& peerId); void EnterMap(const std::string& peerId,Character character); void ExitMap(const std::string& peerId); bool ChangeMap(const std::string& peerId,size_t newMapId); void SendCharactersOnMapToPlayer(const std::string& peerId); void SendNpcsOnMapToPlayer(const std::string& peerId); void SendItemsOnMapToPlayer(const std::string& peerId); void SendMonstersOnMapToPlayer(const std::string& peerId); void SendServerMessageToPeer(const std::string& peerId,const std::string& message); void SendServerMessageToParty(const std::string& peerId,const std::string& message); void SendServerMessageToGuild(const std::string& peerId,const std::string& message); void SendServerMessageToMap(const std::string& peerId,const std::string& message); void SendServerMessageToWorld(const std::string& peerId,const std::string& message); std::string GetUserByCharacterName(const std::string& name); std::string GetUserByCharacterId(size_t characterId); /* * Takes in a peerId and returns a reference to that users current character. * Note that if this user has not selected a character then this will result in an exception. */ Character& GetCurrentCharacter(const std::string& peerId); Character& GetCharacter(size_t mapId, size_t index); void CreateCharacter(size_t mapId, size_t index); void DeleteCharacter(size_t mapId, size_t index); Monster& GetMonster(size_t mapId, size_t index); void CreateMonster(size_t mapId, size_t index); void DeleteMonster(size_t mapId, size_t index); Npc& GetNpc(size_t mapId, const std::string& index); Npc& GetNpc(size_t mapId, size_t index); void CreateNpc(size_t mapId, const std::string& index); void CreateNpc(size_t mapId, size_t index); void DeleteNpc(size_t mapId, const std::string& index); void DeleteNpc(size_t mapId, size_t index); Item& GetItem(size_t mapId, size_t index); void CreateItem(size_t mapId, size_t index); void DeleteItem(size_t mapId, size_t index); /* * Takes in a peerId and returns a reference to that users current character's guild. * Note that if this user has not selected a character or is not in a guild this will result in an exception. */ Guild& GetCurrentGuild(const std::string& peerId); /* * Takes in a peerId and returns a reference to that user's current character's party. * Note that if this user has not selected a character or is not in a party this will result in an exception. */ Party& GetCurrentParty(const std::string& peerId); /* * Takes in a peerId and returns a reference to that users current character's guild rank. * Note that if this user has not selected a character or is not in a guild this will result in an exception. */ Rank& GetCurrentRank(const std::string& peerId); /* * Takes in a peerId and returns a boolean that indicates whether or not the current user's character is the leader of their guild. * Note that if this user has not selected a character or is not in a guild this will result in an exception. */ bool GetIsCurrentGuildLeader(const std::string& peerId); /* * Takes in a peerId and returns a reference to that users current character's selected npc. * Note that if this user has not selected a character or has not selected an npc this will result in an exception. */ Npc& GetCurrentNpc(const std::string& peerId); /* * Takes in a peerId and returns a refernce to that user's current character's map. * Note that if this user has not selected a characer and that character has entered a map this will result in an exception. */ Map& GetCurrentMap(const std::string& peerId); /* * Takes in a peerId and returns a reference to that user's current character's current npc's current question. * Note that if this user has not selected a character,entered a map, and selected an npc this will result in an exception. */ NpcQuestion& GetCurrentNpcQuestion(const std::string& peerId); /* * Takes in a peerId and returns a reference to that user's stash. * Note that if this user is not logged in this will result in an exception. */ std::map<size_t,Item>& GetStash(const std::string& peerId); void GivePlayerItem(const std::string& peerId,Item item); void GivePlayerItem(const std::string& peerId,Item item,size_t stackSize); void TakePlayerItem(const std::string& peerId,size_t locationId); void TakePlayerItem(const std::string& peerId,size_t locationId,size_t stackSize); void TransferPlayerItemToStash(const std::string& peerId,size_t locationId); void TransferPlayerItemToStash(const std::string& peerId,size_t locationId,size_t stackSize); void TransferPlayerItemFromStash(const std::string& peerId,size_t locationId); void TransferPlayerItemFromStash(const std::string& peerId,size_t locationId,size_t stackSize); void TransferPlayerItemToPlayer(const std::string& peerId,size_t locationId,size_t characterId); void TransferPlayerItemToPlayer(const std::string& peerId,size_t locationId,size_t characterId,size_t stackSize); size_t FindNextAvailableSlot(std::map<size_t,Item> itemCollection); size_t FindSlotWithItem(std::map<size_t,Item> itemCollection,size_t itemId); public: ServerSessionManager(); ~ServerSessionManager(); void PreInit(); void Init(IServerTransmissionManager* serverTransmissionManager); void Load(); void Unload(); /* * Used by the transmission manager to inform the session manager that a user has been disconnected and should be removed from the world. * if the peerId is invalid it may result in an exception. */ void DisconnectUser(const std::string& peerId); /* * Fires all application events for all application listeners from the current thread. * Although not limited by the design it is intended that this method be called from one thread. */ void DoApplicationEvents(); /* * Fires all scene events for all scene listeners from the current thread. * Although not limited by the design it is intended that this method be called from one thread. */ void DoSceneEvents(); /* * Fires all chat events for all chat listeners from the current thread. * Although not limited by the design it is intended that this method be called from one thread. */ void DoChatEvents(); /* * Fires all audio events for all audio listeners from the current thread. * Although not limited by the design it is intended that this method be called from one thread. */ void DoAudioEvents(); //Authentication Start //Process a client message related to authentication. std::string ProcessMessage(LoginRequestMessage& message,const std::string& peerId); //Process a client message related to authentication. std::string ProcessMessage(CharacterCreationRequestMessage& message,const std::string& peerId); //Process a client message related to authentication. std::string ProcessMessage(CharacterListRequestMessage& message,const std::string& peerId); //Process a client message related to authentication. std::string ProcessMessage(CharacterSelectionRequestMessage& message,const std::string& peerId); //Authentication End //Movement Start //Process a client message related to movement. std::string ProcessMessage(MovementRequestMessage& message,const std::string& peerId); //Process a client message related to player state change. std::string ProcessMessage(PlayerOnMapUpdateRequestMessage& message,const std::string& peerId); //Process a client message related to player state change. std::string ProcessMessage(ChangeMapRequestMessage& message,const std::string& peerId); //Process a client message related to npc state change. std::string ProcessMessage(NpcOnMapUpdateRequestMessage& message,const std::string& peerId); //Process a client message related to monster state change. std::string ProcessMessage(MonsterOnMapUpdateRequestMessage& message,const std::string& peerId); //Process a client message related to item state change. std::string ProcessMessage(ItemOnMapUpdateRequestMessage& message,const std::string& peerId); //Movement End //Chat Start //Process a client message related to chat. std::string ProcessMessage(ChatRequestMessage& message,const std::string& peerId); //Process a client message related to inviting. std::string ProcessMessage(InviteRequestMessage& message,const std::string& peerId); //Process a client message related to kicking. std::string ProcessMessage(KickRequestMessage& message,const std::string& peerId); //Process a client message related to player list. std::string ProcessMessage(PlayerListRequestMessage& message,const std::string& peerId); //Process a client message related to ?. std::string ProcessMessage(CreatePlayerOrganizationRequestMessage& message,const std::string& peerId); //Process a client message related to ?. std::string ProcessMessage(ModifyPlayerOrganizationRankRequestMessage& message,const std::string& peerId); //Process a client message related to ?. std::string ProcessMessage(SetPlayerRankRequestMessage& message,const std::string& peerId); //Process a client message related to ?. std::string ProcessMessage(RollRequestMessage& message,const std::string& peerId); //Process a client message related to ?. std::string ProcessMessage(ServerTimeRequestMessage& message,const std::string& peerId); //Process a client message related to ?. std::string ProcessMessage(NpcChatRequestMessage& message,const std::string& peerId); //Chat End //Voice Start //Process a client message related to voice chat. std::string ProcessMessage(VoiceChatRequestMessage& message,const std::string& peerId); //Voice End //Combat Start //Process a client message related to combat std::string ProcessMessage(ItemTransferRequestMessage& message,const std::string& peerId); //Process a client message related to combat std::string ProcessMessage(SkillRequestMessage& message,const std::string& peerId); //Combat End }; }; #endif // SERVERSESSIONMANAGER_HPP_INCLUDED
[ [ [ 1, 284 ] ] ]
f52ba2cf1c4b3322b573dfde8e4b977499dbc51b
b4671d6262e1b4171ca3407b0b3de2a1683639a1
/Objects/Sphere.h
dd9442a1a117469cdf7123e5e68d3a38eae6a94e
[]
no_license
dgoemans/g-ray
c600792842c23c065564e984fb36fd14ef936171
268caee1841da2c00d6bc8860341e6196fd75d0f
refs/heads/master
2021-01-01T05:51:46.927060
2008-08-22T21:27:45
2008-08-22T21:27:45
32,354,668
0
0
null
null
null
null
UTF-8
C++
false
false
496
h
#ifndef SPHERE_H_INCLUDED #define SPHERE_H_INCLUDED #include "BaseObject.h" using namespace vmml; using namespace RayTracerHelper; class Sphere : public BaseObject { public: Sphere( const Vector3f& position, const float& radius, const Color& color, const float& reflectivity, const float& refractivity ); virtual ~Sphere(); virtual bool Intersect(Ray ray, IntersectionInfo &outInfo); private: float radius; }; #endif // SPHERE_H_INCLUDED
[ "dgoemans@8105284b-e854-0410-88c8-61786a572e0c" ]
[ [ [ 1, 23 ] ] ]