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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ad9e92d03324db731e359bfc3c1c258dcff22182 | b73f27ba54ad98fa4314a79f2afbaee638cf13f0 | /projects/PacketsGrasper/selectio/contentFilter.cpp | 5052a1e7f487e7d2182a3c16e104efd4ce84773c | [] | no_license | weimingtom/httpcontentparser | 4d5ed678f2b38812e05328b01bc6b0c161690991 | 54554f163b16a7c56e8350a148b1bd29461300a0 | refs/heads/master | 2021-01-09T21:58:30.326476 | 2009-09-23T08:05:31 | 2009-09-23T08:05:31 | 48,733,304 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,563 | cpp | #include "StdAfx.h"
#include ".\contentfilter.h"
#include <com\FilterSetting_i.c>
#include <com\FilterSetting.h>
#include <com\cominit.h>
#include <utility\protocolpacket.h>
#include <utility\HTTPPacket.h>
#include <comdef.h>
#include <zlib\zlib.h>
#include <assert.h>
ContentFilter::ContentFilter(void) {
}
ContentFilter::~ContentFilter(void) {
}
bool ContentFilter::checkHTTPContent(HTTPPacket *packet) {
// 获取数据
ProtocolPacket<HTTP_PACKET_SIZE> * http_data = packet->getData();
const int data_size = http_data->getTotalSize();
char * data = new char[data_size];
// 将数据读出来
int bytes_read = http_data->read(data, data_size);
assert (data_size == bytes_read);
if (packet->getContentType() == HTTP_RESPONSE_HEADER::CONTYPE_HTML) {
return checkText(packet->getContentType(), data, data_size);
} else if (isImage(packet->getContentType())) {
return checkImage(packet->getContentType(), data, data_size);
}
return true;
}
bool ContentFilter::needCheck(const int type) {
return false;
}
// private member
bool ContentFilter::checkText(const int type, char * buf, const int len) {
return false;
}
bool ContentFilter::checkImage(const int type, char * buf, const int len) {
// 首先确定是否需要检测
return false;
}
bool ContentFilter::isImage(const int type) const {
if (type == HTTP_RESPONSE_HEADER::CONTYPE_GIF||
type == HTTP_RESPONSE_HEADER::CONTYPE_JPG||
type == HTTP_RESPONSE_HEADER::CONTYPE_PNG) {
return true;
} else {
return false;
}
} | [
"[email protected]"
] | [
[
[
1,
59
]
]
] |
7b41621b4c838f7f127288971f071fba5d9f269e | 42b849592857850523c3f2a33b8201de23f8dfb9 | /ui_config.h | 540a431e8dfde92812297243f1fc5dd23960c02a | [] | no_license | jemyzhang/M8Calendar_deprecated | 209e2875a7bcb70281ba65dec80ffc254e2446b6 | d87773a0cbb724f29248ebd3ee0344226046b4f0 | refs/heads/master | 2016-09-06T21:55:08.542592 | 2009-11-08T04:39:57 | 2009-11-08T04:39:57 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,518 | h | #ifndef _UI_BROWSECFG_H
#define _UI_BROWSECFG_H
// include the MZFC library header file
#include <mzfc_inc.h>
#include "../MzCommon/MzConfig.h"
// Main window derived from CMzWndEx
class CalendarConfig : public AppConfigIni{
public:
CalendarConfig()
:AppConfigIni(L"m8calendar.ini"){
InitIniKey();
}
protected:
void InitIniKey(){
IniJieqiOrder.InitKey(L"Config",L"JieqiOrder",0);
IniHistodayFontSize.InitKey(L"Config",L"HisFontSize",0);
IniStartupPage.InitKey(L"Config",L"StartupPage",0);
IniFirstRun.InitKey(L"Help",L"isFirstRun",1);
}
public:
MzConfig IniJieqiOrder;//1: 以节气交界日为起点 0: 以农历初一为起点
MzConfig IniHistodayFontSize; //0:小 1: 中 2: 大
MzConfig IniStartupPage; //0: Month 1: Today
MzConfig IniFirstRun;
};
class Ui_ConfigWnd : public CMzWndEx {
MZ_DECLARE_DYNAMIC(Ui_ConfigWnd);
public:
Ui_ConfigWnd();
void updateUi();
public:
UiToolbar_Text m_Toolbar;
UiCaption m_lblTitle;
UiButtonEx m_BtnStartupPage; //启动界面
UiButtonEx m_BtnJieqi; //节气排列方式
UiButtonEx m_BtnFontSize; //浏览字体大小
protected:
// Initialization of the window (dialog)
virtual BOOL OnInitDialog();
// override the MZFC command handler
virtual void OnMzCommand(WPARAM wParam, LPARAM lParam);
private:
void ShowJieqiOptionDlg();
void ShowFontSizeOptionDlg();
void ShowStartupOptionDlg();
};
#endif /*_UI_BROWSECFG_H*/ | [
"jemyzhang@0e50ebb1-d170-7b45-893d-78c2c9fc94b7"
] | [
[
[
1,
54
]
]
] |
829788909be22aad9eda852dd8fc94f92d786048 | c3efe4021165e718d23ce0f853808e10c7114216 | /LuaEdit/InheritanceBuilder.h | b8fcae360c1e294be2247142b72ebe49d0025010 | [] | no_license | lkdd/modstudio2 | 254b47ebd28a51a7d8c8682a86c576dafcc971bf | 287b4782580e37c8ac621046100dc550abd05b1d | refs/heads/master | 2021-01-10T08:14:56.230097 | 2009-03-08T19:14:16 | 2009-03-08T19:14:16 | 52,721,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,939 | h | /*
Copyright (c) 2008 Peter "Corsix" Cawley
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
// for all others, include the necessary headers (this file is usually all you
// need because it includes almost all "standard" wxWidgets headers)
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
// ----------------------------
#include <wx/treectrl.h>
#include <Rainman2.h>
#include <vector>
#include <map>
#include "CustomLuaAlloc.h"
#include "TreeCtrlMemory.h"
struct lua_State;
struct Proto;
class InheritTreeItemData : public wxTreeItemData
{
public:
InheritTreeItemData()
: pRememberedState(0)
{}
virtual ~InheritTreeItemData()
{
delete pRememberedState;
}
RainString sPath;
ITreeCtrlMemory *pRememberedState;
};
class InheritanceBuilder
{
public:
InheritanceBuilder();
~InheritanceBuilder();
void setSource(IDirectory *pDirectory) throw();
void setTreeCtrl(wxTreeCtrl *pTreeDestination) throw();
void doBuild() throw(...);
protected:
void _cleanItems();
void _recurse(IDirectory* pDirectory, RainString sPath) throw(...);
void _doFile(IFile* pFile, RainString sPath) throw(...);
unsigned long _getInheritedFile(Proto* pProto, const char*& sBuffer, size_t& iLength) throw(...);
IDirectory *m_pRootDirectory;
wxTreeCtrl *m_pTreeDestination;
LuaShortSharpAlloc *m_pAllocator;
lua_State *L;
size_t m_iCountNonexistantFiles;
struct _item_t
{
void addToTree(wxTreeCtrl *pTree, const wxTreeItemId& oParent);
RainString sPath;
std::vector<_item_t*> vChildren;
_item_t* pParent;
bool bExists;
};
std::map<unsigned long, _item_t*> m_mapAllItems;
std::vector<_item_t*> m_vRootItems;
void _addRootItemToTree(_item_t* pItem);
};
| [
"corsix@07142bc5-7355-0410-a98c-5fd2ca6e29ee"
] | [
[
[
1,
100
]
]
] |
79b9090ee8a77955613d7c17d4bc2b87f3b01b97 | d8f64a24453c6f077426ea58aaa7313aafafc75c | /utils/TextureImporter/main.cpp | c2148a85e536dfc917da608ed395ec8f70490b1e | [] | no_license | dotted/wfto | 5b98591645f3ddd72cad33736da5def09484a339 | 6eebb66384e6eb519401bdd649ae986d94bcaf27 | refs/heads/master | 2021-01-20T06:25:20.468978 | 2010-11-04T21:01:51 | 2010-11-04T21:01:51 | 32,183,921 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,842 | cpp | #include <iostream>
#include <fstream>
#include "TextureLoader.h"
using namespace std;
using namespace loaders;
#define MAX_ENT 512
#define MAX_TEX 256
int main()
{
/*
Read texture config file (*.tfc). The file has the following structure:
atlas_file_name
new_atlas_file_name
atlas_width
atlas_height
subtile_size(n^2)
image_0_file_name atlas_subtile_index texture_subtile_index texture_index
image_1_file_name atlas_subtile_index texture_subtile_index texture_index
.
.
.
image_n_file_name atlas_subtile_index texture_subtile_index
*/
ifstream listFile;
listFile.open("data/import.tfc");
CImage cimg;
CImage atlasTex;
CImage otherTex[MAX_TEX];
int atlas_width = 0,
atlas_height = 0,
subtile_size = 0,
count = -1,
l_texs = 0;
char atlas_name[MAX_ENT],
new_atlas_name[MAX_PATH];
int atlas_index[MAX_ENT],
texture_index[MAX_ENT],
used_textures[MAX_ENT];
bool loaded[MAX_ENT];
for (int i=0; i<MAX_ENT; i++)
{
used_textures[i] = -1;
loaded[i] = false;
}
// read textures
while (listFile.good())
{
char line[MAX_ENT];
listFile.getline(line,MAX_ENT,'\n');
if (count==-1)
{
strcpy(atlas_name,line);
HRESULT atl = atlasTex.Load(line);
listFile.getline(line,MAX_PATH,'\n');
strcpy(new_atlas_name,line);
listFile.getline(line,MAX_ENT,'\n');
atlas_width = atoi(line);
listFile.getline(line,MAX_ENT,'\n');
atlas_height = atoi(line);
listFile.getline(line,MAX_ENT,'\n');
subtile_size = atoi(line);
}
else
{
char name[64];
sscanf(line,"%s %d %d %d",&name,&atlas_index[count],&texture_index[count],&used_textures[count]);
if (!loaded[used_textures[count]])
{
loaded[l_texs] = true;
otherTex[l_texs++].Load(name);
}
}
count++;
}
// now we have all data, let's create the atlas
for (int i=0; i<count; i++)
{
// calc x,y of atlas
int a_col, a_x, a_y;
a_col = atlasTex.GetWidth()/subtile_size;
a_x = (atlas_index[i] % a_col)*subtile_size;
a_y = (atlas_index[i] / a_col)*subtile_size;
// calc x,y of texture
int t_col, t_x, t_y;
t_col = otherTex[used_textures[i]].GetWidth()/subtile_size;
t_x = (texture_index[i] % t_col)*subtile_size;
t_y = (texture_index[i] / t_col)*subtile_size;
otherTex[used_textures[i]].BitBlt(atlasTex.GetDC(),a_x,a_y,subtile_size,subtile_size,t_x,t_y);
atlasTex.ReleaseDC();
/*for (int y=0; y<subtile_size; y++)
{
for (int x=0; x<subtile_size; x++)
{
atlasTex.SetPixel(a_x+x,a_y+y,otherTex[used_textures[i]].GetPixel(t_x+x,t_y+y));
}
}*/
cout << "Finished " << i+1 << " of " << count << endl;
}
cout << "Saving atlas..." << endl;
atlasTex.Save(new_atlas_name);
//atlasTex.ReleaseDC();
return 0;
} | [
"[email protected]"
] | [
[
[
1,
129
]
]
] |
c87bb86baed2ac403bb861604ce5a5e4e2ea06e3 | 5b2b0e9131a27043573107bf42d8ca7641ba511a | /PropsServer.h | 1563479e3e03f2bb1b3f7ccfca1e4efaa669402d | [
"MIT"
] | permissive | acastroy/pumpkin | 0b1932e9c1fe7672a707cc04f092d98cfcecbd4e | 6e7e413ca364d79673e523c09767c18e7cff1bec | refs/heads/master | 2023-03-15T20:43:59.544227 | 2011-04-27T16:24:42 | 2011-04-27T16:24:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,034 | h | // PropsServer.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CPropsServer dialog
class CPropsServer : public CPropertyPage
{
DECLARE_DYNCREATE(CPropsServer)
// Construction
public:
UINT m_PromptTimeOut;
CPropsServer();
~CPropsServer();
// Dialog Data
//{{AFX_DATA(CPropsServer)
enum { IDD = IDD_PROPS_SERVER };
CButton m_LogBrowseCtl;
CButton m_BrowseCtl;
CSliderCtrl m_PromptTimeoutCtl;
int m_RRQMode;
CString m_TFTPRoot;
BOOL m_TFTPSubdirs;
int m_WRQMode;
CString m_LogFile;
//}}AFX_DATA
// Overrides
// ClassWizard generate virtual function overrides
//{{AFX_VIRTUAL(CPropsServer)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CPropsServer)
virtual BOOL OnInitDialog();
afx_msg void OnBrowse();
afx_msg void OnLogfileBrowse();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]"
] | [
[
[
1,
48
]
]
] |
a0310bb41c72b02d3ae8a917e74397fd945cee6c | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/inc/gfx/ns3tcgltexture.h | 154ba76189b35b2627a0829b76c6a52c8754fe0c | [] | 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 | 3,126 | h | #ifndef N_S3TCGLTEXTURE_H
#define N_S3TCGLTEXTURE_H
#include "gfx/glext.h"
#include "gfx/ns3tctexture.h"
class nS3TCGlTexture : public nS3TCTexture {
public:
nS3TCGlTexture() : nS3TCTexture(), GLformat(0) {}
#ifdef USE_NFILE
bool Load(nFile* file) {
file->Seek(0, nFile::END);
unsigned long fsize = file->Tell();
file->Seek(0, nFile::START);
/* verify the type of file */
file->Read(filecode, 4);
if (strncmp(filecode, "DDS ", 4) != 0) {
file->Close();
return false;
}
/* get the surface desc */
file->Read(&s3tc_desc, sizeof(s3tc_desc));
width = s3tc_desc.width;
height = s3tc_desc.height;
//genericImage->components = (ddsd.ddpfPixelFormat.dwFourCC == FOURCC_DXT1) ? 3 : 4;
numMipmaps = s3tc_desc.mipMapCount;
format = GetS3TCFormatIndex(s3tc_desc.pfPixelFormat.fourCC);
switch(format) {
case S3TC1:
GLformat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
break;
case S3TC3:
GLformat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
break;
case S3TC5:
GLformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
break;
default:
GLformat = 0;
break;
}
if (GLformat) {
/* how big is it going to be including all mipmaps? */
//bufsize = s3tc_desc.mipMapCount > 1 ? s3tc_desc.linearSize * 2 : s3tc_desc.linearSize;
bufsize = fsize - sizeof(s3tc_desc) - 4;
pixels = new unsigned char[bufsize];
file->Read(pixels, bufsize);
}
blockSize = (GLformat == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;
return GLformat != 0;
}
#else
bool Load(const char* fileName) {
FILE *fp;
/* try to open the file */
fp = fopen(fileName, "rb");
if (!fp)
return false;
fseek(fp, 0L, SEEK_END);
unsigned long fsize = ftell(fp);
fseek(fp, 0L, SEEK_SET);
/* verify the type of file */
fread(filecode, 1, 4, fp);
if (strncmp(filecode, "DDS ", 4) != 0) {
fclose(fp);
return false;
}
/* get the surface desc */
fread(&s3tc_desc, sizeof(s3tc_desc), 1, fp);
width = s3tc_desc.width;
height = s3tc_desc.height;
//genericImage->components = (ddsd.ddpfPixelFormat.dwFourCC == FOURCC_DXT1) ? 3 : 4;
numMipmaps = s3tc_desc.mipMapCount;
format = GetS3TCFormatIndex(s3tc_desc.pfPixelFormat.fourCC);
switch(format) {
case S3TC1:
GLformat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
break;
case S3TC3:
GLformat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
break;
case S3TC5:
GLformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
break;
default:
GLformat = 0;
break;
}
if (GLformat) {
/* how big is it going to be including all mipmaps? */
//bufsize = s3tc_desc.mipMapCount > 1 ? s3tc_desc.linearSize * 2 : s3tc_desc.linearSize;
bufsize = fsize - sizeof(s3tc_desc) - 4;
pixels = new unsigned char[bufsize];
fread(pixels, 1, bufsize, fp);
}
/* close the file pointer */
fclose(fp);
blockSize = (GLformat == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;
return GLformat != 0;
}
#endif
long GLformat;
};
#endif | [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
] | [
[
[
1,
114
]
]
] |
5ea3e00d657e7f0dae5ef10481a066205047e399 | a21de044e9c5b4ed3777817cabb728c62f7315fc | /ocean_domination/ShaderLoader.cpp | c7b12ca9db651f3462067dd0465e712beb5bf89a | [] | no_license | alyshamsy/oceandomination | 9470889b9f051086b047f7dbc7e6de4f289d2da9 | 3580c399537045c8ad0817bc7a9d81d24c85a925 | refs/heads/master | 2020-03-30T05:30:08.981859 | 2011-05-12T15:47:06 | 2011-05-12T15:47:06 | 32,115,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,688 | cpp | #include "ShaderLoader.h"
#include <fstream>
#include <iostream>
using namespace std;
ShaderLoader::ShaderLoader() {
}
ShaderLoader::~ShaderLoader() {
}
int ShaderLoader::LoadShader(string& vertex_shader_file, string& fragment_shader_file, GLint current_program) {
GLint status = 0;
program_object = current_program;
if(vertex_shader_file.empty() == false) {
char* vertex_shader_source = NULL;
vertex_shader_source = ReadShaderFile(vertex_shader_file);
if(vertex_shader_source == NULL) {
cout << "Failed to read the vertex shader" << endl;
status = 1;
return status;
}
v_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(v_shader, 1, (const GLchar**) &vertex_shader_source, NULL);
delete vertex_shader_source;
glCompileShader(v_shader);
glGetShaderiv(v_shader, GL_COMPILE_STATUS, &status);
if(status != GL_TRUE) {
cout << "Failed to compile the vertex shader" << endl;
PrintInfoLog(1);
return status;
}
glAttachShader(program_object, v_shader);
}
if(fragment_shader_file.empty() == false) {
char* fragment_shader_source = NULL;
fragment_shader_source = ReadShaderFile(fragment_shader_file);
if(fragment_shader_source == NULL) {
cout << "Failed to read the fragment shader" << endl;
status = 1;
return status;
}
f_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(f_shader, 1, (const GLchar**) &fragment_shader_source, NULL);
delete fragment_shader_source;
glCompileShader(f_shader);
glGetShaderiv(f_shader, GL_COMPILE_STATUS, &status);
if(status != GL_TRUE) {
cout << "Failed to compile the fragment shader" << endl;
PrintInfoLog(2);
return status;
}
glAttachShader(program_object, f_shader);
}
glLinkProgram(program_object);
glGetProgramiv(program_object, GL_LINK_STATUS, &status);
if(status != GL_TRUE) {
cout << "Failed to link the shader program object" << endl;
PrintInfoLog(3);
return status;
}
glUseProgram(program_object);
return status;
}
void ShaderLoader::DetachShader(GLint program) {
glDetachShader(program, v_shader);
glUseProgram(0);
}
char* ShaderLoader::ReadShaderFile(string& shader_file_name) {
char* shader_contents = NULL;
long size = 0;
FILE* shader_file;
shader_file = fopen(shader_file_name.c_str(), "rt");
if (shader_file != NULL) {
fseek(shader_file, 0, SEEK_END);
size = ftell(shader_file);
rewind(shader_file);
shader_contents = new char[size];
size = fread(shader_contents, sizeof(char), size, shader_file);
shader_contents[size] = '\0';
fclose(shader_file);
}
return shader_contents;
}
void ShaderLoader::PrintInfoLog(int object) {
_asm{ int 0x3 };
int log_length = 0;
int characters_written = 0;
char* log_info;
if(object == 1) {
glGetShaderiv(v_shader, GL_INFO_LOG_LENGTH, &log_length);
if(log_length > 0) {
log_info = new char[log_length];
glGetShaderInfoLog(v_shader, log_length, &characters_written, log_info);
cout << log_info << endl;
}
} else if(object == 2) {
glGetShaderiv(f_shader, GL_INFO_LOG_LENGTH, &log_length);
if(log_length > 0) {
log_info = new char[log_length];
glGetShaderInfoLog(f_shader, log_length, &characters_written, log_info);
cout << log_info << endl;
}
} else {
glGetProgramiv(program_object, GL_INFO_LOG_LENGTH, &log_length);
if(log_length > 0) {
log_info = new char[log_length];
glGetProgramInfoLog(program_object, log_length, &characters_written, log_info);
cout << log_info << endl;
}
}
delete log_info;
log_info = NULL;
} | [
"aly.shamsy@b23e3eda-3cbb-b783-0003-8fc1c118d970"
] | [
[
[
1,
151
]
]
] |
c033eba03539f45fdcb72410bd613ab0ccb5deda | 3128346a72b842c6dd94f2b854170d5daeeedc6f | /src/CoreInput.cpp | 6030936a1f369604e05b6e012b22d1430db5b699 | [] | no_license | Valrandir/Core512 | 42c3ed02f3f5455a9e0d722c014c80bb2bae17ab | af6b45aa2eded3f32964339ffebdab3491b08561 | refs/heads/master | 2021-01-22T04:57:15.719013 | 2011-11-11T05:16:30 | 2011-11-11T05:16:30 | 2,607,600 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 704 | cpp | #include "CoreSystem.h"
#include "CoreInput.h"
#define Key(KeyCode)CoreSys.KeyState(KeyCode)
CoreInputEnum CoreInput::Command()
{
if(Key(HGEK_SPACE))
return CoreInput_ShipReset;
if(Key(HGEK_T))
return CoreInput_Background_Toggle;
if(Key(HGEK_X))
return CoreInput_Explode;
return CoreInput_None;
}
void CoreInput::Direction(int& ForceDirection, int& RotationDirection)
{
ForceDirection = 0;
if(Key(HGEK_UP) || Key(HGEK_LBUTTON))
++ForceDirection;
if(Key(HGEK_DOWN) || Key(HGEK_RBUTTON))
--ForceDirection;
RotationDirection = 0;
if(Key(HGEK_LEFT) || Key(HGEK_D))
--RotationDirection;
if(Key(HGEK_RIGHT) || Key(HGEK_F))
++RotationDirection;
}
| [
"[email protected]"
] | [
[
[
1,
33
]
]
] |
fde28b0c907d3c89995190c03b02c76e5bee5d71 | 02c2e62bcb9a54738bfbd95693978b8709e88fdb | /opencv/cvconvolve.cpp | 82f5aeef8a756cc77e2c353f93c3a8238566403b | [] | no_license | ThadeuFerreira/sift-coprojeto | 7ab823926e135f0ac388ae267c40e7069e39553a | bba43ef6fa37561621eb5f2126e5aa7d1c3f7024 | refs/heads/master | 2021-01-10T15:15:21.698124 | 2009-05-08T17:38:51 | 2009-05-08T17:38:51 | 45,042,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,960 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "_cv.h"
#include <limits.h>
/////////////////////// common functions for working with IPP filters ////////////////////
CvMat* icvIPPFilterInit( const CvMat* src, int stripe_size, CvSize ksize )
{
CvSize temp_size;
int pix_size = CV_ELEM_SIZE(src->type);
temp_size.width = cvAlign(src->cols + ksize.width - 1,8/CV_ELEM_SIZE(src->type & CV_MAT_DEPTH_MASK));
//temp_size.width = src->cols + ksize.width - 1;
temp_size.height = (stripe_size*2 + temp_size.width*pix_size) / (temp_size.width*pix_size*2);
temp_size.height = MAX( temp_size.height, ksize.height );
temp_size.height = MIN( temp_size.height, src->rows + ksize.height - 1 );
return cvCreateMat( temp_size.height, temp_size.width, src->type );
}
int icvIPPFilterNextStripe( const CvMat* src, CvMat* temp, int y,
CvSize ksize, CvPoint anchor )
{
int pix_size = CV_ELEM_SIZE(src->type);
int src_step = src->step ? src->step : CV_STUB_STEP;
int temp_step = temp->step ? temp->step : CV_STUB_STEP;
int i, dy, src_y1 = 0, src_y2;
int temp_rows;
uchar* temp_ptr = temp->data.ptr;
CvSize stripe_size, temp_size;
CvCopyNonConstBorderFunc copy_border_func =
icvGetCopyNonConstBorderFunc( pix_size, IPL_BORDER_REPLICATE );
dy = MIN( temp->rows - ksize.height + 1, src->rows - y );
if( y > 0 )
{
int temp_ready = ksize.height - 1;
for( i = 0; i < temp_ready; i++ )
memcpy( temp_ptr + temp_step*i, temp_ptr +
temp_step*(temp->rows - temp_ready + i), temp_step );
temp_ptr += temp_ready*temp_step;
temp_rows = dy;
src_y1 = y + temp_ready - anchor.y;
src_y2 = src_y1 + dy;
if( src_y1 >= src->rows )
{
src_y1 = src->rows - 1;
src_y2 = src->rows;
}
}
else
{
temp_rows = dy + ksize.height - 1;
src_y2 = temp_rows - anchor.y;
}
src_y2 = MIN( src_y2, src->rows );
stripe_size = cvSize(src->cols, src_y2 - src_y1);
temp_size = cvSize(temp->cols, temp_rows);
copy_border_func( src->data.ptr + src_y1*src_step, src_step,
stripe_size, temp_ptr, temp_step, temp_size,
(y == 0 ? anchor.y : 0), anchor.x );
return dy;
}
/////////////////////////////// IPP separable filter functions ///////////////////////////
icvFilterRow_8u_C1R_t icvFilterRow_8u_C1R_p = 0;
icvFilterRow_8u_C3R_t icvFilterRow_8u_C3R_p = 0;
icvFilterRow_8u_C4R_t icvFilterRow_8u_C4R_p = 0;
icvFilterRow_16s_C1R_t icvFilterRow_16s_C1R_p = 0;
icvFilterRow_16s_C3R_t icvFilterRow_16s_C3R_p = 0;
icvFilterRow_16s_C4R_t icvFilterRow_16s_C4R_p = 0;
icvFilterRow_32f_C1R_t icvFilterRow_32f_C1R_p = 0;
icvFilterRow_32f_C3R_t icvFilterRow_32f_C3R_p = 0;
icvFilterRow_32f_C4R_t icvFilterRow_32f_C4R_p = 0;
icvFilterColumn_8u_C1R_t icvFilterColumn_8u_C1R_p = 0;
icvFilterColumn_8u_C3R_t icvFilterColumn_8u_C3R_p = 0;
icvFilterColumn_8u_C4R_t icvFilterColumn_8u_C4R_p = 0;
icvFilterColumn_16s_C1R_t icvFilterColumn_16s_C1R_p = 0;
icvFilterColumn_16s_C3R_t icvFilterColumn_16s_C3R_p = 0;
icvFilterColumn_16s_C4R_t icvFilterColumn_16s_C4R_p = 0;
icvFilterColumn_32f_C1R_t icvFilterColumn_32f_C1R_p = 0;
icvFilterColumn_32f_C3R_t icvFilterColumn_32f_C3R_p = 0;
icvFilterColumn_32f_C4R_t icvFilterColumn_32f_C4R_p = 0;
//////////////////////////////////////////////////////////////////////////////////////////
typedef CvStatus (CV_STDCALL * CvIPPSepFilterFunc)
( const void* src, int srcstep, void* dst, int dststep,
CvSize size, const float* kernel, int ksize, int anchor );
int icvIPPSepFilter( const CvMat* src, CvMat* dst, const CvMat* kernelX,
const CvMat* kernelY, CvPoint anchor )
{
int result = 0;
CvMat* top_bottom = 0;
CvMat* vout_hin = 0;
CvMat* dst_buf = 0;
CV_FUNCNAME( "icvIPPSepFilter" );
__BEGIN__;
CvSize ksize;
CvPoint el_anchor;
CvSize size;
int type, depth, pix_size;
int i, x, y, dy = 0, prev_dy = 0, max_dy;
CvMat vout;
CvCopyNonConstBorderFunc copy_border_func;
CvIPPSepFilterFunc x_func = 0, y_func = 0;
int src_step, top_bottom_step;
float *kx, *ky;
int align, stripe_size;
if( !icvFilterRow_8u_C1R_p )
EXIT;
if( !CV_ARE_TYPES_EQ( src, dst ) || !CV_ARE_SIZES_EQ( src, dst ) ||
!CV_IS_MAT_CONT(kernelX->type & kernelY->type) ||
CV_MAT_TYPE(kernelX->type) != CV_32FC1 ||
CV_MAT_TYPE(kernelY->type) != CV_32FC1 ||
kernelX->cols != 1 && kernelX->rows != 1 ||
kernelY->cols != 1 && kernelY->rows != 1 ||
(unsigned)anchor.x >= (unsigned)(kernelX->cols + kernelX->rows - 1) ||
(unsigned)anchor.y >= (unsigned)(kernelY->cols + kernelY->rows - 1) )
CV_ERROR( CV_StsError, "Internal Error: incorrect parameters" );
ksize.width = kernelX->cols + kernelX->rows - 1;
ksize.height = kernelY->cols + kernelY->rows - 1;
/*if( ksize.width <= 5 && ksize.height <= 5 )
{
float* ker = (float*)cvStackAlloc( ksize.width*ksize.height*sizeof(ker[0]));
CvMat kernel = cvMat( ksize.height, ksize.width, CV_32F, ker );
for( y = 0, i = 0; y < ksize.height; y++ )
for( x = 0; x < ksize.width; x++, i++ )
ker[i] = kernelY->data.fl[y]*kernelX->data.fl[x];
CV_CALL( cvFilter2D( src, dst, &kernel, anchor ));
EXIT;
}*/
type = CV_MAT_TYPE(src->type);
depth = CV_MAT_DEPTH(type);
pix_size = CV_ELEM_SIZE(type);
if( type == CV_8UC1 )
x_func = icvFilterRow_8u_C1R_p, y_func = icvFilterColumn_8u_C1R_p;
else if( type == CV_8UC3 )
x_func = icvFilterRow_8u_C3R_p, y_func = icvFilterColumn_8u_C3R_p;
else if( type == CV_8UC4 )
x_func = icvFilterRow_8u_C4R_p, y_func = icvFilterColumn_8u_C4R_p;
else if( type == CV_16SC1 )
x_func = icvFilterRow_16s_C1R_p, y_func = icvFilterColumn_16s_C1R_p;
else if( type == CV_16SC3 )
x_func = icvFilterRow_16s_C3R_p, y_func = icvFilterColumn_16s_C3R_p;
else if( type == CV_16SC4 )
x_func = icvFilterRow_16s_C4R_p, y_func = icvFilterColumn_16s_C4R_p;
else if( type == CV_32FC1 )
x_func = icvFilterRow_32f_C1R_p, y_func = icvFilterColumn_32f_C1R_p;
else if( type == CV_32FC3 )
x_func = icvFilterRow_32f_C3R_p, y_func = icvFilterColumn_32f_C3R_p;
else if( type == CV_32FC4 )
x_func = icvFilterRow_32f_C4R_p, y_func = icvFilterColumn_32f_C4R_p;
else
EXIT;
size = cvGetMatSize(src);
stripe_size = src->data.ptr == dst->data.ptr ? 1 << 15 : 1 << 16;
max_dy = MAX( ksize.height - 1, stripe_size/(size.width + ksize.width - 1));
max_dy = MIN( max_dy, size.height + ksize.height - 1 );
align = 8/CV_ELEM_SIZE(depth);
CV_CALL( top_bottom = cvCreateMat( ksize.height*2, cvAlign(size.width,align), type ));
CV_CALL( vout_hin = cvCreateMat( max_dy + ksize.height,
cvAlign(size.width + ksize.width - 1, align), type ));
if( src->data.ptr == dst->data.ptr && size.height )
CV_CALL( dst_buf = cvCreateMat( max_dy + ksize.height,
cvAlign(size.width, align), type ));
kx = (float*)cvStackAlloc( ksize.width*sizeof(kx[0]) );
ky = (float*)cvStackAlloc( ksize.height*sizeof(ky[0]) );
// mirror the kernels
for( i = 0; i < ksize.width; i++ )
kx[i] = kernelX->data.fl[ksize.width - i - 1];
for( i = 0; i < ksize.height; i++ )
ky[i] = kernelY->data.fl[ksize.height - i - 1];
el_anchor = cvPoint( ksize.width - anchor.x - 1, ksize.height - anchor.y - 1 );
cvGetCols( vout_hin, &vout, anchor.x, anchor.x + size.width );
copy_border_func = icvGetCopyNonConstBorderFunc( pix_size, IPL_BORDER_REPLICATE );
src_step = src->step ? src->step : CV_STUB_STEP;
top_bottom_step = top_bottom->step ? top_bottom->step : CV_STUB_STEP;
vout.step = vout.step ? vout.step : CV_STUB_STEP;
for( y = 0; y < size.height; y += dy )
{
const CvMat *vin = src, *hout = dst;
int src_y = y, dst_y = y;
dy = MIN( max_dy, size.height - (ksize.height - anchor.y - 1) - y );
if( y < anchor.y || dy < anchor.y )
{
int ay = anchor.y;
CvSize src_stripe_size = size;
if( y < anchor.y )
{
src_y = 0;
dy = MIN( anchor.y, size.height );
src_stripe_size.height = MIN( dy + ksize.height - anchor.y - 1, size.height );
}
else
{
src_y = MAX( y - anchor.y, 0 );
dy = size.height - y;
src_stripe_size.height = MIN( dy + anchor.y, size.height );
ay = MAX( anchor.y - y, 0 );
}
copy_border_func( src->data.ptr + src_y*src_step, src_step, src_stripe_size,
top_bottom->data.ptr, top_bottom_step,
cvSize(size.width, dy + ksize.height - 1),
ay, 0 );
vin = top_bottom;
src_y = anchor.y;
}
// do vertical convolution
IPPI_CALL( y_func( vin->data.ptr + src_y*vin->step, vin->step ? vin->step : CV_STUB_STEP,
vout.data.ptr, vout.step, cvSize(size.width, dy),
ky, ksize.height, el_anchor.y ));
// now it's time to copy the previously processed stripe to the input/output image
if( src->data.ptr == dst->data.ptr )
{
for( i = 0; i < prev_dy; i++ )
memcpy( dst->data.ptr + (y - prev_dy + i)*dst->step,
dst_buf->data.ptr + i*dst_buf->step, size.width*pix_size );
if( y + dy < size.height )
{
hout = dst_buf;
dst_y = 0;
}
}
// create a border for every line by replicating the left-most/right-most elements
for( i = 0; i < dy; i++ )
{
uchar* ptr = vout.data.ptr + i*vout.step;
for( x = -1; x >= -anchor.x*pix_size; x-- )
ptr[x] = ptr[x + pix_size];
for( x = size.width*pix_size; x < (size.width+ksize.width-anchor.x-1)*pix_size; x++ )
ptr[x] = ptr[x - pix_size];
}
// do horizontal convolution
IPPI_CALL( x_func( vout.data.ptr, vout.step, hout->data.ptr + dst_y*hout->step,
hout->step ? hout->step : CV_STUB_STEP,
cvSize(size.width, dy), kx, ksize.width, el_anchor.x ));
prev_dy = dy;
}
result = 1;
__END__;
cvReleaseMat( &vout_hin );
cvReleaseMat( &dst_buf );
cvReleaseMat( &top_bottom );
return result;
}
#define ICV_DEF_FILTER_FUNC( flavor, arrtype, worktype, \
load_macro, cast_macro1, cast_macro2 ) \
static CvStatus CV_STDCALL \
icvFilter_##flavor##_CnR( arrtype* src, int srcstep, \
arrtype* dst, int dststep, CvSize* roi, \
CvFilterState* state, int stage ) \
{ \
int width = roi->width; \
int src_height = roi->height; \
int dst_height = src_height; \
int x, y = 0, i; \
\
int ker_x = state->ker_x; \
int ker_y = state->ker_y; \
int ker_width = state->ker_width; \
int ker_height = state->ker_height; \
const float *ker_data = (const float*)state->ker0; \
\
int crows = state->crows; \
arrtype **rows = (arrtype**) (state->rows); \
arrtype* tbuf = (arrtype*)(state->tbuf); \
\
int channels = state->channels; \
int ker_x_n = ker_x * channels; \
int ker_width_n = ker_width * channels; \
int width_n = width * channels; \
\
int starting_flag = 0; \
int width_rest = width_n & (CV_MORPH_ALIGN - 1); \
arrtype **ker_ptr, **ker = (arrtype**)cvStackAlloc( \
ker_width*ker_height*sizeof(ker[0]) ); \
float* ker_coeffs0 = (float*)cvStackAlloc( \
ker_width*ker_height*sizeof(ker_coeffs0[0]) ); \
float* ker_coeffs = ker_coeffs0; \
\
srcstep /= sizeof(src[0]); \
dststep /= sizeof(dst[0]); \
\
for( i = 0; i < ker_height; i++ ) \
for( x = 0; x < ker_width; x++ ) \
{ \
int t = ((int*)ker_data)[i*ker_width + x]; \
if( t ) \
{ \
*(int*)ker_coeffs = t; \
ker_coeffs++; \
} \
} \
if( stage == CV_START + CV_END ) \
stage = CV_WHOLE; \
\
/* initialize cyclic buffer when starting */ \
if( stage == CV_WHOLE || stage == CV_START ) \
{ \
for( i = 0; i < ker_height; i++ ) \
{ \
rows[i] = (arrtype*)(state->buffer + state->buffer_step * i); \
} \
crows = ker_y; \
if( stage != CV_WHOLE ) \
dst_height -= ker_height - ker_y - 1; \
starting_flag = 1; \
} \
\
if( stage == CV_END ) \
dst_height += ker_height - ker_y - 1; \
\
do \
{ \
arrtype *tsrc, *tdst; \
int need_copy = 0; \
\
/* fill cyclic buffer */ \
for( ; crows < ker_height; crows++ ) \
{ \
tsrc = src; \
tdst = rows[crows]; \
\
if( src_height-- <= 0 ) \
{ \
if( stage != CV_WHOLE && stage != CV_END ) \
break; \
/* duplicate last row */ \
tsrc = rows[crows - 1]; \
CV_COPY( tdst, tsrc, width_n + ker_width_n, x ); \
continue; \
} \
\
src += srcstep; \
\
CV_COPY( tdst + ker_x_n, tsrc, width_n, x ); \
\
/* make replication borders */ \
for( i = ker_x_n - 1; i >= 0; i-- ) \
tdst[i] = tdst[i + channels]; \
for( i = width_n + ker_x_n; i < width_n + ker_width_n; i++ ) \
tdst[i] = tdst[i - channels]; \
} \
\
if( starting_flag ) \
{ \
starting_flag = 0; \
tsrc = rows[ker_y]; \
\
for( i = 0; i < ker_y; i++ ) \
{ \
tdst = rows[i]; \
CV_COPY( tdst, tsrc, width_n + ker_width_n, x ); \
} \
} \
\
/* do convolution */ \
if( crows < ker_height ) \
break; \
\
tdst = dst; \
if( width_rest ) \
{ \
need_copy = width_n < CV_MORPH_ALIGN || y == dst_height - 1; \
\
if( need_copy ) \
tdst = tbuf; \
else \
CV_COPY( tbuf + width_n, dst + width_n, CV_MORPH_ALIGN, x );\
} \
\
ker_ptr = ker; \
for( i = 0; i < ker_height; i++ ) \
for( x = 0; x < ker_width; x++ ) \
if( ((int*)ker_data)[i*ker_width + x] ) \
*ker_ptr++ = rows[i] + x*channels; \
\
if( channels == 3 ) \
{ \
for( x = 0; x < width_n; x += 3 ) \
{ \
double sum0 = 0, sum1 = 0, sum2 = 0; \
worktype t0, t1, t2; \
arrtype** kp = ker; \
ker_coeffs = ker_coeffs0; \
while( kp != ker_ptr ) \
{ \
arrtype* tp = *kp++; \
double f = *ker_coeffs++; \
sum0 += load_macro(tp[x])*f; \
sum1 += load_macro(tp[x+1])*f; \
sum2 += load_macro(tp[x+2])*f; \
} \
t0 = cast_macro1(sum0); \
t1 = cast_macro1(sum1); \
t2 = cast_macro1(sum2); \
tdst[x] = cast_macro2(t0); \
tdst[x+1] = cast_macro2(t1); \
tdst[x+2] = cast_macro2(t2); \
} \
} \
else \
{ \
for( x = 0; x < width_n; x += 4 ) \
{ \
double sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0; \
worktype t0, t1; \
arrtype** kp = ker; \
ker_coeffs = ker_coeffs0; \
while( kp != ker_ptr ) \
{ \
arrtype* tp = *kp++; \
double f = *ker_coeffs++; \
sum0 += load_macro(tp[x])*f; \
sum1 += load_macro(tp[x+1])*f; \
sum2 += load_macro(tp[x+2])*f; \
sum3 += load_macro(tp[x+3])*f; \
} \
t0 = cast_macro1(sum0); \
t1 = cast_macro1(sum1); \
tdst[x] = cast_macro2(t0); \
tdst[x+1] = cast_macro2(t1); \
t0 = cast_macro1(sum2); \
t1 = cast_macro1(sum3); \
tdst[x+2] = cast_macro2(t0); \
tdst[x+3] = cast_macro2(t1); \
} \
} \
\
if( width_rest ) \
{ \
if( need_copy ) \
CV_COPY( dst, tbuf, width_n, x ); \
else \
CV_COPY( dst + width_n, tbuf + width_n, CV_MORPH_ALIGN, x );\
} \
\
/* rotate buffer */ \
{ \
arrtype *t = rows[0]; \
\
CV_COPY( rows, rows + 1, ker_height - 1, i ); \
rows[i] = t; \
crows--; \
dst += dststep; \
} \
} \
while( ++y < dst_height ); \
\
roi->height = y; \
state->crows = crows; \
\
return CV_OK; \
}
ICV_DEF_FILTER_FUNC( 8u, uchar, int, CV_8TO32F, cvRound, CV_CAST_8U )
ICV_DEF_FILTER_FUNC( 16u, ushort, int, CV_NOP, cvRound, CV_CAST_16U )
ICV_DEF_FILTER_FUNC( 32f, float, double, CV_NOP, CV_NOP, CV_CAST_32F )
static void icvInitFilterTab( CvFuncTable* tab )
{
tab->fn_2d[CV_8U] = (void*)icvFilter_8u_CnR;
tab->fn_2d[CV_16U] = (void*)icvFilter_16u_CnR;
tab->fn_2d[CV_32F] = (void*)icvFilter_32f_CnR;
}
//////////////////////////////// IPP generic filter functions ////////////////////////////
icvFilter_8u_C1R_t icvFilter_8u_C1R_p = 0;
icvFilter_8u_C3R_t icvFilter_8u_C3R_p = 0;
icvFilter_8u_C4R_t icvFilter_8u_C4R_p = 0;
icvFilter_16s_C1R_t icvFilter_16s_C1R_p = 0;
icvFilter_16s_C3R_t icvFilter_16s_C3R_p = 0;
icvFilter_16s_C4R_t icvFilter_16s_C4R_p = 0;
icvFilter_32f_C1R_t icvFilter_32f_C1R_p = 0;
icvFilter_32f_C3R_t icvFilter_32f_C3R_p = 0;
icvFilter_32f_C4R_t icvFilter_32f_C4R_p = 0;
//////////////////////////////////////////////////////////////////////////////////////////
typedef CvStatus (CV_STDCALL * CvFilterIPPFunc)
( const void* src, int srcstep, void* dst, int dststep, CvSize size,
const float* kernel, CvSize ksize, CvPoint anchor );
CV_IMPL void
cvFilter2D( const CvArr* _src, CvArr* _dst, const CvMat* _kernel, CvPoint anchor )
{
// below that approximate size OpenCV is faster
const int ipp_lower_limit = 20;
static CvFuncTable filter_tab;
static int inittab = 0;
CvFilterState *state = 0;
float* kernel_data = 0;
int local_alloc = 1;
CvMat* temp = 0;
CV_FUNCNAME( "cvFilter2D" );
__BEGIN__;
CvFilterFunc func = 0;
int coi1 = 0, coi2 = 0;
CvMat srcstub, *src = (CvMat*)_src;
CvMat dststub, *dst = (CvMat*)_dst;
CvSize size;
int type, depth;
int src_step, dst_step;
CvMat kernel_hdr;
const CvMat* kernel = _kernel;
if( !inittab )
{
icvInitFilterTab( &filter_tab );
inittab = 1;
}
CV_CALL( src = cvGetMat( src, &srcstub, &coi1 ));
CV_CALL( dst = cvGetMat( dst, &dststub, &coi2 ));
if( coi1 != 0 || coi2 != 0 )
CV_ERROR( CV_BadCOI, "" );
type = CV_MAT_TYPE( src->type );
if( !CV_ARE_SIZES_EQ( src, dst ))
CV_ERROR( CV_StsUnmatchedSizes, "" );
if( !CV_ARE_TYPES_EQ( src, dst ))
CV_ERROR( CV_StsUnmatchedFormats, "" );
if( !CV_IS_MAT(kernel) ||
(CV_MAT_TYPE(kernel->type) != CV_32F &&
CV_MAT_TYPE(kernel->type) != CV_64F ))
CV_ERROR( CV_StsBadArg, "kernel must be single-channel floating-point matrix" );
if( anchor.x == -1 && anchor.y == -1 )
anchor = cvPoint(kernel->cols/2,kernel->rows/2);
if( (unsigned)anchor.x >= (unsigned)kernel->cols ||
(unsigned)anchor.y >= (unsigned)kernel->rows )
CV_ERROR( CV_StsOutOfRange, "anchor point is out of kernel" );
if( CV_MAT_TYPE(kernel->type) != CV_32FC1 || !CV_IS_MAT_CONT(kernel->type) || icvFilter_8u_C1R_p )
{
int sz = kernel->rows*kernel->cols*sizeof(kernel_data[0]);
if( sz < CV_MAX_LOCAL_SIZE )
kernel_data = (float*)cvStackAlloc( sz );
else
{
CV_CALL( kernel_data = (float*)cvAlloc( sz ));
local_alloc = 0;
}
kernel_hdr = cvMat( kernel->rows, kernel->cols, CV_32F, kernel_data );
if( CV_MAT_TYPE(kernel->type) == CV_32FC1 )
cvCopy( kernel, &kernel_hdr );
else
cvConvertScale( kernel, &kernel_hdr, 1, 0 );
kernel = &kernel_hdr;
}
size = cvGetMatSize( src );
depth = CV_MAT_DEPTH(type);
src_step = src->step;
dst_step = dst->step ? dst->step : CV_STUB_STEP;
if( icvFilter_8u_C1R_p && (src->rows >= ipp_lower_limit || src->cols >= ipp_lower_limit) )
{
CvFilterIPPFunc ipp_func =
type == CV_8UC1 ? (CvFilterIPPFunc)icvFilter_8u_C1R_p :
type == CV_8UC3 ? (CvFilterIPPFunc)icvFilter_8u_C3R_p :
type == CV_8UC4 ? (CvFilterIPPFunc)icvFilter_8u_C4R_p :
type == CV_16SC1 ? (CvFilterIPPFunc)icvFilter_16s_C1R_p :
type == CV_16SC3 ? (CvFilterIPPFunc)icvFilter_16s_C3R_p :
type == CV_16SC4 ? (CvFilterIPPFunc)icvFilter_16s_C4R_p :
type == CV_32FC1 ? (CvFilterIPPFunc)icvFilter_32f_C1R_p :
type == CV_32FC3 ? (CvFilterIPPFunc)icvFilter_32f_C3R_p :
type == CV_32FC4 ? (CvFilterIPPFunc)icvFilter_32f_C4R_p : 0;
if( ipp_func )
{
CvSize el_size = { kernel->cols, kernel->rows };
CvPoint el_anchor = { el_size.width - anchor.x - 1, el_size.height - anchor.y - 1 };
int stripe_size = 1 << 16; // the optimal value may depend on CPU cache,
// overhead of current IPP code etc.
const uchar* shifted_ptr;
int i, j, y, dy = 0;
int temp_step;
// mirror the kernel around the center
for( i = 0; i < (el_size.height+1)/2; i++ )
{
float* top_row = kernel->data.fl + el_size.width*i;
float* bottom_row = kernel->data.fl + el_size.width*(el_size.height - i - 1);
for( j = 0; j < (el_size.width+1)/2; j++ )
{
float a = top_row[j], b = top_row[el_size.width - j - 1];
float c = bottom_row[j], d = bottom_row[el_size.width - j - 1];
top_row[j] = d;
top_row[el_size.width - j - 1] = c;
bottom_row[j] = b;
bottom_row[el_size.width - j - 1] = a;
}
}
CV_CALL( temp = icvIPPFilterInit( src, stripe_size, el_size ));
shifted_ptr = temp->data.ptr +
anchor.y*temp->step + anchor.x*CV_ELEM_SIZE(type);
temp_step = temp->step ? temp->step : CV_STUB_STEP;
for( y = 0; y < src->rows; y += dy )
{
dy = icvIPPFilterNextStripe( src, temp, y, el_size, anchor );
IPPI_CALL( ipp_func( shifted_ptr, temp_step,
dst->data.ptr + y*dst_step, dst_step, cvSize(src->cols, dy),
kernel->data.fl, el_size, el_anchor ));
}
EXIT;
}
}
CV_CALL( state = icvFilterInitAlloc( src->cols, cv32f, CV_MAT_CN(type),
cvSize(kernel->cols, kernel->rows), anchor,
kernel->data.ptr, ICV_GENERIC_KERNEL ));
if( CV_MAT_CN(type) == 2 )
CV_ERROR( CV_BadNumChannels, "Unsupported number of channels" );
func = (CvFilterFunc)(filter_tab.fn_2d[depth]);
if( !func )
CV_ERROR( CV_StsUnsupportedFormat, "" );
if( size.height == 1 )
src_step = dst_step = CV_STUB_STEP;
IPPI_CALL( func( src->data.ptr, src_step, dst->data.ptr,
dst_step, &size, state, 0 ));
__END__;
cvReleaseMat( &temp );
icvFilterFree( &state );
if( !local_alloc )
cvFree( (void**)&kernel_data );
}
/* End of file. */
| [
"[email protected]"
] | [
[
[
1,
738
]
]
] |
ef5ff310ef1bf88e406724b9a2a15221e13cf4c7 | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.8/cbear.berlios.de/meta/identity.test.cpp | f61a0b19bfd74e65ee27cb4e8bbf6c288b6fcdbe | [
"MIT"
] | permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | cpp | #include <cbear.berlios.de/meta/identity.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
namespace M = cbear_berlios_de::meta;
int main()
{
BOOST_STATIC_ASSERT((boost::is_same<M::identity<char>::type, char>::value));
}
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
] | [
[
[
1,
10
]
]
] |
2f23b3479286be11735f11022602d327e42dd856 | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Vehicle/WheelCollide/hkpVehicleWheelCollide.h | 02ceec367bf0bfda4396e48391caeb16e00bbd0a | [] | no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,819 | 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-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HKVEHICLE_COLLISIONDETECTION_hkVehicleCOLLISIONDETECTION_XML_H
#define HKVEHICLE_COLLISIONDETECTION_hkVehicleCOLLISIONDETECTION_XML_H
#include <Common/Base/hkBase.h>
#include <Physics/Dynamics/Entity/hkpRigidBody.h>
class hkpVehicleInstance;
/// This component manages the collision detection between the wheels and the
/// ground.
class hkpVehicleWheelCollide : public hkReferencedObject
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_VEHICLE);
HK_DECLARE_REFLECTION();
/// Container for data output by the collision calculations.
struct CollisionDetectionWheelOutput
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_VEHICLE, hkpVehicleWheelCollide::CollisionDetectionWheelOutput );
/// The point of contact of the wheel with the ground.
class hkContactPoint m_contactPoint;
/// The friction coefficient at the point of contact.
hkReal m_contactFriction;
/// The ground body the vehicle is in contact. This value is HK_NULL
/// if none of the wheels are in contact with the ground.
hkpRigidBody* m_contactBody;
/// The shapeKey of the object at the point of contact.
hkpShapeKey m_contactShapeKey;
/// The length of the suspension due to the wheel being in contact at
/// the given point.
hkReal m_currentSuspensionLength;
/// The velocity of the suspension.
hkReal m_suspensionRelativeVelocity;
/// Scaling factor used to handle curb interaction.
/// Forces along the contact normal are scaled by this factor.
/// This ensures that the suspension force component is unscaled.
/// Clipping is affected by hkpVehicleData::m_normalClippingAngle.
hkReal m_clippedInvContactDotSuspension;
};
//
// Methods
//
/// The caller of this method pre-allocates cdInfoOut with a buffer the size of the
/// number of wheels in the vehicle
virtual void collideWheels(const hkReal deltaTime, hkpVehicleInstance* vehicle, CollisionDetectionWheelOutput* cdInfoOut) = 0;
virtual void init( const hkpVehicleInstance* vehicle ) = 0;
virtual void getPhantoms( hkArray<hkpPhantom*>& phantomsOut ) = 0;
/// As all other parts of the vehicle can usually be shared, except for the wheel collide.
virtual hkpVehicleWheelCollide* clone( const hkArray<hkpPhantom*>& newPhantoms ) const = 0;
public:
/// This component cannot be shared between vehicle instances - this variable
/// indicates if a vehicle already owns it.
hkBool m_alreadyUsed;
};
#endif // HKVEHICLE_COLLISIONDETECTION_hkVehicleCOLLISIONDETECTION_XML_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] | [
[
[
1,
94
]
]
] |
facf9f56724577cc61ff3b44b6873b4333ddd654 | 0da7fec56f63012180d848b1e72bada9f6984ef3 | /PocketDjVu_root/PocketDjvu/SIPState.h | ad762802e67e0f50e8e762c2141540ab06609f2f | [] | no_license | UIKit0/pocketdjvu | a34fb2b8ac724d25fab7a0298942db1755098b25 | 4c0c761e6a3d3628440fb4fb0a9c54e5594807d9 | refs/heads/master | 2021-01-20T12:01:16.947853 | 2010-05-03T12:29:44 | 2010-05-03T12:29:44 | 32,293,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | h | #pragma once
class CSIPState : public SIPINFO
{
public:
CSIPState() throw()
{
ZeroMemory( this, sizeof SIPINFO );
cbSize = sizeof SIPINFO;
m_bValid = SHSipInfo( SPI_GETSIPINFO, 0, this, 0 );
}
~CSIPState() throw()
{
if( IsValid() )
{
SHSipInfo( SPI_SETSIPINFO, 0, this, 0 );
}
}
bool IsValid()
{
return !!m_bValid;
}
private:
BOOL m_bValid;
};
| [
"Igor.Solovyov@84cd470b-3125-0410-acc3-039690e87181"
] | [
[
[
1,
27
]
]
] |
0263e97324f4f58dd48f54091c7be0296be5c9a2 | 57855d23617d6a65298c2ae3485ba611c51809eb | /Zen/Core/Utility/src/I_EnvironmentHandler.cpp | 80e17f6140e0f223ca08ccb5632c7d240cdc893b | [] | no_license | Azaezel/quillus-daemos | 7ff4261320c29e0125843b7da39b7b53db685cd5 | 8ee6eac886d831eec3acfc02f03c3ecf78cc841f | refs/heads/master | 2021-01-01T20:35:04.863253 | 2011-04-08T13:46:40 | 2011-04-08T13:46:40 | 32,132,616 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,210 | cpp | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Core Framework
//
// Copyright (C) 2001 - 2009 Tony Richards
//
// 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.
//
// Tony Richards [email protected]
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#include "../I_EnvironmentHandler.hpp"
#include "EnvironmentHandler.hpp"
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace Utility {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
I_EnvironmentHandler::I_EnvironmentHandler()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
I_EnvironmentHandler::~I_EnvironmentHandler()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
I_EnvironmentHandler&
I_EnvironmentHandler::getDefaultHandler()
{
static I_EnvironmentHandler* pDefaultHandler = NULL;
if (pDefaultHandler == NULL)
{
pDefaultHandler = new EnvironmentHandler();
}
return *pDefaultHandler;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Utility
} // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| [
"sgtflame@Sullivan"
] | [
[
[
1,
59
]
]
] |
d36a514775ed928c2b3258e76d30d2a634608c81 | a8157564af47618589001d80f0f4571c6328f3e0 | /config.h | 74a25d4271bf5296e2bdd6585ce6ff3a83027412 | [
"MIT"
] | permissive | dionyziz/cador | 83848185094c0198ec7b217fdaf2d94c39e541ba | ee939b5556aebdea692d3cea5badbe3c85b49a7d | refs/heads/master | 2020-06-06T07:11:55.517376 | 2011-11-23T21:45:58 | 2011-11-23T21:45:58 | 2,240,956 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,066 | h | #ifndef CADOR_CONFIG
#define CADOR_CONFIG
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <utility>
#include "string.h"
#include "xerces.h"
using namespace std;
class Config {
public:
Config();
~Config();
string GetSetting( string );
string GetSetting( char* );
vector< string > GetMultiSetting( char* );
void SetDefaultSetting( string , string );
void SetDefaultSetting( char* , char* );
void SetSetting( string , string );
void SetSetting( char* , char* );
void LoadFromFile( const string );
private:
void Parse();
void ParseLine( string );
void MultiSettingBegin( string );
void MultiSettingAdd( string );
void MultiSettingEnd( string );
string mFilename;
map< string, string > mConf;
map< string, vector< string > > mMultiConf;
map< string, vector< string > >::iterator mCurrentMultiSetting;
};
extern Config* conf;
#endif
| [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
1375d4e0d271c641a48ac39646391923de41d9ff | 71d018f8dbcf49cfb07511de5d58d6ad7df816f7 | /scistudio/trunk/vocabfind.cpp | 39a86e58417a9e29a69e1616768845599b58f16b | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | qq431169079/SciStudio | 48225261386402530156fc2fc14ff0cad62174e8 | a1fccbdcb423c045078b927e7c275b9d1bcae6b3 | refs/heads/master | 2020-05-29T13:01:50.800903 | 2010-09-14T07:10:07 | 2010-09-14T07:10:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,766 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "scihdr.h"
#include "vocabedit.h"
#include "vocabfind.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TDlgVocabFind *DlgVocabFind;
//---------------------------------------------------------------------------
__fastcall TDlgVocabFind::TDlgVocabFind(TComponent* Owner)
: TForm(Owner)
{
ResetFind();
}
//---------------------------------------------------------------------------
void __fastcall TDlgVocabFind::BtnFindClick(TObject *Sender)
{
Edit1->Text = Edit1->Text.LowerCase();
if(Edit1->Text == "") {
StatusBar1->SimpleText = "Error: Please enter search string!";
return;
}
for(Group = 0; Group < MAX_VOC_GROUPS; Group++)
if(aWndVocabEdit->vocGroups[Group])
for(int s = 0; s < aWndVocabEdit->vocGroups[Group]->Strings->Count; s++)
if(aWndVocabEdit->vocGroups[Group]->Strings->Strings[s] == Edit1->Text) {
StatusBar1->SimpleText = "\""+Edit1->Text+"\" found in Group: "+IntToStr(Group)+".";
BtnOK->Enabled = TRUE;
BtnGoto->Enabled = TRUE;
return;
}
StatusBar1->SimpleText = "\""+Edit1->Text+"\" not found!";
ResetFind();
}
//---------------------------------------------------------------------------
void __fastcall TDlgVocabFind::BtnOKClick(TObject *Sender)
{
Close();
}
//---------------------------------------------------------------------------
void __fastcall TDlgVocabFind::BtnGotoClick(TObject *Sender)
{
AnsiString StrGroup = IntToStr(Group);
TListItem *ListItem =
aWndVocabEdit->ListView->FindCaption(0, StrGroup, FALSE, TRUE, FALSE);
aWndVocabEdit->ListView->SetFocus();
aWndVocabEdit->ListView->Selected = ListItem;
aWndVocabEdit->ListView->ItemFocused = ListItem;
ListItem->MakeVisible(TRUE);
}
//---------------------------------------------------------------------------
void __fastcall TDlgVocabFind::BtnCancelClick(TObject *Sender)
{
Close();
}
//---------------------------------------------------------------------------
void __fastcall TDlgVocabFind::ResetFind()
{
BtnOK->Enabled = FALSE;
BtnGoto->Enabled = FALSE;
Group = -1;
}
//---------------------------------------------------------------------------
void __fastcall TDlgVocabFind::FormClose(TObject *Sender,
TCloseAction &Action)
{
Action = caFree;
}
//---------------------------------------------------------------------------
| [
"mageofmarr@d0e240c1-a1d3-4535-ae25-191325aad40e"
] | [
[
[
1,
77
]
]
] |
ef5692708513d53b9a95eb92849cd83454225250 | 6477cf9ac119fe17d2c410ff3d8da60656179e3b | /Projects/openredalert/src/game/ProjectileDataList.cpp | a5b015dc41a2c945fd1965396490afae4e46bde9 | [] | no_license | crutchwalkfactory/motocakerteam | 1cce9f850d2c84faebfc87d0adbfdd23472d9f08 | 0747624a575fb41db53506379692973e5998f8fe | refs/heads/master | 2021-01-10T12:41:59.321840 | 2010-12-13T18:19:27 | 2010-12-13T18:19:27 | 46,494,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,108 | cpp | // ProjectileDataList.cpp
// 1.0
// This file is part of OpenRedAlert.
//
// OpenRedAlert is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2 of the License.
//
// OpenRedAlert is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with OpenRedAlert. If not, see <http://www.gnu.org/licenses/>.
#include "ProjectileDataList.h"
#include <iterator>
#include <string>
#include <iostream>
#include "ProjectileData.h"
#include "misc/INIFile.h"
#include "include/Logger.h"
using std::string;
using std::iterator;
using std::cout;
using std::endl;
extern Logger * logger;
/**
*/
ProjectileData* ProjectileDataList::getData(string name)
{
map < string, ProjectileData * >::iterator itRecherche;
itRecherche=data.find(name);
if (itRecherche != data.end())
{
// Return the ProjectileData found
//ut << (*itRecherche).second->getWall() << endl;
return (*itRecherche).second;
}
// If here NO PROJECTILEDATA FOUND
logger->error("PROJECTILEDATA [%s] not found in DataList !!!\n", name.c_str());
// Return new ProjectileData by default
logger->warning("New virtual ProjectileData was returned...\n");
return new ProjectileData();
}
/**
*/
void ProjectileDataList::loadProjectileData(INIFile* file, string name)
{
// Save a ref to the ProjectileData
data[name] = ProjectileData::loadProjectileData(file, name);
}
/**
*/
void ProjectileDataList::print()
{
map < string, ProjectileData* >::iterator itRecherche;
itRecherche = data.begin();
while (itRecherche != data.end())
{
cout << "[" << (*itRecherche).first << "]" << endl;
(*itRecherche).second->print();
itRecherche++;
}
}
| [
"[email protected]"
] | [
[
[
1,
79
]
]
] |
4b5fc2e1ddd2ed4b8e7b1c916a2e893993a31c09 | a2904986c09bd07e8c89359632e849534970c1be | /topcoder/RandomAppleEasy.cpp | ad9e653f0c8d0901d578819d493f55bdb4079320 | [] | no_license | naturalself/topcoder_srms | 20bf84ac1fd959e9fbbf8b82a93113c858bf6134 | 7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5 | refs/heads/master | 2021-01-22T04:36:40.592620 | 2010-11-29T17:30:40 | 2010-11-29T17:30:40 | 444,669 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,278 | cpp | // BEGIN CUT HERE
// END CUT HERE
#line 5 "RandomAppleEasy.cpp"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
using namespace std;
#define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i)
#define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i)
#define all(a) a.begin(), a.end()
class RandomAppleEasy {
public:
double theRed(vector <int> red, vector <int> green) {
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {5}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {8}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.38461538461538464; verify_case(0, Arg2, theRed(Arg0, Arg1)); }
void test_case_1() { int Arr0[] = {1, 2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.5888888888888888; verify_case(1, Arg2, theRed(Arg0, Arg1)); }
void test_case_2() { int Arr0[] = {2, 5, 6, 4, 9, 10, 6, 2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2, 5, 6, 4, 9, 10, 6, 2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.4999999999999999; verify_case(2, Arg2, theRed(Arg0, Arg1)); }
void test_case_3() { int Arr0[] = {2, 5, 6, 4, 9, 10, 6, 2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {6, 7, 4, 5, 3, 2, 9, 1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.5429014970733334; verify_case(3, Arg2, theRed(Arg0, Arg1)); }
void test_case_4() { int Arr0[] = {5, 1, 2, 8, 4, 1, 1, 2, 3, 4, 5, 2, 10, 2, 6, 2, 8, 7, 9, 3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {4, 7, 1, 1, 10, 3, 4, 1, 6, 2, 7, 6, 10, 5, 2, 9, 3, 8, 1, 8}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.46460213827476854; verify_case(4, Arg2, theRed(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
RandomAppleEasy ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"shin@CF-7AUJ41TT52JO.(none)"
] | [
[
[
1,
58
]
]
] |
a8ffe8d4d4eda7e58ae41ba6ef1b3ff5ddaed162 | b369aabb8792359175aedfa50e949848ece03180 | /src/wblib/wblib/TGALoader.h | e4f1108a41916f8d1c3b0675729b5c18850c91a9 | [] | no_license | LibreGamesArchive/magiccarpet | 6d49246817ab913f693f172fcfc53bf4cc153842 | 39210d57096d5c412de0f33289fbd4d08c20899b | refs/heads/master | 2021-05-08T02:00:46.182694 | 2009-01-06T20:25:36 | 2009-01-06T20:25:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,922 | h | // Using this class:
// You can use the static method LoadJPEGTexture() to retrieve an OpenGL
// Object ID to the texture object. Use that id to bind the texture
// using glBindTexture(GL_TEXTURE_2D, 0);
//
// If you are using several texture units, you have to make sure that the
// texture is bound onto the correct texture unit:
// glActiveTextureARB(GL_TEXTURE0_ARB + 0);
// glBindTexture(GL_TEXTURE_2D, textureObjectID);
// glEnable(GL_TEXTURE_2D);
#ifndef _TGALOADER
#define _TGALOADER
#include <iostream>
#include <fstream>
#include <GL/glew.h>
#include <GL/glut.h>
// Pragmas are needed to force 18 byte size of tga header struct
#pragma pack(1)
struct TGAHeader {
unsigned char imageIDlength; // number of characters in the ID field (1 Byte), no ID Field
// if a zero is stored in this element
unsigned char colorMapType; // Type of colormap, always 0 (1 Byte)
unsigned char imageTypeCode; // 8 Bit paletized = 1
// uncompressed RGB oder RGBA = 2
// uncompressed grayscale = 3
// Run-Length Encoded RGB oder RGBA = 10
// compressed grayscale = 11 (1 Byte)
short int colorMapOrigin; // always 0 (2 Byte)
short int colorMapLength; // always 0 (2 Byte)
unsigned char entrySize; // size of one entry in the palette (1 Byte)
short int imageXOrigin; // always 0 (2 Byte)
short int imageYOrigin; // always 0 (2 Byte)
short int imageWidth; // Width in Pixels (2 Byte)
short int imageHeight; // Height in Pixels (2 Byte)
unsigned char bitCount; // Bits per Pixel (1 Byte)
unsigned char imageDescriptor; // 24 bit = 0x00; 32 bit = 0 0x08 (1 Byte)
};
#pragma pack()
class TGALoader {
public:
static int LoadTGATexture(const char * _fileName);
};
#endif
| [
"[email protected]"
] | [
[
[
1,
49
]
]
] |
5b07dee60b195b9c4ec2b7917759bb3be1a868b2 | c70941413b8f7bf90173533115c148411c868bad | /core/include/vtxMouseEvent.h | e5009eb8617e8ab87bd203ac2ebfc727c0d63970 | [] | no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,482 | h | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __vtxMouseEvent_H__
#define __vtxMouseEvent_H__
#include "vtxPrerequisites.h"
#include "vtxEvent.h"
// on windows there is a macro named "DOUBLE_CLICK"
#ifdef DOUBLE_CLICK
# undef DOUBLE_CLICK
#endif
namespace vtx
{
//-----------------------------------------------------------------------
/** An event that is triggered by mouse input devices */
class vtxExport MouseEvent : public Event
{
public:
MouseEvent(const String& type);
virtual ~MouseEvent();
static const String CATEGORY;
static const String CLICK;
static const String DOUBLE_CLICK;
static const String MOUSE_DOWN;
static const String MOUSE_MOVE;
static const String MOUSE_OUT;
static const String MOUSE_OVER;
static const String MOUSE_UP;
static const String MOUSE_WHEEL;
static const String ROLL_OUT;
static const String ROLL_OVER;
const String& getCategory() const;
float localX;
float localY;
float stageX;
float stageY;
};
//-----------------------------------------------------------------------
}
#endif
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a",
"fixxxeruk@9773a11d-1121-4470-82d2-da89bd4a628a"
] | [
[
[
1,
31
],
[
33,
72
]
],
[
[
32,
32
]
]
] |
70bc8a9f521cf5380f4c49107b10b3719b36f633 | d7320c9c1f155e2499afa066d159bfa6aa94b432 | /ghost/bnlsclient.cpp | 81a73c6f4838ae66b5fdb27bc65c7db2229f4b64 | [] | no_license | HOST-PYLOS/ghostnordicleague | c44c804cb1b912584db3dc4bb811f29f3761a458 | 9cb262d8005dda0150b75d34b95961d664b1b100 | refs/heads/master | 2016-09-05T10:06:54.279724 | 2011-02-23T08:02:50 | 2011-02-23T08:02:50 | 32,241,503 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,161 | cpp | /*
Copyright [2008] [Trevor Hogan]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#include "ghost.h"
#include "util.h"
#include "socket.h"
#include "commandpacket.h"
#include "bnlsprotocol.h"
#include "bnlsclient.h"
//
// CBNLSClient
//
CBNLSClient :: CBNLSClient( string nServer, uint16_t nPort, uint32_t nWardenCookie )
{
m_Socket = new CTCPClient( );
m_Protocol = new CBNLSProtocol( );
m_WasConnected = false;
m_Server = nServer;
m_Port = nPort;
m_LastNullTime = 0;
m_WardenCookie = nWardenCookie;
m_TotalWardenIn = 0;
m_TotalWardenOut = 0;
}
CBNLSClient :: ~CBNLSClient( )
{
delete m_Socket;
delete m_Protocol;
while( !m_Packets.empty( ) )
{
delete m_Packets.front( );
m_Packets.pop( );
}
}
BYTEARRAY CBNLSClient :: GetWardenResponse( )
{
BYTEARRAY WardenResponse;
if( !m_WardenResponses.empty( ) )
{
WardenResponse = m_WardenResponses.front( );
m_WardenResponses.pop( );
m_TotalWardenOut++;
}
return WardenResponse;
}
unsigned int CBNLSClient :: SetFD( void *fd, void *send_fd, int *nfds )
{
if( !m_Socket->HasError( ) && m_Socket->GetConnected( ) )
{
m_Socket->SetFD( (fd_set *)fd, (fd_set *)send_fd, nfds );
return 1;
}
return 0;
}
bool CBNLSClient :: Update( void *fd, void *send_fd )
{
if( m_Socket->HasError( ) )
{
CONSOLE_Print( "[BNLSC: " + m_Server + ":" + UTIL_ToString( m_Port ) + ":C" + UTIL_ToString( m_WardenCookie ) + "] disconnected from BNLS server due to socket error" );
return true;
}
if( !m_Socket->GetConnecting( ) && !m_Socket->GetConnected( ) && m_WasConnected )
{
CONSOLE_Print( "[BNLSC: " + m_Server + ":" + UTIL_ToString( m_Port ) + ":C" + UTIL_ToString( m_WardenCookie ) + "] disconnected from BNLS server due to socket not connected" );
return true;
}
if( m_Socket->GetConnected( ) )
{
m_Socket->DoRecv( (fd_set *)fd );
ExtractPackets( );
ProcessPackets( );
if( GetTime( ) >= m_LastNullTime + 50 )
{
m_Socket->PutBytes( m_Protocol->SEND_BNLS_NULL( ) );
m_LastNullTime = GetTime( );
}
while( !m_OutPackets.empty( ) )
{
m_Socket->PutBytes( m_OutPackets.front( ) );
m_OutPackets.pop( );
}
m_Socket->DoSend( (fd_set *)send_fd );
return false;
}
if( m_Socket->GetConnecting( ) && m_Socket->CheckConnect( ) )
{
CONSOLE_Print( "[BNLSC: " + m_Server + ":" + UTIL_ToString( m_Port ) + ":C" + UTIL_ToString( m_WardenCookie ) + "] connected" );
m_WasConnected = true;
m_LastNullTime = GetTime( );
return false;
}
if( !m_Socket->GetConnecting( ) && !m_Socket->GetConnected( ) && !m_WasConnected )
{
CONSOLE_Print( "[BNLSC: " + m_Server + ":" + UTIL_ToString( m_Port ) + ":C" + UTIL_ToString( m_WardenCookie ) + "] connecting to server [" + m_Server + "] on port " + UTIL_ToString( m_Port ) );
m_Socket->Connect( string( ), m_Server, m_Port );
return false;
}
return false;
}
void CBNLSClient :: ExtractPackets( )
{
string *RecvBuffer = m_Socket->GetBytes( );
BYTEARRAY Bytes = UTIL_CreateByteArray( (unsigned char *)RecvBuffer->c_str( ), RecvBuffer->size( ) );
while( Bytes.size( ) >= 3 )
{
uint16_t Length = UTIL_ByteArrayToUInt16( Bytes, false );
if( Length >= 3 )
{
if( Bytes.size( ) >= Length )
{
m_Packets.push( new CCommandPacket( 0, Bytes[2], BYTEARRAY( Bytes.begin( ), Bytes.begin( ) + Length ) ) );
*RecvBuffer = RecvBuffer->substr( Length );
Bytes = BYTEARRAY( Bytes.begin( ) + Length, Bytes.end( ) );
}
else
return;
}
else
{
CONSOLE_Print( "[BNLSC: " + m_Server + ":" + UTIL_ToString( m_Port ) + ":C" + UTIL_ToString( m_WardenCookie ) + "] error - received invalid packet from BNLS server (bad length), disconnecting" );
m_Socket->Disconnect( );
return;
}
}
}
void CBNLSClient :: ProcessPackets( )
{
while( !m_Packets.empty( ) )
{
CCommandPacket *Packet = m_Packets.front( );
m_Packets.pop( );
if( Packet->GetID( ) == CBNLSProtocol :: BNLS_WARDEN )
{
BYTEARRAY WardenResponse = m_Protocol->RECEIVE_BNLS_WARDEN( Packet->GetData( ) );
if( !WardenResponse.empty( ) )
m_WardenResponses.push( WardenResponse );
}
delete Packet;
}
}
void CBNLSClient :: QueueWardenSeed( uint32_t seed )
{
m_OutPackets.push( m_Protocol->SEND_BNLS_WARDEN_SEED( m_WardenCookie, seed ) );
}
void CBNLSClient :: QueueWardenRaw( BYTEARRAY wardenRaw )
{
m_OutPackets.push( m_Protocol->SEND_BNLS_WARDEN_RAW( m_WardenCookie, wardenRaw ) );
m_TotalWardenIn++;
}
| [
"fredrik.sigillet@4a4c9648-eef2-11de-9456-cf00f3bddd4e"
] | [
[
[
1,
193
]
]
] |
459c266668c92eb9eb0b4f6a0b1e860bcd5551c8 | cd69369374074a7b4c4f42e970ee95847558e9f0 | /Versao FIX/Marcacao.h | f5ef4756150f8b52dadf2fb2b166b5344bcfac3e | [] | no_license | miaosun/aeda-trab1 | 4e6b8ce3de8bb7e85e13670595012a5977258a2a | 1ec5e2edec383572c452545ed52e45fb26df6097 | refs/heads/master | 2021-01-25T03:40:21.146657 | 2010-12-25T03:35:28 | 2010-12-25T03:35:28 | 33,734,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,371 | h | ///////////////////////////////////////////////////////////
// Marcacao.h
// Implementation of the Class Marcacao
// Created on: 24-Out-2010 20:04:13
// Original author: Answer
///////////////////////////////////////////////////////////
#if !defined(EA_6D34D39A_7937_43d1_9953_2455A3DEDC2B__INCLUDED_)
#define EA_6D34D39A_7937_43d1_9953_2455A3DEDC2B__INCLUDED_
#include "Pessoa.h"
#include "Doente.h"
#include "Medico.h"
#include <string>
#include <vector>
using namespace std;
class Marcacao
{
public:
Marcacao();
virtual ~Marcacao();
Marcacao(string data, string hora, string tipo, Pessoa * medico, Pessoa * doente);
string getData();
void setData(string data);
string getHora();
void setHora(string hora);
string getTipo();
void setTipo(string tipo);
int getId() const;
string toList();
Pessoa * getMedico();
void setMedico(Pessoa * medico);
Pessoa * getDoente();
void setDoente(Pessoa * doente);
virtual string toString();
virtual vector<string> imprime();
virtual vector<string> editMarcacao();
///////////////////////////////////////
//
virtual void setSala(string sala) = 0;
private:
string data;
string hora;
int id;
string tipo;
static int count;
Pessoa * medico;
Pessoa * doente;
};
#endif // !defined(EA_6D34D39A_7937_43d1_9953_2455A3DEDC2B__INCLUDED_)
| [
"gasparlafurtado@9ca0f86a-2074-76d8-43a5-19cf18205b40",
"miaosun88@9ca0f86a-2074-76d8-43a5-19cf18205b40"
] | [
[
[
1,
25
],
[
27,
36
],
[
38,
39
],
[
44,
59
]
],
[
[
26,
26
],
[
37,
37
],
[
40,
43
]
]
] |
11dc167c4b44bffbd60fafdbf6ebe58295877087 | 142382dfb7877fa51ccf9812a13fd6ce120f30da | /Fountain/main.cpp | 90c514d22292d5026983e7527f60545ad4b8d2c5 | [] | no_license | tarunyadav/OpenGL_Animation | 7a12272a36dfe0608af5808f6a88186da0a4af87 | 0eba2b12688d476d943bcca1a5ebea76f0f2e4a3 | refs/heads/master | 2021-01-16T01:08:05.104384 | 2011-11-21T14:56:52 | 2011-11-21T14:56:52 | 2,842,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,876 | cpp | /**********************************************************************
Foutain + Water Simulation
May, 7th, 2003
This opengl sample was written by Philipp Crocoll
Contact:
[email protected]
www.codecolony.de
Every comment would be appreciated.
If you want to use parts of any code of mine:
let me know and
use it!
***********************************************************************
Keys to use
===========
1-7 : Re-initialize scene with another shape of the fountain
w,s : move camera forward/backward
a,d : turn camera right/left
r,f : move camera up/down
x,y : turn camera up/down
c,v : strafe left/right
Esc : Exit
How does it work?
=================
The classes CCamera and COGLTexture are described in tutorials on
www.codecolony.de/OpenGL
The files vectors.h/.cpp provide help with vector maths.
The class CPool was made from my SwimmingPool example (also on CodeColony).
The class CAirFountain was made from my Fountain Tutorial (online, too).
Changes in those classes:
-> Fountain gets a "Pool Pointer". Each time a drop falls into the water
(y < 0) I search for the pool's oscillator which is closest to the
drops position. This oscillator is put down a bit (y-value is decreased).
-> When a fountain has many drops, a whole pool area is often put so strongly
down that it is below the bowl and becomes invisible! This is unrealistic
anyway, so the "AffectOscillator" method does not allow to put an oscillator
too deep. The corresponding line of code should be replaced when using
the pool for other purposes.
-> The pool has a kind of damping (which is not physically correct). Otherwise
the waves would become too strong after a while.
The method "RenderBowl" is not very interesting - it simply renders a bowl!
***********************************************************************/
#include <GL/glut.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include "pool.h"
#include "AirFountain.h"
#include "camera.h" //This is my old camera, but it's easier to control
//for the user and the third rotation axis is not required here
#include "textures.h"
//lighting:
GLfloat LightAmbient[]= { 0.2f, 0.2f, 0.2f, 0.0f };
GLfloat LightDiffuse[]= { 0.8f, 0.8f, 0.8f, 0.0f };
GLfloat LightPosition[]= { 1.0f, -0.5f, -0.5f, 1.0f };
//Constants:
#define NUM_X_OSCILLATORS 170
#define NUM_Z_OSCILLATORS 170
#define OSCILLATOR_DISTANCE 0.015
#define OSCILLATOR_WEIGHT 0.0001
#define MAXX (NUM_X_OSCILLATORS*OSCILLATOR_DISTANCE)
#define MAXZ (NUM_Z_OSCILLATORS*OSCILLATOR_DISTANCE)
#define POOL_HEIGHT 0.3
//Camera object:
CCamera Camera;
//The "pool" which represents the water within the fountain bowl
CPool Pool;
//water outside the bowl is in the air:
CAirFountain AirFountain;
//Textures:
COGLTexture WaterTexture; //the image does not contain a water texture,
//but it is applied to the water
COGLTexture RockTexture;
COGLTexture GroundTexture;
bool g_bRain = true;
bool g_bFillModePoints = true;
bool g_bLighting = true;
void KeyDown(unsigned char key, int x, int y)
{
switch(key)
{
case 27: //ESC
exit(0);
break;
case 'a':
Camera.RotateY(5.0f);
break;
case 'd':
Camera.RotateY(-5.0f);
break;
case 'w':
Camera.MoveForwards(-0.15f ) ;
break;
case 's':
Camera.MoveForwards( 0.15f ) ;
break;
case 'x':
Camera.RotateX(5.0f);
break;
case 'y':
Camera.RotateX(-5.0f);
break;
case 'c':
Camera.StrafeRight(-0.05f);
break;
case 'v':
Camera.StrafeRight(0.05f);
break;
case 'f':
Camera.Move(F3dVector(0.0,-0.1,0.0));
break;
case 'r':
Camera.Move(F3dVector(0.0,0.1,0.0));
break;
//*************************************
//Several initialization calls:
case '1':
Pool.Reset();
AirFountain.Delete();
AirFountain.Initialize(3,8,35,76,90,0.5,0.11);
break;
case '2':
Pool.Reset();
AirFountain.Delete();
AirFountain.Initialize(1,20,100,70,70,5.0,0.15);
break;
case '3':
Pool.Reset();
AirFountain.Initialize(1,20,200,85,85,10,0.1);
break;
case '4':
Pool.Reset();
AirFountain.Initialize(5,20,85,90,90,1.0,0.15);
break;
case '5':
Pool.Reset();
AirFountain.Initialize(2,20,50,40,70,1.5,0.2);
break;
case '6':
Pool.Reset();
AirFountain.Initialize(3,50,25,76,90,0.2,0.11);
break;
case '7':
Pool.Reset();
//AirFountain.Initialize(4,100,45,76,90,0.2,0.11);
AirFountain.Initialize(5,50,65,76,90,0.5,0.11);
break;
}
}
GLfloat OuterRadius = 1.2;
GLfloat InnerRadius = 1.0;
GLint NumOfVerticesStone = 32; //only a quarter of the finally used vertices
GLfloat StoneHeight = 0.5;
GLfloat WaterHeight = 0.45;
GLint ListNum; //The number of the diplay list
struct SVertex
{
GLfloat x,y,z;
};
float turn=0;
void RenderBowl(void)
{
float bowlheight = 0.2 + POOL_HEIGHT;
float bowlwidth = 0.2;
float TexBorderDistance = bowlwidth / (MAXX+2*bowlwidth);
GroundTexture.SetActive();
glBegin(GL_QUADS);
float minX = -4.0;
float minZ = -4.0;
float maxX = 8.0;
float maxZ = 8.0;
//******************
//ground
//******************
glNormal3f(0.0f,1.0f,0.0);
glTexCoord2f(0.0,0.0);
glVertex3f(minX,0.0,minZ);
glTexCoord2f(1.0,0.0);
glVertex3f(maxX,0.0,minZ);
glTexCoord2f(1.0,1.0);
glVertex3f(maxX,0.0,maxZ);
glTexCoord2f(0.0,1.0);
glVertex3f(minX,0.0,maxZ);
glEnd();
glColor3f(.5,.5,.5);
glBegin(GL_QUADS);
/* Ceiling */
glVertex3f(minX,6,minZ);
glVertex3f(maxX,6,minZ);
glVertex3f(maxX,6,maxZ);
glVertex3f(minX,6,maxZ);
/* Walls */
/* glVertex3f(minX,-2,maxZ);
glVertex3f(maxX,-2,maxZ);
glVertex3f(maxX,6,maxZ);
glVertex3f(minX,6,maxZ);*/
glVertex3f(minX,0,minZ);
glVertex3f(maxX,0,minZ);
glVertex3f(maxX,6,minZ);
glVertex3f(minX,6,minZ);
glVertex3f(maxX,6,maxZ);
glVertex3f(maxX,0,maxZ);
glVertex3f(maxX,0,minZ);
glVertex3f(maxX,6,minZ);
glVertex3f(minX,6,maxZ);
glVertex3f(minX,0,maxZ);
glVertex3f(minX,0,minZ);
glVertex3f(minX,6,minZ);
glEnd();
glRotatef(turn,0,1,0);
//GLfloat white[] = {0.8f, 0.8f, 0.8f, 1.0f};
//GLfloat cyan[] = {0.f, .8f, .8f, 1.f};
//glMaterialfv(GL_FRONT, GL_DIFFUSE, cyan);
//glMaterialfv(GL_FRONT, GL_SPECULAR, white);
//GLfloat shininess[] = {200};
//glMaterialfv(GL_FRONT, GL_SHININESS, shininess);
RockTexture.SetActive();
// change here for whole scene translation
glPushMatrix();
//glTranslatef(1.3,0.0,1.0);
SVertex * Vertices = new SVertex[NumOfVerticesStone*4]; //allocate mem for the required vertices
ListNum = glGenLists(1);
for (GLint i = 0; i<NumOfVerticesStone; i++)
{
Vertices[i].x = cos(2.0 * PI / NumOfVerticesStone * i) * OuterRadius;
Vertices[i].y = StoneHeight; //Top
Vertices[i].z = sin(2.0 * PI / NumOfVerticesStone * i) * OuterRadius;
}
for (int i = 0; i<NumOfVerticesStone; i++)
{
Vertices[i + NumOfVerticesStone*1].x = cos(2.0 * PI / NumOfVerticesStone * i) * InnerRadius;
Vertices[i + NumOfVerticesStone*1].y = StoneHeight; //Top
Vertices[i + NumOfVerticesStone*1].z = sin(2.0 * PI / NumOfVerticesStone * i) * InnerRadius;
}
for (int i = 0; i<NumOfVerticesStone; i++)
{
Vertices[i + NumOfVerticesStone*2].x = cos(2.0 * PI / NumOfVerticesStone * i) * OuterRadius;
Vertices[i + NumOfVerticesStone*2].y = 0.0; //Bottom
Vertices[i + NumOfVerticesStone*2].z = sin(2.0 * PI / NumOfVerticesStone * i) * OuterRadius;
}
for (int i = 0; i<NumOfVerticesStone; i++)
{
Vertices[i + NumOfVerticesStone*3].x = cos(2.0 * PI / NumOfVerticesStone * i) * InnerRadius;
Vertices[i + NumOfVerticesStone*3].y = 0.0; //Bottom
Vertices[i + NumOfVerticesStone*3].z = sin(2.0 * PI / NumOfVerticesStone * i) * InnerRadius;
}
//glNewList(ListNum, GL_COMPILE);
glBegin(GL_QUADS);
//ground quad:
//glTranslatef(0.0,0.0,4.0);
//glColor3f(1.0,1.0,0);
// glVertex3f(-OuterRadius*1.3,0.0,OuterRadius*1.3);
// glVertex3f(-OuterRadius*1.3,0.0,-OuterRadius*1.3);
// glVertex3f(OuterRadius*1.3,0.0,-OuterRadius*1.3);
// glVertex3f(OuterRadius*1.3,0.0,OuterRadius*1.3);
//stone:
for (int j = 1; j < 3; j++)
{
if (j == 1) glColor3f(1.0,0.6,0.6);
if (j == 2) glColor3f(0.4,0.2,0.2);
int i;
for (i = 0; i<NumOfVerticesStone-1; i++)
{
glNormal3f(0,1,0);
glTexCoord2f(1,1);
glVertex3fv(&Vertices[i+NumOfVerticesStone*j].x);
glTexCoord2f(0,1);
glVertex3fv(&Vertices[i].x);
glTexCoord2f(1,0);
glVertex3fv(&Vertices[i+1].x);
glTexCoord2f(1,0);
glVertex3fv(&Vertices[i+NumOfVerticesStone*j+1].x);
}
glVertex3fv(&Vertices[i+NumOfVerticesStone*j].x);
glVertex3fv(&Vertices[i].x);
glVertex3fv(&Vertices[0].x);
glVertex3fv(&Vertices[NumOfVerticesStone*j].x);
}
// color of texture of water
glColor3f(0.5,0.5,0.7);
/*int i;
WaterTexture.SetActive();
for (i = 0; i<NumOfVerticesStone-1; i++)
{
glVertex3fv(&Vertices[i+NumOfVerticesStone*3].x);
glVertex3fv(&Vertices[i+NumOfVerticesStone].x);
glVertex3fv(&Vertices[i+NumOfVerticesStone+1].x);
glVertex3fv(&Vertices[i+NumOfVerticesStone*3+1].x);
}
glVertex3fv(&Vertices[i+NumOfVerticesStone*3].x);
glVertex3fv(&Vertices[i+NumOfVerticesStone].x);
glVertex3fv(&Vertices[NumOfVerticesStone].x);
glVertex3fv(&Vertices[NumOfVerticesStone*3].x);
*/
glEnd();
//The "water":
//glTranslatef(0.0,WaterHeight - StoneHeight, 0.0);
//glBindTexture(GL_TEXTURE_2D, ID);
glEnable(GL_TEXTURE_2D);
WaterTexture.SetActive();
glPushMatrix();
glTranslatef(0.0,-0.2,0.0);
glBegin(GL_POLYGON);
for (int i = 0; i<NumOfVerticesStone; i++)
{
glNormal3f(0,1,0);
glTexCoord2f( 0.5+cos(i/GLfloat(NumOfVerticesStone)*360.0*PI/180.0)/2.0,
0.5-sin(i/GLfloat(NumOfVerticesStone)*360.0*PI/180.0)/2.0);
glVertex3fv(&Vertices[i+NumOfVerticesStone].x);
}
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glEndList();
glPopMatrix();
/*float bowlheight = 0.2 + POOL_HEIGHT;
float bowlwidth = 0.2;
float TexBorderDistance = bowlwidth / (MAXX+2*bowlwidth);
GroundTexture.SetActive();
glBegin(GL_QUADS);
float minX = -4.0;
float minZ = -4.0;
float maxX = 8.0;
float maxZ = 8.0;
//******************
//ground
//******************
glNormal3f(0.0f,1.0f,0.0);
glTexCoord2f(0.0,0.0);
glVertex3f(minX,0.0,minZ);
glTexCoord2f(1.0,0.0);
glVertex3f(maxX,0.0,minZ);
glTexCoord2f(1.0,1.0);
glVertex3f(maxX,0.0,maxZ);
glTexCoord2f(0.0,1.0);
glVertex3f(minX,0.0,maxZ);
glEnd();
RockTexture.SetActive();
glBegin(GL_QUADS);
//******************
//top
//******************
glNormal3f(0.0f,1.0f,0.0);
glTexCoord2f(TexBorderDistance,TexBorderDistance);
glVertex3f(0.0f,bowlheight,0.0);
glTexCoord2f(1.0-TexBorderDistance,TexBorderDistance);
glVertex3f(MAXX,bowlheight,0.0);
glTexCoord2f(1.0-TexBorderDistance,0.0);
glVertex3f(MAXX,bowlheight,-bowlwidth);
glTexCoord2f(TexBorderDistance,0.0);
glVertex3f(0.0f,bowlheight,-bowlwidth);
glTexCoord2f(TexBorderDistance,0.0);
glVertex3f(0.0f,bowlheight,-bowlwidth);
glTexCoord2f(0.0,0.0);
glVertex3f(-bowlwidth,bowlheight,-bowlwidth);
glTexCoord2f(0.0,1.0-TexBorderDistance);
glVertex3f(-bowlwidth,bowlheight,MAXZ);
glTexCoord2f(TexBorderDistance,1.0-TexBorderDistance);
glVertex3f(0.0f,bowlheight,MAXZ);
/*
glTexCoord2f(1.0,0.0);
glVertex3f(MAXX+bowlwidth,bowlheight,-bowlwidth);
glTexCoord2f(1.0-TexBorderDistance,0.0);
glVertex3f(MAXX,bowlheight,-bowlwidth);
glTexCoord2f(1.0-TexBorderDistance,1.0-TexBorderDistance);
glVertex3f(MAXX,bowlheight,MAXZ);
glTexCoord2f(1.0,1.0-TexBorderDistance);
glVertex3f(MAXX+bowlwidth,bowlheight,MAXZ);
glTexCoord2f(1.0,1.0-TexBorderDistance);
glVertex3f(MAXX+bowlwidth,bowlheight,MAXZ);
glTexCoord2f(0.0,1.0-TexBorderDistance);
glVertex3f(-bowlwidth,bowlheight,MAXZ);
glTexCoord2f(0.0,1.0);
glVertex3f(-bowlwidth,bowlheight,MAXZ+bowlwidth);
glTexCoord2f(1.0,1.0);
glVertex3f(MAXX+bowlwidth,bowlheight,MAXZ+bowlwidth);
//******************
//front
//******************
glNormal3f(0.0f,0.0f,1.0f);
glTexCoord2f(TexBorderDistance,TexBorderDistance);
glVertex3f(0.0f,bowlheight,0.0);
glTexCoord2f(1.0-TexBorderDistance,TexBorderDistance);
glVertex3f(MAXX,bowlheight,0.0);
glTexCoord2f(1.0-TexBorderDistance,0.0);
glVertex3f(MAXX,0.0f,0.0);
glTexCoord2f(TexBorderDistance,0.0);
glVertex3f(0.0f,0.0f,0.0);
glTexCoord2f(0.0,1.0-TexBorderDistance);
glVertex3f(-bowlwidth,bowlheight,MAXZ+bowlwidth);
glTexCoord2f(1.0,1.0-TexBorderDistance);
glVertex3f(MAXX+bowlwidth,bowlheight,MAXZ+bowlwidth);
glTexCoord2f(1.0,1.0);
glVertex3f(MAXX+bowlwidth,0.0f,MAXZ+bowlwidth);
glTexCoord2f(0.0,1.0);
glVertex3f(-bowlwidth,0.0f,MAXZ+bowlwidth);
//******************
//back
//******************
glNormal3f(0.0,0.0,-1.0f);
glTexCoord2f(TexBorderDistance,TexBorderDistance);
glVertex3f(0.0f,bowlheight,MAXZ);
glTexCoord2f(1.0-TexBorderDistance,TexBorderDistance);
glVertex3f(MAXX,bowlheight,MAXZ);
glTexCoord2f(1.0-TexBorderDistance,0.0);
glVertex3f(MAXX,0.0f,MAXZ);
glTexCoord2f(TexBorderDistance,0.0);
glVertex3f(0.0f,0.0f,MAXZ);
glTexCoord2f(0.0,1.0-TexBorderDistance);
glVertex3f(-bowlwidth,bowlheight,-bowlwidth);
glTexCoord2f(1.0,1.0-TexBorderDistance);
glVertex3f(MAXX+bowlwidth,bowlheight,-bowlwidth);
glTexCoord2f(1.0,1.0);
glVertex3f(MAXX+bowlwidth,0.0f,-bowlwidth);
glTexCoord2f(0.0,1.0);
glVertex3f(-bowlwidth,0.0f,-bowlwidth);
//******************
//side
//******************
glNormal3f(-1.0,0.0,0.0);
glTexCoord2f(1.0-TexBorderDistance,TexBorderDistance);
glVertex3f(MAXX,bowlheight,0.0);
glTexCoord2f(1.0,1.0-TexBorderDistance);
glVertex3f(MAXX,bowlheight,MAXZ);
glTexCoord2f(1.0-TexBorderDistance,1.0-TexBorderDistance);
glVertex3f(MAXX,0.0f,MAXZ);
glTexCoord2f(1.0,TexBorderDistance);
glVertex3f(MAXX,0.0f,0.0);
glTexCoord2f(0.0,0.0);
glVertex3f(-bowlwidth,bowlheight,-bowlwidth);
glTexCoord2f(1.0,0.0);
glVertex3f(-bowlwidth,bowlheight,MAXZ+bowlwidth);
glTexCoord2f(1.0,TexBorderDistance);
glVertex3f(-bowlwidth,0.0f,MAXZ+bowlwidth);
glTexCoord2f(0.0,TexBorderDistance);
glVertex3f(-bowlwidth,0.0f,-bowlwidth);
glNormal3f(1.0,0.0,0.0);
glTexCoord2f(1.0-TexBorderDistance,0.0);
glVertex3f(0.0f,bowlheight,MAXZ);
glTexCoord2f(TexBorderDistance,0.0);
glVertex3f(0.0f,bowlheight,0.0);
glTexCoord2f(TexBorderDistance,TexBorderDistance);
glVertex3f(0.0f,0.0f,0.0);
glTexCoord2f(1.0-TexBorderDistance,TexBorderDistance);
glVertex3f(0.0f,0.0f,MAXZ);
glTexCoord2f(1.0,1.0);
glVertex3f(MAXX+bowlwidth,bowlheight,MAXZ+bowlwidth);
glTexCoord2f(1.0,0.0);
glVertex3f(MAXX+bowlwidth,bowlheight,-bowlwidth);
glTexCoord2f(1.0-TexBorderDistance,0.0);
glVertex3f(MAXX+bowlwidth,0.0f,-bowlwidth);
glTexCoord2f(1.0-TexBorderDistance,1.0);
glVertex3f(MAXX+bowlwidth,0.0f,MAXZ+bowlwidth);
glEnd();*/
}
void DrawScene(void)
{
//Render the pool
glEnable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
WaterTexture.SetActive();
glPushMatrix();
glTranslatef(0.0,POOL_HEIGHT,0.0);
//Pool.Render();
glPopMatrix();
glPushMatrix();
//Render the bowl
RenderBowl();
glPopMatrix();
// postion of fountain is set
glTranslatef(-1.25,0,-1.2);
glDisable(GL_TEXTURE_2D);
//Render the water in the air.
glEnable(GL_BLEND);
glDisable(GL_LIGHTING);
glColor4f(0.8,0.8,0.8,0.8);
AirFountain.Render();
glDisable(GL_BLEND);
}
void Display(void)
{
turn = turn +10;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
Camera.Render();
//glLightfv(GL_LIGHT0,GL_POSITION,LightPosition);
//Turn two sided lighting on:
//glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
DrawScene();
/*GLfloat position[] = {.5,2,0,1};
GLfloat direction[] = {0,-2,0};
glLightfv(GL_LIGHT0, GL_POSITION, position);
glLighti(GL_LIGHT0, GL_SPOT_CUTOFF, 15);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, direction);
GLfloat position1[] = {-.5,2,0,1};
GLfloat direction1[] = {0,-1,0};
glLightfv(GL_LIGHT1, GL_POSITION, position1);
glLighti(GL_LIGHT1, GL_SPOT_CUTOFF, 15);
glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, direction1);
GLfloat position2[] = {1,1,0,1};
GLfloat direction2[] = {0,-1,0};
glLightfv(GL_LIGHT2, GL_POSITION, position2);
glLighti(GL_LIGHT2, GL_SPOT_CUTOFF, 15);
glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, direction2);
GLfloat position3[] = {.75,1,0,1};
GLfloat direction3[] = {0,-2,0};
glLightfv(GL_LIGHT3, GL_POSITION, position3);
glLighti(GL_LIGHT3, GL_SPOT_CUTOFF, 15);
glLightfv(GL_LIGHT3, GL_SPOT_DIRECTION, direction3);*/
// internal
GLfloat position[] = {1,1,1.5,1};
GLfloat direction[] = {-1,-1,-1.5};
GLfloat diffuse[] = {0,1,0};
GLfloat ambient[] = {0,1,0};
GLfloat specular[] = {0,1,0};
glLightfv(GL_LIGHT0, GL_POSITION, position);
glLighti(GL_LIGHT0, GL_SPOT_CUTOFF, 8);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, direction);
glLightfv(GL_LIGHT0, GL_SPECULAR,specular);
glLightfv(GL_LIGHT0, GL_DIFFUSE,diffuse);
glLightfv(GL_LIGHT0, GL_AMBIENT,ambient);
glEnable(GL_LIGHT0);
// internal
GLfloat position1[] = {2,2,1,1};
GLfloat direction1[] = {-1,-2,-1};
GLfloat diffuse1[] = {0,0,1};
GLfloat ambient1[] = {0,0,1};
GLfloat specular1[] = {0,0,1};
glLightfv(GL_LIGHT1, GL_POSITION, position1);
glLighti(GL_LIGHT1, GL_SPOT_CUTOFF, 10);
glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, direction1);
glLightfv(GL_LIGHT1, GL_SPECULAR,specular1);
glLightfv(GL_LIGHT1, GL_DIFFUSE,diffuse1);
glLightfv(GL_LIGHT1, GL_AMBIENT,ambient1);
glEnable(GL_LIGHT1);
// internal
GLfloat position2[] = {2,2,1,1};
GLfloat direction2[] = {0,-2,-1};
GLfloat diffuse2[] = {1,0,0};
GLfloat ambient2[] = {1,0,0};
GLfloat specular2[] = {1,0,0};
glLightfv(GL_LIGHT2, GL_POSITION, position2);
glLighti(GL_LIGHT2, GL_SPOT_CUTOFF, 10);
glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, direction2);
glLightfv(GL_LIGHT2, GL_SPECULAR,specular2);
glLightfv(GL_LIGHT2, GL_DIFFUSE,diffuse2);
glLightfv(GL_LIGHT2, GL_AMBIENT,ambient2);
glEnable(GL_LIGHT2);
// external
GLfloat position3[] = {-2,-2,-1,1};
GLfloat direction3[] = {3,1,1};
GLfloat diffuse3[] = {.6,.6,0};
GLfloat ambient3[] = {.6,.6,0};
GLfloat specular3[] = {.6,.6,0};
glLightfv(GL_LIGHT3, GL_POSITION, position3);
glLighti(GL_LIGHT3, GL_SPOT_CUTOFF, 30);
glLightfv(GL_LIGHT3, GL_SPOT_DIRECTION, direction3);
glLightfv(GL_LIGHT3, GL_SPECULAR,specular3);
glLightfv(GL_LIGHT3, GL_DIFFUSE,diffuse3);
glLightfv(GL_LIGHT3, GL_AMBIENT,ambient3);
glEnable(GL_LIGHT3);
// external
GLfloat position4[] = {2,-1,-1,1};
GLfloat direction4[] = {-1,1,1};
GLfloat diffuse4[] = {1,0,0};
GLfloat ambient4[] = {1,0,0};
GLfloat specular4[] = {1,0,0};
glLightfv(GL_LIGHT4, GL_POSITION, position4);
glLighti(GL_LIGHT4, GL_SPOT_CUTOFF, 30);
glLightfv(GL_LIGHT4, GL_SPOT_DIRECTION, direction4);
glLightfv(GL_LIGHT4, GL_SPECULAR,specular4);
glLightfv(GL_LIGHT4, GL_DIFFUSE,diffuse4);
glLightfv(GL_LIGHT4, GL_AMBIENT,ambient4);
glEnable(GL_LIGHT4);
//external ambient
GLfloat position5[] = {0,2,2,1};
GLfloat direction5[] = {-3,-2,-2};
// GLfloat position5[] = {-4,6,-6,1};
// GLfloat direction5[] = {-3,-6,-6};
GLfloat diffuse5[] = {0,0,1};
GLfloat ambient5[] = {0,0,1};
GLfloat specular5[] = {0,0,1};
glLightfv(GL_LIGHT5, GL_POSITION, position5);
glLighti(GL_LIGHT5, GL_SPOT_CUTOFF, 30);
glLightfv(GL_LIGHT5, GL_SPOT_DIRECTION, direction5);
glLightfv(GL_LIGHT5, GL_SPECULAR,specular5);
glLightfv(GL_LIGHT5, GL_DIFFUSE,diffuse5);
glLightfv(GL_LIGHT5, GL_AMBIENT,ambient5);
glEnable(GL_LIGHT5);
//external
/* GLfloat position6[] = {2,-1,-1,1};
GLfloat direction6[] = {0,1,1};
GLfloat diffuse6[] = {1,1,0};
GLfloat ambient6[] = {1,1,0};
GLfloat specular6[] = {1,1,0};
glLightfv(GL_LIGHT6, GL_POSITION, position6);
glLighti(GL_LIGHT6, GL_SPOT_CUTOFF, 7);
glLightfv(GL_LIGHT6, GL_SPOT_DIRECTION, direction6);
glLightfv(GL_LIGHT6, GL_SPECULAR,specular6);
glLightfv(GL_LIGHT6, GL_DIFFUSE,diffuse6);
glLightfv(GL_LIGHT6, GL_AMBIENT,ambient6);
glEnable(GL_LIGHT6);*/
glFlush(); ///Finish rendering
glutSwapBuffers();
}
void Reshape(int x, int y)
{
if (y == 0 || x == 0) return; //Nothing is visible then, so return
//Set a new projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Angle of view:40 degrees
//Near clipping plane distance: 0.3
//Far clipping plane distance: 50.0
gluPerspective(40.0,(GLdouble)x/(GLdouble)y,0.3,50.0);
glViewport(0,0,x,y); //Use the whole window for rendering
glMatrixMode(GL_MODELVIEW);
}
void Idle(void)
{
//Do the physical calculation for one step:
float dtime = 0.006;
AirFountain.Update(dtime, &Pool);
Pool.Update(dtime);
//render the scene:
Display();
}
int main (int argc, char **argv)
{
//Initialize GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH );
glutInitWindowSize(600,600);
//Create a window with rendering context and everything else we need
glutCreateWindow("Fountain with simulated water");
//compute the vertices and indices
Pool.Initialize(NUM_X_OSCILLATORS,NUM_Z_OSCILLATORS,OSCILLATOR_DISTANCE,OSCILLATOR_WEIGHT, 0.05, 4.0, 4.0);
//init the airfountain: (look at KeyDown() to see more possibilities of initialization)
//AirFountain.Initialize(3,8,35,76,90,0.5,0.11);
//place it in the center of the pool:
AirFountain.Position = F3dVector(NUM_X_OSCILLATORS*OSCILLATOR_DISTANCE/2.0f,
POOL_HEIGHT,
NUM_Z_OSCILLATORS*OSCILLATOR_DISTANCE/2.0f);
//initialize camera:
Camera.Move(F3dVector(NUM_X_OSCILLATORS*OSCILLATOR_DISTANCE / 2.0,3.0,NUM_X_OSCILLATORS*OSCILLATOR_DISTANCE+4.0));
Camera.RotateX(-20);
//Enable the vertex array functionality:
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
//Switch on solid rendering:
g_bFillModePoints = false;
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_DEPTH_TEST);
//Initialize lighting:
g_bLighting = true;
//glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient);
//glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse);
//glLightfv(GL_LIGHT1, GL_POSITION,LightPosition);
//glEnable(GL_LIGHT1);
/*GLfloat specular[] = {1,0,0,1};
glLightfv(GL_LIGHT0, GL_SPECULAR, specular);
glEnable(GL_LIGHT0);
GLfloat specular[] = {0,0,1,1};
glLightfv(GL_LIGHT1, GL_SPECULAR, specular);
glEnable(GL_LIGHT1);
GLfloat specular[] = {-1,0,0,1};
glLightfv(GL_LIGHT2, GL_SPECULAR, specular);
glEnable(GL_LIGHT2);
GLfloat specular[] = {0,0,-1,1};
glLightfv(GL_LIGHT3, GL_SPECULAR, specular);
glEnable(GL_LIGHT3);*/
//GLfloat position[] = {1,4,3,1};
//GLfloat direction[] = {-1,-4,-3};
//GLfloat specular[] = {1,1,1,1};
//glLightfv(GL_LIGHT0,GL_SPECULAR,specular);
// glLightfv(GL_LIGHT3,GL_SPECULAR,specular);
//glLightfv(GL_LIGHT3, GL_AMBIENT, LightAmbient);
//glLightfv(GL_LIGHT3, GL_DIFFUSE, LightDiffuse);
//glEnable(GL_LIGHT0);
//glEnable(GL_LIGHT2);
//glEnable(GL_LIGHT3);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
//Some general settings:
glClearColor(0.2,0.2,0.7,0.0);
glFrontFace(GL_CCW); //Tell OGL which orientation shall be the front face
glShadeModel(GL_SMOOTH);
//Initialize blending:
glEnable(GL_BLEND);
glPointSize(3.0);
glEnable(GL_POINT_SMOOTH);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//Load the textures:
WaterTexture.LoadFromFile("water.bmp");
RockTexture.LoadFromFile("rock.bmp");
GroundTexture.LoadFromFile("ground.bmp");
//initialize generation of random numbers:
srand((unsigned)time(NULL));
//Assign the two used Msg-routines
glutDisplayFunc(Display);
glutReshapeFunc(Reshape);
glutKeyboardFunc(KeyDown);
glutIdleFunc(Idle);
//Let GLUT get the msgs
glutMainLoop();
//Clean up:
AirFountain.Delete();
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
859
]
]
] |
8adbcf519e258f79b185649e42cbed4dee355c68 | b38ab5dcfb913569fc1e41e8deedc2487b2db491 | /libraries/GLFX/header/Override.hpp | d345cef17c6420ef13f907ddb969eb9a12b6eff7 | [] | no_license | santosh90n/Fury2 | dacec86ab3972952e4cf6442b38e66b7a67edade | 740a095c2daa32d33fdc24cc47145a1c13431889 | refs/heads/master | 2020-03-21T00:44:27.908074 | 2008-10-16T07:09:17 | 2008-10-16T07:09:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,522 | hpp | namespace Override {
struct OverrideParameters {
int count;
const char* key;
int index;
unsigned int p[16];
};
typedef int (Override)(OverrideParameters *Parameters);
};
namespace Tags {
namespace Context {
static const unsigned int KeyIndex = 7;
static const unsigned int Key = 0x4F474C;
static const unsigned int ValueIndex = 6;
};
namespace Framebuffer {
static const unsigned int KeyIndex = 7;
static const unsigned int Key = 0x4F474D;
static const unsigned int ValueIndex = 6;
};
namespace Texture {
static const unsigned int ValueIndex = 5;
};
namespace DC {
static const unsigned int ValueIndex = 4;
};
namespace Pointer {
static const unsigned int ValueIndex = 3;
};
};
#define checkNamedTag(img, name) (SoftFX::GetImageTag(img, Tags::name::KeyIndex) == Tags::name::Key)
#define getNamedTag(img, name) SoftFX::GetImageTag(img, Tags::name::ValueIndex)
#define setNamedTag(img, name, value) SoftFX::SetImageTag(img, Tags::name::ValueIndex, value)
#define setNamedTagAndKey(img, name, value) SoftFX::SetImageTag(img, Tags::name::KeyIndex, Tags::name::Key); \
SoftFX::SetImageTag(img, Tags::name::ValueIndex, value)
#define readParam(type, name, idx) type name = (*((type*)&Parameters->p[idx]))
#define readParamD(type, name, idx, defaultValue) type name; \
{ \
type* temp = ((type*)Parameters->p[idx]); \
if (temp) { \
name = *temp; \
} else { \
name = defaultValue; \
} \
}
#define readParamRect(name, idx, image) FX::Rectangle name; \
{ \
FX::Rectangle* temp = ((FX::Rectangle*)Parameters->p[idx]); \
if (temp) { \
name = *temp; \
} else { \
GetImageRectangle(image, &name);\
} \
}
#define getParam(type, idx) (*((type*)&Parameters->p[idx]))
#define defOverride(name) Export int _##name (Override::OverrideParameters *Parameters)
#define passOverride(name, passTo) Export int _##name (Override::OverrideParameters *Parameters) { \
return _##passTo(Parameters); \
}
#define addOverride(name) SoftFX::AddOverride(#name, _##name)
#define addNamedOverride(name, ptr) SoftFX::AddOverride(#name, _##ptr)
#define removeOverride(name) SoftFX::RemoveOverride(#name, _##name)
#define removeNamedOverride(name, ptr) SoftFX::RemoveOverride(#name, _##ptr)
inline unsigned int va_float(float value) {
return *(reinterpret_cast<unsigned int*>(&value));
}
extern void InstallOverrides();
extern void UninstallOverrides(); | [
"janus@1af785eb-1c5d-444a-bf89-8f912f329d98"
] | [
[
[
1,
77
]
]
] |
2181a4e95ab1552ed3028cdd3d82ffc1854d2e07 | c2c93fc3fd90bd77764ac3016d816a59b2370891 | /Incomplited/Controllable NPC SA-MP 0.3.0/plugin/callbacks.h | 4adae494808b85c93dc9b633722da69901f80281 | [] | no_license | MsEmiNeko/samp-alex009-projects | a1d880ee3116de95c189ef3f79ce43b163b91603 | 9b9517486b28411c8b747fae460266a88d462e51 | refs/heads/master | 2021-01-10T16:22:34.863725 | 2011-04-30T04:01:15 | 2011-04-30T04:01:15 | 43,719,520 | 0 | 1 | null | 2018-01-19T16:55:45 | 2015-10-05T23:23:37 | SourcePawn | UTF-8 | C++ | false | false | 662 | h | /*
* Copyright (C) 2011 Alex009
* License read in license.txt
* Description: callbacks
*/
// SDK
#include "SDK/amx/amx.h"
#include "SDK/plugincommon.h"
// plugin
#include "windows.h"
#include "os.h"
class CCallbacks
{
public:
CCallbacks(MUTEX_IDENTIFY(mutex)) ;
~CCallbacks();
int GetDamage(int npcid,int attacker,float damage,int bpart);
int MovingComplete(int npcid);
int PlaybackEnd(int npcid,int reason);
int Spawn(int npcid);
int Death(int npcid,int killer,int reason);
void CallbacksOnAMXLoad(AMX* amx);
void CallbacksOnAMXUnLoad(AMX* amx);
// vars
AMX* SampObjects[17];
MUTEX_IDENTIFY(CallbackMutex);
}; | [
"[email protected]"
] | [
[
[
1,
32
]
]
] |
e8fbb6f2b45bc706dab5d03ae2d5d41ed1cc5bac | 8ade67ab53907d22e40286b377b86d1b1eeaf6f0 | /tabu/util/util.h | 44da36dd26b38ef601f6f30dfd97ef98623069b8 | [] | no_license | robbywalker/ca-phf-research | 1483d1113abd865347c4f26934d4a5f43cd2e9b2 | 7bce5bde73bd6d7314902687b3323dcaf93941a6 | refs/heads/master | 2021-01-16T18:40:29.238236 | 2011-04-24T18:29:55 | 2011-04-24T18:29:55 | 1,657,333 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | h | #pragma once
namespace util {
int random(int max);
int weightedRandom( int * weights, int total );
int ipow( int base, int exp );
long lpow( long base, int exp );
long factorial( int n );
long choose( int n, int c );
}; | [
"[email protected]"
] | [
[
[
1,
13
]
]
] |
36b3a60b4738b966548ef4b6c39dfd66039b9d87 | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /InformationProviders/DirImageInfoProvider/DirImageInfoProvider.h | d8a1b1230b215b75f4dd6298255e7712da33fab7 | [] | no_license | outcast1000/Jaangle | 062c7d8d06e058186cb65bdade68a2ad8d5e7e65 | 18feb537068f1f3be6ecaa8a4b663b917c429e3d | refs/heads/master | 2020-04-08T20:04:56.875651 | 2010-12-25T10:44:38 | 2010-12-25T10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,001 | h | // /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.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, 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 GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
#ifndef _DirImageInfoProvider_H_
#define _DirImageInfoProvider_H_
#include "../InfoProvider.h"
#include <string>
#include <vector>
class SQLManager;
#ifdef _UNITTESTING
BOOL TestDirImageInfoProvider();
#endif
class DirImageInfoProvider:public IInfoProvider
{
#ifdef _UNITTESTING
public:
static BOOL UnitTest();
#endif
public:
DirImageInfoProvider();
virtual ~DirImageInfoProvider();
virtual IInfoProvider* Clone() const;
virtual BOOL OpenRequest(const Request& request);
virtual BOOL GetNextResult(Result& result);
virtual const Request& GetRequest() {return m_request;}
virtual BOOL AddResult(const Result& result) {return FALSE;}
virtual BOOL DeleteResult() {return FALSE;}
virtual BOOL CanHandle(ServiceEnum service) const;
virtual LPCTSTR GetModuleInfo(ModuleInfo mi) const;
virtual void SetInternetHandle(LPVOID hInternet) {}
virtual LPVOID GetInternetHandle() const {return NULL;}
//=== IConfigurable
virtual BOOL GetSettingInfo(INT settingIndex, IConfigurable::SettingInfo& setting) const;
virtual INT GetIntSetting(INT settingIndex) const;
virtual LPCTSTR GetLPCTSTRSetting(INT settingIndex) const {return NULL;}
virtual void SetIntSetting(INT settingIndex, INT intVal);
virtual void SetLPCTSTRSetting(INT settingIndex, LPCTSTR strVal) {}
void SetSQLManager(SQLManager* pSM) {m_pSQLManager = pSM;}
private:
SQLManager* m_pSQLManager;
INT m_curResult;
Request m_request;
std::basic_string<TCHAR> m_Artist;
std::basic_string<TCHAR> m_Album;
std::vector<std::basic_string<TCHAR> > m_results;
BOOL IsLegalPicture(LPCTSTR path, LPCTSTR albumName, BOOL bStrict);
static BOOL IsIncluded(LPCTSTR strMain, LPCTSTR strFind, BOOL bIgnoreCase, LPCTSTR excludedCharacters);
static BOOL HasMoreThanXFilesWithMinSizeY(LPCTSTR path, UINT maxNumFiles, UINT minFileSize);
BOOL GetFirstFileByArtistAlbum(LPTSTR path, LPCTSTR artist, LPCTSTR album);
INT m_StrictCriteriaMaxFilesNum;
INT m_StrictCriteriaMaxFilesSize;
};
#endif
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
] | [
[
[
1,
91
]
]
] |
6ff37c07aeb3553d243a61dd956f1c276ca59a65 | 8d466583574663248d9197c83d490f8de6914f01 | /George.Koshelev/calculator/IntegerValue.h | 30019afc4a3c4fc299cefd90f2d3e343957bab05 | [] | no_license | andrey-malets/usuoop | 186b421080d7ff1fbaed2b230f2f2c77eb081138 | 5ae5876f3622ab8a4598a67a414d544c4d6a7bcb | refs/heads/master | 2021-01-25T10:15:48.239369 | 2011-06-18T08:03:42 | 2011-06-18T08:03:42 | 32,697,629 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,413 | h | #include "AValue.h"
#include "DivizionByZero.h"
class IntegerValue : public AbstractValue
{
private:
size_t value;
public:
IntegerValue(int);
virtual void print();
AbstractValue* add(const AbstractValue&) const;
AbstractValue* sub(const AbstractValue&) const;
AbstractValue* mul(const AbstractValue&) const;
AbstractValue* div(const AbstractValue&) const;
virtual ~IntegerValue();
size_t getValue() const;
};
void IntegerValue::print(){
std::cout<<this->value;
}
IntegerValue::IntegerValue(int val){
this->value = val;
}
size_t IntegerValue::getValue() const{
return value;
}
IntegerValue::~IntegerValue(){};
AbstractValue* IntegerValue::add(const AbstractValue& operand) const {
return new IntegerValue(this->value + static_cast <const IntegerValue*> (&operand)->getValue());
}
AbstractValue* IntegerValue::sub(const AbstractValue& operand) const {
return new IntegerValue(this->value - static_cast <const IntegerValue*> (&operand)->getValue());
}
AbstractValue* IntegerValue::mul(const AbstractValue& operand) const {
return new IntegerValue(this->value * static_cast <const IntegerValue*> (&operand)->getValue());
}
AbstractValue* IntegerValue::div(const AbstractValue& operand) const {
int temp = static_cast <const IntegerValue*> (&operand)->getValue();
if (temp == 0) {throw DivisionByZeroException();}
return new IntegerValue(this->value / temp);
}
| [
"george.koshelev@fe86108a-a7a1-bde3-b2d4-a6a6cc998503"
] | [
[
[
1,
41
]
]
] |
aad189ac6ab0d509025399baccc2df116f8b1ad5 | caadedeea99d88ac6cfd6b367c034e18d031ff37 | /ua.cpp | b75c7f15847a5a63727cc8a70c2c47b54030368d | [] | no_license | rjp/edf-nodejs | fc1e0b2548bddaf1d6276b11dc591f2492f37a0d | f9af948081b2538147b2cbb44791296d390072c5 | refs/heads/master | 2021-01-19T22:33:32.404998 | 2011-06-12T10:31:24 | 2011-06-12T10:31:24 | 861,237 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,114 | cpp | /*
** UNaXcess II Conferencing System
** (c) 1998 Michael Wood ([email protected])
**
** Concepts based on Bradford UNaXcess (c) 1984-87 Brandon S Allbery
** Extensions (c) 1989, 1990 Andrew G Minter
** Manchester UNaXcess extensions by Rob Partington, Gryn Davies,
** Michael Wood, Andrew Armitage, Francis Cook, Brian Widdas
**
** The look and feel was reproduced. No code taken from the original
** UA was someone else's inspiration. Copyright and 'nuff respect due
**
** ua.cpp: Implmentation for common UA functions
*/
#include "stdafx.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "useful/useful.h"
#include "ua.h"
bool NameValid(const char *szName)
{
int iCharPos = 1;
// printf("NameValid %s\n", szName);
if(szName == NULL)
{
// printf("NameValid exit false, NULL\n");
return false;
}
if(strlen(szName) == 0 || strlen(szName) > UA_NAME_LEN)
{
// printf("NameValid exit false, too long\n");
return false;
}
if(!isalpha(szName[0]))
{
// printf("NameValid exit false, non-alpha first char\n");
return false;
}
while(szName[iCharPos] != '\0')
{
if(!isalnum(szName[iCharPos]) && strchr(".,' @-_!", szName[iCharPos]) == NULL)
{
// printf("NameValid exit false, invalid char %d\n", iCharPos);
return false;
}
else
{
iCharPos++;
}
}
if(szName[iCharPos - 1] == ' ')
{
// printf("NameValid exit false, space last char\n");
return false;
}
// printf(". exit true\n");
return true;
}
// AccessName: Convert numerical access level into character string
char *AccessName(int iLevel, int iType)
{
if(iType != -1 && iType == USERTYPE_AGENT)
{
return "Agent";
}
switch(iLevel)
{
case LEVEL_NONE:
return "None";
case LEVEL_GUEST:
return "Guest";
case LEVEL_MESSAGES:
return "Messages";
case LEVEL_EDITOR:
return "Editor";
case LEVEL_WITNESS:
return "Witness";
case LEVEL_SYSOP:
return "SysOp";
}
return "";
}
char *SubTypeStr(int iSubType)
{
STACKTRACE
if(iSubType == SUBTYPE_EDITOR)
{
return SUBNAME_EDITOR;
}
else if(iSubType == SUBTYPE_MEMBER)
{
return SUBNAME_MEMBER;
}
else if(iSubType == SUBTYPE_SUB)
{
return SUBNAME_SUB;
}
return "";
}
int SubTypeInt(const char *szSubType)
{
STACKTRACE
if(stricmp(szSubType, SUBNAME_EDITOR) == 0)
{
return SUBTYPE_EDITOR;
}
else if(stricmp(szSubType, SUBNAME_MEMBER) == 0)
{
return SUBTYPE_MEMBER;
}
else if(stricmp(szSubType, SUBNAME_SUB) == 0)
{
return SUBTYPE_SUB;
}
return -1;
}
int ProtocolVersion(const char *szVersion)
{
return ProtocolCompare(PROTOCOL, szVersion);
}
int ProtocolCompare(const char *szVersion1, const char *szVersion2)
{
return stricmp(szVersion1, szVersion2);
}
| [
"[email protected]"
] | [
[
[
1,
151
]
]
] |
759a1e192cd8a9a46fa21fb5874677469d2fe1bf | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/lvcards.h | f667ad00d49625cf6ac5ca6e60ce8cf71e54be1f | [] | no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | h | class lvcards_state : public driver_device
{
public:
lvcards_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
UINT8 m_payout;
UINT8 m_pulse;
UINT8 m_result;
UINT8 *m_videoram;
UINT8 *m_colorram;
tilemap_t *m_bg_tilemap;
};
/*----------- defined in video/lvcards.c -----------*/
WRITE8_HANDLER( lvcards_videoram_w );
WRITE8_HANDLER( lvcards_colorram_w );
PALETTE_INIT( lvcards );
PALETTE_INIT( ponttehk );
VIDEO_START( lvcards );
SCREEN_UPDATE( lvcards );
| [
"Mike@localhost"
] | [
[
[
1,
24
]
]
] |
6f9008502b356c04a082c7d53af57ead0eaaccb8 | c9efecddc566c701b4b24b9d0997eb3cf929e5f5 | /OgreMetaballs/MetaballsAbstractScene.h | 177dde59d5f9bae403fa9989e170bc567d07e3ca | [] | no_license | vlalo001/metaballs3d | f8ee9404f28cda009654f8edf2f322c72d5bfe8a | a24fddce4ec73fc7348287e2074268cc2920cc2f | refs/heads/master | 2021-01-20T16:56:20.721059 | 2009-07-24T16:33:36 | 2009-07-24T16:33:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 596 | h | #pragma once
//-----------------------------------
// Forward declarations
//-----------------------------------
class ScalarField3D;
//-----------------------------------
// MetaballsAbstractScene
//-----------------------------------
class MetaballsAbstractScene
{
public:
MetaballsAbstractScene();
virtual ~MetaballsAbstractScene();
virtual void CreateFields() = 0;
virtual void UpdateFields(float time) = 0;
virtual const ScalarField3D* GetScalarField() const = 0;
virtual float GetSceneSize() const = 0;
virtual float GetSpaceResolution() const = 0;
};
| [
"garry.wls@99a8374a-4571-11de-aeda-3f4d37dfb5fa"
] | [
[
[
1,
25
]
]
] |
d7be1961077dce42f6f842c3a3569f61b69dfac6 | 2e8adfe9e0e8e6bceb7f7b20c73a66ddddc2b60e | /ThorConfigComponent.h | d75b9e896f42711c124a80084186c382e1493c15 | [] | no_license | j3LLostyL3Z/thor-v2 | ee898f9e11023b40e0100f16150fe026dd863f24 | c4555a347a7f833780bc0b65f039397f3787a4c2 | refs/heads/master | 2021-01-10T10:25:51.677372 | 2009-02-06T12:32:34 | 2009-02-06T12:32:34 | 49,520,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,122 | h | /*
==============================================================================
This is an automatically generated file created by the Jucer!
Creation date: 12 May 2008 3:16:52 pm
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Jucer version: 1.11
------------------------------------------------------------------------------
The Jucer is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-6 by Raw Material Software ltd.
==============================================================================
*/
#ifndef __JUCER_HEADER_THORCONFIGCOMPONENT_THORCONFIGCOMPONENT_B43A9D4E__
#define __JUCER_HEADER_THORCONFIGCOMPONENT_THORCONFIGCOMPONENT_B43A9D4E__
//[Headers] -- You can add your own extra header files here --
#include "juce.h"
#include "ThorConfig.h"
#include "ThorAbout.h"
//[/Headers]
//==============================================================================
/**
//[Comments]
An auto-generated component, created by the Jucer.
Describe your class and how it works here!
//[/Comments]
*/
class ThorConfigComponent : public Component,
public ComboBoxListener,
public ButtonListener
{
public:
//==============================================================================
ThorConfigComponent (ThorConfig *_config);
~ThorConfigComponent();
//==============================================================================
//[UserMethods] -- You can add your own custom methods in this section.
//[/UserMethods]
void paint (Graphics& g);
void resized();
void comboBoxChanged (ComboBox* comboBoxThatHasChanged);
void buttonClicked (Button* buttonThatWasClicked);
// Binary resources:
static const char* vorbis_png;
static const int vorbis_pngSize;
//==============================================================================
juce_UseDebuggingNewOperator
private:
//[UserVariables] -- You can add your own custom variables in this section.
ThorConfig *config;
//[/UserVariables]
//==============================================================================
Label* label;
ComboBox* thorConfigEncodeFormat;
Label* label2;
ComboBox* thorOggQuality;
ToggleButton* thorVersionCheck;
Label* label3;
ComboBox* thorOutputAction;
Image* internalCachedImage1;
//==============================================================================
// (prevent copy constructor and operator= being generated..)
ThorConfigComponent (const ThorConfigComponent&);
const ThorConfigComponent& operator= (const ThorConfigComponent&);
};
#endif // __JUCER_HEADER_THORCONFIGCOMPONENT_THORCONFIGCOMPONENT_B43A9D4E__
| [
"kubiak.roman@f386313e-e04c-0410-8915-733321d37a57"
] | [
[
[
1,
88
]
]
] |
26213dc874e15d3e1dad6ca403bc8c2f0959625f | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/singleplayer/ricochet/dlls/mpstubb.cpp | b01e53b62b149fac71240e6e97818d2f23a44a7e | [] | no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,885 | cpp | /***
*
* Copyright (c) 1999, 2000 Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "monsters.h"
#include "soundent.h"
#include "nodes.h"
#include "talkmonster.h"
float CTalkMonster::g_talkWaitTime = 0; // time delay until it's ok to speak: used so that two NPCs don't talk at once
/*********************************************************/
CGraph WorldGraph;
void CGraph :: InitGraph( void ) { }
int CGraph :: FLoadGraph ( char *szMapName ) { return FALSE; }
int CGraph :: AllocNodes ( void ) { return FALSE; }
int CGraph :: CheckNODFile ( char *szMapName ) { return FALSE; }
int CGraph :: FSetGraphPointers ( void ) { return 0; }
void CGraph :: ShowNodeConnections ( int iNode ) { }
int CGraph :: FindNearestNode ( const Vector &vecOrigin, int afNodeTypes ) { return 0; }
/*********************************************************/
void CBaseMonster :: ReportAIState( void ) { }
float CBaseMonster :: ChangeYaw ( int speed ) { return 0; }
void CBaseMonster :: MakeIdealYaw( Vector vecTarget ) { }
void CBaseMonster::CorpseFallThink( void )
{
if ( pev->flags & FL_ONGROUND )
{
SetThink ( NULL );
SetSequenceBox( );
UTIL_SetOrigin( pev, pev->origin );// link into world.
}
else
pev->nextthink = gpGlobals->time + 0.1;
}
// Call after animation/pose is set up
void CBaseMonster :: MonsterInitDead( void )
{
InitBoneControllers();
pev->solid = SOLID_BBOX;
pev->movetype = MOVETYPE_TOSS;// so he'll fall to ground
pev->frame = 0;
ResetSequenceInfo( );
pev->framerate = 0;
// Copy health
pev->max_health = pev->health;
pev->deadflag = DEAD_DEAD;
UTIL_SetSize(pev, g_vecZero, g_vecZero );
UTIL_SetOrigin( pev, pev->origin );
// Setup health counters, etc.
BecomeDead();
SetThink( CorpseFallThink );
pev->nextthink = gpGlobals->time + 0.5;
}
BOOL CBaseMonster :: ShouldFadeOnDeath( void )
{
return FALSE;
}
BOOL CBaseMonster :: FCheckAITrigger ( void )
{
return FALSE;
}
void CBaseMonster :: KeyValue( KeyValueData *pkvd )
{
CBaseToggle::KeyValue( pkvd );
}
int CBaseMonster::IRelationship ( CBaseEntity *pTarget )
{
static int iEnemy[14][14] =
{ // NONE MACH PLYR HPASS HMIL AMIL APASS AMONST APREY APRED INSECT PLRALY PBWPN ABWPN
/*NONE*/ { R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO, R_NO, R_NO },
/*MACHINE*/ { R_NO ,R_NO ,R_DL ,R_DL ,R_NO ,R_DL ,R_DL ,R_DL ,R_DL ,R_DL ,R_NO ,R_DL, R_DL, R_DL },
/*PLAYER*/ { R_NO ,R_DL ,R_NO ,R_NO ,R_DL ,R_DL ,R_DL ,R_DL ,R_DL ,R_DL ,R_NO ,R_NO, R_DL, R_DL },
/*HUMANPASSIVE*/{ R_NO ,R_NO ,R_AL ,R_AL ,R_HT ,R_FR ,R_NO ,R_HT ,R_DL ,R_FR ,R_NO ,R_AL, R_NO, R_NO },
/*HUMANMILITAR*/{ R_NO ,R_NO ,R_HT ,R_DL ,R_NO ,R_HT ,R_DL ,R_DL ,R_DL ,R_DL ,R_NO ,R_HT, R_NO, R_NO },
/*ALIENMILITAR*/{ R_NO ,R_DL ,R_HT ,R_DL ,R_HT ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_DL, R_NO, R_NO },
/*ALIENPASSIVE*/{ R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO, R_NO, R_NO },
/*ALIENMONSTER*/{ R_NO ,R_DL ,R_DL ,R_DL ,R_DL ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_NO ,R_DL, R_NO, R_NO },
/*ALIENPREY */{ R_NO ,R_NO ,R_DL ,R_DL ,R_DL ,R_NO ,R_NO ,R_NO ,R_NO ,R_FR ,R_NO ,R_DL, R_NO, R_NO },
/*ALIENPREDATO*/{ R_NO ,R_NO ,R_DL ,R_DL ,R_DL ,R_NO ,R_NO ,R_NO ,R_HT ,R_DL ,R_NO ,R_DL, R_NO, R_NO },
/*INSECT*/ { R_FR ,R_FR ,R_FR ,R_FR ,R_FR ,R_NO ,R_FR ,R_FR ,R_FR ,R_FR ,R_NO ,R_FR, R_NO, R_NO },
/*PLAYERALLY*/ { R_NO ,R_DL ,R_AL ,R_AL ,R_DL ,R_DL ,R_DL ,R_DL ,R_DL ,R_DL ,R_NO ,R_NO, R_NO, R_NO },
/*PBIOWEAPON*/ { R_NO ,R_NO ,R_DL ,R_DL ,R_DL ,R_DL ,R_DL ,R_DL ,R_DL ,R_DL ,R_NO ,R_DL, R_NO, R_DL },
/*ABIOWEAPON*/ { R_NO ,R_NO ,R_DL ,R_DL ,R_DL ,R_AL ,R_NO ,R_DL ,R_DL ,R_NO ,R_NO ,R_DL, R_DL, R_NO }
};
return iEnemy[ Classify() ][ pTarget->Classify() ];
}
//=========================================================
// Look - Base class monster function to find enemies or
// food by sight. iDistance is distance ( in units ) that the
// monster can see.
//
// Sets the sight bits of the m_afConditions mask to indicate
// which types of entities were sighted.
// Function also sets the Looker's m_pLink
// to the head of a link list that contains all visible ents.
// (linked via each ent's m_pLink field)
//
//=========================================================
void CBaseMonster :: Look ( int iDistance )
{
int iSighted = 0;
// DON'T let visibility information from last frame sit around!
ClearConditions(bits_COND_SEE_HATE | bits_COND_SEE_DISLIKE | bits_COND_SEE_ENEMY | bits_COND_SEE_FEAR | bits_COND_SEE_NEMESIS | bits_COND_SEE_CLIENT);
m_pLink = NULL;
CBaseEntity *pSightEnt = NULL;// the current visible entity that we're dealing with
CBaseEntity *pList[100];
Vector delta = Vector( iDistance, iDistance, iDistance );
// Find only monsters/clients in box, NOT limited to PVS
int count = UTIL_EntitiesInBox( pList, 100, pev->origin - delta, pev->origin + delta, FL_CLIENT|FL_MONSTER );
for ( int i = 0; i < count; i++ )
{
pSightEnt = pList[i];
if ( pSightEnt != this && pSightEnt->pev->health > 0 )
{
// the looker will want to consider this entity
// don't check anything else about an entity that can't be seen, or an entity that you don't care about.
if ( IRelationship( pSightEnt ) != R_NO && FInViewCone( pSightEnt ) && !FBitSet( pSightEnt->pev->flags, FL_NOTARGET ) && FVisible( pSightEnt ) )
{
if ( pSightEnt->IsPlayer() )
{
// if we see a client, remember that (mostly for scripted AI)
iSighted |= bits_COND_SEE_CLIENT;
}
pSightEnt->m_pLink = m_pLink;
m_pLink = pSightEnt;
if ( pSightEnt == m_hEnemy )
{
// we know this ent is visible, so if it also happens to be our enemy, store that now.
iSighted |= bits_COND_SEE_ENEMY;
}
// don't add the Enemy's relationship to the conditions. We only want to worry about conditions when
// we see monsters other than the Enemy.
switch ( IRelationship ( pSightEnt ) )
{
case R_NM:
iSighted |= bits_COND_SEE_NEMESIS;
break;
case R_HT:
iSighted |= bits_COND_SEE_HATE;
break;
case R_DL:
iSighted |= bits_COND_SEE_DISLIKE;
break;
case R_FR:
iSighted |= bits_COND_SEE_FEAR;
break;
case R_AL:
break;
default:
ALERT ( at_aiconsole, "%s can't assess %s\n", STRING(pev->classname), STRING(pSightEnt->pev->classname ) );
break;
}
}
}
}
SetConditions( iSighted );
}
//=========================================================
// BestVisibleEnemy - this functions searches the link
// list whose head is the caller's m_pLink field, and returns
// a pointer to the enemy entity in that list that is nearest the
// caller.
//
// !!!UNDONE - currently, this only returns the closest enemy.
// we'll want to consider distance, relationship, attack types, back turned, etc.
//=========================================================
CBaseEntity *CBaseMonster :: BestVisibleEnemy ( void )
{
CBaseEntity *pReturn;
CBaseEntity *pNextEnt;
int iNearest;
int iDist;
int iBestRelationship;
iNearest = 8192;// so first visible entity will become the closest.
pNextEnt = m_pLink;
pReturn = NULL;
iBestRelationship = R_NO;
while ( pNextEnt != NULL )
{
if ( pNextEnt->IsAlive() )
{
if ( IRelationship( pNextEnt) > iBestRelationship )
{
// this entity is disliked MORE than the entity that we
// currently think is the best visible enemy. No need to do
// a distance check, just get mad at this one for now.
iBestRelationship = IRelationship ( pNextEnt );
iNearest = ( pNextEnt->pev->origin - pev->origin ).Length();
pReturn = pNextEnt;
}
else if ( IRelationship( pNextEnt) == iBestRelationship )
{
// this entity is disliked just as much as the entity that
// we currently think is the best visible enemy, so we only
// get mad at it if it is closer.
iDist = ( pNextEnt->pev->origin - pev->origin ).Length();
if ( iDist <= iNearest )
{
iNearest = iDist;
iBestRelationship = IRelationship ( pNextEnt );
pReturn = pNextEnt;
}
}
}
pNextEnt = pNextEnt->m_pLink;
}
return pReturn;
}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
] | [
[
[
1,
264
]
]
] |
91e64bfa01f1d8bca66e2d90bddf96eebcf7bf92 | 6630a81baef8700f48314901e2d39141334a10b7 | /1.4/Testing/Cxx/swWxGuiTesting/swCRCppEmitter.cpp | c75bf1b40962a77d7f2dca47f375c05850e267c1 | [] | no_license | jralls/wxGuiTesting | a1c0bed0b0f5f541cc600a3821def561386e461e | 6b6e59e42cfe5b1ac9bca02fbc996148053c5699 | refs/heads/master | 2021-01-10T19:50:36.388929 | 2009-03-24T20:22:11 | 2009-03-26T18:51:24 | 623,722 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 13,311 | cpp | ///////////////////////////////////////////////////////////////////////////////
// Name: swWxGuiTesting/swCRCppEmitter.cpp
// Author: Reinhold Füreder
// Created: 2004
// Copyright: (c) 2005 Reinhold Füreder
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "swCRCppEmitter.h"
#endif
#include "swCRCppEmitter.h"
#include "swWxLogicErrorException.h"
namespace swTst {
// Init single instance:
CRCppEmitter *CRCppEmitter::ms_instance = NULL;
CRCppEmitter::CRCppEmitter ()
{
this->SetTabSize (4);
m_maxChars = 80;
}
CRCppEmitter::~CRCppEmitter ()
{
// Finish copying file after capture keyword:
while (!m_origFile.Eof ()) {
wxString line = m_origFile.GetNextLine ();
m_newFile.AddLine (line);
}
m_origFile.Close ();
m_newFile.Write ();
m_newFile.Close ();
m_contMap.clear ();
m_varNameSet.clear ();
}
CRCppEmitter * CRCppEmitter::GetInstance ()
{
if (ms_instance == NULL) {
ms_instance = new CRCppEmitter ();
}
return ms_instance;
}
void CRCppEmitter::Destroy ()
{
if (ms_instance != NULL) {
delete ms_instance;
ms_instance = NULL;
}
}
void CRCppEmitter::SetTabSize (unsigned int size)
{
m_tab = wxString (' ', size);
}
unsigned int CRCppEmitter::GetTabSize () const
{
return m_tab.Length ();
}
wxString CRCppEmitter::GetTab () const
{
return m_tab;
}
void CRCppEmitter::SetTestCaseFileContext (const wxString &filename, int lineNmb)
{
wxASSERT (::wxFileExists (filename));
wxASSERT (lineNmb != 0);
if (!m_origFile.Open (filename)) {
throw new sw::WxLogicErrorException (wxString::Format ("%s: %s",
_("Could not open test case file"), filename.c_str ()));
}
// Find unique filename with prefix of current test case filename in order
// to prevent file overwritting and create "backup" files, plus allow
// debugging without side effects:
wxString newFilename;
unsigned int uniqueCnt = 0;
do {
uniqueCnt++;
newFilename = wxString::Format ("%s.cr%d", filename.c_str (), uniqueCnt);
} while (::wxFileExists (newFilename));
if (!m_newFile.Create (newFilename)) {
throw new sw::WxLogicErrorException (wxString::Format ("%s: %s",
_("Could not create bootstrap test case file"), filename.c_str ()));
}
// Copy old file until line number or first occurence of capture keyword:
const wxString CAPTURE_KEYWORD = "CAPTURE";
bool isDone = false;
wxString line = m_origFile.GetFirstLine ();
while ((!isDone) && (!m_origFile.Eof ())) {
if (lineNmb >= 0) {
if ((lineNmb - 1) <= m_origFile.GetCurrentLine ()) {
isDone = true;
}
} else {
wxString stripped = line.Strip (wxString::both);
if (CAPTURE_KEYWORD == stripped) {
isDone = true;
}
}
if (!isDone) {
m_newFile.AddLine (line);
line = m_origFile.GetNextLine ();
}
}
// Write out current file - but is not finished yet:
m_newFile.Write ();
}
wxString CRCppEmitter::GetCaptureFilename() const {
return m_newFile.GetName ();
}
void CRCppEmitter::AddComment (wxString str)
{
wxArrayString COMMENT_BREAK_CHARS;
COMMENT_BREAK_CHARS.Add (" ");
COMMENT_BREAK_CHARS.Add (",");
COMMENT_BREAK_CHARS.Add (".");
COMMENT_BREAK_CHARS.Add (":");
COMMENT_BREAK_CHARS.Add ("!");
COMMENT_BREAK_CHARS.Add ("?");
wxString pre = m_tab + "// ";
const unsigned int MIN_CONTENT_LEN = 20;
str.Prepend (pre);
unsigned int idx;
do {
m_newFile.AddLine (this->BreakString (str, COMMENT_BREAK_CHARS, idx,
pre.Length () + MIN_CONTENT_LEN));
if (idx != 0) {
str = str.Mid (idx);
str.Prepend (pre);
}
} while (idx != 0);
// Again, flush current file status (but not finished yet):
m_newFile.Write ();
}
void CRCppEmitter::AddCode (wxString str)
{
wxArrayString CODE_BREAK_CHARS;
CODE_BREAK_CHARS.Add (" ");
CODE_BREAK_CHARS.Add (",");
CODE_BREAK_CHARS.Add (".");
CODE_BREAK_CHARS.Add ("(");
CODE_BREAK_CHARS.Add ("::");
CODE_BREAK_CHARS.Add ("->");
wxString pre = m_tab;
const unsigned int MIN_CONTENT_LEN = 20;
str.Prepend (pre);
bool isInString = false;
unsigned int idx;
do {
wxString line = this->BreakString (str, CODE_BREAK_CHARS, idx,
pre.Length () + MIN_CONTENT_LEN, true);
// Don't break line within string constants, use line splicing instead:
isInString = this->HasBrokenInString (line);
if (isInString) {
line.Append ("\"");
}
m_newFile.AddLine (line);
if (idx != 0) {
str = str.Mid (idx);
// Change string literal line splicing from appending "\" to end with
// "\"" and start next line with "\"":
if (isInString) {
str.Prepend ("\"");
}
for (int i = 0; i < 3; i++) {
str.Prepend (pre);
}
}
} while (idx != 0);
// Again, flush current file status (but not finished yet):
m_newFile.Write ();
}
void CRCppEmitter::AddVerbatimStringWithLineBreaks (wxString str)
{
m_newFile.AddLine (str);
// Again, flush current file status (but not finished yet):
m_newFile.Write ();
}
wxString CRCppEmitter::AddContainerLookupCode (const wxString &containerName,
const wxString &itemDesc, const wxString &containerVarNameSuffix)
{
// Look if container lookup code has already been emitted:
ContainerMap::iterator it = m_contMap.find (containerName);
if (it != m_contMap.end ()) {
return it->second;
}
// Has not been emitted yet!
// Make first letter of container variable name lower case:
wxString containerVarName = containerName + containerVarNameSuffix;
char &firstChar = containerVarName.GetWritableChar (0);
firstChar = tolower (firstChar);
// Make container variable name unique:
unsigned int cnt = 0;
wxString uniqueContainerVarName = containerVarName;
while ((this->IsContainerVarNameDuplicate (uniqueContainerVarName)) ||
(m_varNameSet.find (uniqueContainerVarName) != m_varNameSet.end ())) {
cnt++;
uniqueContainerVarName = wxString::Format ("%s%d", containerVarName.c_str (), cnt);
}
m_contMap[containerName] = uniqueContainerVarName;
m_varNameSet.insert (uniqueContainerVarName);
// And acutal emitting:
wxString lookup, assert;
lookup << "wxWindow *" << uniqueContainerVarName << " = wxWindow::FindWindowByName (\"" << containerName << "\");";
this->AddCode (lookup);
assert << "CPPUNIT_ASSERT_MESSAGE (\"Container window ";
if (itemDesc.IsEmpty ()) {
assert << "'" << containerName << "'";
} else {
assert << "for " << itemDesc;
}
assert << " not found\", "<< uniqueContainerVarName << " != NULL);";
this->AddCode (assert);
return uniqueContainerVarName;
}
wxString CRCppEmitter::MakeVarName (const wxString &name,
const wxString &suffix)
{
// Remove '&' and ' ' characters -- the former is often used for
// accelerator keys in menus et al.:
wxString varNameToClean = name;
varNameToClean.Replace (" ", "");
varNameToClean.Replace ("&", "");
// Extract alphanumeric characters till first non-alphanumeric char (e.g.
// "&Open... Ctrl+O" => "Open... Ctrl+O" => "Open"):
wxString varName;
if ((isalpha (varNameToClean.GetChar (0))) || (varNameToClean.GetChar (0) == '_')) {
varName.Append (varNameToClean.GetChar (0));
} else {
// Variable names must start with alphabetical character:
varName.Append ("var");
}
bool foundTerminator = false;
int idx = 1;
while ((!foundTerminator) && (idx < varNameToClean.Length ())) {
if ((isalnum (varNameToClean.GetChar (idx))) || (varNameToClean.GetChar (idx) == '_')) {
varName.Append (varNameToClean.GetChar (idx));
} else {
foundTerminator = true;
}
idx++;
}
// Make first letter lower case:
char &firstChar = varName.GetWritableChar (0);
firstChar = tolower (firstChar);
// Append suffix before unifying:
varName.Append (suffix);
// Make variable name unique:
unsigned int cnt = 0;
wxString uniqueVarName = varName;
while ((this->IsContainerVarNameDuplicate (uniqueVarName)) ||
(m_varNameSet.find (uniqueVarName) != m_varNameSet.end ())) {
cnt++;
uniqueVarName = wxString::Format ("%s%d", varName.c_str (), cnt);
}
m_varNameSet.insert (uniqueVarName);
return uniqueVarName;
}
wxString CRCppEmitter::BreakString (const wxString &str,
const wxArrayString &breakStrs, unsigned int &idx, int minIdx,
bool isCode) const
{
if (str.Length () > m_maxChars) {
size_t foundIdx = 0;
size_t maxFoundIdx = 0;
unsigned int breakStrsIdx = 0;
for (int i = 0; i < breakStrs.Count (); i++) {
// Blanks at the line ends can be omitted (unless it is code):
int breakStrLen;
if (isCode) {
breakStrLen = breakStrs.Item (i).Length ();
} else {
breakStrLen = breakStrs.Item (i).Strip ().Length ();
}
foundIdx = str.rfind (breakStrs.Item (i),
m_maxChars - breakStrLen);
if (foundIdx != wxString::npos) {
// Prevent line break in non-integer number code emitting:
if (breakStrs.Item (i) == ".") {
// 1. Check that "." is not in a string
wxString line = str.Left (foundIdx);
if (!HasBrokenInString(line)) {
// 2. Check that all characters before "." are digits,
// prepended by "," and whitespace
int charIdx = foundIdx - 1;
bool foundComma = false;
bool foundWhitespace = false;
bool finished = false;
while (charIdx > 0 && !finished) {
if (isdigit (line.GetChar (charIdx))) {
if (foundWhitespace || foundComma) {
finished = true;
}
charIdx--;
} else if (line.GetChar (charIdx) == ' ') {
if (foundComma) {
finished = true;
}
foundWhitespace = true;
charIdx--;
} else if (line.GetChar (charIdx) == ',') {
finished = true;
foundComma = true;
foundIdx = 0;
} else {
finished = true;
}
}
}
}
if (foundIdx > maxFoundIdx) {
maxFoundIdx = foundIdx;
breakStrsIdx = i;
}
}
}
// No breaking string found, break by brute force:
if ((maxFoundIdx == 0) || ((minIdx > 0) && (maxFoundIdx < minIdx))) {
idx = m_maxChars;
return str.Left (m_maxChars);
} else {
idx = maxFoundIdx + breakStrs.Item (breakStrsIdx).Length ();
// Blanks at the line ends can be omitted (unless it is code):
wxString firstLine;
if (isCode) {
firstLine = str.Left (idx);
} else {
firstLine = str.Left (idx).Strip ();
}
return firstLine;
}
} else {
idx = 0;
return str;
}
}
bool CRCppEmitter::HasBrokenInString (const wxString &line) const
{
int freq = line.Freq ('"');
return (freq % 2 == 1);
}
bool CRCppEmitter::IsContainerVarNameDuplicate (const wxString &str) const
{
bool found = false;
ContainerMap::const_iterator it = m_contMap.begin ();
while ((!found) && (it != m_contMap.end ())) {
if (str == it->second) {
found = true;
} else {
it++;
}
}
return found;
}
} // End namespace swTst
| [
"john@64288482-8357-404e-ad65-de92a562ee98"
] | [
[
[
1,
461
]
]
] |
f3439bbd3172061877db910f25066357192db3a3 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Tessellation/WmlDelaunay2.cpp | 2691a5e2eb5b8aaa78a2e618f3b23d8066bf1eb1 | [] | no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,676 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlDelaunay2.h"
using namespace Wml;
//----------------------------------------------------------------------------
template <class Real>
Delaunay2<Real>::Delaunay2 (int iVertexQuantity, Vector2<Real>* akVertex)
{
assert( iVertexQuantity >= 3 && akVertex );
m_akTriangle = NULL;
// for edge processing
typedef int _Index[2];
_Index* akIndex = NULL;
int iE;
m_bOwner = true;
m_iVertexQuantity = iVertexQuantity;
m_akVertex = akVertex;
// Make a copy of the input vertices. These will be modified. The
// extra three slots are required for temporary storage.
Vector2<Real>* akPoint = new Vector2<Real>[m_iVertexQuantity+3];
memcpy(akPoint,akVertex,m_iVertexQuantity*sizeof(Vector2<Real>));
// compute the axis-aligned bounding rectangle of the vertices
m_fXMin = akPoint[0].X();
m_fXMax = m_fXMin;
m_fYMin = akPoint[0].Y();
m_fYMax = m_fYMin;
int i;
for (i = 1; i < m_iVertexQuantity; i++)
{
Real fValue = akPoint[i].X();
if ( m_fXMax < fValue )
m_fXMax = fValue;
if ( m_fXMin > fValue )
m_fXMin = fValue;
fValue = akPoint[i].Y();
if ( m_fYMax < fValue )
m_fYMax = fValue;
if ( m_fYMin > fValue )
m_fYMin = fValue;
}
m_fXRange = m_fXMax-m_fXMin;
m_fYRange = m_fYMax-m_fYMin;
// need to scale the data later to do a correct triangle count
Real fMaxRange = ( m_fXRange > m_fYRange ? m_fXRange : m_fYRange );
Real fMaxRangeSqr = fMaxRange*fMaxRange;
// Tweak the points by very small random numbers to help avoid
// cocircularities in the vertices.
Real fAmplitude = ((Real)0.5)*ms_fEpsilon*fMaxRange;
for (i = 0; i < m_iVertexQuantity; i++)
{
akPoint[i].X() += fAmplitude*Math<Real>::SymmetricRandom();
akPoint[i].Y() += fAmplitude*Math<Real>::SymmetricRandom();
}
Real aafWork[3][2] =
{
{ ((Real)5.0)*ms_fRange, -ms_fRange },
{ -ms_fRange, ((Real)5.0)*ms_fRange },
{ -ms_fRange, -ms_fRange }
};
for (i = 0; i < 3; i++)
{
akPoint[m_iVertexQuantity+i].X() = m_fXMin+m_fXRange*aafWork[i][0];
akPoint[m_iVertexQuantity+i].Y() = m_fYMin+m_fYRange*aafWork[i][1];
}
int i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i11, aiII[3];
Real fTmp;
int iTwoTSize = 2*ms_iTSize;
int** aaiTmp = new int*[iTwoTSize+1];
aaiTmp[0] = new int[2*(iTwoTSize+1)];
for (i0 = 1; i0 < iTwoTSize+1; i0++)
aaiTmp[i0] = aaiTmp[0] + 2*i0;
i1 = 2*(m_iVertexQuantity + 2);
int* aiID = new int[i1];
for (i0 = 0; i0 < i1; i0++)
aiID[i0] = i0;
int** aaiA3S = new int*[i1];
aaiA3S[0] = new int[3*i1];
for (i0 = 1; i0 < i1; i0++)
aaiA3S[i0] = aaiA3S[0] + 3*i0;
aaiA3S[0][0] = m_iVertexQuantity;
aaiA3S[0][1] = m_iVertexQuantity+1;
aaiA3S[0][2] = m_iVertexQuantity+2;
// circumscribed centers and radii
Real** aafCCR = new Real*[i1];
aafCCR[0] = new Real[3*i1];
for (i0 = 1; i0 < i1; i0++)
aafCCR[i0] = aafCCR[0] + 3*i0;
aafCCR[0][0] = (Real)0.0;
aafCCR[0][1] = (Real)0.0;
aafCCR[0][2] = Math<Real>::MAX_REAL;
int iTriangleQuantity = 1; // number of triangles
i4 = 1;
// compute triangulation
for (i0 = 0; i0 < m_iVertexQuantity; i0++)
{
i1 = i7 = -1;
i9 = 0;
for (i11 = 0; i11 < iTriangleQuantity; i11++)
{
i1++;
while ( aaiA3S[i1][0] < 0 )
i1++;
fTmp = aafCCR[i1][2];
for (i2 = 0; i2 < 2; i2++)
{
Real fZ = akPoint[i0][i2] - aafCCR[i1][i2];
fTmp -= fZ*fZ;
if ( fTmp < (Real)0.0 )
goto Corner3;
}
i9--;
i4--;
aiID[i4] = i1;
for (i2 = 0; i2 < 3; i2++)
{
aiII[0] = 0;
if ( aiII[0] == i2 )
aiII[0]++;
for (i3 = 1; i3 < 2; i3++)
{
aiII[i3] = aiII[i3-1] + 1;
if ( aiII[i3] == i2 )
aiII[i3]++;
}
if ( i7 > 1 )
{
i8 = i7;
for (i3 = 0; i3 <= i8; i3++)
{
for (i5 = 0; i5 < 2; i5++)
if ( aaiA3S[i1][aiII[i5]] != aaiTmp[i3][i5] )
goto Corner1;
for (i6 = 0; i6 < 2; i6++)
aaiTmp[i3][i6] = aaiTmp[i8][i6];
i7--;
goto Corner2;
Corner1:;
}
}
if ( ++i7 > iTwoTSize )
{
// Temporary storage exceeded. Increase ms_iTSize and
// call the constructor again.
assert( false );
goto ExitDelaunay;
}
for (i3 = 0; i3 < 2; i3++)
aaiTmp[i7][i3] = aaiA3S[i1][aiII[i3]];
Corner2:;
}
aaiA3S[i1][0] = -1;
Corner3:;
}
for (i1 = 0; i1 <= i7; i1++)
{
for (i2 = 0; i2 < 2; i2++)
for (aafWork[2][i2] = 0, i3 = 0; i3 < 2; i3++)
{
aafWork[i3][i2] = akPoint[aaiTmp[i1][i2]][i3] -
akPoint[i0][i3];
aafWork[2][i2] += ((Real)0.5)*aafWork[i3][i2]*(
akPoint[aaiTmp[i1][i2]][i3] + akPoint[i0][i3]);
}
fTmp = aafWork[0][0]*aafWork[1][1] - aafWork[1][0]*aafWork[0][1];
assert( Math<Real>::FAbs(fTmp) > (Real)0.0 );
fTmp = ((Real)1.0)/fTmp;
aafCCR[aiID[i4]][0] = (aafWork[2][0]*aafWork[1][1] -
aafWork[2][1]*aafWork[1][0])*fTmp;
aafCCR[aiID[i4]][1] = (aafWork[0][0]*aafWork[2][1] -
aafWork[0][1]*aafWork[2][0])*fTmp;
for (aafCCR[aiID[i4]][2] = 0, i2 = 0; i2 < 2; i2++)
{
Real fZ = akPoint[i0][i2] - aafCCR[aiID[i4]][i2];
aafCCR[aiID[i4]][2] += fZ*fZ;
aaiA3S[aiID[i4]][i2] = aaiTmp[i1][i2];
}
aaiA3S[aiID[i4]][2] = i0;
i4++;
i9++;
}
iTriangleQuantity += i9;
}
// count the number of triangles
m_iTriangleQuantity = 0;
i0 = -1;
for (i11 = 0; i11 < iTriangleQuantity; i11++)
{
i0++;
while ( aaiA3S[i0][0] < 0 )
i0++;
if ( aaiA3S[i0][0] < m_iVertexQuantity )
{
for (i1 = 0; i1 < 2; i1++)
{
for (i2 = 0; i2 < 2; i2++)
{
aafWork[i2][i1] = akPoint[aaiA3S[i0][i1]][i2] -
akPoint[aaiA3S[i0][2]][i2];
}
}
fTmp = aafWork[0][0]*aafWork[1][1] - aafWork[0][1]*aafWork[1][0];
if ( Math<Real>::FAbs(fTmp) > ms_fEpsilon*fMaxRangeSqr )
m_iTriangleQuantity++;
}
}
// create the triangles
m_akTriangle = new Triangle[m_iTriangleQuantity];
m_iTriangleQuantity = 0;
i0 = -1;
for (i11 = 0; i11 < iTriangleQuantity; i11++)
{
i0++;
while ( aaiA3S[i0][0] < 0 )
i0++;
if ( aaiA3S[i0][0] < m_iVertexQuantity )
{
for (i1 = 0; i1 < 2; i1++)
{
for (i2 = 0; i2 < 2; i2++)
{
aafWork[i2][i1] = akPoint[aaiA3S[i0][i1]][i2] -
akPoint[aaiA3S[i0][2]][i2];
}
}
fTmp = aafWork[0][0]*aafWork[1][1] - aafWork[0][1]*aafWork[1][0];
if ( Math<Real>::FAbs(fTmp) > ms_fEpsilon*fMaxRangeSqr )
{
int iDelta = (fTmp < (Real)0.0 ? 1 : 0);
Triangle& rkTri = m_akTriangle[m_iTriangleQuantity];
rkTri.m_aiVertex[0] = aaiA3S[i0][0];
rkTri.m_aiVertex[1] = aaiA3S[i0][1+iDelta];
rkTri.m_aiVertex[2] = aaiA3S[i0][2-iDelta];
rkTri.m_aiAdjacent[0] = -1;
rkTri.m_aiAdjacent[1] = -1;
rkTri.m_aiAdjacent[2] = -1;
m_iTriangleQuantity++;
}
}
}
// build edge table
m_iEdgeQuantity = 0;
m_akEdge = new Edge[3*m_iTriangleQuantity];
akIndex = new _Index[3*m_iTriangleQuantity];
int j, j0, j1;
for (i = 0; i < m_iTriangleQuantity; i++)
{
Triangle& rkTri = m_akTriangle[i];
for (j0 = 0, j1 = 1; j0 < 3; j0++, j1 = (j1+1)%3)
{
for (j = 0; j < m_iEdgeQuantity; j++)
{
Edge& rkEdge = m_akEdge[j];
if ( (rkTri.m_aiVertex[j0] == rkEdge.m_aiVertex[0]
&& rkTri.m_aiVertex[j1] == rkEdge.m_aiVertex[1])
|| (rkTri.m_aiVertex[j0] == rkEdge.m_aiVertex[1]
&& rkTri.m_aiVertex[j1] == rkEdge.m_aiVertex[0]) )
{
break;
}
}
if ( j == m_iEdgeQuantity ) // add edge to table
{
m_akEdge[j].m_aiVertex[0] = rkTri.m_aiVertex[j0];
m_akEdge[j].m_aiVertex[1] = rkTri.m_aiVertex[j1];
m_akEdge[j].m_aiTriangle[0] = i;
akIndex[j][0] = j0;
m_akEdge[j].m_aiTriangle[1] = -1;
m_iEdgeQuantity++;
}
else // edge already exists, add triangle to table
{
m_akEdge[j].m_aiTriangle[1] = i;
akIndex[j][1] = j0;
}
}
}
// count boundary edges (the convex hull of the points)
// and establish links between adjacent triangles
m_iExtraTriangleQuantity = 0;
for (i = 0; i < m_iEdgeQuantity; i++)
{
if ( m_akEdge[i].m_aiTriangle[1] != -1 )
{
j0 = m_akEdge[i].m_aiTriangle[0];
j1 = m_akEdge[i].m_aiTriangle[1];
m_akTriangle[j0].m_aiAdjacent[akIndex[i][0]] = j1;
m_akTriangle[j1].m_aiAdjacent[akIndex[i][1]] = j0;
}
else
{
m_iExtraTriangleQuantity++;
}
}
delete[] akIndex;
// set up extra triangle data
m_akExtraTriangle = new Triangle[m_iExtraTriangleQuantity];
for (i = 0, iE = 0; i < m_iTriangleQuantity; i++)
{
Triangle& rkTri = m_akTriangle[i];
for (int j = 0; j < 3; j++)
{
if ( rkTri.m_aiAdjacent[j] == -1 )
{
Triangle& rkETri = m_akExtraTriangle[iE];
int j1 = (j+1) % 3, j2 = (j+2) % 3;
int iS0 = rkTri.m_aiVertex[j];
int iS1 = rkTri.m_aiVertex[j1];
rkETri.m_aiVertex[j] = iS0;
rkETri.m_aiVertex[j1] = iS1;
rkETri.m_aiVertex[j2] = -1;
rkTri.m_aiAdjacent[j] = iE + m_iTriangleQuantity;
iE++;
}
}
}
ExitDelaunay:;
delete[] aaiTmp[0];
delete[] aaiTmp;
delete[] aiID;
delete[] aaiA3S[0];
delete[] aaiA3S;
delete[] aafCCR[0];
delete[] aafCCR;
delete[] akPoint;
}
//----------------------------------------------------------------------------
template <class Real>
Delaunay2<Real>::Delaunay2 (Delaunay2& rkNet)
{
m_bOwner = false;
m_iVertexQuantity = rkNet.m_iVertexQuantity;
m_akVertex = rkNet.m_akVertex;
m_fXMin = rkNet.m_fXMin;
m_fXMax = rkNet.m_fXMax;
m_fXRange = rkNet.m_fXRange;
m_fYMin = rkNet.m_fYMin;
m_fYMax = rkNet.m_fYMax;
m_fYRange = rkNet.m_fYRange;
m_iEdgeQuantity = rkNet.m_iEdgeQuantity;
m_akEdge = rkNet.m_akEdge;
m_iTriangleQuantity = rkNet.m_iTriangleQuantity;
m_akTriangle = rkNet.m_akTriangle;
m_iExtraTriangleQuantity = rkNet.m_iExtraTriangleQuantity;
m_akExtraTriangle = rkNet.m_akExtraTriangle;
}
//----------------------------------------------------------------------------
template <class Real>
Delaunay2<Real>::~Delaunay2 ()
{
if ( m_bOwner )
{
delete[] m_akVertex;
delete[] m_akEdge;
delete[] m_akTriangle;
delete[] m_akExtraTriangle;
}
}
//----------------------------------------------------------------------------
template <class Real>
bool Delaunay2<Real>::IsOwner () const
{
return m_bOwner;
}
//----------------------------------------------------------------------------
template <class Real>
int Delaunay2<Real>::GetVertexQuantity () const
{
return m_iVertexQuantity;
}
//----------------------------------------------------------------------------
template <class Real>
const Vector2<Real>& Delaunay2<Real>::GetVertex (int i) const
{
assert( 0 <= i && i < m_iVertexQuantity );
return m_akVertex[i];
}
//----------------------------------------------------------------------------
template <class Real>
const Vector2<Real>* Delaunay2<Real>::GetVertices () const
{
return m_akVertex;
}
//----------------------------------------------------------------------------
template <class Real>
Real Delaunay2<Real>::GetXMin () const
{
return m_fXMin;
}
//----------------------------------------------------------------------------
template <class Real>
Real Delaunay2<Real>::GetXMax () const
{
return m_fXMax;
}
//----------------------------------------------------------------------------
template <class Real>
Real Delaunay2<Real>::GetXRange () const
{
return m_fXRange;
}
//----------------------------------------------------------------------------
template <class Real>
Real Delaunay2<Real>::GetYMin () const
{
return m_fYMin;
}
//----------------------------------------------------------------------------
template <class Real>
Real Delaunay2<Real>::GetYMax () const
{
return m_fYMax;
}
//----------------------------------------------------------------------------
template <class Real>
Real Delaunay2<Real>::GetYRange () const
{
return m_fYRange;
}
//----------------------------------------------------------------------------
template <class Real>
int Delaunay2<Real>::GetEdgeQuantity () const
{
return m_iEdgeQuantity;
}
//----------------------------------------------------------------------------
template <class Real>
const typename Delaunay2<Real>::Edge& Delaunay2<Real>::GetEdge (int i) const
{
assert( 0 <= i && i < m_iEdgeQuantity );
return m_akEdge[i];
}
//----------------------------------------------------------------------------
template <class Real>
const typename Delaunay2<Real>::Edge* Delaunay2<Real>::GetEdges () const
{
return m_akEdge;
}
//----------------------------------------------------------------------------
template <class Real>
int Delaunay2<Real>::GetTriangleQuantity () const
{
return m_iTriangleQuantity;
}
//----------------------------------------------------------------------------
template <class Real>
typename Delaunay2<Real>::Triangle& Delaunay2<Real>::GetTriangle (int i)
{
assert( 0 <= i && i < m_iTriangleQuantity );
return m_akTriangle[i];
}
//----------------------------------------------------------------------------
template <class Real>
const typename Delaunay2<Real>::Triangle&
Delaunay2<Real>::GetTriangle (int i) const
{
assert( 0 <= i && i < m_iTriangleQuantity );
return m_akTriangle[i];
}
//----------------------------------------------------------------------------
template <class Real>
typename Delaunay2<Real>::Triangle* Delaunay2<Real>::GetTriangles ()
{
return m_akTriangle;
}
//----------------------------------------------------------------------------
template <class Real>
const typename Delaunay2<Real>::Triangle*
Delaunay2<Real>::GetTriangles () const
{
return m_akTriangle;
}
//----------------------------------------------------------------------------
template <class Real>
int Delaunay2<Real>::GetExtraTriangleQuantity () const
{
return m_iExtraTriangleQuantity;
}
//----------------------------------------------------------------------------
template <class Real>
typename Delaunay2<Real>::Triangle& Delaunay2<Real>::GetExtraTriangle (int i)
{
assert( 0 <= i && i < m_iExtraTriangleQuantity );
return m_akExtraTriangle[i];
}
//----------------------------------------------------------------------------
template <class Real>
const typename Delaunay2<Real>::Triangle&
Delaunay2<Real>::GetExtraTriangle (int i) const
{
assert( 0 <= i && i < m_iExtraTriangleQuantity );
return m_akExtraTriangle[i];
}
//----------------------------------------------------------------------------
template <class Real>
typename Delaunay2<Real>::Triangle* Delaunay2<Real>::GetExtraTriangles ()
{
return m_akExtraTriangle;
}
//----------------------------------------------------------------------------
template <class Real>
const typename Delaunay2<Real>::Triangle*
Delaunay2<Real>::GetExtraTriangles () const
{
return m_akExtraTriangle;
}
//----------------------------------------------------------------------------
template <class Real>
Real& Delaunay2<Real>::Epsilon ()
{
return ms_fEpsilon;
}
//----------------------------------------------------------------------------
template <class Real>
Real& Delaunay2<Real>::Range ()
{
return ms_fRange;
}
//----------------------------------------------------------------------------
template <class Real>
int& Delaunay2<Real>::TSize ()
{
return ms_iTSize;
}
//----------------------------------------------------------------------------
template <class Real>
void Delaunay2<Real>::ComputeBarycenter (const Vector2<Real>& rkV0,
const Vector2<Real>& rkV1, const Vector2<Real>& rkV2,
const Vector2<Real>& rkP, Real afBary[3])
{
Vector2<Real> kV02 = rkV0 - rkV2;
Vector2<Real> kV12 = rkV1 - rkV2;
Vector2<Real> kPV2 = rkP - rkV2;
Real fM00 = kV02.Dot(kV02);
Real fM01 = kV02.Dot(kV12);
Real fM11 = kV12.Dot(kV12);
Real fR0 = kV02.Dot(kPV2);
Real fR1 = kV12.Dot(kPV2);
Real fDet = fM00*fM11 - fM01*fM01;
assert( Math<Real>::FAbs(fDet) > (Real)0.0 );
Real fInvDet = ((Real)1.0)/fDet;
afBary[0] = (fM11*fR0 - fM01*fR1)*fInvDet;
afBary[1] = (fM00*fR1 - fM01*fR0)*fInvDet;
afBary[2] = (Real)1.0 - afBary[0] - afBary[1];
}
//----------------------------------------------------------------------------
template <class Real>
bool Delaunay2<Real>::InTriangle (const Vector2<Real>& rkV0,
const Vector2<Real>& rkV1, const Vector2<Real>& rkV2,
const Vector2<Real>& rkTest)
{
// test against normal to first edge
Vector2<Real> kDir = rkTest - rkV0;
Vector2<Real> kNor(rkV0.Y() - rkV1.Y(), rkV1.X() - rkV0.X());
if ( kDir.Dot(kNor) < -Math<Real>::EPSILON )
return false;
// test against normal to second edge
kDir = rkTest - rkV1;
kNor = Vector2<Real>(rkV1.Y() - rkV2.Y(), rkV2.X() - rkV1.X());
if ( kDir.Dot(kNor) < -Math<Real>::EPSILON )
return false;
// test against normal to third edge
kDir = rkTest - rkV2;
kNor = Vector2<Real>(rkV2.Y() - rkV0.Y(), rkV0.X() - rkV2.X());
if ( kDir.Dot(kNor) < -Math<Real>::EPSILON )
return false;
return true;
}
//----------------------------------------------------------------------------
template <class Real>
void Delaunay2<Real>::ComputeInscribedCenter (const Vector2<Real>& rkV0,
const Vector2<Real>& rkV1, const Vector2<Real>& rkV2,
Vector2<Real>& rkCenter)
{
Vector2<Real> kD10 = rkV1 - rkV0, kD20 = rkV2 - rkV0, kD21 = rkV2 - rkV1;
Real fL10 = kD10.Length(), fL20 = kD20.Length(), fL21 = kD21.Length();
Real fPerimeter = fL10 + fL20 + fL21;
if ( fPerimeter > (Real)0.0 )
{
Real fInv = ((Real)1.0)/fPerimeter;
fL10 *= fInv;
fL20 *= fInv;
fL21 *= fInv;
}
rkCenter = fL21*rkV0 + fL20*rkV1 + fL10*rkV2;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template class WML_ITEM Delaunay2<float>;
float Delaunay2f::ms_fEpsilon = 0.00001f;
float Delaunay2f::ms_fRange = 10.0f;
int Delaunay2f::ms_iTSize = 75;
template class WML_ITEM Delaunay2<double>;
double Delaunay2d::ms_fEpsilon = 0.00001;
double Delaunay2d::ms_fRange = 10.0;
int Delaunay2d::ms_iTSize = 75;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
652
]
]
] |
597de27be31f99741ee2e730d2afc6ad0fff6a71 | 3856c39683bdecc34190b30c6ad7d93f50dce728 | /LastProject/Source/TimeLifeItem.cpp | c82bec27d1f7e4d76e800c077122a773bc5710e6 | [] | no_license | yoonhada/nlinelast | 7ddcc28f0b60897271e4d869f92368b22a80dd48 | 5df3b6cec296ce09e35ff0ccd166a6937ddb2157 | refs/heads/master | 2021-01-20T09:07:11.577111 | 2011-12-21T22:12:36 | 2011-12-21T22:12:36 | 34,231,967 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,523 | cpp | /**
@file TimeLifeItem.cpp
@date 2011/11/22
@author [email protected]
@brief 아이템 클래스
*/
#include "stdafx.h"
#include "Charactor.h"
#include "TimeLifeItem.h"
CTimeLifeItem::CTimeLifeItem()
{
m_fLife = 0;
m_bMonster = TRUE;
CCharactor::AliveCheck(FALSE);
}
CTimeLifeItem::~CTimeLifeItem()
{
}
VOID CTimeLifeItem::Update()
{
if ( CollisionAtk( ) )
{
CSound::GetInstance()->PlayEffect( CSound::EFFECT_HIT );
if ( m_iMonsterNumber & 0x00F0 )
{
D3DXMATRIXA16 mat;
D3DXMatrixIdentity( &mat );
BreakQube( mat );
CGameEvent::GetInstance()->Set_PlayerIndex( CObjectManage::GetInstance()->Get_CharTable( CObjectManage::GetInstance()->Get_ClientNumber() ) );
CGameEvent::GetInstance()->Set_MonsterIndex( m_iMonsterNumber );
}
else if ( m_iMonsterNumber & 0xFF00 )
{
m_fLife = 3.0f;
BreakCubeAll();
}
}
if ( m_fLife > 0.0f )
{
m_fLife -= CFrequency::GetInstance()->getFrametime();
if ( m_fLife < 0.0f )
{
AliveCheck( FALSE );
CGameEvent::GetInstance()->Set_MonsterIndex( m_iMonsterNumber );
CGameEvent::GetInstance()->AddEvent( CGameEvent::GAME_HEALING, 0.001f );
}
}
}
VOID CTimeLifeItem::SetActive( BOOL a_bActive )
{
AliveCheck( a_bActive );
UpdateByValue( D3DXVECTOR3( Get_CharaPos().x, 0.0f, Get_CharaPos().z ), 0.0f );
UpdateOtherPlayer( TRUE );
}
VOID CTimeLifeItem::Render()
{
if ( AliveCheck() )
{
D3DXMatrixIdentity( &m_matMonster );
CCharactor::Render();
}
}
| [
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0",
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0"
] | [
[
[
1,
27
],
[
30,
72
]
],
[
[
28,
29
]
]
] |
18f083cd4b4f3ca2e9d0acc96e96a2e6e76955c7 | 6d680e20e4a703f0aa0d4bb5e50568143241f2d5 | /src/MobiHealth/moc_NoteWidget.cpp | 9f474027f56488c864d254a7012ab55e0eee799c | [] | no_license | sirnicolaz/MobiHealt | f7771e53a4a80dcea3d159eca729e9bd227e8660 | bbfd61209fb683d5f75f00bbf81b24933922baac | refs/heads/master | 2021-01-20T12:21:17.215536 | 2010-04-21T14:21:16 | 2010-04-21T14:21:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,122 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'NoteWidget.h'
**
** Created: Sun Apr 11 11:47:54 2010
** by: The Qt Meta Object Compiler version 62 (Qt 4.6.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "NoteWidget.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'NoteWidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.6.1. 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_NoteWidget[] = {
// content:
4, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_NoteWidget[] = {
"NoteWidget\0"
};
const QMetaObject NoteWidget::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_NoteWidget,
qt_meta_data_NoteWidget, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &NoteWidget::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *NoteWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *NoteWidget::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_NoteWidget))
return static_cast<void*>(const_cast< NoteWidget*>(this));
return QWidget::qt_metacast(_clname);
}
int NoteWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
69
]
]
] |
782118bfc4765106e1af53d2cb4b1cf0da77f42b | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/POJ/2911/2911.cpp | 50f8394e3f121aa9a7547057abf501c326b69dab | [] | no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 485 | cpp | #include "stdio.h"
#include "iostream"
#include "string.h"
#include "math.h"
#include "string"
#include "vector"
#include "set"
#include "map"
#include "queue"
#include "list"
using namespace std;
int main()
{
int maxi;
cin>>maxi;
for(int i=32;i<100;i++){
if(i*i>=maxi) break;
for(int j=32;j<i;j++){
int t=i*i-j*j;
if(t<1000) continue;
int d=t%10;
while(t){
if(t%10!=d) break;
t/=10;
}
if(t==0) cout<<i*i<<endl;
}
}
} | [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
] | [
[
[
1,
31
]
]
] |
01d024e79e8bc037b87181cf716978ed2187c055 | 17e1b436ba01206d97861ec9153943592002ecbe | /uppsrc/RichEdit/FormatDlg.cpp | 7be0d0927542f75e894341d964ffe72355eb7f0d | [
"BSD-2-Clause"
] | permissive | ancosma/upp-mac | 4c874e858315a5e68ea74fbb1009ea52e662eca7 | 5e40e8e31a3247e940e1de13dd215222a7a5195a | refs/heads/master | 2022-12-22T17:04:27.008533 | 2010-12-30T16:38:08 | 2010-12-30T16:38:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,485 | cpp | #include "RichEdit.h"
NAMESPACE_UPP
RichPara::NumberFormat ParaFormatting::GetNumbering()
{
RichPara::NumberFormat f;
f.before_number = before_number;
f.after_number = after_number;
f.reset_number = reset_number;
for(int i = 0; i < 8; i++)
f.number[i] = Nvl((int)~n[i]);
return f;
}
bool ParaFormatting::IsNumbering()
{
if(!IsNull(before_number) || !IsNull(after_number) || reset_number)
return true;
for(int i = 0; i < 8; i++)
if(!IsNull(n[i]))
return true;
return false;
}
void ParaFormatting::EnableNumbering()
{
bool b = !IsNull(bullet) && !(int)~bullet;
before_number.Enable(b);
after_number.Enable(b);
for(int i = 0; i < 8; i++)
n[i].Enable(b);
}
int ParaFormatting::ComputeIndent()
{
if(!IsNull(bullet) && (int)~bullet)
return 150;
if(IsNumbering()) {
RichPara::NumberFormat f = GetNumbering();
RichPara::Number n;
static byte n0[] = { 0, 37, 38, 48, 48, 37, 37 };
static byte n1[] = { 0, 17, 18, 12, 12, 17, 17 };
if(f.number[0] && f.number[0] < 8)
n.n[0] = n0[f.number[0]];
if(f.number[1] && f.number[1] < 8)
n.n[1] = n1[f.number[1]];
for(int i = 2; i < 8; i++) {
static byte nn[] = { 0, 7, 8, 1, 1, 7, 7 };
if(f.number[i] && f.number[i] < 8)
n.n[i] = nn[f.number[i]];
}
String s = n.AsText(f);
s.Cat(' ');
return GetTextSize(s, font).cx;
}
return 0;
}
void ParaFormatting::SetupIndent()
{
EnableNumbering();
if(indent.IsModified() || keepindent) return;
indent <<= ComputeIndent();
indent.ClearModify();
}
void ParaFormatting::Set(int unit, const RichText::FormatInfo& formatinfo)
{
font = formatinfo;
ruler.Set(unit, RichText::RULER & formatinfo.paravalid ? formatinfo.ruler : Null);
before.Set(unit, RichText::BEFORE & formatinfo.paravalid ? formatinfo.before : Null);
lm.Set(unit, RichText::LM & formatinfo.paravalid ? formatinfo.lm : Null);
indent.Set(unit, RichText::INDENT & formatinfo.paravalid ? formatinfo.indent : Null);
rm.Set(unit, RichText::RM & formatinfo.paravalid ? formatinfo.rm : Null);
after.Set(unit, RichText::AFTER & formatinfo.paravalid ? formatinfo.after : Null);
if(RichText::ALIGN & formatinfo.paravalid)
align <<= formatinfo.align == ALIGN_LEFT ? 0 :
formatinfo.align == ALIGN_CENTER ? 1 :
formatinfo.align == ALIGN_RIGHT ? 2 :
3;
if(RichText::NEWPAGE & formatinfo.paravalid)
page = formatinfo.newpage;
else {
page = Null;
page.ThreeState();
}
if(RichText::KEEP & formatinfo.paravalid)
keep = formatinfo.keep;
else {
keep = Null;
keep.ThreeState();
}
if(RichText::KEEPNEXT & formatinfo.paravalid)
keepnext = formatinfo.keepnext;
else {
keepnext = Null;
keepnext.ThreeState();
}
if(RichText::ORPHAN & formatinfo.paravalid)
orphan = formatinfo.orphan;
else {
orphan = Null;
orphan.ThreeState();
}
if(RichText::RULERINK & formatinfo.paravalid)
rulerink <<= formatinfo.rulerink;
else
rulerink <<= Null;
tabpos.SetUnit(unit);
if(RichText::BULLET & formatinfo.paravalid)
bullet <<= formatinfo.bullet;
else
bullet <<= Null;
if(RichText::SPACING & formatinfo.paravalid)
linespacing <<= formatinfo.linespacing;
else
linespacing <<= Null;
if(RichText::NUMBERING & formatinfo.paravalid) {
before_number = formatinfo.before_number.ToWString();
after_number = formatinfo.after_number.ToWString();
reset_number = formatinfo.reset_number;
for(int i = 0; i < 8; i++)
n[i] = formatinfo.number[i];
}
else {
before_number <<= Null;
after_number <<= Null;
reset_number <<= Null;
reset_number.ThreeState();
for(int i = 0; i < 8; i++)
n[i] = Null;
}
tabs.Clear();
if(RichText::TABS & formatinfo.paravalid)
for(int i = 0; i < formatinfo.tab.GetCount(); i++)
tabs.Add(formatinfo.tab[i].pos, formatinfo.tab[i].align, formatinfo.tab[i].fillchar);
tabsize.Set(unit, RichText::TABSIZE & formatinfo.paravalid ? formatinfo.tabsize : Null);
keepindent = formatinfo.indent != ComputeIndent();
SetupIndent();
ClearModify();
modified = false;
}
dword ParaFormatting::Get(RichText::FormatInfo& formatinfo)
{
dword v = 0;
if(!IsNull(before)) {
formatinfo.before = ~before;
v |= RichText::BEFORE;
}
if(!IsNull(lm)) {
formatinfo.lm = ~lm;
v |= RichText::LM;
}
if(!IsNull(indent)) {
formatinfo.indent = ~indent;
v |= RichText::INDENT;
}
if(!IsNull(rm)) {
formatinfo.rm = ~rm;
v |= RichText::RM;
}
if(!IsNull(after)) {
formatinfo.after = ~after;
v |= RichText::AFTER;
}
if(!IsNull(align)) {
static int sw[] = { ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT, ALIGN_JUSTIFY };
formatinfo.align = sw[(int)~align];
v |= RichText::ALIGN;
}
if(!IsNull(page)) {
formatinfo.newpage = page;
v |= RichText::NEWPAGE;
}
if(!IsNull(keep)) {
formatinfo.keep = keep;
v |= RichText::KEEP;
}
if(!IsNull(keepnext)) {
formatinfo.keepnext = keepnext;
v |= RichText::KEEPNEXT;
}
if(!IsNull(orphan)) {
formatinfo.orphan = orphan;
v |= RichText::ORPHAN;
}
if(!IsNull(bullet)) {
formatinfo.bullet = ~bullet;
v |= RichText::BULLET;
}
if(!IsNull(linespacing)) {
formatinfo.linespacing = ~linespacing;
v |= RichText::SPACING;
}
if(IsNumbering()) {
(RichPara::NumberFormat&)formatinfo = GetNumbering();
v |= RichText::NUMBERING;
}
if((RichText::TABS & formatinfo.paravalid) || tabs.GetCount()) {
formatinfo.tab.Clear();
for(int i = 0; i < tabs.GetCount(); i++) {
RichPara::Tab tab;
tab.pos = tabs.Get(i, 0);
tab.align = (int)tabs.Get(i, 1);
tab.fillchar = (int)tabs.Get(i, 2);
formatinfo.tab.Add(tab);
}
v |= RichText::TABS;
}
if(!IsNull(tabsize)) {
formatinfo.tabsize = ~tabsize;
v |= RichText::TABSIZE;
}
if(!IsNull(ruler)) {
formatinfo.ruler = ~ruler;
v |= RichText::RULER;
}
if(!IsNull(rulerink)) {
formatinfo.rulerink = ~rulerink;
v |= RichText::RULERINK;
}
return v;
}
ParaFormatting::ParaFormatting()
{
CtrlLayout(*this);
tabtype.Add(ALIGN_LEFT, t_("Left"));
tabtype.Add(ALIGN_RIGHT, t_("Right"));
tabtype.Add(ALIGN_CENTER, t_("Centered"));
tabfill.Add(0, t_("None"));
tabfill.Add(1, t_("...."));
tabfill.Add(2, t_("----"));
tabfill.Add(3, t_("__"));
tabs.AddColumn(t_("Tab position"), 2).Edit(tabpos).SetConvert(tabpos);
tabs.AddColumn(t_("Type"), 2).Edit(tabtype).SetConvert(tabtype).InsertValue(ALIGN_LEFT);
tabs.AddColumn(t_("Fill"), 1).Edit(tabfill).SetConvert(tabfill).InsertValue(0);
tabs.ColumnWidths("103 89 78");
tabs.Appending().Removing().NoAskRemove();
tabs.WhenAcceptEdit = tabs.WhenArrayAction = THISBACK(SetMod);
linespacing.Add(0, "1.0");
linespacing.Add(-1, "1.5");
linespacing.Add(-2, "2.0");
bullet.Add(RichPara::BULLET_NONE, RichEditImg::NoneBullet());
bullet.Add(RichPara::BULLET_ROUND, RichEditImg::RoundBullet());
bullet.Add(RichPara::BULLET_ROUNDWHITE, RichEditImg::RoundWhiteBullet());
bullet.Add(RichPara::BULLET_BOX, RichEditImg::BoxBullet());
bullet.Add(RichPara::BULLET_BOXWHITE, RichEditImg::BoxWhiteBullet());
bullet.Add(RichPara::BULLET_TEXT, RichEditImg::TextBullet());
bullet.SetDisplay(CenteredHighlightImageDisplay());
bullet.SetLineCy(18);
for(int i = 0; i < 8; i++) {
DropList& list = n[i];
list.Add(Null);
list.Add(RichPara::NUMBER_NONE, " - ");
list.Add(RichPara::NUMBER_1, "1, 2, 3");
list.Add(RichPara::NUMBER_0, "0, 1, 2");
list.Add(RichPara::NUMBER_a, "a, b, c");
list.Add(RichPara::NUMBER_A, "A, B, C");
list.Add(RichPara::NUMBER_i, "i, ii, iii");
list.Add(RichPara::NUMBER_I, "I, II, III");
list <<= THISBACK(SetupIndent);
}
before_number <<=
after_number <<=
reset_number <<=
bullet <<= THISBACK(SetupIndent);
EnableNumbering();
rulerink.NullText("---");
}
void StyleManager::EnterStyle()
{
RichText::FormatInfo f;
const RichStyle& s = style.Get(list.GetKey());
f.Set(s.format);
para.Set(unit, f);
height <<= RichEdit::DotToPt(s.format.GetHeight());
face <<= s.format.GetFace();
bold = s.format.IsBold();
italic = s.format.IsItalic();
underline = s.format.IsUnderline();
strikeout = s.format.IsStrikeout();
capitals = s.format.capitals;
ink <<= s.format.ink;
paper <<= s.format.paper;
next <<= s.next;
ClearModify();
SetupFont0();
para.EnableNumbering();
}
void StyleManager::GetFont(Font& font)
{
if(!IsNull(face))
font.Face(~face);
if(!IsNull(height))
font.Height(RichEdit::PtToDot(~height));
font.Bold(bold);
font.Italic(italic);
font.Underline(underline);
font.Strikeout(strikeout);
}
void StyleManager::SetupFont0()
{
Font font = Arial(120);
GetFont(font);
para.SetFont(font);
}
void StyleManager::SetupFont()
{
SetupFont0();
para.SetupIndent();
}
void StyleManager::SaveStyle()
{
if(list.IsCursor()) {
Uuid id = list.GetKey();
RichStyle& s = style.Get(list.GetKey());
if(Ctrl::IsModified() || para.IsChanged()) {
dirty.FindAdd(id);
RichText::FormatInfo f;
para.Get(f);
s.format = f;
GetFont(s.format);
s.format.capitals = capitals;
s.format.ink = ~ink;
s.format.paper = ~paper;
}
if(String(list.Get(1)) != s.name) {
dirty.FindAdd(id);
s.name = list.Get(1);
}
if((Uuid)~next != s.next) {
dirty.FindAdd(id);
s.next = ~next;
}
}
}
void StyleManager::Create()
{
Uuid id = Uuid::Create();
style.Add(id, style.Get(list.GetKey()));
style.Top().next = id;
dirty.FindAdd(id);
list.Add(id);
list.GoEnd();
list.StartEdit();
}
void StyleManager::Remove()
{
if(list.GetCount() > 1 && (Uuid)list.GetKey() != RichStyle::GetDefaultId()) {
dirty.FindAdd(list.GetKey());
style.Remove(list.GetCursor());
list.Remove(list.GetCursor());
}
}
void StyleManager::Menu(Bar& bar)
{
bar.Add(t_("Create new style.."), THISBACK(Create))
.Key(K_INSERT);
bar.Add(t_("Remove style"), THISBACK(Remove))
.Key(K_DELETE);
bar.Add(t_("Rename.."), callback(&list, &ArrayCtrl::DoEdit))
.Key(K_CTRL_ENTER);
}
void StyleManager::ReloadNextStyles()
{
next.ClearList();
for(int i = 0; i < list.GetCount(); i++)
next.Add(list.Get(i, 0), list.Get(i, 1));
}
void RichEdit::DisplayDefault::Paint(Draw& w, const Rect& r, const Value& q, Color ink, Color paper, dword style) const
{
String text = q;
w.DrawRect(r, paper);
DrawSmartText(w, r.left, r.top, r.Width(), text, StdFont().Bold(), ink);
}
void StyleManager::Set(const RichText& text)
{
list.Clear();
int i;
for(i = 0; i < text.GetStyleCount(); i++)
list.Add(text.GetStyleId(i), text.GetStyle(i).name);
list.Sort(1, RichEdit::CompareStyle);
for(i = 0; i < text.GetStyleCount(); i++) {
Uuid id = list.Get(i, 0);
style.Add(id, text.GetStyle(id));
}
int q = list.Find(RichStyle::GetDefaultId());
if(q >= 0)
list.SetDisplay(q, 0, Single<RichEdit::DisplayDefault>());
ReloadNextStyles();
}
void StyleManager::Set(const char *qtf)
{
RichText txt = ParseQTF(qtf);
Set(txt);
}
bool StyleManager::IsChanged() const
{
return dirty.GetCount() || IsModified();
}
void StyleManager::Get(RichText& text)
{
SaveStyle();
for(int i = 0; i < dirty.GetCount(); i++) {
Uuid id = dirty[i];
int q = style.Find(id);
if(q >= 0)
text.SetStyle(id, style.Get(id));
else
text.RemoveStyle(id);
}
}
RichText StyleManager::Get()
{
RichText output;
output.SetStyles(style);
return output;
}
String StyleManager::GetQTF()
{
return AsQTF(Get());
}
void StyleManager::Setup(const Vector<int>& faces, int aunit)
{
unit = aunit;
height.Clear();
for(int i = 0; RichEdit::fh[i]; i++)
height.AddList(RichEdit::fh[i]);
RichEdit::SetupFaceList(face);
for(int i = 0; i < faces.GetCount(); i++)
face.Add(faces[i]);
}
StyleManager::StyleManager()
{
CtrlLayoutOKCancel(*this, t_("Styles"));
list.NoHeader().NoGrid();
list.AddKey();
list.AddColumn().Edit(name);
list.WhenEnterRow = THISBACK(EnterStyle);
list.WhenKillCursor = THISBACK(SaveStyle);
list.WhenBar = THISBACK(Menu);
list.WhenAcceptEdit = THISBACK(ReloadNextStyles);
ink.NotNull();
face <<= height <<= italic <<= bold <<= underline <<= strikeout <<= THISBACK(SetupFont);
Vector<int> ffs;
Vector<int> ff;
ff.Add(Font::ARIAL);
ff.Add(Font::ROMAN);
ff.Add(Font::COURIER);
Setup(ff, UNIT_DOT);
}
END_UPP_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
474
]
]
] |
0a204d74ed4391f6f4618af5f59c158cd59b2cf6 | 031009bf00a8d7cd564e0f768ff3649907bd5b65 | /src_algo/crc32.cpp | 3de034bccfb0dad4649fd9236bf86c499ce18536 | [] | no_license | usertex/autov | 237ab3b655be2dffcb7292cd212fe2b6d95907a7 | b470a96072484afe73ab0ae6ab7096970e34d973 | refs/heads/master | 2020-04-19T02:45:34.548955 | 2006-07-03T01:37:24 | 2006-07-03T01:37:24 | 67,372,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,205 | cpp | /*
Copyright (c) 2003, Dominik Reichl <[email protected]>
All rights reserved.
LICENSE TERMS
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 ReichlSoft nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
DISCLAIMER
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "crc32.h"
#define SHA1_MAX_FILE_BUFFER 8000
// CRC-32 polynominal:
// X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X+1
static const UWORD32 g_pCRC32Tab[] =
{
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};
CCRC32Hash::CCRC32Hash()
{
}
CCRC32Hash::~CCRC32Hash()
{
}
void CCRC32Hash::Init(RH_DATA_INFO *pInfo)
{
m_crc32 = 0xFFFFFFFF;
}
void CCRC32Hash::Update(const UWORD8 *pBuf, UINTPREF uLen)
{
UINTPREF i;
for(i = 0; i < uLen; i++)
m_crc32 = (m_crc32 >> 8) ^ g_pCRC32Tab[pBuf[i] ^ (m_crc32 & 0xFF)];
}
void CCRC32Hash::Final()
{
m_crc32 = ~m_crc32;
}
bool CCRC32Hash::HashFile(char *szFileName)
{
unsigned long ulFileSize, ulRest, ulBlocks;
unsigned long i;
UWORD8 uData[SHA1_MAX_FILE_BUFFER];
FILE *fIn;
if(szFileName == NULL) return false;
fIn = fopen(szFileName, "rb");
if(fIn == NULL) return false;
fseek(fIn, 0, SEEK_END);
ulFileSize = (unsigned long)ftell(fIn);
fseek(fIn, 0, SEEK_SET);
if(ulFileSize != 0)
{
ulBlocks = ulFileSize / SHA1_MAX_FILE_BUFFER;
ulRest = ulFileSize % SHA1_MAX_FILE_BUFFER;
}
else
{
ulBlocks = 0;
ulRest = 0;
}
for(i = 0; i < ulBlocks; i++)
{
fread(uData, 1, SHA1_MAX_FILE_BUFFER, fIn);
Update((UWORD8 *)uData, SHA1_MAX_FILE_BUFFER);
}
if(ulRest != 0)
{
fread(uData, 1, ulRest, fIn);
Update((UWORD8 *)uData, ulRest);
}
fclose(fIn); fIn = NULL;
return true;
}
| [
"[email protected]"
] | [
[
[
1,
173
]
]
] |
ef6fcfc181bce502de11cdece0a3efe2f6c4ae4c | b957e10ed5376dbe85c07bdef1f510f641984a1a | /Input.cpp | 85ad31e5c59343be1391a075ee4072e588d3fe63 | [] | no_license | alexjshank/motors | 063245c206df936a886f72a22f0f15c78e1129cb | 7193b729466d8caece267f0b8ddbf16d99c13f8a | refs/heads/master | 2016-09-10T15:47:20.906269 | 2009-11-04T18:41:21 | 2009-11-04T18:41:21 | 33,394,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,482 | cpp | #include ".\input.h"
#include "graphics.h"
#include "camera.h"
Input::Input(void)
{
priority = TP_ENGINE;
ZeroMemory((void *)&keystate,sizeof(keystate));
ZeroMemory((void *)&laststate,sizeof(laststate));
mouseMovement = Vector(0,0,0);
mouseAbsolute = Vector(0,10,0);
mousePosition = Vector(0,0,0);
inputContext = 0;
}
Input::~Input(void)
{
}
extern Graphics *renderer;
extern Camera *camera;
void Input::run() {
SDL_Event event;
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY;
GLdouble posX, posY, posZ;
memcpy((void *)&laststate,(void *)&keystate,sizeof(keystate));
memcpy((void *)&lastbuttons,(void *)&mousebuttons,sizeof(mousebuttons));
mouseMovement = Vector(0,0,0);
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
exit(1);
break;
case SDL_KEYDOWN:
SetKeyState(event.key.keysym.sym,1);
break;
case SDL_KEYUP:
SetKeyState(event.key.keysym.sym,0);
break;
case SDL_MOUSEMOTION:
mouseMovement.x = (float)event.motion.xrel;
mouseMovement.y = (float)event.motion.yrel;
mouseAbsolute.x = (float)event.motion.x;
mouseAbsolute.y = (float)event.motion.y + 20;
mousePosition += mouseMovement;
glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
glGetDoublev( GL_PROJECTION_MATRIX, projection );
glGetIntegerv( GL_VIEWPORT, viewport );
winX = (float)mouseAbsolute.x;
winY = (float)viewport[3] - (float)mouseAbsolute.y;
// glReadPixels( int(winX), int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );
gluUnProject( winX, winY, 0.999985f, modelview, projection, viewport, &posX, &posY, &posZ);
mouse3dPosition = Vector((float)posX, (float)posY, (float)posZ);
mouseVector = mouse3dPosition - camera->GetActualPosition();
mouseVector.normalize();
break;
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == 4) {
mouseAbsolute.z--;
} else if (event.button.button == 5) {
mouseAbsolute.z++;
} else {
mousebuttons[event.button.button] = 1;
}
break;
case SDL_MOUSEBUTTONUP:
mousebuttons[event.button.button] = 0;
break;
}
}
}
void Input::SetKeyState(int key, int state) {
if (key >= 0 && key < 256 && key != SDLK_RSHIFT && key != SDLK_LSHIFT && (GetKeyState(SDLK_RSHIFT) || GetKeyState(SDLK_LSHIFT))) {
if (isalpha(key)) key = toupper(key);
else if (key == '1') key = '!';
else if (key == '2') key = '@';
else if (key == '3') key = '#';
else if (key == '4') key = '$';
else if (key == '5') key = '%';
else if (key == '6') key = '^';
else if (key == '7') key = '&';
else if (key == '8') key = '*';
else if (key == '9') key = '(';
else if (key == '0') key = ')';
else if (key == '-') key = '-';
else if (key == '=') key = '+';
else if (key == '\\') key = '|';
else if (key == ',') key = '<';
else if (key == '.') key = '>';
else if (key == '/') key = '?';
}
keystate[key] = state;
}
int Input::GetKeyState(int key) {
return keystate[key];
}
bool Input::GetKeyDown(int key) {
return (bool)(keystate[key] != 0);
}
bool Input::GetKeyPressed(int key) {
return (bool)(keystate[key] != 0 && laststate[key] == 0);
}
bool Input::GetKeyReleased(int key) {
return (bool)(keystate[key] == 0 && laststate[key] != 0);
}
/*
class BindSystem : public Task {
public:
BindSystem();
void run();
void Bind(int key, (void *)functor);
void Unbind(int key);
private:
};
*/ | [
"alexjshank@0c9e2a0d-1447-0410-93de-f5a27bb8667b",
"[email protected]@0c9e2a0d-1447-0410-93de-f5a27bb8667b"
] | [
[
[
1,
10
],
[
12,
62
],
[
64,
132
]
],
[
[
11,
11
],
[
63,
63
]
]
] |
aa351cdc7f106dcd0065a13e5e019b67c6c73003 | 2aff7486e6c7afdbda48b7a5f424b257d47199df | /src/Gui/camview.h | 84ac766d2ba64fafbd8b6454405de161374769a4 | [] | no_license | offlinehacker/LDI_test | 46111c60985d735c00ea768bdd3553de48ba2ced | 7b77d3261ee657819bae3262e3ad78793b636622 | refs/heads/master | 2021-01-10T20:44:55.324019 | 2011-08-17T16:41:43 | 2011-08-17T16:41:43 | 2,220,496 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,257 | h | ////////////////////////////////////////////////////////////////////
// Name: camera view header
// File: camview.h
// Purpose: interface for the CCamView class.
//
// Created by: Larry Lart on 06-Jul-2006
// Updated by:
//
////////////////////////////////////////////////////////////////////
#ifndef _CCAMVIEW_H
#define _CCAMVIEW_H
#include "cv.h"
#include "highgui.h"
#include "cvaux.h"
#include "wx/wxprec.h"
#include "../OpenCv/Conversions.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif //precompiled headers
// external classes
class CCamera;
class CCamView : public wxWindow
{
public:
CCamView( wxWindow *frame, wxWindowID id,const wxPoint& pos, const wxSize& size, long style );
// Operations
public:
// Implementation
public:
virtual ~CCamView( );
bool IsCaptureEnabled( );
void CheckUpdate( );
// Draw method
void DrawCam( IplImage* pImg );
void Draw( wxDC& dc );
// Protected data
protected:
wxBitmap m_pBitmap;
bool m_bDrawing;
bool m_bNewImage;
int m_nWidth;
int m_nHeight;
// private methods
private:
void OnPaint(wxPaintEvent& event);
void OnSize( wxSizeEvent& even );
// protected data
protected:
DECLARE_EVENT_TABLE()
};
#endif
| [
"[email protected]"
] | [
[
[
1,
69
]
]
] |
01db936cb15b860e2afc6a1fa0081eb5fdd823ae | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/renaissance/rnsgameplay/src/ncspawnpoint/ncspawnpoint_cmds.cc | f52093999125d66731bac7d1166b5279cbf5c006 | [] | 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 | 652 | cc | //------------------------------------------------------------------------------
// ncspawnpoint_cmds.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "precompiled/pchrnsgameplay.h"
#include "ncspawnpoint/ncspawnpoint.h"
//-----------------------------------------------------------------------------
NSCRIPT_INITCMDS_BEGIN(ncSpawnPoint)
NSCRIPT_ADDCMD_COMPOBJECT('ISWE', nEntityObject*, SpawnEntity, 1, (const nString&), 0, ());
NSCRIPT_ADDCMD_COMPOBJECT('ESWE', nEntityObject*, SpawnEntityFrozen, 1, (const nString&), 0, ());
NSCRIPT_INITCMDS_END()
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
14
]
]
] |
9c08fcac57a4d70a74d2a86c881270108dddcfe4 | 6c8c4728e608a4badd88de181910a294be56953a | /CommunicationModule/TelepathyIM/VoiceSession.cpp | 8152d15a3f3f0a2095e9db820b78ee7d36bfa712 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,014 | cpp | // For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include <TelepathyQt4/ReferencedHandles>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingChannel>
#include "VoiceSession.h"
#include <CommunicationService.h>
#include "ServiceManager.h"
#include "VoiceSessionParticipant.h"
#include "SoundServiceInterface.h"
#include "Contact.h"
#include "CoreException.h"
#include <QDebug>
#include "MemoryLeakCheck.h"
namespace TelepathyIM
{
VoiceSession::VoiceSession(const Tp::StreamedMediaChannelPtr &tp_channel)
: state_(STATE_INITIALIZING),
tp_channel_(tp_channel),
pending_audio_streams_(0),
farsight_channel_(0),
pending_video_streams_(0),
audio_playback_channel_(0),
positional_voice_enabled_(false),
audio_playback_position_( Vector3df(0.0f, 0.0f, 0.0f)),
spatial_audio_playback_(false)
{
connect(tp_channel_->becomeReady(),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(OnIncomingChannelReady(Tp::PendingOperation*)));
}
VoiceSession::VoiceSession(Tp::ContactPtr tp_contact):
state_(STATE_INITIALIZING),
tp_channel_(0),
pending_audio_streams_(0),
farsight_channel_(0),
pending_video_streams_(0),
audio_playback_channel_(0),
positional_voice_enabled_(false),
audio_playback_position_( Vector3df(0.0f, 0.0f, 0.0f)),
spatial_audio_playback_(false)
{
tp_contact_ = tp_contact;
QVariantMap request;
request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA);
request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"), (uint) Tp::HandleTypeContact);
request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle"), tp_contact->handle().at(0));
Tp::ConnectionPtr tp_connection = tp_contact->manager()->connection();
connect(tp_connection->ensureChannel(request),
SIGNAL( finished(Tp::PendingOperation*) ),
SLOT( OnOutgoingChannelCreated(Tp::PendingOperation*) ));
}
VoiceSession::~VoiceSession()
{
DeleteChannels();
for (VoiceSessionParticipantVector::iterator i = participants_.begin(); i != participants_.end(); ++i)
{
VoiceSessionParticipant* p = *i;
SAFE_DELETE(p);
}
participants_.clear();
}
void VoiceSession::DeleteChannels()
{
// todo: check stream closes
//if (pending_audio_streams_)
// disconnect(
pending_audio_streams_ = 0;
//if (pending_video_streams_)
// disconnect(
pending_video_streams_ = 0;
Tp::MediaStreamPtr audio_stream = GetAudioMediaStream();
if (audio_stream)
audio_stream->requestDirection(false, false);
Tp::MediaStreamPtr video_stream = GetVideoMediaStream();
if (video_stream)
audio_stream->requestDirection(false, false);
if (tp_channel_)
{
tp_channel_->requestClose();
}
if (farsight_channel_)
{
farsight_channel_->StopPipeline();
SAFE_DELETE(farsight_channel_);
}
}
Communication::VoiceSessionInterface::State VoiceSession::GetState() const
{
return state_;
}
Communication::VoiceSessionParticipantVector VoiceSession::GetParticipants() const
{
Communication::VoiceSessionParticipantVector participants;
for (VoiceSessionParticipantVector::const_iterator i = participants_.begin(); i != participants_.end(); i++)
{
VoiceSessionParticipant* participant = *i;
participants.push_back( participant );
}
//! @todo IMPLEMENT
return participants;
}
void VoiceSession::Close()
{
if (audio_playback_channel_)
ClosePlaybackChannel();
state_ = STATE_CLOSED;
DeleteChannels();
emit StateChanged(state_);
}
void VoiceSession::ClosePlaybackChannel()
{
Foundation::Framework* framework = ((Communication::CommunicationService*)(Communication::CommunicationService::GetInstance()))->GetFramework();
if (!framework)
return;
Foundation::ServiceManagerPtr service_manager = framework->GetServiceManager();
if (!service_manager.get())
return;
boost::shared_ptr<Foundation::SoundServiceInterface> soundsystem = service_manager->GetService<Foundation::SoundServiceInterface>(Foundation::Service::ST_Sound).lock();
if (!soundsystem.get())
return;
soundsystem->StopSound(audio_playback_channel_);
audio_playback_channel_ = 0;
}
void VoiceSession::Accept()
{
if (state_ != STATE_RINGING_LOCAL || tp_channel_.isNull())
{
LogError("Voice session state doesn't allow accept command");
return;
}
tp_channel_->acceptCall();
connect(tp_channel_.data(),
SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)),
SLOT(OnChannelInvalidated(Tp::DBusProxy *, const QString &, const QString &)));
CreateFarsightChannel();
}
void VoiceSession::Reject()
{
if (state_ != STATE_RINGING_LOCAL || tp_channel_.isNull())
{
LogError("Voice session state doesn't allow accept command");
return;
}
tp_channel_->requestClose(); // reject
state_ = STATE_CLOSED;
reason_ = "User rejected incoming call.";
emit StateChanged(state_);
}
void VoiceSession::OnOutgoingChannelCreated(Tp::PendingOperation *op)
{
if (op->isError())
{
state_ = STATE_ERROR;
reason_ = QString("Cannot create connection").append(op->errorMessage());
LogError(reason_.toStdString());
emit StateChanged(state_);
return;
}
Tp::PendingChannel *pending_channel = qobject_cast<Tp::PendingChannel *>(op);
tp_channel_ = Tp::StreamedMediaChannel::create(pending_channel->connection(),pending_channel->objectPath(), pending_channel->immutableProperties());
connect(tp_channel_->becomeReady(),
SIGNAL( finished(Tp::PendingOperation*) ),
SLOT( OnOutgoingChannelReady(Tp::PendingOperation*) ));
}
void VoiceSession::OnIncomingChannelReady(Tp::PendingOperation *op)
{
Tp::PendingReady *pr = qobject_cast<Tp::PendingReady *>(op);
tp_channel_ = Tp::StreamedMediaChannelPtr(qobject_cast<Tp::StreamedMediaChannel *>(pr->object()));
if (op->isError())
{
state_ = STATE_ERROR;
QString message = QString("Incoming streamed media channel cannot become ready: ").append(op->errorMessage());
LogError(message.toStdString());
reason_ = message;
emit StateChanged(state_);
return;
}
connect(tp_channel_.data(), SIGNAL( invalidated(Tp::DBusProxy *, const QString &, const QString &) ), SLOT( OnChannelInvalidated(Tp::DBusProxy *, const QString &, const QString &) ));
tp_contact_ = tp_channel_->initiatorContact();
Contact* contact = new Contact(tp_contact_); // HACK: The contact should be get from Connection object (now we don't delete it!!!)
VoiceSessionParticipant* participant = new VoiceSessionParticipant(contact);
participants_.push_back(participant);
QString id = tp_contact_->id();
state_ = STATE_RINGING_LOCAL;
emit StateChanged(state_);
emit Ready(this);
}
void VoiceSession::OnOutgoingChannelReady(Tp::PendingOperation *op)
{
if (op->isError())
{
state_ = STATE_ERROR;
emit StateChanged(state_);
return;
}
connect(tp_channel_.data(), SIGNAL( invalidated(Tp::DBusProxy *, const QString &, const QString &) ), SLOT( OnChannelInvalidated(Tp::DBusProxy *, const QString &, const QString &) ));
Tp::ContactManager *cm = tp_channel_->connection()->contactManager();
tp_contact_ = cm->lookupContactByHandle(tp_channel_->targetHandle());
QString id = tp_contact_->id();
CreateFarsightChannel();
if (state_ == STATE_INITIALIZING)
{
state_ = STATE_RINGING_REMOTE;
emit StateChanged(state_);
}
}
void VoiceSession::CreateFarsightChannel()
{
try
{
// todo: for linux use "autoaudiosrc" for audio_src_name
// CURRENT IMPLEMENTATION WORKS ONLY ON WINDOWS
farsight_channel_ = new FarsightChannel(tp_channel_, "dshowaudiosrc", "autovideosrc", "autovideosink");
if ( !farsight_channel_->IsAudioSupported() )
{
SAFE_DELETE(farsight_channel_);
QString message = QString("Cannot initialize audio features.");
reason_ = message;
LogError(message.toStdString());
state_ = STATE_ERROR;
emit StateChanged(state_);
return;
}
}
catch(Exception &e)
{
QString message = QString("Cannot create FarsightChannel object - ").append(e.what());
reason_ = message;
LogError(message.toStdString());
state_ = STATE_ERROR;
emit StateChanged(state_);
return;
}
connect( farsight_channel_, SIGNAL(AudioDataAvailable(int)), SLOT( OnFarsightAudioDataAvailable(int ) ), Qt::QueuedConnection );
connect( farsight_channel_, SIGNAL(AudioBufferOverflow(int)), SLOT( OnFarsightAudioBufferOverflow(int ) ), Qt::QueuedConnection );
connect(tp_channel_->becomeReady(Tp::StreamedMediaChannel::FeatureStreams),
SIGNAL( finished(Tp::PendingOperation*) ),
SLOT( OnStreamFeatureReady(Tp::PendingOperation*) ));
connect(farsight_channel_,
SIGNAL(StatusChanged(TelepathyIM::FarsightChannel::Status)),
SLOT(OnFarsightChannelStatusChanged(TelepathyIM::FarsightChannel::Status)), Qt::QueuedConnection);
connect(farsight_channel_,
SIGNAL( AudioStreamReceived() ),
SLOT( OnFarsightChannelAudioStreamReceived() ), Qt::QueuedConnection);
connect(farsight_channel_,
SIGNAL( VideoStreamReceived() ),
SLOT( OnFarsightChannelVideoStreamReceived() ), Qt::QueuedConnection);
}
void VoiceSession::OnStreamFeatureReady(Tp::PendingOperation* op)
{
if (op->isError())
{
state_ = STATE_ERROR;
QString error_message = "Stream feature cannot become ready!";
reason_ = error_message;
LogError(error_message.toStdString());
emit StateChanged(state_);
return;
}
state_ = STATE_OPEN;
connect(tp_channel_.data(), SIGNAL( streamAdded(const Tp::MediaStreamPtr &) ), SLOT( OnStreamAdded(const Tp::MediaStreamPtr &) ));
connect(tp_channel_.data(), SIGNAL( streamRemoved(const Tp::MediaStreamPtr &) ), SLOT( OnStreamRemoved(const Tp::MediaStreamPtr &) ));
connect(tp_channel_.data(), SIGNAL( streamDirectionChanged(const Tp::MediaStreamPtr &, Tp::MediaStreamDirection, Tp::MediaStreamPendingSend) ), SLOT( OnStreamDirectionChanged(const Tp::MediaStreamPtr &, Tp::MediaStreamDirection, Tp::MediaStreamPendingSend) ));
connect(tp_channel_.data(), SIGNAL( streamStateChanged(const Tp::MediaStreamPtr &, Tp::MediaStreamState) ), SLOT( OnStreamStateChanged(const Tp::MediaStreamPtr &, Tp::MediaStreamState) ));
Tp::MediaStreams streams = tp_channel_->streams();
for(Tp::MediaStreams::iterator i = streams.begin(); i != streams.end(); ++i)
{
Tp::MediaStreamPtr stream = *i;
QString type = "UNKNOWN";
switch(stream->type())
{
case Tp::MediaStreamTypeAudio:
type = "AUDIO";
break;
case Tp::MediaStreamTypeVideo:
type = "VIDEO";
break;
}
QString direction = "unknown";
switch(stream->direction())
{
case Tp::MediaStreamDirectionNone:
direction = "None";
break;
case Tp::MediaStreamDirectionSend:
direction = "Send";
break;
case Tp::MediaStreamDirectionReceive:
direction = "Receive";
break;
case Tp::MediaStreamDirectionBidirectional:
direction = "Bidirectional";
break;
}
QString log_message = type.append(" stream is ready: direction is ").append(direction);
LogDebug(log_message.toStdString());
OnStreamDirectionChanged(stream, stream->direction(), stream->pendingSend());
OnStreamStateChanged(stream, stream->state());
}
Tp::MediaStreamPtr audio_stream = GetAudioMediaStream();
Tp::MediaStreamPtr video_stream = GetVideoMediaStream();
// Create automatically audio stream and start sending audio data
if ( pending_audio_streams_ == 0 && audio_stream.isNull() )
CreateAudioStream();
else
{
if (!audio_stream.isNull())
UpdateStreamDirection(audio_stream, true);
}
emit StateChanged(state_);
}
void VoiceSession::OnChannelInvalidated(Tp::DBusProxy *proxy, const QString &error, const QString &message)
{
QString log_message = QString(" VoiceSession::OnChannelInvalidated - ").append(error).append(" - ").append(message);
LogInfo(log_message.toStdString());
state_ = STATE_CLOSED;
reason_ = message;
emit StateChanged(state_);
}
void VoiceSession::CreateAudioStream()
{
if (pending_audio_streams_ )
return;
if (!tp_channel_)
{
LogError("Cannot create audio stream.");
return;
}
pending_audio_streams_ = tp_channel_->requestStream(tp_contact_, Tp::MediaStreamTypeAudio);
connect(pending_audio_streams_, SIGNAL( finished(Tp::PendingOperation*) ), SLOT( OnAudioStreamCreated(Tp::PendingOperation*) ));
}
void VoiceSession::CreateVideoStream()
{
if (pending_video_streams_ )
return;
if (!tp_channel_)
{
LogError("Cannot create audio stream.");
return;
}
pending_video_streams_ = tp_channel_->requestStream(tp_contact_, Tp::MediaStreamTypeVideo);
connect(pending_video_streams_, SIGNAL( finished(Tp::PendingOperation*) ), SLOT( OnVideoStreamCreated(Tp::PendingOperation*) ));
}
void VoiceSession::OnFarsightChannelStatusChanged(TelepathyIM::FarsightChannel::Status status)
{
emit ReceivingAudioData(IsReceivingAudioData());
emit ReceivingVideoData(IsReceivingVideoData());
emit SendingAudioData(IsReceivingAudioData());
emit SendingVideoData(IsReceivingVideoData());
switch (status)
{
case FarsightChannel::StatusConnecting:
LogInfo("VoiceSession: FarsightChannel status = Connecting...");
break;
case FarsightChannel::StatusConnected:
LogInfo("VoiceSession: FarsightChannel status = Connected.");
//state_ = STATE_OPEN;
//reason_ = "";
//emit StateChanged(state_);
break;
case FarsightChannel::StatusDisconnected:
LogInfo("VoiceSession: Call FarsightChannel status = terminated.");
state_ = STATE_CLOSED;
tp_channel_->requestClose();
emit StateChanged(state_);
break;
}
}
void VoiceSession::UpdateStreamDirection(const Tp::MediaStreamPtr &stream, bool send)
{
QString type = "UNKNOWN";
if (stream->type() == Tp::MediaStreamTypeAudio)
type = "AUDIO";
if (stream->type() == Tp::MediaStreamTypeVideo)
type = "VIDEO";
if (send)
{
if (!(stream->direction() & Tp::MediaStreamDirectionSend))
{
QString log_message = QString("Change ").append(type).append("stream direction to: DirectionSend");
LogDebug(log_message.toStdString());
int dir = stream->direction() | Tp::MediaStreamDirectionSend;
stream->requestDirection((Tp::MediaStreamDirection) dir);
}
}
else
{
if (stream->direction() & Tp::MediaStreamDirectionSend)
{
QString log_message = QString("Change ").append(type).append("stream direction to: ~DirectionSend");
LogDebug(log_message.toStdString());
int dir = stream->direction() & ~Tp::MediaStreamDirectionSend;
stream->requestDirection((Tp::MediaStreamDirection) dir);
}
}
}
void VoiceSession::OnStreamAdded(const Tp::MediaStreamPtr &stream)
{
if (stream->type() == Tp::MediaStreamTypeAudio)
{
LogDebug("Added AUDIO STREAM");
}
if (stream->type() == Tp::MediaStreamTypeVideo)
{
LogDebug("Added VIDEO STREAM");
}
if (stream->type() == Tp::MediaStreamTypeAudio)
UpdateStreamDirection(stream, true);
else
UpdateStreamDirection(stream, stream->direction());
OnStreamDirectionChanged(stream, stream->direction(), stream->pendingSend());
OnStreamStateChanged(stream, stream->state());
//state_ = STATE_OPEN;
//emit StateChanged(state_);
// TODO: Shoud we handle these ?
//stream->localSendingRequested();
//remoteSendingRequested
}
void VoiceSession::OnStreamRemoved(const Tp::MediaStreamPtr &stream)
{
if (stream->type() == Tp::MediaStreamTypeAudio)
{
LogDebug("Removed AUDIO STREAM");
emit AudioStreamStateChanged(SS_DISCONNECTED);
}
if (stream->type() == Tp::MediaStreamTypeVideo)
{
LogDebug("Removed VIDEO STREAM");
emit VideoStreamStateChanged(SS_DISCONNECTED);
}
}
void VoiceSession::OnStreamDirectionChanged(const Tp::MediaStreamPtr &stream, Tp::MediaStreamDirection direction, Tp::MediaStreamPendingSend ps)
{
// Note we do not use value of ps. Instead we use MediaStream interface to obtain that information.
switch(stream->type())
{
case Tp::MediaStreamTypeAudio:
emit SendingAudioData(IsSendingAudioData());
emit ReceivingAudioData(IsReceivingAudioData());
if (stream->localSendingRequested())
{
LogDebug("Audio send requested.");
// todo send audio
}
break;
case Tp::MediaStreamTypeVideo:
emit SendingVideoData(IsSendingVideoData());
emit ReceivingVideoData(IsReceivingVideoData());
if (stream->localSendingRequested())
{
LogDebug("Video send requested.");
// todo send audio
}
break;
}
QString type = "UNKNOWN";
if (stream->type() == Tp::MediaStreamTypeAudio)
type="AUDIO";
if (stream->type() == Tp::MediaStreamTypeVideo)
type="VIDEO";
//if (ps.testFlag(Tp::MediaStreamPendingLocalSend))
//{
// // todo: implementation
//}
//if (ps.testFlag(Tp::MediaStreamPendingRemoteSend))
//{
// // todo: implementation
//}
//QString log_message = type;
//bool new_state = false;
//if (direction == Tp::MediaStreamDirectionSend)
//{
// audio_in_enabled_ = false;
// audio_out_enabled_ = true;
// log_message.append(" stream direction changed to: SEND");
//} else if (direction == Tp::MediaStreamDirectionReceive)
//{
// audio_in_enabled_ = true;
// audio_out_enabled_ = false;
// log_message.append(" stream direction changed to: RECEIVE");
//} else if (direction == (Tp::MediaStreamDirectionSend | Tp::MediaStreamDirectionReceive))
//{
// audio_in_enabled_ = true;
// audio_out_enabled_ = true;
// log_message.append(" stream direction changed to: SEND & RECEIVE");
//} else
//{
// audio_in_enabled_ = false;
// audio_out_enabled_ = false;
// log_message.append(" stream direction changed to: NONE");
//}
//LogDebug(log_message.toStdString());
//if (stream->type() == Tp::MediaStreamTypeAudio)
// emit ReceivingAudioData(new_state);
//if (stream->type() == Tp::MediaStreamTypeVideo)
// emit ReceivingVideoData(new_state);
}
void VoiceSession::OnStreamStateChanged(const Tp::MediaStreamPtr &stream, Tp::MediaStreamState state)
{
QString type = "UNKNOWN";
if (stream->type() == Tp::MediaStreamTypeAudio)
type="AUDIO";
if (stream->type() == Tp::MediaStreamTypeVideo)
type="VIDEO";
QString log_message = type;
switch(state)
{
case Tp::MediaStreamStateDisconnected:
if (stream->type() == Tp::MediaStreamTypeAudio)
emit AudioStreamStateChanged(SS_DISCONNECTED);
if (stream->type() == Tp::MediaStreamTypeVideo)
emit VideoStreamStateChanged(SS_DISCONNECTED);
log_message.append(" stream state changed to: DISCONNECT");
break;
case Tp::MediaStreamStateConnecting:
if (stream->type() == Tp::MediaStreamTypeAudio)
emit AudioStreamStateChanged(SS_CONNECTING);
if (stream->type() == Tp::MediaStreamTypeVideo)
emit VideoStreamStateChanged(SS_CONNECTING);
log_message.append(" stream state changed to: CONNECTING...");
break;
case Tp::MediaStreamStateConnected:
if (stream->type() == Tp::MediaStreamTypeAudio)
emit AudioStreamStateChanged(SS_CONNECTED);
if (stream->type() == Tp::MediaStreamTypeVideo)
emit VideoStreamStateChanged(SS_CONNECTED);
log_message.append(" stream state changed to: CONNECTED");
break;
}
LogDebug(log_message.toStdString());
}
void VoiceSession::OnAudioStreamCreated(Tp::PendingOperation *op)
{
if (op->isError())
{
QString error = "Cannot create AUDIO stream: ";
error.append( op->errorMessage() );
LogError(error.toStdString());
return;
}
pending_audio_streams_ = 0;
LogDebug("AUDIO stream created.");
// do nothing as OnStreamAdded signal will be emitted
}
void VoiceSession::OnVideoStreamCreated(Tp::PendingOperation *op)
{
if (op->isError())
{
QString error = "Cannot create VIDEO stream: ";
error.append( op->errorMessage() );
LogError(error.toStdString());
return;
}
pending_video_streams_ = 0;
LogDebug("VIDEO stream created.");
// do nothing as OnStreamAdded signal will be emitted
}
Tp::MediaStreamPtr VoiceSession::GetAudioMediaStream() const
{
if (!tp_channel_)
return Tp::MediaStreamPtr();
Tp::MediaStreams streams = tp_channel_->streams();
foreach (const Tp::MediaStreamPtr &stream, streams) {
if (stream->type() == Tp::MediaStreamTypeAudio)
return stream;
}
return Tp::MediaStreamPtr();
}
Tp::MediaStreamPtr VoiceSession::GetVideoMediaStream() const
{
if (!tp_channel_)
return Tp::MediaStreamPtr();
Tp::MediaStreams streams = tp_channel_->streams();
foreach (const Tp::MediaStreamPtr &stream, streams) {
if (stream->type() == Tp::MediaStreamTypeVideo)
return stream;
}
return Tp::MediaStreamPtr();
}
Communication::VideoPlaybackWidgetInterface* VoiceSession::GetReceivedVideo()
{
if (farsight_channel_)
return farsight_channel_->GetReceivedVideoWidget();
return 0;
}
Communication::VideoPlaybackWidgetInterface* VoiceSession::GetLocallyCapturedVideo()
{
if (farsight_channel_)
{
return farsight_channel_->GetLocallyCapturedVideoWidget();
}
return 0;
}
void VoiceSession::OnFarsightAudioDataAvailable(int count)
{
if (count < AUDIO_BUFFER_PLAYBACK_MIN_SIZE)
return;
Foundation::Framework* framework = ((Communication::CommunicationService*)(Communication::CommunicationService::GetInstance()))->GetFramework();
if (!framework)
return;
Foundation::ServiceManagerPtr service_manager = framework->GetServiceManager();
if (!service_manager.get())
return;
boost::shared_ptr<Foundation::SoundServiceInterface> soundsystem = service_manager->GetService<Foundation::SoundServiceInterface>(Foundation::Service::ST_Sound).lock();
if (!soundsystem.get())
return;
if (!farsight_channel_)
return;
int size = farsight_channel_->GetAudioData(audio_buffer, AUDIO_BUFFER_SIZE);
bool stereo = false;
int channel_count = farsight_channel_->GetChannelCount();
if (channel_count == 2)
stereo = true;
int sample_width = farsight_channel_->GetSampleWidth();
int sample_rate = farsight_channel_->GetSampleRate();
Foundation::SoundServiceInterface::SoundBuffer sound_buffer;
sound_buffer.data_ = audio_buffer;
sound_buffer.frequency_ = sample_rate;
if (sample_width == 16)
sound_buffer.sixteenbit_ = true;
else
sound_buffer.sixteenbit_ = false;
sound_buffer.size_ = size;
sound_buffer.stereo_ = stereo;
if (size > 0 && sample_rate != -1 && sample_width != -1 && (channel_count == 1 || channel_count == 2) )
{
if (spatial_audio_playback_)
audio_playback_channel_ = soundsystem->PlaySoundBuffer3D(sound_buffer, Foundation::SoundServiceInterface::Voice, audio_playback_position_, audio_playback_channel_);
else
audio_playback_channel_ = soundsystem->PlaySoundBuffer(sound_buffer, Foundation::SoundServiceInterface::Voice, audio_playback_channel_);
}
}
void VoiceSession::OnFarsightAudioBufferOverflow(int count)
{
QString message = QString("Farsight audio buffer overflow. %1 bytes lost.").arg(QString::number(count));
LogDebug(message.toStdString());
}
Communication::VoiceSessionInterface::StreamState VoiceSession::GetAudioStreamState() const
{
Tp::MediaStreamPtr stream = GetAudioMediaStream();
if (!stream)
return Communication::VoiceSessionInterface::SS_DISCONNECTED;
switch( stream->state() )
{
case Tp::MediaStreamStateDisconnected:
return Communication::VoiceSessionInterface::SS_DISCONNECTED;
case Tp::MediaStreamStateConnecting:
return Communication::VoiceSessionInterface::SS_CONNECTING;
case Tp::MediaStreamStateConnected:
return Communication::VoiceSessionInterface::SS_CONNECTED;
}
return Communication::VoiceSessionInterface::SS_DISCONNECTED;
}
Communication::VoiceSessionInterface::StreamState VoiceSession::GetVideoStreamState() const
{
Tp::MediaStreamPtr stream = GetVideoMediaStream();
if (!stream)
return Communication::VoiceSessionInterface::SS_DISCONNECTED;
switch( stream->state() )
{
case Tp::MediaStreamStateDisconnected:
return Communication::VoiceSessionInterface::SS_DISCONNECTED;
case Tp::MediaStreamStateConnecting:
return Communication::VoiceSessionInterface::SS_CONNECTING;
case Tp::MediaStreamStateConnected:
return Communication::VoiceSessionInterface::SS_CONNECTED;
}
return Communication::VoiceSessionInterface::SS_DISCONNECTED;
}
bool VoiceSession::IsSendingAudioData() const
{
if (!farsight_channel_)
return false;
if (farsight_channel_->GetStatus() != FarsightChannel::StatusConnected)
return false;
Tp::MediaStreamPtr stream = GetAudioMediaStream();
if (!stream)
return false;
return stream->sending();
}
bool VoiceSession::IsSendingVideoData() const
{
if (!farsight_channel_)
return false;
if (farsight_channel_->GetStatus() != FarsightChannel::StatusConnected)
return false;
Tp::MediaStreamPtr stream = GetVideoMediaStream();
if (!stream)
return false;
return stream->sending();
}
bool VoiceSession::IsReceivingAudioData() const
{
if (!farsight_channel_)
return false;
if (farsight_channel_->GetStatus() != FarsightChannel::StatusConnected)
return false;
if (GetState() != STATE_OPEN)
return false;
Tp::MediaStreamPtr stream = GetAudioMediaStream();
if (!stream)
return false;
if (!farsight_channel_->IncomingAudioStreamConnected())
return false;
return stream->receiving();
}
bool VoiceSession::IsReceivingVideoData() const
{
if (!farsight_channel_)
return false;
if (farsight_channel_->GetStatus() != FarsightChannel::StatusConnected)
return false;
if (GetState() != STATE_OPEN)
return false;
Tp::MediaStreamPtr stream = GetVideoMediaStream();
if (!stream)
return false;
if (!farsight_channel_->IncomingVideoStreamConnected())
return false;
return stream->receiving();
}
void VoiceSession::SendAudioData(bool send)
{
Tp::MediaStreamPtr audio_stream = GetAudioMediaStream();
if (audio_stream)
UpdateStreamDirection(audio_stream, send);
else
if (send)
CreateAudioStream();
}
void VoiceSession::SendVideoData(bool send)
{
Tp::MediaStreamPtr video_stream = GetVideoMediaStream();
if (video_stream)
UpdateStreamDirection(video_stream, send);
else
if (send)
CreateVideoStream();
}
void VoiceSession::UpdateAudioSourcePosition(Vector3df position)
{
if (!spatial_audio_playback_)
{
ClosePlaybackChannel();
spatial_audio_playback_ = true;
}
audio_playback_position_ = position;
}
void VoiceSession::TrackingAvatar(bool enabled)
{
if (enabled)
qDebug() << "Voice Session >> Spatial tracking enabled";
else
qDebug() << "Voice Session >> Spatial tracking disabled";
positional_voice_enabled_ = enabled;
}
void VoiceSession::OnFarsightChannelAudioStreamReceived()
{
emit ReceivingAudioData(true);
}
void VoiceSession::OnFarsightChannelVideoStreamReceived()
{
emit ReceivingVideoData(true);
}
} // end of namespace: TelepathyIM
| [
"jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3",
"mattiku@5b2332b8-efa3-11de-8684-7d64432d61a3",
"Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3",
"[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3",
"[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3",
"cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3"
] | [
[
[
1,
3
],
[
5,
5
],
[
19,
20
],
[
27,
32
],
[
98,
98
],
[
102,
102
],
[
682,
682
],
[
690,
690
],
[
696,
696
],
[
871,
871
],
[
881,
889
]
],
[
[
4,
4
],
[
13,
17
],
[
21,
22
]
],
[
[
6,
12
],
[
18,
18
],
[
23,
24
],
[
38,
40
],
[
42,
42
],
[
54,
54
],
[
59,
59
],
[
62,
63
],
[
65,
97
],
[
104,
105
],
[
110,
110
],
[
114,
120
],
[
124,
124
],
[
130,
132
],
[
135,
135
],
[
152,
160
],
[
164,
181
],
[
186,
189
],
[
192,
192
],
[
196,
197
],
[
199,
199
],
[
202,
205
],
[
209,
212
],
[
216,
216
],
[
218,
226
],
[
229,
229
],
[
235,
235
],
[
242,
245
],
[
252,
256
],
[
270,
270
],
[
272,
280
],
[
283,
283
],
[
285,
288
],
[
299,
315
],
[
317,
318
],
[
322,
324
],
[
328,
329
],
[
331,
332
],
[
334,
337
],
[
340,
344
],
[
346,
347
],
[
349,
350
],
[
352,
357
],
[
359,
366
],
[
371,
425
],
[
429,
678
],
[
680,
681
],
[
683,
685
],
[
687,
689
],
[
691,
694
],
[
700,
711
],
[
713,
713
],
[
743,
870
],
[
872,
872
],
[
879,
880
],
[
900,
900
]
],
[
[
25,
26
],
[
37,
37
],
[
41,
41
],
[
43,
43
],
[
53,
53
],
[
55,
58
],
[
60,
61
],
[
64,
64
],
[
99,
101
],
[
103,
103
],
[
106,
109
],
[
111,
113
],
[
121,
123
],
[
125,
126
],
[
134,
134
],
[
182,
185
],
[
190,
191
],
[
193,
195
],
[
198,
198
],
[
200,
201
],
[
206,
208
],
[
213,
214
],
[
217,
217
],
[
227,
228
],
[
230,
234
],
[
236,
237
],
[
239,
241
],
[
251,
251
],
[
284,
284
],
[
319,
321
],
[
325,
327
],
[
330,
330
],
[
333,
333
],
[
338,
339
],
[
345,
345
],
[
348,
348
],
[
351,
351
],
[
358,
358
]
],
[
[
33,
36
],
[
44,
52
],
[
127,
129
],
[
133,
133
],
[
136,
151
],
[
246,
250
],
[
258,
258
],
[
262,
262
],
[
281,
282
],
[
290,
290
],
[
294,
294
],
[
298,
298
],
[
721,
729
],
[
731,
736
],
[
873,
878
]
],
[
[
161,
163
],
[
215,
215
],
[
238,
238
],
[
257,
257
],
[
259,
261
],
[
263,
269
],
[
289,
289
],
[
291,
293
],
[
295,
297
],
[
316,
316
],
[
367,
370
],
[
426,
428
],
[
679,
679
],
[
686,
686
],
[
695,
695
],
[
697,
699
],
[
712,
712
],
[
714,
720
],
[
730,
730
],
[
737,
742
],
[
890,
899
]
],
[
[
271,
271
]
]
] |
34e92e80b2df4f6bda479f2cb681b8cbc7c384a3 | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Collide/Agent/hkpCollisionAgentConfig.inl | c166b921475db2b27cb2f634f48af0f1ac8906e0 | [] | no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,326 | inl | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
hkpCollisionAgentConfig::hkpCollisionAgentConfig()
{
m_iterativeLinearCastEarlyOutDistance = 0.01f;
m_iterativeLinearCastMaxIterations = 20;
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
] | [
[
[
1,
31
]
]
] |
23df8d0d7426c1117aa58c00de9687a9fd2e6b1c | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/pymuscle/core/dRdv_real.cpp | 42a6d5245b2c1ab4bcec0aae8e50fd64d6024719 | [] | no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,429 | cpp | /*
* dRdv_real.c
* 2010 Geoyeob Kim
* As a part of the thesis implementation
*
* Rigid body equations (single)
*
* Rotation is parameterized by an exponential map technique
*/
#include "PymCorePch.h"
#include "Config.h"
#include "MathUtil.h"
#define p1 p [0]
#define p2 p [1]
#define p3 p [2]
#define pd1 pd[0]
#define pd2 pd[1]
#define pd3 pd[2]
#define v1 v [0]
#define v2 v [1]
#define v3 v [2]
#define vd1 vd[0]
#define vd2 vd[1]
#define vd3 vd[2]
#define Ixx I[0]
#define Iyy I[1]
#define Izz I[2]
#define Iww I[3]
#define Fr1 Fr [0]
#define Fr2 Fr [1]
#define Fr3 Fr [2]
#define r1 r [0]
#define r2 r [1]
#define r3 r [2]
void __dRdv(double dRdv1_s[3][3], double dRdv2_s[3][3], double dRdv3_s[3][3], const double v[3], const double th) {
/*;
################################################;
# Variable: dRdv1_s;
################################################;
*/;
double _x1 = pow(th,-1);
double _x2 = 0.5*th;
double _x3 = cos(_x2);
double _x4 = sin(_x2);
double _x5 = -1.0*_x1*_x3*_x4*v1;
double _x6 = pow(th,-2);
double _x7 = pow(_x4,2);
double _x8 = pow(th,-3);
double _x9 = pow(v1,3);
double _x10 = pow(th,-4);
double _x11 = pow(v2,2);
double _x12 = -1.0*_x8*_x3*_x4*v1*_x11;
double _x13 = 2*_x10*_x7*v1*_x11;
double _x14 = pow(v3,2);
double _x15 = -1.0*_x8*_x3*_x4*v1*_x14;
double _x16 = 2*_x10*_x7*v1*_x14;
double _x17 = 2*_x6*_x7*v2;
double _x18 = pow(v1,2);
double _x19 = 2.0*_x8*_x3*_x4*_x18*v2;
double _x20 = -4*_x10*_x7*_x18*v2;
double _x21 = pow(_x3,2);
double _x22 = 2*_x6*_x7*v3;
double _x23 = 2.0*_x8*_x3*_x4*_x18*v3;
double _x24 = -4*_x10*_x7*_x18*v3;
double _x25 = -2*_x6*_x7*v1;
double _x26 = -1.0*_x8*_x3*_x4*_x9;
double _x27 = 2*_x10*_x7*_x9;
double _x28 = 2.0*_x8*_x3*_x4*v1*v2*v3;
double _x29 = -4*_x10*_x7*v1*v2*v3;
dRdv1_s[ 0][ 0] = _x16+_x15+_x13+_x12-2*_x10*_x7*_x9+1.0*_x8*_x3*_x4*_x9+2*_x6*_x7*v1+_x5;
dRdv1_s[ 0][ 1] = 1.0*_x6*_x7*v1*v3+2*_x8*_x3*_x4*v1*v3-1.0*_x6*_x21*v1*v3+_x20+_x19+_x17;
dRdv1_s[ 0][ 2] = _x24+_x23+_x22-1.0*_x6*_x7*v1*v2-2*_x8*_x3*_x4*v1*v2+1.0*_x6*_x21*v1*v2;
dRdv1_s[ 1][ 0] = -1.0*_x6*_x7*v1*v3-2*_x8*_x3*_x4*v1*v3+1.0*_x6*_x21*v1*v3+_x20+_x19+_x17;
dRdv1_s[ 1][ 1] = _x16+_x15-2*_x10*_x7*v1*_x11+1.0*_x8*_x3*_x4*v1*_x11+_x27+_x26+_x25+_x5;
dRdv1_s[ 1][ 2] = _x29+_x28+1.0*_x6*_x7*_x18+2*_x8*_x3*_x4*_x18-1.0*_x6*_x21*_x18-2*_x1*_x3*_x4;
dRdv1_s[ 2][ 0] = _x24+_x23+_x22+1.0*_x6*_x7*v1*v2+2*_x8*_x3*_x4*v1*v2-1.0*_x6*_x21*v1*v2;
dRdv1_s[ 2][ 1] = _x29+_x28-1.0*_x6*_x7*_x18-2*_x8*_x3*_x4*_x18+1.0*_x6*_x21*_x18+2*_x1*_x3*_x4;
dRdv1_s[ 2][ 2] = -2*_x10*_x7*v1*_x14+1.0*_x8*_x3*_x4*v1*_x14+_x13+_x12+_x27+_x26+_x25+_x5;
/*;
################################################;
# Variable: dRdv2_s;
################################################;
*/;
_x1 = pow(th,-1);
_x2 = 0.5*th;
_x3 = cos(_x2);
_x4 = sin(_x2);
_x5 = -1.0*_x1*_x3*_x4*v2;
_x6 = pow(th,-2);
_x7 = pow(_x4,2);
_x8 = -2*_x6*_x7*v2;
_x9 = pow(th,-3);
_x10 = pow(v1,2);
_x11 = pow(th,-4);
_x12 = pow(v2,3);
_x13 = -1.0*_x9*_x3*_x4*_x12;
_x14 = 2*_x11*_x7*_x12;
_x15 = pow(v3,2);
_x16 = -1.0*_x9*_x3*_x4*v2*_x15;
_x17 = 2*_x11*_x7*v2*_x15;
_x18 = 2*_x6*_x7*v1;
_x19 = pow(v2,2);
_x20 = 2.0*_x9*_x3*_x4*v1*_x19;
_x21 = -4*_x11*_x7*v1*_x19;
_x22 = pow(_x3,2);
_x23 = 2.0*_x9*_x3*_x4*v1*v2*v3;
_x24 = -4*_x11*_x7*v1*v2*v3;
_x25 = -1.0*_x9*_x3*_x4*_x10*v2;
_x26 = 2*_x11*_x7*_x10*v2;
_x27 = 2*_x6*_x7*v3;
_x28 = 2.0*_x9*_x3*_x4*_x19*v3;
_x29 = -4*_x11*_x7*_x19*v3;
dRdv2_s[ 0][ 0] = _x17+_x16+_x14+_x13-2*_x11*_x7*_x10*v2+1.0*_x9*_x3*_x4*_x10*v2+_x8+_x5;
dRdv2_s[ 0][ 1] = 1.0*_x6*_x7*v2*v3+2*_x9*_x3*_x4*v2*v3-1.0*_x6*_x22*v2*v3+_x21+_x20+_x18;
dRdv2_s[ 0][ 2] = _x24+_x23-1.0*_x6*_x7*_x19-2*_x9*_x3*_x4*_x19+1.0*_x6*_x22*_x19+2*_x1*_x3*_x4;
dRdv2_s[ 1][ 0] = -1.0*_x6*_x7*v2*v3-2*_x9*_x3*_x4*v2*v3+1.0*_x6*_x22*v2*v3+_x21+_x20+_x18;
dRdv2_s[ 1][ 1] = _x17+_x16-2*_x11*_x7*_x12+1.0*_x9*_x3*_x4*_x12+_x26+_x25+2*_x6*_x7*v2+_x5;
dRdv2_s[ 1][ 2] = _x29+_x28+_x27+1.0*_x6*_x7*v1*v2+2*_x9*_x3*_x4*v1*v2-1.0*_x6*_x22*v1*v2;
dRdv2_s[ 2][ 0] = _x24+_x23+1.0*_x6*_x7*_x19+2*_x9*_x3*_x4*_x19-1.0*_x6*_x22*_x19-2*_x1*_x3*_x4;
dRdv2_s[ 2][ 1] = _x29+_x28+_x27-1.0*_x6*_x7*v1*v2-2*_x9*_x3*_x4*v1*v2+1.0*_x6*_x22*v1*v2;
dRdv2_s[ 2][ 2] = -2*_x11*_x7*v2*_x15+1.0*_x9*_x3*_x4*v2*_x15+_x14+_x13+_x26+_x25+_x8+_x5;
/*;
################################################;
# Variable: dRdv3_s;
################################################;
*/;
_x1 = pow(th,-1);
_x2 = 0.5*th;
_x3 = cos(_x2);
_x4 = sin(_x2);
_x5 = -1.0*_x1*_x3*_x4*v3;
_x6 = pow(th,-2);
_x7 = pow(_x4,2);
_x8 = -2*_x6*_x7*v3;
_x9 = pow(th,-3);
_x10 = pow(v1,2);
_x11 = pow(th,-4);
_x12 = pow(v2,2);
_x13 = -1.0*_x9*_x3*_x4*_x12*v3;
_x14 = 2*_x11*_x7*_x12*v3;
_x15 = pow(v3,3);
_x16 = -1.0*_x9*_x3*_x4*_x15;
_x17 = 2*_x11*_x7*_x15;
_x18 = 2.0*_x9*_x3*_x4*v1*v2*v3;
_x19 = -4*_x11*_x7*v1*v2*v3;
_x20 = pow(_x3,2);
_x21 = pow(v3,2);
_x22 = 2*_x6*_x7*v1;
_x23 = 2.0*_x9*_x3*_x4*v1*_x21;
_x24 = -4*_x11*_x7*v1*_x21;
_x25 = -1.0*_x9*_x3*_x4*_x10*v3;
_x26 = 2*_x11*_x7*_x10*v3;
_x27 = 2*_x6*_x7*v2;
_x28 = 2.0*_x9*_x3*_x4*v2*_x21;
_x29 = -4*_x11*_x7*v2*_x21;
dRdv3_s[ 0][ 0] = _x17+_x16+_x14+_x13-2*_x11*_x7*_x10*v3+1.0*_x9*_x3*_x4*_x10*v3+_x8+_x5;
dRdv3_s[ 0][ 1] = 1.0*_x6*_x7*_x21+2*_x9*_x3*_x4*_x21-1.0*_x6*_x20*_x21+_x19+_x18-2*_x1*_x3*_x4;
dRdv3_s[ 0][ 2] = _x24+_x23-1.0*_x6*_x7*v2*v3-2*_x9*_x3*_x4*v2*v3+1.0*_x6*_x20*v2*v3+_x22;
dRdv3_s[ 1][ 0] = -1.0*_x6*_x7*_x21-2*_x9*_x3*_x4*_x21+1.0*_x6*_x20*_x21+_x19+_x18+2*_x1*_x3*_x4;
dRdv3_s[ 1][ 1] = _x17+_x16-2*_x11*_x7*_x12*v3+1.0*_x9*_x3*_x4*_x12*v3+_x26+_x25+_x8+_x5;
dRdv3_s[ 1][ 2] = _x29+_x28+1.0*_x6*_x7*v1*v3+2*_x9*_x3*_x4*v1*v3-1.0*_x6*_x20*v1*v3+_x27;
dRdv3_s[ 2][ 0] = _x24+_x23+1.0*_x6*_x7*v2*v3+2*_x9*_x3*_x4*v2*v3-1.0*_x6*_x20*v2*v3+_x22;
dRdv3_s[ 2][ 1] = _x29+_x28-1.0*_x6*_x7*v1*v3-2*_x9*_x3*_x4*v1*v3+1.0*_x6*_x20*v1*v3+_x27;
dRdv3_s[ 2][ 2] = -2*_x11*_x7*_x15+1.0*_x9*_x3*_x4*_x15+_x14+_x13+_x26+_x25+2*_x6*_x7*v3+_x5;
}
void __dRdv0(double dRdv1_s0[3][3], double dRdv2_s0[3][3], double dRdv3_s0[3][3], const double v[3], const double th) {
/*;
################################################;
# Variable: dRdv1_s0;
################################################;
*/;
double _x1 = pow(v1,3);
double _x2 = pow(v2,2);
double _x3 = -_x2;
double _x4 = pow(v3,2);
double _x5 = -_x4;
double _x6 = pow(th,2);
double _x7 = -15*v2;
double _x8 = pow(v1,2);
double _x9 = 2*_x8*v2;
double _x10 = -6*v2;
double _x11 = _x8*v2;
double _x12 = -6*v3;
double _x13 = _x8*v3;
double _x14 = -15*v3;
double _x15 = 2*_x8*v3;
double _x16 = 4*_x8;
double _x17 = -v1*v2*v3;
double _x18 = 6*_x8;
double _x19 = v1*v2*v3;
dRdv1_s0[ 0][ 0] = _x6*(v1*(_x5+_x3+15)+_x1)/360-(v1*(_x5+_x3)+_x1)/24;
dRdv1_s0[ 0][ 1] = _x6*(-12*v1*v3+_x9+_x7)/360-(-4*v1*v3+_x11+_x10)/12;
dRdv1_s0[ 0][ 2] = _x6*(_x15+_x14+12*v1*v2)/360-(_x13+_x12+4*v1*v2)/12;
dRdv1_s0[ 1][ 0] = _x6*(12*v1*v3+_x9+_x7)/360-(4*v1*v3+_x11+_x10)/12;
dRdv1_s0[ 1][ 1] = (v1*(_x4+_x3-24)+_x1)/24-_x6*(v1*(_x4+_x3-45)+_x1)/360;
dRdv1_s0[ 1][ 2] = (_x17+_x16-12)/12-_x6*(_x17+_x18-30)/180;
dRdv1_s0[ 2][ 0] = _x6*(_x15+_x14-12*v1*v2)/360-(_x13+_x12-4*v1*v2)/12;
dRdv1_s0[ 2][ 1] = _x6*(_x19+_x18-30)/180-(_x19+_x16-12)/12;
dRdv1_s0[ 2][ 2] = (v1*(_x5+_x2-24)+_x1)/24-_x6*(v1*(_x5+_x2-45)+_x1)/360;
/*;
################################################;
# Variable: dRdv2_s0;
################################################;
*/;
_x1 = pow(th,2);
_x2 = pow(v2,3);
_x3 = pow(v1,2);
_x4 = -_x3;
_x5 = pow(v3,2);
_x6 = -15*v1;
_x7 = pow(v2,2);
_x8 = 2*v1*_x7;
_x9 = -6*v1;
_x10 = v1*_x7;
_x11 = 4*_x7;
_x12 = v1*v2*v3;
_x13 = 6*_x7;
_x14 = -_x5;
_x15 = -6*v3;
_x16 = _x7*v3;
_x17 = -15*v3;
_x18 = 2*_x7*v3;
_x19 = -v1*v2*v3;
dRdv2_s0[ 0][ 0] = (v2*(_x5+_x4-24)+_x2)/24-_x1*(v2*(_x5+_x4-45)+_x2)/360;
dRdv2_s0[ 0][ 1] = _x1*(-12*v2*v3+_x8+_x6)/360-(-4*v2*v3+_x10+_x9)/12;
dRdv2_s0[ 0][ 2] = _x1*(_x12+_x13-30)/180-(_x12+_x11-12)/12;
dRdv2_s0[ 1][ 0] = _x1*(12*v2*v3+_x8+_x6)/360-(4*v2*v3+_x10+_x9)/12;
dRdv2_s0[ 1][ 1] = _x1*(v2*(_x14+_x4+15)+_x2)/360-(v2*(_x14+_x4)+_x2)/24;
dRdv2_s0[ 1][ 2] = _x1*(_x18+_x17-12*v1*v2)/360-(_x16+_x15-4*v1*v2)/12;
dRdv2_s0[ 2][ 0] = (_x19+_x11-12)/12-_x1*(_x19+_x13-30)/180;
dRdv2_s0[ 2][ 1] = _x1*(_x18+_x17+12*v1*v2)/360-(_x16+_x15+4*v1*v2)/12;
dRdv2_s0[ 2][ 2] = (v2*(_x14+_x3-24)+_x2)/24-_x1*(v2*(_x14+_x3-45)+_x2)/360;
/*;
################################################;
# Variable: dRdv3_s0;
################################################;
*/;
_x1 = pow(th,2);
_x2 = pow(v1,2);
_x3 = -_x2;
_x4 = pow(v2,2);
_x5 = pow(v3,3);
_x6 = -v1*v2*v3;
_x7 = pow(v3,2);
_x8 = 4*_x7;
_x9 = 6*_x7;
_x10 = -6*v1;
_x11 = v1*_x7;
_x12 = -15*v1;
_x13 = 2*v1*_x7;
_x14 = v1*v2*v3;
_x15 = -_x4;
_x16 = -6*v2;
_x17 = v2*_x7;
_x18 = -15*v2;
_x19 = 2*v2*_x7;
dRdv3_s0[ 0][ 0] = (_x5+(_x4+_x3-24)*v3)/24-_x1*(_x5+(_x4+_x3-45)*v3)/360;
dRdv3_s0[ 0][ 1] = (_x8+_x6-12)/12-_x1*(_x9+_x6-30)/180;
dRdv3_s0[ 0][ 2] = _x1*(_x13+12*v2*v3+_x12)/360-(_x11+4*v2*v3+_x10)/12;
dRdv3_s0[ 1][ 0] = _x1*(_x9+_x14-30)/180-(_x8+_x14-12)/12;
dRdv3_s0[ 1][ 1] = (_x5+(_x15+_x2-24)*v3)/24-_x1*(_x5+(_x15+_x2-45)*v3)/360;
dRdv3_s0[ 1][ 2] = _x1*(_x19-12*v1*v3+_x18)/360-(_x17-4*v1*v3+_x16)/12;
dRdv3_s0[ 2][ 0] = _x1*(_x13-12*v2*v3+_x12)/360-(_x11-4*v2*v3+_x10)/12;
dRdv3_s0[ 2][ 1] = _x1*(_x19+12*v1*v3+_x18)/360-(_x17+4*v1*v3+_x16)/12;
dRdv3_s0[ 2][ 2] = _x1*(_x5+(_x15+_x3+15)*v3)/360-(_x5+(_x15+_x3)*v3)/24;
}
void dRdv(double dRdv1_s[3][3], double dRdv2_s[3][3], double dRdv3_s[3][3], const double v[3]) {
double th = sqrt(v1*v1+v2*v2+v3*v3);
if (th < THETA) __dRdv0(dRdv1_s, dRdv2_s, dRdv3_s, v, th);
else __dRdv(dRdv1_s, dRdv2_s, dRdv3_s, v, th);
}
void __RotationMatrixFromV(double rotMat[3][3], const double v[3], const double th) {
/*
################################################
# Variable: rotMat
################################################
*/
double _x1 = pow(v1,2);
double _x2 = pow(v2,2);
double _x3 = pow(v3,2);
double _x4 = _x3+_x2+_x1;
double _x5 = pow(_x4,1./2);
double _x6 = 0.5*_x5;
double _x7 = cos(_x6);
double _x8 = pow(_x7,2);
double _x9 = pow(_x4,-1);
double _x10 = sin(_x6);
double _x11 = pow(_x10,2);
double _x12 = -_x2*_x9*_x11;
double _x13 = -_x3*_x9*_x11;
double _x14 = pow(_x5,-1);
double _x15 = 2*v1*v2*_x9*_x11;
double _x16 = 2*v1*v3*_x9*_x11;
double _x17 = -_x1*_x9*_x11;
double _x18 = 2*v2*v3*_x9*_x11;
rotMat[ 0][ 0] = _x13+_x12+_x1*_x9*_x11+_x8;
rotMat[ 0][ 1] = _x15-2*v3*_x14*_x7*_x10;
rotMat[ 0][ 2] = _x16+2*v2*_x14*_x7*_x10;
rotMat[ 1][ 0] = _x15+2*v3*_x14*_x7*_x10;
rotMat[ 1][ 1] = _x13+_x2*_x9*_x11+_x17+_x8;
rotMat[ 1][ 2] = _x18-2*v1*_x14*_x7*_x10;
rotMat[ 2][ 0] = _x16-2*v2*_x14*_x7*_x10;
rotMat[ 2][ 1] = _x18+2*v1*_x14*_x7*_x10;
rotMat[ 2][ 2] = _x3*_x9*_x11+_x12+_x17+_x8;
}
void __RotationMatrixFromV0(double rotMat0[3][3], const double v[3], const double th) {
/*
################################################
# Variable: rotMat0
################################################
*/
double _x1 = pow(v1,2);
double _x2 = pow(v2,2);
double _x3 = -_x2;
double _x4 = pow(v3,2);
double _x5 = -_x4;
double _x6 = pow(th,2);
double _x7 = v1*v2;
double _x8 = v1*v3;
double _x9 = 2*v1;
double _x10 = -v2*v3;
double _x11 = 4*v1;
double _x12 = v2*v3;
rotMat0[ 0][ 0] = (_x5+_x3+_x1+4)/4-_x6*(_x5+_x3+_x1+12)/48;
rotMat0[ 0][ 1] = (_x7-2*v3)/2-_x6*(_x7-4*v3)/24;
rotMat0[ 0][ 2] = (_x8+2*v2)/2-_x6*(_x8+4*v2)/24;
rotMat0[ 1][ 0] = (2*v3+_x7)/2-_x6*(4*v3+_x7)/24;
rotMat0[ 1][ 1] = _x6*(_x4+_x3+_x1-12)/48-(_x4+_x3+_x1-4)/4;
rotMat0[ 1][ 2] = _x6*(_x10+_x11)/24-(_x10+_x9)/2;
rotMat0[ 2][ 0] = (_x8-2*v2)/2-_x6*(_x8-4*v2)/24;
rotMat0[ 2][ 1] = (_x12+_x9)/2-_x6*(_x12+_x11)/24;
rotMat0[ 2][ 2] = _x6*(_x5+_x2+_x1-12)/48-(_x5+_x2+_x1-4)/4;
}
void RotationMatrixFromV(double R[3][3], const double v[3]) {
double th = sqrt(v1*v1+v2*v2+v3*v3);
if (th < THETA) __RotationMatrixFromV0(R, v, th);
else __RotationMatrixFromV(R, v, th);
}
void __GeneralizedForce(double Q[6], const double v[3], const double th, const double Fr[3], const double r[3]) {
/*
################################################
# Variable: Q
################################################
*/
double _x1 = pow(th,-2);
double _x2 = 0.5*th;
double _x3 = cos(_x2);
double _x4 = pow(_x3,2);
double _x5 = -1.0*_x1*_x4*v1*v2;
double _x6 = pow(th,-3);
double _x7 = sin(_x2);
double _x8 = 2*_x6*_x3*_x7*v1*v2;
double _x9 = pow(_x7,2);
double _x10 = 1.0*_x1*_x9*v1*v2;
double _x11 = 2*_x1*_x9*v3;
double _x12 = pow(v1,2);
double _x13 = 2.0*_x6*_x3*_x7*_x12*v3;
double _x14 = pow(th,-4);
double _x15 = -4*_x14*_x9*_x12*v3;
double _x16 = pow(th,-1);
double _x17 = 2*_x16*_x3*_x7;
double _x18 = 2.0*_x6*_x3*_x7*v1*v2*v3;
double _x19 = -4*_x14*_x9*v1*v2*v3;
double _x20 = -1.0*_x16*_x3*_x7*v1;
double _x21 = -2*_x1*_x9*v1;
double _x22 = pow(v1,3);
double _x23 = -1.0*_x6*_x3*_x7*_x22;
double _x24 = 2*_x14*_x9*_x22;
double _x25 = pow(v2,2);
double _x26 = -1.0*_x6*_x3*_x7*v1*_x25;
double _x27 = 2*_x14*_x9*v1*_x25;
double _x28 = pow(v3,2);
double _x29 = 2*_x1*_x9*v2;
double _x30 = 2.0*_x6*_x3*_x7*_x12*v2;
double _x31 = -4*_x14*_x9*_x12*v2;
double _x32 = 1.0*_x1*_x4*v1*v3;
double _x33 = -2*_x6*_x3*_x7*v1*v3;
double _x34 = -1.0*_x1*_x9*v1*v3;
double _x35 = -2*_x16*_x3*_x7;
double _x36 = -1.0*_x6*_x3*_x7*v1*_x28;
double _x37 = 2*_x14*_x9*v1*_x28;
double _x38 = -1.0*_x1*_x4*v1*v3;
double _x39 = 2*_x6*_x3*_x7*v1*v3;
double _x40 = 1.0*_x1*_x9*v1*v3;
double _x41 = 1.0*_x1*_x4*v1*v2;
double _x42 = -2*_x6*_x3*_x7*v1*v2;
double _x43 = -1.0*_x1*_x9*v1*v2;
double _x44 = 2*_x1*_x9*v1;
double _x45 = 2.0*_x6*_x3*_x7*_x25*v3;
double _x46 = -4*_x14*_x9*_x25*v3;
double _x47 = -1.0*_x16*_x3*_x7*v2;
double _x48 = -2*_x1*_x9*v2;
double _x49 = -1.0*_x6*_x3*_x7*_x12*v2;
double _x50 = 2*_x14*_x9*_x12*v2;
double _x51 = pow(v2,3);
double _x52 = -1.0*_x6*_x3*_x7*_x51;
double _x53 = 2*_x14*_x9*_x51;
double _x54 = 2.0*_x6*_x3*_x7*v1*_x25;
double _x55 = -4*_x14*_x9*v1*_x25;
double _x56 = 1.0*_x1*_x4*v2*v3;
double _x57 = -2*_x6*_x3*_x7*v2*v3;
double _x58 = -1.0*_x1*_x9*v2*v3;
double _x59 = -1.0*_x6*_x3*_x7*v2*_x28;
double _x60 = 2*_x14*_x9*v2*_x28;
double _x61 = -1.0*_x1*_x4*v2*v3;
double _x62 = 2*_x6*_x3*_x7*v2*v3;
double _x63 = 1.0*_x1*_x9*v2*v3;
double _x64 = 2.0*_x6*_x3*_x7*v1*_x28;
double _x65 = -4*_x14*_x9*v1*_x28;
double _x66 = 2.0*_x6*_x3*_x7*v2*_x28;
double _x67 = -4*_x14*_x9*v2*_x28;
double _x68 = -1.0*_x16*_x3*_x7*v3;
double _x69 = -1.0*_x6*_x3*_x7*_x12*v3;
double _x70 = 2*_x14*_x9*_x12*v3;
double _x71 = -1.0*_x6*_x3*_x7*_x25*v3;
double _x72 = 2*_x14*_x9*_x25*v3;
double _x73 = pow(v3,3);
double _x74 = -2*_x1*_x9*v3;
double _x75 = -1.0*_x6*_x3*_x7*_x73;
double _x76 = 2*_x14*_x9*_x73;
Q[ 0] = Fr1;
Q[ 1] = Fr2;
Q[ 2] = Fr3;
Q[ 3] = Fr1*(r1*(_x37+_x36+_x27+_x26-2*_x14*_x9*_x22+1.0*_x6*_x3*_x7*_x22+_x44+_x20)+r3*(_x15+_x13+_x11+_x43+_x42+_x41)+r2*(_x40+_x39+_x38+_x31+_x30+_x29))+Fr2*(r2*(_x37+_x36-2*_x14*_x9*v1*_x25+1.0*_x6*_x3*_x7*v1*_x25+_x24+_x23+_x21+_x20)+r3*(_x19+_x18+1.0*_x1*_x9*_x12+2*_x6*_x3*_x7*_x12-1.0*_x1*_x4*_x12+_x35)+r1*(_x34+_x33+_x32+_x31+_x30+_x29))+Fr3*(r3*(-2*_x14*_x9*v1*_x28+1.0*_x6*_x3*_x7*v1*_x28+_x27+_x26+_x24+_x23+_x21+_x20)+r2*(_x19+_x18-1.0*_x1*_x9*_x12-2*_x6*_x3*_x7*_x12+1.0*_x1*_x4*_x12+_x17)+r1*(_x15+_x13+_x11+_x10+_x8+_x5));
Q[ 4] = Fr1*(r1*(_x60+_x59+_x53+_x52-2*_x14*_x9*_x12*v2+1.0*_x6*_x3*_x7*_x12*v2+_x48+_x47)+r3*(_x19+_x18-1.0*_x1*_x9*_x25-2*_x6*_x3*_x7*_x25+1.0*_x1*_x4*_x25+_x17)+r2*(_x63+_x62+_x61+_x55+_x54+_x44))+Fr2*(r2*(_x60+_x59-2*_x14*_x9*_x51+1.0*_x6*_x3*_x7*_x51+_x50+_x49+_x29+_x47)+r3*(_x46+_x45+_x11+_x10+_x8+_x5)+r1*(_x58+_x57+_x56+_x55+_x54+_x44))+Fr3*(r3*(-2*_x14*_x9*v2*_x28+1.0*_x6*_x3*_x7*v2*_x28+_x53+_x52+_x50+_x49+_x48+_x47)+r2*(_x46+_x45+_x11+_x43+_x42+_x41)+r1*(_x19+_x18+1.0*_x1*_x9*_x25+2*_x6*_x3*_x7*_x25-1.0*_x1*_x4*_x25+_x35));
Q[ 5] = Fr1*(r1*(_x76+_x75+_x72+_x71-2*_x14*_x9*_x12*v3+1.0*_x6*_x3*_x7*_x12*v3+_x74+_x68)+r3*(_x65+_x64+_x58+_x57+_x56+_x44)+r2*(1.0*_x1*_x9*_x28+2*_x6*_x3*_x7*_x28-1.0*_x1*_x4*_x28+_x19+_x18+_x35))+Fr2*(r2*(_x76+_x75-2*_x14*_x9*_x25*v3+1.0*_x6*_x3*_x7*_x25*v3+_x70+_x69+_x74+_x68)+r3*(_x67+_x66+_x40+_x39+_x38+_x29)+r1*(-1.0*_x1*_x9*_x28-2*_x6*_x3*_x7*_x28+1.0*_x1*_x4*_x28+_x19+_x18+_x17))+Fr3*(r3*(-2*_x14*_x9*_x73+1.0*_x6*_x3*_x7*_x73+_x72+_x71+_x70+_x69+_x11+_x68)+r2*(_x67+_x66+_x34+_x33+_x32+_x29)+r1*(_x65+_x64+_x63+_x62+_x61+_x44));
}
void __GeneralizedForce0(double Q0[6], const double v[3], const double th, const double Fr[3], const double r[3]) {
/*
################################################
# Variable: Q0
################################################
*/
double _x1 = pow(th,2);
double _x2 = pow(v1,3);
double _x3 = -r1*_x2;
double _x4 = 15*r2;
double _x5 = pow(v1,2);
double _x6 = -2*r2*_x5;
double _x7 = pow(v2,2);
double _x8 = r1*v1*_x7;
double _x9 = 15*r3*v3;
double _x10 = -2*r3*_x5*v3;
double _x11 = 12*r2*v3;
double _x12 = pow(v3,2);
double _x13 = r1*_x12;
double _x14 = r2*_x2;
double _x15 = -r2*v1*_x7;
double _x16 = 15*r1;
double _x17 = -2*r1*_x5;
double _x18 = -2*r3*v1*v3;
double _x19 = -12*r1*v3;
double _x20 = r2*_x12;
double _x21 = r3*_x2;
double _x22 = r3*v1*_x7;
double _x23 = -2*r1*v3;
double _x24 = _x23-12*r2;
double _x25 = 12*r1;
double _x26 = -2*r2*v3;
double _x27 = _x26+_x25;
double _x28 = -45*r3;
double _x29 = -r3*_x12;
double _x30 = 12*r2;
double _x31 = 12*r3*v3;
double _x32 = 8*r2*v3;
double _x33 = -24*r3;
double _x34 = -24*r2;
double _x35 = -8*r1*v3;
double _x36 = 12*r1*v3;
double _x37 = _x23-8*r2;
double _x38 = _x26+8*r1;
double _x39 = -2*r2*v1;
double _x40 = pow(v2,3);
double _x41 = r1*_x40;
double _x42 = -r1*_x5;
double _x43 = -r2*_x40;
double _x44 = _x7*(-2*r3*v3-2*r1*v1);
double _x45 = r2*_x5;
double _x46 = r3*_x40;
double _x47 = r3*_x5;
double _x48 = -24*r1;
double _x49 = -r1*_x5*v3;
double _x50 = r1*_x7*v3;
double _x51 = -2*r2*v1*v3;
double _x52 = 12*r3;
double _x53 = -2*r3*_x12;
double _x54 = pow(v3,3);
double _x55 = r1*_x54;
double _x56 = r2*_x5*v3;
double _x57 = -r2*_x7*v3;
double _x58 = -2*r1*v1*v3;
double _x59 = r2*_x54;
double _x60 = r3*_x5*v3;
double _x61 = r3*_x7*v3;
double _x62 = -2*r1*_x12;
double _x63 = -2*r2*_x12;
double _x64 = -r3*_x54;
double _x65 = 15*r3;
Q0[ 0] = Fr1;
Q0[ 1] = Fr2;
Q0[ 2] = Fr3;
Q0[ 3] = (Fr3*(v1*(_x29+_x33)+v1*v2*_x38+_x5*_x37+_x36+_x22+_x21+24*r2)+Fr2*(v1*(_x20+_x35+_x34)+v2*(_x18+_x17+_x25)+_x15+_x14+8*r3*_x5+_x33)+Fr1*(v1*(_x13+_x32)+_x10+_x31+_x8+(_x6-8*r3*v1+_x30)*v2+_x3))/24-_x1*(Fr3*(v1*(_x29+_x28)+v1*v2*_x27+_x5*_x24+15*r1*v3+_x22+_x21+60*r2)+Fr2*(v1*(_x20+_x19-45*r2)+v2*(_x18+_x17+_x16)+_x15+_x14+12*r3*_x5-60*r3)+Fr1*(v1*(_x13+_x11-15*r1)+_x10+_x9+_x8+(_x6-12*r3*v1+_x4)*v2+_x3))/360;
Q0[ 4] = (Fr3*(v2*(_x29+v1*_x37+_x47+_x33)+_x7*_x38+_x11+_x46+_x48)+Fr2*(v2*(_x20+_x35+_x45+8*r3*v1)+_x44+_x31+_x43+12*r1*v1)+Fr1*(v2*(_x13+_x18+_x32+_x42+_x48)+_x41+(_x39-8*r3)*_x7+12*r2*v1+24*r3))/24-_x1*(Fr3*(v2*(_x29+v1*_x24+_x47+_x28)+_x7*_x27+15*r2*v3+_x46-60*r1)+Fr2*(v2*(_x20+_x19+_x45+12*r3*v1-15*r2)+_x44+_x9+_x43+15*r1*v1)+Fr1*(v2*(_x13+_x18+_x11+_x42-45*r1)+_x41+(_x39-12*r3)*_x7+15*r2*v1+60*r3))/360;
Q0[ 5] = (Fr3*(_x64+v2*(_x63+8*r1*v3+_x30)+v1*(_x62-8*r2*v3+_x25)+_x61+_x60)+Fr2*(_x59+v2*(_x53+_x58+_x52)-8*r1*_x12+_x57+_x56+8*r3*v1*v3-24*r2*v3+24*r1)+Fr1*(_x55+v1*(_x53+_x52)+8*r2*_x12+v2*(_x51-8*r3*v3)+_x50+_x49-24*r1*v3+_x34))/24-_x1*(Fr3*(_x64+v2*(_x63+_x36+_x4)+v1*(_x62-12*r2*v3+_x16)+_x61+_x60-15*r3*v3)+Fr2*(_x59+v2*(_x53+_x58+_x65)-12*r1*_x12+_x57+_x56+12*r3*v1*v3-45*r2*v3+60*r1)+Fr1*(_x55+v1*(_x53+_x65)+12*r2*_x12+v2*(_x51-12*r3*v3)+_x50+_x49-45*r1*v3-60*r2))/360;
}
void GeneralizedForce(double Q[6], const double v[3], const double Fr[3], const double r[3]) {
double th = sqrt(v1*v1+v2*v2+v3*v3);
if (th < THETA)
return __GeneralizedForce0(Q, v, th, Fr, r);
else
return __GeneralizedForce(Q, v, th, Fr, r);
}
void dRdq( double dRdqw_s[3][3], double dRdqx_s[3][3], double dRdqy_s[3][3], double dRdqz_s[3][3], const double q[4] )
{
const double &qw = q[0];
const double &qx = q[1];
const double &qy = q[2];
const double &qz = q[3];
const double dRdqw[3][3] = {
{ 0 , - 2 * qz ,2 * qy },
{ 2 * qz , 0 , - 2 * qx },
{ - 2 * qy , 2 * qx , 0 }
};
const double dRdqx[3][3] = {
{ 0 , 2 * qy , 2 * qz },
{ 2 * qy , - 4 * qx , - 2 * qw },
{ 2 * qz , 2 * qw , - 4 * qx }
};
const double dRdqy[3][3] = {
{ - 4 * qy , 2 * qx , 2 * qw },
{ 2 * qx , 0 , 2 * qz },
{ - 2 * qw , 2 * qz , - 4 * qy }
};
const double dRdqz[3][3] = {
{ - 4 * qz , - 2 * qw , 2 * qx },
{ 2 * qw , - 4 * qz , 2 * qy },
{ 2 * qx , 2 * qy , 0 }
};
memcpy(dRdqw_s, dRdqw, sizeof(double)*3*3);
memcpy(dRdqx_s, dRdqw, sizeof(double)*3*3);
memcpy(dRdqy_s, dRdqw, sizeof(double)*3*3);
memcpy(dRdqz_s, dRdqw, sizeof(double)*3*3);
}
void GeneralizedForceQuat( double Q[3+4], const double q[4], const double Fr[3], const double r[3] )
{
double dRdq_tensor[4][3][3];
dRdq(dRdq_tensor[0], dRdq_tensor[1], dRdq_tensor[2], dRdq_tensor[3], q);
double a[4][3];
RotatePoint(a[0], dRdq_tensor[0], r);
RotatePoint(a[1], dRdq_tensor[1], r);
RotatePoint(a[2], dRdq_tensor[2], r);
RotatePoint(a[3], dRdq_tensor[3], r);
Q[0] = Fr[0];
Q[1] = Fr[1];
Q[2] = Fr[2];
Q[3] = Dot33(a[0], Fr);
Q[4] = Dot33(a[1], Fr);
Q[5] = Dot33(a[2], Fr);
Q[6] = Dot33(a[3], Fr);
}
void RotationMatrixFromQuat( double R[3][3], const double q[4] )
{
ArnQuat aq(q[1],q[2],q[3],q[0]);
ArnMatrix amat;
aq.getRotationMatrix(&amat);
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
R[i][j] = amat.m[i][j];
}
| [
"[email protected]",
"Dan@Dan-PC.(none)"
] | [
[
[
1,
9
],
[
11,
584
]
],
[
[
10,
10
]
]
] |
e6efd8178406e0ae8583d3ab023bae45f6aabb2e | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/wheel/WheelAnimalController/src/WinEffect.cpp | 6cd8a828691c30b86a9714df3babc6817d974a33 | [] | no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 5,920 | cpp | #include "WheelAnimalControllerStableHeaders.h"
#include "WinEffect.h"
#include "ThirdParty/Ofusion/OgreOSMScene.h"
#include "Ogre/OgreRibbonTrail.h"
#include <orz/View_OGRE3D/OgreGraphicsManager.h>
//#include "WheelDB.h"
using namespace Orz;
inline static void GetNode(Ogre::SceneNode ** node, /*WheelEnum e,*/const std::string & name, boost::shared_ptr<WheelAnimalSceneObj> scene)
{
//if(WHEEL_HAS(e))
//{
(*node) = OgreGraphicsManager::getSingleton().getSceneManager()->getSceneNode(name);
//}
//else
//{
// (*node) = scene->getNullSceneNode();
//}
}
WinEffect::WinEffect(boost::shared_ptr<WheelAnimalSceneObj> scene):_effect(0),_billboardIsload(false)
{
GetNode(&_leyuan_tx_caitiao, "leyuan_tx_caitiao",scene);
GetNode(&_leyuan_tx_bluehua, "leyuan_tx_bluehua",scene);
GetNode(&_leyuan_tx_caijinyanhua1, "leyuan_tx_caijinyanhua1",scene);
GetNode(&_leyuan_tx_caijinyanhua2, "leyuan_tx_caijinyanhua2",scene);
GetNode(&_zp_ptj1a, "zp_ptj1a",scene);
GetNode(&_zp_ptj1b, "zp_ptj1b",scene);
_sceneAnimation = scene->getSceneAnimation(SCENE_ANIMATION_1);
_starAnimation = scene->getSceneAnimation(SCENE_ANIMATION_4);
_sceneAnimation->setLoop(false);
_sceneAnimation->setEnabled(true);
_starAnimation->setLoop(true);
_starAnimation->setEnabled(true);
clear();
}
void WinEffect::show(Effect effect)
{
_effect |= effect;
}
void WinEffect::hideEffect()
{
_leyuan_tx_caitiao->setVisible(false);
_leyuan_tx_bluehua->setVisible(false);
_leyuan_tx_caijinyanhua1->setVisible(false);
_leyuan_tx_caijinyanhua2->setVisible(false);
_zp_ptj1a->setVisible(false);
_zp_ptj1b->setVisible(false);
}
void WinEffect::clear(void)
{
Ogre::MaterialPtr material = Ogre::MaterialPtr(Ogre::MaterialManager::getSingleton().getByName("Standard_7"));
material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName("guang.bmp");
_leyuan_tx_caitiao->setVisible(false);
_leyuan_tx_bluehua->setVisible(false);
_leyuan_tx_caijinyanhua1->setVisible(false);
_leyuan_tx_caijinyanhua2->setVisible(false);
_zp_ptj1a->setVisible(false);
_zp_ptj1b->setVisible(false);
_sceneAnimation->setEnabled(true);
_sceneAnimation->setTimePosition(0.f);
_starAnimation->setEnabled(true);
_starAnimation->setTimePosition(0.f);
_effect = 0;
_reset();
}
//ÐÇÐÇ×·Î²ÌØÐ§
void WinEffect::setupTrailStars(void)
{
Ogre::SceneManager * sm = Orz::OgreGraphicsManager::getSingleton().getSceneManager();
/* Ogre::Vector3 dir(-1, -1, 0.5);
dir.normalise();
Ogre::Light* l = sm->createLight("light1");
l->setType(Ogre::Light::LT_DIRECTIONAL);
l->setDirection(dir);*/
Ogre::NameValuePairList pairList;
pairList["numberOfChains"] = "2";
pairList["maxElements"] = "50";
Ogre::RibbonTrail* trail = static_cast<Ogre::RibbonTrail*>(sm->createMovableObject("1","RibbonTrail", &pairList));
trail->setMaterialName("Examples/LightRibbonTrail");
trail->setTrailLength(600);
Ogre::RibbonTrail* trail2 = static_cast<Ogre::RibbonTrail*>(sm->createMovableObject("2","RibbonTrail", &pairList));
trail2->setMaterialName("Examples/LightRibbonTrail");
trail2->setTrailLength(600);
sm->getRootSceneNode()->createChildSceneNode()->attachObject(trail);
sm->getRootSceneNode()->createChildSceneNode()->attachObject(trail2);
trail->setInitialColour(0, 1.0f,1.0f, 0.1f);
trail->setColourChange(0, 1.0f, 1.0f, 1.0f, 1.0f);
trail->setInitialWidth(0, 80);
trail->setWidthChange(0,135);
trail->addNode(_zp_ptj1a);
trail2->setInitialColour(0, 1.0f, 1.0f, 0.1f);
trail2->setColourChange(0, 1.0f, 1.0f, 1.0f, 1.0f);
trail2->setInitialWidth(0, 80);
trail2->setWidthChange(0,135);
trail2->addNode(_zp_ptj1b);
//// Add light
//Ogre::Light* l1 = sm->createLight("l1");
//l1->setDiffuseColour(trail->getInitialColour(0));
//_zp_ptj1a->attachObject(l1);
//// Add billboard
//Ogre::BillboardSet* bbs = sm->createBillboardSet("bb", 1);
//bbs->createBillboard(Ogre::Vector3::ZERO, trail->getInitialColour(0));
//bbs->setMaterialName("Examples/Flare");
//_zp_ptj1a->attachObject(bbs);
//// Add light
//Ogre::Light* l2 = sm->createLight("l2");
//l2->setDiffuseColour(trail->getInitialColour(0));
//_zp_ptj1b->attachObject(l2);
//// Add billboard
//Ogre::BillboardSet* bbs2 = sm->createBillboardSet("bb2", 1);
//bbs2->createBillboard(Ogre::Vector3::ZERO, trail->getInitialColour(0));
//bbs2->setMaterialName("Examples/Flare");
//_zp_ptj1b->attachObject(bbs2);
}
void WinEffect::enable(void)
{
if(_effect & Effect4)
{
_sceneAnimation->setEnabled(true);
_sceneAnimation->setTimePosition(0.f);
_leyuan_tx_caijinyanhua1->setVisible(true);
_leyuan_tx_caijinyanhua2->setVisible(true);
Ogre::MaterialPtr material = Ogre::MaterialPtr(Ogre::MaterialManager::getSingleton().getByName("Standard_7"));
material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName("black.png");
}
if(_effect & Effect2)
{
_leyuan_tx_caitiao->setVisible(true);
}
if(_effect & Effect3)
{
_leyuan_tx_bluehua->setVisible(true);
}
if(_effect & Effect1)
{
if(_billboardIsload == false)
{
setupTrailStars();
_billboardIsload = true;
}
_starAnimation->setEnabled(true);
_starAnimation->setTimePosition(0.f);
_zp_ptj1a->setVisible(true);
_zp_ptj1b->setVisible(true);
}
}
bool WinEffect::update(TimeType interval)
{
_update2enable();
if(_effect & Effect4)
{
_sceneAnimation->addTime(interval);
return !_sceneAnimation->hasEnded();
}
if(_effect & Effect1)
{
_starAnimation->addTime(interval);
}
//_sn->yaw(Ogre::Radian(1.f));
// _animation->addTime(interval);
return false;
}
WinEffect::~WinEffect(void)
{
}
| [
"[email protected]"
] | [
[
[
1,
232
]
]
] |
85eee2c31df99de44b041f64af9991ed04074c30 | 2d22825193eacf3669ac8bd7a857791745a9ead4 | /HairSimulation/HairSimulation/src/AppBox.cpp | 4479ddf7c9728f60b30a9f4359bce0a979403b45 | [] | 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 | UTF-8 | C++ | false | false | 1,939 | cpp | #include "AppBox.h"
#include "World.h"
#include "Hair.h"
int AppBox::cNumAppBox = 0;
//--------------------------------------------------------------------
AppBox::AppBox() : ApplicationObject()
{
mDimensions.x = Hair::HAIR_THICKNESS;
mDimensions.y = Hair::HAIR_THICKNESS;
mDimensions.z = Hair::HAIR_EDGE_LENGTH;
String name = "AppBox" + StringConverter::toString(cNumAppBox++);
setUp(name);
}
//--------------------------------------------------------------------
AppBox::AppBox(const Ogre::String &name, Real width, Real height, Real depth) : ApplicationObject(name)
{
mDimensions.x = width;
mDimensions.y = height;
mDimensions.z = depth;
setUp(name);
}
//--------------------------------------------------------------------
AppBox::~AppBox()
{
}
//--------------------------------------------------------------------
void AppBox::setUp(const Ogre::String &name)
{
// Create visual presence
SceneManager* sm = World::getSingleton().getSceneManager();
mEntity = sm->createEntity(name, "cube.mesh");
mSceneNode = sm->getRootSceneNode()->createChildSceneNode(name);
// Scale down, default size is 100x100x100
mSceneNode->scale(mDimensions.x / 100.0f,
mDimensions.y / 100.0f,
mDimensions.z / 100.0f);
mSceneNode->attachObject(mEntity);
// Add reverse reference
mEntity->setUserObject(this);
}
//--------------------------------------------------------------------
void AppBox::setMaterialName(const String& matName)
{
mEntity->setMaterialName(matName);
}
//--------------------------------------------------------------------
void AppBox::setPositionByEnds(const Vector3 &a, const Vector3 &b)
{
mSceneNode->setPosition(a.midPoint(b));
mSceneNode->resetOrientation();
mDimensions.z = a.distance(b);
mSceneNode->setScale(mDimensions.x / 100.0,
mDimensions.y / 100.0,
mDimensions.z / 100.0);
mSceneNode->setDirection(b-a);
} | [
"grahamhuang@73147322-a748-11dd-a8c6-677c70d10fe4"
] | [
[
[
1,
67
]
]
] |
f27b18aaa2f589a8934dac9f4b2ff33a7880174a | 02cd7f7be30f7660f6928a1b8262dc935673b2d7 | / invols --username [email protected]/rf_panel.h | 8a3c088f14d24d577afaca90a735e07bafb6aa3f | [] | no_license | hksonngan/invols | f0886a304ffb81594016b3b82affc58bd61c4c0b | 336b8c2d11d97892881c02afc2fa114dbf56b973 | refs/heads/master | 2021-01-10T10:04:55.844101 | 2011-11-09T07:44:24 | 2011-11-09T07:44:24 | 46,898,469 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 664 | h | #ifndef RF_PANEL_INC
#define RF_PANEL_INC
#include "AllInc.h"
#include "wxIncludes.h"
#include "wx/things/spinctld.h"
// Raw Files interpretation panel
class RFPanel: public wxPanel
{
public:
RFPanel(wxWindow *frame);
// void OnSpinBoxD(wxSpinEvent& event);
// void OnSpinBoxI(wxCommandEvent& event);
void OnBtnOK(wxCommandEvent& event);
void OnBtnDir(wxCommandEvent& event);
void Update_(bool self);
void Save(wxFile& fs);
void Load(wxFile& fs);
//int GetOffset();
private:
wxSpinCtrl *spin_data_size[3],*spin_offset;
wxSpinCtrlDbl *spin_spacing[3];
wxCheckBox *m_check_box[10];
DECLARE_EVENT_TABLE()
};
#endif | [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
b46be171fe126be222ad57c1f7f3008e3033b9c9 | 3e3d5fa109cdd653d43867b46307683514d916a0 | /examples/benchmark/Benchmark.h | 5f6eb78ec6e5bc2814750e0bc533bb10866594fa | [] | no_license | badog1011/aquila | b8a767ea07829934bbbb2b2a4e501e473cfae301 | 887a63ddb032cfc7f71cce72a439b5b5dd2fe65c | refs/heads/master | 2016-08-12T00:32:19.598867 | 2010-03-25T11:28:56 | 2010-03-25T11:28:56 | 50,173,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | h | #ifndef BENCHMARK_H
#define BENCHMARK_H
#include <vector>
#include <boost/timer.hpp>
#include "aquila/feature/MfccExtractor.h"
class Benchmark
{
public:
Benchmark(int iterations_count);
~Benchmark();
void run();
private:
void testFft();
void testDct();
void testWavefile();
void testEnergy();
void testMfcc();
void testDtw();
double clock();
boost::timer t;
int ITERATIONS;
double startTime;
std::vector<double> durations;
Aquila::MfccExtractor* extractor;
};
double generateRandomDouble();
#endif // BENCHMARK_H
| [
"antyqjon@e3e259e2-fbb7-11de-bceb-371847987001"
] | [
[
[
1,
38
]
]
] |
daf4ad3aaa1d61a8ec00b5c9eca82ed5b78c18a3 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/SupportWFLib/symbian/VersionFileReader.h | d7549e94d1305009a28d3524650be0f893803789 | [
"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 | 4,420 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef VERSION_FILE_READER_H
#define VERSION_FILE_READER_H
#include <e32base.h>
class CVersionFileReader : public CBase
{
public:
/**
* @name Enums used to select which part of the version number you
* want.
*/
//@{
/** This enum selects parts of the newversion file. */
enum TNewVersionType {
/** The full (major, minor, misc) app version. Period-separated. */
ENewAppFullVersion = 0,
/** The major and minor app version. Period separated. */
ENewAppMajorMinorVersion = 1,
/** The misc app version.*/
ENewAppMiscNumber = 2,
/** The full (major, minoe, misc) voice version. Period separated. */
ENewResFullVersion = 3,
/** The major and minor voice version. Period separated. */
ENewResMajorMinorVersion = 4,
/** The misc voice version. */
ENewResMiscNumber = 5,
/** The version number of the mlfw upgrade.*/
ENewMlfwVersion = 6,
/**
* This is for internal use. Using it as an argument in any
* function will probably cause a panic.
*/
ENewVersionArraySize = 7
};
/** This enum selects parts of the oldversion file. */
enum TOldVersionType {
/**
* Full version (major, minor, misc). Major and minor are
* separated by a period. minor and misc are separated by an
* underscore.
*/
EOldFullVersion = 0,
/** Major and minor version. Period separated*/
EOldMajorMinorVersion = 1,
/** Misc version. */
EOldMiscNumber = 2,
/** MLFW upgrade version*/
EOldMlfwVersion = 0,
};
//@}
/** @name Constructors and destructor. */
//@{
private:
/** Default constructor. */
CVersionFileReader();
/** Second phase constructor. */
void ConstructL();
public:
/**
* Static constructor.
* @return a new CVersionFileReader object.
*/
static class CVersionFileReader* NewL();
/**
* Static constructor.
* @return a new CVersionFileReader object, still on the top of the
* cleanupstack.
*/
static class CVersionFileReader* NewLC();
/** Virtual destructor. */
virtual ~CVersionFileReader();
//@}
TInt ReadNewVersionFileL(const TDesC& versionFile);
TInt ReadOldVersionFileL(const TDesC& aFilename);
TPtrC8 GetNewVersion(enum TNewVersionType aVersionType);
TPtrC8 GetOldVersion(enum TOldVersionType aVersionType);
class TVersion NewVersion(enum TNewVersionType aVersionType);
class TVersion OldVersion(enum TOldVersionType aVersionType);
private:
class CDesC8Array* iNewVersionArray;
class CDesC8Array* iOldVersionArray;
};
#endif /* VERSION_FILE_READER_H */
| [
"[email protected]"
] | [
[
[
1,
112
]
]
] |
15f3845d8891ba95785832e750d9dedb8d8ecaf3 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/MyGUIEngine/include/MyGUI_ResourceSkin.h | 6a2431a31803a74b7062986216f9638545b0f5fd | [] | no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,703 | h | /*!
@file
@author Albert Semenov
@date 11/2007
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_RESOURCE_SKIN_H__
#define __MYGUI_RESOURCE_SKIN_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_SubWidgetBinding.h"
#include "MyGUI_ChildSkinInfo.h"
#include "MyGUI_MaskPickInfo.h"
#include "MyGUI_IResource.h"
#include "MyGUI_SubWidgetInfo.h"
namespace MyGUI
{
// вспомогательный класс для инициализации одного скина
class MYGUI_EXPORT ResourceSkin :
public IResource
{
MYGUI_RTTI_DERIVED( ResourceSkin )
public:
ResourceSkin();
virtual ~ResourceSkin();
virtual void deserialization(xml::ElementPtr _node, Version _version);
const IntSize& getSize() const
{
return mSize;
}
const std::string& getTextureName() const
{
return mTexture;
}
const VectorSubWidgetInfo& getBasisInfo() const
{
return mBasis;
}
const MapWidgetStateInfo& getStateInfo() const
{
return mStates;
}
const MapString& getProperties() const
{
return mProperties;
}
const VectorChildSkinInfo& getChild() const
{
return mChilds;
}
const std::string& getSkinName() const
{
return mSkinName;
}
private:
void setInfo(const IntSize& _size, const std::string& _texture);
void addInfo(const SubWidgetBinding& _bind);
void addProperty(const std::string& _key, const std::string& _value);
void addChild(const ChildSkinInfo& _child);
void clear();
void checkState(const MapStateInfo& _states);
void checkState(const std::string& _name);
void checkBasis();
void fillState(const MapStateInfo& _states, size_t _index);
private:
IntSize mSize;
std::string mTexture;
VectorSubWidgetInfo mBasis;
MapWidgetStateInfo mStates;
// дополнительные параметры скина
MapString mProperties;
// дети скина
VectorChildSkinInfo mChilds;
std::string mSkinName;
};
} // namespace MyGUI
#endif // __MYGUI_RESOURCE_SKIN_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
] | [
[
[
1,
102
]
]
] |
3205cb2321ca97d8bb1528a71226f99005da0cfb | 8a3fce9fb893696b8e408703b62fa452feec65c5 | /SendMail/SendMail/SendMailDlg.h | fa90329088ea19b20c3fdab79c5e03601be10a54 | [] | no_license | win18216001/tpgame | bb4e8b1a2f19b92ecce14a7477ce30a470faecda | d877dd51a924f1d628959c5ab638c34a671b39b2 | refs/heads/master | 2021-04-12T04:51:47.882699 | 2011-03-08T10:04:55 | 2011-03-08T10:04:55 | 42,728,291 | 0 | 2 | null | null | null | null | GB18030 | C++ | false | false | 913 | h | // SendMailDlg.h : 头文件
//
#pragma once
class CSendMailDlgAutoProxy;
// CSendMailDlg 对话框
class CSendMailDlg : public CDialog
{
DECLARE_DYNAMIC(CSendMailDlg);
friend class CSendMailDlgAutoProxy;
// 构造
public:
CSendMailDlg(CWnd* pParent = NULL); // 标准构造函数
virtual ~CSendMailDlg();
// 对话框数据
enum { IDD = IDD_SENDMAIL_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
CSendMailDlgAutoProxy* m_pAutoProxy;
HICON m_hIcon;
BOOL CanExit();
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnClose();
virtual void OnOK();
virtual void OnCancel();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedButton1();
};
| [
"[email protected]"
] | [
[
[
1,
45
]
]
] |
a56bafa7ac22b2524bc8d17af4dc52468f04c5aa | a3de460e3b893849fb01b4c31bd30a908160a1f8 | /nil/file.hpp | ae90a4c3c52345dc95cad0992a218369933cface | [] | no_license | encratite/nil | 32b3d0d31124dd43469c07df2552f1c3510df36d | b441aba562d87f9c14bfce9291015b7622a064c6 | refs/heads/master | 2022-06-19T18:59:06.212567 | 2008-12-23T05:58:00 | 2008-12-23T05:58:00 | 262,275,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,219 | hpp | #ifndef NIL_FILE_HPP
#define NIL_FILE_HPP
#include <string>
#include <vector>
#include <cstdio>
#include <nil/exception.hpp>
#include <nil/memory.hpp>
#include <nil/types.hpp>
namespace nil
{
enum file_mode
{
file_mode_big_endian,
file_mode_little_endian
};
class file
{
public:
file();
file(std::string const & file_name, bool create_file = false);
~file();
bool is_open() const;
void set_mode(file_mode new_file_mode);
void use_big_endian();
void use_little_endian();
bool open(std::string const & file_name, bool create_file = false);
void close();
std::size_t read(char * output, std::size_t bytes);
std::string read(std::size_t bytes);
ulong read_dword();
ulong read_word();
char read_byte();
void write(char const * data, std::size_t bytes);
void write(std::string const & data);
void write_dword(ulong data);
void write_word(ulong data);
void write_byte(char data);
std::size_t get_pointer() const;
void set_pointer(std::size_t offset);
void seek_end();
std::size_t get_size();
void skip(std::size_t offset);
private:
FILE * file_descriptor;
file_mode mode;
bool read_data(char * output, std::size_t bytes, std::size_t & bytes_read);
void write_data(char const * output, std::size_t bytes);
void write_bytes(ulong input, std::size_t size);
ulong read_bytes(std::size_t size);
void check_file_descriptor() const;
void error_file_descriptor();
void error_unknown();
};
bool read_file(std::string const & file_name, std::string & output);
bool write_file(std::string const & file_name, std::string const & input);
bool append_to_file(std::string const & file_name, std::string const & input);
bool read_lines(std::string const & file_name, std::vector<std::string> & output);
bool read_directory(std::string const & path, std::vector<std::string> & output);
bool move_file(std::string const & file_name, std::string const & new_name);
bool get_file_size(std::string const & path, ullong & output);
std::string get_file_size_string(ullong file_size);
bool create_directory(std::string const & path);
}
#endif
| [
"[email protected]"
] | [
[
[
1,
91
]
]
] |
677a4329dec663d1cf931af602a1d35403df084b | 1e299bdc79bdc75fc5039f4c7498d58f246ed197 | /ServerLib/StateObject.cpp | f53048ba4478185cb33f3ce57269b6fcef4a25f7 | [] | no_license | moosethemooche/Certificate-Server | 5b066b5756fc44151b53841482b7fa603c26bf3e | 887578cc2126bae04c09b2a9499b88cb8c7419d4 | refs/heads/master | 2021-01-17T06:24:52.178106 | 2011-07-13T13:27:09 | 2011-07-13T13:27:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,892 | cpp | //--------------------------------------------------------------------------------
//
// Copyright (c) 1999 MarkCare Solutions
//
// Programming by Rich Schonthal
//
//--------------------------------------------------------------------------------
#include "stdafx.h"
#include "StateObject.h"
#include "SystemObject.h"
#include <ReadLock.h>
#include <WriteLock.h>
//--------------------------------------------------------------------------------
#include "waitlen.h"
//--------------------------------------------------------------------------------
CStateObject::CStateObject(int nValue)
: m_nClients(0)
, m_nClientsInSync(0)
, m_nValue(nValue)
, m_evtClientSync(false, true)
, m_evtChanged(false, true)
{
}
//--------------------------------------------------------------------------------
CStateObject::~CStateObject()
{
}
//--------------------------------------------------------------------------------
bool CStateObject::SetValue(int nValue)
{
int nPrev = ::InterlockedExchange(&m_nValue, nValue);
if(nPrev != m_nValue)
{
m_evtClientSync.ResetEvent();
m_evtChanged.SetEvent();
}
return true;
}
//--------------------------------------------------------------------------------
int CStateObject::GetValue()
{
return (int) m_nValue;
}
//--------------------------------------------------------------------------------
void CStateObject::AddClient()
{
::InterlockedIncrement(&m_nClients);
}
//--------------------------------------------------------------------------------
void CStateObject::RemoveClient()
{
::InterlockedDecrement(&m_nClients);
}
//--------------------------------------------------------------------------------
void CStateObject::AcknowledgeChange()
{
if(m_nClients == 0)
return;
if(::InterlockedIncrement(&m_nClientsInSync) >= m_nClients)
{
m_nClientsInSync = 0;
m_evtClientSync.SetEvent();
m_evtChanged.ResetEvent();
}
}
#ifdef _DEBUG
//--------------------------------------------------------------------------------
static struct tagStateNames
{
int nState;
LPCTSTR pName;
} g_stateNames[] =
{
STATE_UNKNOWN, _T("STATE_UNKNOWN"),
STATE_INIT, _T("STATE_INIT"),
STATE_RUN, _T("STATE_RUN"),
STATE_PAUSE, _T("STATE_PAUSE"),
STATE_STOP, _T("STATE_STOP"),
STATE_EXIT, _T("STATE_EXIT"),
STATE_ERROR, _T("STATE_ERROR"),
STATE_NOSTATE, _T("STATE_NOSTATE"),
STATE_UNATTAINED, _T("STATE_UNATTAINED"),
0, NULL
};
//--------------------------------------------------------------------------------
LPCTSTR CStateObject::GetStateName(int nState) const
{
LPCTSTR sTemp = _T("");
for(int i = 0; ; i++)
{
if(g_stateNames[i].pName == NULL)
break;
if(g_stateNames[i].nState == nState)
{
sTemp = g_stateNames[i].pName;
break;
}
}
return sTemp;
}
#endif
| [
"[email protected]"
] | [
[
[
1,
117
]
]
] |
ad32f8f0871452c4eb406475191d54af21496fec | 99d3989754840d95b316a36759097646916a15ea | /trunk/2011_09_07_to_baoxin_gpd/ferrylibs/test/Test_FMC.h | 81d7ccef4cd761f0b3f5c3ccabd82f441068a8a4 | [] | no_license | svn2github/ferryzhouprojects | 5d75b3421a9cb8065a2de424c6c45d194aeee09c | 482ef1e6070c75f7b2c230617afe8a8df6936f30 | refs/heads/master | 2021-01-02T09:20:01.983370 | 2011-10-20T11:39:38 | 2011-10-20T11:39:38 | 11,786,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,755 | h | #pragma once
#include <iostream>
#include <fstream>
#include <ferry/cv_geometry/DLT_FMC.h>
#include <ferry/cv_geometry/RANSAC_FMC.h>
#include <ferry/cv_geometry/Normalized_FMC.h>
#include <ferry/cv_geometry/OpenCV_FMC.h>
#include <ferry/cv_geometry/IOUtil.h>
#include <ferry/cv_geometry/DrawingUtil.h>
#include <ferry/cv_geometry/PointCorrespondences.h>
using namespace std;
using namespace ferry::cv_geometry;
using namespace ferry::cv_geometry::io_util;
namespace ferry {
namespace cv_geometry {
namespace test {
class Test_FMC
{
public:
void test() {
test_DLT_FMC();
}
void test_DLT_FMC() {
char* file1 = "data/CindyData/cam1_p.txt";
char* file2 = "data/CindyData/cam4_p.txt";
char* im1_file = "data/CindyData/cam1_image0050.png";
char* im2_file = "data/CindyData/cam4_image0050.png";
char* F_file = "data/CindyData/cam1_cam4_F.txt";
char* pc_file = "data/CindyData/cam1_cam4_pc.txt";
vector<CvPoint2D32f> x1s;
vector<CvPoint2D32f> x2s;
ifstream ifs1(file1);
ifs1>>x1s;
ifs1.close();
ifstream ifs2(file2);
ifs2>>x2s;
ifs2.close();
PointCorrespondences pc(x1s, x2s);
ofstream pcofs(pc_file);
pcofs<<pc;
pcofs.close();
DLT_FMC dltfmc;
//Normalized_FMC nfmc(&dltfmc);
RANSAC_FMC ransac_fmc(0.05);
Normalized_FMC nfmc(&ransac_fmc);
//OpenCV_FMC nfmc(CV_FM_RANSAC, 1, 0.99);
//OpenCV_FMC nfmc(CV_FM_LMEDS, 1, 0.99);
//FundamentalMatrix fm = dltfmc.compute(x1s, x2s);
FundamentalMatrix fm = nfmc.compute(x1s, x2s);
cout<<fm.toString()<<endl;
ofstream ffs(F_file);
ffs<<fm.getF();
ffs.close();
FundamentalMatrixErrorCalculator* pfmec = new PointLine_FMEC();
//FundamentalMatrixErrorCalculator* pfmec = new SimpleMultiply_FMEC();
FundamentalMatrixBatchErrorCalculator fmbec(fm.getF(), pfmec);
double error = fmbec.compute(x1s, x2s);
cout<<"error: "<<error<<endl;
FundamentalMatrixInlierOutlierModel fmiom(fm.getF(), pfmec, 1.0);
vector<CvPoint2D32f> ix1s, ix2s, ox1s, ox2s;
fmiom.classify(x1s, x2s, ix1s, ix2s, ox1s, ox2s);
ofstream x1fs("temp/ix1s.txt");
x1fs<<ix1s;
x1fs.close();
ofstream x2fs("temp/ix2s.txt");
x2fs<<ix2s;
x2fs.close();
//char* im1_file = "data/MS_Video/dancing/3_jpg_small.jpg";
//char* im2_file = "data/MS_Video/dancing/4_jpg_small.jpg";
//char* im1_file = "C:/zj/vcprojects/cv_3d_reconstruction/test_cv_geometry/data/snoopy3/0808.jpg";
//char* im2_file = "C:/zj/vcprojects/cv_3d_reconstruction/test_cv_geometry/data/snoopy3/0809.jpg";
//char* im1_file = "data/olympus/1_small.jpg";
//char* im2_file = "data/olympus/3_small.jpg";
//char* im1_file = "C:/zj/vcprojects/cv_3d_reconstruction/test_cv_geometry/data/simulation/view_3.bmp";
//char* im2_file = "C:/zj/vcprojects/cv_3d_reconstruction/test_cv_geometry/data/simulation/view_1.bmp";
IplImage* im1 = cvLoadImage(im1_file, 1);
IplImage* im2 = cvLoadImage(im2_file, 1);
::draw_correspondences_image("cos1", im1, cvPointsFrom32fs(x1s), cvPointsFrom32fs(x2s));
::draw_correspondences_image("cos2", im1, im2, cvPointsFrom32fs(x1s), cvPointsFrom32fs(x2s));
::draw_correspondences_image("inliers cos1", im1, cvPointsFrom32fs(ix1s), cvPointsFrom32fs(ix2s));
CvMat* F = fm.getF();
drawEpipoleLines(im1, im2, F);
int i = 1;
drawEpipolarLine(im1, im2, F, cvPoint2D32f(261.0, 408.0), cvPoint2D32f(149.0, 412.0));
drawEpipolarLine(im1, im2, F, cvPoint2D32f(185.0, 316.0), cvPoint2D32f(96.0, 322.0));
drawEpipolarLine(im1, im2, F, cvPoint2D32f(229.0, 76.0), cvPoint2D32f(165.0, 82.0));
drawEpipolarLine(im1, im2, F, x1s[0], x2s[0]);
drawEpipolarLine(im1, im2, F, x1s[2], x2s[2]);
drawEpipolarLine(im1, im2, F, x1s[1], x2s[1]);
cvNamedWindow("im1", 1);
cvNamedWindow("im2", 1);
cvShowImage("im1", im1);
cvShowImage("im2", im2);
}
void drawEpipolarLine(IplImage* im1, IplImage* im2, CvMat* F, const CvPoint2D32f& p1, const CvPoint2D32f& p2) {
drawCross(im1, cvPointFrom32f(p1));
drawCross(im2, cvPointFrom32f(p2));
CvMat* mx1 = hmatFromPoint2D(p1);
CvMat* line2 = matMul(F, mx1);
drawLine(im2, line2, CV_RGB(255, 0, 0));
CvMat* mx2 = hmatFromPoint2D(p2);
CvMat* line1 = matMul(transpose(F), mx2);
drawLine(im1, line1, CV_RGB(255, 0, 0));
cout<<"point2: "<<mx2<<endl;
cout<<"line2: "<<line2<<endl;
cout<<"point line distance: "<<point2LineDistance(mx2, line2)<<endl;
cout<<"point line distance: "<<point2LineDistance(mx1, line1)<<endl;
cout<<"point1: "<<mx1<<endl;
cout<<"line1: "<<line1<<endl;
cout<<"point line distance: "<<point2LineDistance(mx1, line1)<<endl;
//cout<<"Pfmec: "<<pfmec->compute(F, p1, p2)<<endl;
}
};
}
}
} | [
"ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2"
] | [
[
[
1,
152
]
]
] |
2c4746c4301625981d3bef622cd018722bb97744 | 171daeea8e21d62e4e1ea549f94fcf638c542c25 | /JiangChen/SNARC MMOCAP 091109/real time1107/real time 1016/OGLView.cpp | e29767f30dca0001286849a963bb3e91c94ecf3b | [] | no_license | sworldy/snarcmotioncapture | b8c848ee64212cfb38f002bdd183bf4b6257a9c7 | d4f57f0b7e2ecda6375c11eaa7f6a6b6d3d0af21 | refs/heads/master | 2021-01-13T02:02:54.097775 | 2011-08-07T16:46:24 | 2011-08-07T16:46:24 | 33,110,437 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 69,215 | cpp | ///////////////////////////////////////////////////////////////////////////////
//
// OGLView.cpp : implementation file
//
// Purpose: Implementation of OpenGL Window of Hierarchical Animation System
//
// Created:
// JL 9/1/97
// Versions:
// 1.01 12/20/97 Fix perspective in OpenGL Resize Code
// 1.02 1/10/97 Change to display code to handle skeletal hierarchy
// Modified:
// JL 9/10/99 Created skeleton Demo for Oct 99 GDMag
//
///////////////////////////////////////////////////////////////////////////////
//
// Copyright 1999 Jeff Lander, All Rights Reserved.
// For educational purposes only.
// Please do not republish in electronic or print form without permission
// Thanks - [email protected]
//
///////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <mmsystem.h>
#include <math.h>
#include "Skully.h"
#include "OGLView.h"
#include "LoadOBJ.h"
#include "LoadSkel.h" // Skeleton loading
#include "EulerAngles.h"
#include "QuatTypes.h"
#include <cstring>
#include <fstream>
using namespace std;
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/// Application Definitions ///////////////////////////////////////////////////
#define OGL_AXIS_DLIST 1 // OPENGL DISPLAY LIST ID
#define OGL_SELECTED_DLIST 2 // SELECTED BONE OPENGL DISPLAY LIST
#define ROTATE_SPEED 1.0 // SPEED OF ROTATION
///////////////////////////////////////////////////////////////////////////////
/// Global Variables //////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// COGLView
COGLView::COGLView()
{
// INITIALIZE THE MODE KEYS
m_StatusBar = NULL; // CLEAR THIS. IT IS SET BY MAINFRAME BUT UNTIL THEN MARK IT
m_DrawSkeleton = TRUE;
m_DrawDeformed = FALSE;
m_PickX = -1;
m_PickY = -1;
ResetBone(&m_Skeleton,NULL);
m_SelectedBone = &m_Skeleton;
// INITIALIZE SOME OF THE CAMERA VARIABLES
ResetBone(&m_Camera, NULL);
m_Camera.id = -1;
strcpy(m_Camera.name,"Camera");
m_Camera.rot.x = 0.0f;
m_Camera.rot.y = 0.0f;
m_Camera.rot.z = 0.0f;
m_Camera.b_rot.x = 0.0f;
m_Camera.b_rot.y = 0.0f;
m_Camera.b_rot.z = 0.0f;
m_Camera.b_trans.y = -10.5f;
// m_Camera.b_trans.z = -50.0f;
// m_Camera.trans.x = -0.0f;
// m_Camera.trans.y = -12.0f;
// m_Camera.trans.z = -10.0f;
m_Camera.trans.y = -10.0f;
m_Camera.trans.z = -120.0f;
///////////////////////////////////////////////////
////////////////////////////////////////////////////////
//Quat quater = EulerToQuat(m_Camera.rot.x,m_Camera.rot.y,m_Camera.rot.z);
//m_Camera.axisangle = QuaternionToAxisAngle(quater);
m_Model.vertexData = NULL;
freadout2 = fopen("readout02","wb");//add by wz
cur_index = (int*)malloc(1000 * sizeof(int));
recod_ver_id = (int*)malloc(8438 * sizeof(int));
Play_Animation = 0;
}
COGLView::~COGLView()
{
fclose(freadout2);
free(cur_index);
free(recod_ver_id);
}
BOOL COGLView::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext)
{
return CWnd::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID, pContext);
}
BEGIN_MESSAGE_MAP(COGLView, CWnd)
//{{AFX_MSG_MAP(COGLView)
ON_WM_CREATE()
ON_WM_DESTROY()
ON_WM_PAINT()
ON_WM_LBUTTONDOWN()
ON_WM_RBUTTONDOWN()
ON_WM_MOUSEMOVE()
ON_WM_MOVE()
ON_WM_LBUTTONUP()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COGLView message handlers
BOOL COGLView::SetupPixelFormat(HDC hdc)
{
/// Local Variables ///////////////////////////////////////////////////////////
PIXELFORMATDESCRIPTOR pfd, *ppfd;
int pixelformat;
///////////////////////////////////////////////////////////////////////////////
ppfd = &pfd;
ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
ppfd->nVersion = 1;
ppfd->dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
ppfd->dwLayerMask = PFD_MAIN_PLANE;
ppfd->iPixelType = PFD_TYPE_RGBA;
ppfd->cColorBits = 16;
ppfd->cDepthBits = 16;
ppfd->cAccumBits = 0;
ppfd->cStencilBits = 0;
pixelformat = ChoosePixelFormat(hdc, ppfd);
if ((pixelformat = ChoosePixelFormat(hdc, ppfd)) == 0) {
MessageBox("ChoosePixelFormat failed", "Error", MB_OK);
return FALSE;
}
if (pfd.dwFlags & PFD_NEED_PALETTE) {
MessageBox("Needs palette", "Error", MB_OK);
return FALSE;
}
if (SetPixelFormat(hdc, pixelformat, ppfd) == FALSE) {
MessageBox("SetPixelFormat failed", "Error", MB_OK);
return FALSE;
}
return TRUE;
}
int COGLView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
/// Local Variables ///////////////////////////////////////////////////////////
RECT rect;
///////////////////////////////////////////////////////////////////////////////
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
m_hDC = ::GetDC(m_hWnd);
if (!SetupPixelFormat(m_hDC))
PostQuitMessage (0);
m_hRC = wglCreateContext(m_hDC);
wglMakeCurrent(m_hDC, m_hRC);
GetClientRect(&rect);
initializeGL(rect.right, rect.bottom);
// CREATE THE DISPLAY LIST FOR AN AXIS WITH ARROWS POINTING IN
// THE POSITIVE DIRECTION Red = X, Green = Y, Blue = Z
glNewList(OGL_AXIS_DLIST,GL_COMPILE);
glBegin(GL_LINES);
glColor3f(1.0f, 0.0f, 0.0f); // X AXIS STARTS - COLOR RED
glVertex3f(-0.2f, 0.0f, 0.0f);
glVertex3f( 0.2f, 0.0f, 0.0f);
glVertex3f( 0.2f, 0.0f, 0.0f); // TOP PIECE OF ARROWHEAD
glVertex3f( 0.15f, 0.04f, 0.0f);
glVertex3f( 0.2f, 0.0f, 0.0f); // BOTTOM PIECE OF ARROWHEAD
glVertex3f( 0.15f, -0.04f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f); // Y AXIS STARTS - COLOR GREEN
glVertex3f( 0.0f, 0.2f, 0.0f);
glVertex3f( 0.0f, -0.2f, 0.0f);
glVertex3f( 0.0f, 0.2f, 0.0f); // TOP PIECE OF ARROWHEAD
glVertex3f( 0.04f, 0.15f, 0.0f);
glVertex3f( 0.0f, 0.2f, 0.0f); // BOTTOM PIECE OF ARROWHEAD
glVertex3f( -0.04f, 0.15f, 0.0f);
glColor3f(0.0f, 0.0f, 1.0f); // Z AXIS STARTS - COLOR BLUE
glVertex3f( 0.0f, 0.0f, 0.2f);
glVertex3f( 0.0f, 0.0f, -0.2f);
glVertex3f( 0.0f, 0.0f, 0.2f); // TOP PIECE OF ARROWHEAD
glVertex3f( 0.0f, 0.04f, 0.15f);
glVertex3f( 0.0f, 0.0f, 0.2f); // BOTTOM PIECE OF ARROWHEAD
glVertex3f( 0.0f, -0.04f, 0.15f);
glEnd();
glEndList();
// CREATE THE DISPLAY LIST THE SELECTED BONE JUST A CUBE
glNewList(OGL_SELECTED_DLIST,GL_COMPILE);
glBegin(GL_QUADS);
glColor3f(1.0f, 1.0f, 0.0f); // YELLOW
// BOTTOM
glVertex3f(-0.05f, -0.05f, -0.05f);
glVertex3f( 0.05f, -0.05f, -0.05f);
glVertex3f( 0.05f, -0.05f, 0.05f);
glVertex3f(-0.05f, -0.05f, 0.05f);
// BACK
glVertex3f(-0.05f, 0.05f, -0.05f);
glVertex3f( 0.05f, 0.05f, -0.05f);
glVertex3f( 0.05f, -0.05f, -0.05f);
glVertex3f(-0.05f, -0.05f, -0.05f);
// FRONT
glVertex3f(-0.05f, -0.05f, 0.05f);
glVertex3f( 0.05f, -0.05f, 0.05f);
glVertex3f( 0.05f, 0.05f, 0.05f);
glVertex3f(-0.05f, 0.05f, 0.05f);
// RIGHT
glVertex3f(-0.05f, -0.05f, -0.05f);
glVertex3f(-0.05f, -0.05f, 0.05f);
glVertex3f(-0.05f, 0.05f, 0.05f);
glVertex3f(-0.05f, 0.05f, -0.05f);
// LEFT
glVertex3f( 0.05f, 0.05f, -0.05f);
glVertex3f( 0.05f, 0.05f, 0.05f);
glVertex3f( 0.05f, -0.05f, 0.05f);
glVertex3f( 0.05f, -0.05f, -0.05f);
// TOP
glVertex3f(-0.05f, 0.05f, 0.05f);
glVertex3f( 0.05f, 0.05f, 0.05f);
glVertex3f( 0.05f, 0.05f, -0.05f);
glVertex3f(-0.05f, 0.05f, -0.05f);
glEnd();
glEndList();
drawScene(FALSE);
return 0;
}
/* OpenGL code */
///////////////////////////////////////////////////////////////////////////////
// Function: resize
// Purpose: This code handles the windows resize for OpenGL
// Arguments: Width and heights of the view window
///////////////////////////////////////////////////////////////////////////////
GLvoid COGLView::resize( GLsizei width, GLsizei height )
{
// Local Variables ///////////////////////////////////////////////////////////
GLfloat aspect;
///////////////////////////////////////////////////////////////////////////////
glViewport(0, 0, width, height);
aspect = (GLfloat)width/(GLfloat)height;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(20.0, aspect,1, 2000);
glMatrixMode(GL_MODELVIEW);
m_ScreenWidth = width;
m_ScreenHeight = height;
}
//// resize /////////////////////////////////////////////////////////////////
GLvoid COGLView::initializeGL(GLsizei width, GLsizei height)
{
/// Local Variables ///////////////////////////////////////////////////////////
GLfloat aspect;
GLfloat diffuse[] = { 0.8, 0.8, 0.8, 1.0 };
GLfloat specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat lightpos[] = { 10.5, 10.5, 1.0, 0.0 };
///////////////////////////////////////////////////////////////////////////////
//glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearColor(0.3f, 0.3f, 0.2f, 0.0f);
glClearDepth(1.0);
glDepthFunc(GL_LESS);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
aspect = (GLfloat)width/(GLfloat)height;
// Establish viewing volume
gluPerspective(60.0, aspect,1, 2000);
//gluPerspective(10.0, aspect,1, 2000);
glMatrixMode(GL_MODELVIEW);
// SET SOME OGL INITIAL STATES SO THEY ARE NOT DONE IN THE DRAW LOOP
// glPolygonMode(GL_FRONT,GL_FILL);
glPolygonMode(GL_FRONT,GL_LINE);
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
glHint(GL_LINE_SMOOTH_HINT,GL_FASTEST);
glPointSize(8.0); // NICE BEEFY POINTS FOR THE VERTEX SELECTION
glDisable(GL_TEXTURE_2D);
glMaterialfv(GL_FRONT,GL_DIFFUSE, diffuse);
glMaterialfv(GL_FRONT,GL_SPECULAR, specular);
glMaterialf(GL_FRONT,GL_SHININESS, 25.0f);
glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
}
///////////////////////////////////////////////////////////////////////////////
// At run-time, at each frame of animation, you need to get the
// current matrices for every bone. This is multiplied by the
// inverted matrix from the rest bone and stored. Must be
// recursive.
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Function: GetSkeletonMat
// Purpose: Gets the Matrix values for the character
// Arguments: None
///////////////////////////////////////////////////////////////////////////////
//ofstream file1 = {ofstream("11.txt"),ofstream("12.txt"),ofstream("13.txt"),ofstream("14.txt")};
//ofstream file1 = ofstream("11.txt");
GLvoid COGLView::GetSkeletonMat(t_Bone *rootBone)
{
/// Local Variables ///////////////////////////////////////////////////////////
int loop;
t_Bone *curBone;
tMatrix tempMatrix;
Quat quater;
///////////////////////////////////////////////////////////////////////////////
curBone = rootBone->children;
for (loop = 0; loop < rootBone->childCnt; loop++)
{
glPushMatrix();
if ( IsThisBone(curBone,animboneName0) && Play_Animation)//根节点
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
//glTranslatef(curBone->axisangle.x, curBone->axisangle.y, curBone->axisangle.z);
glRotatef(90.000000, 0.0f, 1.0f, 0.0f);
//glTranslatef(curBone->axisangle.x, 0, 0);
glTranslatef(curBone->axisangle.z, 0,0);
glRotatef(curBone->axisangle.ay, 0.0f, 1.0f, 0.0f);
//glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
//file1 << curBone->axisangle.x<< "\t"<< curBone->axisangle.y << "\t"<< curBone->axisangle.z <<"\n";
}
else if ( IsThisBone(curBone,animboneName1) && Play_Animation)//脊柱1
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
glRotatef(90.00000, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.ay, 1.0f, 0.0f, 0.0f);
//glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
//glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
glRotatef(curBone->axisangle.ax, 1.0f, 0.0f, 0.0f);
glRotatef(curBone->axisangle.ay, 0.0f, 1.0f, 0.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if(IsThisBone(curBone,animboneName2) && Play_Animation)//脊柱2
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(4.204475, 0.0f, 0.0f, 1.0f);
//glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(-curBone->parent->axisangle.ax, 1.0f, 0.0f, 0.0f);
glRotatef(-curBone->parent->axisangle.ay, 0.0f, 1.0f, 0.0f);
glRotatef(-curBone->parent->axisangle.az, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if(IsThisBone(curBone,animboneName3) && Play_Animation)//脊柱3
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(4.609683, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName4)&&Play_Animation)//左上臂
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(1.125000, 0.0f, 1.0f, 0.0f);
glRotatef(15.600511, 0.0f, 0.0f, 1.0f);
// glRotatef(-curBone->parent->parent->parent->parent->parent->parent->axisangle.theta*180/M_PI,curBone->parent->parent->parent->parent->parent->parent->axisangle.ax,curBone->parent->parent->parent->parent->parent->parent->axisangle.ay,curBone->parent->parent->parent->parent->parent->parent->axisangle.az);
glRotatef(-curBone->parent->parent->axisangle.theta*180/M_PI,curBone->parent->parent->axisangle.az,-curBone->parent->parent->axisangle.ay,curBone->parent->parent->axisangle.ax);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName5)&&Play_Animation)//左前臂
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(15.600505, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName6)&&Play_Animation)//左手
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(-0.172924, 1.0f, 0.0f, 0.0f);
//glRotatef(1.111632, 0.0f, 1.0f, 0.0f);
//glRotatef(-3.242059, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName7)&&Play_Animation)//右上臂
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
// glRotatef(-curBone->parent->parent->parent->parent->parent->parent->axisangle.theta*180/M_PI,curBone->parent->parent->parent->parent->parent->parent->axisangle.ax,curBone->parent->parent->parent->parent->parent->parent->axisangle.ay,curBone->parent->parent->parent->parent->parent->parent->axisangle.az);
//glRotatef(-1.118078, 0.0f, 1.0f, 0.0f);
glRotatef(15.600505, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->parent->axisangle.theta*180/M_PI,-curBone->parent->parent->axisangle.az,-curBone->parent->parent->axisangle.ay,-curBone->parent->parent->axisangle.ax);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName8)&&Play_Animation)//右前臂
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(-0.013521, 0.0f, 1.0f, 0.0f);
//glRotatef(-8.840881, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName9)&&Play_Animation)//右手
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(0.171861, 1.0f, 0.0f, 0.0f);
//glRotatef(-1.118314, 0.0f, 1.0f, 0.0f);
//glRotatef(-3.242074, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName10)&&Play_Animation)//头
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
glRotatef(-curBone->parent->parent->axisangle.theta*180/M_PI,curBone->parent->parent->axisangle.ax,curBone->parent->parent->axisangle.ay,curBone->parent->parent-> axisangle.az);
// glRotatef(2.252969, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if ( IsThisBone(curBone,animboneName11) && Play_Animation)//左大腿
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(-6.1, 0.0f, 1.0f, 0.0f);
glRotatef(-92.890663, 0.0f, 0.0f, 1.0f);
//glRotatef(curBone->axisangle.ax, 1.0f, 0.0f, 0.0f);
glRotatef(curBone->axisangle.ay, 0.0f, 1.0f, 0.0f);
//glRotatef(curBone->parent->axisangle.ay, 1.0f, 0.0f, 0.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if( IsThisBone(curBone,animboneName12) && Play_Animation)//左小腿
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(6.012136, 0.0f, 0.0f, 1.0f);
// glRotatef(curBone->axisangle.ax, 1.0f, 0.0f, 0.0f);
//glRotatef(curBone->axisangle.aY, 0.0f, 1.0f, 0.0f);
glRotatef(-curBone->parent->axisangle.az, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if( IsThisBone(curBone,animboneName13) && Play_Animation)//左脚
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(-61.009781, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.az, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if ( IsThisBone(curBone,animboneName14) && Play_Animation)//右大腿
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(6.1, 0.0f, 1.0f, 0.0f);
glRotatef(-92.890663, 0.0f, 0.0f, 1.0f);
//glRotatef(curBone->axisangle.ax, 1.0f, 0.0f, 0.0f);
glRotatef(curBone->axisangle.ay, 0.0f, 1.0f, 0.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if( IsThisBone(curBone,animboneName15) && Play_Animation)//右小腿
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(6.012136, 0.0f, 0.0f, 1.0f);
//glRotatef(curBone->axisangle.ax, 1.0f, 0.0f, 0.0f);
//glRotatef(curBone->axisangle.aY, 0.0f, 1.0f, 0.0f);
glRotatef(-curBone->parent->axisangle.az, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if( IsThisBone(curBone,animboneName16) && Play_Animation)//右脚
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(-61.009781, 0.0f, 0.0f, 1.0f);
//glRotatef(curBone->axisangle.aY, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.az, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else
{
// Set observer's orientation and position
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(curBone->rot.z, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->rot.y, 0.0f, 1.0f, 0.0f);
glRotatef(curBone->rot.x, 1.0f, 0.0f, 0.0f);
}
// Get the current matrix
glGetFloatv(GL_MODELVIEW_MATRIX,tempMatrix.m);
// Multiply it by the inverted root bone and store
MultMatrix(curBone->curMatrix,&tempMatrix,&curBone->matrix);
// CHECK IF THIS BONE HAS CHILDREN, IF SO RECURSIVE CALL
if (curBone->childCnt > 0)
GetSkeletonMat(curBone);
glPopMatrix();
curBone++;
}
}
//// GetSkeletonMat ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// When the base skeleton is set, the matrix for each bones must
// be grabbed, inverted, then stored for run time use. As the
// skeleton is a hierarchy, this must be done recursively
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Function: GetBaseSkeletonMat
// Purpose: Gets the Matrix values for the character
// Arguments: None
///////////////////////////////////////////////////////////////////////////////
GLvoid COGLView::GetBaseSkeletonMat(t_Bone *rootBone)
{
/// Local Variables ///////////////////////////////////////////////////////////
int loop;
t_Bone *curBone;
tMatrix tempMatrix;
Quat quater;
///////////////////////////////////////////////////////////////////////////////
curBone = rootBone->children;
for (loop = 0; loop < rootBone->childCnt; loop++)
{
glPushMatrix();
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
// Set observer's orientation and position
glRotatef(curBone->b_rot.z, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->b_rot.y, 0.0f, 1.0f, 0.0f);
glRotatef(curBone->b_rot.x, 1.0f, 0.0f, 0.0f);
// GRAB THE MATRIX AT THIS POINT SO I CAN USE IT FOR THE DEFORMATION
glGetFloatv(GL_MODELVIEW_MATRIX,tempMatrix.m);
// Invert the matrix and store it for later
InvertMatrix(tempMatrix.m,curBone->matrix.m);
// CHECK IF THIS BONE HAS CHILDREN, IF SO RECURSIVE CALL
if (curBone->childCnt > 0)
GetBaseSkeletonMat(curBone);
glPopMatrix();
curBone++;
}
}
//// GetBaseSkeletonMat ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// This function actually will deform a mesh given a
// skeletal system. At each bone, a combined matrix that
// tranforms the vertex from the rest bone space to the final
// bone space is stored. Each vertex is multiplied by this
// matrix then scaled by the weight. This is accumulated to
// give a fine vertex position
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Function: DeformVertices
// Purpose: Bends the Bodies Based on the Vertices
// Arguments: None
///////////////////////////////////////////////////////////////////////////////
GLvoid COGLView::DeformVertices(t_Bone *rootBone,t_Visual *visual)
{
/// Local Variables ///////////////////////////////////////////////////////////
int loop,loop2;
t_Bone *curBone;
int vertex;
float weight;
tVector post;
float *deformData,*vertexData;
///////////////////////////////////////////////////////////////////////////////
if (rootBone == &m_Skeleton && visual->vertexData != NULL)
{
// ZERO THE DEFORMATION
if (m_Skeleton.childCnt > 0)
{
for (loop = 0; loop < m_Skeleton.childCnt; loop++)
{
memcpy(visual->deformData,visual->vertexData,sizeof(float) * visual->vSize * visual->vertexCnt);
deformData = (float *)(visual->deformData + (visual->vSize - 3));
for (loop2 = 0; loop2 < visual->vertexCnt; loop2++, deformData += visual->vSize)
{
deformData[0] = 0.0f;
deformData[1] = 0.0f;
deformData[2] = 0.0f;
}
}
}
}
curBone = rootBone->children;
for (loop = 0; loop < rootBone->childCnt; loop++)
{
for (loop2 = 0; loop2 < visual->vertexCnt; loop2++)
{
// GET THE WEIGHT
weight = curBone->CV_weight[loop2].weight;
// The weight is between 0-1
if (weight > 0.0f)
{
vertex = curBone->CV_weight[loop2].vertex;
deformData = (float *)(visual->deformData + (visual->vSize * (vertex + 1)) - 3);
vertexData = (float *)(visual->vertexData + (visual->vSize * (vertex + 1)) - 3);
// Multiply the vertex by the combined matrix
MultVectorByMatrix(curBone->curMatrix, (tVector *)vertexData, &post);
// Since the Matrix above is a combination of the rest and current matrices, it does
// the same as the following two calls would
// MultVectorByMatrix(&curBone->matrix, (tVector *)&vertexData[vertex].x, &pre);
// MultVectorByMatrix(curBone->curMatrix, &pre, &post);
// Accumulate the result
deformData[0] += (post.x * weight);
deformData[1] += (post.y * weight);
deformData[2] += (post.z * weight);
}
}
// CHECK IF THIS BONE HAS CHILDREN, IF SO RECURSIVE CALL
if (curBone->childCnt > 0)
DeformVertices(curBone, visual);
curBone++;
}
}
///////////////////////////////////////////////////////////////////////////////
// Function: drawModel
// Purpose: Draw the Mesh model either deformed or not
// Arguments: Pointer to the model
///////////////////////////////////////////////////////////////////////////////
GLvoid COGLView::drawModel(t_Visual *model)
{
/// Local Variables ///////////////////////////////////////////////////////////
tColoredVertex *cdata;
float *data;
int loop;
///////////////////////////////////////////////////////////////////////////////
if (model->vertexData != NULL)
{
glColor3f(1.0f, 1.0f, 1.0f); // NO MODULATION
if (m_DrawDeformed)
data = (float *)model->deformData;
else
data = (float *)model->vertexData;
// Declare the Array of Data
glInterleavedArrays(model->dataFormat,0,(GLvoid *)data);
if (model->vPerFace == 3) // Model is Triangles
glDrawArrays(GL_TRIANGLES,0,model->faceCnt * 3);
else
glDrawArrays(GL_QUADS,0,model->faceCnt * 4);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
// NOW DRAW THE VERTEX MARKERS IF THEY ARE SELECTED
glColor3f(1.0f, 0.0f, 0.0f); // Selected Vertices are Red
glBegin(GL_POINTS);
for (loop = 0; loop < model->vertexCnt; loop++)
{
// IF A POINT IS SELECTED DRAW IT
if (model->CV_select[loop])
{
glVertex3fv((float *)&data[((loop + 1) * model->vSize) - 3]);
}
}
glEnd();
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
}
}
//int COGLView::statThreeandFour(t_Visual *model,t_faceIndex *face,int *cur_index)
//{
// int flag = face[0].ver_count;int k=0;int pre_i=0;int cur_pos = 0;cur_index[0] = 0;
// for (int i = 0;i< model->faceCnt;i++)
// {
//
// if(face[i].ver_count != flag)
// {
// k++;
// cur_index[k] = cur_pos;
// flag = face[i].ver_count;
// }
// cur_pos += face[i].ver_count;
// }
// return k;
//}
GLvoid COGLView::drawModelTest(t_Visual *model)
{
/// Local Variables ///////////////////////////////////////////////////////////
tColoredVertex *cdata;
float *data;
int loop;
///////////////////////////////////////////////////////////////////////////////
if (model->vertexData != NULL)
{
glColor3f(1.0f, 1.0f, 1.0f); // NO MODULATION
if (m_DrawDeformed)
data = (float *)model->deformData;
else
data = (float *)model->vertexData;
// Declare the Array of Data
glInterleavedArrays(model->dataFormat,0,(GLvoid *)data);
for (int i = 0;i< counter;i++)
{
if( (i % 2) == 0)
{
glDrawArrays(GL_QUADS,cur_index[i],cur_index[i+1]-cur_index[i]);
}
else
{
glDrawArrays(GL_TRIANGLES,cur_index[i],cur_index[i+1]-cur_index[i]);
}
}
glDrawArrays(GL_QUADS,cur_index[counter],model->vertexCnt-cur_index[counter]);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
// NOW DRAW THE VERTEX MARKERS IF THEY ARE SELECTED
glColor3f(1.0f, 0.0f, 0.0f); // Selected Vertices are Red
glBegin(GL_POINTS);
for (loop = 0; loop < model->vertexCnt; loop++)
{
// IF A POINT IS SELECTED DRAW IT
if (model->CV_select[loop])
{
glVertex3fv((float *)&data[((loop + 1) * model->vSize) - 3]);
}
}
glEnd();
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
}
}
///////////////////////////////////////////////////////////////////////////////
// Function: drawSkeleton
// Purpose: Actually draws the Skeleton it is recursive
// Arguments: Pointer to the bone
///////////////////////////////////////////////////////////////////////////////
GLvoid COGLView::drawSkeleton(t_Bone *rootBone)
{
/// Local Variables ///////////////////////////////////////////////////////////
int loop;
t_Bone *curBone;
Quat quater;
///////////////////////////////////////////////////////////////////////////////
curBone = rootBone->children;
for (loop = 0; loop < rootBone->childCnt; loop++)
{
glPushMatrix();
if ( IsThisBone(curBone,animboneName0) && Play_Animation)//根节点
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
//glTranslatef(curBone->axisangle.x, curBone->axisangle.y, curBone->axisangle.z);
glRotatef(90.000000, 0.0f, 1.0f, 0.0f);
glTranslatef(curBone->axisangle.z, 0, 0 );
glRotatef(curBone->axisangle.ay, 0.0f, 1.0f, 0.0f);
//glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
//file1 << curBone->axisangle.x<< "\t"<< curBone->axisangle.y << "\t"<< curBone->axisangle.z <<"\n";
}
else if ( IsThisBone(curBone,animboneName1) && Play_Animation)//脊柱1
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
glRotatef(90.00000, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.ay, 1.0f, 0.0f, 0.0f);
//glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
//glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
glRotatef(curBone->axisangle.ax, 1.0f, 0.0f, 0.0f);
glRotatef(curBone->axisangle.ay, 0.0f, 1.0f, 0.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if(IsThisBone(curBone,animboneName2) && Play_Animation)//脊柱2
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(4.204475, 0.0f, 0.0f, 1.0f);
//glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(-curBone->parent->axisangle.ax, 1.0f, 0.0f, 0.0f);
glRotatef(-curBone->parent->axisangle.ay, 0.0f, 1.0f, 0.0f);
glRotatef(-curBone->parent->axisangle.az, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if(IsThisBone(curBone,animboneName3) && Play_Animation)//脊柱3
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(4.609683, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName4)&&Play_Animation)//左上臂
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(1.125000, 0.0f, 1.0f, 0.0f);
glRotatef(15.600511, 0.0f, 0.0f, 1.0f);
// glRotatef(-curBone->parent->parent->parent->parent->parent->parent->axisangle.theta*180/M_PI,curBone->parent->parent->parent->parent->parent->parent->axisangle.ax,curBone->parent->parent->parent->parent->parent->parent->axisangle.ay,curBone->parent->parent->parent->parent->parent->parent->axisangle.az);
glRotatef(-curBone->parent->parent->axisangle.theta*180/M_PI,curBone->parent->parent->axisangle.az,-curBone->parent->parent->axisangle.ay,curBone->parent->parent->axisangle.ax);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName5)&&Play_Animation)//左前臂
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(15.600505, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName6)&&Play_Animation)//左手
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(-0.172924, 1.0f, 0.0f, 0.0f);
//glRotatef(1.111632, 0.0f, 1.0f, 0.0f);
//glRotatef(-3.242059, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName7)&&Play_Animation)//右上臂
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
// glRotatef(-curBone->parent->parent->parent->parent->parent->parent->axisangle.theta*180/M_PI,curBone->parent->parent->parent->parent->parent->parent->axisangle.ax,curBone->parent->parent->parent->parent->parent->parent->axisangle.ay,curBone->parent->parent->parent->parent->parent->parent->axisangle.az);
//glRotatef(-1.118078, 0.0f, 1.0f, 0.0f);
glRotatef(15.600505, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->parent->axisangle.theta*180/M_PI,-curBone->parent->parent->axisangle.az,-curBone->parent->parent->axisangle.ay,-curBone->parent->parent->axisangle.ax);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName8)&&Play_Animation)//右前臂
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(-0.013521, 0.0f, 1.0f, 0.0f);
//glRotatef(-8.840881, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName9)&&Play_Animation)//右手
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
//glRotatef(0.171861, 1.0f, 0.0f, 0.0f);
//glRotatef(-1.118314, 0.0f, 1.0f, 0.0f);
//glRotatef(-3.242074, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.theta*180/M_PI,curBone->parent->axisangle.ax,curBone->parent->axisangle.ay,curBone->parent->axisangle.az);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if (IsThisBone(curBone,animboneName10)&&Play_Animation)//头
{
glTranslatef(curBone->trans.x, curBone->trans.y, curBone->trans.z);
glRotatef(-curBone->parent->parent->axisangle.theta*180/M_PI,curBone->parent->parent->axisangle.ax,curBone->parent->parent->axisangle.ay,curBone->parent->parent->axisangle.az);
// glRotatef(2.252969, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.theta*180/M_PI,curBone->axisangle.ax,curBone->axisangle.ay,curBone->axisangle.az);
}
else if ( IsThisBone(curBone,animboneName11) && Play_Animation)//左大腿
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(-6.1, 0.0f, 1.0f, 0.0f);
glRotatef(-92.890663, 0.0f, 0.0f, 1.0f);
//glRotatef(curBone->axisangle.ax, 1.0f, 0.0f, 0.0f);
glRotatef(curBone->axisangle.ay, 0.0f, 1.0f, 0.0f);
//glRotatef(curBone->parent->axisangle.ay, 1.0f, 0.0f, 0.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if( IsThisBone(curBone,animboneName12) && Play_Animation)//左小腿
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(6.012136, 0.0f, 0.0f, 1.0f);
// glRotatef(curBone->axisangle.ax, 1.0f, 0.0f, 0.0f);
//glRotatef(curBone->axisangle.aY, 0.0f, 1.0f, 0.0f);
glRotatef(-curBone->parent->axisangle.az, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if( IsThisBone(curBone,animboneName13) && Play_Animation)//左脚
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(-61.009781, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.az, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if ( IsThisBone(curBone,animboneName14) && Play_Animation)//右大腿
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(6.1, 0.0f, 1.0f, 0.0f);
glRotatef(-92.890663, 0.0f, 0.0f, 1.0f);
//glRotatef(curBone->axisangle.ax, 1.0f, 0.0f, 0.0f);
glRotatef(curBone->axisangle.ay, 0.0f, 1.0f, 0.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if( IsThisBone(curBone,animboneName15) && Play_Animation)//右小腿
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(6.012136, 0.0f, 0.0f, 1.0f);
//glRotatef(curBone->axisangle.ax, 1.0f, 0.0f, 0.0f);
//glRotatef(curBone->axisangle.aY, 0.0f, 1.0f, 0.0f);
glRotatef(-curBone->parent->axisangle.az, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else if( IsThisBone(curBone,animboneName16) && Play_Animation)//右脚
{
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(-61.009781, 0.0f, 0.0f, 1.0f);
//glRotatef(curBone->axisangle.aY, 0.0f, 0.0f, 1.0f);
glRotatef(-curBone->parent->axisangle.az, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->axisangle.az, 0.0f, 0.0f, 1.0f);
}
else
{
// Set observer's orientation and position
glTranslatef(curBone->b_trans.x, curBone->b_trans.y, curBone->b_trans.z);
glRotatef(curBone->rot.z, 0.0f, 0.0f, 1.0f);
glRotatef(curBone->rot.y, 0.0f, 1.0f, 0.0f);
glRotatef(curBone->rot.x, 1.0f, 0.0f, 0.0f);
}
// GRAB THE MATRIX AT THIS POINT SO I CAN USE IT FOR THE DEFORMATION
// glGetFloatv(GL_MODELVIEW_MATRIX,curBone->matrix.m);
// THE SCALE IS LOCAL SO I PUSH AND POP
glPushMatrix();
glScalef(curBone->bsphere, curBone->bsphere, curBone->bsphere);
if (m_DrawSkeleton)
{
// DRAW THE AXIS OGL OBJECT
glCallList(OGL_AXIS_DLIST);
// IF SOMETHING IS SELECTED, DRAW TAG BOX
if (m_Skeleton.id == (long)curBone)
{
glDisable(GL_CULL_FACE);
m_SelectedBone = curBone;
glCallList(OGL_SELECTED_DLIST);
glEnable(GL_CULL_FACE);
}
}
glPopMatrix();
// CHECK IF THIS BONE HAS CHILDREN, IF SO RECURSIVE CALL
if (curBone->childCnt > 0)
drawSkeleton(curBone);
glPopMatrix();
curBone++;
}
}
//// drawSkeleton /////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Function: drawScene
// Purpose: Actually draw the OpenGL Scene
// Arguments: None
///////////////////////////////////////////////////////////////////////////////
GLvoid COGLView::drawScene(BOOL drawSelectRect)
{
/// Local Variables ///////////////////////////////////////////////////////////
Quat quater;
///////////////////////////////////////////////////////////////////////////////
if (m_Camera.rot.y > 360.0f) m_Camera.rot.y -= 360.0f;
if (m_Camera.rot.x > 360.0f) m_Camera.rot.x -= 360.0f;
if (m_Camera.rot.z > 360.0f) m_Camera.rot.z -= 360.0f;
glDisable(GL_DEPTH_TEST); // TURN OFF DEPTH TEST FOR CLEAR
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity(); // 重置当前的模型观察矩阵
glEnable(GL_DEPTH_TEST); // ENABLE DEPTH TESTING
//////////////绘制地板////////////////////////
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(m_Camera.b_trans.x, m_Camera.b_trans.y, m_Camera.b_trans.z);
RenderStockScene();
glEnable(GL_LIGHTING);
glPopMatrix();
/////////////绘制模型////////////////////////
glPushMatrix();
// Set root skeleton's orientation and position
glTranslatef(m_Camera.trans.x, m_Camera.trans.y, m_Camera.trans.z);
glRotatef(m_Camera.rot.x, 1.0f, 0.0f, 0.0f);
glRotatef(m_Camera.rot.y, 0.0f, 1.0f, 0.0f);
glRotatef(m_Camera.rot.z, 0.0f, 0.0f, 1.0f);
// GRAB THE MATRIX AT THIS POINT SO I CAN USE IT FOR THE DEFORMATION
glGetFloatv(GL_MODELVIEW_MATRIX,m_Skeleton.matrix.m);
glDisable(GL_LIGHTING);
drawSkeleton(&m_Skeleton);
glEnable(GL_LIGHTING);
if (m_Skeleton.childCnt > 0)
{
DeformVertices(&m_Skeleton,&m_Model);
}
//drawModel(&m_Model);
drawModelTest(&m_Model);
m_PickX = -1;
m_PickY = -1;
glPopMatrix();
GetSkeletonMat(&m_Skeleton); // GET THE SKELETON INFO
// IF I AM DRAGGING A SELECTION BOX, DRAW IT
if (drawSelectRect)
{
glMatrixMode(GL_PROJECTION); // I WANT TO PLAY WITH THE PROJECTION
glPushMatrix(); // SAVE THE OLD ONE
glLoadIdentity(); // LOAD A NEW ONE
gluOrtho2D(0,m_ScreenWidth,0,m_ScreenHeight); // USE WINDOW SETTINGS
glColor3f(1.0f, 1.0f, 1.0f); // DRAW A WHITE BOX
glBegin(GL_LINE_STRIP);
glVertex2s((short)m_SelectRect.left,(short)m_SelectRect.top);
glVertex2s((short)m_SelectRect.right,(short)m_SelectRect.top);
glVertex2s((short)m_SelectRect.right,(short)m_SelectRect.bottom);
glVertex2s((short)m_SelectRect.left,(short)m_SelectRect.bottom);
glVertex2s((short)m_SelectRect.left,(short)m_SelectRect.top);
glEnd();
glPopMatrix(); // RESTORE THE OLD PROJECTION
glMatrixMode(GL_MODELVIEW); // BACK TO MODEL MODE
}
// glFinish();
SwapBuffers(m_hDC);
UpdateStatusBarFrameInfo();
}
//// drawScene //////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Function: SelectVertices
// Purpose: Use Feedback to get all the vertices in the view
// Arguments: Should I select or de-select?
///////////////////////////////////////////////////////////////////////////////
void COGLView::SelectVertices(BOOL select)
{
/// Local Variables ///////////////////////////////////////////////////////////
GLfloat *feedBuffer;
GLint hitCount;
int loop2;
float *data;
Quat quater;
///////////////////////////////////////////////////////////////////////////////
if (m_Model.vertexData != NULL)
{
// INITIALIZE A PLACE TO PUT ALL THE FEEDBACK INFO (3 DATA, 1 TAG, 2 TOKENS)
feedBuffer = (GLfloat *)malloc(sizeof(GLfloat) * m_Model.vertexCnt * 6);
// TELL OPENGL ABOUT THE BUFFER
glFeedbackBuffer(m_Model.vertexCnt * 6,GL_3D,feedBuffer);
(void)glRenderMode(GL_FEEDBACK); // SET IT IN FEEDBACK MODE
glPushMatrix();
// Set root skeleton's orientation and position
glTranslatef(m_Camera.trans.x, m_Camera.trans.y, m_Camera.trans.z);
glRotatef(m_Camera.rot.x, 1.0f, 0.0f, 0.0f);
glRotatef(m_Camera.rot.y, 0.0f, 1.0f, 0.0f);
glRotatef(m_Camera.rot.z, 0.0f, 0.0f, 1.0f);
//if (!Play_Animation)
//{
// quater = EulerToQuat(m_Camera.rot.x,m_Camera.rot.y,m_Camera.rot.z);
// m_Camera.axisangle = QuaternionToAxisAngle(quater);
//}
//glRotatef(m_Camera.axisangle.theta*180/M_PI,m_Camera.axisangle.az,m_Camera.axisangle.ay,m_Camera.axisangle.ax);
for (loop2 = 0; loop2 < m_Model.vertexCnt; loop2++)
{
if (m_DrawDeformed)
data = (float *)m_Model.deformData;
else
data = (float *)m_Model.vertexData;
// PASS THROUGH A MARKET LETTING ME KNOW WHAT VERTEX IT WAS
glPassThrough((float)loop2);
// SEND THE VERTEX
glBegin(GL_POINTS);
glVertex3fv((float *)&data[(m_Model.vSize * (loop2 + 1)) - 3]);
glEnd();
}
glPopMatrix();
hitCount = glRenderMode(GL_RENDER); // HOW MANY HITS DID I GET
CompareBuffer(hitCount,feedBuffer, select); // CHECK THEM AGAINST MY SELECTION
free(feedBuffer); // GET RID OF THE MEMORY
}
}
////// SelectVertices /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Function: CompareBuffer
// Purpose: Check the feedback buffer to see if anything is tagged
// Arguments: Number of hits, pointer to buffer, Should I select or de-select
///////////////////////////////////////////////////////////////////////////////
void COGLView::CompareBuffer(GLint size, GLfloat *buffer,BOOL select)
{
/// Local Variables ///////////////////////////////////////////////////////////
GLint count;
GLfloat token,point[3];
int loop,currentVertex;
int *data;
///////////////////////////////////////////////////////////////////////////////
count = size;
while (count)
{
token = buffer[size - count]; // CHECK THE TOKEN
count--;
if (token == GL_PASS_THROUGH_TOKEN) // VERTEX MARKER
{
currentVertex = (int)buffer[size - count]; // WHAT VERTEX
count--;
}
else if (token == GL_POINT_TOKEN)
{
// THERE ARE THREE ELEMENTS TO A POINT TOKEN
for (loop = 0; loop < 3; loop++)
{
point[loop] = buffer[size - count];
count--;
}
data = (BOOL *)m_Model.CV_select;
// CHECK IF THE POINT WAS IN MY SELECTION RECTANGLE
// FLOATS 0 AND 1 ARE SCREEN X AND Y
// NOTE: OPENGL SETS THE BOTTOM Y=0
if (point[0] >= m_SelectRect.left &&
point[0] <= m_SelectRect.right &&
point[1] <= m_SelectRect.top &&
point[1] >= m_SelectRect.bottom)
// SET THIS VERTEX TO THE CURRENT SELECTION VALUE
data[currentVertex] = select;
}
}
}
////// CompareBuffer //////////////////////////////////////////////////////////
void COGLView::OnDestroy()
{
CWnd::OnDestroy();
if (m_hRC)
wglDeleteContext(m_hRC);
if (m_hDC)
::ReleaseDC(m_hWnd,m_hDC);
m_hRC = 0;
m_hDC = 0;
}
void COGLView::OnPaint()
{
CPaintDC dc(this); // device context for painting
drawScene(FALSE);
// Do not call CWnd::OnPaint() for painting messages
}
void COGLView::OnLButtonDown(UINT nFlags, CPoint point)
{
// STORE OFF THE KIT POINT AND SETTINGS FOR THE MOVEMENT LATER
m_mousepos = point;
m_Grab_Rot_X = m_SelectedBone->rot.x;
m_Grab_Rot_Y = m_SelectedBone->rot.y;
m_Grab_Rot_Z = m_SelectedBone->rot.z;
m_Grab_Trans_X = m_SelectedBone->trans.x;
m_Grab_Trans_Y = m_SelectedBone->trans.y;
m_Grab_Trans_Z = m_SelectedBone->trans.z;
m_SelectRect.left = point.x;
m_SelectRect.top = m_ScreenHeight - point.y;
if ((nFlags & MK_CONTROL) == 0 && (nFlags & MK_SHIFT) == 0)
{
m_SelectRect.left = point.x;
m_SelectRect.top = m_ScreenHeight - point.y;
SetCapture( );
}
CWnd::OnLButtonDown(nFlags, point);
}
void COGLView::OnRButtonDown(UINT nFlags, CPoint point)
{
// STORE OFF THE KIT POINT AND SETTINGS FOR THE MOVEMENT LATER
m_mousepos = point;
m_Grab_Rot_X = m_Camera.rot.x;
m_Grab_Rot_Y = m_Camera.rot.y;
m_Grab_Rot_Z = m_Camera.rot.z;
m_Grab_Trans_X = m_Camera.trans.x;
m_Grab_Trans_Y = m_Camera.trans.y;
m_Grab_Trans_Z = m_Camera.trans.z;
m_SelectRect.left = point.x;
m_SelectRect.top = m_ScreenHeight - point.y;
CWnd::OnRButtonDown(nFlags, point);
}
void COGLView::OnLButtonUp(UINT nFlags, CPoint point)
{
if ((nFlags & MK_CONTROL) == 0 && (nFlags & MK_SHIFT) == 0)
{
m_SelectRect.right = point.x;
m_SelectRect.bottom = m_ScreenHeight - point.y;
SelectVertices(TRUE);
drawScene(FALSE);
}
ReleaseCapture( );
CWnd::OnLButtonUp(nFlags, point);
}
///////////////////////////////////////////////////////////////////////////////
// Function: OnMouseMove
// Purpose: Handler for the mouse. Handles movement when pressed
// Arguments: Flags for key masks and point
///////////////////////////////////////////////////////////////////////////////
void COGLView::OnMouseMove(UINT nFlags, CPoint point)
{
UpdateStatusBar(0);
if (nFlags & MK_LBUTTON > 0)
{
// IF I AM HOLDING THE 'CTRL' BUTTON ROTATE IN Z
if ((nFlags & MK_CONTROL) > 0)
{
UpdateStatusBar(1);
if ((point.x - m_mousepos.x) != 0)
{
m_SelectedBone->rot.z = m_Grab_Rot_Z + ((float)ROTATE_SPEED * (point.x - m_mousepos.x));
drawScene(FALSE);
}
}
// ELSE "SHIFT" ROTATE THE BONE IN XY
else if ((nFlags & MK_SHIFT) > 0)
{
UpdateStatusBar(1);
if ((point.x - m_mousepos.x) != 0)
{
m_SelectedBone->rot.y = m_Grab_Rot_Y + ((float)ROTATE_SPEED * (point.x - m_mousepos.x));
drawScene(FALSE);
}
if ((point.y - m_mousepos.y) != 0)
{
m_SelectedBone->rot.x = m_Grab_Rot_X + ((float)ROTATE_SPEED * (point.y - m_mousepos.y));
drawScene(FALSE);
}
}
// ELSE MY SELECTION BOX
else
{
m_SelectRect.right = point.x;
m_SelectRect.bottom = m_ScreenHeight - point.y;
drawScene(TRUE);
}
}
else if ((nFlags & MK_RBUTTON) == MK_RBUTTON) // Handle the Camera
{
if ((nFlags & MK_CONTROL) > 0) // Move Camera in Z
{
UpdateStatusBar(2);
if ((point.x - m_mousepos.x) != 0)
{
m_Camera.trans.z = m_Grab_Trans_Z + (.1f * (point.x - m_mousepos.x));
drawScene(FALSE);
}
}
else if ((nFlags & MK_SHIFT) > 0)
{
UpdateStatusBar(2);
if ((point.x - m_mousepos.x) != 0) // Move Camera in X
{
m_Camera.trans.x = m_Grab_Trans_X + (.1f * (point.x - m_mousepos.x));
drawScene(FALSE);
}
if ((point.y - m_mousepos.y) != 0) // Move Camera in Y
{
m_Camera.trans.y = m_Grab_Trans_Y - (.1f * (point.y - m_mousepos.y));
drawScene(FALSE);
}
}
else
{
UpdateStatusBar(1);
if ((point.x - m_mousepos.x) != 0) // Rotate Camera in Y
{
m_Camera.rot.y = m_Grab_Rot_Y + ((float)ROTATE_SPEED * (point.x - m_mousepos.x));
drawScene(FALSE);
}
if ((point.y - m_mousepos.y) != 0) // Rotate Camera in X
{
m_Camera.rot.x = m_Grab_Rot_X + ((float)ROTATE_SPEED * (point.y - m_mousepos.y));
drawScene(FALSE);
}
}
}
CWnd::OnMouseMove(nFlags, point);
}
//// OnMouseMove //////////////////////////////////////////////////////
void COGLView::OnMove(int x, int y)
{
CWnd::OnMove(x, y);
resize( x,y );
}
// 0 = READY
// 1 = ROTATE
// 2 = TRANSLATE
void COGLView::UpdateStatusBar(int mode)
{
/// Local Variables ///////////////////////////////////////////////////////////
char message[80];
///////////////////////////////////////////////////////////////////////////////
if (mode == 1)
{
strcpy(message,"Rotate");
}
else if (mode == 2)
{
strcpy(message,"Translate");
}
else
{
strcpy(message,"Ready");
}
m_StatusBar->SetPaneText(0,message);
}
void COGLView::UpdateStatusBarFrameInfo()
{
/// Local Variables ///////////////////////////////////////////////////////////
char message[80];
char temp_message[80];
///////////////////////////////////////////////////////////////////////////////
if (m_StatusBar != NULL && m_Skeleton.children != NULL)
{
if (m_SelectedBone != NULL)
{
sprintf(message,"CurBone (%2.2f,%2.2f,%2.2f)",
m_SelectedBone->rot.x,m_SelectedBone->rot.y,m_SelectedBone->rot.z);
sprintf(temp_message,"CurBone ( %2.2f , %2.2f , %2.2f )\r\n",
m_SelectedBone->rot.x,m_SelectedBone->rot.y,m_SelectedBone->rot.z);
fwrite(temp_message,sizeof(char),35,freadout2);
}
else
sprintf(message,"No CurBone");
//m_StatusBar->SetPaneStyle(1,SBPS_POPOUT);
m_StatusBar->SetPaneText(1,message);
}
}
void COGLView::HandleKeyDown(UINT nChar)
{
}
void COGLView::HandleKeyUp(UINT nChar)
{
/// Local Variables ///////////////////////////////////////////////////////////
int loop2;
///////////////////////////////////////////////////////////////////////////////
switch (nChar)
{
case VK_SPACE:
if (m_Model.vertexData != NULL)
{
for (loop2 = 0; loop2 < m_Model.vertexCnt; loop2++)
m_Model.CV_select[loop2] = FALSE;
}
m_Skeleton.id = (long)&m_Skeleton;
break;
case 'W':
WeightBones();
break;
case 'B':
break;
case 'R':
m_SelectedBone->rot.x = m_SelectedBone->b_rot.x;
m_SelectedBone->rot.y = m_SelectedBone->b_rot.y;
m_SelectedBone->rot.z = m_SelectedBone->b_rot.z;
break;
case 'D':
m_DrawDeformed = !m_DrawDeformed;
break;
case 'F':
break;
}
Invalidate(TRUE);
}
///////////////////////////////////////////////////////////////////////////////
// Function: OnViewResetskeleton
// Purpose: Reset the view settings for the skeleton
// Arguments: None
///////////////////////////////////////////////////////////////////////////////
void COGLView::OnViewResetskeleton()
{
ResetSkeleton(&m_Skeleton);
drawScene(FALSE);
Invalidate(TRUE);
}
//// OnViewResetskeleton //////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Function: GetGLInfo
// Purpose: Get the OpenGL Vendor and Renderer
///////////////////////////////////////////////////////////////////////////////
void COGLView::GetGLInfo()
{
//// Local Variables ////////////////////////////////////////////////////////////////
char *who, *which, *ver, *ext, *message;
int len;
/////////////////////////////////////////////////////////////////////////////////////
who = (char *)::glGetString( GL_VENDOR );
which = (char *)::glGetString( GL_RENDERER );
ver = (char *)::glGetString( GL_VERSION );
ext = (char *)::glGetString( GL_EXTENSIONS );
len = 200 + strlen(who) + strlen(which) + strlen(ver) + strlen(ext);
message = (char *)malloc(len);
sprintf(message,"Who:\t%s\nWhich:\t%s\nVersion:\t%s\nExtensions:\t%s",
who, which, ver, ext);
::MessageBox(NULL,message,"GL Info",MB_OK);
free(message);
}
//// GetGLInfo /////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Function: SetSkeletonList
// Purpose: Sets up the Weights in the Skeleton for all vertices. Recursive
// Arguments: Bone pointer
///////////////////////////////////////////////////////////////////////////////
void COGLView::SetSkeletonList(t_Bone *skeleton)
{
/// Local Variables ///////////////////////////////////////////////////////////
int loop,loop2;
long vptr;
t_Bone *child;
///////////////////////////////////////////////////////////////////////////////
if (skeleton->childCnt > 0 && m_Model.vertexData != NULL)
{
child = skeleton->children;
for (loop = 0; loop < skeleton->childCnt; loop++,child++)
{
if (child->CV_weight)
free(child->CV_weight);
child->CV_weight = (t_VWeight *)malloc(sizeof(t_VWeight) * m_Model.vertexCnt);
vptr = 0;
for (loop2 = 0; loop2 < m_Model.vertexCnt; loop2++,vptr++)
{
child->CV_weight[vptr].vertex = loop2;
child->CV_weight[vptr].weight = 0.0f;
child->CV_weight[vptr].flag = FALSE;
}
if (child->childCnt > 0)
SetSkeletonList(child);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Function: SetBasePose
// Purpose: Lock the current pose as the base for deformation
///////////////////////////////////////////////////////////////////////////////
void COGLView::SetBasePose()
{
FreezeSkeleton(&m_Skeleton);
GetBaseSkeletonMat(&m_Skeleton);
}
///////////////////////////////////////////////////////////////////////////////
// Function: WeightBones
// Purpose: Set the weighting for a selected bone
// Arguments: None
///////////////////////////////////////////////////////////////////////////////
GLvoid COGLView::WeightBones()
{
/// Local Variables ///////////////////////////////////////////////////////////
int loop3;
long vptr;
///////////////////////////////////////////////////////////////////////////////
if (m_Model.vertexData != NULL)
{
vptr = 0;
for (loop3 = 0; loop3 < m_Model.vertexCnt; loop3++,vptr++)
{
// IF A POINT IS SELECTED SET THE WEIGHT
if (m_Model.CV_select[loop3])
{
m_SelectedBone->CV_weight[loop3].weight = m_SelectedBone->animBlend;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Function: ClearBoneWeights
// Purpose: Go through bones and clear weights for any selected vertex
// Arguments: Bone pointer
///////////////////////////////////////////////////////////////////////////////
void COGLView::ClearBoneWeights(t_Bone *skeleton)
{
/// Local Variables ///////////////////////////////////////////////////////////
int loop;
t_Bone *child;
///////////////////////////////////////////////////////////////////////////////
if (skeleton->childCnt > 0 && m_Model.vertexData != NULL)
{
child = skeleton->children;
for (loop = 0; loop < skeleton->childCnt; loop++,child++)
{
for (int loop3 = 0; loop3 < m_Model.vertexCnt; loop3++)
{
// IF A POINT IS SELECTED SET THE WEIGHT
if (m_Model.CV_select[loop3])
{
child->CV_weight[loop3].weight = 0.0f;
}
}
// Recurse through Hierarchy
if (child->childCnt > 0)
ClearBoneWeights(child);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Function: IterateBoneWeights
// Purpose: Go through bones and either read or write weight values
// Arguments: Bone pointer, read or write BOOL, and file pointer
///////////////////////////////////////////////////////////////////////////////
void COGLView::IterateBoneWeights(t_Bone *skeleton, BOOL read, FILE *fp)
{
/// Local Variables ///////////////////////////////////////////////////////////
int loop;
t_Bone *child;
///////////////////////////////////////////////////////////////////////////////
if (skeleton->childCnt > 0 && m_Model.vertexData != NULL)
{
child = skeleton->children;
for (loop = 0; loop < skeleton->childCnt; loop++,child++)
{
if (read)
fread(child->CV_weight,sizeof(t_VWeight),m_Model.vertexCnt, fp);
else
fwrite(child->CV_weight,sizeof(t_VWeight),m_Model.vertexCnt, fp);
// Recurse through Hierarchy
if (child->childCnt > 0)
IterateBoneWeights(child, read, fp);
}
}
}
BOOL COGLView::IsThisBone(t_Bone *curbone,char* thename)
{
char string1[] = "Spin";
if (strncmp(curbone->name,string1,4)==0)
{
if(strncmp(curbone->name,thename,7)==0)
{
return TRUE;
}
}
else if(strncmp(curbone->name,thename,4)==0)
{
return TRUE;
}
return FALSE;
}
void COGLView::LoadBoneWeights(t_Bone *skeleton, BOOL read, FILE *fp,char* curname)
{
/// Local Variables ///////////////////////////////////////////////////////////
int loop = 0;
t_Bone *child= NULL;
int tempcnt=0;
int pointid=0;
float pointweight = 0.0;
char string1[] = "Spin";
///////////////////////////////////////////////////////////////////////////////
if (skeleton->childCnt > 0 )
{
child = skeleton->children;
for (loop = 0; loop < skeleton->childCnt; loop++,child++)
{
if (strncmp(curname,string1,4)==0)
{
if(strncmp(child->name,curname,7)==0)
{
fscanf(fp,"%d",&tempcnt);
if (read)
{
for (int i = 0;i<tempcnt;i++)
{
//fscanf(fp," %d %f",&(child->CV_weight[i].vertex),&(child->CV_weight[i].weight));
fscanf(fp,"%d%f",&pointid,&pointweight);
for (int j=0;j<m_Model.vertexCnt;j++)
{
if(((recod_ver_id[j]-1) == pointid) && (child->CV_weight[j].flag == FALSE))
{
child->CV_weight[j].vertex = j;
//if (pointweight>= 30 ||pointweight <= 70)
//{
// child->CV_weight[j].weight = 0.5;
//}else if (pointweight> 70)
//{
// child->CV_weight[j].weight = 1.0;
//}else if (pointweight < 30)
//{
// child->CV_weight[j].weight = 0.0;
//}
child->CV_weight[j].weight = pointweight/100.0;
child->CV_weight[j].flag = TRUE;
}
}
}
for (int j=0;j<m_Model.vertexCnt;j++)
{
if(child->CV_weight[j].flag == FALSE)
{
child->CV_weight[j].vertex = j;
child->CV_weight[j].weight = 0.0;
child->CV_weight[j].flag = TRUE;
}
}
return;
}
}
}
else if(strncmp(child->name,curname,4)==0)
{
fscanf(fp,"%d",&tempcnt);
if (read)
{
for (int i = 0;i<tempcnt;i++)
{
//fscanf(fp," %d %f",&(child->CV_weight[i].vertex),&(child->CV_weight[i].weight));
fscanf(fp,"%d%f",&pointid,&pointweight);
for (int j=0;j<m_Model.vertexCnt;j++)
{
if(((recod_ver_id[j]-1) == pointid) && (child->CV_weight[j].flag == FALSE))
{
child->CV_weight[j].vertex = j;
//if (pointweight>= 30 ||pointweight <= 70)
//{
// child->CV_weight[j].weight = 0.5;
//}else if (pointweight> 70)
//{
// child->CV_weight[j].weight = 1.0;
//}else if (pointweight < 30)
//{
// child->CV_weight[j].weight = 0.0;
//}
child->CV_weight[j].weight = pointweight/100.0;
child->CV_weight[j].flag = TRUE;
}
}
}
for (int j=0;j<m_Model.vertexCnt;j++)
{
if(child->CV_weight[j].flag == FALSE)
{
child->CV_weight[j].vertex = j;
child->CV_weight[j].weight = 0.0;
child->CV_weight[j].flag = TRUE;
}
}
return;
}
}
// Recurse through Hierarchy
if (child->childCnt > 0)
LoadBoneWeights(child, read, fp,curname);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Function: LoadWeights
// Purpose: Load a Weight File
// Arguments: Name of the file to open
///////////////////////////////////////////////////////////////////////////////
BOOL COGLView::LoadWeights(CString name)
{
/// Local Variables ///////////////////////////////////////////////////////////
FILE *fp; // I PREFER THIS STYLE OF FILE ACCESS
int count;
///////////////////////////////////////////////////////////////////////////////
if (fp = fopen((LPCTSTR)name,"rb")) {
fread(&count,sizeof(int),1,fp);
if (m_Model.vertexCnt == count)
{
IterateBoneWeights(&m_Skeleton, TRUE, fp);
}
else
{
::MessageBox(NULL,"Weight File Vertex Count Doesn't Match Model","Weight File Load Error",MB_OK);
}
// Assume if a Weight File is loaded it should be deformed
m_DrawDeformed = TRUE;
fclose(fp);
}
return TRUE;
}
BOOL COGLView::LoadWeightsTest(CString name)
{
/// Local Variables ///////////////////////////////////////////////////////////
FILE *fp; // I PREFER THIS STYLE OF FILE ACCESS
int count;
char tempstr[10];
///////////////////////////////////////////////////////////////////////////////
if (fp = fopen((LPCTSTR)name,"rb"))
{
fscanf(fp,"%d",&count);
if (m_Model.vertexCnt == count)
{
while (!feof(fp))
{
fscanf(fp,"%s",tempstr);
LoadBoneWeights(&m_Skeleton, TRUE, fp,tempstr);
}
}
else
{
::MessageBox(NULL,"Weight File Vertex Count Doesn't Match Model","Weight File Load Error",MB_OK);
}
// Assume if a Weight File is loaded it should be deformed
m_DrawDeformed = TRUE;
fclose(fp);
}
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
// Function: SaveWeights
// Purpose: Save a Set of Weight Files
// Arguments: Name of the file to save
///////////////////////////////////////////////////////////////////////////////
BOOL COGLView::SaveWeights(CString name)
{
/// Local Variables ///////////////////////////////////////////////////////////
FILE *fp; // I PREFER THIS STYLE OF FILE ACCESS
///////////////////////////////////////////////////////////////////////////////
if (fp = fopen((LPCTSTR)name,"wb")) {
fwrite(&m_Model.vertexCnt,sizeof(int),1,fp);
IterateBoneWeights(&m_Skeleton, FALSE, fp);
fclose(fp);
}
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
// Function: LoadOBJModel
// Purpose: Load an OBJ Model into the system
// Arguments: Name of the file to open
///////////////////////////////////////////////////////////////////////////////
BOOL COGLView::LoadOBJModel(CString name)
{
/// Local Variables ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
if (m_Model.vertexData != NULL) // Free model data if exists
{
free(m_Model.vertexData);
free(m_Model.deformData);
free(m_Model.CV_select);
m_Model.vertexData = NULL;
m_Model.deformData = NULL;
m_Model.CV_select = NULL;
}
//LoadOBJ((LPCSTR)name,&m_Model);
LoadOBJTest((LPCSTR)name,&m_Model,cur_index,&counter,recod_ver_id);
SetSkeletonList(&m_Skeleton); // Set up Weights
SetBasePose(); // Lock in the Rest State
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
// Function: LoadSkeletonFile
// Purpose: Load a Skeleton into the system
// Arguments: Name of the file to open
///////////////////////////////////////////////////////////////////////////////
BOOL COGLView::LoadSkeletonFile(CString name)
{
/// Local Variables ///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
DestroySkeleton(&m_Skeleton);
//LoadSkeleton(name,&m_Skeleton);
LoadSkeletonTest(name,&m_Skeleton);
SetSkeletonList(&m_Skeleton); // Set up Weights
return TRUE;
}
void COGLView::RenderStockScene()
{
int color = 0;
// define the two colors
GLfloat color1[3] = { 0.7f, 0.7f, 0.7f };
GLfloat color2[3] = { 0.2f, 0.2f, 0.2f };
glPushAttrib(GL_CURRENT_BIT);
glEnable(GL_BLEND);
glPushMatrix();
int size0 = (int)(40);
glBegin( GL_QUADS );
for ( int x = -size0 ; x <= 32 ; x+=5)
{
for ( int z = -200 ; z <= 40 ; z+=5 )
{
glColor3fv( (color++)%2 ? color1 : color2 );
glVertex3i( x, 0, z+4);
glVertex3i( x+4, 0, z+4);
glVertex3i( x+4, 0, z);
glVertex3i( x, 0, z);
}
}
glEnd();
glBegin(GL_LINES);
glVertex3i(-40, 0, -200); glVertex3i(-40, 80, -200);
glVertex3i(34, 0, -200); glVertex3i( 34, 80, -200);
glEnd();
glPopMatrix();
glDisable(GL_BLEND);
glPopAttrib();
}
| [
"macrotao86@4a66b584-afee-11de-9d1a-45ab25924541"
] | [
[
[
1,
1956
]
]
] |
7f5b66bc2ac4f4dc92238da51857cc1b985b80db | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_core/containers/juce_PropertySet.cpp | 062302e387564f217080283ba6c8539cd958b59c | [] | no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,022 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
BEGIN_JUCE_NAMESPACE
//==============================================================================
PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
: properties (ignoreCaseOfKeyNames),
fallbackProperties (nullptr),
ignoreCaseOfKeys (ignoreCaseOfKeyNames)
{
}
PropertySet::PropertySet (const PropertySet& other)
: properties (other.properties),
fallbackProperties (other.fallbackProperties),
ignoreCaseOfKeys (other.ignoreCaseOfKeys)
{
}
PropertySet& PropertySet::operator= (const PropertySet& other)
{
properties = other.properties;
fallbackProperties = other.fallbackProperties;
ignoreCaseOfKeys = other.ignoreCaseOfKeys;
propertyChanged();
return *this;
}
PropertySet::~PropertySet()
{
}
void PropertySet::clear()
{
const ScopedLock sl (lock);
if (properties.size() > 0)
{
properties.clear();
propertyChanged();
}
}
String PropertySet::getValue (const String& keyName,
const String& defaultValue) const noexcept
{
const ScopedLock sl (lock);
const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
if (index >= 0)
return properties.getAllValues() [index];
return fallbackProperties != nullptr ? fallbackProperties->getValue (keyName, defaultValue)
: defaultValue;
}
int PropertySet::getIntValue (const String& keyName,
const int defaultValue) const noexcept
{
const ScopedLock sl (lock);
const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
if (index >= 0)
return properties.getAllValues() [index].getIntValue();
return fallbackProperties != nullptr ? fallbackProperties->getIntValue (keyName, defaultValue)
: defaultValue;
}
double PropertySet::getDoubleValue (const String& keyName,
const double defaultValue) const noexcept
{
const ScopedLock sl (lock);
const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
if (index >= 0)
return properties.getAllValues()[index].getDoubleValue();
return fallbackProperties != nullptr ? fallbackProperties->getDoubleValue (keyName, defaultValue)
: defaultValue;
}
bool PropertySet::getBoolValue (const String& keyName,
const bool defaultValue) const noexcept
{
const ScopedLock sl (lock);
const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
if (index >= 0)
return properties.getAllValues() [index].getIntValue() != 0;
return fallbackProperties != nullptr ? fallbackProperties->getBoolValue (keyName, defaultValue)
: defaultValue;
}
XmlElement* PropertySet::getXmlValue (const String& keyName) const
{
return XmlDocument::parse (getValue (keyName));
}
void PropertySet::setValue (const String& keyName, const var& v)
{
jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
if (keyName.isNotEmpty())
{
const String value (v.toString());
const ScopedLock sl (lock);
const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
if (index < 0 || properties.getAllValues() [index] != value)
{
properties.set (keyName, value);
propertyChanged();
}
}
}
void PropertySet::removeValue (const String& keyName)
{
if (keyName.isNotEmpty())
{
const ScopedLock sl (lock);
const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
if (index >= 0)
{
properties.remove (keyName);
propertyChanged();
}
}
}
void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
{
setValue (keyName, xml == nullptr ? var::null
: var (xml->createDocument (String::empty, true)));
}
bool PropertySet::containsKey (const String& keyName) const noexcept
{
const ScopedLock sl (lock);
return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
}
void PropertySet::addAllPropertiesFrom (const PropertySet& source)
{
const ScopedLock sl (source.getLock());
for (int i = 0; i < source.properties.size(); ++i)
setValue (source.properties.getAllKeys() [i],
source.properties.getAllValues() [i]);
}
void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) noexcept
{
const ScopedLock sl (lock);
fallbackProperties = fallbackProperties_;
}
XmlElement* PropertySet::createXml (const String& nodeName) const
{
const ScopedLock sl (lock);
XmlElement* const xml = new XmlElement (nodeName);
for (int i = 0; i < properties.getAllKeys().size(); ++i)
{
XmlElement* const e = xml->createNewChildElement ("VALUE");
e->setAttribute ("name", properties.getAllKeys()[i]);
e->setAttribute ("val", properties.getAllValues()[i]);
}
return xml;
}
void PropertySet::restoreFromXml (const XmlElement& xml)
{
const ScopedLock sl (lock);
clear();
forEachXmlChildElementWithTagName (xml, e, "VALUE")
{
if (e->hasAttribute ("name")
&& e->hasAttribute ("val"))
{
properties.set (e->getStringAttribute ("name"),
e->getStringAttribute ("val"));
}
}
if (properties.size() > 0)
propertyChanged();
}
void PropertySet::propertyChanged()
{
}
END_JUCE_NAMESPACE
| [
"ow3nskip"
] | [
[
[
1,
225
]
]
] |
a545569feb2761a66c44f3fdce0848aa066c44f2 | 022d2957a29fe5054263a406bbdd85289cf17ee0 | /GontrolPC/GontrolPC/RecvFrame.cpp | 745385f3283ecb07f17cb2b1aca83019a0f5fdf5 | [] | no_license | amanuelg3/remote-control-with-android | aa6705da5c76311515ef6c4c972b7e64745be76d | 5e51aff7d1727608c615a0027c746592ebc4ba92 | refs/heads/master | 2016-09-03T01:07:29.047261 | 2011-06-11T16:25:32 | 2011-06-11T16:25:32 | 35,783,127 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,780 | cpp | #include "stdafx.h"
#include "RecvFrame.h"
#include "Resource.h"
CRecvFrame::CRecvFrame()
{
m_hSemophere = ::CreateSemaphore(NULL,0,0x7FFFFFFF,NULL);
::InitializeCriticalSection(&m_csFrame);
::InitializeCriticalSection(&m_csBlock);
m_hThread = NULL;
m_ListenSocket= INVALID_SOCKET;
m_fExit = 1;
m_vSocketAddr.reserve(FD_SETSIZE);
this->m_ThreadAddr = sThreadFunc;
m_pMsgQueue = NULL;
}
CRecvFrame::~CRecvFrame()
{
Stop();
for (unsigned i = 0; i < m_vSocketAddr.size(); i++)
{
closesocket(m_vSocketAddr[i].s);
}
::CloseHandle(m_hSemophere);
::DeleteCriticalSection(&m_csFrame);
::DeleteCriticalSection(&m_csBlock);
}
void CRecvFrame::SetSockPort(unsigned short port)
{
m_sPort = port;
}
unsigned short CRecvFrame::GetSockPort() const
{
return m_sPort;
}
void CRecvFrame::SetMsgQueue(CSafeQueue<ConnMsg> * pQueue)
{
m_pMsgQueue = pQueue;
}
HANDLE CRecvFrame::GetSemophere() const
{
return m_hSemophere;
}
void CRecvFrame::AddBlockAddr(const char * szAddr)
{
u_long uaddr = inet_addr(szAddr);
::EnterCriticalSection(&m_csBlock);
if (m_setBlock.insert(uaddr).second)
{
std::vector<Socket_Addr>::iterator iter = m_vSocketAddr.begin();
while (iter != m_vSocketAddr.end())
{
if (((struct sockaddr_in *)&iter->addr)->sin_addr.s_addr == uaddr)
{
m_vSocketAddr.erase(iter);
break;
}
iter++;
}
}
::LeaveCriticalSection(&m_csBlock);
}
void CRecvFrame::DelBlockAddr(const char * szAddr)
{
u_long uaddr = inet_addr(szAddr);
::EnterCriticalSection(&m_csBlock);
m_setBlock.erase(uaddr);
::LeaveCriticalSection(&m_csBlock);
}
int CRecvFrame::Start()
{
if (InitSocket())
{
#ifdef _DEBUG
::OutputDebugString(_T("RecvFrame: Init Socket Error"));
#endif
return -1;
}
return IMyThread::Start();
}
std::string CRecvFrame::GetFrame()
{
std::string frame = "";
::EnterCriticalSection(&m_csFrame);
if (m_dqRecvedFrame.size())
{
frame = m_dqRecvedFrame.front();
m_dqRecvedFrame.pop_front();
}
::LeaveCriticalSection(&m_csFrame);
return frame;
}
unsigned int __stdcall CRecvFrame::sThreadFunc(void * p)
{
CRecvFrame * pThis = dynamic_cast<CRecvFrame *>(reinterpret_cast<IMyThread *>(p));
if (!pThis)
{
#ifdef _DEBUG
::OutputDebugString(_T("RecvFrame: Thread this Pointer Error"));
#endif
return -1;
}
struct fd_set rfds;
struct timeval t;
t.tv_sec = THREADWAIT/1000;
t.tv_usec = (THREADWAIT%1000)*1000;
const int BUFSIZE = 0xFFFF;
char buffer[BUFSIZE];
char * pchStart;
int indexStart;
int len;
int nRecvCount;
int nReadyCount;
unsigned int i = 1;
while (!pThis->m_fExit)
{
FD_ZERO(&rfds);
::EnterCriticalSection(&pThis->m_csBlock);
for (i = 0; i < pThis->m_vSocketAddr.size(); i++)
{
FD_SET(pThis->m_vSocketAddr[i].s,&rfds);
}
::LeaveCriticalSection(&pThis->m_csBlock);
//t.tv_sec = THREADWAIT/1000; //Windows will not alter the timeval
//t.tv_usec = (THREADWAIT%1000)*1000;
if ((nReadyCount = select(pThis->m_SocketMax+1,&rfds,NULL,NULL,&t)) > 0)
{
::EnterCriticalSection(&pThis->m_csBlock);
if (FD_ISSET(pThis->m_ListenSocket,&rfds))
{
Socket_Addr sock_addr;
sock_addr.addrlen = sizeof(struct sockaddr_in);
sock_addr.s = accept(pThis->m_ListenSocket,(struct sockaddr *)&sock_addr.addr,&sock_addr.addrlen);
if (sock_addr.s != INVALID_SOCKET)
{
if (pThis->m_setBlock.find(((struct sockaddr_in *)&(sock_addr.addr))->sin_addr.s_addr)
!= pThis->m_setBlock.end() || pThis->m_vSocketAddr.size() >= FD_SETSIZE)
{
closesocket(sock_addr.s);
if (pThis->m_pMsgQueue)
{
ConnMsg msg;
msg.StringID = IDS_REFUSECONNECT;
msg.iData = 0;
strncpy_s(msg.szData,
::inet_ntoa(((struct sockaddr_in *)&(sock_addr.addr))->sin_addr),
20);
pThis->m_pMsgQueue->Put(msg);
}
}
else
{
if (sock_addr.s > pThis->m_SocketMax)
{
pThis->m_SocketMax = sock_addr.s;
}
pThis->m_vSocketAddr.push_back(sock_addr);
#ifdef _DEBUG
::OutputDebugString(_T("ac "));
#endif
if (pThis->m_pMsgQueue)
{
ConnMsg msg;
msg.StringID = IDS_CONNECTESTABLISH;
msg.iData = 0;
strncpy_s(msg.szData,
::inet_ntoa(((struct sockaddr_in *)&(sock_addr.addr))->sin_addr),
20);
pThis->m_pMsgQueue->Put(msg);
}
}
}
nReadyCount --;
} //end of 'if (FD_ISSET(pThis->m_ListenSocket,&rfds))
std::vector<Socket_Addr>::iterator iter = pThis->m_vSocketAddr.begin();
iter++;
while (nReadyCount && iter != pThis->m_vSocketAddr.end())
{
if (FD_ISSET(iter->s,&rfds))
{
nReadyCount--;
nRecvCount = recv(iter->s,buffer,BUFSIZE-1,0);
if (nRecvCount > 0)
{
#ifdef _DEBUG
::OutputDebugString(_T("rc "));
#endif
buffer[nRecvCount] = 0;
pchStart = buffer;
indexStart = 0;
while (indexStart < nRecvCount)
{
iter->szRecvedBuffer += pchStart;
len = strlen(pchStart);
if (indexStart + len < nRecvCount)
{
::EnterCriticalSection(&pThis->m_csFrame);
pThis->m_dqRecvedFrame.push_back(iter->szRecvedBuffer);
::LeaveCriticalSection(&pThis->m_csFrame);
::ReleaseSemaphore(pThis->m_hSemophere,1,NULL);
iter->szRecvedBuffer = "";
}
pchStart += len + 1;
indexStart += len + 1;
}
}
else if (!nRecvCount)
{
closesocket(iter->s);
#ifdef _DEBUG
::OutputDebugString(_T("dc "));
#endif
if (pThis->m_pMsgQueue)
{
ConnMsg msg;
msg.StringID = IDS_DISCONNECT;
msg.iData = 0;
strncpy_s(msg.szData,
::inet_ntoa(((struct sockaddr_in *)&(iter->addr))->sin_addr),
20);
pThis->m_pMsgQueue->Put(msg);
}
iter = pThis->m_vSocketAddr.erase(iter);
continue;
}
else
{
closesocket(iter->s);
#ifdef _DEBUG
::OutputDebugString(_T("fc "));
#endif
if (pThis->m_pMsgQueue)
{
ConnMsg msg;
msg.StringID = IDS_LOSTCONNECT;
msg.iData = 0;
strncpy_s(msg.szData,
::inet_ntoa(((struct sockaddr_in *)&(iter->addr))->sin_addr),
20);
pThis->m_pMsgQueue->Put(msg);
}
iter = pThis->m_vSocketAddr.erase(iter);
continue;
}
} // end of 'if (FD_ISSET(iter->s,&rfds))
iter++;
}// end of 'while (nReadyCount && iter != pThis->m_vSocketAddr.end())
::LeaveCriticalSection(&pThis->m_csBlock);
}// end of 'if ((nReadyCount = select(pThis->m_SocketMax+1,&rfds,NULL,NULL,&t)) > 0)
else
{
#ifdef _DEBUG
::OutputDebugString(_T("px "));
#endif
}
}
return 0;
}
int CRecvFrame::InitSocket()
{
Socket_Addr sock_addr;
for (unsigned i = 0; i < m_vSocketAddr.size(); i++)
{
closesocket(m_vSocketAddr[i].s);
}
m_vSocketAddr.clear();
sock_addr.s = socket(AF_UNSPEC,SOCK_STREAM,IPPROTO_TCP);
if (sock_addr.s == INVALID_SOCKET)
{
return -1;
}
sock_addr.addrlen = sizeof(struct sockaddr_in);
((struct sockaddr_in *)&(sock_addr.addr))->sin_port = htons(m_sPort);
((struct sockaddr_in *)&(sock_addr.addr))->sin_family = AF_INET;
((struct sockaddr_in *)&(sock_addr.addr))->sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock_addr.s,(struct sockaddr *)&sock_addr.addr,sock_addr.addrlen))
{
closesocket(sock_addr.s);
return -1;
}
if (listen(sock_addr.s,SOMAXCONN))
{
closesocket(sock_addr.s);
return -1;
}
m_vSocketAddr.push_back(sock_addr);
m_ListenSocket = sock_addr.s;
m_SocketMax = sock_addr.s;
return 0;
} | [
"wzmvictor@5d9a875e-b1a7-14b0-4603-314cddc6b85c"
] | [
[
[
1,
304
]
]
] |
ba47fa6589a91ce754b90377ca34a8a549475b45 | 2fc8903fabbf9889c14a109b9210a8b51ed6df0a | /bench/hash2/hash2.gpp | 707afdea02ec1bfd7c1d7a7ad7013bfb21722479 | [
"BSD-3-Clause"
] | permissive | kragen/shootout | 6620f5756d3a2f6d9dce32e86851835cfdf5d5bc | 71aa4ec4cd15940c59f1a1bb71ac1ff1572a55c2 | refs/heads/master | 2021-01-01T06:50:07.668336 | 2011-05-17T22:22:19 | 2011-05-17T22:22:19 | 1,693,719 | 18 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 1,575 | gpp | // -*- mode: c++ -*-
// $Id: hash2.gpp,v 1.2 2004-11-30 07:10:03 bfulgham Exp $
// http://shootout.alioth.debian.org/
#include <stdio.h>
#include <iostream>
#include <ext/hash_map>
using namespace std;
#if (! defined(__INTEL_COMPILER))
using namespace __gnu_cxx;
#endif
struct eqstr {
bool operator()(const char* s1, const char* s2) const {
if (s1 == s2) return true;
if (!s1 || !s2) return false;
while (*s1 != '\0' && *s1 == *s2)
s1++, s2++;
return *s1 == *s2;
}
};
struct strhash {
#if defined(__INTEL_COMPILER)
enum { bucket_size = 4, min_buckets = 8 };
bool operator()(char const *s1, char const *s2) const
{return strcmp(s1, s2) < 0;}
#endif
size_t operator()(const char* s) const {
size_t i;
for (i = 0; *s; s++)
i = 31 * i + *s;
return i;
}
};
int main(int argc, char *argv[]) {
int n = ((argc == 2) ? atoi(argv[1]) : 1);
char buf[16];
#if defined(__INTEL_COMPILER)
typedef hash_map<const char*, int, strhash> HM;
#else
typedef hash_map<const char*, int, strhash, eqstr> HM;
#endif
HM hash1, hash2;
for (int i=0; i<10000; i++) {
sprintf(buf, "foo_%d", i);
hash1[strdup(buf)] = i;
}
for (int i=0; i<n; i++) {
for (HM::iterator k = hash1.begin(); k != hash1.end(); ++k) {
hash2[(*k).first] += k->second;
}
}
cout << hash1["foo_1"] << " " << hash1["foo_9999"] << " "
<< hash2["foo_1"] << " " << hash2["foo_9999"] << endl;
}
| [
"bfulgham"
] | [
[
[
1,
60
]
]
] |
faaea9f80d4ec949ec988056b60cbf689223f599 | af260b99d9f045ac4202745a3c7a65ac74a5e53c | /trunk/engine/src/SeedSearcher.cpp | cc647f6b2c46525d236193eadba96304c7c8e002 | [] | no_license | BackupTheBerlios/snap-svn | 560813feabcf5d01f25bc960d474f7e218373da0 | a99b5c64384cc229e8628b22f3cf6a63a70ed46f | refs/heads/master | 2021-01-22T09:43:37.862180 | 2008-02-17T15:50:06 | 2008-02-17T15:50:06 | 40,819,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,332 | cpp | //
// File : $RCSfile: $
// $Workfile: SeedSearcher.cpp $
// Version : $Revision: 39 $
// $Author: Aviad $
// $Date: 13/05/05 11:11 $
// Description :
// Concrete class for seed-searching in a preprocessor
//
// Author:
// Aviad Rozenhek (mailto:[email protected]) 2003-2004
//
// written for the SeedSearcher program.
// for details see www.huji.ac.il/~hoan
// and also http://www.cs.huji.ac.il/~nirf/Abstracts/BGF1.html
//
// this file and as well as its library are released for academic research
// only. the LESSER GENERAL PUBLIC LICENSE (LPGL) license
// as well as any other restrictions as posed by the computational biology lab
// and the library authors appliy.
// see http://www.cs.huji.ac.il/labs/compbio/LibB/LICENSE
//
#include "SeedSearcher.h"
#include "Assignment.h"
#include "Sequence.h"
#include "Cluster.h"
#include "SeedHash.h"
#include "DebugLog.h"
#include "core/HashTable.h"
#include "persistance/TextWriter.h"
#include "persistance/StrOutputStream.h"
#include <boost/timer.hpp>
#include <iostream>
#include <time.h>
using namespace std;
using namespace seed;
//
// debug: cross-reference tree-search model with prefix-tree-walk model (safer)
#define SEED_TREE_SEARCH_DEBUG 0
#if SEED_TREE_SEARCH_DEBUG
static void compareSeedResult (const PrefixTreePreprocessor& tree,
const Assignment& feature,
const SequenceDB::Cluster& containingFeature);
#endif
//
// Gene counts
//
//
// assignment that lead to a node <--> cluster of sequences in the node
typedef std::pair <Assignment*, SequenceDB::Cluster*> FeaturePairBase;
struct FeaturePair :
public FeaturePairBase
{
FeaturePair () {
}
FeaturePair (Assignment* assg, SequenceDB::Cluster* cluster)
: FeaturePairBase (assg, cluster) {
}
};
class FeatureVector : public Vec <FeaturePair> {
};
static void clean (FeaturePair& p)
{
delete p.first;
delete p.second;
p.first = NULL;
p.second = NULL;
}
struct FeatureComparator : public std::binary_function<FeaturePair, FeaturePair, bool> {
FeatureComparator (int startIndex) : _startIndex (startIndex) {
}
//
// features by their assignment
bool operator() (const FeaturePair& x, const FeaturePair& y) const {
int result = x.first->compare (*y.first, _startIndex);
return result < 0;
}
int _startIndex;
};
static int together (FeatureVector& myFeatures, // stores the features of the node
int fromIndex, // from where to start the merge
int myDepth,
bool totalCount
)
{
int size = myFeatures.size ();
int numFeatures = size - fromIndex;
if (numFeatures == 0)
return 0;
else if (numFeatures == 1) {
//
// add the position that got us here to the feature
return 1;
}
else {
//
// all the features that have similar endings are grouped assg_together.
typedef std::set <FeaturePair, FeatureComparator> FeatureSet;
FeatureComparator comparator (myDepth + 1);
FeatureSet features (comparator);
for (int i=fromIndex ; i<size ; i++) {
//
// we should be unifying on the '?' wildcard character
debug_only (
Assignment::Strategy strategy =
myFeatures [i].first->getPosition (myDepth).strategy ();
debug_mustbe (strategy == assg_together);
);
//
//
std::pair<FeatureSet::iterator, bool> result =
features.insert (myFeatures [i]);
if (result.second == false) {
Assignment& resultProjection =
*result.first->first;
//
// it is already in the set...
# if SEED_TREE_SEARCH_DEBUG
DLOG << "rec_prefixTreeSearch (): grouping assg_together "
<< Format (resultProjection)
<< " with "
<< Format (*myFeatures [i].first)
<< DLOG.EOL ();
# endif
const FeatureSet::iterator& it = result.first;
SeqCluster* seqCluster = it->second;
if (totalCount) {
seqCluster->unifyPositions (*myFeatures [i].second);
}
else {
seqCluster->unify (*myFeatures [i].second);
}
//
// now we generalize the projection
resultProjection [myDepth].unify (
myFeatures [i].first->getPosition (myDepth));
//
// clean memory of this feature
clean (myFeatures [i]);
}
}
//
// resize myFeatures and copy the relevant features back from the set
int newSize = fromIndex + features.size ();
if (size != newSize) {
myFeatures.resize (newSize);
IteratorWrapper <FeatureSet> it (features.begin (), features.end ());
for (int index=fromIndex ; index<newSize ; it.next (), index++) {
//
// add the position that got us here to the feature
myFeatures [index] = *it;
}
}
return features.size ();
}
}
//
// combine child seeds if we have '?' wildcard
static int combineChildSeeds (const Assignment& projection,
FeatureVector& myFeatures,
int newEntries,
int myDepth,
bool totalCount)
{
if (projection [myDepth].strategy () == assg_together) {
//
// this means that we got here with 'assg_together' strategy
// so we keep the exact same positions in the feature.
//
// also, the features added are grouped assg_together.
int size = myFeatures.size ();
int firstFeatureIndex = size - newEntries;
return together (myFeatures, firstFeatureIndex , myDepth, totalCount);
}
return newEntries;
}
static void addAssignmentPosition (
bool specializeProjection,
const Assignment& projection,
FeatureVector& myFeatures,
int childIndex,
int newEntries,
int myDepth)
{
const Assignment::Position& thisPosition = projection [myDepth-1];
Assignment::Strategy strategy = thisPosition.strategy ();
int size = myFeatures.size ();
if (specializeProjection || (strategy == assg_discrete)) {
//
// this means that the exact code of this depth is important
for (int i= size - newEntries ; i< size ; i++) {
myFeatures [i].first->setPosition (myDepth-1,
Assignment::Position (childIndex, strategy));
}
}
else {
debug_mustbe (strategy == assg_together);
//
// this means that we got here with 'assg_together' strategy
// without projection specialization option.
// so we keep the exact same positions in the feature.
for (int i= size - newEntries ; i< size ; i++) {
myFeatures [i].first->setPosition (myDepth-1, thisPosition);
}
}
}
//
// returns the amount of new entries in myFeatures vector
static int rec_prefixTreeSearch (
SeedSearcher::SearchParameters& params,
PrefixTreePreprocessor::TreeNodeRep* inNode, // where to search
const Assignment& projection, // how to climb down the tree
FeatureVector& myFeatures, // stores the features of the node
int myDepth, // current depth in the tree
int desiredDepth, // desired depth / length of features
int childIndex // what is my index as child of my parent
)
{
if (inNode == NULL)
return 0;
PrefixTreePreprocessor::TreeNode node (inNode);
if (myDepth == desiredDepth) {
AutoPtr <SequenceDB::Cluster> seqInNode =
new SequenceDB::Cluster;
if (params.useTotalCount())
node.add2SeqClusterPositions (*seqInNode);
else
node.add2SeqCluster (*seqInNode);
//
// we are at the desired length
myFeatures.push_back(
FeaturePair (new Assignment, seqInNode.release ()));
addAssignmentPosition ( params.useSpecialization (),
projection,
myFeatures,
childIndex,
1,
myDepth);
return 1;
}
//
// we have not yet reached the needed length
// so call the recursive function, for each child that corresponds
// to a code in the assignment's position
int newEntries = 0;
Assignment::PositionIterator posIt (projection [myDepth]);
for (; posIt.hasNext () ; posIt.next ()) {
//
//
const int nextChildIndex = posIt.get ();
const int newChildEntries =
rec_prefixTreeSearch (
params,
node.getChild (nextChildIndex), // where to search
projection, // how to climb down the tree
myFeatures, // stores the features of the node
myDepth + 1, // current depth in the tree
desiredDepth, // desired depth / length of features
nextChildIndex // index of the child
);
//
//
newEntries += newChildEntries;
}
if (newEntries == 0)
return 0;
//
// combine position for chlid if they have assg_together strategy
newEntries = combineChildSeeds (projection,
myFeatures,
newEntries,
myDepth,
params.useTotalCount ());
//
// add our position to all the features
addAssignmentPosition (
params.useSpecialization (),
projection,
myFeatures,
childIndex,
newEntries,
myDepth);
//
// now for each new position in the vector, add the position
// that got us here
return newEntries;
}
int SeedSearcher::prefixTreeSearch (
boost::shared_ptr <SearchParameters> params,
const Assignment& projection, // how to climb down the tree
int desiredDepth // desired depth / length of features
)
{
const PrefixTreePreprocessor& tree =
*safe_cast (const PrefixTreePreprocessor*, &(params->preprocessor ()));
debug_mustbe (projection.length () > 0);
debug_mustbe (projection.length () <= tree.getDepth ());
debug_mustbe (desiredDepth <= projection.length ());
debug_mustbe (desiredDepth > 0);
PrefixTreePreprocessor::TreeNode node (tree.getRoot ());
const Assignment::Position& firstPosition = projection[0];
//
// a projection in the first position is both meaningless
// and is a lot of hassle to program.
debug_mustbe (firstPosition.strategy () == assg_discrete);
int totalSeedsFound = 0;
double totalTimeEvaluatingSeeds = 0;
//
// optimization: we keep the vector here in order to avoid
// increasing capacity and then deleting its contents.
// resize () function does not deallocate space.
FeatureVector childFeatures;
Assignment::PositionIterator posIt (firstPosition);
for (; posIt.hasNext () ; posIt.next ()) {
int childIndex = posIt.get ();
rec_prefixTreeSearch (
*params,
node.getChild (childIndex), //where to search
projection, // how to climb down the tree
childFeatures, // storage for all the child's features
1, // current depth in the tree
desiredDepth, // desired depth / length of features
childIndex // index of the chlid
);
boost::timer t;
//
// now we have all the relevant features from our child
// insert them all to the FeatureFilter container
int size = childFeatures.size ();
for (int i=0 ; i < size ; i++) {
const FeaturePair feature = childFeatures [i];
//
// only for debbuging
# if SEED_TREE_SEARCH_DEBUG
compareSeedResult (tree,
*feature.first, // the assignment
*feature.second // sequences containing the feature
);
# endif
Feature_var seed_feature (new Feature);
FeatureParameters::createFeature (params,
*seed_feature,
// the feature's assignment
feature.first,
// sequences containing the feature
feature.second,
&projection
);
//
// this also cleans up memory, if necessary
params->bestFeatures ().add (seed_feature);
}
//
// accumolate times
totalTimeEvaluatingSeeds += t.elapsed ();
totalSeedsFound += size;
childFeatures.resize (0);
}
DLOG << "[Evaluating seeds: " << static_cast <int> (totalTimeEvaluatingSeeds) << " seconds] ";
return totalSeedsFound;
}
struct TableSearcher {
//
//
class AbstractSeed : public SeedHash::Cluster <AbstractSeed> {
public:
inline AbstractSeed (const Key& key)
: SeedHash::Cluster <AbstractSeed> (key)
{
}
virtual ~AbstractSeed () {
}
virtual void addPositions (const Preprocessor::Node& node)=0;
virtual void addSequences (const Preprocessor::Node& node)=0;
};
class Seed : public AbstractSeed
{
public:
inline Seed (const Key& key) : AbstractSeed (key) {
}
virtual ~Seed () {
}
//
//
virtual void addPositions (const Preprocessor::Node& node) {
node.add2SeqClusterPositions (*_cluster);
}
//
//
virtual void addSequences (const Preprocessor::Node& node) {
node.add2SeqCluster (*_cluster);
}
};
struct SeedComparator {
inline bool operator ()( const TableSearcher::AbstractSeed* a,
const TableSearcher::AbstractSeed* b) {
return (a->assignment().compare (b->assignment()) < 0);
}
};
class SpecializedSeed : public AbstractSeed
{
public:
SpecializedSeed (const Key& key) : AbstractSeed (key) {
//
//
const Assignment& assg = key.assignment ();
_specialization = new Assignment (assg);
//
// an empty assg_together position
Assignment::Position together_p (assg_together);
//
//
int length = assg.length ();
for (int i=0 ; i<length ; i++) {
if (assg [i].strategy () == assg_together)
//
// make all assg_together positions blank
_specialization->setPosition (i, together_p);
}
}
virtual ~SpecializedSeed () {
}
//
//
virtual void addPositions (const Preprocessor::Node& node) {
node.add2SeqClusterPositions (*_cluster);
node.add2Assignment (*_specialization);
}
//
//
virtual void addSequences (const Preprocessor::Node& node) {
node.add2SeqCluster (*_cluster);
node.add2Assignment (*_specialization);
}
Assignment* releaseSpecializtion () {
return _specialization.release ();
}
protected:
AutoPtr <Assignment> _specialization;
};
//
//
typedef SeedHash::Table <AbstractSeed> SeedHashTableBase;
class Table : public SeedHashTableBase{
public:
Table ( bool totalCount,
bool specialize,
int tableSize,
const Langauge& langauge)
: SeedHashTableBase (tableSize, langauge),
_totalCount (totalCount), _specialize (specialize) {
}
//
//
void addSeed ( const Assignment& projection,
const Preprocessor::Node& node) {
SeedHash::AssgKey key (projection, _langauge);
//
// search for it in the table
AbstractSeed* cachedSeed = this->find (key);
if (cachedSeed == NULL) {
//
// it is a totally new feature
cachedSeed = createCluster (key);
this->add (cachedSeed);
}
//
// it converges to a feature we already have
if (_totalCount) {
// so we sum their total counts
cachedSeed->addPositions (node);
}
else {
// so we some their gene counts
cachedSeed->addSequences (node);
}
}
virtual AbstractSeed* createCluster (const SeedHash::AssgKey& key){
if (_specialize)
return new SpecializedSeed (key);
else
return new Seed (key);
}
protected:
bool _totalCount;
bool _specialize;
};
struct SeedVector : public Vec <AbstractSeed*> {
~SeedVector () {
for (iterator i = begin () ; i!= end () ; ++i) {
delete *i;
}
}
};
};
static const int DEFAULT_SEED_HASH_TABLE_SIZE = 7 * 1023 * 1024 - 1;
static void
createFeatureTable ( TableSearcher::SeedVector& outVector,
TableSearcher::Table& hashTable,
SeedSearcher::SearchParameters& params,
const Assignment& projection)
{
//
// collect features assg_together, (with optional total counts)
Preprocessor::NodeCluster nodes;
params.preprocessor ().add2Cluster (nodes, projection);
Preprocessor::NodeIterator it = nodes.iterator ();
for (; it.hasNext () ; it.next ()) {
const Preprocessor::AssgNodePair& nodeWithPath = it.get ();
Preprocessor::Node node (nodeWithPath.node ());
//
//
debug_mustbe (nodeWithPath.path ().length () == projection.length ());
hashTable.addSeed (nodeWithPath.path (), node);
}
//
// sort the features into a vector of features
// this is in order to have consistent results across search algorithms
// and across preprocessors
reserveClear(outVector,
hashTable.TableSearcher::Table::HashTableBase::getSize ());
TableSearcher::SeedHashTableBase::Iterator featureIt (hashTable);
for (; featureIt.hasNext () ; featureIt.next ()) {
//
// put the feature in the vector
outVector.push_back (safe_cast (TableSearcher::AbstractSeed*, featureIt.get ()));
}
std::sort (outVector.begin (), outVector.end (),
TableSearcher::SeedComparator ());
//
// we don't want the table to delete our features
// so we clear it
hashTable.clear(/* do not delete elements */ false);
}
static int extendedTableSearch (
boost::shared_ptr <SeedSearcher::SearchParameters> params,
const Assignment& projection)
{
//
// TODO: support specialization
//
// constants for later use
const int prefixLength = params->preprocessor().maxAssignmentSize();
const int postfixLength = projection.length () - prefixLength;
const int totalLength = prefixLength + postfixLength;
const SubAssignment projectionPrefix (projection, 0, prefixLength);
const SubAssignment projectionPostfix (projection, prefixLength);
//
// make sure SubAssignments work well
debug_mustbe (
projectionPrefix.length () + projectionPostfix.length () == projection.length ());
TableSearcher::SeedVector seeds;
{
//
// now we want to create a unified view of preprocessor-nodes
// according to the projection's prefix
TableSearcher::Table shortHashTable (
/* use total count because we need the positions */ true,
/* don't use specialization */ false,
DEFAULT_SEED_HASH_TABLE_SIZE,
params->langauge ());
//
// get all the nodes of the preprocessor up to maximum length
Preprocessor::NodeCluster nodes;
params->preprocessor ().add2Cluster (nodes, projectionPrefix);
createFeatureTable (seeds, shortHashTable, *params, projectionPrefix);
}
//
// all the variables below are defined outside the loops
// for efficiency - less new/delete
//
// seqCluster - used by outer loop
SeqCluster seqCluster;
//
// used by inner loop
Assignment currentAssgPostfix;
PositionVector currentPositions;
PositionVector nextPositions;
AutoPtr <SeqCluster> currentSeqCluster = new SeqCluster;
int seedsFound = 0;
//
// go over all unified nodes
IteratorWrapper < TableSearcher::SeedVector > featureIt (seeds.begin (), seeds.end ());
for (; featureIt.hasNext () ; featureIt.next ()) {
TableSearcher::AbstractSeed* feature = featureIt.get ();
//
// get the node's assignment and positions
const Assignment& currentAssgPrefix = feature->assignment ();
SeqCluster::SeqPosIterator seqPosIt (feature->getCluster().posIterator ());
for (; seqPosIt.hasNext() ; seqPosIt.next ()) {
//
// discard positions too close to the end
if (seqPosIt.get ()->maxLookahead () >= totalLength) {
currentPositions.push_back(seqPosIt.get ());
}
}
//
// now we look at all the available ways to 'extend' the node
// we work with just one assignment at a time to be memory-conservative
while (!currentPositions.empty ()) {
debug_mustbe (nextPositions.empty ());
debug_mustbe (seqCluster.empty ());
PositionIterator posIt (currentPositions.begin (), currentPositions.end ());
//
// determine current working assignment:
// it is the first position's assignment, generalized to fit
// the wildcards in the projection
{
bool shouldTryAgain;
bool assgFitsProjection;
const SeqPosition* current;
do {
Str actualPostfixSeed = (*posIt)->getSeedString (postfixLength, prefixLength);
Assignment actualPostfixAssg (actualPostfixSeed, params->langauge ().code ());
assgFitsProjection =
currentAssgPostfix.specialize(actualPostfixAssg, projectionPostfix);
current = &(*(*posIt));
posIt.next ();
shouldTryAgain = !assgFitsProjection && posIt.hasNext ();
}
while (shouldTryAgain);
if (assgFitsProjection) {
PosCluster& posCluster =
currentSeqCluster->getCreatePositions (current->sequence ());
posCluster.addPosition (current);
}
else {
debug_mustbe (!posIt.hasNext ());
}
}
//
// go over all positions left in this node
for (; posIt.hasNext() ; posIt.next ()) {
//
// the position's assignment
Assignment posAssignment (
(*posIt)->getSeedString (postfixLength, prefixLength),
params->langauge ().code ()
);
debug_mustbe (currentAssgPostfix.length () == posAssignment.length ());
if (currentAssgPostfix.contains (posAssignment)) {
/*
DLOG << Format (currentAssgPostfix)
<< " contains "
<< Format (posAssignment)
<< DLOG.EOL ();
DLOG.flush ();
*/
//
// this position fits with the current working assignment
// add it later (at the end of the loop) for efficiency
PosCluster& posCluster =
currentSeqCluster->getCreatePositions ((*posIt)->sequence ());
posCluster.addPosition (*posIt);
}
else {
//
// this position does not fit with current working assignment
// we will examine it again later
nextPositions.push_back(*posIt);
}
}
if (!currentSeqCluster->empty ()) {
//
// extend the node's assg-prefix with the current-working-assg
Assignment* completeAssignment =
new Assignment (currentAssgPrefix);
completeAssignment->addAssignmentAt (prefixLength, currentAssgPostfix);
debug_mustbe (completeAssignment->length () == projection.length ());
//
// 1. the prefixes are unique because they are unified-nodes
// 2. the postfixes are unique because we are working
// one (generalized) assignment at a time
//
// so we actually know all the positions for the complete
// (generalized) assignment right now! so we score the seed
// right here. this design is due to memory limitations.
// remember, if we had more memory, we could just have created
// a deeper preprocessor, right?
Feature_var seed_feature (new Feature);
FeatureParameters::createFeature(params,
*seed_feature,
completeAssignment,
currentSeqCluster.release(),
&projection);
params->bestFeatures ().add (seed_feature);
currentSeqCluster = new SeqCluster;
seedsFound++;
}
//
// now concentrate on those position that did not match
// any of the former working-assignments
currentPositions = nextPositions;
reserveClear (nextPositions);
} // finished with one unified-node, next one please
} // finished all nodes, bye!
return seedsFound;
}
//
// Total counts
//
int SeedSearcher::tableSearch ( boost::shared_ptr <SearchParameters> params,
const Assignment& projection)
{
debug_mustbe (projection.length () > 0);
if (projection.length () <= params->preprocessor ().maxAssignmentSize ()) {
TableSearcher::SeedVector seeds;
{
TableSearcher::Table hashTable (
params->useTotalCount (),
params->useSpecialization (),
DEFAULT_SEED_HASH_TABLE_SIZE,
params->langauge ());
createFeatureTable(seeds, hashTable, *params, projection);
}
time_t start = time (NULL), finish;
DLOG << "[Evaluating seeds: ";
DLOG.flush ();
//
// now spit out all the features...
IteratorWrapper < TableSearcher::SeedVector > featureIt (seeds.begin (), seeds.end ());
for (; featureIt.hasNext () ; featureIt.next ()) {
TableSearcher::AbstractSeed* feature = featureIt.get ();
//
// overlaps are not counted when using total-counts
// this is implemented in the score-function, no need
// to do anything here
Assignment* featureAssg;
if (params->useSpecialization ()) {
featureAssg =
safe_cast (TableSearcher::SpecializedSeed*,
feature)->releaseSpecializtion ();
}
else {
featureAssg = new Assignment (feature->assignment ());
}
Feature_var seed_feature (new Feature);
FeatureParameters::createFeature(
params,
*seed_feature,
featureAssg,
feature->releaseCluster (),
&projection);
params->bestFeatures ().add (seed_feature);
}
finish = time (NULL);
DLOG << static_cast <int>(finish - start) << " seconds.] ";
return seeds.size ();
}
else {
return extendedTableSearch (params, projection);
}
}
//
// debug: cross-reference tree-search model with prefix-tree-walk model (safer)
#if SEED_TREE_SEARCH_DEBUG
# include "DebugLog.h"
# include "persistance/TextWriter.h"
# include "persistance/StrOutputStream.h"
static void compareSeedResult (const PrefixTreePreprocessor& tree,
const Assignment& feature,
const SequenceDB::Cluster& containingFeature)
{
Preprocessor::NodeCluster nodes;
tree.add2Cluster (nodes, feature);
AutoPtr <SequenceVector> s = nodes.sequences ();
int a = s->size ();
int b = containingFeature.size ();
if (a != b) {
try {
//
// intended for use with debugger
DLOG << "Seed " << Format (feature) << " tree= " << b << " walk= " << a<< DLOG.EOL ();
DLOG.flush ();
mustfail ();
}
catch (...) {
}
}
}
#endif
| [
"aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478"
] | [
[
[
1,
909
]
]
] |
2d9b0e953f821d2fc613b9a1f0725d6f75e68c57 | dc4b6ab7b120262779e29d8b2d96109517f35551 | /resources/ResMenu.cpp | a2c41babd735f43afea69d3447aac3cc5cc0970a | [] | no_license | cnsuhao/wtlhelper9 | 92daef29b61f95f44a10e3277d8835c2dd620616 | 681df3a014fc71597e9380b0a60bd3cd23e22efe | refs/heads/master | 2021-07-17T19:59:07.143192 | 2009-05-18T14:24:48 | 2009-05-18T14:24:48 | 108,361,858 | 0 | 1 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,918 | cpp | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004 Sergey Solozhentsev
// Author: Sergey Solozhentsev e-mail: [email protected]
// Product: WTL Helper
// File: ResMenu.cpp
// Created: 16.11.2004 8:55
//
// Using this software in commercial applications requires an author
// permission. The permission will be granted to everyone excluding the cases
// when someone simply tries to resell the code.
// This file may be redistributed by any means PROVIDING it is not sold for
// profit without the authors written consent, and providing that this notice
// and the authors name is included.
// This file is provided "as is" with no expressed or implied warranty. The
// author accepts no liability if it causes any damage to you or your computer
// whatsoever.
//
////////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include ".\resmenu.h"
#include "../common.h"
CResMenu::CResMenu(void)
{
}
CResMenu::CResMenu(const CResMenu& parmenu)
{
m_ID = parmenu.m_ID;
m_String = parmenu.m_String;
m_SubMenus.Copy(parmenu.m_SubMenus);
m_vItems.Copy(parmenu.m_vItems);
}
CResMenu& CResMenu::operator =(const CResMenu& parmenu)
{
m_ID = parmenu.m_ID;
m_String = parmenu.m_String;
m_SubMenus.Copy(parmenu.m_SubMenus);
m_vItems.Copy(parmenu.m_vItems);
return *this;
}
CResMenu::~CResMenu(void)
{
}
bool CResMenu::Load(CTextFile &file)
{
int level = 0;
CString buffer;//next line
CString line;
CAtlArray<CString> Words;
while(!file.Eof())
{
CString word;
if (buffer.IsEmpty())
{
file.ReadLine(line);
}
else
{
line = buffer;
buffer.Empty();
}
CutString(line, Words);
if (Words[0] == _T("BEGIN"))
{
continue;
}
if (Words[0] == _T("END"))
{
return true;
}
if (Words[0] == _T("POPUP"))
{
CResMenu SubMenu;
SubMenu.m_String = Words[1];
if (!SubMenu.Load(file))
return false;
m_SubMenus.Add(SubMenu);
}
if (Words[0] == _T("MENUITEM"))
{
file.ReadLine(buffer);
buffer.Trim();
while (_tcsncmp(buffer, _T("MENUITEM"), 8) &&
_tcsncmp(buffer, _T("POPUP"), 5) &&
_tcsncmp(buffer, _T("BEGIN"), 5) &&
_tcsncmp(buffer, _T("END"), 3))
{
//нет ключевых слов
line += _T(" ") + buffer;
CutString(line, Words);
file.ReadLine(buffer);
buffer.Trim();
}
ResMenuItem newitem;
if (Words.GetCount() > 1)
{
newitem.m_String = Words[1];
if (newitem.m_String == _T("SEPARATOR") && Words.GetCount() == 2)
{
}
else
{
newitem.m_String.Replace(_T("\"\""), _T("\""));
newitem.m_ID = Words[2];
if (Words.GetCount() > 3)
{
newitem.m_Style = Words[3];
}
}
}
m_vItems.Add(newitem);
}
}
return false;
} | [
"free2000fly@eea8f18a-16fd-41b0-b60a-c1204a6b73d1"
] | [
[
[
1,
124
]
]
] |
a41c326228633bddcfef5e5a8fd511539ae03e4b | fca81f35295cceafd1525f0c40910bce7d4880af | /Source/EigenUnitDataManager.cpp | 683381968285fd967b8d6302fd2bd07477ad9f32 | [] | no_license | armontoubman/massexpand | b324da674cd5013ba1076865d33fc16bfac4f01f | 4daec6bd7d5799de1019e341917c1179158daaa4 | refs/heads/master | 2021-01-10T13:55:47.067590 | 2011-11-20T16:20:48 | 2011-11-20T16:20:48 | 50,496,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,113 | cpp | #include "EigenUnitDataManager.h"
#include <BWAPI.h>
#include "HighCommand.h"
#include "UnitGroup.h"
#include <boost/format.hpp>
#include "ContractManager.h"
EigenUnitDataManager::EigenUnitDataManager(HighCommand* h)
{
this->hc = h;
}
void EigenUnitDataManager::update()
{
}
void EigenUnitDataManager::onStart()
{
}
void EigenUnitDataManager::updateUnit(Unit* u)
{
}
std::string EigenUnitDataManager::chat()
{
std::string s;
s = boost::str( boost::format( "EIUDM: %d units" ) % this->unitmap.size() );
return s;
}
void EigenUnitDataManager::onUnitDiscover(Unit* u)
{
}
void EigenUnitDataManager::onUnitEvade(Unit* u)
{
}
void EigenUnitDataManager::onUnitShow(Unit* u)
{
}
void EigenUnitDataManager::onUnitHide(Unit* u)
{
}
void EigenUnitDataManager::onUnitCreate(Unit* u)
{
}
void EigenUnitDataManager::onUnitDestroy(Unit* u)
{
}
void EigenUnitDataManager::onUnitMorph(Unit* u)
{
}
void EigenUnitDataManager::onUnitRenegade(Unit* u)
{
}
bool EigenUnitDataManager::unitIsSeen(Unit* u)
{
return this->unitmap[u].seenByEnemy;
} | [
"[email protected]"
] | [
[
[
1,
69
]
]
] |
c4b43736e58a1174fef39a1f43e54784750c3ad0 | 45229380094a0c2b603616e7505cbdc4d89dfaee | /wavelets/edges_src/src/Lib/haar.cpp | 8788d71e66ac0a61bd3c20b8eb33690ea05f1b84 | [] | no_license | xcud/msrds | a71000cc096723272e5ada7229426dee5100406c | 04764859c88f5c36a757dbffc105309a27cd9c4d | refs/heads/master | 2021-01-10T01:19:35.834296 | 2011-11-04T09:26:01 | 2011-11-04T09:26:01 | 45,697,313 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,582 | cpp |
#include "stdafx.h"
#include "vec1d.h"
#include "basefwt.h"
#include "Haar.h"
//haar filter////////////////////////////////////////////////////////////////////////////////////////
// 0 1 0 1
const float Haar::tH[4] = { 0.5f, 0.5f, 0.5f, 0.5f };
// 0 1 0 1
const float Haar::tG[4] = { 0.5f, -0.5f, 0.5f, -0.5f };
//haar filter////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////constructors/destructors///////////////////////////////////////////////////////////////////
Haar::Haar() : BaseFWT2D(L"haar", tH, 4, 0, tG, 4, 0, tH, 2, 0, tG, 2, 0)
{
}
///////////////////////////////////constructors/destructors///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////transforms/////////////////////////////////////////////////////////////////////
void Haar::transrows(char** dest, char** sour, unsigned int w, unsigned int h) const
{
unsigned int w2 = w / 2;
__m64 m00FF;
m00FF.m64_u64 = 0x00FF00FF00FF00FF;
for (unsigned int y = 0; y < h; y++) {
__m64 *mlo = (__m64 *) & dest[y][0];
__m64 *mhi = (__m64 *) & dest[y][w2];
__m64 *msour = (__m64 *) & sour[y][0];
for (unsigned int k = 0; k < w2 / 8; k++) { //k<w2/8 k=8*k
__m64 even = _mm_packs_pu16(_mm_and_si64(*msour, m00FF), _mm_and_si64(*(msour + 1), m00FF)); //even coeffs
__m64 odd = _mm_packs_pu16(_mm_srli_pi16(*msour, 8), _mm_srli_pi16(*(msour + 1), 8)); //odd coeffs
addsub(even, odd, mlo++, mhi++);
msour += 2;
}
if (w2 % 8) {
for (unsigned int k = w2 - (w2 % 8); k < w2; k++) {
dest[y][k] = char(((int)sour[y][2*k] + (int)sour[y][2*k+1]) / 2);
dest[y][k+w2] = threshold(((int)sour[y][2*k] - (int)sour[y][2*k+1]) / 2);
}
}
}
_mm_empty();
}
void Haar::transcols(char** dest, char** sour, unsigned int w, unsigned int h) const
{
unsigned int h2 = h / 2;
for (unsigned int k = 0; k < h2; k++) {
__m64 *mlo = (__m64 *) & dest[k][0];
__m64 *mhi = (__m64 *) & dest[k+h2][0];
__m64 *even = (__m64 *) & sour[2*k][0];
__m64 *odd = (__m64 *) & sour[2*k+1][0];
for (unsigned int x = 0; x < w / 8; x++) {
unsigned int x8 = 8 * x;
if (x8 < w / 2) {
if ((w / 2) - (x8) >= 8)
addsub(*even, *odd, mlo, mhi);
else
addsub(*even, *odd, mlo, mhi, (w / 2) - (x8)); //skip first from LL part 10/2-4=1 [lo] o o o o * | * * * o o [hi]
} else
addsub(*even, *odd, mlo, mhi, 0); //denoise lo,hi
even++;
odd++;
mlo++;
mhi++;
}
}
_mm_empty();
//odd remainder
for (unsigned int x = w - (w % 8); x < w; x++) {
for (unsigned int k = 0; k < h2; k++) {
if (x < w / 2)
dest[k][x] = char(((int)sour[2*k][x] + (int)sour[2*k+1][x]) / 2);
else
dest[k][x] = threshold(((int)sour[2*k][x] + (int)sour[2*k+1][x]) / 2);
dest[k+h2][x] = threshold(((int)sour[2*k][x] - (int)sour[2*k+1][x]) / 2);
}
}
}
///////////////////////////////////////////////transforms/////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////synths//////////////////////////////////////////////////////////////////////////
void Haar::synthrows(char** dest, char** sour, unsigned int w, unsigned int h) const //w,h of the LO part
{
}
void Haar::synthcols(char** dest, char** sour, unsigned int w, unsigned int h) const //w,h of the LO part
{
}
//////////////////////////////////////////////synths////////////////////////////////////////////////////////////////////////// | [
"perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671"
] | [
[
[
1,
113
]
]
] |
00e9e04aef14ed92d0b8bf6299786f7a85521165 | 172e5e180659a6a7242f95a367f5a879114bc38d | /SlideList/SelectedPhotoView.h | 9c92c6b339d8c9221fdeba77cf238b80bafcc42c | [] | no_license | urere/mfcslidelist | 1e66fc1a7b34f7832f5d09d278d2dd145d30adec | 7c7eb47122c6b7c3b52a93145ec8b2d6f2476519 | refs/heads/master | 2021-01-10T02:06:44.884376 | 2008-03-27T21:25:09 | 2008-03-27T21:25:09 | 47,465,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,975 | h | #if !defined(AFX_SELECTEDPHOTOVIEW_H__EF060EED_A02B_4E89_9E6B_77A7DEE3A169__INCLUDED_)
#define AFX_SELECTEDPHOTOVIEW_H__EF060EED_A02B_4E89_9E6B_77A7DEE3A169__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// SelectedPhotoView.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CSelectedPhotoView view
class CSelectedPhotoView : public CScrollView
{
protected:
CSelectedPhotoView(); // protected constructor used by dynamic creation
DECLARE_DYNCREATE(CSelectedPhotoView)
// Attributes
public:
CSlideListDoc* GetDocument();
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSelectedPhotoView)
protected:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual void OnInitialUpdate(); // first time after construct
virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint);
//}}AFX_VIRTUAL
// Implementation
protected:
virtual ~CSelectedPhotoView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
//{{AFX_MSG(CSelectedPhotoView)
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
// Private helper functions
private:
int OutputText( CDC* pDC, LPCTSTR pLocalFontName, LPCTSTR pText, int XPos = 0 );
int OutputParagraph( CDC* pDC, LPCTSTR pLocalFontName, LPCTSTR pText, int XPos = 0, int MaxWidth = 0 );
void NewLine ( LPCTSTR pLocalFontName = NULL );
BOOL AddFont( CDC *pDC, LPCTSTR pLocalName, LPCTSTR pFaceName, int PointSize, BOOL bBold = FALSE, BOOL bItalic = FALSE, BOOL bUnderLine = FALSE );
CFont *GetFont( LPCTSTR pLocalName );
TEXTMETRIC *GetFontInfo( LPCTSTR pLocalName );
int FontsInCache( void ) { return(m_FontCache.GetCount()); };
void DeleteFontCache();
// private attributes
private:
CMapStringToOb m_FontCache; // Cache of fonts
CMapStringToPtr m_FontInfoCache; // Cache of LOGFONTS
CStringArray m_PhotoIdArray; // Array containing id's of selected photos
int m_TopMargin;
int m_BottomMargin;
int m_LeftMargin;
int m_RightMargin;
long int m_CurrentYPos;
int m_CurrentRowHeight;
long int m_FirstPhotoPosition;
long int m_LastPhotoPosition;
long int m_PhotoHeight;
};
#ifndef _DEBUG // debug version in DetailView.cpp
inline CSlideListDoc* CSelectedPhotoView::GetDocument()
{ return (CSlideListDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SELECTEDPHOTOVIEW_H__EF060EED_A02B_4E89_9E6B_77A7DEE3A169__INCLUDED_)
| [
"ratcliffe.gary@e6454d50-7149-0410-9942-4ffd99bf3498"
] | [
[
[
1,
91
]
]
] |
4b2ed04ecc6a4d2182276f2777075b63f2d4d17d | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.6/cbear.berlios.de/base/integer.hpp.test.cpp | 88730bac0c91b44e74cf7669c92587d3a55881f4 | [
"MIT"
] | permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,615 | cpp | /*
The MIT License
Copyright (c) 2005 C Bear (http://cbear.berlios.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cbear.berlios.de/base/integer.hpp>
#include <boost/test/minimal.hpp>
namespace Base = cbear_berlios_de::base;
int test_main(int, char *[])
{
/* See http://www.boost.org/libs/integer/cstdint.htm.
Base::uint_t<64>::type Q = 0x0123456789ABCDEFull;
BOOST_CHECK(Base::low(Q)==0x01234567);
BOOST_CHECK(Base::high(Q)=0x89ABCDEF);
*/
BOOST_CHECK('\1\2\3\4' == 0x01020304);
Base::uint_t<32>::type A = 0x12345678;
BOOST_CHECK(Base::low(A)==0x5678);
BOOST_CHECK(Base::high(A)==0x1234);
Base::low(A) = 0x9ABC;
Base::high(A) = 0xDEF0;
BOOST_CHECK(A == 0xDEF09ABCul);
BOOST_CHECK(Base::compose(Base::high(A), Base::low(A)) == A);
const Base::uint_t<32>::type CA = 0x12345678;
BOOST_CHECK(Base::low(CA)==0x5678);
BOOST_CHECK(Base::high(CA)==0x1234);
BOOST_CHECK(Base::compose(Base::high(CA), Base::low(CA)) == CA);
// 16 => 8, 8
Base::uint_t<16>::type B = 0x1234;
BOOST_CHECK(Base::low(B)==0x34);
BOOST_CHECK(Base::high(B)==0x12);
Base::low(B) = 0x56;
Base::high(B) = 0x78;
BOOST_CHECK(B == 0x7856);
BOOST_CHECK(Base::compose(Base::high(B), Base::low(B)) == B);
const Base::uint_t<16>::type CB = 0x1234;
BOOST_CHECK(Base::low(CB)==0x34);
BOOST_CHECK(Base::high(CB)==0x12);
BOOST_CHECK(Base::compose(Base::high(CB), Base::low(CB)) == CB);
BOOST_CHECK((Base::compose<Base::uint_t<16>::type>(
Base::uint_t<8>::type(0x12), Base::uint_t<16>::type(0x3456))==0x123456));
return 0;
}
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
] | [
[
[
1,
78
]
]
] |
1ce4de0c800fc87bc1bb0a28dada8c4c96a4faba | 99d3989754840d95b316a36759097646916a15ea | /trunk/2011_09_07_to_baoxin_gpd/ferrylibs/src/ferry/cv_geometry/PointCorrespondences.cpp | aaa9a02dd1d3ab3b8df1b51345dcd538eb6e5f66 | [] | no_license | svn2github/ferryzhouprojects | 5d75b3421a9cb8065a2de424c6c45d194aeee09c | 482ef1e6070c75f7b2c230617afe8a8df6936f30 | refs/heads/master | 2021-01-02T09:20:01.983370 | 2011-10-20T11:39:38 | 2011-10-20T11:39:38 | 11,786,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39 | cpp | #include ".\pointcorrespondences.h"
| [
"ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2"
] | [
[
[
1,
2
]
]
] |
911ac1782da4967e526fbf6a8516ffea72e4f3b6 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ogre/OgreNewt/boost/mpl/back_inserter.hpp | 17c0fd58845f17a9513390c45ad2a1a16ef0b8d8 | [] | no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | hpp |
#ifndef BOOST_MPL_BACK_INSERTER_HPP_INCLUDED
#define BOOST_MPL_BACK_INSERTER_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2003-2004
// Copyright David Abrahams 2003-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/back_inserter.hpp,v $
// $Date: 2006/04/17 23:48:05 $
// $Revision: 1.1 $
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/inserter.hpp>
namespace boost {
namespace mpl {
template<
typename Sequence
>
struct back_inserter
: inserter< Sequence,push_back<> >
{
};
}}
#endif // BOOST_MPL_BACK_INSERTER_HPP_INCLUDED
| [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
] | [
[
[
1,
34
]
]
] |
046321dc3f51c724f5746a0a2f5a00fe776f9332 | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /FileBrowse/s60/FileBrowse/inc/filebrowseapplication.h | 763004a29dce7de37c2311b5bf6610ac206534c7 | [] | 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 | 406 | h | // FileBrowseApplication.h
//
// Copyright (c) 2006 Symbian Software Ltd. All rights reserved.
//
#ifndef __FILEBROWSEAPPLICATION_H__
#define __FILEBROWSEAPPLICATION_H__
class CFileBrowseApplication : public CAknApplication
{
public:
CApaDocument* CreateDocumentL();
TUid AppDllUid() const;
IMPORT_C CApaApplication* NewApplication();
};
#endif // __FILEBROWSEAPPLICATION_H__
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
] | [
[
[
1,
19
]
]
] |
716b63075c530b45e61201edb8d342206bdabbae | 2aa5cc5456b48811b7e4dee09cd7d1b019e3f7cc | /engine/script/wrappedhelpers.hpp | 30b16f6ed807d621184085b8acca64931f8f048a | [] | no_license | tstivers/eXistenZ | eb2da9d6d58926b99495319080e13f780862fca0 | 2f5df51fb71d44c3e2689929c9249d10223f8d56 | refs/heads/master | 2021-09-02T22:50:36.733142 | 2010-11-16T06:47:24 | 2018-01-04T00:51:21 | 116,196,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,801 | hpp | #pragma once
namespace script
{
class ScriptedObject
{
public:
struct ScriptClass
{
JSClass* classDef;
JSPropertySpec* properties;
JSFunctionSpec* methods;
JSObject* prototype;
};
ScriptedObject() : m_scriptObject(NULL)
{
}
virtual ~ScriptedObject()
{
ASSERT(!m_scriptObject);
}
virtual JSObject* getScriptObject()
{
if(!m_scriptObject)
m_scriptObject = createScriptObject();
return m_scriptObject;
}
protected:
virtual JSObject* createScriptObject() { return NULL; }
virtual void destroyScriptObject() = 0;
JSObject* m_scriptObject;
};
template<typename T, typename U>
JSObject* RegisterScriptClass(ScriptEngine* engine)
{
T::m_scriptClass.prototype = JS_InitClass(
engine->GetContext(),
engine->GetGlobal(),
U::m_scriptClass.prototype,
T::m_scriptClass.classDef,
NULL,
0,
T::m_scriptClass.properties,
T::m_scriptClass.methods,
NULL,
NULL);
ASSERT(T::m_scriptClass.prototype);
return T::m_scriptClass.prototype;
}
template<typename T>
T* GetReserved(JSContext* cx, JSObject* obj, int index = 0)
{
jsval val = JSVAL_VOID;
JSBool ret = JS_GetReservedSlot(cx, obj, index, &val);
ASSERT(ret == JS_TRUE);
ASSERT(val != JSVAL_VOID);
ASSERT(JSVAL_TO_PRIVATE(val) != NULL);
return (T*)JSVAL_TO_PRIVATE(val);
}
template<typename T>
bool GetProperty(JSContext* cx, JSObject* obj, const char* name, T& value)
{
jsval v;
if(JS_GetProperty(cx, obj, name, &v) && v != JSVAL_VOID)
return jsscript::jsval_to_(cx, v, &value);
return false;
}
template<typename T>
JSBool NameGetter(JSContext *cx, JSObject *obj, jsid id, jsval *vp)
{
T* e = GetReserved<T>(cx, obj);
*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, e->getName().c_str()));
return JS_TRUE;
}
template<typename T, const std::string& (T::* prop)(void)>
JSBool StringGetter(JSContext *cx, JSObject *obj, jsid id, jsval *vp)
{
T* e = GetReserved<T>(cx, obj);
*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, (e->*prop)().c_str()));
return JS_TRUE;
}
template<typename T, typename U, U (T::* prop)(void)>
JSBool PropertyGetter(JSContext *cx, JSObject *obj, jsid id, jsval *vp)
{
T* e = GetReserved<T>(cx, obj);
*vp = jsscript::to_jsval(cx, (e->*prop)());
return JS_TRUE;
}
template<typename T, typename U, void (T::* prop)(U)>
JSBool PropertySetter(JSContext *cx, JSObject *obj, jsid id, jsval *vp)
{
T* e = GetReserved<T>(cx, obj);
boost::remove_const<boost::remove_reference<U>::type>::type val;
if(jsscript::jsval_to_(cx, *vp, &val))
{
(e->*prop)(val);
return JS_TRUE;
}
JS_ReportError(cx, "argument incorrect for property");
return JS_FALSE;
}
} | [
"[email protected]"
] | [
[
[
1,
117
]
]
] |
f529bd4c9915152a2fc97950ddf15792ede4f10b | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/array/array_sort_abstract.h | caa75b7a4a0852379db6f0a2bc70a40926ed3c10 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | athulan/cppagent | 58f078cee55b68c08297acdf04a5424c2308cfdc | 9027ec4e32647e10c38276e12bcfed526a7e27dd | refs/heads/master | 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,587 | h | // Copyright (C) 2003 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_ARRAY_SORt_ABSTRACT_
#ifdef DLIB_ARRAY_SORt_ABSTRACT_
#include "array_kernel_abstract.h"
namespace dlib
{
template <
typename array_base
>
class array_sort : public array_base
{
/*!
REQUIREMENTS ON ARRAY_BASE
- must be an implementation of array/array_kernel_abstract.h
- array_base::type must be a type with that is comparable via operator<
POINTERS AND REFERENCES
sort() may invalidate pointers and references to internal data.
WHAT THIS EXTENSION DOES FOR ARRAY
This gives an array the ability to sort its contents by calling sort().
!*/
public:
void sort (
);
/*!
ensures
- for all elements in #*this the ith element is <= the i+1 element
- #at_start() == true
throws
- std::bad_alloc or any exception thrown by T's constructor
data may be lost if sort() throws
!*/
};
template <
typename array_base
>
inline void swap (
array_sort<array_base>& a,
array_sort<array_base>& b
) { a.swap(b); }
/*!
provides a global swap function
!*/
}
#endif // DLIB_ARRAY_SORt_ABSTRACT_
| [
"jimmy@DGJ3X3B1.(none)"
] | [
[
[
1,
59
]
]
] |
274ae0e7f9b0b8d8bff1750f68c43af146d6d858 | 05f4bd87bd001ab38701ff8a71d91b198ef1cb72 | /TPTaller/TP3/test/TP3/src/Logfinal.cpp | 70fb89173423bb7bdef97ce0860387bbd460b916 | [] | no_license | oscarcp777/tpfontela | ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12 | 2489442b81dab052cf87b6dedd33cbb51c2a0a04 | refs/heads/master | 2016-09-01T18:40:21.893393 | 2011-12-03T04:26:33 | 2011-12-03T04:26:33 | 35,110,434 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,918 | cpp | #include "logfinal.h"
/* Implementación de Primitivas */
/*----------------------------------------------------------------------------*/
/*Primitiva inicializar , inicializa una estructura en que se inicializa
un archivo txt en el que despues se va a escribir y un contador que indica la
cantidad de mensajes que se estan escribiendo.
*/
void inicializarLog (Log& log, string nombreArchivo)
{
log.arch.open(nombreArchivo.c_str(),ios::out | ios::trunc);
log.contador = 0;
}
/*----------------------------------------------------------------------------*/
/*Primitiva Destruir , cierra el archivo de nuestra estructura log
y coloca el contador en cero.Borrando los rastros de nuestra pasada por log.
*/
void destruirLog (Log& log)
{
log.arch.close();
log.contador=0;
}
/*----------------------------------------------------------------------------*/
/*Primitiva escribirMensaje , se utiliza la funcion adicional para insertar la
fecha y hora en nuestra estructura, se incrementa el contador cada vez que se
llama a esta primitiva,y por ultimo graba el mensaje en el archivo de texto
*/
void escribirMensajeLog (Log& log, string mensaje)
{
log.contador+=1;
log.arch << mensaje << endl;
}
/*----------------------------------------------------------------------------*/
/*Primitiva EscribirTitulo ,Crea un Titulo en el archivo con un lindo rotulo
*/
void escribirTituloLog (Log& log, string titulo)
{
log.arch << ASTERISCOS << endl << titulo << endl <<
ASTERISCOS << endl;
}
/*----------------------------------------------------------------------------*/
/*Primitiva escribirTotalMensajes ,Inserta en nuestro archivo el total del
contador de mensajes.
*/
void escribirTotalMensajesLog (Log& log)
{
log.arch << LINEA << endl;
log.arch << TOTMENSAJES << log.contador << endl;
log.arch << LINEA << endl;
}
| [
"[email protected]@a1477896-89e5-11dd-84d8-5ff37064ad4b"
] | [
[
[
1,
50
]
]
] |
2b1673bb078f463d49932a38dc3c62b381fd227c | 8a3fce9fb893696b8e408703b62fa452feec65c5 | /GServerEngine/Public/TestAi/AI1/PlayerEntity.h | f6cbba329d7bcd7b91fff78cef7a4b12536246dd | [] | no_license | win18216001/tpgame | bb4e8b1a2f19b92ecce14a7477ce30a470faecda | d877dd51a924f1d628959c5ab638c34a671b39b2 | refs/heads/master | 2021-04-12T04:51:47.882699 | 2011-03-08T10:04:55 | 2011-03-08T10:04:55 | 42,728,291 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 426 | h | #pragma once
#include "../../State.h"
#include "../../BaseEntity.h"
class CBaseEntity;
class State;
class CPlayerEntity : public CBaseEntity
{
private:
State* m_pCurrentState;
eState m_State;
public:
CPlayerEntity( eEntityType id );
void Update();
void ChangeState( State* new_state );
void ChangeState( eState new_state );
eState GetState()const { return m_State; }
}; | [
"[email protected]"
] | [
[
[
1,
29
]
]
] |
522f9554f15310a338fa74bcd1ef137bee98f659 | c3a0cf3d0c023cbdb9a1ab8295aa1231543d83e7 | /sln/src/FbgGame.h | 72016027b08b54a9cd6497c8035e8160a68e5948 | [] | no_license | yakergong/seedcup2008 | 2596cdb5fe404ef8628366cdd2f8003141625264 | e57b92cf576900ba6cb5e0c0f6661bba3e7f75d7 | refs/heads/master | 2016-09-05T11:06:12.717346 | 2008-12-19T13:04:28 | 2008-12-19T13:04:28 | 32,268,668 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,606 | h | #ifndef FBG_GAME_H
#define FBG_GAME_H
#include "FbgBlock.h"
#include "TetrisAI.h"
#include "Logger.h"
#include "BlockFactory.h"
#include "AIModule.h"
#include <SDL/SDL.h>
#include <vector>
#include <string>
#include <physfs/physfs.h>
#include <utility>
// When line(s) have been gained
class FbgLineGain
{
public:
unsigned char lineCount; // 1-4 lines removed
short linePos[4];
short lineMatrix[4][10];
int levelGained; // Level that was attained
FbgLineGain()
{
levelGained = -1;
lineCount = 0;
linePos[0] = -1;
linePos[1] = -1;
linePos[2] = -1;
linePos[3] = -1;
}
};
enum FbgGameEvent
{
FBG_EVENT_DROP = 1,
FBG_EVENT_UNKNOWN,
};
enum FbgGameState
{
GAMEPLAY = 0,
GAMEOVER,
QUIT,
};
const bool fbgGameStatePauseMask[] = { false, true, false };
class FbgGame
{
public:
// Constructors
FbgGame(int id, bool idleMode, int startLevel, std::string mode);
// Destructor
~FbgGame();
// Event Functions
static inline void issue(const int &eventCode, FbgGame *game);
void processEvent(const SDL_Event & event);
// void gameplayLoop();
// Block Management
void finishCurBlock();
short getMatrixAt(int row, int col)
{
return matrix_[row][col];
}
FbgBlock *getCurBlock()
{
return &curBlock;
}
// Accessors
FbgLineGain *getLineGain()
{
return lineGain;
}
FbgBlock *getBlockSet(int index)
{
return &blockSet[index];
}
short getNextBlockIndex()
{
return nextBlockIndex;
}
unsigned char getLevel()
{
return level_;
}
int getLines()
{
return lines_;
}
int getTotalLines();
long getScore()
{
return score_;
}
long getTotalScore();
bool getPaused()
{
return paused;
}
void setPaused(bool newP)
{
paused = newP;
}
FbgGameState getState()
{
return state_;
}
void setState(FbgGameState newState)
{
state_ = newState;
setPaused(fbgGameStatePauseMask[newState]);
}
bool getIdleMode()
{
return isIdleMode_;
}
int getID() const
{
return id_;
}
std::string getMode() const
{
return mode_;
}
std::pair<float, float> getDestCoord() const
{
return destCoord_;
}
bool getDownHeld() const
{
return downHeld_;
}
void startNewLevel();
void setSpeedUpMode(bool speedUp)
{
speedUpMode_ = speedUp;
}
private:
int id_;
std::string mode_;
Logger log_;
Logger scoreLog_;
BlockFactory blockFactory_;
AIModule aiModule_;
int level_; // Current level
bool levelEndMark_;
bool speedUpMode_; // 是否在加速模式下运行(快速获取结果)
std::vector< int > scorePerLevel_;
std::vector< int > linesPerLevel_;
std::vector< std::vector< MoveState > > moveStates_;
// 多窗口模式下的目标位置
std::pair<float, float> destCoord_;
int newLevelPause_;
// Board-related
short matrix_[18][10]; // Game board
std::vector < FbgBlock > blockSet; // Different pieces
FbgBlock curBlock; // Needed in case we rotate/nudge
short nextBlockIndex; // Next block's type
FbgLineGain *lineGain; // If we're currently animating a line gain this will != NULL
FbgGameState state_; // The current game state
bool paused; // If gameplay is paused (ie during a line gain)
bool isIdleMode_; // 闲置模式,闲置模式下无消息则等待,非闲置模式下程序强行循环
bool downHeld_;
// Game-related
int lines_; // Number of lines removed
int score_; // Current score
// 保存操作的录像
void SaveLogFile();
// 保存分数
void SaveScoreLogFile();
// Block Management
void cycleBlocks();
void putBlockInMatrix(const FbgBlock & theBlock);
void setupBlocks();
bool getSpeedUpMode()
{
return speedUpMode_;
}
void AIMove(MoveState move);
};
#endif
| [
"yakergong@c3067968-ca50-11dd-8ca8-e3ff79f713b6"
] | [
[
[
1,
211
]
]
] |
650f627a272ab661ad6711a4023bff5fe7d7ebb3 | 8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab | /src-ginga-editing/gingancl-cpp/src/gingancl/FormatterScheduler.cpp | 3b04aa55fdb42a34ee12358db86f769f1420f746 | [] | no_license | BrunoSSts/ginga-wac | 7436a9815427a74032c9d58028394ccaac45cbf9 | ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c | refs/heads/master | 2020-05-20T22:21:33.645904 | 2011-10-17T12:34:32 | 2011-10-17T12:34:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,918 | cpp | /******************************************************************************
Este arquivo eh parte da implementacao do ambiente declarativo do middleware
Ginga (Ginga-NCL).
Direitos Autorais Reservados (c) 1989-2007 PUC-Rio/Laboratorio TeleMidia
Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob
os termos da Licen�a Publica Geral GNU versao 2 conforme publicada pela Free
Software Foundation.
Este programa eh distribu�do na expectativa de que seja util, porem, SEM
NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU
ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do
GNU versao 2 para mais detalhes.
Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto
com este programa; se nao, escreva para a Free Software Foundation, Inc., no
endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
Para maiores informacoes:
ncl @ telemidia.puc-rio.br
http://www.ncl.org.br
http://www.ginga.org.br
http://www.telemidia.puc-rio.br
******************************************************************************
This file is part of the declarative environment of middleware Ginga (Ginga-NCL)
Copyright: 1989-2007 PUC-RIO/LABORATORIO TELEMIDIA, All Rights Reserved.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License version 2 for more
details.
You should have received a copy of the GNU General Public License version 2
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
For further information contact:
ncl @ telemidia.puc-rio.br
http://www.ncl.org.br
http://www.ginga.org.br
http://www.telemidia.puc-rio.br
*******************************************************************************/
#include "../include/FormatterConverter.h"
using namespace ::br::pucrio::telemidia::ginga::ncl::converter;
#include "../include/FormatterScheduler.h"
namespace br {
namespace pucrio {
namespace telemidia {
namespace ginga {
namespace ncl {
FormatterScheduler::FormatterScheduler(
PlayerAdapterManager* playerManager,
RuleAdapter* ruleAdapter,
void* compiler) {
this->playerManager = playerManager;
this->ruleAdapter = ruleAdapter;
this->layoutManager = new FormatterLayout();
this->focusManager = new FormatterFocusManager(
this->playerManager, (FormatterConverter*)compiler);
this->schedulerListeners = new vector<FormatterSchedulerListener*>;
this->compiler = compiler;
this->documentEvents = new vector<FormatterEvent*>;
this->documentStatus = new map<FormatterEvent*, bool>;
}
FormatterScheduler::~FormatterScheduler() {
wclog << "FormatterScheduler::~FormatterScheduler" << endl;
playerManager = NULL;
ruleAdapter = NULL;
if (layoutManager != NULL) {
delete layoutManager;
layoutManager = NULL;
}
if (focusManager != NULL) {
delete focusManager;
focusManager = NULL;
}
if (schedulerListeners != NULL) {
delete schedulerListeners;
schedulerListeners = NULL;
}
compiler = NULL;
if (documentEvents != NULL) {
delete documentEvents;
documentEvents = NULL;
}
if (documentStatus != NULL) {
delete documentStatus;
documentStatus = NULL;
}
}
bool FormatterScheduler::isPriorityListener() {
return true;
}
FormatterLayout* FormatterScheduler::getLayoutManager() {
return layoutManager;
}
bool FormatterScheduler::isDocumentRunning(FormatterEvent* event) {
ExecutionObject* executionObject;
CompositeExecutionObject* parentObject;
FormatterEvent* documentEvent;
/*NodeEntity* dataObject;
NodeNesting* referPerspective;
set<ReferNode*>* sameInstances = NULL;
set<ReferNode*>::iterator i;*/
executionObject = (ExecutionObject*)(event->getExecutionObject());
/*dataObject = (NodeEntity*)(executionObject->getDataObject());
if (dataObject != NULL && dataObject->instanceOf("NodeEntity")) {
sameInstances = dataObject->getSameInstances();
if (sameInstances != NULL && !sameInstances->empty()) {
i = sameInstances->begin();
while (i != sameInstances->end()) {
referPerspective = new NodeNesting((*i)->getPerspective());
++i;
}
}
}*/
parentObject = (CompositeExecutionObject*)(executionObject->
getParentObject());
if (parentObject != NULL) {
while (parentObject->getParentObject() != NULL) {
executionObject = (ExecutionObject*)(parentObject);
parentObject = (CompositeExecutionObject*)(parentObject->
getParentObject());
}
documentEvent = executionObject->getWholeContentPresentationEvent();
} else {
documentEvent = event;
}
if (documentStatus->count(documentEvent) != 0) {
return (*documentStatus)[documentEvent];
}
return false;
}
void FormatterScheduler::setTimeBaseObject(
ExecutionObject* object,
FormatterPlayerAdapter* objectPlayer, string nodeId) {
ExecutionObject* documentObject;
ExecutionObject* parentObject;
ExecutionObject* timeBaseObject;
Node* documentNode;
Node* compositeNode;
Node* timeBaseNode;
NodeNesting* perspective;
NodeNesting* compositePerspective;
FormatterPlayerAdapter* timeBasePlayer;
wclog << "FormatterScheduler::setTimeBaseObject 1" << endl;
if (nodeId.find_last_of('#') != std::string::npos) {
return;
}
wclog << "FormatterScheduler::setTimeBaseObject 2" << endl;
documentObject = object;
parentObject = (ExecutionObject*)(documentObject->getParentObject());
if (parentObject != NULL) {
while (parentObject->getParentObject() != NULL) {
documentObject = parentObject;
if (documentObject->getDataObject()->instanceOf("ReferNode")) {
break;
}
parentObject = (ExecutionObject*)(documentObject->
getParentObject());
}
}
if (documentObject == NULL || documentObject->getDataObject() == NULL){
return;
}
wclog << "FormatterScheduler::setTimeBaseObject 3" << endl;
documentNode = documentObject->getDataObject();
if (documentNode->instanceOf("ReferNode")) {
compositeNode = (NodeEntity*)((ReferNode*)documentNode)->
getReferredEntity();
} else {
compositeNode = documentNode;
}
if (compositeNode == NULL ||
!(compositeNode->instanceOf("CompositeNode"))) {
return;
}
wclog << "FormatterScheduler::setTimeBaseObject 4" << endl;
timeBaseNode = ((CompositeNode*)compositeNode)->
recursivelyGetNode(nodeId);
if (timeBaseNode == NULL ||
!(timeBaseNode->instanceOf("ContentNode"))) {
return;
}
wclog << "FormatterScheduler::setTimeBaseObject 5" << endl;
perspective = new NodeNesting(timeBaseNode->getPerspective());
if (documentNode->instanceOf("ReferNode")) {
perspective->removeHeadNode();
compositePerspective = new NodeNesting(
documentNode->getPerspective());
compositePerspective->append(perspective);
perspective = compositePerspective;
}
wclog << "FormatterScheduler::setTimeBaseObject perspective Id = '";
wclog << perspective->getId().c_str() << "'" << endl;
try {
timeBaseObject = ((FormatterConverter*)compiler)->
getExecutionObject(
perspective,
NULL,
((FormatterConverter*)compiler)->getDepthLevel());
if (timeBaseObject != NULL) {
timeBasePlayer = playerManager->getPlayer(timeBaseObject);
if (timeBasePlayer != NULL) {
wclog << "FormatterScheduler::setTimeBaseObject setting";
wclog << " time base to '";
wclog << timeBaseObject->getId().c_str() << "'" << endl;
objectPlayer->setTimeBasePlayer(timeBasePlayer);
}
}
} catch (ObjectCreationForbiddenException* exc) {
return;
}
}
void FormatterScheduler::runAction(void* someAction) {
runAction(((LinkSimpleAction*)someAction)->getEvent(), someAction);
}
void FormatterScheduler::runAction(
FormatterEvent* event, void* someAction) {
LinkSimpleAction* action;
action = (LinkSimpleAction*)someAction;
ExecutionObject* executionObject;
CascadingDescriptor* descriptor;
FormatterPlayerAdapter* player;
NodeEntity* dataObject;
ContentAnchor* anchor;
short actionType;
string attName;
string attValue;
/*double time;
time = getCurrentTimeMillis();*/
if (event == NULL) {
cout << "FormatterScheduler::runAction Warning! Trying to ";
cout << "run a NULL event" << endl;
return;
}
executionObject = (ExecutionObject*)(event->getExecutionObject());
/*cout << "FormatterScheduler::runAction event '";
cout << event->getId() << "' for '";
cout << executionObject->getId() << "'" << endl;*/
if (isDocumentRunning(event) && !executionObject->isCompiled()) {
((FormatterConverter*)compiler)->compileExecutionObjectLinks(
executionObject,
((FormatterConverter*)compiler)->getDepthLevel());
}
dataObject = (NodeEntity*)(executionObject->getDataObject()->
getDataEntity());
if (dataObject->instanceOf("NodeEntity")) {
set<ReferNode*>* gradSame;
set<ReferNode*>::iterator i;
gradSame = ((NodeEntity*)dataObject)->getGradSameInstances();
if (gradSame != NULL) {
((FormatterConverter*)compiler)->checkGradSameInstance(
gradSame, executionObject);
cout << "FormatterScheduler::runAction refer = '";
cout << dataObject->getId() << "' perspective = '";
cout << executionObject->getNodePerspective()->
getHeadNode()->getId() << "'";
cout << endl;
}
}
if (dataObject->instanceOf("ContentNode") &&
((ContentNode*)dataObject)->getNodeType() ==
ContentNode::SETTING_NODE &&
action->instanceOf("LinkAssignmentAction") &&
event->instanceOf("AttributionEvent")) {
attName = ((AttributionEvent*)event)->getAnchor()->
getPropertyName();
attValue = ((LinkAssignmentAction*)action)->getValue();
if (attValue.substr(0, 1) == "$") {
attValue = solveImplicitRefAssessment(
attValue,
(LinkAssignmentAction*)action,
(AttributionEvent*)event);
}
event->start();
((AttributionEvent*)event)->setValue(attValue);
/*cout << "FormatterScheduler::runAction over settingnode";
cout << " evId '" << event->getId() << "' for '";
cout << executionObject->getId() << "' propName '";
cout << attName << "', propValue '" << attValue << "'" << endl;*/
if (attName == "currentFocus" ||
attName == "service.currentFocus") {
focusManager->setFocus(attValue);
} else if (attName == "currentKeyMaster" ||
attName == "service.currentKeyMaster") {
focusManager->setKeyMaster(attValue);
} else {
PresentationContext::getInstance()->setPropertyValue(
attName, attValue);
}
event->stop();
} else if (executionObject->instanceOf("ExecutionObjectSwitch") &&
event->instanceOf("SwitchEvent")) {
runActionOverSwitch(
(ExecutionObjectSwitch*)executionObject,
(SwitchEvent*)event, action);
} else if (executionObject->instanceOf("CompositeExecutionObject") &&
(executionObject->getDescriptor() == NULL ||
executionObject->getDescriptor()->getPlayerName() == "")) {
runActionOverComposition(
(CompositeExecutionObject*)executionObject, action);
} else if (event->instanceOf("AttributionEvent")) {
runActionOverProperty(event, action);
} else {
player = playerManager->getPlayer(executionObject);
if (player == NULL) {
cout << "Player = NULL for ";
cout << executionObject->getId().c_str() << endl;
return;
}
if (executionObject->instanceOf("ProceduralExecutionObject") &&
!event->instanceOf("AttributionEvent")) {
runActionOverProceduralObject(
(ProceduralExecutionObject*)executionObject,
event, player, action);
return;
}
actionType = action->getType();
switch (actionType) {
case SimpleAction::ACT_START:
//TODO: if (isDocumentRunning(event)) {
if (!player->hasPrepared()) {
if (ruleAdapter->adaptDescriptor(
executionObject)) {
descriptor = executionObject->getDescriptor();
if (descriptor != NULL) {
descriptor->setFormatterRegion(
layoutManager);
}
}
player->prepare(
executionObject,
(PresentationEvent*)event);
if (executionObject != NULL && executionObject->
getDescriptor() != NULL) {
// look for a reference time base player
attValue = executionObject->getDescriptor()->
getParameterValue("x-timeBaseObject");
if (attValue != "") {
setTimeBaseObject(
executionObject,
player,
attValue);
}
}
Surface* renderedSurface;
renderedSurface = player->getObjectDisplay();
if (renderedSurface != NULL) {
layoutManager->prepareFormatterRegion(
executionObject, renderedSurface);
}
}
event->addEventListener(this);
//time = getCurrentTimeMillis() - time;
player->start();
/*} else {
cout << "FormatterScheduler::runAction event '";
cout << event->getId() << "' for '";
cout << executionObject->getId() << "'";
cout << "is !running" << endl;
}*/
break;
case SimpleAction::ACT_PAUSE:
player->pause();
break;
case SimpleAction::ACT_RESUME:
player->resume();
break;
case SimpleAction::ACT_ABORT:
player->abort();
break;
case SimpleAction::ACT_STOP:
player->stop();
break;
}
}
}
void FormatterScheduler::runActionOverProperty(
FormatterEvent* event, LinkSimpleAction* action) {
short actionType;
string propValue;
ExecutionObject* executionObject;
FormatterPlayerAdapter* player;
Animation* anim;
anim = ((LinkAssignmentAction*)action)->getAnimation();
executionObject = (ExecutionObject*)(event->getExecutionObject());
player = playerManager->getPlayer(executionObject);
actionType = action->getType();
switch (actionType) {
case SimpleAction::ACT_START:
cout << "FormatterScheduler::runActionOverProperty";
cout << " start" << endl;
break;
case SimpleAction::ACT_PAUSE:
cout << "FormatterScheduler::runActionOverProperty";
cout << " pause" << endl;
break;
case SimpleAction::ACT_RESUME:
cout << "FormatterScheduler::runActionOverProperty";
cout << " resume" << endl;
break;
case SimpleAction::ACT_ABORT:
cout << "FormatterScheduler::runActionOverProperty";
cout << " abort" << endl;
break;
case SimpleAction::ACT_STOP:
cout << "FormatterScheduler::runActionOverProperty";
cout << " stop" << endl;
break;
case SimpleAction::ACT_SET:
/*cout << "FormatterScheduler::runActionOverProperty";
cout << " over '" << event->getId() << "' for '";
cout << executionObject->getId() << "'" << endl;*/
if (event->getCurrentState() != EventUtil::ST_SLEEPING) {
cout << "FormatterScheduler::runActionOverProperty";
cout << " trying to set an event that is not ";
cout << "sleeping: '" << event->getId() << "'" << endl;
return;
}
propValue = ((LinkAssignmentAction*)action)->getValue();
if (propValue.substr(0, 1) == "$") {
propValue = solveImplicitRefAssessment(
propValue,
(LinkAssignmentAction*)action,
(AttributionEvent*)event);
}
event->start();
((AttributionEvent*)event)->setValue(propValue);
if (player != NULL && player->hasPrepared()) {
player->setPropertyValue(
(AttributionEvent*)event, propValue, anim);
} else if (!executionObject->setPropertyValue(
(AttributionEvent*)event,
propValue, anim)) {
event->stop();
}
break;
}
}
void FormatterScheduler::runActionOverProceduralObject(
ProceduralExecutionObject* executionObject,
FormatterEvent* event,
FormatterPlayerAdapter* player,
LinkSimpleAction* action) {
CascadingDescriptor* descriptor;
string attValue, attName;
int actionType;
actionType = action->getType();
switch (actionType) {
case SimpleAction::ACT_START:
if (isDocumentRunning(event)) {
if (!player->hasPrepared()) {
if (ruleAdapter->adaptDescriptor(
executionObject)) {
descriptor = executionObject->getDescriptor();
if (descriptor != NULL) {
descriptor->setFormatterRegion(
layoutManager);
}
}
}
player->prepare(executionObject, event);
if (!player->hasPrepared()) {
if (executionObject->getDescriptor() != NULL) {
// look for a reference time base player
attValue = executionObject->getDescriptor()->
getParameterValue("x-timeBaseObject");
if (attValue != "") {
setTimeBaseObject(
executionObject,
player,
attValue);
}
}
Surface* renderedSurface;
renderedSurface = player->getObjectDisplay();
if (renderedSurface != NULL) {
layoutManager->prepareFormatterRegion(
executionObject, renderedSurface);
} else {
cout << "FormatterScheduler::runProceduralAction";
cout << " Warning! renderedSurface is NULL!";
cout << endl;
}
}
event->addEventListener(this);
((ProceduralPlayerAdapter*)player)->setCurrentEvent(event);
player->start();
}
break;
case SimpleAction::ACT_PAUSE:
((ProceduralPlayerAdapter*)player)->setCurrentEvent(event);
player->pause();
break;
case SimpleAction::ACT_RESUME:
((ProceduralPlayerAdapter*)player)->setCurrentEvent(event);
player->resume();
break;
case SimpleAction::ACT_ABORT:
((ProceduralPlayerAdapter*)player)->setCurrentEvent(event);
player->abort();
break;
case SimpleAction::ACT_STOP:
((ProceduralPlayerAdapter*)player)->setCurrentEvent(event);
player->stop();
break;
}
}
void FormatterScheduler::runActionOverComposition(
CompositeExecutionObject* compositeObject,
LinkSimpleAction* action) {
CompositeNode* compositeNode;
Port* port;
NodeNesting* compositionPerspective;
NodeNesting* perspective;
vector<ExecutionObject*>* objects;
ExecutionObject* childObject;
FormatterEvent* childEvent;
int i, size;
vector<FormatterEvent*>* events;
vector<ExecutionObject*>::iterator j;
/*cout << "Run action " << action->getType() << " over COMPOSITION ";
cout << compositeObject->getId().c_str() << endl;*/
if (action->getType() == SimpleAction::ACT_SET) {
// nothing to be done
} else if (action->getType() == SimpleAction::ACT_START) {
compositeNode = (CompositeNode*)(compositeObject->getDataObject()->
getDataEntity());
size = compositeNode->getNumPorts();
compositionPerspective = compositeObject->getNodePerspective();
events = new vector<FormatterEvent*>;
for (i = 0; i < size; i++) {
port = compositeNode->getPort(i);
perspective = compositionPerspective->copy();
perspective->append(port->getMapNodeNesting());
try {
childObject = ((FormatterConverter*)compiler)->
getExecutionObject(
perspective,
NULL,
((FormatterConverter*)compiler)->
getDepthLevel());
if (childObject != NULL && port->getEndInterfacePoint() !=
NULL && port->getEndInterfacePoint()->instanceOf(
"ContentAnchor")) {
childEvent = (PresentationEvent*)(
((FormatterConverter*)compiler)->getEvent(
childObject,
port->getEndInterfacePoint(),
EventUtil::EVT_PRESENTATION, ""));
if (childEvent != NULL) {
events->push_back(childEvent);
}
}
}
catch (ObjectCreationForbiddenException* exc) {
// keep on starting child objects
}
}
size = events->size();
for (i = 0; i < size; i++) {
runAction((*events)[i], action);
}
delete events;
events = NULL;
} else {
events = new vector<FormatterEvent*>;
objects = compositeObject->getExecutionObjects();
if (objects != NULL) {
j = objects->begin();
while (j != objects->end()) {
childObject = (*j);
childEvent = childObject->getMainEvent();
if (childEvent == NULL) {
childEvent = childObject->
getWholeContentPresentationEvent();
}
if (childEvent != NULL) {
events->push_back(childEvent);
}
++j;
}
delete objects;
objects = NULL;
}
size = events->size();
for (i = 0; i < size; i++) {
runAction((*events)[i], action);
}
delete events;
events = NULL;
}
}
void FormatterScheduler::runActionOverSwitch(
ExecutionObjectSwitch* switchObject,
SwitchEvent* event, LinkSimpleAction* action) {
ExecutionObject* selectedObject;
FormatterEvent* selectedEvent;
wclog << "Run action " << action->getType() << " over SWITCH ";
wclog << switchObject->getId().c_str() << endl;
selectedObject = switchObject->getSelectedObject();
if (selectedObject == NULL) {
selectedObject = ((FormatterConverter*)compiler)->
processExecutionObjectSwitch(switchObject);
if (selectedObject == NULL) {
return;
}
}
selectedEvent = event->getMappedEvent();
if (selectedEvent != NULL) {
runAction(selectedEvent, action);
} else {
runSwitchEvent(switchObject, event, selectedObject, action);
}
if (action->getType() == SimpleAction::ACT_STOP ||
action->getType() == SimpleAction::ACT_ABORT) {
switchObject->select(NULL);
}
}
void FormatterScheduler::runSwitchEvent(
ExecutionObjectSwitch* switchObject,
SwitchEvent* switchEvent,
ExecutionObject* selectedObject,
LinkSimpleAction* action) {
FormatterEvent* selectedEvent;
SwitchPort* switchPort;
vector<Port*>* mappings;
vector<Port*>::iterator i;
Port* mapping;
NodeNesting* nodePerspective;
ExecutionObject* endPointObject;
selectedEvent = NULL;
switchPort = (SwitchPort*)(switchEvent->getInterfacePoint());
mappings = switchPort->getPorts();
if (mappings != NULL) {
i = mappings->begin();
while (i != mappings->end()) {
mapping = *i;
if (mapping->getNode() == selectedObject->getDataObject()) {
nodePerspective = switchObject->getNodePerspective();
nodePerspective->append(mapping->getMapNodeNesting());
try {
endPointObject = ((FormatterConverter*)compiler)->
getExecutionObject(
nodePerspective,
NULL,
((FormatterConverter*)compiler)->
getDepthLevel());
if (endPointObject != NULL) {
selectedEvent = ((FormatterConverter*)compiler)->
getEvent(
endPointObject,
mapping->getEndInterfacePoint(),
switchEvent->getEventType(),
switchEvent->getKey());
}
} catch (ObjectCreationForbiddenException* exc) {
// continue
}
break;
}
++i;
}
}
if (selectedEvent != NULL) {
switchEvent->setMappedEvent(selectedEvent);
runAction(selectedEvent, action);
}
}
string FormatterScheduler::solveImplicitRefAssessment(
string propValue,
LinkAssignmentAction* action, AttributionEvent* event) {
FormatterEvent* refEvent;
ExecutionObject* refObject;
string roleId;
roleId = action->getValue();
roleId = roleId.substr(1, roleId.length());
refEvent = ((AttributionEvent*)event)->
getImplicitRefAssessmentEvent(roleId);
if (refEvent != NULL) {
propValue = ((AttributionEvent*)
refEvent)->getCurrentValue();
refObject = ((ExecutionObject*)(refEvent->getExecutionObject()));
/*cout << "FormatterScheduler::solveImplicitRefAssessment refEvent";
cout << " for '" << refObject->getId() << "' is '";
cout << refEvent->getId() << "', got '" << propValue << "'";
cout << endl;*/
return propValue;
} else {
cout << "FormatterScheduler::solveImplicitRefAssessment warning!";
cout << " refEvent not found for '" << event->getId() << "', ";
cout << " LinkAssignmentAction value is '" << action->getValue();
cout << "'" << endl;
cout << endl;
}
return "";
}
void FormatterScheduler::startEvent(FormatterEvent* event) {
LinkSimpleAction* fakeAction;
fakeAction = new LinkSimpleAction(event, SimpleAction::ACT_START);
runAction(event, fakeAction);
}
void FormatterScheduler::stopEvent(FormatterEvent* event) {
LinkSimpleAction* fakeAction;
fakeAction = new LinkSimpleAction(event, SimpleAction::ACT_STOP);
runAction(event, fakeAction);
}
void FormatterScheduler::pauseEvent(FormatterEvent* event) {
LinkSimpleAction* fakeAction;
fakeAction = new LinkSimpleAction(event, SimpleAction::ACT_PAUSE);
runAction(event, fakeAction);
}
void FormatterScheduler::resumeEvent(FormatterEvent* event) {
LinkSimpleAction* fakeAction;
fakeAction = new LinkSimpleAction(event, SimpleAction::ACT_RESUME);
runAction(event, fakeAction);
}
void FormatterScheduler::initializeDefaultSettings() {
string value;
double alfa;
value = PresentationContext::getInstance()->getPropertyValue(
PresentationContext::DEFAULT_FOCUS_BORDER_TRANSPARENCY);
if (value != "") {
alfa = stof(value);
} else {
alfa = 1;
}
int alpha;
alpha = (int)(255 * alfa);
value = PresentationContext::getInstance()->getPropertyValue(
PresentationContext::DEFAULT_FOCUS_BORDER_COLOR);
if (value != "") {
focusManager->setDefaultFocusBorderColor(new Color(value, alpha));
}
value = PresentationContext::getInstance()->getPropertyValue(
PresentationContext::DEFAULT_FOCUS_BORDER_WIDTH);
if (value != "") {
focusManager->setDefaultFocusBorderWidth((int)
stof(value));
}
value = PresentationContext::getInstance()->getPropertyValue(
PresentationContext::DEFAULT_SEL_BORDER_COLOR);
if (value != "") {
focusManager->setDefaultSelBorderColor(new Color(value, alpha));
}
}
void FormatterScheduler::initializeDocumentSettings(Node* node) {
string nodeType, value;
vector<Anchor*>* anchors;
vector<Anchor*>::iterator i;
vector<Node*>* nodes;
vector<Node*>::iterator j;
Anchor* anchor;
PropertyAnchor* attributeAnchor;
if (node->instanceOf("ContentNode")) {
nodeType = ((ContentNode*)node)->getNodeType();
if (upperCase(nodeType) ==
upperCase(ContentNode::SETTING_NODE)) {
anchors = ((ContentNode*)node)->getAnchors();
if (anchors != NULL) {
i = anchors->begin();
while (i != anchors->end()) {
anchor = (*i);
if (anchor->instanceOf("PropertyAnchor")) {
attributeAnchor = (PropertyAnchor*)anchor;
value = attributeAnchor->getPropertyValue();
if (value != "") {
PresentationContext::getInstance()->
setPropertyValue(
attributeAnchor->getPropertyName(),
value);
}
}
++i;
}
}
}
} else if (node->instanceOf("CompositeNode")) {
nodes = ((CompositeNode*)node)->getNodes();
if (nodes != NULL) {
j = nodes->begin();
while (j != nodes->end()) {
initializeDocumentSettings(*j);
++j;
}
}
} else if (node->instanceOf("ReferNode")) {
initializeDocumentSettings(
(NodeEntity*)((ReferNode*)node)->getDataEntity());
}
}
void FormatterScheduler::startDocument(
FormatterEvent* documentEvent,
vector<FormatterEvent*>* entryEvents) {
if (documentEvent == NULL || entryEvents == NULL) {
wclog << "FormatterScheduler::startDocument Warning! ";
wclog << "documentEvent == NULL || entryEvents == NULL" << endl;
return;
}
if (entryEvents->empty()) {
wclog << "FormatterScheduler::startDocument Warning! ";
wclog << "entryEvents is empty" << endl;
return;
}
vector<FormatterEvent*>::iterator it;
for (it = documentEvents->begin(); it != documentEvents->end(); ++it) {
if (*it == documentEvent) {
return;
}
}
documentEvent->addEventListener(this);
documentEvents->push_back(documentEvent);
(*documentStatus)[documentEvent] = true;
initializeDocumentSettings(((ExecutionObject*)(documentEvent->
getExecutionObject()))->getDataObject());
initializeDefaultSettings();
int i, size;
FormatterEvent* event;
size = entryEvents->size();
for (i = 0; i < size; i++) {
event = (*entryEvents)[i];
startEvent(event);
}
}
void FormatterScheduler::removeDocument(FormatterEvent* documentEvent) {
ExecutionObject* obj;
//TODO: do a better way to remove documents (see lockComposite)
obj = (ExecutionObject*)(documentEvent->getExecutionObject());
if (compiler != NULL) {
((FormatterConverter*)compiler)->removeExecutionObject(obj);
}
if (documentEvents != NULL) {
vector<FormatterEvent*>::iterator i;
for (i = documentEvents->begin();
i != documentEvents->end(); ++i) {
if (*i == documentEvent) {
documentEvents->erase(i);
break;
}
}
}
if (documentStatus != NULL) {
documentStatus->erase(documentStatus->find(documentEvent));
}
}
void FormatterScheduler::stopDocument(FormatterEvent* documentEvent) {
cout << "FormatterScheduler::stopDocument event received" << endl;
if (documentStatus->count(documentEvent) != 0) {
ExecutionObject* executionObject;
documentEvent->removeEventListener(this);
(*documentStatus)[documentEvent] = false;
executionObject = (ExecutionObject*)(documentEvent->
getExecutionObject());
if (executionObject->instanceOf("CompositeExecutionObject")) {
((CompositeExecutionObject*)executionObject)->
setAllLinksAsUncompiled(true);
}
stopEvent(documentEvent);
int i, size;
FormatterSchedulerListener* listener;
size = schedulerListeners->size();
for (i = 0; i < size; i++) {
listener = (*schedulerListeners)[i];
listener->presentationCompleted(documentEvent);
}
removeDocument(documentEvent);
}
}
void FormatterScheduler::pauseDocument(FormatterEvent* documentEvent) {
vector<FormatterEvent*>::iterator i;
for (i = documentEvents->begin(); i != documentEvents->end(); ++i) {
if (*i == documentEvent) {
(*documentStatus)[documentEvent] = false;
pauseEvent(documentEvent);
break;
}
}
}
void FormatterScheduler::resumeDocument(FormatterEvent* documentEvent) {
bool contains;
contains = false;
vector<FormatterEvent*>::iterator i;
for (i = documentEvents->begin(); i != documentEvents->end(); ++i) {
if (*i == documentEvent) {
contains = true;
break;
}
}
if (contains) {
resumeEvent(documentEvent);
(*documentStatus)[documentEvent] = true;
}
}
void FormatterScheduler::stopAllDocuments() {
int i, size;
vector<FormatterEvent*>* auxDocEventList;
FormatterEvent* documentEvent;
if (!documentEvents->empty()) {
auxDocEventList = new vector<FormatterEvent*>(*documentEvents);
size = auxDocEventList->size();
for (i = 0; i < size; i++) {
documentEvent = (*auxDocEventList)[i];
stopDocument(documentEvent);
}
auxDocEventList->clear();
delete auxDocEventList;
auxDocEventList = NULL;
}
}
void FormatterScheduler::pauseAllDocuments() {
int i, size;
FormatterEvent* documentEvent;
if (!documentEvents->empty()) {
size = documentEvents->size();
for (i = 0; i < size; i++) {
documentEvent = (*documentEvents)[i];
pauseDocument(documentEvent);
}
}
}
void FormatterScheduler::resumeAllDocuments() {
int i, size;
FormatterEvent* documentEvent;
if (!documentEvents->empty()) {
size = documentEvents->size();
for (i = 0; i < size; i++) {
documentEvent = (*documentEvents)[i];
resumeDocument(documentEvent);
}
}
}
void FormatterScheduler::eventStateChanged(
void* someEvent, short transition, short previousState) {
ExecutionObject* object;
FormatterPlayerAdapter* player;
int i, size;
FormatterSchedulerListener* listener;
FormatterEvent* event;
bool contains;
event = (FormatterEvent*)someEvent;
contains = false;
vector<FormatterEvent*>::iterator it;
for (it = documentEvents->begin(); it != documentEvents->end(); ++it) {
if (*it == event) {
contains = true;
break;
}
}
if (contains) {
switch (transition) {
case EventUtil::TR_STOPS:
case EventUtil::TR_ABORTS:
size = schedulerListeners->size();
for (i = 0; i < size; i++) {
listener = (*schedulerListeners)[i];
listener->presentationCompleted(event);
}
removeDocument(event);
break;
}
} else {
switch (transition) {
case EventUtil::TR_STARTS:
if (isDocumentRunning(event)) {
object = (ExecutionObject*)(event->
getExecutionObject());
player = playerManager->getPlayer(object);
if (player != NULL) {
layoutManager->showObject(object);
focusManager->showObject(object);
}
}
break;
case EventUtil::TR_STOPS:
if (((PresentationEvent*)event)->getRepetitions() == 0) {
event->removeEventListener(this);
object = (ExecutionObject*)(event->
getExecutionObject());
player = playerManager->getPlayer(object);
Surface* renderedSurface;
renderedSurface = player->getObjectDisplay();
if (renderedSurface != NULL) {
focusManager->hideObject(object);
layoutManager->hideObject(object);
}
}
break;
case EventUtil::TR_ABORTS:
event->removeEventListener(this);
object = (ExecutionObject*)(event->
getExecutionObject());
player = playerManager->getPlayer(object);
Surface* renderedSurface;
renderedSurface = player->getObjectDisplay();
if (renderedSurface != NULL) {
focusManager->hideObject(object);
layoutManager->hideObject(object);
}
break;
}
}
}
void FormatterScheduler::addSchedulerListener(
FormatterSchedulerListener* listener) {
bool contains;
contains = false;
vector<FormatterSchedulerListener*>::iterator i;
for (i = schedulerListeners->begin();
i != schedulerListeners->end(); ++i) {
if (*i == listener) {
contains = true;
break;
}
}
if (!contains) {
schedulerListeners->push_back(listener);
}
}
void FormatterScheduler::removeSchedulerListener(
FormatterSchedulerListener* listener) {
vector<FormatterSchedulerListener*>::iterator i;
for (i = schedulerListeners->begin();
i != schedulerListeners->end(); ++i) {
if (*i == listener) {
schedulerListeners->erase(i);
return;
}
}
}
}
}
}
}
}
| [
"[email protected]"
] | [
[
[
1,
1272
]
]
] |
c4722e7552ee080cab309564bc5c9db902eb4083 | 6a69593bdd78c65cbaeb731155c44d1ccb134802 | /programchallenge/backtrack/subset.cpp | 3510e3c6cd5577ed176891f59c8df11fceed2063 | [] | no_license | fannix/poj | 2ccf77e5ed0c1ea54602015026e17fda8107dd71 | 49b8c49a48fb67cba38bd72d7d12c103545a4511 | refs/heads/master | 2016-09-06T01:35:49.157774 | 2011-05-10T06:04:30 | 2011-05-10T06:04:30 | 1,726,476 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 338 | cpp | #include <iostream>
using namespace std;
#define N 6
bool a [N];
void print(){
for (int i = 0; i < N; i++){
if (a[i])
cout << i;
}
cout << endl;
}
void next(int d){
if (d == N){
print();
return;
}
a[d] = true;
next(d+1);
a[d] = false;
next(d+1);
}
int main(){
next(0);
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
748ff11eda835880da1b2f986af708c0487ab304 | 0cf09d7cc26a513d0b93d3f8ef6158a9c5aaf5bc | /twittle/src/twitter/twitter.cpp | a8fc8925ddf9ad836362635f02cd2dd98fcfee7f | [] | no_license | shenhuashan/Twittle | 0e276c1391c177e7586d71c607e6ca7bf17e04db | 03d3d388d5ba9d56ffcd03482ee50e0a2a5f47a1 | refs/heads/master | 2023-03-18T07:53:25.305468 | 2009-08-11T05:55:07 | 2009-08-11T05:55:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,487 | cpp | /**
* Implements the Twitter API
*
* @author Loren Segal
*/
#include <stdexcept>
#include <utility>
#include <wx/xml/xml.h>
#include "twitter/twitter_status.h"
#include "twitter/twitter_update_listener.h"
#include "twitter/twitter_feed.h"
#include "twitter/twitter_user.h"
#include "twitter/twitter.h"
#include "thread_callback.h"
#include "http/http_client.h"
using namespace std;
wxString Twitter::TwitterBaseUrl = _T("http://twitter.com/");
wxString Twitter::AccountBaseUrl = Twitter::TwitterBaseUrl + _T("account/");
wxString Twitter::StatusesBaseUrl = Twitter::TwitterBaseUrl + _T("statuses/");
wxString Twitter::PublicTimelineUrl = _T("public_timeline");
wxString Twitter::FriendsTimelineUrl = _T("friends_timeline");
wxString Twitter::UpdateStatusUrl = _T("update");
int Twitter::DefaultFeedDelay = 120;
Twitter::Twitter(const wxString& username, const wxString& password)
{
SetAuth(username, password);
}
Twitter::~Twitter()
{
// clear listeners
listeners.clear();
// end session
if (username != _T("")) {
EndSession();
}
// delete feeds
map<wxString, TwitterFeed*>::iterator it;
for (it = feeds.begin(); it != feeds.end(); ++it) {
delete it->second;
}
// delete users
map<unsigned long long, TwitterUser*>::iterator it2;
for (it2 = users.begin(); it2 != users.end(); ++it2) {
delete it2->second;
}
}
void Twitter::SetAuth(const wxString& username_, const wxString& password_)
{
username = username_;
password = password_;
}
void Twitter::SetAuth(HttpClient& http)
{
http.SetUser(username);
http.SetPassword(password);
}
bool Twitter::ResourceRequiresAuthentication(const wxString& resource) const {
if (resource == PublicTimelineUrl) {
return false;
}
return true;
}
void Twitter::RegisterUser(unsigned long long userid, TwitterUser *user)
{
users.insert(make_pair(userid, user));
}
TwitterUser* Twitter::RetrieveUser(unsigned long long userid) const
{
map<unsigned long long, TwitterUser*>::const_iterator it = users.find(userid);
return it != users.end() ? it->second : NULL;
}
void Twitter::BeginFeed(const wxString& resource, int delay)
{
TwitterFeed *feed;
map<wxString, TwitterFeed*>::iterator it;
it = feeds.find(resource);
if (it == feeds.end()) {
feed = new TwitterFeed(*this, resource);
LoadFeed(resource, feed);
}
else {
feed = it->second;
}
feed->SetDelay(delay);
feed->Start();
}
void Twitter::LoadFeed(const wxString& resource, TwitterFeed *feed)
{
feeds.insert(make_pair(resource, feed));
}
TwitterFeed* Twitter::GetFeed(const wxString& resource) const
{
std::map<wxString,TwitterFeed*>::const_iterator it = feeds.find(resource);
return it != feeds.end() ? it->second : NULL;
}
bool Twitter::UpdateStatus(const wxString& message)
{
HttpClient http;
wxString resource = UpdateStatusUrl;
if (ResourceRequiresAuthentication(resource)) {
SetAuth(http);
}
http.SetPostBuffer(_T("status=") + HttpClient::UrlEncode(message));
wxXmlDocument doc = http.GetXml(wxURL(StatusesBaseUrl + resource + _T(".xml")));
wxXmlNode root = *doc.GetRoot();
// check for errors
if (http.GetResponse() != 200) {
// TODO generate exception, use xml result
return false;
}
else if (root.GetName() == _T("hash")) {
// TODO generate twitterexception
return false;
}
else if (root.GetName() == _T("status")) {
// Add to follow feed if it exists
TwitterFeed *feed = GetFeed(FriendsTimelineUrl);
TwitterStatus status(*this, root);
if (feed && feed->AddStatus(status)) {
// notify listeners
NotifyListeners(FriendsTimelineUrl);
}
return true;
}
// TODO generate unknownexception
return false;
}
bool Twitter::VerifyCredentials(const wxString& username_, const wxString& password_) const
{
HttpClient http(username_, password_);
wxString result = http.Get(wxURL(AccountBaseUrl + _T("verify_credentials.xml")));
return (http.GetResponse() == 200) ? true : false;
}
void Twitter::EndSession() const
{
HttpClient cli(username, password);
cli.SetPostBuffer(_T(""));
cli.Get(wxURL(AccountBaseUrl + _T("end_session.xml")));
}
void Twitter::RegisterListener(TwitterUpdateListener& listener, const wxString& resource)
{
listeners.insert( make_pair(resource, &listener) );
}
void Twitter::UnregisterListener(TwitterUpdateListener& listener, const wxString& resource)
{
multimap<wxString, TwitterUpdateListener*>::iterator it;
pair<multimap<wxString, TwitterUpdateListener*>::iterator,
multimap<wxString, TwitterUpdateListener*>::iterator> range;
range = listeners.equal_range(resource);
for (it = range.first; it != range.second; ++it) {
if (it->second == &listener) {
listeners.erase(it);
break;
}
}
}
void Twitter::NotifyListeners(const wxString& resource) const
{
multimap<wxString, TwitterUpdateListener*>::const_iterator it;
pair<multimap<wxString, TwitterUpdateListener*>::const_iterator,
multimap<wxString, TwitterUpdateListener*>::const_iterator> range;
range = listeners.equal_range(resource);
for (it = range.first; it != range.second; ++it) {
it->second->TwitterUpdateReceived(*this, resource);
}
}
void Twitter::NotifyAllListeners() const
{
multimap<wxString, TwitterUpdateListener*>::const_iterator it;
for (it = listeners.begin(); it != listeners.end(); ++it) {
it->second->TwitterUpdateReceived(*this, it->first);
}
}
| [
"[email protected]"
] | [
[
[
1,
205
]
]
] |
b7031a18f1418d4bae111df823b0df2f9058ba3c | 3856c39683bdecc34190b30c6ad7d93f50dce728 | /LastProject/Source/ObjectSRT.cpp | 29e404ecca9d61c1a52785efd9e9795b5ec61be5 | [] | no_license | yoonhada/nlinelast | 7ddcc28f0b60897271e4d869f92368b22a80dd48 | 5df3b6cec296ce09e35ff0ccd166a6937ddb2157 | refs/heads/master | 2021-01-20T09:07:11.577111 | 2011-12-21T22:12:36 | 2011-12-21T22:12:36 | 34,231,967 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,299 | cpp | /**
@file I_ObjectSRT.cpp
@date 2011/09/20
@author 백경훈
@brief 오브젝트 SRT 클래스
*/
#include "StdAfx.h"
#include "ObjectSRT.h"
CObjectSRT::CObjectSRT(VOID)
{
D3DXMatrixIdentity( &m_matWorld );
m_ControlScale[0] = m_ControlScale[1] = m_ControlScale[2] = 1.0f;
ZeroMemory( m_ControlRotate, sizeof(m_ControlRotate) );
ZeroMemory( m_ControlTranslate, sizeof(m_ControlTranslate) );
}
CObjectSRT::~CObjectSRT(VOID)
{
}
VOID CObjectSRT::Calcul_MatWorld()
{
D3DXMatrixScaling( &m_matScale, m_ControlScale[0], m_ControlScale[1], m_ControlScale[2] );
D3DXMatrixRotationX( &m_matRotate[0], m_ControlRotate[0] );
D3DXMatrixRotationY( &m_matRotate[1], m_ControlRotate[1] );
D3DXMatrixRotationZ( &m_matRotate[2], m_ControlRotate[2] );
D3DXMatrixMultiply( &m_matRotate[0], &m_matRotate[0], &m_matRotate[1] );
D3DXMatrixMultiply( &m_matRotate[0], &m_matRotate[0], &m_matRotate[2] );
D3DXMatrixTranslation( &m_matTranslate, m_ControlTranslate[0], m_ControlTranslate[1], m_ControlTranslate[2] );
//m_matWorld = m_matScale * ( m_matRotate[0] * m_matRotate[1] * m_matRotate[2] ) * m_matTranslate;
D3DXMatrixMultiply( &m_matWorld, &m_matScale, &m_matRotate[0] );
D3DXMatrixMultiply( &m_matWorld, &m_matWorld, &m_matTranslate );
}
| [
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0"
] | [
[
[
1,
42
]
]
] |
8efeb890dda151d08d6b00bc6db414f30960c2c4 | a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561 | /SlonEngine/src/Database/Bullet/Bullet.cpp | 3665910a3baa6751fd97709f00b192e647fddc4a | [] | no_license | BackupTheBerlios/slon | e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6 | dc10b00c8499b5b3966492e3d2260fa658fee2f3 | refs/heads/master | 2016-08-05T09:45:23.467442 | 2011-10-28T16:19:31 | 2011-10-28T16:19:31 | 39,895,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,917 | cpp | #include "stdafx.h"
#define _DEBUG_NEW_REDEFINE_NEW 0
#include "Database/Bullet/Bullet.h"
#include "FileSystem/File.h"
#include "Physics/PhysicsManager.h"
#include "Physics/PhysicsModel.h"
#include "Physics/Bullet/BulletCommon.h"
#include "Physics/Bullet/BulletConstraint.h"
#include "Physics/Bullet/BulletDynamicsWorld.h"
#include "Physics/Bullet/BulletConstraint.h"
#include "Physics/Bullet/BulletRigidBody.h"
#include "Utility/error.hpp"
#include <bullet/Extras/Serialize/BulletWorldImporter/btBulletWorldImporter.h>
#include <bullet/LinearMath/btSerializer.h>
DECLARE_AUTO_LOGGER("Database.Bullet")
namespace slon {
namespace database {
namespace detail {
physics::physics_model_ptr BulletLoader::load(filesystem::File* file)
{/*
physics::BulletDynamicsWorld& world = *physics::currentPhysicsManager().getDynamicsWorld()->getImpl();
btDynamicsWorld* btWorld = &world.getBtDynamicsWorld();
// read file content
file->open(filesystem::File::in | filesystem::File::binary);
std::string fileContent(file->size(), ' ');
file->read( &fileContent[0], fileContent.size() );
file->close();
std::auto_ptr<btBulletWorldImporter> fileLoader( new btBulletWorldImporter( &world.getBtDynamicsWorld() ) );
if ( !fileLoader->loadFileFromMemory( (char*)fileContent.data(), fileContent.length() ) ) {
throw file_error(AUTO_LOGGER, "Can't load bullet physics file");
}
*/
// enumerate objects and add them to the scene model
physics::physics_model_ptr sceneModel(new physics::PhysicsModel);
/* for (int i = 0; i<fileLoader->getNumRigidBodies(); ++i)
{
btCollisionObject* collisionObject = fileLoader->getRigidBodyByIndex(i);
if ( btRigidBody* rigidBody = dynamic_cast<btRigidBody*>(collisionObject) )
{
physics::RigidBody::state_desc desc;
desc.mass = rigidBody->getInvMass() > 0 ? 1 / rigidBody->getInvMass() : 0;
desc.inertia = math::Vector3r( 1 / rigidBody->getInvInertiaDiagLocal().x(),
1 / rigidBody->getInvInertiaDiagLocal().y(),
1 / rigidBody->getInvInertiaDiagLocal().z() );
btTransform transform;
if ( rigidBody->getMotionState() ) {
rigidBody->getMotionState()->getWorldTransform(transform);
}
else {
transform = rigidBody->getWorldTransform();
}
desc.transform = physics::to_mat( transform );
desc.angularVelocity = physics::to_vec( rigidBody->getAngularVelocity() );
desc.linearVelocity = physics::to_vec( rigidBody->getLinearVelocity() );
if (rigidBody->getCollisionFlags() & btCollisionObject::CF_KINEMATIC_OBJECT) {
desc.type = physics::RigidBody::DT_KINEMATIC;
}
else if (rigidBody->getCollisionFlags() & btCollisionObject::CF_STATIC_OBJECT) {
desc.type = physics::RigidBody::DT_STATIC;
}
else {
desc.type = physics::RigidBody::DT_DYNAMIC;
}
desc.collisionShape = physics::createCollisionShape( *rigidBody->getCollisionShape() );
sceneModel->addCollisionObject( new physics::RigidBody(desc), fileLoader->getNameForPointer(rigidBody) );
}
}
// enumerate constraints and add them to the scene
for (int i = 0; i<fileLoader->getNumConstraints(); ++i)
{
boost::scoped_ptr<btTypedConstraint> constraint( fileLoader->getConstraintByIndex(i) );
switch ( constraint->getObjectType() )
{
case HINGE_CONSTRAINT_TYPE:
{
btHingeConstraint* hConstraint = static_cast<btHingeConstraint*>(constraint.get());
physics::Constraint::state_desc desc;
desc.rigidBodies[0] = reinterpret_cast<physics::BulletRigidBody*>(hConstraint->getRigidBodyA().getUserPointer())->getInterface();
desc.rigidBodies[1] = reinterpret_cast<physics::BulletRigidBody*>(hConstraint->getRigidBodyB().getUserPointer())->getInterface();
desc.frames[0] = physics::to_mat( hConstraint->getAFrame() );
desc.frames[1] = physics::to_mat( hConstraint->getBFrame() );
desc.linearLimits[0] = math::Vector3r(0);
desc.linearLimits[1] = math::Vector3r(0);
desc.angularLimits[0] = math::Vector3r( 0, 0, hConstraint->getLowerLimit() );
desc.angularLimits[1] = math::Vector3r( 0, 0, hConstraint->getUpperLimit() );
desc.name = fileLoader->getNameForPointer(hConstraint);
btWorld->removeConstraint( hConstraint );
sceneModel->addConstraint( new physics::Constraint(desc) );
break;
}
case CONETWIST_CONSTRAINT_TYPE:
{
btConeTwistConstraint* ctConstraint = static_cast<btConeTwistConstraint*>(constraint.get());
physics::Constraint::state_desc desc;
desc.rigidBodies[0] = reinterpret_cast<physics::BulletRigidBody*>(ctConstraint->getRigidBodyA().getUserPointer())->getInterface();
desc.rigidBodies[1] = reinterpret_cast<physics::BulletRigidBody*>(ctConstraint->getRigidBodyB().getUserPointer())->getInterface();
desc.frames[0] = physics::to_mat( ctConstraint->getAFrame() );
desc.frames[1] = physics::to_mat( ctConstraint->getBFrame() );
desc.linearLimits[0] = math::Vector3r(0);
desc.linearLimits[1] = math::Vector3r(0);
desc.angularLimits[0] = math::Vector3r( -ctConstraint->getTwistSpan(), -ctConstraint->getSwingSpan1(), -ctConstraint->getSwingSpan2() );
desc.angularLimits[1] = -desc.angularLimits[0];
desc.name = fileLoader->getNameForPointer(ctConstraint);
btWorld->removeConstraint( ctConstraint );
sceneModel->addConstraint( new physics::Constraint(desc) );
break;
}
case D6_CONSTRAINT_TYPE:
{
btGeneric6DofConstraint* gConstraint = static_cast<btGeneric6DofConstraint*>(constraint.get());
physics::Constraint::state_desc desc;
desc.rigidBodies[0] = reinterpret_cast<physics::BulletRigidBody*>(gConstraint->getRigidBodyA().getUserPointer())->getInterface();
desc.rigidBodies[1] = reinterpret_cast<physics::BulletRigidBody*>(gConstraint->getRigidBodyB().getUserPointer())->getInterface();
desc.frames[0] = physics::to_mat( gConstraint->getFrameOffsetA() );
desc.frames[1] = physics::to_mat( gConstraint->getFrameOffsetB() );
desc.linearLimits[0] = to_vec(gConstraint->getTranslationalLimitMotor()->m_lowerLimit);
desc.linearLimits[1] = to_vec(gConstraint->getTranslationalLimitMotor()->m_upperLimit);
desc.angularLimits[0] = math::Vector3r(gConstraint->getRotationalLimitMotor(0)->m_loLimit,
gConstraint->getRotationalLimitMotor(1)->m_loLimit,
gConstraint->getRotationalLimitMotor(2)->m_loLimit);
desc.angularLimits[1] = math::Vector3r(gConstraint->getRotationalLimitMotor(0)->m_hiLimit,
gConstraint->getRotationalLimitMotor(1)->m_hiLimit,
gConstraint->getRotationalLimitMotor(2)->m_hiLimit);
desc.name = fileLoader->getNameForPointer(gConstraint);
btWorld->removeConstraint( gConstraint );
sceneModel->addConstraint( new physics::Constraint(desc) );
break;
}
default:
AUTO_LOGGER_MESSAGE(log::S_ERROR, "Unsupported constraint type. Skipping '" << fileLoader->getNameForPointer(constraint.get()) << "'");
btWorld->removeConstraint( constraint.get() );
break;
};
}*/
return sceneModel;
}
void BulletSaver::save(physics::physics_model_ptr model, filesystem::File* file)
{
using namespace physics;
btDefaultSerializer* btSerializer = new btDefaultSerializer(1024*1024*5);
/*
btSerializer->startSerialization();
{
// serialize collision shapes
std::set<btCollisionShape*> serializedShapes;
for (PhysicsModel::collision_object_iterator iter = model->firstCollisionObject();
iter != model->endCollisionObject();
++iter)
{
BulletRigidBody& rigidBody = *static_cast<physics::RigidBody*>(iter->first.get())->getImpl();
btRigidBody& btRB = rigidBody.getBtRigidBody();
btCollisionShape* btShape = btRB.getCollisionShape();
if (serializedShapes.count(btShape) == 0)
{
serializedShapes.insert(btShape);
btSerializer->registerNameForPointer(btShape, iter->second.c_str());
btShape->serializeSingleShape(btSerializer);
}
}
// serialize rigid bodies
for (PhysicsModel::collision_object_iterator iter = model->firstCollisionObject();
iter != model->endCollisionObject();
++iter)
{
btRigidBody& btRB = static_cast<physics::RigidBody*>(iter->first.get())->getImpl()->getBtRigidBody();
btChunk* chunk = btSerializer->allocate(btRB.calculateSerializeBufferSize(), 1);
const char* structType = btRB.serialize(chunk->m_oldPtr, btSerializer);
btSerializer->finalizeChunk(chunk, structType, BT_RIGIDBODY_CODE, &btRB);
}
// serialize constraints
for (PhysicsModel::constraint_iterator iter = model->firstConstraint();
iter != model->endConstraint();
++iter)
{
btGeneric6DofConstraint& btConstraint = static_cast<BulletConstraint&>(*(*iter)->getImpl()).getBtConstraint();
btChunk* chunk = btSerializer->allocate(btConstraint.calculateSerializeBufferSize(), 1);
const char* structType = btConstraint.serialize(chunk->m_oldPtr, btSerializer);
btSerializer->finalizeChunk(chunk, structType, BT_CONSTRAINT_CODE, &btConstraint);
}
}
btSerializer->finishSerialization();
*/
if ( file->open(filesystem::File::out | filesystem::File::binary) )
{
file->write((const char*)btSerializer->getBufferPointer(), btSerializer->getCurrentBufferSize());
file->close();
}
}
} // namespace detail
} // namespace database
} // namespace slon
| [
"devnull@localhost",
"DikobrAz@DikobrAz-PC"
] | [
[
[
1,
21
],
[
23,
27
],
[
32,
33
],
[
35,
154
],
[
156,
205
],
[
211,
215
]
],
[
[
22,
22
],
[
28,
31
],
[
34,
34
],
[
155,
155
],
[
206,
210
]
]
] |
f7917cf798a271a0f7955988ef526e27c436547f | 205069c97095da8f15e45cede1525f384ba6efd2 | /Casino/Code/Server/GameModule/P_Common/VideoPokerTableFrameSink.h | f604f83be82fb4aa26c89e8e120ac8f954803524 | [] | no_license | m0o0m/01technology | 1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea | 5e04cbfa79b7e3cf6d07121273b3272f441c2a99 | refs/heads/master | 2021-01-17T22:12:26.467196 | 2010-01-05T06:39:11 | 2010-01-05T06:39:11 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 235 | h | #pragma once
#include "BaseTableFrameSink.h"
//电动扑克游戏桌子基础类
class CVideoPokerTableFrameSink:public CBaseTableFrameSink
{
public:
CVideoPokerTableFrameSink(void);
~CVideoPokerTableFrameSink(void);
};
| [
"[email protected]"
] | [
[
[
1,
11
]
]
] |
aff376eb687d1cecde317d4cb02800a481ac5d5a | df96cbce59e3597f2aecc99ae123311abe7fce94 | /dom/generated_dom/not_implemented/js_html2_HTMLSelectElement.cpp | a54a64fa38f0367b196ea77c3c7f6d01c917c4d4 | [] | no_license | abhishekbhalani/webapptools | f08b9f62437c81e0682497923d444020d7b319a2 | 93b6034e0a9e314716e072eb6d3379d92014f25a | refs/heads/master | 2021-01-22T17:58:00.860044 | 2011-12-14T10:54:11 | 2011-12-14T10:54:11 | 40,562,019 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 736 | cpp |
/*
DO NOT EDIT!
This file has been generated by generate_sources.py script.
$Id$
*/
#include "precomp.h"
using namespace v8;
void js_html2_HTMLSelectElement::add(v8::Handle<v8::Value> val_element, v8::Handle<v8::Value> val_before)
{
html2::HTMLSelectElement::add(val_element, val_before);
}
void js_html2_HTMLSelectElement::remove(long int val_index)
{
html2::HTMLSelectElement::remove(val_index);
}
void js_html2_HTMLSelectElement::blur()
{
html2::HTMLSelectElement::blur();
}
void js_html2_HTMLSelectElement::focus()
{
html2::HTMLSelectElement::focus();
}
js_html2_HTMLSelectElement::js_html2_HTMLSelectElement() {}
js_html2_HTMLSelectElement::~js_html2_HTMLSelectElement() {}
| [
"stinger911@79c36d58-6562-11de-a3c1-4985b5740c72"
] | [
[
[
1,
30
]
]
] |
47c7e9b211e6d126783e7c0fbe3d1db071480dd3 | 58496be10ead81e2531e995f7d66017ffdfc6897 | /Sources/Common/iStreamFileImpl.cpp | b354c38ffdd8cb04dd5ad6848bfc0775b115e1c2 | [] | no_license | Diego160289/cross-fw | ba36fc6c3e3402b2fff940342315596e0365d9dd | 532286667b0fd05c9b7f990945f42279bac74543 | refs/heads/master | 2021-01-10T19:23:43.622578 | 2011-01-09T14:54:12 | 2011-01-09T14:54:12 | 38,457,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,893 | cpp | //============================================================================
// Date : 22.12.2010
// Author : Tkachenko Dmitry
// Copyright : (c) Tkachenko Dmitry ([email protected])
//============================================================================
#include "IStreamFileImpl.h"
namespace IFacesImpl
{
IStreamFileImpl::IStreamFileImpl()
{
}
IStreamFileImpl::~IStreamFileImpl()
{
}
RetCode IStreamFileImpl::GetSize(unsigned long *size) const
{
if (!size)
return retBadParam;
Common::ISyncObject Locker(GetSynObj());
if (!File.Get())
return retFail;
try
{
*size = File->GetSize();
}
catch (std::exception &)
{
return retFail;
}
return retOk;
}
RetCode IStreamFileImpl::Read(void *buf, unsigned long bufSize, unsigned long *readBytes)
{
if (!readBytes)
return retBadParam;
Common::ISyncObject Locker(GetSynObj());
if (!File.Get())
return retFail;
try
{
*readBytes = File->Read(buf, bufSize);
}
catch (std::exception &)
{
return retFail;
}
return retOk;
}
RetCode IStreamFileImpl::Write(const void *buf, unsigned long bytes)
{
Common::ISyncObject Locker(GetSynObj());
if (!File.Get())
return retFail;
try
{
const char *Buf = reinterpret_cast<const char *>(buf);
for (unsigned long i = bytes ; i ; )
{
unsigned long WriteBytes = File->Write(&Buf[bytes - i], i);
if (!WriteBytes)
return retFalse;
i -= WriteBytes;
}
}
catch (std::exception &)
{
return retFail;
}
return retOk;
}
RetCode IStreamFileImpl::SeekToBegin()
{
Common::ISyncObject Locker(GetSynObj());
if (!File.Get())
return retFail;
try
{
File->SeekToBegin();
}
catch (std::exception &)
{
return retFail;
}
return retOk;
}
RetCode IStreamFileImpl::SeekToEnd()
{
Common::ISyncObject Locker(GetSynObj());
if (!File.Get())
return retFail;
try
{
File->SeekToEnd();
}
catch (std::exception &)
{
return retFail;
}
return retOk;
}
RetCode IStreamFileImpl::SeekTo(unsigned long pos)
{
Common::ISyncObject Locker(GetSynObj());
if (!File.Get())
return retFail;
try
{
File->SeekTo(pos);
}
catch (std::exception &)
{
return retFail;
}
return retOk;
}
RetCode IStreamFileImpl::GetPos(unsigned long *pos) const
{
if (!pos)
return retBadParam;
Common::ISyncObject Locker(GetSynObj());
if (!File.Get())
return retFail;
try
{
*pos = File->GetPos();
}
catch (std::exception &)
{
return retFail;
}
return retOk;
}
RetCode IStreamFileImpl::CopyTo(IStream *dest) const
{
Common::ISyncObject Locker(GetSynObj());
if (!File.Get())
return retFail;
Common::RefObjPtr<IFaces::IStream> Dest(dest);
if (!Dest.Get())
return retFail;
try
{
unsigned long FileSize = File->GetSize();
if (!FileSize)
return retOk;
unsigned long CurPos = File->GetPos();
File->SeekToBegin();
const unsigned long MaxBufSize = 32 * 1024 * 1024;
unsigned long BufSize = MaxBufSize > FileSize ? FileSize : MaxBufSize;
std::vector<char> Buf(BufSize, 0);
for (unsigned long i = File->Read(&Buf[0], BufSize) ; i ; i = File->Read(&Buf[0], BufSize))
{
if (Dest->Write(&Buf[0], i) != retOk)
return retFail;
}
File->SeekTo(CurPos);
}
catch (std::exception &)
{
return retFail;
}
return retOk;
}
void IStreamFileImpl::Init(const std::string &name, bool isNew)
{
if (name.empty())
throw IStreamFileImplException("Emptuy file name");
if (!isNew)
System::File(name.c_str(), System::File::fmRead);
File = new System::File(name.c_str(), System::File::fmReadWrite);
}
Common::RefObjPtr<IStreamFileImpl>
OpenFileStream(const std::string &name, bool createNew, const Common::ISynObj &syn)
{
Common::RefObjPtr<IStreamFileImpl> Ret =
Common::IBaseImpl<IStreamFileImpl>::CreateWithSyn(syn);
Ret->Init(name, createNew);
return Ret;
}
Common::RefObjPtr<IFaces::IRawDataBuffer>
LoadFileToBuffer(const std::string &fileName, const Common::ISynObj &syn)
{
Common::RefObjPtr<IFaces::IStream> Stream(OpenFileStream(fileName, false, syn));
Common::RefObjPtr<IFaces::IStream> Ret(OpenMemoryStream(syn));
IStreamHelper(Stream).CopyTo(Ret);
return Common::RefObjQIPtr<IFaces::IRawDataBuffer>(Ret);
}
}
| [
"TkachenkoDmitryV@d548627a-540d-11de-936b-e9512c4d2277"
] | [
[
[
1,
207
]
]
] |
6e22985e897c13e525c1e6f912e33d0a6cee416e | 105cc69f4207a288be06fd7af7633787c3f3efb5 | /HovercraftUniverse/CoreEngine/BasicGameState.cpp | 6280d460d57d0040caaaa9299db2ba0a597a6381 | [] | 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 | 547 | cpp | #include "BasicGameState.h"
namespace HovUni {
BasicGameState::BasicGameState() {
mGUIManager = GUIManager::getSingletonPtr();
mSoundManager = SoundManager::getSingletonPtr();
mInputManager = InputManager::getSingletonPtr();
}
void BasicGameState::onActivate() {
}
void BasicGameState::onDisable() {
}
void BasicGameState::setManager(GameStateManager* manager) {
mManager = manager;
}
void BasicGameState::switchGameState(GameStateManager::GameState state) {
mManager->switchState(state);
}
} | [
"nick.defrangh@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c"
] | [
[
[
1,
25
]
]
] |
e4f2f9d0fa2e665558e9968293c84eede9693db9 | f96efcf47a7b6a617b5b08f83924c7384dcf98eb | /tags/rvp_0_0_1_6/httplib/HTTPLib.cpp | b15529ff5c553dd7f82bbe8c7235095e3d434f40 | [] | no_license | BackupTheBerlios/mtlen-svn | 0b4e7c53842914416ed3f6b1fa02c3f1623cac44 | f0ea6f0cec85e9ed537b89f7d28f75b1dc108554 | refs/heads/master | 2020-12-03T19:37:37.828462 | 2011-12-07T20:02:16 | 2011-12-07T20:02:16 | 40,800,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,244 | cpp | /*
RVP Protocol Plugin for Miranda IM
Copyright (C) 2005 Piotr Piastucki
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 "HTTPLib.h"
#include "../Utils.h"
#include "MD5.h"
#include "../JLogger.h"
static JLogger *logger = new JLogger("h:/httplib.log");
static PSecurityFunctionTable pSecurityFunctions=NULL;
static HINSTANCE hInstSecurityDll=LoadLibrary("security.dll");
HANDLE HTTPConnection::hNetlibUser;
HTTPConnection::HTTPConnection() {
eof = false;
bufferPos = 0;
bufferLen = 0;
socket = NULL;
}
HTTPConnection::HTTPConnection(HANDLE socket) {
eof = false;
bufferPos = 0;
bufferLen = 0;
this->socket = socket;
}
HTTPConnection::HTTPConnection(const char *host, int port) {
eof = false;
bufferPos = 0;
bufferLen = 0;
socket = connect(host, port);
}
HTTPConnection::~HTTPConnection() {
if (socket != NULL) {
Netlib_CloseHandle(socket);
}
}
void HTTPConnection::release() {
if (hNetlibUser!=NULL) Netlib_CloseHandle(hNetlibUser);
}
bool HTTPConnection::init(const char * protoName, const char *moduleName) {
NETLIBUSER nlu = {0};
NETLIBUSERSETTINGS nlus = {0};
char name[256];
sprintf(name, "%s %s", moduleName, Translate("connection"));
nlu.cbSize = sizeof(nlu);
nlu.flags = NUF_OUTGOING | NUF_INCOMING | NUF_HTTPCONNS; // | NUF_HTTPGATEWAY;
nlu.szDescriptiveName = name;
nlu.szSettingsModule = (char *)protoName;
hNetlibUser = (HANDLE) CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM) &nlu);
return (hNetlibUser!=NULL)?true:false;
}
HANDLE HTTPConnection::connect(const char *host, int port) {
NETLIBOPENCONNECTION nloc;
nloc.cbSize = NETLIBOPENCONNECTION_V1_SIZE;//sizeof(NETLIBOPENCONNECTION);
nloc.szHost = host;
nloc.wPort = port;
nloc.flags = 0;
return (HANDLE) CallService(MS_NETLIB_OPENCONNECTION, (WPARAM) hNetlibUser, (LPARAM) &nloc);
}
HANDLE HTTPConnection::bind(NETLIBBIND *nlb) {
return (HANDLE) CallService(MS_NETLIB_BINDPORT, (WPARAM) hNetlibUser, (LPARAM) nlb);
}
int HTTPConnection::recv(char *data, long datalen) {
int totalret = 0;
while (datalen>0) {
if (bufferLen==0) {
bufferLen = Netlib_Recv(socket, buffer, 1024, MSG_DUMPASTEXT);
if(bufferLen == SOCKET_ERROR) {
eof = true;
return 0;
}
if(bufferLen == 0) {
eof = true;
return 0;
}
bufferPos = 0;
}
int ret = min(bufferLen, datalen);
memcpy (data, buffer+bufferPos, ret);
data += ret;
bufferPos += ret;
bufferLen -= ret;
datalen -= ret;
totalret += ret;
}
return totalret;
}
int HTTPConnection::send(const char *data, long datalen) {
int len;
if ((len=Netlib_Send(socket, data, datalen, /*MSG_NODUMP|*/MSG_DUMPASTEXT))==SOCKET_ERROR || len!=datalen) {
return FALSE;
}
return TRUE;
}
HTTPCredentials::HTTPCredentials() {
domain = NULL;
username = NULL;
password = NULL;
flags = 0;
}
HTTPCredentials::HTTPCredentials(const char *domain, const char *username, const char *password, int flags) {
this->domain = Utils::dupString(domain);
this->username = Utils::dupString(username);
this->password = Utils::dupString(password);
this->flags = flags;
}
HTTPCredentials::~HTTPCredentials() {
if (domain!=NULL) delete domain;
if (username!=NULL) delete username;
if (password!=NULL) delete password;
}
void HTTPCredentials::setDomain(const char *s) {
if (this->domain!=NULL) delete this->domain;
this->domain = Utils::dupString(s);
}
const char *HTTPCredentials::getDomain() {
return domain;
}
void HTTPCredentials::setUsername(const char *s) {
if (this->username!=NULL) delete this->username;
this->username = Utils::dupString(s);
}
const char *HTTPCredentials::getUsername() {
return username;
}
void HTTPCredentials::setPassword(const char *s) {
if (this->password!=NULL) delete this->password;
this->password = Utils::dupString(s);
}
const char *HTTPCredentials::getPassword() {
return password;
}
void HTTPCredentials::setFlags(int f) {
flags = f;
}
int HTTPCredentials::getFlags() {
return flags;
}
HTTPHeader::HTTPHeader(const char *name, const char *value) {
this->name = Utils::dupString(name);
this->value = Utils::dupString(value);
this->next = NULL;
}
HTTPHeader::~HTTPHeader() {
if (name!=NULL) delete name;
if (value!=NULL) delete value;
if (next!=NULL) delete next;
}
const char *HTTPHeader::getName() {
return name;
}
const char *HTTPHeader::getValue() {
return value;
}
HTTPHeader * HTTPHeader::getAttributes(int offset) {
HTTPHeader *attributes = NULL;
int l, j, pos[2];
char *vc = Utils::dupString(value);
l = strlen(vc);
pos[0]=offset;
j = 1;
for (;offset<l+1;offset++) {
if ((vc[offset]==',' || vc[offset]=='\0') && j==2) {
vc[offset]='\0';
Utils::trim(vc+pos[0], " \t\"");
Utils::trim(vc+pos[1], " \t\"");
HTTPHeader *attribute = new HTTPHeader(vc+pos[0], vc+pos[1]);
attribute->next = attributes;
attributes = attribute;
pos[0]=offset+1;
j=1;
}
if (vc[offset]=='=' && j==1) {
vc[offset]='\0';
pos[j++]=offset+1;
}
}
delete vc;
return attributes;
}
HTTPHeader * HTTPHeader::get(const char *name) {
for (HTTPHeader *ptr=this;ptr!=NULL;ptr=ptr->next) {
if (!strcmp(ptr->name, name)) return ptr;
}
return NULL;
}
//free() the return value
void HTTPRequest::NtlmDestroy() {
if (pSecurityFunctions)
{
pSecurityFunctions->DeleteSecurityContext(&hNtlmClientContext);
pSecurityFunctions->FreeCredentialsHandle(&hNtlmClientCredential);
} //if
if(ntlmSecurityPackageInfo) pSecurityFunctions->FreeContextBuffer(ntlmSecurityPackageInfo);
ntlmSecurityPackageInfo=NULL;
}
char *HTTPRequest::NtlmInitialiseAndGetDomainPacket(HINSTANCE hInstSecurityDll) {
PSecurityFunctionTable (*MyInitSecurityInterface)(VOID);
SECURITY_STATUS securityStatus;
SecBufferDesc outputBufferDescriptor;
SecBuffer outputSecurityToken;
TimeStamp tokenExpiration;
ULONG contextAttributes;
SEC_WINNT_AUTH_IDENTITY authIdentity;
MyInitSecurityInterface=(PSecurityFunctionTable (*)(VOID))GetProcAddress(hInstSecurityDll,SECURITY_ENTRYPOINT);
if(MyInitSecurityInterface==NULL) {NtlmDestroy(); return NULL;}
pSecurityFunctions=MyInitSecurityInterface();
if(pSecurityFunctions==NULL) {NtlmDestroy(); return NULL;}
securityStatus=pSecurityFunctions->QuerySecurityPackageInfo("NTLM",&ntlmSecurityPackageInfo);
if(securityStatus!=SEC_E_OK) {NtlmDestroy(); return NULL;}
if (getCredentials()->getFlags() & HTTPCredentials::FLAG_MANUAL_NTLM) {
/* use specified credentials */
memset((void *)&authIdentity, 0, sizeof(authIdentity));
authIdentity.Domain = (unsigned char *) getCredentials()->getDomain();
authIdentity.DomainLength = strlen((char *)authIdentity.Domain);
authIdentity.User = (unsigned char *) getCredentials()->getUsername();
authIdentity.UserLength = strlen((char *)authIdentity.User);
authIdentity.Password = (unsigned char *) getCredentials()->getPassword();
authIdentity.PasswordLength = strlen((char *)authIdentity.Password);
authIdentity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
securityStatus=pSecurityFunctions->AcquireCredentialsHandle(NULL,"NTLM",SECPKG_CRED_OUTBOUND,NULL,&authIdentity,NULL,NULL,&hNtlmClientCredential,&tokenExpiration);
} else {
/* use default credentials */
securityStatus=pSecurityFunctions->AcquireCredentialsHandle(NULL,"NTLM",SECPKG_CRED_OUTBOUND,NULL,NULL,NULL,NULL,&hNtlmClientCredential,&tokenExpiration);
}
if(securityStatus!=SEC_E_OK) {NtlmDestroy(); return NULL;}
outputBufferDescriptor.cBuffers=1;
outputBufferDescriptor.pBuffers=&outputSecurityToken;
outputBufferDescriptor.ulVersion=SECBUFFER_VERSION;
outputSecurityToken.BufferType=SECBUFFER_TOKEN;
outputSecurityToken.cbBuffer=ntlmSecurityPackageInfo->cbMaxToken;
outputSecurityToken.pvBuffer=malloc(outputSecurityToken.cbBuffer);
if(outputSecurityToken.pvBuffer==NULL) {NtlmDestroy(); SetLastError(ERROR_OUTOFMEMORY); return NULL;}
securityStatus=pSecurityFunctions->InitializeSecurityContext(&hNtlmClientCredential,NULL,NULL,0,0,SECURITY_NATIVE_DREP,NULL,0,&hNtlmClientContext,&outputBufferDescriptor,&contextAttributes,&tokenExpiration);
if(securityStatus<0) {free(outputSecurityToken.pvBuffer); NtlmDestroy(); return NULL;}
if (securityStatus==SEC_I_COMPLETE_NEEDED || securityStatus==SEC_I_COMPLETE_AND_CONTINUE) {
securityStatus=pSecurityFunctions->CompleteAuthToken(&hNtlmClientContext,&outputBufferDescriptor);
if(securityStatus<0) {free(outputSecurityToken.pvBuffer); NtlmDestroy(); return NULL;}
}
char *base64Encoded = Utils::base64Encode((char *)outputSecurityToken.pvBuffer, outputSecurityToken.cbBuffer);
if(base64Encoded==NULL) {free(outputSecurityToken.pvBuffer); NtlmDestroy(); return NULL;}
free(outputSecurityToken.pvBuffer);
return base64Encoded;
}
char *HTTPRequest::NtlmCreateResponseFromChallenge(char *szChallenge) {
SECURITY_STATUS securityStatus;
SecBufferDesc outputBufferDescriptor,inputBufferDescriptor;
SecBuffer outputSecurityToken,inputSecurityToken;
TimeStamp tokenExpiration;
ULONG contextAttributes;
int base64DecodedLen;
char *base64Decoded = Utils::base64Decode(szChallenge, &base64DecodedLen);
if(base64Decoded==NULL) {return NULL;}
inputBufferDescriptor.cBuffers=1;
inputBufferDescriptor.pBuffers=&inputSecurityToken;
inputBufferDescriptor.ulVersion=SECBUFFER_VERSION;
inputSecurityToken.BufferType=SECBUFFER_TOKEN;
inputSecurityToken.cbBuffer=base64DecodedLen;
inputSecurityToken.pvBuffer=base64Decoded;
outputBufferDescriptor.cBuffers=1;
outputBufferDescriptor.pBuffers=&outputSecurityToken;
outputBufferDescriptor.ulVersion=SECBUFFER_VERSION;
outputSecurityToken.BufferType=SECBUFFER_TOKEN;
outputSecurityToken.cbBuffer=ntlmSecurityPackageInfo->cbMaxToken;
outputSecurityToken.pvBuffer=malloc(outputSecurityToken.cbBuffer);
if(outputSecurityToken.pvBuffer==NULL) {delete base64Decoded; SetLastError(ERROR_OUTOFMEMORY); return NULL;}
securityStatus=pSecurityFunctions->InitializeSecurityContext(&hNtlmClientCredential,&hNtlmClientContext,NULL,0,0,SECURITY_NATIVE_DREP,&inputBufferDescriptor,0,&hNtlmClientContext,&outputBufferDescriptor,&contextAttributes,&tokenExpiration);
delete base64Decoded;
if(securityStatus!=SEC_E_OK) {free(outputSecurityToken.pvBuffer); return NULL;}
char *base64Encoded = Utils::base64Encode((char *)outputSecurityToken.pvBuffer, outputSecurityToken.cbBuffer);
if(base64Encoded==NULL) {free(outputSecurityToken.pvBuffer); NtlmDestroy(); return NULL;}
free(outputSecurityToken.pvBuffer);
return base64Encoded;
}
HTTPRequest::HTTPRequest() {
flags = 0;
url = NULL;
host = NULL;
uri = NULL;
headers = NULL;
method = NULL;
headersCount = 0;
pData = NULL;
dataLength = 0;
resultCode = 0;
credentials = NULL;
ntlmSecurityPackageInfo = NULL;
}
HTTPRequest::~HTTPRequest() {
if (headers!=NULL) delete headers;
if (url!=NULL) delete url;
if (uri!=NULL) delete uri;
if (host!=NULL) delete host;
if (method!=NULL) delete method;
if (pData!=NULL) delete pData;
}
void HTTPRequest::setMethod(const char *t) {
if (this->method!=NULL) delete this->method;
this->method = Utils::dupString(t);
}
const char *HTTPRequest::getMethod() {
return method;
}
void HTTPRequest::setUrl(const char *url) {
const char *phost;
char *puri, *pcolon;
if (this->url!=NULL) delete this->url;
this->url = Utils::dupString(url);
if (this->host!=NULL) delete this->host;
if (this->uri!=NULL) delete this->uri;
phost = strstr(url,"://");
if (phost==NULL) phost = url;
else phost+=3;
host = Utils::dupString(phost);
puri=strchr(host,'/');
if (puri) {
uri = Utils::dupString(puri);
*puri='\0';
} else {
uri = Utils::dupString("/");
}
pcolon=strrchr(host,':');
if(pcolon) {
*pcolon='\0';
wPort=(WORD)strtol(pcolon+1, NULL, 10);
}
else wPort=80;
}
const char *HTTPRequest::getUrl() {
return url;
}
int HTTPRequest::getPort() {
return wPort;
}
const char *HTTPRequest::getUri() {
return uri;
}
const char *HTTPRequest::getHost() {
return host;
}
void HTTPRequest::setCredentials(HTTPCredentials * c) {
credentials = c;
}
HTTPCredentials * HTTPRequest::getCredentials() {
return credentials;
}
void HTTPRequest::setContent(const char *t, int len) {
if (this->pData!=NULL) delete this->pData;
this->pData = new char[len];
memcpy(this->pData, t, len);
this->dataLength = len;
}
void HTTPRequest::setContent(const char *t) {
int len = strlen(t);
if (this->pData!=NULL) delete this->pData;
this->pData = new char[len];
memcpy(this->pData, t, len);
this->dataLength = len;
}
const char *HTTPRequest::getContent() {
return pData;
}
void HTTPRequest::addHeader(const char *name, const char *value) {
HTTPHeader *header = new HTTPHeader(name, value);
if (headers==NULL) {
headers = header;
} else {
HTTPHeader *ptr;
for (ptr = headers;ptr->next!=NULL; ptr=ptr->next);
ptr->next = header;
}
// header->next = headers;
headersCount++;
}
void HTTPRequest::removeHeader(const char *name) {
for (HTTPHeader *ptr=headers, *lastPtr=NULL;ptr!=NULL;) {
if (!strcmp(ptr->name, name)) {
if (lastPtr==NULL) {
headers=ptr->next;
ptr->next = NULL;
delete ptr;
ptr = headers;
} else {
lastPtr->next=ptr->next;
ptr->next = NULL;
delete ptr;
ptr = lastPtr->next;
}
} else {
lastPtr=ptr;
ptr=ptr->next;
}
}
}
HTTPHeader *HTTPRequest::getHeaders() {
return headers;
}
HTTPHeader *HTTPRequest::getHeader(const char *name) {
for (HTTPHeader *header = headers; header!=NULL; header=header->next) {
if (!strcmpi(header->name, name)) return header;
}
return NULL;
}
void HTTPRequest::addAutoRequestHeaders() {
bool isContentLen = false, isHost = false;
for (HTTPHeader *header = headers; header!=NULL; header=header->next) {
if (!strcmpi(header->name, "Host")) isHost = true;
if (!strcmpi(header->name, "Content-Length")) isContentLen = true;
}
if (!isHost) {
addHeader("Host", host);
}
if (!isContentLen) {
char str[64];
sprintf(str, "%d", dataLength);
addHeader("Content-Length", str);
}
}
void HTTPRequest::addAutoResponseHeaders() {
bool isContentLen = false;
for (HTTPHeader *header = headers; header!=NULL; header=header->next) {
if (!strcmpi(header->name, "Content-Length")) isContentLen = true;
}
if (!isContentLen) {
char str[64];
sprintf(str, "%d", dataLength);
addHeader("Content-Length", str);
}
}
char * HTTPRequest::toStringReq() {
int outputSize = 0;
char *output = NULL;
Utils::appendText(&output, &outputSize, "%s %s HTTP/1.1\n", method, uri);
for (HTTPHeader *header = headers; header!=NULL; header=header->next) {
Utils::appendText(&output, &outputSize, "%s: %s\n", header->name, header->value);
}
Utils::appendText(&output, &outputSize, "\n");
return output;
}
char * HTTPRequest::toStringRsp() {
int outputSize = 0;
char *output = NULL;
Utils::appendText(&output, &outputSize, "HTTP/1.1 %03d %s\n", resultCode, (resultCode/100==2) ? "Successful" :"Error");
for (HTTPHeader *header = headers; header!=NULL; header=header->next) {
Utils::appendText(&output, &outputSize, "%s: %s\n", header->name, header->value);
}
Utils::appendText(&output, &outputSize, "\n");
return output;
}
bool HTTPRequest::authBasic(HTTPHeader *header) {
if (getCredentials()->getUsername()==NULL || getCredentials()->getPassword()==NULL) {
return false;
}
for (; header!=NULL; header=header->next) {
if (!strcmpi(header->name, "WWW-Authenticate")) {
if (!strncmp("Basic", header->value, 5)) {
int resultSize =0;
char *result=NULL;
if (getCredentials()->getDomain()!=NULL) {
Utils::appendText(&result, &resultSize, "%s/%s:%s",getCredentials()->getDomain(),getCredentials()->getUsername(), getCredentials()->getPassword());
} else {
Utils::appendText(&result, &resultSize, "%s:%s",getCredentials()->getUsername(), getCredentials()->getPassword());
}
char *base64hash = Utils::base64Encode(result, strlen(result));
free(result);
result=NULL;
Utils::appendText(&result, &resultSize, "Basic %s",base64hash);
delete base64hash;
addHeader("Authorization", result);
free(result);
return true;
}
}
}
return false;
}
bool HTTPRequest::authDigest(HTTPHeader *header) {
if (getCredentials()->getUsername()==NULL || getCredentials()->getPassword()==NULL) {
return false;
}
for (; header!=NULL; header=header->next) {
if (!strcmpi(header->name, "WWW-Authenticate")) {
if (!strncmp("Digest", header->value, 6)) {
HTTPHeader *hAttributes = header->getAttributes(7);
if (hAttributes!=NULL) {
HTTPHeader *hRealm = hAttributes->get("realm");
HTTPHeader *hNonce = hAttributes->get("nonce");
HTTPHeader *hQop = hAttributes->get("qop");
char *nc = "00000001";
char cnonce[33];
for (int i=0;i<32;i++) {
int v = (rand()>>2)%0x0F;
if (v>9) cnonce[i] = 'a' + v - 10;
else cnonce[i] = '0' + v;
}
cnonce[32]='\0';
if (hRealm == NULL || hNonce == NULL) {
return false;
}
char hashedDigest[33];
int tSize =0;
char ha1[33], ha2[33];
MD5 md5;
md5.init();
if (getCredentials()->getDomain()!=NULL) {
md5.update((unsigned char *)getCredentials()->getDomain(), strlen(getCredentials()->getDomain()));
md5.update((unsigned char *)"/", 1);
}
md5.update((unsigned char *)getCredentials()->getUsername(), strlen(getCredentials()->getUsername()));
md5.update((unsigned char *)":", 1);
md5.update((unsigned char *)hRealm->value, strlen(hRealm->value));
md5.update((unsigned char *)":", 1);
md5.update((unsigned char *)getCredentials()->getPassword(), strlen(getCredentials()->getPassword()));
md5.finalize();
md5.getHex(ha1);
md5.init();
md5.update((unsigned char *)getMethod(), strlen(getMethod()));
// md5.update((unsigned char *)"SUBSCRIBE", strlen("SUBSCRIBE"));
md5.update((unsigned char *)":", 1);
md5.update((unsigned char *)getUri(), strlen(getUri()));
md5.finalize();
md5.getHex(ha2);
md5.init();
md5.update((unsigned char *)ha1, 32);
md5.update((unsigned char *)":", 1);
md5.update((unsigned char *)hNonce->value, strlen(hNonce->value));
if (hQop) {
md5.update((unsigned char *)":", 1);
md5.update((unsigned char *)nc, strlen(nc));
md5.update((unsigned char *)":", 1);
md5.update((unsigned char *)cnonce, strlen(cnonce));
md5.update((unsigned char *)":", 1);
md5.update((unsigned char *)hQop->value, strlen(hQop->value));
}
md5.update((unsigned char *)":", 1);
md5.update((unsigned char *)ha2, strlen(ha2));
md5.finalize();
md5.getHex(hashedDigest);
int resultSize =0;
char *result=NULL;
Utils::appendText(&result, &resultSize, "Digest ");
if (getCredentials()->getDomain()!=NULL) {
Utils::appendText(&result, &resultSize, "username=\"%s/%s\", ",getCredentials()->getDomain(), getCredentials()->getUsername());
} else {
Utils::appendText(&result, &resultSize, "username=\"%s\", ",getCredentials()->getUsername());
}
Utils::appendText(&result, &resultSize, "realm=\"%s\", ",hRealm->value);
Utils::appendText(&result, &resultSize, "algorithm=\"MD5\", ");
Utils::appendText(&result, &resultSize, "uri=\"%s\", ",getUri());
Utils::appendText(&result, &resultSize, "nonce=\"%s\", ",hNonce->value);
if (hQop) {
Utils::appendText(&result, &resultSize, "qop=\"%s\", ",hQop->value);
Utils::appendText(&result, &resultSize, "nc=\"%s\", ",nc);
Utils::appendText(&result, &resultSize, "cnonce=\"%s\", ",cnonce);
}
Utils::appendText(&result, &resultSize, "response=\"%s\"",hashedDigest);
addHeader("Authorization", result);
free(result);
return true;
}
}
}
}
return false;
}
bool HTTPRequest::authNTLM(HTTPHeader *header) {
for (; header!=NULL; header=header->next) {
if (!strcmpi(header->name, "WWW-Authenticate")) {
if (!strncmp("NTLM", header->value, 4)) {
authRejectsMax = 2;
if (strlen(header->value)==4) {
char *ntlmToken = NtlmInitialiseAndGetDomainPacket(hInstSecurityDll);
int resultSize =0;
char *result=NULL;
Utils::appendText(&result, &resultSize, "NTLM %s", ntlmToken);
addHeader("Authorization", result);
free(result);
delete ntlmToken;
return true;
} else {
char *ntlmToken = NtlmCreateResponseFromChallenge(header->value + 5);
int resultSize =0;
char *result=NULL;
Utils::appendText(&result, &resultSize, "NTLM %s", ntlmToken);
delete ntlmToken;
addHeader("Authorization", result);
free(result);
return true;
}
break;
}
}
}
return false;
}
char *HTTPUtils::readLine(HTTPConnection *con)
{
int i, lineSize = 0;
char *line = NULL;
for (i=0;;i++) {
if (i>=lineSize) {
line = (char *)realloc(line, lineSize+128);
lineSize += 128;
}
if (con->recv(line+i, 1) != 0) {
if (line[i]=='\r') {
i--;
}
if (line[i]=='\n') {
break;
}
} else {
free(line);
return NULL;
}
}
line[i]='\0';
return line;
}
HTTPRequest *HTTPUtils::toRequest(const char *text) {
char *line;
int len;
HTTPHeader *header = NULL;
HTTPRequest *request = new HTTPRequest();
for (len=0;;text+=len) {
char *pColon;
line = Utils::getLine(text, &len);
if (line == NULL) {
break;
}
if (line[0]=='\0') {
text += len;
break;
}
pColon=strchr(line,':');
if (pColon == NULL) {
text += len;
break;
}
*pColon = '\0';
Utils::trim(line, " \t");
Utils::trim(pColon+1, " \t");
request->addHeader(line, pColon+1);
delete line;
}
if (line !=NULL) delete line;
if (*text != '\0') {
request->setContent(text, strlen(text)+1);
}
return request;
}
HTTPRequest *HTTPUtils::recvHeaders(HTTPConnection *con) {
int i;
char *line;
HTTPHeader *header = NULL;
HTTPRequest *request = new HTTPRequest();
request->resultCode = 500;
for (i=0;;i++) {
char *pColon;
line = readLine(con);
if (line == NULL) {
break;
}
if (i==0) {
if (strlen(line) > 11 && !strncmp(line, "HTTP/", 5)) {
line[12]='\0';
request->resultCode = atoi(line + 9);
} else if (!strncmp(line, "GET", 3)) {
request->setMethod("GET");
request->setUrl(line + 3);
} else if (!strncmp(line, "POST", 4)) {
request->setMethod("POST");
request->setUrl(line + 4);
} else if (!strncmp(line, "SUBSCRIBE", 9)) {
request->setMethod("SUBSCRIBE");
request->setUrl(line + 9);
} else if (!strncmp(line, "UNSUBSCRIBE", 11)) {
request->setMethod("UNSUBSCRIBE");
request->setUrl(line + 9);
} else if (!strncmp(line, "NOTIFY", 6)) {
request->setMethod("NOTIFY");
request->setUrl(line + 6);
} else {
free(line);
break;
}
} else {
if (line[0]=='\0') {
free(line);
break;
}
pColon=strchr(line,':');
if (pColon != NULL) {
*pColon = '\0';
Utils::trim(line, " \t");
Utils::trim(pColon+1, " \t");
request->addHeader(line, pColon+1);
} else {
break;
}
}
free(line);
}
return request;
}
/*
* Add auto headers, send request and receive response.
*/
HTTPRequest *HTTPUtils::performRequest(HTTPConnection *con, HTTPRequest *request) {
HTTPRequest *response = NULL;
if (con!=NULL) {
request->addAutoRequestHeaders();
char *str = request->toStringReq();
logger->info("REQUEST:\n%s\n", str);
if (con->send(str, strlen(str))) {
if (con->send(request->getContent(), request->dataLength)) {
response = recvHeaders(con);
for (HTTPHeader *header=response->getHeaders(); header!=NULL; header=header->next) {
if (!strcmpi(header->name, "Content-Length")) {
int len = atol(header->value);
char *data = new char[len+1];
for (int l=0;l<len;) {
int j = con->recv(data+l, len-l);
if (j<=0) {
break;
}
l+=j;
}
data[len]='\0';
response->setContent(data, len);
logger->info("RESPONSE:\n%s\n", data);
delete data;
}
}
}
}
free(str);
}
return response;
}
HTTPRequest *HTTPUtils::recvRequest(HTTPConnection *con) {
HTTPRequest *response = NULL;
if (con!=NULL) {
response = recvHeaders(con);
for (HTTPHeader *header=response->getHeaders(); header!=NULL; header=header->next) {
if (!strcmpi(header->name, "Content-Length")) {
int len = atol(header->value);
char *data = new char[len+1];
for (int l=0;l<len;) {
int j = con->recv(data+l, len-l);
if (j<=0) {
break;
}
l+=j;
}
data[len]='\0';
response->setContent(data, len);
delete data;
}
}
}
return response;
}
int HTTPUtils::sendResponse(HTTPConnection *con, HTTPRequest *response) {
int result = 500;
if (con!=NULL) {
response->addAutoResponseHeaders();
char *str = response->toStringRsp();
if (con->send(str, strlen(str))) {
if (con->send(response->getContent(), response->dataLength)) {
result = 0;
}
}
free(str);
}
return result;
}
HTTPRequest *HTTPUtils::performTransaction(HTTPRequest *request) {
char *str;
HTTPRequest *response = NULL;
int authRejects = 0;
HTTPConnection *con = NULL;
request->keepAlive = false;
request->authRejectsMax = 1;
request->authRejects = 0;
str = request->toStringReq();
free(str);
while (1) {
if (con == NULL) {
con = new HTTPConnection(request->getHost(), request->getPort());
}
response = HTTPUtils::performRequest(con, request);
if (response != NULL) {
/* Look for important headers: Connection, */
request->keepAlive = true;
for (HTTPHeader *header=response->getHeaders(); header!=NULL; header=header->next) {
if (!strcmpi(header->name, "Connection")) {
if (!strcmpi(header->value, "close")) {
request->keepAlive = false;
}
}
}
if (response->resultCode == 302) {
HTTPHeader *header;
for (header=response->getHeaders(); header!=NULL; header=header->next) {
if (!strcmpi(header->name, "Location")) {
request->removeHeader("Host");
request->setUrl(header->value);
request->keepAlive = false;
break;
}
}
if (header==NULL) {
// no destination location
break;
}
} else if (response->resultCode == 401) {
request->removeHeader("Authorization");
if (request->getCredentials()==NULL) break;
if (request->authRejects > request->authRejectsMax) break;
request->authRejects++;
if (!request->authNTLM(response->getHeaders())) {
if (!request->authDigest(response->getHeaders())) {
if (!request->authBasic(response->getHeaders())) {
break;
}
}
}
} else if (response->resultCode/100 == 2) {
break;
} else {
break;
}
delete response;
if (!request->keepAlive) {
delete con;
con = NULL;
}
} else {
break;
}
}
if (con != NULL) {
delete con;
}
return response;
}
| [
"the_leech@3f195757-89ef-0310-a553-cc0e5972f89c"
] | [
[
[
1,
952
]
]
] |
754751015b19a141726c9f9326b21b7a5e883590 | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /source/RenderSystemD3D/OED3DShader_Impl.cpp | 7ba5cd489131befb6323d19b26108d2f6d66476e | [] | 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 | 6,018 | cpp | /*!
* \file OED3DShader_Impl.cpp
* \date 1-6-2009 15:49:33
*
*
* \author zjhlogo ([email protected])
*/
#include "OED3DShader_Impl.h"
#include "OED3DTexture_Impl.h"
#include "OED3DUtil.h"
#include <OECore/IOEDevice.h>
#include <OEBase/IOELogFileMgr.h>
#include <libOEBase/OEOS.h>
extern IDirect3DDevice9* g_pd3dDevice;
COED3DShader_Impl::COED3DShader_Impl(const VERT_DECL_ELEMENT* pElement, const tstring& strFileName)
{
Init();
m_bOK = Create(pElement, strFileName);
}
COED3DShader_Impl::~COED3DShader_Impl()
{
Destroy();
}
void COED3DShader_Impl::Init()
{
m_pDecl = NULL;
m_pEffect = NULL;
}
void COED3DShader_Impl::Destroy()
{
SAFE_RELEASE(m_pDecl);
SAFE_RELEASE(m_pEffect);
}
bool COED3DShader_Impl::SetInt(const tstring& strParamName, int nValue)
{
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
if (FAILED(m_pEffect->SetInt(strANSIName.c_str(), nValue))) return false;
return true;
}
bool COED3DShader_Impl::GetInt(int& nOut, const tstring& strParamName)
{
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
if (FAILED(m_pEffect->GetInt(strANSIName.c_str(), &nOut))) return false;
return true;
}
bool COED3DShader_Impl::SetFloat(const tstring& strParamName, float fValue)
{
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
if (FAILED(m_pEffect->SetFloat(strANSIName.c_str(), fValue))) return false;
return true;
}
bool COED3DShader_Impl::GetFloat(float& fOut, const tstring& strParamName)
{
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
if (FAILED(m_pEffect->GetFloat(strANSIName.c_str(), &fOut))) return false;
return true;
}
bool COED3DShader_Impl::SetVector(const tstring& strParamName, const CVector4& vIn)
{
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
D3DXVECTOR4 vD3D;
COED3DUtil::ToD3DVector4(vD3D, vIn);
if (FAILED(m_pEffect->SetVector(strANSIName.c_str(), &vD3D))) return false;
return true;
}
bool COED3DShader_Impl::SetVector(const tstring& strParamName, const CVector3& vIn)
{
CVector4 vVec(vIn.x, vIn.y, vIn.z, 0.0f);
return SetVector(strParamName, vVec);
}
bool COED3DShader_Impl::GetVector(CVector4& vOut, const tstring& strParamName)
{
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
D3DXVECTOR4 vD3D;
if (FAILED(m_pEffect->GetVector(strANSIName.c_str(), &vD3D))) return false;
COED3DUtil::ToOEVector4(vOut, vD3D);
return true;
}
bool COED3DShader_Impl::GetVector(CVector3& vOut, const tstring& strParamName)
{
CVector4 vVec;
if (!GetVector(vVec, strParamName)) return false;
vOut.x = vVec.x;
vOut.y = vVec.y;
vOut.z = vVec.z;
return true;
}
bool COED3DShader_Impl::SetMatrix(const tstring& strParamName, const CMatrix4x4& matIn)
{
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
D3DXMATRIX matD3D;
COED3DUtil::ToD3DXMatrix(matD3D, matIn);
if (FAILED(m_pEffect->SetMatrix(strANSIName.c_str(), &matD3D))) return false;
return true;
}
bool COED3DShader_Impl::GetMatrix(CMatrix4x4& matOut, const tstring& strParamName)
{
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
D3DXMATRIX matD3D;
if (FAILED(m_pEffect->GetMatrix(strANSIName.c_str(), &matD3D))) return false;
COED3DUtil::ToOEMatrix(matOut, matD3D);
return true;
}
bool COED3DShader_Impl::SetMatrixArray(const tstring& strParamName, const CMatrix4x4* pmatIn, uint nCount)
{
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
D3DXMATRIX matD3D;
if (FAILED(m_pEffect->SetMatrixArray(strANSIName.c_str(), (const D3DXMATRIX*)pmatIn, nCount))) return false;
return true;
}
bool COED3DShader_Impl::GetMatrixArray(CMatrix4x4* pmatOut, uint nCount, const tstring& strParamName)
{
// TODO:
return false;
}
bool COED3DShader_Impl::SetTexture(const tstring& strParamName, IOETexture* pTexture)
{
if (!pTexture) return false;
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
COED3DTexture_Impl* pD3DTexture = (COED3DTexture_Impl*)pTexture;
if (FAILED(m_pEffect->SetTexture(strANSIName.c_str(), pD3DTexture->GetTexture())))
{
LOGOUT(TS("IOEShader::SetTexture Failed \"%s\""), strParamName.c_str());
return false;
}
return true;
}
bool COED3DShader_Impl::SetTechnique(const tstring& strParamName)
{
std::string strANSIName;
if (!COEOS::tchar2char(strANSIName, strParamName.c_str())) return false;
if (FAILED(m_pEffect->SetTechnique(strANSIName.c_str())))
{
LOGOUT(TS("IOEShader::SetTechnique Failed \"%s\""), strParamName.c_str());
return false;
}
return true;
}
IOEVertDecl* COED3DShader_Impl::GetVertDecl()
{
return m_pDecl;
}
ID3DXEffect* COED3DShader_Impl::GetEffect() const
{
return m_pEffect;
}
bool COED3DShader_Impl::Create(const VERT_DECL_ELEMENT* pElement, const tstring& strFileName)
{
m_pDecl = (COED3DVertDecl_Impl*)g_pOEDevice->CreateVertDecl(pElement);
if (!m_pDecl) return false;
// create effect
ID3DXBuffer* pErrorBuffer = NULL;
HRESULT hr = D3DXCreateEffectFromFile(g_pd3dDevice, strFileName.c_str(), NULL, NULL, NULL, NULL, &m_pEffect, &pErrorBuffer);
if (pErrorBuffer)
{
tstring strMsg;
COEOS::char2tchar(strMsg, (char*)pErrorBuffer->GetBufferPointer());
LOGOUT(TS("COED3DShader_Impl::Create Failed \"%s\""), strMsg.c_str());
SAFE_RELEASE(pErrorBuffer);
}
if (FAILED(hr)) return false;
D3DXHANDLE hTechnique = m_pEffect->GetTechnique(0);
if (hTechnique)
{
hr = m_pEffect->SetTechnique(hTechnique);
if (FAILED(hr)) return false;
}
return true;
}
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
] | [
[
[
1,
226
]
]
] |
bdf1c561c901042ad7b1741a9bba14035fd38f89 | ce105c9e4ac9b1b77a160793e0c336826b936670 | /c++/sort/sort/list.h | c1d919344022f2c80c2b89ab572e25e777eb8f2f | [] | no_license | jmcgranahan/jusall-programinghw | a32909655cec085d459c2c567c2f1bed2b947612 | d6c5b54d0300a784dee0257364cd049f741cee81 | refs/heads/master | 2020-08-27T03:27:24.013332 | 2011-04-25T06:30:27 | 2011-04-25T06:30:27 | 40,640,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,242 | h | //list.h
#include "node.h"
#include <iostream>
#pragma once
template <class type>
class list
{
node<type> * head; // pointer to first object in list
node<type> * tail; // ... last object in list
node<type> * current; // current pointer
int iCurrent, length; // current pointers position in the list and length of the list
public:
// dafualt construtor
list(void)
{
head = NULL;
tail = NULL;
current = NULL;
iCurrent = 0;
length = 0;
}
// deconstructor
~list(void)
{
while(head)
{
node<type> * pTemp = head;
head = head->getNext();
delete pTemp;
}
}
// create a new node with the input data to the head of the list.
void push(const type & item)
{
node<type> * pTemp = head; // dont loose head
head = new node<type>(item,pTemp); // create new head
if(pTemp) // incase list was empty
pTemp->setPrev(head);
else
tail = head;
current = head;
iCurrent = 0;
length++;
}
//create a new node with the input data to the tail of the list
void append(const type & item)
{
node<type> * pTemp = tail; // dont loose tail
tail = new node<type>(item);
tail->setPrev(pTemp);
if(pTemp) // incase list was empty
pTemp->setNext(tail);
else
head = tail;
current = tail;
iCurrent = length;
length++;
}
// insert a node storing the given item at the specified index
void insert(const type & item,int index)
{
if(index >= length) // checks for front or end of lists inserts - skip searching to it.
this->append(item);
else if(index == 0)
this->push(item);
else
{
get(index); // move current to index
node<type>* pBefore = current->getPrev();
node<type>* newNode = new node<type>(item,current,pBefore);
if(pBefore)
pBefore->setNext(newNode);
current->setPrev(newNode);
current = newNode;
}
}
//return data stored in the head of the list
type getHead(void)
{
return head->getData();
}
//return data stored in the tail of the list
type getTail(void)
{
return tail->getData();
}
//return data stored in the node at index, used often to move current to a specific index
type get(int index)
{
int distFromTail, distFromCurr;
distFromCurr = abs(iCurrent-index);
distFromTail = abs (length-index);
if( index < distFromCurr && index < distFromTail) // determins the closest known pointer to the index
{
current = head;
iCurrent = 0;
}
else if( distFromTail < distFromCurr) // ..and moves current pointer to it
{
current = tail;
iCurrent = length-1;
}
while (current && iCurrent != index) // walk through list
{
if( index > iCurrent)
{
current = current->getNext();
iCurrent++;
}
else
{
current = current->getPrev();
iCurrent--;
}
}
if( current )
return current->getData();
cout << "no object at index" << endl;
}
// removes the indexed node from the list, returning the data stored there
type pop(int index)
{
get(index);
if( current )
{
type data = current->getData();
node<type> * pTemp = current;
if(head == tail)
{
current = tail = head = NULL;
iCurrent = 0;
}
else if( current == tail )
{
current = tail = pTemp->getPrev();
current->setNext(NULL);
iCurrent--;
}
else if( current == head)
{
current = head = pTemp->getNext();
current->setPrev(NULL);
}
else
{
current = current->getNext();
current->setPrev(pTemp->getPrev());
current->getPrev()->setNext(pTemp->getNext());
}
length--;
delete pTemp;
return data;
}
}
//remove the indexed node from the list, no return
void remove(int index)
{
pop(index); // because re-writing is wasteful
}
//searches the list for a node containing data, then returns the index of that node.
int search(const type & item)
{
current = head;
iCurrent = 0;
while( current && current->getData() != item )
{
iCurrent++;
current = current->getNext();
}
if(current)
return iCurrent;
else
return -1;
}
//return list length
int getLength(void)
{
return length;
}
//cat - add the passed list to the end of this list
// inputs: List to cat
//
void cat(list<type> * inputList)
{
int inputLength = inputList->getLength();
for(int i = 0; i < inputLength; i++)
{
type buffer = inputList->get(i);
this->append(buffer);
}
}
//cat - adds the passed lists to the end of this list
// inputs: first list, and seccond list
//
void cat( list<type> * firstList, list<type> * seccondList)
{
this->cat(firstList);
this->cat(seccondList);
}
//cat - adds the passed list, value, list, to the end of this list
// inputs: first list, pivot value ( for quick sort), and seccond list
//
void cat(list<type> * firstList, type pivotValue, list<type> * seccondList)
{
this->cat(firstList);
this->append(pivotValue);
this->cat(seccondList);
}
//quickSort - sort the stack using the quicksort method
//
void quickSort(void)
{
list<type> smaller,larger;
type pivot = pop((int)length/2);
while(length > 0)
{
int currentValue = pop(0);
if (currentValue < pivot)
smaller.append(currentValue);
else
larger.append(currentValue);
}
this->cat(recursiveSort(&smaller), pivot, recursiveSort(&larger)) ;
}
//recursiveSort - recursive sorting for quicksort
//inputs: list pointer to list to sort.
//outputs: list pointer to sorted list
//
list<type> * recursiveSort(list<type> * inputList)
{
if( inputList->getLength() <= 1 )
return inputList;
list<type> smaller,larger;
type pivot = inputList->pop((int)inputList->getLength()/2);
while(inputList->getLength() > 0)
{
int currentValue = inputList->pop(0);
if (currentValue < pivot)
smaller.append(currentValue);
else
larger.append(currentValue);
}
list<type> * buffer = new list<type>();
buffer->cat(recursiveSort(&smaller), pivot, recursiveSort(&larger));
return buffer;
}
};
| [
"[email protected]"
] | [
[
[
1,
288
]
]
] |
fdb8a9e5313507acca3962a2d1a1f91d42db8eab | a4756c3232fd88a74df199acc84ab70ec48d7875 | /FileManagerServer/GUI/clientexplorer.cpp | 550b41a1c79c359d8d4f576939ad871fb3b88bfd | [] | no_license | raygray/filemanagermlf | a7a0cdd14cd558657116b6ae641bcb743084ba37 | 0648183e9c88d6e883861f1f1dcbe67550e5c11f | refs/heads/master | 2021-01-10T05:03:12.702335 | 2010-07-14T13:31:02 | 2010-07-14T13:31:02 | 49,008,746 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 663 | cpp | #include "clientexplorer.h"
ClientExplorer::ClientExplorer(BaseExplorer *baseExplorer)
:BaseExplorer(baseExplorer)
{
setClientSpecificText(); //设置一些控件的显示文字
}
ClientExplorer::~ClientExplorer()
{
}
void ClientExplorer::setClientSpecificText()
{
QMap<QString, QString> paraMap;
paraMap.insert("typeLabel", tr("<font color = red>客户端</font>"));
paraMap.insert("transButton", tr("上传至服务器"));
paraMap.insert("currentPathLabel", tr("<font color = red>路径</font>"));
Parameter parameter(paraMap);
setSpecificText(parameter);
}
void ClientExplorer::InitTreeView()
{
}
| [
"malongfei88@0a542be3-54de-31ef-7baa-42960c810bab"
] | [
[
[
1,
26
]
]
] |
60a6a16a14360a1d4bddd3ce846ac1ad310bcd02 | 3965e5c3231c720938cc10202d2baf5443352ffd | /optimization/numerical_base/barrier_functions_solver.h | 6aaa7655c9fccc9fcda9d3f6ab27d53d009c41ad | [] | no_license | smi13/semester06 | 4224f691677cea6769d7d06acbb8cacbe60f37d8 | 10cd78eb98ca26b46d133b805be5bef06a8ee136 | refs/heads/master | 2021-03-12T21:33:59.363142 | 2010-08-25T22:52:55 | 2010-08-25T22:52:55 | 862,620 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,110 | h | #ifndef _barrier_functions_solver_h
#define _barrier_functions_solver_h
#include "function.h"
#include "md_task_solver.h"
class Vector;
class MdTask;
class BarrierFunctionsSolver : public MdTaskSolver
{
public:
class BarrierFunction : public Func
{
public:
BarrierFunction( double new_BarrierParamter, MdTask &new_Task );
virtual double operator()( Vector &x );
private:
double _barrierParameter;
MdTask &_T;
};
class BarrierFunctionGrad : public VectorFunc
{
public:
BarrierFunctionGrad( double new_BarrierParamter, MdTask &new_Task );
virtual Vector operator()( Vector &x );
private:
double _barrierParameter;
MdTask &_T;
};
BarrierFunctionsSolver( MdTask &T, double new_barrierParamter, double new_betha );
virtual double solve( Vector &res );
void setDebugOutput();
bool isFeasible( Vector &x );
private:
bool _debugOutput;
void _solve( Vector &res );
double _barrierParameter, _betha;
};
#endif /* _barrier_functions_solver_h */ | [
"[email protected]"
] | [
[
[
1,
58
]
]
] |
5bafda46f77c386b314549e82d9b4d3db1378ded | cfcd2a448c91b249ea61d0d0d747129900e9e97f | /thirdparty/OpenCOLLADA/COLLADAFramework/include/COLLADAFWMeshPrimitive.h | 47224e8c0f40ca6b601c8377c63a77ba78500baa | [] | no_license | fire-archive/OgreCollada | b1686b1b84b512ffee65baddb290503fb1ebac9c | 49114208f176eb695b525dca4f79fc0cfd40e9de | refs/heads/master | 2020-04-10T10:04:15.187350 | 2009-05-31T15:33:15 | 2009-05-31T15:33:15 | 268,046 | 0 | 0 | null | null | null | null | WINDOWS-1258 | C++ | false | false | 14,786 | h | /*
Copyright (c) 2008 NetAllied Systems GmbH
This file is part of COLLADAFramework.
Licensed under the MIT Open Source License,
for details please see LICENSE file or the website
http://www.opensource.org/licenses/mit-license.php
*/
#ifndef __COLLADAFW_MESHPRIMITIVE_H__
#define __COLLADAFW_MESHPRIMITIVE_H__
#include "COLLADAFWPrerequisites.h"
#include "COLLADAFWConstants.h"
#include "COLLADAFWTypes.h"
#include "COLLADAFWEdge.h"
#include "COLLADAFWIndexList.h"
#include <map>
#include <vector>
namespace COLLADAFW
{
/**
Geometric primitives, which assemble values from the inputs into vertex attribute data.
Can be any combination of any primitive types in any order.
To describe geometric primitives that are formed from the vertex data, the <mesh> element may
contain zero or more of the primitive elements <lines>, <linestrips>, <polygons>, <polylist>,
<triangles>, <trifans>, and <tristrips>.
The <vertices> element under <mesh> is used to describe mesh-vertices. Polygons, triangles, and
so forth index mesh-vertices, not positions directly. Mesh-vertices must have at least one
<input> (unshared) element with a semantic attribute whose value is POSITION.
For texture coordinates, COLLADA’s right-handed coordinate system applies; therefore, an ST
texture coordinate of [0,0] maps to the lower-left texel of a texture image, when loaded in a
professional 2-D texture viewer/editor.
*/
class MeshPrimitive
{
public:
/** The types of primitives. */
enum PrimitiveType
{
LINES, /**< A list of lines. Only one element is contained in the face-vertex count list.
It represents the total number of line vertices. The total number of lines is
equal to half the total number of line vertices. */
LINE_STRIPS, /**< A list of continuous lines. Each element in the face-vertex count list
represents the number of consecutive line vertices before restarting. */
POLYGONS, /**< A list of polygons. All the polygons may be triangles.
This is the most common primitive type. The polygons may have holes. Each element in the
face-vertex count list represent the number of vertices for one polygon. */
POLYLIST,
TRIANGLES,
TRIANGLE_FANS, /**< A list of triangle fans. Each element in the face-vertex count list
represents the number of vertices for one fan. A triangle fan is defined by re-using the first
vertex for every triangle. Advancing pairs are then used in order to generate adjacent triangles
such that if there are 5 vertices, then 3 triangles are created: {0,1,2}, {0,2,3} and {0,3,4}. */
TRIANGLE_STRIPS, /**< A list of continuous triangles. Each element in the face-vertex count list
represents the number of vertices for one strip. A triangle strip is defined by re-using two
advancing vertices from the previous triangle for the next triangle. If there are 5 vertices in
the strip, then 3 triangles are created: {0,1,2}, {1,2,3}, {2,3,4}. Note that vertex winding must
also be taken into consideration and every even triangle in the strip has its vertices swapped
from the above pattern. */
POINTS, /**< A list of Camera-facing sprites. The face-vertex count list will contain one element that
represents the total number of points. Two non-COLLADA geometry sources (POINT_SIZE and POINT_ROTATION)
are specific to this type. */
UNDEFINED_PRIMITIVE_TYPE
};
private:
/**
* The type of the current primitive. Possible values are:
* <lines>, <linestrips>, <polygons>, <polylist>, <triangles>, <trifans>, and <tristrips>.
*/
PrimitiveType mPrimitiveType;
/**
* The attribute indicates the number of polygon faces in the current primitive element.
*/
size_t mFaceCount;
/**
* The material attribute declares a symbol for a material. This symbol
* is bound to a material at the time of instantiation. If the material
* attribute is not specified then the lighting and shading results are
* application defined. Optional attribute.
*/
String mMaterial;
/** The material id of the sub mesh. This material id is used to assign material
to submeshes when the mesh gets instantiated.*/
MaterialId mMaterialId;
/**
* The index list of the positions array.
*/
UIntValuesArray mPositionIndices;
/**
* The index list of the normals array.
*/
UIntValuesArray mNormalIndices;
/**
* The index list of the colors array (support of multiple colors).
*/
IndexListArray mColorIndicesArray;
/**
* The index list of the uv coordinates array (support of multiple uv sets).
*/
IndexListArray mUVCoordIndicesArray;
public:
/**
* Constructor.
*/
MeshPrimitive ();
/**
* Constructor.
*/
MeshPrimitive ( PrimitiveType primitiveType );
/**
* Destructor.
*/
virtual ~MeshPrimitive() {}
/** The type of the current primitive. Possible values are:
<lines>, <linestrips>, <polygons>, <polylist>, <triangles>, <trifans>, and <tristrips>. */
const MeshPrimitive::PrimitiveType getPrimitiveType () const { return mPrimitiveType; }
/** The type of the current primitive. Possible values are:
<lines>, <linestrips>, <polygons>, <polylist>, <triangles>, <trifans>, and <tristrips>. */
void setPrimitiveType ( const MeshPrimitive::PrimitiveType PrimitiveType ) { mPrimitiveType = PrimitiveType; }
/**
* Gets the count attribute.
* @return Returns the count attribute.
*/
const size_t getFaceCount () const { return mFaceCount; }
/**
* Sets the count attribute.
* @param atCount The new value for the count attribute.
*/
void setFaceCount ( const size_t count ) { mFaceCount = count; }
/**
* Gets the material attribute.
* @return Returns a xsNCName of the material attribute.
*/
String getMaterial () const { return mMaterial; }
/**
* Sets the material attribute.
* @param atMaterial The new value for the material attribute.
*/
void setMaterial ( const String& material ) { mMaterial = material; }
/**
* The index list of the positions array.
*/
COLLADAFW::UIntValuesArray& getPositionIndices () { return mPositionIndices; }
/**
* The index list of the positions array.
*/
const COLLADAFW::UIntValuesArray& getPositionIndices () const { return mPositionIndices; }
/**
* The index list of the positions array.
*/
void setPositionIndices ( const COLLADAFW::UIntValuesArray& PositionIndices ) { mPositionIndices = PositionIndices; }
/**
* The index list of the normals array.
*/
COLLADAFW::UIntValuesArray& getNormalIndices () { return mNormalIndices; }
/**
* The index list of the normals array.
*/
const COLLADAFW::UIntValuesArray& getNormalIndices () const{ return mNormalIndices; }
/**
* The index list of the normals array.
*/
void setNormalIndices ( const COLLADAFW::UIntValuesArray& NormalIndices ) { mNormalIndices = NormalIndices; }
/**
* The index list of the colors array.
*/
IndexList* getColorIndices ( size_t index )
{
assert ( mColorIndicesArray.getCount () > index );
return mColorIndicesArray [ index ];
}
/**
* The index list of the colors array.
*/
const IndexList* getColorIndices ( size_t index ) const
{
assert ( mColorIndicesArray.getCount () > index );
return mColorIndicesArray [ index ];
}
/**
* The index list of the colors array.
*/
IndexListArray& getColorIndicesArray () { return mColorIndicesArray; }
/**
* The index list of the colors array.
*/
const IndexListArray& getColorIndicesArray () const { return mColorIndicesArray; }
/**
* The index list of the colors array.
*/
void appendColorIndices ( IndexList* colorIndices ) { mColorIndicesArray.append ( colorIndices ); }
/**
* The index list of the uv coordinates array.
*/
IndexListArray& getUVCoordIndicesArray () { return mUVCoordIndicesArray; }
/**
* The index list of the uv coordinates array.
*/
const IndexListArray& getUVCoordIndicesArray () const { return mUVCoordIndicesArray; }
/**
* The index list of the uv coordinates array.
*/
IndexList* getUVCoordIndices ( size_t index )
{
assert ( mUVCoordIndicesArray.getCount () > index );
return mUVCoordIndicesArray [ index ];
}
/**
* The index list of the uv coordinates array.
*/
const IndexList* getUVCoordIndices ( size_t index ) const
{
assert ( mUVCoordIndicesArray.getCount () > index );
return mUVCoordIndicesArray [ index ];
}
/**
* The index list of the uv coordinates array.
*/
void appendUVCoordIndices ( IndexList* uvCoordIndices ) { mUVCoordIndicesArray.append ( uvCoordIndices ); }
/** @return The material id of the sub mesh. This material id is used to assign material
to submeshes when the mesh gets instantiated.*/
COLLADAFW::MaterialId getMaterialId() const { return mMaterialId; }
/** Sets the material id of the sub mesh. This material id is used to assign material
to submeshes when the mesh gets instantiated.*/
void setMaterialId(COLLADAFW::MaterialId val) { mMaterialId = val; }
/*
* Fills the array with the index list of the edges
* (the index list referes on the position indices)
*/
COLLADAFW::UIntValuesArray& getEdgeIndices ( COLLADAFW::UIntValuesArray& edgeIndices );
/*
* Determine the edge indices (unique edges, also for multiple primitive elements)
* and write it into the lists (the indices referes on the position indices).
* Does it for triangle elements, polygons or polylist. Trifans and tristrips are a little
* bit special.
* @param edgeIndices
* A vector of edge indices. We use it to write the list of edges into the maya
* file. The vector is already sorted.
* @param edgeIndicesMap
* We store the edge indices also in a sorted map. The dublicate data holding
* is reasonable, because we need the index of a given edge. The search of
* values in a map is much faster than in a vector!
*/
void appendEdgeIndices (
std::vector<Edge>& edgeIndices,
std::map<Edge,size_t>& edgeIndicesMap );
/*
* Determine the edge indices (unique edges, also for multiple primitive elements)
* and write it into the lists (the indices referes on the position indices).
* Does it for triangle elements, polygons or polylist.
* @param edgeIndices
* A vector of edge indices. We use it to write the list of edges into the maya
* file. The vector is already sorted.
* @param edgeIndicesMap
* We store the edge indices also in a sorted map. The dublicate data holding
* is reasonable, because we need the index of a given edge. The search of
* values in a map is much faster than in a vector!
*/
void appendPolygonEdgeIndices (
std::vector<Edge>& edgeIndices,
std::map<Edge,size_t>& edgeIndicesMap );
/*
* Determine the edge indices (unique edges, also for multiple primitive elements)
* and write it into the lists (the indices referes on the position indices).
* Does it for trifans.
* @param edgeIndices
* A vector of edge indices. We use it to write the list of edges into the maya
* file. The vector is already sorted.
* @param edgeIndicesMap
* We store the edge indices also in a sorted map. The dublicate data holding
* is reasonable, because we need the index of a given edge. The search of
* values in a map is much faster than in a vector!
*/
void appendTrifansEdgeIndices (
std::vector<Edge>& edgeIndices,
std::map<Edge,size_t>& edgeIndicesMap );
/*
* Determine the edge indices (unique edges, also for multiple primitive elements)
* and write it into the lists (the indices referes on the position indices).
* Does it for tristrips.
* @param edgeIndices
* A vector of edge indices. We use it to write the list of edges into the maya
* file. The vector is already sorted.
* @param edgeIndicesMap
* We store the edge indices also in a sorted map. The dublicate data holding
* is reasonable, because we need the index of a given edge. The search of
* values in a map is much faster than in a vector!
*/
void appendTristripsEdgeIndices (
std::vector<Edge>& edgeIndices,
std::map<Edge,size_t>& edgeIndicesMap );
/*
* Determine the number of grouped vertex elements in the current mesh primitive.
*/
int getGroupedVertexElementsCount () const;
/*
* Appends the data of an edge, if it is not already in the list.
*/
void appendEdge(
const Edge& edge,
std::vector<Edge>& edgeIndices,
std::map<Edge,size_t>& edgeIndicesMap );
/*
* Returns the vertex count of the face with the specified index.
*/
const int getGroupedVerticesVertexCount ( const size_t faceIndex ) const;
};
typedef ArrayPrimitiveType<MeshPrimitive*> MeshPrimitiveArray;
}
#endif // __COLLADAFW_MESHPRIMITIVE_H__
| [
"[email protected]"
] | [
[
[
1,
369
]
]
] |
53e8670f81b556ae07b59145fd9d2ef252ba7c99 | 299a1b0fca9e1de3858a5ebeaf63be6dc3a02b48 | /tags/051101/trunk/ic2005/src/demo/wallz/WallPieces.cpp | 1399afa1c298973162f8251c89b8b6201a74a72e | [] | no_license | BackupTheBerlios/dingus-svn | 331d7546a6e7a5a3cb38ffb106e57b224efbf5df | 1223efcf4c2079f58860d7fa685fa5ded8f24f32 | refs/heads/master | 2016-09-05T22:15:57.658243 | 2006-09-02T10:10:47 | 2006-09-02T10:10:47 | 40,673,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,802 | cpp | #include "stdafx.h"
#include "WallPieces.h"
#include <dingus/math/Plane.h>
#include <dingus/math/MathUtils.h>
#include <dingus/renderer/RenderableBuffer.h>
//#include <dingus/utils/CpuTimer.h>
#include "../MeshEntity.h"
const float HALF_THICK = 0.02f;
extern int gWallVertCount, gWallTriCount;
static inline float signedAngle2D( const SVector2& a, const SVector2& b )
{
float sgn = a.x*b.y > b.x*a.y ? 1.0f : -1.0f;
float dotp = a.dot( b ) / (a.length()*b.length());
dotp = clamp( dotp, -1.0f, 1.0f );
float ang = acosf( dotp );
return sgn * ang;
}
// --------------------------------------------------------------------------
void CWallPiece3D::init( const CWall3D& w, int idx )
{
const CWallPiece2D& piece = w.getWall2D().getPiece(idx);
// construct VB/IB for this piece, with positions centered
SVector2 pcenter = piece.getAABB().getCenter();
static TIntVector vertRemap;
vertRemap.resize(0);
vertRemap.resize( w.getWall2D().getVerts().size(), -1 );
int i;
int nidx = piece.getTriCount()*3;
mIB.reserve( nidx * 2 + piece.getVertexCount()*6 );
mVB.reserve( piece.getVertexCount()*4 );
// construct one side
for( i = 0; i < nidx; ++i ) {
int oldIdx = piece.getIB()[i];
int newIdx = vertRemap[oldIdx];
if( newIdx < 0 ) {
newIdx = mVB.size();
vertRemap[oldIdx] = newIdx;
SVector2 pos = w.getWall2D().getVerts()[oldIdx];
pos -= pcenter;
SVertexXyzNormal vtx;
vtx.p.set( pos.x, pos.y, HALF_THICK );
vtx.n.set( 0, 0, 1 );
mVB.push_back( vtx );
}
mIB.push_back( newIdx );
}
for( i = 0; i < nidx/3; ++i ) {
int iii = mIB[i*3+1];
mIB[i*3+1] = mIB[i*3+2];
mIB[i*3+2] = iii;
}
// construct another side
int nverts = mVB.size();
//int npolygon = piece.getPolygon().size();
for( i = 0; i < nverts; ++i ) {
SVertexXyzNormal vtx = mVB[i];
vtx.p.z = -vtx.p.z;
vtx.n.set( 0,0, -1 );
mVB.push_back( vtx );
}
for( i = 0; i < nidx/3; ++i ) {
int idx0 = mIB[i*3+0];
int idx1 = mIB[i*3+1];
int idx2 = mIB[i*3+2];
mIB.push_back( idx0 + nverts );
mIB.push_back( idx2 + nverts );
mIB.push_back( idx1 + nverts );
}
// construct side caps. To conserve the geometry amount,
// treat them as a single smoothing group.
assert( nverts == piece.getVertexCount() );
for( i = 0; i < nverts; ++i ) {
int oldIdx0 = piece.getPolygon()[i];
int oldIdx1 = piece.getPolygon()[(i+1)%nverts];
int oldIdx2 = piece.getPolygon()[(i+nverts-1)%nverts];
int idx0 = vertRemap[oldIdx0];
int idx1 = vertRemap[oldIdx1];
int idx2 = vertRemap[oldIdx2];
assert( idx0 >= 0 && idx0 < nverts );
assert( idx1 >= 0 && idx1 < nverts );
assert( idx2 >= 0 && idx2 < nverts );
SVertexXyzNormal v0 = mVB[idx0];
SVertexXyzNormal v1 = v0;
v1.p.z = -v1.p.z;
const SVertexXyzNormal& vnear1 = mVB[idx1];
const SVertexXyzNormal& vnear2 = mVB[idx2];
SVector3 edge1 = vnear2.p - vnear1.p;
SVector3 edge2 = v1.p - v0.p;
SVector3 normal = edge1.cross( edge2 ).getNormalized();
v0.n = v1.n = normal;
mVB.push_back( v0 );
mVB.push_back( v1 );
int ibidx0 = nverts*2 + i*2 + 0;
int ibidx1 = nverts*2 + i*2 + 1;
int ibidx2 = nverts*2 + ((i+1)%nverts)*2 + 0;
int ibidx3 = nverts*2 + ((i+1)%nverts)*2 + 1;
mIB.push_back( ibidx0 );
mIB.push_back( ibidx2 );
mIB.push_back( ibidx1 );
mIB.push_back( ibidx1 );
mIB.push_back( ibidx2 );
mIB.push_back( ibidx3 );
}
// construct initial mMatrix
mMatrix.identify();
mMatrix = w.getMatrix();
mMatrix.getOrigin() += mMatrix.getAxisX() * pcenter.x;
mMatrix.getOrigin() += mMatrix.getAxisY() * pcenter.y;
mSize.set( piece.getAABB().getSize().x, piece.getAABB().getSize().y, HALF_THICK*2 );
}
void CWallPiece3D::preRender( int& vbcount, int& ibcount ) const
{
vbcount = mVB.size();
ibcount = mIB.size();
}
void CWallPiece3D::render( const SMatrix4x4& matrix, TPieceVertex* vb, unsigned short* ib, int baseIndex, int& vbcount, int& ibcount, BYTE alpha ) const
{
int i;
// VB
const SVertexXyzNormal* srcVB = &mVB[0];
vbcount = mVB.size();
for( i = 0; i < vbcount; ++i ) {
SVector3 p, n;
D3DXVec3TransformCoord( &p, &srcVB->p, &matrix );
D3DXVec3TransformNormal( &n, &srcVB->n, &matrix );
vb->p = p;
DWORD ncol = gVectorToColor( n );
ncol |= (alpha<<24);
vb->diffuse = ncol;
++srcVB;
++vb;
}
// IB
const int* srcIB = &mIB[0];
ibcount = mIB.size();
for( i = 0; i < ibcount; ++i ) {
int idx = *srcIB + baseIndex;
assert( idx >= 0 && idx < 64000 );
*ib = idx;
++srcIB;
++ib;
}
}
// --------------------------------------------------------------------------
namespace polygon_merger {
int polygonCount;
typedef std::set<int> TIntSet;
TIntSet vertices;
TIntSet borderVertices;
typedef std::map< int, TIntVector > TIntIntsMap;
TIntIntsMap vertexNexts;
TIntIntsMap vertexPrevs;
TIntVector vertexUseCount;
TIntVector vertexTraceID;
enum eVertexType {
VTYPE_NONE, ///< Not computed yet
VTYPE_INTERIOR, ///< Completely interior
VTYPE_SINGLE, ///< On the border, belongs to single polygon
VTYPE_MULTI, ///< On the border, belongs to multiple polygons
VTYPE_DONE, ///< Already fully processed (traced into result polygon)
};
TIntVector vertexTypes;
bool isVertexInterior( int idx )
{
assert( idx >= 0 && idx < vertexUseCount.size() );
// vertex is interior if it's use count is >1, AND
// it's all neighbors' use counts are >1, AND it has exactly "usecount"
// different neighbors.
int useCount = vertexUseCount[idx];
assert( useCount >= 1 );
if( useCount < 2 )
return false;
TIntIntsMap::const_iterator it;
int i, n;
it = vertexNexts.find( idx );
assert( it != vertexNexts.end() );
const TIntVector& vnext = it->second;
n = vnext.size();
assert( n == useCount );
for( i = 0; i < n; ++i ) {
if( vertexUseCount[vnext[i]] < 2 )
return false;
}
it = vertexPrevs.find( idx );
assert( it != vertexPrevs.end() );
const TIntVector& vprev = it->second;
n = vprev.size();
assert( n == useCount );
for( i = 0; i < n; ++i ) {
int nidx = vprev[i];
if( vertexUseCount[nidx] < 2 )
return false;
if( std::find( vnext.begin(), vnext.end(), nidx ) == vnext.end() )
return false;
}
return true; // fall through: must be interior
}
void markVertexTypes()
{
TIntSet::const_iterator vit, vitEnd = vertices.end();
// first pass: mark all interior and single-border vertices
for( vit = vertices.begin(); vit != vitEnd; ++vit ) {
int idx = *vit;
if( vertexUseCount[idx] == 1 ) {
vertexTypes[idx] = VTYPE_SINGLE;
borderVertices.insert( idx );
} else if( isVertexInterior(idx) )
vertexTypes[idx] = VTYPE_INTERIOR;
}
// now, the unmarked vertices are all shared and on border
for( vit = vertices.begin(); vit != vitEnd; ++vit ) {
int idx = *vit;
if( vertexTypes[idx] == VTYPE_NONE ) {
vertexTypes[idx] = VTYPE_MULTI;
borderVertices.insert( idx );
}
}
}
int getBorderIndex()
{
if( borderVertices.empty() )
return -1;
return *borderVertices.begin();
}
void traceBorder( const TWallVertexVector& vb, TIntVector& polygon, TIntVector& ib )
{
static int traceID = 0;
++traceID;
int idx0 = getBorderIndex();
assert( idx0 >= 0 && idx0 < vertexTypes.size() );
ib.resize( 0 );
polygon.resize( 0 );
polygon.reserve( vertices.size()/2 );
TIntVector localPolygon;
localPolygon.reserve( 128 );
TIntVector localIB;
localIB.reserve( 128 );
int idxPrev = idx0;
int idx = idx0;
int debugCounter = 0;
int debugLoopCounter = 0;
do {
localIB.resize( 0 );
bool willFormLoop;
do{
localPolygon.push_back( idx );
borderVertices.erase( idx );
vertexTraceID[idx] = traceID;
assert( ++debugCounter <= vertices.size()*2 );
// Next vertex is the neighbor of current, that is not interior
// and that is not the previous one.
// When there are many possible ones, trace based on angle.
int idxNext = -1;
SVector2 prevToCurr = vb[idx] - vb[idxPrev];
if( prevToCurr.lengthSq() < 1.0e-6f )
prevToCurr.set( -0.01f, -0.01f );
TIntIntsMap::const_iterator it;
it = vertexNexts.find( idx );
assert( it != vertexNexts.end() );
const TIntVector& vnext = it->second;
int n = vnext.size();
float bestAngle = 100.0f;
for( int i = 0; i < n; ++i ) {
int idx1 = vnext[i];
if( idx1 != idxPrev && vertexTypes[idx1] != VTYPE_INTERIOR ) {
//if( idx1 != idxPrev ) {
SVector2 currToNext = vb[idx1] - vb[idx];
float ang = signedAngle2D( prevToCurr, currToNext );
if( ang < bestAngle ) {
bestAngle = ang;
idxNext = idx1;
}
}
}
assert( bestAngle > -4.0f && bestAngle < 4.0f );
assert( idxNext >= 0 );
willFormLoop = (vertexTraceID[idxNext] == traceID);
// Optimization: if best angle is zero, then we're walking
// in a straight line. Optimize out the current vertex.
if( bestAngle == 0.0f && idx != idx0 && !willFormLoop ) {
localPolygon.pop_back();
}
idxPrev = idx;
idx = idxNext;
} while( !willFormLoop );
assert( localPolygon.size() >= 3 );
//if( localPolygon.size() < 3 ) {
// return;
//}
assert( ++debugLoopCounter < vertices.size() );
if( idx == idx0 ) {
// The polygon is simple or we found the last loop.
// Triangulate local and append to results.
triangulator::process( vb, localPolygon, localIB );
polygon.insert( polygon.end(), localPolygon.begin(), localPolygon.end() );
ib.insert( ib.end(), localIB.begin(), localIB.end() );
// We can have separated other loops. Try fetching them as well.
idx0 = getBorderIndex();
if( idx0 == -1 ) {
return;
} else {
localPolygon.resize( 0 );
idxPrev = idx0;
idx = idx0;
}
} else {
// The polygon must be complex, and we just found a closed loop.
// Take only the loop, triangulate it, append to results, continue.
TIntVector::const_iterator itLoopStart =
std::find( localPolygon.begin(), localPolygon.end(), idx );
assert( itLoopStart != localPolygon.end() );
// append to results
TIntVector loopPolygon( itLoopStart, localPolygon.end() );
triangulator::process( vb, loopPolygon, localIB );
polygon.insert( polygon.end(), loopPolygon.begin(), loopPolygon.end() );
ib.insert( ib.end(), localIB.begin(), localIB.end() );
// continue - remove the looped polygon from local
localPolygon.resize( itLoopStart - localPolygon.begin() );
}
} while( true );
}
void begin( int totalVerts )
{
polygonCount = 0;
vertices.clear();
borderVertices.clear();
vertexNexts.clear();
vertexPrevs.clear();
vertexUseCount.resize( 0 );
vertexUseCount.resize( totalVerts, 0 );
vertexTraceID.resize( totalVerts, -1 );
vertexTypes.resize( 0 );
vertexTypes.resize( totalVerts, VTYPE_NONE );
}
void addPolygon( const TIntVector& ib )
{
++polygonCount;
TIntVector::const_iterator vit, vitEnd = ib.end();
for( vit = ib.begin(); vit != vitEnd; ++vit ) {
int idx = *vit;
assert( idx >= 0 && idx < vertexUseCount.size() );
vertices.insert( idx );
++vertexUseCount[idx];
int idxNext = (vit==vitEnd-1) ? ib.front() : *(vit+1);
int idxPrev = (vit==ib.begin()) ? ib.back() : *(vit-1);
vertexNexts[idx].push_back( idxNext );
vertexPrevs[idx].push_back( idxPrev );
}
}
void end( const TWallVertexVector& vb, TIntVector& polygon, TIntVector& ib )
{
assert( polygonCount );
if( polygonCount == 1 ) {
// trivial case, just output input polygon
polygon.resize( 0 );
polygon.reserve( vertices.size() );
int idx0 = *vertices.begin();
int idx = idx0;
do {
polygon.push_back( idx );
const TIntVector& vnext = vertexNexts[idx];
assert( vnext.size() == 1 );
idx = vnext[0];
} while( idx != idx0 );
triangulator::process( vb, polygon, ib );
} else {
// mark vertex types
markVertexTypes();
// trace and triangulate the polygon(s)
traceBorder( vb, polygon, ib );
}
}
}; // namespace polygon_merger
// --------------------------------------------------------------------------
CWallPieceCombined* CWallPieceCombined::mInitPiece = NULL;
const CWall3D* CWallPieceCombined::mInitWall = NULL;
bool CWallPieceCombined::mInitRoot = false;
void CWallPieceCombined::initBegin( const CWall3D& w, TWallQuadNode* quadnode, bool root )
{
assert( !mInitPiece );
assert( !mInitWall );
assert( mVB.empty() );
assert( mIB.empty() );
mInitPiece = this;
mInitWall = &w;
mInitRoot = root;
mQuadNode = quadnode;
mRenderID = -1;
if( !mInitRoot )
polygon_merger::begin( w.getWall2D().getVerts().size() );
else {
mBounds.getMin().set( 0, 0 );
mBounds.getMax() = w.getWall2D().getSize();
mCombinedPieces.reserve( w.getWall2D().getPieceCount() );
}
}
void CWallPieceCombined::initAddPiece( int idx )
{
mCombinedPieces.push_back( idx );
if( !mInitRoot ) {
const CWallPiece2D& piece = mInitWall->getWall2D().getPiece(idx);
polygon_merger::addPolygon( piece.getPolygonVector() );
mBounds.extend( piece.getAABB() );
}
}
void CWallPieceCombined::initEnd( TWallQuadNode* quadtree )
{
assert( mInitPiece == this );
assert( mInitWall );
// if we're root, just construct the full-wall quad
if( mInitRoot ) {
assert( mQuadNode == quadtree );
mVB.resize( 4 );
mIB.resize( 6 );
const SVector2& bmin = mBounds.getMin();
const SVector2& bmax = mBounds.getMax();
// VB
const SMatrix4x4& mat = mInitWall->getMatrix();
{
DWORD nrmCol = gVectorToColor( mat.getAxisZ() );
SVertexXyzDiffuse vtx;
vtx.p.set( bmin.x, bmin.y, 0 );
D3DXVec3TransformCoord( &vtx.p, &vtx.p, &mat );
vtx.diffuse = nrmCol;
mVB[0] = vtx;
vtx.p.set( bmin.x, bmax.y, 0 );
D3DXVec3TransformCoord( &vtx.p, &vtx.p, &mat );
vtx.diffuse = nrmCol;
mVB[1] = vtx;
vtx.p.set( bmax.x, bmin.y, 0 );
D3DXVec3TransformCoord( &vtx.p, &vtx.p, &mat );
vtx.diffuse = nrmCol;
mVB[2] = vtx;
vtx.p.set( bmax.x, bmax.y, 0 );
D3DXVec3TransformCoord( &vtx.p, &vtx.p, &mat );
vtx.diffuse = nrmCol;
mVB[3] = vtx;
}
// IB
{
mIB[0] = 0;
mIB[1] = 1;
mIB[2] = 2;
mIB[3] = 1;
mIB[4] = 3;
mIB[5] = 2;
}
mVBSizeNoCaps = mVB.size();
mIBSizeNoCaps = mIB.size();
} else {
// for non-roots, construct proper polygon
const TWallVertexVector& wallVerts = mInitWall->getWall2D().getVerts();
// merge the polygons
TIntVector polygon;
TIntVector ibFront;
polygon_merger::end( wallVerts, polygon, ibFront );
static TIntVector vertRemap;
vertRemap.resize(0);
vertRemap.resize( wallVerts.size(), -1 );
int i;
int nidx = ibFront.size();
mIB.reserve( nidx + polygon.size()*6 );
mVB.reserve( polygon.size()*3 );
// construct the front side
for( i = 0; i < nidx; ++i ) {
int oldIdx = ibFront[i];
int newIdx = vertRemap[oldIdx];
if( newIdx < 0 ) {
newIdx = mVB.size();
vertRemap[oldIdx] = newIdx;
SVector2 pos = wallVerts[oldIdx];
SVector3 pos3( pos.x, pos.y, 0.0f );
D3DXVec3TransformCoord( &pos3, &pos3, &mInitWall->getMatrix() );
SVertexXyzDiffuse vtx;
vtx.p = pos3;
vtx.diffuse = gVectorToColor( mInitWall->getMatrix().getAxisZ() );
mVB.push_back( vtx );
}
mIB.push_back( newIdx );
}
// reverse the ordering of triangles
for( i = 0; i < nidx/3; ++i ) {
int iii = mIB[i*3+1];
mIB[i*3+1] = mIB[i*3+2];
mIB[i*3+2] = iii;
}
mVBSizeNoCaps = mVB.size();
mIBSizeNoCaps = mIB.size();
// Don't construct the side caps for non-leaf pieces.
// I think they never can be seen (not sure)
if( !mQuadNode ) {
int nverts = mVB.size();
int npolygon = polygon.size();
// Construct side caps. To conserve the geometry amount,
// treat them as a single smoothing group.
for( i = 0; i < nverts; ++i ) {
int oldIdx0 = polygon[i];
int oldIdx1 = polygon[(i+1)%npolygon];
int oldIdx2 = polygon[(i+nverts-1)%npolygon];
int idx0 = vertRemap[oldIdx0];
int idx1 = vertRemap[oldIdx1];
int idx2 = vertRemap[oldIdx2];
assert( idx0 >= 0 && idx0 < nverts );
assert( idx1 >= 0 && idx1 < nverts );
assert( idx2 >= 0 && idx2 < nverts );
SVertexXyzDiffuse v0 = mVB[idx0];
SVertexXyzDiffuse v1 = v0;
v1.p -= mInitWall->getMatrix().getAxisZ() * (HALF_THICK*2);
const SVertexXyzDiffuse& vnear1 = mVB[idx1];
const SVertexXyzDiffuse& vnear2 = mVB[idx2];
SVector3 edge1 = vnear2.p - vnear1.p;
SVector3 edge2 = v1.p - v0.p;
SVector3 normal = edge1.cross( edge2 ).getNormalized();
v0.diffuse = v1.diffuse = gVectorToColor( normal );
mVB.push_back( v0 );
mVB.push_back( v1 );
int ibidx0 = i*2 + 0;
int ibidx1 = i*2 + 1;
int ibidx2 = ((i+1)%nverts)*2 + 0;
int ibidx3 = ((i+1)%nverts)*2 + 1;
mIB.push_back( ibidx0 );
mIB.push_back( ibidx2 );
mIB.push_back( ibidx1 );
mIB.push_back( ibidx1 );
mIB.push_back( ibidx2 );
mIB.push_back( ibidx3 );
}
}
}
if( !mQuadNode ) {
assert( mCombinedPieces.size()==1 );
TWallQuadNode* node = quadtree->getNode( mBounds );
assert( node );
while( node ) {
node->getData().leafs.push_back( this );
node = node->getParent();
}
} else {
// record ourselves in the quadtree
assert( !mQuadNode->getData().combined );
mQuadNode->getData().combined = this;
}
mInitPiece = NULL;
mInitWall = NULL;
}
void CWallPieceCombined::preRenderSides( int& vbcount, int& ibcount ) const
{
vbcount = mVBSizeNoCaps;
ibcount = mIBSizeNoCaps;
}
void CWallPieceCombined::preRenderCaps( int& vbcount, int& ibcount ) const
{
vbcount = mVB.size() - mVBSizeNoCaps;
ibcount = mIB.size() - mIBSizeNoCaps;
}
void CWallPieceCombined::renderSides( TPieceVertex* vb, unsigned short* ib, int baseIndex, int& vbcount, int& ibcount ) const
{
int i;
preRenderSides( vbcount, ibcount );
// VB
const SVertexXyzDiffuse* srcVB = &mVB[0];
for( i = 0; i < vbcount; ++i ) {
vb->p = srcVB->p;
vb->diffuse = srcVB->diffuse;
++srcVB;
++vb;
}
// IB
const int* srcIB = &mIB[0];
for( i = 0; i < ibcount; ++i ) {
int idx = *srcIB + baseIndex;
assert( idx >= 0 && idx < 64000 );
*ib = idx;
++srcIB;
++ib;
}
}
void CWallPieceCombined::renderCaps( TPieceVertex* vb, unsigned short* ib, int baseIndex, int& vbcount, int& ibcount ) const
{
int i;
preRenderCaps( vbcount, ibcount );
// VB
const SVertexXyzDiffuse* srcVB = &mVB[mVBSizeNoCaps];
for( i = 0; i < vbcount; ++i ) {
vb->p = srcVB->p;
vb->diffuse = srcVB->diffuse;
++srcVB;
++vb;
}
// IB
const int* srcIB = &mIB[mIBSizeNoCaps];
for( i = 0; i < ibcount; ++i ) {
int idx = *srcIB + baseIndex;
assert( idx >= 0 && idx < 64000 );
*ib = idx;
++srcIB;
++ib;
}
}
// --------------------------------------------------------------------------
CWall3D::CWall3D( const SVector2& size, float smallestElemSize, const char* reflTextureID, const char* restoreTextureID )
: mWall2D(size,smallestElemSize)
, mPieces3D(NULL)
, mFracturedPieces(NULL)
, mPieceRestoreTimes(NULL)
, mQuadtree(NULL)
, mPiecesInited(false)
, mNeedsRenderingIntoVB(false)
{
mMatrix.identify();
int i;
for( i = 0; i < RMCOUNT; ++i ) {
mRenderables[i] = NULL;
}
mRenderables[RM_NORMAL] = new CRenderableIndexedBuffer( NULL, 0 );
mRenderables[RM_NORMAL]->getParams().setEffect( *RGET_FX( restoreTextureID ? "wall_DnSR" : "wall_DnR" ) );
mRenderables[RM_NORMAL]->getParams().addTexture( "tShadow", *RGET_S_TEX(RT_SHADOWBLUR) );
mRenderables[RM_NORMAL]->getParams().addVector3( "vLightPos", LIGHT_POS_1 + LIGHT_WOFF );
if( reflTextureID ) {
mRenderables[RM_NORMAL]->getParams().addTexture( "tRefl", *RGET_S_TEX(reflTextureID) );
}
mRenderables[RM_REFLECTED] = new CRenderableIndexedBuffer( NULL, 0 );
mRenderables[RM_REFLECTED]->getParams().setEffect( *RGET_FX( restoreTextureID ? "wall_DnS" : "wall_Dn" ) );
mRenderables[RM_REFLECTED]->getParams().addTexture( "tShadow", *RGET_S_TEX(RT_SHADOWBLUR) );
mRenderables[RM_REFLECTED]->getParams().addVector3( "vLightPos", LIGHT_POS_1 + LIGHT_WOFF );
if( restoreTextureID ) {
mFadeInMesh = new CMeshEntity( "FadeInMesh", "billboard" );
if( reflTextureID ) {
mFadeInMesh->getRenderMesh( RM_NORMAL )->getParams().addTexture( "tRefl", *RGET_S_TEX(reflTextureID) );
}
mResTimeGrid = new float[RESGRID_X*RESGRID_Y];
for( i = 0; i < RESGRID_X*RESGRID_Y; ++i ) {
mResTimeGrid[i] = -1.0f;
}
mRestoreTexture = RGET_S_TEX(restoreTextureID);
} else {
mFadeInMesh = NULL;
mResTimeGrid = NULL;
mRestoreTexture = NULL;
}
}
CWall3D::~CWall3D()
{
for( int i = 0; i < RMCOUNT; ++i ) {
safeDelete( mRenderables[i] );
}
safeDelete( mFadeInMesh );
stl_utils::wipe( mPiecesCombined );
safeDeleteArray( mPieces3D );
safeDeleteArray( mFracturedPieces );
safeDeleteArray( mPieceRestoreTimes );
safeDeleteArray( mQuadtree );
safeDeleteArray( mResTimeGrid );
}
void CWall3D::initPieces()
{
//cputimer::debug_interval tt0( "w3d init" );
assert( !mPiecesInited );
assert( !mFracturedPieces );
assert( !mPieces3D );
assert( mPiecesCombined.empty() );
const int QUADTREE_DEPTH = 2;
//const int QUADTREE_DEPTH = 3;
mQuadtree = TWallQuadNode::create( SVector2(0,0), mWall2D.getSize(), QUADTREE_DEPTH, &mQuadtreeNodeCount );
int i;
int n = mWall2D.getPieceCount();
mPieces3D = new CWallPiece3D[n];
mFracturedPieces = new bool[n];
mPieceRestoreTimes = new float[n];
// init the leaf pieces
for( i = 0; i < n; ++i ) {
mPieces3D[i].init( *this, i );
mFracturedPieces[i] = false;
mPieceRestoreTimes[i] = -1.0f;
CWallPieceCombined* wpc = new CWallPieceCombined();
wpc->initBegin( *this, NULL, false );
wpc->initAddPiece( i );
wpc->initEnd( mQuadtree );
mPiecesCombined.push_back( wpc );
}
// go through quadtree nodes and merge the pieces
n = mQuadtreeNodeCount;
for( i = 0; i < n; ++i ) {
TWallQuadNode& node = mQuadtree[i];
assert( !node.getData().combined );
int npc = node.getData().leafs.size();
if( npc > 0 ) {
CWallPieceCombined* wpc = new CWallPieceCombined();
wpc->initBegin( *this, &node, i==0 );
for( int j = 0; j < npc; ++j )
wpc->initAddPiece( node.getData().leafs[j]->getLeafIndex() );
wpc->initEnd( mQuadtree );
mPiecesCombined.push_back( wpc );
}
}
// init fade-in mesh
if( mFadeInMesh ) {
SMatrix4x4 m = mMatrix;
m.getOrigin() += m.getAxisX() * (mWall2D.getSize().x*0.5f);
m.getOrigin() += m.getAxisY() * (mWall2D.getSize().y*0.5f);
m.getOrigin() += m.getAxisZ() * (-HALF_THICK);
m.getAxisX() *= mWall2D.getSize().x * -1.01f;
m.getAxisY() *= mWall2D.getSize().y * 1.01f;
mFadeInMesh->mWorldMat = m;
mFadeInMesh->addLightToParams( LIGHT_POS_1 + LIGHT_WOFF );
for( i = 0; i < RMCOUNT; ++i ) {
CRenderableMesh* r = mFadeInMesh->getRenderMesh(eRenderMode(i));
if( !r )
continue;
r->getParams().addVector3( "vNormal", m.getAxisZ() );
r->getParams().addTexture( "tAlpha", *mRestoreTexture );
}
}
// init AABB
mWorldAABB.extend( SVector3(0,0,-HALF_THICK*2), 0.1f );
mWorldAABB.extend( SVector3(mWall2D.getSize().x,mWall2D.getSize().y,HALF_THICK*2), 0.1f );
mWorldAABB.transform( mMatrix );
mPiecesInited = true;
mNeedsRenderingIntoVB = true;
mNeedsRenderFadeMesh = true;
}
bool CWall3D::intersectRay( const SLine3& ray, float& t ) const
{
SPlane plane;
D3DXPlaneFromPointNormal( &plane, &mMatrix.getOrigin(), &mMatrix.getAxisZ() );
SVector3 pt;
if( !plane.intersect( ray, pt ) ) {
return false;
}
t = ray.project( pt );
if( t < 0 )
return false;
return true;
}
void CWall3D::fracturePiecesInSphere( float t, const SVector3& pos, float radius, TIntVector& pcs,
float restoreAfter, float restoreDuration, bool noRestore )
{
if( !mPiecesInited )
initPieces();
pcs.resize( 0 );
// to local space
SVector3 locPos;
D3DXVec3TransformCoord( &locPos, &pos, &mInvMatrix );
if( locPos.z < -radius || locPos.z > radius )
return;
// remember restore times
if( mResTimeGrid && !noRestore ) {
float rad = radius*2.0f;
float lx1 = (locPos.x - rad) / mWall2D.getSize().x * RESGRID_X;
float lx2 = (locPos.x + rad) / mWall2D.getSize().x * RESGRID_X;
float ly1 = (locPos.y - rad) / mWall2D.getSize().y * RESGRID_Y;
float ly2 = (locPos.y + rad) / mWall2D.getSize().y * RESGRID_Y;
int ix1 = (int)clamp( lx1, 0, RESGRID_X-1 );
int ix2 = (int)clamp( lx2, 0, RESGRID_X-1 );
int iy1 = (int)clamp( ly1, 0, RESGRID_Y-1 );
int iy2 = (int)clamp( ly2, 0, RESGRID_Y-1 );
float dx = mWall2D.getSize().x / RESGRID_X;
float dy = mWall2D.getSize().y / RESGRID_Y;
for( int iy = iy1; iy <= iy2; ++iy ) {
float* resval = mResTimeGrid + RESGRID_X*iy + ix1;
float fy = iy * dy;
for( int ix = ix1; ix <= ix2; ++ix, ++resval ) {
float fx = ix * dx;
// don't touch restore grid outside the circle
float diffX = fx-locPos.x;
float diffY = fy-locPos.y;
float diffR2 = diffX*diffX + diffY*diffY;
if( diffR2 > rad*rad )
continue;
// restore time for this grid point - start at
// t+restoreAfter at circle boundaries, later at circle
// center
float resTime = t + restoreAfter + (1.0f-diffR2/(rad*rad)) * restoreDuration;
if( *resval < 0.0f )
*resval = resTime;
else
*resval = max( (*resval), resTime );
}
}
}
// fetch the pieces
float pieceRestoreTime;
if( noRestore ) {
pieceRestoreTime = t + 1.0e9f;
} else {
pieceRestoreTime = t + restoreAfter + restoreDuration;
}
// TODO: optimize, right now linear search!
int n = mWall2D.getPieceCount();
for( int i = 0; i < n; ++i ) {
const CWallPiece2D& p = mWall2D.getPiece( i );
SVector2 c = p.getAABB().getCenter();
SVector3 tocenter = locPos - SVector3(c.x,c.y,0);
if( tocenter.lengthSq() < radius*radius ) {
mPieceRestoreTimes[i] = pieceRestoreTime;
if( mFracturedPieces[i] )
continue;
pcs.push_back( i );
fractureOutPiece( i );
}
}
}
void CWall3D::fracturePiecesInYRange( float t, float y1, float y2, TIntVector& pcs )
{
if( !mPiecesInited )
initPieces();
// fetch the pieces
pcs.resize( 0 );
// TODO: optimize, right now linear search!
float pieceRestoreTime = t + 1.0e6f;
int n = mWall2D.getPieceCount();
for( int i = 0; i < n; ++i ) {
const CWallPiece2D& p = mWall2D.getPiece( i );
SVector2 c = p.getAABB().getCenter();
float y = c.y;
if( mMatrix.getAxisY().y < 0.5f ) {
SVector3 wc;
D3DXVec3TransformCoord( &wc, &SVector3(c.x,c.y,0), &mMatrix );
y = wc.y;
}
if( y >= y1 && y <= y2 ) {
mPieceRestoreTimes[i] = pieceRestoreTime;
if( mFracturedPieces[i] )
continue;
pcs.push_back( i );
fractureOutPiece( i );
}
}
}
void CWall3D::fractureOutPiece( int index )
{
assert( index >= 0 && index < mWall2D.getPieceCount() );
assert( !mFracturedPieces[index] );
mFracturedPieces[index] = true;
mNeedsRenderingIntoVB = true;
// mark as fractured in quadtree
TWallQuadNode* node = mQuadtree->getNode( mWall2D.getPiece(index).getAABB() );
while( node ) {
++node->getData().fracturedOutCounter;
node = node->getParent();
}
}
void CWall3D::fractureInPiece( int index )
{
assert( index >= 0 && index < mWall2D.getPieceCount() );
assert( mFracturedPieces[index] );
mFracturedPieces[index] = false;
mPieceRestoreTimes[index] = -1.0f;
mNeedsRenderingIntoVB = true;
// mark as non fractured in quadtree
TWallQuadNode* node = mQuadtree->getNode( mWall2D.getPiece(index).getAABB() );
while( node ) {
--node->getData().fracturedOutCounter;
assert( node->getData().fracturedOutCounter >= 0 );
node = node->getParent();
}
}
void CWall3D::restoreAll()
{
// restore all pieces
int n = mWall2D.getPieceCount();
for( int i = 0; i < n; ++i ) {
if( mFracturedPieces[i] )
fractureInPiece( i );
}
}
void CWall3D::update( float t )
{
if( !mPiecesInited )
initPieces();
// update restoration texture
if( mRestoreTexture ) {
const float RESTORE_FADE_TIME = 0.2f;
bool hadZeros = false;
bool had255s = false;
bool hadOthers = false;
D3DLOCKED_RECT lr;
mRestoreTexture->getObject()->LockRect( 0, &lr, NULL, D3DLOCK_DISCARD );
BYTE* texptr = (BYTE*)lr.pBits;
float* resval = mResTimeGrid;
for( int iy = 0; iy < RESGRID_Y; ++iy ) {
for( int ix = 0; ix < RESGRID_X; ++ix, ++resval ) {
BYTE v;
float rt = *resval;
if( rt < 0.0f ) {
v = 255;
hadZeros = true;
} else if( t <= rt - RESTORE_FADE_TIME ) {
v = 0;
hadZeros = true;
} else {
float alpha = (t-rt+RESTORE_FADE_TIME) / RESTORE_FADE_TIME;
if( alpha >= 1.0f ) {
// fully restored
v = 255;
*resval = -1.0f;
had255s = true;
} else {
v = int(alpha*255);
hadOthers = true;
}
}
texptr[ix] = v;
}
texptr += lr.Pitch;
}
mRestoreTexture->getObject()->UnlockRect( 0 );
mNeedsRenderFadeMesh = (hadOthers) || (hadZeros && had255s);
// restore needed pieces
int n = mWall2D.getPieceCount();
for( int i = 0; i < n; ++i ) {
if( mFracturedPieces[i] && t>=mPieceRestoreTimes[i] )
fractureInPiece( i );
}
}
}
bool CWall3D::renderIntoVB()
{
mNeedsRenderingIntoVB = false;
int nverts = 0, nindices = 0;
mVBChunk = NULL;
mIBChunk = NULL;
int i;
// render process:
//
// 1) go through quadtree, for each node that has no fractured out
// pieces inside (or it's children), render the combined piece and
// mark the node and all combined leaf pieces as rendered. Skip the nodes
// that have their parent rendered.
//
// 2) render the remaining leaf pieces.
static int renderID = 0;
++renderID;
std::vector<const CWallPieceCombined*> piecesToRender;
piecesToRender.reserve( 256 );
int nnodes = mQuadtreeNodeCount;
for( i = 0; i < nnodes; ++i )
{
TWallQuadNode& node = mQuadtree[i];
SWallQuadData& data = node.getData();
data.alreadyRendered = false;
// if we have fractured out pieces somewhere inside, skip
if( data.fracturedOutCounter > 0 )
continue;
// if we have no combined, skip
if( !data.combined )
continue;
// if parent already rendered the combined piece, skip
bool parentRendered = false;
const TWallQuadNode* nodePar = node.getParent();
while( nodePar ) {
if( nodePar->getData().alreadyRendered ) {
parentRendered = true;
break;
}
nodePar = nodePar->getParent();
}
data.alreadyRendered = true;
if( parentRendered )
continue;
// render the combined piece
piecesToRender.push_back( data.combined );
data.alreadyRendered = true;
// mark the combined pieces as rendered
int npcs = data.leafs.size();
for( int j = 0; j < npcs; ++j ) {
CWallPieceCombined* pcleaf = data.leafs[j];
pcleaf->markRendered( renderID );
}
}
int npieces = mWall2D.getPieceCount();
for( i = 0; i < npieces; ++i )
{
if( mFracturedPieces[i] )
continue;
CWallPieceCombined* pcleaf = mPiecesCombined[i];
if( pcleaf->isRendered( renderID ) )
continue;
// not rendered yet, add to render list
piecesToRender.push_back( pcleaf );
pcleaf->markRendered( renderID );
}
//
// accumulate total vertex/index counts
int n = piecesToRender.size();
for( i = 0; i < n; ++i )
{
const CWallPieceCombined& pc = *piecesToRender[i];
int nvb, nib;
pc.preRenderSides( nvb, nib );
nverts += nvb;
nindices += nib;
}
int nvertsNoCaps = nverts;
int nindicesNoCaps = nindices;
for( i = 0; i < n; ++i )
{
const CWallPieceCombined& pc = *piecesToRender[i];
int nvb, nib;
pc.preRenderCaps( nvb, nib );
nverts += nvb;
nindices += nib;
}
gWallVertCount += nverts;
gWallTriCount += nindices/3;
if( !nverts || !nindices )
return false;
// lock and render
assert( nindices < 64000 );
mVBChunk = CDynamicVBManager::getInstance().allocateChunk( nverts, sizeof(TPieceVertex) );
mIBChunk = CDynamicIBManager::getInstance().allocateChunk( nindices, 2 );
TPieceVertex* vb = (TPieceVertex*)mVBChunk->getData();
unsigned short* ib = (unsigned short*)mIBChunk->getData();
int baseIndex = 0;
for( i = 0; i < n; ++i ) {
int nvb, nib;
const CWallPieceCombined& pc = *piecesToRender[i];
pc.renderSides( vb, ib, baseIndex, nvb, nib );
baseIndex += nvb;
vb += nvb;
ib += nib;
}
for( i = 0; i < n; ++i ) {
int nvb, nib;
const CWallPieceCombined& pc = *piecesToRender[i];
pc.renderCaps( vb, ib, baseIndex, nvb, nib );
baseIndex += nvb;
vb += nvb;
ib += nib;
}
mVBChunk->unlock();
mIBChunk->unlock();
// setup renderables
CD3DVertexDecl* vdecl = RGET_VDECL( CVertexFormat( CVertexFormat::V_POSITION | CVertexFormat::COLOR_MASK ) );
for( i = 0; i < RMCOUNT; ++i )
{
if( mRenderables[i] ) {
bool noSideCaps = (i == RM_REFLECTED);
mRenderables[i]->resetVBs();
mRenderables[i]->setVB( mVBChunk->getBuffer(), 0 );
mRenderables[i]->setStride( mVBChunk->getStride(), 0 );
mRenderables[i]->setBaseVertex( mVBChunk->getOffset() );
mRenderables[i]->setMinVertex( 0 );
mRenderables[i]->setNumVertices( noSideCaps ? nvertsNoCaps : nverts );
mRenderables[i]->setIB( mIBChunk->getBuffer() );
mRenderables[i]->setStartIndex( mIBChunk->getOffset() );
mRenderables[i]->setPrimCount( (noSideCaps ? nindicesNoCaps : nindices) / 3 );
mRenderables[i]->setPrimType( D3DPT_TRIANGLELIST );
mRenderables[i]->setVertexDecl( vdecl );
}
}
return true;
}
void CWall3D::render( eRenderMode rm )
{
if( mFadeInMesh && mNeedsRenderFadeMesh )
mFadeInMesh->render( rm );
CRenderable* r = mRenderables[rm];
if( !r )
return;
if( mNeedsRenderingIntoVB ||
!mVBChunk || !mVBChunk->isValid() ||
!mIBChunk || !mIBChunk->isValid() )
{
renderIntoVB();
}
G_RENDERCTX->attach( *r );
}
| [
"nearaz@73827abb-88f4-0310-91e6-a2b8c1a3e93d"
] | [
[
[
1,
1315
]
]
] |
f31b5382e45d46ca05ea71d0b6326ffb784c9ff9 | 105cc69f4207a288be06fd7af7633787c3f3efb5 | /HovercraftUniverse/HovercraftUniverse/MainMenuState.cpp | 7bdfb0136ffb06cdcd170f816e53722d8f52c3b3 | [] | 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 | 6,841 | cpp | #include "MainMenuState.h"
#include "InGameState.h"
#include "LobbyState.h"
#include "HUClient.h"
#include <tinyxml/tinyxml.h>
#include <boost/thread/thread_time.hpp>
#include <HovSound.h>
#include <NMessageBox.h>
namespace HovUni {
MainMenuState::MainMenuState() : mMenu(0), mContinue(true), mLastGUIUpdate(-1), mConnectionThread(0), mConnectionFinished(false) {
}
MainMenuState::~MainMenuState() {
delete mConnectionThread;
delete mMenu;
}
void MainMenuState::onConnect(const Ogre::String& address, ConnectListener* listener) {
//Connect to the given address
///////////////////////////////////////////
///////////////////////////////////////////
//TODO: Parse IP and Port?
HUClient* mClient = new HUClient(address.c_str());
LobbyState* newState = new LobbyState(mClient);
//Store the new state
mManager->addGameState(GameStateManager::LOBBY, newState);
//Store the listener
mConnectionFinished = false;
mConnectListener = listener;
//Try connecting
delete mConnectionThread;
mConnectionThread = new ClientConnectThread(mClient, this);
mConnectionThread->start();
Ogre::LogManager::getSingletonPtr()->getDefaultLog()->stream() << "[HUClient]: Connection thread created.";
}
void MainMenuState::onConnectFinish(bool success) {
//Store this result
mConnectionResult = success;
mConnectionFinished = true;
}
void MainMenuState::onCreate() {
//NEW CODE THAT STARTS THE SERVER::
try {
//HovUni::Console::createConsole("HovercraftUniverse Dedicated Server");
mLocalServer = new HUDedicatedServer("SingleplayerServer.ini");
mLocalServer->init();
mLocalServer->run(false);
//Give the server a second to load, should be enough
DWORD dwMilliseconds = 1000;
Sleep(dwMilliseconds);
//Todo prettify catch blocks error msgs like this:
//HovUni::MessageBox* msg = new MessageBox("Could not connect to server", "connectionmessage");
//GUIManager::getSingletonPtr()->activateOverlay(msg);
//HovUni::Console::destroyConsole();
onConnect("localhost", mMenu);
Ogre::LogManager::getSingletonPtr()->getDefaultLog()->stream() << "[MainMenu]: create game finished";
} catch (Ogre::Exception& e) {
GUIManager::getSingletonPtr()->activateOverlay(new HovUni::NMessageBox(e.getFullDescription(), "OgreException"));
//MessageBoxA(NULL, e.getFullDescription().c_str(), "Ogre Exception in starting Single Player Server", MB_OK | MB_ICONERROR | MB_TASKMODAL);
} catch (HovUni::Exception& e2) {
GUIManager::getSingletonPtr()->activateOverlay(new HovUni::NMessageBox(e2.getMessage(), "HovUniException"));
//MessageBoxA(NULL, e2.getMessage().c_str(), "HovUni Exception in starting Single Player Server", MB_OK | MB_ICONERROR | MB_TASKMODAL);
} catch (std::exception& e) {
GUIManager::getSingletonPtr()->activateOverlay(new HovUni::NMessageBox(e.what(), "stdException"));
//MessageBoxA(NULL, e.what(), "Exception in starting Single Player Server", MB_OK | MB_ICONERROR | MB_TASKMODAL);
} catch (...) {
GUIManager::getSingletonPtr()->activateOverlay(new HovUni::NMessageBox("Unknown fatal Ogre Exception in starting Single Player Server", "unknownException"));
//MessageBoxA(NULL, "Unknown fatal Ogre Exception in starting Single Player Server", "Exception in starting Single Player Server", MB_OK | MB_ICONERROR | MB_TASKMODAL);
}
}
void MainMenuState::finishConnect() {
//Delete the connection thread
delete mConnectionThread;
mConnectionThread = 0;
//Deactivate our overlay
mMenu->deactivate();
mManager->switchState(GameStateManager::LOBBY);
}
Hikari::FlashValue MainMenuState::onQuit(Hikari::FlashControl* caller, const Hikari::Arguments& args) {
mContinue = false;
return Hikari::FlashValue();
}
void MainMenuState::activate() {
//We don't want any crazy input keys
mInputManager->getKeyManager()->setInactive();
//Creat the MainMenu object
if (mMenu != 0) {
delete mMenu;
}
mMenu = new MainMenu(this, Hikari::FlashDelegate(this, &MainMenuState::onQuit));
//Try and move the mouse to the center of the screen
mInputManager->moveMouseTo(mGUIManager->getResolutionWidth() / 2, mGUIManager->getResolutionHeight() / 2);
//Make sure we have a cursor
mGUIManager->showCursor(true);
//Activate the menu overlay
mMenu->activate();
mSoundManager->startAmbient(MUSICCUE_HOVSOUND_MENU);
}
void MainMenuState::disable() {
//Deactivate the menu overlay
mMenu->deactivate();
//Delete the menu overlay
//delete mMenu;
}
bool MainMenuState::frameStarted(const Ogre::FrameEvent & evt) {
//Check if we have a connection result
if (mConnectionFinished) {
mConnectListener->onConnectFinish(mConnectionResult);
mConnectListener = 0;
mConnectionFinished = false;
}
bool result = true;
mLastGUIUpdate += evt.timeSinceLastFrame;
//50 FPS
if (mLastGUIUpdate > (1.0f / 50.0f) || mLastGUIUpdate < 0) {
//We are using a GUI, so update it
mGUIManager->update();
mLastGUIUpdate = 0.0f; //Reset
}
//We have sound, update it
mSoundManager->update();
return (result && mContinue);
}
bool MainMenuState::mouseMoved(const OIS::MouseEvent & e) {
bool result = true;
//We are using a GUI, so update it
result = result && mGUIManager->mouseMoved(e);
return result;
}
bool MainMenuState::mousePressed(const OIS::MouseEvent & e, OIS::MouseButtonID id) {
bool result = true;
//We are using a GUI, so update it
result = result && mGUIManager->mousePressed(e, id);
return result;
}
bool MainMenuState::mouseReleased(const OIS::MouseEvent & e, OIS::MouseButtonID id) {
bool result = true;
//We are using a GUI, so update it
result = result && mGUIManager->mouseReleased(e, id);
return result;
}
bool MainMenuState::keyPressed(const OIS::KeyEvent & e) {
bool result = true;
OIS::Keyboard * keyboard = InputManager::getSingletonPtr()->getKeyboard();
switch (e.key) {
case OIS::KC_ESCAPE:
case OIS::KC_F4:
// Check whether right combinations are pressed concurrently
if ((keyboard->isKeyDown(OIS::KC_ESCAPE)) ||
((keyboard->isKeyDown(OIS::KC_LMENU) || keyboard->isKeyDown(OIS::KC_RMENU)) && keyboard->isKeyDown(OIS::KC_F4))
) {
// Stop rendering
mContinue = false;
}
break;
default:
// Do nothing
break;
}
//We are using a GUI, so update it
result = result && mGUIManager->keyPressed(e);
return result;
}
bool MainMenuState::keyReleased(const OIS::KeyEvent & e) {
bool result = true;
//We are using a GUI, so update it
result = result && mGUIManager->keyReleased(e);
return result;
}
}
| [
"nick.defrangh@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"berghmans.olivier@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c",
"dirk.delahaye@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c"
] | [
[
[
1,
3
],
[
5,
23
],
[
25,
192
],
[
196,
220
]
],
[
[
4,
4
],
[
24,
24
]
],
[
[
193,
195
]
]
] |
449b2868497388681d210c617ec9ad9013452174 | 15732b8e4190ae526dcf99e9ffcee5171ed9bd7e | /INC/cq.h | 1be0c72ec8c9a6d3018fd55481bcada769b507e8 | [] | no_license | clovermwliu/whutnetsim | d95c07f77330af8cefe50a04b19a2d5cca23e0ae | 924f2625898c4f00147e473a05704f7b91dac0c4 | refs/heads/master | 2021-01-10T13:10:00.678815 | 2010-04-14T08:38:01 | 2010-04-14T08:38:01 | 48,568,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,151 | h | //Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu)
//All rights reserved.
//
//PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM
//BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF
//THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO
//NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER.
//
//This License allows you to:
//1. Make copies and distribute copies of the Program's source code provide that any such copy
// clearly displays any and all appropriate copyright notices and disclaimer of warranty as set
// forth in this License.
//2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)").
// Modifications may be copied and distributed under the terms and conditions as set forth above.
// Any and all modified files must be affixed with prominent notices that you have changed the
// files and the date that the changes occurred.
//Termination:
// If at anytime you are unable to comply with any portion of this License you must immediately
// cease use of the Program and all distribution activities involving the Program or any portion
// thereof.
//Statement:
// In this program, part of the code is from the GTNetS project, The Georgia Tech Network
// Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in
// computer networks to study the behavior of moderate to large scale networks, under a variety of
// conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from
// Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage:
// http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/
//
//File Information:
//
//
//File Name:
//File Purpose:
//Original Author:
//Author Organization:
//Construct Data:
//Modify Author:
//Author Organization:
//Modify Data:
// Circular message passing queue
// George F. Riley, Georgia Tech, Winter 2001
#ifndef __CQ_H__
#define __CQ_H__
#include <stddef.h>
// This defines the Queue management structure. All buffer pointers are
// relative to pBase. This is to allow this to work inshared memory
// regions, where the two processors will not have the same (necessarily)
// logical memory addresses for the common region.
typedef struct {
size_t pFirst;
volatile size_t pIn;
volatile size_t pOut;
size_t pLimit;
} CQueue;
#ifdef __cplusplus
extern "C" {
#endif
void QSetBuf(CQueue*, size_t ofs, size_t l); // Set the data buffer address
size_t QAdvance(CQueue*, size_t, size_t); // Advance ptr by specified amt
size_t QData(CQueue* ); // How much data is in the buffer?
size_t QSpace(CQueue* ); // How much space is available in the buffer
void QPut(CQueue*, char*, char*, size_t); // Put some data in the buffer
void QGet(CQueue*, char*, char*, size_t); // Get some data from the buffer
size_t QDiff(CQueue*, size_t, size_t); // Distance from p1 to p2
// QPutN puts without chaning pIn, instead returns advance value
size_t QPutN(CQueue*, char*, char*, size_t, size_t);
// QGetN gets without chaning pOut, instead returns advance value
size_t QGetN(CQueue*, char*, char*, size_t, size_t);
// Debug Routines
void QDump(CQueue*, char*); // Debug..
void QDumpPtrs(CQueue*); // Debug..
void QDumpPartial(CQueue*, char*, size_t, size_t);
#ifdef __cplusplus
}
#endif
#ifdef OLD_CLASS_VERSION
class CQueue {
public :
CQueue() : pFirst(0), pIn(0), pOut(0), pLimit(0) { };
CQueue( char* b, size_t l ) : pFirst(b), pIn(b), pOut(b), pLimit(b+l) { };
void SetBuf(char* buf, size_t l); // Set the data buffer address
size_t Data(); // How much data is in the buffer?
size_t Space(); // How much space is available in the buffer
void Put(char*, size_t); // Put some data in the buffer
void Get(char*, size_t); // Get some data from the buffer
private :
char* pFirst;
char* pIn;
char* pOut;
char* pLimit;
};
#endif
#endif
| [
"pengelmer@f37e807c-cba8-11de-937e-2741d7931076"
] | [
[
[
1,
105
]
]
] |
c76fd489b9a7e87b48d2d395f7456de4618d4209 | b4bff7f61d078e3dddeb760e21174a781ed7f985 | /Source/System/Dynamics/Animation/Animations/Advancers/OSGFieldAnimationAdvancer.h | 6af76f71703e95aa395504c2509cab5823032f06 | [] | no_license | Langkamp/OpenSGToolbox | 8283edb6074dffba477c2c4d632e954c3c73f4e3 | 5a4230441e68f001cdf3e08e9f97f9c0f3c71015 | refs/heads/master | 2021-01-16T18:15:50.951223 | 2010-05-19T20:24:52 | 2010-05-19T20:24:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,068 | h | /*---------------------------------------------------------------------------*\
* OpenSG ToolBox Animation *
* *
* *
* *
* *
* www.vrac.iastate.edu *
* *
* Authors: David Kabala *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
#ifndef _OSGFIELDANIMATIONADVANCER_H_
#define _OSGFIELDANIMATIONADVANCER_H_
#ifdef __sgi
#pragma once
#endif
#include <OpenSG/OSGConfig.h>
#include "OSGAnimationDef.h"
#include "OSGFieldAnimationAdvancerBase.h"
OSG_BEGIN_NAMESPACE
class OSG_ANIMATIONLIB_DLLMAPPING FieldAnimationAdvancer : public FieldAnimationAdvancerBase
{
private:
typedef FieldAnimationAdvancerBase Inherited;
/*========================== PUBLIC =================================*/
public:
/*---------------------------------------------------------------------*/
/*! \name Sync */
/*! \{ */
virtual void changed(BitVector whichField,
UInt32 origin );
/*! \} */
/*---------------------------------------------------------------------*/
/*! \name Output */
/*! \{ */
virtual void dump( UInt32 uiIndent = 0,
const BitVector bvFlags = 0) const;
/*! \} */
virtual osg::Real32 getValue(void) const;
virtual osg::Real32 getPrevValue(void) const;
/*========================= PROTECTED ===============================*/
protected:
// Variables should all be in FieldAnimationAdvancerBase.
/*---------------------------------------------------------------------*/
/*! \name Constructors */
/*! \{ */
FieldAnimationAdvancer(void);
FieldAnimationAdvancer(const FieldAnimationAdvancer &source);
/*! \} */
/*---------------------------------------------------------------------*/
/*! \name Destructors */
/*! \{ */
virtual ~FieldAnimationAdvancer(void);
/*! \} */
/*========================== PRIVATE ================================*/
private:
friend class FieldContainer;
friend class FieldAnimationAdvancerBase;
static void initMethod(void);
// prohibit default functions (move to 'public' if you need one)
void operator =(const FieldAnimationAdvancer &source);
};
typedef FieldAnimationAdvancer *FieldAnimationAdvancerP;
OSG_END_NAMESPACE
#include "OSGFieldAnimationAdvancerBase.inl"
#include "OSGFieldAnimationAdvancer.inl"
#define OSGFIELDANIMATIONADVANCER_HEADER_CVSID "@(#)$Id: FCTemplate_h.h,v 1.23 2005/03/05 11:27:26 dirk Exp $"
#endif /* _OSGFIELDANIMATIONADVANCER_H_ */
| [
"[email protected]"
] | [
[
[
1,
126
]
]
] |
1e56772a282ac30d9f65194d642d698831cd57df | 6e8d3ce33ebaaf9895fdbc84ff8b4f99e4eccd50 | /src/cpp/cpct_exe/cpct_exe/cpct_exe.cpp | 100fe7230c409a56382f7af9bd91d0de79fd2370 | [] | no_license | ssqre/cpct | b0b300c2800479628ff1e5d7b4729e35fa3bc7e3 | 65909bc28a8c742cbd512548a21b3c6cf1dcfb10 | refs/heads/master | 2020-04-10T15:50:27.560350 | 2011-09-19T07:45:39 | 2011-09-19T07:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,909 | cpp | // cpct_exe.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdexcept>
#include "WavManipulateDll.h"
#pragma comment(lib,"../Debug/WavManipulateDll.lib")
#include "../../cpct-mstftm/cpct-mstftm/CPCT_MSTFTM.h"
#pragma comment(lib,"../Debug/cpct-mstftm.lib")
using namespace std;
using namespace CPCT;
#define DATA_LENGTH 8192
#define BUFFER_SIZE (DATA_LENGTH * 3)
static void openFile(void** infile, void** outfile)
{
*infile = getWavInFileByName("e:\\work_SR\\code\\CPCT_MSTFTM\\test\\woman.wav");
int samplerate = (int)getSampleRate(*infile);
int bits = (int)getNumBits(*infile);
int channels = (int)getNumChannels(*infile);
*outfile = saveWavOutFileByName("e:\\work_SR\\code\\CPCT_MSTFTM\\test\\outfile.wav", samplerate, bits, channels);
printf("openFile done!\n");
}
static void process(void* infile, void* outfile, CPCT_MSTFTM* cpct)
{
float sampleBuffer[BUFFER_SIZE];
int nSample;
int nChannels;
nChannels = (int)getNumChannels(infile);
while (isFileEnd(infile)==0)
{
int num;
int datalength;
num = readFloat(infile, sampleBuffer, DATA_LENGTH);
nSample = num / nChannels;
cpct->setData(sampleBuffer, DATA_LENGTH, nChannels);
cpct->setParams(-0.5, 12);
cpct->getData(sampleBuffer, datalength);
writeFloat(outfile , sampleBuffer, datalength);
}
destroyWavInFile(infile);
destroyWavOutFile(outfile);
printf("process done!\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
void* infile;
void* outfile;
CPCT_MSTFTM* cpct = new CPCT_MSTFTM(512, 256, 5);
try
{
openFile(&infile, &outfile);
process(infile, outfile, cpct);
delete cpct;
}
catch (const runtime_error &e)
{
// An exception occurred during processing, display an error message
fprintf(stderr, "%s\n", e.what());
return -1;
}
printf("Done!!!\n");
return 0;
}
| [
"mr.dengjie@20198b2c-5f2b-bef7-f1b6-156c947877ec"
] | [
[
[
1,
78
]
]
] |
06893b49ae86e61e11570609fd8e13b0dd42a994 | 27359980429a4bfce783bfa4699b0b500e088250 | /src/capture/capture.cpp | 0d7ce4f8841eac181401344bb604597ad718970f | [] | no_license | asdlei99/cchelper | d3204e51ad2e8f15f2d813092eba9ff62cf5dddb | a98b85061a864103c06d22d2d6322cc73bdcb1bf | refs/heads/master | 2022-01-29T08:11:40.666682 | 2009-11-19T03:01:42 | 2009-11-19T03:01:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,125 | cpp |
#include <D3D9.h>
#include <D3dx9tex.h>
#include <stdio.h>
#include <string>
#include <tchar.h>
#include "MurmurHash.h"
#include "capture.h"
#include <list>
#include "log.h"
#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")
HRESULT ScreenCapture::CaptureByD3D(HWND hWnd, LPCSTR szFileName)
{
char chBuf[300];
HRESULT hr;
LPDIRECT3D9 pD3D = NULL;
D3DPRESENT_PARAMETERS D3DPP = {0};
LPDIRECT3DDEVICE9 pD3DDevice = NULL;
D3DDISPLAYMODE D3DMode;
LPDIRECT3DSURFACE9 pSurface = NULL;
lstrcpy(chBuf, "Done!");
pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (!pD3D)
{
lstrcpy(chBuf, "Direct3DCreate9() failed.");
goto Cleanup;
}
D3DPP.Windowed = TRUE;
D3DPP.SwapEffect = D3DSWAPEFFECT_DISCARD;
D3DPP.BackBufferFormat = D3DFMT_UNKNOWN;
hr = pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING, &D3DPP, &pD3DDevice);
if (FAILED(hr))
{
wsprintf(chBuf, "IDirect3D9::CreateDevice() failed with 0x%x.\n", hr);
goto Cleanup;
}
hr = pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &D3DMode);
if (FAILED(hr))
{
wsprintf(chBuf, "IDirect3D9::GetAdapterDisplayMode() failed with 0x%x.\n", hr);
goto Cleanup;
}
this->m_dwDisplayModeFormat = D3DMode.Format;
hr = pD3DDevice->CreateOffscreenPlainSurface(D3DMode.Width,
D3DMode.Height,
D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &pSurface, NULL);
if (FAILED(hr))
{
wsprintf(chBuf, "IDirect3DDevice9::CreateOffscreenPlainSurface() failed with 0x%x.\n", hr);
goto Cleanup;
}
hr = pD3DDevice->GetFrontBufferData(0, pSurface);
if (FAILED(hr))
{
wsprintf(chBuf, "IDirect3DDevice9::GetFrontBufferData() failed with 0x%x.\n",
hr);
goto Cleanup;
}
RECT rc;
GetWindowRect(hWnd, &rc);
hr = D3DXSaveSurfaceToFile(szFileName, D3DXIFF_BMP, pSurface, NULL, &rc);
if (FAILED(hr))
{
wsprintf(chBuf, "D3DXSaveSurfaceToFile() failed with 0x%x.\n", hr);
goto Cleanup;
}
Cleanup:
if (pSurface) pSurface->Release();
if (pD3DDevice) pD3DDevice->Release();
if (pD3D) pD3D->Release();
OutputDebugString(chBuf);
return hr;
}
HRESULT ScreenCapture::CaptureByD3D(HWND hWnd, LPBYTE *ppData)
{
char chBuf[300];
HRESULT hr;
LPDIRECT3D9 pD3D = NULL;
D3DPRESENT_PARAMETERS D3DPP = {0};
LPDIRECT3DDEVICE9 pD3DDevice = NULL;
D3DDISPLAYMODE D3DMode;
LPDIRECT3DSURFACE9 pSurface = NULL;
*ppData = NULL;
pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (!pD3D)
{
lstrcpy(chBuf, "Direct3DCreate9() failed.");
goto Cleanup;
}
D3DPP.Windowed = TRUE;
D3DPP.SwapEffect = D3DSWAPEFFECT_DISCARD;
D3DPP.BackBufferFormat = D3DFMT_UNKNOWN;
hr = pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING, &D3DPP, &pD3DDevice);
if (FAILED(hr))
{
wsprintf(chBuf, "IDirect3D9::CreateDevice() failed with 0x%x.\n", hr);
goto Cleanup;
}
hr = pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &D3DMode);
if (FAILED(hr))
{
wsprintf(chBuf, "IDirect3D9::GetAdapterDisplayMode() failed with 0x%x.\n", hr);
goto Cleanup;
}
this->m_dwDisplayModeFormat = D3DMode.Format;
hr = pD3DDevice->CreateOffscreenPlainSurface(D3DMode.Width,
D3DMode.Height,
D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &pSurface, NULL);
if (FAILED(hr))
{
wsprintf(chBuf, "IDirect3DDevice9::CreateOffscreenPlainSurface() failed with 0x%x.\n", hr);
goto Cleanup;
}
hr = pD3DDevice->GetFrontBufferData(0, pSurface);
if (FAILED(hr))
{
wsprintf(chBuf, "IDirect3DDevice9::GetFrontBufferData() failed with 0x%x.\n",
hr);
goto Cleanup;
}
RECT rc;
GetWindowRect(hWnd, &rc);
LPD3DXBUFFER pDestBuf;
hr = D3DXSaveSurfaceToFileInMemory(&pDestBuf, D3DXIFF_BMP, pSurface, NULL, &rc);
if (FAILED(hr))
{
wsprintf(chBuf, "IDirect3DDevice9::D3DXSaveSurfaceToFileInMemory() failed with 0x%x.\n",
hr);
goto Cleanup;
}
int size = pDestBuf->GetBufferSize();
LPBYTE pData = (LPBYTE)malloc(size) ;
memcpy(pData, pDestBuf->GetBufferPointer(), size);
*ppData = pData;
pDestBuf->Release();
Cleanup:
if (pSurface) pSurface->Release();
if (pD3DDevice) pD3DDevice->Release();
if (pD3D) pD3D->Release();
OutputDebugString(chBuf);
return hr;
}
TCHAR * GetFileName(TCHAR * filepath)
{
const TCHAR * delimiters = "/\\";
TCHAR * p = filepath;
TCHAR * plast = p;
p = _tcstok (filepath,delimiters);
while(p!=NULL)
{
plast = p;
p = _tcstok(NULL,delimiters);
}
return plast;
}
BOOL CALLBACK _Capture_EnumChildProc(HWND hwnd, LPARAM lParam)
{
std::list<std::string> * plistStr = (std::list<std::string> * )lParam;
TCHAR szBuf[1024];
TCHAR szStr[256];
szStr[0]=0;
// Get module file name
GetWindowModuleFileName(hwnd, szStr, sizeof(szStr));
_stprintf(szBuf,"%s_0x%x",GetFileName(szStr), GetDlgCtrlID(hwnd));
plistStr->push_back(szBuf);
return TRUE;
}
void GetWindowKeyString(HWND hwnd, std::string& strHash)
{
TCHAR szStr[1024]={0};
// Get module file name
DWORD dwProcessId;
DWORD dwThreadId = GetWindowThreadProcessId(hwnd, &dwProcessId);
HANDLE hProcess;
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, dwProcessId );
GetModuleBaseName(hProcess, NULL, szStr, sizeof(szStr));
strHash.append(GetFileName(szStr));
GetProcessImageFileName(hProcess, szStr, sizeof(szStr));
strHash.append(GetFileName(szStr));
if(hProcess)
CloseHandle(hProcess);
HWND hwndParent = GetParent(hwnd);
if(hwndParent)
{
GetWindowKeyString(hwndParent, strHash);
}
}
unsigned int ScreenCapture::GetWindowKey(HWND hwnd)
{
unsigned int key;
std::string strHash;
// Get module file name
GetWindowKeyString(hwnd, strHash);
//OutputDebugString(strHash.c_str());
key = base::MurmurHash2(strHash.c_str(), strHash.length());
return key;
}
BOOL CALLBACK ScreenCaptureSearch_EnumChildProc( HWND hwnd, LPARAM lParam)
{
ScreenCapture * pCap = (ScreenCapture *) lParam;
// If already found target window, then return FALSE to terminate
// current searching.
if( pCap->m_hwnd )
{
return FALSE;
}
if( ScreenCapture::GetWindowKey(hwnd) == pCap->m_uWindowKey)
{
pCap->m_hwnd = hwnd;
return FALSE;
}
return TRUE;
}
BOOL CALLBACK ScreenCaptureSearch_EnumWindowsProc( HWND hwnd,LPARAM lParam)
{
ScreenCapture * pCap = (ScreenCapture*) lParam;
// If already found target window, then return FALSE to terminate
// current searching.
if( pCap->m_hwnd )
return FALSE;
if(ScreenCapture::GetWindowKey(hwnd) == pCap->m_uWindowKey )
{
pCap->m_hwnd = hwnd;
return FALSE;
}
if( pCap->m_bSearchSubWindow )
{
ScreenCaptureSearch_EnumChildProc(hwnd, (LPARAM)lParam);
}
return TRUE;
}
HWND ScreenCapture::SearchWindow(unsigned int uWindowKey, bool bSearchSubWindow )
{
this->m_bSearchSubWindow = bSearchSubWindow;
this->m_hwnd = NULL;
this->m_uWindowKey = uWindowKey;
EnumWindows(ScreenCaptureSearch_EnumWindowsProc,(LPARAM)this);
return this->m_hwnd ;
}
| [
"tanbunko@2befaa78-c350-11de-b037-cf5282a2cdbc"
] | [
[
[
1,
311
]
]
] |
7fd78239f872e872351625e7acf83e5d910397cf | 26d2b43b622326b792d1e7a8988bc54d02a5d382 | /src/lines.h | 5d397949c03477f146284eb63ebcace2925ea5d5 | [] | no_license | rehno-lindeque/osi-glge | cbfc8ad6f5d15236ec46d280f39f57e9fefdb21f | 6b60fe6a47f5b667bf5ff31d51a559199f96c48c | refs/heads/master | 2021-01-19T21:52:17.218139 | 2011-01-29T09:57:27 | 2011-01-29T09:57:27 | 1,303,689 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 654 | h | #ifndef __GLGE_LINES_H__
#define __GLGE_LINES_H__
//////////////////////////////////////////////////////////////////////////////
//
// LINES.H
//
// Copyright © 2006, Rehno Lindeque. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////
/* DOCUMENTATION */
/*
DESCRIPTION:
GLGE Lines
*/
namespace GLGE
{
/* CLASSES */
class GLLines : public BaseGE::Components
{
public:
inline GLLines() : Components(GE_LINE) {}
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
26
]
]
] |
9bfd455722724c2a76b49ed5c24b94f156b15d5f | bbbced1defe4a25cacd2e3e457c3f6a757682d92 | /asteragy_server/asteragy_server.cpp | 4167ffd0203abf88e19de986e3665d45da95dce4 | [] | no_license | ForestLight/asteragy | 5409debae0660a33662b80fa2f1c99cf1e791d1c | 1b497522a3669d78c7326598d999ca228ab1a5dd | refs/heads/master | 2016-08-12T23:13:29.936709 | 2009-12-06T21:59:59 | 2009-12-06T21:59:59 | 36,563,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,042 | cpp | #include "stdafx.h"
#include "server.h"
#include <memory>
#include <cstdlib> //srand
#include <ctime> //time
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#ifdef _WIN32
#include <windows.h>
#else
#include <signal.h>
#include <unistd.h>
#endif
namespace as = boost::asio;
using as::ip::tcp;
namespace
{
std::auto_ptr<as::io_service> pios;
#ifdef _WIN32
BOOL WINAPI console_ctrl_handler(DWORD ctrl_type)
{
switch (ctrl_type)
{
// case CTRL_C_EVENT:
// case CTRL_BREAK_EVENT:
// case CTRL_CLOSE_EVENT:
case CTRL_SHUTDOWN_EVENT:
if (as::io_service* p = pios.get())
{
p->stop();
return TRUE;
}
}
return FALSE;
}
#else
void sig_handler(int)
{
if (!pios.get())
{
pios->stop();
pios.reset(0);
}
_exit(0);
}
#endif
void NextTimer();
void RemoveGameEntry(const boost::system::error_code&)
{
RemoveGame();
NextTimer();
}
void NextTimer()
{
if (pios.get())
{
as::deadline_timer t(*pios, boost::posix_time::seconds(6 * 60));
t.async_wait(RemoveGameEntry);
}
}
void server_main()
{
pios.reset(new as::io_service);
#ifdef _WIN32
SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
#else
sigset_t wait_mask;
sigemptyset(&wait_mask);
sigaddset(&wait_mask, SIGINT);
sigaddset(&wait_mask, SIGQUIT);
sigaddset(&wait_mask, SIGTERM);
struct sigaction sa = {0};
sa.sa_handler = sig_handler;
sa.sa_mask = wait_mask;
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
#endif
Server s(*pios);
NextTimer();
pios->run();
abs(0);
}
} // end of anonymous namespace
int main()
{
try
{
std::srand(static_cast<unsigned>(std::time(0)));
contentRoot = std::getenv("ASTERAGY_SERVER_CONTENT_ROOT");
server_main();
}
catch (std::exception const& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
| [
"[email protected]",
"yusuke.ichinohe@05ab3c7c-673e-0410-85c5-735cf5110427"
] | [
[
[
1,
2
],
[
16,
21
],
[
23,
23
],
[
26,
26
],
[
40,
40
],
[
43,
43
],
[
73,
73
],
[
83,
83
],
[
90,
90
],
[
93,
99
],
[
102,
110
]
],
[
[
3,
15
],
[
22,
22
],
[
24,
25
],
[
27,
39
],
[
41,
42
],
[
44,
72
],
[
74,
82
],
[
84,
89
],
[
91,
92
],
[
100,
101
]
]
] |
2a064dc805967a6d50f34efc282b64e77739ae88 | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/26042005/vfs/VFSHandle_file_win32.cpp | afb49b7134547919a62e2496d08dd2cc5cd892d5 | [] | no_license | christhomas/fusionengine | 286b33f2c6a7df785398ffbe7eea1c367e512b8d | 95422685027bb19986ba64c612049faa5899690e | refs/heads/master | 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,891 | cpp | /***************************************************************************
* Copyright (C) 2003 by Christopher Thomas *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include <VFSHandle_file_win32.h>
#include <io.h>
#include <sys/stat.h>
#include <direct.h>
VFSHandle_file_win32::VFSHandle_file_win32(VFSTransport *t): VFSHandle_file(t)
{
}
VFSHandle_file_win32::~VFSHandle_file_win32()
{
}
//=========================================================
//=========================================================
// public File/Directory manipulation methods
//=========================================================
//=========================================================
bool VFSHandle_file_win32::IsFile( char *filename )
{
_finddata_t find;
intptr_t Filehandle = _findfirst( filename, &find );
if ( Filehandle == -1 )
{
if ( errno == ENOENT ) {}
if ( errno == EINVAL ) {}
_findclose( Filehandle );
return false;
}
_findclose( Filehandle );
return true;
}
bool VFSHandle_file_win32::IsDirectory( char *directory )
{
if ( strcmp( directory, "" ) != 0 )
{
_finddata_t find;
intptr_t Filehandle = _findfirst( directory, &find );
if ( Filehandle == -1 )
{
if ( errno == ENOENT ) {}
if ( errno == EINVAL ) {}
_findclose( Filehandle );
return false;
}
_findclose( Filehandle );
}
return true;
}
// dummy for the moment, since I dont actually need to extract this kind of information yet
FileInfo * VFSHandle_file_win32::GetFileInfo( char *filename )
{
struct stat s;
if ( stat( filename, &s ) == -1 )
{
if ( errno == ENOENT ) {};
return NULL;
}
return NULL;
}
bool VFSHandle_file_win32::Createfile( char *filename, bool recurse )
{
// TODO: make sure the file is created, make all the directories required too
if ( recurse == true ) CreateDir( filename );
m_stream.clear();
m_stream.open( filename, std::ios::out );
bool r = ( bool ) m_stream.is_open();
m_stream.close();
return r;
}
bool VFSHandle_file_win32::Deletefile( char *filename )
{
if ( remove( filename ) == -1 )
{
if ( errno == EACCES ) return false; // read only file
if ( errno == ENOENT ) return false; // file does not exist
}
return true;
}
bool VFSHandle_file_win32::Copyfile( char *src, char *dest, bool createpath )
{
return false;
}
bool VFSHandle_file_win32::Movefile( char *src, char *dest, bool createpath )
{
return false;
}
bool VFSHandle_file_win32::CreateDir( char *directory )
{
char * dir = directory;
for (unsigned int a = 0;a < strlen( directory );a++ ) if ( dir[ a ] == '\\' ) dir[ a ] = '/';
if ( dir[ 0 ] == '/' ) dir++;
char *token = dir;
while ( token != NULL )
{
token = strchr( token, '/' );
if ( token != NULL )
{
int bytes = (int)(token - directory);
char *temp = new char[ bytes + 1 ];
memset( temp, 0, bytes + 1 );
strncpy( temp, directory, bytes );
if ( mkdir( temp ) == -1 ) if ( errno == ENOENT ) return false;
delete[] temp;
token++;
}
}
return true;
}
bool VFSHandle_file_win32::DeleteDir( char *directory, bool recurse )
{
char path[ 256 ];
sprintf( path, "%s/*.*", directory );
if ( recurse == true )
{
_finddata_t find;
intptr_t Filehandle = _findfirst( path, &find );
if ( Filehandle == -1 )
{
if ( errno == ENOENT )
{
_findclose( Filehandle );
return DeleteDir( directory, false );
}
if ( errno == EINVAL )
{
_findclose( Filehandle );
return false; // should this happen ever with *.* ? I dont think so....
}
}
else
{
do
{
if ( strcmp( find.name, "." ) != 0 && strcmp( find.name, ".." ) != 0 )
{
memset( path, 0, 256 );
sprintf( path, "%s/%s", directory, find.name );
Deletefile( path );
}
}
while ( _findnext( Filehandle, &find ) == 0 );
_findclose( Filehandle );
return DeleteDir( directory, false );
}
// have to delete all the files in the folder, then remove it, all the way back to the root directory requested to delete
return false;
}
if ( rmdir( directory ) == -1 )
{
if ( errno == ENOTEMPTY ) return false;
if ( errno == ENOENT ) return false;
}
return true;
}
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
] | [
[
[
1,
215
]
]
] |
1df48de94b4b948afbc28293879e73aad1f9f5e4 | c2abb873c8b352d0ec47757031e4a18b9190556e | /src/vortex-client/Application.h | 1b05ee36707547bc984a61f9f59bf74b833566eb | [] | no_license | twktheainur/vortex-ee | 70b89ec097cd1c74cde2b75f556448965d0d345d | 8b8aef42396cbb4c9ce063dd1ab2f44d95e994c6 | refs/heads/master | 2021-01-10T02:26:21.913972 | 2009-01-30T12:53:21 | 2009-01-30T12:53:21 | 44,046,528 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,053 | h | #ifndef APPLICATION_H_INCLUDED
#define APPLICATION_H_INCLUDED
#include <Ogre.h>
#include <OIS/OIS.h>
#include "VortexFrameListener.h"
#include "PersonnagePhysique.h"
#include <MyGUI.h>
#include "../common/md5wrapper.h"
using namespace Ogre;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include <CoreFoundation/CoreFoundation.h>
// This function will locate the path to our application on OS X,
// unlike windows you can not rely on the curent working directory
// for locating your configuration files and resources.
std::string macBundlePath()
{
char path[1024];
CFBundleRef mainBundle = CFBundleGetMainBundle();
assert(mainBundle);
CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
assert(mainBundleURL);
CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle);
assert(cfStringRef);
CFStringGetCString(cfStringRef, path, 1024, kCFStringEncodingASCII);
CFRelease(mainBundleURL);
CFRelease(cfStringRef);
return std::string(path);
}
#endif
class Application
{
public:
Application();
~Application();
void go();
private:
Root *mRoot;
OIS::InputManager *mInputManager;
VortexFrameListener *mListener;
Camera *mCamera;
PersonnagePhysique * mPlayer;
SceneManager *mSceneMgr;
RenderWindow *win;
MyGUI::Gui * mGUI;
MyGUI::VectorWidgetPtr winLogin;
MyGUI::EditPtr mEditLogin;
MyGUI::EditPtr mEditPass;
MyGUI::ButtonPtr buttonLogConnec;
MyGUI::StaticTextPtr erreur;
void login();
inline void quitter(MyGUI::WidgetPtr _sender) { continuer = false; }
void buttonConnexionClick(MyGUI::WidgetPtr _widget);
void createRoot();
void defineResources();
void setupRenderSystem();
void createRenderWindow();
void initializeResourceGroups();
void chooseSceneManager();
void setupScene();
void setupInputSystem();
void setupMyGUI();
void createFrameListener();
void startRenderLoop();
};
#endif // APPLICATION_H_INCLUDED
| [
"twk.theainur@37e2baaa-b253-11dd-9381-bf584fb1fa83",
"seb.owk@37e2baaa-b253-11dd-9381-bf584fb1fa83",
"saussage.warrior@37e2baaa-b253-11dd-9381-bf584fb1fa83"
] | [
[
[
1,
5
],
[
10,
10
],
[
12,
44
],
[
46,
52
],
[
56,
56
],
[
72,
76
],
[
78,
81
],
[
84,
88
],
[
90,
96
]
],
[
[
6,
7
],
[
11,
11
],
[
45,
45
],
[
53,
55
],
[
77,
77
],
[
82,
83
]
],
[
[
8,
9
],
[
57,
71
],
[
89,
89
]
]
] |
6b0442f9154230c8dc7418a0dab33906d4655e59 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/source/aosl/axis_y.cpp | 6319ad2f1d642b24ae9f1a0887f57a51111602ba | [] | no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,882 | cpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
// Begin prologue.
//
#define AOSLCPP_SOURCE
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "aosl/axis_y.hpp"
#include <xsd/cxx/xml/dom/wildcard-source.hxx>
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
#include <xsd/cxx/tree/comparison-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
static
const ::xsd::cxx::tree::comparison_plate< 0, char >
comparison_plate_init;
}
namespace aosl
{
// Axis_y
//
const Axis_y::OriginType Axis_y::origin_default_value_ (
"top");
const Axis_y::PositiveType Axis_y::positive_default_value_ (
"down");
Axis_y::
Axis_y ()
: ::xml_schema::Type (),
origin_ (origin_default_value (), ::xml_schema::Flags (), this),
positive_ (positive_default_value (), ::xml_schema::Flags (), this)
{
}
Axis_y::
Axis_y (const Axis_y& x,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xml_schema::Type (x, f, c),
origin_ (x.origin_, f, this),
positive_ (x.positive_, f, this)
{
}
Axis_y::
Axis_y (const ::xercesc::DOMElement& e,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xml_schema::Type (e, f | ::xml_schema::Flags::base, c),
origin_ (f, this),
positive_ (f, this)
{
if ((f & ::xml_schema::Flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, false, true);
this->parse (p, f);
}
}
void Axis_y::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::Flags f)
{
while (p.more_attributes ())
{
const ::xercesc::DOMAttr& i (p.next_attribute ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
if (n.name () == "origin" && n.namespace_ ().empty ())
{
::std::auto_ptr< OriginType > r (
OriginTraits::create (i, f, this));
this->origin_.set (r);
continue;
}
if (n.name () == "positive" && n.namespace_ ().empty ())
{
::std::auto_ptr< PositiveType > r (
PositiveTraits::create (i, f, this));
this->positive_.set (r);
continue;
}
}
if (!origin_.present ())
{
this->origin_.set (origin_default_value ());
}
if (!positive_.present ())
{
this->positive_.set (positive_default_value ());
}
}
Axis_y* Axis_y::
_clone (::xml_schema::Flags f,
::xml_schema::Container* c) const
{
return new class Axis_y (*this, f, c);
}
Axis_y::
~Axis_y ()
{
}
bool
operator== (const Axis_y& x, const Axis_y& y)
{
if (!(x.origin () == y.origin ()))
return false;
if (!(x.positive () == y.positive ()))
return false;
return true;
}
bool
operator!= (const Axis_y& x, const Axis_y& y)
{
return !(x == y);
}
}
#include <ostream>
#include <xsd/cxx/tree/std-ostream-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::std_ostream_plate< 0, char >
std_ostream_plate_init;
}
namespace aosl
{
::std::ostream&
operator<< (::std::ostream& o, const Axis_y& i)
{
o << ::std::endl << "origin: " << i.origin ();
o << ::std::endl << "positive: " << i.positive ();
return o;
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace aosl
{
}
#include <ostream>
#include <xsd/cxx/tree/error-handler.hxx>
#include <xsd/cxx/xml/dom/serialization-source.hxx>
#include <xsd/cxx/tree/type-serializer-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_serializer_plate< 0, char >
type_serializer_plate_init;
}
namespace aosl
{
void
operator<< (::xercesc::DOMElement& e, const Axis_y& i)
{
e << static_cast< const ::xml_schema::Type& > (i);
// origin
//
{
::xercesc::DOMAttr& a (
::xsd::cxx::xml::dom::create_attribute (
"origin",
e));
a << i.origin ();
}
// positive
//
{
::xercesc::DOMAttr& a (
::xsd::cxx::xml::dom::create_attribute (
"positive",
e));
a << i.positive ();
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| [
"klaim@localhost"
] | [
[
[
1,
236
]
]
] |
098c870e6ab264080c22d811182fc7c3edb74616 | bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2 | /Open GL Basic Engine/source/glutFramework/glutFramework/RVB_unit.h | 872963d36db6154a5eed51052859e5c5fe8cd64b | [] | no_license | CorwinJV/rvbgame | 0f2723ed3a4c1a368fc3bac69052091d2d87de77 | a4fc13ed95bd3e5a03e3c6ecff633fe37718314b | refs/heads/master | 2021-01-01T06:49:33.445550 | 2009-11-03T23:14:39 | 2009-11-03T23:14:39 | 32,131,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,010 | h | #ifndef RVB_SOLDIER_H
#define RVB_SOLDIER_H
#include "rvb_weapon.h"
enum soldierState{Fire, Cover, Defend, Move};
enum soldierDirection{UP, RIGHT, LEFT, DOWN};
class rvbSoldier
{
public:
rvbSoldier();
~rvbSoldier();
void applyDamage(int damage); // takes in the damage done and reduces health
void pickUpAmmo(int amount); // pickup ammo and add it to your cache
void pickUpWeapon(rvbWeapon newWeapon); // pickup weapon and add it to your inventory
void retreat(); // get out of Dodge!
void callForBackup(); // call to your team for backup
void idTarget(); // scan area for targets
void idFriendly(); // scan area for friendlies
void getFlag(); // either grab the flag from the enemy base, or return your flag to your base
void claimFlag(); // bring the flag back to your base to earn a point
void seekCover(); // check area for obstacles to hide behind
int checkMyAmmo(); // see how much ammo you currently have
void seekMoreAmmo(); // seek out more ammo if you are low
int getHealth(); // returns the soldier's health
soldierDirection getDirection(); // returns the direction the soldier is facing
rvbWeapon getCurWeapon(); // returns the current weapon
void changeWeapon(); // cycles through weapons in your inventory
void changeDirection(soldierDirection newDirection); // changes soldier's direction
void setState(soldierState newState); // sets soldier to the state passed in
soldierState getState(); // gets the current state of the soldier
private:
int health; // amount of damage unit can take
soldierDirection direction; // direction the soldier is facing
int movementSpeed; // how fast can the soldier move
int armor; // does the soldier have any additional armor
rvbWeapon weaponCache[1]; // stores the weapons you have available
rvbWeapon curWeapon; // weapon on hand
soldierState curState; // current state of the soldier
};
#endif | [
"corwin.j@5457d560-9b84-11de-b17c-2fd642447241"
] | [
[
[
1,
44
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.