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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b7ba26de651d3da74c793d9f9245e568cb019d35 | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/sound/core/win32/directsound8/devicedirectsound8.cpp | d597478d81ff7308f07b3d86492aac6f0e2c4dca | [] | no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,675 | cpp | #include"devicedirectsound8.h"
#include"bufferdirectsound8.h"
#include"../../../../auxiliary/debug/warning.h"
namespace Maid { namespace Sound {
DeviceDirectSound8::DeviceDirectSound8( const boost::shared_ptr<GUID>& guid, const DllWrapper& dsounddll, const Window& window )
:m_pGUID(guid),m_dsounddll(dsounddll),m_Window(window)
{
}
void DeviceDirectSound8::Initialize()
{
{
typedef HRESULT (WINAPI *FUNCTIONPTR)( LPCGUID, LPDIRECTSOUND8*, LPUNKNOWN );
FUNCTIONPTR pdsoundCreate = (FUNCTIONPTR)m_dsounddll.GetProcAddress(MAIDTEXT("DirectSoundCreate8"));
IDirectSound8* pDS8=NULL;
const HRESULT ret = pdsoundCreate( m_pGUID.get(), &pDS8, NULL );
if( FAILED(ret) ) { MAID_WARNING( MAIDTEXT("DirectSoundCreate8()") ); return; }
m_pDevice.reset(pDS8);
}
HRESULT ret;
ret = m_pDevice->SetCooperativeLevel( m_Window.GetHWND(), DSSCL_PRIORITY );
if( FAILED(ret) ) { goto NORMAL_MODE; }
{
IDirectSoundBuffer* pBuf;
DSBUFFERDESC dsbd = {0};
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_GLOBALFOCUS;
dsbd.dwBufferBytes = 0;
dsbd.lpwfxFormat = NULL;
dsbd.guid3DAlgorithm = GUID_NULL ;
ret = m_pDevice->CreateSoundBuffer( &dsbd, &pBuf, NULL );
if( FAILED(ret) ) { goto NORMAL_MODE; }
m_pPrimary.reset( pBuf );
}
PlayDummySound();
return ;
NORMAL_MODE:
ret = m_pDevice->SetCooperativeLevel( m_Window.GetHWND(), DSSCL_NORMAL );
if( FAILED(ret) ) { MAID_WARNING( MAIDTEXT("IDirectSound8::SetCooperativeLevel()") ); }
PlayDummySound();
return ;
}
void DeviceDirectSound8::Finalize()
{
m_pDummy.reset();
m_pPrimary.reset();
m_pDevice.reset();
}
void DeviceDirectSound8::SetFormat( const PCMFORMAT& fmt )
{
// 優先モードでなかったら変更できない
if( !IsPriorityMode() ) { return ; }
WAVEFORMATEX wfx;
ZeroMemory( &wfx, sizeof(WAVEFORMATEX) );
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nChannels = (WORD) fmt.Channels;
wfx.nSamplesPerSec = fmt.SamplesPerSecond;
wfx.wBitsPerSample = (WORD) fmt.BitPerSamples;
wfx.nBlockAlign = fmt.CalcBlockSize();
wfx.nAvgBytesPerSec = fmt.CalcBytePerLength();
const HRESULT ret = m_pPrimary->SetFormat(&wfx);
if( FAILED(ret) ) { MAID_WARNING( MAIDTEXT("IDirectSound8::SetFormat()") ); }
}
SPBUFFER DeviceDirectSound8::CreateBuffer( const CREATEBUFFERPARAM& param )
{
const PCMFORMAT& fmt = param.Format;
WAVEFORMATEX wfx={0};
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nChannels = fmt.Channels;
wfx.nSamplesPerSec = fmt.SamplesPerSecond;
wfx.wBitsPerSample = fmt.BitPerSamples;
wfx.nBlockAlign = fmt.CalcBlockSize();
wfx.nAvgBytesPerSec = fmt.CalcBytePerLength();
wfx.cbSize = 0;
const DWORD flag = DSBCAPS_GLOBALFOCUS
| DSBCAPS_LOCSOFTWARE
| DSBCAPS_CTRLVOLUME
| DSBCAPS_GETCURRENTPOSITION2
;
DSBUFFERDESC dsbd = {0};
dsbd.dwSize = sizeof(dsbd);
dsbd.dwFlags = flag;
dsbd.dwBufferBytes = param.Length;
dsbd.lpwfxFormat = &wfx;
dsbd.guid3DAlgorithm = GUID_NULL ;
IDirectSoundBuffer* pBuf=NULL;
const HRESULT ret = m_pDevice->CreateSoundBuffer( &dsbd, &pBuf, NULL );
if( FAILED(ret) ) { MAID_WARNING( MAIDTEXT("IDirectSound8::CreateSoundBuffer()") ); }
SPDIRECTSOUNDBUFFER p(pBuf);
return SPBUFFER( new BufferDirectSound8(param,p) );
}
SPBUFFER DeviceDirectSound8::DuplicateBuffer( const SPBUFFER& pSrc )
{
BufferDirectSound8* p = static_cast<BufferDirectSound8*>(pSrc.get());
IDirectSoundBuffer* pBuf=NULL;
const HRESULT ret = m_pDevice->DuplicateSoundBuffer( p->GetBuffer().get(), &pBuf );
if( FAILED(ret) ) { MAID_WARNING( MAIDTEXT("IDirectSound8::DuplicateSoundBuffer()") ); }
SPDIRECTSOUNDBUFFER pds(pBuf);
return SPBUFFER( new BufferDirectSound8(p->GetParam(),pds) );
}
bool DeviceDirectSound8::IsPriorityMode()
{
return m_pPrimary.get()!=NULL;
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/
//! WDMドライバのバグ対策関数
/*!
* プライマリバッファが止まった後に再度再生させるとき
* 前回再生したバッファが少し再生されてしまいノイズが聞こえる
* なのでプライマリバッファを停止させないように無音を再生しつづける
*
*/
void DeviceDirectSound8::PlayDummySound()
{
const DWORD chan = 2;
const DWORD freq = 44100;
const DWORD bps = 16;
WAVEFORMATEX wfx={0};
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nChannels = chan;
wfx.nSamplesPerSec = freq;
wfx.wBitsPerSample = bps;
wfx.nBlockAlign = chan* (bps/8);
wfx.nAvgBytesPerSec = freq*wfx.nBlockAlign;
wfx.cbSize = 0;
{
DSBUFFERDESC dsbd;
ZeroMemory( &dsbd, sizeof(DSBUFFERDESC) );
dsbd.dwSize = sizeof(dsbd);
dsbd.dwFlags = DSBCAPS_LOCSOFTWARE;
dsbd.dwBufferBytes = wfx.nAvgBytesPerSec;
dsbd.lpwfxFormat = &wfx;
dsbd.guid3DAlgorithm = GUID_NULL ;
IDirectSoundBuffer* pBuf;
m_pDevice->CreateSoundBuffer( &dsbd, &pBuf, NULL );
m_pDummy.reset(pBuf);
}
// そんでもって流し込む
LPVOID pPos1, pPos2;
DWORD dwLen1, dwLen2;
m_pDummy->Lock( 0, wfx.nAvgBytesPerSec, &pPos1, &dwLen1, &pPos2, &dwLen2, 0 );
{
ZeroMemory( pPos1, wfx.nAvgBytesPerSec );
}
m_pDummy->Unlock( pPos1, dwLen1, pPos2, dwLen2 );
m_pDummy->Play( 0, 0, DSBPLAY_LOOPING );
}
}}
| [
"[email protected]"
] | [
[
[
1,
192
]
]
] |
945d64aef3416c5183f9da3d6e792b26a728855a | e2f961659b90ff605798134a0a512f9008c1575b | /Example-11/MODEL_INIT.INC | 6a928c933e03145f658b702e73f93dd0dba17fdf | [] | no_license | bs-eagle/test-models | 469fe485a0d9aec98ad06d39b75901c34072cf60 | d125060649179b8e4012459c0a62905ca5235ba7 | refs/heads/master | 2021-01-22T22:56:50.982294 | 2009-11-10T05:49:22 | 2009-11-10T05:49:22 | 1,266,143 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 98 | inc | PRESSURE
900*220
/
SWAT
600*0 300*1
/
SOIL
300*0 300*1 300*0
/
RS
900*1
/
| [
"[email protected]"
] | [
[
[
1,
16
]
]
] |
18e393b03122259bc064b27a2777e1bd4a3fc826 | e580637678397200ed79532cd34ef78983e9aacd | /Grapplon/Sound.h | 657483069701cd89a4fa6f0f4124ef99a582d9c4 | [] | no_license | TimToxopeus/grapplon2 | 03520bf6b5feb2c6fcb0c5ddb135abe55d3f344b | 60f0564bdeda7d4c6e1b97148b5d060ab84c8bd5 | refs/heads/master | 2021-01-10T21:11:59.438625 | 2008-07-13T06:49:06 | 2008-07-13T06:49:06 | 41,954,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 539 | h | #pragma once
#include "Resource.h"
class CSound : public IResource
{
protected:
unsigned int m_iSound;
unsigned int m_iSource;
public:
CSound( std::string szName, unsigned int iSound ) : IResource( szName ) { m_eType = RT_SOUND; m_iSound = iSound; m_iSource = 0; }
virtual ~CSound() {}
unsigned int GetSound() { return m_iSound; }
bool CreateSource();
void SetPosition( float fX, float fY, float fZ );
void Play(bool bOverride = false);
void Clean();
bool IsPlaying();
void SetPitch(float pitch);
};
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
20
],
[
23,
23
]
],
[
[
21,
22
]
]
] |
b0312f3723651115901e0802bb69b077262e2b20 | fa5db3a4437f1e3b5f207e8d78b2652b0803e50e | /Pong/Button.h | 949acf2729f1468cb23f4d978eb1ce950f0132d9 | [] | no_license | allenparkhb/strog-pong | 524d181dd59992a747f0a7cf3cabd8d26d901b87 | 6b57189d19a256eef7e9d8130d4ee3b256985b4e | refs/heads/master | 2020-04-27T08:44:34.217184 | 2011-01-24T22:39:51 | 2011-01-24T22:39:51 | 35,724,302 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 755 | h | #pragma once
#include "Object.h"
class Button: public Object
{
private:
TexturePack m_tPack2; // the texture for the button being pressed
int top; // the y position of the first button in the menu
int spacing; // the space between buttons
eButton type; // type of button (ie PLAY, OPTIONS)
public:
TexturePack displayTexture;
virtual void Init(int loc, ScreenDim dimensions) {}
virtual void Init(int loc, ScreenDim dimensions, int texture1, int texture2);
void ChangeTextures();
virtual void Update(){int bob = 0;}
virtual void MoveBack(){int bob = 0;}
virtual void Bounce(int otherObject){int bob = 0;}
virtual void setBack(){int bob = 0;}
TexturePack getDisplayTexture() { return displayTexture; }
}; | [
"StrogAnon@e8402ffd-162d-859a-42b0-96b8e9fa5dff"
] | [
[
[
1,
25
]
]
] |
d78fadf26c72a07ce65243c6a2aec0435558ecf4 | 28ba648bc8e18d3ad3878885ad39a05ebfb9259c | /CGWorkOpenGL/MyVector.cpp | de3f4dfd962c4c92ea29ba7b4ac172ebed8cf585 | [] | no_license | LinusTIAN/cg1-winter10 | 67da233f27dcf2fa693d830598473fde7d402ece | 0b929141c6eac3b96c038656e58620767ff52d9f | refs/heads/master | 2020-05-05T08:12:56.957326 | 2011-01-31T13:24:08 | 2011-01-31T13:24:08 | 36,010,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,034 | cpp | #include "MyVector.h"
#include <cmath>
MyVector::MyVector(void)
{
m_x = m_y = m_z = 0;
}
MyVector::MyVector(double x, double y, double z)
{
m_x = x; m_y = y; m_z = z;
}
MyVector::MyVector(double from_x, double from_y, double from_z,
double to_x, double to_y, double to_z)
{
m_x = to_x - from_x;
m_y = to_y - from_y;
m_z = to_z - from_z;
}
MyVector::~MyVector(void)
{
}
double MyVector::Size(void)
{
return std::sqrt(m_x*m_x + m_y*m_y + m_z*m_z);
}
MyVector MyVector::operator/(double d)
{
return MyVector(m_x/d, m_y/d, m_z/d);
}
MyVector MyVector::operator*(double d)
{
return MyVector(m_x*d, m_y*d, m_z*d);
}
MyVector& MyVector::operator/=(double d)
{
m_x /= d; m_y /= d; m_z /= d;
return *this;
}
MyVector& MyVector::operator*=(double d)
{
m_x *= d; m_y *= d; m_z *= d;
return *this;
}
MyVector MyVector::cross(MyVector& rhs)
{
return MyVector( m_y*rhs.m_z - m_z*rhs.m_y,
m_z*rhs.m_x - m_x*rhs.m_z,
m_x*rhs.m_y - m_y*rhs.m_x );
}
| [
"slavak@2ff579a8-b8b1-c11a-477f-bc6c74f83876"
] | [
[
[
1,
57
]
]
] |
712062a4e705d4cffaa1564d3ffc75e524897bb9 | ddc9569f4950c83f98000a01dff485aa8fa67920 | /naikai/graphics/src/win32/opengl/nkRenderer.cpp | c9c9d6c2b728b2345fe5f2c6b8678469b0b7e94f | [] | no_license | chadaustin/naikai | 0a291ddabe725504cdd80c6e2c7ccb85dc5109da | 83b590b049a7e8a62faca2b0ca1d7d33e2013301 | refs/heads/master | 2021-01-10T13:28:48.743787 | 2003-02-19T19:56:24 | 2003-02-19T19:56:24 | 36,420,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,129 | cpp | #include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdio.h>
#include <math.h>
#include "nsCOMPtr.h"
#include "nsIServiceManagerUtils.h"
#include "nkIWindowingService.h"
#include "nkIWindow.h"
#include "nkIWin32Window.h"
#include "nkRenderer.h"
class Painter : public nkICommand
{
public:
Painter(nkRenderer* renderer) {
m_renderer = renderer;
}
NS_DECL_ISUPPORTS
NS_DECL_NKICOMMAND
private:
nsCOMPtr<nkRenderer> m_renderer;
};
NS_IMPL_ISUPPORTS1(Painter, nkICommand)
NS_IMETHODIMP
Painter::Execute(nsISupports* caller)
{
return m_renderer->Draw();
}
////
class Resizer : public nkICommand
{
public:
Resizer(nkRenderer* renderer) {
m_renderer = renderer;
}
NS_DECL_ISUPPORTS
NS_DECL_NKICOMMAND
private:
nsCOMPtr<nkRenderer> m_renderer;
};
NS_IMPL_ISUPPORTS1(Resizer, nkICommand)
NS_IMETHODIMP
Resizer::Execute(nsISupports* caller)
{
return m_renderer->Resize();
}
////
nkRenderer::nkRenderer()
{
m_window = 0;
m_dc = 0;
m_rc = 0;
}
nkRenderer::~nkRenderer()
{
// detach ourselves! (shouldn't be necessary)
Detach();
}
NS_IMPL_ISUPPORTS1(nkRenderer, nkIRenderer)
NS_IMETHODIMP
nkRenderer::Attach(nkIWindow* window_)
{
nsresult rv;
nsCOMPtr<nkIWindowingService> ws(
do_GetService("@naikai.aegisknight.org/windowing;1", &rv));
if (NS_FAILED(rv) || !ws) {
return NS_ERROR_FAILURE;
}
// QI to a Win32 window (we aren't allowed to attach this type of
// renderer to anything else)
nsCOMPtr<nkIWin32Window> window(do_QueryInterface(window_, &rv));
if (NS_FAILED(rv) || !window) {
return NS_ERROR_ILLEGAL_VALUE;
}
// get HWND
rv = window->GetHandle(m_window);
if (NS_FAILED(rv) || !m_window) {
return NS_ERROR_ILLEGAL_VALUE;
}
static const PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
16,
0,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
m_dc = GetDC(m_window);
if (!m_dc) {
return NS_ERROR_FAILURE;
}
int pixel_format = ChoosePixelFormat(m_dc, &pfd);
if (!pixel_format) {
ReleaseDC(m_window, m_dc);
m_dc = 0;
return NS_ERROR_FAILURE;
}
if (!SetPixelFormat(m_dc, pixel_format, &pfd)) {
ReleaseDC(m_window, m_dc);
m_dc = 0;
return NS_ERROR_FAILURE;
}
m_rc = wglCreateContext(m_dc);
if (!m_rc) {
ReleaseDC(m_window, m_dc);
m_dc = 0;
return NS_ERROR_FAILURE;
}
if (!wglMakeCurrent(m_dc, m_rc)) {
wglDeleteContext(m_rc);
m_rc = 0;
ReleaseDC(m_window, m_dc);
m_dc = 0;
return NS_ERROR_FAILURE;
}
ws->SetOnIdle(new Painter(this));
window_->SetOnResize(new Resizer(this));
rv = Resize();
if (NS_FAILED(rv)) {
return rv;
}
return Setup();
}
NS_IMETHODIMP
nkRenderer::Detach()
{
if (m_rc) {
wglMakeCurrent(0, 0);
wglDeleteContext(m_rc);
m_rc = 0;
}
if (m_dc) {
ReleaseDC(m_window, m_dc);
m_dc = 0;
}
m_window = 0;
return NS_OK;
}
NS_IMETHODIMP
nkRenderer::Draw()
{
static const struct {
int x, y, z;
} vertices[] = {
{ 1, 1, 1 },
{ 1, 1, -1 },
{ 1, -1, -1 },
{ 1, -1, 1 },
{ -1, 1, 1 },
{ -1, 1, -1 },
{ -1, -1, -1 },
{ -1, -1, 1 },
};
static const int faces[6][4] = {
{ 0, 1, 2, 3 },
{ 4, 5, 6, 7 },
{ 0, 1, 5, 4 },
{ 3, 2, 6, 7 },
{ 0, 3, 7, 4 },
{ 1, 2, 6, 5 },
};
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
DWORD t = GetTickCount();
glTranslatef(0, 0, -10);
glRotatef(t / 25.0f, 1, 0, 0);
glRotatef(t / 20.0f, 0, 1, 0);
glRotatef(t / 15.0f, 0, 0, 1);
glBegin(GL_QUADS);
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 4; ++j) {
int f = faces[i][j];
int x = vertices[f].x;
int y = vertices[f].y;
int z = vertices[f].z;
glColor3f(sin(x * t / 500.0),
sin(y * t / 700.0),
sin(z * t / 900.0));
glVertex3f(x, y, z);
}
}
glEnd();
SwapBuffers(m_dc);
return NS_OK;
}
nsresult
nkRenderer::Resize()
{
RECT client_rect;
if (!GetClientRect(m_window, &client_rect)) {
return NS_ERROR_FAILURE;
}
int width = client_rect.right;
int height = client_rect.bottom;
if (height == 0) {
height = 1;
}
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, GLfloat(width) / height, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
return NS_OK;
}
nsresult
nkRenderer::Setup()
{
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
return NS_OK;
}
| [
"aegis@ed5ae262-7be1-47e3-824f-6ab8bb33c1ce"
] | [
[
[
1,
290
]
]
] |
423cb4ccab97b697062140bc13f3947d502004f0 | 85b3c5d2c89d05f4ad9cd90c9becc2ba8912eb0f | /problem6/6.cpp | 23a5cdb472260641d644850b3742977ed8142ee7 | [] | no_license | stevenc49/project_euler | 89ce29403f363363a477a776aaf523712b98185a | 7b3463af4bc37bcd25335431e7854f47b2c021cc | refs/heads/master | 2021-03-12T21:41:45.978945 | 2011-12-16T04:44:35 | 2011-12-16T04:44:35 | 968,635 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 433 | cpp | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int MAX = 100;
int sum_of_sq = 0;
int sq_of_sum = 0;
for(int i=1; i<=MAX; i++)
{
sum_of_sq += pow((double)i,2);
}
for(int i=1; i<=MAX; i++)
{
sq_of_sum += i;
}
sq_of_sum = pow((double)sq_of_sum,2);
int diff = sq_of_sum - sum_of_sq;
cout << diff << endl;
}
| [
"[email protected]"
] | [
[
[
1,
28
]
]
] |
5728bb827123c87c13194030feaaf4ee8dfa6c81 | 394a3cb743fa873132d44a5800440e5bf7bcfad8 | /src/PriorityQueue.h | 8d82da66ffb59ab8e211b79a31eb36b7019f89c5 | [] | no_license | lfsmoura/dalgo | 19487487271b5410b3facfc0b0647c8736074fa8 | 47cfb3be3126955e822ca08179f82aa3eba1de6f | refs/heads/master | 2020-06-03T11:02:49.541436 | 2010-06-30T01:35:30 | 2010-06-30T01:35:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,388 | h | #ifndef PRIORITY_QUEUE
#define PRIORITY_QUEUE
#include "heap.h"
#include <limits>
template <class T>
class PriorityQueue {
const T MINIMO;
Heap* heap_;
T* cost_;
int maxItems_;
public:
PriorityQueue(int maxItems, T* f) : maxItems_(maxItems), cost_(f), MINIMO(std::numeric_limits<T>::min())
{
heap_ = HeapInit(maxItems+1);
HeapSetKeys(heap_, (heapvalues*)cost_);
}
int key_top(){
return HeapMin(heap_);
}
//double value_top(){
//}
void pop(){
if(!empty())
HeapDelMin(heap_);
else
exit(999);
}
void push(int key){
HeapInsert(heap_,key);
}
bool empty(){
return HeapSize(heap_) == 0;
}
void decrease(int key){
HeapDecKey(heap_, key);
}
void increase(int key){
HeapIncKey(heap_, key);
}
void remove(int key){
T temp = cost_[key];
cost_[key] = MINIMO;
decrease(key);
if( key != key_top() )
exit(100);
pop();
cost_[key] = temp;
}
void clear(){
if(!empty())
{
HeapFree(heap_);
heap_ = HeapInit(maxItems_);
HeapSetKeys(heap_, (heapvalues*)cost_);
}
}
~PriorityQueue(){
HeapFree(heap_);
}
};
//#include <vector>
//#include <algorithm>
//
//
//template <class T>
//class PriorityQueue {
// const double MINIMO;
// std::vector<int> heap_;
//
// int maxItems_;
//public:
// T* cost_;
//
// PriorityQueue(int maxItems, T* f) : maxItems_(maxItems), cost_(f), MINIMO(std::numeric_limits<T>::min())
// {
//
// }
// int key_top(){
// T mi = 9999999;
// int key = 0;
// for(std::vector<int>::iterator it = heap_.begin(); it != heap_.end(); it++)
// if(cost_[*it] < mi)
// {
// mi = cost_[*it];
// key = *it;
// }
// return key;
// }
// //double value_top(){
//
// //}
// void pop(){
// remove(key_top());
// }
// void push(int key){
// heap_.push_back(key);
// }
// bool empty(){
// return heap_.size() == 0;
// }
// //bool cmp(const int &a, const int &b){
// // //return cost_[a] >= cost_[b];
// // return true;
// //}
// void decrease(int key){
//
// }
// void increase(int key){
//
// }
// void remove(int key){
// std::vector<int>::iterator it = std::find(heap_.begin(), heap_.end(), key);
// if(it == heap_.end())
// exit(key);
// heap_.erase(it);
// }
// void clear(){
// heap_.clear();
// }
// ~PriorityQueue(){
// heap_.clear();
// }
//};
//
#endif | [
"[email protected]"
] | [
[
[
1,
131
]
]
] |
7f137c844b4eeb598038f997e99bdfa0f6b4ac98 | 347fdd4d3b75c3ab0ecca61cf3671d2e6888e0d1 | /addons/vaNetwork/src/SocketSelector.cpp | c96d5b7f81fde656947d135060a380cafe471666 | [] | no_license | sanyaade/VirtualAwesome | 29688648aa3f191cdd756c826b5c84f6f841b93f | 05f3db98500366be1e79da16f5e353e366aed01f | refs/heads/master | 2020-12-01T03:03:51.561884 | 2010-11-08T00:17:44 | 2010-11-08T00:17:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,151 | cpp | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2009 Laurent Gomila ([email protected])
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <vaNetwork/SocketSelector.h>
#include <vaNetwork/Socket.h>
#include <vaNetwork/SocketImpl.h>
#include <vaNetwork/Err.h>
#include <utility>
#ifdef _MSC_VER
#pragma warning(disable : 4127) // "conditional expression is constant" generated by the FD_SET macro
#endif
namespace vaNetwork {
////////////////////////////////////////////////////////////
struct SocketSelector::SocketSelectorImpl
{
fd_set AllSockets; ///< Set containing all the sockets handles
fd_set SocketsReady; ///< Set containing handles of the sockets that are ready
int MaxSocket; ///< Maximum socket handle
};
////////////////////////////////////////////////////////////
SocketSelector::SocketSelector() :
myImpl(new SocketSelectorImpl)
{
Clear();
}
////////////////////////////////////////////////////////////
SocketSelector::SocketSelector(const SocketSelector& copy) :
myImpl(new SocketSelectorImpl(*copy.myImpl))
{
}
////////////////////////////////////////////////////////////
SocketSelector::~SocketSelector()
{
delete myImpl;
}
////////////////////////////////////////////////////////////
void SocketSelector::Add(Socket& socket)
{
FD_SET(socket.GetHandle(), &myImpl->AllSockets);
int size = static_cast<int>(socket.GetHandle());
if (size > myImpl->MaxSocket)
myImpl->MaxSocket = size;
}
////////////////////////////////////////////////////////////
void SocketSelector::Remove(Socket& socket)
{
FD_CLR(socket.GetHandle(), &myImpl->AllSockets);
FD_CLR(socket.GetHandle(), &myImpl->SocketsReady);
}
////////////////////////////////////////////////////////////
void SocketSelector::Clear()
{
FD_ZERO(&myImpl->AllSockets);
FD_ZERO(&myImpl->SocketsReady);
myImpl->MaxSocket = 0;
}
////////////////////////////////////////////////////////////
bool SocketSelector::Wait(float timeout)
{
// Setup the timeout
timeval time;
time.tv_sec = static_cast<long>(timeout);
time.tv_usec = (static_cast<long>(timeout * 1000) % 1000) * 1000;
// Initialize the set that will contain the sockets that are ready
myImpl->SocketsReady = myImpl->AllSockets;
// Wait until one of the sockets is ready for reading, or timeout is reached
int count = select(myImpl->MaxSocket + 1, &myImpl->SocketsReady, NULL, NULL, timeout > 0 ? &time : NULL);
return count > 0;
}
////////////////////////////////////////////////////////////
bool SocketSelector::IsReady(Socket& socket) const
{
return FD_ISSET(socket.GetHandle(), &myImpl->SocketsReady) != 0;
}
////////////////////////////////////////////////////////////
SocketSelector& SocketSelector::operator =(const SocketSelector& right)
{
SocketSelector temp(right);
std::swap(myImpl, temp.myImpl);
return *this;
}
}
| [
"[email protected]"
] | [
[
[
1,
139
]
]
] |
444cabd2e990798b2392a590dfefd0025746db5d | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/branches/persistence2/engine/core/include/ContentLoader.h | 1c74582281d7465fde85b13834e3db0ff2f4bd14 | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,379 | h | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#ifndef __ContentLoader_H__
#define __ContentLoader_H__
#include "CorePrerequisites.h"
#include "Properties.h"
namespace rl
{
class _RlCoreExport ContentLoader : public PropertyHolder
{
public:
ContentLoader(const Ogre::String& resourceGroup);
virtual ~ContentLoader();
virtual void loadContent() = 0;
virtual void unloadContent() = 0;
const Property getProperty(const CeGuiString& key) const;
void setProperty(const CeGuiString& key, const Property& value);
PropertyKeys getAllPropertyKeys() const;
virtual const CeGuiString getClassName() const = 0;
};
}
#endif
| [
"timm@4c79e8ff-cfd4-0310-af45-a38c79f83013"
] | [
[
[
1,
43
]
]
] |
a9bccc483e693cf724b98cffff5f8177477aeb03 | b4e12edfcdad3ac2ebb7ecd40a825ec70f7a12fc | /src/cubuString.h | a156fe166355a57ab99329021dfd961a183074fc | [] | no_license | curlyfrie/cubu | f7b40c77323b0148d96225c110bc8f76920eb0a7 | 80d2fe4449d8b072be99aa75b9d2a4278120f8b3 | refs/heads/master | 2021-01-01T18:37:00.581538 | 2010-06-28T10:18:47 | 2010-06-28T10:18:47 | 32,509,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | h | /*
* cubuString.h
* cubu
*
* Strings to draw in GUI
*/
#include <iostream>
#include "ofMain.h"
class cubuString {
public:
float x;
float y;
int color;
std::string text;
ofTrueTypeFont font;
cubuString();
cubuString(std::string ptext, float px, float py, std::string pfont, int psize, int pcolor);
cubuString(std::string ptext, float px, float py, std::string pfont, int psize);
cubuString(std::string ptext, float px, float py);
cubuString(std::string ptext);
void appendString(std::string text2);
std::string str_replace (std::string rep, std::string wit, std::string in);
~cubuString();
private:
void setDefaultValues();
}; | [
"danielfritz1@253ed6ba-2f75-df95-9641-daec35089882",
"hiller.elias@253ed6ba-2f75-df95-9641-daec35089882",
"alexander.fried1986@253ed6ba-2f75-df95-9641-daec35089882"
] | [
[
[
1,
26
],
[
28,
28
],
[
30,
30
],
[
32,
38
]
],
[
[
27,
27
]
],
[
[
29,
29
],
[
31,
31
]
]
] |
772702fbc01f69542147760cc10e0f6ce0e7c87a | e9944cc3f8c362cd0314a2d7a01291ed21de19ee | / xcommon/Public/Ext_Memory.cpp | caf56f102fff83d960d35e98ab9c21b6e251d533 | [] | no_license | wermanhme1990/xcommon | 49d7185a28316d46992ad9311ae9cdfe220cb586 | c9b1567da1f11e7a606c6ed638a9fde1f6ece577 | refs/heads/master | 2016-09-06T12:43:43.593776 | 2008-12-05T04:24:11 | 2008-12-05T04:24:11 | 39,864,906 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,686 | cpp |
/********************************************************************
Copyright (c) 2002-2003 汉王科技有限公司. 版权所有.
文件名称: Ext_Memory.h
文件内容: 内存操作的封装 可以提高程序可调适性
版本历史: 1.0
作者: xuejuntao [email protected] 2008/02/26
*********************************************************************/
#include "stdafx.h"
#include "Ext_Memory.h"
#include "Ext_Type.h"
#include <assert.h>
#define Mem_MinOptLen (8)
static LONG BO_LeftShift( const LONG& nValue, const LONG& nBit )
{
return (nValue << nBit );
};
BOOL WINAPI XMemFill(void *pvMem, CHAR bChrFill, LONG nSize)
{
assert(NULL != pvMem);
assert(0 < nSize);
LONG nRet = TRUE;
#ifdef _DEBUG//////////////////////////////////////////////////////////////////////////
// assert(!IsBadWritePtr(pvMem, nSize));
#endif//////////////////////////////////////////////////////////////////////////
XMemSet(pvMem, bChrFill, nSize);
return nRet;
}
BOOL WINAPI XMemZero(void *pvMem, LONG nSize)
{
assert(NULL != pvMem);
assert(0 < nSize);
return XMemFill(pvMem, 0, nSize);
}
BOOL WINAPI XMemEqual(const void *pvMemDest, const void *pvMemSrc, LONG nSize)
{
assert(NULL != pvMemDest);
assert(NULL != pvMemSrc);
assert(0 < nSize);
return !XMemCompare((void *)pvMemDest, (void *)pvMemSrc, nSize);
}
void WINAPI XMemFree(void** ppvMem)
{
assert(NULL != ppvMem);
#ifdef _DEBUG//////////////////////////////////////////////////////////////////////////
{
if (NULL != *ppvMem)
{
LONG nSize = (LONG)_msize(*ppvMem);
if (0 != nSize)
{
XMemSet(*ppvMem, 0, nSize);
}
}
}
#endif//////////////////////////////////////////////////////////////////////////
free(*ppvMem);
*ppvMem = NULL;
}
BOOL WINAPI XMemAlloc(void** ppvMem, LONG nSize)
{
BYTE** ppbMem = (BYTE**)ppvMem;
assert(NULL != ppvMem && 0 < nSize);
*ppbMem = (BYTE*)malloc(nSize);
//*ppbMem = new BYTE[nSize];
#ifdef _DEBUG//////////////////////////////////////////////////////////////////////////
{
if(NULL != *ppbMem)
{
XMemZero(*ppbMem, nSize);
}
}
#endif//////////////////////////////////////////////////////////////////////////
return(NULL != *ppbMem);
}
BOOL WINAPI XMemResize(void** ppvMem, LONG nSizeNew)
{
BYTE **ppbMem = (BYTE **)ppvMem;
BYTE *pbMem = *ppbMem;
BYTE *pbMemResized = NULL;
assert(NULL != ppbMem && 0 != nSizeNew);
#ifdef _DEBUG //////////////////////////////////////////////////////////////////////////
LONG nSizeOrg = 0;
{
if (NULL != pbMem)
{
nSizeOrg = (LONG)_msize(pbMem);
}
else
{
nSizeOrg = 0;
}
/* 如果缩小,冲掉块尾释放的内容 */
if(nSizeNew < nSizeOrg)
{
XMemZero(pbMem + nSizeNew, nSizeOrg - nSizeNew);
}
else if(nSizeNew > nSizeOrg && 0 != nSizeOrg)
{
BYTE* pbTmp = NULL;
if(XMemAlloc((void **)&pbTmp, nSizeOrg))
{
XMemCopy(pbTmp, pbMem, nSizeOrg);
XMemFree((void **)&pbMem);
pbMem = pbTmp;
}
}
}
#endif//////////////////////////////////////////////////////////////////////////
pbMemResized = (BYTE*)realloc(pbMem, nSizeNew);
if (0 == nSizeNew)
{//此时相当于调用free
pbMemResized = NULL;
*ppbMem = NULL;
}
if(NULL != pbMemResized)
{
#ifdef _DEBUG//////////////////////////////////////////////////////////////////////////
{
if(nSizeNew > nSizeOrg)
{/* 如果扩大,对尾部增加的内容进行初始化 */
XMemZero(pbMemResized + nSizeOrg, nSizeNew - nSizeOrg);
}
}
#endif//////////////////////////////////////////////////////////////////////////
*ppbMem = pbMemResized;
}
return(NULL != pbMemResized);
}
LONG WINAPI XMemSet( void *p, const CHAR& b, const LONG& n )
{
CHAR *pchEnd;
//LONG nTail;
LONG nHead , nMiddle;
CHAR *pch = (CHAR*)p;
DWORD bInit = (BYTE)b;
if( pch == NULL || n <= 0 )
return 0;
pchEnd = ((CHAR*)p) + n;
nHead = ((LONG)p) & 3;
if( nHead )
{
nHead = 4 - nHead;
nMiddle = n - nHead;//-= 4;
}
else
{
nMiddle = n;
}
//Deal with head part
if( nHead )
{
CHAR *pchHeadEnd = pch + _min( n, nHead );
for( ; pch < pchHeadEnd; pch++ )
{
*pch = b;
}
}
//Deal with middle part
if( nMiddle > 0 )
{
LONG nSetValue = BO_LeftShift( bInit, 24) + BO_LeftShift(bInit , 16) + BO_LeftShift(bInit, 8) + bInit;
LONG *pnEnd = (LONG*)pch + ( nMiddle >> 2);
for( ; (LONG*)pch < pnEnd; pch += 4 )
{
*((LONG*)pch) = nSetValue;
}
}
//Deal with tail part
//if( nTail )
{
//pchEnd = (CHAR*)p + n;
for( ; pch < pchEnd; pch++ )
{
*pch = b;
}
}
return n;
}
LONG WINAPI XMemCopy( void *pDest, const void *const pSrc, const LONG& n )
{
register CHAR *pchDst, *pchSrc, *pchDstEnd;
LONG nAddrDiff, nMiddle, nHead;// = 3;
if( n <= 0 || !pDest || !pSrc )
{
return 0;
}
if( pDest > pSrc )//&& pchSource + n > pchDest )
{
return XMemMove( pDest, pSrc, n);
}
pchDst = (CHAR*)pDest;
pchSrc = (CHAR*)pSrc;
pchDstEnd = ((CHAR*)pDest ) + n;
if( n >= Mem_MinOptLen )
{
nAddrDiff = ( ((CHAR*)pchSrc) - ((CHAR*)pchDst) ) & 3;
}
else
{
nAddrDiff = 3;
}
switch( nAddrDiff )
{
case 0:// 4-byte aligned
{
nHead = (((LONG)pchDst) & 3);
//compute the odd address part
if( 0 != nHead )
{
nHead = 4 - nHead;
nMiddle = (n - nHead);// & 0xfffffffc;
}
else
{
nMiddle = n;
}
//copy the head part
if( nHead )
{
CHAR *pchDstHeadEnd = ((CHAR*)pchDst) + _min( nHead, n );
for( ; pchDst < pchDstHeadEnd; pchDst++, pchSrc++ )
{
*pchDst = *pchSrc;
}
}
//copy the middle part
if( nMiddle > 0 )
{
LONG *pnDstEnd = ((LONG *)pchDst) + (nMiddle >> 2);
for( ; ((LONG *)pchDst) < pnDstEnd; pchDst += 4, pchSrc += 4 )
{
*((LONG *)pchDst) = *((LONG *)pchSrc);
}
}
// copy the tail part
for( ; pchDst < pchDstEnd; pchDst++, pchSrc++ )
{
*pchDst = *pchSrc;
}
}
break;
case 2:
{//2-byte aligned
nHead = (((LONG)pchDst) & 1);
//compute the odd address part
if( 0 != nHead )
{
nHead = 2 - nHead;
nMiddle = n - nHead;
}
else
{
nMiddle = n;
}
//copy the head part
if( nHead )
{
CHAR *pchDstHeadEnd = ((CHAR*)pchDst) + _min(nHead, n);
for( ; pchDst < pchDstHeadEnd; pchDst++, pchSrc++ )
{
*pchDst = *pchSrc;
}
}
//copy the middle part
if( nMiddle > 0)
{
short *psDstEnd = ((short*)pchDst) + ( nMiddle >> 1);
for( ; ((short*)pchDst) < psDstEnd; pchDst += 2, pchSrc += 2 )
{
*((short*)pchDst) = *((short*)pchSrc);
}
}
// copy the tail part
for( ; pchDst < pchDstEnd; pchDst++, pchSrc++ )
{
*pchDst = *pchSrc;
}
}
break;
default:
// copy the tail part
for( ; pchDst < pchDstEnd; pchDst++, pchSrc++ )
{
*pchDst = *pchSrc;
}
}
return n;
}
LONG WINAPI XMemMove( void *pDest, const void *const pSrc, const LONG& n )
{
register CHAR *pchDest, *pchSrc, *pchDestBgn ;
LONG nAddrDiff, nMiddle, nTail;// = 3;
if( n <= 0 || !pDest || !pSrc )
{
return 0;
}
if( (DWORD)pDest < (DWORD)pSrc )//
//|| (CHAR*)pSrc + n < (CHAR*)pDest )// not overlap
{
return XMemCopy( pDest, pSrc, n);
}
pchDestBgn = (CHAR*)pDest;
pchDest = (CHAR*)pDest + n;
pchSrc = (CHAR*)pSrc + n;
if( n >= Mem_MinOptLen )
nAddrDiff = (pchDest - pchSrc) & 3;
else
nAddrDiff = 3;
switch( nAddrDiff )
{
case 0:
{
nTail = (((LONG)pchDest) & 3);
if( nTail )
{
nMiddle = n - nTail;// & 0xfffffffc;
}
else
nMiddle = n;
//Deal with the tail part
if( nTail )
{
CHAR *pchDstTailBgn = pchDest - _min( nTail, n);
for( ; pchDest > pchDstTailBgn; )
{
pchDest--, pchSrc--;
*pchDest = *pchSrc;
}
}
//copy the middle part
if( nMiddle > 0 )
{
LONG *pnDstBgn = ((LONG*)pchDest) - ( nMiddle >> 2);
for( ; ((LONG*)pchDest) > pnDstBgn; )
{
pchDest -= 4;
pchSrc -= 4;
*((LONG*)pchDest) = *((LONG*)pchSrc);
}
}
//Copy the head part
for( ; pchDest > pchDestBgn; )
{
pchDest--, pchSrc--;
*pchDest = *pchSrc;
}
}
break;
case 2:
{
nTail = (((LONG)pchDest) & 1);
if( nTail )
{
nMiddle = n - nTail;
}
else
nMiddle = n;
//Deal with the tail part
if( nTail )
{
CHAR *pchDstTailBgn = pchDest - _min( nTail, n );
for( ; pchDest > pchDstTailBgn; )
{
pchDest--, pchSrc--;
*pchDest = *pchSrc;
}
}
//copy the middle part
if( nMiddle > 0 )
{
short *psDstBgn = ((short*)pchDest) - ( nMiddle >> 1);
for( ; (short*)pchDest > psDstBgn; )
{
pchDest -= 2;
pchSrc -= 2;
*((short*)pchDest) = *((short*)pchSrc);
}
}
//Copy the head part
for( ; pchDest > pchDestBgn; )
{
pchDest--, pchSrc--;
*pchDest = *pchSrc;
}
}
break;
default:
//Copy the head part
for( ; pchDest > pchDestBgn; )
{
pchDest--, pchSrc--;
*pchDest = *pchSrc;
}
}
return n;
}
//XUE写的
LONG WINAPI XMemCompare( void *const pDest, void *const pSrc, const LONG& n )
{
register CHAR *pchDst = NULL, *pchSrc = NULL, *pchDstEnd = NULL;
register LONG iRet = 0;
if( n <= 0 || pDest == NULL || pSrc == NULL )
{
iRet = 0;
goto _Exit;
}
LONG nLen = n;
pchDst = (CHAR*)pDest;
pchSrc = (CHAR*)pSrc;
while(nLen -- > 0 && 0 == (iRet = *(pchDst ++ ) - *(pchSrc ++)))
{
NULL;
}
_Exit:
return iRet;
} | [
"jtxuee@8e66cb3a-4d54-0410-a772-b92400a1a2d6"
] | [
[
[
1,
473
]
]
] |
5374d570488b3adede5973309b0ac5ad44160521 | b2b5c3694476d1631322a340c6ad9e5a9ec43688 | /Baluchon/BoxDetector.cpp | 5e024445eaec949ab45b515b1494947c2df0b110 | [] | no_license | jpmn/rough-albatross | 3c456ea23158e749b029b2112b2f82a7a5d1fb2b | eb2951062f6c954814f064a28ad7c7a4e7cc35b0 | refs/heads/master | 2016-09-05T12:18:01.227974 | 2010-12-19T08:03:25 | 2010-12-19T08:03:25 | 32,195,707 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,662 | cpp | #include "BoxDetector.h"
#include "MathUtility.h"
using namespace baluchon::utilities;
namespace baluchon { namespace core { namespace services { namespace objectdetection {
BoxDetector::BoxDetector(void) {
mPrismFactory = new PrismFactory();
mRectangleDetector = new RectangleDetector();
}
BoxDetector::~BoxDetector(void) {
delete mPrismFactory;
delete mRectangleDetector;
}
vector<IDetectable*> BoxDetector::find(IplImage* img, IplImage* src) {
vector<BoxPrism*> mListBoxes;
vector<IDetectable*> wListDetectableFacets = mRectangleDetector->find(img, src);
vector<RectangularFacet*> mListFacets;//(wListDetectableFacets.begin(), wListDetectableFacets.end())
for (unsigned int i = 0; i < wListDetectableFacets.size(); i++) {
mListFacets.push_back(static_cast<RectangularFacet*>(wListDetectableFacets[i]));
}
if (mListFacets.size() >= 3) {
// Trouver 3 faces avec un sommet commun
for (unsigned int i = 0; i < mListFacets.size(); i++) {
RectangularFacet* facet1 = mListFacets[i];
for (unsigned int j = 0; j < mListFacets.size(); j++) {
RectangularFacet* facet2 = mListFacets[j];
for (unsigned int k = 0; k < mListFacets.size(); k++) {
RectangularFacet* facet3 = mListFacets[k];
if (facet1 != facet2 && facet2 != facet3 && facet3 != facet1) {
CvPoint dpt = MathUtility::middle(facet1->getTopRightVertex(), facet2->getTopLeftVertex());
if (facet3->getTopRightVertex().x < facet3->getBottomRightVertex().x)
dpt = MathUtility::middle(dpt, facet3->getBottomLeftVertex());
else
dpt = MathUtility::middle(dpt, facet3->getBottomRightVertex());
double dt1 = MathUtility::sqrtdistance(facet1->getTopRightVertex(), dpt);
double dt2 = MathUtility::sqrtdistance(facet2->getTopLeftVertex(), dpt);
double dt3;
if (facet3->getTopRightVertex().x < facet3->getBottomRightVertex().x)
dt3 = MathUtility::sqrtdistance(facet3->getBottomLeftVertex(), dpt);
else
dt3 = MathUtility::sqrtdistance(facet3->getBottomRightVertex(), dpt);
if (dt1 < mDistanceTolerance && dt2 < mDistanceTolerance && dt3 < mDistanceTolerance) {
BoxPrism* wBoxPrism = mPrismFactory->createBoxPrism(facet1, facet2, facet3);
mListBoxes.push_back(wBoxPrism);
// TODO : supprimer les faces utilisées.
}
}
}
}
}
}
vector<IDetectable*> wListDetectables(mListBoxes.begin(), mListBoxes.end());
return wListDetectables;
}
void BoxDetector::setDistanceTolerance(double distanceTolerance) {
mDistanceTolerance = distanceTolerance;
}
}}}}; | [
"jpmorin196@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5"
] | [
[
[
1,
80
]
]
] |
1b2436df93df468dffcfaef38d41ec642e6e06de | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/numeric/ublas/test4/test43.cpp | c32525e2f10b05fbfc0fdfeb5a33503a3aee097c | [] | no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,748 | cpp | //
// Copyright (c) 2000-2002
// Joerg Walter, Mathias Koch
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation. The authors make no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
//
// The authors gratefully acknowledge the support of
// GeNeSys mbH & Co. KG in producing this work.
//
#include "test4.hpp"
// Test matrix expression templates
template<class M, int N>
struct test_my_matrix {
typedef typename M::value_type value_type;
template<class MP>
void test_with (MP &m1, MP &m2, MP &m3) const {
{
value_type t;
// Default Construct
MP default_constuct;
initialize_matrix (default_constuct);
std::cout << "default construct = " << default_constuct << std::endl;
// Copy and swap
initialize_matrix (m1);
initialize_matrix (m2);
m1 = m2;
std::cout << "m1 = m2 = " << m1 << std::endl;
m1.assign_temporary (m2);
std::cout << "m1.assign_temporary (m2) = " << m1 << std::endl;
m1.swap (m2);
std::cout << "m1.swap (m2) = " << m1 << " " << m2 << std::endl;
// Unary matrix operations resulting in a matrix
initialize_matrix (m1);
m2 = - m1;
std::cout << "- m1 = " << m2 << std::endl;
m2 = ublas::conj (m1);
std::cout << "conj (m1) = " << m2 << std::endl;
// Binary matrix operations resulting in a matrix
initialize_matrix (m1);
initialize_matrix (m2);
m3 = m1 + m2;
std::cout << "m1 + m2 = " << m3 << std::endl;
m3 = m1 - m2;
std::cout << "m1 - m2 = " << m3 << std::endl;
// Scaling a matrix
t = N;
initialize_matrix (m1);
m2 = value_type (1.) * m1;
std::cout << "1. * m1 = " << m2 << std::endl;
m2 = t * m1;
std::cout << "N * m1 = " << m2 << std::endl;
initialize_matrix (m1);
m2 = m1 * value_type (1.);
std::cout << "m1 * 1. = " << m2 << std::endl;
m2 = m1 * t;
std::cout << "m1 * N = " << m2 << std::endl;
// Some assignments
initialize_matrix (m1);
initialize_matrix (m2);
m2 += m1;
std::cout << "m2 += m1 = " << m2 << std::endl;
m2 -= m1;
std::cout << "m2 -= m1 = " << m2 << std::endl;
m2 = m2 + m1;
std::cout << "m2 = m2 + m1 = " << m2 << std::endl;
m2 = m2 - m1;
std::cout << "m2 = m2 - m1 = " << m2 << std::endl;
m1 *= value_type (1.);
std::cout << "m1 *= 1. = " << m1 << std::endl;
m1 *= t;
std::cout << "m1 *= N = " << m1 << std::endl;
// Transpose
initialize_matrix (m1);
m2 = ublas::trans (m1);
std::cout << "trans (m1) = " << m2 << std::endl;
// Hermitean
initialize_matrix (m1);
m2 = ublas::herm (m1);
std::cout << "herm (m1) = " << m2 << std::endl;
// Matrix multiplication
initialize_matrix (m1);
initialize_matrix (m2);
// Banded times banded isn't banded
std::cout << "prod (m1, m2) = " << ublas::prod (m1, m2) << std::endl;
}
}
void operator () () const {
{
#ifdef USE_BANDED
M m1 (N, N, 1, 1), m2 (N, N, 1, 1), m3 (N, N, 1, 1);
#endif
#ifdef USE_DIAGONAL
M m1 (N, N), m2 (N, N), m3 (N, N);
#endif
test_with (m1, m2, m3);
#ifdef USE_RANGE
ublas::matrix_range<M> mr1 (m1, ublas::range (0, N), ublas::range (0, N)),
mr2 (m2, ublas::range (0, N), ublas::range (0, N)),
mr3 (m3, ublas::range (0, N), ublas::range (0, N));
test_with (mr1, mr2, mr3);
#endif
#ifdef USE_SLICE
ublas::matrix_slice<M> ms1 (m1, ublas::slice (0, 1, N), ublas::slice (0, 1, N)),
ms2 (m2, ublas::slice (0, 1, N), ublas::slice (0, 1, N)),
ms3 (m3, ublas::slice (0, 1, N), ublas::slice (0, 1, N));
test_with (ms1, ms2, ms3);
#endif
}
}
void operator () (int) const {
#ifdef USE_ADAPTOR
{
#ifdef USE_BANDED
M m1 (N, N, 1, 1), m2 (N, N, 1, 1), m3 (N, N, 1, 1);
ublas::banded_adaptor<M> bam1 (m1, 1, 1), bam2 (m2, 1, 1), bam3 (m3, 1, 1);
test_with (bam1, bam2, bam3);
#ifdef USE_RANGE
ublas::matrix_range<ublas::banded_adaptor<M> > mr1 (bam1, ublas::range (0, N), ublas::range (0, N)),
mr2 (bam2, ublas::range (0, N), ublas::range (0, N)),
mr3 (bam3, ublas::range (0, N), ublas::range (0, N));
test_with (mr1, mr2, mr3);
#endif
#ifdef USE_SLICE
ublas::matrix_slice<ublas::banded_adaptor<M> > ms1 (bam1, ublas::slice (0, 1, N), ublas::slice (0, 1, N)),
ms2 (bam2, ublas::slice (0, 1, N), ublas::slice (0, 1, N)),
ms3 (bam3, ublas::slice (0, 1, N), ublas::slice (0, 1, N));
test_with (ms1, ms2, ms3);
#endif
#endif
#ifdef USE_DIAGONAL
M m1 (N, N), m2 (N, N), m3 (N, N);
ublas::diagonal_adaptor<M> dam1 (m1), dam2 (m2), dam3 (m3);
test_with (dam1, dam2, dam3);
#ifdef USE_RANGE
ublas::matrix_range<ublas::diagonal_adaptor<M> > mr1 (dam1, ublas::range (0, N), ublas::range (0, N)),
mr2 (dam2, ublas::range (0, N), ublas::range (0, N)),
mr3 (dam3, ublas::range (0, N), ublas::range (0, N));
test_with (mr1, mr2, mr3);
#endif
#ifdef USE_SLICE
ublas::matrix_slice<ublas::diagonal_adaptor<M> > ms1 (dam1, ublas::slice (0, 1, N), ublas::slice (0, 1, N)),
ms2 (dam2, ublas::slice (0, 1, N), ublas::slice (0, 1, N)),
ms3 (dam3, ublas::slice (0, 1, N), ublas::slice (0, 1, N));
test_with (ms1, ms2, ms3);
#endif
#endif
}
#endif
}
};
// Test matrix
void test_matrix () {
std::cout << "test_matrix" << std::endl;
#ifdef USE_BANDED
#ifdef USE_BOUNDED_ARRAY
#ifdef USE_FLOAT
std::cout << "float, bounded_array" << std::endl;
test_my_matrix<ublas::banded_matrix<float, ublas::row_major, ublas::bounded_array<float, 3 * 3> >, 3 > () ();
test_my_matrix<ublas::banded_matrix<float, ublas::row_major, ublas::bounded_array<float, 3 * 3> >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "double, bounded_array" << std::endl;
test_my_matrix<ublas::banded_matrix<double, ublas::row_major, ublas::bounded_array<double, 3 * 3> >, 3 > () ();
test_my_matrix<ublas::banded_matrix<double, ublas::row_major, ublas::bounded_array<double, 3 * 3> >, 3 > () (0);
#endif
#ifdef USE_STD_COMPLEX
#ifdef USE_FLOAT
std::cout << "std::complex<float>, bounded_array" << std::endl;
test_my_matrix<ublas::banded_matrix<std::complex<float>, ublas::row_major, ublas::bounded_array<std::complex<float>, 3 * 3> >, 3 > () ();
test_my_matrix<ublas::banded_matrix<std::complex<float>, ublas::row_major, ublas::bounded_array<std::complex<float>, 3 * 3> >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "std::complex<double>, bounded_array" << std::endl;
test_my_matrix<ublas::banded_matrix<std::complex<double>, ublas::row_major, ublas::bounded_array<std::complex<double>, 3 * 3> >, 3 > () ();
test_my_matrix<ublas::banded_matrix<std::complex<double>, ublas::row_major, ublas::bounded_array<std::complex<double>, 3 * 3> >, 3 > () (0);
#endif
#endif
#endif
#ifdef USE_UNBOUNDED_ARRAY
#ifdef USE_FLOAT
std::cout << "float, unbounded_array" << std::endl;
test_my_matrix<ublas::banded_matrix<float, ublas::row_major, ublas::unbounded_array<float> >, 3 > () ();
test_my_matrix<ublas::banded_matrix<float, ublas::row_major, ublas::unbounded_array<float> >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "double, unbounded_array" << std::endl;
test_my_matrix<ublas::banded_matrix<double, ublas::row_major, ublas::unbounded_array<double> >, 3 > () ();
test_my_matrix<ublas::banded_matrix<double, ublas::row_major, ublas::unbounded_array<double> >, 3 > () (0);
#endif
#ifdef USE_STD_COMPLEX
#ifdef USE_FLOAT
std::cout << "std::complex<float>, unbounded_array" << std::endl;
test_my_matrix<ublas::banded_matrix<std::complex<float>, ublas::row_major, ublas::unbounded_array<std::complex<float> > >, 3 > () ();
test_my_matrix<ublas::banded_matrix<std::complex<float>, ublas::row_major, ublas::unbounded_array<std::complex<float> > >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "std::complex<double>, unbounded_array" << std::endl;
test_my_matrix<ublas::banded_matrix<std::complex<double>, ublas::row_major, ublas::unbounded_array<std::complex<double> > >, 3 > () ();
test_my_matrix<ublas::banded_matrix<std::complex<double>, ublas::row_major, ublas::unbounded_array<std::complex<double> > >, 3 > () (0);
#endif
#endif
#endif
#ifdef USE_STD_VECTOR
#ifdef USE_FLOAT
std::cout << "float, std::vector" << std::endl;
test_my_matrix<ublas::banded_matrix<float, ublas::row_major, std::vector<float> >, 3 > () ();
test_my_matrix<ublas::banded_matrix<float, ublas::row_major, std::vector<float> >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "double, std::vector" << std::endl;
test_my_matrix<ublas::banded_matrix<double, ublas::row_major, std::vector<double> >, 3 > () ();
test_my_matrix<ublas::banded_matrix<double, ublas::row_major, std::vector<double> >, 3 > () (0);
#endif
#ifdef USE_STD_COMPLEX
#ifdef USE_FLOAT
std::cout << "std::complex<float>, std::vector" << std::endl;
test_my_matrix<ublas::banded_matrix<std::complex<float>, ublas::row_major, std::vector<std::complex<float> > >, 3 > () ();
test_my_matrix<ublas::banded_matrix<std::complex<float>, ublas::row_major, std::vector<std::complex<float> > >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "std::complex<double>, std::vector" << std::endl;
test_my_matrix<ublas::banded_matrix<std::complex<double>, ublas::row_major, std::vector<std::complex<double> > >, 3 > () ();
test_my_matrix<ublas::banded_matrix<std::complex<double>, ublas::row_major, std::vector<std::complex<double> > >, 3 > () (0);
#endif
#endif
#endif
#endif
#ifdef USE_DIAGONAL
#ifdef USE_BOUNDED_ARRAY
#ifdef USE_FLOAT
std::cout << "float, bounded_array" << std::endl;
test_my_matrix<ublas::diagonal_matrix<float, ublas::row_major, ublas::bounded_array<float, 3 * 3> >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<float, ublas::row_major, ublas::bounded_array<float, 3 * 3> >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "double, bounded_array" << std::endl;
test_my_matrix<ublas::diagonal_matrix<double, ublas::row_major, ublas::bounded_array<double, 3 * 3> >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<double, ublas::row_major, ublas::bounded_array<double, 3 * 3> >, 3 > () (0);
#endif
#ifdef USE_STD_COMPLEX
#ifdef USE_FLOAT
std::cout << "std::complex<float>, bounded_array" << std::endl;
test_my_matrix<ublas::diagonal_matrix<std::complex<float>, ublas::row_major, ublas::bounded_array<std::complex<float>, 3 * 3> >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<std::complex<float>, ublas::row_major, ublas::bounded_array<std::complex<float>, 3 * 3> >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "std::complex<double>, bounded_array" << std::endl;
test_my_matrix<ublas::diagonal_matrix<std::complex<double>, ublas::row_major, ublas::bounded_array<std::complex<double>, 3 * 3> >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<std::complex<double>, ublas::row_major, ublas::bounded_array<std::complex<double>, 3 * 3> >, 3 > () (0);
#endif
#endif
#endif
#ifdef USE_UNBOUNDED_ARRAY
#ifdef USE_FLOAT
std::cout << "float, unbounded_array" << std::endl;
test_my_matrix<ublas::diagonal_matrix<float, ublas::row_major, ublas::unbounded_array<float> >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<float, ublas::row_major, ublas::unbounded_array<float> >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "double, unbounded_array" << std::endl;
test_my_matrix<ublas::diagonal_matrix<double, ublas::row_major, ublas::unbounded_array<double> >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<double, ublas::row_major, ublas::unbounded_array<double> >, 3 > () (0);
#endif
#ifdef USE_STD_COMPLEX
#ifdef USE_FLOAT
std::cout << "std::complex<float>, unbounded_array" << std::endl;
test_my_matrix<ublas::diagonal_matrix<std::complex<float>, ublas::row_major, ublas::unbounded_array<std::complex<float> > >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<std::complex<float>, ublas::row_major, ublas::unbounded_array<std::complex<float> > >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "std::complex<double>, unbounded_array" << std::endl;
test_my_matrix<ublas::diagonal_matrix<std::complex<double>, ublas::row_major, ublas::unbounded_array<std::complex<double> > >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<std::complex<double>, ublas::row_major, ublas::unbounded_array<std::complex<double> > >, 3 > () (0);
#endif
#endif
#endif
#ifdef USE_STD_VECTOR
#ifdef USE_FLOAT
std::cout << "float, std::vector" << std::endl;
test_my_matrix<ublas::diagonal_matrix<float, ublas::row_major, std::vector<float> >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<float, ublas::row_major, std::vector<float> >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "double, std::vector" << std::endl;
test_my_matrix<ublas::diagonal_matrix<double, ublas::row_major, std::vector<double> >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<double, ublas::row_major, std::vector<double> >, 3 > () (0);
#endif
#ifdef USE_STD_COMPLEX
#ifdef USE_FLOAT
std::cout << "std::complex<float>, std::vector" << std::endl;
test_my_matrix<ublas::diagonal_matrix<std::complex<float>, ublas::row_major, std::vector<std::complex<float> > >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<std::complex<float>, ublas::row_major, std::vector<std::complex<float> > >, 3 > () (0);
#endif
#ifdef USE_DOUBLE
std::cout << "std::complex<double>, std::vector" << std::endl;
test_my_matrix<ublas::diagonal_matrix<std::complex<double>, ublas::row_major, std::vector<std::complex<double> > >, 3 > () ();
test_my_matrix<ublas::diagonal_matrix<std::complex<double>, ublas::row_major, std::vector<std::complex<double> > >, 3 > () (0);
#endif
#endif
#endif
#endif
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
] | [
[
[
1,
352
]
]
] |
da138420aaea2bb5c1c11cd18bb1db6309ffcc02 | 56c792a91c174293c8f848ea5498c1145b4946fe | /rgrow-release/RegionGrowingBase.h | 9f573bc3668d258c523cbc8ab1c94bac0c21feb9 | [] | no_license | ltflores/csc821a3 | f9e4e1d31eaefaa6246515b444d1a9008d8b8f94 | cc22d481e466172dfdac20366d41a14bf2eb2470 | refs/heads/master | 2020-06-12T18:13:05.260330 | 2011-05-08T22:39:32 | 2011-05-08T22:39:32 | 32,131,514 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,624 | h | /*=========================================================================
Program: Region Gorwing Application
Course: CSC821
Date: April 13, 2011
Version: 1.0
Author: Lorenzo Flores
Notes: Code based on ITK region growing segmentation application.
=========================================================================*/
#ifndef REGIONGROWINGBASE
#define REGIONGROWINGBASE
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "DICOMFileReader.h"
#include "itkImageSeriesWriter.h"
#include "itkNumericSeriesFileNames.h"
#include "itkGDCMImageIO.h"
#include "itkImage.h"
#include "itkCastImageFilter.h"
#include "itkExtractImageFilter.h"
#include "itkImageIterator.h"
#include <itkImageRegionIterator.h>
#include "itkConnectedThresholdImageFilter.h"
#include "itkConfidenceConnectedImageFilter.h"
#include "itkCustomRegionGrowingImageFilter.h"
#include "itkCurvatureFlowImageFilter.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkUnaryFunctorImageFilter.h"
/**
* RegionGrowingBase class that instantiate
* the elements required for a Region Growing approach for segmentation
*/
class RegionGrowingBase
{
public:
/** image dimensions */
enum { ImageDimension = 3, ImageSeriesWriterDimension = 2 };
/** input image pixel type */
typedef signed short InputPixelType;
/** dicom pixel type */
typedef signed short DicomPixelType;
/** output image pixel type, gives range [0,255] */
typedef unsigned char OutputPixelType;
/** 2D pixel type for writing */
/** internal pixel type */
typedef float InternalPixelType;
/** input image type */
typedef itk::Image<InputPixelType,ImageDimension> InputImageType;
/** output image type */
typedef itk::Image<OutputPixelType,ImageDimension> OutputImageType;
/** internal image type */
typedef itk::Image<InternalPixelType,ImageDimension> InternalImageType;
/** 2D image type for series writing */
typedef itk::Image< DicomPixelType, ImageSeriesWriterDimension > Image2DType;
/** dicom image type */
typedef itk::Image< InputPixelType, ImageDimension> DicomImageType;
/** input image reader */
typedef itk::ImageFileReader< InputImageType > ImageReaderType;
/** write input image */
typedef itk::ImageFileWriter< OutputImageType > ImageWriterType;
/** DICOM reader */
typedef itk::ImageFileReader< InputImageType > DicomReaderType;
/** DICOM series writer */
typedef itk::ImageSeriesWriter< OutputImageType, Image2DType > SeriesWriterType;
typedef itk::GDCMImageIO ImageIOType;
typedef itk::NumericSeriesFileNames OutputNamesType;
/** DICOM to internal image type filter */
typedef itk::RescaleIntensityImageFilter<DicomImageType, InternalImageType> DicomToInternalImageTypeFilterType;
/** cast filter to convert from input to internal image */
typedef itk::CastImageFilter<InputImageType,InternalImageType> CastImageFilterType;
typedef itk::CastImageFilter<InputImageType,OutputImageType> CastImageFilterType2;
/** null filter, commented code would allow filtered images as input */
typedef itk::CastImageFilter<InternalImageType,InternalImageType> NullImageFilterType;
//typedef itk::CastImageFilter<InputImageType,InternalImageType> NullImageFilterType;
/** Gradient Anisotropic Image Filter */
typedef itk::GradientAnisotropicDiffusionImageFilter<InternalImageType,InternalImageType>
GradientAnisotropicDiffusionImageFilterType;
/** Curvature Anisotropic Image Filter */
typedef itk::CurvatureAnisotropicDiffusionImageFilter<InternalImageType,InternalImageType>
CurvatureAnisotropicDiffusionImageFilterType;
/** threshold image filter */
typedef itk::ConnectedThresholdImageFilter<InternalImageType,OutputImageType> ConnectedThresholdImageFilterType;
/** confidence connected image filter */
typedef itk::ConfidenceConnectedImageFilter<InternalImageType,OutputImageType> ConfidenceConnectedImageFilterType;
/** custom region growing fillter*/
typedef itk::CustomRegionGrowingImageFilter<InternalImageType,OutputImageType> CustomRegionGrowingImageFilterType;
/** volume iterator */
typedef itk::ImageRegionIterator< OutputImageType > ImageIterator;
public:
RegionGrowingBase();
virtual ~RegionGrowingBase();
virtual void LoadInputImage(void)=0;
virtual void LoadInputImage(const char * filename);
virtual void LoadInputImageSeries(void)=0;
virtual void LoadInputImageSeries(const char * dirname);
virtual void SaveConfConSeries(const char * outputDirectory);
virtual void SaveCustomSeries(const char * outputDirectory);
virtual void WriteOutputImage()=0;
virtual void WriteOutputImage(const char * filename);
virtual void WriteConnectedThresholdImage()=0;
virtual void WriteConfidenceConnectedImage()=0;
virtual void ShowStatus(const char * text)=0;
virtual void Stop(void);
virtual void SelectSmoothingFilter( unsigned int );
protected:
ImageReaderType::Pointer m_ImageReader;
ImageWriterType::Pointer m_ImageWriter;
DICOMFileReader::Pointer m_DicomReader;
/** dicom series writer */
SeriesWriterType::Pointer m_SeriesWriter;
OutputNamesType::Pointer m_OutputNames;
ImageIOType::Pointer m_ImageIO;
bool m_InputImageIsLoaded;
CastImageFilterType::Pointer m_CastImageFilter;
CastImageFilterType2::Pointer m_CastImageFilter2;
NullImageFilterType::Pointer m_NullImageFilter;
CurvatureAnisotropicDiffusionImageFilterType::Pointer m_CurvatureAnisotropicDiffusionImageFilter;
GradientAnisotropicDiffusionImageFilterType::Pointer m_GradientAnisotropicDiffusionImageFilter;
ConnectedThresholdImageFilterType::Pointer m_ConnectedThresholdImageFilter;
ConfidenceConnectedImageFilterType::Pointer m_ConfidenceConnectedImageFilter;
CustomRegionGrowingImageFilterType::Pointer m_CustomRegionGrowingImageFilter;
/** boolean that indicates DICOM image */
bool m_InputImageIsDICOM;
/** dicom conversion filters*/
DicomToInternalImageTypeFilterType::Pointer m_DicomToInternalImageTypeFilter;
};
#endif | [
"[email protected]@f99ad3ae-f7c5-c186-d9e4-f786dcd8cbb9"
] | [
[
[
1,
189
]
]
] |
55386ff6d2004f8070e0ee50979409651aaf68fc | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/crypto++/5.2.1/winpipes.cpp | 0745192bf0cf0f55636caa449294456fd41dc4ce | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-cryptopp"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,451 | cpp | // winpipes.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "winpipes.h"
#ifdef WINDOWS_PIPES_AVAILABLE
#include "wait.h"
NAMESPACE_BEGIN(CryptoPP)
WindowsHandle::WindowsHandle(HANDLE h, bool own)
: m_h(h), m_own(own)
{
}
WindowsHandle::~WindowsHandle()
{
if (m_own)
{
try
{
CloseHandle();
}
catch (...)
{
}
}
}
bool WindowsHandle::HandleValid() const
{
return m_h && m_h != INVALID_HANDLE_VALUE;
}
void WindowsHandle::AttachHandle(HANDLE h, bool own)
{
if (m_own)
CloseHandle();
m_h = h;
m_own = own;
HandleChanged();
}
HANDLE WindowsHandle::DetachHandle()
{
HANDLE h = m_h;
m_h = INVALID_HANDLE_VALUE;
HandleChanged();
return h;
}
void WindowsHandle::CloseHandle()
{
if (m_h != INVALID_HANDLE_VALUE)
{
::CloseHandle(m_h);
m_h = INVALID_HANDLE_VALUE;
HandleChanged();
}
}
// ********************************************************
void WindowsPipe::HandleError(const char *operation) const
{
DWORD err = GetLastError();
throw Err(GetHandle(), operation, err);
}
WindowsPipe::Err::Err(HANDLE s, const std::string& operation, int error)
: OS_Error(IO_ERROR, "WindowsPipe: " + operation + " operation failed with error 0x" + IntToString(error, 16), operation, error)
, m_h(s)
{
}
// *************************************************************
WindowsPipeReceiver::WindowsPipeReceiver()
: m_resultPending(false), m_eofReceived(false)
{
m_event.AttachHandle(CreateEvent(NULL, true, false, NULL), true);
CheckAndHandleError("CreateEvent", m_event.HandleValid());
memset(&m_overlapped, 0, sizeof(m_overlapped));
m_overlapped.hEvent = m_event;
}
bool WindowsPipeReceiver::Receive(byte* buf, unsigned int bufLen)
{
assert(!m_resultPending && !m_eofReceived);
HANDLE h = GetHandle();
// don't queue too much at once, or we might use up non-paged memory
if (ReadFile(h, buf, STDMIN(bufLen, 128U*1024U), &m_lastResult, &m_overlapped))
{
if (m_lastResult == 0)
m_eofReceived = true;
}
else
{
switch (GetLastError())
{
default:
CheckAndHandleError("ReadFile", false);
case ERROR_BROKEN_PIPE:
case ERROR_HANDLE_EOF:
m_lastResult = 0;
m_eofReceived = true;
break;
case ERROR_IO_PENDING:
m_resultPending = true;
}
}
return !m_resultPending;
}
void WindowsPipeReceiver::GetWaitObjects(WaitObjectContainer &container)
{
if (m_resultPending)
container.AddHandle(m_event);
else if (!m_eofReceived)
container.SetNoWait();
}
unsigned int WindowsPipeReceiver::GetReceiveResult()
{
if (m_resultPending)
{
HANDLE h = GetHandle();
if (GetOverlappedResult(h, &m_overlapped, &m_lastResult, false))
{
if (m_lastResult == 0)
m_eofReceived = true;
}
else
{
switch (GetLastError())
{
default:
CheckAndHandleError("GetOverlappedResult", false);
case ERROR_BROKEN_PIPE:
case ERROR_HANDLE_EOF:
m_lastResult = 0;
m_eofReceived = true;
}
}
m_resultPending = false;
}
return m_lastResult;
}
// *************************************************************
WindowsPipeSender::WindowsPipeSender()
: m_resultPending(false), m_lastResult(0)
{
m_event.AttachHandle(CreateEvent(NULL, true, false, NULL), true);
CheckAndHandleError("CreateEvent", m_event.HandleValid());
memset(&m_overlapped, 0, sizeof(m_overlapped));
m_overlapped.hEvent = m_event;
}
void WindowsPipeSender::Send(const byte* buf, unsigned int bufLen)
{
DWORD written = 0;
HANDLE h = GetHandle();
// don't queue too much at once, or we might use up non-paged memory
if (WriteFile(h, buf, STDMIN(bufLen, 128U*1024U), &written, &m_overlapped))
{
m_resultPending = false;
m_lastResult = written;
}
else
{
if (GetLastError() != ERROR_IO_PENDING)
CheckAndHandleError("WriteFile", false);
m_resultPending = true;
}
}
void WindowsPipeSender::GetWaitObjects(WaitObjectContainer &container)
{
if (m_resultPending)
container.AddHandle(m_event);
else
container.SetNoWait();
}
unsigned int WindowsPipeSender::GetSendResult()
{
if (m_resultPending)
{
HANDLE h = GetHandle();
BOOL result = GetOverlappedResult(h, &m_overlapped, &m_lastResult, false);
CheckAndHandleError("GetOverlappedResult", result);
m_resultPending = false;
}
return m_lastResult;
}
NAMESPACE_END
#endif
| [
"[email protected]"
] | [
[
[
1,
205
]
]
] |
5d4e53db7082247874e99a52eb9632a353cc0a3f | f13f46fbe8535a7573d0f399449c230a35cd2014 | /JelloMan/TerrainLoader.h | 5002f9d8d525eb843c43456ee7abe8a2db7cd18c | [] | no_license | fangsunjian/jello-man | 354f1c86edc2af55045d8d2bcb58d9cf9b26c68a | 148170a4834a77a9e1549ad3bb746cb03470df8f | refs/heads/master | 2020-12-24T16:42:11.511756 | 2011-06-14T10:16:51 | 2011-06-14T10:16:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 864 | h | #pragma once
//-----------------------------------------------------
// Include Files
//-----------------------------------------------------
#include "d3dUtil.h"
#include "AssetContainer.h"
#include "Model.h"
#include <vector>
class TerrainLoader
{
public:
//------Constructor-Destructor------->
TerrainLoader(void);
virtual ~TerrainLoader(void);
//<-----------------------------------
Model<VertexPosNormTanTex>* Load(ID3D10Device* pDXDevice, const tstring& key);
private:
TerrainLoader(TerrainLoader& t);
TerrainLoader& operator=(TerrainLoader& t);
AssetContainer<Model<VertexPosNormTanTex>>* m_pAssets;
};
void CalculateNormals(vector<VertexPosNormTanTex>& vecVPNTData, const vector<DWORD>& vecIndexData);
void CalculateTangents(vector<VertexPosNormTanTex>& vecVPNTData, const vector<DWORD>& vecIndexData); | [
"bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6"
] | [
[
[
1,
29
]
]
] |
e02101d6eaecc5b58ae946ba189e277b114bc7ce | 4d01363b089917facfef766868fb2b1a853605c7 | /src/Utils/Structures/Position3.h | e2f5155ffb98c39e902822e37e2a0ce7487591f9 | [] | no_license | FardMan69420/aimbot-57 | 2bc7075e2f24dc35b224fcfb5623083edcd0c52b | 3f2b86a1f86e5a6da0605461e7ad81be2a91c49c | refs/heads/master | 2022-03-20T07:18:53.690175 | 2009-07-21T22:45:12 | 2009-07-21T22:45:12 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,659 | h | #ifndef position3_h
#define position3_h
#include "Vector3.h"
class Position3
{
public:
float x, y, z;
Position3()
{
x = y = z = 0;
}
Position3(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
}
Position3(const Position3& other)
{
this->x = other.x;
this->y = other.y;
this->z = other.z;
}
void operator=(const Position3& other)
{
x = other.x;
y = other.y;
z = other.z;
}
Position3 operator*(const float value)
{
return Position3(x * value, y * value, z * value);
}
const Position3 operator+(const Position3& other)
{
return Position3(x + other.x, y + other.y, z + other.z);
}
const Position3 operator+(const Vector3& vect)
{
return Position3(x + vect.x, y + vect.y, z + vect.z);
}
/* for physical operations, like d = v·dt */
void operator+=(const Vector3& vect)
{
x += vect.x;
y += vect.y;
z += vect.z;
}
void operator+=(const Position3& pos)
{
x += pos.x;
y += pos.y;
z += pos.z;
}
void operator*=(float ratio)
{
x *= ratio;
y *= ratio;
z *= ratio;
}
float operator[](int index) const
{
switch(index) {
case 0: return x;
case 1: return y;
case 2: return z;
}
}
float dist(const Position3& point) const
{
return sqrtf(dist2(point));
}
float dist2(const Position3& point) const
{
return (x - point.x) * (x - point.x) +
(y - point.y) * (y - point.y) +
(z - point.z) * (z - point.z);
}
std::string print()
{
char buf[30];
sprintf(buf, "%3.3f %3.3f %3.3f", x, y, z);
return std::string(buf);
}
};
#endif
| [
"daven.hughes@92c3b6dc-493d-11de-82d9-516ade3e46db"
] | [
[
[
1,
102
]
]
] |
e74df649f25b5201b71040c7af99cb0d2d5a2b24 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osgUtil/SmoothingVisitor | e14759386e410147b3622c7fdccb96432a793edb | [] | no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,421 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#ifndef OSGUTIL_SMOOTHINGVISITOR
#define OSGUTIL_SMOOTHINGVISITOR 1
#include <osg/NodeVisitor>
#include <osg/Geode>
#include <osg/Geometry>
#include <osgUtil/Export>
namespace osgUtil {
/** A smoothing visitor for calculating smoothed normals for
* osg::GeoSet's which contains surface primitives.
*/
class OSGUTIL_EXPORT SmoothingVisitor : public osg::NodeVisitor
{
public:
/// default to traversing all children.
SmoothingVisitor();
virtual ~SmoothingVisitor();
/// smooth geoset by creating per vertex normals.
static void smooth(osg::Geometry& geoset);
/// apply smoothing method to all geode geosets.
virtual void apply(osg::Geode& geode);
};
}
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
] | [
[
[
1,
46
]
]
] |
|
59197c9851400d3b2a0f68c3d1ac8d45b005881b | d826e0dcc5b51f57101f2579d65ce8e010f084ec | /pre/FSKETCHCreate2DCircleCenterPoint.cpp | a2ac3fbbe349a48723479ea57a8f1c7565bd6e24 | [] | no_license | crazyhedgehog/macro-parametric | 308d9253b96978537a26ade55c9c235e0442d2c4 | 9c98d25e148f894b45f69094a4031b8ad938bcc9 | refs/heads/master | 2020-05-18T06:01:30.426388 | 2009-06-26T15:00:02 | 2009-06-26T15:00:02 | 38,305,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,429 | cpp | #include ".\FSKETCHCreate2DCircleCenterPoint.h"
#include <iostream>
#include "Part.h"
#include "FSketch.h"
int FSKETCHCreate2DCircleCenterPoint::_circle2DCPCnt = 0;
FSKETCHCreate2DCircleCenterPoint::FSKETCHCreate2DCircleCenterPoint(Part * part, tag_t fTag, FSketch * pFSketch)
: Feature (part, fTag)
{
_pFSketch = pFSketch;
}
FSKETCHCreate2DCircleCenterPoint::~FSKETCHCreate2DCircleCenterPoint(void)
{
}
void FSKETCHCreate2DCircleCenterPoint::GetUGInfo()
{
// To get curve arc coordinate infomation from a object feature Tag
UF_CURVE_arc_t ugArc;
UF_CALL(UF_CURVE_ask_arc_data( GetFTag(), &ugArc ) );
// To translate center point from world to local coord
double sketInfo[12];
GetFSketch()->GetSketInfo(sketInfo);
Cir_Map(sketInfo, ugArc.arc_center);
// set center point and dR
SetCntPnt(ugArc.arc_center);
SetRadius(ugArc.radius);
//---------- Set Result_Object_Name ----------//
char buffer[20];
_itoa( _circle2DCPCnt ++ , buffer, 10 );
SetName("circle2DCP" + (string)buffer);
}
void FSKETCHCreate2DCircleCenterPoint::ToTransCAD()
{
// Get SketchEditorPtr
TransCAD::ISketchEditorPtr spSketchEditor = GetFSketch()->GetSketchEditorPtr();
// Create sketch lines
spSketchEditor->Create2DCircleCenterPoint(GetName().c_str(), _cP[0], _cP[1], GetRadius());
//DEBUG
cout << " Center Point " << _cP[0] << " " << _cP[1] << " " << _cP[2] << endl;
} | [
"surplusz@2d8c97fe-2f4b-11de-8e0c-53a27eea117e"
] | [
[
[
1,
50
]
]
] |
46fe3981f2b2fb75f3b5dc9a3de47452d33dc43c | de75637338706776f8770c9cd169761cec128579 | /VHFOS/Simple Game Framework/GameMonkey/gmLog.cpp | 330dea9b7bf80103551f52f2f360c2baee65e4cb | [] | no_license | huytd/fosengine | e018957abb7b2ea2c4908167ec83cb459c3de716 | 1cebb1bec49720a8e9ecae1c3d0c92e8d16c27c5 | refs/heads/master | 2021-01-18T23:47:32.402023 | 2008-07-12T07:20:10 | 2008-07-12T07:20:10 | 38,933,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,263 | cpp | /*
_____ __ ___ __ ____ _ __
/ ___/__ ___ _ ___ / |/ /__ ___ / /_____ __ __/ __/_______(_)__ / /_
/ (_ / _ `/ ' \/ -_) /|_/ / _ \/ _ \/ '_/ -_) // /\ \/ __/ __/ / _ \/ __/
\___/\_,_/_/_/_/\__/_/ /_/\___/_//_/_/\_\\__/\_, /___/\__/_/ /_/ .__/\__/
/___/ /_/
See Copyright Notice in gmMachine.h
*/
#include "gmConfig.h"
#include "gmLog.h"
#include "gmMem.h"
gmLog::gmLog() :
m_mem(1, GMLOG_CHAINSIZE)
{
m_first = NULL;
m_last = NULL;
m_curr = NULL;
m_memApproxLimit = -1;
}
gmLog::~gmLog()
{
}
void gmLog::Reset()
{
m_first = NULL;
m_last = NULL;
m_curr = NULL;
m_mem.Reset();
}
void gmLog::ResetAndFreeMemory()
{
m_first = NULL;
m_last = NULL;
m_curr = NULL;
m_mem.ResetAndFreeMemory();
}
void GM_CDECL gmLog::LogEntry(const char * a_format, ...)
{
va_list ap;
char buffer[GMLOG_CHAINSIZE];
va_start(ap, a_format);
_gmvsnprintf(buffer, GMLOG_CHAINSIZE, a_format, ap);
va_end(ap);
strcat(buffer, GM_NL);
GM_PRINTF(buffer);//sorry but I prefer writing directly
/*if( (m_memApproxLimit > 0) && (m_mem.GetSystemMemUsed() > (unsigned int)m_memApproxLimit) )
{
m_mem.Reset();
}*/
// add to entry list
/*Entry * entry = (Entry *) m_mem.AllocBytes(sizeof(Entry) + sizeof(int), GM_DEFAULT_ALLOC_ALIGNMENT);
if(entry != NULL)
{
char * text = (char *) m_mem.AllocBytes(strlen(buffer) + 1, GM_DEFAULT_ALLOC_ALIGNMENT);
if(text)
{
strcpy(text, buffer);
entry->m_text = text;
entry->m_next = NULL;
if(m_last)
{
m_last->m_next = entry;
m_last = entry;
}
else
{
m_first = m_last = entry;
}
}
}*/
}
const char * gmLog::GetEntry(bool &a_first)
{
if(a_first == true)
{
a_first = false;
m_curr = m_first;
}
if(m_curr)
{
const char * text = m_curr->m_text;
m_curr = m_curr->m_next;
return text;
}
return NULL;
}
void gmLog::SetMemLimit(int a_limit)
{
m_memApproxLimit = a_limit;
}
| [
"doqkhanh@52f955dd-904d-0410-b1ed-9fe3d3cbfe06"
] | [
[
[
1,
118
]
]
] |
94fb39d643a358f7b8092ac85f3b1e7bbbc9031d | 1d693dd1b12b23c72dd0bb12a3fc29ed88a7e2d5 | /src/nbpflcompiler/strutils.h | e42b984c9cc82cb4cba8960a4824734c3b651928 | [] | no_license | rrdenicol/Netbee | 8765ebc2db4ba9bd27c2263483741b409da8300a | 38edb4ffa78b8fb7a4167a5d04f40f8f4466be3e | refs/heads/master | 2021-01-16T18:42:17.961177 | 2011-12-26T20:27:03 | 2011-12-26T20:27:03 | 3,053,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,308 | h | /*****************************************************************************/
/* */
/* Copyright notice: please read file license.txt in the NetBee root folder. */
/* */
/*****************************************************************************/
#pragma once
#include <string>
#include <algorithm>
using namespace std;
#define SPACES " \r\n"
#define CRLF "\r\n"
inline string trim_right(const string &s, const string & t = SPACES)
{
string d (s);
string::size_type i(d.find_last_not_of (t));
if (i == string::npos)
return "";
else
return d.erase (d.find_last_not_of (t) + 1) ;
}
inline string remove_chars(const string &s, const string & t = CRLF, const string & w = " ")
{
string d (s);
string::size_type i;
while ((i = d.find_first_of(t)) != string::npos)
d.replace(i, 1, w) ;
return d;
}
inline string ToUpper(const string &s)
{
string d(s);
transform (d.begin (), d.end (), d.begin (), (int(*)(int)) toupper);
return d;
}
inline string ToLower(const string &s)
{
string d(s);
transform (d.begin (), d.end (), d.begin (), (int(*)(int)) tolower);
return d;
}
| [
"[email protected]"
] | [
[
[
1,
57
]
]
] |
9d7079e3153c40341ea686ee04f2b8b56e77745a | de24ee2f04bf6d69bc093db4b3091da8c9e44a90 | /TutorialApplication.cpp | 0d6e5d1c6556bd11f69c8052d09c2e0bc68ff9f0 | [] | no_license | martinvium/sidescroller | 713361432d5d3e3235766bf9a14b1394dc83085a | 00e9a51fc9f6d8a5b765a469c4560ea9f33cb9b6 | refs/heads/master | 2020-12-24T15:49:37.627554 | 2011-04-25T17:00:00 | 2011-04-25T17:00:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,620 | cpp | /*
-----------------------------------------------------------------------------
Filename: TutorialApplication.cpp
-----------------------------------------------------------------------------
This source file is part of the
___ __ __ _ _ _
/___\__ _ _ __ ___ / / /\ \ (_) | _(_)
// // _` | '__/ _ \ \ \/ \/ / | |/ / |
/ \_// (_| | | | __/ \ /\ /| | <| |
\___/ \__, |_| \___| \/ \/ |_|_|\_\_|
|___/
Tutorial Framework
http://www.ogre3d.org/tikiwiki/
-----------------------------------------------------------------------------
*/
#include "TutorialApplication.h"
#include <OgreManualObject.h>
#include <OgreRenderOperation.h>
#include <OgreResourceGroupManager.h>
#include <OgreString.h>
//-------------------------------------------------------------------------------------
TutorialApplication::TutorialApplication(void)
{
mCameraLocked = true;
}
//-------------------------------------------------------------------------------------
TutorialApplication::~TutorialApplication(void)
{
}
//-------------------------------------------------------------------------------------
void TutorialApplication::createScene(void)
{
// Set the default lighting.
mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5f, 0.5f, 0.5f));
mSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);
createTerrain();
createPlayer();
// Set the camera to look at our handiwork
mCamera->setPosition(90.0f, CAMERA_Y, CAMERA_Z);
mCamera->pitch(Ogre::Degree(-30.0f));
mCamera->yaw(Ogre::Degree(-15.0f));
// Set idle animation
mAnimationState = mPlayerEntity->getAnimationState("Idle");
mAnimationState->setLoop(true);
mAnimationState->setEnabled(true);
}
//-------------------------------------------------------------------------------------
void TutorialApplication::createTerrain(void)
{
createBackground();
createLava();
createBox("Cube1", Ogre::Vector3(100.0f, 0.0f, 25.0f));
createBox("Cube2", Ogre::Vector3(300.0f, -100.0f, 25.0f));
createBox("Cube3", Ogre::Vector3(500.0f, 50.0f, 25.0f));
}
//-------------------------------------------------------------------------------------
void TutorialApplication::createBackground(void)
{
// wall
Ogre::Plane wallPlane(Ogre::Vector3::UNIT_Z, 0);
Ogre::MeshManager::getSingleton().createPlane("wall", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
wallPlane, 1500, 1500, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Y);
Ogre::Entity* entWall = mSceneMgr->createEntity("WallEntity", "wall");
Ogre::SceneNode *nodeWall = mSceneMgr->getRootSceneNode()->createChildSceneNode();
nodeWall->attachObject(entWall);
nodeWall->setPosition(Ogre::Vector3(0.0f, 0.0f, -25.0f));
entWall->setMaterialName("Environment/Rockwall");
entWall->setCastShadows(false);
}
//-------------------------------------------------------------------------------------
void TutorialApplication::createLava(void)
{
Ogre::Plane lavaPlane(Ogre::Vector3::UNIT_Y, 0);
Ogre::MeshManager::getSingleton().createPlane("lava", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
lavaPlane, 1500, 1500, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z);
Ogre::Entity* entLava = mSceneMgr->createEntity("LavaEntity", "lava");
Ogre::SceneNode *nodeLava = mSceneMgr->getRootSceneNode()->createChildSceneNode();
nodeLava->attachObject(entLava);
nodeLava->setPosition(Ogre::Vector3(0.0f, -150.0f, 0.0f));
entLava->setMaterialName("Environment/Lava");
entLava->setCastShadows(false);
createLavaLight();
}
//-------------------------------------------------------------------------------------
void TutorialApplication::createLavaLight(void)
{
Ogre::Light* pointLight = mSceneMgr->createLight("pointLight1");
pointLight->setType(Ogre::Light::LT_POINT);
pointLight->setPosition(Ogre::Vector3(-50, -100, 50));
pointLight->setDiffuseColour(Ogre::ColourValue(1, 0, 0));
pointLight->setSpecularColour(Ogre::ColourValue(.25, 0, 0));
Ogre::Light* pointLight2 = mSceneMgr->createLight("pointLight2");
pointLight2->setType(Ogre::Light::LT_POINT);
pointLight2->setPosition(Ogre::Vector3(200, -100, 50));
pointLight2->setDiffuseColour(Ogre::ColourValue(1, 0, 0));
pointLight2->setSpecularColour(Ogre::ColourValue(.25, 0, 0));
Ogre::Light* pointLight3 = mSceneMgr->createLight("pointLight3");
pointLight3->setType(Ogre::Light::LT_POINT);
pointLight3->setPosition(Ogre::Vector3(400, -100, 50));
pointLight3->setDiffuseColour(Ogre::ColourValue(1, 0, 0));
pointLight3->setSpecularColour(Ogre::ColourValue(.25, 0, 0));
}
//-------------------------------------------------------------------------------------
void TutorialApplication::createPlayer(void)
{
// Create the entity
mPlayerEntity = mSceneMgr->createEntity("PlayerEntity", "player.mesh");
mPlayerEntity->setCastShadows(false);
// Create the scene node
mPlayerNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("PlayerNode", Ogre::Vector3(0.0f, 10.0f, 35.0f));
mPlayerNode->attachObject(mPlayerEntity);
mCameraMan->setTarget(mPlayerNode);
}
//-------------------------------------------------------------------------------------
void TutorialApplication::createBox(const Ogre::String &name, const Ogre::Vector3 &pos)
{
// Create the entity
Ogre::Entity *entityCube = mSceneMgr->createEntity("Entity" + name, "box.mesh");
entityCube->setMaterialName("Environment/Rockwall");
entityCube->setCastShadows(true);
// Create the scene node
Ogre::SceneNode *nodeCube = mSceneMgr->getRootSceneNode()->createChildSceneNode("Node" + name, pos);
nodeCube->attachObject(entityCube);
nodeCube->setScale(2.0f, 0.2f, 1.0f);
}
//-------------------------------------------------------------------------------------
void TutorialApplication::createFrameListener(void)
{
BaseApplication::createFrameListener();
// Set default values for variables
mWalkSpeed = 25.0f;
mDirection = Ogre::Vector3::ZERO;
}
//-------------------------------------------------------------------------------------
bool TutorialApplication::nextLocation(void)
{
if (mWalkList.empty())
return false;
mDestination = mWalkList.front(); // this gets the front of the deque
mWalkList.pop_front(); // this removes the front of the deque
mDirection = mDestination - mPlayerNode->getPosition();
mDistance = mDirection.normalise();
return true;
}
//-------------------------------------------------------------------------------------
bool TutorialApplication::frameRenderingQueued(const Ogre::FrameEvent &evt)
{
movePlayer(evt);
return BaseApplication::frameRenderingQueued(evt);
}
//-------------------------------------------------------------------------------------
void TutorialApplication::movePlayer(const Ogre::FrameEvent &evt)
{
if (mDirection == Ogre::Vector3::ZERO) {
if (nextLocation()) {
// Set walking animation
mAnimationState = mPlayerEntity->getAnimationState("Walk");
mAnimationState->setLoop(true);
mAnimationState->setEnabled(true);
}
} else {
Ogre::Real move = mWalkSpeed * evt.timeSinceLastFrame;
mDistance -= move;
if (mDistance <= 0.0f) {
mPlayerNode->setPosition(mDestination);
mDirection = Ogre::Vector3::ZERO;
// Set animation based on if the robot has another point to walk to.
if (! nextLocation()) {
// Set Idle animation
mAnimationState = mPlayerEntity->getAnimationState("Idle");
mAnimationState->setLoop(true);
mAnimationState->setEnabled(true);
} else {
Ogre::Vector3 src = mPlayerNode->getOrientation() * Ogre::Vector3::UNIT_X;
if ((1.0f + src.dotProduct(mDirection)) < 0.0001f) {
mPlayerNode->yaw(Ogre::Degree(180));
} else {
Ogre::Quaternion quat = src.getRotationTo(mDirection);
mPlayerNode->rotate(quat);
}
}
} else {
mPlayerNode->translate(mDirection * move);
//Ogre::Vector3 pos = mNode->getPosition();
//mCamera->setPosition(pos.x, CAMERA_Y, CAMERA_Z);
}
}
mAnimationState->addTime(evt.timeSinceLastFrame);
}
void TutorialApplication::movePlayerLeft(void)
{
Ogre::Vector3 vector;
vector = mPlayerNode->getPosition();
Ogre::Quaternion q(Ogre::Degree(180), vector.NEGATIVE_UNIT_Y);
mPlayerNode->setOrientation(q);
vector.x = vector.x -10;
mWalkList.insert(mWalkList.begin(), vector);
}
void TutorialApplication::jumpPlayer(void)
{
mDirection = Ogre::Vector3::ZERO;
Ogre::Vector3 vector;
vector = mWalkList.front();
vector.y = vector.y +100 ;
mWalkList.insert(mWalkList.begin(), vector);
}
bool TutorialApplication::keyPressed(const OIS::KeyEvent &arg)
{
bool ret = BaseApplication::keyPressed(arg);
switch(arg.key)
{
case OIS::KC_SPACE:
jumpPlayer();
break;
case OIS::KC_A:
movePlayerLeft();
break;
}
return ret;
}
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char * argv[])
#endif
{
// Create application object
TutorialApplication app;
try {
app.go();
} catch( Ogre::Exception& e ) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occured: " <<
e.getFullDescription().c_str() << std::endl;
#endif
}
return 0;
}
#ifdef __cplusplus
}
#endif
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
43
],
[
45,
225
],
[
250,
251
],
[
253,
254
],
[
265,
268
],
[
270,
281
],
[
283,
304
]
],
[
[
44,
44
],
[
226,
249
],
[
252,
252
],
[
255,
264
],
[
269,
269
],
[
282,
282
]
]
] |
0886af496aba798ef98866080bb1d088f5b5d39a | fd196fe7f1a57a3d589dd987127391b6428dbc9f | /Projects/Platform2DGameTest/Engine/Win32/GWTimer.cpp | 6d801804d9788a235a1d345c9e208d358807a849 | [] | no_license | aosyang/Graphic-Workbench | 73651b597b7ad9f759618bad30313bfad12a35b5 | 48c3b4b034ea332fb926ac0a0bd1f7c1fc1a2bb1 | refs/heads/master | 2021-01-22T23:25:48.330855 | 2011-11-29T09:27:52 | 2011-11-29T09:27:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 333 | cpp | /********************************************************************
created: 2011/10/31
filename: GWTimer.cpp
author: Mwolf
purpose:
*********************************************************************/
#include "GWTimer.h"
#include <windows.h>
GW_UINT32 GWSys_GetTickCount()
{
return GetTickCount();
}
| [
"[email protected]@b4c0308a-e464-ec88-fcea-6ff8c68c914a"
] | [
[
[
1,
15
]
]
] |
7fa453dc98b311259f0f594aebaab1487c18de71 | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct2D/D2DException.h | b48da8933bdb114542252d3aef50e58af94ec39a | [] | no_license | midnite8177/phever | f9a55a545322c9aff0c7d0c45be3d3ddd6088c97 | 45529e80ebf707e7299887165821ca360aa1907d | refs/heads/master | 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,077 | h | // Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
#include "DirectXException.h"
using namespace System;
using namespace Microsoft::WindowsAPICodePack::DirectX;
namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct2D1 {
/// <summary>
/// Base class for all Direct2D exceptions
/// </summary>
public ref class Direct2DException : public DirectXException
{
public:
Direct2DException(void) : DirectXException() {}
Direct2DException(String^ message, int hr) : DirectXException(message, hr)
{
}
Direct2DException(int hr) : DirectXException("Direct2D Error was returned. Check ErrorCode.", hr)
{
HResult = hr;
}
Direct2DException(String^ message, Exception^ innerException, int hr) :
DirectXException(message, innerException, hr)
{
}
Direct2DException(String^ message, Exception^ innerException) :
DirectXException(message, innerException, 0)
{
}
};
} } } }
| [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
] | [
[
[
1,
42
]
]
] |
9509154429a3a39ec5db508e667353c67b818266 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/xpressive/traits/null_regex_traits.hpp | 34f30727821b7db0f7fdfdaa5fb43bb0c793ba25 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,163 | hpp | ///////////////////////////////////////////////////////////////////////////////
/// \file null_regex_traits.hpp
/// Contains the definition of the null_regex_traits\<\> template, which is a
/// stub regex traits implementation that can be used by static and dynamic
/// regexes for searching non-character data.
//
// Copyright 2004 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_XPRESSIVE_TRAITS_NULL_REGEX_TRAITS_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_TRAITS_NULL_REGEX_TRAITS_HPP_EAN_10_04_2005
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <vector>
#include <boost/assert.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/xpressive/detail/detail_fwd.hpp>
#include <boost/xpressive/detail/utility/never_true.hpp>
#include <boost/xpressive/detail/utility/ignore_unused.hpp>
namespace boost { namespace xpressive
{
namespace detail
{
struct not_a_locale {};
}
struct regex_traits_version_1_tag;
///////////////////////////////////////////////////////////////////////////////
// null_regex_traits
//
/// \brief stub regex_traits for non-char data
///
template<typename Elem>
struct null_regex_traits
{
typedef Elem char_type;
typedef std::vector<char_type> string_type;
typedef detail::not_a_locale locale_type;
typedef int char_class_type;
typedef regex_traits_version_1_tag version_tag;
/// Initialize a null_regex_traits object.
///
null_regex_traits(locale_type = locale_type())
{
}
/// Checks two null_regex_traits objects for equality
///
/// \return true.
bool operator ==(null_regex_traits<char_type> const &that) const
{
detail::ignore_unused(&that);
return true;
}
/// Checks two null_regex_traits objects for inequality
///
/// \return false.
bool operator !=(null_regex_traits<char_type> const &that) const
{
detail::ignore_unused(&that);
return false;
}
/// Convert a char to a Elem
///
/// \param ch The source character.
/// \return Elem(ch).
char_type widen(char ch) const
{
//BOOST_MPL_ASSERT((detail::never_true<char_type>));
BOOST_ASSERT(false);
return char_type(ch);
}
/// Returns a hash value for a Elem in the range [0, UCHAR_MAX]
///
/// \param ch The source character.
/// \return a value between 0 and UCHAR_MAX, inclusive.
static unsigned char hash(char_type ch)
{
return static_cast<unsigned char>(ch);
}
/// No-op
///
/// \param ch The source character.
/// \return ch
static char_type translate(char_type ch)
{
return ch;
}
/// No-op
///
/// \param ch The source character.
/// \return ch
static char_type translate_nocase(char_type ch)
{
return ch;
}
/// Checks to see if a character is within a character range.
///
/// \param first The bottom of the range, inclusive.
/// \param last The top of the range, inclusive.
/// \param ch The source character.
/// \return first <= ch && ch <= last.
static bool in_range(char_type first, char_type last, char_type ch)
{
return first <= ch && ch <= last;
}
/// Checks to see if a character is within a character range.
///
/// \param first The bottom of the range, inclusive.
/// \param last The top of the range, inclusive.
/// \param ch The source character.
/// \return first <= ch && ch <= last.
/// \attention Since the null_regex_traits does not do case-folding,
/// this function is equivalent to in_range().
static bool in_range_nocase(char_type first, char_type last, char_type ch)
{
return first <= ch && ch <= last;
}
/// Returns a sort key for the character sequence designated by the iterator range [F1, F2)
/// such that if the character sequence [G1, G2) sorts before the character sequence [H1, H2)
/// then v.transform(G1, G2) < v.transform(H1, H2).
///
/// \attention Not used in xpressive 1.0
template<typename FwdIter>
static string_type transform(FwdIter begin, FwdIter end)
{
return string_type(begin, end);
}
/// Returns a sort key for the character sequence designated by the iterator range [F1, F2)
/// such that if the character sequence [G1, G2) sorts before the character sequence [H1, H2)
/// when character case is not considered then
/// v.transform_primary(G1, G2) < v.transform_primary(H1, H2).
///
/// \attention Not used in xpressive 1.0
template<typename FwdIter>
static string_type transform_primary(FwdIter begin, FwdIter end)
{
return string_type(begin, end);
}
/// Returns a sequence of characters that represents the collating element
/// consisting of the character sequence designated by the iterator range [F1, F2).
/// Returns an empty string if the character sequence is not a valid collating element.
///
/// \attention Not used in xpressive 1.0
template<typename FwdIter>
static string_type lookup_collatename(FwdIter begin, FwdIter end)
{
detail::ignore_unused(&begin);
detail::ignore_unused(&end);
return string_type();
}
/// The null_regex_traits does not have character classifications, so lookup_classname()
/// is unused.
///
/// \param begin not used
/// \param end not used
/// \param icase not used
/// \return static_cast\<char_class_type\>(0)
template<typename FwdIter>
static char_class_type lookup_classname(FwdIter begin, FwdIter end, bool icase)
{
detail::ignore_unused(&begin);
detail::ignore_unused(&end);
detail::ignore_unused(&icase);
return 0;
}
/// The null_regex_traits does not have character classifications, so isctype()
/// is unused.
///
/// \param ch not used
/// \param mask not used
/// \return false
static bool isctype(char_type ch, char_class_type mask)
{
detail::ignore_unused(&ch);
detail::ignore_unused(&mask);
return false;
}
/// The null_regex_traits recognizes no elements as digits, so value() is unused.
///
/// \param ch not used
/// \param radix not used
/// \return -1
static int value(char_type ch, int radix)
{
detail::ignore_unused(&ch);
detail::ignore_unused(&radix);
return -1;
}
/// Not used
///
/// \param loc not used
/// \return loc
static locale_type imbue(locale_type loc)
{
return loc;
}
/// Returns locale_type().
///
/// \return locale_type()
static locale_type getloc()
{
return locale_type();
}
};
}}
#endif
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
233
]
]
] |
12407285eaee4b4445e554f340ecedeb8af37179 | 5851a831bcc95145bf501b40e90e224d08fa4ac9 | /src/plugins/imex-plugin/ui_imexport.cpp | f990dec00dad7a2c149deed259cbacbe90dba63b | [] | no_license | jemyzhang/Cashup | a80091921a2e74f24db045dd731f7bf43c09011a | f4e768a7454bfa437ad9842172de817fa8da71e2 | refs/heads/master | 2021-01-13T01:35:51.871352 | 2010-03-06T14:26:55 | 2010-03-06T14:26:55 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 11,752 | cpp | #include "ui_imexport.h"
#include <cMzCommon.h>
using namespace cMzCommon;
#include "ui_calendar.h"
MZ_IMPLEMENT_DYNAMIC(Ui_ImExportWnd)
MZ_IMPLEMENT_DYNAMIC(Ui_ExDateRangeWnd)
#define MZ_IDC_TOOLBAR_CONFIG 101
#define MZ_IDC_BUTTON_IMPORT 102
#define MZ_IDC_BUTTON_EXPORT 103
#define IDC_PPM_QIF 106
#define IDC_PPM_COMMA 107
#define IDC_PPM_TAB 108
#define IDC_PPM_CANCEL 109
BOOL Ui_ExDateRangeWnd::OnInitDialog(){
// Must all the Init of parent class first!
if (!CMzWndEx::OnInitDialog()) {
return FALSE;
}
// Then init the controls & other things in the window
m_bg.SetPos(0,0,GetWidth(),GetHeight());
AddUiWin(&m_bg);
int y = 20;
m_s1.SetPos(10,y + 10,50,50);
m_s1.SetID(MZ_IDC_BTN_S1);
m_s1.EnableNotifyMessage(true);
m_bg.AddChild(&m_s1);
m_LblAll.SetPos(60,y,GetWidth() - 50,MZM_HEIGHT_BUTTONEX);
m_LblAll.SetText(LOADSTRING(IDS_STR_EXPORT_CHOOSE_ALL).C_Str());
m_LblAll.SetDrawTextFormat(DT_LEFT | DT_VCENTER);
m_LblAll.SetTextColor(RGB(255,255,255));
m_LblAll.SetID(MZ_IDC_BTN_ALL);
m_LblAll.EnableNotifyMessage(true);
m_bg.AddChild(&m_LblAll);
y += MZM_HEIGHT_BUTTONEX;
m_s2.SetPos(10,y + 10,50,50);
m_s2.SetID(MZ_IDC_BTN_S2);
m_s2.EnableNotifyMessage(true);
m_bg.AddChild(&m_s2);
m_EdtFromDate.SetPos(60,y,(GetWidth()-10-60-40)/2,MZM_HEIGHT_BUTTONEX);
m_EdtFromDate.SetButtonType(MZC_BUTTON_NONE);
m_EdtFromDate.SetID(MZ_IDC_BTN_EFROM);
m_bg.AddChild(&m_EdtFromDate);
m_LblTo.SetPos(60+m_EdtFromDate.GetWidth(),y,40,MZM_HEIGHT_BUTTONEX);
m_LblTo.SetText(L"~");
m_LblTo.SetTextColor(RGB(255,255,255));
m_bg.AddChild(&m_LblTo);
m_EdtToDate.SetPos(GetWidth() - m_EdtFromDate.GetWidth() - 10,y,m_EdtFromDate.GetWidth(),MZM_HEIGHT_BUTTONEX);
m_EdtToDate.SetButtonType(MZC_BUTTON_NONE);
m_EdtToDate.SetID(MZ_IDC_BTN_ETO);
m_bg.AddChild(&m_EdtToDate);
y += MZM_HEIGHT_BUTTONEX;
m_BtnOK.SetPos(0,y,GetWidth()/2,MZM_HEIGHT_BUTTONEX + 20);
m_BtnOK.SetText(LOADSTRING(IDS_STR_OK).C_Str());
m_BtnOK.SetID(MZ_IDC_BTN_OK);
m_bg.AddChild(&m_BtnOK);
m_BtnCancel.SetPos(GetWidth()/2,y,GetWidth()/2,MZM_HEIGHT_BUTTONEX + 20);
m_BtnCancel.SetText(LOADSTRING(IDS_STR_CANCEL).C_Str());
m_BtnCancel.SetID(MZ_IDC_BTN_CANCEL);
m_bg.AddChild(&m_BtnCancel);
updateUi();
return TRUE;
}
void Ui_ExDateRangeWnd::OnMzCommand(WPARAM wParam, LPARAM lParam){
UINT_PTR id = LOWORD(wParam);
switch (id) {
case MZ_IDC_BTN_EFROM:
{
Ui_CalendarWnd calendardlg;
RECT rcWork = MzGetWorkArea();
calendardlg.initDate(_sdate.Date.Year,_sdate.Date.Month,_sdate.Date.Day);
calendardlg.Create(rcWork.left, rcWork.top, RECT_WIDTH(rcWork), RECT_HEIGHT(rcWork),
m_hWnd, 0, WS_POPUP);
// set the animation of the window
calendardlg.SetAnimateType_Show(MZ_ANIMTYPE_SCROLL_RIGHT_TO_LEFT_2);
calendardlg.SetAnimateType_Hide(MZ_ANIMTYPE_SCROLL_LEFT_TO_RIGHT_1);
int nRet = calendardlg.DoModal();
if (nRet == ID_OK) {
DWORD year,month,day;
swscanf(calendardlg.getDate().C_Str(),L"%04d-%02d-%02d",
&year,&month,&day);
_sdate.Date.Year = year;
_sdate.Date.Month = month;
_sdate.Date.Day = day;
_selIndex = false;
updateUi();
}
break;
}
case MZ_IDC_BTN_ETO:
{
Ui_CalendarWnd calendardlg;
RECT rcWork = MzGetWorkArea();
calendardlg.initDate(_edate.Date.Year,_edate.Date.Month,_edate.Date.Day);
calendardlg.Create(rcWork.left, rcWork.top, RECT_WIDTH(rcWork), RECT_HEIGHT(rcWork),
m_hWnd, 0, WS_POPUP);
// set the animation of the window
calendardlg.SetAnimateType_Show(MZ_ANIMTYPE_SCROLL_RIGHT_TO_LEFT_2);
calendardlg.SetAnimateType_Hide(MZ_ANIMTYPE_SCROLL_LEFT_TO_RIGHT_1);
int nRet = calendardlg.DoModal();
if (nRet == ID_OK) {
DWORD year,month,day;
swscanf(calendardlg.getDate().C_Str(),L"%04d-%02d-%02d",
&year,&month,&day);
_edate.Date.Year = year;
_edate.Date.Month = month;
_edate.Date.Day = day;
_selIndex = false;
updateUi();
}
break;
}
case MZ_IDC_BTN_OK:
if(!_selIndex){
if(_edate.Value == 0 && _sdate.Value == 0){
return;
}
if(_sdate.Value > _edate.Value){
if(_sdate.Value != 0){
_edate.Value = _sdate.Value;
}else{
_sdate.Value = _edate.Value;
}
}
}
EndModal(ID_OK);
break;
case MZ_IDC_BTN_CANCEL:
EndModal(ID_CANCEL);
break;
}
return;
}
Ui_ImExportWnd::Ui_ImExportWnd(void)
{
_isImport = false;
//读取导出日期设定
_bExportAll = appconfig.IniExportAll.Get();
_StartExportDate.Value = appconfig.IniExportStartDate.Get();
_EndExportDate.Value = appconfig.IniExportEndDate.Get();
}
Ui_ImExportWnd::~Ui_ImExportWnd(void)
{
}
BOOL Ui_ImExportWnd::OnInitDialog() {
// Must all the Init of parent class first!
if (!CMzWndEx::OnInitDialog()) {
return FALSE;
}
// Then init the controls & other things in the window
int y = 0;
m_CaptionTitle.SetPos(0, y, GetWidth(), MZM_HEIGHT_CAPTION);
if(_isImport){
m_CaptionTitle.SetText(LOADSTRING(IDS_STR_IMPORT).C_Str());
}else{
m_CaptionTitle.SetText(LOADSTRING(IDS_STR_EXPORT).C_Str());
}
AddUiWin(&m_CaptionTitle);
y += MZM_HEIGHT_CAPTION;
m_BtnImExAccounts.SetPos(0, y, GetWidth(), MZM_HEIGHT_BUTTONEX);
m_BtnImExAccounts.SetText(LOADSTRING(IDS_STR_ACCOUNT).C_Str());
m_BtnImExAccounts.SetButtonType(MZC_BUTTON_LINE_BOTTOM);
m_BtnImExAccounts.SetID(MZ_IDC_BUTTON_IMEX_ACCOUNT);
//set the right image of the extended button m_BtnSetting1
m_BtnImExAccounts.SetImage2(imgArrow);
m_BtnImExAccounts.SetImageWidth2(imgArrow->GetImageWidth());
m_BtnImExAccounts.SetShowImage2(true);
AddUiWin(&m_BtnImExAccounts);
y += MZM_HEIGHT_BUTTONEX;
m_BtnImExCategories.SetPos(0, y, GetWidth(), MZM_HEIGHT_BUTTONEX);
m_BtnImExCategories.SetText(LOADSTRING(IDS_STR_CATEGORY).C_Str());
m_BtnImExCategories.SetButtonType(MZC_BUTTON_LINE_BOTTOM);
m_BtnImExCategories.SetID(MZ_IDC_BUTTON_IMEX_CATEGORY);
m_BtnImExCategories.SetImage2(imgArrow);
m_BtnImExCategories.SetImageWidth2(imgArrow->GetImageWidth());
m_BtnImExCategories.SetShowImage2(true);
AddUiWin(&m_BtnImExCategories);
y += MZM_HEIGHT_BUTTONEX;
m_BtnImExRecords.SetPos(0, y, GetWidth(), MZM_HEIGHT_BUTTONEX);
m_BtnImExRecords.SetText(LOADSTRING(IDS_STR_RECORDS).C_Str());
m_BtnImExRecords.SetButtonType(MZC_BUTTON_LINE_BOTTOM);
m_BtnImExRecords.SetID(MZ_IDC_BUTTON_IMEX_RECORD);
m_BtnImExRecords.SetImage2(imgArrow);
m_BtnImExRecords.SetImageWidth2(imgArrow->GetImageWidth());
m_BtnImExRecords.SetShowImage2(true);
AddUiWin(&m_BtnImExRecords);
if(!_isImport){
y += MZM_HEIGHT_BUTTONEX;
m_BtnExRange.SetPos(0, y, GetWidth(), MZM_HEIGHT_BUTTONEX);
m_BtnExRange.SetText(LOADSTRING(IDS_STR_DATE_RANGE).C_Str());
m_BtnExRange.SetButtonType(MZC_BUTTON_LINE_BOTTOM);
m_BtnExRange.SetID(MZ_IDC_BUTTON_EX_RANGE);
m_BtnExRange.SetImage2(imgArrow);
m_BtnExRange.SetImageWidth2(imgArrow->GetImageWidth());
m_BtnExRange.SetShowImage2(true);
AddUiWin(&m_BtnExRange);
}
m_Toolbar.SetPos(0, GetHeight() - MZM_HEIGHT_TEXT_TOOLBAR, GetWidth(), MZM_HEIGHT_TEXT_TOOLBAR);
m_Toolbar.SetButton(0, true, true,LOADSTRING(IDS_STR_RETURN).C_Str());
m_Toolbar.EnableLeftArrow(true);
m_Toolbar.SetID(MZ_IDC_TOOLBAR_CONFIG);
AddUiWin(&m_Toolbar);
updateButtonRange();
return TRUE;
}
void Ui_ImExportWnd::updateButtonRange(){
if(_bExportAll){
m_BtnExRange.SetText2(LOADSTRING(IDS_STR_ALLDATE).C_Str());
}else{
if(_StartExportDate.Value == 0 || _EndExportDate.Value == 0){
_bExportAll = true;
m_BtnExRange.SetText2(LOADSTRING(IDS_STR_ALLDATE).C_Str());
}else{
wchar_t strDate[32];
if(_StartExportDate.Value == _EndExportDate.Value){
wsprintf(strDate,L"%d.%d.%d",
_StartExportDate.Date.Year,_StartExportDate.Date.Month,_StartExportDate.Date.Day);
}else{
wsprintf(strDate,L"%d.%d.%d-%d.%d.%d",
_StartExportDate.Date.Year,_StartExportDate.Date.Month,_StartExportDate.Date.Day,
_EndExportDate.Date.Year,_EndExportDate.Date.Month,_EndExportDate.Date.Day);
}
m_BtnExRange.SetText2(strDate);
}
}
appconfig.IniExportAll.Set(_bExportAll);
appconfig.IniExportStartDate.Set(_StartExportDate.Value);
appconfig.IniExportEndDate.Set(_EndExportDate.Value);
m_BtnExRange.Invalidate();
}
void Ui_ImExportWnd::OnMzCommand(WPARAM wParam, LPARAM lParam) {
UINT_PTR id = LOWORD(wParam);
// pop out a PopupMenu:
CPopupMenu ppm;
struct PopupMenuItemProp pmip;
pmip.itemCr = MZC_BUTTON_PELLUCID;
pmip.itemRetID = IDC_PPM_CANCEL;
pmip.str = LOADSTRING(IDS_STR_CANCEL).C_Str();
ppm.AddItem(pmip);
if(!_isImport){
pmip.itemCr = MZC_BUTTON_PELLUCID;
pmip.itemRetID = IDC_PPM_QIF;
pmip.str = LOADSTRING(IDS_STR_EXPORT_QIF).C_Str();
ppm.AddItem(pmip);
}
pmip.itemCr = MZC_BUTTON_PELLUCID;
pmip.itemRetID = IDC_PPM_TAB;
pmip.str = _isImport ? LOADSTRING(IDS_STR_IMPORT_TC).C_Str() : LOADSTRING(IDS_STR_EXPORT_TC).C_Str();
ppm.AddItem(pmip);
pmip.itemCr = MZC_BUTTON_PELLUCID;
pmip.itemRetID = IDC_PPM_COMMA;
pmip.str = _isImport ? LOADSTRING(IDS_STR_IMPORT_CC).C_Str() : LOADSTRING(IDS_STR_EXPORT_CC).C_Str();
ppm.AddItem(pmip);
switch (id) {
case MZ_IDC_BUTTON_EXPORT:
{
break;
}
case MZ_IDC_BUTTON_IMPORT:
{
int mode = 0;
Processor proc;
mode |= _isImport ? Ui_ProcessImExport::PROCESS_IMPORT : Ui_ProcessImExport::PROCESS_EXPORT;
mode |= Ui_ProcessImExport::PROCESS_RECORD;
RECT rc = MzGetWorkArea();
rc.top = rc.bottom - ppm.GetHeight();
ppm.Create(rc.left,rc.top,RECT_WIDTH(rc),RECT_HEIGHT(rc),m_hWnd,0,WS_POPUP);
int nID = ppm.DoModal();
if (nID==IDC_PPM_TAB)
{
mode |= Ui_ProcessImExport::PROCESS_FILE_CSV_S;
}else if(nID == IDC_PPM_COMMA){
mode |= Ui_ProcessImExport::PROCESS_FILE_CSV_C;
}else if(nID == IDC_PPM_QIF){
mode |= Ui_ProcessImExport::PROCESS_FILE_QIF;
}else{
return;
}
//设置时间范围
proc.setExportDateRange(_bExportAll,
_StartExportDate.Value,_EndExportDate.Value);
bool ret = proc.excute(mode);
if(proc.isNoFileSelected()) return;
wchar_t* msg = proc.getLastErrMsg();
MzMessageBoxEx(m_hWnd,msg,ret ? LOADSTRING(IDS_STR_SUCCEED).C_Str() : LOADSTRING(IDS_STR_FAILED).C_Str());
break;
}
case MZ_IDC_BUTTON_EX_RANGE:
{
Ui_ExDateRangeWnd dlg;
dlg.setSelection(_bExportAll);
dlg.setFromDate(_StartExportDate);
dlg.setToDate(_EndExportDate);
RECT rcWork = MzGetWorkArea();
dlg.Create(rcWork.left, rcWork.bottom - 250, RECT_WIDTH(rcWork),250,// RECT_HEIGHT(rcWork),
m_hWnd, 0, WS_POPUP);
// set the animation of the window
dlg.SetAnimateType_Show(MZ_ANIMTYPE_SCROLL_BOTTOM_TO_TOP_2);
dlg.SetAnimateType_Hide(MZ_ANIMTYPE_SCROLL_TOP_TO_BOTTOM_1);
int ret = dlg.DoModal();
if(ret == ID_OK){
_StartExportDate = dlg.getDateFrom();
_EndExportDate = dlg.getDateTo();
_bExportAll = dlg.getSelection();
updateButtonRange();
//TODO: save configuration
}
break;
}
case MZ_IDC_TOOLBAR_CONFIG:
{
int nIndex = lParam;
if (nIndex == 0) {
// exit the modal dialog
EndModal(ID_CANCEL);
return;
}
}
}
} | [
"jemyzhang@e7c2eee8-530d-454e-acc3-bb8019a9d48c"
] | [
[
[
1,
362
]
]
] |
23e2aab13d68ad2cbc0612639a6b93bb9cde2e7b | 9b575a11ef9652d78a93f71f5a61a01ae46ef7d0 | /Box2D2EngineReflexingBalls/sourcecode/LinkerAgent.cpp | abb04676d95567cf09adaaeb00c59870cf9da465 | [] | no_license | vanminhle246/Physics2Engine | f9133786868a8c33d3919ef069372f4b1f9f6eb4 | cd6f0e6d90e02b16dcc397a1f99e0858812dc494 | refs/heads/master | 2021-01-10T19:09:09.757772 | 2011-12-22T10:43:32 | 2011-12-22T10:43:32 | 2,913,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 855 | cpp | #include "LinkerAgent.h"
LinkerAgent::LinkerAgent(void)
{
}
LinkerAgent::~LinkerAgent(void)
{
}
LinkerAgent::LinkerAgent(DJ2DSprite* pSprite, b2Body* pBody)
{
m_pSprite = pSprite;
m_pBody = pBody;
m_isSeed = DJFALSE;
m_pBody->SetUserData(this);
}
void LinkerAgent::UpdateFromEngine()
{
DJVector2 djPosition = m_pSprite->GetPosition();
float djAngle = m_pSprite->GetRotation();
m_pBody->SetTransform(b2Vec2(djPosition.x(), -djPosition.y()), -djAngle);
}
void LinkerAgent::UpdateFromBox2D()
{
b2Vec2 b2dPosition = m_pBody->GetPosition();
m_pSprite->SetPosition(b2dPosition.x, -b2dPosition.y);
m_pSprite->SetRotation(-m_pBody->GetAngle());
}
LinkerAgent::LinkerAgent(DJ2DSprite* pSprite, b2Body* pBody, djbool isSeed)
{
m_pSprite = pSprite;
m_pBody = pBody;
m_isSeed = isSeed;
m_pBody->SetUserData(this);
}
| [
"[email protected]"
] | [
[
[
1,
35
]
]
] |
8b13b083cdc27496c7f913558545df6f0d5dd1fd | 26fe293ae9d1c8eebb6e7112eba4f5ccfb261648 | /jni/Sample.h | dbe43650e93c19561769ba042d00bd253b1c789b | [
"MIT"
] | permissive | jongyeol/rosetta | 767bd5a14368d9cc7df1b853786a84d65bcac9e5 | de2761a4770d6b438fbd471ee4d33dfeb62b011b | refs/heads/master | 2020-05-30T22:17:38.902476 | 2011-01-21T05:30:23 | 2011-01-21T05:30:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | h | #ifndef _SAMPLE_H_
#define _SAMPLE_H_
class Sample {
static Sample* uniqueInstance_;
public:
Sample();
static Sample* getInstance();
int add(int a, int b);
void printLog(char *tag, char *log);
char* getString();
void testCallback();
};
#endif//_SAMPLE_H_
| [
"[email protected]"
] | [
[
[
1,
16
]
]
] |
13909b36da1c98a41e974ade7a6731c6e0a55d67 | 252e638cde99ab2aa84922a2e230511f8f0c84be | /mainlib/src/LoginForm.h | 62024d41703a4e571a8a193bdccba789e9ffa3f0 | [] | no_license | openlab-vn-ua/tour | abbd8be4f3f2fe4d787e9054385dea2f926f2287 | d467a300bb31a0e82c54004e26e47f7139bd728d | refs/heads/master | 2022-10-02T20:03:43.778821 | 2011-11-10T12:58:15 | 2011-11-10T12:58:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,373 | h | //---------------------------------------------------------------------------
#ifndef LoginFormH
#define LoginFormH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ExtCtrls.hpp>
#include <ADODB.hpp>
#include <Db.hpp>
#include <DBTables.hpp>
#include "VStringStorage.h"
//---------------------------------------------------------------------------
class TTourLoginForm : public TForm
{
__published: // IDE-managed Components
TLabel *UserIDLabel;
TLabel *PasswordLabel;
TEdit *UserIDEdit;
TEdit *PasswordEdit;
TButton *AcceptButton;
TButton *ExitButton;
TVStringStorage *VStringStorage;
void __fastcall AcceptButtonClick(TObject *Sender);
void __fastcall FormCloseQuery(TObject *Sender, bool &CanClose);
void __fastcall UserIDEditExit(TObject *Sender);
void __fastcall FormCreate(TObject *Sender);
private: // User declarations
// TADOQuery *LoginQuery;
// Boolean LoginQueryCreate(void);
public: // User declarations
__fastcall TTourLoginForm(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TTourLoginForm *TourLoginForm;
//---------------------------------------------------------------------------
#endif
| [
"[email protected]"
] | [
[
[
1,
39
]
]
] |
163c3caa840aed356891ec08e12b73f68ce178d3 | 3472e587cd1dff88c7a75ae2d5e1b1a353962d78 | /ytk_bak/BatDown/src/BaseTableModel.cpp | 5e2501a927ac40767d8bf3b6451cd741adf13694 | [] | no_license | yewberry/yewtic | 9624d05d65e71c78ddfb7bd586845e107b9a1126 | 2468669485b9f049d7498470c33a096e6accc540 | refs/heads/master | 2021-01-01T05:40:57.757112 | 2011-09-14T12:32:15 | 2011-09-14T12:32:15 | 32,363,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,901 | cpp | #include "BaseTableModel.h"
#include "BatDown.h"
BaseTableModel::BaseTableModel(BatDown* app, QObject *parent)
: QAbstractTableModel(parent), BatDownBase(app)
{
}
BaseTableModel::~BaseTableModel(void)
{
}
QVariant BaseTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole) {
return m_headers.at(section);
}
}
return QAbstractTableModel::headerData(section, orientation, role);
}
int BaseTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_entries.size();
}
int BaseTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_headers.size();
}
QVariant BaseTableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) return QVariant();
record_t entry = m_entries.at(index.row());
if (role == Qt::DisplayRole || role == Qt::EditRole) {
QString fld = m_dbFields.at(index.column());
return entry.value(fld);
}
return QVariant();
}
Qt::ItemFlags BaseTableModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return QAbstractItemModel::flags(index);// | Qt::ItemIsEditable;
}
bool BaseTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if( index.isValid() && (role == Qt::EditRole || role == Qt::DisplayRole) ){
// add 1 to the row index to skip over the header
//m_entries.value(index.row()).replace(index.column(), value.toString());
emit dataChanged(index, index);
return true;
}
return false;
}
void BaseTableModel::insertRecord(record_t &rec, int position)
{
beginInsertRows( QModelIndex(), position, position );
m_pApp->getDbMgr().insertRecord(rec, m_table);
m_entries.insert(position, rec);
insertRows(position, 1);
endInsertRows();
} | [
"yew1998@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86"
] | [
[
[
1,
78
]
]
] |
845212506f305a832ce258270168fea96c938859 | 05869e5d7a32845b306353bdf45d2eab70d5eddc | /soft/application/NetworkSimulator/Dialog/AsyncMessageDlg.cpp | a206a52682845fb141bed280651323d488c8b668 | [] | no_license | shenfahsu/sc-fix | beb9dc8034f2a8fd9feb384155fa01d52f3a4b6a | ccc96bfaa3c18f68c38036cf68d3cb34ca5b40cd | refs/heads/master | 2020-07-14T16:13:47.424654 | 2011-07-22T16:46:45 | 2011-07-22T16:46:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,103 | cpp | // AsyncMessageDlg.cpp : implementation file
//
#include "stdafx.h"
#include "NetworkSimulator.h"
#include "AsyncMessageDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAsyncMessageDlg dialog
CAsyncMessageDlg::CAsyncMessageDlg(CWnd* pParent /*=NULL*/)
: CDialog(CAsyncMessageDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CAsyncMessageDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CAsyncMessageDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAsyncMessageDlg)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAsyncMessageDlg, CDialog)
//{{AFX_MSG_MAP(CAsyncMessageDlg)
// NOTE: the ClassWizard will add message map macros here
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAsyncMessageDlg message handlers
| [
"windyin@2490691b-6763-96f4-2dba-14a298306784"
] | [
[
[
1,
43
]
]
] |
9017bcc0df3ba14e26082f2245cfc9b1c59f3274 | e618b452106f251f3ac7cf929da9c79256c3aace | /src/lib/cpp/uploader/Factory.h | e1ddbe79ddc03f2f2c957b9a2142929852b54f15 | [] | no_license | dlinsin/yfrog | 714957669da86deff3a093a7714e7d800c9260d8 | 513e0d64a0ff749e902e797524ad4a521ead37f8 | refs/heads/master | 2020-12-25T15:40:54.751312 | 2010-04-13T16:31:15 | 2010-04-13T16:31:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 890 | h | #pragma once
#include "ImageShackBase.h"
#include "Uploader.h"
#include "UniversalUploader.h"
#include "URLResolver.h"
namespace UPLOAD {
/**
* Factory to create instance of UniversalUploader and etc.
*
* @author Alexander Kozlov
*/
class IMAGESHACK_API Factory
{
public:
static SmartReleasePtr<ISimpleUploader> CreateSimpleUploader();
template <typename TItem>
static SmartReleasePtr<IUniversalUploaderURLResolver<TItem> > CreateURLResolver(LPCTSTR pszURL)
{
return URLResolver<TItem>::NewInstance(pszURL);
}
template <typename TItem, typename TResult>
static SmartReleasePtr< IUniversalUploader<TItem, TResult> > CreateUploader()
{
return UniversalUploader<TItem, TResult>::NewInstance();
}
};
}//namespace UPLOAD
| [
"[email protected]"
] | [
[
[
1,
32
]
]
] |
0bee6176312f7fd3baa056cf1f10165372243792 | 2d22f791ee4a754eb18e057136bf081d070178e3 | /flPear/flPear.cxx | 444b558096abadfa515f739780ed2522645c6632 | [] | no_license | timfel/ftlk-stuff | 31b5a12b88a8c1ef11297f72670f9e185166ed0a | 1c58ff3f8fd9053f43c2da151b9248071d56ffce | refs/heads/master | 2021-01-22T03:49:34.213475 | 2009-06-29T22:03:24 | 2009-06-29T22:03:24 | 106,745 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,687 | cxx | // generated by Fast Light User Interface Designer (fluid) version 2.1000
#include "flPear.h"
#include <sys/types.h>
#ifndef WIN32
#include <sys/wait.h>
#endif
#include <errno.h>
Fl_Input *hddimg=(Fl_Input *)0;
Fl_Input* create_hddimg=(Fl_Input *)0;
Fl_Input *cdimg=(Fl_Input *)0;
Fl_Check_Button *fscreen=(Fl_Check_Button *)0;
Fl_Check_Button *g4use=(Fl_Check_Button *)0;
Fl_Check_Button *ramuse=(Fl_Check_Button *)0;
Fl_Check_Button *netuse1=(Fl_Check_Button *)0;
Fl_Check_Button *netuse2=(Fl_Check_Button *)0;
Fl_Input *boot_args=(Fl_Input *)0;
Fl_Input_Choice *res=(Fl_Input_Choice *)0;
Fl_Check_Button *cd_dev_check=(Fl_Check_Button *)0;
Fl_Value_Output *valuemoutput=(Fl_Value_Output *)0;
Fl_Input_Choice *valueout=(Fl_Input_Choice *)0;
#include <FL/Fl.H>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
//#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Text_Display.H>
using namespace std;
int parse_config_file(string);
string binary;
string systemcall;
string location;
#ifndef WIN32
fstream conffile;
#endif
Fl_Text_Display *G_disp;
Fl_Text_Buffer *G_buff;
int G_outfd;
pid_t G_pids;
#ifndef WIN32
void start_child(int t) {
int out[2]; pipe(out);
switch ( ( G_pids = fork() ) ) {
case -1: // Error
close(out[0]); close(out[1]);
perror("fork()");
exit(1);
case 0: // Child
close(out[0]); dup2(out[1], 2); close(out[1]);
execlp("/bin/sh", "sh", "-c", systemcall.c_str(),0);
perror("execlp(ps)");
exit(1);
default: // Parent
G_outfd = out[0]; close(out[1]);
return;
}
}
void data_ready(int fd, void *data) {
//int t = (int)data;
int t = 0;
char s[4096];
int bytes = read(fd, s, 4096-1);
// fprintf(stderr, "Data ready for %d) pid=%ld fd=%d bytes=%d\n", t, (long)G_pids, fd, bytes);
if ( bytes == -1 ) { // ERROR
perror("read()");
} else if ( bytes == 0 ) { // EOF
G_buff->append("\n\n*** EOF ***\n");
int status;
if ( waitpid(G_pids, &status, WNOHANG) < 0 ) {
sprintf(s, "waitpid(): %s\n", strerror(errno));
} else {
if ( WIFEXITED(status) ) {
sprintf(s, "Exit=%d\n", WEXITSTATUS(status));
close(fd); Fl::remove_fd(fd); G_pids = -1;
} else if ( WIFSIGNALED(status) ) {
sprintf(s, "Killed with %d\n", WTERMSIG(status));
close(fd); Fl::remove_fd(fd); G_pids = -1;
} else if ( WIFSTOPPED(status) ) {
sprintf(s, "Stopped with %d\n", WSTOPSIG(status));
}
}
G_buff->append(s);
} else { // DATA
s[bytes] = 0;
G_buff->append(s);
}
}
void close_cb(Fl_Widget*, void*) {
printf("Killing child processes..\n");
(G_pids != -1) ? kill(G_pids, 9) : printf("Nothing to kill.\n");
printf("Done.\n");
exit(0);
}
#endif
void cancel_callback(Fl_Button*, void* wp) {
Fl_Window* w = (Fl_Window*)wp;
w->hide();
}
void create_callback(Fl_Return_Button*, void* wp) {
Fl_Window* w = (Fl_Window*)wp;
w->hide();
#ifndef WIN32
string creatorcall = "wine /usr/share/pearpc/buildhdd.exe";
#endif
#ifdef WIN32
string creatorcall = location;
creatorcall += "\\buildhdd.exe";
#endif
creatorcall += " ";
#ifndef WIN32
int pos;
creatorcall += "Z:\\";
#endif
creatorcall += create_hddimg->value();
#ifndef WIN32
for (int i = 35; i < creatorcall.length(); i++)
{
if ((pos = creatorcall.find("/", i)) != string::npos)
{
creatorcall.replace(pos, 1, "\\\\");
}
}
#endif
creatorcall += " ";
creatorcall += valueout->value();
cout << creatorcall << endl;
system(creatorcall.c_str());
}
void hddmake_callback(Fl_Button*, void*) {
Fl_Window* w;
{Fl_Window* o = new Fl_Window(280, 180);
w = o;
o->begin();
{Fl_Input* o = create_hddimg = new Fl_Input(25, 25, 175, 25, "HDD-Image");
o->align(FL_ALIGN_TOP|FL_ALIGN_LEFT);
}
{Fl_Button* o = new Fl_Button(205, 25, 50, 25, "Find...");
o->callback((Fl_Callback*)hdd_callback, (void*)(create_hddimg));
}
valueout = new Fl_Input_Choice(160, 75, 50, 25);
valueout->add("1");
valueout->add("3");
valueout->add("6");
valueout->value("3");
{Fl_Box* o = new Fl_Box(25, 75, 110, 25, "Size in GB");
o->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE);
}
{Fl_Return_Button* o = new Fl_Return_Button(35, 125, 100, 25, "Create it!");
o->shortcut(0xff0d);
o->callback((Fl_Callback*)create_callback, (void*)(w));
}
{Fl_Button* o = new Fl_Button(145, 125, 100, 25, "Cancel");
o->callback((Fl_Callback*)cancel_callback, (void*)(w));
}
o->end();
}
w->show();
}
int main (int argc, char **argv) {
#ifdef WIN32
location = argv[0];
//location.erase((location.length()-11), 11);
cout << "flPear - the PearPC Frontend. Built for Windows" << endl;
#endif
#ifndef WIN32
cout << "flPear - the PearPC Frontend. Built for UNIX" << endl;
Fl::scheme("gtk+");
#endif
Fl_Window* w;
{Fl_Window* o = new Fl_Window(425, 355);
w = o;
o->begin();
{Fl_Input* o = hddimg = new Fl_Input(25, 25, 255, 25, "HDD-Image");
o->align(FL_ALIGN_TOP|FL_ALIGN_LEFT);
}
{Fl_Input* o = cdimg = new Fl_Input(25, 70, 255, 25, "CD-Image");
o->align(FL_ALIGN_TOP|FL_ALIGN_LEFT);
}
{Fl_Check_Button* o = fscreen = new Fl_Check_Button(25, 160, 90, 25, "Fullscreen");
o->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE);
o->labelsize(11);
}
{Fl_Check_Button* o = g4use = new Fl_Check_Button(25, 185, 215, 25, "Use experimental G4 processor");
o->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE);
o->labelsize(11);
}
{Fl_Check_Button* o = ramuse = new Fl_Check_Button(25, 210, 245, 25, "Use 256 MB RAM instead of 128 MB");
o->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE|FL_ALIGN_WRAP);
o->labelsize(11);
}
{Fl_Check_Button* o = netuse1 = new Fl_Check_Button(25, 235, 190, 25, "Use 3c90x network device");
o->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE);
o->labelsize(11);
}
{Fl_Check_Button* o = netuse2 = new Fl_Check_Button(25, 260, 195, 25, "Use rtl8139 network device");
o->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE);
o->labelsize(11);
}
{Fl_Input* o = boot_args = new Fl_Input(100, 285, 180, 25, "BootArgs:");
o->align(FL_ALIGN_LEFT);
o->labelsize(11);
}
{Fl_Button* o = new Fl_Button(290, 25, 50, 25, "Find...");
o->callback((Fl_Callback*)hdd_callback, (void*)(hddimg));
}
{Fl_Button* o = new Fl_Button(350, 25, 50, 25, "Make...");
o->callback((Fl_Callback*)hddmake_callback, (void*)(hddimg));
}
{Fl_Button* o = new Fl_Button(290, 70, 50, 25, "Find...");
o->callback((Fl_Callback*)cd_callback, (void*)(cdimg));
}
{Fl_Input_Choice* o = res = new Fl_Input_Choice(25, 115, 230, 25, "Resolution");
o->align(FL_ALIGN_TOP|FL_ALIGN_LEFT);
res->add("800x600x15");
res->add("1024x768x15");
res->add("1280x800x15");
res->add("1280x960x15");
}
{Fl_Check_Button* o = cd_dev_check = new Fl_Check_Button(5, 70, 20, 25);
o->callback((Fl_Callback*)cd_dev_callback);
o->value(1);
}
{Fl_Dial* o = new Fl_Dial(305, 205, 75, 75);
o->box(FL_OSHADOW_BOX);
o->minimum(10);
o->maximum(500);
o->type(0);
o->step(5);
o->value(40);
o->callback((Fl_Callback*)dial_change);
}
{Fl_Box* o = new Fl_Box(280, 190, 125, 20, "Refresh Rate");
o->align(FL_ALIGN_TOP|FL_ALIGN_INSIDE);
}
{Fl_Value_Output* o = valuemoutput = new Fl_Value_Output(328, 280, 30, 20);
o->box(FL_THIN_DOWN_BOX);
o->minimum(10);
o->maximum(500);
o->step(1);
o->value(40);
}
{Fl_Return_Button* o = new Fl_Return_Button(295, 315, 110, 25, "Run PearPC");
o->shortcut(0xff0d);
o->callback((Fl_Callback*)run_callback);
}
{Fl_Button* o = new Fl_Button(155, 315, 110, 25, "Locate ppc");
o->callback((Fl_Callback*)locate_callback);
}
{Fl_Button* o = new Fl_Button(15, 315, 110, 25, "Save config");
o->callback((Fl_Callback*)save_callback);
}
o->end();
}
#ifndef WIN32
parse_config_file(getenv("HOME"));
#endif
#ifdef WIN32
parse_config_file("");
#endif
w->show(argc, argv);
return Fl::run();
}
void run_callback(Fl_Return_Button*, void*) {
#ifndef WIN32
ofstream ofile("/tmp/ppc.cfg", ios::trunc);
#endif
#ifdef WIN32
string temp = location;
temp += "\\ppc.cfg";
ofstream ofile(temp.c_str(), ios::trunc);
#endif
ofile << "ppc_start_resolution = \"" << res->value() << "\"" << endl;
fscreen->value()==1 ?
ofile << "ppc_start_full_screen = 1" << endl :
ofile << "ppc_start_full_screen = 0" << endl;
#ifndef WIN32
ofile << "redraw_interval_msec = " << valuemoutput->value() << endl;
#endif
#ifdef WIN32
ofile << "redraw_interval_msec = 40" << endl;
#endif
ofile << "key_compose_dialog = \"F11\"" << endl;
ofile << "key_change_cd_0 = \"none\"" << endl;
ofile << "key_toggle_mouse_grab = \"F12\"" << endl;
ofile << "key_toggle_full_screen = \"Alt+Return\"" << endl;
ofile << "prom_bootmethod = \"select\"" << endl;
if (boot_args->value() == "") {
ofile << "prom_env_machargs = \"-v\"" << endl;
} else {
ofile << "prom_env_machargs = \"" << boot_args->value() << "\"" << endl;
}
#ifndef WIN32
ofile << "prom_driver_graphic = \"/usr/share/pearpc/video.x\"" << endl;
#endif
#ifdef WIN32
ofile << "prom_driver_graphic = \"" << location << "\\video.x\"" << endl;
#endif
ofile << "#page_table_pa = 104857600" << endl;
g4use->value()==1 ?
ofile << "cpu_pvr = 0x000c0000" << endl :
ofile << "cpu_pvr = 0x00088302" << endl;
ramuse->value()==1 ?
ofile << "memory_size=0x10000000" << endl :
ofile << "#memory_size=0x10000000" << endl;
ofile << "pci_ide0_master_installed = 1" << endl;
ofile << "pci_ide0_master_image = \"" << hddimg->value() << "\"" << endl;
ofile << "pci_ide0_master_type = \"hd\"" << endl;
cd_dev_check->value()==1 ?
ofile << "pci_ide0_slave_installed = 1" << endl :
ofile << "pci_ide0_slave_installed = 0" << endl;
ofile << "pci_ide0_slave_image = \"" << cdimg->value() << "\"" << endl;
ofile << "pci_ide0_slave_type = \"cdrom\"" << endl;
netuse1->value()==1 ?
ofile << "pci_3c90x_installed = 1" << endl :
ofile << "pci_3c90x_installed = 0" << endl;
ofile << "pci_3c90x_mac = \"de:ad:ca:fe:12:34\"" << endl;
netuse2->value()==1 ?
ofile << "pci_rtl8139_installed = 1" << endl :
ofile << "pci_rtl8139_installed = 0" << endl;
ofile << "pci_rtl8139_mac = \"de:ad:ca:fe:12:35\"" << endl;
ofile << "pci_usb_installed = 1" << endl;
#ifndef WIN32
ofile << "pci_serial_installed = 0" << endl;
ofile << "nvram_file = \"/tmp/nvram\"" << endl;
#endif
#ifdef WIN32
ofile << "nvram_file = \"" << location << "\\nvram\"" << endl;
#endif
ofile.close();
#ifndef WIN32
systemcall = binary;
systemcall += " /tmp/ppc.cfg 1>&2";
#endif
#ifdef WIN32
systemcall = binary;
systemcall += " ";
systemcall += location;
systemcall += "\\ppc.cfg";
#endif
#ifndef WIN32
Fl_Window* out = new Fl_Window(520, 320, "Output");
out->begin();
{
start_child(0);
G_buff = new Fl_Text_Buffer();
G_disp = new Fl_Text_Display(10, 10, 500, 300);
G_disp->buffer(G_buff);
G_disp->textfont(FL_COURIER);
G_disp->textsize(12);
Fl::add_fd(G_outfd, data_ready, (void*)0);
}
out->resizable(out);
out->end();
out->show();
#endif
#ifdef WIN32
system(systemcall.c_str());
#endif
}
void hdd_callback(Fl_Button*, void* ph) {
Fl_Input* hd = (Fl_Input*)ph;
char* newfile;
newfile = fl_file_chooser("Choose a hdd image...",
"Image Files (*.img)",
"",0);
if (newfile != NULL) hd->value(newfile);
}
void cd_callback(Fl_Button*, void*) {
char* newfile;
newfile = fl_file_chooser("Choose an iso image...",
"ISO Files (*.iso)",
"",0);
if (newfile != NULL) cdimg->value(newfile);
}
void dial_change(Fl_Dial* w, void*) {
valuemoutput->value(w->value());
}
void cd_dev_callback(Fl_Check_Button* chk, void*) {
chk->value()==0 ? cdimg->deactivate() : cdimg->activate();
}
int parse_config_file(string homedir) {
#ifndef WIN32
homedir += "/.flPear.cfg";
conffile.open(homedir.c_str(), ios::in);
#endif
#ifdef WIN32
homedir = location;
homedir += "\\flPear.cfg";
ifstream conffile(homedir.c_str());
#endif
if (conffile == NULL)
{
#ifndef WIN32
cerr << "\nCreating config file";
conffile.open(homedir.c_str(), ios::out);
binary = "/usr/share/pearpc/ppc";
#endif
#ifdef WIN32
cerr << "\nCreating config file";
ofstream conffile(homedir.c_str());
binary = location;
binary += "\\ppc";
#endif
conffile << binary << "\n\n\n\n\n\n\n\n";
conffile.close();
}
else
{
char c;
string buf;
int opt;
getline(conffile, binary);
cout << "Binary:" << binary << endl;
getline(conffile,buf);
hddimg->value(buf.c_str());
cout << "HDD-Image:" << buf << endl;
opt = conffile.get();
cd_dev_check->value(opt);
cd_dev_callback(cd_dev_check, 0);
c = conffile.get();
getline(conffile,buf);
cdimg->value(buf.c_str());
cout << "CD-Image:" << buf << endl;
getline(conffile, buf);
res->value(buf.c_str());
cout << "Resolution:" << buf << endl;
opt = conffile.get();
fscreen->value(opt);
opt = conffile.get();
g4use->value(opt);
opt = conffile.get();
ramuse->value(opt);
opt = conffile.get();
netuse1->value(opt);
opt = conffile.get();
netuse2->value(opt);
conffile >> opt;
valuemoutput->value(opt);
opt = conffile.get();
getline(conffile,buf);
boot_args->value(buf.c_str());
cout << "Boot Arguments:" << buf << endl;
}
conffile.close();
}
void save_callback(Fl_Button*, void*) {
#ifndef WIN32
string homedir = getenv("HOME");
homedir += "/.flPear.cfg";
#endif
#ifdef WIN32
string homedir = location;
homedir += "\\flPear.cfg";
#endif
cout << "Saving to " << homedir << endl;
#ifndef WIN32
conffile.open(homedir.c_str(), ios::out|ios::trunc);
#endif
#ifdef WIN32
ofstream conffile(homedir.c_str(), ios::trunc);
#endif
conffile << binary.c_str() << endl;
conffile << hddimg->value() << endl;
conffile.put(cd_dev_check->value());
conffile.put('\n');
conffile << cdimg->value() << endl;
conffile << res->value() << endl;
conffile.put(fscreen->value());
conffile.put(g4use->value());
conffile.put(ramuse->value());
conffile.put(netuse1->value());
conffile.put(netuse2->value());
conffile.put('\n');
conffile << valuemoutput->value() << endl;
conffile << boot_args->value() << endl;
conffile.close();
}
void locate_callback(Fl_Button*, void*) {
char* newfile;
newfile = fl_file_chooser("Locate the ppc binary...",
"Any File (*)",
"",0);
#ifndef WIN32
string configfile = getenv("HOME");
configfile += "/.flPear.cfg";
#endif
#ifdef WIN32
string configfile = location;
configfile += "\\flPear.cfg";
#endif
if (newfile != NULL) binary=newfile;
}
| [
"tim@tim-laptop.(none)",
"[email protected]"
] | [
[
[
1,
176
],
[
178,
518
]
],
[
[
177,
177
]
]
] |
86ed5fc1db223addc628b3e60ae5448f9fe68748 | 6c8c4728e608a4badd88de181910a294be56953a | /InventoryModule/ItemPropertiesWindow.h | c383325e35e607b5307b210eae04ab6572ea3630 | [
"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 | 3,730 | h | // For conditions of distribution and use, see copyright notice in license.txt
/**
* @file ItemPropertiesWindow.h
* @brief Item properties window. Shows basic information about inventory item and the asset
* it's referencing to.
*/
#ifndef incl_InventoryModule_ItemPropertiesWindow_h
#define incl_InventoryModule_ItemPropertiesWindow_h
#include <RexUUID.h>
#include <boost/shared_ptr.hpp>
#include <QWidget>
#include <QMap>
namespace Foundation
{
class AssetInterface;
typedef boost::shared_ptr<AssetInterface> AssetPtr;
}
namespace UiServices
{
class UiProxyWidget;
}
QT_BEGIN_NAMESPACE
class QVBoxLayout;
class QLineEdit;
class QLabel;
class QPushButton;
QT_END_NAMESPACE
namespace Inventory
{
class InventoryModule;
class InventoryAsset;
class ItemPropertiesWindow : public QWidget
{
Q_OBJECT
public:
/// Constructor.
/// @param owner InventoryModule pointer.
/// @param parent Parent widget.
ItemPropertiesWindow(InventoryModule *owner, QWidget *parent = 0);
/// Destructor.
~ItemPropertiesWindow();
public slots:
/// Sets the item which properties we want to view.
/// @param item Inventory asset.
void SetItem(InventoryAsset *item);
/// Set the file size shown in the UI.
/// @param file_size File size.
void SetFileSize(size_t file_size);
/// Handles UuidNameReply
/// Inserts the corresponding name to the UI if it matches with the UUID.
/// @param uuid_name_map Map of UUID-name pairs.
void HandleUuidNameReply(QMap<RexUUID, QString> uuid_name_map);
private slots:
/// Tells InventoryModule to destroy the window and save the changes made to the item.
void Save();
/// Tells InventoryModule to destroy the window. Doesn't save changes made to the item.
void Cancel();
/// Checks the validity of user-editable fiels.
/// Disables Save button if no modifications are made.
/// @return True if values were modified, false otherwise.
bool EditingFinished();
private:
/// Main widget loaded from .ui file.
QWidget *mainWidget_;
/// Layout
QVBoxLayout *layout_;
/// InventoryModule pointer.
InventoryModule *owner_;
/// Proxy widget for ui
UiServices::UiProxyWidget *proxyWidget_;
/// Inventory item ID
QString inventoryId_;
/// Original name of the item.
QString originalName_;
/// Original description of the item.
QString originalDescription_;
/// Creator ID.
RexUUID creatorId_;
/// Owner ID.
RexUUID ownerId_;
/// Group ID.
RexUUID groupId_;
/// Line edit for name.
QLineEdit *lineEditName_;
/// Line edit for description.
QLineEdit *lineEditDescription_;
/// Asset ID value label.
QLabel *labelAssetIdData_;
/// Type value label.
QLabel *labelTypeData_;
/// File size value label
QLabel *labelFileSizeData_;
/// Creation time value label.
QLabel *labelCreationTimeData_;
/// Creator value label.
QLabel *labelCreatorData_;
/// Owner value label.
QLabel *labelOwnerData_;
/// Group value label.
QLabel *labelGroupData_;
/// Save button.
QPushButton *pushButtonSave_;
/// Cancel buytton.
QPushButton *pushButtonCancel_;
};
}
#endif
| [
"Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3"
] | [
[
[
1,
147
]
]
] |
73bb3671aa89a6e3af4d48a3d60bc9fa3c4e1174 | af6700f0656c42c3634c1b7cf6d1559f526558f5 | /src/Document.h | 704119a45ef9a4d5aac4873ab99bd9fdcc043e2f | [] | no_license | BackupTheBerlios/lprojector-svn | 56c037c13c95cc8c86c54c1f7a35182f6c3acf93 | aa3a9accf1db75efcb0dad9e4a86cdf8d7e01c84 | refs/heads/master | 2020-05-18T07:29:51.646042 | 2008-12-30T14:29:04 | 2008-12-30T14:29:04 | 40,800,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,196 | h | #ifndef DOCUMENT_H_INCLUDED
#define DOCUMENT_H_INCLUDED
#include "DocumentInfo.h"
#include <QWidget>
//#include <QPlainTextEdit>
class QString;
class QSyntaxHighlighter;
class LineNumberWidget;
class QHBoxLayout;
class CodeEdit;
class Document : public QWidget {
Q_OBJECT
public:
Document(const DocumentInfo& docinfo,
const QString & text, QWidget* parent=0);
~Document();
DocumentInfo* documentInfo() { return &docinfo_; }
QString text() const;
int currentLine() const;
int currentColumn() const;
int lines() const;
int length() const;
int selectionStart() const;
int selectionEnd() const;
int selectionLength() const;
protected:
DocumentInfo docinfo_;
QSyntaxHighlighter* highlighter;
CodeEdit* m_textEdit;
// LineNumberWidget* m_lineNumberWidget;
QHBoxLayout* m_layout;
signals:
void aboutToClose(Document* sender);
void textChanged();
void cursorPositionChanged();
public slots:
void close();
protected slots:
void onTextChanged();
};
#endif // DOCUMENT_H_INCLUDED
| [
"ckrudewig@8ed94309-155f-0410-a4f3-f9db7d64bce2"
] | [
[
[
1,
55
]
]
] |
6fc916276b4f4a62615e44625bb2560aaa187c70 | d2996420f8c3a6bbeef63a311dd6adc4acc40436 | /src/server/ServerGravitationalObject.cpp | 49d147c53e180b60b84c8acc21a21a726fcf75b7 | [] | no_license | aruwen/graviator | 4d2e06e475492102fbf5d65754be33af641c0d6c | 9a881db9bb0f0de2e38591478429626ab8030e1d | refs/heads/master | 2021-01-19T00:13:10.843905 | 2011-03-13T13:15:25 | 2011-03-13T13:15:25 | 32,136,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,863 | cpp | #include "ServerGravitationalObject.h"
#include "../Utility.h"
typedef ServerObjectFactory<ServerGravitationalObject> ObjectFactory;
#define OF ObjectFactory::getInstance()
namespace //so this will be created before entering main()
{
ServerGravitationalObject* shotPoint()
{
return new ServerGravitationalObject();
}
bool registerShot = OF.Register("shotPoint", shotPoint);
}
namespace
{
ServerGravitationalObject* steeringPoint()
{
return new ServerGravitationalObject();
}
bool registerSteering = OF.Register("steeringPoint", steeringPoint);
}
namespace
{
ServerGravitationalObject* centerPoint()
{
return new ServerGravitationalObject();
}
bool registerCenter = OF.Register("centerPoint", centerPoint);
}
ServerGravitationalObject::~ServerGravitationalObject(void)
{
}
void ServerGravitationalObject::update()
{
}
bool ServerGravitationalObject::shouldBeKilled()
{
if (mMortal)
{
if (clock() > mCreationTime + mSecondsToLive * CLOCKS_PER_SEC)
{
return true;
}
else return false;
}
else return false;
}
vec3f ServerGravitationalObject::getForce( vec3f affectedLocation )
{
vec3f returnVector(0, 0, 0);
float gravity = LUA.getFloat("gravity");
vec3f calculationPosition;
if (USE_2D_CALCULATION)
calculationPosition = mPosition;
else
calculationPosition = transformToCalculationCoordinates(mPosition);
vec3f radius(
affectedLocation.x - calculationPosition.x,
0,
affectedLocation.z - calculationPosition.z);
returnVector = (-radius/radius.getLength() * (gravity * mMass) / radius.dotSelf());
if (returnVector.getLength() > mMass / 10)
{
returnVector.normalize();
returnVector = returnVector * mMass / 10;
}
return returnVector;
}
| [
"[email protected]@c8d5bfcc-1391-a108-90e5-e810ef6ef867"
] | [
[
[
1,
86
]
]
] |
928fbc9f36008a71d477683bbfd6391441819b45 | 66c63eb5a9ccbc3543264816823cd982679c04c3 | /src/core/Actions.h | 36fc4b0b2b7d88e022d16cb0be7d5029bc6a87ad | [
"Zlib"
] | permissive | unjello/calkulator | 4a299fa554d7b4505b750e8deaa959524cdf98db | 12ee2702ed6e324e2bded7abaf664aeb4cfb4c1b | refs/heads/master | 2021-01-25T10:28:46.194017 | 2010-03-08T21:58:39 | 2010-03-08T21:58:39 | 553,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,511 | h | /*
* function actors
*
* calculator
* (c) 2003 andrzej lichnerowicz. all rights reserved.
*
* permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* this software is provided "as is" without express or implied warranty,
* and with no claim as to its suitability for any purpose.
*
* Changeslog:
* 12 Mar 2003 AL + added assign operators actions
* 08 Mar 2003 AL * completly rewritten
* * moved from "Grammar.h"
*
*/
#pragma once
struct UnaryFunction_t : unary_function<Value_t,Value_t> {
virtual result_type operator()(argument_type const&) const { return 0.0; }
};
struct BinaryFunction_t : binary_function<Value_t,Value_t,Value_t> {
virtual result_type operator()(first_argument_type const&,second_argument_type const&) const { return 0.0; }
};
class FuncSin_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return sin(arg); }
} FuncSin;
class FuncCos_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return cos(arg); }
} FuncCos;
class FuncTg_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return tan(arg); }
} FuncTg;
class FuncCtg_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return cos(arg)/sin(arg); }
} FuncCtg;
class FuncArcTg_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return atan(arg); }
} FuncArcTg;
class FuncSqr_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return arg*arg; }
} FuncSqr;
class FuncSqrt_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return sqrt(arg); }
} FuncSqrt;
class FuncLog_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return log10(arg); }
} FuncLog;
class FuncLn_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return log(arg); }
} FuncLn;
class FuncRad_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return arg*pi/180.0; }
} FuncRad;
class FuncDeg_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return arg*180.0/pi; }
} FuncDeg;
class FuncAbs_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return fabs(arg); }
} FuncAbs;
class FuncFloor_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return floor(arg); }
} FuncFloor;
class FuncCeil_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return ceil(arg); }
} FuncCeil;
class FuncExp_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return exp(arg); }
} FuncExp;
class FuncSign_t : public UnaryFunction_t {
result_type operator()(argument_type const& arg) const { return arg>0?1:-1; }
} FuncSign;
class FuncPow_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return pow(arg1,arg2); }
} FuncPow;
class OpAssign_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return arg2; }
} OpAssign;
class OpAssignMul_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return arg1*arg2; }
} OpAssignMul;
class OpAssignDiv_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return arg1/arg2; }
} OpAssignDiv;
class OpAssignModulo_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return static_cast<DWORD>(arg1)%static_cast<DWORD>(arg2); }
} OpAssignModulo;
class OpAssignAdd_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return arg1+arg2; }
} OpAssignAdd;
class OpAssignSub_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return arg1-arg2; }
} OpAssignSub;
class OpAssignShiftLeft_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return static_cast<DWORD>(arg1)<<static_cast<DWORD>(arg2); }
} OpAssignShiftLeft;
class OpAssignShiftRight_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return static_cast<DWORD>(arg1)>>static_cast<DWORD>(arg2); }
} OpAssignShiftRight;
class OpAssignBitAnd_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return static_cast<DWORD>(arg1)&static_cast<DWORD>(arg2); }
} OpAssignBitAnd;
class OpAssignBitXor_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return static_cast<DWORD>(arg1)^static_cast<DWORD>(arg2); }
} OpAssignBitXor;
class OpAssignBitOr_t : public BinaryFunction_t {
result_type operator()(first_argument_type const& arg1,second_argument_type const& arg2) const { return static_cast<DWORD>(arg1)|static_cast<DWORD>(arg2); }
} OpAssignBitOr;
| [
"[email protected]"
] | [
[
[
1,
114
]
]
] |
de88677768c5b9b9072b3631bf30b49e2dd329cd | 4e708256396ac2e5374286018174f01497c9a7e9 | /phonetheater/QSelectByTheater.cpp | 3b63a63a9aed9280b0113e15c5dc58fac7feaa23 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | momofarm/MobileTheater | 8bcea21e178077cebe2683422e9869cca14df374 | 921f60b6ea520fa23d46c3f9d6b16f7955f12514 | refs/heads/master | 2021-01-10T20:44:23.134327 | 2010-09-29T07:27:36 | 2010-09-29T07:27:36 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,435 | cpp |
#include "QSelectByTheater.h"
#include <stdlib.h>
#include <QPushButton>
#include <QVBoxLayout>
#include <QDialog>
#include <QSignalMapper>
#include <QTextCodec>
#include "qtimetable.h"
#include "httpTool.h"
#include "Constants.h"
#include "todayshow.h"
#include <QAction>
QSelectByTheater::QSelectByTheater(QWidget *pParent, QStringList *pTheaterNameList, QStringList *pTheaterCodeList)
:QDialog(pParent)
{
QAction *pActionBack = new QAction("°h¥X", this);
pActionBack->setSoftKeyRole(QAction::NegativeSoftKey);
QAction *pActionOption = new QAction("¿ï¶µ", this);
pActionOption->setSoftKeyRole(QAction::PositiveSoftKey);
addAction(pActionBack);
addAction(pActionOption);
connect(pActionBack, SIGNAL(triggered()), this, SLOT(close()));
connect(pActionOption, SIGNAL(triggered()), this, SLOT(close()));
std::vector<QPushButton *> ar;
QVBoxLayout *pLayout = new QVBoxLayout();
pMapper = new QSignalMapper(this);
QTextCodec *codec = QTextCodec::codecForName("BIG5");
for (int i = 0; i < pTheaterNameList->count(); i++)
{
QString str = pTheaterNameList->at(i);
QByteArray arydata;
arydata.append(str);
QPushButton *pButton = new QPushButton(str, this);
ar.push_back(pButton);
pLayout->addWidget(pButton);
pMapper->setMapping(pButton, pTheaterCodeList->at(i));
connect(pButton, SIGNAL(clicked()), pMapper, SLOT(map()));
}
//mapped(QString &)
connect(pMapper, SIGNAL(mapped(QString)), this, SLOT(Press(QString)));
setLayout(pLayout);
show();
}
QSelectByTheater::~QSelectByTheater()
{
}
void QSelectByTheater::Press(QString strCode)
{
//sender()->
int a = 0;
QHttpTool *t = new QHttpTool(this);
QTimeTable *list = new QTimeTable(this, strCode);
connect(t, SIGNAL(ReturnResult(QByteArray &)), list, SLOT(DealResult(QByteArray &)));
t->Request(HTTP_URL_HOST, HTTP_URL_PORT, list);
QTodayShow showDlg(list->GetMovieNames(), list->GetMovieHall(), list->GetMovieTime(), this);
QStringList theaterInfo = list->GetTheaterInfo();
//name/phone/addr
QString name = theaterInfo.at(0);
QString phone = theaterInfo.at(1);
QString addr = theaterInfo.at(2);
showDlg.SetInfo(name, phone, addr);
showDlg.exec();
}
| [
"[email protected]"
] | [
[
[
1,
108
]
]
] |
cad1c6f191cc18577a937df9727917aa951eb109 | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/core/Query/ListSelection.cpp | 8c8c68402ab72a61f9c1c5f7104ce420abb235d0 | [
"BSD-3-Clause"
] | permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | ISO-8859-9 | C++ | false | false | 25,994 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright © 2008, Daniel Önnerby
//
// 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 author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#ifdef WIN32
#include "pch.hpp"
#else
#include <core/pch.hpp>
#endif
#include <core/Query/ListSelection.h>
#include <core/Library/Base.h>
#include <core/xml/ParserNode.h>
#include <core/xml/WriterNode.h>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
using namespace musik::core;
//////////////////////////////////////////
///\brief
///Constructor
//////////////////////////////////////////
Query::ListSelection::ListSelection(void) : selectionOrderSensitive(true){
}
//////////////////////////////////////////
///\brief
///Destructor
//////////////////////////////////////////
Query::ListSelection::~ListSelection(void){
}
//////////////////////////////////////////
///\brief
///Set if the list should be sensitive for the selection order of metalist. Default is true.
///
///\param sensitive
///sensitive or not
///
///The behavior of the query will be a lot different if this is turned on.
///Consider the folloing example:
///\code
/// ...
/// musik::core::Query::ListSelection query;
/// ... // Connect the "artist" and "album" using the OnMetadataEvent()
///
/// query.SelectMetadata("genre",1); // selects the genre with id 1
/// library.AddQuery(query); // this will list "artist" and "album"
///
/// query.SelectMetadata("artist",3); // select the artist with id 3
///
/// // this is where the selection order differes.
/// query.SelectMetadata("genre",2); // Adds the genre id 2 to the selection
/// // If the Sensitivity is turned on, the selection of "artist" will be cleared
/// // witch means that the query will automatically call query.ClearMetadata("artist").
///\endcode
///
//////////////////////////////////////////
void Query::ListSelection::SelectionOrderSensitive(bool sensitive){
this->selectionOrderSensitive = sensitive;
}
//////////////////////////////////////////
///\brief
///Select a specific metadata
///
///\param metakey
///meta key to select. Like "genre" or "artist"
///
///\param metadataId
///The database identifier of the metakeys value
///
///\remarks
///SelectMetadata will add to the selection.
///
///\see
///ClearMetadata|RemoveMetadata
//////////////////////////////////////////
void Query::ListSelection::SelectMetadata(const char* metakey,DBINT metadataId){
if(this->selectionOrderSensitive){
std::vector<std::string>::iterator themetakey = std::find(this->metakeySelectionOrder.begin(),this->metakeySelectionOrder.end(),metakey);
if(themetakey==this->metakeySelectionOrder.end()){
// Not in selection yet
this->metakeySelectionOrder.push_back(metakey);
}else{
// Erase everything after this metakey
++themetakey;
if( themetakey!=this->metakeySelectionOrder.end() ){
// Clear selection
this->ClearMetadata(themetakey->c_str());
}
}
}
this->selectedMetadata[metakey].insert(metadataId);
}
//////////////////////////////////////////
///\brief
///Remove a selection
///
///\param metakey
///metakey to remove. Like "genre" or "artist"
///
///\param metadataId
///The database identifier of the metakeys value
///
///\see
///ClearMetadata|SelectMetadata
//////////////////////////////////////////
void Query::ListSelection::RemoveMetadata(const char* metatag,DBINT metadataId){
SelectedMetadata::iterator keyiterator = this->selectedMetadata.find(metatag);
if(keyiterator!=this->selectedMetadata.end()){
keyiterator->second.erase(metadataId);
if(keyiterator->second.empty()){
// All selections have been removed, Clear
this->ClearMetadata(metatag);
}else{
if(this->selectionOrderSensitive){
std::vector<std::string>::iterator themetakey = std::find(this->metakeySelectionOrder.begin(),this->metakeySelectionOrder.end(),metatag);
if(themetakey==this->metakeySelectionOrder.end()){
++themetakey;
if( themetakey!=this->metakeySelectionOrder.end() ){
// Clear selection
this->ClearMetadata(themetakey->c_str());
}
}
}
}
}
}
//////////////////////////////////////////
///\brief
///Clear a selection totaly or clear a specific metakey selection
///
///\param metakey
///metakey to clear. Like "genre" or "artist"
///
///\see
///RemoveMetadata|SelectMetadata
//////////////////////////////////////////
void Query::ListSelection::ClearMetadata(const char* metatag){
if(metatag==NULL){
this->selectedMetadata.clear();
this->metakeySelectionOrder.clear();
}else{
this->selectedMetadata.erase(metatag);
if(this->selectionOrderSensitive){
std::vector<std::string>::iterator metakey = std::find(this->metakeySelectionOrder.begin(),this->metakeySelectionOrder.end(),metatag);
while( metakey!=this->metakeySelectionOrder.end() ){
// Clear selection
this->selectedMetadata.erase( *metakey );
// Go to the next selection
metakey = this->metakeySelectionOrder.erase(metakey);
}
}
}
}
//////////////////////////////////////////
///\brief
///Parse the list query
///
///\param library
///pointer to library that parses the query. Needed for mutexes.
///
///\param db
///pointer to database connect object
///
///\returns
///true when successfully parsed
///
///This is a pretty tricky thing to parse.
///First lets select the tracks
/// SELECT t.id FROM tracks t ORDER BY t.sort_order1
///
/// 1. lets check the genre and artists metadata
/// if they are selected insert into the select like:
/// SELECT t.id FROM tracks t WHERE t.id IN (SELECT track_id FROM track_genres WHERE genre_id IN ($genrelist$))
/// AND t.id IN (SELECT track_id FROM track_artists WHERE artist_id IN ($artistlist$))
/// this should make SQLite use the indexes on the track_* tables.
///
/// 2. Check the album and the fixed fields
/// SELECT t.id FROM tracks t WHERE album_id IN ($albumlist$)
/// AND year IN ($yearlist$)
/// This will only work on fields that are INTEGERS
/// year,duration,filesize,track,album_id
///
/// 3. Check for other selected metadata
/// SELECT t.id FROM tracks t WHERE t.id IN
/// (SELECT track_id FROM track_meta WHERE meta_value_id IN ($metadatalist$))
///
/// Second, we need to select the metadata
///
/// 1. if genre or artists are connected for callbacks
/// SELECT g.id,g.name FROM genres g WHERE g.id IN (SELECT genre_id FROM track_genres WHERE track_id IN ($tracklist$)) ORDER BY g.sort_order
///
/// I guess I could generate a list from the tracks, but this list
/// could become VERY long (20000 tracks is not uncommon). Using the
/// sql from the tracks select is my temporary solution.
///
/// 2. Getting fixed fields
/// Well.. I guess I could do this at the same time when I select the tracks by adding them in the select
/// SELECT t.id,t.year FROM tracks t ORDER BY t.sort_order1
/// and store the output in a std::set<DBINT> to get the uniq fields
/// This way they will also be sorted.
/// Do the same for the "album" but get album_id and query for it later.
///
/// 3. Get the metadata
/// SELECT id,content FROM meta_values WHERE meta_key_id IN (SELECT id FROM meta_keys WHERE name=?) AND id IN (SELECT meta_value_id FROM track_meta WHERE track_id IN ($tracklist$)) ORDER BY sort_order
///
//////////////////////////////////////////
bool Query::ListSelection::ParseQuery(Library::Base *library,db::Connection &db){
bool success(true);
////////////////////////////////////////////////
// First lets make sure we do not have any signals
// or selections that are empty
for(MetadataSignals::iterator signal=this->metadataEvent.begin();signal!=this->metadataEvent.end();){
if( !signal->second.has_connections() ){
this->metadataEvent.erase(signal);
signal=this->metadataEvent.begin();
}else{
++signal;
}
}
for(SelectedMetadata::iterator selected=this->selectedMetadata.begin();selected!=this->selectedMetadata.end();){
if( selected->second.empty() ){
this->selectedMetadata.erase(selected);
selected = this->selectedMetadata.begin();
}else{
++selected;
}
}
////////////////////////////////////////////////
// Second. Select track
std::string sqlSelectTrack("SELECT t.id AS id,t.duration AS sum_duration,t.filesize AS sum_filesize");
std::string sqlSelectTrackFrom(" FROM tracks t ");
std::string sqlSelectTrackWhere;
std::string sqlSelectTrackOrder("ORDER BY t.sort_order1");
// Copy selected metakeys
std::set<std::string> metakeysSelected,metakeysSelectedCopy;
for(SelectedMetadata::iterator selected=this->selectedMetadata.begin();selected!=this->selectedMetadata.end();++selected){
metakeysSelected.insert(selected->first);
}
metakeysSelectedCopy = metakeysSelected;
// Copy queried metakeys
std::set<std::string> metakeysQueried,metakeysQueriedCopy;
for(MetadataSignals::iterator signal=this->metadataEvent.begin();signal!=this->metadataEvent.end();++signal){
if(metakeysSelected.find(signal->first)==metakeysSelected.end()){ // Do not insert metakeys that are selected
metakeysQueried.insert(signal->first);
}
}
metakeysQueriedCopy = metakeysQueried;
if(!metakeysSelected.empty()){
////////////////////////////////////////////////
// Selected genre
this->SQLSelectQuery("genre","t.id IN (SELECT track_id FROM track_genres WHERE genre_id IN (",")) ",metakeysSelected,sqlSelectTrackWhere,library);
////////////////////////////////////////////////
// Selected artists
this->SQLSelectQuery("artist","t.id IN (SELECT track_id FROM track_artists WHERE artist_id IN (",")) ",metakeysSelected,sqlSelectTrackWhere,library);
////////////////////////////////////////////////
// Selected albums
this->SQLSelectQuery("album","t.album_id IN (",") ",metakeysSelected,sqlSelectTrackWhere,library);
////////////////////////////////////////////////
// Selected year
this->SQLSelectQuery("year","t.year IN (",") ",metakeysSelected,sqlSelectTrackWhere,library);
////////////////////////////////////////////////
// Selected duration
this->SQLSelectQuery("duration","t.duration IN (",") ",metakeysSelected,sqlSelectTrackWhere,library);
////////////////////////////////////////////////
// Selected track
this->SQLSelectQuery("track","t.track IN (",") ",metakeysSelected,sqlSelectTrackWhere,library);
////////////////////////////////////////////////
// Selected metadata
std::set<std::string> tempMetakeysSelected(metakeysSelected);
for(std::set<std::string>::iterator metakey=tempMetakeysSelected.begin();metakey!=tempMetakeysSelected.end();++metakey){
this->SQLSelectQuery(metakey->c_str(),"t.id IN (SELECT track_id FROM track_meta WHERE meta_value_id IN (",")) ",metakeysSelected,sqlSelectTrackWhere,library);
}
}
////////////////////////////////////////////////
// check for fixed fields that are queried and add them to the selected fields
if(metakeysQueried.find("year")!=metakeysQueried.end()){
sqlSelectTrack.append(",t.year AS year");
}
if(metakeysQueried.find("bpm")!=metakeysQueried.end()){
sqlSelectTrack.append(",t.bpm AS bpm");
}
if(metakeysQueried.find("album")!=metakeysQueried.end()){
sqlSelectTrack.append(",t.album_id AS album_id");
}
if(metakeysQueried.find("duration")!=metakeysQueried.end()){
sqlSelectTrack.append(",t.duration AS duration");
}
if(metakeysQueried.find("filesize")!=metakeysQueried.end()){
sqlSelectTrack.append(",t.filesize AS filesize");
}
if(metakeysQueried.find("track")!=metakeysQueried.end()){
sqlSelectTrack.append(",t.track AS track");
}
////////////////////////////////////////////////
// Lets get the tracks from the database and insert into a temporary table
std::string sqlTracks = sqlSelectTrack+sqlSelectTrackFrom+sqlSelectTrackWhere+sqlSelectTrackOrder;
if(!metakeysSelectedCopy.empty()){
// Select into temporary table
sqlTracks = "CREATE TEMPORARY TABLE temp_tracks_list AS ";
sqlTracks.append(sqlSelectTrack+sqlSelectTrackFrom+sqlSelectTrackWhere+sqlSelectTrackOrder);
// Drop table if last Query::ListSelection was canceled
db.Execute("DROP TABLE IF EXISTS temp_tracks_list");
db.Execute(sqlTracks.c_str());
}
////////////////////////////////////////////////
// Third. Get the metadata values for connected slots.
// std::string sqlTrackQuery(sqlTracks);
// Genre
if(metakeysSelectedCopy.empty()){
this->QueryForMetadata("genre","SELECT g.id,g.name FROM genres g WHERE g.aggregated=0 ORDER BY g.sort_order",metakeysQueried,library,db);
}else{
this->QueryForMetadata("genre","SELECT g.id,g.name FROM genres g WHERE g.aggregated=0 AND g.id IN (SELECT genre_id FROM track_genres WHERE track_id IN (SELECT id FROM temp_tracks_list)) ORDER BY g.sort_order",metakeysQueried,library,db);
}
// Artists
if(metakeysSelectedCopy.empty()){
this->QueryForMetadata("artist","SELECT a.id,a.name FROM artists a WHERE a.aggregated=0 ORDER BY a.sort_order",metakeysQueried,library,db);
}else{
this->QueryForMetadata("artist","SELECT a.id,a.name FROM artists a WHERE a.aggregated=0 AND a.id IN (SELECT artist_id FROM track_artists WHERE track_id IN (SELECT id FROM temp_tracks_list)) ORDER BY a.sort_order",metakeysQueried,library,db);
}
////////////////////////////////////////////////
// Take care of selecting fixed fields like album,track,duration,year
// Album
if(metakeysSelectedCopy.empty()){
this->QueryForMetadata("album","SELECT a.id,a.name FROM albums a ORDER BY a.sort_order",metakeysQueried,library,db);
}else{
this->QueryForMetadata("album","SELECT a.id,a.name FROM albums a WHERE a.id IN (SELECT album_id FROM temp_tracks_list) ORDER BY a.sort_order",metakeysQueried,library,db);
}
// Track
if(metakeysSelectedCopy.empty()){
this->QueryForMetadata("track","SELECT track,track FROM (SELECT DISTINCT(track) AS track FROM tracks ORDER BY track)",metakeysQueried,library,db);
}else{
this->QueryForMetadata("track","SELECT track,track FROM (SELECT DISTINCT(track) AS track FROM temp_tracks_list ORDER BY track)",metakeysQueried,library,db);
}
// Year
if(metakeysSelectedCopy.empty()){
this->QueryForMetadata("year","SELECT year,year FROM (SELECT DISTINCT(year) AS year FROM tracks ORDER BY year)",metakeysQueried,library,db);
}else{
this->QueryForMetadata("year","SELECT year,year FROM (SELECT DISTINCT(year) AS year FROM temp_tracks_list ORDER BY year)",metakeysQueried,library,db);
}
// Duration
if(metakeysSelectedCopy.empty()){
this->QueryForMetadata("duration","SELECT duration,duration FROM (SELECT DISTINCT(duration) AS duration FROM tracks ORDER BY duration)",metakeysQueried,library,db);
}else{
this->QueryForMetadata("duration","SELECT duration,duration FROM (SELECT DISTINCT(duration) AS duration FROM temp_tracks_list ORDER BY duration)",metakeysQueried,library,db);
}
////////////////////////////////////////////////
// Select metadata
std::set<std::string> tempMetakeysQueried(metakeysQueried);
{
db::CachedStatement metakeyId("SELECT id FROM meta_keys WHERE name=?",db);
for(std::set<std::string>::iterator metakey=tempMetakeysQueried.begin();metakey!=tempMetakeysQueried.end();++metakey){
metakeyId.BindText(0,*metakey);
if(metakeyId.Step()==db::Row){
std::string metadataKeyId(metakeyId.ColumnText(0));
std::string sql("SELECT mv.id,mv.content FROM meta_values mv WHERE mv.meta_key_id=");
sql.append(metadataKeyId);
if(metakeysSelectedCopy.empty()){
// List all
sql.append(" ORDER BY mv.sort_order");
}else{
sql.append(" AND mv.id IN (SELECT meta_value_id FROM track_meta WHERE track_id IN (SELECT id FROM temp_tracks_list))");
}
this->QueryForMetadata(metakey->c_str(),sql.c_str(),metakeysQueried,library,db);
}
metakeyId.Reset();
}
}
////////////////////////////////////////////////
// Select tracks
std::string sql("SELECT t.id,t.duration,t.filesize FROM tracks t ORDER BY t.sort_order1");
if(!metakeysSelectedCopy.empty()){
sql = "SELECT t.id,t.sum_duration,t.sum_filesize FROM temp_tracks_list t";
}
return (success && this->ParseTracksSQL(sql,library,db));
}
//////////////////////////////////////////
///\brief
///Copy a query
///
///\returns
///A shared_ptr to the Query::Base
//////////////////////////////////////////
Query::Ptr Query::ListSelection::copy() const{
Query::Ptr queryCopy(new Query::ListSelection(*this));
queryCopy->PostCopy();
return queryCopy;
}
void Query::ListSelection::SQLPrependWhereOrAnd(std::string &sql){
if(sql.empty()){
sql.append("WHERE ");
}else{
sql.append("AND ");
}
}
//////////////////////////////////////////
///\brief
///Helper method to construct SQL query for selected metakeys
//////////////////////////////////////////
void Query::ListSelection::SQLSelectQuery(const char *metakey,const char *sqlStart,const char *sqlEnd,std::set<std::string> &metakeysSelected,std::string &sqlSelectTrackWhere,Library::Base *library){
if(!library->QueryCanceled(this)){
SelectedMetadata::iterator selected = this->selectedMetadata.find(metakey);
if(selected!=this->selectedMetadata.end()){
this->SQLPrependWhereOrAnd(sqlSelectTrackWhere);
sqlSelectTrackWhere.append(sqlStart);
bool first(true);
for(std::set<DBINT>::iterator id=selected->second.begin();id!=selected->second.end();++id){
if(first){
first=false;
}else{
sqlSelectTrackWhere.append(",");
}
sqlSelectTrackWhere.append(boost::lexical_cast<std::string>(*id));
}
sqlSelectTrackWhere.append(sqlEnd);
}
metakeysSelected.erase(metakey);
}
}
//////////////////////////////////////////
///\brief
///Method called by ParseQuery for every queried metakey
//////////////////////////////////////////
void Query::ListSelection::QueryForMetadata(const char *metakey,const char *sql,std::set<std::string> &metakeysQueried,Library::Base *library,db::Connection &db){
if(library->QueryCanceled(this))
return;
if(metakeysQueried.find(metakey)!=metakeysQueried.end()){
db::Statement metaValueStmt(sql,db);
MetadataValueVector tempMetadataValues;
tempMetadataValues.reserve(10);
int row(0);
{
boost::mutex::scoped_lock lock(library->resultMutex);
this->metadataResults[metakey];
}
while(metaValueStmt.Step()==db::Row){
tempMetadataValues.push_back(
MetadataValuePtr(
new MetadataValue(
metaValueStmt.ColumnInt(0),
metaValueStmt.ColumnTextUTF(1)
)
)
);
if( (++row)%10==0 ){
boost::mutex::scoped_lock lock(library->resultMutex);
this->metadataResults[metakey].insert(this->metadataResults[metakey].end(),tempMetadataValues.begin(),tempMetadataValues.end());
tempMetadataValues.clear();
tempMetadataValues.reserve(10);
}
}
if(!tempMetadataValues.empty()){
boost::mutex::scoped_lock lock(library->resultMutex);
this->metadataResults[metakey].insert(this->metadataResults[metakey].end(),tempMetadataValues.begin(),tempMetadataValues.end());
}
metakeysQueried.erase(metakey);
}
}
//////////////////////////////////////////
///\brief
///Receive the query from XML
///
///\param queryNode
///Reference to query XML node
///
///The excpeted input format is like this:
///\code
///<query type="ListSelection">
/// <selections>
/// <selection key="genre">1,3,5,7</selection>
/// <selection key="artist">6,7,8</selection>
/// </selections>
/// <listeners>genre,artist,album</listeners>
///</query>
///\endcode
///
///\returns
///true when successfully received
//////////////////////////////////////////
bool Query::ListSelection::ReceiveQuery(musik::core::xml::ParserNode &queryNode){
while( musik::core::xml::ParserNode node = queryNode.ChildNode() ){
if(node.Name()=="selections"){
// Get metakey nodes
// Expected tag is likle this:
// <selection key="genre">2,5,3</selection>
while( musik::core::xml::ParserNode selectionNode = node.ChildNode("selection") ){
// Wait for all content
selectionNode.WaitForContent();
// Split comaseparated list
typedef std::vector<std::string> StringVector;
StringVector values;
boost::algorithm::split(values,selectionNode.Content(),boost::algorithm::is_any_of(","));
for(StringVector::iterator value=values.begin();value!=values.end();++value){
this->SelectMetadata(selectionNode.Attributes()["key"].c_str(),boost::lexical_cast<DBINT>(*value));
}
}
}else{
this->ReceiveQueryStandardNodes(node);
}
}
return true;
}
std::string Query::ListSelection::Name(){
return "ListSelection";
}
/// <selections>
/// <selection key="genre">1,3,5,7</selection>
/// <selection key="artist">6,7,8</selection>
/// </selections>
bool Query::ListSelection::SendQuery(musik::core::xml::WriterNode &queryNode){
xml::WriterNode selectionsNode(queryNode,"selections");
// Start with the selection nodes
for(SelectedMetadata::iterator selection=this->selectedMetadata.begin();selection!=this->selectedMetadata.end();++selection){
xml::WriterNode selectionNode(selectionsNode,"selection");
selectionNode.Attributes()["key"] = selection->first;
std::string selectionIDs;
for(SelectedMetadataIDs::iterator id=selection->second.begin();id!=selection->second.end();++id){
if(!selectionIDs.empty()){
selectionIDs.append(",");
}
selectionIDs.append(boost::lexical_cast<std::string>(*id));
}
selectionNode.Content() = selectionIDs;
}
this->SendQueryStandardNodes(queryNode);
return true;
}
| [
"onnerby@6a861d04-ae47-0410-a6da-2d49beace72e",
"Urioxis@6a861d04-ae47-0410-a6da-2d49beace72e",
"[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e"
] | [
[
[
1,
36
],
[
43,
561
],
[
563,
578
],
[
580,
580
],
[
582,
604
],
[
606,
645
]
],
[
[
37,
42
]
],
[
[
562,
562
],
[
579,
579
],
[
581,
581
],
[
605,
605
]
]
] |
767491662060c1e09419cba7221285f06c3345e3 | 59166d9d1eea9b034ac331d9c5590362ab942a8f | /FrustumTerrainShader/TerrainShader/DynamicGroupLevel2048Node.cpp | 1b397857cd362f8be2d8d38b5af1c3644bc3dac3 | [] | no_license | seafengl/osgtraining | 5915f7b3a3c78334b9029ee58e6c1cb54de5c220 | fbfb29e5ae8cab6fa13900e417b6cba3a8c559df | refs/heads/master | 2020-04-09T07:32:31.981473 | 2010-09-03T15:10:30 | 2010-09-03T15:10:30 | 40,032,354 | 0 | 3 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 7,046 | cpp | #include "DynamicGroupLevel2048Node.h"
#include <osg/Geometry>
#include <iostream>
DynamicGroupLevel2048Node::DynamicGroupLevel2048Node() : m_iCount( 0 )
{
//зарезервировать память для 128 узлов
m_vData.resize( 128 );
//группа узлов
m_rootNode = new osg::Group;
//инициализировать геометрию патчей земной поверхности
InitGeodes();
//узел динамически меняет количество потомков
m_rootNode->setDataVariance( osg::Object::DYNAMIC );
}
void DynamicGroupLevel2048Node::InitGeodes()
{
//инициализировать геометрию патчей земной поверхности
for ( int i = 0 ; i < m_vData.size() ; ++i )
{
//добавить узел геометрии
m_vData[ i ].m_Geode = new osg::Geode;
//добавить uniform
m_vData[ i ].m_unfOffset = new osg::Uniform( m_vData[ i ].m_sOffset.c_str() , osg::Vec3( 0,0,0) );
m_vData[ i ].m_unfColorP = new osg::Uniform( m_vData[ i ].m_sColorP.c_str() , osg::Vec3( 0,1,0 ) );
m_vData[ i ].m_unfColorS = new osg::Uniform( m_vData[ i ].m_sColorS.c_str() , osg::Vec3( 1,0,0 ) );
m_vData[ i ].m_unfKofScale = new osg::Uniform( m_vData[ i ].m_sKofScale.c_str() , 32.0f );
m_vData[ i ].m_unfDist = new osg::Uniform( m_vData[ i ].m_sDist.c_str() , 2048.0f * DIST_SCALE );
m_vData[ i ].m_unfTexCoordAdd = new osg::Uniform( m_vData[ i ].m_sTexCoordAdd.c_str() , 2.0f );
m_vData[ i ].m_unfTexCoordScale = new osg::Uniform( m_vData[ i ].m_sTexCoordScale.c_str() , 64.0f );
//добавить геометрию в i'ый узел
AddGeometry( i );
//настроить параметры необходимые в шейдере
SetupShaderParam( i );
m_rootNode->addChild( m_vData[ i ].m_Geode.get() );
}
}
void DynamicGroupLevel2048Node::ResetRootNode()
{
//удалить всех потомков корневого узла
m_iCount = 0;
m_rootNode->removeChildren( 0 , m_rootNode->getNumChildren() );
}
void DynamicGroupLevel2048Node::AddGeometry( int i )
{
//добавить геометрию в i'ый узел
//создать объект для хранения в нем геометрии
osg::ref_ptr< osg::Geometry > geom = new osg::Geometry;
//создать массив вершин
geom->setVertexArray( CreateVertexArray( 0 , 0 , 68 , 2048 ).get() );
std::vector< unsigned short > m_vIndex;
//заполнить вектор индексами
FillIndexVector( m_vIndex , 68 );
geom->addPrimitiveSet( new osg::DrawElementsUShort(
osg::PrimitiveSet::TRIANGLE_STRIP, m_vIndex.size() / GEOM_DIV , &m_vIndex[ 0 ] ) );
osg::BoundingBox bbox( 0, 0, 0, 512 * 512 , 512 * 512 , 64 );
geom->setInitialBound( bbox );
//добавить рисуемую геометрию
m_vData[ i ].m_Geode->addDrawable( geom.get() );
}
void DynamicGroupLevel2048Node::SetupShaderParam( int i )
{
//настроить параметры необходимые в шейдере
//формирование сцены с шейдером
osg::StateSet* ss = m_vData[ i ].m_Geode->getOrCreateStateSet();
//добавление uniform'а для задания смещения патча
ss->addUniform( m_vData[ i ].m_unfOffset.get() );
ss->addUniform( m_vData[ i ].m_unfColorP.get() );
ss->addUniform( m_vData[ i ].m_unfColorS.get() );
ss->addUniform( m_vData[ i ].m_unfKofScale.get() );
ss->addUniform( m_vData[ i ].m_unfDist.get() );
ss->addUniform( m_vData[ i ].m_unfTexCoordAdd.get() );
ss->addUniform( m_vData[ i ].m_unfTexCoordScale.get() );
}
osg::ref_ptr<osg::Vec4Array> DynamicGroupLevel2048Node::CreateVertexArray( int x , int y , int sizeC , int scaleC )
{
//создать массив вершин
osg::ref_ptr<osg::Vec4Array> v = new osg::Vec4Array;
//kof = 32.0f
float kof = (float)scaleC / (float)( sizeC - 4 );
kof = 1.0;
//номер ячейки в которой будет сдвиг
int iQuad = ( sizeC - 4 ) / 4 + 1;
//смещение по Y
int iY = 0;
//Заполнение массива points
for (int i = 0 ; i < sizeC ; ++i )
{
//момент когда надо сдвигать на 1 по Y
int shift = iQuad * ( iY + 1 );
//если i совпадает с iHalf то сместиться на 1 вниз
if ( i == shift )
++iY;
//смещение по X
int iX = 0;
for (int j = 0 ; j < sizeC ; ++j )
{
//момент когда надо сдвигать на 1 по Y
int shift = iQuad * ( iX + 1 );
//если j совпадает с iHalf то сместиться на 1 в лево
if ( j == shift )
++iX;
v->push_back( osg::Vec4( x + ( j - iX ) * kof , y + ( i - iY ) * kof , iX , iY ) );
}
}
return v.get();
}
void DynamicGroupLevel2048Node::FillIndexVector( std::vector< unsigned short > &m_vIndex , int sizeC )
{
//заполнить вектор индексами
//заполнить вектор индексами
m_vIndex.push_back( 0 );
m_vIndex.push_back( sizeC );
int count = sizeC - 1;
int ind = 0;
while( count > 0 )
{
for( int i = 0 ; i < count ; i++ )
{
ind = m_vIndex.size() - 2;
m_vIndex.push_back( m_vIndex[ ind ] + 1 );
ind = m_vIndex.size() - 2;
m_vIndex.push_back( m_vIndex[ ind ] + 1 );
}
ind = m_vIndex.size() - 3;
m_vIndex.push_back( m_vIndex[ ind ] );
count--;
for( int i = 0 ; i< count ; i++ )
{
ind = m_vIndex.size() - 2;
m_vIndex.push_back( m_vIndex[ ind ] + sizeC );
ind = m_vIndex.size() - 2;
m_vIndex.push_back( m_vIndex[ ind ] + sizeC );
}
ind = m_vIndex.size() - 3;
m_vIndex.push_back( m_vIndex[ ind ] );
for( int i = 0 ; i < count ; i++ )
{
ind = m_vIndex.size() - 2;
m_vIndex.push_back( m_vIndex[ ind ] - 1 );
ind = m_vIndex.size() - 2;
m_vIndex.push_back( m_vIndex[ ind ] - 1 );
}
ind = m_vIndex.size() - 3;
m_vIndex.push_back( m_vIndex[ ind ] );
count--;
for( int i=0 ; i < count ; i++ )
{
ind = m_vIndex.size() - 2;
m_vIndex.push_back( m_vIndex[ ind ] - sizeC );
ind = m_vIndex.size() - 2;
m_vIndex.push_back( m_vIndex[ ind ] - sizeC );
}
ind = m_vIndex.size() - 3;
m_vIndex.push_back( m_vIndex[ ind ] );
}
}
void DynamicGroupLevel2048Node::AddPatch( float x , float y )
{
//добавить патч геометрии из буффера в корневой узел
//обновить данные в uniform'e
m_vData[ m_iCount ].m_unfOffset->set( osg::Vec3( x , y , 0.0f ) );
//добавить очередной узел из буффера
m_rootNode->addChild( m_vData[ m_iCount ].m_Geode.get() );
++m_iCount;
}
void DynamicGroupLevel2048Node::PrintSize()
{
//вывести количество узлов для отрисовки
std::cout << m_rootNode->getNumChildren() << " ";
} | [
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
] | [
[
[
1,
216
]
]
] |
b99586cf0b8eba372662c647977839acadb060e1 | 54745d6fa529d0adcd19a41e115bbccfb804b575 | /OtherCode/treelimit.cpp | aa81aff32b15a39276793273870b7ccf922eb044 | [] | no_license | jackylee1/regretitron | e7a5f1a8794f0150b57f3ca679438d0f38984bca | bb241e6dea4d345e48d633da48ed2cfd410a5fdf | refs/heads/master | 2020-03-26T17:53:07.040365 | 2011-11-14T03:38:53 | 2011-11-14T03:38:53 | 145,185,451 | 0 | 1 | null | 2018-08-18T03:04:05 | 2018-08-18T03:04:04 | null | UTF-8 | C++ | false | false | 1,244 | cpp | #if 0
#include "treelimit.h"
// For extern vs static and const,
// see: http://www.gamedev.net/community/forums/topic.asp?topic_id=318620
//THESE ARE THE GLOBAL VARIABLES THAT MAKE UP THE BETTING TREE.
//ONE IS FOR POST FLOP, THE OTHER IS FOR PREFLOP.
const betnode n[10] = //10 is how many betindex values.
{// { pl#,Nacts,{children}, {winners}, {utilities} }
{ 0, 2, {1, 9, NA}, {NA, NA, NA}, {NA, NA, NA} }, //0
{ 1, 2, {NA, 8, NA}, {-1, NA, NA}, {0, NA, NA} }, //1
{ 0, 3, {NA, NA, 3 }, {1, -1, NA}, {2, 4, NA} }, //2
{ 1, 3, {NA, NA, 4 }, {0, -1, NA}, {4, 6, NA} }, //3
{ 0, 2, {NA, NA, NA}, {1, -1, NA}, {6, 8, NA} }, //4
{ 1, 3, {NA, NA, 6 }, {0, -1, NA}, {2, 4, NA} }, //5
{ 0, 3, {NA, NA, 7 }, {1, -1, NA}, {4, 6, NA} }, //6
{ 1, 2, {NA, NA, NA}, {0, -1, NA}, {6, 8, NA} }, //7
{ 0, 3, {NA, NA, 5 }, {1, -1, NA}, {0, 2, NA} }, //8
{ 1, 3, {NA, NA, 2 }, {0, -1, NA}, {0, 2, NA} } //9
};
const betnode pfn[8] = //preflop is different.
{// { pl#,Nacts,{children}, {winners}, {utilities} }
{ 1, 3, {NA, 1, 2 }, {0, NA, NA}, {1, NA, NA} }, //0
{ 0, 2, {NA, 5, NA}, {-1, NA, NA}, {2, NA, NA} }, //1
n[2], n[3], n[4], n[5], n[6], n[7] // 2 - 7
};
#endif | [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
ea7629a1cf55727a24f87749a1f34afe00848311 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ogre/OgreNewt/boost/mpl/min_max.hpp | fa0e59bca83f357fb1841748f1f07bd5dc7c9c94 | [] | 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 | 1,052 | hpp |
#ifndef BOOST_MPL_MAX_HPP_INCLUDED
#define BOOST_MPL_MAX_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-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/min_max.hpp,v $
// $Date: 2006/04/17 23:49:40 $
// $Revision: 1.1 $
#include <boost/mpl/less.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/aux_/na_spec.hpp>
namespace boost { namespace mpl {
template<
typename BOOST_MPL_AUX_NA_PARAM(N1)
, typename BOOST_MPL_AUX_NA_PARAM(N2)
>
struct min
: if_< less<N1,N2>,N1,N2 >
{
};
template<
typename BOOST_MPL_AUX_NA_PARAM(N1)
, typename BOOST_MPL_AUX_NA_PARAM(N2)
>
struct max
: if_< less<N1,N2>,N2,N1 >
{
};
BOOST_MPL_AUX_NA_SPEC(2, min)
BOOST_MPL_AUX_NA_SPEC(2, max)
}}
#endif // BOOST_MPL_MAX_HPP_INCLUDED
| [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
] | [
[
[
1,
46
]
]
] |
a22513d84e8102410300becc70be10bb7796ac3c | 22d9640edca14b31280fae414f188739a82733e4 | /Code/VTK/include/vtk-5.2/vtkExtractTemporalFieldData.h | b29f10a06a101484ac4acb0091552791eff1af25 | [] | no_license | tack1/Casam | ad0a98febdb566c411adfe6983fcf63442b5eed5 | 3914de9d34c830d4a23a785768579bea80342f41 | refs/heads/master | 2020-04-06T03:45:40.734355 | 2009-06-10T14:54:07 | 2009-06-10T14:54:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,497 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkExtractTemporalFieldData.h,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkExtractTemporalFieldData - Extract temporal arrays from input field data
// .SECTION Description
// vtkExtractTemporalFieldData extracts arrays from the input vtkFieldData.
// These arrays are assumed to contain temporal data, where the nth tuple
// contains the value for the nth timestep.
// The output is a 1D rectilinear grid where the
// XCoordinates correspond to time (the same array is also copied to
// a point array named Time or TimeData (if Time exists in the input).
// This algorithm does not produce a TIME_STEPS or TIME_RANGE information
// because it works across time.
// .Section Caveat
// vtkExtractTemporalFieldData puts a vtkOnePieceExtentTranslator in the
// output during RequestInformation(). As a result, the same whole
// extented is produced independent of the piece request.
// This algorithm works only with source that produce TIME_STEPS().
// Continuous time range is not yet supported.
#ifndef __vtkExtractTemporalFieldData_h
#define __vtkExtractTemporalFieldData_h
#include "vtkRectilinearGridAlgorithm.h"
class vtkDataSet;
class vtkRectilinearGrid;
class vtkDataSetAttributes;
class VTK_GRAPHICS_EXPORT vtkExtractTemporalFieldData : public vtkRectilinearGridAlgorithm
{
public:
static vtkExtractTemporalFieldData *New();
vtkTypeRevisionMacro(vtkExtractTemporalFieldData,vtkRectilinearGridAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Get the number of time steps
vtkGetMacro(NumberOfTimeSteps,int);
protected:
vtkExtractTemporalFieldData();
~vtkExtractTemporalFieldData();
virtual int ProcessRequest(vtkInformation*,
vtkInformationVector**,
vtkInformationVector*);
virtual int RequestInformation(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector);
virtual int RequestUpdateExtent(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector);
virtual int RequestData(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector);
virtual int FillInputPortInformation(int port, vtkInformation* info);
// Description:
// This looks at the arrays in the vtkFieldData of input and copies them
// to the output point data.
void CopyDataToOutput(vtkDataSet *input, vtkRectilinearGrid *output);
int NumberOfTimeSteps;
private:
vtkExtractTemporalFieldData(const vtkExtractTemporalFieldData&); // Not implemented.
void operator=(const vtkExtractTemporalFieldData&); // Not implemented.
};
#endif
| [
"nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f"
] | [
[
[
1,
88
]
]
] |
e6b403ddc8d1308616a9c433b9bdc37e65e80114 | 29c5bc6757634a26ac5103f87ed068292e418d74 | /externallibs/ogre/include/OgrePrerequisites.h | 4a0df6003d0408cd882664e98cd8b928e4476fb7 | [] | no_license | drivehappy/tlapi | d10bb75f47773e381e3ba59206ff50889de7e66a | 56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9 | refs/heads/master | 2021-03-19T07:10:57.343889 | 2011-04-18T22:58:29 | 2011-04-18T22:58:29 | 32,191,364 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,869 | h | /*-------------------------------------------------------------------------
This source file is a part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License (LGPL) as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or go to
http://www.gnu.org/copyleft/lesser.txt
-------------------------------------------------------------------------*/
#ifndef __OgrePrerequisites_H__
#define __OgrePrerequisites_H__
// Platform-specific stuff
#include "OgrePlatform.h"
// Needed for OGRE_WCHAR_T_STRINGS below
#include <string>
#if OGRE_COMPILER == OGRE_COMPILER_MSVC
// Turn off warnings generated by long std templates
// This warns about truncation to 255 characters in debug/browse info
# pragma warning (disable : 4786)
// Turn off warnings generated by long std templates
// This warns about truncation to 255 characters in debug/browse info
# pragma warning (disable : 4503)
// disable: "conversion from 'double' to 'float', possible loss of data
# pragma warning (disable : 4244)
// disable: "truncation from 'double' to 'float'
# pragma warning (disable : 4305)
// disable: "<type> needs to have dll-interface to be used by clients'
// Happens on STL member variables which are not public therefore is ok
# pragma warning (disable : 4251)
// disable: "non dll-interface class used as base for dll-interface class"
// Happens when deriving from Singleton because bug in compiler ignores
// template export
# pragma warning (disable : 4275)
// disable: "C++ Exception Specification ignored"
// This is because MSVC 6 did not implement all the C++ exception
// specifications in the ANSI C++ draft.
# pragma warning( disable : 4290 )
// disable: "no suitable definition provided for explicit template
// instantiation request" Occurs in VC7 for no justifiable reason on all
// #includes of Singleton
# pragma warning( disable: 4661)
// disable: deprecation warnings when using CRT calls in VC8
// These show up on all C runtime lib code in VC8, disable since they clutter
// the warnings with things we may not be able to do anything about (e.g.
// generated code from nvparse etc). I doubt very much that these calls
// will ever be actually removed from VC anyway, it would break too much code.
# pragma warning( disable: 4996)
// disable: "conditional expression constant", always occurs on
// OGRE_MUTEX_CONDITIONAL when no threading enabled
# pragma warning (disable : 201)
#endif
// configure memory tracking
#if OGRE_DEBUG_MODE
# if OGRE_MEMORY_TRACKER_DEBUG_MODE
# define OGRE_MEMORY_TRACKER 1
# else
# define OGRE_MEMORY_TRACKER 0
# endif
#else
# if OGRE_MEMORY_TRACKER_RELEASE_MODE
# define OGRE_MEMORY_TRACKER 1
# else
# define OGRE_MEMORY_TRACKER 0
# endif
#endif
namespace Ogre {
// Define ogre version
#define OGRE_VERSION_MAJOR 1
#define OGRE_VERSION_MINOR 6
#define OGRE_VERSION_PATCH 4
#define OGRE_VERSION_SUFFIX ""
#define OGRE_VERSION_NAME "Shoggoth"
#define OGRE_VERSION ((OGRE_VERSION_MAJOR << 16) | (OGRE_VERSION_MINOR << 8) | OGRE_VERSION_PATCH)
// define the real number values to be used
// default to use 'float' unless precompiler option set
#if OGRE_DOUBLE_PRECISION == 1
/** Software floating point type.
@note Not valid as a pointer to GPU buffers / parameters
*/
typedef double Real;
#else
/** Software floating point type.
@note Not valid as a pointer to GPU buffers / parameters
*/
typedef float Real;
#endif
#if OGRE_COMPILER == OGRE_COMPILER_GNUC && OGRE_COMP_VER >= 310 && !defined(STLPORT)
# if OGRE_COMP_VER >= 430
# define HashMap ::std::tr1::unordered_map
# define HashSet ::std::tr1::unordered_set
# else
# define HashMap ::__gnu_cxx::hash_map
# define HashSet ::__gnu_cxx::hash_set
# endif
#else
# if OGRE_COMPILER == OGRE_COMPILER_MSVC
# if OGRE_COMP_VER >= 1600 // VC++ 10.0
# define HashMap ::std::tr1::unordered_map
# define HashSet ::std::tr1::unordered_set
# elif OGRE_COMP_VER > 1300 && !defined(_STLP_MSVC)
# define HashMap ::stdext::hash_map
# define HashSet ::stdext::hash_set
# else
# define HashMap ::std::hash_map
# define HashSet ::std::hash_set
# endif
# else
# define HashMap ::std::hash_map
# define HashSet ::std::hash_set
# endif
#endif
/** In order to avoid finger-aches :)
*/
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
#if OGRE_WCHAR_T_STRINGS
typedef std::wstring _StringBase;
#else
typedef std::string _StringBase;
#endif
typedef _StringBase String;
// Useful threading defines
#define OGRE_AUTO_MUTEX_NAME mutex
#if OGRE_THREAD_SUPPORT
#define OGRE_AUTO_MUTEX mutable boost::recursive_mutex OGRE_AUTO_MUTEX_NAME;
#define OGRE_LOCK_AUTO_MUTEX boost::recursive_mutex::scoped_lock ogreAutoMutexLock(OGRE_AUTO_MUTEX_NAME);
#define OGRE_MUTEX(name) mutable boost::recursive_mutex name;
#define OGRE_STATIC_MUTEX(name) static boost::recursive_mutex name;
#define OGRE_STATIC_MUTEX_INSTANCE(name) boost::recursive_mutex name;
#define OGRE_LOCK_MUTEX(name) boost::recursive_mutex::scoped_lock ogrenameLock(name);
#define OGRE_LOCK_MUTEX_NAMED(mutexName, lockName) boost::recursive_mutex::scoped_lock lockName(mutexName);
// like OGRE_AUTO_MUTEX but mutex held by pointer
#define OGRE_AUTO_SHARED_MUTEX mutable boost::recursive_mutex *OGRE_AUTO_MUTEX_NAME;
#define OGRE_LOCK_AUTO_SHARED_MUTEX assert(OGRE_AUTO_MUTEX_NAME); boost::recursive_mutex::scoped_lock ogreAutoMutexLock(*OGRE_AUTO_MUTEX_NAME);
#define OGRE_NEW_AUTO_SHARED_MUTEX assert(!OGRE_AUTO_MUTEX_NAME); OGRE_AUTO_MUTEX_NAME = new boost::recursive_mutex();
#define OGRE_DELETE_AUTO_SHARED_MUTEX assert(OGRE_AUTO_MUTEX_NAME); delete OGRE_AUTO_MUTEX_NAME;
#define OGRE_COPY_AUTO_SHARED_MUTEX(from) assert(!OGRE_AUTO_MUTEX_NAME); OGRE_AUTO_MUTEX_NAME = from;
#define OGRE_SET_AUTO_SHARED_MUTEX_NULL OGRE_AUTO_MUTEX_NAME = 0;
#define OGRE_MUTEX_CONDITIONAL(mutex) if (mutex)
#define OGRE_THREAD_SYNCHRONISER(sync) boost::condition sync;
#define OGRE_THREAD_WAIT(sync, lock) sync.wait(lock);
#define OGRE_THREAD_NOTIFY_ONE(sync) sync.notify_one();
#define OGRE_THREAD_NOTIFY_ALL(sync) sync.notify_all();
// Thread-local pointer
#define OGRE_THREAD_POINTER(T, var) boost::thread_specific_ptr<T> var
#define OGRE_THREAD_POINTER_SET(var, expr) var.reset(expr)
#define OGRE_THREAD_POINTER_DELETE(var) var.reset(0)
#define OGRE_THREAD_POINTER_GET(var) var.get()
#else
#define OGRE_AUTO_MUTEX
#define OGRE_LOCK_AUTO_MUTEX
#define OGRE_MUTEX(name)
#define OGRE_STATIC_MUTEX(name)
#define OGRE_STATIC_MUTEX_INSTANCE(name)
#define OGRE_LOCK_MUTEX(name)
#define OGRE_LOCK_MUTEX_NAMED(mutexName, lockName)
#define OGRE_AUTO_SHARED_MUTEX
#define OGRE_LOCK_AUTO_SHARED_MUTEX
#define OGRE_NEW_AUTO_SHARED_MUTEX
#define OGRE_DELETE_AUTO_SHARED_MUTEX
#define OGRE_COPY_AUTO_SHARED_MUTEX(from)
#define OGRE_SET_AUTO_SHARED_MUTEX_NULL
#define OGRE_MUTEX_CONDITIONAL(name) if(true)
#define OGRE_THREAD_SYNCHRONISER(sync)
#define OGRE_THREAD_WAIT(sync, lock)
#define OGRE_THREAD_NOTIFY_ONE(sync)
#define OGRE_THREAD_NOTIFY_ALL(sync)
#define OGRE_THREAD_POINTER(T, var) T* var
#define OGRE_THREAD_POINTER_SET(var, expr) var = expr
#define OGRE_THREAD_POINTER_DELETE(var) OGRE_DELETE var; var = 0
#define OGRE_THREAD_POINTER_GET(var) var
#endif
// Pre-declare classes
// Allows use of pointers in header files without including individual .h
// so decreases dependencies between files
class Angle;
class Animation;
class AnimationState;
class AnimationStateSet;
class AnimationTrack;
class Archive;
class ArchiveFactory;
class ArchiveManager;
class AutoParamDataSource;
class AxisAlignedBox;
class AxisAlignedBoxSceneQuery;
class Billboard;
class BillboardChain;
class BillboardSet;
class Bone;
class Camera;
class Codec;
class ColourValue;
class ConfigDialog;
template <typename T> class Controller;
template <typename T> class ControllerFunction;
class ControllerManager;
template <typename T> class ControllerValue;
class Degree;
class DynLib;
class DynLibManager;
class EdgeData;
class EdgeListBuilder;
class Entity;
class ErrorDialog;
class ExternalTextureSourceManager;
class Factory;
class Font;
class FontPtr;
class FontManager;
struct FrameEvent;
class FrameListener;
class Frustum;
class GpuProgram;
class GpuProgramPtr;
class GpuProgramManager;
class GpuProgramUsage;
class HardwareIndexBuffer;
class HardwareOcclusionQuery;
class HardwareVertexBuffer;
class HardwarePixelBuffer;
class HardwarePixelBufferSharedPtr;
class HighLevelGpuProgram;
class HighLevelGpuProgramPtr;
class HighLevelGpuProgramManager;
class HighLevelGpuProgramFactory;
class IndexData;
class IntersectionSceneQuery;
class IntersectionSceneQueryListener;
class Image;
class KeyFrame;
class Light;
class Log;
class LogManager;
class ManualResourceLoader;
class ManualObject;
class Material;
class MaterialPtr;
class MaterialManager;
class Math;
class Matrix3;
class Matrix4;
class MemoryManager;
class Mesh;
class MeshPtr;
class MeshSerializer;
class MeshSerializerImpl;
class MeshManager;
class MovableObject;
class MovablePlane;
class Node;
class NodeAnimationTrack;
class NodeKeyFrame;
class NumericAnimationTrack;
class NumericKeyFrame;
class Overlay;
class OverlayContainer;
class OverlayElement;
class OverlayElementFactory;
class OverlayManager;
class Particle;
class ParticleAffector;
class ParticleAffectorFactory;
class ParticleEmitter;
class ParticleEmitterFactory;
class ParticleSystem;
class ParticleSystemManager;
class ParticleSystemRenderer;
class ParticleSystemRendererFactory;
class ParticleVisualData;
class Pass;
class PatchMesh;
class PixelBox;
class Plane;
class PlaneBoundedVolume;
class Plugin;
class Pose;
class ProgressiveMesh;
class Profile;
class Profiler;
class Quaternion;
class Radian;
class Ray;
class RaySceneQuery;
class RaySceneQueryListener;
class Renderable;
class RenderPriorityGroup;
class RenderQueue;
class RenderQueueGroup;
class RenderQueueInvocation;
class RenderQueueInvocationSequence;
class RenderQueueListener;
class RenderSystem;
class RenderSystemCapabilities;
class RenderSystemCapabilitiesManager;
class RenderSystemCapabilitiesSerializer;
class RenderTarget;
class RenderTargetListener;
class RenderTexture;
class MultiRenderTarget;
class RenderWindow;
class RenderOperation;
class Resource;
class ResourceBackgroundQueue;
class ResourceGroupManager;
class ResourceManager;
class RibbonTrail;
class Root;
class SceneManager;
class SceneManagerEnumerator;
class SceneNode;
class SceneQuery;
class SceneQueryListener;
class ScriptCompiler;
class ScriptCompilerManager;
class ScriptLoader;
class Serializer;
class ShadowCaster;
class ShadowRenderable;
class ShadowTextureManager;
class SimpleRenderable;
class SimpleSpline;
class Skeleton;
class SkeletonPtr;
class SkeletonInstance;
class SkeletonManager;
class Sphere;
class SphereSceneQuery;
class StaticGeometry;
class StringConverter;
class StringInterface;
class SubEntity;
class SubMesh;
class TagPoint;
class Technique;
class TempBlendedBufferInfo;
class ExternalTextureSource;
class TextureUnitState;
class Texture;
class TexturePtr;
class TextureManager;
class TransformKeyFrame;
class Timer;
class UserDefinedObject;
class Vector2;
class Vector3;
class Vector4;
class Viewport;
class VertexAnimationTrack;
class VertexBufferBinding;
class VertexData;
class VertexDeclaration;
class VertexMorphKeyFrame;
class WireBoundingBox;
class Compositor;
class CompositorManager;
class CompositorChain;
class CompositorInstance;
class CompositionTechnique;
class CompositionPass;
class CompositionTargetPass;
}
/* Include all the standard header *after* all the configuration
settings have been made.
*/
#include "OgreStdHeaders.h"
#include "OgreMemoryAllocatorConfig.h"
#endif // __OgrePrerequisites_H__
| [
"drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522"
] | [
[
[
1,
417
]
]
] |
18e20c6f1968152ac6056506c2d44a76ff01bcf8 | 453607cc50d8e248e83472e81e8254c5d6997f64 | /packet/include/haar.h | 260de4dfb22fffc9e96c57e2bdd5f6cd1ddaf2d8 | [] | no_license | wbooze/test | 9242ba09b65547d422defec34405b843b289053f | 29e20eae9f1c1900bf4bb2433af43c351b9c531e | refs/heads/master | 2016-09-05T11:23:41.471171 | 2011-02-10T10:08:59 | 2011-02-10T10:08:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,508 | h |
#ifndef _HAAR_H_
#define _HAAR_H_
#include <math.h>
#include "liftbase.h"
/** \file
The documentation in this file is formatted for doxygen
(see www.doxygen.org).
<h4>
Copyright and Use
</h4>
<p>
You may use this source code without limitation and without
fee as long as you include:
</p>
<blockquote>
This software was written and is copyrighted by Ian Kaplan, Bear
Products International, www.bearcave.com, 2002.
</blockquote>
<p>
This software is provided "as is", without any warranty or
claim as to its usefulness. Anyone who uses this source code
uses it at their own risk. Nor is any support provided by
Ian Kaplan and Bear Products International.
<p>
Please send any bug fixes or suggested source changes to:
<pre>
[email protected]
</pre>
@author Ian Kaplan
*/
/**
Haar (flat line) wavelet.
As with all Lifting scheme wavelet transform functions, the
first stage of a transform step is the split stage. The
split step moves the even element to the first half of an
N element region and the odd elements to the second half of the N
element region.
The Lifting Scheme version of the Haar transform uses a wavelet
function (predict stage) that "predicts" that an odd element will
have the same value as it preceeding even element. Stated another
way, the odd element is "predicted" to be on a flat (zero slope
line) shared with the even point. The difference between this
"prediction" and the actual odd value replaces the odd element.
The wavelet scaling function (a.k.a. smoothing function) used
in the update stage calculates the average between an even and
an odd element.
The merge stage at the end of the inverse transform interleaves
odd and even elements from the two halves of the array
(e.g., ordering them even<sub>0</sub>, odd<sub>0</sub>,
even<sub>1</sub>, odd<sub>1</sub>, ...)
This is a template version of the Haar wavelet. The template must
be instantiated with an array or an object that acts like an array.
Objects that act like arrays define the left hand side and right
hand side index operators: [].
See www.bearcave.com for more information on wavelets and the
wavelet lifting scheme.
\author Ian Kaplan
*/
template <class T>
class haar : public liftbase<T, double> {
public:
/**
Haar predict step
*/
void predict( T& vec, int N, transDirection direction )
{
int half = N >> 1;
for (int i = 0; i < half; i++) {
double predictVal = vec[i];
int j = i + half;
if (direction == forward) {
vec[j] = vec[j] - predictVal;
}
else if (direction == inverse) {
vec[j] = vec[j] + predictVal;
}
else {
printf("haar::predict: bad direction value\n");
}
}
}
/**
Update step of the Haar wavelet transform.
The wavelet transform calculates a set of detail or
difference coefficients in the predict step. These
are stored in the upper half of the array. The update step
calculates an average from the even-odd element pairs.
The averages will replace the even elements in the
lower half of the array.
The Haar wavelet calculation used in the Lifting Scheme
is
<pre>
d<sub>j+1, i</sub> = odd<sub>j+1, i</sub> = odd<sub>j, i</sub> - even<sub>j, i</sub>
a<sub>j+1, i</sub> = even<sub>j, i</sub> = (even<sub>j, i</sub> + odd<sub>j, i</sub>)/2
</pre>
Note that the Lifting Scheme uses an in-place algorithm. The odd
elements have been replaced by the detail coefficients in the
predict step. With a little algebra we can substitute the
coefficient calculation into the average calculation, which
gives us
<pre>
a<sub>j+1, i</sub> = even<sub>j, i</sub> = even<sub>j, i</sub> + (odd<sub>j, i</sub>/2)
</pre>
*/
void update( T& vec, int N, transDirection direction )
{
int half = N >> 1;
for (int i = 0; i < half; i++) {
int j = i + half;
double updateVal = vec[j] / 2.0;
if (direction == forward) {
vec[i] = vec[i] + updateVal;
}
else if (direction == inverse) {
vec[i] = vec[i] - updateVal;
}
else {
printf("update: bad direction value\n");
}
}
}
/**
The normalization step assures that each step of the wavelet
transform has the constant "energy" where energy is defined as
<pre>
double energy = 0.0;
for (int n = 0; n < N; n++) {
energy = energy + (a[i] * a[i]);
}
</pre>
See 5.2.1 of <i>Ripples in Mathematics</i> by Jensen
and la Cour-Harbo
The most common implementation of the Haar transform leaves out
the normalization step, since it does not make much of a
difference in many cases. However, in the case of the wavelet
packet transform, many of the cost functions are squares, so
normalization produces smaller wavelet values (although the
scaling function values are larger). This may lead to a better
wavelet packet result (e.g., a few large values and lots of small
values).
Normalization does have the disadvantage of destroying the
averaging property of the Haar wavelet algorithm. That is, the
final scaling factor is no longer the mean of the time series.
*/
void normalize( T& vec, int N, transDirection direction )
{
const double sqrt2 = sqrt( 2.0 );
int half = N >> 1;
for (int i = 0; i < half; i++) {
int j = i + half;
if (direction == forward) {
vec[i] = sqrt2 * vec[i];
vec[j] = vec[j]/sqrt2;
}
else if (direction == inverse) {
vec[i] = vec[i]/sqrt2;
vec[j] = sqrt2 * vec[j];
}
else {
printf("normalize: bad direction value\n");
}
} // for
} // normalize
/**
One inverse wavelet transform step, with normalization
*/
void inverseStep( T& vec, const int n )
{
normalize( vec, n, inverse );
update( vec, n, inverse );
predict( vec, n, inverse );
merge( vec, n );
} // inverseStep
/**
One step in the forward wavelet transform, with normalization
*/
void forwardStep( T& vec, const int n )
{
split( vec, n );
predict( vec, n, forward );
update( vec, n, forward );
normalize( vec, n, forward );
} // forwardStep
}; // haar
#endif
| [
"[email protected]"
] | [
[
[
1,
229
]
]
] |
2d63c134c3828b305aae7bd1375af4045f1a8174 | b03c23324d8f048840ecf50875b05835dedc8566 | /engin3d/src/Window/Window.h | cd2453cfd5d4a3975ba009e1749c2af9a5a64a57 | [] | no_license | carlixyz/engin3d | 901dc61adda54e6098a3ac6637029efd28dd768e | f0b671b1e75a02eb58a2c200268e539154cd2349 | refs/heads/master | 2018-01-08T16:49:50.439617 | 2011-06-16T00:13:26 | 2011-06-16T00:13:26 | 36,534,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | h | #ifndef CWIN_H
#define CWIN_H
#ifdef _WIN32
#include <windows.h>
#endif
#include "../Utility/Singleton.h"
#include "ApplicationProperties.h"
class cWindow : public cSingleton<cWindow>
{
private:
friend class cSingleton<cWindow>;
HINSTANCE mInstance;
HWND mWnd;
HDC mDC;
cApplicationProperties mProperties;
bool mbCloseApplication;
static LRESULT CALLBACK WndProc( HWND lWnd, UINT lMsg, WPARAM lWParam, LPARAM lLParam);
public:
//Method to initialize the Window
bool Init(cApplicationProperties &lProperties);
// Method to update the window
void Update();
//Method to deinitialize the window
bool Deinit();
//Method to get the width
inline unsigned GetWidth() { return mProperties.muiWidth; }
//Method to get the height
inline unsigned GetHeight() { return mProperties.muiHeight; }
//Method to get the bpp
inline unsigned GetBpp() { return mProperties.muiBits; }
//Get DC
inline HDC &GetHDC() { return mDC; }
inline bool GetCloseApplication() { return mbCloseApplication; }
inline HWND GetHWND() { return mWnd; }
protected:
cWindow() {;}
};
#endif | [
"[email protected]",
"manolopm@8d52fbf8-9d52-835b-178e-190adb01ab0c"
] | [
[
[
1,
30
],
[
43,
50
]
],
[
[
31,
42
]
]
] |
967bd7196918c45f84e6a3c569e86bb0810c3145 | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /demo/demo_hatching/HatchingApp.h | 1edc7f8d1a05f968c16ea85172e2a37f8e19ea16 | [] | 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 | 688 | h | /*!
* \file HatchingApp.h
* \date 11-2-2010 20:11:14
*
*
* \author zjhlogo ([email protected])
*/
#ifndef __HATCHINGAPP_H__
#define __HATCHINGAPP_H__
#include "../common/BaseApp.h"
#include <OECore/IOEModel.h>
#include <libOEMsg/OEMsgShaderParam.h>
class CHatchingApp : public CBaseApp
{
public:
CHatchingApp();
virtual ~CHatchingApp();
virtual bool UserDataInit();
virtual void UserDataTerm();
virtual void Update(float fDetailTime);
private:
void Init();
void Destroy();
bool OnSetupShaderParam(COEMsgShaderParam& msg);
private:
IOEModel* m_pModel;
CVector3 m_vLightPos;
float m_bTimeStop;
};
#endif // __HATCHINGAPP_H__
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
] | [
[
[
1,
38
]
]
] |
ccce9f359ff8d8e6ab084ced65fc49274f523280 | b822313f0e48cf146b4ebc6e4548b9ad9da9a78e | /KylinSdk/Standard/Source/CCRC32.cpp | 670b4ec3778eae9a48ba34d6e2fd9942ce20acf0 | [] | no_license | dzw/kylin001v | 5cca7318301931bbb9ede9a06a24a6adfe5a8d48 | 6cec2ed2e44cea42957301ec5013d264be03ea3e | refs/heads/master | 2021-01-10T12:27:26.074650 | 2011-05-30T07:11:36 | 2011-05-30T07:11:36 | 46,501,473 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,682 | cpp | #include "stdpch.h"
#include "CCRC32.H"
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CCRC32::Initialize(void)
{
memset(&this->ulTable, 0, sizeof(this->ulTable));
// 256 values representing ASCII character codes.
for(int iCodes = 0; iCodes <= 0xFF; iCodes++)
{
this->ulTable[iCodes] = this->Reflect(iCodes, 8) << 24;
for(int iPos = 0; iPos < 8; iPos++)
{
this->ulTable[iCodes] = (this->ulTable[iCodes] << 1) ^
(this->ulTable[iCodes] & (1 << 31) ? CRC32_POLYNOMIAL : 0);
}
this->ulTable[iCodes] = this->Reflect(this->ulTable[iCodes], 32);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Reflection is a requirement for the official CRC-32 standard.
// You can create CRCs without it, but they won't conform to the standard.
unsigned long CCRC32::Reflect(unsigned long ulReflect, char cChar)
{
unsigned long ulValue = 0;
// Swap bit 0 for bit 7 bit 1 For bit 6, etc....
for(int iPos = 1; iPos < (cChar + 1); iPos++)
{
if(ulReflect & 1) ulValue |= 1 << (cChar - iPos);
ulReflect >>= 1;
}
return ulValue;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned long CCRC32::FileCRC(const char *sFileName)
{
unsigned long ulCRC = 0xffffffff;
FILE *fSource = NULL;
unsigned char sBuf[CRC32BUFSZ];
int iBytesRead = 0;
if((fSource = fopen(sFileName, "rb")) == NULL)
{
return 0xffffffff;
}
do{
iBytesRead = fread(sBuf, sizeof(char), CRC32BUFSZ, fSource);
this->PartialCRC(&ulCRC, sBuf, iBytesRead);
}while(iBytesRead == CRC32BUFSZ);
fclose(fSource);
return(ulCRC ^ 0xffffffff);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned long CCRC32::FullCRC(unsigned char *sData, unsigned long ulLength)
{
unsigned long ulCRC = 0xffffffff;
this->PartialCRC(&ulCRC, sData, ulLength);
return ulCRC ^ 0xffffffff;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//For Example usage example, see FileCRC().
void CCRC32::PartialCRC(unsigned long *ulInCRC, unsigned char *sData, unsigned long ulLength)
{
while(ulLength--)
{
*ulInCRC = (*ulInCRC >> 8) ^ this->ulTable[(*ulInCRC & 0xFF) ^ *sData++];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | [
[
[
1,
88
]
]
] |
f6ed1bb24633283e4eaba6714138443659a15b2a | 71ef91a70301f475af906967630eb06b44d0ebc9 | /inc/ShaderUniformVector.h | 1cf5515ab7180df3528d680669e261f42a46071c | [] | no_license | willemfrishert/parallaxmapping | f88f5e5aaad8e78c8a985d9ddfe565042a6907ae | 8b0172f6807f52b2c66ef4ff977eef5c1d2d56a3 | refs/heads/master | 2021-01-01T18:54:53.657814 | 2006-12-21T20:37:21 | 2006-12-21T20:37:21 | 32,184,702 | 0 | 1 | null | null | null | null | ISO-8859-13 | C++ | false | false | 1,321 | h | /**
* @description Represents a uniform shader attribute
* TODO: support for matrices
*
* @file ShaderUniformVector.h
* @author Joćo Pedro Jorge
*/
#pragma once
#include "ShaderUniformObject.h"
// specifies the type of uniform variable
enum VECSIZE {VEC3 = 3, VEC4 = 4};
template <class T>
class ShaderUniformVector: public ShaderUniformObject
{
public:
ShaderUniformVector(VECSIZE size);
virtual ~ShaderUniformVector(void);
void setValues(T* values);
virtual void use() const;
// attributes
private:
T* values;
VECSIZE size;
};
template <class T>
ShaderUniformVector<T>::ShaderUniformVector(VECSIZE size)
{
this->size = size;
values = new T[ size ];
}
template <class T>
ShaderUniformVector<T>::~ShaderUniformVector(void)
{
delete values;
}
/**
* @param name the uniform attribute name
* @param value the attribute value
*/
template <class T>
void ShaderUniformVector<T>::setValues(T* values)
{
for (int i = 0; i < this->size; i++)
{
this->values[ i ] = values[ i ];
}
// NOTE: we must call the upper class and MARK the
// value as CHANGED
this->setHasChanged( true );
}
template <class T>
void ShaderUniformVector<T>::use() const
{
if ( this->getHasChanged() )
{
setUniform(this->location, this->values, this->size);
}
}
| [
"jpjorge@18efd892-9420-0410-97b9-638391ccb344"
] | [
[
[
1,
71
]
]
] |
593050f35fce57628215eaf2750b0cc8290ffa51 | 3ac8c943b13d943fbd3b92787e40aa5519460a32 | /Source/Common/Ports.cpp | 7efe30a6d37f89ac8a0a2a5a5f90ce946ca887d7 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | locosoft1986/Microkernel-1 | 8069bd2be390d6d8ad10f73e8a944112a764a401 | c9dfeec4581d4dd8b1e9020adb3778ad78b3e525 | refs/heads/master | 2021-01-24T04:54:08.589308 | 2010-09-23T19:38:01 | 2010-09-23T19:38:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | cpp | #include <Common/Ports.h>
Ports::Ports()
{
}
Ports::~Ports()
{
}
unsigned int Ports::ReadInt(unsigned short port)
{
unsigned int value;
asm volatile ("inl %1, %0" : "=a"(value) : "dN"(port));
return value;
}
unsigned short Ports::ReadShort(unsigned short port)
{
unsigned short value;
asm volatile ("inw %1, %0" : "=a"(value) : "dN"(port));
return value;
}
unsigned char Ports::ReadByte(unsigned short port)
{
unsigned char value;
asm volatile("inb %1, %0" : "=a"(value) : "Nd"(port));
return value;
}
void Ports::WriteInt(unsigned short port, unsigned int value)
{
asm volatile ("outl %1, %0" : : "dN"(port), "a"(value));
}
void Ports::WriteShort(unsigned short port, unsigned short value)
{
asm volatile ("outw %1, %0" : : "dN"(port), "a"(value));
}
void Ports::WriteByte(unsigned short port, unsigned char value)
{
asm volatile ("outb %1, %0" : : "dN"(port), "a"(value));
}
| [
"[email protected]"
] | [
[
[
1,
48
]
]
] |
1ea97a43a961a9947fd629c14319686a22a6e602 | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/stack_trace.h | 4b9b2106694e4f877cadf1a882b7376fdd3c6c32 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | 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 | 3,973 | h | // Copyright (C) 2008 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_STACK_TRACe_
#define DLIB_STACK_TRACe_
/*!
This file defines 3 things. Two of them are preprocessor macros that
enable you to tag functions with the dlib stack trace watcher. The
third thing is a function named get_stack_trace() which returns the
current stack trace in std::string form.
To enable the stack trace you must #define DLIB_ENABLE_STACK_TRACE.
When this #define isn't set then the 3 things described above
still exist but they don't do anything.
Also note that when the stack trace is enabled it changes the DLIB_ASSERT
and DLIB_CASSERT macros so that they print stack traces when
an assert fails.
See the following example program for details:
#include <iostream>
#include <dlib/stack_trace.h>
void funct2()
{
// put this macro at the top of each function you would
// like to appear in stack traces
DLIB_STACK_TRACE;
// you may print the current stack trace as follows.
std::cout << dlib::get_stack_trace() << endl;
}
void funct()
{
// This alternate form of DLIB_STACK_TRACE allows you to specify
// the string used to name the current function. The other form
// will usually output an appropriate function name automatically
// so this may not be needed.
DLIB_STACK_TRACE_NAMED("funct");
funct2();
}
int main()
{
funct();
}
!*/
#include <string>
#include "assert.h"
// only setup the stack trace stuff if the asserts are enabled (which happens in debug mode
// basically). Also, this stuff doesn't work if you use NO_MAKEFILE
#if defined(DLIB_ENABLE_STACK_TRACE)
#ifdef NO_MAKEFILE
#error "You can't use the dlib stack trace stuff and NO_MAKEFILE at the same time"
#endif
namespace dlib
{
const std::string get_stack_trace();
}
// redefine the DLIB_CASSERT macro to include the stack trace
#undef DLIB_CASSERT
#define DLIB_CASSERT(_exp,_message) \
{if ( !(_exp) ) \
{ \
std::ostringstream dlib__out; \
dlib__out << "\n\nError occurred at line " << __LINE__ << ".\n"; \
dlib__out << "Error occurred in file " << __FILE__ << ".\n"; \
dlib__out << "Error occurred in function " << DLIB_FUNCTION_NAME << ".\n\n"; \
dlib__out << "Failing expression was " << #_exp << ".\n"; \
dlib__out << _message << "\n\n"; \
dlib__out << "Stack Trace: \n" << dlib::get_stack_trace() << "\n"; \
dlib_assert_breakpoint(); \
throw dlib::fatal_error(dlib::EBROKEN_ASSERT,dlib__out.str()); \
}}
namespace dlib
{
class stack_tracer
{
public:
stack_tracer (
const char* funct_name,
const char* file_name,
const int line_number
);
~stack_tracer();
};
}
#define DLIB_STACK_TRACE_NAMED(x) dlib::stack_tracer dlib_stack_tracer_object(x,__FILE__,__LINE__)
#define DLIB_STACK_TRACE dlib::stack_tracer dlib_stack_tracer_object(DLIB_FUNCTION_NAME,__FILE__,__LINE__)
#else // don't do anything if ENABLE_ASSERTS isn't defined
#define DLIB_STACK_TRACE_NAMED(x)
#define DLIB_STACK_TRACE
namespace dlib
{
inline const std::string get_stack_trace() { return std::string("stack trace not enabled");}
}
#endif
#endif // DLIB_STACK_TRACe_
| [
"jimmy@DGJ3X3B1.(none)"
] | [
[
[
1,
118
]
]
] |
14044981286507494b336ccd6d987269a5f7fbab | 8a8873b129313b24341e8fa88a49052e09c3fa51 | /inc/HandleInSearch.h | 5cf8ad52a376dfcf7862ebd56184b1e9e4505765 | [] | no_license | flaithbheartaigh/wapbrowser | ba09f7aa981d65df810dba2156a3f153df071dcf | b0d93ce8517916d23104be608548e93740bace4e | refs/heads/master | 2021-01-10T11:29:49.555342 | 2010-03-08T09:36:03 | 2010-03-08T09:36:03 | 50,261,329 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | h | /*
============================================================================
Name : HandleInSearch.h
Author :
Version :
Copyright : Your copyright notice
Description : CHandleInSearch declaration
============================================================================
*/
#ifndef HANDLEINSEARCH_H
#define HANDLEINSEARCH_H
// INCLUDES
#include <e32std.h>
#include <e32base.h>
#include <BADESCA.H>
#include "HttpObserver.h"
// CLASS DECLARATION
class CMainEngine;
class MHandleEventObserver;
class CHttpManager;
class CSearchResultTempItem;
/**
* CHandleInSearch
*
*/
class CHandleInSearch :public CBase,public MOperationObserver
{
public: // Constructors and destructor
~CHandleInSearch();
static CHandleInSearch* NewL(MHandleEventObserver& aObserver,CMainEngine& aMainEngine);
static CHandleInSearch* NewLC(MHandleEventObserver& aObserver,CMainEngine& aMainEngine);
private:
CHandleInSearch(MHandleEventObserver& aObserver,CMainEngine& aMainEngine);
void ConstructL();
public://From MOperationObserver
virtual void OperationEvent(TInt aEventType,const TDesC& aEventData,TInt aType=0);
public:
TInt GetCount();
const TDesC& GetOneItem(TInt aIndex);
TInt GetCurPage();
TInt GetAllPage();
const TDesC& GetInfo();
void SendRequest(const TDesC8& aKeyWord,TInt aIndex,TInt aPage);
void CancelSendRequest();
const TDesC8& GetSendUrl();
void SetSendUrl(const TDesC8& aUrl);
private:
void ClearTempBuf();
TBool CheckTempBuf(TInt aPage);
void HandleXmlData();
private:
RPointerArray<CSearchResultTempItem> iPointArray;
MHandleEventObserver& iObserver;
CMainEngine& iMainEngine;
CHttpManager& iHttpManager;
HBufC* iBuf;
HBufC8* iKeyWord;
HBufC8* iUrl;
HBufC8* iCurUrl;
TFileName iFileName;
TInt iCurPage;
TInt iAllPage;
TInt iCurIndex;
TBool iContentError;
};
#endif // HANDLEINSEARCH_H
| [
"sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f"
] | [
[
[
1,
87
]
]
] |
75eb1f740ed237b0ea71a23f8cbd33ae0dbd1e28 | ba4b61e8f5f04982943cc8135ee07eb866c21ef3 | /src/HeeksPython.cpp | 0c286ca8820b9ad78aadf4576bfd3b013488a031 | [] | no_license | xethm55/heekspython | c86f91637846b5f12589935545fe40e32ff341dc | aa46dde26b53be6948beaf2e5e5242b17f94624c | refs/heads/master | 2021-01-21T01:38:52.592857 | 2011-04-03T07:27:19 | 2011-04-03T07:27:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,760 | cpp | // HeeksPython.cpp
/*
* Copyright (c) 2009, Dan Heeks
* This program is released under the BSD license. See the file COPYING for
* details.
*/
#include "stdafx.h"
#include <wx/stdpaths.h>
#include <wx/dynlib.h>
#include <wx/aui/aui.h>
#include "interface/PropertyString.h"
#include "interface/Observer.h"
#include "ConsoleCanvas.h"
#include "PythonConfig.h"
#ifdef _DEBUG
#undef _DEBUG
#include <Python.h>
#include <wx/wxPython/wxPython.h>
#define _DEBUG
#else
#include <Python.h>
#include <wx/wxPython/wxPython.h>
#endif
CHeeksCADInterface* heeksCAD = NULL;
CHeeksPythonApp theApp;
CHeeksPythonApp::CHeeksPythonApp(){
m_console = NULL;
}
CHeeksPythonApp::~CHeeksPythonApp(){
}
void CHeeksPythonApp::OnInitDLL()
{
}
void CHeeksPythonApp::OnDestroyDLL()
{
#if !defined WXUSINGDLL
wxUninitialize();
#endif
heeksCAD = NULL;
}
void OnConsole( wxCommandEvent& event )
{
wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
wxAuiPaneInfo& pane_info = aui_manager->GetPane(theApp.m_console);
if(pane_info.IsOk()){
pane_info.Show(event.IsChecked());
aui_manager->Update();
}
}
void OnUpdateConsole( wxUpdateUIEvent& event )
{
wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
event.Check(aui_manager->GetPane(theApp.m_console).IsShown());
}
void RunAutoExecPyFile()
{
#if 0
// As always, first grab the GIL
wxPyBlock_t blocked = wxPyBeginBlockThreads();
// Now make a dictionary to serve as the global namespace when the code is
// executed. Put a reference to the builtins module in it. (Yes, the
// names are supposed to be different, I don't know why...)
PyObject* globals = PyDict_New();
PyObject* builtins = PyImport_ImportModule("__builtin__");
PyDict_SetItemString(globals, "__builtins__", builtins);
Py_DECREF(builtins);
// Execute the code "import autoexec"
PyObject* result = PyRun_String("import autoexec", Py_file_input, globals, globals);
// Release the python objects we still have
if (result)Py_DECREF(result);
else PyErr_Print();
Py_DECREF(globals);
// Finally, after all Python stuff is done, release the GIL
wxPyEndBlockThreads(blocked);
#else
PyEval_RestoreThread(theApp.m_console->m_mainTState);
PyObject* result = PyImport_ImportModule("autoexec");
// Release the python objects we still have
if (result)Py_DECREF(result);
else PyErr_Print();
PyEval_SaveThread();
#endif
}
void CHeeksPythonApp::OnStartUp(CHeeksCADInterface* h, const wxString& dll_path)
{
m_dll_path = dll_path;
heeksCAD = h;
#if !defined WXUSINGDLL
wxInitialize();
#endif
// add menus and toolbars
wxFrame* frame = heeksCAD->GetMainFrame();
wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
// add the console canvas
m_console = new CConsoleCanvas(frame);
m_console->InitP();
aui_manager->AddPane(m_console, wxAuiPaneInfo().Name(_T("Console")).Caption(_T("Console")).Bottom().BestSize(wxSize(600, 200)));
bool console_visible;
PythonConfig config;
config.Read(_T("ConsoleVisible"), &console_visible);
aui_manager->GetPane(m_console).Show(console_visible);
// add tick boxes for them all on the view menu
wxMenu* view_menu = heeksCAD->GetWindowMenu();
heeksCAD->AddMenuItem(view_menu, _T("Console"), wxBitmap(), OnConsole, OnUpdateConsole,0,true);
heeksCAD->RegisterHideableWindow(m_console);
// run autoexec.py
RunAutoExecPyFile();
heeksCAD->SetDefaultLayout(wxString(_T("layout2|name=ToolBar;caption=General Tools;state=2108156;dir=1;layer=10;row=0;pos=0;prop=100000;bestw=279;besth=31;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=GeomBar;caption=Geometry Tools;state=2108156;dir=1;layer=10;row=0;pos=290;prop=100000;bestw=248;besth=31;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=SolidBar;caption=Solid Tools;state=2108156;dir=1;layer=10;row=1;pos=0;prop=100000;bestw=341;besth=31;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=970;floaty=297;floatw=296;floath=57|name=ViewingBar;caption=Viewing Tools;state=2108156;dir=1;layer=10;row=1;pos=352;prop=100000;bestw=248;besth=31;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=TransformBar;caption=Transformation Tools;state=2108156;dir=1;layer=10;row=1;pos=611;prop=100000;bestw=217;besth=31;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=Graphics;caption=Graphics;state=768;dir=5;layer=0;row=0;pos=0;prop=100000;bestw=800;besth=600;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=Objects;caption=Objects;state=2099196;dir=4;layer=1;row=0;pos=0;prop=100000;bestw=300;besth=400;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=Options;caption=Options;state=2099196;dir=4;layer=1;row=0;pos=1;prop=100000;bestw=300;besth=200;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=Input;caption=Input;state=2099196;dir=4;layer=1;row=0;pos=2;prop=100000;bestw=300;besth=200;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=Properties;caption=Properties;state=2099196;dir=4;layer=1;row=0;pos=3;prop=100000;bestw=300;besth=200;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=MachiningBar;caption=Machining tools;state=2108156;dir=1;layer=10;row=0;pos=549;prop=100000;bestw=279;besth=31;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=Program;caption=Program;state=2099196;dir=3;layer=0;row=0;pos=0;prop=100000;bestw=600;besth=200;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|name=Output;caption=Output;state=2099196;dir=3;layer=0;row=0;pos=1;prop=100000;bestw=600;besth=200;minw=-1;minh=-1;maxw=-1;maxh=-1;floatx=-1;floaty=-1;floatw=-1;floath=-1|dock_size(5,0,0)=504|dock_size(4,1,0)=234|dock_size(1,10,0)=33|dock_size(1,10,1)=33|dock_size(3,0,0)=219|")));
}
void CHeeksPythonApp::OnNewOrOpen(bool open, int res)
{
}
void CHeeksPythonApp::GetOptions(std::list<Property *> *list){
}
void CHeeksPythonApp::OnFrameDelete()
{
wxAuiManager* aui_manager = heeksCAD->GetAuiManager();
PythonConfig config;
config.Write(_T("ConsoleVisible"), aui_manager->GetPane(m_console).IsShown());
}
wxString CHeeksPythonApp::GetDllFolder()
{
return m_dll_path;
}
wxString CHeeksPythonApp::GetResFolder()
{
#if defined(WIN32) || defined(RUNINPLACE) //compile with 'RUNINPLACE=yes make' then skip 'sudo make install'
return m_dll_path;
#else
return (m_dll_path + _T("/../../share/heekscad"));
#endif
}
bool MyApp::OnInit(void)
{
return true;
}
IMPLEMENT_APP(MyApp)
| [
"danheeks@ae8bab52-3526-11de-9d05-31133e6853b1",
"jonpry@ae8bab52-3526-11de-9d05-31133e6853b1"
] | [
[
[
1,
1
],
[
13,
14
],
[
18,
28
],
[
31,
31
],
[
57,
57
],
[
67,
67
],
[
70,
104
],
[
136,
137
],
[
142,
143
],
[
165,
165
],
[
168,
168
],
[
170,
170
],
[
181,
181
]
],
[
[
2,
12
],
[
15,
17
],
[
29,
30
],
[
32,
56
],
[
58,
66
],
[
68,
69
],
[
105,
135
],
[
138,
141
],
[
144,
164
],
[
166,
167
],
[
169,
169
],
[
171,
180
]
]
] |
874074d4dbe5dba8fec286de035c5ba3fd2a8b50 | 0b1a87e3aac9d80f719a34e5522796cdb061d64d | /composite.h | ec21738da449a72115c2904e1d67df3c1a70dcbb | [] | no_license | xiangruipuzhao/qaac | 6769239471d920d42095a916c94ab0e706a76619 | ed2a1392a3c6c9df2046bd559b6486965928af53 | refs/heads/master | 2021-01-21T01:39:23.237184 | 2011-02-05T14:01:10 | 2011-02-05T14:01:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,543 | h | #ifndef _COMPOSITE_H
#define _COMPOSITE_H
#include <boost/shared_ptr.hpp>
#include "iointer.h"
class CompositeSource: public ISource {
typedef boost::shared_ptr<ISource> source_t;
std::vector<source_t> m_sources;
SampleFormat m_format;
size_t m_curpos;
public:
CompositeSource() : m_curpos(0) {}
const std::vector<uint32_t> *getChannelMap() const { return 0; }
const SampleFormat &getSampleFormat() const { return m_format; }
// takes ownership.
void addSource(ISource *src)
{
if (!m_sources.size())
m_format = src->getSampleFormat();
else if (m_format != src->getSampleFormat())
throw std::runtime_error(
"CompositeSource: can't compose different sample format");
m_sources.push_back(source_t(src));
}
uint64_t length() const
{
uint64_t len = 0;
for (size_t i = 0; i < m_sources.size(); ++i)
len += m_sources[i]->length();
return len;
}
size_t readSamples(void *buffer, size_t nsamples)
{
if (m_curpos == m_sources.size())
return 0;
size_t rc = m_sources[m_curpos]->readSamples(buffer, nsamples);
if (rc == nsamples)
return rc;
if (rc == 0) {
++m_curpos;
return readSamples(buffer, nsamples);
}
return rc + readSamples(
reinterpret_cast<char*>(buffer) + rc * m_format.bytesPerFrame(),
nsamples - rc);
}
void setRange(int64_t start=0, int64_t length=-1)
{
throw std::runtime_error("CompositeSource::setRange: not implemented");
}
};
#endif
| [
"[email protected]"
] | [
[
[
1,
55
]
]
] |
885238f83c9252ff84074c561bac1f264e048612 | 02c2e62bcb9a54738bfbd95693978b8709e88fdb | /opencv/cxmean.cpp | 14462e4a7694bd0991784ef231c92ddeed21b8c7 | [] | 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 | 19,621 | 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 "_cxcore.h"
#include <float.h>
/****************************************************************************************\
* Mean value over the region *
\****************************************************************************************/
#define ICV_MEAN_CASE_C1( len ) \
for( ; x <= (len) - 2; x += 2 ) \
{ \
if( mask[x] ) \
s0 += src[x], pix++; \
if( mask[x+1] ) \
s0 += src[x+1], pix++; \
} \
\
for( ; x < (len); x++ ) \
if( mask[x] ) \
s0 += src[x], pix++
#define ICV_MEAN_CASE_C2( len ) \
for( ; x < (len); x++ ) \
if( mask[x] ) \
{ \
s0 += src[x*2]; \
s1 += src[x*2+1]; \
pix++; \
}
#define ICV_MEAN_CASE_C3( len ) \
for( ; x < (len); x++ ) \
if( mask[x] ) \
{ \
s0 += src[x*3]; \
s1 += src[x*3+1]; \
s2 += src[x*3+2]; \
pix++; \
}
#define ICV_MEAN_CASE_C4( len ) \
for( ; x < (len); x++ ) \
if( mask[x] ) \
{ \
s0 += src[x*4]; \
s1 += src[x*4+1]; \
s2 += src[x*4+2]; \
s3 += src[x*4+3]; \
pix++; \
}
#define ICV_MEAN_COI_CASE( len, cn ) \
for( ; x <= (len) - 2; x += 2 ) \
{ \
if( mask[x] ) \
s0 += src[x*(cn)], pix++; \
if( mask[x+1] ) \
s0+=src[(x+1)*(cn)], pix++; \
} \
\
for( ; x < (len); x++ ) \
if( mask[x] ) \
s0 += src[x*(cn)], pix++;
////////////////////////////////////// entry macros //////////////////////////////////////
#define ICV_MEAN_ENTRY_COMMON() \
int pix = 0; \
step /= sizeof(src[0])
#define ICV_MEAN_ENTRY_C1( sumtype ) \
sumtype s0 = 0; \
ICV_MEAN_ENTRY_COMMON()
#define ICV_MEAN_ENTRY_C2( sumtype ) \
sumtype s0 = 0, s1 = 0; \
ICV_MEAN_ENTRY_COMMON()
#define ICV_MEAN_ENTRY_C3( sumtype ) \
sumtype s0 = 0, s1 = 0, s2 = 0; \
ICV_MEAN_ENTRY_COMMON()
#define ICV_MEAN_ENTRY_C4( sumtype ) \
sumtype s0 = 0, s1 = 0, s2 = 0, s3 = 0; \
ICV_MEAN_ENTRY_COMMON()
#define ICV_MEAN_ENTRY_BLOCK_COMMON( block_size ) \
int remaining = block_size; \
ICV_MEAN_ENTRY_COMMON()
#define ICV_MEAN_ENTRY_BLOCK_C1( sumtype, worktype, block_size )\
sumtype sum0 = 0; \
worktype s0 = 0; \
ICV_MEAN_ENTRY_BLOCK_COMMON( block_size )
#define ICV_MEAN_ENTRY_BLOCK_C2( sumtype, worktype, block_size )\
sumtype sum0 = 0, sum1 = 0; \
worktype s0 = 0, s1 = 0; \
ICV_MEAN_ENTRY_BLOCK_COMMON( block_size )
#define ICV_MEAN_ENTRY_BLOCK_C3( sumtype, worktype, block_size )\
sumtype sum0 = 0, sum1 = 0, sum2 = 0; \
worktype s0 = 0, s1 = 0, s2 = 0; \
ICV_MEAN_ENTRY_BLOCK_COMMON( block_size )
#define ICV_MEAN_ENTRY_BLOCK_C4( sumtype, worktype, block_size )\
sumtype sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0; \
worktype s0 = 0, s1 = 0, s2 = 0, s3 = 0; \
ICV_MEAN_ENTRY_BLOCK_COMMON( block_size )
/////////////////////////////////////// exit macros //////////////////////////////////////
#define ICV_MEAN_EXIT_COMMON() \
double scale = pix ? 1./pix : 0
#define ICV_MEAN_EXIT_C1( tmp ) \
ICV_MEAN_EXIT_COMMON(); \
mean[0] = scale*(double)tmp##0
#define ICV_MEAN_EXIT_C2( tmp ) \
ICV_MEAN_EXIT_COMMON(); \
double t0 = scale*(double)tmp##0; \
double t1 = scale*(double)tmp##1; \
mean[0] = t0; \
mean[1] = t1
#define ICV_MEAN_EXIT_C3( tmp ) \
ICV_MEAN_EXIT_COMMON(); \
double t0 = scale*(double)tmp##0; \
double t1 = scale*(double)tmp##1; \
double t2 = scale*(double)tmp##2; \
mean[0] = t0; \
mean[1] = t1; \
mean[2] = t2
#define ICV_MEAN_EXIT_C4( tmp ) \
ICV_MEAN_EXIT_COMMON(); \
double t0 = scale*(double)tmp##0; \
double t1 = scale*(double)tmp##1; \
mean[0] = t0; \
mean[1] = t1; \
t0 = scale*(double)tmp##2; \
t1 = scale*(double)tmp##3; \
mean[2] = t0; \
mean[3] = t1
#define ICV_MEAN_EXIT_BLOCK_C1() \
sum0 += s0; \
ICV_MEAN_EXIT_C1( sum )
#define ICV_MEAN_EXIT_BLOCK_C2() \
sum0 += s0; sum1 += s1; \
ICV_MEAN_EXIT_C2( sum )
#define ICV_MEAN_EXIT_BLOCK_C3() \
sum0 += s0; sum1 += s1; \
sum2 += s2; \
ICV_MEAN_EXIT_C3( sum )
#define ICV_MEAN_EXIT_BLOCK_C4() \
sum0 += s0; sum1 += s1; \
sum2 += s2; sum3 += s3; \
ICV_MEAN_EXIT_C4( sum )
////////////////////////////////////// update macros /////////////////////////////////////
#define ICV_MEAN_UPDATE_COMMON( block_size )\
remaining = block_size
#define ICV_MEAN_UPDATE_C1( block_size ) \
ICV_MEAN_UPDATE_COMMON( block_size ); \
sum0 += s0; \
s0 = 0
#define ICV_MEAN_UPDATE_C2( block_size ) \
ICV_MEAN_UPDATE_COMMON( block_size ); \
sum0 += s0; sum1 += s1; \
s0 = s1 = 0
#define ICV_MEAN_UPDATE_C3( block_size ) \
ICV_MEAN_UPDATE_COMMON( block_size ); \
sum0 += s0; sum1 += s1; sum2 += s2; \
s0 = s1 = s2 = 0
#define ICV_MEAN_UPDATE_C4( block_size ) \
ICV_MEAN_UPDATE_COMMON( block_size ); \
sum0 += s0; sum1 += s1; \
sum2 += s2; sum3 += s3; \
s0 = s1 = s2 = s3 = 0
#define ICV_IMPL_MEAN_BLOCK_FUNC_2D( flavor, cn, \
arrtype, sumtype, worktype, block_size ) \
IPCVAPI_IMPL( CvStatus, icvMean_##flavor##_C##cn##MR, \
( const arrtype* src, int step, \
const uchar* mask, int maskstep, \
CvSize size, double* mean ), \
(src, step, mask, maskstep, size, mean)) \
{ \
ICV_MEAN_ENTRY_BLOCK_C##cn( sumtype, worktype, block_size );\
\
for( ; size.height--; src += step, mask += maskstep ) \
{ \
int x = 0; \
while( x < size.width ) \
{ \
int limit = MIN( remaining, size.width - x ); \
remaining -= limit; \
limit += x; \
ICV_MEAN_CASE_C##cn( limit ); \
if( remaining == 0 ) \
{ \
ICV_MEAN_UPDATE_C##cn( block_size ); \
} \
} \
} \
\
{ ICV_MEAN_EXIT_BLOCK_C##cn(); } \
return CV_OK; \
}
#define ICV_IMPL_MEAN_FUNC_2D( flavor, cn, \
arrtype, sumtype, worktype ) \
IPCVAPI_IMPL( CvStatus, icvMean_##flavor##_C##cn##MR, \
( const arrtype* src, int step, \
const uchar* mask, int maskstep, \
CvSize size, double* mean), \
(src, step, mask, maskstep, size, mean)) \
{ \
ICV_MEAN_ENTRY_C##cn( sumtype ); \
\
for( ; size.height--; src += step, mask += maskstep ) \
{ \
int x = 0; \
ICV_MEAN_CASE_C##cn( size.width ); \
} \
\
{ ICV_MEAN_EXIT_C##cn( s ); } \
return CV_OK; \
}
#define ICV_IMPL_MEAN_BLOCK_FUNC_2D_COI( flavor, \
arrtype, sumtype, worktype, block_size ) \
static CvStatus CV_STDCALL \
icvMean_##flavor##_CnCMR( const arrtype* src, int step, \
const uchar* mask, int maskstep, \
CvSize size, int cn, \
int coi, double* mean ) \
{ \
ICV_MEAN_ENTRY_BLOCK_C1( sumtype, worktype, block_size ); \
src += coi - 1; \
\
for( ; size.height--; src += step, mask += maskstep ) \
{ \
int x = 0; \
while( x < size.width ) \
{ \
int limit = MIN( remaining, size.width - x ); \
remaining -= limit; \
limit += x; \
ICV_MEAN_COI_CASE( limit, cn ); \
if( remaining == 0 ) \
{ \
ICV_MEAN_UPDATE_C1( block_size ); \
} \
} \
} \
\
{ ICV_MEAN_EXIT_BLOCK_C1(); } \
return CV_OK; \
}
#define ICV_IMPL_MEAN_FUNC_2D_COI( flavor, \
arrtype, sumtype, worktype ) \
static CvStatus CV_STDCALL \
icvMean_##flavor##_CnCMR( const arrtype* src, int step, \
const uchar* mask, int maskstep, \
CvSize size, int cn, \
int coi, double* mean ) \
{ \
ICV_MEAN_ENTRY_C1( sumtype ); \
src += coi - 1; \
\
for( ; size.height--; src += step, mask += maskstep ) \
{ \
int x = 0; \
ICV_MEAN_COI_CASE( size.width, cn ); \
} \
\
{ ICV_MEAN_EXIT_C1( s ); } \
return CV_OK; \
}
#define ICV_IMPL_MEAN_BLOCK_ALL( flavor, arrtype, sumtype, \
worktype, block_size ) \
ICV_IMPL_MEAN_BLOCK_FUNC_2D( flavor, 1, arrtype, sumtype, \
worktype, block_size ) \
ICV_IMPL_MEAN_BLOCK_FUNC_2D( flavor, 2, arrtype, sumtype, \
worktype, block_size ) \
ICV_IMPL_MEAN_BLOCK_FUNC_2D( flavor, 3, arrtype, sumtype, \
worktype, block_size ) \
ICV_IMPL_MEAN_BLOCK_FUNC_2D( flavor, 4, arrtype, sumtype, \
worktype, block_size ) \
ICV_IMPL_MEAN_BLOCK_FUNC_2D_COI( flavor, arrtype, sumtype, \
worktype, block_size )
#define ICV_IMPL_MEAN_ALL( flavor, arrtype, sumtype, worktype ) \
ICV_IMPL_MEAN_FUNC_2D( flavor, 1, arrtype, sumtype, worktype ) \
ICV_IMPL_MEAN_FUNC_2D( flavor, 2, arrtype, sumtype, worktype ) \
ICV_IMPL_MEAN_FUNC_2D( flavor, 3, arrtype, sumtype, worktype ) \
ICV_IMPL_MEAN_FUNC_2D( flavor, 4, arrtype, sumtype, worktype ) \
ICV_IMPL_MEAN_FUNC_2D_COI( flavor, arrtype, sumtype, worktype )
ICV_IMPL_MEAN_BLOCK_ALL( 8u, uchar, int64, unsigned, 1 << 24 )
ICV_IMPL_MEAN_BLOCK_ALL( 16u, ushort, int64, unsigned, 1 << 16 )
ICV_IMPL_MEAN_BLOCK_ALL( 16s, short, int64, int, 1 << 16 )
ICV_IMPL_MEAN_ALL( 32s, int, double, double )
ICV_IMPL_MEAN_ALL( 32f, float, double, double )
ICV_IMPL_MEAN_ALL( 64f, double, double, double )
#define icvMean_8s_C1MR 0
#define icvMean_8s_C2MR 0
#define icvMean_8s_C3MR 0
#define icvMean_8s_C4MR 0
#define icvMean_8s_CnCMR 0
CV_DEF_INIT_BIG_FUNC_TAB_2D( Mean, MR )
CV_DEF_INIT_FUNC_TAB_2D( Mean, CnCMR )
CV_IMPL CvScalar
cvAvg( const void* img, const void* maskarr )
{
CvScalar mean = {{0,0,0,0}};
static CvBigFuncTable mean_tab;
static CvFuncTable meancoi_tab;
static int inittab = 0;
CV_FUNCNAME("cvAvg");
__BEGIN__;
CvSize size;
double scale;
if( !maskarr )
{
CV_CALL( mean = cvSum(img));
size = cvGetSize( img );
size.width *= size.height;
scale = size.width ? 1./size.width : 0;
mean.val[0] *= scale;
mean.val[1] *= scale;
mean.val[2] *= scale;
mean.val[3] *= scale;
}
else
{
int type, coi = 0;
int mat_step, mask_step;
CvMat stub, maskstub, *mat = (CvMat*)img, *mask = (CvMat*)maskarr;
if( !inittab )
{
icvInitMeanMRTable( &mean_tab );
icvInitMeanCnCMRTable( &meancoi_tab );
inittab = 1;
}
if( !CV_IS_MAT(mat) )
CV_CALL( mat = cvGetMat( mat, &stub, &coi ));
if( !CV_IS_MAT(mask) )
CV_CALL( mask = cvGetMat( mask, &maskstub ));
if( !CV_IS_MASK_ARR(mask) )
CV_ERROR( CV_StsBadMask, "" );
if( !CV_ARE_SIZES_EQ( mat, mask ) )
CV_ERROR( CV_StsUnmatchedSizes, "" );
type = CV_MAT_TYPE( mat->type );
size = cvGetMatSize( mat );
mat_step = mat->step;
mask_step = mask->step;
if( CV_IS_MAT_CONT( mat->type & mask->type ))
{
size.width *= size.height;
size.height = 1;
mat_step = mask_step = CV_STUB_STEP;
}
if( CV_MAT_CN(type) == 1 || coi == 0 )
{
CvFunc2D_2A1P func = (CvFunc2D_2A1P)(mean_tab.fn_2d[type]);
if( !func )
CV_ERROR( CV_StsBadArg, cvUnsupportedFormat );
IPPI_CALL( func( mat->data.ptr, mat_step, mask->data.ptr,
mask_step, size, mean.val ));
}
else
{
CvFunc2DnC_2A1P func = (CvFunc2DnC_2A1P)(
meancoi_tab.fn_2d[CV_MAT_DEPTH(type)]);
if( !func )
CV_ERROR( CV_StsBadArg, cvUnsupportedFormat );
IPPI_CALL( func( mat->data.ptr, mat_step, mask->data.ptr,
mask_step, size, CV_MAT_CN(type), coi, mean.val ));
}
}
__END__;
return mean;
}
/* End of file */
| [
"[email protected]"
] | [
[
[
1,
476
]
]
] |
1d942ab33babd0e356b070a5ab02290a0cf62ca8 | 941e1c9c87576247aac5c28db16e2d73a2bec0af | /LogManager.cpp | 9e6d47083949a13c6395831470066d674ca51258 | [] | no_license | luochong/vc-gms-1 | 49a5ccc2edd3da74da2a7d9271352db8213324cb | 607b087e37cc0946b4562b681bb65875863bc084 | refs/heads/master | 2016-09-06T09:32:16.340313 | 2009-06-14T07:35:19 | 2009-06-14T07:35:19 | 32,432,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | cpp | // LogManager.cpp: implementation of the CLogManager class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "mygms.h"
#include "LogManager.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CLogManager::CLogManager()
{
}
CLogManager::~CLogManager()
{
}
bool CLogManager::AddLog(LPCSTR op)
{
CTime tm = CTime::GetCurrentTime();
CString strSql;
strSql.Format("INSERT INTO log (Admin_name,do_what,do_date) VALUES('%s','%s','%d-%d-%d %d:%d:%d')",
CGMSRole::Instance()->m_admin_name, op,
tm.GetYear(), tm.GetMonth(), tm.GetDay(),
tm.GetHour(), tm.GetMinute(), tm.GetSecond());
_variant_t vtQuery(strSql);
return theApp.ADOExecute(theApp.m_pRs, vtQuery);
}
| [
"luochong1987@29d93fdc-527c-11de-bf49-a932634fd5a9"
] | [
[
[
1,
42
]
]
] |
a2e8fa1d243bd893bbec800ad713a4500aa2eac2 | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlGlossMap.inl | 4ef45f67de80222dc0d05b03ad3785c3218ad3fe | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,132 | inl | // 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.
//----------------------------------------------------------------------------
inline NodePtr GlossMap::GetObjects () const
{
return m_spkObjects;
}
//----------------------------------------------------------------------------
inline TextureStatePtr GlossMap::GetTextureState () const
{
return m_spkTextureState;
}
//----------------------------------------------------------------------------
inline AlphaStatePtr GlossMap::GetAlphaState () const
{
return m_spkAlphaState;
}
//----------------------------------------------------------------------------
inline int GlossMap::GetTextureUnit () const
{
return m_iTexUnit;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
2aab89cfd06764792a18526a0a5375fb3c8eb2ac | bdb1e38df8bf74ac0df4209a77ddea841045349e | /CapsuleSortor/Version 1.0 -2.0/CapsuleSortor-10-11-15/CapuleDemo/cvimagectrl1.cpp | 3aec2f6939b0183e8d2e3c17c1a73566318ac26f | [] | no_license | Strongc/my001project | e0754f23c7818df964289dc07890e29144393432 | 07d6e31b9d4708d2ef691d9bedccbb818ea6b121 | refs/heads/master | 2021-01-19T07:02:29.673281 | 2010-12-17T03:10:52 | 2010-12-17T03:10:52 | 49,062,858 | 0 | 1 | null | 2016-01-05T11:53:07 | 2016-01-05T11:53:07 | null | GB18030 | C++ | false | false | 616 | cpp | // 计算机生成了由 Microsoft Visual C++ 创建的 IDispatch 包装类
// 注意: 不要修改此文件的内容。如果此类由
// Microsoft Visual C++ 重新生成,您的修改将被改写。
#include "stdafx.h"
#include "cvimagectrl1.h"
/////////////////////////////////////////////////////////////////////////////
// CCvimagectrl1
IMPLEMENT_DYNCREATE(CCvimagectrl1, CWnd)
/////////////////////////////////////////////////////////////////////////////
// CCvimagectrl1 属性
/////////////////////////////////////////////////////////////////////////////
// CCvimagectrl1 操作
| [
"vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e"
] | [
[
[
1,
19
]
]
] |
1651e3c21d85c65c4ccaddbf127d9b8168aff90b | 5ff30d64df43c7438bbbcfda528b09bb8fec9e6b | /kcore/sys/Logger.h | 29128ac99303e8af4dbe3f396933926589f57c31 | [] | no_license | lvtx/gamekernel | c80cdb4655f6d4930a7d035a5448b469ac9ae924 | a84d9c268590a294a298a4c825d2dfe35e6eca21 | refs/heads/master | 2016-09-06T18:11:42.702216 | 2011-09-27T07:22:08 | 2011-09-27T07:22:08 | 38,255,025 | 3 | 1 | null | null | null | null | UHC | C++ | false | false | 2,129 | h | #pragma once
#include <kcore/sys/Thread.h>
#include <kcore/sys/Queue.h>
#include <kcore/sys/LogFile.h>
#include <kcore/sys/Tick.h>
#include <bitset>
namespace gk
{
enum FEATURE
{
FT_DEBUG = 1
, FT_DEBUG_FLOW
, FT_INFO
, FT_WARN
, FT_ERROR
, FT_SERVICE
, FEATURE_LIMIT = 64
};
/**
* @class Logger
*
* Logs to a sys log file.
*/
class Logger : public Thread
{
public:
static Logger* Instance();
~Logger();
/**
* Enable the feature
*
* @param feature Index value of feature
*/
void Enable( int feature );
/**
* Disable the feature
*
* @param feature Index value of feature
*/
void Disable( int feature );
/**
* Check whether the feature is enabled
*
* @param feature Index value of feature
* @return true if the feature is enabled
*/
bool IsEnabled( int feature );
/**
* Enable log to console
*/
void EnableConsole();
/**
* Disable log to console
*/
void DisableConsole();
/**
* Put a line to log
*
* @param line A string to log
*/
void Put( const tstring& line );
/**
* Thread::Run
*/
int Run();
/**
* Explicit finish
*/
void Fini();
private:
Logger();
void flush();
void cleanup();
private:
Queue<tstring, Mutex> m_q;
LogFile m_logFile;
std::bitset<FEATURE_LIMIT> m_features;
Mutex m_memberLock;
bool m_isConsolePrint; // 콘솔에 출력하는가?
Tick m_flushTick;
};
extern void LOG( int feature, const TCHAR* fmt, ... );
} // gk
#define NS_LOG_RETURN_IF( cond, msg ) \
if ( (cond) ) { kcore::LOG( kcore::FT_INFO, msg ); return; }
#define NS_LOG_RETURN_IF_NOT( cond, msg ) \
if ( !(cond) ) { kcore::LOG( kcore::FT_INFO, msg ); return; }
#define NS_LOG_RETURN_VAL_IF( cond, v, msg ) \
if ( (cond) ) { kcore::LOG( kcore::FT_INFO, msg ); return v; }
#define NS_LOG_RETURN_VAL_IF_NOT( cond, v, msg ) \
if ( !(cond) ) { kcore::LOG( kcore::FT_INFO, msg ); return v; }
| [
"darkface@localhost"
] | [
[
[
1,
118
]
]
] |
98bf3d08e9e76f16ff113d4726ce9a817eef0168 | 10bac563fc7e174d8f7c79c8777e4eb8460bc49e | /gui/glt_stream_server_t.hpp | 8d6635cdfb0a7f25a0d1bc15eaea4d2fcb71f0c3 | [] | no_license | chenbk85/alcordev | 41154355a837ebd15db02ecaeaca6726e722892a | bdb9d0928c80315d24299000ca6d8c492808f1d5 | refs/heads/master | 2021-01-10T13:36:29.338077 | 2008-10-22T15:57:50 | 2008-10-22T15:57:50 | 44,953,286 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 960 | hpp | #ifndef glt_stream_server_t_H_INCLUDED
#define glt_stream_server_t_H_INCLUDED
#include <glutm/window.h>
#include <alcor/gui/trackball.h>
#include <alcor/core/image_utils.h>
#include <alcor/core/stream_server_t.hpp>
class glt_stream_source_t;
class glt_stream_server_t : public GlutWindow{
public:
glt_stream_server_t(int, int);
void OnOpen();
void OnClose();
void OnDisplay();
void init_gl();
void build_trans_matrix();
void reset_projection_mode();
void update_buffer();
boost::function <void (void)> draw_data;
public:
float quat[4]; // orientation of object
float xcam;
float ycam;
float zcam;
int width, height;
all::core::uint8_sarr image;
boost::mutex mutex;
protected:
all::core::uint8_sarr m_frame_buffer;
boost::shared_ptr<glt_stream_source_t> m_stream_source;
boost::shared_ptr<all::core::stream_server_t> m_stream_server;
};
#endif | [
"stefano.marra@1c7d64d3-9b28-0410-bae3-039769c3cb81"
] | [
[
[
1,
54
]
]
] |
4e13e7b44ecd838a194384dff01a78475d83417b | f8b364974573f652d7916c3a830e1d8773751277 | /emulator/allegrex/instructions/VRCP.h | 57256cb7e1ad1613426b6bd6e28ecefb8fed2dc8 | [] | no_license | lemmore22/pspe4all | 7a234aece25340c99f49eac280780e08e4f8ef49 | 77ad0acf0fcb7eda137fdfcb1e93a36428badfd0 | refs/heads/master | 2021-01-10T08:39:45.222505 | 2009-08-02T11:58:07 | 2009-08-02T11:58:07 | 55,047,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | h | template< > struct AllegrexInstructionTemplate< 0xd0100000, 0xffff0000 > : AllegrexInstructionUnknown
{
static AllegrexInstructionTemplate &self()
{
static AllegrexInstructionTemplate insn;
return insn;
}
static AllegrexInstruction *get_instance()
{
return &AllegrexInstructionTemplate::self();
}
virtual AllegrexInstruction *instruction(u32 opcode)
{
return this;
}
virtual char const *opcode_name()
{
return "VRCP";
}
virtual void interpret(Processor &processor, u32 opcode);
virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment);
protected:
AllegrexInstructionTemplate() {}
};
typedef AllegrexInstructionTemplate< 0xd0100000, 0xffff0000 >
AllegrexInstruction_VRCP;
namespace Allegrex
{
extern AllegrexInstruction_VRCP &VRCP;
}
#ifdef IMPLEMENT_INSTRUCTION
AllegrexInstruction_VRCP &Allegrex::VRCP =
AllegrexInstruction_VRCP::self();
#endif
| [
"[email protected]"
] | [
[
[
1,
41
]
]
] |
3198a7bf1fb083c7b8436fb4b17dc9a2322653b9 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Application/ScDDESrvr/dde_dlgs.cpp | 889cd0ae316a8effcb352ca62cc569ad02cf27ff | [] | no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,951 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#include "sc_defs.h"
#include "scd_wm.h"
#include "scdctrls.h"
#include "resource.h"
#include "dde_dlgs.h"
#include "dde_mngr.h"
#include "dde_exec.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
//===========================================================================
CDDEStatsDlg::CDDEStatsDlg(CScdDDEManager* pDDEMngr, CWnd* pParent /*=NULL*/)
: CDialog(CDDEStatsDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CDDEStatsDlg)
m_ShowStats = 0;
//}}AFX_DATA_INIT
pMngr = pDDEMngr;
bDidInit = 0;
Create(CDDEStatsDlg::IDD, pParent); // NonModal Create
}
//---------------------------------------------------------------------------
CDDEStatsDlg::~CDDEStatsDlg()
{
if (pMngr)
pMngr->pTheDDEStatsDlg = NULL;
}
//--------------------------------------------------------------------------
void CDDEStatsDlg::PostNcDestroy()
{
CDialog::PostNcDestroy();
delete this;
}
//---------------------------------------------------------------------------
void CDDEStatsDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDDEStatsDlg)
DDX_Control(pDX, IDC_DDESTATSLIST, m_StatsList);
DDX_Radio(pDX, IDC_DDESHOWSTATS, m_ShowStats);
//}}AFX_DATA_MAP
}
//---------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(CDDEStatsDlg, CDialog)
//{{AFX_MSG_MAP(CDDEStatsDlg)
ON_BN_CLICKED(IDC_DDEFORCE, OnForce)
ON_BN_CLICKED(IDC_DDESHOWSTATS, OnShowStats)
ON_BN_CLICKED(IDC_DDESHOWTAGS, OnShowStats)
ON_BN_CLICKED(IDC_DDEREFRESH, OnRefresh)
//}}AFX_MSG_MAP
ON_MESSAGE(WMU_DDEUPDATESTATS, OnUpdateStats)
ON_UPDATE_COMMAND_UI(IDC_DDEFORCE, OnUpdateForce)
ON_UPDATE_COMMAND_UI(IDC_DDEREFRESH, OnUpdateRefresh)
END_MESSAGE_MAP()
//---------------------------------------------------------------------------
BOOL CDDEStatsDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CProfINIFile PF(PrjIniFile());
int xPos = PF.RdInt("General", "DDEXPos", 10);
int yPos = PF.RdInt("General", "DDEYPos", 50);
//UpdateData(FALSE);
SetVisibleWindowPos(this, xPos, yPos);
m_StatsList.SetTabStops(20);
bDidInit = 1;
//UpdateDialogControls(this, FALSE);
PostMessage(WMU_DDEUPDATESTATS, (WPARAM)SUB_UPDATE_REDRAW, (LPARAM)0);
return TRUE;
}
//---------------------------------------------------------------------------
void CDDEStatsDlg::OnOK()
{
RECT Rect;
GetWindowRect(&Rect);
CProfINIFile PF(PrjIniFile());
PF.WrInt("General", "DDEXPos", Rect.left);
PF.WrInt("General", "DDEYPos", Rect.top);
CDialog::OnOK();
DestroyWindow();
}
//---------------------------------------------------------------------------
void CDDEStatsDlg::OnCancel()
{
OnOK();
}
//---------------------------------------------------------------------------
const char* DDEStatDescs[] = { "Writes", "Requests", "Pokes", "Invalid tag requests" };
LRESULT CDDEStatsDlg::OnUpdateStats(WPARAM wParam, LPARAM lParam)
{
static int UpdateCnt = 0;
const char* UpdateRotate[4] = {"/","-","\\","|"};
wParam &= (~(SUB_UPDATE_SENDMSG|SUB_UPDATE_SUBSCHANGED));
const bool IsExec = (wParam==SUB_UPDATE_EOWRITE || wParam==SUB_UPDATE_EOEXEC);
if (!IsExec)
UpdateDialogControls(this, FALSE);
if (bDidInit && pMngr->DDEExec())
{
const int TagCnt = pMngr->DDEExec()->SubsData.GetSize();
char Buff[128];
if (!XBusy())
{
SetDlgItemText(IDC_DDESTATUS_TXT, ".");
sprintf(Buff, "Stopped! (%d tags)", TagCnt);
}
else
{
if (IsExec)
{
if (++UpdateCnt>3)
UpdateCnt=0;
}
SetDlgItemText(IDC_DDESTATUS_TXT, UpdateRotate[UpdateCnt]);
sprintf(Buff, "%d subscription tags", TagCnt);
}
SetDlgItemText(IDC_DDESUBSCNT_TXT, Buff);
if (m_ShowStats==0)
{//show stats...
m_StatsList.ResetContent();
for (int i=0; i<MaxDDEStats; i++)
{
sprintf(Buff, "%d\t%s", pMngr->DDEExec()->StatsCnt[i], DDEStatDescs[i]);
m_StatsList.InsertString(-1, Buff);
if (IsExec)
pMngr->DDEExec()->StatsCnt[i] = 0;
}
UpdateData(FALSE);
}
else if (m_ShowStats==1)
{//show tag list & values...
if (bSubsChanged)
{
m_StatsList.ResetContent();
//pMngr->DDEExec()->BuildTagList(&m_StatsList);
pMngr->DDEExec()->BuildSubsList(&m_StatsList);
UpdateData(FALSE);
bSubsChanged = 0;
}
}
}
return TRUE;
}
//---------------------------------------------------------------------------
void CDDEStatsDlg::OnRefresh()
{
if (m_ShowStats!=0)
{
bSubsChanged = 1;
PostMessage(WMU_DDEUPDATESTATS, (WPARAM)SUB_UPDATE_REDRAW, (LPARAM)0);
}
}
void CDDEStatsDlg::OnUpdateRefresh(CCmdUI* pCmdUi)
{
pCmdUi->Enable(m_ShowStats!=0);
}
//---------------------------------------------------------------------------
void CDDEStatsDlg::OnForce()
{
if (XBusy())
//pMngr->DDEExec()->DoWriteAll();
pMngr->DDEExec()->ForceAllWrites();
//PostMessage(WMU_DDEUPDATESTATS, (WPARAM)SUB_UPDATE_REDRAW, (LPARAM)0);
}
void CDDEStatsDlg::OnUpdateForce(CCmdUI* pCmdUi)
{
pCmdUi->Enable(XBusy());
}
//---------------------------------------------------------------------------
void CDDEStatsDlg::OnShowStats()
{
bSubsChanged = 1;
UpdateData(TRUE);
if (m_ShowStats!=0)
PostMessage(WMU_DDEUPDATESTATS, (WPARAM)SUB_UPDATE_REDRAW, (LPARAM)0);
}
//---------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
212
]
]
] |
27fc39c1c79e5223b2377e2ba4dbcb116f519c5d | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Dynamics/Constraint/Bilateral/BallAndSocket/hkpBallAndSocketConstraintData.h | cd8712b3080d752b2b9bf5a90a7095eb3b663997 | [] | 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 | 4,347 | 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 HK_DYNAMICS2_BALL_AND_SOCKET_CONSTRAINT_H
#define HK_DYNAMICS2_BALL_AND_SOCKET_CONSTRAINT_H
#include <Physics/Dynamics/Constraint/hkpConstraintData.h>
#include <Physics/ConstraintSolver/Constraint/Atom/hkpConstraintAtom.h>
extern const hkClass hkpBallAndSocketConstraintDataClass;
/// The ball-and-socket or point-to-point constraint.
class hkpBallAndSocketConstraintData : public hkpConstraintData
{
public:
HK_DECLARE_REFLECTION();
hkpBallAndSocketConstraintData();
/// Sets the construction information with body space information.
/// \param pivotA The constraint pivot point, specified in bodyA's space.
/// \param pivotB The constraint pivot point, specified in bodyB's space.
void setInBodySpace(const hkVector4& pivotA, const hkVector4& pivotB);
/// Sets the construction information with world space information. Will use the
/// given transforms to work out the two local pivots.
/// \param bodyA The first rigid body transform
/// \param bodyB The second rigid body transform
/// \param pivot The constraint pivot point, specified in world space.
void setInWorldSpace(const hkTransform& bodyATransform, const hkTransform& bodyBTransform,
const hkVector4& pivot);
/// Check consistency of constraint members.
virtual hkBool isValid() const;
/// Get type from this constraint.
virtual int getType() const;
public:
//
// Solver interface
//
enum
{
SOLVER_RESULT_LIN_0 = 0, // linear constraint
SOLVER_RESULT_LIN_1 = 1, // linear constraint
SOLVER_RESULT_LIN_2 = 2, // linear constraint
SOLVER_RESULT_MAX = 3
};
struct Runtime
{
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DYNAMICS, hkpBallAndSocketConstraintData::Runtime );
class hkpSolverResults m_solverResults[3/*VC6 doesn't like the scoping for SOLVER_RESULT_MAX*/];
};
inline const Runtime* getRuntime( hkpConstraintRuntime* runtime ){ return reinterpret_cast<Runtime*>(runtime); }
public:
struct Atoms
{
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DYNAMICS, hkpBallAndSocketConstraintData::Atoms );
HK_DECLARE_REFLECTION();
struct hkpSetLocalTranslationsConstraintAtom m_pivots;
struct hkpBallSocketConstraintAtom m_ballSocket;
Atoms() { }
// get a pointer to the first atom
const hkpConstraintAtom* getAtoms() const { return &m_pivots; }
int getSizeOfAllAtoms() const { return hkGetByteOffsetInt(this, &m_ballSocket+1); }
Atoms(hkFinishLoadedObjectFlag f) : m_pivots(f), m_ballSocket(f) {}
};
HK_ALIGN16( struct Atoms m_atoms );
public:
//
// Internal functions.
//
// hkpConstraintData interface implementations
virtual void getConstraintInfo( hkpConstraintData::ConstraintInfo& infoOut ) const;
// hkpConstraintData interface implementations
virtual void getRuntimeInfo( hkBool wantRuntime, hkpConstraintData::RuntimeInfo& infoOut ) const;
public:
hkpBallAndSocketConstraintData(hkFinishLoadedObjectFlag f) : hkpConstraintData(f), m_atoms(f) {}
};
#endif // HK_DYNAMICS2_BALL_AND_SOCKET_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,
123
]
]
] |
4fe7acc260fe19028da996c73317325aa03b088a | 5eb582292aeef7c56b13bc05accf71592d15931f | /include/raknet/RakClientInterface.h | 26fb9a74645e922490edbbd244e5fbdff22aabdb | [] | no_license | goebish/WiiBlob | 9316a56f2a60a506ecbd856ab7c521f906b961a1 | bef78fc2fdbe2d52749ed3bc965632dd699c2fea | refs/heads/master | 2020-05-26T12:19:40.164479 | 2010-09-05T18:09:07 | 2010-09-05T18:09:07 | 188,229,195 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,754 | h | /* -*- mode: c++; c-file-style: raknet; tab-always-indent: nil; -*- */
/**
* @file
* @brief User view of a RakClient object.
*
* This file is part of RakNet Copyright 2003 Rakkarsoft LLC and Kevin Jenkins.
*
* Usage of Raknet is subject to the appropriate licence agreement.
* "Shareware" Licensees with Rakkarsoft LLC are subject to the
* shareware license found at
* http://www.rakkarsoft.com/shareWareLicense.html which you agreed to
* upon purchase of a "Shareware license" "Commercial" Licensees with
* Rakkarsoft LLC are subject to the commercial license found at
* http://www.rakkarsoft.com/sourceCodeLicense.html which you agreed
* to upon purchase of a "Commercial license"
* Custom license users are subject to the terms therein.
* All other users are
* subject to the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* Refer to the appropriate license agreement for distribution,
* modification, and warranty rights.
*/
#ifndef __RAK_CLIENT_INTERFACE_H
#define __RAK_CLIENT_INTERFACE_H
#include "NetworkTypes.h"
#include "PacketPriority.h"
#include "RakPeerInterface.h"
#include "BitStream.h"
#include "RakNetStatistics.h"
/**
* @brief Define user point of vue of a RakClient communication end point.
*
* This class define the user view of a RakClient communication
* end-point. All accessible operation are available in this class.
* You should only deal with RakClient object throught instance of
* RakClientInterface.
*/
class RakClientInterface
{
public:
/**
* Destructor
*/
virtual ~RakClientInterface()
{}
/**
* Call this to connect the client to the specified host (ip or domain name) and server port.
* This is a non-blocking connection. You know the connection is successful when IsConnected() returns true
* or receive gets a packet with the type identifier ID_CONNECTION_REQUEST_ACCEPTED.
* serverPort is which port to connect to on the remote machine. clientPort is the port you want the
* client to use. Both ports must be open for UDP
*
* @param host a hostname
* @param serverPort The port on which to contact @em host
* @param clientPort The port to use localy
* @param depreciated is legacy and unused
* @param threadSleepTimer >=0 for how many ms to Sleep each internal update cycle
* (recommended 30 for low performance, 0 for regular)
* @return true on successful initiation, false otherwise
*/
virtual bool Connect( const char* host, unsigned short serverPort, unsigned short clientPort, unsigned int depreciated, int threadSleepTimer ) = 0;
/**
* Stops the client, stops synchronized data, and resets all internal data.
* Does nothing if the client is not connected to begin with
* blockDuration is how long you should wait for all remaining packets to go out
* If you set it to 0 then the disconnection notification probably won't arrive
* @param blockDuration The time to wait before truly close the communication and point
*/
virtual void Disconnect( unsigned int blockDuration ) = 0;
/**
* Can be called to use specific public RSA keys. (e and n)
* In order to prevent altered keys. Will return ID_RSA_PUBLIC_KEY_MISMATCH in a packet
* If a key has been altered.
*
* @param privKeyP Private keys generated from the RSACrypt class. Can be 0
* @param privKeyQ Private keys generated from the RSACrypt class. Can be 0
* @see Encryption sample.
*/
virtual void InitializeSecurity( const char *privKeyP, const char *privKeyQ ) = 0;
/**
* Set the password to use when connecting to a server. The password persists between connections.
* Pass 0 for no password.
* @param _password The password to use to connect to a server
*/
virtual void SetPassword( const char *_password ) = 0;
/**
* Returns true if a password was set, false otherwise
* @return true if a password has previously been set using SetPassword
*/
virtual bool HasPassword( void ) const = 0;
/**
* This function only works while the client is connected (Use the
* Connect function). Returns false on failure, true on success
* Sends the data stream of length length If you aren't sure what to
* specify for priority and reliability, use HIGH_PRIORITY and
* RELIABLE, 0 for ordering channel
* @param data a byte buffer
* @param length the size of the byte buffer
* @param priority the priority of the message
* @param reliability the reliability policy required
* @param orderingChannel the channel to send the message to.
*/
virtual bool Send( const char *data, const long length, PacketPriority priority, PacketReliability reliability, char orderingChannel ) = 0;
/**
* This function only works while the client is connected (Use the
* Connect function). Returns false on failure, true on success
* Sends the BitStream If you aren't sure what to specify for
* priority and reliability, use HIGH_PRIORITY and RELIABLE, 0 for
* ordering channel
* @param bitstream the data to send.
* @param priority the priority of the message
* @param reliability the reliability policy required
* @param orderingChannel the channel to send the message to.
*/
virtual bool Send( RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel ) = 0;
/**
* Call this to get a packet from the incoming packet queue. Use
* DeallocatePacket to deallocate the packet after you are done with
* it. Check the Packet struct at the top of
* CoreNetworkStructures.h for the format of the struct Returns 0 if
* no packets are waiting to be handled If the client is not active
* this will also return 0, as all waiting packets are flushed when
* the client is Disconnected This also updates all memory blocks
* associated with synchronized memory
* @return the last receive packet
*/
virtual Packet* Receive( void ) = 0;
/**
* Call this to deallocate a packet returned by Receive when you are done handling it.
* Free the memory associated to a packet. It is not the same as using delete operator because
* RakNet might decide not to delete right now the packet in order to use it later.
* @param packet the packet to deallocate.
*/
virtual void DeallocatePacket( Packet *packet ) = 0;
/**
* Send a ping request to the server.Occasional pings are on by
* default (see StartOccasionalPing and StopOccasionalPing) so
* unless you turn them off it is not necessary to call this
* function. It is here for completeness if you want it Does
* nothing if the client is not connected to begin with
*/
virtual void PingServer( void ) = 0;
/**
* Sends a ping request to a server we are not connected to. This will also initialize the
* networking system if it is not already initialized. You can stop the networking system
* by calling Disconnect()
* The final ping time will be encoded in the following 4 bytes (2-5) as an unsigned int
* You can specify if the server should only reply if it has an open connection or not
* This must be true for LAN broadcast server discovery on "255.255.255.255"
* or you will get replies from clients as well. A broadcast will always have 0 for the ping time as only single
* byte packets are allowed from unconnected systems.
* @param host The host to contact
* @param ServerPort the port used by the server
* @param clientPort the port used to receive the answer
* @param onlyReplyOnAcceptingConnections if true the server must be ready to accept incomming connection.
*/
virtual void PingServer( const char* host, unsigned short serverPort, unsigned short clientPort, bool onlyReplyOnAcceptingConnections ) = 0;
/**
* Returns the average of all ping times read
* @return the average ping value to the server
*/
virtual int GetAveragePing( void ) = 0;
/**
* Returns the last ping time read for the specific player or -1 if none read yet
* @return last ping value
*/
virtual int GetLastPing( void ) const = 0;
/**
* Returns the lowest ping time read or -1 if none read yet
* @return lowest ping value
*/
virtual int GetLowestPing( void ) const = 0;
/**
* Returns the last ping for the specified player. This information
* is broadcast by the server automatically In order to save
* bandwidth this information is updated only infrequently and only
* for the first 32 players
* @param playerId The id of the player you want to have the ping (it might be your id)
* @return the last ping for this player
* @note You can read your own ping with
* this method by passing your own playerId, however for more
* up-to-date readings you should use one of the three functions
* above
*
*/
virtual int GetPlayerPing( PlayerID playerId ) = 0;
/**
* Ping the server every so often. This is on by default. In games
* where you don't care about ping you can call StopOccasionalPing
* to save the bandwidth This will work anytime
*/
virtual void StartOccasionalPing( void ) = 0;
/**
* Stop pinging the server every so often. The server is pinged by
* default. In games where you don't care about ping you can call
* this to save the bandwidth This will work anytime
*/
virtual void StopOccasionalPing( void ) = 0;
/**
* Returns true if the client is connected to a responsive server
* @return true if connected to a server
*/
virtual bool IsConnected( void ) const = 0;
/**
* Returns a number automatically synchronized between the server
* and client which randomly changes every 9 seconds. The time it
* changes is accurate to within a few ms and is best used to seed
* random number generators that you want to usually return the same
* output on all systems. Keep in mind this isn't perfectly
* accurate as there is always a very small chance the numbers will
* by out of synch during changes so you should confine its use to
* visual effects or functionality that has a backup method to
* maintain synchronization. If you don't need this functionality
* and want to save the bandwidth call StopSynchronizedRandomInteger
* after starting the server
* @return A random int common to all client and to the server.
*/
virtual unsigned int GetSynchronizedRandomInteger( void ) const = 0;
/**
* This is an optional function to generate the compression layer
* from the input frequency table. You should call this twice -
* once with inputLayer as true and once as false. The frequency
* table passed here with inputLayer=true should match the frequency
* table on the recipient with inputLayer=false. Likewise, the
* frequency table passed here with inputLayer=false should match
* the frequency table on the recipient with inputLayer=true Calling
* this function when there is an existing layer will overwrite the
* old layer You should only call this when disconnected
*
* @param inputFrenquencyTable the table to used for compression
* @param inputLayer says if the @em inputFrequencyTable should be used for
* sending or receiveing.
* @return false (failure) if connected. Otherwise true (success)
*
* @note The server Sends should share the same inputFrequencyTable
* as the client for receiving. It's also true for the client sending and the server receiving.
*/
virtual bool GenerateCompressionLayer( unsigned int inputFrequencyTable[ 256 ], bool inputLayer ) = 0;
/**
* Delete the output or input layer as specified. This is not necessary to call and is only valuable for freeing memory
* You should only call this when disconnected
* @param inputLayer Delete the compression layer for sending or for receiving ?
* @return false (failure) if connected. Otherwise true (success)
*/
virtual bool DeleteCompressionLayer( bool inputLayer ) = 0;
/**
* Register a C function as available for calling as a remote
* procedure call uniqueID should be a null terminated non-case
* senstive string of only letters to identify this procedure
* Parameter 2 should be the name of the C function or C++ singleton
* to be used as a function pointer This can be called whether the
* client is active or not, and registered functions stay registered
* unless unregistered with UnregisterAsRemoteProcedureCall
* Only call offline
* @param uniqueID the id of the RPC
* @param functionPointer a pointer to the C function.
*/
virtual void RegisterAsRemoteProcedureCall( char* uniqueID, void ( *functionPointer ) ( RPCParameters *rpcParms ) ) = 0;
/**
* @ingroup RAKNET_RPC
* Register a C++ member function as available for calling as a remote procedure call.
*
* @param uniqueID: A null terminated string to identify this procedure.
* Recommended you use the macro REGISTER_CLASS_MEMBER_RPC
* @param functionPointer: The name of the function to be used as a function pointer
* This can be called whether the client is active or not, and registered functions stay registered unless unregistered with
* UnregisterAsRemoteProcedureCall
* See the ObjectMemberRPC sample for notes on how to call this and setup the member function
* @note This is part of the Remote Procedure Call Subsystem
*
*/
virtual void RegisterClassMemberRPC( char* uniqueID, void *functionPointer ) = 0;
/**
* Unregisters a C function as available for calling as a remote procedure call that was formerly registered
* with RegisterAsRemoteProcedureCall
* Only call offline
* @param uniqueID the id of the RPC.
*/
virtual void UnregisterAsRemoteProcedureCall( char* uniqueID ) = 0;
/**
* Calls a C function on the server that the server already
* registered using RegisterAsRemoteProcedureCall Pass the data you
* want to pass to that function in parameters, or 0 for no data to
* pass You can also pass a regular data stream which will be
* converted to a bitstream internally by passing data and bit
* length If you want that function to return data you should call
* RPC from that system in the same way Returns true on a successful
* packet send (this does not indicate the recipient performed the
* call), false on failure The uniqueID must be composed of a string
* with only characters from a-z and is not case sensitive
* @param objectID For static functions, pass UNASSIGNED_OBJECT_ID. For member functions, you must derive from NetworkIDGenerator and pass the value returned by NetworkIDGenerator::GetNetworkID for that object.
*/
virtual bool RPC( char* uniqueID, const char *data, unsigned int bitLength, PacketPriority priority, PacketReliability reliability, char orderingChannel, bool shiftTimestamp, ObjectID objectID ) = 0;
/**
* Calls a C function on the server that the server already
* registered using RegisterAsRemoteProcedureCall Pass the data you
* want to pass to that function in parameters, or 0 for no data to
* pass You can also pass a regular data stream which will be
* converted to a bitstream internally by passing data and bit
* length If you want that function to return data you should call
* RPC from that system in the same way Returns true on a successful
* packet send (this does not indicate the recipient performed the
* call), false on failure The uniqueID must be composed of a string
* with only characters from a-z and is not case sensitive
* @param objectID For static functions, pass UNASSIGNED_OBJECT_ID. For member functions, you must derive from NetworkIDGenerator and pass the value returned by NetworkIDGenerator::GetNetworkID for that object.
*/
virtual bool RPC( char* uniqueID, RakNet::BitStream *parameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, bool shiftTimestamp, ObjectID objectID ) = 0;
// OBSOLETE - DONE AUTOMATICALLY
// Handles an RPC packet. If you get a packet with the ID ID_RPC you should pass it to this function
// This is already done in Multiplayer.cpp, so if you use the Multiplayer class it is handled for you.
// Returns true on success, false on a bad packet or an unregistered function
// virtual bool HandleRPCPacket(Packet* packet)=0;
/**
* Enables or disables frequency table tracking. This is required
* to get a frequency table, which is used to generate A new
* compression layer. You can call this at any time - however you
* SHOULD only call it when disconnected. Otherwise you will only
* track part of the values sent over the network. This value
* persists between connect calls and defaults to false (no
* frequency tracking)
* @param b true to unable tracking.
*/
virtual void SetTrackFrequencyTable( bool b ) = 0;
/**
* Returns the frequency of outgoing bytes into outputFrequencyTable
* The purpose is to save to file as either a master frequency table
* from a sample game session for passing to
* GenerateCompressionLayer. You should only call this when
* disconnected. Requires that you first enable data frequency
* tracking by calling SetTrackFrequencyTable(true)
* @param outputFrequencyTable The frequency table produce during the tracking time.
* @return false (failure) if connected or if frequency table tracking is
* not enabled. Otherwise true (success)
*/
virtual bool GetSendFrequencyTable( unsigned int outputFrequencyTable[ 256 ] ) = 0;
/**
* Returns the compression ratio. A low compression ratio is good. Compression is for outgoing data
* @return the current compression ratio
*/
virtual float GetCompressionRatio( void ) const = 0;
/**
* Returns the decompression ratio. A high decompression ratio is good. Decompression is for incoming data
* @return the current decompression ratio
*/
virtual float GetDecompressionRatio( void ) const = 0;
/**
* Attatches a message handler interface to run code automatically on message receipt in the Receive call
*
* @param messageHandler Pointer to a message handler to attach
*/
virtual void AttachMessageHandler( MessageHandlerInterface *messageHandler )=0;
/**
* Detatches a message handler interface to run code automatically on message receipt
*
* @param messageHandler Pointer to a message handler to detatch
*/
virtual void DetachMessageHandler( MessageHandlerInterface *messageHandler )=0;
/**
* The server internally maintains a data struct that is
* automatically sent to clients when the connect. This is useful
* to contain data such as the server name or message of the day.
* Access that struct with this function. The data is entered as an
* array and stored and returned as a BitStream. Everytime you call
* GetStaticServerData it resets the read pointer to the start of
* the bitstream. To do multiple reads without reseting the pointer
* Maintain a pointer copy to the bitstream as in RakNet::BitStream *copy = ...->GetStaticServerData(...);
* To store a bitstream, use the GetData() and GetNumberOfBytesUsed() methods
* of the bitstream for the 2nd and 3rd parameters
* Note that the server may change at any time the
* data contents and/or its length!
* @return a bitstream containing statistics.
*/
virtual RakNet::BitStream * GetStaticServerData( void ) = 0;
/**
* The server internally maintains a data struct that is
* automatically sent to clients when the connect. This is useful
* to contain data such as the server name or message of the day.
* Access that struct with this function. The data is entered as an
* array and stored and returned as a BitStream. Everytime you call
* GetStaticServerData it resets the read pointer to the start of
* the bitstream. To do multiple reads without reseting the pointer
* Maintain a pointer copy to the bitstream as in RakNet::BitStream *copy = ...->GetStaticServerData(...);
* To store a bitstream, use the GetData() and GetNumberOfBytesUsed() methods
* of the bitstream for the 2nd and 3rd parameters
* Note that the server may change at any time the
* data contents and/or its length!
* @param data a byte buffer containing statistical information.
* @param length the size of @em data
*/
virtual void SetStaticServerData( const char *data, const long length ) = 0;
/**
* The client internally maintains a data struct that is automatically sent to the server on connection
* This is useful to contain data such as the player name. Access that struct with this
* function. Pass UNASSIGNED_PLAYER_ID for playerId to reference your internal data. A playerId value to access the data of another player.
* *** NOTE ***
* If you change any data in the struct the server won't reflect this change unless you manually update it
* Do so by calling SendStaticClientDataToServer
* The data is entered as an array and stored and returned as a BitStream.
* Everytime you call GetStaticServerData it resets the read pointer to the start of the bitstream. To do multiple reads without reseting the pointer
* Maintain a pointer copy to the bitstream as in
* RakNet::BitStream *copy = ...->GetStaticServerData(...);
* To store a bitstream, use the GetData() and GetNumberOfBytesUsed() methods
* of the bitstream for the 2nd and 3rd parameters
*/
virtual RakNet::BitStream * GetStaticClientData( PlayerID playerId ) = 0;
/**
* Set Local statistical information for playId. Call this
* function when you receive statistical information from a
* client.
*
* @param playerId the player ID
* @param data the packet data
* @param length the size of the data
*/
virtual void SetStaticClientData( PlayerID playerId, const char *data, const long length ) = 0;
/**
* Send the static server data to the server The only time you need
* to call this function is to update clients that are already
* connected when you change the static server data by calling
* GetStaticServerData and directly modifying the object pointed to.
* Obviously if the connected clients don't need to know the new
* data you don't need to update them, so it's up to you The server
* must be active for this to have meaning
*/
virtual void SendStaticClientDataToServer( void ) = 0;
/**
* Return the player number of the server.
* @return the server playerID
*/
virtual PlayerID GetServerID( void ) const = 0;
/**
* Return the player number the server has assigned to you.
*
* @return our player ID
* @note that unlike in previous versions, this is a struct and is not sequential
*
*/
virtual PlayerID GetPlayerID( void ) const = 0;
/**
* Returns the dotted IP address for the specified playerId
*
* @param playerId Any player ID other than UNASSIGNED_PLAYER_ID,
* even if that player is not currently connected
* @return a dotted notation string representation of the address of playerId.
*/
virtual const char* PlayerIDToDottedIP( PlayerID playerId ) const = 0;
/**
* Put a packet back at the end of the receive queue in case you don't want to deal with it immediately
* @param packet the packet to delayed
*/
virtual void PushBackPacket( Packet *packet ) = 0;
/**
* Change the MTU size in order to improve performance when sending large packets
* This can only be called when not connected.
* Returns false on failure (we are connected). True on success. Maximum allowed size is MAXIMUM_MTU_SIZE
* A too high of value will cause packets not to arrive at worst and be fragmented at best.
* A too low of value will split packets unnecessarily.
* Set according to the following table:
* 1500. The largest Ethernet packet size; it is also the default value.
* This is the typical setting for non-PPPoE, non-VPN connections. The default value for NETGEAR routers, adapters and switches.
* 1492. The size PPPoE prefers.
* 1472. Maximum size to use for pinging. (Bigger packets are fragmented.)
* 1468. The size DHCP prefers.
* 1460. Usable by AOL if you don't have large email attachments, etc.
* 1430. The size VPN and PPTP prefer.
* 1400. Maximum size for AOL DSL.
* 576. Typical value to connect to dial-up ISPs. (Default)
*/
virtual bool SetMTUSize( int size ) = 0;
/**
* Returns the current MTU size
*/
virtual int GetMTUSize( void ) const = 0;
/**
* Allow or disallow connection responses from any IP. Normally this should be false, but may be necessary
* when connection to servers with multiple IP addresses.
*
*
* @param allow True to allow this behavior, false to not allow.
* Defaults to false. Value persists between connections
*/
virtual void AllowConnectionResponseIPMigration( bool allow ) = 0;
/**
* Sends a one byte message ID_ADVERTISE_SYSTEM to the remote unconnected system.
* This will tell the remote system our external IP outside the LAN, and can be used for NAT punch through
*
* @param host Either a dotted IP address or a domain name
* @param remotePort Which port to connect to on the remote machine.
* @param data Optional data to append to the packet.
* @param dataLength length of data in bytes. Use 0 if no data.
*/
virtual void AdvertiseSystem( char *host, unsigned short remotePort, const char *data, int dataLength ) = 0;
/**
* Returns a structure containing a large set of network statistics for the server/client connection
* You can map this data to a string using the C style StatisticsToString function
*
* @return 0 on can't find the specified system. A pointer to a set of data otherwise.
*/
virtual RakNetStatisticsStruct * const GetStatistics( void ) = 0;
/**
* @internal
* Retrieve the player index corresponding to this client.
*/
virtual PlayerIndex GetPlayerIndex( void ) = 0;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
521
]
]
] |
557295d8512c50fb0724ec85653b4d9c56c55adc | d5f525c995dd321375a19a8634a391255f0e5b6f | /graphic_front_end/ledINT/ledINT/ledINTDlg.cpp | 1a7f319ae02ebd875a1bf158d69f4bf637922d2a | [] | no_license | shangdawei/cortex-simulator | bac4b8f19be3e2df622ad26e573330642ec97bae | d343b66a88a5b78d5851a3ee5dc2a4888ff00b20 | refs/heads/master | 2016-09-05T19:45:32.930832 | 2009-03-19T06:07:47 | 2009-03-19T06:07:47 | 42,106,205 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,419 | cpp | // ledINTDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "ledINT.h"
#include "ledINTDlg.h"
#include "vbus/vbus_interface.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CledINTDlg 对话框
CledINTDlg::CledINTDlg(CWnd* pParent /*=NULL*/)
: CDialog(CledINTDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
bd = 0;
}
void CledINTDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CledINTDlg, CDialog)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_BUTTON1, &CledINTDlg::OnBnClickedButton1)
ON_WM_TIMER()
END_MESSAGE_MAP()
// CledINTDlg 消息处理程序
BOOL CledINTDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
vb_load("vbus");
SetTimer(1, 5, NULL);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CledINTDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标显示。
//
HCURSOR CledINTDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CledINTDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
bd = ~bd;
}
void CledINTDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CDialog::OnTimer(nIDEvent);
if(bd){
vb_write(12,1);
vb_write(13,1);
}
SetTimer(nIDEvent, 1, NULL);
}
| [
"yihengw@3e89f612-834b-0410-bb31-dbad55e6f342"
] | [
[
[
1,
112
]
]
] |
eb8ede05e79133416dc6aa1907900369bc5c13ea | 8a223ca4416c60f4ad302bc045a182af8b07c2a5 | /Orders-ListeningFakeProblem-Cpp/Support-GTest-Cpp/src/ILFileUtils.cpp | 78115c0a8d2af4b27e71956f4234263ede92b6fc | [
"BSD-3-Clause"
] | permissive | sinojelly/sinojelly | 8a773afd0fcbae73b1552a217ed9cee68fc48624 | ee40852647c6a474a7add8efb22eb763a3be12ff | refs/heads/master | 2016-09-06T18:13:28.796998 | 2010-03-06T13:22:12 | 2010-03-06T13:22:12 | 33,052,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,278 | cpp | /// ***************************************************************************
/// Copyright (c) 2009, Industrial Logic, Inc., All Rights Reserved.
///
/// This code is the exclusive property of Industrial Logic, Inc. It may ONLY be
/// used by students during Industrial Logic's workshops or by individuals
/// who are being coached by Industrial Logic on a project.
///
/// This code may NOT be copied or used for any other purpose without the prior
/// written consent of Industrial Logic, Inc.
/// ****************************************************************************
#include "ILFileUtils.h"
#include "ILStringUtils.h"
#include <string>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <ctype.h>
#include <sys/stat.h> // stat()
using namespace std;
namespace IL
{
FileUtils::FileUtils()
{
}
FileUtils::~FileUtils()
{
}
FileList FileUtils::listFilesInDirWithSuffix(const std::string& sourceDirectory,
const std::string& fileSuffix)
{
FileList result;
DIR *dir = opendir(sourceDirectory.c_str());
if (dir == NULL)
return result;
struct dirent *entry;
for(; NULL != (entry = readdir(dir)); )
{
FilePath filepath((sourceDirectory + entry->d_name).c_str());
if (isDir(entry, filepath.c_str()))
continue;
if (stringEndsWithCaseInsensitive(entry->d_name, fileSuffix))
result.push_back(entry->d_name);
}
closedir(dir);
sort(result.begin(), result.end());
return result;
}
vector<long> FileUtils::getModDatesForFiles(const FilePathList& files)
{
vector<long> result;
for (FilePathList::size_type i = 0; i < files.size(); i++)
{
result.push_back(files[i].GetModificationDateInSeconds());
}
return result;
}
bool FileUtils::isDir(dirent* entry, const char* filePathName) {
#ifdef __CYGWIN__
struct stat entryStat;
stat(filePathName, &entryStat);
return S_ISDIR(entryStat.st_mode);
#elif defined(_MSC_VER)
struct _stat entryStat;
_stat(filePathName, &entryStat);
return (entryStat.st_mode & S_IFDIR)==S_IFDIR;
#elif defined(_WIN32)
struct stat entryStat;
stat(filePathName, &entryStat);
return (entryStat.st_mode & S_IFDIR)==S_IFDIR;
#else
return (DT_DIR == entry->d_type);
#endif
}
FileList FileUtils::listFilesInDir(const std::string& sourceDirectory)
{
FileList result;
DIR *dir = opendir(sourceDirectory.c_str());
if (dir == NULL)
return result;
struct dirent *entry;
for(; NULL != (entry = readdir(dir)); )
{
FilePath filepath((sourceDirectory + entry->d_name).c_str());
if (stringBeginsWith(entry->d_name, ".") // skip invisible files
|| isDir(entry, filepath.c_str()))
continue;
result.push_back(entry->d_name);
}
closedir(dir);
sort(result.begin(), result.end());
return result;
}
FileList FileUtils::listAllFilesInDir(const std::string& sourceDirectory)
{
FileList result;
DIR *dir = opendir(sourceDirectory.c_str());
if (dir == NULL)
return result;
struct dirent *entry;
for(; NULL != (entry = readdir(dir)); )
{
FilePath filepath(sourceDirectory + entry->d_name);
if (isDir(entry, filepath.c_str()))
continue;
result.push_back(entry->d_name);
}
closedir(dir);
sort(result.begin(), result.end());
return result;
}
FileList FileUtils::listDirsInDir(const std::string& sourceDirectory)
{
const std::string CVS = "CVS";
FileList result;
DIR *dir = opendir(sourceDirectory.c_str());
if (dir == NULL)
return result;
struct dirent *entry;
for(; NULL != (entry = readdir(dir)); )
{
FilePath filepath((sourceDirectory + entry->d_name).c_str());
if (stringBeginsWith(entry->d_name, ".") // skip invisibles
|| CVS == entry->d_name) // skip CVS junk
continue;
if (isDir(entry, filepath.c_str()))
result.push_back(entry->d_name);
}
closedir(dir);
sort(result.begin(), result.end());
return result;
}
FileList FileUtils::listAllDirsInDir(const std::string& sourceDirectory)
{
const std::string DOT = ".";
const std::string DOT_DOT = "..";
FileList result;
DIR *dir = opendir(sourceDirectory.c_str());
if (dir == NULL)
return result;
struct dirent *entry;
for(; NULL != (entry = readdir(dir)); )
{
FilePath filepath(sourceDirectory + entry->d_name);
if (DOT == entry->d_name || DOT_DOT == entry->d_name)
continue;
if (isDir(entry, filepath.c_str()))
result.push_back(entry->d_name);
}
closedir(dir);
sort(result.begin(), result.end());
return result;
}
FilePathList FileUtils::listFilePathsInDir(const std::string& sourceDirectory)
{
FileList localNames = listFilesInDir(sourceDirectory);
FilePathList absoluteNames;
for (FileList::size_type i = 0; i < localNames.size(); i++)
{
string absName = sourceDirectory;
if (!stringEndsWith(absName, PATH_SEP_STRING))
absName += PATH_SEP_STRING;
absName += localNames[i];
absoluteNames.push_back(FilePath(absName.c_str()));
}
return absoluteNames;
}
FilePathList FileUtils::listAllFilePathsInDir(const std::string& sourceDirectory)
{
FileList localNames = listAllFilesInDir(sourceDirectory);
FilePathList absoluteNames;
for (FileList::size_type i = 0; i < localNames.size(); i++)
{
string absName = sourceDirectory;
if (!stringEndsWith(absName, PATH_SEP_STRING))
absName += PATH_SEP_STRING;
absName += localNames[i];
absoluteNames.push_back(FilePath(absName.c_str()));
}
return absoluteNames;
}
bool FileUtils::fileListContains(const FileList& fileList,
const std::string& nameToFind)
{
for (FileList::size_type i = 0; i < fileList.size(); i++)
{
if (nameToFind == fileList[i])
return true;
}
return false;
}
std::string FileUtils::fileListAsString(const FileList& fileList)
{
string fileNames;
for (FileList::size_type i = 0; i < fileList.size(); i++)
{
fileNames += fileList[i];
fileNames += ", ";
}
return fileNames;
}
void FileUtils::makeSnapshot(FilePath& labDir, long timestamp)
{
// timestamp is in seconds, but generate the directory name as milliseconds.
// We don't want to mess with int64, since some compiler may not support that, so append
// string instead of multiplying by 1000.
// data/editing.history/123456000/src
// data/editing.history/123456000/test
FilePath snapshotDir(labDir.GetChildDirectory("data")
.GetChildDirectory("editing.history")
.GetChildDirectory((numToString(timestamp)+"000").c_str()));
if (!snapshotDir.CreateDirectoriesRecursively())
throw string("can't create ") + snapshotDir.c_str();
FilePath labSrc = labDir.GetChildDirectory("src");
FilePath srcInSnap = snapshotDir.GetChildDirectory("src");
copyEntireDirectoryFromTo(labSrc, srcInSnap);
suffixAllFilesIn(srcInSnap);
FilePath labTest = labDir.GetChildDirectory("test");
FilePath testInSnap = snapshotDir.GetChildDirectory("test");
copyEntireDirectoryFromTo(labTest, testInSnap);
suffixAllFilesIn(testInSnap);
}
void FileUtils::suffixAllFilesIn(IL::FilePath& srcInSnap)
{
FilePathList files = FileUtils::listAllFilePathsInDir(srcInSnap.c_str());
for (FilePathList::size_type i = 0; i < files.size(); i++)
files[i].AddSuffixToFilename(".x");
}
void FileUtils::unsuffixAllFilesIn(IL::FilePath& srcInSnap)
{
FilePathList files = FileUtils::listAllFilePathsInDir(srcInSnap.c_str());
for (FilePathList::size_type i = 0; i < files.size(); i++)
files[i].RemoveSuffixFromFilename(".x");
}
void FileUtils::copyEntireDirectoryFromTo(FilePath& sourceDir, FilePath& destDir)
{
destDir.CreateDirectoriesRecursively();
sourceDir.CopyContentsTo(destDir);
}
const std::string ILConfig::TESTING_HISTORY = "TESTING_HISTORY";
const std::string ILConfig::EDITING_HISTORY = "EDITING_HISTORY";
const std::string ILConfig::ARCHIVE_NAME = "ARCHIVE_NAME";
const std::string ILConfig::ARCHIVE_DIRS = "ARCHIVE_DIRS";
ILConfig::ILConfig(const FilePath& fileIn)
: file(fileIn)
{ }
ILConfig::~ILConfig()
{ }
std::string ILConfig::extractProperty(const std::string& propName)
{
if (properties.size() == 0)
readFile();
return properties[propName];
}
bool ILConfig::extractBoolProperty(const std::string& propName)
{
string prop = extractProperty(propName);
return (prop == "1");
}
void ILConfig::readFile()
{
string line;
ifstream infile(file.c_str());
if (!infile.is_open())
throw string("can't read file ") + file.c_str();
while (!infile.eof())
{
getline(infile, line);
for (size_t i = 0; i < line.length(); i++)
if (isspace(line[i]) || iscntrl(line[i]))
line[i] = ' ';
if (line.length() == 0 || line[0] == '#'
|| !stringContains(line, "="))
continue;
int index = line.find('=');
string key = line.substr(0, index);
key = trimSpaces(key);
string value = line.substr(index + 1);
value = trimSpaces(value);
properties[key] = value;
}
infile.close();
}
void FileUtils::addFilesWithSuffixInDir(FilePathList& pathList,
const FilePath& dir, const std::string& suffix)
{
FileList fileList = FileUtils::listFilesInDirWithSuffix(dir.c_str(), suffix);
for (FileList::size_type i = 0; i < fileList.size(); i++)
{
FilePath projectFileToAdd(dir.GetChildFile(fileList[i].c_str()));
pathList.push_back(projectFileToAdd);
}
}
IL::FilePath FileUtils::getDataDirOf(const IL::FilePath& currentDir)
{
IL::FilePath result;
string curDir = currentDir.c_str();
if (stringEndsWithCaseInsensitive(curDir, PATH_SEP_STRING + "bin" + PATH_SEP_STRING)
|| stringEndsWithCaseInsensitive(curDir, PATH_SEP_STRING + "build" + PATH_SEP_STRING)
|| stringEndsWithCaseInsensitive(curDir, "\\VS2008\\")
|| stringEndsWithCaseInsensitive(curDir, "\\VS2005\\"))
{
result = currentDir.GetParentDirectory();
}
else
{
result = currentDir;
}
return result.GetChildDirectory("data");
}
FilePathList FileUtils::getFilesForModDates(const FilePath& labDir)
{
FilePathList result;
addFilesWithSuffixInDir(result, labDir, ".project");
addFilesWithSuffixInDir(result, labDir.GetChildDirectory("VS2005"), ".ncb");
addFilesWithSuffixInDir(result, labDir.GetChildDirectory("VS2008"), ".ncb");
return result;
}
} // namespace IL
| [
"chenguodong@localhost"
] | [
[
[
1,
377
]
]
] |
e5fa3d233d70a4007429713e8189c1166ace9c3b | 758378bbd01ff3fc509c5725596c671b53ddb4dd | /include/ngl/Quaternion.h | 596de094bf9d2413b9bf59d6857bfa068470084b | [] | no_license | suncorner/NGL | 38a5a520899ce4f4a3796e419f5ff3fc35b02721 | 18b232416742f4ccfaecf60c9541559637c9cf5a | refs/heads/master | 2016-09-05T16:51:47.833680 | 2010-06-17T17:58:49 | 2010-06-17T17:58:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,106 | h | /*
Copyright (C) 2009 Jon Macey
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//=========================================================================
///
/// \file Quaternion.h
/// \author Rob Bateman
/// \brief Defines the class Quaternion, a class definition for a Quaternion
/// see www.robthebloke.org
//=========================================================================
//=========================================================================
// Sentry
//=========================================================================
// This directive is used to stop the header file from being included
// Twice and is standard for all headers.
// must include types.h first for ngl::Real and GLEW if required
#include "Types.h"
#ifndef QUATERNION_H_INCLUDED
#define QUATERNION_H_INCLUDED
//=========================================================================
// Includes
//=========================================================================
#include <iostream>
#include "Vector.h"
//=========================================================================
// Class Definitions
//=========================================================================
namespace ngl
{
class Matrix;
//------------------------------------------------------------------------------
/// \class Quaternion "include/Quaternion.h"
/// \brief The Quaternion class is used to hold rotational values for both
/// transforms and animation keyframes.
///
class Quaternion
{
public:
//--------------------------------------------------------------------------
/// \brief constructor
/// @param [in] _x - the x component of the quaternion
/// @param [in] _y - the y component of the quaternion
/// @param [in] _z - the z component of the quaternion
/// @param [in] _w - the w component of the quaternion
///
inline Quaternion(
const Real _x=0,
const Real _y=0,
const Real _z=0,
const Real _w=1
):
m_x(_x),
m_y(_y),
m_z(_z),
m_w(_w) {;}
//--------------------------------------------------------------------------
/// \brief copy constructor
/// @param [in] _q - the quaternion to copy
///
inline Quaternion(
const Quaternion& _q
):
m_x(_q.m_x),
m_y(_q.m_y),
m_z(_q.m_z),
m_w(_q.m_w) {;}
/// \brief method to set the quaternion values
/// @param[in] _x the x value
/// @param[in] _y the y value
/// @param[in] _z the z value
/// @param[in] _w the w value
inline void Set(
const Real& _x,const Real& _y,const Real& _z,const Real& _w
)
{
m_x=_x;
m_y=_y;
m_z=_z;
m_w=_w;
}
//--------------------------------------------------------------------------
/// \brief returns the inverse of the quaternion (aka conjugate)
/// \return the conjugate of the quaternion
///
inline Quaternion operator-() const
{
return Quaternion( -m_x,-m_y,-m_z,m_w );
}
//--------------------------------------------------------------------------
/// \brief Perform a multiplication between 2 quaternions
///
/// ResultQuaternion = Q1.Q2 = ( w1.w2 - v1.v2, w1.v2 + w2.v1 + v1 x v2 )
///
/// where v1 = (x,y,z) of Q1
/// w1 = (w) of Q1
/// v2 = (x,y,z) of Q2
/// w2 = (w) of Q2
///
/// \return the result of the mutliplication
///
Quaternion operator *(
const Quaternion& _q
) const;
//--------------------------------------------------------------------------
/// \brief
/// \note A rotation matrix may be converted back to a quaternion.
/// @param [in] _m the matrix to construct from
Quaternion(
const Matrix& _m
);
//--------------------------------------------------------------------------
/// \brief This function normalises the quaternion
/// \return A constant reference to itself
///
const Quaternion& Normalise();
//--------------------------------------------------------------------------
/// \brief returns a normalised version of this quaternion
/// \return The normalised quaternion
///
Quaternion Normalised() const ;
//--------------------------------------------------------------------------
/// \brief this function turns the quaternion into a 4x4 rotation matrix
/// @param [in] o_matrix - the output matrix
///
void AsMatrix(Real* o_matrix) const;
//--------------------------------------------------------------------------
/// \brief This function returns the quaternion as a matrix
/// \return The rotation matrix equivalent
///
Matrix AsMatrix() const;
//--------------------------------------------------------------------------
/// \brief This function extracts a quaternion from the rotations
/// present in a matrix.
/// @param [in] _mat - the input matrix
///
void FromMatrix(const Matrix &_mat);
//--------------------------------------------------------------------------
/// \brief This function converts an axis angle rotation to a quaternion
/// @param [in] _axis - the axis around which the rotation occurs
/// @param [in] _angle - the amount of rotation
///
void FromAxisAngle(const Vector& _axis,const float _angle) ;
//--------------------------------------------------------------------------
/// \brief This function converts a quaternion to an axis angle rotation
/// @param [out] o_axis - the output axis
/// @param [out] o_angle - the output angle.
///
void ToAxisAngle( Vector& o_axis, float &o_angle );
//--------------------------------------------------------------------------
/// \brief This function converts a set of euler angles to a quaternion
/// @param [in] _ax - rotation in x
/// @param [in] _ay - rotation in y
/// @param [in] _az - rotation in z
///
void FromEulerAngles( const float _ax, const float _ay, const float _az );
//--------------------------------------------------------------------------
/// \brief returns the magnitude of the quaternion
/// \return The magnitude of the quaternion
///
Real Mag() const ;
/// \brief test for equality
/// @param [in] _q the quaternion to test against
/// \returns true if the same (based on EPSILON test range) or false
inline bool operator == (
const Quaternion& _q
) const;
//--------------------------------------------------------------------------
/// \brief this function spherically interpolates between two quaternions with respect to t
/// @param [in] _q1 - the first quaternion
/// @param [in] _q2 - the second quaternion
/// @param [in] _t - the interpolating t value
///
friend Quaternion SLERP(
const Quaternion &_q1,
const Quaternion &_q2,
const float &_t
);
//--------------------------------------------------------------------------
/// \brief the streaming operator for the quaternion
/// @param [in] _ifs - the input stream
/// @param [in] _q - the place to read the values into
///
friend std::istream& operator >> (
std::istream& _ifs,
Quaternion &_q
)
{
return _ifs >> _q.m_x >> _q.m_y >> _q.m_z >> _q.m_w;
}
//--------------------------------------------------------------------------
/// \brief the streaming operator for the quaternion
/// @param [in] i_ifs - the input stream
/// @param [in] i_q - the place to read the values into
///
friend std::ostream& operator << (
std::ostream& i_ifs,
Quaternion &i_q
)
{
return i_ifs << i_q.m_x << " " << i_q.m_y << " " << i_q.m_z << " " << i_q.m_w;
}
protected :
/// the quaternion data for x
Real m_x;
/// the quaternion data for y
Real m_y;
/// the quaternion data for z
Real m_z;
/// the quaternion data for w
Real m_w;
}; // end of class
/// \brief If the original rotation was 'orig' and it got rotated to 'qnew',
/// then this function will return the quaternion that will transform
/// you from orig to qnew, ie the difference between the two rotations
///
/* static Quaternion DIFF(const Quaternion& orig, const Quaternion& qnew) {
Quaternion d;
d = -orig * qnew;
return d;
}*/
}
#include "Matrix.h"
#endif
| [
"[email protected]"
] | [
[
[
1,
274
]
]
] |
f3a1d1b5dff2255166e942fa40ee52a16d01c0bf | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/mangalore/fsm/action.cc | 2611bad014c56acc7768c2d946d72d07c9fda17a | [] | no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 595 | cc | //------------------------------------------------------------------------------
// fsm/action.cc
// (C) 2005 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "fsm/action.h"
namespace FSM
{
ImplementRtti(FSM::Action, Foundation::RefCounted);
//------------------------------------------------------------------------------
/**
*/
Action::Action()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
Action::~Action()
{
// empty
}
} // namespace FSM
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
27
]
]
] |
68499a39d6e48478ec00ff5543d27944d09a36c1 | accd6e4daa3fc1103c86d245c784182e31681ea4 | /HappyHunter/Core/ParticleSystem.h | 37e4bdf68e8d90c7d81ca7233d6ee346e2bdb2d3 | [] | no_license | linfuqing/zero3d | d87ad6cf97069aea7861332a9ab8fc02b016d286 | cebb12c37fe0c9047fb5b8fd3c50157638764c24 | refs/heads/master | 2016-09-05T19:37:56.213992 | 2011-08-04T01:37:36 | 2011-08-04T01:37:36 | 34,048,942 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 12,229 | h | #pragma once
#include "Surface.h"
#include "VertexBuffer.h"
#include "SceneNode.h"
namespace zerO
{
template<typename T>
class CParticleSystem :
public CSceneNode
{
public:
typedef T PARTICLEPARAMETERS, * LPPARTICLEPARAMETERS;
typedef struct
{
D3DXVECTOR3 Position;
D3DCOLOR Color;
}PARTICLEVERTEX, * LPPARTICLEVERTEX;
typedef struct PARTICLE
{
PARTICLEPARAMETERS Parameter;
PARTICLEVERTEX Vertex;
CParticleSystem* const pPARENT;
PARTICLE(CParticleSystem* const pParent) :
pPARENT(pParent)
{
}
}PARTICLE, * LPPARTICLE;
//Update
typedef void (*HANDLEPARTICLE)(LPPARTICLE);
typedef bool (*CHECKPARTICLE)(LPPARTICLE);
//Render
typedef UINT (*GETPARTICLEDATA)(const PARTICLE&);
typedef bool (*SETPARTICLEDATA)(const PARTICLE&, PARTICLEVERTEX&);
CParticleSystem(void);
~CParticleSystem(void);
bool Destroy();
CSurface& GetSurface();
void SetNumberEmitedPerFrame(UINT uValue);
bool Create(
UINT uNumEmitedPerFrame,
UINT uMaxNumParticles,
UINT uFlush,
UINT uDiscard,
FLOAT fPointSize,
FLOAT fPointSizeMax,
FLOAT fPointSizeMin,
FLOAT fPointScaleA,
FLOAT fPointScaleB,
FLOAT fPointScaleC,
HANDLEPARTICLE pfnInit,
HANDLEPARTICLE pfnUpdate,
CHECKPARTICLE pfnIsDestroy,
GETPARTICLEDATA pfnGetSteps,
SETPARTICLEDATA pfnSetRenderData);
void UpdateTransform();
bool ApplyForRender();
virtual void Render(CRenderQueue::LPRENDERENTRY pEntry, zerO::UINT32 uFlag);
protected:
typedef struct PARTICLENODE
{
PARTICLE Particle;
PARTICLENODE* pNext;
PARTICLENODE* pRear;
PARTICLENODE(CParticleSystem* const pParent) :
Particle(pParent),
pNext(NULL),
pRear(NULL)
{
}
}PARTICLENODE, * LPPARTICLENODE;
UINT m_uNumEmitedPerFrame;
UINT m_uNumParticles; //当前链表中粒子的数量
UINT m_uMaxNumParticles; //链表中粒子的最大数量
FLOAT m_fPointSize;
FLOAT m_fPointSizeMax;
FLOAT m_fPointSizeMin;
FLOAT m_fPointScaleA;
FLOAT m_fPointScaleB;
FLOAT m_fPointScaleC;
LPPARTICLENODE m_pParticles; //当前粒子链表
LPPARTICLENODE m_pTail;
LPPARTICLENODE m_pParticlesFree;
CVertexBuffer m_VertexBuffer;
UINT m_uBase; //每次填充顶点缓冲区时的起始位置:m_uBase += m_uFlush;
UINT m_uFlush; //一次填充顶点缓冲区的粒子数量
UINT m_uDiscard; //顶点缓冲区能够容纳的最大粒子数量
CSurface m_Surface;
HANDLEPARTICLE m_pfnInit;
HANDLEPARTICLE m_pfnUpdate;
CHECKPARTICLE m_pfnIsDestroy;
GETPARTICLEDATA m_pfnGetSteps;
SETPARTICLEDATA m_pfnSetRenderData;
};
template<typename T>
inline CSurface& CParticleSystem<T>::GetSurface()
{
return m_Surface;
}
template<typename T>
inline void CParticleSystem<T>::SetNumberEmitedPerFrame(UINT uValue)
{
m_uNumEmitedPerFrame = uValue;
}
template<typename T>
CParticleSystem<T>::CParticleSystem() :
m_uNumEmitedPerFrame(0),
m_uNumParticles(0),
m_uMaxNumParticles(0),
m_uBase(0),
m_uFlush(0),
m_fPointSize(0),
m_fPointSizeMax(0),
m_fPointSizeMin(0),
m_fPointScaleA(0),
m_fPointScaleB(0),
m_fPointScaleC(0),
m_uDiscard(0),
m_pfnInit(NULL),
m_pfnUpdate(NULL),
m_pfnIsDestroy(NULL),
m_pfnGetSteps(NULL),
m_pfnSetRenderData(NULL),
m_pParticles(NULL),
m_pTail(NULL),
m_pParticlesFree(NULL)
{
}
template<typename T>
CParticleSystem<T>::~CParticleSystem(void)
{
Destroy();
}
template<typename T>
bool CParticleSystem<T>::Create(
zerO::UINT uNumEmitedPerFrame,
zerO::UINT uMaxNumParticles,
zerO::UINT uFlush,
zerO::UINT uDiscard,
zerO::FLOAT fPointSize,
zerO::FLOAT fPointSizeMax,
zerO::FLOAT fPointSizeMin,
zerO::FLOAT fPointScaleA,
zerO::FLOAT fPointScaleB,
zerO::FLOAT fPointScaleC,
HANDLEPARTICLE pfnInit,
HANDLEPARTICLE pfnUpdate,
CHECKPARTICLE pfnIsDestroy,
GETPARTICLEDATA pfnGetSteps,
SETPARTICLEDATA pfnSetRenderData)
{
m_uNumEmitedPerFrame = uNumEmitedPerFrame;
m_uMaxNumParticles = uMaxNumParticles;
m_uBase = uDiscard;
m_uFlush = uFlush;
m_uDiscard = uDiscard;
m_fPointSize = fPointSize;
m_fPointSizeMax = fPointSizeMax;
m_fPointSizeMin = fPointSizeMin;
m_fPointScaleA = fPointScaleA;
m_fPointScaleB = fPointScaleB;
m_fPointScaleC = fPointScaleC;
m_pfnInit = pfnInit;
m_pfnUpdate = pfnUpdate;
m_pfnIsDestroy = pfnIsDestroy;
m_pfnGetSteps = pfnGetSteps;
m_pfnSetRenderData = pfnSetRenderData;
return m_VertexBuffer.Create(
m_uDiscard,
sizeof(PARTICLEVERTEX),
D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY | D3DUSAGE_POINTS,
D3DPOOL_DEFAULT,
NULL,
D3DFVF_XYZ | D3DFVF_DIFFUSE);
}
template<typename T>
bool CParticleSystem<T>::Destroy()
{
while(m_pParticles)
{
PARTICLENODE* pParticle = m_pParticles;
m_pParticles = pParticle->pNext;
DEBUG_DELETE(pParticle);
}
while(m_pParticlesFree)
{
PARTICLENODE *pParticle = m_pParticlesFree;
m_pParticlesFree = pParticle->pNext;
DEBUG_DELETE(pParticle);
}
return true;
}
template<typename T>
void CParticleSystem<T>::UpdateTransform()
{
CSceneNode::UpdateTransform();
LPPARTICLENODE pParticle, *ppParticle;
//更新已存在粒子的属性值
ppParticle = &m_pParticles; //粒子链表
while( *ppParticle )
{
pParticle = *ppParticle; //取出当前粒子
//更新粒子
m_pfnUpdate(&pParticle->Particle);
//删除死亡粒子
if( m_pfnIsDestroy(&pParticle->Particle) )
{
if(pParticle->pRear)
pParticle->pRear->pNext = pParticle->pNext;
if(pParticle->pNext)
pParticle->pNext->pRear = pParticle->pRear;
if(pParticle == m_pParticles)
m_pParticles = pParticle->pNext;
if(pParticle == m_pTail)
m_pTail = pParticle->pRear;
if(pParticle == m_pTail)
m_pTail = pParticle->pRear;
*ppParticle = pParticle->pNext;
pParticle->pNext = m_pParticlesFree;
pParticle->pRear = NULL;
if(m_pParticlesFree)
m_pParticlesFree->pRear = pParticle;
m_pParticlesFree = pParticle;
m_uNumParticles--;
}
else //准备处理下一个粒子
ppParticle = &pParticle->pNext;
}
//添加新粒子
UINT uEmited = 0;
while( m_uNumParticles < m_uMaxNumParticles && uEmited < m_uNumEmitedPerFrame)
{
if( m_pParticlesFree )
{
pParticle = m_pParticlesFree;
m_pParticlesFree = pParticle->pNext;
pParticle->pNext = NULL;
}
else
{
DEBUG_NEW( pParticle, PARTICLENODE(this) );
}
if(!m_pParticles)
m_pParticles = pParticle;
pParticle->pRear = m_pTail;
if(m_pTail)
m_pTail->pNext = pParticle;
m_pTail = pParticle;
/*pParticle->pNext = m_pParticles;
m_pParticles = pParticle;*/
m_uNumParticles++;
uEmited++;
m_pfnInit(&pParticle->Particle);
}
}
template<typename T>
bool CParticleSystem<T>::ApplyForRender()
{
if( !(m_pfnInit && m_pfnUpdate && m_pfnIsDestroy && m_pfnGetSteps && m_pfnSetRenderData) )
{
DEBUG_WARNING("Particle System had be created.");
return false;
}
CRenderQueue::LPRENDERENTRY pEntry = RENDERQUEUE.LockRenderEntry();
pEntry->uModelType = CRenderQueue::RENDERENTRY::PARTICLE_TYPE;
pEntry->hModel = m_VertexBuffer.GetHandle();
pEntry->hSurface = m_Surface.GetHandle();
pEntry->pParent = this;
RENDERQUEUE.UnLockRenderEntry(pEntry);
return true;
}
inline DWORD FtoDW( zerO::FLOAT f ) { return *((DWORD*)&f); }
template<typename T>
void CParticleSystem<T>::Render(CRenderQueue::LPRENDERENTRY pEntry, zerO::UINT32 uFlag)
{
DEBUG_ASSERT(m_pfnInit && m_pfnUpdate && m_pfnIsDestroy && m_pfnGetSteps && m_pfnSetRenderData, "Particle System had be created.");
HRESULT hr;
DEVICE.SetVertexShader(NULL);
DEVICE.SetPixelShader(NULL);
//DEVICE.SetRenderState( D3DRS_ZWRITEENABLE, false ); //禁用深度缓冲区操作
//DEVICE.SetRenderState( D3DRS_ALPHABLENDENABLE, true ); //启用Alpha 混合
//DEVICE.SetRenderState( D3DRS_SRCBLEND, D3DBLEND_ONE ); //注意Alpha混合方式
//DEVICE.SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ONE );
DEVICE.SetRenderState( D3DRS_POINTSPRITEENABLE, TRUE ); //使用点精灵
DEVICE.SetRenderState( D3DRS_POINTSCALEENABLE, TRUE );
if( TEST_BIT(uFlag, CRenderQueue::MODEL) )
{
//为使用点精灵设置相关渲染状态
DEVICE.SetRenderState( D3DRS_POINTSIZE, FtoDW(m_fPointSize) ); //粒子大小
DEVICE.SetRenderState( D3DRS_POINTSIZE_MAX, FtoDW(m_fPointSizeMax) );
DEVICE.SetRenderState( D3DRS_POINTSIZE_MIN, FtoDW(m_fPointSizeMin) ); //点的最小尺寸
DEVICE.SetRenderState( D3DRS_POINTSCALE_A, FtoDW(m_fPointScaleA) );
DEVICE.SetRenderState( D3DRS_POINTSCALE_B, FtoDW(m_fPointScaleB) );
DEVICE.SetRenderState( D3DRS_POINTSCALE_C, FtoDW(m_fPointScaleC) );
DEVICE.SetTransform( D3DTS_WORLD, &m_WorldMatrix);
DEVICE.SetTransform( D3DTS_VIEW, &CAMERA.GetViewMatrix() );
DEVICE.SetTransform( D3DTS_PROJECTION, &CAMERA.GetProjectionMatrix() );
m_VertexBuffer.Activate(0, 0, true);
}
if( TEST_BIT(uFlag, CRenderQueue::SURFACE) )
m_Surface.Activate();
LPPARTICLENODE pParticle = m_pParticles;
LPPARTICLEVERTEX pVertices;
UINT uNumParticlesToRender = 0;//, uParticleVertexSize = sizeof(PARTICLEVERTEX);
m_uBase += m_uFlush;
if(m_uBase >= m_uDiscard)
m_uBase = 0;
/*hr = m_VertexBuffer.GetBuffer()->Lock(
m_uBase * uParticleVertexSize,
m_uFlush * uParticleVertexSize,
(void**) &pVertices,
m_uBase ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD);
DEBUG_ASSERT(SUCCEEDED(hr), hr);*/
if( !m_VertexBuffer.Lock(m_uBase, m_uFlush, m_uBase ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD, (void**)&pVertices) )
return;
//渲染粒子
while( pParticle )
{
UINT uSteps = m_pfnGetSteps(pParticle->Particle);
//通过对其在不同位置渲染多次来实现模糊效果
for( UINT i = 0; i < uSteps; i++ )
{
if( !m_pfnSetRenderData(pParticle->Particle, *pVertices) )
continue;
pVertices ++;
if( ++ uNumParticlesToRender == m_uFlush ) //填充完毕指定的数据块
{
/*hr = m_VertexBuffer.GetBuffer()->Unlock();
DEBUG_ASSERT(SUCCEEDED(hr), hr);*/
if( !m_VertexBuffer.Unlock() )
return;
hr = DEVICE.DrawPrimitive(D3DPT_POINTLIST, m_uBase, uNumParticlesToRender);
DEBUG_ASSERT(SUCCEEDED(hr), hr);
m_uBase += m_uFlush;
if(m_uBase >= m_uDiscard)
m_uBase = 0;
/*hr = m_VertexBuffer.GetBuffer()->Lock(
m_uBase * uParticleVertexSize,
m_uFlush * uParticleVertexSize,
(void**)&pVertices,
m_uBase ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD);
DEBUG_ASSERT(SUCCEEDED(hr), hr);*/
if( !m_VertexBuffer.Lock(m_uBase, m_uFlush, m_uBase ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD, (void**)&pVertices) )
return;
uNumParticlesToRender = 0; //将需要渲染的顶点数重新置零
} //end if
} //end for
pParticle = pParticle->pNext;
} //end while
// Unlock the vertex buffer
/*hr = m_VertexBuffer.GetBuffer()->Unlock();*/
if( !m_VertexBuffer.Unlock() )
return;
/*DEBUG_ASSERT(SUCCEEDED(hr), hr);*/
//渲染剩余不足一块的粒子
if(uNumParticlesToRender)
{
hr = DEVICE.DrawPrimitive(D3DPT_POINTLIST, m_uBase, uNumParticlesToRender);
DEBUG_ASSERT(SUCCEEDED(hr), hr);
}
//恢复渲染状态
DEVICE.SetRenderState(D3DRS_POINTSPRITEENABLE, FALSE);
DEVICE.SetRenderState(D3DRS_POINTSCALEENABLE, FALSE);
DEVICE.SetRenderState(D3DRS_ZWRITEENABLE, true);
DEVICE.SetRenderState(D3DRS_ALPHABLENDENABLE, false);
}
}
| [
"[email protected]"
] | [
[
[
1,
461
]
]
] |
880ddd304a62a5fc31efeeacde7c66d84285c92d | 777399eafeb952743fcb973fbba392842c2e9b14 | /CyberneticWarrior/CyberneticWarrior/source/CSeekerDrone.cpp | fee66ee14bf6f7ff095175fc35ea63f167d64e73 | [] | no_license | Warbeleth/cyberneticwarrior | 7c0af33ada4d461b90dc843c6a25cd5dc2ba056a | 21959c93d638b5bc8a881f75119d33d5708a3ea9 | refs/heads/master | 2021-01-10T14:31:27.017284 | 2010-11-23T23:16:28 | 2010-11-23T23:16:28 | 53,352,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,406 | cpp | #include "PrecompiledHeader.h"
#include "CSeekerDrone.h"
#include "CCamera.h"
#include "CGame.h"
#include "CMapLoad.h"
CSeekerDrone::CSeekerDrone()
{
}
CSeekerDrone::CSeekerDrone(int nImageID, float PosX, float PosY,int Width, int Height, int nState, float fCurrentPatrolDistance,
int nMaxHP, int nCurrentHP, int nSightRange, int nAttackRange, int nGlobalType, float fRateOfFire,
float fSpeed) : CPatrolEnemy(nState, fCurrentPatrolDistance,
float(nSightRange + 100) /*max patrol distance*/, nGlobalType, nImageID, nMaxHP, nCurrentHP, nSightRange,
nAttackRange, fRateOfFire, fSpeed, PosX, PosY, Width, Height)
{
SetAnimations(CMapLoad::GetInstance()->CreateAnimation(Drone_Seeker));
GetAnimations()->SetCurrentAnimation(0);
}
CSeekerDrone::~CSeekerDrone()
{
}
void CSeekerDrone::Update(float fElapsedTime)
{
CPatrolEnemy::Update(fElapsedTime);
switch(ReturnAIState())
{
case Patrol:
GetAnimations()->SetCurrentAnimation(0);
break;
case pActive:
GetAnimations()->SetCurrentAnimation(0);
break;
case pDead:
ReleaseSpawner();
CGame::GetInstance()->GetMessageSystemPointer()->SendMsg(new CDestroyEnemyMessage((CBaseEnemy*)this));
break;
};
}
void CSeekerDrone::Render()
{
CPatrolEnemy::Render();
int OffsetX = CCamera::GetInstance()->GetOffsetX();
int OffsetY = CCamera::GetInstance()->GetOffsetY();
} | [
"[email protected]",
"atmuccio@d49f6b0b-9fae-41b6-31ce-67b77e794db9"
] | [
[
[
1,
7
],
[
9,
18
],
[
21,
30
],
[
32,
32
],
[
40,
41
],
[
44,
53
]
],
[
[
8,
8
],
[
19,
20
],
[
31,
31
],
[
33,
39
],
[
42,
43
]
]
] |
5f80f52df4aad9f18926377b37d9ee8cab2e5a07 | e02fa80eef98834bf8a042a09d7cb7fe6bf768ba | /TEST_MyGUI_Source/LayoutEditor/WidgetContainer.cpp | 5346fa077bc47966b66f80a5d5d153390edcdadb | [] | no_license | MyGUI/mygui-historical | fcd3edede9f6cb694c544b402149abb68c538673 | 4886073fd4813de80c22eded0b2033a5ba7f425f | refs/heads/master | 2021-01-23T16:40:19.477150 | 2008-03-06T22:19:12 | 2008-03-06T22:19:12 | 22,805,225 | 2 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 9,944 | cpp | #include "WidgetContainer.h"
#include "BasisManager.h"
const std::string LogSection = "LayoutEditor";
INSTANCE_IMPLEMENT(EditorWidgets);
void EditorWidgets::initialise()
{
global_counter = 0;
}
void EditorWidgets::shutdown()
{
for (std::vector<WidgetContainer*>::iterator iter = widgets.begin(); iter != widgets.end(); ++iter) delete *iter;
widgets.clear();
}
bool EditorWidgets::load(std::string _fileName)
{
std::string _instance = "Editor";
MyGUI::xml::xmlDocument doc;
std::string file(MyGUI::helper::getResourcePath(_fileName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME));
if (file.empty())
{
if (false == doc.open(_fileName)) {
LOGGING(LogSection, Error, _instance << " : '" << _fileName << "' not found");
return false;
}
}
else if (false == doc.open(file))
{
LOGGING(LogSection, Error, _instance << " : " << doc.getLastError());
return false;
}
MyGUI::xml::xmlNodePtr root = doc.getRoot();
if ( (null == root) || (root->getName() != "MyGUI") ) {
LOGGING(LogSection, Error, _instance << " : '" << _fileName << "', tag 'MyGUI' not found");
return false;
}
std::string type;
if (root->findAttribute("type", type)) {
if (type == "Layout")
{
// берем детей и крутимся
MyGUI::xml::xmlNodeIterator widget = root->getNodeIterator();
while (widget.nextNode("Widget")) parseWidget(widget, 0);
}
}
return true;
}
bool EditorWidgets::save(std::string _fileName)
{
std::string _instance = "Editor";
MyGUI::xml::xmlDocument doc;
std::string file(MyGUI::helper::getResourcePath(_fileName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME));
if (file.empty()) {
file = _fileName;
}
doc.createInfo();
MyGUI::xml::xmlNodePtr root = doc.createRoot("MyGUI");
root->addAttributes("type", "Layout");
for (std::vector<WidgetContainer*>::iterator iter = widgets.begin(); iter != widgets.end(); ++iter)
{
// в корень только сирот
if (null == (*iter)->widget->getParent()) serialiseWidget(*iter, root);
}
if (false == doc.save(file)) {
LOGGING(LogSection, Error, _instance << " : " << doc.getLastError());
return false;
}
return true;
}
void EditorWidgets::loadxmlDocument(MyGUI::xml::xmlDocument * doc)
{
MyGUI::xml::xmlNodePtr root = doc->getRoot();
std::string type;
if (root->findAttribute("type", type)) {
if (type == "Layout")
{
// берем детей и крутимся
MyGUI::xml::xmlNodeIterator widget = root->getNodeIterator();
while (widget.nextNode("Widget")) parseWidget(widget, 0);
}
}
}
MyGUI::xml::xmlDocument * EditorWidgets::savexmlDocument()
{
MyGUI::xml::xmlDocument * doc = new MyGUI::xml::xmlDocument();
doc->createInfo();
MyGUI::xml::xmlNodePtr root = doc->createRoot("MyGUI");
root->addAttributes("type", "Layout");
for (std::vector<WidgetContainer*>::iterator iter = widgets.begin(); iter != widgets.end(); ++iter)
{
// в корень только сирот
if (null == (*iter)->widget->getParent()) serialiseWidget(*iter, root);
}
return doc;
}
void EditorWidgets::add(WidgetContainer * _container)
{
widgets.push_back(_container);
}
void EditorWidgets::remove(MyGUI::WidgetPtr _widget)
{
// дети вперед
MyGUI::VectorWidgetPtr childs = _widget->getChilds();
for (MyGUI::VectorWidgetPtr::iterator iter = childs.begin(); iter != childs.end(); ++iter)
{
if (null != find(*iter)) remove(*iter);
}
WidgetContainer * _container = find(_widget);
MyGUI::Gui::getInstance().destroyWidget(_widget);
if (null != _container)
{
widgets.erase(std::find(widgets.begin(), widgets.end(), _container));
delete _container;
}
}
void EditorWidgets::clear()
{
while (!widgets.empty())
{
remove(widgets[widgets.size()-1]->widget);
}
}
WidgetContainer * EditorWidgets::find(MyGUI::WidgetPtr _widget)
{
for (std::vector<WidgetContainer*>::iterator iter = widgets.begin(); iter != widgets.end(); ++iter)
{
if ((*iter)->widget == _widget)
{
return *iter;
}
}
return null;
}
WidgetContainer * EditorWidgets::find(std::string _name)
{
if (_name.empty()) return null;
for (std::vector<WidgetContainer*>::iterator iter = widgets.begin(); iter != widgets.end(); ++iter)
{
if ((*iter)->name == _name)
{
return *iter;
}
}
return null;
}
void EditorWidgets::parseWidget(MyGUI::xml::xmlNodeIterator & _widget, MyGUI::WidgetPtr _parent)
{
WidgetContainer * container = new WidgetContainer();
// парсим атрибуты виджета
MyGUI::IntCoord coord;
MyGUI::Align align = MyGUI::ALIGN_DEFAULT;
_widget->findAttribute("name", container->name);
_widget->findAttribute("type", container->type);
_widget->findAttribute("skin", container->skin);
_widget->findAttribute("layer", container->layer);
if (_widget->findAttribute("align", container->align)) align = MyGUI::SkinManager::getInstance().parseAlign(container->align);
if (_widget->findAttribute("position", container->position)) coord = MyGUI::IntCoord::parse(container->position);
if (_widget->findAttribute("position_real", container->position_real)) coord = MyGUI::Gui::getInstance().convertRelativeToInt(MyGUI::FloatCoord::parse(container->position_real), _parent);
// в гуе на 2 одноименных виджета ругается и падает, а у нас будет просто переименовывать
if (false == container->name.empty())
{
WidgetContainer * iter = find(container->name);
if (null != iter)
{
static long renameN=0;
std::string mess = MyGUI::utility::toString("widget with same name name '", container->name, "'. Renamed to '", container->name, renameN, "'.");
LOGGING(LogSection, Warning, mess);
MyGUI::Message::_createMessage("Warning", mess, "", "LayoutEditor_Popup", true, null, MyGUI::Message::IconWarning | MyGUI::Message::Ok);
container->name = MyGUI::utility::toString(container->name, renameN++);
}
}
std::string tmpname = container->name;
if (tmpname.empty())
{
tmpname = MyGUI::utility::toString(container->type, global_counter);
global_counter++;
}
//может и не стоит
tmpname = "LayoutEditor_" + tmpname;
if (null == _parent) {
container->widget = MyGUI::Gui::getInstance().createWidgetT(container->type, container->skin, coord, align, container->layer, tmpname);
add(container);
}
else
{
container->widget = _parent->createWidgetT(container->type, container->skin, coord, align, tmpname);
add(container);
}
// берем детей и крутимся
MyGUI::xml::xmlNodeIterator widget = _widget->getNodeIterator();
while (widget.nextNode()) {
std::string key, value;
if (widget->getName() == "Widget") parseWidget(widget, container->widget);
else if (widget->getName() == "Property") {
// парсим атрибуты
if (false == widget->findAttribute("key", key)) continue;
if (false == widget->findAttribute("value", value)) continue;
// и парсим свойство
try{
if (("Message_Modal" != key) && ("Window_AutoAlpha" != key) && ("Window_Snap" != key))
MyGUI::WidgetManager::getInstance().parse(container->widget, key, value);
Ogre::Root::getSingleton().renderOneFrame();
}
catch(...)
{
MyGUI::Message::_createMessage("Warning", "No such " + key + ": '" + value + "'", "", "LayoutEditor_Popup", true, null, MyGUI::Message::IconWarning | MyGUI::Message::Ok);
if (key == "Image_Texture") MyGUI::WidgetManager::getInstance().parse(container->widget, key, "");
}// for incorrect meshes or textures
container->mProperty.push_back(std::make_pair(key, value));
}
else if (widget->getName() == "UserString") {
// парсим атрибуты
if (false == widget->findAttribute("key", key)) continue;
if (false == widget->findAttribute("value", value)) continue;
container->mUserString.insert(std::make_pair(key, value));
}
};
}
void EditorWidgets::serialiseWidget(WidgetContainer * _container, MyGUI::xml::xmlNodePtr _node)
{
MyGUI::xml::xmlNodePtr node = _node->createChild("Widget");
node->addAttributes("type", _container->type);
if ("" != _container->skin) node->addAttributes("skin", _container->skin);
if ("" != _container->position) node->addAttributes("position", _container->position);
if ("" != _container->position_real) node->addAttributes("position_real", _container->position_real);
if ("" != _container->align) node->addAttributes("align", _container->align);
if ("" != _container->layer) node->addAttributes("layer", _container->layer);
if ("" != _container->name) node->addAttributes("name", _container->name);
for (StringPairs::iterator iter = _container->mProperty.begin(); iter != _container->mProperty.end(); ++iter)
{
MyGUI::xml::xmlNodePtr nodeProp = node->createChild("Property");
nodeProp->addAttributes("key", iter->first);
nodeProp->addAttributes("value", iter->second);
}
for (MapString::iterator iter = _container->mUserString.begin(); iter != _container->mUserString.end(); ++iter)
{
MyGUI::xml::xmlNodePtr nodeProp = node->createChild("UserString");
nodeProp->addAttributes("key", iter->first);
nodeProp->addAttributes("value", iter->second);
}
// метод медленный, т.к. квадратичная сложность
for (std::vector<WidgetContainer*>::iterator iter = widgets.begin(); iter != widgets.end(); ++iter)
{
MyGUI::WidgetPtr parent = (*iter)->widget->getParent();
// сынок - это ты?
if (_container->widget->getWidgetType() == "Window"){
if (null != parent)
if (_container->widget == parent->getParent()) serialiseWidget(*iter, node);
}else if (_container->widget == parent) serialiseWidget(*iter, node);
}
}
| [
"[email protected]"
] | [
[
[
1,
295
]
]
] |
54eae5133f1e0edd83d421507f9b497e9c78bf1a | 6b69ffde6fd67f5bdfd4f51d41feb7b8cf5aefe4 | /TouchControl/View/Widgets/ValueButton.h | c314160a95a84cd55ff52d2bc159602df1238a23 | [] | no_license | mkrentovskiy/qttswidgetexample | e59a8303d0003d8c2b8178e9cce1adf4b2d6960a | 745ffa2ca206ca74451e7b2087f8b408ad2192e5 | refs/heads/master | 2020-08-08T20:13:37.251389 | 2008-05-05T09:01:22 | 2008-05-05T09:01:22 | 32,144,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | h | #ifndef VALUEBUTTON_H_
#define VALUEBUTTON_H_
#include <QWidget>
#include <QAbstractButton>
#include <QDomDocument>
#include <QPixmap>
#include <QHash>
#include <QFont>
#include <QPen>
#include "../WidgetFabric.h"
#include "../../Variables.h"
/*
* - Почему не снаследовано как в предыдущей версии?
* - Мало ли...
*/
class ValueButton : public QAbstractButton
{
Q_OBJECT
public:
ValueButton(QWidget *, WidgetControl *, QDomElement &, QDomElement &, WidgetFabric *);
void setState(QString s) { state = s; repaint(); };
void setLabel(QString l) { label = l; repaint(); };
signals:
void idClicked(QString);
protected slots:
void isClicked() { emit idClicked(id); };
protected:
QString id;
virtual void paintEvent(QPaintEvent *event);
private:
QHash<QString, QPixmap> states;
QString state;
QString label;
QPen pen;
int x;
int y;
int w;
int h;
};
#endif /*VALUEBUTTON_H_*/
| [
"mkrentovskiy@2d1e7c9e-774c-0410-a78d-1fc8eb1d9a0d"
] | [
[
[
1,
55
]
]
] |
780a447a80e649a82c1b7fc9e1870b19ee3f9bba | 0dfa7f23c2384251443da0cb129f79e3ea4d6b52 | /Player.cpp | 1339359cc7ff589a122bcfc543ebfb351ac0da12 | [] | no_license | TeamFirst/Galcon | b908a1df4e161b3e726084a6e8054cbfa95d3ec4 | f7ccb7f0bb27820d2246529a577be2e89de248e4 | refs/heads/master | 2020-12-25T15:40:04.411443 | 2011-06-14T14:25:38 | 2011-06-14T14:25:38 | 1,810,650 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 728 | cpp | #include "Player.h"
CPlayer::CPlayer(unsigned short i_id, std::string i_name): m_id(i_id), m_name(i_name)
{
m_army = 0;
m_fleetArmy = 0;
}
unsigned short CPlayer::GetId() const
{
return m_id;
}
std::string CPlayer::GetName() const
{
return m_name;
}
unsigned long CPlayer::GetArmy() const
{
return m_army;
}
unsigned long CPlayer::GetFleetArmy() const
{
return m_fleetArmy;
}
void CPlayer::SetArmy(const unsigned long army)
{
m_army += army;
}
void CPlayer::NullArmy()
{
m_army = 0;
}
void CPlayer::AddFleetArmy(const unsigned long army)
{
m_fleetArmy += army;
}
void CPlayer::RemoveFleetArmy(const unsigned long army)
{
m_fleetArmy -= army;
}
| [
"[email protected]"
] | [
[
[
1,
46
]
]
] |
7d85939a2a25c74fc4568b4fd668db94647d79ad | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/core/Crypt.h | f245bc93e9d52609f5c7d7235103f6644fa58f1a | [
"BSD-3-Clause"
] | permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,435 | h | //////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright © 2008, mC2 team
//
// 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 author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
#include <core/config.h>
//////////////////////////////////////////////////////////////////////////////
namespace musik{ namespace core{
//////////////////////////////////////////////////////////////////////////////
class Crypt{
public:
static std::string GenerateSalt();
static std::string StaticSalt();
static std::string Encrypt(std::string cryptContent,std::string salt);
};
//////////////////////////////////////////////////////////////////////////////
} }
//////////////////////////////////////////////////////////////////////////////
| [
"onnerby@6a861d04-ae47-0410-a6da-2d49beace72e",
"urioxis@6a861d04-ae47-0410-a6da-2d49beace72e"
] | [
[
[
1,
45
],
[
47,
56
]
],
[
[
46,
46
]
]
] |
983593337c24aa6df1f380d45be2647eff30ac87 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/testpthreadonce/src/tpthreadoncecases.cpp | 5582a8334839e6c1cf0e089b5871ecedea49a7d6 | [] | no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,854 | cpp | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#include "tpthreadonce.h"
void ResetVar();
extern "C" void IncVar(void);
void DelVar();
char ReadVar();
int (*fp)(void* arg);
int func(void* arg);
// -----------------------------------------------------------------------------
// ResetVar resets shared variable with persistance storage
void ResetVar()
{
FILE* file = fopen("C:\\pthread_once.tst", "w");
if(file)
{
char a =0;
fwrite(&a,1,1,file);
}
fclose(file);
}
// -----------------------------------------------------------------------------
// IncVar increments the shared variable
extern "C" void IncVar(void)
{
char a=0;
FILE* file = fopen("C:\\pthread_once.tst", "r+");
if(file)
{
fread(&a,1,1,file);
fclose(file);
}
file = fopen("C:\\pthread_once.tst", "r+");
if(file)
{
a++;
fwrite(&a,1,1,file);
fclose(file);
}
};
// -----------------------------------------------------------------------------
// DelVar deletes the shared variable
void DelVar()
{
unlink("C:\\pthread_once.tst");
}
// -----------------------------------------------------------------------------
// ReadVar read the current value of the shared variable
char ReadVar()
{
char a = 0;
FILE* file = fopen("C:\\pthread_once.tst", "r+");
if(file)
{
fread(&a,1,1,file);
}
fclose(file);
return a;
}
int CallOnce(ThreadData* aThreadData,void* iArgument)
{
int retval=0;
void (*pOnceFn)(void) = NULL;
pOnceFn = (void (*)(void) ) iArgument;
retval = pthread_once(&(aThreadData->iCommonData->iOnceControl), pOnceFn);
return retval;
}
int VerifyResult(ThreadData* aThreadData,int expectedResult)
{
int retval=0;
if ( (expectedResult == aThreadData->iRetValue) && (aThreadData->iExpectederrno == aThreadData->ierrno) )
{
errno = 0;
}
else
{
#ifdef WINDOWS
printf("Expected retval %d Seen %d Expected errno %d Seen %d\n",expectedResult, aThreadData->iRetValue,aThreadData->iExpectederrno,aThreadData->ierrno);
#else
;
#endif
retval = 0;
}
aThreadData->iRetValue = 0;
aThreadData->ierrno = 0;
return retval;
}
int ThreadCreate(ThreadData* aThreadData, void* aThreadId)
{
HarnessThread threadId;
int retval=0;
if(aThreadData->iSelf != EThreadMain)
{
retval = KNoPermission;
}
else
{
threadId = (HarnessThread)(int) aThreadId;
retval = NewThread(aThreadData,threadId);
}
return retval;
}
int NewThread(ThreadData* aThreadData, HarnessThread aThreadId)
{
ThreadData* newData = new ThreadData;
if(!newData)
{
return KNoMemory;
}
if(aThreadId < EThreadMain && aThreadId >= 0)
{
aThreadData->iTDArr[aThreadId] = newData;
}
else
{
return KNoArgument;
}
newData->iSignalSemaphore = aThreadData->iSignalSemaphore;
newData->iSuspendSemaphore = aThreadData->iSuspendSemaphore;
newData->iTestSemaphore = aThreadData->iTestSemaphore;
newData->iTestMutex = aThreadData->iTestMutex;
newData->iTestCondVar = aThreadData->iTestCondVar;
newData->iDefaultAttr = aThreadData->iDefaultAttr;
newData->iErrorcheckAttr = aThreadData->iErrorcheckAttr;
newData->iRecursiveAttr = aThreadData->iRecursiveAttr;
newData->iCondAttr = aThreadData->iCondAttr;
newData->iSuspending = false;
newData->iSpinCounter = 0;
newData->iCurrentCommand = -1;
newData->iSelf = aThreadId;
newData->iValue = 0;
newData->iRetValue = 0;
newData->ierrno = 0;
newData->iValue = 0;
newData->iExpectederrno = 0;
newData->iTimes = 0;
newData->iStopped = false;
newData->iCommonData = aThreadData->iCommonData;
#ifdef USE_RTHREAD
TBuf<10> threadName;
threadName.NumFixedWidth(TUint(aThreadId), EDecimal, 10);
RThread lNewThread;
lNewThread.Create(
(const TDesC &)threadName, // Thread Name
_mrtEntryPtFun, // Entry pt function
KDefaultStackSize, // Stack Size
NULL, // Use common heap
(TAny*)newData); // Args to entry pt function
lNewThread.Resume();
lNewThread.Close();
#else
pthread_create(&aThreadData->iIdArr[aThreadId],NULL,StartFn,(void*)newData);
#endif
return 0;
}
void StopThread(ThreadData* aThreadData)
{
if(aThreadData->iSelf != EThreadMain)
{
aThreadData->iStopped = true;
sem_post(aThreadData->iSuspendSemaphore);
#ifdef USE_RTHREAD
User::Exit(KErrNone);
#endif
}
}
int DeleteThread(ThreadData* aThreadData, HarnessThread aThreadId)
{
#ifndef USE_RTHREAD
pthread_join(aThreadData->iIdArr[aThreadId],NULL);
#else
int signalsEaten = 0;
sem_wait(aThreadData->iSuspendSemaphore);
while(aThreadData->iTDArr[aThreadId]->iStopped == false)
{
signalsEaten++;
sem_wait(aThreadData->iSuspendSemaphore);
}
for(int i=0; i<signalsEaten; i++)
{
sem_post(aThreadData->iSuspendSemaphore);
}
#endif
if(aThreadData->iTDArr[aThreadId]->iRetValue != 0)
{
printf("Thread %d errvalue %d\n",aThreadId,aThreadData->iTDArr[aThreadId]->iRetValue);
}
delete aThreadData->iTDArr[aThreadId];
aThreadData->iTDArr[aThreadId] = NULL;
return 0;
}
int ThreadDestroy(ThreadData* aThreadData,void* aThreadId)
{
int retval=0;
HarnessThread threadId;
if(aThreadData->iSelf != EThreadMain)
{
retval = KNoPermission;
}
else
{
threadId = (HarnessThread)(int) aThreadId;
retval = DeleteThread(aThreadData,threadId);
}
return retval;
}
void* StartFn(void* arg)
{
int retval=0;
retval = (*fp)(arg);
return (void *)retval;
}
int func(void* arg)
{
int retval=0;
ThreadData* pData = (ThreadData*) arg;
retval = CallOnce(pData,(void*) IncVar);
if(retval == 0)
{
StopThread(pData);
}
return retval;
}
TInt CTestPthreadonce::TestFramework()
{
int retval = 0;
ResetVar();
if(ReadVar() != 0)
{
retval+= 1;
}
IncVar();
IncVar();
IncVar();
if(ReadVar() != 3)
{
retval+= 1;
}
ResetVar();
IncVar();
if(ReadVar() != 1)
{
retval+= 1;
}
return -retval;
}
//1_6_2_1682 pthread_once called with NULL as pointer to the once_control_t structure
TInt CTestPthreadonce::TestOnce1682()
{
if(pthread_once(NULL,IncVar) != EINVAL)
{
return -1;
}
return KErrNone;
}
//pthread_once called with pthread_once_control_t structure not statically initialized"
TInt CTestPthreadonce::TestOnce324()
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
ResetVar();
retval = CallOnce(&lThreadData,(void*) IncVar);
retval = VerifyResult(&lThreadData,EINVAL);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
//pthread_once called with NULL value for init_routine
TInt CTestPthreadonce::TestOnce325()
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
ResetVar();
lThreadData.iCommonData->iOnceControl = PTHREAD_ONCE_INIT;
retval = CallOnce(&lThreadData,(void*) NULL);
retval = VerifyResult(&lThreadData,EINVAL);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
//pthread_once called for the 1st time by any thread
TInt CTestPthreadonce::TestOnce326()
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
ResetVar();
lThreadData.iCommonData->iOnceControl = PTHREAD_ONCE_INIT;
retval = CallOnce(&lThreadData,(void*) IncVar);
retval = VerifyResult(&lThreadData,0);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
//pthread_once called by any thread after 1st invocation
TInt CTestPthreadonce::TestOnce327()
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
ResetVar();
lThreadData.iCommonData->iOnceControl = PTHREAD_ONCE_INIT;
retval = CallOnce(&lThreadData,(void*) IncVar);
retval = CallOnce(&lThreadData,(void*) IncVar);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
//pthread_once called with different once_control_t structure
TInt CTestPthreadonce::TestOnce328()
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
ResetVar();
lThreadData.iCommonData->iOnceControl = PTHREAD_ONCE_INIT;
retval = CallOnce(&lThreadData,(void*) IncVar);
pthread_once_t lOnce = PTHREAD_ONCE_INIT;
pthread_once(&lOnce,IncVar);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
//race to call pthread_once while pthread_once_control_t state is _ENotDone
TInt CTestPthreadonce::TestOnce329()
{
int retval = 0;
int errsum=0, err = 0;
ThreadData lThreadData;
sem_t lSignalSemaphore;
sem_t lSuspendSemaphore;
sem_t lTestSemaphore;
pthread_mutex_t lTestMutex;
pthread_cond_t lTestCondVar;
pthread_condattr_t lCondAttr;
pthread_mutexattr_t lTestMutexAttr;
pthread_mutexattr_t defaultattr;
pthread_mutexattr_t errorcheckattr;
pthread_mutexattr_t recursiveattr;
pthread_mutexattr_init(&defaultattr);
pthread_mutexattr_init(&errorcheckattr);
pthread_mutexattr_init(&recursiveattr);
pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER;
CommonData lCommonData;
lCommonData.iStaticMutex = &l_staticmutex;
lCommonData.iErrorCheckMutex = &l_errorcheckmutex;
lCommonData.iRecursiveMutex = &l_recursivemutex;
lCommonData.iStaticCondVar = &l_staticcondvar;
retval = sem_init(&lSignalSemaphore,0,0);
if(retval != 0)
{
return retval;
}
retval = sem_init(&lSuspendSemaphore,0,0);
if(retval != 0)
{
return retval;
}
lThreadData.iSignalSemaphore = &lSignalSemaphore;
lThreadData.iSuspendSemaphore = &lSuspendSemaphore;
lThreadData.iTestSemaphore = &lTestSemaphore;
lThreadData.iTestMutex = &lTestMutex;
lThreadData.iTestMutexAttr = &lTestMutexAttr;
lThreadData.iTestCondVar = &lTestCondVar;
lThreadData.iDefaultAttr = &defaultattr;
lThreadData.iErrorcheckAttr = &errorcheckattr;
lThreadData.iRecursiveAttr = &recursiveattr;
lThreadData.iCondAttr = &lCondAttr;
for (int loop = 0; loop < EThreadMain; loop++)
{
g_spinFlag[loop] = true;
}
lThreadData.iSuspending = false;
lThreadData.iSpinCounter = 0;
lThreadData.iCurrentCommand = -1;
lThreadData.iSelf = EThreadMain;
lThreadData.iValue = 0;
lThreadData.iRetValue = 0;
lThreadData.ierrno = 0;
lThreadData.iExpectederrno = 0;
lThreadData.iTimes = 0;
lThreadData.iStopped = false;
lThreadData.iCommonData = &lCommonData;
ResetVar();
lThreadData.iCommonData->iOnceControl = PTHREAD_ONCE_INIT;
fp=func;
retval = ThreadCreate(&lThreadData, (void*) EThread1);
fp=func;
retval = ThreadCreate(&lThreadData, (void*) EThread2);
fp=func;
retval = ThreadCreate(&lThreadData, (void*) EThread3);
fp=func;
retval = ThreadCreate(&lThreadData, (void*) EThread4);
fp=func;
retval = ThreadCreate(&lThreadData, (void*) EThread5);
retval = ThreadDestroy(&lThreadData, (void*) EThread1);
retval = ThreadDestroy(&lThreadData, (void*) EThread2);
retval = ThreadDestroy(&lThreadData, (void*) EThread3);
retval = ThreadDestroy(&lThreadData, (void*) EThread4);
retval = ThreadDestroy(&lThreadData, (void*) EThread5);
err = pthread_cond_destroy(&l_staticcondvar);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_recursivemutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_errorcheckmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutex_destroy(&l_staticmutex);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&recursiveattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&errorcheckattr);
if(err != EINVAL)
{
errsum += err;
}
err = pthread_mutexattr_destroy(&defaultattr);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSignalSemaphore);
if(err != EINVAL)
{
errsum += err;
}
err = sem_destroy(&lSuspendSemaphore);
if(err != EINVAL)
{
errsum += err;
}
return retval+errsum;
}
| [
"none@none"
] | [
[
[
1,
1115
]
]
] |
b0ff5fa8b32233a8e13033a855cffbd8b1bf626a | 10bac563fc7e174d8f7c79c8777e4eb8460bc49e | /splam/detail/pmap_wrap.cpp | 662f386b2e7c1605f173a446bcecde3480a9b0f0 | [] | no_license | chenbk85/alcordev | 41154355a837ebd15db02ecaeaca6726e722892a | bdb9d0928c80315d24299000ca6d8c492808f1d5 | refs/heads/master | 2021-01-10T13:36:29.338077 | 2008-10-22T15:57:50 | 2008-10-22T15:57:50 | 44,953,286 | 0 | 1 | null | null | null | null | ISO-8859-13 | C++ | false | false | 5,470 | cpp | #define WIN32_LEAN_AND_MEAN
#include "pmap_wrap.h"
#include "conversion.hpp"
#include "alcor/core/iniWrapper.h"
#include <fstream>
//-----------------------------------------------------------------------------------------------
using namespace all::math;
using namespace all::util;
//-----------------------------------------------------------------------------------------------
namespace all{
namespace splam{
pmap_wrap::pmap_wrap(const char* name)
{
iniWrapper w(name);
/** parametri contenuti nel file ini per allocare le mappe */
laser_scan_number_= w.GetInt("laser:num_step",0);
double r_max= w.GetDouble("laser:raggio_max",0.0);
double r_res = w.GetDouble("mappa:dim_cella",0.0);
int n_camp= w.GetInt("mappa:num_camp",0);
double r_start = w.GetDouble("laser:start_angle",0.0);
double r_step = w.GetDouble("laser:angle_step", 0.0);
double larg = w.GetDouble("mappa:larghezza",0.0);
double alt = w.GetDouble("mappa:altezza",0.0);
//std::cout << "SPAAAAAAAAAAAAAAAAAM: "<<laser_scan_number_ << " " << r_max << " " << r_res << " " << n_camp << " " << r_start << " " << r_step
// << " " << larg << " " << alt << std::endl;
/** Alloca la memoria per omap_, pmap_, lodo_*/
pmap_ = pmap_alloc(laser_scan_number_, r_max, r_start, r_step, n_camp, larg*r_res, alt*r_res, r_res);
lodo_ = lodo_alloc(laser_scan_number_, r_max, r_res, r_start, r_step);
omap_ = omap_alloc(laser_scan_number_, r_max, r_start, r_step, larg*r_res, alt*r_res, r_res);
laser_scan_data_ = new double[laser_scan_number_];
offset_laser_pose_.set_x1(w.GetDouble("laser:offset_x",0.0));
offset_laser_pose_.set_x2(w.GetDouble("laser:offset_y",0.0));
offset_laser_pose_.set_th(w.GetDouble("laser:offset_th",0.0),deg_tag);
}
/*
Il distruttore della classe pensa a deallocare la memoria di lodo_, pmap_ e omap_*/
pmap_wrap::~pmap_wrap()
{
lodo_free(lodo_);
pmap_free(pmap_);
omap_free(omap_);
delete[] laser_scan_data_;
}
/*
La funzione GetPosition()restituisce la posizione del campione che in quel momento risulta migliore,
per fare ciņ indicizza il puntatore alla struttura dei campioni di pmap_ sul campione miglire e dopo
copia la posizione corrispondente nella variabile privata di pmap_wrap corrpose.
*/
pose2d pmap_wrap::get_current_position() const
{
pmap_sample_t* campione=PMAP_GET_SAMPLE(pmap_,pmap_->best_sample);
return pose2_t_to_pose2d(campione->pose);
}
/**
* Function fill_slam_data fills the splam_data object passed ad a shared pointer.
* Not all splam_data object can be filled by pmap_wrap... what is filled here is:
* 1)
*/
void pmap_wrap::fill_slam_data(splam_data_ptr data)
{
pmap_sample_t* best_sample;
pmap_scan_t* scann;
pose2_t pose_slap;
//std::cout << "pmap_wrap::fill_slam_data......... FASE 1"<<std::endl;
//Best sample
best_sample = PMAP_GET_SAMPLE(pmap_, pmap_->best_sample);
//std::cout << "pmap_wrap::fill_slam_data......... FASE 2"<<std::endl;
//Realizzo una occupancy grid con i dati della posizione e della scansione del
//campione migliore
omap_clear(omap_);
data->path_.clear();
data->path_.push_back(pose2d(0,0,0,deg_tag));
data->og_cells_.resize(omap_->grid_sx * omap_->grid_sy, 0);
data->path_.reserve(pmap_->step_count);
//std::ofstream filazzo("ceppaflex.txt", std::ios::out);
//std::cout << "pmap_wrap::fill_slam_data......... FASE 3"<<std::endl;
for (int j = 0; j < pmap_->step_count; ++j)
{
scann = pmap_->scans + j;
pose_slap = best_sample->poses[j];
omap_add(omap_, pose_slap, pmap_->num_ranges, scann->ranges);
data->path_.push_back(pose2_t_to_pose2d(pose_slap));
//for(int z=0; z<pmap_->num_ranges; z++)
// filazzo << " "<<scann->ranges[z];
//filazzo<<std::endl<<std::endl;
}
//std::cout << "pmap_wrap::fill_slam_data......... FASE 4"<<std::endl;
for (int i=0; i< omap_->grid_size; ++i)
{
data->og_cells_.at(i)= omap_->grid[i];
//filazzo<< static_cast<int>(omap_->grid[i])<< " ";
}
data->og_resolution_ = omap_->grid_res;
data->og_col_ = omap_->grid_sx;
data->og_row_ = omap_->grid_sy;
//std::cout << "pmap_wrap::fill_slam_data......... FASE 5"<<std::endl;
#if 1
static int contazzo=1;
if(!(contazzo%10))
{
std::ostringstream mappazza;
mappazza << "mappa" << contazzo << ".png";
save_map_as_file(mappazza.str().c_str());
}
contazzo++;
#endif
}
void pmap_wrap::process(const scan_data& scan)
{
pose2_t current_lodoPose;
//std::cout << "pmap_wrap::process......... FASE 1"<<std::endl;
for(size_t i=0; i<scan.ranges_.size(); i++)
laser_scan_data_[i] = static_cast<double>(scan.ranges_.at(i))/1000.0;
//std::cout << "pmap_wrap::process......... FASE 2"<<std::endl;
current_lodoPose = lodo_add_scan(lodo_,pose2d_to_pose2_t(scan.odo_pose_),laser_scan_number_,laser_scan_data_);
//std::cout << "pmap_wrap::process......... FASE 3"<<std::endl;
pmap_update(pmap_, pose2_add(pose2d_to_pose2_t(offset_laser_pose_), current_lodoPose), laser_scan_number_, laser_scan_data_);
}
void pmap_wrap::save_map_as_file(const char* filename)
{
omap_save_pgm(omap_, filename);
}
size2d pmap_wrap::get_current_coord() const
{
pmap_sample_t* campione=PMAP_GET_SAMPLE(pmap_,pmap_->best_sample);
pose2_t temp = campione->pose;
return size2d((omap_->grid_sy/2 + temp.pos.y/omap_->grid_res) , (omap_->grid_sx/2 + temp.pos.x/omap_->grid_res));
}
}//namespace splam
}//namespace all
| [
"andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81",
"giorgio.ugazio@1c7d64d3-9b28-0410-bae3-039769c3cb81"
] | [
[
[
1,
2
],
[
73,
74
],
[
80,
80
],
[
82,
92
],
[
94,
103
]
],
[
[
3,
72
],
[
75,
79
],
[
81,
81
],
[
93,
93
],
[
104,
157
]
]
] |
321f3cab1c87b7c3cfb6102074ffd1bd8d08f327 | d9a78f212155bb978f5ac27d30eb0489bca87c3f | /PB/src/RMsg/stdafx.h | abb4bd80eeaa34cedc59c933d6ef6249f2326672 | [] | no_license | marchon/pokerbridge | 1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c | 97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9 | refs/heads/master | 2021-01-10T07:15:26.496252 | 2010-05-17T20:01:29 | 2010-05-17T20:01:29 | 36,398,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 531 | h | #pragma once
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <psapi.h>
#include <shlwapi.h>
#include <stdio.h>
#include <iostream>
#define QWEAKPOINTER_ENABLE_ARROW
#include <QtCore\QtCore>
#include <QtGui\QtGui>
#include <QtSql\QtSql>
#include <QtScript\QtScript>
#include <QtNetwork\QtNetwork>
#include <QtCore\QtAlgorithms>
#include "rmsg_global.h"
#undef PB_EXPORT
#define PB_EXPORT
#include "qpblog.h"
| [
"mikhail.mitkevich@a5377438-2eb2-11df-b28a-19025b8c0740"
] | [
[
[
1,
23
]
]
] |
20d64988ffd5394912aa086a0cf11576b5375694 | 1ad4b1dcc3d7327673ec31784a47ff3b64a6e34b | /pdetect.cpp | 8fc899c91b94aebee6d149837a516c8f66e1161b | [] | no_license | iasoule/WMGestures | c0354f0687bea85666ccd8ff7d9e0c8c44f162bc | 3cf6caf0c8b32bbede6766c7440bbd07e8086e36 | refs/heads/master | 2016-09-05T11:17:14.208267 | 2011-06-30T08:02:56 | 2011-06-30T08:02:56 | 1,339,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,425 | cpp | /* Posture detection using blob analysis
To the glory of Yeshua Ha'Mashiach
Idris Soule, Michael Pang
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <highgui.h>
#include <pthread.h>
#include <signal.h>
#include <windows.h>
#include "fsm.h"
#include "Blob.h"
#include "BlobResult.h"
#include "NPTrackingTools.h"
#if OCV_DEBUG
#include "ocv.h"
#endif
#define W 200
#define H 200
#define KEY_ESC 27
#define KEY_NOTPRESSED 0
#define MAX_NUM_CAMERAS 3
#pragma warning(disable:4716) //disable missing return from function error
int key = KEY_NOTPRESSED;
pthread_mutex_t keyMutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER;
typedef struct {
unsigned int i;
IplImage *displayImage;
}CameraData_t;
int sortLowHigh(const void * a, const void *b)
{
return (int)(*(double*)a - *(double*)b);
}
/* Filter to retrieve modifiers in the track state
** These modifiers are for left and right click
*/
class ModifierFilter {
public:
static const int MAX_BLOBS = 10;
ModifierFilter() {
bres = new CBlobResult();
};
~ModifierFilter() {
if(bres)
delete bres;
}
CBlobResult * modifiers(const CBlobResult *cbr);
CBlob keyFeature(const CBlobResult *cbr);
private:
CBlobResult *bres;
CBlob kf;
double m1[10], m2[10], m3[10];
double m4[10];
};
/* ModifierFilter::modifiers
Returns the two modifiers left, right
@cbr: a CBlobResult of the current hand
@return: the two filtered modifiers
*/
CBlobResult * ModifierFilter::modifiers(const CBlobResult *cbr)
{
const int numBlobs = cbr->GetNumBlobs();
assert(numBlobs <= MAX_BLOBS);
for(int i = 0; i < numBlobs; i++){
CBlob blob = cbr->GetBlob(i);
if(blob.MaxY() >= W) //blobs of image width/height
m1[i] = W;
else
m1[i] = cbr->GetBlob(i).MinX();
}
qsort(m1, numBlobs, sizeof(double), &sortLowHigh);
for(int j = 0; j < numBlobs; j++)
{
CBlob blob = cbr->GetBlob(j);
if(blob.MaxY() >= W) //blobs of image width/height
m2[j] = W;
else
m2[j] = cbr->GetBlob(j).MaxX();
}
qsort(m2, numBlobs, sizeof(double), &sortLowHigh);
for(int k = 0; k < numBlobs; k++) //RC sphere
{
CBlob blob = cbr->GetBlob(k);
if(blob.MaxY() >= W) //blobs of image width/height
m3[k] = W;
else
m3[k] = cbr->GetBlob(k).MinY();
}
qsort(m3, numBlobs, sizeof(double), &sortLowHigh);
//check blobs against m1, m2, m3
for(int i = 0; i < numBlobs; i++)
{
CBlob b = cbr->GetBlob(i);
if(m1[0] == b.MinX() && m2[0] == b.MaxX())
bres->AddBlob(&cbr->GetBlob(i));
if(m3[0] == b.MinY())
bres->AddBlob(&cbr->GetBlob(i));
}
return bres;
}
/*
Modifier::keyFeature
Calculate keyfeature
*/
CBlob ModifierFilter::keyFeature(const CBlobResult *cbr)
{
assert(cbr);
const int numBlobs = cbr->GetNumBlobs();
assert(numBlobs <= MAX_BLOBS);
for(int i = 0; i < numBlobs; i++){
CBlob blob = cbr->GetBlob(i);
if(blob.MaxY() >= W) //blobs of image width/height
m4[i] = -W;
else
m4[i] = cbr->GetBlob(i).MaxY();
}
qsort(m4, numBlobs, sizeof(double), &sortLowHigh);
for(int i = 0; i < numBlobs; i++)
{
CBlob b = cbr->GetBlob(i);
if(b.MaxY() == m4[numBlobs - 1]){
kf = cbr->GetBlob(i) ;
}
}
return kf;
}
/* thread to execute display of camera frames */
void *showCameraWindow(void *arg)
{
CameraData_t *myCam = (CameraData_t *)arg;
const char *windowName = TT_CameraName(myCam->i);
const CBlobResult *hand;
int x = 0, y = 0;
int lx = 0, ly = 0;
int rx = 0, ry = 0;
enum {EMPTY = 2, DRAG = 4, _ZOOM = 8, _TRACK = 9};
cvNamedWindow(windowName,CV_WINDOW_AUTOSIZE);
if(myCam->i != 0)
pthread_exit(NULL); //use Camera 21 for now
for( ;key != KEY_ESC; ){
TT_CameraFrameBuffer(myCam->i, W, H, 0, 8, (unsigned char *)myCam->displayImage->imageData);
cvFlip(myCam->displayImage, 0, -1);
cvShowImage(windowName, myCam->displayImage);
pthread_mutex_lock(&keyMutex);
hand = new CBlobResult(myCam->displayImage, 0, 20, false);
switch(hand->GetNumBlobs()){
case EMPTY:
puts("Hand not in view!");
break;
case _ZOOM: puts("ZOOM");
break;
case _TRACK:
do {
ModifierFilter modFilter;
CBlobResult *filteredHand = modFilter.modifiers(hand);
CBlob keyF = modFilter.keyFeature(hand);
#if 1
POINT cursor;
CBlobGetXCenter centreX;
CBlobGetYCenter centreY;
cursor.x = (LONG) centreX(keyF);
cursor.y = (LONG) centreY(keyF);
#endif
if( x >= cursor.x - 2 && x <= cursor.x + 2 &&
y >= cursor.y - 2 && y <= cursor.y + 2) {//some type of click?
POINT lSphere, rSphere;
lSphere.x = (LONG) centreX(filteredHand->GetBlob(1)); //TODO Assert idx 1
lSphere.y = (LONG) centreY(filteredHand->GetBlob(1));
rSphere.x = (LONG) centreX(filteredHand->GetBlob(0));
rSphere.y = (LONG) centreY(filteredHand->GetBlob(0));
const int threshold = 3;
if( ly >= (lSphere.y - threshold) && ly <= (lSphere.y + threshold)){ //LEFT CLICK
printf("LEFT CLICK \n");
lx = lSphere.x;
ly = lSphere.y;
}
}
else { //purely tracking as keyfeature has changed
printf("-- true tracking\n");
x = cursor.x;
y = cursor.y;
}
}
while(0);
break;
default:
puts("<<UNKNOWN>>\n");
}
delete hand;
key = cvWaitKey(50); //delay atleast n ms for TT firmware propogation delay
pthread_mutex_unlock(&keyMutex);
}
cvReleaseImage(&myCam->displayImage);
pthread_exit(NULL);
}
int main()
{
TT_Initialize(); //setup TT cameras
printf("Opening Calibration: %s\n",
TT_LoadCalibration("CalibrationResult 2010-12-30 4.39pm.cal") == NPRESULT_SUCCESS ?
"PASS" : "ERROR");
int cameraCount = TT_CameraCount();
CameraData_t cameras[MAX_NUM_CAMERAS];
pthread_t threads[MAX_NUM_CAMERAS];
assert(MAX_NUM_CAMERAS == cameraCount);
TT_SetCameraSettings(0, NPVIDEOTYPE_PRECISION,300, 150, 15);
TT_SetCameraSettings(1, NPVIDEOTYPE_PRECISION,300, 150, 15);
TT_SetCameraSettings(2, NPVIDEOTYPE_PRECISION,300, 150, 15);
/* 1. Change camera settings ^
2. Allocate space for the displays
*/
for(int i = 0; i < cameraCount; i++){
cameras[i].i = i;
cameras[i].displayImage = cvCreateImage(cvSize(W,H), IPL_DEPTH_8U, 1);
}
/* Setup priority for the process, pthreads-win32 threads inherit process priority
threads don't support RT or near-RT threads natively
*/
SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS/*(HIGH)REALTIME_PRIORITY_CLASS*/);
fsm_initialize(TRACK);
for(int i = 0; i < cameraCount; i++){
if(pthread_create(&threads[i], NULL, showCameraWindow, (void*)&cameras[i])){
printf("\aThread couldn't be created!");
cvDestroyAllWindows();
TT_Shutdown();
TT_FinalCleanup();
exit(-1);
}
}
printf("Press any Key to Exit!\n");
while(!_kbhit()){
int result = TT_Update();
if(result != NPRESULT_SUCCESS)
Sleep(10UL); //wait for updated frame 1/sleeptime[ms] = frame-rate
}
for(int i = 0; i < cameraCount; i++)
pthread_join(threads[i], NULL);
pthread_mutex_destroy(&keyMutex);
cvDestroyAllWindows();
TT_Shutdown();
TT_FinalCleanup();
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
316
]
]
] |
6f7640952ab47d29d1cfd9838ab5eaa87b9c19f1 | fa609a5b5a0e7de3344988a135b923a0f655f59e | /Source/values/Bool.h | f449822dc45dbe24b215da0ab789bb45f58dd45d | [
"MIT"
] | permissive | Sija/swift | 3edfd70e1c8d9d54556862307c02d1de7d400a7e | dddedc0612c0d434ebc2322fc5ebded10505792e | refs/heads/master | 2016-09-06T09:59:35.416041 | 2007-08-30T02:29:30 | 2007-08-30T02:29:30 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,512 | h | /**
* Swift Parser Library
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright (c) 2007 Sijawusz Pur Rahnama
* @copyright Copyright (c) 2007 Paweł Złomaniec
* @version $Revision: 89 $
* @modifiedby $LastChangedBy: Sija $
* @lastmodified $Date: 2007-07-22 21:38:08 +0200 (N, 22 lip 2007) $
*/
#pragma once
#ifndef __SWIFT_BOOL_VALUE_H__
#define __SWIFT_BOOL_VALUE_H__
#include "../iValueBase.h"
namespace Swift { namespace Values {
class Bool : public iValueBase<Bool, bool, 15> {
public:
Bool(bool b = false) : _value(b) { }
public:
void set(bool b) {
_value = b;
}
const bool& output() {
return _value;
}
void clear() {
_value = false;
}
public:
oValue not() const {
return !_value;
}
oValue equal(const oValue& value) const {
return _value == assimilate(value);
}
oValue notEqual(const oValue& value) const {
return _value != assimilate(value);
}
protected:
bool _value;
};
SWIFT_REGISTER_TYPE(Bool, "Bool");
inline oValue& operator << (oValue& value, bool b) {
return value = new Bool(b);
}
inline bool operator >> (const oValue& value, bool b) {
return Bool::assimilate(value);
}
}
using Values::operator <<;
using Values::operator >>;
}
#endif // __SWIFT_BOOL_VALUE_H__ | [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
31ebaf534f0ab6eaba00a3e4eb9c844045796416 | 16d6176d43bf822ad8d86d4363c3fee863ac26f9 | /hw4/objectFunctions.h | 8473a676c4a682b91dc59f69f5dc73ccab72bc02 | [] | no_license | preethinarayan/cgraytracer | 7a0a16e30ef53075644700494b2f8cf2a0693fbd | 46a4a22771bd3f71785713c31730fdd8f3aebfc7 | refs/heads/master | 2016-09-06T19:28:04.282199 | 2008-12-10T00:02:32 | 2008-12-10T00:02:32 | 32,247,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,999 | h | #ifndef _objectFunctions_h_
#define _objectFunctions_h_
#include <vector>
#include "nv_math.h"
#include "nv_mathdecl.h"
#include "nv_algebra.h"
#include "lightFunctions.h"
#include <math.h>
using namespace std;
extern const int OBJ_TYPE_TRIANGLE;
extern const int OBJ_TYPE_SPHERE;
extern int maxVertexSize, maxVertexNormalsSize;
extern float alpha, beta, gamma;
extern bool doingVertexNormals;
struct Materials
{
RGBA material_ambient;
RGBA material_diffuse;
RGBA material_specular;
int shininess;
RGBA material_emission;
};
struct Vertex {
vec3 vert;
vec3 normal;
int index;
};
struct Edge
{
Vertex a, b;
};
struct Object3D
{
int type;
int verts[3];
//Vertex verts[3];
vec3 facenormal;
Edge edges[3];
float radius;
vec3 center;
mat4 inverse_transformation;
Materials mat;
};
extern vector<Object3D> allObjects;
extern vector<Vertex> vertexList;
bool isVertexWithNormal(Vertex v);
extern vector<Vertex> verticesList();
extern vector<Vertex> vertexNormalsList();
Materials initializeMaterials();
bool isVertexNormalTriangle(Object3D tri) ;
bool isVertexListFull();
bool isVertexNormalListFull();
bool operator == (Vertex v1, Vertex v2) ;
bool operator != (Vertex v1, Vertex v2) ;
bool operator == (Object3D o1, Object3D o2) ;
bool operator != (Object3D o1, Object3D o2);
bool operator == (Edge e1, Edge e2);
bool isEdgeOfTriangle(Edge thisEdge, Object3D tri);
vector<Object3D> vertexSharedFaces(Vertex v);
vector<Edge> vertexSharedEdges(Vertex v);
vector<Object3D> threeAdjacentTriangles(Object3D thisTri) ;
vector<Object3D> twoTrianglesSharingEdge(Edge thisEdge) ;
vec3 normalofSphereIntersection(Object3D sphere, vec3 sphereIntersect);
void doFaceNormal (Object3D tri, vec3& normal);
vec3 normalofTriangleIntersection(Object3D tri);
float lengthOfVector(vec3 v);
void doNormalsForVertices();
vector<int> getNonNormalTriangles();
void calculateVertexNormal(int vertexIndex);
#endif | [
"dhrumins@074c0a88-b503-11dd-858c-a3a1ac847323"
] | [
[
[
1,
85
]
]
] |
5a34eb49e11e08b7b369b3d98eaece48c13c664f | 701f9ab221639b56c28417ee6f6ee984acb24142 | /Src/Force Game/Animation Engine/AnimEngine.cpp | 88e0622ced62cbf0c5c85f8f1de0c19728e48ab0 | [] | no_license | nlelouche/desprog1 | 2397130e427b4ada83721ecbb1a131682bc73187 | 71c7839675698e74ca43dd26c4af752e309dccb6 | refs/heads/master | 2021-01-22T06:33:14.083467 | 2010-02-26T16:18:39 | 2010-02-26T16:18:39 | 32,653,851 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,502 | cpp | /****************************************************************************
Force Engine v0.5
Creado: 28/03/08
Clase: AnimEngine.cpp
Hecho by: German Battiston AKA Melkor
****************************************************************************/
//---------------------------------------------------------------------------
#include "AnimEngine.h"
//---------------------------------------------------------------------------
AnimEngine::AnimEngine(Graphics & rkGraphics)
:
Scene(rkGraphics),
m_pkSpriteLogoFist(NULL),
m_pkSpriteLogoGear(NULL)
{
/***/
}
//---------------------------------------------------------------------------
bool AnimEngine::onInit()
{
// FMOD INIT INTRO AUDIO TRANSFORMERS
FMOD_RESULT result;
FMOD::Sound * pkSonido;
FMOD::System * pkSystem;
FMOD::Channel * pkChannel;
result = FMOD::System_Create(&pkSystem);
result = pkSystem->setSoftwareChannels(100);
result = pkSystem->setHardwareChannels(32, 64, 32, 64);
result = pkSystem->init(1, FMOD_INIT_NORMAL, 0);
result = pkSystem->setSpeakerMode(FMOD_SPEAKERMODE_STEREO);
result = pkSystem->createSound("../../res/transform2.wav",FMOD_DEFAULT,0,& pkSonido);
result = pkSystem->playSound(FMOD_CHANNEL_FREE,pkSonido, false, &pkChannel);
result = pkChannel->setVolume(0.5f);
result = pkChannel->setPaused(false);
// INIT SPRITE Y TEXTURE LOGO
m_pkSpriteLogoFist = new Sprite();
m_pkSpriteLogoGear = new Sprite();
m_pkTextureLogoFist = Texture::Ptr(new Texture("../../res/Force Logo.png", D3DCOLOR_XRGB(255,255,255)));
m_pkTextureLogoGear = Texture::Ptr(new Texture("../../res/Force Logo.png", D3DCOLOR_XRGB(255,255,255)));
if(!m_pkGraphics->loadTexture("../../res/Force Logo.png", * m_pkTextureLogoFist))
{
return false;
}
if(!m_pkGraphics->loadTexture("../../res/Force Logo.png", * m_pkTextureLogoGear))
{
return false;
}
m_pkSpriteLogoFist->setTexture(m_pkTextureLogoFist);
m_pkSpriteLogoFist->setDim(256,256);
m_pkSpriteLogoFist->setPosXYZ(0,0,1);
m_pkSpriteLogoGear->setTexture(m_pkTextureLogoGear);
m_pkSpriteLogoGear->setDim(256,256);
m_pkSpriteLogoGear->setPosXYZ(0,0,0);
addEntity(m_pkSpriteLogoGear);
addEntity(m_pkSpriteLogoFist);
return true;
}
//---------------------------------------------------------------------------
bool AnimEngine::onUpdate(float fTimeBetweenFrames)
{
rotateLogo(fTimeBetweenFrames);
return true;
}
//---------------------------------------------------------------------------
void AnimEngine::rotateLogo(float fTimeBetweenFrames)
{
static float m_fAngle = 0.0f;
static float m_fAccel = 0.0001f;
m_fAngle += fTimeBetweenFrames * m_fAccel;
m_pkSpriteLogoFist->setRotationZ(m_fAngle);
m_pkSpriteLogoFist->Update(fTimeBetweenFrames);
m_pkSpriteLogoGear->Update(fTimeBetweenFrames);
if(m_fAccel < 0.5f)
{
m_fAccel += 0.0001f;
}
}
//---------------------------------------------------------------------------
void AnimEngine::onDraw(Graphics & rkGraphics) const
{
/***/
}
//---------------------------------------------------------------------------
bool AnimEngine::onDeInit()
{
delete m_pkSpriteLogoFist;
m_pkSpriteLogoFist = NULL;
delete m_pkSpriteLogoGear;
m_pkSpriteLogoGear = NULL;
return true;
}
//---------------------------------------------------------------------------
AnimEngine::~AnimEngine()
{
/***/
}
//--------------------------------------------------------------------------- | [
"gersurfer@a82ef5f6-654a-0410-99b4-23d68ab79cb1"
] | [
[
[
1,
120
]
]
] |
cf6f8c0e95b34281e062d8c93d4cff662628757b | dde6e080c5f427d57dbd416f92b25e1bb32aad83 | /Sphere.cpp | 24de6b4ee6bc9d6062d2cc4daa1633e093fcba0a | [] | no_license | davidjonsson/aglobal | b0d715fa155cce1767cc0a4577e8d60006dbbf30 | a7c1fb8bf456de655bd5fa62259d131b8f18f48d | refs/heads/master | 2021-01-01T19:39:09.981802 | 2010-11-08T15:39:58 | 2010-11-08T15:39:58 | 1,025,287 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,271 | cpp | #include "Sphere.h"
Sphere::Sphere(): radius(0), origin(Vec3f(0,0,0))
, Shape::Shape(Material(0,0,0,0,0)){}
Sphere::Sphere(float r, Vec3f ori, Material mat) : radius(r), origin(ori)
, Shape::Shape(mat) {}
Vec3f Sphere::intersect(Ray* ray, Vec3f* normalR){
std::cout<<"Sphere Intersect"<<std::endl;
Vec3f raySphere = origin - ray->start;
float d = raySphere.dot(ray->direction); //direction normaliserad annars division
float length2 = raySphere.lengthSquare();
float radius2 = radius*radius;
if((d < 0) && (length2 > radius2)) //ray pekar bort från sfär och ray börjar ej inom sfär
return Vec3f(0,0,0);
float m2 = length2 - d*d;
if(m2 > radius2)
return Vec3f(0,0,0);
float q = sqrt(radius2-m2);
float t = 0;
if(length2 > radius2)
t = d - q;
else
t = d + q;
ray->color = material.color;
*normalR = (ray->start + ray->direction * t) - origin;
return (ray->start + ray->direction * t);
}
/*
Sphere::Sphere(float rad, Vec3f ori, Material mat){}
Vec3f Sphere::intersect(Ray r){
return Vec3f(0,0,0);
}
*/
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
3
],
[
5,
44
]
],
[
[
4,
4
]
]
] |
61a8d83d238629cc1120b7e70d1ba8a330341921 | 55196303f36aa20da255031a8f115b6af83e7d11 | /private/tools/editor/PropertiesWnd.h | d5b058d0977daf82b1d231569026e82091d7d578 | [] | no_license | Heartbroken/bikini | 3f5447647d39587ffe15a7ae5badab3300d2a2ff | fe74f51a3a5d281c671d303632ff38be84d23dd7 | refs/heads/master | 2021-01-10T19:48:40.851837 | 2010-05-25T19:58:52 | 2010-05-25T19:58:52 | 37,190,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,544 | h |
#pragma once
class CPropertiesToolBar : public CMFCToolBar
{
public:
virtual void OnUpdateCmdUI(CFrameWnd* /*pTarget*/, BOOL bDisableIfNoHndler)
{
CMFCToolBar::OnUpdateCmdUI((CFrameWnd*) GetOwner(), bDisableIfNoHndler);
}
virtual BOOL AllowShowOnList() const { return FALSE; }
};
class CPropertiesWnd : public CDockablePane
{
// Construction
public:
CPropertiesWnd();
void AdjustLayout();
// Attributes
public:
void SetVSDotNetLook(BOOL bSet)
{
m_wndPropList.SetVSDotNetLook(bSet);
m_wndPropList.SetGroupNameFullWidth(bSet);
}
protected:
CFont m_fntPropList;
CComboBox m_wndObjectCombo;
CPropertiesToolBar m_wndToolBar;
CMFCPropertyGridCtrl m_wndPropList;
// Implementation
public:
virtual ~CPropertiesWnd();
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnExpandAllProperties();
afx_msg void OnUpdateExpandAllProperties(CCmdUI* pCmdUI);
afx_msg void OnSortProperties();
afx_msg void OnUpdateSortProperties(CCmdUI* pCmdUI);
afx_msg void OnProperties1();
afx_msg void OnUpdateProperties1(CCmdUI* pCmdUI);
afx_msg void OnProperties2();
afx_msg void OnUpdateProperties2(CCmdUI* pCmdUI);
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection);
// ???
afx_msg LRESULT OnPropertyChanged( __in WPARAM wparam, __in LPARAM lparam );
DECLARE_MESSAGE_MAP()
public:
void InitPropList();
void SetPropListFont();
};
| [
"[email protected]",
"viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587"
] | [
[
[
1,
54
],
[
58,
59
],
[
61,
64
]
],
[
[
55,
57
],
[
60,
60
]
]
] |
2a8424d7ab40890609f8fd3b2239efc6307ebad1 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/wheel/NetWheelController/include/WheelClock.h | c01b15c24856d16e18996973d57bb61e32478f4d | [] | no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 860 | h | #ifndef __Orz_WheelClock_h__
#define __Orz_WheelClock_h__
#include "WheelControllerConfig.h"
#include "WheelClockListener.h"
namespace Orz
{
class _OrzNetWheelControlleExport WheelClock
{
public:
WheelClock(void);
~WheelClock(void);
//获取剩余时间
int getLastSecond(void) const;
//获取当前时间
int getSecond(void) const;
//获取总时间
int getAllSecond(void) const;
//设置当前时间
void setSecond(int second);
//设置总时间
void setAllSecond(int allSecond);
void setListener(WheelClockListener * listener);
void update(TimeType interval);
void reset(void);
private:
void changeClock();
int _second;
int _allSecond;
WheelClockListener * _callback;
TimeType _pass;
};
typedef boost::shared_ptr<WheelClock > WheelClockPtr;
}
#endif
| [
"[email protected]"
] | [
[
[
1,
46
]
]
] |
9ce2b5eda74732a79c18ec9ee00e39a2df44db24 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SESceneGraph/SECameraNode.cpp | 32356831f502fabbf10a066a0cc73073265c5ca1 | [] | no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,135 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEFoundationPCH.h"
#include "SECameraNode.h"
using namespace Swing;
SE_IMPLEMENT_RTTI(Swing, SECameraNode, SENode);
SE_IMPLEMENT_STREAM(SECameraNode);
//SE_REGISTER_STREAM(SECameraNode);
//----------------------------------------------------------------------------
SECameraNode::SECameraNode(SECamera* pCamera)
:
m_spCamera(pCamera)
{
if( m_spCamera )
{
Local.SetTranslate(m_spCamera->GetLocation());
Local.SetRotate(SEMatrix3f(m_spCamera->GetRVector(),
m_spCamera->GetUVector(), m_spCamera->GetDVector()));
}
}
//----------------------------------------------------------------------------
SECameraNode::~SECameraNode()
{
}
//----------------------------------------------------------------------------
void SECameraNode::SetCamera(SECamera* pCamera)
{
m_spCamera = pCamera;
if( m_spCamera )
{
Local.SetTranslate(m_spCamera->GetLocation());
Local.SetRotate(SEMatrix3f(m_spCamera->GetRVector(),
m_spCamera->GetUVector(), m_spCamera->GetDVector()));
UpdateGS();
}
}
//----------------------------------------------------------------------------
void SECameraNode::UpdateWorldData(double dAppTime)
{
SENode::UpdateWorldData(dAppTime);
if( m_spCamera )
{
SEVector3f vec3fR, vec3fU, vec3fD;
World.GetRotate().GetRow(0, vec3fR);
World.GetRotate().GetRow(1, vec3fU);
World.GetRotate().GetRow(2, vec3fD);
m_spCamera->SetFrame(World.GetTranslate(), vec3fR, vec3fU, vec3fD);
}
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// name and unique id
//----------------------------------------------------------------------------
SEObject* SECameraNode::GetObjectByName(const std::string& rName)
{
SEObject* pFound = SENode::GetObjectByName(rName);
if( pFound )
{
return pFound;
}
if( m_spCamera )
{
pFound = m_spCamera->GetObjectByName(rName);
if( pFound )
{
return pFound;
}
}
return 0;
}
//----------------------------------------------------------------------------
void SECameraNode::GetAllObjectsByName(const std::string& rName,
std::vector<SEObject*>& rObjects)
{
SENode::GetAllObjectsByName(rName, rObjects);
if( m_spCamera )
{
m_spCamera->GetAllObjectsByName(rName, rObjects);
}
}
//----------------------------------------------------------------------------
SEObject* SECameraNode::GetObjectByID(unsigned int uiID)
{
SEObject* pFound = SENode::GetObjectByID(uiID);
if( pFound )
{
return pFound;
}
if( m_spCamera )
{
pFound = m_spCamera->GetObjectByID(uiID);
if( pFound )
{
return pFound;
}
}
return 0;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// streaming
//----------------------------------------------------------------------------
void SECameraNode::Load(SEStream& rStream, SEStream::SELink* pLink)
{
SE_BEGIN_DEBUG_STREAM_LOAD;
SENode::Load(rStream, pLink);
// link data
SEObject* pObject;
rStream.Read(pObject); // m_spCamera
pLink->Add(pObject);
SE_END_DEBUG_STREAM_LOAD(SECameraNode);
}
//----------------------------------------------------------------------------
void SECameraNode::Link(SEStream& rStream, SEStream::SELink* pLink)
{
SENode::Link(rStream, pLink);
SEObject* pLinkID = pLink->GetLinkID();
m_spCamera = (SECamera*)rStream.GetFromMap(pLinkID);
}
//----------------------------------------------------------------------------
bool SECameraNode::Register(SEStream& rStream) const
{
if( !SENode::Register(rStream) )
{
return false;
}
if( m_spCamera )
{
m_spCamera->Register(rStream);
}
return true;
}
//----------------------------------------------------------------------------
void SECameraNode::Save(SEStream& rStream) const
{
SE_BEGIN_DEBUG_STREAM_SAVE;
SENode::Save(rStream);
// link data
rStream.Write(m_spCamera);
SE_END_DEBUG_STREAM_SAVE(SECameraNode);
}
//----------------------------------------------------------------------------
int SECameraNode::GetDiskUsed(const SEStreamVersion& rVersion) const
{
return SENode::GetDiskUsed(rVersion) + SE_PTRSIZE(m_spCamera);
}
//----------------------------------------------------------------------------
SEStringTree* SECameraNode::SaveStrings(const char*)
{
SEStringTree* pTree = SE_NEW SEStringTree;
// strings
pTree->Append(Format(&TYPE, GetName().c_str()));
// children
pTree->Append(SENode::SaveStrings());
if( m_spCamera )
{
pTree->Append(m_spCamera->SaveStrings());
}
return pTree;
}
//----------------------------------------------------------------------------
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
205
]
]
] |
c03deebc392373acc97115f5be790920629c12a0 | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/MapRenderer/include/renderer/Characters.h | c12427054b4ec3217469abf725e17a99b0b6783d | [] | no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,943 | h | //
// File: Characters.h
// Created by: Alexander Oster - [email protected]
//
/*****
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*****/
#ifndef _CHARACTERS_H_
#define _CHARACTERS_H_
#ifdef WIN32
#include <windows.h>
#endif
#include "SDL/SDL.h"
#include <map>
#include <string>
struct sSkillEntry {
Uint16 value;
Uint16 unmodified;
Uint16 skillcap;
Uint8 skillLock;
};
class cCharacterEquip
{
private:
Uint16 m_layer;
Uint32 m_id;
Uint16 m_hue;
Uint16 m_anim;
Uint16 m_model;
public:
cCharacterEquip() {
m_layer = 0;
m_id = 0;
m_model = 0;
m_anim = 10;
m_hue = 0;
}
void setLayer(Uint16 layer) { m_layer = layer; }
void setID(Uint32 id) { m_id = id; }
void setHue(Uint16 hue) { m_hue = hue; }
void setModel(Uint16 model) { m_model = model; }
void setAnim(Uint16 anim) { m_anim = anim; }
Uint16 layer() { return m_layer; }
Uint16 hue() { return m_hue; }
Uint16 model() { return m_model; }
Uint32 id () { return m_id; }
Uint16 anim () { return m_anim; }
};
typedef std::map<Uint32, cCharacterEquip *> equiplist_t;
typedef std::map<Uint16, sSkillEntry *> skilllist_t;
class cCharacter
{
private:
Uint32 m_id;
float m_x, m_y, m_z;
float m_destx, m_desty, m_destz;
float m_angle;
Uint16 m_body;
Uint16 m_hue;
Uint8 m_flag;
Uint8 m_direction;
float m_animtime;
Uint32 m_lastanim;
bool m_moving;
std::string m_name;
bool m_name_change;
Uint8 m_sex;
Uint32 m_gold;
Uint16 m_armor;
Uint16 m_weight;
Uint16 m_strength;
Uint16 m_dexterity;
Uint16 m_intelligence;
Uint16 m_hits_current;
Uint16 m_hits_max;
Uint16 m_stamina_current;
Uint16 m_stamina_max;
Uint16 m_mana_current;
Uint16 m_mana_max;
equiplist_t equiplist;
skilllist_t m_skills;
public:
cCharacter();
~cCharacter();
void setID (Uint32 id) { m_id = id; }
void setX (float x) { m_x = x; m_destx = x; m_moving = 0; }
void setY (float y) { m_y = y; m_desty = y; m_moving = 0; }
void setZ (float z) { m_z = z; m_destz = z; m_moving = 0; }
void setX (int x) { m_x = (float) x; m_destx = m_x; }
void setY (int y) { m_y = (float) y; m_desty = m_y; }
void setZ (int z) { m_z = (float) z; m_destz = m_z; }
void setPosition (float x, float y, float z) {
m_x = x; m_destx = m_x;
m_y = y; m_desty = m_y;
m_z = z; m_destz = m_z;
m_moving = 0;
}
void setPosition (int x, int y, int z) {
m_x = (float) x; m_destx = m_x;
m_y = (float) y; m_desty = m_y;
m_z = (float) z; m_destz = m_z;
m_moving = 0;
}
void getPosition (float & x, float & y, float & z) { x = m_x; y = m_y; z = m_z; }
void setBody (int body) { m_body = body; }
void setHue (int hue) { m_hue = hue; }
void setFlag (int flag) { m_flag = flag; }
void setAnimtime (float animtime) { m_animtime = animtime; }
void setLastAnim (Uint32 lastanim) { m_lastanim = lastanim; }
void setDirection(Uint8 direction) { m_direction = direction; m_angle = direction * 45.0f;}
void setName (std::string name) { m_name = name; }
void setNameChange (bool name_change) { m_name_change = name_change; }
void setSex (Uint8 sex) { m_sex = sex; }
void setGold (Uint32 gold) { m_gold = gold; }
void setArmor (Uint16 armor) { m_armor = armor; }
void setWeight (Uint16 weight) { m_weight = weight; }
void setStr (Uint16 strength) { m_strength = strength; }
void setDex (Uint16 dexterity) { m_dexterity = dexterity; }
void setInt (Uint16 intelligence) { m_intelligence = intelligence; }
void setCurrentHits (Uint16 hits_current) { m_hits_current = hits_current; }
void setMaxHits (Uint16 hits_max) { m_hits_max = hits_max; }
void setCurrentStamina (Uint16 stamina_current) { m_stamina_current = stamina_current; }
void setMaxStamina (Uint16 stamina_max) { m_stamina_max = stamina_max; }
void setCurrentMana (Uint16 mana_current) { m_mana_current = mana_current; }
void setMaxMana (Uint16 mana_max) { m_mana_max = mana_max; }
Uint32 id () { return m_id; }
int x () { return (int) (m_x + 0.5f); }
int y () { return (int) (m_y + 0.5f); }
int z () { return (int) (m_z + 0.5f); }
float fx () { return m_x; }
float fy () { return m_y; }
float fz () { return m_z; }
int body () { return m_body; }
int hue () { return m_hue; }
int flag () { return m_flag; }
int moving () { return m_moving; }
float angle () { return m_angle; }
float animtime () { return m_animtime; }
Uint32 lastanim () { return m_lastanim; }
Uint8 direction() { return m_direction; }
std::string name () { return m_name; }
bool name_change () { return m_name_change; }
Uint8 sex () { return m_sex; }
Uint32 gold () { return m_gold; }
Uint16 armor () { return m_armor; }
Uint16 weight () { return m_weight; }
Uint16 strength () { return m_strength; }
Uint16 dexterity () { return m_dexterity; }
Uint16 intelligence () { return m_intelligence; }
Uint16 hits_current () { return m_hits_current; }
Uint16 hits_max () { return m_hits_max; }
Uint16 stamina_current () { return m_stamina_current; }
Uint16 stamina_max () { return m_stamina_max; }
Uint16 mana_current () { return m_mana_current; }
Uint16 mana_max () { return m_mana_max; }
void ClearEquip (void);
cCharacterEquip * AddEquip (Uint32 layer);
cCharacterEquip * GetEquip (unsigned int layer);
void Handle (float time_factor);
void MoveTo (float x, float y, float z);
void RotateTo(Uint8 direction) { m_direction = direction; }
void RenderText ();
sSkillEntry * skill (Uint16 id);
void ClearSkills();
Uint16 anim_frame;
Uint32 last_anim_time;
};
typedef std::map<Uint32, cCharacter *> characterlist_t;
class cCharacterList
{
private:
characterlist_t characterlist;
public:
cCharacterList ();
~cCharacterList ();
void Clear (void);
cCharacter * Add (Uint32 id);
cCharacter * Get (unsigned int id);
void Delete(unsigned int id);
characterlist_t * GetList(void) { return &characterlist; }
int GetCount(void) { return characterlist.size(); }
void Handle (float time_factor);
protected:
};
extern cCharacterList * pCharacterList;
#endif //_CHARACTERS_H_
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
] | [
[
[
1,
239
]
]
] |
3c21edffd8592e18309f01c34332c0d8aa79396d | 8b506bf34b36af04fa970f2749e0c8033f1a9d7a | /Code/Win32/dx/dxVertexBuffer.h | a2b98d9bcbbf893691e433522476f1e4013351f9 | [] | no_license | gunstar/Prototype | a5155e25d7d54a1991425e7be85bfc7da42c634f | a4448b5f6d18048ecaedf26c71e2b107e021ea6e | refs/heads/master | 2021-01-10T21:42:24.221750 | 2011-11-06T10:16:26 | 2011-11-06T10:16:26 | 2,708,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | h | /*
dxVertexBuffer
*/
#ifndef _dxVertexBuffer
#define _dxVertexBuffer
#include "dxVertexDeclarationCache.h"
class dxVertexBuffer
{
public:
dxVertexBuffer (IDirect3DDevice9* device, dxVertexDeclarationCache* vdCache);
~dxVertexBuffer ();
int getCount () { return VB_Count; }
void kill ();
bool set (class enVertexPC* min, enVertexPC* max);
void setDevice ();
private:
bool set (void* data, int stride, int count, IDirect3DVertexDeclaration9* vd);
bool setSize (int size);
private:
IDirect3DVertexBuffer9* VB;
int VB_Capacity;
int VB_Size;
private:
int VB_Count;
IDirect3DVertexDeclaration9* VB_VD;
int VB_Stride;
private:
IDirect3DDevice9* Device;
dxVertexDeclarationCache* VDCache;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
42
]
]
] |
d4396f77dc0af79d142f883a386d1d6b14aa148c | 842997c28ef03f8deb3422d0bb123c707732a252 | /src/uslscore/USMemStream.cpp | 1efac6520770a21b32b728ba334a44206c77cf21 | [] | no_license | bjorn/moai-beta | e31f600a3456c20fba683b8e39b11804ac88d202 | 2f06a454d4d94939dc3937367208222735dd164f | refs/heads/master | 2021-01-17T11:46:46.018377 | 2011-06-10T07:33:55 | 2011-06-10T07:33:55 | 1,837,561 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,624 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <uslscore/USFilename.h>
#include <uslscore/USFileSys.h>
#include <uslscore/USDirectoryItr.h>
#include <uslscore/USMemStream.h>
#include <math.h>
//================================================================//
// USMemStream
//================================================================//
//----------------------------------------------------------------//
void USMemStream::Clear () {
if ( this->mChunks ) {
for ( u32 i = 0; i < this->mTotalChunks; ++i ) {
free ( this->mChunks [ i ]);
}
free ( this->mChunks );
this->mLength = 0;
this->mTotalChunks = 0;
this->mChunks = 0;
}
this->mCursor = 0;
}
//----------------------------------------------------------------//
u32 USMemStream::GetCursor () {
return this->mCursor;
}
//----------------------------------------------------------------//
u32 USMemStream::GetLength () {
return this->mLength;
}
//----------------------------------------------------------------//
u32 USMemStream::ReadBytes ( void* buffer, u32 size ) {
if ( size == 0 ) return 0;
u32 cursor0 = this->mCursor;
u32 cursor1 = cursor0 + size;
if ( cursor1 > this->mLength ) {
size = this->mLength - this->mCursor;
cursor1 = this->mLength;
}
u32 chunk0 = ( u32 )( cursor0 / this->mChunkSize );
u32 chunk1 = ( u32 )( cursor1 / this->mChunkSize );
u32 offset0 = cursor0 - ( chunk0 * this->mChunkSize );
u32 offset1 = cursor1 - ( chunk1 * this->mChunkSize );
void* src = ( void* )(( uintptr )this->mChunks [ chunk0 ] + offset0 );
void* dest = buffer;
if ( chunk0 == chunk1 ) {
memcpy ( dest, src, offset1 - offset0 );
}
else {
memcpy ( dest, src, this->mChunkSize - offset0 );
dest = ( void* )(( uintptr )dest + this->mChunkSize - offset0 );
for ( u32 i = ( chunk0 + 1 ); i < chunk1; ++i ) {
memcpy ( dest, this->mChunks [ i ], this->mChunkSize );
dest = ( void* )(( uintptr )dest + this->mChunkSize );
}
memcpy ( dest, this->mChunks [ chunk1 ], offset1 );
}
this->mCursor = cursor1;
return size;
}
//----------------------------------------------------------------//
void USMemStream::Reserve ( u32 length ) {
if ( length <= this->mLength ) return;
u32 totalChunks = ( u32 )ceil (( float )length / ( float )this->mChunkSize );
if ( totalChunks <= this->mTotalChunks ) return;
void** chunks = ( void** )malloc ( totalChunks * sizeof ( void* ));
if ( this->mChunks ) {
memcpy ( chunks, this->mChunks, this->mTotalChunks * sizeof ( void* ));
free ( this->mChunks );
}
for ( u32 i = this->mTotalChunks; i < totalChunks; ++i ) {
chunks [ i ] = malloc ( this->mChunkSize );
}
this->mTotalChunks = totalChunks;
this->mChunks = chunks;
}
//----------------------------------------------------------------//
void USMemStream::Seek ( long offset, int origin ) {
switch ( origin ) {
case SEEK_CUR: {
this->mCursor = this->mCursor + offset;
break;
}
case SEEK_END: {
this->mCursor = this->mLength;
break;
}
case SEEK_SET: {
this->mCursor = offset;
break;
}
}
if ( this->mCursor > this->mLength ) {
this->mCursor = this->mLength;
}
}
//----------------------------------------------------------------//
void USMemStream::SetChunkSize ( u32 chunkSize ) {
assert ( chunkSize );
this->Clear ();
this->mChunkSize = chunkSize;
}
//----------------------------------------------------------------//
STLString USMemStream::ToString ( u32 size ) {
if ( size == 0 ) return 0;
if (( this->mCursor + size ) > this->mLength ) {
size = this->mLength - this->mCursor;
}
STLString str;
char buffer [ DEFAULT_CHUNK_SIZE + 1 ];
u32 readSize = DEFAULT_CHUNK_SIZE;
while ( size > 0 ) {
if ( size < readSize ) {
readSize = size;
}
this->ReadBytes ( buffer, readSize );
buffer [ readSize ] = 0;
str.write ( "%s", buffer );
size -= readSize;
}
return str;
}
//----------------------------------------------------------------//
USMemStream::USMemStream () :
mChunkSize ( DEFAULT_CHUNK_SIZE ),
mTotalChunks ( 0 ),
mChunks ( 0 ),
mCursor ( 0 ),
mLength ( 0 ) {
}
//----------------------------------------------------------------//
USMemStream::~USMemStream () {
this->Clear ();
}
//----------------------------------------------------------------//
u32 USMemStream::WriteBytes ( const void* buffer, u32 size ) {
u32 cursor0 = this->mCursor;
u32 cursor1 = cursor0 + size;
this->Reserve ( cursor1 );
u32 chunk0 = ( u32 )( cursor0 / this->mChunkSize );
u32 chunk1 = ( u32 )( cursor1 / this->mChunkSize );
u32 offset0 = cursor0 - ( chunk0 * this->mChunkSize );
u32 offset1 = cursor1 - ( chunk1 * this->mChunkSize );
void* dest = ( void* )(( uintptr )this->mChunks [ chunk0 ] + offset0 );
const void* src = buffer;
if ( chunk0 == chunk1 ) {
memcpy ( dest, src, offset1 - offset0 );
}
else {
memcpy ( dest, src, this->mChunkSize - offset0 );
src = ( void* )(( uintptr )src + this->mChunkSize - offset0 );
for ( u32 i = ( chunk0 + 1 ); i < chunk1; ++i ) {
memcpy ( this->mChunks [ i ], src, this->mChunkSize );
src = ( void* )(( uintptr )src + this->mChunkSize );
}
memcpy ( this->mChunks [ chunk1 ], src, offset1 );
}
this->mCursor = cursor1;
if ( this->mLength < this->mCursor ) {
this->mLength = this->mCursor;
}
return size;
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
64
],
[
66,
74
],
[
76,
78
],
[
80,
198
],
[
200,
208
],
[
210,
212
],
[
214,
224
]
],
[
[
65,
65
],
[
75,
75
],
[
79,
79
],
[
199,
199
],
[
209,
209
],
[
213,
213
]
]
] |
482e500d264f540c9752d98f2121426518cebb4e | da9e4cd28021ecc9e17e48ac3ded33b798aae59c | /SAMPLES/DSHOWFILTERS/mpeg4ip_mp4v2/src/mp4info.cpp | d439405d6d750efc44f9f7cff2a5db124d4264b2 | [] | no_license | hibive/sjmt6410pm090728 | d45242e74b94f954cf0960a4392f07178088e560 | 45ceea6c3a5a28172f7cd0b439d40c494355015c | refs/heads/master | 2021-01-10T10:02:35.925367 | 2011-01-27T04:22:44 | 2011-01-27T04:22:44 | 43,739,703 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,506 | cpp | /*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is MPEG4IP.
*
* The Initial Developer of the Original Code is Cisco Systems Inc.
* Portions created by Cisco Systems Inc. are
* Copyright (C) Cisco Systems Inc. 2001-2002. All Rights Reserved.
*
* Portions created by Ximpo Group Ltd. are
* Copyright (C) Ximpo Group Ltd. 2003, 2004. All Rights Reserved.
*
* Contributor(s):
* Dave Mackie [email protected]
* Bill May [email protected]
* Alix Marchandise-Franquet [email protected]
* Ximpo Group Ltd. [email protected]
*/
#include "mp4common.h"
static char* PrintAudioInfo(
MP4FileHandle mp4File,
MP4TrackId trackId)
{
static const char* mpeg4AudioNames[] = {
"MPEG-4 AAC main",
"MPEG-4 AAC LC",
"MPEG-4 AAC SSR",
"MPEG-4 AAC LTP",
"MPEG-4 AAC HE",
"MPEG-4 AAC Scalable",
"MPEG-4 TwinVQ",
"MPEG-4 CELP",
"MPEG-4 HVXC",
NULL, NULL,
"MPEG-4 TTSI",
"MPEG-4 Main Synthetic",
"MPEG-4 Wavetable Syn",
"MPEG-4 General MIDI",
"MPEG-4 Algo Syn and Audio FX",
"MPEG-4 ER AAC LC",
NULL,
"MPEG-4 ER AAC LTP",
"MPEG-4 ER AAC Scalable",
"MPEG-4 ER TwinVQ",
"MPEG-4 ER BSAC",
"MPEG-4 ER ACC LD",
"MPEG-4 ER CELP",
"MPEG-4 ER HVXC",
"MPEG-4 ER HILN",
"MPEG-4 ER Parametric",
};
static const u_int8_t mpegAudioTypes[] = {
MP4_MPEG2_AAC_MAIN_AUDIO_TYPE, // 0x66
MP4_MPEG2_AAC_LC_AUDIO_TYPE, // 0x67
MP4_MPEG2_AAC_SSR_AUDIO_TYPE, // 0x68
MP4_MPEG2_AUDIO_TYPE, // 0x69
MP4_MPEG1_AUDIO_TYPE, // 0x6B
// private types
MP4_PCM16_LITTLE_ENDIAN_AUDIO_TYPE,
MP4_VORBIS_AUDIO_TYPE,
MP4_ALAW_AUDIO_TYPE,
MP4_ULAW_AUDIO_TYPE,
MP4_G723_AUDIO_TYPE,
MP4_PCM16_BIG_ENDIAN_AUDIO_TYPE,
};
static const char* mpegAudioNames[] = {
"MPEG-2 AAC Main",
"MPEG-2 AAC LC",
"MPEG-2 AAC SSR",
"MPEG-2 Audio (13818-3)",
"MPEG-1 Audio (11172-3)",
// private types
"PCM16 (little endian)",
"Vorbis",
"G.711 aLaw",
"G.711 uLaw",
"G.723.1",
"PCM16 (big endian)",
};
u_int8_t numMpegAudioTypes =
sizeof(mpegAudioTypes) / sizeof(u_int8_t);
const char* typeName = "Unknown";
bool foundType = false;
u_int8_t type = 0;
const char *media_data_name;
media_data_name = MP4GetTrackMediaDataName(mp4File, trackId);
if (media_data_name == NULL) {
typeName = "Unknown - no media data name";
} else if (strcasecmp(media_data_name, "samr") == 0) {
typeName = "AMR";
foundType = true;
} else if (strcasecmp(media_data_name, "sawb") == 0) {
typeName = "AMR-WB";
foundType = true;
} else if (strcasecmp(media_data_name, "mp4a") == 0) {
type = MP4GetTrackEsdsObjectTypeId(mp4File, trackId);
switch (type) {
case MP4_INVALID_AUDIO_TYPE:
typeName = "AAC from .mov";
foundType = true;
break;
case MP4_MPEG4_AUDIO_TYPE: {
u_int8_t* pAacConfig = NULL;
u_int32_t aacConfigLength;
MP4GetTrackESConfiguration(mp4File,
trackId,
&pAacConfig,
&aacConfigLength);
if (pAacConfig != NULL && aacConfigLength >= 2) {
type = (pAacConfig[0] >> 3) & 0x1f;
if (type == 0 || /* type == 5 || */ type == 10 || type == 11 ||
type == 18 || type >= 28) {
typeName = "MPEG-4 Unknown Profile";
} else {
typeName = mpeg4AudioNames[type - 1];
foundType = true;
}
free(pAacConfig);
} else {
typeName = "MPEG-4 (no GAConfig)";
foundType = true;
}
break;
}
// fall through
default:
for (u_int8_t i = 0; i < numMpegAudioTypes; i++) {
if (type == mpegAudioTypes[i]) {
typeName = mpegAudioNames[i];
foundType = true;
break;
}
}
}
} else {
typeName = media_data_name;
foundType = true;
}
u_int32_t timeScale =
MP4GetTrackTimeScale(mp4File, trackId);
MP4Duration trackDuration =
MP4GetTrackDuration(mp4File, trackId);
double msDuration =
UINT64_TO_DOUBLE(MP4ConvertFromTrackDuration(mp4File, trackId,
trackDuration, MP4_MSECS_TIME_SCALE));
u_int32_t avgBitRate =
MP4GetTrackBitRate(mp4File, trackId);
char *sInfo = (char*)MP4Malloc(256);
// type duration avgBitrate samplingFrequency
if (foundType)
sprintf(sInfo,
"%u\taudio\t%s%s, %.3f secs, %u kbps, %u Hz\n",
trackId,
MP4IsIsmaCrypMediaTrack(mp4File, trackId) ? "enca - " : "",
typeName,
msDuration / 1000.0,
(avgBitRate + 500) / 1000,
timeScale);
else
sprintf(sInfo,
"%u\taudio\t%s%s(%u), %.3f secs, %u kbps, %u Hz\n",
trackId,
MP4IsIsmaCrypMediaTrack(mp4File, trackId) ? "enca - " : "",
typeName,
type,
msDuration / 1000.0,
(avgBitRate + 500) / 1000,
timeScale);
return sInfo;
}
static const struct {
uint8_t profile;
const char *name;
} VisualProfileToName[] = {
{ MPEG4_SP_L1, "MPEG-4 Simple @ L1"},
{ MPEG4_SP_L2, "MPEG-4 Simple @ L2" },
{ MPEG4_SP_L3, "MPEG-4 Simple @ L3" },
{ MPEG4_SP_L0, "MPEG-4 Simple @ L0" },
{ MPEG4_SSP_L1, "MPEG-4 Simple Scalable @ L1"},
{ MPEG4_SSP_L2, "MPEG-4 Simple Scalable @ L2" },
{ MPEG4_CP_L1, "MPEG-4 Core @ L1"},
{ MPEG4_CP_L2, "MPEG-4 Core @ L2"},
{ MPEG4_MP_L2, "MPEG-4 Main @ L2"},
{ MPEG4_MP_L3, "MPEG-4 Main @ L3"},
{ MPEG4_MP_L4, "MPEG-4 Main @ L4"},
{ MPEG4_NBP_L2, "MPEG-4 N-bit @ L2"},
{ MPEG4_STP_L1, "MPEG-4 Scalable Texture @ L1"},
{ MPEG4_SFAP_L1, "MPEG-4 Simple Face Anim @ L1"},
{ MPEG4_SFAP_L2, "MPEG-4 Simple Face Anim @ L2"},
{ MPEG4_SFBAP_L1, "MPEG-4 Simple FBA @ L1"},
{ MPEG4_SFBAP_L2, "MPEG-4 Simple FBA @ L2"},
{ MPEG4_BATP_L1, "MPEG-4 Basic Anim Text @ L1"},
{ MPEG4_BATP_L2, "MPEG-4 Basic Anim Text @ L2"},
{ MPEG4_HP_L1, "MPEG-4 Hybrid @ L1"},
{ MPEG4_HP_L2, "MPEG-4 Hybrid @ L2"},
{ MPEG4_ARTSP_L1, "MPEG-4 Adv RT Simple @ L1"},
{ MPEG4_ARTSP_L2, "MPEG-4 Adv RT Simple @ L2"},
{ MPEG4_ARTSP_L3, "MPEG-4 Adv RT Simple @ L3"},
{ MPEG4_ARTSP_L4, "MPEG-4 Adv RT Simple @ L4"},
{ MPEG4_CSP_L1, "MPEG-4 Core Scalable @ L1"},
{ MPEG4_CSP_L2, "MPEG-4 Core Scalable @ L2"},
{ MPEG4_CSP_L3, "MPEG-4 Core Scalable @ L3"},
{ MPEG4_ACEP_L1, "MPEG-4 Adv Coding Efficieny @ L1"},
{ MPEG4_ACEP_L2, "MPEG-4 Adv Coding Efficieny @ L2"},
{ MPEG4_ACEP_L3, "MPEG-4 Adv Coding Efficieny @ L3"},
{ MPEG4_ACEP_L4, "MPEG-4 Adv Coding Efficieny @ L4"},
{ MPEG4_ACP_L1, "MPEG-4 Adv Core Profile @ L1"},
{ MPEG4_ACP_L2, "MPEG-4 Adv Core Profile @ L2"},
{ MPEG4_AST_L1, "MPEG-4 Adv Scalable Texture @ L1"},
{ MPEG4_AST_L2, "MPEG-4 Adv Scalable Texture @ L2"},
{ MPEG4_AST_L3, "MPEG-4 Adv Scalable Texture @ L3"},
{ MPEG4_S_STUDIO_P_L1, "MPEG-4 Simple Studio @ L1"},
{ MPEG4_S_STUDIO_P_L2, "MPEG-4 Simple Studio @ L2"},
{ MPEG4_S_STUDIO_P_L3, "MPEG-4 Simple Studio @ L3"},
{ MPEG4_S_STUDIO_P_L4, "MPEG-4 Simple Studio @ L4"},
{ MPEG4_C_STUDIO_P_L1, "MPEG-4 Core Studio @ L1"},
{ MPEG4_C_STUDIO_P_L2, "MPEG-4 Core Studio @ L2"},
{ MPEG4_C_STUDIO_P_L3, "MPEG-4 Core Studio @ L3"},
{ MPEG4_C_STUDIO_P_L4, "MPEG-4 Core Studio @ L4"},
{ MPEG4_ASP_L0, "MPEG-4 Adv Simple@L0"},
{ MPEG4_ASP_L1, "MPEG-4 Adv Simple@L1"},
{ MPEG4_ASP_L2, "MPEG-4 Adv Simple@L2"},
{ MPEG4_ASP_L3, "MPEG-4 Adv Simple@L3"},
{ MPEG4_ASP_L4, "MPEG-4 Adv Simple@L4"},
{ MPEG4_ASP_L5, "MPEG-4 Adv Simple@L5"},
{ MPEG4_ASP_L3B, "MPEG-4 Adv Simple@L3b"},
{ MPEG4_FGSP_L0, "MPEG-4 FGS @ L0" },
{ MPEG4_FGSP_L1, "MPEG-4 FGS @ L1" },
{ MPEG4_FGSP_L2, "MPEG-4 FGS @ L2" },
{ MPEG4_FGSP_L3, "MPEG-4 FGS @ L3" },
{ MPEG4_FGSP_L4, "MPEG-4 FGS @ L4" },
{ MPEG4_FGSP_L5, "MPEG-4 FGS @ L5" }
};
static const char *Mpeg4VisualProfileName (uint8_t visual_profile)
{
size_t size = sizeof(VisualProfileToName) / sizeof(*VisualProfileToName);
for (size_t ix = 0; ix < size; ix++) {
if (visual_profile == VisualProfileToName[ix].profile) {
return (VisualProfileToName[ix].name);
}
}
return (NULL);
}
static char* PrintVideoInfo(
MP4FileHandle mp4File,
MP4TrackId trackId)
{
static const u_int8_t mpegVideoTypes[] = {
MP4_MPEG2_SIMPLE_VIDEO_TYPE, // 0x60
MP4_MPEG2_MAIN_VIDEO_TYPE, // 0x61
MP4_MPEG2_SNR_VIDEO_TYPE, // 0x62
MP4_MPEG2_SPATIAL_VIDEO_TYPE, // 0x63
MP4_MPEG2_HIGH_VIDEO_TYPE, // 0x64
MP4_MPEG2_442_VIDEO_TYPE, // 0x65
MP4_MPEG1_VIDEO_TYPE, // 0x6A
MP4_JPEG_VIDEO_TYPE, // 0x6C
MP4_YUV12_VIDEO_TYPE,
MP4_H263_VIDEO_TYPE,
MP4_H261_VIDEO_TYPE,
};
static const char* mpegVideoNames[] = {
"MPEG-2 Simple",
"MPEG-2 Main",
"MPEG-2 SNR",
"MPEG-2 Spatial",
"MPEG-2 High",
"MPEG-2 4:2:2",
"MPEG-1",
"JPEG",
"YUV12",
"H.263",
"H.261",
};
u_int8_t numMpegVideoTypes =
sizeof(mpegVideoTypes) / sizeof(u_int8_t);
bool foundTypeName = false;
const char* typeName = "Unknown";
const char *media_data_name;
uint8_t type = 0;
media_data_name = MP4GetTrackMediaDataName(mp4File, trackId);
char typebuffer[80];
if (media_data_name == NULL) {
typeName = "Unknown - no media data name";
foundTypeName = true;
} else if (strcasecmp(media_data_name, "avc1") == 0) {
// avc
uint8_t profile, level;
char profileb[20], levelb[20];
if (MP4GetTrackH264ProfileLevel(mp4File, trackId,
&profile, &level)) {
if (profile == 66) {
strcpy(profileb, "Baseline");
} else if (profile == 77) {
strcpy(profileb, "Main");
} else if (profile == 88) {
strcpy(profileb, "Extended");
} else if (profile == 100) {
strcpy(profileb, "High");
} else if (profile == 110) {
strcpy(profileb, "High 10");
} else if (profile == 122) {
strcpy(profileb, "High 4:2:2");
} else if (profile == 144) {
strcpy(profileb, "High 4:4:4");
} else {
sprintf(profileb, "Unknown Profile %x", profile);
}
switch (level) {
case 10: case 20: case 30: case 40: case 50:
sprintf(levelb, "%u", level / 10);
break;
case 11: case 12: case 13:
case 21: case 22:
case 31: case 32:
case 41: case 42:
case 51:
sprintf(levelb, "%u.%u", level / 10, level % 10);
break;
default:
sprintf(levelb, "unknown level %x", level);
break;
}
sprintf(typebuffer, "H264 %s@%s", profileb, levelb);
typeName = typebuffer;
} else {
typeName = "H.264 - profile/level error";
}
foundTypeName = true;
} else if (strcasecmp(media_data_name, "s263") == 0) {
// 3gp h.263
typeName = "H.263";
foundTypeName = true;
} else if ((strcasecmp(media_data_name, "mp4v") == 0) ||
(strcasecmp(media_data_name, "encv") == 0)) {
// note encv might needs it's own field eventually.
type = MP4GetTrackEsdsObjectTypeId(mp4File, trackId);
if (type == MP4_MPEG4_VIDEO_TYPE) {
type = MP4GetVideoProfileLevel(mp4File, trackId);
typeName = Mpeg4VisualProfileName(type);
if (typeName == NULL) {
typeName = "MPEG-4 Unknown Profile";
} else {
foundTypeName = true;
}
} else {
for (u_int8_t i = 0; i < numMpegVideoTypes; i++) {
if (type == mpegVideoTypes[i]) {
typeName = mpegVideoNames[i];
foundTypeName = true;
break;
}
}
}
} else {
typeName = media_data_name;
foundTypeName = true; // we don't have a type value to display
}
MP4Duration trackDuration =
MP4GetTrackDuration(mp4File, trackId);
double msDuration =
UINT64_TO_DOUBLE(MP4ConvertFromTrackDuration(mp4File, trackId,
trackDuration, MP4_MSECS_TIME_SCALE));
u_int32_t avgBitRate =
MP4GetTrackBitRate(mp4File, trackId);
// Note not all mp4 implementations set width and height correctly
// The real answer can be buried inside the ES configuration info
u_int16_t width = MP4GetTrackVideoWidth(mp4File, trackId);
u_int16_t height = MP4GetTrackVideoHeight(mp4File, trackId);
double fps = MP4GetTrackVideoFrameRate(mp4File, trackId);
char *sInfo = (char*)MP4Malloc(256);
// type duration avgBitrate frameSize frameRate
if (foundTypeName) {
sprintf(sInfo,
"%u\tvideo\t%s%s, %.3f secs, %u kbps, %ux%u @ %f fps\n",
trackId,
MP4IsIsmaCrypMediaTrack(mp4File, trackId) ? "encv - " : "",
typeName,
msDuration / 1000.0,
(avgBitRate + 500) / 1000,
width,
height,
fps
);
} else {
sprintf(sInfo,
"%u\tvideo\t%s(%u), %.3f secs, %u kbps, %ux%u @ %f fps\n",
trackId,
typeName,
type,
msDuration / 1000.0,
(avgBitRate + 500) / 1000,
width,
height,
fps
);
}
return sInfo;
}
static char* PrintCntlInfo(
MP4FileHandle mp4File,
MP4TrackId trackId)
{
const char *media_data_name = MP4GetTrackMediaDataName(mp4File, trackId);
const char *typeName = "Unknown";
if (media_data_name == NULL) {
typeName = "Unknown - no media data name";
} else if (strcasecmp(media_data_name, "href") == 0) {
typeName = "ISMA Href";
} else {
typeName = media_data_name;
}
MP4Duration trackDuration =
MP4GetTrackDuration(mp4File, trackId);
double msDuration =
UINT64_TO_DOUBLE(MP4ConvertFromTrackDuration(mp4File, trackId,
trackDuration, MP4_MSECS_TIME_SCALE));
char *sInfo = (char *)MP4Malloc(256);
snprintf(sInfo, 256,
"%u\tcontrol\t%s, %.3f secs\n",
trackId,
typeName,
msDuration / 1000.0);
return sInfo;
}
static char* PrintHintInfo(
MP4FileHandle mp4File,
MP4TrackId trackId)
{
MP4TrackId referenceTrackId =
MP4GetHintTrackReferenceTrackId(mp4File, trackId);
char* payloadName = NULL;
MP4GetHintTrackRtpPayload(mp4File, trackId, &payloadName);
char *sInfo = (char*)MP4Malloc(256);
sprintf(sInfo,
"%u\thint\tPayload %s for track %u\n",
trackId,
payloadName,
referenceTrackId);
free(payloadName);
return sInfo;
}
static char* PrintTrackInfo(
MP4FileHandle mp4File,
MP4TrackId trackId)
{
char* trackInfo = NULL;
const char* trackType =
MP4GetTrackType(mp4File, trackId);
if (!strcmp(trackType, MP4_AUDIO_TRACK_TYPE)) {
trackInfo = PrintAudioInfo(mp4File, trackId);
} else if (!strcmp(trackType, MP4_VIDEO_TRACK_TYPE)) {
trackInfo = PrintVideoInfo(mp4File, trackId);
} else if (!strcmp(trackType, MP4_HINT_TRACK_TYPE)) {
trackInfo = PrintHintInfo(mp4File, trackId);
} else if (strcmp(trackType, MP4_CNTL_TRACK_TYPE) == 0) {
trackInfo = PrintCntlInfo(mp4File, trackId);
} else {
trackInfo = (char*)MP4Malloc(256);
if (!strcmp(trackType, MP4_OD_TRACK_TYPE)) {
sprintf(trackInfo,
"%u\tod\tObject Descriptors\n",
trackId);
} else if (!strcmp(trackType, MP4_SCENE_TRACK_TYPE)) {
sprintf(trackInfo,
"%u\tscene\tBIFS\n",
trackId);
} else {
sprintf(trackInfo,
"%u\t%s\n",
trackId, trackType);
}
}
return trackInfo;
}
extern "C" char* MP4Info(
MP4FileHandle mp4File,
MP4TrackId trackId)
{
char* info = NULL;
if (MP4_IS_VALID_FILE_HANDLE(mp4File)) {
__try {
if (trackId == MP4_INVALID_TRACK_ID) {
info = (char*)MP4Calloc(4*1024);
sprintf(info, "Track\tType\tInfo\n");
u_int32_t numTracks = MP4GetNumberOfTracks(mp4File);
for (u_int32_t i = 0; i < numTracks; i++) {
trackId = MP4FindTrackId(mp4File, i);
char* trackInfo = PrintTrackInfo(mp4File, trackId);
strcat(info, trackInfo);
MP4Free(trackInfo);
}
} else {
info = PrintTrackInfo(mp4File, trackId);
}
}
__except (EXCEPTION_EXECUTE_HANDLER) {
// delete e;
}
}
return info;
}
extern "C" char* MP4FileInfo(
const char* fileName,
MP4TrackId trackId)
{
MP4FileHandle mp4File =
MP4Read(fileName);
if (!mp4File) {
return NULL;
}
char* info = MP4Info(mp4File, trackId);
MP4Close(mp4File);
return info; // caller should free this
}
| [
"jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006"
] | [
[
[
1,
579
]
]
] |
858bfebe1b551d1e950e199bd4817baf116fe257 | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/UILayer/Functions/AddTask/AddTaskLinksEdit.h | 57b8065f84b581fedc6cc07913ebee2b4f26aab3 | [] | no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | h | #pragma once
#include "AddTaskDoc.h"
// CAddTaskLinksEdit
class CAddTaskLinksEdit : public CEdit
{
DECLARE_DYNAMIC(CAddTaskLinksEdit)
public:
CAddTaskLinksEdit();
virtual ~CAddTaskLinksEdit();
void SetDoc(CAddTaskDoc *pDoc){m_pDoc = pDoc;}
void UpdateLinksByWindowText();
protected:
void ConvertStrToStrList(CList<CString> *pList, const CString &str);
void AddText(LPCTSTR lpszText);
void RemoveLine(LPCTSTR lpszText);
void SetText(const CFileHashKey &key, LPCTSTR lpszText);
void RemoveText(const CFileHashKey &key);
CString RemoveLine(const CString &str, int iStart, int iEnd);
BOOL FindLineByKey(const CFileHashKey &key, int &iStartPos, int &iEndPos);
CAddTaskDoc *m_pDoc;
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnEnChange();
afx_msg LRESULT OnDocAdded(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnDocModified(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnDocUrlAdded(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnDocUrlModified(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnDocUrlRemoved(WPARAM wParam, LPARAM lParam);
};
| [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
] | [
[
[
1,
41
]
]
] |
4fd250681fab9865dc76f35db005ead1228b7a5d | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/ref1/src-root/include/common/interface/window.h | 49f8add6711a5cb0aed7694d3a2e92beea28dbd5 | [] | no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15T00:22:02.905112 | 2010-01-07T20:31:07 | 2010-01-07T20:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,964 | h | /* Copyright (C) 2005 ireon.org developers council
* $Id: window.h 510 2006-02-26 21:09:40Z zak $
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file window.h
* Interface window class
*/
#ifndef _WINDOW_H
#define _WINDOW_H
#include <OgreNoMemoryMacros.h>
#include <CEGUI/elements/CEGUIStaticText.h>
#include <CEGUI/CEGUIForwardRefs.h>
#include <OgreMemoryMacros.h>
struct WindowEvent;
class CWindow
{
friend class CInterface;
protected:
CWindow(CEGUI::Window* win);
public:
virtual ~CWindow();
virtual bool init();
virtual void deInit();
// CEGUI::Window* win() {return m_window;}
uint getChildCount() const {return (uint)m_children.size();}
WndPtr getChildAtIdx(size_t s) const {return m_children[s];}
void addChildWindow(const WndPtr& win);
void removeChild(size_t s);
void disable();
void enable();
bool isVisible();
void setVisible(bool);
bool isActive();
void activate();
float getAlpha();
void setAlpha(float);
String getName();
Vector2 getPosition();
void setPosition(const Vector2& p);
Vector2 getAbsolutePosition();
void setAbsolutePosition(const Vector2& p);
Vector2 getSize();
void setSize(const Vector2&);
/** Set unified width
* see CEGUI documentation for details about unified
* coords
*/
void setUWidth(const Vector2&);
/** Set unified height
* see CEGUI documentation for details about unified
* coords
*/
void setUHeight(const Vector2&);
/** Get unified width
*/
Vector2 getUWidth();
/** Get unified height
*/
Vector2 getUHeight();
/** Set unified X coordinate
*/
void setUX(const Vector2& x);
/** Get unified X coordinate
*/
Vector2 getUX();
/** Set unified Y coordinate
*/
void setUY(const Vector2& y);
/** Get unified Y coordinate
*/
Vector2 getUY();
String getText();
void setText(const String&);
void setAlwaysOnTop(bool);
void subscribeEvent(const CEGUI::String& type, const WindowEvent& evt);
void subscribeEvent(const CEGUI::String& type, const WindowKeyEvent& evt);
CInterface::WinType type() {return m_type;}
bool active() {return m_active;}
protected:
CEGUI::Window* m_window;
std::vector<WndPtr> m_children;
std::vector<WndPtr>::iterator it;
CInterface::WinType m_type;
///Window was created, so can be destroyed
bool m_created;
///Is window in tree?
bool m_active;
};
class CFrameWindow : public CWindow
{
friend class CInterface;
protected:
CFrameWindow(CEGUI::Window* win): CWindow(win) {}
public:
void setCloseButtonEnabled(bool);
void setDragMovingEnabled(bool);
void setFrameEnabled(bool);
void setSizingEnabled(bool);
};
class CMultiListWindow : public CWindow
{
friend class CInterface;
protected:
CMultiListWindow(CEGUI::Window* win);
public:
bool init();
void deInit();
CEGUI::MultiColumnList* win() {return (CEGUI::MultiColumnList*)m_window;}
///Clear list
void reset();
///Set number of cols
void setCol(byte col);
///Set column widths
void setWidth(std::vector<byte> &vec);
///Insert row with values
uint insertRow(StringVector values, int id = -1);
///Get value at cell
String getValue(uint row, uint col);
///Get row count
uint getRowCount();
///Get col count
uint getColCount() {return m_colCount;}
void setHead(uint idx, const String& str);
///Get first selected item's id
int getFirstSelected();
/// Set selected row
void setSelected(uint row);
protected:
byte m_colCount;
};
class CStaticTextWindow : public CWindow
{
friend class CInterface;
protected:
CStaticTextWindow(CEGUI::Window* win):CWindow(win){};
public:
void setFormatting(CEGUI::StaticText::HorzFormatting, CEGUI::StaticText::VertFormatting);
void setBackgroundEnabled(bool);
void setVerticalScrollbarEnabled(bool);
void setFrameEnabled(bool);
void setTextColour(CEGUI::colour col);
};
class CStaticImage : public CWindow
{
friend class CInterface;
protected:
CStaticImage(CEGUI::Window* win):CWindow(win){};
public:
void setImage(const String& imageset, const String& image);
void setColour(const CEGUI::colour& col);
};
class CCheckBox : public CWindow
{
friend class CInterface;
protected:
CCheckBox(CEGUI::Window* win):CWindow(win){};
public:
bool isChecked();
void setChecked(bool);
};
class CListBox: public CWindow
{
friend class CInterface;
protected:
CListBox(CEGUI::Window* win):CWindow(win){};
public:
void addRow(const String& str, CEGUI::colour col);
void removeRow(uint num);
void clear();
void clearSelection();
};
class CScrollBar : public CWindow
{
friend class CInterface;
protected:
CScrollBar(CEGUI::Window* win):CWindow(win){};
public:
/// Is scrollbar at the end of document
bool atEnd();
/// Set scrollbar position to the end of document
void toEnd();
/// Set scrollbar position
void setScrollPosition(float pos);
float getScrollPosition();
float getPageSize();
};
class CProgressBar : public CWindow
{
friend class CInterface;
protected:
CProgressBar(CEGUI::Window* win):CWindow(win){};
public:
void setProgress(float progress);
float getProgress();
};
#endif | [
"[email protected]"
] | [
[
[
1,
276
]
]
] |
0288235ec980cb4215523be884843496a94056b1 | 3856c39683bdecc34190b30c6ad7d93f50dce728 | /LastProject/Source/Mouse.h | 7613cc9ebd2efe99c27b08e9c546a4c3b8a79787 | [] | 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 | 761 | h | #pragma once
#ifndef _MOUSE_H_
#define _MOUSE_H_
class Mouse : public CSingleton<Mouse> //한번만 누르는건 구현이 되지 않았음 & 0x8001 을 쓰면 되겟는데 함수 이름은 뭘로? LButton One Click? 이상해...
{
friend class CSingleton<Mouse>;
private:
HWND m_hWnd;
bool m_bLKeyUp;
bool m_bLKeyDown;
bool m_bLDrag;
RECT m_rt; //윈도우 크기 밖으로는 나가지 마셔라
POINT m_pt;
public:
Mouse()
{
m_bLKeyUp = true;
m_bLKeyDown = false;
m_bLDrag = false;
}
virtual ~Mouse(){}
void Initialize( HWND a_hWnd );
void Update();
bool LButton_Up();
bool LButton_Down();
bool LButton_Drag();
bool IsClickedLButton();
POINT GetPosition();
};
#endif | [
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0",
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0"
] | [
[
[
1,
25
],
[
27,
40
]
],
[
[
26,
26
]
]
] |
21dc460a2319537f6ff79577ae82a9d7cb4eca2a | 1deb3507c241b7e2417ba041c9c71cb5cf7eef06 | /heroin/utility.cpp | 2ca0ec685caeb0e8694a96f7b14ec563054e5020 | [] | no_license | ChefKeeper/heroinglands | 2a076db02bc48d578eb1d8d0eb2771079e8a9e9d | 4585a4adf8c6f3b42e57928fe956cddb5a91ef1a | refs/heads/master | 2016-08-13T02:20:18.085064 | 2009-02-13T20:30:21 | 2009-02-13T20:30:21 | 47,699,838 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,981 | cpp | #include "utility.hpp"
#include <iostream>
#include <sstream>
#include <nil/time.hpp>
std::string get_data_string(std::string const & data)
{
std::stringstream stream;
for(std::size_t i = 0; i < data.size(); i++)
{
stream << std::hex;
stream.width(2);
stream.fill('0');
stream << get_byte(data, i) << " ";
}
return stream.str();
}
void print_data(std::string const & data)
{
std::cout << get_data_string(data) << std::endl;
}
void print_dword(ulong dword)
{
std::cout << std::hex;
std::cout.width(8);
std::cout.fill('0');
std::cout << dword;
}
std::string get_dword_string(ulong dword)
{
std::stringstream stream;
for(ulong i = 0; i < 4; i++)
{
stream << std::hex;
stream.width(2);
stream.fill('0');
stream << ((dword >> (i * 8)) & 0xff);
}
return stream.str();
}
ulong read_number(std::string const & input, std::size_t offset, std::size_t size)
{
ulong output = 0;
for(std::size_t i = 0; i < size; i++, offset++)
{
unsigned char byte = static_cast<unsigned char>(input[offset]);
output |= byte << (i * 8);
}
return output;
}
ulong read_nbo_number(std::string const & input, std::size_t offset, std::size_t size)
{
ulong output = 0;
for(std::size_t i = 0; i < size; i++, offset++)
{
unsigned char byte = static_cast<unsigned char>(input[offset]);
output <<= 8;
output |= byte;
}
return output;
}
ulong read_nbo_dword(std::string const & input, std::size_t offset)
{
return read_nbo_number(input, offset, 4);
}
ulong read_nbo_word(std::string const & input, std::size_t offset)
{
return read_nbo_number(input, offset, 2);
}
ulong read_dword(std::string const & input, std::size_t offset)
{
return read_number(input, offset, 4);
}
ulong read_word(std::string const & input, std::size_t offset)
{
return read_number(input, offset, 2);
}
ulong char_to_byte(char input)
{
return static_cast<ulong>(static_cast<unsigned char>(input));
}
ulong read_byte(std::string const & input, std::size_t offset)
{
return char_to_byte(input[offset]);
}
std::string number_to_string(ulong input, ulong size)
{
std::string output;
for(ulong i = 0; i < size; i++)
output.push_back(static_cast<char>((input >> (i * 8)) & 0xff));
return output;
}
std::string dword_to_string(ulong input)
{
return number_to_string(input, 4);
}
std::string word_to_string(ulong input)
{
return number_to_string(input, 2);
}
std::string byte_to_string(ulong input)
{
return number_to_string(input, 1);
}
std::string char_to_string(char input)
{
std::stringstream stream;
stream << std::hex;
stream.width(2);
stream.fill('0');
stream << char_to_byte(input);
return stream.str();
}
ulong get_byte(std::string const & input, std::size_t offset)
{
return static_cast<ulong>(static_cast<unsigned char>(input[offset]));
}
ulong get_tick_count()
{
return static_cast<ulong>(nil::boot_time());
}
| [
"binrapt@92c0f8f3-e753-0410-a10c-b3df2c4a8671"
] | [
[
[
1,
141
]
]
] |
c0772ccecace0a287c8daeb2620827783cf1d2c0 | 629e4fdc23cb90c0144457e994d1cbb7c6ab8a93 | /lib/entity/component.h | 8e4b5f8339e0242ab81869e79953f3f1aea15c48 | [] | no_license | akin666/ice | 4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2 | 7cfd26a246f13675e3057ff226c17d95a958d465 | refs/heads/master | 2022-11-06T23:51:57.273730 | 2011-12-06T22:32:53 | 2011-12-06T22:32:53 | 276,095,011 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,680 | h | /*
* component.h
*
* Created on: 14.10.2011
* Author: akin
*
* Without aspect oriented programming, this class causes a bit of trouble
* especially, if you forget to add _one_ finish() call to the end of the
* execution of your component.
* If the component is single-threaded, make sure that start() calls finish
* at the end! If it is multi-threaded, you just some magical way, must make
* sure that it gets called.
*/
#ifndef ICE_COMPONENT_H_
#define ICE_COMPONENT_H_
#include <string>
#include <set>
#include "componentexception.h"
#include "componentwork"
namespace ice
{
class Entity;
class ComponentNode;
class Component
{
protected:
unsigned int concurrent_reference_counting;
protected:
static unsigned int sm_id;
static unsigned int getNewId();
unsigned int id;
std::string name;
bool concurrent;
unsigned int priority;
std::set<std::string> dependencies;
ComponentNode *componentNode;
void addDependency( std::string dependency );
void setPriority( unsigned int prio );
public:
Component( std::string name , bool concurrent = false) throw (ComponentException);
virtual ~Component();
void setComponentNode( ComponentNode *cn );
// get string identifier of the component
std::string getName() const;
// get integer identifier of the component
// decided on runtime!
unsigned int getId() const;
// Figure out if this component can be before the linked component
virtual bool before( Component& component ) throw (ComponentException);
// Generate list of components dependencies
virtual void getDependencyList( std::set<std::string>& list ) throw (ComponentException);
bool isConcurrent();
// Return components priority
unsigned int getPriority();
// Attach / Detach an entity to the component.
virtual void attach( Entity& entity ) throw (ComponentException) = 0;
virtual void detach( Entity& entity ) throw (ComponentException) = 0;
// Start can be blocking, if the component wants to go singlethreaded.
// on multithreaded situation, it should start work packages, but not block.
// Once all computing is done, finish() has to be called.
virtual void start() throw (ComponentException);
public:
// finish should be called, once the thread/all the stuff the component is doing
// is done. Not before! Applies to singlethreaded mode too!.
void finish();
void execute();
void schedule( ComponentWork& work ) throw (ComponentException);
void finished( ComponentWork& work );
};
} /* namespace ice */
#endif /* COMPONENT_H_ */
| [
"akin@lich",
"akin@localhost"
] | [
[
[
1,
14
],
[
17,
19
],
[
22,
24
],
[
27,
27
],
[
35,
35
],
[
41,
42
],
[
45,
45
],
[
51,
51
],
[
53,
53
],
[
56,
56
],
[
60,
60
],
[
63,
63
],
[
66,
66
],
[
68,
68
],
[
71,
71
],
[
75,
75
],
[
90,
92
]
],
[
[
15,
16
],
[
20,
21
],
[
25,
26
],
[
28,
34
],
[
36,
40
],
[
43,
44
],
[
46,
50
],
[
52,
52
],
[
54,
55
],
[
57,
59
],
[
61,
62
],
[
64,
65
],
[
67,
67
],
[
69,
70
],
[
72,
74
],
[
76,
89
]
]
] |
41acae276efa27372cae9b0973dff4ac1a4fae9d | 3d9e738c19a8796aad3195fd229cdacf00c80f90 | /src/geometries/medial_explore_3/Medial_explore_3.h | 5305a97dd55f5bc897fb85737ab37fd9d3a683fc | [] | no_license | mrG7/mesecina | 0cd16eb5340c72b3e8db5feda362b6353b5cefda | d34135836d686a60b6f59fa0849015fb99164ab4 | refs/heads/master | 2021-01-17T10:02:04.124541 | 2011-03-05T17:29:40 | 2011-03-05T17:29:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,298 | h | /* This source file is part of Mesecina, a software for visualization and studying of
* the medial axis and related computational geometry structures.
* More info: http://www.agg.ethz.ch/~miklosb/mesecina
* Copyright Balint Miklos, Applied Geometry Group, ETH Zurich
*
* $Id: Union_of_balls_2.h 737 2009-05-16 15:40:46Z miklosb $
*/
#ifndef MESECINA_MEDIAL_EXPLORE_3_H
#define MESECINA_MEDIAL_EXPLORE_3_H
#include <geometries/Geometry.h>
#include <list>
#include <vector>
#include <string>
#ifdef MESECINA_GEOMETRY_LIBRARY
#define MV_API __declspec( dllexport )
#else
#define MV_API __declspec( dllimport )
#endif
#include "Medial_axis_structure_3.h"
using namespace medial;
class MV_API Medial_explore_3 : public Geometry {
public:
Medial_explore_3();
virtual ~Medial_explore_3();
virtual Geometry* clone();
// methods to communicate with other geometries
//virtual std::list<std::string> offer_structures();
//virtual void* give_structure(const std::string& name);
virtual void receive_structure_changed(const std::string& name);
// points communication with user interface
//virtual void add_points(std::list<Point3D>*);
//virtual std::list<Point3D>* get_points();
// ball communication with user interface
//virtual void add_weighted_points(std::list<Point4D>*);
//virtual std::list<Point4D>* get_weighted_points();
// directly handle file io
virtual void load_generic_file(const std::string&);
//virtual void save_generic_file(const std::string&);
// receive application settings changes
virtual void application_settings_changed(const QString&);
// modification for evolutions
//virtual void apply_modification(const std::string& );
Medial_axis_transform_3* get_medial_axis();
Medial_axis_transform_3* get_topology_filtered_medial_axis();
std::vector<std::set<Face*> >* get_medial_axis_sheets();
std::vector<double>* get_sheet_topology_angle_stability();
std::vector<Ball>* get_sampled_balls();
void write_mesh_balls(const std::string& file_name, std::vector<Ball>* balls);
void invalidate_cache();
Medial_axis_transform_3 mat;
//private:
bool has_topology_filtration, has_sheets, has_topology_sheets, has_mat, has_balls;
};
#endif //MESECINA_MEDIAL_EXPLORE_3_H | [
"balint.miklos@localhost"
] | [
[
[
1,
72
]
]
] |
d33878f2301c737782f56439e6fcc74b62f25cdd | 197ac28d1481843225f35aff4aa85f1909ef36bf | /mcucpp/delay.h | afe3120cf46db0bc466a11af8a03a5b3a5f26c16 | [
"BSD-3-Clause"
] | permissive | xandroalmeida/Mcucpp | 831e1088eb38dfcf65bfb6fb3205d4448666983c | 6fc5c8d5b9839ade60b3f57acc78a0ed63995fca | refs/heads/master | 2020-12-24T12:13:53.497692 | 2011-11-21T15:36:03 | 2011-11-21T15:36:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,379 | h | #pragma once
// platform specific delay loop implementation
#include <platform_dalay.h>
#include <clock.h>
namespace Util
{
template<unsigned long ns, unsigned long CpuFreq>
void delay_ns()
{
const unsigned long delayLoops32 = CpuFreq / (1.0e9 * PlatformCyslesPerDelayLoop32) * ns;
const unsigned long delayLoops16 = CpuFreq / (1.0e9 * PlatformCyslesPerDelayLoop16) * ns;
const unsigned long delayLoops8 = CpuFreq / (1.0e9 * PlatformCyslesPerDelayLoop8) * ns;
if(delayLoops16 > 0xfffful)
PlatformDelayCycle32(delayLoops32);
else if(delayLoops8 > 0xfful)
PlatformDelayCycle16((uint16_t)delayLoops16);
else PlatformDelayCycle8((uint8_t)delayLoops8);
}
template<unsigned long us, unsigned long CpuFreq >
void delay_us()
{
const unsigned long delayLoops32 = CpuFreq / (1.0e6 * PlatformCyslesPerDelayLoop32) * us;
const unsigned long delayLoops16 = CpuFreq / (1.0e6 * PlatformCyslesPerDelayLoop16) * us;
const unsigned long delayLoops8 = CpuFreq / (1.0e6 * PlatformCyslesPerDelayLoop8) * us;
if(delayLoops16 > 0xfffful)
PlatformDelayCycle32(delayLoops32);
else if(delayLoops8 > 0xfful)
PlatformDelayCycle16((uint16_t)delayLoops16);
else PlatformDelayCycle8((uint8_t)delayLoops8);
}
template<unsigned long ms, unsigned long CpuFreq>
void delay_ms()
{
delay_us<ms * 1000, CpuFreq>();
}
}
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
4
],
[
6,
14
],
[
16,
21
],
[
24,
28
],
[
30,
35
],
[
37,
42
]
],
[
[
5,
5
],
[
15,
15
],
[
22,
23
],
[
29,
29
],
[
36,
36
]
]
] |
f4df819d8e6acc4b82bcf6af0bce16c763459cca | cb1c6c586d769f919ed982e9364d92cf0aa956fe | /include/TinyRT.h | 73ca77dffca84ed031f95a85c3d9d762f326566f | [] | no_license | jrk/tinyrt | 86fd6e274d56346652edbf50f0dfccd2700940a6 | 760589e368a981f321e5f483f6d7e152d2cf0ea6 | refs/heads/master | 2016-09-01T18:24:22.129615 | 2010-01-07T15:19:44 | 2010-01-07T15:19:44 | 462,454 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,956 | h |
/// \defgroup TinyRT TinyRT
/**
\mainpage
What TRT is:
The goal of TRT is to provide a set of clean, generic, and reasonably efficient implementations of common raytracing algorithms.
Its intended uses are:
- As a reference codebase for research, prototyping, and recreational raytracing
- As a starting point for a renderer
- As a drop-in solution for 'lightweight' raycasting applications (such as collision detection or line-of-sight detection)
TRT is template driven, and is organized around a set of 'concepts'. The most central concept is the ObjectSet.
To incorporate one of TRT's raytracing data structures, all that is needed is to define a class which implements TinyRT::ObjectSet_C.
Given an object set class, it is straightforward to use TinyRT to construct a variety of raytracing data structures.
\sa TRTConcepts
TRT provides a pair of object set implementations for triangle meshes, but at the moment, object support is rather sparse.
\sa TinyRT::BasicMesh, TinyRT::StridedMesh
What TRT is not:
- TRT is not a complete renderer, only a collection of usable components.
TRT provides many of the components needed to build a simple raytracer, but geometry loading, image sampling, shading, and output
must all be implemented at the application level.
- TRT is not a high performance raycasting library (nor does it claim to be).
TRT's priority is to be generic, flexible, and modular. Although every effort has been made to optimize TRT's raycasting functions,
they have been deliberately designed to use a very general interface, in order to support as many diverse data structure implementations
as possible. This generality is likely to result in worse performance than could be acheived by an implementation which is specialized
for a particular data structure. For performance critical applications, it is best to pair TRT's data structure classes with a customized
raytracing kernel.
*/
#ifndef _TINYRT_H_
#define _TINYRT_H_
#include <vector>
#include <limits>
#include <float.h>
#include <string.h> // for memcpy
#ifndef TRT_FORCEINLINE
#ifdef __GNUC__
// If we use the GCC equivalent of __forceinline, GCC sometimes fails to inline things, and errors out when that happens...
/// Macro to force function inlining
#define TRT_FORCEINLINE inline
#else
/// Macro to force function inlining
#define TRT_FORCEINLINE __forceinline
#endif
#endif
/// Minimum distance used for epsilon rays. TRT clients may #define TRT_EPSILON to override its value
#ifndef TRT_EPSILON
#define TRT_EPSILON 0.000001f
#endif
#include "TRTAssert.h"
#include "TRTTypes.h"
#include "TRTMalloc.h"
#include "TRTSimd.h"
#include "TRTMath.h"
#include "TRTScratchMemory.h"
// Utility classes
#include "TRTAxisAlignedBox.h"
#include "TRTPacketFrustum.h"
#include "TRTPerspectiveCamera.h"
#include "TRTScopedArray.h"
#include "TRTObjectUtils.h"
// Analysis utilities
#include "TRTTreeStatistics.h"
#include "TRTCostMetric.h"
// Rays
#include "TRTRay.h"
#include "TRTEPsilonRay.h"
// Basic intersection testing
#include "TRTTriIntersect.h"
#include "TRTBoxIntersect.h"
// Mailboxing
#include "TRTNullMailbox.h"
#include "TRTFifoMailbox.h"
#include "TRTDirectMapMailbox.h"
#include "TRTSimdFifoMailbox.h"
// Object sets
#include "TRTBasicMesh.h"
#include "TRTStridedMesh.h"
// AABB trees
#include "TRTMedianCutAABBTreeBuilder.h"
#include "TRTSahAABBTreeBuilder.h"
#include "TRTAABBTree.h"
#include "TRTBVHTraversal.h"
// QBVH
#include "TRTQuadAABBTree.h"
#include "TRTMultiBVHTraversal.h"
// Uniform Grids
#include "TRTUniformGrid.h"
#include "TRTGridTraversal.h"
// KD Trees
#include "TRTKDTree.h"
#include "TRTKDTraversal.h"
#include "TRTSahKDTreeBuilder.h"
#include "TRTBoxClipper.h"
#endif
| [
"jbarcz1@6ce04321-59f9-4392-9e3f-c0843787e809"
] | [
[
[
1,
131
]
]
] |
16afe383d73324f9e8f1c1dcf474b6eb4d13baa9 | 6581dacb25182f7f5d7afb39975dc622914defc7 | /easyMule/easyMule/src/UILayer/PPgConnection.h | f0de367be5c2cfdcc482ebfdb9b457ae7c34b813 | [] | no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,283 | h | /*
* $Id: PPgConnection.h 5130 2008-03-25 10:43:20Z fengwen $
*
* this file is part of easyMule
* Copyright (C)2002-2008 VeryCD Dev Team ( strEmail.Format("%s@%s", "emuledev", "verycd.com") / http: * www.easymule.org )
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#pragma once
#include "BetterSP2.h" //Added by thilon 2006.08.07
#include "ToolTipCtrlZ.h"
#include "numericedit.h"
class CPPgConnection : public CPropertyPage
{
DECLARE_DYNAMIC(CPPgConnection)
public:
CPPgConnection();
virtual ~CPPgConnection();
// Dialog Data
enum { IDD = IDD_PPG_CONNECTION };
void Localize(void);
void LoadSettings(void);
protected:
bool guardian;
// VC-kernel[2007-03-02]:
CSliderCtrl m_ctlMaxDown;
CSliderCtrl m_ctlMaxUp;
CComboBox m_ctlConnectionType;
// VC-kernel[2007-02-27]:
bool m_iUPnPNat;
bool m_iUPnPTryRandom;
int m_iMaxHalfOpen;
int m_isXP; //Added by thilon on 2006.08.07
CBetterSP2 m_betterSP2; //Added by thilon on 2006.08.07
int m_iTCPIPInit; //Added by thilon on 2006.08.07
CToolTipCtrlZ m_ttc;
//ADDED by VC-fengwen on 2008/03/18 <begin> :
void LoadSpeedValues();
void SaveSpeedValues();
BOOL m_bConnectionTypeChanging;
void UpdateConnectionType(int iType);
void ConnTypeToCustomize();
UINT GetDownCapacity();
UINT GetUpCapacity();
BOOL GetDownLimitSwitch(){return IsDlgButtonChecked(IDC_DLIMIT_LBL);}
BOOL GetUpLimitSwitch(){return IsDlgButtonChecked(IDC_ULIMIT_LBL);}
UINT GetDownLimitValue(){return m_uDownloadLimitValue;}
UINT GetUpLimitValue(){return m_uUploadLimitValue;}
void UpdateDownCapacity(UINT uCapacity, BOOL bUpdateEdit = TRUE);
void UpdateUpCapacity(UINT uCapacity, BOOL bUpdateEdit = TRUE);
void UpdateDownLimitSwitch(BOOL bLimit);
void UpdateUpLimitSwitch(BOOL bLimit);
void UpdateDownLimitValue(UINT uLimit);
void UpdateUpLimitValue(UINT uLimit);
//ADDED by VC-fengwen on 2008/03/18 <end> :
BOOL ValidateInputs(BOOL bPrompt = TRUE, BOOL bFocus = TRUE);
void SetRateSliderTicks(CSliderCtrl& rRate);
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
virtual BOOL OnApply();
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnSettingsChange() { SetModified(); }
afx_msg void OnEnChangeUDPDisable();
afx_msg void OnBnClickedDLimit();
afx_msg void OnBnClickedULimit();
afx_msg void OnBnClickedWizard();
afx_msg void OnBnClickedNetworkKademlia();
afx_msg void OnHelp();
afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
afx_msg void OnBnClickedOpenports();
afx_msg void OnStartPortTest();
afx_msg void OnEnChangeTCP();
afx_msg void OnEnChangeUDP();
afx_msg void OnEnChangePorts(uint8 istcpport);
public:
afx_msg void OnBnClickedRandomPort();
afx_msg void OnChangeSpin(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnEnChangeDownloadCap();
afx_msg void OnEnChangeUploadCap();
afx_msg void OnCbnSelchangeConnectiontype();
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
CNumericEdit m_MaxHalfConEdit;
CNumericEdit m_MaxConEdit;
CNumericEdit m_MaxSourcePerFileEdit;
CNumericEdit m_DownloadEdit;
CNumericEdit m_UploadEdit;
CNumericEdit m_PortEdit;
CNumericEdit m_UDPPortEdit;
UINT m_uDownloadLimitValue; // 因为ScrollCtrl不能及时更新它的Position值,所以用变量来表示。
UINT m_uUploadLimitValue; // 因为ScrollCtrl不能及时更新它的Position值,所以用变量来表示。
};
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
] | [
[
[
1,
124
]
]
] |
1f43268edd6349ad84df73bca8277b5e28a5d3b2 | 59166d9d1eea9b034ac331d9c5590362ab942a8f | /Branch/xmlRoot/xmlLeaf/xmlLeafSave.cpp | e0390b1d87b3a9df43b9fed48947385d1eee6e88 | [] | no_license | seafengl/osgtraining | 5915f7b3a3c78334b9029ee58e6c1cb54de5c220 | fbfb29e5ae8cab6fa13900e417b6cba3a8c559df | refs/heads/master | 2020-04-09T07:32:31.981473 | 2010-09-03T15:10:30 | 2010-09-03T15:10:30 | 40,032,354 | 0 | 3 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 5,218 | cpp | #include "xmlLeafSave.h"
#include "../xmlRoot.h"
#include "xmlLeafNames.h"
xmlLeafSave::xmlLeafSave()
{
}
xmlLeafSave::~xmlLeafSave()
{
}
TiXmlElement* xmlLeafSave::GetXmlData()
{
//получить xml тег с сформированными данными
//получить ссылку на данные веток
dataLeaf &_data = xmlRoot::Instance().GetDataLeaf();
//формируем корневой узел данных
TiXmlElement *pLeaf = NULL;
pLeaf = new TiXmlElement( m_LeafNames.m_sLeaf.c_str() );
//заполнить данными о текстурах
FillTextures( _data , pLeaf );
//заполнить данными о ветре
FillWind( pLeaf );
//формирование записей LOD'ов
FillLODs( _data , pLeaf );
return pLeaf;
}
void xmlLeafSave::FillLODs( const dataLeaf &_data , TiXmlElement* root )
{
//формирование записей LOD'ов
TiXmlElement *pLods = NULL;
pLods = new TiXmlElement( m_LeafNames.m_sLODs.c_str() );
//количество LOD's
pLods->SetAttribute( m_LeafNames.m_sNum.c_str() , _data.m_vLfLOD.size() );
for( int i = 0 ; i < _data.m_vLfLOD.size() ; ++i )
{
//создать запись для вершин
TiXmlElement *pLod = NULL;
pLod = new TiXmlElement( m_LeafNames.m_sLOD.c_str() );
//номер LOD's
pLod->SetAttribute( m_LeafNames.m_sNum.c_str() , i );
//номер LOD's
pLod->SetDoubleAttribute( m_LeafNames.m_sAlfaTest.c_str() , _data .m_vLfLOD[ i ].m_fAlphaTestValue );
//заполнить данными о координатах
FillVertex( _data .m_vLfLOD[ i ] , pLod );
pLods->LinkEndChild( pLod );
}
root->LinkEndChild( pLods );
}
void xmlLeafSave::FillTextures( const dataLeaf &_data , TiXmlElement* root )
{
//заполнить данными о текстурах
//создать запись для текстур
TiXmlElement *pTextures = NULL;
pTextures = new TiXmlElement( m_LeafNames.m_sTextures.c_str() );
//количество текстур
pTextures->SetAttribute( m_LeafNames.m_sNum.c_str() , _data.m_vTextures.size() );
for ( int i = 0 ; i < _data.m_vTextures.size() ; ++i )
{
TiXmlElement *pTexture = NULL;
pTexture = new TiXmlElement( m_LeafNames.m_sTexture.c_str() );
//количество текстур
pTexture->SetAttribute( m_LeafNames.m_sVal.c_str() , _data.m_vTextures[ i ].c_str() );
pTextures->LinkEndChild( pTexture );
}
root->LinkEndChild( pTextures );
}
void xmlLeafSave::FillVertex( const dataLfLOD &_data , TiXmlElement* root )
{
//создать запись для вершин
TiXmlElement *pVertexs = NULL;
pVertexs = new TiXmlElement( m_LeafNames.m_sVertexs.c_str() );
//количество вершин
pVertexs->SetAttribute( m_LeafNames.m_sNum.c_str() , _data.m_vCoords.size() / 3 );
for ( int i = 0; i < _data.m_vCoords.size() / 3; ++i )
{
//формирем узел очередной точки
TiXmlElement *pPoint = new TiXmlElement( m_LeafNames.m_sPoint.c_str() );
//атрибуты точки
pPoint->SetDoubleAttribute( m_LeafNames.m_sX.c_str() , _data.m_vCoords[ i * 3 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_sY.c_str() , _data.m_vCoords[ i * 3 + 1 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_sZ.c_str() , _data.m_vCoords[ i * 3 + 2 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_snX.c_str() , _data.m_vNormals[ i * 3 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_snY.c_str() , _data.m_vNormals[ i * 3 + 1 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_snZ.c_str() , _data.m_vNormals[ i * 3 + 2 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_sS0.c_str() , _data.m_vTexCoords0[ i * 4 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_sT0.c_str() , _data.m_vTexCoords0[ i * 4 + 1 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_sP0.c_str() , _data.m_vTexCoords0[ i * 4 + 2 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_sQ0.c_str() , _data.m_vTexCoords0[ i * 4 + 3 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_sS1.c_str() , _data.m_vTexCoords1[ i * 3 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_sT1.c_str() , _data.m_vTexCoords1[ i * 3 + 1 ] );
pPoint->SetDoubleAttribute( m_LeafNames.m_sP1.c_str() , _data.m_vTexCoords1[ i * 3 + 2 ] );
pVertexs->LinkEndChild( pPoint );
}
root->LinkEndChild( pVertexs );
}
void xmlLeafSave::FillWind( TiXmlElement* root )
{
//заполнить данными о ветре
//создать запись для ветра
TiXmlElement *pWind = NULL;
pWind = new TiXmlElement( m_LeafNames.m_sWind.c_str() );
//частота вращения вокруг оси Y
pWind->SetAttribute( m_LeafNames.m_sFreqY.c_str() , 0 );
//амплитуда вращения вокруг оси Y
pWind->SetAttribute( m_LeafNames.m_sAmplY.c_str() , 0 );
//частота вращения вокруг оси Z
pWind->SetAttribute( m_LeafNames.m_sFreqZ.c_str() , 0 );
//амплитуда вращения вокруг оси Z
pWind->SetAttribute( m_LeafNames.m_sAmplZ.c_str() , 0 );
root->LinkEndChild( pWind );
} | [
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
] | [
[
[
1,
155
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.