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
bebdf8122715ea9d192833b6f81d6fcae49b1c1f
b8c3d2d67e983bd996b76825f174bae1ba5741f2
/RTMP/utils/gil_2/boost/gil/extension/opencv/ipl_image_wrapper.hpp
7a6df2d11858e370c2bf4fbe9d06dfd7791e9816
[]
no_license
wangscript007/rtmp-cpp
02172f7a209790afec4c00b8855d7a66b7834f23
3ec35590675560ac4fa9557ca7a5917c617d9999
refs/heads/master
2021-05-30T04:43:19.321113
2008-12-24T20:16:15
2008-12-24T20:16:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,712
hpp
/* Copyright 2008 Christian Henning Use, modification and distribution are subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). */ /*************************************************************************************************/ #ifndef BOOST_GIL_EXTENSION_OPENCV_IPL_IMAGE_WRAPPER_HPP_INCLUDED #define BOOST_GIL_EXTENSION_OPENCV_IPL_IMAGE_WRAPPER_HPP_INCLUDED //////////////////////////////////////////////////////////////////////////////////////// /// \file /// \brief /// \author Christian Henning \n /// /// \date 2008 \n /// //////////////////////////////////////////////////////////////////////////////////////// #include <boost\gil\gil_all.hpp> #include "utilities.hpp" namespace boost { namespace gil { namespace opencv { template < typename Channel > struct ipl_channel_type : boost::mpl::false_ {}; template<> struct ipl_channel_type< bits8 > : boost::mpl::int_< IPL_DEPTH_8U > {}; template<> struct ipl_channel_type< bits16 > : boost::mpl::int_< IPL_DEPTH_16U > {}; template<> struct ipl_channel_type< bits32f > : boost::mpl::int_< IPL_DEPTH_32F > {}; template<> struct ipl_channel_type< double > : boost::mpl::int_< IPL_DEPTH_64F > {}; template<> struct ipl_channel_type< bits8s > : boost::mpl::int_< IPL_DEPTH_8S > {}; template<> struct ipl_channel_type< bits16s > : boost::mpl::int_< IPL_DEPTH_16S > {}; template<> struct ipl_channel_type< bits32s > : boost::mpl::int_< IPL_DEPTH_32S > {}; // doesn't work //typedef boost::shared_ptr< IplImage > ipl_image_wrapper; class ipl_image_wrapper { public: ipl_image_wrapper( IplImage* img ) : _img( img ) {} IplImage* get() { return _img; } const IplImage* get() const { return _img; } private: IplImage* _img; }; template< typename View > inline ipl_image_wrapper create_ipl_image( View view ) { typedef typename channel_type< View >::type channel_t; IplImage* img; if(( img = cvCreateImageHeader( make_cvSize( view.dimensions() ) , ipl_channel_type<channel_t>::type::value , num_channels<View>::value )) == NULL ) { throw std::runtime_error( "Cannot create IPL image." ); } cvSetData( img , &view.begin()[0] , num_channels<View>::value * view.width() * sizeof( channel_t ) ); return ipl_image_wrapper( img ); } } // namespace opencv } // namespace gil } // namespace boost #endif // BOOST_GIL_EXTENSION_OPENCV_IPL_IMAGE_WRAPPER_HPP_INCLUDED
[ "fpelliccioni@71ea4c15-5055-0410-b3ce-cda77bae7b57" ]
[ [ [ 1, 81 ] ] ]
cef16fb6db50c2622c591058bed167282cab5a5e
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlTCBSpline2.h
b3af540c9147b68532765b80b76e95c17d4d29bb
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
2,191
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLTCBSPLINE2_H #define WMLTCBSPLINE2_H #include "WmlMultipleCurve2.h" namespace Wml { template <class Real> class WML_ITEM TCBSpline2 : public MultipleCurve2<Real> { public: // Construction and destruction. TCBSpline2 accepts responsibility for // deleting the input arrays. TCBSpline2 (int iSegments, Real* afTime, Vector2<Real>* akPoint, Real* afTension, Real* afContinuity, Real* afBias); virtual ~TCBSpline2 (); const Vector2<Real>* GetPoints () const; const Real* GetTensions () const; const Real* GetContinuities () const; const Real* GetBiases () const; virtual Vector2<Real> GetPosition (Real fTime) const; virtual Vector2<Real> GetFirstDerivative (Real fTime) const; virtual Vector2<Real> GetSecondDerivative (Real fTime) const; virtual Vector2<Real> GetThirdDerivative (Real fTime) const; protected: void ComputePoly (int i0, int i1, int i2, int i3); virtual Real GetSpeedKey (int iKey, Real fTime) const; virtual Real GetLengthKey (int iKey, Real fT0, Real fT1) const; virtual Real GetVariationKey (int iKey, Real fT0, Real fT1, const Vector2<Real>& rkA, const Vector2<Real>& rkB) const; Vector2<Real>* m_akPoint; Real* m_afTension; Real* m_afContinuity; Real* m_afBias; Vector2<Real>* m_akA; Vector2<Real>* m_akB; Vector2<Real>* m_akC; Vector2<Real>* m_akD; class ThisPlusKey { public: ThisPlusKey (const TCBSpline2* pkThis, int iKey) : This(pkThis), Key(iKey) { } const TCBSpline2* This; int Key; }; }; typedef TCBSpline2<float> TCBSpline2f; typedef TCBSpline2<double> TCBSpline2d; } #endif
[ [ [ 1, 77 ] ] ]
a5e2a3335f4968a603c2c5433c87452c77b32e73
33cdd09e352529963fe8b28b04e0d2e33483777b
/trunk/ReportAsistent/AElConfigDialog.h
20add31c76abe333e170b967266640a4e13f19a1
[]
no_license
BackupTheBerlios/reportasistent-svn
20e386c86b6990abafb679eeb9205f2aef1af1ac
209650c8cbb0c72a6e8489b0346327374356b57c
refs/heads/master
2020-06-04T16:28:21.972009
2010-05-18T12:06:48
2010-05-18T12:06:48
40,804,982
0
0
null
null
null
null
UTF-8
C++
false
false
1,965
h
//AElConfigDialog.h /* This file is part of LM Report Asistent. Authors: Jan Dedek, Jan Kodym, Martin Chrz, Iva Bartunkova LM Report Asistent 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. LM Report Asistent 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 LM Report Asistent; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "afxwin.h" #include "complexfilterdialog.h" // CAElConfigDialog dialog /** * class CAElConfigDialog: This class encapsulates the Properties tab of Active Element dialog. * * @author */ class CAElConfigDialog : public CPropertyPage, CAElDataShare, CFilterResultImpl { DECLARE_DYNAMIC(CAElConfigDialog) private: BOOL m_bSourceIsInit; CComboBox m_SourcesCombo; public: CAElConfigDialog(CAElDataShare & data_share); virtual ~CAElConfigDialog(); // Dialog Data enum { IDD = IDD_AEL_CONFIG_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support BOOL LoadSource(public_source_id_t sId); void DDV_NonDuplicateID(CDataExchange *pDX, int nId, CString csIDEditValue); DECLARE_MESSAGE_MAP() public: virtual BOOL OnInitDialog(); afx_msg void OnCbnSelchangeDataSourceCombo(); afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); CString m_sIdEdit; CString m_OldID; public: afx_msg void OnEnChangeIdEdit(); public: virtual BOOL OnApply(); public: virtual BOOL OnSetActive(); };
[ "chrzm@fded5620-0c03-0410-a24c-85322fa64ba0", "dedej1am@fded5620-0c03-0410-a24c-85322fa64ba0", "ibart@fded5620-0c03-0410-a24c-85322fa64ba0" ]
[ [ [ 1, 20 ], [ 28, 28 ], [ 30, 32 ] ], [ [ 21, 27 ], [ 33, 71 ] ], [ [ 29, 29 ] ] ]
f16ecacf0db3269ac81d5fd65cc314426e0a19c8
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/math/dot_net_example/boost_math/boost_math.cpp
6287348d7371ff9a42becb4e0d313417a07913e8
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,209
cpp
// Copyright John Maddock 2007. // Copyright Paul A. Bristow 2007. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) // boost_math.cpp This is the main DLL file. //#define BOOST_MATH_OVERFLOW_ERROR_POLICY errno_on_error //#define BOOST_MATH_ASSERT_UNDEFINED_POLICY false // These are now defined in project properties // to avoid complications with pre-compiled headers: // "BOOST_MATH_ASSERT_UNDEFINED_POLICY=0" // "BOOST_MATH_OVERFLOW_ERROR_POLICY="errno_on_error"" // so command line shows: // /D "BOOST_MATH_ASSERT_UNDEFINED_POLICY=0" // /D "BOOST_MATH_OVERFLOW_ERROR_POLICY="errno_on_error"" #include "stdafx.h" #pragma warning(disable: 4400) // 'const boost_math::any_distribution ^' : const/volatile qualifiers on this type are not supported #include "boost_math.h" namespace boost_math { any_distribution::any_distribution(int t, double arg1, double arg2, double arg3) { TRANSLATE_EXCEPTIONS_BEGIN // This is where all the work gets done: switch(t) // index of distribution to distribution_info distributions[] { // New entires must match distribution names, parameter name(s) and defaults defined below. case 0: this->reset(new concrete_distribution<boost::math::bernoulli>(boost::math::bernoulli(arg1))); break; case 1: this->reset(new concrete_distribution<boost::math::beta_distribution<> >(boost::math::beta_distribution<>(arg1, arg2))); break; // Note - no typedef, so need explicit type <> but rely on default = double. case 2: this->reset(new concrete_distribution<boost::math::binomial_distribution<> >(boost::math::binomial_distribution<>(arg1, arg2))); break; // Note - no typedef, so need explicit type <> but rely on default = double. case 3: this->reset(new concrete_distribution<boost::math::cauchy>(boost::math::cauchy(arg1, arg2))); break; case 4: this->reset(new concrete_distribution<boost::math::chi_squared>(boost::math::chi_squared(arg1))); break; case 5: this->reset(new concrete_distribution<boost::math::exponential>(boost::math::exponential(arg1))); break; case 6: this->reset(new concrete_distribution<boost::math::extreme_value>(boost::math::extreme_value(arg1))); break; case 7: this->reset(new concrete_distribution<boost::math::fisher_f >(boost::math::fisher_f(arg1, arg2))); break; case 8: this->reset(new concrete_distribution<boost::math::gamma_distribution<> >(boost::math::gamma_distribution<>(arg1, arg2))); break; case 9: this->reset(new concrete_distribution<boost::math::lognormal_distribution<> >(boost::math::lognormal_distribution<>(arg1, arg2))); break; case 10: this->reset(new concrete_distribution<boost::math::negative_binomial_distribution<> >(boost::math::negative_binomial_distribution<>(arg1, arg2))); break; case 11: this->reset(new concrete_distribution<boost::math::normal_distribution<> >(boost::math::normal_distribution<>(arg1, arg2))); break; case 12: this->reset(new concrete_distribution<boost::math::pareto>(boost::math::pareto(arg1, arg2))); break; case 13: this->reset(new concrete_distribution<boost::math::poisson>(boost::math::poisson(arg1))); break; case 14: this->reset(new concrete_distribution<boost::math::rayleigh>(boost::math::rayleigh(arg1))); break; case 15: this->reset(new concrete_distribution<boost::math::students_t>(boost::math::students_t(arg1))); break; case 16: this->reset(new concrete_distribution<boost::math::triangular>(boost::math::triangular(arg1, arg2, arg3))); break; case 17: this->reset(new concrete_distribution<boost::math::uniform>(boost::math::uniform(arg1, arg2))); break; case 18: this->reset(new concrete_distribution<boost::math::weibull>(boost::math::weibull(arg1, arg2))); break; default: // TODO: // Need some proper error handling here: assert(0); } TRANSLATE_EXCEPTIONS_END } // any_distribution constructor. struct distribution_info { const char* name; // of distribution. const char* first_param; // parameters name like "degrees of freedom" const char* second_param; // if required, else "". const char* third_param; // if required, else "". // triangular need 3 parameters. // (Only the Bi-Weibull would need 5 parameters?) double first_default; // distribution parameter value, often 0, 0.5 or 1. double second_default; // 0 if there isn't a second argument. // Note that defaults below follow default argument in constructors, // if any, but need not be the same. double third_default; // 0 if there isn't a third argument. }; distribution_info distributions[] = { // distribution name, parameter name(s) and default(s) // Order must match any_distribution constructor above! // Null string "" and zero default for un-used arguments. { "Bernoulli", "Probability", "", "",0.5, 0, 0}, // case 0 { "Beta", "Alpha", "Beta", "", 1, 1, 0}, // case 1 { "Binomial", "Trials", "Probability of success", "", 1, 0.5, 0}, // case 2 { "Cauchy", "Location", "Scale", "", 0, 1, 0}, // case 3 { "Chi_squared", "Degrees of freedom", "", "", 1, 0, 0}, // case 4 { "Exponential", "lambda", "", "", 1, 0, 0}, // case 5 { "Extreme value", "Location", "Scale", "", 0, 1, 0}, // case 6 { "Fisher-F", "Degrees of freedom 1", "Degrees of freedom 2", "", 1, 1, 0}, // case 7 { "Gamma", "Shape", "Scale", "", 1, 1, }, // case 8 { "Lognormal", "Location", "Scale", "", 0, 1, 0}, // case 9 { "Negative Binomial", "Successes", "Probability of success", "", 1, 0.5, 0}, // case 10 { "Normal (Gaussian)", "Mean", "Standard Deviation", "", 0, 1, 0}, // case 11 { "Pareto", "Location", "Shape","", 1, 1, 0}, // case 12 { "Poisson", "Mean", "", "", 1, 0, 0}, // case 13 { "Rayleigh", "Sigma", "", "", 1, 0, 0}, // case 14 { "Student's t", "Degrees of Freedom", "", "", 1, 0, 0}, // case 15 { "Triangular", "Lower", "Mode", "Upper", -1, 0, +1 }, // case 16 3rd parameter! // 0, 0.5, 1 also said to 'standard' but this is most like an approximation to Gaussian distribution. { "Uniform", "Lower", "Upper", "", 0, 1, 0}, // case 17 { "Weibull", "Shape", "Scale", "", 1, 1, 0}, // case 18 }; // How many distributions are supported: int any_distribution::size() { return sizeof(distributions) / sizeof(distributions[0]); } // Display name of i'th distribution: System::String^ any_distribution::distribution_name(int i) { if(i >= size()) return ""; return gcnew System::String(distributions[i].name); } // Name of first distribution parameter, or null if not supported: System::String^ any_distribution::first_param_name(int i) { if(i >= size()) return ""; return gcnew System::String(distributions[i].first_param); } // Name of second distribution parameter, or null if not supported: System::String^ any_distribution::second_param_name(int i) { if(i >= size()) return ""; return gcnew System::String(distributions[i].second_param); } // Name of third distribution parameter, or null if not supported: System::String^ any_distribution::third_param_name(int i) { if(i >= size()) return ""; return gcnew System::String(distributions[i].third_param); } // default value for first parameter: double any_distribution::first_param_default(int i) { if(i >= size()) return 0; return distributions[i].first_default; } // default value for second parameter: double any_distribution::second_param_default(int i) { if(i >= size()) return 0; return distributions[i].second_default; } // default value for third parameter: double any_distribution::third_param_default(int i) { if(i >= size()) return 0; return distributions[i].third_default; } } // namespace boost_math
[ "metrix@Blended.(none)" ]
[ [ [ 1, 200 ] ] ]
d6cb1285456d58d96b4acdfd82761ee219124b39
00dc01cc668101fa47dccdd0c930e5a5ae1e62a3
/DirectX/DxIncludeCallback.cpp
9ed3d4aad8769472b9bdba12752dbd28d16c9252
[ "MIT" ]
permissive
jtilander/unittestcg
3f18265a4bd6bf4b1d66623ad9b1b13e9fda9512
d56910eb75c6c3d4673a3bf465ab8e21169aaec5
refs/heads/master
2021-01-25T03:40:43.035650
2008-01-15T06:45:38
2008-01-15T06:45:38
32,777,280
0
0
null
null
null
null
UTF-8
C++
false
false
1,105
cpp
#include "Precompiled.h" #include "DxIncludeCallback.h" #ifdef UNITTESTCG_ENABLE_DIRECTX #include "../FileInStream.h" #include <cstring> namespace aurora { DxIncludeCallback::DxIncludeCallback( const IncludeSet& includePaths ) : m_includePaths(includePaths) { } HRESULT STDMETHODCALLTYPE DxIncludeCallback::Open( D3DXINCLUDE_TYPE /*IncludeType*/, LPCSTR pFileName, LPCVOID /*pParentData*/, LPCVOID * ppData, UINT * pBytes) { for( IncludeSet::const_iterator it = m_includePaths.begin(); it != m_includePaths.end(); ++it ) { FileInStream stream; char buffer[512]; std::sprintf( buffer, "%s\\%s", it->c_str(), pFileName ); if( !stream.open( buffer ) ) continue; const int len = (int)stream.bytesLeft(); char** dst = (char**)ppData; *dst = new char[ len + 1 ]; stream.read( *dst, len ); (*dst)[len] = 0; *pBytes = len; return S_OK; } return E_FAIL; } HRESULT STDMETHODCALLTYPE DxIncludeCallback::Close(LPCVOID pData) { const char* pointer = (const char*)pData; delete[] pointer; return S_OK; } } #endif
[ "jim.tilander@e486c63a-db1d-0410-a17c-a9b5b17689e2" ]
[ [ [ 1, 49 ] ] ]
8cb4961b8c7422c03207942c63203bc3702fd368
cfa6cdfaba310a2fd5f89326690b5c48c6872a2a
/Temp/Kims Project1/RGBBYTE.h
fa05c19e48044547cf4647322cd6ed311cc5e9d9
[]
no_license
asdlei00/project-jb
1cc70130020a5904e0e6a46ace8944a431a358f6
0bfaa84ddab946c90245f539c1e7c2e75f65a5c0
refs/heads/master
2020-05-07T21:41:16.420207
2009-09-12T03:40:17
2009-09-12T03:40:17
40,292,178
0
0
null
null
null
null
UHC
C++
false
false
500
h
#pragma once class RGBBYTE { public: RGBBYTE(const BYTE& pixel = 0); RGBBYTE(const BYTE& _r, const BYTE& _g, const BYTE& _b); RGBBYTE(const RGBBYTE& pixel); ~RGBBYTE(void); public: BYTE b; BYTE g; BYTE r; public: //치환 연산자 오버로딩 RGBBYTE& operator= (const RGBBYTE& pixel); RGBBYTE& operator= (const COLORREF& pixel); RGBBYTE& operator= (const BYTE& pixel); int operator== (const RGBBYTE& pixel); int operator!= (const RGBBYTE& pixel); };
[ [ [ 1, 25 ] ] ]
f2eb5702d4e7c1e1b9b8f793675fbf4bb9f60d2e
b9a435b95854371395384d101c35ee640f73c779
/src/UrlHelper.h
7abbe8b34e96a5c164e952937a213f1f1833bca9
[]
no_license
jmxx/tiny
a5fd43498fe3b32fe24a4df84a970fd96b449bea
6cfa2f33089863ac222b3cebca627704583bbef9
refs/heads/master
2020-04-10T11:55:30.934859
2011-11-11T04:31:01
2011-11-11T04:31:01
2,530,793
1
0
null
null
null
null
WINDOWS-1250
C++
false
false
625
h
#ifndef URL_HELPER_H #define URL_HELPER_H #include <string> #include <map> class UrlHelper { public: UrlHelper(std::string url); static void SplitUrl (std::string const& url, std::string& protocol, std::string& server, std::string& path); static bool RemoveProtocolFromUrl(std::string const& url, std::string& protocol, std::string& rest); /* * Parse una petición GET y devuelve la ruta solicitada y los parametros. */ static void parseGetRequest(std::string et_req, std::string& path, std::map<std::string, std::string>& params); }; #endif /* URL_HELPER_H */
[ [ [ 1, 22 ] ] ]
56d3d0f2fb674fc92eaa094a70cd856fe30e1b48
ac342d97dda23af771da4f257a12a2910aed8987
/progress.cpp
2878abb0c0e6c884d81bf2ee95aa81ba2bafaea3
[]
no_license
kitech/mwget
41cfb180c67d22fe3abe67a8c1ecfb2d71d762a4
c7aafefd4061f70ec565778b313732792a276fc0
refs/heads/master
2020-05-28T13:23:32.333877
2011-11-16T03:32:21
2011-11-16T03:32:21
2,785,265
8
5
null
null
null
null
GB18030
C++
false
false
42,972
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <signal.h> #include "progress.h" struct progress_implementation { const char *name; int interactive; void *(*create) (wgint, wgint); void (*update) (void *, wgint, double); void (*finish) (void *, double); void (*set_params) (const char *); }; /* Necessary forward declarations. */ static void *dot_create (wgint, wgint); static void dot_update (void *, wgint, double); static void dot_finish (void *, double); static void dot_set_params (const char *); static void *bar_create (wgint, wgint); static void bar_update (void *, wgint, double); static void bar_finish (void *, double); static void bar_set_params (const char *); static struct progress_implementation implementations[] = { { "dot", 0, dot_create, dot_update, dot_finish, dot_set_params }, { "bar", 1, bar_create, bar_update, bar_finish, bar_set_params } }; static struct progress_implementation *current_impl; static int current_impl_locked; /* Progress implementation used by default. Can be overriden in wgetrc or by the fallback one. */ #define DEFAULT_PROGRESS_IMPLEMENTATION "bar" /* Fallnback progress implementation should be something that works under all display types. If you put something other than "dot" here, remember that bar_set_params tries to switch to this if we're not running on a TTY. So changing this to "bar" could cause infloop. */ #define FALLBACK_PROGRESS_IMPLEMENTATION "dot" /* Return non-zero if NAME names a valid progress bar implementation. The characters after the first : will be ignored. */ int valid_progress_implementation_p (const char *name) { int i; struct progress_implementation *pi = implementations; char *colon = strchr (name, ':'); int namelen = colon ? colon - name : strlen (name); for (i = 0; i < countof (implementations); i++, pi++) if (!strncmp (pi->name, name, namelen)) return 1; return 0; } /* Set the progress implementation to NAME. */ void set_progress_implementation (const char *name) { int i, namelen; struct progress_implementation *pi = implementations; char *colon; if (!name) name = DEFAULT_PROGRESS_IMPLEMENTATION; colon = strchr (name, ':'); namelen = colon ? colon - name : strlen (name); for (i = 0; i < countof (implementations); i++, pi++) if (!strncmp (pi->name, name, namelen)) { current_impl = pi; current_impl_locked = 0; if (colon) /* We call pi->set_params even if colon is NULL because we want to give the implementation a chance to set up some things it needs to run. */ ++colon; if (pi->set_params) pi->set_params (colon); return; } abort (); } static int output_redirected; void progress_schedule_redirect (void) { output_redirected = 1; } /* Create a progress gauge. INITIAL is the number of bytes the download starts from (zero if the download starts from scratch). TOTAL is the expected total number of bytes in this download. If TOTAL is zero, it means that the download size is not known in advance. */ void * progress_create (wgint initial, wgint total) { /* Check if the log status has changed under our feet. */ if (output_redirected) { if (!current_impl_locked) set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION); output_redirected = 0; } return current_impl->create (initial, total); } /* Return non-zero if the progress gauge is "interactive", i.e. if it can profit from being called regularly even in absence of data. The progress bar is interactive because it regularly updates the ETA and current update. */ int progress_interactive_p (void *progress) { return current_impl->interactive; } /* Inform the progress gauge of newly received bytes. DLTIME is the time in milliseconds since the beginning of the download. */ void progress_update (void *progress, wgint howmuch, double dltime) { current_impl->update (progress, howmuch, dltime); } /* Tell the progress gauge to clean up. Calling this will free the PROGRESS object, the further use of which is not allowed. */ void progress_finish (void *progress, double dltime) { current_impl->finish (progress, dltime); } /* Dot-printing. */ struct dot_progress { wgint initial_length; /* how many bytes have been downloaded previously. */ wgint total_length; /* expected total byte count when the download finishes */ int accumulated; int rows; /* number of rows printed so far */ int dots; /* number of dots printed in this row */ double last_timer_value; }; /* Dot-progress backend for progress_create. */ static void * dot_create (wgint initial, wgint total) { struct dot_progress *dp = (struct dot_progress*)malloc (sizeof(struct dot_progress)); memset(dp,0,sizeof(struct dot_progress)); dp->initial_length = initial; dp->total_length = total; if (dp->initial_length) { int dot_bytes = 1000;//opt.dot_bytes; wgint row_bytes = 100000;//opt.dot_bytes * opt.dots_in_line; int remainder = (int) (dp->initial_length % row_bytes); wgint skipped = dp->initial_length - remainder; if (skipped) { int skipped_k = (int) (skipped / 1024); /* skipped amount in K */ int skipped_k_len = 3;//numdigit (skipped_k); if (skipped_k_len < 5) skipped_k_len = 5; /* Align the [ skipping ... ] line with the dots. To do that, insert the number of spaces equal to the number of digits in the skipped amount in K. */ fprintf (stderr, "\n%*s[ skipping %dK ]", 2 + skipped_k_len, skipped_k); } fprintf (stderr, "\n%5ldK", (long) (skipped / 1024)); for (; remainder >= dot_bytes; remainder -= dot_bytes) { //if (dp->dots % opt.dot_spacing == 0) if (dp->dots % 3 == 0) fprintf (stderr, " "); fprintf (stderr,","); ++dp->dots; } //assert (dp->dots < opt.dots_in_line); assert (dp->dots < 1000 ); dp->accumulated = remainder; dp->rows = skipped / row_bytes; } return dp; } static void print_percentage (wgint bytes, wgint expected) { int percentage = (int)(100.0 * bytes / expected); fprintf (stderr, "%3d%%", percentage); } static void print_download_speed (struct dot_progress *dp, wgint bytes, double dltime) { fprintf (stderr, " %s", // retr_rate (bytes, dltime - dp->last_timer_value, 1)); " 2.0K/S"); dp->last_timer_value = dltime; } /* Dot-progress backend for progress_update. */ static void dot_update (void *progress, wgint howmuch, double dltime) { struct dot_progress *dp = (struct dot_progress *)progress; int dot_bytes = 1000;//opt.dot_bytes; wgint row_bytes = 100000;//opt.dot_bytes * opt.dots_in_line; //log_set_flush (0); dp->accumulated += howmuch; for (; dp->accumulated >= dot_bytes; dp->accumulated -= dot_bytes) { if (dp->dots == 0) fprintf (stderr, "\n%5ldK", (long) (dp->rows * row_bytes / 1024)); // if (dp->dots % opt.dot_spacing == 0) if (dp->dots % 3 == 0) fprintf (stderr, " "); fprintf (stderr, "."); ++dp->dots; // if (dp->dots >= opt.dots_in_line) if (dp->dots >= 1000) { wgint row_qty = row_bytes; if (dp->rows == dp->initial_length / row_bytes) row_qty -= dp->initial_length % row_bytes; ++dp->rows; dp->dots = 0; if (dp->total_length) print_percentage (dp->rows * row_bytes, dp->total_length); print_download_speed (dp, row_qty, dltime); } } //log_set_flush (1); } /* Dot-progress backend for progress_finish. */ static void dot_finish (void *progress, double dltime) { struct dot_progress *dp = (struct dot_progress *)progress; int dot_bytes = 1000;//opt.dot_bytes; wgint row_bytes = 100000;//opt.dot_bytes * opt.dots_in_line; int i; //log_set_flush (0); if (dp->dots == 0) fprintf (stderr, "\n%5ldK", (long) (dp->rows * row_bytes / 1024)); for (i = dp->dots; i < 1000; i++) { if (i % 3 == 0) fprintf (stderr, " "); fprintf (stderr, " "); } if (dp->total_length) { print_percentage (dp->rows * row_bytes + dp->dots * dot_bytes + dp->accumulated, dp->total_length); } { wgint row_qty = dp->dots * dot_bytes + dp->accumulated; if (dp->rows == dp->initial_length / row_bytes) row_qty -= dp->initial_length % row_bytes; print_download_speed (dp, row_qty, dltime); } fprintf (stderr, "\n\n"); //log_set_flush (0); free (dp); } /* This function interprets the progress "parameters". For example, if Wget is invoked with --progress=dot:mega, it will set the "dot-style" to "mega". Valid styles are default, binary, mega, and giga. */ static void dot_set_params (const char *params) { if (!params || !*params) params = "aa";//opt.dot_style; if (!params) return; /* We use this to set the retrieval style. */ if (!strcasecmp (params, "default")) { /* Default style: 1K dots, 10 dots in a cluster, 50 dots in a line. */ //opt.dot_bytes = 1024; //opt.dot_spacing = 10; //opt.dots_in_line = 50; } else if (!strcasecmp (params, "binary")) { /* "Binary" retrieval: 8K dots, 16 dots in a cluster, 48 dots (384K) in a line. */ //opt.dot_bytes = 8192; //opt.dot_spacing = 16; //opt.dots_in_line = 48; } else if (!strcasecmp (params, "mega")) { /* "Mega" retrieval, for retrieving very long files; each dot is 64K, 8 dots in a cluster, 6 clusters (3M) in a line. */ //opt.dot_bytes = 65536L; //opt.dot_spacing = 8; //opt.dots_in_line = 48; } else if (!strcasecmp (params, "giga")) { /* "Giga" retrieval, for retrieving very very *very* long files; each dot is 1M, 8 dots in a cluster, 4 clusters (32M) in a line. */ //opt.dot_bytes = (1L << 20); //opt.dot_spacing = 8; //opt.dots_in_line = 32; } else fprintf (stderr, "Invalid dot style specification `%s'; leaving unchanged.\n", params); } /* "Thermometer" (bar) progress. */ /* Assumed screen width if we can't find the real value. */ #define DEFAULT_SCREEN_WIDTH 80 /* Minimum screen width we'll try to work with. If this is too small, create_image will overflow the buffer. */ #define MINIMUM_SCREEN_WIDTH 45 /* The last known screen width. This can be updated by the code that detects that SIGWINCH was received (but it's never updated from the signal handler). */ static int screen_width; /* A flag that, when set, means SIGWINCH was received. */ static volatile sig_atomic_t received_sigwinch; /* Size of the download speed history ring. */ #define DLSPEED_HISTORY_SIZE 20 /* The minimum time length of a history sample. By default, each sample is at least 150ms long, which means that, over the course of 20 samples, "current" download speed spans at least 3s into the past. */ #define DLSPEED_SAMPLE_MIN 150 /* The time after which the download starts to be considered "stalled", i.e. the current bandwidth is not printed and the recent download speeds are scratched. */ #define STALL_START_TIME 5000 struct bar_progress_hist { int pos; wgint times[DLSPEED_HISTORY_SIZE]; wgint bytes[DLSPEED_HISTORY_SIZE]; /* The sum of times and bytes respectively, maintained for efficiency. */ wgint total_time; wgint total_bytes; } ; struct bar_progress { wgint initial_length; /* how many bytes have been downloaded previously. */ wgint total_length; /* expected total byte count when the download finishes */ wgint count; /* bytes downloaded so far */ double last_screen_update; /* time of the last screen update, measured since the beginning of download. */ int width; /* screen width we're using at the time the progress gauge was created. this is different from the screen_width global variable in that the latter can be changed by a signal. */ char *buffer; /* buffer where the bar "image" is stored. */ int tick; /* counter used for drawing the progress bar where the total size is not known. */ /* The following variables (kept in a struct for namespace reasons) keep track of recent download speeds. See bar_update() for details. */ struct bar_progress_hist hist; double recent_start; /* timestamp of beginning of current position. */ wgint recent_bytes; /* bytes downloaded so far. */ int stalled; /* set when no data arrives for longer than STALL_START_TIME, then reset when new data arrives. */ /* create_image() uses these to make sure that ETA information doesn't flicker. */ double last_eta_time; /* time of the last update to download speed and ETA, measured since the beginning of download. */ wgint last_eta_value; }; static void create_image (struct bar_progress *, double); static void display_image (char *); /* Determine the width of the terminal we're running on. If that's not possible, return 0. */ int determine_screen_width (void) { /* If there's a way to get the terminal size using POSIX tcgetattr(), somebody please tell me. */ #ifdef TIOCGWINSZ int fd; struct winsize wsz; if (opt.lfilename != NULL) return 0; fd = fileno (stderr); if (ioctl (fd, TIOCGWINSZ, &wsz) < 0) return 0; /* most likely ENOTTY */ return wsz.ws_col; #else /* not TIOCGWINSZ */ # ifdef WINDOWS CONSOLE_SCREEN_BUFFER_INFO csbi; if (!GetConsoleScreenBufferInfo (GetStdHandle (STD_ERROR_HANDLE), &csbi)) return 0; return csbi.dwSize.X; # else /* neither WINDOWS nor TIOCGWINSZ */ return 0; #endif /* neither WINDOWS nor TIOCGWINSZ */ #endif /* not TIOCGWINSZ */ } static void * bar_create (wgint initial, wgint total) { struct bar_progress *bp = (struct bar_progress*) malloc(sizeof(struct bar_progress)); /* In theory, our callers should take care of this pathological case, but it can sometimes happen. */ if (initial > total) total = initial; bp->initial_length = initial; bp->total_length = total; /* Initialize screen_width if this hasn't been done or if it might have changed, as indicated by receiving SIGWINCH. */ if (!screen_width || received_sigwinch) { screen_width = determine_screen_width (); if (!screen_width) screen_width = DEFAULT_SCREEN_WIDTH; else if (screen_width < MINIMUM_SCREEN_WIDTH) screen_width = MINIMUM_SCREEN_WIDTH; received_sigwinch = 0; } /* - 1 because we don't want to use the last screen column. */ bp->width = screen_width - 1; /* + 1 for the terminating zero. */ bp->buffer = (char*)malloc (bp->width + 1); fprintf(stderr, "\n"); create_image (bp, 0.0); display_image (bp->buffer); return bp; } static void update_speed_ring (struct bar_progress *, wgint, double); static void bar_update (void *progress, wgint howmuch, double dltime) { struct bar_progress *bp = (struct bar_progress*) progress; int force_screen_update = 0; bp->count += howmuch; if (bp->total_length > 0 && bp->count + bp->initial_length > bp->total_length) /* We could be downloading more than total_length, e.g. when the server sends an incorrect Content-Length header. In that case, adjust bp->total_length to the new reality, so that the code in create_image() that depends on total size being smaller or equal to the expected size doesn't abort. */ bp->total_length = bp->initial_length + bp->count; update_speed_ring (bp, howmuch, dltime); /* If SIGWINCH (the window size change signal) been received, determine the new screen size and update the screen. */ if (received_sigwinch) { int old_width = screen_width; screen_width = determine_screen_width (); if (!screen_width) screen_width = DEFAULT_SCREEN_WIDTH; else if (screen_width < MINIMUM_SCREEN_WIDTH) screen_width = MINIMUM_SCREEN_WIDTH; if (screen_width != old_width) { bp->width = screen_width - 1; bp->buffer = (char*)realloc (bp->buffer, bp->width + 1); force_screen_update = 1; } received_sigwinch = 0; } if (dltime - bp->last_screen_update < 200 && !force_screen_update) /* Don't update more often than five times per second. */ return; create_image (bp, dltime); display_image (bp->buffer); bp->last_screen_update = dltime; } static void bar_finish (void *progress, double dltime) { struct bar_progress *bp = (struct bar_progress*) progress; if (bp->total_length > 0 && bp->count + bp->initial_length > bp->total_length) /* See bar_update() for explanation. */ bp->total_length = bp->initial_length + bp->count; create_image (bp, dltime); display_image (bp->buffer); fprintf(stderr, "\n\n"); free (bp->buffer); free (bp); } /* This code attempts to maintain the notion of a "current" download speed, over the course of no less than 3s. (Shorter intervals produce very erratic results.) To do so, it samples the speed in 150ms intervals and stores the recorded samples in a FIFO history ring. The ring stores no more than 20 intervals, hence the history covers the period of at least three seconds and at most 20 reads into the past. This method should produce reasonable results for downloads ranging from very slow to very fast. The idea is that for fast downloads, we get the speed over exactly the last three seconds. For slow downloads (where a network read takes more than 150ms to complete), we get the speed over a larger time period, as large as it takes to complete thirty reads. This is good because slow downloads tend to fluctuate more and a 3-second average would be too erratic. */ #define xzero(x) memset (&(x), '\0', sizeof (x)) static void update_speed_ring (struct bar_progress *bp, wgint howmuch, double dltime) { struct bar_progress_hist *hist = &bp->hist; double recent_age = dltime - bp->recent_start; /* Update the download count. */ bp->recent_bytes += howmuch; /* For very small time intervals, we return after having updated the "recent" download count. When its age reaches or exceeds minimum sample time, it will be recorded in the history ring. */ if (recent_age < DLSPEED_SAMPLE_MIN) return; if (howmuch == 0) { /* If we're not downloading anything, we might be stalling, i.e. not downloading anything for an extended period of time. Since 0-reads do not enter the history ring, recent_age effectively measures the time since last read. */ if (recent_age >= STALL_START_TIME) { /* If we're stalling, reset the ring contents because it's stale and because it will make bar_update stop printing the (bogus) current bandwidth. */ bp->stalled = 1; xzero (*hist); bp->recent_bytes = 0; } return; } /* We now have a non-zero amount of to store to the speed ring. */ /* If the stall status was acquired, reset it. */ if (bp->stalled) { bp->stalled = 0; /* "recent_age" includes the the entired stalled period, which could be very long. Don't update the speed ring with that value because the current bandwidth would start too small. Start with an arbitrary (but more reasonable) time value and let it level out. */ recent_age = 1000; } /* Store "recent" bytes and download time to history ring at the position POS. */ /* To correctly maintain the totals, first invalidate existing data (least recent in time) at this position. */ hist->total_time -= hist->times[hist->pos]; hist->total_bytes -= hist->bytes[hist->pos]; /* Now store the new data and update the totals. */ hist->times[hist->pos] = (long int)recent_age; hist->bytes[hist->pos] = bp->recent_bytes; hist->total_time += (long int)recent_age; hist->total_bytes += bp->recent_bytes; /* Start a new "recent" period. */ bp->recent_start = dltime; bp->recent_bytes = 0; /* Advance the current ring position. */ if (++hist->pos == DLSPEED_HISTORY_SIZE) hist->pos = 0; #if 0 /* Sledgehammer check to verify that the totals are accurate. */ { int i; double sumt = 0, sumb = 0; for (i = 0; i < DLSPEED_HISTORY_SIZE; i++) { sumt += hist->times[i]; sumb += hist->bytes[i]; } assert (sumt == hist->total_time); assert (sumb == hist->total_bytes); } #endif } #define APPEND_LITERAL(s) do { \ memcpy (p, s, sizeof (s) - 1); \ p += sizeof (s) - 1; \ } while (0) #ifndef MAX # define MAX(a, b) ((a) >= (b) ? (a) : (b)) #endif /* Return a static pointer to the number printed with thousand separators inserted at the right places. */ /* Shorthand for casting to wgint. */ #define W wgint /* SPRINTF_WGINT is used by number_to_string to handle pathological cases and to portably support strange sizes of wgint. Ideally this would just use "%j" and intmax_t, but many systems don't support it, so it's used only if nothing else works. */ #if SIZEOF_LONG >= SIZEOF_WGINT # define SPRINTF_WGINT(buf, n) sprintf (buf, "%ld", (long) (n)) #else # if SIZEOF_LONG_LONG >= SIZEOF_WGINT # define SPRINTF_WGINT(buf, n) sprintf (buf, "%lld", (long long) (n)) # else # ifdef WINDOWS # define SPRINTF_WGINT(buf, n) sprintf (buf, "%I64", (__int64) (n)) # else # define SPRINTF_WGINT(buf, n) sprintf (buf, "%j", (intmax_t) (n)) # endif # endif #endif /* Print NUMBER to BUFFER in base 10. This is equivalent to `sprintf(buffer, "%lld", (long long) number)', only typically much faster and portable to machines without long long. The speedup may make a difference in programs that frequently convert numbers to strings. Some implementations of sprintf, particularly the one in GNU libc, have been known to be extremely slow when converting integers to strings. Return the pointer to the location where the terminating zero was printed. (Equivalent to calling buffer+strlen(buffer) after the function is done.) BUFFER should be big enough to accept as many bytes as you expect the number to take up. On machines with 64-bit longs the maximum needed size is 24 bytes. That includes the digits needed for the largest 64-bit number, the `-' sign in case it's negative, and the terminating '\0'. */ /* Add thousand separators to a number already in string form. Used by with_thousand_seps and with_thousand_seps_large. */ static char * add_thousand_seps (const char *repr) { static char outbuf[48]; int i, i1, mod; char *outptr; const char *inptr; /* Reset the pointers. */ outptr = outbuf; inptr = repr; /* Ignore the sign for the purpose of adding thousand separators. */ if (*inptr == '-') { *outptr++ = '-'; ++inptr; } /* How many digits before the first separator? */ mod = strlen (inptr) % 3; /* Insert them. */ for (i = 0; i < mod; i++) *outptr++ = inptr[i]; /* Now insert the rest of them, putting separator before every third digit. */ for (i1 = i, i = 0; inptr[i1]; i++, i1++) { if (i % 3 == 0 && i1 != 0) *outptr++ = ','; *outptr++ = inptr[i1]; } /* Zero-terminate the string. */ *outptr = '\0'; return outbuf; } char * number_to_string (char *buffer, wgint number) { char *p = buffer; wgint n = number; #if (SIZEOF_WGINT != 4) && (SIZEOF_WGINT != 8) /* We are running in a strange or misconfigured environment. Let sprintf cope with it. */ SPRINTF_WGINT (buffer, n); p += strlen (buffer); #else /* (SIZEOF_WGINT == 4) || (SIZEOF_WGINT == 8) */ if (n < 0) { if (n < -WGINT_MAX) { /* -n would overflow. Have sprintf deal with this. */ SPRINTF_WGINT (buffer, n); p += strlen (buffer); return p; } *p++ = '-'; n = -n; } /* Use the DIGITS_ macro appropriate for N's number of digits. That way printing any N is fully open-coded without a loop or jump. (Also see description of DIGITS_*.) */ if (n < 10) DIGITS_1 (1); else if (n < 100) DIGITS_2 (10); else if (n < 1000) DIGITS_3 (100); else if (n < 10000) DIGITS_4 (1000); else if (n < 100000) DIGITS_5 (10000); else if (n < 1000000) DIGITS_6 (100000); else if (n < 10000000) DIGITS_7 (1000000); else if (n < 100000000) DIGITS_8 (10000000); else if (n < 1000000000) DIGITS_9 (100000000); #if SIZEOF_WGINT == 4 /* wgint is 32 bits wide: no number has more than 10 digits. */ else DIGITS_10 (1000000000); #else /* wgint is 64 bits wide: handle numbers with more than 9 decimal digits. Constants are constructed by compile-time multiplication to avoid dealing with different notations for 64-bit constants (nnnL, nnnLL, and nnnI64, depending on the compiler). */ else if (n < 10*(W)1000000000) DIGITS_10 (1000000000); else if (n < 100*(W)1000000000) DIGITS_11 (10*(W)1000000000); else if (n < 1000*(W)1000000000) DIGITS_12 (100*(W)1000000000); else if (n < 10000*(W)1000000000) DIGITS_13 (1000*(W)1000000000); else if (n < 100000*(W)1000000000) DIGITS_14 (10000*(W)1000000000); else if (n < 1000000*(W)1000000000) DIGITS_15 (100000*(W)1000000000); else if (n < 10000000*(W)1000000000) DIGITS_16 (1000000*(W)1000000000); else if (n < 100000000*(W)1000000000) DIGITS_17 (10000000*(W)1000000000); else if (n < 1000000000*(W)1000000000) DIGITS_18 (100000000*(W)1000000000); else DIGITS_19 (1000000000*(W)1000000000); #endif *p = '\0'; #endif /* (SIZEOF_WGINT == 4) || (SIZEOF_WGINT == 8) */ return p; } char * with_thousand_seps (wgint l) { char inbuf[24]; /* Print the number into the buffer. */ number_to_string (inbuf, l); return add_thousand_seps (inbuf); } static void create_image (struct bar_progress *bp, double dl_total_time) { char *p = bp->buffer; wgint size = bp->initial_length + bp->count; char *size_legible = with_thousand_seps (size); int size_legible_len = strlen (size_legible); struct bar_progress_hist *hist = &bp->hist; /* The progress bar should look like this: xx% [=======> ] nn,nnn 12.34K/s ETA 00:00 Calculate the geometry. The idea is to assign as much room as possible to the progress bar. The other idea is to never let things "jitter", i.e. pad elements that vary in size so that their variance does not affect the placement of other elements. It would be especially bad for the progress bar to be resized randomly. "xx% " or "100%" - percentage - 4 chars "[]" - progress bar decorations - 2 chars " nnn,nnn,nnn" - downloaded bytes - 12 chars or very rarely more " 1012.56K/s" - dl rate - 11 chars " ETA xx:xx:xx" - ETA - 13 chars "=====>..." - progress bar - the rest */ int dlbytes_size = 1 + MAX (size_legible_len, 11); int progress_size = bp->width - (4 + 2 + dlbytes_size + 11 + 13); if (progress_size < 5) progress_size = 0; /* "xx% " */ if (bp->total_length > 0) { int percentage = (int)(100.0 * size / bp->total_length); assert (percentage <= 100); if (percentage < 100) sprintf (p, "%2d%% ", percentage); else strcpy (p, "100%"); p += 4; } else APPEND_LITERAL (" "); /* The progress bar: "[====> ]" or "[++==> ]". */ if (progress_size && bp->total_length > 0) { /* Size of the initial portion. */ int insz = (int)((double)bp->initial_length / bp->total_length * progress_size ) ; /* Size of the downloaded portion. */ int dlsz = (int)((double)size / bp->total_length * progress_size) ; char *begin; int i; assert (dlsz <= progress_size); assert (insz <= dlsz); *p++ = '['; begin = p; /* Print the initial portion of the download with '+' chars, the rest with '=' and one '>'. */ for (i = 0; i < insz; i++) *p++ = '+'; dlsz -= insz; if (dlsz > 0) { for (i = 0; i < dlsz - 1; i++) *p++ = '='; *p++ = '>'; } while (p - begin < progress_size) *p++ = ' '; *p++ = ']'; } else if (progress_size) { /* If we can't draw a real progress bar, then at least show *something* to the user. */ int ind = bp->tick % (progress_size * 2 - 6); int i, pos; /* Make the star move in two directions. */ if (ind < progress_size - 2) pos = ind + 1; else pos = progress_size - (ind - progress_size + 5); *p++ = '['; for (i = 0; i < progress_size; i++) { if (i == pos - 1) *p++ = '<'; else if (i == pos ) *p++ = '='; else if (i == pos + 1) *p++ = '>'; else *p++ = ' '; } *p++ = ']'; ++bp->tick; } /* " 234,567,890" */ sprintf (p, " %-11s", with_thousand_seps (size)); p += strlen (p); /* " 1012.45K/s" */ if (hist->total_time && hist->total_bytes) { static const char *short_units[] = { "B/s", "K/s", "M/s", "G/s" }; int units = 0; /* Calculate the download speed using the history ring and recent data that hasn't made it to the ring yet. */ wgint dlquant = hist->total_bytes + bp->recent_bytes; double dltime = hist->total_time + (dl_total_time - bp->recent_start); double dlspeed = 11.11;//calc_rate (dlquant, dltime, &units); sprintf (p, " %7.2f%s", dlspeed, short_units[units]); p += strlen (p); } else APPEND_LITERAL (" --.--K/s"); /* " ETA xx:xx:xx"; wait for three seconds before displaying the ETA. That's because the ETA value needs a while to become reliable. */ if (bp->total_length > 0 && bp->count > 0 && dl_total_time > 3000) { wgint eta; int eta_hrs, eta_min, eta_sec; /* Don't change the value of ETA more than approximately once per second; doing so would cause flashing without providing any value to the user. */ if (bp->total_length != size && bp->last_eta_value != 0 && dl_total_time - bp->last_eta_time < 900) eta = bp->last_eta_value; else { /* Calculate ETA using the average download speed to predict the future speed. If you want to use a speed averaged over a more recent period, replace dl_total_time with hist->total_time and bp->count with hist->total_bytes. I found that doing that results in a very jerky and ultimately unreliable ETA. */ double time_sofar = (double)dl_total_time / 1000; wgint bytes_remaining = bp->total_length - size; eta = (wgint) (time_sofar * bytes_remaining / bp->count); bp->last_eta_value = eta; bp->last_eta_time = dl_total_time; } eta_hrs = eta / 3600, eta %= 3600; eta_min = eta / 60, eta %= 60; eta_sec = eta; if (eta_hrs > 99) goto no_eta; if (eta_hrs == 0) { /* Hours not printed: pad with three spaces. */ APPEND_LITERAL (" "); sprintf (p, " ETA %02d:%02d", eta_min, eta_sec); } else { if (eta_hrs < 10) /* Hours printed with one digit: pad with one space. */ *p++ = ' '; sprintf (p, " ETA %d:%02d:%02d", eta_hrs, eta_min, eta_sec); } p += strlen (p); } else if (bp->total_length > 0) { no_eta: APPEND_LITERAL (" "); } assert (p - bp->buffer <= bp->width); while (p < bp->buffer + bp->width) *p++ = ' '; *p = '\0'; } /* Print the contents of the buffer as a one-line ASCII "image" so that it can be overwritten next time. */ static void display_image (char *buf) { int old = 3;//log_set_save_context (0); fprintf(stderr, "\r"); fprintf(stderr, buf); //log_set_save_context (old); } static void bar_set_params (const char *params) { char *term = getenv ("TERM"); if (params && 0 == strcmp (params, "force")) current_impl_locked = 1; // if ((opt.lfilename if ((true #ifdef HAVE_ISATTY /* The progress bar doesn't make sense if the output is not a TTY -- when logging to file, it is better to review the dots. */ || !isatty (fileno (stderr)) #endif /* Normally we don't depend on terminal type because the progress bar only uses ^M to move the cursor to the beginning of line, which works even on dumb terminals. But Jamie Zawinski reports that ^M and ^H tricks don't work in Emacs shell buffers, and only make a mess. */ || (term && 0 == strcmp (term, "emacs")) ) && !current_impl_locked) { /* We're not printing to a TTY, so revert to the fallback display. #### We're recursively calling set_progress_implementation here, which is slightly kludgy. It would be nicer if we provided that function a return value indicating a failure of some sort. */ set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION); return; } } #ifdef SIGWINCH void progress_handle_sigwinch (int sig) { received_sigwinch = 1; signal (SIGWINCH, progress_handle_sigwinch); } #endif ProgressBar *ProgressBar::mPBar = 0 ; ProgressBar::ProgressBar() { //mMsgOutMutex = PTHREAD_MUTEX_INITIALIZER ; pthread_mutex_init(&mMsgOutMutex, 0); //trace(TRACE_IEVENT|TRACE_CALLS); initscr(); keypad(stdscr,true); nonl(); cbreak(); noecho(); if(has_colors()) { start_color(); //初始化颜色配对表 init_pair(-1,-1,COLOR_BLUE); init_pair(0,COLOR_BLACK,COLOR_BLUE); init_pair(1,COLOR_GREEN,COLOR_BLUE); init_pair(2,COLOR_RED,COLOR_BLUE); init_pair(3,COLOR_CYAN,COLOR_BLUE); init_pair(4,COLOR_WHITE,COLOR_BLUE); init_pair(5,COLOR_MAGENTA,COLOR_BLUE); init_pair(6,COLOR_BLUE,COLOR_BLUE); init_pair(7,COLOR_YELLOW,COLOR_BLUE); init_pair(8,COLOR_RED,COLOR_YELLOW); init_pair(9,COLOR_MAGENTA,COLOR_CYAN); init_pair(10,COLOR_BLACK,COLOR_GREEN); init_pair(11,COLOR_WHITE,COLOR_YELLOW ); } assume_default_colors(-1,-1); //attron(A_BLINK|COLOR_PAIR(7)); //attrset(COLOR_PAIR(7)); bkgdset(COLOR_PAIR(4)); erase(); //addstr("dsfsdf"); wborder(stdscr , '|' , '|' , '=' , '=', '/' , '\\', '\\' , '/'); curs_set(0); refresh(); mCurrMsgLine = LINES - 5 ; mBarBeginRow = 1 ; mBarHeight = LINES / 2 ; mMsgBeginRow = 1+ mBarHeight + 1 ; mMsgHeight = LINES - 1 * 2 - mBarHeight - 1; } ProgressBar::~ProgressBar() { endwin(); ProgressBar::mPBar = 0 ; } ProgressBar * ProgressBar::Instance() { if( ProgressBar::mPBar == 0 ) { ProgressBar::mPBar = new ProgressBar(); } return ProgressBar::mPBar; } bool ProgressBar::Message(const char * msg) { int cr = mMsgBeginRow ; if( msg != 0 ) { mMsgLists.insert(mMsgLists.begin(),std::string(msg)); } if( mMsgLists.size() > mMsgHeight ) { mMsgLists.resize(mMsgHeight); } pthread_mutex_lock( & mMsgOutMutex ) ; std::vector<std::string>::iterator it = mMsgLists.end()-1; for( ; it >= mMsgLists.begin() ; it -- ,cr++) { move(cr,2); clrtoeol(); addstr(it->c_str() ); //mvwaddstr( stdscr , cr , 2 , it->c_str() ) ; } //clrtobot() ; wrefresh(stdscr); pthread_mutex_unlock( & mMsgOutMutex ) ; return true ; /* pthread_mutex_lock( &mMsgOutMutex); move(mCurrMsgLine,1); clrtoeol(); addstr(msg); refresh(); pthread_mutex_unlock( &mMsgOutMutex); return true; */ } bool ProgressBar::Progress(int no,const char * barstr) { pthread_mutex_lock( &mMsgOutMutex); move(no+1,1); clrtoeol(); addstr(barstr); refresh(); pthread_mutex_unlock(& mMsgOutMutex); return true; } void ProgressBar::CreateBarImage(char *barstr , long total , long got , long dltime ) { char *p = barstr ; int size = got ; char sizestr[24] ={ 0} ; char * size_legible = number_to_string( sizestr , size ) ; int size_legible_len = strlen (size_legible); /* The progress bar should look like this: xx% [=======> ] nn,nnn 12.34K/s ETA 00:00 Calculate the geometry. The idea is to assign as much room as possible to the progress bar. The other idea is to never let things "jitter", i.e. pad elements that vary in size so that their variance does not affect the placement of other elements. It would be especially bad for the progress bar to be resized randomly. "xx% " or "100%" - percentage - 4 chars "[]" - progress bar decorations - 2 chars " nnn,nnn,nnn" - downloaded bytes - 12 chars or very rarely more " 1012.56K/s" - dl rate - 11 chars " ETA xx:xx:xx" - ETA - 13 chars "=====>..." - progress bar - the rest */ int dlbytes_size = 1 + MAX (size_legible_len, 11); int progress_size = LINES -2 - (4 + 2 + dlbytes_size + 11 + 13); if (progress_size < 5) progress_size = 0; /* "xx% " */ if (total > 0) { int percentage = (int)(100.0 * size / total ); assert (percentage <= 100); if (percentage < 100) sprintf (p, "%2d%% ", percentage); else strcpy (p, "100%"); p += 4; } else APPEND_LITERAL (" "); /* The progress bar: "[====> ]" or "[++==> ]". */ if (progress_size && total > 0) { /* Size of the initial portion. */ int insz = (int)((double)got / total * progress_size ) ; /* Size of the downloaded portion. */ int dlsz = (int)((double)size / total * progress_size) ; char *begin; int i; assert (dlsz <= progress_size); assert (insz <= dlsz); *p++ = '['; begin = p; /* Print the initial portion of the download with '+' chars, the rest with '=' and one '>'. */ for (i = 0; i < insz; i++) *p++ = '+'; dlsz -= insz; if (dlsz > 0) { for (i = 0; i < dlsz - 1; i++) *p++ = '='; *p++ = '>'; } while (p - begin < progress_size) *p++ = ' '; *p++ = ']'; } else if (progress_size) { /* If we can't draw a real progress bar, then at least show *something* to the user. */ int ind = 70 % (progress_size * 2 - 6); int i, pos; /* Make the star move in two directions. */ if (ind < progress_size - 2) pos = ind + 1; else pos = progress_size - (ind - progress_size + 5); *p++ = '['; for (i = 0; i < progress_size; i++) { if (i == pos - 1) *p++ = '<'; else if (i == pos ) *p++ = '='; else if (i == pos + 1) *p++ = '>'; else *p++ = ' '; } *p++ = ']'; //++70; } /* " 234,567,890" */ sprintf (p, " %-11s", with_thousand_seps (size)); p += strlen (p); /* " 1012.45K/s" */ if ( dltime && total ) { static const char *short_units[] = { "B/s", "K/s", "M/s", "G/s" }; int units = 0; /* Calculate the download speed using the history ring and recent data that hasn't made it to the ring yet. */ int dlquant = total + got ; double dltime = dltime ; double dlspeed = 11.11;//calc_rate (dlquant, dltime, &units); sprintf (p, " %7.2f%s", dlspeed, short_units[units]); p += strlen (p); } else APPEND_LITERAL (" --.--K/s"); /* " ETA xx:xx:xx"; wait for three seconds before displaying the ETA. That's because the ETA value needs a while to become reliable. */ if (total> 0 && dltime > 3000) { int eta; int eta_hrs, eta_min, eta_sec; /* Don't change the value of ETA more than approximately once per second; doing so would cause flashing without providing any value to the user. */ if ( total != size ) eta = 50 ; else { /* Calculate ETA using the average download speed to predict the future speed. If you want to use a speed averaged over a more recent period, replace dl_total_time with hist->total_time and bp->count with hist->total_bytes. I found that doing that results in a very jerky and ultimately unreliable ETA. */ double time_sofar = (double)dltime / 1000; int bytes_remaining = total - size; eta = (int) (time_sofar * bytes_remaining / 6); } eta_hrs = eta / 3600, eta %= 3600; eta_min = eta / 60, eta %= 60; eta_sec = eta; if (eta_hrs > 99) goto no_eta; if (eta_hrs == 0) { /* Hours not printed: pad with three spaces. */ APPEND_LITERAL (" "); sprintf (p, " ETA %02d:%02d", eta_min, eta_sec); } else { if (eta_hrs < 10) /* Hours printed with one digit: pad with one space. */ *p++ = ' '; sprintf (p, " ETA %d:%02d:%02d", eta_hrs, eta_min, eta_sec); } p += strlen (p); } else if ( total > 0) { no_eta: APPEND_LITERAL (" "); } assert (p - barstr <= LINES -2 ); while ( p < barstr + LINES -2 ) *p++ = ' '; *p = '\0'; } void ProgressBar::CreateBarImage(char *barstr , long total , long got , char * ratestr ) { char * p = barstr ; int barsize = 50 ; int i = 0 ; int percentage = (int)(100.0 * got / total ); percentage = percentage>100?100:percentage ; int eqlen = (int)(percentage * barsize/100) ; char tmp[30] = {0}; *p = '[';p++; memset(p,'=',eqlen ); p = p + eqlen ; *p = '>';p++; memset(p,' ',barsize-eqlen ); p = p + barsize-eqlen ; *p = ']';p++; for(i=0;i<3;i++) { *p = ' ';p++; } memset(tmp,0,sizeof(tmp)); sprintf(tmp ,"%d/%d", got , total ); for(i=0;i<strlen(tmp);i++,p++) *p = tmp[i] ; for(i=0;i<3;i++,p++) *p = ' '; for(i=0;i<strlen(ratestr);i++,p++) *p = ratestr[i] ; *p = '\0'; }
[ [ [ 1, 1495 ] ] ]
bdd3433e77a014e11e04b8eeb83459734e298cee
b799c972367cd014a1ffed4288a9deb72f590bec
/project/NetServices/services/http/client/data/HTTPMap.h
9986e15a946923b2cfd647998473312731725fae
[]
no_license
intervigilium/csm213a-embedded
647087de8f831e3c69e05d847d09f5fa12b468e6
ae4622be1eef8eb6e4d1677a9b2904921be19a9e
refs/heads/master
2021-01-13T02:22:42.397072
2011-12-11T22:50:37
2011-12-11T22:50:37
2,832,079
2
1
null
null
null
null
UTF-8
C++
false
false
3,020
h
/* Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com) 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. */ /** \file HTTP Map data source/sink header file */ #ifndef HTTP_MAP_H #define HTTP_MAP_H #include "../HTTPData.h" #include "mbed.h" #include <map> using std::map; typedef map<string, string> Dictionary; ///HTTP Client data container for key/value pairs /** This class simplifies the use of key/value pairs requests and responses used widely among web APIs. Note that HTTPMap inherits from std::map<std::string,std::string>. You can therefore use any public method of that class, including the square brackets operator ( [ ] ) to access a value. The data is encoded or decoded to/from a key/value pairs-formatted string, after url-encoding/decoding. */ class HTTPMap : public HTTPData, public Dictionary //Key/Value pairs { public: ///Instantiates map /** @param keyValueSep Key/Value separator (defaults to "=") @param pairSep Pairs separator (defaults to "&") */ HTTPMap(const string& keyValueSep = "=", const string& pairSep = "&"); virtual ~HTTPMap(); /* string& operator[](const string& key); int count();*/ ///Clears the content virtual void clear(); protected: virtual int read(char* buf, int len); virtual int write(const char* buf, int len); virtual string getDataType(); //Internet media type for Content-Type header virtual void setDataType(const string& type); //Internet media type from Content-Type header virtual bool getIsChunked(); //For Transfer-Encoding header virtual void setIsChunked(bool chunked); //From Transfer-Encoding header virtual int getDataLen(); //For Content-Length header virtual void setDataLen(int len); //From Content-Length header private: void generateString(); void parseString(); //map<string, string> m_map; string m_buf; int m_len; bool m_chunked; string m_keyValueSep; string m_pairSep; }; #endif
[ [ [ 1, 89 ] ] ]
05282a755f5d10f0311805c8564afb2d56d2aa7d
905a210043c8a48d128822ddb6ab141a0d583d27
/sigviewer/cameraortho.cpp
993d5a4efc492252f65527e5d48fd4c4171f2770
[]
no_license
mweiguo/sgt
50036153c81f35356e2bfbba7019a8307556abe4
7770cdc030f5e69fef0b2150b92b87b7c8b56ba5
refs/heads/master
2020-04-01T16:32:21.566890
2011-10-31T04:35:02
2011-10-31T04:35:02
1,139,668
0
0
null
null
null
null
UTF-8
C++
false
false
1,388
cpp
#include "cameraortho2.h" CameraOrtho2::CameraOrtho2 (const string& name="default") { _mvid = SGR::SeedGenerator::getInst().maxseed(); _invmvid = SGR::SeedGenerator::getInst().maxseed(); _projid = SGR::SeedGenerator::getInst().maxseed(); _invprojid = SGR::SeedGenerator::getInst().maxseed(); camera_create ( _mvid ); camera_create ( _invmvid ); projection_create ( _projid ); projection_create ( _invprojid ); } void CameraOrtho2::translate ( float dx, float dy, float dz ) { SGR::vec3f dir = _tar.normal(); _pos += dir * SGR::vec3f(dx, dy, dz); } void CameraOrtho2::lookat ( const vec3f& pos, const vec3f& tar, const vec3f& right ) { _pos = pos; _tar = tar; _right = right; calcMVMatrix(); } void CameraOrtho2::position ( const vec3f& pos ) { _pos = pos; calcMVMatrix(); } void CameraOrtho2::target ( const vec3f& tar ) { _tar = tar; calcMVMatrix(); } void CameraOrtho2::righthand ( const vec3f& r ) { _right = right; calcMVMatrix(); } void CameraOrtho2::setortho ( float left, float top, float right, float bottom, float near, float far ) { _projmatrix = ortho_matrix ( left, top, right, bottom, near, far ); _inverseprojmatrix = ortho_inv_matrix ( left, top, right, bottom, near, far ); } void CameraOrtho2::calcMVMatrix() { }
[ [ [ 1, 58 ] ] ]
b30b2fa43ae1aa9342d1ccebfb419efe20154f25
073dfce42b384c9438734daa8ee2b575ff100cc9
/RCF/include/SF/DataPtr.hpp
ff16507662be1400493bcb129dbad2da3b07834e
[]
no_license
r0ssar00/iTunesSpeechBridge
a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf
71a27a52e66f90ade339b2b8a7572b53577e2aaf
refs/heads/master
2020-12-24T17:45:17.838301
2009-08-24T22:04:48
2009-08-24T22:04:48
285,393
1
0
null
null
null
null
UTF-8
C++
false
false
2,002
hpp
//****************************************************************************** // RCF - Remote Call Framework // Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved. // Consult your license for conditions of use. // Version: 1.1 // Contact: jarl.lindrud <at> gmail.com //****************************************************************************** #ifndef INCLUDE_SF_DATAPTR_HPP #define INCLUDE_SF_DATAPTR_HPP #include <string> #include <RCF/Export.hpp> #include <SF/PortableTypes.hpp> namespace SF { //************************************************************************ // DataPtr class holds a pointer to a buffer of data. It includes an internal // buffer in order to avoid dynamic memory allocation for small buffer sizes, < 64bytes. class RCF_EXPORT DataPtr { private: typedef Byte8 T; public: DataPtr(); DataPtr(const T *sz); DataPtr(const T *sz, UInt32 length); DataPtr(const DataPtr &rhs); DataPtr &operator=(const DataPtr &rhs); ~DataPtr(); void assign(const T *sz, UInt32 length); void assign(const T *sz); void assign(const std::string &s); void release(); UInt32 allocate(UInt32 length); void terminatebufferwithzero() const; void update_length(); T *get() const; UInt32 length() const; bool empty() const; std::string cpp_str() const; private: T *ptr_; UInt32 length_; UInt32 allocatedLength_; int whichDeleter_; void (*pfn_deleter_)(T *); T buffer_[64]; UInt32 length(const T *sz); }; RCF_EXPORT bool operator<(const DataPtr &lhs, const DataPtr &rhs); RCF_EXPORT bool operator==(const DataPtr &lhs, const DataPtr &rhs); RCF_EXPORT bool operator!=(const DataPtr &lhs, const DataPtr &rhs); } // namespace SF #endif // ! INCLUDE_SF_DATAPTR_HPP
[ [ [ 1, 66 ] ] ]
22330351258e51bf4e92d3aeb241417b3f072cdf
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/dependencies/include/ParticleUniverse/ParticleAffectors/ParticleUniverseGeometryRotatorFactory.h
5af0b35e3ef10e3f1102117790c2ed09f1c93b76
[]
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,110
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_GEOMETRY_ROTATOR_FACTORY_H__ #define __PU_GEOMETRY_ROTATOR_FACTORY_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseGeometryRotatorTokens.h" #include "ParticleUniverseGeometryRotator.h" #include "ParticleUniverseAffectorFactory.h" namespace ParticleUniverse { /** Factory class responsible for creating the GeometryRotator. */ class _ParticleUniverseExport GeometryRotatorFactory : public ParticleAffectorFactory { public: GeometryRotatorFactory(void){}; virtual ~GeometryRotatorFactory(void){}; /** See ParticleAffectorFactory */ Ogre::String getAffectorType(void) const { return "GeometryRotator"; } /** See ParticleAffectorFactory */ ParticleAffector* createAffector(void) { return _createAffector<GeometryRotator>(); } /** See ScriptReader */ virtual bool translateChildProperty(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { return mGeometryRotatorTranslator.translateChildProperty(compiler, node); }; /** See ScriptReader */ virtual bool translateChildObject(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { return mGeometryRotatorTranslator.translateChildObject(compiler, node); }; /* */ virtual void write(ParticleScriptSerializer* serializer , const IElement* element) { // Delegate mGeometryRotatorWriter.write(serializer, element); } protected: GeometryRotatorWriter mGeometryRotatorWriter; GeometryRotatorTranslator mGeometryRotatorTranslator; }; } #endif
[ [ [ 1, 68 ] ] ]
03c63b6a220a2b567ea318750ebe8beee4479a2a
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/Messaging/TextMTM/txti/TXTI.CPP
1a068a495b71abb7030cf8a40b90de48ae6e446e
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
9,851
cpp
// TXTI.CPP // // Copyright (c) 1999 Symbian Ltd. All rights reserved. // // Standard includes #include <coemain.h> // CCoeEnv // Messaging includes #include <mtclbase.h> #include <msvstd.hrh> #include <mtmdef.hrh> #include <msvuids.h> #include <msvids.h> // Specific includes #include "txut.h" #include "txtucmds.h" #include "txclient.h" #include "txti.h" #include "txtipan.h" #include <txti.rsg> #include <txti.mbg> #include <MTMUIDEF.HRH> // Constants const TInt KTxtiMtmUdZoomNumberOfStates = 1; #ifdef __WINS__ // on wins, assume built to z: _LIT(KTxtiMtmUdResourceFile,"TXTI.RSC"); _LIT(KTxtiMtmUdBitmapFile,"TXTI.MBM"); #else _LIT(KTxtiMtmUdResourceFile,"c:\\resource\\messaging\\TXTI.RSC"); _LIT(KTxtiMtmUdBitmapFile,"c:\\resource\\messaging\\TXTI.MBM"); #endif //WINS _LIT(KTxtiReadyToSend,"Ready To Send"); // // TTxtiBitmapIndexes: index to bitmap sets // 3 sets for messages (at different priority levels), and 1 for a service // enum TTxtiBitmapIndexes { ETxtiLowPriority=0, ETxtiNormalPriority, ETxtiHighPriority, ETxtiService, ETxtiFolder }; // This constant is required for TechView. It's defined in MTMExtendedCapabilities.hrh // but we define it ourselves to keep this code generic, and not depend on TechView-specific headers #define KUidMtmQueryCanCreateNewMsgValue 0x10008b24 // // CTxtiMtmUiData: UI Data MTM // // // Construction, initialisation, and destruction // CTxtiMtmUiData* CTxtiMtmUiData::NewL(CRegisteredMtmDll& aRegisteredDll) { CTxtiMtmUiData* base=new(ELeave) CTxtiMtmUiData(aRegisteredDll); CleanupStack::PushL(base); base->ConstructL(); CleanupStack::Pop(); return base; } CTxtiMtmUiData::~CTxtiMtmUiData() { } void CTxtiMtmUiData::PopulateArraysL() // Initialise bitmaps and function information { // Read MTM-specific operation information ReadFunctionsFromResourceFileL(R_TEXTUD_FUNCTION_ARRAY); // Populate bitmap array CreateBitmapsL(KTxtiMtmUdZoomNumberOfStates, KTxtiMtmUdBitmapFile, EMbmTxtiTextl1, EMbmTxtiFold1); } CTxtiMtmUiData::CTxtiMtmUiData(CRegisteredMtmDll& aRegisteredDll) : CBaseMtmUiData(aRegisteredDll) {} void CTxtiMtmUiData::GetResourceFileName(TFileName& aFileName) const // Resource file loading { aFileName=KTxtiMtmUdResourceFile; } // // MTM-specific functionality // TInt CTxtiMtmUiData::OperationSupportedL(TInt aOperationId, const TMsvEntry& aContext) const // Context-sensitive operation query { TInt aReasonResourceId=0; // 0 means "operation is available" if (aContext.iMtm!=KUidMsgTypeText) return R_TEXTUD_NOT_SUPPORTED; const TBool isMessage=aContext.iType==KUidMsvMessageEntry; const TBool isService=aContext.iType==KUidMsvServiceEntry; if (aOperationId==ETxtuCommandRefreshMBox) { // Only allow refresh on services if (!isService) aReasonResourceId=R_TEXTUD_ONLY_REFRESH_SERVICES; } else if (aOperationId==ETxtuCommandExportText) { // Only allow export on local messages if ( (!isMessage) || (aContext.iServiceId != KMsvLocalServiceIndexEntryId) ) aReasonResourceId=R_TEXTUD_ONLY_MESSAGES; } return aReasonResourceId; } TInt CTxtiMtmUiData::QueryCapability(TUid aCapability, TInt& aResponse) const // Query for capability { switch (aCapability.iUid) { // Supported valued capabilities case KUidMtmQueryMaxBodySizeValue: aResponse=KMaxTextMessageSize; break; case KUidMtmQueryMaxTotalMsgSizeValue: aResponse=KMaxTextMessageSize; break; // Supported non-valued capabilities // boolean returns case KUidMtmQuerySupportedBodyValue: case KUidMtmQueryCanSendMsgValue: case KUidMtmQueryOffLineAllowedValue: case KUidMtmQueryCanReceiveMsgValue: case KUidMtmQueryCanCreateNewMsgValue: aResponse=ETrue; break; // Non-supported capabilities // Boolean returns case KUidMtmQuerySupportAttachmentsValue: aResponse=EFalse; break; default: return KErrNotSupported; }; return KErrNone; } const CBaseMtmUiData::CBitmapArray& CTxtiMtmUiData::ContextIcon(const TMsvEntry& aContext, TInt /*aStateFlags*/) const // Get context-specific icon // Text UI Data MTM has 3 sets of message icons relating to the priority of the message { __ASSERT_ALWAYS(aContext.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aContext.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdNoIconForAttachment)); TInt retIndex=ETxtiLowPriority; if (aContext.iType == KUidMsvServiceEntry) retIndex=ETxtiService; else if (aContext.iType == KUidMsvFolderEntry) retIndex=ETxtiFolder; else if (aContext.Priority()==EMsvMediumPriority) retIndex=ETxtiNormalPriority; else if (aContext.Priority()==EMsvHighPriority) retIndex=ETxtiHighPriority; return *iIconArrays->At(retIndex); } // // Context-specific information // TBool CTxtiMtmUiData::CanOpenEntryL(const TMsvEntry& aContext, TInt& aReasonResourceId) const { __ASSERT_ALWAYS(aContext.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aContext.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdAttachmentsNotSupported)); aReasonResourceId=0; if ( aContext.iType != KUidMsvMessageEntry ) { aReasonResourceId=R_TEXTUD_ONLY_MESSAGES; return KErrNotSupported; } else return KErrNone; } TBool CTxtiMtmUiData::CanCloseEntryL(const TMsvEntry& aContext, TInt& aReasonResourceId) const { __ASSERT_ALWAYS(aContext.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aContext.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdAttachmentsNotSupported)); aReasonResourceId=0; if ( aContext.iType != KUidMsvMessageEntry ) { aReasonResourceId=R_TEXTUD_ONLY_MESSAGES; return KErrNotSupported; } else return KErrNone; } TBool CTxtiMtmUiData::CanViewEntryL(const TMsvEntry& aContext, TInt& aReasonResourceId) const { __ASSERT_ALWAYS(aContext.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aContext.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdAttachmentsNotSupported)); aReasonResourceId=0; if ( aContext.iType != KUidMsvMessageEntry ) { aReasonResourceId=R_TEXTUD_ONLY_MESSAGES; return KErrNotSupported; } else return KErrNone; } TBool CTxtiMtmUiData::CanEditEntryL(const TMsvEntry& aContext, TInt& aReasonResourceId) const { __ASSERT_ALWAYS(aContext.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aContext.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdAttachmentsNotSupported)); aReasonResourceId=0; if ( aContext.iType == KUidMsvFolderEntry ) { aReasonResourceId=R_TEXTUD_CAN_NOT_EDIT_FOLDERS; return KErrNotSupported; } else return KErrNone; } TBool CTxtiMtmUiData::CanDeleteFromEntryL(const TMsvEntry& aContext, TInt& aReasonResourceId) const { __ASSERT_ALWAYS(aContext.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aContext.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdAttachmentsNotSupported)); aReasonResourceId=0; return KErrNone; } TBool CTxtiMtmUiData::CanCopyMoveToEntryL(const TMsvEntry& aContext, TInt& aReasonResourceId) const { __ASSERT_ALWAYS(aContext.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aContext.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdAttachmentsNotSupported)); aReasonResourceId=0; return KErrNone; } TBool CTxtiMtmUiData::CanCopyMoveFromEntryL(const TMsvEntry& aContext, TInt& aReasonResourceId) const { __ASSERT_ALWAYS(aContext.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aContext.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdAttachmentsNotSupported)); aReasonResourceId=0; return KErrNone; } TBool CTxtiMtmUiData::CanReplyToEntryL(const TMsvEntry& aContext, TInt& aReasonResourceId) const // // MTM UI does not support replying. // { __ASSERT_ALWAYS(aContext.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aContext.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdAttachmentsNotSupported)); aReasonResourceId=R_TEXTUD_NOT_SUPPORTED; return KErrNotSupported; } TBool CTxtiMtmUiData::CanForwardEntryL(const TMsvEntry& aContext, TInt& aReasonResourceId) const // // MTM UI does not supports forwarding. // { __ASSERT_ALWAYS(aContext.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aContext.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdAttachmentsNotSupported)); aReasonResourceId=R_TEXTUD_NOT_SUPPORTED; return KErrNotSupported; } TBool CTxtiMtmUiData::CanCreateEntryL(const TMsvEntry& aParent, TMsvEntry& aNewEntry, TInt& aReasonResourceId) const { __ASSERT_ALWAYS(aNewEntry.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); __ASSERT_ALWAYS(aNewEntry.iType!=KUidMsvAttachmentEntry, Panic(ETxtiMtmUdAttachmentsNotSupported)); aReasonResourceId=0; // --- Can create services if they are off root --- if (aNewEntry.iType == KUidMsvServiceEntry) return (aParent.Id() == KMsvRootIndexEntryIdValue); // --- Can create messages in local folders --- if (aNewEntry.iType == KUidMsvMessageEntry) return (aParent.iMtm.iUid == KMsvLocalServiceIndexEntryIdValue); return KErrNotSupported; } TBool CTxtiMtmUiData::CanDeleteServiceL(const TMsvEntry& aService, TInt& aReasonResourceId)const { __ASSERT_ALWAYS(aService.iMtm==KUidMsgTypeText, Panic(ETxtiMtmUdWrongMtm)); aReasonResourceId=0; return KErrNone; } TBool CTxtiMtmUiData::CanCancelL(const TMsvEntry& /*aContext*/, TInt& /*aReasonResourceId*/) const { return EFalse; } HBufC* CTxtiMtmUiData::StatusTextL(const TMsvEntry& /*aContext*/) const { HBufC* statusBuffer = HBufC::NewL(15); *statusBuffer = KTxtiReadyToSend; return statusBuffer; }
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 335 ] ] ]
a6d221fdd0e4b4ad59bd02e2200b203f6a8c6cca
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/libs/STLPort-4.0/src/c_locale_stub.cpp
c789fa73335ac41573e7e6ad80bbbc27b6e002de
[ "LicenseRef-scancode-stlport-4.5" ]
permissive
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
10,502
cpp
/* * Copyright (c) 1999 * Silicon Graphics Computer Systems, Inc. * * Copyright (c) 1999 * Boris Fomitchev * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * */ # include "stlport_prefix.h" #include <stl/c_locale.h> #include <limits.h> # ifdef __STL_REAL_LOCALE_IMPLEMENTED // here, we'll put C locale implementation for those compilers where // it has to be done in C++ # else /* This is a "stub" implementation of the <c_locale.h> interface, intended for operating systems where we have not yet written a real implementation. A C++ library using this stub implementation is still standard-conforming, since the C++ standard does not require that any locales other than "C" be supported. */ /* Framework functions */ struct _Locale_ctype /* { } */ ; struct _Locale_numeric /* { } */; struct _Locale_time /* { } */; struct _Locale_collate /*{ } */; struct _Locale_monetary /* { } */; struct _Locale_messages /* { } */; # ifdef __cplusplus __STL_BEGIN_NAMESPACE extern "C" { # define __DUMMY_PAR # define __DUMMY_PAR1 # define __DUMMY_PAR2 # define __DUMMY_PAR3 # define __DUMMY_PAR4 # define __DUMMY_PAR5 # define __DUMMY_PAR6 # define __DUMMY_PAR7 # endif void* _Locale_ctype_create(const char * __DUMMY_PAR) { return 0; } void* _Locale_numeric_create(const char * __DUMMY_PAR) { return 0; } void*_Locale_time_create(const char * __DUMMY_PAR) { return 0; } void* _Locale_collate_create(const char *__DUMMY_PAR) { return 0; } void* _Locale_monetary_create(const char * __DUMMY_PAR) { return 0; } void* _Locale_messages_create(const char *__DUMMY_PAR) { return 0; } const char* _Locale_ctype_default(char*) { return 0; } const char* _Locale_numeric_default(char *) { return 0; } const char* _Locale_time_default(char*) { return 0; } const char* _Locale_collate_default(char*) { return 0; } const char* _Locale_monetary_default(char*) { return 0; } const char* _Locale_messages_default(char*) { return 0; } char* _Locale_ctype_name(const void* __DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_numeric_name(const void* __DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_time_name(const void* __DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_collate_name(const void* __DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_monetary_name(const void* __DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_messages_name(const void* __DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } void _Locale_ctype_destroy(void* __DUMMY_PAR) {} void _Locale_numeric_destroy(void* __DUMMY_PAR) {} void _Locale_time_destroy(void* __DUMMY_PAR) {} void _Locale_collate_destroy(void* __DUMMY_PAR) {} void _Locale_monetary_destroy(void* __DUMMY_PAR) {} void _Locale_messages_destroy(void* __DUMMY_PAR) {} char* _Locale_extract_ctype_name(const char* __DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_extract_numeric_name(const char*__DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_extract_time_name(const char*__DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_extract_collate_name(const char*__DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_extract_monetary_name(const char*__DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_extract_messages_name(const char*__DUMMY_PAR1, char* __DUMMY_PAR) { return 0; } char* _Locale_compose_name(char*__DUMMY_PAR1, const char*__DUMMY_PAR2, const char*__DUMMY_PAR3, const char*__DUMMY_PAR4, const char*__DUMMY_PAR5, const char*__DUMMY_PAR6, const char*__DUMMY_PAR7) { return 0; } /* ctype */ _Locale_mask_t* _Locale_ctype_table(struct _Locale_ctype* __DUMMY_PAR) { return 0; } int _Locale_toupper(struct _Locale_ctype*__DUMMY_PAR1, int __DUMMY_PAR) { return 0; } int _Locale_tolower(struct _Locale_ctype*__DUMMY_PAR1, int __DUMMY_PAR) { return 0; } # ifndef __STL_NO_WCHAR_T _Locale_mask_t _Locale_wchar_ctype(struct _Locale_ctype*__DUMMY_PAR1, wint_t __DUMMY_PAR) { return 0; } wint_t _Locale_wchar_tolower(struct _Locale_ctype*__DUMMY_PAR1, wint_t __DUMMY_PAR) { return 0; } wint_t _Locale_wchar_toupper(struct _Locale_ctype*__DUMMY_PAR1, wint_t __DUMMY_PAR) { return 0; } # endif # ifndef __STL_NO_MBSTATE_T int _Locale_mb_cur_max (struct _Locale_ctype * __DUMMY_PAR) { return 0; } int _Locale_mb_cur_min (struct _Locale_ctype * __DUMMY_PAR) { return 0; } int _Locale_is_stateless (struct _Locale_ctype * __DUMMY_PAR) { return 1; } wint_t _Locale_btowc(struct _Locale_ctype * __DUMMY_PAR1, int __DUMMY_PAR) { return 0; } int _Locale_wctob(struct _Locale_ctype * __DUMMY_PAR2, wint_t __DUMMY_PAR) { return 0; } size_t _Locale_mbtowc(struct _Locale_ctype *__DUMMY_PAR1, wchar_t *__DUMMY_PAR2, const char *__DUMMY_PAR3, size_t __DUMMY_PAR4, mbstate_t *__DUMMY_PAR5) { return (size_t) -1; } size_t _Locale_wctomb(struct _Locale_ctype *__DUMMY_PAR1, char *__DUMMY_PAR2, size_t __DUMMY_PAR3, const wchar_t __DUMMY_PAR4, mbstate_t *__DUMMY_PAR5) { return (size_t) -1; } size_t _Locale_unshift(struct _Locale_ctype *__DUMMY_PAR1, mbstate_t *__DUMMY_PAR2, char *__DUMMY_PAR3, size_t __DUMMY_PAR4, char ** __DUMMY_PAR5) { return (size_t) -1; } # endif /* __STL_NO_MBSTATE_T */ /* Collate */ int _Locale_strcmp(struct _Locale_collate* __DUMMY_PAR1, const char* __DUMMY_PAR2, size_t __DUMMY_PAR3, const char* __DUMMY_PAR4, size_t __DUMMY_PAR5) { return 0; } # ifndef __STL_NO_WCHAR_T int _Locale_strwcmp(struct _Locale_collate* __DUMMY_PAR1, const wchar_t* __DUMMY_PAR2, size_t __DUMMY_PAR3, const wchar_t* __DUMMY_PAR4, size_t __DUMMY_PAR5) { return 0; } # endif size_t _Locale_strxfrm(struct _Locale_collate* __DUMMY_PAR1, char* __DUMMY_PAR2, size_t __DUMMY_PAR3, const char* __DUMMY_PAR4, size_t __DUMMY_PAR5) { return 0; } # ifndef __STL_NO_WCHAR_T size_t _Locale_strwxfrm(struct _Locale_collate* __DUMMY_PAR1, wchar_t* __DUMMY_PAR2, size_t __DUMMY_PAR3, const wchar_t* __DUMMY_PAR4, size_t __DUMMY_PAR5) { return 0; } # endif /* Numeric */ char _Locale_decimal_point(struct _Locale_numeric* __DUMMY_PAR) { return '.'; } char _Locale_thousands_sep(struct _Locale_numeric* __DUMMY_PAR) { return ','; } const char* _Locale_grouping(struct _Locale_numeric * __DUMMY_PAR) { return ""; } const char * _Locale_true(struct _Locale_numeric * __DUMMY_PAR) { return 0; } const char * _Locale_false(struct _Locale_numeric * __DUMMY_PAR) { return 0; } /* Monetary */ const char* _Locale_int_curr_symbol(struct _Locale_monetary * __DUMMY_PAR) { return 0; } const char* _Locale_currency_symbol(struct _Locale_monetary * __DUMMY_PAR) { return 0; } char _Locale_mon_decimal_point(struct _Locale_monetary * __DUMMY_PAR) { return '.'; } char _Locale_mon_thousands_sep(struct _Locale_monetary * __DUMMY_PAR) { return ','; } const char* _Locale_mon_grouping(struct _Locale_monetary * __DUMMY_PAR) { return ""; } const char* _Locale_positive_sign(struct _Locale_monetary * __DUMMY_PAR) { return ""; } const char* _Locale_negative_sign(struct _Locale_monetary * __DUMMY_PAR) { return ""; } char _Locale_int_frac_digits(struct _Locale_monetary * __DUMMY_PAR) { return CHAR_MAX; } char _Locale_frac_digits(struct _Locale_monetary * __DUMMY_PAR) { return CHAR_MAX; } int _Locale_p_cs_precedes(struct _Locale_monetary * __DUMMY_PAR) { return CHAR_MAX; } int _Locale_p_sep_by_space(struct _Locale_monetary * __DUMMY_PAR) { return CHAR_MAX; } int _Locale_p_sign_posn(struct _Locale_monetary * __DUMMY_PAR) { return CHAR_MAX; } int _Locale_n_cs_precedes(struct _Locale_monetary * __DUMMY_PAR) { return CHAR_MAX; } int _Locale_n_sep_by_space(struct _Locale_monetary * __DUMMY_PAR) { return CHAR_MAX; } int _Locale_n_sign_posn(struct _Locale_monetary * __DUMMY_PAR) { return CHAR_MAX; } /* Time */ const char ** _Locale_full_monthname(struct _Locale_time * __DUMMY_PAR) { return 0; } const char ** _Locale_abbrev_monthname(struct _Locale_time * __DUMMY_PAR) { return 0; } const char ** _Locale_full_dayofweek(struct _Locale_time * __DUMMY_PAR) { return 0; } const char ** _Locale_abbrev_dayofweek(struct _Locale_time * __DUMMY_PAR) { return 0; } const char* _Locale_d_t_fmt(struct _Locale_time* __DUMMY_PAR) { return 0; } const char* _Locale_d_fmt(struct _Locale_time* __DUMMY_PAR) { return 0; } const char* _Locale_t_fmt(struct _Locale_time* __DUMMY_PAR) { return 0; } const char* _Locale_am_str(struct _Locale_time* __DUMMY_PAR) { return 0; } const char* _Locale_pm_str(struct _Locale_time* __DUMMY_PAR) { return 0; } const char* _Locale_t_fmt_ampm(struct _Locale_time* __DUMMY_PAR) { return 0; } /* Messages */ int _Locale_catopen(struct _Locale_messages* __DUMMY_PAR1, const char* __DUMMY_PAR) { return -1; } void _Locale_catclose(struct _Locale_messages* __DUMMY_PAR1, int __DUMMY_PAR) {} const char* _Locale_catgets(struct _Locale_messages* __DUMMY_PAR1, int __DUMMY_PAR2, int __DUMMY_PAR3, int __DUMMY_PAR4, const char *dfault) { return dfault; } #ifdef __cplusplus } /* extern C */ __STL_END_NAMESPACE #endif #endif /* real locale */
[ [ [ 1, 273 ] ] ]
54087f50a9abe9835165a54485b7563c1996988d
deb8ef49795452ff607023c6bce8c3e8ed4c8360
/Projects/UAlbertaBot/Source/base/StarcraftBuildOrderSearchManager.cpp
339afe752403fc98fc1d001fd90e48e786e2a863
[]
no_license
timburr1/ou-skynet
f36ed7996c21f788a69e3ae643b629da7d917144
299a95fae4419429be1d04286ea754459a9be2d6
refs/heads/master
2020-04-19T22:58:46.259980
2011-12-06T20:10:34
2011-12-06T20:10:34
34,360,542
0
0
null
null
null
null
UTF-8
C++
false
false
7,123
cpp
#include "Common.h" #include "StarcraftBuildOrderSearchManager.h" typedef std::map<MetaType, int> mapType; // gotta keep c++ static happy StarcraftBuildOrderSearchManager * StarcraftBuildOrderSearchManager::instance = NULL; // get an instance of this StarcraftBuildOrderSearchManager * StarcraftBuildOrderSearchManager::getInstance() { // if the instance doesn't exist, create it if (!StarcraftBuildOrderSearchManager::instance) { StarcraftBuildOrderSearchManager::instance = new StarcraftBuildOrderSearchManager(); } return StarcraftBuildOrderSearchManager::instance; } // constructor StarcraftBuildOrderSearchManager::StarcraftBuildOrderSearchManager() : lastSearchFinishTime(0) { StarcraftData::getInstance().init(BWAPI::Races::Protoss); } void StarcraftBuildOrderSearchManager::update(double timeLimit) { starcraftSearchData.update(timeLimit); } // function which is called from the bot std::vector<MetaType> StarcraftBuildOrderSearchManager::findBuildOrder(BWAPI::Race race, std::vector< std::pair<MetaType, int> > & goalUnits) { return getMetaVector(search<ProtossState>(goalUnits)); } // function which does all the searching template <class StarcraftStateType> SearchResults StarcraftBuildOrderSearchManager::search(std::vector< std::pair<MetaType, int> > & goalUnits) { // construct the Smart Starcraft Search SmartStarcraftSearch<StarcraftStateType> sss; // set the goal based on the input MetaType vector sss.setGoal(getGoal(goalUnits)); // set the initial state to the current state of the BW game sss.setState(getCurrentState<StarcraftStateType>()); // get the parameters from the smart search SearchParameters<StarcraftStateType> params = sss.getParameters(); // pass this goal into the searcher starcraftSearchData.startNewSearch(params); // do the search and store the results SearchResults result = starcraftSearchData.getResults(); if (result.solved) { lastSearchFinishTime = result.solutionLength; //BWAPI::Broodwar->printf("%12d[opt]%9llu[nodes]%7d[ms]", result.solutionLength, result.nodesExpanded, (int)result.timeElapsed); } else { //BWAPI::Broodwar->printf("No solution found!"); //BWAPI::Broodwar->printf("%12d%12d%12d%14llu", result.upperBound, result.lowerBound, 0, result.nodesExpanded); } return result; } // gets the StarcraftState corresponding to the beginning of a Melee game template <class StarcraftStateType> StarcraftStateType StarcraftBuildOrderSearchManager::getStartState() { return StarcraftStateType(true); } // parses current BWAPI game state and turns it into a StarcraftState of given type template <class StarcraftStateType> StarcraftStateType StarcraftBuildOrderSearchManager::getCurrentState() { StarcraftStateType s; s.setFrame(BWAPI::Broodwar->getFrameCount()); s.setSupply(BWAPI::Broodwar->self()->supplyUsed(), BWAPI::Broodwar->self()->supplyTotal()); s.setResources(BWAPI::Broodwar->self()->minerals(), BWAPI::Broodwar->self()->gas()); s.setMineralWorkers(WorkerManager::getInstance()->getNumMineralWorkers()); s.setGasWorkers(WorkerManager::getInstance()->getNumGasWorkers()); // for each unit we have BOOST_FOREACH(BWAPI::Unit * unit, BWAPI::Broodwar->self()->getUnits()) { Action action(DATA.getAction(unit->getType())); // if the unit is completed if (unit->isCompleted()) { // add the unit to the state s.addNumUnits(action, 1); // if it is a building if (unit->getType().isBuilding()) { // add the building data accordingly s.addBuilding(action, unit->getRemainingTrainTime() + unit->getRemainingResearchTime() + unit->getRemainingUpgradeTime()); if (unit->getRemainingResearchTime() > 0) { s.addActionInProgress(DATA.getAction(unit->getTech()), BWAPI::Broodwar->getFrameCount() + unit->getRemainingTrainTime()); } else if (unit->getRemainingUpgradeTime() > 0) { s.addActionInProgress(DATA.getAction(unit->getUpgrade()), BWAPI::Broodwar->getFrameCount() + unit->getRemainingTrainTime()); } } } // if the unit is under construction (building) if (unit->isBeingConstructed()) { s.addActionInProgress(DATA.getAction(unit->getType()), BWAPI::Broodwar->getFrameCount() + unit->getRemainingBuildTime()); } } BOOST_FOREACH (BWAPI::UpgradeType type, BWAPI::UpgradeTypes::allUpgradeTypes()) { if (BWAPI::Broodwar->self()->getUpgradeLevel(type) > 0) { //BWAPI::Broodwar->printf("I have %s", type.getName().c_str()); s.addNumUnits(DATA.getAction(type), BWAPI::Broodwar->self()->getUpgradeLevel(type)); } } return s; } StarcraftSearchGoal StarcraftBuildOrderSearchManager::getGoal(std::vector< std::pair<MetaType, int> > & goalUnits) { StarcraftSearchGoal goal; for (size_t i=0; i<goalUnits.size(); ++i) { goal.setGoal(getAction(goalUnits[i].first), goalUnits[i].second); } return goal; } // converts SearchResults.buildOrder vector into vector of MetaType std::vector<MetaType> StarcraftBuildOrderSearchManager::getMetaVector(SearchResults & results) { std::vector<MetaType> metaVector; std::vector<Action> & buildOrder = results.buildOrder; //Logger::getInstance()->log("Get Meta Vector:\n"); // for each item in the results build order, add it for (size_t i(0); i<buildOrder.size(); ++i) { // retrieve the action from the build order Action a = buildOrder[buildOrder.size()-1-i]; metaVector.push_back(getMetaType(a)); } return metaVector; } // converts from MetaType to StarcraftSearch Action Action StarcraftBuildOrderSearchManager::getAction(MetaType t) { //Logger::getInstance()->log("Action StarcraftBuildOrderSearchManager::getAction(" + t.getName() + ")\n"); return t.isUnit() ? DATA.getAction(t.unitType) : (t.isTech() ? DATA.getAction(t.techType) : DATA.getAction(t.upgradeType)); } std::vector<MetaType> StarcraftBuildOrderSearchManager::getOpeningBuildOrder() { std::vector<std::string> buildStrings; //initial build order buildStrings.push_back("0 0 0 0 1 0 0 3 0 0 4 4 4"); //0 = probe, 1 = pylon, 3 = gateway //buildStrings.push_back("0 0 0 0 1 0 0 3 0 0 3 0 1 3 0 4 4 4 4 4 1 0 4 4 4"); return getMetaVector(buildStrings[rand() % buildStrings.size()]); } MetaType StarcraftBuildOrderSearchManager::getMetaType(Action a) { const StarcraftAction & s = DATA[a]; MetaType meta; // set the appropriate type if (s.getType() == StarcraftAction::UnitType) { meta = MetaType(s.getUnitType()); } else if (s.getType() == StarcraftAction::UpgradeType) { meta = MetaType(s.getUpgradeType()); } else if (s.getType() == StarcraftAction::TechType) { meta = MetaType(s.getTechType()); } else { assert(false); } return meta; } std::vector<MetaType> StarcraftBuildOrderSearchManager::getMetaVector(std::string buildString) { std::stringstream ss; ss << buildString; std::vector<MetaType> meta; int action(0); while (ss >> action) { meta.push_back(getMetaType(action)); } return meta; }
[ "[email protected]@ce23f72d-95c0-fd94-fabd-fc6dce850bd1" ]
[ [ [ 1, 233 ] ] ]
03a777236948bc8982c37f7d3fb425fc116f0a44
22438bd0a316b62e88380796f0a8620c4d129f50
/applications/rythmbuilder/instrument_factory.h
f7b868e32f583fe9971475324375b429bf6477be
[ "BSL-1.0" ]
permissive
DannyHavenith/NAPL
1578f5e09f1b825f776bea9575f76518a84588f4
5db7bf823bdc10587746d691cb8d94031115b037
refs/heads/master
2021-01-20T02:17:01.186461
2010-11-26T22:26:25
2010-11-26T22:26:25
1,856,141
0
1
null
null
null
null
UTF-8
C++
false
false
649
h
#ifndef __INSTRUMENT_FACTORY_H__ #define __INSTRUMENT_FACTORY_H__ #include <string> #include <set> #include <boost/shared_ptr.hpp> #include <boost/filesystem/path.hpp> class instrument; class instrument_factory { public: instrument_factory( const boost::filesystem::path &p); boost::shared_ptr< instrument> get_instrument( const std::string &instrument_name); std::set< std::string> get_note_names(); private: typedef std::map< std::string, boost::shared_ptr< instrument> > instrument_map; instrument_map instruments; boost::filesystem::path instrument_path; }; #endif //__INSTRUMENT_FACTORY_H__
[ [ [ 1, 25 ] ] ]
ef164e3955e9f4112dd17da261b93f4a143a2e85
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/include/ParticleUniverseScriptDeserializer.h
97e8ddc7ccde03438bba0de054ab83598b934a2d
[]
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
30,255
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_PARTICLE_SCRIPT_DESERIALIZER_H__ #define __PU_PARTICLE_SCRIPT_DESERIALIZER_H__ #include "ParticleUniverseDynamicAttribute.h" #include "OgreScriptTranslator.h" #include "OgreScriptCompiler.h" namespace ParticleUniverse { // Define static tokens static enum { // Generic TOKEN_GROUP_MASK, TOKEN_ACCELERATION, TOKEN_MAX_INCREMENT, TOKEN_MIN_INCREMENT, TOKEN_ITERATIONS, TOKEN_COLOUR_CHANGE, TOKEN_INITIAL_COLOUR, TOKEN_RANDOM_INITIAL_COLOUR, TOKEN_USE_VERTEX_COLOURS, TOKEN_USE_OWN_ROTATION, TOKEN_MAX_DEVIATION, TOKEN_TIME_STEP, TOKEN_BOX_WIDTH, TOKEN_BOX_HEIGHT, TOKEN_BOX_DEPTH, TOKEN_VELOCITY, TOKEN_SPEED, TOKEN_ROTATION_SPEED, TOKEN_ROTATION, TOKEN_ROTATION_AXIS, TOKEN_NORMAL, TOKEN_STEP, TOKEN_NUMBER_OF_SEGMENTS, TOKEN_MAX_ELEMENTS, TOKEN_UPDATE_INTERVAL, TOKEN_DISTANCE_THRESHOLD, TOKEN_MATERIAL, TOKEN_MESH_NAME, TOKEN_RADIUS, TOKEN_ENABLED, TOKEN_POSITION, TOKEN_KEEP_LOCAL, TOKEN_LESS_THAN, TOKEN_GREATER_THAN, TOKEN_VISUAL_PARTICLE, TOKEN_EMITTER_PARTICLE, TOKEN_AFFECTOR_PARTICLE, TOKEN_TECHNIQUE_PARTICLE, TOKEN_SYSTEM_PARTICLE, TOKEN_POINT, TOKEN_VERTEX, TOKEN_INCREASE, TOKEN_ALIAS, TOKEN_USE_ALIAS, // Particle System TOKEN_SYSTEM, TOKEN_PS_ITERATION_INTERVAL, TOKEN_PS_NONVIS_UPDATE_TIMEOUT, TOKEN_PS_FIXED_TIMEOUT, TOKEN_PS_LOD_DISTANCES, TOKEN_PS_MAIN_CAMERA_NAME, TOKEN_PS_SMOOTH_LOD, TOKEN_PS_FAST_FORWARD, TOKEN_PS_SCALE, TOKEN_PS_SCALE_VELOCITY, TOKEN_PS_SCALE_TIME, TOKEN_PS_TIGHT_BOUNDING_BOX, // Particle Technique TOKEN_TECHNIQUE, TOKEN_TECH_VISUAL_PARTICLE_QUOTA, TOKEN_TECH_EMITTED_EMITTER_QUOTA, TOKEN_TECH_EMITTED_AFFECTOR_QUOTA, TOKEN_TECH_EMITTED_TECHNIQUE_QUOTA, TOKEN_TECH_EMITTED_SYSTEM_QUOTA, TOKEN_TECH_LOD_INDEX, TOKEN_TECH_DEFAULT_PARTICLE_WIDTH, TOKEN_TECH_DEFAULT_PARTICLE_HEIGHT, TOKEN_TECH_DEFAULT_PARTICLE_DEPTH, TOKEN_TECH_SPHASHING_CELL_DIMENSION, TOKEN_TECH_SPHASHING_CELL_OVERLAP, TOKEN_TECH_SPHASHING_SIZE, TOKEN_TECH_SPHASHING_UPDATE_INTERVAL, TOKEN_TECH_MAX_VELOCITY, // Particle Renderer TOKEN_RENDERER, TOKEN_RENDERER_Q_GROUP, TOKEN_RENDERER_SORTING, TOKEN_RENDERER_TEXCOORDS_DEFINE, TOKEN_RENDERER_TEXCOORDS_ROWS, TOKEN_RENDERER_TEXCOORDS_SET, TOKEN_RENDERER_TEXCOORDS_COLUMNS, TOKEN_RENDERER_USE_SOFT_PARTICLES, TOKEN_RENDERER_SOFT_PARTICLES_CONTRAST_POWER, TOKEN_RENDERER_SOFT_PARTICLES_SCALE, TOKEN_RENDERER_SOFT_PARTICLES_DELTA, // Particle Emitter TOKEN_EMITTER, TOKEN_EMITTER_DIRECTION, TOKEN_EMITTER_ORIENTATION, TOKEN_EMITTER_ORIENTATION_RANGE_START, TOKEN_EMITTER_ORIENTATION_RANGE_END, TOKEN_EMITTER_START_ORIENTATION_RANGE, TOKEN_EMITTER_END_ORIENTATION_RANGE, TOKEN_EMITTER_DURATION, TOKEN_EMITTER_REPEAT_DELAY, TOKEN_EMITTER_EMITS, TOKEN_ANGLE, TOKEN_EMITTER_EMISSION_RATE, TOKEN_TIME_TO_LIVE, TOKEN_EMITTER_MASS, TOKEN_EMITTER_START_TEXCOORDS, TOKEN_EMITTER_END_TEXCOORDS, TOKEN_EMITTER_START_TEXCOORDS_RANGE, TOKEN_EMITTER_END_TEXCOORDS_RANGE, TOKEN_EMITTER_TEXCOORDS, TOKEN_EMITTER_START_COLOUR_RANGE, TOKEN_EMITTER_END_COLOUR_RANGE, TOKEN_EMITTER_COLOUR, TOKEN_EMITTER_ALL_PARTICLE_DIM, TOKEN_EMITTER_PARTICLE_WIDTH, TOKEN_EMITTER_PARTICLE_HEIGHT, TOKEN_EMITTER_PARTICLE_DEPTH, TOKEN_EMITTER_AUTO_DIRECTION, TOKEN_EMITTER_FORCE_EMISISON, // Particle Affector TOKEN_AFFECTOR, TOKEN_AFFECTOR_MASS, TOKEN_AFFECTOR_EXCLUDE_EMITTER, TOKEN_AFFECTOR_SPECIALISATION, TOKEN_AFFECTOR_SPEC_DEFAULT, TOKEN_AFFECTOR_SPEC_TTL_INCREASE, TOKEN_AFFECTOR_SPEC_TTL_DECREASE, // Particle Observer TOKEN_OBSERVER, TOKEN_OBSERVE_PARTICLE_TYPE, TOKEN_OBSERVE_INTERVAL, TOKEN_OBSERVE_UNTIL_EVENT, // Particle Event Handler TOKEN_HANDLER, // Particle Behaviour TOKEN_BEHAVIOUR, // Extern TOKEN_EXTERN, TOKEN_EXTERN_DISTANCE_THRESHOLD, // Dynamic Attribute TOKEN_DYN_CONTROL_POINT, TOKEN_DYN_MIN, TOKEN_DYN_MAX, TOKEN_DYN_OSCILLATE_FREQUENCY, TOKEN_DYN_OSCILLATE_PHASE, TOKEN_DYN_OSCILLATE_BASE, TOKEN_DYN_OSCILLATE_AMPLITUDE, TOKEN_DYN_OSCILLATE_TYPE, TOKEN_DYN_OSCILLATE, TOKEN_DYN_RANDOM, TOKEN_DYN_CURVED_LINEAR, TOKEN_DYN_CURVED_SPLINE, TOKEN_DYN_SINE, TOKEN_DYN_SQUARE, // CameraDependency (unused) TOKEN_CAMERA_DEPENDENCY, // BeamRenderer TOKEN_BEAMRENDERER_UPDATE_INTERVAL, TOKEN_BEAMRENDERER_MAX_ELEMENTS, TOKEN_BEAMRENDERER_DEVIATION, TOKEN_BEAMRENDERER_NUMBER_OF_SEGMENTS, TOKEN_BEAMRENDERER_JUMP, TOKEN_BEAMRENDERER_TEXCOORD_DIRECTION, TOKEN_BEAMRENDERER_VERTEX_COLOURS, TOKEN_BEAMRENDERER_TCD_U, TOKEN_BEAMRENDERER_TCD_V, // BillboardRenderer TOKEN_BILLBOARD_TYPE, TOKEN_BILLBOARD_ORIGIN, TOKEN_BILLBOARD_ROTATION_TYPE, TOKEN_BILLBOARD_COMMON_DIRECTION, TOKEN_BILLBOARD_COMMON_UP_VECTOR, TOKEN_BILLBOARD_POINT_RENDERING, TOKEN_BILLBOARD_ACCURATE_FACING, TOKEN_BILLBOARD_ORIENTED_COMMON, TOKEN_BILLBOARD_ORIENTED_SELF, TOKEN_BILLBOARD_ORIENTED_SHAPE, TOKEN_BILLBOARD_PERPENDICULAR_COMMON, TOKEN_BILLBOARD_PERPENDICULAR_SELF, TOKEN_BILLBOARD_TOP_LEFT, TOKEN_BILLBOARD_TOP_CENTER, TOKEN_BILLBOARD_TOP_RIGHT, TOKEN_BILLBOARD_CENTER_LEFT, TOKEN_BILLBOARD_CENTER_RIGHT, TOKEN_BILLBOARD_CENTER, TOKEN_BILLBOARD_BOTTON_LEFT, TOKEN_BILLBOARD_BOTTOM_CENTER, TOKEN_BILLBOARD_BOTTOM_RIGHT, TOKEN_BILLBOARD_TEXCOORD, // EntityRenderer TOKEN_ENT_MESH_NAME, TOKEN_ENT_ORIENTATION_TYPE, TOKEN_ENT_ORIENTED_SELF, TOKEN_ENT_ORIENTED_SELF_MIRRORED, TOKEN_ENT_ORIENTED_SHAPE, // LightRenderer TOKEN_LIGHT_TYPE, TOKEN_LIGHT_RENDER_QUEUE, TOKEN_LIGHT_SPECULAR, TOKEN_LIGHT_ATT_RANGE, TOKEN_LIGHT_ATT_CONSTANT, TOKEN_LIGHT_ATT_LINEAR, TOKEN_LIGHT_ATT_QUADRATIC, TOKEN_LIGHT_SPOT_INNER, TOKEN_LIGHT_SPOT_OUTER, TOKEN_LIGHT_FALLOFF, TOKEN_LIGHT_POWERSCALE, TOKEN_LIGHT_SPOT, TOKEN_FLASH_FREQUENCY, TOKEN_FLASH_LENGTH, TOKEN_FLASH_RANDOM, // RibbonTrailRenderer TOKEN_RIBBONTRAIL_VERTEX_COLOURS, TOKEN_RIBBONTRAIL_MAX_ELEMENTS, TOKEN_RIBBONTRAIL_LENGTH, TOKEN_RIBBONTRAIL_WIDTH, TOKEN_RIBBONTRAIL_RANDOM_INITIAL_COLOUR, TOKEN_RIBBONTRAIL_INITIAL_COLOUR, TOKEN_RIBBONTRAIL_COLOUR_CHANGE, // BoxEmitter TOKEN_EMITTER_BOX_WIDTH, TOKEN_EMITTER_BOX_HEIGHT, TOKEN_EMITTER_BOX_DEPTH, // CircleEmitter TOKEN_CIRCLE_RADIUS, TOKEN_CIRCLE_STEP, TOKEN_CIRCLE_ANGLE, TOKEN_CIRCLE_RANDOM, TOKEN_EMIT_RANDOM, TOKEN_CIRCLE_NORMAL, // LineEmitter TOKEN_LINE_EMIT_END, TOKEN_LINE_EMIT_MAX_INCREMENT, TOKEN_LINE_EMIT_MIN_INCREMENT, TOKEN_LINE_EMIT_MAX_DEVIATION, // MeshSurfaceEmitter TOKEN_MESH_SURFACE_NAME, TOKEN_MESH_SURFACE_DISTRIBUTION, TOKEN_MESH_SURFACE_MESH_SCALE, TOKEN_MESH_SURFACE_EDGE, TOKEN_MESH_SURFACE_HETEROGENEOUS_1, TOKEN_MESH_SURFACE_HETEROGENEOUS_2, TOKEN_MESH_SURFACE_HOMOGENEOUS, // PositionEmitter TOKEN_POS_ADD_POSITION, TOKEN_POS_RANDOMIZE, // SlaveEmitter TOKEN_MASTER_TECHNIQUE, TOKEN_MASTER_EMITTER, // SphereSurfaceEmitter TOKEN_SPHERE_RADIUS, // VertexEmitter TOKEN_VERTEX_STEP, TOKEN_VERTEX_SEGMENTS, TOKEN_VERTEX_ITERATIONS, TOKEN_VERTEX_MESH_NAME, // AlignAffector TOKEN_ALIGN_RESIZE, TOKEN_RESIZE, // BoxCollider TOKEN_BOXCOLL_WIDTH, TOKEN_BOXCOLL_HEIGHT, TOKEN_BOXCOLL_DEPTH, // BaseCollider TOKEN_FRICTION, TOKEN_BOUNCYNESS, TOKEN_INTERSECTION, TOKEN_COLLIDER_FRICTION, TOKEN_COLLIDER_BOUNCYNESS, TOKEN_COLLIDER_INTERSECTION, TOKEN_COLLIDER_COLLISION_TYPE, TOKEN_COLLIDER_BOUNCE, TOKEN_COLLIDER_FLOW, TOKEN_COLLIDER_NONE, TOKEN_COLLIDER_INTERSECTION_POINT, TOKEN_COLLIDER_INTERSECTION_BOX, TOKEN_INNER_COLLISION, // CollisionAvoidanceAffector TOKEN_AVOIDANCE_RADIUS, // ColourAffector TOKEN_TIME_COLOUR, TOKEN_COLOUR_TIME_COLOUR, TOKEN_COLOUR_OPERATION, TOKEN_COLOUR_MULTIPLY, TOKEN_COLOUR_SET, // BaseForceAffector TOKEN_FORCE_VECTOR, TOKEN_FORCE_APPLICATION, TOKEN_FORCE_AFF_VECTOR, TOKEN_FORCE_AFF_APPLICATION, TOKEN_FORCE_ADD, TOKEN_FORCE_AVERAGE, // ForceFieldAffector TOKEN_FORCEFIELD_TYPE, TOKEN_REALTIME, TOKEN_MATRIX, TOKEN_DELTA, TOKEN_FORCE, TOKEN_OCTAVES, TOKEN_FREQUENCY, TOKEN_AMPLITUDE, TOKEN_PERSISTENCE, TOKEN_FORCEFIELDSIZE, TOKEN_WORLDSIZE, TOKEN_IGNORE_NEGATIVE_X, TOKEN_IGNORE_NEGATIVE_Y, TOKEN_IGNORE_NEGATIVE_Z, TOKEN_MOVEMENT, TOKEN_MOVEMENT_FREQUENCY, // GeometryRotator TOKEN_GEOMROT_USE_OWN_ROTATION, TOKEN_GEOMROT_ROTATION_SPEED, TOKEN_GEOMROT_ROTATION_AXIS, // GravityAffector TOKEN_GRAVITY, // InterParticleCollider TOKEN_ADJUSTMENT, TOKEN_COLLISION_RESPONSE, TOKEN_IPC_ADJUSTMENT, TOKEN_IPC_COLLISION_RESPONSE, TOKEN_IPC_AVERAGE_VELOCITY, TOKEN_IPC_ANGLE_BASED_VELOCITY, // JetAffector TOKEN_JET_ACCELERATION, // LineAffector TOKEN_END, TOKEN_DRIFT, TOKEN_LINE_AFF_MAX_DEVIATION, TOKEN_LINE_AFF_TIME_STEP, TOKEN_LINE_AFF_END, TOKEN_LINE_AFF_DRIFT, // ParticleFollower TOKEN_FOLLOW_MAX_DISTANCE, TOKEN_FOLLOW_MIN_DISTANCE, TOKEN_MAX_DISTANCE, TOKEN_MIN_DISTANCE, // PathFollower TOKEN_PATH_POINT, // PlaneCollider TOKEN_PLANECOLL_NORMAL, // Randomiser TOKEN_RND_MAX_DEVIATION_X, TOKEN_RND_MAX_DEVIATION_Y, TOKEN_RND_MAX_DEVIATION_Z, TOKEN_MAX_DEVIATION_X, TOKEN_MAX_DEVIATION_Y, TOKEN_MAX_DEVIATION_Z, TOKEN_RND_TIME_STEP, TOKEN_RND_DIRECTION, TOKEN_USE_DIRECTION, // ScaleAffector TOKEN_SCALE_XYZ_SCALE, TOKEN_SCALE_X_SCALE, TOKEN_SCALE_Y_SCALE, TOKEN_SCALE_Z_SCALE, // SineForceAffector TOKEN_SINE_MIN_FREQUENCY, TOKEN_SINE_MAX_FREQUENCY, TOKEN_MIN_FREQUENCY, TOKEN_MAX_FREQUENCY, // SphereCollider TOKEN_SPHERE_COLLIDER_RADIUS, // TextureAnimator TOKEN_TEXANIM_TIME_STEP, TOKEN_TEXANIM_TEXCOORDS_START, TOKEN_TEXANIM_TEXCOORDS_END, TOKEN_START_TEXANIM_TEXCOORDS_RANGE, TOKEN_END_TEXANIM_TEXCOORDS_RANGE, TOKEN_TEXANIM_ANIMATION_TYPE, TOKEN_TEXANIM_START_RANDOM, TOKEN_TEXANIM_LOOP, TOKEN_TEXANIM_UP_DOWN, TOKEN_TEXANIM_RANDOM, // TextureRotator TOKEN_TEXROT_USE_OWN_ROTATION, TOKEN_TEXROT_ROTATION_SPEED, TOKEN_TEXROT_ROTATION, // VelocityMatchingAffector TOKEN_VELO_MATCHING_RADIUS, // VortexAffector TOKEN_VORTEX_ROTATION_VECTOR, TOKEN_VORTEX_ROTATION_SPEED, // OnCountObserver TOKEN_ONCOUNT_THRESHOLD, // OnEventFlagObserver TOKEN_ONEVENT_FLAG, // OnPositionObserver TOKEN_ONPOSITION_X, TOKEN_ONPOSITION_Y, TOKEN_ONPOSITION_Z, // OnRandomObserver TOKEN_ONRANDOM_THRESHOLD, // OnTimeObserver TOKEN_ONTIME, TOKEN_ONTIME_SINCE_START_SYSTEM, // OnVelocityObserver TOKEN_ONVELOCITY_THRESHOLD, // DoAffectorEventHandler TOKEN_FORCE_AFFECTOR, TOKEN_FORCE_AFFECTOR_PRE_POST, // DoEnableComponentEventHandler TOKEN_DOENABLE_COMPONENT, TOKEN_DOENABLE_EMITTER_COMPONENT, TOKEN_DOENABLE_AFFECTOR_COMPONENT, TOKEN_DOENABLE_TECHNIQUE_COMPONENT, TOKEN_DOENABLE_OBSERVER_COMPONENT, // DoPlacementParticleEventHandler TOKEN_DOPLACE_FORCE_EMITTER, TOKEN_DOPLACE_NUMBER_OF_PARTICLES, // DoScaleEventHandler TOKEN_DOSCALE_FRACTION, TOKEN_DOSCALE_TYPE, TOKEN_DOSCALE_TIME_TO_LIVE, TOKEN_DOSCALE_VELOCITY, // SlaveBehaviour // PhysXActorExtern TOKEN_PHYSX_SHAPE_TYPE, TOKEN_PHYSX_ACTOR_COLLISION_GROUP, TOKEN_PHYSX_SHAPE_COLLISION_GROUP, TOKEN_PHYSX_GROUP_MASK, TOKEN_PHYSX_ANGULAR_VELOCITY, TOKEN_PHYSX_ANGULAR_DAMPING, TOKEN_PHYSX_MATERIAL_INDEX, TOKEN_SHAPE_TYPE, TOKEN_ACTOR_COLLISION_GROUP, TOKEN_SHAPE_COLLISION_GROUP, TOKEN_ANGULAR_VELOCITY, TOKEN_ANGULAR_DAMPING, TOKEN_MATERIAL_INDEX, TOKEN_PHYSX_BOX, TOKEN_PHYSX_SPHERE, TOKEN_PHYSX_CAPSULE, // PhysXFluidExtern TOKEN_REST_PARTICLE_PER_METER, TOKEN_REST_DENSITY, TOKEN_KERNEL_RADIUS_MULTIPLIER, TOKEN_MOTION_LIMIT_MULTIPLIER, TOKEN_COLLISION_DISTANCE_MULTIPLIER, TOKEN_PACKET_SIZE_MULTIPLIER, TOKEN_STIFFNESS, TOKEN_VISCOSITY, TOKEN_SURFACE_TENSION, TOKEN_DAMPING, TOKEN_EXTERNAL_ACCELERATION, TOKEN_RESTITUTION_FOR_STATIC_SHAPES, TOKEN_DYNAMIC_FRICTION_FOR_STATIC_SHAPES, TOKEN_STATIC_FRICTION_FOR_STATIC_SHAPES, TOKEN_ATTRACTION_FOR_STATIC_SHAPES, TOKEN_RESTITUTION_FOR_DYNAMIC_SHAPES, TOKEN_DYNAMIC_FRICTION_FOR_DYNAMIC_SHAPES, TOKEN_STATIC_FRICTION_FOR_DYNAMIC_SHAPES, TOKEN_ATTRACTION_FOR_DYNAMIC_SHAPES, TOKEN_COLLISION_RESPONSE_COEFFICIENT, TOKEN_COLLISION_GROUP, TOKEN_SIMULATION_METHOD, TOKEN_COLLISION_METHOD, TOKEN_FLAGS, TOKEN_FLAG_VISUALIZATION, TOKEN_FLAG_DISABLE_GRAVITY, TOKEN_FLAG_COLLISION_TWOWAY, TOKEN_FLAG_FLUID_ENABLED, TOKEN_FLAG_HARDWARE, TOKEN_FLAG_PRIORITY_MODE, TOKEN_FLAG_PROJECT_TO_PLANE, TOKEN_FLAG_STRICT_COOKING_FORMAT, TOKEN_INTERCOLLISION, TOKEN_NOINTERCOLLISION, TOKEN_MIX_INTERCOLLISION, TOKEN_STATIC, TOKEN_DYNAMIC, // SceneDecoratorExtern TOKEN_SCENE_MESH_NAME, TOKEN_SCENE_MATERIAL_NAME, TOKEN_SCENE_SCALE, TOKEN_SCENE_POSITION }; // Static tokens: Note, that the order must be the same as the enum static const Ogre::String token[1000] = { // Generic "group_mask", "acceleration", "max_increment", "min_increment", "number_of_iterations", "colour_change", "initial_colour", "random_initial_colour", "use_vertex_colours", "use_own_rotation", "max_deviation", "time_step", "box_width", "box_height", "box_depth", "velocity", "speed", "rotation_speed", "rotation", "rotation_axis", "normal", "step", "number_of_segments", "max_elements", "update_interval", "distance_threshold", "material", "mesh_name", "radius", "enabled", "position", "keep_local", "less_than", "greater_than", "visual_particle", "emitter_particle", "affector_particle", "technique_particle", "system_particle", "point", "vertex", "increase", "alias", "use_alias", // Particle System "system", "iteration_interval", "nonvisible_update_timeout", "fixed_timeout", "lod_distances", "main_camera_name", "smooth_lod", "fast_forward", "scale", "scale_velocity", "scale_time", "tight_bounding_box", // Particle Technique "technique", "visual_particle_quota", "emitted_emitter_quota", "emitted_affector_quota", "emitted_technique_quota", "emitted_system_quota", "lod_index", "default_particle_width", "default_particle_height", "default_particle_depth", "spatial_hashing_cell_dimension", "spatial_hashing_cell_overlap", "spatial_hashtable_size", "spatial_hashing_update_interval", "max_velocity", // Particle Renderer "renderer", "render_queue_group", "sorting", "texture_coords_define", "texture_coords_rows", "texture_coords_set", "texture_coords_columns", "use_soft_particles", "soft_particles_contrast_power", "soft_particles_scale", "soft_particles_delta", // Particle Emitter "emitter", "direction", "orientation", "range_start_orientation", "range_end_orientation", "start_orientation_range", "end_orientation_range", "duration", "repeat_delay", "emits", "angle", "emission_rate", "time_to_live", "mass", "start_texture_coords", "end_texture_coords", "start_texture_coords_range", "end_texture_coords_range", "texture_coords", "start_colour_range", "end_colour_range", "colour", "all_particle_dimensions", "particle_width", "particle_height", "particle_depth", "auto_direction", "force_emission", // Particle Affector "affector", "mass_affector", "exclude_emitter", "affect_specialisation", "special_default", "special_ttl_increase", "special_ttl_decrease", // Particle Observer "observer", "observe_particle_type", "observe_interval", "observe_until_event", // Particle Event Handler "handler", // Particle Behaviour "behaviour", // Extern "extern", "attachable_distance_threshold", // Dynamic Attribute "control_point", "min", "max", "oscillate_frequency", "oscillate_phase", "oscillate_base", "oscillate_amplitude", "oscillate_type", "dyn_oscillate", "dyn_random", "dyn_curved_linear", "dyn_curved_spline", "sine", "square", // CameraDependency (unused) "camera_dependency", // ------------------------- Renderers ------------------------- // BeamRenderer "beam_update_interval", "beam_max_elements", "beam_deviation", "beam_number_segments", "beam_jump_segments", "beam_texcoord_direction", "beam_vertex_colours", "tcd_u", "tcd_v", // BillboardRenderer "billboard_type", "billboard_origin", "billboard_rotation_type", "common_direction", "common_up_vector", "point_rendering", "accurate_facing", "oriented_common", "oriented_self", "oriented_shape", "perpendicular_common", "perpendicular_self", "top_left", "top_center", "top_right", "center_left", "center_right", "center", "bottom_left", "bottom_center", "bottom_right", "texcoord", // BoxRenderer: No properties itself // EntityRenderer "entity_renderer_mesh_name", "entity_orientation_type", "ent_oriented_self", "ent_oriented_self_mirrored", "ent_oriented_shape", // LightRenderer "light_renderer_light_type", "light_renderer_queue_group", "light_renderer_specular", "light_renderer_att_range", "light_renderer_att_constant", "light_renderer_att_linear", "light_renderer_att_quadratic", "light_renderer_spot_inner", "light_renderer_spot_outer", "light_renderer_falloff", "light_renderer_powerscale", "spot", "flash_frequency", "flash_length", "flash_random", // RibbonTrailRenderer "ribbontrail_vertex_colours", "ribbontrail_max_elements", "ribbontrail_length", "ribbontrail_width", "ribbontrail_random_initial_colour", "ribbontrail_initial_colour", "ribbontrail_colour_change", // SphereRenderer: No properties itself // ------------------------- Emitters ------------------------- // BoxEmitter "box_em_width", "box_em_height", "box_em_depth", // CircleEmitter "circle_em_radius", "circle_em_step", "circle_em_angle", "circle_em_random", "emit_random", "circle_em_normal", // LineEmitter "line_em_end", "line_em_max_increment", "line_em_min_increment", "line_em_max_deviation", // MeshSurfaceEmitter "mesh_surface_mesh_name", "mesh_surface_distribution", "mesh_surface_scale", "edge", "heterogeneous_1", "heterogeneous_2", "homogeneous", // PointEmitter: No properties itself // PositionEmitter "add_position", "random_position", // SlaveEmitter "master_technique_name", "master_emitter_name", // SphereSurfaceEmitter "sphere_surface_em_radius", // VertexEmitter "vertex_em_step", "vertex_em_segments", "vertex_em_iterations", "vertex_em_mesh_name", // ------------------------- Affectors ------------------------- // AlignAffector "align_aff_resize", "resize", // BoxCollider "box_collider_width", "box_collider_height", "box_collider_depth", // BaseCollider "friction", "bouncyness", "intersection", "collision_friction", "collision_bouncyness", "collision_intersection", "collision_type", "bounce", "flow", "none", "point", "box", "inner_collision", // CollisionAvoidanceAffector "avoidance_radius", // ColourAffector "time_colour", "colour_aff_time_colour", "colour_operation", "multiply", "set", // FlockCenteringAffector: No properties itself // BaseForceAffector "force_vector", "force_application", "force_aff_vector", "force_aff_application", "add", "average", // ForceFieldAffector "forcefield_type", "realtime", "matrix", "delta", "force", "octaves", "frequency", "amplitude", "persistence", "forcefield_size", "worldsize", "ignore_negative_x", "ignore_negative_y", "ignore_negative_z", "movement", "movement_frequency", // GeometryRotator "geom_rot_use_own_rotation", "geom_rot_rotation_speed", "geom_rot_axis", // GravityAffector "gravity", // InterParticleCollider "adjustment", "collision_response", "ip_adjustment", "ip_collision_response", "average_velocity", "angle_based_velocity", // JetAffector "jet_aff_accel", // LineAffector "end", "drift", "line_aff_max_deviation", "line_aff_time_step", "line_aff_end", "line_aff_drift", // LinearForceAffector: No properties itself // ParticleFollower "follower_max_distance", "follower_min_distance", "max_distance", "min_distance", // PathFollower "path_follower_point", // PlaneCollider "plane_collider_normal", // Randomiser "rand_aff_max_deviation_x", "rand_aff_max_deviation_y", "rand_aff_max_deviation_z", "max_deviation_x", "max_deviation_y", "max_deviation_z", "rand_aff_time_step", "rand_aff_direction", "use_direction", // ScaleAffector "xyz_scale", "x_scale", "y_scale", "z_scale", // SineForceAffector "sinef_aff_frequency_min", "sinef_aff_frequency_max", "min_frequency", "max_frequency", // SphereCollider "sphere_collider_radius", // TextureAnimator "time_step_animation", "texture_coords_start", "texture_coords_end", "start_texture_coords_range", "end_texture_coords_range", "texture_animation_type", "texture_start_random", "loop", "up_down", "random", // TextureRotator "tex_rot_use_own_rotation", "tex_rot_speed", "tex_rot_rotation", // VelocityMatchingAffector "velocity_matching_radius", // VortexAffector "vortex_aff_vector", "vortex_aff_speed", // ------------------------- Observers ------------------------- // OnClearObserver: No properties itself // OnCollisionObserver: No properties itself // OnCountObserver "count_threshold", // OnEmissionObserver: No properties itself // OnEventFlagObserver "event_flag", // OnExpireObserver: No properties itself // OnPositionObserver "position_x", "position_y", "position_z", // OnQuotaObserver: No properties itself // OnRandomObserver "random_threshold", // OnTimeObserver "on_time", "since_start_system", // OnVelocityObserver "velocity_threshold", // ------------------------- Event Handlers ------------------------- // DoAffectorEventHandler "force_affector", "pre_post", // DoEnableComponentEventHandler "enable_component", "emitter_component", "affector_component", "technique_component", "observer_component", // DoExpireEventHandler: No properties itself // DoFreezeEventHandler: No properties itself // DoPlacementParticleEventHandler "force_emitter", "number_of_particles", // DoScaleEventHandler "scale_fraction", "scale_type", "st_time_to_live", "st_velocity", // DoStopSystemEventHandler: No properties itself // ------------------------- Behaviours ------------------------- // SlaveBehaviour: No properties itself // ------------------------- Externs ------------------------- // BoxColliderExtern: Defined in BoxCollider // GravityExtern: Defined in GravityAffector // PhysXActorExtern "physx_shape", "physx_actor_group", "physx_shape_group", "physx_group_mask", "physx_angular_velocity", "physx_angular_damping", "physx_material_index", "shape", "actor_group", "shape_group", "angular_velocity", "angular_damping", "material_index", "Box", "Sphere", "Capsule", // PhysXFluidExtern "rest_particles_per_meter", "rest_density", "kernel_radius_multiplier", "motion_limit_multiplier", "collision_distance_multiplier", "packet_size_multiplier", "stiffness", "viscosity", "surface_tension", "damping", "external_acceleration", "restitution_for_static_shapes", "dynamic_friction_for_static_shapes", "static_friction_for_static_shapes", "attraction_for_static_shapes", "restitution_for_dynamic_shapes", "dynamic_friction_for_dynamic_shapes", "static_friction_for_dynamic_shapes", "attraction_for_dynamic_shapes", "collision_response_coefficient", "collision_group", "simulation_method", "collision_method", "flags", "visualization", "disable_gravity", "collision_twoway", "fluid_enabled", "hardware", "priority_mode", "project_to_plane", "strict_cooking_format", "intercollision", "no_intercollision", "mix_intercollision", "static", "dynamic", // SceneDecoratorExtern "scene_mesh_name", "scene_material_name", "scene_node_scale", "scene_node_position", // SphereColliderExtern: Defined in SphereCollider // VortexExtern: Defined in VortexAffector }; /** ScriptTranslator subclasses the Ogre::ScriptTranslator and adds some plumbing functions. */ class _ParticleUniverseExport ScriptTranslator : public Ogre::ScriptTranslator { public: // Define validation types enum ValidationType { VAL_REAL, VAL_BOOL, VAL_UINT, VAL_INT, VAL_STRING, VAL_VECTOR2, VAL_VECTOR3, VAL_VECTOR4, VAL_COLOURVALUE, VAL_QUATERNION }; ScriptTranslator(void); virtual ~ScriptTranslator(void){}; /** @See Ogre::ScriptTranslator */ virtual void translate(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { // No own implementation }; /** Only parses a certain child property */ virtual bool translateChildProperty(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { // No own implementation return false; }; /** Only parses a certain child objec */ virtual bool translateChildObject(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { // No own implementation return false; }; /** Parse Vector2 */ bool getVector2(Ogre::AbstractNodeList::const_iterator i, Ogre::AbstractNodeList::const_iterator end, Ogre::Vector2* result, int maxEntries = 2); /** Parse Vector3 */ bool getVector3(Ogre::AbstractNodeList::const_iterator i, Ogre::AbstractNodeList::const_iterator end, Ogre::Vector3* result, int maxEntries = 3); /** Parse Vector4 */ bool getVector4(Ogre::AbstractNodeList::const_iterator i, Ogre::AbstractNodeList::const_iterator end, Ogre::Vector4* result, int maxEntries = 4); /** Parse Quaternion */ bool getQuaternion(Ogre::AbstractNodeList::const_iterator i, Ogre::AbstractNodeList::const_iterator end, Ogre::Quaternion* result, int maxEntries = 4); /** Validate a property. */ bool passValidateProperty(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop, const Ogre::String& token, ValidationType validationType); /** Validate whether a property has values. */ bool passValidatePropertyNoValues(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop, const Ogre::String& token); /** Validate whether the number of values is correct. */ bool passValidatePropertyNumberOfValues(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop, const Ogre::String& token, Ogre::ushort numberOfValues); /** Validate whether the number of values is between a range. */ bool passValidatePropertyNumberOfValuesRange(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop, const Ogre::String& token, Ogre::ushort minNumberOfValues, Ogre::ushort maxNumberOfValues); /** Validate whether the value is a correct Ogre::Real. */ bool passValidatePropertyValidReal(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop); /** Validate whether the value is a correct int. */ bool passValidatePropertyValidInt(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop); /** Validate whether the value is a correct uint. */ bool passValidatePropertyValidUint(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop); /** Validate whether the value is a correct bool. */ bool passValidatePropertyValidBool(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop); /** Validate whether the value is a correct Vector2. */ bool passValidatePropertyValidVector2(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop); /** Validate whether the value is a correct Vector3. */ bool passValidatePropertyValidVector3(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop); /** Validate whether the value is a correct Vector4. */ bool passValidatePropertyValidVector4(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop); /** Validate whether the value is a correct Quaternion. */ bool passValidatePropertyValidQuaternion(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop); /** Adds an error to the compiler: An unknown token is read. */ void errorUnexpectedToken(Ogre::ScriptCompiler* compiler, Ogre::AbstractNodePtr node); /** Adds an error to the compiler: An unknown property is read. */ void errorUnexpectedProperty(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop); }; } #endif
[ [ [ 1, 1283 ] ] ]
d98e1669d71323b7fac7e597993a09126ad292b5
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/geometries/mesh_view_3/Mesh_polar_vertex_base.h
81ec66a058d6c22ad4759f9e1a490fdbf80c8370
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
861
h
#ifndef MESECINA_POLAR_MESH_VERTEX_BASE_H #define MESECINA_POLAR_MESH_VERTEX_BASE_H #include <CGAL/Triangulation_vertex_base_3.h> template < class GT, class Vb = CGAL::Triangulation_vertex_base_3<GT> > class Mesh_polar_vertex_base : public Vb { public: typedef typename Vb::Cell_handle Cell_handle; typedef typename Vb::Point Point; template < class TDS2 > struct Rebind_TDS { typedef typename Vb::template Rebind_TDS<TDS2>::Other Vb2; typedef Mesh_polar_vertex_base<GT, Vb2> Other; }; Mesh_polar_vertex_base() { mesh_pole = 0;} Mesh_polar_vertex_base(const Point& p) : Vb(p) { mesh_pole = 0; } Mesh_polar_vertex_base(const Point& p, Cell_handle c) : Vb(p, c) { mesh_pole = 0; } Cell_handle mesh_pole; }; #endif //MESECINA_POLAR_MESH_VERTEX_BASE_H
[ "balint.miklos@localhost" ]
[ [ [ 1, 31 ] ] ]
a73799fc6c9681277f611a31adaded3b29c3c9f6
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/bsktball.h
91d6a340a0c67dcf189dea943d3a00cca345f339
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,679
h
/************************************************************************* Atari Basketball hardware *************************************************************************/ #include "sound/discrete.h" /* Discrete Sound Input Nodes */ #define BSKTBALL_NOTE_DATA NODE_01 #define BSKTBALL_CROWD_DATA NODE_02 #define BSKTBALL_NOISE_EN NODE_03 #define BSKTBALL_BOUNCE_EN NODE_04 class bsktball_state : public driver_device { public: bsktball_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ UINT8 * m_videoram; UINT8 * m_motion; /* video-related */ tilemap_t *m_bg_tilemap; /* misc */ UINT32 m_nmi_on; int m_i256v; /* input-related */ int m_ld1; int m_ld2; int m_dir0; int m_dir1; int m_dir2; int m_dir3; int m_last_p1_horiz; int m_last_p1_vert; int m_last_p2_horiz; int m_last_p2_vert; }; /*----------- defined in machine/bsktball.c -----------*/ WRITE8_HANDLER( bsktball_nmion_w ); INTERRUPT_GEN( bsktball_interrupt ); WRITE8_HANDLER( bsktball_ld1_w ); WRITE8_HANDLER( bsktball_ld2_w ); READ8_HANDLER( bsktball_in0_r ); WRITE8_HANDLER( bsktball_led1_w ); WRITE8_HANDLER( bsktball_led2_w ); /*----------- defined in audio/bsktball.c -----------*/ WRITE8_DEVICE_HANDLER( bsktball_bounce_w ); WRITE8_DEVICE_HANDLER( bsktball_note_w ); WRITE8_DEVICE_HANDLER( bsktball_noise_reset_w ); DISCRETE_SOUND_EXTERN( bsktball ); /*----------- defined in video/bsktball.c -----------*/ VIDEO_START( bsktball ); SCREEN_UPDATE( bsktball ); WRITE8_HANDLER( bsktball_videoram_w );
[ "Mike@localhost" ]
[ [ [ 1, 72 ] ] ]
6d6cb98c20f050301d946c37855472031bd24076
8258620cb8eca7519a58dadde63e84f65d99cc80
/sandbox/dani/open_GL_examples/camera_with_robot/robot.cpp
c2964dcf5fbaf38020f118454b99f4de4899b7ff
[]
no_license
danieleferro/3morduc
bfdf4c296243dcd7c5ba5984bc899001bf74732b
a27901ae90065ded879f5dd119b2f44a2933c6da
refs/heads/master
2016-09-06T06:02:39.202421
2011-03-23T08:51:56
2011-03-23T08:51:56
32,210,720
0
0
null
null
null
null
UTF-8
C++
false
false
3,645
cpp
#include "robot.h" void PaintCylinder(GLfloat radius,GLfloat height); void PaintDisk(GLfloat radius); Robot::Robot(float x, float y, float theta) { radius = y; this->x = x; this->y = y; this->theta = theta; this->x_zero = 0; this->y_zero = 0; this->theta_zero = 0; } void Robot::Place(GLfloat new_x, GLfloat new_y, GLfloat new_theta) { this->x = new_x - x_zero; this->y = new_y - y_zero; this->theta = new_theta - theta_zero; } void Robot::DrawRobot() { std::cout << "Robot in: \t" << x << "; " << y << "; " << theta * 180 / M_PI << std::endl; GLfloat reflectance_black[] = { 0.2f, 0.2f, 0.2f}; GLfloat reflectance_white[] = { 0.8f, 0.8f, 0.8f}; GLfloat cosine, sine; //glMatrixMode(GL_MODELVIEW); glPushMatrix(); //glLoadIdentity(); // set robot height glTranslatef(0.0f, -12.0f, 0.0f); // set robot reflectance (it is black) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, reflectance_black); // set robot position glTranslatef(this->x, 0.0f, this->y); glRotatef(-(this->theta) * 180 / M_PI, 0.0f, 1.0f, 0.0f); // compute theta's cosine and sine value cosine = cos(this->theta); sine = sin(this->theta); // translate on z axis glTranslatef(0.0f,0.08f,0.0f); glScalef(radius, radius, radius); // draw robot PaintCylinder(1.0f, 0.1); PaintDisk(-1.0f); glTranslatef(0.0f, 0.1f, 0.0f); PaintDisk(1.0f); glTranslatef(0.0f, 0.6f, 0.0f); PaintCylinder(1.0f, 0.1f); PaintDisk(-1.0f); glTranslatef(0.0f, 0.1f, 0.0f); PaintDisk(1.0f); glTranslatef(0.8f, 0.0f, 0.0f); glColor3f(0.5f, 0.5f, 0.5f); PaintCylinder(0.2f, 0.3f); glTranslatef(0.0f, 0.3f, 0.0f); PaintDisk(0.2f); glTranslatef(0,0.401,0); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, reflectance_white); PaintDisk(0.1f); glTranslatef(0,-0.701,0); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, reflectance_black); glTranslatef(-0.8f, 0.0f, 0.0f); glColor3f(0.1f, 0.1f, 0.1f); glTranslatef(0.0f ,0.6f, 0.0f); PaintCylinder(1.0f, 0.1f); PaintDisk(-1.0f); glTranslatef(0.0f, 0.1f, 0.0f); PaintDisk(1.0f); glTranslatef(0.0f, -1.5f, 0.0f); glTranslatef(0.0f, 0.0f, 0.8f); PaintCylinder(0.1f, 1.5f); glTranslatef(0.0f, 0.0f, -1.60f); PaintCylinder(0.1f, 1.5f); glTranslatef(-0.8f, 0.0f, 0.8f); PaintCylinder(0.1f, 1.5f); glTranslatef(0.8f, 0.0f, 0.0f); glScalef(1/radius, 1/radius, 1/radius); glPopMatrix(); } void PaintDisk(GLfloat radius) { glBegin(GL_POLYGON); float pos = -1; if (radius <= 0) pos = pos*pos; glNormal3f(0,pos,0); // glVertex3f(0,0,0); for (int k = 0; k <= 360; k++) glVertex3f(radius * cos(M_PI/180*k), 0, radius * sin(M_PI/180*k*pos)); glEnd(); } void PaintCylinder(GLfloat radius, GLfloat height) { GLfloat c[361], s[361]; glBegin(GL_QUAD_STRIP); for (int k=0;k<=360;k++) { c[k]=cos(M_PI/180*k); s[k]=sin(M_PI/180*k); glNormal3f(c[k], s[k], 0); glVertex3f(radius * c[k], 0, radius * s[k]); glVertex3f(radius * c[k], height, radius * s[k]); } for (int k=0; k<=360; k++) { glNormal3f(c[k], s[k], 0); glVertex3f(radius*c[k], height, radius*s[k]); } glEnd(); } GLfloat Robot::GetX() { return this->x; } GLfloat Robot::GetY() { return this->y; } GLfloat Robot::GetTheta() { return this->theta; } void Robot::SetInit(float x, float y, float theta) { x_zero = x; y_zero = y; theta_zero = theta; }
[ "daniele.ferro86@9b93cbac-0697-c522-f574-8d8975c4cc90" ]
[ [ [ 1, 188 ] ] ]
4e9ffe277f74943ef3b1c9f8600e358006b9477a
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/daolib/Model/MMH/EMAT.cpp
aaffae8ee28911f16360b1c1b418acd0199b281e
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
code-google-com/fbx4eclipse
110766ee9760029d5017536847e9f3dc09e6ebd2
cc494db4261d7d636f8c4d0313db3953b781e295
refs/heads/master
2016-09-08T01:55:57.195874
2009-12-03T20:35:48
2009-12-03T20:35:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,976
cpp
/********************************************************************** *< FILE: EMAT.h DESCRIPTION: MMH File Format HISTORY: *> Copyright (c) 2009, All Rights Reserved. **********************************************************************/ #include <stdafx.h> #include "GFF/GFFCommon.h" #include "GFF/GFFField.h" #include "GFF/GFFList.h" #include "GFF/GFFStruct.h" #include "MMH/MMHCommon.h" #include "MMH/EMAT.h" using namespace std; using namespace DAO; using namespace DAO::GFF; using namespace DAO::MMH; /////////////////////////////////////////////////////////////////// ShortString EMAT::type("EMAT");EMAT::EMAT(GFFStructRef owner) : impl(owner) { } unsigned long EMAT::get_emitterEmitterAttachmentType() const { return impl->GetField(GFF_MMH_EMITTER_EMITTER_ATTACHMENT_TYPE)->asUInt32(); } void EMAT::set_emitterEmitterAttachmentType(unsigned long value) { impl->GetField(GFF_MMH_EMITTER_EMITTER_ATTACHMENT_TYPE)->assign(value); } Text EMAT::get_emitterEmitterAttachmentName() const { return impl->GetField(GFF_MMH_EMITTER_EMITTER_ATTACHMENT_NAME)->asECString(); } void EMAT::set_emitterEmitterAttachmentName(const Text& value) { impl->GetField(GFF_MMH_EMITTER_EMITTER_ATTACHMENT_NAME)->assign(value); } unsigned char EMAT::get_emitterEmitterAttachmentSpawnOnSurface() const { return impl->GetField(GFF_MMH_EMITTER_EMITTER_ATTACHMENT_SPAWN_ON_SURFACE)->asUInt8(); } void EMAT::set_emitterEmitterAttachmentSpawnOnSurface(unsigned char value) { impl->GetField(GFF_MMH_EMITTER_EMITTER_ATTACHMENT_SPAWN_ON_SURFACE)->assign(value); } unsigned char EMAT::get_emitterEmitterAttachmentUseNormalForVelocity() const { return impl->GetField(GFF_MMH_EMITTER_EMITTER_ATTACHMENT_USE_NORMAL_FOR_VELOCITY)->asUInt8(); } void EMAT::set_emitterEmitterAttachmentUseNormalForVelocity(unsigned char value) { impl->GetField(GFF_MMH_EMITTER_EMITTER_ATTACHMENT_USE_NORMAL_FOR_VELOCITY)->assign(value); }
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 58 ] ] ]
ab4ab40584455b45e1afa4d1a1b1f3beed7469e7
b22c254d7670522ec2caa61c998f8741b1da9388
/Server/LBA_Server/ClientSessionManagerServant.h
3bad9f0ea4f3749235dcca13e6bc54011f6984b5
[]
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
1,792
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/>. ----------------------------------------------------------------------------- */ #ifndef _CLIENT_SESSION_MANAGER_SERVANT_H #define _CLIENT_SESSION_MANAGER_SERVANT_H #include <Ice/Ice.h> #include <Glacier2/Session.h> #include <RoomManager.h> #include <ConnectedTracker.h> #include <MapManager.h> #include "DatabaseHandler.h" class ClientSessionManagerServant : public Glacier2::SessionManager { public: ClientSessionManagerServant(const Ice::CommunicatorPtr& communicator, DatabaseHandler & dbh); ~ClientSessionManagerServant(); virtual Glacier2::SessionPrx create(const std::string & userId,const Glacier2::SessionControlPrx &, const Ice::Current &current); private: LbaNet::RoomManagerPrx _manager; LbaNet::ConnectedTrackerPrx _ctracker; LbaNet::MapManagerPrx _map_manager; std::string _version; DatabaseHandler & _dbh; }; #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 56 ] ] ]
e9c18f8a895c75c24f8b65529d8cd9411b6f3c23
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nphysics/src/nphysics/nphygeomplane_main.cc
e9b0ab51e46b4069ab2578c514038d93418b8e32
[]
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
5,772
cc
//----------------------------------------------------------------------------- // nphygeomplane_main.cc // (C) 2005 Conjurer Services, S.A. //----------------------------------------------------------------------------- #include "precompiled/pchnphysics.h" #include "nphysics/nphygeomplane.h" #ifndef NGAME #include "nphysics/nphysicsserver.h" #endif //----------------------------------------------------------------------------- nNebulaScriptClass(nPhyGeomPlane, "nphysicsgeom"); //----------------------------------------------------------------------------- /** Constructor history: - 12-Jan-2005 Zombie created */ nPhyGeomPlane::nPhyGeomPlane() : planeequation( 0, 0, 0, 0 ) { this->type = InfinitePlane; this->Create(); } //----------------------------------------------------------------------------- /** Destructor history: - 12-Jan-2005 Zombie created */ nPhyGeomPlane::~nPhyGeomPlane() { // Empty } //----------------------------------------------------------------------------- /** Creates the geometry history: - 12-Jan-2005 Zombie created */ void nPhyGeomPlane::Create() { n_assert2( this->Id() == NoValidID, "Attempting to create an already created geometry" ); geomID = phyCreatePlane( planeequation ); n_assert2( this->Id() != NoValidID, "Error creating a geometry" ); nPhysicsGeom::Create(); } //----------------------------------------------------------------------------- /** Sets the position of this geometry (doesn't affect). @param newposition new geometry position history: - 12-Jan-2005 Zombie created */ void nPhyGeomPlane::SetPosition( const vector3& /*newposition*/ ) { // Empty } //----------------------------------------------------------------------------- /** Returns current position. @param position world position history: - 12-Jan-2005 Zombie created */ void nPhyGeomPlane::GetPosition( vector3& position ) const { position.x = this->GetEquation().x * this->GetEquation().w; position.y = this->GetEquation().y * this->GetEquation().w; position.z = this->GetEquation().z * this->GetEquation().w; } #ifndef NGAME //----------------------------------------------------------------------------- /** Draws the plane. history: - 12-Jan-2005 Zombie created */ void nPhyGeomPlane::Draw( nGfxServer2* server ) { nPhysicsGeom::Draw( server ); if( !(nPhysicsServer::Instance()->GetDraw() & nPhysicsServer::phyShapes) ) return; if( nPhysicsServer::Instance()->isDrawingAlphaShapes() == false ) { nPhysicsServer::Instance()->ListAlphaShapes().PushBack(this); return; } if( this->DrawShape() ) { vector3 position( this->GetEquation().x*this->GetEquation().w-.0005f, this->GetEquation().y*this->GetEquation().w-.0005f, this->GetEquation().z*this->GetEquation().w-.0005f ); matrix33 orientation; orientation.rotate( vector3( -this->GetEquation().z, 0, this->GetEquation().x ), acos( this->GetEquation().y ) ); matrix44 transform; transform.set( orientation.x_component(), orientation.y_component(), orientation.z_component(), vector3(0,0,0) ); transform.M14 = 0; transform.M24 = 0; transform.M34 = 0; transform.M44 = 1; matrix44 model; vector3 lengths( 100000.0f, 0.01f, 100000.0f ); model.scale( vector3( lengths.x,lengths.y , lengths.z) ); model = model * transform; model.translate( position ); server->BeginShapes(); int col1(int(reinterpret_cast<size_t>(this)) & 0x0f); int col2((int(reinterpret_cast<size_t>(this)) & 0xf0) >> 4); server->DrawShape( nGfxServer2::Box, model, vector4(0.0f, col1/16.0f, col2/16.0f, 0.5f ) ); server->EndShapes(); } } #endif //----------------------------------------------------------------------------- /** Sets plane equation. @param equation plane equation coeficients history: - 12-Jan-2005 Zombie created */ void nPhyGeomPlane::SetEquation( const vector4& equation ) { n_assert2( this->Id() != NoValidID, "Error the plane hasn't been created" ); // testing that the plane normal has lenght one. vector3 planeNormal( equation.x, equation.y, equation.z ); planeNormal.norm(); vector4 equationPlane( planeNormal.x, planeNormal.y, planeNormal.z, equation.w ); this->planeequation = equationPlane; phyPlaneSetEquation( this->Id(), equationPlane ); } //----------------------------------------------------------------------------- /** Sets the orientation of this geometry (doesn't affect). @param neworientation matrix new orientation history: - 08-Aug-2005 Zombie created */ void nPhyGeomPlane::SetOrientation( const matrix33& /*neworientation*/) { // Empty } //----------------------------------------------------------------------------- /** Returns current orientation (doesn't affect). @param orientation matrix orientation history: - 08-Aug-2005 Zombie created */ void nPhyGeomPlane::GetOrientation( matrix33& /*orientation*/) const { // Empty } //----------------------------------------------------------------------------- // EOF //-----------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 211 ] ] ]
c654e136cf37f90dfdca814292d5aae7313e2884
9f2d447c69e3e86ea8fd8f26842f8402ee456fb7
/shooting2011/shooting2011/main_bak.cpp
17be7585352f43c4fbc1887fcdd0e8c77b1ab203
[]
no_license
nakao5924/projectShooting2011
f086e7efba757954e785179af76503a73e59d6aa
cad0949632cff782f37fe953c149f2b53abd706d
refs/heads/master
2021-01-01T18:41:44.855790
2011-11-07T11:33:44
2011-11-07T11:33:44
2,490,410
0
1
null
null
null
null
SHIFT_JIS
C++
false
false
979
cpp
/* #include "main.h" #include "shooting.h" // WinMain関数 int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { // 画面モードの設定 ChangeWindowMode(true); SetGraphMode( WINDOW_WIDTH, WINDOW_HEIGHT, 16 ) ; // DXライブラリ初期化処理 if( DxLib_Init() == -1 ) return -1; // グラフィックの描画先を裏画面にセット SetDrawScreen( DX_SCREEN_BACK ); Shooting shooting; // 移動ルーチン while( 1 ){ shooting.action(); // Windows 特有の面倒な処理をDXライブラリにやらせる // -1 が返ってきたらループを抜ける if( ProcessMessage() < 0 ) break ; // もしESCキーが押されていたらループから抜ける if( CheckHitKey( KEY_INPUT_ESCAPE ) ) break; } DxLib_End(); // DXライブラリ使用の終了処理 return 0; // ソフトの終了 } */
[ [ [ 1, 34 ] ], [ [ 35, 35 ] ] ]
45ac7fc279c9085f574414117a6e770408230203
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/plugins/onepad/Linux/ini.cpp
3f59932e5eab74850e910bfcf9c1cfb336719a23
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
4,011
cpp
/* OnePAD - author: arcum42(@gmail.com) * Copyright (C) 2009 * * Based on ZeroPAD, author [email protected] * Copyright (C) 2006-2007 * * 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 */ #include <string.h> #include <gtk/gtk.h> #include "joystick.h" #include "onepad.h" #include "linux.h" extern char* KeysymToChar(int keysym); extern std::string s_strIniPath; string KeyName(int pad, int key) { string tmp; KeyType k = type_of_key(pad, key); switch (k) { case PAD_KEYBOARD: { char* pstr = KeysymToChar(pad_to_key(pad, key)); if (pstr != NULL) tmp = pstr; break; } case PAD_JOYBUTTONS: { int button = key_to_button(pad, key); tmp.resize(28); sprintf(&tmp[0], "JBut %d", button); break; } case PAD_JOYSTICK: { int axis = key_to_axis(pad, key); tmp.resize(28); sprintf(&tmp[0], "JAxis %d", axis); break; } case PAD_HAT: { int axis = key_to_axis(pad, key); tmp.resize(28); switch(key_to_hat_dir(pad, key)) { case SDL_HAT_UP: sprintf(&tmp[0], "JPOVU-%d", axis); break; case SDL_HAT_RIGHT: sprintf(&tmp[0], "JPOVR-%d", axis); break; case SDL_HAT_DOWN: sprintf(&tmp[0], "JPOVD-%d", axis); break; case SDL_HAT_LEFT: sprintf(&tmp[0], "JPOVL-%d", axis); break; } break; } case PAD_POV: { tmp.resize(28); sprintf(&tmp[0], "JPOV %d%s", key_to_axis(pad, key), key_to_pov_sign(pad, key) ? "-" : "+"); break; } default: break; } return tmp; } void DefaultValues() { set_key(0, PAD_L2, XK_a); set_key(0, PAD_R2, XK_semicolon); set_key(0, PAD_L1, XK_w); set_key(0, PAD_R1, XK_p); set_key(0, PAD_TRIANGLE, XK_i); set_key(0, PAD_CIRCLE, XK_l); set_key(0, PAD_CROSS, XK_k); set_key(0, PAD_SQUARE, XK_j); set_key(0, PAD_SELECT, XK_v); set_key(0, PAD_START, XK_n); set_key(0, PAD_UP, XK_e); set_key(0, PAD_RIGHT, XK_f); set_key(0, PAD_DOWN, XK_d); set_key(0, PAD_LEFT, XK_s); } void SaveConfig() { FILE *f; const std::string iniFile(s_strIniPath + "OnePAD.ini"); f = fopen(iniFile.c_str(), "w"); if (f == NULL) { printf("ZeroPAD: failed to save ini %s\n", iniFile.c_str()); return; } for (int pad = 0; pad < 2 * MAX_SUB_KEYS; pad++) { for (int key = 0; key < MAX_KEYS; key++) { fprintf(f, "[%d][%d] = 0x%lx\n", pad, key, get_key(pad,key)); } } fprintf(f, "log = %d\n", conf.log); fprintf(f, "options = %d\n", conf.options); fclose(f); } void LoadConfig() { FILE *f; char str[256]; memset(&conf, 0, sizeof(conf)); DefaultValues(); conf.log = 0; const std::string iniFile(s_strIniPath + "OnePAD.ini"); f = fopen(iniFile.c_str(), "r"); if (f == NULL) { printf("OnePAD: failed to load ini %s\n", iniFile.c_str()); SaveConfig(); //save and return return; } for (int pad = 0; pad < 2 * MAX_SUB_KEYS; pad++) { for (int key = 0; key < MAX_KEYS; key++) { sprintf(str, "[%d][%d] = 0x%%x\n", pad, key); u32 temp; if (fscanf(f, str, &temp) == 0) temp = 0; set_key(pad, key, temp); } } fscanf(f, "log = %d\n", &conf.log); fscanf(f, "options = %d\n", &conf.options); fclose(f); }
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 171 ] ] ]
cd17b9b2ff14095f62485ed3392e92af3c660aa2
073dfce42b384c9438734daa8ee2b575ff100cc9
/RCF/src/RCF/Token.cpp
93d2c474f6c5863f406e8fac32b32a9f77668e14
[]
no_license
r0ssar00/iTunesSpeechBridge
a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf
71a27a52e66f90ade339b2b8a7572b53577e2aaf
refs/heads/master
2020-12-24T17:45:17.838301
2009-08-24T22:04:48
2009-08-24T22:04:48
285,393
1
0
null
null
null
null
UTF-8
C++
false
false
3,817
cpp
//****************************************************************************** // RCF - Remote Call Framework // Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved. // Consult your license for conditions of use. // Version: 1.1 // Contact: jarl.lindrud <at> gmail.com //****************************************************************************** #include <RCF/Token.hpp> #include <SF/Archive.hpp> #include <iostream> namespace RCF { //***************************************** // Token Token::Token() : mId(RCF_DEFAULT_INIT) {} bool operator<(const Token &lhs, const Token &rhs) { return (lhs.getId() < rhs.getId()); } bool operator==(const Token &lhs, const Token &rhs) { return lhs.getId() == rhs.getId(); } bool operator!=(const Token &lhs, const Token &rhs) { return ! (lhs == rhs); } int Token::getId() const { return mId; } std::ostream &operator<<(std::ostream &os, const Token &token) { os << "( id = " << token.getId() << " )"; return os; } Token::Token(int id) : mId(id) {} #ifdef RCF_USE_SF_SERIALIZATION void Token::serialize(SF::Archive &ar, const unsigned int) { ar & mId; } #endif // TokenFactory #if defined(_MSC_VER) && _MSC_VER <= 1200 #define for if (0) {} else for #endif TokenFactory::TokenFactory(int tokenCount) : mMutex(WriterPriority) { for (int i=0; i<tokenCount; i++) { mTokenSpace.push_back( Token(i+1) ); } #if defined(_MSC_VER) && _MSC_VER < 1310 && !(defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)) //for (std::size_t i = mTokenSpace.size() - 1; i >= 0; --i) //{ // mAvailableTokens.push_back(mTokenSpace[i]); //} std::for_each( mTokenSpace.rbegin(), mTokenSpace.rend(), boost::bind( &std::vector<Token>::push_back, boost::ref(mAvailableTokens), _1)); #else mAvailableTokens.assign( mTokenSpace.rbegin(), mTokenSpace.rend() ); #endif } #if defined(_MSC_VER) && _MSC_VER <= 1200 #undef for #endif bool TokenFactory::requestToken(Token &token) { WriteLock writeLock(mMutex); RCF_UNUSED_VARIABLE(writeLock); if (mAvailableTokens.empty()) { RCF_TRACE("no more tokens available") (mAvailableTokens.size())(mTokenSpace.size()); return false; } else { Token myToken = mAvailableTokens.back(); mAvailableTokens.pop_back(); token = myToken; return true; } } void TokenFactory::returnToken(const Token &token) { // TODO: perhaps should verify that the token is part of the token // space as well... if (token != Token()) { WriteLock writeLock(mMutex); RCF_UNUSED_VARIABLE(writeLock); mAvailableTokens.push_back(token); } } const std::vector<Token> &TokenFactory::getTokenSpace() { return mTokenSpace; } std::size_t TokenFactory::getAvailableTokenCount() { ReadLock readLock( mMutex ); RCF_UNUSED_VARIABLE(readLock); return mAvailableTokens.size(); } bool TokenFactory::isAvailable(const Token & token) { ReadLock readLock( mMutex ); return std::find(mAvailableTokens.begin(), mAvailableTokens.end(), token) != mAvailableTokens.end(); } } // namespace RCF
[ [ [ 1, 155 ] ] ]
9c176058301753c2d37fa1657a82458acd7f5ecf
f5fe5f7325176b8c19ca5165da4aa5ad9714d995
/DSK-Native/trunk/DSK2.0/DSKInitParameters.h
b9dc74a0fb081d083725a945d592e9a7bb7f52be
[]
no_license
Sukumi/directshowkev2
a812e3f8bb6c7d26e4cfb5dbc5a77481c8d91882
bc4594c6642073e89b5eda78c99d9adcc2d72d3b
refs/heads/master
2021-01-01T03:54:29.040186
2011-03-06T23:31:00
2011-03-06T23:31:00
56,792,429
1
0
null
null
null
null
UTF-8
C++
false
false
498
h
#include <string> enum DSVideoRendererType { VMR7, VMR9, EVR}; enum DSGraphType {OGG, INTELIGENT_CONNECT}; class DSKInitParameters { public: DSKInitParameters(const std::string filePathIn, DSVideoRendererType videoRendererType, DSGraphType graphType); ~DSKInitParameters(); std::string getFilePath(); DSVideoRendererType getVideoRendererType(); DSGraphType getGraphType(); private: std::string filePath; DSVideoRendererType videoRendererType; DSGraphType graphType; };
[ [ [ 1, 18 ] ] ]
7379c085b76e65d0e347af5b02601226dd77160b
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/terralib/kernel/TeBaseSTInstanceSet.h
de71c7a3c1d6f9e6e3f1934683d150643c7865e7
[]
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
43,531
h
/************************************************************************************ TerraLib - a library for developing GIS applications. Copyright 2001-2007 INPE and Tecgraf/PUC-Rio. This code is part of the TerraLib library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. You should have received a copy of the GNU Lesser General Public License along with this library. 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 library 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 library and its documentation. *************************************************************************************/ /*! \file TeBaseSTInstanceSet.h \brief This file contains structures to deal with a set of spatio-temporal instances. These instances can belong to a specific layer or theme. */ #ifndef __TERRALIB_INTERNAL_STINSTANCESET_H #define __TERRALIB_INTERNAL_STINSTANCESET_H #include "TeBaseSTInstance.h" #include "TeRTree.h" #include "TeTheme.h" #include "TeLayer.h" #include "TeQuerierParams.h" #include "TeQuerier.h" #include "TeSharedPtr.h" /*! \class TeBaseSTInstanceSet \brief A abstract class that represents a set of spatial temporal instances. This abstract class implements a generic spatio-temporal instance set. It must be specialized according to the instance type (its geometry type, its time type and its own type). \sa TeBaseSTInstance TeTheme TeLayer */ template< typename GeometryType, typename TimeType, typename InstanceType > class TeBaseSTInstanceSet { protected: //! Set of spatio temporal instances vector<InstanceType> instances_; //! Minimal time associated to spatial temporal instances TimeType minTime_; //! Maximal time associated to spatial temporal instances TimeType maxTime_; //! Description of all attributes TeSharedPtr<TeAttributeList> attrList_; //! A pointer to a theme TeTheme* theme_; //! A pointer to a layer TeLayer* layer_; //! A bounding box that contains all geometries of the spatial temporal instances TeBox box_; //! A map from object identity to its associated instances in the set map<string, vector<int> > objectIdToInstances_; //! A map from time to its associated instances in the set map<TimeType, vector<int> > timeToInstances_; //! A map from slice to its associated instances in the set map<int, vector<int> > sliceToInstances_; //! A struture to index the geometries: RTree TeSAM::TeRTree<int>* rTree_; //! Builds the set using a given querier and a specific slice virtual bool buildImpl(TeQuerier* querier, const int& slide = -1) = 0; public: //! An iterator that traverse each instance in the set typedef typename vector<InstanceType>::iterator iterator; //! Constructor. It does not initialize the rTree. TeBaseSTInstanceSet(); //! Constructor. It initializes the rTree based on theme box. TeBaseSTInstanceSet(TeTheme* theme, const TeAttributeList& attrList = TeAttributeList()); //! Constructor. It initializes the rTree based on layer box. TeBaseSTInstanceSet(TeLayer* layer, const TeAttributeList& attrList = TeAttributeList()); //! Constructor. It initializes the rTree based on the given box. TeBaseSTInstanceSet(const TeBox& box, const TeAttributeList& attrList = TeAttributeList()); //! Copy constructor TeBaseSTInstanceSet (const TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>& other); //! Destructor virtual ~TeBaseSTInstanceSet(); //! Assignment operator virtual TeBaseSTInstanceSet& operator= (const TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>& other); //! Gets minimal time virtual TimeType getMinTime() { return minTime_; } //! Sets minimal time virtual void setMinTime(TimeType& t) { minTime_ = t; } //! Gets maximal time virtual TimeType getMaxTime() { return maxTime_; } //! Sets maximal time virtual void setMaxTime(TimeType& t) { maxTime_ = t; } //! Gets the attribute list, that is, the description of all attributes virtual TeAttributeList& getAttributeList() { return (*attrList_); } //! Sets the attribute list, that is, the description of all attributes virtual void setAttributeList(const TeAttributeList& attrs); //! Returns the index of an attribute named "attrName" virtual int getAttributeIndex(const string& attrName); //! Gets theme pointer virtual TeTheme* getTheme() { return theme_; } //! Sets theme pointer virtual void setTheme(TeTheme* t) { theme_ = t; } //! Deprecated: Returns a theme pointer TeTheme* theme() { return getTheme(); } //! Gets layer pointer virtual TeLayer* getLayer() { return layer_; } //! Sets layer pointer virtual void setLayer(TeLayer* l) { layer_ = l; } //! Gets a reference to the instance set virtual vector<InstanceType>& getSTInstances() { return instances_; } //! Gets a pointer to the index-th ST instance virtual InstanceType* getSTInstance(const unsigned int& index); //! Gets a pointer to a ST instance of an object in a specific slice virtual InstanceType* getSTInstance(const string& objectId, const int& slice = -1); //! Gets a pointer to a ST instance of an object in a specific time and slice virtual InstanceType* getSTInstance(const string& objectId, TimeType& time, const int& slice = -1); //! Gets pointers to all ST instances of a specific object in a specific slice virtual void getSTInstances(vector<InstanceType*>& set, const string& objectId, const int& slice = -1); //! Gets pointers to all ST instances of a specific object in a specific time and slice virtual void getSTInstances(vector<InstanceType*>& set, const string& objectId, TimeType& time, const int& slice = -1); ///! Gets pointers to all ST instances of a specific time virtual void getSTInstances(vector<InstanceType*>& set, TimeType& time, const int& slice = -1); //! Gets pointers to all ST instances of a specific slice virtual void getSTInstances(vector<InstanceType*>& set, const int& slice); //! Inserts a new ST instance in the set virtual bool insertSTInstance (InstanceType& object); //! Returns the number of instances virtual int numSTInstance(); //! Returns the number of instances of an object or element virtual int numSTInstance(const string& objectId); //! Returns the number of instances in a specific slice virtual int numSTInstance(const int& slice); //! Returns the number of instances in a specific time virtual int numSTInstance(TimeType& time); //! Returns the number of elements or objects in the set virtual int numElements() { return objectIdToInstances_.size(); } //! Sets a geometry of an object in a specific slice virtual bool setGeometry(const string& object_id, GeometryType& geom, const int& slice = -1); //! Sets a geometry of an object in a specific time and slice virtual bool setGeometry(const string& object_id, GeometryType& geom, TimeType& time, const int& slice = -1); //! Gets the geometry of an object in a specific slice virtual bool getGeometry(const string& object_id, GeometryType& geom, const int& slice = -1); //! Gets the geometry of an object in a specific time and slice virtual bool getGeometry(const string& object_id, GeometryType& geom, TimeType& time, const int& slice = -1); //! Gets a vector of attributes or properties of a object that is valid in a slice virtual bool getPropertyVector (const string& object_id, TePropertyVector& propVec, const int& slice = -1); //! Gets a vector of attributes or properties of a object that is valid in a time and slice virtual bool getPropertyVector (const string& object_id, TePropertyVector& propVec, TimeType& time, const int& slice = -1); //! Sets a vector of attribute values of a object that is valid in a slice virtual bool setProperties (const string& object_id, const vector<string>& values, const int& slice = -1); //! Sets a vector of attribute values of a object that is valid in a time and slice virtual bool setProperties (const string& object_id, const vector<string>& values, TimeType& time, const int& slice = -1); //! Gets a vector of attribute values of a object that is valid in a slice virtual bool getProperties (const string& object_id, vector<string>& values, const int& slice = -1); //! Gets a vector of attribute values of a object that is valid in a time and slice virtual bool getProperties (const string& object_id, vector<string>& values, TimeType& time, const int& slice = -1); //! Sets the value of the attribute named "attr_name" of an object that is valid in a slice virtual bool setAttributeValue (const string& object_id, const string& attr_name, const string& val, const int& slice = -1); //! Sets the value of the attribute named "attr_name" of an object that is valid in a time and slice virtual bool setAttributeValue (const string& object_id, const string& attr_name, const string& val, TimeType& time, const int& slice = -1); //! Sets the value of the i-th attribute of an object that is valid in a slice virtual bool setAttributeValue (const string& object_id, const int& i, const string& val, const int& slice = -1); //! Sets the value of the i-th attribute of an object that is valid in a time and slice virtual bool setAttributeValue (const string& object_id, const int& i, const string& val, TimeType& time, const int& slice = -1); //! Get the value of the attribute named "attr_name" of an object that is valid in a slice virtual bool getAttributeValue (const string& object_id, const string& attr_name, string& val, const int& slice = -1); //! Get the value of the attribute named "attr_name" of an object that is valid in a time and slice virtual bool getAttributeValue (const string& object_id, const string& attr_name, string& val, TimeType& time, const int& slice = -1); //! Gets the value of the i-th attribute of an object that is valid in a slice virtual bool getAttributeValue (const string& object_id, const int& i, string& val, const int& slice = -1); //! Gets the value of the i-th attribute of an object that is valid in a time and slice virtual bool getAttributeValue (const string& object_id, const int& i, string& val, TimeType& time, const int& slice = -1); //! Adds a new attribute in the attribute list and adds it in all instances in the set using a default value virtual bool addProperty(TeAttributeRep& attr, const string& defaultValue); //! Adds a new attribute only in the attribute list virtual bool addProperty(TeAttribute& attr); /*! \brief Adds the property or sets its value in the object in a valid slice. If there is already the property in the attribute list, sets the value of the instances of an object valid in a specific slice. If there is no this property in the attribute list, adds it in the attribute list and in all instances in the set. After that, sets the value of the instances of an object valid in a specific slice. */ virtual bool addProperty(const string& object_id, TeProperty& prop, const int& slice=-1); /*! \brief Adds the property or sets its value in the object in a valid time and slice. If there is already the property in the attribute list, sets the value of the instances of an object valid in a specific time and slice. If there is no this property in the attribute list, adds it in the attribute list and in all instances in the set. After that, sets the value of the instances of an object valid in a specific time and slice. */ virtual bool addProperty(const string& object_id, TeProperty& prop, TimeType& time, const int& slice = -1); //! Removes an attribute of the attribute list and removes it of all instances in the set virtual void removeProperty(TeAttributeRep& attr); //! Calculates the bounding box of all instances of all objects included in the set virtual TeBox& getBox(); //! Sets the bounding box of all instances of all objects included in the set virtual void setBox(const TeBox& b) { box_ = b; } //! Clears the set virtual void clear(); void clearInstances(); //! Returns an iterator to the first element of the set virtual iterator begin() { return instances_.begin(); } //! Returns an iterator to the one past last element of the set virtual iterator end() { return instances_.end(); } //! Searchs the instances which bounding boxes intersect a specific bounding box, using the R Tree. virtual bool search(const TeBox& b, vector<InstanceType* >& result); //! Fills the ST instance set from a layer or theme, using the given filled parameters virtual bool build(bool loadGeometries=false, bool loadAllAttributes=true, vector<string> attrNames=vector<string>(), int slide=-1); //! Fills the ST instance set from a layer or theme, using the given filled parameters virtual bool build(TeGroupingAttr& groupAttr, bool loadGeometries=false, int slide=-1); /*! \class propertyIterator \brief This class implements an iterator concept over the instance set. A structure that allows the traversal ST element set in a similar way as the STL iterators. This iterator passes over each ST instance of the ST element set and returns a specific numerical property. */ class propertyIterator { public: //! Constructor propertyIterator (TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>* setIt, typename std::vector<InstanceType>::iterator it, const string& attrName): attrName_(attrName), attrIndex_(-1), it_(it), setIt_(setIt) { attrIndex_ = setIt_->getAttributeIndex(attrName); } //! Constructor propertyIterator (TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>* setIt, typename std::vector<InstanceType>::iterator it, const int& attrIndex): attrName_ (""), attrIndex_(attrIndex), it_(it), setIt_(setIt) { } //! Constructor propertyIterator (typename vector<InstanceType>::iterator it, const int& attrIndex): attrName_ (""), attrIndex_(attrIndex), it_(it) {} //! Moves to the next attribute in the set propertyIterator& operator++() { ++it_; return (*this); } //! Returns the current attribute as double double operator*() { return (*it_)[attrIndex_]; } //! Sets a new value to the attrIndex_-th attribute of the element pointed by the iterator void setValue(const double& val) { it_->setPropertyValue(attrIndex_, Te2String(val)); } //! Returns a pointer to the instance set TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>* elemSet() { return setIt_; } //! Equal operator bool operator==(const propertyIterator& rhs) const { return (this->attrIndex_ == rhs.attrIndex_ && this->it_== rhs.it_); } //! Unequal operator bool operator!=(const propertyIterator& rhs) const { return (this->attrIndex_ != rhs.attrIndex_ || this->it_!= rhs.it_); } //! Deprecated: Returns the numerical property of the current instance. bool getProperty(TeProperty& prop) { return (*it_).getProperty(prop, attrIndex_); } protected: string attrName_; //<! the numerical property name int attrIndex_; //<! the numerical property index typename vector<InstanceType>::iterator it_; TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>* setIt_; }; //! Returns a property iterator to the attribute named "attName" of the first instance in the set. propertyIterator begin(const string& attName) { return propertyIterator(this, instances_.begin(), attName); } //! Returns a property iterator to the attIndex-th attribute of the first instance in the set. propertyIterator begin(const int& attIndex) { return propertyIterator(this, instances_.begin(), attIndex); } //! Returns a property iterator to the attribute named "attName" of the one past last element of the set propertyIterator end(const string& attName) { return propertyIterator(this, instances_.end(), attName); } //! Returns a property iterator to the attIndex-th attribute of the one past last element of the set propertyIterator end(const int& attIndex) { return propertyIterator(this, instances_.end(), attIndex); } }; template<typename GeometryType, typename TimeType, typename InstanceType> TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::TeBaseSTInstanceSet() : theme_(0), layer_(0), rTree_(0) { TeAttributeList* att = new TeAttributeList(); attrList_ = TeSharedPtr<TeAttributeList>(att); } template<typename GeometryType, typename TimeType, typename InstanceType> TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::TeBaseSTInstanceSet(TeTheme* theme, const TeAttributeList& attrList) { layer_ = 0; theme_ = 0; rTree_ = 0; TeAttributeList* att = new TeAttributeList(attrList); attrList_ = TeSharedPtr<TeAttributeList>(att); if(!theme) return; theme_ = theme; rTree_ = new TeSAM::TeRTree<int>(theme_->box()); } template<typename GeometryType, typename TimeType, typename InstanceType> TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::TeBaseSTInstanceSet(TeLayer* layer, const TeAttributeList& attrList) { layer_ = 0; theme_ = 0; rTree_ = 0; TeAttributeList* att = new TeAttributeList(attrList); attrList_ = TeSharedPtr<TeAttributeList>(att); if(!layer) return; layer_ = layer; rTree_ = new TeSAM::TeRTree<int>(layer_->box()); } template<typename GeometryType, typename TimeType, typename InstanceType> TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::TeBaseSTInstanceSet(const TeBox& box, const TeAttributeList& attrList) { layer_ = 0; theme_ = 0; rTree_ = 0; box_ = box; TeAttributeList* att = new TeAttributeList(attrList); attrList_ = TeSharedPtr< TeAttributeList >(att); if(!box_.isValid()) return; rTree_ = new TeSAM::TeRTree<int>(box); } template<typename GeometryType, typename TimeType, typename InstanceType> TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::TeBaseSTInstanceSet(const TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>& other) { instances_ = other.instances_; minTime_ = other.minTime_; maxTime_ = other.maxTime_; attrList_ = other.attrList_; theme_ = other.theme_; layer_ = other.layer_; box_ = other.box_; objectIdToInstances_ = other.objectIdToInstances_; timeToInstances_ = other.timeToInstances_; sliceToInstances_ = other.sliceToInstances_; rTree_ = 0; if(other.rTree_) { //Operador de copia nao implementado! //rTree_ = new TeSAM::TeRTree<int>(other.rTree_->getBox()); //*rTree_ = *other.rTree_; } } template<typename GeometryType, typename TimeType, typename InstanceType> TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::~TeBaseSTInstanceSet() { if(rTree_) delete rTree_; } template<typename GeometryType, typename TimeType, typename InstanceType> TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>& TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::operator= (const TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>& other) { if ( this != &other ) { instances_ = other.instances_; minTime_ = other.minTime_; maxTime_ = other.maxTime_; attrList_ = other.attrList_; theme_ = other.theme_; layer_ = other.layer_; box_ = other.box_; objectIdToInstances_ = other.objectIdToInstances_; timeToInstances_ = other.timeToInstances_; sliceToInstances_ = other.sliceToInstances_; if(rTree_) delete rTree_; rTree_ = 0; if(other.rTree_) { //Operador de copia nao implementado! //rTree_ = new TeSAM::TeRTree<int>(other.rTree_->getBox()); //*rTree_ = *other.rTree_; } } return *this; } template<typename GeometryType, typename TimeType, typename InstanceType> void TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::setAttributeList(const TeAttributeList& attrs) { if(!attrList_.isActive()) return; attrList_->clear(); TeAttributeList::const_iterator it = attrs.begin(); while(it!=attrs.end()) { attrList_->push_back(*it); ++it; } } template<typename GeometryType, typename TimeType, typename InstanceType> int TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getAttributeIndex(const string& attrName) { string newName = TeConvertToUpperCase(attrName); size_t pos = newName.find(".", 0, 1); if (pos != string::npos) newName = TeConvertToUpperCase(attrName.substr(pos+1)); for(unsigned int i=0; i<attrList_->size(); ++i) { string s = TeConvertToUpperCase((*attrList_)[i].rep_.name_); if((s == TeConvertToUpperCase(attrName)) || (s == newName)) return i; } return -1; } template<typename GeometryType, typename TimeType, typename InstanceType> InstanceType* TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getSTInstance(const unsigned int& index) { if(index<instances_.size()) return &(instances_[index]); return 0; } template<typename GeometryType, typename TimeType, typename InstanceType> InstanceType* TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getSTInstance(const string& objectId, const int& slice) { map<string, vector<int> >::iterator itObj = objectIdToInstances_.find(objectId); if(itObj==objectIdToInstances_.end()) return 0; if(slice<0) { //The slice is not considered vector<int>::iterator it = itObj->second.begin(); if(it==itObj->second.end()) return 0; return getSTInstance(*it); } map<int, vector<int> >::iterator itSlice = sliceToInstances_.find(slice); if(itSlice==sliceToInstances_.end()) return 0; vector<int>::iterator it = itObj->second.begin(); while(it != itObj->second.end()) { vector<int>::iterator it2; it2 = find(itSlice->second.begin(), itSlice->second.end(), *it); if(it2!=itSlice->second.end()) return getSTInstance(*it2); ++it; } return 0; } template<typename GeometryType, typename TimeType, typename InstanceType> InstanceType* TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getSTInstance(const string& objectId, TimeType& time, const int& slice) { map<string, vector<int> >::iterator itObj = objectIdToInstances_.find(objectId); if(itObj==objectIdToInstances_.end()) return 0; typename map<TimeType, vector<int> >::iterator itTime = timeToInstances_.find(time); if(itTime==timeToInstances_.end()) return 0; if(slice<0) { //The slice is not considered vector<int>::iterator it = itObj->second.begin(); while(it != itObj->second.end()) { vector<int>::iterator it2; it2 = find(itTime->second.begin(), itTime->second.end(), *it); if(it2!=itTime->second.end()) return getSTInstance(*it2); ++it; } return 0; } map<int, vector<int> >::iterator itSlice = sliceToInstances_.find(slice); if(itSlice==sliceToInstances_.end()) return 0; vector<int>::iterator it = itObj->second.begin(); while(it != itObj->second.end()) { vector<int>::iterator it2, it3; it2 = find(itTime->second.begin(), itTime->second.end(), *it); it3 = find(itSlice->second.begin(), itSlice->second.end(), *it); if((it2!=itTime->second.end()) && (it3!=itSlice->second.end())) return getSTInstance(*it2); ++it; } return 0; } template<typename GeometryType, typename TimeType, typename InstanceType> void TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getSTInstances(vector<InstanceType* >& set, const string& objectId, const int& slice) { set.clear(); map<string, vector<int> >::iterator itObj = objectIdToInstances_.find(objectId); if(itObj==objectIdToInstances_.end()) return; vector<int>::iterator it = itObj->second.begin(); while(it != itObj->second.end()) { InstanceType* inst = getSTInstance(*it); if((slice<0) || (inst->getSlice()==slice)) set.push_back(inst); ++it; } return; } template<typename GeometryType, typename TimeType, typename InstanceType> void TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getSTInstances(vector<InstanceType* >& set, const string& objectId, TimeType& time, const int& slice) { set.clear(); map<string, vector<int> >::iterator itObj = objectIdToInstances_.find(objectId); if(itObj==objectIdToInstances_.end()) return; vector<int>::iterator it = itObj->second.begin(); while(it != itObj->second.end()) { InstanceType* inst = getSTInstance(*it); if(((slice<0) || (inst->getSlice()==slice)) && (inst->getTime()== time)) set.push_back(inst); ++it; } return; } template<typename GeometryType, typename TimeType, typename InstanceType> void TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getSTInstances(vector<InstanceType* >& set, TimeType& time, const int& slice) { set.clear(); typename map<TimeType, vector<int> >::iterator itTime = timeToInstances_.find(time); if(itTime==timeToInstances_.end()) return; vector<int>::iterator it = itTime->second.begin(); while(it != itTime->second.end()) { InstanceType* inst = getSTInstance(*it); if((slice<0) || (inst->getSlice()==slice)) set.push_back(inst); ++it; } return; } template<typename GeometryType, typename TimeType, typename InstanceType> void TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getSTInstances(vector<InstanceType* >& set, const int& slice) { set.clear(); map<int, vector<int> >::iterator itSlice = sliceToInstances_.find(slice); if(itSlice==sliceToInstances_.end()) return; vector<int>::iterator it = itSlice->second.begin(); while(it != itSlice->second.end()) { set.push_back(getSTInstance(*it)); ++it; } return; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::insertSTInstance (InstanceType& inst) { inst.setAttrList(attrList_); instances_.push_back(inst); int index = (instances_.size()-1); vector<int> aux; aux.push_back(index); //object identity information map<string, vector<int> >::iterator itObj = objectIdToInstances_.find(inst.getObjectId()); if(itObj!=objectIdToInstances_.end()) itObj->second.push_back(index); else objectIdToInstances_[inst.getObjectId()] = aux; //time information if(inst.isTimeValid()) { typename map<TimeType, vector<int> >::iterator itTime = timeToInstances_.find(inst.getTime()); if(itTime!=timeToInstances_.end()) itTime->second.push_back(index); else timeToInstances_[inst.getTime()] = aux; } //slice information if(inst.getSlice()>=0) { map<int, vector<int> >::iterator itSlice = sliceToInstances_.find(inst.getSlice()); if(itSlice!=sliceToInstances_.end()) itSlice->second.push_back(index); else sliceToInstances_[inst.getSlice()] = aux; } //insert in the RTree TeBox b = inst.getGeometries().box(); if(b.isValid()) { if(rTree_) rTree_->insert(b, index); updateBox(box_, b); } return true; } template<typename GeometryType, typename TimeType, typename InstanceType> int TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::numSTInstance() { return instances_.size(); } template<typename GeometryType, typename TimeType, typename InstanceType> int TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::numSTInstance(const string& objectId) { map<string, vector<int> >::iterator it = objectIdToInstances_.find(objectId); if(it==objectIdToInstances_.end()) return 0; return it->second.size(); } template<typename GeometryType, typename TimeType, typename InstanceType> int TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::numSTInstance(const int& slice) { map<int, vector<int> >::iterator it = sliceToInstances_.find(slice); if(it==sliceToInstances_.end()) return 0; return it->second.size(); } template<typename GeometryType, typename TimeType, typename InstanceType> int TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::numSTInstance(TimeType& time) { typename map<TimeType, vector<int> >::iterator it = timeToInstances_.find(time); if(it==timeToInstances_.end()) return 0; return it->second.size(); } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::setGeometry(const string& object_id, GeometryType& geom, const int& slice) { InstanceType* aux = this->getSTInstance(object_id, slice); if(!aux) return false; aux->setGeometry(geom); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::setGeometry(const string& object_id, GeometryType& geom, TimeType& time, const int& slice) { InstanceType* aux = this->getSTInstance(object_id, time, slice); if(!aux) return false; aux->setGeometry(geom); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getGeometry(const string& object_id, GeometryType& geom, const int& slice) { InstanceType* aux = this->getSTInstance(object_id, slice); if(!aux) return false; geom = aux->getGeometries(); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getGeometry(const string& object_id, GeometryType& geom, TimeType& time, const int& slice) { InstanceType* aux = this->getSTInstance(object_id, time, slice); if(!aux) return false; geom = aux->getGeometries(); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getPropertyVector (const string& object_id, TePropertyVector& propVec, const int& slice) { propVec.clear(); InstanceType* aux = this->getSTInstance(object_id, slice); if(!aux) return false; for(unsigned int i=0; i<aux->getProperties().size(); ++i) { TeProperty prop; prop.value_ = aux->getProperties()[i]; if(i<attrList_->size()) prop.attr_ = (*attrList_)[i]; propVec.push_back(prop); } return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getPropertyVector (const string& object_id, TePropertyVector& propVec, TimeType& time, const int& slice) { propVec.clear(); InstanceType* aux = this->getSTInstance(object_id, time, slice); if(!aux) return false; for(unsigned int i=0; i<aux->getProperties().size(); ++i) { TeProperty prop; prop.value_ = aux->getProperties()[i]; if(i<attrList_->size()) prop.attr_ = (*attrList_)[i]; propVec.push_back(prop); } return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::setProperties (const string& object_id, const vector<string>& values, const int& slice) { //the number of attributes in each instance must be equal to the number of attibutes //in the attribute list. if(values.size() != attrList_->size()) return false; InstanceType* aux = this->getSTInstance(object_id, slice); if(!aux) return false; aux->setProperties(values); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::setProperties (const string& object_id, const vector<string>& values, TimeType& time, const int& slice) { //the number of attributes in each instance must be equal to the number of attibutes //in the attribute list. if(values.size() != attrList_->size()) return false; InstanceType* aux = this->getSTInstance(object_id, time, slice); if(!aux) return false; aux->setProperties(values); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getProperties (const string& object_id, vector<string>& values, const int& slice) { values.clear(); InstanceType* aux = this->getSTInstance(object_id, slice); if(!aux) return false; values = aux->getProperties(); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getProperties (const string& object_id, vector<string>& values, TimeType& time, const int& slice) { values.clear(); InstanceType* aux = this->getSTInstance(object_id, time, slice); if(!aux) return false; values = aux->getProperties(); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::setAttributeValue (const string& object_id, const string& attr_name, const string& val, const int& slice) { int index = this->getAttributeIndex(attr_name); return this->setAttributeValue(object_id, index, val, slice); } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::setAttributeValue (const string& object_id, const string& attr_name, const string& val, TimeType& time, const int& slice) { int index = this->getAttributeIndex(attr_name); return this->setAttributeValue(object_id, index, val, time, slice); } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::setAttributeValue (const string& object_id, const int& i, const string& val, const int& slice) { if(i<0 || i>=(int)attrList_->size()) //if there is not this attribute, return false return false; InstanceType* aux = this->getSTInstance(object_id, slice); if(!aux) return false; aux->setPropertyValue(i, val); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::setAttributeValue (const string& object_id, const int& i, const string& val, TimeType& time, const int& slice) { if(i<0 || i>=(int)attrList_->size()) //if there is not this attribute, return false return false; InstanceType* aux = this->getSTInstance(object_id, time, slice); if(!aux) return false; aux->setPropertyValue(i, val); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getAttributeValue (const string& object_id, const string& attr_name, string& val, const int& slice) { int index = this->getAttributeIndex(attr_name); return this->getAttributeValue(object_id, index, val, slice); } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getAttributeValue (const string& object_id, const string& attr_name, string& val, TimeType& time, const int& slice) { int index = this->getAttributeIndex(attr_name); return this->getAttributeValue(object_id, index, val, time, slice); } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getAttributeValue (const string& object_id, const int& i, string& val, const int& slice) { if(i<0 || i>=(int)attrList_->size()) return false; InstanceType* aux = this->getSTInstance(object_id, slice); if(!aux) return false; val = aux->getProperties()[i]; return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getAttributeValue (const string& object_id, const int& i, string& val, TimeType& time, const int& slice) { if(i<0 || i>=(int)attrList_->size()) return false; InstanceType* aux = this->getSTInstance(object_id, time, slice); if(!aux) return false; val = aux->getProperties()[i]; return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::addProperty(TeAttributeRep& attr, const string& defaultValue) { //verify if there is this attribute if(getAttributeIndex(attr.name_)>=0) return true; TeAttribute at; at.rep_ = attr; attrList_->push_back(at); typename vector<InstanceType>::iterator it = instances_.begin(); //the number of attributes in each instance must be equal to the number of attibutes //in the attribute list. if((attrList_->size()-1) != it->getProperties().size()) return false; while(it!=instances_.end()) { it->addPropertyValue(defaultValue); ++it; } return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::addProperty(TeAttribute& attr) { //verify if there is this attribute if(getAttributeIndex(attr.rep_.name_)<0) attrList_->push_back(attr); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::addProperty(const string& object_id, TeProperty& prop, const int& slice) { int index = this->getAttributeIndex(prop.attr_.rep_.name_); if(index<0) { //adds this new attribute in the attr list and in all instances attrList_->push_back(prop.attr_); typename vector<InstanceType>::iterator it = instances_.begin(); while(it!=instances_.end()) { if( (object_id == it->getObjectId()) && ((slice<0) || (slice==it->getSlice()))) it->addPropertyValue(prop.value_); else it->addPropertyValue(string("")); ++it; } return true; } //Sets this attribute value typename vector<InstanceType>::iterator it = instances_.begin(); while(it!=instances_.end()) { if( (object_id == it->getObjectId()) && ((slice<0) || (slice==it->getSlice()))) it->setPropertyValue(index, prop.value_); ++it; } return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::addProperty(const string& object_id, TeProperty& prop, TimeType& time, const int& slice) { int index = this->getAttributeIndex(prop.attr_.rep_.name_); if(index<0) { //adds this new attribute in the attr list and in all instances attrList_->push_back(prop.attr_); typename vector<InstanceType>::iterator it = instances_.begin(); while(it!=instances_.end()) { if( (object_id == it->getObjectId()) && (time == it->getTime()) && ((slice<0) || (slice==it->getSlice()))) it->addPropertyValue(prop.value_); else it->addPropertyValue(string("")); ++it; } return true; } //Sets this attribute value typename vector<InstanceType>::iterator it = instances_.begin(); while(it!=instances_.end()) { if( (object_id == it->getObjectId()) && (time == it->getTime()) && ((slice<0) || (slice==it->getSlice()))) it->setPropertyValue(index, prop.value_); ++it; } return true; } template<typename GeometryType, typename TimeType, typename InstanceType> void TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::removeProperty(TeAttributeRep& attr) { //Remove of the attribute list string newName = TeConvertToUpperCase(attr.name_); size_t pos = attr.name_.find(".", 0, 1); if (pos != string::npos) newName = TeConvertToUpperCase(attr.name_.substr(pos+1)); unsigned int index = 0; TeAttributeList::iterator it = attrList_->begin(); while(it!=attrList_->end()) { string s = TeConvertToUpperCase(it->rep_.name_); if((s == TeConvertToUpperCase(attr.name_)) || (s == newName)) { attrList_->erase(it); break; } ++it; ++index; } //Remove of all instances typename vector<InstanceType>::iterator it2 = instances_.begin(); while(it2!=instances_.end()) { it2->removePropertyValue(index); ++it2; } } template<typename GeometryType, typename TimeType, typename InstanceType> TeBox& TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::getBox() { if(box_.isValid()) return box_; if (instances_.size() <= 0) return box_; typename TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::iterator it = this->begin(); while (it != this->end()) { updateBox(box_,it->getGeometries().box()); ++it; } return box_; } template<typename GeometryType, typename TimeType, typename InstanceType> void TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::clear() { instances_.clear(); attrList_->clear(); objectIdToInstances_.clear(); timeToInstances_.clear(); sliceToInstances_.clear(); if(rTree_) rTree_->clear(); } template<typename GeometryType, typename TimeType, typename InstanceType> void TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::clearInstances() { instances_.clear(); } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::search(const TeBox& b, vector<InstanceType* >& result) { if(!rTree_ ) return false; vector<int> intResult; rTree_->search(b, intResult); for(unsigned int i=0; i<intResult.size(); ++i) result.push_back(getSTInstance(intResult[i])); return true; } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::build(bool loadGeometries, bool loadAllAttributes, vector<string> attrNames, int slide) { TeQuerierParams param; if(theme_) param.setParams(theme_); else if(layer_) param.setParams(layer_); else return false; param.setFillParams(loadGeometries, loadAllAttributes, attrNames); TeQuerier querier(param); return(buildImpl(&querier, slide)); } template<typename GeometryType, typename TimeType, typename InstanceType> bool TeBaseSTInstanceSet<GeometryType, TimeType, InstanceType>::build(TeGroupingAttr& groupAttr, bool loadGeometries, int slide) { TeQuerierParams param; if(theme_) param.setParams(theme_); else if(layer_) param.setParams(layer_); else return false; param.setFillParams(loadGeometries, groupAttr); TeQuerier querier(param); return(buildImpl(&querier, slide)); } #endif
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 1220 ] ] ]
da0fedd1902603cb3f95668ef5b6c0ac46e0e6c5
5fea042a436493f474afaf862ea592fa37c506ab
/Antihack/connection.cpp
9f1c6905e9c3731fadc0bd1e4384dd6d7bae6e7c
[]
no_license
Danteoriginal/twilight-antihack
9fde8fbd2f34954752dc2de3927490d657b43739
4ccc51c13c33abcb5e370ef1b992436e6a1533c9
refs/heads/master
2021-01-13T06:25:31.618338
2009-10-25T14:44:34
2009-10-25T14:44:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,396
cpp
#include "connection.h" // ------------------------------------------------------------------------------- // CONSTRUCTOR / DESTRUCTOR: // ------------------------------------------------------------------------------- CConnection::CConnection() { connected = false; hSocket = 0; } CConnection::~CConnection() { } // ------------------------------------------------------------------------------- // COMMUNICATION: // ------------------------------------------------------------------------------- int CConnection::Init(SOCKET s) { if (connected) return 0; hSocket = s; connected = true; return 1; } int CConnection::Shutdown(SOCKET s) { if (!connected || hSocket != s) return 0; hSocket = 0; connected = false; return 1; } int CConnection::Connected() { return connected; } int CConnection::SendBuffer(void* buffer, unsigned int size) { if (!connected) return 0; int ret = 0; int pos = 0; do { ret = send(hSocket, (const char*)((int)buffer + pos), size-pos, MSG_PARTIAL); if (ret == -1) { Shutdown(hSocket); break; } else { pos += ret; } } while (ret < size); return ret; } int CConnection::ReceiveBuffer(void* buffer, unsigned int size) { if (!connected) return 0; return 1; } int CConnection::SendPacket(PACKET* packet) { if (!connected) return 0; return 1; }
[ [ [ 1, 78 ] ] ]
e82055a1a50048d8321573ac174eae25b90ffc7e
d397b0d420dffcf45713596f5e3db269b0652dee
/src/Lib/PropertySystem/String.hpp
d5c35008b320bd823dfae42506444b39c05241d5
[]
no_license
irov/Axe
62cf29def34ee529b79e6dbcf9b2f9bf3709ac4f
d3de329512a4251470cbc11264ed3868d9261d22
refs/heads/master
2021-01-22T20:35:54.710866
2010-09-15T14:36:43
2010-09-15T14:36:43
85,337,070
0
0
null
null
null
null
UTF-8
C++
false
false
390
hpp
# pragma once # include "Base.hpp" # include <string> namespace AxeProperty { class String : public Base { PROPERTY_VISITOR_DECLARE() public: String( const TypePtr & _type ); public: void setValue( const std::string & _value ); const std::string & getValue() const; protected: std::string m_value; }; typedef AxeHandle<String> StringPtr; }
[ "yuriy_levchenko@b35ac3e7-fb55-4080-a4c2-184bb04a16e0" ]
[ [ [ 1, 26 ] ] ]
887ccedb878aeac8106bd37923940c948b98b8f2
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/06112002/src/Input/InputDeviceDB.cpp
91d984bfda1592feee7833e30c1035fa801187a7
[]
no_license
christhomas/fusionengine
286b33f2c6a7df785398ffbe7eea1c367e512b8d
95422685027bb19986ba64c612049faa5899690e
refs/heads/master
2020-04-05T22:52:07.491706
2006-10-24T11:21:28
2006-10-24T11:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,420
cpp
// InputDeviceDB.cpp: implementation of the InputDeviceDB class. // ////////////////////////////////////////////////////////////////////// #include <Input/InputDeviceDB.h> #include <Fusion.h> /** InputDeviceDB Constructor * * Operation: * -# Set all the linked lists to null and number of devices to 0 * -# Set the name of the subsystem and it's module dll */ InputDeviceDB::InputDeviceDB(void) { m_mouse = NULL; m_keyboard = NULL; m_joystick = NULL; m_num_mouse = 0; m_num_keyboard = 0; m_num_joystick = 0; object_name = "InputDeviceDB Version 1.2 <[email protected]>"; object_filename = "libInput.dll"; } /** InputDeviceDB Deconstructor * * Operation: * -# Remove all the Mice * -# Remove all the Keyboards * -# Remove all the joysticks */ InputDeviceDB::~InputDeviceDB() { IInputDevice *temp; temp = m_mouse; while(m_mouse != NULL){ temp = m_mouse->prev; delete m_mouse; m_mouse = temp; } temp = m_keyboard; while(m_keyboard != NULL){ temp = m_keyboard->prev; delete m_keyboard; m_keyboard = temp; } temp = m_joystick; while(m_joystick != NULL){ temp = m_joystick->prev; delete m_joystick; m_joystick = temp; } } /** Initialise the subsystem * * @returns true * * @todo Deprecate from the fusion subsystem object and allow each object to decide whether it needs an initialisation method or not */ bool InputDeviceDB::Initialise(void) { return true; } /** Retrieves a device pointer * * @param type The type of device to retrieve * @param DeviceID The id of the device in the database * * @returns An IInputDevice object or NULL, if the object was not found */ IInputDevice * InputDeviceDB::GetDevicePtr(IInputDevice::DeviceType type,unsigned int DeviceID) { IInputDevice *temp; if(type == IInputDevice::MOUSE) for(temp=m_mouse; temp!=NULL;temp=temp->prev) if(temp->GetDeviceID() == DeviceID) return temp; if(type == IInputDevice::KEYBOARD) for(temp=m_keyboard;temp!=NULL;temp=temp->prev) if(temp->GetDeviceID() == DeviceID) return temp; if(type == IInputDevice::JOYSTICK) for(temp=m_joystick;temp!=NULL;temp=temp->prev) if(temp->GetDeviceID() == DeviceID) return temp; return NULL; } /** Removes a device from the database * * @param id The input device to remove * * NOTE: This method is not yet implemented */ void InputDeviceDB::RemoveDevice(IInputDevice **id) { // not implemented yet } /** Stores a device in the database * * @param device The device to store * * Operation: * -# Find out what type of device this is * -# Add it to the appropriate linked list */ void InputDeviceDB::StoreDevice(IInputDevice *device) { switch(device->GetDeviceType()){ case IInputDevice::MOUSE: { device->prev = m_mouse; m_mouse = device; }break; case IInputDevice::KEYBOARD: { device->prev = m_keyboard; m_keyboard = device; }break; case IInputDevice::JOYSTICK: { device->prev = m_joystick; m_joystick = device; }break; }; } /** Flush all the device input event queues */ void InputDeviceDB::FlushAll(void) { IInputDevice *temp; for(temp=m_mouse; temp!=NULL;temp=temp->prev) temp->FlushEventQueue(); for(temp=m_keyboard;temp!=NULL;temp=temp->prev) temp->FlushEventQueue(); for(temp=m_joystick;temp!=NULL;temp=temp->prev) temp->FlushEventQueue(); } /** Updates all the devices in the database * * @returns boolean true or false, but this method ignores any failure and only returns true at this time * * Operation: * -# calls each devices IInputDevice::GetActive() method to find whether the device is active or not * -# If the device is active, call IInputDevice::Update() method to update the device * * Do nothing if the device fails to update properly */ bool InputDeviceDB::Update(void) { IInputDevice *temp; // For now, do nothing when a device fails to update // (havent figured out what is best to do in this situation, just carry on, or do some interrogation) for(temp=m_mouse; temp!=NULL;temp=temp->prev) if(temp->GetActive() == true) if(temp->Update() == false){} for(temp=m_keyboard;temp!=NULL;temp=temp->prev) if(temp->GetActive() == true) if(temp->Update() == false){} for(temp=m_joystick;temp!=NULL;temp=temp->prev) if(temp->GetActive() == true) if(temp->Update() == false){} return true; }
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
[ [ [ 1, 149 ] ] ]
d0b669dd3336bd042b96abd53d7a6ba51a18804f
406b4b18f5c58c689d2324f49db972377fe8feb6
/ANE/Include/Foundation/Ptr.h
daad97c8c194d593bbaeca179a4768789b788769
[]
no_license
Mobiwoom/ane
e17167de36699c451ed92eab7bf733e7d41fe847
ec20667c556a99351024f3ae9c8880e944c5bfbd
refs/heads/master
2021-01-17T13:09:57.966141
2010-03-23T16:30:17
2010-03-23T16:30:17
33,132,357
0
1
null
null
null
null
UTF-8
C++
false
false
2,261
h
#pragma once namespace Ane { template<class Type> class Ptr { public: Ptr(); Ptr(Type* p); Ptr(const Ptr<Type>& p); ~Ptr(); void operator=(const Ptr<Type>& p); void operator=(Type* p); bool operator==(const Ptr<Type>& p) const; bool operator!=(const Ptr<Type>& p) const; bool operator==(const Type* p) const; bool operator!=(const Type* p) const; Type* operator->() const; Type& operator*() const; operator Type*() const; private: Type* m_Ptr; }; template<class Type> Ptr<Type>::Ptr() : m_Ptr(0) { } template<class Type> Ptr<Type>::Ptr(Type* p) :m_Ptr(p) { if(0 != this->m_Ptr) { this->m_Ptr->InitRef(); this->m_Ptr->AddRef(); } } template<class Type> Ptr<Type>::Ptr(const Ptr<Type> &p) :m_Ptr(p.m_Ptr) { if(0 != this->m_Ptr) { this->m_Ptr->AddRef(); } } template<class Type> Ptr<Type>::~Ptr() { if(0 != this->m_Ptr) { this->m_Ptr->Release(); this->m_Ptr = 0; } } template<class Type> void Ptr<Type>::operator=(const Ptr<Type>& p) { if(this->m_Ptr) { this->m_Ptr->Release(); } this->m_Ptr = p.m_Ptr; if(this->m_Ptr) { this->m_Ptr->AddRef(); } } template<class Type> void Ptr<Type>::operator=(Type* p) { if(this->m_Ptr) { this->m_Ptr->Release(); } this->m_Ptr = p; if(this->m_Ptr) { this->m_Ptr->AddRef(); } } template<class Type> bool Ptr<Type>::operator==(const Ptr<Type>& p) const { return (this->m_Ptr == p.m_Ptr); } template<class Type> bool Ptr<Type>::operator!=(const Ptr<Type>&p) const { return(this->m_Ptr != p.m_Ptr); } template<class Type> bool Ptr<Type>::operator ==(const Type* p) const { return (this->m_Ptr == p); } template<class Type> bool Ptr<Type>::operator!=(const Type* p)const { return (this->m_Ptr != p); } template<class Type> Type* Ptr<Type>::operator->() const { return this->m_Ptr; } template<class Type> Type& Ptr<Type>::operator*() const { this->m_Ptr->AddRef(); return this->m_Ptr; } template<class Type> Ptr<Type>::operator Type*() const { this->m_Ptr->AddRef(); return this->m_Ptr; } }
[ "inthejm@5abed23c-1faa-11df-9e62-c93c6248c2ac" ]
[ [ [ 1, 138 ] ] ]
5283ae12c3a1caf6a56eebb33c1f740a85e53ffd
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/Base/BufsAndStrings/Desc/BinaryData/BinaryData.cpp
913f75ab88e57fee8721bb42011df42e6d70108f
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
2,381
cpp
// BinaryData.cpp // // Copyright (C) Symbian Software Ltd 2000-2005. All rights reserved. // Examples to demonstrate how descriptors can handle // general binary data. #include "CommonFramework.h" // // Common literal text // _LIT(KTxtNewLine,"\n"); // // Common format strings // _LIT(KCommonFormat2,"Size()=%d; MaxLength()=%d\n"); _LIT(KCommonFormat3,"0x%02x "); _LIT(KCommonFormat4,"; Length()=%d;\n"); // do the example LOCAL_C void doExampleL() { TInt counter; TInt index; // For general binary data, construct an 8 bit // variant descriptor. Binary data is always // treated as 8 bit data regardless of the // build. // // This example constructs a TBuf8 using the // default constructor. TBuf8<32> buffer; // Look at: // 1. Descriptor content // 2. Length of descriptor // 3. Size of descriptor // 4. Maximum length of descriptor // // Length is zero. Maximum length is 32. // Size is zero. _LIT(KFormat1,"\"%S\"; Length()=%d; "); console->Printf(KFormat1,&buffer,buffer.Length()); console->Printf(KCommonFormat2,buffer.Size(),buffer.MaxLength()); // Set up an area in memory initialised // with binary data. TUint8 data[6] = {0x00,0x01,0x02,0xAD,0xAE,0xAF}; // Put data into descriptor buffer.Append(&data[0],sizeof(data)); // Append the following byte values buffer.Append(0xFD); buffer.Append(0xFE); buffer.Append(0xFF); // Length is now 9; maxlength is still 32; // Size is always 9 regardless of build. counter = buffer.Length(); console->Printf(KTxtNewLine); for (index = 0; index < counter; index++) console->Printf(KCommonFormat3,buffer[index]); console->Printf(KCommonFormat4,buffer.Length() ); console->Printf(KCommonFormat2,buffer.Size(),buffer.MaxLength()); // We can also mix text characters and // general binary data. buffer.Append('A'); buffer.Append('B'); buffer.Append(0x11); // Show it counter = buffer.Length(); console->Printf(KTxtNewLine); for (index = 0; index < counter; index++) console->Printf(KCommonFormat3,buffer[index]); console->Printf(KCommonFormat4,buffer.Length()); console->Printf(KCommonFormat2,buffer.Size(),buffer.MaxLength()); }
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 86 ] ] ]
73599c938e4099759081b10f55d9c720d1accd36
d258dd0ca5e8678c8eb81777e5fe360b8bbf7b7e
/Library/PhysXCPP/NxaSphereShapeDescription.cpp
d166307c8b50b0900c8d405f1d426878a4c6cb20
[]
no_license
ECToo/physxdotnet
1e7d7e9078796f1dad5c8582d28441a908e11a83
2b85d57bc877521cdbf1a9147bd6716af68a64b0
refs/heads/master
2021-01-22T07:17:58.918244
2008-04-13T11:15:26
2008-04-13T11:15:26
32,543,781
0
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
#include "StdAfx.h" #include "NxaSphereShapeDescription.h" NxaSphereShapeDescription::NxaSphereShapeDescription(void) { nxShapeDesc = new NxSphereShapeDesc(); } NxaSphereShapeDescription::NxaSphereShapeDescription(NxSphereShapeDesc* ptr) { nxShapeDesc = ptr; } void NxaSphereShapeDescription::Radius::set(float radius) { NxSphereShapeDesc* sphereDesc = (NxSphereShapeDesc*)nxShapeDesc; sphereDesc->radius = radius; }
[ "amiles@e8b6d1ee-b643-0410-9178-bfabf5f736f5" ]
[ [ [ 1, 20 ] ] ]
f7cff004078a7a18eda08ef7c75b3ec8e941b97c
1bc2f450f157ce39cbd92d0549e1459368a76e94
/lib/cppunit-1.12.1/include/cppunit/portability/CppUnitMap.h
eaa1a33663cdf65221f6cd6306743c6a8157722d
[]
no_license
mirror/odin
168267277386d6c07c006cb196fec3bb208f5e3c
63b4633a87b03a924df612271c2d6310c34834a8
refs/heads/master
2023-09-01T13:28:38.392325
2011-10-09T15:38:02
2011-10-09T15:38:02
9,256,124
5
4
null
null
null
null
UTF-8
C++
false
false
621
h
#ifndef CPPUNIT_PORTABILITY_CPPUNITMAP_H #define CPPUNIT_PORTABILITY_CPPUNITMAP_H // The technic used is similar to the wrapper of STLPort. #include <cppunit/Portability.h> #include <functional> #include <map> #if CPPUNIT_STD_NEED_ALLOCATOR template<class Key, class T> class CppUnitMap : public std::map<Key ,T ,std::less<Key> ,CPPUNIT_STD_ALLOCATOR> { public: }; #else // CPPUNIT_STD_NEED_ALLOCATOR #define CppUnitMap std::map #endif #endif // CPPUNIT_PORTABILITY_CPPUNITMAP_H
[ "kaltduscher65@b91d169b-bf28-450c-9b59-d70c078a1df8" ]
[ [ [ 1, 29 ] ] ]
1e34b29c5f31a1d564242ec65b0eaab3d357fcfe
7ae740fa8238860450738d713986f86c4ed87753
/GameLogic.cpp
de01ba77c9605cf71ff70477d3ad6187c43d3c14
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
radekp/qsolitaire
154de71636a5b3b40524997e7b19c499027d80ca
2c6c8f8942344003820cecd5cc51d37ea503ea96
refs/heads/master
2020-04-18T07:42:30.180834
2011-02-17T08:04:40
2011-02-17T08:04:40
1,373,322
0
1
null
null
null
null
UTF-8
C++
false
false
8,580
cpp
/* * Copyright (c) 2009 Nokia Corporation. */ #include <QTime> #include "GameLogic.h" #include "Card.h" #include "CardDeck.h" GameLogic::GameLogic(QObject *parent) : QObject(parent) { // Create cards createCards(); // Create seed for the random QTime time = QTime::currentTime(); qsrand((uint)time.msec()); } GameLogic::~GameLogic() { // Removes pointer from the array and deletes // actual class while (!cards.isEmpty()) { delete cards[0]; cards.removeAt(0); } while (!messedCards.isEmpty()) { delete messedCards[0]; messedCards.removeAt(0); } } int GameLogic::randInt(int low, int high) { // Get random number between low and high return qrand() % ((high + 1) - low) + low; } void GameLogic::messCards() { while (!cards.isEmpty()) { int rand = randInt(0,cards.count()-1); Card* card = cards[rand]; messedCards.append(card); //delete cards[rand]; // NOTE: do not delete card object cards.removeAt(rand); } } QList<Card*> GameLogic::messedCardList() { return messedCards; } void GameLogic::createCards() { cards.append(new Card(QString(":/images/clubs/Club_ace_75x110.svg"),1,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_2_75x110.svg"),2,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_3_75x110.svg"),3,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_4_75x110.svg"),4,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_5_75x110.svg"),5,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_6_75x110.svg"),6,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_7_75x110.svg"),7,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_8_75x110.svg"),8,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_9_75x110.svg"),9,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_10_75x110.svg"),10,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_jack_75x110.svg"),11,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_queen_75x110.svg"),12,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/clubs/Club_king_75x110.svg"),13,Card::Club,Card::Black)); cards.append(new Card(QString(":/images/diamond/Diamond_ace_75x110.svg"),1,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_2_75x110.svg"),2,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_3_75x110.svg"),3,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_4_75x110.svg"),4,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_5_75x110.svg"),5,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_6_75x110.svg"),6,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_7_75x110.svg"),7,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_8_75x110.svg"),8,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_9_75x110.svg"),9,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_10_75x110.svg"),10,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_jack_75x110.svg"),11,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_queen_75x110.svg"),12,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/diamond/Diamond_king_75x110.svg"),13,Card::Diamond,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_ace_75x110.svg"),1,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_2_75x110.svg"),2,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_3_75x110.svg"),3,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_4_75x110.svg"),4,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_5_75x110.svg"),5,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_6_75x110.svg"),6,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_7_75x110.svg"),7,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_8_75x110.svg"),8,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_9_75x110.svg"),9,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_10_75x110.svg"),10,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_jack_75x110.svg"),11,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_queen_75x110.svg"),12,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/heart/Heart_king_75x110.svg"),13,Card::Heart,Card::Red)); cards.append(new Card(QString(":/images/spade/Spade_ace_75x110.svg"),1,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_2_75x110.svg"),2,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_3_75x110.svg"),3,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_4_75x110.svg"),4,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_5_75x110.svg"),5,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_6_75x110.svg"),6,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_7_75x110.svg"),7,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_8_75x110.svg"),8,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_9_75x110.svg"),9,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_10_75x110.svg"),10,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_jack_75x110.svg"),11,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_queen_75x110.svg"),12,Card::Spade,Card::Black)); cards.append(new Card(QString(":/images/spade/Spade_king_75x110.svg"),13,Card::Spade,Card::Black)); } bool GameLogic::isValidMove(Card* topCard, BaseCardDeck* deck) { if (deck->Type()==BaseCardDeck::CardDeck) { // If there is no cards in the deck, then the first one must be King card if (deck->Cards().count()==0 && topCard->value()!=13) { return false; } } else if (deck->Type()==BaseCardDeck::Foundation) { // Ace card must be the first card in foundation if (deck->Cards().count()==0 && topCard->value()!=1) { return false; } } else { return false; } return true; } bool GameLogic::isValidMove(Card* topCard, Card* bottomCard) { if (!topCard || !bottomCard) { return false; } // Moving cards between card decks if (bottomCard->deck()->Type()==BaseCardDeck::CardDeck) { // Card decks must differ if (bottomCard->deck() == topCard->deck()) { return false; } // Card can be top of one step greater card and different color if (bottomCard->color() == topCard->color() || topCard->value()+1 != bottomCard->value()) { return false; } } // Moving cards between card deck and foundation else if (bottomCard->deck()->Type()==BaseCardDeck::Foundation) { // Card decks must differ if (bottomCard->deck() == topCard->deck()) { return false; } // Cards must be in ascending order and same suite if (topCard->value() != bottomCard->value()+1 || topCard->suite() != bottomCard->suite()) { return false; } } else { return false; } return true; }
[ [ [ 1, 192 ] ] ]
f5b5fa43358e24017c73ce00a02a957d8ecc6274
1a328b077420752dd39a215ce8d653741dda5dc7
/seg3.cpp
4c860e78fc802ff064e29a3c562922bbc083b8bd
[]
no_license
softwaresunday/Comprovisation
d47f943ba692de5c69a6711f5e0f997334c8ecde
05df0f8cc319c771433147d63cbe35e5974352b5
refs/heads/master
2020-03-30T06:55:12.998143
2011-08-20T09:42:03
2011-08-20T09:42:03
2,211,280
0
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
#include "windows.h" #include "stdio.h" #include <signal.h> #include "digits.h" void colorOn(int n) { Out32(PPORT_BASE,0x01<<(n-1)); } void colorOff(int n) { Out32(PPORT_BASE,0); }
[ [ [ 1, 18 ] ] ]
bd79cb490441060968b78353660e713a318c5056
bf7d05c055c5686e4ded30f9705a28a396520d48
/Meta/MetaProject.h
548b506d23e0d6400cce389eb9c56d0626259262
[]
no_license
ghemingway/mgalib
f32438d5abdbeb5739c298e401a0513f91c8d6d0
c8cf8507a7fe73efe1da19abcdb77b52e75e2de0
refs/heads/master
2020-12-24T15:40:33.538434
2011-02-04T16:38:09
2011-02-04T16:38:09
32,185,568
0
1
null
null
null
null
UTF-8
C++
false
false
2,533
h
#ifndef __META_PROJECT_H__ #define __META_PROJECT_H__ /*** Included Header Files ***/ #include "../MGA/MgaTypes.h" #include "../Core/CoreObject.h" /*** Namespace Declaration ***/ namespace MGA { /*** Class Predefinitions ***/ class MetaBase; class CoreProject; class MetaFolder; /*** Type Definitions ***/ //None // --------------------------- MetaProject --------------------------- // class MetaProject { private: CoreProject *_coreProject; CoreObject _rootObject; MetaProject(); //!< Deny access to default constructor MetaProject(const MetaProject &); //!< Deny access to copy constructor MetaProject& operator=(const MetaProject&); //!< Deny access to equals operator MetaProject(CoreProject* &coreProject); //!< Hidden primary constructor public: ~MetaProject(); static const Result_t Open(const std::string &connection, MetaProject* &project) throw(); static const Result_t Create(const std::string &connection, MetaProject* &project) throw(); const Result_t Save(const std::string &filename="", const bool &forceOverwrite=false) throw(); const Result_t BeginTransaction(void) throw(); const Result_t CommitTransaction(void) throw(); const Result_t AbortTransaction(void) throw(); const Result_t GetUuid(Uuid &uuid) const throw(); const Result_t SetUuid(const Uuid &uuid) throw(); const Result_t GetName(std::string &name) const throw(); const Result_t SetName(const std::string &name) throw(); const Result_t GetDisplayedName(std::string &name) const throw(); const Result_t SetDisplayedName(const std::string &name) throw(); const Result_t GetVersion(std::string &version) const throw(); const Result_t SetVersion(const std::string &version) throw(); const Result_t GetAuthor(std::string &author) const throw(); const Result_t SetAuthor(const std::string &author) throw(); const Result_t GetComment(std::string &comment) const throw(); const Result_t SetComment(const std::string &comment) throw(); const Result_t GetCreatedAt(std::string &dateTime) const throw(); const Result_t SetCreatedAt(const std::string &dateTime) throw(); const Result_t GetModifiedAt(std::string &dateTime) const throw(); const Result_t SetModifiedAt(const std::string &dateTime) throw(); const Result_t RootFolder(MetaFolder* &folder) throw(); const Result_t FindObject(const Uuid &uuid, MetaBase* &metaBase) throw(); }; /*** End of MGA Namespace ***/ } #endif // __META_PROJECT_H__
[ "graham.hemingway@8932de9b-a0df-7518-fb39-9aee4a96b462" ]
[ [ [ 1, 74 ] ] ]
19e7fb33f9a3d45ec45eacc9f545339dc5eb9b30
3d7fc34309dae695a17e693741a07cbf7ee26d6a
/aluminizer/StringConversion.cpp
738ceb265df6f402165d572032b7a6cbcf565c57
[ "LicenseRef-scancode-public-domain" ]
permissive
nist-ionstorage/ionizer
f42706207c4fb962061796dbbc1afbff19026e09
70b52abfdee19e3fb7acdf6b4709deea29d25b15
refs/heads/master
2021-01-16T21:45:36.502297
2010-05-14T01:05:09
2010-05-14T01:05:09
20,006,050
5
0
null
null
null
null
UTF-8
C++
false
false
689
cpp
#ifdef PRECOMPILED_HEADER #include "common.h" #endif //FPGA and AluminizerSim need stringable.h #if (ALUMINIZER_SIM || ALUMINIZER_ES) #include "stringable.h" #endif #include "dds_pulse_info.h" template<> dds_pulse_info from_string(const std::string& s) { return dds_pulse_info(s); } template<> ttl_pulse_info from_string(const std::string& s) { return ttl_pulse_info(s); } template<> std::string to_string(const dds_pulse_info& value, int) { char s[256]; value.to_string(s, 256); return std::string(s); } template<> std::string to_string(const ttl_pulse_info& value, int) { char s[256]; value.to_string(s, 256); return std::string(s); }
[ "trosen@814e38a0-0077-4020-8740-4f49b76d3b44" ]
[ [ [ 1, 36 ] ] ]
a4b4c25ac092e3a0ca406c1ef9402741b277db3e
203f8465075e098f69912a6bbfa3498c36ce2a60
/sandbox/point_cloud_clustering/src/3rd_party/KmTree.cpp
5a0570c69b1c8a24e9620a4b38fed82932578e21
[]
no_license
robcn/personalrobots-pkg
a4899ff2db9aef00a99274d70cb60644124713c9
4dcf3ca1142d3c3cb85f6d42f7afa33c59e2240a
refs/heads/master
2021-06-20T16:28:29.549716
2009-09-04T23:56:10
2009-09-04T23:56:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,539
cpp
// See KmTree.cpp // // Author: David Arthur ([email protected]), 2009 // Includes #include <point_cloud_clustering/3rd_party/KmTree.h> //#include "KmTree.h" #include <iostream> #include <stdlib.h> using namespace std; KmTree::KmTree(int n, int d, Scalar *points): n_(n), d_(d), points_(points) { // Initialize memory int node_size = sizeof(Node) + d_ * 3 * sizeof(Scalar); node_data_ = (char*)malloc((2*n-1) * node_size); point_indices_ = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) point_indices_[i] = i; KM_ASSERT(node_data_ != 0 && point_indices_ != 0); // Calculate the bounding box for the points Scalar *bound_v1 = PointAllocate(d_); Scalar *bound_v2 = PointAllocate(d_); KM_ASSERT(bound_v1 != 0 && bound_v2 != 0); PointCopy(bound_v1, points, d_); PointCopy(bound_v2, points, d_); for (int i = 1; i < n; i++) for (int j = 0; j < d; j++) { if (bound_v1[j] > points[i*d_ + j]) bound_v1[j] = points[i*d_ + j]; if (bound_v2[j] < points[i*d_ + j]) bound_v1[j] = points[i*d_ + j]; } // Build the tree char *temp_node_data = node_data_; top_node_ = BuildNodes(points, 0, n-1, &temp_node_data); // Cleanup PointFree(bound_v1); PointFree(bound_v2); } KmTree::~KmTree() { free(point_indices_); free(node_data_); } Scalar KmTree::DoKMeansStep(int k, Scalar *centers, int *assignment) const { // Create an invalid center for comparison purposes Scalar *bad_center = PointAllocate(d_); KM_ASSERT(bad_center != 0); memset(bad_center, 0xff, d_ * sizeof(Scalar)); // Allocate data Scalar *sums = (Scalar*)calloc(k * d_, sizeof(Scalar)); int *counts = (int*)calloc(k, sizeof(int)); int num_candidates = 0; int *candidates = (int*)malloc(k * sizeof(int)); KM_ASSERT(sums != 0 && counts != 0 && candidates != 0); for (int i = 0; i < k; i++) if (memcmp(centers + i*d_, bad_center, d_ * sizeof(Scalar)) != 0) candidates[num_candidates++] = i; // Find nodes Scalar result = DoKMeansStepAtNode(top_node_, num_candidates, candidates, centers, sums, counts, assignment); // Set the new centers for (int i = 0; i < k; i++) { if (counts[i] > 0) { PointScale(sums + i*d_, Scalar(1) / counts[i], d_); PointCopy(centers + i*d_, sums + i*d_, d_); } else { memcpy(centers + i*d_, bad_center, d_ * sizeof(Scalar)); } } // Cleanup memory PointFree(bad_center); free(candidates); free(counts); free(sums); return result; } // Helper functions for constructor // ================================ // Build a kd tree from the given set of points KmTree::Node *KmTree::BuildNodes(Scalar *points, int first_index, int last_index, char **next_node_data) { // Allocate the node Node *node = (Node*)(*next_node_data); (*next_node_data) += sizeof(Node); node->sum = (Scalar*)(*next_node_data); (*next_node_data) += sizeof(Scalar) * d_; node->median = (Scalar*)(*next_node_data); (*next_node_data) += sizeof(Scalar) * d_; node->radius = (Scalar*)(*next_node_data); (*next_node_data) += sizeof(Scalar) * d_; // Fill in basic info node->num_points = (last_index - first_index + 1); node->first_point_index = first_index; // Calculate the bounding box Scalar *first_point = points + point_indices_[first_index] * d_; Scalar *bound_p1 = PointAllocate(d_); Scalar *bound_p2 = PointAllocate(d_); KM_ASSERT(bound_p1 != 0 && bound_p2 != 0); PointCopy(bound_p1, first_point, d_); PointCopy(bound_p2, first_point, d_); for (int i = first_index+1; i <= last_index; i++) for (int j = 0; j < d_; j++) { Scalar c = points[point_indices_[i]*d_ + j]; if (bound_p1[j] > c) bound_p1[j] = c; if (bound_p2[j] < c) bound_p2[j] = c; } // Calculate bounding box stats and delete the bounding box memory Scalar max_radius = -1; int split_d = -1; for (int j = 0; j < d_; j++) { node->median[j] = (bound_p1[j] + bound_p2[j]) / 2; node->radius[j] = (bound_p2[j] - bound_p1[j]) / 2; if (node->radius[j] > max_radius) { max_radius = node->radius[j]; split_d = j; } } PointFree(bound_p2); PointFree(bound_p1); // If the max spread is 0, make this a leaf node if (max_radius == 0) { node->lower_node = node->upper_node = 0; PointCopy(node->sum, first_point, d_); if (last_index != first_index) PointScale(node->sum, Scalar(last_index - first_index + 1), d_); node->opt_cost = 0; return node; } // Partition the points around the midpoint in this dimension. The partitioning is done in-place // by iterating from left-to-right and right-to-left in the same way that partioning is done for // quicksort. Scalar split_pos = node->median[split_d]; int i1 = first_index, i2 = last_index, size1 = 0; while (i1 <= i2) { bool is_i1_good = (points[point_indices_[i1]*d_ + split_d] < split_pos); bool is_i2_good = (points[point_indices_[i2]*d_ + split_d] >= split_pos); if (!is_i1_good && !is_i2_good) { int temp = point_indices_[i1]; point_indices_[i1] = point_indices_[i2]; point_indices_[i2] = temp; is_i1_good = is_i2_good = true; } if (is_i1_good) { i1++; size1++; } if (is_i2_good) { i2--; } } // Create the child nodes KM_ASSERT(size1 >= 1 && size1 <= last_index - first_index); node->lower_node = BuildNodes(points, first_index, first_index + size1 - 1, next_node_data); node->upper_node = BuildNodes(points, first_index + size1, last_index, next_node_data); // Calculate the new sum and opt cost PointCopy(node->sum, node->lower_node->sum, d_); PointAdd(node->sum, node->upper_node->sum, d_); Scalar *center = PointAllocate(d_); KM_ASSERT(center != 0); PointCopy(center, node->sum, d_); PointScale(center, Scalar(1) / node->num_points, d_); node->opt_cost = GetNodeCost(node->lower_node, center) + GetNodeCost(node->upper_node, center); PointFree(center); return node; } // Returns the total contribution of all points in the given kd-tree node, assuming they are all // assigned to a center at the given location. We need to return: // // sum_{x \in node} ||x - center||^2. // // If c denotes the center of mass of the points in this node and n denotes the number of points in // it, then this quantity is given by // // n * ||c - center||^2 + sum_{x \in node} ||x - c||^2 // // The sum is precomputed for each node as opt_cost. This formula follows from expanding both sides // as dot products. See Kanungo/Mount for more info. Scalar KmTree::GetNodeCost(const Node *node, Scalar *center) const { Scalar dist_sq = 0; for (int i = 0; i < d_; i++) { Scalar x = (node->sum[i] / node->num_points) - center[i]; dist_sq += x*x; } return node->opt_cost + node->num_points * dist_sq; } // Helper functions for DoKMeans step // ================================== // A recursive version of DoKMeansStep. This determines which clusters all points that are rooted // node will be assigned to, and updates sums, counts and assignment (if not null) accordingly. // candidates maintains the set of cluster indices which could possibly be the closest clusters // for points in this subtree. Scalar KmTree::DoKMeansStepAtNode(const Node *node, int k, int *candidates, Scalar *centers, Scalar *sums, int *counts, int *assignment) const { // Determine which center the node center is closest to Scalar min_dist_sq = PointDistSq(node->median, centers + candidates[0]*d_, d_); int closest_i = candidates[0]; for (int i = 1; i < k; i++) { Scalar dist_sq = PointDistSq(node->median, centers + candidates[i]*d_, d_); if (dist_sq < min_dist_sq) { min_dist_sq = dist_sq; closest_i = candidates[i]; } } // If this is a non-leaf node, recurse if necessary if (node->lower_node != 0) { // Build the new list of candidates int new_k = 0; int *new_candidates = (int*)malloc(k * sizeof(int)); KM_ASSERT(new_candidates != 0); for (int i = 0; i < k; i++) if (!ShouldBePruned(node->median, node->radius, centers, closest_i, candidates[i])) new_candidates[new_k++] = candidates[i]; // Recurse if there's at least two if (new_k > 1) { Scalar result = DoKMeansStepAtNode(node->lower_node, new_k, new_candidates, centers, sums, counts, assignment) + DoKMeansStepAtNode(node->upper_node, new_k, new_candidates, centers, sums, counts, assignment); free(new_candidates); return result; } else { free(new_candidates); } } // Assigns all points within this node to a single center PointAdd(sums + closest_i*d_, node->sum, d_); counts[closest_i] += node->num_points; if (assignment != 0) { for (int i = node->first_point_index; i < node->first_point_index + node->num_points; i++) assignment[point_indices_[i]] = closest_i; } return GetNodeCost(node, centers + closest_i*d_); } // Determines whether every point in the box is closer to centers[best_index] than to // centers[test_index]. // // If x is a point, c_0 = centers[best_index], c = centers[test_index], then: // (x-c).(x-c) < (x-c_0).(x-c_0) // <=> (c-c_0).(c-c_0) < 2(x-c_0).(c-c_0) // // The right-hand side is maximized for a vertex of the box where for each dimension, we choose // the low or high value based on the sign of x-c_0 in that dimension. bool KmTree::ShouldBePruned(Scalar *box_median, Scalar *box_radius, Scalar *centers, int best_index, int test_index) const { if (best_index == test_index) return false; Scalar *best = centers + best_index*d_; Scalar *test = centers + test_index*d_; Scalar lhs = 0, rhs = 0; for (int i = 0; i < d_; i++) { Scalar component = test[i] - best[i]; lhs += component * component; if (component > 0) rhs += (box_median[i] + box_radius[i] - best[i]) * component; else rhs += (box_median[i] - box_radius[i] - best[i]) * component; } return (lhs >= 2*rhs); } // Helper functions for SeekKMeansPlusPlus // ======================================= Scalar KmTree::SeedKMeansPlusPlus(int k, Scalar *centers) const { Scalar *dist_sq = (Scalar*)malloc(n_ * sizeof(Scalar)); KM_ASSERT(dist_sq != 0); // Choose an initial center uniformly at random SeedKmppSetClusterIndex(top_node_, 0); int i = GetRandom(n_); memcpy(centers, points_ + point_indices_[i]*d_, d_*sizeof(Scalar)); Scalar total_cost = 0; for (int j = 0; j < n_; j++) { dist_sq[j] = PointDistSq(points_ + point_indices_[j]*d_, centers, d_); total_cost += dist_sq[j]; } // Repeatedly choose more centers for (int new_cluster = 1; new_cluster < k; new_cluster++) { Scalar temp = 0; for (i = 0; i < n_; i++) temp += dist_sq[i]; while (1) { Scalar cutoff = (rand() / Scalar(RAND_MAX)) * total_cost; Scalar cur_cost = 0; for (i = 0; i < n_; i++) { cur_cost += dist_sq[i]; if (cur_cost >= cutoff) break; } if (i < n_) break; } memcpy(centers + new_cluster*d_, points_ + point_indices_[i]*d_, d_*sizeof(Scalar)); total_cost = SeedKmppUpdateAssignment(top_node_, new_cluster, centers, dist_sq); } // Clean up and return free(dist_sq); return total_cost; } // Sets kmpp_cluster_index to 0 for all nodes void KmTree::SeedKmppSetClusterIndex(const Node *node, int value) const { node->kmpp_cluster_index = value; if (node->lower_node != 0) { SeedKmppSetClusterIndex(node->lower_node, value); SeedKmppSetClusterIndex(node->upper_node, value); } } Scalar KmTree::SeedKmppUpdateAssignment(const Node *node, int new_cluster, Scalar *centers, Scalar *dist_sq) const { // See if we can assign all points in this node to one cluster if (node->kmpp_cluster_index >= 0) { if (ShouldBePruned(node->median, node->radius, centers, node->kmpp_cluster_index, new_cluster)) return GetNodeCost(node, centers + node->kmpp_cluster_index*d_); if (ShouldBePruned(node->median, node->radius, centers, new_cluster, node->kmpp_cluster_index)) { SeedKmppSetClusterIndex(node, new_cluster); for (int i = node->first_point_index; i < node->first_point_index + node->num_points; i++) dist_sq[i] = PointDistSq(points_ + point_indices_[i]*d_, centers + new_cluster*d_, d_); return GetNodeCost(node, centers + new_cluster*d_); } // It may be that the a leaf-node point is equidistant from the new center or old if (node->lower_node == 0) return GetNodeCost(node, centers + node->kmpp_cluster_index*d_); } // Recurse Scalar cost = SeedKmppUpdateAssignment(node->lower_node, new_cluster, centers, dist_sq) + SeedKmppUpdateAssignment(node->upper_node, new_cluster, centers, dist_sq); int i1 = node->lower_node->kmpp_cluster_index, i2 = node->upper_node->kmpp_cluster_index; if (i1 == i2 && i1 != -1) node->kmpp_cluster_index = i1; else node->kmpp_cluster_index = -1; return cost; }
[ "danmuno@f5854215-dd47-0410-b2c4-cdd35faa7885" ]
[ [ [ 1, 364 ] ] ]
d3c9c085364ad6a7d966a43af4e435282908c4c2
1092bd6dc9b728f3789ba96e37e51cdfb9e19301
/loci/numeric/detail/euler/basic_euler.h
27bf89b7b75c3fafaf30e9689ea9901a6c889de6
[]
no_license
dtbinh/loci-extended
772239e63b4e3e94746db82d0e23a56d860b6f0d
f4b5ad6c4412e75324d19b71559a66dd20f4f23f
refs/heads/master
2021-01-10T12:23:52.467480
2011-03-15T22:03:06
2011-03-15T22:03:06
36,032,427
0
0
null
null
null
null
UTF-8
C++
false
false
1,172
h
#ifndef LOCI_NUMERIC_DETAIL_EULER_BASIC_EULER_H_ #define LOCI_NUMERIC_DETAIL_EULER_BASIC_EULER_H_ /** * Spatial euler classes. * Defines a templates base class for 3D euler angles to specialise. * * @file basic_euler.h * @author David Gill * @date 19/11/2009 */ #include "loci/numeric/detail/simple_maths_sequence.h" #include "loci/numeric/detail/xyzw_manipulators.h" namespace loci { namespace numeric { template <typename T> class basic_euler : public detail::with_xyz<detail::onesize_simple_maths_sequence<basic_euler, T, 3> > { public: basic_euler() { } explicit basic_euler(const T & value) { assign(value); } basic_euler(const T & x, const T & y, const T & z) { elems[0] = x; elems[1] = y; elems[2] = z; } T yaw() const { return y(); } T pitch() const { return x(); } T roll() const { return z(); } }; } // namespace numeric } // namespace loci #endif // LOCI_NUMERIC_DETAIL_EULER_BASIC_EULER_H_
[ "[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132" ]
[ [ [ 1, 50 ] ] ]
4b6082129a24877b6cca20a8f7363d17c2b584e3
9773c3304eecc308671bcfa16b5390c81ef3b23a
/MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/AIPI_DecisionTree/Aipi_DT_AVF.h
42f320e30d730093be58d22e5ebed6989abda186
[]
no_license
15831944/AiPI-1
2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4
9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8
refs/heads/master
2021-12-02T20:34:03.136125
2011-10-27T00:07:54
2011-10-27T00:07:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
846
h
// Aipi_DT_AVF.h: interface for the CAipi_DT_AVF class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_AIPI_DT_AVF_H__8926F452_8CCE_4A50_96F2_7BB9CEFF6A26__INCLUDED_) #define AFX_AIPI_DT_AVF_H__8926F452_8CCE_4A50_96F2_7BB9CEFF6A26__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CAipi_DT_AVF { public: CAipi_DT_AVF(); virtual ~CAipi_DT_AVF(); public: void setAtributeName(tstring a); void setAtributeValue(tstring av); void setAtributeValueFreq(int freq); tstring getAtributeName(); tstring getAtributeValue(); int getAtributeValueFreq(); public: std::tstring m_AtributeName; std::tstring m_AtributeValue; int m_Freq; }; #endif // !defined(AFX_AIPI_DT_AVF_H__8926F452_8CCE_4A50_96F2_7BB9CEFF6A26__INCLUDED_)
[ [ [ 1, 33 ] ] ]
d51bf4d172681866b941cbac4158d5d916d1001b
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/Libs/LTGUIMgr/ltguilargetext.cpp
c98a47485644fa117d415915ed345b3ee8583c56
[]
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
10,850
cpp
// ----------------------------------------------------------------------- // // // MODULE : LTGUILargeText.cp // // PURPOSE : Simple text control which may be used as a menu item. // // (c) 2001 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "ltguimgr.h" #include "LTGUILargeText.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CLTGUILargeText::CLTGUILargeText() { m_nFixedHeight = 0; m_nNumLines = 0; memset(m_nLineOffsets,0,sizeof(m_nLineOffsets)); m_nFirstLine = kMaxNumLines+1; m_nLastLine = kMaxNumLines+1; m_nFrameWidth = 0; memset(m_Frame,0,sizeof(m_Frame)); m_pUp = LTNULL; m_pDown = LTNULL; } CLTGUILargeText::~CLTGUILargeText() { Destroy(); } // Create the control LTBOOL CLTGUILargeText::Create ( const char *pText, CUIFont *pFont, uint8 nFontSize, LTIntPt ptTextSize ) { if (!SetFont(pFont,nFontSize)) { return LTFALSE; } if (!SetSize(ptTextSize)) { return LTFALSE; } // Add the string if (pText) { SetString(pText); } return LTTRUE; } // Destroys the control void CLTGUILargeText::Destroy ( ) { CLTGUITextCtrl::Destroy ( ); if (m_pUp) { debug_delete(m_pUp); m_pUp = LTNULL; } if (m_pDown) { debug_delete(m_pDown); m_pDown = LTNULL; } } LTBOOL CLTGUILargeText::SetSize(LTIntPt ptTextSize) { if (ptTextSize.x < (m_nBaseFontSize * 2)) return LTFALSE; if (ptTextSize.y < m_nBaseFontSize) return LTFALSE; SetFixedWidth(ptTextSize.x); m_nFixedHeight = ptTextSize.y; CalculateSize(); return LTTRUE; } void CLTGUILargeText::CalculateSize() { m_nWidth = (uint16)(m_fScale * (float)m_nFixedWidth); m_nHeight = (uint16)(m_fScale * (float)m_nFixedHeight); if (m_pUp) m_nWidth += m_pUp->GetWidth(); float frameW = ((float)m_nFrameWidth * m_fScale); //top float fx = (float)m_pos.x - frameW; float fy = (float)m_pos.y - frameW; float fw = (float)m_nWidth + frameW; float fh = frameW; g_pDrawPrim->SetXYWH(&m_Frame[0],fx,fy,fw,fh); //right fx = (float)(m_pos.x + m_nWidth); fy = (float)m_pos.y - frameW; fw = (float)frameW; fh = (float)m_nHeight + frameW; g_pDrawPrim->SetXYWH(&m_Frame[1],fx,fy,fw,fh); //bottom fx = (float)m_pos.x; fy = (float)(m_pos.y + m_nHeight); fw = (float)m_nWidth + frameW; fh = frameW; g_pDrawPrim->SetXYWH(&m_Frame[2],fx,fy,fw,fh); //left fx = (float)m_pos.x - frameW; fy = (float)m_pos.y; fw = (float)frameW; fh = (float)m_nHeight + frameW; g_pDrawPrim->SetXYWH(&m_Frame[3],fx,fy,fw,fh); CalculateLines(); } void CLTGUILargeText::CalculateLines() { m_nNumLines = 0; memset(m_nLineOffsets,0,sizeof(m_nLineOffsets)); m_nFirstLine = kMaxNumLines+1; m_nLastLine = kMaxNumLines+1; if (m_pString && m_pString->GetLength()) { LT_POLYGT4* pPolys = m_pString->GetPolys(); uint16 nPos = 0; float fYPos = pPolys[nPos].verts[ 0 ].y; m_nNumLines = 1; m_nLineOffsets[0] = 0; //if the pos is in our rect, and we haven't found the first line yet, this is it if (fYPos >= m_pos.y) m_nFirstLine = 0; //while we have chars to test while (nPos < m_pString->GetLength()) { //find the top of the char float fTestY = pPolys[nPos].verts[ 0 ].y; //have started a new line? if (fTestY > fYPos) { //if the pos is in our rect, and we haven't found the first line yet, this is it if (fTestY >= m_pos.y && m_nFirstLine > kMaxNumLines) m_nFirstLine = m_nNumLines; //if the os is past the bottom of our rect, and we haven't found the last line, this is it if (fTestY+m_nFontSize >= (m_pos.y+m_nHeight) && m_nLastLine > kMaxNumLines) m_nLastLine = m_nNumLines-1; fYPos = fTestY; m_nLineOffsets[m_nNumLines] = nPos; m_nNumLines++; if (m_nNumLines >= kMaxNumLines) { ASSERT(!"CLTGUILargeText::SetSize() : Too many lines."); return; } } nPos++; } //if we never ran past the bottom, the last line visible is the last line if (m_nLastLine > kMaxNumLines) m_nLastLine = m_nNumLines-1; } } // Render the control void CLTGUILargeText::Render() { // Sanity checks... if (!IsVisible() || !m_pString) return; if (m_nFrameWidth) { // set up the render state SetRenderState(); for (int f = 0;f < 4; ++f) g_pDrawPrim->SetRGBA(&m_Frame[f],GetCurrentColor()); // draw our frames g_pDrawPrim->DrawPrim(m_Frame,4); } uint32 argbColor=GetCurrentColor(); m_pString->SetColor(argbColor); //if we know what lines to draw if (m_nFirstLine <= kMaxNumLines) { //figure out the first char uint16 nFirstChar = m_nLineOffsets[m_nFirstLine]; uint16 nLastChar = m_pString->GetLength(); //if the last line drawn is not the last overall line, // find the first char of the next line and step back one if (m_nLastLine < (m_nNumLines-1)) nLastChar = m_nLineOffsets[m_nLastLine+1]; // draw 'em m_pString->Render(nFirstChar,nLastChar); if (m_pUp && m_nFirstLine > 0) m_pUp->Render(); if (m_pDown && m_nFirstLine < (m_nNumLines-1) ) m_pDown->Render(); } } // Sets the width of the text's frame, set to 0 to not show the frame void CLTGUILargeText::SetFrameWidth(uint8 nFrameWidth) { m_nFrameWidth = nFrameWidth; if (nFrameWidth) { CalculateSize(); } } void CLTGUILargeText::SetRenderState() { g_pDrawPrim->SetTransformType(DRAWPRIM_TRANSFORM_SCREEN); g_pDrawPrim->SetZBufferMode(DRAWPRIM_NOZ); g_pDrawPrim->SetClipMode(DRAWPRIM_NOCLIP); g_pDrawPrim->SetFillMode(DRAWPRIM_FILL); g_pDrawPrim->SetColorOp(DRAWPRIM_NOCOLOROP); g_pDrawPrim->SetAlphaTestMode(DRAWPRIM_NOALPHATEST); g_pDrawPrim->SetAlphaBlendMode(DRAWPRIM_NOBLEND); } void CLTGUILargeText::SetBasePos ( LTIntPt pos ) { CLTGUICtrl::SetBasePos(pos); if (m_pString) { float fi = (float)m_nIndent * m_fScale; float line = 0; if (m_nFirstLine <= kMaxNumLines) { line = (float)(m_nFirstLine * m_nFontSize); } m_pString->SetPosition((float)m_pos.x+fi,(float)m_pos.y+line); } if (m_pUp) { LTIntPt pos = m_basePos; pos.x += m_nFixedWidth; m_pUp->SetBasePos(pos); } if (m_pDown) { LTIntPt pos = m_basePos; pos.x += m_nFixedWidth; pos.y += (m_nFixedHeight - m_pDown->GetHeight()); m_pDown->SetBasePos(pos); } } void CLTGUILargeText::SetScale(float fScale) { CLTGUICtrl::SetScale(fScale); m_nFontSize = (uint8)(m_fScale * (float)m_nBaseFontSize); uint16 nWidth = (uint16)(m_fScale * (float)(m_nFixedWidth-m_nIndent)); if (m_pString) { float fi = (float)m_nIndent * m_fScale; float line = 0; if (m_nFirstLine <= kMaxNumLines) { line = (float)(m_nFirstLine * m_nFontSize); } m_pString->SetPosition((float)m_pos.x+fi,(float)m_pos.y+line); m_pString->SetCharScreenHeight(m_nFontSize); m_pString->SetWrapWidth(nWidth); } if (m_pUp) { m_pUp->SetScale(m_fScale); } if (m_pDown) { m_pDown->SetScale(m_fScale); } CalculateSize(); } void CLTGUILargeText::SetIndent(uint16 nIndent) { if (m_nFixedWidth) { ASSERT(m_nFixedWidth > nIndent); if(m_nFixedWidth <= nIndent) return; } m_nIndent = nIndent; if (m_nFixedWidth && !m_bClip) { uint16 nTrueWidth = (uint16)(m_fScale * (float)(m_nFixedWidth-m_nIndent)); if (m_pString) { m_pString->SetWrapWidth(nTrueWidth); } } if (m_pString) { float fi = (float)m_nIndent * m_fScale; float line = 0; if (m_nFirstLine <= kMaxNumLines) { line = (float)(m_nFirstLine * m_nFontSize); } m_pString->SetPosition((float)m_pos.x+fi,(float)m_pos.y+line); } CalculateSize(); } LTBOOL CLTGUILargeText::OnUp ( ) { if (!m_pString || m_nFirstLine == 0 || m_nFirstLine > kMaxNumLines) return LTFALSE; m_nFirstLine--; float fi = (float)m_nIndent * m_fScale; LT_POLYGT4* pPolys = m_pString->GetPolys(); uint16 nPos = m_nLineOffsets[m_nFirstLine]; float fYPos = pPolys[nPos].verts[ 0 ].y; float fBasePos = pPolys[0].verts[ 0 ].y; float offset = fYPos - fBasePos; m_pString->SetPosition((float)m_pos.x+fi,(float)m_pos.y-offset); CalculateLines(); return LTTRUE; } LTBOOL CLTGUILargeText::OnDown ( ) { if (!m_pString || m_nFirstLine >= (m_nNumLines-1) ) return LTFALSE; m_nFirstLine++; float fi = (float)m_nIndent * m_fScale; LT_POLYGT4* pPolys = m_pString->GetPolys(); uint16 nPos = m_nLineOffsets[m_nFirstLine]; float fYPos = pPolys[nPos].verts[ 0 ].y; float fBasePos = pPolys[0].verts[ 0 ].y; float offset = fYPos - fBasePos; m_pString->SetPosition((float)m_pos.x+fi,(float)m_pos.y-offset); CalculateLines(); return LTTRUE; } // Handles the left button down message LTBOOL CLTGUILargeText::OnLButtonDown(int x, int y) { // Get the control that the click was on if (m_pUp && m_pUp->IsOnMe(x,y)) { m_pUp->Select(LTTRUE); return LTTRUE; } if (m_pDown && m_pDown->IsOnMe(x,y)) { m_pDown->Select(LTTRUE); return LTTRUE; } return LTFALSE; } // Handles the left button up message LTBOOL CLTGUILargeText::OnLButtonUp(int x, int y) { // Get the control that the click was on if (m_pUp && m_pUp->IsOnMe(x,y) && m_pUp->IsSelected()) { m_pUp->Select(LTFALSE); return OnUp(); } if (m_pDown && m_pDown->IsOnMe(x,y) && m_pDown->IsSelected()) { m_pDown->Select(LTFALSE); return OnDown(); } return LTFALSE; } // Handles the mouse move message LTBOOL CLTGUILargeText::OnMouseMove(int x, int y) { if (m_pUp && !m_pUp->IsOnMe(x,y)) m_pUp->Select(LTFALSE); if (m_pDown && !m_pDown->IsOnMe(x,y)) m_pDown->Select(LTFALSE); return LTFALSE; } LTBOOL CLTGUILargeText::UseArrows(LTFLOAT fTextureScale, HTEXTURE hUpNormal, HTEXTURE hUpSelected, HTEXTURE hDownNormal, HTEXTURE hDownSelected) { if (m_pUp) { debug_delete(m_pUp); m_pUp = LTNULL; } if (m_pDown) { debug_delete(m_pDown); m_pDown = LTNULL; } m_pUp = debug_new(CLTGUIButton); m_pUp->Create(LTNULL,LTNULL,hUpNormal,hUpSelected); m_pUp->SetTextureScale(fTextureScale); LTIntPt pos = m_basePos; pos.x += m_nFixedWidth; m_pUp->SetBasePos(pos); m_pUp->SetScale(m_fScale); m_pDown = debug_new(CLTGUIButton); m_pDown->Create(LTNULL,LTNULL,hDownNormal,hDownSelected); m_pDown->SetTextureScale(fTextureScale); pos.y += (m_nFixedHeight - m_pDown->GetHeight()); m_pDown->SetBasePos(pos); m_pDown->SetScale(m_fScale); CalculateSize(); return LTTRUE; }
[ [ [ 1, 503 ] ] ]
91db9407e0558de155f59b47c237dde4a479fcf1
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/src/nvmesh/kdtree/KDTree.h
0d074e8cf6c1f92ceb558978988b5654dc00bc92
[]
no_license
saggita/nvidia-mesh-tools
9df27d41b65b9742a9d45dc67af5f6835709f0c2
a9b7fdd808e6719be88520e14bc60d58ea57e0bd
refs/heads/master
2020-12-24T21:37:11.053752
2010-09-03T01:39:02
2010-09-03T01:39:02
56,893,300
0
1
null
null
null
null
ISO-8859-10
C++
false
false
4,807
h
// This code is in the public domain -- Ignacio Castaņo <[email protected]> #ifndef NV_MESH_KDTREE_H #define NV_MESH_KDTREE_H #include <nvcore/Ptr.h> #include <nvmath/Box.h> #include <nvmesh/nvmesh.h> #include <nvmesh/raytracing/FaceBuffer.h> namespace nv { /// KDTree acceleration structure. class KDTree// : public RefCounted { friend class KDTreeBuilder; public: struct Cache; struct Query; /// Ctor. KDTree() : m_nodeCount(0), m_nodeBuffer(NULL), m_leafFaceCount(0), m_leafFaceBuffer(NULL), m_faceBuffer(NULL) { // Enabled or not, reset the stats. m_node_test_count = 0; m_leaf_test_count = 0; m_face_test_count = 0; } /** @name Tree queries. */ //@{ NVMESH_API bool testRay(const Ray & ray, Query * query = NULL) const; NVMESH_API void testRay(const Ray & ray, Hit * hit, Query * query = NULL) const; //NVMESH_API bool testRay(const Cache & cache, const Ray & ray) const; NVMESH_API void testRay(const Cache & cache, const Ray & ray, Hit * hit, Query * query = NULL) const; // Debug method. void testAllFaces(const Ray & ray, Hit * hit) const; NVMESH_API Cache * createCache() const; NVMESH_API void deleteCache(Cache * ) const; NVMESH_API Query * createQuery() const; NVMESH_API void deleteQuery(Query * ) const; NVMESH_API void initSphericalCache(const Ray & ray, Cache * cache) const; NVMESH_API void initHemiSphericalCache(const Ray & ray, Cache * cache) const; Box bounds() const { return m_bounds; } //@} /** @name Tree allocation. */ //@{ NVMESH_API void allocateNodes(uint nodeCount); NVMESH_API void allocateLeafFaces(uint leafFaceCount); NVMESH_API void allocateFaces(uint faceCount); NVMESH_API void free(); //@} private: struct Node; struct Leaf; struct Face; // Node tests. void testRayIterative(const Ray & ray, Hit * hit, Query * query) const; bool testRayIterative(const Ray & ray, Query * query) const; // Face tests. bool testFace(const uint f, const Ray & ray, Hit * hit) const; bool testFaceDoubleSided(const uint f, const Ray & ray, Hit * hit) const; /// Returns true if the tree is built, returns false otherwise. bool isReady() const { return m_nodeBuffer != NULL; } /// Get node pointer for the given offset. const Node * nodeAt(const uint offset) const { nvDebugCheck(offset / sizeof(Node) < m_nodeCount); return reinterpret_cast<Node *>(m_nodeBuffer + offset); } /// Get left side child node. const Node * leftSideSon(const Node * node) const { return nodeAt(node->offset()); } /// Get right side child node. const Node * rightSideSon(const Node * node) const { return nodeAt(node->offset()) + 1; } /// Get leaf face pointer for the given offset. const uint * leafFaces(const uint offset) const { nvDebugCheck(offset / sizeof(uint) < m_leafFaceCount); return reinterpret_cast<uint *>(m_leafFaceBuffer + offset); } friend Stream & operator<< (Stream & s, KDTree & tree); private: friend Stream & operator<< (Stream & s, Node & node); /// Get node buffer. Node * nodeBuffer() { return reinterpret_cast<Node *>(m_nodeBuffer); } /// Get leaf face buffer. uint * leafFaceBuffer() { return reinterpret_cast<uint *>(m_leafFaceBuffer); } /// Stack item. struct Item { Item() {} Item(const Item & i) : node(i.node), t_near(i.t_near), t_far(i.t_far) { } Item(const Node * b, float n, float f) : node(b), t_near(n), t_far(f) { } const Node * node; float t_near; float t_far; }; /// Inner node of the tree. This is public, because is used in the cache. struct Node { bool isLeaf() const { return (flags & uint(1<<31)) != 0; // flags < 0 } uint dimension() const { return flags & 0x3; } uint offset() const { return flags & 0x7FFFFFFC; } uint32 flags; // bits 0..1 : splitting dimension // bits 2..30 : offset bits // bit 31 (sign) : flag whether node is a leaf. float distance; }; /// Leaf of the tree. struct Leaf { uint32 flags; // bits 0..1 : face types. (not used) // bits 2..30 : offset to first son. // bit 31 (sign) : flag whether node is a leaf. uint32 face_count; }; Box m_bounds; uint m_nodeCount; uint8 * m_nodeBuffer; uint m_leafFaceCount; uint8 * m_leafFaceBuffer; FaceBuffer * m_faceBuffer; // Traversal state. Changes during the queries. @@ Move this to a query object. KD-Tree should be reentrant. //mutable uint m_last; //mutable Item m_stack[32]; public: // Statistics. mutable uint m_node_test_count; mutable uint m_leaf_test_count; mutable uint m_face_test_count; }; } // nv namespace #endif // NV_MESH_KDTREE_H
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 200 ] ] ]
54e6bd6e5c93cfdbff5b0882b0619afd01f549cf
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/wiseml/writer/wiseml_scenario_collector.cpp
d25820a2c73ca4b8713e45c68b7812dcf08fadae
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,010
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2010 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #include "apps/wiseml/writer/wiseml_scenario_collector.h" #ifdef ENABLE_WISEML namespace wiseml { WisemlScenarioCollector:: WisemlScenarioCollector(shawn::SimulationController &sc, std::string id) : WisemlDataCollector(sc, id) {} // ---------------------------------------------------------------------- WisemlScenarioCollector::~WisemlScenarioCollector(){} // ---------------------------------------------------------------------- std::string WisemlScenarioCollector::name() const throw() { return id_; } // ---------------------------------------------------------------------- std::string WisemlScenarioCollector::description() const throw() { return "Scenario section data"; } // ---------------------------------------------------------------------- double WisemlScenarioCollector::next_timestamp_after(double time) { double next = -1.0; if(items_.upper_bound(time) != items_.end()) next = items_.upper_bound(time)->first; return next; } // ---------------------------------------------------------------------- // Data collection methods // ---------------------------------------------------------------------- void WisemlScenarioCollector::enable_node(std::string node) { double timestamp = current_time(); string item = "en,"; item += node; items_.insert(pair<double, string>(timestamp, item)); } // ---------------------------------------------------------------------- void WisemlScenarioCollector::disable_node(std::string node) { double timestamp = current_time(); string item = "dn,"; item += node; items_.insert(pair<double, string>(timestamp, item)); } // ---------------------------------------------------------------------- void WisemlScenarioCollector:: enable_link(std::string src, std::string dst) { double timestamp = current_time(); string item = "el,"; item += src + string(",") + dst; items_.insert(pair<double, string>(timestamp, item)); } // ---------------------------------------------------------------------- void WisemlScenarioCollector:: disable_link(std::string src, std::string dst) { double timestamp = current_time(); string item = "dl,"; item += src + string(",") + dst; items_.insert(pair<double, string>(timestamp, item)); } // ---------------------------------------------------------------------- void WisemlScenarioCollector::node_movement(std::string node) { double timestamp = current_time(); shawn::Vec pos = sc_.world().find_node_by_label(node)->real_position(); std::stringstream item; item << "np," << node << "," << pos.x() << "," << pos.y() << "," << pos.z(); items_.insert(pair<double, string>(timestamp, item.str())); } // ---------------------------------------------------------------------- void WisemlScenarioCollector::capability_value(std::string node, std::string capability, std::string value) { double timestamp = current_time(); std::stringstream item; item << "nc," << node << "," << capability << "," << value; items_.insert(pair<double, string>(timestamp, item.str())); } // ---------------------------------------------------------------------- std::string WisemlScenarioCollector::generate_xml() const { std::stringstream wml; wml << "\t" << "<scenario id=\"" << id_ << "\">" << std::endl; double next_timestamp = items_.lower_bound(0.0)->first; while(next_timestamp >= 0.0) { wml << "\t\t" << "<timestamp>" << next_timestamp << "</timestamp>" << std::endl; wml << generate_timestamp_xml(next_timestamp); if(items_.upper_bound(next_timestamp)!= items_.end()) next_timestamp = items_.upper_bound(next_timestamp)->first; else next_timestamp = -1.0; } wml << "\t</scenario>" << std::endl; return wml.str(); } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- std::string WisemlScenarioCollector::generate_timestamp_xml(double timestamp) const { std::stringstream wml; std::map<string, NodeTemplate*> nodes; std::map<string, pair<LinkInfo*, bool> > links; std::multimap<double, std::string>::const_iterator ts_begin = items_.lower_bound(timestamp); std::multimap<double, std::string>::const_iterator ts_end = items_.upper_bound(timestamp); for(std::multimap<double, std::string>::const_iterator it = ts_begin; it != ts_end; ++it) { std::list<std::string> data(make_list(it->second)); list<string>::iterator dit = data.begin(); std::string datatype = dit->c_str(); if(datatype == "en") { ++dit; std::string label = dit->c_str(); wml << "\t\t<enablenode id=\"" << label << "\"/>" << std::endl; } else if(datatype == "dn") { ++dit; std::string label = dit->c_str(); wml << "\t\t<disablenode id=\"" << label << "\"/>" << std::endl; } else if(datatype == "el") { ++dit; std::string source = dit->c_str(); ++dit; std::string target = dit->c_str(); wml << "\t\t<enablelink source=\"" << source << "\"/>" << "target=\"" << target << "\"/>" << std::endl; } else if(datatype == "dl") { ++dit; std::string source = dit->c_str(); ++dit; std::string target = dit->c_str(); wml << "\t\t<disablelink source=\"" << source << "\"/>" << "target=\"" << target << "\"/>" << std::endl; } else if(datatype == "np") { ++dit; std::string label = dit->c_str(); NodeTemplate *tmp; if(nodes.find(label) != nodes.end()) { tmp = nodes.find(label)->second; } else { tmp = new NodeTemplate(); nodes.insert(pair<string, NodeTemplate*>(label, tmp)); } tmp->label = label; ++dit; tmp->posx = atof(dit->c_str()); ++dit; tmp->posy= atof(dit->c_str()); ++dit; tmp->posz = atof(dit->c_str()); Capability dummy; dummy.name = "positioned"; tmp->capabilities.push_front(dummy); } else if(datatype == "nc") { ++dit; std::string label = dit->c_str(); NodeTemplate *tmp; if(nodes.find(label) != nodes.end()) { tmp = nodes.find(label)->second; } else { tmp = new NodeTemplate(); nodes.insert(pair<string, NodeTemplate*>(label, tmp)); } tmp->label = label; Capability cap; ++dit; cap.name = dit->c_str(); ++dit; cap.def_value = dit->c_str(); tmp->capabilities.push_back(cap); } /// Item syntax: lrssi;source_node;target_node;rssi_value else if(datatype == "lrssi") { ++dit; std::string src = dit->c_str(); ++dit; std::string dst = dit->c_str(); ++dit; std::string value = dit->c_str(); LinkInfo *info; if(links.find(src + dst) != links.end()) { info = links.find(src + dst)->second.first; links.find(src + dst)->second.second = true; } else { info = new LinkInfo(); links.insert(pair<string, pair<LinkInfo*, bool> >(src+dst, pair<LinkInfo*, bool>(info, true))); } info->source = src; info->target = dst; info->rssi = value; } /// Item syntax: /// lc;source_node;target_node;capability_name;capability_value else if(datatype == "lc") { ++dit; std::string src = dit->c_str(); ++dit; std::string dst = dit->c_str(); LinkInfo *info; if(links.find(src + dst) != links.end()) { info = links.find(src + dst)->second.first; } else { info = new LinkInfo(); links.insert(pair<string, pair<LinkInfo*, bool> >(src+dst, pair<LinkInfo*, bool>(info, false))); } info->source = src; info->target = dst; Capability cap; ++dit; cap.name = dit->c_str();; ++dit; cap.def_value = dit->c_str(); info->capabilities.push_back(cap); } } for(map<string, NodeTemplate*>::iterator it = nodes.begin(); it != nodes.end(); ++it) { wml << "\t\t<node id=\"" << it->second->label << "\">" << std::endl; if(it->second->capabilities.front().name == "positioned") { wml << "\t\t\t<position>" << std::endl; wml << "\t\t\t\t<x>" << it->second->posx << "</x>" << std::endl; wml << "\t\t\t\t<y>" << it->second->posy << "</y>" << std::endl; wml << "\t\t\t\t<z>" << it->second->posz << "</z>" << std::endl; wml << "\t\t\t</position>" << std::endl; } for(CapList::iterator cit = it->second->capabilities.begin(); cit != it->second->capabilities.end(); ++cit) { if(cit->name != "positioned") wml << "\t\t\t<data key=\"" << cit->name << "\">" << cit->def_value << "</data>" << std::endl; } wml << "\t\t</node>" << std::endl; } for(map<string, pair<LinkInfo*,bool> >::iterator it = links.begin(); it != links.end(); ++it) { wml << "\t\t<link source=\"" << it->second.first->source << "\" " << "target=\"" << it->second.first->target << "\">" << std::endl; if(it->second.second) { wml << "\t\t\t<rssi>" << it->second.first->rssi << "</rssi>" << std::endl; } for(CapList::iterator cit = it->second.first->capabilities.begin(); cit != it->second.first->capabilities.end(); ++cit) { wml << "\t\t\t<data key=\"" << cit->name << "\">" << cit->def_value << "</data>" << std::endl; } wml << "\t\t</link>" << std::endl; } return wml.str(); } // ---------------------------------------------------------------------- void WisemlScenarioCollector::clear() { items_.clear(); } } #endif
[ [ [ 1, 323 ] ] ]
63276dfb8ad0a2fea3ce29cd3fe9102b07c8a803
9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab
/demos/rtc/RTCSAMPLE/rtcwatcher.h
f950c7819aaff6f163629ceb0fab8511baf27526
[]
no_license
zzjs2001702/sfsipua-svn
ca3051b53549066494f6264e8f3bf300b8090d17
e8768338340254aa287bf37cf620e2c68e4ff844
refs/heads/master
2022-01-09T20:02:20.777586
2006-03-29T13:24:02
2006-03-29T13:24:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,889
h
// rtcwatcher.h // #ifndef _RTCWATCHER_H_ #define _RTCWATCHER_H_ #define WM_POPULATE WM_USER+200 // Class for the watcher window class CRTCWatcher { public: CRTCWatcher(); ~CRTCWatcher(); // Registers the window class static HRESULT RegisterClass(); // Window procedure static LRESULT CALLBACK WindowProc( HWND hWnd, // handle to window UINT uMsg, // message identifier WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); private: friend class CRTCWin; CRTCWin * m_pWin; IRTCClient * m_pClient; HWND m_hWnd; HWND m_hWatcherList; // Update a watcher entry in the watcher list HRESULT UpdateWatcherList(IRTCWatcher * pWatcher); // Clear the watcher list HRESULT ClearWatcherList(IRTCWatcher * pWatcher); HRESULT ClearWatcherList(); // Populate the watcher list HRESULT PopulateWatcherList(); // Add a watcher HRESULT DoAddWatcher(BSTR bstrURI, BSTR bstrName, RTC_WATCHER_STATE enState); // Remove a watcher HRESULT DoRemoveWatcher(IRTCWatcher *pWatcher); // Allow/Block a watcher HRESULT DoSetWatcherState(IRTCWatcher *pWatcher, RTC_WATCHER_STATE enState); // Window message handlers LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT OnCommand(UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT OnNotify(UINT uMsg, WPARAM wParam, LPARAM lParam); // Event handlers HRESULT DeliverWatcher(IRTCWatcher * pWatcher, RTC_WATCHER_EVENT_TYPE enType, LONG lStatus); }; #endif //_RTCWATCHER_H_
[ "yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd" ]
[ [ [ 1, 68 ] ] ]
b243e23bc6971e370a6f3eadaefcec7132666c1f
198faaa66e25fb612798ee7eecd1996f77f56cf8
/Console/PageSettingsTabs2.h
bbfa81062499df7d70164692e6039da535652c81
[]
no_license
atsuoishimoto/console2-ime-old
bb83043d942d91b1835acefa94ce7e1f679a9e41
85e7909761fde64e4de3687e49b1e1457d1571dd
refs/heads/master
2021-01-17T17:21:35.221688
2011-05-27T04:06:14
2011-05-27T04:06:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,100
h
#pragma once ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// class PageSettingsTabs2 : public CDialogImpl<PageSettingsTabs2> , public CWinDataExchange<PageSettingsTabs2> { public: enum { IDD = IDD_SETTINGS_TABS_2 }; PageSettingsTabs2(); BEGIN_DDX_MAP(PageSettingsTabs2) DDX_RADIO(IDC_RADIO_BK_TYPE, m_nBkType) DDX_TEXT(IDC_BK_IMAGE, m_strBkImage) DDX_CHECK(IDC_CHECK_BK_RELATIVE, m_nRelative) DDX_CHECK(IDC_CHECK_BK_EXTEND, m_nExtend) END_DDX_MAP() BEGIN_MSG_MAP(PageSettingsTabs2) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) // MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd) MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnCtlColorStatic) MESSAGE_HANDLER(WM_HSCROLL, OnHScroll) COMMAND_RANGE_CODE_HANDLER(IDC_RADIO_BK_TYPE, IDC_RADIO_BK_TYPE3, BN_CLICKED, OnClickedBkType) COMMAND_HANDLER(IDC_BK_COLOR, BN_CLICKED, OnClickedBkColor) COMMAND_ID_HANDLER(IDC_BTN_BROWSE_BK, OnBtnBrowseImage) COMMAND_HANDLER(IDC_TINT_COLOR, BN_CLICKED, OnClickedTintColor) END_MSG_MAP() // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnCtlColorStatic(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnHScroll(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnClickedBkType(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnClickedBkColor(WORD /*wNotifyCode*/, WORD /*wID*/, HWND hWndCtl, BOOL& /*bHandled*/); LRESULT OnBtnBrowseImage(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnClickedTintColor(WORD /*wNotifyCode*/, WORD /*wID*/, HWND hWndCtl, BOOL& /*bHandled*/); public: void UpdateSliderText(); void EnableControls(); void Load(shared_ptr<TabData>& tabData); void Save(); private: shared_ptr<TabData> m_tabData; CComboBox m_comboBkPosition; CTrackBarCtrl m_sliderTintOpacity; CStatic m_staticTintOpacity; CStatic m_staticCursorColor; CStatic m_staticBkColor; CStatic m_staticTintColor; int m_nBkType; CString m_strBkImage; int m_nRelative; int m_nExtend; }; //////////////////////////////////////////////////////////////////////////////
[ [ [ 1, 83 ] ] ]
6aeb3ae10f4d83aa5962e8453a29e93ea11f0f74
44890f9b95a8c77492bf38514d26c0da51d2fae5
/Gif/MotionFont/GifFont.cpp
1aefb722f291f9b7d0e6e10e6a9d7be66f7eed66
[]
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
GB18030
C++
false
false
19,523
cpp
#define _USE_MATH_DEFINES #include "GifFont.h" #include "drawing.h" #include <math.h> inline void GetChars(vector<string>& chars, string& text) { const char* p = text.c_str(); for (int i=0, end=text.length(); i<end;) { if (*(p+i)<0) { chars.push_back(text.substr(i,2)); i+=2; } else { chars.push_back(text.substr(i,1)); i++; } } } /* 0 个性化字体版本号 %d - 透明色 无 客户端背景不同有 1 画质 %d 2 帧数 %d 3 帧间隔时间 %d 单位:ms 4 边缘颜色 %d 负值表示没有边缘 5 阴影颜色 %d 负值表示没有阴影 6 阴影距离 %d 7 变换大小规则 %d 8 变换大小比例 %d 单位:1% 9 变换大小单字对齐 %d %d 负值表示随机 10 字体形状 %d 11 字体动画 %d */ string CGifFont::GetParamsString() { char chs[0x100]; string formatString = _T(""); #define ADD(i)\ formatString += itoa((int)(i), chs, 10);\ formatString.push_back(' '); ADD(m_Version); ADD(m_Quality); ADD(m_FramesCount); ADD(m_Interval); ADD(m_HasEdge?(m_EdgeColor&0x00ffffff):-1); ADD(m_HasShadow?(m_ShadowColor&0x00ffffff):-1); ADD(m_ShadowDis); ADD(m_Sizing); ADD(0.5+m_SizingProportion*100); ADD(m_SizingAlign); ADD(m_SizingVAlign); ADD(m_Shape); ADD(m_Motion); #undef ADD return formatString; } bool CGifFont::SetParamsString(string& formatString) { int index = 0, index1, t; #define GETT(i, type)\ index1 = formatString.find_first_of(' ', index);\ if (index1<0)\ return false;\ (i) = (type)atoi(formatString.substr(index, index1-index).c_str());\ index = index1+1; #define GET(i) GETT(i, int) GET(m_Version); GET(m_Quality); GET(m_FramesCount); GET(m_Interval); GET(m_EdgeColor); m_HasEdge = m_EdgeColor>=0; GET(m_ShadowColor); m_HasShadow = m_ShadowColor>=0; GET(m_ShadowDis); GETT(m_Sizing, SizingType); GET(t); m_SizingProportion = (double)t / 100; GETT(m_SizingAlign, AlignType); GETT(m_SizingVAlign, VAlignType); GETT(m_Shape, ShapeType); GETT(m_Motion, MotionType); #undef GET #undef GETT return true; } bool CGifFont::Generate(string& giffile, string& text, HFONT hFont) { if (!IsValid()) { return false; } CGifEncoder age; age.Start(giffile); age.SetQuality(m_Quality); age.SetTransparent(m_Transparent); age.SetRepeat(0); age.SetDelay(m_Interval); vector<string> chars; GetChars(chars, text); //迫使每次随机得到相同. srand(RANDSEED); AddFrames(age, chars, hFont); age.Finish(); return true; } void CGifFont::Check() { m_Transparent &= 0xffffff; CHECKRANGE(m_SizingProportion, 0.01, 1); CHECKRANGE(m_Quality, 1, 20); CHECKRANGE(m_Interval, 10, 10000); } bool CGifFont::IsValid() { Check(); return m_Sizing>=0 && m_Sizing<SIZINGCOUNT && m_SizingAlign>=-1 && m_SizingAlign<3 && m_SizingVAlign>=-1 && m_SizingVAlign<3 && m_Shape>=0 && m_Shape<SHAPECOUNT && m_Motion>=0 && m_Motion<MOTIONCOUNT; } void CGifFont::GetOrignalSize(CDC& dc, vector<string>& chars, int& w, int& h) { w = 0; h = 0; CSize size; for (int i=0; i<chars.size(); i++) { dc.GetTextExtent(chars[i].c_str(), chars[i].length(), &size); w += size.cx; h = max(h,size.cy); } if (m_HasShadow) { h += m_ShadowDis+2; w += chars.size()*(2+m_ShadowDis); } else if (m_HasEdge) { w += chars.size()*2; h += 2; } } HBITMAP CGifFont::GetOrignalBitmap(vector<string>& chars, HFONT hFont, LPBYTE& lpData, RECT& r, RECT* rs) { CDCHandle dcScreen = GetDC(NULL); CDC dc; dc.CreateCompatibleDC(dcScreen); dc.SetBkMode(TRANSPARENT); dc.SelectFont(hFont); int w,h; GetOrignalSize(dc, chars, w, h); r.left = 0; r.top = 0; r.right = w; r.bottom = h; lpData = NULL; HBITMAP hBm = CreateDIB(dcScreen, w, h, lpData), hBmp = dc.SelectBitmap(hBm); CBrush brush; brush.CreateSolidBrush(m_Transparent); dc.FillRect(&r, brush); if (rs == NULL) { DrawAllChars(dc,lpData,chars,0,0,w,h); } else { DrawAllChars(dc,lpData,chars,0,0,w,h,rs); } dc.SelectBitmap(hBmp); ::ReleaseDC(NULL,dcScreen.m_hDC); return hBm; } void CGifFont::AddFrames(CGifEncoder& ge, vector<string>& chars, HFONT hFont) { CRectMappingConverter *prmc; switch(m_Motion) { case Nomotion: DoNomotion(ge, chars, hFont); break; case DisappearingMotion: DoDisappearingMotion(ge, chars, hFont); break; case ShakeMotion: DoShakeMotion(ge, chars, hFont); break; case SnowMotion: DoSnowMotion(ge, chars, hFont); break; case BluringMotion: DoBluringMotion(ge, chars, hFont); break; //case SharpenMotion: // DoSharpenMotion(ge, chars, hFont); // break; case SizingMotion: DoSizingMotion(ge, chars, hFont); break; case HTurnOverMotion: prmc = new CHTurnOverRectMappingConverter(); DoRectMappingConvertMotion(prmc, ge, chars, hFont); delete prmc; break; case VTurnOverMotion: prmc = new CVTurnOverRectMappingConverter(); DoRectMappingConvertMotion(prmc, ge, chars, hFont); delete prmc; break; case RollingMotion: prmc = new CRollingRectMappingConverter(); DoRectMappingConvertMotion(prmc, ge, chars, hFont, true); delete prmc; break; case WobblyMotion: prmc = new CWobblyRectMappingConverter(); DoRectMappingConvertMotion(prmc, ge, chars, hFont, true); delete prmc; break; case JumperMotion: prmc = new CJumperRectMappingConverter(); DoRectMappingConvertMotion(prmc, ge, chars, hFont, true); delete prmc; break; case CircinateMotion: prmc = new CCircinateRectMappingConverter(); DoRectMappingConvertMotion(prmc, ge, chars, hFont, true); delete prmc; break; } } void CGifFont::DrawAllChars(CDC& dc, LPBYTE lpData, vector<string>& chars, int x, int y, int width, int height) { RECT* rs = new RECT[chars.size()]; DrawAllChars(dc, lpData, chars, x, y, width, height, rs); delete rs; } void CGifFont::DrawAllChars(CDC& dc, LPBYTE lpData, vector<string>& chars, int x, int y, int width, int height, RECT* rs) { for (int i=0; i<chars.size(); i++) { rs[i] = DrawOneChar(dc, lpData, chars, i, x, y, width, height); x = rs[i].right; } } void RectNoTransform(LPBYTE lpData, int cx, int cy, RECT& rc, DIB32COLOR trans) {} void PieSliceMap(double& x, double& y) { y*=0.8; y = 1-y; double alpha = (1+x)*M_PI/3; x = y * cos(alpha)+0.5; y = y * sin(alpha); x = 1-x; y = 1.1-y; } void RectToPieSlice(LPBYTE lpData, int cx, int cy, RECT& rc, DIB32COLOR trans) { RectConvert(lpData,cx,cy, rc, PieSliceMap, trans); } void MirrorMap(double& x, double& y) { x = 1-x; } void RectToMirror(LPBYTE lpData, int cx, int cy, RECT& rc, DIB32COLOR trans) { RectConvert(lpData,cx,cy, rc, MirrorMap, trans); } void ReflectionMap(double& x, double& y) { y = 1-y; } void RectToReflection(LPBYTE lpData, int cx, int cy, RECT& rc, DIB32COLOR trans) { RectConvert(lpData,cx,cy, rc, ReflectionMap, trans); } const RectTransformMethod rectTransformMethods[SHAPECOUNT] = {RectNoTransform, RectToEllipse, RectToTriangle, RectToDiamond, RectToSShape, RectToPieSlice, RectToMirror, RectToReflection}; void CGifFont::SizingConvert(LPBYTE lpData, int cx, int cy, RECT& rc, double proportion, AlignType at, VAlignType vt, DIB32COLOR trans) { CHECKRANGE(proportion, MINSIZINGPROPORTION, 1); int dx = rc.right-rc.left, dy = rc.bottom-rc.top; int* buffer = new int[dx*dy*4], *p; memset(buffer, 0, dx*dy*16); double w = (double)(dx-1), h = (double)(dy-1), pt2 = (1-proportion)/2; for (int i=dx-1; i>=0; i--) { for(int j=dy-1; j>=0; j--) { DIB32COLOR clr = DIBPixel(lpData, rc.left+i,rc.top+j,cx,cy); double x = (double)i/w, y = (double)j/h; //mapping x*=proportion; y*=proportion; //if (at<0) //{ // x+=(rand()%3)*pt2; //} //else { x+=(int)at*pt2; } //if (vt<0) //{ // y+=(rand()%3)*pt2; //} //else { y+=(int)vt*pt2; } CHECKRANGE(x, 0, 1); CHECKRANGE(y, 0, 1); int ix = INTROUND(x*w), iy = INTROUND(y*h); p = buffer+(ix+iy*dx)*4; p[0]++; p[1]+=GetR(clr); p[2]+=GetG(clr); p[3]+=GetB(clr); } } for (int i=dx-1; i>=0; i--) { for(int j=dy-1; j>=0; j--) { p = buffer+(i+j*dx)*4; if (*p==0) { DIBPixel(lpData,rc.left+i,rc.top+j,cx,cy) = trans; } else { DIBPixel(lpData,rc.left+i,rc.top+j,cx,cy) = GetAvg(p[1],p[2],p[3],p[0]); } } } delete buffer; } void CGifFont::Sizing(LPBYTE lpData, vector<string>& chars, int charIndex, int cx, int cy, RECT& rc, DIB32COLOR trans) { if (m_Sizing != NoSizing && m_SizingProportion < 1.0 && m_SizingProportion > 0.0) { AlignType at = m_SizingAlign; VAlignType vt = m_SizingVAlign; if (at<0) at = (AlignType)(rand()%3); if (vt<0) vt = (VAlignType)(rand()%3); double p = (double)(charIndex)/(double)(chars.size()-1); #define P(p) (1-(1-m_SizingProportion)*(p)) switch(m_Sizing) { case NormalSizing: SizingConvert(lpData, cx, cy, rc, m_SizingProportion, at, vt, trans); break; case RandomSizing: SizingConvert(lpData, cx, cy, rc, P((double)rand()/(double)RAND_MAX), at, vt, trans); break; case IncSizing: SizingConvert(lpData, cx, cy, rc, P(1-p), at, vt, trans); break; case DecSizing: SizingConvert(lpData, cx, cy, rc, P(p), at, vt, trans); break; case MiddleUpSizing: if (p<0.5) { p = 1-p; } SizingConvert(lpData, cx, cy, rc, P(p*2-1), at, vt, trans); break; case MiddleDownSizing: if (p<0.5) { p = 1-p; } SizingConvert(lpData, cx, cy, rc, P(2-p*2), at, vt, trans); break; case AlternateSizing: if (charIndex&1) { SizingConvert(lpData, cx, cy, rc, m_SizingProportion, at, vt, trans); } else { SizingConvert(lpData, cx, cy, rc, 1, at, vt, trans); } break; } } #undef P } RECT CGifFont::DrawOneChar(CDC& dc, LPBYTE lpData, vector<string>& chars, int charIndex, int x, int y, int width, int height) { string text = chars[charIndex]; CSize size; dc.GetTextExtent(text.c_str(), text.length(), &size); RECT rc; int exsize = 0, esize = 0; if (m_HasShadow) { float h,s,v,h1,s1,v1; GetHSBbyRGB(m_ShadowColor, h,s,v); GetHSBbyRGB(m_Transparent, h1,s1,v1); exsize = m_ShadowDis+2; DrawTextWithOuter(dc, text, size, x+m_ShadowDis, y+m_ShadowDis, m_ShadowColor, GetRGBbyHSB(h,s,(v+2*v1)/3)); } if (m_HasEdge) { if (exsize==0) { exsize = 2; } esize = 2; DrawTextWithOuter(dc, text, size, x, y, m_FontColor, m_EdgeColor); } else { dc.SetTextColor(m_FontColor); rc.left = x; rc.top = y; rc.right = x+size.cx; rc.bottom = y+size.cy; dc.DrawText(text.c_str(), text.length(), &rc, DT_SINGLELINE | DT_LEFT | DT_VCENTER); } rc.left = x; rc.top = y; rc.right = x + size.cx + exsize; rc.bottom = y + size.cy + exsize; DIB32COLOR trans = RGB2DIB(m_Transparent); rectTransformMethods[m_Shape](lpData, width, height, rc, trans); Sizing(lpData, chars, charIndex, width, height, rc, trans); if (m_Shape || m_Sizing) { AntiAliasing(lpData, width, height, rc, trans); } //rc.left = x; //rc.top = y; //rc.right = x + size.cx + esize; //rc.bottom = y + size.cy + esize; return rc; } void CGifFont::DoNomotion(CGifEncoder& ge, vector<string>& chars, HFONT hFont) { LPBYTE lpData; RECT rc; HBITMAP hBm = GetOrignalBitmap(chars, hFont, lpData, rc); ge.AddFrame(hBm); DeleteObject(hBm); } void CGifFont::DoDisappearingMotion(CGifEncoder& ge, vector<string>& chars, HFONT hFont) { LPBYTE lpData = NULL, lpData0; RECT rc; HBITMAP hBm = GetOrignalBitmap(chars, hFont, lpData, rc); int w = rc.right-rc.left, h = rc.bottom-rc.top; int fc = GetFramesCount(), fc2 = fc/2; if (fc2<2) { fc2 = 2; } HBITMAP* bms = new HBITMAP[fc2]; CBrush brush; brush.CreateSolidBrush(GetTransparent()); lpData0 = lpData; DIB32COLOR clr, trans = RGB2DIB(m_Transparent); CDCHandle dcScreen = GetDC(NULL); for (int i=0; i<fc2; i++) { CDC dc;dc.CreateCompatibleDC(dcScreen); LPBYTE lpData1 = NULL; bms[i] = CreateDIB(dc, w, h, lpData1); HBITMAP hBmp = dc.SelectBitmap(bms[i]); dc.FillRect(&rc, brush); for (int x=0; x<w; x++) { for (int y=0; y<h; y++) { if ((clr = DIBPixel(lpData0, x, y, w, h)) != trans && (rand()%fc)) { int xx = x-i-1 + (rand()%(2*i+3)), yy=y-i-1+(rand()%(2*i+3)); if (0<=xx&&xx<w&&0<=yy&&yy<h) { DIBPixel(lpData1, xx, yy, w, h) = clr; } } } } lpData0 = lpData1; dc.SelectBitmap(hBmp); } ge.AddFrame(hBm); fc2--; for (int i=0; i<fc2; i++) { ge.AddFrame(bms[i]); } for (int i=fc2; i>=0; i--) { ge.AddFrame(bms[i]); DeleteObject(bms[i]); } ge.AddFrame(hBm); DeleteObject(hBm); delete bms; ::ReleaseDC(NULL,dcScreen.m_hDC); } void CGifFont::DoShakeMotion( CGifEncoder& ge, vector<string>& chars, HFONT hFont) { CBrush brush; brush.CreateSolidBrush(m_Transparent); CDCHandle dcScreen = GetDC(NULL); CDC dc; dc.CreateCompatibleDC(dcScreen); dc.SetBkMode(TRANSPARENT); dc.SelectFont(hFont); int w,h; GetOrignalSize(dc, chars, w, h); const int d = 4; w+=d; h+=d; RECT r,rc; r.left = 0; r.top = 0; r.right = w; r.bottom = h; LPBYTE lpData = NULL; int fc = GetFramesCount(); if (fc<2) { fc = 2; } for (int i=fc; i>0; i--) { HBITMAP hBm = CreateDIB(dcScreen, w, h, lpData), hBmp = dc.SelectBitmap(hBm); dc.FillRect(&r, brush); int x=0,y=0; for (int i=0; i<chars.size(); i++) { rc = DrawOneChar(dc, lpData, chars, i, x+(rand()%d), y+(rand()%d), w, h); x+=rc.right-rc.left; } dc.SelectBitmap(hBmp); ge.AddFrame(hBm); DeleteObject(hBm); } ::ReleaseDC(NULL,dcScreen.m_hDC); } void CGifFont::DoSnowMotion(CGifEncoder& ge, vector<string>& chars, HFONT hFont) { DIB32COLOR clr, trans = RGB2DIB(m_Transparent); LPBYTE lpData = NULL; RECT rc; HBITMAP hBm = GetOrignalBitmap(chars, hFont, lpData, rc); int w = rc.right-rc.left, h = rc.bottom-rc.top; int buffersize = w*h*4; int fc = GetFramesCount(); if (fc<2) { fc = 2; } CDCHandle dcScreen = GetDC(NULL); for (int i=0; i<fc; i++) { CDC dc;dc.CreateCompatibleDC(dcScreen); LPBYTE lpData1 = NULL; HBITMAP hBm1 = CreateDIB(dc, w, h, lpData1); HBITMAP hBmp = dc.SelectBitmap(hBm1); memcpy(lpData1,lpData,buffersize); for (int x=0; x<w; x++) { for (int y=0; y<h; y++) { if (DIBPixel(lpData1, x, y, w, h) == trans) { int xx = x-2 + (rand()%5), yy=y+(rand()%3); if (xx>=w) { xx -=w; } if (xx<0) { xx +=w; } if (yy>=h) { yy-=h; } DIBPixel(lpData1, xx, yy, w, h) = trans; } } } dc.SelectBitmap(hBmp); ge.AddFrame(hBm1); DeleteObject(hBm1); } DeleteObject(hBm); ::ReleaseDC(NULL,dcScreen.m_hDC); } const int BluringMatrix[3][3] = {{1,1,1}, {1,1,1}, {1,1,1}}; void CGifFont::DoBluringMotion(CGifEncoder& ge, vector<string>& chars, HFONT hFont) { LPBYTE lpData = NULL, lpData0; RECT rc; HBITMAP hBm = GetOrignalBitmap(chars, hFont, lpData0, rc); int w = rc.right-rc.left, h = rc.bottom-rc.top; int fc = GetFramesCount(), fc2 = fc/2; if (fc2<2) { fc2 = 2; } HBITMAP* bms = new HBITMAP[fc2]; CDCHandle dcScreen = GetDC(NULL); for (int i=0; i<fc2; i++) { bms[i] = CreateDIB(dcScreen, w, h, lpData); Transform(lpData0, lpData, w,h, rc, BluringMatrix); lpData0 = lpData; } ge.AddFrame(hBm); fc2--; for (int i=0; i<fc2; i++) { ge.AddFrame(bms[i]); } for (int i=fc2; i>=0; i--) { ge.AddFrame(bms[i]); DeleteObject(bms[i]); } ge.AddFrame(hBm); DeleteObject(hBm); delete bms; ::ReleaseDC(NULL,dcScreen.m_hDC); } void CGifFont::DoSharpenMotion(CGifEncoder& ge, vector<string>& chars, HFONT hFont) { const int m[3][3] = {{1,2,1}, {2,-36,2}, {1,2,1}}; LPBYTE lpData = NULL, lpData0; RECT rc; HBITMAP hBm = GetOrignalBitmap(chars, hFont, lpData0, rc); int w = rc.right-rc.left, h = rc.bottom-rc.top; int fc = GetFramesCount(), fc2 = fc/2; if (fc2<2) { fc2 = 2; } HBITMAP* bms = new HBITMAP[fc2]; CDCHandle dcScreen = GetDC(NULL); for (int i=0; i<fc2; i++) { bms[i] = CreateDIB(dcScreen, w, h, lpData); Transform(lpData0, lpData, w,h, rc, m); lpData0 = lpData; } ge.AddFrame(hBm); fc2--; for (int i=0; i<fc2; i++) { ge.AddFrame(bms[i]); } for (int i=fc2; i>=0; i--) { ge.AddFrame(bms[i]); DeleteObject(bms[i]); } ge.AddFrame(hBm); DeleteObject(hBm); delete bms; ::ReleaseDC(NULL,dcScreen.m_hDC); } void CGifFont::DoSizingMotion( CGifEncoder& ge, vector<string>& chars, HFONT hFont) { DIB32COLOR trans = RGB2DIB(m_Transparent); LPBYTE lpData = NULL; RECT rc, *rs = new RECT[chars.size()]; HBITMAP hBm = GetOrignalBitmap(chars, hFont, lpData, rc, rs); int w = rc.right-rc.left, h = rc.bottom-rc.top; int fc = GetFramesCount(), fc2 = fc/2; if (fc2<2) { fc2 = 2; } fc = fc2*2; HBITMAP* bms = new HBITMAP[fc]; LPBYTE * lpDatas = new LPBYTE[fc]; CDCHandle dcScreen = GetDC(NULL); for (int i=0; i<fc; i++) { bms[i] = CreateDIB(dcScreen, w, h, lpDatas[i]); memcpy(lpDatas[i], lpData, 4*w*h); } DeleteObject(hBm); for (int index=chars.size()-1; index>=0; index--) { //if (m_HasShadow) //{ // rs[index].right += m_ShadowDis; // rs[index].bottom += m_ShadowDis; // if (!m_HasEdge) // { // rs[index].right += 2; // rs[index].bottom += 2; // } //} AlignType at = m_SizingAlign; VAlignType vt = m_SizingVAlign; if (at<0) at = (AlignType)(rand()%3); if (vt<0) vt = (VAlignType)(rand()%3); for (int i=0; i<fc2; i++) { SizingConvert(lpDatas[i], w, h, rs[index], 1 - (double)((i)%fc2)/(double)fc2, at, vt, trans); } for (int i=fc2; i<fc; i++) { SizingConvert(lpDatas[i], w, h, rs[index], (double)((i)%fc2)/(double)fc2, at, vt, trans); } } for (int i=0; i<fc; i++) { ge.AddFrame(bms[i]); DeleteObject(bms[i]); } delete bms; delete rs; delete lpDatas; ::ReleaseDC(NULL,dcScreen.m_hDC); } void CGifFont::DoRectMappingConvertMotion(CRectMappingConverter* prmc, CGifEncoder& ge, vector<string>& chars, HFONT hFont, bool bAntiAliasing) { DIB32COLOR clr, trans = RGB2DIB(m_Transparent); LPBYTE lpData = NULL; RECT rc, *rs = new RECT[chars.size()]; HBITMAP hBm = GetOrignalBitmap(chars, hFont, lpData, rc, rs); int w = rc.right-rc.left, h = rc.bottom-rc.top; int buffersize = w*h; int fc = GetFramesCount(); if (fc<4) { fc = 4; } double fc1 = (double)(fc-1); CDCHandle dcScreen = GetDC(NULL); CDC dc;dc.CreateCompatibleDC(dcScreen); LPBYTE lpData1 = NULL; HBITMAP hBm1 = CreateDIB(dc, w, h, lpData1); for (int i=0; i<fc; i++) { prmc->m_Pos = (double)i/fc1; FillDib32Color(lpData1, w, h, trans); for (int index=chars.size()-1; index>=0; index--) { prmc->RectConvert(lpData, lpData1, w, h, rs[index], trans); } if (bAntiAliasing) { AntiAliasing(lpData1, w, h, rc, trans); } ge.AddFrame(hBm1); } DeleteObject(hBm1); DeleteObject(hBm); ::ReleaseDC(NULL,dcScreen.m_hDC); }
[ "mr.huanghuan@48bf5850-ed27-0410-9317-b938f814dc16" ]
[ [ [ 1, 815 ] ] ]
50b1054098c680a05587a2a19c62a27b6d7d5584
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/HovercraftUniverse/StartPhantom.h
1ab38001c873a76ce3a973ffaa7ed64d4d4c2dc6
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
631
h
#ifndef STARTPHANTOM_H #define STARTPHANTOM_H #include <Physics/Dynamics/Phantom/hkpAabbPhantom.h> namespace HovUni { class Start; /** * A phantom to check if a player has passed the start line * @author Pieter-Jan Pintens */ class StartPhantom : public hkpAabbPhantom { private: Start * mStart; public: /** * Constructor * @param aabb, the bounding box */ StartPhantom(const hkAabb& aabb, Start * start ); ~StartPhantom(void); virtual void addOverlappingCollidable( hkpCollidable* handle ); virtual void removeOverlappingCollidable( hkpCollidable* handle ); }; } #endif
[ "pintens.pieterjan@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c", "[email protected]" ]
[ [ [ 1, 7 ], [ 10, 17 ], [ 20, 24 ], [ 26, 36 ] ], [ [ 8, 9 ], [ 18, 19 ], [ 25, 25 ] ] ]
bdd5ce595b75ba13c08d30214095afe3d1b54d18
17083b919f058848c3eb038eae37effd1a5b0759
/SimpleGL/sgl/GL/GLSamplerState.h
b2b7449a5f977ed780c3f45ad4a3ab07dd802f15
[]
no_license
BackupTheBerlios/sgl
e1ce68dfc2daa011bdcf018ddce744698cc7bc5f
2ab6e770dfaf5268c1afa41a77c04ad7774a70ed
refs/heads/master
2021-01-21T12:39:59.048415
2011-10-28T16:14:29
2011-10-28T16:14:29
39,894,148
0
0
null
null
null
null
UTF-8
C++
false
false
492
h
#ifndef SIMPLE_GL_GL_SAMPLER_STATE_H #define SIMPLE_GL_GL_SAMPLER_STATE_H #include "GLDevice.h" namespace sgl { class GLSamplerState : public ReferencedImpl<SamplerState> { public: GLSamplerState(sgl::GLDevice* device, const DESC& desc); // Override SamplerState const DESC& SGL_DLLCALL Desc() const { return desc; } private: GLDevice* device; // properties DESC desc; }; } // namepsace sgl #endif // SIMPLE_GL_GL_SAMPLER_STATE_H
[ "devnull@localhost" ]
[ [ [ 1, 26 ] ] ]
203076a677f185b1e548a97d247b269ba8e76f54
6188f1aaaf5508e046cde6da16b56feb3d5914bc
/Doc/Web/Shaders/Samples/Tutorials-0.8-src/1-06-texturing/main.cpp
5c3f67663a76860c8381e35ef546706491f5dc0c
[]
no_license
dogtwelve/fighter3d
7bb099f0dc396e8224c573743ee28c54cdd3d5a2
c073194989bc1589e4aa665714c5511f001e6400
refs/heads/master
2021-04-30T15:58:11.300681
2011-06-27T18:51:30
2011-06-27T18:51:30
33,675,635
1
0
null
null
null
null
UTF-8
C++
false
false
1,722
cpp
// ************************************************ // Tutorial 6: Textures // // (c) 2003 by Martin Christen. // ************************************************ #include "../cwc/aGLSL.h" #include "../cwc/simpleGL.h" #include <GL/glut.h> #include <iostream> using namespace std; #define FRAG_FILE "tutorial6.frag" #define VERT_FILE "tutorial6.vert" // GLobals: aShaderObject* myShader = 0; GLuint texture1; GLuint texture2; //************************************************************* //Draw one Frame (don't Swap Buffers) void DrawFrame(void) { //myShader->begin(); //myShader->sendUniform1i("myTexture", 0); // Texture Unit 0 glBindTexture(GL_TEXTURE_2D, texture1); glutSolidTeapot(1.0); glTranslatef(2.0,0.0,0.0); glBindTexture(GL_TEXTURE_2D, texture2); glutSolidTeapot(0.5); //myShader->end(); } void AppInit(void) { myShader = DefaultShaderSetup(VERT_FILE, FRAG_FILE); // --------------------------------------- // OpenGL Settings //DefaultLighting(); glEnable(GL_TEXTURE_2D); // LoadTexture is definied in simpleGL.cpp, it // loads a 256x256 RAW RGBA (32bit) texture. char* tex = LoadTexture("../textures/texture256x256RGBA.raw"); char* tex2 = LoadTexture("../textures/texture2-256x256RGBA.raw"); // createTexture creates an OpenGL 2D Texture (defined in // simpleGL.cpp) createTexture(tex, &texture1); createTexture(tex2, &texture2); } //************************************************************* // use App Exit to clean up void AppExit(void) { DefaultCleanup(); } //************************************************************* //END
[ "dmaciej1@f75eed02-8a0f-11dd-b20b-83d96e936561" ]
[ [ [ 1, 77 ] ] ]
2e45d2b2d3f3c0d198ae40721778857919c59568
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Source/Intersection/WmlIntrBox3Box3.cpp
8a3a5e5771c2cb3c50d47683d008145715835a56
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
35,160
cpp
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlIntrBox3Box3.h" #include "WmlIntrUtilityLin3.h" #include "WmlIntrUtilityBox3.h" using namespace Wml; //---------------------------------------------------------------------------- // stationary objects //---------------------------------------------------------------------------- template <class Real> bool Wml::TestIntersection (const Box3<Real>& rkBox0, const Box3<Real>& rkBox1) { // Cutoff for cosine of angles between box axes. This is used to catch // the cases when at least one pair of axes are parallel. If this happens, // there is no need to test for separation along the Cross(A[i],B[j]) // directions. const Real fCutoff = (Real)0.999999; bool bExistsParallelPair = false; int i; // convenience variables const Vector3<Real>* akA = rkBox0.Axes(); const Vector3<Real>* akB = rkBox1.Axes(); const Real* afEA = rkBox0.Extents(); const Real* afEB = rkBox1.Extents(); // compute difference of box centers, D = C1-C0 Vector3<Real> kD = rkBox1.Center() - rkBox0.Center(); Real aafC[3][3]; // matrix C = A^T B, c_{ij} = Dot(A_i,B_j) Real aafAbsC[3][3]; // |c_{ij}| Real afAD[3]; // Dot(A_i,D) Real fR0, fR1, fR; // interval radii and distance between centers Real fR01; // = R0 + R1 // axis C0+t*A0 for (i = 0; i < 3; i++) { aafC[0][i] = akA[0].Dot(akB[i]); aafAbsC[0][i] = Math<Real>::FAbs(aafC[0][i]); if ( aafAbsC[0][i] > fCutoff ) bExistsParallelPair = true; } afAD[0] = akA[0].Dot(kD); fR = Math<Real>::FAbs(afAD[0]); fR1 = afEB[0]*aafAbsC[0][0]+afEB[1]*aafAbsC[0][1]+afEB[2]*aafAbsC[0][2]; fR01 = afEA[0] + fR1; if ( fR > fR01 ) return false; // axis C0+t*A1 for (i = 0; i < 3; i++) { aafC[1][i] = akA[1].Dot(akB[i]); aafAbsC[1][i] = Math<Real>::FAbs(aafC[1][i]); if ( aafAbsC[1][i] > fCutoff ) bExistsParallelPair = true; } afAD[1] = akA[1].Dot(kD); fR = Math<Real>::FAbs(afAD[1]); fR1 = afEB[0]*aafAbsC[1][0]+afEB[1]*aafAbsC[1][1]+afEB[2]*aafAbsC[1][2]; fR01 = afEA[1] + fR1; if ( fR > fR01 ) return false; // axis C0+t*A2 for (i = 0; i < 3; i++) { aafC[2][i] = akA[2].Dot(akB[i]); aafAbsC[2][i] = Math<Real>::FAbs(aafC[2][i]); if ( aafAbsC[2][i] > fCutoff ) bExistsParallelPair = true; } afAD[2] = akA[2].Dot(kD); fR = Math<Real>::FAbs(afAD[2]); fR1 = afEB[0]*aafAbsC[2][0]+afEB[1]*aafAbsC[2][1]+afEB[2]*aafAbsC[2][2]; fR01 = afEA[2] + fR1; if ( fR > fR01 ) return false; // axis C0+t*B0 fR = Math<Real>::FAbs(akB[0].Dot(kD)); fR0 = afEA[0]*aafAbsC[0][0]+afEA[1]*aafAbsC[1][0]+afEA[2]*aafAbsC[2][0]; fR01 = fR0 + afEB[0]; if ( fR > fR01 ) return false; // axis C0+t*B1 fR = Math<Real>::FAbs(akB[1].Dot(kD)); fR0 = afEA[0]*aafAbsC[0][1]+afEA[1]*aafAbsC[1][1]+afEA[2]*aafAbsC[2][1]; fR01 = fR0 + afEB[1]; if ( fR > fR01 ) return false; // axis C0+t*B2 fR = Math<Real>::FAbs(akB[2].Dot(kD)); fR0 = afEA[0]*aafAbsC[0][2]+afEA[1]*aafAbsC[1][2]+afEA[2]*aafAbsC[2][2]; fR01 = fR0 + afEB[2]; if ( fR > fR01 ) return false; // At least one pair of box axes was parallel, so the separation is // effectively in 2D where checking the "edge" normals is sufficient for // the separation of the boxes. if ( bExistsParallelPair ) return true; // axis C0+t*A0xB0 fR = Math<Real>::FAbs(afAD[2]*aafC[1][0]-afAD[1]*aafC[2][0]); fR0 = afEA[1]*aafAbsC[2][0] + afEA[2]*aafAbsC[1][0]; fR1 = afEB[1]*aafAbsC[0][2] + afEB[2]*aafAbsC[0][1]; fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0+t*A0xB1 fR = Math<Real>::FAbs(afAD[2]*aafC[1][1]-afAD[1]*aafC[2][1]); fR0 = afEA[1]*aafAbsC[2][1] + afEA[2]*aafAbsC[1][1]; fR1 = afEB[0]*aafAbsC[0][2] + afEB[2]*aafAbsC[0][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0+t*A0xB2 fR = Math<Real>::FAbs(afAD[2]*aafC[1][2]-afAD[1]*aafC[2][2]); fR0 = afEA[1]*aafAbsC[2][2] + afEA[2]*aafAbsC[1][2]; fR1 = afEB[0]*aafAbsC[0][1] + afEB[1]*aafAbsC[0][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0+t*A1xB0 fR = Math<Real>::FAbs(afAD[0]*aafC[2][0]-afAD[2]*aafC[0][0]); fR0 = afEA[0]*aafAbsC[2][0] + afEA[2]*aafAbsC[0][0]; fR1 = afEB[1]*aafAbsC[1][2] + afEB[2]*aafAbsC[1][1]; fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0+t*A1xB1 fR = Math<Real>::FAbs(afAD[0]*aafC[2][1]-afAD[2]*aafC[0][1]); fR0 = afEA[0]*aafAbsC[2][1] + afEA[2]*aafAbsC[0][1]; fR1 = afEB[0]*aafAbsC[1][2] + afEB[2]*aafAbsC[1][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0+t*A1xB2 fR = Math<Real>::FAbs(afAD[0]*aafC[2][2]-afAD[2]*aafC[0][2]); fR0 = afEA[0]*aafAbsC[2][2] + afEA[2]*aafAbsC[0][2]; fR1 = afEB[0]*aafAbsC[1][1] + afEB[1]*aafAbsC[1][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0+t*A2xB0 fR = Math<Real>::FAbs(afAD[1]*aafC[0][0]-afAD[0]*aafC[1][0]); fR0 = afEA[0]*aafAbsC[1][0] + afEA[1]*aafAbsC[0][0]; fR1 = afEB[1]*aafAbsC[2][2] + afEB[2]*aafAbsC[2][1]; fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0+t*A2xB1 fR = Math<Real>::FAbs(afAD[1]*aafC[0][1]-afAD[0]*aafC[1][1]); fR0 = afEA[0]*aafAbsC[1][1] + afEA[1]*aafAbsC[0][1]; fR1 = afEB[0]*aafAbsC[2][2] + afEB[2]*aafAbsC[2][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0+t*A2xB2 fR = Math<Real>::FAbs(afAD[1]*aafC[0][2]-afAD[0]*aafC[1][2]); fR0 = afEA[0]*aafAbsC[1][2] + afEA[1]*aafAbsC[0][2]; fR1 = afEB[0]*aafAbsC[2][1] + afEB[1]*aafAbsC[2][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) return false; return true; } //---------------------------------------------------------------------------- // moving objects //---------------------------------------------------------------------------- template <class Real> static bool BoxAxisFind (const Vector3<Real>& rkVelocity, const Vector3<Real>& rkAxis, const Box3<Real>& rkBoxU, const Box3<Real>& rkBoxV, Real& rfTFirst, Real& rfTLast, Real fTMax, ContactSide& reSide, ContactConfig<Real>& rkTUC, ContactConfig<Real>& rkTVC) { ContactConfig<Real> kUC; GetBoxConfiguration(rkAxis,rkBoxU,kUC); ContactConfig<Real> kVC; GetBoxConfiguration(rkAxis,rkBoxV,kVC); return AxisFind(rkVelocity,rkAxis,kUC,kVC,reSide,rkTUC,rkTVC,rfTFirst, rfTLast,fTMax); } //---------------------------------------------------------------------------- template <class Real> static void FindContactSetCoplanarRectRect (const Vector3<Real> akFace0[4], const Vector3<Real> akFace1[4], int& riQuantity, Vector3<Real>* akP) { // The potential intersection is initialized to face 0, and then clipped // against the four sides of face 1. riQuantity = 4; memcpy(akP,akFace0,4*sizeof(Vector3<Real>)); for (int i0 = 3, i1 = 0; i1 < 4; i0 = i1++) { Vector3<Real> kNormal = akFace1[i1] - akFace1[i0]; Real fConstant = kNormal.Dot(akFace1[i0]); ClipConvexPolygonAgainstPlane(kNormal,fConstant,riQuantity,akP); } } //---------------------------------------------------------------------------- template <class Real> static void FindContactSet (const Box3<Real>& rkBox0, const Box3<Real>& rkBox1, ContactSide eSide, const ContactConfig<Real>& rkUC, const ContactConfig<Real>& rkVC, const Vector3<Real>& rkVel0, const Vector3<Real>& rkVel1, Real fTFirst, int& riQuantity, Vector3<Real>* akP) { // move boxes to new position Box3<Real> kNewBox0, kNewBox1; kNewBox0.Center() = rkBox0.Center() + fTFirst*rkVel0; kNewBox1.Center() = rkBox1.Center() + fTFirst*rkVel1; for (int i = 0; i < 3; i++) { kNewBox0.Axis(i) = rkBox0.Axis(i); kNewBox0.Extent(i) = rkBox0.Extent(i); kNewBox1.Axis(i) = rkBox1.Axis(i); kNewBox1.Extent(i) = rkBox1.Extent(i); } if ( eSide == LEFT ) { // box1 on left of box0 if ( rkUC.m_kMap == m1_1 ) { riQuantity = 1; akP[0] = GetPoint(rkUC.m_aiIndex[0],kNewBox0); } else if ( rkVC.m_kMap == m1_1 ) { riQuantity = 1; akP[0] = GetPoint(rkVC.m_aiIndex[7],kNewBox1); } else if ( rkUC.m_kMap == m2_2 ) { if ( rkVC.m_kMap == m2_2 ) { // box0edge-box1edge intersection Vector3<Real> akEdge0[2], akEdge1[2]; akEdge0[0] = GetPoint(rkUC.m_aiIndex[0],kNewBox0); akEdge0[1] = GetPoint(rkUC.m_aiIndex[1],kNewBox0); akEdge1[0] = GetPoint(rkVC.m_aiIndex[6],kNewBox1); akEdge1[1] = GetPoint(rkVC.m_aiIndex[7],kNewBox1); FindContactSetLinLin(akEdge0,akEdge1,riQuantity,akP); } else // rkVC.m_kMap == m44 { // box0edge-box1face intersection Vector3<Real> akEdge0[2], akFace1[4]; akEdge0[0] = GetPoint(rkUC.m_aiIndex[0],kNewBox0); akEdge0[1] = GetPoint(rkUC.m_aiIndex[1],kNewBox0); akFace1[0] = GetPoint(rkVC.m_aiIndex[4],kNewBox1); akFace1[1] = GetPoint(rkVC.m_aiIndex[5],kNewBox1); akFace1[2] = GetPoint(rkVC.m_aiIndex[6],kNewBox1); akFace1[3] = GetPoint(rkVC.m_aiIndex[7],kNewBox1); FindContactSetCoplanarLineRect(akEdge0,akFace1,riQuantity, akP); } } else // rkUC.m_kMap == m44 { if ( rkVC.m_kMap == m2_2 ) { // box0face-box1edge intersection Vector3<Real> akFace0[4], akEdge1[2]; akFace0[0] = GetPoint(rkUC.m_aiIndex[0],kNewBox0); akFace0[1] = GetPoint(rkUC.m_aiIndex[1],kNewBox0); akFace0[2] = GetPoint(rkUC.m_aiIndex[2],kNewBox0); akFace0[3] = GetPoint(rkUC.m_aiIndex[3],kNewBox0); akEdge1[0] = GetPoint(rkVC.m_aiIndex[6],kNewBox1); akEdge1[1] = GetPoint(rkVC.m_aiIndex[7],kNewBox1); FindContactSetCoplanarLineRect(akEdge1,akFace0,riQuantity, akP); } else { // box0face-box1face intersection Vector3<Real> akFace0[4], akFace1[4]; akFace0[0] = GetPoint(rkUC.m_aiIndex[0],kNewBox0); akFace0[1] = GetPoint(rkUC.m_aiIndex[1],kNewBox0); akFace0[2] = GetPoint(rkUC.m_aiIndex[2],kNewBox0); akFace0[3] = GetPoint(rkUC.m_aiIndex[3],kNewBox0); akFace1[0] = GetPoint(rkVC.m_aiIndex[4],kNewBox1); akFace1[1] = GetPoint(rkVC.m_aiIndex[5],kNewBox1); akFace1[2] = GetPoint(rkVC.m_aiIndex[6],kNewBox1); akFace1[3] = GetPoint(rkVC.m_aiIndex[7],kNewBox1); FindContactSetCoplanarRectRect(akFace0,akFace1,riQuantity, akP); } } } else // rkSide == RIGHT { // box1 on right of box0 if ( rkUC.m_kMap == m1_1 ) { riQuantity = 1; akP[0] = GetPoint(rkUC.m_aiIndex[7],kNewBox0); } else if ( rkVC.m_kMap == m1_1 ) { riQuantity = 1; akP[0] = GetPoint(rkUC.m_aiIndex[0],kNewBox1); } else if ( rkUC.m_kMap == m2_2 ) { if ( rkVC.m_kMap == m2_2 ) { // box0edge-box1edge intersection Vector3<Real> akEdge0[2], akEdge1[2]; akEdge0[0] = GetPoint(rkUC.m_aiIndex[6],kNewBox0); akEdge0[1] = GetPoint(rkUC.m_aiIndex[7],kNewBox0); akEdge1[0] = GetPoint(rkVC.m_aiIndex[0],kNewBox1); akEdge1[1] = GetPoint(rkVC.m_aiIndex[1],kNewBox1); FindContactSetLinLin(akEdge0,akEdge1,riQuantity,akP); } else // rkVC.m_kMap == m44 { // box0edge-box1face intersection Vector3<Real> akEdge0[2], akFace1[4]; akEdge0[0] = GetPoint(rkUC.m_aiIndex[6],kNewBox0); akEdge0[1] = GetPoint(rkUC.m_aiIndex[7],kNewBox0); akFace1[0] = GetPoint(rkVC.m_aiIndex[0],kNewBox1); akFace1[1] = GetPoint(rkVC.m_aiIndex[1],kNewBox1); akFace1[2] = GetPoint(rkVC.m_aiIndex[2],kNewBox1); akFace1[3] = GetPoint(rkVC.m_aiIndex[3],kNewBox1); FindContactSetCoplanarLineRect(akEdge0,akFace1,riQuantity, akP); } } else // rkUC.m_kMap == m44 { if ( rkVC.m_kMap == m2_2 ) { // box0face-box1edge intersection Vector3<Real> akFace0[4], akEdge1[2]; akFace0[0] = GetPoint(rkUC.m_aiIndex[4],kNewBox0); akFace0[1] = GetPoint(rkUC.m_aiIndex[5],kNewBox0); akFace0[2] = GetPoint(rkUC.m_aiIndex[6],kNewBox0); akFace0[3] = GetPoint(rkUC.m_aiIndex[7],kNewBox0); akEdge1[0] = GetPoint(rkVC.m_aiIndex[0],kNewBox1); akEdge1[1] = GetPoint(rkVC.m_aiIndex[1],kNewBox1); FindContactSetCoplanarLineRect(akEdge1,akFace0,riQuantity, akP); } else // rkVC.m_kMap == m44 { // box0face-box1face intersection Vector3<Real> akFace0[4], akFace1[4]; akFace0[0] = GetPoint(rkUC.m_aiIndex[4],kNewBox0); akFace0[1] = GetPoint(rkUC.m_aiIndex[5],kNewBox0); akFace0[2] = GetPoint(rkUC.m_aiIndex[6],kNewBox0); akFace0[3] = GetPoint(rkUC.m_aiIndex[7],kNewBox0); akFace1[0] = GetPoint(rkVC.m_aiIndex[0],kNewBox1); akFace1[1] = GetPoint(rkVC.m_aiIndex[1],kNewBox1); akFace1[2] = GetPoint(rkVC.m_aiIndex[2],kNewBox1); akFace1[3] = GetPoint(rkVC.m_aiIndex[3],kNewBox1); FindContactSetCoplanarRectRect(akFace0,akFace1,riQuantity, akP); } } } } //---------------------------------------------------------------------------- template <class Real> bool Wml::TestIntersection (Real fTime, const Box3<Real>& rkBox0, const Vector3<Real>& rkVel0, const Box3<Real>& rkBox1, const Vector3<Real>& rkVel1) { // convenience variables const Vector3<Real>* akA = rkBox0.Axes(); const Vector3<Real>* akB = rkBox1.Axes(); const Real* afEA = rkBox0.Extents(); const Real* afEB = rkBox1.Extents(); // Compute relative velocity of box1 with respect to box0 so that box0 // may as well be stationary. Vector3<Real> kW = rkVel1 - rkVel0; // Compute difference of box centers at time 0 and time 'fTime'. Vector3<Real> kD0 = rkBox1.Center() - rkBox0.Center(); Vector3<Real> kD1 = kD0 + fTime*kW; Real aafC[3][3]; // matrix C = A^T B, c_{ij} = Dot(A_i,B_j) Real aafAbsC[3][3]; // |c_{ij}| Real afAD0[3]; // Dot(A_i,D0) Real afAD1[3]; // Dot(A_i,D1) Real fR0, fR1, fR; // interval radii and distance between centers Real fR01; // = R0 + R1 // axis C0+t*A0 aafC[0][0] = akA[0].Dot(akB[0]); aafC[0][1] = akA[0].Dot(akB[1]); aafC[0][2] = akA[0].Dot(akB[2]); afAD0[0] = akA[0].Dot(kD0); afAD1[0] = akA[0].Dot(kD1); aafAbsC[0][0] = Math<Real>::FAbs(aafC[0][0]); aafAbsC[0][1] = Math<Real>::FAbs(aafC[0][1]); aafAbsC[0][2] = Math<Real>::FAbs(aafC[0][2]); fR1 = afEB[0]*aafAbsC[0][0]+afEB[1]*aafAbsC[0][1]+afEB[2]*aafAbsC[0][2]; fR01 = afEA[0] + fR1; if ( afAD0[0] > fR01 ) { if ( afAD1[0] > fR01 ) return false; } else if ( afAD0[0] < -fR01 ) { if ( afAD1[0] < -fR01 ) return false; } // axis C0+t*A1 aafC[1][0] = akA[1].Dot(akB[0]); aafC[1][1] = akA[1].Dot(akB[1]); aafC[1][2] = akA[1].Dot(akB[2]); afAD0[1] = akA[1].Dot(kD0); afAD1[1] = akA[1].Dot(kD1); aafAbsC[1][0] = Math<Real>::FAbs(aafC[1][0]); aafAbsC[1][1] = Math<Real>::FAbs(aafC[1][1]); aafAbsC[1][2] = Math<Real>::FAbs(aafC[1][2]); fR1 = afEB[0]*aafAbsC[1][0]+afEB[1]*aafAbsC[1][1]+afEB[2]*aafAbsC[1][2]; fR01 = afEA[1] + fR1; if ( afAD0[1] > fR01 ) { if ( afAD1[1] > fR01 ) return false; } else if ( afAD0[1] < -fR01 ) { if ( afAD1[1] < -fR01 ) return false; } // axis C0+t*A2 aafC[2][0] = akA[2].Dot(akB[0]); aafC[2][1] = akA[2].Dot(akB[1]); aafC[2][2] = akA[2].Dot(akB[2]); afAD0[2] = akA[2].Dot(kD0); afAD1[2] = akA[2].Dot(kD1); aafAbsC[2][0] = Math<Real>::FAbs(aafC[2][0]); aafAbsC[2][1] = Math<Real>::FAbs(aafC[2][1]); aafAbsC[2][2] = Math<Real>::FAbs(aafC[2][2]); fR1 = afEB[0]*aafAbsC[2][0]+afEB[1]*aafAbsC[2][1]+afEB[2]*aafAbsC[2][2]; fR01 = afEA[2] + fR1; if ( afAD0[2] > fR01 ) { if ( afAD1[2] > fR01 ) return false; } else if ( afAD0[2] < -fR01 ) { if ( afAD1[2] < -fR01 ) return false; } // axis C0+t*B0 fR = akB[0].Dot(kD0); fR0 = afEA[0]*aafAbsC[0][0]+afEA[1]*aafAbsC[1][0]+afEA[2]*aafAbsC[2][0]; fR01 = fR0 + afEB[0]; if ( fR > fR01 ) { fR = akB[0].Dot(kD1); if ( fR > fR01) return false; } else if ( fR < -fR01 ) { fR = akB[0].Dot(kD1); if ( fR < -fR01 ) return false; } // axis C0+t*B1 fR = akB[1].Dot(kD0); fR0 = afEA[0]*aafAbsC[0][1]+afEA[1]*aafAbsC[1][1]+afEA[2]*aafAbsC[2][1]; fR01 = fR0 + afEB[1]; if ( fR > fR01 ) { fR = akB[1].Dot(kD1); if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = akB[1].Dot(kD1); if ( fR < -fR01 ) return false; } // axis C0+t*B2 fR = akB[2].Dot(kD0); fR0 = afEA[0]*aafAbsC[0][2]+afEA[1]*aafAbsC[1][2]+afEA[2]*aafAbsC[2][2]; fR01 = fR0 + afEB[2]; if ( fR > fR01 ) { fR = akB[2].Dot(kD1); if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = akB[2].Dot(kD1); if ( fR < -fR01 ) return false; } // axis C0+t*A0xB0 fR = afAD0[2]*aafC[1][0]-afAD0[1]*aafC[2][0]; fR0 = afEA[1]*aafAbsC[2][0] + afEA[2]*aafAbsC[1][0]; fR1 = afEB[1]*aafAbsC[0][2] + afEB[2]*aafAbsC[0][1]; fR01 = fR0 + fR1; if ( fR > fR01 ) { fR = afAD1[2]*aafC[1][0]-afAD1[1]*aafC[2][0]; if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = afAD1[2]*aafC[1][0]-afAD1[1]*aafC[2][0]; if ( fR < -fR01 ) return false; } // axis C0+t*A0xB1 fR = afAD0[2]*aafC[1][1]-afAD0[1]*aafC[2][1]; fR0 = afEA[1]*aafAbsC[2][1] + afEA[2]*aafAbsC[1][1]; fR1 = afEB[0]*aafAbsC[0][2] + afEB[2]*aafAbsC[0][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) { fR = afAD1[2]*aafC[1][1]-afAD1[1]*aafC[2][1]; if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = afAD1[2]*aafC[1][1]-afAD1[1]*aafC[2][1]; if ( fR < -fR01 ) return false; } // axis C0+t*A0xB2 fR = afAD0[2]*aafC[1][2]-afAD0[1]*aafC[2][2]; fR0 = afEA[1]*aafAbsC[2][2] + afEA[2]*aafAbsC[1][2]; fR1 = afEB[0]*aafAbsC[0][1] + afEB[1]*aafAbsC[0][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) { fR = afAD1[2]*aafC[1][2]-afAD1[1]*aafC[2][2]; if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = afAD1[2]*aafC[1][2]-afAD1[1]*aafC[2][2]; if ( fR < -fR01 ) return false; } // axis C0+t*A1xB0 fR = afAD0[0]*aafC[2][0]-afAD0[2]*aafC[0][0]; fR0 = afEA[0]*aafAbsC[2][0] + afEA[2]*aafAbsC[0][0]; fR1 = afEB[1]*aafAbsC[1][2] + afEB[2]*aafAbsC[1][1]; fR01 = fR0 + fR1; if ( fR > fR01 ) { fR = afAD1[0]*aafC[2][0]-afAD1[2]*aafC[0][0]; if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = afAD1[0]*aafC[2][0]-afAD1[2]*aafC[0][0]; if ( fR < -fR01 ) return false; } // axis C0+t*A1xB1 fR = afAD0[0]*aafC[2][1]-afAD0[2]*aafC[0][1]; fR0 = afEA[0]*aafAbsC[2][1] + afEA[2]*aafAbsC[0][1]; fR1 = afEB[0]*aafAbsC[1][2] + afEB[2]*aafAbsC[1][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) { fR = afAD1[0]*aafC[2][1]-afAD1[2]*aafC[0][1]; if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = afAD1[0]*aafC[2][1]-afAD1[2]*aafC[0][1]; if ( fR < -fR01 ) return false; } // axis C0+t*A1xB2 fR = afAD0[0]*aafC[2][2]-afAD0[2]*aafC[0][2]; fR0 = afEA[0]*aafAbsC[2][2] + afEA[2]*aafAbsC[0][2]; fR1 = afEB[0]*aafAbsC[1][1] + afEB[1]*aafAbsC[1][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) { fR = afAD1[0]*aafC[2][2]-afAD1[2]*aafC[0][2]; if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = afAD1[0]*aafC[2][2]-afAD1[2]*aafC[0][2]; if ( fR < -fR01 ) return false; } // axis C0+t*A2xB0 fR = afAD0[1]*aafC[0][0]-afAD0[0]*aafC[1][0]; fR0 = afEA[0]*aafAbsC[1][0] + afEA[1]*aafAbsC[0][0]; fR1 = afEB[1]*aafAbsC[2][2] + afEB[2]*aafAbsC[2][1]; fR01 = fR0 + fR1; if ( fR > fR01 ) { fR = afAD1[1]*aafC[0][0]-afAD1[0]*aafC[1][0]; if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = afAD1[1]*aafC[0][0]-afAD1[0]*aafC[1][0]; if ( fR < -fR01 ) return false; } // axis C0+t*A2xB1 fR = afAD0[1]*aafC[0][1]-afAD0[0]*aafC[1][1]; fR0 = afEA[0]*aafAbsC[1][1] + afEA[1]*aafAbsC[0][1]; fR1 = afEB[0]*aafAbsC[2][2] + afEB[2]*aafAbsC[2][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) { fR = afAD1[1]*aafC[0][1]-afAD1[0]*aafC[1][1]; if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = afAD1[1]*aafC[0][1]-afAD1[0]*aafC[1][1]; if ( fR < -fR01 ) return false; } // axis C0+t*A2xB2 fR = afAD0[1]*aafC[0][2]-afAD0[0]*aafC[1][2]; fR0 = afEA[0]*aafAbsC[1][2] + afEA[1]*aafAbsC[0][2]; fR1 = afEB[0]*aafAbsC[2][1] + afEB[1]*aafAbsC[2][0]; fR01 = fR0 + fR1; if ( fR > fR01 ) { fR = afAD1[1]*aafC[0][2]-afAD1[0]*aafC[1][2]; if ( fR > fR01 ) return false; } else if ( fR < -fR01 ) { fR = afAD1[1]*aafC[0][2]-afAD1[0]*aafC[1][2]; if ( fR < -fR01 ) return false; } // At this point none of the 15 axes separate the boxes. It is still // possible that they are separated as viewed in any plane orthogonal // to the relative direction of motion W. In the worst case, the two // projected boxes are hexagons. This requires three separating axis // tests per box. Vector3<Real> kWxD0 = kW.Cross(kD0); Real afWA[3], afWB[3]; // axis C0 + t*WxA0 afWA[1] = kW.Dot(akA[1]); afWA[2] = kW.Dot(akA[2]); fR = Math<Real>::FAbs(akA[0].Dot(kWxD0)); fR0 = afEA[1]*Math<Real>::FAbs(afWA[2]) + afEA[2]*Math<Real>::FAbs(afWA[1]); fR1 = afEB[0]*Math<Real>::FAbs(aafC[1][0]*afWA[2] - aafC[2][0]*afWA[1]) + afEB[1]*Math<Real>::FAbs(aafC[1][1]*afWA[2] - aafC[2][1]*afWA[1]) + afEB[2]*Math<Real>::FAbs(aafC[1][2]*afWA[2] - aafC[2][2]*afWA[1]); fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0 + t*WxA1 afWA[0] = kW.Dot(akA[0]); fR = Math<Real>::FAbs(akA[1].Dot(kWxD0)); fR0 = afEA[2]*Math<Real>::FAbs(afWA[0]) + afEA[0]*Math<Real>::FAbs(afWA[2]); fR1 = afEB[0]*Math<Real>::FAbs(aafC[2][0]*afWA[0] - aafC[0][0]*afWA[2]) + afEB[1]*Math<Real>::FAbs(aafC[2][1]*afWA[0] - aafC[0][1]*afWA[2]) + afEB[2]*Math<Real>::FAbs(aafC[2][2]*afWA[0] - aafC[0][2]*afWA[2]); fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0 + t*WxA2 fR = Math<Real>::FAbs(akA[2].Dot(kWxD0)); fR0 = afEA[0]*Math<Real>::FAbs(afWA[1]) + afEA[1]*Math<Real>::FAbs(afWA[0]); fR1 = afEB[0]*Math<Real>::FAbs(aafC[0][0]*afWA[1] - aafC[1][0]*afWA[0]) + afEB[1]*Math<Real>::FAbs(aafC[0][1]*afWA[1] - aafC[1][1]*afWA[0]) + afEB[2]*Math<Real>::FAbs(aafC[0][2]*afWA[1] - aafC[1][2]*afWA[0]); fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0 + t*WxB0 afWB[1] = kW.Dot(akB[1]); afWB[2] = kW.Dot(akB[2]); fR = Math<Real>::FAbs(akB[0].Dot(kWxD0)); fR0 = afEA[0]*Math<Real>::FAbs(aafC[0][1]*afWB[2] - aafC[0][2]*afWB[1]) + afEA[1]*Math<Real>::FAbs(aafC[1][1]*afWB[2] - aafC[1][2]*afWB[1]) + afEA[2]*Math<Real>::FAbs(aafC[2][1]*afWB[2] - aafC[2][2]*afWB[1]); fR1 = afEB[1]*Math<Real>::FAbs(afWB[2]) + afEB[2]*Math<Real>::FAbs(afWB[1]); fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0 + t*WxB1 afWB[0] = kW.Dot(akB[0]); fR = Math<Real>::FAbs(akB[1].Dot(kWxD0)); fR0 = afEA[0]*Math<Real>::FAbs(aafC[0][2]*afWB[0] - aafC[0][0]*afWB[2]) + afEA[1]*Math<Real>::FAbs(aafC[1][2]*afWB[0] - aafC[1][0]*afWB[2]) + afEA[2]*Math<Real>::FAbs(aafC[2][2]*afWB[0] - aafC[2][0]*afWB[2]); fR1 = afEB[2]*Math<Real>::FAbs(afWB[0]) + afEB[0]*Math<Real>::FAbs(afWB[2]); fR01 = fR0 + fR1; if ( fR > fR01 ) return false; // axis C0 + t*WxB2 fR = Math<Real>::FAbs(akB[2].Dot(kWxD0)); fR0 = afEA[0]*Math<Real>::FAbs(aafC[0][0]*afWB[1] - aafC[0][1]*afWB[0]) + afEA[1]*Math<Real>::FAbs(aafC[1][0]*afWB[1] - aafC[1][1]*afWB[0]) + afEA[2]*Math<Real>::FAbs(aafC[2][0]*afWB[1] - aafC[2][1]*afWB[0]); fR1 = afEB[0]*Math<Real>::FAbs(afWB[1]) + afEB[1]*Math<Real>::FAbs(afWB[0]); fR01 = fR0 + fR1; if ( fR > fR01 ) return false; return true; } //---------------------------------------------------------------------------- template <class Real> bool Wml::TestIntersection (Real fTime, int iNumSteps, const Box3<Real>& rkBox0, const Vector3<Real>& rkVel0, const Vector3<Real>& rkRotCen0, const Vector3<Real>& rkRotAxis0, const Box3<Real>& rkBox1, const Vector3<Real>& rkVel1, const Vector3<Real>& rkRotCen1, const Vector3<Real>& rkRotAxis1) { // time step for the integration Real fStep = fTime/Real(iNumSteps); // initialize subinterval boxes Box3<Real> kSubBox0, kSubBox1; kSubBox0.Center() = rkBox0.Center(); kSubBox1.Center() = rkBox1.Center(); int i; for (i = 0; i < 3; i++) { kSubBox0.Axis(i) = rkBox0.Axis(i); kSubBox1.Axis(i) = rkBox1.Axis(i); } // integrate the differential equations using Euler's method for (int iStep = 1; iStep <= iNumSteps; iStep++) { // compute box velocities and test boxes for intersection Real fSubTime = fStep*Real(iStep); Vector3<Real> kNewRotCen0 = rkRotCen0 + fSubTime*rkVel0; Vector3<Real> kNewRotCen1 = rkRotCen1 + fSubTime*rkVel1; Vector3<Real> kDiff0 = kSubBox0.Center() - kNewRotCen0; Vector3<Real> kDiff1 = kSubBox1.Center() - kNewRotCen1; Vector3<Real> kSubVel0 = fStep*(rkVel0 + rkRotAxis0.Cross(kDiff0)); Vector3<Real> kSubVel1 = fStep*(rkVel1 + rkRotAxis1.Cross(kDiff1)); if ( TestIntersection(fStep,kSubBox0,kSubVel0,kSubBox1,kSubVel1) ) return true; // update the box centers kSubBox0.Center() = kSubBox0.Center() + kSubVel0; kSubBox1.Center() = kSubBox1.Center() + kSubVel1; // update the box axes for (i = 0; i < 3; i++) { kSubBox0.Axis(i) = kSubBox0.Axis(i) + fStep*rkRotAxis0.Cross(kSubBox0.Axis(i)); kSubBox1.Axis(i) = kSubBox1.Axis(i) + fStep*rkRotAxis1.Cross(kSubBox1.Axis(i)); } // Use Gram-Schmidt to orthonormalize the updated axes. NOTE: If // T/N is small and N is small, you can remove this expensive step // with the assumption that the updated axes are nearly orthonormal. Vector3<Real>::Orthonormalize(kSubBox0.Axes()); Vector3<Real>::Orthonormalize(kSubBox1.Axes()); } // NOTE: If the boxes do not intersect, then the application might // want to move/rotate the boxes to their new locations. In this case // you want to return the final values of kSubBox0 and kSubBox1 so that // the application can set rkBox0 <- kSubBox0 and rkBox1 <- kSubBox1. // Otherwise, the application would have to solve the differential // equation again or compute the new box locations using the closed form // solution for the rigid motion. return false; } //---------------------------------------------------------------------------- template <class Real> bool Wml::FindIntersection (const Box3<Real>& rkBox0, const Vector3<Real>& rkVel0, const Box3<Real>& rkBox1, const Vector3<Real>& rkVel1, Real& rfTFirst, Real fTMax, int& riQuantity, Vector3<Real>* akP) { rfTFirst = (Real)0.0; Real fTLast = Math<Real>::MAX_REAL; // relative velocity of box1 relative to box0 Vector3<Real> kVel = rkVel1 - rkVel0; int i0, i1; ContactSide eSide = NONE; ContactConfig<Real> kUC, kVC; Vector3<Real> kAxis; // box 0 normals for (i0 = 0; i0 < 3; i0++) { kAxis = rkBox0.Axis(i0); if ( !BoxAxisFind(kVel,kAxis,rkBox0,rkBox1,rfTFirst,fTLast,fTMax, eSide,kUC,kVC) ) { return false; } } // box 1 normals for (i1 = 0; i1 < 3; i1++) { kAxis = rkBox1.Axis(i1); if ( !BoxAxisFind(kVel,kAxis,rkBox0,rkBox1,rfTFirst,fTLast,fTMax, eSide,kUC,kVC) ) { return false; } } // box 0 edges cross box 1 edges for (i0 = 0; i0 < 3; i0++) { for (i1 = 0; i1 < 3; i1++) { kAxis = rkBox0.Axis(i0).Cross(rkBox1.Axis(i1)); // Since all axes are unit length (assumed), then can // just compare against a constant (not relative) epsilon if ( kAxis.SquaredLength() <= Math<Real>::EPSILON ) { // Simple separation, axis i0 and i1 are parallel // If any two axes are parallel, then the only comparisons // that need to be done are between the faces themselves, // which have already been done. Therefore, if they haven't // been separated yet, nothing else will. Quick out. return true; } if ( !BoxAxisFind(kVel,kAxis,rkBox0,rkBox1,rfTFirst,fTLast, fTMax,eSide,kUC,kVC) ) { return false; } } } // velocity cross box 0 edges for (i0 = 0; i0 < 3; i0++) { kAxis = kVel.Cross(rkBox0.Axis(i0)); if ( !BoxAxisFind(kVel,kAxis,rkBox0,rkBox1,rfTFirst,fTLast,fTMax, eSide,kUC,kVC) ) { return false; } } // velocity cross box 1 edges for (i1 = 0; i1 < 3; i1++) { kAxis = kVel.Cross(rkBox1.Axis(i1)); if ( !BoxAxisFind(kVel,kAxis,rkBox0,rkBox1,rfTFirst,fTLast,fTMax, eSide,kUC,kVC) ) { return false; } } if ( rfTFirst <= (Real)0.0 || eSide == NONE ) return false; FindContactSet(rkBox0,rkBox1,eSide,kUC,kVC,rkVel0,rkVel1,rfTFirst, riQuantity,akP); return true; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- namespace Wml { template WML_ITEM bool TestIntersection<float> (const Box3<float>&, const Box3<float>&); template WML_ITEM bool TestIntersection<float> (float, const Box3<float>&, const Vector3<float>&, const Box3<float>&, const Vector3<float>&); template WML_ITEM bool TestIntersection<float> (float, int, const Box3<float>&, const Vector3<float>&, const Vector3<float>&, const Vector3<float>&, const Box3<float>&, const Vector3<float>&, const Vector3<float>&, const Vector3<float>&); template WML_ITEM bool FindIntersection<float> ( const Box3<float>&, const Vector3<float>&, const Box3<float>&, const Vector3<float>&, float&, float, int&, Vector3<float>*); template WML_ITEM bool TestIntersection<double> (const Box3<double>&, const Box3<double>&); template WML_ITEM bool TestIntersection<double> (double, const Box3<double>&, const Vector3<double>&, const Box3<double>&, const Vector3<double>&); template WML_ITEM bool TestIntersection<double> (double, int, const Box3<double>&, const Vector3<double>&, const Vector3<double>&, const Vector3<double>&, const Box3<double>&, const Vector3<double>&, const Vector3<double>&, const Vector3<double>&); template WML_ITEM bool FindIntersection<double> ( const Box3<double>&, const Vector3<double>&, const Box3<double>&, const Vector3<double>&, double&, double, int&, Vector3<double>*); } //----------------------------------------------------------------------------
[ [ [ 1, 982 ] ] ]
e552e2a560ad47fd7f6bebb26b30795c568cc9d0
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/Bowling/trunk/Source/LethalBowling/Quaternion.cpp
5073eaae3fd2f8939144943ad83cbeb90329f6ba
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
20,314
cpp
#include "Quaternion.h" #include "TMath.h" namespace Virgin { const Quaternion Quaternion::ZERO(0.0f, 0.0f, 0.0f, 0.0f); const Quaternion Quaternion::IDENTITY(1.0f, 0.0f, 0.0f, 0.0f); Quaternion::Quaternion () { // the object is uninitialized } //---------------------------------------------------------------------------- Quaternion::Quaternion (float fW, float fX, float fY, float fZ) { m_afTuple[0] = fW; m_afTuple[1] = fX; m_afTuple[2] = fY; m_afTuple[3] = fZ; } //---------------------------------------------------------------------------- Quaternion::Quaternion (const Quaternion& rkQ) { memcpy(m_afTuple,rkQ.m_afTuple,4*sizeof(float)); } //---------------------------------------------------------------------------- Quaternion::Quaternion (const Matrix3& rkRot) { FromRotationMatrix(rkRot); } //---------------------------------------------------------------------------- Quaternion::Quaternion (const Vector3& rkAxis, float fAngle) { FromAxisAngle(rkAxis,fAngle); } //---------------------------------------------------------------------------- Quaternion::Quaternion (const Vector3 akRotColumn[3]) { FromRotationMatrix(akRotColumn); } //---------------------------------------------------------------------------- Quaternion::operator const float* () const { return m_afTuple; } //---------------------------------------------------------------------------- Quaternion::operator float* () { return m_afTuple; } //---------------------------------------------------------------------------- float Quaternion::operator[] (int i) const { //assert( 0 <= i && i < 4 ); return m_afTuple[i]; } //---------------------------------------------------------------------------- float& Quaternion::operator[] (int i) { //assert( 0 <= i && i < 4 ); return m_afTuple[i]; } //---------------------------------------------------------------------------- float Quaternion::W () const { return m_afTuple[3]; } //---------------------------------------------------------------------------- float& Quaternion::W () { return m_afTuple[3]; } //---------------------------------------------------------------------------- float Quaternion::X () const { return m_afTuple[0]; } //---------------------------------------------------------------------------- float& Quaternion::X () { return m_afTuple[0]; } //---------------------------------------------------------------------------- float Quaternion::Y () const { return m_afTuple[1]; } //---------------------------------------------------------------------------- float& Quaternion::Y () { return m_afTuple[1]; } //---------------------------------------------------------------------------- float Quaternion::Z () const { return m_afTuple[2]; } //---------------------------------------------------------------------------- float& Quaternion::Z () { return m_afTuple[2]; } //---------------------------------------------------------------------------- Quaternion& Quaternion::operator= (const Quaternion& rkQ) { memcpy(m_afTuple,rkQ.m_afTuple,4*sizeof(float)); return *this; } //---------------------------------------------------------------------------- bool Quaternion::operator== (const Quaternion& rkQ) const { for (int i = 0; i < 4; i++) { if ( m_afTuple[i] != rkQ.m_afTuple[i] ) return false; } return true; } //---------------------------------------------------------------------------- bool Quaternion::operator!= (const Quaternion& rkQ) const { return !operator==(rkQ); } //---------------------------------------------------------------------------- int Quaternion::CompareArrays (const Quaternion& rkQ) const { for (int i = 0; i < 4; i++) { unsigned int uiTest0 = *(unsigned int*)&m_afTuple[i]; unsigned int uiTest1 = *(unsigned int*)&rkQ.m_afTuple[i]; if ( uiTest0 < uiTest1 ) return -1; if ( uiTest0 > uiTest1 ) return +1; } return 0; } //---------------------------------------------------------------------------- bool Quaternion::operator< (const Quaternion& rkQ) const { return CompareArrays(rkQ) < 0; } //---------------------------------------------------------------------------- bool Quaternion::operator<= (const Quaternion& rkQ) const { return CompareArrays(rkQ) <= 0; } //---------------------------------------------------------------------------- bool Quaternion::operator> (const Quaternion& rkQ) const { return CompareArrays(rkQ) > 0; } //---------------------------------------------------------------------------- bool Quaternion::operator>= (const Quaternion& rkQ) const { return CompareArrays(rkQ) >= 0; } //---------------------------------------------------------------------------- Quaternion Quaternion::operator+ (const Quaternion& rkQ) const { Quaternion kSum; for (int i = 0; i < 4; i++) kSum.m_afTuple[i] = m_afTuple[i] + rkQ.m_afTuple[i]; return kSum; } //---------------------------------------------------------------------------- Quaternion Quaternion::operator- (const Quaternion& rkQ) const { Quaternion kDiff; for (int i = 0; i < 4; i++) kDiff.m_afTuple[i] = m_afTuple[i] - rkQ.m_afTuple[i]; return kDiff; } //---------------------------------------------------------------------------- Quaternion Quaternion::operator* (const Quaternion& rkQ) const { // NOTE: Multiplication is not generally commutative, so in most // cases p*q != q*p. Quaternion kProd; kProd.m_afTuple[0] = m_afTuple[0]*rkQ.m_afTuple[0] - m_afTuple[1]*rkQ.m_afTuple[1] - m_afTuple[2]*rkQ.m_afTuple[2] - m_afTuple[3]*rkQ.m_afTuple[3]; kProd.m_afTuple[1] = m_afTuple[0]*rkQ.m_afTuple[1] + m_afTuple[1]*rkQ.m_afTuple[0] + m_afTuple[2]*rkQ.m_afTuple[3] - m_afTuple[3]*rkQ.m_afTuple[2]; kProd.m_afTuple[2] = m_afTuple[0]*rkQ.m_afTuple[2] + m_afTuple[2]*rkQ.m_afTuple[0] + m_afTuple[3]*rkQ.m_afTuple[1] - m_afTuple[1]*rkQ.m_afTuple[3]; kProd.m_afTuple[3] = m_afTuple[0]*rkQ.m_afTuple[3] + m_afTuple[3]*rkQ.m_afTuple[0] + m_afTuple[1]*rkQ.m_afTuple[2] - m_afTuple[2]*rkQ.m_afTuple[1]; return kProd; } //---------------------------------------------------------------------------- Quaternion Quaternion::operator* (float fScalar) const { Quaternion kProd; for (int i = 0; i < 4; i++) kProd.m_afTuple[i] = fScalar*m_afTuple[i]; return kProd; } //---------------------------------------------------------------------------- Quaternion Quaternion::operator/ (float fScalar) const { Quaternion kQuot; int i; if ( fScalar != (float)0.0 ) { float fInvScalar = ((float)1.0)/fScalar; for (i = 0; i < 4; i++) kQuot.m_afTuple[i] = fInvScalar*m_afTuple[i]; } else { for (i = 0; i < 4; i++) kQuot.m_afTuple[i] = Math::MAX_REAL; } return kQuot; } //---------------------------------------------------------------------------- Quaternion Quaternion::operator- () const { Quaternion kNeg; for (int i = 0; i < 4; i++) kNeg.m_afTuple[i] = -m_afTuple[i]; return kNeg; } //---------------------------------------------------------------------------- Quaternion operator* (float fScalar, const Quaternion& rkQ) { Quaternion kProd; for (int i = 0; i < 4; i++) kProd[i] = fScalar*rkQ[i]; return kProd; } //---------------------------------------------------------------------------- Quaternion& Quaternion::operator+= (const Quaternion& rkQ) { for (int i = 0; i < 4; i++) m_afTuple[i] += rkQ.m_afTuple[i]; return *this; } //---------------------------------------------------------------------------- Quaternion& Quaternion::operator-= (const Quaternion& rkQ) { for (int i = 0; i < 4; i++) m_afTuple[i] -= rkQ.m_afTuple[i]; return *this; } //---------------------------------------------------------------------------- Quaternion& Quaternion::operator*= (float fScalar) { for (int i = 0; i < 4; i++) m_afTuple[i] *= fScalar; return *this; } //---------------------------------------------------------------------------- Quaternion& Quaternion::operator/= (float fScalar) { int i; if ( fScalar != (float)0.0 ) { float fInvScalar = ((float)1.0)/fScalar; for (i = 0; i < 4; i++) m_afTuple[i] *= fInvScalar; } else { for (i = 0; i < 4; i++) m_afTuple[i] = Math::MAX_REAL; } return *this; } //---------------------------------------------------------------------------- void Quaternion::FromRotationMatrix (const Matrix3& rkRot) { // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes // article "Quaternion Calculus and Fast Animation". float fTrace = rkRot(0,0) + rkRot(1,1) + rkRot(2,2); float fRoot; if ( fTrace > (float)0.0 ) { // |w| > 1/2, may as well choose w > 1/2 fRoot = Math::Sqrt(fTrace + (float)1.0); // 2w m_afTuple[0] = ((float)0.5)*fRoot; fRoot = ((float)0.5)/fRoot; // 1/(4w) m_afTuple[1] = (rkRot(2,1)-rkRot(1,2))*fRoot; m_afTuple[2] = (rkRot(0,2)-rkRot(2,0))*fRoot; m_afTuple[3] = (rkRot(1,0)-rkRot(0,1))*fRoot; } else { // |w| <= 1/2 int i = 0; if ( rkRot(1,1) > rkRot(0,0) ) i = 1; if ( rkRot(2,2) > rkRot(i,i) ) i = 2; int j = ms_iNext[i]; int k = ms_iNext[j]; fRoot = Math::Sqrt(rkRot(i,i)-rkRot(j,j)-rkRot(k,k)+(float)1.0); float* apfQuat[3] = { &m_afTuple[1], &m_afTuple[2], &m_afTuple[3] }; *apfQuat[i] = ((float)0.5)*fRoot; fRoot = ((float)0.5)/fRoot; m_afTuple[0] = (rkRot(k,j)-rkRot(j,k))*fRoot; *apfQuat[j] = (rkRot(j,i)+rkRot(i,j))*fRoot; *apfQuat[k] = (rkRot(k,i)+rkRot(i,k))*fRoot; } } //---------------------------------------------------------------------------- void Quaternion::ToRotationMatrix (Matrix3& rkRot) const { float fTx = ((float)2.0)*m_afTuple[1]; float fTy = ((float)2.0)*m_afTuple[2]; float fTz = ((float)2.0)*m_afTuple[3]; float fTwx = fTx*m_afTuple[0]; float fTwy = fTy*m_afTuple[0]; float fTwz = fTz*m_afTuple[0]; float fTxx = fTx*m_afTuple[1]; float fTxy = fTy*m_afTuple[1]; float fTxz = fTz*m_afTuple[1]; float fTyy = fTy*m_afTuple[2]; float fTyz = fTz*m_afTuple[2]; float fTzz = fTz*m_afTuple[3]; rkRot(0,0) = ((float)1.0)-(fTyy+fTzz); rkRot(0,1) = fTxy-fTwz; rkRot(0,2) = fTxz+fTwy; rkRot(1,0) = fTxy+fTwz; rkRot(1,1) = ((float)1.0)-(fTxx+fTzz); rkRot(1,2) = fTyz-fTwx; rkRot(2,0) = fTxz-fTwy; rkRot(2,1) = fTyz+fTwx; rkRot(2,2) = ((float)1.0)-(fTxx+fTyy); } //---------------------------------------------------------------------------- void Quaternion::FromRotationMatrix (const Vector3 akRotColumn[3]) { Matrix3 kRot; for (int iCol = 0; iCol < 3; iCol++) { kRot(0,iCol) = akRotColumn[iCol][0]; kRot(1,iCol) = akRotColumn[iCol][1]; kRot(2,iCol) = akRotColumn[iCol][2]; } FromRotationMatrix(kRot); } //---------------------------------------------------------------------------- void Quaternion::ToRotationMatrix (Vector3 akRotColumn[3]) const { Matrix3 kRot; ToRotationMatrix(kRot); for (int iCol = 0; iCol < 3; iCol++) { akRotColumn[iCol][0] = kRot(0,iCol); akRotColumn[iCol][1] = kRot(1,iCol); akRotColumn[iCol][2] = kRot(2,iCol); } } //---------------------------------------------------------------------------- void Quaternion::FromAxisAngle (const Vector3& rkAxis, float fAngle) { // //assert: axis[] is unit length // // The quaternion representing the rotation is // q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k) float fHalfAngle = ((float)0.5)*fAngle; float fSin = Math::Sin(fHalfAngle); m_afTuple[0] = Math::Cos(fHalfAngle); m_afTuple[1] = fSin*rkAxis[0]; m_afTuple[2] = fSin*rkAxis[1]; m_afTuple[3] = fSin*rkAxis[2]; } //---------------------------------------------------------------------------- void Quaternion::ToAxisAngle (Vector3& rkAxis, float& rfAngle) const { // The quaternion representing the rotation is // q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k) float fSqrLength = m_afTuple[1]*m_afTuple[1] + m_afTuple[2]*m_afTuple[2] + m_afTuple[3]*m_afTuple[3]; if ( fSqrLength > Math::EPSILON ) { rfAngle = ((float)2.0)*Math::ACos(m_afTuple[0]); float fInvLength = Math::InvSqrt(fSqrLength); rkAxis[0] = m_afTuple[1]*fInvLength; rkAxis[1] = m_afTuple[2]*fInvLength; rkAxis[2] = m_afTuple[3]*fInvLength; } else { // angle is 0 (mod 2*pi), so any axis will do rfAngle = (float)0.0; rkAxis[0] = (float)1.0; rkAxis[1] = (float)0.0; rkAxis[2] = (float)0.0; } } //---------------------------------------------------------------------------- float Quaternion::Dot (const Quaternion& rkQ) const { float fDot = (float)0.0; for (int i = 0; i < 4; i++) fDot += m_afTuple[i]*rkQ.m_afTuple[i]; return fDot; } //---------------------------------------------------------------------------- Quaternion Quaternion::Inverse () const { Quaternion kInverse; float fNorm = (float)0.0; int i; for (i = 0; i < 4; i++) fNorm += m_afTuple[i]*m_afTuple[i]; if ( fNorm > (float)0.0 ) { float fInvNorm = ((float)1.0)/fNorm; kInverse.m_afTuple[0] = m_afTuple[0]*fInvNorm; kInverse.m_afTuple[1] = -m_afTuple[1]*fInvNorm; kInverse.m_afTuple[2] = -m_afTuple[2]*fInvNorm; kInverse.m_afTuple[3] = -m_afTuple[3]*fInvNorm; } else { // return an invalid result to flag the error for (i = 0; i < 4; i++) kInverse.m_afTuple[i] = (float)0.0; } return kInverse; } //---------------------------------------------------------------------------- Quaternion Quaternion::Conjugate () const { // //assert: 'this' is unit length return Quaternion(m_afTuple[0],-m_afTuple[1],-m_afTuple[2],-m_afTuple[3]); } //---------------------------------------------------------------------------- Quaternion Quaternion::Exp () const { // If q = A*(x*i+y*j+z*k) where (x,y,z) is unit length, then // exp(q) = cos(A)+sin(A)*(x*i+y*j+z*k). If sin(A) is near zero, // use exp(q) = cos(A)+A*(x*i+y*j+z*k) since A/sin(A) has limit 1. Quaternion kResult; float fAngle = Math::Sqrt(m_afTuple[1]*m_afTuple[1] + m_afTuple[2]*m_afTuple[2] + m_afTuple[3]*m_afTuple[3]); float fSin = Math::Sin(fAngle); kResult.m_afTuple[0] = Math::Cos(fAngle); int i; if ( Math::FAbs(fSin) >= Math::EPSILON ) { float fCoeff = fSin/fAngle; for (i = 1; i <= 3; i++) kResult.m_afTuple[i] = fCoeff*m_afTuple[i]; } else { for (i = 1; i <= 3; i++) kResult.m_afTuple[i] = m_afTuple[i]; } return kResult; } //---------------------------------------------------------------------------- Quaternion Quaternion::Log () const { // If q = cos(A)+sin(A)*(x*i+y*j+z*k) where (x,y,z) is unit length, then // log(q) = A*(x*i+y*j+z*k). If sin(A) is near zero, use log(q) = // sin(A)*(x*i+y*j+z*k) since sin(A)/A has limit 1. Quaternion kResult; kResult.m_afTuple[0] = (float)0.0; int i; if ( Math::FAbs(m_afTuple[0]) < (float)1.0 ) { float fAngle = Math::ACos(m_afTuple[0]); float fSin = Math::Sin(fAngle); if ( Math::FAbs(fSin) >= Math::EPSILON ) { float fCoeff = fAngle/fSin; for (i = 1; i <= 3; i++) kResult.m_afTuple[i] = fCoeff*m_afTuple[i]; return kResult; } } for (i = 1; i <= 3; i++) kResult.m_afTuple[i] = m_afTuple[i]; return kResult; } //---------------------------------------------------------------------------- Vector3 Quaternion::operator* (const Vector3& rkVector) const { // Given a vector u = (x0,y0,z0) and a unit length quaternion // q = <w,x,y,z>, the vector v = (x1,y1,z1) which represents the // rotation of u by q is v = q*u*q^{-1} where * indicates quaternion // multiplication and where u is treated as the quaternion <0,x0,y0,z0>. // Note that q^{-1} = <w,-x,-y,-z>, so no real work is required to // invert q. Now // // q*u*q^{-1} = q*<0,x0,y0,z0>*q^{-1} // = q*(x0*i+y0*j+z0*k)*q^{-1} // = x0*(q*i*q^{-1})+y0*(q*j*q^{-1})+z0*(q*k*q^{-1}) // // As 3-vectors, q*i*q^{-1}, q*j*q^{-1}, and 2*k*q^{-1} are the columns // of the rotation matrix computed in Quaternion::ToRotationMatrix. // The vector v is obtained as the product of that rotation matrix with // vector u. As such, the quaternion representation of a rotation // matrix requires less space than the matrix and more time to compute // the rotated vector. Typical space-time tradeoff... Matrix3 kRot; ToRotationMatrix(kRot); return kRot*rkVector; } //---------------------------------------------------------------------------- Quaternion Quaternion::Slerp (float fT, const Quaternion& rkP, const Quaternion& rkQ) { float fCos = rkP.Dot(rkQ); float fAngle = Math::ACos(fCos); if ( Math::FAbs(fAngle) < Math::EPSILON ) return rkP; float fSin = Math::Sin(fAngle); float fInvSin = ((float)1.0)/fSin; float fCoeff0 = Math::Sin((((float)1.0)-fT)*fAngle)*fInvSin; float fCoeff1 = Math::Sin(fT*fAngle)*fInvSin; return fCoeff0*rkP + fCoeff1*rkQ; } //---------------------------------------------------------------------------- Quaternion Quaternion::SlerpExtraSpins (float fT, const Quaternion& rkP, const Quaternion& rkQ, int iExtraSpins) { float fCos = rkP.Dot(rkQ); float fAngle = Math::ACos(fCos); if ( Math::FAbs(fAngle) < Math::EPSILON ) return rkP; float fSin = Math::Sin(fAngle); float fPhase = Math::PI*iExtraSpins*fT; float fInvSin = ((float)1.0)/fSin; float fCoeff0 = Math::Sin((((float)1.0)-fT)*fAngle-fPhase)*fInvSin; float fCoeff1 = Math::Sin(fT*fAngle + fPhase)*fInvSin; return fCoeff0*rkP + fCoeff1*rkQ; } //---------------------------------------------------------------------------- Quaternion Quaternion::GetIntermediate (const Quaternion& rkQ0, const Quaternion& rkQ1, const Quaternion& rkQ2) { // //assert: Q0, Q1, Q2 all unit-length Quaternion kQ1Inv = rkQ1.Conjugate(); Quaternion kP0 = kQ1Inv*rkQ0; Quaternion kP2 = kQ1Inv*rkQ2; Quaternion kArg = -((float)0.25)*(kP0.Log()+kP2.Log()); Quaternion kA = rkQ1*kArg.Exp(); return kA; } //---------------------------------------------------------------------------- Quaternion Quaternion::Squad (float fT, const Quaternion& rkQ0, const Quaternion& rkA0, const Quaternion& rkA1, const Quaternion& rkQ1) { float fSlerpT = ((float)2.0)*fT*(((float)1.0)-fT); Quaternion kSlerpP = Slerp(fT,rkQ0,rkQ1); Quaternion kSlerpQ = Slerp(fT,rkA0,rkA1); return Slerp(fSlerpT,kSlerpP,kSlerpQ); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- int Quaternion::ms_iNext[3] = { 1, 2, 0 }; }
[ [ [ 1, 665 ] ] ]
3ac149d2d814622ef7600d638e493345f13b2b8a
1b3a26845c00ede008ea66d26f370c3542641f45
/pymfclib/pymwin32funcs.cpp
71954a8d492fad1a109ef7e95978cfdf6d0f53fc
[]
no_license
atsuoishimoto/pymfc
26617fac259ed0ffd685a038b47702db0bdccd5f
1341ef3be6ca85ea1fa284689edbba1ac29c72cb
refs/heads/master
2021-01-01T05:50:51.613190
2010-12-29T07:38:01
2010-12-29T07:38:01
33,760,622
0
0
null
null
null
null
UTF-8
C++
false
false
5,538
cpp
// Copyright (c) 2001- Atsuo Ishimoto // See LICENSE for details. #include "stdafx.h" #include "pymwndbase.h" #include "pymwin32funcs.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif void pymRaiseWin32Err() { PyMFC_PROLOGUE(pymRaiseWin32Err); throw PyMFC_WIN32ERR(); PyMFC_VOID_EPILOGUE(); } void pymRaiseWin32Errcode(HRESULT hr) { PyMFC_PROLOGUE(pymRaiseWin32Errcode); throw PyMFC_WIN32ERRCODE(hr); PyMFC_VOID_EPILOGUE(); } long pymGetLastError() { PyMFC_PROLOGUE(pymFormatMessage); return GetLastError(); PyMFC_EPILOGUE(IMM_ERROR_GENERAL); } PyObject *pymFormatMessage(long err) { PyMFC_PROLOGUE(pymFormatMessage); char *buf; DWORD ret = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, LANG_NEUTRAL, (LPTSTR)&buf, 0, NULL); if (ret) { PyObject *ret = PyString_FromString(buf); LocalFree(buf); return ret; } return NULL; PyMFC_EPILOGUE(0); } HIMC pymImmGetContext(HWND hWnd) { PyMFC_PROLOGUE(pymFormatMessage); { PyMFCLeavePython lp; return ImmGetContext(hWnd); } PyMFC_EPILOGUE(0); } BOOL pymImmReleaseContext(HWND hWnd, HIMC hIMC) { PyMFC_PROLOGUE(pymFormatMessage); { PyMFCLeavePython lp; return ImmReleaseContext(hWnd, hIMC); } PyMFC_EPILOGUE(0); } BOOL pymImmSetOpenStatus(HIMC hIMC, int fopen) { PyMFC_PROLOGUE(pymFormatMessage); { PyMFCLeavePython lp; return ImmSetOpenStatus(hIMC, fopen); } PyMFC_EPILOGUE(0); } BOOL pymImmGetOpenStatus(HIMC hIMC) { PyMFC_PROLOGUE(pymFormatMessage); { PyMFCLeavePython lp; return ImmGetOpenStatus(hIMC); } PyMFC_EPILOGUE(0); } BOOL pymImmSetCompositionWindow(HIMC hIMC, COMPOSITIONFORM *lpCompForm) { PyMFC_PROLOGUE(pymFormatMessage); { PyMFCLeavePython lp; return ImmSetCompositionWindow(hIMC, lpCompForm); } PyMFC_EPILOGUE(0); } BOOL pymImmSetCompositionFont(HIMC hIMC, LOGFONT *lplf) { PyMFC_PROLOGUE(pymFormatMessage); { PyMFCLeavePython lp; return ImmSetCompositionFont(hIMC, lplf); } PyMFC_EPILOGUE(0); } long pymImmGetCompositionString(HIMC hIMC, long dwIndex, void *lpBuf, long dwBufLen) { PyMFC_PROLOGUE(pymFormatMessage); { PyMFCLeavePython lp; LONG ret = ImmGetCompositionString(hIMC, dwIndex, lpBuf, dwBufLen); if (ret == IMM_ERROR_NODATA || ret == IMM_ERROR_GENERAL) { throw PyMFC_WIN32ERR(); } return ret; } PyMFC_EPILOGUE(-1); } BOOL pymOpenClipboard(HWND hWndNewOwner) { PyMFC_PROLOGUE(pymOpenClipboard); { PyMFCLeavePython lp; if (!OpenClipboard(hWndNewOwner)) { throw PyMFC_WIN32ERR(); } return TRUE; } PyMFC_EPILOGUE(0); } HANDLE pymGetClipboardData(UINT uFormat) { PyMFC_PROLOGUE(pymGetClipboardData); { PyMFCLeavePython lp; return GetClipboardData(uFormat); } PyMFC_EPILOGUE(0); } BOOL pymIsClipboardFormatAvailable(UINT format) { PyMFC_PROLOGUE(pymIsClipboardFormatAvailable); { PyMFCLeavePython lp; BOOL ret = IsClipboardFormatAvailable(format); return ret; } PyMFC_EPILOGUE(0); } BOOL pymCloseClipboard() { PyMFC_PROLOGUE(pymCloseClipboard); { PyMFCLeavePython lp; if (!CloseClipboard()) { throw PyMFC_WIN32ERR(); } return TRUE; } PyMFC_EPILOGUE(0); } HANDLE pymSetClipboardData(UINT uFormat, HANDLE hMem) { PyMFC_PROLOGUE(pymSetClipboardData); { PyMFCLeavePython lp; HANDLE ret = SetClipboardData(uFormat, hMem); if (!ret) { throw PyMFC_WIN32ERR(); } return ret; } PyMFC_EPILOGUE(0); } BOOL pymEmptyClipboard() { PyMFC_PROLOGUE(pymEmptyClipboard); { PyMFCLeavePython lp; if (!EmptyClipboard()) { throw PyMFC_WIN32ERR(); } return TRUE; } PyMFC_EPILOGUE(0); } BOOL pymPostMessage(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { PyMFC_PROLOGUE(pymPostMessage); { PyMFCLeavePython lp; BOOL ret = PostMessage(hWnd, Msg, wParam, lParam); if (!ret) { throw PyMFC_WIN32ERR(); } return TRUE; } PyMFC_EPILOGUE(0); } BOOL pymPostThreadMessage(DWORD idThread, UINT Msg, WPARAM wParam, LPARAM lParam) { PyMFC_PROLOGUE(pymPostThreadMessage); { PyMFCLeavePython lp; if (!PostThreadMessage(idThread, Msg, wParam, lParam)) { throw PyMFC_WIN32ERR(); } return TRUE; } PyMFC_EPILOGUE(0); } int pymMessageBox(HWND hWnd, TCHAR *lpText, TCHAR *lpCaption, UINT uType) { PyMFC_PROLOGUE(pymMessageBox); { PyMFCLeavePython lp; return MessageBox(hWnd, lpText, lpCaption, uType); } PyMFC_EPILOGUE(0); } BOOL pymShGetSpecialFolderPath(HWND hWnd, TCHAR *buf, int nFolder, BOOL fCreate) { PyMFC_PROLOGUE(pymShGetSpecialFolderPath); { PyMFCLeavePython lp; if (!SHGetSpecialFolderPath(hWnd, buf, nFolder, fCreate)) { throw PyMFC_WIN32ERR(); } return TRUE; } PyMFC_EPILOGUE(0); } BOOL pymShellExecute(SHELLEXECUTEINFO *se) { PyMFC_PROLOGUE(pymShellExecute); { PyMFCLeavePython lp; if (!ShellExecuteEx(se)) { throw PyMFC_WIN32ERR(); } return TRUE; } PyMFC_EPILOGUE(0); } DWORD pymWaitForMultipleObjectsEx(DWORD nCount, HANDLE* lpHandles, BOOL bWaitAll, DWORD dwMilliseconds, BOOL bAlertable) { PyMFC_PROLOGUE(pymShellExecute); { PyMFCLeavePython lp; DWORD ret = WaitForMultipleObjectsEx(nCount, lpHandles, bWaitAll, dwMilliseconds, bAlertable); if (ret == WAIT_FAILED) { throw PyMFC_WIN32ERR(); } return ret; } PyMFC_EPILOGUE(0); }
[ [ [ 1, 266 ] ] ]
3112fa9e141b9127771fd03040b5b2c920ec9a77
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleEventHandlers/ParticleUniverseDoAffectorEventHandler.h
e12bda39562af8c738c2f35314c88428f637aef4
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
2,883
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __PU_DO_AFFECTOR_EVENT_HANDLER_H__ #define __PU_DO_AFFECTOR_EVENT_HANDLER_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseEventHandler.h" namespace ParticleUniverse { /** This class explicitly calls an affector to affect the particles. There are several reasons why this is appropriate. One reason is, that you only want to affect a particle if a certain event occurs. Disable an affector and call it using this event handler, is the method (calling the affector from the event handler doesn't take into consideration that the affector is disabled). */ class _ParticleUniverseExport DoAffectorEventHandler : public ParticleEventHandler { protected: // Identifies the name of affector Ogre::String mAffectorName; // Determines whether the pre- and post processing activities must be executed also bool mPrePost; public: DoAffectorEventHandler(void); virtual ~DoAffectorEventHandler(void) {}; /** Get the indication whether pre- and postprocessing must be done. */ const bool getPrePost(void) const {return mPrePost;}; /** Set the indication whether pre- and postprocessing must be done. */ void setPrePost(const bool prePost){mPrePost = prePost;}; /** Get the name of the affector that must be enabled or disabled. */ const Ogre::String& getAffectorName(void) const {return mAffectorName;}; /** Set the name of the affector. */ void setAffectorName(const Ogre::String& affectorName){mAffectorName = affectorName;}; /** If the _handle() function of this class is invoked (by an Observer), it searches the ParticleAffector defined by the its name. The ParticleAffector is either part of the ParticleTechnique in which the DoAffectorEventHandler is defined, or if the Affector is not found, other ParticleTechniques are searched. */ virtual void _handle (ParticleTechnique* particleTechnique, Particle* particle, Ogre::Real timeElapsed); /** Copy attributes to another event handler. */ virtual void copyAttributesTo (ParticleEventHandler* eventHandler); }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 73 ] ] ]
024dcd1249bb69a8246b0657b383089a17aab76b
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/MyGUIEngine/src/MyGUI_SharedLayer.cpp
b9935f508a07cc84352a7764dd32153c35f25256
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
4,052
cpp
/*! @file @author Albert Semenov @date 02/2008 */ /* This file is part of MyGUI. MyGUI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #include "MyGUI_Precompiled.h" #include "MyGUI_LayerItem.h" #include "MyGUI_SharedLayer.h" #include "MyGUI_LayerNode.h" #include "MyGUI_RenderManager.h" namespace MyGUI { SharedLayer::SharedLayer() : mIsPick(false), mChildItem(nullptr) { } SharedLayer::~SharedLayer() { MYGUI_ASSERT(mChildItem == nullptr, "Layer '" << getName() << "' must be empty before destroy"); } void SharedLayer::deserialization(xml::ElementPtr _node, Version _version) { mName = _node->findAttribute("name"); if (_version >= Version(1, 2)) { MyGUI::xml::ElementEnumerator propert = _node->getElementEnumerator(); while (propert.next("Property")) { const std::string& key = propert->findAttribute("key"); const std::string& value = propert->findAttribute("value"); if (key == "Pick") mIsPick = utility::parseValue<bool>(value); } } else { mIsPick = utility::parseBool(_version < Version(1, 0) ? _node->findAttribute("peek") : _node->findAttribute("pick")); } } ILayerNode* SharedLayer::createChildItemNode() { if (mChildItem == nullptr) { mChildItem = new SharedLayerNode(this); } mChildItem->addUsing(); return mChildItem; } void SharedLayer::destroyChildItemNode(ILayerNode* _item) { // айтем рутовый, мы удаляем if (mChildItem == _item) { mChildItem->removeUsing(); if (0 == mChildItem->countUsing()) { delete mChildItem; mChildItem = nullptr; } return; } //MYGUI_EXCEPT("item node not found"); } void SharedLayer::upChildItemNode(ILayerNode* _item) { // если есть отец, то пусть сам рулит ILayerNode* parent = _item->getParent(); if (parent != nullptr) { parent->upChildItemNode(_item); } } ILayerItem* SharedLayer::getLayerItemByPoint(int _left, int _top) const { if (!mIsPick) return nullptr; if (mChildItem != nullptr) { ILayerItem* item = mChildItem->getLayerItemByPoint(_left, _top); if (item != nullptr) return item; } return nullptr; } IntPoint SharedLayer::getPosition(int _left, int _top) const { return IntPoint(_left, _top); } void SharedLayer::renderToTarget(IRenderTarget* _target, bool _update) { if (mChildItem != nullptr) mChildItem->renderToTarget(_target, _update); } EnumeratorILayerNode SharedLayer::getEnumerator() const { static VectorILayerNode nodes; if (mChildItem == nullptr) { nodes.clear(); } else { if (nodes.empty()) nodes.push_back(mChildItem); else nodes[0] = mChildItem; } return EnumeratorILayerNode(nodes); } void SharedLayer::dumpStatisticToLog() { static const char* spacer = " "; MYGUI_LOG(Info, spacer); MYGUI_LOG(Info, "Layer name='" << getName() << "'" << " type='" << getTypeName() << "'" << spacer); MYGUI_LOG(Info, "Count root nodes : " << (mChildItem == nullptr ? 0 : 1) << spacer); if (mChildItem != nullptr) { mChildItem->dumpStatisticToLog(0); } } const IntSize& SharedLayer::getSize() const { return RenderManager::getInstance().getViewSize(); } } // namespace MyGUI
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 154 ] ] ]
f79de28db5ec1e73c762582d855af6c41fc5a52d
893d8c9628e99dfe4412c400e626ad6fd08da6ee
/SocketException.cpp
656414981dbe19cede80db153333475e9fecc680
[]
no_license
herzi/distrrtgen
3db54ace872076c3cd609d0dbbad4fea9dbcc815
5cad3a168eedb11ab0288e0748294630d078c10e
refs/heads/master
2021-01-13T02:31:21.060660
2007-12-19T18:56:48
2007-12-19T18:56:48
5,073
2
0
null
null
null
null
UTF-8
C++
false
false
228
cpp
#include "SocketException.h" SocketException::SocketException(int nErrorCode, std::string szErrorMessage) : Exception(szErrorMessage) { this->nErrorCode = nErrorCode; } SocketException::~SocketException(void) { }
[ "alexis.dagues@14c93cb0-9641-0410-902e-89133d47d5d8" ]
[ [ [ 1, 11 ] ] ]
0977850907319da7a2081e852cdc6902d4498617
c58f258a699cc866ce889dc81af046cf3bff6530
/include/qmlib/corelib/dates/datestring.hpp
b90d75137e288564aee9601af5329e5ab4c3e704
[]
no_license
KoWunnaKo/qmlib
db03e6227d4fff4ad90b19275cc03e35d6d10d0b
b874501b6f9e537035cabe3a19d61eed7196174c
refs/heads/master
2021-05-27T21:59:56.698613
2010-02-18T08:27:51
2010-02-18T08:27:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,810
hpp
// /// \file /// \ingroup dates // #ifndef __DATE_STRING_QM_HPP__ #define __DATE_STRING_QM_HPP__ // // #include <qmlib/corelib/dates/daycount.hpp> QM_NAMESPACE /// \brief Period manager /// /// This class perform the basic conversions between a string period and numeric values /// \ingroup dates class period : public basedes { public: period(qm_int months = 0, qm_int days = 0):m_months(months),m_days(days){} period(const qm_string& str):m_months(0),m_days(0){this->add_tenure(str,"Y");} period(const qm_string& str, const qm_string& defpe):m_months(0),m_days(0){ this->add_tenure(str,defpe); } period(const period& rhs):m_months(rhs.m_months),m_days(rhs.m_days){} period(const qdate& start, const qdate& end); const period& operator = (const period& rhs) {m_months = rhs.m_months; m_days = rhs.m_days; return *this;} const period& operator = (const qm_string& rhs) {period p(rhs); return *this = p;} bool operator > (const period& pe) const {return this->total() > pe.total();} bool operator >= (const period& pe) const {return this->total() >= pe.total();} bool operator == (const period& pe) const {return this->total() == pe.total();} bool operator < (const period& pe) const {return this->total() < pe.total();} bool operator <= (const period& pe) const {return this->total() <= pe.total();} bool isempty() const {return m_months == 0 && m_days == 0;} void add_days(qm_int d) {m_days += d;} void add_weeks(qm_int w) {m_days += 7*w;} void add_months(qm_int m) {m_months += m;} void add_years(qm_int y) {m_months += 12*y;} void add_tenure(const qm_string& str, const qm_string& defpe); period& operator += (const period& pe) {m_months += pe.m_months; m_days += pe.m_days; return *this;} period& operator -= (const period& pe) {m_months -= pe.m_months; m_days -= pe.m_days; return *this;} period& operator += (const qm_string& rhs) {period pe(rhs); m_months += pe.m_months; m_days += pe.m_days; return *this;} period& operator -= (const qm_string& rhs) {period pe(rhs); m_months -= pe.m_months; m_days -= pe.m_days; return *this;} qm_int years() const {return m_months/12;} qm_int months() const {return m_months % 12;} qm_int totalmonths() const {return m_months;} qm_int weeks() const {return m_days/7;} qm_int days() const {return m_days % 7;} qm_int totaldays() const {return m_days;} qm_long total() const {return 30*m_months + m_days;} qm_real dcf() const {return this->totalmonths()/12.0 + this->totaldays()/365.0;} qm_string tostring() const; qm_string tofrequency() const; friend period operator + (const period& lhs, const period& rhs) {period p(lhs); return p+=rhs;} friend period operator + (const period& lhs, const qm_string& rhs) {period p(lhs); return p+=rhs;} friend period operator + (const qm_string& lhs, const period& rhs) {period p(lhs); return p+=rhs;} friend period operator - (const period& lhs, const period& rhs) {period p(lhs); return p-=rhs;} friend period operator - (const period& lhs, const qm_string& rhs) {period p(lhs); return p-=rhs;} friend period operator - (const qm_string& lhs, const period& rhs) {period p(lhs); return p-=rhs;} private: qm_long m_months; qm_long m_days; }; /// \brief An object used for specifing a date either by qm_date or by a tenure string /// /// This objec could be either a qm_date or a string such as "3M" or "1Y3M" etc.. /// \ingroup dates template<class D> class datestring : public basedes { public: typedef D datetype; //datestring(const qm_string& tenure = ""):m_tenure(tenure),m_isdate(false){} /// \brief default constructor datestring(const char* tenure = ""):m_period(tenure),m_isdate(false){} /// \brief string constructor datestring(const qm_string& tenure):m_period(tenure),m_isdate(false){} /// \brief date constructor datestring(const datetype& date):m_date(date),m_isdate(true){} /// \brief copy constructor datestring(const datestring& dtst); datestring& operator = (const datestring& rhs); datestring& operator = (const datetype& rhs); datestring& operator = (const qm_string& rhs); datestring& operator = (const period& rhs); bool operator > (const datestring& rh) const {return m_isdate ? m_date > rh.date() : m_period > rh.tenure();} bool operator >= (const datestring& rh) const {return m_isdate ? m_date >= rh.date() : m_period >= rh.tenure();} bool operator == (const datestring& rh) const {return m_isdate ? m_date == rh.date() : m_period == rh.tenure();} bool operator < (const datestring& rh) const {return m_isdate ? m_date < rh.date() : m_period < rh.tenure();} bool operator <= (const datestring& rh) const {return m_isdate ? m_date <= rh.date() : m_period <= rh.tenure();} const datetype& date() const; const period& tenure() const; bool isdate() const {return m_isdate;} bool isempty() const {return !m_isdate && m_period.isempty();} qm_string tostring() const; qm_real dcf(const D& date, const qm_string& dct = "ActAct") const; operator const qm_string& () {return this->tostring();} private: period m_period; datetype m_date; bool m_isdate; }; // // /// \brief parse a character into a string frequency /// @param freq a character in 'A' (annual), 'S' (semiannual), 'Q' (quarterly), /// 'B' (bimonthly) 'M' (monthly) /// @return a integer indicationg the number of months /// \ingroup tools inline period charFrequencyToPeriod(const char& freq) { char uf = std::toupper(freq); if(uf == 'A') return period(12); else if(uf == 'S') return period(6); else if(uf == 'Q') return period(3); else if(uf == 'B') return period(2); else if(uf == 'M') return period(1); else if(uf == 'W') return period(0,7); else if(uf == 'D') return period(0,1); else QM_FAIL("unrecognized frequency character. It must be in ('A','S','Q','M','W','D')"); } typedef datestring<qdate> dateperiod; inline period::period(const qdate& start, const qdate& end):m_months(0),m_days(0) { qm_long d = qdate::daydiff(start,end); if(d < 0) { QM_FAIL("negative period"); } else if(d < 4) m_days = d; else if(d < 25) { qm_real wr = d/7.0; int w = int(wr); if(wr - w > 0.5) m_days = 7*(w+1); else m_days = 7*w; } else { qm_real y = d/365.0; int yi = int(y); qm_real m = (d - 365*yi)/30.0; int mi = int(m); if(m - mi > 0.5) mi++; m_months = 12*yi + mi; } } inline void period::add_tenure(const qm_string& str, const qm_string& defaultPeriod) { if(str.length() == 0) return; qm_string st = qmstring::uppercase(str); if(st == "ON") { this->add_days(1); return; } else if(st == "TN") { this->add_days(2); return; } char abbr; for(;;) { qm_Size ip = st.find_first_of("DdWwMmYy"); if(ip >= st.length() && st.length() > 0) { ip = st.length(); QM_REQUIRE(defaultPeriod.length()>0,"Unknown period"); abbr = std::toupper(defaultPeriod[0]); } else if(ip <= str.length()-1) { QM_REQUIRE(ip>0,"Could not parse tenure string " + str); abbr = std::toupper(st[ip]); } else break; qm_int n = boost::lexical_cast<qm_int>(st.substr(0,ip)); if (abbr == 'D') this->add_days(n); else if (abbr == 'W') this->add_weeks(n); else if (abbr == 'M') this->add_months(n); else if (abbr == 'Y') this->add_years(n); if(ip >= st.length()-1) break; st = st.substr(ip+1); } } inline qm_string period::tostring() const { if(m_months == 0 && m_days == 1) return "ON"; if(m_months == 0 && m_days == 2) return "TN"; qm_int y = this->years(); qm_int m = this->months(); qm_int w = this->weeks(); qm_int d = this->days(); qm_string te; if(y>0) te += boost::lexical_cast<qm_string>(y)+"Y"; if(m>0) te += boost::lexical_cast<qm_string>(m)+"M"; if(w>0) te += boost::lexical_cast<qm_string>(w)+"W"; if(d>0) te += boost::lexical_cast<qm_string>(d)+"D"; return te; } inline qm_string period::tofrequency() const { if(m_months == 0) { switch(m_days) { case 0: return "continuous"; case 1: return "daily"; case 7: return "weekly"; case 14: return "biweekly"; default: return this->tostring(); } } else if(m_days == 0) { switch(m_months) { case 1: return "monthly"; case 2: return "bimonthly"; case 3: return "quarterly"; case 6: return "semiannually"; case 12: return "annually"; case 24: return "biannually"; default: return this->tostring(); } } else return this->tostring(); } template<class D> inline datestring<D>::datestring(const datestring<D>& rhs):m_isdate(rhs.m_isdate) { if(m_isdate) m_date = rhs.m_date; else m_period = rhs.m_period; } template<class D> inline datestring<D>& datestring<D>::operator = (const datestring<D>& rhs) { m_period = rhs.m_period; m_date = rhs.m_date; m_isdate = rhs.m_isdate; return *this; } template<class D> inline datestring<D>& datestring<D>::operator = (const D& rhs) { m_date = rhs; m_isdate = true; return *this; } template<class D> inline datestring<D>& datestring<D>::operator = (const qm_string& rhs) { m_period = rhs; m_isdate = false; return *this; } template<class D> inline datestring<D>& datestring<D>::operator = (const period& rhs) { m_period = rhs; m_isdate = false; return *this; } template<class D> inline const D& datestring<D>::date() const { QM_REQUIRE(this->isdate(),"not a date"); return m_date; } template<class D> inline const period& datestring<D>::tenure() const { QM_REQUIRE(!this->isdate(),"not a tenure"); return m_period; } template<class D> inline qm_string datestring<D>::tostring() const { if(this->isdate()) return m_date.tostring(); else return m_period.tostring(); } template<class D> inline qm_real datestring<D>::dcf(const D& date, const qm_string& dcname) const { if(this->isdate()) { DC dc = daycounter::get(dcname); if(dc) return dc->dcf(date,m_date); else QM_FAIL("Day counter not specified"); } else return m_period.dcf(); } QM_NAMESPACE_END #endif // __DATE_STRING_QM_HPP__
[ [ [ 1, 322 ] ] ]
e3c776f216edf797b84dedb969f3089c943bd678
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/nsrpc/include/nsrpc/p2p/P2pSession.h
936fdbd4f326bda27effc58c1fd39fb028571093
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UTF-8
C++
false
false
4,626
h
#ifndef NSRPC_P2PSESSION_H #define NSRPC_P2PSESSION_H #ifdef _MSC_VER # pragma once #endif #include "P2pConfig.h" #include "PeerId.h" #include "PeerStats.h" #include "PeerAddress.h" #include "Group.h" #include "PlugIn.h" #include <boost/noncopyable.hpp> class ACE_Reactor; namespace srpc { class RpcNetwork; } // namespace srpc namespace nsrpc { /** @addtogroup p2p * @{ */ /** * @class P2pSession * The session interface for a P2P. * @warning no thread-safe */ class P2pSession : public boost::noncopyable { public: virtual ~P2pSession() {} /** * Initialize this session. * @param port local listening port * @param password P2P session password * @param p2pOptions P2P options for each peer */ virtual bool open(srpc::UInt16 port, const srpc::String& password = srpc::null_string, P2pOptions p2pOptions = poNone) = 0; /// Disconnect & Deinitialize this session. virtual void close() = 0; /// it must be called before host() or connect() virtual void addP2pOptions(P2pOptions p2pOptions) = 0; /** * Creates a new P2P session, hosted by the local computer. * @param maxPeers the maximum number of peers allowed in the session. * Set this member to 0 to specify an unlimited number of players. * @param hostMigration enable host migration? * @param hostPrecedence if not empty, host migration is occurred by this order */ virtual void host(size_t maxPeers = 0, bool hostMigration = true, const PeerIds& hostPrecedence = PeerIds()) = 0; /** * Establishes the connection to all the peers in a peer-to-peer session. * @param hostAddresses the addresses to use to connect to the P2P host. */ virtual void connect(const PeerAddresses& hostAddresses) = 0; /// disconnect all peers from the current session virtual void disconnect() = 0; /// disconnect the peer from the current session virtual void disconnect(PeerId peerId) = 0; /** * Set the UDP Relay(STUN) server. * @param address Relay server's address * @param cipherKey relay server's packet cipher key. * If the key is null string, a default key is used. */ virtual void setRelayServer(const PeerAddress& address, const srpc::String& cipherKey = srpc::null_string) = 0; /** * Set host by manually. */ virtual void setHost(PeerId newHostId) = 0; /** * tick. (handle events, etc) * - tick() should be called fairly regularly for adequate performance. */ virtual void tick() = 0; /// attach a plug-in virtual void attach(PlugInPtr& plugIn) = 0; /// detach a plug-in virtual void detach(PlugInPtr& plugIn) = 0; /** * create a group (only host allowed) * @param groupName group name (duplication allowed) */ virtual GroupId createGroup(const RGroupName& groupName) = 0; /// destroy a group(only host allowed) virtual bool destroyGroup(GroupId groupId) = 0; /// join a group virtual bool joinGroup(GroupId groupId) = 0; /// leave from a group virtual bool leaveGroup(GroupId groupId) = 0; /** * get P2P groups */ virtual const RGroupMap& getGroups() const = 0; /// Is the host for a P2P session. virtual bool isHost() const = 0; /// Get the number of Peers that connected. virtual size_t getPeerCount() const = 0; /// Get my PeerId. virtual PeerId getPeerId() const = 0; /// Get a peer's target address(connection path). virtual PeerAddress getTargetAddress(PeerId peerId) const = 0; /** * Get the addresses of the peer. * - If the address resolved via RelayServer, first address is public. */ virtual PeerAddresses getAddresses(PeerId peerId) const = 0; /// get peer's P2P options virtual P2pOptions getP2pOptions(PeerId peerId) const = 0; /// Get the statistics of the peer. virtual PeerStats getStats(PeerId peerId) const = 0; /// Get the statistics string of the peer. virtual srpc::String getStatsString(PeerId peerId) const = 0; /// get the RpcNetwork instance for RPC bind. virtual srpc::RpcNetwork& getRpcNetwork() = 0; /// Get host PeerId. virtual PeerId getHostPeerId() const = 0; /// is host alive? virtual bool isHostAlive() const = 0; }; /** @} */ // addtogroup p2p } // namespace nsrpc #endif // NSRPC_P2PSESSION_H
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 165 ] ] ]
86fea7ec807b333b3c9827e5d0b13a18034907fa
8ffc2ad8cf32ffd9ba2974ee9bb4ae36de90a860
/SIFTCustom/src/CvPointCustom.cpp
4f7ae7a34a214a1a0b17129154e7a9e92ccae379
[]
no_license
mhlee1215/sift-custom
ca40895d3b3ba6e3e2c6b45947e21a4e07a5270e
ec3910e172eae4bafa6e21952e058f6875362569
refs/heads/master
2016-09-06T10:54:10.910652
2010-06-10T08:52:48
2010-06-10T08:52:48
33,061,761
0
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
/* * CvPointCustom.cpp * * Created on: 2010. 5. 26. * Author: hp */ #include "CvPointCustom.h" CvPointCustom::CvPointCustom(int inX, int inY) { // TODO Auto-generated constructor stub x = inX; y = inY; } CvPointCustom::~CvPointCustom() { // TODO Auto-generated destructor stub } bool CvPointCustom::operator == (CvPointCustom another){ if(x == another.x && y == another.y) return true; return false; }
[ "mhlee1215@6231343e-7b99-2e4e-8751-d345bb62f328" ]
[ [ [ 1, 24 ] ] ]
a4de9b1a85b39b30c4e9cafa75eeb2fe1de37d26
a1e9c29572b2404e4195c14a14dbf5f2d260d595
/src/RealitySynthesizer.h
885fbc2d5cd87e91b041c0934d58540bd33a6846
[]
no_license
morsela/texton-izer
87333d229a34bf885e00c77b672d671ff72941f3
8e9f96d4a00834087247d000ae4df5282cbbfc4e
refs/heads/master
2021-07-29T01:37:38.232643
2009-02-13T15:40:03
2009-02-13T15:40:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
974
h
#ifndef __H_REALITY_SYNTHESIZER_H__ #define __H_REALITY_SYNTHESIZER_H__ #include "defs.h" #include "Cluster.h" #include "Synthesizer.h" #include <vector> using std::vector; class RealitySynthesizer : public Synthesizer { public: RealitySynthesizer(int nWindow, int MaxDiff); virtual ~RealitySynthesizer(); IplImage* synthesize(int nNewWidth, int nNewHeight, int depth, int nChannels, vector<Cluster> &clusterList,int * pTextonMap, int nMapWidth, int nMapHeight); private: bool checkMapSpace(int x, int y, int nCluster, int *scaledTextonMap, IplImage* img); int * scaleTextonMap(int * pTextonMap, int nWidth, int nHeight, int nScaledWidth, int nScaledHeight); void removeFromMap(int x, int y, Texton *t, int nWidth, int nHeight, int*scaledTextonMap); void printTextonMap(int nMapWidth, int nMapHeight, int *scaledTextonMap); private: int m_nWindow; int m_nMaxDiff; }; #endif //__H_REALITY_SYNTHESIZER_H__
[ "morsela@7f168336-c49e-11dd-bdf1-993be837f8bb" ]
[ [ [ 1, 41 ] ] ]
db28e1d96a62b363387ce8dc4cf6a2e5af95a764
98fb339799882c5959f0342ddb6def10bad37bf8
/Workspace/GC/Windows-GCFEM/GC_FaceOrientationMapper/AAM_CAM.cpp
16e92cface18b6168ffaf73b60cfbb17e84ca83b
[]
no_license
sreedal/GC
58a849794b8deaafb631a5954c897bb551a1e122
7dcd86584296d6beb9cef0b8e8d8760210e7dab1
refs/heads/master
2016-09-05T21:38:54.911411
2009-12-11T08:34:38
2009-12-11T08:34:38
419,540
0
1
null
null
null
null
UTF-8
C++
false
false
13,654
cpp
/**************************************************************************** * AAMLibrary * http://code.google.com/p/aam-library * Copyright (c) 2008-2009 by GreatYao, all rights reserved. ****************************************************************************/ #include "stdafx.h" #include "AAM_CAM.h" //============================================================================ AAM_CAM::AAM_CAM() { __MeanAppearance = 0; __AppearanceEigenValues = 0; __AppearanceEigenVectors = 0; __Qs = 0; __Qg = 0; __MeanS = 0; __MeanG = 0; __Points = 0; __Storage = 0; __pq = 0; __a = 0; } //============================================================================ AAM_CAM::~AAM_CAM() { cvReleaseMat(&__MeanAppearance); cvReleaseMat(&__AppearanceEigenValues); cvReleaseMat(&__AppearanceEigenVectors); cvReleaseMat(&__Qg); cvReleaseMat(&__Qs); cvReleaseMat(&__MeanS); cvReleaseMat(&__MeanG); cvReleaseMat(&__Points); cvReleaseMemStorage(&__Storage); cvReleaseMat(&__pq); cvReleaseMat(&__a); } //============================================================================ void AAM_CAM::Train(const file_lists& pts_files, const file_lists& img_files, double scale /* = 1.0 */, double shape_percentage /* = 0.95 */, double texture_percentage /* = 0.95 */, double appearance_percentage /* = 0.95 */) { //building shape and texture distribution model std::vector<AAM_Shape> AllShapes; for(int ii = 0; ii < pts_files.size(); ii++) { AAM_Shape Shape; bool flag = Shape.ReadAnnotations(pts_files[ii]); if(!flag) { IplImage* image = cvLoadImage(img_files[ii].c_str(), -1); Shape.ScaleXY(image->width, image->height); cvReleaseImage(&image); } AllShapes.push_back(Shape); } printf("Build point distribution model...\n"); __shape.Train(AllShapes, scale, shape_percentage); printf("Build warp information of mean shape mesh..."); __Points = cvCreateMat (1, __shape.nPoints(), CV_32FC2); __Storage = cvCreateMemStorage(0); AAM_Shape refShape = __shape.__AAMRefShape/* * scale */; __paw.Train(refShape, __Points, __Storage); printf("[%d by %d, %d triangles, %d*3 pixels]\n", __paw.Width(), __paw.Height(), __paw.nTri(), __paw.nPix()); printf("Build texture distribution model...\n"); __texture.Train(pts_files, img_files, __paw, texture_percentage, true); __pq = cvCreateMat(1, __shape.nModes()+4, CV_64FC1); printf("Build combined appearance model...\n"); int nsamples = pts_files.size(); int npointsby2 = __shape.nPoints()*2; int npixels = __texture.nPixels(); int nfeatures = __shape.nModes() + __texture.nModes(); CvMat* AllAppearances = cvCreateMat(nsamples, nfeatures, CV_64FC1); CvMat* s = cvCreateMat(1, npointsby2, CV_64FC1); CvMat* t = cvCreateMat(1, npixels, CV_64FC1); __MeanS = cvCreateMat(1, npointsby2, CV_64FC1); __MeanG = cvCreateMat(1, npixels, CV_64FC1); cvCopy(__shape.GetMean(), __MeanS); cvCopy(__texture.GetMean(), __MeanG); //calculate ratio of shape to appearance CvScalar Sum1 = cvSum(__shape.__ShapesEigenValues); CvScalar Sum2 = cvSum(__texture.__TextureEigenValues); __WeightsS2T = sqrt(Sum2.val[0] / Sum1.val[0]); for(int i = 0; i < nsamples; i++) { //Get Shape and Texture respectively IplImage* image = cvLoadImage(img_files[i].c_str(), -1); AAM_Shape Shape; if(!Shape.ReadAnnotations(pts_files[i])) Shape.ScaleXY(image->width, image->height); Shape.Point2Mat(s); __paw.CalcWarpTexture(s, image, t); __texture.NormalizeTexture(__MeanG, t); //combine shape and texture parameters CvMat OneAppearance; cvGetRow(AllAppearances, &OneAppearance, i); ShapeTexture2Combined(s, t, &OneAppearance); cvReleaseImage(&image); } //Do PCA of appearances DoPCA(AllAppearances, appearance_percentage); int np = __AppearanceEigenVectors->rows; printf("Extracting the shape and texture part of the combined eigen vectors..\n"); // extract the shape part of the combined eigen vectors CvMat Ps; cvGetCols(__AppearanceEigenVectors, &Ps, 0, __shape.nModes()); __Qs = cvCreateMat(np, npointsby2, CV_64FC1); cvMatMul(&Ps, __shape.GetBases(), __Qs); cvConvertScale(__Qs, __Qs, 1.0/__WeightsS2T); // extract the texture part of the combined eigen vectors CvMat Pg; cvGetCols(__AppearanceEigenVectors, &Pg, __shape.nModes(), nfeatures); __Qg = cvCreateMat(np, npixels, CV_64FC1); cvMatMul(&Pg, __texture.GetBases(), __Qg); __a = cvCreateMat(1, __AppearanceEigenVectors->cols, CV_64FC1); } //============================================================================ void AAM_CAM::ShapeTexture2Combined(const CvMat* Shape, const CvMat* Texture, CvMat* Appearance) { __shape.CalcParams(Shape, __pq); CvMat mat1, mat2; cvGetCols(__pq, &mat1, 4, 4+__shape.nModes()); cvGetCols(Appearance, &mat2, 0, __shape.nModes()); cvCopy(&mat1, &mat2); cvConvertScale(&mat2, &mat2, __WeightsS2T); cvGetCols(Appearance, &mat2, __shape.nModes(), __shape.nModes()+__texture.nModes()); __texture.CalcParams(Texture, &mat2); } //============================================================================ void AAM_CAM::DoPCA(const CvMat* AllAppearances, double percentage) { printf("Doing PCA of appearance datas..."); int nSamples = AllAppearances->rows; int nfeatures = AllAppearances->cols; int nEigenAtMost = MIN(nSamples, nfeatures); CvMat* tmpEigenValues = cvCreateMat(1, nEigenAtMost, CV_64FC1); CvMat* tmpEigenVectors = cvCreateMat(nEigenAtMost, nfeatures, CV_64FC1); __MeanAppearance = cvCreateMat(1, nfeatures, CV_64FC1 ); cvCalcPCA(AllAppearances, __MeanAppearance, tmpEigenValues, tmpEigenVectors, CV_PCA_DATA_AS_ROW); double allSum = cvSum(tmpEigenValues).val[0]; double partSum = 0.0; int nTruncated = 0; double largesteigval = cvmGet(tmpEigenValues, 0, 0); for(int i = 0; i < nEigenAtMost; i++) { double thiseigval = cvmGet(tmpEigenValues, 0, i); if(thiseigval / largesteigval < 0.0001) break; // firstly check partSum += thiseigval; ++ nTruncated; if(partSum/allSum >= percentage) break; //secondly check } __AppearanceEigenValues = cvCreateMat(1, nTruncated, CV_64FC1); __AppearanceEigenVectors = cvCreateMat(nTruncated, nfeatures, CV_64FC1); CvMat G; cvGetCols(tmpEigenValues, &G, 0, nTruncated); cvCopy(&G, __AppearanceEigenValues); cvGetRows(tmpEigenVectors, &G, 0, nTruncated); cvCopy(&G, __AppearanceEigenVectors); cvReleaseMat(&tmpEigenVectors); cvReleaseMat(&tmpEigenValues); printf("Done (%d/%d)\n", nTruncated, nEigenAtMost); } //============================================================================ void AAM_CAM::CalcLocalShape(CvMat* s, const CvMat* c) { cvMatMul(c, __Qs, s); cvAdd(s, __MeanS, s); } //============================================================================ void AAM_CAM::CalcGlobalShape(CvMat* s, const CvMat* pose) { int npoints = s->cols/2; double* fasts = s->data.db; double a=cvmGet(pose,0,0)+1, b=cvmGet(pose,0,1), tx=cvmGet(pose,0,2), ty=cvmGet(pose,0,3); double x, y; for(int i = 0; i < npoints; i++) { x = fasts[2*i ]; y = fasts[2*i+1]; fasts[2*i ] = a*x-b*y+tx; fasts[2*i+1] = b*x+a*y+ty; } } //============================================================================ void AAM_CAM::CalcTexture(CvMat* t, const CvMat* c) { cvMatMul(c, __Qg, t); cvAdd(t, __MeanG, t); } //============================================================================ void AAM_CAM::CalcParams(CvMat* c, const CvMat* bs, const CvMat* bg) { double* fasta = __a->data.db; double* fastbs = bs->data.db; double* fastbg = bg->data.db; int i; for(i = 0; i < bs->cols; i++) fasta[i] = __WeightsS2T * fastbs[i]; for(i = 0; i < bg->cols; i++) fasta[i+bs->cols] = fastbg[i]; cvProjectPCA(__a, __MeanAppearance, __AppearanceEigenVectors, c); } //============================================================================ void AAM_CAM::Clamp(CvMat* c, double s_d /* = 3.0 */) { double* fastc = c->data.db; double* fastv = __AppearanceEigenValues->data.db; int nmodes = nModes(); double limit; for(int i = 0; i < nmodes; i++) { limit = s_d*sqrt(fastv[i]); if(fastc[i] > limit) fastc[i] = limit; else if(fastc[i] < -limit) fastc[i] = -limit; } } //============================================================================ void AAM_CAM::DrawAppearance(IplImage* image, const AAM_Shape& Shape, CvMat* Texture) { AAM_PAW paw; int x1, x2, y1, y2, idx1 = 0, idx2 = 0; int tri_idx, v1, v2, v3; int minx, miny, maxx, maxy; paw.Train(Shape, __Points, __Storage, __paw.GetTri(), false); AAM_Shape refShape = __paw.__referenceshape; double minV, maxV; cvMinMaxLoc(Texture, &minV, &maxV); cvConvertScale(Texture, Texture, 1/(maxV-minV)*255, -minV*255/(maxV-minV)); minx = Shape.MinX(); miny = Shape.MinY(); maxx = Shape.MaxX(); maxy = Shape.MaxY(); for(int y = miny; y < maxy; y++) { y1 = y-miny; for(int x = minx; x < maxx; x++) { x1 = x-minx; idx1 = paw.Rect(y1, x1); if(idx1 >= 0) { tri_idx = paw.PixTri(idx1); v1 = paw.Tri(tri_idx, 0); v2 = paw.Tri(tri_idx, 1); v3 = paw.Tri(tri_idx, 2); x2 = paw.Alpha(idx1)*refShape[v1].x + paw.Belta(idx1)*refShape[v2].x + paw.Gamma(idx1)*refShape[v3].x; y2 = paw.Alpha(idx1)*refShape[v1].y + paw.Belta(idx1)*refShape[v2].y + paw.Gamma(idx1)*refShape[v3].y; idx2 = __paw.Rect(y2, x2); if(idx2 < 0) continue; CV_IMAGE_ELEM(image, byte, y, 3*x) = cvmGet(Texture, 0, 3*idx2); CV_IMAGE_ELEM(image, byte, y, 3*x+1) = cvmGet(Texture, 0, 3*idx2+1); CV_IMAGE_ELEM(image, byte, y, 3*x+2) = cvmGet(Texture, 0, 3*idx2+2); } } } } //============================================================================ void AAM_CAM::Write(std::ofstream& os) { __shape.Write(os); __texture.Write(os); __paw.Write(os); os << __AppearanceEigenVectors->rows << " " << __AppearanceEigenVectors->cols << " " << __WeightsS2T << std::endl; os << __MeanAppearance; os << __AppearanceEigenValues; os << __AppearanceEigenVectors; os << __Qs; os << __Qg; os << __MeanS; os << __MeanG; } //============================================================================ void AAM_CAM::Read(std::ifstream& is) { __shape.Read(is); __texture.Read(is); __paw.Read(is); int np, nfeatures; is >> np >> nfeatures >> __WeightsS2T; __MeanAppearance = cvCreateMat(1, nfeatures, CV_64FC1); __AppearanceEigenValues = cvCreateMat(1, np, CV_64FC1); __AppearanceEigenVectors = cvCreateMat(np, nfeatures, CV_64FC1); __Qs = cvCreateMat(np, __shape.nPoints()*2, CV_64FC1); __Qg = cvCreateMat(np, __texture.nPixels(), CV_64FC1); __MeanS = cvCreateMat(1, __shape.nPoints()*2, CV_64FC1); __MeanG = cvCreateMat(1, __texture.nPixels(), CV_64FC1); is >> __MeanAppearance; is >> __AppearanceEigenValues; is >> __AppearanceEigenVectors; is >> __Qs; is >> __Qg; is >> __MeanS; is >> __MeanG; __Points = cvCreateMat (1, __shape.nPoints(), CV_32FC2); __Storage = cvCreateMemStorage(0); __pq = cvCreateMat(1, __shape.nModes()+4, CV_64FC1); __a = cvCreateMat(1, __AppearanceEigenVectors->cols, CV_64FC1); } //============================================================================ static AAM_CAM *g_cam; static const int n = 6;//appearance modes static int b_c[n]; static const int offset = 40; static CvMat* c = 0;//conbined appearance parameters static CvMat* s = 0;//shape instance static CvMat* t = 0;//texture instance static IplImage* image = 0; static AAM_Shape aam_s; //============================================================================ //============================================================================ void ontrackcam(int pos) { if(c == 0) { c = cvCreateMat(1, g_cam->nModes(), CV_64FC1);cvZero(c); s = cvCreateMat(1, g_cam->__shape.nPoints()*2, CV_64FC1); t = cvCreateMat(1, g_cam->__texture.nPixels(), CV_64FC1); } double var; //registrate appearance parameters for(int i = 0; i < n; i++) { var = 3*sqrt(g_cam->Var(i))*(double(b_c[i])/offset-1.0); cvmSet(c, 0, i, var); } //generate shape and texture instance g_cam->CalcLocalShape(s, c); g_cam->CalcTexture(t, c); //warp texture instance from base mesh to current shape instance aam_s.Mat2Point(s); int w = aam_s.GetWidth(), h = aam_s.MaxY()-aam_s.MinY(); aam_s.Translate(w, h); if(image == 0)image = cvCreateImage(cvSize(w*2,h*2), 8, 3); cvSet(image, cvScalar(128, 128, 128)); g_cam->DrawAppearance(image, aam_s, t); cvNamedWindow("Combined Appearance Model",1); cvShowImage("Combined Appearance Model", image); if(cvWaitKey(10) == '27') { cvReleaseImage(&image); cvReleaseMat(&s); cvReleaseMat(&t); cvReleaseMat(&c); cvDestroyWindow("Parameters"); cvDestroyWindow("Combined Appearance Model"); } } //============================================================================ void AAM_CAM::ShowVariation() { printf("Show modes of appearance variations...\n"); cvNamedWindow("Parameters",1); //create trackbars for appearance for(int i = 0; i < n; i++) { char barname[100]; sprintf(barname, "a %d", i); b_c[i] = offset; cvCreateTrackbar(barname, "Parameters", &b_c[i], 2*offset+1, ontrackcam); } g_cam = this; ontrackcam(1); cvWaitKey(0); }
[ [ [ 1, 435 ] ] ]
d08fa10e410657a142b53062522e94ac4ec3ac0f
22fb52fc26ab1da21ab837a507524f111df5b694
/voxelbrain/nifti.cpp
f2d49c1fc20425a8cfdbd4c6d9091b58bf65896e
[]
no_license
yangguang-ecnu/voxelbrain
b343cec00e7b76bc46cc12723f750185fa84e6d2
82e1912ff69998077a5d7ecca9b5b1f9d7c1b948
refs/heads/master
2021-01-10T01:21:59.902255
2009-02-10T05:24:40
2009-02-10T05:24:40
52,189,505
0
0
null
null
null
null
UTF-8
C++
false
false
11,186
cpp
/********************************************************************* * * Very simple code snippets to read/write nifti1 files * This code is placed in the public domain. * * If you are the type who doesn't want to use a file format unless * you can write your own i/o code in less than 30minutes, this * example is for you. * * This code does not deal with wrong-endian data, compressed data, * the new qform/sform orientation codes, parsing filenames, volume- * wise or timecourse-wise data access or any of a million other very useful * things that are in the niftilib i/o reference libraries. * We encourage people to use the niftilib reference library and send * feedback/suggestions, see http://niftilib.sourceforge.net/ * But, if that is too much to tackle and you just want to jump in, this * code is a starting point. * This code was written for maximum readability, not for the greatest * coding style. * * * If you are already a little familiar with reading/writing Analyze * files of some flavor, and maybe even have some of your own code, here * are the most important things to be aware of in transitioning to nifti1: * * 1. nii vs .hdr/.img * nifti1 datasets can be stored either in .hdr/.img pairs of files * or in 1 .nii file. In a .nii file the data will start at the byte * specified by the vox_offset field, which will be 352 if no extensions * have been added. And, nifti1 really does like that magic field set * to "n+1" for .nii and "ni1" for .img/.hdr * * 2. scaling * nifti1 datasets can contain a scaling factor. You need to check the * scl_slope field and if that isn't 0, scale your data by * Y * scl_slope + scl_inter * * 3. extensions * nifti1 datasets can have some "extension data" stuffed after the * regular header. You can just ignore it, but, be aware that a * .hdr file may be longer than 348 bytes, and, in a .nii file * you can't just jump to byte 352, you need to use the vox_offset * field to get the start of the image data. * * 4. new datatypes * nifti1 added a few new datatypes that were not in the Analyze 7.5 * format from which nifti1 is derived. If you're just working with * your own data this is not an issue but if you get a foreign nifti1 * file, be aware of exotic datatypes like DT_COMPLEX256 and mundane * things like DT_UINT16. * * 5. other stuff * nifti1 really does like the dim[0] field set to the number of * dimensions of the dataset. Other Analyze flavors might not * have been so scrupulous about that. * nifti1 has a bunch of other new fields such as intent codes, * qform/sform, etc. but, if you just want to get your hands on * the data blob you can ignore these. Example use of these fields * is in the niftilib reference libraries. * * * * To compile: * You need to put a copy of the nifti1.h header file in this directory. * It can be obtained from the NIFTI homepage http://nifti.nimh.nih.gov/ * or from the niftilib SourceForge site http://niftilib.sourceforge.net/ * * cc -o nifti1_read_write nifti1_read_write.c * * * To run: * nifti1_read_write -w abc.nii abc.nii * nifti1_read_write -r abc.nii abc.nii * * * The read method is hardcoded to read float32 data. To change * to your datatype, just change the line: * typedef float MY_DATATYPE; * * The write method is hardcoded to write float32 data. To change * to your datatype, change the line: * typedef float MY_DATATYPE; * and change the lines: * hdr.datatype = NIFTI_TYPE_FLOAT32; * hdr.bitpix = 32; * * * Written by Kate Fissell, University of Pittsburgh, May 2005. * *********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "nifti.h" #include "volio.h" typedef short int MY_DATATYPE; #define MIN_HEADER_SIZE 348 #define NII_HEADER_SIZE 352 /********************************************************************** * * read_nifti_file * **********************************************************************/ int raw_volume::read_nifti_file(const char * hdr_file, const char * data_file) { FILE *fp; size_t ret,i; double total; /********** open and read header */ fp = fopen(hdr_file,"rb"); if (fp == NULL) { fprintf(stderr, "\nError opening header file %s\n",hdr_file); exit(1); } ret = fread(&hdr, MIN_HEADER_SIZE, 1, fp); if (ret != 1) { fprintf(stderr, "\nError reading header file %s\n",hdr_file); exit(1); } fclose(fp); /********** print a little header information */ fprintf(stderr, "\n%s header information:",hdr_file); fprintf(stderr, "\nXYZT dimensions: %d %d %d %d",hdr.dim[1],hdr.dim[2],hdr.dim[3],hdr.dim[4]); fprintf(stderr, "\nDatatype code and bits/pixel: %d %d",hdr.datatype,hdr.bitpix); fprintf(stderr, "\nScaling slope and intercept: %.6f %.6f",hdr.scl_slope,hdr.scl_inter); fprintf(stderr, "\nByte offset to data in datafile: %ld",(long)(hdr.vox_offset)); fprintf(stderr, "\n"); /* copying */ dim[0] = hdr.dim[1]; dim[1] = hdr.dim[2]; dim[2] = hdr.dim[3]; /********** open the datafile, jump to data offset */ fp = fopen(data_file,"rb"); if (fp == NULL) { fprintf(stderr, "\nError opening data file %s\n",data_file); exit(1); } ret = fseek(fp, (long)(hdr.vox_offset), SEEK_SET); if (ret != 0) { fprintf(stderr, "\nError doing fseek() to %ld in data file %s\n",(long)(hdr.vox_offset), data_file); exit(1); } /********** allocate buffer and read first 3D volume from data file */ int bpv = hdr.bitpix / 8; //bytes per voxel //raw buffer void * raw_data = malloc(bpv * hdr.dim[1]*hdr.dim[2]*hdr.dim[3]); //allocating the data to be used data = (MY_DATATYPE *) malloc(sizeof(MY_DATATYPE) * hdr.dim[1]*hdr.dim[2]*hdr.dim[3]); if (data == NULL) { fprintf(stderr, "\nError allocating data buffer for %s\n",data_file); exit(1); } ret = fread(raw_data, bpv, hdr.dim[1]*hdr.dim[2]*hdr.dim[3], fp); printf("Read %d out of %d items", ret, hdr.dim[1]*hdr.dim[2]*hdr.dim[3]); if(ret == hdr.dim[1]*hdr.dim[2]*hdr.dim[3]) { for (i=0; i<(unsigned int)hdr.dim[1]*hdr.dim[2]*hdr.dim[3]; i++){ //once again, lousy. switch(bpv){ case 1: data[i] = ((unsigned char *)raw_data)[i]; break; case 2: data[i] = ((unsigned short *)raw_data)[i]; break; case 4: data[i] = ((unsigned int *)raw_data)[i]; break; }; }; } else { fprintf(stderr, "\nError reading volume 1 from %s (%d)\n",data_file,ret); exit(1); } free(raw_data); fclose(fp); /********** scale the data buffer */ if (hdr.scl_slope != 0) { for (i=0; i<(unsigned int)hdr.dim[1]*hdr.dim[2]*hdr.dim[3]; i++) data[i] = (data[i] * hdr.scl_slope) + hdr.scl_inter; } /********** print mean of data */ min = 10000; max = 0; int voxel_count = 0; total = 0; for (i=0; i<(unsigned int)hdr.dim[1]*hdr.dim[2]*hdr.dim[3]; i++){ if(data[i]>0){ total += data[i]; voxel_count++; }; if(data[i] > max)max = data[i]; if(data[i] < min)min = data[i]; }; total /= voxel_count;//(hdr.dim[1]*hdr.dim[2]*hdr.dim[3]); fprintf(stderr, "\nMean of volume 1 in %s is %.3f; max/min %d/%d\n",data_file,total, max , min); return(0); } /********************************************************************** * * write_nifti_file * * write a sample nifti1 (.nii) data file * datatype is float32 * XYZT size is 64x64x16x10 * XYZ voxel size is 1mm * TR is 1500ms * **********************************************************************/ int raw_volume::write_nifti_file(const char * hdr_file, const char * data_file) { //nifti_1_header hdr; //nifti1_extender pad={0,0,0,0}; FILE *fp; int ret,i; //MY_DATATYPE *data=NULL; short do_nii; /********** make sure user specified .hdr/.img or .nii/.nii */ if ( (strlen(hdr_file) < 4) || (strlen(data_file) < 4) ) { fprintf(stderr, "\nError: write files must end with .hdr/.img or .nii/.nii extension\n"); exit(1); } if ( (!strncmp(hdr_file+(strlen(hdr_file)-4), ".hdr",4)) && (!strncmp(data_file+(strlen(data_file)-4), ".img",4)) ) { do_nii = 0; } else if ( (!strncmp(hdr_file+(strlen(hdr_file)-4), ".nii",4)) && (!strncmp(data_file+(strlen(data_file)-4), ".nii",4)) ) { do_nii = 1; } else { fprintf(stderr, "\nError: file(s) to be written must end with .hdr/.img or .nii/.nii extension\n"); exit(1); } /********** fill in the minimal default header fields */ //memset((void *)&hdr, 0, sizeof(hdr)); //zerowing /*hdr.sizeof_hdr = MIN_HEADER_SIZE; hdr.dim[0] = 4; hdr.dim[1] = 64; hdr.dim[2] = 64; hdr.dim[3] = 16; hdr.dim[4] = 10; hdr.datatype = NIFTI_TYPE_FLOAT32; hdr.bitpix = 32; hdr.pixdim[1] = 1.0; hdr.pixdim[2] = 1.0; hdr.pixdim[3] = 1.0; hdr.pixdim[4] = 1.5; if (do_nii) hdr.vox_offset = (float) NII_HEADER_SIZE; else hdr.vox_offset = (float)0; hdr.scl_slope = 100.0; hdr.xyzt_units = NIFTI_UNITS_MM | NIFTI_UNITS_SEC; if (do_nii) strncpy(hdr.magic, "n+1\0", 4); else strncpy(hdr.magic, "ni1\0", 4); data = (MY_DATATYPE *) malloc(sizeof(MY_DATATYPE) * hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4]); if (data == NULL) { fprintf(stderr, "\nError allocating data buffer for %s\n",data_file); exit(1); } for (i=0; i<hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4]; i++) data[i] = (raw_volume::MY_DATA)(i / hdr.scl_slope); */ /********** write first 348 bytes of header */ fp = fopen(hdr_file,"w"); if (fp == NULL) { fprintf(stderr, "\nError opening header file %s for write\n",hdr_file); exit(1); } ret = fwrite(&hdr, MIN_HEADER_SIZE, 1, fp); if (ret != 1) { fprintf(stderr, "\nError writing header file %s\n",hdr_file); exit(1); } fclose(fp); /* close .hdr file */ int bpv = hdr.bitpix / 8; //bytes per voxel printf("Trying to do %d bpv\n", bpv); //raw buffer void * raw_data = malloc(bpv * hdr.dim[1]*hdr.dim[2]*hdr.dim[3]); for (i=0; i<(unsigned int)hdr.dim[1]*hdr.dim[2]*hdr.dim[3]; i++){ //once again, lousy. switch(bpv){ case 1: ((unsigned char *)raw_data)[i] = data[i]; break; case 2: ((unsigned short *)raw_data)[i] = data[i]; break; case 4: ((unsigned int *)raw_data)[i] = data[i]; break; }; }; fp = fopen(data_file,"wb"); if (fp == NULL) { fprintf(stderr, "\nError opening data file %s for write\n",data_file); exit(1); } ret = fwrite(raw_data, bpv, hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4], fp); printf("written %d itens\n", ret); // if (ret != hdr.dim[1]*hdr.dim[2]*hdr.dim[3]*hdr.dim[4]) { // fprintf(stderr, "\nError writing data to %s\n",data_file); // exit(1); // } free(raw_data); fclose(fp); return(0); };
[ "konstantin.levinski@04f5dad0-e037-0410-8c28-d9c1d3725aa7" ]
[ [ [ 1, 343 ] ] ]
29496d5f41c1008275653d351cf4185755fd5774
cfc9acc69752245f30ad3994cce0741120e54eac
/bikini/include/bikini/flash/shape.hpp
367b7edf12231c3d02fb1976c4bd359518a17424
[]
no_license
Heartbroken/bikini-iii
3b7852d1af722b380864ac87df57c37862eb759b
93ffa5d43d9179b7c5e7f7c2df9df7dafd79a739
refs/heads/master
2020-03-28T00:41:36.281253
2009-04-30T14:58:10
2009-04-30T14:58:10
37,190,689
0
0
null
null
null
null
UTF-8
C++
false
false
1,992
hpp
/*---------------------------------------------------------------------------------------------*//* Binary Kinematics 3 - C++ Game Programming Library Copyright (C) 2008 Viktor Reutzky [email protected] *//*---------------------------------------------------------------------------------------------*/ #pragma once struct shape : _placed { typedef real2 point; typedef array_<point> points; struct edge { uint s, c, e; }; typedef array_<edge> edges; struct fillstyle { color c; }; typedef array_<fillstyle> fillstyles; typedef array_<edges> filledges; //struct linestyle : fillstyle { uint w; }; //struct path { uint style; std::vector<edge> edges; }; struct info : _placed::info { typedef shape object; info(swfstream &_s, tag::type _type); inline uint point_count() const { return m_points.size(); } inline const point& get_point(uint _i) const { return m_points[_i]; } inline uint fillstyle_count() const { return m_fillstyles.size(); } inline const fillstyle& get_fillstyle(uint _i) const { return m_fillstyles[_i]; } inline const edges& get_fillstyle_edges(uint _i) const { return m_filledges[_i]; } //inline uint line_style_count() const { return m_line_styles.size(); } //inline const line_style& get_line_style(uint _i) const { return m_line_styles[_i]; } //inline uint line_path_count() const { return m_line_paths.size(); } //inline const path& get_line_path(uint _i) const { return m_line_paths[_i]; } private: rect m_rect, m_edge_rect; void m_read_fill_styles(swfstream &_s, tag::type _type); void m_read_line_styles(swfstream &_s, tag::type _type); uint m_add_point(const point &_p); void m_read_shape_records(swfstream &_s, tag::type _type); points m_points; fillstyles m_fillstyles; filledges m_filledges; //std::vector<line_style> m_line_styles; //std::vector<path> m_line_paths; }; shape(const info &_info, player &_player); ~shape(); bool render() const; };
[ "my.mass.storage@f4697e32-284f-0410-9ba2-936c71724aef" ]
[ [ [ 1, 46 ] ] ]
6416d275819f8bde526d8dac866a5069235c8bd5
bfdfb7c406c318c877b7cbc43bc2dfd925185e50
/compiler/hyCFfiType.cpp
6eea352797443255fb524ad6f5ff366c3172a567
[ "MIT" ]
permissive
ysei/Hayat
74cc1e281ae6772b2a05bbeccfcf430215cb435b
b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0
refs/heads/master
2020-12-11T09:07:35.606061
2011-08-01T12:38:39
2011-08-01T12:38:39
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,601
cpp
/* -*- coding: sjis-dos; -*- */ /* * copyright 2010 FUKUZAWA Tadashi. All rights reserved. */ #include "hyCFfiType.h" #include "hyCSymbolTable.h" #include "hpInputBuffer.h" using namespace Hayat::Common; using namespace Hayat::Compiler; using namespace Hayat::Parser; FfiType::m_InitStruct FfiTypeMgr::m_ini[] = { // [0]は型指定無しの場合、又はc++クラス定義の無いユーザー定義型の場合 // [1]はNilClass又は値無しの場合 {NULL, "Value", "", "%s"}, {"NilClass", NULL, NULL, "NIL_VALUE"}, {"Bool", "bool", ".toBool()", "Value::fromBool(%s)"}, {"Int", "hys32", ".toInt()", "Value::fromInt(%s)"}, {"Float", "hyf32", ".toFloat()", "Value::fromFloat(%s)"}, {"String", "const char*", ".toString()", "Value::fromString(%s)"}, {"Object", "Object*", ".toObj()", "Value::fromObj(%s)"}, {"Symbol", "SymbolID_t", ".toSymbol()", "Value::fromSymbol(%s)"}, {"Class", "const HClass*", ".toClass()", "Value::fromClass(%s)"}, {"Array", "ValueArray*", ".toCppObj<ValueArray>(HSym_Array)", "Value::fromObj(%s->getObj())"}, {"List", "ValueList*", ".toList()", "Value::fromList(%s)"}, {"StringBuffer", "StringBuffer*", ".toCppObj<StringBuffer>(HSym_StringBuffer)", "Value::fromObj(%s->getObj())"}, }; FfiTypeMgr::FfiTypeMgr(void) : m_interfaces(0) { } void FfiTypeMgr::initialize(void) { if (m_interfaces.size() > 0) return; for (hyu32 i = 0; i < sizeof(m_ini)/sizeof(m_ini[0]); i++) { m_interfaces.add(new FfiType(m_ini[i])); } } void FfiTypeMgr::finalize(void) { hyu32 n = m_interfaces.size(); for (hyu32 i = 0; i < n; i++) { delete m_interfaces[i]; } m_interfaces.finalize(); } FfiTypeMgr::~FfiTypeMgr() { finalize(); } void FfiTypeMgr::createInterface (const char* hClassName, const char* cppClassName) { FfiType* p = find(hClassName); if (p != NULL) return; p = new FfiType(hClassName, cppClassName); m_interfaces.add(p); } FfiType* FfiTypeMgr::find(Substr_st key) { if (key.len() == 0) return m_interfaces[0]; hyu32 n = m_interfaces.size(); for (hyu32 i = 1; i < n; i++) { if (gpInp->cmpStr(key, m_interfaces[i]->name())) return m_interfaces[i]; } return NULL; } FfiType* FfiTypeMgr::find(const char* key) { if (key == NULL) return m_interfaces[0]; hyu32 n = m_interfaces.size(); for (hyu32 i = 1; i < n; i++) { if (HMD_STRCMP(key, m_interfaces[i]->name()) == 0) return m_interfaces[i]; } return NULL; } const FfiType& FfiTypeMgr::get(Substr_st key) { FfiType* p = find(key); if (p != NULL) return *p; return *m_interfaces[0]; } const FfiType& FfiTypeMgr::get(const char* key) { FfiType* p = find(key); if (p != NULL) return *p; return *m_interfaces[0]; } void* FfiType::operator new(size_t size) { HMD_DEBUG_ASSERT_EQUAL(sizeof(FfiType), size); return (void*) gMemPool->alloc(sizeof(FfiType)); } void FfiType::operator delete(void* p) { gMemPool->free(p); } FfiType::FfiType(const char* hClassName, const char* cppClassName) { static const char* TO_TMPL = ".toCppObj<%s>()"; static const char* FROM_TMPL = "Value::fromObj(Object::fromCppObj(%s))"; static const hyu32 LEN_TO_TMPL = 16; //static const hyu32 LEN_FROM_TMPL = 39; HMD_DEBUG_ASSERT(HMD_STRLEN(TO_TMPL) <= LEN_TO_TMPL); //HMD_DEBUG_ASSERT(HMD_STRLEN(FROM_TMPL) <= LEN_FROM_TMPL); hyu32 len = HMD_STRLEN(cppClassName); m_type = gMemPool->allocT<char>(len + 2); m_to = gMemPool->allocT<char>(len + LEN_TO_TMPL); m_memAllocFlag = true; m_name = hClassName; HMD_STRNCPY(m_type, cppClassName, len+1); HMD_SNPRINTF(m_to, len+LEN_TO_TMPL, TO_TMPL, m_type); // HMD_SNPRINTF(m_from, nnn+LEN_FROM_TMPL, FROM_TMPL, mmm); m_from = (char*)FROM_TMPL; m_type[len] = '*'; m_type[len+1] = '\0'; } FfiType::FfiType(const m_InitStruct& ini) { m_name = (char*) ini.name; m_type = (char*) ini.type; m_to = (char*) ini.to; m_from = (char*) ini.from; m_memAllocFlag = false; } FfiType::~FfiType() { if (m_memAllocFlag) { // m_name is not allcated gMemPool->free(m_type); gMemPool->free(m_to); m_memAllocFlag = false; } }
[ [ [ 1, 166 ] ] ]
bf004ca6198ddda52b8299d3a54878e0f4cbed53
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aosdesigner/view/DesignerActions.hpp
d7c83fe792d812ed9e8036902c681073d736e1c6
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
665
hpp
#ifndef HGUARD_AOSD_VIEW_DESIGNERACTIONS_HPP__ #define HGUARD_AOSD_VIEW_DESIGNERACTIONS_HPP__ #pragma once #include <QAction> namespace aosd { namespace view { /** Provide actions for manipulating the Designer(the application). */ class DesignerActions { public: DesignerActions(); /** Setup a full main menu. **/ void setup_menubar( QMenuBar& menubar ); private: QAction m_quit; QAction m_new_project; QAction m_open_project; QAction m_close_project; QAction m_new_sequence; QAction m_save_project; QAction m_restore_project; QAction m_new_edition; }; } } #endif
[ "klaim@localhost" ]
[ [ [ 1, 48 ] ] ]
8eb7dc2a1aa52f8fa0b5030184788ca50f8ddff9
d1dc408f6b65c4e5209041b62cd32fb5083fe140
/src/ai.cpp
94d60757b6bc1520a68571a4dc21136bbfceb2ef
[]
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
33,700
cpp
/* Dune II - The Maker Author : Stefan Hendriks Contact: [email protected] Website: http://dune2themaker.fundynamic.com 2001 - 2009 (c) code by Stefan Hendriks */ #include "include/d2tmh.h" // TODO: constructor/destructors // cAIPlayer functions void cAIPlayer::init(int iID) { ID = iID; // SKIRMISH RELATED SETTINGS if (iID > 1) bPlaying=false; else bPlaying=true; iUnits=1; iCheckingPlaceStructure=-1; // -- END // iBuildingUnit[TRIKE] > 0 = its building a trike (progress!) memset(iBuildingUnit, -1, sizeof(iBuildingUnit)); memset(iBuildingStructure, -1, sizeof(iBuildingStructure)); memset(TIMER_BuildUnit, -1, sizeof(TIMER_BuildUnit)); memset(TIMER_BuildStructure, -1, sizeof(TIMER_BuildStructure)); TIMER_attack=-(900 + rnd(200)); // TIMER_attack=-50; TIMER_BuildUnits=-500; // give player advantage to build his stuff first, before computer grows his army TIMER_harv=200; TIMER_repair=500; } void cAIPlayer::BUILD_STRUCTURE(int iStrucType) { for (int i=0; i < MAX_STRUCTURETYPES; i++) if (iBuildingStructure[i] > -1) { // already building return; } // not building // check if its allowed at all if (player[ID].iStructures[CONSTYARD] < 1) return; if (player[ID].credits < structures[iStrucType].cost) return; // cannot buy iBuildingStructure[iStrucType]=0; TIMER_BuildStructure[iStrucType]=0; // start building player[ID].credits-= structures[iStrucType].cost; if (DEBUGGING) { logbook("Building STRUCTURE: "); logbook(structures[iStrucType].name); } } void cAIPlayer::BUILD_UNIT(int iUnitType) { // Fix up house mixtures if (player[ID].getHouse() == HARKONNEN || player[ID].getHouse() == SARDAUKAR) { if (iUnitType == INFANTRY) iUnitType = TROOPERS; if (iUnitType == SOLDIER) iUnitType = TROOPER; if (iUnitType == TRIKE) iUnitType = QUAD; } // In mission 9 there are only WOR's, so make a special hack hack for that ;) if (game.iMission >= 8) { if (iUnitType == INFANTRY) iUnitType = TROOPERS; if (iUnitType == SOLDIER) iUnitType = TROOPER; } if (player[ID].getHouse() == ORDOS) { if (iUnitType == TRIKE) iUnitType = RAIDER; } bool bAllowed = AI_UNITSTRUCTURETYPE(ID, iUnitType); if (bAllowed == false) return; // do not go further // when building a tank, etc, check if we do not already build bool bAlreadyBuilding=false; for (int i=0; i < MAX_UNITTYPES; i++) { // when building a quad if (iUnitType == QUAD || iUnitType == TRIKE || iUnitType == RAIDER) { // the same if (i == iUnitType) if (iBuildingUnit[i] > -1) bAlreadyBuilding=true; } // when building a tank or something if (iUnitType == TANK || iUnitType == LAUNCHER || iUnitType == SIEGETANK || iUnitType == SONICTANK || iUnitType == DEVASTATOR || iUnitType == HARVESTER) { if (i == iUnitType) if (iBuildingUnit[i] > -1) bAlreadyBuilding=true; } // when building a carryall if (iUnitType == CARRYALL || iUnitType == ORNITHOPTER) { if (i == iUnitType) if (iBuildingUnit[i] > -1) bAlreadyBuilding=true; } } //if (bAlreadyBuilding) // return; // Now build it iBuildingUnit[iUnitType]=0; // start building! player[ID].credits -= units[iUnitType].cost; // pay for it if (DEBUGGING) { logbook("Building UNIT: "); logbook(units[iUnitType].name); } } void cAIPlayer::think_building() { if (ID == 0) return; // human player does not think /* structure building; when building completed, search for a spot and place it! */ for (int i=0; i < MAX_STRUCTURETYPES; i++) { if (iBuildingStructure[i] > -1) { int iTimerCap=35; // was 35 if (DEBUGGING) iTimerCap=7; // the more constyards iTimerCap /= (1+(player[ID].iStructures[CONSTYARD]/2)); TIMER_BuildStructure[i]++; if (TIMER_BuildStructure[i] > iTimerCap) { iBuildingStructure[i]++; TIMER_BuildStructure[i]=0; } if (iBuildingStructure[i] >= structures[i].build_time) { // find place to place structure if (game.bSkirmish) { int iCll=iPlaceStructureCell(i); if (iCll > -1) { iBuildingStructure[i]=-1; TIMER_BuildStructure[i]=-1; cStructureFactory::getInstance()->createStructure(iCll, i, ID, 100); } else { // cannot place structure now, this sucks big time. return money iBuildingStructure[i]=-1; TIMER_BuildStructure[i]=0; player[ID].credits+= structures[i].cost; } } } // now break the loop, as we may only do one building at a time! break; } } /* unit building */ for (int i=0; i < MAX_UNITTYPES; i++) { if (iBuildingUnit[i] > -1) { int iStrucType = AI_STRUCTYPE(i); TIMER_BuildUnit[i]++; int iTimerCap=35; iTimerCap /= (1+(player[ID].iStructures[iStrucType]/2)); cPlayerDifficultySettings * difficultySettings = player[ID].getDifficultySettings(); iTimerCap = difficultySettings->getBuildSpeed(iTimerCap); if (TIMER_BuildUnit[i] > iTimerCap) { iBuildingUnit[i]++; TIMER_BuildUnit[i]=0; // set to 0 again } if (iBuildingUnit[i] >= units[i].build_time) { //logbook("DONE BUILDING"); // produce now int iStr = player[ID].iPrimaryBuilding[iStrucType]; // no primary building yet, assign one if (iStr < 0) { // TODO: remove/rewrite! This has nothing to do with primary stuff and such.. iStr = structureUtils.findStructureToDeployUnit( &player[ID], iStrucType); // iStr = FIND_PRIMARY_BUILDING(iStrucType, ID); } if (iStr > -1) { int iProducedUnit=-1; if (structure[iStr]) { if (structure[iStr]->iFreeAround() -1) { int iSpot = structure[iStr]->iFreeAround(); player[ID].iPrimaryBuilding[iStrucType] = iStr; structure[iStr]->setAnimating(true); // animate iProducedUnit=UNIT_CREATE(iSpot, i, ID, false); } else { int iNewStr = structureUtils.findStructureToDeployUnit( &player[ID], iStrucType); // assign new primary if (iNewStr != iStr && iNewStr > -1) { int iSpot = structure[iNewStr]->iFreeAround(); player[ID].iPrimaryBuilding[iStrucType] = iNewStr; structure[iNewStr]->setAnimating(true); // animate iProducedUnit=UNIT_CREATE(iSpot, i, ID, false); } else { // nothing found, deliver the unit as is. } } } else { player[ID].iPrimaryBuilding[iStrucType]=-1; } // produce iBuildingUnit[i] = -1; // Assign to team (for AI attack purposes) unit[iProducedUnit].iGroup=rnd(3)+1; } else { // deliver unit by carryall for (int s=0; s < MAX_STRUCTURES; s++) { if (structure[s]) if (structure[s]->getOwner() == ID) if (structure[s]->getType() == iStrucType) { REINFORCE(ID, i, structure[s]->getCell(), -1); } } // produce iBuildingUnit[i] = -1; } } } } // END OF THINK BUILDING } void cAIPlayer::think_harvester() { if (TIMER_harv > 0) { TIMER_harv--; return; } TIMER_harv=200; // think about spice blooms int iBlooms=-1; for (int c=0; c < MAX_CELLS; c++) if (map.cell[c].type == TERRAIN_BLOOM) iBlooms++; // When no blooms are detected, we must 'spawn' one if (iBlooms < 3) { int iCll = rnd(MAX_CELLS); if (map.cell[iCll].type == TERRAIN_SAND) { // create bloom mapEditor.createCell(iCll, TERRAIN_BLOOM, 0); } } else { if (rnd(100) < 15) { // if we got a unit to spare (something light), we can blow it up by walking over it // with a soldier or something int iUnit=-1; int iDist=9999; int iBloom = CLOSE_SPICE_BLOOM(-1); for (int i=0; i < MAX_UNITS; i++) { if (unit[i].isValid()){ if (unit[i].iPlayer > 0 && unit[i].iPlayer == ID && unit[i].iAction == ACTION_GUARD) { if (units[unit[i].iType].infantry) { int d = ABS_length( iCellGiveX(iBloom), iCellGiveY(iBloom), iCellGiveX(unit[i].iCell), iCellGiveY(unit[i].iCell)); if (d < iDist) { iUnit = i; iDist = d; } } } } } if (iUnit > -1) { // shoot spice bloom UNIT_ORDER_ATTACK(iUnit, iBloom,-1, -1, iBloom); } else BUILD_UNIT(SOLDIER); } } bool bFoundHarvester=false; if (player[ID].iStructures[REFINERY] > 0) { bFoundHarvester=false; for (int j = 0; j < MAX_UNITS; j++) { if (unit[j].isValid()) if (unit[j].iPlayer == ID) { if (unit[j].iType == HARVESTER) { bFoundHarvester=true; break; } else if (unit[j].iType == CARRYALL) { if (unit[j].iUnitID > -1) if (unit[unit[j].iUnitID].iType == HARVESTER) { bFoundHarvester=true; break; } if (unit[j].iNewUnitType == HARVESTER) { bFoundHarvester=true; break; } } } } if (bFoundHarvester == false) { for (int k=0; k < MAX_STRUCTURES; k++) { if (structure[k]) if (structure[k]->getOwner() == ID) if (structure[k]->getType() == REFINERY) { REINFORCE(ID, HARVESTER, structure[k]->getCell(), -1); } } } } // has refinery } void cAIPlayer::think() { think_building(); // not time yet to think if (player[ID].TIMER_think < 10) { player[ID].TIMER_think++; return; } player[ID].TIMER_think = 0; // think about fair harvester stuff think_harvester(); if (ID == 0) return; // we do not think further // depening on player, do thinking if (ID == AI_WORM) { if (rnd(100) < 25) think_worm(); return; } // Now think about building stuff etc think_buildbase(); think_buildarmy(); think_attack(); } void cAIPlayer::think_repair() { if (TIMER_repair > 0) { TIMER_repair--; return; } TIMER_repair=500; // next timed interval to think about this... // check if we must repair, only if we have a repair structure ofcourse // and we have some money to spare for repairs if (player[ID].iStructures[REPAIR] > 0 && player[ID].credits > 250) { // yes, we can repair for (int i=0; i < MAX_UNITS; i++) { if (unit[i].isValid()) { if (unit[i].iPlayer == ID) { if (unit[i].iHitPoints < units[unit[i].iType].hp) { // head off to repair cStructureUtils structureUtils; int iNewID = structureUtils.findClosestStructureTypeToCell(unit[i].iCell, REPAIR, &player[ID]); if (iNewID > -1) { int iCarry = CARRYALL_TRANSFER(i, structure[iNewID]->getCell() + 2); if (iCarry > -1) { // yehaw we will be picked up! unit[i].TIMER_movewait = 100; unit[i].TIMER_thinkwait = 100; } else { UNIT_ORDER_MOVE(i, structure[iNewID]->getCell()); } unit[i].iStructureID = iNewID; unit[i].iGoalCell = structure[iNewID]->getCell(); } } } } } // FOR } // check if any structures where breaking down due decay } void cAIPlayer::think_attack() { if (TIMER_attack < 0) { TIMER_attack++; think_repair(); return; } TIMER_attack = -(rnd(600)+100); // TIMER_attack=-50; // find anyone with a specific random group number and send it to attack the player (focus cell) int iAmount=3 + rnd(8); int iTarget=-1; bool bUnit=false; int iGroup=rnd(3)+1; bool bInfantryOnly=false; int iAttackPlayer=0; if (game.bSkirmish) { // skirmish games will make the ai a bit more agressive! iAmount+=3 + rnd(7); // check what players are playing int iPl[5]; int iPlID=0; memset(iPl, -1, sizeof(iPl)); for (int p=0; p < AI_WORM; p++) { if (p != ID) { bool bOk=false; if (p == 0) bOk=true; if (p > 1 && aiplayer[p].bPlaying) bOk=true; if (player[p].iTeam != player[ID].iTeam) { iPl[iPlID] = p; iPlID++; } } } iAttackPlayer=iPl[rnd(iPlID)]; if (DEBUGGING) { char msg[255]; sprintf(msg, "Attacking player id %d", iAttackPlayer); logbook(msg); } } // only when ai has a wor/barracks to regenerate his troops, send off infantry sometimes. if (player[ID].iStructures[WOR] > 0 || player[ID].iStructures[BARRACKS]) if (rnd(100) < 30) { bInfantryOnly=true; iAmount=10; } if (rnd(100) < 50) { iTarget = AI_RANDOM_STRUCTURE_TARGET(ID, iAttackPlayer); if (iTarget < 0) { iTarget = AI_RANDOM_UNIT_TARGET(ID, iAttackPlayer); bUnit=true; } } else { iTarget = AI_RANDOM_UNIT_TARGET(ID,iAttackPlayer); bUnit=true; if (iTarget < 0) { iTarget = AI_RANDOM_STRUCTURE_TARGET(ID, iAttackPlayer); bUnit=false; } } if (iTarget < 0) { if (DEBUGGING) logbook("No target!"); return; } // make up the balance int iWe=0; int iThem=0; for (int i=0; i < MAX_UNITS; i++) { if (unit[i].isValid()) if (unit[i].iPlayer == 0) { if (unit[i].iType != HARVESTER && unit[i].iType != CARRYALL) iThem++; } else { if (unit[i].iType != HARVESTER && unit[i].iType != CARRYALL) iWe++; } } // When WE do not even match THEM, we wait until we have build more if (iWe <= iThem && rnd(100) < 50) { if (DEBUGGING) logbook("AI: Decission to wait, no use to attack opponent which is equal or stronger then AI"); TIMER_attack = -250; return; } int iUnits=0; for (int i=0; i < MAX_UNITS; i++) { if (unit[i].isValid()) if (unit[i].iPlayer == ID && unit[i].iType != HARVESTER && unit[i].iType != CARRYALL) { if (bInfantryOnly == false) { if (unit[i].iGroup == iGroup) { if (bUnit) UNIT_ORDER_ATTACK(i, unit[iTarget].iCell, iTarget, -1, -1); else UNIT_ORDER_ATTACK(i, structure[iTarget]->getCell(), -1, iTarget, -1); iUnits++; } } else { if (units[unit[i].iType].infantry) { if (bUnit) UNIT_ORDER_ATTACK(i, unit[iTarget].iCell, iTarget, -1, -1); else UNIT_ORDER_ATTACK(i, structure[iTarget]->getCell(), -1, iTarget, -1); } } } } // get remaining units (not always) if (iUnits < iAmount && rnd(100) < 10 && player[ID].credits > 700) { for (int i=0; i < MAX_UNITS; i++) { if (unit[i].isValid()) if (unit[i].iPlayer == ID) { if (unit[i].iType != HARVESTER && unit[i].iType != CARRYALL && unit[i].iType != FRIGATE && unit[i].iAction == ACTION_GUARD) { if (bUnit) UNIT_ORDER_ATTACK(i, unit[iTarget].iCell, iTarget, -1, -1); else UNIT_ORDER_ATTACK(i, structure[iTarget]->getCell(), -1, iTarget, -1); iUnits++; if (iUnits >= iAmount) break; } } } } } void cAIPlayer::think_buildarmy() { // prevent human player thinking if (ID == 0) return; // do not build for human! :) if (TIMER_BuildUnits < 3) { TIMER_BuildUnits++; return; } /* if (game.bSkirmish) { if (player[ID].credits < 300) return; }*/ TIMER_BuildUnits=0; // Depending on the mission/tech level, try to build stuff int iMission = game.iMission; int iChance = 10; if (player[ID].getHouse() == HARKONNEN || player[ID].getHouse() == SARDAUKAR) { if (iMission <= 2) { iChance=50; } else { iChance=10; } } else { // non trooper house(s) if (iMission <= 2) { iChance=20; } } // Skirmish override if (game.bSkirmish) { iChance=10; } if (iMission > 1 && rnd(100) < iChance) { if (player[ID].credits > units[INFANTRY].cost) { BUILD_UNIT(INFANTRY); // (INFANTRY->TROOPERS CONVERSION IN FUNCTION) } else BUILD_UNIT(SOLDIER); // (SOLDIER->TROOPER CONVERSION IN FUNCTION) } iChance=50; // low chance on buying the higher the mission if (iMission > 4) iChance = 30; if (iMission > 6) iChance = 20; if (iMission > 7) iChance = 10; if (iMission > 8) iChance = 5; // Skirmish override if (game.bSkirmish) iChance=7; // build quads / trikes if (iMission > 2 && rnd(100) < iChance) { if (player[ID].credits > units[QUAD].cost) { BUILD_UNIT(QUAD); } else if (player[ID].credits > units[TRIKE].cost) { BUILD_UNIT(TRIKE); } } int iHarvs = 0; // harvesters int iCarrys= 0; // carryalls if (iMission > 3) { // how many harvesters do we own? for (int i=0; i < MAX_UNITS; i++) if (unit[i].isValid()) if (unit[i].iPlayer == ID && unit[i].iType == HARVESTER) iHarvs++; if (iHarvs < player[ID].iStructures[REFINERY]) { if (player[ID].credits > units[HARVESTER].cost) BUILD_UNIT(HARVESTER); // build harvester } else if (iHarvs >= player[ID].iStructures[REFINERY]) { // enough harvesters , try to get ratio 2 harvs - 1 refinery if (iHarvs < (player[ID].iStructures[REFINERY] * 2)) if (rnd(100) < 30) BUILD_UNIT(HARVESTER); } } // ability to build carryalls if (iMission >= 5) { if (player[ID].credits > units[CARRYALL].cost) { for (int i=0; i < MAX_UNITS; i++) if (unit[i].isValid()) if (unit[i].iPlayer == ID && unit[i].iType == CARRYALL) iCarrys++; int iLimit = 1; if (iHarvs > 1 ) iLimit = iHarvs / 2; if (iCarrys < iLimit) { // randomly, build if (rnd(100) < 50) // it is pretty wise to do so, so high chance of doing so... BUILD_UNIT(CARRYALL); } } } if (iMission > 6) { if (player[ID].getHouse() == ATREIDES) { if (player[ID].credits > units[ORNITHOPTER].cost) { if (rnd(100) < 15) { BUILD_UNIT(ORNITHOPTER); } } } } if (iMission >= 8 || game.bSkirmish) { int iSpecial = DEVASTATOR; if (player[ID].getHouse() == ATREIDES) { iSpecial = SONICTANK; } if (player[ID].getHouse() == ORDOS) { iSpecial = DEVIATOR; } if (player[ID].credits > units[iSpecial].cost) { BUILD_UNIT(iSpecial); } if (player[ID].credits > units[SIEGETANK].cost) { // enough to buy launcher , tank int nr = rnd(100); if (nr < 30) BUILD_UNIT(LAUNCHER); else if (nr > 30 && nr < 60) BUILD_UNIT(TANK); else if (nr > 60) BUILD_UNIT(SIEGETANK); } else if (player[ID].credits > units[LAUNCHER].cost) { if (rnd(100) < 50) BUILD_UNIT(LAUNCHER); else BUILD_UNIT(TANK); } else if (player[ID].credits > units[TANK].cost) { BUILD_UNIT(TANK); } } if (iMission == 4 && rnd(100) < 70) { if (player[ID].credits > units[TANK].cost) BUILD_UNIT(TANK); } if (iMission == 5) { if (player[ID].credits > units[LAUNCHER].cost) { // enough to buy launcher , tank if (rnd(100) < 50) BUILD_UNIT(LAUNCHER); else BUILD_UNIT(TANK); } else if (player[ID].credits > units[TANK].cost) { BUILD_UNIT(TANK); } } if (iMission == 6) { // when enough money, 50/50 on siege/launcher. Else just buy a tank or do nothing if (player[ID].credits > units[SIEGETANK].cost) { if (rnd(100) < 50) BUILD_UNIT(SIEGETANK); else BUILD_UNIT(LAUNCHER); } else if (player[ID].credits > units[TANK].cost) { if (rnd(100) < 30) BUILD_UNIT(TANK); // buy a normal tank in mission 6 } } if (iMission == 7) { // when enough money, 50/50 on siege/launcher. Else just buy a tank or do nothing if (player[ID].credits > units[SIEGETANK].cost) { if (rnd(100) < 50) BUILD_UNIT(SIEGETANK); else BUILD_UNIT(LAUNCHER); } else if (player[ID].credits > units[TANK].cost) { if (rnd(100) < 30) BUILD_UNIT(TANK); // buy a normal tank in mission 6 } } } void cAIPlayer::think_buildbase() { if (game.bSkirmish) { if (player[ID].iStructures[CONSTYARD] > 0) { // already building for (int i=0; i < MAX_STRUCTURETYPES; i++) if (iBuildingStructure[i] > -1) { // already building return; } // when no windtrap, then build one (or when low power) if (player[ID].iStructures[WINDTRAP] < 1 || player[ID].bEnoughPower() == false) { BUILD_STRUCTURE(WINDTRAP); return; } // build refinery if (player[ID].iStructures[REFINERY] < 1) { BUILD_STRUCTURE(REFINERY); return; } // build wor / barracks if (player[ID].getHouse() == ATREIDES) { if (player[ID].iStructures[BARRACKS] < 1) { BUILD_STRUCTURE(BARRACKS); return; } } else { if (player[ID].iStructures[WOR] < 1) { BUILD_STRUCTURE(WOR); return; } } if (player[ID].iStructures[RADAR] < 1) { BUILD_STRUCTURE(RADAR); return; } // from here, we can build turrets & rocket turrets if (player[ID].iStructures[LIGHTFACTORY] < 1) { BUILD_STRUCTURE(LIGHTFACTORY); return; } if (player[ID].iStructures[HEAVYFACTORY] < 1) { BUILD_STRUCTURE(HEAVYFACTORY); return; } // when mission is lower then 5, build normal turrets if (game.iMission <= 5) { if (player[ID].iStructures[TURRET] < 3) { BUILD_STRUCTURE(TURRET); return; } } if (game.iMission >= 6) { if (player[ID].iStructures[RTURRET] < 3) { BUILD_STRUCTURE(RTURRET); return; } } // build refinery if (player[ID].iStructures[REFINERY] < 2) { BUILD_STRUCTURE(REFINERY); return; } if (player[ID].iStructures[HIGHTECH] < 1) { BUILD_STRUCTURE(HIGHTECH); return; } if (player[ID].iStructures[REPAIR] < 1) { BUILD_STRUCTURE(REPAIR); return; } if (player[ID].iStructures[PALACE] < 1) { BUILD_STRUCTURE(PALACE); return; } if (game.iMission >= 6) { if (player[ID].iStructures[RTURRET] < 9) { BUILD_STRUCTURE(RTURRET); return; } } if (player[ID].iStructures[STARPORT] < 1) { BUILD_STRUCTURE(STARPORT); return; } } } else { // rebuild only destroyed stuff } } void cAIPlayer::think_worm() { // loop through all its worms and move them around for (int i=0; i < MAX_UNITS; i++) if (unit[i].isValid()) if (unit[i].iType == SANDWORM && unit[i].iPlayer == ID) { // when on guard if (unit[i].iAction == ACTION_GUARD) { // find new spot to go to for (int iTries=0; iTries < 10; iTries++) { int iMoveTo = rnd(MAX_CELLS); if (map.cell[iMoveTo].type == TERRAIN_SAND || map.cell[iMoveTo].type == TERRAIN_HILL || map.cell[iMoveTo].type == TERRAIN_SPICE || map.cell[iMoveTo].type == TERRAIN_SPICEHILL) { logbook("Order move #4"); UNIT_ORDER_MOVE(i, iMoveTo); break; } } } } } ///////////////////////////////////////////////// int AI_STRUCTYPE(int iUnitType) { // CHECK FOR BUILDING int iStrucType=HEAVYFACTORY; // what do we need to build this unit? // Default = heavyfactory, so do a check if its NOT. // light vehicles if (iUnitType == TRIKE || iUnitType == RAIDER || iUnitType == QUAD) iStrucType =LIGHTFACTORY; // soldiers and troopers if (iUnitType == INFANTRY || iUnitType == SOLDIER) iStrucType = BARRACKS; if (iUnitType == TROOPER || iUnitType == TROOPERS) iStrucType = WOR; // airborn stuff if (iUnitType == CARRYALL || iUnitType == ORNITHOPTER) iStrucType = HIGHTECH; return iStrucType; } // Helper functions to keep fair play: bool AI_UNITSTRUCTURETYPE(int iPlayer, int iUnitType) { // This function will do a check what kind of structure is needed to build the unittype // Basicly the function returns true when its valid to build the unittype, or false // when its impossible (due no structure, money, etc) // Once known, a check will be made to see if the AI has a structure to produce that // unit type. If not, it will return false. // CHECK 1: Do we have the money? if (player[iPlayer].credits < units[iUnitType].cost) return false; // NOPE // CHECK 2: Aren't we building this already? if (aiplayer[iPlayer].iBuildingUnit[iUnitType] >= 0) return false; int iStrucType = AI_STRUCTYPE(iUnitType); // Do the reality-check, do we have the building needed? if (player[iPlayer].iStructures[iStrucType] < 1) return false; // we do not have the building // WE MAY BUILD IT! return true; } int AI_RANDOM_UNIT_TARGET(int iPlayer, int iAttackPlayer) { // Randomly assemble list, and then pick one int iTargets[100]; memset(iTargets, -1, sizeof(iTargets)); int iT=0; for (int i=0; i < MAX_UNITS; i++) if (unit[i].isValid()) if (unit[i].iPlayer == iAttackPlayer) { if (DEBUGGING) { char msg[255]; sprintf(msg, "AI %d (House %d) -> Visible = %d", iPlayer, player[iPlayer].getHouse(), mapUtils->isCellVisibleForPlayerId(iPlayer, unit[i].iCell)); logbook(msg); } if (mapUtils->isCellVisibleForPlayerId(iPlayer, unit[i].iCell) || game.bSkirmish) { iTargets[iT] = i; iT++; if (iT > 99) break; } } if (DEBUGGING) { char msg[255]; sprintf(msg, "Targets %d", iT); logbook(msg); } return (iTargets[rnd(iT)]); } int AI_RANDOM_STRUCTURE_TARGET(int iPlayer, int iAttackPlayer) { // Randomly assemble list, and then pick one int iTargets[100]; memset(iTargets, -1, sizeof(iTargets)); int iT=0; for (int i=0; i < MAX_STRUCTURES; i++) if (structure[i]) if (structure[i]->getOwner() == iAttackPlayer) if (mapUtils->isCellVisibleForPlayerId(iPlayer, structure[i]->getCell()) || game.bSkirmish) { iTargets[iT] = i; iT++; if (iT > 99) break; } if (DEBUGGING) { char msg[255]; sprintf(msg, "STR] Targets %d", iT); logbook(msg); } return (iTargets[rnd(iT)]); } void cAIPlayer::think_repair_structure(cAbstractStructure *struc) { // think of repairing, only when it is not being repaired yet. if (!struc->isRepairing()) { // when ai has a lot of money, repair even faster if (player[struc->getOwner()].credits > 1000) { if (struc->getHitPoints() < (structures[struc->getType()].hp)) { struc->setRepairing(true); } } else { // AUTO-REPAIR BY AI if (struc->getHitPoints() < (structures[struc->getType()].hp/2)) { struc->setRepairing(true); } } } } int cAIPlayer::iPlaceStructureCell(int iType) { // loop through all structures, and try to place structure // next to them: // ww // ss // ss // s = structure: // w = start point (+ width of structure). // so starting at : x - width , y - height. // ending at : x + width of structure + width of type // ... : y + height of s + height of type int iWidth=structures[iType].bmp_width/32; int iHeight=structures[iType].bmp_height/32; int iDistance=0; int iGoodCells[50]; // remember 50 possible locations int iGoodCellID=0; // clear out table of good locations memset(iGoodCells, -1, sizeof(iGoodCells)); bool bGood=false; if (iCheckingPlaceStructure < 0) iCheckingPlaceStructure=0; if (iCheckingPlaceStructure >= MAX_STRUCTURES) iCheckingPlaceStructure=0; // loop through structures int i; for (i=iCheckingPlaceStructure; i < iCheckingPlaceStructure+2; i++) { // just in case if (i >= MAX_STRUCTURES) break; // valid if (structure[i]) { // same owner if (structure[i]->getOwner() == ID) { // scan around int iStartX=iCellGiveX(structure[i]->getCell()); int iStartY=iCellGiveY(structure[i]->getCell()); int iEndX = iStartX + (structures[structure[i]->getType()].bmp_width/32) + 1; int iEndY = iStartY + (structures[structure[i]->getType()].bmp_height/32) + 1; iStartX -= iWidth; iStartY -= iHeight; // do not go out of boundries FIX_POS(iStartX, iStartY); FIX_POS(iEndX, iEndY); for (int sx=iStartX; sx < iEndX; sx++) { for (int sy=iStartY; sy < iEndY; sy++) { int r = cStructureFactory::getInstance()->getSlabStatus(iCellMake(sx, sy), iType, -1); if (r > -2) { if (iType != TURRET && iType != RTURRET) { // for turrets, the most far counts bGood=true; iGoodCells[iGoodCellID] = iCellMake(sx, sy); iGoodCellID++; return iCellMake(sx, sy); } else { bGood=true; int iDist=ABS_length(sx, sy, iCellGiveX(player[ID].focus_cell),iCellGiveY(player[ID].focus_cell)); if ((iDist > iDistance) || (iDist == iDistance)) { iDistance=iDist; iGoodCells[iGoodCellID] = iCellMake(sx, sy); iGoodCellID++; return iCellMake(sx, sy); } } } } } // sx } // same player } // valid structure } // not turret if (bGood) { // STRUCTURE_CREATE(iGoodCells[rnd(iGoodCellID)], iType, structures[iType].hp, ID); logbook("FOUND CELL TO PLACE"); iCheckingPlaceStructure=-1; return (iGoodCells[rnd(iGoodCellID)]); } iCheckingPlaceStructure=i; player[ID].TIMER_think-=5; return -1; }
[ "stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151" ]
[ [ [ 1, 1409 ] ] ]
04b21a5d6d6e80620b716a97a060bf70c1076a6e
b4d726a0321649f907923cc57323942a1e45915b
/CODE/NETWORK/MULTI.CPP
af946e856e091a3076dcfbeae5fb85c56363a826
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
65,506
cpp
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ /* * $Logfile: /Freespace2/code/Network/Multi.cpp $ * $Revision: 1.1.1.1 $ * $Date: 2004/08/13 22:47:42 $ * $Author: Spearhawk $ * * C file that contains high-level multiplayer functions * * $Log: MULTI.CPP,v $ * Revision 1.1.1.1 2004/08/13 22:47:42 Spearhawk * no message * * Revision 1.1.1.1 2004/08/13 21:21:02 Darkhill * no message * * Revision 2.18 2004/03/31 05:42:27 Goober5000 * got rid of all those nasty warnings from xlocale and so forth; also added comments * for #pragma warning disable to indicate the message being disabled * --Goober5000 * * Revision 2.17 2004/03/09 17:59:01 Kazan * Disabled multithreaded TCP_Socket in favor of safer single threaded * FS2NetD doesn't kill the game on connection failure now - just gives warning message and effectively dsiables itself until they try to connect again * * Revision 2.16 2004/03/09 00:02:16 Kazan * more fs2netd stuff * * Revision 2.15 2004/03/08 22:02:39 Kazan * Lobby GUI screen restored * * Revision 2.14 2004/03/08 15:06:24 Kazan * Did, undo * * Revision 2.13 2004/03/05 09:02:02 Goober5000 * Uber pass at reducing #includes * --Goober5000 * * Revision 2.12 2003/11/13 03:59:54 Kazan * PXO_SID changed from unsigned to signed * * Revision 2.11 2003/11/11 02:15:45 Goober5000 * ubercommit - basically spelling and language fixes with some additional * warnings disabled * --Goober5000 * * Revision 2.10 2003/11/06 20:22:13 Kazan * slight change to .dsp - leave the release target as fs2_open_r.exe already * added myself to credit * killed some of the stupid warnings (including doing some casting and commenting out unused vars in the graphics modules) * Release builds should have warning level set no higher than 2 (default is 1) * Why are we getting warning's about function selected for inline expansion... (killing them with warning disables) * FS2_SPEECH was not defined (source file doesn't appear to capture preproc defines correctly either) * * Revision 2.9 2003/10/04 22:42:22 Kazan * fs2netd now TCP * * Revision 2.8 2003/09/25 21:12:24 Kazan * ##Kazan## FS2NetD Completed! Just needs some thorough bug checking (i don't think there are any serious bugs) * Also D3D8 Screenshots work now. * * Revision 2.7 2003/09/24 19:35:58 Kazan * ##KAZAN## FS2 Open PXO --- W00t! Stats Storage, everything but table verification completed! * * Revision 2.6 2003/09/23 02:42:54 Kazan * ##KAZAN## - FS2NetD Support! (FS2 Open PXO) -- Game Server Listing, and mission validation completed - stats storing to come - needs fs2open_pxo.cfg file [VP-able] * * Revision 2.5 2003/09/05 04:25:28 Goober5000 * well, let's see here... * * * persistent variables * * rotating gun barrels * * positive/negative numbers fixed * * sexps to trigger whether the player is controlled by AI * * sexp for force a subspace jump * * I think that's it :) * --Goober5000 * * Revision 2.4 2002/12/24 07:42:29 Goober5000 * added change-ai-class and is-ai-class, and I think I may also have nailed the * is-iff bug; did some other bug hunting as well * --Goober5000 * * Revision 2.3 2002/12/17 02:18:40 Goober5000 * added functionality and fixed a few things with cargo being revealed and hidden in preparation for the set-scanned and set-unscanned sexp commit * --Goober5000 * * Revision 2.2 2002/08/01 01:41:07 penguin * The big include file move * * Revision 2.1 2002/07/22 01:22:25 penguin * Linux port -- added NO_STANDALONE ifdefs * * Revision 2.0 2002/06/03 04:02:25 penguin * Warpcore CVS sync * * Revision 1.2 2002/05/13 21:09:28 mharris * I think the last of the networking code has ifndef NO_NETWORK... * * Revision 1.1 2002/05/02 18:03:10 mharris * Initial checkin - converted filenames and includes to lower case * * * 47 9/15/99 1:45a Dave * Don't init joystick on standalone. Fixed campaign mode on standalone. * Fixed no-score-report problem in TvT * * 46 8/24/99 1:49a Dave * Fixed client-side afterburner stuttering. Added checkbox for no version * checking on PXO join. Made button info passing more friendly between * client and server. * * 45 8/22/99 5:53p Dave * Scoring fixes. Added self destruct key. Put callsigns in the logfile * instead of ship designations for multiplayer players. * * 44 8/22/99 1:19p Dave * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in * which d3d cards are detected. * * 43 8/19/99 10:59a Dave * Packet loss detection. * * 42 8/16/99 4:05p Dave * Big honking checkin. * * 41 8/06/99 12:34a Dave * Be more careful about resetting timestamps. * * 40 8/04/99 2:24a Dave * Fixed escort gauge ordering for dogfight. * * 39 7/26/99 5:50p Dave * Revised ingame join. Better? We'll see.... * * 38 7/08/99 10:53a Dave * New multiplayer interpolation scheme. Not 100% done yet, but still * better than the old way. * * 37 7/06/99 4:24p Dave * Mid-level checkin. Starting on some potentially cool multiplayer * smoothness crap. * * 36 7/03/99 5:50p Dave * Make rotated bitmaps draw properly in padlock views. * * 35 6/21/99 7:24p Dave * netplayer pain packet. Added type E unmoving beams. * * 34 6/07/99 9:51p Dave * Consolidated all multiplayer ports into one. * * 33 6/04/99 9:52a Dave * Fixed some rendering problems. * * 32 5/22/99 6:05p Dave * Fixed a few localization # problems. * * 31 5/22/99 5:35p Dave * Debrief and chatbox screens. Fixed small hi-res HUD bug. * * 30 5/14/99 1:59p Andsager * Multiplayer message for subsystem cargo revealed. * * 29 4/29/99 2:29p Dave * Made flak work much better in multiplayer. * * 28 4/28/99 11:13p Dave * Temporary checkin of artillery code. * * 27 4/25/99 7:43p Dave * Misc small bug fixes. Made sun draw properly. * * 26 4/25/99 3:02p Dave * Build defines for the E3 build. * * 25 4/12/99 10:07p Dave * Made network startup more forgiving. Added checkmarks to dogfight * screen for players who hit commit. * * 24 4/09/99 2:21p Dave * Multiplayer beta stuff. CD checking. * * 23 3/19/99 9:51a Dave * Checkin to repair massive source safe crash. Also added support for * pof-style nebulae, and some new weapons code. * * 23 3/11/99 5:53p Dave * More network optimization. Spliced in Dell OEM planet bitmap crap. * * 22 3/10/99 6:50p Dave * Changed the way we buffer packets for all clients. Optimized turret * fired packets. Did some weapon firing optimizations. * * 21 3/09/99 6:24p Dave * More work on object update revamping. Identified several sources of * unnecessary bandwidth. * * 20 3/08/99 7:03p Dave * First run of new object update system. Looks very promising. * * 19 3/02/99 4:40p Jasons * Be more careful when calling server-lost-contact popup (make sure other * popups aren't active) * * 18 3/01/99 7:39p Dave * Added prioritizing ship respawns. Also fixed respawns in TvT so teams * don't mix respawn points. * * 17 2/23/99 2:29p Dave * First run of oldschool dogfight mode. * * 16 2/19/99 2:55p Dave * Temporary checking to report the winner of a squad war match. * * 15 2/17/99 2:10p Dave * First full run of squad war. All freespace and tracker side stuff * works. * * 14 2/12/99 6:16p Dave * Pre-mission Squad War code is 95% done. * * 13 2/11/99 3:08p Dave * PXO refresh button. Very preliminary squad war support. * * 12 1/14/99 12:48a Dave * Todo list bug fixes. Made a pass at putting briefing icons back into * FRED. Sort of works :( * * 11 1/12/99 5:45p Dave * Moved weapon pipeline in multiplayer to almost exclusively client side. * Very good results. Bandwidth goes down, playability goes up for crappy * connections. Fixed object update problem for ship subsystems. * * 10 12/14/98 12:13p Dave * Spiffed up xfer system a bit. Put in support for squad logo file xfer. * Need to test now. * * 9 12/03/98 5:22p Dave * Ported over Freespace 1 multiplayer ships.tbl and weapons.tbl * checksumming. * * 8 11/19/98 4:19p Dave * Put IPX sockets back in psnet. Consolidated all multiplayer config * files into one. * * 7 11/19/98 8:03a Dave * Full support for D3-style reliable sockets. Revamped packet lag/loss * system, made it receiver side and at the lowest possible level. * * 6 11/17/98 11:12a Dave * Removed player identification by address. Now assign explicit id #'s. * * 5 11/12/98 12:13a Dave * Tidied code up for multiplayer test. Put in network support for flak * guns. * * * $NoKeywords: $ */ #include "network/multi.h" #include "network/multiutil.h" #include "network/multimsgs.h" #include "ship/ship.h" #include "io/timer.h" #include "playerman/player.h" #include "mission/missionparse.h" #include "mission/missioncampaign.h" #include "gamesequence/gamesequence.h" #include "freespace2/freespace.h" #include "osapi/osapi.h" #include "network/stand_gui.h" #include "network/multi_xfer.h" #include "network/multiui.h" #include "network/multi_ingame.h" #include "popup/popup.h" #include "missionui/chatbox.h" #include "network/multiteamselect.h" #include "network/multi_data.h" #include "network/multi_kick.h" #include "network/multi_campaign.h" #include "network/multi_voice.h" #include "network/multi_team.h" #include "network/multi_respawn.h" #include "network/multi_pmsg.h" #include "network/multi_endgame.h" #include "missionui/missiondebrief.h" #include "network/multi_pause.h" #include "mission/missiongoals.h" #include "network/multi_log.h" #include "network/multi_rate.h" #include "hud/hudescort.h" #include "globalincs/alphacolors.h" #include "cfile/cfile.h" #pragma warning(push) // 4018 = signed/unsigned mismatch // 4663 = new template specification syntax // 4245 = signed/unsigned mismatch in conversion of const value #pragma warning(disable: 4663 4018 4663 4245) #include "fs2open_pxo/Client.h" #if !defined(PXO_TCP) extern UDP_Socket FS2OpenPXO_Socket; // obvious :D - Kazan #else extern TCP_Socket FS2OpenPXO_Socket; // obvious :D - Kazan #endif extern int PXO_SID; // FS2 Open PXO Session ID extern char PXO_Server[]; extern int PXO_port; #pragma warning(pop) // ---------------------------------------------------------------------------------------- // Basic module scope defines // // // timestamp defines // #define NETGAME_SEND_TIME 1000 // time between sending netgame update packets // #define STATE_SEND_TIME 1000 // time between sending netplayer state packets // #define GAMEINFO_SEND_TIME 3000 // time between sending game information packets // #define PING_SEND_TIME 2000 // time between player pings // #define INGAME_UPDATE_TIME 1000 // time limit between ingame join operations #define NETGAME_SEND_TIME 2 // time between sending netgame update packets #define STATE_SEND_TIME 2 // time between sending netplayer state packets #define GAMEINFO_SEND_TIME 3 // time between sending game information packets #define PING_SEND_TIME 2 // time between player pings #define BYTES_SENT_TIME 5 // every five seconds // netplayer stuff #define CULL_ZOMBIE_TIME 1000 // zombies are checked for at this interval (in milliseconds) // object update stuff #define SEND_POS_INTERVAL 30 // min time in milliseconds between sending position updates // local network buffer stuff #define MAX_NET_BUFFER (1024 * 16) // define and variable declaration for our local tcp buffer #define NUM_REENTRANT_LEVELS 3 // time (in fixed seconds) to put up dialog about no contect from server #define MULTI_SERVER_MAX_TIMEOUT (F1_0 * 4) // after this number of milliseoncds, stop client simulation #define MULTI_SERVER_MAX_TIMEOUT_LARGE (F1_0 * 40) // done anytime not in mission #define MULTI_SERVER_WAIT_TIME (F1_0 * 60) // wait 60 seconds to reconnect with the server #define MULTI_SERVER_GONE 1 #define MULTI_SERVER_ALIVE 2 #define DISCONNECT_TIMEOUT (F1_0 * 10) // 10 seconds to timeout someone who cannot connnect // define for when to show "slow network" icon #define MULTI_SERVER_SLOW_PING_TIME 700 // when average ping time to server reaches this -- display hud icon // update times for clients ships based on object update level #define MULTI_CLIENT_UPDATE_TIME 333 int Multi_display_netinfo = 1; // ---------------------------------------------------------------------------------------- // Multiplayer vars // // // net player vars net_player Net_players[MAX_PLAYERS]; // array of all netplayers in the game net_player *Net_player; // pointer to console's net_player entry // netgame vars netgame_info Netgame; // netgame information int Multi_mission_loaded = 0; // flag, so that we dont' load the mission more than once client side int Ingame_join_net_signature = -1; // signature for the player obj for use when joining ingame int Multi_button_info_ok = 0; // flag saying it is ok to apply critical button info on a client machine int Multi_button_info_id = 0; // identifier of the stored button info to be applying // low level networking vars int ADDRESS_LENGTH; // will be 6 for IPX, 4 for IP int PORT_LENGTH; // will be 2 for IPX, 2 for IP int HEADER_LENGTH; // 1 byte (packet type) // misc data active_game* Active_game_head; // linked list of active games displayed on Join screen int Active_game_count; // for interface screens as well CFILE* Multi_chat_stream; // for streaming multiplayer chat strings to a file int Multi_has_cd = 0; // if this machine has a cd or not (call multi_common_verify_cd() to set this) int Multi_connection_speed; // connection speed of this machine. int Multi_num_players_at_start = 0; // the # of players present (kept track of only on the server) at the very start of the mission short Multi_id_num = 0; // for assigning player id #'s // permanent server list server_item* Game_server_head; // list of permanent game servers to be querying // timestamp data int Netgame_send_time = -1; // timestamp used to send netgame info to players before misison starts int State_send_time = -1; // timestamp used to send state information to the host before a mission starts int Gameinfo_send_time = -1; // timestamp used by master to send game information to clients int Next_ping_time = -1; // when we should next ping all int Multi_server_check_count = 0; // var to keep track of reentrancy when checking server status int Next_bytes_time = -1; // bytes sent // how often each player gets updated int Multi_client_update_times[MAX_PLAYERS]; // client update packet timestamp // local network buffer data LOCAL ubyte net_buffer[NUM_REENTRANT_LEVELS][MAX_NET_BUFFER]; LOCAL ubyte Multi_read_count; int Multi_restr_query_timestamp = -1; join_request Multi_restr_join_request; net_addr Multi_restr_addr; int Multi_join_restr_mode = -1; LOCAL fix Multi_server_wait_start; // variable to hold start time when waiting to reestablish with server // non API master tracker vars char Multi_tracker_login[100] = ""; char Multi_tracker_passwd[100] = ""; char Multi_tracker_squad_name[100] = ""; int Multi_tracker_id = -1; char Multi_tracker_id_string[255]; // current file checksum ushort Multi_current_file_checksum = 0; int Multi_current_file_length = -1; // ------------------------------------------------------------------------------------------------- // multi_init() is called only once, at game start-up. Get player address + port, initialize the // network players list. // // void multi_init() { int idx; // read in config file multi_options_read_config(); Assert( Net_player == NULL ); Multi_id_num = 0; // clear out all netplayers memset(Net_players, 0, sizeof(net_player) * MAX_PLAYERS); for(idx=0; idx<MAX_PLAYERS; idx++){ Net_players[idx].reliable_socket = INVALID_SOCKET; } // initialize the local netplayer Net_player = &Net_players[0]; Net_player->tracker_player_id = Multi_tracker_id; Net_player->player = Player; Net_player->flags = 0; Net_player->s_info.xfer_handle = -1; Net_player->player_id = multi_get_new_id(); Net_player->client_cinfo_seq = 0; Net_player->client_server_seq = 0; // get our connection speed Multi_connection_speed = multi_get_connection_speed(); // initialize other stuff multi_log_init(); // load up common multiplayer icons if (!Is_standalone) multi_load_common_icons(); } // this is an important function which re-initializes any variables required in multiplayer games. // Always make sure globals you add are re-initialized here !!!! void multi_vars_init() { // initialize this variable right away. Used in game_level_init for init'ing the player Next_ship_signature = SHIP_SIG_MIN; Next_asteroid_signature = ASTEROID_SIG_MIN; Next_non_perm_signature = NPERM_SIG_MIN; Next_debris_signature = DEBRIS_SIG_MIN; // server-client critical stuff Multi_button_info_ok = 0; Multi_button_info_id = 0; // Ingame join stuff Ingame_join_net_signature = -1; // Netgame stuff Netgame.game_state = NETGAME_STATE_FORMING; // team select stuff Multi_ts_inited = 0; // load send stuff Multi_mission_loaded = 0; // client side // restricted game stuff Multi_restr_query_timestamp = -1; // respawn stuff Multi_server_check_count = 0; // reentrant variable Multi_read_count = 0; // unset the "have cd" var // NOTE: we unset this here because we are going to be calling multi_common_verify_cd() // immediately after this (in multi_level_init() to re-check the status) Multi_has_cd = 0; // current file checksum Multi_current_file_checksum = 0; Multi_current_file_length = -1; Active_game_head = NULL; Game_server_head = NULL; // only the server should ever care about this Multi_id_num = 0; } // ------------------------------------------------------------------------------------------------- // multi_level_init() is called whenever the player starts a multiplayer game // // void multi_level_init() { int idx; // NETLOG ml_string(NOX("multi_level_init()")); // initialize the Net_players array for(idx=0;idx<MAX_PLAYERS;idx++) { // close all sockets down just for good measure psnet_rel_close_socket(&Net_players[idx].reliable_socket); memset(&Net_players[idx],0,sizeof(net_player)); Net_players[idx].reliable_socket = INVALID_SOCKET; Net_players[idx].s_info.xfer_handle = -1; Net_players[idx].p_info.team = 0; } // initialize the Players array for(idx=0;idx<MAX_PLAYERS;idx++){ if(Player == &Players[idx]){ continue; } memset(&Players[idx],0,sizeof(player)); } multi_vars_init(); // initialize the fake lag/loss system #ifdef MULTI_USE_LAG multi_lag_init(); #endif // initialize the kick system multi_kick_init(); // initialize all file xfer stuff multi_xfer_init(multi_file_xfer_notify); // close the chatbox (if one exists) chatbox_close(); // reset the data xfer system multi_data_reset(); // initialize the voice system multi_voice_init(); // intialize the pause system multi_pause_reset(); // initialize endgame stuff multi_endgame_init(); // initialize respawning multi_respawn_init(); // initialize all netgame timestamps multi_reset_timestamps(); // flush psnet sockets psnet_flush(); } // multi_check_listen() calls low level psnet routine to see if we have a connection from a client we // should accept. void multi_check_listen() { int i; net_addr addr; PSNET_SOCKET_RELIABLE sock = INVALID_SOCKET; // call psnet routine which calls select to see if we need to check for a connect from a client // by passing addr, we are telling check_for_listen to do the accept and return who it was from in // addr. The sock = psnet_rel_check_for_listen(&addr); if ( sock != INVALID_SOCKET ) { // be sure that my address and the server address are set correctly. if ( !psnet_same(&Psnet_my_addr, &Net_player->p_info.addr) ){ Net_player->p_info.addr = Psnet_my_addr; } if ( !psnet_same(&Psnet_my_addr, &(Netgame.server_addr)) ){ Netgame.server_addr = Psnet_my_addr; } // the connection was accepted in check_for_listen. Find the netplayer whose address we connected // with and assign the socket descriptor for (i = 0; i < MAX_PLAYERS; i++ ) { if ( (Net_players[i].flags & NETINFO_FLAG_CONNECTED) && (!memcmp(&(addr.addr), &(Net_players[i].p_info.addr.addr), 6)) ) { // mark this flag so we know he's "fully" connected Net_players[i].flags |= NETINFO_FLAG_RELIABLE_CONNECTED; Net_players[i].reliable_socket = sock; // send player information to the joiner send_accept_player_data( &Net_players[i], (Net_players[i].flags & NETINFO_FLAG_INGAME_JOIN)?1:0 ); // send a netgame update so the new client has all the necessary settings send_netgame_update_packet(); // if this is a team vs. team game, send an update if(Netgame.type_flags & NG_TYPE_TEAM){ multi_team_send_update(); } // NETLOG ml_printf(NOX("Accepted TCP connection from %s"), Net_players[i].player == NULL ? NOX("Unknown") : Net_players[i].player->callsign); break; } } // if we didn't find a player, close the socket if ( i == MAX_PLAYERS ) { nprintf(("Network", "Got accept on my listen socket, but unknown player. Closing socket.\n")); psnet_rel_close_socket(&sock); } } } // returns true is server hasn't been heard from in N seconds. false otherwise int multi_client_server_dead() { fix this_time, last_time, max; // get the last time we have heard from the server. If greater than some default, then maybe // display some icon on the HUD indicating slow network connection. if greater than some higher // max, stop simulating on the client side until we hear from the server again. this_time = timer_get_fixed_seconds(); last_time = Netgame.server->last_heard_time; // check for wrap! must return 0 if ( last_time > this_time ) return 0; this_time -= last_time; // if in mission, use the smaller timeout value. Outside of mission, use a large one. if ( MULTI_IN_MISSION ){ max = MULTI_SERVER_MAX_TIMEOUT; } else { max = MULTI_SERVER_MAX_TIMEOUT_LARGE; } if ( this_time > max){ return 1; } else { return 0; } } void multi_process_incoming(); // prototype for function later in this module // function to process network data in hopes of getting info back from server int multi_client_wait_on_server() { int is_dead; is_dead = multi_client_server_dead(); // if the server is back alive, tell our popup if ( !is_dead ){ return MULTI_SERVER_ALIVE; } // on release version -- keep popup active for 60 seconds, then bail #ifdef NDEBUG fix this_time = timer_get_fixed_seconds(); // if the timer wrapped: if ( this_time < Multi_server_wait_start ) { Multi_server_wait_start = timer_get_fixed_seconds(); return FALSE; } // check to see if timeout expired this_time -= Multi_server_wait_start; if ( this_time > MULTI_SERVER_WAIT_TIME ){ return MULTI_SERVER_GONE; } #endif return FALSE; } // function called by multiplayer clients to stop simulating when they have not heard from the server // in a while. void multi_client_check_server() { int rval; Assert( MULTIPLAYER_CLIENT ); // this function can get called while in the popup code below. So we include this check as a // reentrancy check. if ( Multi_server_check_count ) return; // make sure we have a valid server if(Netgame.server == NULL){ return; } Multi_server_check_count++; if(multi_client_server_dead()){ Netgame.flags |= NG_FLAG_SERVER_LOST; } else { Netgame.flags &= ~(NG_FLAG_SERVER_LOST); } if(Netgame.flags & NG_FLAG_SERVER_LOST) { if(!(Game_mode & GM_IN_MISSION) && !popup_active()){ // need to start a popup Multi_server_wait_start = timer_get_fixed_seconds(); rval = popup_till_condition( multi_client_wait_on_server, XSTR("Cancel",641), XSTR("Contact lost with server. Stopping simulation until contact reestablished. Press Cancel to exit game.",642) ); if ( !rval || (rval == MULTI_SERVER_GONE) ) { multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_CONTACT_LOST); } Netgame.flags &= ~(NG_FLAG_SERVER_LOST); } } Multi_server_check_count--; } // ------------------------------------------------------------------------------------------------- // process_packet_normal() will determine what sort of packet it is, and send it to the appropriate spot. // Prelimiary verification of the magic number and checksum are done here. // void process_packet_normal(ubyte* data, header *header_info) { switch ( data[0] ) { case JOIN: process_join_packet(data, header_info); break; case GAME_CHAT: process_game_chat_packet( data, header_info ); break; case NOTIFY_NEW_PLAYER: process_new_player_packet(data, header_info); break; case HUD_MSG: process_hud_message(data, header_info); break; case MISSION_MESSAGE: process_mission_message_packet( data, header_info ); break; case LEAVE_GAME: process_leave_game_packet(data, header_info); break; case GAME_QUERY: process_game_query(data, header_info); break; case GAME_ACTIVE: process_game_active_packet(data, header_info); break; case GAME_INFO: process_game_info_packet( data, header_info ); break; case SECONDARY_FIRED_AI: process_secondary_fired_packet(data, header_info, 0); break; case SECONDARY_FIRED_PLR: process_secondary_fired_packet(data, header_info, 1); break; case COUNTERMEASURE_FIRED: process_countermeasure_fired_packet( data, header_info ); break; case FIRE_TURRET_WEAPON: process_turret_fired_packet( data, header_info ); break; case GAME_UPDATE: process_netgame_update_packet( data, header_info ); break; case UPDATE_DESCRIPT: process_netgame_descript_packet( data, header_info ); break; case NETPLAYER_UPDATE: process_netplayer_update_packet( data, header_info ); break; case ACCEPT : process_accept_packet(data, header_info); break; case OBJECT_UPDATE: multi_oo_process_update(data, header_info); break; case SHIP_KILL: process_ship_kill_packet( data, header_info ); break; case WING_CREATE: process_wing_create_packet( data, header_info ); break; case SHIP_CREATE: process_ship_create_packet( data, header_info ); break; case SHIP_DEPART: process_ship_depart_packet( data, header_info ); break; case MISSION_LOG_ENTRY: process_mission_log_packet( data, header_info ); break; case PING: process_ping_packet(data, header_info); break; case PONG: process_pong_packet(data, header_info); break; case XFER_PACKET: Assert(header_info->id >= 0); int np_index; PSNET_SOCKET_RELIABLE sock; sock = INVALID_SOCKET; // if I'm the server of the game, find out who this came from if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_AM_MASTER)){ np_index = find_player_id(header_info->id); if(np_index >= 0){ sock = Net_players[np_index].reliable_socket; } } // otherwise always use my own socket else if(Net_player != NULL){ sock = Net_player->reliable_socket; } header_info->bytes_processed = multi_xfer_process_packet(data + HEADER_LENGTH, sock) + HEADER_LENGTH; break; case MISSION_REQUEST: process_mission_request_packet(data,header_info); break; case MISSION_ITEM: process_mission_item_packet(data,header_info); break; case MULTI_PAUSE_REQUEST: process_multi_pause_packet(data, header_info); break; case INGAME_NAK: process_ingame_nak(data, header_info); break; case SHIPS_INGAME_PACKET: process_ingame_ships_packet(data, header_info); break; case WINGS_INGAME_PACKET: process_ingame_wings_packet(data, header_info); break; case MISSION_END: process_endgame_packet(data, header_info); break; case OBSERVER_UPDATE: process_observer_update_packet(data, header_info); break; case NETPLAYER_SLOTS_P: process_netplayer_slot_packet(data, header_info); break; case SHIP_STATUS_CHANGE: process_ship_status_packet(data, header_info); break; case PLAYER_ORDER_PACKET: process_player_order_packet(data, header_info); break; case INGAME_SHIP_UPDATE: process_ingame_ship_update_packet(data, header_info); break; case INGAME_SHIP_REQUEST: process_ingame_ship_request_packet(data, header_info); break; case FILE_SIG_INFO: process_file_sig_packet(data, header_info); break; case RESPAWN_NOTICE: multi_respawn_process_packet(data,header_info); break; case SUBSYSTEM_DESTROYED: process_subsystem_destroyed_packet( data, header_info ); break; case LOAD_MISSION_NOW : process_netplayer_load_packet(data, header_info); break; case FILE_SIG_REQUEST : process_file_sig_request(data, header_info); break; case JUMP_INTO_GAME: process_jump_into_mission_packet(data, header_info); break; case CLIENT_REPAIR_INFO: process_repair_info_packet(data,header_info); break; case MISSION_SYNC_DATA: process_mission_sync_packet(data,header_info); break; case STORE_MISSION_STATS: process_store_stats_packet(data, header_info); break; case DEBRIS_UPDATE: process_debris_update_packet(data, header_info); break; case SHIP_WSTATE_CHANGE: process_ship_weapon_change( data, header_info ); break; case WSS_UPDATE_PACKET: process_wss_update_packet(data, header_info); break; case WSS_REQUEST_PACKET: process_wss_request_packet( data, header_info ); break; case FIRING_INFO: process_firing_info_packet( data, header_info ); break; case CARGO_REVEALED: process_cargo_revealed_packet( data, header_info); break; case CARGO_HIDDEN: process_cargo_hidden_packet( data, header_info); break; case SUBSYS_CARGO_REVEALED: process_subsystem_cargo_revealed_packet( data, header_info); break; case SUBSYS_CARGO_HIDDEN: process_subsystem_cargo_hidden_packet( data, header_info); break; case MISSION_GOAL_INFO: process_mission_goal_info_packet(data, header_info); break; case KICK_PLAYER: process_player_kick_packet(data, header_info); break; case PLAYER_SETTINGS: process_player_settings_packet(data, header_info); break; case DENY: process_deny_packet(data, header_info); break; case POST_SYNC_DATA: process_post_sync_data_packet(data, header_info); break; case WSS_SLOTS_DATA: process_wss_slots_data_packet(data,header_info); break; case SHIELD_EXPLOSION: process_shield_explosion_packet( data, header_info ); break; case PLAYER_STATS: process_player_stats_block_packet(data, header_info); break; case SLOT_UPDATE: process_pslot_update_packet(data,header_info); break; case AI_INFO_UPDATE: process_ai_info_update_packet( data, header_info ); break; case CAMPAIGN_UPDATE : multi_campaign_process_update(data,header_info); break; case CAMPAIGN_UPDATE_INGAME: multi_campaign_process_ingame_start(data,header_info); break; case VOICE_PACKET : multi_voice_process_packet(data,header_info); break; case TEAM_UPDATE : multi_team_process_packet(data,header_info); break; case ASTEROID_INFO: process_asteroid_info(data, header_info); break; case HOST_RESTR_QUERY: process_host_restr_packet(data, header_info); break; case OPTIONS_UPDATE: multi_options_process_packet(data,header_info); break; case SQUADMSG_PLAYER: multi_msg_process_squadmsg_packet(data,header_info); break; case NETGAME_END_ERROR: process_netgame_end_error_packet(data,header_info); break; case COUNTERMEASURE_SUCCESS: process_countermeasure_success_packet( data, header_info ); break; case CLIENT_UPDATE: process_client_update_packet(data, header_info); break; case COUNTDOWN: process_countdown_packet(data, header_info); break; case DEBRIEF_INFO: process_debrief_info( data, header_info ); break; case ACCEPT_PLAYER_DATA: process_accept_player_data( data, header_info ); break; case HOMING_WEAPON_UPDATE: process_homing_weapon_info( data, header_info ); break; case EMP_EFFECT: process_emp_effect(data, header_info); break; case REINFORCEMENT_AVAIL: process_reinforcement_avail( data, header_info ); break; case CHANGE_TEAM: process_change_team_packet(data, header_info); break; case CHANGE_IFF: process_change_iff_packet(data, header_info); break; case CHANGE_AI_CLASS: process_change_ai_class_packet(data, header_info); break; case PRIMARY_FIRED_NEW: process_NEW_primary_fired_packet(data, header_info); break; case COUNTERMEASURE_NEW: process_NEW_countermeasure_fired_packet(data, header_info); break; case BEAM_FIRED: process_beam_fired_packet(data, header_info); break; case SW_STD_QUERY: process_sw_query_packet(data, header_info); break; case EVENT_UPDATE: process_event_update_packet(data, header_info); break; case OBJECT_UPDATE_NEW: multi_oo_process_update(data, header_info); break; case WEAPON_DET: process_weapon_detonate_packet(data, header_info); break; case FLAK_FIRED: process_flak_fired_packet(data, header_info); break; case NETPLAYER_PAIN: process_player_pain_packet(data, header_info); break; case LIGHTNING_PACKET: process_lightning_packet(data, header_info); break; case BYTES_SENT: process_bytes_recvd_packet(data, header_info); break; case TRANSFER_HOST: process_host_captain_change_packet(data, header_info); break; case SELF_DESTRUCT: process_self_destruct_packet(data, header_info); break; case SHIP_DISABLED: process_ship_disabled_packet(data, header_info); break; case SFOIL_UPDATE: process_ship_sfoil_update_packet(data, header_info); break; case POD_UPDATE: process_ship_pod_update_packet(data, header_info); break; case LINK_UPDATE: process_ship_barrel_link_packet(data, header_info); break; default: nprintf(("Network", "Received packet with unknown type %d\n", data[0] )); header_info->bytes_processed = 10000; break; } // end switch } // Takes a bunch of messages, check them for validity, // and pass them to multi_process_data. // --------------------^ // this should be process_packet() I think, or with the new code // process_tracker_packet() as defined in MultiTracker.[h,cpp] void multi_process_bigdata(ubyte *data, int len, net_addr *from_addr, int reliable) { int type, bytes_processed; int player_num; header header_info; ubyte *buf; // the only packets we will process from an unknown player are GAME_QUERY, GAME_INFO, JOIN, PING, PONG, ACCEPT, and GAME_ACTIVE packets player_num = find_player(from_addr); // find the player who sent the message and mark the last_heard time for this player // check to see if netplayer is null (it may be in cases such as getting lists of games from the tracker) if(player_num >= 0){ Net_players[player_num].last_heard_time = timer_get_fixed_seconds(); } // store fields that were passed along in the message // store header information that was captured from the network-layer header memcpy(header_info.addr, from_addr->addr, 6); memcpy(header_info.net_id, from_addr->net_id, 4); header_info.port = from_addr->port; if(player_num >= 0){ header_info.id = Net_players[player_num].player_id; } else { header_info.id = -1; } bytes_processed = 0; while( (bytes_processed >= 0) && (bytes_processed < len) ) { buf = &(data[bytes_processed]); type = buf[0]; // if its coming from an unknown source, there are only certain packets we will actually process if((player_num == -1) && !multi_is_valid_unknown_packet((ubyte)type)){ return ; } if ( (type<0) || (type > MAX_TYPE_ID )) { nprintf( ("Network", "multi_process_bigdata: Invalid packet type %d!\n", type )); return; } // perform any special processing checks here process_packet_normal(buf,&header_info); // MWA -- magic number was removed from header on 8/4/97. Replaced with bytes_processed // variable which gets stuffed whenever a packet is processed. bytes_processed += header_info.bytes_processed; } // if this is not reliable data and we have a valid player if(Net_player != NULL){ if(!MULTIPLAYER_MASTER && !reliable && (Game_mode & GM_IN_MISSION)){ Net_player->cl_bytes_recvd += len; } } } // process all reliable socket details void multi_process_reliable_details() { int idx; int sock_status; // run reliable sockets #ifdef PSNET2 psnet_rel_work(); #endif // server operations if ( MULTIPLAYER_MASTER ){ // listen for new reliable socket connections multi_check_listen(); // check for any broken sockets and delete any players for(idx=0; idx<MAX_PLAYERS; idx++){ // players who _should_ be validly connected if((idx != MY_NET_PLAYER_NUM) && MULTI_CONNECTED(Net_players[idx])){ // if this guy's socket is broken or disconnected, kill him sock_status = psnet_rel_get_status(Net_players[idx].reliable_socket); if((sock_status == RNF_UNUSED) || (sock_status == RNF_BROKEN) || (sock_status == RNF_DISCONNECTED)){ ml_string("Shutting down rel socket because of disconnect!"); delete_player(idx); } // if we're still waiting for this guy to connect on his reliable socket and he's timed out, boot him if(Net_players[idx].s_info.reliable_connect_time != -1){ // if he's connected if(Net_players[idx].reliable_socket != INVALID_SOCKET){ Net_players[idx].s_info.reliable_connect_time = -1; } // if he's timed out else if(((time(NULL) - Net_players[idx].s_info.reliable_connect_time) > MULTI_RELIABLE_CONNECT_WAIT) && (Net_players[idx].reliable_socket == INVALID_SOCKET)){ ml_string("Player timed out while connecting on reliable socket!"); delete_player(idx); } } } } } // clients should detect broken sockets else { extern unsigned int Serverconn; if(Serverconn != 0xffffffff){ int status = psnet_rel_get_status(Serverconn); if(status == RNF_BROKEN){ mprintf(("CLIENT SOCKET DISCONNECTED")); // quit the game if(!multi_endgame_ending()){ multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_CONTACT_LOST); } } } } } // multi_process_incoming reads incoming data off the unreliable and reliable ports and sends // the data to process_big_data void multi_process_incoming() { int size; ubyte *data, *savep; net_addr from_addr; Assert( Multi_read_count < NUM_REENTRANT_LEVELS ); savep = net_buffer[Multi_read_count]; Multi_read_count++; data = savep; // get the other net players data while( (size = psnet_get(data, &from_addr))>0 ) { // ingame joiners will ignore UDP packets until they are have picked a ship and are in the mission if( (Net_player->flags & NETINFO_FLAG_INGAME_JOIN) && (Net_player->state != NETPLAYER_STATE_INGAME_SHIP_SELECT) ){ //nprintf(("Network","Tossing UDP like a good little ingame joiner...\n")); } // otherwise process incoming data normally else { multi_process_bigdata(data, size, &from_addr, 0); } } // end while // read reliable sockets for data data = savep; int idx; if(Net_player->flags & NETINFO_FLAG_AM_MASTER){ for (idx=0;idx<MAX_PLAYERS;idx++) { if((Net_players[idx].flags & NETINFO_FLAG_CONNECTED) && (Net_player != NULL) && (Net_player->player_id != Net_players[idx].player_id)){ while( (size = psnet_rel_get(Net_players[idx].reliable_socket, data, MAX_NET_BUFFER)) > 0){ multi_process_bigdata(data, size, &Net_players[idx].p_info.addr, 1); } } } } else { // if I'm not the master of the game, read reliable data from my connection with the server if((Net_player->reliable_socket != INVALID_SOCKET) && (Net_player->reliable_socket != 0)){ while( (size = psnet_rel_get(Net_player->reliable_socket,data, MAX_NET_BUFFER)) > 0){ multi_process_bigdata(data, size, &Netgame.server_addr, 1); } } } Multi_read_count--; } // ------------------------------------------------------------------------------------------------- // multi_do_frame() is called once per game loop do update all the multiplayer objects, and send // the player data to all the other net players. // // int eye_tog = 1; DCF(eye_tog, "") { eye_tog = !eye_tog; if(eye_tog){ dc_printf("proper eye stuff on\n"); } else { dc_printf("proper eye stuff off\n"); } } void multi_do_frame() { /* FS2NetD Heartbeat Continue */ static int LastSend = -1; if (Om_tracker_flag && FS2OpenPXO_Socket.isInitialized()) { // should never have to init here //fs2netd_maybe_init(); // -------------------- send if ((clock() - LastSend) >= 30000 || LastSend == -1) { LastSend = clock(); // finish implementation! //void SendHeartBeat(const char* masterserver, int targetport, const char* myName, int myNetspeed, int myStatus, int myType, int numPlayers); if (Net_player->flags & NETINFO_FLAG_AM_MASTER) { SendHeartBeat(PXO_Server, PXO_port, FS2OpenPXO_Socket, Netgame.name, Netgame.mission_name, Netgame.title, Netgame.flags, Netgame.server_addr.port, Netgame.max_players); } Ping(PXO_Server, FS2OpenPXO_Socket); ml_printf("Network FS2netD sent PING\n"); } // stuff that should be checked every frame! if (FS2OpenPXO_Socket.DataReady()) { ml_printf("Network FS2netD received PONG: Time diff %d ms\n", GetPingReply(FS2OpenPXO_Socket)); } } PSNET_TOP_LAYER_PROCESS(); // always set the local player eye position/orientation here so we know its valid throughout all multiplayer // function calls if((Net_player != NULL) && eye_tog){ player_get_eye(&Net_player->s_info.eye_pos, &Net_player->s_info.eye_orient); } // send all buffered packets from the previous frame multi_io_send_buffered_packets(); // datarate tracking multi_rate_process(); // always process any pending endgame details multi_endgame_process(); // process all reliable socket details, including : // 1.) Listening for new pending reliable connections (server) // 2.) Checking for broken sockets (server/client) // 3.) Checking for clients who haven't fully connected multi_process_reliable_details(); // get the other net players data multi_process_incoming(); // process object update datarate stuff (for clients and server both) multi_oo_rate_process(); // clients should check when last time they heard from sever was -- if too long, then // pause the simulation so wait for it to possibly come back if ( (MULTIPLAYER_CLIENT) && (Net_player->flags & NETINFO_FLAG_CONNECTED) ){ multi_client_check_server(); } // everybody pings all the time if((Next_ping_time < 0) || ((time(NULL) - Next_ping_time) > PING_SEND_TIME) ){ if( (Net_player->flags & NETINFO_FLAG_AM_MASTER) ){ send_netplayer_update_packet(); } // ping everyone multi_ping_send_all(); Next_ping_time = time(NULL); } // if I am the master, and we are not yet actually playing the mission, send off netgame // status to all other players in the game. If I am not the master of the game, and we // are not in the game, then send out my netplayer status to the host if ( (Net_player->flags & NETINFO_FLAG_CONNECTED) && !(Game_mode & GM_IN_MISSION)){ if ( Net_player->flags & NETINFO_FLAG_AM_MASTER ) { if ( (Netgame_send_time < 0) || ((time(NULL) - Netgame_send_time) > NETGAME_SEND_TIME) ) { send_netgame_update_packet(); Netgame_send_time = time(NULL); } } else { if ( (State_send_time < 0) || ((time(NULL) - State_send_time) > STATE_SEND_TIME) ){ // observers shouldn't send an update state packet if ( !(Net_player->flags & NETINFO_FLAG_OBSERVER) ){ send_netplayer_update_packet(); } State_send_time = time(NULL); } } } else if ( (Net_player->flags & NETINFO_FLAG_CONNECTED) && (Game_mode & GM_IN_MISSION) ) { // if I am connected and am in the mission, do things that need to be done on a regular basis if ( Net_player->flags & NETINFO_FLAG_AM_MASTER ) { if ( (Gameinfo_send_time < 0) || ((time(NULL) - Gameinfo_send_time) > GAMEINFO_SEND_TIME)){ send_game_info_packet(); Gameinfo_send_time = time(NULL); } // for any potential respawns multi_respawn_handle_invul_players(); multi_respawn_check_ai(); // for any potential ingame joiners multi_handle_ingame_joiners(); } else { // the clients need to do some processing of stuff as well } } // check to see if we're waiting on confirmation for a restricted ingame join if(Multi_restr_query_timestamp != -1){ // if it has elapsed, unset the ingame join flag if(timestamp_elapsed(Multi_restr_query_timestamp)){ Multi_restr_query_timestamp = -1; Netgame.flags &= ~(NG_FLAG_INGAME_JOINING); } } // while in the mission, send my PlayerControls to the host so that he can process // my movement if ( Game_mode & GM_IN_MISSION ) { // tickers extern void oo_update_time(); oo_update_time(); if ( !(Net_player->flags & NETINFO_FLAG_AM_MASTER)){ if(Net_player->flags & NETINFO_FLAG_OBSERVER){ // if the rate limiting system says its ok if(multi_oo_cirate_can_send()){ // send my observer position/object update send_observer_update_packet(); } } else if ( !(Player_ship->flags & SF_DEPARTING ) ){ // if the rate limiting system says its ok if(multi_oo_cirate_can_send()){ // use the new method multi_oo_send_control_info(); } } // bytes received info if( (Next_bytes_time < 0) || ((time(NULL) - Next_bytes_time) > BYTES_SENT_TIME) ){ if(Net_player != NULL){ send_bytes_recvd_packet(Net_player); // reset bytes recvd Net_player->cl_bytes_recvd = 0; } // reset timestamp Next_bytes_time = time(NULL); } } else { // sending new objects from here is dependent on having objects only created after // the game is done moving the objects. I think that I can enforce this. multi_oo_process(); // evaluate whether the time limit has been reached or max kills has been reached // Commented out by Sandeep 4/12/98, was causing problems with testing. if( ((f2fl(Netgame.options.mission_time_limit) > 0.0f) && (Missiontime > Netgame.options.mission_time_limit)) || multi_kill_limit_reached() ) { // make sure we don't do this more than once if(Netgame.game_state == NETGAME_STATE_IN_MISSION){ multi_handle_end_mission_request(); } } } } // periodically send a client update packet to all clients if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_AM_MASTER)){ int idx; for(idx=0;idx<MAX_PLAYERS;idx++){ if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != &Net_players[idx])){ if((Multi_client_update_times[idx] < 0) || timestamp_elapsed_safe(Multi_client_update_times[idx], 1000)){ send_client_update_packet(&Net_players[idx]); Multi_client_update_times[idx] = timestamp(MULTI_CLIENT_UPDATE_TIME); } } } } // process any kicked player details multi_kick_process(); // do any file xfer details multi_xfer_do(); // process any player data details (wav files, pilot pics, etc) multi_data_do(); // do any voice details multi_voice_process(); // process any player messaging details multi_msg_process(); #ifndef NO_STANDALONE // if on the standalone, do any gui stuff if(Game_mode & GM_STANDALONE_SERVER){ std_do_gui_frame(); } #endif // dogfight nonstandalone players should recalc the escort list every frame if(!(Game_mode & GM_STANDALONE_SERVER) && (Netgame.type_flags & NG_TYPE_DOGFIGHT) && MULTI_IN_MISSION){ hud_setup_escort_list(0); } } // ------------------------------------------------------------------------------------------------- // multi_pause_do_frame() is called once per game loop do update all the multiplayer objects, and send // the player data to all the other net players when the multiplayer game is paused. It only will do // checking for a few specialized packets (MULTI_UNPAUSE, etc) // void multi_pause_do_frame() { PSNET_TOP_LAYER_PROCESS(); // always set the local player eye position/orientation here so we know its valid throughout all multiplayer // function calls // if((Net_player != NULL) && eye_tog){ // player_get_eye(&Net_player->s_info.eye_pos, &Net_player->s_info.eye_orient); // } // send all buffered packets from the previous frame multi_io_send_buffered_packets(); // always process any pending endgame details multi_endgame_process(); // process all reliable socket details, including : // 1.) Listening for new pending reliable connections (server) // 2.) Checking for broken sockets (server/client) // 3.) Checking for clients who haven't fully connected multi_process_reliable_details(); // these timestamps and handlers shoul be evaluated in the pause state if ( Net_player->flags & NETINFO_FLAG_AM_MASTER ) { if ( (Gameinfo_send_time < 0) || ((time(NULL) - Gameinfo_send_time) > GAMEINFO_SEND_TIME) ){ send_game_info_packet(); Gameinfo_send_time = time(NULL); } } // everybody pings all the time if((Next_ping_time < 0) || ((time(NULL) - Next_ping_time) > PING_SEND_TIME) ){ multi_ping_send_all(); Next_ping_time = time(NULL); } // periodically send a client update packet to all clients if(Net_player->flags & NETINFO_FLAG_AM_MASTER){ int idx; for(idx=0;idx<MAX_PLAYERS;idx++){ if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != &Net_players[idx])){ if((Multi_client_update_times[idx] < 0) || timestamp_elapsed_safe(Multi_client_update_times[idx], 1000)){ send_client_update_packet(&Net_players[idx]); Multi_client_update_times[idx] = timestamp(MULTI_CLIENT_UPDATE_TIME); } } } // for any potential ingame joiners multi_handle_ingame_joiners(); } // do any file xfer details multi_xfer_do(); // process any player data details (wav files, pilot pics, etc) multi_data_do(); // get the other net players data multi_process_incoming(); // do any voice details multi_voice_process(); // process any player messaging details multi_msg_process(); // process any kicked player details multi_kick_process(); // process any pending endgame details multi_endgame_process(); // process object update stuff (for clients and server both) if(MULTIPLAYER_MASTER){ multi_oo_process(); } #ifndef NO_STANDALONE // if on the standalone, do any gui stuff if(Game_mode & GM_STANDALONE_SERVER){ std_do_gui_frame(); } #endif } #ifndef NO_STANDALONE // -------------------------------------------------------------------------------- // standalone_main_init() the standalone equivalent of the main menu // extern int sock_inited; float frame_time = (float)1.0/(float)30.0; void standalone_main_init() { std_debug_set_standalone_state_string("Main Init"); Game_mode = (GM_STANDALONE_SERVER | GM_MULTIPLAYER); // NETLOG ml_string(NOX("Standalone server initializing")); // read in config file // multi_options_read_config(); #ifdef _WIN32 // if we failed to startup on our desired protocol, fail if((Multi_options_g.protocol == NET_IPX) && !Ipx_active){ MessageBox((HWND)os_get_window(), XSTR( "You have selected IPX for multiplayer Freespace, but the IPX protocol was not detected on your machine.", 1402), "Error", MB_OK); exit(1); } if((Multi_options_g.protocol == NET_TCP) && !Tcp_active){ MessageBox((HWND)os_get_window(), XSTR("You have selected TCP/IP for multiplayer Freespace, but the TCP/IP protocol was not detected on your machine.", 362), "Error", MB_OK); exit(1); } #endif // ifdef _WIN32 // set the protocol #ifdef MULTIPLAYER_BETA_BUILD Multi_options_g.protocol = NET_TCP; psnet_use_protocol(Multi_options_g.protocol); ADDRESS_LENGTH = IP_ADDRESS_LENGTH; PORT_LENGTH = IP_PORT_LENGTH; #else psnet_use_protocol(Multi_options_g.protocol); switch (Multi_options_g.protocol) { case NET_IPX: ADDRESS_LENGTH = IPX_ADDRESS_LENGTH; PORT_LENGTH = IPX_PORT_LENGTH; break; case NET_TCP: ADDRESS_LENGTH = IP_ADDRESS_LENGTH; PORT_LENGTH = IP_PORT_LENGTH; break; default: Int3(); } // end switch #endif HEADER_LENGTH = 1; // clear out the Netgame structure and start filling in the values // NOTE : these values are not incredibly important since they will be overwritten by the host when he joins memset( &Netgame, 0, sizeof(Netgame) ); Netgame.game_state = NETGAME_STATE_FORMING; // game is currently starting up Netgame.security = 0; Netgame.server_addr = Psnet_my_addr; memset(&The_mission,0,sizeof(The_mission)); // reinitialize all systems multi_level_init(); // intialize endgame stuff multi_endgame_init(); // clear the file xfer system multi_xfer_reset(); multi_xfer_force_dir(CF_TYPE_MULTI_CACHE); // reset timer timestamp_reset(); // setup the netplayer for the standalone Net_player = &Net_players[0]; Net_player->tracker_player_id = -1; Net_player->flags |= (NETINFO_FLAG_AM_MASTER | NETINFO_FLAG_CONNECTED | NETINFO_FLAG_DO_NETWORKING | NETINFO_FLAG_MISSION_OK); Net_player->state = NETPLAYER_STATE_WAITING; Net_player->player = Player; strcpy(Player->callsign, "server"); Net_player->p_info.addr = Psnet_my_addr; Net_player->s_info.xfer_handle = -1; Net_player->player_id = multi_get_new_id(); Netgame.server = Net_player; // maybe flag the game as having a hacked ships.tbl /*if(!Game_ships_tbl_valid){ Netgame.flags |= NG_FLAG_HACKED_SHIPS_TBL; } // maybe flag the game as having a hacked weapons.tbl if(!Game_weapons_tbl_valid){ Netgame.flags |= NG_FLAG_HACKED_WEAPONS_TBL; }*/ // hacked data if(game_hacked_data()){ Net_player->flags |= NETINFO_FLAG_HAXOR; } // setup debug flags Netgame.debug_flags = 0; /* if(!Cmdline_server_firing){ Netgame.debug_flags |= NETD_FLAG_CLIENT_FIRING; } if(!Cmdline_client_dodamage){ Netgame.debug_flags |= NETD_FLAG_CLIENT_NODAMAGE; } */ // setup the default game name for the standalone std_connect_set_gamename(NULL); // set netgame default options multi_options_set_netgame_defaults(&Netgame.options); // set local netplayer default options multi_options_set_local_defaults(&Net_player->p_info.options); // set our object update level from the standalone default Net_player->p_info.options.obj_update_level = Multi_options_g.std_datarate; switch(Net_player->p_info.options.obj_update_level){ case OBJ_UPDATE_LOW: nprintf(("Network","STANDALONE USING LOW UPDATES\n")); break; case OBJ_UPDATE_MEDIUM: nprintf(("Network","STANDALONE USING MEDIUM UPDATES\n")); break; case OBJ_UPDATE_HIGH: nprintf(("Network","STANDALONE USING HIGH UPDATE\n")); break; case OBJ_UPDATE_LAN: nprintf(("Network","STANDALONE USING LAN UPDATE\n")); break; } // clear out various things psnet_flush(); game_flush(); ship_init(); std_debug_set_standalone_state_string("Main Do"); std_set_standalone_fps((float)0); std_multi_set_standalone_missiontime((float)0); // load my missions and campaigns multi_create_list_load_missions(); multi_create_list_load_campaigns(); // if this is a tracker game, validate missions if(MULTI_IS_TRACKER_GAME){ multi_update_valid_missions(); } } // -------------------------------------------------------------------------------- // standalone_main_do() // // DESCRIPTION : the standalone server will wait in this state until the host of the game // is "Waiting". That is, his state==NETPLAYER_STATE_WAITING, and he has finished // doing everything and wants to play the game. Once this happens, we will jump // into GS_STATE_MULTI_SERVER_WAIT void standalone_main_do() { Sleep(10); // since nothing will really be going on here, we can afford to give some time // back to the operating system. // kind of a do-nothing spin state. // The standalone will eventually move into the GS_STATE_MULTI_MISSION_SYNC state when a host connects and // attempts to start a game } // -------------------------------------------------------------------------------- // standalone_main_close() // void standalone_main_close() { std_debug_set_standalone_state_string("Main Close"); } void multi_standalone_reset_all() { int idx; // NETLOG ml_string(NOX("Standalone resetting")); // shut all game stuff down game_level_close(); // reinitialize the gui std_reset_standalone_gui(); // close down all sockets for(idx=0;idx<MAX_PLAYERS;idx++){ // 6/25/98 -- MWA -- call delete_player here to remove the player. This closes down the socket // and marks the player as not connected anymore. It is probably cleaner to do this. if ( &Net_players[idx] != Net_player ) { delete_player( idx ); } } // make sure we go to the proper state. if(gameseq_get_state() == GS_STATE_STANDALONE_MAIN){ standalone_main_init(); } gameseq_post_event(GS_EVENT_STANDALONE_MAIN); } // -------------------------------------------------------------------------------- // multi_server_wait_init() do stuff like setting the status bits correctly // void multi_standalone_wait_init() { std_debug_set_standalone_state_string("Wait Do"); std_multi_add_goals(); // fill in the goals for the mission into the tree view multi_reset_timestamps(); // create the bogus standalone object multi_create_standalone_object(); } // -------------------------------------------------------------------------------- // multi_server_wait_do_frame() wait for everyone to log in or the host to send commands // // DESCRIPTION : we will be in this state once the host of the game is waiting for everyone // to be finished and ready to go, at which point, we will will tell everyone // to enter the game, and we will start simulating ourselves. Note that most of // this code is lifted from multi_wait_do_frame() void multi_standalone_wait_do() { } // -------------------------------------------------------------------------------- // multi_server_wait_close() cleanup // void multi_standalone_wait_close() { std_debug_set_standalone_state_string("Wait Close / Game Play"); // all players should reset sequencing int idx; for(idx=0;idx<MAX_PLAYERS;idx++){ if(Net_player->flags & NETINFO_FLAG_CONNECTED){ Net_players[idx].client_cinfo_seq = 0; Net_players[idx].client_server_seq = 0; } } } // this is an artificial state which will push the standalone into the main state without it having to go through // the init function (which would disconnect everyone and generally just screw things up) // it will also eventually do tracker stats update extern int Multi_debrief_server_framecount; void multi_standalone_postgame_init() { std_debug_set_standalone_state_string("Postgame / Send Stats"); // NETLOG ml_string(NOX("Standlone entering postgame")); mission_goal_fail_incomplete(); // handle campaign stuff if ( Game_mode & GM_CAMPAIGN_MODE ) { // MUST store goals and events first - may be used to evaluate next mission // store goals and events mission_campaign_store_goals_and_events_and_variables(); // evaluate next mission mission_campaign_eval_next_mission(); } // always set my state to be "DEBRIEF_ACCEPT" Net_player->state = NETPLAYER_STATE_DEBRIEF_ACCEPT; // mark stats as not being store yet Netgame.flags &= ~(NG_FLAG_STORED_MT_STATS); Multi_debrief_server_framecount = 0; // reset network timestamps multi_reset_timestamps(); } void multi_standalone_postgame_do() { // wait until everyone is in the debriefing if((Netgame.game_state != NETGAME_STATE_DEBRIEF) && multi_netplayer_state_check(NETPLAYER_STATE_DEBRIEF, 1)){ Netgame.game_state = NETGAME_STATE_DEBRIEF; send_netgame_update_packet(); debrief_multi_server_stuff(); } // process server debriefing details if(Netgame.game_state == NETGAME_STATE_DEBRIEF){ multi_debrief_server_process(); } } void multi_standalone_postgame_close() { } #endif // ifndef NO_STANDALONE void multi_reset_timestamps() { int i; for ( i = 0 ; i < MAX_PLAYERS; i++ ){ Multi_client_update_times[i] = -1; } Netgame_send_time = -1; Gameinfo_send_time = -1; Next_ping_time = -1; State_send_time = -1; Next_bytes_time = -1; chatbox_reset_timestamps(); // do for all players so that ingame joiners work properly. for (i = 0; i < MAX_PLAYERS; i++ ) { Players[i].update_dumbfire_time = timestamp(0); Players[i].update_lock_time = timestamp(0); Net_players[i].s_info.voice_token_timestamp = -1; } #ifndef NO_STANDALONE // reset standalone gui timestamps (these are not game critical, so there is not much danger) std_reset_timestamps(); #endif // initialize all object update timestamps multi_oo_gameplay_init(); } // netgame debug flags for debug console stuff DCF(netd, "change/list netgame debug flags") { dc_get_arg(ARG_INT); // if we got an integer, and we're the server, change flags if((Dc_arg_type & ARG_INT) && (Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (Dc_arg_int <= 7)){ Netgame.debug_flags ^= (1<<Dc_arg_int); } // display network flags dc_printf("BITS\n"); // dc_printf("1 - Client side firing (%d)\n", Netgame.debug_flags & NETD_FLAG_CLIENT_FIRING ? 1 : 0); // dc_printf("2 - Client nodamage (%d)\n", Netgame.debug_flags & NETD_FLAG_CLIENT_NODAMAGE ? 1 : 0); } // display any multiplayer/networking information here void multi_display_netinfo() { int sx = gr_screen.max_w - 200; int sy = 20; int idx; // not multiplayer if(!(Game_mode & GM_MULTIPLAYER)){ return; } gr_set_color_fast(&Color_normal); // server or client if(MULTIPLAYER_MASTER){ gr_string(sx, sy, "SERVER"); sy += 10; for(idx=0; idx<MAX_PLAYERS; idx++){ if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != &Net_players[idx]) && (Net_players[idx].player != NULL)){ if(Net_players[idx].sv_last_pl < 0){ gr_printf(sx, sy, "%s : %d, %d pl", Net_players[idx].player->callsign, Net_players[idx].sv_bytes_sent, 0); sy += 10; } else { gr_printf(sx, sy, "%s : %d, %d pl", Net_players[idx].player->callsign, Net_players[idx].sv_bytes_sent, Net_players[idx].sv_last_pl); sy += 10; } } } } else { gr_string(sx, sy, "CLIENT"); sy += 10; // display PL if(Net_player != NULL){ if(Net_player->cl_last_pl < 0){ gr_printf(sx, sy, "PL : %d %d pl\n", Net_player->cl_bytes_recvd, 0); sy += 10; } else { gr_printf(sx, sy, "PL : %d %d pl\n", Net_player->cl_bytes_recvd, Net_player->cl_last_pl); sy += 10; } } } }
[ [ [ 1, 2148 ] ] ]
6f42d9f91a67156294cfdd09f9bf13cb4221ab11
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/MPJoinScreen.cpp
6bad8382635012057a758d414a83e4adbd7ef726
[]
no_license
infernuslord/ja2
d5ac783931044e9b9311fc61629eb671f376d064
91f88d470e48e60ebfdb584c23cc9814f620ccee
refs/heads/master
2021-01-02T23:07:58.941216
2011-10-18T09:22:53
2011-10-18T09:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,758
cpp
#ifdef PRECOMPILEDHEADERS #include "JA2 All.h" #include "Intro.h" #else #include "Types.h" #include "MPJoinScreen.h" #include "GameSettings.h" #include "Utilities.h" #include "wCheck.h" #include "Font Control.h" #include "WordWrap.h" #include "Render Dirty.h" #include "Input.h" #include "Options Screen.h" #include "English.h" #include "Sysutil.h" #include "Fade Screen.h" #include "Cursor Control.h" #include "Music Control.h" #include "cursors.h" #include "Intro.h" #include "Text.h" #include "Text Input.h" #include "_Ja25EnglishText.h" #include "Soldier Profile.h" #endif #include "gameloop.h" #include "connect.h" #include "network.h" // for client name #include "saveloadscreen.h" #include "game init.h" #include <vfs/Core/vfs.h> #include <vfs/Core/vfs_init.h> #include <vfs/Tools/vfs_property_container.h> #include <vfs/Core/vfs_os_functions.h> #include "Random.h" //////////////////////////////////////////// // // Global Defines // /////////////////////////////////////////// #define MPJ_TITLE_FONT FONT14ARIAL//FONT16ARIAL #define MPJ_TITLE_COLOR FONT_MCOLOR_WHITE #define MPJ_LABEL_TEXT_FONT FONT12ARIAL//FONT16ARIAL #define MPJ_LABEL_TEXT_COLOR FONT_MCOLOR_WHITE //buttons #define MPJ_CANCEL_X iScreenWidthOffset + ((320 - 115) / 2) #define MPJ_BTN_HOST_X iScreenWidthOffset + 265 #define MPJ_BTN_HOST_Y iScreenHeightOffset + 435 #define MPJ_BTN_JOIN_X iScreenWidthOffset + 425 #define MPJ_BTN_JOIN_Y iScreenHeightOffset + 435 //textboxes #define MPJ_TXT_HANDLE_X iScreenWidthOffset + 100 #define MPJ_TXT_HANDLE_Y iScreenHeightOffset + 100 #define MPJ_TXT_HANDLE_WIDTH 120 #define MPJ_TXT_HANDLE_HEIGHT 17 #define MPJ_TXT_IP_X iScreenWidthOffset + 100 #define MPJ_TXT_IP_Y iScreenHeightOffset + 400 #define MPJ_TXT_IP_WIDTH 100 #define MPJ_TXT_IP_HEIGHT 17 #define MPJ_TXT_PORT_X MPJ_TXT_IP_X + MPJ_TXT_IP_WIDTH + 40 #define MPJ_TXT_PORT_Y iScreenHeightOffset + 400 #define MPJ_TXT_PORT_WIDTH 40 #define MPJ_TXT_PORT_HEIGHT 17 //main title #define MPJ_MAIN_TITLE_X 0 #define MPJ_MAIN_TITLE_Y iScreenHeightOffset + 10 #define MPJ_MAIN_TITLE_WIDTH SCREEN_WIDTH //labels #define MPJ_LABEL_HANDLE_X MPJ_TXT_HANDLE_X - 80 #define MPJ_LABEL_HANDLE_Y MPJ_TXT_HANDLE_Y + 3 #define MPJ_LABEL_HANDLE_WIDTH 80 #define MPJ_LABEL_HANDLE_HEIGHT 17 #define MPJ_LABEL_IP_X MPJ_TXT_IP_X - 80 #define MPJ_LABEL_IP_Y MPJ_TXT_IP_Y + 3 #define MPJ_LABEL_IP_WIDTH 80 #define MPJ_LABEL_IP_HEIGHT 17 #define MPJ_LABEL_PORT_X MPJ_TXT_PORT_X - 30 #define MPJ_LABEL_PORT_Y MPJ_TXT_PORT_Y + 3 #define MPJ_LABEL_PORT_WIDTH 80 #define MPJ_LABEL_PORT_HEIGHT 17 //////////////////////////////////////////// // // Global Variables // /////////////////////////////////////////// BOOLEAN gfMPJScreenEntry = TRUE; BOOLEAN gfMPJScreenExit = FALSE; BOOLEAN gfReRenderMPJScreen=TRUE; BOOLEAN gfMPJButtonsAllocated = FALSE; //enum for different states of screen enum { MPJ_NOTHING, MPJ_CANCEL, MPJ_EXIT, MPJ_HOST, MPJ_JOIN }; UINT8 gubMPJScreenHandler=MPJ_NOTHING; // State changer for HandleMPJScreen() UINT32 gubMPJExitScreen = MP_JOIN_SCREEN; // The screen that is in control next iteration of the game_loop UINT32 guiMPJMainBackGroundImage; // Wide-char strings that will hold the variables until they are transferred to the CHAR ascii fields CHAR16 gzPlayerHandleField[ 10+1 ] = {0} ; CHAR16 gzServerIPField[ 15+1 ] = {0} ; CHAR16 gzServerPortField[ 5+1 ] = {0} ; // client sets this when joining extern CHAR16 gzFileTransferDirectory[100]; void CUniqueServerId::uniqueRandomString(vfs::String& str) { std::vector<wchar_t> _rand(30,0); int pos = 0; for(int block = 0; block < 5; ++block) { for(int i=0; i<5; ++i) { int r = Random(36); if(r < 10) { r += L'0'; } else { r += L'A' - 10; } _rand[pos++] = r; } _rand[pos++] = L'-'; } str.r_wcs().assign(&_rand[0],29); } vfs::String const& CUniqueServerId::getServerId(vfs::Path dir, vfs::PropertyContainer* props) { if(!props) { return _id; } vfs::String key = L"\"" + dir.c_wcs() + L"\""; vfs::String id = props->getStringProperty(JA2MP_INI_SERVER_SECTION,key); if(id.empty()) { uniqueRandomString(id); } _id = id; props->setStringProperty(JA2MP_INI_SERVER_SECTION,key,_id); return _id; } CUniqueServerId s_ServerId; //////////////////////////////////////////// // // Screen Controls // /////////////////////////////////////////// // Join Button void BtnMPJoinCallback(GUI_BUTTON *btn,INT32 reason); UINT32 guiMPJoinButton; INT32 giMPJoinBtnImage; // Host Button void BtnMPJHostCallback(GUI_BUTTON *btn,INT32 reason); UINT32 guiMPJHostButton; INT32 giMPJHostBtnImage; // Cancel Button void BtnMPJCancelCallback(GUI_BUTTON *btn,INT32 reason); UINT32 guiMPJCancelButton; INT32 giMPJCancelBtnImage; // Message Box handle INT8 giMPJMessageBox = -1; //////////////////////////////////////////// // // Local Function Prototypes // /////////////////////////////////////////// extern void ClearMainMenu(); BOOLEAN EnterMPJScreen(); BOOLEAN ExitMPJScreen(); void HandleMPJScreen(); BOOLEAN RenderMPJScreen(); void GetMPJScreenUserInput(); bool ValidateJoinSettings(bool bSkipServerAddress); BOOLEAN DoMPJMessageBox( UINT8 ubStyle, const STR16 zString, UINT32 uiExitScreen, UINT16 usFlags, MSGBOX_CALLBACK ReturnCallback ); void DoneFadeOutForExitMPJScreen( void ); void DoneFadeInForExitMPJScreen( void ); void MpIniExists() { if(!getVFS()->fileExists(JA2MP_INI_FILENAME)) { SGP_THROW_IFFALSE(getVFS()->createNewFile(JA2MP_INI_FILENAME),L"could not create file : Ja2_mp.ini"); vfs::tWritableFile* file = getVFS()->getWriteFile(JA2MP_INI_FILENAME); if(file) { file->openWrite(true); file->close(); } } } UINT32 MPJoinScreenInit( void ) { // WANNE - MP: Read the values from Profiles/UserProfile/ja2_mp.ini MpIniExists(); vfs::PropertyContainer props; props.initFromIniFile( JA2MP_INI_FILENAME); props.getStringProperty( JA2MP_INI_INITIAL_SECTION, JA2MP_SERVER_IP, gzServerIPField, 16, "127.0.0.1"); props.getStringProperty( JA2MP_INI_INITIAL_SECTION, JA2MP_SERVER_PORT, gzServerPortField, 6, "60005"); props.getStringProperty( JA2MP_INI_INITIAL_SECTION, JA2MP_CLIENT_NAME, gzPlayerHandleField, 12, L"Player Name"); return( 1 ); } void SaveJoinSettings(bool ReSaving) { if (!ReSaving) { Get16BitStringFromField( 0, gzPlayerHandleField, 12 ); // these indexes are based on the order created Get16BitStringFromField( 1, gzServerIPField, 16 ); Get16BitStringFromField( 2, gzServerPortField, 6 ); } MpIniExists(); vfs::PropertyContainer props; props.initFromIniFile(JA2MP_INI_FILENAME); props.setStringProperty(JA2MP_INI_INITIAL_SECTION,JA2MP_SERVER_IP, gzServerIPField); props.setStringProperty(JA2MP_INI_INITIAL_SECTION,JA2MP_SERVER_PORT, gzServerPortField); props.setStringProperty(JA2MP_INI_INITIAL_SECTION,JA2MP_CLIENT_NAME, gzPlayerHandleField); s_ServerId.getServerId(vfs::Path(gzFileTransferDirectory), &props); props.writeToIniFile(JA2MP_INI_FILENAME,false); } bool ValidateJoinSettings(bool bSkipServerAddress, bool bSkipSyncDir) { // Check a Player name is entered Get16BitStringFromField( 0, gzPlayerHandleField, 12 ); // these indexes are based on the order created if (wcscmp(gzPlayerHandleField,L"")<=0) { DoMPJMessageBox( MSG_BOX_BASIC_STYLE, gzMPJScreenText[MPJ_HANDLE_INVALID], MP_JOIN_SCREEN, MSG_BOX_FLAG_OK, NULL ); return false; } if (!bSkipServerAddress) { // Verify the IP Address Get16BitStringFromField( 1, gzServerIPField, 16 ); // loop through octets and check int numOctets = 0; wchar_t* tok; tok = wcstok(gzServerIPField,L"."); while (tok != NULL) { numOctets++; INT32 oct = _wtoi(tok); // check for invalid conversion, ie alpha chars // wtoi returns 0 if it cant convert, but we need this value // therefore if tok <> 0 then it was a bad convert. if (oct == 0 && wcscmp(tok,L"0") != 0) { // force error numOctets=0; break; } if (oct < 0 || oct > 255) // allow 255 { // bad octet, error numOctets=0; break; } // get next octet tok = wcstok(NULL,L"."); } if (numOctets != 4) { // not a valid ip address DoMPJMessageBox( MSG_BOX_BASIC_STYLE, gzMPJScreenText[MPJ_SERVERIP_INVALID], MP_JOIN_SCREEN, MSG_BOX_FLAG_OK, NULL ); return false; } // Verify the Server Port Get16BitStringFromField( 2, gzServerPortField, 6 ); INT32 svrPort = _wtoi(gzServerPortField); if (svrPort < 1 || svrPort > 65535) { DoMPJMessageBox( MSG_BOX_BASIC_STYLE, gzMPJScreenText[MPJ_SERVERPORT_INVALID], MP_JOIN_SCREEN, MSG_BOX_FLAG_OK, NULL ); return false; } } if (!bSkipSyncDir) { if(vfs::OS::createRealDirectory(vfs::Path(L"Multiplayer"))) { vfs::OS::createRealDirectory(vfs::Path(L"Multiplayer/Servers")); } } return true; } UINT32 MPJoinScreenHandle( void ) { StartFrameBufferRender(); if( gfMPJScreenEntry ) { EnterMPJScreen(); gfMPJScreenEntry = FALSE; gfMPJScreenExit = FALSE; InvalidateRegion( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT ); } GetMPJScreenUserInput(); HandleMPJScreen(); // render buttons marked dirty MarkButtonsDirty( ); RenderButtons( ); // render text boxes RenderAllTextFields(); // textbox system call ExecuteBaseDirtyRectQueue(); EndFrameBufferRender(); // handle fades in and out if ( HandleFadeOutCallback( ) ) { ClearMainMenu(); return( gubMPJExitScreen ); } if ( HandleBeginFadeOut( gubMPJExitScreen ) ) { return( gubMPJExitScreen ); } if ( HandleFadeInCallback( ) ) { // Re-render the scene! RenderMPJScreen(); } if ( HandleBeginFadeIn( gubMPJExitScreen ) ) { } if( gfMPJScreenExit ) { ExitMPJScreen(); } return( gubMPJExitScreen ); } UINT32 MPJoinScreenShutdown( void ) { return( 1 ); } BOOLEAN EnterMPJScreen() { VOBJECT_DESC VObjectDesc; if( gfMPJButtonsAllocated ) return( TRUE ); SetCurrentCursorFromDatabase( CURSOR_NORMAL ); // load the Main trade screen backgroiund image VObjectDesc.fCreateFlags=VOBJECT_CREATE_FROMFILE; if (iResolution == 0) { FilenameForBPP("INTERFACE\\OptionsScreenBackGround.sti", VObjectDesc.ImageFile); } else if (iResolution == 1) { FilenameForBPP("INTERFACE\\OptionsScreenBackGround_800x600.sti", VObjectDesc.ImageFile); } else if (iResolution == 2) { FilenameForBPP("INTERFACE\\OptionsScreenBackGround_1024x768.sti", VObjectDesc.ImageFile); } CHECKF(AddVideoObject(&VObjectDesc, &guiMPJMainBackGroundImage )); //Join button giMPJoinBtnImage = LoadButtonImage("INTERFACE\\PreferencesButtons.sti", -1,0,-1,2,-1 ); guiMPJoinButton = CreateIconAndTextButton( giMPJoinBtnImage, gzMPJScreenText[MPJ_JOIN_TEXT], OPT_BUTTON_FONT, OPT_BUTTON_ON_COLOR, DEFAULT_SHADOW, OPT_BUTTON_OFF_COLOR, DEFAULT_SHADOW, TEXT_CJUSTIFIED, MPJ_BTN_JOIN_X, MPJ_BTN_JOIN_Y, BUTTON_TOGGLE, MSYS_PRIORITY_HIGH, DEFAULT_MOVE_CALLBACK, BtnMPJoinCallback); SpecifyButtonSoundScheme( guiMPJoinButton, BUTTON_SOUND_SCHEME_BIGSWITCH3 ); SpecifyDisabledButtonStyle( guiMPJoinButton, DISABLED_STYLE_NONE ); //Host button giMPJHostBtnImage = UseLoadedButtonImage( giMPJoinBtnImage, -1,1,-1,3,-1 ); guiMPJHostButton = CreateIconAndTextButton( giMPJHostBtnImage, gzMPJScreenText[MPJ_HOST_TEXT], OPT_BUTTON_FONT, OPT_BUTTON_ON_COLOR, DEFAULT_SHADOW, OPT_BUTTON_OFF_COLOR, DEFAULT_SHADOW, TEXT_CJUSTIFIED, MPJ_BTN_HOST_X, MPJ_BTN_HOST_Y, BUTTON_TOGGLE, MSYS_PRIORITY_HIGH, DEFAULT_MOVE_CALLBACK, BtnMPJHostCallback); SpecifyButtonSoundScheme( guiMPJHostButton, BUTTON_SOUND_SCHEME_BIGSWITCH3 ); SpecifyDisabledButtonStyle( guiMPJHostButton, DISABLED_STYLE_NONE ); //Cancel button giMPJCancelBtnImage = UseLoadedButtonImage( giMPJoinBtnImage, -1,1,-1,3,-1 ); guiMPJCancelButton = CreateIconAndTextButton( giMPJCancelBtnImage, gzMPJScreenText[MPJ_CANCEL_TEXT], OPT_BUTTON_FONT, OPT_BUTTON_ON_COLOR, DEFAULT_SHADOW, OPT_BUTTON_OFF_COLOR, DEFAULT_SHADOW, TEXT_CJUSTIFIED, MPJ_CANCEL_X, MPJ_BTN_JOIN_Y, BUTTON_TOGGLE, MSYS_PRIORITY_HIGH, DEFAULT_MOVE_CALLBACK, BtnMPJCancelCallback ); SpecifyButtonSoundScheme( guiMPJCancelButton, BUTTON_SOUND_SCHEME_BIGSWITCH3 ); // Initialise Text Boxes InitTextInputMode(); // API call to initialise text input mode for this screen // does not mean we are inputting text right away // Player Name field SetTextInputCursor( CUROSR_IBEAM_WHITE ); SetTextInputFont( (UINT16) FONT12ARIALFIXEDWIDTH ); //FONT12ARIAL //FONT12ARIALFIXEDWIDTH Set16BPPTextFieldColor( Get16BPPColor(FROMRGB( 0, 0, 0) ) ); SetBevelColors( Get16BPPColor(FROMRGB(136, 138, 135)), Get16BPPColor(FROMRGB(24, 61, 81)) ); SetTextInputRegularColors( FONT_WHITE, 2 ); SetTextInputHilitedColors( 2, FONT_WHITE, FONT_WHITE ); SetCursorColor( Get16BPPColor(FROMRGB(255, 255, 255) ) ); //AddUserInputField( NULL ); // API Call that sets a special input-handling routine and method for the TAB key //Add Player Name textbox AddTextInputField( MPJ_TXT_HANDLE_X, MPJ_TXT_HANDLE_Y, MPJ_TXT_HANDLE_WIDTH, MPJ_TXT_HANDLE_HEIGHT, MSYS_PRIORITY_HIGH+2, gzPlayerHandleField, 11, INPUTTYPE_ASCII );//23 //Add Server IP textbox AddTextInputField( MPJ_TXT_IP_X, MPJ_TXT_IP_Y, MPJ_TXT_IP_WIDTH, MPJ_TXT_IP_HEIGHT, MSYS_PRIORITY_HIGH+2, gzServerIPField, 15, INPUTTYPE_ASCII );//23 //Add Server Port textbox AddTextInputField( MPJ_TXT_PORT_X, MPJ_TXT_PORT_Y, MPJ_TXT_PORT_WIDTH, MPJ_TXT_PORT_HEIGHT, MSYS_PRIORITY_HIGH+2, gzServerPortField, 5, INPUTTYPE_ASCII );//23 SetActiveField( 0 ); // Playername textbox has focus //Reset the exit screen - screen the main game loop will call next iteration gubMPJExitScreen = MP_JOIN_SCREEN; //REnder the screen once so we can blt ot to ths save buffer RenderMPJScreen(); BlitBufferToBuffer(guiRENDERBUFFER, guiSAVEBUFFER, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT ); gfMPJButtonsAllocated = TRUE; return( TRUE ); } BOOLEAN ExitMPJScreen() { if( !gfMPJButtonsAllocated ) return( TRUE ); //Delete the main options screen background DeleteVideoObjectFromIndex( guiMPJMainBackGroundImage ); RemoveButton( guiMPJoinButton ); RemoveButton( guiMPJHostButton ); RemoveButton( guiMPJCancelButton ); UnloadButtonImage( giMPJCancelBtnImage ); UnloadButtonImage( giMPJHostBtnImage ); UnloadButtonImage( giMPJoinBtnImage ); // exit text input mode in this screen and clean up text boxes KillAllTextInputModes(); SetTextInputCursor( CURSOR_IBEAM ); gfMPJButtonsAllocated = FALSE; //If we are starting the game stop playing the music // <TODO> review this, i think MPJ_EXIT is the proceed mode... //if( gubMPJScreenHandler == MPJ_EXIT ) // SetMusicMode( MUSIC_NONE ); gfMPJScreenExit = FALSE; gfMPJScreenEntry = TRUE; return( TRUE ); } void HandleMPJScreen() { if( gubMPJScreenHandler != MPJ_NOTHING ) { switch( gubMPJScreenHandler ) { case MPJ_CANCEL: gubMPJExitScreen = MAINMENU_SCREEN; gfMPJScreenExit = TRUE; break; case MPJ_HOST: gubMPJExitScreen = MP_HOST_SCREEN; gfMPJScreenExit = TRUE; break; case MPJ_JOIN: { //if we are already fading out, get out of here if( gFadeOutDoneCallback != DoneFadeOutForExitMPJScreen ) { //Disable the ok button DisableButton( guiMPJoinButton ); DisableButton( guiMPJHostButton ); gFadeOutDoneCallback = DoneFadeOutForExitMPJScreen; FadeOutNextFrame( ); } break; } } gubMPJScreenHandler = MPJ_NOTHING; } if( gfReRenderMPJScreen ) { RenderMPJScreen(); gfReRenderMPJScreen = FALSE; } } void DrawHelpText() { int x = MPJ_LABEL_HANDLE_X; int y = iScreenHeightOffset + 60; int width = 640 - (2 * 50); int lineSpacing = 12; // Visit IRC DrawTextToScreen( gzMPJHelpText[ 0 ], x, y, width, FONT10ARIAL, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, CENTER_JUSTIFIED ); // Host y += 150; y+= lineSpacing; DrawTextToScreen( gzMPJHelpText[ 1 ], x, y, width, FONT12ARIAL, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); y+= lineSpacing + 5; DrawTextToScreen( gzMPJHelpText[ 2 ], x, y, width, FONT10ARIAL, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); y+= lineSpacing; DrawTextToScreen( gzMPJHelpText[ 3 ], x, y, width, FONT10ARIAL, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); y+= lineSpacing; DrawTextToScreen( gzMPJHelpText[ 4 ], x, y, width, FONT10ARIAL, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); y+= lineSpacing; DrawTextToScreen( gzMPJHelpText[ 5 ], x, y, width, FONT10ARIAL, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); // Join y += 20; y += lineSpacing; DrawTextToScreen( gzMPJHelpText[ 6 ], x, y, width, FONT12ARIAL, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); y += lineSpacing + 5; DrawTextToScreen( gzMPJHelpText[ 7 ], x, y, width, FONT10ARIAL, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); y += lineSpacing; DrawTextToScreen( gzMPJHelpText[ 8 ], x, y, width, FONT10ARIAL, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); y += lineSpacing; DrawTextToScreen( gzMPJHelpText[ 9 ], x, y, width, FONT10ARIAL, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); } BOOLEAN RenderMPJScreen() { HVOBJECT hPixHandle; //Get the main background screen graphic and blt it GetVideoObject(&hPixHandle, guiMPJMainBackGroundImage ); BltVideoObject(FRAME_BUFFER, hPixHandle, 0,0,0, VO_BLT_SRCTRANSPARENCY,NULL); //Shade the background ShadowVideoSurfaceRect( FRAME_BUFFER, iScreenWidthOffset, iScreenHeightOffset, iScreenWidthOffset + 640, iScreenHeightOffset + 480 ); //Display the title DrawTextToScreen( gzMPJScreenText[ MPJ_TITLE_TEXT ], MPJ_MAIN_TITLE_X, MPJ_MAIN_TITLE_Y, MPJ_MAIN_TITLE_WIDTH, MPJ_TITLE_FONT, MPJ_TITLE_COLOR, FONT_MCOLOR_BLACK, FALSE, CENTER_JUSTIFIED ); DrawHelpText(); // Player name text label DisplayWrappedString( MPJ_LABEL_HANDLE_X, MPJ_LABEL_HANDLE_Y, MPJ_LABEL_HANDLE_WIDTH, 2, MPJ_LABEL_TEXT_FONT, MPJ_LABEL_TEXT_COLOR, gzMPJScreenText[ MPJ_HANDLE_TEXT ], FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); // Server IP text label DisplayWrappedString( MPJ_LABEL_IP_X, MPJ_LABEL_IP_Y, MPJ_LABEL_IP_WIDTH, 2, MPJ_LABEL_TEXT_FONT, MPJ_LABEL_TEXT_COLOR, gzMPJScreenText[ MPJ_SERVERIP_TEXT ], FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); // Server Port text label DisplayWrappedString( MPJ_LABEL_PORT_X, MPJ_LABEL_PORT_Y, MPJ_LABEL_PORT_WIDTH, 2, MPJ_LABEL_TEXT_FONT, MPJ_LABEL_TEXT_COLOR, gzMPJScreenText[ MPJ_SERVERPORT_TEXT ], FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED ); return( TRUE ); } void GetMPJScreenUserInput() { InputAtom Event; while( DequeueEvent( &Event ) ) { // check if this event is swallowed by text input, otherwise process key if( !HandleTextInput( &Event ) && Event.usEvent == KEY_DOWN ) { switch( Event.usParam ) { case ESC: //Exit out of the screen gubMPJScreenHandler = MPJ_CANCEL; break; case ENTER: if (ValidateJoinSettings(false, false)) { SaveJoinSettings(false); gubMPJScreenHandler = MPJ_JOIN; // force client to use "MULTIPLAYER/SERVERS" path memset(gzFileTransferDirectory,0,100*sizeof(CHAR16)); wcscpy(gzFileTransferDirectory,L"multiplayer/servers"); } break; } } } } // CALLBACKS void BtnMPJoinCallback(GUI_BUTTON *btn,INT32 reason) { if(reason & MSYS_CALLBACK_REASON_LBUTTON_DWN ) { btn->uiFlags |= BUTTON_CLICKED_ON; InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY); } if(reason & MSYS_CALLBACK_REASON_LBUTTON_UP ) { btn->uiFlags &= (~BUTTON_CLICKED_ON ); if (ValidateJoinSettings(false, false)) { SaveJoinSettings(false); gubMPJScreenHandler = MPJ_JOIN; // force client to use "MULTIPLAYER/SERVERS" path memset(gzFileTransferDirectory,0,100*sizeof(CHAR16)); wcscpy(gzFileTransferDirectory,L"multiplayer/servers"); } InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY); } } void BtnMPJHostCallback(GUI_BUTTON *btn,INT32 reason) { if(reason & MSYS_CALLBACK_REASON_LBUTTON_DWN ) { btn->uiFlags |= BUTTON_CLICKED_ON; InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY); } if(reason & MSYS_CALLBACK_REASON_LBUTTON_UP ) { btn->uiFlags &= (~BUTTON_CLICKED_ON ); if (ValidateJoinSettings(true, false)) { SaveJoinSettings(false); gubMPJScreenHandler = MPJ_HOST; } InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY); } } void BtnMPJCancelCallback(GUI_BUTTON *btn,INT32 reason) { if(reason & MSYS_CALLBACK_REASON_LBUTTON_DWN ) { btn->uiFlags |= BUTTON_CLICKED_ON; InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY); } if(reason & MSYS_CALLBACK_REASON_LBUTTON_UP ) { btn->uiFlags &= (~BUTTON_CLICKED_ON ); gubMPJScreenHandler = MPJ_CANCEL; InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY); } } BOOLEAN DoMPJMessageBox( UINT8 ubStyle, const STR16 zString, UINT32 uiExitScreen, UINT16 usFlags, MSGBOX_CALLBACK ReturnCallback ) { SGPRect CenteringRect= {0, 0, SCREEN_WIDTH-1, SCREEN_HEIGHT-1 }; // do message box and return giMPJMessageBox = DoMessageBox( ubStyle, zString, uiExitScreen, ( UINT16 ) ( usFlags| MSG_BOX_FLAG_USE_CENTERING_RECT ), ReturnCallback, &CenteringRect ); // send back return state return( ( giMPJMessageBox != -1 ) ); } void DoneFadeOutForExitMPJScreen( void ) { // As we bypassed the GIO screen, set up some game options for multiplayer here is_networked = true; is_host = false; // we want to be a client, not we ARE a client yet (is_client) auto_retry = true; giNumTries = 5; // set up and initialise a new game on the client InitNewGame(false); SetPendingNewScreen( MP_CONNECT_SCREEN ); if (is_networked) gGameOptions.fTurnTimeLimit = TRUE; else gGameOptions.fTurnTimeLimit = FALSE; // Bobby Rays - why would we want anything less than the best gGameOptions.ubBobbyRay = BR_AWESOME; gubMPJExitScreen = MP_CONNECT_SCREEN; ExitMPJScreen(); // cleanup please, if we called a fadeout then we didnt do it above SetCurrentCursorFromDatabase( VIDEO_NO_CURSOR ); } void DoneFadeInForExitMPJScreen( void ) { SetCurrentCursorFromDatabase( VIDEO_NO_CURSOR ); }
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 803 ] ] ]
afb48bbf9772b91513e801eecc7f701a5ed4f761
822ab63b75d4d4e2925f97b9360a1b718b5321bc
/pagecurl/dpageturneffect.h
b9a6031c0af5e1a8521e8699d2875d6211e8efec
[]
no_license
sriks/decii
71e4becff5c30e77da8f87a56383e02d48b78b28
02c58fbaea69c2448249710d13f2e774762da2c3
refs/heads/master
2020-05-17T23:03:27.822905
2011-12-16T07:29:38
2011-12-16T07:29:38
32,251,281
0
0
null
null
null
null
UTF-8
C++
false
false
679
h
#ifndef DPAGETURNEFFECT_H #define DPAGETURNEFFECT_H #include <QGraphicsView> class QGraphicsPixmapItem; class DPageCurl; class DGraphicsLayer; class DPageTurnEffect : public QGraphicsView { public: DPageTurnEffect(QObject* parent=0); void setWidget(QWidget* hostWidget); void startEffect(); void testAnimation(); protected: void timerEvent(QTimerEvent *event); private: void makeTransparent(); private: DPageCurl* mPageCurl; QGraphicsPixmapItem* mPagePixmap; QGraphicsPixmapItem* mCurlPixmap; DGraphicsLayer* mCurlLayer; DGraphicsLayer* mPageCutLayer; int mTimerId; }; #endif // DPAGETURNEFFECT_H
[ "srikanthsombhatla@016151e7-202e-141d-2e90-f2560e693586" ]
[ [ [ 1, 30 ] ] ]
f4d3b7dedb4e5b86d0297ee6811288493a84790f
960d6f5c4195a18f795f741c5d2d484f26482c0c
/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp
8687c2b699451636374e6b724036450efb92dfac
[]
no_license
Bootz/TrilliumEMU-1
ec4100d345cc28171e52d60f092ebd39298c40b0
961bfa5d9b0e028d6d89cc238ed8db78a46c69f4
refs/heads/master
2020-12-25T04:30:12.412196
2011-11-25T10:11:04
2011-11-25T10:11:04
2,769,808
0
0
null
null
null
null
UTF-8
C++
false
false
166,391
cpp
/* * Copyright (C) 2005 - 2011 MaNGOS <http://www.getmangos.org/> * * Copyright (C) 2008 - 2011 TrilliumCore <http://www.trinitycore.org/> * * Copyright (C) 2011 TrilliumEMU <http://www.arkania.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ObjectMgr.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "SpellAuraEffects.h" #include "icecrown_citadel.h" #include "Group.h" #include "MapManager.h" #include "Vehicle.h" #define GOSSIP_MENU 10700 #define GOSSIP_START_EVENT "We are prepared, Highlord. Let us battle for the fate of Azeroth! For the light of dawn!" enum eAchievements { ACHIEV_BEEN_WAITING_A_LONG_TIME_FOR_THIS_10 = 4601, ACHIEV_BEEN_WAITING_A_LONG_TIME_FOR_THIS_25 = 4621, ACHIEV_NECK_DEEP_IN_VILE_10 = 4581, ACHIEV_NECK_DEEP_IN_VILE_25 = 4622, ACHIEV_THE_FROZEN_THRONE_10 = 4530, ACHIEV_THE_FROZEN_THRONE_25 = 4597 }; enum eEnums { SOUND_ENDING_7_KING = 17360, MOVIE_ID_ARTHAS_DEATH = 16 }; enum Yells { SAY_INTRO_1_KING = -1810001, SAY_INTRO_2_TIRION = -1810002, SAY_INTRO_3_KING = -1810003, SAY_INTRO_4_TIRION = -1810004, SAY_INTRO_5_KING = -1810005, SAY_AGGRO = -1810006, SAY_REMORSELESSS_WINTER = -1810007, SAY_RANDOM_1 = -1810008, SAY_RANDOM_2 = -1810009, SAY_KILL_1 = -1810010, SAY_KILL_2 = -1810011, SAY_BERSERK = -1810012, SAY_ENDING_1_KING = -1810013, SAY_ENDING_2_KING = -1810014, SAY_ENDING_3_KING = -1810015, SAY_ENDING_4_KING = -1810016, SAY_ENDING_5_TIRION = -1810017, SAY_ENDING_6_KING = -1810018, SAY_ENDING_8_TIRION = -1810020, SAY_ENDING_9_FATHER = -1810021, SAY_ENDING_10_TIRION = -1810022, SAY_ENDING_11_FATHER = -1810023, SAY_ENDING_12_KING = -1810024, SAY_DEATH_KING = -1810025, SAY_ESCAPE_FROSTMOURNE = -1810026, SAY_HARVEST_SOUL = -1810027, SAY_DEVOURED_FROSTMOURNE = -1810028, SAY_SUMMON_VALKYR = -1810029, SAY_BROKEN_ARENA = -1810030, SAY_10_PERCENT = -1810031, SAY_EMOTE_DEFILE = -1810032, }; enum ePhases { PHASE_1 = 1, PHASE_2_TRANSITION, PHASE_3, PHASE_4_TRANSITION, PHASE_5, PHASE_6_ENDING }; enum eEvents { // Lich King EVENT_SPEECH = 1, EVENT_BERSERK = 2, EVENT_CHECK_ALIVE_PLAYERS = 3, EVENT_SUMMON_SHAMBLING_HORROR = 4, EVENT_SUMMON_DRUDGE_GHOULS = 5, EVENT_INFEST = 6, EVENT_NECROTIC_PLAGUE = 7, EVENT_SHADOW_TRAP = 8, //Transition phase events EVENT_SUMMON_RAGING_SPIRIT = 9, EVENT_SUMMON_ICE_SPHERE = 10, EVENT_TRANSITION_PHASE_END = 11, EVENT_PAIN_AND_SUFFERING = 12, //Phase three events EVENT_SUMMON_VAL_KYR_SHADOWGUARD = 13, EVENT_DEFILE = 14, EVENT_SOUL_REAPER = 15, //Phase five events EVENT_SUMMON_VILE_SPIRITS = 16, EVENT_HARVEST_SOUL = 17, EVENT_KILL_FROSTMOURNE_PLAYERS = 18, // Valkyr Shadowguard EVENT_MOVE_TO_PLATFORM_EDGE = 19, EVENT_SIPHON_LIFE = 20, EVENT_CHECK_AT_PLATFORM_EDGE = 21, EVENT_CHARGE_PLAYER = 22, // Vile Spirit EVENT_BECOME_ACTIVE = 23, EVENT_DESPAWN = 24, EVENT_MOVE_RANDOM = 25, EVENT_CHECK_PLAYER_IN_FROSTMOURNE_ROOM = 26, // Shambling Horror EVENT_ENRAGE = 27, EVENT_SHOCKWAVE = 28, // Raging Spirit EVENT_SOUL_SHRIEK = 29, // Ice Sphere EVENT_MOVE_FORWARD = 30, EVENT_ACTIVATE = 31, // Spirit Warden EVENT_SOUL_RIP = 32, EVENT_DESTROY_SOUL = 33, EVENT_CHECK_SOUL_RIP_DISPELLED = 34, // Terenas Menethil EVENT_GREET_PLAYER = 35, //Yell "You have come to bring Arthas to justice? To see the Lich King destroyed?" EVENT_ENCOURAGE_PLAYER_TO_ESCAPE = 36, //Yell "First, you must escape Frostmourne's hold or be damned as I am; trapped within this cursed blade for all eternity." EVENT_ASK_PLAYER_FOR_AID = 37, //Yell "Aid me in destroying these tortured souls! Together we will loosen Frostmourne's hold and weaken the Lich King from within!" EVENT_CHECK_SPIRIT_WARDEN_HEALTH = 38, EVENT_RESTART_COMBAT_MOVEMENT = 39, }; enum Spells { SPELL_DEATH_GRIP = 49560, SPELL_SUMMON_SHAMBLING_HORROR = 70372, SPELL_SUMMON_DRUDGE_GHOULS = 70358, SPELL_SUMMON_ICE_SPEHERE = 69104, SPELL_SUMMON_RAGING_SPIRIT = 69200, SPELL_SUMMON_VALKYR = 74361, SPELL_SUMMON_DEFILE = 72762, SPELL_SUMMON_VILE_SPIRIT = 70498, SPELL_SUMMON_BROKEN_FROSTMOURNE = 73017, SPELL_SUMMON_SHADOW_TRAP = 73539, SPELL_SHADOW_TRAP_INTRO = 73530, SPELL_SHADOW_TRAP_PERIODIC = 73525, SPELL_SHADOW_TRAP_EFFECT = 73529, SPELL_INFEST_10N = 70541, SPELL_INFEST_10H = 73780, SPELL_INFEST_25N = 73779, SPELL_INFEST_25H = 73781, SPELL_NECROTIC_PLAGUE_10N = 70337, SPELL_NECROTIC_PLAGUE_10H = 73913, SPELL_NECROTIC_PLAGUE_25N = 73912, SPELL_NECROTIC_PLAGUE_25H = 73914, SPELL_NECROTIC_PLAGUE_IMMUNITY = 72846, SPELL_NECROTIC_PLAGUE_EFFECT = 70338, SPELL_PLAGUE_SIPHON = 74074, SPELL_REMORSELESS_WINTER_10N = 72259, SPELL_REMORSELESS_WINTER_10H = 74274, SPELL_REMORSELESS_WINTER_25N = 74273, SPELL_REMORSELESS_WINTER_25H = 74275, SPELL_REMORSELESS_WINTER_DAMAGE = 68983, SPELL_PAIN_AND_SUFFERING_10N = 72133, SPELL_PAIN_AND_SUFFERING_10H = 73789, SPELL_PAIN_AND_SUFFERING_25N = 73788, SPELL_PAIN_AND_SUFFERING_25H = 73790, SPELL_WINGS_OF_THE_DAMNED = 74352, SPELL_SOUL_REAPER_10N = 69409, SPELL_SOUL_REAPER_10H = 73798, SPELL_SOUL_REAPER_25N = 73797, SPELL_SOUL_REAPER_25H = 73799, SPELL_SOUL_REAPER_HASTE_AURA = 69410, SPELL_HARVEST_SOUL_TELEPORT = 71372, SPELL_HARVEST_SOULS_10N = 68980, SPELL_HARVEST_SOULS_10H = 74296, SPELL_HARVEST_SOULS_25N = 74325, SPELL_HARVEST_SOULS_25H = 74297, SPELL_HARVESTED_SOUL_NORMAL = 74321, SPELL_HARVESTED_SOUL_HEROIC = 74323, SPELL_HARVEST_SOUL_HEROIC_FROSTMOURNE_PLAYER_DEBUFF = 73655, SPELL_HARVESTED_SOUL_FROSTMOURNE_PLAYER_BUFF = 74322, SPELL_FROSTMOURNE_ROOM_TELEPORT_VISUAL = 73078, SPELL_QUAKE = 72262, SPELL_RAISE_DEAD = 71769, SPELL_RAISE_DEAD_EFFECT = 72376, SPELL_BROKEN_FROSTMOURNE = 72398, SPELL_BOOM_VISUAL = 72726, SPELL_ICEBLOCK_TRIGGER = 71614, SPELL_TIRION_LIGHT = 71797, SPELL_FROSTMOURNE_TRIGGER = 72405, SPELL_DISENGAGE = 61508, SPELL_FURY_OF_FROSTMOURNE = 72350, SPELL_REVIVE = 72429, SPELL_REVIVE_EFFECT = 72423, SPELL_CLONE_PLAYER = 57507, SPELL_DEFILE = 72743, SPELL_DEFILE_DAMAGE = 72754, SPELL_DEFILE_INCREASE = 72756, SPELL_ICE_PULSE = 69091, SPELL_ICE_BURST = 69108, SPELL_LIFE_SIPHON = 73783, SPELL_SPIRIT_BURST = 70503, SPELL_VILE_SPIRIT_DISTANCE_CHECK = 70502, SPELL_ICE_BURST_DISTANCE_CHECK = 69109, SPELL_VILE_SPIRIT_ACTIVE = 72130, SPELL_RAGING_VISUAL = 69198, SPELL_REMOVE_WEAPON = 72399, SPELL_DROP_FROSTMOURNE = 73017, SPELL_SUMMON_FROSTMOURNE_TRIGGER = 72407, SPELL_WMO_INTACT = 50176, SPELL_WMO_DESTROY = 50177, SPELL_WMO_REBUILD = 50178, SPELL_SUMMON_MENETHIL = 72420, SPELL_MENETHIL_VISUAL = 72372, SPELL_VALKYR_CARRY_CAN_CAST = 74506, SPELL_VALKYR_GRAB_PLAYER = 68985, SPELL_RIDE_VEHICLE = 46598, SPELL_VALKYR_TARGET_SEARCH = 69030, SPELL_VALKYR_CHARGE = 74399, SPELL_VALKYR_EJECT_PASSENGER = 68576, SPELL_LIGHTS_BLESSING = 71773, SPELL_EMOTE_SHOUT = 73213, SPELL_RAGING_GHOUL_VISUAL = 69636, SPELL_RISEN_WITCH_DOCTOR_SPAWN = 69639, SPELL_ICE_SPHERE_VISUAL = 69090, SPELL_TIRION_JUMP = 71811, SPELL_CANT_RESSURECT_AURA = 72431, SPELL_FROSTMOURNE_DESPAWN = 72726, SPELL_SUMMON_FROSTMOURNE = 74081, SPELL_SOUL_EFFECT = 72305, SPELL_IN_FROSTMOURNE_ROOM = 74276, SPELL_VILE_SPIRIT_TARGET_SEARCH = 70501, SPELL_SOUL_RIP = 69397, SPELL_DESTROY_SOUL = 74086, SPELL_DARK_HUNGER = 69383, SPELL_DARK_HUNGER_HEAL_EFFECT = 69384, SPELL_LIGHT_S_FAVOR = 69382, SPELL_RESTORE_SOUL = 72595, SPELL_FEIGN_DEATH = 5384, SPELL_SHOCKWAVE = 72149, SPELL_ENRAGE = 72143, SPELL_FRENZY = 28747, SPELL_SOUL_SHRIEK = 69242, SPELL_FURY_OF_FROSTMOURNE_NORES = 72351, SPELL_KNOCKDOWN = 68848, }; enum eActions { ACTION_PHASE_SWITCH_1 = 1, //phase 1 and 3 ACTION_PHASE_SWITCH_2, //phase 2 and 4 ACTION_START_EVENT, ACTION_RESET, ACTION_CANCEL_ALL_TRANSITION_EVENTS, ACTION_DESPAWN, ACTION_CHARGE_PLAYER, ACTION_PREPARE_FROSTMOURNE_ROOM, ACTION_ATTACK_SPIRIT_WARDEN, ACTION_ATTACK_TERENAS_FIGHTER, }; enum eSetGuid { TYPE_VICTIM = 1 }; enum ePoints { POINT_MOVE_NEAR_RANDOM = 1, POINT_START_EVENT_1 = 3659700, POINT_PLATFORM_CENTER = 3659701, POINT_PLATFORM_END = 3659702, POINT_VALKYR_END = 3659703, POINT_VALKYR_ZET = 3659704, POINT_VALKYR_CONTINUE_FLYING = 3659705 }; enum eLKData { DATA_PHASE = 2 }; struct Position StartEvent[]= { {465.0731f, -2123.473f, 1040.8569f}, {462.8351f, -2123.673f, 1040.9082f}, {461.5851f, -2123.673f, 1041.4082f}, {445.5851f, -2123.673f, 1056.1582f}, {436.0851f, -2123.673f, 1064.6582f} }; struct Position MovePos[]= { {459.039f, -2124.21f, 1040.860f, 0.0f}, // move {503.156f, -2124.51f, 1040.860f, 0.0f}, // move center X: 505.2118 Y: -2124.353 Z: 840.9403 {490.110f, -2124.98f, 1040.860f, 0.0f}, // move tirion frostmourne {467.069f, -2123.58f, 1040.857f, 0.0f}, // move tirion attack {498.004f, 2201.57f, 1046.093f, 0.0f}, // move valkyr {489.297f, -2124.84f, 1040.857f, 0.0f}, //start event tirion move 1 {503.682f, -2126.63f, 1040.940f, 0.0f}, //boss escapes after wipe {508.989f, -2124.55f, 1045.356f, 0.0f}, //boss levitates above the frostmourne {505.212f, -2124.35f, 1040.94f, 3.14159f}, {491.759f, -2124.86f, 1040.86f, 0.0f}, // tirion talk position {517.482f, -2124.91f, 1040.86f, 0.0f}, // Jump position {529.413f, -2124.94f, 1040.86f, 0.0f}, // Knockback position }; struct Position FrostmourneRoom[] = { {520.0f, -2524.0f, 1051.0f, 0.0f}, //Place where player is teleported to {539.1f, -2513.0f, 1042.6f, 2.8f}, //Home position of the Spirit Warden {508.4f, -2506.2f, 1042.6f, 6.0f}, //Home position of Terenas Menethil }; typedef std::list<Player*> TPlayerList; TPlayerList GetPlayersInTheMap(Map *pMap) { TPlayerList players; const Map::PlayerList &PlayerList = pMap->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* player = i->getSource()) players.push_back(player); return players; } TPlayerList GetAttackablePlayersInTheMap(Map *pMap) { TPlayerList players = GetPlayersInTheMap(pMap); for (TPlayerList::iterator it = players.begin(); it != players.end();) if (!(*it)->isTargetableForAttack()) players.erase(it++); else ++it; return players; } Player *SelectRandomPlayerFromList(TPlayerList &players) { if (players.empty()) return NULL; TPlayerList::iterator it = players.begin(); std::advance(it, urand(0, players.size()-1)); return *it; } Player *SelectRandomPlayerInTheMap(Map *pMap) { TPlayerList players = GetPlayersInTheMap(pMap); return SelectRandomPlayerFromList(players); } Player *SelectRandomAttackablePlayerInTheMap(Map *pMap) { TPlayerList players = GetAttackablePlayersInTheMap(pMap); return SelectRandomPlayerFromList(players); } uint32 GetPhase(const EventMap &em) { switch (em.GetPhaseMask()) { case 0x01: return 0; case 0x02: return 1; case 0x04: return 2; case 0x08: return 3; case 0x10: return 4; case 0x20: return 5; case 0x40: return 6; case 0x80: return 7; default: return 0; } } class boss_the_lich_king : public CreatureScript { public: boss_the_lich_king() : CreatureScript("boss_the_lich_king") { } struct boss_the_lich_kingAI : public BossAI { boss_the_lich_kingAI(Creature* creature) : BossAI(creature, DATA_THE_LICH_KING), summons(me) { instance = me->GetInstanceScript(); } uint32 GetData(uint32 dataId) { if (dataId == DATA_PHASE) return GetPhase(events); return BossAI::GetData(dataId); } void Reset() { me->SetReactState(REACT_PASSIVE); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); SetEquipmentSlots(false, 49706, EQUIP_NO_CHANGE, EQUIP_NO_CHANGE); if(me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE) me->GetMotionMaster()->MovementExpired(); if (instance) instance->SetBossState(DATA_THE_LICH_KING, NOT_STARTED); me->SetReactState(REACT_PASSIVE); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); if (Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) { tirion->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } uiStage = 1; } void EnterEvadeMode() { events.Reset(); BossAI::EnterEvadeMode(); me->SetReactState(REACT_PASSIVE); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); if (Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) { tirion->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } } void EnterCombat(Unit* /*pWho*/) { if (uiStage > 1) return; instance->SetData(DATA_BEEN_WAITING_ACHIEVEMENT, NOT_STARTED); instance->SetData(DATA_NECK_DEEP_ACHIEVEMENT, DONE); uiEndingTimer = 1000; uiTirionGUID = 0; isSwitching = false; imSummoning = false; isAboutToDie = false; events.Reset(); events.SetPhase(PHASE_1); events.ScheduleEvent(EVENT_BERSERK, 900000, PHASE_1); events.ScheduleEvent(EVENT_BERSERK, 900000, PHASE_2_TRANSITION); events.ScheduleEvent(EVENT_BERSERK, 900000, PHASE_3); events.ScheduleEvent(EVENT_BERSERK, 900000, PHASE_4_TRANSITION); events.ScheduleEvent(EVENT_BERSERK, 900000, PHASE_5); events.ScheduleEvent(EVENT_CHECK_ALIVE_PLAYERS, 5000, PHASE_1); events.ScheduleEvent(EVENT_CHECK_ALIVE_PLAYERS, 5000, PHASE_2_TRANSITION); events.ScheduleEvent(EVENT_CHECK_ALIVE_PLAYERS, 5000, PHASE_3); events.ScheduleEvent(EVENT_CHECK_ALIVE_PLAYERS, 5000, PHASE_4_TRANSITION); events.ScheduleEvent(EVENT_CHECK_ALIVE_PLAYERS, 5000, PHASE_5); events.ScheduleEvent(EVENT_SUMMON_DRUDGE_GHOULS, 10000, 0, PHASE_1); events.ScheduleEvent(EVENT_INFEST, 5000, 0, PHASE_1); events.ScheduleEvent(EVENT_SUMMON_SHAMBLING_HORROR, 20000, 0, PHASE_1); events.ScheduleEvent(EVENT_NECROTIC_PLAGUE, 30000, 0, PHASE_1); if (IsHeroic()) events.ScheduleEvent(EVENT_SHADOW_TRAP, 10000, 0, PHASE_1); //DoScriptText(SAY_AGGRO, me); DoCast(me, SPELL_NECROTIC_PLAGUE_IMMUNITY); if(instance) uiTirionGUID = instance->GetData64(GUID_TIRION); if (instance) { instance->SetBossState(DATA_THE_LICH_KING, IN_PROGRESS); instance->SetData(DATA_THE_LICH_KING, IN_PROGRESS); } } void Cleanup() { instance->DoRemoveAurasDueToSpellOnPlayers(RAID_MODE(SPELL_INFEST_10N, SPELL_INFEST_25N, SPELL_INFEST_10H, SPELL_INFEST_25H)); instance->DoCastSpellOnPlayers(FROZEN_THRONE_TELEPORT); instance->DoRemoveAurasDueToSpellOnPlayers(RAID_MODE(SPELL_NECROTIC_PLAGUE_10N, SPELL_NECROTIC_PLAGUE_25N, SPELL_NECROTIC_PLAGUE_10H, SPELL_NECROTIC_PLAGUE_25H)); instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_NECROTIC_PLAGUE_EFFECT); instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_ICE_PULSE); instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_IN_FROSTMOURNE_ROOM); summons.DespawnAll(); } void JustDied(Unit* /*killer*/) { if (!instance) return; instance->SetBossState(DATA_THE_LICH_KING, DONE); instance->SetData(DATA_THE_LICH_KING, DONE); //instance->DoCompleteAchievement(RAID_MODE<uint32>(ACHIEV_THE_FROZEN_THRONE_10, ACHIEV_BANE_OF_THE_FALLEN_KING, ACHIEV_THE_FROZEN_THRONE_25, ACHIEV_THE_LIGHT_OF_DAWN)); if (instance->GetData(DATA_BEEN_WAITING_ACHIEVEMENT) == DONE) instance->DoCompleteAchievement(RAID_MODE(ACHIEV_BEEN_WAITING_A_LONG_TIME_FOR_THIS_10,ACHIEV_BEEN_WAITING_A_LONG_TIME_FOR_THIS_25)); if (instance->GetData(DATA_NECK_DEEP_ACHIEVEMENT) == DONE) instance->DoCompleteAchievement(RAID_MODE(ACHIEV_NECK_DEEP_IN_VILE_10,ACHIEV_NECK_DEEP_IN_VILE_25)); Cleanup(); TPlayerList players = GetPlayersInTheMap(me->GetMap()); for (TPlayerList::iterator it = players.begin(); it != players.end(); ++it) if ((*it)->isAlive()) (*it)->SendMovieStart(MOVIE_ID_ARTHAS_DEATH); if(Creature* father = me->FindNearestCreature(NPC_TERENAS_MENETHIL, 25.0f, true)) father->SetVisible(false); if(Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) { tirion->GetMotionMaster()->MovePoint(0, MovePos[1]); tirion->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_NONE); tirion->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); tirion->SetReactState(REACT_PASSIVE); tirion->RemoveAllAuras(); } } void MovementInform(uint32 type, uint32 id) { if (type != POINT_MOTION_TYPE) return; if (instance->GetBossState(DATA_THE_LICH_KING) == DONE) return; switch(id) { case POINT_PLATFORM_CENTER: { me->GetMotionMaster()->MovementExpired(); uint32 curPhase = GetPhase(events); events.ScheduleEvent(EVENT_PAIN_AND_SUFFERING, 2500+2000, 0, curPhase); events.ScheduleEvent(EVENT_SUMMON_ICE_SPHERE, 2500+7000, 0, curPhase); events.ScheduleEvent(EVENT_SUMMON_RAGING_SPIRIT, 6000, 0, curPhase); events.ScheduleEvent(EVENT_TRANSITION_PHASE_END, 60000, 0, curPhase); DoScriptText(SAY_REMORSELESSS_WINTER, me); DoCast(me, RAID_MODE(SPELL_REMORSELESS_WINTER_10N, SPELL_REMORSELESS_WINTER_25N, SPELL_REMORSELESS_WINTER_10H, SPELL_REMORSELESS_WINTER_25H)); break; } } } void JustReachedHome() { if (!instance) return; instance->SetBossState(DATA_THE_LICH_KING, FAIL); instance->SetData(DATA_THE_LICH_KING, FAIL); Cleanup(); if (Creature *tirion = ObjectAccessor::GetCreature(*me, instance->GetData64(GUID_TIRION))) tirion->AI()->DoAction(ACTION_RESET); events.Reset(); } void KilledUnit(Unit* victim) { if (GetPhase(events) != PHASE_6_ENDING && victim->GetTypeId() == TYPEID_PLAYER) DoScriptText(RAND(SAY_KILL_1, SAY_KILL_2), me); } void JustSummoned(Creature* summoned) { summons.Summon(summoned); switch(summoned->GetEntry()) { case NPC_RAGING_SPIRIT: summoned->CastSpell(summoned, SPELL_NECROTIC_PLAGUE_IMMUNITY, true); if (Unit *target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true)) { target->CastSpell(summoned, SPELL_RAGING_VISUAL, true); summoned->AI()->AttackStart(target); // Hack Fix: If we cloned a non player unit, the model would be wrong // so set it to a generic one if(target->GetTypeId() != TYPEID_PLAYER) target->SetDisplayId(278); } break; case NPC_DEFILE: { Position pos; summoned->GetPosition(&pos); pos.m_positionZ += 0.75f; summoned->UpdatePosition(pos, true); summoned->SetInCombatWithZone(); break; } case NPC_TRIGGER: summoned->AI()->AttackStart(me); summoned->SetVisible(false); summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); break; case NPC_FROSTMOURNE_TRIGGER: { summoned->CastSpell(summoned, SPELL_BROKEN_FROSTMOURNE, false); summoned->CastSpell(summoned, SPELL_FROSTMOURNE_TRIGGER, false); //summoned->SetVisible(false); break; } case NPC_TERENAS_MENETHIL: { DoScriptText(SAY_ENDING_9_FATHER, summoned); summoned->CastSpell(summoned, SPELL_MENETHIL_VISUAL, true); summoned->CastSpell(summoned, SPELL_REVIVE, true); TPlayerList players = GetPlayersInTheMap(me->GetMap()); for (TPlayerList::iterator it = players.begin(); it != players.end(); ++it) summoned->CastSpell(*it, SPELL_REVIVE_EFFECT, true); break; } case NPC_VALKYR: { if (Unit *valkyrTarget = SelectTarget(SELECT_TARGET_RANDOM, 1, 100.0f, true)) summoned->AI()->SetGUID(valkyrTarget->GetGUID(), TYPE_VICTIM); else { //There is no target - unsummon valkyr summoned->Kill(summoned); summoned->DespawnOrUnsummon(); } break; } case NPC_DRUDGE_GHOUL: summoned->CastSpell(summoned, SPELL_RAGING_GHOUL_VISUAL, true); if (Unit* pVictim = SelectTarget(SELECT_TARGET_RANDOM)) summoned->AI()->AttackStart(pVictim); break; case NPC_SHAMBLING_HORROR: summoned->CastSpell(summoned, SPELL_RISEN_WITCH_DOCTOR_SPAWN, true); if (Unit* pVictim = SelectTarget(SELECT_TARGET_RANDOM)) summoned->AI()->AttackStart(pVictim); break; } } void DoAction(const int32 action) { switch(action) { case ACTION_PREPARE_FROSTMOURNE_ROOM: { Creature *terenasFighter = ObjectAccessor::GetCreature(*me, instance->GetData64(GUID_TERENAS_FIGHTER)); Creature *spiritWarden = ObjectAccessor::GetCreature(*me, instance->GetData64(GUID_SPIRIT_WARDEN)); if (terenasFighter && spiritWarden) { terenasFighter->Respawn(); spiritWarden->Respawn(); terenasFighter->AI()->DoAction(ACTION_ATTACK_SPIRIT_WARDEN); spiritWarden->AI()->DoAction(ACTION_ATTACK_TERENAS_FIGHTER); events.ScheduleEvent(EVENT_KILL_FROSTMOURNE_PLAYERS, 60000, 0, PHASE_5); } break; } case ACTION_CANCEL_ALL_TRANSITION_EVENTS: { events.CancelEvent(EVENT_PAIN_AND_SUFFERING); events.CancelEvent(EVENT_SUMMON_ICE_SPHERE); events.CancelEvent(EVENT_SUMMON_RAGING_SPIRIT); events.CancelEvent(EVENT_TRANSITION_PHASE_END); break; } case ACTION_PHASE_SWITCH_1: { uint32 nextPhase = PHASE_2_TRANSITION; if (GetPhase(events) == PHASE_3) nextPhase = PHASE_4_TRANSITION; events.SetPhase(nextPhase); me->SetReactState(REACT_PASSIVE); me->AttackStop(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE); SetCombatMovement(false); me->SetInCombatWithZone(); me->GetMotionMaster()->MovePoint(POINT_PLATFORM_CENTER, MovePos[1]); break; } case ACTION_PHASE_SWITCH_2: { if (GetPhase(events) == PHASE_2_TRANSITION) { events.SetPhase(PHASE_3); events.ScheduleEvent(EVENT_SUMMON_VAL_KYR_SHADOWGUARD, 13000, 0, PHASE_3); events.ScheduleEvent(EVENT_SOUL_REAPER, 35000, 0, PHASE_3); events.ScheduleEvent(EVENT_DEFILE, 32000, 0, PHASE_3); events.ScheduleEvent(EVENT_INFEST, 8000, 0, PHASE_3); } if (GetPhase(events) == PHASE_4_TRANSITION) { events.SetPhase(PHASE_5); events.ScheduleEvent(EVENT_SUMMON_VILE_SPIRITS, 15000, 0, PHASE_5); events.ScheduleEvent(EVENT_SOUL_REAPER, 35000, 0, PHASE_5); events.ScheduleEvent(EVENT_DEFILE, 32000, 0, PHASE_5); events.ScheduleEvent(EVENT_HARVEST_SOUL, 7000, 0, PHASE_5); } me->SetReactState(REACT_AGGRESSIVE); me->RemoveAurasDueToSpell(RAID_MODE(SPELL_PAIN_AND_SUFFERING_10N, SPELL_PAIN_AND_SUFFERING_25N, SPELL_PAIN_AND_SUFFERING_10H, SPELL_PAIN_AND_SUFFERING_25H)); DoZoneInCombat(me); SetCombatMovement(true); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE); isSwitching = false; break; } } } void DamageTaken(Unit* /*done_by*/, uint32& /*damage*/) { switch(GetPhase(events)) { case PHASE_1: if(!HealthAbovePct(71) && !isSwitching) { isSwitching = true; DoAction(ACTION_PHASE_SWITCH_1); break; } case PHASE_3: if(!HealthAbovePct(41) && !isSwitching) { isSwitching = true; DoAction(ACTION_PHASE_SWITCH_1); break; } case PHASE_5: if(!HealthAbovePct(11) && !isSwitching) { isSwitching = true; me->SummonCreature(NPC_TRIGGER, MovePos[6], TEMPSUMMON_CORPSE_DESPAWN, 900000); summons.DespawnAll(); events.Reset(); events.SetPhase(PHASE_6_ENDING); } break; case PHASE_6_ENDING: if(HealthBelowPct(1) && !isAboutToDie) { if (Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) { isAboutToDie = true; me->RemoveAurasDueToSpell(34873); me->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), tirion->GetPositionZ()); me->UpdatePosition(me->GetPositionX(), me->GetPositionY(), tirion->GetPositionZ(), me->GetOrientation(), true); } } break; } } void UpdateAI(const uint32 diff) { if (GetPhase(events) != PHASE_6_ENDING && (!UpdateVictim() || !CheckInRoom())) return; events.Update(diff); if (me->HasUnitState(UNIT_STAT_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { //Remove players from threat list if they fall down if (eventId == EVENT_CHECK_ALIVE_PLAYERS) { if (Creature *pTirion = ObjectAccessor::GetCreature(*me, instance->GetData64(GUID_TIRION))) { TPlayerList players = GetPlayersInTheMap(me->GetMap()); for (TPlayerList::iterator it = players.begin(); it != players.end(); ++it) if ((*it)->GetDistanceZ(pTirion) > 10.0f && !(*it)->HasAura(SPELL_IN_FROSTMOURNE_ROOM)) { (*it)->RemoveAllAuras(); me->DealDamage(*it, (*it)->GetHealth()); pTirion->CastSpell(*it, FROZEN_THRONE_TELEPORT, true); } } events.ScheduleEvent(EVENT_CHECK_ALIVE_PLAYERS, 5000); } switch (GetPhase(events)) { case PHASE_1: { switch (eventId) { case EVENT_SPEECH: { DoScriptText(RAND(SAY_RANDOM_1, SAY_RANDOM_2), me); events.ScheduleEvent(EVENT_SPEECH, 33000, 0, PHASE_1); break; } case EVENT_SUMMON_SHAMBLING_HORROR: { DoCast(SPELL_SUMMON_SHAMBLING_HORROR); events.ScheduleEvent(EVENT_SUMMON_SHAMBLING_HORROR, 60000, 0, PHASE_1); break; } case EVENT_SUMMON_DRUDGE_GHOULS: { PauseForSummoning(true); DoCast(SPELL_SUMMON_DRUDGE_GHOULS); events.ScheduleEvent(EVENT_RESTART_COMBAT_MOVEMENT, 4100, 0, PHASE_1); events.ScheduleEvent(EVENT_SUMMON_DRUDGE_GHOULS, 30000, 0, PHASE_1); break; } case EVENT_INFEST: { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 100.0f, true, -RAID_MODE(SPELL_INFEST_10N, SPELL_INFEST_25N, SPELL_INFEST_10H, SPELL_INFEST_25H))) DoCast(target, RAID_MODE(SPELL_INFEST_10N, SPELL_INFEST_10H, SPELL_INFEST_25N, SPELL_INFEST_25H)); events.ScheduleEvent(EVENT_INFEST, 20000, 0, PHASE_1); break; } case EVENT_NECROTIC_PLAGUE: { if(Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 100.0f, true, -EVENT_NECROTIC_PLAGUE)) DoCast(target, RAID_MODE<uint32>(SPELL_NECROTIC_PLAGUE_10N, SPELL_NECROTIC_PLAGUE_25N, SPELL_NECROTIC_PLAGUE_10H, SPELL_NECROTIC_PLAGUE_25H)); events.ScheduleEvent(EVENT_NECROTIC_PLAGUE, 25000, 0, PHASE_1); break; } case EVENT_SHADOW_TRAP: { ASSERT(IsHeroic()); //First, try to select somebody far away from the boss Unit *target = NULL; target = SelectTarget(SELECT_TARGET_RANDOM, 0, -5.0f, true); if (!target) target = SelectTarget(SELECT_TARGET_RANDOM, 1, 100.0f, true); DoCast(target, SPELL_SUMMON_SHADOW_TRAP, true); events.ScheduleEvent(EVENT_SHADOW_TRAP, 30000, 0, PHASE_1); break; } case EVENT_RESTART_COMBAT_MOVEMENT: { PauseForSummoning(false); break; } } break; } case PHASE_2_TRANSITION: case PHASE_4_TRANSITION: { switch (eventId) { case EVENT_PAIN_AND_SUFFERING: { if (Player *randomPlayer = SelectRandomAttackablePlayerInTheMap(me->GetMap())) { me->SetFacingToObject(randomPlayer); DoCast(randomPlayer, RAID_MODE(SPELL_PAIN_AND_SUFFERING_10N, SPELL_PAIN_AND_SUFFERING_25N, SPELL_PAIN_AND_SUFFERING_10H, SPELL_PAIN_AND_SUFFERING_25H), true); } events.ScheduleEvent(EVENT_PAIN_AND_SUFFERING, 1500, 0, GetPhase(events)); break; } case EVENT_SUMMON_RAGING_SPIRIT: { if(Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true)) DoCast(target, SPELL_SUMMON_RAGING_SPIRIT); events.RescheduleEvent(EVENT_PAIN_AND_SUFFERING, 3000, 0, PHASE_2_TRANSITION); events.ScheduleEvent(EVENT_SUMMON_RAGING_SPIRIT, RAID_MODE(20000, 15000, 20000, 15000), 0, GetPhase(events)); break; } case EVENT_SUMMON_ICE_SPHERE: { events.RescheduleEvent(EVENT_PAIN_AND_SUFFERING, 3000, 0, GetPhase(events)); DoCast(SPELL_SUMMON_ICE_SPEHERE); events.ScheduleEvent(EVENT_SUMMON_ICE_SPHERE, urand(6000, 8000), 0, GetPhase(events)); break; } case EVENT_BERSERK: { events.Reset(); DoScriptText(SAY_BERSERK, me); DoCast(me, SPELL_BERSERK2); break; } } break; } case PHASE_3: { switch (eventId) { case EVENT_SUMMON_VAL_KYR_SHADOWGUARD: { DoScriptText(SAY_SUMMON_VALKYR, me); DoCast(me, SPELL_SUMMON_VALKYR); events.ScheduleEvent(EVENT_SUMMON_VAL_KYR_SHADOWGUARD, urand(40000, 45000), 0, PHASE_3); break; } case EVENT_DEFILE: { DoScriptText(SAY_EMOTE_DEFILE, me); if(Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true)) DoCast(target, SPELL_SUMMON_DEFILE); events.ScheduleEvent(EVENT_DEFILE, 35000, 0, PHASE_3); break; } case EVENT_SOUL_REAPER: { DoCastVictim(RAID_MODE(SPELL_SOUL_REAPER_10N, SPELL_SOUL_REAPER_25N, SPELL_SOUL_REAPER_10H, SPELL_SOUL_REAPER_25H)); DoCast(SPELL_SOUL_REAPER_HASTE_AURA); events.ScheduleEvent(EVENT_SOUL_REAPER, 30000, 0, PHASE_3); break; } case EVENT_INFEST: { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 100.0f, true, -RAID_MODE(SPELL_INFEST_10N, SPELL_INFEST_25N, SPELL_INFEST_10H, SPELL_INFEST_25H))) DoCast(target, RAID_MODE(SPELL_INFEST_10N, SPELL_INFEST_25N, SPELL_INFEST_10H, SPELL_INFEST_25H)); events.ScheduleEvent(EVENT_INFEST, 20000, 0, PHASE_3); break; } case EVENT_BERSERK: { DoScriptText(SAY_BERSERK, me); DoCast(me, SPELL_BERSERK2); break; } } break; } case PHASE_5: { switch (eventId) { case EVENT_DEFILE: { DoScriptText(SAY_EMOTE_DEFILE, me); if(Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true)) DoCast(target, SPELL_SUMMON_DEFILE); events.ScheduleEvent(EVENT_DEFILE, 35000, 0, PHASE_5); break; } case EVENT_SOUL_REAPER: { DoCastVictim(RAID_MODE(SPELL_SOUL_REAPER_10N, SPELL_SOUL_REAPER_25N, SPELL_SOUL_REAPER_10H, SPELL_SOUL_REAPER_25H)); DoCast(SPELL_SOUL_REAPER_HASTE_AURA); events.ScheduleEvent(EVENT_SOUL_REAPER, 30000, 0, PHASE_5); break; } case EVENT_SUMMON_VILE_SPIRITS: { PauseForSummoning(true); DoCast(me, SPELL_SUMMON_VILE_SPIRIT); events.ScheduleEvent(EVENT_RESTART_COMBAT_MOVEMENT, 5700, 0, PHASE_5); events.ScheduleEvent(EVENT_SUMMON_VILE_SPIRITS, 30000, 0, PHASE_5); break; } case EVENT_HARVEST_SOUL: { DoScriptText(SAY_HARVEST_SOUL, me); if(Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 100.0f, true)) DoCast(target, RAID_MODE(SPELL_HARVEST_SOULS_10N, SPELL_HARVEST_SOULS_25N, SPELL_HARVEST_SOULS_10H, SPELL_HARVEST_SOULS_25H)); events.ScheduleEvent(EVENT_HARVEST_SOUL, 75000, 0, PHASE_5); break; } case EVENT_BERSERK: { DoScriptText(SAY_BERSERK, me); DoCast(me, SPELL_BERSERK2); break; } case EVENT_RESTART_COMBAT_MOVEMENT: { PauseForSummoning(false); break; } } break; } } } if(GetPhase(events) == PHASE_6_ENDING) { if (uiStage > 25) return; if (uiEndingTimer <= diff) { switch(uiStage) { case 1: { //Teleport all players who are inside Frostmourne back to Frozen Throne platform TPlayerList players = GetPlayersInTheMap(me->GetMap()); for (TPlayerList::iterator it = players.begin(); it != players.end(); ++it) if ((*it)->HasAura(SPELL_IN_FROSTMOURNE_ROOM)) TeleportPlayerToFrozenThrone(*it); if (Creature *terenasFighter = ObjectAccessor::GetCreature(*me, GUID_TERENAS_FIGHTER)) terenasFighter->AI()->DoAction(ACTION_DESPAWN); if (Creature *spiritWarden = ObjectAccessor::GetCreature(*me, GUID_SPIRIT_WARDEN)) spiritWarden->AI()->DoAction(ACTION_DESPAWN); me->GetMotionMaster()->MoveIdle(); me->SetReactState(REACT_PASSIVE); me->AttackStop(); me->CastStop(); me->SetInCombatWithZone(); if(Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) me->SetInCombatWith(tirion); DoScriptText(SAY_10_PERCENT, me); //Wait for everyone who is inside the Frostmourne Room to get teleported to the Platform uiEndingTimer = 4000; break; } case 2: { DoCast(me, SPELL_FURY_OF_FROSTMOURNE); uiEndingTimer = 12000; break; } case 3: { DoScriptText(SAY_ENDING_1_KING, me); uiEndingTimer = 30000; break; } case 4: { if (Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) me->SetFacingToObject(tirion); DoScriptText(SAY_ENDING_2_KING, me); uiEndingTimer = 25000; break; } case 5: { me->GetMotionMaster()->MovePoint(0, MovePos[1]); uiEndingTimer = 4000; break; } case 6: { DoScriptText(SAY_ENDING_3_KING, me); if (Creature* trigger = me->FindNearestCreature(37882, 50.0f, true)) me->SetFacingToObject(trigger); //DoCast(me, SPELL_RAISE_DEAD); // Temp fix for visual rising sword on spellcast me->SetUInt32Value(UNIT_NPC_EMOTESTATE, 468); me->HandleEmoteCommand(EMOTE_ONESHOT_SPELLCAST_OMNI); uiEndingTimer = 28000; break; } case 7: { DoScriptText(SAY_ENDING_4_KING, me); uiEndingTimer = 8000; break; } case 8: { if(uiTirionGUID) if(Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) DoScriptText(SAY_ENDING_5_TIRION, tirion); uiEndingTimer = 11000; break; } case 9: { if(uiTirionGUID) if(Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) { tirion->CastSpell(tirion, SPELL_TIRION_LIGHT, true); tirion->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } uiEndingTimer = 7000; break; } case 10: { if(uiTirionGUID) if(Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) { tirion->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_READY2H); tirion->GetMotionMaster()->MovePoint(0, MovePos[2]); } uiEndingTimer = 3000; break; } case 11: { if(uiTirionGUID) { if(Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) { tirion->GetMotionMaster()->MoveJump(MovePos[10].GetPositionX(), MovePos[10].GetPositionY(), MovePos[10].GetPositionZ(), 10.0f, 15.0f); tirion->UpdatePosition(MovePos[10]); } } me->RemoveAura(SPELL_RAISE_DEAD); uiEndingTimer = 600; break; } case 12: { if (uiTirionGUID) if (Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) tirion->HandleEmoteCommand(EMOTE_ONESHOT_ATTACK2HTIGHT); DoPlaySoundToSet(me, SOUND_ENDING_7_KING); //Equip broken Frostmourne SetEquipmentSlots(false, 50840, EQUIP_NO_CHANGE, EQUIP_NO_CHANGE); me->CastSpell(me, SPELL_BOOM_VISUAL, false); me->HandleEmoteCommand(EMOTE_STATE_CUSTOM_SPELL_01); uiEndingTimer = 3000; break; } case 13: { me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_CUSTOM_SPELL_02); uiEndingTimer = 1000; break; } case 14: { if(Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) tirion->SetFacingToObject(me); uiEndingTimer = 1000; break; } case 15: { me->CastSpell(me, SPELL_DROP_FROSTMOURNE, false); SetEquipmentSlots(false, EQUIP_UNEQUIP, EQUIP_NO_CHANGE, EQUIP_NO_CHANGE); uiEndingTimer = 500; break; } case 16: { // Here Tirion is knocked back to the teleport circle if (Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) tirion->GetMotionMaster()->MoveJump(MovePos[11].GetPositionX(), MovePos[11].GetPositionY(), MovePos[11].GetPositionZ(), 11.0f, 9.0f); uiEndingTimer = 800; break; } case 17: { if (Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) tirion->CastSpell(tirion, SPELL_KNOCKDOWN, true); DoScriptText(SAY_ENDING_6_KING, me); uiEndingTimer = 5000; break; } case 18: { me->CastSpell(me, SPELL_SOUL_EFFECT, true); if (Creature* frostmourne = me->FindNearestCreature(NPC_FROSTMOURNE_TRIGGER, 25.0f, true)) { me->GetMotionMaster()->MovePoint(0, frostmourne->GetPositionX(),frostmourne->GetPositionY(), frostmourne->GetPositionZ() + 3.0f); me->UpdatePosition(frostmourne->GetPositionX(),frostmourne->GetPositionY(), frostmourne->GetPositionZ() + 3.0f, me->GetOrientation()); } uiEndingTimer = 5000; break; } case 19: { if(uiTirionGUID) if(Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) DoScriptText(SAY_ENDING_8_TIRION, tirion); uiEndingTimer = 6000; break; } case 20: { if(Creature* frostmourne = me->FindNearestCreature(NPC_FROSTMOURNE_TRIGGER, 25.0f, true)) frostmourne->CastSpell(frostmourne, SPELL_SUMMON_MENETHIL, true); uiEndingTimer = 500; break; } case 21: { if(Creature* father = me->FindNearestCreature(NPC_TERENAS_MENETHIL, 25.0f, true)) { DoScriptText(SAY_ENDING_9_FATHER, father); father->SetFacingToObject(me); } uiEndingTimer = 11000; break; } case 22: { if (Creature* father = me->FindNearestCreature(NPC_TERENAS_MENETHIL, 25.0f, true)) { DoScriptText(SAY_ENDING_11_FATHER, father); instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_FURY_OF_FROSTMOURNE_NORES); father->CastSpell(father, SPELL_MENETHIL_VISUAL, true); father->CastSpell(father, SPELL_REVIVE, false); } uiEndingTimer = 6000; break; } case 23: { if(uiTirionGUID) if(Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) DoScriptText(SAY_ENDING_10_TIRION, tirion); uiEndingTimer = 5000; break; } case 24: { DoScriptText(SAY_ENDING_12_KING, me); if (uiTirionGUID) if (Creature* tirion = Unit::GetCreature(*me, uiTirionGUID)) { if(Creature* frostmourne = me->FindNearestCreature(NPC_FROSTMOURNE_TRIGGER, 25.0f, true)) tirion->GetMotionMaster()->MoveChase(frostmourne, 2.0f, 1.5f); tirion->SetUInt64Value(UNIT_FIELD_TARGET, me->GetGUID()); } if (Creature* father = me->FindNearestCreature(NPC_TERENAS_MENETHIL, 25.0f, true)) { if(Creature* frostmourne = me->FindNearestCreature(NPC_FROSTMOURNE_TRIGGER, 25.0f, true)) father->GetMotionMaster()->MoveChase(frostmourne, 3.0f, 0.0f); father->SetUInt64Value(UNIT_FIELD_TARGET, me->GetGUID()); } uiEndingTimer = 10000; break; } case 25: { DoScriptText(SAY_DEATH_KING, me); break; } } ++uiStage; } else uiEndingTimer -= diff; } switch (GetPhase(events)) { case PHASE_1: case PHASE_3: case PHASE_5: if(!imSummoning) DoMeleeAttackIfReady(); break; } } void PauseForSummoning(bool on) { imSummoning = on; if(on) me->GetMotionMaster()->MoveIdle(); else me->GetMotionMaster()->MoveChase(me->getVictim()); } // JUST FOR TESTING PROPUSES!!!! void SpellHit(Unit* /*caster*/, const SpellEntry * spell) { if (spell->Id == 72400) events.SetPhase(PHASE_6_ENDING); } private: InstanceScript* instance; uint8 uiStage; uint8 uiPhase; uint32 uiEndingTimer; uint32 uiSummonShamblingHorrorTimer; uint32 uiSummonDrudgeGhoulsTimer; uint32 uiSummonShadowTrap; uint32 uiInfestTimer; uint32 uiNecroticPlagueTimer; uint32 uiSummonValkyrTimer; uint32 uiSoulReaperTimer; uint32 uiDefileTimer; uint32 uiHarvestSoulTimer; uint32 uiSummonVileSpiritTimer; uint32 uiIcePulsSummonTimer; uint32 uiSummonSpiritTimer; uint64 uiTirionGUID; bool isSwitching; bool imSummoning; bool isAboutToDie; SummonList summons; EventMap events; }; CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<boss_the_lich_kingAI>(creature); } }; class npc_tirion_icc : public CreatureScript { public: npc_tirion_icc() : CreatureScript("npc_tirion_icc") { } struct npc_tirion_iccAI : public ScriptedAI { npc_tirion_iccAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } void Reset() { uiIntroTimer = 1000; uiStage = 1; uiLichKingGUID = 0; bIntro = false; me->RemoveAllAuras(); me->SetReactState(REACT_PASSIVE); me->SetSpeed(MOVE_RUN, 1.8f); me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); me->GetMotionMaster()->MovePoint(POINT_PLATFORM_CENTER, MovePos[8]); DoCast(me, SPELL_REVIVE, true); DoCast(SPELL_WMO_INTACT); //Rebuilding ice shards if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetData64(GUID_ICE_SHARD_1))) go->SetGoState(GO_STATE_READY); if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetData64(GUID_ICE_SHARD_2))) go->SetGoState(GO_STATE_READY); if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetData64(GUID_ICE_SHARD_3))) go->SetGoState(GO_STATE_READY); if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetData64(GUID_ICE_SHARD_4))) go->SetGoState(GO_STATE_READY); if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetData64(GUID_EDGE_DESTROY_WARNING))) go->SetGoState(GO_STATE_READY); if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetData64(GUID_FROSTY_EDGE_INNER))) go->SetGoState(GO_STATE_READY); if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetData64(GUID_FROSTY_EDGE_OUTER))) go->SetGoState(GO_STATE_ACTIVE); } void MovementInform(uint32 type, uint32 id) { if (type != POINT_MOTION_TYPE) return; switch (id) { case POINT_PLATFORM_CENTER: { if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE) me->GetMotionMaster()->MovementExpired(); me->UpdatePosition(MovePos[8]); me->SetOrientation(3.1416f); me->SetFacing(3.1416f); break; } } } void DoAction(const int32 action) { switch (action) { case ACTION_START_EVENT: { bIntro = true; if (instance) uiLichKingGUID = instance->GetData64(DATA_THE_LICH_KING); break; } case ACTION_RESET: { Reset(); break; } } } void SpellHit(Unit* /*caster*/, const SpellInfo * spell) { if(spell->Id == SPELL_LIGHTS_BLESSING) me->RemoveAurasDueToSpell(SPELL_ICEBLOCK_TRIGGER); } void UpdateAI(const uint32 diff) { if(!bIntro || !uiLichKingGUID) return; if (uiStage > 12) return; if(uiIntroTimer <= diff) { switch(uiStage) { case 1: { // IntroStarts. Tirion moves to talk position me->SetUnitMovementFlags(MOVEMENTFLAG_WALKING); me->GetMotionMaster()->MovePoint(0, MovePos[9]); uiIntroTimer = 8000; break; } case 2: { // Tirion reaches talk position, Arthas stands up if (Creature* lich = Unit::GetCreature(*me, uiLichKingGUID)) lich->SetStandState(UNIT_STAND_STATE_STAND); me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_READY2H); uiIntroTimer = 1000; break; } case 3: { // Arthas talks if(Creature* lich = Unit::GetCreature(*me, uiLichKingGUID)) DoScriptText(SAY_INTRO_1_KING, lich); uiIntroTimer = 2000; break; } case 4: { // Arthas walks downstair if (Creature* lich = Unit::GetCreature(*me, uiLichKingGUID)) { lich->SetUnitMovementFlags(MOVEMENTFLAG_WALKING); lich->GetMotionMaster()->MovePoint(POINT_START_EVENT_1, MovePos[0]); } uiIntroTimer = 13500; break; } case 5: { // Arthas has reached bottom of stairs, Tirion talks if (Creature* lich = Unit::GetCreature(*me, uiLichKingGUID)) lich->SetFacingToObject(me); DoScriptText(SAY_INTRO_2_TIRION, me); uiIntroTimer = 8000; break; } case 6: { if(Creature* lich = Unit::GetCreature(*me, uiLichKingGUID)) { lich->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_LAUGH); DoScriptText(SAY_INTRO_3_KING, lich); } uiIntroTimer = 3000; break; } case 7: { if(Creature* lich = Unit::GetCreature(*me, uiLichKingGUID)) lich->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_POINT_NOSHEATHE); uiIntroTimer = 2000; break; } case 8: { if(Creature* lich = Unit::GetCreature(*me, uiLichKingGUID)) lich->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); uiIntroTimer = 18000; break; } case 9: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_POINT_NOSHEATHE); DoScriptText(SAY_INTRO_4_TIRION, me); uiIntroTimer = 2000; break; case 10: // Tirion runs to Arthas me->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); me->GetMotionMaster()->MovePoint(0, MovePos[3]); uiIntroTimer = 1600; break; case 11: // Arthas freezes Tirion if(Creature* lich = Unit::GetCreature(*me, uiLichKingGUID)) { lich->CastSpell(lich, SPELL_ICEBLOCK_TRIGGER, true); me->GetMotionMaster()->MoveIdle(); me->SetFacingToObject(lich); } me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); // From here, Arthas is attackable if(Creature* lich = Unit::GetCreature(*me, uiLichKingGUID)) { lich->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); lich->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE); lich->SetReactState(REACT_AGGRESSIVE); } uiIntroTimer = 2000; break; case 12: { if (Creature* lich = Unit::GetCreature(*me, uiLichKingGUID)) { DoScriptText(SAY_INTRO_5_KING, lich); // If Arthas stills not in combat, find nearest player and attack him if(!lich->isInCombat()) { if(Unit* target = lich->FindNearestPlayer(100.0f)) lich->AI()->AttackStart(target); } } break; } } ++uiStage; } else uiIntroTimer -= diff; } private: InstanceScript* instance; uint64 uiLichKingGUID; uint32 uiIntroTimer; uint8 uiStage; bool bIntro; }; bool OnGossipHello(Player* player, Creature* creature) { InstanceScript* instance = creature->GetInstanceScript(); if (!instance) return false; if (instance->GetBossState(DATA_THE_LICH_KING) == DONE) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, "The Lich King was already defeated here. Teleport me back to the Light's Hammer", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+4); player->SEND_GOSSIP_MENU(GOSSIP_MENU, creature->GetGUID()); return true; } player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_START_EVENT, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); player->SEND_GOSSIP_MENU(GOSSIP_MENU, creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*uiSender*/, uint32 uiAction) { switch (uiAction) { case GOSSIP_ACTION_INFO_DEF+4: creature->CastSpell(player, LIGHT_S_HAMMER_TELEPORT, true); break; case GOSSIP_ACTION_INFO_DEF+3: CAST_AI(npc_tirion_icc::npc_tirion_iccAI, creature->AI())->DoAction(ACTION_START_EVENT); creature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); player->CLOSE_GOSSIP_MENU(); break; default: creature->MonsterSay("You've just found a bug. Contact server admin and explain what to do to reproduce this bug", LANG_UNIVERSAL, player->GetGUID()); break; } return true; } CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<npc_tirion_iccAI>(creature); } }; class npc_valkyr_shadowguard : public CreatureScript { public: static const float Z_FLY; npc_valkyr_shadowguard() : CreatureScript("npc_valkyr_shadowguard") { } struct npc_valkyr_shadowguardAI : public ScriptedAI { npc_valkyr_shadowguardAI(Creature* creature) : ScriptedAI(creature), vehicle(creature->GetVehicleKit()), m_victimGuid(0) { ASSERT(vehicle); } void Reset() { SetCombatMovement(false); me->SetReactState(REACT_PASSIVE); m_moveUpdatePeriod = 100; events.Reset(); me->SetFlying(true); me->AddUnitMovementFlag(MOVEMENTFLAG_LEVITATING); me->GetPosition(&m_pos); m_pos.m_positionZ = Z_FLY + 6.0f; me->UpdatePosition(m_pos); bCanCast = false; m_victimGuid = 0; if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE) me->GetMotionMaster()->MovementExpired(); events.ScheduleEvent(EVENT_CHARGE_PLAYER, 2000); DoCast(me, SPELL_WINGS_OF_THE_DAMNED, true); //summoned->AI()->AttackStart(*it); //summoned->CastSpell(*it, SPELL_VALKYR_TARGET_SEARCH, true); } void DamageTaken(Unit* /*done_by*/, uint32& /*damage*/) { if(!HealthAbovePct(50) && IsHeroic() && !bCanCast) { vehicle->RemoveAllPassengers(); me->RemoveAllAuras(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->GetMotionMaster()->MovePoint(POINT_VALKYR_ZET, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ() + 10); events.Reset(); } } void SetGUID(const uint64& guid, int32 type = 0) { if (type == TYPE_VICTIM) m_victimGuid = guid; } void DoAction(const int32 action) { switch(action) { case ACTION_CHARGE_PLAYER: { events.ScheduleEvent(EVENT_CHARGE_PLAYER, 2000); break; } } } void SpellHitTarget(Unit* victim, SpellInfo const* spellEntry) { if (spellEntry->Id == SPELL_VALKYR_CHARGE) if (Player *player = ObjectAccessor::GetPlayer(*me, m_victimGuid)) DoCast(player, SPELL_VALKYR_CARRY_CAN_CAST, true); ScriptedAI::SpellHitTarget(victim, spellEntry); } void SpellHit(Unit *attacker, const SpellInfo *spellEntry) { if (spellEntry) switch (spellEntry->Id) { case SPELL_VALKYR_GRAB_PLAYER: { float speedRate = me->GetSpeedRate(MOVE_RUN); speedRate = 0.25f; me->SetSpeed(MOVE_FLIGHT, speedRate); me->SetSpeed(MOVE_RUN, speedRate); float x, y, z; me->GetPosition(x, y, z); me->UpdatePosition(x, y, Z_FLY, 0.0f, true); me->SetReactState(REACT_PASSIVE); me->AttackStop(); SetCombatMovement(false); me->SetInCombatWithZone(); me->AddUnitMovementFlag(MOVEMENTFLAG_LEVITATING); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_CHARM, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_FEAR, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_ROOT, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_PACIFY, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_SILENCE, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_TRANSFORM, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_SCALE, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_DISARM, true); me->ApplySpellImmune(0, IMMUNITY_ID, SPELL_DEATH_GRIP, true); //The Val'kyrs always choose the closest edge of the platform). std::list<Creature*> allEdgeStalkers; GetCreatureListWithEntryInGrid(allEdgeStalkers, me, NPC_PLATFORM_DESTRUCTIBLE_EDGE_STALKER, 1000.0f); if (allEdgeStalkers.empty()) { me->Kill(me); me->DespawnOrUnsummon(); } else { Creature *nearestEdgeStalker = allEdgeStalkers.front(); for (std::list<Creature*>::iterator it = allEdgeStalkers.begin(); it != allEdgeStalkers.end(); ++it) if (me->GetDistance2d(nearestEdgeStalker) > me->GetDistance2d(*it)) nearestEdgeStalker = *it; //Position edgePos; me->GetPosition(&m_pos); m_pos.m_positionZ = Z_FLY; me->UpdatePosition(m_pos, true); float ex, ey, ez; nearestEdgeStalker->GetPosition(ex, ey, ez); float distanceToEdge = m_pos.GetExactDist2d(ex, ey); distanceToEdge += 10.0f; m_angle = m_pos.GetAngle(ex, ey); me->GetNearPoint2D(ex, ey, distanceToEdge, m_angle); me->SetFacingToObject(nearestEdgeStalker); me->GetMotionMaster()->MovePoint(POINT_PLATFORM_END, ex, ey, Z_FLY); //events.ScheduleEvent(EVENT_MOVE_TO_PLATFORM_EDGE, 1000); //events.ScheduleEvent(EVENT_CHECK_AT_PLATFORM_EDGE, 1000); } //me->GetMotionMaster()->MovePoint(POINT_PLATFORM_END, MovePos[4]); } } ScriptedAI::SpellHit(attacker, spellEntry); } void MovementInform(uint32 type, uint32 id) { if(type != POINT_MOTION_TYPE) return; if(bCanCast) me->GetMotionMaster()->Clear(); switch(id) { case POINT_PLATFORM_END: { DoCast(me, SPELL_VALKYR_EJECT_PASSENGER); //Fly 15 feet upward, then despawn me->GetPosition(&m_pos); m_pos.m_positionZ = 1055.0f; me->GetMotionMaster()->MovePoint(POINT_VALKYR_END, m_pos); break; } case POINT_VALKYR_END: { me->DespawnOrUnsummon(); break; } case POINT_VALKYR_ZET: { events.ScheduleEvent(EVENT_SIPHON_LIFE, 3000); bCanCast = true; break; } case POINT_VALKYR_CONTINUE_FLYING: { me->UpdatePosition(m_pos); events.ScheduleEvent(EVENT_MOVE_TO_PLATFORM_EDGE, m_moveUpdatePeriod); break; } } } void UpdateAI(const uint32 diff) { if (!me->isAlive() || me->HasUnitState(UNIT_STAT_CASTING)) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_CHARGE_PLAYER: { if (Player *player = ObjectAccessor::GetPlayer(*me, m_victimGuid)) DoCast(player, SPELL_VALKYR_CHARGE, true); else me->DespawnOrUnsummon(); break; } case EVENT_CHECK_AT_PLATFORM_EDGE: { if (me->GetDistance2d(MovePos[1].m_positionX, MovePos[1].m_positionY) > 55.0f) { events.Reset(); DoCast(me, SPELL_VALKYR_EJECT_PASSENGER); //Fly 15 feet upward, then despawn me->GetPosition(&m_pos); m_pos.m_positionZ = 1055.0f; me->GetMotionMaster()->MovePoint(POINT_VALKYR_END, m_pos); } else events.ScheduleEvent(EVENT_CHECK_AT_PLATFORM_EDGE, 1000); } case EVENT_MOVE_TO_PLATFORM_EDGE: { me->GetPosition(&m_pos); if (!me->HasAuraType(SPELL_AURA_MOD_STUN)) { float flySpeed = me->GetSpeed(MOVE_RUN) * m_moveUpdatePeriod / 10000; m_pos.m_positionX += flySpeed * cosf(m_angle); m_pos.m_positionY += flySpeed * sinf(m_angle); m_pos.m_positionZ = Z_FLY; } me->SetFacing(m_angle); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MovePoint(POINT_VALKYR_CONTINUE_FLYING, m_pos); me->UpdatePosition(m_pos); break; } case EVENT_SIPHON_LIFE: { DoCastVictim(SPELL_LIFE_SIPHON); events.ScheduleEvent(EVENT_SIPHON_LIFE, 3000); } } } } private: bool bCanCast; EventMap events; Position m_pos; float m_angle; uint32 m_moveUpdatePeriod; Vehicle* vehicle; uint64 m_victimGuid; }; CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<npc_valkyr_shadowguardAI>(creature); } }; const float npc_valkyr_shadowguard::Z_FLY = 1045.0f; class npc_vile_spirit : public CreatureScript { public: static const float Z_VILE_SPIRIT; npc_vile_spirit() : CreatureScript("npc_vile_spirit") { } struct npc_vile_spiritAI : public ScriptedAI { npc_vile_spiritAI(Creature* creature) : ScriptedAI(creature) { } void Reset() { events.ScheduleEvent(EVENT_BECOME_ACTIVE, 15000); //If they don't reach that player within around 30 seconds, they will despawn harmlessly. events.ScheduleEvent(EVENT_DESPAWN, 45000); SetCombatMovement(false); me->SetReactState(REACT_PASSIVE); me->SetFlying(true); float x, y, z; me->GetPosition(x, y, z); me->UpdatePosition(x, y, npc_vile_spirit::Z_VILE_SPIRIT, true); Position randomPos; float dist = 1.0f * (float)rand_norm() * 10.0f; me->GetRandomNearPosition(randomPos, dist); randomPos.m_positionZ = Z_VILE_SPIRIT; me->GetMotionMaster()->MovePoint(POINT_MOVE_NEAR_RANDOM, randomPos); bActive = false; } void MovementInform(uint32 type, uint32 id) { if (type != POINT_MOTION_TYPE) return; if (id == POINT_MOVE_NEAR_RANDOM) { me->GetMotionMaster()->MovementExpired(); if (!bActive) events.ScheduleEvent(EVENT_MOVE_RANDOM, 1000); } } void DoAction(const int32 action) { switch(action) { case ACTION_DESPAWN: { me->RemoveAura(SPELL_VILE_SPIRIT_DISTANCE_CHECK); events.ScheduleEvent(EVENT_DESPAWN, 1000); me->SetReactState(REACT_PASSIVE); SetCombatMovement(false); break; } } } void UpdateAI(const uint32 diff) { events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_MOVE_RANDOM: { Position randomPos; float dist = 1.0f * (float)rand_norm() * 10.0f; me->GetRandomNearPosition(randomPos, dist); randomPos.m_positionZ = Z_VILE_SPIRIT; me->GetMotionMaster()->MovePoint(POINT_MOVE_NEAR_RANDOM, randomPos); break; } case EVENT_BECOME_ACTIVE: { events.CancelEvent(EVENT_MOVE_RANDOM); bActive = true; SetCombatMovement(true); me->SetReactState(REACT_AGGRESSIVE); me->GetMotionMaster()->MovementExpired(); DoCast(me, SPELL_VILE_SPIRIT_ACTIVE, true); //DoCast(me, SPELL_VILE_SPIRIT_TARGET_SEARCH, true); DoCast(me, SPELL_VILE_SPIRIT_DISTANCE_CHECK, true); events.ScheduleEvent(EVENT_CHECK_PLAYER_IN_FROSTMOURNE_ROOM, 1000); break; } case EVENT_CHECK_PLAYER_IN_FROSTMOURNE_ROOM: { Unit *curVictim = me->getVictim(); if (!curVictim) curVictim = SelectRandomAttackablePlayerInTheMap(me->GetMap()); if (!curVictim) { me->DespawnOrUnsummon(); return; } if (!curVictim->isAlive() || curVictim->GetTypeId() != TYPEID_PLAYER) { Player *player = curVictim->ToPlayer(); uint8 count = 0; if (player) { while ((!player->isTargetableForAttack() || !player->HasAura(SPELL_IN_FROSTMOURNE_ROOM)) && count++ < 20) player = SelectRandomAttackablePlayerInTheMap(me->GetMap()); EnterEvadeMode(); AttackStart(player); } } events.ScheduleEvent(EVENT_CHECK_PLAYER_IN_FROSTMOURNE_ROOM, 2000); break; } case EVENT_DESPAWN: { me->DespawnOrUnsummon(); break; } default: break; } } } private: EventMap events; bool bActive; }; CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<npc_vile_spiritAI>(creature); } }; const float npc_vile_spirit::Z_VILE_SPIRIT = 1050.0f; class npc_shambling_horror: public CreatureScript { public: npc_shambling_horror(): CreatureScript("npc_shambling_horror") { } struct npc_shambling_horrorAI: public ScriptedAI { npc_shambling_horrorAI(Creature* creature): ScriptedAI(creature) { instance = creature->GetInstanceScript(); } void EnterCombat(Unit* /*who*/) { events.Reset(); events.ScheduleEvent(EVENT_ENRAGE, 15000); events.ScheduleEvent(EVENT_SHOCKWAVE, 10000); isFrenzied = false; } void DamageTaken(Unit* /*done_by*/, uint32& /*damage*/) { if (IsHeroic()) if (HealthBelowPct(20) && !isFrenzied) { isFrenzied = true; DoCast(me, SPELL_FRENZY); } } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STAT_CASTING)) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_ENRAGE: { DoCast(me, SPELL_ENRAGE); events.ScheduleEvent(EVENT_ENRAGE, urand(20000, 30000)); break; } case EVENT_SHOCKWAVE: { DoCast(me->getVictim(), SPELL_SHOCKWAVE); events.ScheduleEvent(EVENT_SHOCKWAVE, 20000); break; } default: break; } } DoMeleeAttackIfReady(); } private: bool isFrenzied; InstanceScript* instance; EventMap events; }; CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<npc_shambling_horrorAI>(creature); } }; class npc_shadow_trap : public CreatureScript { enum eEvents { EVENT_BECOME_ACTIVE = 1, EVENT_ACTIVE, EVENT_CHECK, EVENT_DESPAWN }; public: npc_shadow_trap() : CreatureScript("npc_shadow_trap") { } struct npc_shadow_trapAI : public Scripted_NoMovementAI { npc_shadow_trapAI(Creature* creature) : Scripted_NoMovementAI(creature) { } void Reset() { events.ScheduleEvent(EVENT_BECOME_ACTIVE, 500); events.ScheduleEvent(EVENT_DESPAWN, 60000); SetCombatMovement(false); active = false; } //void MoveInLineOfSight(Unit* who) //{ // if (active && me->IsWithinDistInMap(who, 4.0f)) // { // if (who->GetTypeId() == TYPEID_PLAYER) // me->CastSpell(who, SPELL_SHADOW_TRAP_EFFECT, true); // } //} void UpdateAI(const uint32 uiDiff) { events.Update(uiDiff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_BECOME_ACTIVE: { DoCast(me, SPELL_SHADOW_TRAP_INTRO, true); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); events.ScheduleEvent(EVENT_ACTIVE, 1500); break; } case EVENT_ACTIVE: { me->RemoveAura(SPELL_SHADOW_TRAP_INTRO); DoCast(me, SPELL_SHADOW_TRAP_PERIODIC, true); //If they don't reach that player within around 45 seconds, they will despawn harmlessly. events.ScheduleEvent(EVENT_DESPAWN, 45000); events.ScheduleEvent(EVENT_CHECK, 500); active = true; break; } case EVENT_CHECK: { if(Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 4.0f, true)) { if (target->GetTypeId() == TYPEID_PLAYER) me->CastSpell(target, SPELL_SHADOW_TRAP_EFFECT, true); } else if(Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 4.0f, true)) { if (target->GetTypeId() == TYPEID_PLAYER) me->CastSpell(target, SPELL_SHADOW_TRAP_EFFECT, true); } events.ScheduleEvent(EVENT_CHECK, 1500); break; } case EVENT_DESPAWN: { DoCast(me, SPELL_SHADOW_TRAP_INTRO, true); me->RemoveAura(SPELL_SHADOW_TRAP_PERIODIC); me->DespawnOrUnsummon(2000); break; } default: break; } } } private: EventMap events; bool active; }; CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<npc_shadow_trapAI>(creature); } }; class npc_raging_spirit: public CreatureScript { public: npc_raging_spirit(): CreatureScript("npc_raging_spirit") { } struct npc_raging_spiritAI: public ScriptedAI { npc_raging_spiritAI(Creature* creature): ScriptedAI(creature) { } void EnterCombat(Unit* /*who*/) { events.Reset(); events.ScheduleEvent(EVENT_SOUL_SHRIEK, 15000); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STAT_CASTING)) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SOUL_SHRIEK: { DoCast(me->getVictim(), SPELL_SOUL_SHRIEK); events.ScheduleEvent(EVENT_SOUL_SHRIEK, 10000); break; } default: break; } } DoMeleeAttackIfReady(); } private: EventMap events; }; CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<npc_raging_spiritAI>(creature); } }; class npc_ice_sphere : public CreatureScript { public: npc_ice_sphere() : CreatureScript("npc_ice_sphere") { } struct npc_ice_sphereAI : public ScriptedAI { npc_ice_sphereAI(Creature* creature) : ScriptedAI(creature), m_victimGuid(0) { } void Reset() { events.ScheduleEvent(EVENT_MOVE_FORWARD, 3000); SetCombatMovement(false); me->SetReactState(REACT_PASSIVE); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->ApplySpellImmune(0, IMMUNITY_ID, SPELL_REMORSELESS_WINTER_DAMAGE, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true); me->ApplySpellImmune(0, IMMUNITY_ID, SPELL_DEATH_GRIP, true); events.ScheduleEvent(EVENT_ACTIVATE, 2500); } void SetGUID(const uint64& guid, int32 type = 0) { if (type == TYPE_VICTIM) { m_victimGuid = guid; if (Unit* victim = ObjectAccessor::GetUnit(*me, m_victimGuid)) me->GetMotionMaster()->MoveChase(victim); } } void JustDied(Unit* /*killer*/) { if (Unit* victim = ObjectAccessor::GetUnit(*me, m_victimGuid)) victim->RemoveAurasDueToSpell(SPELL_ICE_PULSE, me->GetGUID()); me->DespawnOrUnsummon(); } void KilledUnit(Unit* victim) { victim->RemoveAurasDueToSpell(SPELL_ICE_PULSE, me->GetGUID()); me->DespawnOrUnsummon(); } void UpdateAI(const uint32 diff) { events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_ACTIVATE: { me->CastSpell(me, SPELL_ICE_SPHERE_VISUAL, true); me->SetDisplayId(30243); //Make sphere visible me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->CastSpell(me, SPELL_ICE_BURST_DISTANCE_CHECK, true); me->SetReactState(REACT_AGGRESSIVE); if (Player* target = SelectRandomAttackablePlayerInTheMap(me->GetMap())) { me->AI()->AttackStart(target); me->AI()->SetGUID(target->GetGUID(), TYPE_VICTIM); me->CastSpell(target, SPELL_ICE_PULSE, true); } else me->DespawnOrUnsummon(); break; } case EVENT_MOVE_FORWARD: { if (Unit* pVictim = ObjectAccessor::GetUnit(*me, m_victimGuid)) if (pVictim->isAlive() && pVictim->isTargetableForAttack()) { me->SetFacingToObject(pVictim); pVictim->GetPosition(&m_victimPos); me->GetPosition(&m_newPos); me->MovePosition(m_newPos, 0.20f, 0.0f); me->UpdatePosition(m_newPos); } else { if (Player* newVictim = SelectRandomPlayerInTheMap(me->GetMap())) { m_victimGuid = newVictim->GetGUID(); AttackStart(newVictim); me->CastSpell(newVictim, SPELL_ICE_PULSE, true); } else me->DespawnOrUnsummon(); } events.ScheduleEvent(EVENT_MOVE_FORWARD, 100); } default: break; } } } private: EventMap events; Position m_victimPos, m_newPos; uint64 m_victimGuid; }; CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<npc_ice_sphereAI>(creature); } }; class npc_defile : public CreatureScript { public: npc_defile() : CreatureScript("npc_defile") { } struct npc_defileAI : public Scripted_NoMovementAI { npc_defileAI(Creature* creature) : Scripted_NoMovementAI(creature), alreadyReset(false), m_hitNumber(0) { } void JustRespawned() { me->SetInCombatWithZone(); me->SetReactState(REACT_PASSIVE); } /*void UpdateDefileAura() { ++m_hitNumber; m_radiusMod = (int32)(((float)m_hitNumber / 60) * 0.9f + 0.1f) * 10000 * 2 / 3; if (SpellEntry const* defileAuraSpellEntry = sSpellMgr->GetSpellForDifficultyFromSpell(sSpellStore.LookupEntry(SPELL_DEFILE), me)) me->CastCustomSpell(defileAuraSpellEntry->Id, SPELLVALUE_RADIUS_MOD, m_radiusMod, me, true, NULL, NULL, me->GetGUID()); }*/ void Reset() { if (!alreadyReset) { if (SpellInfo const* defileAuraSpellEntry = sSpellMgr->GetSpellForDifficultyFromSpell(sSpellMgr->GetSpellInfo(SPELL_DEFILE), me)) DoCast(me, defileAuraSpellEntry->Id, true); //UpdateDefileAura(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); alreadyReset = true; } } /*void SpellHitTarget(Unit* target, SpellEntry const* spell) { if (spell->Id == SPELL_DEFILE_DAMAGE) { AttackStart(target); if (SpellEntry const* defileIncrease = sSpellMgr->GetSpellForDifficultyFromSpell(sSpellStore.LookupEntry(SPELL_DEFILE_INCREASE), me)) DoCast(me, defileIncrease->Id, true); UpdateDefileAura(); } }*/ void UpdateAI(const uint32 diff) {} private: bool alreadyReset; int32 m_hitNumber, m_radiusMod; }; CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<npc_defileAI>(creature); } }; class npc_spirit_warden : public CreatureScript { public: npc_spirit_warden() : CreatureScript("npc_spirit_warden") { } struct npc_spirit_wardenAI : public ScriptedAI { npc_spirit_wardenAI(Creature* creature) : ScriptedAI(creature) {} void Reset() { me->AddUnitMovementFlag(MOVEMENTFLAG_LEVITATING); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_CHARM, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_SILENCE, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_TRANSFORM, true); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_SCALE, true); DoCast(me, SPELL_DARK_HUNGER, true); me->SetReactState(REACT_PASSIVE); } void DamageDealt(Unit* /*target*/, uint32& damage, DamageEffectType /*damageType*/) { me->CastCustomSpell(SPELL_DARK_HUNGER_HEAL_EFFECT, SPELLVALUE_BASE_POINT0, damage, me, true, NULL, NULL, me->GetGUID()); } void JustDied(Unit* /*killer*/) { if (Player* player = me->FindNearestPlayer(80.0f, true)) { if (Creature* terenasFighter = ObjectAccessor::GetCreature(*me, me->GetInstanceScript()->GetData64(GUID_TERENAS_FIGHTER))) terenasFighter->CastSpell(player, SPELL_RESTORE_SOUL, true); TeleportPlayerToFrozenThrone(player); player->RemoveAurasDueToSpell(SPELL_IN_FROSTMOURNE_ROOM); events.Reset(); } } void DoAction(const int32 action) { switch(action) { case ACTION_DESPAWN: { me->DespawnOrUnsummon(); break; } case ACTION_ATTACK_TERENAS_FIGHTER: { events.Reset(); me->NearTeleportTo(FrostmourneRoom[1].m_positionX, FrostmourneRoom[1].m_positionY, FrostmourneRoom[1].m_positionZ, FrostmourneRoom[1].m_orientation); if (Creature* terenasFighter = ObjectAccessor::GetCreature(*me, me->GetInstanceScript()->GetData64(GUID_TERENAS_FIGHTER))) AttackStart(terenasFighter); me->SetHealth(me->GetMaxHealth()); events.ScheduleEvent(EVENT_SOUL_RIP, 5000); events.ScheduleEvent(EVENT_DESTROY_SOUL, 60000); events.ScheduleEvent(EVENT_CHECK_SOUL_RIP_DISPELLED, 1000); break; } } } void UpdateAI(const uint32 diff) { if (!me->isAlive() || me->HasUnitState(UNIT_STAT_CASTING)) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_CHECK_SOUL_RIP_DISPELLED: { if (Creature* terenasFighter = ObjectAccessor::GetCreature(*me, me->GetInstanceScript()->GetData64(GUID_TERENAS_FIGHTER))) if (!terenasFighter->HasAura(SPELL_SOUL_RIP, me->GetGUID())) { me->InterruptNonMeleeSpells(false); me->InterruptSpell(CURRENT_CHANNELED_SPELL, false); } events.ScheduleEvent(EVENT_CHECK_SOUL_RIP_DISPELLED, 1000); break; } case EVENT_SOUL_RIP: { if (Creature* terenasFighter = ObjectAccessor::GetCreature(*me, me->GetInstanceScript()->GetData64(GUID_TERENAS_FIGHTER))) DoCast(terenasFighter, SPELL_SOUL_RIP, true); events.ScheduleEvent(EVENT_SOUL_RIP, 20000); break; } case EVENT_DESTROY_SOUL: { //Player failed to help Terenas to defeat Spirit Warden within 60 seconds - kill Player forcibly if (Creature* lichKing = ObjectAccessor::GetCreature(*me, me->GetInstanceScript()->GetData64(DATA_THE_LICH_KING))) DoCast(lichKing, IsHeroic() ? SPELL_HARVESTED_SOUL_HEROIC : SPELL_HARVESTED_SOUL_NORMAL, true); if (Player *player = me->FindNearestPlayer(80.0f, true)) { player->CastSpell(player, SPELL_DESTROY_SOUL, true); TeleportPlayerToFrozenThrone(player); player->RemoveAurasDueToSpell(SPELL_IN_FROSTMOURNE_ROOM); } events.Reset(); break; } } } DoMeleeAttackIfReady(); } private: EventMap events; }; CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<npc_spirit_wardenAI>(creature); } }; class npc_terenas_menethil : public CreatureScript { public: npc_terenas_menethil() : CreatureScript("npc_terenas_menethil") { } struct npc_terenas_menethilAI : public ScriptedAI { npc_terenas_menethilAI(Creature* creature) : ScriptedAI(creature) {} void Reset() { DoCast(me, SPELL_LIGHT_S_FAVOR, true); me->SetReactState(REACT_PASSIVE); me->SetHealth(me->GetMaxHealth() / 2); } void DoAction(const int32 action) { switch(action) { case ACTION_DESPAWN: { me->DespawnOrUnsummon(); break; } case ACTION_ATTACK_SPIRIT_WARDEN: { me->NearTeleportTo(FrostmourneRoom[2].m_positionX, FrostmourneRoom[2].m_positionY, FrostmourneRoom[2].m_positionZ, FrostmourneRoom[2].m_orientation); if (Creature* spiritWarden = ObjectAccessor::GetCreature(*me, me->GetInstanceScript()->GetData64(GUID_SPIRIT_WARDEN))) AttackStart(spiritWarden); me->SetHealth(me->GetMaxHealth() / 2); events.ScheduleEvent(EVENT_GREET_PLAYER, 1000); break; } } } void DamageDealt(Unit* /*target*/, uint32& damage, DamageEffectType /*damageType*/) { //Damage scales with Terenas' health damage = damage * (100 + (uint32)me->GetHealthPct()) / 100; } void JustDied(Unit* /*killer*/) { Player* player = me->FindNearestPlayer(80.0f, true); player->CastSpell(player, SPELL_DESTROY_SOUL, true); if (Creature* lichKing = ObjectAccessor::GetCreature(*me, me->GetInstanceScript()->GetData64(DATA_THE_LICH_KING))) DoCast(lichKing, IsHeroic() ? SPELL_HARVESTED_SOUL_HEROIC : SPELL_HARVESTED_SOUL_NORMAL, true); TeleportPlayerToFrozenThrone(player); events.Reset(); } void UpdateAI(const uint32 diff) { if (!me->isAlive() || me->HasUnitState(UNIT_STAT_CASTING)) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_GREET_PLAYER: { me->MonsterYell("You have come to bring Arthas to justice? To see the Lich King destroyed?", LANG_UNIVERSAL, 0); me->PlayDirectSound(17394); events.ScheduleEvent(EVENT_ENCOURAGE_PLAYER_TO_ESCAPE, 10000); break; } case EVENT_ENCOURAGE_PLAYER_TO_ESCAPE: { me->MonsterYell("First, you must escape Frostmourne's hold or be damned as I am; trapped within this cursed blade for all eternity.", LANG_UNIVERSAL, 0); me->PlayDirectSound(17395); events.ScheduleEvent(EVENT_ASK_PLAYER_FOR_AID, 10000); break; } case EVENT_ASK_PLAYER_FOR_AID: { me->MonsterYell("Aid me in destroying these tortured souls! Together we will loosen Frostmourne's hold and weaken the Lich King from within!", LANG_UNIVERSAL, 0); me->PlayDirectSound(17396); break; } case EVENT_CHECK_SPIRIT_WARDEN_HEALTH: { if (Creature* spiritWarden = ObjectAccessor::GetCreature(*me, me->GetInstanceScript()->GetData64(GUID_SPIRIT_WARDEN))) { if (!spiritWarden->isAlive()) KilledUnit(spiritWarden); } break; } } } DoMeleeAttackIfReady(); } private: EventMap events; }; CreatureAI* GetAI(Creature* creature) const { return GetIcecrownCitadelAI<npc_terenas_menethilAI>(creature); } }; /*class spell_lich_king_pain_and_suffering : public SpellScriptLoader { public: spell_lich_king_pain_and_suffering() : SpellScriptLoader("spell_lich_king_pain_and_suffering") { } class spell_lich_king_pain_and_suffering_AuraScript : public AuraScript { PrepareAuraScript(spell_lich_king_pain_and_suffering_AuraScript) class AnyAlivePetOrPlayerInObjectFrontalConeCheck { public: AnyAlivePetOrPlayerInObjectFrontalConeCheck(WorldObject const* obj) : i_obj(obj) {} bool operator()(Unit* u) { if (u->GetTypeId() != TYPEID_PLAYER) return false; if (!u->isTargetableForAttack()) return false; if (!u->isAlive()) return false; Position myPos, uPos; i_obj->GetPosition(&myPos); u->GetPosition(&uPos); float orientation = i_obj->GetOrientation(); float angle = myPos.GetAngle(&uPos); float coneAngle = M_PI / 180 * 1.0f; angle = MapManager::NormalizeOrientation(orientation - angle); if ((0.0f <= angle) && (angle <= coneAngle / 2) || ((2 * M_PI - coneAngle / 2) <= angle) && (angle <= (2 * M_PI))) return true; return false; } private: WorldObject const* i_obj; }; void OnPeriodic(AuraEffect const*aurEff) { PreventDefaultAction(); Unit *caster = GetCaster(); if (!caster || !caster->isAlive() || caster->HasUnitState(UNIT_STAT_CASTING)) return; AnyAlivePetOrPlayerInObjectFrontalConeCheck checker(caster); std::list<Unit *> targets; Trillium::UnitListSearcher<AnyAlivePetOrPlayerInObjectFrontalConeCheck> searcher(caster, targets, checker); TypeContainerVisitor<Trillium::UnitListSearcher<AnyAlivePetOrPlayerInObjectFrontalConeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher); TypeContainerVisitor<Trillium::UnitListSearcher<AnyAlivePetOrPlayerInObjectFrontalConeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher); CellCoord p(Trillium::ComputeCellCoord(caster->GetPositionX(), caster->GetPositionY())); Cell cell(p); cell.data.Part.reserved = ALL_DISTRICT; cell.SetNoCreate(); cell.Visit(p, world_unit_searcher, *GetTarget()->GetMap(), *GetTarget(), 100.0f); cell.Visit(p, grid_unit_searcher, *GetTarget()->GetMap(), *GetTarget(), 100.0f); for (std::list<Unit*>::iterator it = targets.begin(); it != targets.end(); ++it) caster->CastSpell((*it), SPELL_PAIN_AND_SUFFERING_DAMAGE, true); //Next time try to target somebody else if (Player *randomTarget = SelectRandomPlayerInTheMap(caster->GetMap())) caster->SetFacingToObject(randomTarget); } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_lich_king_pain_and_suffering_AuraScript::OnPeriodic, EFFECT_2, SPELL_AURA_PERIODIC_TRIGGER_SPELL); //74117 } }; AuraScript* GetAuraScript() const { return new spell_lich_king_pain_and_suffering_AuraScript(); } };*/ class spell_lich_king_pain_and_suffering_effect : public SpellScriptLoader { public: spell_lich_king_pain_and_suffering_effect() : SpellScriptLoader("spell_lich_king_pain_and_suffering_effect") { } class spell_lich_king_pain_and_suffering_effect_SpellScript : public SpellScript { PrepareSpellScript(spell_lich_king_pain_and_suffering_effect_SpellScript); /*void HandleScript(SpellEffIndex effIndex) { Unit *caster = GetCaster(); if (!caster || !caster->isAlive()) { PreventHitDefaultEffect(effIndex); return; } //Next time try to target random player if (Player *randomTarget = SelectRandomPlayerInTheMap(caster->GetMap())) caster->SetFacingToObject(randomTarget); }*/ class AnyAlivePetOrPlayerInObjectFrontalConeCheck { public: AnyAlivePetOrPlayerInObjectFrontalConeCheck(WorldObject const* obj) : i_obj(obj) {} bool operator()(Unit* u) { if (u->GetTypeId() != TYPEID_PLAYER) return true; if (!u->isTargetableForAttack()) return true; if (!u->isAlive()) return true; Position myPos, uPos; i_obj->GetPosition(&myPos); u->GetPosition(&uPos); float orientation = i_obj->GetOrientation(); float angle = myPos.GetAngle(&uPos); float coneAngle = M_PI / 180 * 15.0f; angle = MapManager::NormalizeOrientation(orientation - angle); if ((0.0f <= angle) && (angle <= coneAngle / 2) || ((2 * M_PI - coneAngle / 2) <= angle) && (angle <= (2 * M_PI))) return false; return true; } private: WorldObject const* i_obj; }; void FilterTargets(std::list<Unit*>& unitList) { Unit *caster = GetCaster(); if (!caster || !caster->isAlive()) return; unitList.remove_if (AnyAlivePetOrPlayerInObjectFrontalConeCheck(caster)); } void Register() { OnUnitTargetSelect += SpellUnitTargetFn(spell_lich_king_pain_and_suffering_effect_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_TARGET_ENEMY); OnUnitTargetSelect += SpellUnitTargetFn(spell_lich_king_pain_and_suffering_effect_SpellScript::FilterTargets, EFFECT_1, TARGET_UNIT_CONE_ENEMY_104); OnUnitTargetSelect += SpellUnitTargetFn(spell_lich_king_pain_and_suffering_effect_SpellScript::FilterTargets, EFFECT_2, TARGET_UNIT_CONE_ENEMY_104); //OnEffectHitTarget += SpellEffectFn(spell_lich_king_pain_and_suffering_effect_SpellScript::HandleScript, EFFECT_1, SPELL_EFFECT_SCHOOL_DAMAGE); } }; SpellScript* GetSpellScript() const { return new spell_lich_king_pain_and_suffering_effect_SpellScript(); } }; class spell_lich_king_necrotic_plague : public SpellScriptLoader { public: spell_lich_king_necrotic_plague() : SpellScriptLoader("spell_lich_king_necrotic_plague") { } class spell_lich_king_necrotic_plague_AuraScript : public AuraScript { PrepareAuraScript(spell_lich_king_necrotic_plague_AuraScript) class AnyAliveCreatureOrPlayerInObjectRangeCheck { public: AnyAliveCreatureOrPlayerInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) {} bool operator()(Unit* u) { if (!u->isTargetableForAttack()) return false; if (u->GetGUID() == i_obj->GetGUID()) return false; if (!(u->isAlive() && i_obj->IsWithinDistInMap(u, i_range))) return false; if (u->GetTypeId() == TYPEID_PLAYER) return true; if (u->GetTypeId() != TYPEID_UNIT) return false; if (((Creature*)u)->isTotem()) return false; if (u->GetOwner() && u->GetOwner()->GetTypeId() == TYPEID_PLAYER) return false; uint32 entry = u->ToCreature()->GetEntry(); if (entry == NPC_THE_LICH_KING || entry == NPC_TIRION_ICC || entry == NPC_RAGING_SPIRIT) return false; return true; } private: WorldObject const* i_obj; float i_range; }; /*void OnPeriodic(AuraEffect const*aurEff) { PreventDefaultAction(); if (!(GetTarget() && GetTarget()->isAlive() && GetCaster() && GetCaster()->isAlive())) return; m_stackAmount = GetStackAmount(); GetCaster()->DealDamage(GetTarget(), (uint32)aurEff->GetBaseAmount() * m_stackAmount, 0, SPELL_DIRECT_DAMAGE, SPELL_SCHOOL_MASK_SHADOW, aurEff->GetSpellProto(), true); //if (GetTarget() && GetTarget()->isAlive() && GetCaster() && GetCaster()->isAlive()) // GetCaster()->CastSpell(GetTarget(), SPELL_NECROTIC_PLAGUE_EFFECT, true); }*/ void OnRemove(AuraEffect const * aurEff, AuraEffectHandleModes mode) { Unit* target = GetTarget(); if (!target) return; if (GetStackAmount() >= 30) if (InstanceScript *instance = target->GetInstanceScript()) instance->SetData(DATA_BEEN_WAITING_ACHIEVEMENT, DONE); CellCoord p(Trillium::ComputeCellCoord(target->GetPositionX(), target->GetPositionY())); Cell cell(p); cell.SetNoCreate(); Unit* anyPlayerOrCreatureInRange = NULL; float dist = 10.0f; AnyAliveCreatureOrPlayerInObjectRangeCheck checker(target, dist); Unit* newTarget = NULL; Trillium::UnitLastSearcher<AnyAliveCreatureOrPlayerInObjectRangeCheck> searcher(target, newTarget, checker); TypeContainerVisitor<Trillium::UnitLastSearcher<AnyAliveCreatureOrPlayerInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher); TypeContainerVisitor<Trillium::UnitLastSearcher<AnyAliveCreatureOrPlayerInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher); cell.Visit(p, world_unit_searcher, *target->GetMap(), *target, dist); cell.Visit(p, grid_unit_searcher, *target->GetMap(), *target, dist); uint32 stacksTransferred = GetStackAmount(); //If target is still alive and it's a player, it means that this spell was dispelled - increase stack amount then //I don't know the way to find out whether it's dispelled or not if (!target->isAlive()) ++stacksTransferred; else { //Player was a target and is still alive - assume that the spell was dispelled if (target->GetTypeId() == TYPEID_PLAYER) if (stacksTransferred > 1) --stacksTransferred; } if (stacksTransferred < 1) stacksTransferred = 1; uint32 spellId = aurEff->GetSpellInfo()->Effects[EFFECT_0].Effect; InstanceScript* instance = target->GetInstanceScript(); if (instance) { Unit* lichKing = ObjectAccessor::GetCreature(*target, instance->GetData64(DATA_THE_LICH_KING)); if (lichKing) { if (newTarget) { Aura* appAura = newTarget->GetAura(spellId); if (!appAura) { Unit* newCaster = lichKing; newCaster->CastSpell(newTarget, spellId, true); appAura = newTarget->GetAura(spellId); --stacksTransferred; //One stack is already transferred } if (appAura) { appAura->SetStackAmount(appAura->GetStackAmount() + stacksTransferred); appAura->RefreshDuration(); } } Aura* plagueSiphon = lichKing->GetAura(SPELL_PLAGUE_SIPHON); if (!plagueSiphon) { lichKing->CastSpell(lichKing, SPELL_PLAGUE_SIPHON, true); plagueSiphon = lichKing->GetAura(SPELL_PLAGUE_SIPHON); } if (plagueSiphon) { plagueSiphon->ModStackAmount(1); plagueSiphon->RefreshDuration(); } } } } void Register() { //OnEffectPeriodic += AuraEffectPeriodicFn(spell_lich_king_necrotic_plague_AuraScript::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE); //OnEffectApply += AuraEffectApplyFn(spell_lich_king_necrotic_plague_AuraScript::OnApply, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE, AURA_EFFECT_HANDLE_REAL); OnEffectRemove += AuraEffectRemoveFn(spell_lich_king_necrotic_plague_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE, AURA_EFFECT_HANDLE_REAL); } private: uint8 m_stackAmount; }; AuraScript* GetAuraScript() const { return new spell_lich_king_necrotic_plague_AuraScript(); } }; class spell_lich_king_defile : public SpellScriptLoader { public: spell_lich_king_defile() : SpellScriptLoader("spell_lich_king_defile") { } class spell_lich_king_defile_AuraScript : public AuraScript { PrepareAuraScript(spell_lich_king_defile_AuraScript) void OnPeriodic(AuraEffect const* aurEff) { PreventDefaultAction(); Unit* caster = GetCaster(); if (!(caster && caster->isAlive()) && caster->GetAI()) return; Map* map = caster->GetMap(); //Radius increases by 10% per hit on heroic and by 5% if it's normal m_radius = 8.0f + m_hitCount; //Find targest std::list<Unit *> targets; Trillium::AnyUnfriendlyAttackableVisibleUnitInObjectRangeCheck checker(caster, m_radius); Trillium::UnitListSearcher<Trillium::AnyUnfriendlyAttackableVisibleUnitInObjectRangeCheck> searcher(caster, targets, checker); TypeContainerVisitor<Trillium::UnitListSearcher<Trillium::AnyUnfriendlyAttackableVisibleUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher); TypeContainerVisitor<Trillium::UnitListSearcher<Trillium::AnyUnfriendlyAttackableVisibleUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher); CellCoord p(Trillium::ComputeCellCoord(caster->GetPositionX(), caster->GetPositionY())); Cell cell(p); cell.SetNoCreate(); cell.Visit(p, world_unit_searcher, *map, *caster, 100.0f); cell.Visit(p, grid_unit_searcher, *map, *caster, 100.0f); if (targets.empty()) return; uint32 triggeredSpellId = SPELL_DEFILE_DAMAGE; int32 triggeredSpellBaseDamage = 3000; if (SpellInfo const* defileDamage = sSpellMgr->GetSpellForDifficultyFromSpell(sSpellMgr->GetSpellInfo(SPELL_DEFILE_DAMAGE), caster)) { triggeredSpellId = defileDamage->Id; triggeredSpellBaseDamage = (int32)(defileDamage->Effects[EFFECT_0].CalcValue() * (1.0f + (map->IsHeroic() ? 0.1f : 0.05f) * m_hitCount)); } values.AddSpellMod(SPELLVALUE_BASE_POINT0, ((int32)(triggeredSpellBaseDamage))); values.AddSpellMod(SPELLVALUE_RADIUS_MOD, ((int32)(m_radius * 50))); //values.AddSpellMod(SPELLVALUE_MAX_TARGETS, 1); bool increaseRadius = false; uint64 ownerGuid = (caster->GetOwner() ? caster->GetOwner()->GetGUID() : 0); Unit* curVictim = NULL; for (std::list<Unit*>::iterator it = targets.begin(); it != targets.end(); ++it) { curVictim = *it; if (curVictim->GetGUID() == ownerGuid) continue; if (curVictim->GetTypeId() != TYPEID_PLAYER) continue; if (curVictim->GetDistance2d(caster) > m_radius) continue; caster->CastCustomSpell(triggeredSpellId, values, curVictim, true, NULL, NULL, GetCasterGUID()); increaseRadius = true; } if (!increaseRadius) return; if (SpellInfo const* defileIncrease = sSpellMgr->GetSpellForDifficultyFromSpell(sSpellMgr->GetSpellInfo(SPELL_DEFILE_INCREASE), caster)) { caster->CastSpell(caster, defileIncrease->Id, true); if (Aura* defileIncreaseAura = caster->GetAura(defileIncrease->Id)) m_hitCount = defileIncreaseAura->GetStackAmount(); else ++m_hitCount; } } void Register() { m_hitCount = 0; m_radius = 0.0f; OnEffectPeriodic += AuraEffectPeriodicFn(spell_lich_king_defile_AuraScript::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } private: uint32 m_hitCount; float m_radius; CustomSpellValues values; }; AuraScript* GetAuraScript() const { return new spell_lich_king_defile_AuraScript(); } }; class spell_lich_king_infection : public SpellScriptLoader { public: spell_lich_king_infection() : SpellScriptLoader("spell_lich_king_infection") { } //70541 class spell_lich_king_infection_AuraScript : public AuraScript { PrepareAuraScript(spell_lich_king_infection_AuraScript) void HandleTick(AuraEffect const* aurEff) { if (!GetTarget()->isAlive() || GetTarget()->GetHealthPct() >= 90) { //Aura::ApplicationMap &apmap = const_cast<Aura::ApplicationMap&>(aurEff->GetBase()->GetApplicationMap()); //Aura::ApplicationMap::iterator it = apmap.find(GetTarget()->GetGUID()); //if (it != apmap.end()) // apmap.erase(it); PreventDefaultAction(); GetTarget()->RemoveAurasDueToSpell(aurEff->GetSpellInfo()->Effects[EFFECT_0].Effect); } } void OnCalcAmount(AuraEffect const* aurEff, int32 & amount, bool & canBeRecalculated) { amount = (int32)(1000.0f * powf(1.15f, (float)aurEff->GetTickNumber())); } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_lich_king_infection_AuraScript::HandleTick, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE); DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_lich_king_infection_AuraScript::OnCalcAmount, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE); } }; AuraScript* GetAuraScript() const { return new spell_lich_king_infection_AuraScript(); } }; class spell_lich_king_valkyr_summon : public SpellScriptLoader { public: spell_lich_king_valkyr_summon() : SpellScriptLoader("spell_lich_king_valkyr_summon") { } //74361 class spell_lich_king_valkyr_summon_AuraScript : public AuraScript { PrepareAuraScript(spell_lich_king_valkyr_summon_AuraScript); void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { if (Unit* caster = GetCaster()) { uint32 spawnMod = caster->GetMap()->GetSpawnMode(); GetTargetApplication()->GetBase()->SetDuration(spawnMod == 1 || spawnMod == 3 ? 3000 : 1000); } } void HandleTriggerSpell(AuraEffect const* aurEff) { PreventDefaultAction(); if (Unit* caster = GetCaster()) { Position randomPos; caster->GetRandomNearPosition(randomPos, 10.0f); uint32 triggerSpellId = aurEff->GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; randomPos.m_positionZ = caster->GetPositionZ() + 6.0f; caster->CastSpell(randomPos.GetPositionX(), randomPos.GetPositionY(), randomPos.GetPositionZ(), triggerSpellId, true, NULL); } } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_lich_king_valkyr_summon_AuraScript::HandleTriggerSpell, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); OnEffectApply += AuraEffectApplyFn(spell_lich_king_valkyr_summon_AuraScript::OnApply, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_lich_king_valkyr_summon_AuraScript(); } }; class spell_lich_king_vile_spirit_summon : public SpellScriptLoader { public: spell_lich_king_vile_spirit_summon() : SpellScriptLoader("spell_lich_king_vile_spirit_summon") { } class spell_lich_king_vile_spirit_summon_AuraScript : public AuraScript { PrepareAuraScript(spell_lich_king_vile_spirit_summon_AuraScript); void OnPeriodic(AuraEffect const* aurEff) { PreventDefaultAction(); Unit* caster = GetCaster(); if (!caster || !caster->isAlive()) return; InstanceScript* instance = caster->GetInstanceScript(); if (instance) { uint32 spawnMod = caster->GetMap()->GetSpawnMode(); uint32 maxSummoned; if (spawnMod == 1 || spawnMod == 3) maxSummoned = 10; else maxSummoned = 8; if (aurEff->GetTickNumber() >= maxSummoned) return; } Position pos; caster->GetRandomNearPosition(pos, 13.0f); pos.m_positionZ = npc_vile_spirit::Z_VILE_SPIRIT; uint32 triggeredSpell = aurEff->GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; caster->CastSpell(pos.m_positionX, pos.m_positionY, pos.m_positionZ, triggeredSpell, true); } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_lich_king_vile_spirit_summon_AuraScript::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); OnEffectPeriodic += AuraEffectPeriodicFn(spell_lich_king_vile_spirit_summon_AuraScript::OnPeriodic, EFFECT_1, SPELL_AURA_LINKED); } }; AuraScript* GetAuraScript() const { return new spell_lich_king_vile_spirit_summon_AuraScript(); } }; class spell_lich_king_vile_spirit_summon_visual : public SpellScriptLoader { public: spell_lich_king_vile_spirit_summon_visual() : SpellScriptLoader("spell_lich_king_vile_spirit_summon_visual") { } class spell_lich_king_vile_spirit_summon_visual_AuraScript : public AuraScript { PrepareAuraScript(spell_lich_king_vile_spirit_summon_visual_AuraScript); void OnPeriodic(AuraEffect const* aurEff) { PreventDefaultAction(); Unit* caster = GetCaster(); if (!caster || !caster->isAlive()) return; Position pos; caster->GetRandomNearPosition(pos, 13.0f); pos.m_positionZ = npc_vile_spirit::Z_VILE_SPIRIT; uint32 triggeredSpell = aurEff->GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; caster->CastSpell(pos.m_positionX, pos.m_positionY, pos.m_positionZ, triggeredSpell, true); } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_lich_king_vile_spirit_summon_visual_AuraScript::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const { return new spell_lich_king_vile_spirit_summon_visual_AuraScript(); } }; class spell_lich_king_winter : public SpellScriptLoader { public: spell_lich_king_winter() : SpellScriptLoader("spell_lich_king_winter") { } //68981 class spell_lich_king_winter_AuraScript : public AuraScript { PrepareAuraScript(spell_lich_king_winter_AuraScript) void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { if (Unit* caster = GetCaster()) { if (UnitAI* pBossAI = caster->GetAI()) pBossAI->DoAction(ACTION_CANCEL_ALL_TRANSITION_EVENTS); caster->CastSpell(caster, SPELL_QUAKE, true); DoScriptText(SAY_BROKEN_ARENA, caster); InstanceScript* instance = caster->GetInstanceScript(); if (!instance) return; } } void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes mode) { Unit* caster = GetCaster(); if (!caster || !caster->isAlive()) return; InstanceScript* instance = caster->GetInstanceScript(); if (!instance) return; //Rebuild platform's edge only in second transition phase if (UnitAI* pAI = caster->GetAI()) if (pAI->GetData(DATA_PHASE) == PHASE_4_TRANSITION) { //Two spells should be casted in this very sequence to get working animation caster->CastSpell(caster, SPELL_WMO_INTACT, true); caster->CastSpell(caster, SPELL_WMO_REBUILD, true); } //Destroying ice shards if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_ICE_SHARD_1))) go->SetGoState(GO_STATE_ACTIVE); if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_ICE_SHARD_2))) go->SetGoState(GO_STATE_ACTIVE); if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_ICE_SHARD_3))) go->SetGoState(GO_STATE_ACTIVE); if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_ICE_SHARD_4))) go->SetGoState(GO_STATE_ACTIVE); if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_EDGE_DESTROY_WARNING))) go->SetGoState(GO_STATE_READY); if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_FROSTY_EDGE_INNER))) go->SetGoState(GO_STATE_READY); if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_FROSTY_EDGE_OUTER))) go->SetGoState(GO_STATE_ACTIVE); } void Register() { OnEffectApply += AuraEffectApplyFn(spell_lich_king_winter_AuraScript::OnApply, EFFECT_1, SPELL_AURA_MOD_ROOT, AURA_EFFECT_HANDLE_REAL); OnEffectRemove += AuraEffectRemoveFn(spell_lich_king_winter_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_lich_king_winter_AuraScript(); } }; class spell_lich_king_quake : public SpellScriptLoader { public: spell_lich_king_quake() : SpellScriptLoader("spell_lich_king_quake") { } //72262 class spell_lich_king_quake_AuraScript : public AuraScript { PrepareAuraScript(spell_lich_king_quake_AuraScript) void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* caster = GetCaster(); if (!caster) return; caster->CastSpell(caster, SPELL_WMO_INTACT, true); caster->CastSpell(caster, SPELL_WMO_DESTROY, true); if (InstanceScript* instance = GetTarget()->GetInstanceScript()) { if (Creature* lichKing = Unit::GetCreature(*GetTarget(), instance->GetData64(DATA_THE_LICH_KING))) lichKing->AI()->DoAction(ACTION_PHASE_SWITCH_2); if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_EDGE_DESTROY_WARNING))) go->SetGoState(GO_STATE_READY); if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_FROSTY_EDGE_INNER))) go->SetGoState(GO_STATE_ACTIVE); if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_FROSTY_EDGE_OUTER))) go->SetGoState(GO_STATE_READY); } } void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes mode) { Unit* caster = GetCaster(); if (!caster || !caster->isAlive()) return; InstanceScript* instance = caster->GetInstanceScript(); if (!instance) return; if (GameObject* go = ObjectAccessor::GetGameObject(*caster, instance->GetData64(GUID_EDGE_DESTROY_WARNING))) go->SetGoState(GO_STATE_ACTIVE); } void Register() { OnEffectApply += AuraEffectApplyFn(spell_lich_king_quake_AuraScript::OnApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); OnEffectRemove += AuraEffectRemoveFn(spell_lich_king_quake_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_lich_king_quake_AuraScript(); } }; class spell_vile_spirit_distance_check : public SpellScriptLoader { public: spell_vile_spirit_distance_check() : SpellScriptLoader("spell_vile_spirit_distance_check") { } class spell_vile_spirit_distance_check_SpellScript : public SpellScript { PrepareSpellScript(spell_vile_spirit_distance_check_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { if (!(GetHitUnit() && GetHitUnit()->isAlive())) return; if (Unit* caster = GetCaster()) { caster->CastSpell(caster, SPELL_SPIRIT_BURST, true); if (InstanceScript* instance = caster->GetInstanceScript()) instance->SetData(DATA_NECK_DEEP_ACHIEVEMENT, FAIL); caster->GetAI()->DoAction(ACTION_DESPAWN); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_vile_spirit_distance_check_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_vile_spirit_distance_check_SpellScript(); } }; class spell_ice_burst_distance_check : public SpellScriptLoader { public: spell_ice_burst_distance_check() : SpellScriptLoader("spell_ice_burst_distance_check") { } class spell_ice_burst_distance_check_SpellScript : public SpellScript { PrepareSpellScript(spell_ice_burst_distance_check_SpellScript); void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); if (!(GetHitUnit() && GetHitUnit()->isAlive())) return; if (GetHitUnit()->GetTypeId() != TYPEID_PLAYER) return; if (Unit* caster = GetCaster()) caster->CastSpell(caster, SPELL_ICE_BURST, true); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_ice_burst_distance_check_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_ice_burst_distance_check_SpellScript(); } }; class spell_valkyr_carry_can_cast : public SpellScriptLoader { public: spell_valkyr_carry_can_cast() : SpellScriptLoader("spell_valkyr_carry_can_cast") { } class spell_valkyr_carry_can_cast_SpellScript : public SpellScript { PrepareSpellScript(spell_valkyr_carry_can_cast_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(), *target = GetHitUnit(); InstanceScript* instance = GetCaster()->GetInstanceScript(); if (!(target && target->isAlive() && caster)) return; if (instance) if (Creature* lichKing = ObjectAccessor::GetCreature(*caster, instance->GetData64(DATA_THE_LICH_KING))) if (target->GetTypeId() == TYPEID_PLAYER && target != lichKing->getVictim()) target->CastSpell(caster, SPELL_VALKYR_GRAB_PLAYER, true); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_valkyr_carry_can_cast_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_valkyr_carry_can_cast_SpellScript(); } }; class spell_valkyr_target_search : public SpellScriptLoader { public: spell_valkyr_target_search() : SpellScriptLoader("spell_valkyr_target_search") { } class spell_valkyr_target_search_SpellScript : public SpellScript { PrepareSpellScript(spell_valkyr_target_search_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { Unit* target = GetHitUnit(), *caster = GetCaster(); if (!(target && target->isAlive() && caster)) return; if (target->GetTypeId() == TYPEID_PLAYER) { if (UnitAI* pAI = caster->GetAI()) { pAI->SetGUID(target->GetGUID(), TYPE_VICTIM); pAI->DoAction(ACTION_CHARGE_PLAYER); } } } void FilterTargets(std::list<Unit*>& unitList) { } void Register() { OnUnitTargetSelect += SpellUnitTargetFn(spell_valkyr_target_search_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnEffectHitTarget += SpellEffectFn(spell_valkyr_target_search_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_valkyr_target_search_SpellScript(); } }; class spell_valkyr_eject_passenger : public SpellScriptLoader { public: spell_valkyr_eject_passenger() : SpellScriptLoader("spell_valkyr_eject_passenger") { } class spell_valkyr_eject_passenger_SpellScript : public SpellScript { PrepareSpellScript(spell_valkyr_eject_passenger_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { if (!(GetCaster() && GetCaster()->IsVehicle())) return; if (Vehicle* vehicle = GetCaster()->GetVehicleKit()) vehicle->RemoveAllPassengers(); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_valkyr_eject_passenger_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_valkyr_eject_passenger_SpellScript(); } }; class spell_vile_spirit_target_search : public SpellScriptLoader { public: spell_vile_spirit_target_search() : SpellScriptLoader("spell_vile_spirit_target_search") { } class spell_vile_spirit_target_search_SpellScript : public SpellScript { PrepareSpellScript(spell_vile_spirit_target_search_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { if (!(GetHitUnit() && GetHitUnit()->isAlive() && GetCaster())) return; if (GetHitUnit()->GetTypeId() == TYPEID_PLAYER) GetCaster()->AddThreat(GetHitUnit(), 1000.0f); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_vile_spirit_target_search_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_vile_spirit_target_search_SpellScript(); } }; class spell_lich_king_tirion_mass_resurrection : public SpellScriptLoader { public: spell_lich_king_tirion_mass_resurrection() : SpellScriptLoader("spell_lich_king_tirion_mass_resurrection") { } class spell_lich_king_tirion_mass_resurrection_SpellScript : public SpellScript { PrepareSpellScript(spell_lich_king_tirion_mass_resurrection_SpellScript) void MassResurrect(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); if (Unit* caster = GetCaster()) { const Map::PlayerList &PlayerList = caster->GetMap()->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* player = i->getSource()) caster->CastSpell(player, SPELL_REVIVE_EFFECT, true); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_lich_king_tirion_mass_resurrection_SpellScript::MassResurrect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_lich_king_tirion_mass_resurrection_SpellScript(); } }; class spell_lich_king_harvest_soul : public SpellScriptLoader { public: spell_lich_king_harvest_soul() : SpellScriptLoader("spell_lich_king_harvest_soul") { } class spell_lich_king_harvest_soul_AuraScript : public AuraScript { PrepareAuraScript(spell_lich_king_harvest_soul_AuraScript) class TeleportToFrostmourneRoom : public BasicEvent { public: TeleportToFrostmourneRoom(Player* player, uint8 attempts): pPlayer(player), attemptsLeft(attempts) { } bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) { pPlayer->NearTeleportTo(FrostmourneRoom[0].m_positionX, FrostmourneRoom[0].m_positionY, FrostmourneRoom[0].m_positionZ, FrostmourneRoom[0].m_orientation); pPlayer->RemoveAurasDueToSpell(SPELL_FEIGN_DEATH); if (--attemptsLeft) pPlayer->m_Events.AddEvent(new TeleportToFrostmourneRoom(pPlayer, attemptsLeft), pPlayer->m_Events.CalculateTime(uint64(1000))); else pPlayer->CastSpell(pPlayer, SPELL_FROSTMOURNE_ROOM_TELEPORT_VISUAL, true); return true; } private: Player* pPlayer; uint8 attemptsLeft; }; void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes mode) { Unit* target = GetTarget(), *caster = GetCaster(); if (target->GetTypeId() != TYPEID_PLAYER || !caster) return; Player* player = target->ToPlayer(); bool isHeroic = caster->GetMap()->IsHeroic(); if (!player || !player->isAlive()) caster->CastSpell(caster, isHeroic ? SPELL_HARVESTED_SOUL_HEROIC : SPELL_HARVESTED_SOUL_NORMAL, true); player->CastSpell(player, SPELL_HARVESTED_SOUL_FROSTMOURNE_PLAYER_BUFF, true); if (isHeroic) player->CastSpell(player, SPELL_HARVEST_SOUL_HEROIC_FROSTMOURNE_PLAYER_DEBUFF, true); player->CastSpell(player, SPELL_IN_FROSTMOURNE_ROOM, true); //Should use Feign death to emulate player's death player->CastSpell(player, SPELL_FEIGN_DEATH, true); player->getThreatManager().clearReferences(); player->GetMap()->LoadGrid(FrostmourneRoom[0].m_positionX, FrostmourneRoom[0].m_positionY); player->m_Events.AddEvent(new TeleportToFrostmourneRoom(player, 2), player->m_Events.CalculateTime(uint64(2000))); InstanceScript* instance = player->GetInstanceScript(); if (instance) if (Creature* lichKing = ObjectAccessor::GetCreature(*caster, instance->GetData64(DATA_THE_LICH_KING))) lichKing->AI()->DoAction(ACTION_PREPARE_FROSTMOURNE_ROOM); } void Register() { OnEffectRemove += AuraEffectRemoveFn(spell_lich_king_harvest_soul_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_lich_king_harvest_soul_AuraScript(); } }; class spell_lich_king_fury_of_frostmourne : public SpellScriptLoader { public: spell_lich_king_fury_of_frostmourne() : SpellScriptLoader("spell_lich_king_fury_of_frostmourne") { } class spell_lich_king_fury_of_frostmourneSpellScript : public SpellScript { PrepareSpellScript(spell_lich_king_fury_of_frostmourneSpellScript); // function called on server startup // checks if script has data required for it to work bool Validate(SpellEntry const* /*spellEntry*/) { if (!sSpellStore.LookupEntry(SPELL_FURY_OF_FROSTMOURNE_NORES)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { if (Unit* target = GetHitUnit()) GetCaster()->AddAura(SPELL_FURY_OF_FROSTMOURNE_NORES, target); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_lich_king_fury_of_frostmourneSpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_APPLY_AURA); } }; SpellScript* GetSpellScript() const { return new spell_lich_king_fury_of_frostmourneSpellScript(); } }; void AddSC_boss_lichking() { new boss_the_lich_king(); new npc_tirion_icc(); new npc_valkyr_shadowguard(); new npc_vile_spirit(); new npc_shambling_horror(); new npc_raging_spirit(); new npc_ice_sphere(); new npc_defile(); new npc_spirit_warden(); new npc_terenas_menethil(); new npc_shadow_trap(); new spell_lich_king_necrotic_plague(); new spell_lich_king_infection(); new spell_lich_king_valkyr_summon(); new spell_lich_king_vile_spirit_summon(); new spell_lich_king_vile_spirit_summon_visual(); new spell_lich_king_winter(); new spell_vile_spirit_distance_check(); new spell_lich_king_pain_and_suffering_effect(); new spell_ice_burst_distance_check(); new spell_lich_king_quake(); new spell_valkyr_carry_can_cast(); new spell_valkyr_target_search(); new spell_valkyr_eject_passenger(); new spell_vile_spirit_target_search(); new spell_lich_king_defile(); new spell_lich_king_tirion_mass_resurrection(); new spell_lich_king_harvest_soul(); new spell_lich_king_fury_of_frostmourne(); }
[ [ [ 1, 5 ], [ 7, 257 ], [ 259, 331 ], [ 333, 1741 ], [ 1743, 2061 ], [ 2063, 2406 ], [ 2408, 2470 ], [ 2472, 2496 ], [ 2498, 2597 ], [ 2599, 2732 ], [ 2734, 2734 ], [ 2737, 2737 ], [ 2739, 2826 ], [ 2828, 2913 ], [ 2915, 2921 ], [ 2923, 2923 ], [ 2926, 3007 ], [ 3009, 3026 ], [ 3032, 3635 ], [ 3637, 3643 ], [ 3652, 3810 ] ], [ [ 6, 6 ], [ 258, 258 ], [ 332, 332 ], [ 1742, 1742 ], [ 2062, 2062 ], [ 2407, 2407 ], [ 2471, 2471 ], [ 2497, 2497 ], [ 2598, 2598 ], [ 2733, 2733 ], [ 2735, 2736 ], [ 2738, 2738 ], [ 2827, 2827 ], [ 2914, 2914 ], [ 2922, 2922 ], [ 2924, 2925 ], [ 3008, 3008 ], [ 3027, 3031 ], [ 3636, 3636 ], [ 3644, 3651 ] ] ]
731375405739898153333dbb7495ba7b4f910f03
de98f880e307627d5ce93dcad1397bd4813751dd
/3libs/ut/include/CPYSTDLG.h
252edf40502fb9e8e729905964089f7e8e9ba8b1
[]
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
5,109
h
// ========================================================================== // Class Specification : COXCopyStatusDialog // ========================================================================== // Header file : cpystdlg.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 COXModelessDialog // YES Is a Cwnd. // YES Two stage creation (constructor & Create()) // YES Has a message map // YES/NO Needs a resource (template) // NO Persistent objects (saveable on disk) // NO Uses exceptions // ////////////////////////////////////////////////////////////////////////// // Desciption : // This class is used to give the user some feedback regarding the copy process // The user is also able to cancel the process via the cancel button // Remark: // // Prerequisites (necessary conditions): // ///////////////////////////////////////////////////////////////////////////// #ifndef __COPYSTATUS_H__ #define __COPYSTATUS_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "OXDllExt.h" #include "mdeldlg.h" class OX_CLASS_DECL COXCopyStatusDialog : public COXModelessDialog { DECLARE_DYNAMIC(COXCopyStatusDialog) // Data members ------------------------------------------------------------- public: enum ECopyStatus { CSUndefined = 0, CSCopying = 1, CSRemoving = 2, }; static const ECopyStatus CS_FIRST; static const ECopyStatus CS_LAST; protected: BOOL m_bCancelled; CWnd* m_pParentWnd; CStatic* m_pFromLabel; CStatic* m_pToLabel; CStatic* m_pFromMsg; CStatic* m_pToMsg; private: // Member functions --------------------------------------------------------- public: COXCopyStatusDialog(COXCopyStatusDialog** ppSelf = NULL, CWnd* pParentWnd = NULL); // --- In : ppSelf : a pointer to itself, used to null out automatic // any reference the user made to this dialog // pParentWnd : the parent of this modeless dialog // --- Out : // --- Returns : // --- Effect : Contructor of object // It will initialize the internal state virtual BOOL Create(); // --- In : // --- Out : // --- Returns : // --- Effect : Creates the Resource template in memory and Calls CreateIndirect // to finally create the modeless dlg with it. virtual BOOL IsCancelled(); // --- In : // --- Out : // --- Returns : Whether the user has pushed the cancel button or not // --- Effect : virtual void OnCancel(); // --- In : // --- Out : // --- Returns : // --- Effect : Called when the user clicks the Cancel button (the button with an ID of IDCANCEL). // The Cancelled member is set virtual void SetStatusText(ECopyStatus eCopyStatus, LPCTSTR pszFromText = _T(""), LPCTSTR pszToText = _T("")); // --- In : eCopyStatus : The status of the copy process // pszFromText : the text representing the file you're copying from // pszToText : the text representing the file you're copying to // --- Out : // --- Returns : Succeeded or not // --- Effect : Gives the user some feedback on the copy process by setting some text to // a few Static variables. static int nCopyAnsiToWideChar (LPWORD lpWCStr, LPTSTR lpAnsiIn); // --- In : lpWCStr : Wide char String to copy to // lpAnsiIn : ansi String to copy from // --- Out : // --- Returns : // --- Effect :Takes second parameter as Ansi string, copies // it to first parameter as wide character (16-bits / char) string, // and returns integer number of wide characters (words) in string // including the trailing wide char NULL) #ifdef _DEBUG virtual void Dump(CDumpContext&) const; virtual void AssertValid() const; #endif //_DEBUG virtual ~COXCopyStatusDialog(); // --- In : // --- Out : // --- Returns : // --- Effect : Destructor of object protected: BOOL CreateControls(); BOOL CreateStatic(UINT nIDC, LPCTSTR pszText = _T(""), const CRect& Position=CRect(0,0,0,0)); virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //{{AFX_MSG(CFindDialog) //}}AFX_MSG DECLARE_MESSAGE_MAP() private: }; #endif // ==========================================================================
[ [ [ 1, 159 ] ] ]
23ddb7eb088422e11c79887091f62f40c159fff6
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/wave/test/testwave/testfiles/t_1_037.cpp
21e621b30a13619ab0b2bcab62c61a395485b2d7
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
740
cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2009 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // the following concatenation failed //R #line 16 "t_1_037.cpp" //R // bool; #define _VARIANT_BOOL /##/ _VARIANT_BOOL bool; //H 10: t_1_037.cpp(15): #define //H 08: t_1_037.cpp(15): _VARIANT_BOOL=/##/ //H 01: t_1_037.cpp(15): _VARIANT_BOOL //H 02: // //H 03: //
[ "metrix@Blended.(none)" ]
[ [ [ 1, 22 ] ] ]
8faf93938f253e4e71c90a309d959579346be9c3
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/Learning OpenCV/Chapter 3 - Getting to Know OpenCV/Exercise_3_5.cpp
f77626fed73ac53f8b7543bcf475d98433369fd5
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,090
cpp
///////////////////////////////////////////////////////////////// // Date: 2009-10-16 // Author: Yishi Guo // Exercise: 3.5 // Page: 88 // Content: Practice using region of interest(ROI). ///////////////////////////////////////////////////////////////// #include <cv.h> #include <highgui.h> int main( int argc, char** argv ) { IplImage* img = cvCreateImage( cvSize(210, 210), IPL_DEPTH_8U, 1 ); cvSetZero( img ); // Processing // for ( int value = 0, x = 0; value <= 200; value += 20, x += 10 ) { CvRect rect = cvRect( x, x, 210-2*x, 210-2*x ); // ROI Rectangle // cvRect( int x, int y, int width, int height ); cvSetImageROI( img, rect ); // Set Image ROI cvSet( img, cvScalarAll(value) ); // Set the ROI Value cvResetImageROI( img ); // Release Image ROI } cvNamedWindow( "Exercise 3-5", CV_WINDOW_AUTOSIZE ); cvShowImage( "Exercise 3-5", img ); cvWaitKey(0); cvReleaseImage( &img ); cvDestroyWindow( "Exercise 3-5" ); return 0; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 40 ] ] ]
ac7220ac4a8081a95e01c5742a8191a2c4aa5e98
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Application/SysCAD/ArchMngr.H
632c72cc999c7bc13e7d2037d681946ad5c8d892
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,665
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #ifndef __ARCHMAN_H #define __ARCHMAN_H #ifndef __EXECUTIV_H #include "executiv.h" #endif #include <afxtempl.h> //------------------------------------------------------------------------ class CArchiveManager; // forward; //------------------------------------------------------------------------ class CArcAddress { public: CArcAddress() { m_lInputIndex=-1; m_lFieldIndex=-1; }; void SetTag(LPCTSTR Tag)//, CCnvIndex iCnv, LPCTSTR CnvTxt) { m_sTag=Tag; }; void SetIndex(CArchiveManager & AM); char* GetValue(CArchiveManager & AM); double GetValue(CArchiveManager & AM, LPTSTR CnvTxt); CCnvIndex GetCnvIndex(CArchiveManager & AM); public: CString m_sTag; long m_lInputIndex; long m_lFieldIndex; }; //------------------------------------------------------------------------ class CArchiveInput { public: CArchiveInput(); void PutValue(CPkDataItem &PItem); void PutValue(double Value); void PutValue(char* Value); double GetValue(LPTSTR CnvTxt);// { return Cnvs[m_iCnv]->Human(m_dValue, CnvTxt); }; char* GetValue();// { return (char*)(const char*)m_sValue; }; bool IsString() { return (IsStrng(m_iType)!=0); }; public: CString m_sScdMTag; byte m_iType; CCnvIndex m_iCnv; //conversion index protected: double m_dValue; CString m_sValue; }; class CAInputArray : public CArray < CArchiveInput*, CArchiveInput* > {}; //------------------------------------------------------------------------ class CArchiveDBField { public: CArchiveDBField(CArchiveManager *pAM); ~CArchiveDBField(); bool GetValue(CPkDataList &List, /*CPkDataItem * &pPItem,*/ bool Complete); double GetValue() { return m_dCalculatedValue; }; char* GetSValue() { return (char*)(const char*)m_sInputValue; }; void Execute(CXM_TimeControl &CB); void StepDone(CXM_TimeControl &CB, double DeltaSecs); void ClearChanged() { m_bChanged=false; }; bool Changed() { return m_bChanged; }; ADOX::DataTypeEnum dbType(); ADOX::ColumnAttributesEnum dbAttr(); public: CArchiveManager &m_rAM; // By Example CArcAddress m_Src; // m_Src.m_sTag = SomeTag CString m_sTable; // ATable CString m_sFldTag; // SomeTag-AVG CString m_sScdMTag; // ATable.SomeTag.AVG byte m_iFn; byte m_iMeas; byte m_iFirstOnRewind; long m_lTableIndex; byte m_iType; long m_iSize; Strng m_sCnvTxt; //engineering units CString m_sDescription; bool m_bSystem; bool m_bResetReqd; bool m_bChanged; double m_dInputValue; CString m_sInputValue; long m_nSamples; double m_dCalculatedValue; // ... double m_dPrevInputMeas; }; class CArchiveTrigger { public: CArchiveTrigger(CArchiveManager *pAM); ~CArchiveTrigger(); bool Parse(LPCTSTR Table, int No, LPCTSTR Cfg); bool TestTrigger(); public: CArchiveManager &m_rAM; CString m_sName; CArcAddress m_Src; Strng m_sCnvTxt; //engineering units bool m_bInitReqd; bool m_bRewindReqd; bool m_bStepTest; bool m_bRise; bool m_bFall; bool m_bAny; long m_iTriggerFiredCount; double m_dPrevAny; double m_dPrevEdge; double m_dDeltaRise; double m_dDeltaFall; double m_dDeltaAny; }; class CADBFieldArray : public CArray<CArchiveDBField*, CArchiveDBField*> {}; class CADBFieldMap : public CMap <LPCTSTR, LPCTSTR, long, long> {}; class CATriggerArray : public CArray <CArchiveTrigger*, CArchiveTrigger*> {}; class CArchiveDBTable { public: CArchiveDBTable(CArchiveManager *pAM, LPCTSTR TbName); CArchiveDBTable(CArchiveManager *pAM, LPCTSTR TbName, byte iTbFmt, LPCTSTR sPath, byte iSigDigits); ~CArchiveDBTable(); bool AddPeriod(long Period, long Offset); bool AddTrigger(LPCTSTR Cfg); bool Execute(CXM_TimeControl &CB); bool StepDone(CXM_TimeControl &CB); bool CreateDBTable(); bool DeleteDBTable(); bool ReOpenTxtTable(bool Rewind); bool CreateDBFields(ADOX::_TablePtr & pTbl); bool CreateTxtFields(); bool CreateDBField(ADOX::_TablePtr & pTbl, bool SysFld, LPCTSTR FldName, ADOX::DataTypeEnum FldType, int Size, ADOX::ColumnAttributesEnum FldAttr, bool MakeAutoInc=false); bool CreateDBRecordset(); bool CloseDBTable(); void AddTimeFieldsDB(CXM_TimeControl &CB); void AddTimeFieldsTxt(CXM_TimeControl &CB, char Separ); bool AddDBRecord(CXM_TimeControl &CB); bool AddMsgRecord(CXM_TimeControl &CB, CMsgLogItem & Msg); bool AddEventRecord(CXM_TimeControl &CB, LPCTSTR Tag, LPCTSTR Msg); bool DeleteDBRecords(); long TriggerCount() { return m_Triggers.GetSize(); }; long FieldCount() { return m_Fields.GetSize(); }; CArchiveTrigger &GetTrigger(long Index) { return *m_Triggers[Index]; }; CArchiveDBField &GetField(long Index) { return *m_Fields[Index]; }; public: CArchiveManager &m_rAM; CString m_sName; CString m_sCfgSection; // Starts @ 1 long m_lPeriod; long m_lOffset; bool m_bInitReqd; bool m_bRewindReqd; bool m_bClearOnRewind; CTimeValue m_dNextSaveTime; bool m_bPeriodOn; CATriggerArray m_Triggers; CADBFieldArray m_Fields; byte m_iFormat; bool m_bOn; ADODB::_RecordsetPtr m_pRst; CString m_sPath; Strng m_sFileName; FILE * m_hFile; byte m_nSigDigits; long m_nTxtRecNo; }; class CADBTableArray : public CArray<CArchiveDBTable*, CArchiveDBTable*> {}; //======================================================================== //======================================================================== //======================================================================== //------------------------------------------------------------------------ class CArchiveManager : public CExecObj//, public CArchiveManagerBase { friend class CArchiveDBTable; friend class CAddToArchive; public: CArchiveManager(); ~CArchiveManager(); void AddTimeFields(LPCTSTR Table); void AddReqdTables(); static DWORD ReadOptions(LPCTSTR FileName); static void WriteOptions(LPCTSTR FileName, DWORD Opts); bool ReadCfg(); static bool CheckCfg(LPCTSTR CfgFile); bool CompleteOpen(); long DoAddField(LPCTSTR Table, LPCTSTR Field, LPCTSTR CfgString); long AddField(LPCTSTR Table, LPCTSTR Field, LPCTSTR CfgString); long AddField(bool System, LPCTSTR Tag, LPCTSTR Table, LPCTSTR FldName, byte iFn, byte iMeas, byte iFirst, byte iType, int iSize, CCnvIndex iCnv, LPCTSTR CnvTxt, LPCTSTR Description); long AppendField(bool System, LPCTSTR Tag, LPCTSTR Table, LPCTSTR FldName, byte iFn, byte iMeas, byte iFirst, byte iType, int iSize, CCnvIndex iCnv, LPCTSTR CnvTxt, LPCTSTR Description); //bool ConnectField(int Index); //bool DisConnectField(int Index); long AddInput(LPCTSTR Tag);//, CCnvIndex iCnv, LPCTSTR CnvTxt); long FindInputIndex(LPCTSTR Tag); long FindFieldIndex(LPCTSTR Tag); long FindTable(LPCTSTR TbName); long FindField(LPCTSTR TbName, LPCTSTR FldName); long FindField(long iTb, LPCTSTR FldName); byte FieldType(long Index); bool GetCalcValue(long Index, CPkDataList &List, /*CPkDataItem * &pPItem,*/ bool Complete); long NoOfChanges(); long GetNextChange(); long TableCount() { return m_Tables.GetSize(); }; long FieldCount() { return m_Fields.GetSize(); }; long InputCount() { return m_Inputs.GetSize(); }; CArchiveDBTable & GetTable(long Index); CArchiveInput & GetInput(long ItemIndex); CArchiveDBField & GetField(long ItemIndex); bool OpenTheDB(); bool OpenDB(); bool CreateDBTables(); bool RestartDBTables(); bool CreateDBRecordsets(); bool CloseDB(); bool Start(CXM_TimeControl &CB); bool Stop(); bool Execute(CXM_TimeControl &CB); bool StepDone(CXM_TimeControl &CB); void DisplayException(_com_error & e, DWORD LogOpts=0, LPCTSTR strMsg1="", LPCTSTR strMsg2=""); bool SendStart(); bool SendExecute(); bool SendStepDone(); bool SendStop(); void SetEvent() { ::SetEvent(m_evDone); }; bool Rewind() { return m_bRewind; }; void Initialise(); //int Configure(LPCTSTR CfgFile, bool OpenDBOnRun); void Options(char* pGotoTag = NULL); void CloseOptions(); int Open(LPCTSTR CfgFile, bool FirstClear); bool ConnectAll(); bool DisConnectAll(); bool Close(BOOL SaveState = TRUE); void Restart(); void SaveTags(FilingControlBlock &FCB, BOOL SaveAll); void LoadTags(FilingControlBlock &FCB); void AddFieldDlg(TagInfoBlk &IB); void LogAMessage(CMsgLogItem &Itm); void LogAnEvent(LPCTSTR Tag, LPCTSTR Msg); CArchiveDBTable & MessageLog() { return *m_pMessageLog; }; CArchiveDBTable & EventLog() { return *m_pEventLog; }; private : // ExecObj Overrides virtual DWORD EO_Message(CXMsgLst &XM, CXM_Route &Route); virtual flag EO_SetTime(CTimeValue TimeRqd, bool Rewind); virtual flag EO_QueryTime(CXM_TimeControl &CB, CTimeValue &TimeRqd, CTimeValue &dTimeRqd); virtual void EO_SetModelState(eScdMdlStateActs RqdState, Strng_List &RqdTags); virtual flag EO_Start(CXM_TimeControl &CB); virtual void EO_QuerySubsReqd(CXMsgLst &XM); virtual void EO_QuerySubsAvail(CXMsgLst &XM, CXMsgLst &XMRet); virtual flag EO_ReadSubsData(CXMsgLst &XM); virtual flag EO_WriteSubsData(CXMsgLst &XM, flag FirstBlock, flag LastBlock); virtual DWORD EO_ReadTaggedItem(CXM_ObjectTag & ObjTag, CXM_ObjectData &ObjData, CXM_Route &Route); virtual int EO_WriteTaggedItem(CXM_ObjectData &ObjData, CXM_Route &Route); virtual flag EO_Execute(CXM_TimeControl &CB, CEOExecReturn &EORet); virtual flag EO_StepDone(CXM_TimeControl &CB, flag StepExecuted); virtual flag EO_Stop(CXM_TimeControl &CB); virtual flag EO_TagsNotAvail(CXMsgLst &XM); virtual flag EO_BeginSave(FilingControlBlock &FCB); virtual flag EO_SaveDefinedData(FilingControlBlock &FCB, Strng &Tag, CXMsgLst &XM); virtual flag EO_SaveOtherData(FilingControlBlock &FCB); virtual flag EO_BeginLoad(FilingControlBlock &FCB); virtual flag EO_LoadDefinedData(FilingControlBlock &FCB, CXMsgLst &XM); virtual flag EO_LoadOtherData(FilingControlBlock &FCB); virtual flag EO_ConnectsDone(FilingControlBlock &FCB); virtual flag EO_DataLoaded(FilingControlBlock &FCB); virtual flag EO_EndLoad(FilingControlBlock &FCB); virtual int EO_QueryChangeTag(pchar pOldTag, pchar pNewTag); virtual int EO_ChangeTag(pchar pOldTag, pchar pNewTag); virtual int EO_ChangeTagDone(pchar pOldTag, pchar pNewTag); virtual int EO_QueryDeleteTags(Strng_List & Tags); virtual int EO_DeleteTags(Strng_List & Tags); virtual int EO_DeleteTagsDone(Strng_List & Tags); virtual void EO_OnAppActivate(BOOL bActive); virtual flag EO_RequestTagInfo(RequestTagInfoRec& Rqst, ReplyTagInfoRec& Info); protected: bool m_bOn; bool m_bAllowTagAccess; bool m_bDBOK, m_bRegistered, //m_bOpenDBOnRun, m_bDoneLocalLoadSave; DWORD m_dwOptions; CString m_sCfgFile; CString m_sDataFile; CADBTableArray m_Tables; CADBFieldArray m_Fields; CADBFieldMap m_FieldMap; CAInputArray m_Inputs; CArchiveDBTable *m_pMessageLog; CArchiveDBTable *m_pEventLog; int m_iBusyLoggingMsg; int m_iBusyLoggingEvent; ADODB::_ConnectionPtr m_pCnn; ADOX::_CatalogPtr m_pCat; bool m_bDBExclusive; bool m_bDBReadOnly; CString m_sDBConnect; long m_lChgSrchStart; long m_iLoadSaveCnt; CEvent m_evDone; CString m_sPrevTempFile; //file last used for saving driver state long m_nFieldsOpn; long m_nTablesOpn; long m_lInputOffset; long m_lBusyChanges; bool m_bSubsRead_Busy; CString m_sSeparator; bool m_bFirstClear; bool m_bRewind; bool m_TimeAtStartValid; CTimeValue m_TimeAtStart; CTimeValue m_TimeOfLastExec; }; inline byte CArchiveManager::FieldType(long Index) { return m_Fields[Index]->m_iType; }; inline CArchiveDBTable & CArchiveManager::GetTable(long ItemIndex) { return *m_Tables[ItemIndex]; }; inline CArchiveInput & CArchiveManager::GetInput(long ItemIndex) { return *m_Inputs[ItemIndex]; }; inline CArchiveDBField & CArchiveManager::GetField(long ItemIndex) { return *m_Fields[ItemIndex]; }; inline bool CArchiveManager::GetCalcValue(long Index, CPkDataList &List, /*CPkDataItem * &pPItem,*/ bool Complete) { return !m_Fields[Index]->m_bSystem && m_Fields[Index]->GetValue(List, /*pPItem,*/ Complete); }; //------------------------------------------------------------------------- extern CArchiveManager* gs_pArcMan; //pointer to one and only driver manager EO //------------------------------------------------------------------------- #endif
[ [ [ 1, 27 ], [ 29, 29 ], [ 31, 31 ], [ 41, 46 ], [ 56, 60 ], [ 62, 62 ], [ 64, 73 ], [ 90, 94 ], [ 98, 99 ], [ 102, 103 ], [ 106, 106 ], [ 113, 117 ], [ 128, 128 ], [ 132, 132 ], [ 135, 137 ], [ 139, 151 ], [ 186, 186 ], [ 189, 193 ], [ 197, 197 ], [ 199, 200 ], [ 202, 202 ], [ 206, 207 ], [ 213, 232 ], [ 237, 237 ], [ 239, 240 ], [ 248, 254 ], [ 256, 268 ], [ 270, 271 ], [ 273, 273 ], [ 277, 279 ], [ 282, 284 ], [ 287, 287 ], [ 289, 290 ], [ 296, 301 ], [ 308, 311 ], [ 316, 321 ], [ 325, 331 ], [ 334, 336 ], [ 341, 342 ], [ 392, 397 ], [ 400, 408 ] ], [ [ 28, 28 ], [ 30, 30 ], [ 32, 32 ], [ 34, 40 ], [ 47, 48 ], [ 55, 55 ], [ 61, 61 ], [ 74, 78 ], [ 82, 88 ], [ 95, 97 ], [ 100, 100 ], [ 104, 105 ], [ 118, 121 ], [ 123, 127 ], [ 129, 131 ], [ 133, 133 ], [ 152, 185 ], [ 187, 188 ], [ 194, 196 ], [ 198, 198 ], [ 201, 201 ], [ 203, 205 ], [ 208, 212 ], [ 233, 236 ], [ 238, 238 ], [ 242, 247 ], [ 255, 255 ], [ 274, 276 ], [ 280, 281 ], [ 285, 286 ], [ 288, 288 ], [ 291, 294 ], [ 302, 307 ], [ 312, 315 ], [ 322, 324 ], [ 332, 333 ], [ 337, 340 ], [ 343, 344 ], [ 348, 390 ], [ 398, 399 ] ], [ [ 33, 33 ], [ 49, 54 ], [ 63, 63 ], [ 79, 81 ], [ 89, 89 ], [ 101, 101 ], [ 107, 112 ], [ 122, 122 ], [ 134, 134 ], [ 138, 138 ], [ 241, 241 ], [ 269, 269 ], [ 272, 272 ], [ 295, 295 ], [ 345, 347 ], [ 391, 391 ] ] ]
a0f5844868a78a1bb61880703fc5208968449930
984de065178d4905b7096dc1f018b274dacb540d
/id3lib-ruby-0.5.0/ext/id3lib_api_wrap.cxx
26941fc0d8245aa0a534ac2c63b329976a657f48
[ "Ruby" ]
permissive
IonicaBizauKitchen/cardfile_music_collection
a2cc4c96f8dc425fe1df763158e9d46a09ab61dc
c9caacbff4105d7f646c225b5fb87859eb761172
refs/heads/master
2021-01-18T14:48:44.824589
2008-12-15T22:50:21
2008-12-15T22:50:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
99,594
cxx
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.31 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #define SWIGRUBY #ifdef __cplusplus template<class T> class SwigValueWrapper { T *tt; public: SwigValueWrapper() : tt(0) { } SwigValueWrapper(const SwigValueWrapper<T>& rhs) : tt(new T(*rhs.tt)) { } SwigValueWrapper(const T& t) : tt(new T(t)) { } ~SwigValueWrapper() { delete tt; } SwigValueWrapper& operator=(const T& t) { delete tt; tt = new T(t); return *this; } operator T&() const { return *tt; } T *operator&() { return tt; } private: SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs); }; #endif /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) # if (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) # if (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic CAPI SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "3" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the swig runtime code. In 99.9% of the cases, swig just needs to declare them as 'static'. But only do this if is strictly necessary, ie, if you have problems with your compiler or so. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The swig conversion methods, as ConvertPtr, return and integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old swig versions, you usually write code as: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit as: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } that seems to be the same, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that requires also to SWIG_ConvertPtr to return new result values, as int SWIG_ConvertPtr(obj, ptr,...) { if (<obj is ok>) { if (<need new object>) { *ptr = <ptr to new allocated object>; return SWIG_NEWOBJ; } else { *ptr = <ptr to old object>; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the swig errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include <string.h> #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *); typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store inforomation on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ void *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class<int>" == "Class<int >", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (l1 - f1) - (l2 - f2); } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCompare(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* think of this as a c++ template<> or a scheme macro */ #define SWIG_TypeCheck_Template(comparison, ty) \ if (ty) { \ swig_cast_info *iter = ty->cast; \ while (iter) { \ if (comparison) { \ if (iter == ty->cast) return iter; \ /* Move iter to the top of the linked list */ \ iter->prev->next = iter->next; \ if (iter->next) \ iter->next->prev = iter->prev; \ iter->next = ty->cast; \ iter->prev = 0; \ if (ty->cast) ty->cast->prev = iter; \ ty->cast = iter; \ return iter; \ } \ iter = iter->next; \ } \ } \ return 0 /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty); } /* Same as previous function, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) { SWIG_TypeCheck_Template(iter->type == from, into); } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { register size_t l = 0; register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { register size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* Errors in SWIG */ #define SWIG_UnknownError -1 #define SWIG_IOError -2 #define SWIG_RuntimeError -3 #define SWIG_IndexError -4 #define SWIG_TypeError -5 #define SWIG_DivisionByZero -6 #define SWIG_OverflowError -7 #define SWIG_SyntaxError -8 #define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 #define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 #include <ruby.h> /* Ruby 1.7 defines NUM2LL(), LL2NUM() and ULL2NUM() macros */ #ifndef NUM2LL #define NUM2LL(x) NUM2LONG((x)) #endif #ifndef LL2NUM #define LL2NUM(x) INT2NUM((long) (x)) #endif #ifndef ULL2NUM #define ULL2NUM(x) UINT2NUM((unsigned long) (x)) #endif /* Ruby 1.7 doesn't (yet) define NUM2ULL() */ #ifndef NUM2ULL #ifdef HAVE_LONG_LONG #define NUM2ULL(x) rb_num2ull((x)) #else #define NUM2ULL(x) NUM2ULONG(x) #endif #endif /* RSTRING_LEN, etc are new in Ruby 1.9, but ->ptr and ->len no longer work */ /* Define these for older versions so we can just write code the new way */ #ifndef RSTRING_LEN # define RSTRING_LEN(x) RSTRING(x)->len #endif #ifndef RSTRING_PTR # define RSTRING_PTR(x) RSTRING(x)->ptr #endif #ifndef RARRAY_LEN # define RARRAY_LEN(x) RARRAY(x)->len #endif #ifndef RARRAY_PTR # define RARRAY_PTR(x) RARRAY(x)->ptr #endif /* * Need to be very careful about how these macros are defined, especially * when compiling C++ code or C code with an ANSI C compiler. * * VALUEFUNC(f) is a macro used to typecast a C function that implements * a Ruby method so that it can be passed as an argument to API functions * like rb_define_method() and rb_define_singleton_method(). * * VOIDFUNC(f) is a macro used to typecast a C function that implements * either the "mark" or "free" stuff for a Ruby Data object, so that it * can be passed as an argument to API functions like Data_Wrap_Struct() * and Data_Make_Struct(). */ #ifdef __cplusplus # ifndef RUBY_METHOD_FUNC /* These definitions should work for Ruby 1.4.6 */ # define PROTECTFUNC(f) ((VALUE (*)()) f) # define VALUEFUNC(f) ((VALUE (*)()) f) # define VOIDFUNC(f) ((void (*)()) f) # else # ifndef ANYARGS /* These definitions should work for Ruby 1.6 */ # define PROTECTFUNC(f) ((VALUE (*)()) f) # define VALUEFUNC(f) ((VALUE (*)()) f) # define VOIDFUNC(f) ((RUBY_DATA_FUNC) f) # else /* These definitions should work for Ruby 1.7+ */ # define PROTECTFUNC(f) ((VALUE (*)(VALUE)) f) # define VALUEFUNC(f) ((VALUE (*)(ANYARGS)) f) # define VOIDFUNC(f) ((RUBY_DATA_FUNC) f) # endif # endif #else # define VALUEFUNC(f) (f) # define VOIDFUNC(f) (f) #endif /* Don't use for expressions have side effect */ #ifndef RB_STRING_VALUE #define RB_STRING_VALUE(s) (TYPE(s) == T_STRING ? (s) : (*(volatile VALUE *)&(s) = rb_str_to_str(s))) #endif #ifndef StringValue #define StringValue(s) RB_STRING_VALUE(s) #endif #ifndef StringValuePtr #define StringValuePtr(s) RSTRING_PTR(RB_STRING_VALUE(s)) #endif #ifndef StringValueLen #define StringValueLen(s) RSTRING_LEN(RB_STRING_VALUE(s)) #endif #ifndef SafeStringValue #define SafeStringValue(v) do {\ StringValue(v);\ rb_check_safe_str(v);\ } while (0) #endif #ifndef HAVE_RB_DEFINE_ALLOC_FUNC #define rb_define_alloc_func(klass, func) rb_define_singleton_method((klass), "new", VALUEFUNC((func)), -1) #define rb_undef_alloc_func(klass) rb_undef_method(CLASS_OF((klass)), "new") #endif /* ----------------------------------------------------------------------------- * error manipulation * ----------------------------------------------------------------------------- */ /* Define some additional error types */ #define SWIG_ObjectPreviouslyDeletedError -100 /* Define custom exceptions for errors that do not map to existing Ruby exceptions. Note this only works for C++ since a global cannot be initialized by a funtion in C. For C, fallback to rb_eRuntimeError.*/ SWIGINTERN VALUE getNullReferenceError(void) { static int init = 0; static VALUE rb_eNullReferenceError ; if (!init) { init = 1; rb_eNullReferenceError = rb_define_class("NullReferenceError", rb_eRuntimeError); } return rb_eNullReferenceError; } SWIGINTERN VALUE getObjectPreviouslyDeletedError(void) { static int init = 0; static VALUE rb_eObjectPreviouslyDeleted ; if (!init) { init = 1; rb_eObjectPreviouslyDeleted = rb_define_class("ObjectPreviouslyDeleted", rb_eRuntimeError); } return rb_eObjectPreviouslyDeleted; } SWIGINTERN VALUE SWIG_Ruby_ErrorType(int SWIG_code) { VALUE type; switch (SWIG_code) { case SWIG_MemoryError: type = rb_eNoMemError; break; case SWIG_IOError: type = rb_eIOError; break; case SWIG_RuntimeError: type = rb_eRuntimeError; break; case SWIG_IndexError: type = rb_eIndexError; break; case SWIG_TypeError: type = rb_eTypeError; break; case SWIG_DivisionByZero: type = rb_eZeroDivError; break; case SWIG_OverflowError: type = rb_eRangeError; break; case SWIG_SyntaxError: type = rb_eSyntaxError; break; case SWIG_ValueError: type = rb_eArgError; break; case SWIG_SystemError: type = rb_eFatal; break; case SWIG_AttributeError: type = rb_eRuntimeError; break; case SWIG_NullReferenceError: type = getNullReferenceError(); break; case SWIG_ObjectPreviouslyDeletedError: type = getObjectPreviouslyDeletedError(); break; case SWIG_UnknownError: type = rb_eRuntimeError; break; default: type = rb_eRuntimeError; } return type; } /* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * rubytracking.swg * * This file contains support for tracking mappings from * Ruby objects to C++ objects. This functionality is needed * to implement mark functions for Ruby's mark and sweep * garbage collector. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #endif /* Global Ruby hash table to store Trackings from C/C++ structs to Ruby Objects. */ static VALUE swig_ruby_trackings; /* Global variable that stores a reference to the ruby hash table delete function. */ static ID swig_ruby_hash_delete = 0; /* Setup a Ruby hash table to store Trackings */ SWIGRUNTIME void SWIG_RubyInitializeTrackings(void) { /* Create a ruby hash table to store Trackings from C++ objects to Ruby objects. Also make sure to tell the garabage collector about the hash table. */ swig_ruby_trackings = rb_hash_new(); rb_gc_register_address(&swig_ruby_trackings); /* Now store a reference to the hash table delete function so that we only have to look it up once.*/ swig_ruby_hash_delete = rb_intern("delete"); } /* Get a Ruby number to reference a pointer */ SWIGRUNTIME VALUE SWIG_RubyPtrToReference(void* ptr) { /* We cast the pointer to an unsigned long and then store a reference to it using a Ruby number object. */ /* Convert the pointer to a Ruby number */ unsigned long value = (unsigned long) ptr; return LONG2NUM(value); } /* Get a Ruby number to reference an object */ SWIGRUNTIME VALUE SWIG_RubyObjectToReference(VALUE object) { /* We cast the object to an unsigned long and then store a reference to it using a Ruby number object. */ /* Convert the Object to a Ruby number */ unsigned long value = (unsigned long) object; return LONG2NUM(value); } /* Get a Ruby object from a previously stored reference */ SWIGRUNTIME VALUE SWIG_RubyReferenceToObject(VALUE reference) { /* The provided Ruby number object is a reference to the Ruby object we want.*/ /* First convert the Ruby number to a C number */ unsigned long value = NUM2LONG(reference); return (VALUE) value; } /* Add a Tracking from a C/C++ struct to a Ruby object */ SWIGRUNTIME void SWIG_RubyAddTracking(void* ptr, VALUE object) { /* In a Ruby hash table we store the pointer and the associated Ruby object. The trick here is that we cannot store the Ruby object directly - if we do then it cannot be garbage collected. So instead we typecast it as a unsigned long and convert it to a Ruby number object.*/ /* Get a reference to the pointer as a Ruby number */ VALUE key = SWIG_RubyPtrToReference(ptr); /* Get a reference to the Ruby object as a Ruby number */ VALUE value = SWIG_RubyObjectToReference(object); /* Store the mapping to the global hash table. */ rb_hash_aset(swig_ruby_trackings, key, value); } /* Get the Ruby object that owns the specified C/C++ struct */ SWIGRUNTIME VALUE SWIG_RubyInstanceFor(void* ptr) { /* Get a reference to the pointer as a Ruby number */ VALUE key = SWIG_RubyPtrToReference(ptr); /* Now lookup the value stored in the global hash table */ VALUE value = rb_hash_aref(swig_ruby_trackings, key); if (value == Qnil) { /* No object exists - return nil. */ return Qnil; } else { /* Convert this value to Ruby object */ return SWIG_RubyReferenceToObject(value); } } /* Remove a Tracking from a C/C++ struct to a Ruby object. It is very important to remove objects once they are destroyed since the same memory address may be reused later to create a new object. */ SWIGRUNTIME void SWIG_RubyRemoveTracking(void* ptr) { /* Get a reference to the pointer as a Ruby number */ VALUE key = SWIG_RubyPtrToReference(ptr); /* Delete the object from the hash table by calling Ruby's do this we need to call the Hash.delete method.*/ rb_funcall(swig_ruby_trackings, swig_ruby_hash_delete, 1, key); } /* This is a helper method that unlinks a Ruby object from its underlying C++ object. This is needed if the lifetime of the Ruby object is longer than the C++ object */ SWIGRUNTIME void SWIG_RubyUnlinkObjects(void* ptr) { VALUE object = SWIG_RubyInstanceFor(ptr); if (object != Qnil) { DATA_PTR(object) = 0; } } #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Ruby API portion that goes into the runtime * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #endif SWIGINTERN VALUE SWIG_Ruby_AppendOutput(VALUE target, VALUE o) { if (NIL_P(target)) { target = o; } else { if (TYPE(target) != T_ARRAY) { VALUE o2 = target; target = rb_ary_new(); rb_ary_push(target, o2); } rb_ary_push(target, o); } return target; } #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * rubyrun.swg * * This file contains the runtime support for Ruby modules * and includes code for managing global variables and pointer * type checking. * ----------------------------------------------------------------------------- */ /* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 /* for raw pointers */ #define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Ruby_ConvertPtrAndOwn(obj, pptr, type, flags, 0) #define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Ruby_ConvertPtrAndOwn(obj, pptr, type, flags, own) #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Ruby_NewPointerObj(ptr, type, flags) #define SWIG_AcquirePtr(ptr, own) SWIG_Ruby_AcquirePtr(ptr, own) #define swig_owntype ruby_owntype /* for raw packed data */ #define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Ruby_ConvertPacked(obj, ptr, sz, ty, flags) #define SWIG_NewPackedObj(ptr, sz, type) SWIG_Ruby_NewPackedObj(ptr, sz, type) /* for class or struct pointers */ #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) #define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) /* for C or C++ function pointers */ #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_ConvertPtr(obj, pptr, type, 0) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_NewPointerObj(ptr, type, 0) /* for C++ member pointers, ie, member methods */ #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Ruby_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIG_Ruby_NewPackedObj(ptr, sz, type) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_Ruby_GetModule() #define SWIG_SetModule(clientdata, pointer) SWIG_Ruby_SetModule(pointer) /* Error manipulation */ #define SWIG_ErrorType(code) SWIG_Ruby_ErrorType(code) #define SWIG_Error(code, msg) rb_raise(SWIG_Ruby_ErrorType(code), msg) #define SWIG_fail goto fail /* Ruby-specific SWIG API */ #define SWIG_InitRuntime() SWIG_Ruby_InitRuntime() #define SWIG_define_class(ty) SWIG_Ruby_define_class(ty) #define SWIG_NewClassInstance(value, ty) SWIG_Ruby_NewClassInstance(value, ty) #define SWIG_MangleStr(value) SWIG_Ruby_MangleStr(value) #define SWIG_CheckConvert(value, ty) SWIG_Ruby_CheckConvert(value, ty) /* ----------------------------------------------------------------------------- * pointers/data manipulation * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* cc-mode */ #endif #endif typedef struct { VALUE klass; VALUE mImpl; void (*mark)(void *); void (*destroy)(void *); int trackObjects; } swig_class; static VALUE _mSWIG = Qnil; static VALUE _cSWIG_Pointer = Qnil; static VALUE swig_runtime_data_type_pointer = Qnil; SWIGRUNTIME VALUE getExceptionClass(void) { static int init = 0; static VALUE rubyExceptionClass ; if (!init) { init = 1; rubyExceptionClass = rb_const_get(_mSWIG, rb_intern("Exception")); } return rubyExceptionClass; } /* This code checks to see if the Ruby object being raised as part of an exception inherits from the Ruby class Exception. If so, the object is simply returned. If not, then a new Ruby exception object is created and that will be returned to Ruby.*/ SWIGRUNTIME VALUE SWIG_Ruby_ExceptionType(swig_type_info *desc, VALUE obj) { VALUE exceptionClass = getExceptionClass(); if (rb_obj_is_kind_of(obj, exceptionClass)) { return obj; } else { return rb_exc_new3(rb_eRuntimeError, rb_obj_as_string(obj)); } } /* Initialize Ruby runtime support */ SWIGRUNTIME void SWIG_Ruby_InitRuntime(void) { if (_mSWIG == Qnil) { _mSWIG = rb_define_module("SWIG"); } } /* Define Ruby class for C type */ SWIGRUNTIME void SWIG_Ruby_define_class(swig_type_info *type) { VALUE klass; char *klass_name = (char *) malloc(4 + strlen(type->name) + 1); sprintf(klass_name, "TYPE%s", type->name); if (NIL_P(_cSWIG_Pointer)) { _cSWIG_Pointer = rb_define_class_under(_mSWIG, "Pointer", rb_cObject); rb_undef_method(CLASS_OF(_cSWIG_Pointer), "new"); } klass = rb_define_class_under(_mSWIG, klass_name, _cSWIG_Pointer); free((void *) klass_name); } /* Create a new pointer object */ SWIGRUNTIME VALUE SWIG_Ruby_NewPointerObj(void *ptr, swig_type_info *type, int flags) { int own = flags & SWIG_POINTER_OWN; char *klass_name; swig_class *sklass; VALUE klass; VALUE obj; if (!ptr) return Qnil; if (type->clientdata) { sklass = (swig_class *) type->clientdata; /* Are we tracking this class and have we already returned this Ruby object? */ if (sklass->trackObjects) { obj = SWIG_RubyInstanceFor(ptr); /* Check the object's type and make sure it has the correct type. It might not in cases where methods do things like downcast methods. */ if (obj != Qnil) { VALUE value = rb_iv_get(obj, "__swigtype__"); char* type_name = RSTRING_PTR(value); if (strcmp(type->name, type_name) == 0) { return obj; } } } /* Create a new Ruby object */ obj = Data_Wrap_Struct(sklass->klass, VOIDFUNC(sklass->mark), (own ? VOIDFUNC(sklass->destroy) : 0), ptr); /* If tracking is on for this class then track this object. */ if (sklass->trackObjects) { SWIG_RubyAddTracking(ptr, obj); } } else { klass_name = (char *) malloc(4 + strlen(type->name) + 1); sprintf(klass_name, "TYPE%s", type->name); klass = rb_const_get(_mSWIG, rb_intern(klass_name)); free((void *) klass_name); obj = Data_Wrap_Struct(klass, 0, 0, ptr); } rb_iv_set(obj, "__swigtype__", rb_str_new2(type->name)); return obj; } /* Create a new class instance (always owned) */ SWIGRUNTIME VALUE SWIG_Ruby_NewClassInstance(VALUE klass, swig_type_info *type) { VALUE obj; swig_class *sklass = (swig_class *) type->clientdata; obj = Data_Wrap_Struct(klass, VOIDFUNC(sklass->mark), VOIDFUNC(sklass->destroy), 0); rb_iv_set(obj, "__swigtype__", rb_str_new2(type->name)); return obj; } /* Get type mangle from class name */ SWIGRUNTIMEINLINE char * SWIG_Ruby_MangleStr(VALUE obj) { VALUE stype = rb_iv_get(obj, "__swigtype__"); return StringValuePtr(stype); } /* Acquire a pointer value */ typedef void (*ruby_owntype)(void*); SWIGRUNTIME ruby_owntype SWIG_Ruby_AcquirePtr(VALUE obj, ruby_owntype own) { if (obj) { ruby_owntype oldown = RDATA(obj)->dfree; RDATA(obj)->dfree = own; return oldown; } else { return 0; } } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Ruby_ConvertPtrAndOwn(VALUE obj, void **ptr, swig_type_info *ty, int flags, ruby_owntype *own) { char *c; swig_cast_info *tc; void *vptr = 0; /* Grab the pointer */ if (NIL_P(obj)) { *ptr = 0; return SWIG_OK; } else { if (TYPE(obj) != T_DATA) { return SWIG_ERROR; } Data_Get_Struct(obj, void, vptr); } if (own) *own = RDATA(obj)->dfree; /* Check to see if the input object is giving up ownership of the underlying C struct or C++ object. If so then we need to reset the destructor since the Ruby object no longer owns the underlying C++ object.*/ if (flags & SWIG_POINTER_DISOWN) { /* Is tracking on for this class? */ int track = 0; if (ty && ty->clientdata) { swig_class *sklass = (swig_class *) ty->clientdata; track = sklass->trackObjects; } if (track) { /* We are tracking objects for this class. Thus we change the destructor * to SWIG_RubyRemoveTracking. This allows us to * remove the mapping from the C++ to Ruby object * when the Ruby object is garbage collected. If we don't * do this, then it is possible we will return a reference * to a Ruby object that no longer exists thereby crashing Ruby. */ RDATA(obj)->dfree = SWIG_RubyRemoveTracking; } else { RDATA(obj)->dfree = 0; } } /* Do type-checking if type info was provided */ if (ty) { if (ty->clientdata) { if (rb_obj_is_kind_of(obj, ((swig_class *) (ty->clientdata))->klass)) { if (vptr == 0) { /* The object has already been deleted */ return SWIG_ObjectPreviouslyDeletedError; } *ptr = vptr; return SWIG_OK; } } if ((c = SWIG_MangleStr(obj)) == NULL) { return SWIG_ERROR; } tc = SWIG_TypeCheck(c, ty); if (!tc) { return SWIG_ERROR; } *ptr = SWIG_TypeCast(tc, vptr); } else { *ptr = vptr; } return SWIG_OK; } /* Check convert */ SWIGRUNTIMEINLINE int SWIG_Ruby_CheckConvert(VALUE obj, swig_type_info *ty) { char *c = SWIG_MangleStr(obj); if (!c) return 0; return SWIG_TypeCheck(c,ty) != 0; } SWIGRUNTIME VALUE SWIG_Ruby_NewPackedObj(void *ptr, int sz, swig_type_info *type) { char result[1024]; char *r = result; if ((2*sz + 1 + strlen(type->name)) > 1000) return 0; *(r++) = '_'; r = SWIG_PackData(r, ptr, sz); strcpy(r, type->name); return rb_str_new2(result); } /* Convert a packed value value */ SWIGRUNTIME int SWIG_Ruby_ConvertPacked(VALUE obj, void *ptr, int sz, swig_type_info *ty) { swig_cast_info *tc; const char *c; if (TYPE(obj) != T_STRING) goto type_error; c = StringValuePtr(obj); /* Pointer values must start with leading underscore */ if (*c != '_') goto type_error; c++; c = SWIG_UnpackData(c, ptr, sz); if (ty) { tc = SWIG_TypeCheck(c, ty); if (!tc) goto type_error; } return SWIG_OK; type_error: return SWIG_ERROR; } SWIGRUNTIME swig_module_info * SWIG_Ruby_GetModule(void) { VALUE pointer; swig_module_info *ret = 0; VALUE verbose = rb_gv_get("VERBOSE"); /* temporarily disable warnings, since the pointer check causes warnings with 'ruby -w' */ rb_gv_set("VERBOSE", Qfalse); /* first check if pointer already created */ pointer = rb_gv_get("$swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); if (pointer != Qnil) { Data_Get_Struct(pointer, swig_module_info, ret); } /* reinstate warnings */ rb_gv_set("VERBOSE", verbose); return ret; } SWIGRUNTIME void SWIG_Ruby_SetModule(swig_module_info *pointer) { /* register a new class */ VALUE cl = rb_define_class("swig_runtime_data", rb_cObject); /* create and store the structure pointer to a global variable */ swig_runtime_data_type_pointer = Data_Wrap_Struct(cl, 0, 0, pointer); rb_define_readonly_variable("$swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, &swig_runtime_data_type_pointer); } #ifdef __cplusplus #if 0 { /* cc-mode */ #endif } #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_ID3_Field swig_types[0] #define SWIGTYPE_p_ID3_Frame swig_types[1] #define SWIGTYPE_p_ID3_Tag swig_types[2] #define SWIGTYPE_p_ID3_Tag__Iterator swig_types[3] #define SWIGTYPE_p_char swig_types[4] #define SWIGTYPE_p_unsigned_int swig_types[5] static swig_type_info *swig_types[7]; static swig_module_info swig_module = {swig_types, 6, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #define SWIG_init Init_id3lib_api #define SWIG_name "ID3Lib::API" static VALUE mAPI; #define SWIGVERSION 0x010331 #define SWIG_VERSION SWIGVERSION #define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) #include <stdexcept> #include <id3/tag.h> SWIGINTERN swig_type_info* SWIG_pchar_descriptor(void) { static int init = 0; static swig_type_info* info = 0; if (!init) { info = SWIG_TypeQuery("_p_char"); init = 1; } return info; } SWIGINTERN int SWIG_AsCharPtrAndSize(VALUE obj, char** cptr, size_t* psize, int *alloc) { if (TYPE(obj) == T_STRING) { char *cstr = STR2CSTR(obj); size_t size = RSTRING_LEN(obj) + 1; if (cptr) { if (alloc) { if (*alloc == SWIG_NEWOBJ) { *cptr = reinterpret_cast< char* >(memcpy((new char[size]), cstr, sizeof(char)*(size))); } else { *cptr = cstr; *alloc = SWIG_OLDOBJ; } } } if (psize) *psize = size; return SWIG_OK; } else { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); if (pchar_descriptor) { void* vptr = 0; if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { if (cptr) *cptr = (char *)vptr; if (psize) *psize = vptr ? (strlen((char*)vptr) + 1) : 0; if (alloc) *alloc = SWIG_OLDOBJ; return SWIG_OK; } } } return SWIG_TypeError; } #include <limits.h> #ifndef LLONG_MIN # define LLONG_MIN LONG_LONG_MIN #endif #ifndef LLONG_MAX # define LLONG_MAX LONG_LONG_MAX #endif #ifndef ULLONG_MAX # define ULLONG_MAX ULONG_LONG_MAX #endif SWIGINTERN VALUE SWIG_ruby_failed(void) { return Qnil; } /*@SWIG:%ruby_aux_method@*/ SWIGINTERN VALUE SWIG_AUX_NUM2LONG(VALUE *args) { VALUE obj = args[0]; VALUE type = TYPE(obj); long *res = (long *)(args[1]); *res = type == T_FIXNUM ? NUM2LONG(obj) : rb_big2long(obj); return obj; } /*@SWIG@*/ SWIGINTERN int SWIG_AsVal_long (VALUE obj, long* val) { VALUE type = TYPE(obj); if ((type == T_FIXNUM) || (type == T_BIGNUM)) { long v; VALUE a[2]; a[0] = obj; a[1] = (VALUE)(&v); if (rb_rescue(RUBY_METHOD_FUNC(SWIG_AUX_NUM2LONG), (VALUE)a, RUBY_METHOD_FUNC(SWIG_ruby_failed), 0) != Qnil) { if (val) *val = v; return SWIG_OK; } } return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_int (VALUE obj, int *val) { long v; int res = SWIG_AsVal_long (obj, &v); if (SWIG_IsOK(res)) { if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = static_cast< int >(v); } } return res; } SWIGINTERNINLINE VALUE SWIG_From_bool (bool value) { return value ? Qtrue : Qfalse; } /*@SWIG:%ruby_aux_method@*/ SWIGINTERN VALUE SWIG_AUX_NUM2ULONG(VALUE *args) { VALUE obj = args[0]; VALUE type = TYPE(obj); unsigned long *res = (unsigned long *)(args[1]); *res = type == T_FIXNUM ? NUM2ULONG(obj) : rb_big2ulong(obj); return obj; } /*@SWIG@*/ SWIGINTERN int SWIG_AsVal_unsigned_SS_long (VALUE obj, unsigned long *val) { VALUE type = TYPE(obj); if ((type == T_FIXNUM) || (type == T_BIGNUM)) { unsigned long v; VALUE a[2]; a[0] = obj; a[1] = (VALUE)(&v); if (rb_rescue(RUBY_METHOD_FUNC(SWIG_AUX_NUM2ULONG), (VALUE)a, RUBY_METHOD_FUNC(SWIG_ruby_failed), 0) != Qnil) { if (val) *val = v; return SWIG_OK; } } return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_unsigned_SS_int (VALUE obj, unsigned int *val) { unsigned long v; int res = SWIG_AsVal_unsigned_SS_long (obj, &v); if (SWIG_IsOK(res)) { if ((v > UINT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = static_cast< unsigned int >(v); } } return res; } #define SWIG_From_long LONG2NUM SWIGINTERNINLINE VALUE SWIG_From_unsigned_SS_long (unsigned long value) { return ULONG2NUM(value); } SWIGINTERNINLINE VALUE SWIG_From_size_t (size_t value) { return SWIG_From_unsigned_SS_long (static_cast< unsigned long >(value)); } SWIGINTERNINLINE VALUE SWIG_From_unsigned_SS_int (unsigned int value) { return SWIG_From_unsigned_SS_long (value); } SWIGINTERNINLINE VALUE SWIG_FromCharPtrAndSize(const char* carray, size_t size) { if (carray) { if (size > LONG_MAX) { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); return pchar_descriptor ? SWIG_NewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : Qnil; } else { return rb_str_new(carray, static_cast< long >(size)); } } else { return Qnil; } } SWIGINTERNINLINE VALUE SWIG_FromCharPtr(const char *cptr) { return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); } SWIGINTERN int SWIG_AsVal_bool (VALUE obj, bool *val) { if (obj == Qtrue) { if (val) *val = true; return SWIG_OK; } else if (obj == Qfalse) { if (val) *val = false; return SWIG_OK; } else { int res = 0; if (SWIG_AsVal_int (obj, &res) == SWIG_OK) { if (val) *val = res ? true : false; return SWIG_OK; } } return SWIG_TypeError; } SWIGINTERNINLINE VALUE SWIG_From_int (int value) { return SWIG_From_long (value); } SWIGINTERN VALUE ID3_Field_get_binary(ID3_Field *self){ return rb_str_new((const char *)self->GetRawBinary(), self->Size()); } SWIGINTERN VALUE ID3_Field_get_unicode(ID3_Field *self){ const char *str = (const char *)self->GetRawUnicodeText(); if (str == NULL) return rb_str_new("", 0); long size = self->Size(); if (size >= 2 && str[size-2] == '\0' && str[size-1] == '\0') { // id3lib seems to be inconsistent: the Unicode strings // don't always end in 0x0000. If they do, we don't want these // trailing bytes. size -= 2; } return rb_str_new(str, size); } SWIGINTERN size_t ID3_Field_set_binary(ID3_Field *self,VALUE data){ StringValue(data); return self->Set((const unsigned char *)RSTRING(data)->ptr, RSTRING(data)->len); } SWIGINTERN size_t ID3_Field_set_unicode(ID3_Field *self,VALUE data){ StringValue(data); long len; unicode_t *unicode; len = RSTRING(data)->len / sizeof(unicode_t); unicode = (unicode_t *)malloc(sizeof(unicode_t) * (len+1)); if (unicode == NULL) { rb_raise(rb_eNoMemError, "Couldn't allocate memory for Unicode data."); } memcpy(unicode, RSTRING(data)->ptr, sizeof(unicode_t) * len); // Unicode strings need 0x0000 at the end. unicode[len] = 0; size_t retval = self->Set(unicode); // Free Unicode! ;) free(unicode); return retval; } swig_class cTag; SWIGINTERN VALUE _wrap_new_Tag__SWIG_0(int argc, VALUE *argv, VALUE self) { char *arg1 = (char *) 0 ; ID3_Tag *result = 0 ; int res1 ; char *buf1 = 0 ; int alloc1 = 0 ; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_AsCharPtrAndSize(argv[0], &buf1, NULL, &alloc1); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ID3_Tag" "', argument " "1"" of type '" "char const *""'"); } arg1 = reinterpret_cast< char * >(buf1); result = (ID3_Tag *)new ID3_Tag((char const *)arg1);DATA_PTR(self) = result; if (alloc1 == SWIG_NEWOBJ) delete[] buf1; return self; fail: if (alloc1 == SWIG_NEWOBJ) delete[] buf1; return Qnil; } #ifdef HAVE_RB_DEFINE_ALLOC_FUNC SWIGINTERN VALUE _wrap_Tag_allocate(VALUE self) { #else SWIGINTERN VALUE _wrap_Tag_allocate(int argc, VALUE *argv, VALUE self) { #endif VALUE vresult = SWIG_NewClassInstance(self, SWIGTYPE_p_ID3_Tag); #ifndef HAVE_RB_DEFINE_ALLOC_FUNC rb_obj_call_init(vresult, argc, argv); #endif return vresult; } SWIGINTERN VALUE _wrap_new_Tag__SWIG_1(int argc, VALUE *argv, VALUE self) { ID3_Tag *result = 0 ; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } result = (ID3_Tag *)new ID3_Tag();DATA_PTR(self) = result; return self; fail: return Qnil; } SWIGINTERN VALUE _wrap_new_Tag(int nargs, VALUE *args, VALUE self) { int argc; VALUE argv[1]; int ii; argc = nargs; if (argc > 1) SWIG_fail; for (ii = 0; (ii < argc); ii++) { argv[ii] = args[ii]; } if (argc == 0) { return _wrap_new_Tag__SWIG_1(nargs, args, self); } if (argc == 1) { int _v; int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); _v = SWIG_CheckState(res); if (_v) { return _wrap_new_Tag__SWIG_0(nargs, args, self); } } fail: rb_raise(rb_eArgError, "No matching function for overloaded 'new_Tag'"); return Qnil; } SWIGINTERN void free_ID3_Tag(ID3_Tag *arg1) { delete arg1; } SWIGINTERN VALUE _wrap_Tag_has_tag_type(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; ID3_TagType arg2 ; bool result; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "HasTagType" "', argument " "1"" of type '" "ID3_Tag const *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); ecode2 = SWIG_AsVal_int(argv[0], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "HasTagType" "', argument " "2"" of type '" "ID3_TagType""'"); } arg2 = static_cast< ID3_TagType >(val2); result = (bool)((ID3_Tag const *)arg1)->HasTagType(arg2); vresult = SWIG_From_bool(static_cast< bool >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_link__SWIG_0(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; char *arg2 = (char *) 0 ; flags_t arg3 ; size_t result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; unsigned int val3 ; int ecode3 = 0 ; VALUE vresult = Qnil; if ((argc < 2) || (argc > 2)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 2)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Link" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); res2 = SWIG_AsCharPtrAndSize(argv[0], &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Link" "', argument " "2"" of type '" "char const *""'"); } arg2 = reinterpret_cast< char * >(buf2); ecode3 = SWIG_AsVal_unsigned_SS_int(argv[1], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Link" "', argument " "3"" of type '" "flags_t""'"); } arg3 = static_cast< flags_t >(val3); result = (arg1)->Link((char const *)arg2,arg3); vresult = SWIG_From_size_t(static_cast< size_t >(result)); if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return vresult; fail: if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return Qnil; } SWIGINTERN VALUE _wrap_Tag_link__SWIG_1(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; char *arg2 = (char *) 0 ; size_t result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Link" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); res2 = SWIG_AsCharPtrAndSize(argv[0], &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Link" "', argument " "2"" of type '" "char const *""'"); } arg2 = reinterpret_cast< char * >(buf2); result = (arg1)->Link((char const *)arg2); vresult = SWIG_From_size_t(static_cast< size_t >(result)); if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return vresult; fail: if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return Qnil; } SWIGINTERN VALUE _wrap_Tag_link(int nargs, VALUE *args, VALUE self) { int argc; VALUE argv[4]; int ii; argc = nargs + 1; argv[0] = self; if (argc > 4) SWIG_fail; for (ii = 1; (ii < argc); ii++) { argv[ii] = args[ii-1]; } if (argc == 2) { int _v; void *vptr = 0; int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_ID3_Tag, 0); _v = SWIG_CheckState(res); if (_v) { int res = SWIG_AsCharPtrAndSize(argv[1], 0, NULL, 0); _v = SWIG_CheckState(res); if (_v) { return _wrap_Tag_link__SWIG_1(nargs, args, self); } } } if (argc == 3) { int _v; void *vptr = 0; int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_ID3_Tag, 0); _v = SWIG_CheckState(res); if (_v) { int res = SWIG_AsCharPtrAndSize(argv[1], 0, NULL, 0); _v = SWIG_CheckState(res); if (_v) { { int res = SWIG_AsVal_unsigned_SS_int(argv[2], NULL); _v = SWIG_CheckState(res); } if (_v) { return _wrap_Tag_link__SWIG_0(nargs, args, self); } } } } fail: rb_raise(rb_eArgError, "No matching function for overloaded 'Tag_link'"); return Qnil; } SWIGINTERN VALUE _wrap_Tag_update__SWIG_0(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; flags_t arg2 ; flags_t result; void *argp1 = 0 ; int res1 = 0 ; unsigned int val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Update" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); ecode2 = SWIG_AsVal_unsigned_SS_int(argv[0], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Update" "', argument " "2"" of type '" "flags_t""'"); } arg2 = static_cast< flags_t >(val2); result = (flags_t)(arg1)->Update(arg2); vresult = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_update__SWIG_1(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; flags_t result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Update" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); result = (flags_t)(arg1)->Update(); vresult = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_update(int nargs, VALUE *args, VALUE self) { int argc; VALUE argv[3]; int ii; argc = nargs + 1; argv[0] = self; if (argc > 3) SWIG_fail; for (ii = 1; (ii < argc); ii++) { argv[ii] = args[ii-1]; } if (argc == 1) { int _v; void *vptr = 0; int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_ID3_Tag, 0); _v = SWIG_CheckState(res); if (_v) { return _wrap_Tag_update__SWIG_1(nargs, args, self); } } if (argc == 2) { int _v; void *vptr = 0; int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_ID3_Tag, 0); _v = SWIG_CheckState(res); if (_v) { { int res = SWIG_AsVal_unsigned_SS_int(argv[1], NULL); _v = SWIG_CheckState(res); } if (_v) { return _wrap_Tag_update__SWIG_0(nargs, args, self); } } } fail: rb_raise(rb_eArgError, "No matching function for overloaded 'Tag_update'"); return Qnil; } SWIGINTERN VALUE _wrap_Tag_strip__SWIG_0(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; flags_t arg2 ; flags_t result; void *argp1 = 0 ; int res1 = 0 ; unsigned int val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Strip" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); ecode2 = SWIG_AsVal_unsigned_SS_int(argv[0], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Strip" "', argument " "2"" of type '" "flags_t""'"); } arg2 = static_cast< flags_t >(val2); result = (flags_t)(arg1)->Strip(arg2); vresult = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_strip__SWIG_1(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; flags_t result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Strip" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); result = (flags_t)(arg1)->Strip(); vresult = SWIG_From_unsigned_SS_int(static_cast< unsigned int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_strip(int nargs, VALUE *args, VALUE self) { int argc; VALUE argv[3]; int ii; argc = nargs + 1; argv[0] = self; if (argc > 3) SWIG_fail; for (ii = 1; (ii < argc); ii++) { argv[ii] = args[ii-1]; } if (argc == 1) { int _v; void *vptr = 0; int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_ID3_Tag, 0); _v = SWIG_CheckState(res); if (_v) { return _wrap_Tag_strip__SWIG_1(nargs, args, self); } } if (argc == 2) { int _v; void *vptr = 0; int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_ID3_Tag, 0); _v = SWIG_CheckState(res); if (_v) { { int res = SWIG_AsVal_unsigned_SS_int(argv[1], NULL); _v = SWIG_CheckState(res); } if (_v) { return _wrap_Tag_strip__SWIG_0(nargs, args, self); } } } fail: rb_raise(rb_eArgError, "No matching function for overloaded 'Tag_strip'"); return Qnil; } SWIGINTERN VALUE _wrap_Tag_clear(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; void *argp1 = 0 ; int res1 = 0 ; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Clear" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); (arg1)->Clear(); return Qnil; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_remove_frame(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; ID3_Frame *arg2 = (ID3_Frame *) 0 ; ID3_Frame *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "RemoveFrame" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); res2 = SWIG_ConvertPtr(argv[0], &argp2,SWIGTYPE_p_ID3_Frame, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "RemoveFrame" "', argument " "2"" of type '" "ID3_Frame const *""'"); } arg2 = reinterpret_cast< ID3_Frame * >(argp2); result = (ID3_Frame *)(arg1)->RemoveFrame((ID3_Frame const *)arg2); vresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ID3_Frame, 0 | 0 ); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_add_frame(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; ID3_Frame *arg2 = (ID3_Frame *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "AddFrame" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); res2 = SWIG_ConvertPtr(argv[0], &argp2,SWIGTYPE_p_ID3_Frame, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "AddFrame" "', argument " "2"" of type '" "ID3_Frame const *""'"); } arg2 = reinterpret_cast< ID3_Frame * >(argp2); (arg1)->AddFrame((ID3_Frame const *)arg2); return Qnil; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_get_filename(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetFileName" "', argument " "1"" of type '" "ID3_Tag const *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); result = (char *)((ID3_Tag const *)arg1)->GetFileName(); vresult = SWIG_FromCharPtr((const char *)result); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_set_padding(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; bool arg2 ; bool result; void *argp1 = 0 ; int res1 = 0 ; bool val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SetPadding" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); ecode2 = SWIG_AsVal_bool(argv[0], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SetPadding" "', argument " "2"" of type '" "bool""'"); } arg2 = static_cast< bool >(val2); result = (bool)(arg1)->SetPadding(arg2); vresult = SWIG_From_bool(static_cast< bool >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_size(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; size_t result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Size" "', argument " "1"" of type '" "ID3_Tag const *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); result = ((ID3_Tag const *)arg1)->Size(); vresult = SWIG_From_size_t(static_cast< size_t >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_find(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; ID3_FrameID arg2 ; ID3_Frame *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Find" "', argument " "1"" of type '" "ID3_Tag const *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); ecode2 = SWIG_AsVal_int(argv[0], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Find" "', argument " "2"" of type '" "ID3_FrameID""'"); } arg2 = static_cast< ID3_FrameID >(val2); result = (ID3_Frame *)((ID3_Tag const *)arg1)->Find(arg2); vresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ID3_Frame, 0 | 0 ); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Tag_create_iterator(int argc, VALUE *argv, VALUE self) { ID3_Tag *arg1 = (ID3_Tag *) 0 ; ID3_Tag::Iterator *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "CreateIterator" "', argument " "1"" of type '" "ID3_Tag *""'"); } arg1 = reinterpret_cast< ID3_Tag * >(argp1); result = (ID3_Tag::Iterator *)(arg1)->CreateIterator(); vresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ID3_Tag__Iterator, SWIG_POINTER_OWN | 0 ); return vresult; fail: return Qnil; } swig_class cTag_Iterator; SWIGINTERN VALUE _wrap_Tag_Iterator_get_next(int argc, VALUE *argv, VALUE self) { ID3_Tag::Iterator *arg1 = (ID3_Tag::Iterator *) 0 ; ID3_Frame *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Tag__Iterator, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetNext" "', argument " "1"" of type '" "ID3_Tag::Iterator *""'"); } arg1 = reinterpret_cast< ID3_Tag::Iterator * >(argp1); result = (ID3_Frame *)(arg1)->GetNext(); vresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ID3_Frame, 0 | 0 ); return vresult; fail: return Qnil; } SWIGINTERN void free_ID3_Tag_Iterator(ID3_Tag::Iterator *arg1) { delete arg1; } swig_class cFrame; SWIGINTERN VALUE _wrap_new_Frame__SWIG_0(int argc, VALUE *argv, VALUE self) { ID3_FrameID arg1 ; ID3_Frame *result = 0 ; int val1 ; int ecode1 = 0 ; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } ecode1 = SWIG_AsVal_int(argv[0], &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "ID3_Frame" "', argument " "1"" of type '" "ID3_FrameID""'"); } arg1 = static_cast< ID3_FrameID >(val1); result = (ID3_Frame *)new ID3_Frame(arg1);DATA_PTR(self) = result; return self; fail: return Qnil; } #ifdef HAVE_RB_DEFINE_ALLOC_FUNC SWIGINTERN VALUE _wrap_Frame_allocate(VALUE self) { #else SWIGINTERN VALUE _wrap_Frame_allocate(int argc, VALUE *argv, VALUE self) { #endif VALUE vresult = SWIG_NewClassInstance(self, SWIGTYPE_p_ID3_Frame); #ifndef HAVE_RB_DEFINE_ALLOC_FUNC rb_obj_call_init(vresult, argc, argv); #endif return vresult; } SWIGINTERN VALUE _wrap_new_Frame__SWIG_1(int argc, VALUE *argv, VALUE self) { ID3_Frame *result = 0 ; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } result = (ID3_Frame *)new ID3_Frame();DATA_PTR(self) = result; return self; fail: return Qnil; } SWIGINTERN VALUE _wrap_new_Frame(int nargs, VALUE *args, VALUE self) { int argc; VALUE argv[1]; int ii; argc = nargs; if (argc > 1) SWIG_fail; for (ii = 0; (ii < argc); ii++) { argv[ii] = args[ii]; } if (argc == 0) { return _wrap_new_Frame__SWIG_1(nargs, args, self); } if (argc == 1) { int _v; { int res = SWIG_AsVal_int(argv[0], NULL); _v = SWIG_CheckState(res); } if (_v) { return _wrap_new_Frame__SWIG_0(nargs, args, self); } } fail: rb_raise(rb_eArgError, "No matching function for overloaded 'new_Frame'"); return Qnil; } SWIGINTERN void free_ID3_Frame(ID3_Frame *arg1) { delete arg1; } SWIGINTERN VALUE _wrap_Frame_get_field(int argc, VALUE *argv, VALUE self) { ID3_Frame *arg1 = (ID3_Frame *) 0 ; ID3_FieldID arg2 ; ID3_Field *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Frame, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetField" "', argument " "1"" of type '" "ID3_Frame const *""'"); } arg1 = reinterpret_cast< ID3_Frame * >(argp1); ecode2 = SWIG_AsVal_int(argv[0], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "GetField" "', argument " "2"" of type '" "ID3_FieldID""'"); } arg2 = static_cast< ID3_FieldID >(val2); result = (ID3_Field *)((ID3_Frame const *)arg1)->GetField(arg2); vresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ID3_Field, 0 | 0 ); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Frame_get_id(int argc, VALUE *argv, VALUE self) { ID3_Frame *arg1 = (ID3_Frame *) 0 ; ID3_FrameID result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Frame, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetID" "', argument " "1"" of type '" "ID3_Frame const *""'"); } arg1 = reinterpret_cast< ID3_Frame * >(argp1); result = (ID3_FrameID)((ID3_Frame const *)arg1)->GetID(); vresult = SWIG_From_int(static_cast< int >(result)); return vresult; fail: return Qnil; } swig_class cField; SWIGINTERN VALUE _wrap_Field_get_type(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; ID3_FieldType result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetType" "', argument " "1"" of type '" "ID3_Field const *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); result = (ID3_FieldType)((ID3_Field const *)arg1)->GetType(); vresult = SWIG_From_int(static_cast< int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Field_get_encoding(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; ID3_TextEnc result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetEncoding" "', argument " "1"" of type '" "ID3_Field const *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); result = (ID3_TextEnc)((ID3_Field const *)arg1)->GetEncoding(); vresult = SWIG_From_int(static_cast< int >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Field_get_integer(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; unsigned long result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Get" "', argument " "1"" of type '" "ID3_Field const *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); result = (unsigned long)((ID3_Field const *)arg1)->Get(); vresult = SWIG_From_unsigned_SS_long(static_cast< unsigned long >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Field_get_ascii(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; char *result = 0 ; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "GetRawText" "', argument " "1"" of type '" "ID3_Field const *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); result = (char *)((ID3_Field const *)arg1)->GetRawText(); vresult = SWIG_FromCharPtr((const char *)result); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Field_get_binary(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; VALUE result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_binary" "', argument " "1"" of type '" "ID3_Field *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); result = (VALUE)ID3_Field_get_binary(arg1); vresult = result; return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Field_get_unicode(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; VALUE result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 0) || (argc > 0)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 0)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "get_unicode" "', argument " "1"" of type '" "ID3_Field *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); result = (VALUE)ID3_Field_get_unicode(arg1); vresult = result; return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Field_set_encoding(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; ID3_TextEnc arg2 ; bool result; void *argp1 = 0 ; int res1 = 0 ; int val2 ; int ecode2 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "SetEncoding" "', argument " "1"" of type '" "ID3_Field *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); ecode2 = SWIG_AsVal_int(argv[0], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "SetEncoding" "', argument " "2"" of type '" "ID3_TextEnc""'"); } arg2 = static_cast< ID3_TextEnc >(val2); result = (bool)(arg1)->SetEncoding(arg2); vresult = SWIG_From_bool(static_cast< bool >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Field_set_integer(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; unsigned long arg2 ; void *argp1 = 0 ; int res1 = 0 ; unsigned long val2 ; int ecode2 = 0 ; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Set" "', argument " "1"" of type '" "ID3_Field *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); ecode2 = SWIG_AsVal_unsigned_SS_long(argv[0], &val2); if (!SWIG_IsOK(ecode2)) { SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Set" "', argument " "2"" of type '" "unsigned long""'"); } arg2 = static_cast< unsigned long >(val2); (arg1)->Set(arg2); return Qnil; fail: return Qnil; } SWIGINTERN VALUE _wrap_Field_set_ascii(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; char *arg2 = (char *) 0 ; size_t result; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Set" "', argument " "1"" of type '" "ID3_Field *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); res2 = SWIG_AsCharPtrAndSize(argv[0], &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Set" "', argument " "2"" of type '" "char const *""'"); } arg2 = reinterpret_cast< char * >(buf2); result = (arg1)->Set((char const *)arg2); vresult = SWIG_From_size_t(static_cast< size_t >(result)); if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return vresult; fail: if (alloc2 == SWIG_NEWOBJ) delete[] buf2; return Qnil; } SWIGINTERN VALUE _wrap_Field_set_binary(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; VALUE arg2 = (VALUE) 0 ; size_t result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "set_binary" "', argument " "1"" of type '" "ID3_Field *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); arg2 = argv[0]; result = ID3_Field_set_binary(arg1,arg2); vresult = SWIG_From_size_t(static_cast< size_t >(result)); return vresult; fail: return Qnil; } SWIGINTERN VALUE _wrap_Field_set_unicode(int argc, VALUE *argv, VALUE self) { ID3_Field *arg1 = (ID3_Field *) 0 ; VALUE arg2 = (VALUE) 0 ; size_t result; void *argp1 = 0 ; int res1 = 0 ; VALUE vresult = Qnil; if ((argc < 1) || (argc > 1)) { rb_raise(rb_eArgError, "wrong # of arguments(%d for 1)",argc); SWIG_fail; } res1 = SWIG_ConvertPtr(self, &argp1,SWIGTYPE_p_ID3_Field, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "set_unicode" "', argument " "1"" of type '" "ID3_Field *""'"); } arg1 = reinterpret_cast< ID3_Field * >(argp1); arg2 = argv[0]; result = ID3_Field_set_unicode(arg1,arg2); vresult = SWIG_From_size_t(static_cast< size_t >(result)); return vresult; fail: return Qnil; } /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info _swigt__p_ID3_Field = {"_p_ID3_Field", "ID3_Field *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ID3_Frame = {"_p_ID3_Frame", "ID3_Frame *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ID3_Tag = {"_p_ID3_Tag", "ID3_Tag *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ID3_Tag__Iterator = {"_p_ID3_Tag__Iterator", "ID3_Tag::Iterator *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_unsigned_int = {"_p_unsigned_int", "unsigned int *|flags_t *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_ID3_Field, &_swigt__p_ID3_Frame, &_swigt__p_ID3_Tag, &_swigt__p_ID3_Tag__Iterator, &_swigt__p_char, &_swigt__p_unsigned_int, }; static swig_cast_info _swigc__p_ID3_Field[] = { {&_swigt__p_ID3_Field, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ID3_Frame[] = { {&_swigt__p_ID3_Frame, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ID3_Tag[] = { {&_swigt__p_ID3_Tag, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ID3_Tag__Iterator[] = { {&_swigt__p_ID3_Tag__Iterator, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_int[] = { {&_swigt__p_unsigned_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_ID3_Field, _swigc__p_ID3_Frame, _swigc__p_ID3_Tag, _swigc__p_ID3_Tag__Iterator, _swigc__p_char, _swigc__p_unsigned_int, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found; clientdata = clientdata; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" #endif SWIGEXPORT void Init_id3lib_api(void) { size_t i; SWIG_InitRuntime(); mAPI = rb_define_module("ID3Lib"); mAPI = rb_define_module_under(mAPI, "API"); SWIG_InitializeModule(0); for (i = 0; i < swig_module.size; i++) { SWIG_define_class(swig_module.types[i]); } SWIG_RubyInitializeTrackings(); cTag.klass = rb_define_class_under(mAPI, "Tag", rb_cObject); SWIG_TypeClientData(SWIGTYPE_p_ID3_Tag, (void *) &cTag); rb_define_alloc_func(cTag.klass, _wrap_Tag_allocate); rb_define_method(cTag.klass, "initialize", VALUEFUNC(_wrap_new_Tag), -1); rb_define_method(cTag.klass, "has_tag_type", VALUEFUNC(_wrap_Tag_has_tag_type), -1); rb_define_method(cTag.klass, "link", VALUEFUNC(_wrap_Tag_link), -1); rb_define_method(cTag.klass, "update", VALUEFUNC(_wrap_Tag_update), -1); rb_define_method(cTag.klass, "strip", VALUEFUNC(_wrap_Tag_strip), -1); rb_define_method(cTag.klass, "clear", VALUEFUNC(_wrap_Tag_clear), -1); rb_define_method(cTag.klass, "remove_frame", VALUEFUNC(_wrap_Tag_remove_frame), -1); rb_define_method(cTag.klass, "add_frame", VALUEFUNC(_wrap_Tag_add_frame), -1); rb_define_method(cTag.klass, "get_filename", VALUEFUNC(_wrap_Tag_get_filename), -1); rb_define_method(cTag.klass, "set_padding", VALUEFUNC(_wrap_Tag_set_padding), -1); rb_define_method(cTag.klass, "size", VALUEFUNC(_wrap_Tag_size), -1); rb_define_method(cTag.klass, "find", VALUEFUNC(_wrap_Tag_find), -1); rb_define_method(cTag.klass, "create_iterator", VALUEFUNC(_wrap_Tag_create_iterator), -1); cTag.mark = 0; cTag.destroy = (void (*)(void *)) free_ID3_Tag; cTag.trackObjects = 0; cTag_Iterator.klass = rb_define_class_under(mAPI, "Tag_Iterator", rb_cObject); SWIG_TypeClientData(SWIGTYPE_p_ID3_Tag__Iterator, (void *) &cTag_Iterator); rb_undef_alloc_func(cTag_Iterator.klass); rb_define_method(cTag_Iterator.klass, "get_next", VALUEFUNC(_wrap_Tag_Iterator_get_next), -1); cTag_Iterator.mark = 0; cTag_Iterator.destroy = (void (*)(void *)) free_ID3_Tag_Iterator; cTag_Iterator.trackObjects = 0; cFrame.klass = rb_define_class_under(mAPI, "Frame", rb_cObject); SWIG_TypeClientData(SWIGTYPE_p_ID3_Frame, (void *) &cFrame); rb_define_alloc_func(cFrame.klass, _wrap_Frame_allocate); rb_define_method(cFrame.klass, "initialize", VALUEFUNC(_wrap_new_Frame), -1); rb_define_method(cFrame.klass, "get_field", VALUEFUNC(_wrap_Frame_get_field), -1); rb_define_method(cFrame.klass, "get_id", VALUEFUNC(_wrap_Frame_get_id), -1); cFrame.mark = 0; cFrame.destroy = (void (*)(void *)) free_ID3_Frame; cFrame.trackObjects = 0; cField.klass = rb_define_class_under(mAPI, "Field", rb_cObject); SWIG_TypeClientData(SWIGTYPE_p_ID3_Field, (void *) &cField); rb_undef_alloc_func(cField.klass); rb_define_method(cField.klass, "get_type", VALUEFUNC(_wrap_Field_get_type), -1); rb_define_method(cField.klass, "get_encoding", VALUEFUNC(_wrap_Field_get_encoding), -1); rb_define_method(cField.klass, "get_integer", VALUEFUNC(_wrap_Field_get_integer), -1); rb_define_method(cField.klass, "get_ascii", VALUEFUNC(_wrap_Field_get_ascii), -1); rb_define_method(cField.klass, "get_binary", VALUEFUNC(_wrap_Field_get_binary), -1); rb_define_method(cField.klass, "get_unicode", VALUEFUNC(_wrap_Field_get_unicode), -1); rb_define_method(cField.klass, "set_encoding", VALUEFUNC(_wrap_Field_set_encoding), -1); rb_define_method(cField.klass, "set_integer", VALUEFUNC(_wrap_Field_set_integer), -1); rb_define_method(cField.klass, "set_ascii", VALUEFUNC(_wrap_Field_set_ascii), -1); rb_define_method(cField.klass, "set_binary", VALUEFUNC(_wrap_Field_set_binary), -1); rb_define_method(cField.klass, "set_unicode", VALUEFUNC(_wrap_Field_set_unicode), -1); cField.mark = 0; cField.trackObjects = 0; }
[ [ [ 1, 3341 ] ] ]
47a7d371a277a3c82ea6d0fad26f0e041d531809
3472e587cd1dff88c7a75ae2d5e1b1a353962d78
/ytk_bak/test/TestVSQt/TestQtWebKit.h
9e3d4614a9eb0bd246c76e474654eac659b2fe8d
[]
no_license
yewberry/yewtic
9624d05d65e71c78ddfb7bd586845e107b9a1126
2468669485b9f049d7498470c33a096e6accc540
refs/heads/master
2021-01-01T05:40:57.757112
2011-09-14T12:32:15
2011-09-14T12:32:15
32,363,059
0
0
null
null
null
null
UTF-8
C++
false
false
682
h
#ifndef TESTQTWEBKIT_H #define TESTQTWEBKIT_H #include "common.h" #include <QtGui/QDialog> QT_BEGIN_NAMESPACE class QWebView; class QLineEdit; QT_END_NAMESPACE class TestQtWebKit : public QDialog { Q_OBJECT public: TestQtWebKit(QWidget *parent = 0, Qt::WFlags flags = 0); ~TestQtWebKit(void); public slots: void populateJavaScriptWindowObject(); void setValues(const QString &value); protected slots: void finishLoading(bool); private slots: void evalJS(); private: void initLogger(); Logger logger; private: QString extjs; QWebView *view; QLineEdit *locationEdit; QPushButton *gooBtn; }; #endif // TESTQTWEBKIT_H
[ "yew1998@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86" ]
[ [ [ 1, 44 ] ] ]
74391c8182980e3db882aa80480f29109ccb42d5
d6a28d9d845a20463704afe8ebe644a241dc1a46
/source/Irrlicht/CWADReader.cpp
b2268249ca2ee95e58a2e7a42a1f590df66bc819
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "Zlib" ]
permissive
marky0720/irrlicht-android
6932058563bf4150cd7090d1dc09466132df5448
86512d871eeb55dfaae2d2bf327299348cc5202c
refs/heads/master
2021-04-30T08:19:25.297407
2010-10-08T08:27:33
2010-10-08T08:27:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,138
cpp
// Copyright (C) 2002-2009 Thomas Alten // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h // Code contributed by skreamz #include "IrrCompileConfig.h" #ifdef __IRR_COMPILE_WITH_WAD_ARCHIVE_LOADER_ #include "CWADReader.h" #include "os.h" #include "coreutil.h" namespace irr { namespace io { //! Constructor CArchiveLoaderWAD::CArchiveLoaderWAD( io::IFileSystem* fs) : FileSystem(fs) { #ifdef _DEBUG setDebugName("CArchiveLoaderWAD"); #endif } //! returns true if the file maybe is able to be loaded by this class bool CArchiveLoaderWAD::isALoadableFileFormat(const io::path& filename) const { return core::hasFileExtension ( filename, "wad" ); } //! Creates an archive from the filename /** \param file File handle to check. \return Pointer to newly created archive, or 0 upon error. */ IFileArchive* CArchiveLoaderWAD::createArchive(const io::path& filename, bool ignoreCase, bool ignorePaths) const { IFileArchive *archive = 0; io::IReadFile* file = FileSystem->createAndOpenFile(filename); if (file) { archive = createArchive ( file, ignoreCase, ignorePaths ); file->drop (); } return archive; } //! creates/loads an archive from the file. //! \return Pointer to the created archive. Returns 0 if loading failed. IFileArchive* CArchiveLoaderWAD::createArchive(io::IReadFile* file, bool ignoreCase, bool ignorePaths) const { IFileArchive *archive = 0; if ( file ) { file->seek ( 0 ); archive = new CWADReader(file, ignoreCase, ignorePaths); } return archive; } //! Check if the file might be loaded by this class /** Check might look into the file. \param file File handle to check. \return True if file seems to be loadable. */ bool CArchiveLoaderWAD::isALoadableFileFormat(io::IReadFile* file) const { SWADFileHeader header; memset(&header, 0, sizeof(header)); file->read( &header.tag, 4 ); return !strncmp ( header.tag, "WAD2", 4 ) || !strncmp ( header.tag, "WAD3", 4 ); } //! Check to see if the loader can create archives of this type. bool CArchiveLoaderWAD::isALoadableFileFormat(E_FILE_ARCHIVE_TYPE fileType) const { return fileType == EFAT_WAD; } void createDir ( const c8 *full ); /*! WAD Reader */ CWADReader::CWADReader(IReadFile* file, bool ignoreCase, bool ignorePaths) : CFileList((file ? file->getFileName() : io::path("")), ignoreCase, ignorePaths), File(file) { #ifdef _DEBUG setDebugName("CWADReader"); #endif if (File) { File->grab(); Base = File->getFileName(); Base.replace ( '\\', '/' ); // scan local headers scanLocalHeader(); sort(); } #if 0 for ( u32 i = 0; i < FileList.size(); ++i ) { SWADFileEntry &e = FileList[i]; char buf[128]; snprintf ( buf, 128, "c:\\h2\\%s", e.wadFileName.c_str() ); createDir ( buf ); FILE * f = fopen ( buf, "wb" ); if ( 0 == f ) continue; u8 * mem = new u8 [ e.header.disksize ]; File->seek ( e.header.filepos ); File->read ( mem, e.header.disksize ); fwrite ( mem, e.header.disksize, 1, f ); delete [] mem; fclose ( f ); } #endif } CWADReader::~CWADReader() { if (File) File->drop(); } //! return the id of the file Archive const io::path& CWADReader::getArchiveName () const { return Base; } const IFileList* CWADReader::getFileList() const { return this; } //! scans for a local header, returns false if there is no more local file header. bool CWADReader::scanLocalHeader() { SWADFileEntryOriginal entry; SWADFileEntry save; memset(&Header, 0, sizeof(SWADFileHeader)); File->read(&Header, sizeof(SWADFileHeader)); if ( 0 == strncmp ( Header.tag, "WAD2", 4 ) ) WadType = WAD_FORMAT_QUAKE2; else if ( 0 == strncmp ( Header.tag, "WAD3", 4 ) ) WadType = WAD_FORMAT_HALFLIFE; else WadType = WAD_FORMAT_UNKNOWN; if ( WadType == WAD_FORMAT_UNKNOWN ) return false; #ifdef __BIG_ENDIAN__ Header.numlumps = os::Byteswap::byteswap(Header.numlumps); Header.infotableofs = os::Byteswap::byteswap(Header.infotableofs); #endif File->seek ( Header.infotableofs ); c8 buf[16]; for ( u32 i = 0; i < Header.numlumps; ++i ) { // read entry File->read(&entry, sizeof ( SWADFileEntryOriginal )); entry.name[ sizeof ( entry.name ) - 1 ] = 0; save.header = entry; save.wadFileName = "/"; save.wadFileName += entry.name; if ( WadType == WAD_FORMAT_HALFLIFE ) { // don't know about the types! i'm guessing switch ( entry.type ) { case WAD_TYP_MIPTEX_HALFLIFE: save.wadFileName += ".wal2"; break; default: snprintf ( buf, 16, ".%02d", entry.type ); save.wadFileName += buf; break; } } else if ( WadType == WAD_FORMAT_QUAKE2 ) { switch ( entry.type ) { case WAD_TYP_MIPTEX: save.wadFileName += ".miptex"; break; case WAD_TYP_SOUND: save.wadFileName += ".sound"; break; case WAD_TYP_PALETTE: save.wadFileName += ".palette"; break; case WAD_TYP_QTEX: save.wadFileName += ".qtex"; break; case WAD_TYP_QPIC: save.wadFileName += ".qpic"; break; case WAD_TYP_FONT: save.wadFileName += ".font"; break; default: snprintf ( buf, 16, ".%02d", entry.type ); save.wadFileName += buf; break; } } // add file to list addItem(save.wadFileName,save.header.filepos, save.header.disksize, false ); //FileInfo.push_back(save); } return true; } //! opens a file by file name IReadFile* CWADReader::createAndOpenFile(const io::path& filename) { s32 index = findFile(filename, false); if (index != -1) return createAndOpenFile(index); return 0; } //! opens a file by index IReadFile* CWADReader::createAndOpenFile(u32 index) { if (index >= Files.size() ) return 0; const SFileListEntry &entry = Files[index]; return createLimitReadFile( entry.FullName, File, entry.Offset, entry.Size ); } } // end namespace io } // end namespace irr #endif // __IRR_COMPILE_WITH_WAD_ARCHIVE_LOADER_
[ "engineer_apple@dfc29bdd-3216-0410-991c-e03cc46cb475", "hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475" ]
[ [ [ 1, 176 ], [ 179, 263 ] ], [ [ 177, 178 ] ] ]
485b9cde60f915967bca445260b61bfa5d26e1e6
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/NewWheelDirector/src/logic/ProRunLogic.cpp
9a2190c888b8ca344914c7e9cc888ee33100dc1c
[]
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
968
cpp
#include "NewWheelDirectorStableHeaders.h" #include "logic/AllLogic.h" #include "WheelEvents.h" using namespace Orz; ProRunLogic::ProRunLogic(my_context ctx):LogicAdv(ctx) { ORZ_LOG_NORMAL_MESSAGE("State In: ProRunLogic!"); getOwner()->runWinner(); //WheelUI::getSingleton().runZXH(Hardware::getSingleton().getWinType()->getBanker()); _process.reset( new Process( getOwner()->getWorld(), WheelEvents::PROCESS_PRORUN_ENABLE, WheelEvents::PROCESS_PRORUN_DISABLE)); } ProRunLogic::~ProRunLogic(void) { ORZ_LOG_NORMAL_MESSAGE("State Out: ProRunLogic!"); } sc::result ProRunLogic::react(const UpdateEvt & evt) { if(_process->update(evt.getInterval())) return forward_event(); //return forward_event(); return transit<RunLogic>(); } //sc::result ProRunLogic::react(const LogicEvent::AskState & evt) //{ // evt.execute(getOwner(), 0x01); // //Hardware::getSingleton().answerState(0x01); // return forward_event(); //}
[ [ [ 1, 36 ] ] ]
d117b3a0d61942ae0e9ccdf42d31edb555794247
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/pcsx2/gui/i18n.cpp
5dcb77519bed6482e3d0ee4f28d06acd4c6963b3
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
5,427
cpp
/* PCSX2 - PS2 Emulator for PCs * Copyright (C) 2002-2010 PCSX2 Dev Team * * PCSX2 is free software: you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Found- * ation, either version 3 of the License, or (at your option) any later version. * * PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with PCSX2. * If not, see <http://www.gnu.org/licenses/>. */ #include "PrecompiledHeader.h" #include "i18n.h" #include "AppConfig.h" #include "Utilities/SafeArray.h" LangPackEnumeration::LangPackEnumeration( wxLanguage langId ) : wxLangId( langId ) , englishName( wxLocale::GetLanguageName( wxLangId ) ) , xlatedName( pxIsEnglish( wxLangId ) ? wxEmptyString : wxGetTranslation( L"NativeName" ) ) { } LangPackEnumeration::LangPackEnumeration() : wxLangId( wxLANGUAGE_DEFAULT ) , englishName( L" System Default" ) // left-side space forces it to sort to the front of the lists , xlatedName() { int sysLang( wxLocale::GetSystemLanguage() ); if( sysLang != wxLANGUAGE_UNKNOWN ) englishName += L" [" + wxLocale::GetLanguageName( sysLang ) + L"]"; } static void i18n_DoPackageCheck( wxLanguage wxLangId, LangPackList& langs ) { // Plain english is a special case that's built in, and we only want it added to the list // once, so we check for wxLANGUAGE_ENGLISH and then ignore other IsEnglish ids below. if( wxLangId == wxLANGUAGE_ENGLISH ) langs.push_back( LangPackEnumeration( wxLangId ) ); if( pxIsEnglish( wxLangId ) ) return; // Note: wx auto-preserves the current locale for us if( !wxLocale::IsAvailable( wxLangId ) ) return; wxLocale* locale = new wxLocale( wxLangId, wxLOCALE_CONV_ENCODING ); // Force the msgIdLanguage param to wxLANGUAGE_UNKNOWN to disable wx's automatic english // matching logic, which will bypass the catalog loader for all english-based dialects, and // (wrongly) enumerate a bunch of locales that don't actually exist. if( locale->IsOk() && locale->AddCatalog( L"pcsx2ident", wxLANGUAGE_UNKNOWN, NULL ) ) langs.push_back( LangPackEnumeration( wxLangId ) ); delete locale; } // Finds all valid PCSX2 language packs, and enumerates them for configuration selection. // Note: On linux there's no easy way to reliably enumerate language packs, since every distro // could use its own location for installing pcsx2.mo files (wtcrap?). Furthermore wxWidgets // doesn't give us a public API for checking what the language search paths are. So the only // safe way to enumerate the languages is by forcibly loading every possible locale in the wx // database. Anything which hasn't been installed will fail to load. // // Because loading and hashing the entire pcsx2 translation for every possible language would // asinine and slow, I've decided to use a two-file translation system. One file (pcsx2ident.mo) // is very small and simply contains the name of the language in the language native. The // second file (pcsx2.mo) is loaded only if the user picks the language (or if it's the default // language of the user's OS installation). // void i18n_EnumeratePackages( LangPackList& langs ) { wxDoNotLogInThisScope here; // wx generates verbose errors if languages don't exist, so disable them here. langs.push_back( LangPackEnumeration() ); for( int li=wxLANGUAGE_UNKNOWN+1; li<wxLANGUAGE_USER_DEFINED; ++li ) { i18n_DoPackageCheck( (wxLanguage)li, langs ); } // Brilliant. Because someone in the wx world didn't think to move wxLANGUAGE_USER_DEFINED // to a place where it wasn't butt right up against the main languages (like, say, start user // defined values at 4000 or something?), they had to add new languages in at some arbitrary // value instead. Let's handle them here: // fixme: these won't show up in alphabetical order if they're actually present (however // horribly unlikely that is)... do we care? Probably not. // Note: These aren't even available in some packaged Linux distros anyway. >_< //i18n_DoPackageCheck( wxLANGUAGE_VALENCIAN, englishNames, xlatedNames ); //i18n_DoPackageCheck( wxLANGUAGE_SAMI, englishNames, xlatedNames ); } bool i18n_SetLanguage( int wxLangId ) { if( !wxLocale::IsAvailable( wxLangId ) ) { Console.Warning( "Invalid Language Identifier (wxID=%d).", wxLangId ); return false; } ScopedPtr<wxLocale> locale( new wxLocale( wxLangId, wxLOCALE_CONV_ENCODING ) ); if( !locale->IsOk() ) { Console.Warning( L"SetLanguage: '%s' [%s] is not supported by the operating system", wxLocale::GetLanguageName( locale->GetLanguage() ).c_str(), locale->GetCanonicalName().c_str() ); return false; } if( !pxIsEnglish(wxLangId) && !locale->AddCatalog( L"pcsx2main" ) ) { /*Console.Warning( L"SetLanguage: Cannot find pcsx2main.mo file for language '%s' [%s]", wxLocale::GetLanguageName( locale->GetLanguage() ).c_str(), locale->GetCanonicalName().c_str() );*/ Console.Warning("SetLanguage is not implemented yet, using English."); return false; } locale.DetachPtr(); return true; }
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 128 ] ] ]
e0fd5d05a1d004ca8f49b785fb61c79bbc4e131d
6188f1aaaf5508e046cde6da16b56feb3d5914bc
/CamFighter/Graphics/OGL/GuiCheckBox.h
da40759837b36c90c825248cb01d337c7c6ede22
[]
no_license
dogtwelve/fighter3d
7bb099f0dc396e8224c573743ee28c54cdd3d5a2
c073194989bc1589e4aa665714c5511f001e6400
refs/heads/master
2021-04-30T15:58:11.300681
2011-06-27T18:51:30
2011-06-27T18:51:30
33,675,635
1
0
null
null
null
null
UTF-8
C++
false
false
2,104
h
#ifndef __incl_Graphics_OGL_GuiCheckBox_h #define __incl_Graphics_OGL_GuiCheckBox_h #include "../Textures/TextureMgr.h" #include "GuiLabel.h" namespace Graphics { namespace OGL { class CGuiCheckBox : public CGuiControl { private: HTexture m_hBoxIcon; HTexture m_hTickIcon; CGuiLabel * m_pcLabel; xSHORT m_nBoxX, m_nBoxY, m_nBoxWidth, m_nBoxHeight; xSHORT m_nTickX, m_nTickY, m_nTickWidth, m_nTickHeight; bool m_bChecked; void Zero(); protected: virtual void ChildIsRemoving(const CGuiControl &pcChild) { if (&pcChild == m_pcLabel) m_pcLabel = 0; } public: xColor m_sBackgroundColor; xColor m_sBorderColor; void SetImage(const char *sTickIcon, xSHORT nTickWidth = 0, xSHORT nTickHeight = 0, const char *sBoxIcon = 0, xSHORT nBoxWidth = 0, xSHORT nBoxHeight = 0 ); void SetText(const xString &sText, const xString &sFont = xString::Empty(), xSHORT nSize = 0); void SetChecked(bool bChecked) { if (bChecked != m_bChecked) { m_bChecked = bChecked; OnCheckedChanged(); } } bool IsChecked() { return m_bChecked; } ControlEvent OnCheckedChanged; CGuiCheckBox() : CGuiControl() { Zero(); } CGuiCheckBox(xSHORT nX, xSHORT nY, xSHORT nWidth, xSHORT nHeight) : CGuiControl(nX, nY, nWidth, nHeight) { Zero(); } virtual ~CGuiCheckBox() { g_TextureMgr.Release(m_hBoxIcon); g_TextureMgr.Release(m_hTickIcon); } virtual void OnMouseLeftDown(bool receiver); virtual void OnMouseLeftUp (bool receiver); virtual void OnMouseEnter (); virtual void OnMouseLeave (); virtual void OnRender(); }; } } // namespace Graphics::OGL #endif // __incl_Graphics_OGL_GuiCheckBox_h
[ "[email protected]@f75eed02-8a0f-11dd-b20b-83d96e936561" ]
[ [ [ 1, 72 ] ] ]
f10a1c9f56db7f35090421b37d3067a0cae2a840
89b720ca3097d4e5ca81f78500eca5ee83c23fdb
/3dGame/engine/MyUserInput.h
d3bf66e4ea4efc8e6dfd5146888c140ae6a8b50e
[]
no_license
BackupTheBerlios/vrrace-svn
3a95635c63b08cfa0bb26ae295d35d2f7b4f14e4
078b0fa532d84586be3ccd0535776686ed19f126
refs/heads/master
2021-01-19T15:40:47.631561
2005-03-30T17:09:07
2005-03-30T17:09:07
40,748,970
0
0
null
null
null
null
UTF-8
C++
false
false
1,514
h
#pragma once #ifndef MYUSERINPUT_H #define MYUSERINPUT_H #include "includes.h" #include "MyGameControl.h" class MyUserInput { public: MyUserInput(void); ~MyUserInput(void); bool init(HINSTANCE* hInst, HWND* hWnd, MyGameControl* givenGC); //alles Initialisieren void inputKB(); //Tastatureingaben verarbeiten HRESULT inputJS(); void doFF(); bool m_JoystickAvailable; static LPDIRECTINPUTEFFECT pEff[6]; private: bool initDinput(); //Initialisierung des Input-Objektes bool initKeyboard(); //Initialisierung der Tastatur bool initJoystick(); //Initialisierung des Joysticks bool initMouse(); //Initialisierung der Maus float inputFactor(float givenValue); static BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE* pdidInstance, VOID* pContext); static BOOL CALLBACK EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE* pdidoi, VOID* pContext); static BOOL CALLBACK DIEnumEffectsProc(LPCDIEFFECTINFO pei, LPVOID pv); void loadEffects(); static BOOL CALLBACK EnumEffectsInFileProc(LPCDIFILEEFFECT lpdife, LPVOID pvRef); HINSTANCE* m_hInst; HWND* m_hWnd; static HRESULT m_hr; static LPDIRECTINPUT8 m_lpDI; DIDEVCAPS m_diDevCaps; LPDIRECTINPUTDEVICE8 m_lpDIDevice; LPDIRECTINPUTDEVICE8 m_pMouse; LPDIRECTINPUTEFFECT m_lpdiEffect; static LPDIRECTINPUTDEVICE8 m_pJoystick; static BOOL EffectFound; MyGameControl* _m_pGameControl; }; #endif
[ "lxorg@b1670157-89ef-0310-b5f9-fe94102b68b0" ]
[ [ [ 1, 49 ] ] ]
4222aa9165262d86ae0f2e3fc83c03627675a097
0468c65f767387da526efe03b37e1d6e8ddd1815
/source/drivers/win/main.h
a70db9c2db65098185a56928833bded9ea9474c6
[]
no_license
arntsonl/fc2x
aadc4e1a6c4e1d5bfcc76a3815f1f033b2d7e2fd
57ffbf6bcdf0c0b1d1e583663e4466adba80081b
refs/heads/master
2021-01-13T02:22:19.536144
2011-01-11T22:48:58
2011-01-11T22:48:58
32,103,729
0
0
null
null
null
null
UTF-8
C++
false
false
3,802
h
#ifndef WIN_MAIN_H #define WIN_MAIN_H #include "common.h" #include <string> // #defines #define MAX(x,y) ((x)<(y)?(y):(x)) #define MIN(x,y) ((x)>(y)?(y):(x)) #define VNSCLIP ((eoptions&EO_CLIPSIDES)?8:0) #define VNSWID ((eoptions&EO_CLIPSIDES)?240:256) #define SO_FORCE8BIT 1 #define SO_SECONDARY 2 #define SO_GFOCUS 4 #define SO_D16VOL 8 #define SO_MUTEFA 16 #define SO_OLDUP 32 #define GOO_DISABLESS 1 /* Disable screen saver when game is loaded. */ #define GOO_CONFIRMEXIT 2 /* Confirmation before exiting. */ #define GOO_POWERRESET 4 /* Confirm on power/reset. */ //For single instance mode, transfers with WM_COPYDATA //http://www.go4expert.com/forums/showthread.php?t=19730 typedef struct WMCopyStruct { char strFilePath[2048]; } DATA; extern int maxconbskip; extern int ffbskip; extern void LoadNewGamey(HWND hParent, const char *initialdir); extern void CloseGame(); extern int fullscreen; //Windows files only, keeps track of fullscreen status // Flag that indicates whether Game Genie is enabled or not. extern int genie; // Flag that indicates whether PAL Emulation is enabled or not. extern int pal_emulation; extern int status_icon; extern int frame_display; extern int input_display; extern int allowUDLR; extern int pauseAfterPlayback; extern int closeFinishedMovie; extern int EnableBackgroundInput; extern int AFon; extern int AFoff; extern int AutoFireOffset; extern int vmod; extern char* directory_names[14]; char *GetRomName(); //Checks if rom is loaded, if so, outputs the Rom name with no directory path or file extension ///Contains the names of the default directories. static const char *default_directory_names[13] = { "", // roms "sav", // nonvol "fcs", // states "", // fdsrom "snaps", // snaps "cheats", // cheats "movies", // movies "tools", // memwatch "tools", // macro "tools", // input presets "tools", // lua scripts "", // avi output "" // adelikat - adding a dummy one here ( [13] but only 12 entries) }; #define NUMBER_OF_DIRECTORIES sizeof(directory_names) / sizeof(*directory_names) #define NUMBER_OF_DEFAULT_DIRECTORIES sizeof(default_directory_names) / sizeof(*default_directory_names) extern double saspectw, saspecth; extern double winsizemulx, winsizemuly; extern int ismaximized; extern int soundoptions; extern int soundrate; extern int soundbuftime; extern int soundvolume; //Master volume control extern int soundTrianglevol;//Sound channel Triangle - volume control extern int soundSquare1vol; //Sound channel Square1 - volume control extern int soundSquare2vol; //Sound channel Square2 - volume control extern int soundNoisevol; //Sound channel Noise - volume control extern int soundPCMvol; //Sound channel PCM - volume control extern int soundquality; extern bool muteTurbo; extern uint8 cpalette[192]; extern int srendlinen; extern int erendlinen; extern int srendlinep; extern int erendlinep; extern int ntsccol, ntsctint, ntschue; //mbg merge 7/17/06 did these have to be unsigned? //static int srendline, erendline; static int changerecursive=0; /// Contains the base directory of FCE extern std::string BaseDirectory; extern int soundo; extern int eoptions; extern int soundoptions; extern uint8 *xbsave; extern HRESULT ddrval; extern int windowedfailed; extern uint32 goptions; void DoFCEUExit(); void ShowAboutBox(); int BlockingCheck(); void DoPriority(); void RemoveDirs(); void CreateDirs(); void SetDirs(); void FCEUX_LoadMovieExtras(const char * fname); //void initDirectories(); //adelikat 03/02/09 - commenting out reference to a directory that I commented out #endif
[ "Cthulhu32@e9098629-9c10-95be-0fa9-336bad66c20b" ]
[ [ [ 1, 132 ] ] ]
05de44b0de13cbe9489844328076b0da738aa0d4
77aa13a51685597585abf89b5ad30f9ef4011bde
/dep/src/boost/boost/utility/result_of.hpp
dc4203020fe35e41a0b2983ffe6012d17c10edb3
[]
no_license
Zic/Xeon-MMORPG-Emulator
2f195d04bfd0988a9165a52b7a3756c04b3f146c
4473a22e6dd4ec3c9b867d60915841731869a050
refs/heads/master
2021-01-01T16:19:35.213330
2009-05-13T18:12:36
2009-05-14T03:10:17
200,849
8
10
null
null
null
null
UTF-8
C++
false
false
2,159
hpp
// Boost result_of library // Copyright Douglas Gregor 2004. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // For more information, see http://www.boost.org/libs/utility #ifndef BOOST_RESULT_OF_HPP #define BOOST_RESULT_OF_HPP #include <boost/config.hpp> #include <boost/type_traits/ice.hpp> #include <boost/type.hpp> #include <boost/preprocessor.hpp> #include <boost/detail/workaround.hpp> #include <boost/mpl/has_xxx.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/bool.hpp> #ifndef BOOST_RESULT_OF_NUM_ARGS # define BOOST_RESULT_OF_NUM_ARGS 10 #endif namespace boost { template<typename F> struct result_of; #if !defined(BOOST_NO_SFINAE) && !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) namespace detail { BOOST_MPL_HAS_XXX_TRAIT_DEF(result_type) template<typename F, typename FArgs, bool HasResultType> struct result_of_impl; template<typename F> struct result_of_void_impl { typedef void type; }; template<typename R> struct result_of_void_impl<R (*)(void)> { typedef R type; }; template<typename R> struct result_of_void_impl<R (&)(void)> { typedef R type; }; template<typename F, typename FArgs> struct result_of_impl<F, FArgs, true> { typedef typename F::result_type type; }; template<typename FArgs> struct is_function_with_no_args : mpl::false_ {}; template<typename F> struct is_function_with_no_args<F(void)> : mpl::true_ {}; template<typename F, typename FArgs> struct result_of_nested_result : F::template result<FArgs> {}; template<typename F, typename FArgs> struct result_of_impl<F, FArgs, false> : mpl::if_<is_function_with_no_args<FArgs>, result_of_void_impl<F>, result_of_nested_result<F, FArgs> >::type {}; } // end namespace detail #define BOOST_PP_ITERATION_PARAMS_1 (3,(0,BOOST_RESULT_OF_NUM_ARGS,<boost/utility/detail/result_of_iterate.hpp>)) #include BOOST_PP_ITERATE() #else # define BOOST_NO_RESULT_OF 1 #endif } #endif // BOOST_RESULT_OF_HPP
[ "pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88" ]
[ [ [ 1, 88 ] ] ]
fd33846e2afff9b808736c16ca23c318711355fa
eb869f3bc7728e55b5bd6ab2ad5f2a25e7f2a0a6
/S60_V5x/TMApp/inc/TraceManagerAppUi.h
3ee967aae15387c0c7a1fb84145042ba0b5dc88a
[]
no_license
runforu/musti-emulator
257420f505a519113fe7c529a3eaeda4e91d918c
0254eb549e5e0ec8e8a0a4da796b5652268aa17c
refs/heads/master
2020-05-19T07:49:09.924331
2010-11-30T06:28:37
2010-11-30T06:28:37
32,321,074
0
1
null
null
null
null
UTF-8
C++
false
false
1,667
h
/* ======================================================================== Name : TraceManagerAppUi.h Author : DH Copyright : All right is reserved! Version : E-Mail : [email protected] Description : Copyright (c) 2009-2015 DH. This material, including documentation and any related computer programs, is protected by copyright controlled BY Du Hui(DH) ======================================================================== */ #ifndef TRACEMANAGERAPPUI_H #define TRACEMANAGERAPPUI_H #include <aknviewappui.h> class CTraceManagerMainView; class CTraceManagerSettingView; class CTMBtWriter; /** * @class CTraceManagerAppUi TraceManagerAppUi.h * @brief The AppUi class handles application-wide aspects of the user interface, including * view management and the default menu, control pane, and status pane. */ class CTraceManagerAppUi : public CAknViewAppUi { public: // constructor and destructor CTraceManagerAppUi(); virtual ~CTraceManagerAppUi(); void ConstructL(); public: // from CCoeAppUi TKeyResponse HandleKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType ); // from CEikAppUi void HandleCommandL( TInt aCommand ); void HandleResourceChangeL( TInt aType ); // from CAknAppUi void HandleViewDeactivation( const TVwsViewId& aViewIdToBeDeactivated, const TVwsViewId& aNewlyActivatedViewId ); private: void InitializeContainersL(); public: private: CTraceManagerMainView* iTraceManagerMainView; CTraceManagerSettingView* iTraceManagerSettingView; protected: }; #endif // TRACEMANAGERAPPUI_H
[ "[email protected]@c3ffc87a-496d-339f-d77d-193528aa0bc0" ]
[ [ [ 1, 64 ] ] ]
ed8c41b7c297b189a97b55fedbe81ea46500c881
11af1673bab82ca2329ef8b596d1f3d2f8b82481
/source/game/FP_Team_Heal.cpp
dd2854a63b173b6d5cdd9cbc4f31b8e5be4199ca
[]
no_license
legacyrp/legacyojp
8b33ecf24fd973bee5e7adbd369748cfdd891202
d918151e917ea06e8698f423bbe2cf6ab9d7f180
refs/heads/master
2021-01-10T20:09:55.748893
2011-04-18T21:07:13
2011-04-18T21:07:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,913
cpp
#include "w_force.h" void WP_AddToClientBitflags(gentity_t *ent, int entNum) { if (!ent) return; if (entNum > 47) ent->s.trickedentindex4 |= (1 << (entNum-48)); else if (entNum > 31) ent->s.trickedentindex3 |= (1 << (entNum-32)); else if (entNum > 15) ent->s.trickedentindex2 |= (1 << (entNum-16)); else ent->s.trickedentindex |= (1 << entNum); } void ForceTeamHeal( gentity_t *self ) { float radius = 256; int i = 0; gentity_t *ent; vec3_t a; int numpl = 0; int pl[MAX_CLIENTS]; int healthadd = 0; gentity_t *te = NULL; if ( self->health <= 0 ) return; if ( !WP_ForcePowerUsable( self, FP_TEAM_HEAL ) ) return; if (self->client->ps.fd.forcePowerDebounce[FP_TEAM_HEAL] >= level.time) return; if (self->client->ps.fd.forcePowerLevel[FP_TEAM_HEAL] == FORCE_LEVEL_2) radius *= 1.5; else if (self->client->ps.fd.forcePowerLevel[FP_TEAM_HEAL] == FORCE_LEVEL_3) radius *= 2; while (i < MAX_CLIENTS) { ent = &g_entities[i]; //Legacy MOD : Removed && OnSameTeam(self, ent) if (ent && ent->client && self != ent && ent->client->ps.stats[STAT_HEALTH] < ent->client->ps.stats[STAT_MAX_HEALTH] && ent->client->ps.stats[STAT_HEALTH] > 0 && ForcePowerUsableOn(self, ent, FP_TEAM_HEAL) && trap_InPVS(self->client->ps.origin, ent->client->ps.origin)) { VectorSubtract(self->client->ps.origin, ent->client->ps.origin, a); if (VectorLength(a) <= radius) { pl[numpl] = i; numpl++; } } i++; } if (numpl < 1) return; if (numpl == 1) healthadd = 50; else if (numpl == 2) healthadd = 33; else healthadd = 25; self->client->ps.fd.forcePowerDebounce[FP_TEAM_HEAL] = level.time + 2000; i = 0; while (i < numpl) { if (g_entities[pl[i]].client->ps.stats[STAT_HEALTH] > 0 && g_entities[pl[i]].health > 0) { g_entities[pl[i]].client->ps.stats[STAT_HEALTH] += healthadd; if (g_entities[pl[i]].client->ps.stats[STAT_HEALTH] > g_entities[pl[i]].client->ps.stats[STAT_MAX_HEALTH]) { g_entities[pl[i]].client->ps.stats[STAT_HEALTH] = g_entities[pl[i]].client->ps.stats[STAT_MAX_HEALTH]; } g_entities[pl[i]].health = g_entities[pl[i]].client->ps.stats[STAT_HEALTH]; //At this point we know we got one, so add him into the collective event client bitflag if (!te) { te = G_TempEntity( self->client->ps.origin, EV_TEAM_POWER); te->s.eventParm = 1; //eventParm 1 is heal, eventParm 2 is force regen //since we had an extra check above, do the drain now because we got at least one guy BG_ForcePowerDrain( &self->client->ps, FP_TEAM_HEAL, forcePowerNeeded[self->client->ps.fd.forcePowerLevel[FP_TEAM_HEAL]][FP_TEAM_HEAL] ); } WP_AddToClientBitflags(te, pl[i]); //Now cramming it all into one event.. doing this many g_sound events at once was a Bad Thing. } i++; } }
[ "[email protected]@5776d9f2-9662-11de-ad41-3fcdc5e0e42d" ]
[ [ [ 1, 108 ] ] ]
fe99959a27be53bd7c84fd21717378250b8a002e
011359e589f99ae5fe8271962d447165e9ff7768
/ps3/burner_ps3.h
5230218e3ec5f4535497124fefa5d8eda18befa8
[]
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
9,072
h
#ifndef BURNER_PS3_H #define BURNER_PS3_H #ifdef _UNICODE #define UNICODE #endif #include <string.h> #include <sys/timer.h> #include <sys/return_code.h> #include <sys/process.h> #include <sys/vm.h> #include <cell/audio.h> #include <cell/sysmodule.h> #include <cell/cell_fs.h> #include <cell/pad.h> #include <stddef.h> #include <math.h> #include <sysutil/sysutil_sysparam.h> // --------------------------------------------------------------------------- // use STL #include <string> #include <list> #include <set> #include <map> #include <string> #include <vector> #include <hash_map> #include <fstream> using std::string; using std::list; using std::set; using std::map; using std::vector; using std::multimap; using std::ofstream; enum { ASPECT_RATIO_4_3, ASPECT_RATIO_5_4, ASPECT_RATIO_7_5, ASPECT_RATIO_8_7, ASPECT_RATIO_10_7, ASPECT_RATIO_11_8, ASPECT_RATIO_12_7, ASPECT_RATIO_16_9, ASPECT_RATIO_16_10, ASPECT_RATIO_16_15, ASPECT_RATIO_19_14, ASPECT_RATIO_1_1, ASPECT_RATIO_2_1, ASPECT_RATIO_3_2, ASPECT_RATIO_3_4, ASPECT_RATIO_CUSTOM, ASPECT_RATIO_AUTO, ASPECT_RATIO_AUTO_FBA }; #define LAST_ASPECT_RATIO ASPECT_RATIO_AUTO_FBA extern int custom_aspect_ratio_mode; #define DEFAULT_INP_FILENAME "/dev_hdd0/game/FBAN00000/USRDIR/config/presets/default.ini" #define DEFAULT_NEO_INP_FILENAME "/dev_hdd0/game/FBAN00000/USRDIR/config/presets/default_neo.ini" #define DEFAULT_CPS_INP_FILENAME "/dev_hdd0/game/FBAN00000/USRDIR/config/presets/default_cps.ini" #define DEFAULT_MENU_BORDER_FILE "/dev_hdd0/game/FBAN00000/USRDIR/borders/Menu/main-menu.png" #define DEFAULT_MENU_SHADER_FILE "/dev_hdd0/game/FBAN00000/USRDIR/shaders/Borders/Menu/border-only.cg" #define GAME_INPUT_DIR "/dev_hdd0/game/FBAN00000/USRDIR/config/games/" #define SHADER_DIRECTORY "/dev_hdd0/game/FBAN00000/USRDIR/shaders/" #define DEFAULT_SHADER "/dev_hdd0/game/FBAN00000/USRDIR/shaders/stock.cg" #define SYS_CONFIG_FILE "/dev_hdd0/game/FBAN00000/USRDIR/fbanext-ps3.cfg" #define DAT_FILE "/dev_hdd0/game/FBAN00000/USRDIR/clrmame.dat" #define MULTIMAN_SELF "/dev_hdd0/game/BLES80608/USRDIR/RELOAD.SELF" #define PREVIEWS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/previews/" #define CHEATS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/cheats/" #define ROMS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/roms/" #define SAVESTATES_DIR "/dev_hdd0/game/FBAN00000/USRDIR/savestates/" //redundant #define SCREENSHOTS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/screenshots/" #define RECORDINGS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/recordings/" #define SKINS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/skins/" #define SCORES_DIR "/dev_hdd0/game/FBAN00000/USRDIR/scores/" #define SELECTS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/selects/" #define IPS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/ips/" #define TITLES_DIR "/dev_hdd0/game/FBAN00000/USRDIR/titles/" #define FLYERS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/flyers/" #define GAMEOVERS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/gameovers/" #define BOSSES_DIR "/dev_hdd0/game/FBAN00000/USRDIR/bosses/" #define ICONS_DIR "/dev_hdd0/game/FBAN00000/USRDIR/icons/" typedef std::basic_string<char> tstring; #ifndef MAX_PATH #define MAX_PATH (260) #endif // media.cpp #define InputInit() bInputOkay = true; #define InputExit() bInputOkay = false; #define mediaExit() \ nBurnSoundRate = 0; \ pBurnSoundOut = NULL; \ audio_exit(); \ VidExit(); \ InputExit(); // --------------------------------------------------------------------------- // from burn extern int bsavedecryptedcs; extern int bsavedecryptedps; extern int bsavedecrypteds1; extern int bsavedecryptedvs; extern int bsavedecryptedm1; extern int bsavedecryptedxor; extern int bsavedecryptedprom; // main.cpp extern int nLastFilter; extern int nLastRom; extern int nLastFilter; extern int HideChildren; extern int ThreeOrFourPlayerOnly; extern int CurrentFilter; extern int is_running; extern int nVidScrnAspectMode; extern int nVidOriginalScrnAspectX; extern int nVidOriginalScrnAspectY; // vid_psgl.cpp extern int nImageWidth, nImageHeight; extern uint32_t m_overscan; extern float m_overscan_amount; extern uint32_t m_viewport_x, m_viewport_y, m_viewport_width, m_viewport_height; extern uint32_t m_viewport_x_temp, m_viewport_y_temp, m_viewport_width_temp, m_viewport_height_temp, m_delta_temp; extern uint32_t currentAvailableResolutionId; extern uint32_t currentAvailableResolutionNo; extern void glSetViewports(); extern int FetchRoms(); typedef struct { int index; char filename[512]; char fullpath[1024]; } selected_shader_t; extern selected_shader_t selectedShader[2]; extern char szAppBurnVer[16]; extern char szSVNVer[16]; extern char szSVNDate[30]; int dprintf(char* pszFormat, ...); // Use instead of printf() in the UI // popup_win32.cpp enum FBAPopupType { MT_NONE = 0, MT_ERROR, MT_WARNING, MT_INFO }; #define PUF_TYPE_ERROR (1) #define PUF_TYPE_WARNING (2) #define PUF_TYPE_INFO (3) #define PUF_TYPE_LOGONLY (8) #define PUF_TEXT_TRANSLATE (1 << 16) #define PUF_TEXT_NO_TRANSLATE (0) #define PUF_TEXT_DEFAULT (PUF_TEXT_TRANSLATE) int FBAPopupDisplay(int nFlags); int FBAPopupAddText(int nFlags, char* pszFormat, ...); int FBAPopupDestroyText(); // misc_win32.cpp void pathCheck(char * path); int directLoadGame(const char * name); int findRom(int i, struct ArcEntry* list, int count); extern void setWindowAspect(bool first_boot); // drv.cpp extern int bDrvOkay; // 1 if the Driver has been inited okay, and it's okay to use the BurnDrv functions int BurnerDrvInit(int nDrvNum, bool bRestore); int DrvInitCallback(); // Used when Burn library needs to load a game. DrvInit(nBurnSelect, false) int BurnerDrvExit(); // run.cpp extern int nAppVirtualFps; // virtual fps extern bool bShowFPS; extern uint32_t bBurnFirstStartup; void RunIdle(); int RunMessageLoop(int argc, char ** argv); int RunExit(); // scrn.cpp extern int nWindowSize; extern int nWindowPosX, nWindowPosY; extern int nSavestateSlot; extern int nXOffset; extern int nYOffset; extern void UpdateConsoleXY(const char *text, float X, float Y); void simpleReinitScrn(void); // sel.cpp extern int nLoadMenuShowX; extern int nLoadDriverShowX; extern int nTabSel; extern char szUserFilterStr[MAX_PATH]; extern int nSystemSel; void clearNodeInfo(); // translist.cpp extern char szTransGamelistFile[MAX_PATH]; int loadGamelist(); int createGamelist(); char* mangleGamename(const char* pszOldName, bool bRemoveArticle = true); char* transGameName(const char* pszOldName, bool bRemoveArticle = true); // config.cpp extern int nIniVersion; int configAppLoadXml(); int configAppSaveXml(); // conc.cpp int configCheatLoad(const char* filename = NULL); int configCheatReload(const char* filename = NULL); // inpd.cpp int loadDefaultInput(); int SaveDefaultInput(); // inpcheat.cpp int InpCheatCreate(); #ifndef NO_CHEATSEARCH // cheatsearch.cpp int cheatSearchCreate(); void cheatSearchDestroy(); void updateCheatSearch(); #endif // inpdipsw.cpp void InpDIPSWResetDIPs(); int InpDIPSWCreate(); // inps.cpp extern unsigned int nInpsInput; // The input number we are redefining // inpc.cpp extern unsigned int nInpcInput; // The input number we are redefining int InpcCreate(); // stated.cpp extern int bDrvSaveAll; int StatedAuto(int bSave); int StatedLoad(int nSlot); int StatedSave(int nSlot); // roms.cpp extern bool avOk; extern bool bRescanRoms; int CreateROMInfo(); // miscpaths.cpp enum ePath { PATH_PREVIEW = 0, PATH_CHEAT, PATH_SCREENSHOT, PATH_SAVESTATE, PATH_RECORDING, PATH_SKIN, PATH_IPS, PATH_TITLE, PATH_FLYER, PATH_SCORE, PATH_SELECT, PATH_GAMEOVER, PATH_BOSS, PATH_ICON, PATH_SUM }; extern char szMiscPaths[PATH_SUM][MAX_PATH]; const char * getMiscPath(unsigned int dirType); const char * getMiscArchiveName(unsigned int dirType); extern char szAppRomPaths[DIRS_MAX][MAX_PATH]; // memcard.cpp extern int nMemoryCardStatus; // & 1 = file selected, & 2 = inserted int MemCardCreate(); int MemCardSelect(); int MemCardInsert(); int MemCardEject(); int MemCardToggle(); // progress.cpp int ProgressUpdateBurner(const char* pszText); int ProgressCreate(); int ProgressDestroy(); // ---------------------------------------------------------------------------- // Audit // State is non-zero if found. 1 = found totally okay #define STAT_NOFIND 0 #define STAT_OK 1 #define STAT_CRC 2 #define STAT_SMALL 3 #define STAT_LARGE 4 #define AUDIT_FAIL 0 #define AUDIT_PARTPASS 1 #define AUDIT_FULLPASS 3 int getAllRomsetInfo(); void auditPrepare(); int auditRomset(); void auditCleanup(); void initAuditState(); void resetAuditState(); void freeAuditState(); char getAuditState(const unsigned int& id); void setAuditState(const unsigned int& id, char ret); void DebugMsg(const char* format, ...); #endif
[ [ [ 1, 334 ] ] ]
029f8c16d7d6b354804f454f978b4cb67b93a142
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/Utils/_Ja25DutchText.cpp
1947d7465f6710d552b13c2d5f76da8b75d3c71f
[]
no_license
infernuslord/ja2
d5ac783931044e9b9311fc61629eb671f376d064
91f88d470e48e60ebfdb584c23cc9814f620ccee
refs/heads/master
2021-01-02T23:07:58.941216
2011-10-18T09:22:53
2011-10-18T09:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,856
cpp
// WANNE: Yes, this should be disabled, otherwise we get weird behavior when running the game with a VS 2005 build! //#pragma setlocale("DUTCH") #ifdef PRECOMPILEDHEADERS #include "Utils All.h" #include "_Ja25Dutchtext.h" #else #include "Language Defines.h" #ifdef DUTCH #include "text.h" #include "Fileman.h" #endif #endif //suppress : warning LNK4221: no public symbols found; archive member will be inaccessible void this_is_the_Ja25DutchText_public_symbol(void){;} #ifdef DUTCH // VERY TRUNCATED FILE COPIED FROM JA2.5 FOR ITS FEATURES FOR JA2 GOLD /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SANDRO - New STOMP laptop strings //these strings match up with the defines in IMP Skill trait.cpp STR16 gzIMPSkillTraitsText[]= { // made this more elegant L"Lock Picking", L"Hand to Hand", L"Electronics", L"Night Operations", L"Throwing", L"Teaching", L"Heavy Weapons", L"Auto Weapons", L"Stealth", L"Ambidextrous", L"Knifing", L"Sniper", L"Camouflaged", L"Martial Arts", L"None", L"I.M.P. Specialties", L"(Expert)", }; //added another set of skill texts for new major traits STR16 gzIMPSkillTraitsTextNewMajor[]= { L"Auto Weapons", L"Heavy Weapons", L"Marksman", L"Hunter", L"Gunslinger", L"Hand to Hand", L"Deputy", L"Technician", L"Paramedic", L"None", L"I.M.P. Major Traits", // second names L"Machinegunner", L"Bombardier", L"Sniper", L"Ranger", L"Gunfighter", L"Martial Arts", L"Squadleader", L"Engineer", L"Doctor", }; //added another set of skill texts for new minor traits STR16 gzIMPSkillTraitsTextNewMinor[]= { L"Ambidextrous", L"Melee", L"Throwing", L"Night Ops", L"Stealthy", L"Athletics", L"Bodybuilding", L"Demolitions", L"Teaching", L"Scouting", L"None", L"I.M.P. Minor Traits", }; //these texts are for help popup windows, describing trait properties STR16 gzIMPMajorTraitsHelpTextsAutoWeapons[]= { L"+%d%s Chance to Hit with Assault Rifles\n", L"+%d%s Chance to Hit with SMGs\n", L"+%d%s Chance to Hit with LMGs\n", L"-%d%s APs needed to fire with LMGs\n", L"-%d%s APs needed to ready light machine guns\n", L"Auto fire/burst chance to hit penalty is reduced by %d%s\n", L"Reduced chance for shooting unwanted bullets on autofire\n", }; STR16 gzIMPMajorTraitsHelpTextsHeavyWeapons[]= { L"-%d%s APs needed to fire grenade launchers\n", L"-%d%s APs needed to fire rocket launchers\n", L"+%d%s chance to hit with grenade launchers\n", L"+%d%s chance to hit with rocket launchers\n", L"-%d%s APs needed to fire mortar\n", L"Reduce penalty for mortar CtH by %d%s\n", L"+%d%s damage to tanks with heavy weapons, grenades and explosives\n", L"+%d%s damage to other targets with heavy weapons\n", }; STR16 gzIMPMajorTraitsHelpTextsSniper[]= { L"+%d%s Chance to Hit with Rifles\n", L"+%d%s Chance to Hit with Sniper Rifles\n", L"-%d%s effective range to target with all weapons\n", L"+%d%s aiming bonus per aim click (except for handguns)\n", L"+%d%s damage on shot", L" plus", L" per every aim click", L" after first", L" after second", L" after third", L" after fourth", L" after fifth", L" after sixth", L" after seventh", L"-%d%s APs needed to chamber a round with bolt-action rifles \n", L"Adds one more aim click for rifle-type guns\n", L"Adds %d more aim clicks for rifle-type guns\n", }; STR16 gzIMPMajorTraitsHelpTextsRanger[]= { L"+%d%s Chance to Hit with Rifles\n", L"+%d%s Chance to Hit with Shotguns\n", L"-%d%s APs needed to pump Shotguns\n", L"+%d%s group travelling speed between sectors if traveling by foot\n", L"+%d%s group travelling speed between sectors if traveling in vehicle (except helicopter)\n", L"-%d%s less energy spent for travelling between sectors\n", L"-%d%s weather penalties\n", L"+%d%s camouflage effectiveness\n", L"-%d%s worn out speed of camouflage by water or time\n", }; STR16 gzIMPMajorTraitsHelpTextsGunslinger[]= { L"-%d%s APs needed to fire with pistols and revolvers\n", L"+%d%s effective range with pistols and revolvers\n", L"+%d%s chance to hit with pistols and revolvers\n", L"+%d%s chance to hit with machine pistols", L" (on single shots only)", L"+%d%s aiming bonus per click with pistols, machine pistols and revolvers\n", L"-%d%s APs needed to raise pistols and revolvers\n", L"-%d%s APs needed to reload pistols, machine pistols and revolvers\n", L"Adds %d more aim click for pistols, machine pistols and revolvers\n", L"Adds %d more aim clicks for pistols, machine pistols and revolvers\n", }; STR16 gzIMPMajorTraitsHelpTextsMartialArts[]= { L"-%d%s AP cost of hand to hand attacks(bare hands or with brass knuckles)\n", L"+%d%s chance to hit with hand to hand attacks with bare hands\n", L"+%d%s chance to hit with hand to hand attacks with brass knuckles\n", L"+%d%s damage of hand to hand attacks(bare hands or with brass knuckles)\n", L"+%d%s breath damage of hand to hand attacks(bare hands or with brass knuckles)\n", L"Enemy knocked out due to your HtH attacks takes slightly longer to recuperate\n", L"Enemy knocked out due to your HtH attacks takes longer to recuperate\n", L"Enemy knocked out due to your HtH attacks takes much longer to recuperate\n", L"Enemy knocked out due to your HtH attacks takes very long to recuperate\n", L"Enemy knocked out due to your HtH attacks takes extremely long to recuperate\n", L"Enemy knocked out due to your HtH attacks takes long hours to recuperate\n", L"Enemy knocked out due to your HtH attacks probably never stand up\n", L"Focused (aimed) punch deals +%d%s more damage\n", L"Your special spinning kick deals +%d%s more damage\n", L"+%d%s change to dodge hand to hand attacks\n", L"+%d%s on top chance to dodge HtH attacks with bare hands", L" or brass knuckles", L" (+%d%s with brass knuckles)", L"+%d%s on top chance to dodge HtH attacks with brass knuckles\n", L"+%d%s chance to dodge attacks by any melee weapon\n", L"-%d%s APs needed to steal weapon from enemy hands\n", L"-%d%s APs needed to change state (stand, crouch, lie down), turn around, climb on/off roof and jump obstacles\n", L"-%d%s APs needed to change state (stand, crouch, lie down)\n", L"-%d%s APs needed to turn around\n", L"-%d%s APs needed to climb on/off roof and jump obstacles\n", L"+%d%s chance to kick doors\n", L"You gain special animations for hand to hand combat\n", }; STR16 gzIMPMajorTraitsHelpTextsSquadleader[]= { L"+%d%s APs per round of other mercs in vicinity\n", L"+%d effective exp level of other mercs in vicinity, which have lesser level than the %s\n", L"+%d effective exp level to count as a standby when counting friends' bonus for suppression\n", L"+%d%s total suppression tolerance of other mercs in vicinity and %s himself\n", L"+%d morale gain of other mercs in vicinity\n", L"-%d morale loss of other mercs in vicinity\n", L"The vicinity for bonuses is %d tiles", L" (%d tiles with extended ears)", L"(Max simultaneous bonuses for one soldier is %d)\n", L"+%d%s fear resistence of %s\n", L"Drawback: %dx morale loss for %s's death for all other mercs\n", }; STR16 gzIMPMajorTraitsHelpTextsTechnician[]= { L"+%d%s to repairing speed\n", L"+%d%s to lockpicking (normal/electronic locks)\n", L"+%d%s to disarming electronic traps\n", L"+%d%s to attaching special items and combining things\n", L"+%d%s to unjamming a gun in combat\n", L"Reduce penalty to repair electronic items by %d%s\n", L"Increased chance to detect traps and mines (+%d detect level)\n", L"+%d%s CtH of robot controlled by the %s\n", L"%s trait grants you the ability to repair the robot\n", L"Reduced penalty to repair speed of the robot by %d%s\n", }; STR16 gzIMPMajorTraitsHelpTextsDoctor[]= { L"Has ability to make surgical intervention by using medical bag on wounded soldier\n", L"Surgery instantly returns %d%s of lost health back.", L" (This drains the medical bag a lot.)", L"Can heal lost stats (from critical hits) by the", L" surgery or", L" doctor assignment.\n", L"+%d%s effectiveness on doctor-patient assignment\n", L"+%d%s bandaging speed\n", L"+%d%s natural regeneration speed of all soldiers in the same sector", L" (max %d these bonuses per sector)", }; STR16 gzIMPMajorTraitsHelpTextsNone[]= { L"No bonuses", }; STR16 gzIMPMinorTraitsHelpTextsAmbidextrous[]= { L"Reduce penalty to shoot dual weapons by %d%s\n", L"+%d%s speed of reloading guns with magazines\n", L"+%d%s speed of reloading guns with loose rounds\n", L"-%d%s APs needed to pickup items\n", L"-%d%s APs needed to work backpack\n", L"-%d%s APs needed to handle doors\n", L"-%d%s APs needed to plant/remove bombs and mines\n", L"-%d%s APs needed to attach items\n", }; STR16 gzIMPMinorTraitsHelpTextsMelee[]= { L"-%d%s APs needed to attack by blades\n", L"+%d%s chance to hit with blades\n", L"+%d%s chance to hit with blunt melee weapons\n", L"+%d%s damage of blades\n", L"+%d%s damage of blunt melee weapons\n", L"Aimed attack by any melee weapon deals +%d%s damage\n", L"+%d%s chance to dodge attack by melee blades\n", L"+%d%s on top chance to dodge melee blades if having a blade in hands\n", L"+%d%s chance to dodge attack by blunt melee weapons\n", L"+%d%s on top chance to dodge blunt melee weapons if having a blade in hands\n", }; STR16 gzIMPMinorTraitsHelpTextsThrowing[]= { L"-%d%s basic APs needed to throw blades\n", L"+%d%s max range when throwing blades\n", L"+%d%s chance to hit when throwing blades\n", L"+%d%s chance to hit when throwing blades per aim click\n", L"+%d%s damage of throwing blades\n", L"+%d%s damage of throwing blades per aim click\n", L"+%d%s chance to inflict critical hit by throwing blade if not seen or heard\n", L"+%d critical hit by throwing blade multiplier\n", L"Adds %d more aim click for throwing blades\n", L"Adds %d more aim clicks for throwing blades\n", }; STR16 gzIMPMinorTraitsHelpTextsNightOps[]= { L"+%d to effective sight range in dark\n", L"+%d to general effective hearing range\n", L"+%d to effective hearing range in dark on top\n", L"+%d to interrupts modifier in dark\n", L"-%d need to sleep\n", }; STR16 gzIMPMinorTraitsHelpTextsStealthy[]= { L"-%d%s APs needed to move quietly\n", L"+%d%s chance to move quietly\n", L"+%d%s stealth (being 'invisible' if unnoticed)\n", L"Reduced cover penalty for movement by %d%s\n", }; STR16 gzIMPMinorTraitsHelpTextsAthletics[]= { L"-%d%s APs needed for moving (running, walking, swatting, crawling, swimming, etc.)\n", L"-%d%s energy spent for movement, roof-climbing, obstacle-jumping, swimming, etc.\n", }; STR16 gzIMPMinorTraitsHelpTextsBodybuilding[]= { L"Has %d%s damage resistance\n", L"+%d%s effective strength for carrying weight capacity \n", L"Reduced energy lost when hit by HtH attack by %d%s\n", L"Increased damage needed to fall down if hit to legs by %d%s\n", }; STR16 gzIMPMinorTraitsHelpTextsDemolitions[]= { L"-%d%s APs needed to throw grenades\n", L"+%d%s max range when throwing grenades\n", L"+%d%s chance to hit when throwing grenades\n", L"+%d%s damage of set bombs and mines\n", L"+%d%s to attaching detonators check\n", L"+%d%s to planting/removing bombs check\n", L"Decreases chance enemy will detect your bombs and mines (+%d bomb level)\n", L"Increased chance shaped charge will open the doors (damage multiplied by %d)\n", }; STR16 gzIMPMinorTraitsHelpTextsTeaching[]= { L"+%d%s bonus to train militia\n", L"+%d%s bonus to effective leadership for determining militia training\n", L"+%d%s bonus to teaching other mercs\n", L"Skill value counts to be +%d higher for being able to teach this skill to other mercs\n", L"+%d%s bonus to train stats through self-practising assignment\n", }; STR16 gzIMPMinorTraitsHelpTextsScouting[]= { L"+%d to effective sight range with scopes on weapons\n", L"+%d to effective sight range with binoculars (and scopes separated from weapons)\n", L"-%d tunnel vision with binoculars (and scopes separated from weapons)\n", L"If in sector, adjacent sectors will show exact number of enemies\n", L"If in sector, adjacent sectors will show presence of enemies if any\n", L"Prevents the enemy to ambush your squad\n", L"Prevents the bloodcats to ambush your squad\n", }; STR16 gzIMPMinorTraitsHelpTextsNone[]= { L"No bonuses", }; STR16 gzIMPOldSkillTraitsHelpTexts[]= { L"+%d%s bonus to lockpicking\n", // 0 L"+%d%s hand to hand chance to hit\n", L"+%d%s hand to hand damage\n", L"+%d%s chance to dodge hand to hand attacks\n", L"Eliminates the penalty to repair and handle\nelectronic things (locks, traps, rem. detonators, robot, etc.)\n", L"+%d to effective sight range in dark\n", L"+%d to general effective hearing range\n", L"+%d to effective hearing range in dark on top\n", L"+%d to interrupts modifier in dark\n", L"-%d need to sleep\n", L"+%d%s max range when throwing anything\n", // 10 L"+%d%s chance to hit when throwing anything\n", L"+%d%s chance to instantly kill by throwing knife if not seen or heard\n", L"+%d%s bonus to train militia and instruct other mercs\n", L"+%d%s effective leadership for militia training calculations\n", L"+%d%s chance to hit with rocket/greande launchers and mortar\n", L"Auto fire/burst chance to hit penalty is divided by %d\n", L"Reduced chance for shooting unwanted bullets on autofire\n", L"+%d%s chance to move quietly\n", L"+%d%s stealth (being 'invisible' if unnoticed)\n", L"Eliminates the CtH penalty for second hand when firing two weapons at once\n", // 20 L"+%d%s chance to hit with melee blades\n", L"+%d%s chance to dodge attacks by melee blades if having blade in hands\n", L"+%d%s chance to dodge attacks by melee blades if having anything else in hands\n", L"+%d%s chance to dodge hand to hand attacks if having blade in hands\n", L"-%d%s effective range to target with all weapons\n", L"+%d%s aiming bonus per aim click\n", L"Provides permanent camouflage\n", L"+%d%s hand to hand chance to hit\n", L"+%d%s hand to hand damage\n", L"+%d%s chance to dodge hand to hand attacks if having empty hands\n", // 30 L"+%d%s chance to dodge hand to hand attacks if not having empty hands\n", L"+%d%s chance to dodge attacks by melee blades\n", L"Can perform spinning kick attack on weakened enemies to deal double damage\n", L"You gain special animations for hand to hand combat\n", L"No bonuses", }; STR16 gzIMPNewCharacterTraitsHelpTexts[]= { L"A: No advantage.\nD: No disadvantage.", L"A: Has better performance when a couple of mercs are nearby.\nD: Gains no morale when no other merc is nearby.", L"A: Has better performance when no other merc is nearby.\nD: Gains no morale when in a group.", L"A: His morale sinks a little slower and grows faster than normal.\nD: Has lesser chance to detect traps and mines.", L"A: Has bonus on training militia and is better at communication with people.\nD: Gains no morale for actions of other mercs.", L"A: Slightly faster learning when assigned on practicing or as a student.\nD: Has lesser suppression and fear resistance.", L"A: His energy goes down a bit slower except on assignments such as doctor, repairman, militia trainer or if learning certain skills.\nD: His wisdom, leadership, explosives, mechanical and medical skills improve slightly slower.", L"A: Has slightly better chance to hit on burst/autofire and inflicts slightly bigger damage in close combat\n Gains a little more morale for killing.\nD: Has penalty for actions which need patience like repairing items, picking locks, removing traps, doctoring, training militia.", L"A: Has bonus for actions which need patience like repairing items, picking locks, removing traps, doctoring and training militia.\nD: His interrupt chance is slightly lowered.", L"A: Increased resistance to suppression and fear.\n Morale loss for taking damage and companions deaths is lower for him.\nD: Can be hit easier and enemy penalty for moving target is lesser in his case.", L"A: He gains morale when on non-combat assignments (except training militia).\nD: Gains no morale for killing.", L"A: Has greater chance of inflicting stat loss, which may also inflict special painful wounds.\n Gains bonus morale for inflicting stat loss.\nD: Has penalty for communication with people and his morale sinks faster if not fighting.", L"A: Has better performance when there are some mercs of opposite gender nearby.\nD: Morale of other mercs of the same gender grows slower if nearby.", }; STR16 gzIMPDisabilitiesHelpTexts[]= { L"No effects.", L"Has problems with breathing and reduced overall performance if in tropical or desert sectors.", L"Can suffer panic attack if left alone in certain situations.", L"His overall performance is reduced if underground.", L"If trying to swim he can easily drown.", L"A look at large insects can cause big problems\nand being in tropical sectors also reduce his performance a bit.", L"Sometimes forgets what orders he got and therefore loses some APs if in combat.", L"He can go psycho and shoot like mad once in a while\nand can lose morale if unable to do so with given weapon.", }; STR16 gzIMPProfileCostText[]= { L"The profile cost is %d$. Do you authorize the payment? ", }; STR16 zGioNewTraitsImpossibleText[]= { L"You cannot choose the New Trait System with PROFEX utility deactivated. Check your JA2_Options.ini for entry: READ_PROFILE_DATA_FROM_XML.", }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //@@@: New string as of March 3, 2000. STR16 gzIronManModeWarningText[]= { L"You have chosen IRON MAN mode. This setting makes the game considerably more challenging as you will not be able to save your game when in a sector occupied by enemies. This setting will affect the entire course of the game. Are you sure want to play in IRON MAN mode?", }; STR16 gzDisplayCoverText[]= { L"Cover: %d/100 %s, Brightness: %d/100", L"Gun Range: %d/%d tiles, Chance to hit: %d/100", L"Gun Range: %d/%d tiles, Muzzle Stability: %d/100", L"Disabling cover display", L"Showing mercenary view", L"Showing danger zones for mercenary", L"Wood", // wanted to use jungle , but wood is shorter in german too (dschungel vs wald) L"Urban", L"Desert", L"Snow", // NOT USED!!! L"Wood and Desert", L"" // yes empty for now }; #endif
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 457 ] ] ]
9cee1729ec74c0597ef4e48528697d4e38aaf2bc
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/MapLib/Shared/src/SFDIndexor.cpp
50243004f0c37101c2f39db9296551697e5df897
[ "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
2,379
cpp
/* 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. */ #include "config.h" #include <string.h> #include <algorithm> #include "SFDIndexor.h" bool SFDIndexor::operator<( const char* other ) const { return strcmp( getStr(), other ) < 0; } bool SFDIndexor::operator<( const SFDIndexor& other ) const { return *this < other.getStr(); } bool SFDIndexor::operator<( const MC2SimpleString& other ) const { return *this < other.c_str(); } bool operator<( const MC2SimpleString& str1, const SFDIndexor& str2 ) { return str1 < str2.getStr(); } void SFDIndexor::swap( SFDIndexor& other ) { std::swap( m_str, other.m_str ); std::swap( m_strNbr, other.m_strNbr ); std::swap( m_strOffset, other.m_strOffset ); std::swap( m_strAllocSize, other.m_strAllocSize ); std::swap( m_stringRead, other.m_stringRead ); }
[ [ [ 1, 55 ] ] ]
44e013382102ae76c357d839ad12dd8d221b4003
33d2272f0af4d08cb3b20e81f2ece571b2c7e131
/HeadDetect/HeadDetect/Gauss.h
9ac728621f166ea69e6f6231378401d0d0e0a3d1
[]
no_license
mscreolo/huy-khanh-people-counting
776b66e44b7881d1dc9a24b0d4b9361e99aa30ca
5875d54e28eb86b8f127e1fc94c61cb7795c7bdf
refs/heads/master
2016-09-15T20:43:32.200996
2011-10-26T03:07:40
2011-10-26T03:07:40
33,321,132
0
0
null
null
null
null
UTF-8
C++
false
false
986
h
#include "cv.h" #include "highgui.h" #include <fstream> using namespace std; //#define PI 3.14 #pragma once class Gauss { public: double InvCov[2][2]; double sub[3]; double rsl[3]; double b; double phi; double logOfSqrt2PiVariance; double threshold; CvMat* mean; CvMat* corrvariant; void TrainData(char *prefix, char *suffix, int number_images, int start_index, int end_index, char* fileOutput); void LoadData(char* fileOutput); //IplImage* Classify(IplImage *imgColor, IplImage *mask); IplImage* Classify(IplImage *imgColor, float thresh); IplImage* Classify(IplImage *imgColor); void SetThreshold(double threshold); CvScalar getPixalValue(IplImage* img, int x, int y, int channels) { CvScalar rtValue; uchar* ptrSrc = (uchar*) (img->imageData + y * img->widthStep + x * channels); for (int i=0; i < channels; i++) { rtValue.val[i] = ptrSrc[i]; } return rtValue; } Gauss(void); ~Gauss(void); };
[ "[email protected]@ead409af-2641-a09c-7308-cf4d77c96f99" ]
[ [ [ 1, 46 ] ] ]
eade1e16789c58963a3a1e3121c234c4d29c80a4
b22c254d7670522ec2caa61c998f8741b1da9388
/shared/ClientObject.cpp
868209ee4559c88407a6907ff16842f08c37f9be
[]
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
12,069
cpp
/* ------------------------[ 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/>. ----------------------------------------------------------------------------- */ #include <zoidcom.h> #include "ClientObject.h" #include "LogHandler.h" // declare static member ZCom_ClassID ClientObject::m_classid = ZCom_Invalid_ID; /************************************************************************/ /* register this class /************************************************************************/ void ClientObject::registerClass(ZCom_Control *_control) { m_classid = _control->ZCom_registerClass("ClientObject", ZCOM_CLASSFLAG_ANNOUNCEDATA); } /************************************************************************/ /* constructor /************************************************************************/ ClientObject::ClientObject(ZCom_Control *_control, unsigned int id, const std::string & name, const std::string & status, const std::string & namecolor, ClientListHandlerBase* clH, ChatSubscriberBase* WorldSubscriber, DatabaseHandlerBase * dbH, long playerdbid) : m_id(id), m_name(name), m_status(status), m_namecolor(namecolor), m_clH(clH), m_WorldSubscriber(WorldSubscriber), m_dbH(dbH), m_playerdbid(playerdbid) { #ifndef _ZOID_USED_NEW_VERSION_ m_node->registerNodeDynamic(m_classid, _control); #else _control->ZCom_registerDynamicNode( m_node, m_classid ); #endif #ifdef _DEBUG std::stringstream strs; strs<<"New Node "<<GetObjectName()<<" of id "<<m_id; LogHandler::getInstance()->LogToFile(strs.str(), 2); #endif //reset announcement data ResetAnnouncement(); if(m_clH) m_clH->Connected(m_id, m_name, m_status, m_namecolor); } /************************************************************************/ /* used to reset announcement data /************************************************************************/ void ClientObject::ResetAnnouncement() { ZCom_BitStream *adata = new ZCom_BitStream(); adata->addInt(m_id, 32); adata->addString(m_name.c_str()); adata->addString(m_status.c_str()); adata->addString(m_namecolor.c_str()); m_node->setAnnounceData(adata); } /************************************************************************/ /* destructor /************************************************************************/ ClientObject::~ClientObject() { #ifdef _DEBUG std::stringstream strs; strs<<"Deleted Node "<<GetObjectName()<<" of id "<<m_id; LogHandler::getInstance()->LogToFile(strs.str(), 2); #endif if(m_clH) m_clH->Disconnected(m_id); } /************************************************************************/ /* handle user event /************************************************************************/ void ClientObject::HandleUserEvent(ZCom_BitStream * data, eZCom_NodeRole remoterole, unsigned int eventconnid, unsigned int _estimated_time_sent) { // type of custom event is in the first 2 bits of the event unsigned int etype = data->getInt(3); switch(etype) { //subscribe event case 0: { // if coming from owner to server if(remoterole == eZCom_RoleOwner) { // get status char buf[255]; data->getString(buf, 255); m_status = buf; //reset announcement data ResetAnnouncement(); //send to all ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(0, 3); evt->addString(m_status.c_str()); m_node->sendEvent(eZCom_ReliableUnordered, ZCOM_REPRULE_AUTH_2_ALL, evt); } // if coming from server to all if(remoterole == eZCom_RoleAuthority) { // get status char buf[255]; data->getString(buf, 255); m_status = buf; m_clH->ChangedStatus(m_id, m_status, m_namecolor); } } break; //unsubscribe event case 1: { // if coming from owner to server if(remoterole == eZCom_RoleOwner) { // get color char buf[255]; data->getString(buf, 255); m_namecolor = buf; //reset announcement data ResetAnnouncement(); //send to all ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(1, 3); evt->addString(m_namecolor.c_str()); m_node->sendEvent(eZCom_ReliableUnordered, ZCOM_REPRULE_AUTH_2_ALL, evt); } // if coming from server to all if(remoterole == eZCom_RoleAuthority) { // get color char buf[255]; data->getString(buf, 255); m_namecolor = buf; m_clH->ChangedStatus(m_id, m_status, m_namecolor); } } break; //text event from client case 2: { // if event comes from the owner client if(remoterole == eZCom_RoleOwner) { // 0 if text is complete - 1 if we expect more unsigned int textform = data->getInt(1); // check who to send the text to unsigned int sendto = data->getInt(32); // get text unsigned short sizes = data->getStringLength()+1; char *buf = new char[sizes]; data->getString(buf, sizes); #ifdef _DEBUG std::stringstream strs; strs<<"Machine "<<eventconnid<<" sent "<<buf; LogHandler::getInstance()->LogToFile(strs.str()); #endif //send to concerned person ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(2, 3); evt->addInt(textform, 1); evt->addString(buf); m_node->sendEventDirect(eZCom_ReliableOrdered, evt, sendto); delete buf; } // if event comes from the server if(remoterole == eZCom_RoleAuthority) { // 0 if text is complete - 1 if we expect more unsigned int textform = data->getInt(1); // get text unsigned short sizes = data->getStringLength()+1; char *buf = new char[sizes]; data->getString(buf, sizes); #ifdef _DEBUG std::stringstream strs; strs<<"Server "<<eventconnid<<" sent "<<buf<<" from "<<m_clH->GetName(m_id); LogHandler::getInstance()->LogToFile(strs.str()); #endif // addtextpart _tmpstring[m_id].append(buf); // if end of text if(textform == 0) { //publish text to all subscribers m_WorldSubscriber->ReceivedText("All", "from " + m_clH->GetName(m_id), _tmpstring[m_id]); //clear the string _tmpstring[m_id].clear(); } delete buf; } } break; //add friend event case 3: { // if coming from owner to server if(remoterole == eZCom_RoleOwner) { // get friend name char buf[255]; data->getString(buf, 255); if(m_dbH) m_dbH->AddFriend(m_playerdbid, buf); } } break; //remove friend event case 4: { // if coming from owner to server if(remoterole == eZCom_RoleOwner) { // get friend name char buf[255]; data->getString(buf, 255); if(m_dbH) m_dbH->RemoveFriend(m_playerdbid, buf); } } //friends list request case 5: { // if coming from owner to server if(remoterole == eZCom_RoleOwner) { if(m_dbH) { std::vector<std::string> friends = m_dbH->GetFriends(m_playerdbid); //send message to client for each friends for(size_t i=0; i<friends.size(); ++i) { ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(6, 3); evt->addString(friends[i].c_str()); m_node->sendEventDirect(eZCom_ReliableUnordered, evt, eventconnid); } } } } //received friend name from server case 6: { // if coming from owner to server if(remoterole == eZCom_RoleAuthority) { // get friend name char buf[255]; data->getString(buf, 255); m_clH->NewFriend(buf); } } break; } } /************************************************************************/ /* change player status /************************************************************************/ void ClientObject::ChangeStatus(const std::string & status) { ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(0, 3); evt->addString(status.c_str()); m_node->sendEvent(eZCom_ReliableUnordered, ZCOM_REPRULE_OWNER_2_AUTH, evt); } /************************************************************************/ /* change player color /************************************************************************/ void ClientObject::ChangeColor(const std::string & color) { ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(1, 3); evt->addString(color.c_str()); m_node->sendEvent(eZCom_ReliableUnordered, ZCOM_REPRULE_OWNER_2_AUTH, evt); } /************************************************************************/ /* whisper to someone /************************************************************************/ bool ClientObject::Whisper(const std::string & playername, std::string text) { unsigned int id = m_clH->GetId(playername); if(id == 0) return false; //send part of the string text while(text.length() > _MAX_CHAR_SIZE_) { std::string Textpart = text.substr(0, _MAX_CHAR_SIZE_); text = text.substr(_MAX_CHAR_SIZE_); ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(2, 3); evt->addInt(1, 1); evt->addInt(id, 32); evt->addString(Textpart.c_str()); m_node->sendEvent(eZCom_ReliableOrdered, ZCOM_REPRULE_OWNER_2_AUTH, evt); } // send last part of the text ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(2, 3); evt->addInt(0, 1); evt->addInt(id, 32); evt->addString(text.c_str()); m_node->sendEvent(eZCom_ReliableOrdered, ZCOM_REPRULE_OWNER_2_AUTH, evt); return true; } /************************************************************************/ /* add friend to friend list /************************************************************************/ void ClientObject::AddFriend(const std::string & name) { ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(3, 3); evt->addString(name.c_str()); m_node->sendEvent(eZCom_ReliableUnordered, ZCOM_REPRULE_OWNER_2_AUTH, evt); } /************************************************************************/ /* remove friend from friend list /************************************************************************/ void ClientObject::RemoveFriend(const std::string & name) { ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(4, 3); evt->addString(name.c_str()); m_node->sendEvent(eZCom_ReliableUnordered, ZCOM_REPRULE_OWNER_2_AUTH, evt); } /************************************************************************/ /* ask server for friend list /************************************************************************/ void ClientObject::GetFriendList() { ZCom_BitStream *evt = new ZCom_BitStream(); evt->addInt(5, 3); m_node->sendEvent(eZCom_ReliableUnordered, ZCOM_REPRULE_OWNER_2_AUTH, evt); }
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 423 ] ] ]
437b20a835422b627fb122877b44a2cc8a5f770a
37b093a477029397fda72f643bd266ca5327b763
/server/src/eArticleParser.h
9baaf2eccb1d297d13c5f3bf679fe4e375b7efd6
[]
no_license
pablorusso/breader
9f9c9527f88c06a58fa10b3deb1dc2df7f30ec7f
5c34e5c41b287d43d97612bc53a32ba1a6b83687
refs/heads/master
2018-12-31T15:50:47.173860
2007-07-13T21:48:11
2007-07-13T21:48:11
32,188,644
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
h
#ifndef E_ARTICLE_PARSER #define E_ARTICLE_PARSER #include "IException.h" typedef enum {SW_ARCHIVO_CORRUPTO,} AP_error; class eArticleParser : public std::exception::exception, public IException { private: AP_error errnumber; //!< El numero de error que arrojo la excepcion public: /** * Constructor de la excepcion * @param e el numero de error * @param l la linea * @param f el archivo */ eArticleParser (AP_error e, unsigned int l, std::string f) :IException(l, f), errnumber(e) {} /** * Destructor default */ ~eArticleParser () throw() {} /** * Metodo sobrecargado de la clase exeption * @return una secuencia de chars terminada en NULL con una descripcion * del error */ const char *what() const throw() { switch(errnumber){ case SW_ARCHIVO_CORRUPTO: { return "Archivo de stopwords corrupto"; break; } default: { return "Error inesperado"; break; } } } /** * @see IException#getErrorMensaje() */ virtual std::string getErrorMensaje(){ std::string msg(this->what()); msg.append(" "); msg.append(this->where()); return msg; } }; #endif
[ "dalef84@1b01bc9b-1c2c-0410-9f71-9794c14141d8" ]
[ [ [ 1, 57 ] ] ]
e20fa40ec7e9fa0875b6dad4b67fd00013e3e025
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/config/test/has_tr1_type_traits_pass.cpp
58602c1126e1f5b76ea066ff36e0a39be0fdbee6
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,059
cpp
// This file was automatically generated on Tue Feb 15 17:34:12 2005 // by libs/config/tools/generate.cpp // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for the most recent version. // Test file for macro BOOST_HAS_TR1_TYPE_TRAITS // This file should compile, if it does not then // BOOST_HAS_TR1_TYPE_TRAITS should not be defined. // See file boost_has_tr1_type_traits.ipp for details // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifdef BOOST_HAS_TR1_TYPE_TRAITS #include "boost_has_tr1_type_traits.ipp" #else namespace boost_has_tr1_type_traits = empty_boost; #endif int main( int, char *[] ) { return boost_has_tr1_type_traits::test(); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 34 ] ] ]
ece4434a40a0d3a450ee48510976a22fba8da106
2e5fd1fc05c0d3b28f64abc99f358145c3ddd658
/deps/quickfix/examples/ordermatch/test/TestSuite.h
31b9847fa0b892201f3405618e2f3610e78bcb21
[ "BSD-2-Clause" ]
permissive
indraj/fixfeed
9365c51e2b622eaff4ce5fac5b86bea86415c1e4
5ea71aab502c459da61862eaea2b78859b0c3ab3
refs/heads/master
2020-12-25T10:41:39.427032
2011-02-15T13:38:34
2011-02-15T20:50:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,166
h
/* -*- C++ -*- */ /**************************************************************************** ** Copyright (c) quickfixengine.org All rights reserved. ** ** This file is part of the QuickFIX FIX Engine ** ** This file may be distributed under the terms of the quickfixengine.org ** license as defined by quickfixengine.org and appearing in the file ** LICENSE included in the packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.quickfixengine.org/LICENSE for licensing information. ** ** Contact [email protected] if any conditions of this licensing are ** not clear to you. ** ****************************************************************************/ #include <CPPTest/TestSuite.h> #include <CPPTest/TestDisplay.h> #include "OrderMatcherTestCase.h" class TestSuite : public CPPTest::TestSuite { public: TestSuite(CPPTest::TestDisplay& display) : CPPTest::TestSuite(display) { add( &m_orderMatcher ); } private: OrderMatcherTestCase m_orderMatcher; };
[ [ [ 1, 37 ] ] ]
3923cf676f994e2141689fefc95455ea859bc328
a30b091525dc3f07cd7e12c80b8d168a0ee4f808
/EngineAll/Complex Mesh/ComplexMesh.cpp
210dd7a6f01a1d9d3aa7a994abb6b31227259fb5
[]
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
32,921
cpp
/* ComplexMesh.cpp Written by Matthew Fisher ComplexMesh is a complex (edge-based) mesh structure. */ #include "..\\..\\Main.h" #include "ComplexMesh.h" HalfEdge HalfEdge::Invalid; FullEdge FullEdge::Invalid; Triangle Triangle::Invalid; Vertex Vertex::Invalid; Triangle Triangle::Boundary; FullEdge FullEdge::NotFound; ComplexMesh::ComplexMesh() { } ComplexMesh::~ComplexMesh() { FreeMemory(); } ComplexMesh::ComplexMesh(const ComplexMesh &M) { Mesh MTemp; M.Dump(MTemp); Load(MTemp); } void ComplexMesh::FreeMemory() { _Vertices.FreeMemory(); _Triangles.FreeMemory(); _HalfEdges.FreeMemory(); for(UINT i = 0; i < _FullEdges.Length(); i++) { delete _FullEdges[i]; } _FullEdges.FreeMemory(); ClearHashTable(); } ComplexMesh& ComplexMesh::operator = (const ComplexMesh &M) { Mesh MTemp; M.Dump(MTemp); Load(MTemp); return *this; } bool ComplexMesh::ShootRay(const D3D9Mesh &M, const Vec3f &Pos, const Vec3f &Dir, UINT &TriangleIndex, UINT &VertexIndex, UINT &EdgeIndex, Vec3f &WorldPos) const { #ifdef USE_D3D9 Vector<float> Hits; Vec3f NormalizedDir = Vec3f::Normalize(Dir); float u, v; DWORD FaceIndex; M.QueryHits(Pos, NormalizedDir, Hits, FaceIndex, u, v); if(Hits.Length() > 0) { TriangleIndex = FaceIndex; WorldPos = Pos + NormalizedDir * Hits[0]; float ClosestVertexDistance = 1e10f, ClosestEdgeDistance = 1e10f; const Triangle &CurTriangle = _Triangles[TriangleIndex]; for(UINT LocalIndex = 0; LocalIndex < 3; LocalIndex++) { float CurVertexDistance = Vec3f::Dist(CurTriangle.GetVertex(LocalIndex).Pos(), WorldPos); if(CurVertexDistance < ClosestVertexDistance) { ClosestVertexDistance = CurVertexDistance; VertexIndex = CurTriangle.GetVertex(LocalIndex).Index(); } float CurEdgeDistance = Vec3f::Dist(CurTriangle.GetFullEdge(LocalIndex).Center(), WorldPos); if(CurEdgeDistance < ClosestEdgeDistance) { ClosestEdgeDistance = CurEdgeDistance; EdgeIndex = CurTriangle.GetFullEdge(LocalIndex).Index(); } } return true; } else { VertexIndex = _Vertices.Length(); EdgeIndex = _FullEdges.Length(); TriangleIndex = _Triangles.Length(); return false; } #else SignalError("DirectX 9 required for ComplexMesh::ShootRay"); return false; #endif } float ComplexMesh::AverageEdgeLength() const { float Avg = 0.0f; for(UINT EdgeIndex = 0; EdgeIndex < _FullEdges.Length(); EdgeIndex++) { Avg += _FullEdges[EdgeIndex]->Vector().Length(); } return Avg / _FullEdges.Length(); } float ComplexMesh::AverageTriangleArea() const { float Avg = 0.0f; for(UINT TriangleIndex = 0; TriangleIndex < _Triangles.Length(); TriangleIndex++) { Avg += _Triangles[TriangleIndex].Area(); } return Avg / _Triangles.Length(); } void ComplexMesh::ValidateTopology() { for(UINT TriangleIndex = 0; TriangleIndex < _Triangles.Length(); TriangleIndex++) { Triangle &CurTriangle = _Triangles[TriangleIndex]; for(UINT i = 0; i < 3; i++) { PersistentAssert(CurTriangle.GetHalfEdge(i).NextEdge() == CurTriangle.GetHalfEdge((i + 1) % 3), "Invalid topology"); PersistentAssert(CurTriangle.GetHalfEdge(i).AcrossEdge() == CurTriangle.GetFullEdge(i), "Invalid topology"); } } } void ComplexMesh::VerboseSave(const String &Filename) { ofstream File(Filename.CString()); File << "Triangle Count: " << _Triangles.Length() << endl; File << "Index\tEdges\t\t\tVertices\t\t\t\n"; for(UINT TriangleIndex = 0; TriangleIndex < _Triangles.Length(); TriangleIndex++) { Triangle &CurTriangle = _Triangles[TriangleIndex]; File << TriangleIndex << '\t'; for(UINT i = 0; i < 3; i++) { File << CurTriangle.GetHalfEdge(i).AcrossEdge().Index() << '\t'; } for(UINT i = 0; i < 3; i++) { File << CurTriangle.GetVertex(i).Index() << '\t'; } File << endl; } File << "Edge Count: " << _FullEdges.Length() << endl; File << "Index\tTriangles\t\tVertices\t\t\n"; for(UINT EdgeIndex = 0; EdgeIndex < _FullEdges.Length(); EdgeIndex++) { FullEdge &CurEdge = *(_FullEdges[EdgeIndex]); File << EdgeIndex << '\t'; for(UINT i = 0; i < 2; i++) { if(CurEdge.GetTriangle(i) == Triangle::Boundary) { File << "Boundary" << '\t'; } else { File << CurEdge.GetTriangle(i).Index() << '\t'; } } for(UINT i = 0; i < 2; i++) { File << CurEdge.GetVertex(i).Index() << '\t'; } File << endl; } } bool ComplexMesh::ComputeDiskBoundary(Vector<FullEdge *> &Boundary) { Boundary.FreeMemory(); FullEdge *InitialBoundaryEdge = NULL; Vector<BYTE> VerticesVisited(_Vertices.Length()); Vector<BYTE> EdgesVisited(_FullEdges.Length()); VerticesVisited.Clear(0); EdgesVisited.Clear(0); for(UINT EdgeIndex = 0; EdgeIndex < _FullEdges.Length(); EdgeIndex++) { FullEdge *CurEdge = _FullEdges[EdgeIndex]; if(CurEdge->Boundary()) { InitialBoundaryEdge = CurEdge; } } if(InitialBoundaryEdge == NULL) { return false; } bool Done = false; FullEdge *CurBoundaryEdge = InitialBoundaryEdge; Vertex *StartVertex = &(CurBoundaryEdge->GetVertex(0)); while(!Done) { Boundary.PushEnd(CurBoundaryEdge); EdgesVisited[CurBoundaryEdge->Index()] = true; VerticesVisited[CurBoundaryEdge->GetVertex(1).Index()] = true; Vertex &CurVertex = CurBoundaryEdge->GetVertex(1); bool NextEdgeFound = false; for(UINT i = 0; i < CurVertex.Vertices().Length() && !NextEdgeFound; i++) { Vertex *NeighborVertex = CurVertex.Vertices()[i]; FullEdge &CurEdge = CurVertex.GetSharedEdge(*NeighborVertex); if(CurEdge.Boundary() && (CurEdge.GetVertex(0) == CurVertex)) { NextEdgeFound = true; CurBoundaryEdge = &CurEdge; if(CurBoundaryEdge == InitialBoundaryEdge) { Done = true; } else if(EdgesVisited[CurBoundaryEdge->Index()]) { SignalError("Revisited an edge!"); } } } if(!NextEdgeFound) { SignalError("Invalid boundary behavior"); } } for(UINT EdgeIndex = 0; EdgeIndex < _FullEdges.Length(); EdgeIndex++) { FullEdge *CurEdge = _FullEdges[EdgeIndex]; if(!EdgesVisited[CurEdge->Index()]) { //return false; } } return true; } bool ComplexMesh::ComputeDiskParameterization(bool Natural) { const float Lambda = 1.0f; Vector<FullEdge *> Boundary; if(!ComputeDiskBoundary(Boundary)) { return false; } float TotalBoundaryLength = 0.0f; for(UINT i = 0; i < Boundary.Length(); i++) { TotalBoundaryLength += Boundary[i]->Vector().Length(); if(i != 0) { Assert(Boundary[i]->GetVertex(0).Index() == Boundary[i - 1]->GetVertex(1).Index(), "Invalid boundary"); } } PersistentAssert(TotalBoundaryLength > 0.0f, "Invalid boundary"); float CurBoundaryLength = 0.0f; for(UINT i = 0; i < Boundary.Length(); i++) { Vertex &CurVertex = Boundary[i]->GetVertex(0); CurVertex.TexCoords() = Vec2f::ConstructFromPolar(0.5f, 2.0f * Math::PIf * CurBoundaryLength / TotalBoundaryLength) + Vec2f(0.5f, 0.5f); CurBoundaryLength += Boundary[i]->Vector().Length(); } SparseMatrix<double> M(_Vertices.Length() * 2); const UINT FixedIndexCount = 2; UINT FixedIndices[FixedIndexCount]; FixedIndices[0] = Boundary[0]->GetVertex(0).Index(); FixedIndices[1] = Boundary[Boundary.Length() / 2]->GetVertex(1).Index(); for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex &CurVertex = _Vertices[VertexIndex]; if(CurVertex.Boundary()) { if(Natural && VertexIndex != FixedIndices[0] && VertexIndex != FixedIndices[1]) { for(UINT TriangleIndex = 0; TriangleIndex < CurVertex.Triangles().Length(); TriangleIndex++) { Triangle &CurTriangle = *(CurVertex.Triangles()[TriangleIndex]); UINT IBaseIndex = CurTriangle.GetVertexLocalIndex(CurVertex); UINT IIndex = CurTriangle.GetVertex((IBaseIndex + 0) % 3).Index(); UINT JIndex = CurTriangle.GetVertex((IBaseIndex + 1) % 3).Index(); UINT KIndex = CurTriangle.GetVertex((IBaseIndex + 2) % 3).Index(); double Alpha = CurTriangle.GetCotangent(CurTriangle.GetVertex((IBaseIndex + 2) % 3)); double Beta = CurTriangle.GetCotangent(CurTriangle.GetVertex((IBaseIndex + 1) % 3)); M.PushElement(2 * VertexIndex + 0, 2 * IIndex + 0, Alpha + Beta); M.PushElement(2 * VertexIndex + 1, 2 * IIndex + 1, Alpha + Beta); M.PushElement(2 * VertexIndex + 0, 2 * JIndex + 0, -Alpha); M.PushElement(2 * VertexIndex + 1, 2 * JIndex + 1, -Alpha); M.PushElement(2 * VertexIndex + 0, 2 * KIndex + 0, -Beta); M.PushElement(2 * VertexIndex + 1, 2 * KIndex + 1, -Beta); M.PushElement(2 * VertexIndex + 0, 2 * JIndex + 1, 1.0); M.PushElement(2 * VertexIndex + 1, 2 * JIndex + 0, -1.0); M.PushElement(2 * VertexIndex + 0, 2 * KIndex + 1, -1.0); M.PushElement(2 * VertexIndex + 1, 2 * KIndex + 0, 1.0); } /*for(UINT EdgeIndex = 0; EdgeIndex < CurVertex.Vertices().Length(); EdgeIndex++) { Vertex &OtherVertex = *(CurVertex.Vertices()[EdgeIndex]); FullEdge &CurEdge = CurVertex.GetSharedEdge(OtherVertex); double ConstantFactor = Lambda * CurEdge.GetCotanTerm(); Assert(ConstantFactor == ConstantFactor, "ConstantFactor invalid"); M.PushDiagonalElement(VertexIndex * 2 + 0, -ConstantFactor); M.PushDiagonalElement(VertexIndex * 2 + 1, -ConstantFactor); M.PushElement(VertexIndex * 2 + 0, OtherVertex.Index() * 2 + 1, ConstantFactor); M.PushElement(VertexIndex * 2 + 0, OtherVertex.Index() * 2 + 1, ConstantFactor); M.PushElement(VertexIndex * 2 + 1, OtherVertex.Index() * 2 + 0, 1.0f); M.PushElement(VertexIndex * 2 + 0, OtherVertex.Index() * 2 + 1, -1.0f); }*/ } else { M.PushDiagonalElement(VertexIndex * 2 + 0, 1.0f); M.PushDiagonalElement(VertexIndex * 2 + 1, 1.0f); } } else { //M.PushDiagonalElement(VertexIndex * 2 + 0, VertexAreas[VertexIndex]); //M.PushDiagonalElement(VertexIndex * 2 + 1, VertexAreas[VertexIndex]); for(UINT EdgeIndex = 0; EdgeIndex < CurVertex.Vertices().Length(); EdgeIndex++) { Vertex &OtherVertex = *(CurVertex.Vertices()[EdgeIndex]); FullEdge &CurEdge = CurVertex.GetSharedEdge(OtherVertex); double ConstantFactor = Lambda * CurEdge.GetCotanTerm(); Assert(ConstantFactor == ConstantFactor, "ConstantFactor invalid"); M.PushDiagonalElement(VertexIndex * 2 + 0, -ConstantFactor); M.PushDiagonalElement(VertexIndex * 2 + 1, -ConstantFactor); M.PushElement(VertexIndex * 2 + 0, OtherVertex.Index() * 2 + 0, ConstantFactor); M.PushElement(VertexIndex * 2 + 1, OtherVertex.Index() * 2 + 1, ConstantFactor); } } } BiCGLinearSolver<double> Solver; //TaucsSymmetricLinearSolver Solver; Solver.LoadMatrix(&M); Solver.Factor(); //ofstream File("Matrix.TexCoord.xt"); //M.Dump(File, false); //File << endl; Solver.SetParamaters(1000, 1e-6); Vector<double> x(_Vertices.Length() * 2), b(_Vertices.Length() * 2); for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex &CurVertex = _Vertices[VertexIndex]; if(CurVertex.Boundary()) { if(!Natural || VertexIndex == FixedIndices[0] || VertexIndex == FixedIndices[1]) { x[VertexIndex * 2 + 0] = CurVertex.TexCoords().x; x[VertexIndex * 2 + 1] = CurVertex.TexCoords().y; b[VertexIndex * 2 + 0] = CurVertex.TexCoords().x; b[VertexIndex * 2 + 1] = CurVertex.TexCoords().y; } else { x[VertexIndex * 2 + 0] = CurVertex.Pos().x; x[VertexIndex * 2 + 1] = CurVertex.Pos().y; b[VertexIndex * 2 + 0] = 0.0f; b[VertexIndex * 2 + 1] = 0.0f; } } else { x[VertexIndex * 2 + 0] = CurVertex.Pos().x; x[VertexIndex * 2 + 1] = CurVertex.Pos().y; b[VertexIndex * 2 + 0] = 0.0f; b[VertexIndex * 2 + 1] = 0.0f; } //File << b[VertexIndex * 2 + 0] << '\t' << b[VertexIndex * 2 + 1] << endl; } Solver.Solve(x, b); Console::WriteLine(Solver.GetOutputString()); double Error = Solver.ComputeError(x, b); Console::WriteLine(String("Parameterization error: ") + String(Error)); for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex &CurVertex = _Vertices[VertexIndex]; if(Natural || !CurVertex.Boundary()) { CurVertex.TexCoords().x = float(x[VertexIndex * 2 + 0]); CurVertex.TexCoords().y = float(x[VertexIndex * 2 + 1]); } } return true; } void ComplexMesh::ComputeConstrainedParameterization() { const float Lambda = 1.0f; SparseMatrix<double> M(_Vertices.Length() * 2); Vector<double> x(_Vertices.Length() * 2), b(_Vertices.Length() * 2); for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex &CurVertex = _Vertices[VertexIndex]; if(CurVertex.Boundary()) { M.PushDiagonalElement(VertexIndex * 2 + 0, 1.0f); M.PushDiagonalElement(VertexIndex * 2 + 1, 1.0f); } else { for(UINT EdgeIndex = 0; EdgeIndex < CurVertex.Vertices().Length(); EdgeIndex++) { Vertex &OtherVertex = *(CurVertex.Vertices()[EdgeIndex]); FullEdge &CurEdge = CurVertex.GetSharedEdge(OtherVertex); double ConstantFactor = Lambda * CurEdge.GetCotanTerm(); Assert(ConstantFactor == ConstantFactor, "ConstantFactor invalid"); M.PushDiagonalElement(VertexIndex * 2 + 0, -ConstantFactor); M.PushDiagonalElement(VertexIndex * 2 + 1, -ConstantFactor); M.PushElement(VertexIndex * 2 + 0, OtherVertex.Index() * 2 + 0, ConstantFactor); M.PushElement(VertexIndex * 2 + 1, OtherVertex.Index() * 2 + 1, ConstantFactor); } } } for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex &CurVertex = _Vertices[VertexIndex]; if(CurVertex.Boundary()) { x[VertexIndex * 2 + 0] = CurVertex.TexCoords().x; x[VertexIndex * 2 + 1] = CurVertex.TexCoords().y; b[VertexIndex * 2 + 0] = CurVertex.TexCoords().x; b[VertexIndex * 2 + 1] = CurVertex.TexCoords().y; } else { //x[VertexIndex * 2 + 0] = CurVertex.Pos().x; //x[VertexIndex * 2 + 1] = CurVertex.Pos().y; x[VertexIndex * 2 + 0] = pmrnd() * 0.01f; x[VertexIndex * 2 + 1] = pmrnd() * 0.01f; b[VertexIndex * 2 + 0] = 0.0f; b[VertexIndex * 2 + 1] = 0.0f; } } BiCGLinearSolver<double> Solver; //TaucsSymmetricLinearSolver Solver; Solver.LoadMatrix(&M); Solver.Factor(); Solver.SetParamaters(1000, 1e-6); Solver.Solve(x, b); Console::WriteLine(Solver.GetOutputString()); double Error = Solver.ComputeError(x, b); Console::WriteLine(String("Parameterization error: ") + String(Error)); for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex &CurVertex = _Vertices[VertexIndex]; if(!CurVertex.Boundary()) { CurVertex.TexCoords().x = float(x[VertexIndex * 2 + 0]); CurVertex.TexCoords().y = float(x[VertexIndex * 2 + 1]); } //Console::WriteLine(String(CurVertex.TexCoords().x)); } } void ComplexMesh::ExplicitMeanCurvatureFlow(float TimeStep) { Vector<Vec3f> NewVertexPositions(_Vertices.Length()); float AverageDelta = 0.0f; for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex &CurVertex = _Vertices[VertexIndex]; Vec3f Delta = -TimeStep * CurVertex.MeanCurvatureNormal(); AverageDelta += Delta.Length(); NewVertexPositions[VertexIndex] = Delta; } AverageDelta /= _Vertices.Length(); for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex &CurVertex = _Vertices[VertexIndex]; if(NewVertexPositions[VertexIndex].Length() > 2.0f * AverageDelta) { NewVertexPositions[VertexIndex].SetLength(2.0f * AverageDelta); } CurVertex.Pos() += NewVertexPositions[VertexIndex]; } } void ComplexMesh::ImplicitMeanCurvatureFlow(float TimeStep) { Vector<double> VertexAreas(_Vertices.Length()); Vector<Vec3f> NewVertexPositions(_Vertices.Length()); NewVertexPositions.Clear(Vec3f::Origin); SparseMatrix<double> M(_Vertices.Length()); for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex &CurVertex = _Vertices[VertexIndex]; VertexAreas[VertexIndex] = CurVertex.ComputeTriangleArea(); M.PushElement(VertexIndex, VertexIndex, VertexAreas[VertexIndex]); //M.PushElement(VertexIndex, VertexIndex, 1.0f); for(UINT EdgeIndex = 0; EdgeIndex < CurVertex.Vertices().Length(); EdgeIndex++) { Vertex &OtherVertex = *(CurVertex.Vertices()[EdgeIndex]); FullEdge &CurEdge = CurVertex.GetSharedEdge(OtherVertex); double ConstantFactor = CurEdge.GetCotanTerm() / 4.0f; Assert(ConstantFactor == ConstantFactor, "ConstantFactor invalid"); M.PushElement(VertexIndex, VertexIndex, TimeStep * ConstantFactor); M.PushElement(VertexIndex, OtherVertex.Index(), -TimeStep * ConstantFactor); } } BiCGLinearSolver<double> Solver; Solver.LoadMatrix(&M); const double ErrorTolerance = 1e-6; Solver.SetParamaters(1000, ErrorTolerance); Solver.Factor(); for(UINT ElementIndex = 0; ElementIndex < 3; ElementIndex++) { Vector<double> x, b(_Vertices.Length()); for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { b[VertexIndex] = _Vertices[VertexIndex].Pos()[ElementIndex] * VertexAreas[VertexIndex]; //b[VertexIndex] = _Vertices[VertexIndex].Pos().Element(ElementIndex); } Solver.Solve(x, b); Console::WriteLine(Solver.GetOutputString()); double Error = Solver.ComputeError(x, b); Console::WriteLine(String("Mean curvature error: ") + String(Error)); if(Error < ErrorTolerance) { for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { NewVertexPositions[VertexIndex][ElementIndex] = float(x[VertexIndex]); } } } float AverageDelta = 0.0f; for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vec3f Delta = NewVertexPositions[VertexIndex] - _Vertices[VertexIndex].Pos(); AverageDelta += Delta.Length(); } AverageDelta /= _Vertices.Length(); for(UINT VertexIndex = 0; VertexIndex < _Vertices.Length(); VertexIndex++) { Vertex &CurVertex = _Vertices[VertexIndex]; Vec3f Delta = NewVertexPositions[VertexIndex] - _Vertices[VertexIndex].Pos(); if(Delta.Length() > 2.0f * AverageDelta) { Delta.SetLength(2.0f * AverageDelta); } CurVertex.Pos() += Delta; } } bool ComplexMesh::Oriented() { for(UINT i = 0; i < _FullEdges.Length(); i++) { FullEdge *CurEdge = _FullEdges[i]; if(!CurEdge->Oriented()) { return false; } } return true; } void ComplexMesh::ClearHashTable() { for(UINT i = 0; i < _HashTable.Length(); i++) { if(_HashTable[i].Length() > 0) { _HashTable[i].FreeMemory(); } } _HashTable.FreeMemory(); } void ComplexMesh::InitHashTable(UINT Size) { ClearHashTable(); _HashTable.Allocate(Size); } void ComplexMesh::HashEdge(const FullEdge &FullE) { Assert(FullE.GetVertex(0).Index() < FullE.GetVertex(1).Index(), "Invalid vertex ordering"); //Console::WriteLine(String("Enqueing edge: ") + String(FullE.GetVertex(0).Index()) + String(", ") + String(FullE.GetVertex(1).Index())); UINT HTableIndex = FullE.GetVertex(0).Index() % _HashTable.Length(); _HashTable[HTableIndex].PushEnd(FullE.Index()); } FullEdge& ComplexMesh::FindFullEdge(Vertex *SearchV[2]) { UINT HTableIndex = SearchV[0]->Index() % _HashTable.Length(); ComplexMeshEdgeHash &CurHashTable = _HashTable[HTableIndex]; for(UINT EntryIndex = 0; EntryIndex < CurHashTable.Length(); EntryIndex++) { FullEdge &CurFullEdge = *(_FullEdges[CurHashTable[EntryIndex]]); if(CurFullEdge.ContainsVertex(*SearchV[0]) && CurFullEdge.ContainsVertex(*SearchV[1])) { return CurFullEdge; } } return FullEdge::NotFound; } void ComplexMesh::Load(const BaseMesh &Mesh) { FreeMemory(); _Vertices.Allocate(Mesh.VertexCount()); _Triangles.Allocate(Mesh.FaceCount()); _HalfEdges.Allocate(Mesh.FaceCount() * 3); _FullEdges.FreeMemory(); for(UINT i = 0; i < _Vertices.Length(); i++) { _Vertices[i].Pos() = Mesh.Vertices()[i].Pos; _Vertices[i].TexCoords() = Mesh.Vertices()[i].TexCoord; _Vertices[i].Boundary() = false; _Vertices[i]._Index = i; } InitHashTable(_Vertices.Length()); for(UINT TriangleIndex = 0; TriangleIndex < _Triangles.Length(); TriangleIndex++) { Triangle &CurTriangle = _Triangles[TriangleIndex]; UINT LocalIndices[3]; LocalIndices[0] = Mesh.Indices()[TriangleIndex * 3 + 0]; LocalIndices[1] = Mesh.Indices()[TriangleIndex * 3 + 1]; LocalIndices[2] = Mesh.Indices()[TriangleIndex * 3 + 2]; CurTriangle._Index = TriangleIndex; for(UINT LocalEdgeIndex = 0; LocalEdgeIndex < 3; LocalEdgeIndex++) { Vertex *SearchV[2]; CurTriangle._HalfEdges[LocalEdgeIndex] = &_HalfEdges[TriangleIndex * 3 + LocalEdgeIndex]; CurTriangle._Vertices[LocalEdgeIndex] = &_Vertices[LocalIndices[LocalEdgeIndex]]; _HalfEdges[TriangleIndex * 3 + LocalEdgeIndex]._NextEdge = &_HalfEdges[TriangleIndex * 3 + (LocalEdgeIndex + 1) % 3]; SearchV[0] = &_Vertices[LocalIndices[(LocalEdgeIndex + 1) % 3]]; SearchV[1] = &_Vertices[LocalIndices[(LocalEdgeIndex + 2) % 3]]; if(SearchV[0]->Index() > SearchV[1]->Index()) { Utility::Swap(SearchV[0], SearchV[1]); } FullEdge &Target = FindFullEdge(SearchV); if(Target != FullEdge::NotFound) { PersistentAssert(Target.GetTriangle(1) == Triangle::Boundary, "Duplicate edge; 2-manifold criterion violated."); //PersistentAssert(Target.GetTriangle(1) == Triangle::Boundary, // String("Duplicate edge; 2-manifold criterion violated: ") + String(SearchV[0]->Index()) + String(", ") + String(SearchV[1]->Index())); _HalfEdges[TriangleIndex * 3 + LocalEdgeIndex]._AcrossEdge = &Target; Target._Triangles[1] = &CurTriangle; } else { FullEdge *NewEdge = new FullEdge; Assert(NewEdge != NULL, "Out of memory"); NewEdge->_Index = _FullEdges.Length(); NewEdge->_Triangles[0] = &CurTriangle; NewEdge->_Triangles[1] = &Triangle::Boundary; NewEdge->_Vertices[0] = SearchV[0]; NewEdge->_Vertices[1] = SearchV[1]; _HalfEdges[TriangleIndex * 3 + LocalEdgeIndex]._AcrossEdge = NewEdge; _FullEdges.PushEnd(NewEdge); HashEdge(*NewEdge); } } } for(UINT TriangleIndex = 0; TriangleIndex < _Triangles.Length(); TriangleIndex++) { Triangle &CurTriangle = _Triangles[TriangleIndex]; for(UINT AdjacentTriangleIndex = 0; AdjacentTriangleIndex < 3; AdjacentTriangleIndex++) { Triangle &AdjTriangle = CurTriangle.GetNeighboringTriangle(AdjacentTriangleIndex); } } ClearHashTable(); for(UINT i = 0; i < _FullEdges.Length(); i++) { if(_FullEdges[i]->Boundary()) { _FullEdges[i]->GetVertex(0).Boundary() = true; _FullEdges[i]->GetVertex(1).Boundary() = true; _FullEdges[i]->OrientMatchingBoundary(); } } PrepareTopology(); /*if(!Oriented()) { Orient(); } PersistentAssert(Oriented(), "Mesh not oriented");*/ } void ComplexMesh::Orient() { for(UINT TriangleIndex = 0; TriangleIndex < _Triangles.Length(); TriangleIndex++) { Triangle &CurTriangle = _Triangles[TriangleIndex]; for(UINT AdjacentTriangleIndex = 0; AdjacentTriangleIndex < 3; AdjacentTriangleIndex++) { Triangle &AdjTriangle = CurTriangle.GetNeighboringTriangle(AdjacentTriangleIndex); } } Vector<BYTE> TriangleOriented(_Triangles.Length()); Vector<Triangle *> TriangleQueue; TriangleOriented.Clear(0); bool Done = false; while(!Done) { bool UnorientedTriangleFound = false; for(UINT TriangleIndex = 0; TriangleIndex < _Triangles.Length() && !UnorientedTriangleFound; TriangleIndex++) { if(TriangleOriented[TriangleIndex] == 0) { UnorientedTriangleFound = true; TriangleQueue.PushEnd(&_Triangles[TriangleIndex]); TriangleOriented[TriangleIndex] = 1; } } if(UnorientedTriangleFound) { while(TriangleQueue.Length() > 0) { Triangle &CurTriangle = *(TriangleQueue.Last()); TriangleQueue.PopEnd(); for(UINT AdjacentTriangleIndex = 0; AdjacentTriangleIndex < 3; AdjacentTriangleIndex++) { Triangle &NeighborTriangle = CurTriangle.GetNeighboringTriangle(AdjacentTriangleIndex); if(NeighborTriangle != Triangle::Boundary) { FullEdge &SharedEdge = CurTriangle.GetSharedEdge(NeighborTriangle); if((CurTriangle.OrientedWith(SharedEdge) && NeighborTriangle.OrientedWith(SharedEdge)) || (!CurTriangle.OrientedWith(SharedEdge) && !NeighborTriangle.OrientedWith(SharedEdge))) { if(TriangleOriented[NeighborTriangle.Index()] == 1) { SignalError("Mesh not orientable"); } Utility::Swap(NeighborTriangle._Vertices[0], NeighborTriangle._Vertices[1]); //Utility::Swap(NeighborTriangle._HalfEdges[0], NeighborTriangle._HalfEdges[1]); TriangleOriented[NeighborTriangle.Index()] = 1; TriangleQueue.PushEnd(&NeighborTriangle); } } } } } else { Done = true; } } } void ComplexMesh::PrepareTopology() { for(UINT i = 0; i < _Vertices.Length(); i++) { _Vertices[i].Triangles().FreeMemory(); } for(UINT i = 0; i < _Triangles.Length(); i++) { Triangle &CurTriangle = _Triangles[i]; for(UINT i2 = 0; i2 < 3; i2++) { CurTriangle.GetVertex(i2).Triangles().PushEnd(&CurTriangle); } } for(UINT i = 0; i < _Vertices.Length(); i++) { _Vertices[i].LoadVertices(); } } void ComplexMesh::Dump(BaseMesh &Mesh) const { Mesh.Allocate(_Vertices.Length(),_Triangles.Length()); for(UINT i=0;i<_Vertices.Length();i++) { Mesh.Vertices()[i].Pos = _Vertices[i].Pos(); Mesh.Vertices()[i].TexCoord.x = _Vertices[i].TexCoords().x; Mesh.Vertices()[i].TexCoord.y = _Vertices[i].TexCoords().y; } for(UINT i=0;i<_Triangles.Length();i++) { Mesh.Indices()[i * 3 + 0] = _Triangles[i].GetVertex(0).Index(); Mesh.Indices()[i * 3 + 1] = _Triangles[i].GetVertex(1).Index(); Mesh.Indices()[i * 3 + 2] = _Triangles[i].GetVertex(2).Index(); } Mesh.GenerateNormals(); } void ComplexMesh::Subdivision() { Mesh M; Subdivision(M); Load(M); } void ComplexMesh::Subdivision(BaseMesh &Mesh) { UINT VertexCount = _Vertices.Length(); UINT EdgeCount = _FullEdges.Length(); UINT TriangleCount = _Triangles.Length(); //IntPair P; Mesh.Allocate(VertexCount + EdgeCount, TriangleCount * 4); MeshVertex *V = Mesh.Vertices(); DWORD *I = Mesh.Indices(); Vector<Vec3f> NewVertexPositions(_Vertices.Length()); for(UINT VertexIndex = 0; VertexIndex < VertexCount; VertexIndex++) { V[VertexIndex].Pos = _Vertices[VertexIndex].ComputeLoopSubdivisionPos(); } for(UINT EdgeIndex = 0; EdgeIndex < EdgeCount; EdgeIndex++) { V[VertexCount + EdgeIndex].Pos = _FullEdges[EdgeIndex]->ComputeLoopSubdivisionPos(); } for(UINT i = 0; i < TriangleCount; i++) { UINT SourceI[6]; Triangle &CurTriangle = _Triangles[i]; for(UINT i2 = 0; i2 < 3; i2++) { SourceI[i2 + 0] = CurTriangle.GetVertex(i2).Index(); SourceI[i2 + 3] = VertexCount + CurTriangle.GetOtherEdge(_Triangles[i].GetVertex(i2)).Index(); } I[i * 12 + 0] = SourceI[0]; I[i * 12 + 1] = SourceI[5]; I[i * 12 + 2] = SourceI[4]; I[i * 12 + 3] = SourceI[5]; I[i * 12 + 4] = SourceI[1]; I[i * 12 + 5] = SourceI[3]; I[i * 12 + 6] = SourceI[4]; I[i * 12 + 7] = SourceI[3]; I[i * 12 + 8] = SourceI[2]; I[i * 12 + 9] = SourceI[4]; I[i * 12 + 10] = SourceI[5]; I[i * 12 + 11] = SourceI[3]; } } void Subdivide(BaseMesh &M1, BaseMesh &M2) { M2.SetGD(M1.GetGD()); ComplexMesh EM; EM.Load(M1); EM.Subdivision(M2); } void Subdivide(BaseMesh &M1, BaseMesh &M2, UINT Iterations) { Mesh MTemp = M1; for(UINT i = 0; i < Iterations; i++) { Subdivide(MTemp, M2); MTemp = M2; } }
[ "zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2" ]
[ [ [ 1, 911 ] ] ]
e7737fcc1466508a97120d69dde9617a1f00049b
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Com/ScdIF/ScdCOMTmpl.cpp
a8cc60651ff9cbbf9e8bc9760703d4fbcd3fa9ef
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
96
cpp
#include "stdafx.h" __declspec(dllexport) HRESULT DoFC_ROF(HRESULT hr) { return hr; }
[ [ [ 1, 7 ] ] ]
229b5ef3c21c7049b9119bb672b345bb8a43e70c
b22c254d7670522ec2caa61c998f8741b1da9388
/NewClient/LbaNetEngine.h
b7316c44d2ca09b6e50353912c18531a6b6598a5
[]
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
3,697
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_LbaNetEngine_h) #define __LbaNetModel_1_LbaNetEngine_h #include <string> #include <boost/shared_ptr.hpp> #include "LbaNetModel.h" #include "GuiHandler.h" class PhysXEngine; class EventHandler; class ChatClient; class GameClient; /*********************************************************************** * Module: LbaNetEngine.h * Author: vivien * Modified: mardi 14 juillet 2009 17:41:03 * Purpose: Declaration of the class LbaNetEngine ***********************************************************************/ class LbaNetEngine { public: //!constructor LbaNetEngine(ChatClient* Chatcl, GameClient* Gamecl); //!destructor ~LbaNetEngine(); //! entry point of the engine void run(void); //! start a move from keyboard input void StartMove(int MoveType); //! stop a move from keyboard input void StopMove(int MoveType); //! do action from keyboard input void DoAction(); // display a specific gui void DisplayGUI(int guinumber); //connection callback void ConnectionCallback(int SuccessFlag, const std::string & reason); // focus the chatbox void FocusChatbox(bool focus); protected: //! process function void Process(void); //! initialize the class void Initialize(void); //! called to check for game events and handle them void HandleGameEvents(); //! try to login to the server void TryLogin(const std::string &Name, const std::string &Passwordl); //! switch gui helpers void SwitchGuiToLogin(); void SwitchGuiToChooseWorld(); void SwitchGuiToGame(); void SwitchGuiToMenu(); void SwitchGuiToOption(); // exit current active gui void ExitGui(); // change the world void ChangeWorld(const std::string & NewWorld); // called to play the assigned music when menu void PlayMenuMusic(); // called when need to connect to game server void ConnectToGameServer(const std::string &ServerName, const std::string &ServerAddress); // called when game server unreachable void GameErrorMessage(const std::string &Message); private: GuiHandler m_gui_handler; // pointer on gui class LbaNetModel m_lbaNetModel; // game model boost::shared_ptr<EventHandler> m_eventHandler; // handle input events boost::shared_ptr<PhysXEngine> m_physic_engine; //physic engine ChatClient* m_Chatcl; //chat client GameClient* m_Gamecl; //game client std::string m_userlogin; std::string m_userpass; // game states enum EngineState {ELogin=0, EChoosingWorld, EGaming, EMenu, EOption }; EngineState m_currentstate; EngineState m_oldstate; // last music played std::string m_lastmusic; }; #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 134 ] ] ]
c2097aadeda0e3b51eb029f7217144c4886ecfd5
974a20e0f85d6ac74c6d7e16be463565c637d135
/trunk/coreLibrary_200/source/physics/dgMeshEffectSolidTree.cpp
4c029d4730065d6303a4442f3e4986e3838533c5
[]
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
18,012
cpp
/* Copyright (c) <2003-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. */ #include "dgPhysicsStdafx.h" #include "dgMeshEffect.h" #include "dgMeshEffectSolidTree.h" #define DG_CLIPPER_TOL dgFloat64 (1.0e-12) dgMeshTreeCSGFace::dgMeshTreeCSGFace(const dgMeshEffect& mesh, dgEdge* const face) : dgList<dgHugeVector>(mesh.GetAllocator()), m_side( dgMeshEffectSolidTree::m_divider) { const dgEdge* ptr = face; const dgMeshEffect::dgVertexAtribute* const attib = mesh.m_attib; do { Append(attib[ptr->m_userData].m_vertex); ptr = ptr->m_next; } while (ptr != face); } dgMeshTreeCSGFace::dgMeshTreeCSGFace(dgMemoryAllocator* const allocator, dgInt32 count, const dgHugeVector* const points) : dgList<dgHugeVector>(allocator), m_side(dgMeshEffectSolidTree::m_divider) { for (dgInt32 i = 0; i < count; i++) { Append(points[i]); } } bool dgMeshTreeCSGFace::IsPointOnEdge(const dgHugeVector& p0, const dgHugeVector& p1, const dgHugeVector& q0) const { dgHugeVector p1p0(p1 - p0); dgGoogol den(p1p0 % p1p0); dgHugeVector q0p0(q0 - p0); dgGoogol num(q0p0 % p1p0); dgFloat64 numf = num.GetAproximateValue(); if (numf > (DG_CLIPPER_TOL * dgFloat64(1.0e3))) { if (numf < den.GetAproximateValue() * dgFloat64(1.0 - (DG_CLIPPER_TOL * dgFloat64(1.0e3)))) { dgGoogol t = num / den; _ASSERTE(t.GetAproximateValue() > dgFloat64 (0.0f)); _ASSERTE(t.GetAproximateValue() < dgFloat64 (1.0f)); dgHugeVector q1(p0 + p1p0.Scale(t)); dgHugeVector dist(q1 - q0); dgGoogol dist2 = dist % dist; if (dist2.GetAproximateValue() < DG_CLIPPER_TOL) { return true; } } } return false; } bool dgMeshTreeCSGFace::CheckConvex(const dgHugeVector& normal) const { dgHugeVector p1(GetLast()->GetInfo()); dgHugeVector p0(GetLast()->GetPrev()->GetInfo()); dgHugeVector e0(p0 - p1); for (dgListNode* node = GetFirst(); node; node = node->GetNext()) { dgHugeVector p2(node->GetInfo()); dgHugeVector e1(p2 - p1); dgHugeVector n(e1 * e0); dgGoogol convex = n % normal; if (convex.GetAproximateValue() < dgFloat64(-1.0e10f)) { return false; } p1 = p2; e0 = e1.Scale(dgGoogol(-1.0f)); } return true; } ; void dgMeshTreeCSGFace::MergeMissingVertex(const dgMeshTreeCSGFace* const face) { for (dgMeshTreeCSGFace::dgListNode* outNode = GetFirst(); outNode != GetLast(); outNode = outNode->GetNext()) { dgHugeVector p0(outNode->GetInfo()); for (dgMeshTreeCSGFace::dgListNode* node = face->GetFirst(); node; node = node->GetNext()) { if (IsPointOnEdge(p0, outNode->GetNext()->GetInfo(), node->GetInfo())) { dgMeshTreeCSGFace::dgListNode* const insertNode = Append( node->GetInfo()); InsertAfter(outNode, insertNode); } } } RotateToBegin(GetLast()); dgListNode* const last = GetFirst()->GetNext(); for (dgMeshTreeCSGFace::dgListNode* outNode = GetFirst(); outNode != last; outNode = outNode->GetNext()) { dgHugeVector p0(outNode->GetInfo()); dgHugeVector p1(outNode->GetNext()->GetInfo()); for (dgMeshTreeCSGFace::dgListNode* node = face->GetFirst(); node; node = node->GetNext()) { if (IsPointOnEdge(p0, outNode->GetNext()->GetInfo(), node->GetInfo())) { dgMeshTreeCSGFace::dgListNode* const insertNode = Append( node->GetInfo()); InsertAfter(outNode, insertNode); } } } } dgInt32 dgMeshTreeCSGFace::RemoveDuplicates(dgInt32 count, dgHugeVector* const points) const { dgInt32 index[256]; for (dgInt32 i = 0; i < count; i++) { index[i] = i + 1; } index[count - 1] = 0; dgInt32 originalCount = count; dgInt32 start = index[0]; for (dgInt32 count1 = 0; (count1 != count) && (count >= 3);) { count1 = 0; for (dgInt32 i = 0; i < count; i++) { dgInt32 next = index[start]; dgHugeVector err(points[start] - points[next]); dgGoogol dist2 = err % err; dgFloat64 val = dist2.GetAproximateValue(); if (val < dgFloat64(1.0e-12f)) { index[start] = index[index[start]]; count1 = 0; count--; break; } count1++; start = index[start]; } } if ((count != originalCount) && (count >= 3)) { dgHugeVector tmp[256]; for (dgInt32 i = 0; i < count; i++) { tmp[i] = points[start]; start = index[start]; } for (dgInt32 i = 0; i < count; i++) { points[i] = tmp[i]; } } return count; } #ifdef _DEBUG dgMatrix dgMeshTreeCSGFace::DebugMatrix() const { dgMatrix matrix(dgGetIdentityMatrix()); dgHugeVector e0(GetFirst()->GetNext()->GetInfo() - GetFirst()->GetInfo()); dgHugeVector e1( GetFirst()->GetNext()->GetNext()->GetInfo() - GetFirst()->GetInfo()); dgHugeVector aaa(e0 * e1); dgVector aaaa(dgFloat32(aaa.m_x.GetAproximateValue()), dgFloat32(aaa.m_y.GetAproximateValue()), dgFloat32(aaa.m_z.GetAproximateValue()), 0.0f); aaaa = aaaa.Scale(dgFloat32(1.0) / dgSqrt (aaaa % aaaa)); dgVector bbbb(dgFloat32(e0.m_x.GetAproximateValue()), dgFloat32(e0.m_y.GetAproximateValue()), dgFloat32(e0.m_z.GetAproximateValue()), 0.0f); bbbb = bbbb.Scale(dgFloat32(1.0) / dgSqrt (bbbb % bbbb)); matrix.m_up = bbbb; matrix.m_right = aaaa; matrix.m_front = bbbb * aaaa; return matrix; } void dgMeshTreeCSGFace::Trace(const dgMatrix& matrix) const { for (dgMeshTreeCSGFace::dgListNode* node = GetFirst(); node; node = node->GetNext()) { const dgHugeVector& bbb = node->GetInfo(); dgVector bbbb(dgFloat32(bbb.m_x.GetAproximateValue()), dgFloat32(bbb.m_y.GetAproximateValue()), dgFloat32(bbb.m_z.GetAproximateValue()), 0.0f); bbbb = matrix.UnrotateVector(bbbb); bbbb.Trace(); }dgTrace(("\n")); } #endif dgHugeVector dgMeshTreeCSGFace::FaceNormal() const { dgHugeVector area(0.0f, 0.0f, 0.0f, 0.0f); dgHugeVector e0(GetFirst()->GetNext()->GetInfo() - GetFirst()->GetInfo()); for (dgListNode* node = GetFirst()->GetNext()->GetNext(); node; node = node->GetNext()) { dgHugeVector e1(node->GetInfo() - GetFirst()->GetInfo()); area += e0 * e1; e0 = e1; } return area; } bool dgMeshTreeCSGFace::CheckFaceArea(dgInt32 count, const dgHugeVector* const points) const { dgHugeVector area(dgFloat64(0.0), dgFloat64(0.0), dgFloat64(0.0), dgFloat64(0.0)); dgHugeVector e0(points[1] - points[0]); for (dgInt32 i = 2; i < count; i++) { dgHugeVector e1(points[i] - points[0]); area += e0 * e1; e0 = e1; } dgFloat64 val = (area % area).GetAproximateValue(); return (val > dgFloat64(1.0e-12f)) ? true : false; } /* //dgGoogol xxx1(dgGoogol v) dgGoogol xxx1(dgInt32 x) { dgGoogol old (0); dgGoogol ans (1); while (x > 1) { dgGoogol n (ans + old); old = ans; ans = n; x = x - 1; } return ans; } dgGoogol xxx2(dgInt32 x) { dgGoogol one (1); dgGoogol n (x); dgGoogol a (1); for (int i = x; i >= 1; i --) { a = a * n; n -= one; } return a; } void xxxx() { char text[256]; // dgGoogol a (xxx1(100)); // dgGoogol a (1.05); dgGoogol a (xxx2 (60)); a.ToString(text); // dgFloat64 xxxxx = a.GetAproximateValue(); } */ void dgMeshTreeCSGFace::Clip(const dgHugeVector& plane, dgMeshTreeCSGFace** leftOut, dgMeshTreeCSGFace** rightOut) { //xxxx (); dgInt8 pointSide[256]; dgInt32 count = 0; dgInt32 rightCount = 0; dgInt32 leftCount = 0; for (dgMeshTreeCSGFace::dgListNode* ptr = GetFirst(); ptr; ptr = ptr->GetNext()) { const dgHugeVector& p = ptr->GetInfo(); dgGoogol test = plane.EvaluePlane(p); dgFloat64 val = test.GetAproximateValue(); if (fabs(val) < DG_CLIPPER_TOL) { val = dgFloat64(0.0f); } if (val > dgFloat64(0.0f)) { pointSide[count] = 1; rightCount++; } else if (val < dgFloat64(0.0f)) { pointSide[count] = -1; leftCount++; } else { pointSide[count] = 0; } count++; } *leftOut = NULL; *rightOut = NULL; if ((leftCount && !rightCount) || (!leftCount && rightCount)) { if (leftCount) { _ASSERTE(!rightCount); AddRef(); *leftOut = this; } else { _ASSERTE(!leftCount); *rightOut = this; AddRef(); } } else if (!(leftCount || rightCount)) { _ASSERTE(!leftCount); _ASSERTE(!rightCount); AddRef(); //AddRef(); } else { dgInt32 leftCount = 0; dgInt32 rightCount = 0; dgHugeVector leftFace[256]; dgHugeVector rightFace[256]; dgInt32 i1 = 0; dgInt32 i0 = count - 1; dgHugeVector p0(GetLast()->GetInfo()); for (dgMeshTreeCSGFace::dgListNode* ptr = GetFirst(); ptr; ptr = ptr->GetNext()) { const dgHugeVector& p1(ptr->GetInfo()); dgHugeVector inter; if (((pointSide[i0] == -1) && (pointSide[i1] == 1)) || ((pointSide[i0] == 1) && (pointSide[i1] == -1))) { //inter = Interpolate (plane, p0, p1); dgHugeVector dp(p1 - p0); dgGoogol den(plane % dp); dgGoogol num = plane.EvaluePlane(p0); _ASSERTE(fabs (num.GetAproximateValue()) > dgFloat64 (0.0f)); dgGoogol ti(num / den); inter = p0 - dp.Scale(num / den); } if (pointSide[i1] == -1) { if (pointSide[i0] == 1) { rightFace[rightCount] = inter; rightCount++; } } else { if ((pointSide[i1] == 1) && (pointSide[i0] == -1)) { rightFace[rightCount] = inter; rightCount++; } rightFace[rightCount] = p1; rightCount++; } if (pointSide[i1] == 1) { if (pointSide[i0] == -1) { leftFace[leftCount] = inter; leftCount++; } } else { if ((pointSide[i1] == -1) && (pointSide[i0] == 1)) { leftFace[leftCount] = inter; leftCount++; } leftFace[leftCount] = p1; leftCount++; }_ASSERTE(leftCount < (sizeof (leftFace)/sizeof (leftFace[0]) - 1)); _ASSERTE(rightCount < (sizeof (rightFace)/sizeof (rightFace[0]) - 1)); i0 = i1; i1++; p0 = p1; } leftCount = RemoveDuplicates(leftCount, leftFace); rightCount = RemoveDuplicates(rightCount, rightFace); if ((leftCount >= 3) && CheckFaceArea(leftCount, leftFace)) { *leftOut = new (GetAllocator()) dgMeshTreeCSGFace(GetAllocator(), leftCount, leftFace); } if ((rightCount >= 3) && CheckFaceArea(rightCount, rightFace)) { *rightOut = new (GetAllocator()) dgMeshTreeCSGFace(GetAllocator(), rightCount, rightFace); } _ASSERTE(*leftOut || *rightOut); } } dgMeshEffectSolidTree::dgMeshEffectSolidTree(dgPlaneType type) : m_planeType(type), m_back(NULL), m_front(NULL), m_plane(0.0, 0.0, 0.0, 0.0) { } dgMeshEffectSolidTree::dgMeshEffectSolidTree(const dgMeshEffect& mesh, dgEdge* const face) : m_planeType(m_divider), m_back( new (mesh.GetAllocator()) dgMeshEffectSolidTree(m_solid)), m_front( new (mesh.GetAllocator()) dgMeshEffectSolidTree(m_empty)), m_plane( BuildPlane(mesh, face)) { } dgMeshEffectSolidTree::dgMeshEffectSolidTree(const dgHugeVector& plane, dgMemoryAllocator* const allocator) : m_planeType(m_divider), m_back( new (allocator) dgMeshEffectSolidTree(m_solid)), m_front( new (allocator) dgMeshEffectSolidTree(m_empty)), m_plane(plane) { } dgMeshEffectSolidTree::~dgMeshEffectSolidTree() { if (m_front) { delete m_front; } if (m_back) { delete m_back; } } dgHugeVector dgMeshEffectSolidTree::BuildPlane(const dgMeshEffect& mesh, dgEdge* const face) const { dgEdge* edge = face; dgHugeVector plane(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f)); dgHugeVector p0(mesh.m_points[edge->m_incidentVertex]); edge = edge->m_next; dgHugeVector p1(mesh.m_points[edge->m_incidentVertex]); dgHugeVector e1(p1 - p0); for (edge = edge->m_next; edge != face; edge = edge->m_next) { dgHugeVector p2(mesh.m_points[edge->m_incidentVertex]); dgHugeVector e2(p2 - p0); plane += e1 * e2; e1 = e2; } plane.m_w = (p0 % plane) * dgGoogol(-1.0); return plane; } void dgMeshEffectSolidTree::AddFace(const dgMeshEffect& mesh, dgEdge* const face) { dgBigVector normal( mesh.FaceNormal(face, &mesh.m_points[0][0], sizeof(dgBigVector))); dgFloat64 mag2 = normal % normal; if (mag2 > dgFloat32(1.0e-14f)) { dgMeshTreeCSGFace* faces[DG_MESH_EFFECT_BOLLEAN_STACK]; dgMeshEffectSolidTree* pool[DG_MESH_EFFECT_BOLLEAN_STACK]; dgHugeVector plane(BuildPlane(mesh, face)); dgInt32 stack = 1; pool[0] = this; faces[0] = new (mesh.GetAllocator()) dgMeshTreeCSGFace(mesh, face); while (stack) { stack--; dgMeshEffectSolidTree* const root = pool[stack]; _ASSERTE(root->m_planeType == m_divider); dgMeshTreeCSGFace* const curve = faces[stack]; _ASSERTE(curve->CheckConvex(plane)); dgMeshTreeCSGFace* backOut; dgMeshTreeCSGFace* frontOut; curve->Clip(root->m_plane, &backOut, &frontOut); if ((backOut == NULL) && (frontOut == NULL)) { curve->Release(); } else { if (backOut && frontOut) { dgHugeVector backArea(backOut->FaceNormal()); dgHugeVector frontArea(frontOut->FaceNormal()); dgFloat64 backMag = (backArea % backArea).GetAproximateValue(); dgFloat64 frontMag = (frontArea % frontArea).GetAproximateValue(); if (backMag > frontMag) { if (backMag > (frontMag * dgFloat64(1.0e6))) { frontOut->Release(); frontOut = NULL; } } else { if (frontMag > (backMag * dgFloat64(1.0e6))) { backOut->Release(); backOut = NULL; } } } if (backOut) { if (root->m_back->m_planeType != m_divider) { backOut->Release(); delete root->m_back; root->m_back = new (mesh.GetAllocator()) dgMeshEffectSolidTree( plane, mesh.GetAllocator()); } else { faces[stack] = backOut; pool[stack] = root->m_back; stack++; _ASSERTE(stack < (sizeof (pool)/sizeof (pool[0]))); } } if (frontOut) { if (root->m_front->m_planeType != m_divider) { frontOut->Release(); delete root->m_front; root->m_front = new (mesh.GetAllocator()) dgMeshEffectSolidTree( plane, mesh.GetAllocator()); } else { faces[stack] = frontOut; pool[stack] = root->m_front; stack++; _ASSERTE(stack < (sizeof (pool)/sizeof (pool[0]))); } } } curve->Release(); } } } dgMeshEffectSolidTree::dgPlaneType dgMeshEffectSolidTree::GetPointSide( const dgHugeVector& point) const { const dgMeshEffectSolidTree* root = this; _ASSERTE(root); while (root->m_planeType == dgMeshEffectSolidTree::m_divider) { dgGoogol test = root->m_plane.EvaluePlane(point); dgFloat64 dist = test.GetAproximateValue(); if (fabs(dist) < dgFloat64(1.0e-16f)) { dgPlaneType isBackSide = root->m_back->GetPointSide(point); dgPlaneType isFrontSide = root->m_front->GetPointSide(point); return (isBackSide == isFrontSide) ? isFrontSide : m_divider; } else if (dist > dgFloat64(0.0f)) { root = root->m_front; } else { _ASSERTE(dist < dgFloat64 (0.0f)); root = root->m_back; } } return root->m_planeType; } dgMeshEffectSolidTree::dgPlaneType dgMeshEffectSolidTree::GetFaceSide( const dgMeshTreeCSGFace* const face) const { dgHugeVector center(0.0, 0.0, 0.0, 0.0); for (dgMeshTreeCSGFace::dgListNode* node = face->GetFirst(); node; node = node->GetNext()) { const dgHugeVector& point = node->GetInfo(); center += point; } center = center.Scale(dgGoogol(1.0) / dgGoogol(face->GetCount())); dgPlaneType faceSide(GetPointSide(center)); return faceSide; }
[ "[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692" ]
[ [ [ 1, 668 ] ] ]
4aa4ec493d242558b8ec5fbb32d82bd31410113b
69eed80ee7eb670d957d2fe86e3044cab51e517a
/src/main/cpp/sikuli/event-manager.cpp
48500f38c3b318b80ccdc68c3cd88234ece3e166
[]
no_license
lineCode/libsikuli
9a6e4a883362002be18741fdecb0e5fc0c32ec6d
b0e2f381375456561a2b4d87b1b2241c7e085b17
refs/heads/master
2021-01-16T07:19:19.254683
2011-01-04T01:34:15
2011-01-04T01:34:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,752
cpp
#include <iostream> #include <vector> #include <list> #include <algorithm> #include <time.h> #include "finder.h" #include "event-manager.h" using namespace std; using namespace sikuli; #define CHANGE_THRESHOLD 0.001 vector<RegionObserver> EventManager::region_observers; bool EventManager::bObserving = false; void EventManager::addObserver(Region r, Observer observer){ // find the region for (vector<RegionObserver>::iterator it = region_observers.begin(); it != region_observers.end(); it++){ RegionObserver& rob = (*it); if (rob.getRegion() == r){ rob.addObserver(observer); return; } } RegionObserver rob(r); region_observers.push_back(rob); region_observers.back().addObserver(observer); } void EventManager::observe(int seconds, bool background){ bObserving = true; time_t time_limit = time(NULL) + seconds; while (time(NULL) < time_limit && bObserving){ EventManager::update(); //Robot::delay(100); } } void EventManager::stop(){ bObserving = false; } vector<Event> EventManager::update(){ vector<Event> all_events; for (vector<RegionObserver>::iterator rob = region_observers.begin(); rob != region_observers.end(); rob++){ vector<Event> region_events = (*rob).observe(); for (vector<Event>::iterator evt = region_events.begin(); evt != region_events.end(); evt++) all_events.push_back(*evt); } return all_events; } void RegionObserver::addObserver(Observer observer){ observers.push_back(observer); }; RegionObserver::RegionObserver(const Region& r){ region = r; } RegionObserver::~RegionObserver(){ } #include "vision.h" vector<Event> RegionObserver::observe(){ Match top_match; vector<Event> events; for (vector<Observer>::iterator it = observers.begin(); it != observers.end(); it++){ Observer& ob = (*it); Event e; bool triggered = false; if (ob.event_type == CHANGE){ ScreenImage simg = region.capture(); Mat current_screen_image = simg.getMat(); if (prev_screen_image.data == NULL) prev_screen_image = current_screen_image; double score = Vision::compare(prev_screen_image, current_screen_image); prev_screen_image = current_screen_image; if (score > CHANGE_THRESHOLD){ e.type = ob.event_type; e.region = region; triggered = true; } } else if (ob.event_type == APPEAR){ if (region.exists(ob.pattern,0)){ if (!ob.active){ e.type = ob.event_type; e.match = region.getLastMatch(); e.pattern = ob.pattern; e.region = region; triggered = true; ob.active = true; } }else{ ob.active = false; } }else if (ob.event_type == VANISH){ if (region.exists(ob.pattern,0)){ ob.active = false; }else{ if (!ob.active){ e.type = ob.event_type; e.pattern = ob.pattern; e.region = region; triggered = true; ob.active = true; } } } if (triggered){ events.push_back(e); if (ob.callback) (*ob.callback)(e); if (ob.event_handler){ ob.event_handler->handle(e); } } } return events; } Observer::Observer(int event_type_, Pattern ptn, SikuliEventCallback func_){ event_type = event_type_; callback = func_; event_handler = NULL; active = false; pattern = ptn; } Observer::Observer(int event_type_, Pattern ptn, SikuliEventHandler* handler){ event_type = event_type_; callback = 0; event_handler = handler; active = false; pattern = ptn; } Observer::Observer(const Observer& ob){ event_type = ob.event_type; callback = ob.callback; event_handler = ob.event_handler; active = ob.active; pattern = ob.pattern; } Observer::~Observer(){ }
[ [ [ 1, 5 ], [ 7, 202 ] ], [ [ 6, 6 ] ] ]
1a286fc7b66c5e373fdde548d341d2860f6dcfaf
b3b0c727bbafdb33619dedb0b61b6419692e03d3
/Source/DCOMPrototype/DcomConsole/stdafx.h
3bc6f277db2c756dcbb31833856ee07158269df8
[]
no_license
testzzzz/hwccnet
5b8fb8be799a42ef84d261e74ee6f91ecba96b1d
4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113
refs/heads/master
2021-01-10T02:59:32.527961
2009-11-04T03:39:39
2009-11-04T03:39:39
45,688,112
0
1
null
null
null
null
GB18030
C++
false
false
497
h
// stdafx.h : 标准系统包含文件的包含文件, // 或是经常使用但不常更改的 // 特定于项目的包含文件 // #pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h> #ifndef _WIN32_DCOM #define _WIN32_DCOM #endif #include <windows.h> #include <iostream> #import "..\DcomSvr\Debug\DcomSvr.tlb" raw_interfaces_only, no_namespace,named_guids using namespace std; // TODO: 在此处引用程序需要的其他头文件
[ [ [ 1, 22 ] ] ]