blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
โŒ€
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
64e67ac97c782a59439b7f14acb56cd5e0e21016
4f89f1c71575c7a5871b2a00de68ebd61f443dac
/lib/boost/gil/extension/io_new/bmp_io_old.hpp
96e8b1ddab567221a50a79147febd6fb6279b9e7
[]
no_license
inayatkh/uniclop
1386494231276c63eb6cdbe83296cdfd0692a47c
487a5aa50987f9406b3efb6cdc656d76f15957cb
refs/heads/master
2021-01-10T09:43:09.416338
2009-09-03T16:26:15
2009-09-03T16:26:15
50,645,836
0
0
null
null
null
null
UTF-8
C++
false
false
6,142
hpp
/* Copyright 2008 Christian Henning Use, modification and distribution are subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). */ /*************************************************************************************************/ #ifndef BOOST_GIL_EXTENSION_IO_BMP_IO_OLD_HPP_INCLUDED #define BOOST_GIL_EXTENSION_IO_BMP_IO_OLD_HPP_INCLUDED //////////////////////////////////////////////////////////////////////////////////////// /// \file /// \brief /// \author Christian Henning \n /// /// \date 2008 \n /// //////////////////////////////////////////////////////////////////////////////////////// #include "bmp_all.hpp" namespace boost { namespace gil { /// \ingroup BMP_IO /// \brief Returns the width and height of the BMP file at the specified location. /// Throws std::ios_base::failure if the location does not correspond to a valid BMP file template< typename String > inline point2< std::ptrdiff_t > bmp_read_dimensions( const String& filename ) { image_read_info< bmp_tag > info = read_image_info( filename , bmp_tag() ); return point2< std::ptrdiff_t >( info._width , info._height ); } /// \ingroup BMP_IO /// \brief Loads the image specified by the given bmp image file name into the given view. /// Triggers a compile assert if the view color space and channel depth are not supported by the BMP library or by the I/O extension. /// Throws std::ios_base::failure if the file is not a valid BMP file, or if its color space or channel depth are not /// compatible with the ones specified by View, or if its dimensions don't match the ones of the view. template< typename String , typename View > inline void bmp_read_view( const String& filename , const View& view ) { read_view( filename , view , bmp_tag() ); } /// \ingroup BMP_IO /// \brief Allocates a new image whose dimensions are determined by the given bmp image file, and loads the pixels into it. /// Triggers a compile assert if the image color space or channel depth are not supported by the BMP library or by the I/O extension. /// Throws std::ios_base::failure if the file is not a valid BMP file, or if its color space or channel depth are not /// compatible with the ones specified by Image template< typename String , typename Image > inline void bmp_read_image( const String& filename , Image& img ) { read_image( filename , img , bmp_tag() ); } /// \ingroup BMP_IO /// \brief Loads and color-converts the image specified by the given bmp image file name into the given view. /// Throws std::ios_base::failure if the file is not a valid BMP file, or if its dimensions don't match the ones of the view. template< typename String , typename View , typename CC > inline void bmp_read_and_convert_view( const String& filename , const View& view , CC cc ) { read_and_convert_view( filename , view , cc , bmp_tag() ); } /// \ingroup BMP_IO /// \brief Loads and color-converts the image specified by the given bmp image file name into the given view. /// Throws std::ios_base::failure if the file is not a valid BMP file, or if its dimensions don't match the ones of the view. template< typename String , typename View > inline void bmp_read_and_convert_view( const String& filename , const View& view ) { read_and_convert_view( filename , view , bmp_tag() ); } /// \ingroup BMP_IO /// \brief Allocates a new image whose dimensions are determined by the given bmp image file, loads and color-converts the pixels into it. /// Throws std::ios_base::failure if the file is not a valid BMP file template< typename String , typename Image , typename CC > inline void bmp_read_and_convert_image( const String& filename , Image& img , CC cc ) { read_and_convert_image( filename , img , cc , bmp_tag() ); } /// \ingroup BMP_IO /// \brief Allocates a new image whose dimensions are determined by the given bmp image file, loads and color-converts the pixels into it. /// Throws std::ios_base::failure if the file is not a valid BMP file template< typename String , typename Image > inline void bmp_read_and_convert_image( const String filename , Image& img ) { read_and_convert_image( filename , img , bmp_tag() ); } /// \ingroup BMP_IO /// \brief Saves the view to a bmp file specified by the given bmp image file name. /// Triggers a compile assert if the view color space and channel depth are not supported by the BMP library or by the I/O extension. /// Throws std::ios_base::failure if it fails to create the file. template< typename String , typename View > inline void bmp_write_view( const String& filename , const View& view ) { write_view( filename , view , bmp_tag() ); } } // namespace gil } // namespace boost #endif // BOOST_GIL_EXTENSION_IO_BMP_IO_OLD_HPP_INCLUDED
[ "rodrigo.benenson@gmailcom" ]
[ [ [ 1, 180 ] ] ]
da24178d835f79e68beb6f763e49fc1772d61ec1
d2fc16640fb0156afb6528e744867e2be4eec02c
/src/stringUtil.h
09e07a328ce73bd5dbe8d939a6248b2aeae8abf4
[]
no_license
wlschmidt/lcdmiscellany
8cd93b5403f9c62a127ddd00c8c5dd577cf72e2f
6623ca05cd978d91580673e6d183f2242bb8eb24
refs/heads/master
2021-01-19T02:30:05.104179
2011-11-02T21:52:07
2011-11-02T21:52:07
48,021,331
1
1
null
2016-07-23T09:08:48
2015-12-15T05:20:15
C++
UTF-8
C++
false
false
6,025
h
#ifndef STRING_UTIL_H #define STRING_UTIL_H #include <string.h> int localwcsicmp(wchar_t *s1, wchar_t*s2); #ifdef strcpy #undef strcpy #endif #ifdef sprintf #undef sprintf #endif //#define wcslen wcslen2 //#define strlen strlen2 /*#define wcscpy wcscpy2 #define strcpy strcpy2 #define wcschr wcschr2 #define strchr strchr2 //*/ #define IsLetter(c) (((c)>='a' && (c)<='z') || ((c)>='A' && (c)<='Z')) #define IsNumber(c) ((c)>='0' && (c)<='9') #define IsHex(c) (IsNumber(c) || ((c)>='A' && (c)<='F') || ((c)>='a' && (c)<='f')) #define IsWhitespace(c) ((c)==' ' || (c)=='\t' || (c)=='\n' || (c)=='\r') inline int IsPunctuation(char c) { return ('.'== c || c==';' || c=='\"' || c=='>' || ','== c || c==':' || c=='\'' || c=='<' || '['== c || c==']' || c=='{' || c=='}' || '='== c || c=='-' || c=='(' || c==')'); } #define KEY_SHIFT 1 #define KEY_CONTROL 2 #define KEY_ALT 4 #define KEY_WIN 8 #define KEY_IGNORE 16 #define KEY_CHARACTER 32 // Remove leading and trailing spaces, make sure zeroed out to // at least minLen characters. template<class T> void LeftJustify(T *s, int minLen=0) { int i=0; int j=0; // remove leading spaces. while (s[i] && (s[i] == ' ' || s[i] == '\t')) i++; while (s[i]) { s[j++] = s[i++]; } // 0 it out to minLen. minLen can be 0. s[j++] = 0; while (j<minLen) { s[j++] = 0; } // remove trailing spaces. j--; while (j && (s[j]== ' ' || s[j] == 0 || s[j] == '\t')) { s[j] = 0; j--; } } inline char LCASE(char c) { if (c > 'Z' || c<'A') return c; return c - 'A'+'a'; } inline char UCASE(char c) { if (c > 'z' || c<'a') return c; return c + 'A'-'a'; } int FormatDuration(char *s, int secs); int substricmp(const char *s1, const char *s2); int substrcmp(const char *s1, const char *s2); inline int stricmp(const unsigned char *s1, const unsigned char *s2) { return stricmp((char*)s1, (char*)s2); } inline int strcmp(const unsigned char *s1, const unsigned char *s2) { return strcmp((char*)s1, (char*)s2); } int utf8stricmp(const unsigned char *s1, const unsigned char *s2); wchar_t *wcsistr(wchar_t *s1, wchar_t *s2); void FormatDataSize (char *out, double d, int min=0, int extra=0, int extension=0); __forceinline void FormatBytes (char *s, double b, int min=2, int extra = 0, int extension = 0) { FormatDataSize(s, b, min, extra, extension); //size_t i = strlen(s); //if (s[i-2] == 'B') s[i-1] = 0; } /* __forceinline void FormatBytesPerSecond (char *s, double b, int min=1) { FormatDataSize(s, b, "/s", 2, min); } //*/ char *localstristr(char *s, char *s2); #define UCASE(x) ((x)>='a' && (x) <= 'z' ? (x)-'a'+'A' : (x)) #define LCASE(x) ((x)>='A' && (x) <= 'Z' ? (x)-'A'+'a' : (x)) #define IsLowercase(x) ((x)>='a' && (x)<='z') #define IsUppercase(x) ((x)>='A' && (x)<='Z') template<class T> inline int StrLen(T *s) { int i=0; for (; s[i]; i++); return i; } template<class T> inline int Compare(T *s1, T *s2) { int i=0; for (; s1[i]; i++) { if (s1[i] != s2[i]) break; } if (s1[i] == s2[i]) return 0; return (s1[i] > s2[i])*2 - 1; } template<class T> inline int CompareSubstringNoCase(T *s1, T *s2) { int i=0; for (; s2[i]; i++) { if (UCASE(s1[i]) != UCASE(s2[i])) break; } if (0 == s2[i]) return 0; return (UCASE(s1[i]) > UCASE(s2[i]))*2 - 1; } template<class T> inline int CompareSubstring(T *s1, T *s2) { int i=0; for (; s2[i]; i++) { if (s1[i] != s2[i]) break; } if (0 == s2[i]) return 0; return (s1[i] > s2[i])*2 - 1; } template<class T> inline int CompareSubstringReverse(T *s1, T *s2) { int i=0; for (; s2[i]; i--) { if (s1[i] != s2[i]) break; } if (0 == s2[i]) return 0; return (s1[i] > s2[i])*2 - 1; } template<class T> inline int ReverseCompare(T *s1, T *s2) { int i=0; for (; s1[i]; i--) { if (s1[i] != s2[i]) break; } if (s1[i] == s2[i]) return 0; return (s1[i] > s2[i])*2 - 1; } void *memdup (const void *mem, size_t size); #define WHITESPACE(x) ((x)==' ' ||(x)=='\t' ||(x)=='\n' ||(x)=='\r') char ** parseArgs(char *s, int *argc, char *split); // Only works on values from 0 to 999 void GenericDisplay (char *& start, char *&out, int val); __int64 strtoi64(const char *s, char **end, int base); inline __int64 strtoi64(const unsigned char *s, unsigned char **end, int base) { return strtoi64((const char*)s, (char**)end, base); } #define strtoul(x,y,z) ((unsigned int)strtoi64(x,y,z)); /* inline unsigned int wcslen(const wchar_t *s) { const wchar_t *s2 = s; while (*s2) s2++; return (unsigned int)(s2 - s); } inline unsigned int strlen(const char *s) { const char *s2 = s; while (*s2) s2++; return (unsigned int)(s2 - s); } /* inline wchar_t *wcscpy(wchar_t *s, const wchar_t *s2) { wchar_t *out = s; while (*s2) { *s = *s2; s++; s2++; } *s = 0; return out; } inline void strcpy(char *s, const char *s2) { while (*s2) { *s = *s2; s++; s2++; } *s = 0; } inline wchar_t * wcschr(const wchar_t *s, wchar_t c) { while (*s) { if (*s == c) return (wchar_t*)s; s++; } if (!c) return (wchar_t*)s; return 0; } inline char * strchr(const char *s, char c) { while (*s) { if (*s == c) return (char*)s; s++; } if (!c) return (char*)s; return 0; } //*/ inline unsigned int strlen(const unsigned char *s) { return (unsigned int)strlen((const char*)s); } inline void strcpy(unsigned char *s, const unsigned char *s2) { strcpy((char*)s, (const char*) s2); } inline unsigned char* strchr(const unsigned char *s, unsigned char c) { return (unsigned char*)strchr((const char*)s, (char) c); } inline unsigned char* strdup(const unsigned char *s) { return (unsigned char*)strdup((char*)s); } inline int strncmp(const unsigned char *s1, const unsigned char *s2, size_t len) { return strncmp((const char*)s1, (const char*)s2, len); } int Unescape(unsigned char *s, int len); #endif
[ "mattmenke@88352c64-7129-11de-90d8-1fdda9445408" ]
[ [ [ 1, 261 ] ] ]
fe52568608fd07a8867e2fc9032c038fe4bda8e5
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/geometries/union_of_balls_3/Union_of_balls_3.cpp
65972a0c1524c65212097f5c3e28569b7db4dfed
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
#include "Union_of_balls_3.h" #include "Union_of_balls_3_implement.h" /*extern*/ template class __declspec(dllexport) Union_of_balls_3<Double_kernel>; ///*extern*/ template class __declspec(dllexport) Union_of_balls_3<Exact_kernel>;
[ "balint.miklos@localhost" ]
[ [ [ 1, 5 ] ] ]
f585ee4d0f2b67e6cd8a4bbcebb37ab5bc89992f
cb1c6c586d769f919ed982e9364d92cf0aa956fe
/examples/TRTRenderTest/BoundingBoxViewpointGenerator.cpp
6d9248e5df47b29666e8b2b453c3dcc22c717adb
[]
no_license
jrk/tinyrt
86fd6e274d56346652edbf50f0dfccd2700940a6
760589e368a981f321e5f483f6d7e152d2cf0ea6
refs/heads/master
2016-09-01T18:24:22.129615
2010-01-07T15:19:44
2010-01-07T15:19:44
462,454
3
0
null
null
null
null
UTF-8
C++
false
false
2,999
cpp
//===================================================================================================================== // // BoundingBoxViewpointGenerator.cpp // // Implementation of class: TinyRT::ndingBoxViewpointGenerator // // Part of the TinyRT Raytracing Library. // Author: Joshua Barczak // // Copyright 2008 Joshua Barczak. All rights reserved. // See Doc/LICENSE.txt for terms and conditions. // //===================================================================================================================== #include "TinyRT.h" #include "BoundingBoxViewpointGenerator.h" #include "TestUtils.h" //===================================================================================================================== // // Constructors/Destructors // //===================================================================================================================== //===================================================================================================================== //===================================================================================================================== BoundingBoxViewpointGenerator::BoundingBoxViewpointGenerator( const TinyRT::AxisAlignedBox& rBox, uint32 nViews ) : m_box( rBox ), m_nViews(nViews), m_nViewsLeft(nViews) { } //===================================================================================================================== // // Public Methods // //===================================================================================================================== //===================================================================================================================== //===================================================================================================================== bool BoundingBoxViewpointGenerator::GetViewpoint( TinyRT::Vec3f* pPosition, TinyRT::Vec3f* pLookAt, float* pFOV ) { if( m_nViewsLeft == 0 ) return false; TinyRT::Vec3f vS1 = TinyRT::Vec3f( RandomFloat(), RandomFloat(), RandomFloat() ); TinyRT::Vec3f vS2 = TinyRT::Vec3f( RandomFloat(), RandomFloat(), RandomFloat() ); *pPosition = m_box.Min() + (m_box.Max()-m_box.Min())*vS1; *pLookAt = m_box.Min() + (m_box.Max()-m_box.Min())*vS2; *pFOV = 60.0f; m_nViewsLeft--; return true; } //===================================================================================================================== // // Protected Methods // //===================================================================================================================== //===================================================================================================================== // // Private Methods // //=====================================================================================================================
[ "jbarcz1@6ce04321-59f9-4392-9e3f-c0843787e809" ]
[ [ [ 1, 69 ] ] ]
8eba57e902400974573e25879c985664008f0ac5
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/capcom/ctv.cpp
1272603311cf1898576098f0758115f0139bfb97
[]
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
1,345
cpp
#include "cps.h" // CPS Tile Variants // horizontal/vertical clip rolls unsigned int nCtvRollX=0,nCtvRollY=0; // Add 0x7fff after each pixel/line // If nRollX/Y&0x20004000 both == 0, you can draw the pixel unsigned char *pCtvTile=NULL; // Pointer to tile data int nCtvTileAdd=0; // Amount to add after each tile line unsigned char *pCtvLine=NULL; // Pointer to output bitmap // Include all tile variants: #include "../../generated/ctv.h" static int nLastBpp=0; int CtvReady() { // Set up the CtvDoX functions to point to the correct bpp functions. // Must be called before calling CpstOne #if USE_BPP_RENDERING == 16 memcpy(CtvDoX,CtvDo2,sizeof(CtvDoX)); memcpy(CtvDoXM,CtvDo2m,sizeof(CtvDoXM)); memcpy(CtvDoXB,CtvDo2b,sizeof(CtvDoXB)); #else if (nBurnBpp!=nLastBpp) { if (nBurnBpp==2) { memcpy(CtvDoX,CtvDo2,sizeof(CtvDoX)); memcpy(CtvDoXM,CtvDo2m,sizeof(CtvDoXM)); memcpy(CtvDoXB,CtvDo2b,sizeof(CtvDoXB)); } else if (nBurnBpp==3) { memcpy(CtvDoX,CtvDo3,sizeof(CtvDoX)); memcpy(CtvDoXM,CtvDo3m,sizeof(CtvDoXM)); memcpy(CtvDoXB,CtvDo3b,sizeof(CtvDoXB)); } else if (nBurnBpp==4) { memcpy(CtvDoX,CtvDo4,sizeof(CtvDoX)); memcpy(CtvDoXM,CtvDo4m,sizeof(CtvDoXM)); memcpy(CtvDoXB,CtvDo4b,sizeof(CtvDoXB)); } } nLastBpp=nBurnBpp; #endif return 0; }
[ [ [ 1, 47 ] ] ]
7f2214c555f69f757d18089c7068134d275140a1
17083b919f058848c3eb038eae37effd1a5b0759
/SimpleGL/sgl/FFPProgram.h
66b71f5c25e36bf5f9dfc6cf89ff9d8c2fe14190
[]
no_license
BackupTheBerlios/sgl
e1ce68dfc2daa011bdcf018ddce744698cc7bc5f
2ab6e770dfaf5268c1afa41a77c04ad7774a70ed
refs/heads/master
2021-01-21T12:39:59.048415
2011-10-28T16:14:29
2011-10-28T16:14:29
39,894,148
0
0
null
null
null
null
UTF-8
C++
false
false
2,491
h
#ifndef SIMPLE_GL_FFP_PROGRAM_H #define SIMPLE_GL_FFP_PROGRAM_H #include "Program.h" namespace sgl { /** Program that uses(or emulates) fixed function pipeline */ class FFPProgram : public Program { public: /** Get uniform to setup single 4x4 model view matrix. */ virtual Uniform4x4F* SGL_DLLCALL GetModelViewMatrixUniform() const = 0; /** Get uniform to setup single 4x4 projection matrix. */ virtual Uniform4x4F* SGL_DLLCALL GetProjectionMatrixUniform() const = 0; /** Get uniform to setup array of texture matrices for each sampler. */ virtual Uniform4x4F* SGL_DLLCALL GetTextureMatrixUniform() const = 0; /** Get uniform to setup lighting toggle. */ virtual UniformI* SGL_DLLCALL GetLightingToggleUniform() const = 0; /** Get uniform to setup array of light toggles. */ virtual UniformI* SGL_DLLCALL GetLightToggleUniform() const = 0; /** Get uniform to setup array of light positions. */ virtual Uniform4F* SGL_DLLCALL GetLightPositionUniform() const = 0; /** Get uniform to setup array of light directions. */ virtual Uniform4F* SGL_DLLCALL GetLightDirectionUniform() const = 0; /** Get uniform to setup array of light ambient colors. */ virtual Uniform4F* SGL_DLLCALL GetLightAmbientUniform() const = 0; /** Get uniform to setup array of light diffuse colors. */ virtual Uniform4F* SGL_DLLCALL GetLightDiffuseUniform() const = 0; /** Get uniform to setup array of light specular colors. */ virtual Uniform4F* SGL_DLLCALL GetLightSpecularUniform() const = 0; /** Get uniform to setup ambient lighting color. */ virtual Uniform4F* SGL_DLLCALL GetAmbientUniform() const = 0; /** Get uniform to setup material ambient color. */ virtual Uniform4F* SGL_DLLCALL GetMaterialAmbientUniform() const = 0; /** Get uniform to setup material diffuse color. */ virtual Uniform4F* SGL_DLLCALL GetMaterialDiffuseUniform() const = 0; /** Get uniform to setup material emission color. */ virtual Uniform4F* SGL_DLLCALL GetMaterialEmissionUniform() const = 0; /** Get uniform to setup material specular color. */ virtual Uniform4F* SGL_DLLCALL GetMaterialSpecularUniform() const = 0; /** Get uniform to setup material shininess. */ virtual UniformF* SGL_DLLCALL GetMaterialShininessUniform() const = 0; virtual ~FFPProgram() {} }; } // namepace sgl #endif // SIMPLE_GL_FFP_PROGRAM_H
[ "devnull@localhost" ]
[ [ [ 1, 66 ] ] ]
e8f1ea4e03bfbe84f76120b77c85425e92aca55a
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Modules/NavTask/GuiCommandHandler.h
8ff10c44a46a5bbb44399f6877de96094fc8dc3f
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,698
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. */ #include "GuiFileOperation.h" #ifndef MODULE_GuiCommandHandler_H #define MODULE_GuiCommandHandler_H namespace isab { class GuiCommandHandler { public: GuiCommandHandler(class NavTask* nt); ~GuiCommandHandler(); void HandleOperationSelect(class GuiFileOperationSelect* op); void HandleOperationSelectReply(class GuiFileOperationSelectReply* op); void HandleOperationConfirm(class GuiFileOperationConfirm* op); void HandleOperationConfirmReply(class GuiFileOperationConfirmReply* op); void HandleOperationCommand(class GuiFileOperationCommand* op); private: class NavTask* m_navTask; //getDriveList is implemented in architecture specific files. void getDriveList(LocationVector* locations); void findSavedRoutes(LocationVector* locations, LocationVector* driveList); char* createFullPathName_new(const char* sDir, const char* sName); char* addFileExtension_new(const char* sFileName); }; } /* namespace isab */ #endif /* MODULE_GuiCommandHandler_H */
[ [ [ 1, 44 ] ] ]
6eb0bd53dab521565f12363601433ae103938ec7
39d36b98402c4ad75aadee357295b92b2f0c0d3d
/src/fceu/ines.cpp
13a40cedb251c12ed5b134fcd278d0053ddd670a
[]
no_license
xxsl/fceux-ps3
9eda7c1ee49e69f14b695ddda904b1cc3a79d51a
dc0674a4b8e8c52af6969c8d59330c072486107c
refs/heads/master
2021-01-20T04:26:05.430450
2011-01-02T21:22:47
2011-01-02T21:22:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,638
cpp
/* FCE Ultra - NES/Famicom Emulator * * Copyright notice for this file: * Copyright (C) 1998 BERO * Copyright (C) 2002 Xodnizel * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _USE_SHARED_MEMORY_ #include <windows.h> #endif #include "types.h" #include "x6502.h" #include "fceu.h" #include "cart.h" #include "ppu.h" #define INESPRIV #include "ines.h" #include "unif.h" #include "state.h" #include "file.h" #include "utils/general.h" #include "utils/memory.h" #include "utils/crc32.h" #include "utils/md5.h" #include "cheat.h" #include "vsuni.h" #include "driver.h" extern SFORMAT FCEUVSUNI_STATEINFO[]; //mbg merge 6/29/06 - these need to be global uint8 *trainerpoo=0; uint8 *ROM = NULL; uint8 *VROM = NULL; iNES_HEADER head ; #ifdef _USE_SHARED_MEMORY_ HANDLE mapROM = NULL, mapVROM = NULL; #endif #ifdef GEKKO CartInfo iNESCart; #else static CartInfo iNESCart; #endif uint8 iNESMirroring=0; uint16 iNESCHRBankList[8]={0,0,0,0,0,0,0,0}; int32 iNESIRQLatch=0,iNESIRQCount=0; uint8 iNESIRQa=0; uint32 ROM_size=0; uint32 VROM_size=0; char LoadedRomFName[2048]; //mbg merge 7/17/06 added static void iNESPower(void); static int NewiNES_Init(int num); void (*MapClose)(void); void (*MapperReset)(void); static int MapperNo=0; /* MapperReset() is called when the NES is reset(with the reset button). Mapperxxx_init is called when the NES has been powered on. */ static DECLFR(TrainerRead) { return(trainerpoo[A&0x1FF]); } void iNESGI(GI h) //bbit edited: removed static keyword { switch(h) { case GI_RESETSAVE: FCEU_ClearGameSave(&iNESCart); break; case GI_RESETM2: if(MapperReset) MapperReset(); if(iNESCart.Reset) iNESCart.Reset(); break; case GI_POWER: if(iNESCart.Power) iNESCart.Power(); if(trainerpoo) { int x; for(x=0;x<512;x++) { X6502_DMW(0x7000+x,trainerpoo[x]); if(X6502_DMR(0x7000+x)!=trainerpoo[x]) { SetReadHandler(0x7000,0x71FF,TrainerRead); break; } } } break; case GI_CLOSE: { FCEU_SaveGameSave(&iNESCart); if(iNESCart.Close) iNESCart.Close(); #ifdef _USE_SHARED_MEMORY_ if(ROM) { if(mapROM) { CloseHandle(mapROM); mapROM = NULL; UnmapViewOfFile(ROM); } else free(ROM); ROM = NULL; } if(VROM) { if(mapVROM) { CloseHandle(mapVROM); mapVROM = NULL; UnmapViewOfFile(VROM); } else free(VROM); VROM = NULL; } #else if(ROM) {free(ROM); ROM = NULL;} if(VROM) {free(VROM); VROM = NULL;} #endif if(MapClose) MapClose(); if(trainerpoo) {FCEU_gfree(trainerpoo);trainerpoo=0;} } break; } } uint32 iNESGameCRC32=0; struct CRCMATCH { uint32 crc; char *name; }; struct INPSEL { uint32 crc32; ESI input1; ESI input2; ESIFC inputfc; }; static void SetInput(void) { static struct INPSEL moo[]= { {0x3a1694f9,SI_GAMEPAD,SI_GAMEPAD,SIFC_4PLAYER}, // Nekketsu Kakutou Densetsu {0xc3c0811d,SI_GAMEPAD,SI_GAMEPAD,SIFC_OEKAKIDS}, // The two "Oeka Kids" games {0x9d048ea4,SI_GAMEPAD,SI_GAMEPAD,SIFC_OEKAKIDS}, // {0xaf4010ea,SI_GAMEPAD,SI_POWERPADB,SIFC_UNSET}, // World Class Track Meet {0xd74b2719,SI_GAMEPAD,SI_POWERPADB,SIFC_UNSET}, // Super Team Games {0x61d86167,SI_GAMEPAD,SI_POWERPADB,SIFC_UNSET}, // Street Cop {0x6435c095,SI_GAMEPAD,SI_POWERPADB,SIFC_UNSET}, // Short Order/Eggsplode {0x47232739,SI_GAMEPAD,SI_GAMEPAD,SIFC_TOPRIDER}, // Top Rider {0x48ca0ee1,SI_GAMEPAD,SI_GAMEPAD,SIFC_BWORLD}, // Barcode World {0x9f8f200a,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERA}, // Super Mogura Tataki!! - Pokkun Moguraa {0x9044550e,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERA}, // Rairai Kyonshizu {0x2f128512,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERA}, // Jogging Race {0x60ad090a,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERA}, // Athletic World {0x8a12a7d9,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERB}, // Totsugeki Fuuun Takeshi Jou {0xea90f3e2,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERB}, // Running Stadium {0x370ceb65,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERB}, // Meiro Dai Sakusen // Bad dump? {0x69ffb014,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERB}, // Fuun Takeshi Jou 2 {0x6cca1c1f,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERB}, // Dai Undoukai {0x29de87af,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERB}, // Aerobics Studio {0xbba58be5,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERB}, // Family Trainer: Manhattan Police {0xea90f3e2,SI_GAMEPAD,SI_GAMEPAD,SIFC_FTRAINERB}, // Family Trainer: Running Stadium {0xd9f45be9,SI_GAMEPAD,SI_GAMEPAD,SIFC_QUIZKING}, // Gimme a Break ... {0x1545bd13,SI_GAMEPAD,SI_GAMEPAD,SIFC_QUIZKING}, // Gimme a Break ... 2 {0x7b44fb2a,SI_GAMEPAD,SI_GAMEPAD,SIFC_MAHJONG}, // Ide Yousuke Meijin no Jissen Mahjong 2 {0x9fae4d46,SI_GAMEPAD,SI_GAMEPAD,SIFC_MAHJONG}, // Ide Yousuke Meijin no Jissen Mahjong {0x980be936,SI_GAMEPAD,SI_GAMEPAD,SIFC_HYPERSHOT}, // Hyper Olympic {0x21f85681,SI_GAMEPAD,SI_GAMEPAD,SIFC_HYPERSHOT}, // Hyper Olympic (Gentei Ban) {0x915a53a7,SI_GAMEPAD,SI_GAMEPAD,SIFC_HYPERSHOT}, // Hyper Sports {0xad9c63e2,SI_GAMEPAD,SI_UNSET,SIFC_SHADOW}, // Space Shadow {0x24598791,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Duck Hunt {0xff24d794,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Hogan's Alley {0xbeb8ab01,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Gumshoe {0xde8fd935,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // To the Earth {0xedc3662b,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Operation Wolf {0x2a6559a1,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Operation Wolf (J) {0x4e959173,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Gotcha! - The Sport! {0x23d17f5e,SI_GAMEPAD,SI_ZAPPER,SIFC_NONE}, // The Lone Ranger {0xb8b9aca3,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Wild Gunman {0x5112dc21,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Wild Gunman {0x4318a2f8,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Barker Bill's Trick Shooting {0x5ee6008e,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Mechanized Attack {0x3e58a87e,SI_UNSET,SI_ZAPPER,SIFC_NONE}, // Freedom Force {0xe9a7fe9e,SI_UNSET,SI_MOUSE,SIFC_NONE}, // Educational Computer 2000 //mbg merge 7/17/06 added -- appears to be from newer MM build {0x851eb9be,SI_GAMEPAD,SI_ZAPPER,SIFC_NONE}, // Shooting Range {0x74bea652,SI_GAMEPAD,SI_ZAPPER,SIFC_NONE}, // Supergun 3-in-1 {0x32fb0583,SI_UNSET,SI_ARKANOID,SIFC_NONE}, // Arkanoid(NES) {0xd89e5a67,SI_UNSET,SI_UNSET,SIFC_ARKANOID}, // Arkanoid (J) {0x0f141525,SI_UNSET,SI_UNSET,SIFC_ARKANOID}, // Arkanoid 2(J) {0x912989dc,SI_UNSET,SI_UNSET,SIFC_FKB}, // Playbox BASIC {0xf7606810,SI_UNSET,SI_UNSET,SIFC_FKB}, // Family BASIC 2.0A {0x895037bc,SI_UNSET,SI_UNSET,SIFC_FKB}, // Family BASIC 2.1a {0xb2530afc,SI_UNSET,SI_UNSET,SIFC_FKB}, // Family BASIC 3.0 {0x82f1fb96,SI_UNSET,SI_UNSET,SIFC_SUBORKB}, // Subor 1.0 Russian {0xabb2f974,SI_UNSET,SI_UNSET,SIFC_SUBORKB}, // Study and Game 32-in-1 {0xd5d6eac4,SI_UNSET,SI_UNSET,SIFC_SUBORKB}, // Edu (As) {0x589b6b0d,SI_UNSET,SI_UNSET,SIFC_SUBORKB}, // SuporV20 {0x5e073a1b,SI_UNSET,SI_UNSET,SIFC_SUBORKB}, // Supor English (Chinese) {0x8b265862,SI_UNSET,SI_UNSET,SIFC_SUBORKB}, {0x41401c6d,SI_UNSET,SI_UNSET,SIFC_SUBORKB}, // SuporV40 {0x41ef9ac4,SI_UNSET,SI_UNSET,SIFC_SUBORKB}, {0x368c19a8,SI_UNSET,SI_UNSET,SIFC_SUBORKB}, // LIKO Study Cartridge {0x543ab532,SI_UNSET,SI_UNSET,SIFC_SUBORKB}, // LIKO Color Lines {0,SI_UNSET,SI_UNSET,SIFC_UNSET} }; int x=0; while(moo[x].input1>=0 || moo[x].input2>=0 || moo[x].inputfc>=0) { if(moo[x].crc32==iNESGameCRC32) { GameInfo->input[0]=moo[x].input1; GameInfo->input[1]=moo[x].input2; GameInfo->inputfc=moo[x].inputfc; break; } x++; } } #define INESB_INCOMPLETE 1 #define INESB_CORRUPT 2 #define INESB_HACKED 4 struct BADINF { uint64 md5partial; char *name; uint32 type; }; static struct BADINF BadROMImages[]= { #include "ines-bad.h" }; void CheckBad(uint64 md5partial) { int x; x=0; //printf("0x%llx\n",md5partial); while(BadROMImages[x].name) { if(BadROMImages[x].md5partial == md5partial) { FCEU_PrintError("The copy game you have loaded, \"%s\", is bad, and will not work properly on FCE Ultra.", BadROMImages[x].name); return; } x++; } } struct CHINF { uint32 crc32; int32 mapper; int32 mirror; }; void MapperInit() { if(NewiNES_Init(MapperNo)) { } else { iNESCart.Power=iNESPower; if(head.ROM_type&2) { iNESCart.SaveGame[0]=WRAM; iNESCart.SaveGameLen[0]=8192; } } } static void CheckHInfo(void) { /* ROM images that have the battery-backed bit set in the header that really don't have battery-backed RAM is not that big of a problem, so I'll treat this differently by only listing games that should have battery-backed RAM. Lower 64 bits of the MD5 hash. */ static uint64 savie[]= { 0x498c10dc463cfe95LL, /* Battle Fleet */ 0x6917ffcaca2d8466LL, /* Famista '90 */ 0xd63dcc68c2b20adcLL, /* Final Fantasy J */ 0x012df596e2b31174LL, /* Final Fantasy 1+2 */ 0xf6b359a720549ecdLL, /* Final Fantasy 2 */ 0x5a30da1d9b4af35dLL, /* Final Fantasy 3 */ 0x2ee3417ba8b69706LL, /* Hydlide 3*/ 0xebbce5a54cf3ecc0LL, /* Justbreed */ 0x6a858da551ba239eLL, /* Kaijuu Monogatari */ 0xa40666740b7d22feLL, /* Mindseeker */ 0x77b811b2760104b9LL, /* Mouryou Senki Madara */ 0x11b69122efe86e8cLL, /* RPG Jinsei Game */ 0xa70b495314f4d075LL, /* Ys 3 */ 0xc04361e499748382LL, /* AD&D Heroes of the Lance */ 0xb72ee2337ced5792LL, /* AD&D Hillsfar */ 0x2b7103b7a27bd72fLL, /* AD&D Pool of Radiance */ 0x854d7947a3177f57LL, /* Crystalis */ 0xb0bcc02c843c1b79LL, /* DW */ 0x4a1f5336b86851b6LL, /* DW */ 0x2dcf3a98c7937c22LL, /* DW 2 */ 0x733026b6b72f2470LL, /* Dw 3 */ 0x98e55e09dfcc7533LL, /* DW 4*/ 0x8da46db592a1fcf4LL, /* Faria */ 0x91a6846d3202e3d6LL, /* Final Fantasy */ 0xedba17a2c4608d20LL, /* "" */ 0x94b9484862a26cbaLL, /* Legend of Zelda */ 0x04a31647de80fdabLL, /* "" */ 0x9aa1dc16c05e7de5LL, /* Startropics */ 0x1b084107d0878bd0LL, /* Startropics 2*/ 0x836c0ff4f3e06e45LL, /* Zelda 2 */ 0x82000965f04a71bbLL, /* Mirai Shinwa Jarvas */ 0 /* Abandon all hope if the game has 0 in the lower 64-bits of its MD5 hash */ }; static struct CHINF moo[]= { #include "ines-correct.h" }; int tofix=0; int x; uint64 partialmd5=0; for(x=0;x<8;x++) { partialmd5 |= (uint64)iNESCart.MD5[15-x] << (x*8); //printf("%16llx\n",partialmd5); } CheckBad(partialmd5); x=0; do { if(moo[x].crc32==iNESGameCRC32) { if(moo[x].mapper>=0) { if(moo[x].mapper&0x800 && VROM_size) { VROM_size=0; #ifdef _USE_SHARED_MEMORY_ if(mapVROM) { CloseHandle(mapVROM); UnmapViewOfFile(VROM); mapVROM = NULL; } else { free(VROM); } #else free(VROM); #endif VROM = NULL; tofix|=8; } if(MapperNo!=(moo[x].mapper&0xFF)) { tofix|=1; MapperNo=moo[x].mapper&0xFF; } } if(moo[x].mirror>=0) { if(moo[x].mirror==8) { if(Mirroring==2) /* Anything but hard-wired(four screen). */ { tofix|=2; Mirroring=0; } } else if(Mirroring!=moo[x].mirror) { if(Mirroring!=(moo[x].mirror&~4)) if((moo[x].mirror&~4)<=2) /* Don't complain if one-screen mirroring needs to be set(the iNES header can't hold this information). */ tofix|=2; Mirroring=moo[x].mirror; } } break; } x++; } while(moo[x].mirror>=0 || moo[x].mapper>=0); x=0; while(savie[x] != 0) { if(savie[x] == partialmd5) { if(!(head.ROM_type&2)) { tofix|=4; head.ROM_type|=2; } } x++; } /* Games that use these iNES mappers tend to have the four-screen bit set when it should not be. */ if((MapperNo==118 || MapperNo==24 || MapperNo==26) && (Mirroring==2)) { Mirroring=0; tofix|=2; } /* Four-screen mirroring implicitly set. */ if(MapperNo==99) Mirroring=2; if(tofix) { char gigastr[768]; strcpy(gigastr,"The iNES header contains incorrect information. For now, the information will be corrected in RAM. "); if(tofix&1) sprintf(gigastr+strlen(gigastr),"The mapper number should be set to %d. ",MapperNo); if(tofix&2) { char *mstr[3]={"Horizontal","Vertical","Four-screen"}; sprintf(gigastr+strlen(gigastr),"Mirroring should be set to \"%s\". ",mstr[Mirroring&3]); } if(tofix&4) strcat(gigastr,"The battery-backed bit should be set. "); if(tofix&8) strcat(gigastr,"This game should not have any CHR ROM. "); strcat(gigastr,"\n"); FCEU_printf("%s",gigastr); } } typedef struct { int mapper; void (*init)(CartInfo *); } NewMI; //this is for games that is not the a power of 2 //mapper based for now... //not really accurate but this works since games //that are not in the power of 2 tends to come //in obscure mappers themselves which supports such //size static int not_power2[] = { 228 }; typedef struct { char* name; int number; void (*init)(CartInfo *); } BMAPPINGLocal; static BMAPPINGLocal bmap[] = { {"NROM", 0, NROM_Init}, {"MMC1", 1, Mapper1_Init}, {"UNROM", 2, UNROM_Init}, {"CNROM", 3, CNROM_Init}, {"MMC3", 4, Mapper4_Init}, {"MMC5", 5, Mapper5_Init}, {"ANROM", 7, ANROM_Init}, {"Color Dreams", 11, Mapper11_Init}, {"", 12, Mapper12_Init}, {"CPROM", 13, CPROM_Init}, {"100-in1", 15, Mapper15_Init}, {"Bandai", 16, Mapper16_Init}, {"Namcot 106", 19, Mapper19_Init}, {"Konami VRC2 type B", 23, Mapper23_Init}, {"Wario Land 2", 35, UNLSC127_Init}, // Wario Land 2 {"TXC Policeman", 36, Mapper36_Init}, // TXC Policeman {"", 37, Mapper37_Init}, {"Bit Corp. Crime Busters", 38, Mapper38_Init}, // Bit Corp. Crime Busters {"", 43, Mapper43_Init}, {"", 44, Mapper44_Init}, {"", 45, Mapper45_Init}, {"", 47, Mapper47_Init}, {"", 49, Mapper49_Init}, {"", 52, Mapper52_Init}, {"", 57, Mapper57_Init}, {"", 58, BMCGK192_Init}, {"", 60, BMCD1038_Init}, {"MHROM", 66, MHROM_Init}, {"Sunsoft Mapper #4", 68, Mapper68_Init}, {"", 70, Mapper70_Init}, {"", 74, Mapper74_Init}, {"Irem 74HC161/32", 78, Mapper78_Init}, {"", 87, Mapper87_Init}, {"", 88, Mapper88_Init}, {"", 90, Mapper90_Init}, {"Sunsoft UNROM", 93, SUNSOFT_UNROM_Init}, {"", 94, Mapper94_Init}, {"", 95, Mapper95_Init}, {"", 101, Mapper101_Init}, {"", 103, Mapper103_Init}, {"", 105, Mapper105_Init}, {"", 106, Mapper106_Init}, {"", 107, Mapper107_Init}, {"", 108, Mapper108_Init}, {"", 112, Mapper112_Init}, {"", 113, Mapper113_Init}, {"", 114, Mapper114_Init}, {"", 115, Mapper115_Init}, {"", 116, Mapper116_Init}, // {116, UNLSL1632_Init}, {"", 117, Mapper117_Init}, {"TSKROM", 118, TKSROM_Init}, {"", 119, Mapper119_Init}, {"", 120, Mapper120_Init}, {"", 121, Mapper121_Init}, {"UNLH2288", 123, UNLH2288_Init}, {"UNL22211", 132, UNL22211_Init}, {"SA72008", 133, SA72008_Init}, {"", 134, Mapper134_Init}, {"TCU02", 136, TCU02_Init}, {"S8259D", 137, S8259D_Init}, {"S8259B", 138, S8259B_Init}, {"S8259C", 139, S8259C_Init}, {"", 140, Mapper140_Init}, {"S8259A", 141, S8259A_Init}, {"UNLKS7032", 142, UNLKS7032_Init}, {"TCA01", 143, TCA01_Init}, {"", 144, Mapper144_Init}, {"SA72007", 145, SA72007_Init}, {"SA0161M", 146, SA0161M_Init}, {"TCU01", 147, TCU01_Init}, {"SA0037", 148, SA0037_Init}, {"SA0036", 149, SA0036_Init}, {"S74LS374N", 150, S74LS374N_Init}, {"", 152, Mapper152_Init}, {"", 153, Mapper153_Init}, {"", 154, Mapper154_Init}, {"", 155, Mapper155_Init}, {"SA009", 160, SA009_Init}, {"", 163, Mapper163_Init}, {"", 164, Mapper164_Init}, {"", 165, Mapper165_Init}, // {169, Mapper169_Init}, {"", 171, Mapper171_Init}, {"", 172, Mapper172_Init}, {"", 173, Mapper173_Init}, {"", 175, Mapper175_Init}, {"BMCFK23C", 176, BMCFK23C_Init}, {"", 177, Mapper177_Init}, {"", 178, Mapper178_Init}, {"", 180, Mapper180_Init}, {"", 181, Mapper181_Init}, {"", 182, Mapper182_Init}, {"", 183, Mapper183_Init}, {"", 184, Mapper184_Init}, {"", 185, Mapper185_Init}, {"", 186, Mapper186_Init}, {"", 187, Mapper187_Init}, {"", 188, Mapper188_Init}, {"", 189, Mapper189_Init}, {"", 191, Mapper191_Init}, {"", 192, Mapper192_Init}, {"", 194, Mapper194_Init}, {"", 195, Mapper195_Init}, {"", 196, Mapper196_Init}, {"", 197, Mapper197_Init}, {"", 198, Mapper198_Init}, {"", 199, Mapper199_Init}, {"", 200, Mapper200_Init}, {"", 205, Mapper205_Init}, {"DEIROM", 206, DEIROM_Init}, {"", 208, Mapper208_Init}, {"", 209, Mapper209_Init}, {"", 210, Mapper210_Init}, {"", 211, Mapper211_Init}, {"", 215, Mapper215_Init}, {"", 216, Mapper216_Init}, {"", 217, Mapper217_Init}, {"UNLA9746", 219, UNLA9746_Init}, {"OneBus", 220, UNLOneBus_Init}, // {220, BMCFK23C_Init}, // {220, UNL3DBlock_Init}, // {220, UNLTF1201_Init}, // {220, TCU02_Init}, // {220, UNLCN22M_Init}, // {220, BMCT2271_Init}, // {220, UNLDANCE_Init}, {"UNLN625092", 221, UNLN625092_Init}, {"", 222, Mapper222_Init}, {"", 226, Mapper226_Init}, {"", 235, Mapper235_Init}, {"UNL6035052", 238, UNL6035052_Init}, {"", 240, Mapper240_Init}, {"S74LS374NA", 243, S74LS374NA_Init}, {"", 245, Mapper245_Init}, {"", 249, Mapper249_Init}, {"", 250, Mapper250_Init}, {"", 253, Mapper253_Init}, {"", 254, Mapper254_Init}, {"", 0, 0} }; int iNESLoad(const char *name, FCEUFILE *fp, int OverwriteVidMode) { struct md5_context md5; if(FCEU_fread(&head,1,16,fp)!=16) return 0; if(memcmp(&head,"NES\x1a",4)) return 0; head.cleanup(); memset(&iNESCart,0,sizeof(iNESCart)); MapperNo = (head.ROM_type>>4); MapperNo|=(head.ROM_type2&0xF0); Mirroring = (head.ROM_type&1); // int ROM_size=0; if(!head.ROM_size) { // FCEU_PrintError("No PRG ROM!"); // return(0); ROM_size=256; //head.ROM_size++; } else ROM_size=uppow2(head.ROM_size); // ROM_size = head.ROM_size; VROM_size = head.VROM_size; int round = true; for (int i = 0; i != sizeof(not_power2)/sizeof(not_power2[0]); ++i) { //for games not to the power of 2, so we just read enough //prg rom from it, but we have to keep ROM_size to the power of 2 //since PRGCartMapping wants ROM_size to be to the power of 2 //so instead if not to power of 2, we just use head.ROM_size when //we use FCEU_read if (not_power2[i] == MapperNo) { round = false; break; } } if(VROM_size) VROM_size=uppow2(VROM_size); if(head.ROM_type&8) Mirroring=2; #ifdef _USE_SHARED_MEMORY_ mapROM = CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE, 0, ROM_size<<14,"fceu.ROM"); if(mapROM == NULL || GetLastError() == ERROR_ALREADY_EXISTS) { if((ROM = (uint8 *)FCEU_malloc(ROM_size<<14)) == NULL) return 0; } else { if((ROM = (uint8 *)MapViewOfFile(mapROM, FILE_MAP_WRITE, 0, 0, 0)) == NULL) { CloseHandle(mapROM); mapROM = NULL; if((ROM = (uint8 *)FCEU_malloc(ROM_size<<14)) == NULL) return 0; } } if(VROM_size) { mapVROM = CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE, 0, VROM_size<<13,"fceu.VROM"); if(mapVROM == NULL || GetLastError() == ERROR_ALREADY_EXISTS) { if((VROM=(uint8 *)FCEU_malloc(VROM_size<<13)) == NULL) { if(mapROM) { UnmapViewOfFile(mapROM); mapROM = NULL; CloseHandle(ROM); } else free(ROM); ROM = NULL; return 0; } } else { if((VROM = (uint8 *)MapViewOfFile(mapVROM, FILE_MAP_WRITE, 0, 0, 0)) == NULL) { CloseHandle(mapVROM); mapVROM = NULL; if((VROM=(uint8 *)FCEU_malloc(VROM_size<<13)) == NULL) { if(mapROM) { UnmapViewOfFile(mapROM); mapROM = NULL; CloseHandle(ROM); } else free(ROM); ROM = NULL; return 0; } } } } #else if((ROM = (uint8 *)FCEU_malloc(ROM_size<<14)) == NULL) return 0; if(VROM_size) { if((VROM = (uint8 *)FCEU_malloc(VROM_size<<13)) == NULL) { free(ROM); ROM = NULL; return 0; } } #endif memset(ROM,0xFF,ROM_size<<14); if(VROM_size) memset(VROM,0xFF,VROM_size<<13); if(head.ROM_type&4) /* Trainer */ { trainerpoo=(uint8 *)FCEU_gmalloc(512); FCEU_fread(trainerpoo,512,1,fp); } ResetCartMapping(); ResetExState(0,0); SetupCartPRGMapping(0,ROM,ROM_size*0x4000,0); // SetupCartPRGMapping(1,WRAM,8192,1); FCEU_fread(ROM,0x4000,(round) ? ROM_size : head.ROM_size,fp); if(VROM_size) FCEU_fread(VROM,0x2000,head.VROM_size,fp); md5_starts(&md5); md5_update(&md5,ROM,ROM_size<<14); iNESGameCRC32=CalcCRC32(0,ROM,ROM_size<<14); if(VROM_size) { iNESGameCRC32=CalcCRC32(iNESGameCRC32,VROM,VROM_size<<13); md5_update(&md5,VROM,VROM_size<<13); } md5_finish(&md5,iNESCart.MD5); memcpy(&GameInfo->MD5,&iNESCart.MD5,sizeof(iNESCart.MD5)); iNESCart.CRC32=iNESGameCRC32; FCEU_printf(" PRG ROM: %3d x 16KiB\n CHR ROM: %3d x 8KiB\n ROM CRC32: 0x%08lx\n", (round) ? ROM_size : head.ROM_size, head.VROM_size,iNESGameCRC32); { int x; FCEU_printf(" ROM MD5: 0x"); for(x=0;x<16;x++) FCEU_printf("%02x",iNESCart.MD5[x]); FCEU_printf("\n"); } char* mappername = "Not Listed"; for(int mappertest=0;mappertest< (sizeof bmap / sizeof bmap[0]) - 1;mappertest++) { if (bmap[mappertest].number == MapperNo) { mappername = bmap[mappertest].name; break; } } FCEU_printf(" Mapper #: %d\n Mapper name: %s\n Mirroring: %s\n", MapperNo, mappername, Mirroring==2?"None (Four-screen)":Mirroring?"Vertical":"Horizontal"); FCEU_printf(" Battery-backed: %s\n", (head.ROM_type&2)?"Yes":"No"); FCEU_printf(" Trained: %s\n", (head.ROM_type&4)?"Yes":"No"); // (head.ROM_type&8) = Mirroring: None(Four-screen) SetInput(); CheckHInfo(); { int x; uint64 partialmd5=0; for(x=0;x<8;x++) { partialmd5 |= (uint64)iNESCart.MD5[7-x] << (x*8); } FCEU_VSUniCheck(partialmd5, &MapperNo, &Mirroring); } /* Must remain here because above functions might change value of VROM_size and free(VROM). */ if(VROM_size) SetupCartCHRMapping(0,VROM,VROM_size*0x2000,0); if(Mirroring==2) SetupCartMirroring(4,1,ExtraNTARAM); else if(Mirroring>=0x10) SetupCartMirroring(2+(Mirroring&1),1,0); else SetupCartMirroring(Mirroring&1,(Mirroring&4)>>2,0); iNESCart.battery=(head.ROM_type&2)?1:0; iNESCart.mirror=Mirroring; //if(MapperNo != 18) { // if(ROM) free(ROM); // if(VROM) free(VROM); // ROM=VROM=0; // return(0); // } GameInfo->mappernum = MapperNo; MapperInit(); FCEU_LoadGameSave(&iNESCart); strcpy(LoadedRomFName,name); //bbit edited: line added // Extract Filename only. Should account for Windows/Unix this way. if (strrchr(name, '/')) { name = strrchr(name, '/') + 1; } else if(strrchr(name, '\\')) { name = strrchr(name, '\\') + 1; } GameInterface=iNESGI; FCEU_printf("\n"); // since apparently the iNES format doesn't store this information, // guess if the settings should be PAL or NTSC from the ROM name // TODO: MD5 check against a list of all known PAL games instead? if(OverwriteVidMode) { if(strstr(name,"(E)") || strstr(name,"(e)") || strstr(name,"(F)") || strstr(name,"(f)") || strstr(name,"(G)") || strstr(name,"(g)") || strstr(name,"(I)") || strstr(name,"(i)") //BEGIN OF FCEU PS3: Had to expand this || strstr(name,"(Europe)") || strstr(name, "(Australia)") || strstr(name,"(France)") || strstr(name, "(Germany)") || strstr(name,"(Sweden)") || strstr(name, "(En, Fr, De)") || strstr(name,"(Italy)")) //END OF FCEU PS3 FCEUI_SetVidSystem(1); else FCEUI_SetVidSystem(0); } return 1; } //bbit edited: the whole function below was added int iNesSave(){ FILE *fp; char name[2048]; if(GameInfo->type != GIT_CART)return 0; if(GameInterface!=iNESGI)return 0; strcpy(name,LoadedRomFName); if (strcmp(name+strlen(name)-4,".nes") != 0) { //para edit strcat(name,".nes"); } fp = fopen(name,"wb"); if(fwrite(&head,1,16,fp)!=16)return 0; if(head.ROM_type&4) /* Trainer */ { fwrite(trainerpoo,512,1,fp); } fwrite(ROM,0x4000,ROM_size,fp); if(head.VROM_size)fwrite(VROM,0x2000,head.VROM_size,fp); fclose(fp); return 1; } int iNesSaveAs(char* name) { //adelikat: TODO: iNesSave() and this have pretty much the same code, outsource the common code to a single function FILE *fp; if(GameInfo->type != GIT_CART)return 0; if(GameInterface!=iNESGI)return 0; fp = fopen(name,"wb"); int x = 0; if (!fp) int x = 1; if(fwrite(&head,1,16,fp)!=16)return 0; if(head.ROM_type&4) /* Trainer */ { fwrite(trainerpoo,512,1,fp); } fwrite(ROM,0x4000,ROM_size,fp); if(head.VROM_size)fwrite(VROM,0x2000,head.VROM_size,fp); fclose(fp); return 1; } //para edit: added function below char *iNesShortFName() { char *ret; if (!(ret = strrchr(LoadedRomFName,'\\'))) { if (!(ret = strrchr(LoadedRomFName,'/'))) return 0; } return ret+1; } void VRAM_BANK1(uint32 A, uint8 V) { V&=7; PPUCHRRAM|=(1<<(A>>10)); CHRBankList[(A)>>10]=V; VPage[(A)>>10]=&CHRRAM[V<<10]-(A); } void VRAM_BANK4(uint32 A, uint32 V) { V&=1; PPUCHRRAM|=(0xF<<(A>>10)); CHRBankList[(A)>>10]=(V<<2); CHRBankList[((A)>>10)+1]=(V<<2)+1; CHRBankList[((A)>>10)+2]=(V<<2)+2; CHRBankList[((A)>>10)+3]=(V<<2)+3; VPage[(A)>>10]=&CHRRAM[V<<10]-(A); } void VROM_BANK1(uint32 A,uint32 V) { setchr1(A,V); CHRBankList[(A)>>10]=V; } void VROM_BANK2(uint32 A,uint32 V) { setchr2(A,V); CHRBankList[(A)>>10]=(V<<1); CHRBankList[((A)>>10)+1]=(V<<1)+1; } void VROM_BANK4(uint32 A, uint32 V) { setchr4(A,V); CHRBankList[(A)>>10]=(V<<2); CHRBankList[((A)>>10)+1]=(V<<2)+1; CHRBankList[((A)>>10)+2]=(V<<2)+2; CHRBankList[((A)>>10)+3]=(V<<2)+3; } void VROM_BANK8(uint32 V) { setchr8(V); CHRBankList[0]=(V<<3); CHRBankList[1]=(V<<3)+1; CHRBankList[2]=(V<<3)+2; CHRBankList[3]=(V<<3)+3; CHRBankList[4]=(V<<3)+4; CHRBankList[5]=(V<<3)+5; CHRBankList[6]=(V<<3)+6; CHRBankList[7]=(V<<3)+7; } void ROM_BANK8(uint32 A, uint32 V) { setprg8(A,V); if(A>=0x8000) PRGBankList[((A-0x8000)>>13)]=V; } void ROM_BANK16(uint32 A, uint32 V) { setprg16(A,V); if(A>=0x8000) { PRGBankList[((A-0x8000)>>13)]=V<<1; PRGBankList[((A-0x8000)>>13)+1]=(V<<1)+1; } } void ROM_BANK32(uint32 V) { setprg32(0x8000,V); PRGBankList[0]=V<<2; PRGBankList[1]=(V<<2)+1; PRGBankList[2]=(V<<2)+2; PRGBankList[3]=(V<<2)+3; } void onemir(uint8 V) { if(Mirroring==2) return; if(V>1) V=1; Mirroring=0x10|V; setmirror(MI_0+V); } void MIRROR_SET2(uint8 V) { if(Mirroring==2) return; Mirroring=V; setmirror(V); } void MIRROR_SET(uint8 V) { if(Mirroring==2) return; V^=1; Mirroring=V; setmirror(V); } static void NONE_init(void) { ROM_BANK16(0x8000,0); ROM_BANK16(0xC000,~0); if(VROM_size) VROM_BANK8(0); else setvram8(CHRRAM); } void (*MapInitTab[256])(void)= { 0, 0, 0, //Mapper2_init, 0, //Mapper3_init, 0, 0, Mapper6_init, 0,//Mapper7_init, Mapper8_init, Mapper9_init, Mapper10_init, 0, //Mapper11_init, 0, 0, //Mapper13_init, 0, 0, //Mapper15_init, 0, //Mapper16_init, Mapper17_init, Mapper18_init, 0, 0, Mapper21_init, Mapper22_init, 0, //Mapper23_init, Mapper24_init, Mapper25_init, Mapper26_init, Mapper27_init, 0, 0, 0, 0, Mapper32_init, Mapper33_init, Mapper34_init, 0, 0, 0, 0, 0, Mapper40_init, Mapper41_init, Mapper42_init, 0, //Mapper43_init, 0, 0, Mapper46_init, 0, Mapper48_init, 0, Mapper50_init, Mapper51_init, 0, 0, 0, 0, 0, 0,// Mapper57_init, 0,// Mapper58_init, Mapper59_init, 0,// Mapper60_init, Mapper61_init, Mapper62_init, 0, Mapper64_init, Mapper65_init, 0,//Mapper66_init, Mapper67_init, 0,//Mapper68_init, Mapper69_init, 0,//Mapper70_init, Mapper71_init, Mapper72_init, Mapper73_init, 0, Mapper75_init, Mapper76_init, Mapper77_init, 0, //Mapper78_init, Mapper79_init, Mapper80_init, 0, Mapper82_init, Mapper83_init, 0, Mapper85_init, Mapper86_init, 0, //Mapper87_init, 0, //Mapper88_init, Mapper89_init, 0, Mapper91_init, Mapper92_init, 0, //Mapper93_init, 0, //Mapper94_init, 0, Mapper96_init, Mapper97_init, 0, Mapper99_init, 0, 0, 0, 0, 0, 0, 0, 0, //Mapper107_init, 0, 0, 0, 0, 0, 0, // Mapper113_init, 0, 0, 0, //Mapper116_init, 0, //Mapper117_init, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //Mapper140_init, 0, 0, 0, 0, //Mapper144_init, 0, 0, 0, 0, 0, 0, Mapper151_init, 0, //Mapper152_init, 0, //Mapper153_init, 0, //Mapper154_init, 0, Mapper156_init, Mapper157_init, 0, //Mapper158_init, removed 0, 0, 0, 0, 0, 0, 0, Mapper166_init, Mapper167_init, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //Mapper180_init, 0, 0, 0, 0, //Mapper184_init, 0, //Mapper185_init, 0, 0, 0, 0, //Mapper189_init, 0, 0, //Mapper191_init, 0, Mapper193_init, 0, 0, 0, 0, 0, 0, 0, //Mapper200_init, Mapper201_init, Mapper202_init, Mapper203_init, Mapper204_init, 0, 0, Mapper207_init, 0, 0, 0, 0, //Mapper211_init, Mapper212_init, Mapper213_init, Mapper214_init, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Mapper225_init, 0, //Mapper226_init, Mapper227_init, Mapper228_init, Mapper229_init, Mapper230_init, Mapper231_init, Mapper232_init, 0, Mapper234_init, 0, //Mapper235_init, 0, 0, 0, 0, 0, //Mapper240_init, Mapper241_init, Mapper242_init, 0, Mapper244_init, 0, Mapper246_init, 0, 0, 0, 0, 0, 0, 0, 0, Mapper255_init }; static DECLFW(BWRAM) { WRAM[A-0x6000]=V; } static DECLFR(AWRAM) { return WRAM[A-0x6000]; } void (*MapStateRestore)(int version); void iNESStateRestore(int version) { int x; if(!MapperNo) return; for(x=0;x<4;x++) setprg8(0x8000+x*8192,PRGBankList[x]); if(VROM_size) for(x=0;x<8;x++) setchr1(0x400*x,CHRBankList[x]); if(0) switch(Mirroring) { case 0:setmirror(MI_H);break; case 1:setmirror(MI_V);break; case 0x12: case 0x10:setmirror(MI_0);break; case 0x13: case 0x11:setmirror(MI_1);break; } if(MapStateRestore) MapStateRestore(version); } static void iNESPower(void) { int x; int type=MapperNo; SetReadHandler(0x8000,0xFFFF,CartBR); GameStateRestore=iNESStateRestore; MapClose=0; MapperReset=0; MapStateRestore=0; setprg8r(1,0x6000,0); SetReadHandler(0x6000,0x7FFF,AWRAM); SetWriteHandler(0x6000,0x7FFF,BWRAM); FCEU_CheatAddRAM(8,0x6000,WRAM); /* This statement represents atrocious code. I need to rewrite all of the iNES mapper code... */ IRQCount=IRQLatch=IRQa=0; if(head.ROM_type&2) memset(GameMemBlock+8192,0,GAME_MEM_BLOCK_SIZE-8192); else memset(GameMemBlock,0,GAME_MEM_BLOCK_SIZE); NONE_init(); ResetExState(0,0); if(GameInfo->type == GIT_VSUNI) AddExState(FCEUVSUNI_STATEINFO, ~0, 0, 0); AddExState(WRAM, 8192, 0, "WRAM"); if(type==19 || type==6 || type==69 || type==85 || type==96) AddExState(MapperExRAM, 32768, 0, "MEXR"); if((!VROM_size || type==6 || type==19) && (type!=13 && type!=96)) AddExState(CHRRAM, 8192, 0, "CHRR"); if(head.ROM_type&8) AddExState(ExtraNTARAM, 2048, 0, "EXNR"); /* Exclude some mappers whose emulation code handle save state stuff themselves. */ if(type && type!=13 && type!=96) { AddExState(mapbyte1, 32, 0, "MPBY"); AddExState(&Mirroring, 1, 0, "MIRR"); AddExState(&IRQCount, 4, 1, "IRQC"); AddExState(&IRQLatch, 4, 1, "IQL1"); AddExState(&IRQa, 1, 0, "IRQA"); AddExState(PRGBankList, 4, 0, "PBL"); for(x=0;x<8;x++) { char tak[8]; sprintf(tak,"CBL%d",x); AddExState(&CHRBankList[x], 2, 1,tak); } } if(MapInitTab[type]) MapInitTab[type](); else if(type) { FCEU_PrintError("iNES mapper #%d is not supported at all.",type); } } static int NewiNES_Init(int num) { BMAPPINGLocal *tmp=bmap; if(GameInfo->type == GIT_VSUNI) AddExState(FCEUVSUNI_STATEINFO, ~0, 0, 0); while(tmp->init) { if(num==tmp->number) { UNIFchrrama=0; // need here for compatibility with UNIF mapper code if(!VROM_size) { int CHRRAMSize; if(num==13) { CHRRAMSize=16384; } else { CHRRAMSize=8192; } #ifdef _USE_SHARED_MEMORY_ mapVROM = CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE, 0, CHRRAMSize,"fceu.VROM"); if(mapVROM == NULL || GetLastError() == ERROR_ALREADY_EXISTS) { CloseHandle(mapVROM); mapVROM = NULL; if((VROM = (uint8 *)FCEU_dmalloc(CHRRAMSize)) == NULL) return 0; } else { if((VROM = (uint8 *)MapViewOfFile(mapVROM, FILE_MAP_WRITE, 0, 0, 0)) == NULL) { CloseHandle(mapVROM); mapVROM = NULL; if((VROM = (uint8 *)FCEU_dmalloc(CHRRAMSize)) == NULL) return 0; } } #else if((VROM = (uint8 *)FCEU_dmalloc(CHRRAMSize)) == NULL) return 0; #endif UNIFchrrama=VROM; SetupCartCHRMapping(0,VROM,CHRRAMSize,1); AddExState(VROM,CHRRAMSize, 0, "CHRR"); } if(head.ROM_type&8) AddExState(ExtraNTARAM, 2048, 0, "EXNR"); tmp->init(&iNESCart); return 1; } tmp++; } return 0; }
[ [ [ 1, 1544 ] ] ]
0f5036f29d1955d22263cb409d4a269c9d768a4e
09ea547305ed8be9f8aa0dc6a9d74752d660d05d
/smf/smfservermodule/smfserver/transportmgr/smftransportmanagerutil.cpp
d5de2f7385b97a024aa26f6f107f391f8e4215a6
[]
no_license
SymbianSource/oss.FCL.sf.mw.socialmobilefw
3c49e1d1ae2db8703e7c6b79a4c951216c9c5019
7020b195cf8d1aad30732868c2ed177e5459b8a8
refs/heads/master
2021-01-13T13:17:24.426946
2010-10-12T09:53:52
2010-10-12T09:53:52
72,676,540
0
0
null
null
null
null
UTF-8
C++
false
false
32,166
cpp
/** * Copyright (c) 2010 Sasken Communication Technologies Ltd. * All rights reserved. * This component and the accompanying materials are made available * under the terms of the "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: * Chandradeep Gandhi, Sasken Communication Technologies Ltd - Initial contribution * * Contributors: * Manasij Roy, Nalina Hariharan * * Description: * The Transport Manager Utility class provides the http/https transaction * methods for the smf framework * */ // Include files #define EMULATORTESTING #include <QNetworkAccessManager> #include <QNetworkReply> #include <QSettings> #include <zlib.h> #ifdef EMULATORTESTING // For proxy settings on emulator only - REMOVE for device #include <QNetworkProxy> #endif #include "smftransportmanagerutil.h" #include "smfpluginmanager.h" // Static Global constants static const char kSmfUserAgent[] = "SmfFrameWork"; static const char kSmfCacheControl[] = "no-cache"; static const char kSmfAcceptEncoding[] = "gzip"; // Static data initialisation SmfTransportManagerUtil* SmfTransportManagerUtil::m_myInstance = NULL; /** * Method to get the instance of SmfTransportManagerUtil class * @return The instance of SmfTransportManager class */ SmfTransportManagerUtil* SmfTransportManagerUtil::getInstance ( ) { if(NULL == m_myInstance) m_myInstance = new SmfTransportManagerUtil( ); return m_myInstance; } /** * Constructor with default argument * @param aParent The parent object */ SmfTransportManagerUtil::SmfTransportManagerUtil ( ) : m_networkAccessManager ( this ) { // Storage of settings (Only data usage as of now) m_settings = new QSettings("Sasken", "SmfTransportManager"); // Create the settings if no data is stored if( !m_settings->contains("Sent Data") ) m_settings->setValue("Sent Data", 0); if( !m_settings->contains("Received Data") ) m_settings->setValue("Received Data", 0); #ifdef EMULATORTESTING qDebug()<<"Using PROXY SETTINGS!!!, change for device testing"; // Reading the keys, CSM Stubbed - START QFile winFile("c:\\data\\DoNotShare.txt"); if (!winFile.open(QIODevice::ReadOnly)) { qDebug()<<"File to read the windows username and password could not be opened, returning!!!"; return; } QByteArray winArr = winFile.readAll(); QList<QByteArray> winList = winArr.split(' '); winFile.close(); QString httpUser(winList[0]); QString httpPass(winList[1]); // For proxy settings on emulator only - REMOVE for device QString httpProxy = "10.1.0.214"; QString httpPort = "3128"; //==Classes used from Network Module== QNetworkProxy proxy; proxy.setType(QNetworkProxy::HttpProxy); proxy.setHostName(httpProxy); proxy.setPort(httpPort.toInt()); proxy.setUser(httpUser); proxy.setPassword(httpPass); QNetworkProxy::setApplicationProxy(proxy); #endif } /** * Destructor */ SmfTransportManagerUtil::~SmfTransportManagerUtil ( ) { m_activeNetwReplyList.clear(); if(m_settings) delete m_settings; if(m_myInstance) delete m_myInstance; } /** * Method that does a http GET request. Returns the unique QNetworkReply * instance for this transaction to the plugin manager to trace the * proper response. * @param aRequest The request formed by the plugin * @param aUrlList The list of accessible Urls for this plugin * @param aSOPCompliant [out] Output parameter indicating Same Origin * Policy Compliance. Contains true if the request complies to the policy, * else false. If it is false, the network request will not performed * @return The unique QNetworkReply instance for this transaction */ QNetworkReply* SmfTransportManagerUtil::get ( QNetworkRequest &aRequest, const QList<QUrl> &aUrlList, bool &aSOPCompliant ) { qDebug()<<"Inside SmfTransportManagerUtil::get()";; bool found = false; QString hostName = aRequest.url().host(); // Same Origin Policy checking // Check if the host name of the url in the request created by the // plugin is among the authorised url host name list foreach(QUrl url, aUrlList) { if(0 == hostName.compare(url.host())) { found = true; break; } } if(found) { aSOPCompliant = true; // Set header to accept gzip encoded data aRequest.setRawHeader("Accept-encoding", kSmfAcceptEncoding); // Set the cache control aRequest.setRawHeader("Cache-Control", kSmfCacheControl); // Put the same user agent for all requests sent by Smf aRequest.setRawHeader("User-Agent", kSmfUserAgent); QNetworkReply* reply = m_networkAccessManager.get(aRequest); qDebug()<<"QNetworkReply of get() = "<<(long)reply; connect(&m_networkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(networkReplyFinished(QNetworkReply *))); connect(&m_networkAccessManager, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkReplyError(QNetworkReply::NetworkError))); m_activeNetwReplyList.append(reply); return reply; } else { // Error :: SAME ORIGIN POLICY violation!!! aSOPCompliant = false; qDebug()<<"SOP violation"; return NULL; } } /** * Method that does a http POST request. Returns the unique QNetworkReply * instance for this transaction to the plugin manager to trace the * proper response. * @param aRequest The request formed by the plugin * @param aPostData The data to be posted via http POST request * @param aUrlList The list of accessible Urls for this plugin * @param aSOPCompliant [out] Output parameter indicating Same Origin * Policy Compliance. Contains true if the request complies to the policy, * else false. If it is false, the network request will not performed * @return The unique QNetworkReply instance for this transaction */ QNetworkReply* SmfTransportManagerUtil::post ( QNetworkRequest &aRequest, const QByteArray& aPostData, const QList<QUrl> &aUrlList, bool &aSOPCompliant ) { qDebug()<<"Inside SmfTransportManagerUtil::post()"; bool found = false; QString hostName = aRequest.url().host(); // Same Origin Policy checking // Check if the host name of the url in the request created by the // plugin is among the authorised url host name list foreach(QUrl url, aUrlList) { if(0 == hostName.compare(url.host())) { found = true; break; } } if(found) { aSOPCompliant = true; // Set header to accept gzip encoded data aRequest.setRawHeader("Accept-encoding", kSmfAcceptEncoding); // Set the cache control aRequest.setRawHeader("Cache-Control", kSmfCacheControl); // Put the same user agent for all requests sent by Smf aRequest.setRawHeader("User-Agent", kSmfUserAgent); #ifdef DETAILEDDEBUGGING qDebug()<<"post data size is = "<<aPostData.size(); qDebug()<<"post data is = "<<QString(aPostData); #endif QNetworkReply* reply = m_networkAccessManager.post(aRequest, aPostData); qDebug()<<"QNetworkReply of post() = "<<(long)reply; connect(&m_networkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(networkReplyFinished(QNetworkReply *))); connect(&m_networkAccessManager, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkReplyError(QNetworkReply::NetworkError))); m_activeNetwReplyList.append(reply); return reply; } else { // Error :: SAME ORIGIN POLICY violation!!! aSOPCompliant = false; qDebug()<<"SOP violation"; return NULL; } } /** * Method that does a http HEAD request. Returns the unique QNetworkReply * instance for this transaction to the plugin manager to trace the * proper response. * @param aRequest The request formed by the plugin * @param aUrlList The list of accessible Urls for this plugin * @param aSOPCompliant [out] Output parameter indicating Same Origin * Policy Compliance. Contains true if the request complies to the policy, * else false. If it is false, the network request will not performed * @return The unique QNetworkReply instance for this transaction */ QNetworkReply* SmfTransportManagerUtil::head ( QNetworkRequest& aRequest, const QList<QUrl> &aUrlList, bool &aSOPCompliant ) { qDebug()<<"Inside SmfTransportManagerUtil::head()"; bool found = false; QString hostName = aRequest.url().host(); // Same Origin Policy checking // Check if the host name of the url in the request created by the // plugin is among the authorised url host name list foreach(QUrl url, aUrlList) { if(0 == hostName.compare(url.host())) { found = true; break; } } if(found) { aSOPCompliant = true; // Set header to accept gzip encoded data aRequest.setRawHeader("Accept-encoding", kSmfAcceptEncoding); // Set the cache control aRequest.setRawHeader("Cache-Control", kSmfCacheControl); // Put the same user agent for all requests sent by Smf aRequest.setRawHeader("User-Agent", kSmfUserAgent); QNetworkReply* reply = m_networkAccessManager.head(aRequest); qDebug()<<"QNetworkReply of head() = "<<(long)reply; connect(&m_networkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(networkReplyFinished(QNetworkReply *))); connect(&m_networkAccessManager, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkReplyError(QNetworkReply::NetworkError))); m_activeNetwReplyList.append(reply); return reply; } else { // Error :: SAME ORIGIN POLICY violation!!! aSOPCompliant = false; qDebug()<<"SOP violation"; return NULL; } } /** * Method that does a http PUT request. Returns the unique QNetworkReply * instance for this transaction to the plugin manager to trace the * proper response. * @param aRequest The request formed by the plugin * @param aPostData The data to be posted via http PUT request * @param aUrlList The list of accessible Urls for this plugin * @param aSOPCompliant [out] Output parameter indicating Same Origin * Policy Compliance. Contains true if the request complies to the policy, * else false. If it is false, the network request will not performed * @return The unique QNetworkReply instance for this transaction */ QNetworkReply* SmfTransportManagerUtil::put ( QNetworkRequest &aRequest, const QByteArray& aPostData, const QList<QUrl> &aUrlList, bool &aSOPCompliant ) { qDebug()<<"Inside SmfTransportManagerUtil::put()"; bool found = false; QString hostName = aRequest.url().host(); // Same Origin Policy checking // Check if the host name of the url in the request created by the // plugin is among the authorised url host name list foreach(QUrl url, aUrlList) { if(0 == hostName.compare(url.host())) { found = true; break; } } if(found) { aSOPCompliant = true; // Set header to accept gzip encoded data aRequest.setRawHeader("Accept-encoding", kSmfAcceptEncoding); // Set the cache control aRequest.setRawHeader("Cache-Control", kSmfCacheControl); // Put the same user agent for all requests sent by Smf aRequest.setRawHeader("User-Agent", kSmfUserAgent); QNetworkReply* reply = m_networkAccessManager.put(aRequest, aPostData); qDebug()<<"QNetworkReply of put() = "<<(long)reply; connect(&m_networkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(networkReplyFinished(QNetworkReply *))); connect(&m_networkAccessManager, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkReplyError(QNetworkReply::NetworkError))); m_activeNetwReplyList.append(reply); return reply; } else { // Error :: SAME ORIGIN POLICY violation!!! aSOPCompliant = false; qDebug()<<"SOP violation"; return NULL; } } /** * Method that does a http DELETE request. Returns the unique QNetworkReply * instance for this transaction to the plugin manager to trace the * proper response. * @param aRequest The request formed by the plugin * @param aUrlList The list of accessible Urls for this plugin * @param aSOPCompliant [out] Output parameter indicating Same Origin * Policy Compliance. Contains true if the request complies to the policy, * else false. If it is false, the network request will not performed * @return The unique QNetworkReply instance for this transaction */ QNetworkReply* SmfTransportManagerUtil::deleteResource ( QNetworkRequest &aRequest, const QList<QUrl> &aUrlList, bool &aSOPCompliant ) { qDebug()<<"Inside SmfTransportManagerUtil::deleteResource()"; bool found = false; QString hostName = aRequest.url().host(); // Same Origin Policy checking // Check if the host name of the url in the request created by the // plugin is among the authorised url host name list foreach(QUrl url, aUrlList) { if(0 == hostName.compare(url.host())) { found = true; break; } } if(found) { aSOPCompliant = true; // Set header to accept gzip encoded data aRequest.setRawHeader("Accept-encoding", kSmfAcceptEncoding); // Set the cache control aRequest.setRawHeader("Cache-Control", kSmfCacheControl); // Put the same user agent for all requests sent by Smf aRequest.setRawHeader("User-Agent", kSmfUserAgent); QNetworkReply* reply = m_networkAccessManager.deleteResource(aRequest); qDebug()<<"QNetworkReply of deleteResource() = "<<(long)reply; connect(&m_networkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(networkReplyFinished(QNetworkReply *))); connect(&m_networkAccessManager, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkReplyError(QNetworkReply::NetworkError))); m_activeNetwReplyList.append(reply); return reply; } else { // Error :: SAME ORIGIN POLICY violation!!! aSOPCompliant = false; qDebug()<<"SOP violation"; return NULL; } } /** * Method that cancels the service request by cancelling the current * http transaction. * @param aCancelReply The QNetworkReply instance whose transaction * has to be cancelled * @return Returns true for success, else false */ bool SmfTransportManagerUtil::cancelRequest ( QNetworkReply *aCancelReply ) { qDebug()<<"Inside SmfTransportManagerUtil::cancelRequest()"; // Checks if this transaction is running if( aCancelReply->isRunning() ) { // Aborts the running transaction aCancelReply->abort(); } // Close the connection aCancelReply->close(); int index = m_activeNetwReplyList.indexOf(aCancelReply); if( index >= 0 ) m_activeNetwReplyList.removeAt(index); return true; } /* * Method that is called whenever a new network configuration is added to the system. * @param aResult SmfTransportResult */ void SmfTransportManagerUtil::configurationAdded ( const SmfTransportResult &aResult ) { // Inform PM and plugins that a new IAP ia added, and hence resend the request SmfPluginManager::getInstance()->responseAvailable ( aResult, NULL, NULL ); } /* * Method that is called when the state of the network configuration changes. * @param aResult SmfTransportResult */ void SmfTransportManagerUtil::configurationChanged ( const SmfTransportResult &aResult ) { // Inform PM and plugins that the IAP is changed, and hence resend the request SmfPluginManager::getInstance()->responseAvailable ( aResult, NULL, NULL ); } /* * Method that is called when a configuration is about to be removed from the system. * The removed configuration is invalid but retains name and identifier. * @param aResult SmfTransportResult */ void SmfTransportManagerUtil::configurationRemoved ( const SmfTransportResult &aResult ) { // Inform PM and plugins that the IAP is to be deleted, and // hence resend the request SmfPluginManager::getInstance()->responseAvailable ( aResult, NULL, NULL ); } /** * Method to indicate the http transaction has finished. * @param aNetworkReply The QNetworkReply instance for which the http * transaction was made */ void SmfTransportManagerUtil::networkReplyFinished ( QNetworkReply *aNetworkReply ) { qDebug()<<"Inside SmfTransportManagerUtil::networkReplyFinished()"; qDebug()<<"QNetworkReply = "<<(long)aNetworkReply; qDebug()<<"QNetworkReply error code = "<<aNetworkReply->error(); // remove the QNetworkReply instance from the list of outstanding transactions int index = m_activeNetwReplyList.indexOf(aNetworkReply); if( index >= 0 ) m_activeNetwReplyList.removeAt(index); // indicate the result of transaction to the plugin manager SmfTransportResult trResult; convertErrorType(aNetworkReply->error(), trResult); // Read the response from the device QByteArray response = aNetworkReply->readAll(); qDebug()<<"Response size is = "<<response.size(); #ifdef DETAILEDDEBUGGING qDebug()<<"Response is = "<<QString(response); #endif // Store the number of bytes of data received bool converted = false; quint64 data = m_settings->value("Received Data").toULongLong(&converted); if(converted) { data += response.size(); m_settings->setValue("Received Data", data); } SmfError error = SmfUnknownError; QByteArray *arr = NULL; #ifdef DETAILEDDEBUGGING foreach(QByteArray arr, aNetworkReply->rawHeaderList()) qDebug()<<QString(arr)<<" = "<<QString(aNetworkReply->rawHeader(arr)); #endif // Check if the http response header has the raw header "Content-Encoding:gzip" bool gzipEncoded = false; QByteArray headerKey("Content-Encoding"); if(aNetworkReply->hasRawHeader(headerKey)) { qDebug()<<"Content-Encoding:"<<QString(aNetworkReply->rawHeader(headerKey)); // If http response header has the raw header "Content-Encoding:gzip" if( "gzip" == QString(aNetworkReply->rawHeader(headerKey))) { QByteArray firstByte(1, response[0]); QByteArray secondByte(1, response[1]); #ifdef DETAILEDDEBUGGING qDebug()<<"first byte : "<<QString(firstByte.toHex()); qDebug()<<"second byte : "<<QString(secondByte.toHex()); #endif // And the header says the response is a valid gzip data. // If so, inflate the gzip deflated data if((QString("1f") == QString(firstByte.toHex())) && (QString("8b") == QString(secondByte.toHex())) ) { gzipEncoded = true; qDebug()<<"Response is gzip encoded!!! = "<<gzipEncoded; arr = inflateResponse(response, error); if(!arr) trResult = SmfTransportOpGzipError; } else { qDebug()<<"Header says gzip encoded, but response is not a valid data, so ignoring the header!!!"; arr = new QByteArray(response); } } else { qDebug()<<"Unsupported encoding format!!! - error"; trResult = SmfTransportOpUnsupportedContentEncodingFormat; } } else { qDebug()<<"Response is not gzip encoded"; arr = new QByteArray(response); } // Write the uncompressed data to a file #ifdef DETAILEDDEBUGGING if(arr) { QFile file1("c:\\data\\networkResponse.txt"); if (!file1.open(QIODevice::WriteOnly)) qDebug()<<"File to write the network response could not be opened"; file1.write(*arr); file1.close(); } #endif SmfPluginManager::getInstance()->responseAvailable ( trResult, aNetworkReply, arr ); } /** * Method to inflate a gzipped network response. * @param aResponse The QByteArray holding the gzip encoded data * @param aError Argument indicating error * @return a QByteArray* containing the inflated data. If inflation fails, * NULL is returned */ QByteArray* SmfTransportManagerUtil::inflateResponse ( QByteArray &aResponse, SmfError& aError ) { qDebug()<<"Inside SmfTransportManagerUtil::inflateResponse()"; // Read the response from the device qDebug()<<"Encoded response content size = "<<aResponse.size(); if(aResponse.size() <= 0) { aError = SmfTMUnknownContentError; return NULL; } // Get the uncompressed size of the response (last 4 bytes of the compressed data as per GZIP format spec) QByteArray sizeStr; for(int count = 1 ; count <= 4 ; count++) sizeStr.append(aResponse[aResponse.size()-count]); #ifdef DETAILEDDEBUGGING qDebug()<<"Size string as a string = "<<QString(sizeStr.toHex()); #endif bool ok = false; int uncomSize = sizeStr.toHex().toInt(&ok, 16); qDebug()<<"Size of uncompressed data = "<<uncomSize; // Initialize the data required for zlib method call z_stream stream; unsigned char *out = new unsigned char[uncomSize]; if(out) qDebug()<<"Memory allocated for output buffer"; else { //Error qDebug()<<"Memory not allocated for output buffer!!!"; aError = SmfMemoryAllocationFailure; return NULL; } stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; stream.avail_in = 0; stream.next_in = Z_NULL; int ret = inflateInit2(&stream, 16+MAX_WBITS); #ifdef DETAILEDDEBUGGING qDebug()<<"return value of inflateInit2() = "<<ret; #endif if(Z_OK != ret) { qDebug()<<"Error in inflateInit2, returning..."; delete[] out; if(Z_STREAM_ERROR == ret) aError = SmfTMGzipStreamError; else if(Z_MEM_ERROR == ret) aError = SmfTMGzipMemoryError; else if(Z_DATA_ERROR == ret) aError = SmfTMGzipDataError; else aError = SmfUnknownError; return NULL; } // Initialize the data required for inflate() method call stream.avail_in = aResponse.size(); stream.next_in = (unsigned char *)aResponse.data(); stream.avail_out = uncomSize; stream.next_out = out; ret = inflate(&stream, Z_NO_FLUSH); #ifdef DETAILEDDEBUGGING qDebug()<<"return value of inflate() = "<<ret; #endif switch (ret) { // fall through case Z_NEED_DICT: case Z_DATA_ERROR: case Z_MEM_ERROR: { qDebug()<<"Error in inflate, returning..."; (void)inflateEnd(&stream); delete[] out; aError = SmfTMGzipDataError; return NULL; } } qDebug()<<"total bytes read so far = "<<stream.total_in; qDebug()<<"total bytes output so far = "<<stream.total_out; // Write the inflated data to a QByteArray QByteArray *uncompressedData = new QByteArray((char *)out, stream.total_out); delete[] out; // If there is some unwanted data at the end of uncompressed data, chop them int chopLength = uncompressedData->size() - uncomSize; #ifdef DETAILEDDEBUGGING qDebug()<<"old size of uncompressed data = "<<uncompressedData->size(); #endif uncompressedData->chop(chopLength); #ifdef DETAILEDDEBUGGING qDebug()<<"new size of uncompressed data = "<<uncompressedData->size(); #endif return uncompressedData; } /** * Method to deflate a network request to gzip format. * @param aResponse The QByteArray that has to be gzipped * @param aError Argument indicating error * @return a QByteArray* containing the deflated data. If deflation fails, * NULL is returned */ QByteArray* SmfTransportManagerUtil::deflateRequest( QByteArray &aResponse, SmfError& aError ) { qDebug()<<"Inside SmfTransportManagerUtil::deflateRequest()"; if(aResponse.size() <= 0) { aError = SmfTMUnknownContentError; return NULL; } // Initialize the data required for zlib initialize method call z_stream stream; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; stream.next_in = (unsigned char *)aResponse.data(); stream.avail_in = aResponse.size(); stream.total_out = 0; int level = Z_DEFAULT_COMPRESSION; int method = Z_DEFLATED; int windowBits = 16+MAX_WBITS; int mem_level = 8; int strategy = Z_DEFAULT_STRATEGY; // Call deflateInit2 for gzip compression initialization int initError = deflateInit2(&stream, level, method, windowBits, mem_level, strategy); #ifdef DETAILEDDEBUGGING qDebug()<<"Return value of deflateInit2() = "<<initError; qDebug()<<"Error msg if any = "<<QString(zError(initError)); #endif if(Z_OK != initError) { qDebug()<<"deflateInit2() failed, returning error = "<<QString(zError(initError)); if(Z_STREAM_ERROR == initError) aError = SmfTMGzipStreamError; else if(Z_MEM_ERROR == initError) aError = SmfTMGzipMemoryError; else if(Z_DATA_ERROR == initError) aError = SmfTMGzipDataError; else aError = SmfUnknownError; return NULL; } // Initialize the data required for inflate() method call int out_size = (int)((aResponse.size()*1.01)+17); unsigned char *out = new unsigned char[out_size]; if(out) { qDebug()<<"Memory allocated for output buffer with size = "<<out_size; memset(out, 0, out_size); } else { //Error qDebug()<<"Memory not allocated for output buffer!!!"; deflateEnd(&stream); aError = SmfTMGzipDataError; return NULL; } stream.next_out = out; stream.avail_out = out_size; #ifdef DETAILEDDEBUGGING qDebug()<<"Before calling deflate()"; qDebug()<<"next_in = "<<(long)stream.next_in; qDebug()<<"avail_in = "<<stream.avail_in; qDebug()<<"next_out = "<<(long)stream.next_out; qDebug()<<"avail_out = "<<stream.avail_out; qDebug()<<"total_in = "<<stream.total_in; qDebug()<<"total_out = "<<stream.total_out; #endif int deflateStatus; do { stream.next_out = out + stream.total_out; stream.avail_out = out_size - stream.total_out; deflateStatus = deflate(&stream, Z_FINISH); qDebug()<<"Return value of deflate() is = "<<deflateStatus; qDebug()<<"Error msg if any = "<<QString(zError(deflateStatus)); #ifdef DETAILEDDEBUGGING qDebug()<<"avail_in = "<<stream.avail_in; qDebug()<<"avail_out = "<<stream.avail_out; qDebug()<<"total_in = "<<stream.total_in; qDebug()<<"total_out = "<<stream.total_out; #endif }while(Z_OK == deflateStatus); if (Z_STREAM_END != deflateStatus) { QString errorMsg; switch (deflateStatus) { case Z_ERRNO: errorMsg.append("Error occured while reading file."); aError = SmfUnknownError; break; case Z_STREAM_ERROR: errorMsg.append("The stream state was inconsistent (e.g., next_in or next_out was NULL)."); aError = SmfTMGzipStreamError; break; case Z_DATA_ERROR: errorMsg.append("The deflate data was invalid or incomplete."); aError = SmfTMGzipDataError; break; case Z_MEM_ERROR: errorMsg.append("Memory could not be allocated for processing."); aError = SmfTMGzipMemoryError; break; case Z_BUF_ERROR: errorMsg.append("Ran out of output buffer for writing compressed bytes."); aError = SmfTMGzipMemoryError; break; case Z_VERSION_ERROR: errorMsg.append("The version of zlib.h and the version of the library linked do not match."); aError = SmfUnknownError; break; default: errorMsg.append("Unknown error code."); aError = SmfUnknownError; } qDebug()<<"Error string for deflate() is = "<<errorMsg; // Free data structures that were dynamically created for the stream. deflateEnd(&stream); return NULL; } int retVal = deflateEnd(&stream); qDebug()<<"Return value of deflateEnd() = "<<retVal; qDebug()<<"Error msg if any = "<<QString(zError(retVal)); #ifdef DETAILEDDEBUGGING /*QByteArray byteArray; for (int i=0; i<stream.total_out;i++) { QString str(out[i]); byteArray.clear(); byteArray.append(str.toAscii()); qDebug()<<QString("out[%1] = '%2'").arg(i).arg(QString(byteArray.toHex())); }*/ #endif // Write the inflated data to a QByteArray QByteArray *compressedData = new QByteArray((char*)out, stream.total_out); delete[] out; qDebug()<<"Number of bytes of compressed data = "<<compressedData->size(); #ifdef DETAILEDDEBUGGING qDebug()<<"compressed data = "<<QString(compressedData->toHex()); #endif return compressedData; } /** * Method called when the QNetworkReply detects an error in processing. * @param aError The QNetworkReply error code */ void SmfTransportManagerUtil::networkReplyError ( QNetworkReply::NetworkError aError ) { qDebug()<<"Inside SmfTransportManagerUtil::networkReplyError()"; // indicate the error to the plugin manager SmfTransportResult trResult; convertErrorType(aError, trResult); SmfPluginManager::getInstance()->responseAvailable ( trResult, NULL, NULL ); } /** * Method to convert QNetworkReply Error to the type SmfTransportResult * QNetworkRequest received before executing the web query. * @param aError The QNetworkReply Error * @param aResult [out] The SmfTransportResult error */ void SmfTransportManagerUtil::convertErrorType( const QNetworkReply::NetworkError &aError, SmfTransportResult &aResult ) { switch(aError) { case QNetworkReply::NoError: aResult = SmfTransportOpNoError; break; case QNetworkReply::ConnectionRefusedError: aResult = SmfTransportOpConnectionRefusedError; break; case QNetworkReply::RemoteHostClosedError: aResult = SmfTransportOpRemoteHostClosedError; break; case QNetworkReply::HostNotFoundError: aResult = SmfTransportOpHostNotFoundError; break; case QNetworkReply::TimeoutError: aResult = SmfTransportOpTimeoutError; break; case QNetworkReply::OperationCanceledError: aResult = SmfTransportOpOperationCanceledError; break; case QNetworkReply::SslHandshakeFailedError: aResult = SmfTransportOpSslHandshakeFailedError; break; case QNetworkReply::ProxyConnectionRefusedError: aResult = SmfTransportOpProxyConnectionRefusedError; break; case QNetworkReply::ProxyConnectionClosedError: aResult = SmfTransportOpProxyConnectionClosedError; break; case QNetworkReply::ProxyNotFoundError: aResult = SmfTransportOpProxyNotFoundError; break; case QNetworkReply::ProxyTimeoutError: aResult = SmfTransportOpProxyTimeoutError; break; case QNetworkReply::ProxyAuthenticationRequiredError: aResult = SmfTransportOpProxyAuthenticationRequiredError; break; case QNetworkReply::ContentAccessDenied: aResult = SmfTransportOpContentAccessDenied; break; case QNetworkReply::ContentOperationNotPermittedError: aResult = SmfTransportOpContentOperationNotPermittedError; break; case QNetworkReply::ContentNotFoundError: aResult = SmfTransportOpContentNotFoundError; break; case QNetworkReply::AuthenticationRequiredError: aResult = SmfTransportOpAuthenticationRequiredError; break; case QNetworkReply::ContentReSendError: aResult = SmfTransportOpContentReSendError; break; case QNetworkReply::ProtocolUnknownError: aResult = SmfTransportOpProtocolUnknownError; break; case QNetworkReply::ProtocolInvalidOperationError: aResult = SmfTransportOpProtocolInvalidOperationError; break; case QNetworkReply::UnknownNetworkError: aResult = SmfTransportOpUnknownNetworkError; break; case QNetworkReply::UnknownProxyError: aResult = SmfTransportOpUnknownProxyError; break; case QNetworkReply::UnknownContentError: aResult = SmfTransportOpUnknownContentError; break; case QNetworkReply::ProtocolFailure: aResult = SmfTransportOpProtocolFailure; break; default: ; } }
[ "[email protected]", "none@none" ]
[ [ [ 1, 20 ], [ 22, 72 ], [ 74, 75 ], [ 78, 82 ], [ 86, 86 ], [ 89, 90 ], [ 93, 163 ], [ 165, 602 ], [ 605, 666 ], [ 668, 668 ], [ 670, 692 ], [ 694, 694 ], [ 696, 717 ], [ 719, 719 ], [ 721, 728 ], [ 730, 745 ], [ 747, 747 ], [ 749, 749 ], [ 751, 751 ], [ 753, 791 ], [ 793, 794 ], [ 796, 1056 ] ], [ [ 21, 21 ], [ 73, 73 ], [ 76, 77 ], [ 83, 85 ], [ 87, 88 ], [ 91, 92 ], [ 164, 164 ], [ 603, 604 ], [ 667, 667 ], [ 669, 669 ], [ 693, 693 ], [ 695, 695 ], [ 718, 718 ], [ 720, 720 ], [ 729, 729 ], [ 746, 746 ], [ 748, 748 ], [ 750, 750 ], [ 752, 752 ], [ 792, 792 ], [ 795, 795 ] ] ]
26ddaf01e03453f4f87e36a29892aed3df795c4e
960d6f5c4195a18f795f741c5d2d484f26482c0c
/src/server/scripts/Kalimdor/HallsOfOrigination/boss_earthrager_ptah.cpp
1b2fcd6c0d881bdbfafb57be6a49401bfea9f3f5
[]
no_license
Bootz/TrilliumEMU-1
ec4100d345cc28171e52d60f092ebd39298c40b0
961bfa5d9b0e028d6d89cc238ed8db78a46c69f4
refs/heads/master
2020-12-25T04:30:12.412196
2011-11-25T10:11:04
2011-11-25T10:11:04
2,769,808
0
0
null
null
null
null
UTF-8
C++
false
false
6,393
cpp
/* * Copyright (C) 2005 - 2011 MaNGOS <http://www.getmangos.org/> * * Copyright (C) 2008 - 2011 TrinityCore <http://www.trinitycore.org/> * * Copyright (C) 2011 TrilliumEMU <http://www.arkania.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Made By: Jenova Project: Atlantiss Core Known Bugs: TODO: 1. Needs Testing */ #include "ScriptPCH.h" #include "WorldPacket.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "SpellAuraEffects.h" #define SAY_AGGRO "More carrion for the swarm..." #define SAY_DIED "Ptah... is... no more..." #define SAY_SPELL "Dust to dust." enum CreatureIds { BOSS_EARTHRAGER_PTAH = 39428, MOB_HORROR = 40810, MOB_SCARAB = 40458, }; enum Spells { SPELL_FLAME_BOLT = 77370, SPELL_RAGING_SMASH = 83650, SPELL_EARTH_POINT = 75339, SPELL_DUST_MOVE = 75547, SPELL_VORTEX_DUST = 93570, }; enum Events { EVENT_FLAME_BOLT, EVENT_RAGING_SMASH, EVENT_EARTH_POINT, EVENT_SUMMON, EVENT_DUST_MOVE, EVENT_VORTEX_DUST, }; enum SummonIds { NPC_HORROR = 40810, NPC_SCARAB = 40458, }; const Position aSpawnLocations[3] = { {-530.561584f, -370.613525f, 156.935913f, 5.081081f}, {-484.478302f, -371.117584f, 155.954208f, 4.429200f}, {-507.319977f, -381.939392f, 154.764664f, 4.700163f}, }; class boss_ptah : public CreatureScript { public: boss_ptah() : CreatureScript("boss_ptah") {} struct boss_ptahAI : public ScriptedAI { boss_ptahAI(Creature* pCreature) : ScriptedAI(pCreature), Summons(me) { pInstance = pCreature->GetInstanceScript(); } InstanceScript* pInstance; EventMap events; SummonList Summons; void EnterCombat(Unit * /*who*/) { EnterPhaseGround(); me->MonsterYell(SAY_AGGRO, 0, 0); } void JustDied(Unit* /*killer*/) { me->MonsterYell(SAY_DIED, 0, 0); } void JustSummoned(Creature *pSummoned) { pSummoned->SetInCombatWithZone(); if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM,0)) pSummoned->AI()->AttackStart(pTarget); Summons.Summon(pSummoned); } void SummonedCreatureDespawn(Creature *summon) { Summons.Despawn(summon); } void EnterPhaseGround() { events.ScheduleEvent(EVENT_FLAME_BOLT, 7500); events.ScheduleEvent(EVENT_RAGING_SMASH, urand(4000, 10000)); events.ScheduleEvent(EVENT_EARTH_POINT, 8000); events.ScheduleEvent(EVENT_SUMMON, 50000); events.ScheduleEvent(EVENT_DUST_MOVE, 15000); events.ScheduleEvent(EVENT_VORTEX_DUST, urand(14000, 20000)); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch(eventId) { case EVENT_FLAME_BOLT: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, true)) DoCast(target, SPELL_FLAME_BOLT); events.ScheduleEvent(EVENT_FLAME_BOLT, 7500); return; case EVENT_RAGING_SMASH: DoCast(me->getVictim(), SPELL_RAGING_SMASH); events.ScheduleEvent(EVENT_RAGING_SMASH, urand(4000, 10000)); return; case EVENT_EARTH_POINT: me->MonsterYell(SAY_SPELL, LANG_UNIVERSAL, NULL); if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM,1,100,true)) DoCast(target, SPELL_EARTH_POINT); events.ScheduleEvent(EVENT_EARTH_POINT, 8000); return; case EVENT_SUMMON: me->SummonCreature(NPC_HORROR, aSpawnLocations[0].GetPositionX(), aSpawnLocations[0].GetPositionY(), aSpawnLocations[0].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); me->SummonCreature(NPC_SCARAB, aSpawnLocations[1].GetPositionX(), aSpawnLocations[1].GetPositionY(), aSpawnLocations[1].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); events.ScheduleEvent(EVENT_SUMMON, 50000); return; case EVENT_DUST_MOVE: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, true)) DoCast(target, SPELL_DUST_MOVE); events.ScheduleEvent(EVENT_DUST_MOVE, 15000); return; case EVENT_VORTEX_DUST: if (IsHeroic()) { DoCastAOE(SPELL_VORTEX_DUST); } events.ScheduleEvent(EVENT_VORTEX_DUST, urand(14000, 20000)); return; } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_ptahAI(creature); } }; void AddSC_boss_ptah() { new boss_ptah(); }
[ [ [ 1, 5 ], [ 7, 20 ], [ 22, 22 ], [ 25, 30 ], [ 32, 37 ], [ 39, 41 ], [ 43, 48 ], [ 50, 57 ], [ 59, 63 ], [ 65, 67 ], [ 69, 73 ], [ 75, 80 ], [ 82, 85 ], [ 87, 92 ], [ 94, 102 ], [ 104, 107 ], [ 109, 115 ], [ 117, 120 ], [ 122, 130 ], [ 132, 135 ], [ 137, 137 ], [ 139, 150 ], [ 157, 179 ], [ 181, 185 ], [ 187, 190 ] ], [ [ 6, 6 ], [ 21, 21 ], [ 23, 24 ], [ 31, 31 ], [ 38, 38 ], [ 42, 42 ], [ 49, 49 ], [ 58, 58 ], [ 64, 64 ], [ 68, 68 ], [ 74, 74 ], [ 81, 81 ], [ 86, 86 ], [ 93, 93 ], [ 103, 103 ], [ 108, 108 ], [ 116, 116 ], [ 121, 121 ], [ 131, 131 ], [ 136, 136 ], [ 138, 138 ], [ 151, 156 ], [ 180, 180 ], [ 186, 186 ] ] ]
01fbb83c8bb301aa4abfb875a332965186be79e2
4cc8918e439df4809a1f32212d8971df31800b94
/include/GameState.h
3a1493c4156ba79b4c7d51f6670cc88adaec8e01
[]
no_license
aplusbi/ggj2009
8dc39d4874e39a94b1fb7994e7085ab5b2a8600e
a2b0ad4eacee0ce00cae1538f58bbec486b4eb41
refs/heads/master
2020-04-06T07:09:48.253815
2011-08-16T02:24:11
2011-08-16T02:24:11
2,213,528
0
0
null
null
null
null
UTF-8
C++
false
false
749
h
/////////////////////////////////////////////////////////////////// // File : "CGameState.h" // // Author : Stefan Woskowiak // // Purpose : Contains base class for game states to inherit from. /////////////////////////////////////////////////////////////////// #ifndef _H_GAMESTATE #define _H_GAMESTATE #include "includes.h" #include "BaseState.h" class GameState : public BaseState { static GameState m_Instance; GameState(){} GameState(const GameState& r){} GameState& operator=(const GameState& r){} public: static GameState* getInstance(); void Enter(); bool Update( float fElapsedTime ); bool Render(); void Exit(); void HandleInput(SDL_KeyboardEvent keyPress); }; #endif
[ [ [ 1, 37 ] ] ]
915ee4ea171f509a1f4fe27f32b3dcc86e880abe
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Include/FreeTypePlugin/FreeTypePlugin.h
1c01ff4a4f5bf61d7508805ffde8f5d64e3a0d6f
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
4,893
h
//  // // # # ### # # -= Nuclex Project =-  // // ## # # # ## ## NuclexFreeType.h - FreeType plugin implementation  // // ### # # ###  // // # ### # ### The plugin implementation for nuclex  // // # ## # # ## ##  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #ifndef NUCLEX_FREETYPE_H #define NUCLEX_FREETYPE_H #include "Nuclex/Nuclex.h" #include "Nuclex/Support/Synchronization.h" #include "Nuclex/Kernel.h" #include "FT2Build.h" #include FT_FREETYPE_H // The following block will decide whether symbols are imported from a // dll (client app) or exported to a dll (library). The NUCLEX_EXPORTS symbol // should only be used for compiling the nuclex library and nowhere else. // // If you dynamically link against nuclex, you should define NUCLEX_DLL for // your project in order to import the dll symbols from nuclex. // #ifdef FREETYPEPLUGIN_EXPORTS #define NUCLEXFREETYPE_API __declspec(dllexport) #else #define NUCLEXFREETYPE_API __declspec(dllimport) #endif namespace Nuclex { namespace Text { /// Get the FreeType libraries handle NUCLEXFREETYPE_API FT_Library getFreeTypeLibrary(); /// Get the FreeType mutex used for all thread-critical regions NUCLEXFREETYPE_API Mutex &getFreeTypeMutex(); // ############################################################################################# // // # Nuclex::Text::getFreeTypeErrorDescription() # // // ############################################################################################# // /// Obtain a textual description of a FreeType error code /** Returns a human-readable description of an error given its error code @param nErrorCode The error code whose textual description to look up @return The text associated with the error code specified when calling this function */ NUCLEXFREETYPE_API inline string getFreeTypeErrorDescription(int nErrorCode) { // A little hack to enforce the header to be processed a second time #undef __FTERRORS_H__ // This is FreeType's way to help define our own structure for storing the // FreeType error codes #define FT_ERRORDEF(e, v, s) { e, s }, #define FT_ERROR_START_LIST { #define FT_ERROR_END_LIST { 0, 0 } }; // By including the header below, we actually provide this structure // definition with a list of all the error codes known to FreeType static const struct { int nErrorCode; const char *pszErrorMessage; } FreeTypeErrors[] = #include FT_ERRORS_H // We're done, undef the symbols to not pollute the global namespace #undef FT_ERRORDEF #undef FT_ERROR_START_LIST #undef FT_ERROR_END_LIST // This is the actual error lookup, performed by as a simple incremental search ;) for( size_t ErrorIndex = 0; ErrorIndex < sizeof(FreeTypeErrors) / sizeof(*FreeTypeErrors); ++ErrorIndex ) { // If this is the error code we're looking for, return it! if(FreeTypeErrors[ErrorIndex].nErrorCode == nErrorCode) return FreeTypeErrors[ErrorIndex].pszErrorMessage; } // Error code not found, report it as being an unknown error return string("unknown error ") + lexical_cast<string>(nErrorCode); } }} // namespace Nuclex::Text using namespace Nuclex; //  // //  FreeTypeInitTerm  // //  // /// FreeType global initialization class /** Initializes global DLL data */ class FreeTypeInitTerm { public: /// Constructor /** Initializes global data when the dll enters a process */ FreeTypeInitTerm() { FT_Error Error = ::FT_Init_FreeType(&m_FTLibrary); if(Error) { Kernel::logMessage(Kernel::MT_WARNING, "FreeType library could not be initialized. FreeType support disabled."); return; } Kernel::logMessage(Kernel::MT_INFO, "FreeType initialized successfully."); } /// Destructor /** Destroys global data when the dll leaves a process */ ~FreeTypeInitTerm() { ::FT_Done_FreeType(m_FTLibrary); m_FTLibrary = NULL; } FT_Library getFTLibrary() const { return m_FTLibrary; } private: FT_Library m_FTLibrary; }; DECLARATIONPACKAGE(FreeTypePlugin); #endif // NUCLEX_FREETYPE_H
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 135 ] ] ]
f9d32a0186500cedd9fc407e6bcfec156a59ccfb
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/napplication/src/napplication/nappviewportui_main.cc
b259a8ae94dbdda64ccf85e7cdc99bb4f727dfa7
[]
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
10,043
cc
#include "precompiled/pchnapplication.h" //------------------------------------------------------------------------------ // nappviewportui_main.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "napplication/nappviewportui.h" #include "napplication/nappviewport.h" nNebulaScriptClass(nAppViewportUI, "nroot"); //------------------------------------------------------------------------------ /** */ nAppViewportUI::nAppViewportUI() : singleViewportMode(true), isLayoutDirty(true), isOpen(false), isVisible(false), numViewports(0), curViewport(0), draggingBar(0), borderWidth(4.0f) { // Do not save children. This behavior is needed to persist/restore presets. this->SetSaveModeFlags(this->N_FLAG_SAVESHALLOW); } //------------------------------------------------------------------------------ /** */ nAppViewportUI::~nAppViewportUI() { if (this->isOpen) { this->Close(); } } //------------------------------------------------------------------------------ /** */ void nAppViewportUI::Open() { n_assert(!this->isOpen); this->isOpen = true; // set default client rectangle if none set if (this->absClientRect.width() == 0.0f && this->absClientRect.height() == 0.0f) { const nDisplayMode2& displayMode = nGfxServer2::Instance()->GetDisplayMode(); this->SetClientRect(0, 0, displayMode.GetWidth(), displayMode.GetHeight()); } // load existing viewports if (this->GetNumViewports() > 0) { for (int i = 0; i < this->GetNumViewports(); i++) { this->viewports[i].GetViewport()->Open(); } this->SetCurrentViewport(this->viewports[0].GetViewport()); } // FIXME! initialize maximized mode //this->SwitchMaximized(true); this->UpdateLayout(); } //------------------------------------------------------------------------------ /** Shutdown */ void nAppViewportUI::Close() { n_assert(this->isOpen); this->isOpen = false; // close viewports if (this->GetNumViewports() > 0) { for (int i = 0; i < this->GetNumViewports(); i++) { this->viewports[i].GetViewport()->Close(); } } this->numViewports = 0; } //------------------------------------------------------------------------------ /** Set client area rectangle in pixels. @param */ void nAppViewportUI::SetClientRect(int x, int y, int width, int height) { this->absClientRect.set(vector2(float(x), float(y)), vector2(float(x + width), float(y + height))); this->isLayoutDirty = true; } //------------------------------------------------------------------------------ /** Get client area rectangle. All parameters are in the 0..1 range, relative to the size of the window */ void nAppViewportUI::GetClientRect(int& x, int& y, int& width, int& height) { x = int(this->absClientRect.v0.x); y = int(this->absClientRect.v0.y); width = int(this->absClientRect.width()); height = int(this->absClientRect.height()); } //------------------------------------------------------------------------------ /** */ void nAppViewportUI::SetVisible(const bool visible) { if (visible != this->isVisible) { this->isVisible = visible; if (visible) { this->isLayoutDirty = true; } else { //hide all viewports int i; for (i = 0; i < this->numViewports; i++) { this->GetViewportAt(i)->SetVisible(false); } } this->VisibleChanged(); } } //------------------------------------------------------------------------------ /** Called when the viewport layout has changed the visible attribute. Override in subclasses. */ void nAppViewportUI::VisibleChanged() { // empty } //------------------------------------------------------------------------------ /** Set maximized viewport. */ void nAppViewportUI::SetMaximizedViewport(bool /*value*/) { /// @todo REMOVE this function. It wasn't removed for compatibility with old scripts } //------------------------------------------------------------------------------ /** Set single viewport. */ void nAppViewportUI::SetSingleViewport(bool value) { if (this->singleViewportMode != value) { //this->SwitchSingleSize(); this->singleViewportMode = value; this->isLayoutDirty = true; } } //------------------------------------------------------------------------------ /** Get single viewport. */ bool nAppViewportUI::GetSingleViewport() { return this->singleViewportMode; } //------------------------------------------------------------------------------ /** Set current viewport. */ void nAppViewportUI::SetCurrentViewport(nAppViewport* viewport) { n_assert(viewport); this->curViewport = viewport; } //------------------------------------------------------------------------------ /** Set current viewport. */ nAppViewport* nAppViewportUI::GetCurrentViewport() { return this->curViewport; } //------------------------------------------------------------------------------ /** Set current viewport. */ nAppViewport* nAppViewportUI::FindViewport(const char *name) { for (int i = 0; i < this->numViewports; i++) { if (this->viewports[i].GetName() == name) { return this->GetViewportAt(i); } } return 0; } //------------------------------------------------------------------------------ /** GetNumViewports */ int nAppViewportUI::GetNumViewports() { return this->numViewports; } //------------------------------------------------------------------------------ /** GetNumViewports */ nAppViewport* nAppViewportUI::GetViewportAt(const int index) { n_assert(index < this->numViewports); return this->viewports[index].GetViewport(); } //------------------------------------------------------------------------------ /** Clear all viewports and dockbars */ void nAppViewportUI::ClearAll() { //FIXME this->numViewports = 0; this->dragBars.Clear(); } //------------------------------------------------------------------------------ /** Reset to default state. Reimplement in subclasses. */ void nAppViewportUI::Reset() { // empty } //------------------------------------------------------------------------------ /** Perform input handling and viewport layout. Reimplement in subclasses. */ void nAppViewportUI::Trigger() { if (this->GetVisible()) { this->UpdateLayout(); } } //------------------------------------------------------------------------------ /** Reimplement in subclasses. */ void nAppViewportUI::OnRender3D() { if (!this->GetVisible()) { return; } int i; for (i = 0; i < this->GetNumViewports(); ++i) { if (this->GetViewportAt(i)->GetVisible()) { this->GetViewportAt(i)->OnRender3D(); } } } //------------------------------------------------------------------------------ /** Draw viewport GUI: frames around viewports, selected one, etc. */ void nAppViewportUI::OnRender2D() { if (!this->GetVisible()) { return; } /* static const vector4 VECTOR_DKGREY = nGfxUtils::color24(94, 92, 108); static const vector4 VECTOR_YELLOW = nGfxUtils::color24(225, 225, 0);//(230,160,6); for orange static const vector4 VECTOR_RED = nGfxUtils::color24(225, 0, 0); nGfxServer2::Instance()->BeginLines(); if (!this->singleViewportMode) { // FIXME check for docked viewports //this->DrawRectangle(this->clientRect, 0, 0, COLOR_DKGREY); //for (int i = 0; i < this->numViewports; i++) //{ // this->DrawRectangle(this->viewports[i]->GetViewportRect(), 0, 0, COLOR_DKGREY); //} //draw rectangle around current viewport this->lineDraw.DrawRectangle2DRelBorder(this->curViewport->GetViewportRect(), 1, 3, VECTOR_YELLOW); //draw dragbars when dragging or highlighted vector2 mousePos = nInputServer::Instance()->GetMousePos(); //if (this->clientRect.inside(mousePos)) { //bool isMouseOverGui = nGuiServer::Instance()->IsMouseOverGui(); //if (!isMouseOverGui) //{ DragBar* highlight = 0; for (int i = 0; i < this->dragBars.Size(); i++) { if (dragBars[i].rect.inside(mousePos)) { highlight = &dragBars[i]; break; } } if (nGfxServer2::Instance()->GetCursorVisibility() != nGfxServer2::None) { if (this->draggingBar) { this->lineDraw.DrawRectangle2DRelBorder(this->draggingBar->rect, -3, -1, VECTOR_RED); } else if (highlight) { this->lineDraw.DrawRectangle2DRelBorder(highlight->rect, -3, -1, VECTOR_RED); } } //} } } nGfxServer2::Instance()->EndLines(); */ } //------------------------------------------------------------------------------ /** */ void nAppViewportUI::OnFrameBefore() { // empty } //------------------------------------------------------------------------------ /** */ void nAppViewportUI::OnFrameRendered() { // empty }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 391 ] ] ]
664edcad0ecaf0ff35ae68cfd5a09411c1186c4c
52f70251d04ca4f42ba3cb991727003a87d2c358
/src/pragma/system/clock.h
707daa45d76415d6ca8cf6603760f3dbc28ec43d
[ "MIT" ]
permissive
vicutrinu/pragma-studios
71a14e39d28013dfe009014cb0e0a9ca16feb077
181fd14d072ccbb169fa786648dd942a3195d65a
refs/heads/master
2016-09-06T14:57:33.040762
2011-09-11T23:20:24
2011-09-11T23:20:24
2,151,432
0
0
null
null
null
null
UTF-8
C++
false
false
145
h
#pragma once #include <pragma/types.h> namespace pragma { typedef uint32 TMillisecond; TMillisecond GetTimeMilliseconds(); }
[ [ [ 1, 12 ] ] ]
4b9b5386e08525962ffcd00278679877f3b51f35
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/trunk/engine/core/include/Actor.h
9a94830b83889aa8a3f22dc83e94f36b006bb9ba
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,453
h
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #ifndef __Actor_H__ #define __Actor_H__ #include "CorePrerequisites.h" #include <map> #include <vector> namespace Ogre { class Bone; } namespace rl { class PhysicalThing; class ActorControlledObject; class MovableText; class Actor; class GameAreaEventSource; // this is used to notify a gameobject (which is derived from ActorNotifiedObject) if his actor was deleted class ActorNotifiedObject { public: virtual void setActor(Actor*) = 0; }; typedef std::map<const Ogre::String,Actor*> ActorMap; typedef std::vector<Actor*> ActorVector; typedef std::pair<const Ogre::String,Actor*> ActorPair; class _RlCoreExport Actor : public Ogre::Node::Listener { public: static const Ogre::String DEFAULT_SLOT_NAME; enum UpdateFlags { UF_NONE = 0, UF_PHYSICAL_THING = 1, UF_CHILDREN = 2, UF_SCENE_NODE = 4, UF_CONTROLLED = 8, UF_ALL = 0xFFFFFFFF }; Actor(const Ogre::String& name, ActorControlledObject* aco = NULL, PhysicalThing* pt = NULL, ActorNotifiedObject* go = NULL); /** Dekonstruktor * @remark Nicht direkt aufrufen, * sondern ActorManager::destroyActor() benutzen. */ ~Actor(); /// Gibt den eindeutigen Namen des Aktors zur๏ฟฝck const Ogre::String& getName() const; /// Gibt das UserdefinedObject der n๏ฟฝchsten Schicht zur๏ฟฝck ActorNotifiedObject* getGameObject() const; /// Setzt das UserdefinedObject der n๏ฟฝchsten Schicht void setGameObject(ActorNotifiedObject* uo); /// Gibt die Physikalische Repr๏ฟฝsentation zur๏ฟฝck PhysicalThing* getPhysicalThing() const; /// Setzt die Physikalische Repr๏ฟฝsentation void setPhysicalThing( PhysicalThing* pt ); /// Gibt das kontrollierte Objekt zur๏ฟฝck ActorControlledObject* getControlledObject() const; /// Setzt das kontrollierte Objekt void setControlledObject( ActorControlledObject* act ); /** F๏ฟฝgt diesen Aktor in einen SzenenKnoten ein. * * @param parent Der SzenenKnoten in den der Aktor eingef๏ฟฝgt werden soll * @param offsetPosition Die Verschiebung * @param offsetOrientation Die Drehung * @param physicsBone Der Knochen an den die * Physikalische Verkn๏ฟฝpfung gebunden werden soll * */ void placeIntoNode( Ogre::SceneNode* parent, const Ogre::Vector3& offsetPosition = Ogre::Vector3::ZERO, const Ogre::Quaternion& offsetOrientation = Ogre::Quaternion::IDENTITY, const Ogre::String& physicsBone = ""); /** F๏ฟฝgt diesen Aktor in die Szene (der RootNode) ein. * * @param offsetPosition Die Verschiebung * @param offsetOrientation Die Drehung * @param physicsBone Der Knochen an den die * Physikalische Verkn๏ฟฝpfung gebunden werden soll * */ void placeIntoScene( const Ogre::Vector3& position = Ogre::Vector3::ZERO, const Ogre::Quaternion& orientation = Ogre::Quaternion::IDENTITY, const Ogre::String& physicsBone = ""); /// F๏ฟฝgt diesen Aktor in die Szene (der RootNode) ein. void placeIntoScene( Ogre::Real px, Ogre::Real py, Ogre::Real pz, Ogre::Real ow, Ogre::Real ox, Ogre::Real oy, Ogre::Real oz, const Ogre::String& physicsBone = ""); /// Entfernt den Aktor aus der Szene void removeFromScene(); /// Gibt die Anfrage-Maske zur๏ฟฝck, unsigned long getQueryFlags() const; /// Setzt die Anfrage-Maske void setQueryFlags( unsigned long mask = 0xFFFFFFFF ); /// F๏ฟฝgt der Anfrage-Maske ein Flag hinzu void addQueryFlag( unsigned long flag ); /// Entfernt ein Flag aus der Anfrage-Maske void removeQueryFlag( unsigned long flag ); /// Gibt die aktuelle Position des Aktors relativ zu seinem Parent zur๏ฟฝck const Ogre::Vector3& getPosition(void) const; /// Gibt die aktuelle Position des Aktors relativ zur Welt zur๏ฟฝck const Ogre::Vector3& getWorldPosition(void) const; /// Ermittelt die aktuelle Geschwindigkeit des Actors, falls moeglich const Ogre::Vector3 getVelocity() const; /// Setzt die Position des Aktors relativ zu seinem Parent void setPosition(const Ogre::Vector3& vec); /// Setzt die Position des Aktors relativ zu seinem Parent void setPosition(Ogre::Real x, Ogre::Real y, Ogre::Real z); /// Skaliert den Aktor void setScale( Ogre::Real sx, Ogre::Real sy, Ogre::Real sz ); /// Gibt die Orientierung des Aktors relativ zu seinem Parent zur๏ฟฝck const Ogre::Quaternion& getOrientation(void) const; /// Gibt die Orientierung des Aktors relativ zur Welt zur๏ฟฝck const Ogre::Quaternion& getWorldOrientation(void) const; /// Gibt die bounding box in world space zur๏ฟฝck. Ogre::AxisAlignedBox getWorldBoundingBox() const; /// Setzt die Orientierung des Aktors void setOrientation(const Ogre::Quaternion& orientation); /// Bewegt den Aktor an seiner Achse entlang void translate(const Ogre::Vector3& d, Ogre::Node::TransformSpace ts); /// Dreht den Aktor um seine Z-Achse void roll(Ogre::Real angleunits); /// Dreht den Aktor um seine Z-Achse void pitch(Ogre::Real angleunits); /// Dreht den Aktor um seine Z-Achse void yaw(Ogre::Real angleunits); /// Dreht den Aktor void rotate(const Ogre::Quaternion& q, Ogre::Node::TransformSpace ts); /** * Befestigt einen anderen Aktor ๏ฟฝber einen UnterNode an diesem Aktors. * * @param actor Der Aktor * @param childSlot Der Slot an dem zu befestigenden Aktor, wenn DEFAULT_SLOT_NAME ignoriert * verursacht zus๏ฟฝtzliche Offset/Drehung * @param offsetPosition Die zus๏ฟฝtzliche Verschiebung * @param offsetOrientation Die zus๏ฟฝtzliche Drehung */ void attach( Actor* actor, const Ogre::String& childSlot = "SLOT_DEFAULT", const Ogre::Vector3& offsetPosition=Ogre::Vector3::ZERO, const Ogre::Quaternion& offsetOrientation=Ogre::Quaternion::IDENTITY ); /** * Befestigt einen anderen Aktor ๏ฟฝber einen UnterNode an diesem Aktors. * * @param actor Der Aktor * @param childSlot Der Slot an dem zu befestigenden Aktor, wenn DEFAULT_SLOT_NAME ignoriert, * verursacht zus๏ฟฝtzliche Offset/Drehung * @param offsetPosition Die zus๏ฟฝtzliche Verschiebung * @param offsetAxis Die Achse der zus๏ฟฝtzlichen Drehung * @param offsetRotation Die zus๏ฟฝtzliche Drehung */ void attachAxisRot( Actor* actor, const Ogre::String& childSlot = "SLOT_DEFAULT", const Ogre::Vector3& offsetPosition=Ogre::Vector3::ZERO, const Ogre::Vector3& offsetAxis=Ogre::Vector3::UNIT_X, const Ogre::Radian& offsetRotation=Ogre::Radian(0) ); /** * Befestigt einen anderen Aktor an einem SLOT dieses Aktors. * * @param actor Der Aktor * @param slot Der Slot an diesem Aktor, wenn DEFAULT_SLOT_NAME ignoriert * @param childSlot Der Slot an dem zu befestigenden Aktor, wenn DEFAULT_SLOT_NAME ignoriert, * verursacht zus๏ฟฝtzliche Offset/Drehung * @param offsetPosition Die zus๏ฟฝtzliche Verschiebung * @param offsetOrientation Die zus๏ฟฝtzliche Drehung */ void attachToSlot( Actor* actor, const Ogre::String& slot, const Ogre::String& childSlot = "SLOT_DEFAULT", const Ogre::Vector3& offsetPosition=Ogre::Vector3::ZERO, const Ogre::Quaternion& offsetOrientation=Ogre::Quaternion::IDENTITY); /** * Befestigt einen anderen Aktor an einem SLOT dieses Aktors. * * @param actor Der Aktor * @param slot Der Slot an diesem Aktor, wenn DEFAULT_SLOT_NAME ignoriert * @param childSlot Der Slot an dem zu befestigenden Aktor, wenn DEFAULT_SLOT_NAME ignoriert, * verursacht zus๏ฟฝtzliche Offset/Drehung * @param offsetPosition Die zus๏ฟฝtzliche Verschiebung * @param offsetAxis Die Achse der zus๏ฟฝtzlichen Drehung * @param offsetRotation Die zus๏ฟฝtzliche Drehung */ void attachToSlotAxisRot( Actor* actor, const Ogre::String& slot, const Ogre::String& childSlot = "SLOT_DEFAULT", const Ogre::Vector3& offsetPosition=Ogre::Vector3::ZERO, const Ogre::Vector3& offsetAxis=Ogre::Vector3::UNIT_X, const Ogre::Radian& offsetRotation=Ogre::Radian(0) ); /** Entfernt einen zuvor befestigten Aktor. * @param actor Der zu entfernende Aktor */ void detach(Actor* actor); /// Entfernt alle Kinder vom Node void detachAllChildren(); void merge(Actor* actor, const Ogre::String& slot); /** * Entfernt den Aktor von seinem Elternaktor */ void detachFromParent(); Ogre::SceneNode* _getSceneNode() const; Ogre::MovableObject* _getMovableObject() const; void _update(unsigned long flags = UF_ALL); /// Setzt diesem Aktor ein Highlight void setHighlighted(bool highlight, const CeGuiString& descriptionText = ""); /// Gibt zur๏ฟฝck ob der Aktor gehighlighted ist bool isHighlighted() const; ///@todo mehr Query-Methoden f๏ฟฝr Childs Actor* getChildByName(const Ogre::String& name ) const; bool hasChild(Actor*) const; /// Sets the Visibility void setVisible( bool vis, bool cascade = true ); bool isVisible() const; /// Set Rendering Distance Ogre::Real getRenderingDistance() const; void setRenderingDistance( Ogre::Real dist ); // Die Methoden die Node::Listener definiert. virtual void nodeUpdated (const Ogre::Node *node); virtual void nodeDestroyed (const Ogre::Node *node); virtual void nodeAttached (const Ogre::Node *node); virtual void nodeDetached (const Ogre::Node *node); /// Setze den Listener des Nodes void setListenerOf(Ogre::SceneNode *node); /// gib das Bone zur๏ฟฝck Ogre::Bone *_getBone() const; bool isInScene() const; protected: friend class GameAreaEventSource; /// this is called from the gameareaeventsource when the actor enters it void addToGameArea(GameAreaEventSource *ga); /// this is called from the gameareaeventsource when the actor leaves it void removeFromGameArea(GameAreaEventSource *ga); private: typedef std::set<Actor*> ChildSet; /// Der einzigartige Name Ogre::String mName; /// Verkn๏ฟฝpfung zur Physikalischen Repr๏ฟฝsentation PhysicalThing* mPhysicalThing; /// Verkn๏ฟฝpfung zur N๏ฟฝchsten Schicht ActorNotifiedObject* mGameObject; /// Verkn๏ฟฝpfung zum kontrollierten Objekt ActorControlledObject* mActorControlledObject; /// Der Parent-Aktor Actor* mParent; /// Darunterliegende Aktoren ChildSet mChildren; /// Der SceneNode des Aktors Ogre::SceneNode* mSceneNode; /// MovableText mit der Objektbeschreibung MovableText* mDescription; /// Speichert ob der Aktor zur Zeit leuchtet bool mHighlighted; /// Ist der Aktor an einem Bone angehangen? //bool mAttachedToBone; /// Der Bone, an dem wir vielleicht h๏ฟฝngen. Ogre::Bone *mBone; /// the actor is in these areas, this is needed to notify areas of deleted actors std::list<GameAreaEventSource*> mGameAreas; void doPlaceIntoScene( Ogre::SceneNode* parent, const Ogre::Vector3& position = Ogre::Vector3::ZERO, const Ogre::Quaternion& orientation = Ogre::Quaternion::IDENTITY, const Ogre::String& physicsBone = "" ); /** * K๏ฟฝmmert sich um das Durchf๏ฟฝhren des Befestigens * * @param actor Der Aktor * @param slot Der Slot an diesem Aktor, wenn DEFAULT_SLOT_NAME ignoriert * @param childSlot Der Slot an dem zu befestigenden Aktor, wenn DEFAULT_SLOT_NAME ignoriert * verursacht zus๏ฟฝtzliche Offset/Drehung * @param offsetPosition Die zus๏ฟฝtzliche Verschiebung * @param offsetOrientation Die zus๏ฟฝtzliche Drehung */ void doAttach( Actor* actor, const Ogre::String& slot, const Ogre::String& childSlot, const Ogre::Vector3& offsetPosition, const Ogre::Quaternion& offsetOrientation); /** * K๏ฟฝmmert sich um das Durchf๏ฟฝhren des Abnehmens */ void doDetach(Actor* actor); }; } #endif
[ "tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013", "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013", "josch@4c79e8ff-cfd4-0310-af45-a38c79f83013", "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013", "zero-gravity@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 1 ], [ 3, 4 ], [ 6, 9 ], [ 11, 11 ], [ 13, 13 ], [ 15, 16 ], [ 22, 24 ], [ 31, 34 ], [ 36, 36 ], [ 45, 48 ], [ 51, 52 ], [ 55, 63 ], [ 65, 65 ], [ 69, 69 ], [ 71, 75 ], [ 78, 78 ], [ 83, 83 ], [ 93, 93 ], [ 96, 96 ], [ 98, 100 ], [ 102, 103 ], [ 110, 113 ], [ 115, 118 ], [ 122, 124 ], [ 126, 126 ], [ 128, 129 ], [ 132, 132 ], [ 134, 134 ], [ 152, 152 ], [ 154, 155 ], [ 163, 163 ], [ 165, 166 ], [ 168, 169 ], [ 171, 172 ], [ 174, 174 ], [ 176, 176 ], [ 178, 179 ], [ 182, 182 ], [ 186, 188 ], [ 192, 192 ], [ 202, 204 ], [ 209, 209 ], [ 218, 222 ], [ 226, 226 ], [ 235, 239 ], [ 244, 244 ], [ 249, 249 ], [ 254, 257 ], [ 276, 276 ], [ 281, 282 ], [ 284, 286 ], [ 288, 294 ], [ 296, 296 ], [ 308, 308 ], [ 311, 311 ], [ 313, 313 ], [ 317, 317 ], [ 319, 319 ], [ 323, 325 ], [ 344, 347 ], [ 351, 351 ], [ 357, 357 ], [ 361, 361 ], [ 364, 364 ] ], [ [ 2, 2 ], [ 5, 5 ], [ 10, 10 ], [ 12, 12 ], [ 14, 14 ], [ 17, 21 ], [ 29, 30 ], [ 39, 39 ], [ 49, 50 ], [ 76, 76 ], [ 79, 79 ], [ 81, 81 ], [ 84, 84 ], [ 86, 86 ], [ 89, 89 ], [ 95, 95 ], [ 97, 97 ], [ 101, 101 ], [ 109, 109 ], [ 114, 114 ], [ 119, 119 ], [ 121, 121 ], [ 131, 131 ], [ 136, 136 ], [ 143, 143 ], [ 145, 145 ], [ 159, 159 ], [ 161, 161 ], [ 164, 164 ], [ 185, 185 ], [ 189, 191 ], [ 195, 195 ], [ 201, 201 ], [ 205, 208 ], [ 210, 210 ], [ 223, 225 ], [ 232, 232 ], [ 240, 243 ], [ 245, 245 ], [ 258, 267 ], [ 271, 271 ], [ 273, 274 ], [ 277, 277 ], [ 295, 295 ], [ 298, 299 ], [ 312, 312 ], [ 314, 314 ], [ 316, 316 ], [ 321, 321 ], [ 330, 330 ], [ 343, 343 ], [ 348, 350 ], [ 360, 360 ], [ 365, 366 ] ], [ [ 25, 28 ], [ 64, 64 ], [ 270, 270 ], [ 297, 297 ], [ 329, 329 ], [ 331, 331 ] ], [ [ 35, 35 ], [ 37, 38 ], [ 40, 44 ], [ 68, 68 ], [ 80, 80 ], [ 82, 82 ], [ 148, 150 ], [ 279, 279 ], [ 300, 306 ], [ 315, 315 ], [ 333, 335 ] ], [ [ 53, 54 ], [ 66, 67 ], [ 70, 70 ], [ 77, 77 ], [ 85, 85 ], [ 87, 88 ], [ 90, 92 ], [ 94, 94 ], [ 104, 108 ], [ 120, 120 ], [ 125, 125 ], [ 127, 127 ], [ 130, 130 ], [ 133, 133 ], [ 135, 135 ], [ 137, 142 ], [ 144, 144 ], [ 146, 147 ], [ 151, 151 ], [ 153, 153 ], [ 156, 158 ], [ 160, 160 ], [ 162, 162 ], [ 167, 167 ], [ 170, 170 ], [ 173, 173 ], [ 175, 175 ], [ 177, 177 ], [ 180, 181 ], [ 183, 184 ], [ 193, 194 ], [ 196, 200 ], [ 211, 217 ], [ 227, 231 ], [ 233, 234 ], [ 246, 248 ], [ 250, 253 ], [ 268, 269 ], [ 272, 272 ], [ 275, 275 ], [ 278, 278 ], [ 280, 280 ], [ 283, 283 ], [ 287, 287 ], [ 307, 307 ], [ 309, 310 ], [ 318, 318 ], [ 320, 320 ], [ 322, 322 ], [ 326, 328 ], [ 332, 332 ], [ 336, 342 ], [ 352, 356 ], [ 358, 359 ], [ 362, 363 ] ] ]
23dbc8fe65ae803a57bedfedb426e841cf333588
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SETools/SEToolsCommon/SECollada/SEColladaUnimaterialMesh.cpp
c8eece8ecb4273ffd650c46dd4b44c67b6c5d3d4
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
GB18030
C++
false
false
11,618
cpp
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #include "SEToolsCommonPCH.h" #include "SEColladaUnimaterialMesh.h" #include <algorithm> #include <vector> using namespace Swing; using namespace std; //---------------------------------------------------------------------------- SEColladaUnimaterialMesh::SEColladaUnimaterialMesh() { m_iVCount = 0; m_aVertex = 0; m_aNormal = 0; m_iCCount = 0; m_aColor = 0; m_iTCount = 0; m_aTexture = 0; m_iFCount = 0; m_aiFace = 0; m_aiCFace = 0; m_aiTFace = 0; } //---------------------------------------------------------------------------- int& SEColladaUnimaterialMesh::VCount() { return m_iVCount; } //---------------------------------------------------------------------------- SEVector3f*& SEColladaUnimaterialMesh::Vertex() { return m_aVertex; } //---------------------------------------------------------------------------- SEVector3f*& SEColladaUnimaterialMesh::Normal() { return m_aNormal; } //---------------------------------------------------------------------------- int& SEColladaUnimaterialMesh::CCount() { return m_iCCount; } //---------------------------------------------------------------------------- SEColorRGB*& SEColladaUnimaterialMesh::Color() { return m_aColor; } //---------------------------------------------------------------------------- int& SEColladaUnimaterialMesh::TCount() { return m_iTCount; } //---------------------------------------------------------------------------- SEVector2f*& SEColladaUnimaterialMesh::SETexture() { return m_aTexture; } //---------------------------------------------------------------------------- int& SEColladaUnimaterialMesh::FCount() { return m_iFCount; } //---------------------------------------------------------------------------- int*& SEColladaUnimaterialMesh::Face() { return m_aiFace; } //---------------------------------------------------------------------------- int*& SEColladaUnimaterialMesh::CFace() { return m_aiCFace; } //---------------------------------------------------------------------------- int*& SEColladaUnimaterialMesh::TFace() { return m_aiTFace; } //---------------------------------------------------------------------------- SEMaterialStatePtr& SEColladaUnimaterialMesh::MState() { return m_spSEMaterialState; } //---------------------------------------------------------------------------- SETexturePtr& SEColladaUnimaterialMesh::TState() { return m_spTState; } //---------------------------------------------------------------------------- void SEColladaUnimaterialMesh::DuplicateGeometry() { // ๅปบ็ซ‹ไธ€ไธชๅฝ“ๅ‰็ฝ‘ๆ ผ็š„้กถ็‚นๅฑžๆ€งๆ•ฐ็ป„, // ่ฏฅๆ•ฐ็ป„่กจๆ˜Žไบ†ๅฝ“ๅ‰็ฝ‘ๆ ผ็š„ๆฏไธช้กถ็‚น่ขซๅนณ้ข็ดขๅผ•็š„ๆฌกๆ•ฐ, // ๆฏไธช้กถ็‚นๆฏๆฌก่ขซๅนณ้ข็ดขๅผ•ๆ—ถ,ๅฏ่ƒฝไฝฟ็”จไธๅŒ็š„้กถ็‚น้ขœ่‰ฒๅ’Œ็บน็†ๅๆ ‡. vector<VertexAttr>* aVArray = SE_NEW vector<VertexAttr>[m_iVCount]; int i; for( i = 0; i < 3*m_iFCount; i++ ) { VertexAttr tempAttr; tempAttr.V = m_aiFace[i]; if( m_iCCount > 0 ) { tempAttr.C = m_aiCFace[i]; } if( m_iTCount > 0 ) { tempAttr.T = m_aiTFace[i]; } aVArray[m_aiFace[i]].push_back(tempAttr); } // ๅฆ‚ๆžœๆŸไธช้กถ็‚น่ขซๅคšๆฌก็ดขๅผ•,ๅนถไธ”ๅœจ่ฟ™ไบ›็ดขๅผ•ไธญๆŒ‡ๅฎšไบ†ไธๅŒ็š„้กถ็‚น้ขœ่‰ฒๆˆ–็บน็†ๅๆ ‡, // ๅˆ™ๆ นๆฎๆˆ‘ไปฌ็š„ๆ•ฐๆฎ่ฆๆฑ‚,่ฏฅ้กถ็‚นๅบ”่ฏฅ่ขซๅคๅˆถ,ๅคๅˆถๅ‡บ็š„ๆ–ฐ้กถ็‚นไฝฟ็”จๅŒๆ ท็š„้กถ็‚น็ดขๅผ•, // ไฝ†ไฝฟ็”จไบ†ไธๅŒ็š„้ขœ่‰ฒๆˆ–็บน็†ๅๆ ‡็ดขๅผ•. // ๅ› ๆญคไธบไบ†ๅŒ…ๅซ่ฟ™ไบ›ๆ–ฐๅคๅˆถๅ‡บ็š„้กถ็‚น,่ฎก็ฎ—ๆ€ปๅ…ฑ้œ€่ฆๅคšๅฐ‘้กถ็‚น. int iNewVCount = 0; for( i = 0; i < m_iVCount; i++ ) { // ็กฎไฟๅ”ฏไธ€ๆ€ง,็งป้™ค้‡ๅค็š„็ดขๅผ•. sort(aVArray[i].begin(), aVArray[i].end()); vector<VertexAttr>::iterator pEnd = unique(aVArray[i].begin(), aVArray[i].end()); aVArray[i].erase(pEnd, aVArray[i].end()); iNewVCount += (int)aVArray[i].size(); } // ๅˆ†้…Swing Engineๅ‡ ไฝ•ไฝ“ๆ‰€้œ€ๆ•ฐๆฎ. SEVector3f* aNewVertex = SE_NEW SEVector3f[iNewVCount]; SEVector3f* aNewNormal = SE_NEW SEVector3f[iNewVCount]; SEColorRGB* aNewColor = 0; if( m_iCCount > 0 ) { aNewColor = SE_NEW SEColorRGB[iNewVCount]; } SEVector2f* aNewTexture = 0; if( m_iTCount > 0 ) { aNewTexture = SE_NEW SEVector2f[iNewVCount]; } int j, k; for( i = 0, k = 0; i < m_iVCount; i++ ) { vector<VertexAttr>& rVArray = aVArray[i]; int iSize = (int)rVArray.size(); for( j = 0; j < iSize; j++, k++ ) { aNewVertex[k] = m_aVertex[i]; aNewNormal[k] = m_aNormal[i]; VertexAttr tempAttr = rVArray[j]; if( aNewColor ) { aNewColor[k] = m_aColor[tempAttr.C]; } if( aNewTexture ) { aNewTexture[k] = m_aTexture[tempAttr.T]; } // ๅคๅˆถๅฝ“ๅ‰slotไธญ็š„ๆฏไธช้กถ็‚นๅฑžๆ€ง,ไพ›็จๅŽไฝฟ็”จ. tempAttr.V = k; rVArray.push_back(tempAttr); } } // ไฟฎๆ”นๅนณ้ข้กถ็‚น็ดขๅผ•,ไฝฟๅ…ถ็ดขๅผ•ๅˆฐๆ–ฐๅˆ›ๅปบ็š„้‡ๅค้กถ็‚น. for( i = 0; i < m_iFCount; i++ ) { int iThreeI = 3 * i; int* aiVIndex = m_aiFace + iThreeI; int* aiCIndex = ( m_iCCount > 0 ? m_aiCFace + iThreeI : 0 ); int* aiTIndex = ( m_iTCount > 0 ? m_aiTFace + iThreeI : 0 ); for( j = 0; j < 3; j++ ) { VertexAttr tempAttr; tempAttr.V = aiVIndex[j]; if( aiCIndex ) { tempAttr.C = aiCIndex[j]; } if( aiTIndex ) { tempAttr.T = aiTIndex[j]; } // VArrayไธญๆœ‰NไธชๅŽŸๅง‹้กถ็‚นๅฑžๆ€งๅ’ŒNไธชๅคๅˆถๅ‡บ็š„้กถ็‚นๅฑžๆ€ง. vector<VertexAttr>& rVArray = aVArray[aiVIndex[j]]; int iHalfSize = (int)rVArray.size()/2; for( k = 0; k < iHalfSize; k++ ) { if( rVArray[k] == tempAttr ) { // ๆ‰พๅˆฐๅŒน้…็š„้กถ็‚นๅฑžๆ€ง,ๆ›ดๆ–ฐ้กถ็‚น็ดขๅผ•. aiVIndex[j] = rVArray[iHalfSize + k].V; break; } } } } SE_DELETE[] m_aVertex; SE_DELETE[] m_aNormal; SE_DELETE[] m_aColor; SE_DELETE[] m_aTexture; SE_DELETE[] m_aiTFace; m_iVCount = iNewVCount; m_aVertex = aNewVertex; m_aNormal = aNewNormal; m_aColor = aNewColor; m_aTexture = aNewTexture; SE_DELETE[] aVArray; } //---------------------------------------------------------------------------- SETriMesh* SEColladaUnimaterialMesh::ToTriMesh() { // ๅˆ›ๅปบๆ‰€้œ€Swing Engine VB. SEAttributes tempSEAttr; tempSEAttr.SetPositionChannels(3); if( m_aNormal ) { tempSEAttr.SetNormalChannels(3); } if( m_aColor ) { tempSEAttr.SetColorChannels(0, 3); } if( m_aTexture ) { tempSEAttr.SetTCoordChannels(0, 2); } SEVertexBuffer* pSEVBuffer = SE_NEW SEVertexBuffer(tempSEAttr, m_iVCount); for( int i = 0; i < m_iVCount; i++ ) { (*(SEVector3f*)pSEVBuffer->PositionTuple(i)) = m_aVertex[i]; if( m_aNormal ) { *(SEVector3f*)pSEVBuffer->NormalTuple(i) = m_aNormal[i]; } if( m_aColor ) { *(SEColorRGB*)pSEVBuffer->ColorTuple(0, i) = m_aColor[i]; } if( m_aTexture ) { *(SEVector2f*)pSEVBuffer->TCoordTuple(0, i) = m_aTexture[i]; } } // ๅˆ›ๅปบๆ‰€้œ€Swing Engine IB. SEIndexBuffer* pSEIBuffer = SE_NEW SEIndexBuffer(3 * m_iFCount); int* pSEIBufferData = pSEIBuffer->GetData(); memcpy(pSEIBufferData, m_aiFace, 3*m_iFCount*sizeof(int)); SETriMesh* pSEMesh = SE_NEW SETriMesh(pSEVBuffer, pSEIBuffer); SEEffect* pSEEffect = 0; // ๆ นๆฎSwing Engine็ฝ‘ๆ ผๆ‰€ๅธฆๆ่ดจๅ’Œ็บน็†,ไธบๅ…ถๆทปๅŠ effect. // ็›ฎๅ‰ๅฏผๅ‡บๅ™จๆ”ฏๆŒ็š„ๆ่ดจๅ’Œ็บน็†effectๆ˜ฏ: // SEMaterialEffect,SEMaterialTextureEffect,SEDefaultShaderEffect. if( m_spSEMaterialState ) { pSEMesh->AttachGlobalState(m_spSEMaterialState); if( m_spTState ) { // ๅพ…ๅฎž็Žฐ. // ๅฝ“ๆ‹†ๅˆ†็ฝ‘ๆ ผๅŽๅฆ‚ไฝ•ๅค„็†ๅคš้‡็บน็†? SEImage* pImage = m_spTState->GetImage(); SE_ASSERT( pImage ); if( pImage ) { std::string tempFName = pImage->GetName(); // ๅ‡ๅŽป".seif"้•ฟๅบฆ. size_t uiLength = strlen(tempFName.c_str()) - 5; char tempBuffer[64]; SESystem::SE_Strncpy(tempBuffer, 64, tempFName.c_str(), uiLength); tempBuffer[uiLength] = 0; pSEEffect = SE_NEW SEMaterialTextureEffect(tempBuffer); } } else { pSEEffect = SE_NEW SEDefaultShaderEffect; if( m_aTexture ) { SE_DELETE[] m_aTexture; } } } // ็†่ฎบไธŠไธๅฏ่ƒฝๅ‡บ็Žฐ่ฟ™็งๆƒ…ๅ†ต. if( !m_spSEMaterialState && m_spTState ) { SE_ASSERT( false ); } if( !m_spSEMaterialState && !m_spTState ) { pSEEffect = SE_NEW SEDefaultShaderEffect; } if( pSEEffect ) { pSEMesh->AttachEffect(pSEEffect); } return pSEMesh; } //---------------------------------------------------------------------------- SEColladaUnimaterialMesh::VertexAttr::VertexAttr() { V = -1; C = -1; T = -1; } //---------------------------------------------------------------------------- bool SEColladaUnimaterialMesh::VertexAttr::operator==(const VertexAttr& rAttr) const { return V == rAttr.V && C == rAttr.C && T == rAttr.T; } //---------------------------------------------------------------------------- bool SEColladaUnimaterialMesh::VertexAttr::operator<(const VertexAttr& rAttr) const { if( V < rAttr.V ) { return true; } if( V > rAttr.V ) { return false; } if( C < rAttr.C ) { return true; } if( C > rAttr.C ) { return false; } return T < rAttr.T; } //----------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 389 ] ] ]
8444a009c5e326d703b6cfc9b2987949cfbfa70c
e31046aee3ad2d4600c7f35aaeeba76ee2b99039
/trunk/libs/bullet/includes/BulletCollision/CollisionShapes/btCollisionShape.h
0f46e851c2c806d9a135892ffdad969abfd572e8
[]
no_license
BackupTheBerlios/trinitas-svn
ddea265cf47aff3e8853bf6d46861e0ed3031ea1
7d3ff64a7d0e5ba37febda38e6ce0b2d0a4b6cca
refs/heads/master
2021-01-23T08:14:44.215249
2009-02-18T19:37:51
2009-02-18T19:37:51
40,749,519
0
0
null
null
null
null
UTF-8
C++
false
false
3,656
h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef COLLISION_SHAPE_H #define COLLISION_SHAPE_H #include "LinearMath/btTransform.h" #include "LinearMath/btVector3.h" #include "LinearMath/btMatrix3x3.h" #include "LinearMath/btPoint3.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" //for the shape types ///The btCollisionShape class provides an interface for collision shapes that can be shared among btCollisionObjects. class btCollisionShape { protected: int m_shapeType; void* m_userPointer; public: btCollisionShape() : m_shapeType (INVALID_SHAPE_PROXYTYPE), m_userPointer(0) { } virtual ~btCollisionShape() { } ///getAabb returns the axis aligned bounding box in the coordinate frame of the given transform t. virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const =0; virtual void getBoundingSphere(btVector3& center,btScalar& radius) const; ///getAngularMotionDisc returns the maximus radius needed for Conservative Advancement to handle time-of-impact with rotations. virtual btScalar getAngularMotionDisc() const; ///calculateTemporalAabb calculates the enclosing aabb for the moving object over interval [0..timeStep) ///result is conservative void calculateTemporalAabb(const btTransform& curTrans,const btVector3& linvel,const btVector3& angvel,btScalar timeStep, btVector3& temporalAabbMin,btVector3& temporalAabbMax) const; #ifndef __SPU__ SIMD_FORCE_INLINE bool isPolyhedral() const { return btBroadphaseProxy::isPolyhedral(getShapeType()); } SIMD_FORCE_INLINE bool isConvex() const { return btBroadphaseProxy::isConvex(getShapeType()); } SIMD_FORCE_INLINE bool isConcave() const { return btBroadphaseProxy::isConcave(getShapeType()); } SIMD_FORCE_INLINE bool isCompound() const { return btBroadphaseProxy::isCompound(getShapeType()); } ///isInfinite is used to catch simulation error (aabb check) SIMD_FORCE_INLINE bool isInfinite() const { return btBroadphaseProxy::isInfinite(getShapeType()); } virtual void setLocalScaling(const btVector3& scaling) =0; virtual const btVector3& getLocalScaling() const =0; virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const = 0; //debugging support virtual const char* getName()const =0 ; #endif //__SPU__ int getShapeType() const { return m_shapeType; } virtual void setMargin(btScalar margin) = 0; virtual btScalar getMargin() const = 0; ///optional user data pointer void setUserPointer(void* userPtr) { m_userPointer = userPtr; } void* getUserPointer() const { return m_userPointer; } }; #endif //COLLISION_SHAPE_H
[ "paradoxon@ab3bda7c-5b37-0410-9911-e7f4556ba333" ]
[ [ [ 1, 111 ] ] ]
7e5db078d780e143d6bf9639745c0eb8919286f0
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/opensteer/src/GlobalData.cpp
b0f8bbb251230972a96d181d5ab30e478da70d53
[ "MIT" ]
permissive
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
9,638
cpp
//----------------------------------------------------------------------------- // Copyright (c) 2009, Jan Fietz, Cyrus Preuss // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of EduNetGames nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #include "OpenSteer/GlobalData.h" #include "OpenSteer/AbstractPlugin.h" #include "OpenSteer/AbstractVehicle.h" #include "OpenSteer/SimplePlayer.h" #include "OpenSteer/PluginRegistry.h" #include "OpenSteer/Camera.h" #include "OpenSteer/Clock.h" #include "OpenSteer/GlobalSelection.h" #include "OpenSteer/AbstractRenderer.h" //----------------------------------------------------------------------------- namespace OpenSteer { static bool g_bIsDll = false; static GlobalData* g_pkGlobalData = NULL; GlobalData* GlobalData::ms_pkGlobalDataInstance = NULL; class GlobalDataConstructor { public: GlobalDataConstructor() { g_pkGlobalData = new GlobalData(); }; virtual ~GlobalDataConstructor() { delete g_pkGlobalData; }; }; //------------------------------------------------------------------------- void GlobalData::_SDMInitApp( EduNet::IProfile* pkProfile ) { if( false == GlobalData::hasInstance() ) { OpenSteer::GlobalSelection::_SDMInitApp( ); static GlobalDataConstructor kConstructor; GlobalData* pkGlobalData = g_pkGlobalData; pkGlobalData->initializeGlobalData(); pkGlobalData->m_pkProfile = pkProfile; GlobalData::setInstance( pkGlobalData ); } } //------------------------------------------------------------------------- void GlobalData::_SDMInitDLL( GlobalData* pkGlobalData ) { g_bIsDll = true; GlobalData::setInstance( pkGlobalData ); } //------------------------------------------------------------------------- void GlobalData::setInstance( GlobalData* pkGlobalData ) { GlobalData::ms_pkGlobalDataInstance = pkGlobalData; } //------------------------------------------------------------------------- GlobalData* GlobalData::getInstance( void ) { handleGlobalDataInstanceFailure(); assert( NULL != GlobalData::ms_pkGlobalDataInstance ); return GlobalData::ms_pkGlobalDataInstance; } //------------------------------------------------------------------------- bool GlobalData::hasInstance( void) { return ( NULL != GlobalData::ms_pkGlobalDataInstance ); } //------------------------------------------------------------------------- AbstractPlayer* GlobalData::accessSimpleLocalPlayer( void ) { return GlobalData::getInstance()->m_pkSimpleLocalPlayer; } //------------------------------------------------------------------------- EduNet::IProfile* GlobalData::accessProfile( void ) { return GlobalData::getInstance()->m_pkProfile; } //------------------------------------------------------------------------- Camera* GlobalData::accessCamera( void ) { // pointer to debug validity GlobalData* pkGlobalData = GlobalData::getInstance(); // one static camera instance that automatically tracks selected vehicle return GlobalData::getInstance()->m_pkCamera; } //------------------------------------------------------------------------- Clock* GlobalData::accessClock( void ) { // pointer to debug validity GlobalData* pkGlobalData = GlobalData::getInstance(); return GlobalData::getInstance()->m_pkClock; } //------------------------------------------------------------------------- PluginRegistry* GlobalData::accessPluginRegistry( void ) { return GlobalData::getInstance()->m_pkPluginRegistry; } ////------------------------------------------------------------------------- //AbstractRenderer* GlobalData::accessRenderer( void ) //{ // return GlobalData::getInstance()->m_pkRenderer; //} // ////------------------------------------------------------------------------- //void GlobalData::setRenderer( AbstractRenderer* pkRenderer ) //{ // GlobalData::getInstance()->m_pkRenderer = pkRenderer; //} //------------------------------------------------------------------------- bool GlobalData::getEnableAnnotation( void ) { return GlobalData::getInstance()->m_bEnableAnnotation; } //------------------------------------------------------------------------- void GlobalData::setEnableAnnotation( bool bValue ) { GlobalData::getInstance()->m_bEnableAnnotation = bValue; } //------------------------------------------------------------------------- bool GlobalData::getDrawPhaseActive( void ) { return GlobalData::getInstance()->m_bDrawPhaseActive; } //------------------------------------------------------------------------- void GlobalData::setDrawPhaseActive( bool bValue ) { GlobalData::getInstance()->m_bDrawPhaseActive = bValue; } //------------------------------------------------------------------------- GlobalData::GlobalData( void ): m_pkSimpleLocalPlayer( NULL ), m_pkSimpleController( NULL ), m_pkPluginRegistry( NULL ), m_pkCamera( NULL ), m_pkClock( NULL ), m_pkRenderer( NULL ), m_bShowClientNetworkTrail(0), m_bShowServerNetworkTrail(0), m_NetWriteFPS(20), m_collect3DAnnotations(0), m_bDebugNetStats(1), m_bShowMotionStatePlot(0), m_bEnableAnnotation(true), m_bDrawPhaseActive(false), m_SteeringForceFPS(30), m_bIsDll(false), m_fNetInterpolationDistanceThreshHold(0.05f), m_fNetPositionInterpolationFactor(0.5f) { memset( this->m_bReplicationDataConfig, 0, sizeof(int) * ESerializeDataType_Count); this->m_bReplicationDataConfig[ESerializeDataType_Position] = 1; this->m_bReplicationDataConfig[ESerializeDataType_Forward] = 1; this->m_bReplicationDataConfig[ESerializeDataType_UpdateTicks] = 1; this->m_uiReplicationDataBytes[ESerializeDataType_Position] = sizeof(OpenSteer::Vec3) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_Forward] = sizeof(OpenSteer::Vec3) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_Side] = sizeof(OpenSteer::Vec3) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_Up] = sizeof(OpenSteer::Vec3) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_Force] = sizeof(OpenSteer::Vec3) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_Radius] = sizeof(osScalar) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_Speed] = sizeof(osScalar) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_Orientation] = 0; // this->m_uiReplicationDataBytes[ESerializeDataType_Orientation] = sizeof(btQuaternion) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_CompressedOrientation1] = sizeof(OpenSteer::Vec3) + 2; this->m_uiReplicationDataBytes[ESerializeDataType_CompressedOrientation2] = sizeof(char) * 3 + 2; this->m_uiReplicationDataBytes[ESerializeDataType_CompressedForce] = 0; // this->m_uiReplicationDataBytes[ESerializeDataType_CompressedForce] = sizeof(CompressedVector) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_AngularVelocity] = sizeof(OpenSteer::Vec3) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_LinearVelocity] = sizeof(OpenSteer::Vec3) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_UpdateTicks] = sizeof(size_t) + 1; this->m_uiReplicationDataBytes[ESerializeDataType_ControllerAction] = sizeof(float) + 1; } //------------------------------------------------------------------------- GlobalData::~GlobalData() { if( this == GlobalData::ms_pkGlobalDataInstance ) { GlobalData::ms_pkGlobalDataInstance = NULL; } } void GlobalData::initializeGlobalData( void ) { static PluginRegistry kPluginRegistry; this->m_pkPluginRegistry = &kPluginRegistry; static Camera kCamera; this->m_pkCamera = &kCamera; static Clock kClock; this->m_pkClock = &kClock; static SimplePlayer kPlayer(true); this->m_pkSimpleLocalPlayer = &kPlayer; if( NULL == kPlayer.getController() ) { static SimpleController kController; this->m_pkSimpleController = &kController; kPlayer.setController( &kController ); } } } //! namespace OpenSteer
[ "janfietz@localhost" ]
[ [ [ 1, 256 ] ] ]
f9814e2a7c87d17d6e28b5239ca4f107e595b10e
2f77d5232a073a28266f5a5aa614160acba05ce6
/01.DevelopLibrary/03.Code/CommonLib/FunctionLib/ResultXmlOperator.h
10d85b05b5847eb55b96bcc517eb4bd6548e9ca1
[]
no_license
radtek/mobilelzz
87f2d0b53f7fd414e62c8b2d960e87ae359c81b4
402276f7c225dd0b0fae825013b29d0244114e7d
refs/heads/master
2020-12-24T21:21:30.860184
2011-03-26T02:19:47
2011-03-26T02:19:47
58,142,323
0
0
null
null
null
null
UTF-8
C++
false
false
2,392
h
#ifndef __ResultXmlOperator_h__ #define __ResultXmlOperator_h__ typedef wchar_t UiCodeChar; typedef struct CoreItemData_t { long lPid; long lSid; long lCnt; bool bIsLock; bool bIsRead; UiCodeChar wcFirst; /*CDynamicArray<UiCodeChar>*/CComBSTR bstrTelNo; /*CDynamicArray<UiCodeChar>*/CComBSTR bstrName; /*CDynamicArray<UiCodeChar>*/CComBSTR bstrTime; /*CDynamicArray<UiCodeChar>*/CComBSTR bstrContent; /*CDynamicArray<UiCodeChar>*/CComBSTR bstrDetail; // unsigned short usIcon; UiCodeChar wcFromTo; bool bIsEncode; }stCoreItemData; enum EnCoreType { EN_CORE_NONE = 0, EN_CORE_DOUBLE, EN_CORE_LONG, EN_CORE_WCHAR }; class COMMONLIB_API CCoreSmsUiCtrl { public: CCoreSmsUiCtrl( void ); virtual ~CCoreSmsUiCtrl( void ); public: APP_Result MakeUnReadRltListReq ( UiCodeChar **ppBuf, long *lSize ); APP_Result MakeCtorRltListReq ( UiCodeChar **ppBuf, long *lSize ); APP_Result MakeMsgRltListReq ( UiCodeChar **ppBuf, long *lSize, long lPid, UiCodeChar *pDecode = NULL ); APP_Result MakeSendSmsInfo ( UiCodeChar **ppBuf, long *lSize, UiCodeChar *pwcSmsInfo, UiCodeChar* pwcsNumber ); APP_Result MakeDeleteSmsInfo ( OUT UiCodeChar **ppBuf, OUT long *lSize, IN long *plSid, IN long lCnt ); APP_Result MakeUpdateSmsStatusReq( UiCodeChar **ppBuf, long *lSize, long lSid, long lLock, long lRead ); APP_Result MakePassWordStatusReq ( UiCodeChar **ppBuf, long *lSize, long lPid, UiCodeChar* pwcDataKind, UiCodeChar* pwcCode, UiCodeChar* pwcNewCode ); APP_Result MakeDetailReq ( UiCodeChar **ppBuf, long *lSize, long lSid, UiCodeChar* pwcCode ); APP_Result MakeListRlt ( UiCodeChar *pwcRltStream, stCoreItemData **ppclstItemData, long *plCnt ); APP_Result MakeDetailRlt ( UiCodeChar *pwcRltStream, wchar_t **ppwcDetail ); private: APP_Result MakeNode( CXmlStream *pCXmlStream, UiCodeChar *pNodePath, NodeAttribute_t *pNodeAttribute_t, long lCnt, void *pValue = NULL, EnCoreType _type = EN_CORE_NONE ); APP_Result GetListCnt( CXmlStream *pCXmlStream, long &lCnt ); APP_Result AppendList( CXmlNode *pCXmlNode, stCoreItemData *pclstItemData ); APP_Result GetInfo( IN CXmlNode *pCXmlNode, OUT stCoreItemData *pstItemData ); }; #endif __RequestXmlOperator_h__
[ [ [ 1, 75 ] ] ]
2cd8ed5b771f7d07fe09a079dfa28ed284eff1f6
c7fd308ee062c23e1b036b84bbf890c3f7e74fc4
/simple2/main.cpp
3ef6f15388c4ce9c0a29498b642af1b621995522
[]
no_license
truenite/truenite-opengl
805881d06a5f6ef31c32235fb407b9a381a59ed9
157b0e147899f95445aed8f0d635848118fce8b6
refs/heads/master
2021-01-10T01:59:35.796094
2011-05-06T02:03:16
2011-05-06T02:03:16
53,160,700
0
0
null
null
null
null
UTF-8
C++
false
false
695
cpp
#include <windows.h> #include <GL/glut.h> void miFunc(){ glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); glVertex2f(-.5,-.5); glVertex2f(-.5,.5); glVertex2f(.5,.5); glVertex2f(.5,-.5); glEnd(); glFlush(); } void initValores(){ glClearColor(0,0,0,1); glColor3f(1,1,1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-1,1,-1,1); } main( ){ glutInitDisplayMode(GLUT_RGB); glutInitWindowSize(300,300); glutInitWindowPosition(0,0); glutCreateWindow("simple2"); glutDisplayFunc(miFunc); initValores(); glutMainLoop(); }
[ [ [ 1, 38 ] ] ]
082417ebf8c589c86bd56f8f02ee60928718a979
4d838ba98a21fc4593652e66eb7df0fac6282ef6
/CaveProj/BillboardSpriteDrawer.cpp
436644fe518b77f406f42bd2215b5c7a85066cc2
[]
no_license
davidhart/ProceduralCaveEditor
39ed0cf4ab4acb420fa2ad4af10f9546c138a83a
31264591f2dcd250299049c826aeca18fc52880e
refs/heads/master
2021-01-17T15:10:09.100572
2011-05-03T19:24:06
2011-05-03T19:24:06
69,302,913
0
0
null
null
null
null
UTF-8
C++
false
false
3,493
cpp
#include "BillboardSpriteDrawer.h" #include "RenderWindow.h" #include "Camera.h" #include "ShaderBuilder.h" BillboardSpriteDrawer::BillboardSpriteDrawer() : _renderEffect(NULL), _renderTechnique(NULL), _vertexLayout(NULL), _worldviewprojection(NULL), _invview(NULL), _device(NULL), _batchTexture(NULL), _textureVar(NULL) { } void BillboardSpriteDrawer::Load(RenderWindow& renderWindow) { _device = renderWindow.GetDevice(); _renderEffect = ShaderBuilder::RequestEffect("Assets/billboard_sprite", "fx_4_0", _device); _renderTechnique = _renderEffect->GetTechniqueByName("Render"); D3D10_PASS_DESC PassDesc; _renderTechnique->GetPassByIndex(0)->GetDesc(&PassDesc); D3D10_INPUT_ELEMENT_DESC layoutRender[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0}, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0}, { "TEXCOORD", 0, DXGI_FORMAT_R32_FLOAT, 0, 16, D3D10_INPUT_PER_VERTEX_DATA, 0}, }; UINT numElements = sizeof(layoutRender) / sizeof(layoutRender[0]); _device->CreateInputLayout(layoutRender, numElements, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &_vertexLayout); _invview = _renderEffect->GetVariableByName("InvView")->AsMatrix(); _worldviewprojection = _renderEffect->GetVariableByName("WorldViewProjection")->AsMatrix(); _textureVar = _renderEffect->GetVariableByName("Tex")->AsShaderResource(); } void BillboardSpriteDrawer::Unload() { _vertexLayout->Release(); _vertexLayout = NULL; _renderEffect->Release(); _renderEffect = NULL; _renderTechnique = NULL; _worldviewprojection = NULL; _invview = NULL; _textureVar = NULL; } void BillboardSpriteDrawer::Begin(const Camera& camera) { D3DXMATRIX viewm = camera.GetViewMatrix(); D3DXMATRIX worldviewproj; D3DXMatrixMultiply(&worldviewproj, &viewm, &camera.GetProjectionMatrix()); _worldviewprojection->SetMatrix((float*)&worldviewproj); D3DXMATRIX invview; D3DXMatrixInverse(&invview, NULL, &viewm); _invview->SetMatrix((float*)&invview); _renderTechnique->GetPassByIndex(0)->Apply(0); _device->IASetInputLayout(_vertexLayout); _device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST); } void BillboardSpriteDrawer::End() { Flush(); } void BillboardSpriteDrawer::Draw(const Vector3f& position, float size, DWORD color, ID3D10ShaderResourceView* texture) { if (_batchTexture != texture) { Flush(); _batchTexture = texture; _textureVar->SetResource(texture); } Sprite s; s._position = position; s._size = size; s._color = color; _sprites.push_back(s); } void BillboardSpriteDrawer::Flush() { if (!_sprites.empty()) { D3D10_BUFFER_DESC bd; bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = _sprites.size() *sizeof(Sprite); bd.BindFlags = D3D10_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA InitData; InitData.pSysMem = &_sprites[0]; ID3D10Buffer* buffer; _device->CreateBuffer(&bd, &InitData, &buffer); UINT stride = sizeof(Sprite); UINT offset = 0; _device->IASetVertexBuffers(0, 1, &buffer, &stride, &offset); _device->Draw(_sprites.size(), 0); ID3D10Buffer* null = NULL; _device->IASetVertexBuffers(0, 1, &null, &stride, &offset); // Suppress "currently bound buffer is released" warnings buffer->Release(); _sprites.clear(); } }
[ [ [ 1, 121 ] ] ]
fadcb7661f9079b80c6e5d3245e26363b2589239
8ecce0e77f9be08b26a3a5a92e994a00cb0dfdd4
/SettingsPage.cpp
2fa42d048319a445d45b69c4870880122a3407a3
[ "MIT" ]
permissive
acastroy/bigbrother
c0b044bc12dc2719a3053b1bf3a9f89b078d7d18
09ab4d57cf66855e3ce04477d5baa2376ae2b7e3
refs/heads/master
2023-03-18T17:41:11.568291
2005-08-06T12:07:08
2005-08-06T12:07:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,177
cpp
// SettingsPage.cpp : implementation file // #include "stdafx.h" #include "BigBrother.h" #include "SettingsPage.h" #include "HostPropertyPages.h" #include "BigBrotherDoc.h" #include "BigBrotherView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSettingsPage property page IMPLEMENT_DYNCREATE(CSettingsPage, CPropertyPage) CSettingsPage::CSettingsPage() : CPropertyPage(CSettingsPage::IDD) { //{{AFX_DATA_INIT(CSettingsPage) m_OverrideIntervals = FALSE; m_OverrideRetries = FALSE; m_OverrideTimeout = FALSE; m_IntervalBad = 0; m_IntervalGood = 0; m_TimeOut = 0; m_Retries = 0; //}}AFX_DATA_INIT } CSettingsPage::~CSettingsPage() { } void CSettingsPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSettingsPage) DDX_Control(pDX, IDC_RETRIES, m_RetriesCtl); DDX_Control(pDX, IDC_PINGTIMEOUT, m_TimeOutCtl); DDX_Control(pDX, IDC_PINGINTERVAL_GOOD, m_IntervalGoodCtl); DDX_Control(pDX, IDC_PINGINTERVAL_BAD, m_IntervalBadCtl); DDX_Control(pDX, IDC_OVERRIDE_TIMEOUT, m_OverrideTimeoutCtl); DDX_Control(pDX, IDC_OVERRIDE_RETRIES, m_OverrideRetriesCtl); DDX_Control(pDX, IDC_OVERRIDE_INTERVALS, m_OverrideIntervalsCtl); DDX_Check(pDX, IDC_OVERRIDE_INTERVALS, m_OverrideIntervals); DDX_Check(pDX, IDC_OVERRIDE_RETRIES, m_OverrideRetries); DDX_Check(pDX, IDC_OVERRIDE_TIMEOUT, m_OverrideTimeout); DDX_Text(pDX, IDC_PINGINTERVAL_BAD, m_IntervalBad); DDX_Text(pDX, IDC_PINGINTERVAL_GOOD, m_IntervalGood); DDX_Text(pDX, IDC_PINGTIMEOUT, m_TimeOut); DDX_Text(pDX, IDC_RETRIES, m_Retries); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CSettingsPage, CPropertyPage) //{{AFX_MSG_MAP(CSettingsPage) ON_BN_CLICKED(IDC_OVERRIDE_INTERVALS, OnOverrideIntervals) ON_BN_CLICKED(IDC_OVERRIDE_RETRIES, OnOverrideRetries) ON_BN_CLICKED(IDC_OVERRIDE_TIMEOUT, OnOverrideTimeout) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSettingsPage message handlers void CSettingsPage::SetupControls() { m_IntervalBadCtl.EnableWindow(m_OverrideIntervals); m_IntervalGoodCtl.EnableWindow(m_OverrideIntervals); m_RetriesCtl.EnableWindow(m_OverrideRetries); m_TimeOutCtl.EnableWindow(m_OverrideTimeout); } void CSettingsPage::UpdatePage() { if(!m_dad->m_Brother) return; if(::IsWindow(m_hWnd)){ if(m_dad->m_Brother->m_Daddy){ m_OverrideIntervalsCtl.EnableWindow(TRUE); m_OverrideRetriesCtl.EnableWindow(TRUE); m_OverrideTimeoutCtl.EnableWindow(TRUE); }else{ m_OverrideIntervalsCtl.EnableWindow(FALSE); m_OverrideRetriesCtl.EnableWindow(FALSE); m_OverrideTimeoutCtl.EnableWindow(FALSE); } } if(m_dad->m_Brother->flags&CBrother::flagsOverrideIntervals) m_OverrideIntervals=TRUE; else m_OverrideIntervals=FALSE; if(m_dad->m_Brother->flags&CBrother::flagsOverrideTimeout) m_OverrideTimeout=TRUE; else m_OverrideTimeout=FALSE; if(m_dad->m_Brother->flags&CBrother::flagsOverrideRetries) m_OverrideRetries=TRUE; else m_OverrideRetries=FALSE; m_IntervalBad=m_dad->m_Brother->m_IntervalBad; m_IntervalGood=m_dad->m_Brother->m_IntervalGood; m_Retries=m_dad->m_Brother->m_Retries; m_TimeOut=m_dad->m_Brother->m_TimeOut; if(::IsWindow(m_hWnd)){ UpdateData(FALSE); SetupControls(); } } BOOL CSettingsPage::OnSetActive() { UpdatePage(); return CPropertyPage::OnSetActive(); } void CSettingsPage::OnOverrideIntervals() { UpdateBrother(); if(m_OverrideIntervals) m_IntervalGoodCtl.SetFocus(); } void CSettingsPage::OnOverrideRetries() { UpdateBrother(); if(m_OverrideRetries) m_RetriesCtl.SetFocus(); } void CSettingsPage::OnOverrideTimeout() { UpdateBrother(); if(m_OverrideTimeout) m_TimeOutCtl.SetFocus(); } void CSettingsPage::UpdateBrother() { if(!m_dad->m_Brother){ TRACE0("No brother on update\n"); return; } if(::IsWindow(m_hWnd)) UpdateData(); CBrother toCompare; toCompare = *m_dad->m_Brother; m_dad->m_Brother->m_IntervalBad=m_IntervalBad; m_dad->m_Brother->m_IntervalGood=m_IntervalGood; if(m_OverrideIntervals) m_dad->m_Brother->flags|=CBrother::flagsOverrideIntervals; else m_dad->m_Brother->flags&=~CBrother::flagsOverrideIntervals; m_dad->m_Brother->m_Retries=m_Retries; if(m_OverrideRetries) m_dad->m_Brother->flags|=CBrother::flagsOverrideRetries; else m_dad->m_Brother->flags&=~CBrother::flagsOverrideRetries; m_dad->m_Brother->m_TimeOut=m_TimeOut; if(m_OverrideTimeout) m_dad->m_Brother->flags|=CBrother::flagsOverrideTimeout; else m_dad->m_Brother->flags&=~CBrother::flagsOverrideTimeout; m_dad->m_Brother->ParentalAdjust(); if(toCompare!=(*m_dad->m_Brother)){ CDocument *pDoc = m_dad->m_Daddy->GetDocument(); ASSERT(pDoc); pDoc->SetModifiedFlag(); } if(::IsWindow(m_hWnd)){ UpdateData(FALSE); SetupControls(); } } BOOL CSettingsPage::OnKillActive() { UpdateBrother(); return CPropertyPage::OnKillActive(); }
[ [ [ 1, 186 ] ] ]
8c5b01e2e28415ad5491cfb693b4272bedd92532
6397eabfb8610d3b56c49f7d61bfc6f8636e6e09
/classes/VideoCallReceiver.h
a4cd9f28785a1eb00b86b5ece5a49f65f8b7e0db
[]
no_license
ForjaOMF/OMF-WindowsMFCSDK
947638d047f352ec958623a03d6ab470eae9cedd
cb6e6d1b6b90f91cb3668bc2bc831119b38b0011
refs/heads/master
2020-04-06T06:40:54.080051
2009-10-27T12:22:40
2009-10-27T12:22:40
null
0
0
null
null
null
null
ISO-8859-3
C++
false
false
1,623
h
// VideoCallReceiver.h: archivo de encabezado // #include "VideoCall.h" typedef void (* tagCBStartCall)(DWORD dwCookie, CVideoCall* pVCall); typedef void (* tagCBEndCall)(DWORD dwCookie, CVideoCall* pVCall); class CSIPSocket; class CFrame263; class CVideoCallReceiver : public CObject { // Construcciรณn public: CVideoCallReceiver(CString csLogin, CString csPassword, CString csLocalIP, CString csPath, DWORD dwCookie=0); virtual ~CVideoCallReceiver(); void SetStartCallCB(tagCBStartCall pStartCall){m_pStartCall=pStartCall;}; void SetEndCallCB(tagCBEndCall pEndCall){m_pEndCall=pEndCall;}; void RegisterAttempt(); void Unregister(); // Implementaciรณn protected: CMapStringToOb m_msoCalls; CSIPSocket* m_pSocket; CString m_csNonce; CString m_csPassword; CString m_csLogin; CString m_csLocalIP; CString m_csPath; DWORD m_dwCookie; bool m_bRegistered; UINT m_nRegisterAttempts; static void WINAPI TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); tagCBStartCall m_pStartCall; tagCBEndCall m_pEndCall; void Register(long lExpires); void ReRegister(CString cs401,long lExpires); void AcceptInvitation(CString csInvitation); void SendMultimediaData(CString csAckData); void OnReceiveData(char* pBufData,DWORD dwLenData,int nErrorCode); static void OnEvent(DWORD dwCookie,UINT nCode,char* pBufData,DWORD dwLenData,int nErrorCode); void AckBye(CString csBye); CString GetCallId(CString csData); CString GetBranch(CString csData); CString GetFrom(CString csData); CString GetFromTag(CString csData); };
[ [ [ 1, 63 ] ] ]
957d3df58a082bfb14f0da4b04cbb57804b8e5ce
55d6f54f463bf0f97298eb299674e2065863b263
/joueurIA.h
ffe7b465871d5518994506daefbab323f53a951d
[]
no_license
Coinche/CoinchePAV
a344e69b096ef5fd4e24c98af1b24de2a99235f0
134cac106ee8cea78abc5b29b23a32706b2aad08
refs/heads/master
2020-06-01T09:35:51.793153
2011-12-01T19:57:12
2011-12-01T19:57:12
2,729,958
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,718
h
#ifndef JOUEURIA_H #define JOUEURIA_H #include "joueur.h" #include "carte.h" #include "annonce.h" #include "regles.h" #include "donneur.h" class IA : public Joueur { public: void set_donneur(Donneur* _donneur); protected: Donneur *donneur; }; class IA_dummy : public IA { //Classes hรฉritรฉes : /* Annonce annoncer(); Carte jouer(); //si on le lui demande, le joueur doit dire quelles cartes il lui reste. Main get_main() const; //privรฉe et amie avec Donneur?? peut-etre un peu trop keke dans un premier temps void recevoirMain(const Main&); //privรฉe et amie avec Donneur?? peut-etre un peu trop keke dans un premier temps */ public: Annonce reflechirEtAnnoncer(const std::pair<std::vector<Couleur>, std::vector<Hauteur> > &possibles); Carte reflechirEtJouer(const Main& valides); }; class IA_intermediate : public IA { //Classes hรฉritรฉes : /* Annonce annoncer(); Carte jouer(); //si on le lui demande, le joueur doit dire quelles cartes il lui reste. Main get_main() const; //privรฉe et amie avec Donneur?? peut-etre un peu trop keke dans un premier temps void recevoirMain(const Main&); //privรฉe et amie avec Donneur?? peut-etre un peu trop keke dans un premier temps */ public: Annonce reflechirEtAnnoncer(const std::pair<std::vector<Couleur>, std::vector<Hauteur> > &possibles); Carte reflechirEtJouer(const Main&); private: Hauteur estimerValeurDeLaMain(const Couleur& atout); Hauteur estimerValeurMainAvecPartner(const Couleur& couleurdemandeeparpartner); Annonce MaximiserlAnnonceInitiale(); Hauteur RenvoyerDerniereAnnonceDansLaCouleur(const Encheres& encheresIA, const Couleur& couleurdemandee); Hauteur RenvoyerPremiereAnnonceDansLaCouleur(const Encheres& encheresIA, const Couleur& couleurdemandee); int DeposerNefle(const Couleur& atout, const Main &valides); bool EstMaitre(const Carte& carteATester, const Couleur& atout, const Pli& PliEnCours); Couleur atout; Pli PliEnCours; unsigned int tourAlaCouleur[4]; // on compte les tours unsigned int cartesRestantesalaCouleur[4]; }; class IA_cheater : public Joueur { //Classes hรฉritรฉes : /* Annonce annoncer(); Carte jouer(); //si on le lui demande, le joueur doit dire quelles cartes il lui reste. Main get_main() const; //privรฉe et amie avec Donneur?? peut-etre un peu trop keke dans un premier temps void recevoirMain(const Main&); //privรฉe et amie avec Donneur?? peut-etre un peu trop keke dans un premier temps */ public: Annonce reflechirEtAnnoncer(const Annonce&); int reflechirEtJouer(const Annonce&); Main main; }; #endif //JOUEURIA_H
[ "lucas@graham.(none)" ]
[ [ [ 1, 84 ] ] ]
1744f78ca04c2d3e2a8cc4f1ceb182f6976259e1
2d22825193eacf3669ac8bd7a857791745a9ead4
/HairSimulation/HairSimulation/DynamicsLib/aabb.cpp
8366d39afcf4d43b9949aa8b0fcc03ab7bc9aa80
[]
no_license
dtbinh/com-animation-classprojects
557ba550b575c3d4efc248f7984a3faac8f052fd
37dc800a6f2bac13f5aa4fc7e0e96aa8e9cec29e
refs/heads/master
2021-01-06T20:45:42.613604
2009-01-20T00:23:11
2009-01-20T00:23:11
41,496,905
0
0
null
null
null
null
BIG5
C++
false
false
10,457
cpp
#include <cassert> #include <vector> //#include <list> #include "aabb.h" //~~~~~~~~~ AabbTree ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // prototype bool sphereTri3D_v2( const Vector3 & A, const Vector3 & B, const Vector3 & C, const Vector3 & N, const Vector3 & P, float R2 ); bool AabbTree::testBallTri( const Vector3 & C, float R2 ) const { return ballTriTester( root, C, R2 ); } bool AabbTree::ballTriTester( TreeNode *tptr, const Vector3 &C, float R2 ) const { if( tptr->box.BallBoxIntersect( C, R2 ) ){ if( tptr->left == NULL ){ // leaf node return sphereTri3D_v2( *tptr->facePtr->vPtr[0], *tptr->facePtr->vPtr[1], *tptr->facePtr->vPtr[2], *tptr->facePtr->fnPtr, C, R2 ); }else{ return ( ballTriTester( tptr->left, C, R2 ) || ballTriTester( tptr->right, C, R2 ) ); } } return false; } // return which Tri Face* AabbTree::testBallTri_v2( const Vector3 & C, float R2 ) const { return ballTriTester_v2( root, C, R2 ); } Face* AabbTree::ballTriTester_v2( TreeNode *tptr, const Vector3 &C, float R2 ) const { if( tptr->box.BallBoxIntersect( C, R2 ) ){ if( tptr->left == NULL ){ // leaf node if( sphereTri3D_v2( *tptr->facePtr->vPtr[0], *tptr->facePtr->vPtr[1], *tptr->facePtr->vPtr[2], *tptr->facePtr->fnPtr, C, R2 ) ){ return tptr->facePtr; }else{ return NULL; } }else{ Face *tri = NULL; if( ( tri = ballTriTester_v2( tptr->left, C, R2 ) ) != NULL ){ return tri; }else{ return ballTriTester_v2( tptr->right, C, R2 ); } } } return NULL; } void AabbTree::display() const { // ็ฒ‰็ด… ็ด… ๆฉ™ ้ปƒ ไบฎ็ถ  ๅขจ็ถ  ่—็ถ  ๅคฉ่— ๆทบ่— ๆทฑ่— ็ดซ ็ดซ็ด… Vector3 colorTable[12] = { Vector3(1, 0.6, 0.8), Vector3(1, 0, 0), Vector3(1, 0.6, 0), Vector3(1, 1, 0.6), Vector3(0.6, 1, 0.2), Vector3(0, 0.5, 0), Vector3(0, 1, 0.6), Vector3(0, 0.8, 1), Vector3(0.6, 0.8, 1), Vector3(0.2, 0.2, 1), Vector3(0.6, 0.2, 1), Vector3(1, 0.2, 0.8) }; int depth = 0; postorderVisitor( root, depth, colorTable ); } void AabbTree::postorderVisitor( TreeNode *tptr, int depth, Vector3 *colorTable ) const { if( tptr != NULL ){ //visit node /* Vector3 *c = colorTable + ( depth ); glColor3f( c->x, c->y, c->z ); GLfloat Ks[] = { 0 , 0 , 0 }; GLfloat Ns = 160; glMaterialfv(GL_FRONT, GL_AMBIENT , c->ptr ); //่ฉฒbox็š„ambient้ก่‰ฒ glMaterialfv(GL_FRONT, GL_DIFFUSE , c->ptr); //่ฉฒbox็š„diffuse้ก่‰ฒ glMaterialfv(GL_FRONT, GL_SPECULAR , Ks); //่ฉฒbox็š„specular้ก่‰ฒ glMaterialf(GL_FRONT, GL_SHININESS, Ns); //่ฉฒbox็š„shininessๅผทๅบฆ tptr->box.display(); */ depth++; depth %= 12; postorderVisitor( tptr->left, depth, colorTable ); postorderVisitor( tptr->right, depth, colorTable ); } } void AabbTree::preorder() { preorderVisitor(root); } void AabbTree::preorderVisitor( TreeNode *tptr ) { if( tptr != NULL ){ //visit node if( tptr->left == NULL ){ printf("tree leaf: "); //for(int j = 0; j < 3; j++ ){ // Vec3 v = m_meshData->vList[ (tptr->facePtr)->v[j].v ]; // printf( "(%g,%g,%g)", v.x, v.y, v.z ); //} printf("\n"); } preorderVisitor( tptr->left ); preorderVisitor( tptr->right ); } } void AabbTree::buildTree( std::vector<Face> &faceList, int faceTotal ) { //setup Face* m_facePtrArray m_faceTotal = faceTotal; m_facePtrArray = new Face*[faceTotal]; assert( m_facePtrArray != 0 ); int i = 0; for( std::vector<Face>::iterator fPtr = faceList.begin(); fPtr != faceList.end(); ++fPtr ) { m_facePtrArray[i] = &(*fPtr); ++i; } //ๅปบ็ฏ€้ปž root = NULL; insertTreeNode( &root, m_facePtrArray, 0, m_faceTotal-1 ); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ้ž่ฟดๅปบๅ‡บไธ€ๆฃต Aabb ็š„ tree => BV tree //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void AabbTree::insertTreeNode( TreeNode ** nodePtr, Face **fArray, int start, int end ) { // if subtree is empty, create new TreeNode containing value assert( *nodePtr == 0 ); Vector3 max, min, center; // ็ฎ—ไธ€็พคไธ‰่ง’ๅฝข็š„่ณ‡่จŠ calcTriangleListInfo( fArray, start, end, max, min, center ); *nodePtr = new TreeNode(); (*nodePtr)->facePtr = NULL; (*nodePtr)->left = (*nodePtr)->right = NULL; BoundBox box; box.center = (max+min)/2; box.dim=(max-min)/2; box.bounds[0] = min; box.bounds[1] = max; (*nodePtr)->box = box; assert( max[0] >= min[0] ); assert( max[1] >= min[1] ); assert( max[2] >= min[2] ); // recurssion stop criteria: num of triangle == 1 if( (end-start+1) > 1 ){ int longestAxis = box.longestAxis(); //ๅฐ‡ไธ‰่ง’ๅฝข Array ๅš partition, ไปฅไธ‰่ง’ๅฝข centroid ๅœจๅ“ชๅŠ้‚Šๅšๅˆ†้กž // i ๅทฆ้‚Š็š„ๅ€ผ <= k // j ๅŽปๆ‰พ <= k ็š„ๅ€ผไบคๆ› int i = start - 1; for( int j = start; j <= end; j++ ){ Vector3 c = calcTriangleCenter( fArray[j] ); if( c[longestAxis] <= box.center[longestAxis] ){ i++; //swap A[i],A[j] if( i != j ){ Face* temp = fArray[i]; fArray[i] = fArray[j]; fArray[j] = temp; } } } //่™•็†ๅฆ‚ๆžœๅทฆๅŠ้‚Š / ๅณๅŠ้‚Šๆฒ’ๆœ‰ไปปไฝ•ไธ€ๅ€‹ไธ‰่ง’ๅฝข็š„็‹€ๆณ //่‡ชๅ‹•็งปไธ€ๆ ผ็ตฆๆฒ’ๆœ‰็š„้‚ฃๅŠ้‚Š if( i == start-1 ){ i = start; }else if( i == end ){ i = end-1; } //ๅ€ๅˆ†ๆˆ [start,i], [i+1, end] //ๅš recursion insertTreeNode( &((*nodePtr)->left), fArray, start, i ); insertTreeNode( &((*nodePtr)->right), fArray, i+1, end ); } else{ // stop recurssion (*nodePtr)->facePtr = fArray[start]; } //ๅปบๅฎŒ TreeNode } void AabbTree::update() { postOrderUpdate( root ); } void AabbTree::postOrderUpdate( TreeNode *tPtr ) { // leaf node // ้€™่ฃก tree ็š„ non-leaf node ไธ€ๅฎšๆœ‰ left,right child // ๆชขๆŸฅ left or right ๅฐฑ็Ÿฅๆ˜ฏไธๆ˜ฏ leaf node if( tPtr->left == 0 ){ // update bounding volume Vector3 max, min; max = min = *(tPtr->facePtr->vPtr[0]); for( int i = 1; i < 3; i++ ){ for( int j = 0; j < 3; ++j ){ if( (*(tPtr->facePtr->vPtr[i]))[j] > max[j] ){ max[j] = (*(tPtr->facePtr->vPtr[i]))[j]; }else if( (*(tPtr->facePtr->vPtr[i]))[j] < min[j] ){ min[j] = (*(tPtr->facePtr->vPtr[i]))[j]; } } } tPtr->box.center = (max+min)/2; tPtr->box.dim=(max-min)/2; return; }else{ postOrderUpdate( tPtr->left ); assert( tPtr->right != 0 ); postOrderUpdate( tPtr->right ); //merge children's bounding volume Vector3 min, max; Vector3 minL, maxL; //left box's min,max Vector3 minR, maxR; //right box's min,max BoundBox *b = &(tPtr->left->box); minL = Vector3( b->center[0] -b->dim[0], b->center[1] -b->dim[1], b->center[2] -b->dim[2] ); maxL = Vector3( b->center[0] +b->dim[0], b->center[1] +b->dim[1], b->center[2] +b->dim[2] ); b = &(tPtr->right->box); minR = Vector3( b->center[0] -b->dim[0], b->center[1] -b->dim[1], b->center[2] -b->dim[2] ); maxR = Vector3( b->center[0] +b->dim[0], b->center[1] +b->dim[1], b->center[2] +b->dim[2] ); for( int j = 0; j < 3; ++j ){ max[j] = (maxL[j] > maxR[j] ? maxL[j] : maxR[j] ); min[j] = (minL[j] < minR[j] ? minL[j] : minR[j] ); } tPtr->box.center = (max+min)/2; tPtr->box.dim=(max-min)/2; tPtr->box.bounds[0] = min; tPtr->box.bounds[1] = max; assert( max[0] >= min[0] ); assert( max[1] >= min[1] ); assert( max[2] >= min[2] ); } } /********************************************************************************************** * ็ฎ—ไธ€ๅˆ—ไธ‰่ง’ๅฝข็š„ x,y,z ๆœ€ๅคงๆœ€ๅฐๅ€ผ * ไธ‰่ง’ๅฝข่ณ‡ๆ–™ๅญ˜ๅœจ facePtrArray, (start,end) = Array ่ตทๅง‹/็ตๆŸ index * ๅ›žๅ‚ณๆ”พๅœจ max, min, center **********************************************************************************************/ void AabbTree::calcTriangleListInfo( Face** facePtrArray, int start, int end, Vector3 &max, Vector3 &min, Vector3 &center ) { //list< Face* >::iterator iter = faceList.begin(); center = Vector3(0, 0, 0); // foreach face, foreach vertex, for x,y,z //max = min = m_meshData->vList[ (*iter)->v[0].v ]; //for( iter = faceList.begin(); iter != faceList.end(); iter++ ){ // for( int j = 1; j < 3; j++ ){ // for( int i = 0; i < 3; i++ ){ // if( max[i] < m_meshData->vList[ (*iter)->v[j].v ][i] ){ // max[i] = m_meshData->vList[ (*iter)->v[j].v ][i]; // }else if( min[i] > m_meshData->vList[ (*iter)->v[j].v ][i] ){ // min[i] = m_meshData->vList[ (*iter)->v[j].v ][i]; // } // } // } // center = center + calcTriangleCenter( *iter ); //} //center = center / m_meshData->fTotal; ?? center / faceList.size() max = min = *facePtrArray[start]->vPtr[0] ; // for each ไธ‰่ง’ๅฝข in array // for each ้ ‚้ปž in ไธ‰่ง’ๅฝข // for x,y,z in ้ ‚้ปž // ๅ’Œ max, min ็š„x,y,z ๅšๆฏ”่ผƒ for(int i = start; i <= end; i++ ){ for( int j = 0; j < 3; j++ ){ for( int k = 0; k < 3; k++ ){ if( max[k] < (*(facePtrArray[i]->vPtr[j])) [k] ){ max[k] = (*(facePtrArray[i]->vPtr[j])) [k]; }else if( min[k] > (*(facePtrArray[i]->vPtr[j])) [k] ){ min[k] = (*(facePtrArray[i]->vPtr[j])) [k]; } } center += (*(facePtrArray[i]->vPtr[j])) ; } } center /= ((end - start + 1) * 3); #ifdef DEBUG Vec3 v = max; printf( "%g %g %g\n", v.x, v.y, v.z ); v = min; printf( "%g %g %g\n", v.x, v.y, v.z ); v = center; printf( "%g %g %g\n", v.x, v.y, v.z ); #endif } // calculate centroid/ geometry center/ barycenter of a triangle Vector3 AabbTree::calcTriangleCenter( Face* facePtr ) { Vector3 center( 0, 0, 0 ); for( int j = 0; j < 3; j++ ){ center = center + *(facePtr->vPtr[j]) ; } center = center / 3; #ifdef DEBUG2 Vec3 &v = center; printf( "%g %g %g\n", v.x, v.y, v.z ); #endif return center; } #if 0 void AabbTree::calculateTriangleSize( Face* facePtr, Vec3& max, Vec3& min ){ // face็š„็ฌฌjๅ€‹้ปž็š„vertex // m_meshData->vList[ face.v[j].v ].ptr max = min = m_meshData->vList[ facePtr->v[0].v ]; for( int j = 1; j < 3; j++ ){ for( int i = 0; i < 3; i++ ){ if( max[i] < m_meshData->vList[ facePtr->v[j].v ][i] ){ max[i] = m_meshData->vList[ facePtr->v[j].v ][i]; }else if( min[i] > m_meshData->vList[ facePtr->v[j].v ][i] ){ min[i] = m_meshData->vList[ facePtr->v[j].v ][i]; } } } } #endif
[ "grahamhuang@73147322-a748-11dd-a8c6-677c70d10fe4" ]
[ [ [ 1, 356 ] ] ]
3147d9d2c606037b87305372f50cd38947b37640
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib-test/af2-test/af2_test_1.cpp
169904a904cbe03f650b4394b09e28d82a39c909
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
#include <windows.h> #include "mwlagh.h" #include "MwlAghFactory.h" class CMyWindow : public agh::IWindow { public: virtual bool OnClose(){ MessageBox(NULL,"sdfa","sfda",0); return true; } virtual bool OnDropFiles(std::vector<std::string> &files){ for(int i=0; i<files.size(); i++) MessageBox(NULL,files[i].c_str(),"Drop",0); return true; } }; int _MWL_APIENTRY WinMain( _MWL_HINSTANCE hInstance, _MWL_HINSTANCE hPrevInstance, char* lpCmdLine, int nCmdShow ) //int main() { //::FreeConsole(); CMwlAghFactory fact; CMyWindow myWindow; //agh::IWindow* pWindow = fact.CreateWindow(new CMyWindow); agh::IWindow* pWindow = fact.CreateWindow(&myWindow); pWindow->EnableDropFiles(); pWindow->Start(); delete pWindow; return 0; }
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 37 ] ] ]
7fd4de318d715a31da904f88a60fa4fbcbfc0464
53b5a4f5750ba78b612f16d2c39aef281332d15d
/etsGame/gameobject.h
b197bad601248d92dabee6268dec2bd2e16a4149
[]
no_license
lseelenbinder/evil-twin-souls
b7cd0155a57e6543925cf308c81bb32e4ef4cdf4
ba83e67be78433b6bb0bc01bcc52a9595949bbba
refs/heads/master
2021-01-23T13:29:26.942953
2011-04-04T15:50:01
2011-04-04T15:50:01
33,510,157
0
0
null
null
null
null
UTF-8
C++
false
false
588
h
#ifndef GAMEOBJECT_H #define GAMEOBJECT_H #include <QLabel> #include <QObject> #include <QTimer> #include <QPixmap> enum gameObjectType {FISH, BUBBLE, SHARK}; class gameObject : public QObject { Q_OBJECT public: gameObject(QObject *parent, int myCount, gameObjectType, QWidget*, int, int, int); int getDirection(); void setDirection(int); void setType(gameObjectType); gameObjectType getType(); QLabel* label; void setSprite(); private: gameObjectType type; int direction; signals: }; #endif // GAMEOBJECT_H
[ "[email protected]@b7444b13-40a3-a05b-aa3e-fda0021e588c", "[email protected]@b7444b13-40a3-a05b-aa3e-fda0021e588c" ]
[ [ [ 1, 3 ], [ 5, 8 ], [ 10, 15 ], [ 17, 18 ], [ 23, 24 ], [ 26, 32 ] ], [ [ 4, 4 ], [ 9, 9 ], [ 16, 16 ], [ 19, 22 ], [ 25, 25 ] ] ]
5102d9ad40e75920bdd41a5dcc599b4c45653db3
6f8721dafe2b841f4eb27237deead56ba6e7a55b
/src/WorldOfAnguis/Units/Player/HUD.h
899be29c2341a94849f4744a7f18f79914d51b6b
[]
no_license
worldofanguis/WoA
dea2abf6db52017a181b12e9c0f9989af61cfa2a
161c7bb4edcee8f941f31b8248a41047d89e264b
refs/heads/master
2021-01-19T10:25:57.360015
2010-02-19T16:05:40
2010-02-19T16:05:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
564
h
/* * ___ ___ __ * \ \ / / / \ * \ \ / / / \ * \ \ /\ / /___ / /\ \ * \ \/ \/ /| | / ____ \ * \___/\___/ |___|/__/ \__\ * World Of Anguis * */ #pragma once #include "Common.h" #include "Singleton.h" #include "Graphics/DirectX/HUD/DXHUDView.h" class HUD : public Singleton<HUD> { public: HUD(); ~HUD(); void Update(DXHUDView::HUD_PART Part,int Data) {sHudView->Update(Part,Data);} private: }; #define sHud HUD::Instance()
[ [ [ 1, 29 ] ] ]
6bcfc5ee3b612bea25bd2b44df328c0a9778edf6
85c91b680d74357b379204ecf7643ae1423f8d1e
/branches/pre_mico_2_3-12/dci/DCI_RepNodeManagerImpl/PropertiesRepository.h
866240f027090dd22a32c6097d27431795eb4f2a
[]
no_license
BackupTheBerlios/qedo-svn
6fdec4ca613d24b99a20b138fb1488f1ae9a80a2
3679ffe8ac7c781483b012dbef70176e28fea174
refs/heads/master
2020-11-26T09:42:37.603285
2010-07-02T10:00:26
2010-07-02T10:00:26
40,806,890
0
0
null
null
null
null
UTF-8
C++
false
false
3,383
h
//************************************************************** // //************************************************************** #ifndef PROPERTIESREPOSITORY #define PROPERTIESREPOSITORY #include <vector> #include <CORBA.h> #ifdef _WIN32 #include "NodeProperties.h" #endif //using namespace std; // Structure of a property : name, value and mode struct propertydef { char* property_name; CORBA::Any property_value; }; typedef struct propertydef PropertyDef; // Vector of properties typedef std::vector<PropertyDef *> PropertyDefs; // Vector of types typedef std::vector<CORBA::TypeCode_var> PropertyTypes; // exception thrown if the PropertyRepository object can't be initialized class PropertiesRepositoryInitializationException {}; class InvalidPropertyName {}; class UnsupportedProperty {}; class ConflictingProperty {}; class UnsupportedTypeCode {}; class PropertiesRepository { private: // Vector of properties PropertyDefs properties_vector; // Vector of allowed properties PropertyDefs allowed_properties_vector; // Returns true if the parameter is not "" bool is_property_name_valid (const char *); // Vector of allowed types PropertyTypes allowed_types_vector; // Returns true if the parameter is in the vector of types bool is_property_type_allowed (CORBA::TypeCode_ptr); void definition (const char *property_name, const CORBA::Any &property_value) throw (InvalidPropertyName, UnsupportedProperty); bool is_property_allowed (const char *name, const CORBA::Any &value); void initialize_properties_(); const char * NameOfProperty_(int i); void retrieve_property_(const char * name); #ifdef _WIN32 NodeProperties* nodeprop_; #endif int prop_counter; //NodeInformation interface stuff // Indexes of the properties. These indexes are used in loops and // for the vector of refresh rates. static const int OSNAME = 0; static const int OSVERSION = 1; static const int OSDIRECTORY = 2; static const int OSVENDOR = 3; static const int PROCNUMBER = 4; static const int PROCTYPE = 5; static const int PROCVENDOR = 6; static const int COMPCLASS = 7; static const int CPULOAD = 8; static const int AVCPULOAD = 9; static const int NUMBERPROC = 10; static const int INSTALLMEM = 11; static const int FREEMEM = 12; static const int AVFREEMEM = 13; static const int COMPUTNAME = 14; static const int IPADDRESS = 15; static const int NETWORKTYP = 16; static const int MAXBANDWID = 17; static const int COMMLOAD = 18; static const int PROTOCOLS = 19; static const int INSTALLORB = 20; static const int NUMBEROFPROPERTIES = 21; static const int TIMEINTERVAL = 5000; public: // Constructor without parameters PropertiesRepository(); // Constructor with initialization PropertiesRepository(const PropertyDefs &); // Destructor ~PropertiesRepository(); // Returns the vector of properties PropertyDefs * get_properties_vector(); // Returns the vector of allowed properties PropertyDefs * get_allowed_properties_vector(); void define_property(const char *prop_name, const CORBA::Any &property_value); bool get_index (const char *property_name, int *ind); char* get_name (int ind); CORBA::Any* get_value (int ind); }; #endif
[ "tom@798282e8-cfd4-0310-a90d-ae7fb11434eb" ]
[ [ [ 1, 124 ] ] ]
febfa1c443b5d147710a4400026b7dd64c5d62e8
bf19f77fdef85e76a7ebdedfa04a207ba7afcada
/NewAlpha/TMNT Tactics Tech Demo/Source/BaseMenuState.h
0a6518e08319de7b3697898282e36de7480b1491
[]
no_license
marvelman610/tmntactis
2aa3176d913a72ed985709843634933b80d7cb4a
a4e290960510e5f23ff7dbc1e805e130ee9bb57d
refs/heads/master
2020-12-24T13:36:54.332385
2010-07-12T08:08:12
2010-07-12T08:08:12
39,046,976
0
0
null
null
null
null
UTF-8
C++
false
false
5,606
h
////////////////////////////////////////////////////////////////////////// // Filename : BaseMenuState.h // // Author : Ramon Johannessen (RJ) // // Purpose : Base Class for all menu states ////////////////////////////////////////////////////////////////////////// #ifndef CBASEMENUSTATE_H #define CBASEMENUSTATE_H #include "IGameState.h" #include "Player.h" #include "FModSDK/inc/fmod.hpp" class CBitmapFont; class CAssets; class CSGD_TextureManager; class CSGD_Direct3D; class CSGD_DirectInput; class CGame; class CSGD_FModManager; class CBaseMenuState : public IGameState { private: int m_nBGImageID; // bg image ID int m_nMenuClick; // sound ID for when the user moves from one menu selection to the next int m_nScreenWidth; // the program's width and height int m_nScreenHeight; int m_nBGX; // where the background x is int m_nBGY; // where the background y is int m_nImageWidth; // bg image width int m_nImageHeight; // bg image height int m_nCursorImageID; // the menu selection cursor image int m_nCurrMenuSelection; // where is the menu cursor at? int m_nMenuCursorX; // screen x for cursor int m_nMenuCusorY; // screen y for cursor int m_nMenuX; // used for menu items, should be the same for all int m_nMenuY; int m_nMenuItemSpacing; // the distance between one menu item and the next CBitmapFont* m_pBitmapFont; // a pointer to the bitmap font singleton CAssets* m_pAssets; CSGD_TextureManager* m_pTM; CSGD_Direct3D* m_pD3D; CSGD_DirectInput* m_pDI; CGame* m_pGame; //CBaseMenuState* m_pCurrentState;// a pointer to the current menu state CBaseMenuState(const CBaseMenuState&); CBaseMenuState& operator= (const CBaseMenuState&); protected: CSGD_FModManager* m_pFMOD; int m_nMouseX; int m_nMouseY; public: CBaseMenuState(); ~CBaseMenuState(); ////////////////////////////////////////////////////////////////////////// // Function : Update // // Purpose : Any update code goes here, pure virtual, virtual, to be overwritten ////////////////////////////////////////////////////////////////////////// virtual void Update(float fElapsedTime); ////////////////////////////////////////////////////////////////////////// // Function : Render // // Purpose : draw everything to the screen, virtual, to be overwritten ////////////////////////////////////////////////////////////////////////// virtual void Render(); ////////////////////////////////////////////////////////////////////////// // Function : Input // // Purpose : Handle any user input for all menu states, mouse or keyboard, virtual, to be overwritten // // Return : true/false, false if we are exiting the game ////////////////////////////////////////////////////////////////////////// virtual bool Input(float elapsedTime, POINT mousePt); ////////////////////////////////////////////////////////////////////////// // Function : Enter // // Purpose : When the state is first entered, execute this code, virtual, to be overwritten ////////////////////////////////////////////////////////////////////////// virtual void Enter(); ////////////////////////////////////////////////////////////////////////// // Function : Exit // // Purpose : When the state exits, execute this code, virtual, to be overwritten ////////////////////////////////////////////////////////////////////////// virtual void Exit(); ////////////////////////////////////////////////////////////////////////// // Function : CenterBGImage // // Purpose : Automatically centers the background image ////////////////////////////////////////////////////////////////////////// void CenterBGImage(); ////////////////////////////////////////////////////////////////////////// // Accessors ////////////////////////////////////////////////////////////////////////// CAssets* GetAssets() {return m_pAssets;} CSGD_DirectInput* GetDI() {return m_pDI;} CSGD_TextureManager* GetTM() {return m_pTM;} CSGD_Direct3D* GetD3D() {return m_pD3D;} CBitmapFont* GetBitmapFont() {return m_pBitmapFont;} CGame* GetGame() {return m_pGame;} CSGD_FModManager* GetFMOD() {return m_pFMOD;} int GetCurrMenuSelection() {return m_nCurrMenuSelection;} int GetMenuItemSpacing() {return m_nMenuItemSpacing;} int GetCursorX() {return m_nMenuCursorX;} int GetCursorY() {return m_nMenuCusorY;} int GetScreenWidth() {return m_nScreenWidth;} int GetScreenHeight() {return m_nScreenHeight;} int GetBGImageID() {return m_nBGImageID; } int GetMenuX() const {return m_nMenuX; } int GetMenuY() const {return m_nMenuY; } int GetBGImageHeight() {return m_nImageHeight; } int GetBGImageWidth() {return m_nImageWidth; } int GetBGx() {return m_nBGX;} int GetBGy() {return m_nBGY;} ////////////////////////////////////////////////////////////////////////// // Mutators ////////////////////////////////////////////////////////////////////////// void SetCursorX(int x) {m_nMenuCursorX = x;} void SetCursorY(int y) {m_nMenuCusorY = y;} void SetCurrMenuSelection(int selection) {m_nCurrMenuSelection = selection;} void SetBGImageID(int bgImageID) {m_nBGImageID = bgImageID;} void SetBGWidth(int width) {m_nImageWidth = width;} void SetBGHeight(int height) {m_nImageHeight = height;} void SetCursorImageID(int cursorID) {m_nCursorImageID = cursorID;} void SetMenuX(int val) {m_nMenuX = val; } void SetMenuY(int val) {m_nMenuY = val; } }; #endif
[ "AllThingsCandid@7dc79cba-3e6d-11de-b8bc-ddcf2599578a", "jsierra099@7dc79cba-3e6d-11de-b8bc-ddcf2599578a" ]
[ [ [ 1, 117 ], [ 119, 120 ], [ 123, 140 ] ], [ [ 118, 118 ], [ 121, 122 ] ] ]
069703afbb8d4e21e665f460204c2dd8209762fa
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/compatanalysercmd/bcfilter/inc/xmlsaxparser.hpp
0ce0a2813ed396ba5a1a4005073beaa06299975d
[]
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
3,702
hpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // XML Parsing includes #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/parsers/SAXParser.hpp> #include <iostream> #include <string> #if !defined XMLSAXPARSER #define XMLSAXPARSER #include "XMLParserInterface.h" class XMLNode; // T - Document Handler // U - ErrorHandler template<typename T, typename U> class XMLSAXParser : public XMLParserInterface { public: XMLSAXParser(); virtual ~XMLSAXParser(); virtual bool parse(); virtual bool parse(const std::string&); T& getDocumentHandler() { return docHandler; } XMLNode& getRootElement() { return docHandler.getRootElement(); } virtual void doValidation(bool v = true) { validate = v; } virtual void doSchema(bool s = true) { schema = s; } virtual void fullSchemaChecking(bool s = true) { schemaChecking = s; } virtual void namespaces(bool n = true) { names = n; } private: SAXParser* parser; std::string xmlFile; T docHandler; U errorHandler; bool validate; bool schema; bool schemaChecking; bool names; bool getValidation() { return validate; } bool getSchema() { return schema; } bool getSchemaChecking() { return schemaChecking; } bool getNamespaces() { return names; } void init(); void deinit(); }; template<typename T, typename U> XMLSAXParser<T, U>::XMLSAXParser() { parser = NULL; this->init(); } template<typename T, typename U> XMLSAXParser<T, U>::~XMLSAXParser() { this->deinit(); ;; } template<typename T, typename U> void XMLSAXParser<T, U>::init() { this->doValidation(); this->doSchema(); this->fullSchemaChecking(); this->namespaces(); try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { cerr << "Error during initialization! Message:\n" << XMLString::transcode(toCatch.getMessage()) << endl; } } template<typename T, typename U> void XMLSAXParser<T, U>::deinit() { // Delete the parser if(parser) delete parser; // And call the termination method XMLPlatformUtils::Terminate(); } template<typename T, typename U> bool XMLSAXParser<T, U>::parse() { return this->parse(xmlFile); } template<typename T, typename U> bool XMLSAXParser<T, U>::parse(const std::string& file) { xmlFile = file; bool errorOccurred = false; // Create a SAX parser object. Then, according to what we were told on // the command line, set it to validate or not. parser = new SAXParser; if(!parser) return false; parser->setDoValidation(this->getValidation()); parser->setDoNamespaces(this->getNamespaces()); parser->setDoSchema(this->getSchema()); parser->setValidationSchemaFullChecking(this->getSchemaChecking()); parser->setDocumentHandler(&docHandler); parser->setErrorHandler(&errorHandler); try { parser->parse(file.c_str()); } catch (const XMLException& e) { cerr << "\nError during parsing: '" << file << "'\n" << "Exception message is: \n" << XMLString::transcode(e.getMessage()) << "\n" << endl; errorOccurred = true; } catch (...) { cerr << "\nUnexpected exception during parsing: '" << file << "'\n"; errorOccurred = true; } return (!errorOccurred); } #endif // XMLSAXPARSER
[ "none@none" ]
[ [ [ 1, 162 ] ] ]
ee322e17d23b4ac0b5063092fb436a0131a084fb
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nscene/src/nscene/nanimator_cmds.cc
2b1746d5fe28502a60158b8bc4040c89cd1b2091
[]
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
4,592
cc
#include "precompiled/pchnscene.h" //------------------------------------------------------------------------------ // nanimator_cmds.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "nscene/nanimator.h" #include "kernel/npersistserver.h" static void n_resetkeys(void* slf, nCmd* cmd); static void n_setchannel(void* slf, nCmd* cmd); static void n_getchannel(void* slf, nCmd* cmd); static void n_setlooptype(void* slf, nCmd* cmd); static void n_getlooptype(void* slf, nCmd* cmd); static void n_setfixedtimeoffset(void* slf, nCmd* cmd); static void n_getfixedtimeoffset(void* slf, nCmd* cmd); //------------------------------------------------------------------------------ /** @scriptclass nanimator @cppclass nAnimator @superclass nscenenode @classinfo Base class for all scene node animators. */ void n_initcmds_nAnimator(nClass* cl) { cl->BeginCmds(); cl->AddCmd("v_resetkeys_v", 'RKEY', n_resetkeys); cl->AddCmd("v_setchannel_s", 'SCHN', n_setchannel); cl->AddCmd("s_getchannel_v", 'GCHN', n_getchannel); cl->AddCmd("v_setlooptype_s", 'SLPT', n_setlooptype); cl->AddCmd("s_getlooptype_v", 'GLPT', n_getlooptype); cl->AddCmd("v_setfixedtimeoffset_f", 'SFTO', n_setfixedtimeoffset); cl->AddCmd("f_getfixedtimeoffset_v", 'GFTO', n_getfixedtimeoffset); cl->EndCmds(); } //------------------------------------------------------------------------------ /** @cmd setchannel @input s(ChannelName) @output v @info Set name of animation channel which drives this animation (e.g. "time"). */ static void n_setchannel(void* slf, nCmd* cmd) { nAnimator* self = (nAnimator*) slf; self->SetChannel(cmd->In()->GetS()); } //------------------------------------------------------------------------------ /** @cmd getchannel @input v @output s(ChannelName) @info Get name of animation channel which drives this animation. */ static void n_getchannel(void* slf, nCmd* cmd) { nAnimator* self = (nAnimator*) slf; cmd->Out()->SetS(self->GetChannel()); } //------------------------------------------------------------------------------ /** @cmd setlooptype @input s(LoopType = "loop", "clamp") @output v @info Set the loop type for this animation. Default is "loop". */ static void n_setlooptype(void* slf, nCmd* cmd) { nAnimator* self = (nAnimator*) slf; self->SetLoopType(nAnimLoopType::FromString(cmd->In()->GetS())); } //------------------------------------------------------------------------------ /** @cmd getlooptype @input v @output s(LoopType = "loop", "clamp") @info Get the loop type for this animation. */ static void n_getlooptype(void* slf, nCmd* cmd) { nAnimator* self = (nAnimator*) slf; cmd->Out()->SetS(nAnimLoopType::ToString(self->GetLoopType()).Get()); } //------------------------------------------------------------------------------ /** */ static void n_setfixedtimeoffset(void* slf, nCmd* cmd) { nAnimator* self = (nAnimator*) slf; self->SetFixedTimeOffset(cmd->In()->GetF()); } //------------------------------------------------------------------------------ /** */ static void n_getfixedtimeoffset(void* slf, nCmd* cmd) { nAnimator* self = (nAnimator*) slf; cmd->Out()->SetF(self->GetFixedTimeOffset()); } //------------------------------------------------------------------------------ /** */ static void n_resetkeys(void* slf, nCmd* /*cmd*/) { nAnimator* self = (nAnimator*) slf; self->ResetKeys(); } //------------------------------------------------------------------------------ /** */ bool nAnimator::SaveCmds(nPersistServer* ps) { if (nSceneNode::SaveCmds(ps)) { nCmd* cmd; //--- setchannel --- if (this->GetChannel()) { cmd = ps->GetCmd(this, 'SCHN'); cmd->In()->SetS(this->GetChannel()); ps->PutCmd(cmd); } //--- setlooptype --- cmd = ps->GetCmd(this, 'SLPT'); cmd->In()->SetS(nAnimLoopType::ToString(this->GetLoopType()).Get()); ps->PutCmd(cmd); //--- resetkeys --- cmd = ps->GetCmd(this, 'RKEY'); ps->PutCmd(cmd); return true; } return false; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 183 ] ] ]
9ac34e41465d5b305b4a17874201b96af9998b53
3a577d02f876776b22e2bf1c0db12a083f49086d
/vba2/gba2/gba/Sound.h
2a4ba80a7b24cc63d578c96bb2a99fa55965efe5
[]
no_license
xiaoluoyuan/VisualBoyAdvance-2
d19565617b26e1771f437842dba5f0131d774e73
cadd2193ba48e1846b45f87ff7c36246cd61b6ee
refs/heads/master
2021-01-10T01:19:23.884491
2010-05-12T09:59:37
2010-05-12T09:59:37
46,539,728
0
0
null
null
null
null
UTF-8
C++
false
false
3,060
h
/* VisualBoyAdvance 2 Copyright (C) 2009-2010 VBA development team This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SOUND_H #define SOUND_H // Sound emulation setup/options and GBA sound emulation #include "../System.h" #include <stdio.h> class CDriver_Sound; //// Setup/options (these affect GBA and GB sound) extern CDriver_Sound *soundDriver; // Initializes sound and returns true if successful. Sets sound quality to // current value in soundQuality global. bool soundInit(); // sets the Sound throttle void soundSetThrottle(unsigned short throttle); // Manages sound volume, where 1.0 is normal void soundSetVolume( float ); float soundGetVolume(); // Manages muting bitmask. The bits control the following channels: // 0x001 Pulse 1 // 0x002 Pulse 2 // 0x004 Wave // 0x008 Noise // 0x100 PCM 1 // 0x200 PCM 2 void soundSetEnable( int mask ); int soundGetEnable(); // Pauses/resumes system sound output void soundPause(); void soundResume(); extern bool soundPaused; // current paused state // Cleans up sound. Afterwards, soundInit() can be called again. void soundShutdown(); //// GBA sound options long soundGetSampleRate(); void soundSetSampleRate(long sampleRate); // Sound settings extern bool soundInterpolation; // 1 if PCM should have low-pass filtering extern float soundFiltering; // 0.0 = none, 1.0 = max //// GBA sound emulation // GBA sound registers #define SGCNT0_H 0x82 #define FIFOA_L 0xa0 #define FIFOA_H 0xa2 #define FIFOB_L 0xa4 #define FIFOB_H 0xa6 // Resets emulated sound hardware void soundReset(); // Emulates write to sound hardware void soundEvent( u32 addr, u8 data ); void soundEvent( u32 addr, u16 data ); // TODO: error-prone to overload like this // Notifies emulator that a timer has overflowed void soundTimerOverflow( int which ); // Notifies emulator that PCM rate may have changed void interp_rate(); // Notifies emulator that SOUND_CLOCK_TICKS clocks have passed void psoundTickfn(); extern int SOUND_CLOCK_TICKS; // Number of 16.8 MHz clocks between calls to soundTick() extern int soundTicks; // Number of 16.8 MHz clocks until soundTick() will be called // Saves/loads emulator state void soundSaveGame( FILE *out ); void soundReadGame( FILE *in, int version ); class Multi_Buffer; void flush_samples(Multi_Buffer * buffer); #endif // SOUND_H
[ "spacy51@5a53c671-dd2d-0410-9261-3f5c817b7aa0" ]
[ [ [ 1, 106 ] ] ]
07bd63c7d42435bf151c54fbe124a6ab185d1fe0
36d0ddb69764f39c440089ecebd10d7df14f75f3
/ใƒ—ใƒญใ‚ฐใƒฉใƒ /Ngllib/include/Ngl/Rect.h
64c514c1a857cf4826e3bad1cf0b99ffecb6ff2c
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,050
h
/*******************************************************************************/ /** * @file Rect.h. * * @brief ็Ÿฉๅฝขๆง‹้€ ไฝ“ใƒ˜ใƒƒใƒ€ใƒ•ใ‚กใ‚คใƒซ. * * @date 2008/07/05. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #ifndef _NGL_RECT_H_ #define _NGL_RECT_H_ #ifdef __cplusplus namespace Ngl{ #endif /** * @struct Rect * @brief ็Ÿฉๅฝขๆง‹้€ ไฝ“๏ผŽ */ typedef struct Rect { /** ๅทฆๅบงๆจ™ */ float left; /** ไธŠๅบงๆจ™ */ float top; /** ๅณๅบงๆจ™ */ float right; /** ไธ‹ๅบงๆจ™ */ float bottom; #ifdef __cplusplus /*=========================================================================*/ /** * @brief ใ‚ณใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ฟ * * @param[in] ใชใ—. */ Rect(); /*=========================================================================*/ /** * @brief ใ‚ณใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ฟ * * @param[in] L ๅทฆ็ซฏไฝ็ฝฎ. * @param[in] T ไธŠ็ซฏไฝ็ฝฎ. * @param[in] R ๅณ็ซฏไฝ็ฝฎ. * @param[in] B ไธ‹็ซฏไฝ็ฝฎ. */ Rect( float L, float T, float R, float B ); /*=========================================================================*/ /** * @brief ๅˆๆœŸๅŒ–ใ™ใ‚‹ * * @param[in] L ๅทฆ็ซฏไฝ็ฝฎ. * @param[in] T ไธŠ็ซฏไฝ็ฝฎ. * @param[in] R ๅณ็ซฏไฝ็ฝฎ. * @param[in] B ไธ‹็ซฏไฝ็ฝฎ. * @return ใชใ—. */ void initialize( float L, float T, float R, float B ); /*=========================================================================*/ /** * @brief ไฝ็ฝฎๅบงๆจ™, ๅน…ใจ้ซ˜ใ•ใ‹ใ‚‰็Ÿฉๅฝขใ‚’ๆฑ‚ใ‚ใ‚‹ * * @param[in] L ๅทฆไธŠไฝ็ฝฎxๅบงๆจ™. * @param[in] T ๅทฆไธŠไฝ็ฝฎyๅบงๆจ™. * @param[in] Width ๅณ็ซฏไฝ็ฝฎ. * @param[in] Height ไธ‹็ซฏไฝ็ฝฎ. * @return ใชใ—. */ void fromSize( float L, float T, float Width, float Height ); #endif } NGLrect; #ifdef __cplusplus /** ้›ถ็Ÿฉๅฝข */ static const Rect RECT_ZERO = Rect( 0.0f, 0.0f, 0.0f, 0.0f ); /** ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆใฎใƒ†ใ‚ฏใ‚นใƒใƒฃๅบงๆจ™ */ static const Rect RECT_TEXCOORD = Rect( 0.0f, 0.0f, 1.0f, 1.0f ); } // namespace Ngl /*=========================================================================*/ /** * @brief == ๆผ”็ฎ—ๅญใ‚ชใƒผใƒใƒผใƒญใƒผใƒ‰ * * ๅŒใ˜ๅ€คใฎ็Ÿฉๅฝขใ‹ๆฏ”่ผƒใ™ใ‚‹ใ€‚ * * @param[in] r1 ๆฏ”่ผƒใ™ใ‚‹็Ÿฉๅฝข1. * @param[in] r2 ๆฏ”่ผƒใ™ใ‚‹็Ÿฉๅฝข2. * @retval true ๅŒใ˜ๅ€ค. * @retval false ้•ใ†ๅ€ค. */ bool operator == ( const Ngl::Rect& r1, const Ngl::Rect& r2 ); /*=========================================================================*/ /** * @brief != ๆผ”็ฎ—ๅญใ‚ชใƒผใƒใƒผใƒญใƒผใƒ‰ * * ้•ใ†ๅ€คใฎ็Ÿฉๅฝขใ‹ๆฏ”่ผƒใ™ใ‚‹ใ€‚ * * @param[in] r1 ๆฏ”่ผƒใ™ใ‚‹็Ÿฉๅฝข1. * @param[in] r2 ๆฏ”่ผƒใ™ใ‚‹็Ÿฉๅฝข2. * @retval true ้•ใ†ๅ€ค. * @retval false ๅŒใ˜ๅ€ค. */ bool operator != ( const Ngl::Rect& r1, const Ngl::Rect& r2 ); #endif #endif /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 144 ] ] ]
3722cfa209d307c9e486a4439d6d232e2fdbe6ed
444a151706abb7bbc8abeb1f2194a768ed03f171
/trunk/ENIGMAsystem/SHELL/auxilary.h
301800196baa99b6a70e4032d25c2c746794fa7b
[]
no_license
amorri40/Enigma-Game-Maker
9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6
c6b701201b6037f2eb57c6938c184a5d4ba917cf
refs/heads/master
2021-01-15T11:48:39.834788
2011-11-22T04:09:28
2011-11-22T04:09:28
1,855,342
1
1
null
null
null
null
UTF-8
C++
false
false
1,711
h
/** Copyright (C) 2008 Josh Ventura ** This file is a part of the ENIGMA Development Environment. ** It is released under the GNU General Public License, version 3. ** See the license of local files for more details. **/ #define const __const #define inline __inline #define signed __signed #define volatile __volatile template<typename _Category, typename _Tp, typename _Distance = ptrdiff_t, typename _Pointer = _Tp*, typename _Reference = _Tp&> struct iterator { /// One of the @link iterator_tags tag types@endlink. typedef _Category iterator_category; /// The type "pointed to" by the iterator. typedef _Tp value_type; /// Distance between iterators is represented as this type. }; template<typename _Iterator> struct iterator_traits { typedef typename _Iterator::iterator_category iterator_category; typedef typename _Iterator::value_type value_type; typedef typename _Iterator::difference_type difference_type; typedef typename _Iterator::pointer pointer; typedef typename _Iterator::reference reference; }; template<typename _Tp> struct iterator_traits<_Tp*> { typedef _Tp value_type; typedef _Tp* pointer; typedef _Tp& reference; }; template<typename _Tp> struct iterator_traits<const _Tp*> { typedef _Tp value_type; typedef ptrdiff_t difference_type; typedef const _Tp* pointer; typedef const _Tp& reference; }; #error Ass caekz
[ [ [ 1, 49 ] ] ]
5712537f83715364bdb06411be6daf3066d99f05
d609fb08e21c8583e5ad1453df04a70573fdd531
/trunk/OpenXP/ๆ•ฐๆฎๅบ“็ป„ไปถ/stdafx.cpp
81c1672db6e5a98159bd3bb93f788d288f917f49
[]
no_license
svn2github/openxp
d68b991301eaddb7582b8a5efd30bc40e87f2ac3
56db08136bcf6be6c4f199f4ac2a0850cd9c7327
refs/heads/master
2021-01-19T10:29:42.455818
2011-09-17T10:27:15
2011-09-17T10:27:15
21,675,919
0
1
null
null
null
null
GB18030
C++
false
false
175
cpp
// stdafx.cpp : ๅชๅŒ…ๆ‹ฌๆ ‡ๅ‡†ๅŒ…ๅซๆ–‡ไปถ็š„ๆบๆ–‡ไปถ // DataBaseModule.pch ๅฐ†ไฝœไธบ้ข„็ผ–่ฏ‘ๅคด // stdafx.obj ๅฐ†ๅŒ…ๅซ้ข„็ผ–่ฏ‘็ฑปๅž‹ไฟกๆฏ #include "stdafx.h"
[ "[email protected]@f92b348d-55a1-4afa-8193-148a6675784b" ]
[ [ [ 1, 7 ] ] ]
53f23b65c3c87d365fb895214b218020291b3334
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Common/Procedural/kppPlane.h
d457992aa60112aed6a79d220eddc8c2292198bf
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
579
h
#pragma once #include "Common\Procedural\kppGeometry.h" #include "Common\Utility\kpuVector.h" class kppPlane : public kppGeometry { public: kppPlane(void); kppPlane(float fWidth, float fHeight, const kpuVector& vNormal); virtual ~kppPlane(void); void SetNormal(const kpuVector& vNormal) { m_vNormal = vNormal; m_vNormal.Normalize(); } void SetWidth(float fWidth) { m_fWidth = fWidth; } void SetHeight(float fHeight) { m_fHeight = fHeight; } virtual void Build(); protected: kpuVector m_vNormal; float m_fWidth; float m_fHeight; };
[ "acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 22 ] ] ]
ee9b1efdf83eee6d8ada85080141692fd4e369e4
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Common/Network/kpnServer.h
86cb7d5ebacdf57e3a7e83f1d711f1e2c356feda
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
877
h
#pragma once #include "kpnBaseSocket.h" class kpnPacket; #define LOGIN_SERVER_PORT 8873 #define WORLD_SERVER_PORT 8874 #define DATABASE_SERVER_PORT 8875 // The kpnServer class is the base communication class for communicating with other servers in the cluster. class kpnServer : public kpnBaseSocket { public: enum eServerState { eSS_None = 0, eSS_Connecting, eSS_Connected, eSS_Ready, eSS_Closed, eSS_Last }; kpnServer(); virtual ~kpnServer(); void CreateConnectionFromAddress(u32 unAddress, int nPort); bool Connect(u32 unServerAddress, int nPort); void Send(kpnPacket* pPacket); eServerState GetState() const { return m_eState; } void SetState(eServerState s) { m_eState = s; } static kpnServer* FindWorldServer(); static kpnServer* FindDatabaseServer(); protected: eServerState m_eState; };
[ "acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 41 ] ] ]
0741c8ffddca8dc5e03b26458ee5786c010cbb5e
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/Graphics/WS/Scroll/Scroll.h
6ed06d5c7f5b50bd18548f42e5c7c572629d029b
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
2,056
h
// WSSCROL1.H // // Copyright (c) 2005 Symbian Softwares Ltd. All rights reserved. // #if !defined(__WSSCROL1_H__) #define __WSSCROL1_H__ #include "Base.h" ////////////////////////////////////////////////////////////////////////// // Derived window classes ////////////////////////////////////////////////////////////////////////// // CNumberedWindow displays a number in its center and supports drag and drop class CNumberedWindow : public CWindow { public: enum EScrollDir { Up, Down }; CNumberedWindow(CWsClient* aClient, TInt aNum); ~CNumberedWindow(); void Draw(const TRect& aRect); void HandlePointerEvent(TPointerEvent& aPointerEvent); void HandlePointerMoveBufferReady() { } protected: // window height to calculate vertical text offset TInt WinHeight(); TInt WinWidth(); TInt BaselineOffset(); TRect TextBox(); private: static TInt iCount; TInt iNumber; // Number displayed in window TPoint iOldPos; // Position is required for drag and drop TPoint iOffsetPoint; // Used for scrolling TRect iRepeatRect; // Boundary for pointer repeat events EScrollDir iScrollDir; // Scroll direction for pointer repeat events }; // CMainWindow is a plain window that just acts as a container for the // other windows class CMainWindow : public CWindow { public: CMainWindow(CWsClient* aClient); ~CMainWindow(); void Draw(const TRect& aRect); void HandlePointerEvent(TPointerEvent& aPointerEvent); }; ////////////////////////////////////////////////////////////////////////// // Derived client class ////////////////////////////////////////////////////////////////////////// class CExampleWsClient : public CWsClient { public: static CExampleWsClient* NewL(const TRect& aRect); private: CExampleWsClient(const TRect& aRect); void ConstructMainWindowL(); ~CExampleWsClient(); void RunL(); void HandleKeyEventL(TKeyEvent& aKeyEvent); private: CMainWindow* iMainWin; CNumberedWindow* iNumWin; const TRect& iRect; }; #endif
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 77 ] ] ]
490d4d25de306827699afe4748b1ee3cbf6b858e
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Network/Mcl/Include/CMclGlobal.h
634ef6314575697a38b8fb35a414068fda51a176
[]
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
UTF-8
C++
false
false
3,006
h
// // FILE: CMclGlobal.h // // Copyright (c) 1997 by Aaron Michael Cohen and Mike Woodring // ///////////////////////////////////////////////////////////////////////// #ifndef __CMCLGLOBAL_H__ #define __CMCLGLOBAL_H__ #include <windows.h> #include <process.h> #include <winerror.h> // forward class declarations to make the compiler happy... class CMclWaitableObject; class CMclWaitableCollection; class CMclKernel; class CMclMutex; class CMclSemaphore; class CMclEvent; class CMclThread; class CMclCritSec; class CMclAutoLock; class CMclMonitor; class CMclSharedMemory; class CMclMailbox; // defined symbol determines if CMclThrowError throws exceptions // or just prints debug error messages... #ifndef __CMCL_THROW_EXCEPTIONS__ #define __CMCL_THROW_EXCEPTIONS__ TRUE #endif // for higher level objects which might have to check internal // object status when exceptions are disabled, these macros can be useful... // PTR is the smart pointer to check for NULL, // STATUS is the variable in which to store an error code if an error is detected... #if __CMCL_THROW_EXCEPTIONS__ #define CMCL_CHECK_AUTOPTR_OBJECT(PTR,STATUS) if ((PTR).IsNull()) { CMclThrowError(ERROR_OUTOFMEMORY); } #else #define CMCL_CHECK_AUTOPTR_OBJECT(PTR,STATUS) if ((PTR).IsNull()) { (STATUS) = ERROR_OUTOFMEMORY; return; } #endif // SCODE is the return value to check, // STATUS is the variable in which to store an error code if an error is detected... #if __CMCL_THROW_EXCEPTIONS__ #define CMCL_CHECK_CREATION_STATUS(SCODE,STATUS) {} #else #define CMCL_CHECK_CREATION_STATUS(SCODE,STATUS) if (((SCODE)!=NO_ERROR)&&((SCODE)!=ERROR_ALREADY_EXISTS)) { STATUS = (SCODE); return; } #endif // error handling macro and function... #define CMclThrowError(dwStatus) CMclInternalThrowError((dwStatus), __FILE__, __LINE__) extern void CMclInternalThrowError( DWORD dwStatus, LPCTSTR lpFilename, int line); // check handle for NULL and INVALID_HANDLE inline BOOL CMclIsValidHandle( HANDLE hHandle) { return ((hHandle != NULL) && (hHandle != INVALID_HANDLE_VALUE)); } // validate wait return codes... inline BOOL CMclWaitSucceeded( DWORD dwWaitResult, DWORD dwHandleCount) { return ((dwWaitResult >= WAIT_OBJECT_0) && (dwWaitResult < WAIT_OBJECT_0 + dwHandleCount)); } inline BOOL CMclWaitAbandoned( DWORD dwWaitResult, DWORD dwHandleCount) { return ((dwWaitResult >= WAIT_ABANDONED_0) && (dwWaitResult < WAIT_ABANDONED_0 + dwHandleCount)); } inline BOOL CMclWaitTimeout( DWORD dwWaitResult) { return (dwWaitResult == WAIT_TIMEOUT); } inline BOOL CMclWaitFailed( DWORD dwWaitResult) { return (dwWaitResult == WAIT_FAILED); } // compute object indices for waits... inline DWORD CMclWaitSucceededIndex( DWORD dwWaitResult) { return (dwWaitResult - WAIT_OBJECT_0); } inline DWORD CMclWaitAbandonedIndex( DWORD dwWaitResult) { return (dwWaitResult - WAIT_ABANDONED_0); } #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 92 ] ] ]
3b2afe6e47d0bf7330005cc85e1d59153181aa32
e5ded38277ec6db30ef7721a9f6f5757924e130e
/Cpp/SoSe10/Blatt09.Aufgabe01/RoadVehicle.h
d579c9bedf0d10059236a42b4131496aa854548d
[]
no_license
TetsuoCologne/sose10
67986c8a014c4bdef19dc52e0e71e91602600aa0
67505537b0eec497d474bd2d28621e36e8858307
refs/heads/master
2020-05-27T04:36:02.620546
2010-06-22T20:47:08
2010-06-22T20:47:08
32,480,813
0
0
null
null
null
null
UTF-8
C++
false
false
225
h
#ifndef VEHICLE #define VEHICLE #include "Vehicle.h" #endif class RoadVehicle : public Vehicle{ public: RoadVehicle(int=0, double=0, int=0) ; int getWheels(); virtual std::string id(); protected: int wheels; };
[ "[email protected]@f2f8bf26-27bb-74d3-be08-1e18597623ec" ]
[ [ [ 1, 12 ] ] ]
0cfe3b81854406cf60fce35c44fb714e7a2046e4
f95341dd85222aa39eaa225262234353f38f6f97
/DesktopX/Plugins/DXCanvas/Sources/Canvas.h
7ac9d61bc98a4642431a52e1913fc509c5425171
[]
no_license
Templier/threeoaks
367b1a0a45596b8fe3607be747b0d0e475fa1df2
5091c0f54bd0a1b160ddca65a5e88286981c8794
refs/heads/master
2020-06-03T11:08:23.458450
2011-10-31T04:33:20
2011-10-31T04:33:20
32,111,618
0
0
null
null
null
null
UTF-8
C++
false
false
5,784
h
/////////////////////////////////////////////////////////////////////////////////////////////// // // Canvas Plugin for DesktopX // // Copyright (c) 2008-2010, Julien Templier // All rights reserved. // /////////////////////////////////////////////////////////////////////////////////////////////// // * $LastChangedRevision$ // * $LastChangedDate$ // * $LastChangedBy$ /////////////////////////////////////////////////////////////////////////////////////////////// // // 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 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. // /////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "stdafx.h" #include "DXCanvas.h" #include "resource.h" #include <comsvcs.h> #include <cairo.h> #include <cairo-win32.h> #include "CanvasRenderingContext2D.h" #include "CanvasState.h" #include <gdiplus.h> using namespace Gdiplus; #include <process.h> #define _DEBUG_LOG #include <LogFile.h> #define DEFAULT_WIDTH 300 #define DEFAULT_HEIGHT 150 // CCanvas class ATL_NO_VTABLE CCanvas : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CCanvas, &CLSID_Canvas>, public IDispatchImpl<ICanvas, &IID_ICanvas, &LIBID_DXCanvasLib, /*wMajor =*/ 1, /*wMinor =*/ 0>, public ISupportErrorInfo { friend class CCanvasRenderingContext2D; friend class CanvasState; public: CCanvas() : surface(NULL), context(NULL), debugMode(FALSE), shouldDraw(FALSE), logFile(NULL), repeat(TRUE), hDrawMutex(NULL), isDrawingSuspended(FALSE) { } DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL); hThread = NULL; config = new CONFIG_CANVAS; state = new CanvasState(this); return S_OK; } void FinalRelease() { killthreadQueueDraw(); SAFE_DELETE(state); SAFE_DELETE(config); SAFE_DELETE(logFile); #ifdef USE_DRAWING_MUTEX if (hDrawMutex != NULL) CloseHandle(hDrawMutex); #endif GdiplusShutdown(m_gdiplusToken); } DECLARE_REGISTRY_RESOURCEID(IDR_CANVAS) DECLARE_NOT_AGGREGATABLE(CCanvas) BEGIN_COM_MAP(CCanvas) COM_INTERFACE_ENTRY(ICanvas) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY(IDispatch) END_COM_MAP() private: ULONG_PTR m_gdiplusToken; GdiplusStartupInput gdiplusStartupInput; cairo_surface_t *surface; cairo_t *context; CanvasState* state; BOOL debugMode; BOOL isDrawingSuspended; CLogFile *logFile; HANDLE hDrawMutex; // Draw thread HANDLE hThread; unsigned tid; // Thread id static unsigned threadQueueDrawStatic(void* param); unsigned threadQueueDraw(); BOOL repeat; BOOL shouldDraw; DWORD objID; // the object id used to send messages public: struct CONFIG_CANVAS { int width; int height; bool alphablend; // used only by DX char objectDirectory[MAX_PATH]; char objectName[100]; CONFIG_CANVAS() { width = DEFAULT_WIDTH; height = DEFAULT_HEIGHT; alphablend = true; strcpy_s(objectDirectory, ""); strcpy_s(objectName, ""); } }; CONFIG_CANVAS* config; void initCairo(); void destroyCairo(); void clearContext(); void draw(HDC hdc, HBITMAP hBitmap); void queueDraw(); void killthreadQueueDraw(); void resize(); void setObjID(DWORD id); cairo_surface_t* getSurface(); int getWidth(); int getHeight(); ////////////////////////////////////////////////////////////////////////// // ISupportErrorInfo ////////////////////////////////////////////////////////////////////////// STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); ////////////////////////////////////////////////////////////////////////// // ICanvas ////////////////////////////////////////////////////////////////////////// STDMETHOD(put_width)(long width); STDMETHOD(get_width)(long *width); STDMETHOD(put_height)(long height); STDMETHOD(get_height)(long *height); STDMETHOD(put_debugMode)(VARIANT_BOOL isDebugMode); STDMETHOD(get_debugMode)(VARIANT_BOOL* isDebugMode); STDMETHOD(suspendDrawing)(); STDMETHOD(resumeDrawing)(); STDMETHOD(getContext)(BSTR type, ICanvasRenderingContext2D** context); STDMETHOD(toImage)(BSTR path, VARIANT_BOOL* result); }; OBJECT_ENTRY_AUTO(__uuidof(Canvas), CCanvas)
[ "julien.templier@ab80709b-eb45-0410-bb3a-633ce738720d" ]
[ [ [ 1, 205 ] ] ]
138dea18e595d0bd3ae08eac920979ee61fed0ec
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/odephysics/nodeamotorjointnode_main.cc
883ce3073c674b4e4cecc4741785354c10bb6163
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,318
cc
#define N_IMPLEMENTS nOdeAMotorJointNode //------------------------------------------------------------------------------ // (c) 2003 Vadim Macagon // // nOdeAMotorJointNode is licensed under the terms of the Nebula License. //------------------------------------------------------------------------------ #include "odephysics/nodeamotorjointnode.h" nNebulaScriptClass(nOdeAMotorJointNode, "nodejointnode") #include "odephysics/nodephysicscontext.h" #include "odephysics/nodejoint.h" //------------------------------------------------------------------------------ /** */ nOdeAMotorJointNode::nOdeAMotorJointNode() { // empty } //------------------------------------------------------------------------------ /** */ nOdeAMotorJointNode::~nOdeAMotorJointNode() { // empty } //------------------------------------------------------------------------------ /** @brief Create the underlying nOdeAMotorJoint instance. This obviously must be called before trying to do anything else with the joint. */ void nOdeAMotorJointNode::InitJoint( const char* physContext ) { n_assert( !this->joint ); this->ref_PhysContext = physContext; n_assert( this->ref_PhysContext.isvalid() ); this->joint = this->ref_PhysContext->NewAMotorJoint(); } //------------------------------------------------------------------------------ /** */ void nOdeAMotorJointNode::SetMode( const char* mode ) { nOdeAMotorJoint* j = (nOdeAMotorJoint*)this->GetJoint(); if ( strcmp( mode, "user" ) == 0 ) j->SetMode( dAMotorUser ); else if ( strcmp( mode, "euler" ) == 0 ) j->SetMode( dAMotorEuler ); else n_warn( "nOdeAMotorJointNode::SetMode(): Uknown mode!" ); } //------------------------------------------------------------------------------ /** */ const char* nOdeAMotorJointNode::GetMode() { nOdeAMotorJoint* j = (nOdeAMotorJoint*)this->GetJoint(); if ( j->GetMode() == dAMotorUser ) return "user"; else if ( j->GetMode() == dAMotorEuler ) return "euler"; else n_warn( "nOdeAMotorJointNode::GetMode(): Unknown mode!" ); return "uknown"; } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 75 ] ] ]
b074d7e3cb5324488c55ba300489a45bed1e7458
f3001cd56567b121736343b480a1abf9cba1cd52
/K-Scope/Host/devicebase.cpp
ef53be8a8838cf35463ac49872aa2e3ada6d66eb
[]
no_license
cjsatuforc/AvrProjects
257f0594740b215ff2db2abaa79ec718cd14d647
a9f70a87a28e426ee4a558ca5ddc198f97a1ebdb
refs/heads/master
2020-04-13T19:00:06.609001
2011-03-18T16:01:42
2011-03-18T16:01:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
59
cpp
#include "devicebase.h" DeviceBase::DeviceBase() { }
[ [ [ 1, 5 ] ] ]
23f380cee3741d07d680ce1b240d51f1273a373c
81a38f1f0e77081746812a7f76a52dd0290fde81
/minicurso-glsl/00.Basico/src/main.cpp
73ff5b41f2e391ad5cdbc376e863f49819f0740e
[]
no_license
tamiresharumi/cg_project
500f437977465264460cd345f484c83feae95454
5c4027b3ae749f57f676ae830f2140cd72b51898
refs/heads/master
2021-01-20T12:16:41.916754
2011-06-20T02:00:23
2011-06-20T02:00:23
1,761,107
0
0
null
null
null
null
UTF-8
C++
false
false
3,562
cpp
//Pra comeรงar, sรณ queremos a SDL.h e gl.h #include <SDL/SDL.h> #include <GL/gl.h> int main(int argc, char *argv[]) { //Essas duas funรงรตes servem pra criar a nossa janela. A primeira inicializa //a SDL, enquanto que a segunda cria de fato a janela. Os parรขmetros para a //segunda funรงรฃo sรฃo: largura, altura, bpp, modo. // * largura, altura: as dimensรตes da janela que queremos criar // * bpp: bits per pixel, a "resoluรงรฃo de cores" da janela. O valor 32 // significa que queremos uma janela RGBA com 8 bits pra cada componente // * modo: como a janela deve ser criada. O valor SDL_OPENGL indica que a // janela deve ser criada com suporte a OpenGL SDL_Init(SDL_INIT_EVERYTHING); SDL_Surface *tela = SDL_SetVideoMode(300, 600, 32, SDL_OPENGL); //Ah, o loop principal. Jogue "false" em "rodando" e o programa para bool rodando = true; while (rodando) { //A primeira coisa a se fazer todo frame รฉ verificar quais foram os //eventos gerados pelo sistema operacional no frame anterior. Por //"evento", entende-se: // * Tecla pressionada/solta // * Botรฃo do mouse pressionado/solto // * Mouse movimentado // * รcone "X" da janela clicado // * Janela redimensionada // * Outros eventos do sistema operacional que nรฃo nos interessam agora SDL_Event e; //A funรงรฃo SDL_PollEvent pega o primeiro evento nรฃo processado atรฉ //agora (sรฃo armazenados em uma fila). Ela retorna 0 quando nรฃo hรก mais //eventos pra serem processados e alguma coisa diferente de zero quando //hรก algo ainda pendente. Isso รฉ usado pra tratar todos os eventos //_antes_ de fazer qualquer outra coisa no programa while (SDL_PollEvent(&e)) { //Um evento bastante comum: tecla pressionada. Os cรณdigos das teclas //como SDLK_ESCAPE, SDLK_UP etc. estรฃo no arquivo SDL/SDL_keysym.h if (e.type == SDL_KEYDOWN) if ((e.key.keysym.sym == SDLK_ESCAPE) or (e.key.keysym.sym == SDLK_e)) rodando = false; //Esse รฉ o evento gerado quando o usuรกrio clicou no "x" da janela. //Sรณ clicar nรฃo faz nada, o programa รฉ quem tem que decidir o que //fazer quando isso acontece. Aqui, sรณ fechamos o programa direto if (e.type == SDL_QUIT) rodando = false; } //Esses comandos servem pra limpar a tela. O primeiro serve pra //especificar a cor que รฉ pra ser usada pra limpar a tela, e nรฃo //precisaria ser chamada toda vez, pois ela seta a cor pra qual vocรช //quer atรฉ que essa funรงรฃo seja chamada de novo. A segunda limpa de fato //a tela. O argumento indica o que deve ser limpo. Nesse caso, sรณ //estamos limpando o "color buffer", mas hรก outros que usaremos em //outros projetos glClearColor(1,1,0,0); glClear(GL_COLOR_BUFFER_BIT); //Isso aqui รฉ pra mostrar o buffer na tela. Atรฉ agora, todos os comandos //de desenhar alguma coisa foram aplicados em um buffer "escondido", pra //que nรฃo apareรงa na tela uma imagem pela metade. Essa funรงรฃo faz com //que o buffer que estava escondido seja mostrado e, a partir de agora, //os comandos de desenho vรฃo pro buffer que aparecia antes. Depois troca //de novo e troca troca troca troca... Por isso que chama "double //buffering". A janela do SDL com OpenGL por padrรฃo รฉ criada com o //double buffer. Prรกtico, nรฉ? SDL_GL_SwapBuffers(); //Isso รฉ sรณ pra fazer o programa nรฃo gastar 100% de CPU pra uma coisa //tรฃo simples. SDL_Delay(10); } //Faz a SDL fechar todas as coisas dela SDL_Quit(); //Tchau! return 0; }
[ [ [ 1, 79 ] ] ]
45016cef90d852bac25fcc9142a59ed685ba1dd5
2c9e29d0cdae3e532ff969c0de530b5b8084b61e
/psp/video_hardware_surface.cpp
56ebeed29cf9fd3a829bd2c26c219f4abe416c4e
[]
no_license
Sondro/kurok
1695a976700f6c9732a761d33d092a679518e23b
59da1adb94e1132c5a2215b308280bacd7a3c812
refs/heads/master
2022-02-01T17:41:12.584690
2009-08-03T01:19:05
2009-08-03T01:19:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
37,666
cpp
/* Copyright (C) 1996-1997 Id Software, Inc. Copyright (C) 2007 Peter Mackay and Chris Swindle. 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. */ // r_surf.c: surface-related refresh code #include <pspgu.h> #include <pspgum.h> extern "C" { #include "../quakedef.h" } #include "lightmaps.h" #include "clipping.hpp" using namespace quake; int skytexturenum; /* #ifdef NORMAL_MODEL #define LIGHTMAP_BYTES 4 // 1 or 4, used to be 1 #define MAX_LIGHTMAPS 16 // used to be 64, reduced to fit under 2MB or else crashes psp if lightmap bytes is 4 #endif #ifdef SLIM_MODEL #define LIGHTMAP_BYTES 4 // 1 or 4, used to be 1 #define MAX_LIGHTMAPS 28 // used to be 64, reduced to fit under 2MB or else crashes psp if lightmap bytes is 4 //#define LIGHTMAP_BYTES 3 // 1 or 4, used to be 1 //#define MAX_LIGHTMAPS 37 // used to be 64, reduced to fit under 2MB or else crashes psp if lightmap bytes is 4 #endif */ #define BLOCK_WIDTH 128 #define BLOCK_HEIGHT 128 int lightmap_textures; //unsigned blocklights[18*18]; unsigned blocklights[BLOCK_WIDTH*BLOCK_HEIGHT*3]; // LordHavoc: .lit support (*3 for RGB) int active_lightmaps; typedef struct glRect_s { unsigned char l,t,w,h; } glRect_t; ////////////////////////////////////////////////////////////////////////////// // For none .lit maps. ////////////////////////////////////////////////////////////////////////////// glpoly_t *lightmap_polys[64]; qboolean lightmap_modified[64]; glRect_t lightmap_rectchange[64]; int allocated[64][BLOCK_WIDTH]; // the lightmap texture data needs to be kept in // main memory so texsubimage can update properly byte lightmaps[1*64*BLOCK_WIDTH*BLOCK_HEIGHT]; int lightmap_index[64]; // For gl_texsort 0 msurface_t *skychain = NULL; msurface_t *waterchain = NULL; void R_RenderDynamicLightmaps (msurface_t *fa); void VID_SetPaletteLM(); // switch palette for lightmaps void VID_SetPaletteTX(); // switch palette for textures /* =============== R_AddDynamicLights =============== */ void R_AddDynamicLights (msurface_t *surf) { int lnum; int sd, td; float dist, rad, minlight; vec3_t impact, local; int s, t; int i; int smax, tmax; mtexinfo_t *tex; // LordHavoc: .lit support begin float cred, cgreen, cblue, brightness; unsigned *bl; // LordHavoc: .lit support end smax = (surf->extents[0]>>4)+1; tmax = (surf->extents[1]>>4)+1; tex = surf->texinfo; for (lnum=0 ; lnum<MAX_DLIGHTS ; lnum++) { if ( !(surf->dlightbits & (1<<lnum) ) ) continue; // not lit by this light rad = cl_dlights[lnum].radius; dist = DotProduct (cl_dlights[lnum].origin, surf->plane->normal) - surf->plane->dist; rad -= fabsf(dist); minlight = cl_dlights[lnum].minlight; if (rad < minlight) continue; minlight = rad - minlight; for (i=0 ; i<3 ; i++) { impact[i] = cl_dlights[lnum].origin[i] - surf->plane->normal[i]*dist; } local[0] = DotProduct (impact, tex->vecs[0]) + tex->vecs[0][3]; local[1] = DotProduct (impact, tex->vecs[1]) + tex->vecs[1][3]; local[0] -= surf->texturemins[0]; local[1] -= surf->texturemins[1]; // LordHavoc: .lit support begin bl = blocklights; cred = cl_dlights[lnum].color[0] * 256.0f; cgreen = cl_dlights[lnum].color[1] * 256.0f; cblue = cl_dlights[lnum].color[2] * 256.0f; // LordHavoc: .lit support end for (t = 0 ; t<tmax ; t++) { td = int(local[1]) - t*16; if (td < 0) td = -td; for (s=0 ; s<smax ; s++) { sd = int(local[0]) - s*16; if (sd < 0) sd = -sd; if (sd > td) dist = sd + (td>>1); else dist = td + (sd>>1); if (dist < minlight) // LordHavoc: .lit support begin // blocklights[t*smax + s] += (rad - dist)*256; // LordHavoc: original code { brightness = rad - dist; bl[0] += (int) (brightness * cred); bl[1] += (int) (brightness * cgreen); bl[2] += (int) (brightness * cblue); } bl += 3; // LordHavoc: .lit support end } } } } /* =============== R_BuildLightMap Combine and scale multiple lightmaps into the 8.8 format in blocklights =============== */ void R_BuildLightMap (msurface_t *surf, byte *dest, int stride) { int smax, tmax; int t, r, s, q; int i, j, size; byte *lightmap; unsigned scale; int maps; unsigned *bl; unsigned *blcr, *blcg, *blcb; surf->cached_dlight = (surf->dlightframe == r_framecount) ? qtrue : qfalse; smax = (surf->extents[0]>>4)+1; tmax = (surf->extents[1]>>4)+1; size = smax*tmax; lightmap = surf->samples; // set to full bright if no light data if (r_fullbright.value || !cl.worldmodel->lightdata) { // LordHavoc: .lit support begin bl = blocklights; for (i=0 ; i<size ; i++) // LordHavoc: original code // blocklights[i] = 255*256; // LordHavoc: original code { *bl++ = 255*256; *bl++ = 255*256; *bl++ = 255*256; } // LordHavoc: .lit support end goto store; } // clear to no light // LordHavoc: .lit support begin bl = blocklights; for (i=0 ; i<size ; i++) // LordHavoc: original code // blocklights[i] = 0; // LordHavoc: original code { *bl++ = 0; *bl++ = 0; *bl++ = 0; } // LordHavoc: .lit support end // add all the lightmaps if (lightmap) for (maps = 0 ; maps < MAXLIGHTMAPS && surf->styles[maps] != 255 ; maps++) { scale = d_lightstylevalue[surf->styles[maps]]; surf->cached_light[maps] = scale; // 8.8 fraction // LordHavoc: .lit support begin bl = blocklights; for (i=0 ; i<size ; i++) // LordHavoc: original code // blocklights[i] += lightmap[i] * scale; // LordHavoc: original code //lightmap += size; // skip to next lightmap // LordHavoc: original code { *bl++ += *lightmap++ * scale; *bl++ += *lightmap++ * scale; *bl++ += *lightmap++ * scale; } // LordHavoc: .lit support end } // add all the dynamic lights if (surf->dlightframe == r_framecount) R_AddDynamicLights (surf); // bound, invert, and shift store: switch (LIGHTMAP_BYTES) { case 4: stride -= (smax<<2); bl = blocklights; for (i=0 ; i<tmax ; i++, dest += stride) { for (j=0 ; j<smax ; j++) { // LordHavoc: .lit support begin /* LordHavoc: original code t = *bl++; t >>= 7; if (t > 255) t = 255; dest[3] = 255-t; dest += 4; */ // LordHavoc: positive lighting (would be 255-t if it were inverse like glquake was) t = *bl++ >> 7;if (t > 255) t = 255;*dest++ = t; t = *bl++ >> 7;if (t > 255) t = 255;*dest++ = t; t = *bl++ >> 7;if (t > 255) t = 255;*dest++ = t; *dest++ = 255; // LordHavoc: .lit support end } } break; case 3: stride -= (smax<<2); bl = blocklights; for (i=0 ; i<tmax ; i++, dest += stride) { for (j=0 ; j<smax ; j++) { // LordHavoc: .lit support begin /* LordHavoc: original code t = *bl++; t >>= 7; if (t > 255) t = 255; dest[3] = 255-t; dest += 4; */ // LordHavoc: positive lighting (would be 255-t if it were inverse like glquake was) t = *bl++ >> 7;if (t > 255) t = 255;*dest++ = t; t = *bl++ >> 7;if (t > 255) t = 255;*dest++ = t; t = *bl++ >> 7;if (t > 255) t = 255;*dest++ = t; *dest++ = 255; // LordHavoc: .lit support end } } break; /* stride -= smax * 3; bl = blocklights; for (i=0 ; i<tmax ; i++, dest += stride) { for (j=0 ; j<smax ; j++) { t = *bl++ >> 7;if (t > 255) t = 255;*dest++ = t; t = *bl++ >> 7;if (t > 255) t = 255;*dest++ = t; t = *bl++ >> 7;if (t > 255) t = 255;*dest++ = t; } } break; */ case 2: bl = blocklights; for (i=0 ; i<tmax ; i++ ,dest += stride) { for (j=0 ; j<smax ; j++) { // LordHavoc: .lit support begin //t = *bl++; // LordHavoc: original code //t >>= 7; // LordHavoc: original code t = ((bl[0] + bl[1] + bl[2]) * 85) >> 15; // LordHavoc: basically / 3, but faster and combined with >> 7 shift down, note: actual number would be 85.3333... bl += 3; // LordHavoc: .lit support end if (t > 255) t = 255; dest[j] = t; } } break; /* //stride -= (smax<<1); bl = blocklights; for (i=0 ; i<tmax ; i++ , dest += stride) { for (j=0 ; j<smax ; j++) { t = *bl++; t >>= 7; if (t > 255) t = 255; byte x = (t & 0x00f0) >> 4; dest[2*j] = x | (x << 4); dest[2*j+1] = x | (x << 4); //dest += 2; } } break; */ case 1: bl = blocklights; for (i=0 ; i<tmax ; i++ ,dest += stride) { for (j=0 ; j<smax ; j++) { // LordHavoc: .lit support begin //t = *bl++; // LordHavoc: original code //t >>= 7; // LordHavoc: original code t = ((bl[0] + bl[1] + bl[2]) * 85) >> 15; // LordHavoc: basically / 3, but faster and combined with >> 7 shift down, note: actual number would be 85.3333... bl += 3; // LordHavoc: .lit support end if (t > 255) t = 255; dest[j] = t; } } break; default: Sys_Error ("Bad lightmap format"); } } /* =============== R_TextureAnimation Returns the proper texture for a given time and base texture =============== */ texture_t *R_TextureAnimation (texture_t *base) { int reletive; int count; if (currententity->frame) { if (base->alternate_anims) base = base->alternate_anims; } if (!base->anim_total) return base; reletive = (int)(cl.time*10) % base->anim_total; count = 0; while (base->anim_min > reletive || base->anim_max <= reletive) { base = base->anim_next; if (!base) Sys_Error ("R_TextureAnimation: broken cycle"); if (++count > 100) Sys_Error ("R_TextureAnimation: infinite cycle"); } return base; } /* ============================================================= BRUSH MODELS ============================================================= */ extern int solidskytexture; extern int alphaskytexture; extern float speedscale; // for top sky and bottom sky static inline void DrawGLPolyLM (glpoly_t *p) { // Does this poly need clipped? const int unclipped_vertex_count = p->numverts; const glvert_t* const unclipped_vertices = &(p->verts[p->numverts]); if (clipping::is_clipping_required( unclipped_vertices, unclipped_vertex_count)) { // Clip the polygon. const glvert_t* clipped_vertices; std::size_t clipped_vertex_count; clipping::clip( unclipped_vertices, unclipped_vertex_count, &clipped_vertices, &clipped_vertex_count); // Did we have any vertices left? if (clipped_vertex_count) { // Copy the vertices to the display list. const std::size_t buffer_size = clipped_vertex_count * sizeof(glvert_t); glvert_t* const display_list_vertices = static_cast<glvert_t*>(sceGuGetMemory(buffer_size)); memcpy(display_list_vertices, clipped_vertices, buffer_size); if (r_showtris.value) { sceGuDisable(GU_TEXTURE_2D); sceGuDisable(GU_BLEND); // Draw the clipped vertices. sceGumDrawArray( GU_LINE_STRIP, GU_TEXTURE_32BITF | GU_VERTEX_32BITF , clipped_vertex_count, 0, display_list_vertices); sceGuEnable(GU_TEXTURE_2D); sceGuEnable(GU_BLEND); } else { // Draw the clipped vertices. sceGuDrawArray( GU_TRIANGLE_FAN, GU_TEXTURE_32BITF | GU_VERTEX_32BITF , clipped_vertex_count, 0, display_list_vertices); } } } else { if (r_showtris.value) { sceGuDisable(GU_TEXTURE_2D); sceGuDisable(GU_BLEND); // Draw the lines directly. sceGumDrawArray( GU_LINE_STRIP, GU_TEXTURE_32BITF | GU_VERTEX_32BITF , unclipped_vertex_count, 0, unclipped_vertices); sceGuEnable(GU_TEXTURE_2D); sceGuEnable(GU_BLEND); } else { // Draw the poly directly. sceGuDrawArray( GU_TRIANGLE_FAN, GU_TEXTURE_32BITF | GU_VERTEX_32BITF , unclipped_vertex_count, 0, unclipped_vertices); } } } static inline void DrawGLPoly (glpoly_t *p) { // Does this poly need clipped? const int unclipped_vertex_count = p->numverts; const glvert_t* const unclipped_vertices = p->verts; if (clipping::is_clipping_required( unclipped_vertices, unclipped_vertex_count)) { // Clip the polygon. const glvert_t* clipped_vertices; std::size_t clipped_vertex_count; clipping::clip( unclipped_vertices, unclipped_vertex_count, &clipped_vertices, &clipped_vertex_count); // Did we have any vertices left? if (clipped_vertex_count) { // Copy the vertices to the display list. const std::size_t buffer_size = clipped_vertex_count * sizeof(glvert_t); glvert_t* const display_list_vertices = static_cast<glvert_t*>(sceGuGetMemory(buffer_size)); memcpy(display_list_vertices, clipped_vertices, buffer_size); // Draw the clipped vertices. sceGuDrawArray( GU_TRIANGLE_FAN, GU_TEXTURE_32BITF | GU_VERTEX_32BITF, clipped_vertex_count, 0, display_list_vertices); } } else { // Draw the poly directly. sceGuDrawArray( GU_TRIANGLE_FAN, GU_TEXTURE_32BITF | GU_VERTEX_32BITF, unclipped_vertex_count, 0, unclipped_vertices); } } static void DrawGLWaterPoly (glpoly_t *p) { #if 0 int i; const glvert_t *v; float s, t, os, ot; vec3_t nv; /*GL_DisableMultitexture(); glBegin (GL_TRIANGLE_FAN);*/ v = p->verts; for (i=0 ; i<p->numverts ; i++, ++v) { /*glTexCoord2f (v[3], v[4]);*/ nv[0] = v->xyz[0] + 8*sinf(v->xyz[1]*0.05+realtime)*sinf(v->xyz[2]*0.05+realtime); nv[1] = v->xyz[1] + 8*sinf(v->xyz[0]*0.05+realtime)*sinf(v->xyz[2]*0.05+realtime); nv[2] = v->xyz[2]; /*glVertex3fv (nv);*/ } /*glEnd ();*/ #else DrawGLPoly(p); #endif } //static void DrawGLWaterPolyLightmap (glpoly_t *p) //{ // int i; // const glvert_t *v; // float s, t, os, ot; // vec3_t nv; /*GL_DisableMultitexture(); glBegin (GL_TRIANGLE_FAN);*/ // v = p->verts; // for (i=0 ; i<p->numverts ; i++, ++v) // { /*glTexCoord2f (v[5], v[6]);*/ // nv[0] = v->xyz[0] + 8*sinf(v->xyz[1]*0.05+realtime)*sinf(v->xyz[2]*0.05+realtime); // nv[1] = v->xyz[1] + 8*sinf(v->xyz[0]*0.05+realtime)*sinf(v->xyz[2]*0.05+realtime); // nv[2] = v->xyz[2]; /*glVertex3fv (nv);*/ // } /*glEnd ();*/ //} /* ================ R_BlendLightmaps ================ */ static void R_BlendLightmaps (void) { int i; glpoly_t *p; if (r_fullbright.value) return; sceGuDepthMask(GU_TRUE); sceGuEnable(GU_BLEND); sceGuBlendFunc(GU_ADD, GU_DST_COLOR, GU_SRC_COLOR, 0, 0); VID_SetPaletteLM(); if (r_lightmap.value) sceGuDisable(GU_BLEND); for (i=0 ; i<MAX_LIGHTMAPS ; i++) { p = lightmap_polys[i]; if (!p) continue; char lm_name[16]; if (lightmap_modified[i]) { lightmap_modified[i] = qfalse; lightmap_rectchange[i].l = BLOCK_WIDTH; lightmap_rectchange[i].t = BLOCK_HEIGHT; lightmap_rectchange[i].w = 0; lightmap_rectchange[i].h = 0; sprintf(lm_name,"lightmap%d",i); lightmap_index[i] = GL_LoadTextureLM (lm_name, BLOCK_WIDTH, BLOCK_HEIGHT, lightmaps+(i*BLOCK_WIDTH*BLOCK_HEIGHT*LIGHTMAP_BYTES), LIGHTMAP_BYTES, GU_LINEAR, qtrue); } GL_BindLM (lightmap_index[i]); for ( ; p ; p=p->chain) { if (p->flags & SURF_UNDERWATER) DrawGLPolyLM(p); else DrawGLPolyLM(p); } } VID_SetPaletteTX(); sceGuDisable(GU_BLEND); sceGuBlendFunc(GU_ADD, GU_SRC_ALPHA, GU_ONE_MINUS_SRC_ALPHA, 0, 0); sceGuDepthMask (GU_FALSE); } /* ================ R_RenderBrushPoly ================ */ void R_RenderBrushPoly (msurface_t *fa) { texture_t *t; byte *base; int maps; glRect_t *theRect; int smax, tmax; unsigned *bl; c_brush_polys++; if (fa->flags & SURF_DRAWSKY) { // warp texture, no lightmaps EmitBothSkyLayers (fa); return; } t = R_TextureAnimation (fa->texinfo->texture); GL_Bind (t->gl_texturenum); if (fa->flags & SURF_DRAWTURB) { // warp texture, no lightmaps EmitWaterPolys (fa); return; } sceGuEnable(GU_ALPHA_TEST); sceGuAlphaFunc(GU_GREATER, 0x88, 0xff); if (fa->flags & SURF_UNDERWATER) DrawGLWaterPoly (fa->polys); // Don't draw texture and lightmaps. else if (!Q_strncmp(fa->texinfo->texture->name,"nodraw",6)) return; // Alpha blended textures, no lightmaps. else if ((!Q_strncmp(fa->texinfo->texture->name,"z",1)) || (!Q_strncmp(fa->texinfo->texture->name,"{",1))) { if (kurok) { sceGuDepthMask(GU_TRUE); sceGuDisable(GU_ALPHA_TEST); sceGuEnable(GU_BLEND); sceGuTexFunc(GU_TFX_REPLACE, GU_TCC_RGBA); DrawGLPoly (fa->polys); sceGuDepthMask(GU_FALSE); sceGuEnable(GU_ALPHA_TEST); sceGuDisable(GU_BLEND); sceGuTexFunc(GU_TFX_MODULATE, GU_TCC_RGBA); return; } else DrawGLPoly (fa->polys); } // No lightmaps. else if (!Q_strncmp(fa->texinfo->texture->name,"light",5)) { if (kurok) { DrawGLPoly (fa->polys); return; } else DrawGLPoly (fa->polys); } // Surface uvmaps warp, like metal or glass effects. else if (!Q_strncmp(fa->texinfo->texture->name,"env",3)) { if (kurok) EmitReflectivePolys (fa); else DrawGLPoly (fa->polys); } // Surface uvmaps warp, like metal or glass effects + transparency. else if (!Q_strncmp(fa->texinfo->texture->name,"glass",5)) { if (r_glassalpha.value < 1) { if (kurok) { float alpha1 = r_glassalpha.value; float alpha2 = 1 - r_glassalpha.value; sceGuEnable (GU_BLEND); sceGuDepthMask(GU_TRUE); sceGuBlendFunc(GU_ADD, GU_FIX, GU_FIX, GU_COLOR(alpha1,alpha1,alpha1,alpha1), GU_COLOR(alpha2,alpha2,alpha2,alpha2)); EmitReflectivePolys (fa); sceGuBlendFunc(GU_ADD, GU_SRC_ALPHA, GU_ONE_MINUS_SRC_ALPHA, 0, 0); sceGuDepthMask(GU_FALSE); sceGuDisable (GU_BLEND); } else DrawGLPoly (fa->polys); } else { if (kurok) EmitReflectivePolys (fa); else DrawGLPoly (fa->polys); } } else DrawGLPoly (fa->polys); // add the poly to the proper lightmap chain fa->polys->chain = lightmap_polys[fa->lightmaptexturenum]; lightmap_polys[fa->lightmaptexturenum] = fa->polys; // check for lightmap modification for (maps = 0 ; maps < MAXLIGHTMAPS && fa->styles[maps] != 255 ; maps++) if (d_lightstylevalue[fa->styles[maps]] != fa->cached_light[maps]) goto dynamic; if (fa->dlightframe == r_framecount // dynamic this frame || fa->cached_dlight) // dynamic previously { dynamic: if (r_dynamic.value) { lightmap_modified[fa->lightmaptexturenum] = qtrue; theRect = &lightmap_rectchange[fa->lightmaptexturenum]; if (fa->light_t < theRect->t) { if (theRect->h) theRect->h += theRect->t - fa->light_t; theRect->t = fa->light_t; } if (fa->light_s < theRect->l) { if (theRect->w) theRect->w += theRect->l - fa->light_s; theRect->l = fa->light_s; } smax = (fa->extents[0]>>4)+1; tmax = (fa->extents[1]>>4)+1; if ((theRect->w + theRect->l) < (fa->light_s + smax)) theRect->w = (fa->light_s-theRect->l)+smax; if ((theRect->h + theRect->t) < (fa->light_t + tmax)) theRect->h = (fa->light_t-theRect->t)+tmax; base = lightmaps + fa->lightmaptexturenum*LIGHTMAP_BYTES*BLOCK_WIDTH*BLOCK_HEIGHT; base += fa->light_t * BLOCK_WIDTH * LIGHTMAP_BYTES + fa->light_s * LIGHTMAP_BYTES; R_BuildLightMap (fa, base, BLOCK_WIDTH*LIGHTMAP_BYTES); } } sceGuAlphaFunc(GU_GREATER, 0, 0xff); sceGuDisable(GU_ALPHA_TEST); } /* ================ R_RenderDynamicLightmaps Multitexture ================ */ void R_RenderDynamicLightmaps (msurface_t *fa) { // texture_t *t; byte *base; int maps; glRect_t *theRect; int smax, tmax; c_brush_polys++; if (fa->flags & ( SURF_DRAWSKY | SURF_DRAWTURB) ) return; fa->polys->chain = lightmap_polys[fa->lightmaptexturenum]; lightmap_polys[fa->lightmaptexturenum] = fa->polys; // check for lightmap modification for (maps = 0 ; maps < MAXLIGHTMAPS && fa->styles[maps] != 255 ; maps++) if (d_lightstylevalue[fa->styles[maps]] != fa->cached_light[maps]) goto dynamic; if (fa->dlightframe == r_framecount // dynamic this frame || fa->cached_dlight) // dynamic previously { dynamic: if (r_dynamic.value) { lightmap_modified[fa->lightmaptexturenum] = qtrue; theRect = &lightmap_rectchange[fa->lightmaptexturenum]; if (fa->light_t < theRect->t) { if (theRect->h) theRect->h += theRect->t - fa->light_t; theRect->t = fa->light_t; } if (fa->light_s < theRect->l) { if (theRect->w) theRect->w += theRect->l - fa->light_s; theRect->l = fa->light_s; } smax = (fa->extents[0]>>4)+1; tmax = (fa->extents[1]>>4)+1; if ((theRect->w + theRect->l) < (fa->light_s + smax)) theRect->w = (fa->light_s-theRect->l)+smax; if ((theRect->h + theRect->t) < (fa->light_t + tmax)) theRect->h = (fa->light_t-theRect->t)+tmax; base = lightmaps + fa->lightmaptexturenum*LIGHTMAP_BYTES*BLOCK_WIDTH*BLOCK_HEIGHT; base += fa->light_t * BLOCK_WIDTH * LIGHTMAP_BYTES + fa->light_s * LIGHTMAP_BYTES; R_BuildLightMap (fa, base, BLOCK_WIDTH*LIGHTMAP_BYTES); } } } /* ================ R_MirrorChain ================ */ void R_MirrorChain (msurface_t *s) { if (mirror) return; mirror = qtrue; mirror_plane = s->plane; } /* ================ R_DrawWaterSurfaces ================ */ void R_DrawWaterSurfaces (void) { int i; msurface_t *s; texture_t *t; if (r_wateralpha.value == 1.0) return; float alpha1 = r_wateralpha.value; float alpha2 = 1 - r_wateralpha.value; // // go back to the world matrix // sceGumMatrixMode(GU_VIEW); sceGumLoadMatrix(&r_world_matrix); sceGumUpdateMatrix(); sceGumMatrixMode(GU_MODEL); if (r_wateralpha.value < 1.0) { sceGuEnable (GU_BLEND); sceGuTexFunc(GU_TFX_REPLACE , GU_TCC_RGBA); sceGuBlendFunc(GU_ADD, GU_FIX, GU_FIX, GU_COLOR(alpha1,alpha1,alpha1,alpha1), GU_COLOR(alpha2,alpha2,alpha2,alpha2)); } { for (i=0 ; i<cl.worldmodel->numtextures ; i++) { t = cl.worldmodel->textures[i]; if (!t) continue; s = t->texturechain; if (!s) continue; if ( !(s->flags & SURF_DRAWTURB ) ) continue; // set modulate mode explicitly GL_Bind (t->gl_texturenum); for ( ; s ; s=s->texturechain) EmitWaterPolys (s); t->texturechain = NULL; } } if (r_wateralpha.value < 1.0) { sceGuTexFunc(GU_TFX_REPLACE, GU_TCC_RGBA); sceGuBlendFunc(GU_ADD, GU_SRC_ALPHA, GU_ONE_MINUS_SRC_ALPHA, 0, 0); sceGuDisable (GU_BLEND); } } /* ================ DrawTextureChains ================ */ static void DrawTextureChains (void) { int i; msurface_t *s; texture_t *t; /* if (!gl_texsort.value) { GL_DisableMultitexture(); if (skychain) { R_DrawSkyChain(skychain); skychain = NULL; } return; } */ for (i=0 ; i<cl.worldmodel->numtextures ; i++) { t = cl.worldmodel->textures[i]; if (!t) continue; s = t->texturechain; if (!s) continue; if (i == skytexturenum) R_DrawSkyChain (s); else if (i == mirrortexturenum && r_mirroralpha.value != 1.0) { R_MirrorChain (s); continue; } else { if ((s->flags & SURF_DRAWTURB) && r_wateralpha.value != 1.0) continue; // draw translucent water later for ( ; s ; s=s->texturechain) R_RenderBrushPoly (s); } t->texturechain = NULL; } } /* ================= R_DrawBrushModel ================= */ void R_DrawBrushModel (entity_t *e) { int k;//j, k; vec3_t mins, maxs; int i;//, numsurfaces; msurface_t *psurf; float dot; mplane_t *pplane; model_t *clmodel; qboolean rotated; currententity = e; currenttexture = -1; clmodel = e->model; if (e->angles[0] || e->angles[1] || e->angles[2]) { rotated = qtrue; for (i=0 ; i<3 ; i++) { mins[i] = (e->origin[i] - clmodel->radius); maxs[i] = (e->origin[i] + clmodel->radius); } } else { rotated = qfalse; VectorAdd (e->origin, clmodel->mins, mins); VectorAdd (e->origin, clmodel->maxs, maxs); } if (R_CullBox (mins, maxs)) return; memset (lightmap_polys, 0, sizeof(lightmap_polys)); VectorSubtract (r_refdef.vieworg, e->origin, modelorg); if (rotated) { vec3_t temp; vec3_t forward, right, up; VectorCopy (modelorg, temp); AngleVectors (e->angles, forward, right, up); modelorg[0] = DotProduct (temp, forward); modelorg[1] = -DotProduct (temp, right); modelorg[2] = DotProduct (temp, up); } psurf = &clmodel->surfaces[clmodel->firstmodelsurface]; // calculate dynamic lighting for bmodel if it's not an // instanced model if (clmodel->firstmodelsurface != 0/* && !gl_flashblend.value*/) { for (k=0 ; k<MAX_DLIGHTS ; k++) { if ((cl_dlights[k].die < cl.time) || (!cl_dlights[k].radius)) continue; R_MarkLights (&cl_dlights[k], 1<<k, clmodel->nodes + clmodel->hulls[0].firstclipnode); } } sceGumPushMatrix(); e->angles[0] = -e->angles[0]; // stupid quake bug R_RotateForEntity (e); clipping::begin_brush_model(); e->angles[0] = -e->angles[0]; // stupid quake bug // // draw texture // for (i=0 ; i<clmodel->nummodelsurfaces ; i++, psurf++) { // find which side of the node we are on pplane = psurf->plane; dot = DotProduct (modelorg, pplane->normal) - pplane->dist; // draw the polygon if (((psurf->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) { R_RenderBrushPoly (psurf); } } R_BlendLightmaps (); clipping::end_brush_model(); sceGumPopMatrix(); sceGumUpdateMatrix(); } /* ============================================================= WORLD MODEL ============================================================= */ /* ================ R_RecursiveWorldNode ================ */ void R_RecursiveWorldNode (mnode_t *node) { int c, side;//, i, *pindex; // vec3_t acceptpt, rejectpt; mplane_t *plane; msurface_t *surf, **mark; mleaf_t *pleaf; float dot;//, d; // vec3_t mins, maxs; if (node->contents == CONTENTS_SOLID) return; // solid if (node->visframe != r_visframecount) return; if (R_CullBox (node->minmaxs, node->minmaxs+3)) return; // if a leaf node, draw stuff if (node->contents < 0) { pleaf = (mleaf_t *)node; mark = pleaf->firstmarksurface; c = pleaf->nummarksurfaces; if (c) { do { (*mark)->visframe = r_framecount; mark++; } while (--c); } // deal with model fragments in this leaf if (pleaf->efrags) R_StoreEfrags (&pleaf->efrags); return; } // node is just a decision point, so go down the apropriate sides // find which side of the node we are on plane = node->plane; switch (plane->type) { case PLANE_X: dot = modelorg[0] - plane->dist; break; case PLANE_Y: dot = modelorg[1] - plane->dist; break; case PLANE_Z: dot = modelorg[2] - plane->dist; break; default: dot = DotProduct (modelorg, plane->normal) - plane->dist; break; } if (dot >= 0) side = 0; else side = 1; // recurse down the children, front side first R_RecursiveWorldNode (node->children[side]); // draw stuff c = node->numsurfaces; if (c) { surf = cl.worldmodel->surfaces + node->firstsurface; if (dot < 0 -BACKFACE_EPSILON) side = SURF_PLANEBACK; else if (dot > BACKFACE_EPSILON) side = 0; { for ( ; c ; c--, surf++) { if (surf->visframe != r_framecount) continue; // don't backface underwater surfaces, because they warp if ( !(surf->flags & SURF_UNDERWATER) && ( (dot < 0) ^ !!(surf->flags & SURF_PLANEBACK)) ) continue; // wrong side // if sorting by texture, just store it out /*if (gl_texsort.value)*/ { if (!mirror || surf->texinfo->texture != cl.worldmodel->textures[mirrortexturenum]) { surf->texturechain = surf->texinfo->texture->texturechain; surf->texinfo->texture->texturechain = surf; } }/* else if (surf->flags & SURF_DRAWSKY) { surf->texturechain = skychain; skychain = surf; } else if (surf->flags & SURF_DRAWTURB) { surf->texturechain = waterchain; waterchain = surf; } else R_DrawSequentialPoly (surf);*/ } } } // recurse down the back side R_RecursiveWorldNode (node->children[!side]); } extern char skybox_name[32]; /* ============= R_DrawWorld ============= */ void R_DrawWorld (void) { entity_t ent; // int i; memset (&ent, 0, sizeof(ent)); ent.model = cl.worldmodel; VectorCopy (r_refdef.vieworg, modelorg); currententity = &ent; currenttexture = -1; /*glColor3f (1,1,1);*/ memset (lightmap_polys, 0, sizeof(lightmap_polys)); //#ifdef QUAKE2 R_ClearSkyBox (); //#endif R_RecursiveWorldNode (cl.worldmodel->nodes); DrawTextureChains (); R_BlendLightmaps (); //#ifdef QUAKE2 if (skybox_name[0]) R_DrawSkyBox (); // if (r_refdef.fog_end > 0) // R_DrawSkyBoxFog (); //#endif } /* =============== R_MarkLeaves =============== */ void R_MarkLeaves (void) { byte *vis; mnode_t *node; int i; byte solid[4096]; if (r_oldviewleaf == r_viewleaf && !r_novis.value) return; if (mirror) return; r_visframecount++; r_oldviewleaf = r_viewleaf; if (r_novis.value) { vis = solid; memset (solid, 0xff, (cl.worldmodel->numleafs+7)>>3); } else vis = Mod_LeafPVS (r_viewleaf, cl.worldmodel); for (i=0 ; i<cl.worldmodel->numleafs ; i++) { if (vis[i>>3] & (1<<(i&7))) { node = (mnode_t *)&cl.worldmodel->leafs[i+1]; do { if (node->visframe == r_visframecount) break; node->visframe = r_visframecount; node = node->parent; } while (node); } } } /* ============================================================================= LIGHTMAP ALLOCATION ============================================================================= */ // returns a texture number and the position inside it static int AllocBlock (int w, int h, int *x, int *y) { int i, j; int best, best2; // int bestx; int texnum; for (texnum=0 ; texnum<MAX_LIGHTMAPS ; texnum++) { best = BLOCK_HEIGHT; for (i=0 ; i<BLOCK_WIDTH-w ; i++) { best2 = 0; for (j=0 ; j<w ; j++) { if (allocated[texnum][i+j] >= best) break; if (allocated[texnum][i+j] > best2) best2 = allocated[texnum][i+j]; } if (j == w) { // this is a valid spot *x = i; *y = best = best2; } } if (best + h > BLOCK_HEIGHT) continue; for (i=0 ; i<w ; i++) allocated[texnum][*x + i] = best + h; return texnum; } // Con_Printf ("Lightmap surfaces in map exceeds maximum\n"); // Sys_Error ("AllocBlock: full"); return 0; //johnfitz -- shut up compiler } mvertex_t *r_pcurrentvertbase; model_t *currentmodel; int nColinElim; /* ================ BuildSurfaceDisplayList ================ */ static void BuildSurfaceDisplayList (msurface_t *fa) { int i, lindex, lnumverts;//, s_axis, t_axis; // float dist, lastdist, lzi, scale, u, v, frac; // unsigned mask; // vec3_t local, transformed; medge_t *pedges, *r_pedge; // mplane_t *pplane; int vertpage;//, newverts, newpage, lastvert; // qboolean visible; float *vec; float s, t; glpoly_t *poly; // reconstruct the polygon pedges = currentmodel->edges; lnumverts = fa->numedges; vertpage = 0; // // draw texture // poly = static_cast<glpoly_t*>(Hunk_Alloc (sizeof(glpoly_t) + (lnumverts * 2 - 1) * sizeof(glvert_t))); poly->next = fa->polys; poly->flags = fa->flags; fa->polys = poly; poly->numverts = lnumverts; for (i=0 ; i<lnumverts ; i++) { lindex = currentmodel->surfedges[fa->firstedge + i]; if (lindex > 0) { r_pedge = &pedges[lindex]; vec = r_pcurrentvertbase[r_pedge->v[0]].position; } else { r_pedge = &pedges[-lindex]; vec = r_pcurrentvertbase[r_pedge->v[1]].position; } s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3]; s /= fa->texinfo->texture->width; t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3]; t /= fa->texinfo->texture->height; VectorCopy(vec, poly->verts[i].xyz); poly->verts[i].st[0] = s; poly->verts[i].st[1] = t; // // lightmap texture coordinates // s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3]; s -= fa->texturemins[0]; s += fa->light_s*16; s += 8; s /= BLOCK_WIDTH*16; //fa->texinfo->texture->width; t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3]; t -= fa->texturemins[1]; t += fa->light_t*16; t += 8; t /= BLOCK_HEIGHT*16; //fa->texinfo->texture->height; VectorCopy(vec, poly->verts[i + lnumverts].xyz); poly->verts[i + lnumverts].st[0] = s; poly->verts[i + lnumverts].st[1] = t; } // // remove co-linear points - Ed // // Colinear point removal-start int lm_vert_offset = lnumverts; if (!gl_keeptjunctions.value && !(fa->flags & SURF_UNDERWATER) ) { int numRemoved = 0; int j; for (i = 0 ; i < lnumverts ; ++i) { vec3_t v1, v2; const glvert_t *prev, *this_, *next; // float f; prev = &poly->verts[(i + lnumverts - 1) % lnumverts]; this_ = &poly->verts[i]; next = &poly->verts[(i + 1) % lnumverts]; VectorSubtract( this_->xyz, prev->xyz, v1 ); VectorNormalize( v1 ); VectorSubtract( next->xyz, prev->xyz, v2 ); VectorNormalize( v2 ); // skip co-linear points #define COLINEAR_EPSILON 0.001 if ((fabsf( v1[0] - v2[0] ) <= COLINEAR_EPSILON) && (fabsf( v1[1] - v2[1] ) <= COLINEAR_EPSILON) && (fabsf( v1[2] - v2[2] ) <= COLINEAR_EPSILON)) { for (j = i + 1; j < lnumverts; ++j) { poly->verts[j - 1] = poly->verts[j]; poly->verts[lm_vert_offset + j - 1] = poly->verts[lm_vert_offset+j]; } --lnumverts; ++nColinElim; numRemoved++; // retry next vertex next time, which is now current vertex --i; } } if (numRemoved > 0) { for (j = lm_vert_offset; j < lm_vert_offset + lnumverts; j++) { poly->verts[j - numRemoved] = poly->verts[j]; } } } // Colinear point removal-end poly->numverts = lnumverts; } /* ======================== GL_CreateSurfaceLightmap ======================== */ static void GL_CreateSurfaceLightmap (msurface_t *surf) { int smax, tmax;//, s, t, l, i; byte *base; if (surf->flags & (SURF_DRAWSKY|SURF_DRAWTURB)) return; smax = (surf->extents[0]>>4)+1; tmax = (surf->extents[1]>>4)+1; surf->lightmaptexturenum = AllocBlock (smax, tmax, &surf->light_s, &surf->light_t); base = lightmaps + surf->lightmaptexturenum*LIGHTMAP_BYTES*BLOCK_WIDTH*BLOCK_HEIGHT; base += (surf->light_t * BLOCK_WIDTH + surf->light_s) * LIGHTMAP_BYTES; R_BuildLightMap (surf, base, BLOCK_WIDTH*LIGHTMAP_BYTES); } /* ================== GL_BuildLightmaps Builds the lightmap texture with all the surfaces from all brush models ================== */ void GL_BuildLightmaps (void) { int i, j; model_t *m; // Con_Printf ("Lightmap surfaces = %i\n", MAX_LIGHTMAPS); // Con_Printf ("Lightmap bytes = %i\n", LIGHTMAP_BYTES); memset (allocated, 0, sizeof(allocated)); r_framecount = 1; // no dlightcache if (!lightmap_textures) { lightmap_textures = 0; } for (j=1 ; j<MAX_MODELS ; j++) { m = cl.model_precache[j]; if (!m) break; if (m->name[0] == '*') continue; r_pcurrentvertbase = m->vertexes; currentmodel = m; for (i=0 ; i<m->numsurfaces ; i++) { GL_CreateSurfaceLightmap (m->surfaces + i); if ( m->surfaces[i].flags & SURF_DRAWTURB ) continue; #ifndef QUAKE2 if ( m->surfaces[i].flags & SURF_DRAWSKY ) continue; #endif BuildSurfaceDisplayList (m->surfaces + i); } } // // upload all lightmaps that were filled // char lm_name[16]; for (i=0 ; i<MAX_LIGHTMAPS ; i++) { if (!allocated[i][0]) break; // no more used lightmap_modified[i] = qfalse; lightmap_rectchange[i].l = BLOCK_WIDTH; lightmap_rectchange[i].t = BLOCK_HEIGHT; lightmap_rectchange[i].w = 0; lightmap_rectchange[i].h = 0; sprintf(lm_name,"lightmap%d",i); lightmap_index[i] = GL_LoadTextureLM (lm_name, BLOCK_WIDTH, BLOCK_HEIGHT, lightmaps+(i*BLOCK_WIDTH*BLOCK_HEIGHT*LIGHTMAP_BYTES), LIGHTMAP_BYTES, GU_LINEAR, qtrue); } }
[ [ [ 1, 1646 ] ] ]
c49f6474f6cab4b06ebc539447daf01cca113480
8d1d891c3a1f9b4c09d6edf8cad30fcf03a214ed
/source/tools/ImageBank.h
1299f982f4854425415e06729ca29c27897ecd5c
[]
no_license
mightymouse2016/shootmii
7a53a70d027ec8bc8e957c7113144de57ecfa1a5
6a44637da4db44ba05d5d14c9a742f5d053041fa
refs/heads/master
2021-01-10T06:36:38.009975
2010-07-20T19:43:23
2010-07-20T19:43:23
54,534,472
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,327
h
#ifndef IMAGEBANK_H_ #define IMAGEBANK_H_ #include <vector> #include "GRRLIB.h" namespace shootmii { enum ImageTexture { TXT_SUN, TXT_DOCK, TXT_TANK, TXT_AMMO1, TXT_AMMO2, TXT_SMOKE, TXT_POPUP, TXT_SHIELD, TXT_CANNON, TXT_GHOST1, TXT_GHOST2, TXT_TERRAIN, TXT_HOMING1, TXT_HOMING2, TXT_GUIDED1, TXT_GUIDED2, TXT_BG_CLOUD, TXT_FG_CLOUD, TXT_BUTTON_1, TXT_POINTER_1, TXT_POINTER_2, TXT_POINTER_3, TXT_POINTER_4, TXT_BONUS_LIFE, TXT_LIFE_JAUGE, TXT_HEAT_JAUGE, TXT_WIND_JAUGE, TXT_CROSSHAIR1, TXT_CROSSHAIR2, TXT_FURY_JAUGE1, TXT_FURY_JAUGE2, TXT_LASER_JAUGE, TXT_SCORE_PANEL, TXT_BONUS_SHIELD, TXT_SHIELD_JAUGE, TXT_TITLE_SCREEN, TXT_BONUS_HOMING, TXT_BONUS_POISON, TXT_BONUS_POTION, TXT_BONUS_GUIDED, TXT_HOMING_SMOKE, TXT_STRENGTH_JAUGE, TXT_BONUS_CROSS_HAIR, TXT_STRENGTH_SPRITES, TXT_ALPHA_FURY_JAUGE1, TXT_ALPHA_FURY_JAUGE2, TXT_CANNONBALL_AIR_EXPLOSION, TXT_CANNONBALL_HIT_EXPLOSION, TXT_CANNONBALL_GROUND_EXPLOSION, NUMBER_OF_TEXTURES // Utilisรฉ comme condition d'arrรชt des boucles }; class ImageBank { private: std::vector<GRRLIB_texImg*> allTextures; public: ImageBank(); virtual ~ImageBank(); GRRLIB_texImg* get(ImageTexture textureName); void init(); }; } #endif /*IMAGEBANK_H_*/
[ "denisgeorge666@c8eafc54-4d23-11de-9e51-a92ed582648b", "Altarfinch@c8eafc54-4d23-11de-9e51-a92ed582648b", "altarfinch@c8eafc54-4d23-11de-9e51-a92ed582648b" ]
[ [ [ 1, 3 ], [ 6, 7 ], [ 28, 28 ], [ 52, 52 ], [ 72, 75 ] ], [ [ 4, 5 ], [ 16, 16 ], [ 65, 65 ] ], [ [ 8, 15 ], [ 17, 27 ], [ 29, 51 ], [ 53, 64 ], [ 66, 71 ] ] ]
1204b7ad31f2947665f2ed7cedb6f90f927099a9
a84b013cd995870071589cefe0ab060ff3105f35
/webdriver/branches/chrome/chrome/src/cpp/include/v8/src/frames-ia32.h
333fbc3cdd6bc1e95d27d6d576e2ede55cf21c6d
[ "Apache-2.0" ]
permissive
vdt/selenium
137bcad58b7184690b8785859d77da0cd9f745a0
30e5e122b068aadf31bcd010d00a58afd8075217
refs/heads/master
2020-12-27T21:35:06.461381
2009-08-18T15:56:32
2009-08-18T15:56:32
13,650,409
1
0
null
null
null
null
UTF-8
C++
false
false
10,779
h
// Copyright 2006-2008 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_FRAMES_IA32_H_ #define V8_FRAMES_IA32_H_ namespace v8 { namespace internal { // Register lists // Note that the bit values must match those used in actual instruction encoding static const int kNumRegs = 8; // Caller-saved registers static const RegList kJSCallerSaved = 1 << 0 | // eax 1 << 1 | // ecx 1 << 2 | // edx 1 << 3 | // ebx - used as a caller-saved register in JavaScript code 1 << 7; // edi - callee function static const int kNumJSCallerSaved = 5; typedef Object* JSCallerSavedBuffer[kNumJSCallerSaved]; // ---------------------------------------------------- class StackHandlerConstants : public AllStatic { public: static const int kNextOffset = 0 * kPointerSize; static const int kPPOffset = 1 * kPointerSize; static const int kFPOffset = 2 * kPointerSize; // TODO(1233780): Get rid of the code slot in stack handlers. static const int kCodeOffset = 3 * kPointerSize; static const int kStateOffset = 4 * kPointerSize; static const int kPCOffset = 5 * kPointerSize; static const int kAddressDisplacement = -1 * kPointerSize; static const int kSize = kPCOffset + kPointerSize; }; class EntryFrameConstants : public AllStatic { public: static const int kCallerFPOffset = -6 * kPointerSize; static const int kFunctionArgOffset = +3 * kPointerSize; static const int kReceiverArgOffset = +4 * kPointerSize; static const int kArgcOffset = +5 * kPointerSize; static const int kArgvOffset = +6 * kPointerSize; }; class ExitFrameConstants : public AllStatic { public: static const int kDebugMarkOffset = -2 * kPointerSize; static const int kSPOffset = -1 * kPointerSize; // Let the parameters pointer for exit frames point just below the // frame structure on the stack (frame pointer and return address). static const int kPPDisplacement = +2 * kPointerSize; static const int kCallerFPOffset = 0 * kPointerSize; static const int kCallerPCOffset = +1 * kPointerSize; }; class StandardFrameConstants : public AllStatic { public: static const int kExpressionsOffset = -3 * kPointerSize; static const int kMarkerOffset = -2 * kPointerSize; static const int kContextOffset = -1 * kPointerSize; static const int kCallerFPOffset = 0 * kPointerSize; static const int kCallerPCOffset = +1 * kPointerSize; static const int kCallerSPOffset = +2 * kPointerSize; }; class JavaScriptFrameConstants : public AllStatic { public: // FP-relative. static const int kLocal0Offset = StandardFrameConstants::kExpressionsOffset; static const int kSavedRegistersOffset = +2 * kPointerSize; static const int kFunctionOffset = StandardFrameConstants::kMarkerOffset; // CallerSP-relative (aka PP-relative) static const int kParam0Offset = -2 * kPointerSize; static const int kReceiverOffset = -1 * kPointerSize; }; class ArgumentsAdaptorFrameConstants : public AllStatic { public: static const int kLengthOffset = StandardFrameConstants::kExpressionsOffset; }; class InternalFrameConstants : public AllStatic { public: static const int kCodeOffset = StandardFrameConstants::kExpressionsOffset; }; inline Object* JavaScriptFrame::function() const { const int offset = JavaScriptFrameConstants::kFunctionOffset; Object* result = Memory::Object_at(fp() + offset); ASSERT(result->IsJSFunction()); return result; } // ---------------------------------------------------- // C Entry frames: // lower | Stack | // addresses | ^ | // | | | // | | // +-------------+ // | entry_pc | // +-------------+ <--+ entry_sp // . | // . | // . | // +-------------+ | // -3 | entry_sp --+----+ // e +-------------+ // n -2 | C function | // t +-------------+ // r -1 | caller_pp | // y +-------------+ <--- fp (frame pointer, ebp) // 0 | caller_fp | // f +-------------+ // r 1 | caller_pc | // a +-------------+ <--- caller_sp (stack pointer, esp) // m 2 | | // e | arguments | // | | // +- - - - - - -+ // | argument0 | // +=============+ // | | // | caller | // higher | expressions | // addresses | | // Proper JS frames: // lower | Stack | // addresses | ^ | // | | | // | | // ----------- +=============+ <--- sp (stack pointer, esp) // | function | // +-------------+ // | | // | expressions | // | | // +-------------+ // a | | // c | locals | // t | | // i +- - - - - - -+ <--- // v -4 | local0 | ^ // a +-------------+ | // t -3 | code | | // i +-------------+ | // o -2 | context | | kLocal0Offset // n +-------------+ | // -1 | caller_pp | v // f +-------------+ <--- fp (frame pointer, ebp) // r 0 | caller_fp | // a +-------------+ // m 1 | caller_pc | // e +-------------+ <--- caller_sp (incl. parameters) // 2 | | // | parameters | // | | // +- - - - - - -+ <--- // -2 | parameter0 | ^ // +-------------+ | kParam0Offset // -1 | receiver | v // ----------- +=============+ <--- pp (parameter pointer, edi) // 0 | function | // +-------------+ // | | // | caller | // higher | expressions | // addresses | | // JS entry frames: When calling from C to JS, we construct two extra // frames: An entry frame (C) and a trampoline frame (JS). The // following pictures shows the two frames: // lower | Stack | // addresses | ^ | // | | | // | | // ----------- +=============+ <--- sp (stack pointer, esp) // | | // | parameters | // t | | // r +- - - - - - -+ // a | parameter0 | // m +-------------+ // p | receiver | // o +-------------+ <--- // l | function | ^ // i +-------------+ | // n -3 | code | | kLocal0Offset // e +-------------+ // -2 | NULL | context is always NULL // +-------------+ // f -1 | NULL | caller pp is always NULL for entry frames // r +-------------+ <--- fp (frame pointer, ebp) // a 0 | caller fp | // m +-------------+ // e 1 | caller pc | // +-------------+ <--- caller_sp (incl. parameters) // | 0 | // ----------- +=============+ <--- pp (parameter pointer, edi) // | 0 | // +-------------+ <--- // . ^ // . | try-handler (HandlerOffsets::kSize) // . v // +-------------+ <--- // -5 | next top pp | // +-------------+ // e -4 | next top fp | // n +-------------+ <--- // t -3 | ebx | ^ // r +-------------+ | // y -2 | esi | | callee-saved registers // +-------------+ | // -1 | edi | v // f +-------------+ <--- fp // r 0 | caller fp | // a +-------------+ pp == NULL (parameter pointer) // m 1 | caller pc | // e +-------------+ <--- caller sp // 2 | code entry | ^ // +-------------+ | // 3 | function | | // +-------------+ | arguments passed from C code // 4 | receiver | | // +-------------+ | // 5 | argc | | // +-------------+ | // 6 | argv | v // +-------------+ <--- // | | // higher | | // addresses | | } } // namespace v8::internal #endif // V8_FRAMES_IA32_H_
[ "noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9" ]
[ [ [ 1, 293 ] ] ]
f28195b4e1b4dfde2cae0a992c909b48a2c2d977
d67b01b820739ea2d63968389a83c36c4b0ff163
/UnitTests/QuizBotUnitTest/QuizBotUnitTest/QuizParticipant.cpp
eeaa43975e89fa9f23689a29b5da219b2c0e2663
[]
no_license
iamukasa/pookas
114458dc7347c66844ff8cf3023ec75ce4c486b5
bd5bf9178d2a2a37b3251a07eb3e6afa96f66c67
refs/heads/master
2021-01-13T02:08:54.947799
2009-11-04T00:52:06
2009-11-04T00:52:06
35,762,044
0
0
null
null
null
null
UTF-8
C++
false
false
1,617
cpp
#include "QuizParticipant.h" QuizParticipant::QuizParticipant(void) { score = 0; name = ""; } QuizParticipant::QuizParticipant( int session ) { sessionID = session; state = QUIZPLAYER_CLICKED; score = 0; } QuizParticipant::~QuizParticipant(void) { } void QuizParticipant::setState( PlayerState s ) { state = s; } PlayerState QuizParticipant::getState() { return state; } void QuizParticipant::setSessionID( int session ) { sessionID = session; } int QuizParticipant::getSessionID() { return sessionID; } /** \fn bool QuizParticipant::checkCollision( Vect3D objPos, int radius ) \brief Sphere collision detection between a player and an object \param objPos The position of the object \param radius The size of the object \return Whether the player collided with the object When a player is within the radius of the object, detect as collided. */ bool QuizParticipant::checkCollision( Vect3D objPos, int radius ) { //get this player's position if ( int rc = aw_avatar_location (NULL, sessionID, NULL) ) { return false; } Vect3D playerPos( (float)aw_int(AW_AVATAR_X), (float)aw_int(AW_AVATAR_Y), (float)aw_int(AW_AVATAR_Z) ); //check collision with the object pos float dist = Vect3D::Distance( playerPos, objPos ); if ( dist <= radius ) { return true; } return false; } void QuizParticipant::addScore() { score+=1; } int QuizParticipant::getScore() { return score; } void QuizParticipant::setName(std::string n) { name = n; } std::string QuizParticipant::getName() { return name; }
[ "lab4games@40cc54bc-b367-11de-8ef2-6d788aed22ac" ]
[ [ [ 1, 88 ] ] ]
a2a5af48d4a9fd60f7f022336d15aea54b1d9438
3970f1a70df104f46443480d1ba86e246d8f3b22
/imebra/src/imebra/src/colorTransform.cpp
00645891cdb3c55d2ea8b6f5559b32899a12517a
[]
no_license
zhan2016/vimrid
9f8ea8a6eb98153300e6f8c1264b2c042c23ee22
28ae31d57b77df883be3b869f6b64695df441edb
refs/heads/master
2021-01-20T16:24:36.247136
2009-07-28T18:32:31
2009-07-28T18:32:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,047
cpp
/* 0.0.46 Imebra: a C++ dicom library. Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 by Paolo Brandoli This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 for more details. You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 along with this program; If not, see http://www.gnu.org/licenses/ ------------------- If you want to use Imebra commercially then you have to buy the commercial license available at http://puntoexe.com After you buy the commercial license then you can use Imebra according to the terms described in the Imebra Commercial License Version 1. A copy of the Imebra Commercial License Version 1 is available in the documentation pages. Imebra is available at http://puntoexe.com The author can be contacted by email at [email protected] or by mail at the following address: Paolo Brandoli Preglov trg 6 1000 Ljubljana Slovenia */ /*! \file colorTransform.cpp \brief Implementation of the base class for the color transforms. */ #include "../../base/include/exception.h" #include "../include/colorTransform.h" #include "../include/colorTransformsFactory.h" #include "../include/image.h" namespace puntoexe { namespace imebra { namespace transforms { namespace colorTransforms { /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // // colorTransform // // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Transformation // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// void colorTransform::doTransform() { PUNTOEXE_FUNCTION_START(L"colorTransform::doTransform"); // Process all the input images /////////////////////////////////////////////////////////// for(int scanImages = 0; ; ++scanImages) { // Get the input image /////////////////////////////////////////////////////////// ptr<image> pInputImage=getInputImage(scanImages); // If the input image doesn't exist, then exit /////////////////////////////////////////////////////////// if(pInputImage == 0) break; // Check the input color space /////////////////////////////////////////////////////////// if(pInputImage->getColorSpace()!=getInitialColorSpace()) { PUNTOEXE_THROW(colorTransformExceptionWrongColorSpace, "the image's color space cannot be handled by the transform"); } // Get the output image /////////////////////////////////////////////////////////// ptr<image> pOutputImage=getOutputImage(scanImages); if(pOutputImage == 0) { ptr<image> tempImage(new image); pOutputImage=tempImage; declareOutputImage(scanImages, pOutputImage); } // Get the input image's attributes and the data handler /////////////////////////////////////////////////////////// imbxUint32 sizeX, sizeY; pInputImage->getSize(&sizeX, &sizeY); double sizeMmX, sizeMmY; pInputImage->getSizeMm(&sizeMmX, &sizeMmY); pOutputImage->setSizeMm(sizeMmX, sizeMmY); image::bitDepth inputDepth=pInputImage->getDepth(); image::bitDepth outputDepth=inputDepth; imbxUint32 highBit=pInputImage->getHighBit(); imbxUint32 totalPixelsNumber=sizeX*sizeY; imbxInt32 inputMinValue = 0; imbxInt32 inputMaxValue = (1L<<(highBit+1))-1L; imbxInt32 outputMinValue = inputMinValue; imbxInt32 outputMaxValue = inputMaxValue; if(inputDepth==image::depthS8 || inputDepth==image::depthS16) { inputMinValue-=1L<<highBit; inputMaxValue-=1L<<highBit; std::wstring outputColorSpace = getFinalColorSpace(); if(outputColorSpace == L"MONOCHROME2" || outputColorSpace == L"MONOCHROME1") { outputMinValue-=1L<<highBit; outputMaxValue-=1L<<highBit; } else { if(inputDepth==image::depthS8) outputDepth = image::depthU8; if(inputDepth==image::depthS16) outputDepth = image::depthU16; } } // Get the data handler for the input and the output // images /////////////////////////////////////////////////////////// imbxUint32 rowSize, channelPixelSize, channelsNumber; ptr<handlers::imageHandler> pInputDataHandler = pInputImage->getDataHandler(false, &rowSize, &channelPixelSize, &channelsNumber); if(pInputDataHandler->getSize() < totalPixelsNumber * channelsNumber) { PUNTOEXE_THROW(colorTransformExceptionWrongColorSpace, "the input image's size doesn't match the requested size"); } ptr<handlers::imageHandler> pOutputDataHandler = pOutputImage->create(sizeX, sizeY, outputDepth, getFinalColorSpace(), (imbxUint8)highBit); channelsNumber = pOutputImage->getChannelsNumber(); if(pOutputDataHandler->getSize() < totalPixelsNumber * channelsNumber) { PUNTOEXE_THROW(colorTransformExceptionWrongColorSpace, "the output image's size doesn't match the requested size"); } doColorTransform(pInputDataHandler->getMemoryBuffer(), pOutputDataHandler->getMemoryBuffer(), totalPixelsNumber, inputMinValue, inputMaxValue, outputMinValue, outputMaxValue); } PUNTOEXE_FUNCTION_END(); } /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // // registerColorTransform // // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// // // // Constructor // // /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// registerColorTransform::registerColorTransform(ptr<colorTransform> newColorTransform) { PUNTOEXE_FUNCTION_START(L"registerColorTransform::registerColorTransform"); ptr<colorTransformsFactory> pFactory(colorTransformsFactory::getColorTransformsFactory()); pFactory->registerTransform(newColorTransform); PUNTOEXE_FUNCTION_END(); } } // namespace colorTransforms } // namespace transforms } // namespace imebra } // namespace puntoexe
[ [ [ 1, 225 ] ] ]
b47f72ad719bcc5d3a76839812b62a3ea23ce67c
3276915b349aec4d26b466d48d9c8022a909ec16
/ๆ•ฐๆฎ็ป“ๆž„/ๅ›พ/ๅ…ณ้”ฎ่ทฏๅพ„.cpp
60b0939d4493d9c64d28c3e308ab5bb4cf3accc4
[]
no_license
flyskyosg/3dvc
c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82
0279b1a7ae097b9028cc7e4aa2dcb67025f096b9
refs/heads/master
2021-01-10T11:39:45.352471
2009-07-31T13:13:50
2009-07-31T13:13:50
48,670,844
0
0
null
null
null
null
GB18030
C++
false
false
6,202
cpp
#include<iostream.h> #include<iostream> // ๅ›พ็š„้‚ปๆŽฅ็Ÿฉ้˜ตๅญ˜ๅ‚จ็ป“ๆž„ #define max 50 #define mweight 50 typedef char datatype; typedef struct lnode { int number, //่Š‚็‚น่ฆๅญ˜ๅ‚จๅ…ถ็ผ–ๅท weight, //่Š‚็‚นๅญ˜ๅ‚จ่พน็š„ๆƒๅ€ผ ve, //่พน็š„ๆœ€ๆ—ฉๅ‘็”Ÿๆ—ถ้—ด vl; //่พน็š„ๆœ€ๆ™šๅ‘็”Ÿๆ—ถ้—ด struct lnode *next; //ๆŒ‡ๅ‘ไธ‹ไธ€ไธช่Š‚็‚น }lnode; typedef struct node { int number; //่Š‚็‚น่ฆๅญ˜ๅ‚จๅ…ถ็ผ–ๅท datatype inf; //่Š‚็‚นไฟกๆฏ int count, //่Š‚็‚น็š„ๅ…ฅๅบฆ๏ผ› ve, //่Š‚็‚น็š„ๆœ€ๆ—ฉๅ‘็”Ÿๆ—ถ้—ด vl; //่Š‚็‚น็š„ๆœ€ๆ™šๅ‘็”Ÿๆ—ถ้—ด lnode *first; //ๆŒ‡ๅ‘่Š‚็‚น็š„้‚ปๆŽฅ็‚น }node; typedef struct graph //ๅฎšไน‰ๅ›พ { int n,e; //ๅ›พ็š„่Š‚็‚นๆ•ฐไธŽ่พนๆ•ฐ node vex[max]; //ๅญ˜ๅ‚จ่Š‚็‚น็š„ไฟกๆฏไปฅๅŠๅบๅท,first }G; //************************ๅˆ›ๅปบๅ›พ*************************// void creatgraph(G & l) { int i=0,j=0,b=0,t=0,w=0;lnode * p; cout<<"่พ“ๅ…ฅๅ›พ็š„้กถ็‚นๆ•ฐไธŽ่พนๆ•ฐ:"; cin>>l.n>>l.e; cout<<"่ฏฅๅ›พๆœ‰"<<l.n<<"ไธช้กถ็‚น"<<l.e<<"ๆก่พน"<<endl; for(;i<l.n;i++) { cout<<"่ฏท่พ“ๅ…ฅ็ฌฌ"<<i<<"ไธช่Š‚็‚น็š„ไฟกๆฏ,่พ“ๅ…ฅๅบๅท_่Š‚็‚นๅ†…ๅฎน_่Š‚็‚นๅ…ฅๅบฆ:"; cin>>l.vex[i].number>>l.vex[i].inf>>l.vex[i].count; l.vex[i].first=NULL; l.vex[i].ve=0; //ๆŠŠๆ‰€ๆœ‰่Š‚็‚น็š„ๅˆๅง‹ๆœ€ๆ—ฉๅ‘็”Ÿๆ—ถ้—ด่ฎพ็ฝฎไธบ0๏ผŒๆ–นไพฟๅŽ่พนๆฏ”่พƒๅ–ๆœ€้•ฟ่ทฏๅพ„็ฎ—ๆณ•ๅฎž็Žฐ l.vex[i].vl=mweight; //ๆŠŠๆ‰€ๆœ‰่Š‚็‚น็š„ๅˆๅง‹ๆœ€ๆ™šๅ‘็”Ÿๆ—ถ้—ด่ฎพ็ฝฎไธบweight,fๆ–นไพฟๅŽไพฟ็š„ๆฏ”่พƒๅ–ๆœ€็Ÿญ่ทฏๅพ„็ฎ—ๆณ•็š„ๅฎž็Žฐ } for(j=0;j<l.e;j++) { cout<<"่พ“ๅ…ฅ่พน็š„ไฟกๆฏ,่ตท็‚นๅบๅท_็ปˆ็‚น_ๆƒๅ€ผ:"; cin>>b>>t>>w; if(b<0||b>=l.n) cout<<"่ตท็‚นไธๅœจๆœ็ดข่Œƒๅ›ดๅ†…."<<endl; if(t<0||t>=l.n) cout<<"็ปˆ็‚นไธๅœจๆœ็ดข่Œƒๅ›ดๅ†…."<<endl; p=(lnode *)malloc(sizeof(lnode)); p->number=t;p->weight=w; p->next=l.vex[b].first; l.vex[b].first=p; } cout<<"ๅปบ็ซ‹ๆœ‰ๅ‘้‚ปๆŽฅ่กจๅฎŒๆฏ•."<<endl; } void disp(G l) { int i=0;lnode * p; cout<<"่พ“ๅ‡บๆ ผๅผ:"<<"่Š‚็‚นๅบๅท_่Š‚็‚นไฟกๆฏ_่Š‚็‚นๅ…ฅๅบฆ+้‚ปๆŽฅ็‚นๅบๅท_่ฏฅ่พน็š„ๆƒๅ€ผ+........."<<endl; for(i;i<l.n;i++) { cout<<l.vex[i].number<<" "<<l.vex[i].inf<<" "<<l.vex[i].count<<" "; p=l.vex[i].first; while(p!=NULL) { cout<<p->number<<" "<<p->weight<<" "; p=p->next; } cout<<endl; } } //************************AOE็ฝ‘็š„ๅ…ณ้”ฎ่ทฏๅพ„***************************// void keyroad(G & l) { //*************ๅ…ˆๅค„็†่Š‚็‚น็š„ๆœ€ๆ—ฉๅ‘็”Ÿๆ—ถ้—ดไปฅๅŠๆ‰€ๅ…ณ่”็š„่พน็š„ๆœ€ๆ—ฉๅ‘็”Ÿๆ—ถ้—ด int visited[max], //็Šถๆ€ๆ•ฐ็ป„๏ผŒ่ฎฐๅฝ•ๅทฒ็ป่ฎฟ้—ฎ่ฟ‡็š„่Š‚็‚น๏ผŒ่ฎฟ้—ฎ่ฟ‡ๅŽๅ…จ้ƒจไฝ็ฝฎไธบ1; st[max], //ๅญ˜ๆ”พๅ…ฅๅบฆไธบ0็š„่Š‚็‚น็š„ๆ ˆ top=-1; for(int i=0;i<l.n;i++) //ๅˆๅง‹ๅŒ–็Šถๆ€ๆ•ฐ็ป„ visited[i]=0; for( i=0;i<l.n;i++) //ไบ‹ๅ…ˆๅฐ†ๅ…ฅๅบฆไธบ0็š„่Š‚็‚นๅ…ฅๆ ˆ๏ผŒๆ–นไพฟๅŽ่พน็š„ๅพช็Žฏ { if(l.vex[i].count==0&& visited[i]==0) { top++; st[top]=i; visited[i]=1; break; //ๅ› ไธบAOE็ฝ‘็ปœไธญๅฆ‚ๅบฆไธบ0ไปฅๅŠๅˆๅบฆไธบ0็š„็‚นๅชๆœ‰ไธ€ไธช๏ผŒๆ‰€ไปฅไธ€ๆ—ฆๆ‰พๅˆฐๅฐฑๅฏไปฅๅœๆญขๅพช็Žฏ } } l.vex[i].ve=0;l.vex[i].vl=0; //ๅŽŸ็‚น็š„ๆœ€ๆ—ฉๅ‘็”Ÿๆ—ถ้—ดๅ’Œๆœ€ๆ™šๅ‘็”Ÿๆ—ถ้—ดๅฟ…ๅฎšไธบ0 lnode * p=NULL; int n=0,j=-1, //ไฝœไธบๅญ˜ๅ‚จ่Š‚็‚น็š„ไธดๆ—ถๅ˜้‡ order[max]; //่ฎฐๅฝ•ๆ‹“ๆ‰‘ๆŽ’ๅบ็š„้กบๅบ่พ“ๅ‡บๅบๅˆ—.ๆ–นไพฟๅŽ่พน็š„ๆœ€ๆ™šๅ‘็”Ÿๆ—ถ้—ด็š„ๅค„็†๏ผŒๅ…จๅฑ€ๆ•ฐ็ป„ 000000000000 while(top>=0) //่ฟ™ๅฑ‚ๅพช็ŽฏๆŽงๅˆถๅฝ“็ซ™็ฉบ็š„ๆ—ถๅ€™็ปˆๆญขๅคงๅพช็Žฏ๏ผŒ่ฏดๆ˜Žๆ‰€ๆœ‰็š„ๅ…ƒ็ด ๅค„็†ๅฎŒๆฏ• { while(top>=0) //ๆŽงๅˆถๅฐ†ๆ ˆๅ†…็š„ๅ…ฅๅบฆไธบ้›ถ็š„่Š‚็‚น่พ“ๅ‡บๅนถไธ”ๅฐ†ๅ…ฅๅบฆไธบ้›ถ็š„่Š‚็‚น็š„ๆ‰€ๆœ‰็š„็›ดๆŽฅๅŽๅณ่Š‚็‚น็š„ๅ…ฅๅบฆๅ‡ไธ€ { n=st[top]; j++; order[j]=n; //่ฎฐๅฝ•ๆ‹“ๆ‰‘ๆŽ’ๅบ็š„้กบๅบ่พ“ๅ‡บๅบๅˆ— p=l.vex[n].first; visited[n]=1; //ๆ ‡่ฎฐๅทฒ็ป่ฎฟ้—ฎ่ฟ‡็š„่Š‚็‚น while(p!=NULL) //ๅฐ†่ฏฅ่Š‚็‚น็š„ๆ‰€ๆœ‰็š„้‚ปๆŽฅ็‚น็š„ๅ…ฅๅบฆๅ‡1, { l.vex[p->number].count--; if(l.vex[n].ve+p->weight>l.vex[p->number].ve) l.vex[p->number].ve=l.vex[n].ve+p->weight; //ๅ…ณ้”ฎ๏ผŒไพๆฌกๆ”นๅ†™่ฏฅ่Š‚็‚น็š„ๆœ€ๆ—ฉๅ‘็”Ÿๆ—ถ้—ด๏ผŒๆœ€ๅŽไปŽๆ‰€ๆœ‰้‚ปๆŽฅ่ทฏๅพ„ไธญๅ–็š„ๆœ€ๅคง่ทฏๅพ„ p=p->next; } top--; //ๅฝ“top<0็š„ๆ—ถๅ€™๏ผŒๅ‡บๆ ˆๅฎŒๆฏ• } for( i=0;i<l.n;i++) //ๅ†ๆฌกๆ‰ซๆๅ…ฅๅบฆไธบ0็š„่Š‚็‚น;ๅนถไธ”ๅ…ฅๆ ˆ { if(l.vex[i].count==0&&visited[i]==0) { top++; st[top]=i; } } } //************ไธ‹้ขๅค„็†่Š‚็‚น็š„ๆœ€ๆ™šๅ‘็”Ÿๆ—ถ้—ด๏ผŒ ๅˆฉ็”จๆ‹“ๆ‰‘ๆŽ’ๅบ็š„้กบๅบ่พ“ๅ‡บ็š„็š„้€†ๅบไฝœไธบๆกไปถ l.vex[order[j]].vl=l.vex[order[j]].ve; //ๆฑ‡็‚น็š„ๆœ€ๆ—ฉๅ‘็”Ÿๆ—ถ้—ดๅ’Œๆœ€ๆ™šๅ‘็”Ÿๆ—ถ้—ด็›ธๅŒ int m=0; //ไฝœไธบๅญ˜ๅ‚จ่Š‚็‚นๅบๅท็š„ไธดๆ—ถๅ˜้‡ for(j;j>=0;j--) { m=order[j]; for(i=0;i<l.n;i++) { p=l.vex[i].first; while(p!=NULL) { if(p->number==m&&l.vex[m].vl-p->weight<l.vex[i].vl) //ๅ…ณ้”ฎ๏ผŒ่ฟ™้‡Œ็š„ๆกไปถๅ†ณๅฎšไบ†ไปŽ่Š‚็‚น็š„้‚ปๆŽฅ็‚น่พน้‡้€‰ๅ‡บๆœ€ๅฐ่ทฏๅพ„๏ผŒไพๆฌกๆ”นๅ†™ไธดๆŽฅ็‚น็š„ๆœ€ๅฐ่ทฏๅพ„๏ผŒๅพช็ŽฏๅฎŒๆฏ•ๅŽๆœ€ๅŽไปŽๆ‰€ๆœ‰็š„้‚ปๆŽฅ่ทฏๅพ„ไธญๅ–ๅพ—ๅฐ่ทฏๅพ„ { l.vex[i].vl=l.vex[m].vl-p->weight; } p=p->next; } } } //******************ไธ‹่พนๅค„็†่พน็š„ๆœ€ๆ—ฉไปฅๅŠๆœ€ๆ™šๅ‘็”Ÿๆ—ถ้—ด**************// for(i=0;i<l.n;i++) { p=l.vex[i].first; while(p!=NULL) { p->ve=l.vex[i].ve; p->vl=l.vex[p->number].vl-p->weight; if(p->ve==p->vl) cout<<i<<"->"<<p->number<<"ๅ…ณ้”ฎๆดปๅŠจ"<<endl; p=p->next; } } } //******************ไธปๅ‡ฝๆ•ฐ******************// void main() { G l; cout<<"ๅˆ›ๅปบๅ›พ:"<<endl; creatgraph(l); cout<<"ๅˆ›ๅปบๅฅฝ็š„ๅ›พ:"<<endl; disp(l); cout<<"AOEๅ…ณ้”ฎ่ทฏๅพ„:"<<endl; keyroad(l); cout<<endl; }
[ [ [ 1, 204 ] ] ]
5b2422673104f6d796405462ba433c76b8f7344a
5210c96be32e904a51a0f32019d6be4abdb62a6d
/Particle.h
10f9cc430d83fdd859f006a035c6a4e7f993382d
[]
no_license
Russel-Root/knot-trying-FTL
699cec27fcf3f2b766a4beef6a58176c3cbab33e
2c1a7992855927689ad1570dd7c5998a73728504
refs/heads/master
2021-01-15T13:18:35.661929
2011-04-02T07:51:51
2011-04-02T07:51:51
1,554,271
1
0
null
null
null
null
UTF-8
C++
false
false
784
h
#ifndef __Particle_h__ #define __Particle_h__ #include "Vector3f.h" class Particle{ public: Particle(){ gravity3f = Vector3f(0.0, -1.96, 0.0); // mass = 0.2kg, amplitude:gravity = 0.2 * 9.8 = 1.96 N, and orientation/direction } // return the resultant force Vector3f Addgravity(Vector3f force){ return Vector3f( force + gravity3f ); } Vector3f CalculateForce(Particle* another, float gaugeDistance, float dampingCoefficient){ Vector3f distance3f = this->position - another->position; return Vector3f( distance3f * (gaugeDistance - distance3f.getLength()) * dampingCoefficient ); } public: int index; // index in the particle cluster Vector3f gravity3f; // for the gravity Vector3f position; // (x, y, z) }; #endif // __Particle_h__
[ [ [ 1, 27 ] ] ]
cdc41d75ee75dd0005f2230e219da1cd2cb3f74f
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/extras/collision/collision_dll/vmap/IVMapManager.h
a4affb4b354a82b8cc2b3b5a136ca00e93a9c255
[]
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
3,232
h
/* * Copyright (C) 2005,2006,2007 MaNGOS <http://www.mangosproject.org/> * Copyright (C) 2007-2008 Ascent Team <http://www.ascentemu.com/> * * 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 _IVMAPMANAGER_H #define _IVMAPMANAGER_H #include<string> class LocationVector; //=========================================================== /** This is the minimum interface to the VMapMamager. */ namespace VMAP { enum VMAP_LOAD_RESULT { VMAP_LOAD_RESULT_ERROR, VMAP_LOAD_RESULT_OK, VMAP_LOAD_RESULT_IGNORED, }; #define VMAP_INVALID_HEIGHT -100000.0f //=========================================================== class IVMapManager { public: IVMapManager() {} virtual ~IVMapManager(void) {} virtual int loadMap(const char* pBasePath, unsigned int pMapId, int x, int y) = 0; virtual void unloadMap(unsigned int pMapId, int x, int y) = 0; virtual void unloadMap(unsigned int pMapId) = 0; // LOS virtual bool isInLineOfSight(unsigned int pMapId, float x1, float y1, float z1, float x2, float y2, float z2) = 0; virtual bool isInLineOfSight(unsigned int pMapId, LocationVector & v1, LocationVector & v2) = 0; // Height virtual float getHeight(unsigned int pMapId, float x, float y, float z) = 0; virtual float getHeight(unsigned int mapid, LocationVector & vec) = 0; // Indoors virtual bool isInDoors(unsigned int mapid, float x, float y, float z) = 0; virtual bool isInDoors(unsigned int mapid, LocationVector & vec) = 0; // Outdoors virtual bool isOutDoors(unsigned int mapid, float x, float y, float z) = 0; virtual bool isOutDoors(unsigned int mapid, LocationVector & vec) = 0; /** test if we hit an object. return true if we hit one. rx,ry,rz will hold the hit position or the dest position, if no intersection was found return a position, that is pReduceDist closer to the origin */ // Closest Point virtual bool getObjectHitPos(unsigned int pMapId, float x1, float y1, float z1, float x2, float y2, float z2, float& rx, float &ry, float& rz, float pModifyDist) = 0; virtual bool getObjectHitPos(unsigned int pMapId, LocationVector & v1, LocationVector & v2, LocationVector & vout, float pModifyDist) = 0; virtual std::string getDirFileName(unsigned int pMapId, int x, int y) const =0; }; } #endif
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 86 ] ] ]
edb9be3752a7b43dcab47d7b623bbbabf7d290b9
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/HovercraftUniverse/HUDedicatedServer.cpp
81e740e3e4b8bccfebace0cdf8bf9a7c780d5200
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
2,180
cpp
#include "HUDedicatedServer.h" #include <OgreRoot.h> #include <OgreConfigFile.h> #include <OgreMaterialManager.h> #include <windows.h> #include <math.h> namespace HovUni { HUDedicatedServer::HUDedicatedServer(const std::string& configINI) : DedicatedServer(configINI), mServer(0) { } HUDedicatedServer::~HUDedicatedServer() { if (mServer) { mServer->stop(); } delete mServer; mServer = 0; } void HUDedicatedServer::run(bool standalone) { Ogre::Root* ogreRoot = Ogre::Root::getSingletonPtr(); if (ogreRoot == 0) { ogreRoot = new Ogre::Root(getConfig()->getValue<std::string>("Ogre", "Plugins", "plugins.cfg"), getConfig()->getValue<std::string>("Ogre", "ConfigFile", "ogre.cfg"), getConfig()->getValue<std::string>("Ogre", "LogFile", "Server.log")); Ogre::ConfigFile cf; cf.load(mConfig->getValue<std::string>("Ogre", "Resources", "resources.cfg").c_str()); // Iterate over config Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); while (seci.hasMoreElements()) { // Read property Ogre::String secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap * settings = seci.getNext(); // For all settings of that property, add them for (Ogre::ConfigFile::SettingsMultiMap::iterator it = settings->begin(); it != settings->end(); it++) { Ogre::String typeName = it->first; Ogre::String archName = it->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName); } } //make sure it doesn't parse materials Ogre::ResourceGroupManager::getSingleton()._unregisterScriptLoader(Ogre::MaterialManager::getSingletonPtr()); } //Save the INI here to make it complete getConfig()->saveFile(); mServer = new HUServer(); mServer->start(); if (standalone) { mServer->join(); delete mServer; mServer = 0; delete ogreRoot; ogreRoot = 0; } } void HUDedicatedServer::init() { DedicatedServer::init(); } void HUDedicatedServer::stop() { if (mServer != 0) { if (mServer->isRunning()) { mServer->stop(); } } } }
[ "dirk.delahaye@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c", "nick.defrangh@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c" ]
[ [ [ 1, 10 ], [ 20, 21 ], [ 23, 50 ], [ 61, 65 ], [ 74, 74 ] ], [ [ 11, 19 ], [ 22, 22 ], [ 51, 60 ], [ 66, 73 ] ] ]
8c13933296ab07433b8173256fe0ecd3e224e7cb
26b6f15c144c2f7a26ab415c3997597fa98ba30a
/sdp/inc/PhoneField.h
8122e0dec56111ef9212972b73bc6d578254b15a
[]
no_license
wangscript007/rtspsdk
fb0b52e63ad1671e8b2ded1d8f10ef6c3c63fddf
f5b095f0491e5823f50a83352945acb88f0b8aa0
refs/heads/master
2022-03-09T09:25:23.988183
2008-12-27T17:23:31
2008-12-27T17:23:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,901
h
/***************************************************************************** // SDP Parser Classes // // Phone Field Class // // description: // represents SDP description phone field // // revision of last commit: // $Rev$ // author of last commit: // $Author$ // date of last commit: // $Date$ // // created by Argenet {[email protected]} // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // ******************************************************************************/ #ifndef __PHONE_FIELD__H__ #define __PHONE_FIELD__H__ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Includes //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include "sdp_parser.h" #include "common.h" #include "Field.h" namespace SDP { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // PhoneField class //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class SDP_PARSER_API PhoneField : public Field /// A Phone represents a p= field contained within a SessionDescription. { public: PhoneField(); /// Creates an empty PhoneField. PhoneField(const std::string & value); /// Creates a new PhoneField according to the specified value string. PhoneField(const PhoneField & phoneField); /// Creates a copy of specified PhoneField object. PhoneField & operator=(const PhoneField & phoneField); /// Copies the specified PhoneField object. }; } // namespace SDP #endif // __PHONE_FIELD__H__
[ [ [ 1, 79 ] ], [ [ 80, 81 ] ] ]
40e72305525566d3ab34f11f5da462086c026a45
1e5a2230acf1c2edfe8b9d226100438f9374e98a
/src/tabimswitch/TabImSwitchApp.h
2552d373b186ce0f01921c0546fb0fc9975f4dcd
[]
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
788
h
#ifndef __TABIMSWITCH_APP_H__ #define __TABIMSWITCH_APP_H__ #include <memory> #include "tabimswitch.h" #define TABIMSWITCH_APP_CONTRACTID "@tabimswitch.googlecode.com/application;1" #define TABIMSWITCH_APP_CLASSNAME "TabImSwitchApp" /* 1efb2b80-1908-4dde-a9bd-ccadef225069 */ #define TABIMSWITCH_APP_CID { 0x1efb2b80, 0x1908, 0x4dde, \ {0xa9, 0xbd, 0xcc, 0xad, 0xef, 0x22, 0x50, 0x69} } class SystemInputMethod; class CTabImSwitchApp : public ITabImSwitchApp { public: NS_DECL_ISUPPORTS NS_DECL_ITABIMSWITCHAPP CTabImSwitchApp(); private: ~CTabImSwitchApp(); CTabImSwitchApp& operator=(CTabImSwitchApp const&); private: void setInputMethodByCurrent(IInputMethod* im); SystemInputMethod& m_sysIME; }; #endif // __TABIMSWITCH_APP_H__
[ "ftofficer.zhangc@237747d1-5336-0410-8d3f-2982d197fc3e" ]
[ [ [ 1, 32 ] ] ]
d0d77d5502069774187342e5fd7dd997106a53fe
ef25bd96604141839b178a2db2c008c7da20c535
/src/src/Engine/Game/Level.cpp
5920df8387b19a35441354760a941de207e396bb
[]
no_license
OtterOrder/crock-rising
fddd471971477c397e783dc6dd1a81efb5dc852c
543dc542bb313e1f5e34866bd58985775acf375a
refs/heads/master
2020-12-24T14:57:06.743092
2009-07-15T17:15:24
2009-07-15T17:15:24
32,115,272
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,156
cpp
#include "Level.h" //****************************************************************** /*********************************************************** * Constructeur. * @param[in] levelID : ID (CRC32) du level **********************************************************/ Level::Level( crc32 levelID ) { m_LevelID = levelID; } /*********************************************************** * Destructeur. **********************************************************/ Level::~Level( void ) { } /*********************************************************** * Initialisation du niveau. **********************************************************/ void Level::Init( void ) { } /*********************************************************** * Update, mรฉthode appellรฉe ร  chaque tour moteur. **********************************************************/ void Level::Update( void ) { } /*********************************************************** * Donne l'ID du niveau. * @return l'ID du niveau **********************************************************/ crc32 Level::GetLevelID( void ) const { return m_LevelID; }
[ "mathieu.chabanon@7c6770cc-a6a4-11dd-91bf-632da8b6e10b" ]
[ [ [ 1, 42 ] ] ]
7edb8646ec56467b914e1ba952d0caae56b02f75
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Scada/ScdOPC/ServerDLL/OPCGroup.cpp
128625230bca170b52cdf4bb0d5ec7e55e2bfb8f
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,073
cpp
//************************************************************************** // // Copyright (c) FactorySoft, INC. 1996-1998, All Rights Reserved // //************************************************************************** // // Filename : OPCGroup.cpp // $Author : Jim Hansen // // Subsystem : FS OPC Server DLL // Version : 2.04 // // Description: The OPC Group object implementation. // // //************************************************************************** #include "stdafx.h" #include "OPCServer.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern COPCCallback* pCallback; //******************************************************************* // class COPCItem //******************************************************************* CFSItem::CFSItem(CTag* pTarget) : pTag( pTarget ) { pTag->AddRef(); } CFSItem::~CFSItem() { pTag->Release(); } //******************************************************************* // class OPCGroup //******************************************************************* // Initialize does the real work OPCGroup::OPCGroup() { } //******************************************************************* OPCGroup::~OPCGroup() { Shutdown(); EnterCriticalSection( &m_cs ); // Also delete any removed items still around DWORD count = m_removedItems.GetCount(); int index=0; if( count > 0 ) { CTag** ppTags = (CTag**)_alloca(count*sizeof(CTag*)); while( !m_removedItems.IsEmpty() ) { CFSItem* pItem = (CFSItem*)m_removedItems.RemoveHead(); m_itemMap.RemoveKey( (LPVOID)pItem ); CTag* pTag = pItem->pTag; delete pItem; // decrement tag's reference count if( !pTag->InUse() ) ppTags[index++] = pTag; } pCallback->Remove(index, ppTags); } // remove all items CSLock wait( &m_cs ); index=0; if( m_itemMap.GetCount() > 0 ) { CTag** ppTags = (CTag**)_alloca(m_itemMap.GetCount()*sizeof(CTag*)); CFSItem* pItem = NULL; LPVOID key = 0; POSITION pos = m_itemMap.GetStartPosition(); while( pos ) { m_itemMap.GetNextAssoc( pos, key, (COPCItem*&)pItem ); CTag* pTag = pItem->pTag; delete pItem; // decrement tag's reference count if( !pTag->InUse() ) ppTags[index++] = pTag; } pCallback->Remove(index, ppTags); m_itemMap.RemoveAll(); } LeaveCriticalSection( &m_cs ); } //******************************************************************* // OPCGroup overrides //******************************************************************* void OPCGroup::DoSetUpdateRate( DWORD newUpdateRate ) { if( !running ) return; ASSERT( pCallback ); m_updateRate = pCallback->SetUpdateRate(newUpdateRate); } //******************************************************************* // DoRead performs the synchronous read // Values are put into the OPCITEMSTATE structures, // not the COPCItems themselves // (there is no interaction with subscriptions) //******************************************************************* HRESULT OPCGroup::DoRead( OPCDATASOURCE dwSource, DWORD dwNumItems, COPCItem ** ppItems, OPCITEMSTATE * pItemValues, HRESULT * pErrors) { if( !running ) return E_FAIL; ASSERT( pCallback ); HRESULT hr = S_OK; // Base just initializes the arrays OPCGroupBase::DoRead(dwSource,dwNumItems,ppItems,pItemValues,pErrors); if( dwSource == OPC_DS_CACHE ) // just read from the tags { CSLock wait( &m_cs ); CSLock wait2( &pCallback->m_CS ); // protect data // for each item requested, read its value from the tag for( DWORD index=0; index<dwNumItems; index++ ) { if( pErrors[index] == S_OK ) { CFSItem* pItem = (CFSItem*)ppItems[index]; pItemValues[index].hClient = pItem->clientHandle; pItemValues[index].ftTimeStamp = pItem->pTag->m_timestamp; if( m_active && pItem->active ) pItemValues[index].wQuality = pItem->pTag->m_quality; else pItemValues[index].wQuality = OPC_QUALITY_BAD | OPC_QUALITY_OUT_OF_SERVICE; pItemValues[index].wReserved = 0; VariantCopy( &pItemValues[index].vDataValue, &pItem->pTag->m_value ); } else { hr = S_FALSE; } } } else // OPC_DS_DEVICE { // get the tag pointers EnterCriticalSection( &m_cs ); CTag** ppTags = (CTag**)_alloca(dwNumItems*sizeof(CTag*)); for( DWORD index=0; index<dwNumItems; index++ ) { CFSItem* pItem = (CFSItem*)ppItems[index]; pItemValues[index].hClient = pItem->clientHandle; pItemValues[index].wReserved = 0; ppTags[index] = pItem->pTag; } LeaveCriticalSection( &m_cs ); // Read the tags pCallback->Read(dwNumItems, ppTags, pErrors); // for each item requested, return its data CSLock wait( &m_cs ); CSLock wait2( &pCallback->m_CS ); // protect data for( index=0; index<dwNumItems; index++ ) { if( pErrors[index] == S_OK ) { CFSItem* pItem = (CFSItem*)ppItems[index]; // also update the item (added 2.02) pItem->value = pItem->pTag->m_value; pItem->quality = pItem->pTag->m_quality; pItem->timestamp = pItem->pTag->m_timestamp; pItemValues[index].ftTimeStamp = ppTags[index]->m_timestamp; pItemValues[index].wQuality = ppTags[index]->m_quality; VariantCopy( &pItemValues[index].vDataValue, &ppTags[index]->m_value ); } else { hr = S_FALSE; } } } return hr; } //******************************************************************* HRESULT OPCGroup::DoWrite( DWORD dwNumItems, COPCItem ** ppItems, VARIANT * pItemValues, HRESULT * pErrors) { if( !running ) return E_FAIL; ASSERT( pCallback ); HRESULT hr = S_OK; EnterCriticalSection( &m_cs ); // get the tag pointers CTag** ppTags = (CTag**)_alloca(dwNumItems*sizeof(CTag*)); for( DWORD index=0; index<dwNumItems; index++ ) { if(pErrors[index] == S_OK) { CFSItem* pItem = (CFSItem*)ppItems[index]; ppTags[index] = pItem->pTag; } else ppTags[index] = NULL; } LeaveCriticalSection( &m_cs ); // Write the tags hr = pCallback->Write(dwNumItems, ppTags, pItemValues, pErrors); return hr; } //******************************************************************* BOOL OPCGroup::DoUpdateGroup() { if( !running ) return E_FAIL; ASSERT( pCallback ); // delete the removed items now that it is safe EnterCriticalSection( &m_cs ); DWORD count = m_removedItems.GetCount(); int index=0; if( count > 0 ) { CTag** ppTags = (CTag**)_alloca(count*sizeof(CTag*)); while( !m_removedItems.IsEmpty() ) { CFSItem* pItem = (CFSItem*)m_removedItems.RemoveHead(); m_itemMap.RemoveKey( (LPVOID)pItem ); CTag* pTag = pItem->pTag; delete pItem; // decrement tag's reference count if( !pTag->InUse() ) ppTags[index++] = pTag; } if( index > 0 ) pCallback->Remove(index, ppTags); } BOOL changed = FALSE; if( m_itemMap.GetCount() == 0 ) { LeaveCriticalSection( &m_cs ); return changed; } // get the tag pointers in the group HRESULT* pErrors = (HRESULT*)_alloca(m_itemMap.GetCount()*sizeof(HRESULT)); memset( pErrors, 0, m_itemMap.GetCount()*sizeof(HRESULT)); CTag** ppTags = (CTag**)_alloca(m_itemMap.GetCount()*sizeof(CTag*)); index = 0; CFSItem* pItem = NULL; LPVOID key = 0; POSITION pos = m_itemMap.GetStartPosition(); while( pos ) { m_itemMap.GetNextAssoc( pos, key, (COPCItem*&)pItem ); ASSERT( pItem->pTag ); if( pItem->active ) { ppTags[index] = pItem->pTag; index++; } } LeaveCriticalSection( &m_cs ); // Scan the tags pCallback->Scan(index, ppTags, pErrors); // update items from tags CSLock wait( &m_cs ); pos = m_itemMap.GetStartPosition(); while( pos ) { m_itemMap.GetNextAssoc( pos, key, (COPCItem*&)pItem ); CSLock wait( &pCallback->m_CS ); // protect data if( !pItem->active ) continue; // skip the change detection code // mark changed values to be sent to clients if( (pItem->value == (LPCVARIANT)&pItem->pTag->m_value ) ) ; // only "operator==" works, not "operator !=" else // the values are different { double high, low; if( m_deadBand == 0.0 ) { pItem->value = pItem->pTag->m_value; pItem->changed = changed = TRUE; } // deadband only applies to "analog" types else if( pCallback->GetTagLimits( pItem->pTag, &high, &low ) ) { double engRange = high - low; double current, last; BOOL incompatible = FALSE; switch( pItem->pTag->m_value.vt ) { case VT_UI1: current = pItem->pTag->m_value.iVal; break; case VT_I2: current = pItem->pTag->m_value.iVal; break; case VT_I4: current = pItem->pTag->m_value.lVal; break; case VT_R4: current = pItem->pTag->m_value.fltVal; break; case VT_R8: current = pItem->pTag->m_value.dblVal; break; default: incompatible=TRUE; }; switch( pItem->value.vt ) { case VT_UI1: last = pItem->value.iVal; break; case VT_I2: last = pItem->value.iVal; break; case VT_I4: last = pItem->value.lVal; break; case VT_R4: last = pItem->value.fltVal; break; case VT_R8: last = pItem->value.dblVal; break; default: incompatible=TRUE; }; if( incompatible ) // do the assign { pItem->value = pItem->pTag->m_value; pItem->changed = changed = TRUE; } // Now check if the deadband is exceeded else if( fabs(current - last) > m_deadBand*engRange/100.0 ) // deadband is in % { pItem->value = pItem->pTag->m_value; pItem->changed = changed = TRUE; } } else // deadband doesn't apply to other types { pItem->value = pItem->pTag->m_value; pItem->changed = changed = TRUE; } } if( pItem->quality != pItem->pTag->m_quality ) { pItem->quality = pItem->pTag->m_quality; pItem->changed = changed = TRUE; } if( pItem->changed ) pItem->timestamp = pItem->pTag->m_timestamp; } return changed; } //****************************************************************** void OPCGroup::ClearRemovedItems() { // delete the removed items now that it is safe EnterCriticalSection( &m_cs ); DWORD count = m_removedItems.GetCount(); int index=0; if( count > 0 ) { CTag** ppTags = (CTag**)_alloca(count*sizeof(CTag*)); while( !m_removedItems.IsEmpty() ) { CFSItem* pItem = (CFSItem*)m_removedItems.RemoveHead(); m_itemMap.RemoveKey( (LPVOID)pItem ); CTag* pTag = pItem->pTag; delete pItem; // decrement tag's reference count if( !pTag->InUse() ) ppTags[index++] = pTag; } if( index > 0 ) pCallback->Remove(index, ppTags); } LeaveCriticalSection( &m_cs ); } //******************************************************************* HRESULT OPCGroup::DoAddItems( DWORD dwNumItems, OPCITEMDEF * pItemArray, OPCITEMRESULT * pAddResults, HRESULT * pErrors) { if( !running ) return E_FAIL; ASSERT( pCallback ); HRESULT hr = S_OK; CSLock wait( &m_cs ); for(DWORD i=0; i<dwNumItems; i++ ) { // search for this tag CString itemName( pItemArray[i].szItemID ); CString accessPath( pItemArray[i].szAccessPath ); CTag* pTag = pCallback->AddTag( itemName, accessPath, pItemArray[i].vtRequestedDataType ); if( pTag == NULL ) { pErrors[i] = OPC_E_INVALIDITEMID; hr = S_FALSE; } else { // verify valid requested data type if(pItemArray[i].vtRequestedDataType == VT_I1 || pItemArray[i].vtRequestedDataType == VT_I2 || pItemArray[i].vtRequestedDataType == VT_I4 || pItemArray[i].vtRequestedDataType == VT_UI1 || pItemArray[i].vtRequestedDataType == VT_UI2 || pItemArray[i].vtRequestedDataType == VT_UI4 || pItemArray[i].vtRequestedDataType == VT_R4 || pItemArray[i].vtRequestedDataType == VT_R8 || pItemArray[i].vtRequestedDataType == VT_CY || pItemArray[i].vtRequestedDataType == VT_DATE || pItemArray[i].vtRequestedDataType == VT_BSTR || pItemArray[i].vtRequestedDataType == VT_BOOL || pItemArray[i].vtRequestedDataType == VT_EMPTY ) { // Create the OPC item CFSItem* pItem = new CFSItem( pTag ); if( pItem ) { pErrors[i] = S_OK; pItem->changed = TRUE; pItem->active = pItemArray[i].bActive; pItem->clientHandle = pItemArray[i].hClient; pItem->clientType = pItemArray[i].vtRequestedDataType; if( pItem->clientType == VT_EMPTY ) pItem->clientType = pItem->pTag->m_nativeType; pAddResults[i].hServer = (OPCHANDLE)pItem; pAddResults[i].vtCanonicalDataType = pItem->pTag->m_nativeType; pAddResults[i].wReserved = 0; pAddResults[i].dwAccessRights = pItem->accessRights = pItem->pTag->m_accessRights; pAddResults[i].dwBlobSize = 0; pAddResults[i].pBlob = NULL; m_itemMap.SetAt( (LPVOID)pItem, pItem ); } else { pErrors[i] = E_OUTOFMEMORY; hr = S_FALSE; } } else { pErrors[i] = OPC_E_BADTYPE; hr = S_FALSE; } } } return hr; } //******************************************************************* HRESULT OPCGroup::DoValidateItems( DWORD dwNumItems, OPCITEMDEF * pItemArray, OPCITEMRESULT * pValidationResults, HRESULT * pErrors) { if( !running ) return E_FAIL; ASSERT( pCallback ); HRESULT hr = S_OK; CSLock wait( &m_cs ); for(DWORD i=0; i<dwNumItems; i++ ) { // search for this tag CString itemName( pItemArray[i].szItemID ); CString accessPath( pItemArray[i].szAccessPath ); CTag tag; pErrors[i] = pCallback->ValidateTag( &tag, itemName, accessPath, pItemArray[i].vtRequestedDataType ); if( FAILED(pErrors[i]) ) { hr = S_FALSE; } else { pValidationResults[i].hServer = NULL; pValidationResults[i].vtCanonicalDataType = tag.m_nativeType; pValidationResults[i].wReserved = 0; pValidationResults[i].dwAccessRights = tag.m_accessRights; pValidationResults[i].dwBlobSize = 0; pValidationResults[i].pBlob = NULL; } } return hr; } //******************************************************************* HRESULT OPCGroup::DoRemoveItems( DWORD dwNumItems, COPCItem ** ppItems, HRESULT * pErrors) { if( !running ) return E_FAIL; ASSERT( pCallback ); HRESULT hr = S_OK; CSLock wait( &m_cs ); for( DWORD index=0; index<dwNumItems; index++ ) { if( pErrors[index] == S_OK ) { CFSItem* pItem = (CFSItem*)ppItems[index]; // remove from map of all items m_removedItems.AddHead( pItem ); } else hr = S_FALSE; } return hr; } /* Don't need to override these //******************************************************************* HRESULT OPCGroup::DoSetActiveState( DWORD dwNumItems, COPCItem ** ppItems, BOOL bActive, HRESULT * pErrors) { if( !running ) return E_FAIL; HRESULT hr = S_OK; CSLock wait( &cs ); for( DWORD index=0; index<dwNumItems; index++ ) { if( pErrors[index] == S_OK ) { COPCItem* pItem = ppItems[index]; pItem->active = bActive; } else hr = S_FALSE; } return hr; } //******************************************************************* HRESULT OPCGroup::DoSetClientHandles( DWORD dwNumItems, COPCItem ** ppItems, OPCHANDLE * phClient, HRESULT * pErrors) { if( !running ) return E_FAIL; HRESULT hr = S_OK; CSLock wait( &cs ); for( DWORD index=0; index<dwNumItems; index++ ) { if( pErrors[index] == S_OK ) { COPCItem* pItem = ppItems[index]; pItem->clientHandle = phClient[index]; } else hr = S_FALSE; } return hr; } */ //******************************************************************* HRESULT OPCGroup::DoSetDatatypes( DWORD dwNumItems, COPCItem ** ppItems, VARTYPE * pRequestedDatatypes, HRESULT * pErrors) { if( !running ) return E_FAIL; HRESULT hr = S_OK; CSLock wait( &m_cs ); for( DWORD index=0; index<dwNumItems; index++ ) { if( pErrors[index] == S_OK ) { CFSItem* pItem = (CFSItem*)ppItems[index]; pItem->clientType = pRequestedDatatypes[index]; if( pItem->clientType == VT_EMPTY ) // if none, use Double pItem->clientType = pItem->pTag->m_nativeType; } else hr = S_FALSE; } return hr; } IUnknown* OPCGroup::DoCreateEnumerator() { if( !running ) return NULL; CComEnumItemAttributes* pEnumerator = new CComEnumItemAttributes; if( pEnumerator ) pEnumerator->Initialize(this); return pEnumerator; } //******************************************************************* HRESULT OPCGroup::DoCloneGroupItems(OPCGroupBase* pCloneGroup) { HRESULT hr = S_OK; CFSItem* pItem = NULL; LPVOID key = 0; POSITION position = m_itemMap.GetStartPosition(); while( position ) { m_itemMap.GetNextAssoc( position, key, (COPCItem*&)pItem ); if( pItem ) { // Create the OPC item CFSItem* pNewItem = new CFSItem( pItem->pTag ); if( pNewItem ) { pNewItem->changed = TRUE; pNewItem->active = pItem->active; pNewItem->clientHandle = pItem->clientHandle; pNewItem->clientType = pItem->clientType; ((OPCGroup*)pCloneGroup)->m_itemMap.SetAt( (LPVOID)pNewItem, pNewItem ); } } else hr = E_OUTOFMEMORY; } return hr; } //******************************************************************* // CEnumItemAttributes implementation //******************************************************************* CEnumItemAttributes::CEnumItemAttributes() { m_pos = NULL; m_parent = NULL; } CEnumItemAttributes::~CEnumItemAttributes() { m_pos = NULL; } //******************************************************************* void CEnumItemAttributes::Initialize(OPCGroup* pGroup) { m_parent = pGroup; Reset(); } //******************************************************************* STDMETHODIMP CEnumItemAttributes::Next( ULONG celt, OPCITEMATTRIBUTES ** ppItemArray, ULONG * pceltFetched ) { USES_CONVERSION; if( !running ) return E_FAIL; ASSERT( pCallback ); // All args should be valid if( ppItemArray==NULL ) return E_INVALIDARG; *ppItemArray = NULL; OPCITEMATTRIBUTES * pItemArray = (OPCITEMATTRIBUTES*)CoTaskMemAlloc(celt*sizeof(OPCITEMATTRIBUTES)); if( pItemArray == NULL ) return E_OUTOFMEMORY; for( ULONG index = 0; index < celt && m_pos; index++ ) { CFSItem* pItem = NULL; LPVOID key = 0; m_parent->m_itemMap.GetNextAssoc( m_pos, key, (COPCItem*&)pItem ); // Get the access path (optional, may be empty); CString accessPath( pCallback->GetTagAccessPath( pItem->pTag ) ); pItemArray[index].szAccessPath = (LPWSTR)CoTaskMemAlloc(2+accessPath.GetLength()*2); if( pItemArray[index].szAccessPath == NULL ) { CoTaskMemFree( pItemArray ); return E_OUTOFMEMORY; } wcscpy( pItemArray[index].szAccessPath, T2OLE(accessPath.GetBuffer(0)) ); // Get the item name CString itemID( pCallback->GetTagName( pItem->pTag ) ); pItemArray[index].szItemID = (LPWSTR)CoTaskMemAlloc(2+itemID.GetLength()*2); if( pItemArray[index].szItemID == NULL ) { CoTaskMemFree( pItemArray[index].szAccessPath ); CoTaskMemFree( pItemArray ); return E_OUTOFMEMORY; } wcscpy( pItemArray[index].szItemID, T2OLE(itemID.GetBuffer(0)) ); pItemArray[index].bActive = pItem->active; pItemArray[index].hClient = pItem->clientHandle; pItemArray[index].hServer = (OPCHANDLE)pItem; pItemArray[index].dwAccessRights = pItem->pTag->m_accessRights; pItemArray[index].dwBlobSize = 0; pItemArray[index].pBlob = NULL; pItemArray[index].vtRequestedDataType = pItem->clientType; pItemArray[index].vtCanonicalDataType = pItem->pTag->m_nativeType; pItemArray[index].pBlob = NULL; pItemArray[index].dwEUType = OPC_NOENUM; VariantInit( &pItemArray[index].vEUInfo ); double high, low; if( pCallback->GetTagLimits( pItem->pTag, &high, &low ) ) { pItemArray[index].dwEUType = OPC_ANALOG; SAFEARRAYBOUND bound; bound.lLbound = 0; bound.cElements = 2; SAFEARRAY *pArray = SafeArrayCreate(VT_R8, 1, &bound); if(pArray == NULL) return E_OUTOFMEMORY; LONG eu = 0; SafeArrayPutElement(pArray, &eu, (void *)&low); eu++; SafeArrayPutElement(pArray, &eu, (void *)&high); pItemArray[index].vEUInfo.vt = VT_ARRAY | VT_R8; pItemArray[index].vEUInfo.parray = pArray; } } if( pceltFetched ) *pceltFetched = index; *ppItemArray = pItemArray; return (celt==index) ? S_OK : S_FALSE; } //******************************************************************* // just iterate celt times to skip those items STDMETHODIMP CEnumItemAttributes::Skip( ULONG celt ) { for( ULONG i = 0; i < celt && m_pos; i++ ) { COPCItem* pItem = NULL; LPVOID key = 0; m_parent->m_itemMap.GetNextAssoc( m_pos, key, pItem ); } return (celt==i) ? S_OK : S_FALSE; } //******************************************************************* STDMETHODIMP CEnumItemAttributes::Reset( void ) { m_pos = m_parent->m_itemMap.GetStartPosition(); return S_OK; } //******************************************************************* STDMETHODIMP CEnumItemAttributes::Clone( IEnumOPCItemAttributes ** ppEnumItemAttributes ) { *ppEnumItemAttributes = NULL; CComEnumItemAttributes* pEnumerator = new CComEnumItemAttributes; pEnumerator->Initialize(m_parent); pEnumerator->m_pos = m_pos; return pEnumerator->QueryInterface( IID_IEnumOPCItemAttributes, (LPVOID*)ppEnumItemAttributes ); }
[ [ [ 1, 784 ] ] ]
effff00c94b061068589d3f8f7635f1897087172
028d6009f3beceba80316daa84b628496a210f8d
/uidesigner/com.nokia.sdt.referenceprojects.test/data2/form_all_3_0/reference/inc/form_all_3_0AppUi.h
261faad40bf7b5837c803dec4c583ccc1433ba0e
[]
no_license
JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp
fa50cafa69d3e317abf0db0f4e3e557150fd88b3
4420f338bc4e522c563f8899d81201857236a66a
refs/heads/master
2020-12-30T16:45:28.474973
2010-10-20T16:19:31
2010-10-20T16:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,655
h
#ifndef FORM_ALL_3_0APPUI_H #define FORM_ALL_3_0APPUI_H // [[[ begin generated region: do not modify [Generated Includes] #include <aknviewappui.h> // ]]] end generated region [Generated Includes] // [[[ begin generated region: do not modify [Generated Forward Declarations] class Cform_all_3_0FormView; // ]]] end generated region [Generated Forward Declarations] /** * @class Cform_all_3_0AppUi form_all_3_0AppUi.h * @brief The AppUi class handles application-wide aspects of the user interface, including * view management and the default menu, control pane, and status pane. */ class Cform_all_3_0AppUi : public CAknViewAppUi { public: // constructor and destructor Cform_all_3_0AppUi(); virtual ~Cform_all_3_0AppUi(); void ConstructL(); public: // from CCoeAppUi TKeyResponse HandleKeyEventL( const TKeyEvent& aKeyEvent, TEventCode aType ); // from CEikAppUi void HandleCommandL( TInt aCommand ); void HandleResourceChangeL( TInt aType ); // from CAknAppUi void HandleViewDeactivation( const TVwsViewId& aViewIdToBeDeactivated, const TVwsViewId& aNewlyActivatedViewId ); private: void InitializeContainersL(); // [[[ begin generated region: do not modify [Generated Methods] public: // ]]] end generated region [Generated Methods] // [[[ begin generated region: do not modify [Generated Instance Variables] private: Cform_all_3_0FormView* iForm_all_3_0FormView; // ]]] end generated region [Generated Instance Variables] // [[[ begin [User Handlers] protected: // ]]] end [User Handlers] }; #endif // FORM_ALL_3_0APPUI_H
[ [ [ 1, 58 ] ] ]
9d66b2f540c947ff9557cdb7ffbc48ddf4d2b513
d9a78f212155bb978f5ac27d30eb0489bca87c3f
/PB/src/PbLib/GeneratedFiles/Debug/moc_pbhandinfo.cpp
12fdcbb0480582233a1d953b4fce7c7ce2d7e380
[]
no_license
marchon/pokerbridge
1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c
97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9
refs/heads/master
2021-01-10T07:15:26.496252
2010-05-17T20:01:29
2010-05-17T20:01:29
36,398,892
0
0
null
null
null
null
UTF-8
C++
false
false
3,087
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'pbhandinfo.h' ** ** Created: Mon 29. Mar 21:29:34 2010 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "stdafx.h" #include "..\..\pbhandinfo.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'pbhandinfo.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_PBHandInfo[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 2, 12, // properties 0, 0, // enums/sets 0, 0, // constructors // properties: name, type, flags 19, 11, 0x0a095103, 26, 11, 0x0a095103, 0 // eod }; static const char qt_meta_stringdata_PBHandInfo[] = { "PBHandInfo\0QString\0handId\0tableId\0" }; const QMetaObject PBHandInfo::staticMetaObject = { { &PBGameInfo::staticMetaObject, qt_meta_stringdata_PBHandInfo, qt_meta_data_PBHandInfo, 0 } }; const QMetaObject *PBHandInfo::metaObject() const { return &staticMetaObject; } void *PBHandInfo::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_PBHandInfo)) return static_cast<void*>(const_cast< PBHandInfo*>(this)); return PBGameInfo::qt_metacast(_clname); } int PBHandInfo::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = PBGameInfo::qt_metacall(_c, _id, _a); if (_id < 0) return _id; #ifndef QT_NO_PROPERTIES if (_c == QMetaObject::ReadProperty) { void *_v = _a[0]; switch (_id) { case 0: *reinterpret_cast< QString*>(_v) = handId(); break; case 1: *reinterpret_cast< QString*>(_v) = tableId(); break; } _id -= 2; } else if (_c == QMetaObject::WriteProperty) { void *_v = _a[0]; switch (_id) { case 0: setHandId(*reinterpret_cast< QString*>(_v)); break; case 1: setTableId(*reinterpret_cast< QString*>(_v)); break; } _id -= 2; } else if (_c == QMetaObject::ResetProperty) { _id -= 2; } else if (_c == QMetaObject::QueryPropertyDesignable) { _id -= 2; } else if (_c == QMetaObject::QueryPropertyScriptable) { _id -= 2; } else if (_c == QMetaObject::QueryPropertyStored) { _id -= 2; } else if (_c == QMetaObject::QueryPropertyEditable) { _id -= 2; } else if (_c == QMetaObject::QueryPropertyUser) { _id -= 2; } #endif // QT_NO_PROPERTIES return _id; } QT_END_MOC_NAMESPACE
[ "[email protected]", "mikhail.mitkevich@a5377438-2eb2-11df-b28a-19025b8c0740" ]
[ [ [ 1, 3 ], [ 5, 98 ] ], [ [ 4, 4 ] ] ]
7ba53eb448d3e93041188e21b0e55b649652ca92
d609fb08e21c8583e5ad1453df04a70573fdd531
/trunk/ๅผ€ๅ‘ๅบ“/include/HGetRunTime.h
e1779c2a763d06d0a2b1d98780115f8d4fc29e77
[]
no_license
svn2github/openxp
d68b991301eaddb7582b8a5efd30bc40e87f2ac3
56db08136bcf6be6c4f199f4ac2a0850cd9c7327
refs/heads/master
2021-01-19T10:29:42.455818
2011-09-17T10:27:15
2011-09-17T10:27:15
21,675,919
0
1
null
null
null
null
UTF-8
C++
false
false
391
h
#ifndef __HGETRUNTIME__H__ #define __HGETRUNTIME__H__ #pragma once class TEMPLATE_CONTROL_API HGetRunTime { public: HGetRunTime(TCHAR *pszFunc = NULL); ~HGetRunTime(); private: int m_nElapse; TCHAR m_szFunc[260]; }; #ifdef _DEBUG #define ALJ_GET_FUNC_TIME\ HGetRunTime HRunT; #else #define ALJ_GET_FUNC_TIME\ HGetRunTime HRunT(__FUNCTION__); #endif #endif
[ "[email protected]@f92b348d-55a1-4afa-8193-148a6675784b" ]
[ [ [ 1, 23 ] ] ]
5404b8079b15623d9b4071abc08909cdbcdc66c5
9907be749dc7553f97c9e51c5f35e69f55bd02c0
/FrameworkMenu/FrameworkMenu/sprite_handler.h
54583dfc9b92892823aa1d01e5e8a4847118a18c
[]
no_license
jdeering/csci476winthrop
bc8907b9cc0406826de76aca05e6758810377813
2bc485781f819c8fd82393ac86de33404e7ad6d3
refs/heads/master
2021-01-10T19:53:14.853438
2009-04-24T14:26:36
2009-04-24T14:26:36
32,223,762
0
0
null
null
null
null
UTF-8
C++
false
false
4,719
h
/* Jason Deering sprite_handler.h This class is for use in the Framework. It requires the C++ STL map class file reference and sprite containers. The SpriteHandler class controls the display and changing of all sprites and bitmap image files. DATA ITEMS std::map<std::string, Sprite> sprites - container for all active sprites std::map<std::string, ImageFile*> files - container for all files that may be used by the framework a module int numSprites - the number of sprites currently in the sprite container int numFiles - the number of files currently in image file container FUNCTIONS bool RemoveSprite(std::string refName) - removes the sprite from the container at key refName. Returns success or fail as a boolean. bool AddSprite(std::string refName, std::string imageRef, int x, int y, int w, int h) - adds a sprite to the container with the specified properties to the key refName. Returns success or fail as a boolean. bool AddSprite(std::string refName, std::string imageRef, int x, int y) - adds a sprite to the container with the specified properties to the key refName. Uses the width and height parameters of the image file specified by imageRef for use in the sprite. Returns success or fail as a boolean. DrawSprites(BITMAP* dest) - draws all active sprites to the dest parameter bool AddFile(std::string imageRef, std::string filePath, int w, int h, int frame_count, int col_count) - adds the image file referenced by the key imageRef to container with the specified properties returns success or fail as a boolean bool RemoveFile(std::string imageRef) - removes the image file referenced by the key imageRef in the container returns success or fail as a boolean MoveSprite(std::string refName, int new_x, int new_y, int speed) - calls the Sprite class's move function for the sprite at key refName using the remaining parameters SetSpriteSize(std::string refName, int w, int h) - calls the Sprite class's set size function for the sprite at key refName using the remaining parameters SetSpriteLocation(std::string refName, int x, int y) - calls the Sprite class's set location function for the sprite at key refName using the remaining parameters SetVisible(std::string refName, int visible) - calls the Sprite class's set visible function for the sprite at key refName using the remaining parameter SetFrameDelay(std::string refName, int delay) - calls the Sprite class's frame delay function for the sprite at key refName using the remaining parameter SetAnimation(std::string refName, int animate) - calls the Sprite class's set animate function for the sprite at key refName using the remaining parameter SetFrame(std::string refName, int frame) - calls the Sprite class's set frame function for the sprite at key refName using the remaining parameter ChangeBitmap(std::string refName, std::string fileRef) - calls the Sprite class's change bitmap function for the sprite at key refName using the remaining parameter CheckClicks(BoundingBox &pointer) - checks collision detection of the mouse pointer on a sprite on clicks returns a std::string reference to the sprite */ #ifndef _SPRITE_HANDLER_H #define _SPRITE_HANDLER_H #include "sprite.h" #include "image_file.h" #include "globals.h" #define MAX_SPRITES 500 class SpriteHandler { private: // Sprite Container std::map<std::string, Sprite> sprites; // Bitmap Files std::map<std::string, ImageFile*> files; int numSprites, numFiles; public: SpriteHandler(); ~SpriteHandler(); // Sprite updater bool RemoveSprite(std::string refName); bool AddSprite(std::string refName, std::string imageRef, int x, int y, int w, int h); bool AddSprite(std::string refName, std::string imageRef, int x, int y); void DrawSprites(BITMAP*); bool AddFile(std::string imageRef, std::string filePath, int frame_count, int col_count, int w, int h); bool RemoveFile(std::string imageRef); // Sprite moving/animating void MoveSprite(std::string refName, int new_x, int new_y, int speed){ sprites[refName].MoveTo(new_x, new_y, speed); } void SetSpriteSize(std::string refName, int w, int h); void SetSpriteLocation(std::string refName, int x, int y); void SetVisible(std::string refName, int visible); void SetFrameDelay(std::string refName, int delay); void SetAnimation(std::string refName, int animate); void SetFrame(std::string refName, int frame); void ChangeBitmap(std::string refName, std::string fileRef); // Check Mouse Clicks on Sprites std::string CheckClicks(BoundingBox &pointer); }; #endif
[ "deeringj2@2656ef14-ecf4-11dd-8fb1-9960f2a117f8" ]
[ [ [ 1, 103 ] ] ]
f1825dfdee1ed1ba45bb7e29392bc75eaaae3290
2628dc980c1bf2ab0b3e166d654261617dcbd26e
/samplecode/libxml2_sax2_example.cpp
185cecc61155353181b2dd056216640f55345178
[]
no_license
neuhq/svnnccode
583c8521aeae70dec96005607b99ce054f7c6967
9fb6b012da859b8e61a97ec5515e6cd012549190
refs/heads/master
2020-05-17T06:38:37.636781
2010-01-02T03:51:12
2010-01-02T03:51:12
40,288,703
0
0
null
null
null
null
UTF-8
C++
false
false
6,172
cpp
#include <stdio.h> #include <memory.h> #include <libxml/xmlmemory.h> #include <libxml/parser.h> #include <string> class ParseFSM { public: /** SAX2 callback when an element start has been detected by the parser. It provides the namespace informations for the element, as well as the new namespace declarations on the element. ctx: the user data (XML parser context) localname: the local name of the element prefix: the element namespace prefix if available URI: the element namespace name if available nb_namespaces: number of namespace definitions on that node namespaces: pointer to the array of prefix/URI pairs namespace definitions nb_attributes: the number of attributes on that node nb_defaulted: the number of defaulted attributes. The defaulted ones are at the end of the array attributes: pointer to the array of (localname/prefix/URI/value/end) attribute values. */ static void charactersSAXFunc(void* ctx, const xmlChar *ch, int len) { printf("%s\n", ch); } static void startElementNs( void * ctx, const xmlChar * localname, const xmlChar * prefix, const xmlChar * URI, int nb_namespaces, const xmlChar ** namespaces, int nb_attributes, int nb_defaulted, const xmlChar ** attributes ) { ParseFSM &fsm = *( static_cast<ParseFSM *>( ctx ) ); printf( "startElementNs: name = '%s' prefix = '%s' uri = (%p)'%s'\n", localname, prefix, URI, URI ); for ( int indexNamespace = 0; indexNamespace < nb_namespaces; ++indexNamespace ) { const xmlChar *prefix = namespaces[indexNamespace*2]; const xmlChar *nsURI = namespaces[indexNamespace*2+1]; printf( " namespace: name='%s' uri=(%p)'%s'\n", prefix, nsURI, nsURI ); } unsigned int index = 0; for ( int indexAttribute = 0; indexAttribute < nb_attributes; ++indexAttribute, index += 5 ) { const xmlChar *localname = attributes[index]; const xmlChar *prefix = attributes[index+1]; const xmlChar *nsURI = attributes[index+2]; const xmlChar *valueBegin = attributes[index+3]; const xmlChar *valueEnd = attributes[index+4]; std::string value( (const char *)valueBegin, (const char *)valueEnd ); printf( " %sattribute: localname='%s', prefix='%s', uri=(%p)'%s', value='%s'\n", indexAttribute >= (nb_attributes - nb_defaulted) ? "defaulted " : "", localname, prefix, nsURI, nsURI, value.c_str() ); } } /** SAX2 callback when an element end has been detected by the parser. It provides the namespace informations for the element. ctx: the user data (XML parser context) localname: the local name of the element prefix: the element namespace prefix if available URI: the element namespace name if available */ static void endElementNs( void * ctx, const xmlChar * localname, const xmlChar * prefix, const xmlChar * URI ) { ParseFSM &fsm = *( static_cast<ParseFSM *>( ctx ) ); printf( "endElementNs: name = '%s' prefix = '%s' uri = '%s'\n", localname, prefix, URI ); } /** Display and format an error messages, callback. ctx: an XML parser context msg: the message to display/transmit ...: extra parameters for the message display */ static void error( void * ctx, const char * msg, ... ) { ParseFSM &fsm = *( static_cast<ParseFSM *>( ctx ) ); va_list args; va_start(args, msg); vprintf( msg, args ); va_end(args); } /** Display and format a warning messages, callback. ctx: an XML parser context msg: the message to display/transmit ...: extra parameters for the message display */ static void warning( void * ctx, const char * msg, ... ) { ParseFSM &fsm = *( static_cast<ParseFSM *>( ctx ) ); va_list args; va_start(args, msg); vprintf( msg, args ); va_end(args); } }; int main(int argc, const char * argv[]) { std::string xmlIn = "<test:Plan xmlns:test='http://test.org/schema'>" "<test:Case name='test1' emptyAttribute='' test:ns_id='auio'>" "</test:Case>" "</test:Plan>"; /* * this initialize the library and check potential ABI mismatches * between the version it was compiled for and the actual shared * library used. */ LIBXML_TEST_VERSION xmlSAXHandler saxHandler; // See http://xmlsoft.org/html/libxml-tree.html#xmlSAXHandler memset( &saxHandler, 0, sizeof(saxHandler) ); // Using xmlSAXVersion( &saxHandler, 2 ) generate crash as it sets plenty of other pointers... saxHandler.initialized = XML_SAX2_MAGIC; // so we do this to force parsing as SAX2. saxHandler.startElementNs = &ParseFSM::startElementNs; saxHandler.endElementNs = &ParseFSM::endElementNs; saxHandler.warning = &ParseFSM::warning; saxHandler.error = &ParseFSM::error; saxHandler.characters = &ParseFSM::charactersSAXFunc; ParseFSM fsm; // int result = xmlSAXUserParseMemory( &saxHandler, &fsm, xmlIn.c_str(), int(xmlIn.length()) ); int result = xmlSAXUserParseFile(&saxHandler, &fsm, "/mnt/f/zhwiki-latest-pages-articles.xml"); if ( result != 0 ) { printf("Failed to parse document.\n" ); return 1; } /* * Cleanup function for the XML library. */ xmlCleanupParser(); /* * this is to debug memory for regression tests */ xmlMemoryDump(); return 0; }
[ "svncode@16a6eac2-a0cf-11dd-a874-8d3a81574e67" ]
[ [ [ 1, 160 ] ] ]
7256352e452f60e63a23e7fca5271ef2be166332
be7df324d5509c7ebb368c884b53ea9445d32e4f
/GUI/Cardiac/Optimizer.h
3367a53a8dad746edb3a693bb16ae85ab01f67fa
[]
no_license
shadimsaleh/thesis.code
b75281001aa0358282e9cceefa0d5d0ecfffdef1
085931bee5b07eec9e276ed0041d494c4a86f6a5
refs/heads/master
2021-01-11T12:20:13.655912
2011-10-19T13:34:01
2011-10-19T13:34:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,575
h
/** * @file Optimizer.h * @brief The base class for Optimizers * @author Hari Sundar * @date 5/29/03 * * This is supposed to be a base class for optimizers as such. However, because of limited use currently * it is being written as a non-linear optimizer. It can be later on rewritten as a non-linear optimizer * derived from a more generic Optimizer class. * **/ #ifndef OPTIMIZER_H #define OPTIMIZER_H class Optimizer { public: /** @name Constructors and Destructors **/ //@{ Optimizer (); virtual ~ Optimizer (); //@} virtual bool init () = 0; virtual double costFunction (double *tmpParams) = 0; virtual bool optimize () = 0; virtual void verbose () = 0; /** @name access methods **/ //@{ void setParamsTolerance (double x) { m_paramsTolerance = x; } void setFunctionTolerance (double x) { m_functionTolerance = x; } void setNumberOfIterations (int n) { m_maxIterations = n; } void setNumberOfEvaluations (int n) { m_maxEvaluations = n; } void setMinimize (bool flag) { m_minimize = flag; } double getParamsTolerance () const { return m_paramsTolerance; } double getFunctionTolerance () const { return m_functionTolerance; } int getMaximumNumberOfIterations () const { return m_maxIterations; } int getMaximumNumberOfEvaluations () const { return m_maxEvaluations; } int getFinalNumberOfIterations () const { return m_numIterations; } int getFinalNumberOfEvaluations () const { return m_numEvaluations; } double getCostFunctionValue () const { return m_costFunctionValue; }; void setInitialParameters (double *parameters, double *stepsizes, int dimensions); double *getParameters () const { return m_parameters; }; bool isOptimizing ()const { return m_isOptimizing; }; //@} protected: /** @name Data members **/ //@{ double m_costFunctionValue; double m_paramsTolerance; double m_functionTolerance; int m_maxIterations; int m_numIterations; int m_maxEvaluations; int m_numEvaluations; double *m_parameters; double *m_stepsizes; double *m_workParams; double *m_workResults; double m_scale; int m_numberOfParams; bool m_isOptimizing; bool m_minimize; //@} }; #endif /* */
[ [ [ 1, 109 ] ] ]
0d38ee998114f787ea369723de3d9dd325f99767
59166d9d1eea9b034ac331d9c5590362ab942a8f
/XMLTree2Geom/Singletons/xmlTree.h
06c27139a05283bbc4a0a750956727e66cc2f7fe
[]
no_license
seafengl/osgtraining
5915f7b3a3c78334b9029ee58e6c1cb54de5c220
fbfb29e5ae8cab6fa13900e417b6cba3a8c559df
refs/heads/master
2020-04-09T07:32:31.981473
2010-09-03T15:10:30
2010-09-03T15:10:30
40,032,354
0
3
null
null
null
null
WINDOWS-1251
C++
false
false
1,305
h
#ifndef _XML_TREE_H_ #define _XML_TREE_H_ #include "Singleton.h" #include "ticpp.h" #include "xmlTmpl.h" #include "xmlBranch/xmlBranch.h" #include "xmlFronds/xmlFronds.h" #include "xmlLeaf/xmlLeaf.h" #include <string> class xmlTree : public Singleton< xmlTree > { public: xmlTree(); ~xmlTree(); //ะธะฝะธั†ะธะฐะปะธะทะฐั†ะธั void Init( std::string _sFileName ); //ะทะฐะฒะตั€ัˆะตะฝะธะต ั€ะฐะฑะพั‚ั‹ void Close(); //ะฟะพะปัƒั‡ะธั‚ัŒ ะดะพัั‚ัƒะฟ ะบ ะดะฐะฝะฝั‹ะผ ัั‚ะฒะพะปะฐ binBranch &GetBranch(){ return m_xmlBranch.GetData(); }; //ะฟะพะปัƒั‡ะธั‚ัŒ ะดะพัั‚ัƒะฟ ะบ ะดะฐะฝะฝั‹ะผ ะฒะตั‚ะพะบ binFronds &GetFronds(){ return m_xmlFronds.GetData(); }; //ะฟะพะปัƒั‡ะธั‚ัŒ ะดะพัั‚ัƒะฟ ะบ ะดะฐะฝะฝั‹ะผ ะปะธัั‚ะฒั‹ binLeaf &GetLeaf(){ return m_xmlLeaf.GetData(); }; private: //ะธะฝะธั†ะธะฐะปะธะทะธั€ะพะฒะฐั‚ัŒ ะดะพั‡ะตั€ะฝะธะต ะดะฐะฝะฝั‹ะต void InitChild( ticpp::Node* pNode ); xmlTmpl< binBranch , xmlBranchLoad , xmlBranchSave > m_xmlBranch; //ะดะฐะฝะฝั‹ะต ะพ ัั‚ะฒะพะปะต xmlTmpl< binFronds , xmlFrondsLoad , xmlFrondsSave > m_xmlFronds; //ะดะฐะฝะฝั‹ะต ะพ ะฒะตั‚ะบะฐั… xmlTmpl< binLeaf , xmlLeafLoad , xmlLeafSave > m_xmlLeaf; //ะดะฐะฝะฝั‹ะต ะพ ะปะธัั‚ะฒะต //ะธะผั ั„ะฐะนะปะฐ xml std::string m_sFileName; }; #endif //_XML_TREE_H_
[ "asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b" ]
[ [ [ 1, 47 ] ] ]
714ef687db39724c42593d6b57aeca0093da0f31
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/FileBrowse/s60/FileBrowse/src/rfsengine.cpp
10b27090d45802cd23d57a552b45c9d6f6dc2daa
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
1,708
cpp
// FileBrowseEngine.cpp // // Copyright (c) 2006 Symbian Software Ltd. All rights reserved. // #include <f32file.h> #include "RFsEngine.h" CRFsEngine* CRFsEngine::NewL() { CRFsEngine* me = new (ELeave) CRFsEngine(); CleanupStack::PushL(me); me->ConstructL(); CleanupStack::Pop(me); return (me); } CRFsEngine::~CRFsEngine() { delete iFileList; delete iDirList; iFs.Close(); } TInt CRFsEngine::GetDirectoryAndFileList(const TDesC& aPath) { if (iFileList) { delete iFileList; iFileList = NULL; } if (iDirList) { delete iDirList; iDirList = NULL; } TInt result = iFs.GetDir(aPath, KEntryAttNormal | KEntryAttHidden | KEntryAttSystem, ESortByName | EDirsFirst | EAscending, iFileList, iDirList); return (result); } TInt CRFsEngine::DirectoryCount() { if (iDirList) return (iDirList->Count()); else return (0); } TInt CRFsEngine::FileCount() { if (iFileList) return (iFileList->Count()); else return (0); } const TDesC& CRFsEngine::DirectoryName(TInt aDirListIndex) { if ( (!iDirList) || (iDirList->Count()<=aDirListIndex) ) return (KNullDesC); else return (iDirList->operator[](aDirListIndex).iName); } const TDesC& CRFsEngine::FileName(TInt aFileNameIndex) { if ( (!iFileList) || (iFileList->Count()<=aFileNameIndex) ) return (KNullDesC); else return (iFileList->operator[](aFileNameIndex).iName); } void CRFsEngine::ConstructL() { User::LeaveIfError(iFs.Connect()); } CRFsEngine::CRFsEngine() {}
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 93 ] ] ]
bad7de344cbae27a4fddaabc5545da304a5e134e
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/SegmentShape2D.h
0845fd9660108371813cefe711dcfd3144dfe1e3
[]
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
1,376
h
#pragma once #ifndef __HALAK_SEGMENTSHAPE2D_H__ #define __HALAK_SEGMENTSHAPE2D_H__ # include <Halak/FWD.h> # include <Halak/Shape2D.h> namespace Halak { class SegmentShape2D : public Shape2D { public: SegmentShape2D(); virtual ~SegmentShape2D(); Vector2 GetDirection() const; void SetDirection(Vector2 value); float GetFrontLength() const; void SetFrontLength(float value); float GetBackLength() const; void SetBackLength(float value); float GetLength() const; Vector2 GetStartPoint(); Vector2 GetEndPoint(); Vector2 GetRotatedDirection(); virtual bool Raycast(const Ray2D& ray, RaycastReport2D& outReport, IRaycastCallback2D* callback); virtual void AppendTo(std::list<Vector2>& vertices); private: void UpdateParameters(); private: Vector2 direction; float frontLength; float backLength; Vector2 startPoint; Vector2 endPoint; Vector2 rotatedDirection; unsigned int revision; }; } #endif
[ [ [ 1, 49 ] ] ]
5f021d5aa1fce288a68a86b5b47bbbb7387b97c6
234a9bca80cac2aff7ad92dcd0c308dcb790e8d4
/v7ui/LayoutManager.h
f3068785a75497c29d1f028c339c0545c3a1d92b
[]
no_license
ste6an/v7ui
a15e529db7defa0930a7b950ac7d3ec2d8e11eeb
5b04049377cf9691d490322a0fae0ccf7a1a2dac
refs/heads/master
2021-01-10T03:28:26.659178
2008-08-14T16:01:49
2008-08-14T16:01:49
50,845,135
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
14,425
h
// ========================================================================== // Class Specification : COXLayoutManager // ========================================================================== // Header file : OXLayoutManager.h // // Version: 9.3 // // This software along with its related components, documentation and files ("The Libraries") // is ยฉ 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is // governed by a software license agreement ("Agreement"). Copies of the Agreement are // available at The Code Project (www.codeproject.com), as part of the package you downloaded // to obtain this file, or directly from our office. For a copy of the license governing // this software, you may contact us at [email protected], or by calling 416-849-8900. // // // Properties: // NO Abstract class (does not have any objects) // YES Derived from CObject // // NO Is a CWnd. // NO Two stage creation (constructor & Create()) // NO Has a message map // NO Needs a resource (template) // // NO Persistent objects (saveable on disk) // NO Uses exceptions // // Description: // COXLayoutManager can be attached to a container window (dialog, form etc.). // From that moment on the layout manager will manage the layout of the child // windows of this container. So imagine you have a dialog with several // controls on it. When the dialog is resized the layout manager moves and // resizes the controls of this dialog. The programmer can specify certain // constraints that have to be fulfilled at all times. By using these // constraints and the new size of the container window (dialog), the layout // manager is able to move and resize the controls appropriately. // ///////////////////////////////////////////////////////////////////////////// #ifndef __OXLAYOUTMANAGER_H__ #define __OXLAYOUTMANAGER_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #ifndef __AFXTEMPL_H__ //#include <AfxTempl.h> #define __AFXTEMPL_H__ #endif #define OX_LMS_TOP 1 // 0001 #define OX_LMS_BOTTOM 2 // 0010 #define OX_LMS_LEFT 4 // 0100 #define OX_LMS_RIGHT 8 // 1000 #define OX_LMS_VERT 3 // 0011 #define OX_LMS_HORZ 12 // 1100 #define OX_LMS_MAJOR 5 // 0101 #define OX_LMS_MINOR 10 // 1010 #define OX_LMS_ANY 15 // 1111 #define OX_LMT_SAME 1 #define OX_LMT_OPPOSITE 2 #define OX_LMT_POSITION 3 #define OX_LMOFFSET_ANY 32767 #define OX_LMPOS_NULL 32767 #define OX_LMPOS_TRACING 32766 ///////////////////////////////////////////////////////////////////////////// // helper classes for COXLayoutManager #define OX_CLASS_DECL class COXLayoutManager; class COXWndConstraint; class OX_CLASS_DECL COXSideConstraint { friend class COXLayoutManager; friend class COXWndConstraint; protected: COXSideConstraint(); void Empty(); BOOL IsEmpty(); UINT nBaseWnd; int nOffset1; int nOffset2; int nPos; int nBaseWndIndex; }; class OX_CLASS_DECL COXWndConstraint { friend class COXLayoutManager; protected: COXWndConstraint(UINT nChildID); void Empty(); CRect GetRect(); void ResetPos(); UINT nID; BOOL bHasMinMax; CSize sizeMin; CSize sizeMax; COXSideConstraint sc[4]; }; ///////////////////////////////////////////////////////////////////////////// class OX_CLASS_DECL COXLayoutManager : public CObject { DECLARE_DYNCREATE(COXLayoutManager) // Data members ------------------------------------------------------------- public: protected: CWnd* m_pContainerWnd; int m_nBase; UINT m_nMinMaxCount; int m_cx; int m_cy; int m_cxMin; int m_cxMax; int m_cyMin; int m_cyMax; CArray<COXWndConstraint*, COXWndConstraint*> m_wcTable; HWND m_hWnd; WNDPROC m_pfnSuper; static CMap<HWND, HWND, COXLayoutManager*, COXLayoutManager*> m_allLayoutManagers; private: // Member functions --------------------------------------------------------- public: COXLayoutManager(CWnd* pContainerWnd = NULL); // --- In : pContainerWnd, the container window to attach // --- Out : // --- Returns : // --- Effect : Constructor of object virtual ~COXLayoutManager(); // --- In : // --- Out : // --- Returns : // --- Effect : Destructor of object void Attach(CWnd* pContainerWnd); // --- In : pContainerWnd, the container window to attach // --- Out : // --- Returns : // --- Effect : attach a container window to start the layout management // of this window void Detach(); // --- In : // --- Out : // --- Returns : // --- Effect : detach the container window (and remove all constraints) BOOL IsAttached() const; // --- In : // --- Out : // --- Returns : TRUE if any container is attached to layout manager object // --- Effect : retrieves the flag that specifies whether any container // window is attached to the object or not int AddChild(UINT nChildWnd, BOOL bSetDefaultConstraints = TRUE); int AddChild(CWnd* pChildWnd, BOOL bSetDefaultConstraints = TRUE); // --- In : nChildWnd, the ID of the child window to add // pChildWnd, the child window to add // bSetDefaultConstraints, if TRUE, left and top will be constrainted // to the container window using current distance // --- Out : // --- Returns : internal index of this child window; -1 if not successful // --- Effect : add one child window of the container window to prepare for // setting constraints void AddAllChildren(BOOL bSetDefaultConstraints = TRUE); // --- In : bSetDefaultConstraints, if TRUE, left and top will be constrainted // to the container window using current distance // --- Out : // --- Returns : // --- Effect : add all child windows of the container window to prepare for // setting constraints, and set default constraints if specified BOOL RemoveChild(UINT nChildWnd); BOOL RemoveChild(CWnd* pChildWnd); // --- In : nChildWnd, the ID of the child window to remove // pChildWnd, the child window to remove // --- Out : // --- Returns : TRUE if successful; FALSE if not found or it is necessary // for another window to calculate positions // --- Effect : remove one child window of the container window to free all its // constraints void RemoveAllChildren(); // --- In : // --- Out : // --- Returns : // --- Effect : remove all child windows that are previously added and free // all constraints void SetFractionBase(int nBase); // --- In : nBase, the new fraction base to use (cannot be 0) // --- Out : // --- Returns : // --- Effect : set a new fraction base that is used in specifying an OX_LMT_POSITION // constraint (default is 100) int GetFractionBase() const; // --- In : // --- Out : // --- Returns : the current fraction base // --- Effect : get the current fraction base BOOL SetConstraint(UINT nChildWnd, int nSide, int nType, int nOffset = 0, UINT nBaseWnd = 0); BOOL SetConstraint(CWnd* pChildWnd, int nSide, int nType, int nOffset = 0, CWnd* pBaseWnd = NULL); // --- In : nChildWnd, pChildWnd, the child window to apply constraint // nSide, can be any combination of the following values: // OX_LMS_TOP top side // OX_LMS_BOTTOM bottom side // OX_LMS_LEFT left side // OX_LMS_RIGHT right side // OX_LMS_VERT top and bottom sides // OX_LMS_HORZ left and right sides // OX_LMS_MAJOR top and left sides // OX_LMS_MINOR bottom and right sides // OX_LMS_ANY all four sides // nType, can be one of the following values (see .html file for details): // OX_LMT_SAME the constrainted side of the child window is based on // the same side of the base window // OX_LMT_OPPOSITE the constrainted side of the child window is based on // the opposite side of the base window // OX_LMT_POSITION the constrainted side of the child window is based on // a fraction to both sides of the base window // nOffset, when nType is OX_LMT_POSITION, the fraction that the // constrainted side will be positioned within the base window; // otherwise, the offset that the constrainted side will be positioned // from the specified side (determined by nType) of the base window. // nBaseWnd, pBaseWnd, the window upon which the constrainted side // will be positioned // --- Out : // --- Returns : // --- Effect : set constraints on one or more sides of a child window virtual void SetDefaultConstraint(UINT nChildWnd); // --- In : nChildWnd : the child window to apply default constraint on // --- Out : // --- Returns : // --- Effect : set default constraints on a child window; called by AddChild() // left and top will be constrainted to the container window using // current distance // right and bottom will not be constrained BOOL SetMinMax(UINT nChildWnd, CSize sizeMin, CSize sizeMax = CSize(0,0)); BOOL SetMinMax(CWnd* pChildWnd, CSize sizeMin, CSize sizeMax = CSize(0,0)); // --- In : nChildWnd, pChildWnd, the child window to apply min/max limits // sizeMin, minimum size of the child window; CSize(0,0) means "don't care" // sizeMax, maximum size of the child window; CSize(0,0) means "don't care" // --- Out : // --- Returns : // --- Effect : set the minimum size and maximum size of a child window BOOL RemoveConstraint(UINT nChildWnd, int nSide); BOOL RemoveConstraint(CWnd* pChildWnd, int nSide); // --- In : nChildWnd, pChildWnd, the child window to remove constraints on // nSide, can be any combination of the following values: // OX_LMS_TOP top side // OX_LMS_BOTTOM bottom side // OX_LMS_LEFT left side // OX_LMS_RIGHT right side // OX_LMS_VERT top and bottom sides // OX_LMS_HORZ left and right sides // OX_LMS_MAJOR top and left sides // OX_LMS_MINOR bottom and right sides // OX_LMS_ANY all four sides // --- Out : // --- Returns : // --- Effect : remove constraints from one or more sides of a child window BOOL GetConstraint(UINT nChildWnd, int nSide, int& nType, int& nOffset, UINT& nBaseWnd); // --- In : nChildWnd, the child window to check constraints on // nSide, can be one of the following values: // OX_LMS_TOP top side // OX_LMS_BOTTOM bottom side // OX_LMS_LEFT left side // OX_LMS_RIGHT right side // --- Out : nType, the constraint type // nOffset, offset position or fraction // nBaseWnd, base window of the constraint // --- Returns : TRUE if successful; false otherwise // --- Effect : retrieve constraints on a side of a child window BOOL GetMinMax(UINT nChildWnd, CSize& sizeMin, CSize& sizeMax); // --- In : nChildWnd, the child window to check min/max limits // --- Out : sizeMin, minimum size of the child window // sizeMax, maximum size of the child window // --- Returns : TRUE if successful; false otherwise // --- Effect : retrieve the minimum size and maximum size of a child window BOOL TieChild(UINT nChildWnd, int nSide, int nType, UINT nBaseWnd=0); BOOL TieChild(CWnd* pChildWnd, int nSide, int nType, CWnd* pBaseWnd=NULL); // --- In : nChildWnd, pChildWnd, the child window to apply constraint // nSide, can be any combination of the following values: // OX_LMS_TOP top side // OX_LMS_BOTTOM bottom side // OX_LMS_LEFT left side // OX_LMS_RIGHT right side // OX_LMS_VERT top and bottom sides // OX_LMS_HORZ left and right sides // OX_LMS_MAJOR top and left sides // OX_LMS_MINOR bottom and right sides // OX_LMS_ANY all four sides // nType, can be one of the following values : // OX_LMT_SAME child window will be tied to the // same sides of base window // OX_LMT_OPPOSITE child window will be tied to the // opposite sides of base window // nBaseWnd, pBaseWnd, the window to which the specified // child window will be tied // --- Out : // --- Returns : // --- Effect : ties specified side(s) of child control to the base window virtual BOOL RedrawLayout(); // --- In : // --- Out : // --- Returns : TRUE if all constraints and min/max limits can be fulfilled, // FALSE otherwise // --- Effect : read container window's current positions and apply constraints // on all child windows virtual BOOL OnSize(int cx, int cy); // --- In : cx, new width of the container window // cy, new height of the container window // --- Out : // --- Returns : TRUE if all constraints and min/max limits can be fulfilled, // FALSE otherwise // --- Effect : use new size of the container window to apply constraints // on all child windows virtual void OnMouseMove(int flags, int x, int y); virtual void OnLButtonDown(int flags, int x, int y); virtual void OnLButtonUp(int flags, int x, int y); virtual void SetCursor(int x, int y); virtual void Tracking(int x, int y); virtual void StopTracking(); virtual COXSideConstraint* GetMovableSide(int x, int y, int* nSide); protected: int CalcLayout(); void ResetContainerMinMax(); int GetChildIndex(UINT nChildWnd) const; BOOL CalcBaseWndIndex(COXSideConstraint* pSC); int CalcSideConstraint(COXWndConstraint* pWC, int nSideIndex); void CalcOffsets( COXWndConstraint* pWC); BOOL SubclassContainer(CWnd* pContainerWnd); void UnsubclassContainer(); static LRESULT CALLBACK GlobalLayoutManagerProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT LayoutManagerProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); HCURSOR hArrow; HCURSOR hSizeNS; HCURSOR hSizeWE; int m_nSplitterSize; int m_nOffset; COXSideConstraint* m_pTrackingSide; COXWndConstraint* m_pTrackingWnd; private: }; ///////////////////////////////////////////////////////////////////////////// #include "LayoutManager.inl" #endif // __OXLAYOUTMANAGER_H__ // end of OXLayoutManager.h
[ "steban.r@localhost" ]
[ [ [ 1, 381 ] ] ]
59eaafd7ced811588193a35a982bb4979ebd209c
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume CIV/10424.cpp
54ea818469c062725e0d8dfd40b2e71011051e4c
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
754
cpp
///////////////////////////////// // 10424 - Love Calculator ///////////////////////////////// #include<cstdio> #include<cstring> char first[26],second[26]; unsigned short int a,b,suma,sumb; char value[127],i; int main(void){ memset(value,0,sizeof(value)); for(i = 'a'; i < 'z'+1; i++) value[i] = value[i-32] = i-'a'+1; while(gets(first)){ gets(second); for(a = i = 0; first[i]; i++) a+=value[first[i]]; for(b = i = 0; second[i]; i++) b+=value[second[i]]; while(a>9){ suma = 0; while(a){suma += a%10;a/=10;} a = suma; } while(b>9){ sumb = 0; while(b){sumb += b%10;b/=10;} b = sumb; } if(a>b) printf("%.2lf %%\n",b/(a*1.00)*100); else printf("%.2lf %%\n",a/(b*1.00)*100); } return 0; }
[ [ [ 1, 30 ] ] ]
92d7e184c5c5076f26c788ecafc565644a9e0930
0033659a033b4afac9b93c0ac80b8918a5ff9779
/game/server/hl2/npc_headcrab.cpp
6f345a03b8fdd337dd67d89d9d7bcc2f4b1e40de
[]
no_license
jonnyboy0719/situation-outbreak-two
d03151dc7a12a97094fffadacf4a8f7ee6ec7729
50037e27e738ff78115faea84e235f865c61a68f
refs/heads/master
2021-01-10T09:59:39.214171
2011-01-11T01:15:33
2011-01-11T01:15:33
53,858,955
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
112,872
cpp
//========= Copyright ยฉ 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Implements the headcrab, a tiny, jumpy alien parasite. // // TODO: make poison headcrab hop in response to nearby bullet impacts? // //=============================================================================// #include "cbase.h" #include "game.h" #include "antlion_dust.h" #include "ai_default.h" #include "ai_schedule.h" #include "ai_hint.h" #include "ai_hull.h" #include "ai_navigator.h" #include "ai_moveprobe.h" #include "ai_memory.h" #include "bitstring.h" #include "hl2_shareddefs.h" #include "npcevent.h" #include "soundent.h" #include "npc_headcrab.h" #include "gib.h" #include "ai_interactions.h" #include "ndebugoverlay.h" #include "vstdlib/random.h" #include "engine/IEngineSound.h" #include "movevars_shared.h" #include "world.h" #include "npc_bullseye.h" #include "physics_npc_solver.h" #include "hl2_gamerules.h" #include "decals.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define CRAB_ATTN_IDLE (float)1.5 #define HEADCRAB_GUTS_GIB_COUNT 1 #define HEADCRAB_LEGS_GIB_COUNT 3 #define HEADCRAB_ALL_GIB_COUNT 5 #define HEADCRAB_RUNMODE_ACCELERATE 1 #define HEADCRAB_RUNMODE_IDLE 2 #define HEADCRAB_RUNMODE_DECELERATE 3 #define HEADCRAB_RUNMODE_FULLSPEED 4 #define HEADCRAB_RUNMODE_PAUSE 5 #define HEADCRAB_RUN_MINSPEED 0.5 #define HEADCRAB_RUN_MAXSPEED 1.0 const float HEADCRAB_BURROWED_FOV = -1.0f; const float HEADCRAB_UNBURROWED_FOV = 0.5f; #define HEADCRAB_IGNORE_WORLD_COLLISION_TIME 0.5 const int HEADCRAB_MIN_JUMP_DIST = 48; const int HEADCRAB_MAX_JUMP_DIST = 256; #define HEADCRAB_BURROW_POINT_SEARCH_RADIUS 256.0 // Debugging #define HEADCRAB_DEBUG_HIDING 1 #define HEADCRAB_BURN_SOUND_FREQUENCY 10 ConVar g_debug_headcrab( "g_debug_headcrab", "0", FCVAR_CHEAT ); //------------------------------------ // Spawnflags //------------------------------------ #define SF_HEADCRAB_START_HIDDEN (1 << 16) #define SF_HEADCRAB_START_HANGING (1 << 17) //----------------------------------------------------------------------------- // Think contexts. //----------------------------------------------------------------------------- static const char *s_pPitchContext = "PitchContext"; //----------------------------------------------------------------------------- // Animation events. //----------------------------------------------------------------------------- int AE_HEADCRAB_JUMPATTACK; int AE_HEADCRAB_JUMP_TELEGRAPH; int AE_POISONHEADCRAB_FLINCH_HOP; int AE_POISONHEADCRAB_FOOTSTEP; int AE_POISONHEADCRAB_THREAT_SOUND; int AE_HEADCRAB_BURROW_IN; int AE_HEADCRAB_BURROW_IN_FINISH; int AE_HEADCRAB_BURROW_OUT; int AE_HEADCRAB_CEILING_DETACH; //----------------------------------------------------------------------------- // Custom schedules. //----------------------------------------------------------------------------- enum { SCHED_HEADCRAB_RANGE_ATTACK1 = LAST_SHARED_SCHEDULE, SCHED_HEADCRAB_WAKE_ANGRY, SCHED_HEADCRAB_WAKE_ANGRY_NO_DISPLAY, SCHED_HEADCRAB_DROWN, SCHED_HEADCRAB_FAIL_DROWN, SCHED_HEADCRAB_AMBUSH, SCHED_HEADCRAB_HOP_RANDOMLY, // get off something you're not supposed to be on. SCHED_HEADCRAB_BARNACLED, SCHED_HEADCRAB_UNHIDE, SCHED_HEADCRAB_HARASS_ENEMY, SCHED_HEADCRAB_FALL_TO_GROUND, SCHED_HEADCRAB_RUN_TO_BURROW_IN, SCHED_HEADCRAB_RUN_TO_SPECIFIC_BURROW, SCHED_HEADCRAB_BURROW_IN, SCHED_HEADCRAB_BURROW_WAIT, SCHED_HEADCRAB_BURROW_OUT, SCHED_HEADCRAB_WAIT_FOR_CLEAR_UNBURROW, SCHED_HEADCRAB_CRAWL_FROM_CANISTER, SCHED_FAST_HEADCRAB_RANGE_ATTACK1, SCHED_HEADCRAB_CEILING_WAIT, SCHED_HEADCRAB_CEILING_DROP, }; //========================================================= // tasks //========================================================= enum { TASK_HEADCRAB_HOP_ASIDE = LAST_SHARED_TASK, TASK_HEADCRAB_HOP_OFF_NPC, TASK_HEADCRAB_DROWN, TASK_HEADCRAB_WAIT_FOR_BARNACLE_KILL, TASK_HEADCRAB_UNHIDE, TASK_HEADCRAB_HARASS_HOP, TASK_HEADCRAB_FIND_BURROW_IN_POINT, TASK_HEADCRAB_BURROW, TASK_HEADCRAB_UNBURROW, TASK_HEADCRAB_BURROW_WAIT, TASK_HEADCRAB_CHECK_FOR_UNBURROW, TASK_HEADCRAB_JUMP_FROM_CANISTER, TASK_HEADCRAB_CLIMB_FROM_CANISTER, TASK_HEADCRAB_CEILING_WAIT, TASK_HEADCRAB_CEILING_POSITION, TASK_HEADCRAB_CEILING_DETACH, TASK_HEADCRAB_CEILING_FALL, TASK_HEADCRAB_CEILING_LAND, }; //========================================================= // conditions //========================================================= enum { COND_HEADCRAB_IN_WATER = LAST_SHARED_CONDITION, COND_HEADCRAB_ILLEGAL_GROUNDENT, COND_HEADCRAB_BARNACLED, COND_HEADCRAB_UNHIDE, }; //========================================================= // private activities //========================================================= int ACT_HEADCRAB_THREAT_DISPLAY; int ACT_HEADCRAB_HOP_LEFT; int ACT_HEADCRAB_HOP_RIGHT; int ACT_HEADCRAB_DROWN; int ACT_HEADCRAB_BURROW_IN; int ACT_HEADCRAB_BURROW_OUT; int ACT_HEADCRAB_BURROW_IDLE; int ACT_HEADCRAB_CRAWL_FROM_CANISTER_LEFT; int ACT_HEADCRAB_CRAWL_FROM_CANISTER_CENTER; int ACT_HEADCRAB_CRAWL_FROM_CANISTER_RIGHT; int ACT_HEADCRAB_CEILING_IDLE; int ACT_HEADCRAB_CEILING_DETACH; int ACT_HEADCRAB_CEILING_FALL; int ACT_HEADCRAB_CEILING_LAND; //----------------------------------------------------------------------------- // Skill settings. //----------------------------------------------------------------------------- ConVar sk_headcrab_health( "sk_headcrab_health","0"); ConVar sk_headcrab_fast_health( "sk_headcrab_fast_health","0"); ConVar sk_headcrab_poison_health( "sk_headcrab_poison_health","0"); ConVar sk_headcrab_melee_dmg( "sk_headcrab_melee_dmg","0"); ConVar sk_headcrab_poison_npc_damage( "sk_headcrab_poison_npc_damage", "0" ); BEGIN_DATADESC( CBaseHeadcrab ) // m_nGibCount - don't save DEFINE_FIELD( m_bHidden, FIELD_BOOLEAN ), DEFINE_FIELD( m_flTimeDrown, FIELD_TIME ), DEFINE_FIELD( m_bCommittedToJump, FIELD_BOOLEAN ), DEFINE_FIELD( m_vecCommittedJumpPos, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_flNextNPCThink, FIELD_TIME ), DEFINE_FIELD( m_flIgnoreWorldCollisionTime, FIELD_TIME ), DEFINE_KEYFIELD( m_bStartBurrowed, FIELD_BOOLEAN, "startburrowed" ), DEFINE_FIELD( m_bBurrowed, FIELD_BOOLEAN ), DEFINE_FIELD( m_flBurrowTime, FIELD_TIME ), DEFINE_FIELD( m_nContext, FIELD_INTEGER ), DEFINE_FIELD( m_bCrawlFromCanister, FIELD_BOOLEAN ), DEFINE_FIELD( m_bMidJump, FIELD_BOOLEAN ), DEFINE_FIELD( m_nJumpFromCanisterDir, FIELD_INTEGER ), DEFINE_FIELD( m_bHangingFromCeiling, FIELD_BOOLEAN ), DEFINE_FIELD( m_flIlluminatedTime, FIELD_TIME ), DEFINE_INPUTFUNC( FIELD_VOID, "Burrow", InputBurrow ), DEFINE_INPUTFUNC( FIELD_VOID, "BurrowImmediate", InputBurrowImmediate ), DEFINE_INPUTFUNC( FIELD_VOID, "Unburrow", InputUnburrow ), DEFINE_INPUTFUNC( FIELD_VOID, "StartHangingFromCeiling", InputStartHangingFromCeiling ), DEFINE_INPUTFUNC( FIELD_VOID, "DropFromCeiling", InputDropFromCeiling ), // Function Pointers DEFINE_THINKFUNC( EliminateRollAndPitch ), DEFINE_THINKFUNC( ThrowThink ), DEFINE_ENTITYFUNC( LeapTouch ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseHeadcrab::Spawn( void ) { //Precache(); //SetModel( "models/headcrab.mdl" ); //m_iHealth = sk_headcrab_health.GetFloat(); #ifdef _XBOX // Always fade the corpse AddSpawnFlags( SF_NPC_FADE_CORPSE ); #endif // _XBOX SetHullType(HULL_TINY); SetHullSizeNormal(); SetSolid( SOLID_BBOX ); AddSolidFlags( FSOLID_NOT_STANDABLE ); SetMoveType( MOVETYPE_STEP ); SetCollisionGroup( HL2COLLISION_GROUP_HEADCRAB ); SetViewOffset( Vector(6, 0, 11) ) ; // Position of the eyes relative to NPC's origin. SetBloodColor( BLOOD_COLOR_GREEN ); m_flFieldOfView = 0.5; m_NPCState = NPC_STATE_NONE; m_nGibCount = HEADCRAB_ALL_GIB_COUNT; // Are we starting hidden? if ( m_spawnflags & SF_HEADCRAB_START_HIDDEN ) { m_bHidden = true; AddSolidFlags( FSOLID_NOT_SOLID ); SetRenderColorA( 0 ); m_nRenderMode = kRenderTransTexture; AddEffects( EF_NODRAW ); } else { m_bHidden = false; } CapabilitiesClear(); CapabilitiesAdd( bits_CAP_MOVE_GROUND | bits_CAP_INNATE_RANGE_ATTACK1 ); CapabilitiesAdd( bits_CAP_SQUAD ); // headcrabs get to cheat for 5 seconds (sjb) GetEnemies()->SetFreeKnowledgeDuration( 5.0 ); m_bHangingFromCeiling = false; m_flIlluminatedTime = -1; } //----------------------------------------------------------------------------- // Purpose: Stuff that must happen after NPCInit is called. //----------------------------------------------------------------------------- void CBaseHeadcrab::HeadcrabInit() { // See if we're supposed to start burrowed if ( m_bStartBurrowed ) { SetBurrowed( true ); SetSchedule( SCHED_HEADCRAB_BURROW_WAIT ); } if ( GetSpawnFlags() & SF_HEADCRAB_START_HANGING ) { SetSchedule( SCHED_HEADCRAB_CEILING_WAIT ); m_flIlluminatedTime = -1; } } //----------------------------------------------------------------------------- // Purpose: Precaches all resources this monster needs. //----------------------------------------------------------------------------- void CBaseHeadcrab::Precache( void ) { BaseClass::Precache(); } //----------------------------------------------------------------------------- // The headcrab will crawl from the cannister, then jump to a burrow point //----------------------------------------------------------------------------- void CBaseHeadcrab::CrawlFromCanister() { // This is necessary to prevent ground computations, etc. from happening // while the crawling animation is occuring AddFlag( FL_FLY ); m_bCrawlFromCanister = true; SetNextThink( gpGlobals->curtime ); } //----------------------------------------------------------------------------- // Purpose: // Input : NewActivity - //----------------------------------------------------------------------------- void CBaseHeadcrab::OnChangeActivity( Activity NewActivity ) { bool fRandomize = false; float flRandomRange = 0.0; // If this crab is starting to walk or idle, pick a random point within // the animation to begin. This prevents lots of crabs being in lockstep. if ( NewActivity == ACT_IDLE ) { flRandomRange = 0.75; fRandomize = true; } else if ( NewActivity == ACT_RUN ) { flRandomRange = 0.25; fRandomize = true; } BaseClass::OnChangeActivity( NewActivity ); if( fRandomize ) { SetCycle( random->RandomFloat( 0.0, flRandomRange ) ); } } //----------------------------------------------------------------------------- // Purpose: Indicates this monster's place in the relationship table. // Output : //----------------------------------------------------------------------------- Class_T CBaseHeadcrab::Classify( void ) { if( m_bHidden ) { // Effectively invisible to other AI's while hidden. return( CLASS_NONE ); } else { return( CLASS_HEADCRAB ); } } //----------------------------------------------------------------------------- // Purpose: // Input : &posSrc - // Output : Vector //----------------------------------------------------------------------------- Vector CBaseHeadcrab::BodyTarget( const Vector &posSrc, bool bNoisy ) { Vector vecResult; vecResult = GetAbsOrigin(); vecResult.z += 6; return vecResult; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- float CBaseHeadcrab::GetAutoAimRadius() { if( g_pGameRules->GetAutoAimMode() == AUTOAIM_ON_CONSOLE ) { return 24.0f; } return 12.0f; } //----------------------------------------------------------------------------- // Purpose: Allows each sequence to have a different turn rate associated with it. // Output : float //----------------------------------------------------------------------------- float CBaseHeadcrab::MaxYawSpeed( void ) { return BaseClass::MaxYawSpeed(); } //----------------------------------------------------------------------------- // Because the AI code does a tracehull to find the ground under an NPC, headcrabs // can often be seen standing with one edge of their box perched on a ledge and // 80% or more of their body hanging out over nothing. This is often a case // where a headcrab will be unable to pathfind out of its location. This heuristic // very crudely tries to determine if this is the case by casting a simple ray // down from the center of the headcrab. //----------------------------------------------------------------------------- #define HEADCRAB_MAX_LEDGE_HEIGHT 12.0f bool CBaseHeadcrab::IsFirmlyOnGround() { if( !(GetFlags()&FL_ONGROUND) ) return false; trace_t tr; UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() - Vector( 0, 0, HEADCRAB_MAX_LEDGE_HEIGHT ), MASK_NPCSOLID, this, GetCollisionGroup(), &tr ); return tr.fraction != 1.0; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CBaseHeadcrab::MoveOrigin( const Vector &vecDelta ) { UTIL_SetOrigin( this, GetLocalOrigin() + vecDelta ); } //----------------------------------------------------------------------------- // Purpose: // Input : vecPos - //----------------------------------------------------------------------------- void CBaseHeadcrab::ThrowAt( const Vector &vecPos ) { JumpAttack( false, vecPos, true ); } //----------------------------------------------------------------------------- // Purpose: // Input : vecPos - //----------------------------------------------------------------------------- void CBaseHeadcrab::JumpToBurrowHint( CAI_Hint *pHint ) { Vector vecVel = VecCheckToss( this, GetAbsOrigin(), pHint->GetAbsOrigin(), 0.5f, 1.0f, false, NULL, NULL ); // Undershoot by a little because it looks bad if we overshoot and turn around to burrow. vecVel *= 0.9f; Leap( vecVel ); GrabHintNode( pHint ); } //----------------------------------------------------------------------------- // Purpose: // Input : vecVel - //----------------------------------------------------------------------------- void CBaseHeadcrab::Leap( const Vector &vecVel ) { SetTouch( &CBaseHeadcrab::LeapTouch ); SetCondition( COND_FLOATING_OFF_GROUND ); SetGroundEntity( NULL ); m_flIgnoreWorldCollisionTime = gpGlobals->curtime + HEADCRAB_IGNORE_WORLD_COLLISION_TIME; if( HasHeadroom() ) { // Take him off ground so engine doesn't instantly reset FL_ONGROUND. MoveOrigin( Vector( 0, 0, 1 ) ); } SetAbsVelocity( vecVel ); // Think every frame so the player sees the headcrab where he actually is... m_bMidJump = true; SetThink( &CBaseHeadcrab::ThrowThink ); SetNextThink( gpGlobals->curtime ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseHeadcrab::ThrowThink( void ) { if (gpGlobals->curtime > m_flNextNPCThink) { NPCThink(); m_flNextNPCThink = gpGlobals->curtime + 0.1; } if( GetFlags() & FL_ONGROUND ) { SetThink( &CBaseHeadcrab::CallNPCThink ); SetNextThink( gpGlobals->curtime + 0.1 ); return; } SetNextThink( gpGlobals->curtime ); } //----------------------------------------------------------------------------- // Purpose: Does a jump attack at the given position. // Input : bRandomJump - Just hop in a random direction. // vecPos - Position to jump at, ignored if bRandom is set to true. // bThrown - //----------------------------------------------------------------------------- void CBaseHeadcrab::JumpAttack( bool bRandomJump, const Vector &vecPos, bool bThrown ) { Vector vecJumpVel; if ( !bRandomJump ) { float gravity = sv_gravity.GetFloat(); if ( gravity <= 1 ) { gravity = 1; } // How fast does the headcrab need to travel to reach the position given gravity? float flActualHeight = vecPos.z - GetAbsOrigin().z; float height = flActualHeight; if ( height < 16 ) { height = 16; } else { float flMaxHeight = bThrown ? 400 : 120; if ( height > flMaxHeight ) { height = flMaxHeight; } } // overshoot the jump by an additional 8 inches // NOTE: This calculation jumps at a position INSIDE the box of the enemy (player) // so if you make the additional height too high, the crab can land on top of the // enemy's head. If we want to jump high, we'll need to move vecPos to the surface/outside // of the enemy's box. float additionalHeight = 0; if ( height < 32 ) { additionalHeight = 8; } height += additionalHeight; // NOTE: This equation here is from vf^2 = vi^2 + 2*a*d float speed = sqrt( 2 * gravity * height ); float time = speed / gravity; // add in the time it takes to fall the additional height // So the impact takes place on the downward slope at the original height time += sqrt( (2 * additionalHeight) / gravity ); // Scale the sideways velocity to get there at the right time VectorSubtract( vecPos, GetAbsOrigin(), vecJumpVel ); vecJumpVel /= time; // Speed to offset gravity at the desired height. vecJumpVel.z = speed; // Don't jump too far/fast. float flJumpSpeed = vecJumpVel.Length(); float flMaxSpeed = bThrown ? 1000.0f : 650.0f; if ( flJumpSpeed > flMaxSpeed ) { vecJumpVel *= flMaxSpeed / flJumpSpeed; } } else { // // Jump hop, don't care where. // Vector forward, up; AngleVectors( GetLocalAngles(), &forward, NULL, &up ); vecJumpVel = Vector( forward.x, forward.y, up.z ) * 350; } AttackSound(); Leap( vecJumpVel ); } //----------------------------------------------------------------------------- // Purpose: Catches the monster-specific messages that occur when tagged // animation frames are played. // Input : *pEvent - //----------------------------------------------------------------------------- void CBaseHeadcrab::HandleAnimEvent( animevent_t *pEvent ) { if ( pEvent->event == AE_HEADCRAB_JUMPATTACK ) { // Ignore if we're in mid air if ( m_bMidJump ) return; CBaseEntity *pEnemy = GetEnemy(); if ( pEnemy ) { if ( m_bCommittedToJump ) { JumpAttack( false, m_vecCommittedJumpPos ); } else { // Jump at my enemy's eyes. JumpAttack( false, pEnemy->EyePosition() ); } m_bCommittedToJump = false; } else { // Jump hop, don't care where. JumpAttack( true ); } return; } if ( pEvent->event == AE_HEADCRAB_CEILING_DETACH ) { SetMoveType( MOVETYPE_STEP ); RemoveFlag( FL_ONGROUND ); RemoveFlag( FL_FLY ); SetAbsVelocity( Vector ( 0, 0, -128 ) ); return; } if ( pEvent->event == AE_HEADCRAB_JUMP_TELEGRAPH ) { TelegraphSound(); CBaseEntity *pEnemy = GetEnemy(); if ( pEnemy ) { // Once we telegraph, we MUST jump. This is also when commit to what point // we jump at. Jump at our enemy's eyes. m_vecCommittedJumpPos = pEnemy->EyePosition(); m_bCommittedToJump = true; } return; } if ( pEvent->event == AE_HEADCRAB_BURROW_IN ) { EmitSound( "NPC_Headcrab.BurrowIn" ); CreateDust(); return; } if ( pEvent->event == AE_HEADCRAB_BURROW_IN_FINISH ) { SetBurrowed( true ); return; } if ( pEvent->event == AE_HEADCRAB_BURROW_OUT ) { Assert( m_bBurrowed ); if ( m_bBurrowed ) { EmitSound( "NPC_Headcrab.BurrowOut" ); CreateDust(); SetBurrowed( false ); // We're done with this burrow hint node. It might be NULL here // because we may have started burrowed (no hint node in that case). GrabHintNode( NULL ); } return; } CAI_BaseNPC::HandleAnimEvent( pEvent ); } //----------------------------------------------------------------------------- // Purpose: Does all the fixup for going to/from the burrowed state. //----------------------------------------------------------------------------- void CBaseHeadcrab::SetBurrowed( bool bBurrowed ) { if ( bBurrowed ) { AddEffects( EF_NODRAW ); AddFlag( FL_NOTARGET ); m_spawnflags |= SF_NPC_GAG; AddSolidFlags( FSOLID_NOT_SOLID ); m_takedamage = DAMAGE_NO; m_flFieldOfView = HEADCRAB_BURROWED_FOV; SetState( NPC_STATE_IDLE ); SetActivity( (Activity) ACT_HEADCRAB_BURROW_IDLE ); } else { RemoveEffects( EF_NODRAW ); RemoveFlag( FL_NOTARGET ); m_spawnflags &= ~SF_NPC_GAG; RemoveSolidFlags( FSOLID_NOT_SOLID ); m_takedamage = DAMAGE_YES; m_flFieldOfView = HEADCRAB_UNBURROWED_FOV; } m_bBurrowed = bBurrowed; } //----------------------------------------------------------------------------- // Purpose: // Input : *pTask - //----------------------------------------------------------------------------- void CBaseHeadcrab::RunTask( const Task_t *pTask ) { switch ( pTask->iTask ) { case TASK_HEADCRAB_CLIMB_FROM_CANISTER: AutoMovement( ); if ( IsActivityFinished() ) { TaskComplete(); } break; case TASK_HEADCRAB_JUMP_FROM_CANISTER: GetMotor()->UpdateYaw(); if ( FacingIdeal() ) { TaskComplete(); } break; case TASK_HEADCRAB_WAIT_FOR_BARNACLE_KILL: if ( m_flNextFlinchTime < gpGlobals->curtime ) { m_flNextFlinchTime = gpGlobals->curtime + random->RandomFloat( 1.0f, 2.0f ); CTakeDamageInfo info; PainSound( info ); } break; case TASK_HEADCRAB_HOP_OFF_NPC: if( GetFlags() & FL_ONGROUND ) { TaskComplete(); } else { // Face the direction I've been forced to jump. GetMotor()->SetIdealYawToTargetAndUpdate( GetAbsOrigin() + GetAbsVelocity() ); } break; case TASK_HEADCRAB_DROWN: if( gpGlobals->curtime > m_flTimeDrown ) { OnTakeDamage( CTakeDamageInfo( this, this, m_iHealth * 2, DMG_DROWN ) ); } break; case TASK_RANGE_ATTACK1: case TASK_RANGE_ATTACK2: case TASK_HEADCRAB_HARASS_HOP: { if ( IsActivityFinished() ) { TaskComplete(); m_bMidJump = false; SetTouch( NULL ); SetThink( &CBaseHeadcrab::CallNPCThink ); SetIdealActivity( ACT_IDLE ); if ( m_bAttackFailed ) { // our attack failed because we just ran into something solid. // delay attacking for a while so we don't just repeatedly leap // at the enemy from a bad location. m_bAttackFailed = false; m_flNextAttack = gpGlobals->curtime + 1.2f; } } break; } case TASK_HEADCRAB_CHECK_FOR_UNBURROW: { // Must wait for our next check time if ( m_flBurrowTime > gpGlobals->curtime ) return; // See if we can pop up if ( ValidBurrowPoint( GetAbsOrigin() ) ) { m_spawnflags &= ~SF_NPC_GAG; RemoveSolidFlags( FSOLID_NOT_SOLID ); TaskComplete(); return; } // Try again in a couple of seconds m_flBurrowTime = gpGlobals->curtime + random->RandomFloat( 0.5f, 1.0f ); break; } case TASK_HEADCRAB_BURROW_WAIT: { if ( HasCondition( COND_CAN_RANGE_ATTACK1 ) || HasCondition( COND_CAN_RANGE_ATTACK2 ) ) { TaskComplete(); } break; } case TASK_HEADCRAB_CEILING_WAIT: { #ifdef HL2_EPISODIC if ( DarknessLightSourceWithinRadius( this, DARKNESS_LIGHTSOURCE_SIZE ) ) { DropFromCeiling(); } #endif if ( HasCondition( COND_CAN_RANGE_ATTACK1 ) || HasCondition( COND_CAN_RANGE_ATTACK2 ) ) { TaskComplete(); } break; } case TASK_HEADCRAB_CEILING_DETACH: { if ( IsActivityFinished() ) { ClearCondition( COND_CAN_RANGE_ATTACK1 ); RemoveFlag(FL_FLY); TaskComplete(); } } break; case TASK_HEADCRAB_CEILING_FALL: { Vector vecPrPos; trace_t tr; //Figure out where the headcrab is going to be in quarter of a second. vecPrPos = GetAbsOrigin() + ( GetAbsVelocity() * 0.25f ); UTIL_TraceHull( vecPrPos, vecPrPos, GetHullMins(), GetHullMaxs(), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr ); if ( tr.startsolid == true || GetFlags() & FL_ONGROUND ) { RemoveSolidFlags( FSOLID_NOT_SOLID ); TaskComplete(); } } break; case TASK_HEADCRAB_CEILING_LAND: { if ( IsActivityFinished() ) { RemoveSolidFlags( FSOLID_NOT_SOLID ); //double-dog verify that we're solid. TaskComplete(); m_bHangingFromCeiling = false; } } break; default: { BaseClass::RunTask( pTask ); } } } //----------------------------------------------------------------------------- // Before jumping, headcrabs usually use SetOrigin() to lift themselves off the // ground. If the headcrab doesn't have the clearance to so, they'll be stuck // in the world. So this function makes sure there's headroom first. //----------------------------------------------------------------------------- bool CBaseHeadcrab::HasHeadroom() { trace_t tr; UTIL_TraceEntity( this, GetAbsOrigin(), GetAbsOrigin() + Vector( 0, 0, 1 ), MASK_NPCSOLID, this, GetCollisionGroup(), &tr ); #if 0 if( tr.fraction == 1.0f ) { Msg("Headroom\n"); } else { Msg("NO Headroom\n"); } #endif return (tr.fraction == 1.0); } //----------------------------------------------------------------------------- // Purpose: LeapTouch - this is the headcrab's touch function when it is in the air. // Input : *pOther - //----------------------------------------------------------------------------- void CBaseHeadcrab::LeapTouch( CBaseEntity *pOther ) { m_bMidJump = false; if ( IRelationType( pOther ) == D_HT ) { // Don't hit if back on ground if ( !( GetFlags() & FL_ONGROUND ) ) { if ( pOther->m_takedamage != DAMAGE_NO ) { BiteSound(); TouchDamage( pOther ); // attack succeeded, so don't delay our next attack if we previously thought we failed m_bAttackFailed = false; } else { ImpactSound(); } } else { ImpactSound(); } } else if( !(GetFlags() & FL_ONGROUND) ) { // Still in the air... if( !pOther->IsSolid() ) { // Touching a trigger or something. return; } // just ran into something solid, so the attack probably failed. make a note of it // so that when the attack is done, we'll delay attacking for a while so we don't // just repeatedly leap at the enemy from a bad location. m_bAttackFailed = true; if( gpGlobals->curtime < m_flIgnoreWorldCollisionTime ) { // Headcrabs try to ignore the world, static props, and friends for a // fraction of a second after they jump. This is because they often brush // doorframes or props as they leap, and touching those objects turns off // this touch function, which can cause them to hit the player and not bite. // A timer probably isn't the best way to fix this, but it's one of our // safer options at this point (sjb). return; } } // Shut off the touch function. SetTouch( NULL ); SetThink ( &CBaseHeadcrab::CallNPCThink ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CBaseHeadcrab::CalcDamageInfo( CTakeDamageInfo *pInfo ) { pInfo->Set( this, this, sk_headcrab_melee_dmg.GetFloat(), DMG_SLASH ); CalculateMeleeDamageForce( pInfo, GetAbsVelocity(), GetAbsOrigin() ); return pInfo->GetDamage(); } //----------------------------------------------------------------------------- // Purpose: Deal the damage from the headcrab's touch attack. //----------------------------------------------------------------------------- void CBaseHeadcrab::TouchDamage( CBaseEntity *pOther ) { CTakeDamageInfo info; CalcDamageInfo( &info ); pOther->TakeDamage( info ); } //--------------------------------------------------------- //--------------------------------------------------------- void CBaseHeadcrab::GatherConditions( void ) { // If we're hidden, just check to see if we should unhide if ( m_bHidden ) { // See if there's enough room for our hull to fit here. If so, unhide. trace_t tr; AI_TraceHull( GetAbsOrigin(), GetAbsOrigin(),GetHullMins(), GetHullMaxs(), MASK_SHOT, this, GetCollisionGroup(), &tr ); if ( tr.fraction == 1.0 ) { SetCondition( COND_PROVOKED ); SetCondition( COND_HEADCRAB_UNHIDE ); if ( g_debug_headcrab.GetInt() == HEADCRAB_DEBUG_HIDING ) { NDebugOverlay::Box( GetAbsOrigin(), GetHullMins(), GetHullMaxs(), 0,255,0, true, 1.0 ); } } else if ( g_debug_headcrab.GetInt() == HEADCRAB_DEBUG_HIDING ) { NDebugOverlay::Box( GetAbsOrigin(), GetHullMins(), GetHullMaxs(), 255,0,0, true, 0.1 ); } // Prevent baseclass thinking, so we don't respond to enemy fire, etc. return; } BaseClass::GatherConditions(); if( m_lifeState == LIFE_ALIVE && GetWaterLevel() > 1 ) { // Start Drowning! SetCondition( COND_HEADCRAB_IN_WATER ); } // See if I've landed on an NPC or player or something else illegal ClearCondition( COND_HEADCRAB_ILLEGAL_GROUNDENT ); CBaseEntity *ground = GetGroundEntity(); if( (GetFlags() & FL_ONGROUND) && ground && !ground->IsWorld() ) { if ( IsHangingFromCeiling() == false ) { if( ( ground->IsNPC() || ground->IsPlayer() ) ) { SetCondition( COND_HEADCRAB_ILLEGAL_GROUNDENT ); } else if( ground->VPhysicsGetObject() && (ground->VPhysicsGetObject()->GetGameFlags() & FVPHYSICS_PLAYER_HELD) ) { SetCondition( COND_HEADCRAB_ILLEGAL_GROUNDENT ); } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseHeadcrab::PrescheduleThink( void ) { BaseClass::PrescheduleThink(); // Are we fading in after being hidden? if ( !m_bHidden && (m_nRenderMode != kRenderNormal) ) { int iNewAlpha = min( 255, GetRenderColor().a + 120 ); if ( iNewAlpha >= 255 ) { m_nRenderMode = kRenderNormal; SetRenderColorA( 0 ); } else { SetRenderColorA( iNewAlpha ); } } // // Make the crab coo a little bit in combat state. // if (( m_NPCState == NPC_STATE_COMBAT ) && ( random->RandomFloat( 0, 5 ) < 0.1 )) { IdleSound(); } // Make sure we've turned off our burrow state if we're not in it Activity eActivity = GetActivity(); if ( m_bBurrowed && ( eActivity != ACT_HEADCRAB_BURROW_IDLE ) && ( eActivity != ACT_HEADCRAB_BURROW_OUT ) && ( eActivity != ACT_HEADCRAB_BURROW_IN) ) { DevMsg( "Headcrab failed to unburrow properly!\n" ); Assert( 0 ); SetBurrowed( false ); } } //----------------------------------------------------------------------------- // Eliminates roll + pitch from the headcrab //----------------------------------------------------------------------------- #define HEADCRAB_ROLL_ELIMINATION_TIME 0.3f #define HEADCRAB_PITCH_ELIMINATION_TIME 0.3f //----------------------------------------------------------------------------- // Eliminates roll + pitch potentially in the headcrab at canister jump time //----------------------------------------------------------------------------- void CBaseHeadcrab::EliminateRollAndPitch() { QAngle angles = GetAbsAngles(); angles.x = AngleNormalize( angles.x ); angles.z = AngleNormalize( angles.z ); if ( ( angles.x == 0.0f ) && ( angles.z == 0.0f ) ) return; float flPitchRate = 90.0f / HEADCRAB_PITCH_ELIMINATION_TIME; float flPitchDelta = flPitchRate * TICK_INTERVAL; if ( fabs( angles.x ) <= flPitchDelta ) { angles.x = 0.0f; } else { flPitchDelta *= (angles.x > 0.0f) ? -1.0f : 1.0f; angles.x += flPitchDelta; } float flRollRate = 180.0f / HEADCRAB_ROLL_ELIMINATION_TIME; float flRollDelta = flRollRate * TICK_INTERVAL; if ( fabs( angles.z ) <= flRollDelta ) { angles.z = 0.0f; } else { flRollDelta *= (angles.z > 0.0f) ? -1.0f : 1.0f; angles.z += flRollDelta; } SetAbsAngles( angles ); SetContextThink( &CBaseHeadcrab::EliminateRollAndPitch, gpGlobals->curtime + TICK_INTERVAL, s_pPitchContext ); } //----------------------------------------------------------------------------- // Begins the climb from the canister //----------------------------------------------------------------------------- void CBaseHeadcrab::BeginClimbFromCanister() { Assert( GetMoveParent() ); // Compute a desired position or hint Vector vecForward, vecActualForward; AngleVectors( GetMoveParent()->GetAbsAngles(), &vecActualForward ); vecForward = vecActualForward; vecForward.z = 0.0f; VectorNormalize( vecForward ); Vector vecSearchCenter = GetAbsOrigin(); CAI_Hint *pHint = CAI_HintManager::FindHint( this, HINT_HEADCRAB_BURROW_POINT, 0, HEADCRAB_BURROW_POINT_SEARCH_RADIUS, &vecSearchCenter ); if( !pHint && hl2_episodic.GetBool() ) { // Look for exit points within 10 feet. pHint = CAI_HintManager::FindHint( this, HINT_HEADCRAB_EXIT_POD_POINT, 0, 120.0f, &vecSearchCenter ); } if ( pHint && ( !pHint->IsLocked() ) ) { // Claim the hint node so other headcrabs don't try to take it! GrabHintNode( pHint ); // Compute relative yaw.. Vector vecDelta; VectorSubtract( pHint->GetAbsOrigin(), vecSearchCenter, vecDelta ); vecDelta.z = 0.0f; VectorNormalize( vecDelta ); float flAngle = DotProduct( vecDelta, vecForward ); if ( flAngle >= 0.707f ) { m_nJumpFromCanisterDir = 1; } else { // Check the cross product to see if it's on the left or right. // All we care about is the sign of the z component. If it's +, the hint is on the left. // If it's -, then the hint is on the right. float flCrossZ = vecForward.x * vecDelta.y - vecDelta.x * vecForward.y; m_nJumpFromCanisterDir = ( flCrossZ > 0 ) ? 0 : 2; } } else { // Choose a random direction (forward, left, or right) m_nJumpFromCanisterDir = random->RandomInt( 0, 2 ); } Activity act; switch( m_nJumpFromCanisterDir ) { case 0: act = (Activity)ACT_HEADCRAB_CRAWL_FROM_CANISTER_LEFT; break; default: case 1: act = (Activity)ACT_HEADCRAB_CRAWL_FROM_CANISTER_CENTER; break; case 2: act = (Activity)ACT_HEADCRAB_CRAWL_FROM_CANISTER_RIGHT; break; } SetIdealActivity( act ); } //----------------------------------------------------------------------------- // Jumps from the canister //----------------------------------------------------------------------------- #define HEADCRAB_ATTACK_PLAYER_FROM_CANISTER_DIST 250.0f #define HEADCRAB_ATTACK_PLAYER_FROM_CANISTER_COSANGLE 0.866f void CBaseHeadcrab::JumpFromCanister() { Assert( GetMoveParent() ); Vector vecForward, vecActualForward, vecActualRight; AngleVectors( GetMoveParent()->GetAbsAngles(), &vecActualForward, &vecActualRight, NULL ); switch( m_nJumpFromCanisterDir ) { case 0: VectorMultiply( vecActualRight, -1.0f, vecForward ); break; case 1: vecForward = vecActualForward; break; case 2: vecForward = vecActualRight; break; } vecForward.z = 0.0f; VectorNormalize( vecForward ); QAngle headCrabAngles; VectorAngles( vecForward, headCrabAngles ); SetActivity( ACT_RANGE_ATTACK1 ); StudioFrameAdvanceManual( 0.0 ); SetParent( NULL ); RemoveFlag( FL_FLY ); AddEffects( EF_NOINTERP ); GetMotor()->SetIdealYaw( headCrabAngles.y ); // Check to see if the player is within jump range. If so, jump at him! bool bJumpedAtEnemy = false; // FIXME: Can't use GetEnemy() here because enemy only updates during // schedules which are interruptible by COND_NEW_ENEMY or COND_LOST_ENEMY CBaseEntity *pEnemy = BestEnemy(); if ( pEnemy ) { Vector vecDirToEnemy; VectorSubtract( pEnemy->GetAbsOrigin(), GetAbsOrigin(), vecDirToEnemy ); vecDirToEnemy.z = 0.0f; float flDist = VectorNormalize( vecDirToEnemy ); if ( ( flDist < HEADCRAB_ATTACK_PLAYER_FROM_CANISTER_DIST ) && ( DotProduct( vecDirToEnemy, vecForward ) >= HEADCRAB_ATTACK_PLAYER_FROM_CANISTER_COSANGLE ) ) { GrabHintNode( NULL ); JumpAttack( false, pEnemy->EyePosition(), false ); bJumpedAtEnemy = true; } } if ( !bJumpedAtEnemy ) { if ( GetHintNode() ) { JumpToBurrowHint( GetHintNode() ); } else { vecForward *= 100.0f; vecForward += GetAbsOrigin(); JumpAttack( false, vecForward, false ); } } EliminateRollAndPitch(); } #define HEADCRAB_ILLUMINATED_TIME 0.15f void CBaseHeadcrab::DropFromCeiling( void ) { if ( HL2GameRules()->IsAlyxInDarknessMode() ) { if ( IsHangingFromCeiling() ) { if ( m_flIlluminatedTime == -1 ) { m_flIlluminatedTime = gpGlobals->curtime + HEADCRAB_ILLUMINATED_TIME; return; } if ( m_flIlluminatedTime <= gpGlobals->curtime ) { if ( IsCurSchedule( SCHED_HEADCRAB_CEILING_DROP ) == false ) { SetSchedule( SCHED_HEADCRAB_CEILING_DROP ); ////// // SO2 - James // Fix various NPC-related issues and bugs in multiplayer // http://developer.valvesoftware.com/wiki/Fixing_AI_in_multiplayer#Patch //CBaseEntity *pPlayer = AI_GetSinglePlayer(); CBaseEntity *pPlayer = UTIL_GetNearestPlayer( GetAbsOrigin() ); ////// if ( pPlayer ) { SetEnemy( pPlayer ); //Is this a bad thing to do? UpdateEnemyMemory( pPlayer, pPlayer->GetAbsOrigin()); } } } } } } //----------------------------------------------------------------------------- // Purpose: Player has illuminated this NPC with the flashlight //----------------------------------------------------------------------------- void CBaseHeadcrab::PlayerHasIlluminatedNPC( CBasePlayer *pPlayer, float flDot ) { if ( flDot < 0.97387f ) return; DropFromCeiling(); } bool CBaseHeadcrab::CanBeAnEnemyOf( CBaseEntity *pEnemy ) { #ifdef HL2_EPISODIC if ( IsHangingFromCeiling() ) return false; #endif return BaseClass::CanBeAnEnemyOf( pEnemy ); } //----------------------------------------------------------------------------- // Purpose: // Input : pTask - //----------------------------------------------------------------------------- void CBaseHeadcrab::StartTask( const Task_t *pTask ) { switch ( pTask->iTask ) { case TASK_HEADCRAB_WAIT_FOR_BARNACLE_KILL: break; case TASK_HEADCRAB_BURROW_WAIT: break; case TASK_HEADCRAB_CLIMB_FROM_CANISTER: BeginClimbFromCanister(); break; case TASK_HEADCRAB_JUMP_FROM_CANISTER: JumpFromCanister(); break; case TASK_HEADCRAB_CEILING_POSITION: { trace_t tr; UTIL_TraceHull( GetAbsOrigin(), GetAbsOrigin() + Vector( 0, 0, 512 ), NAI_Hull::Mins( GetHullType() ), NAI_Hull::Maxs( GetHullType() ), MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr ); // SetMoveType( MOVETYPE_NONE ); AddFlag(FL_FLY); m_bHangingFromCeiling = true; //Don't need this anymore RemoveSpawnFlags( SF_HEADCRAB_START_HANGING ); SetAbsOrigin( tr.endpos ); TaskComplete(); } break; case TASK_HEADCRAB_CEILING_WAIT: break; case TASK_HEADCRAB_CEILING_DETACH: { SetIdealActivity( (Activity)ACT_HEADCRAB_CEILING_DETACH ); } break; case TASK_HEADCRAB_CEILING_FALL: { SetIdealActivity( (Activity)ACT_HEADCRAB_CEILING_FALL ); } break; case TASK_HEADCRAB_CEILING_LAND: { SetIdealActivity( (Activity)ACT_HEADCRAB_CEILING_LAND ); } break; case TASK_HEADCRAB_HARASS_HOP: { // Just pop up into the air like you're trying to get at the // enemy, even though it's known you can't reach them. if ( GetEnemy() ) { Vector forward, up; GetVectors( &forward, NULL, &up ); m_vecCommittedJumpPos = GetAbsOrigin(); m_vecCommittedJumpPos += up * random->RandomFloat( 80, 150 ); m_vecCommittedJumpPos += forward * random->RandomFloat( 32, 80 ); m_bCommittedToJump = true; SetIdealActivity( ACT_RANGE_ATTACK1 ); } else { TaskFail( "No enemy" ); } } break; case TASK_HEADCRAB_HOP_OFF_NPC: { CBaseEntity *ground = GetGroundEntity(); if( ground ) { // If jumping off of a physics object that the player is holding, create a // solver to prevent the headcrab from colliding with that object for a // short time. if( ground && ground->VPhysicsGetObject() ) { if( ground->VPhysicsGetObject()->GetGameFlags() & FVPHYSICS_PLAYER_HELD ) { NPCPhysics_CreateSolver( this, ground, true, 0.5 ); } } Vector vecJumpDir; // Jump in some random direction. This way if the person I'm standing on is // against a wall, I'll eventually get away. vecJumpDir.z = 0; vecJumpDir.x = 0; vecJumpDir.y = 0; while( vecJumpDir.x == 0 && vecJumpDir.y == 0 ) { vecJumpDir.x = random->RandomInt( -1, 1 ); vecJumpDir.y = random->RandomInt( -1, 1 ); } vecJumpDir.NormalizeInPlace(); SetGroundEntity( NULL ); if( HasHeadroom() ) { // Bump up MoveOrigin( Vector( 0, 0, 1 ) ); } SetAbsVelocity( vecJumpDir * 200 + Vector( 0, 0, 200 ) ); } else { // *shrug* I guess they're gone now. Or dead. TaskComplete(); } } break; case TASK_HEADCRAB_DROWN: { // Set the gravity really low here! Sink slowly SetGravity( UTIL_ScaleForGravity( 80 ) ); m_flTimeDrown = gpGlobals->curtime + 4; break; } case TASK_RANGE_ATTACK1: { #ifdef WEDGE_FIX_THIS CPASAttenuationFilter filter( this, ATTN_IDLE ); EmitSound( filter, entindex(), CHAN_WEAPON, pAttackSounds[0], GetSoundVolume(), ATTN_IDLE, 0, GetVoicePitch() ); #endif SetIdealActivity( ACT_RANGE_ATTACK1 ); break; } case TASK_HEADCRAB_UNHIDE: { m_bHidden = false; RemoveSolidFlags( FSOLID_NOT_SOLID ); RemoveEffects( EF_NODRAW ); TaskComplete(); break; } case TASK_HEADCRAB_CHECK_FOR_UNBURROW: { if ( ValidBurrowPoint( GetAbsOrigin() ) ) { m_spawnflags &= ~SF_NPC_GAG; RemoveSolidFlags( FSOLID_NOT_SOLID ); TaskComplete(); } break; } case TASK_HEADCRAB_FIND_BURROW_IN_POINT: { if ( FindBurrow( GetAbsOrigin(), pTask->flTaskData, true ) == false ) { TaskFail( "TASK_HEADCRAB_FIND_BURROW_IN_POINT: Unable to find burrow in position\n" ); } else { TaskComplete(); } break; } case TASK_HEADCRAB_BURROW: { Burrow(); TaskComplete(); break; } case TASK_HEADCRAB_UNBURROW: { Unburrow(); TaskComplete(); break; } default: { BaseClass::StartTask( pTask ); } } } //----------------------------------------------------------------------------- // Purpose: For innate melee attack // Input : // Output : //----------------------------------------------------------------------------- float CBaseHeadcrab::InnateRange1MinRange( void ) { return HEADCRAB_MIN_JUMP_DIST; } float CBaseHeadcrab::InnateRange1MaxRange( void ) { return HEADCRAB_MAX_JUMP_DIST; } int CBaseHeadcrab::RangeAttack1Conditions( float flDot, float flDist ) { if ( gpGlobals->curtime < m_flNextAttack ) return 0; if ( ( GetFlags() & FL_ONGROUND ) == false ) return 0; // When we're burrowed ignore facing, because when we unburrow we'll cheat and face our enemy. if ( !m_bBurrowed && ( flDot < 0.65 ) ) return COND_NOT_FACING_ATTACK; // This code stops lots of headcrabs swarming you and blocking you // whilst jumping up and down in your face over and over. It forces // them to back up a bit. If this causes problems, consider using it // for the fast headcrabs only, rather than just removing it.(sjb) if ( flDist < HEADCRAB_MIN_JUMP_DIST ) return COND_TOO_CLOSE_TO_ATTACK; if ( flDist > HEADCRAB_MAX_JUMP_DIST ) return COND_TOO_FAR_TO_ATTACK; // Make sure the way is clear! CBaseEntity *pEnemy = GetEnemy(); if( pEnemy ) { bool bEnemyIsBullseye = ( dynamic_cast<CNPC_Bullseye *>(pEnemy) != NULL ); trace_t tr; AI_TraceLine( EyePosition(), pEnemy->EyePosition(), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr ); if ( tr.m_pEnt != GetEnemy() ) { if ( !bEnemyIsBullseye || tr.m_pEnt != NULL ) return COND_NONE; } if( GetEnemy()->EyePosition().z - 36.0f > GetAbsOrigin().z ) { // Only run this test if trying to jump at a player who is higher up than me, else this // code will always prevent a headcrab from jumping down at an enemy, and sometimes prevent it // jumping just slightly up at an enemy. Vector vStartHullTrace = GetAbsOrigin(); vStartHullTrace.z += 1.0; Vector vEndHullTrace = GetEnemy()->EyePosition() - GetAbsOrigin(); vEndHullTrace.NormalizeInPlace(); vEndHullTrace *= 8.0; vEndHullTrace += GetAbsOrigin(); AI_TraceHull( vStartHullTrace, vEndHullTrace,GetHullMins(), GetHullMaxs(), MASK_NPCSOLID, this, GetCollisionGroup(), &tr ); if ( tr.m_pEnt != NULL && tr.m_pEnt != GetEnemy() ) { return COND_TOO_CLOSE_TO_ATTACK; } } } return COND_CAN_RANGE_ATTACK1; } //------------------------------------------------------------------------------ // Purpose: Override to do headcrab specific gibs // Output : //------------------------------------------------------------------------------ bool CBaseHeadcrab::CorpseGib( const CTakeDamageInfo &info ) { EmitSound( "NPC_HeadCrab.Gib" ); return BaseClass::CorpseGib( info ); } //------------------------------------------------------------------------------ // Purpose: // Input : //------------------------------------------------------------------------------ void CBaseHeadcrab::Touch( CBaseEntity *pOther ) { // If someone has smacked me into a wall then gib! if (m_NPCState == NPC_STATE_DEAD) { if (GetAbsVelocity().Length() > 250) { trace_t tr; Vector vecDir = GetAbsVelocity(); VectorNormalize(vecDir); AI_TraceLine(GetAbsOrigin(), GetAbsOrigin() + vecDir * 100, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr); float dotPr = DotProduct(vecDir,tr.plane.normal); if ((tr.fraction != 1.0) && (dotPr < -0.8) ) { CTakeDamageInfo info( GetWorldEntity(), GetWorldEntity(), 100.0f, DMG_CRUSH ); info.SetDamagePosition( tr.endpos ); Event_Gibbed( info ); } } } BaseClass::Touch(pOther); } //----------------------------------------------------------------------------- // Purpose: // Input : pevInflictor - // pevAttacker - // flDamage - // bitsDamageType - // Output : //----------------------------------------------------------------------------- int CBaseHeadcrab::OnTakeDamage_Alive( const CTakeDamageInfo &inputInfo ) { CTakeDamageInfo info = inputInfo; // // Don't take any acid damage. // if ( info.GetDamageType() & DMG_ACID ) { info.SetDamage( 0 ); } // // Certain death from melee bludgeon weapons! // if ( info.GetDamageType() & DMG_CLUB ) { info.SetDamage( m_iHealth ); } if( info.GetDamageType() & DMG_BLAST ) { if( random->RandomInt( 0 , 1 ) == 0 ) { // Catch on fire randomly if damaged in a blast. Ignite( 30 ); } } if( info.GetDamageType() & DMG_BURN ) { // Slow down burn damage so that headcrabs live longer while on fire. info.ScaleDamage( 0.25 ); #define HEADCRAB_SCORCH_RATE 5 #define HEADCRAB_SCORCH_FLOOR 30 if( IsOnFire() ) { Scorch( HEADCRAB_SCORCH_RATE, HEADCRAB_SCORCH_FLOOR ); if( m_iHealth <= 1 && (entindex() % 2) ) { // Some headcrabs leap at you with their dying breath if( !IsCurSchedule( SCHED_HEADCRAB_RANGE_ATTACK1 ) && !IsRunningDynamicInteraction() ) { SetSchedule( SCHED_HEADCRAB_RANGE_ATTACK1 ); } } } Ignite( 30 ); } return CAI_BaseNPC::OnTakeDamage_Alive( info ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CBaseHeadcrab::ClampRagdollForce( const Vector &vecForceIn, Vector *vecForceOut ) { // Assumes the headcrab mass is 5kg (100 feet per second) float MAX_HEADCRAB_RAGDOLL_SPEED = 100.0f * 12.0f * 5.0f; Vector vecClampedForce; BaseClass::ClampRagdollForce( vecForceIn, &vecClampedForce ); // Copy the force to vecForceOut, in case we don't change it. *vecForceOut = vecClampedForce; float speed = VectorNormalize( vecClampedForce ); if( speed > MAX_HEADCRAB_RAGDOLL_SPEED ) { // Don't let the ragdoll go as fast as it was going to. vecClampedForce *= MAX_HEADCRAB_RAGDOLL_SPEED; *vecForceOut = vecClampedForce; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CBaseHeadcrab::Event_Killed( const CTakeDamageInfo &info ) { // Create a little decal underneath the headcrab // This type of damage combination happens from dynamic scripted sequences if ( info.GetDamageType() & (DMG_GENERIC | DMG_PREVENT_PHYSICS_FORCE) ) { trace_t tr; AI_TraceLine( GetAbsOrigin()+Vector(0,0,1), GetAbsOrigin()-Vector(0,0,64), MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr ); UTIL_DecalTrace( &tr, "YellowBlood" ); } BaseClass::Event_Killed( info ); } //----------------------------------------------------------------------------- // Purpose: // Input : Type - //----------------------------------------------------------------------------- int CBaseHeadcrab::TranslateSchedule( int scheduleType ) { switch( scheduleType ) { case SCHED_FALL_TO_GROUND: return SCHED_HEADCRAB_FALL_TO_GROUND; case SCHED_WAKE_ANGRY: { if ( HaveSequenceForActivity((Activity)ACT_HEADCRAB_THREAT_DISPLAY) ) return SCHED_HEADCRAB_WAKE_ANGRY; else return SCHED_HEADCRAB_WAKE_ANGRY_NO_DISPLAY; } case SCHED_RANGE_ATTACK1: return SCHED_HEADCRAB_RANGE_ATTACK1; case SCHED_FAIL_TAKE_COVER: return SCHED_ALERT_FACE; case SCHED_CHASE_ENEMY_FAILED: { if( !GetEnemy() ) break; if( !HasCondition( COND_SEE_ENEMY ) ) break; float flZDiff; flZDiff = GetEnemy()->GetAbsOrigin().z - GetAbsOrigin().z; // Make sure the enemy isn't so high above me that this would look silly. if( flZDiff < 128.0f || flZDiff > 512.0f ) return SCHED_COMBAT_PATROL; float flDist; flDist = ( GetEnemy()->GetAbsOrigin() - GetAbsOrigin() ).Length2D(); // Maybe a patrol will bring me closer. if( flDist > 384.0f ) { return SCHED_COMBAT_PATROL; } return SCHED_HEADCRAB_HARASS_ENEMY; } break; } return BaseClass::TranslateSchedule( scheduleType ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CBaseHeadcrab::SelectSchedule( void ) { if ( m_bCrawlFromCanister ) { m_bCrawlFromCanister = false; return SCHED_HEADCRAB_CRAWL_FROM_CANISTER; } // If we're hidden or waiting until seen, don't do much at all if ( m_bHidden || HasSpawnFlags(SF_NPC_WAIT_TILL_SEEN) ) { if( HasCondition( COND_HEADCRAB_UNHIDE ) ) { // We've decided to unhide return SCHED_HEADCRAB_UNHIDE; } return m_bBurrowed ? SCHED_HEADCRAB_BURROW_WAIT : SCHED_IDLE_STAND; } if ( GetSpawnFlags() & SF_HEADCRAB_START_HANGING && IsHangingFromCeiling() == false ) { return SCHED_HEADCRAB_CEILING_WAIT; } if ( IsHangingFromCeiling() ) { if ( HL2GameRules()->IsAlyxInDarknessMode() == false && ( HasCondition( COND_CAN_RANGE_ATTACK1 ) || HasCondition( COND_NEW_ENEMY ) ) ) return SCHED_HEADCRAB_CEILING_DROP; if ( HasCondition( COND_LIGHT_DAMAGE ) || HasCondition( COND_HEAVY_DAMAGE ) ) return SCHED_HEADCRAB_CEILING_DROP; return SCHED_HEADCRAB_CEILING_WAIT; } if ( m_bBurrowed ) { if ( HasCondition( COND_CAN_RANGE_ATTACK1 ) ) return SCHED_HEADCRAB_BURROW_OUT; return SCHED_HEADCRAB_BURROW_WAIT; } if( HasCondition( COND_HEADCRAB_IN_WATER ) ) { // No matter what, drown in water return SCHED_HEADCRAB_DROWN; } if( HasCondition( COND_HEADCRAB_ILLEGAL_GROUNDENT ) ) { // You're on an NPC's head. Get off. return SCHED_HEADCRAB_HOP_RANDOMLY; } if ( HasCondition( COND_HEADCRAB_BARNACLED ) ) { // Caught by a barnacle! return SCHED_HEADCRAB_BARNACLED; } switch ( m_NPCState ) { case NPC_STATE_ALERT: { if (HasCondition( COND_LIGHT_DAMAGE ) || HasCondition( COND_HEAVY_DAMAGE )) { if ( fabs( GetMotor()->DeltaIdealYaw() ) < ( 1.0 - m_flFieldOfView) * 60 ) // roughly in the correct direction { return SCHED_TAKE_COVER_FROM_ORIGIN; } else if ( SelectWeightedSequence( ACT_SMALL_FLINCH ) != -1 ) { m_flNextFlinchTime = gpGlobals->curtime + random->RandomFloat( 1, 3 ); return SCHED_SMALL_FLINCH; } } else if (HasCondition( COND_HEAR_DANGER ) || HasCondition( COND_HEAR_PLAYER ) || HasCondition( COND_HEAR_WORLD ) || HasCondition( COND_HEAR_COMBAT )) { return SCHED_ALERT_FACE_BESTSOUND; } else { return SCHED_PATROL_WALK; } break; } } if ( HasCondition( COND_FLOATING_OFF_GROUND ) ) { SetGravity( 1.0 ); SetGroundEntity( NULL ); return SCHED_FALL_TO_GROUND; } if ( GetHintNode() && GetHintNode()->HintType() == HINT_HEADCRAB_BURROW_POINT ) { // Only burrow if we're not within leap attack distance of our enemy. if ( ( GetEnemy() == NULL ) || ( ( GetEnemy()->GetAbsOrigin() - GetAbsOrigin() ).Length() > HEADCRAB_MAX_JUMP_DIST ) ) { return SCHED_HEADCRAB_RUN_TO_SPECIFIC_BURROW; } else { // Forget about burrowing, we've got folks to leap at! GrabHintNode( NULL ); } } int nSchedule = BaseClass::SelectSchedule(); if ( nSchedule == SCHED_SMALL_FLINCH ) { m_flNextFlinchTime = gpGlobals->curtime + random->RandomFloat( 1, 3 ); } return nSchedule; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CBaseHeadcrab::SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode ) { if ( failedSchedule == SCHED_BACK_AWAY_FROM_ENEMY && failedTask == TASK_FIND_BACKAWAY_FROM_SAVEPOSITION ) { if ( HasCondition( COND_SEE_ENEMY ) ) { return SCHED_RANGE_ATTACK1; } } if ( failedSchedule == SCHED_BACK_AWAY_FROM_ENEMY || failedSchedule == SCHED_PATROL_WALK || failedSchedule == SCHED_COMBAT_PATROL ) { if( !IsFirmlyOnGround() ) { return SCHED_HEADCRAB_HOP_RANDOMLY; } } return BaseClass::SelectFailSchedule( failedSchedule, failedTask, taskFailCode ); } //----------------------------------------------------------------------------- // Purpose: // Input : &info - // &vecDir - // *ptr - //----------------------------------------------------------------------------- void CBaseHeadcrab::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr ) { CTakeDamageInfo newInfo = info; // Ignore if we're in a dynamic scripted sequence if ( info.GetDamageType() & DMG_PHYSGUN && !IsRunningDynamicInteraction() ) { Vector puntDir = ( info.GetDamageForce() * 1000.0f ); newInfo.SetDamage( m_iMaxHealth / 3.0f ); if( info.GetDamage() >= GetHealth() ) { // This blow will be fatal, so scale the damage force // (it's a unit vector) so that the ragdoll will be // affected. newInfo.SetDamageForce( info.GetDamageForce() * 3000.0f ); } PainSound( newInfo ); SetGroundEntity( NULL ); ApplyAbsVelocityImpulse( puntDir ); } BaseClass::TraceAttack( newInfo, vecDir, ptr ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CBaseHeadcrab::Ignite( float flFlameLifetime, bool bNPCOnly, float flSize, bool bCalledByLevelDesigner ) { // Can't start on fire if we're burrowed if ( m_bBurrowed ) return; bool bWasOnFire = IsOnFire(); #ifdef HL2_EPISODIC if( GetHealth() > flFlameLifetime ) { // Add some burn time to very healthy headcrabs to fix a bug where // black headcrabs would sometimes spontaneously extinguish (and survive) flFlameLifetime += 10.0f; } #endif// HL2_EPISODIC BaseClass::Ignite( flFlameLifetime, bNPCOnly, flSize, bCalledByLevelDesigner ); if( !bWasOnFire ) { #ifdef HL2_EPISODIC if ( HL2GameRules()->IsAlyxInDarknessMode() == true ) { GetEffectEntity()->AddEffects( EF_DIMLIGHT ); } #endif // HL2_EPISODIC // For the poison headcrab, who runs around when ignited SetActivity( TranslateActivity(GetIdealActivity()) ); } } //----------------------------------------------------------------------------- // Purpose: This is a generic function (to be implemented by sub-classes) to // handle specific interactions between different types of characters // (For example the barnacle grabbing an NPC) // Input : Constant for the type of interaction // Output : true - if sub-class has a response for the interaction // false - if sub-class has no response //----------------------------------------------------------------------------- bool CBaseHeadcrab::HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt) { if (interactionType == g_interactionBarnacleVictimDangle) { // Die instantly return false; } else if (interactionType == g_interactionVortigauntStomp) { SetIdealState( NPC_STATE_PRONE ); return true; } else if (interactionType == g_interactionVortigauntStompFail) { SetIdealState( NPC_STATE_COMBAT ); return true; } else if (interactionType == g_interactionVortigauntStompHit) { // Gib the existing guy, but only with legs and guts m_nGibCount = HEADCRAB_LEGS_GIB_COUNT; OnTakeDamage ( CTakeDamageInfo( sourceEnt, sourceEnt, m_iHealth, DMG_CRUSH|DMG_ALWAYSGIB ) ); // Create dead headcrab in its place CBaseHeadcrab *pEntity = (CBaseHeadcrab*) CreateEntityByName( "npc_headcrab" ); pEntity->Spawn(); pEntity->SetLocalOrigin( GetLocalOrigin() ); pEntity->SetLocalAngles( GetLocalAngles() ); pEntity->m_NPCState = NPC_STATE_DEAD; return true; } else if ( (interactionType == g_interactionVortigauntKick) /* || (interactionType == g_interactionBullsquidThrow) */ ) { SetIdealState( NPC_STATE_PRONE ); if( HasHeadroom() ) { MoveOrigin( Vector( 0, 0, 1 ) ); } Vector vHitDir = GetLocalOrigin() - sourceEnt->GetLocalOrigin(); VectorNormalize(vHitDir); CTakeDamageInfo info( sourceEnt, sourceEnt, m_iHealth+1, DMG_CLUB ); CalculateMeleeDamageForce( &info, vHitDir, GetAbsOrigin() ); TakeDamage( info ); return true; } return BaseClass::HandleInteraction( interactionType, data, sourceEnt ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CBaseHeadcrab::FValidateHintType( CAI_Hint *pHint ) { return true; } //----------------------------------------------------------------------------- // Purpose: // Input : &origin - //----------------------------------------------------------------------------- void CBaseHeadcrab::ClearBurrowPoint( const Vector &origin ) { CBaseEntity *pEntity = NULL; float flDist; Vector vecSpot, vecCenter, vecForce; //Cause a ruckus UTIL_ScreenShake( origin, 1.0f, 80.0f, 1.0f, 256.0f, SHAKE_START ); //Iterate on all entities in the vicinity. for ( CEntitySphereQuery sphere( origin, 128 ); ( pEntity = sphere.GetCurrentEntity() ) != NULL; sphere.NextEntity() ) { if ( pEntity->m_takedamage != DAMAGE_NO && pEntity->Classify() != CLASS_PLAYER && pEntity->VPhysicsGetObject() ) { vecSpot = pEntity->BodyTarget( origin ); vecForce = ( vecSpot - origin ) + Vector( 0, 0, 16 ); // decrease damage for an ent that's farther from the bomb. flDist = VectorNormalize( vecForce ); //float mass = pEntity->VPhysicsGetObject()->GetMass(); CollisionProp()->RandomPointInBounds( vec3_origin, Vector( 1.0f, 1.0f, 1.0f ), &vecCenter ); if ( flDist <= 128.0f ) { pEntity->VPhysicsGetObject()->Wake(); pEntity->VPhysicsGetObject()->ApplyForceOffset( vecForce * 250.0f, vecCenter ); } } } } //----------------------------------------------------------------------------- // Purpose: Determine whether a point is valid or not for burrowing up into // Input : &point - point to test for validity // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CBaseHeadcrab::ValidBurrowPoint( const Vector &point ) { trace_t tr; AI_TraceHull( point, point+Vector(0,0,1), GetHullMins(), GetHullMaxs(), MASK_NPCSOLID, this, GetCollisionGroup(), &tr ); // See if we were able to get there if ( ( tr.startsolid ) || ( tr.allsolid ) || ( tr.fraction < 1.0f ) ) { CBaseEntity *pEntity = tr.m_pEnt; //If it's a physics object, attempt to knock is away, unless it's a car if ( ( pEntity ) && ( pEntity->VPhysicsGetObject() ) && ( pEntity->GetServerVehicle() == NULL ) ) { ClearBurrowPoint( point ); } return false; } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseHeadcrab::GrabHintNode( CAI_Hint *pHint ) { // Free up the node for use ClearHintNode(); if ( pHint ) { SetHintNode( pHint ); pHint->Lock( this ); } } //----------------------------------------------------------------------------- // Purpose: Finds a point where the headcrab can burrow underground. // Input : distance - radius to search for burrow spot in // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CBaseHeadcrab::FindBurrow( const Vector &origin, float distance, bool excludeNear ) { // Attempt to find a burrowing point CHintCriteria hintCriteria; hintCriteria.SetHintType( HINT_HEADCRAB_BURROW_POINT ); hintCriteria.SetFlag( bits_HINT_NODE_NEAREST ); hintCriteria.AddIncludePosition( origin, distance ); if ( excludeNear ) { hintCriteria.AddExcludePosition( origin, 128 ); } CAI_Hint *pHint = CAI_HintManager::FindHint( this, hintCriteria ); if ( pHint == NULL ) return false; GrabHintNode( pHint ); // Setup our path and attempt to run there Vector vHintPos; pHint->GetPosition( this, &vHintPos ); AI_NavGoal_t goal( vHintPos, ACT_RUN ); return GetNavigator()->SetGoal( goal ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseHeadcrab::Burrow( void ) { // Stop us from taking damage and being solid m_spawnflags |= SF_NPC_GAG; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseHeadcrab::Unburrow( void ) { // Become solid again and visible m_spawnflags &= ~SF_NPC_GAG; RemoveSolidFlags( FSOLID_NOT_SOLID ); m_takedamage = DAMAGE_YES; SetGroundEntity( NULL ); // If we have an enemy, come out facing them if ( GetEnemy() ) { Vector dir = GetEnemy()->GetAbsOrigin() - GetAbsOrigin(); VectorNormalize(dir); GetMotor()->SetIdealYaw( dir ); QAngle angles = GetLocalAngles(); angles[YAW] = UTIL_VecToYaw( dir ); SetLocalAngles( angles ); } } //----------------------------------------------------------------------------- // Purpose: Tells the headcrab to unburrow as soon the space is clear. //----------------------------------------------------------------------------- void CBaseHeadcrab::InputUnburrow( inputdata_t &inputdata ) { if ( IsAlive() == false ) return; SetSchedule( SCHED_HEADCRAB_WAIT_FOR_CLEAR_UNBURROW ); } //----------------------------------------------------------------------------- // Purpose: Tells the headcrab to run to a nearby burrow point and burrow. //----------------------------------------------------------------------------- void CBaseHeadcrab::InputBurrow( inputdata_t &inputdata ) { if ( IsAlive() == false ) return; SetSchedule( SCHED_HEADCRAB_RUN_TO_BURROW_IN ); } //----------------------------------------------------------------------------- // Purpose: Tells the headcrab to burrow right where he is. //----------------------------------------------------------------------------- void CBaseHeadcrab::InputBurrowImmediate( inputdata_t &inputdata ) { if ( IsAlive() == false ) return; SetSchedule( SCHED_HEADCRAB_BURROW_IN ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseHeadcrab::InputStartHangingFromCeiling( inputdata_t &inputdata ) { if ( IsAlive() == false ) return; SetSchedule( SCHED_HEADCRAB_CEILING_WAIT ); m_flIlluminatedTime = -1; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseHeadcrab::InputDropFromCeiling( inputdata_t &inputdata ) { if ( IsAlive() == false ) return; if ( IsHangingFromCeiling() == false ) return; SetSchedule( SCHED_HEADCRAB_CEILING_DROP ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseHeadcrab::CreateDust( bool placeDecal ) { trace_t tr; AI_TraceLine( GetAbsOrigin()+Vector(0,0,1), GetAbsOrigin()-Vector(0,0,64), MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction < 1.0f ) { const surfacedata_t *pdata = physprops->GetSurfaceData( tr.surface.surfaceProps ); if ( ( (char) pdata->game.material == CHAR_TEX_CONCRETE ) || ( (char) pdata->game.material == CHAR_TEX_DIRT ) ) { UTIL_CreateAntlionDust( tr.endpos + Vector(0, 0, 24), GetLocalAngles() ); //CEffectData data; //data.m_vOrigin = GetAbsOrigin(); //data.m_vNormal = tr.plane.normal; //DispatchEffect( "headcrabdust", data ); if ( placeDecal ) { UTIL_DecalTrace( &tr, "Headcrab.Unburrow" ); } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHeadcrab::Precache( void ) { PrecacheModel( "models/headcrabclassic.mdl" ); PrecacheScriptSound( "NPC_HeadCrab.Gib" ); PrecacheScriptSound( "NPC_HeadCrab.Idle" ); PrecacheScriptSound( "NPC_HeadCrab.Alert" ); PrecacheScriptSound( "NPC_HeadCrab.Pain" ); PrecacheScriptSound( "NPC_HeadCrab.Die" ); PrecacheScriptSound( "NPC_HeadCrab.Attack" ); PrecacheScriptSound( "NPC_HeadCrab.Bite" ); PrecacheScriptSound( "NPC_Headcrab.BurrowIn" ); PrecacheScriptSound( "NPC_Headcrab.BurrowOut" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHeadcrab::Spawn( void ) { Precache(); SetModel( "models/headcrabclassic.mdl" ); BaseClass::Spawn(); m_iHealth = sk_headcrab_health.GetFloat(); m_flBurrowTime = 0.0f; m_bCrawlFromCanister = false; m_bMidJump = false; NPCInit(); HeadcrabInit(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- Activity CHeadcrab::NPC_TranslateActivity( Activity eNewActivity ) { if ( eNewActivity == ACT_WALK ) return ACT_RUN; return BaseClass::NPC_TranslateActivity( eNewActivity ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHeadcrab::IdleSound( void ) { EmitSound( "NPC_HeadCrab.Idle" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHeadcrab::AlertSound( void ) { EmitSound( "NPC_HeadCrab.Alert" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHeadcrab::PainSound( const CTakeDamageInfo &info ) { if( IsOnFire() && random->RandomInt( 0, HEADCRAB_BURN_SOUND_FREQUENCY ) > 0 ) { // Don't squeak every think when burning. return; } EmitSound( "NPC_HeadCrab.Pain" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHeadcrab::DeathSound( const CTakeDamageInfo &info ) { EmitSound( "NPC_HeadCrab.Die" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHeadcrab::TelegraphSound( void ) { //FIXME: Need a real one EmitSound( "NPC_HeadCrab.Alert" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHeadcrab::AttackSound( void ) { EmitSound( "NPC_Headcrab.Attack" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHeadcrab::BiteSound( void ) { EmitSound( "NPC_HeadCrab.Bite" ); } //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CFastHeadcrab ) DEFINE_FIELD( m_iRunMode, FIELD_INTEGER ), DEFINE_FIELD( m_flRealGroundSpeed, FIELD_FLOAT ), DEFINE_FIELD( m_flSlowRunTime, FIELD_TIME ), DEFINE_FIELD( m_flPauseTime, FIELD_TIME ), DEFINE_FIELD( m_vecJumpVel, FIELD_VECTOR ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFastHeadcrab::Precache( void ) { PrecacheModel( "models/headcrab.mdl" ); PrecacheScriptSound( "NPC_FastHeadcrab.Idle" ); PrecacheScriptSound( "NPC_FastHeadcrab.Alert" ); PrecacheScriptSound( "NPC_FastHeadcrab.Pain" ); PrecacheScriptSound( "NPC_FastHeadcrab.Die" ); PrecacheScriptSound( "NPC_FastHeadcrab.Bite" ); PrecacheScriptSound( "NPC_FastHeadcrab.Attack" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFastHeadcrab::Spawn( void ) { Precache(); SetModel( "models/headcrab.mdl" ); BaseClass::Spawn(); m_iHealth = sk_headcrab_health.GetFloat(); m_iRunMode = HEADCRAB_RUNMODE_IDLE; m_flPauseTime = 999999; NPCInit(); HeadcrabInit(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFastHeadcrab::IdleSound( void ) { EmitSound( "NPC_FastHeadcrab.Idle" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFastHeadcrab::AlertSound( void ) { EmitSound( "NPC_FastHeadcrab.Alert" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFastHeadcrab::PainSound( const CTakeDamageInfo &info ) { if( IsOnFire() && random->RandomInt( 0, HEADCRAB_BURN_SOUND_FREQUENCY ) > 0 ) { // Don't squeak every think when burning. return; } EmitSound( "NPC_FastHeadcrab.Pain" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFastHeadcrab::DeathSound( const CTakeDamageInfo &info ) { EmitSound( "NPC_FastHeadcrab.Die" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFastHeadcrab::PrescheduleThink( void ) { #if 1 // #IF 0 this to stop the accelrating/decelerating movement. #define HEADCRAB_ACCELERATION 0.1 if( IsAlive() && GetNavigator()->IsGoalActive() ) { switch( m_iRunMode ) { case HEADCRAB_RUNMODE_IDLE: if ( GetActivity() == ACT_RUN ) { m_flRealGroundSpeed = m_flGroundSpeed; m_iRunMode = HEADCRAB_RUNMODE_ACCELERATE; m_flPlaybackRate = HEADCRAB_RUN_MINSPEED; } break; case HEADCRAB_RUNMODE_FULLSPEED: if( gpGlobals->curtime > m_flSlowRunTime ) { m_iRunMode = HEADCRAB_RUNMODE_DECELERATE; } break; case HEADCRAB_RUNMODE_ACCELERATE: if( m_flPlaybackRate < HEADCRAB_RUN_MAXSPEED ) { m_flPlaybackRate += HEADCRAB_ACCELERATION; } if( m_flPlaybackRate >= HEADCRAB_RUN_MAXSPEED ) { m_flPlaybackRate = HEADCRAB_RUN_MAXSPEED; m_iRunMode = HEADCRAB_RUNMODE_FULLSPEED; m_flSlowRunTime = gpGlobals->curtime + random->RandomFloat( 0.1, 1.0 ); } break; case HEADCRAB_RUNMODE_DECELERATE: m_flPlaybackRate -= HEADCRAB_ACCELERATION; if( m_flPlaybackRate <= HEADCRAB_RUN_MINSPEED ) { m_flPlaybackRate = HEADCRAB_RUN_MINSPEED; // Now stop the crab. m_iRunMode = HEADCRAB_RUNMODE_PAUSE; SetActivity( ACT_IDLE ); GetNavigator()->SetMovementActivity(ACT_IDLE); m_flPauseTime = gpGlobals->curtime + random->RandomFloat( 0.2, 0.5 ); m_flRealGroundSpeed = 0.0; } break; case HEADCRAB_RUNMODE_PAUSE: { if( gpGlobals->curtime > m_flPauseTime ) { m_iRunMode = HEADCRAB_RUNMODE_IDLE; SetActivity( ACT_RUN ); GetNavigator()->SetMovementActivity(ACT_RUN); m_flPauseTime = gpGlobals->curtime - 1; m_flRealGroundSpeed = m_flGroundSpeed; } } break; default: Warning( "BIG TIME HEADCRAB ERROR\n" ); break; } m_flGroundSpeed = m_flRealGroundSpeed * m_flPlaybackRate; } else { m_flPauseTime = gpGlobals->curtime - 1; } #endif BaseClass::PrescheduleThink(); } //----------------------------------------------------------------------------- // Purpose: // Input : scheduleType - //----------------------------------------------------------------------------- int CFastHeadcrab::SelectSchedule( void ) { if ( HasSpawnFlags(SF_NPC_WAIT_TILL_SEEN) ) { return SCHED_IDLE_STAND; } if ( HasCondition(COND_CAN_RANGE_ATTACK1) && IsHangingFromCeiling() == false ) { if ( OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) ) return SCHED_RANGE_ATTACK1; ClearCondition(COND_CAN_RANGE_ATTACK1); } return BaseClass::SelectSchedule(); } //----------------------------------------------------------------------------- // Purpose: // Input : scheduleType - //----------------------------------------------------------------------------- int CFastHeadcrab::TranslateSchedule( int scheduleType ) { switch( scheduleType ) { case SCHED_IDLE_STAND: return SCHED_PATROL_WALK; break; case SCHED_RANGE_ATTACK1: return SCHED_FAST_HEADCRAB_RANGE_ATTACK1; break; case SCHED_CHASE_ENEMY: if ( !OccupyStrategySlotRange( SQUAD_SLOT_ENGAGE1, SQUAD_SLOT_ENGAGE4 ) ) return SCHED_PATROL_WALK; break; } return BaseClass::TranslateSchedule( scheduleType ); } //----------------------------------------------------------------------------- // Purpose: // Input : *pTask - //----------------------------------------------------------------------------- void CFastHeadcrab::RunTask( const Task_t *pTask ) { switch ( pTask->iTask ) { case TASK_RANGE_ATTACK1: case TASK_RANGE_ATTACK2: if ( GetEnemy() ) // Fast headcrab faces the target in flight. GetMotor()->SetIdealYawAndUpdate( GetEnemy()->GetAbsOrigin() - GetAbsOrigin(), AI_KEEP_YAW_SPEED ); // Call back up into base headcrab for collision. BaseClass::RunTask( pTask ); break; case TASK_HEADCRAB_HOP_ASIDE: if ( GetEnemy() ) GetMotor()->SetIdealYawAndUpdate( GetEnemy()->GetAbsOrigin() - GetAbsOrigin(), AI_KEEP_YAW_SPEED ); if( GetFlags() & FL_ONGROUND ) { SetGravity(1.0); SetMoveType( MOVETYPE_STEP ); if( GetEnemy() && ( GetEnemy()->GetAbsOrigin() - GetAbsOrigin() ).Length() > HEADCRAB_MAX_JUMP_DIST ) { TaskFail( ""); } TaskComplete(); } break; default: BaseClass::RunTask( pTask ); break; } } //----------------------------------------------------------------------------- // Purpose: // Input : pTask - //----------------------------------------------------------------------------- void CFastHeadcrab::StartTask( const Task_t *pTask ) { switch ( pTask->iTask ) { case TASK_HEADCRAB_HOP_ASIDE: { Vector vecDir, vecForward, vecRight; bool fJumpIsLeft; trace_t tr; GetVectors( &vecForward, &vecRight, NULL ); fJumpIsLeft = false; if( random->RandomInt( 0, 100 ) < 50 ) { fJumpIsLeft = true; vecRight.Negate(); } vecDir = ( vecRight + ( vecForward * 2 ) ); VectorNormalize( vecDir ); vecDir *= 150.0; // This could be a problem. Since I'm adjusting the headcrab's gravity for flight, this check actually // checks farther ahead than the crab will actually jump. (sjb) AI_TraceHull( GetAbsOrigin(), GetAbsOrigin() + vecDir,GetHullMins(), GetHullMaxs(), MASK_SHOT, this, GetCollisionGroup(), &tr ); //NDebugOverlay::Line( tr.startpos, tr.endpos, 0, 255, 0, false, 1.0 ); if( tr.fraction == 1.0 ) { AIMoveTrace_t moveTrace; GetMoveProbe()->MoveLimit( NAV_JUMP, GetAbsOrigin(), tr.endpos, MASK_NPCSOLID, GetEnemy(), &moveTrace ); // FIXME: Where should this happen? m_vecJumpVel = moveTrace.vJumpVelocity; if( !IsMoveBlocked( moveTrace ) ) { SetAbsVelocity( m_vecJumpVel );// + 0.5f * Vector(0,0,sv_gravity.GetFloat()) * flInterval; SetGravity( UTIL_ScaleForGravity( 1600 ) ); SetGroundEntity( NULL ); SetNavType( NAV_JUMP ); if( fJumpIsLeft ) { SetIdealActivity( (Activity)ACT_HEADCRAB_HOP_LEFT ); GetNavigator()->SetMovementActivity( (Activity) ACT_HEADCRAB_HOP_LEFT ); } else { SetIdealActivity( (Activity)ACT_HEADCRAB_HOP_RIGHT ); GetNavigator()->SetMovementActivity( (Activity) ACT_HEADCRAB_HOP_RIGHT ); } } else { // Can't jump, just fall through. TaskComplete(); } } else { // Can't jump, just fall through. TaskComplete(); } } break; default: { BaseClass::StartTask( pTask ); } } } LINK_ENTITY_TO_CLASS( npc_headcrab, CHeadcrab ); LINK_ENTITY_TO_CLASS( npc_headcrab_fast, CFastHeadcrab ); //----------------------------------------------------------------------------- // Purpose: Make the sound of this headcrab chomping a target. // Input : //----------------------------------------------------------------------------- void CFastHeadcrab::BiteSound( void ) { EmitSound( "NPC_FastHeadcrab.Bite" ); } void CFastHeadcrab::AttackSound( void ) { EmitSound( "NPC_FastHeadcrab.Attack" ); } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : //----------------------------------------------------------------------------- float CHeadcrab::MaxYawSpeed ( void ) { switch ( GetActivity() ) { case ACT_IDLE: return 30; case ACT_RUN: case ACT_WALK: return 20; case ACT_TURN_LEFT: case ACT_TURN_RIGHT: return 15; case ACT_RANGE_ATTACK1: { const Task_t *pCurTask = GetTask(); if ( pCurTask && pCurTask->iTask == TASK_HEADCRAB_JUMP_FROM_CANISTER ) return 15; } return 30; default: return 30; } return BaseClass::MaxYawSpeed(); } //----------------------------------------------------------------------------- // Purpose: Allows for modification of the interrupt mask for the current schedule. // In the most cases the base implementation should be called first. //----------------------------------------------------------------------------- void CBaseHeadcrab::BuildScheduleTestBits( void ) { if ( !IsCurSchedule(SCHED_HEADCRAB_DROWN) ) { // Interrupt any schedule unless already drowning. SetCustomInterruptCondition( COND_HEADCRAB_IN_WATER ); } else { // Don't stop drowning just because you're in water! ClearCustomInterruptCondition( COND_HEADCRAB_IN_WATER ); } if( !IsCurSchedule(SCHED_HEADCRAB_HOP_RANDOMLY) ) { SetCustomInterruptCondition( COND_HEADCRAB_ILLEGAL_GROUNDENT ); } else { ClearCustomInterruptCondition( COND_HEADCRAB_ILLEGAL_GROUNDENT ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CFastHeadcrab::MaxYawSpeed( void ) { switch ( GetActivity() ) { case ACT_IDLE: { return( 120 ); } case ACT_RUN: case ACT_WALK: { return( 150 ); } case ACT_TURN_LEFT: case ACT_TURN_RIGHT: { return( 120 ); } case ACT_RANGE_ATTACK1: { return( 120 ); } default: { return( 120 ); } } } bool CFastHeadcrab::QuerySeeEntity(CBaseEntity *pSightEnt, bool bOnlyHateOrFearIfNPC ) { if ( IsHangingFromCeiling() == true ) return BaseClass::QuerySeeEntity(pSightEnt, bOnlyHateOrFearIfNPC); if( m_NPCState != NPC_STATE_COMBAT ) { if( fabs( pSightEnt->GetAbsOrigin().z - GetAbsOrigin().z ) >= 150 ) { // Don't see things much higher or lower than me unless // I'm already pissed. return false; } } return BaseClass::QuerySeeEntity(pSightEnt, bOnlyHateOrFearIfNPC); } //----------------------------------------------------------------------------- // Black headcrab stuff //----------------------------------------------------------------------------- int ACT_BLACKHEADCRAB_RUN_PANIC; BEGIN_DATADESC( CBlackHeadcrab ) DEFINE_FIELD( m_bPanicState, FIELD_BOOLEAN ), DEFINE_FIELD( m_flPanicStopTime, FIELD_TIME ), DEFINE_FIELD( m_flNextHopTime, FIELD_TIME ), DEFINE_ENTITYFUNC( EjectTouch ), END_DATADESC() LINK_ENTITY_TO_CLASS( npc_headcrab_black, CBlackHeadcrab ); LINK_ENTITY_TO_CLASS( npc_headcrab_poison, CBlackHeadcrab ); //----------------------------------------------------------------------------- // Purpose: Make the sound of this headcrab chomping a target. //----------------------------------------------------------------------------- void CBlackHeadcrab::BiteSound( void ) { EmitSound( "NPC_BlackHeadcrab.Bite" ); } //----------------------------------------------------------------------------- // Purpose: The sound we make when leaping at our enemy. //----------------------------------------------------------------------------- void CBlackHeadcrab::AttackSound( void ) { EmitSound( "NPC_BlackHeadcrab.Attack" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBlackHeadcrab::TelegraphSound( void ) { EmitSound( "NPC_BlackHeadcrab.Telegraph" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBlackHeadcrab::Spawn( void ) { Precache(); SetModel( "models/headcrabblack.mdl" ); BaseClass::Spawn(); m_bPanicState = false; m_iHealth = sk_headcrab_poison_health.GetFloat(); NPCInit(); HeadcrabInit(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBlackHeadcrab::Precache( void ) { PrecacheModel( "models/headcrabblack.mdl" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Telegraph" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Attack" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Bite" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Threat" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Alert" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Idle" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Talk" ); PrecacheScriptSound( "NPC_BlackHeadcrab.AlertVoice" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Pain" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Die" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Impact" ); PrecacheScriptSound( "NPC_BlackHeadcrab.ImpactAngry" ); PrecacheScriptSound( "NPC_BlackHeadcrab.FootstepWalk" ); PrecacheScriptSound( "NPC_BlackHeadcrab.Footstep" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: Returns the max yaw speed for the current activity. //----------------------------------------------------------------------------- float CBlackHeadcrab::MaxYawSpeed( void ) { // Not a constant, can't be in a switch statement. if ( GetActivity() == ACT_BLACKHEADCRAB_RUN_PANIC ) { return 30; } switch ( GetActivity() ) { case ACT_WALK: case ACT_RUN: { return 10; } case ACT_TURN_LEFT: case ACT_TURN_RIGHT: { return( 30 ); } case ACT_RANGE_ATTACK1: { return( 30 ); } default: { return( 30 ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- Activity CBlackHeadcrab::NPC_TranslateActivity( Activity eNewActivity ) { if ( eNewActivity == ACT_RUN || eNewActivity == ACT_WALK ) { if( m_bPanicState || IsOnFire() ) { return ( Activity )ACT_BLACKHEADCRAB_RUN_PANIC; } } return BaseClass::NPC_TranslateActivity( eNewActivity ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBlackHeadcrab::PrescheduleThink( void ) { BaseClass::PrescheduleThink(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CBlackHeadcrab::TranslateSchedule( int scheduleType ) { switch ( scheduleType ) { // Keep trying to take cover for at least a few seconds. case SCHED_FAIL_TAKE_COVER: { if ( ( m_bPanicState ) && ( gpGlobals->curtime > m_flPanicStopTime ) ) { //DevMsg( "I'm sick of panicking\n" ); m_bPanicState = false; return SCHED_CHASE_ENEMY; } break; } } return BaseClass::TranslateSchedule( scheduleType ); } //----------------------------------------------------------------------------- // Purpose: Allows for modification of the interrupt mask for the current schedule. // In the most cases the base implementation should be called first. //----------------------------------------------------------------------------- void CBlackHeadcrab::BuildScheduleTestBits( void ) { // Ignore damage if we're attacking or are fleeing and recently flinched. if ( IsCurSchedule( SCHED_HEADCRAB_CRAWL_FROM_CANISTER ) || IsCurSchedule( SCHED_RANGE_ATTACK1 ) || ( IsCurSchedule( SCHED_TAKE_COVER_FROM_ENEMY ) && HasMemory( bits_MEMORY_FLINCHED ) ) ) { ClearCustomInterruptCondition( COND_LIGHT_DAMAGE ); ClearCustomInterruptCondition( COND_HEAVY_DAMAGE ); } else { SetCustomInterruptCondition( COND_LIGHT_DAMAGE ); SetCustomInterruptCondition( COND_HEAVY_DAMAGE ); } // If we're committed to jump, carry on even if our enemy hides behind a crate. Or a barrel. if ( IsCurSchedule( SCHED_RANGE_ATTACK1 ) && m_bCommittedToJump ) { ClearCustomInterruptCondition( COND_ENEMY_OCCLUDED ); } } //----------------------------------------------------------------------------- // Purpose: // Output : //----------------------------------------------------------------------------- int CBlackHeadcrab::SelectSchedule( void ) { // don't override inherited behavior when hanging from ceiling if ( !IsHangingFromCeiling() ) { if ( HasSpawnFlags(SF_NPC_WAIT_TILL_SEEN) ) { return SCHED_IDLE_STAND; } if ( HasCondition( COND_LIGHT_DAMAGE ) || HasCondition( COND_HEAVY_DAMAGE ) ) { if ( ( gpGlobals->curtime >= m_flNextHopTime ) && SelectWeightedSequence( ACT_SMALL_FLINCH ) != -1 ) { m_flNextHopTime = gpGlobals->curtime + random->RandomFloat( 1, 3 ); return SCHED_SMALL_FLINCH; } } if ( m_bPanicState ) { // We're looking for a place to hide, and we've found one. Lurk! if ( HasMemory( bits_MEMORY_INCOVER ) ) { m_bPanicState = false; m_flPanicStopTime = gpGlobals->curtime; return SCHED_HEADCRAB_AMBUSH; } return SCHED_TAKE_COVER_FROM_ENEMY; } } return BaseClass::SelectSchedule(); } //----------------------------------------------------------------------------- // Purpose: Black headcrab's touch attack damage. Evil! //----------------------------------------------------------------------------- void CBlackHeadcrab::TouchDamage( CBaseEntity *pOther ) { if ( pOther->m_iHealth > 1 ) { CTakeDamageInfo info; if ( CalcDamageInfo( &info ) >= pOther->m_iHealth ) info.SetDamage( pOther->m_iHealth - 1 ); pOther->TakeDamage( info ); if ( pOther->IsAlive() && pOther->m_iHealth > 1) { // Episodic change to avoid NPCs dying too quickly from poison bites if ( hl2_episodic.GetBool() ) { if ( pOther->IsPlayer() ) { // That didn't finish them. Take them down to one point with poison damage. It'll heal. pOther->TakeDamage( CTakeDamageInfo( this, this, pOther->m_iHealth - 1, DMG_POISON ) ); } else { // Just take some amount of slash damage instead pOther->TakeDamage( CTakeDamageInfo( this, this, sk_headcrab_poison_npc_damage.GetFloat(), DMG_SLASH ) ); } } else { // That didn't finish them. Take them down to one point with poison damage. It'll heal. pOther->TakeDamage( CTakeDamageInfo( this, this, pOther->m_iHealth - 1, DMG_POISON ) ); } } } } //----------------------------------------------------------------------------- // Purpose: Bails out of our host zombie, either because he died or was blown // into two pieces by an explosion. // Input : vecAngles - The yaw direction we should face. // flVelocityScale - A multiplier for our ejection velocity. // pEnemy - Who we should acquire as our enemy. Usually our zombie host's enemy. //----------------------------------------------------------------------------- void CBlackHeadcrab::Eject( const QAngle &vecAngles, float flVelocityScale, CBaseEntity *pEnemy ) { SetGroundEntity( NULL ); m_spawnflags |= SF_NPC_FALL_TO_GROUND; SetIdealState( NPC_STATE_ALERT ); if ( pEnemy ) { SetEnemy( pEnemy ); UpdateEnemyMemory(pEnemy, pEnemy->GetAbsOrigin()); } SetActivity( ACT_RANGE_ATTACK1 ); SetNextThink( gpGlobals->curtime ); PhysicsSimulate(); GetMotor()->SetIdealYaw( vecAngles.y ); SetAbsVelocity( flVelocityScale * random->RandomInt( 20, 50 ) * Vector( random->RandomFloat( -1.0, 1.0 ), random->RandomFloat( -1.0, 1.0 ), random->RandomFloat( 0.5, 1.0 ) ) ); m_bMidJump = false; SetTouch( &CBlackHeadcrab::EjectTouch ); } //----------------------------------------------------------------------------- // Purpose: Touch function for when we are ejected from the poison zombie. // Panic when we hit the ground. //----------------------------------------------------------------------------- void CBlackHeadcrab::EjectTouch( CBaseEntity *pOther ) { LeapTouch( pOther ); if ( GetFlags() & FL_ONGROUND ) { // Keep trying to take cover for at least a few seconds. Panic( random->RandomFloat( 2, 8 ) ); } } //----------------------------------------------------------------------------- // Purpose: Puts us in a state in which we just want to hide. We'll stop // hiding after the given duration. //----------------------------------------------------------------------------- void CBlackHeadcrab::Panic( float flDuration ) { m_flPanicStopTime = gpGlobals->curtime + flDuration; m_bPanicState = true; } #if HL2_EPISODIC //----------------------------------------------------------------------------- // Purpose: Black headcrabs have 360-degree vision when they are in the ambush // schedule. This is because they ignore sounds when in ambush, and // you could walk up behind them without having them attack you. // This vision extends only 24 feet. //----------------------------------------------------------------------------- #define CRAB_360_VIEW_DIST_SQR (12 * 12 * 24 * 24) bool CBlackHeadcrab::FInViewCone( CBaseEntity *pEntity ) { if( IsCurSchedule( SCHED_HEADCRAB_AMBUSH ) && (( pEntity->IsNPC() || pEntity->IsPlayer() ) && pEntity->GetAbsOrigin().DistToSqr(GetAbsOrigin()) <= CRAB_360_VIEW_DIST_SQR ) ) { // Only see players and NPC's with 360 cone // For instance, DON'T tell the eyeball/head tracking code that you can see an object that is behind you! return true; } else { return BaseClass::FInViewCone( pEntity ); } } #endif //----------------------------------------------------------------------------- // Purpose: Does a spastic hop in a random or provided direction. // Input : pvecDir - 2D direction to hop, NULL picks a random direction. //----------------------------------------------------------------------------- void CBlackHeadcrab::JumpFlinch( const Vector *pvecDir ) { SetGroundEntity( NULL ); // // Take him off ground so engine doesn't instantly reset FL_ONGROUND. // if( HasHeadroom() ) { MoveOrigin( Vector( 0, 0, 1 ) ); } // // Jump in a random direction. // Vector up; AngleVectors( GetLocalAngles(), NULL, NULL, &up ); if (pvecDir) { SetAbsVelocity( Vector( pvecDir->x * 4, pvecDir->y * 4, up.z ) * random->RandomFloat( 40, 80 ) ); } else { SetAbsVelocity( Vector( random->RandomFloat( -4, 4 ), random->RandomFloat( -4, 4 ), up.z ) * random->RandomFloat( 40, 80 ) ); } } //----------------------------------------------------------------------------- // Purpose: Catches the monster-specific messages that occur when tagged // animation frames are played. // Input : pEvent - //----------------------------------------------------------------------------- void CBlackHeadcrab::HandleAnimEvent( animevent_t *pEvent ) { if ( pEvent->event == AE_POISONHEADCRAB_FOOTSTEP ) { bool walk = ( GetActivity() == ACT_WALK ); // ? 1.0 : 0.6; !!cgreen! old code had bug if ( walk ) { EmitSound( "NPC_BlackHeadcrab.FootstepWalk" ); } else { EmitSound( "NPC_BlackHeadcrab.Footstep" ); } return; } if ( pEvent->event == AE_HEADCRAB_JUMP_TELEGRAPH ) { EmitSound( "NPC_BlackHeadcrab.Telegraph" ); CBaseEntity *pEnemy = GetEnemy(); if ( pEnemy ) { // Once we telegraph, we MUST jump. This is also when commit to what point // we jump at. Jump at our enemy's eyes. m_vecCommittedJumpPos = pEnemy->EyePosition(); m_bCommittedToJump = true; } return; } if ( pEvent->event == AE_POISONHEADCRAB_THREAT_SOUND ) { EmitSound( "NPC_BlackHeadcrab.Threat" ); EmitSound( "NPC_BlackHeadcrab.Alert" ); return; } if ( pEvent->event == AE_POISONHEADCRAB_FLINCH_HOP ) { // // Hop in a random direction, then run and hide. If we're already running // to hide, jump forward -- hopefully that will take us closer to a hiding spot. // if (m_bPanicState) { Vector vecForward; AngleVectors( GetLocalAngles(), &vecForward ); JumpFlinch( &vecForward ); } else { JumpFlinch( NULL ); } Panic( random->RandomFloat( 2, 5 ) ); return; } BaseClass::HandleAnimEvent( pEvent ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CBlackHeadcrab::IsHeavyDamage( const CTakeDamageInfo &info ) { if ( !HasMemory(bits_MEMORY_FLINCHED) && info.GetDamage() > 1.0f ) { // If I haven't flinched lately, any amount of damage is interpreted as heavy. return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBlackHeadcrab::IdleSound( void ) { // TODO: hook up "Marco" / "Polo" talking with nearby buddies if ( m_NPCState == NPC_STATE_IDLE ) { EmitSound( "NPC_BlackHeadcrab.Idle" ); } else if ( m_NPCState == NPC_STATE_ALERT ) { EmitSound( "NPC_BlackHeadcrab.Talk" ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBlackHeadcrab::AlertSound( void ) { EmitSound( "NPC_BlackHeadcrab.AlertVoice" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBlackHeadcrab::PainSound( const CTakeDamageInfo &info ) { if( IsOnFire() && random->RandomInt( 0, HEADCRAB_BURN_SOUND_FREQUENCY ) > 0 ) { // Don't squeak every think when burning. return; } EmitSound( "NPC_BlackHeadcrab.Pain" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBlackHeadcrab::DeathSound( const CTakeDamageInfo &info ) { EmitSound( "NPC_BlackHeadcrab.Die" ); } //----------------------------------------------------------------------------- // Purpose: Played when we jump and hit something that we can't bite. //----------------------------------------------------------------------------- void CBlackHeadcrab::ImpactSound( void ) { EmitSound( "NPC_BlackHeadcrab.Impact" ); if ( !( GetFlags() & FL_ONGROUND ) ) { // Hit a wall - make a pissed off sound. EmitSound( "NPC_BlackHeadcrab.ImpactAngry" ); } } //----------------------------------------------------------------------------- // // Schedules // //----------------------------------------------------------------------------- AI_BEGIN_CUSTOM_NPC( npc_headcrab, CBaseHeadcrab ) DECLARE_TASK( TASK_HEADCRAB_HOP_ASIDE ) DECLARE_TASK( TASK_HEADCRAB_DROWN ) DECLARE_TASK( TASK_HEADCRAB_HOP_OFF_NPC ) DECLARE_TASK( TASK_HEADCRAB_WAIT_FOR_BARNACLE_KILL ) DECLARE_TASK( TASK_HEADCRAB_UNHIDE ) DECLARE_TASK( TASK_HEADCRAB_HARASS_HOP ) DECLARE_TASK( TASK_HEADCRAB_BURROW ) DECLARE_TASK( TASK_HEADCRAB_UNBURROW ) DECLARE_TASK( TASK_HEADCRAB_FIND_BURROW_IN_POINT ) DECLARE_TASK( TASK_HEADCRAB_BURROW_WAIT ) DECLARE_TASK( TASK_HEADCRAB_CHECK_FOR_UNBURROW ) DECLARE_TASK( TASK_HEADCRAB_JUMP_FROM_CANISTER ) DECLARE_TASK( TASK_HEADCRAB_CLIMB_FROM_CANISTER ) DECLARE_TASK( TASK_HEADCRAB_CEILING_POSITION ) DECLARE_TASK( TASK_HEADCRAB_CEILING_WAIT ) DECLARE_TASK( TASK_HEADCRAB_CEILING_DETACH ) DECLARE_TASK( TASK_HEADCRAB_CEILING_FALL ) DECLARE_TASK( TASK_HEADCRAB_CEILING_LAND ) DECLARE_ACTIVITY( ACT_HEADCRAB_THREAT_DISPLAY ) DECLARE_ACTIVITY( ACT_HEADCRAB_HOP_LEFT ) DECLARE_ACTIVITY( ACT_HEADCRAB_HOP_RIGHT ) DECLARE_ACTIVITY( ACT_HEADCRAB_DROWN ) DECLARE_ACTIVITY( ACT_HEADCRAB_BURROW_IN ) DECLARE_ACTIVITY( ACT_HEADCRAB_BURROW_OUT ) DECLARE_ACTIVITY( ACT_HEADCRAB_BURROW_IDLE ) DECLARE_ACTIVITY( ACT_HEADCRAB_CRAWL_FROM_CANISTER_LEFT ) DECLARE_ACTIVITY( ACT_HEADCRAB_CRAWL_FROM_CANISTER_CENTER ) DECLARE_ACTIVITY( ACT_HEADCRAB_CRAWL_FROM_CANISTER_RIGHT ) DECLARE_ACTIVITY( ACT_HEADCRAB_CEILING_FALL ) DECLARE_ACTIVITY( ACT_HEADCRAB_CEILING_IDLE ) DECLARE_ACTIVITY( ACT_HEADCRAB_CEILING_DETACH ) DECLARE_ACTIVITY( ACT_HEADCRAB_CEILING_LAND ) DECLARE_CONDITION( COND_HEADCRAB_IN_WATER ) DECLARE_CONDITION( COND_HEADCRAB_ILLEGAL_GROUNDENT ) DECLARE_CONDITION( COND_HEADCRAB_BARNACLED ) DECLARE_CONDITION( COND_HEADCRAB_UNHIDE ) //Adrian: events go here DECLARE_ANIMEVENT( AE_HEADCRAB_JUMPATTACK ) DECLARE_ANIMEVENT( AE_HEADCRAB_JUMP_TELEGRAPH ) DECLARE_ANIMEVENT( AE_HEADCRAB_BURROW_IN ) DECLARE_ANIMEVENT( AE_HEADCRAB_BURROW_IN_FINISH ) DECLARE_ANIMEVENT( AE_HEADCRAB_BURROW_OUT ) DECLARE_ANIMEVENT( AE_HEADCRAB_CEILING_DETACH ) //========================================================= // > SCHED_HEADCRAB_RANGE_ATTACK1 //========================================================= DEFINE_SCHEDULE ( SCHED_HEADCRAB_RANGE_ATTACK1, " Tasks" " TASK_STOP_MOVING 0" " TASK_FACE_ENEMY 0" " TASK_RANGE_ATTACK1 0" " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" " TASK_FACE_IDEAL 0" " TASK_WAIT_RANDOM 0.5" "" " Interrupts" " COND_ENEMY_OCCLUDED" " COND_NO_PRIMARY_AMMO" ) //========================================================= // //========================================================= DEFINE_SCHEDULE ( SCHED_HEADCRAB_WAKE_ANGRY, " Tasks" " TASK_STOP_MOVING 0" " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE " " TASK_FACE_IDEAL 0" " TASK_SOUND_WAKE 0" " TASK_PLAY_SEQUENCE_FACE_ENEMY ACTIVITY:ACT_HEADCRAB_THREAT_DISPLAY" "" " Interrupts" ) //========================================================= // //========================================================= DEFINE_SCHEDULE ( SCHED_HEADCRAB_WAKE_ANGRY_NO_DISPLAY, " Tasks" " TASK_STOP_MOVING 0" " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE " " TASK_FACE_IDEAL 0" " TASK_SOUND_WAKE 0" " TASK_FACE_ENEMY 0" "" " Interrupts" ) //========================================================= // > SCHED_FAST_HEADCRAB_RANGE_ATTACK1 //========================================================= DEFINE_SCHEDULE ( SCHED_FAST_HEADCRAB_RANGE_ATTACK1, " Tasks" " TASK_STOP_MOVING 0" " TASK_FACE_ENEMY 0" " TASK_RANGE_ATTACK1 0" " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" " TASK_FACE_IDEAL 0" " TASK_WAIT_RANDOM 0.5" "" " Interrupts" ) //========================================================= // The irreversible process of drowning //========================================================= DEFINE_SCHEDULE ( SCHED_HEADCRAB_DROWN, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_HEADCRAB_FAIL_DROWN" " TASK_SET_ACTIVITY ACTIVITY:ACT_HEADCRAB_DROWN" " TASK_HEADCRAB_DROWN 0" "" " Interrupts" ) DEFINE_SCHEDULE ( SCHED_HEADCRAB_FAIL_DROWN, " Tasks" " TASK_HEADCRAB_DROWN 0" "" " Interrupts" ) //========================================================= // Headcrab lurks in place and waits for a chance to jump on // some unfortunate soul. //========================================================= DEFINE_SCHEDULE ( SCHED_HEADCRAB_AMBUSH, " Tasks" " TASK_STOP_MOVING 0" " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" " TASK_WAIT_INDEFINITE 0" " Interrupts" " COND_SEE_ENEMY" " COND_SEE_HATE" " COND_CAN_RANGE_ATTACK1" " COND_LIGHT_DAMAGE" " COND_HEAVY_DAMAGE" " COND_PROVOKED" ) //========================================================= // Headcrab has landed atop another NPC or has landed on // a ledge. Get down! //========================================================= DEFINE_SCHEDULE ( SCHED_HEADCRAB_HOP_RANDOMLY, " Tasks" " TASK_STOP_MOVING 0" " TASK_HEADCRAB_HOP_OFF_NPC 0" " Interrupts" ) //========================================================= // Headcrab is in the clutches of a barnacle //========================================================= DEFINE_SCHEDULE ( SCHED_HEADCRAB_BARNACLED, " Tasks" " TASK_STOP_MOVING 0" " TASK_SET_ACTIVITY ACTIVITY:ACT_HEADCRAB_DROWN" " TASK_HEADCRAB_WAIT_FOR_BARNACLE_KILL 0" " Interrupts" ) //========================================================= // Headcrab is unhiding //========================================================= DEFINE_SCHEDULE ( SCHED_HEADCRAB_UNHIDE, " Tasks" " TASK_HEADCRAB_UNHIDE 0" " Interrupts" ) DEFINE_SCHEDULE ( SCHED_HEADCRAB_HARASS_ENEMY, " Tasks" " TASK_FACE_ENEMY 0" " TASK_HEADCRAB_HARASS_HOP 0" " TASK_WAIT_FACE_ENEMY 1" " TASK_SET_ROUTE_SEARCH_TIME 2" // Spend 2 seconds trying to build a path if stuck " TASK_GET_PATH_TO_RANDOM_NODE 300" " TASK_WALK_PATH 0" " TASK_WAIT_FOR_MOVEMENT 0" " Interrupts" " COND_NEW_ENEMY" ) DEFINE_SCHEDULE ( SCHED_HEADCRAB_FALL_TO_GROUND, " Tasks" " TASK_SET_ACTIVITY ACTIVITY:ACT_HEADCRAB_DROWN" " TASK_FALL_TO_GROUND 0" "" " Interrupts" ) DEFINE_SCHEDULE ( SCHED_HEADCRAB_CRAWL_FROM_CANISTER, " Tasks" " TASK_HEADCRAB_CLIMB_FROM_CANISTER 0" " TASK_HEADCRAB_JUMP_FROM_CANISTER 0" "" " Interrupts" ) //================================================== // Burrow In //================================================== DEFINE_SCHEDULE ( SCHED_HEADCRAB_BURROW_IN, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY_FAILED" " TASK_HEADCRAB_BURROW 0" " TASK_PLAY_SEQUENCE ACTIVITY:ACT_HEADCRAB_BURROW_IN" " TASK_PLAY_SEQUENCE ACTIVITY:ACT_HEADCRAB_BURROW_IDLE" " TASK_SET_SCHEDULE SCHEDULE:SCHED_HEADCRAB_BURROW_WAIT" "" " Interrupts" " COND_TASK_FAILED" ) //================================================== // Run to a nearby burrow hint and burrow there //================================================== DEFINE_SCHEDULE ( SCHED_HEADCRAB_RUN_TO_BURROW_IN, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY_FAILED" " TASK_HEADCRAB_FIND_BURROW_IN_POINT 512" " TASK_SET_TOLERANCE_DISTANCE 8" " TASK_RUN_PATH 0" " TASK_WAIT_FOR_MOVEMENT 0" " TASK_SET_SCHEDULE SCHEDULE:SCHED_HEADCRAB_BURROW_IN" "" " Interrupts" " COND_TASK_FAILED" " COND_GIVE_WAY" " COND_CAN_RANGE_ATTACK1" ) //================================================== // Run to m_pHintNode and burrow there //================================================== DEFINE_SCHEDULE ( SCHED_HEADCRAB_RUN_TO_SPECIFIC_BURROW, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY_FAILED" " TASK_SET_TOLERANCE_DISTANCE 8" " TASK_GET_PATH_TO_HINTNODE 0" " TASK_RUN_PATH 0" " TASK_WAIT_FOR_MOVEMENT 0" " TASK_SET_SCHEDULE SCHEDULE:SCHED_HEADCRAB_BURROW_IN" "" " Interrupts" " COND_TASK_FAILED" " COND_GIVE_WAY" ) //================================================== // Wait until we can unburrow and attack something //================================================== DEFINE_SCHEDULE ( SCHED_HEADCRAB_BURROW_WAIT, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_HEADCRAB_BURROW_WAIT" " TASK_HEADCRAB_BURROW_WAIT 1" "" " Interrupts" " COND_TASK_FAILED" " COND_NEW_ENEMY" // HACK: We don't actually choose a new schedule on new enemy, but // we need this interrupt so that the headcrab actually acquires // new enemies while burrowed. (look in ai_basenpc.cpp for "DO NOT mess") " COND_CAN_RANGE_ATTACK1" ) //================================================== // Burrow Out //================================================== DEFINE_SCHEDULE ( SCHED_HEADCRAB_BURROW_OUT, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_HEADCRAB_BURROW_WAIT" " TASK_HEADCRAB_UNBURROW 0" " TASK_PLAY_SEQUENCE ACTIVITY:ACT_HEADCRAB_BURROW_OUT" "" " Interrupts" " COND_TASK_FAILED" ) //================================================== // Wait for it to be clear for unburrowing //================================================== DEFINE_SCHEDULE ( SCHED_HEADCRAB_WAIT_FOR_CLEAR_UNBURROW, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_HEADCRAB_BURROW_WAIT" " TASK_HEADCRAB_CHECK_FOR_UNBURROW 1" " TASK_SET_SCHEDULE SCHEDULE:SCHED_HEADCRAB_BURROW_OUT" "" " Interrupts" " COND_TASK_FAILED" ) //================================================== // Wait until we can drop. //================================================== DEFINE_SCHEDULE ( SCHED_HEADCRAB_CEILING_WAIT, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_HEADCRAB_CEILING_DROP" " TASK_SET_ACTIVITY ACTIVITY:ACT_HEADCRAB_CEILING_IDLE" " TASK_HEADCRAB_CEILING_POSITION 0" " TASK_HEADCRAB_CEILING_WAIT 1" "" " Interrupts" " COND_TASK_FAILED" " COND_NEW_ENEMY" " COND_CAN_RANGE_ATTACK1" ) //================================================== // Deatch from ceiling. //================================================== DEFINE_SCHEDULE ( SCHED_HEADCRAB_CEILING_DROP, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_HEADCRAB_CEILING_WAIT" " TASK_HEADCRAB_CEILING_DETACH 0" " TASK_HEADCRAB_CEILING_FALL 0" " TASK_HEADCRAB_CEILING_LAND 0" "" " Interrupts" " COND_TASK_FAILED" ) AI_END_CUSTOM_NPC() //----------------------------------------------------------------------------- AI_BEGIN_CUSTOM_NPC( npc_headcrab_poison, CBlackHeadcrab ) DECLARE_ACTIVITY( ACT_BLACKHEADCRAB_RUN_PANIC ) //Adrian: events go here DECLARE_ANIMEVENT( AE_POISONHEADCRAB_FLINCH_HOP ) DECLARE_ANIMEVENT( AE_POISONHEADCRAB_FOOTSTEP ) DECLARE_ANIMEVENT( AE_POISONHEADCRAB_THREAT_SOUND ) AI_END_CUSTOM_NPC() AI_BEGIN_CUSTOM_NPC( npc_headcrab_fast, CFastHeadcrab ) DECLARE_SQUADSLOT( SQUAD_SLOT_ENGAGE1 ) DECLARE_SQUADSLOT( SQUAD_SLOT_ENGAGE2 ) DECLARE_SQUADSLOT( SQUAD_SLOT_ENGAGE3 ) DECLARE_SQUADSLOT( SQUAD_SLOT_ENGAGE4 ) AI_END_CUSTOM_NPC()
[ "MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61" ]
[ [ [ 1, 3994 ] ] ]
ec3af601707c17e280fda6136a1730cb2b0b17e7
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/26042005/vfs/jpeg/VFSPlugin_JPEG.h
8d3853efd6beac1d04f0309e62caba064244ceee
[]
no_license
christhomas/fusionengine
286b33f2c6a7df785398ffbe7eea1c367e512b8d
95422685027bb19986ba64c612049faa5899690e
refs/heads/master
2020-04-05T22:52:07.491706
2006-10-24T11:21:28
2006-10-24T11:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
698
h
#ifndef _VFSPLUGIN_JPEG_H_ #define _VFSPLUGIN_JPEG_H_ #include <vfs/VirtualFS.h> #include <jpeglib.h> class VFSPlugin_JPEG: public VFSPlugin{ protected: /** @var ImageFileInfo *m_fileinfo * @brief Structure to store the image data */ ImageFileInfo *m_fileinfo; jpeg_decompress_struct m_cinfo; jpeg_error_mgr m_jerr; virtual void Setup (void); virtual bool Decode (void); public: VFSPlugin_JPEG (); virtual ~VFSPlugin_JPEG (); virtual FileInfo * Read (unsigned char *buffer, unsigned int length); virtual char * Write (FileInfo *data, unsigned int &length); virtual char * Type (void); }; #endif // #ifndef _VFSPLUGIN_JPEG_H_
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
[ [ [ 1, 31 ] ] ]
c4fc79d729bf051082bca4f099a95cd64cca7158
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
/Code/controllers/Tcleaner/robotapi/real/RealPCBattery.cpp
754d96bca18f240c462ef8d3731cc4e415970a59
[]
no_license
dh-04/tpf-robotica
5efbac38d59fda0271ac4639ea7b3b4129c28d82
10a7f4113d5a38dc0568996edebba91f672786e9
refs/heads/master
2022-12-10T18:19:22.428435
2010-11-05T02:42:29
2010-11-05T02:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
606
cpp
#include "RealPCBattery.h" namespace robotapi { namespace real { RealPCBattery::RealPCBattery(std::string name) : RealDevice(&name){ } void RealPCBattery::enable(int ms){ return; } void RealPCBattery::disable(){ return; } double RealPCBattery::getValue(){ return 0.2; } bool RealPCBattery::isFull(){ return false; } void RealPCBattery::setEmptyBias(double bias){ } bool RealPCBattery::isEmpty(){ return false; } void RealPCBattery::setFullBias(double bias){ } } /* End of namespace robotapi::real */ } /* End of namespace robotapi */
[ "guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a" ]
[ [ [ 1, 36 ] ] ]
da47c761dc9c8f8563ef1984df6940d626d2d7cc
59166d9d1eea9b034ac331d9c5590362ab942a8f
/Forest/LightSource.h
4ec4ab14f6d7a2405de35393f0a15a44c8016ea0
[]
no_license
seafengl/osgtraining
5915f7b3a3c78334b9029ee58e6c1cb54de5c220
fbfb29e5ae8cab6fa13900e417b6cba3a8c559df
refs/heads/master
2020-04-09T07:32:31.981473
2010-09-03T15:10:30
2010-09-03T15:10:30
40,032,354
0
3
null
null
null
null
WINDOWS-1251
C++
false
false
1,046
h
#ifndef _LIGHT_SOURCE_H_ #define _LIGHT_SOURCE_H_ #include "LightSourceCallback.h" #include <osg/Referenced> #include <osg/Group> #include <osg/ref_ptr> #include <osg/Transform> class LightSource : public osg::Referenced { public: LightSource(); ~LightSource(); //ะฒะตั€ะฝัƒั‚ัŒ ัƒะทะตะป ัะฒะตั‚ะฐ osg::ref_ptr< osg::Group > getRootNode() { return m_rootGroup.get(); } //ะฟะตั€ะตะดะฐั‚ัŒ Uniform ะฟะพะปะพะถะตะฝะธั ะธัั‚ะพั‡ะฝะธะบะฐ ัะฒะตั‚ะฐ void SetUniform( osg::Uniform *_LightPos ){ cb->SetUniform( _LightPos ); }; private: /*methods*/ void buildScene(); //ัะพะทะดะฐั‚ัŒ ั‚ะพั‡ะบัƒ ะฟั€ะตะดัั‚ะฐะฒะปััŽั‰ัƒัŽ ะธัั‚ะพั‡ะฝะธะบ ัะฒะตั‚ะฐ osg::ref_ptr< osg::Geode > createLightPoint(); //ัะพะทะดะฐั‚ัŒ ะธัั‚ะพั‡ะฝะธะบ ัะฒะตั‚ะฐ osg::ref_ptr< osg::Transform > CreateLight(); //ะณั€ัƒะฟะฟะฐ, ัะพะดะตั€ะถะฐั‰ะฐั ะณะตะพะผะตั‚ั€ะธัŽ ะธัั‚ะพั‡ะฝะธะบะฐ ัะฒะตั‚ะฐ ะธ ัะฐะผ ัะฒะตั‚ osg::ref_ptr< osg::Group > m_rootGroup; LightSourceCallback *cb; }; #endif //_LIGHT_SOURCE_H_
[ "asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b" ]
[ [ [ 1, 39 ] ] ]
63dcd5cabdde982d15d1015aaa30d64d24aeb39a
3e69b159d352a57a48bc483cb8ca802b49679d65
/trunk/pcbnew/edtxtmod.cpp
1fd8c77dc6d289b3f40ec2209a7f7ee42b66d109
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
6,697
cpp
/*************************************************************/ /* Edition des Modules: Routines de modification des textes */ /* sur les MODULES */ /*************************************************************/ /* Fichier EDTXTMOD.CPP */ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "pcbnew.h" #include "trigo.h" #include "protos.h" /* Routines Locales */ static void Show_MoveTexte_Module(WinEDA_DrawPanel * panel, wxDC * DC, bool erase); static void ExitTextModule(WinEDA_DrawFrame * frame, wxDC *DC); /* local variables */ wxPoint MoveVector; // Move vector for move edge, exported to dialog_edit mod_text.cpp static wxPoint CursorInitialPosition; // Mouse cursor inital position for move command /******************************************************************************/ TEXTE_MODULE * WinEDA_BasePcbFrame::CreateTextModule(MODULE * Module, wxDC * DC) /******************************************************************************/ /* Add a new graphical text to the active module (footprint) Note there always are 2 texts: reference and value. New texts have the member TEXTE_MODULE.m_Type set to TEXT_is_DIVERS */ { TEXTE_MODULE * Text; Text = new TEXTE_MODULE(Module); /* Chainage de la nouvelle structure en tete de liste drawings */ Text->Pnext = Module->m_Drawings; Text->Pback = Module; if( Module->m_Drawings ) Module->m_Drawings->Pback = Text; Module->m_Drawings = Text; Text->m_Flags = IS_NEW; Text->m_Text = wxT("text"); Text->m_Size = ModuleTextSize; Text->m_Width = ModuleTextWidth; Text->m_Pos = GetScreen()->m_Curseur; Text->SetLocalCoord(); InstallTextModOptionsFrame(Text, NULL, wxPoint(-1,-1) ); Text->m_Flags = 0; Text->Draw(DrawPanel, DC, wxPoint(0,0), GR_OR ); Affiche_Infos_E_Texte(this, Module, Text); return Text; } /**************************************************************************/ void WinEDA_BasePcbFrame::RotateTextModule(TEXTE_MODULE * Text, wxDC * DC) /**************************************************************************/ /* Rotation de 90 du texte d'un module */ { MODULE * Module; if ( Text == NULL ) return; Module = (MODULE*)Text->m_Parent; Text->Draw(DrawPanel, DC, wxPoint(0,0), GR_XOR ); Text->m_Orient += 900 ; while (Text->m_Orient >= 1800) Text->m_Orient -= 1800 ; /* Redessin du Texte */ Text->Draw(DrawPanel, DC, wxPoint(0,0), GR_XOR ); Affiche_Infos_E_Texte(this, Module,Text); ((MODULE*)Text->m_Parent)->m_LastEdit_Time = time(NULL); GetScreen()->SetModify(); } /**************************************************************************/ void WinEDA_BasePcbFrame::DeleteTextModule(TEXTE_MODULE * Text, wxDC * DC) /**************************************************************************/ /* Supprime 1 texte sur module (si ce n'est pas la rรฉfรฉrence ou la valeur) */ { MODULE * Module; if (Text == NULL) return; Module = (MODULE*)Text->m_Parent; if(Text->m_Type == TEXT_is_DIVERS) { Text->Draw(DrawPanel, DC, wxPoint(0,0), GR_XOR ); /* liberation de la memoire : */ DeleteStructure(Text); GetScreen()->SetModify(); Module->m_LastEdit_Time = time(NULL); } } /*************************************************************/ static void ExitTextModule(WinEDA_DrawFrame * frame, wxDC *DC) /*************************************************************/ /* Routine de sortie du menu edit texte module Si un texte est selectionne, ses coord initiales sont regenerees */ { BASE_SCREEN * screen = frame->GetScreen(); TEXTE_MODULE * Text = (TEXTE_MODULE *) screen->m_CurrentItem; MODULE * Module; screen->ManageCurseur = NULL; screen->ForceCloseManageCurseur = NULL; if ( Text == NULL ) return; Module = ( MODULE *) Text->m_Parent; Text->Draw(frame->DrawPanel, DC, MoveVector, GR_XOR ); /* Redessin du Texte */ Text->Draw(frame->DrawPanel, DC, wxPoint(0,0), GR_OR ); Text->m_Flags = 0; Module->m_Flags = 0; screen->m_CurrentItem = NULL; } /****************************************************************************/ void WinEDA_BasePcbFrame::StartMoveTexteModule(TEXTE_MODULE * Text, wxDC * DC) /****************************************************************************/ /* Routine d'initialisation du deplacement d'un texte sur module */ { MODULE * Module; if( Text == NULL ) return; Module = (MODULE*) Text->m_Parent; Text->m_Flags |= IS_MOVED; Module->m_Flags |= IN_EDIT; MoveVector.x = MoveVector.y = 0; CursorInitialPosition = Text->m_Pos; Affiche_Infos_E_Texte(this, Module, Text); GetScreen()->m_CurrentItem = Text; GetScreen()->ManageCurseur = Show_MoveTexte_Module; GetScreen()->ForceCloseManageCurseur = ExitTextModule; GetScreen()->ManageCurseur(DrawPanel, DC, TRUE); } /*************************************************************************/ void WinEDA_BasePcbFrame::PlaceTexteModule(TEXTE_MODULE * Text, wxDC * DC) /*************************************************************************/ /* Routine complementaire a StartMoveTexteModule(). Place le texte en cours de deplacement ou nouvellement cree */ { if (Text != NULL ) { Text->m_Pos = GetScreen()->m_Curseur; /* mise a jour des coordonnรฉes relatives a l'ancre */ MODULE * Module = ( MODULE *) Text->m_Parent; if (Module ) { int px = Text->m_Pos.x - Module->m_Pos.x; int py = Text->m_Pos.y - Module->m_Pos.y; RotatePoint( &px, &py, - Module->m_Orient); Text->m_Pos0.x = px; Text->m_Pos0.y = py; Text->m_Flags = 0; Module->m_Flags = 0; Module->m_LastEdit_Time = time(NULL); GetScreen()->SetModify(); /* Redessin du Texte */ Text->Draw(DrawPanel, DC, wxPoint(0,0), GR_OR ); } } GetScreen()->ManageCurseur = NULL; GetScreen()->ForceCloseManageCurseur = NULL; } /********************************************************************************/ static void Show_MoveTexte_Module(WinEDA_DrawPanel * panel, wxDC * DC, bool erase) /********************************************************************************/ { BASE_SCREEN * screen = panel->GetScreen(); TEXTE_MODULE * Text = (TEXTE_MODULE *) screen->m_CurrentItem; MODULE * Module; if (Text == NULL ) return ; Module = ( MODULE *) Text->m_Parent; /* effacement du texte : */ if ( erase ) Text->Draw(panel, DC, MoveVector, GR_XOR ); MoveVector.x = -(screen->m_Curseur.x - CursorInitialPosition.x); MoveVector.y = -(screen->m_Curseur.y - CursorInitialPosition.y); /* Redessin du Texte */ Text->Draw(panel, DC, MoveVector, GR_XOR ); }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 230 ] ] ]
d2bf85d56bcc25d04267500de23553da0b44041d
a6d5d811222889c750c786ef5487f9b49edb2de1
/motion/RST/GUI/RSTFrame.h
12e9ed64c7d27e966b75669a2c653e2b0ddfc640
[]
no_license
oarslan3/gt-cs-rip-projects
1f29f979b5ca57f87cd154bfa1c88b93fb09ccb9
0b8f470679d5c107c7f10dbe9a67cdda392a9329
refs/heads/master
2021-01-10T05:50:57.921487
2009-12-13T16:48:49
2009-12-13T16:48:49
52,402,944
0
0
null
null
null
null
UTF-8
C++
false
false
2,518
h
//--------------------------------------------------------------------- // Copyright (c) 2009 Mike Stilman // All Rights Reserved. // // Permission to duplicate or use this software in whole or in part // is only granted by consultation with the author. // // Mike Stilman [email protected] // // Robotics and Intelligent Machines // Georgia Tech //-------------------------------------------------------------------- #ifndef RSTFRAME_H #define RSTFRAME_H class RSTSlider; class Viewer; class World; class RSTimeSlice; #include <vector> #include "TreeView.h" #include <string> using namespace std; #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include <wx/notebook.h> // ---------------------------------------------------------------------------- class RSTFrame : public wxFrame { public: RSTFrame(const wxString& title); wxPanel *backPanel; RSTSlider *timeSlider; wxSlider *timeTrack; wxTextCtrl *timeText; wxToolBar* filebar; wxToolBar* optionbar; wxBitmap toolBarBitmaps[10]; //void OnSize(wxSizeEvent& evt); int saveText(wxString scenepath, const char* llfile); void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); void OnSaveScene(wxCommandEvent& event); void OnSaveRobot(wxCommandEvent& event); void OnLoad(wxCommandEvent& event); void OnQuickLoad(wxCommandEvent& event); void OnToolOrder(wxCommandEvent& event); void OnToolCheckColl(wxCommandEvent& event); void OnToolScreenshot(wxCommandEvent& event); void OnToolMovie(wxCommandEvent& event); void OnClose(wxCommandEvent& event); void OnTimeScroll(wxScrollEvent &evt); void OnTimeEnter(wxCommandEvent &evt); void OnWhite(wxCommandEvent& event); void OnBlack(wxCommandEvent& event); void InitTimer(string title, double period); void AddWorld(World* world); vector<RSTimeSlice*> timeVector; double tCurrent; double tMax; double tIncrement; int tPrecision; void setTimeValue(double value, bool sendSignal = false); void updateTimeValue(double value, bool sendSignal = false); void updateAllTabs(); void DoLoad(string filename); void DeleteWorld(); void onTVChange(wxTreeEvent& event); DECLARE_EVENT_TABLE() }; enum { MenuSaveScene = wxID_HIGHEST+1, MenuSaveRobot, MenuLoad, MenuQuickLoad, MenuClose, MenuBgWhite, MenuBgBlack, MenuQuit = wxID_EXIT, MenuAbout = wxID_ABOUT }; #endif
[ "alexgcunningham@e642834e-98c8-11de-b255-e1213ca11573" ]
[ [ [ 1, 108 ] ] ]
371bc75b788bbcc9c2f332ca92507301992ee2f3
a30b091525dc3f07cd7e12c80b8d168a0ee4f808
/EngineAll/Core/InputDataStream.cpp
ee737fd2b6c29c3397488a716c90df555a097170
[]
no_license
ghsoftco/basecode14
f50dc049b8f2f8d284fece4ee72f9d2f3f59a700
57de2a24c01cec6dc3312cbfe200f2b15d923419
refs/heads/master
2021-01-10T11:18:29.585561
2011-01-23T02:25:21
2011-01-23T02:25:21
47,255,927
0
0
null
null
null
null
UTF-8
C++
false
false
1,154
cpp
/* InputDataStream.cpp Written by Matthew Fisher */ #include "..\\..\\Main.h" #include "InputDataStream.h" InputDataStream::InputDataStream() { } InputDataStream::~InputDataStream() { } void InputDataStream::LoadFromFile(const String &Filename) { FILE *File = Utility::CheckedFOpen(Filename.CString(), "rb"); UINT Length; Utility::CheckedFRead(&Length, sizeof(UINT), 1, File); _Data.Allocate(Length); Utility::CheckedFRead(_Data.CArray(), sizeof(BYTE), Length, File); fclose(File); _ReadPtr = 0; } void InputDataStream::LoadFromMemory(const Vector<BYTE> &Data) { _Data = Data; _ReadPtr = 0; } void InputDataStream::ReadData(BYTE *Data, UINT BytesToRead) { Assert(_Data.Length() >= _ReadPtr + BytesToRead, "Read past end of stream"); if(BytesToRead > 0) { memcpy(Data, _Data.CArray() + _ReadPtr, BytesToRead); _ReadPtr += BytesToRead; } } InputDataStream& operator >> (InputDataStream &S, String &V) { UINT Length; S >> Length; V.ReSize(Length); S.ReadData((BYTE *)V.CString(), Length); return S; }
[ "zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2" ]
[ [ [ 1, 52 ] ] ]
f581f32e7215c67847ffb3d2ec6be5fe9fbba515
f73eca356aba8cbc5c0cbe7527c977f0e7d6a116
/Glop/third_party/raknet/RakPeerInterface.h
11efcd242e915fee1805a3764d1496b8e1cd03ad
[ "BSD-3-Clause" ]
permissive
zorbathut/glop
40737587e880e557f1f69c3406094631e35e6bb5
762d4f1e070ce9c7180a161b521b05c45bde4a63
refs/heads/master
2016-08-06T22:58:18.240425
2011-10-20T04:22:20
2011-10-20T04:22:20
710,818
1
0
null
null
null
null
UTF-8
C++
false
false
43,780
h
/// \file /// \brief An interface for RakPeer. Simply contains all user functions as pure virtuals. /// /// This file is part of RakNet Copyright 2003 Kevin Jenkins. /// /// Usage of RakNet is subject to the appropriate license agreement. /// Creative Commons Licensees are subject to the /// license found at /// http://creativecommons.org/licenses/by-nc/2.5/ /// Single application licensees are subject to the license found at /// http://www.jenkinssoftware.com/SingleApplicationLicense.html /// Custom license users are subject to the terms therein. /// GPL license users are subject to 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. #ifndef __RAK_PEER_INTERFACE_H #define __RAK_PEER_INTERFACE_H #include "PacketPriority.h" #include "RakNetTypes.h" #include "RakMemoryOverride.h" #include "Export.h" // Forward declarations namespace RakNet { class BitStream; } class PluginInterface; struct RPCMap; struct RakNetStatistics; class RouterInterface; class NetworkIDManager; /// The primary interface for RakNet, RakPeer contains all major functions for the library. /// See the individual functions for what the class can do. /// \brief The main interface for network communications class RAK_DLL_EXPORT RakPeerInterface : public RakNet::RakMemoryOverride { public: ///Destructor virtual ~RakPeerInterface() {} // --------------------------------------------------------------------------------------------Major Low Level Functions - Functions needed by most users-------------------------------------------------------------------------------------------- /// \brief Starts the network threads, opens the listen port. /// You must call this before calling Connect(). /// Multiple calls while already active are ignored. To call this function again with different settings, you must first call Shutdown(). /// \note Call SetMaximumIncomingConnections if you want to accept incoming connections /// \note Set _RAKNET_THREADSAFE in RakNetDefines.h if you want to call RakNet functions from multiple threads (not recommended, as it is much slower and RakNet is already asynchronous). /// \param[in] maxConnections The maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.- A hybrid would set it to the sum of both types of connections /// \param[in] localPort The port to listen for connections on. /// \param[in] _threadSleepTimer How many ms to Sleep each internal update cycle (30 to give the game priority, 0 for regular (recommended) /// \param[in] socketDescriptors An array of SocketDescriptor structures to force RakNet to listen on a particular IP address or port (or both). Each SocketDescriptor will represent one unique socket. Do not pass redundant structures. To listen on a specific port, you can pass SocketDescriptor(myPort,0); such as for a server. For a client, it is usually OK to just pass SocketDescriptor(); /// \param[in] socketDescriptorCount The size of the \a socketDescriptors array. Pass 1 if you are not sure what to pass. /// \return False on failure (can't create socket or thread), true on success. virtual bool Startup( unsigned short maxConnections, int _threadSleepTimer, SocketDescriptor *socketDescriptors, unsigned socketDescriptorCount )=0; /// Secures connections though a combination of SHA1, AES128, SYN Cookies, and RSA to prevent connection spoofing, replay attacks, data eavesdropping, packet tampering, and MitM attacks. /// There is a significant amount of processing and a slight amount of bandwidth overhead for this feature. /// If you accept connections, you must call this or else secure connections will not be enabled for incoming connections. /// If you are connecting to another system, you can call this with values for the (e and p,q) public keys before connecting to prevent MitM /// \pre Must be called while offline /// \param[in] pubKeyE A pointer to the public keys from the RSACrypt class. /// \param[in] pubKeyN A pointer to the public keys from the RSACrypt class. /// \param[in] privKeyP Public key generated from the RSACrypt class. /// \param[in] privKeyQ Public key generated from the RSACrypt class. If the private keys are 0, then a new key will be generated when this function is called@see the Encryption sample virtual void InitializeSecurity(const char *pubKeyE, const char *pubKeyN, const char *privKeyP, const char *privKeyQ )=0; /// Disables all security. /// \note Must be called while offline virtual void DisableSecurity( void )=0; /// If secure connections are on, do not use secure connections for a specific IP address. /// This is useful if you have a fixed-address internal server behind a LAN. /// \note Secure connections are determined by the recipient of an incoming connection. This has no effect if called on the system attempting to connect. /// \param[in] ip IP address to add. * wildcards are supported. virtual void AddToSecurityExceptionList(const char *ip)=0; /// Remove a specific connection previously added via AddToSecurityExceptionList /// \param[in] ip IP address to remove. Pass 0 to remove all IP addresses. * wildcards are supported. virtual void RemoveFromSecurityExceptionList(const char *ip)=0; /// Checks to see if a given IP is in the security exception list /// \param[in] IP address to check. virtual bool IsInSecurityExceptionList(const char *ip)=0; /// Sets how many incoming connections are allowed. If this is less than the number of players currently connected, /// no more players will be allowed to connect. If this is greater than the maximum number of peers allowed, /// it will be reduced to the maximum number of peers allowed. /// Defaults to 0, meaning by default, nobody can connect to you /// \param[in] numberAllowed Maximum number of incoming connections allowed. virtual void SetMaximumIncomingConnections( unsigned short numberAllowed )=0; /// Returns the value passed to SetMaximumIncomingConnections() /// \return the maximum number of incoming connections, which is always <= maxConnections virtual unsigned short GetMaximumIncomingConnections( void ) const=0; /// Returns how many open connections there are at this time /// \return the number of open connections virtual unsigned short NumberOfConnections(void) const=0; /// Sets the password incoming connections must match in the call to Connect (defaults to none). Pass 0 to passwordData to specify no password /// This is a way to set a low level password for all incoming connections. To selectively reject connections, implement your own scheme using CloseConnection() to remove unwanted connections /// \param[in] passwordData A data block that incoming connections must match. This can be just a password, or can be a stream of data. Specify 0 for no password data /// \param[in] passwordDataLength The length in bytes of passwordData virtual void SetIncomingPassword( const char* passwordData, int passwordDataLength )=0; /// Gets the password passed to SetIncomingPassword /// \param[out] passwordData Should point to a block large enough to hold the password data you passed to SetIncomingPassword() /// \param[in,out] passwordDataLength Maximum size of the array passwordData. Modified to hold the number of bytes actually written virtual void GetIncomingPassword( char* passwordData, int *passwordDataLength )=0; /// \brief Connect to the specified host (ip or domain name) and server port. /// Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client. /// Calling both acts as a true peer. This is a non-blocking connection. /// You know the connection is successful when IsConnected() returns true or Receive() gets a message with the type identifier ID_CONNECTION_ACCEPTED. /// If the connection is not successful, such as a rejected connection or no response then neither of these things will happen. /// \pre Requires that you first call Initialize /// \param[in] host Either a dotted IP address or a domain name /// \param[in] remotePort Which port to connect to on the remote machine. /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password. /// \param[in] passwordDataLength The length in bytes of passwordData /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. /// \return True on successful initiation. False on incorrect parameters, internal error, or too many existing peers. Returning true does not mean you connected! virtual bool Connect( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, unsigned connectionSocketIndex=0 )=0; /// \brief Connect to the specified network ID (Platform specific console function) /// Does built-in NAt traversal /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password. /// \param[in] passwordDataLength The length in bytes of passwordData //virtual bool Console2LobbyConnect( void *networkServiceId, const char *passwordData, int passwordDataLength )=0; /// \brief Stops the network threads and closes all connections. /// \param[in] blockDuration How long, in milliseconds, you should wait for all remaining messages to go out, including ID_DISCONNECTION_NOTIFICATION. If 0, it doesn't wait at all. /// \param[in] orderingChannel If blockDuration > 0, ID_DISCONNECTION_NOTIFICATION will be sent on this channel /// If you set it to 0 then the disconnection notification won't be sent virtual void Shutdown( unsigned int blockDuration, unsigned char orderingChannel=0 )=0; /// Returns if the network thread is running /// \return true if the network thread is running, false otherwise virtual bool IsActive( void ) const=0; /// Fills the array remoteSystems with the SystemAddress of all the systems we are connected to /// \param[out] remoteSystems An array of SystemAddress structures to be filled with the SystemAddresss of the systems we are connected to. Pass 0 to remoteSystems to only get the number of systems we are connected to /// \param[in, out] numberOfSystems As input, the size of remoteSystems array. As output, the number of elements put into the array virtual bool GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const=0; /// Sends a block of data to the specified system that you are connected to. /// This function only works while the connected /// The first byte should be a message identifier starting at ID_USER_PACKET_ENUM /// \param[in] data The block of data to send /// \param[in] length The size in bytes of the data to send /// \param[in] priority What priority level to send on. See PacketPriority.h /// \param[in] reliability How reliability to send this data. See PacketPriority.h /// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream /// \param[in] systemAddress Who to send this packet to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. /// \return False if we are not connected to the specified recipient. True otherwise virtual bool Send( const char *data, const int length, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast )=0; /// Sends a block of data to the specified system that you are connected to. Same as the above version, but takes a BitStream as input. /// \param[in] bitStream The bitstream to send /// \param[in] priority What priority level to send on. See PacketPriority.h /// \param[in] reliability How reliability to send this data. See PacketPriority.h /// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream /// \param[in] systemAddress Who to send this packet to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. /// \return False if we are not connected to the specified recipient. True otherwise /// \note COMMON MISTAKE: When writing the first byte, bitStream->Write((unsigned char) ID_MY_TYPE) be sure it is casted to a byte, and you are not writing a 4 byte enumeration. virtual bool Send( const RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast )=0; /// Sends multiple blocks of data, concatenating them automatically. /// /// This is equivalent to: /// RakNet::BitStream bs; /// bs.WriteAlignedBytes(block1, blockLength1); /// bs.WriteAlignedBytes(block2, blockLength2); /// bs.WriteAlignedBytes(block3, blockLength3); /// Send(&bs, ...) /// /// This function only works while the connected /// \param[in] data An array of pointers to blocks of data /// \param[in] lengths An array of integers indicating the length of each block of data /// \param[in] numParameters Length of the arrays data and lengths /// \param[in] priority What priority level to send on. See PacketPriority.h /// \param[in] reliability How reliability to send this data. See PacketPriority.h /// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream /// \param[in] systemAddress Who to send this packet to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. /// \return False if we are not connected to the specified recipient. True otherwise virtual bool SendList( char **data, const int *lengths, const int numParameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast )=0; /// Gets a message from the incoming message queue. /// Use DeallocatePacket() to deallocate the message after you are done with it. /// User-thread functions, such as RPC calls and the plugin function PluginInterface::Update occur here. /// \return 0 if no packets are waiting to be handled, otherwise a pointer to a packet. /// \note COMMON MISTAKE: Be sure to call this in a loop, once per game tick, until it returns 0. If you only process one packet per game tick they will buffer up. /// sa RakNetTypes.h contains struct Packet virtual Packet* Receive( void )=0; /// Call this to deallocate a message returned by Receive() when you are done handling it. /// \param[in] packet The message to deallocate. virtual void DeallocatePacket( Packet *packet )=0; /// Return the total number of connections we are allowed // TODO - rename for RakNet 3.0 virtual unsigned short GetMaximumNumberOfPeers( void ) const=0; // --------------------------------------------------------------------------------------------Remote Procedure Call Functions - Functions to initialize and perform RPC-------------------------------------------------------------------------------------------- /// \ingroup RAKNET_RPC /// \depreciated Use the AutoRPC plugin instead /// Register a C or static member function as available for calling as a remote procedure call /// \param[in] uniqueID A null-terminated unique string to identify this procedure. See RegisterClassMemberRPC() for class member functions. /// \param[in] functionPointer(...) The name of the function to be used as a function pointer. This can be called whether active or not, and registered functions stay registered unless unregistered virtual void RegisterAsRemoteProcedureCall( const char* uniqueID, void ( *functionPointer ) ( RPCParameters *rpcParms ) )=0; /// \ingroup RAKNET_RPC /// \depreciated Use the AutoRPC plugin instead /// Register a C++ member function as available for calling as a remote procedure call. /// \param[in] uniqueID A null terminated string to identify this procedure. Recommended you use the macro REGISTER_CLASS_MEMBER_RPC to create the string. Use RegisterAsRemoteProcedureCall() for static functions. /// \param[in] functionPointer The name of the function to be used as a function pointer. This can be called whether active or not, and registered functions stay registered unless unregistered with UnregisterAsRemoteProcedureCall /// \sa The sample ObjectMemberRPC.cpp virtual void RegisterClassMemberRPC( const char* uniqueID, void *functionPointer )=0; /// \ingroup RAKNET_RPC /// \depreciated Use the AutoRPC plugin instead /// Unregisters a C function as available for calling as a remote procedure call that was formerly registered with RegisterAsRemoteProcedureCall. Only call offline. /// \param[in] uniqueID A string of only letters to identify this procedure. Recommended you use the macro CLASS_MEMBER_ID for class member functions. virtual void UnregisterAsRemoteProcedureCall( const char* uniqueID )=0; /// \ingroup RAKNET_RPC /// Used by Object member RPC to lookup objects given that object's ID /// Also used by the ReplicaManager plugin /// \param[in] An instance of NetworkIDManager to use for the lookup. virtual void SetNetworkIDManager( NetworkIDManager *manager )=0; /// \return Returns the value passed to SetNetworkIDManager or 0 if never called. virtual NetworkIDManager *GetNetworkIDManager(void) const=0; /// \ingroup RAKNET_RPC /// Calls a C function on the remote system that was already registered using RegisterAsRemoteProcedureCall(). /// \param[in] uniqueID A NULL terminated string identifying the function to call. Recommended you use the macro CLASS_MEMBER_ID for class member functions. /// \param[in] data The data to send /// \param[in] bitLength The number of bits of \a data /// \param[in] priority What priority level to send on. See PacketPriority.h. /// \param[in] reliability How reliability to send this data. See PacketPriority.h. /// \param[in] orderingChannel When using ordered or sequenced message, what channel to order these on. /// \param[in] systemAddress Who to send this message to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. /// \param[in] includedTimestamp Pass a timestamp if you wish, to be adjusted in the usual fashion as per ID_TIMESTAMP. Pass 0 to not include a timestamp. /// \param[in] networkID For static functions, pass UNASSIGNED_NETWORK_ID. For member functions, you must derive from NetworkIDObject and pass the value returned by NetworkIDObject::GetNetworkID for that object. /// \param[in] replyFromTarget If 0, this function is non-blocking. Otherwise it will block while waiting for a reply from the target procedure, which should be remotely written to RPCParameters::replyToSender and copied to replyFromTarget. The block will return early on disconnect or if the sent packet is unreliable and more than 3X the ping has elapsed. /// \return True on a successful packet send (this does not indicate the recipient performed the call), false on failure virtual bool RPC( const char* uniqueID, const char *data, BitSize_t bitLength, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, RakNetTime *includedTimestamp, NetworkID networkID, RakNet::BitStream *replyFromTarget )=0; /// \ingroup RAKNET_RPC /// Calls a C function on the remote system that was already registered using RegisterAsRemoteProcedureCall. /// If you want that function to return data you should call RPC from that system in the same wayReturns true on a successful packet /// send (this does not indicate the recipient performed the call), false on failure /// \param[in] uniqueID A NULL terminated string identifying the function to call. Recommended you use the macro CLASS_MEMBER_ID for class member functions. /// \param[in] data The data to send /// \param[in] bitLength The number of bits of \a data /// \param[in] priority What priority level to send on. See PacketPriority.h. /// \param[in] reliability How reliability to send this data. See PacketPriority.h. /// \param[in] orderingChannel When using ordered or sequenced message, what channel to order these on. /// \param[in] systemAddress Who to send this message to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. /// \param[in] includedTimestamp Pass a timestamp if you wish, to be adjusted in the usual fashion as per ID_TIMESTAMP. Pass 0 to not include a timestamp. /// \param[in] networkID For static functions, pass UNASSIGNED_NETWORK_ID. For member functions, you must derive from NetworkIDObject and pass the value returned by NetworkIDObject::GetNetworkID for that object. /// \param[in] replyFromTarget If 0, this function is non-blocking. Otherwise it will block while waiting for a reply from the target procedure, which should be remotely written to RPCParameters::replyToSender and copied to replyFromTarget. The block will return early on disconnect or if the sent packet is unreliable and more than 3X the ping has elapsed. /// \return True on a successful packet send (this does not indicate the recipient performed the call), false on failure virtual bool RPC( const char* uniqueID, const RakNet::BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, RakNetTime *includedTimestamp, NetworkID networkID, RakNet::BitStream *replyFromTarget )=0; // -------------------------------------------------------------------------------------------- Connection Management Functions-------------------------------------------------------------------------------------------- /// Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out). /// \param[in] target Which system to close the connection to. /// \param[in] sendDisconnectionNotification True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently. /// \param[in] channel Which ordering channel to send the disconnection notification on, if any virtual void CloseConnection( const SystemAddress target, bool sendDisconnectionNotification, unsigned char orderingChannel=0 )=0; /// Returns if a particular systemAddress is connected to us (this also returns true if we are in the process of connecting) /// \param[in] systemAddress The SystemAddress we are referring to /// \param[in] includeInProgress If true, also return true for connections that are in progress but haven't completed /// \param[in] includeDisconnecting If true, also return true for connections that are in the process of disconnecting /// \return True if this system is connected and active, false otherwise. virtual bool IsConnected(const SystemAddress systemAddress, bool includeInProgress=false, bool includeDisconnecting=false)=0; /// Given a systemAddress, returns an index from 0 to the maximum number of players allowed - 1. /// \param[in] systemAddress The SystemAddress we are referring to /// \return The index of this SystemAddress or -1 on system not found. virtual int GetIndexFromSystemAddress( const SystemAddress systemAddress )=0; /// This function is only useful for looping through all systems /// Given an index, will return a SystemAddress. /// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. /// \return The SystemAddress virtual SystemAddress GetSystemAddressFromIndex( int index )=0; /// Bans an IP from connecting. Banned IPs persist between connections but are not saved on shutdown nor loaded on startup. /// param[in] IP Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban all IP addresses starting with 128.0.0 /// \param[in] milliseconds how many ms for a temporary ban. Use 0 for a permanent ban virtual void AddToBanList( const char *IP, RakNetTime milliseconds=0 )=0; /// Allows a previously banned IP to connect. /// param[in] Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will banAll IP addresses starting with 128.0.0 virtual void RemoveFromBanList( const char *IP )=0; /// Allows all previously banned IPs to connect. virtual void ClearBanList( void )=0; /// Returns true or false indicating if a particular IP is banned. /// \param[in] IP - Dotted IP address. /// \return true if IP matches any IPs in the ban list, accounting for any wildcards. False otherwise. virtual bool IsBanned( const char *IP )=0; // --------------------------------------------------------------------------------------------Pinging Functions - Functions dealing with the automatic ping mechanism-------------------------------------------------------------------------------------------- /// Send a ping to the specified connected system. /// \pre The sender and recipient must already be started via a successful call to Startup() /// \param[in] target Which system to ping virtual void Ping( const SystemAddress target )=0; /// Send a ping to the specified unconnected system. The remote system, if it is Initialized, will respond with ID_PONG followed by sizeof(RakNetTime) containing the system time the ping was sent.(Default is 4 bytes - See __GET_TIME_64BIT in RakNetTypes.h /// \param[in] host Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast. /// \param[in] remotePort Which port to connect to on the remote machine. /// \param[in] onlyReplyOnAcceptingConnections Only request a reply if the remote system is accepting connections /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. /// \return true on success, false on failure (unknown hostname) virtual bool Ping( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections, unsigned connectionSocketIndex=0 )=0; /// Returns the average of all ping times read for the specific system or -1 if none read yet /// \param[in] systemAddress Which system we are referring to /// \return The ping time for this system, or -1 virtual int GetAveragePing( const SystemAddress systemAddress )=0; /// Returns the last ping time read for the specific system or -1 if none read yet /// \param[in] systemAddress Which system we are referring to /// \return The last ping time for this system, or -1 virtual int GetLastPing( const SystemAddress systemAddress ) const=0; /// Returns the lowest ping time read or -1 if none read yet /// \param[in] systemAddress Which system we are referring to /// \return The lowest ping time for this system, or -1 virtual int GetLowestPing( const SystemAddress systemAddress ) const=0; /// Ping the remote systems every so often, or not. This is off by default. Can be called anytime. /// \param[in] doPing True to start occasional pings. False to stop them. virtual void SetOccasionalPing( bool doPing )=0; // --------------------------------------------------------------------------------------------Static Data Functions - Functions dealing with API defined synchronized memory-------------------------------------------------------------------------------------------- /// Sets the data to send along with a LAN server discovery or offline ping reply. /// \a length should be under 400 bytes, as a security measure against flood attacks /// \param[in] data a block of data to store, or 0 for none /// \param[in] length The length of data in bytes, or 0 for none /// \sa Ping.cpp virtual void SetOfflinePingResponse( const char *data, const unsigned int length )=0; /// Returns pointers to a copy of the data passed to SetOfflinePingResponse /// \param[out] data A pointer to a copy of the data passed to \a SetOfflinePingResponse() /// \param[out] length A pointer filled in with the length parameter passed to SetOfflinePingResponse() /// \sa SetOfflinePingResponse virtual void GetOfflinePingResponse( char **data, unsigned int *length )=0; //--------------------------------------------------------------------------------------------Network Functions - Functions dealing with the network in general-------------------------------------------------------------------------------------------- /// Return the unique address identifier that represents you on the the network and is based on your local IP / port. /// \return the identifier of your system internally, which may not be how other systems see if you if you are behind a NAT or proxy virtual SystemAddress GetInternalID( const SystemAddress systemAddress=UNASSIGNED_SYSTEM_ADDRESS ) const=0; /// Return the unique address identifier that represents you on the the network and is based on your externalIP / port /// (the IP / port the specified player uses to communicate with you) /// \param[in] target Which remote system you are referring to for your external ID. Usually the same for all systems, unless you have two or more network cards. virtual SystemAddress GetExternalID( const SystemAddress target ) const=0; /// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message. /// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug. /// \param[in] timeMS Time, in MS /// \param[in] target Which system to do this for. Pass UNASSIGNED_SYSTEM_ADDRESS for all systems. virtual void SetTimeoutTime( RakNetTime timeMS, const SystemAddress target )=0; /// Set the MTU per datagram. It's important to set this correctly - otherwise packets will be needlessly split, decreasing performance and throughput. /// Maximum allowed size is MAXIMUM_MTU_SIZE. /// Too high of a value will cause packets not to arrive at worst and be fragmented at best. /// Too low of a value will split packets unnecessarily. /// Recommended size is 1500 /// sa MTUSize.h /// \param[in] size The MTU size /// \param[in] target Which system to set this for. UNASSIGNED_SYSTEM_ADDRESS to set the default, for new systems /// \pre Can only be called when not connected. /// \return false on failure (we are connected), else true virtual bool SetMTUSize( int size, const SystemAddress target=UNASSIGNED_SYSTEM_ADDRESS )=0; /// Returns the current MTU size /// \param[in] target Which system to get this for. UNASSIGNED_SYSTEM_ADDRESS to get the default /// \return The current MTU size virtual int GetMTUSize( const SystemAddress target ) const=0; /// Returns the number of IP addresses this system has internally. Get the actual addresses from GetLocalIP() virtual unsigned GetNumberOfAddresses( void )=0; /// Returns an IP address at index 0 to GetNumberOfAddresses-1 /// \param[in] index index into the list of IP addresses /// \return The local IP address at this index virtual const char* GetLocalIP( unsigned int index )=0; /// Is this a local IP? /// \param[in] An IP address to check, excluding the port /// \return True if this is one of the IP addresses returned by GetLocalIP virtual bool IsLocalIP( const char *ip )=0; /// Allow or disallow connection responses from any IP. Normally this should be false, but may be necessary /// when connecting to servers with multiple IP addresses. /// \param[in] allow - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections virtual void AllowConnectionResponseIPMigration( bool allow )=0; /// Sends a one byte message ID_ADVERTISE_SYSTEM to the remote unconnected system. /// This will tell the remote system our external IP outside the LAN along with some user data. /// \pre The sender and recipient must already be started via a successful call to Initialize /// \param[in] host Either a dotted IP address or a domain name /// \param[in] remotePort Which port to connect to on the remote machine. /// \param[in] data Optional data to append to the packet. /// \param[in] dataLength length of data in bytes. Use 0 if no data. /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. /// \return false if IsActive()==false or the host is unresolvable. True otherwise virtual bool AdvertiseSystem( const char *host, unsigned short remotePort, const char *data, int dataLength, unsigned connectionSocketIndex=0 )=0; /// Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads. /// ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived /// As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned. /// Defaults to 0 (never return this notification) /// \param[in] interval How many messages to use as an interval virtual void SetSplitMessageProgressInterval(int interval)=0; /// Returns what was passed to SetSplitMessageProgressInterval() /// \return What was passed to SetSplitMessageProgressInterval(). Default to 0. virtual int GetSplitMessageProgressInterval(void) const=0; /// Set how long to wait before giving up on sending an unreliable message /// Useful if the network is clogged up. /// Set to 0 or less to never timeout. Defaults to 0. /// \param[in] timeoutMS How many ms to wait before simply not sending an unreliable message. virtual void SetUnreliableTimeout(RakNetTime timeoutMS)=0; /// Send a message to host, with the IP socket option TTL set to 3 /// This message will not reach the host, but will open the router. /// Used for NAT-Punchthrough virtual void SendTTL( const char* host, unsigned short remotePort, int ttl, unsigned connectionSocketIndex=0 )=0; // --------------------------------------------------------------------------------------------Compression Functions - Functions related to the compression layer-------------------------------------------------------------------------------------------- /// Enables or disables frequency table tracking. This is required to get a frequency table, which is used in GenerateCompressionLayer() /// This value persists between connect calls and defaults to false (no frequency tracking) /// \pre You can call this at any time - however you SHOULD only call it when disconnected. Otherwise you will only trackpart of the values sent over the network. /// \param[in] doCompile True to enable tracking virtual void SetCompileFrequencyTable( bool doCompile )=0; /// Returns the frequency of outgoing bytes into output frequency table /// The purpose is to save to file as either a master frequency table from a sample game session for passing to /// GenerateCompressionLayer() /// \pre You should only call this when disconnected. Requires that you first enable data frequency tracking by calling SetCompileFrequencyTable(true) /// \param[out] outputFrequencyTable The frequency of each corresponding byte /// \return False (failure) if connected or if frequency table tracking is not enabled. Otherwise true (success) virtual bool GetOutgoingFrequencyTable( unsigned int outputFrequencyTable[ 256 ] )=0; /// This is an optional function to generate the compression layer based on the input frequency table. /// If you want to use it you should call this twice - once with inputLayer as true and once as false. /// The frequency table passed here with inputLayer=true should match the frequency table on the recipient with inputLayer=false. /// Likewise, the frequency table passed here with inputLayer=false should match the frequency table on the recipient with inputLayer=true. /// Calling this function when there is an existing layer will overwrite the old layer. /// \pre You should only call this when disconnected /// \param[in] inputFrequencyTable A frequency table for your data /// \param[in] inputLayer Is this the input layer? /// \return false (failure) if connected. Otherwise true (success) /// \sa Compression.cpp virtual bool GenerateCompressionLayer( unsigned int inputFrequencyTable[ 256 ], bool inputLayer )=0; /// Delete the output or input layer as specified. This is not necessary to call and is only valuable for freeing memory. /// \pre You should only call this when disconnected /// \param[in] inputLayer True to mean the inputLayer, false to mean the output layer /// \return false (failure) if connected. Otherwise true (success) virtual bool DeleteCompressionLayer( bool inputLayer )=0; /// Returns the compression ratio. A low compression ratio is good. Compression is for outgoing data /// \return The compression ratio virtual float GetCompressionRatio( void ) const=0; ///Returns the decompression ratio. A high decompression ratio is good. Decompression is for incoming data /// \return The decompression ratio virtual float GetDecompressionRatio( void ) const=0; // -------------------------------------------------------------------------------------------- Plugin Functions-------------------------------------------------------------------------------------------- /// Attatches a Plugin interface to run code automatically on message receipt in the Receive call /// \note If plugins have dependencies on each other then the order does matter - for example the router plugin should go first because it might route messages for other plugins /// \param[in] messageHandler Pointer to a plugin to attach virtual void AttachPlugin( PluginInterface *plugin )=0; /// Detaches a Plugin interface to run code automatically on message receipt /// \param[in] messageHandler Pointer to a plugin to detach virtual void DetachPlugin( PluginInterface *messageHandler )=0; // --------------------------------------------------------------------------------------------Miscellaneous Functions-------------------------------------------------------------------------------------------- /// Put a message back at the end of the receive queue in case you don't want to deal with it immediately /// \param[in] packet The packet you want to push back. /// \param[in] pushAtHead True to push the packet so that the next receive call returns it. False to push it at the end of the queue (obviously pushing it at the end makes the packets out of order) virtual void PushBackPacket( Packet *packet, bool pushAtHead )=0; /// \Internal // \param[in] routerInterface The router to use to route messages to systems not directly connected to this system. virtual void SetRouterInterface( RouterInterface *routerInterface )=0; /// \Internal // \param[in] routerInterface The router to use to route messages to systems not directly connected to this system. virtual void RemoveRouterInterface( RouterInterface *routerInterface )=0; /// \Returns a packet for you to write to if you want to create a Packet for some reason. /// You can add it to the receive buffer with PushBackPacket /// \param[in] dataSize How many bytes to allocate for the buffer /// \return A packet you can write to virtual Packet* AllocatePacket(unsigned dataSize)=0; // --------------------------------------------------------------------------------------------Network Simulator Functions-------------------------------------------------------------------------------------------- /// Adds simulated ping and packet loss to the outgoing data flow. /// To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and maxSendBPS value on each. /// You can exclude network simulator code with the _RELEASE #define to decrease code size /// \depreciated Use http://www.jenkinssoftware.com/raknet/forum/index.php?topic=1671.0 instead. /// \param[in] maxSendBPS Maximum bits per second to send. Packetloss grows linearly. 0 to disable. (CURRENTLY BROKEN - ALWAYS DISABLED) /// \param[in] minExtraPing The minimum time to delay sends. /// \param[in] extraPingVariance The additional random time to delay sends. virtual void ApplyNetworkSimulator( double maxSendBPS, unsigned short minExtraPing, unsigned short extraPingVariance)=0; /// Limits how much outgoing bandwidth can be sent per-connection. /// This limit does not apply to the sum of all connections! /// Exceeding the limit queues up outgoing traffic /// \param[in] maxBitsPerSecond Maximum bits per second to send. Use 0 for unlimited (default). Once set, it takes effect immedately and persists until called again. virtual void SetPerConnectionOutgoingBandwidthLimit( unsigned maxBitsPerSecond )=0; /// Returns if you previously called ApplyNetworkSimulator /// \return If you previously called ApplyNetworkSimulator virtual bool IsNetworkSimulatorActive( void )=0; // --------------------------------------------------------------------------------------------Statistical Functions - Functions dealing with API performance-------------------------------------------------------------------------------------------- /// Returns a structure containing a large set of network statistics for the specified system. /// You can map this data to a string using the C style StatisticsToString() function /// \param[in] systemAddress: Which connected system to get statistics for /// \return 0 on can't find the specified system. A pointer to a set of data otherwise. /// \sa RakNetStatistics.h virtual RakNetStatistics * const GetStatistics( const SystemAddress systemAddress )=0; // --------------------------------------------------------------------------------------------EVERYTHING AFTER THIS COMMENT IS FOR INTERNAL USE ONLY-------------------------------------------------------------------------------------------- /// \internal virtual char *GetRPCString( const char *data, const BitSize_t bitSize, const SystemAddress systemAddress)=0; /// \internal virtual bool SendOutOfBand(const char *host, unsigned short remotePort, MessageID header, const char *data, BitSize_t dataLength, unsigned connectionSocketIndex=0 )=0; }; #endif
[ [ [ 1, 558 ] ] ]
93dec01d89d3e4786881c0d1ccc420751468e4a0
6581dacb25182f7f5d7afb39975dc622914defc7
/CodeProject/ComAggregationSrc/AggregationClient/AggregationClient.cpp
1b90e12ab9d096d69d3c93f1c5afa322f9c2236f
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,200
cpp
// This is the client which will be using the services provided // by AggregationSample.dll and AggregableObject.dll servers. // The client should be unaware of the fact that the outer component // is aggregating the inner component. // This is the AggregationClient Implementation. // Code By Dinesh Ahuja, October 25,2003. #include <iostream.h> #include "CScientific.h" #include "CBasic.h" // Outer Component CLSID: {E247F701-0743-11d8-B532-30A64EC10000} static const CLSID CLSID_CScientific = { 0xe247f701, 0x743, 0x11d8, { 0xb5, 0x32, 0x30, 0xa6, 0x4e, 0xc1, 0x0, 0x0 } }; // {E247F702-0743-11d8-B532-30A64EC10000} static const CLSID CLSID_CBasic = { 0xe247f702, 0x743, 0x11d8, { 0xb5, 0x32, 0x30, 0xa6, 0x4e, 0xc1, 0x0, 0x0 } }; int main() { // Call this to Initialize COM Runtime Library.for the current thread. CoInitialize(NULL); cout<<"CScientific Creation Process starts"<<endl; // This is meant for storing the error description, corrosponding // to HRESULT. void * pMsgBuf; IClassFactory *pIFactory = NULL; // Request for a IClassFactory interface pointer on the class object. HRESULT hResult = CoGetClassObject(CLSID_CScientific,CLSCTX_INPROC_SERVER,NULL,IID_IClassFactory,(void**)&pIFactory); if(SUCCEEDED(hResult)) { cout<<"IClassFactory pointer on class object for CScientific succeeded"<<endl; IUnknown *pUnk = NULL; // This will create a CMath's instance and returns an IUnknown // pointer on that component. hResult = pIFactory->CreateInstance(NULL,IID_IUnknown,(void**)&pUnk); /* After instantiating the CMath's instance, the class object can be ** released from memory. ** At this point, we will release class object by calling Release ** on IClassFactory. */ cout<<"Calling Release on the IClassFactory for CScientific's instance"<<endl; pIFactory->Release(); pIFactory = NULL; if(SUCCEEDED(hResult)) { ITrignometry *pITrignometry = NULL; /* Request for IMath interface on the component by using the ** IUnknown interface pointer on component. */ hResult = pUnk->QueryInterface(IID_ITrignometry,(void**)&pITrignometry); pUnk->Release(); // If succeeded, then we can call the methods of IMath. if(SUCCEEDED(hResult)) { double RetVal; double pi = 3.1415926535; pITrignometry->GetSin(pi/2,&RetVal); cout<<"CScientific::GetSin's returned value: "<<RetVal<<endl; IAddSub* pAddSub = NULL; // This QueryInterface will cause the reference count // of the outer component to be incremented by 1. cout<<"ITrignometry Interface queries for IAddSub Interface"<<endl; hResult = pITrignometry->QueryInterface(IID_IAddSub,(void**) &pAddSub); cout<<"Returned: ITrignometry Interface queries for IAddSub Interface"<<endl; // The increment in the above QueryInterface call has to be nullified // ,otherwise the outer component will not be released. // This Release will decrement the reference count on the // outer component. cout<<"Calling Release to Nullify the increment in Reference count"<<endl; static_cast<IUnknown*>(pITrignometry)->Release(); cout<<"Returned: Release to Nullify the increment in Reference count"<<endl; IUnknown* pUnknown = NULL; // This will return the Controlling outer IUnknown pointer. // This will increment the reference count of the outer component by 1. cout<<"pAddSub pointer queries for IUnknown pointer"<<endl; hResult = pAddSub->QueryInterface(IID_IUnknown,(void**) &pUnknown); cout<<"Returned: pAddSub pointer queries for IUnknown pointer"<<endl; // Client is using the service provided by the IAddSub Interface. int retVal = 0; pAddSub->GetAdd(10,20,&retVal); cout<<"Output of IAddSub::GetAdd is: "<<retVal<<endl; // The increment in the above QueryInterface call has to be nullified // ,otherwise the outer component will not be released. // This Release will decrement the reference count on the // outer component. cout<<"Calling Release to Nullify the increment in Reference count"<<endl; pUnknown->Release(); cout<<"Returned: Release to Nullify the increment in Reference count"<<endl; /* This call to Release() will cause the component to be ** released from memory. */ cout<<"Final Release on the Outer Component"<<endl; pITrignometry->Release(); } else { // This gives a string description for the error. ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,NULL, hResult,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPTSTR)&pMsgBuf,0,NULL); cout<<(LPTSTR)pMsgBuf<<endl; LocalFree((HLOCAL)pMsgBuf); } } } else { // This gives a string description for the error. ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,NULL, hResult,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPTSTR)&pMsgBuf,0,NULL); cout<<(LPTSTR)pMsgBuf<<endl; LocalFree((HLOCAL)pMsgBuf); } cout<<"CScientific Creation Process ends."<<endl; CoUninitialize(); return 0; }
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 140 ] ] ]
6c5b329269f11f93ae8a3c36edce3673247ee1c5
cdf231431217413f50c2f1193e56271a09e856ac
/่ฎก็ฎ—ๆœบๅ›พๅฝขๅญฆ/ParticleSystem/ParticlePattern/quat.h
4893b1e7ba85f35e2a473f488e4b0e25afd7d63b
[]
no_license
zinking/wz-graduate-project
98ae89870f0d1557b12a449794480ead34f5fc46
de60b4fd04c861a6cd03884d16fa50540e7c52a4
refs/heads/master
2016-09-05T21:40:50.946079
2009-07-24T11:39:32
2009-07-24T11:39:32
32,133,474
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
h
/* * * quat.h * * EXPLANATION: * calc quaternion * * IMPLEMENTATION: * quat.cpp * * AUTHOR: * Daisuke Iwai * */ #pragma once #include <math.h> struct QUAT { float w, x, y, z; }; typedef struct QUAT quat; class Quaternion { public: /* * c'tor/d'tor */ Quaternion(); ~Quaternion(); /* * a = 0 */ void quat_zero(quat *a); /* * a = 1 */ void quat_identity(quat *a); /* * a = (w, x, y, z) */ void quat_assign(quat *a, float w, float x, float y, float z); /* * a = b + c */ void quat_add(quat *a, const quat *b, const quat *c); /* * a = b - c */ void quat_sub(quat *a, const quat *b, const quat *c); /* * a = b * c */ void quat_mul(quat *a, const quat *b, const quat *c); /* * a = s * b */ void quat_mul_real(quat *a, float s, const quat *b); /* * a = b / s */ void quat_div_real(quat *a, const quat *b, float s); /* * ||a||^2 */ float quat_norm_sqr(const quat *a); /* * ||a|| */ float quat_norm(const quat *a); };
[ "zinking3@927cf1a0-783d-11de-8a01-315fa775be5f" ]
[ [ [ 1, 84 ] ] ]
b0a8b2f9242b1c89a1e28cd1aa3509b993c04632
1cad3b6a31431aad44ca792adea12cebf15afe5e
/ReadSoftwareSerial/ReadSoftwareSerial.ino
1cf774dd971f33e517e4313fdf09be12859de0d6
[]
no_license
martikaljuve/vabalinn
98dc8ab732470bf56b762e61f9dc007504769dfc
f6dff8fa85eda59fa04238e2f6385725dac9854c
refs/heads/master
2016-09-06T13:56:43.077821
2011-11-14T19:25:49
2011-11-14T19:25:49
2,520,450
0
0
null
null
null
null
UTF-8
C++
false
false
286
ino
#include <SoftwareSerial.h> SoftwareSerial serial = SoftwareSerial(11, 3); void setup() { serial.begin(57600); Serial.begin(115200); } char c; void loop() { if (serial.available()) { c = serial.read(); if (c == '$') Serial.println(); Serial.write(c); } }
[ [ [ 1, 18 ] ] ]
6926683ac48c3d2e6d377ca90d8e3a46990deb09
6581dacb25182f7f5d7afb39975dc622914defc7
/ZTable/comdate.h
0096d288537bfdff25cf3b40c0678b805bcf1590
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
36,614
h
// comdate.h ///////////////////////////////////////////////////////////////////////////// // Copyright (c) 1998-2000 Chris Sells // All rights reserved. // // NO WARRANTIES ARE EXTENDED. USE AT YOUR OWN RISK. // // To contact the author with suggestions or comments, use [email protected]. ///////////////////////////////////////////////////////////////////////////// // History: // 9/27/01 - Dropped in operator SYSTEMTIME() and operator FILETIME() from // Scott Zionic [[email protected]]. Thanks, Scott. // 4/9/01 - Implemented operator time_t() and operator struct tm() as per // Shawn Wildermuth's request. // 2/8/01 - Fixed a rounding bug in CComSpan reported by Ralf Mohaupt // [[email protected]]. // 11/4/00 - Moved everything to the header file for convenience. // 4/13/00 - Sudhakar M [[email protected]] contributed // CComDATE(const struct tm& tmSrc), from which I also extrapolated // CComDATE::operator=(const struct tm& tmSrc). // 3/10/00 - Inspired by Eric White [[email protected]] to add an // operator DBTIMESTAMP using his implementation. Also added // extra ctor, operator= and conversion operators for other date/time // formats, but haven't implemented all of them yet. // Inspired by Artyom Tyazhelov [[email protected]] to // leave current time alone when calling SetDate and leaving current // date alone when calling SetTime. // 1/15/00 - Fixed a 2038 bug in Now. Thanks Michael Entin [[email protected]]. // 7/14/99 - Fixed a linker problem w/ some inline functions release // builds. Thanks to David Maw [[email protected]] for // first pointing it out. // 6/9/99 - Fixed a problem in Maketm where tm_isdst was not being set // (as is required by the CRT). Thanks to Jim Hoffman // [[email protected]] for pointing it out. // 4/18/99 - Fixed a problem in Format to provide a work-around in the // VC6 implementation of wcsftime. Thanks for Joe O'Leary for // pointing it out. // Even better, Joe also contributed FormatDate and FormatTime // to wrap the National Language Support functions GetTimeFormat() // and GetDateFormat(). Thanks, Joe! // Also, Juan Rivera ([email protected]) pointed out a missing operator= // declaration. Thanks, Juan. // 12/24/98 - Based on a suggestion by Ronald Laeremans [[email protected]], // replaced all of the manual Maketm code w/ VariantToSystemTime. // Also updated MakeDATE to use SystemTimeToVariantTime. Thanks, Ron! // 12/23/98 - Fixed a bug Ward pointed out in CComDATE::operator=(const time_t&). // 12/21/98 - Ward Fuller <[email protected]> pointed out a BSTR leak in // the Format implementation. It's plugged. Thanks, Ward! // 12/21/98 - Initial release. ///////////////////////////////////////////////////////////////////////////// // The file provides two class for use with dates and times under Windows. // // CComDATE: Wraps the COM DATE type, providing conversions from VARIANT, // DATE, ANSI string, UNICODE string, time_t, SYSTEMTIME, FILETIME, // DOS time and DBTIMESTAMP data types. // // CComSpan: Represents the result of subtracting one CComDATE from another. // Useful for time/date math. // // NOTE: This usage of these classes are based loosely on the MFC classes // COleDateTime and COleDateTimeSpan. However, the implementation is 99% mine. #pragma once #ifndef __COMDATE_H__ #define __COMDATE_H__ #include <time.h> #include <limits.h> #include <tchar.h> #include <math.h> // ceil, floor and modf #include <winnls.h> ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma warning(disable :4996) // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CComDATE class class CComSpan; // Forward declaration class CComDATE { public: static CComDATE Now(); static bool IsValidDate(const DATE& dt); //////////////////////////////////////////////// //Common date helper functions, added by Zhu Li //DateAdd //Parameters: //1. datepart: // Is the parameter that specifies on which part of the date to return a new value. // The table lists the dateparts and abbreviations recognized for now // "Y" for Year // "M" for Month // "D" for Day //2. number: // Is the value used to increment datepart. //3. date: // Is the original date static DATE DateAdd(const TCHAR* datepart, long number, DATE date); CComDATE(); CComDATE(const CComDATE& dtSrc); CComDATE(const VARIANT& varSrc); CComDATE(DATE dtSrc); CComDATE(const char* pszSrc); CComDATE(const wchar_t* pszSrc); CComDATE(time_t timeSrc); CComDATE(const struct tm& tmSrc); CComDATE(const SYSTEMTIME& systimeSrc); CComDATE(const FILETIME& filetimeSrc); CComDATE(long nYear, long nMonth, long nDay, long nHour = 0, long nMin = 0, long nSec = 0); CComDATE(WORD wDosDate, WORD wDosTime); #ifdef __oledb_h__ CComDATE(const DBTIMESTAMP& dbts); #endif public: bool IsValid() const; long Year() const; long Month() const; // month of year (1 = Jan) long Day() const; // day of month (1-31) long Hour() const; // hour in day (0-23) long Minute() const; // minute in hour (0-59) long Second() const; // second in minute (0-59) long DayOfWeek() const; // 1=Sun, 2=Mon, ..., 7=Sat long DayOfYear() const; // days since start of year, Jan 1 = 1 bool IsLeapYear() const; // Whether it's a leap year or not bool IsNoon() const; // Whether it's 12:00:00pm or not bool IsMidnight() const; // Whether it's 12:00:00am or not // Operations public: const CComDATE& operator=(const CComDATE& dtSrc); const CComDATE& operator=(const VARIANT& varSrc); const CComDATE& operator=(DATE dtSrc); const CComDATE& operator=(const char* pszSrc); const CComDATE& operator=(const wchar_t* pszSrc); const CComDATE& operator=(const time_t& timeSrc); const CComDATE& operator=(const struct tm& tmSrc); const CComDATE& operator=(const SYSTEMTIME& systimeSrc); const CComDATE& operator=(const FILETIME& filetimeSrc); #ifdef __oledb_h__ const CComDATE& CComDATE::operator=(const DBTIMESTAMP& dbts); #endif bool operator==(const CComDATE& date) const; bool operator!=(const CComDATE& date) const; bool operator<(const CComDATE& date) const; bool operator>(const CComDATE& date) const; bool operator<=(const CComDATE& date) const; bool operator>=(const CComDATE& date) const; // Date math const CComDATE& operator+=(const CComSpan& span); const CComDATE& operator-=(const CComSpan& span); friend CComDATE operator+(const CComDATE& date, const CComSpan& span); friend CComDATE operator-(const CComDATE& date, const CComSpan& span); friend CComDATE operator+(const CComSpan& span, const CComDATE& date); friend CComSpan operator-(const CComDATE& date1, const CComDATE& date2); operator DATE() const; DATE* operator&(); operator VARIANT() const; operator time_t() const; operator struct tm() const; operator SYSTEMTIME() const; operator FILETIME() const; #ifdef __oledb_h__ operator DBTIMESTAMP() const; #endif bool SetDateTime(long nYear, long nMonth, long nDay, long nHour, long nMin, long nSec); bool SetDate(long nYear, long nMonth, long nDay); bool SetTime(long nHour, long nMin, long nSec); bool ParseDateTime(const char* lpszDate, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT); bool ParseDateTime(const wchar_t* lpszDate, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT); // Formatting LPTSTR Format(LPTSTR pszOut, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT) const; LPTSTR Format(LPTSTR pszOut, LPCTSTR lpszFormat) const; #ifdef __ATLCOM_H__ LPTSTR Format(LPTSTR pszOut, UINT nFormatID, HINSTANCE hinst = _Module.GetResourceInstance()) const; #else LPTSTR Format(LPTSTR pszOut, UINT nFormatID, HINSTANCE hinst = GetModuleHandle(0)) const; #endif // Formatting using National Language Support functions GetTimeFormat() and GetDateFormat() LPTSTR FormatTime(LPTSTR pszOut, LPCTSTR szFmt=NULL, DWORD dwFlags=0, LCID lcid=LOCALE_USER_DEFAULT) const; LPTSTR FormatDate(LPTSTR pszOut, LPCTSTR szFmt=NULL, DWORD dwFlags=0, LCID lcid=LOCALE_USER_DEFAULT) const; protected: enum { COMDATE_ERROR = INT_MIN, MIN_DATE = -657434L, // About year 100 MAX_DATE = 2958465L, // About year 9999 INVALID_DATE = (MIN_DATE-1), // Used to indicate invalid date }; protected: DATE m_date; protected: void Invalidate(); }; ///////////////////////////////////////////////////////////////////////////// // CComSpan class class CComSpan { public: CComSpan(); CComSpan(double dblSpanSrc); CComSpan(const CComSpan& dateSpanSrc); CComSpan(long nDays, long nHours = 0, long nMins = 0, long nSecs = 0); bool IsValid() const; double TotalDays() const; // span in days (about -3.65e6 to 3.65e6) double TotalHours() const; // span in hours (about -8.77e7 to 8.77e6) double TotalMinutes() const; // span in minutes (about -5.26e9 to 5.26e9) double TotalSeconds() const; // span in seconds (about -3.16e11 to 3.16e11) long Days() const; // component days in span long Hours() const; // component hours in span (-23 to 23) long Minutes() const; // component minutes in span (-59 to 59) long Seconds() const; // component seconds in span (-59 to 59) public: const CComSpan& operator=(double dblSpanSrc); const CComSpan& operator=(const CComSpan& dateSpanSrc); bool operator==(const CComSpan& dateSpan) const; bool operator!=(const CComSpan& dateSpan) const; bool operator<(const CComSpan& dateSpan) const; bool operator>(const CComSpan& dateSpan) const; bool operator<=(const CComSpan& dateSpan) const; bool operator>=(const CComSpan& dateSpan) const; // Math const CComSpan& operator+=(const CComSpan& rhs); const CComSpan& operator-=(const CComSpan& rhs); CComSpan operator-() const; friend CComSpan operator+(const CComSpan& span1, const CComSpan& span2); friend CComSpan operator-(const CComSpan& span1, const CComSpan& span2); operator double() const; void SetSpan(long nDays, long nHours, long nMins, long nSecs); protected: enum { MAX_SPAN = 3615897L, MIN_SPAN = -MAX_SPAN, INVALID_SPAN = (MIN_SPAN-1), // Used to indicate invalid span }; protected: double m_span; protected: void Invalidate(); }; ///////////////////////////////////////////////////////////////////////////// // CComDATE inline implementations inline bool CComDATE::IsValidDate(const DATE& dt) { // About year 100 to about 9999 return (dt >= MIN_DATE && dt <= MAX_DATE); } inline CComDATE CComDATE::Now() { SYSTEMTIME sysTime; GetLocalTime(&sysTime); return CComDATE(sysTime); } //////////////////////////////////////////////////////////////////////////////////// //DateAdd //Parameters: //1. datepart: // Is the parameter that specifies on which part of the date to return a new value. // The table lists the dateparts and abbreviations recognized for now // "Y" for Year // "M" for Month // "D" for Day //2. number: // Is the value used to increment datepart. //3. date: // Is the original date inline DATE CComDATE::DateAdd(const TCHAR* datepart, long number, DATE date) { CComDATE dt,dteRet; dteRet=date; dt=date; long arrDaysInMonth[]={31,28,31,30,31,30,31,31,30,31,30,31}; long nYears,nMonths,nDays; if(_tcsncicmp( datepart, _T("y") , 1 )==0) //add years { dteRet.SetDate(dt.Year()+number,dt.Month(),1); if(dteRet.IsLeapYear()) arrDaysInMonth[1]=29; if((dt.Day()>arrDaysInMonth[1])&&(dt.Month()==2)) nDays=arrDaysInMonth[1]; else nDays=dt.Day(); dteRet.SetDate(dt.Year()+number,dt.Month(),nDays); } else if(_tcsncicmp( datepart, _T("m") , 1 )==0) //add months { nYears=number/12; nMonths=number%12; if((nMonths+dt.Month())<=0) { nYears-=1; nMonths=nMonths+12; } else if((nMonths+dt.Month())>12) { nYears+=1; nMonths=nMonths-12; } dteRet.SetDate(dt.Year()+nYears,dt.Month()+nMonths,1); if(dteRet.IsLeapYear()) arrDaysInMonth[1]=29; if (dt.Day()>arrDaysInMonth[dteRet.Month()-1]) nDays = arrDaysInMonth[dteRet.Month()-1]; else nDays = dt.Day(); dteRet.SetDate(dt.Year()+nYears,dt.Month()+nMonths,nDays); } else if(_tcsncicmp( datepart, _T("d") , 1 )==0) //add days { CComSpan spanDays(number); dteRet=dt+spanDays; } return (DATE)dteRet; } inline CComDATE::CComDATE() { Invalidate(); } inline CComDATE::CComDATE(const CComDATE& dtSrc) { m_date = dtSrc.m_date; } inline CComDATE::CComDATE(const VARIANT& varSrc) { *this = varSrc; } inline CComDATE::CComDATE(DATE dtSrc) { m_date = dtSrc; } inline CComDATE::CComDATE(const char* pszSrc) { ParseDateTime(pszSrc); } inline CComDATE::CComDATE(const wchar_t* pszSrc) { ParseDateTime(pszSrc); } inline CComDATE::CComDATE(time_t timeSrc) { *this = timeSrc; } inline CComDATE::CComDATE(const struct tm& tmSrc) { SetDateTime(tmSrc.tm_year + 1900, tmSrc.tm_mon + 1, tmSrc.tm_mday, tmSrc.tm_hour, tmSrc.tm_min, tmSrc.tm_sec); } inline CComDATE::CComDATE(const SYSTEMTIME& systimeSrc) { *this = systimeSrc; } inline CComDATE::CComDATE(const FILETIME& filetimeSrc) { *this = filetimeSrc; } inline CComDATE::CComDATE(long nYear, long nMonth, long nDay, long nHour, long nMin, long nSec) { SetDateTime(nYear, nMonth, nDay, nHour, nMin, nSec); } inline CComDATE::CComDATE(WORD wDosDate, WORD wDosTime) { if( !DosDateTimeToVariantTime(wDosDate, wDosTime, &m_date) ) Invalidate(); } inline const CComDATE& CComDATE::operator=(const CComDATE& dtSrc) { m_date = dtSrc.m_date; return *this; } inline const CComDATE& CComDATE::operator=(const char* pszSrc) { ParseDateTime(pszSrc); return *this; } inline const CComDATE& CComDATE::operator=(const wchar_t* pszSrc) { ParseDateTime(pszSrc); return *this; } inline bool CComDATE::operator==(const CComDATE& date) const { return (m_date == date.m_date); } inline bool CComDATE::operator!=(const CComDATE& date) const { return (m_date != date.m_date); } inline CComDATE::operator DATE() const { return m_date; } inline DATE* CComDATE::operator&() { return &m_date; } inline bool CComDATE::SetDate(long nYear, long nMonth, long nDay) { return SetDateTime(nYear, nMonth, nDay, Hour(), Minute(), Second()); } inline bool CComDATE::SetTime(long nHour, long nMin, long nSec) { return SetDateTime(Year(), Month(), Day(), nHour, nMin, nSec); } inline const CComDATE& CComDATE::operator+=(const CComSpan& span) { *this = *this + span; return *this; } inline const CComDATE& CComDATE::operator-=(const CComSpan& span) { *this = *this - span; return *this; } inline bool CComDATE::IsValid() const { return IsValidDate(m_date); } inline void CComDATE::Invalidate() { m_date = INVALID_DATE; } #ifdef __oledb_h__ inline CComDATE::CComDATE(const DBTIMESTAMP& dbts) { SetDateTime(dbts.year, dbts.month, dbts.day, dbts.hour, dbts.minute, dbts.second); } inline const CComDATE& CComDATE::operator=(const DBTIMESTAMP& dbts) { SetDateTime(dbts.year, dbts.month, dbts.day, dbts.hour, dbts.minute, dbts.second); return *this; } #endif // __oledb_h__ ///////////////////////////////////////////////////////////////////////////// // CComSpan inline implementations inline CComSpan::CComSpan() { Invalidate(); } inline CComSpan::CComSpan(double db) : m_span(db) {} inline CComSpan::CComSpan(const CComSpan& rhs) { m_span = rhs.m_span; } inline CComSpan::CComSpan(long nDays, long nHours, long nMins, long nSecs) { SetSpan(nDays, nHours, nMins, nSecs); } inline const CComSpan& CComSpan::operator=(double db) { m_span = db; return *this; } inline const CComSpan& CComSpan::operator=(const CComSpan& span) { m_span = span.m_span; return *this; } inline double CComSpan::TotalDays() const { _ASSERTE(IsValid()); return m_span; } inline double CComSpan::TotalHours() const { _ASSERTE(IsValid()); return m_span * 24; } inline double CComSpan::TotalMinutes() const { _ASSERTE(IsValid()); return m_span * 24 * 60; } inline double CComSpan::TotalSeconds() const { _ASSERTE(IsValid()); return m_span * 24 * 60 * 60; } inline long CComSpan::Days() const { _ASSERTE(IsValid()); return (long)m_span; } inline bool CComSpan::operator==(const CComSpan& rhs) const { return m_span == rhs.m_span; } inline bool CComSpan::operator!=(const CComSpan& rhs) const { return m_span != rhs.m_span; } inline bool CComSpan::operator<(const CComSpan& rhs) const { return m_span < rhs.m_span; } inline bool CComSpan::operator>(const CComSpan& rhs) const { return m_span > rhs.m_span; } inline bool CComSpan::operator<=(const CComSpan& rhs) const { return m_span <= rhs.m_span; } inline bool CComSpan::operator>=(const CComSpan& rhs) const { return m_span >= rhs.m_span; } inline const CComSpan& CComSpan::operator+=(const CComSpan& rhs) { return (*this = *this + rhs); } inline const CComSpan& CComSpan::operator-=(const CComSpan& rhs) { return (*this = *this - rhs); } inline CComSpan CComSpan::operator-() const { return CComSpan(-m_span); } inline CComSpan::operator double() const { return m_span; } inline bool CComSpan::IsValid() const { return (m_span >= MIN_SPAN && m_span <= MAX_SPAN); } inline void CComSpan::Invalidate() { m_span = INVALID_SPAN; } ///////////////////////////////////////////////////////////////////////////// // CComDATE class helper definitions #define HALF_SECOND 1.0/172800.0 // Half a second, expressed in days bool MakeDATE(DATE* pdtDest, WORD wYear, WORD wMonth, WORD wDay, WORD wHour, WORD wMinute, WORD wSecond); bool Maketm(struct tm* ptmDest, DATE dtSrc); double DATEAsDouble(DATE dtSrc); DATE MakeDATE(double dbSrc); ///////////////////////////////////////////////////////////////////////////// // CComDATE class inline long CComDATE::Year() const { struct tm tmDest; if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_year + 1900; return COMDATE_ERROR; } inline long CComDATE::Month() const { struct tm tmDest; if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_mon + 1; return COMDATE_ERROR; } inline long CComDATE::Day() const { struct tm tmDest; if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_mday; return COMDATE_ERROR; } inline long CComDATE::Hour() const { struct tm tmDest; if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_hour; return COMDATE_ERROR; } inline long CComDATE::Minute() const { struct tm tmDest; if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_min; return COMDATE_ERROR; } inline long CComDATE::Second() const { struct tm tmDest; if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_sec; return COMDATE_ERROR; } inline long CComDATE::DayOfWeek() const { struct tm tmDest; if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_wday + 1; return COMDATE_ERROR; } inline long CComDATE::DayOfYear() const { struct tm tmDest; if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_yday + 1; return COMDATE_ERROR; } inline bool CComDATE::IsLeapYear() const { long year = Year(); return ((year != COMDATE_ERROR) && ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0)); } inline bool CComDATE::IsNoon() const { return Hour() == 12 && Minute() == 0 && Second() == 0; } inline bool CComDATE::IsMidnight() const { return Hour() == 0 && Minute() == 0 && Second() == 0; } inline const CComDATE& CComDATE::operator=(const VARIANT& varSrc) { if( varSrc.vt == VT_DATE ) { m_date = varSrc.date; } else { VARIANT varDest = { 0 }; if( SUCCEEDED(VariantChangeType(&varDest, const_cast<VARIANT*>(&varSrc), 0, VT_DATE)) ) { m_date = varDest.date; VariantClear(&varDest); } else { Invalidate(); } } return *this; } inline const CComDATE& CComDATE::operator=(DATE dtSrc) { m_date = dtSrc; return *this; } inline const CComDATE& CComDATE::operator=(const time_t& tmSrc) { // Convert time_t to struct tm tm *ptm = localtime(&tmSrc); if( !ptm || !MakeDATE(&m_date, (WORD)(ptm->tm_year + 1900), (WORD)(ptm->tm_mon + 1), (WORD)ptm->tm_mday, (WORD)ptm->tm_hour, (WORD)ptm->tm_min, (WORD)ptm->tm_sec) ) { // Local time must have failed (tmSrc before 1/1/70 12am) Invalidate(); } return *this; } inline const CComDATE& CComDATE::operator=(const struct tm& tmSrc) { SetDateTime(tmSrc.tm_year + 1900, tmSrc.tm_mon + 1, tmSrc.tm_mday, tmSrc.tm_hour, tmSrc.tm_min, tmSrc.tm_sec); return *this; } inline const CComDATE& CComDATE::operator=(const SYSTEMTIME& systmSrc) { if( !MakeDATE(&m_date, systmSrc.wYear, systmSrc.wMonth, systmSrc.wDay, systmSrc.wHour, systmSrc.wMinute, systmSrc.wSecond) ) { Invalidate(); } return *this; } inline const CComDATE& CComDATE::operator=(const FILETIME& ftSrc) { // Assume UTC FILETIME, so convert to LOCALTIME FILETIME ftLocal; if( !FileTimeToLocalFileTime( &ftSrc, &ftLocal) ) { #ifdef ATLTRACE ATLTRACE("\nFileTimeToLocalFileTime failed. Error = %lu.\n\t", GetLastError()); #endif Invalidate(); } else { // Take advantage of SYSTEMTIME -> FILETIME conversion SYSTEMTIME systime; // At this polong systime should always be valid, but... if( !FileTimeToSystemTime(&ftLocal, &systime) || !MakeDATE(&m_date, systime.wYear, systime.wMonth, systime.wDay, systime.wHour, systime.wMinute, systime.wSecond) ) { Invalidate(); } } return *this; } inline CComDATE::operator VARIANT() const { VARIANT var = { 0 }; var.vt = VT_DATE; var.date = m_date; return var; } inline CComDATE::operator time_t() const { struct tm tmDest; if( Maketm(&tmDest, m_date) ) { return mktime(&tmDest); } return -1; } inline CComDATE::operator struct tm() const { struct tm tmDest = { 0 }; Maketm(&tmDest, m_date); return tmDest; } inline CComDATE::operator SYSTEMTIME() const { SYSTEMTIME st = { 0 }; VariantTimeToSystemTime(m_date, &st); return st; } inline CComDATE::operator FILETIME() const { FILETIME ft = { 0 }; SYSTEMTIME st; VariantTimeToSystemTime(m_date, &st); SystemTimeToFileTime(&st, &ft); return ft; } #ifdef __oledb_h__ inline CComDATE::operator DBTIMESTAMP() const { DBTIMESTAMP dbts = { 0 }; struct tm tmDest; if( IsValid() && Maketm(&tmDest, m_date) ) { dbts.day = tmDest.tm_mday; dbts.month = tmDest.tm_mon + 1; dbts.year = tmDest.tm_year + 1900; dbts.hour = tmDest.tm_hour; dbts.minute = tmDest.tm_min; dbts.second = tmDest.tm_sec; } return dbts; } #endif inline bool CComDATE::operator<(const CComDATE& date) const { _ASSERTE(IsValid()); _ASSERTE(date.IsValid()); // Handle negative dates return DATEAsDouble(m_date) < DATEAsDouble(date.m_date); } inline bool CComDATE::operator>(const CComDATE& date) const { _ASSERTE(IsValid()); _ASSERTE(date.IsValid()); // Handle negative dates return DATEAsDouble(m_date) > DATEAsDouble(date.m_date); } inline bool CComDATE::operator<=(const CComDATE& date) const { _ASSERTE(IsValid()); _ASSERTE(date.IsValid()); // Handle negative dates return DATEAsDouble(m_date) <= DATEAsDouble(date.m_date); } inline bool CComDATE::operator>=(const CComDATE& date) const { _ASSERTE(IsValid()); _ASSERTE(date.IsValid()); // Handle negative dates return DATEAsDouble(m_date) >= DATEAsDouble(date.m_date); } inline bool CComDATE::SetDateTime( long nYear, long nMonth, long nDay, long nHour, long nMin, long nSec) { if( !MakeDATE(&m_date, (WORD)nYear, (WORD)nMonth, (WORD)nDay, (WORD)nHour, (WORD)nMin, (WORD)nSec) ) { Invalidate(); } return IsValid(); } inline bool CComDATE::ParseDateTime(const char* lpszDate, DWORD dwFlags, LCID lcid) { USES_CONVERSION; return ParseDateTime(A2OLE(lpszDate), dwFlags, lcid); } inline bool CComDATE::ParseDateTime(const wchar_t* lpszDate, DWORD dwFlags, LCID lcid) { if( FAILED(VarDateFromStr(const_cast<wchar_t*>(lpszDate), lcid, dwFlags, &m_date)) ) { Invalidate(); } return IsValid(); } inline LPTSTR CComDATE::Format(LPTSTR pszOut, DWORD dwFlags, LCID lcid) const { *pszOut = 0; // If invalild, return empty string if (!IsValid()) return pszOut; BSTR bstr = 0; if( SUCCEEDED(VarBstrFromDate(m_date, lcid, dwFlags, &bstr)) ) { #ifdef _UNICODE wcscpy(pszOut, bstr); #else wcstombs(pszOut, bstr, wcslen(bstr) + 1); #endif SysFreeString(bstr); } return pszOut; } inline LPTSTR CComDATE::Format(LPTSTR pszOut, LPCTSTR pFormat) const { *pszOut = 0; // If invalild, return empty string struct tm tmDest; if (!IsValid() || !Maketm(&tmDest, m_date) ) return pszOut; // Fill in the buffer, disregard return value as it's not necessary // NOTE: 4096 is an arbitrary value picked lower than INT_MAX // as the VC6 implementation of wcsftime allocates memory based // on the 2nd parameter for some reason. _tcsftime(pszOut, 4096, pFormat, &tmDest); return pszOut; } inline LPTSTR CComDATE::Format(LPTSTR pszOut, UINT nFormatID, HINSTANCE hinst) const { *pszOut = 0; TCHAR sz[256]; if( LoadString(hinst, nFormatID, sz, sizeof(sz)/sizeof(*sz)) ) { return Format(pszOut, sz); } return pszOut; } // The FormatDate and FormatTime functions were provided by Joe O'Leary ([email protected]) to // wrap he Win32 National Language Support functions ::GetDateFormat() and ::GetTimeFormat(). // The format strings used here are specified in the on-line help for those functions. // The default format is the current user locale. inline LPTSTR CComDATE::FormatDate(LPTSTR pszOut, LPCTSTR szFmt, DWORD dwFlags, LCID lcid) const { _ASSERTE((szFmt==NULL) || (dwFlags==0));// if format is non-NULL, 'dwFlags' MUST be zero SYSTEMTIME st; memset(&st, 0, sizeof(SYSTEMTIME)); *pszOut = NULL; if ( !VariantTimeToSystemTime(m_date, &st) ) { #ifdef ATLTRACE ATLTRACE("\nVariantTimeToSystemTime failed. Error = %lu.\n\t", GetLastError()); #endif } else if ( GetDateFormat(lcid, dwFlags, &st, szFmt, pszOut, 255) == 0 ) { #ifdef ATLTRACE ATLTRACE("\nGetDateFormat failed. Error = %lu.\n\t", GetLastError()); #endif } return pszOut; } inline LPTSTR CComDATE::FormatTime(LPTSTR pszOut, LPCTSTR szFmt, DWORD dwFlags, LCID lcid) const { _ASSERTE((szFmt==NULL) || (dwFlags==0));// if format is non-NULL, 'dwFlags' MUST be zero SYSTEMTIME st; memset(&st, 0, sizeof(SYSTEMTIME)); *pszOut = NULL; if ( !VariantTimeToSystemTime(m_date, &st) ) { #ifdef ATLTRACE ATLTRACE("\nVariantTimeToSystemTime failed. Error = %lu.\n\t", GetLastError()); #endif } else if ( GetTimeFormat(lcid, dwFlags, &st, szFmt, pszOut, 255) == 0 ) { #ifdef ATLTRACE ATLTRACE("\nGetTimeFormat failed. Error = %lu.\n\t", GetLastError()); #endif } return pszOut; } inline bool Maketm(struct tm* ptmDest, DATE dtSrc) { SYSTEMTIME st; if( !VariantTimeToSystemTime(dtSrc, &st) ) return false; struct tm& tmDest = *ptmDest; // Convenience tmDest.tm_sec = st.wSecond; tmDest.tm_min = st.wMinute; tmDest.tm_hour = st.wHour; tmDest.tm_mday = st.wDay; tmDest.tm_mon = st.wMonth - 1; tmDest.tm_year = st.wYear - 1900; tmDest.tm_wday = st.wDayOfWeek; tmDest.tm_isdst = -1; // Force DST checking mktime(&tmDest); // Normalize return true; } inline double DATEAsDouble(DATE dt) { // No problem if positive if (dt >= 0) return dt; // If negative, must convert since negative dates not continuous // (examples: -1.25 to -.75, -1.50 to -.50, -1.75 to -.25) double temp = ceil(dt); return temp - (dt - temp); } inline DATE MakeDATE(double dbl) { // No problem if positive if (dbl >= 0) return dbl; // If negative, must convert since negative dates not continuous // (examples: -.75 to -1.25, -.50 to -1.50, -.25 to -1.75) double temp = floor(dbl); // dbl is now whole part return temp + (temp - dbl); } inline bool MakeDATE( DATE* pdtDest, WORD wYear, WORD wMonth, WORD wDay, WORD wHour, WORD wMinute, WORD wSecond) { SYSTEMTIME st = { 0 }; st.wYear = wYear; st.wMonth = wMonth; st.wDay = wDay; st.wHour = wHour; st.wMinute = wMinute; st.wSecond = wSecond; return SystemTimeToVariantTime(&st, pdtDest) ? true : false; } ///////////////////////////////////////////////////////////////////////////// // CComSpan class inline long CComSpan::Hours() const { _ASSERTE(IsValid()); // Truncate days and scale up double dbTemp = modf(m_span, &dbTemp); return (long)(dbTemp * 24); } inline long CComSpan::Minutes() const { _ASSERTE(IsValid()); // Truncate hours and scale up double dbTemp = modf(m_span * 24, &dbTemp); return (long)((dbTemp + HALF_SECOND) * 60); } inline long CComSpan::Seconds() const { _ASSERTE(IsValid()); // Truncate minutes and scale up double dbTemp = modf(m_span * 24 * 60, &dbTemp); return (long)(dbTemp * 60); } inline void CComSpan::SetSpan( long nDays, long nHours, long nMins, long nSecs) { // Set date span by breaking longo fractional days (all input ranges valid) m_span = nDays + ((double)nHours)/24 + ((double)nMins)/(24*60) + ((double)nSecs)/(24*60*60); } ///////////////////////////////////////////////////////////////////////////// // CComDATE/CComSpan math friend functions // date2 = date1 + span; inline CComDATE operator+(const CComDATE& date1, const CComSpan& span) { CComDATE date2; if( date1.IsValid() && span.IsValid() ) { // Compute the actual date difference by adding underlying data date2 = MakeDATE(DATEAsDouble(static_cast<DATE>(date1)) + static_cast<double>(span)); } return date2; } // date2 = span + date1; inline CComDATE operator+(const CComSpan& span, const CComDATE& date1) { CComDATE date2; if( date1.IsValid() && span.IsValid() ) { // Compute the actual date difference by adding underlying data date2 = MakeDATE(DATEAsDouble(static_cast<DATE>(date1)) + static_cast<double>(span)); } return date2; } // date2 = date1 - span; inline CComDATE operator-(const CComDATE& date1, const CComSpan& span) { CComDATE date2; if( date1.IsValid() && span.IsValid() ) { // Compute the actual date difference by adding underlying data date2 = MakeDATE(DATEAsDouble(static_cast<DATE>(date1)) - static_cast<double>(span)); } return date2; } // span = date1 - date2; inline CComSpan operator-(const CComDATE& date1, const CComDATE& date2) { CComSpan span; if( date1.IsValid() && date2.IsValid() ) { span = DATEAsDouble(static_cast<DATE>(date1)) - DATEAsDouble(static_cast<DATE>(date2)); } return span; } // span3 = span1 + span2; inline CComSpan operator+(const CComSpan& span1, const CComSpan& span2) { CComSpan span3; if( span1.IsValid() && span2.IsValid() ) span3 = span1.m_span + span2.m_span; return span3; } // span3 = span1 - span2; inline CComSpan operator-(const CComSpan& span1, const CComSpan& span2) { return span1 + (-span2); } class DateAdd { public: enum time_unit { TU_Days = 0, TU_Weeks = 1, TU_Months = 2, TU_Years = 3 }; public: DateAdd( const DATE & dateStart,const time_unit& timeUnit): m_dateStart(dateStart),m_timeUnit(timeUnit),m_lngInterval(1) { } DateAdd(const DATE& dateStart,const long& lngInterval,const time_unit& timeUnit): m_dateStart(dateStart),m_timeUnit(timeUnit),m_lngInterval(lngInterval) { } DateAdd(const DATE & dateStart,const long& payFreqID): m_dateStart(dateStart) { switch(payFreqID) { case 2: m_timeUnit=TU_Years; m_lngInterval=1; break; case 3: m_timeUnit=TU_Months; m_lngInterval=6; break; case 4: m_timeUnit=TU_Months; m_lngInterval=4; break; case 5: m_timeUnit=TU_Months; m_lngInterval=3; break; case 6: m_timeUnit=TU_Months; m_lngInterval=2; break; case 7: m_timeUnit=TU_Months; m_lngInterval=1; break; case 8: m_timeUnit=TU_Days; m_lngInterval=7; break; case 9: m_timeUnit=TU_Days; m_lngInterval=1; break; default: m_timeUnit=TU_Days; m_lngInterval=0; } } DATE operator()(const time_unit& timeUnit,const long& length)const; DATE operator()(const long& length) const; static DATE calculate(const time_unit& timeUnit,const long& length,const DATE& dateStart); DATE dateStart() const {return m_dateStart;} time_unit timeUnit() const {return m_timeUnit;} long timeInterval() const {return m_lngInterval;} private: DATE m_dateStart; time_unit m_timeUnit; long m_lngInterval; }; inline DATE DateAdd::operator()(const time_unit& timeUnit,const long& length) const { return calculate(timeUnit,length,m_dateStart); } inline DATE DateAdd::operator()(const long& length)const { return calculate(m_timeUnit,length*m_lngInterval,m_dateStart); } inline DATE DateAdd::calculate(const time_unit& timeUnit,const long& length,const DATE& dateStart) { DATE ret; switch(timeUnit) { case TU_Days: ret=CComDATE::DateAdd(_T("D"),length,dateStart); break; case TU_Weeks: ret=CComDATE::DateAdd(_T("D"),length*7,dateStart); break; case TU_Months: ret=CComDATE::DateAdd(_T("M"),length,dateStart); break; case TU_Years: ret=CComDATE::DateAdd(_T("Y"),length,dateStart); } return ret; } #undef HALF_SECOND #endif // __COMDATE_H__
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 1288 ] ] ]
2b79da873e91709e3f83da9d83a6027ccc5654e9
bd89d3607e32d7ebb8898f5e2d3445d524010850
/connectivitylayer/usbphonetlink/usbpnclient_dll/src/rusbpnclient.cpp
03757a867c323c0de8b0a4d5ffa893bb074e9424
[]
no_license
wannaphong/symbian-incubation-projects.fcl-modemadaptation
9b9c61ba714ca8a786db01afda8f5a066420c0db
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
refs/heads/master
2021-05-30T05:09:10.980036
2010-10-19T10:16:20
2010-10-19T10:16:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,811
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // INCLUDE FILES #include "rusbpnclient.h" #include "cusbpnserver.h" #include "usbpndefinitions.h" #include "usbpntrace.h" #include "OstTraceDefinitions.h" #ifdef OST_TRACE_COMPILER_IN_USE #include "rusbpnclientTraces.h" #endif // EXTERNAL DATA STRUCTURES // EXTERNAL FUNCTION PROTOTYPES // CONSTANTS // MACROS // LOCAL CONSTANTS AND MACROS // MODULE DATA STRUCTURES // LOCAL FUNCTION PROTOTYPES // FORWARD DECLARATIONS // ============================= LOCAL FUNCTIONS =============================== // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // RUsbPnClient::RUsbPnClient // C++ default constructor can NOT contain any code, that // might leave. // ----------------------------------------------------------------------------- // EXPORT_C RUsbPnClient::RUsbPnClient() :RSessionBase() { } // ----------------------------------------------------------------------------- // RUsbPnClient::ConnectL // (other items were commented in a header). // ----------------------------------------------------------------------------- // EXPORT_C void RUsbPnClient::ConnectL() { OstTrace0( TRACE_BORDER, RUSBPNCLIENT_CONNECTL_ENTRY, "RUsbPnClient::ConnectL" ); A_TRACE( ( _T( "RUsbPnClient::ConnectL()" ) ) ); TInt err( KErrNone ); // Create USB Phonet Link Server session err = CreateSession( KUsbPnServerName, TVersion(1,0,0)); if ( err == KErrNotFound ) { // Session not created // Find lock semaphore for server process creation TFindSemaphore lock( KUsbPnServerName ); TFullName semaphoreName; err = lock.Next( semaphoreName ); if ( err == KErrNotFound ) { // Lock is not enabled OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL, "RUsbPnClient::ConnectL() - semaphore not found, start server" ); E_TRACE( ( _L( "RUsbPnClient::ConnectL() - semaphore not found, start server" ) ) ); RSemaphore startLock; // Create lock User::LeaveIfError( startLock.CreateGlobal( KUsbPnServerName, 0, EOwnerProcess ) ); /********************************************/ /* Start the USB Phonet Link process process */ TRequestStatus status; RProcess server; User::LeaveIfError( server.Create( KUsbPnServerName, TPtrC( NULL, 0), EOwnerThread ) ); server.Rendezvous( status ); if( status != KRequestPending ) { server.Kill(0); // Abort startup } else { server.Resume(); // Logon OK -> start the server } OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP1, "RUsbPnClient::ConnectL() - waiting server response" ); E_TRACE( ( _T( "RUsbPnClient::ConnectL() - waiting server response" ) ) ); User::WaitForRequest( status ); // Wait for start or death // we can't use the 'exit reason' if the server panicked as this // is the panic 'reason' and may be '0' which cannot be distinguished // from KErrNone TInt err = status.Int(); if (err == KErrNone && (server.ExitType() == EExitPanic || server.ExitType() == EExitKill)) { err = KErrServerTerminated; } server.Close(); if( err ) { OstTrace1( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP2, "RUsbPnClient::ConnectL() - waiting server response status; err=%d", err ); E_TRACE( ( _T( "RUsbPnClient::ConnectL() - waiting server response status: %d" ), err ) ); TRACE_ASSERT_ALWAYS; User::LeaveIfError( err ); } /* End of starting process */ /********************************************/ OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP3, "RUsbPnClient::ConnectL() - server is started, signal other clients" ); E_TRACE( ( _L( "RUsbPnClient::ConnectL() - server is started, signal other clients" ) ) ); // Signal other clients startLock.Signal( KMaxTInt ); // Close semaphore startLock.Close(); } else { // Lock is enabled RSemaphore startLock; // Open lock semaphore User::LeaveIfError( startLock.Open( lock ) ); OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP4, "RUsbPnClient::ConnectL() - server is starting, wait for signal" ); E_TRACE( ( _L( "RUsbPnClient::ConnectL() - server is starting, wait for signal" ) ) ); // Wait for signal startLock.Wait(); OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP5, "RUsbPnClient::ConnectL() - signal received" ); E_TRACE( ( _L( "RUsbPnClient::ConnectL() - signal received" ) ) ); // Close semaphore startLock.Close(); } // Create USB Phonet Link server session OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP6, "RUsbPnClient::ConnectL() - Create session" ); E_TRACE( ( _L( "RUsbPnClient::ConnectL() - Create session" ) ) ); User::LeaveIfError( CreateSession( KUsbPnServerName, TVersion(1,0,0) ) ); OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP7, "RUsbPnClient::ConnectL() - session created1" ); E_TRACE( ( _L( "RUsbPnClient::ConnectL() - session created1" ) ) ); } else if ( err ) { OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP8, "RUsbPnClient::ConnectL() - session not created, reason uknown" ); E_TRACE( ( _L( "RUsbPnClient::ConnectL() - session not created, reason uknown" ) ) ); TRACE_ASSERT_ALWAYS; User::Leave( err ); } else { OstTrace0( TRACE_INTERNALS, RUSBPNCLIENT_CONNECTL_DUP9, "RUsbPnClient::ConnectL() - session created2" ); E_TRACE( ( _T( "RUsbPnClient::ConnectL() - session created2" ) ) ); } OstTrace0( TRACE_BORDER, RUSBPNCLIENT_CONNECTL_EXIT, "RUsbPnClient::ConnectL() - return void" ); A_TRACE( ( _T( "RUsbPnClient::ConnectL() - return void" ) ) ); } //----------------------------------------------------------------------------- // RPtp::DestroyPtpStatck() // Destroy PTP stack //----------------------------------------------------------------------------- // EXPORT_C void RUsbPnClient::Detach() { OstTrace0( TRACE_BORDER, RUSBPNCLIENT_DETACH_ENTRY, "RUsbPnClient::Detach" ); A_TRACE( ( _T( "RUsbPnClient::Disconnect()" ) ) ); SendReceive( EPnDetach ); // close the session RSessionBase::Close(); OstTrace0( TRACE_BORDER, RUSBPNCLIENT_DETACH_EXIT, "RUsbPnClient::Detach - return void" ); A_TRACE( ( _T( "RUsbPnClient::Disconnect() - return void" ) ) ); } // ========================== OTHER EXPORTED FUNCTIONS ========================= // End of File
[ "dalarub@localhost", "[email protected]", "mikaruus@localhost" ]
[ [ [ 1, 23 ], [ 25, 59 ], [ 61, 79 ], [ 81, 107 ], [ 109, 124 ], [ 126, 132 ], [ 134, 149 ], [ 151, 153 ], [ 155, 162 ], [ 164, 167 ], [ 170, 172 ], [ 175, 179 ], [ 182, 182 ], [ 184, 193 ], [ 195, 198 ], [ 200, 206 ] ], [ [ 24, 24 ], [ 169, 169 ], [ 174, 174 ], [ 181, 181 ] ], [ [ 60, 60 ], [ 80, 80 ], [ 108, 108 ], [ 125, 125 ], [ 133, 133 ], [ 150, 150 ], [ 154, 154 ], [ 163, 163 ], [ 168, 168 ], [ 173, 173 ], [ 180, 180 ], [ 183, 183 ], [ 194, 194 ], [ 199, 199 ] ] ]
a3b3f48673507e5c7da19415aab2e03fcb8c561b
41efaed82e413e06f31b65633ed12adce4b7abc2
/projects/lab6/src/MyCamera.cpp
66943c1f2a9fe6b7ffe194bff55f9a14ec4b381c
[]
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
2,551
cpp
// This file is an example for CGLib. // // CGLib 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. // // CGLib 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 CGLib; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // Copyright 2007 Carlos Martinho #include "MyCamera.h" namespace lab6 { MyCamera::MyCamera() : Entity("Camera") { } MyCamera::~MyCamera() { } void MyCamera::init() { cg::tWindowInfo win = cg::Manager::instance()->getApp()->getWindowInfo(); _winSize.set(win.width,win.height); _orientation.setRotationDeg(0,cg::Vector3d::ny); _up.set(0,1,0); _front.set(1,0,0); _right.set(0,0,1); _isRoll = false; } void MyCamera::draw() { _position = _front * 15.0; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60,_winSize[0]/(double)_winSize[1],1.0,100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(_position[0],_position[1],_position[2],0,0,0,_up[0],_up[1],_up[2]); } void MyCamera::onReshape(int width, int height) { _winSize.set(width,height); } void MyCamera::onMouse(int button, int state, int x, int y) { _isRoll = (button == GLUT_RIGHT_BUTTON); _lastMousePosition.set(x,y); } void MyCamera::onMouseMotion(int x, int y) { if(_isRoll) { double anglez = (_lastMousePosition[0] - x) / (double)5; _q.setRotationDeg(anglez,_front); _up = apply(_q,_up); _right = apply(_q,_right); _orientation = _q * _orientation; } else { double anglex = (_lastMousePosition[0] - x) / (double)5; _q.setRotationDeg(anglex,_up); _front = apply(_q,_front); _right = apply(_q,_right); _orientation = _q * _orientation; double angley = (y - _lastMousePosition[1]) / (double)5; _q.setRotationDeg(angley, _right); _up = apply(_q,_up); _front = apply(_q,_front); _orientation = _q * _orientation; } _lastMousePosition.set(x,y); } void MyCamera::onMousePassiveMotion(int x, int y) { } }
[ "Moreira@Moreira-PC.(none)" ]
[ [ [ 1, 75 ] ] ]
7697e816f161e04e6e32a8eec7b9a3d0dec4f8c8
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Dynamics/Constraint/ConstraintKit/hkpGenericConstraintData.h
eed9c84bfdf91c75b1b77bcb26663853fb88df7d
[]
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
6,732
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_DYNAMICS2_GENERIC_CONSTRAINT_H #define HK_DYNAMICS2_GENERIC_CONSTRAINT_H #include <Physics/Dynamics/Constraint/hkpConstraintData.h> #include <Physics/ConstraintSolver/Constraint/Atom/hkpConstraintAtom.h> #include <Physics/Dynamics/Constraint/ConstraintKit/hkpGenericConstraintScheme.h> class hkpGenericConstraintDataParameters; extern const hkClass hkpGenericConstraintDataClass; /// A generic constraint for use with the hkpConstraintConstructionKit. A generic constraint /// initially doesn't restrict any movement for its bodies - it must be configured using the kit. class hkpGenericConstraintData : public hkpConstraintData { public: HK_DECLARE_REFLECTION(); /// A parameter index. The constraint construction kit returns an index each time you specify a pivot /// point, basis, or axis for the constraint, allowing you to access these later. typedef int hkpParameterIndex; /// Creates a new generic constraint. hkpGenericConstraintData(); virtual ~hkpGenericConstraintData(); /// Gets the parameter at the index returned during kit construction hkVector4* getParameters( hkpParameterIndex parameterIndex ); /// Sets the parameters starting at the index returned during kit construction void setParameters( hkpParameterIndex parameterIndex, int numParameters, const hkVector4* newValues ); /// Checks consistency of constraint members. virtual hkBool isValid() const; hkpGenericConstraintDataScheme* getScheme(); public: struct hkpBridgeAtoms m_atoms; protected: // commands // linear constraints void constrainAllLinearW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; inline void constrainLinearW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; inline void constrainToAngularW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; inline void constrainAllAngularW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; // limits, friction, motors inline void setLinearLimitW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; inline void setAngularLimitW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; inline void setConeLimitW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; inline void setTwistLimitW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, const hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; inline void setAngularMotorW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; inline void setLinearMotorW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; inline void setAngularFrictionW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; void setLinearFrictionW( hkArray<int>::iterator& currentCommand, hkArray<hkVector4>::iterator& currentData, hkpGenericConstraintDataScheme& scheme, hkpGenericConstraintDataParameters& vars, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ) const; /// end commands void hatchScheme( hkpGenericConstraintDataScheme* scheme, const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ); class hkpGenericConstraintDataScheme m_scheme; public: // Internal functions virtual void buildJacobian( const hkpConstraintQueryIn &in, hkpConstraintQueryOut &out ); virtual void getConstraintInfo( hkpConstraintData::ConstraintInfo& info ) const; virtual int getType() const; virtual void getRuntimeInfo( hkBool wantRuntime, hkpConstraintData::RuntimeInfo& infoOut ) const; public: hkpGenericConstraintData(hkFinishLoadedObjectFlag f); }; #endif /* * 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, 123 ] ] ]
98e8e980da198dbd45d1365f2e6d3724632113a8
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/qrteereg.hpp
2ebef171642fa948d21077466bf15c7fe50b90ea
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
936
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'QRTEEReg.pas' rev: 6.00 #ifndef QRTEERegHPP #define QRTEERegHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Qrteereg { //-- type declarations ------------------------------------------------------- //-- var, const, procedure --------------------------------------------------- extern PACKAGE void __fastcall Register(void); } /* namespace Qrteereg */ using namespace Qrteereg; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // QRTEEReg
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 31 ] ] ]
c11e7b11a754aacb800811d0f56f0ba7e1c46e4c
55196303f36aa20da255031a8f115b6af83e7d11
/private/external/gameswf/gameswf/gameswf_as_sprite.h
db3a20c36f225ca80e1d938ce7ff7b8f1a038fe5
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
1,948
h
// gameswf_as_sprite.h -- Thatcher Ulrich <[email protected]> 2003 // This source code has been donated to the Public Domain. Do // whatever you want with it. // Some implementation for SWF player. // Useful links: // // http://sswf.sourceforge.net/SWFalexref.html // http://www.openswf.org #ifndef GAMESWF_AS_SPRITE_H #define GAMESWF_AS_SPRITE_H namespace gameswf { // // sprite built-in ActionScript methods // void as_global_movieclip_ctor(const fn_call& fn); void sprite_hit_test(const fn_call& fn); void sprite_start_drag(const fn_call& fn); void sprite_stop_drag(const fn_call& fn); void sprite_play(const fn_call& fn); void sprite_stop(const fn_call& fn); void sprite_goto_and_play(const fn_call& fn); void sprite_goto_and_stop(const fn_call& fn); void sprite_next_frame(const fn_call& fn); void sprite_prev_frame(const fn_call& fn); void sprite_get_bytes_loaded(const fn_call& fn); void sprite_get_bytes_total(const fn_call& fn); void sprite_swap_depths(const fn_call& fn) ; void sprite_duplicate_movieclip(const fn_call& fn); void sprite_get_depth(const fn_call& fn); void sprite_create_empty_movieclip(const fn_call& fn); void sprite_remove_movieclip(const fn_call& fn); void sprite_loadmovie(const fn_call& fn); void sprite_unloadmovie(const fn_call& fn); void sprite_getnexthighestdepth(const fn_call& fn); void sprite_create_text_field(const fn_call& fn); void sprite_attach_movie(const fn_call& fn); // drawing API void sprite_begin_fill(const fn_call& fn); void sprite_end_fill(const fn_call& fn); void sprite_clear(const fn_call& fn); void sprite_move_to(const fn_call& fn); void sprite_line_to(const fn_call& fn); void sprite_curve_to(const fn_call& fn); void sprite_line_style(const fn_call& fn); // gameSWF extension void sprite_set_fps(const fn_call& fn); // flash9 void sprite_add_script(const fn_call& fn); } #endif
[ "viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587" ]
[ [ [ 1, 63 ] ] ]
9b0b574ae93864e30e48e7ee819b01387ae09ae9
9324000ac1cb567bd4862547cbdccf0923446095
/game/bullet.cpp
d7b89ffa18f5f65549bc021b95c30f42b2f42dc1
[]
no_license
mguillemot/kamaku.foliage
cf63d49e1e5ddd7c30b75acfc1841028d109cba4
18c225346916e240bc19bf5570a8c414bbb4153b
refs/heads/master
2016-08-03T20:09:17.929309
2007-09-04T18:15:17
2007-09-04T18:15:17
2,226,835
0
0
null
null
null
null
UTF-8
C++
false
false
2,893
cpp
#include <iostream> #include "bullet.hpp" #include "fastmath.hpp" #include "game_globals.hpp" #include "rythm_display.hpp" #define NB_BULLET_TYPES 6 std::vector<Foliage::Surface *> Bullet::_bulletSurfaces(NB_BULLET_TYPES); void Bullet::loadBulletSurfaces() { _bulletSurfaces[0] = Foliage::BmpLoader::loadBmp("bul.bmp"); Foliage::Instancizator::instancize(_bulletSurfaces[0]); _bulletSurfaces[1] = Foliage::BmpLoader::loadBmp("bul_red.bmp"); Foliage::Instancizator::instancize(_bulletSurfaces[1]); _bulletSurfaces[2] = Foliage::BmpLoader::loadBmp("bul_blue.bmp"); Foliage::Instancizator::instancize(_bulletSurfaces[2]); _bulletSurfaces[3] = Foliage::BmpLoader::loadBmp("bul_gree.bmp"); Foliage::Instancizator::instancize(_bulletSurfaces[3]); _bulletSurfaces[4] = Foliage::BmpLoader::loadBmp("bullet0.bmp"); Foliage::Instancizator::instancize(_bulletSurfaces[4]); _bulletSurfaces[5] = Foliage::BmpLoader::loadBmp("bullet1.bmp"); Foliage::Instancizator::instancize(_bulletSurfaces[5]); } Bullet::Bullet(const Foliage::Point position, const Foliage::Fixed direction, const Foliage::Fixed speed, const BulletType type) : _direction(direction) { _dead = false; _entity = new SimpleEntity(_bulletSurfaces[type]); const Foliage::Size size = _entity->getSize(); if (type >= 0 && type <= 3) { // enemy round bullet (8x8) const Foliage::Rect bulletHitbox = Foliage::Rect(2, 2, 4, 4); _entity->getHitbox()->addRect(bulletHitbox); } else { // my digital bullets (6x9) const Foliage::Rect bulletHitbox = Foliage::Rect(0, 0, 6, 9); _entity->getHitbox()->addRect(bulletHitbox); } _entity->setPosition(Foliage::Point(position.x - (size.w >> 1), position.y - (size.h >> 1))); setSpeed(speed); } Bullet::~Bullet() { delete _entity; } void Bullet::updateEntitySpeed() { const Foliage::Fixed sx = _speed * Foliage::FastMath::cos(_direction); const Foliage::Fixed sy = _speed * Foliage::FastMath::sin(_direction); _entity->setSpeed(Foliage::Speed(sx, sy)); } void Bullet::update() { _entity->update(); } void Bullet::setSpeed(const Foliage::Fixed speed) { _speed = speed; updateEntitySpeed(); } void Bullet::setDirection(const Foliage::Fixed direction) { _direction = direction; updateEntitySpeed(); } void BulletGenerator::update() { Bullet::update(); _generateTimer--; //if (_generateTimer == 0) if (currentLevel->rythm->tap(3)) { _dead = true; const Foliage::Point from = _entity->getCenter(); const int N = 20; Foliage::Fixed space = F_TWOPI; space /= Sint16(N); Foliage::Fixed angle; const Foliage::Fixed speed(2.5f); for (int i = 0; i < N; i++) { Bullet *shot = new Bullet(from, angle, speed, Bullet_Standard); currentLevel->enemyBullets.push_back(shot); angle += space; } } }
[ "erhune@1bdb3d1c-df69-384c-996e-f7b9c3edbfcf", "Erhune@1bdb3d1c-df69-384c-996e-f7b9c3edbfcf" ]
[ [ [ 1, 3 ], [ 5, 6 ], [ 8, 8 ], [ 28, 29 ], [ 46, 50 ], [ 52, 53 ], [ 55, 55 ], [ 59, 62 ], [ 64, 65 ], [ 67, 68 ], [ 70, 71 ], [ 73, 74 ], [ 76, 76 ] ], [ [ 4, 4 ], [ 7, 7 ], [ 9, 27 ], [ 30, 45 ], [ 51, 51 ], [ 54, 54 ], [ 56, 58 ], [ 63, 63 ], [ 66, 66 ], [ 69, 69 ], [ 72, 72 ], [ 75, 75 ], [ 77, 99 ] ] ]
115cde751a56bd843e0b92d61b02c2334d9ff2ca
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/Body.h
0d9dac0f9d1a0845667681adf72a264d2fdc48e1
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
7,637
h
// ----------------------------------------------------------------------- // // // MODULE : Body.h // // PURPOSE : Body Prop - Definition // // CREATED : 1997 (was BodyProp) // // (c) 1997-2002 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __BODY_PROP_H__ #define __BODY_PROP_H__ enum EnumAIStateType; class CAttachments; class CBodyState; class CSearchable; #include "Character.h" #include "Prop.h" #include "ModelButeMgr.h" #include "SFXMsgIDs.h" #include "Animator.h" #include "DeathScene.h" #include "GeneralInventory.h" #include "IHitBoxUser.h" #include "SharedFXStructs.h" LINKTO_MODULE( Body ); struct BODYINITSTRUCT { CCharacter* pCharacter; EnumAIStateType eBodyState; bool bPermanentBody; float fBodyLifetime; bool bCanRevive; }; class CAnimatorBody : public CAnimator { public : // Ctors/Dtors/etc void Init(HOBJECT hObject); // Updates void Update(); // Methods void Twitch(); protected : AniTracker m_eAniTrackerTwitch; // Our twitch ani tracker Ani m_eAniTwitch; // Our twitch ani }; class Body : public Prop, public IHitBoxUser { typedef Prop super; public : // Public methods // Ctors/Dtors/etc Body(); ~Body(); void Init(const BODYINITSTRUCT& bi); CBodyState* AI_FACTORY_NEW_State(EnumAIStateType eStateType); void SetState(EnumAIStateType eBodyState, LTBOOL bLoad = LTFALSE); EnumAIStateType GetBodyState() {return m_eBodyState;} void FacePos(const LTVector& vTargetPos); void FaceDir(const LTVector& vTargetDir); ModelId GetModelId() const { return m_eModelId; } ModelSkeleton GetModelSkeleton() const { return m_eModelSkeleton; } void AddWeapon(HOBJECT hWeapon, char *pszPosition); bool AddPickupItem(HOBJECT hItem, bool bForcePickup = false); void AddSpear(HOBJECT hSpear, const LTRotation& rRot, ModelNode eModelNode=eModelNodeInvalid); void SetModelNodeLastHit(ModelNode eModelNodeLastHit) { m_eModelNodeLastHit = eModelNodeLastHit; } ModelNode GetModelNodeLastHit() const { return m_eModelNodeLastHit; } CAttachments* GetAttachments() { return m_pAttachments; } HOBJECT GetHitBox() const { return m_hHitBox; } LTFLOAT GetLifetime() { return m_fLifetime; } LTFLOAT GetStarttime() { return m_fStartTime; } bool GetFadeAfterLifetime() { return m_bFadeAfterLifetime; } HOBJECT GetLastDamager() const { return m_damage.GetLastDamager(); } const LTVector& GetDeathDir() const { return m_vDeathDir; } void ReleasePowerups(bool bWeaponsOnly = false); void RemovePowerupObjects(); bool IsPermanentBody() const { return m_bPermanentBody; } void SetPermanentBody( bool bPerm ); // for game types where a players body may sit aound indefinitely while waiting to respawn void ResetLifetime(float fLifetime); virtual LTBOOL UsingHitDetection() const { return LTTRUE; } virtual float GetNodeRadius( ModelSkeleton eModelSkeleton, ModelNode eModelNode ) { return ( g_pModelButeMgr->GetSkeletonNodeHitRadius(eModelSkeleton, eModelNode) ); } HOBJECT GetCharacter( ) const { return m_hCharacter; } // [kml] 3/19/02 // For general inventory stuff void DropInventoryObject(); LTBOOL CanCheckPulse(); bool CanBeSearched(); void AddToObjectList( ObjectList *pObjList, eObjListControl eControl ); virtual HATTACHMENT GetAttachment() const { return NULL; } virtual LTFLOAT ComputeDamageModifier(ModelNode eModelNode) { return 1.0f; } // Checker void SetChecker(HOBJECT hChecker); LTBOOL HasChecker() const { return !!m_hChecker; } HOBJECT GetChecker() const { return m_hChecker; } void SetBodyResetTime( LTFLOAT fResetTime ) { m_fBodyResetTime = fResetTime; } LTFLOAT GetBodyResetTime() { return m_fBodyResetTime; } // General inventory accessor GEN_INVENTORY_LIST& GetInventory() { return m_lstInventory; } float GetEnergy() { return m_fEnergy; } // Implementing classes will have this function called // when HOBJECT ref points to gets deleted. virtual void OnLinkBroken( LTObjRefNotifier *pRef, HOBJECT hObj ); // Carrying virtual void SetCanCarry( bool bCarry ); virtual void SetBeingCarried( bool bBeingCarried, HOBJECT hCarrier ); virtual bool BeingCarried() { return m_bBeingCarried; } void SetCanRevive( bool bCanRevive ); bool GetCanRevive( ) const { return m_bCanRevive; } // Hide the body and it's associated objects. void HideBody( bool bHide ); virtual CAnimator* GetAnimator() { return &m_Animator; } // Get the complete list of all bodies. typedef std::vector< Body* > BodyList; static BodyList const& GetBodyList( ) { return m_lstBodies; } protected : // Protected methods // Engine methods uint32 EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData); uint32 ObjectMessageFn(HOBJECT hSender, ILTMessage_Read *pMsg); virtual bool OnTrigger(HOBJECT hSender, const CParsedMsg &cMsg); virtual uint32 OnDeactivate(); // Hitbox message void CreateHitBox(const BODYINITSTRUCT& bi); void UpdateHitBox(); void UpdateClientHitBox(); // Handling methods void HandleDamage(const DamageStruct& damage); void HandleVectorImpact(IntersectInfo& iInfo, LTVector& vDir, LTVector& vFrom, ModelNode& eModelNode) {} virtual void HandleDestroy(HOBJECT hDamager); void ReadProp(ObjectCreateStruct *pData); void Update(); void Save(ILTMessage_Write *pMsg, uint32 dwSaveFlags); void Load(ILTMessage_Read *pMsg, uint32 dwLoadFlags); void CreateDeathScene(CCharacter *pChar); void ReleasePowerup(HOBJECT hPowerup); // Keeps body density down within a radius. void CapNumberOfBodies( ); void CreateSpecialFX(); protected : enum Constants { kMaxSpears = 32, kMaxWeapons = 2, }; private: // Returns true when it shouldn't be passed to parent. bool HandleModelString(ArgList* pArgList); protected : CAttachments* m_pAttachments; CharacterDeath m_eDeathType; ModelId m_eModelId; ModelSkeleton m_eModelSkeleton; ModelNode m_eModelNodeLastHit; LTBOOL m_bFirstUpdate; LTFLOAT m_fStartTime; LTFLOAT m_fLifetime; bool m_bFadeAfterLifetime; LTVector m_vColor; LTVector m_vDeathDir; DamageType m_eDamageType; LTObjRef m_hHitBox; uint32 m_cWeapons; LTObjRefNotifier m_ahWeapons[kMaxWeapons]; LTObjRef m_hChecker; LTFLOAT m_fBodyResetTime; EnumAIStateType m_eBodyState; EnumAIStateType m_eBodyStatePrevious; CBodyState* m_pState; CAnimatorBody m_Animator; uint32 m_cSpears; LTObjRefNotifier m_ahSpears[kMaxSpears]; CDeathScene m_DeathScene; CSearchable* m_pSearch; EnumAIStimulusID m_eDeathStimID; // Registration ID of dead body stimulus. bool m_bCanBeCarried; bool m_bUpdateHitBox; bool m_bDimsUpdated; GEN_INVENTORY_LIST m_lstInventory; // General inventory items (see GeneralInventory.h) float m_fEnergy; LTObjRef m_hCharacter; // The character our body spawned from // Never remove this body through body density capping. bool m_bPermanentBody; static BodyList m_lstBodies; bool m_bCanCarry; bool m_bBeingCarried; LTObjRef m_hCarrier; bool m_bCanRevive; BODYCREATESTRUCT m_BCS; }; #endif // __BODY_PROP_H__
[ [ [ 1, 284 ] ] ]
35e395e416593c15d8ca64b381f5a430c2e5e521
842997c28ef03f8deb3422d0bb123c707732a252
/src/moaicore/MOAISim.cpp
1e55d1d8d71d0a6d1b124e3ca0437a37b521c5a1
[]
no_license
bjorn/moai-beta
e31f600a3456c20fba683b8e39b11804ac88d202
2f06a454d4d94939dc3937367208222735dd164f
refs/heads/master
2021-01-17T11:46:46.018377
2011-06-10T07:33:55
2011-06-10T07:33:55
1,837,561
2
1
null
null
null
null
UTF-8
C++
false
false
18,393
cpp
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moaicore/MOAIDebugLines.h> #include <moaicore/MOAIInputMgr.h> #include <moaicore/MOAILogMessages.h> #include <moaicore/MOAINodeMgr.h> #include <moaicore/MOAIProp2D.h> #include <moaicore/MOAISim.h> #include <moaicore/MOAIFmod.h> #include <aku/AKU.h> #if USE_LUA_SOCKET //extern "C" { #include <luasocket.h> //} #endif //================================================================// // local //================================================================// //----------------------------------------------------------------// /** @name clearRenderStack @text Clears the render stack. @out nil */ int MOAISim::_clearRenderStack ( lua_State* L ) { USLuaState state ( L ); MOAISim& device = MOAISim::Get (); device.Clear (); return 0; } //----------------------------------------------------------------// /** @name enterFullscreenMode @text Enters fullscreen mode on the device if possible. @out nil */ int MOAISim::_enterFullscreenMode ( lua_State* L ) { USLuaState state ( L ); AKUEnterFullscreenModeFunc enterFullscreenMode = AKUGetFunc_EnterFullscreenMode (); if ( enterFullscreenMode ) { enterFullscreenMode (); } return 0; } //----------------------------------------------------------------// /** @name exitFullscreenMode @text Exits fullscreen mode on the device if possible. @out nil */ int MOAISim::_exitFullscreenMode ( lua_State* L ) { USLuaState state ( L ); AKUEnterFullscreenModeFunc exitFullscreenMode = AKUGetFunc_ExitFullscreenMode (); if ( exitFullscreenMode ) { exitFullscreenMode (); } return 0; } //----------------------------------------------------------------// /** @name framesToTime @text Converts the number of frames to time passed in seconds. @in number frames The number of frames. @out number time The equivilant number of seconds for the specified number of frames. */ int MOAISim::_framesToTime ( lua_State* L ) { USLuaState state ( L ); if ( !state.CheckParams ( 1, "N" )) return 0; float frames = state.GetValue < float >( 1, 0.0f ); MOAISim& device = MOAISim::Get (); lua_pushnumber ( state, frames * device.mStep ); return 1; } //----------------------------------------------------------------// /** @name getDeviceIDString @text Gets a unique string that identifies the device. @out string id The identifier string. */ int MOAISim::_getDeviceIDString ( lua_State* L ) { #ifdef _WIN32 USAdapterInfoList infoList; infoList.EnumerateAdapters(); STLString name = infoList[0].GetName(); if( name ){ lua_pushstring( L, name ); return 1; } #else MOAISim& device = MOAISim::Get (); if( device.mUniqueID ){ lua_pushstring( L, device.mUniqueID ); return 1; } #endif return 0; } //----------------------------------------------------------------// /** @name getDeviceSize @text Gets the dimensions of the device screen as two return values (width, height). @out number width The width of the device screen. @out number height The height of the device screen. */ int MOAISim::_getDeviceSize ( lua_State* L ) { USGfxDevice& gfxDevice = USGfxDevice::Get (); lua_pushnumber ( L, gfxDevice.GetWidth ()); lua_pushnumber ( L, gfxDevice.GetHeight ()); return 2; } //----------------------------------------------------------------// /** @name getElapsedFrames @text Gets the number of frames elapsed since the application was started. @out number frames The number of elapsed frames. */ int MOAISim::_getElapsedFrames ( lua_State* L ) { MOAISim& device = MOAISim::Get (); lua_pushnumber ( L, device.mTime / device.mStep ); return 1; } //----------------------------------------------------------------// /** @name getElapsedTime @text Gets the number of seconds elapsed since the application was started. @out number time The number of elapsed seconds. */ int MOAISim::_getElapsedTime ( lua_State* L ) { lua_pushnumber ( L, MOAISim::Get ().mTime ); return 1; } //----------------------------------------------------------------// /** @name getFrameSize @text Gets the amount of time (in seconds) that it takes for one frame to pass. This often will be a decimal number between 0 and 1. @out number size The size of the frame; the time it takes for one frame to pass. */ int MOAISim::_getFrameSize ( lua_State* L ) { MOAISim& device = MOAISim::Get (); lua_pushnumber ( L, device.mStep ); return 1; } //----------------------------------------------------------------// /** @name getNetworkStatus @text Returns whether this device is currently able to reach the internet. @out boolean status Whether the device can reach the internet. */ int MOAISim::_getNetworkStatus ( lua_State* L ) { MOAISim& device = MOAISim::Get (); lua_pushboolean ( L, device.mHasNetwork ); return 1; } //----------------------------------------------------------------// /** @name getPerformance @text Returns an estimated frames per second based on measurements taked at every render. @out number fps Estimated frames per second. */ int MOAISim::_getPerformance ( lua_State* L ) { MOAISim& device = MOAISim::Get (); lua_pushnumber ( L, device.mFrameRate ); return 1; } //----------------------------------------------------------------// /** @name openWindow @text Opens a new window for the application to render on. This must be called before any rendering can be done, and it must only be called once. @in string title The title of the window. @in number width The width of the window in pixels. @in number height The height of the window in pixels. @out nil */ int MOAISim::_openWindow ( lua_State* L ) { USLuaState state ( L ); if ( !state.CheckParams ( 1, "SNN" )) return 0; cc8* title = lua_tostring ( state, 1 ); u32 width = state.GetValue < u32 >( 2, 320 ); u32 height = state.GetValue < u32 >( 3, 480 ); USGfxDevice::Get ().SetSize ( width, height ); AKUOpenWindowFunc openWindow = AKUGetFunc_OpenWindow (); if ( openWindow ) { openWindow ( title, width, height ); } return 0; } //----------------------------------------------------------------// /** @name pauseTimer @text Pauses or unpauses the device timer, preventing any visual updates (rendering) while paused. @in boolean pause Whether the device timer should be paused. @out nil */ int MOAISim::_pauseTimer ( lua_State* L ) { USLuaState state ( L ); bool pause = state.GetValue < bool >( 1, true ); if ( pause ) { MOAISim::Get ().mTimerState = MOAISim::RESUMING; } else { MOAISim::Get ().mTimerState = MOAISim::RUNNING; } return 0; } //----------------------------------------------------------------// /** @name popRenderPass @text Pops the rendering prim off the stack. @out nil */ int MOAISim::_popRenderPass ( lua_State* L ) { UNUSED ( L ); MOAISim& device = MOAISim::Get (); device.PopRenderPass (); return 0; } //----------------------------------------------------------------// /** @name pushRenderPass @text Pushes the specified prim onto the render stack. @in MOAIProp2D prop The viewport of the render prim. @out nil */ int MOAISim::_pushRenderPass ( lua_State* L ) { USLuaState state ( L ); if ( !state.CheckParams ( 1, "U" )) return 0; MOAIProp2D* prop = state.GetLuaObject < MOAIProp2D >( 1 ); if ( !prop ) return 0; MOAISim& device = MOAISim::Get (); device.PushRenderPass ( prop ); return 0; } //----------------------------------------------------------------// /** @name setClearColor @text At the start of each frame the device will by default automatically render a background color. Using this function you can set the background color that is drawn each frame. If you specify no arguments to this function, then automatic redraw of the background color will be turned off (i.e. the previous render will be used as the background). @opt number red The red value of the color. @opt number green The green value of the color. @opt number blue The blue value of the color. @opt number alpha The alpha value of the color. @out nil */ int MOAISim::_setClearColor ( lua_State* L ) { USLuaState state ( L ); MOAISim& sim = MOAISim::Get (); if ( state.GetTop () == 0 ) { sim.mClearFlags &= ~GL_COLOR_BUFFER_BIT; } else { float r = state.GetValue < float >( 1, 0.0f ); float g = state.GetValue < float >( 2, 0.0f ); float b = state.GetValue < float >( 3, 0.0f ); float a = state.GetValue < float >( 4, 1.0f ); sim.mClearColor = USColor::PackRGBA ( r, g, b, a ); sim.mClearFlags |= GL_COLOR_BUFFER_BIT; } return 0; } //----------------------------------------------------------------// /** @name setClearDepth @text At the start of each frame the device will by default automatically clear the depth buffer. This function sets whether or not the depth buffer should be cleared at the start of each frame. @in boolean clearDepth Whether to clear the depth buffer each frame. @out nil */ int MOAISim::_setClearDepth ( lua_State* L ) { USLuaState state ( L ); MOAISim& sim = MOAISim::Get (); bool clearDepth = state.GetValue < bool >( 1, false ); if ( clearDepth ) { sim.mClearFlags |= GL_DEPTH_BUFFER_BIT; } else { sim.mClearFlags &= ~GL_DEPTH_BUFFER_BIT; } return 0; } //----------------------------------------------------------------// /** @name setFrameSize @text Sets the amount of time it takes for one frame to pass. This in effect can be used to set the FPS limit of the application by passing (1 / FPS). @in number size The frame size (how long in seconds it takes for one frame to be rendered). @out nil */ int MOAISim::_setFrameSize ( lua_State* L ) { USLuaState state ( L ); if ( !state.CheckParams ( 1, "N" )) return 0; MOAISim& device = MOAISim::Get (); device.mStep = state.GetValue < double >( 1, device.mStep ); return 0; } //----------------------------------------------------------------// /** @name timeToFrames @text Converts the number of time passed in seconds to frames. @in number time The number of seconds. @out number frames The equivilant number of frames for the specified number of seconds. */ int MOAISim::_timeToFrames ( lua_State* L ) { USLuaState state ( L ); if ( !state.CheckParams ( 1, "N" )) return 0; float time = state.GetValue < float >( 1, 0.0f ); MOAISim& device = MOAISim::Get (); lua_pushnumber ( state, time / device.mStep ); return 0; } //================================================================// // MOAISim //================================================================// //----------------------------------------------------------------// void MOAISim::Clear () { while ( this->mRenderPasses.Count ()) { this->PopRenderPass (); } } //----------------------------------------------------------------// MOAISim::MOAISim () : mTimerState ( RESUMING ), mDeviceTime ( 0.0f ), mStep ( 0.01f ), mTime ( 0.0f ), mFrameTime ( 0.0 ), mFrameRate ( 0.0f ), mFrameRateIdx ( 0 ), mClearFlags ( GL_COLOR_BUFFER_BIT ), mClearColor ( 0xff000000 ), mHasNetwork ( false ) { RTTI_SINGLE ( USLuaObject ) this->mDeviceTime = USDeviceTime::GetTimeInSeconds (); // Start Lua USLuaRuntime& luaRuntime = USLuaRuntime::Get (); luaRuntime.Open (); luaRuntime.LoadLibs ( "moai" ); #if USE_LUA_SOCKET USLuaStateHandle state = luaRuntime.State (); luaopen_socket_core ( state ); #endif for ( u32 i = 0; i < FPS_BUFFER_SIZE; ++i ) { this->mFrameRateBuffer [ i ] = 0.0f; } } //----------------------------------------------------------------// MOAISim::~MOAISim () { this->Clear (); } //----------------------------------------------------------------// void MOAISim::MeasureFrameRate () { double delay = USDeviceTime::GetTimeInSeconds () - this->mFrameTime; this->mFrameTime = USDeviceTime::GetTimeInSeconds (); if ( delay > 0.0 ) { float sample = ( float )( 1.0 / delay ); this->mFrameRateBuffer [ this->mFrameRateIdx++ ] = sample; this->mFrameRateIdx %= FPS_BUFFER_SIZE; sample = 0.0f; for ( u32 i = 0; i < FPS_BUFFER_SIZE; ++i ) { sample += this->mFrameRateBuffer [ i ]; } this->mFrameRate = sample / ( float )FPS_BUFFER_SIZE; } } //----------------------------------------------------------------// void MOAISim::PauseMOAI () { this->mTimerState = PAUSED; } //----------------------------------------------------------------// void MOAISim::PopRenderPass () { if ( this->mRenderPasses.Count ()) { MOAIProp2D* prop = this->mRenderPasses.Back (); this->mRenderPasses.PopBack (); prop->Release (); } } //----------------------------------------------------------------// void MOAISim::PushRenderPass ( MOAIProp2D* prop ) { if ( prop ) { if ( !this->mRenderPasses.Contains ( prop )) { prop->Retain (); this->mRenderPasses.PushBack ( prop ); } } } //----------------------------------------------------------------// void MOAISim::RegisterLuaClass ( USLuaState& state ) { luaL_Reg regTable [] = { { "clearRenderStack", _clearRenderStack }, { "enterFullscreenMode", _enterFullscreenMode }, { "exitFullscreenMode", _exitFullscreenMode }, { "framesToTime", _framesToTime }, { "getDeviceIDString", _getDeviceIDString }, { "getDeviceSize", _getDeviceSize }, { "getElapsedFrames", _getElapsedFrames }, { "getElapsedTime", _getElapsedTime }, { "getFrameSize", _getFrameSize }, { "getNetworkStatus", _getNetworkStatus }, { "getPerformance", _getPerformance }, { "openWindow", _openWindow }, { "pauseTimer", _pauseTimer }, { "popRenderPass", _popRenderPass }, { "pushRenderPass", _pushRenderPass }, { "setClearColor", _setClearColor }, { "setClearDepth", _setClearDepth }, { "setFrameSize", _setFrameSize }, { "timeToFrames", _timeToFrames }, { NULL, NULL } }; luaL_register( state, 0, regTable ); } //----------------------------------------------------------------// void MOAISim::Render () { if ( this->mClearFlags & GL_COLOR_BUFFER_BIT ) { USColorVec clearColor; clearColor.SetRGBA ( this->mClearColor ); glClearColor ( clearColor.mR, clearColor.mG, clearColor.mB, clearColor.mA ); } if ( this->mClearFlags ) { glClear ( this->mClearFlags ); } USDrawBuffer::Get ().Reset (); RenderPassIt passIt = this->mRenderPasses.Head (); for ( ; passIt; passIt = passIt->Next ()) { MOAIProp2D* renderPass = passIt->Data (); USCanvas::BeginDrawing (); renderPass->Draw (); } USDrawBuffer::Get ().Flush (); } //----------------------------------------------------------------// void MOAISim::ResumeMOAI() { if ( this->mTimerState == PAUSED ) { this->mTimerState = RESUMING; } } //----------------------------------------------------------------// void MOAISim::RunFile ( cc8* filename ) { if ( !USFileSys::CheckFileExists ( filename )) return; int status; USLuaStateHandle state = USLuaRuntime::Get ().State (); status = luaL_loadfile ( state, filename ); if ( state.PrintErrors ( status )) return; this->mRenderPasses.Clear (); MOAIActionMgr::Get ().Clear (); this->mTime = 0.0f; this->mDeviceTime = 0.0; state.DebugCall ( 0, 0 ); AKUStartGameLoopFunc startGameLoop = AKUGetFunc_StartGameLoop (); if ( startGameLoop ) { startGameLoop (); } } //----------------------------------------------------------------// void MOAISim::RunString ( cc8* script ) { int status; USLuaStateHandle state = USLuaRuntime::Get ().State (); status = luaL_loadstring ( state, script ); if ( state.PrintErrors ( status )) return; this->mRenderPasses.Clear (); MOAIActionMgr::Get ().Clear (); this->mTime = 0.0f; this->mDeviceTime = 0.0; state.DebugCall ( 0, 0 ); AKUStartGameLoopFunc startGameLoop = AKUGetFunc_StartGameLoop (); if ( startGameLoop ) { startGameLoop (); } } //----------------------------------------------------------------// void MOAISim::SetReachability ( bool networkStatus ) { mHasNetwork = networkStatus; } //----------------------------------------------------------------// void MOAISim::SetUniqueIdentifier ( cc8* uniqueID ) { mUniqueID = uniqueID; } //----------------------------------------------------------------// void MOAISim::Update () { this->MeasureFrameRate (); this->mDeviceTime = USDeviceTime::GetTimeInSeconds (); if ( this->mTimerState != RUNNING ) { this->mTime = this->mDeviceTime; if ( this->mTimerState == RESUMING ) { this->mTimerState = RUNNING; MOAIDebugLines::Get ().Reset (); MOAIInputMgr::Get ().Update (); MOAIActionMgr::Get ().Update ( 0.0f ); MOAINodeMgr::Get ().Update (); } else { return; } } USLuaStateHandle state = USLuaRuntime::Get ().State (); while (( this->mTime + this->mStep ) < this->mDeviceTime ) { MOAIDebugLines::Get ().Reset (); MOAIInputMgr::Get ().Update (); MOAIActionMgr::Get ().Update (( float )this->mStep ); MOAINodeMgr::Get ().Update (); this->mTime += this->mStep; } USUrlMgr::Get ().Process (); #if USE_FMOD MOAIFmod::Get ().Update (); #endif this->mDataIOThread.Publish (); } //----------------------------------------------------------------// STLString MOAISim::ToString () { STLString repr; const char *timer_state; switch ( mTimerState ) { case PAUSED: timer_state = "paused"; break; case RESUMING: timer_state = "resuming"; break; case RUNNING: timer_state = "running"; break; default: timer_state = "INVALID"; } PrettyPrint ( repr, "mTimerState", timer_state ); PRETTY_PRINT ( repr, mTime ) PRETTY_PRINT ( repr, mDeviceTime ) PRETTY_PRINT ( repr, mHasNetwork ) PRETTY_PRINT ( repr, mUniqueID ) return repr; }
[ "[email protected]", "Patrick@agile.(none)", "[email protected]" ]
[ [ [ 1, 13 ], [ 20, 189 ], [ 191, 194 ], [ 210, 404 ], [ 408, 420 ], [ 430, 437 ], [ 459, 499 ], [ 501, 615 ], [ 618, 684 ] ], [ [ 14, 19 ], [ 190, 190 ], [ 195, 209 ], [ 405, 407 ], [ 421, 429 ], [ 438, 458 ], [ 500, 500 ], [ 616, 617 ] ], [ [ 685, 685 ] ] ]
f8ffc580ecaf0742533f51e7a75047f763521e41
b22c254d7670522ec2caa61c998f8741b1da9388
/FinalClient/GuiHandler.cpp
ece313fff2819194dc9a4218c6e664395417396d
[]
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
18,455
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 "GUI.h" #include "GuiHandler.h" #include "LoginGUI.h" #include "LogHandler.h" #include "ChooseWorldGUI.h" #include "GameGUI.h" #include "MenuGUI.h" #include "MenuGUI.h" #include "OptionsGUI.h" #include "ConfigurationManager.h" #include "LbaNetEngine.h" #include "SynchronizedTimeHandler.h" //#include "DataLoader.h" #include <CEGUI.h> #include <RendererModules/OpenGL/CEGUIOpenGLRenderer.h> #include <CEGUIDefaultResourceProvider.h> /*********************************************************** Constructor ***********************************************************/ GuiHandler::GuiHandler() : _currentGUI(-1), _gui_renderer(NULL), _game_gui(NULL), _login_gui(NULL) { } /*********************************************************** Destructor ***********************************************************/ GuiHandler::~GuiHandler() { std::vector<GUI *>::iterator it = _guis.begin(); std::vector<GUI *>::iterator end = _guis.end(); for(; it != end; ++it) delete *it; CEGUI::System::destroy(); CEGUI::OpenGLRenderer::destroy(*_gui_renderer); } /*********************************************************** initialize function ***********************************************************/ void GuiHandler::Initialize(bool ServerOn, const std::string &clientversion, LbaNetEngine * engine) { _engine = engine; try { _gui_renderer = &CEGUI::OpenGLRenderer::create(); _gui_renderer->enableExtraStateSettings(true); //new CEGUI::OpenGLRenderer (0, screen_size_X, screen_size_Y); CEGUI::System::create( *_gui_renderer ); //new CEGUI::System (_gui_renderer); // initialise the required dirs for the DefaultResourceProvider CEGUI::DefaultResourceProvider* rp = static_cast<CEGUI::DefaultResourceProvider*> (CEGUI::System::getSingleton().getResourceProvider()); rp->setResourceGroupDirectory("schemes", "./Data/GUI/schemes/"); rp->setResourceGroupDirectory("imagesets", "./Data/GUI/imagesets/"); rp->setResourceGroupDirectory("fonts", "./Data/GUI/fonts/"); rp->setResourceGroupDirectory("layouts", "./Data/GUI/layouts/"); rp->setResourceGroupDirectory("looknfeels", "./Data/GUI/looknfeel/"); rp->setResourceGroupDirectory("lua_scripts", "./Data/GUI/lua_scripts/"); // set the default resource groups to be used CEGUI::Imageset::setDefaultResourceGroup("imagesets"); CEGUI::Font::setDefaultResourceGroup("fonts"); CEGUI::Scheme::setDefaultResourceGroup("schemes"); CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels"); CEGUI::WindowManager::setDefaultResourceGroup("layouts"); CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts"); // load in the scheme file, which auto-loads the TaharezLook imageset CEGUI::SchemeManager::getSingleton().create( "TaharezLook.scheme" ); //! load font file CEGUI::FontManager::getSingleton().create( "abbey_m1-9.font" ); ReloadFontSize(); CEGUI::System::getSingleton().setDefaultMouseCursor( "TaharezLook", "MouseArrow" ); CEGUI::System::getSingleton().setDefaultTooltip( "TaharezLook/Tooltip" ); // Load the Imageset that has the pictures for our button. CEGUI::ImagesetManager::getSingleton().create( "LogoBig.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "LogoCenter.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "lbaNetB.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "chatbutton.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "TeleportButton.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "HeadInterface.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "optionsbutton.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "soundbutton.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "changeworldbutton.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "quitbutton.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "MenuChar.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "tunic.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "quest.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "weapon.imageset" ); CEGUI::ImagesetManager::getSingleton().create( "contourfont.imageset" ); CEGUI::FontManager::getSingleton().create( "ContourFont.font" ); // loading the smileys { { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_biggrin", "smileys/biggrin.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_bloated", "smileys/bloated.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_confused", "smileys/confused.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_cool", "smileys/cool.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_dinofly", "smileys/dinofly.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_eek", "smileys/eek.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_embarrassment", "smileys/embarrassment.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_evil", "smileys/evil.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_evilwink", "smileys/evilwink.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_frown", "smileys/frown.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_funfrock", "smileys/funfrock.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_hmpf", "smileys/hmpf.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_hmz", "smileys/hmz.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_kiss", "smileys/kiss.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_lol", "smileys/lol.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_mad", "smileys/mad.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_proud", "smileys/proud.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_rabibunny", "smileys/rabibunny.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_rolleyes", "smileys/rolleyes.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_sad", "smileys/sad.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_sigh", "smileys/sigh.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_smilie", "smileys/smilie.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_stupid", "smileys/stupid.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_tdown", "smileys/tdown.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_tup", "smileys/tup.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_wink", "smileys/wink.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_zoe", "smileys/zoe.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_zombie", "smileys/zombie.png"); ims.setAutoScalingEnabled(false); } { CEGUI::Imageset &ims = CEGUI::ImagesetManager::getSingleton().createFromImageFile("sm_tongue", "smileys/tongue.png"); ims.setAutoScalingEnabled(false); } } } catch(CEGUI::Exception &ex) { LogHandler::getInstance()->LogToFile(std::string("Exception init gui: ") + ex.getMessage().c_str()); } //initialize the login gui _login_gui = new LoginGUI(); _login_gui->Initialize(clientversion); _login_gui->SetServrOn(ServerOn); _guis.push_back(_login_gui); ChooseWorldGUI * cwG = new ChooseWorldGUI(); cwG->Initialize(); _guis.push_back(cwG); //std::vector<WorldDesc> list; //DataLoader::getInstance()->GetAvailableWorlds(list); //cwG->SetWorldList(list); _game_gui = new GameGUI(); _game_gui->Initialize(); _guis.push_back(_game_gui); MenuGUI * menuG = new MenuGUI(); menuG->Initialize(); _guis.push_back(menuG); _option_gui = new OptionsGUI(); _option_gui->Initialize(); _guis.push_back(_option_gui); SwitchGUI(0); // clearing this queue actually makes sure it's created(!) //_gui_renderer->getDefaultRenderingRoot().clearGeometry(CEGUI::RQ_OVERLAY); // subscribe handler to render overlay items //_gui_renderer->getDefaultRenderingRoot(). // subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted, // CEGUI::Event::Subscriber(&GuiHandler::overlayHandler, this)); } /*********************************************************** inject time to the GUI ***********************************************************/ void GuiHandler::inject_time_pulse() { /* get current "run-time" in seconds */ double t = 0.001*SynchronizedTimeHandler::getInstance()->GetCurrentTimeDoubleSync(); /* inject the time that passed since the last call */ CEGUI::System::getSingleton().injectTimePulse( float(t-m_last_time_pulse) ); /* store the new time as the last time */ m_last_time_pulse = t; } /*********************************************************** process function ***********************************************************/ void GuiHandler::Process(void) { inject_time_pulse(); std::vector<GUI *>::iterator it = _guis.begin(); std::vector<GUI *>::iterator end = _guis.end(); for(; it != end; ++it) (*it)->Process(); } /*********************************************************** switch from current gui to another one ***********************************************************/ void GuiHandler::SwitchGUI(int GuiNumber) { if(GuiNumber == _currentGUI) return; try { CEGUI::Window * root = _guis[GuiNumber]->GetRoot(); if(root) { CEGUI::System::getSingleton().setGUISheet( root ); _guis[GuiNumber]->Displayed(); } } catch(CEGUI::Exception &ex) { LogHandler::getInstance()->LogToFile(std::string("Exception changing gui: ") + ex.getMessage().c_str()); } _currentGUI = GuiNumber; } /*********************************************************** redraw the scene on screen ***********************************************************/ //void GuiHandler::Redraw(void) //{ // CEGUI::System::getSingleton().renderGUI(); //} /*********************************************************** called when the windows is resized ***********************************************************/ void GuiHandler::Resize(int screen_size_X, int screen_size_Y) { CEGUI::System::getSingleton(). notifyDisplaySizeChanged(CEGUI::Size((float)screen_size_X,(float)screen_size_Y)); _game_gui->Refresh(); } /*********************************************************** called when the windows is resized ***********************************************************/ void GuiHandler::grabTextures() { _gui_renderer->grabTextures(); } /*********************************************************** called when the windows is resized ***********************************************************/ void GuiHandler::restoreTextures() { _gui_renderer->restoreTextures(); } /*********************************************************** set the current map of the game ***********************************************************/ void GuiHandler::SetCurrentMap(const std::string & WorldName, const std::string & MapName) { if(_game_gui) _game_gui->SetCurrentMap(WorldName, MapName); } /*********************************************************** focus the chatbox ***********************************************************/ void GuiHandler::FocusChatbox(bool focus) { if(_game_gui) _game_gui->FocusChatbox(focus); } /*********************************************************** set irc thread ***********************************************************/ void GuiHandler::SetIrcThread(IrcThread * IT) { if(_game_gui) _game_gui->SetIrcThread(IT); } /*********************************************************** called when font size changed ***********************************************************/ void GuiHandler::ReloadFontSize() { // load in a font. The first font loaded automatically becomes the default font. int fontsize; ConfigurationManager::GetInstance()->GetInt("Options.Gui.FontSize", fontsize); std::stringstream strs; strs<<"DejaVuSans-"<<fontsize; //if(!CEGUI::FontManager::getSingleton().isFontPresent( strs.str() ) ) CEGUI::FontManager::getSingleton().create( strs.str() + ".font" ); CEGUI::System::getSingleton().setDefaultFont( strs.str() ); } /*********************************************************** set the list of teleport places ***********************************************************/ void GuiHandler::SetTeleportList(const std::map<std::string, TPInfo> &_lists) { if(_game_gui) _game_gui->SetTeleportList(_lists); } /*********************************************************** display game text ***********************************************************/ bool GuiHandler::DisplayGameText(long textid, bool show) { if(_game_gui) return _game_gui->DisplayGameText(textid, show); return true; } /*********************************************************** inform the user the login failed ***********************************************************/ void GuiHandler::InformNotLoggedIn(int problem, const std::string & reason) { if(_login_gui) _login_gui->InformNotLoggedIn(problem, reason); } /*********************************************************** set actors ***********************************************************/ //void GuiHandler::SetActors(std::map<long, Actor *> * Lactors, std::map<long, Actor *> * Eactors) //{ // if(_game_gui)_game_gui->SetActors(Lactors, Eactors); //} /*********************************************************** set player name ***********************************************************/ void GuiHandler::SetPlayerName(const std::string & name) { if(_game_gui) _game_gui->SetPlayerName(name); } /*********************************************************** handle overlay ***********************************************************/ bool GuiHandler::overlayHandler(const CEGUI::EventArgs& args) { if (static_cast<const CEGUI::RenderQueueEventArgs&>(args).queueID != CEGUI::RQ_OVERLAY) return false; //_engine->DrawOverlay(); return true; } /*********************************************************** display inventory ***********************************************************/ void GuiHandler::ShowInventory() { if(_game_gui)_game_gui->ShowInventory(); } /*********************************************************** display inventory ***********************************************************/ void GuiHandler::RefreshOption() { if(_option_gui)_option_gui->SendNameColor(); } /*********************************************************** show dialog with NPC ***********************************************************/ //void GuiHandler::ShowDialog(long ActorId, const std::string &ActorName, DialogHandlerPtr Dialog, // bool Show, const std::map<long, TraderItem> &inventory) //{ // if(_game_gui)_game_gui->ShowDialog(ActorId, ActorName, Dialog, Show, inventory); //}
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 566 ] ] ]
996ffbe6d2025d13c0fc45450d177416f3800d08
b2155efef00dbb04ae7a23e749955f5ec47afb5a
/tools/ModelConverter/IConverter.cpp
b3214899283ee03c798772b31b93903a0ef5a801
[]
no_license
zjhlogo/originengine
00c0bd3c38a634b4c96394e3f8eece86f2fe8351
a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f
refs/heads/master
2021-01-20T13:48:48.015940
2011-04-21T04:10:54
2011-04-21T04:10:54
32,371,356
1
0
null
null
null
null
UTF-8
C++
false
false
229
cpp
/*! * \file IConverter.cpp * \date 1-3-2010 21:19:26 * * * \author zjhlogo ([email protected]) */ #include "IConverter.h" IConverter::IConverter() { // TODO: } IConverter::~IConverter() { // TODO: }
[ "zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571" ]
[ [ [ 1, 18 ] ] ]
88c717e2681bfdf9e3d5140036ade932dbfd2e69
636990a23a0f702e3c82fa3fc422f7304b0d7b9e
/ocx/AnvizOcx/AnvizOcx/ProtocolTest/Reader.h
1f6f7ef34055df6c42da257f349df92297453419
[]
no_license
ak869/armcontroller
09599d2c145e6457aa8c55c8018514578d897de9
da68e180cacce06479158e7b31374e7ec81c3ebf
refs/heads/master
2021-01-13T01:17:25.501840
2009-02-09T18:03:20
2009-02-09T18:03:20
40,271,726
0
1
null
null
null
null
UTF-8
C++
false
false
768
h
// Reader.h: interface for the CReader class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_READER_H__859025B4_1F31_418C_A31C_16C020F75793__INCLUDED_) #define AFX_READER_H__859025B4_1F31_418C_A31C_16C020F75793__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Controller.h" class CReader : public CController { public: BOOL UnLinkDoor(BYTE nDoor); BOOL LinkDoor(BYTE nDoor); BOOL SetStatus(BYTE node, BYTE value); BOOL GetStatus(BYTE node, BYTE *value); BOOL GetAttrib(BYTE node, BYTE *value); BOOL SetAttrib(BYTE node, BYTE value); CReader(); virtual ~CReader(); }; #endif // !defined(AFX_READER_H__859025B4_1F31_418C_A31C_16C020F75793__INCLUDED_)
[ "leon.b.dong@41cf9b94-d0c3-11dd-86c2-0f8696b7b6f9" ]
[ [ [ 1, 28 ] ] ]
9e1ac8c6da4415b7cd7aadf0e1a9e6672cac9053
cfa667b1f83649600e78ea53363ee71dfb684d81
/code/toolkit/idlcompiler/idlc.cc
9ffb71511342c5d025397d2bd42649fa4374c4d4
[]
no_license
zhouxh1023/nebuladevice3
c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f
3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241
refs/heads/master
2021-01-23T08:56:15.823698
2011-08-26T02:22:25
2011-08-26T02:22:25
32,018,644
0
1
null
null
null
null
UTF-8
C++
false
false
747
cc
//------------------------------------------------------------------------------ // idlc.cc // (C) 2006 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "toolkit/idlcompiler/idlcompiler.h" using namespace Tools; using namespace Util; //------------------------------------------------------------------------------ /** */ void __cdecl main(int argc, const char** argv) { CommandLineArgs args(argc, argv); IDLCompiler app; app.SetCompanyName("Radon Labs GmbH"); app.SetAppTitle("Nebula3 IDL Compiler"); app.SetCmdLineArgs(args); if (app.Open()) { app.Run(); app.Close(); } app.Exit(); }
[ [ [ 1, 28 ] ] ]
7d6e25457d63006f0f05b3e66efba2fd677d5fc5
9907be749dc7553f97c9e51c5f35e69f55bd02c0
/WordplaySingle/template_project/api_code/GFText.h
b78fed667bf2a9d624b31c592b9deed3b6c62cc8
[]
no_license
jdeering/csci476winthrop
bc8907b9cc0406826de76aca05e6758810377813
2bc485781f819c8fd82393ac86de33404e7ad6d3
refs/heads/master
2021-01-10T19:53:14.853438
2009-04-24T14:26:36
2009-04-24T14:26:36
32,223,762
0
0
null
null
null
null
UTF-8
C++
false
false
632
h
#pragma once #include <string> #include "GFObject.h" class GFText : public GFObject { /* SO THAT THE FRAMEWORK CAN ACCESS PROTECTED MEMBERS */ friend class GameFramework; public: /* PUBLIC DESTRUCTOR */ ~GFText(); /* SCREEN POSITION */ int _x, _y; /* NULL OBJECT */ static const GFText null; /* FRAMEWORK CALLS */ void setTextPosition(int, int); void setVisible(bool); void setContent(std::string); /* PRINT FUNCTION (FOR DEBUG) */ friend std::ostream& operator<<(std::ostream&, GFText&); protected: /* PROTECTED CONSTRUCTOR */ GFText(int, int, int); };
[ "lcairco@2656ef14-ecf4-11dd-8fb1-9960f2a117f8" ]
[ [ [ 1, 33 ] ] ]
be39143be44384c0c67eee87f7ba4ff718d7e3fa
c2ffd6042f31e6f524a9b275e8242a7f18525f67
/plugin/malextract/malextract/MalwareExtractor.h
f6607b77a1c9909f281fb832dd6ba96f7a85a1b9
[]
no_license
tadasv/splinterbyte
76ac6b64b192eb1d4d53b7e2c4ac8ca54c0168bb
d8b674d4dc9a6f7a186972b18cf33a6abcf29e95
refs/heads/master
2016-09-03T06:52:46.970481
2011-05-18T03:20:07
2011-05-18T03:20:07
1,764,249
9
0
null
null
null
null
UTF-8
C++
false
false
1,170
h
#ifndef __MALWARE_EXTRACTOR_H__ #define __MALWARE_EXTRACTOR_H__ #include "plugin.h" #include <vector> enum { ME_ERROR_NOERROR = 0, // Everything is fine. ME_ERROR_NOTHREAD, // No thread found. ME_ERROR_MEMALLOC, // Memory allocation failed. ME_ERROR_MEMREAD, // Memory read failed. ME_ERROR_OUTOFBOUNDS, // Trying to access array out of its bounds. ME_ERROR_NOTFOUND // Could not find something. }; struct ME_MODULE_RANGE { ulong base; // Starting memory address. ulong size; // Size of the memory region. }; class MalwareExtractor { private: uchar *m_imagecopy; // Copy of a whole executable image. int m_running; // Set to 1 if plugin is running. t_thread *m_thread; // t_module *m_module; // // std::vector<ME_MODULE_RANGE> m_module_ranges; int m_error_code; // Error code of a last operation/function. ulong m_next_address; // Address of the next CF changing instruction. public: MalwareExtractor(); ~MalwareExtractor(); int Initialize(); void Reset(); int FindNextAddress(ulong start); int IsRunning(); int GetErrorCode(); private: void BackupModuleRanges(); }; #endif
[ [ [ 1, 49 ] ] ]
6b68af3b48eabd0ec2e6f98381084c8b29343e55
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/test/switch_tests_single.cpp
3852838b392b59359efbf5bf14d5330a76b2f68b
[ "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
11,588
cpp
/*============================================================================= Copyright (c) 2003 Hartmut Kaiser http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #include <iostream> #include <boost/detail/lightweight_test.hpp> using namespace std; #define BOOST_SPIRIT_SWITCH_CASE_LIMIT 6 #define BOOST_SPIRIT_SELECT_LIMIT 6 #define PHOENIX_LIMIT 6 //#define BOOST_SPIRIT_DEBUG #include <boost/mpl/list.hpp> #include <boost/mpl/for_each.hpp> #include <boost/spirit/core/primitives/primitives.hpp> #include <boost/spirit/core/primitives/numerics.hpp> #include <boost/spirit/core/composite/actions.hpp> #include <boost/spirit/core/composite/operators.hpp> #include <boost/spirit/core/non_terminal/rule.hpp> #include <boost/spirit/core/non_terminal/grammar.hpp> #include <boost/spirit/dynamic/switch.hpp> #include <boost/spirit/dynamic/select.hpp> #include <boost/spirit/attribute/closure.hpp> using namespace boost::spirit; namespace test_grammars { /////////////////////////////////////////////////////////////////////////////// // Test the direct switch_p usage struct switch_grammar_direct_single : public grammar<switch_grammar_direct_single> { template <typename ScannerT> struct definition { definition(switch_grammar_direct_single const& /*self*/) { r = switch_p [ case_p<'a'>(int_p) ]; } rule<ScannerT> r; rule<ScannerT> const& start() const { return r; } }; }; struct switch_grammar_direct_default_single1 : public grammar<switch_grammar_direct_default_single1> { template <typename ScannerT> struct definition { definition(switch_grammar_direct_default_single1 const& /*self*/) { r = switch_p [ default_p(str_p("default")) ]; } rule<ScannerT> r; rule<ScannerT> const& start() const { return r; } }; }; struct switch_grammar_direct_default_single2 : public grammar<switch_grammar_direct_default_single2> { template <typename ScannerT> struct definition { definition(switch_grammar_direct_default_single2 const& /*self*/) { r = switch_p [ default_p ]; } rule<ScannerT> r; rule<ScannerT> const& start() const { return r; } }; }; /////////////////////////////////////////////////////////////////////////////// // Test the switch_p usage given a parser as the switch condition struct switch_grammar_parser_single : public grammar<switch_grammar_parser_single> { template <typename ScannerT> struct definition { definition(switch_grammar_parser_single const& /*self*/) { r = switch_p(anychar_p) [ case_p<'a'>(int_p) ]; } rule<ScannerT> r; rule<ScannerT> const& start() const { return r; } }; }; struct switch_grammar_parser_default_single1 : public grammar<switch_grammar_parser_default_single1> { template <typename ScannerT> struct definition { definition(switch_grammar_parser_default_single1 const& /*self*/) { r = switch_p(anychar_p) [ default_p(str_p("default")) ]; } rule<ScannerT> r; rule<ScannerT> const& start() const { return r; } }; }; struct switch_grammar_parser_default_single2 : public grammar<switch_grammar_parser_default_single2> { template <typename ScannerT> struct definition { definition(switch_grammar_parser_default_single2 const& /*self*/) { r = switch_p(anychar_p) [ default_p ]; } rule<ScannerT> r; rule<ScannerT> const& start() const { return r; } }; }; /////////////////////////////////////////////////////////////////////////////// // Test the switch_p usage given an actor as the switch condition struct select_result : public boost::spirit::closure<select_result, int> { member1 val; }; struct switch_grammar_actor_single : public grammar<switch_grammar_actor_single> { template <typename ScannerT> struct definition { definition(switch_grammar_actor_single const& /*self*/) { using phoenix::arg1; r = select_p('a')[r.val = arg1] >> switch_p(r.val) [ case_p<0>(int_p) ]; } rule<ScannerT, select_result::context_t> r; rule<ScannerT, select_result::context_t> const& start() const { return r; } }; }; struct switch_grammar_actor_default_single1 : public grammar<switch_grammar_actor_default_single1> { template <typename ScannerT> struct definition { definition(switch_grammar_actor_default_single1 const& /*self*/) { using phoenix::arg1; r = select_p('d')[r.val = arg1] >> switch_p(r.val) [ default_p(str_p("default")) ]; } rule<ScannerT, select_result::context_t> r; rule<ScannerT, select_result::context_t> const& start() const { return r; } }; }; struct switch_grammar_actor_default_single2 : public grammar<switch_grammar_actor_default_single2> { template <typename ScannerT> struct definition { definition(switch_grammar_actor_default_single2 const& /*self*/) { using phoenix::arg1; r = select_p('d')[r.val = arg1] >> switch_p(r.val) [ default_p ]; } rule<ScannerT, select_result::context_t> r; rule<ScannerT, select_result::context_t> const& start() const { return r; } }; }; } // namespace test_grammars /////////////////////////////////////////////////////////////////////////////// namespace tests { // Tests for known (to the grammars) sequences struct check_grammar_unknown { template <typename GrammarT> void operator()(GrammarT) { GrammarT g; BOOST_TEST(!parse("a1", g).hit); BOOST_TEST(!parse("a,", g).hit); BOOST_TEST(!parse("abcd", g).hit); BOOST_TEST(!parse("a 1", g, space_p).hit); BOOST_TEST(!parse("a ,", g, space_p).hit); BOOST_TEST(!parse("a bcd", g, space_p).hit); BOOST_TEST(!parse("b1", g).hit); BOOST_TEST(!parse("b,", g).hit); BOOST_TEST(!parse("bbcd", g).hit); BOOST_TEST(!parse("b 1", g, space_p).hit); BOOST_TEST(!parse("b ,", g, space_p).hit); BOOST_TEST(!parse("b bcd", g, space_p).hit); BOOST_TEST(!parse("c1", g).hit); BOOST_TEST(!parse("c,", g).hit); BOOST_TEST(!parse("cbcd", g).hit); BOOST_TEST(!parse("c 1", g, space_p).hit); BOOST_TEST(!parse("c ,", g, space_p).hit); BOOST_TEST(!parse("c bcd", g, space_p).hit); } }; // Tests for the default branches (with parsers) of the grammars struct check_grammar_default { template <typename GrammarT> void operator()(GrammarT) { GrammarT g; BOOST_TEST(parse("ddefault", g).full); BOOST_TEST(parse("d default", g, space_p).full); } }; // Tests for the default branches (without parsers) of the grammars struct check_grammar_default_plain { template <typename GrammarT> void operator()(GrammarT) { GrammarT g; BOOST_TEST(parse("d", g).full); BOOST_TEST(parse(" d", g, space_p).full); // JDG 10-18-2005 removed trailing ' ' to // avoid post skip problems } }; // Tests grammars with a single case_p branch struct check_grammar_single { template <typename GrammarT> void operator()(GrammarT) { GrammarT g; BOOST_TEST(parse("a1", g).full); BOOST_TEST(!parse("a,", g).hit); BOOST_TEST(!parse("abcd", g).hit); BOOST_TEST(parse("a 1", g, space_p).full); BOOST_TEST(!parse("a ,", g, space_p).hit); BOOST_TEST(!parse("a bcd", g, space_p).hit); BOOST_TEST(!parse("b1", g).hit); BOOST_TEST(!parse("b,", g).hit); BOOST_TEST(!parse("bbcd", g).hit); BOOST_TEST(!parse("b 1", g, space_p).hit); BOOST_TEST(!parse("b ,", g, space_p).hit); BOOST_TEST(!parse("b bcd", g, space_p).hit); BOOST_TEST(!parse("c1", g).hit); BOOST_TEST(!parse("c,", g).hit); BOOST_TEST(!parse("cbcd", g).hit); BOOST_TEST(!parse("c 1", g, space_p).hit); BOOST_TEST(!parse("c ,", g, space_p).hit); BOOST_TEST(!parse("c bcd", g, space_p).hit); } }; } // namespace tests int main() { // Test switch_p with a single case_p branch typedef boost::mpl::list< test_grammars::switch_grammar_direct_single, test_grammars::switch_grammar_parser_single, test_grammars::switch_grammar_actor_single > single_list_t; boost::mpl::for_each<single_list_t>(tests::check_grammar_single()); typedef boost::mpl::list< test_grammars::switch_grammar_direct_default_single1, test_grammars::switch_grammar_parser_default_single1, test_grammars::switch_grammar_actor_default_single1 > default_single_t; boost::mpl::for_each<default_single_t>(tests::check_grammar_default()); boost::mpl::for_each<default_single_t>(tests::check_grammar_unknown()); typedef boost::mpl::list< test_grammars::switch_grammar_direct_default_single2, test_grammars::switch_grammar_parser_default_single2, test_grammars::switch_grammar_actor_default_single2 > default_plain_single_t; boost::mpl::for_each<default_plain_single_t>( tests::check_grammar_default_plain()); return boost::report_errors(); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 351 ] ] ]
77351de50634f8b7d2f63725be2df10536727810
5fb9b06a4bf002fc851502717a020362b7d9d042
/developertools/GrannyViewer/LogView.cpp
a41a9de58b9a1f9fc60875e67151807c512eb40d
[]
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
UHC
C++
false
false
1,811
cpp
// LogView.cpp : ๊ตฌํ˜„ ํŒŒ์ผ์ž…๋‹ˆ๋‹ค. // #include "stdafx.h" #include "GrannyViewer.h" #include "LogView.h" #include ".\logview.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CLogView IMPLEMENT_DYNCREATE(CLogView, CEditView) CLogView::CLogView() { } CLogView::~CLogView() { } BEGIN_MESSAGE_MAP(CLogView, CEditView) ON_WM_CREATE() END_MESSAGE_MAP() // CLogView ์ง„๋‹จ์ž…๋‹ˆ๋‹ค. #ifdef _DEBUG void CLogView::AssertValid() const { CEditView::AssertValid(); } void CLogView::Dump(CDumpContext& dc) const { CEditView::Dump(dc); } #endif //_DEBUG // CLogView ๋ฉ”์‹œ์ง€ ์ฒ˜๋ฆฌ๊ธฐ์ž…๋‹ˆ๋‹ค. int CLogView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CEditView::OnCreate(lpCreateStruct) == -1) return -1; GetEditCtrl().SetReadOnly(); CWinApp *pApp = AfxGetApp(); CString strFont = pApp->GetProfileString(_T("font"), _T("name"), _T("Courier")); int iSize = pApp->GetProfileInt(_T("font"), _T("size"), 10); SetFont(strFont, iSize, false); return 0; } void CLogView::Log(LPCTSTR lpszLog) { CEdit& edit = GetEditCtrl(); edit.SetSel((int)GetBufferLength(), -1); CString strLog(lpszLog); strLog.Replace("\n", "\r\n"); edit.ReplaceSel(strLog); } void CLogView::OnInitialUpdate() { CEditView::OnInitialUpdate(); } void CLogView::Clear(void) { CEdit& edit = GetEditCtrl(); edit.SetSel(0,-1); edit.ReplaceSel(""); } void CLogView::SetFont(LPCTSTR szFontName, int iFontSize, bool bSave) { if (bSave) { CWinApp *pApp = AfxGetApp(); pApp->WriteProfileString(_T("font"), _T("name"), szFontName); pApp->WriteProfileInt(_T("font"), _T("size"), iFontSize); } m_font.DeleteObject(); m_font.CreatePointFont(iFontSize, szFontName); SendMessage(WM_SETFONT, (WPARAM)(HFONT)m_font); }
[ "harkon@a725d9c3-d2eb-0310-b856-fa980ef11a19" ]
[ [ [ 1, 97 ] ] ]
8e2f4dc38d414d5c23fe73aebc424e8f104fe1a0
57574cc7192ea8564bd630dbc2a1f1c4806e4e69
/Poker/Servidor/OpGetCantidadFichas.cpp
3b187f7fe69d7228a945c679f741a252e5969bb8
[]
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
1,105
cpp
#include "OpGetCantidadFichas.h" #include "AccesoDatos.h" #include "JugadorModelo.h" #include "GeneradorRespuesta.h" #include "Resultado.h" #include "UtilTiposDatos.h" OpGetCantidadFichas::OpGetCantidadFichas(int idCliente, vector<string> parametros): Operacion(idCliente) { this->parametros = parametros; } OpGetCantidadFichas::~OpGetCantidadFichas(void) { } bool OpGetCantidadFichas::ejecutarAccion(Socket* socket) { bool error = false; bool ok = true; string respuesta = ""; string usuario = this->parametros.at(0); AccesoDatos ad; JugadorModelo* jugador = ad.obtenerJugador(usuario); string msjRetorno = ""; GeneradorRespuesta generador = GeneradorRespuesta(); Resultado* resultado = new Resultado("", UtilTiposDatos::enteroAString(jugador->getFichas()), "OpGetCantidadFichas"); generador.agregarRespuesta(resultado); string resul = generador.obtenerRespuesta(); if (socket != NULL && !MensajesUtil::esVacio(resul)) { if(!socket->enviar(resul)) { error = true; } } else { error = true; } return error; }
[ "[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296" ]
[ [ [ 1, 49 ] ] ]
9031cd9ce6b524fc8e33d6f728fa9673d3a6cdba
f2b4a9d938244916aa4377d4d15e0e2a6f65a345
/Common/ScopePtr.h
ba71c1e1d590ed6bd2e115807c94e56743c37e38
[ "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
5,898
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. */ /// @file /// @brief Non moveable scoped smart pointers //|----------------------------------------------------------- /// @addtogroup mm_common /// @{ #ifndef __SCOPEPTR_H #define __SCOPEPTR_H #pragma warning( push ) #pragma warning( disable: 4284 ) /// Smart scoped pointer class /// Mimics a built-in pointer except that it guarantees deletion /// of the object pointed to, either on destruction of the self /// or via an explicit method call. ScopedPtr is the simple /// solution for the simple needs; Use SharedPtr in other cases. /// \note /// Cannot be used with Array or other container, which /// requires copy constructor or assignment operator /// being defined. Instead use SharedPtr. template< typename T > class ScopedPtr { private: /// contained object T* ptr_; /// Disabled copy ctor ScopedPtr( ScopedPtr const& ); /// Disabled assignment ScopedPtr& operator=( ScopedPtr const& ); typedef ScopedPtr<T> ThisType; public: /// Type of the contained object typedef T ElementType; /// Constructs new ScopedPtr /// Takes as argument pointer to the object which becomes managed. /// \note Does not throw. explicit ScopedPtr( T* p = 0 ) : ptr_( p ) // throw() {} /// Destroys ScopedPtr /// If there still managed object present - destoys it as well. /// \note Does not throw. ~ScopedPtr() // throw() { delete ptr_; } /// Resets ScopedPtr /// Release managed object and destoy it. /// \note Does not throw. void Reset( T* p = 0 ) // throw() { if ( ptr_ != p ) { ThisType(p).Swap( *this ); } } /// Takes reference to the managed pointer. /// \note Does not throw. T& operator*() const // throw() { assert( ptr_ != 0 ); return *ptr_; } /// Dereference managed pointer /// \note Does not throw. T* operator->() const // throw() { assert( ptr_ != 0 ); return ptr_; } /// Takes out managed pointer from ScopedPtr. /// \note Does not throw. T* Get() const // throw() { return ptr_; } /// Checks if there managed pointer inside. /// \return True if managed object present /// \note Does not throw. operator bool() const // throw() { return ptr_ == 0 ? false : true; } /// Checks if there no managed pointer inside. /// \return True if not managed object present. /// \note Does not throw. bool operator!() const // throw() { return ptr_ == 0; } /// Swaps two ScopedPtrs. /// \note Does not throw. void Swap( ScopedPtr& s ) // throw() { T* tmp = s.ptr_; s.ptr_ = ptr_; ptr_ = tmp; } T* Giveup() { T* val = ptr_; ptr_ = 0; return val; } }; /// Smart scoped pointer as array class /// Mimics a built-in pointer to the array, except that it guarantees deletion /// of the array pointed to, either on destruction of the self /// or via an explicit method call. ScopedArray is the simple /// solution for the simple needs; Use SharedArray in other cases. /// \note /// Cannot be used with Array or other container, which /// requires copy constructor or assignment operator /// being defined. Instead use SharedArray. template< typename T > class ScopedArray { private: /// contained array T* ptr_; /// Disabled copy ctor ScopedArray( ScopedArray const& ); /// Disabled assignment ScopedArray& operator=( ScopedArray const& ); typedef ScopedArray<T> ThisType; public: /// Type of the contained object typedef T ElementType; /// Constructs new ScopedArray /// Takes as argument pointer to the object which becomes managed. /// \note Does not throw. explicit ScopedArray( T* p = 0 ) : ptr_( p ) // throw() {} /// Destroys ScopedPtr /// If there still managed object present - destoys it as well. /// \note Does not throw. ~ScopedArray() // throw() { delete[] ptr_; } /// Resets ScopedPtr /// Release managed object and destoy it. /// \note Does not throw. void Reset( T* p = 0 ) // throw() { if ( ptr_ != p ) { delete[] ptr_; ptr_ = p; } } /// Implements [] operator for the contained array /// \note Does not throw. T& operator[]( size_t i ) const // throw() { assert( ptr_ != 0 ); assert( i >= 0 ); return ptr_[ i ]; } /// Takes out managed pointer from ScopedArray. /// \note Does not throw. T* Get() const // throw() { return ptr_; } /// Checks if there managed pointer inside. /// \return True if managed object present /// \note Does not throw. operator bool() const // throw() { return ptr_ == 0 ? false : true; } /// Checks if there no managed pointer inside. /// \return True if not managed object present. /// \note Does not throw. bool operator!() const // throw() { return ptr_ == 0; } /// Swaps two ScopedArrays. /// \note Does not throw. void Swap( ScopedArray& s ) // throw() { T* tmp = s.ptr_; s.ptr_ = ptr_; ptr_ = tmp; } T* Giveup() { T* val = ptr_; ptr_ = 0; return val; } }; #pragma warning( pop ) #endif //__SCOPEPTR_H //--------------------------------------------------------- /// @}
[ "palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276" ]
[ [ [ 1, 228 ] ] ]
49a4a383d63c2c347ed52b72dd6ea968ffd41504
c25bc19757f5cdf030c20c51b5fa85b1867048ec
/Addons/MogreNewt/MogreNewt_Main/inc/OgreNewt_World.h
f9fa5772cf7e56c6fd7a2a8114d6bf5e66fff8e8
[]
no_license
MogreBindings/Mogre17VS2010
99ace77f58548c39f39725b1f7b2ce0157e13079
5f204dd7323a7ff64c7324bbb3ce5d2ceb461c30
refs/heads/master
2022-11-05T02:51:10.751168
2010-05-13T20:53:04
2010-05-13T20:53:04
276,068,888
0
0
null
null
null
null
UTF-8
C++
false
false
12,523
h
/* OgreNewt Library Ogre implementation of Newton Game Dynamics SDK OgreNewt basically has no license, you may use any or all of the library however you desire... I hope it can help you in any way. by Walaber */ #ifndef _INCLUDE_OGRENEWT_WORLD #define _INCLUDE_OGRENEWT_WORLD #include <Newton.h> #include <Ogre.h> #include "OgreNewt_Prerequisites.h" #include "OgreNewt_Debugger.h" #include "OgreNewt_MaterialID.h" #include <gcroot.h> //! main namespace. /*! This is the main namespace for the OgreNewt library. all classes are included in this namespace. */ namespace MogreNewt { ref class MaterialID; ref class Body; ref class World; ref class BodyInAABBIterator; class WorldNativeInfo; public delegate void LeaveWorldEventHandler(MogreNewt::Body^ body,int threadIndex ); //! represents a physics world. /*! this class represents a NewtonWorld, which is the basic space in which physics elements can exist. It can have various Rigid Bodies, connected by joints, and other constraints. */ public ref class World { public: //! physics solver mode. /*! you can adjust the accuracy of the solver (and therefore the speed of the solver) using these, or a simple int >= 2. a value >= 2 represents the number of passes you want the engine to take when attempting to reconcile joints. */ enum class SolverModelMode { SM_EXACT = 0, /*!< the most accurate simulation. */ SM_ADAPTIVE = 1, /*!< still accurate, but faster. */ SM_2_PASS = 2, SM_3_PASS = 3, SM_4_PASS = 4, SM_5_PASS = 5, SM_6_PASS = 6, SM_7_PASS = 7, SM_8_PASS = 8, SM_9_PASS = 9, SM_10_PASS = 10, }; //! friction solver mode. /*! like the physics solver mode, these options allow you to reduce the accuracy of the friction model in exchange for speed. */ enum class FrictionModelMode { FM_EXACT = 0, /*!< exact friction model (default). */ FM_ADAPTIVE = 1 /*!< adaptive friction mode. (faster but less accurate) */ }; enum class PlatformArchitecture { PA_COMMON_DENOMINATOR = 0, PA_FLOAT_ENHANCEMENT = 1, PA_BEST_HARDWARE = 2 }; //! leave world callback. /*! this function is called when a body leaves the MogreNewt::World. you can use this to destroy bodies that have left the scene, or re-position them, reflect them, do whatever you want. callback binding to member classes is exactly the same as the various callbacks for the Body class. */ event LeaveWorldEventHandler^ LeaveWorld { void add(LeaveWorldEventHandler^ hnd); void remove(LeaveWorldEventHandler^ hnd); private: void raise( MogreNewt::Body^ body ,int threadIndex) { if (m_leaveWorld) m_leaveWorld->Invoke( body ,threadIndex); } } delegate void DisposeEventHandler(MogreNewt::World^ sender); event DisposeEventHandler^ Disposed { void add(DisposeEventHandler^ hnd); void remove(DisposeEventHandler^ hnd); private: void raise(MogreNewt::World^ sender) { if(m_dispose) m_dispose->Invoke( sender ); } } property bool IsDisposed { bool get() { return m_IsDisposed; } } Mogre::Real m_step; public: //! Standard Constructor, creates the world. World(); //! Standard Destructor, destroys the world. !World(); ~World() { this->!World(); } //! update the world by the specified time_step. /*! this function is clamped between values representing fps [60,600]. if you pass a smaller value, it is internally clamped to 60fps. likewise a value higher than 600fps is treated as 600fs. \param t_step Real value representing the time elapsed in seconds. */ void Update( Mogre::Real t_step ); //adding body enumerator for the world, TODO : move it to a specific class like ogrenewt value class BodyEnumerator : Collections::Generic::IEnumerator<Body^> { const ::NewtonWorld* _world; NewtonBody* _current; internal: BodyEnumerator(const NewtonWorld* world) : _world(world) { Reset(); } public: BodyEnumerator(World^ world); virtual bool MoveNext(); property Body^ Current { virtual Body^ get(); } property Object^ NonGenericCurrent { private: virtual Object^ get() sealed = Collections::IEnumerator::Current::get { return Current; } } virtual void Reset() { _current = (NewtonBody*)-1; } }; value class BodiesEnumerable : Collections::Generic::IEnumerable<Body^> { World^ m_World; public: BodiesEnumerable(World^ world) : m_World(world) {} private: virtual Collections::IEnumerator^ NonGenericGetEnumerator() sealed = Collections::IEnumerable::GetEnumerator { return BodyEnumerator(m_World); } public: virtual Collections::Generic::IEnumerator<Body^>^ GetEnumerator() { return BodyEnumerator(m_World); } }; property BodiesEnumerable Bodies { BodiesEnumerable get() { return BodiesEnumerable(this); } } void InvalidateCache() { NewtonInvalidateCache( m_world ); } //! retrieves a pointer to the NewtonWorld /*! in most cases you shouldn't need this... but in case you want to implement something not yet in the library, you can use this to get a pointer to the NewtonWorld object. \return pointer to NewtonWorld */ property const ::NewtonWorld* NewtonWorld { const ::NewtonWorld* get() { return m_world; } } property Mogre::Real TimeStep { virtual Mogre::Real get() { return m_step; } } //! get the default materialID object. /*! when you create a world, a default material is created, which is by default applied to all new rigid bodies. you might need this pointer when assigning material callbacks, etc. \return pointer to a MaterialID^ representing the default material. */ property MaterialID^ DefaultMaterialID { MaterialID^ get() { return m_defaultMatID; } // get pointer to default material ID object. } //! remove all bodies from the world. /*! destroys all Rigid Bodies and Joints in the world. the bodies are properly deleted, so don't try and access any pointers you have laying around! */ void DestroyAllBodies() { NewtonDestroyAllBodies( m_world ); } //! set the physics solver model /*! setting the solver model allows sacrificing accuracy and realism for speed, good for games, etc. for a more detailed description of how to use this function, see the Newton documentation. \param model int representing the physics model. you can also pass the enum values I've included. \sa SolverModelMode */ void SetSolverModel(SolverModelMode model) { NewtonSetSolverModel( m_world, (int)model ); } //! set the physics friction model /*! setting the friction model allows sacrificing accuracy and realism for speed, good for games, etc. for a more detailed description of how to use this function, see the Newton documentation. \param model int representing friction model. you can also pass the enum values I've included. \sa FrictionModelMode */ void SetFrictionModel(FrictionModelMode model) { NewtonSetFrictionModel( m_world, (int)model ); } //! specify a specific architecture to use for physics calculations. /*! Setting to a specific architecture can allow for deterministic physics calculations on systems with different cpus, which is particularly useful for multiplayer systems where deterministic physics are absolutely vital. */ void SetPlatformArchitecture( PlatformArchitecture mode ) { NewtonSetPlatformArchitecture( m_world, (int)mode ); } PlatformArchitecture GetPlatformArchitecture([Out] System::String^ %description) {char desc[265]; int mode = NewtonGetPlatformArchitecture(m_world,desc); description = gcnew System::String(desc); return (PlatformArchitecture)System::Enum::ToObject(PlatformArchitecture::typeid,mode);} //! get the number of bodies in the simulation. /*! returns the number of bodies in the simulation. */ int GetBodyCount() { return NewtonWorldGetBodyCount( m_world ); } int GetConstraintCount() { return NewtonWorldGetConstraintCount(m_world); } //! multithread settings void SetMultithreadSolverOnSingleIsland( int mode ) { NewtonSetMultiThreadSolverOnSingleIsland( m_world, mode ); } //! get multithread settings int GetMultithreadSolverOnSingleIsland( ) { return NewtonGetMultiThreadSolverOnSingleIsland( m_world ); } //! set the number of threads for the physics simulation to use. void SetThreadCount(int threads) { NewtonSetThreadsCount( m_world, threads ); } //! get the number of threads the simulation is using. int GetThreadCount() { return NewtonGetThreadsCount( m_world ); } //! notify an entrance to a critical section of code. void CriticalSectionLock() { NewtonWorldCriticalSectionLock( m_world ); } //! notify the exit of a critical section of code. void CricicalSectionUnlock() { NewtonWorldCriticalSectionUnlock( m_world ); } //! set minimum framerate void SetMinimumFrameRate(Mogre::Real frame) { NewtonSetMinimumFrameRate( m_world, frame ); } //! set the newton world size /*! setting the world size is very important for a efficient simulation. although basic collisions will work outside the world limits, other things like raycasting will not work outside the world limits. \param min minimum point of the world. \param max maximum point of the world. */ void SetWorldSize( const Mogre::Vector3 min, const Mogre::Vector3 max ); /*! \param box bos describing the size of the world. */ void SetWorldSize( Mogre::AxisAlignedBox^ box ); /*! get the world limits. */ property Mogre::AxisAlignedBox^ WorldSize { Mogre::AxisAlignedBox^ get(){return m_limits; } } //! get the Newton SDK version. property int Version { int get() { return NewtonWorldGetVersion( m_world ); } } //! updates only the collision of the world and call the callback functions if necessary, can be used for an collision only system void CollisionUpdate() { NewtonCollisionUpdate( m_world ); } property MogreNewt::BodyInAABBIterator^ BodyInAABB { MogreNewt::BodyInAABBIterator^ get() { return m_bodyInAABBIterator; } } //! get the debugger for this world /*! * the debugger needs to be initialized (Debugger::init(...) ) in order to work correctly */ property MogreNewt::Debugger^ DebuggerInstance { MogreNewt::Debugger^ get() { return m_debugger;} } //! adds an update request for the body, this means that after the next world update the function body->updateNode will be called, if the bodie needs updating void AddBodyUpdateNodeRequest( int threadIndex, MogreNewt::Body^ body ) ; protected: ::NewtonWorld* m_world; MaterialID^ m_defaultMatID; LeaveWorldEventHandler^ m_leaveWorld; cli::array<System::Collections::Generic::List<MogreNewt::Body^>^>^ m_bodyUpdateNodeRequests; MogreNewt::Debugger^ m_debugger; bool m_IsDisposed; MogreNewt::BodyInAABBIterator^ m_bodyInAABBIterator; WorldNativeInfo* m_nativeInfo; private: [UnmanagedFunctionPointer(CallingConvention::Cdecl)] delegate void NewtonLeaveWorldDelegate( const NewtonBody* body,int threadIndex ); NewtonLeaveWorldDelegate^ m_newtonLeaveWorld; DisposeEventHandler^ m_dispose; NewtonBodyLeaveWorld m_fptr_newtonLeaveWorld; void NewtonLeaveWorld( const NewtonBody* body,int threadIndex ); Mogre::AxisAlignedBox^ m_limits; }; class WorldNativeInfo { public: gcroot<MogreNewt::World^> managedWorld; WorldNativeInfo( MogreNewt::World^ world ) : managedWorld( world ) { } }; } #endif // _INCLUDE_OGRENEWT_WORLD
[ "gantz@localhost" ]
[ [ [ 1, 404 ] ] ]