blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a422edebeaaf6a738bd6c9425f22ecd4ceed80ee | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/crypto++/5.2.1/rijndael.cpp | 3b4a361a3f27d52398a46ea2f7d4a1832a22718a | [
"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 | 10,630 | cpp | // rijndael.cpp - modified by Chris Morgan <[email protected]>
// and Wei Dai from Paulo Baretto's Rijndael implementation
// The original code and all modifications are in the public domain.
// This is the original introductory comment:
/**
* version 3.0 (December 2000)
*
* Optimised ANSI C code for the Rijndael cipher (now AES)
*
* author Vincent Rijmen <[email protected]>
* author Antoon Bosselaers <[email protected]>
* author Paulo Barreto <[email protected]>
*
* This code is hereby placed in the public domain.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''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 AUTHORS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "rijndael.h"
#include "misc.h"
NAMESPACE_BEGIN(CryptoPP)
void Rijndael::Base::UncheckedSetKey(CipherDir dir, const byte *userKey, unsigned int keylen)
{
AssertValidKeyLength(keylen);
m_rounds = keylen/4 + 6;
m_key.New(4*(m_rounds+1));
word32 temp, *rk = m_key;
unsigned int i=0;
GetUserKey(BIG_ENDIAN_ORDER, rk, keylen/4, userKey, keylen);
switch(keylen)
{
case 16:
while (true)
{
temp = rk[3];
rk[4] = rk[0] ^
(Te4[GETBYTE(temp, 2)] & 0xff000000) ^
(Te4[GETBYTE(temp, 1)] & 0x00ff0000) ^
(Te4[GETBYTE(temp, 0)] & 0x0000ff00) ^
(Te4[GETBYTE(temp, 3)] & 0x000000ff) ^
rcon[i];
rk[5] = rk[1] ^ rk[4];
rk[6] = rk[2] ^ rk[5];
rk[7] = rk[3] ^ rk[6];
if (++i == 10)
break;
rk += 4;
}
break;
case 24:
while (true) // for (;;) here triggers a bug in VC60 SP4 w/ Processor Pack
{
temp = rk[ 5];
rk[ 6] = rk[ 0] ^
(Te4[GETBYTE(temp, 2)] & 0xff000000) ^
(Te4[GETBYTE(temp, 1)] & 0x00ff0000) ^
(Te4[GETBYTE(temp, 0)] & 0x0000ff00) ^
(Te4[GETBYTE(temp, 3)] & 0x000000ff) ^
rcon[i];
rk[ 7] = rk[ 1] ^ rk[ 6];
rk[ 8] = rk[ 2] ^ rk[ 7];
rk[ 9] = rk[ 3] ^ rk[ 8];
if (++i == 8)
break;
rk[10] = rk[ 4] ^ rk[ 9];
rk[11] = rk[ 5] ^ rk[10];
rk += 6;
}
break;
case 32:
while (true)
{
temp = rk[ 7];
rk[ 8] = rk[ 0] ^
(Te4[GETBYTE(temp, 2)] & 0xff000000) ^
(Te4[GETBYTE(temp, 1)] & 0x00ff0000) ^
(Te4[GETBYTE(temp, 0)] & 0x0000ff00) ^
(Te4[GETBYTE(temp, 3)] & 0x000000ff) ^
rcon[i];
rk[ 9] = rk[ 1] ^ rk[ 8];
rk[10] = rk[ 2] ^ rk[ 9];
rk[11] = rk[ 3] ^ rk[10];
if (++i == 7)
break;
temp = rk[11];
rk[12] = rk[ 4] ^
(Te4[GETBYTE(temp, 3)] & 0xff000000) ^
(Te4[GETBYTE(temp, 2)] & 0x00ff0000) ^
(Te4[GETBYTE(temp, 1)] & 0x0000ff00) ^
(Te4[GETBYTE(temp, 0)] & 0x000000ff);
rk[13] = rk[ 5] ^ rk[12];
rk[14] = rk[ 6] ^ rk[13];
rk[15] = rk[ 7] ^ rk[14];
rk += 8;
}
break;
}
if (dir == DECRYPTION)
{
unsigned int i, j;
rk = m_key;
/* invert the order of the round keys: */
for (i = 0, j = 4*m_rounds; i < j; i += 4, j -= 4) {
temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;
temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;
temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;
temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;
}
/* apply the inverse MixColumn transform to all round keys but the first and the last: */
for (i = 1; i < m_rounds; i++) {
rk += 4;
rk[0] =
Td0[Te4[GETBYTE(rk[0], 3)] & 0xff] ^
Td1[Te4[GETBYTE(rk[0], 2)] & 0xff] ^
Td2[Te4[GETBYTE(rk[0], 1)] & 0xff] ^
Td3[Te4[GETBYTE(rk[0], 0)] & 0xff];
rk[1] =
Td0[Te4[GETBYTE(rk[1], 3)] & 0xff] ^
Td1[Te4[GETBYTE(rk[1], 2)] & 0xff] ^
Td2[Te4[GETBYTE(rk[1], 1)] & 0xff] ^
Td3[Te4[GETBYTE(rk[1], 0)] & 0xff];
rk[2] =
Td0[Te4[GETBYTE(rk[2], 3)] & 0xff] ^
Td1[Te4[GETBYTE(rk[2], 2)] & 0xff] ^
Td2[Te4[GETBYTE(rk[2], 1)] & 0xff] ^
Td3[Te4[GETBYTE(rk[2], 0)] & 0xff];
rk[3] =
Td0[Te4[GETBYTE(rk[3], 3)] & 0xff] ^
Td1[Te4[GETBYTE(rk[3], 2)] & 0xff] ^
Td2[Te4[GETBYTE(rk[3], 1)] & 0xff] ^
Td3[Te4[GETBYTE(rk[3], 0)] & 0xff];
}
}
}
typedef BlockGetAndPut<word32, BigEndian> Block;
void Rijndael::Enc::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
{
word32 s0, s1, s2, s3, t0, t1, t2, t3;
const word32 *rk = m_key;
/*
* map byte array block to cipher state
* and add initial round key:
*/
Block::Get(inBlock)(s0)(s1)(s2)(s3);
s0 ^= rk[0];
s1 ^= rk[1];
s2 ^= rk[2];
s3 ^= rk[3];
/*
* Nr - 1 full rounds:
*/
unsigned int r = m_rounds >> 1;
for (;;) {
t0 =
Te0[GETBYTE(s0, 3)] ^
Te1[GETBYTE(s1, 2)] ^
Te2[GETBYTE(s2, 1)] ^
Te3[GETBYTE(s3, 0)] ^
rk[4];
t1 =
Te0[GETBYTE(s1, 3)] ^
Te1[GETBYTE(s2, 2)] ^
Te2[GETBYTE(s3, 1)] ^
Te3[GETBYTE(s0, 0)] ^
rk[5];
t2 =
Te0[GETBYTE(s2, 3)] ^
Te1[GETBYTE(s3, 2)] ^
Te2[GETBYTE(s0, 1)] ^
Te3[GETBYTE(s1, 0)] ^
rk[6];
t3 =
Te0[GETBYTE(s3, 3)] ^
Te1[GETBYTE(s0, 2)] ^
Te2[GETBYTE(s1, 1)] ^
Te3[GETBYTE(s2, 0)] ^
rk[7];
rk += 8;
if (--r == 0) {
break;
}
s0 =
Te0[GETBYTE(t0, 3)] ^
Te1[GETBYTE(t1, 2)] ^
Te2[GETBYTE(t2, 1)] ^
Te3[GETBYTE(t3, 0)] ^
rk[0];
s1 =
Te0[GETBYTE(t1, 3)] ^
Te1[GETBYTE(t2, 2)] ^
Te2[GETBYTE(t3, 1)] ^
Te3[GETBYTE(t0, 0)] ^
rk[1];
s2 =
Te0[GETBYTE(t2, 3)] ^
Te1[GETBYTE(t3, 2)] ^
Te2[GETBYTE(t0, 1)] ^
Te3[GETBYTE(t1, 0)] ^
rk[2];
s3 =
Te0[GETBYTE(t3, 3)] ^
Te1[GETBYTE(t0, 2)] ^
Te2[GETBYTE(t1, 1)] ^
Te3[GETBYTE(t2, 0)] ^
rk[3];
}
/*
* apply last round and
* map cipher state to byte array block:
*/
s0 =
(Te4[GETBYTE(t0, 3)] & 0xff000000) ^
(Te4[GETBYTE(t1, 2)] & 0x00ff0000) ^
(Te4[GETBYTE(t2, 1)] & 0x0000ff00) ^
(Te4[GETBYTE(t3, 0)] & 0x000000ff) ^
rk[0];
s1 =
(Te4[GETBYTE(t1, 3)] & 0xff000000) ^
(Te4[GETBYTE(t2, 2)] & 0x00ff0000) ^
(Te4[GETBYTE(t3, 1)] & 0x0000ff00) ^
(Te4[GETBYTE(t0, 0)] & 0x000000ff) ^
rk[1];
s2 =
(Te4[GETBYTE(t2, 3)] & 0xff000000) ^
(Te4[GETBYTE(t3, 2)] & 0x00ff0000) ^
(Te4[GETBYTE(t0, 1)] & 0x0000ff00) ^
(Te4[GETBYTE(t1, 0)] & 0x000000ff) ^
rk[2];
s3 =
(Te4[GETBYTE(t3, 3)] & 0xff000000) ^
(Te4[GETBYTE(t0, 2)] & 0x00ff0000) ^
(Te4[GETBYTE(t1, 1)] & 0x0000ff00) ^
(Te4[GETBYTE(t2, 0)] & 0x000000ff) ^
rk[3];
Block::Put(xorBlock, outBlock)(s0)(s1)(s2)(s3);
}
void Rijndael::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const
{
word32 s0, s1, s2, s3, t0, t1, t2, t3;
const word32 *rk = m_key;
/*
* map byte array block to cipher state
* and add initial round key:
*/
Block::Get(inBlock)(s0)(s1)(s2)(s3);
s0 ^= rk[0];
s1 ^= rk[1];
s2 ^= rk[2];
s3 ^= rk[3];
/*
* Nr - 1 full rounds:
*/
unsigned int r = m_rounds >> 1;
for (;;) {
t0 =
Td0[GETBYTE(s0, 3)] ^
Td1[GETBYTE(s3, 2)] ^
Td2[GETBYTE(s2, 1)] ^
Td3[GETBYTE(s1, 0)] ^
rk[4];
t1 =
Td0[GETBYTE(s1, 3)] ^
Td1[GETBYTE(s0, 2)] ^
Td2[GETBYTE(s3, 1)] ^
Td3[GETBYTE(s2, 0)] ^
rk[5];
t2 =
Td0[GETBYTE(s2, 3)] ^
Td1[GETBYTE(s1, 2)] ^
Td2[GETBYTE(s0, 1)] ^
Td3[GETBYTE(s3, 0)] ^
rk[6];
t3 =
Td0[GETBYTE(s3, 3)] ^
Td1[GETBYTE(s2, 2)] ^
Td2[GETBYTE(s1, 1)] ^
Td3[GETBYTE(s0, 0)] ^
rk[7];
rk += 8;
if (--r == 0) {
break;
}
s0 =
Td0[GETBYTE(t0, 3)] ^
Td1[GETBYTE(t3, 2)] ^
Td2[GETBYTE(t2, 1)] ^
Td3[GETBYTE(t1, 0)] ^
rk[0];
s1 =
Td0[GETBYTE(t1, 3)] ^
Td1[GETBYTE(t0, 2)] ^
Td2[GETBYTE(t3, 1)] ^
Td3[GETBYTE(t2, 0)] ^
rk[1];
s2 =
Td0[GETBYTE(t2, 3)] ^
Td1[GETBYTE(t1, 2)] ^
Td2[GETBYTE(t0, 1)] ^
Td3[GETBYTE(t3, 0)] ^
rk[2];
s3 =
Td0[GETBYTE(t3, 3)] ^
Td1[GETBYTE(t2, 2)] ^
Td2[GETBYTE(t1, 1)] ^
Td3[GETBYTE(t0, 0)] ^
rk[3];
}
/*
* apply last round and
* map cipher state to byte array block:
*/
s0 =
(Td4[GETBYTE(t0, 3)] & 0xff000000) ^
(Td4[GETBYTE(t3, 2)] & 0x00ff0000) ^
(Td4[GETBYTE(t2, 1)] & 0x0000ff00) ^
(Td4[GETBYTE(t1, 0)] & 0x000000ff) ^
rk[0];
s1 =
(Td4[GETBYTE(t1, 3)] & 0xff000000) ^
(Td4[GETBYTE(t0, 2)] & 0x00ff0000) ^
(Td4[GETBYTE(t3, 1)] & 0x0000ff00) ^
(Td4[GETBYTE(t2, 0)] & 0x000000ff) ^
rk[1];
s2 =
(Td4[GETBYTE(t2, 3)] & 0xff000000) ^
(Td4[GETBYTE(t1, 2)] & 0x00ff0000) ^
(Td4[GETBYTE(t0, 1)] & 0x0000ff00) ^
(Td4[GETBYTE(t3, 0)] & 0x000000ff) ^
rk[2];
s3 =
(Td4[GETBYTE(t3, 3)] & 0xff000000) ^
(Td4[GETBYTE(t2, 2)] & 0x00ff0000) ^
(Td4[GETBYTE(t1, 1)] & 0x0000ff00) ^
(Td4[GETBYTE(t0, 0)] & 0x000000ff) ^
rk[3];
Block::Put(xorBlock, outBlock)(s0)(s1)(s2)(s3);
}
NAMESPACE_END
#endif
| [
"[email protected]"
] | [
[
[
1,
380
]
]
] |
d4dd3af0227a95f23ba3dfcd42e49ad28ffc1aee | c3db5e9c2778ed2e37edb5483f9d86a9b6d95aca | /PSGamepad/PSGamepadRTC.cpp | 184fd28a479f85da317c9d13993f5775846df38e | [] | no_license | marciopocebon/InputDevices | e859bda8c70571fe1d91df73d17428c39240d220 | 50363fe7359f921bb0b39e87548a7dc759a07230 | refs/heads/master | 2020-06-23T15:07:44.829866 | 2010-11-04T03:17:04 | 2010-11-04T03:17:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,816 | cpp | // -*- C++ -*-
/*!
* @file PSGamepadComp.cpp
* @brief Playstation Gamepad component
* $Date$
*
* $Id$
*/
#include "PSGamepadRTC.h"
#include "VectorConvert.h"
#define AXES_AND_BUTTON_NUM 15
using namespace std;
// Module specification
static const char* psgamepadcomp_spec[] =
{
"implementation_id", "PSGamepadComp",
"type_name", "PSGamepadComp",
"description", "Playstation Gamepad component",
"version", "0.1",
"vendor", "S.Kurihara",
"category", "Generic",
"activity_type", "DataFlowComponent",
"max_instance", "10",
"language", "C++",
"lang_type", "compile",
// Configuration variables
"conf.default.ratio", "0.01,-0.01,0.01",
"conf.default.threshold", "1000",
"conf.default.max", "1000",
"conf.default.min", "-1000",
""
};
PSGamepadComp::PSGamepadComp(RTC::Manager* manager)
: RTC::DataFlowComponentBase(manager),
m_axes_and_buttonsOut("axes_and_buttons", m_axes_and_buttons),
dummy(0)
{
// Registration: InPort/OutPort/Service
// Set OutPort buffer
registerOutPort("axes_and_buttons", m_axes_and_buttonsOut);
}
PSGamepadComp::~PSGamepadComp()
{
}
RTC::ReturnCode_t PSGamepadComp::onInitialize()
{
// Bind variables and configuration variable
bindParameter("ratio", m_ratio, "0.01,-0.01,0.01");
bindParameter("threshold", m_threshold, "1000");
bindParameter("max", m_max, "1000");
bindParameter("min", m_min, "-1000");
m_axes_and_buttons.data.length(AXES_AND_BUTTON_NUM);
return RTC::RTC_OK;
}
RTC::ReturnCode_t PSGamepadComp::onActivated(RTC::UniqueId ec_id)
{
if (FAILED(m_psGamepad.InitDirectInput(m_max, m_min, m_threshold)))
{
cout << "Error: Called InitDirectInput()." << endl;
return RTC::RTC_ERROR;
}
return RTC::RTC_OK;
}
RTC::ReturnCode_t PSGamepadComp::onDeactivated(RTC::UniqueId ec_id)
{
m_psGamepad.FreeDirectInput();
return RTC::RTC_OK;
}
RTC::ReturnCode_t PSGamepadComp::onExecute(RTC::UniqueId ec_id)
{
std::vector<float> axes_and_buttons_data(AXES_AND_BUTTON_NUM, 0.0);
if (FAILED(m_psGamepad.UpdateInputState(axes_and_buttons_data, m_ratio)))
{
return RTC::RTC_ERROR;
}
for (int i = 0; i < AXES_AND_BUTTON_NUM; i++) {
m_axes_and_buttons.data[i] = axes_and_buttons_data[i];
}
m_axes_and_buttonsOut << m_axes_and_buttons;
return RTC::RTC_OK;
}
extern "C"
{
void PSGamepadCompInit(RTC::Manager* manager)
{
RTC::Properties profile(psgamepadcomp_spec);
manager->registerFactory(profile,
RTC::Create<PSGamepadComp>,
RTC::Delete<PSGamepadComp>);
}
};
| [
"kurihara@49ca9add-c54f-4622-9f17-f1590135c5e3"
] | [
[
[
1,
115
]
]
] |
174dcbf22eb4d3c7990af3d3f22bed61847fde9f | 080d0991b0b9246584851c8378acbd5111c9220e | /UsoDeVectores.cpp | d9d0651dbc5c3ad4f85fd2c6eae7c37fe6a5f836 | [] | no_license | jlstr/acm | 93c9bc3192dbfbeb5e39c18193144503452dac2a | cd3f99e66ac5eb9e16a5dccaf563ca489e08abc3 | refs/heads/master | 2021-01-16T19:33:50.867234 | 2011-09-29T19:56:16 | 2011-09-29T19:56:16 | 8,509,059 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,134 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool compara(int i, int j){
return i < j;
}
main(){
//Inicializa el vector v con 15 veces un 1
vector<int> v(15, 1);
//Copia el contenido de v a v2
vector<int> v2(v);
//Borra v2 y le asigna 10 4's
v2.assign(10, 4);
v2.clear();
for (int i=1; i<=10; i++)
v2.push_back(11-i);
//Borra desde el tercer elemento (incluido) hasta tres elementos antes del final
//Ej. de 1 2 3 4 5 6 7 8 9 10
//queda 1 2 8 9 10
v2.erase(v2.begin()+2, v2.end()-3);
//muestra el ultimo elemento
cout << *v2.begin() << " " << v2.front() << endl;
//muestra el ultimo elemento
cout << *(v2.end()-1) << " " << v2.back() << endl;
//muestra mayor cantidad de elementos que este vector puede almacenar
cout << v2.max_size() << endl;
//ordena todo el vector de menor a mayor
sort(v2.begin(), v2.end());
sort(v2.begin(), v2.end(), compara);
for (vector<int>::iterator it=v2.begin(); it<v2.end(); it++){
cout << *it << " ";
}
cout << "\n";
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
48
]
]
] |
82da86ce8260cc595ce945c2570079089713b0a3 | b104d53c6a02e70b23bc34f06c995875be41c126 | /src/plugins/PerfCounterMuninNodePlugin.cpp | 47c49839a8a69c7241061100105092ba1a34a1c2 | [] | no_license | Elbandi/munin-node-win32 | 9b7db40cc9110d0ff6cd97a13370ba4ab7ebe8eb | 4b9264ae772e6cd828d5710a4e4259e8434414c0 | refs/heads/master | 2021-01-10T21:22:58.768457 | 2011-11-09T21:11:47 | 2011-11-09T21:11:47 | 2,117,902 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 11,040 | cpp | /* This file is part of munin-node-win32
* Copyright (C) 2006-2011 Jory Stone ([email protected])
* Support for DERIVE Permon counters by [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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "StdAfx.h"
#include "PerfCounterMuninNodePlugin.h"
#include "../core/Service.h"
const char *PerfCounterMuninNodePlugin::SectionPrefix = "PerfCounterPlugin_";
PerfCounterMuninNodePlugin::PerfCounterMuninNodePlugin(const std::string §ionName)
: m_SectionName(sectionName)
{
m_PerfQuery = NULL;
m_Loaded = OpenCounter();
}
PerfCounterMuninNodePlugin::~PerfCounterMuninNodePlugin()
{
for (size_t i = 0; i < m_Counters.size(); i++) {
// Close the counters
PdhRemoveCounter(m_Counters[i]);
}
if (m_PerfQuery != NULL) {
// Close the query
PdhCloseQuery(&m_PerfQuery);
}
}
bool PerfCounterMuninNodePlugin::OpenCounter()
{
PDH_STATUS status;
m_Name = m_SectionName.substr(strlen(PerfCounterMuninNodePlugin::SectionPrefix));
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (!GetVersionEx(&osvi) || (osvi.dwPlatformId != VER_PLATFORM_WIN32_NT)) {
_Module.LogError("PerfCounter plugin: %s: unknown OS or not NT based", m_Name.c_str());
return false; //unknown OS or not NT based
}
// Create a PDH query
status = PdhOpenQuery(NULL, 0, &m_PerfQuery);
if (status != ERROR_SUCCESS) {
_Module.LogError("PerfCounter plugin: %s: PdhOpenQuery error=%x", m_Name.c_str(), status);
return false;
}
TString objectName = A2TConvert(g_Config.GetValue(m_SectionName, "Object", "LogicalDisk"));
TString counterName = A2TConvert(g_Config.GetValue(m_SectionName, "Counter", "% Disk Time"));
DWORD counterListLength = 0;
DWORD instanceListLength = 0;
status = PdhEnumObjectItems(NULL, NULL, objectName.c_str(), NULL, &counterListLength, NULL, &instanceListLength, PERF_DETAIL_EXPERT, 0);
if (status != PDH_MORE_DATA) {
_Module.LogError("PerfCounter plugin: %s: PdhEnumObjectItems error=%x", m_Name.c_str(), status);
return false;
}
TCHAR *counterList = new TCHAR[counterListLength+2];
TCHAR *instanceList = new TCHAR[instanceListLength+2];
counterList[0] = NULL;
instanceList[0] = NULL;
counterList[1] = NULL;
instanceList[1] = NULL;
status = PdhEnumObjectItems(NULL, NULL, objectName.c_str(), counterList, &counterListLength, instanceList, &instanceListLength, PERF_DETAIL_EXPERT, 0);
if (status != ERROR_SUCCESS) {
delete [] counterList;
delete [] instanceList;
_Module.LogError("PerfCounter plugin: %s: PdhEnumObjectItems error=%x", m_Name.c_str(), status);
return false;
}
int pos = 0;
TCHAR *instanceName = instanceList;
while (instanceName[0] != NULL) {
std::string counterInstanceName = T2AConvert(instanceName);
m_CounterNames.push_back(counterInstanceName);
while (instanceName[0] != NULL)
instanceName++;
instanceName++;
}
delete [] counterList;
delete [] instanceList;
TCHAR counterPath[MAX_PATH] = {0};
HCOUNTER counterHandle;
if (!m_CounterNames.empty()) {
if (g_Config.GetValueB(m_SectionName, "DropTotal", true)) {
assert(m_CounterNames.back().compare("_Total") == 0);
// We drop the last instance name as it is _Total
m_CounterNames.pop_back();
}
for (size_t i = 0; i < m_CounterNames.size(); i++) {
TString instanceNameStr = A2TConvert(m_CounterNames[i]);
_sntprintf(counterPath, MAX_PATH, _T("\\%s(%s)\\%s"), objectName.c_str(), instanceNameStr.c_str(), counterName.c_str());
// Associate the uptime counter with the query
status = PdhAddCounter(m_PerfQuery, counterPath, 0, &counterHandle);
if (status != ERROR_SUCCESS) {
_Module.LogError("PerfCounter plugin: %s: PDH add counter error=%x", m_Name.c_str(), status);
return false;
}
m_Counters.push_back(counterHandle);
}
} else {
// A counter with a single instance (Uptime for example)
m_CounterNames.push_back("0");
_sntprintf(counterPath, MAX_PATH, _T("\\%s\\%s"), objectName.c_str(), counterName.c_str());
// Associate the uptime counter with the query
status = PdhAddCounter(m_PerfQuery, counterPath, 0, &counterHandle);
if (status != ERROR_SUCCESS) {
_Module.LogError("PerfCounter plugin: %s: PDH add counter error=%x", m_Name.c_str(), status);
return false;
}
m_Counters.push_back(counterHandle);
}
// Collect init data
status = PdhCollectQueryData(m_PerfQuery);
if (status != ERROR_SUCCESS) {
if (status == PDH_INVALID_HANDLE) {
_Module.LogError("PerfCounter plugin: %s: PDH collect data: PDH_INVALID_HANDLE", m_Name.c_str());
return false;
}
if (status == PDH_NO_DATA) {
_Module.LogError("PerfCounter plugin: %s: PDH collect data: PDH_NO_DATA", m_Name.c_str());
return false;
}
_Module.LogError("PerfCounter plugin: %s: PDH collect data error", m_Name.c_str());
return false;
}
// Setup Counter Format
m_dwCounterFormat = PDH_FMT_DOUBLE;
std::string counterFormatStr = g_Config.GetValue(m_SectionName, "CounterFormat", "double");
if (!counterFormatStr.compare("double")
|| !counterFormatStr.compare("float")) {
m_dwCounterFormat = PDH_FMT_DOUBLE;
} else if (!counterFormatStr.compare("int")
|| !counterFormatStr.compare("long")) {
m_dwCounterFormat = PDH_FMT_LONG;
} else if (!counterFormatStr.compare("int64")
|| !counterFormatStr.compare("longlong")
|| !counterFormatStr.compare("large")) {
m_dwCounterFormat = PDH_FMT_LARGE;
} else {
_Module.LogError("PerfCounter plugin: %s: Unknown CounterFormat", m_Name.c_str());
assert(!"Unknown CounterFormat!");
}
m_CounterMultiply = g_Config.GetValueF(m_SectionName, "CounterMultiply", 1.0);
return true;
}
int PerfCounterMuninNodePlugin::GetConfig(char *buffer, int len)
{
if (!m_Counters.empty()) {
PDH_STATUS status;
DWORD infoSize = 0;
status = PdhGetCounterInfo(m_Counters[0], TRUE, &infoSize, NULL);
if (status != PDH_MORE_DATA)
return -1;
PDH_COUNTER_INFO *info = (PDH_COUNTER_INFO *)malloc(infoSize);
status = PdhGetCounterInfo(m_Counters[0], TRUE, &infoSize, info);
if (status != ERROR_SUCCESS)
return -1;
int printCount;
std::string graphTitle = g_Config.GetValue(m_SectionName, "GraphTitle", "Disk Time");
std::string graphCategory = g_Config.GetValue(m_SectionName, "GraphCategory", "system");
std::string graphArgs = g_Config.GetValue(m_SectionName, "GraphArgs", "--base 1000 -l 0");
std::string explainText = W2AConvert(info->szExplainText);
std::string counterName = W2AConvert(info->szCounterName);
printCount = _snprintf(buffer, len, "graph_title %s\n"
"graph_category %s\n"
"graph_args %s\n"
"graph_info %s\n"
"graph_vlabel %s\n",
graphTitle.c_str(), graphCategory.c_str(),
graphArgs.c_str(),
explainText.c_str(), counterName.c_str());
len -= printCount;
buffer += printCount;
free(info);
std::string graphDraw = g_Config.GetValue(m_SectionName, "GraphDraw", "LINE");
std::string counterType = g_Config.GetValue(m_SectionName, "CounterType", "GAUGE");
std::string minValue;
std::string minValueNumbered;
if(counterType == "DERIVE") {
minValue = "%s.min 0\n";
minValueNumbered = "%s_%i_.min 0\n";
} else {
minValue = minValueNumbered = "";
}
assert(m_CounterNames.size() == m_Counters.size());
std::string labels;
// We handle multiple counters
for (size_t i = 0; i < m_CounterNames.size(); i++) {
if (i == 0) {
labels = "%s.label %s\n"
"%s.draw %s\n"
"%s.type %s\n";
labels += minValue;
// First counter gets a normal name
printCount = _snprintf(buffer, len,
labels.c_str(),
m_Name.c_str(), m_CounterNames[i].c_str(),
m_Name.c_str(), graphDraw.c_str(),
m_Name.c_str(), counterType.c_str(),
m_Name.c_str());
} else {
// Rest of the counters are numbered
labels = "%s_%i_.label %s\n"
"%s_%i_.draw %s\n"
"%s_%i_.type %s\n";
labels += minValueNumbered;
printCount = _snprintf(buffer, len,
labels.c_str(),
m_Name.c_str(), i, m_CounterNames[i].c_str(),
m_Name.c_str(), i, graphDraw.c_str(),
m_Name.c_str(), i, counterType.c_str(),
m_Name.c_str(), i);
}
len -= printCount;
buffer += printCount;
}
}
strncat(buffer, ".\n", len);
return 0;
}
int printvalue(char* buffer, size_t len, const char* name, size_t i, double value, DWORD counterformat) {
if(counterformat == PDH_FMT_LONG)
if(0==i)
return _snprintf(buffer, len, "%s.value %i\n", name, (int)value);
else
return _snprintf(buffer, len, "%s_%i_.value %i\n", name, i, (int)value);
else
if(0==i)
return _snprintf(buffer, len, "%s.value %.2f\n", name, value);
else
return _snprintf(buffer, len, "%s_%i_.value %.2f\n", name, i, value);
}
int PerfCounterMuninNodePlugin::GetValues(char *buffer, int len)
{
PDH_STATUS status;
PDH_FMT_COUNTERVALUE counterValue;
int printCount;
status = PdhCollectQueryData(m_PerfQuery);
if (status != ERROR_SUCCESS)
return -1;
for (size_t i = 0; i < m_Counters.size(); i++) {
// Get the formatted counter value
status = PdhGetFormattedCounterValue(m_Counters[i], m_dwCounterFormat, NULL, &counterValue);
if (status != ERROR_SUCCESS)
return -1;
double value = 0;
switch (m_dwCounterFormat) {
case PDH_FMT_DOUBLE:
value = counterValue.doubleValue * m_CounterMultiply;
break;
case PDH_FMT_LONG:
value = counterValue.longValue * m_CounterMultiply;
break;
case PDH_FMT_LARGE:
value = counterValue.largeValue * m_CounterMultiply;
break;
}
printCount = printvalue(buffer, len, m_Name.c_str(), i, value, m_dwCounterFormat);
len -= printCount;
buffer += printCount;
}
strncat(buffer, ".\n", len);
return 0;
}
| [
"agroszer@04e79fd8-011e-11df-a6f0-ed93ac2c91d0",
"[email protected]@04e79fd8-011e-11df-a6f0-ed93ac2c91d0"
] | [
[
[
1,
1
],
[
4,
63
],
[
65,
74
],
[
76,
89
],
[
91,
120
],
[
122,
133
],
[
135,
199
],
[
202,
208
],
[
210,
215
],
[
227,
228
],
[
232,
233
],
[
241,
241
],
[
244,
244
],
[
248,
249
],
[
258,
258
],
[
262,
271
],
[
285,
311
],
[
313,
318
]
],
[
[
2,
3
],
[
64,
64
],
[
75,
75
],
[
90,
90
],
[
121,
121
],
[
134,
134
],
[
200,
201
],
[
209,
209
],
[
216,
226
],
[
229,
231
],
[
234,
240
],
[
242,
243
],
[
245,
247
],
[
250,
257
],
[
259,
261
],
[
272,
284
],
[
312,
312
]
]
] |
63fbcbb02991aeaa464ecc844d3bb6fad8bd01b6 | 1749b790322956a6dc63cb2897769bef200e5940 | /geopochiv1/GEopochi/lib/src/CI/create_image.cpp | c4677a65f92633418e47d88b056be8ada0c7d412 | [
"MIT"
] | permissive | gvellut/geopochi | fabcbfcb90e019877a0ad1e23b3e586c88e78a2a | f0378dc2009e522678cede3969136f62884de994 | refs/heads/master | 2016-09-06T12:21:02.875833 | 2009-05-02T19:58:10 | 2009-05-02T19:58:10 | 191,076 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,070 | cpp | #include "gdal_priv.h"
#include "gdalwarper.h"
#include "ogr_spatialref.h"
#include "ruby.h"
typedef VALUE (ruby_method)(...);
static VALUE mCreateImage;
//Arguments :
//The path to the resulting image,
//the number of tiles in i,
//the number of tiles in j,
//an array with the fs location of the gp tiles taking part in the mosaic (ordered; should be i*j tiles),
//an array with the affine parameters to go from pixel (of the mosaic to be created) to world (in a non wgs84 lat/lon proj)
//the Proj4 string of the projection of the local coordinate
//an array with the the affine parameters to go from pixel to WGS84 lat/lon coordinate in the result image
//the size of the gp tiles,
//the size of the WGS84 tiles
static VALUE ci_create(VALUE self,
VALUE path,VALUE format,
VALUE num_i, VALUE num_j,
VALUE gp_tiles,
VALUE corresp, VALUE proj,
VALUE output_corresp, VALUE output_proj,
VALUE tile_size, VALUE width, VALUE height){
GDALDataset* hGeopDstDS = NULL; //Will contain the mosaic of gp tiles
GDALDataset* hGeopSrcDS = NULL; //Will temporarily contain all the original gp tiles
GDALDataset* hGEDstDS = NULL; //Will contain the raster to send back to ge in tiff
GDALDataset* hGEDstDS_output = NULL; //Will contain the raster to send back to ge in JPEG format
int numI,numJ;
char * tile_path;
int tileSize,outputWidth,outputHeight;
char * projection;
char *outputProjection;
GDALDriver *tiffDriver;
GDALDriver *outputDriver;
VALUE *ptr;
CPLErr err;
tiffDriver = GetGDALDriverManager()->GetDriverByName("GTiff");
char* outputFormat = STR2CSTR(format);
if(!strcmp(outputFormat,"image/jpeg"))
outputDriver = GetGDALDriverManager()->GetDriverByName("JPEG");
else if(!strcmp(outputFormat,"image/png"))
outputDriver = GetGDALDriverManager()->GetDriverByName("PNG");
else
return Qfalse;
numI = FIX2INT(num_i);
numJ = FIX2INT(num_j);
tile_path = STR2CSTR(path);
projection = STR2CSTR(proj);
outputProjection = STR2CSTR(output_proj);
tileSize = FIX2INT(tile_size);
outputWidth = FIX2INT(width);
outputHeight = FIX2INT(height);
char * tmpFilePathA = (char*) CPLMalloc((RSTRING(path)->len + 7) * sizeof(char));
sprintf(tmpFilePathA,"%s.a.tif",tile_path);
int numbands;
int size = RARRAY(gp_tiles)->len;
ptr = RARRAY(gp_tiles)->ptr;
GByte *dataBuffer = (GByte*) CPLMalloc(sizeof(GByte)* tileSize * tileSize * 3);
for(int i = 0 ; i < size ; i++,ptr++){
//copy to the dst file the tiles whose path are in the array
int row,col;
row = i % numJ;
col = (int) i / numJ;
hGeopSrcDS = (GDALDataset *) GDALOpen(STR2CSTR(*ptr), GA_ReadOnly );
if(hGeopSrcDS == NULL)
return Qfalse;
//The xSize and ySize are smaller than tileSize. So the tile can get into the buffer
int xSize = hGeopSrcDS->GetRasterXSize();
int ySize = hGeopSrcDS->GetRasterYSize();
numbands = hGeopSrcDS->GetRasterCount();
if(numbands > 3)
numbands = 3;
if(hGeopDstDS == NULL){
//Create the temp image, which is a mosaic of all the local tiles,
//downloaded from the geoportail
hGeopDstDS = tiffDriver->Create(tmpFilePathA,numI*tileSize,numJ*tileSize,numbands,GDT_Byte,0);
if(hGeopDstDS == NULL)
return Qfalse;
}
err = hGeopSrcDS->RasterIO(GF_Read,0,0,xSize,ySize,
dataBuffer,xSize,ySize,
GDT_Byte,numbands,0,0,0,0);
if(err == CE_Failure)
return Qfalse;
err = hGeopDstDS->RasterIO(GF_Write,col * tileSize,row * tileSize,
xSize,ySize,dataBuffer,xSize,ySize,
GDT_Byte,numbands,0,0,0,0);
if(err == CE_Failure)
return Qfalse;
GDALClose(hGeopSrcDS);
}
CPLFree(dataBuffer);
//Add an affine transform
ptr = RARRAY(corresp)->ptr;
double afTransform[6];
afTransform[0] = NUM2DBL(ptr[0]);
afTransform[1] = NUM2DBL(ptr[1]);
afTransform[2] = NUM2DBL(ptr[2]);
afTransform[3] = NUM2DBL(ptr[3]);
afTransform[4] = NUM2DBL(ptr[4]);
afTransform[5] = NUM2DBL(ptr[5]);
OGRSpatialReference oSRS;
oSRS.importFromProj4(projection);
char *localProjWKT = NULL;
oSRS.exportToWkt(&localProjWKT);
hGeopDstDS->SetProjection(localProjWKT);
hGeopDstDS->SetGeoTransform(afTransform);
//open the dest file and warp the mosaic into it
char * tmpFilePathB = (char*) CPLMalloc((RSTRING(path)->len + 7) * sizeof(char));
sprintf(tmpFilePathB,"%s.b.tif",tile_path);
hGEDstDS = tiffDriver->Create(tmpFilePathB,outputWidth,outputHeight,numbands,GDT_Byte,0);
if(hGEDstDS == NULL)
return Qfalse;
//Add the affine geotransform
ptr = RARRAY(output_corresp)->ptr;
afTransform[0] = NUM2DBL(ptr[0]);
afTransform[1] = NUM2DBL(ptr[1]);
afTransform[2] = NUM2DBL(ptr[2]);
afTransform[3] = NUM2DBL(ptr[3]);
afTransform[4] = NUM2DBL(ptr[4]);
afTransform[5] = NUM2DBL(ptr[5]);
OGRSpatialReference oSRSOutput;
oSRSOutput.importFromProj4(outputProjection);
char * outputProjWKT = NULL;
oSRSOutput.exportToWkt(&outputProjWKT);
hGEDstDS->SetProjection(outputProjWKT);
hGEDstDS->SetGeoTransform(afTransform);
//Do the warping
GDALWarpOptions *psWarpOptions = GDALCreateWarpOptions();
psWarpOptions->hSrcDS = hGeopDstDS;
psWarpOptions->hDstDS = hGEDstDS;
psWarpOptions->nBandCount = 0;
// Establish reprojection transformer.
psWarpOptions->pTransformerArg =
GDALCreateGenImgProjTransformer( hGeopDstDS,
GDALGetProjectionRef(hGeopDstDS),
hGEDstDS,
GDALGetProjectionRef(hGEDstDS),
FALSE, 0.0, 1 );
psWarpOptions->pfnTransformer = GDALGenImgProjTransform;
// Initialize and execute the warp operation.
GDALWarpOperation oOperation;
oOperation.Initialize( psWarpOptions );
oOperation.ChunkAndWarpImage( 0, 0,
hGEDstDS->GetRasterXSize() ,
hGEDstDS->GetRasterYSize() );
GDALDestroyGenImgProjTransformer( psWarpOptions->pTransformerArg );
GDALDestroyWarpOptions( psWarpOptions );
//Clean up the mosaic'ed file
GDALClose( hGeopDstDS );
//export the temp tiff file into the jpeg file
hGEDstDS_output = outputDriver->CreateCopy(tile_path,hGEDstDS,TRUE,0,0,0);
if(hGEDstDS_output == NULL){
return Qfalse;
}
//Clean up the still open datasets
GDALClose(hGEDstDS);
GDALClose(hGEDstDS_output);
//Clean up the temp tiff files
VSIUnlink(tmpFilePathA);
CPLFree(tmpFilePathA);
VSIUnlink(tmpFilePathB);
CPLFree(tmpFilePathB);
//Clean up the WKT strings
CPLFree(localProjWKT);
CPLFree(outputProjWKT);
return Qtrue;
}
void Init_CI(void) {
mCreateImage = rb_define_module("CreateImage");
rb_define_module_function(mCreateImage,"create",(ruby_method*) &ci_create,12);
GDALAllRegister(); //Register the GDAL drivers
}
| [
"Guilhem.Vellut@519bc41f-613d-0410-a9d2-e7e10bd5ccdb"
] | [
[
[
1,
224
]
]
] |
f4b6d4b18cff378616fb6e3a6d8b742d004dc873 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/qt/Api/qwebpage.cpp | 93872b7519eeb03ab47014cafba1f9625537785c | [
"BSD-2-Clause"
] | permissive | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 143,958 | cpp | /*
Copyright (C) 2008, 2009 Nokia Corporation and/or its subsidiary(-ies)
Copyright (C) 2007 Staikos Computing Services Inc.
Copyright (C) 2007 Apple Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "qwebpage.h"
#include "qwebview.h"
#include "qwebframe.h"
#include "qwebpage_p.h"
#include "qwebframe_p.h"
#include "qwebhistory.h"
#include "qwebhistory_p.h"
#include "qwebinspector.h"
#include "qwebinspector_p.h"
#include "qwebsettings.h"
#include "qwebkitversion.h"
#include "Chrome.h"
#include "ContextMenuController.h"
#include "Frame.h"
#include "FrameTree.h"
#include "FrameLoader.h"
#include "FrameLoaderClientQt.h"
#include "FrameView.h"
#include "FormState.h"
#include "ApplicationCacheStorage.h"
#include "ChromeClientQt.h"
#include "ContextMenu.h"
#include "ContextMenuClientQt.h"
#include "DocumentLoader.h"
#include "DragClientQt.h"
#include "DragController.h"
#include "DragData.h"
#include "EditorClientQt.h"
#include "SchemeRegistry.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "Page.h"
#include "Pasteboard.h"
#include "FrameLoader.h"
#include "FrameLoadRequest.h"
#include "KURL.h"
#include "Logging.h"
#include "Image.h"
#include "InspectorClientQt.h"
#include "InspectorController.h"
#include "FocusController.h"
#include "Editor.h"
#include "Scrollbar.h"
#include "PlatformKeyboardEvent.h"
#include "PlatformWheelEvent.h"
#include "PluginDatabase.h"
#include "ProgressTracker.h"
#include "RefPtr.h"
#include "RenderTextControl.h"
#include "TextIterator.h"
#include "HashMap.h"
#include "HTMLFormElement.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HitTestResult.h"
#include "WindowFeatures.h"
#include "LocalizedStrings.h"
#include "Cache.h"
#include "runtime/InitializeThreading.h"
#include "PageGroup.h"
#include "GeolocationPermissionClientQt.h"
#include "NotificationPresenterClientQt.h"
#include "PageClientQt.h"
#include "WorkerThread.h"
#include "wtf/Threading.h"
#include <QApplication>
#include <QBasicTimer>
#include <QBitArray>
#include <QDebug>
#include <QDragEnterEvent>
#include <QDragLeaveEvent>
#include <QDragMoveEvent>
#include <QDropEvent>
#include <QFileDialog>
#include <QHttpRequestHeader>
#include <QInputDialog>
#include <QLocale>
#include <QMessageBox>
#include <QNetworkProxy>
#include <QUndoStack>
#include <QUrl>
#include <QPainter>
#include <QClipboard>
#include <QSslSocket>
#include <QStyle>
#include <QSysInfo>
#include <QTextCharFormat>
#include <QTextDocument>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#if defined(Q_WS_X11)
#include <QX11Info>
#endif
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
#include <QTouchEvent>
#include "PlatformTouchEvent.h"
#endif
using namespace WebCore;
bool QWebPagePrivate::drtRun = false;
// Lookup table mapping QWebPage::WebActions to the associated Editor commands
static const char* editorCommandWebActions[] =
{
0, // OpenLink,
0, // OpenLinkInNewWindow,
0, // OpenFrameInNewWindow,
0, // DownloadLinkToDisk,
0, // CopyLinkToClipboard,
0, // OpenImageInNewWindow,
0, // DownloadImageToDisk,
0, // CopyImageToClipboard,
0, // Back,
0, // Forward,
0, // Stop,
0, // Reload,
"Cut", // Cut,
"Copy", // Copy,
"Paste", // Paste,
"Undo", // Undo,
"Redo", // Redo,
"MoveForward", // MoveToNextChar,
"MoveBackward", // MoveToPreviousChar,
"MoveWordForward", // MoveToNextWord,
"MoveWordBackward", // MoveToPreviousWord,
"MoveDown", // MoveToNextLine,
"MoveUp", // MoveToPreviousLine,
"MoveToBeginningOfLine", // MoveToStartOfLine,
"MoveToEndOfLine", // MoveToEndOfLine,
"MoveToBeginningOfParagraph", // MoveToStartOfBlock,
"MoveToEndOfParagraph", // MoveToEndOfBlock,
"MoveToBeginningOfDocument", // MoveToStartOfDocument,
"MoveToEndOfDocument", // MoveToEndOfDocument,
"MoveForwardAndModifySelection", // SelectNextChar,
"MoveBackwardAndModifySelection", // SelectPreviousChar,
"MoveWordForwardAndModifySelection", // SelectNextWord,
"MoveWordBackwardAndModifySelection", // SelectPreviousWord,
"MoveDownAndModifySelection", // SelectNextLine,
"MoveUpAndModifySelection", // SelectPreviousLine,
"MoveToBeginningOfLineAndModifySelection", // SelectStartOfLine,
"MoveToEndOfLineAndModifySelection", // SelectEndOfLine,
"MoveToBeginningOfParagraphAndModifySelection", // SelectStartOfBlock,
"MoveToEndOfParagraphAndModifySelection", // SelectEndOfBlock,
"MoveToBeginningOfDocumentAndModifySelection", //SelectStartOfDocument,
"MoveToEndOfDocumentAndModifySelection", // SelectEndOfDocument,
"DeleteWordBackward", // DeleteStartOfWord,
"DeleteWordForward", // DeleteEndOfWord,
0, // SetTextDirectionDefault,
0, // SetTextDirectionLeftToRight,
0, // SetTextDirectionRightToLeft,
"ToggleBold", // ToggleBold,
"ToggleItalic", // ToggleItalic,
"ToggleUnderline", // ToggleUnderline,
0, // InspectElement,
"InsertNewline", // InsertParagraphSeparator
"InsertLineBreak", // InsertLineSeparator
"SelectAll", // SelectAll
0, // ReloadAndBypassCache,
"PasteAndMatchStyle", // PasteAndMatchStyle
"RemoveFormat", // RemoveFormat
"Strikethrough", // ToggleStrikethrough,
"Subscript", // ToggleSubscript
"Superscript", // ToggleSuperscript
"InsertUnorderedList", // InsertUnorderedList
"InsertOrderedList", // InsertOrderedList
"Indent", // Indent
"Outdent", // Outdent,
"AlignCenter", // AlignCenter,
"AlignJustified", // AlignJustified,
"AlignLeft", // AlignLeft,
"AlignRight", // AlignRight,
0 // WebActionCount
};
// Lookup the appropriate editor command to use for WebAction \a action
const char* QWebPagePrivate::editorCommandForWebActions(QWebPage::WebAction action)
{
if ((action > QWebPage::NoWebAction) && (action < int(sizeof(editorCommandWebActions) / sizeof(const char*))))
return editorCommandWebActions[action];
return 0;
}
static inline DragOperation dropActionToDragOp(Qt::DropActions actions)
{
unsigned result = 0;
if (actions & Qt::CopyAction)
result |= DragOperationCopy;
// DragOperationgeneric represents InternetExplorer's equivalent of Move operation,
// hence it should be considered as "move"
if (actions & Qt::MoveAction)
result |= (DragOperationMove | DragOperationGeneric);
if (actions & Qt::LinkAction)
result |= DragOperationLink;
return (DragOperation)result;
}
static inline Qt::DropAction dragOpToDropAction(unsigned actions)
{
Qt::DropAction result = Qt::IgnoreAction;
if (actions & DragOperationCopy)
result = Qt::CopyAction;
else if (actions & DragOperationMove)
result = Qt::MoveAction;
// DragOperationgeneric represents InternetExplorer's equivalent of Move operation,
// hence it should be considered as "move"
else if (actions & DragOperationGeneric)
result = Qt::MoveAction;
else if (actions & DragOperationLink)
result = Qt::LinkAction;
return result;
}
QWebPagePrivate::QWebPagePrivate(QWebPage *qq)
: q(qq)
, client(0)
#if QT_VERSION < QT_VERSION_CHECK(4, 6, 0)
, view(0)
#endif
, clickCausedFocus(false)
, viewportSize(QSize(0, 0))
, inspectorFrontend(0)
, inspector(0)
, inspectorIsInternalOnly(false)
{
WebCore::InitializeLoggingChannelsIfNecessary();
ScriptController::initializeThreading();
WTF::initializeMainThread();
WebCore::SecurityOrigin::setLocalLoadPolicy(WebCore::SecurityOrigin::AllowLocalLoadsForLocalAndSubstituteData);
#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
WebCore::Font::setCodePath(WebCore::Font::Complex);
#endif
Page::PageClients pageClients;
pageClients.chromeClient = new ChromeClientQt(q);
pageClients.contextMenuClient = new ContextMenuClientQt();
pageClients.editorClient = new EditorClientQt(q);
pageClients.dragClient = new DragClientQt(q);
pageClients.inspectorClient = new InspectorClientQt(q);
page = new Page(pageClients);
settings = new QWebSettings(page->settings());
#ifndef QT_NO_UNDOSTACK
undoStack = 0;
#endif
mainFrame = 0;
networkManager = 0;
pluginFactory = 0;
insideOpenCall = false;
forwardUnsupportedContent = false;
editable = false;
useFixedLayout = false;
linkPolicy = QWebPage::DontDelegateLinks;
#ifndef QT_NO_CONTEXTMENU
currentContextMenu = 0;
#endif
smartInsertDeleteEnabled = true;
selectTrailingWhitespaceEnabled = false;
history.d = new QWebHistoryPrivate(page->backForwardList());
memset(actions, 0, sizeof(actions));
PageGroup::setShouldTrackVisitedLinks(true);
#if ENABLE(NOTIFICATIONS)
NotificationPresenterClientQt::notificationPresenter()->addClient();
#endif
}
QWebPagePrivate::~QWebPagePrivate()
{
#ifndef QT_NO_CONTEXTMENU
delete currentContextMenu;
#endif
#ifndef QT_NO_UNDOSTACK
delete undoStack;
#endif
delete settings;
delete page;
#if ENABLE(NOTIFICATIONS)
NotificationPresenterClientQt::notificationPresenter()->removeClient();
#endif
}
WebCore::Page* QWebPagePrivate::core(const QWebPage* page)
{
return page->d->page;
}
QWebPagePrivate* QWebPagePrivate::priv(QWebPage* page)
{
return page->d;
}
bool QWebPagePrivate::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, QWebPage::NavigationType type)
{
if (insideOpenCall
&& frame == mainFrame)
return true;
return q->acceptNavigationRequest(frame, request, type);
}
void QWebPagePrivate::createMainFrame()
{
if (!mainFrame) {
QWebFrameData frameData(page);
mainFrame = new QWebFrame(q, &frameData);
emit q->frameCreated(mainFrame);
}
}
static QWebPage::WebAction webActionForContextMenuAction(WebCore::ContextMenuAction action)
{
switch (action) {
case WebCore::ContextMenuItemTagOpenLink: return QWebPage::OpenLink;
case WebCore::ContextMenuItemTagOpenLinkInNewWindow: return QWebPage::OpenLinkInNewWindow;
case WebCore::ContextMenuItemTagDownloadLinkToDisk: return QWebPage::DownloadLinkToDisk;
case WebCore::ContextMenuItemTagCopyLinkToClipboard: return QWebPage::CopyLinkToClipboard;
case WebCore::ContextMenuItemTagOpenImageInNewWindow: return QWebPage::OpenImageInNewWindow;
case WebCore::ContextMenuItemTagDownloadImageToDisk: return QWebPage::DownloadImageToDisk;
case WebCore::ContextMenuItemTagCopyImageToClipboard: return QWebPage::CopyImageToClipboard;
case WebCore::ContextMenuItemTagOpenFrameInNewWindow: return QWebPage::OpenFrameInNewWindow;
case WebCore::ContextMenuItemTagCopy: return QWebPage::Copy;
case WebCore::ContextMenuItemTagGoBack: return QWebPage::Back;
case WebCore::ContextMenuItemTagGoForward: return QWebPage::Forward;
case WebCore::ContextMenuItemTagStop: return QWebPage::Stop;
case WebCore::ContextMenuItemTagReload: return QWebPage::Reload;
case WebCore::ContextMenuItemTagCut: return QWebPage::Cut;
case WebCore::ContextMenuItemTagPaste: return QWebPage::Paste;
case WebCore::ContextMenuItemTagDefaultDirection: return QWebPage::SetTextDirectionDefault;
case WebCore::ContextMenuItemTagLeftToRight: return QWebPage::SetTextDirectionLeftToRight;
case WebCore::ContextMenuItemTagRightToLeft: return QWebPage::SetTextDirectionRightToLeft;
case WebCore::ContextMenuItemTagBold: return QWebPage::ToggleBold;
case WebCore::ContextMenuItemTagItalic: return QWebPage::ToggleItalic;
case WebCore::ContextMenuItemTagUnderline: return QWebPage::ToggleUnderline;
#if ENABLE(INSPECTOR)
case WebCore::ContextMenuItemTagInspectElement: return QWebPage::InspectElement;
#endif
default: break;
}
return QWebPage::NoWebAction;
}
#ifndef QT_NO_CONTEXTMENU
QMenu *QWebPagePrivate::createContextMenu(const WebCore::ContextMenu *webcoreMenu,
const QList<WebCore::ContextMenuItem> *items, QBitArray *visitedWebActions)
{
if (!client)
return 0;
QMenu* menu = new QMenu(client->ownerWidget());
for (int i = 0; i < items->count(); ++i) {
const ContextMenuItem &item = items->at(i);
switch (item.type()) {
case WebCore::CheckableActionType: /* fall through */
case WebCore::ActionType: {
QWebPage::WebAction action = webActionForContextMenuAction(item.action());
QAction *a = q->action(action);
if (a) {
ContextMenuItem it(item);
webcoreMenu->checkOrEnableIfNeeded(it);
PlatformMenuItemDescription desc = it.releasePlatformDescription();
a->setEnabled(desc.enabled);
a->setChecked(desc.checked);
a->setCheckable(item.type() == WebCore::CheckableActionType);
menu->addAction(a);
visitedWebActions->setBit(action);
}
break;
}
case WebCore::SeparatorType:
menu->addSeparator();
break;
case WebCore::SubmenuType: {
QMenu *subMenu = createContextMenu(webcoreMenu, item.platformSubMenu(), visitedWebActions);
bool anyEnabledAction = false;
QList<QAction *> actions = subMenu->actions();
for (int i = 0; i < actions.count(); ++i) {
if (actions.at(i)->isVisible())
anyEnabledAction |= actions.at(i)->isEnabled();
}
// don't show sub-menus with just disabled actions
if (anyEnabledAction) {
subMenu->setTitle(item.title());
menu->addAction(subMenu->menuAction());
} else
delete subMenu;
break;
}
}
}
return menu;
}
#endif // QT_NO_CONTEXTMENU
#ifndef QT_NO_ACTION
void QWebPagePrivate::_q_webActionTriggered(bool checked)
{
QAction *a = qobject_cast<QAction *>(q->sender());
if (!a)
return;
QWebPage::WebAction action = static_cast<QWebPage::WebAction>(a->data().toInt());
q->triggerAction(action, checked);
}
#endif // QT_NO_ACTION
void QWebPagePrivate::_q_cleanupLeakMessages()
{
#ifndef NDEBUG
// Need this to make leak messages accurate.
cache()->setCapacities(0, 0, 0);
#endif
}
void QWebPagePrivate::updateAction(QWebPage::WebAction action)
{
#ifdef QT_NO_ACTION
Q_UNUSED(action)
#else
QAction *a = actions[action];
if (!a || !mainFrame)
return;
WebCore::FrameLoader *loader = mainFrame->d->frame->loader();
WebCore::Editor *editor = page->focusController()->focusedOrMainFrame()->editor();
bool enabled = a->isEnabled();
bool checked = a->isChecked();
switch (action) {
case QWebPage::Back:
enabled = page->canGoBackOrForward(-1);
break;
case QWebPage::Forward:
enabled = page->canGoBackOrForward(1);
break;
case QWebPage::Stop:
enabled = loader->isLoading();
break;
case QWebPage::Reload:
case QWebPage::ReloadAndBypassCache:
enabled = !loader->isLoading();
break;
#ifndef QT_NO_UNDOSTACK
case QWebPage::Undo:
case QWebPage::Redo:
// those two are handled by QUndoStack
break;
#endif // QT_NO_UNDOSTACK
case QWebPage::SelectAll: // editor command is always enabled
break;
case QWebPage::SetTextDirectionDefault:
case QWebPage::SetTextDirectionLeftToRight:
case QWebPage::SetTextDirectionRightToLeft:
enabled = editor->canEdit();
checked = false;
break;
default: {
// see if it's an editor command
const char* commandName = editorCommandForWebActions(action);
// if it's an editor command, let it's logic determine state
if (commandName) {
Editor::Command command = editor->command(commandName);
enabled = command.isEnabled();
if (enabled)
checked = command.state() != FalseTriState;
else
checked = false;
}
break;
}
}
a->setEnabled(enabled);
if (a->isCheckable())
a->setChecked(checked);
#endif // QT_NO_ACTION
}
void QWebPagePrivate::updateNavigationActions()
{
updateAction(QWebPage::Back);
updateAction(QWebPage::Forward);
updateAction(QWebPage::Stop);
updateAction(QWebPage::Reload);
updateAction(QWebPage::ReloadAndBypassCache);
}
void QWebPagePrivate::updateEditorActions()
{
updateAction(QWebPage::Cut);
updateAction(QWebPage::Copy);
updateAction(QWebPage::Paste);
updateAction(QWebPage::MoveToNextChar);
updateAction(QWebPage::MoveToPreviousChar);
updateAction(QWebPage::MoveToNextWord);
updateAction(QWebPage::MoveToPreviousWord);
updateAction(QWebPage::MoveToNextLine);
updateAction(QWebPage::MoveToPreviousLine);
updateAction(QWebPage::MoveToStartOfLine);
updateAction(QWebPage::MoveToEndOfLine);
updateAction(QWebPage::MoveToStartOfBlock);
updateAction(QWebPage::MoveToEndOfBlock);
updateAction(QWebPage::MoveToStartOfDocument);
updateAction(QWebPage::MoveToEndOfDocument);
updateAction(QWebPage::SelectNextChar);
updateAction(QWebPage::SelectPreviousChar);
updateAction(QWebPage::SelectNextWord);
updateAction(QWebPage::SelectPreviousWord);
updateAction(QWebPage::SelectNextLine);
updateAction(QWebPage::SelectPreviousLine);
updateAction(QWebPage::SelectStartOfLine);
updateAction(QWebPage::SelectEndOfLine);
updateAction(QWebPage::SelectStartOfBlock);
updateAction(QWebPage::SelectEndOfBlock);
updateAction(QWebPage::SelectStartOfDocument);
updateAction(QWebPage::SelectEndOfDocument);
updateAction(QWebPage::DeleteStartOfWord);
updateAction(QWebPage::DeleteEndOfWord);
updateAction(QWebPage::SetTextDirectionDefault);
updateAction(QWebPage::SetTextDirectionLeftToRight);
updateAction(QWebPage::SetTextDirectionRightToLeft);
updateAction(QWebPage::ToggleBold);
updateAction(QWebPage::ToggleItalic);
updateAction(QWebPage::ToggleUnderline);
updateAction(QWebPage::InsertParagraphSeparator);
updateAction(QWebPage::InsertLineSeparator);
updateAction(QWebPage::PasteAndMatchStyle);
updateAction(QWebPage::RemoveFormat);
updateAction(QWebPage::ToggleStrikethrough);
updateAction(QWebPage::ToggleSubscript);
updateAction(QWebPage::ToggleSuperscript);
updateAction(QWebPage::InsertUnorderedList);
updateAction(QWebPage::InsertOrderedList);
updateAction(QWebPage::Indent);
updateAction(QWebPage::Outdent);
updateAction(QWebPage::AlignCenter);
updateAction(QWebPage::AlignJustified);
updateAction(QWebPage::AlignLeft);
updateAction(QWebPage::AlignRight);
}
void QWebPagePrivate::timerEvent(QTimerEvent *ev)
{
int timerId = ev->timerId();
if (timerId == tripleClickTimer.timerId())
tripleClickTimer.stop();
else
q->timerEvent(ev);
}
void QWebPagePrivate::mouseMoveEvent(QGraphicsSceneMouseEvent* ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
bool accepted = frame->eventHandler()->mouseMoved(PlatformMouseEvent(ev, 0));
ev->setAccepted(accepted);
}
void QWebPagePrivate::mouseMoveEvent(QMouseEvent *ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
bool accepted = frame->eventHandler()->mouseMoved(PlatformMouseEvent(ev, 0));
ev->setAccepted(accepted);
}
void QWebPagePrivate::mousePressEvent(QGraphicsSceneMouseEvent* ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
RefPtr<WebCore::Node> oldNode;
Frame* focusedFrame = page->focusController()->focusedFrame();
if (Document* focusedDocument = focusedFrame ? focusedFrame->document() : 0)
oldNode = focusedDocument->focusedNode();
if (tripleClickTimer.isActive()
&& (ev->pos().toPoint() - tripleClick).manhattanLength()
< QApplication::startDragDistance()) {
mouseTripleClickEvent(ev);
return;
}
bool accepted = false;
PlatformMouseEvent mev(ev, 1);
// ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton
if (mev.button() != NoButton)
accepted = frame->eventHandler()->handleMousePressEvent(mev);
ev->setAccepted(accepted);
RefPtr<WebCore::Node> newNode;
focusedFrame = page->focusController()->focusedFrame();
if (Document* focusedDocument = focusedFrame ? focusedFrame->document() : 0)
newNode = focusedDocument->focusedNode();
if (newNode && oldNode != newNode)
clickCausedFocus = true;
}
void QWebPagePrivate::mousePressEvent(QMouseEvent *ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
RefPtr<WebCore::Node> oldNode;
Frame* focusedFrame = page->focusController()->focusedFrame();
if (Document* focusedDocument = focusedFrame ? focusedFrame->document() : 0)
oldNode = focusedDocument->focusedNode();
if (tripleClickTimer.isActive()
&& (ev->pos() - tripleClick).manhattanLength()
< QApplication::startDragDistance()) {
mouseTripleClickEvent(ev);
return;
}
bool accepted = false;
PlatformMouseEvent mev(ev, 1);
// ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton
if (mev.button() != NoButton)
accepted = frame->eventHandler()->handleMousePressEvent(mev);
ev->setAccepted(accepted);
RefPtr<WebCore::Node> newNode;
focusedFrame = page->focusController()->focusedFrame();
if (Document* focusedDocument = focusedFrame ? focusedFrame->document() : 0)
newNode = focusedDocument->focusedNode();
if (newNode && oldNode != newNode)
clickCausedFocus = true;
}
void QWebPagePrivate::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
bool accepted = false;
PlatformMouseEvent mev(ev, 2);
// ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton
if (mev.button() != NoButton)
accepted = frame->eventHandler()->handleMousePressEvent(mev);
ev->setAccepted(accepted);
tripleClickTimer.start(QApplication::doubleClickInterval(), q);
tripleClick = ev->pos().toPoint();
}
void QWebPagePrivate::mouseDoubleClickEvent(QMouseEvent *ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
bool accepted = false;
PlatformMouseEvent mev(ev, 2);
// ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton
if (mev.button() != NoButton)
accepted = frame->eventHandler()->handleMousePressEvent(mev);
ev->setAccepted(accepted);
tripleClickTimer.start(QApplication::doubleClickInterval(), q);
tripleClick = ev->pos();
}
void QWebPagePrivate::mouseTripleClickEvent(QGraphicsSceneMouseEvent *ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
bool accepted = false;
PlatformMouseEvent mev(ev, 3);
// ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton
if (mev.button() != NoButton)
accepted = frame->eventHandler()->handleMousePressEvent(mev);
ev->setAccepted(accepted);
}
void QWebPagePrivate::mouseTripleClickEvent(QMouseEvent *ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
bool accepted = false;
PlatformMouseEvent mev(ev, 3);
// ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton
if (mev.button() != NoButton)
accepted = frame->eventHandler()->handleMousePressEvent(mev);
ev->setAccepted(accepted);
}
void QWebPagePrivate::handleClipboard(QEvent* ev, Qt::MouseButton button)
{
#ifndef QT_NO_CLIPBOARD
if (QApplication::clipboard()->supportsSelection()) {
bool oldSelectionMode = Pasteboard::generalPasteboard()->isSelectionMode();
Pasteboard::generalPasteboard()->setSelectionMode(true);
WebCore::Frame* focusFrame = page->focusController()->focusedOrMainFrame();
if (button == Qt::LeftButton) {
if (focusFrame && (focusFrame->editor()->canCopy() || focusFrame->editor()->canDHTMLCopy())) {
focusFrame->editor()->copy();
ev->setAccepted(true);
}
} else if (button == Qt::MidButton) {
if (focusFrame && (focusFrame->editor()->canPaste() || focusFrame->editor()->canDHTMLPaste())) {
focusFrame->editor()->paste();
ev->setAccepted(true);
}
}
Pasteboard::generalPasteboard()->setSelectionMode(oldSelectionMode);
}
#endif
}
void QWebPagePrivate::mouseReleaseEvent(QGraphicsSceneMouseEvent* ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
bool accepted = false;
PlatformMouseEvent mev(ev, 0);
// ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton
if (mev.button() != NoButton)
accepted = frame->eventHandler()->handleMouseReleaseEvent(mev);
ev->setAccepted(accepted);
handleClipboard(ev, ev->button());
handleSoftwareInputPanel(ev->button());
}
void QWebPagePrivate::handleSoftwareInputPanel(Qt::MouseButton button)
{
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
Frame* frame = page->focusController()->focusedFrame();
if (!frame)
return;
if (client && client->inputMethodEnabled()
&& frame->document()->focusedNode()
&& button == Qt::LeftButton && qApp->autoSipEnabled()) {
QStyle::RequestSoftwareInputPanel behavior = QStyle::RequestSoftwareInputPanel(
client->ownerWidget()->style()->styleHint(QStyle::SH_RequestSoftwareInputPanel));
if (!clickCausedFocus || behavior == QStyle::RSIP_OnMouseClick) {
QEvent event(QEvent::RequestSoftwareInputPanel);
QApplication::sendEvent(client->ownerWidget(), &event);
}
}
clickCausedFocus = false;
#endif
}
void QWebPagePrivate::mouseReleaseEvent(QMouseEvent *ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
bool accepted = false;
PlatformMouseEvent mev(ev, 0);
// ignore the event if we can't map Qt's mouse buttons to WebCore::MouseButton
if (mev.button() != NoButton)
accepted = frame->eventHandler()->handleMouseReleaseEvent(mev);
ev->setAccepted(accepted);
handleClipboard(ev, ev->button());
handleSoftwareInputPanel(ev->button());
}
#ifndef QT_NO_CONTEXTMENU
void QWebPagePrivate::contextMenuEvent(const QPoint& globalPos)
{
QMenu *menu = q->createStandardContextMenu();
if (menu) {
menu->exec(globalPos);
delete menu;
}
}
#endif // QT_NO_CONTEXTMENU
/*!
\since 4.5
This function creates the standard context menu which is shown when
the user clicks on the web page with the right mouse button. It is
called from the default contextMenuEvent() handler. The popup menu's
ownership is transferred to the caller.
*/
QMenu *QWebPage::createStandardContextMenu()
{
#ifndef QT_NO_CONTEXTMENU
QMenu *menu = d->currentContextMenu;
d->currentContextMenu = 0;
return menu;
#else
return 0;
#endif
}
#ifndef QT_NO_WHEELEVENT
void QWebPagePrivate::wheelEvent(QGraphicsSceneWheelEvent* ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
WebCore::PlatformWheelEvent pev(ev);
bool accepted = frame->eventHandler()->handleWheelEvent(pev);
ev->setAccepted(accepted);
}
void QWebPagePrivate::wheelEvent(QWheelEvent *ev)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return;
WebCore::PlatformWheelEvent pev(ev);
bool accepted = frame->eventHandler()->handleWheelEvent(pev);
ev->setAccepted(accepted);
}
#endif // QT_NO_WHEELEVENT
#ifndef QT_NO_SHORTCUT
QWebPage::WebAction QWebPagePrivate::editorActionForKeyEvent(QKeyEvent* event)
{
static struct {
QKeySequence::StandardKey standardKey;
QWebPage::WebAction action;
} editorActions[] = {
{ QKeySequence::Cut, QWebPage::Cut },
{ QKeySequence::Copy, QWebPage::Copy },
{ QKeySequence::Paste, QWebPage::Paste },
{ QKeySequence::Undo, QWebPage::Undo },
{ QKeySequence::Redo, QWebPage::Redo },
{ QKeySequence::MoveToNextChar, QWebPage::MoveToNextChar },
{ QKeySequence::MoveToPreviousChar, QWebPage::MoveToPreviousChar },
{ QKeySequence::MoveToNextWord, QWebPage::MoveToNextWord },
{ QKeySequence::MoveToPreviousWord, QWebPage::MoveToPreviousWord },
{ QKeySequence::MoveToNextLine, QWebPage::MoveToNextLine },
{ QKeySequence::MoveToPreviousLine, QWebPage::MoveToPreviousLine },
{ QKeySequence::MoveToStartOfLine, QWebPage::MoveToStartOfLine },
{ QKeySequence::MoveToEndOfLine, QWebPage::MoveToEndOfLine },
{ QKeySequence::MoveToStartOfBlock, QWebPage::MoveToStartOfBlock },
{ QKeySequence::MoveToEndOfBlock, QWebPage::MoveToEndOfBlock },
{ QKeySequence::MoveToStartOfDocument, QWebPage::MoveToStartOfDocument },
{ QKeySequence::MoveToEndOfDocument, QWebPage::MoveToEndOfDocument },
{ QKeySequence::SelectNextChar, QWebPage::SelectNextChar },
{ QKeySequence::SelectPreviousChar, QWebPage::SelectPreviousChar },
{ QKeySequence::SelectNextWord, QWebPage::SelectNextWord },
{ QKeySequence::SelectPreviousWord, QWebPage::SelectPreviousWord },
{ QKeySequence::SelectNextLine, QWebPage::SelectNextLine },
{ QKeySequence::SelectPreviousLine, QWebPage::SelectPreviousLine },
{ QKeySequence::SelectStartOfLine, QWebPage::SelectStartOfLine },
{ QKeySequence::SelectEndOfLine, QWebPage::SelectEndOfLine },
{ QKeySequence::SelectStartOfBlock, QWebPage::SelectStartOfBlock },
{ QKeySequence::SelectEndOfBlock, QWebPage::SelectEndOfBlock },
{ QKeySequence::SelectStartOfDocument, QWebPage::SelectStartOfDocument },
{ QKeySequence::SelectEndOfDocument, QWebPage::SelectEndOfDocument },
{ QKeySequence::DeleteStartOfWord, QWebPage::DeleteStartOfWord },
{ QKeySequence::DeleteEndOfWord, QWebPage::DeleteEndOfWord },
{ QKeySequence::InsertParagraphSeparator, QWebPage::InsertParagraphSeparator },
{ QKeySequence::InsertLineSeparator, QWebPage::InsertLineSeparator },
{ QKeySequence::SelectAll, QWebPage::SelectAll },
{ QKeySequence::UnknownKey, QWebPage::NoWebAction }
};
for (int i = 0; editorActions[i].standardKey != QKeySequence::UnknownKey; ++i)
if (event == editorActions[i].standardKey)
return editorActions[i].action;
return QWebPage::NoWebAction;
}
#endif // QT_NO_SHORTCUT
void QWebPagePrivate::keyPressEvent(QKeyEvent *ev)
{
bool handled = false;
WebCore::Frame* frame = page->focusController()->focusedOrMainFrame();
// we forward the key event to WebCore first to handle potential DOM
// defined event handlers and later on end up in EditorClientQt::handleKeyboardEvent
// to trigger editor commands via triggerAction().
if (!handled)
handled = frame->eventHandler()->keyEvent(ev);
if (!handled) {
handled = true;
if (!handleScrolling(ev, frame)) {
switch (ev->key()) {
case Qt::Key_Back:
q->triggerAction(QWebPage::Back);
break;
case Qt::Key_Forward:
q->triggerAction(QWebPage::Forward);
break;
case Qt::Key_Stop:
q->triggerAction(QWebPage::Stop);
break;
case Qt::Key_Refresh:
q->triggerAction(QWebPage::Reload);
break;
case Qt::Key_Backspace:
if (ev->modifiers() == Qt::ShiftModifier)
q->triggerAction(QWebPage::Forward);
else
q->triggerAction(QWebPage::Back);
break;
default:
handled = false;
break;
}
}
}
ev->setAccepted(handled);
}
void QWebPagePrivate::keyReleaseEvent(QKeyEvent *ev)
{
if (ev->isAutoRepeat()) {
ev->setAccepted(true);
return;
}
WebCore::Frame* frame = page->focusController()->focusedOrMainFrame();
bool handled = frame->eventHandler()->keyEvent(ev);
ev->setAccepted(handled);
}
void QWebPagePrivate::focusInEvent(QFocusEvent*)
{
FocusController *focusController = page->focusController();
focusController->setActive(true);
focusController->setFocused(true);
if (!focusController->focusedFrame())
focusController->setFocusedFrame(QWebFramePrivate::core(mainFrame));
}
void QWebPagePrivate::focusOutEvent(QFocusEvent*)
{
// only set the focused frame inactive so that we stop painting the caret
// and the focus frame. But don't tell the focus controller so that upon
// focusInEvent() we can re-activate the frame.
FocusController *focusController = page->focusController();
// Call setFocused first so that window.onblur doesn't get called twice
focusController->setFocused(false);
focusController->setActive(false);
}
void QWebPagePrivate::dragEnterEvent(QGraphicsSceneDragDropEvent* ev)
{
#ifndef QT_NO_DRAGANDDROP
DragData dragData(ev->mimeData(), ev->pos().toPoint(),
QCursor::pos(), dropActionToDragOp(ev->possibleActions()));
Qt::DropAction action = dragOpToDropAction(page->dragController()->dragEntered(&dragData));
ev->setDropAction(action);
if (action != Qt::IgnoreAction)
ev->acceptProposedAction();
#endif
}
void QWebPagePrivate::dragEnterEvent(QDragEnterEvent* ev)
{
#ifndef QT_NO_DRAGANDDROP
DragData dragData(ev->mimeData(), ev->pos(), QCursor::pos(),
dropActionToDragOp(ev->possibleActions()));
Qt::DropAction action = dragOpToDropAction(page->dragController()->dragEntered(&dragData));
ev->setDropAction(action);
// We must accept this event in order to receive the drag move events that are sent
// while the drag and drop action is in progress.
ev->acceptProposedAction();
#endif
}
void QWebPagePrivate::dragLeaveEvent(QGraphicsSceneDragDropEvent* ev)
{
#ifndef QT_NO_DRAGANDDROP
DragData dragData(0, IntPoint(), QCursor::pos(), DragOperationNone);
page->dragController()->dragExited(&dragData);
ev->accept();
#endif
}
void QWebPagePrivate::dragLeaveEvent(QDragLeaveEvent* ev)
{
#ifndef QT_NO_DRAGANDDROP
DragData dragData(0, IntPoint(), QCursor::pos(), DragOperationNone);
page->dragController()->dragExited(&dragData);
ev->accept();
#endif
}
void QWebPagePrivate::dragMoveEvent(QGraphicsSceneDragDropEvent* ev)
{
#ifndef QT_NO_DRAGANDDROP
DragData dragData(ev->mimeData(), ev->pos().toPoint(),
QCursor::pos(), dropActionToDragOp(ev->possibleActions()));
Qt::DropAction action = dragOpToDropAction(page->dragController()->dragUpdated(&dragData));
ev->setDropAction(action);
if (action != Qt::IgnoreAction)
ev->acceptProposedAction();
#endif
}
void QWebPagePrivate::dragMoveEvent(QDragMoveEvent* ev)
{
#ifndef QT_NO_DRAGANDDROP
DragData dragData(ev->mimeData(), ev->pos(), QCursor::pos(),
dropActionToDragOp(ev->possibleActions()));
Qt::DropAction action = dragOpToDropAction(page->dragController()->dragUpdated(&dragData));
m_lastDropAction = action;
ev->setDropAction(action);
// We must accept this event in order to receive the drag move events that are sent
// while the drag and drop action is in progress.
ev->acceptProposedAction();
#endif
}
void QWebPagePrivate::dropEvent(QGraphicsSceneDragDropEvent* ev)
{
#ifndef QT_NO_DRAGANDDROP
DragData dragData(ev->mimeData(), ev->pos().toPoint(),
QCursor::pos(), dropActionToDragOp(ev->possibleActions()));
if (page->dragController()->performDrag(&dragData))
ev->acceptProposedAction();
#endif
}
void QWebPagePrivate::dropEvent(QDropEvent* ev)
{
#ifndef QT_NO_DRAGANDDROP
// Overwrite the defaults set by QDragManager::defaultAction()
ev->setDropAction(m_lastDropAction);
DragData dragData(ev->mimeData(), ev->pos(), QCursor::pos(),
dropActionToDragOp(Qt::DropAction(ev->dropAction())));
if (page->dragController()->performDrag(&dragData))
ev->acceptProposedAction();
#endif
}
void QWebPagePrivate::leaveEvent(QEvent*)
{
// Fake a mouse move event just outside of the widget, since all
// the interesting mouse-out behavior like invalidating scrollbars
// is handled by the WebKit event handler's mouseMoved function.
QMouseEvent fakeEvent(QEvent::MouseMove, QCursor::pos(), Qt::NoButton, Qt::NoButton, Qt::NoModifier);
mouseMoveEvent(&fakeEvent);
}
/*!
\property QWebPage::palette
\brief the page's palette
The base brush of the palette is used to draw the background of the main frame.
By default, this property contains the application's default palette.
*/
void QWebPage::setPalette(const QPalette &pal)
{
d->palette = pal;
if (!d->mainFrame || !d->mainFrame->d->frame->view())
return;
QBrush brush = pal.brush(QPalette::Base);
QColor backgroundColor = brush.style() == Qt::SolidPattern ? brush.color() : QColor();
QWebFramePrivate::core(d->mainFrame)->view()->updateBackgroundRecursively(backgroundColor, !backgroundColor.alpha());
}
QPalette QWebPage::palette() const
{
return d->palette;
}
void QWebPagePrivate::inputMethodEvent(QInputMethodEvent *ev)
{
WebCore::Frame *frame = page->focusController()->focusedOrMainFrame();
WebCore::Editor *editor = frame->editor();
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
QInputMethodEvent::Attribute selection(QInputMethodEvent::Selection, 0, 0, QVariant());
#endif
if (!editor->canEdit()) {
ev->ignore();
return;
}
RenderObject* renderer = 0;
RenderTextControl* renderTextControl = 0;
if (frame->selection()->rootEditableElement())
renderer = frame->selection()->rootEditableElement()->shadowAncestorNode()->renderer();
if (renderer && renderer->isTextControl())
renderTextControl = toRenderTextControl(renderer);
Vector<CompositionUnderline> underlines;
bool hasSelection = false;
for (int i = 0; i < ev->attributes().size(); ++i) {
const QInputMethodEvent::Attribute& a = ev->attributes().at(i);
switch (a.type) {
case QInputMethodEvent::TextFormat: {
QTextCharFormat textCharFormat = a.value.value<QTextFormat>().toCharFormat();
QColor qcolor = textCharFormat.underlineColor();
underlines.append(CompositionUnderline(qMin(a.start, (a.start + a.length)), qMax(a.start, (a.start + a.length)), Color(makeRGBA(qcolor.red(), qcolor.green(), qcolor.blue(), qcolor.alpha())), false));
break;
}
case QInputMethodEvent::Cursor: {
frame->selection()->setCaretVisible(a.length); //if length is 0 cursor is invisible
if (a.length > 0) {
RenderObject* caretRenderer = frame->selection()->caretRenderer();
if (caretRenderer) {
QColor qcolor = a.value.value<QColor>();
caretRenderer->style()->setColor(Color(makeRGBA(qcolor.red(), qcolor.green(), qcolor.blue(), qcolor.alpha())));
}
}
break;
}
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
case QInputMethodEvent::Selection: {
selection = a;
hasSelection = true;
break;
}
#endif
}
}
if (!ev->commitString().isEmpty())
editor->confirmComposition(ev->commitString());
else {
// 1. empty preedit with a selection attribute, and start/end of 0 cancels composition
// 2. empty preedit with a selection attribute, and start/end of non-0 updates selection of current preedit text
// 3. populated preedit with a selection attribute, and start/end of 0 or non-0 updates selection of supplied preedit text
// 4. otherwise event is updating supplied pre-edit text
QString preedit = ev->preeditString();
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
if (hasSelection) {
QString text = (renderTextControl) ? QString(renderTextControl->text()) : QString();
if (preedit.isEmpty() && selection.start + selection.length > 0)
preedit = text;
editor->setComposition(preedit, underlines,
(selection.length < 0) ? selection.start + selection.length : selection.start,
(selection.length < 0) ? selection.start : selection.start + selection.length);
} else
#endif
if (!preedit.isEmpty())
editor->setComposition(preedit, underlines, preedit.length(), 0);
}
ev->accept();
}
#ifndef QT_NO_PROPERTIES
typedef struct {
const char* name;
double deferredRepaintDelay;
double initialDeferredRepaintDelayDuringLoading;
double maxDeferredRepaintDelayDuringLoading;
double deferredRepaintDelayIncrementDuringLoading;
} QRepaintThrottlingPreset;
void QWebPagePrivate::dynamicPropertyChangeEvent(QDynamicPropertyChangeEvent* event)
{
if (event->propertyName() == "_q_viewMode") {
page->setViewMode(Page::stringToViewMode(q->property("_q_viewMode").toString()));
} else if (event->propertyName() == "_q_HTMLTokenizerChunkSize") {
int chunkSize = q->property("_q_HTMLTokenizerChunkSize").toInt();
q->handle()->page->setCustomHTMLTokenizerChunkSize(chunkSize);
} else if (event->propertyName() == "_q_HTMLTokenizerTimeDelay") {
double timeDelay = q->property("_q_HTMLTokenizerTimeDelay").toDouble();
q->handle()->page->setCustomHTMLTokenizerTimeDelay(timeDelay);
} else if (event->propertyName() == "_q_RepaintThrottlingDeferredRepaintDelay") {
double p = q->property("_q_RepaintThrottlingDeferredRepaintDelay").toDouble();
FrameView::setRepaintThrottlingDeferredRepaintDelay(p);
} else if (event->propertyName() == "_q_RepaintThrottlingnInitialDeferredRepaintDelayDuringLoading") {
double p = q->property("_q_RepaintThrottlingnInitialDeferredRepaintDelayDuringLoading").toDouble();
FrameView::setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading(p);
} else if (event->propertyName() == "_q_RepaintThrottlingMaxDeferredRepaintDelayDuringLoading") {
double p = q->property("_q_RepaintThrottlingMaxDeferredRepaintDelayDuringLoading").toDouble();
FrameView::setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading(p);
} else if (event->propertyName() == "_q_RepaintThrottlingDeferredRepaintDelayIncrementDuringLoading") {
double p = q->property("_q_RepaintThrottlingDeferredRepaintDelayIncrementDuringLoading").toDouble();
FrameView::setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading(p);
} else if (event->propertyName() == "_q_RepaintThrottlingPreset") {
static const QRepaintThrottlingPreset presets[] = {
{ "NoThrottling", 0, 0, 0, 0 },
{ "Legacy", 0.025, 0, 2.5, 0.5 },
{ "Minimal", 0.01, 0, 1, 0.2 },
{ "Medium", 0.025, 1, 5, 0.5 },
{ "Heavy", 0.1, 2, 10, 1 }
};
QString p = q->property("_q_RepaintThrottlingPreset").toString();
for(int i = 0; i < sizeof(presets) / sizeof(presets[0]); i++) {
if(p == presets[i].name) {
FrameView::setRepaintThrottlingDeferredRepaintDelay(
presets[i].deferredRepaintDelay);
FrameView::setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading(
presets[i].initialDeferredRepaintDelayDuringLoading);
FrameView::setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading(
presets[i].maxDeferredRepaintDelayDuringLoading);
FrameView::setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading(
presets[i].deferredRepaintDelayIncrementDuringLoading);
break;
}
}
}
#if ENABLE(TILED_BACKING_STORE)
else if (event->propertyName() == "_q_TiledBackingStoreTileSize") {
WebCore::Frame* frame = QWebFramePrivate::core(q->mainFrame());
if (!frame->tiledBackingStore())
return;
QSize tileSize = q->property("_q_TiledBackingStoreTileSize").toSize();
frame->tiledBackingStore()->setTileSize(tileSize);
} else if (event->propertyName() == "_q_TiledBackingStoreTileCreationDelay") {
WebCore::Frame* frame = QWebFramePrivate::core(q->mainFrame());
if (!frame->tiledBackingStore())
return;
int tileCreationDelay = q->property("_q_TiledBackingStoreTileCreationDelay").toInt();
frame->tiledBackingStore()->setTileCreationDelay(static_cast<double>(tileCreationDelay) / 1000.);
} else if (event->propertyName() == "_q_TiledBackingStoreKeepAreaMultiplier") {
WebCore::Frame* frame = QWebFramePrivate::core(q->mainFrame());
if (!frame->tiledBackingStore())
return;
FloatSize keepMultiplier;
FloatSize coverMultiplier;
frame->tiledBackingStore()->getKeepAndCoverAreaMultipliers(keepMultiplier, coverMultiplier);
QSizeF qSize = q->property("_q_TiledBackingStoreKeepAreaMultiplier").toSizeF();
keepMultiplier = FloatSize(qSize.width(), qSize.height());
frame->tiledBackingStore()->setKeepAndCoverAreaMultipliers(keepMultiplier, coverMultiplier);
} else if (event->propertyName() == "_q_TiledBackingStoreCoverAreaMultiplier") {
WebCore::Frame* frame = QWebFramePrivate::core(q->mainFrame());
if (!frame->tiledBackingStore())
return;
FloatSize keepMultiplier;
FloatSize coverMultiplier;
frame->tiledBackingStore()->getKeepAndCoverAreaMultipliers(keepMultiplier, coverMultiplier);
QSizeF qSize = q->property("_q_TiledBackingStoreCoverAreaMultiplier").toSizeF();
coverMultiplier = FloatSize(qSize.width(), qSize.height());
frame->tiledBackingStore()->setKeepAndCoverAreaMultipliers(keepMultiplier, coverMultiplier);
}
#endif
}
#endif
void QWebPagePrivate::shortcutOverrideEvent(QKeyEvent* event)
{
WebCore::Frame* frame = page->focusController()->focusedOrMainFrame();
WebCore::Editor* editor = frame->editor();
if (editor->canEdit()) {
if (event->modifiers() == Qt::NoModifier
|| event->modifiers() == Qt::ShiftModifier
|| event->modifiers() == Qt::KeypadModifier) {
if (event->key() < Qt::Key_Escape) {
event->accept();
} else {
switch (event->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
case Qt::Key_Delete:
case Qt::Key_Home:
case Qt::Key_End:
case Qt::Key_Backspace:
case Qt::Key_Left:
case Qt::Key_Right:
case Qt::Key_Up:
case Qt::Key_Down:
case Qt::Key_Tab:
event->accept();
default:
break;
}
}
}
#ifndef QT_NO_SHORTCUT
else if (editorActionForKeyEvent(event) != QWebPage::NoWebAction)
event->accept();
#endif
}
}
bool QWebPagePrivate::handleScrolling(QKeyEvent *ev, Frame *frame)
{
ScrollDirection direction;
ScrollGranularity granularity;
#ifndef QT_NO_SHORTCUT
if (ev == QKeySequence::MoveToNextPage
|| (ev->key() == Qt::Key_Space && !(ev->modifiers() & Qt::ShiftModifier))) {
granularity = ScrollByPage;
direction = ScrollDown;
} else if (ev == QKeySequence::MoveToPreviousPage
|| ((ev->key() == Qt::Key_Space) && (ev->modifiers() & Qt::ShiftModifier))) {
granularity = ScrollByPage;
direction = ScrollUp;
} else
#endif // QT_NO_SHORTCUT
if ((ev->key() == Qt::Key_Up && ev->modifiers() & Qt::ControlModifier)
|| ev->key() == Qt::Key_Home) {
granularity = ScrollByDocument;
direction = ScrollUp;
} else if ((ev->key() == Qt::Key_Down && ev->modifiers() & Qt::ControlModifier)
|| ev->key() == Qt::Key_End) {
granularity = ScrollByDocument;
direction = ScrollDown;
} else {
switch (ev->key()) {
case Qt::Key_Up:
granularity = ScrollByLine;
direction = ScrollUp;
break;
case Qt::Key_Down:
granularity = ScrollByLine;
direction = ScrollDown;
break;
case Qt::Key_Left:
granularity = ScrollByLine;
direction = ScrollLeft;
break;
case Qt::Key_Right:
granularity = ScrollByLine;
direction = ScrollRight;
break;
default:
return false;
}
}
return frame->eventHandler()->scrollRecursively(direction, granularity);
}
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
bool QWebPagePrivate::touchEvent(QTouchEvent* event)
{
WebCore::Frame* frame = QWebFramePrivate::core(mainFrame);
if (!frame->view())
return false;
// Always accept the QTouchEvent so that we'll receive also TouchUpdate and TouchEnd events
event->setAccepted(true);
// Return whether the default action was cancelled in the JS event handler
return frame->eventHandler()->handleTouchEvent(PlatformTouchEvent(event));
}
#endif
/*!
This method is used by the input method to query a set of properties of the page
to be able to support complex input method operations as support for surrounding
text and reconversions.
\a property specifies which property is queried.
\sa QWidget::inputMethodEvent(), QInputMethodEvent, QInputContext
*/
QVariant QWebPage::inputMethodQuery(Qt::InputMethodQuery property) const
{
Frame* frame = d->page->focusController()->focusedFrame();
if (!frame)
return QVariant();
WebCore::Editor* editor = frame->editor();
RenderObject* renderer = 0;
RenderTextControl* renderTextControl = 0;
if (frame->selection()->rootEditableElement())
renderer = frame->selection()->rootEditableElement()->shadowAncestorNode()->renderer();
if (renderer && renderer->isTextControl())
renderTextControl = toRenderTextControl(renderer);
switch (property) {
case Qt::ImMicroFocus: {
WebCore::FrameView* view = frame->view();
if (view && view->needsLayout()) {
// We can't access absoluteCaretBounds() while the view needs to layout.
return QVariant();
}
return QVariant(view->contentsToWindow(frame->selection()->absoluteCaretBounds()));
}
case Qt::ImFont: {
if (renderTextControl) {
RenderStyle* renderStyle = renderTextControl->style();
return QVariant(QFont(renderStyle->font().font()));
}
return QVariant(QFont());
}
case Qt::ImCursorPosition: {
if (renderTextControl) {
if (editor->hasComposition()) {
RefPtr<Range> range = editor->compositionRange();
return QVariant(renderTextControl->selectionEnd() - TextIterator::rangeLength(range.get()));
}
return QVariant(frame->selection()->extent().offsetInContainerNode());
}
return QVariant();
}
case Qt::ImSurroundingText: {
if (renderTextControl) {
QString text = renderTextControl->text();
RefPtr<Range> range = editor->compositionRange();
if (range) {
text.remove(range->startPosition().offsetInContainerNode(), TextIterator::rangeLength(range.get()));
}
return QVariant(text);
}
return QVariant();
}
case Qt::ImCurrentSelection: {
if (renderTextControl) {
int start = renderTextControl->selectionStart();
int end = renderTextControl->selectionEnd();
if (end > start)
return QVariant(QString(renderTextControl->text()).mid(start,end-start));
}
return QVariant();
}
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
case Qt::ImAnchorPosition: {
if (renderTextControl) {
if (editor->hasComposition()) {
RefPtr<Range> range = editor->compositionRange();
return QVariant(renderTextControl->selectionStart() - TextIterator::rangeLength(range.get()));
}
return QVariant(frame->selection()->base().offsetInContainerNode());
}
return QVariant();
}
case Qt::ImMaximumTextLength: {
if (frame->selection()->isContentEditable()) {
if (frame->document() && frame->document()->focusedNode()) {
if (frame->document()->focusedNode()->hasTagName(HTMLNames::inputTag)) {
HTMLInputElement* inputElement = static_cast<HTMLInputElement*>(frame->document()->focusedNode());
return QVariant(inputElement->maxLength());
}
}
return QVariant(InputElement::s_maximumLength);
}
return QVariant(0);
}
#endif
default:
return QVariant();
}
}
/*!
\internal
*/
void QWebPagePrivate::setInspector(QWebInspector* insp)
{
if (inspector)
inspector->d->setFrontend(0);
if (inspectorIsInternalOnly) {
QWebInspector* inspToDelete = inspector;
inspector = 0;
inspectorIsInternalOnly = false;
delete inspToDelete; // Delete after to prevent infinite recursion
}
inspector = insp;
// Give inspector frontend web view if previously created
if (inspector && inspectorFrontend)
inspector->d->setFrontend(inspectorFrontend);
}
/*!
\internal
Returns the inspector and creates it if it wasn't created yet.
The instance created here will not be available through QWebPage's API.
*/
QWebInspector* QWebPagePrivate::getOrCreateInspector()
{
#if ENABLE(INSPECTOR)
if (!inspector) {
QWebInspector* insp = new QWebInspector;
insp->setPage(q);
inspectorIsInternalOnly = true;
Q_ASSERT(inspector); // Associated through QWebInspector::setPage(q)
}
#endif
return inspector;
}
/*! \internal */
InspectorController* QWebPagePrivate::inspectorController()
{
#if ENABLE(INSPECTOR)
return page->inspectorController();
#else
return 0;
#endif
}
/*!
\enum QWebPage::FindFlag
This enum describes the options available to the findText() function. The options
can be OR-ed together from the following list:
\value FindBackward Searches backwards instead of forwards.
\value FindCaseSensitively By default findText() works case insensitive. Specifying this option
changes the behaviour to a case sensitive find operation.
\value FindWrapsAroundDocument Makes findText() restart from the beginning of the document if the end
was reached and the text was not found.
\value HighlightAllOccurrences Highlights all existing occurrences of a specific string.
*/
/*!
\enum QWebPage::LinkDelegationPolicy
This enum defines the delegation policies a webpage can have when activating links and emitting
the linkClicked() signal.
\value DontDelegateLinks No links are delegated. Instead, QWebPage tries to handle them all.
\value DelegateExternalLinks When activating links that point to documents not stored on the
local filesystem or an equivalent - such as the Qt resource system - then linkClicked() is emitted.
\value DelegateAllLinks Whenever a link is activated the linkClicked() signal is emitted.
\sa QWebPage::linkDelegationPolicy
*/
/*!
\enum QWebPage::NavigationType
This enum describes the types of navigation available when browsing through hyperlinked
documents.
\value NavigationTypeLinkClicked The user clicked on a link or pressed return on a focused link.
\value NavigationTypeFormSubmitted The user activated a submit button for an HTML form.
\value NavigationTypeBackOrForward Navigation to a previously shown document in the back or forward history is requested.
\value NavigationTypeReload The user activated the reload action.
\value NavigationTypeFormResubmitted An HTML form was submitted a second time.
\value NavigationTypeOther A navigation to another document using a method not listed above.
\sa acceptNavigationRequest()
*/
/*!
\enum QWebPage::WebAction
This enum describes the types of action which can be performed on the web page.
Actions only have an effect when they are applicable. The availability of
actions can be be determined by checking \l{QAction::}{isEnabled()} on the
action returned by action().
One method of enabling the text editing, cursor movement, and text selection actions
is by setting \l contentEditable to true.
\value NoWebAction No action is triggered.
\value OpenLink Open the current link.
\value OpenLinkInNewWindow Open the current link in a new window.
\value OpenFrameInNewWindow Replicate the current frame in a new window.
\value DownloadLinkToDisk Download the current link to the disk.
\value CopyLinkToClipboard Copy the current link to the clipboard.
\value OpenImageInNewWindow Open the highlighted image in a new window.
\value DownloadImageToDisk Download the highlighted image to the disk.
\value CopyImageToClipboard Copy the highlighted image to the clipboard.
\value Back Navigate back in the history of navigated links.
\value Forward Navigate forward in the history of navigated links.
\value Stop Stop loading the current page.
\value StopScheduledPageRefresh Stop all pending page refresh/redirect requests.
\value Reload Reload the current page.
\value ReloadAndBypassCache Reload the current page, but do not use any local cache. (Added in Qt 4.6)
\value Cut Cut the content currently selected into the clipboard.
\value Copy Copy the content currently selected into the clipboard.
\value Paste Paste content from the clipboard.
\value Undo Undo the last editing action.
\value Redo Redo the last editing action.
\value MoveToNextChar Move the cursor to the next character.
\value MoveToPreviousChar Move the cursor to the previous character.
\value MoveToNextWord Move the cursor to the next word.
\value MoveToPreviousWord Move the cursor to the previous word.
\value MoveToNextLine Move the cursor to the next line.
\value MoveToPreviousLine Move the cursor to the previous line.
\value MoveToStartOfLine Move the cursor to the start of the line.
\value MoveToEndOfLine Move the cursor to the end of the line.
\value MoveToStartOfBlock Move the cursor to the start of the block.
\value MoveToEndOfBlock Move the cursor to the end of the block.
\value MoveToStartOfDocument Move the cursor to the start of the document.
\value MoveToEndOfDocument Move the cursor to the end of the document.
\value SelectNextChar Select to the next character.
\value SelectPreviousChar Select to the previous character.
\value SelectNextWord Select to the next word.
\value SelectPreviousWord Select to the previous word.
\value SelectNextLine Select to the next line.
\value SelectPreviousLine Select to the previous line.
\value SelectStartOfLine Select to the start of the line.
\value SelectEndOfLine Select to the end of the line.
\value SelectStartOfBlock Select to the start of the block.
\value SelectEndOfBlock Select to the end of the block.
\value SelectStartOfDocument Select to the start of the document.
\value SelectEndOfDocument Select to the end of the document.
\value DeleteStartOfWord Delete to the start of the word.
\value DeleteEndOfWord Delete to the end of the word.
\value SetTextDirectionDefault Set the text direction to the default direction.
\value SetTextDirectionLeftToRight Set the text direction to left-to-right.
\value SetTextDirectionRightToLeft Set the text direction to right-to-left.
\value ToggleBold Toggle the formatting between bold and normal weight.
\value ToggleItalic Toggle the formatting between italic and normal style.
\value ToggleUnderline Toggle underlining.
\value InspectElement Show the Web Inspector with the currently highlighted HTML element.
\value InsertParagraphSeparator Insert a new paragraph.
\value InsertLineSeparator Insert a new line.
\value SelectAll Selects all content.
\value PasteAndMatchStyle Paste content from the clipboard with current style.
\value RemoveFormat Removes formatting and style.
\value ToggleStrikethrough Toggle the formatting between strikethrough and normal style.
\value ToggleSubscript Toggle the formatting between subscript and baseline.
\value ToggleSuperscript Toggle the formatting between supercript and baseline.
\value InsertUnorderedList Toggles the selection between an ordered list and a normal block.
\value InsertOrderedList Toggles the selection between an ordered list and a normal block.
\value Indent Increases the indentation of the currently selected format block by one increment.
\value Outdent Decreases the indentation of the currently selected format block by one increment.
\value AlignCenter Applies center alignment to content.
\value AlignJustified Applies full justification to content.
\value AlignLeft Applies left justification to content.
\value AlignRight Applies right justification to content.
\omitvalue WebActionCount
*/
/*!
\enum QWebPage::WebWindowType
This enum describes the types of window that can be created by the createWindow() function.
\value WebBrowserWindow The window is a regular web browser window.
\value WebModalDialog The window acts as modal dialog.
*/
/*!
\class QWebPage::ViewportConfiguration
\since 4.7
\brief The QWebPage::ViewportConfiguration class describes hints that can be applied to a viewport.
QWebPage::ViewportConfiguration provides a description of a viewport, such as viewport geometry,
initial scale factor with limits, plus information about whether a user should be able
to scale the contents in the viewport or not, ie. by zooming.
ViewportConfiguration can be set by a web author using the viewport meta tag extension, documented
at \l{http://developer.apple.com/safari/library/documentation/appleapplications/reference/safariwebcontent/usingtheviewport/usingtheviewport.html}{Safari Reference Library: Using the Viewport Meta Tag}.
All values might not be set, as such when dealing with the hints, the developer needs to
check whether the values are valid. Negative values denote an invalid qreal value.
\inmodule QtWebKit
*/
/*!
Constructs an empty QWebPage::ViewportConfiguration.
*/
QWebPage::ViewportConfiguration::ViewportConfiguration()
: d(0)
, m_initialScaleFactor(-1.0)
, m_minimumScaleFactor(-1.0)
, m_maximumScaleFactor(-1.0)
, m_devicePixelRatio(-1.0)
, m_isUserScalable(true)
, m_isValid(false)
{
}
/*!
Constructs a QWebPage::ViewportConfiguration which is a copy from \a other .
*/
QWebPage::ViewportConfiguration::ViewportConfiguration(const QWebPage::ViewportConfiguration& other)
: d(other.d)
, m_initialScaleFactor(other.m_initialScaleFactor)
, m_minimumScaleFactor(other.m_minimumScaleFactor)
, m_maximumScaleFactor(other.m_maximumScaleFactor)
, m_devicePixelRatio(other.m_devicePixelRatio)
, m_isUserScalable(other.m_isUserScalable)
, m_isValid(other.m_isValid)
, m_size(other.m_size)
{
}
/*!
Destroys the QWebPage::ViewportConfiguration.
*/
QWebPage::ViewportConfiguration::~ViewportConfiguration()
{
}
/*!
Assigns the given QWebPage::ViewportConfiguration to this viewport hints and returns a
reference to this.
*/
QWebPage::ViewportConfiguration& QWebPage::ViewportConfiguration::operator=(const QWebPage::ViewportConfiguration& other)
{
if (this != &other) {
d = other.d;
m_initialScaleFactor = other.m_initialScaleFactor;
m_minimumScaleFactor = other.m_minimumScaleFactor;
m_maximumScaleFactor = other.m_maximumScaleFactor;
m_isUserScalable = other.m_isUserScalable;
m_isValid = other.m_isValid;
m_size = other.m_size;
}
return *this;
}
/*! \fn inline bool QWebPage::ViewportConfiguration::isValid() const
Returns whether this is a valid ViewportConfiguration or not.
An invalid ViewportConfiguration will have an empty QSize, negative values for scale factors and
true for the boolean isUserScalable.
*/
/*! \fn inline QSize QWebPage::ViewportConfiguration::size() const
Returns the size of the viewport.
*/
/*! \fn inline qreal QWebPage::ViewportConfiguration::initialScaleFactor() const
Returns the initial scale of the viewport as a multiplier.
*/
/*! \fn inline qreal QWebPage::ViewportConfiguration::minimumScaleFactor() const
Returns the minimum scale value of the viewport as a multiplier.
*/
/*! \fn inline qreal QWebPage::ViewportConfiguration::maximumScaleFactor() const
Returns the maximum scale value of the viewport as a multiplier.
*/
/*! \fn inline bool QWebPage::ViewportConfiguration::isUserScalable() const
Determines whether or not the scale can be modified by the user.
*/
/*!
\class QWebPage
\since 4.4
\brief The QWebPage class provides an object to view and edit web documents.
\inmodule QtWebKit
QWebPage holds a main frame responsible for web content, settings, the history
of navigated links and actions. This class can be used, together with QWebFrame,
to provide functionality like QWebView in a widget-less environment.
QWebPage's API is very similar to QWebView, as you are still provided with
common functions like action() (known as
\l{QWebView::pageAction()}{pageAction}() in QWebView), triggerAction(),
findText() and settings(). More QWebView-like functions can be found in the
main frame of QWebPage, obtained via the mainFrame() function. For example,
the \l{QWebFrame::load()}{load}(), \l{QWebFrame::setUrl()}{setUrl}() and
\l{QWebFrame::setHtml()}{setHtml}() functions for QWebPage can be accessed
using QWebFrame.
The loadStarted() signal is emitted when the page begins to load.The
loadProgress() signal, on the other hand, is emitted whenever an element
of the web page completes loading, such as an embedded image, a script,
etc. Finally, the loadFinished() signal is emitted when the page has
loaded completely. Its argument, either true or false, indicates whether
or not the load operation succeeded.
\section1 Using QWebPage in a Widget-less Environment
Before you begin painting a QWebPage object, you need to set the size of
the viewport by calling setViewportSize(). Then, you invoke the main
frame's render function (QWebFrame::render()). An example of this
is shown in the code snippet below.
Suppose we have a \c Thumbnail class as follows:
\snippet webkitsnippets/webpage/main.cpp 0
The \c Thumbnail's constructor takes in a \a url. We connect our QWebPage
object's \l{QWebPage::}{loadFinished()} signal to our private slot,
\c render().
\snippet webkitsnippets/webpage/main.cpp 1
The \c render() function shows how we can paint a thumbnail using a
QWebPage object.
\snippet webkitsnippets/webpage/main.cpp 2
We begin by setting the \l{QWebPage::viewportSize()}{viewportSize} and
then we instantiate a QImage object, \c image, with the same size as our
\l{QWebPage::viewportSize()}{viewportSize}. This image is then sent
as a parameter to \c painter. Next, we render the contents of the main
frame and its subframes into \c painter. Finally, we save the scaled image.
\sa QWebFrame
*/
/*!
Constructs an empty QWebPage with parent \a parent.
*/
QWebPage::QWebPage(QObject *parent)
: QObject(parent)
, d(new QWebPagePrivate(this))
{
setView(qobject_cast<QWidget*>(parent));
connect(this, SIGNAL(loadProgress(int)), this, SLOT(_q_onLoadProgressChanged(int)));
#ifndef NDEBUG
connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(_q_cleanupLeakMessages()));
#endif
}
/*!
Destroys the web page.
*/
QWebPage::~QWebPage()
{
d->createMainFrame();
FrameLoader *loader = d->mainFrame->d->frame->loader();
if (loader)
loader->detachFromParent();
if (d->inspector) {
// Since we have to delete an internal inspector,
// call setInspector(0) directly to prevent potential crashes
if (d->inspectorIsInternalOnly)
d->setInspector(0);
else
d->inspector->setPage(0);
}
delete d;
}
/*!
Returns the main frame of the page.
The main frame provides access to the hierarchy of sub-frames and is also needed if you
want to explicitly render a web page into a given painter.
\sa currentFrame()
*/
QWebFrame *QWebPage::mainFrame() const
{
d->createMainFrame();
return d->mainFrame;
}
/*!
Returns the frame currently active.
\sa mainFrame(), frameCreated()
*/
QWebFrame *QWebPage::currentFrame() const
{
d->createMainFrame();
return static_cast<WebCore::FrameLoaderClientQt *>(d->page->focusController()->focusedOrMainFrame()->loader()->client())->webFrame();
}
/*!
\since 4.6
Returns the frame at the given point \a pos, or 0 if there is no frame at
that position.
\sa mainFrame(), currentFrame()
*/
QWebFrame* QWebPage::frameAt(const QPoint& pos) const
{
QWebFrame* webFrame = mainFrame();
if (!webFrame->geometry().contains(pos))
return 0;
QWebHitTestResult hitTestResult = webFrame->hitTestContent(pos);
return hitTestResult.frame();
}
/*!
Returns a pointer to the view's history of navigated web pages.
*/
QWebHistory *QWebPage::history() const
{
d->createMainFrame();
return &d->history;
}
/*!
Sets the \a view that is associated with the web page.
\sa view()
*/
void QWebPage::setView(QWidget* view)
{
if (this->view() == view)
return;
d->view = view;
setViewportSize(view ? view->size() : QSize(0, 0));
// If we have no client, we install a special client delegating
// the responsibility to the QWidget. This is the code path
// handling a.o. the "legacy" QWebView.
//
// If such a special delegate already exist, we substitute the view.
if (d->client) {
if (d->client->isQWidgetClient())
static_cast<PageClientQWidget*>(d->client)->view = view;
return;
}
if (view)
d->client = new PageClientQWidget(view);
}
/*!
Returns the view widget that is associated with the web page.
\sa setView()
*/
QWidget *QWebPage::view() const
{
#if QT_VERSION < QT_VERSION_CHECK(4, 6, 0)
return d->view;
#else
return d->view.data();
#endif
}
/*!
This function is called whenever a JavaScript program tries to print a \a message to the web browser's console.
For example in case of evaluation errors the source URL may be provided in \a sourceID as well as the \a lineNumber.
The default implementation prints nothing.
*/
void QWebPage::javaScriptConsoleMessage(const QString& message, int lineNumber, const QString& sourceID)
{
Q_UNUSED(sourceID)
// Catch plugin logDestroy message for LayoutTests/plugins/open-and-close-window-with-plugin.html
// At this point DRT's WebPage has already been destroyed
if (QWebPagePrivate::drtRun) {
if (message == "PLUGIN: NPP_Destroy")
fprintf (stdout, "CONSOLE MESSAGE: line %d: %s\n", lineNumber, message.toUtf8().constData());
}
}
/*!
This function is called whenever a JavaScript program running inside \a frame calls the alert() function with
the message \a msg.
The default implementation shows the message, \a msg, with QMessageBox::information.
*/
void QWebPage::javaScriptAlert(QWebFrame *frame, const QString& msg)
{
Q_UNUSED(frame)
#ifndef QT_NO_MESSAGEBOX
QWidget* parent = (d->client) ? d->client->ownerWidget() : 0;
QMessageBox::information(parent, tr("JavaScript Alert - %1").arg(mainFrame()->url().host()), Qt::escape(msg), QMessageBox::Ok);
#endif
}
/*!
This function is called whenever a JavaScript program running inside \a frame calls the confirm() function
with the message, \a msg. Returns true if the user confirms the message; otherwise returns false.
The default implementation executes the query using QMessageBox::information with QMessageBox::Yes and QMessageBox::No buttons.
*/
bool QWebPage::javaScriptConfirm(QWebFrame *frame, const QString& msg)
{
Q_UNUSED(frame)
#ifdef QT_NO_MESSAGEBOX
return true;
#else
QWidget* parent = (d->client) ? d->client->ownerWidget() : 0;
return QMessageBox::Yes == QMessageBox::information(parent, tr("JavaScript Confirm - %1").arg(mainFrame()->url().host()), Qt::escape(msg), QMessageBox::Yes, QMessageBox::No);
#endif
}
/*!
This function is called whenever a JavaScript program running inside \a frame tries to prompt the user for input.
The program may provide an optional message, \a msg, as well as a default value for the input in \a defaultValue.
If the prompt was cancelled by the user the implementation should return false; otherwise the
result should be written to \a result and true should be returned. If the prompt was not cancelled by the
user, the implementation should return true and the result string must not be null.
The default implementation uses QInputDialog::getText().
*/
bool QWebPage::javaScriptPrompt(QWebFrame *frame, const QString& msg, const QString& defaultValue, QString* result)
{
Q_UNUSED(frame)
bool ok = false;
#ifndef QT_NO_INPUTDIALOG
QWidget* parent = (d->client) ? d->client->ownerWidget() : 0;
QString x = QInputDialog::getText(parent, tr("JavaScript Prompt - %1").arg(mainFrame()->url().host()), Qt::escape(msg), QLineEdit::Normal, defaultValue, &ok);
if (ok && result)
*result = x;
#endif
return ok;
}
/*!
\fn bool QWebPage::shouldInterruptJavaScript()
\since 4.6
This function is called when a JavaScript program is running for a long period of time.
If the user wanted to stop the JavaScript the implementation should return true; otherwise false.
The default implementation executes the query using QMessageBox::information with QMessageBox::Yes and QMessageBox::No buttons.
\warning Because of binary compatibility constraints, this function is not virtual. If you want to
provide your own implementation in a QWebPage subclass, reimplement the shouldInterruptJavaScript()
slot in your subclass instead. QtWebKit will dynamically detect the slot and call it.
*/
bool QWebPage::shouldInterruptJavaScript()
{
#ifdef QT_NO_MESSAGEBOX
return false;
#else
QWidget* parent = (d->client) ? d->client->ownerWidget() : 0;
return QMessageBox::Yes == QMessageBox::information(parent, tr("JavaScript Problem - %1").arg(mainFrame()->url().host()), tr("The script on this page appears to have a problem. Do you want to stop the script?"), QMessageBox::Yes, QMessageBox::No);
#endif
}
void QWebPage::setUserPermission(QWebFrame* frame, PermissionDomain domain, PermissionPolicy policy)
{
switch (domain) {
case NotificationsPermissionDomain:
#if ENABLE(NOTIFICATIONS)
if (policy == PermissionGranted)
NotificationPresenterClientQt::notificationPresenter()->allowNotificationForFrame(frame);
#endif
break;
case GeolocationPermissionDomain:
#if ENABLE(GEOLOCATION)
GeolocationPermissionClientQt::geolocationPermissionClient()->setPermission(frame, policy);
#endif
break;
default:
break;
}
}
/*!
This function is called whenever WebKit wants to create a new window of the given \a type, for
example when a JavaScript program requests to open a document in a new window.
If the new window can be created, the new window's QWebPage is returned; otherwise a null pointer is returned.
If the view associated with the web page is a QWebView object, then the default implementation forwards
the request to QWebView's createWindow() function; otherwise it returns a null pointer.
If \a type is WebModalDialog, the application must call setWindowModality(Qt::ApplicationModal) on the new window.
\note In the cases when the window creation is being triggered by JavaScript, apart from
reimplementing this method application must also set the JavaScriptCanOpenWindows attribute
of QWebSettings to true in order for it to get called.
\sa acceptNavigationRequest(), QWebView::createWindow()
*/
QWebPage *QWebPage::createWindow(WebWindowType type)
{
QWebView *webView = qobject_cast<QWebView*>(view());
if (webView) {
QWebView *newView = webView->createWindow(type);
if (newView)
return newView->page();
}
return 0;
}
/*!
This function is called whenever WebKit encounters a HTML object element with type "application/x-qt-plugin". It is
called regardless of the value of QWebSettings::PluginsEnabled. The \a classid, \a url, \a paramNames and \a paramValues
correspond to the HTML object element attributes and child elements to configure the embeddable object.
*/
QObject *QWebPage::createPlugin(const QString &classid, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues)
{
Q_UNUSED(classid)
Q_UNUSED(url)
Q_UNUSED(paramNames)
Q_UNUSED(paramValues)
return 0;
}
static WebCore::FrameLoadRequest frameLoadRequest(const QUrl &url, WebCore::Frame *frame)
{
WebCore::ResourceRequest rr(url, frame->loader()->outgoingReferrer());
return WebCore::FrameLoadRequest(rr);
}
static void openNewWindow(const QUrl& url, WebCore::Frame* frame)
{
if (Page* oldPage = frame->page()) {
WindowFeatures features;
if (Page* newPage = oldPage->chrome()->createWindow(frame,
frameLoadRequest(url, frame), features))
newPage->chrome()->show();
}
}
static void collectChildFrames(QWebFrame* frame, QList<QWebFrame*>& list)
{
list << frame->childFrames();
QListIterator<QWebFrame*> it(frame->childFrames());
while (it.hasNext()) {
collectChildFrames(it.next(), list);
}
}
/*!
This function can be called to trigger the specified \a action.
It is also called by QtWebKit if the user triggers the action, for example
through a context menu item.
If \a action is a checkable action then \a checked specified whether the action
is toggled or not.
\sa action()
*/
void QWebPage::triggerAction(WebAction action, bool)
{
WebCore::Frame *frame = d->page->focusController()->focusedOrMainFrame();
if (!frame)
return;
WebCore::Editor *editor = frame->editor();
const char *command = 0;
switch (action) {
case OpenLink:
if (QWebFrame *targetFrame = d->hitTestResult.linkTargetFrame()) {
WTF::RefPtr<WebCore::Frame> wcFrame = targetFrame->d->frame;
targetFrame->d->frame->loader()->loadFrameRequest(frameLoadRequest(d->hitTestResult.linkUrl(), wcFrame.get()),
/*lockHistory*/ false, /*lockBackForwardList*/ false, /*event*/ 0,
/*FormState*/ 0, SendReferrer);
break;
}
// fall through
case OpenLinkInNewWindow:
openNewWindow(d->hitTestResult.linkUrl(), frame);
break;
case OpenFrameInNewWindow: {
KURL url = frame->loader()->documentLoader()->unreachableURL();
if (url.isEmpty())
url = frame->loader()->documentLoader()->url();
openNewWindow(url, frame);
break;
}
case CopyLinkToClipboard: {
#if defined(Q_WS_X11)
bool oldSelectionMode = Pasteboard::generalPasteboard()->isSelectionMode();
Pasteboard::generalPasteboard()->setSelectionMode(true);
editor->copyURL(d->hitTestResult.linkUrl(), d->hitTestResult.linkText());
Pasteboard::generalPasteboard()->setSelectionMode(oldSelectionMode);
#endif
editor->copyURL(d->hitTestResult.linkUrl(), d->hitTestResult.linkText());
break;
}
case OpenImageInNewWindow:
openNewWindow(d->hitTestResult.imageUrl(), frame);
break;
case DownloadImageToDisk:
frame->loader()->client()->startDownload(WebCore::ResourceRequest(d->hitTestResult.imageUrl(), frame->loader()->outgoingReferrer()));
break;
case DownloadLinkToDisk:
frame->loader()->client()->startDownload(WebCore::ResourceRequest(d->hitTestResult.linkUrl(), frame->loader()->outgoingReferrer()));
break;
#ifndef QT_NO_CLIPBOARD
case CopyImageToClipboard:
QApplication::clipboard()->setPixmap(d->hitTestResult.pixmap());
break;
#endif
case Back:
d->page->goBack();
break;
case Forward:
d->page->goForward();
break;
case Stop:
mainFrame()->d->frame->loader()->stopForUserCancel();
break;
case Reload:
mainFrame()->d->frame->loader()->reload(/*endtoendreload*/false);
break;
case ReloadAndBypassCache:
mainFrame()->d->frame->loader()->reload(/*endtoendreload*/true);
break;
case SetTextDirectionDefault:
editor->setBaseWritingDirection(NaturalWritingDirection);
break;
case SetTextDirectionLeftToRight:
editor->setBaseWritingDirection(LeftToRightWritingDirection);
break;
case SetTextDirectionRightToLeft:
editor->setBaseWritingDirection(RightToLeftWritingDirection);
break;
case InspectElement: {
#if ENABLE(INSPECTOR)
if (!d->hitTestResult.isNull()) {
d->getOrCreateInspector(); // Make sure the inspector is created
d->inspector->show(); // The inspector is expected to be shown on inspection
d->page->inspectorController()->inspect(d->hitTestResult.d->innerNonSharedNode.get());
}
#endif
break;
}
case StopScheduledPageRefresh: {
QWebFrame* topFrame = mainFrame();
topFrame->d->frame->redirectScheduler()->cancel();
QList<QWebFrame*> childFrames;
collectChildFrames(topFrame, childFrames);
QListIterator<QWebFrame*> it(childFrames);
while (it.hasNext())
it.next()->d->frame->redirectScheduler()->cancel();
break;
}
default:
command = QWebPagePrivate::editorCommandForWebActions(action);
break;
}
if (command)
editor->command(command).execute();
}
QSize QWebPage::viewportSize() const
{
if (d->mainFrame && d->mainFrame->d->frame->view())
return d->mainFrame->d->frame->view()->frameRect().size();
return d->viewportSize;
}
/*!
\property QWebPage::viewportSize
\brief the size of the viewport
The size affects for example the visibility of scrollbars
if the document is larger than the viewport.
By default, for a newly-created Web page, this property contains a size with
zero width and height.
\sa QWebFrame::render(), preferredContentsSize
*/
void QWebPage::setViewportSize(const QSize &size) const
{
d->viewportSize = size;
QWebFrame *frame = mainFrame();
if (frame->d->frame && frame->d->frame->view()) {
WebCore::FrameView* view = frame->d->frame->view();
view->setFrameRect(QRect(QPoint(0, 0), size));
view->adjustViewSize();
}
}
QWebPage::ViewportConfiguration QWebPage::viewportConfigurationForSize(QSize availableSize) const
{
static int desktopWidth = 980;
static int deviceDPI = 160;
FloatRect rect = d->page->chrome()->windowRect();
int deviceWidth = rect.width();
int deviceHeight = rect.height();
WebCore::ViewportConfiguration conf = WebCore::findConfigurationForViewportData(mainFrame()->d->viewportArguments, desktopWidth, deviceWidth, deviceHeight, deviceDPI, availableSize);
ViewportConfiguration result;
result.m_isValid = true;
result.m_size = conf.layoutViewport;
result.m_initialScaleFactor = conf.initialScale;
result.m_minimumScaleFactor = conf.minimumScale;
result.m_maximumScaleFactor = conf.maximumScale;
result.m_devicePixelRatio = conf.devicePixelRatio;
return result;
}
QSize QWebPage::preferredContentsSize() const
{
QWebFrame* frame = d->mainFrame;
if (frame) {
WebCore::FrameView* view = frame->d->frame->view();
if (view && view->useFixedLayout())
return d->mainFrame->d->frame->view()->fixedLayoutSize();
}
return d->fixedLayoutSize;
}
/*!
\property QWebPage::preferredContentsSize
\since 4.6
\brief a custom size used for laying out the page contents.
By default all pages are laid out using the viewport of the page as the base.
As pages mostly are designed for desktop usage, they often do not layout properly
on small devices as the contents require a certain view width. For this reason
it is common to use a different layout size and then scale the contents to fit
within the actual view.
If this property is set to a valid size, this size is used for all layout needs
instead of the size of the viewport.
Setting an invalid size, makes the page fall back to using the viewport size for layout.
\sa viewportSize
*/
void QWebPage::setPreferredContentsSize(const QSize& size) const
{
// FIXME: Rename this method to setCustomLayoutSize
d->fixedLayoutSize = size;
QWebFrame* frame = mainFrame();
if (!frame->d->frame || !frame->d->frame->view())
return;
WebCore::FrameView* view = frame->d->frame->view();
if (size.isValid()) {
view->setUseFixedLayout(true);
view->setFixedLayoutSize(size);
} else if (view->useFixedLayout())
view->setUseFixedLayout(false);
view->layout();
}
/*!
\fn bool QWebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, QWebPage::NavigationType type)
This function is called whenever WebKit requests to navigate \a frame to the resource specified by \a request by means of
the specified navigation type \a type.
If \a frame is a null pointer then navigation to a new window is requested. If the request is
accepted createWindow() will be called.
The default implementation interprets the page's linkDelegationPolicy and emits linkClicked accordingly or returns true
to let QWebPage handle the navigation itself.
\sa createWindow()
*/
bool QWebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, QWebPage::NavigationType type)
{
Q_UNUSED(frame)
if (type == NavigationTypeLinkClicked) {
switch (d->linkPolicy) {
case DontDelegateLinks:
return true;
case DelegateExternalLinks:
if (WebCore::SchemeRegistry::shouldTreatURLSchemeAsLocal(request.url().scheme()))
return true;
emit linkClicked(request.url());
return false;
case DelegateAllLinks:
emit linkClicked(request.url());
return false;
}
}
return true;
}
/*!
\property QWebPage::selectedText
\brief the text currently selected
By default, this property contains an empty string.
\sa selectionChanged()
*/
QString QWebPage::selectedText() const
{
d->createMainFrame();
return d->page->focusController()->focusedOrMainFrame()->editor()->selectedText();
}
#ifndef QT_NO_ACTION
/*!
Returns a QAction for the specified WebAction \a action.
The action is owned by the QWebPage but you can customize the look by
changing its properties.
QWebPage also takes care of implementing the action, so that upon
triggering the corresponding action is performed on the page.
\sa triggerAction()
*/
QAction *QWebPage::action(WebAction action) const
{
if (action == QWebPage::NoWebAction) return 0;
if (d->actions[action])
return d->actions[action];
QString text;
QIcon icon;
QStyle *style = d->client ? d->client->style() : qApp->style();
bool checkable = false;
switch (action) {
case OpenLink:
text = contextMenuItemTagOpenLink();
break;
case OpenLinkInNewWindow:
text = contextMenuItemTagOpenLinkInNewWindow();
break;
case OpenFrameInNewWindow:
text = contextMenuItemTagOpenFrameInNewWindow();
break;
case DownloadLinkToDisk:
text = contextMenuItemTagDownloadLinkToDisk();
break;
case CopyLinkToClipboard:
text = contextMenuItemTagCopyLinkToClipboard();
break;
case OpenImageInNewWindow:
text = contextMenuItemTagOpenImageInNewWindow();
break;
case DownloadImageToDisk:
text = contextMenuItemTagDownloadImageToDisk();
break;
case CopyImageToClipboard:
text = contextMenuItemTagCopyImageToClipboard();
break;
case Back:
text = contextMenuItemTagGoBack();
icon = style->standardIcon(QStyle::SP_ArrowBack);
break;
case Forward:
text = contextMenuItemTagGoForward();
icon = style->standardIcon(QStyle::SP_ArrowForward);
break;
case Stop:
text = contextMenuItemTagStop();
icon = style->standardIcon(QStyle::SP_BrowserStop);
break;
case Reload:
text = contextMenuItemTagReload();
icon = style->standardIcon(QStyle::SP_BrowserReload);
break;
case Cut:
text = contextMenuItemTagCut();
break;
case Copy:
text = contextMenuItemTagCopy();
break;
case Paste:
text = contextMenuItemTagPaste();
break;
#ifndef QT_NO_UNDOSTACK
case Undo: {
QAction *a = undoStack()->createUndoAction(d->q);
d->actions[action] = a;
return a;
}
case Redo: {
QAction *a = undoStack()->createRedoAction(d->q);
d->actions[action] = a;
return a;
}
#endif // QT_NO_UNDOSTACK
case MoveToNextChar:
text = tr("Move the cursor to the next character");
break;
case MoveToPreviousChar:
text = tr("Move the cursor to the previous character");
break;
case MoveToNextWord:
text = tr("Move the cursor to the next word");
break;
case MoveToPreviousWord:
text = tr("Move the cursor to the previous word");
break;
case MoveToNextLine:
text = tr("Move the cursor to the next line");
break;
case MoveToPreviousLine:
text = tr("Move the cursor to the previous line");
break;
case MoveToStartOfLine:
text = tr("Move the cursor to the start of the line");
break;
case MoveToEndOfLine:
text = tr("Move the cursor to the end of the line");
break;
case MoveToStartOfBlock:
text = tr("Move the cursor to the start of the block");
break;
case MoveToEndOfBlock:
text = tr("Move the cursor to the end of the block");
break;
case MoveToStartOfDocument:
text = tr("Move the cursor to the start of the document");
break;
case MoveToEndOfDocument:
text = tr("Move the cursor to the end of the document");
break;
case SelectAll:
text = tr("Select all");
break;
case SelectNextChar:
text = tr("Select to the next character");
break;
case SelectPreviousChar:
text = tr("Select to the previous character");
break;
case SelectNextWord:
text = tr("Select to the next word");
break;
case SelectPreviousWord:
text = tr("Select to the previous word");
break;
case SelectNextLine:
text = tr("Select to the next line");
break;
case SelectPreviousLine:
text = tr("Select to the previous line");
break;
case SelectStartOfLine:
text = tr("Select to the start of the line");
break;
case SelectEndOfLine:
text = tr("Select to the end of the line");
break;
case SelectStartOfBlock:
text = tr("Select to the start of the block");
break;
case SelectEndOfBlock:
text = tr("Select to the end of the block");
break;
case SelectStartOfDocument:
text = tr("Select to the start of the document");
break;
case SelectEndOfDocument:
text = tr("Select to the end of the document");
break;
case DeleteStartOfWord:
text = tr("Delete to the start of the word");
break;
case DeleteEndOfWord:
text = tr("Delete to the end of the word");
break;
case SetTextDirectionDefault:
text = contextMenuItemTagDefaultDirection();
break;
case SetTextDirectionLeftToRight:
text = contextMenuItemTagLeftToRight();
checkable = true;
break;
case SetTextDirectionRightToLeft:
text = contextMenuItemTagRightToLeft();
checkable = true;
break;
case ToggleBold:
text = contextMenuItemTagBold();
checkable = true;
break;
case ToggleItalic:
text = contextMenuItemTagItalic();
checkable = true;
break;
case ToggleUnderline:
text = contextMenuItemTagUnderline();
checkable = true;
break;
case InspectElement:
text = contextMenuItemTagInspectElement();
break;
case InsertParagraphSeparator:
text = tr("Insert a new paragraph");
break;
case InsertLineSeparator:
text = tr("Insert a new line");
break;
case PasteAndMatchStyle:
text = tr("Paste and Match Style");
break;
case RemoveFormat:
text = tr("Remove formatting");
break;
case ToggleStrikethrough:
text = tr("Strikethrough");
checkable = true;
break;
case ToggleSubscript:
text = tr("Subscript");
checkable = true;
break;
case ToggleSuperscript:
text = tr("Superscript");
checkable = true;
break;
case InsertUnorderedList:
text = tr("Insert Bulleted List");
checkable = true;
break;
case InsertOrderedList:
text = tr("Insert Numbered List");
checkable = true;
break;
case Indent:
text = tr("Indent");
break;
case Outdent:
text = tr("Outdent");
break;
case AlignCenter:
text = tr("Center");
break;
case AlignJustified:
text = tr("Justify");
break;
case AlignLeft:
text = tr("Align Left");
break;
case AlignRight:
text = tr("Align Right");
break;
case NoWebAction:
return 0;
}
if (text.isEmpty())
return 0;
QAction *a = new QAction(d->q);
a->setText(text);
a->setData(action);
a->setCheckable(checkable);
a->setIcon(icon);
connect(a, SIGNAL(triggered(bool)),
this, SLOT(_q_webActionTriggered(bool)));
d->actions[action] = a;
d->updateAction(action);
return a;
}
#endif // QT_NO_ACTION
/*!
\property QWebPage::modified
\brief whether the page contains unsubmitted form data, or the contents have been changed.
By default, this property is false.
\sa contentsChanged(), contentEditable, undoStack()
*/
bool QWebPage::isModified() const
{
#ifdef QT_NO_UNDOSTACK
return false;
#else
if (!d->undoStack)
return false;
return d->undoStack->canUndo();
#endif // QT_NO_UNDOSTACK
}
#ifndef QT_NO_UNDOSTACK
/*!
Returns a pointer to the undo stack used for editable content.
\sa modified
*/
QUndoStack *QWebPage::undoStack() const
{
if (!d->undoStack)
d->undoStack = new QUndoStack(const_cast<QWebPage *>(this));
return d->undoStack;
}
#endif // QT_NO_UNDOSTACK
/*! \reimp
*/
bool QWebPage::event(QEvent *ev)
{
switch (ev->type()) {
case QEvent::Timer:
d->timerEvent(static_cast<QTimerEvent*>(ev));
break;
case QEvent::MouseMove:
d->mouseMoveEvent(static_cast<QMouseEvent*>(ev));
break;
case QEvent::GraphicsSceneMouseMove:
d->mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent*>(ev));
break;
case QEvent::MouseButtonPress:
d->mousePressEvent(static_cast<QMouseEvent*>(ev));
break;
case QEvent::GraphicsSceneMousePress:
d->mousePressEvent(static_cast<QGraphicsSceneMouseEvent*>(ev));
break;
case QEvent::MouseButtonDblClick:
d->mouseDoubleClickEvent(static_cast<QMouseEvent*>(ev));
break;
case QEvent::GraphicsSceneMouseDoubleClick:
d->mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent*>(ev));
break;
case QEvent::MouseButtonRelease:
d->mouseReleaseEvent(static_cast<QMouseEvent*>(ev));
break;
case QEvent::GraphicsSceneMouseRelease:
d->mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent*>(ev));
break;
#ifndef QT_NO_CONTEXTMENU
case QEvent::ContextMenu:
d->contextMenuEvent(static_cast<QContextMenuEvent*>(ev)->globalPos());
break;
case QEvent::GraphicsSceneContextMenu:
d->contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent*>(ev)->screenPos());
break;
#endif
#ifndef QT_NO_WHEELEVENT
case QEvent::Wheel:
d->wheelEvent(static_cast<QWheelEvent*>(ev));
break;
case QEvent::GraphicsSceneWheel:
d->wheelEvent(static_cast<QGraphicsSceneWheelEvent*>(ev));
break;
#endif
case QEvent::KeyPress:
d->keyPressEvent(static_cast<QKeyEvent*>(ev));
break;
case QEvent::KeyRelease:
d->keyReleaseEvent(static_cast<QKeyEvent*>(ev));
break;
case QEvent::FocusIn:
d->focusInEvent(static_cast<QFocusEvent*>(ev));
break;
case QEvent::FocusOut:
d->focusOutEvent(static_cast<QFocusEvent*>(ev));
break;
#ifndef QT_NO_DRAGANDDROP
case QEvent::DragEnter:
d->dragEnterEvent(static_cast<QDragEnterEvent*>(ev));
break;
case QEvent::GraphicsSceneDragEnter:
d->dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(ev));
break;
case QEvent::DragLeave:
d->dragLeaveEvent(static_cast<QDragLeaveEvent*>(ev));
break;
case QEvent::GraphicsSceneDragLeave:
d->dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(ev));
break;
case QEvent::DragMove:
d->dragMoveEvent(static_cast<QDragMoveEvent*>(ev));
break;
case QEvent::GraphicsSceneDragMove:
d->dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(ev));
break;
case QEvent::Drop:
d->dropEvent(static_cast<QDropEvent*>(ev));
break;
case QEvent::GraphicsSceneDrop:
d->dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(ev));
break;
#endif
case QEvent::InputMethod:
d->inputMethodEvent(static_cast<QInputMethodEvent*>(ev));
case QEvent::ShortcutOverride:
d->shortcutOverrideEvent(static_cast<QKeyEvent*>(ev));
break;
case QEvent::Leave:
d->leaveEvent(ev);
break;
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd:
// Return whether the default action was cancelled in the JS event handler
return d->touchEvent(static_cast<QTouchEvent*>(ev));
#endif
#ifndef QT_NO_PROPERTIES
case QEvent::DynamicPropertyChange:
d->dynamicPropertyChangeEvent(static_cast<QDynamicPropertyChangeEvent*>(ev));
break;
#endif
default:
return QObject::event(ev);
}
return true;
}
/*!
Similar to QWidget::focusNextPrevChild() it focuses the next focusable web element
if \a next is true; otherwise the previous element is focused.
Returns true if it can find a new focusable element, or false if it can't.
*/
bool QWebPage::focusNextPrevChild(bool next)
{
QKeyEvent ev(QEvent::KeyPress, Qt::Key_Tab, Qt::KeyboardModifiers(next ? Qt::NoModifier : Qt::ShiftModifier));
d->keyPressEvent(&ev);
bool hasFocusedNode = false;
Frame *frame = d->page->focusController()->focusedFrame();
if (frame) {
Document *document = frame->document();
hasFocusedNode = document && document->focusedNode();
}
//qDebug() << "focusNextPrevChild(" << next << ") =" << ev.isAccepted() << "focusedNode?" << hasFocusedNode;
return hasFocusedNode;
}
/*!
\property QWebPage::contentEditable
\brief whether the content in this QWebPage is editable or not
\since 4.5
If this property is enabled the contents of the page can be edited by the user through a visible
cursor. If disabled (the default) only HTML elements in the web page with their
\c{contenteditable} attribute set are editable.
\sa modified, contentsChanged(), WebAction
*/
void QWebPage::setContentEditable(bool editable)
{
if (d->editable != editable) {
d->editable = editable;
d->page->setTabKeyCyclesThroughElements(!editable);
if (d->mainFrame) {
WebCore::Frame* frame = d->mainFrame->d->frame;
if (editable) {
frame->editor()->applyEditingStyleToBodyElement();
// FIXME: mac port calls this if there is no selectedDOMRange
//frame->setSelectionFromNone();
}
}
d->updateEditorActions();
}
}
bool QWebPage::isContentEditable() const
{
return d->editable;
}
/*!
\property QWebPage::forwardUnsupportedContent
\brief whether QWebPage should forward unsupported content
If enabled, the unsupportedContent() signal is emitted with a network reply that
can be used to read the content.
If disabled, the download of such content is aborted immediately.
By default unsupported content is not forwarded.
*/
void QWebPage::setForwardUnsupportedContent(bool forward)
{
d->forwardUnsupportedContent = forward;
}
bool QWebPage::forwardUnsupportedContent() const
{
return d->forwardUnsupportedContent;
}
/*!
\property QWebPage::linkDelegationPolicy
\brief how QWebPage should delegate the handling of links through the
linkClicked() signal
The default is to delegate no links.
*/
void QWebPage::setLinkDelegationPolicy(LinkDelegationPolicy policy)
{
d->linkPolicy = policy;
}
QWebPage::LinkDelegationPolicy QWebPage::linkDelegationPolicy() const
{
return d->linkPolicy;
}
#ifndef QT_NO_CONTEXTMENU
/*!
Filters the context menu event, \a event, through handlers for scrollbars and
custom event handlers in the web page. Returns true if the event was handled;
otherwise false.
A web page may swallow a context menu event through a custom event handler, allowing for context
menus to be implemented in HTML/JavaScript. This is used by \l{http://maps.google.com/}{Google
Maps}, for example.
*/
bool QWebPage::swallowContextMenuEvent(QContextMenuEvent *event)
{
d->page->contextMenuController()->clearContextMenu();
if (QWebFrame* webFrame = frameAt(event->pos())) {
Frame* frame = QWebFramePrivate::core(webFrame);
if (Scrollbar* scrollbar = frame->view()->scrollbarAtPoint(PlatformMouseEvent(event, 1).pos()))
return scrollbar->contextMenu(PlatformMouseEvent(event, 1));
}
WebCore::Frame* focusedFrame = d->page->focusController()->focusedOrMainFrame();
focusedFrame->eventHandler()->sendContextMenuEvent(PlatformMouseEvent(event, 1));
ContextMenu *menu = d->page->contextMenuController()->contextMenu();
// If the website defines its own handler then sendContextMenuEvent takes care of
// calling/showing it and the context menu pointer will be zero. This is the case
// on maps.google.com for example.
return !menu;
}
#endif // QT_NO_CONTEXTMENU
/*!
Updates the page's actions depending on the position \a pos. For example if \a pos is over an image
element the CopyImageToClipboard action is enabled.
*/
void QWebPage::updatePositionDependentActions(const QPoint &pos)
{
#ifndef QT_NO_ACTION
// First we disable all actions, but keep track of which ones were originally enabled.
QBitArray originallyEnabledWebActions(QWebPage::WebActionCount);
for (int i = ContextMenuItemTagNoAction; i < ContextMenuItemBaseApplicationTag; ++i) {
QWebPage::WebAction action = webActionForContextMenuAction(WebCore::ContextMenuAction(i));
if (QAction *a = this->action(action)) {
originallyEnabledWebActions.setBit(action, a->isEnabled());
a->setEnabled(false);
}
}
#endif // QT_NO_ACTION
d->createMainFrame();
WebCore::Frame* focusedFrame = d->page->focusController()->focusedOrMainFrame();
HitTestResult result = focusedFrame->eventHandler()->hitTestResultAtPoint(focusedFrame->view()->windowToContents(pos), /*allowShadowContent*/ false);
if (result.scrollbar())
d->hitTestResult = QWebHitTestResult();
else
d->hitTestResult = QWebHitTestResult(new QWebHitTestResultPrivate(result));
WebCore::ContextMenu menu(result);
menu.populate();
#if ENABLE(INSPECTOR)
if (d->page->inspectorController()->enabled())
menu.addInspectElementItem();
#endif
QBitArray visitedWebActions(QWebPage::WebActionCount);
#ifndef QT_NO_CONTEXTMENU
delete d->currentContextMenu;
// Then we let createContextMenu() enable the actions that are put into the menu
d->currentContextMenu = d->createContextMenu(&menu, menu.platformDescription(), &visitedWebActions);
#endif // QT_NO_CONTEXTMENU
#ifndef QT_NO_ACTION
// Finally, we restore the original enablement for the actions that were not put into the menu.
originallyEnabledWebActions &= ~visitedWebActions; // Mask out visited actions (they're part of the menu)
for (int i = 0; i < QWebPage::WebActionCount; ++i) {
if (originallyEnabledWebActions.at(i)) {
if (QAction *a = this->action(QWebPage::WebAction(i)))
a->setEnabled(true);
}
}
#endif // QT_NO_ACTION
// This whole process ensures that any actions put into to the context menu has the right
// enablement, while also keeping the correct enablement for actions that were left out of
// the menu.
}
/*!
\enum QWebPage::Extension
This enum describes the types of extensions that the page can support. Before using these extensions, you
should verify that the extension is supported by calling supportsExtension().
\value ChooseMultipleFilesExtension Whether the web page supports multiple file selection.
This extension is invoked when the web content requests one or more file names, for example
as a result of the user clicking on a "file upload" button in a HTML form where multiple
file selection is allowed.
\value ErrorPageExtension Whether the web page can provide an error page when loading fails.
(introduced in Qt 4.6)
\sa ChooseMultipleFilesExtensionOption, ChooseMultipleFilesExtensionReturn, ErrorPageExtensionOption, ErrorPageExtensionReturn
*/
/*!
\enum QWebPage::ErrorDomain
\since 4.6
This enum describes the domain of an ErrorPageExtensionOption object (i.e. the layer in which the error occurred).
\value QtNetwork The error occurred in the QtNetwork layer; the error code is of type QNetworkReply::NetworkError.
\value Http The error occurred in the HTTP layer; the error code is a HTTP status code (see QNetworkRequest::HttpStatusCodeAttribute).
\value WebKit The error is an internal WebKit error.
*/
/*!
\class QWebPage::ExtensionOption
\since 4.4
\brief The ExtensionOption class provides an extended input argument to QWebPage's extension support.
\inmodule QtWebKit
\sa QWebPage::extension() QWebPage::ExtensionReturn
*/
/*!
\class QWebPage::ExtensionReturn
\since 4.4
\brief The ExtensionReturn class provides an output result from a QWebPage's extension.
\inmodule QtWebKit
\sa QWebPage::extension() QWebPage::ExtensionOption
*/
/*!
\class QWebPage::ErrorPageExtensionOption
\since 4.6
\brief The ErrorPageExtensionOption class describes the option
for the error page extension.
\inmodule QtWebKit
The ErrorPageExtensionOption class holds the \a url for which an error occurred as well as
the associated \a frame.
The error itself is reported by an error \a domain, the \a error code as well as \a errorString.
\sa QWebPage::extension() QWebPage::ErrorPageExtensionReturn
*/
/*!
\variable QWebPage::ErrorPageExtensionOption::url
\brief the url for which an error occurred
*/
/*!
\variable QWebPage::ErrorPageExtensionOption::frame
\brief the frame associated with the error
*/
/*!
\variable QWebPage::ErrorPageExtensionOption::domain
\brief the domain that reported the error
*/
/*!
\variable QWebPage::ErrorPageExtensionOption::error
\brief the error code. Interpretation of the value depends on the \a domain
\sa QWebPage::ErrorDomain
*/
/*!
\variable QWebPage::ErrorPageExtensionOption::errorString
\brief a string that describes the error
*/
/*!
\class QWebPage::ErrorPageExtensionReturn
\since 4.6
\brief The ErrorPageExtensionReturn describes the error page, which will be shown for the
frame for which the error occured.
\inmodule QtWebKit
The ErrorPageExtensionReturn class holds the data needed for creating an error page. Some are
optional such as \a contentType, which defaults to "text/html", as well as the \a encoding, which
is assumed to be UTF-8 if not indicated otherwise.
The error page is stored in the \a content byte array, as HTML content. In order to convert a
QString to a byte array, the QString::toUtf8() method can be used.
External objects such as stylesheets or images referenced in the HTML are located relative to
\a baseUrl.
\sa QWebPage::extension() QWebPage::ErrorPageExtensionOption, QString::toUtf8()
*/
/*!
\fn QWebPage::ErrorPageExtensionReturn::ErrorPageExtensionReturn()
Constructs a new error page object.
*/
/*!
\variable QWebPage::ErrorPageExtensionReturn::contentType
\brief the error page's content type
*/
/*!
\variable QWebPage::ErrorPageExtensionReturn::encoding
\brief the error page encoding
*/
/*!
\variable QWebPage::ErrorPageExtensionReturn::baseUrl
\brief the base url
External objects such as stylesheets or images referenced in the HTML are located relative to this url.
*/
/*!
\variable QWebPage::ErrorPageExtensionReturn::content
\brief the HTML content of the error page
*/
/*!
\class QWebPage::ChooseMultipleFilesExtensionOption
\since 4.5
\brief The ChooseMultipleFilesExtensionOption class describes the option
for the multiple files selection extension.
\inmodule QtWebKit
The ChooseMultipleFilesExtensionOption class holds the frame originating the request
and the suggested filenames which might be provided.
\sa QWebPage::extension() QWebPage::chooseFile(), QWebPage::ChooseMultipleFilesExtensionReturn
*/
/*!
\variable QWebPage::ChooseMultipleFilesExtensionOption::parentFrame
\brief The frame in which the request originated
*/
/*!
\variable QWebPage::ChooseMultipleFilesExtensionOption::suggestedFileNames
\brief The suggested filenames
*/
/*!
\variable QWebPage::ChooseMultipleFilesExtensionReturn::fileNames
\brief The selected filenames
*/
/*!
\class QWebPage::ChooseMultipleFilesExtensionReturn
\since 4.5
\brief The ChooseMultipleFilesExtensionReturn describes the return value
for the multiple files selection extension.
\inmodule QtWebKit
The ChooseMultipleFilesExtensionReturn class holds the filenames selected by the user
when the extension is invoked.
\sa QWebPage::extension() QWebPage::ChooseMultipleFilesExtensionOption
*/
/*!
This virtual function can be reimplemented in a QWebPage subclass to provide support for extensions. The \a option
argument is provided as input to the extension; the output results can be stored in \a output.
The behavior of this function is determined by \a extension. The \a option
and \a output values are typically casted to the corresponding types (for
example, ChooseMultipleFilesExtensionOption and
ChooseMultipleFilesExtensionReturn for ChooseMultipleFilesExtension).
You can call supportsExtension() to check if an extension is supported by the page.
Returns true if the extension was called successfully; otherwise returns false.
\sa supportsExtension(), Extension
*/
bool QWebPage::extension(Extension extension, const ExtensionOption *option, ExtensionReturn *output)
{
#ifndef QT_NO_FILEDIALOG
if (extension == ChooseMultipleFilesExtension) {
// FIXME: do not ignore suggestedFiles
QStringList suggestedFiles = static_cast<const ChooseMultipleFilesExtensionOption*>(option)->suggestedFileNames;
QWidget* parent = (d->client) ? d->client->ownerWidget() : 0;
QStringList names = QFileDialog::getOpenFileNames(parent, QString::null);
static_cast<ChooseMultipleFilesExtensionReturn*>(output)->fileNames = names;
return true;
}
#endif
return false;
}
/*!
This virtual function returns true if the web page supports \a extension; otherwise false is returned.
\sa extension()
*/
bool QWebPage::supportsExtension(Extension extension) const
{
#ifndef QT_NO_FILEDIALOG
return extension == ChooseMultipleFilesExtension;
#else
Q_UNUSED(extension);
return false;
#endif
}
/*!
Finds the specified string, \a subString, in the page, using the given \a options.
If the HighlightAllOccurrences flag is passed, the function will highlight all occurrences
that exist in the page. All subsequent calls will extend the highlight, rather than
replace it, with occurrences of the new string.
If the HighlightAllOccurrences flag is not passed, the function will select an occurrence
and all subsequent calls will replace the current occurrence with the next one.
To clear the selection, just pass an empty string.
Returns true if \a subString was found; otherwise returns false.
*/
bool QWebPage::findText(const QString &subString, FindFlags options)
{
::TextCaseSensitivity caseSensitivity = ::TextCaseInsensitive;
if (options & FindCaseSensitively)
caseSensitivity = ::TextCaseSensitive;
if (options & HighlightAllOccurrences) {
if (subString.isEmpty()) {
d->page->unmarkAllTextMatches();
return true;
} else
return d->page->markAllMatchesForText(subString, caseSensitivity, true, 0);
} else {
if (subString.isEmpty()) {
d->page->mainFrame()->selection()->clear();
Frame* frame = d->page->mainFrame()->tree()->firstChild();
while (frame) {
frame->selection()->clear();
frame = frame->tree()->traverseNextWithWrap(false);
}
}
::FindDirection direction = ::FindDirectionForward;
if (options & FindBackward)
direction = ::FindDirectionBackward;
const bool shouldWrap = options & FindWrapsAroundDocument;
return d->page->findString(subString, caseSensitivity, direction, shouldWrap);
}
}
/*!
Returns a pointer to the page's settings object.
\sa QWebSettings::globalSettings()
*/
QWebSettings *QWebPage::settings() const
{
return d->settings;
}
/*!
This function is called when the web content requests a file name, for example
as a result of the user clicking on a "file upload" button in a HTML form.
A suggested filename may be provided in \a suggestedFile. The frame originating the
request is provided as \a parentFrame.
\sa ChooseMultipleFilesExtension
*/
QString QWebPage::chooseFile(QWebFrame *parentFrame, const QString& suggestedFile)
{
Q_UNUSED(parentFrame)
#ifndef QT_NO_FILEDIALOG
QWidget* parent = (d->client) ? d->client->ownerWidget() : 0;
return QFileDialog::getOpenFileName(parent, QString::null, suggestedFile);
#else
return QString::null;
#endif
}
/*!
Sets the QNetworkAccessManager \a manager responsible for serving network requests for this
QWebPage.
\note It is currently not supported to change the network access manager after the
QWebPage has used it. The results of doing this are undefined.
\sa networkAccessManager()
*/
void QWebPage::setNetworkAccessManager(QNetworkAccessManager *manager)
{
if (manager == d->networkManager)
return;
if (d->networkManager && d->networkManager->parent() == this)
delete d->networkManager;
d->networkManager = manager;
}
/*!
Returns the QNetworkAccessManager that is responsible for serving network
requests for this QWebPage.
\sa setNetworkAccessManager()
*/
QNetworkAccessManager *QWebPage::networkAccessManager() const
{
if (!d->networkManager) {
QWebPage *that = const_cast<QWebPage *>(this);
that->d->networkManager = new QNetworkAccessManager(that);
}
return d->networkManager;
}
/*!
Sets the QWebPluginFactory \a factory responsible for creating plugins embedded into this
QWebPage.
Note: The plugin factory is only used if the QWebSettings::PluginsEnabled attribute is enabled.
\sa pluginFactory()
*/
void QWebPage::setPluginFactory(QWebPluginFactory *factory)
{
d->pluginFactory = factory;
}
/*!
Returns the QWebPluginFactory that is responsible for creating plugins embedded into
this QWebPage. If no plugin factory is installed a null pointer is returned.
\sa setPluginFactory()
*/
QWebPluginFactory *QWebPage::pluginFactory() const
{
return d->pluginFactory;
}
/*!
This function is called when a user agent for HTTP requests is needed. You can reimplement this
function to dynamically return different user agents for different URLs, based on the \a url parameter.
The default implementation returns the following value:
"Mozilla/5.0 (%Platform%; %Security%; %Subplatform%; %Locale%) AppleWebKit/%WebKitVersion% (KHTML, like Gecko) %AppVersion Safari/%WebKitVersion%"
On mobile platforms such as Symbian S60 and Maemo, "Mobile Safari" is used instead of "Safari".
In this string the following values are replaced at run-time:
\list
\o %Platform% and %Subplatform% are expanded to the windowing system and the operation system.
\o %Security% expands to U if SSL is enabled, otherwise N. SSL is enabled if QSslSocket::supportsSsl() returns true.
\o %Locale% is replaced with QLocale::name(). The locale is determined from the view of the QWebPage. If no view is set on the QWebPage,
then a default constructed QLocale is used instead.
\o %WebKitVersion% is the version of WebKit the application was compiled against.
\o %AppVersion% expands to QCoreApplication::applicationName()/QCoreApplication::applicationVersion() if they're set; otherwise defaulting to Qt and the current Qt version.
\endlist
*/
QString QWebPage::userAgentForUrl(const QUrl&) const
{
// splitting the string in three and user QStringBuilder is better than using QString::arg()
static QString firstPart;
static QString secondPart;
static QString thirdPart;
if (firstPart.isNull() || secondPart.isNull() || thirdPart.isNull()) {
QString firstPartTemp;
firstPartTemp.reserve(150);
firstPartTemp += QString::fromLatin1("Mozilla/5.0 ("
// Platform
#ifdef Q_WS_MAC
"Macintosh"
#elif defined Q_WS_QWS
"QtEmbedded"
#elif defined Q_WS_WIN
"Windows"
#elif defined Q_WS_X11
"X11"
#elif defined Q_OS_SYMBIAN
"Symbian"
#else
"Unknown"
#endif
);
#if defined Q_OS_SYMBIAN
QSysInfo::SymbianVersion symbianVersion = QSysInfo::symbianVersion();
switch (symbianVersion) {
case QSysInfo::SV_9_2:
firstPartTemp += QString::fromLatin1("OS/9.2");
break;
case QSysInfo::SV_9_3:
firstPartTemp += QString::fromLatin1("OS/9.3");
break;
case QSysInfo::SV_9_4:
firstPartTemp += QString::fromLatin1("OS/9.4");
break;
case QSysInfo::SV_SF_2:
firstPartTemp += QString::fromLatin1("/2");
break;
case QSysInfo::SV_SF_3:
firstPartTemp += QString::fromLatin1("/3");
break;
case QSysInfo::SV_SF_4:
firstPartTemp += QString::fromLatin1("/4");
default:
break;
}
#endif
firstPartTemp += QString::fromLatin1("; ");
// SSL support
#if !defined(QT_NO_OPENSSL)
// we could check QSslSocket::supportsSsl() here, but this makes
// OpenSSL, certificates etc being loaded in all cases were QWebPage
// is used. This loading is not needed for non-https.
firstPartTemp += QString::fromLatin1("U; ");
// this may lead to a false positive: We indicate SSL since it is
// compiled in even though supportsSsl() might return false
#else
firstPartTemp += QString::fromLatin1("N; ");
#endif
// Operating system
#ifdef Q_OS_AIX
firstPartTemp += QString::fromLatin1("AIX");
#elif defined Q_OS_WIN32
switch (QSysInfo::WindowsVersion) {
case QSysInfo::WV_32s:
firstPartTemp += QString::fromLatin1("Windows 3.1");
break;
case QSysInfo::WV_95:
firstPartTemp += QString::fromLatin1("Windows 95");
break;
case QSysInfo::WV_98:
firstPartTemp += QString::fromLatin1("Windows 98");
break;
case QSysInfo::WV_Me:
firstPartTemp += QString::fromLatin1("Windows 98; Win 9x 4.90");
break;
case QSysInfo::WV_NT:
firstPartTemp += QString::fromLatin1("WinNT4.0");
break;
case QSysInfo::WV_2000:
firstPartTemp += QString::fromLatin1("Windows NT 5.0");
break;
case QSysInfo::WV_XP:
firstPartTemp += QString::fromLatin1("Windows NT 5.1");
break;
case QSysInfo::WV_2003:
firstPartTemp += QString::fromLatin1("Windows NT 5.2");
break;
case QSysInfo::WV_VISTA:
firstPartTemp += QString::fromLatin1("Windows NT 6.0");
break;
case QSysInfo::WV_WINDOWS7:
firstPartTemp += QString::fromLatin1("Windows NT 6.1");
break;
case QSysInfo::WV_CE:
firstPartTemp += QString::fromLatin1("Windows CE");
break;
case QSysInfo::WV_CENET:
firstPartTemp += QString::fromLatin1("Windows CE .NET");
break;
case QSysInfo::WV_CE_5:
firstPartTemp += QString::fromLatin1("Windows CE 5.x");
break;
case QSysInfo::WV_CE_6:
firstPartTemp += QString::fromLatin1("Windows CE 6.x");
break;
}
#elif defined Q_OS_DARWIN
#ifdef __i386__ || __x86_64__
firstPartTemp += QString::fromLatin1("Intel Mac OS X");
#else
firstPartTemp += QString::fromLatin1("PPC Mac OS X");
#endif
#elif defined Q_OS_BSDI
firstPartTemp += QString::fromLatin1("BSD");
#elif defined Q_OS_BSD4
firstPartTemp += QString::fromLatin1("BSD Four");
#elif defined Q_OS_CYGWIN
firstPartTemp += QString::fromLatin1("Cygwin");
#elif defined Q_OS_DGUX
firstPartTemp += QString::fromLatin1("DG/UX");
#elif defined Q_OS_DYNIX
firstPartTemp += QString::fromLatin1("DYNIX/ptx");
#elif defined Q_OS_FREEBSD
firstPartTemp += QString::fromLatin1("FreeBSD");
#elif defined Q_OS_HPUX
firstPartTemp += QString::fromLatin1("HP-UX");
#elif defined Q_OS_HURD
firstPartTemp += QString::fromLatin1("GNU Hurd");
#elif defined Q_OS_IRIX
firstPartTemp += QString::fromLatin1("SGI Irix");
#elif defined Q_OS_LINUX
#if defined(__x86_64__)
firstPartTemp += QString::fromLatin1("Linux x86_64");
#elif defined(__i386__)
firstPartTemp += QString::fromLatin1("Linux i686");
#else
firstPartTemp += QString::fromLatin1("Linux");
#endif
#elif defined Q_OS_LYNX
firstPartTemp += QString::fromLatin1("LynxOS");
#elif defined Q_OS_NETBSD
firstPartTemp += QString::fromLatin1("NetBSD");
#elif defined Q_OS_OS2
firstPartTemp += QString::fromLatin1("OS/2");
#elif defined Q_OS_OPENBSD
firstPartTemp += QString::fromLatin1("OpenBSD");
#elif defined Q_OS_OS2EMX
firstPartTemp += QString::fromLatin1("OS/2");
#elif defined Q_OS_OSF
firstPartTemp += QString::fromLatin1("HP Tru64 UNIX");
#elif defined Q_OS_QNX6
firstPartTemp += QString::fromLatin1("QNX RTP Six");
#elif defined Q_OS_QNX
firstPartTemp += QString::fromLatin1("QNX");
#elif defined Q_OS_RELIANT
firstPartTemp += QString::fromLatin1("Reliant UNIX");
#elif defined Q_OS_SCO
firstPartTemp += QString::fromLatin1("SCO OpenServer");
#elif defined Q_OS_SOLARIS
firstPartTemp += QString::fromLatin1("Sun Solaris");
#elif defined Q_OS_ULTRIX
firstPartTemp += QString::fromLatin1("DEC Ultrix");
#elif defined Q_OS_SYMBIAN
firstPartTemp += QLatin1Char(' ');
QSysInfo::S60Version s60Version = QSysInfo::s60Version();
switch (s60Version) {
case QSysInfo::SV_S60_3_1:
firstPartTemp += QString::fromLatin1("Series60/3.1");
break;
case QSysInfo::SV_S60_3_2:
firstPartTemp += QString::fromLatin1("Series60/3.2");
break;
case QSysInfo::SV_S60_5_0:
firstPartTemp += QString::fromLatin1("Series60/5.0");
break;
default:
break;
}
#elif defined Q_OS_UNIX
firstPartTemp += QString::fromLatin1("UNIX BSD/SYSV system");
#elif defined Q_OS_UNIXWARE
firstPartTemp += QString::fromLatin1("UnixWare Seven, Open UNIX Eight");
#else
firstPartTemp += QString::fromLatin1("Unknown");
#endif
// language is the split
firstPartTemp += QString::fromLatin1("; ");
firstPartTemp.squeeze();
firstPart = firstPartTemp;
QString secondPartTemp;
secondPartTemp.reserve(150);
secondPartTemp += QString::fromLatin1(") ");
// webkit/qt version
secondPartTemp += QString::fromLatin1("AppleWebKit/");
secondPartTemp += qWebKitVersion();
secondPartTemp += QString::fromLatin1(" (KHTML, like Gecko) ");
// Application name split the third part
secondPartTemp.squeeze();
secondPart = secondPartTemp;
QString thirdPartTemp;
thirdPartTemp.reserve(150);
#if defined(Q_OS_SYMBIAN) || defined(Q_WS_MAEMO_5)
thirdPartTemp += QLatin1String(" Mobile Safari/");
#else
thirdPartTemp += QLatin1String(" Safari/");
#endif
thirdPartTemp += qWebKitVersion();
thirdPartTemp.squeeze();
thirdPart = thirdPartTemp;
Q_ASSERT(!firstPart.isNull());
Q_ASSERT(!secondPart.isNull());
Q_ASSERT(!thirdPart.isNull());
}
// Language
QString languageName;
if (d->client && d->client->ownerWidget())
languageName = d->client->ownerWidget()->locale().name();
else
languageName = QLocale().name();
languageName.replace(QLatin1Char('_'), QLatin1Char('-'));
// Application name/version
QString appName = QCoreApplication::applicationName();
if (!appName.isEmpty()) {
QString appVer = QCoreApplication::applicationVersion();
if (!appVer.isEmpty())
appName.append(QLatin1Char('/') + appVer);
} else {
// Qt version
appName = QString::fromLatin1("Qt/") + QString::fromLatin1(qVersion());
}
return firstPart + languageName + secondPart + appName + thirdPart;
}
void QWebPagePrivate::_q_onLoadProgressChanged(int)
{
m_totalBytes = page->progress()->totalPageAndResourceBytesToLoad();
m_bytesReceived = page->progress()->totalBytesReceived();
}
/*!
Returns the total number of bytes that were received from the network to render the current page,
including extra content such as embedded images.
\sa bytesReceived()
*/
quint64 QWebPage::totalBytes() const
{
return d->m_totalBytes;
}
/*!
Returns the number of bytes that were received from the network to render the current page.
\sa totalBytes(), loadProgress()
*/
quint64 QWebPage::bytesReceived() const
{
return d->m_bytesReceived;
}
/*!
\since 4.7
\fn void QWebPage::viewportChangeRequested()
Page authors can provide the supplied values by using the viewport meta tag. More information
about this can be found at \l{http://developer.apple.com/safari/library/documentation/appleapplications/reference/safariwebcontent/usingtheviewport/usingtheviewport.html}{Safari Reference Library: Using the Viewport Meta Tag}.
\sa QWebPage::ViewportConfiguration, setPreferredContentsSize(), QGraphicsWebView::setScale()
*/
/*!
\fn void QWebPage::loadStarted()
This signal is emitted when a new load of the page is started.
\sa loadFinished()
*/
/*!
\fn void QWebPage::loadProgress(int progress)
This signal is emitted when the global progress status changes.
The current value is provided by \a progress and scales from 0 to 100,
which is the default range of QProgressBar.
It accumulates changes from all the child frames.
\sa bytesReceived()
*/
/*!
\fn void QWebPage::loadFinished(bool ok)
This signal is emitted when a load of the page is finished.
\a ok will indicate whether the load was successful or any error occurred.
\sa loadStarted(), ErrorPageExtension
*/
/*!
\fn void QWebPage::linkHovered(const QString &link, const QString &title, const QString &textContent)
This signal is emitted when the mouse hovers over a link.
\a link contains the link url.
\a title is the link element's title, if it is specified in the markup.
\a textContent provides text within the link element, e.g., text inside an HTML anchor tag.
When the mouse leaves the link element the signal is emitted with empty parameters.
\sa linkClicked()
*/
/*!
\fn void QWebPage::statusBarMessage(const QString& text)
This signal is emitted when the statusbar \a text is changed by the page.
*/
/*!
\fn void QWebPage::frameCreated(QWebFrame *frame)
This signal is emitted whenever the page creates a new \a frame.
\sa currentFrame()
*/
/*!
\fn void QWebPage::selectionChanged()
This signal is emitted whenever the selection changes, either interactively
or programmatically (e.g. by calling triggerAction() with a selection action).
\sa selectedText()
*/
/*!
\fn void QWebPage::contentsChanged()
\since 4.5
This signal is emitted whenever the text in form elements changes
as well as other editable content.
\sa contentEditable, modified, QWebFrame::toHtml(), QWebFrame::toPlainText()
*/
/*!
\fn void QWebPage::geometryChangeRequested(const QRect& geom)
This signal is emitted whenever the document wants to change the position and size of the
page to \a geom. This can happen for example through JavaScript.
*/
/*!
\fn void QWebPage::repaintRequested(const QRect& dirtyRect)
This signal is emitted whenever this QWebPage should be updated and no view was set.
\a dirtyRect contains the area that needs to be updated. To paint the QWebPage get
the mainFrame() and call the render(QPainter*, const QRegion&) method with the
\a dirtyRect as the second parameter.
\sa mainFrame()
\sa view()
*/
/*!
\fn void QWebPage::scrollRequested(int dx, int dy, const QRect& rectToScroll)
This signal is emitted whenever the content given by \a rectToScroll needs
to be scrolled \a dx and \a dy downwards and no view was set.
\sa view()
*/
/*!
\fn void QWebPage::windowCloseRequested()
This signal is emitted whenever the page requests the web browser window to be closed,
for example through the JavaScript \c{window.close()} call.
*/
/*!
\fn void QWebPage::printRequested(QWebFrame *frame)
This signal is emitted whenever the page requests the web browser to print \a frame,
for example through the JavaScript \c{window.print()} call.
\sa QWebFrame::print(), QPrintPreviewDialog
*/
/*!
\fn void QWebPage::unsupportedContent(QNetworkReply *reply)
This signal is emitted when WebKit cannot handle a link the user navigated to or a
web server's response includes a "Content-Disposition" header with the 'attachment'
directive. If "Content-Disposition" is present in \a reply, the web server is indicating
that the client should prompt the user to save the content regardless of content-type.
See RFC 2616 sections 19.5.1 for details about Content-Disposition.
At signal emission time the meta-data of the QNetworkReply \a reply is available.
\note This signal is only emitted if the forwardUnsupportedContent property is set to true.
\sa downloadRequested()
*/
/*!
\fn void QWebPage::downloadRequested(const QNetworkRequest &request)
This signal is emitted when the user decides to download a link. The url of
the link as well as additional meta-information is contained in \a request.
\sa unsupportedContent()
*/
/*!
\fn void QWebPage::microFocusChanged()
This signal is emitted when for example the position of the cursor in an editable form
element changes. It is used to inform input methods about the new on-screen position where
the user is able to enter text. This signal is usually connected to the
QWidget::updateMicroFocus() slot.
*/
/*!
\fn void QWebPage::linkClicked(const QUrl &url)
This signal is emitted whenever the user clicks on a link and the page's linkDelegationPolicy
property is set to delegate the link handling for the specified \a url.
By default no links are delegated and are handled by QWebPage instead.
\note This signal possibly won't be emitted for clicked links which use
JavaScript to trigger navigation.
\sa linkHovered()
*/
/*!
\fn void QWebPage::toolBarVisibilityChangeRequested(bool visible)
This signal is emitted whenever the visibility of the toolbar in a web browser
window that hosts QWebPage should be changed to \a visible.
*/
/*!
\fn void QWebPage::statusBarVisibilityChangeRequested(bool visible)
This signal is emitted whenever the visibility of the statusbar in a web browser
window that hosts QWebPage should be changed to \a visible.
*/
/*!
\fn void QWebPage::menuBarVisibilityChangeRequested(bool visible)
This signal is emitted whenever the visibility of the menubar in a web browser
window that hosts QWebPage should be changed to \a visible.
*/
/*!
\fn void QWebPage::databaseQuotaExceeded(QWebFrame* frame, QString databaseName);
\since 4.5
This signal is emitted whenever the web site shown in \a frame is asking to store data
to the database \a databaseName and the quota allocated to that web site is exceeded.
\sa QWebDatabase
*/
/*!
\since 4.5
\fn void QWebPage::saveFrameStateRequested(QWebFrame* frame, QWebHistoryItem* item);
This signal is emitted shortly before the history of navigated pages
in \a frame is changed, for example when navigating back in the history.
The provided QWebHistoryItem, \a item, holds the history entry of the frame before
the change.
A potential use-case for this signal is to store custom data in
the QWebHistoryItem associated to the frame, using QWebHistoryItem::setUserData().
*/
/*!
\since 4.5
\fn void QWebPage::restoreFrameStateRequested(QWebFrame* frame);
This signal is emitted when the load of \a frame is finished and the application may now update its state accordingly.
*/
/*!
\fn QWebPagePrivate* QWebPage::handle() const
\internal
*/
#include "moc_qwebpage.cpp"
| [
"[email protected]"
] | [
[
[
1,
3960
]
]
] |
cb2868bf534222bd20be7735188c230a5a149533 | ffb2c41127e4a47d59a44dfd2ce0c115a9a125af | /helpers/StatusLocks.h | 47385af745bc2f000e763a59bd1871e6b569e630 | [] | no_license | jcaesar/crctrl | b02e0c845e4820c6c7270e99119a19690c887542 | 4410461f0d8d360dfd065cb867e9a4f3e5276c21 | refs/heads/master | 2020-12-24T14:36:15.121574 | 2010-04-29T17:19:04 | 2013-05-29T14:04:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | h | #ifndef StatusLocksHpp
#define StatusLocksHpp
#include <pthread.h>
//Note: Ihateyouihateyouihateyou.
//I just can't figure out how to build it that it will allow what I want it to do, without allocating memory in LockStatus-Calls
//I should better implement the fast version. Collisions won't appear for my code anyway, so this is a lot slower than it could be.
class StatusLocks {
private:
pthread_mutex_t statuslock;
pthread_cond_t statuscond;
struct ReaderInfo {
pthread_t thread;
unsigned int count;
ReaderInfo * next;
} readerinfo;
unsigned int writercount;
pthread_t writer;
protected:
void StatusUnstable();
void StatusStable();
public:
void LockStatus();
void UnlockStatus();
StatusLocks();
~StatusLocks();
};
#endif | [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
950559d017716c4451464c96f8f4a1096d70c7c7 | dfc04887c24e0e7d31ca3a779cee13860baa8810 | /native/swtlibrary/SWTQtContainer_win32.cpp | 686d8f8655aac2464ca75fe3cf8da93ae27638f8 | [] | no_license | kevinmiles/qtwidgetsinswt | cdf48cb9bef4999faff7950179fc70d4395e0ec5 | b53ada927d77ed920de3dfa5493da18e2ce077f1 | refs/heads/master | 2021-01-10T08:23:15.194659 | 2010-10-29T21:39:01 | 2010-10-29T21:39:01 | 51,097,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,664 | cpp | /**
* Copyright (c) 2010 Symbian Foundation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the GNU Lesser General Public License
* which accompanies this distribution
*
* Initial Contributors:
* Symbian Foundation - initial contribution.
* Contributors:
* Description:
* Overview:
* Details:
* Platforms/Drives/Compatibility:
* Assumptions/Requirement/Pre-requisites:
* Failures and causes:
*/
#include "SWTQtContainer.h"
#include "../qtwinmigrate/QWinWidget"
#include <windows.h>
static QApplication* app;
class WindowsNativePanel: public INativePanel {
private:
QWinWidget *winWidget;
public:
WindowsNativePanel(HWND);
virtual QWidget* container();
virtual void resize(int x, int y, int w, int h);
virtual ~WindowsNativePanel();
};
INativePanel* create(int parentHandle) {
return new WindowsNativePanel(reinterpret_cast<HWND> (parentHandle));
}
void startQt() {
int argc = 0;
app = new QApplication(argc, 0);
}
void tearDownQt() {
delete app;
}
WindowsNativePanel::WindowsNativePanel(HWND parentWindow) {
winWidget = new QWinWidget(parentWindow);
}
void WindowsNativePanel::resize(int x, int y, int w, int h) {
HWND hWnd = winWidget->winId();
UINT flags = SWP_NOZORDER | SWP_DRAWFRAME | SWP_NOACTIVATE;
SetWindowPos(hWnd, (HWND) 0, x, 0, w, h, flags);
winWidget->move(x, 0);
winWidget->resize(w, h);
}
QWidget* WindowsNativePanel::container() {
return winWidget;
}
WindowsNativePanel::~WindowsNativePanel() {
}
| [
"your_email_address@localhost"
] | [
[
[
1,
66
]
]
] |
2ffcb889019e6d6be1e6c075ff1028e4df098479 | 8bf3d8714b3ed7b5663951aaf6d997ba41178d54 | /Window.cpp | 4bffa72dd4bd9783f1ed01f8f9d86a8d2df59f55 | [] | no_license | burnchar/cnb-data-parser | f71565bfab3e8de3600a553d6084a7ba0fde6059 | cf63d326eb265242c420e10d3e873d63eb131b94 | refs/heads/master | 2021-01-13T02:05:59.895672 | 2010-05-11T23:23:54 | 2010-05-11T23:23:54 | 35,288,490 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,905 | cpp | /*
Name : Window.cpp
Author : Charles N. Burns (charlesnburns|gmail|com / burnchar|isu|edu)
Date : August 2009
License : GPL3. See license.txt or www.gnu.org/licenses/gpl-3.0.txt
Requirements: Qt 4, data to parse, any spreadsheet program.
Notes : Tested only with Atmel hardware. Best viewed with tab width 4.
Description : This is the main class of the program. It dynamically creates
the GUI, responds to user input, and does all necessary
calculations, parsing, and file I/O.
*/
#include "Window.h"
//! Constructor for Window class. @see Window
Window::Window()
{
this->setWindowTitle("CNB Data Parser 1.0");
this->configFileURI = "config.xml";
this->maxComboItems = 10;
this->config = new Config();
this->createStatusBar();
this->createDataLayout();
this->createAdvFeaturesLayout();
this->createMainLayout();
this->updateColumnList();
this->mainLayoutCreateConnections();
this->importSettings();
this->setMaximumWidth(300);
this->setAcceptDrops(true);
}
//! Sets up and creates the status bar (the information panel at the bottom)
//! @see window()
void Window::createStatusBar()
{
statusBar = new QStatusBar(this);
statusBarMessage = new QLabel();
statusBarMessage->setText(defaultStatusMessage);
statusBar->addWidget(statusBarMessage, 100);
}
//! Finds the integer by which the row count must divide to stay within limits.
//! For example, if there are 200 rows, and the row limit is 50, returns 4
//! @returns That integer
//! @see infileNumberRows()
//! @see updateInfileRowsDisplay()
quint64 Window::infileRowLimitDivisor()
{
quint64 rowLimit = comboRowLimit->currentText().toULongLong();
quint64 rows = infileNumberRows();
quint64 divider = 1;
quint64 start;
if((rowLimit < rows) && (rows > 0) && (rowLimit > 0)) {
if(checkBoxWriteColNames->isChecked()) rows += 1;
start = rows / (rowLimit + 1);
for(divider = start; ((rows / divider) > rowLimit); divider += 1);
}
return divider;
}
//! Creates and configures main layout
//! @see mainLayoutAllocateWidgets()
//! @see mainLayoutConfigureWidgets()
//! @see mainLayoutAddWidgets()
void Window::createMainLayout()
{
mainLayout = new QGridLayout();
mainLayout->setColumnStretch(1, 2);
mainLayoutAllocateWidgets();
mainLayoutConfigureWidgets();
mainLayoutAddWidgets();
this->setLayout(mainLayout);
}
//! Allocates widgets for the main layout.
//! @see createMainLayout()
void Window::mainLayoutAllocateWidgets()
{
comboInfile = new QComboBox();
comboOutfile = new QComboBox();
comboRowLimit = new QComboBox();
spinColumns = new QSpinBox();
infileRowsDisplay = new QLabel();
buttonBrowseInput = new QPushButton(tr("Browse"));
buttonBrowseOutput = new QPushButton(tr("Browse"));
buttonProcessData = new QPushButton(tr("Process data"));
checkBoxOpenWhenDone = new QCheckBox(tr("Open output file when finished"));
}
//! Configures widgets for the main layout. Widgets must already be allocated.
//! @see createMainLayout()
void Window::mainLayoutConfigureWidgets()
{
QIcon iconExcel(":/embedded/icon_excel.png");
QIcon iconOocalc(":/embedded/icon_oocalc.png");
QIcon iconQuattro(":/embedded/icon_quattropro.png");
QIcon iconUnlimited(":/embedded/icon_unlimited.png");
spinColumns->setRange(1, 255);
comboOutfile->setEditable(true);
comboOutfile->setMaxCount(maxComboItems);
comboOutfile->setInsertPolicy(QComboBox::InsertAtTop);
comboInfile->setEditable(true);
comboInfile->setMaxCount(maxComboItems);
comboInfile->setInsertPolicy(QComboBox::InsertAtTop);
comboInfile->setMaximumWidth(300);
comboOutfile->setMaximumWidth(300);
comboRowLimit->setEditable(true);
comboRowLimit->setMaxCount(maxComboItems);
comboRowLimit->addItem(iconUnlimited, tr("No limit"));
comboRowLimit->addItem(iconOocalc, tr("65536 (OpenOffice, Excel)"));
comboRowLimit->addItem(iconExcel, tr("1048576 (Excel 2007+)"));
comboRowLimit->addItem(iconQuattro, tr("1000000 (Quattro Pro)"));
comboRowLimit->setCompleter(0);
comboRowLimit->insertSeparator(0);
comboRowLimitDefaultItemCount = 4;
}
//! Adds widgets to the appropriate grid coordinates of the main layout.
//! @see createMainLayout()
void Window::mainLayoutAddWidgets()
{
mainLayout->addWidget(new QLabel(tr("Data file:")), 0, 0);
mainLayout->addWidget(comboInfile, 0, 1, 1, 2);
mainLayout->addWidget(buttonBrowseInput, 0, 3);
mainLayout->addWidget(new QLabel(tr("Output file:")), 1, 0);
mainLayout->addWidget(comboOutfile, 1, 1, 1, 2);
mainLayout->addWidget(buttonBrowseOutput, 1, 3);
mainLayout->addWidget(checkBoxOpenWhenDone, 2, 1, 1, 2);
mainLayout->addWidget(new QLabel(tr("Limit rows:")), 3, 0);
mainLayout->addWidget(comboRowLimit, 3, 1, 1, 1);
mainLayout->addWidget(infileRowsDisplay, 3, 2, 1, 2);
mainLayout->addWidget(new QLabel(tr("Columns:")), 4, 0);
mainLayout->addWidget(spinColumns, 4, 1, 1, 1);
mainLayout->addWidget(scrollArea, 5, 0, 1, 4);
mainLayout->addLayout(advFeaturesLayout, 6, 0, 1, 4);
mainLayout->addWidget(buttonProcessData, 7, 0, 1, 4);
mainLayout->addWidget(statusBar, 8, 0, 1, 4);
}
//! Connects the signals of widgets in the main layout to the appropriate slots.
//! @see createMainLayout()
void Window::mainLayoutCreateConnections() const
{
connect(comboInfile, SIGNAL(editTextChanged(QString)), this,
SLOT(updateDisplay()));
connect(comboOutfile, SIGNAL(editTextChanged(QString)), this,
SLOT(updateDisplay()));
connect(spinColumns, SIGNAL(valueChanged(int)), this,
SLOT(updateColumnList()));
connect(spinColumns, SIGNAL(valueChanged(int)), this,
SLOT(updateDisplay()));
connect(buttonBrowseInput, SIGNAL(clicked()), this,
SLOT(openFileDialog()));
connect(buttonBrowseOutput, SIGNAL(clicked()), this,
SLOT(saveFileDialog()));
connect(buttonProcessData, SIGNAL(clicked()), this,
SLOT(dataToCsv()));
connect(comboRowLimit, SIGNAL(editTextChanged(const QString&)), this,
SLOT(filterLimitRowsName(const QString&)));
connect(comboRowLimit, SIGNAL(editTextChanged(const QString&)), this,
SLOT(updateDisplay()));
connect(statusBarMessage, SIGNAL(linkActivated(QString)), this,
SLOT(openSystemWebBrowser(QString)));
}
//! Allocates, configures, and adds widgets to the layout which shows columns.
//! @see Window()
void Window::createDataLayout()
{
dataLayout = new QGridLayout;
dataLayout->addWidget(new QLabel(tr("#")), 0, 0);
checkBoxWriteColNames = new QCheckBox("Column Name");
checkBoxWriteColNames->setChecked(true);
dataLayout->addWidget(checkBoxWriteColNames, 0, 1, 1, 1, Qt::AlignCenter);
dataLayout->addWidget(new QLabel(tr("# bytes")), 0, 2);
dataLayout->addWidget(new QLabel(tr("Count")), 0, 3);
dataLayout->setColumnStretch(1, 2);
dataLayout->setAlignment(Qt::AlignTop);
dataGroupBox = new QGroupBox();
dataGroupBox->setFocusPolicy(Qt::WheelFocus);
dataGroupBox->setLayout(dataLayout);
scrollArea = new QScrollArea;
scrollArea->setWidgetResizable(true);
scrollArea->setWidget(dataGroupBox);
connect(checkBoxWriteColNames, SIGNAL(toggled(bool)), this,
SLOT(updateDisplay()));
}
//! Allocates, configures, and adds widgets to the advanced features layout.
//! @see Window()
void Window::createAdvFeaturesLayout()
{
minVoltage = new QDoubleSpinBox();
maxVoltage = new QDoubleSpinBox();
checkBoxEndian = new QCheckBox("Swap byte order");
checkBoxEndian->setChecked(true);
advFeaturesLayout = new QHBoxLayout();
advFeaturesLayout->addWidget(
new QLabel(tr("Low voltage:")), 0, Qt::AlignRight);
advFeaturesLayout->addWidget(minVoltage, 0);
advFeaturesLayout->addWidget(
new QLabel(tr("High voltage:")), 0, Qt::AlignRight);
advFeaturesLayout->addWidget(maxVoltage);
advFeaturesLayout->addWidget(checkBoxEndian);
minVoltage->setValue(0.0);
maxVoltage->setValue(5.0);
minVoltage->setRange(-1000.0, 1000.0);
maxVoltage->setRange(-1000.0, 1000.0);
minVoltage->setSuffix("v");
maxVoltage->setSuffix("v");
minVoltage->setDecimals(3);
maxVoltage->setDecimals(3);
connect(minVoltage, SIGNAL(valueChanged(double)), this,
SLOT(minVoltageChanged(double)));
connect(maxVoltage, SIGNAL(valueChanged(double)), this,
SLOT(maxVoltageChanged(double)));
}
//! This slot changes the number of items displayed in the data layout.
//! @see mainLayoutCreateConnections()
void Window::updateColumnList()
{
static int oldCount; //! Remembers previous number of columns
int newCount = spinColumns->value();
for(; oldCount < newCount; ++oldCount) {
if(dataLayout->rowCount() -1 > oldCount)
dataRowSetVisible(oldCount, true);
else
dataRowCreate(oldCount);
}
while(oldCount > newCount) {
--oldCount;
dataRowSetVisible(newCount, false);
}
}
//! Changes the visibility of a row in the data layout.
//! @param index Index of the row of controls (0-based) to make show or hide.
//! @param visible Should this row be visible? True or false?
//! @see updateColumnList()
void Window::dataRowSetVisible(const int index, const bool visible)
{
dataLabel.at(index)->setVisible(visible);
dataComboName.at(index)->setVisible(visible);
dataSpinNumBytes.at(index)->setVisible(visible);
dataCheckBox.at(index)->setVisible(visible);
}
//! Creates and configures an entire row of widgets in the data layout.
//! @param index Index of the row (0-based) to create controls in
//! @see updateColumnList()
void Window::dataRowCreate(const int index)
{
dataLabel.append(new QLabel(QString::number(index + 1)));
dataComboName.append(new QComboBox());
dataComboName.at(index)->setEditable(true);
dataSpinNumBytes.append(new QSpinBox());
dataSpinNumBytes.at(index)->setRange(1, maxColumnBytes);
dataCheckBox.append(new QCheckBox());
dataLayout->addWidget(dataLabel.at(index));
dataLayout->addWidget(dataComboName.at(index));
dataLayout->addWidget(dataSpinNumBytes.at(index));
connect(dataSpinNumBytes.at(index), SIGNAL(valueChanged(int)),
this, SLOT(updateDisplay()));
dataLayout->addWidget(dataCheckBox.at(index));
connect(dataComboName.at(index),
SIGNAL(editTextChanged(const QString&)), this,
SLOT(filterColumnName(const QString&)));
}
//! Sets up the default file dialog box.
//! @see Window()
void Window::openFileDialog()
{
QString fileURI = QFileDialog::getOpenFileName(
this, tr("Open data file"), comboInfile->currentText(),
tr("All Files (*.*);;Data files (*.dat *.bin)"));
QFileInfo fInfo(fileURI);
if(fInfo.exists()) {
int dupeIndex = comboInfile->findText(
fileURI, Qt::MatchFixedString | Qt::MatchCaseSensitive);
if(dupeIndex >= 0) comboInfile->removeItem(dupeIndex);
comboInfile->insertItem(0, QDir::convertSeparators(fileURI));
comboInfile->setCurrentIndex(0);
}
}
//! Computes the sum of bytes in the columns of any one row of input data.
//! @returns the number of bytes
//! @see infileNumberRows()
//! @see dataToCsv()
int Window::rowDataSize()
{
int accumulator = 0, columns = spinColumns->value();
for(int index = 0; index < columns; ++index)
accumulator += dataSpinNumBytes.at(index)->value();
return accumulator;
}
//! Computes number of rows in input file based on its size and bytes per row.
//! @returns The number of rows
//! @see rowDataSize()
//! @see dataToCsv()
//! @see updateInfileRowsDisplay()
//! @see updateStatusBarFileStats()
//! @see infileRowLimitDivisor()
quint64 Window::infileNumberRows()
{
quint64 rows;
QFile infile(comboInfile->currentText().trimmed());
if(!infile.open(QIODevice::ReadOnly))
rows = 0;
else {
int rowSize = this->rowDataSize();
quint64 fileSize = infile.size();
rows = fileSize / rowSize;
if(fileSize % rowSize != 0) rows += 1; // Don't ignore partial rows
infile.close();
}
return rows;
}
//! Opens file dialog box to determine the file in which to save processed data
//! @see mainLayoutCreateConnections()
void Window::saveFileDialog()
{
QString fileURI = QFileDialog::getSaveFileName(
this, tr("Save as..."), comboOutfile->currentText(),
tr("Comma-separated values file (*.csv *.txt);; All files (*.* )"));
// If file is already in list, delete it and re-insert at the top.
int dupeIndex = comboOutfile->findText(
fileURI, Qt::MatchFixedString | Qt::MatchCaseSensitive);
if(dupeIndex >= 0) comboOutfile->removeItem(dupeIndex);
comboOutfile->insertItem(0, QDir::convertSeparators(fileURI));
comboOutfile->setCurrentIndex(0);
}
/*
000000000000AA80 Correct value
00000000000080AA Raw data before qbswap
AA80000000000000 After qbswap
000000000000AA80 Bit shifted 8 - bytecount * 8 bits.
*/
//! Opens both input and output files for processing.
//! @param infile Unassociated QFile object representing input file.
//! @param outfile Unassociated QFile object representing output file.
//! @returns True if there was an error opening either one, false otherwise.
//! @see dataToCsv()
bool Window::csvOpenFiles(QFile &infile, QFile &outfile)
{
bool errorState = false;
infile.setFileName(comboInfile->currentText());
if(!infile.open(QIODevice::ReadOnly)) {
statusBarMessage->setText(tr("Cannot open data file for reading."));
errorState = true;
}
else {
outfile.setFileName(comboOutfile->currentText());
if(!outfile.open(QIODevice::WriteOnly | QIODevice::Text)) {
statusBarMessage->setText(tr(
"Cannot open output file for writing."));
errorState = true;
}
else {
QFileInfo ifinfo(infile);
QFileInfo ofinfo(outfile);
if(ifinfo.canonicalFilePath() == ofinfo.canonicalFilePath()) {
statusBarMessage->setText(tr(
"Input and output files must not be the same file!"));
errorState = true;
}
}
}
return errorState;
}
//! Writes the first row of the output file -- the names of each column.
//! @param ts QTextStream object already associated with an output file
//! @returns True if column names were written, false otherwise
//! @see dataToCsv()
bool Window::csvWriteColumnNames(QTextStream &ts)
{
bool retval = false;
for(int index = 0; index < spinColumns->value(); ++index) {
if(dataComboName.at(index)->isHidden()) break;
else {
ts << dataComboName.at(index)->currentText().trimmed() << ',';
retval = true;
}
}
ts << endl;
return retval;
}
//! Processes all data in one row of input & writes appropriate data to output
//! @param ts QTextStream already associated with an output file
//! @param infile QFile object representing input (raw data) file
//! @param colCount Interpret data in infile as having this many "columns"
//! @param colSize Array of column sizes with colSize[n] = bytes in column n
//! @param byteSwap Swap endianness of source data. True or false.
//! @param vMin If device outputs between 1.1v and 5.5v, this is the 1.1v
//! @param vMax If device outputs between 1.1v and 5.5v, this is the 5.1v
//! @see dataToCsv()
void inline Window::csvProcessRow(QTextStream &ts, QFile &infile, int colCount,
QByteArray &colSize, bool byteSwap,
double vMin, double vMax)
{
static raw2quint64 raw;
raw.ui64 = 0;
for(int col = 0; col < colCount; ++col) { // For each column in this row
int readError = infile.read(raw.bytes, colSize[col]);
if(readError == -1) {
statusBarMessage->setText(tr("Error reading data file."));
return; // TODO: Get rid of multiple returns
}
if(byteSwap) raw.ui64 = qbswap(raw.ui64) >> ((8 - colSize[col]) << 3);
// TODO: Get rid of this check against a GUI checkbox
if(dataCheckBox.at(col)->isChecked()) ts << raw.ui64 << ',';
else {
double colVal = rawIntToVoltage(raw.ui64, colSize[col], vMin, vMax);
ts << qSetRealNumberPrecision(15) << colVal << ',';
}
}
ts << endl;
}
//! Controller function to convert input file data to an output .CSV file
//! @see mainLayoutCreateConnections()
void Window::dataToCsv()
{
QFile infile, outfile;
bool errorOpeningEitherFile = csvOpenFiles(infile, outfile);
if(!errorOpeningEitherFile) {
int colCount = spinColumns->value();
int rowSize = rowDataSize();
quint64 rowsOutput = 0;
quint64 rowLimit = comboRowLimit->currentText().toULongLong();
quint64 divCount = infileRowLimitDivisor();
bool byteSwap = checkBoxEndian->isChecked();
bool cancelled = false;
double vMin = minVoltage->value();
double vMax = maxVoltage->value();
QTextStream ts(&outfile);
if(checkBoxWriteColNames->isChecked())
if(csvWriteColumnNames(ts)) rowsOutput += 1;
QByteArray colSize(colCount, '\n');
for(int index = 0; index < colCount; ++index)
colSize[index] = dataSpinNumBytes.at(index)->value();
quint64 pMax = infileNumberRows();
if(rowLimit > 0 && rowLimit < pMax) pMax = rowLimit;
QProgressDialog progress("Saving CSV file...", "Cancel", 0, pMax, this);
progress.setModal(true);
statusBarMessage->setText(tr("Processing data file..."));
while(!infile.atEnd()) {
// while(rowsOutput <= pMax) {
if(rowLimit > 0 && rowsOutput >= rowLimit) break;
// Updating the status bar for every line processed is too slow!
if(rowsOutput % 1024 == 0) {
progress.setValue(rowsOutput);
if(progress.wasCanceled()) {
cancelled = true;
statusBarMessage->setText(tr("Processing cancelled."));
outfile.remove();
break;
}
}
csvProcessRow(ts, infile, colCount, colSize, byteSwap, vMin, vMax);
++rowsOutput;
if(divCount > 1)
infile.seek(infile.pos() + (rowSize * (divCount - 1)));
}
infile.close();
outfile.close();
if(!cancelled) statusBarMessage->setText(tr("Processing complete."));
if(checkBoxOpenWhenDone->isChecked()) openFileWithAssociatedProgram();
}
}
//! Converts a raw unsigned integer value range [0, 2^numBits] to a voltage.
//! Assumes that vMax > vMin
//! @param value One piece of the raw uninterpreted data from the source file
//! @param numBytes The size of value in number of bytes
//! @param vMin If device outputs between 1.1v and 5.5v, this is the 1.1v
//! @param vMax If device outputs between 1.1v and 5.5v, this is the 5.1v
//! @returns The computed voltage in the range [vMin, vMax]
//! @see dataToCsv()
inline double Window::rawIntToVoltage(const quint64 value, const int numBytes,
const double vMin, const double vMax) const
{
double range = vMax - vMin;
// Corrected bug reported by Riley Pack, 26 Jan 2010
// quint64 maxVal = 1 << (numBytes << 3); // pow(2,(bits in numBytes))
quint64 maxVal = (1 << (numBytes << 3)) -1; // pow(2,(bits in numBytes))
return (value / (maxVal / range)) + vMin;
}
//! Opens a file or URI with an applications the host operating system suggests.
//! @see dataToCsv()
void Window::openFileWithAssociatedProgram() const
{
QString filePath("file:///");
filePath += comboOutfile->currentText();
QUrl fileURI(filePath, QUrl::TolerantMode);
QDesktopServices::openUrl(fileURI);
}
//! Reads program settings from the data structures in the Config class
//! @returns false on any error, true otherwise
//! @see Window()
bool Window::importSettings()
{
bool retval = config->xmlRead(configFileURI, "charles_n_burns-data_parser");
if(!retval) statusBarMessage->setText("Unable to read config file.");
retval = config->xmlParse();
if(!retval) statusBarMessage->setText("Unable to parse config file.");
if(! config->pathlistInfile.isEmpty())
comboInfile->addItems(config->pathlistInfile);
if(! config->pathlistOutfile.isEmpty())
comboOutfile->addItems(config->pathlistOutfile);
checkBoxOpenWhenDone->setChecked(config->boxOpen);
comboRowLimit->insertItem(0, QString::number(
getUint64(config->limitRows.trimmed())));
comboRowLimit->setCurrentIndex(0);
int colCount = config->colCount;
if(this->spinColumns->value() < colCount) spinColumns->setValue(colCount);
for(int index = 0; index < colCount; ++index) {
if(config->colNames.size() > index)
dataComboName.at(index)->addItems(config->colNames.at(index));
if(config->colBoxChecked.size() > index)
dataCheckBox.at(index)->setChecked(config->colBoxChecked.at(index));
if(config->colBytes.size() > index)
dataSpinNumBytes.at(index)->setValue(config->colBytes.at(index));
}
spinColumns->setValue(config->colCount);
return retval;
}
//! Writes current program state to data structures in Config class
//! @see closeEvent()
void Window::exportSettings() const
{
config->clear();
int index;
config->pathlistInfile.append(comboInfile->currentText());
for(index = 0; index < comboInfile->count(); ++index) {
config->pathlistInfile.append(comboInfile->itemText(index));
}
config->pathlistInfile.removeDuplicates();
config->pathlistOutfile.append(comboOutfile->currentText());
for(index = 0; index < comboOutfile->count(); ++index) {
config->pathlistOutfile.append(comboOutfile->itemText(index));
}
config->pathlistOutfile.removeDuplicates();
config->boxOpen = checkBoxOpenWhenDone->isChecked();
if(comboRowLimit->count() > comboRowLimitDefaultItemCount) {
config->limitRows = comboRowLimit->currentText();
}
config->colCount = spinColumns->value();
QStringList sl;
for(index = 0; index < spinColumns->value(); ++index) { // For each column
QComboBox *cBox = dataComboName.at(index);
sl.append(cBox->currentText()); // Add the currently displayed text
// For each name in this combobox
for(int name = 0; name < cBox->count(); ++name) {
sl.append(cBox->itemText(name));
}
sl.removeDuplicates();
config->colNames.append(sl);
sl.clear();
config->colBoxChecked.append(dataCheckBox.at(index)->isChecked());
config->colBytes.append(dataSpinNumBytes.at(index)->value());
}
}
//! Grabs digits from a string. Stops when non-digit is reached or at maxDigits
//! @param text A QString of characters which theoretically contain a number
//! @param maxDigits The max number of individual numeric characters to extract
//! @returns the integer whose digits were collected from the string.
//! @see importSettings()
quint64 Window::getUint64(const QString &text, const quint8 maxDigits) const
{
int limit = (text.size() > maxDigits) ? maxDigits : text.size();
int index;
for(index = 0; index < limit; ++index) if(!text.at(index).isDigit()) break;
return text.left(index).toULongLong();
}
//! Blocks disruptive characters from being entered in a column name field.
//! This function directly changes the text in the GUI combobox controls.
//! @param text The string to insert into the output CSV file after filtering
//! @see dataRowCreate()
void Window::filterColumnName(const QString &text)
{
QString filtered = text;
// The following characters cause problems with CSV and so are banned: \",
filtered.remove(QRegExp("[\\\\\\\",]"));
if(text.length() != filtered.length()) {
// To find out which combobox is being typed in, we have to request
// the sender. It arrives as a QObject, which we cast to a QComboBox
QComboBox * cBox = reinterpret_cast<QComboBox*>(QObject::sender());
cBox->setEditText(filtered);
}
}
//! This slot updates to on-screen stats (number of rows in current file, etc.)
//! @see mainLayoutCreateConnections()
//! @see createDataLayout()
//! @see dataRowCreate()
void Window::updateDisplay()
{
this->updateInfileRowsDisplay();
this->updateStatusBarFileStats();
}
//! Updates the display of the number of data rows in the current input file.
//! @see updateDisplay()
void Window::updateInfileRowsDisplay()
{
QString display;
int addRows = 0;
quint64 numRows = infileNumberRows();
if(numRows < 1) display = "Unknown # rows";
else {
if(checkBoxWriteColNames->isChecked()) addRows = 1;
display = QString("/ %1 rows").arg(numRows + addRows);
}
infileRowsDisplay->setText(display);
}
//! Updates the status bar with statistics regarding current file vs. row limit.
//! @see updateDisplay()
void Window::updateStatusBarFileStats()
{
quint64 rowLimit = comboRowLimit->currentText().toULongLong();
quint64 rowDivide = infileRowLimitDivisor();
QString display = defaultStatusMessage;
if(rowLimit < infileNumberRows() && rowLimit != 0)
display = QString("Row limit %1: Keeping 1 in %2 rows."
).arg(rowLimit).arg(rowDivide);
statusBarMessage->setText(display);
}
//! Ensures only digits are accepted into comboRowLimit, for integer validity
//! comboRowLimit displays individual row limits for several office suites.
//! This function removes text such as (Excel 2007+) and grabs just the number.
//! @see mainLayoutCreateConnections()
void Window::filterLimitRowsName(const QString &text)
{
int indexNonInt = text.indexOf(QRegExp("[^0-9]"));
QString filtered = text.left(indexNonInt);
if(text.length() != filtered.length()) comboRowLimit->setEditText(filtered);
}
//! Slot called when minVoltage is changed. Ensures maxVoltage > minVoltage
//! newValue The new minimum voltage value from the min voltage spinbox
//! @see createAdvFeaturesLayout()
void Window::minVoltageChanged(double newValue)
{
if(newValue > (maxVoltage->value() - minVoltageDifference)) {
maxVoltage->setValue(newValue + minVoltageDifference);
}
}
//! Slot called when maxVoltage is changed. Ensures minVoltage < maxVoltage
//! newValue The new maximum voltage value from the max voltage spinbox
//! @see createAdvFeaturesLayout()
void Window::maxVoltageChanged(double newValue)
{
if(newValue < minVoltage->value() + minVoltageDifference) {
minVoltage->setValue(newValue - minVoltageDifference);
}
}
//! Slot which open's a url on system's default web browser
//! @param url The URI to open in the web browser, such as www.formortals.com
//! @see window()
//! @see createStatusBar()
void Window::openSystemWebBrowser(QString uri)
{
QDesktopServices::openUrl(uri);
}
//! Accepts a drag over the main window if and only if it's a list of files.
void Window::dragEnterEvent(QDragEnterEvent *event)
{
if(event->mimeData()->hasUrls()) event->acceptProposedAction();
}
//! Sets comboInfile text to the first in a file list dropped on the main window
void Window::dropEvent(QDropEvent *event)
{
QFileInfo fInfo;
QList<QUrl> urls = event->mimeData()->urls();
if(! urls.isEmpty()) {
QString fileURI = urls.first().toLocalFile();
if(! fileURI.isEmpty()) {
fInfo.setFile(fileURI);
if(fInfo.isFile()) {
comboInfile->insertItem(0, QDir::toNativeSeparators(fileURI));
comboInfile->setCurrentIndex(0);
}
}
}
}
//! Called when program is closed. Saves settings and writes them to disk.
void Window::closeEvent(QCloseEvent *event)
{
exportSettings();
config->xmlWrite(this->configFileURI);
event->accept();
}
| [
"charlesnburns@58430ede-5dd5-a7d2-092b-58c681406964"
] | [
[
[
1,
763
]
]
] |
4263dff808e9679c19b95c318ca8bd0dbc75f0f2 | ad33a51b7d45d8bf1aa900022564495bc08e0096 | /include/hge/hgecolor.h | 9bc95f82051fd24c1ad6979f16c2c6ca22a091e0 | [] | no_license | CBE7F1F65/e20671a6add96e9aa3551d07edee6bd4 | 31aff43df2571d334672929c88dfd41315a4098a | f33d52bbb59dfb758b24c0651449322ecd1b56b7 | refs/heads/master | 2016-09-11T02:42:42.116248 | 2011-09-26T04:30:32 | 2011-09-26T04:30:32 | 32,192,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,649 | h | /*
* Thanks to Dr.Watson JGE++!
** Haaf's Game Engine 1.7
** Copyright (C) 2003-2007, Relish Games
** hge.relishgames.com
**
** hgeColor*** helper classes
*/
#ifndef HGECOLOR_H
#define HGECOLOR_H
#include "../nge_define.h"
#define hgeColor hgeColorRGB
inline void ColorClamp(float &x) { if(x<0.0f) x=0.0f; if(x>1.0f) x=1.0f; }
class hgeColorRGB
{
public:
float r,g,b,a;
hgeColorRGB(float _r, float _g, float _b, float _a) { r=_r; g=_g; b=_b; a=_a; }
hgeColorRGB(uint32 col) { SetHWColor(col); }
hgeColorRGB() { r=g=b=a=0; }
hgeColorRGB operator- (const hgeColorRGB &c) const { return hgeColorRGB(r-c.r, g-c.g, b-c.b, a-c.a); }
hgeColorRGB operator+ (const hgeColorRGB &c) const { return hgeColorRGB(r+c.r, g+c.g, b+c.b, a+c.a); }
hgeColorRGB operator* (const hgeColorRGB &c) const { return hgeColorRGB(r*c.r, g*c.g, b*c.b, a*c.a); }
hgeColorRGB& operator-= (const hgeColorRGB &c) { r-=c.r; g-=c.g; b-=c.b; a-=c.a; return *this; }
hgeColorRGB& operator+= (const hgeColorRGB &c) { r+=c.r; g+=c.g; b+=c.b; a+=c.a; return *this; }
BOOLu8 operator== (const hgeColorRGB &c) const { return (r==c.r && g==c.g && b==c.b && a==c.a); }
BOOLu8 operator!= (const hgeColorRGB &c) const { return (r!=c.r || g!=c.g || b!=c.b || a!=c.a); }
hgeColorRGB operator/ (const float scalar) const { return hgeColorRGB(r/scalar, g/scalar, b/scalar, a/scalar); }
hgeColorRGB operator* (const float scalar) const { return hgeColorRGB(r*scalar, g*scalar, b*scalar, a*scalar); }
hgeColorRGB& operator*= (const float scalar) { r*=scalar; g*=scalar; b*=scalar; a*=scalar; return *this; }
void Clamp() { ColorClamp(r); ColorClamp(g); ColorClamp(b); ColorClamp(a); }
void SetHWColor(uint32 col) { a = (col>>24)/255.0f; r = ((col>>16) & 0xFF)/255.0f; g = ((col>>8) & 0xFF)/255.0f; b = (col & 0xFF)/255.0f; }
uint32 GetHWColor() const { return MAKE_RGBA_8888(((int)(r*255.0f)), ((int)(g*255.0f)), ((int)(b*255.0f)),((int)(a*255.0f))); }
};
inline hgeColorRGB operator* (const float sc, const hgeColorRGB &c) { return c*sc; }
class hgeColorHSV
{
public:
float h,s,v,a;
hgeColorHSV(float _h, float _s, float _v, float _a) { h=_h; s=_s; v=_v; a=_a; }
hgeColorHSV(uint32 col) { SetHWColor(col); }
hgeColorHSV() { h=s=v=a=0; }
hgeColorHSV operator- (const hgeColorHSV &c) const { return hgeColorHSV(h-c.h, s-c.s, v-c.v, a-c.a); }
hgeColorHSV operator+ (const hgeColorHSV &c) const { return hgeColorHSV(h+c.h, s+c.s, v+c.v, a+c.a); }
hgeColorHSV operator* (const hgeColorHSV &c) const { return hgeColorHSV(h*c.h, s*c.s, v*c.v, a*c.a); }
hgeColorHSV& operator-= (const hgeColorHSV &c) { h-=c.h; s-=c.s; v-=c.v; a-=c.a; return *this; }
hgeColorHSV& operator+= (const hgeColorHSV &c) { h+=c.h; s+=c.s; v+=c.v; a+=c.a; return *this; }
BOOLu8 operator== (const hgeColorHSV &c) const { return (h==c.h && s==c.s && v==c.v && a==c.a); }
BOOLu8 operator!= (const hgeColorHSV &c) const { return (h!=c.h || s!=c.s || v!=c.v || a!=c.a); }
hgeColorHSV operator/ (const float scalar) const { return hgeColorHSV(h/scalar, s/scalar, v/scalar, a/scalar); }
hgeColorHSV operator* (const float scalar) const { return hgeColorHSV(h*scalar, s*scalar, v*scalar, a*scalar); }
hgeColorHSV& operator*= (const float scalar) { h*=scalar; s*=scalar; v*=scalar; a*=scalar; return *this; }
void Clamp() { ColorClamp(h); ColorClamp(s); ColorClamp(v); ColorClamp(a); }
void SetHWColor(uint32 col);
uint32 GetHWColor() const;
};
inline hgeColorHSV operator* (const float sc, const hgeColorHSV &c) { return c*sc; }
#endif
| [
"CBE7F1F65@b503aa94-de59-8b24-8582-4b2cb17628fa"
] | [
[
[
1,
79
]
]
] |
22b91ed21bb15b542c1acb6a1e2327101f0167e6 | 5ff30d64df43c7438bbbcfda528b09bb8fec9e6b | /kcore/base/Assert.cpp | f43743c37510925f5f7cf40dc9a61e9ae9f125ac | [] | 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 | UTF-8 | C++ | false | false | 266 | cpp | #include "stdafx.h"
#include <kcore/corebase.h>
#include <cassert>
void nassert( bool cond, const char* cs, int line, const char* file )
{
file;
line;
cs;
if ( !cond )
{
#ifdef _DEBUG
__asm { int 3 };
#endif
assert( cond );
}
}
| [
"darkface@localhost"
] | [
[
[
1,
21
]
]
] |
97c2728b3b1333fcaf9bb06f5d51b7bf2aa8e664 | a381a69db3bd4f37266bf0c7129817ebb999e7b8 | /Common/AtgSessionManager.cpp | 29fb5bf47f2a90598433a1ec13750dd7442a2358 | [] | no_license | oukiar/vdash | 4420d6d6b462b7a833929b59d1ca232bd410e632 | d2bff3090c7d1c081d5b7ab41abb963f03d6118b | refs/heads/master | 2021-01-10T06:00:03.653067 | 2011-12-29T10:19:01 | 2011-12-29T10:19:01 | 49,607,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 65,940 | cpp | #include "stdafx.h"
#include "AtgUtil.h"
#include "AtgSessionManager.h"
#define DebugSpew ATG::DebugSpew
#define FatalError ATG::FatalError
#define XNKIDToInt64 ATG::XNKIDToInt64
//------------------------------------------------------------------------
// Name: SessionManager()
// Desc: Public constructor
//------------------------------------------------------------------------
SessionManager::SessionManager()
{
Reset();
}
//------------------------------------------------------------------------
// Name: Reset()
// Desc: Resets this SessionManager instance to its creation state
//------------------------------------------------------------------------
VOID SessionManager::Reset()
{
m_bIsInitialized = FALSE;
m_SessionCreationReason = SessionCreationReasonNone;
m_dwSessionFlags = 0;
m_dwOwnerController = XUSER_MAX_COUNT + 1;
m_xuidOwner = INVALID_XUID;
m_SessionState = SessionStateNone;
m_migratedSessionState = SessionStateNone;
m_bIsMigratedSessionHost = FALSE;
m_hSession = INVALID_HANDLE_VALUE;
m_qwSessionNonce = 0;
m_strSessionError = NULL;
m_bUsingQoS = FALSE;
m_pRegistrationResults = NULL;
ZeroMemory( &m_SessionInfo, sizeof( XSESSION_INFO ) );
ZeroMemory( &m_NewSessionInfo, sizeof( XSESSION_INFO ) );
ZeroMemory( &m_migratedSessionID, sizeof( XNKID ) );
}
//------------------------------------------------------------------------
// Name: ~SessionManager()
// Desc: Public destructor
//------------------------------------------------------------------------
SessionManager::~SessionManager()
{
// Close our XSession handle to clean up resources held by it
if( m_hSession != INVALID_HANDLE_VALUE &&
m_hSession != NULL )
{
XCloseHandle( m_hSession );
}
}
//------------------------------------------------------------------------
// Name: Initialize()
// Desc: Initializes this SessionManager instance
//------------------------------------------------------------------------
BOOL SessionManager::Initialize( SessionManagerInitParams initParams )
{
if( m_bIsInitialized )
{
DebugSpew( "SessionManager already initialized. Reinitializing..\n" );
}
m_SessionCreationReason = initParams.m_SessionCreationReason;
m_dwSessionFlags = initParams.m_dwSessionFlags;
m_bIsHost = initParams.m_bIsHost;
m_Slots[SLOTS_TOTALPUBLIC] = initParams.m_dwMaxPublicSlots;
m_Slots[SLOTS_TOTALPRIVATE] = initParams.m_dwMaxPrivateSlots;
m_Slots[SLOTS_FILLEDPUBLIC] = 0;
m_Slots[SLOTS_FILLEDPRIVATE] = 0;
m_Slots[SLOTS_ZOMBIEPUBLIC] = 0;
m_Slots[SLOTS_ZOMBIEPRIVATE] = 0;
m_bIsInitialized = TRUE;
return TRUE;
}
//------------------------------------------------------------------------
// Name: IsInitialized()
// Desc: Queries SessionManager initialization state
//------------------------------------------------------------------------
BOOL SessionManager::IsInitialized()
{
return m_bIsInitialized;
}
//------------------------------------------------------------------------
// Name: IsSessionDeleted()
// Desc: Returns TRUE if the XSession for this instance
// has a 0 sessionID; otherwise false
//------------------------------------------------------------------------
BOOL SessionManager::IsSessionDeleted( VOID ) const
{
static const XNKID zero = {0};
if( m_SessionState == SessionStateDeleted )
{
return TRUE;
}
BOOL bIsSessionDeleted = FALSE;
if( m_hSession == INVALID_HANDLE_VALUE || m_hSession == NULL )
{
// If the session hasn't been created yet, return false
if ( m_SessionState < SessionStateCreated )
{
bIsSessionDeleted = FALSE;
}
else
{
bIsSessionDeleted = TRUE;
}
return bIsSessionDeleted;
}
// Call XSessionGetDetails first time to get back the size
// of the results buffer we need
DWORD cbResults = 0;
DWORD ret = XSessionGetDetails( m_hSession,
&cbResults,
NULL,
NULL );
if( ( ret != ERROR_INSUFFICIENT_BUFFER ) || ( cbResults == 0 ) )
{
DebugSpew( "SessionManager::IsSessionDeleted - Failed on first call to XSessionGetDetails, hr=0x%08x\n", ret );
return FALSE;
}
XSESSION_LOCAL_DETAILS* pSessionDetails = (XSESSION_LOCAL_DETAILS*)new BYTE[ cbResults ];
if( pSessionDetails == NULL )
{
FatalError( "SessionManager::IsSessionDeleted - Failed to allocate buffer.\n" );
}
// Call second time to fill our results buffer
ret = XSessionGetDetails( m_hSession,
&cbResults,
pSessionDetails,
NULL );
if( ret != ERROR_SUCCESS )
{
DebugSpew( "SessionManager::IsSessionDeleted - XSessionGetDetails failed with error %d\n", ret );
return FALSE;
}
// Iterate through the returned results
const XNKID sessionID = pSessionDetails->sessionInfo.sessionID;
if ( !memcmp( &sessionID, &zero, sizeof( sessionID ) ) )
{
bIsSessionDeleted = TRUE;
}
if ( pSessionDetails )
{
delete [] pSessionDetails;
}
return bIsSessionDeleted;
}
//------------------------------------------------------------------------
// Name: IsPlayerInSession()
// Desc: Uses XSessionGetDetails API to determine if a player is in the session
//------------------------------------------------------------------------
BOOL SessionManager::IsPlayerInSession( const XUID xuidPlayer, const DWORD dwUserIndex ) const
{
if( m_hSession == INVALID_HANDLE_VALUE || m_hSession == NULL )
{
DebugSpew( "SessionManager::IsPlayerInSession - Session handle invalid. Perhaps session has been deleted?\n" );
return FALSE;
}
// Call XSessionGetDetails first time to get back the size
// of the results buffer we need
DWORD cbResults = 0;
DWORD ret = XSessionGetDetails( m_hSession,
&cbResults,
NULL,
NULL );
if( ( ret != ERROR_INSUFFICIENT_BUFFER ) || ( cbResults == 0 ) )
{
DebugSpew( "SessionManager::IsPlayerInSession - Failed on first call to XSessionGetDetails, hr=0x%08x\n", ret );
return FALSE;
}
// Increase our buffer size to include an estimate of the maximum number
// of players allowed in the session
const DWORD dwMaxMembers = m_Slots[SLOTS_TOTALPUBLIC] + m_Slots[SLOTS_TOTALPRIVATE];
cbResults += dwMaxMembers * sizeof(XSESSION_MEMBER);
XSESSION_LOCAL_DETAILS* pSessionDetails = (XSESSION_LOCAL_DETAILS*)new BYTE[ cbResults ];
if( pSessionDetails == NULL )
{
FatalError( "SessionManager::IsPlayerInSession - Failed to allocate buffer.\n" );
}
// Call second time to fill our results buffer
ret = XSessionGetDetails( m_hSession,
&cbResults,
pSessionDetails,
NULL );
if( ret != ERROR_SUCCESS )
{
DebugSpew( "SessionManager::IsPlayerInSession - XSessionGetDetails failed with error %d\n", ret );
return FALSE;
}
const BOOL bIsValidUserIndex = ( dwUserIndex < XUSER_MAX_COUNT );
BOOL bIsInSession = FALSE;
for ( DWORD i = 0; i < pSessionDetails->dwReturnedMemberCount; ++i )
{
if( ( bIsValidUserIndex && ( pSessionDetails->pSessionMembers[i].dwUserIndex == dwUserIndex ) ) ||
( xuidPlayer == pSessionDetails->pSessionMembers[i].xuidOnline ) )
{
bIsInSession = TRUE;
break;
}
}
if ( pSessionDetails )
{
delete [] pSessionDetails;
}
return bIsInSession;
}
//------------------------------------------------------------------------
// Name: DebugDumpSessionDetails()
// Desc: Dumps session deletes
//------------------------------------------------------------------------
VOID SessionManager::DebugDumpSessionDetails() const
{
#ifdef _DEBUG
if( m_hSession == INVALID_HANDLE_VALUE || m_hSession == NULL )
{
DebugSpew( "SessionManager::DebugDumpSessionDetails - Session handle invalid. Perhaps session has been deleted?\n" );
return;
}
// Call XSessionGetDetails first time to get back the size
// of the results buffer we need
DWORD cbResults = 0;
DWORD ret = XSessionGetDetails( m_hSession,
&cbResults,
NULL,
NULL );
if( ( ret != ERROR_INSUFFICIENT_BUFFER ) || ( cbResults == 0 ) )
{
DebugSpew( "SessionManager::DebugDumpSessionDetails - Failed on first call to XSessionGetDetails, hr=0x%08x\n", ret );
return;
}
// Increase our buffer size to include an estimate of the maximum number
// of players allowed in the session
const DWORD dwMaxMembers = m_Slots[SLOTS_TOTALPUBLIC] + m_Slots[SLOTS_TOTALPRIVATE];
cbResults += dwMaxMembers * sizeof(XSESSION_MEMBER);
XSESSION_LOCAL_DETAILS* pSessionDetails = (XSESSION_LOCAL_DETAILS*)new BYTE[ cbResults ];
if( pSessionDetails == NULL )
{
FatalError( "SessionManager::DebugDumpSessionDetails - Failed to allocate buffer.\n" );
}
// Call second time to fill our results buffer
ret = XSessionGetDetails( m_hSession,
&cbResults,
pSessionDetails,
NULL );
if( ret != ERROR_SUCCESS )
{
DebugSpew( "SessionManager::DebugDumpSessionDetails - XSessionGetDetails failed with error %d\n", ret );
return;
}
// Iterate through the returned results
DebugSpew( "***************** DebugDumpSessionDetails *****************\n" \
"instance: %p\n" \
"sessionID: %016I64X\n" \
"Matchmaking session?: %s\n" \
"m_hSession: %p\n" \
"bIsHost: %d\n" \
"sessionstate: %s\n" \
"qwSessionNonce: %I64u\n" \
"dwUserIndexHost: %d\n" \
"dwGameType: %d\n" \
"dwGameMode: %d\n" \
"dwFlags: 0x%x\n" \
"dwMaxPublicSlots: %d\n" \
"dwMaxPrivateSlots: %d\n" \
"dwAvailablePublicSlots: %d\n" \
"dwAvailablePrivateSlots: %d\n" \
"dwActualMemberCount: %d\n" \
"dwReturnedMemberCount: %d\n" \
"xnkidArbitration: %016I64X\n",
this,
GetSessionIDAsInt(),
( HasSessionFlags( XSESSION_CREATE_USES_MATCHMAKING ) ) ? "Yes" : "No",
m_hSession,
m_bIsHost,
g_astrSessionState[m_SessionState],
m_qwSessionNonce,
pSessionDetails->dwUserIndexHost,
pSessionDetails->dwGameType,
pSessionDetails->dwGameMode,
pSessionDetails->dwFlags,
pSessionDetails->dwMaxPublicSlots,
pSessionDetails->dwMaxPrivateSlots,
pSessionDetails->dwAvailablePublicSlots,
pSessionDetails->dwAvailablePrivateSlots,
pSessionDetails->dwActualMemberCount,
pSessionDetails->dwReturnedMemberCount,
XNKIDToInt64( pSessionDetails->xnkidArbitration ) );
for ( DWORD i = 0; i < pSessionDetails->dwReturnedMemberCount; ++i )
{
DebugSpew( "***************** XSESSION_MEMBER %d *****************\n" \
"Online XUID: 0x%016I64X\n" \
"dwUserIndex: %d\n" \
"dwFlags: 0x%x\n",
i,
pSessionDetails->pSessionMembers[i].xuidOnline,
pSessionDetails->pSessionMembers[i].dwUserIndex,
pSessionDetails->pSessionMembers[i].dwFlags );
}
if ( pSessionDetails )
{
delete [] pSessionDetails;
}
#endif
}
//------------------------------------------------------------------------
// Name: DebugValidateExpectedSlotCounts()
// Desc: Makes sure slot counts are consistent with what is stored with
// the XSession
//------------------------------------------------------------------------
BOOL SessionManager::DebugValidateExpectedSlotCounts( const BOOL bBreakOnDifferent ) const
{
BOOL bSlotCountsDiffer = FALSE;
assert (m_SessionState < SessionStateCount);
#ifdef _DEBUG
if( m_hSession == INVALID_HANDLE_VALUE || m_hSession == NULL )
{
DebugSpew( "SessionManager::DebugValidateExpectedSlotCounts - Session handle invalid. Perhaps session has been deleted?\n" );
return !bSlotCountsDiffer;
}
// Call XSessionGetDetails first time to get back the size
// of the results buffer we need
DWORD cbResults = 0;
DWORD ret = XSessionGetDetails( m_hSession,
&cbResults,
NULL,
NULL );
if( ( ret != ERROR_INSUFFICIENT_BUFFER ) || ( cbResults == 0 ) )
{
DebugSpew( "SessionManager::DebugValidateExpectedSlotCounts - Failed on first call to XSessionGetDetails, hr=0x%08x\n", ret );
return FALSE;
}
XSESSION_LOCAL_DETAILS* pSessionDetails = (XSESSION_LOCAL_DETAILS*)new BYTE[ cbResults ];
if( pSessionDetails == NULL )
{
FatalError( "SessionManager::DebugValidateExpectedSlotCounts - Failed to allocate buffer.\n" );
}
// Call second time to fill our results buffer
ret = XSessionGetDetails( m_hSession,
&cbResults,
pSessionDetails,
NULL );
if( ret != ERROR_SUCCESS )
{
DebugSpew( "SessionManager::DebugValidateExpectedSlotCounts - XSessionGetDetails failed with error %d\n", ret );
return FALSE;
}
const XNKID sessionID = pSessionDetails->sessionInfo.sessionID;
const DWORD dwMaxPublicSlots = m_Slots[SLOTS_TOTALPUBLIC];
const DWORD dwMaxPrivateSlots = m_Slots[SLOTS_TOTALPRIVATE];
const DWORD dwAvailablePublicSlots = m_Slots[SLOTS_TOTALPUBLIC] - m_Slots[SLOTS_FILLEDPUBLIC];
const DWORD dwAvailablePrivateSlots = m_Slots[SLOTS_TOTALPRIVATE] - m_Slots[SLOTS_FILLEDPRIVATE];
bSlotCountsDiffer = ( pSessionDetails->dwMaxPublicSlots != dwMaxPublicSlots ||
pSessionDetails->dwMaxPrivateSlots != dwMaxPrivateSlots );
// XSessionGetDetails only returns dwAvailablePublicSlots and dwAvailablePrivateSlots data
// for:
// 1. matchmaking sessions,
// 2. sessions that are joinable during gameplay,
// 3. sessions that aren't deleted
//
// Therefore it only makes sense to compare against are expected slot counts if all of
// these conditions are met
const BOOL bIsMatchmakingSession = HasSessionFlags( XSESSION_CREATE_USES_MATCHMAKING );
const BOOL bJoinable = !HasSessionFlags( XSESSION_CREATE_USES_ARBITRATION ) &&
!HasSessionFlags( XSESSION_CREATE_JOIN_IN_PROGRESS_DISABLED );
if( bIsMatchmakingSession &&
( m_SessionState != SessionStateDeleted ) &&
( ( m_SessionState != SessionStateInGame ) || ( ( m_SessionState == SessionStateInGame ) && bJoinable ) ) )
{
bSlotCountsDiffer |= ( pSessionDetails->dwAvailablePublicSlots != dwAvailablePublicSlots ||
pSessionDetails->dwAvailablePrivateSlots != dwAvailablePrivateSlots );
}
// Any differences detected?
if( !bSlotCountsDiffer )
{
goto Terminate;
}
// Spew expected/actual slot counts
DebugSpew( "***************** DebugValidateExpectedSlotCounts *****************\n" \
"instance: %p\n" \
"sessionID: %016I64X\n" \
"m_hSession: %p\n" \
"bIsHost: %d\n" \
"sessionstate: %s\n" \
"dwMaxPublicSlots expected: %d; actual: %d\n" \
"dwMaxPrivateSlots expected: %d; actual: %d\n",
this,
XNKIDToInt64( sessionID ),
m_hSession,
m_bIsHost,
g_astrSessionState[m_SessionState],
dwMaxPublicSlots, pSessionDetails->dwMaxPublicSlots,
dwMaxPrivateSlots, pSessionDetails->dwMaxPrivateSlots );
if( HasSessionFlags( XSESSION_CREATE_USES_MATCHMAKING ) )
{
DebugSpew( "dwAvailablePublicSlots expected: %d; actual: %d\n" \
"dwAvailablePrivateSlots expected: %d; actual: %d\n",
dwAvailablePublicSlots, pSessionDetails->dwAvailablePublicSlots,
dwAvailablePrivateSlots, pSessionDetails->dwAvailablePrivateSlots );
}
if( bBreakOnDifferent & bSlotCountsDiffer )
{
DebugBreak();
}
Terminate:
if ( pSessionDetails )
{
delete [] pSessionDetails;
}
#endif
return !bSlotCountsDiffer;
}
//------------------------------------------------------------------------
// Name: GetSessionCreationReason()
// Desc: Retrieves session creation reason
//------------------------------------------------------------------------
SessionCreationReason SessionManager::GetSessionCreationReason( VOID ) const
{
return m_SessionCreationReason;
}
//------------------------------------------------------------------------
// Name: GetSessionState()
// Desc: Retrieves current session state
//------------------------------------------------------------------------
SessionState SessionManager::GetSessionState( VOID ) const
{
return m_SessionState;
}
//------------------------------------------------------------------------
// Name: GetSessionStateString()
// Desc: Retrieves current session state
//------------------------------------------------------------------------
const char* SessionManager::GetSessionStateString( VOID ) const
{
return g_astrSessionState[m_SessionState];
}
//------------------------------------------------------------------------
// Name: SetSessionOwner()
// Desc: Sets current session owner
//------------------------------------------------------------------------
VOID SessionManager::SetSessionOwner( const DWORD dwOwnerController )
{
m_dwOwnerController = dwOwnerController;
XUserGetXUID( m_dwOwnerController, &m_xuidOwner );
}
//------------------------------------------------------------------------
// Name: GetSessionOwner()
// Desc: Retrieves current session owner
//------------------------------------------------------------------------
DWORD SessionManager::GetSessionOwner( VOID ) const
{
return m_dwOwnerController;
}
//------------------------------------------------------------------------
// Name: GetSessionOwner()
// Desc: Retrieves current session owner XUID
//------------------------------------------------------------------------
XUID SessionManager::GetSessionOwnerXuid( VOID ) const
{
return m_xuidOwner;
}
//------------------------------------------------------------------------
// Name: IsSessionOwner()
// Desc: Retrieves current session owner
//------------------------------------------------------------------------
BOOL SessionManager::IsSessionOwner( const DWORD dwController ) const
{
return ( dwController == m_dwOwnerController );
}
//------------------------------------------------------------------------
// Name: IsSessionOwner()
// Desc: Retrieves current session owner
//------------------------------------------------------------------------
BOOL SessionManager::IsSessionOwner( const XUID xuidOwner ) const
{
return ( xuidOwner == m_xuidOwner );
}
//------------------------------------------------------------------------
// Name: IsSessionHost()
// Desc: True if this SessionManager instance is the session host,
// else false
//------------------------------------------------------------------------
BOOL SessionManager::IsSessionHost( VOID ) const
{
return m_bIsHost;
}
//------------------------------------------------------------------------
// Name: MakeSessionHost()
// Desc: Make this SessionManager instance the session host.
//------------------------------------------------------------------------
VOID SessionManager::MakeSessionHost( VOID )
{
m_bIsHost = TRUE;
}
//------------------------------------------------------------------------
// Name: GetSessionNonce()
// Desc: Function to retrieve current session nonce
//------------------------------------------------------------------------
ULONGLONG SessionManager::GetSessionNonce( VOID ) const
{
return m_qwSessionNonce;
}
//------------------------------------------------------------------------
// Name: SetSessionNonce()
// Desc: Function to set the session nonce
// Only non-hosts should ever call this method
//------------------------------------------------------------------------
VOID SessionManager::SetSessionNonce( const ULONGLONG qwNonce )
{
if( m_bIsHost )
{
FatalError( "Only non-hosts should call this function!\n" );
}
m_qwSessionNonce = qwNonce;
DebugDumpSessionDetails();
}
//------------------------------------------------------------------------
// Name: SetHostInAddr()
// Desc: Sets the IN_ADDR of the session host
//------------------------------------------------------------------------
VOID SessionManager::SetHostInAddr( const IN_ADDR& inaddr )
{
m_HostInAddr = inaddr;
}
//------------------------------------------------------------------------
// Name: GetHostInAddr()
// Desc: Returns the IN_ADDR of the session host
//------------------------------------------------------------------------
IN_ADDR SessionManager::GetHostInAddr( VOID ) const
{
return m_HostInAddr;
}
//------------------------------------------------------------------------
// Name: GetSessionID()
// Desc: Function to retrieve current session ID
//------------------------------------------------------------------------
XNKID SessionManager::GetSessionID( VOID ) const
{
return m_SessionInfo.sessionID;
}
//------------------------------------------------------------------------
// Name: GetSessionIDAsInt()
// Desc: Function to retrieve current session ID as an __int64
//------------------------------------------------------------------------
__int64 SessionManager::GetSessionIDAsInt( VOID ) const
{
// XNKID's are big-endian. Convert to little-endian if needed.
#ifdef LIVE_ON_WINDOWS
XNKID sessionID = m_SessionInfo.sessionID;
for( BYTE i = 0; i < 4; ++i )
{
BYTE temp = (BYTE)( *( (BYTE*)&sessionID + i ) ); //temp = sessionID[ i ]
*( (BYTE*)&sessionID + i ) = (BYTE)( *( (BYTE*)&sessionID + 8 - i - 1 ) ); //sessionID[ i ] = sessionID[ 8 - i - 1 ]
*( (BYTE*)&sessionID + 8 - i - 1 ) = temp; //sessionID[ 8 - i - 1 ] = temp
}
return *(const __int64*)&sessionID;
#else
return *(const __int64*)&m_SessionInfo.sessionID;
#endif
}
//------------------------------------------------------------------------
// Name: GetMigratedSessionID()
// Desc: Function to retrieve the session ID of the session while
// it is being migrated. This method can only be called
// when this session manager instance is actively migrating a session
//------------------------------------------------------------------------
XNKID SessionManager::GetMigratedSessionID( VOID ) const
{
if( !( m_SessionState >= SessionStateMigrateHost &&
m_SessionState <= SessionStateMigratedHost ) )
{
FatalError( "GetMigratedSessionID called in state %s!\n", GetSessionStateString() );
}
return m_migratedSessionID;
}
//------------------------------------------------------------------------
// Name: SetSessionState()
// Desc: Sets current session state
//------------------------------------------------------------------------
VOID SessionManager::SetSessionState( const SessionState newState )
{
m_SessionState = newState;
}
//------------------------------------------------------------------------
// Name: CheckSessionState()
// Desc: Checks if session in the expected state
//------------------------------------------------------------------------
BOOL SessionManager::CheckSessionState( const SessionState expectedState ) const
{
SessionState actual = GetSessionState();
if( actual != expectedState )
{
FatalError( "SessionManager instance in invalid state. Expected: %d; Got: %d\n",
expectedState, actual );
}
return TRUE;
}
//------------------------------------------------------------------------
// Name: GetRegistrationResults()
// Desc: Retrieves last results from registering this client for
// arbitratrion
//------------------------------------------------------------------------
const PXSESSION_REGISTRATION_RESULTS SessionManager::GetRegistrationResults() const
{
return (const PXSESSION_REGISTRATION_RESULTS)m_pRegistrationResults;
}
//------------------------------------------------------------------------
// Name: SwitchToState()
// Desc: Changes to a new session state and performs initialization
// for the new state
//------------------------------------------------------------------------
VOID SessionManager::SwitchToState( SessionState newState )
{
// Ignore transitions to the same state
if( m_SessionState == newState )
{
return;
}
// If we're in state SessionStateMigratedHost, force a switch to
// the state we were in prior to migration
if( m_SessionState == SessionStateMigratedHost )
{
DebugSpew( "SessionManager %016I64X (instance %p): Detected to be in state SessionStateMigratedHost. " \
"Switching to correct pre-migration state\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
this );
SwitchToPreHostMigrationState();
}
assert( m_SessionState < _countof( g_astrSessionState ) );
DebugSpew( "SessionManager %016I64X (instance %p): Switching from session state %s to %s\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
this,
g_astrSessionState[m_SessionState],
g_astrSessionState[newState] );
// Clean up from the previous state
switch( m_SessionState )
{
case SessionStateDeleted:
//Reset();
// Clear out our slots and update our presence info
m_Slots[ SLOTS_FILLEDPUBLIC ] = 0;
m_Slots[ SLOTS_FILLEDPRIVATE ] = 0;
m_Slots[ SLOTS_ZOMBIEPUBLIC ] = 0;
m_Slots[ SLOTS_ZOMBIEPRIVATE ] = 0;
if( m_pRegistrationResults )
{
delete[] m_pRegistrationResults;
m_pRegistrationResults = NULL;
}
break;
case SessionStateMigratedHost:
m_bIsMigratedSessionHost = FALSE;
break;
case SessionStateRegistering:
case SessionStateInGame:
case SessionStateNone:
case SessionStateCreating:
case SessionStateWaitingForRegistration:
case SessionStateStarting:
case SessionStateEnding:
case SessionStateDeleting:
default:
break;
}
// Initialize the next state
switch( newState )
{
case SessionStateCreated:
if( !IsSessionHost() )
{
// Re-entering this state is a bad thing, since
// that would wipe out the session nonce
assert( m_SessionState != SessionStateCreated );
// XSessionCreate would have
// returned a 0 session nonce,
// so set our session nonce
// to a random value that we'll
// replace once we get the
// true nonce from the session host
int retVal = XNetRandom( (BYTE *)&m_qwSessionNonce, sizeof( m_qwSessionNonce ) );
if ( retVal )
{
FatalError( "XNetRandom failed: %d\n", retVal );
}
DebugDumpSessionDetails();
}
break;
case SessionStateMigratedHost:
// Copy m_NewSessionInfo into m_SessionInfo
// and zero out m_NewSessionInfo
m_SessionInfo = m_NewSessionInfo;
ZeroMemory( &m_NewSessionInfo, sizeof( XSESSION_INFO ) );
break;
case SessionStateEnded:
// If this is an arbitrated session, we might have slots occupied by zombies. Free up those slots
// and zero out our zombie slot counts
if( m_dwSessionFlags & XSESSION_CREATE_USES_ARBITRATION )
{
m_Slots[ SLOTS_FILLEDPRIVATE ] -= m_Slots[ SLOTS_ZOMBIEPRIVATE ];
m_Slots[ SLOTS_FILLEDPRIVATE ] = max( m_Slots[ SLOTS_FILLEDPRIVATE ], 0 );
m_Slots[ SLOTS_FILLEDPUBLIC ] -= m_Slots[ SLOTS_ZOMBIEPUBLIC ];
m_Slots[ SLOTS_FILLEDPUBLIC ] = max( m_Slots[ SLOTS_FILLEDPUBLIC ], 0 );
m_Slots[ SLOTS_ZOMBIEPRIVATE ] = 0;
m_Slots[ SLOTS_ZOMBIEPUBLIC ] = 0;
}
break;
case SessionStateDeleted:
if( ( m_hSession != INVALID_HANDLE_VALUE ) &&
( m_hSession != NULL ) )
{
XCloseHandle( m_hSession );
m_hSession = NULL;
}
break;
case SessionStateNone:
case SessionStateIdle:
case SessionStateWaitingForRegistration:
case SessionStateRegistered:
case SessionStateInGame:
default:
break;
}
m_SessionState = newState;
}
//------------------------------------------------------------------------
// Name: NotifyOverlappedOperationCancelled()
// Desc: Lets this instance know that the current overlapped operation
// was cancelled.
//------------------------------------------------------------------------
HRESULT SessionManager::NotifyOverlappedOperationCancelled( const XOVERLAPPED* const pXOverlapped )
{
//
// Only certain states can be rolled back to the previous state
switch( m_SessionState )
{
case SessionStateCreating:
m_SessionState = SessionStateNone;
break;
case SessionStateRegistering:
m_SessionState = SessionStateIdle;
break;
case SessionStateStarting:
m_SessionState = HasSessionFlags( XSESSION_CREATE_USES_ARBITRATION ) ? SessionStateRegistered : SessionStateIdle;
break;
case SessionStateEnding:
m_SessionState = SessionStateInGame;
break;
case SessionStateDeleting:
m_SessionState = SessionStateEnded;
break;
}
return S_OK;
}
//------------------------------------------------------------------------
// Name: SwitchToPreHostMigrationState()
// Desc: Switches the current session state back to what it was
// prior to host migration
//------------------------------------------------------------------------
VOID SessionManager::SwitchToPreHostMigrationState()
{
// We can only transition to this state from SessionStateMigratedHost
assert( m_SessionState == SessionStateMigratedHost );
// Zero out m_migratedSessionID
ZeroMemory( &m_migratedSessionID, sizeof( XNKID ) );
// Return session state to what it was before migration started
// and set m_migratedSessionState to a blank state
m_SessionState = m_migratedSessionState;
m_migratedSessionState = SessionStateNone;
m_bIsMigratedSessionHost = FALSE;
DebugDumpSessionDetails();
}
//------------------------------------------------------------------------
// Name: HasSessionFlags()
// Desc: Checks if passed-in flags are set for the current session
//------------------------------------------------------------------------
BOOL SessionManager::HasSessionFlags( const DWORD dwFlags ) const
{
BOOL bHasFlags = FALSE;
// What flags in m_dwSessionFlags and dwFlags are different?
DWORD dwDiffFlags = m_dwSessionFlags ^ dwFlags;
// If none of dwDiffFlags are in dwFlags,
// we have a match
if( ( dwDiffFlags & dwFlags ) == 0 )
{
bHasFlags = TRUE;
}
return bHasFlags;
}
//------------------------------------------------------------------------
// Name: FlipSessionFlags()
// Desc: XORs the state of the current session's
// flags with that of the passed-in flags
//------------------------------------------------------------------------
VOID SessionManager::FlipSessionFlags( const DWORD dwFlags )
{
m_dwSessionFlags ^= dwFlags;
DebugSpew( "FlipSessionFlags: New session flags: %d\n", m_dwSessionFlags );
}
//------------------------------------------------------------------------
// Name: ClearSessionFlags()
// Desc: Clear the passed-in flags for the
// current session
//------------------------------------------------------------------------
VOID SessionManager::ClearSessionFlags( const DWORD dwFlags )
{
m_dwSessionFlags &= ~dwFlags;
DebugSpew( "ClearSessionFlags: New session flags: %d\n", m_dwSessionFlags );
}
//------------------------------------------------------------------------
// Name: SetSessionInfo()
// Desc: Set session info data. This only be called outside of an
// active session
//------------------------------------------------------------------------
VOID SessionManager::SetSessionInfo( const XSESSION_INFO& session_info )
{
SessionState actual = GetSessionState();
if( m_SessionState > SessionStateCreating && m_SessionState < SessionStateDelete )
{
FatalError( "SessionManager instance in invalid state: %s\n", g_astrSessionState[actual] );
}
m_SessionInfo = session_info;
}
//------------------------------------------------------------------------
// Name: SetNewSessionInfo()
// Desc: Set session info data for the new session we will migrate this
// session to. This only be called inside of an active session
//------------------------------------------------------------------------
VOID SessionManager::SetNewSessionInfo( const XSESSION_INFO& session_info,
const BOOL bIsNewSessionHost )
{
SessionState actual = GetSessionState();
if( m_SessionState < SessionStateCreated || m_SessionState >= SessionStateDelete )
{
FatalError( "SessionManager instance in invalid state: %d\n", actual );
}
m_NewSessionInfo = session_info;
m_bIsMigratedSessionHost = bIsNewSessionHost;
// Cache current session ID for a possible host migration scenario..
memcpy( &m_migratedSessionID, &m_SessionInfo.sessionID, sizeof( XNKID ) );
}
//------------------------------------------------------------------------
// Name: SetSessionFlags()
// Desc: Set session flags. Optionally first clears all currently set
// flags. This only be called outside of an active session
//------------------------------------------------------------------------
VOID SessionManager::SetSessionFlags( const DWORD dwFlags, const BOOL fClearExisting )
{
SessionState actual = GetSessionState();
if( m_SessionState > SessionStateCreating && m_SessionState < SessionStateDelete )
{
FatalError( "SessionManager instance in invalid state: %s\n", g_astrSessionState[actual] );
}
if( fClearExisting )
{
m_dwSessionFlags = 0;
}
m_dwSessionFlags |= dwFlags;
DebugSpew( "SetSessionFlags: New session flags: %d\n", m_dwSessionFlags );
}
//------------------------------------------------------------------------
// Name: GetSessionFlags()
// Desc: Returns current session flags
//------------------------------------------------------------------------
DWORD SessionManager::GetSessionFlags() const
{
return m_dwSessionFlags;
}
//------------------------------------------------------------------------
// Name: GetSessionInfo()
// Desc: Returns current XSESSION_INFO
//------------------------------------------------------------------------
const XSESSION_INFO& SessionManager::GetSessionInfo() const
{
return m_SessionInfo;
}
//------------------------------------------------------------------------
// Name: GetMaxSlotCounts()
// Desc: Returns current maximum slot counts
//------------------------------------------------------------------------
VOID SessionManager::GetMaxSlotCounts( DWORD& dwMaxPublicSlots, DWORD& dwMaxPrivateSlots ) const
{
dwMaxPublicSlots = m_Slots[SLOTS_TOTALPUBLIC];
dwMaxPrivateSlots = m_Slots[SLOTS_TOTALPRIVATE];
// DebugValidateExpectedSlotCounts();
}
//------------------------------------------------------------------------
// Name: GetFilledSlotCounts()
// Desc: Returns current filled slot counts
//------------------------------------------------------------------------
VOID SessionManager::GetFilledSlotCounts( DWORD& dwFilledPublicSlots, DWORD& dwFilledPrivateSlots ) const
{
dwFilledPublicSlots = m_Slots[SLOTS_FILLEDPUBLIC];
dwFilledPrivateSlots = m_Slots[SLOTS_FILLEDPRIVATE];
// DebugValidateExpectedSlotCounts();
}
//------------------------------------------------------------------------
// Name: SetMaxSlotCounts()
// Desc: Sets current maximum slot counts
//------------------------------------------------------------------------
VOID SessionManager::SetMaxSlotCounts( const DWORD dwMaxPublicSlots, const DWORD dwMaxPrivateSlots )
{
#ifdef _DEBUG
DebugSpew( "SetMaxSlotCounts(%016I64X): Old: [%d, %d, %d, %d]\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
m_Slots[SLOTS_TOTALPUBLIC],
m_Slots[SLOTS_TOTALPRIVATE],
m_Slots[SLOTS_FILLEDPUBLIC],
m_Slots[SLOTS_FILLEDPRIVATE]);
#endif
m_Slots[SLOTS_TOTALPUBLIC] = dwMaxPublicSlots;
m_Slots[SLOTS_TOTALPRIVATE] = dwMaxPrivateSlots;
#ifdef _DEBUG
DebugSpew( "SetMaxSlotCounts(%016I64X): New: [%d, %d, %d, %d]\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
m_Slots[SLOTS_TOTALPUBLIC],
m_Slots[SLOTS_TOTALPRIVATE],
m_Slots[SLOTS_FILLEDPUBLIC],
m_Slots[SLOTS_FILLEDPRIVATE]);
#endif
}
//------------------------------------------------------------------------
// Name: SetFilledSlotCounts()
// Desc: Sets current filled slot counts
//------------------------------------------------------------------------
VOID SessionManager::SetFilledSlotCounts( const DWORD dwFilledPublicSlots, DWORD dwFilledPrivateSlots )
{
#ifdef _DEBUG
DebugSpew( "SetFilledSlotCounts(%016I64X): Old: [%d, %d, %d, %d]\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
m_Slots[SLOTS_TOTALPUBLIC],
m_Slots[SLOTS_TOTALPRIVATE],
m_Slots[SLOTS_FILLEDPUBLIC],
m_Slots[SLOTS_FILLEDPRIVATE]);
#endif
m_Slots[SLOTS_FILLEDPUBLIC] = dwFilledPublicSlots;
m_Slots[SLOTS_FILLEDPRIVATE] = dwFilledPrivateSlots;
#ifdef _DEBUG
DebugSpew( "SetFilledSlotCounts(%016I64X): New: [%d, %d, %d, %d]\n",
XNKIDToInt64( m_SessionInfo.sessionID ),
m_Slots[SLOTS_TOTALPUBLIC],
m_Slots[SLOTS_TOTALPRIVATE],
m_Slots[SLOTS_FILLEDPUBLIC],
m_Slots[SLOTS_FILLEDPRIVATE]);
#endif
}
//------------------------------------------------------------------------
// Name: GetSessionError()
// Desc: Returns session error string
//------------------------------------------------------------------------
WCHAR* SessionManager::GetSessionError() const
{
return m_strSessionError;
}
//------------------------------------------------------------------------
// Name: SetSessionError()
// Desc: Sets session error string
//------------------------------------------------------------------------
VOID SessionManager::SetSessionError( WCHAR* error )
{
m_strSessionError = error;
}
//--------------------------------------------------------------------------------------
// Name: StartQoSListener()
// Desc: Turn on the Quality of Service Listener for the current session
//--------------------------------------------------------------------------------------
VOID SessionManager::StartQoSListener( BYTE* data, const UINT dataLen, const DWORD bitsPerSec )
{
DWORD flags = XNET_QOS_LISTEN_SET_DATA;
if( bitsPerSec )
{
flags |= XNET_QOS_LISTEN_SET_BITSPERSEC;
}
if( !m_bUsingQoS )
{
flags |= XNET_QOS_LISTEN_ENABLE;
}
DWORD dwRet;
dwRet = XNetQosListen( &( m_SessionInfo.sessionID ), data, dataLen, bitsPerSec, flags );
if( ERROR_SUCCESS != dwRet )
{
FatalError( "Failed to start QoS listener, error 0x%08x\n", dwRet );
}
m_bUsingQoS = TRUE;
}
//--------------------------------------------------------------------------------------
// Name: StopQoSListener()
// Desc: Turn off the Quality of Service Listener for the current session
//--------------------------------------------------------------------------------------
VOID SessionManager::StopQoSListener()
{
if( m_bUsingQoS )
{
DWORD dwRet;
dwRet = XNetQosListen( &( m_SessionInfo.sessionID ), NULL, 0, 0,
XNET_QOS_LISTEN_RELEASE );
if( ERROR_SUCCESS != dwRet )
{
DebugSpew( "Warning: Failed to stop QoS listener, error 0x%08x\n", dwRet );
}
m_bUsingQoS = FALSE;
}
}
//------------------------------------------------------------------------
// Name: CreateSession()
// Desc: Creates a session
//------------------------------------------------------------------------
HRESULT SessionManager::CreateSession( XOVERLAPPED* pXOverlapped )
{
// Make sure our instance is in the right state
SessionState actual = GetSessionState();
if( actual != SessionStateNone && actual != SessionStateDeleted )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
// Modify session flags if host
if( m_bIsHost )
{
m_dwSessionFlags |= XSESSION_CREATE_HOST;
}
else
{
// Turn off host bit
m_dwSessionFlags &= ~XSESSION_CREATE_HOST;
}
// If we're just in a Matchmaking session, we can only specify the
// XSESSION_CREATE_JOIN_IN_PROGRESS_DISABLED modifier
if( !( m_dwSessionFlags & XSESSION_CREATE_USES_PRESENCE ) &&
( m_dwSessionFlags & XSESSION_CREATE_USES_MATCHMAKING ) &&
( m_dwSessionFlags & XSESSION_CREATE_MODIFIERS_MASK ) )
{
// turn off all modifiers
m_dwSessionFlags &= ~XSESSION_CREATE_MODIFIERS_MASK;
// turn on XSESSION_CREATE_JOIN_IN_PROGRESS_DISABLED
m_dwSessionFlags |= XSESSION_CREATE_JOIN_IN_PROGRESS_DISABLED;
}
// Call XSessionCreate
DWORD ret = XSessionCreate( m_dwSessionFlags,
m_dwOwnerController,
m_Slots[SLOTS_TOTALPRIVATE],
m_Slots[SLOTS_TOTALPUBLIC],
&m_qwSessionNonce,
&m_SessionInfo,
pXOverlapped,
&m_hSession );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateCreating );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateCreated );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: StartSession()
// Desc: Starts the current session
//------------------------------------------------------------------------
HRESULT SessionManager::StartSession( XOVERLAPPED* pXOverlapped )
{
DWORD ret = XSessionStart( m_hSession,
0,
pXOverlapped );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateStarting );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateInGame );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: EndSession()
// Desc: Ends the current session
//------------------------------------------------------------------------
HRESULT SessionManager::EndSession( XOVERLAPPED* pXOverlapped )
{
DWORD ret = XSessionEnd( m_hSession, pXOverlapped );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateEnding );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateEnded );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: DeleteSession()
// Desc: Deletes the current session
//------------------------------------------------------------------------
HRESULT SessionManager::DeleteSession( XOVERLAPPED* pXOverlapped )
{
// Make sure our instance is in the right state
SessionState actual = GetSessionState();
if( actual < SessionStateCreated )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
SwitchToState( SessionStateDelete );
// Stop QoS listener if it's running
StopQoSListener();
// Call XSessionDelete
DWORD ret = XSessionDelete( m_hSession, pXOverlapped );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateDeleting );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateDeleted );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: MigrateSession()
// Desc: Migrates the current session
//------------------------------------------------------------------------
HRESULT SessionManager::MigrateSession( XOVERLAPPED* pXOverlapped )
{
// Make sure our instance is in the right state
SessionState actual = GetSessionState();
if( actual < SessionStateCreated || actual >= SessionStateDelete )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
m_migratedSessionState = m_SessionState;
DWORD ret = XSessionMigrateHost( m_hSession,
( m_bIsMigratedSessionHost ) ? m_dwOwnerController : XUSER_INDEX_NONE,
&m_NewSessionInfo,
pXOverlapped );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateMigratingHost );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateMigratedHost );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: ModifySessionFlags()
// Desc: Modifies session flags
//------------------------------------------------------------------------
HRESULT SessionManager::ModifySessionFlags( const DWORD dwFlags,
const BOOL bClearFlags,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( m_SessionState <= SessionStateCreating || m_SessionState >= SessionStateDelete )
{
FatalError( "SessionManager instance in invalid state: %s\n", g_astrSessionState[actual] );
}
DWORD dwNewFlags = dwFlags;
// If no flags in the modifiers mask are specified, do nothing
if( ( dwNewFlags & XSESSION_CREATE_MODIFIERS_MASK ) == 0 )
{
return ERROR_SUCCESS;
}
// Flags cannot be modified for arbitrated sessions
if( m_dwSessionFlags & XSESSION_CREATE_USES_ARBITRATION )
{
return ERROR_SUCCESS;
}
// Add host bit to dwFlags if host; otherwise remove
if( m_bIsHost )
{
dwNewFlags |= XSESSION_CREATE_HOST;
}
else
{
// Turn off host bit
dwNewFlags &= ~XSESSION_CREATE_HOST;
}
// Apply allowable session modifier flags to our session flags
if( bClearFlags )
{
m_dwSessionFlags ^= dwNewFlags & MODIFY_FLAGS_ALLOWED;
}
else
{
m_dwSessionFlags |= dwNewFlags & MODIFY_FLAGS_ALLOWED;
}
// Re-insert host bit if host
if( m_bIsHost )
{
m_dwSessionFlags |= XSESSION_CREATE_HOST;
}
DebugSpew( "ProcessModifySessionFlagsMessage: New session flags: %d\n", m_dwSessionFlags );
DWORD ret = XSessionModify( m_hSession,
m_dwSessionFlags,
m_Slots[SLOTS_TOTALPUBLIC],
m_Slots[SLOTS_TOTALPRIVATE],
pXOverlapped );
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: ModifySkill()
// Desc: Modifies TrueSkill(TM)
//------------------------------------------------------------------------
HRESULT SessionManager::ModifySkill( const DWORD dwNumXuids,
const XUID* pXuids,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( m_SessionState <= SessionStateCreating || m_SessionState >= SessionStateDelete )
{
FatalError( "SessionManager instance in invalid state: %s\n", g_astrSessionState[actual] );
}
DWORD ret = XSessionModifySkill( m_hSession,
dwNumXuids,
pXuids,
pXOverlapped );
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: RegisterArbitration()
// Desc: Registers the current session for arbitration
//------------------------------------------------------------------------
HRESULT SessionManager::RegisterArbitration( XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateCreated || actual >= SessionStateStarting )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
// Call once to determine size of results buffer
DWORD cbRegistrationResults = 0;
DWORD ret = XSessionArbitrationRegister( m_hSession,
0,
m_qwSessionNonce,
&cbRegistrationResults,
NULL,
NULL );
if( ( ret != ERROR_INSUFFICIENT_BUFFER ) || ( cbRegistrationResults == 0 ) )
{
DebugSpew( "Failed on first call to XSessionArbitrationRegister, hr=0x%08x\n", ret );
return ERROR_FUNCTION_FAILED;
}
m_pRegistrationResults = (PXSESSION_REGISTRATION_RESULTS)new BYTE[cbRegistrationResults];
if( m_pRegistrationResults == NULL )
{
DebugSpew( "Failed to allocate buffer.\n" );
return ERROR_FUNCTION_FAILED;
}
// Call second time to fill our results buffer
ret = XSessionArbitrationRegister( m_hSession,
0,
m_qwSessionNonce,
&cbRegistrationResults,
m_pRegistrationResults,
pXOverlapped );
if( pXOverlapped && ( ret == ERROR_IO_PENDING ) )
{
SwitchToState( SessionStateRegistering );
}
else if( !pXOverlapped )
{
SwitchToState( SessionStateRegistered );
}
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: AddLocalPlayers()
// Desc: Add local players to the session
//------------------------------------------------------------------------
HRESULT SessionManager::AddLocalPlayers( const DWORD dwUserCount,
DWORD* pdwUserIndices,
const BOOL* pfPrivateSlots,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateCreating || actual >= SessionStateDelete )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
DWORD ret = ERROR_SUCCESS;
// Do nothing if the session is already deleted
if( m_SessionState == SessionStateDeleted )
{
return HRESULT_FROM_WIN32( ret );
}
for ( DWORD i = 0; i < dwUserCount; ++i )
{
XUID xuid;
XUserGetXUID( pdwUserIndices[i], &xuid );
DebugSpew( "Processing local user: index: %d; xuid: 0x%016I64X; bInvited: %d\n",
pdwUserIndices[ i ], xuid, pfPrivateSlots[ i ] );
// If xuid is already in the session, don't re-add
if( IsPlayerInSession( xuid ) )
{
pdwUserIndices[ i ] = XUSER_INDEX_NONE;
}
}
ret = XSessionJoinLocal( m_hSession,
dwUserCount,
pdwUserIndices,
pfPrivateSlots,
pXOverlapped );
// Update slot counts
for ( DWORD i = 0; i < dwUserCount; ++i )
{
m_Slots[ SLOTS_FILLEDPRIVATE ] += ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_FILLEDPUBLIC ] += ( pfPrivateSlots[ i ] ) ? 0 : 1;
}
if( m_Slots[ SLOTS_FILLEDPRIVATE ] > m_Slots[ SLOTS_TOTALPRIVATE ] )
{
DWORD diff = m_Slots[ SLOTS_FILLEDPRIVATE ] - m_Slots[ SLOTS_TOTALPRIVATE ];
m_Slots[ SLOTS_FILLEDPUBLIC ] += diff;
assert( m_Slots[ SLOTS_FILLEDPUBLIC ] <= m_Slots[ SLOTS_TOTALPUBLIC ] );
if( m_Slots[ SLOTS_FILLEDPUBLIC ] > m_Slots[ SLOTS_TOTALPUBLIC ] )
{
FatalError( "Too many slots filled!\n" );
}
m_Slots[ SLOTS_FILLEDPRIVATE ] = m_Slots[ SLOTS_TOTALPRIVATE ];
}
DebugDumpSessionDetails();
DebugValidateExpectedSlotCounts();
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: AddRemotePlayers()
// Desc: Adds remote players to the session
//------------------------------------------------------------------------
HRESULT SessionManager::AddRemotePlayers( const DWORD dwXuidCount,
XUID* pXuids,
const BOOL* pfPrivateSlots,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateCreating || actual >= SessionStateDelete )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
for ( DWORD i=0; i<dwXuidCount; ++i )
{
DebugSpew( "AddRemotePlayers: 0x%016I64X; bInvited: %d\n", pXuids[ i ], pfPrivateSlots[ i ] );
}
DWORD ret = ERROR_SUCCESS;
// Do nothing if the session is already deleted
if( m_SessionState == SessionStateDeleted )
{
return HRESULT_FROM_WIN32( ret );
}
for ( DWORD i = 0; i < dwXuidCount; ++i )
{
DebugSpew( "Processing remote user: 0x%016I64X; bInvited: %d\n",
pXuids[ i ], pfPrivateSlots[ i ] );
// If msg.m_pXuids[ i ] is already in the session, don't re-add
if( IsPlayerInSession( pXuids[ i ] ) )
{
pXuids[ i ] = INVALID_XUID;
DebugSpew( "Remote user: 0x%016I64X already in the session!\n",
pXuids[ i ] );
}
}
ret = XSessionJoinRemote( m_hSession,
dwXuidCount,
pXuids,
pfPrivateSlots,
pXOverlapped );
// Update slot counts
for ( DWORD i = 0; i < dwXuidCount; ++i )
{
m_Slots[ SLOTS_FILLEDPRIVATE ] += ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_FILLEDPUBLIC ] += ( pfPrivateSlots[ i ] ) ? 0 : 1;
}
if( m_Slots[ SLOTS_FILLEDPRIVATE ] > m_Slots[ SLOTS_TOTALPRIVATE ] )
{
DWORD diff = m_Slots[ SLOTS_FILLEDPRIVATE ] - m_Slots[ SLOTS_TOTALPRIVATE ];
m_Slots[ SLOTS_FILLEDPUBLIC ] += diff;
assert( m_Slots[ SLOTS_FILLEDPUBLIC ] <= m_Slots[ SLOTS_TOTALPUBLIC ] );
if( m_Slots[ SLOTS_FILLEDPUBLIC ] > m_Slots[ SLOTS_TOTALPUBLIC ] )
{
FatalError( "Too many slots filled!\n" );
}
m_Slots[ SLOTS_FILLEDPRIVATE ] = m_Slots[ SLOTS_TOTALPRIVATE ];
}
DebugDumpSessionDetails();
DebugValidateExpectedSlotCounts();
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: RemoveLocalPlayers()
// Desc: Add local players to the session
//------------------------------------------------------------------------
HRESULT SessionManager::RemoveLocalPlayers( const DWORD dwUserCount,
const DWORD* pdwUserIndices,
const BOOL* pfPrivateSlots,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateCreated || actual >= SessionStateDelete )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
DWORD ret = ERROR_SUCCESS;
// Do nothing if the session is already deleted
if( m_SessionState == SessionStateDeleted )
{
return HRESULT_FROM_WIN32( ret );
}
#ifdef _DEBUG
for( DWORD i = 0; i < dwUserCount; ++i )
{
XUID xuid;
XUserGetXUID( i, &xuid );
DebugSpew( "%016I64X: ProcessRemoveLocalPlayerMessage: 0x%016I64X\n",
GetSessionIDAsInt(),
xuid );
}
#endif
ret = XSessionLeaveLocal( m_hSession,
dwUserCount,
pdwUserIndices,
pXOverlapped );
// If the session is arbitrated and gameplay is happening, then the player will still be
// kept in the session so stats can be reported, so we don't want to modify our slot counts
const BOOL bPlayersKeptForStatsReporting = ( ( m_dwSessionFlags & XSESSION_CREATE_USES_ARBITRATION ) &&
( m_SessionState == SessionStateInGame ) );
if( !bPlayersKeptForStatsReporting )
{
for ( DWORD i = 0; i < dwUserCount; ++i )
{
m_Slots[ SLOTS_FILLEDPRIVATE ] -= ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_FILLEDPUBLIC ] -= ( pfPrivateSlots[ i ] ) ? 0 : 1;
m_Slots[ SLOTS_FILLEDPRIVATE ] = max( m_Slots[ SLOTS_FILLEDPRIVATE ], 0 );
m_Slots[ SLOTS_FILLEDPUBLIC ] = max( m_Slots[ SLOTS_FILLEDPUBLIC ], 0 );
}
}
else
{
DebugSpew( "%016I64X: ProcessRemoveLocalPlayerMessage: Arbitrated session, so leaving players become zombies and not updating local slot counts\n",
GetSessionIDAsInt() );
for ( DWORD i = 0; i < dwUserCount; ++i )
{
m_Slots[ SLOTS_ZOMBIEPRIVATE ] += ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_ZOMBIEPUBLIC ] += ( pfPrivateSlots[ i ] ) ? 0 : 1;
}
}
DebugDumpSessionDetails();
DebugValidateExpectedSlotCounts();
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: RemoveRemotePlayers()
// Desc: Remove remote players to the session
//------------------------------------------------------------------------
HRESULT SessionManager::RemoveRemotePlayers( const DWORD dwXuidCount,
const XUID* pXuids,
const BOOL* pfPrivateSlots,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateCreated || actual >= SessionStateDelete )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
#ifdef _DEBUG
for( DWORD i = 0; i < dwXuidCount; ++i )
{
DebugSpew( "%016I64X: ProcessRemoveRemotePlayerMessage: 0x%016I64X\n",
GetSessionIDAsInt(),
pXuids[i] );
}
#endif
DWORD ret = XSessionLeaveRemote( m_hSession,
dwXuidCount,
pXuids,
pXOverlapped );
{
// If the session is arbitrated and gameplay is happening, then the player will still be
// kept in the session so stats can be reported, so we don't want to modify our slot counts
const BOOL bPlayersKeptForStatsReporting = ( ( m_dwSessionFlags & XSESSION_CREATE_USES_ARBITRATION ) &&
( m_SessionState == SessionStateInGame ) );
if( !bPlayersKeptForStatsReporting )
{
for ( DWORD i = 0; i < dwXuidCount; ++i )
{
m_Slots[ SLOTS_FILLEDPRIVATE ] -= ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_FILLEDPUBLIC ] -= ( pfPrivateSlots[ i ] ) ? 0 : 1;
m_Slots[ SLOTS_FILLEDPRIVATE ] = max( m_Slots[ SLOTS_FILLEDPRIVATE ], 0 );
m_Slots[ SLOTS_FILLEDPUBLIC ] = max( m_Slots[ SLOTS_FILLEDPUBLIC ], 0 );
}
}
else
{
DebugSpew( "%016I64X: ProcessRemoveRemotePlayerMessage: Arbitrated session, so leaving players become zombies and not updating local slot counts\n",
GetSessionIDAsInt() );
for ( DWORD i = 0; i < dwXuidCount; ++i )
{
m_Slots[ SLOTS_ZOMBIEPRIVATE ] += ( pfPrivateSlots[ i ] ) ? 1 : 0;
m_Slots[ SLOTS_ZOMBIEPUBLIC ] += ( pfPrivateSlots[ i ] ) ? 0 : 1;
}
}
}
DebugDumpSessionDetails();
DebugValidateExpectedSlotCounts();
return HRESULT_FROM_WIN32( ret );
}
//------------------------------------------------------------------------
// Name: WriteStats()
// Desc: Write stats for a player in the session
//------------------------------------------------------------------------
HRESULT SessionManager::WriteStats( const XUID xuid,
const DWORD dwNumViews,
const XSESSION_VIEW_PROPERTIES *pViews,
XOVERLAPPED* pXOverlapped )
{
SessionState actual = GetSessionState();
if( actual < SessionStateInGame || actual >= SessionStateEnding )
{
FatalError( "Wrong state: %s\n", g_astrSessionState[actual] );
}
DebugSpew( "%016I64X: ProcessWriteStatsMessage: 0x%016I64X\n",
GetSessionIDAsInt(),
xuid );
DWORD ret = XSessionWriteStats( m_hSession,
xuid,
dwNumViews,
pViews,
pXOverlapped );
return HRESULT_FROM_WIN32( ret );
}
| [
"[email protected]"
] | [
[
[
1,
1783
]
]
] |
7b9abfaff982a7716f4e2d5ed654156829fa2f97 | f47a5673793521f5e7efe2d0664b36d48b19ce0d | /libraries/AirSerial/AirSerial.cpp | 8b602d213cb52af1c2a9ed793485a36cff1fc58f | [] | no_license | Baseeball/lolosalarmclock | 9b2b8aaa19724e2dc02de5475c49d4bf949721c5 | 0f33a86b3b3771bf19021374e78c0a9f1e471790 | refs/heads/master | 2016-09-01T07:09:25.054932 | 2010-09-10T17:59:55 | 2010-09-10T17:59:55 | 55,884,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,183 | cpp | /*
AirSerial.cpp
*/
#include "AirSerial.h"
#define STARTSIGNALLENGTH 2
#define BEGINOFPACKET ((char)B10101010)
#define ENDOFPACKET ((char)B00000000)
//
// Constructor
//
AirSerial::AirSerial(HardwareSerial* _serial)
{
serial = _serial;
clearpacket();
}
//
// Destructor
//
AirSerial::~AirSerial()
{
end();
}
//
// Public methods
//
//
// initialize
//
void AirSerial::begin(long _speed)
{
speed = _speed;
serial->begin(speed);
clearpacket();
}
//
// de-initialize
//
void AirSerial::end()
{
}
void AirSerial::beginpacket()
{
check1=1;
check2=1;
check3=1;
check4=1;
for(int i=0; i<=(speed/1200); i++)
{
serial->print((char)B11111111);
serial->print((char)B11110000);
serial->print((char)B11100001);
serial->print((char)B11000011);
serial->print((char)B10000111);
serial->print((char)B11001100);
serial->print((char)B10011001);
serial->print((char)B10101010);
}/**/
for(int i=0; i<STARTSIGNALLENGTH; i++)
{
serial->print(BEGINOFPACKET);
}
}
void AirSerial::endpacket()
{
serial->print('$');
serial->print(check1);
serial->print(check2);
serial->print(check3);
serial->print(check4);
serial->print(ENDOFPACKET);
}
//
// This is a home-made checksum,
// it is not really good ....
//
void AirSerial::checksum(char b)
{
check1 ^= b+check4;
if(check1==ENDOFPACKET) check1=1;
check2 += check1^b;
if(check2==ENDOFPACKET) check2=1;
check3 = check3*b+check2;
if(check3==ENDOFPACKET) check3=1;
check4 = check4^(check3>>1);
if(check4==ENDOFPACKET) check4=1;
}
void AirSerial::write(uint8_t b)
{
checksum(b);
serial->Print::print(b);
};
void AirSerial::receive()
{
if (!available && serial->available())
{
if(nextbyte+1<BUFFERSIZE)
{
char receivedchar = (char)serial->read();
//Serial.print(receivedchar);
//Serial.print(" s:");
//Serial.println(state);
if(receivedchar==BEGINOFPACKET && state!=32)
{
state++;
//Serial.println((int)state);
}
else
{
if(state>=2)
{
//Serial.print("!!!!!!!!!!!!!!!!1");
state = 32;
}
else if(state>0 && state!=32)
{
state=0;
}
//Serial.println((int)state);
}
if(state==32)
{
//Serial.print(receivedchar);
buffer[nextbyte]=receivedchar;
nextbyte++;
if(receivedchar==ENDOFPACKET)
{
available=true;
overflow=false;
buffer[nextbyte-6]=0x00;// hide checksum;
}
}
}
else
{
available=true;
overflow=true;
buffer[BUFFERSIZE-1]=0x00; //has to be a null terminated string...
}
}
}
bool AirSerial::packetavailable()
{
return available;
};
bool validpayload(unsigned char byte)
{
//Serial.println((int)byte);
return (byte==9)||(byte==13)||(byte==11)||(byte==10)||(byte>=32 && byte<=126);
}
bool AirSerial::packetok()
{
for(int i=0; i<nextbyte-6; i++)
{
if(!validpayload(buffer[i]))
return false;
}
check1=1;
check2=1;
check3=1;
check4=1;
//Serial.print("'");
for(int i=0; i<nextbyte-6; i++)
{
//Serial.print(buffer[i]);
checksum(buffer[i]);
}
//Serial.print("'");
//Serial.println((int)xorcheck);
//Serial.println((int)sumcheck);
char packetcheck1 = buffer[nextbyte-5];
char packetcheck2 = buffer[nextbyte-4];
char packetcheck3 = buffer[nextbyte-3];
char packetcheck4 = buffer[nextbyte-2];
//Serial.println(packetxorcheck);
//Serial.println(packetsumcheck);
//Serial.println("packet checksum");
//Serial.println((int)packetxorcheck);
//Serial.println((int)packetsumcheck);
return (packetcheck1==check1)&&(packetcheck2==check2)&&(packetcheck3==check3)&&(packetcheck4==check4);
}
int AirSerial::packetlength()
{
return nextbyte;
}
bool AirSerial::packetoverflow()
{
return overflow;
}
char* AirSerial::getpacket()
{
return buffer;
}
void AirSerial::clearpacket()
{
state=0;
nextbyte=0;
available=false;
overflow=false;
check1=1;
check2=1;
check3=1;
check4=1;
}
| [
"LolosAlarmClock@c0386a1c-1ca0-4305-d708-b558a3e1b3b7"
] | [
[
[
1,
232
]
]
] |
d145711b461b4fd92852fb301f8cb889b4d81b93 | 28476e6f67b37670a87bfaed30fbeabaa5f773a2 | /src/AutumnGen/test/Class.h | 0e916df2d01548a8ba793491a9501dcc7f05014a | [] | no_license | rdmenezes/autumnframework | d1aeb657cd470b67616dfcf0aacdb173ac1e96e1 | d082d8dc12cc00edae5f132b7f5f6e0b6406fe1d | refs/heads/master | 2021-01-20T13:48:52.187425 | 2008-07-17T18:25:19 | 2008-07-17T18:25:19 | 32,969,073 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 90 | h |
class ClassA{
};
class ClassB{
};
class ClassA_1: public ClassA, ClassB{
};
| [
"sharplog@c16174ff-a625-0410-88e5-87db5789ed7d"
] | [
[
[
1,
10
]
]
] |
0b8419c2aee1abe1c48378d373f520d776314826 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/UrbanExtreme/inc/properties/bak1/ueplayerinputproperty_ldw.h | a4d46de2499148e125ef9f5337e73c9844421545 | [] | 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 | 883 | h | #ifndef PROPERTIES_UEPLAYERINPUTPRPERTY_H
#define PROPERTIES_UEPLAYERINPUTPRPERTY_H
#include "properties/inputproperty.h"
#include "msg/ueplayerkey.h"
namespace Properties
{
class Message::UePlayerKey;
class UePlayerInputProperty : public InputProperty
{
public:
DeclareRtti;
DeclareFactory(UePlayerInputProperty);
public:
///
UePlayerInputProperty();
///
virtual ~UePlayerInputProperty();
///
virtual void OnBeginFrame();
protected:
///
virtual void HandleInput();
///
void SendMove(const vector3& dir);
void SendTurn(const float dir);
void SendTurnTest(const float dir);
void SendTurnTest2(const vector3& dir);
void SendMoveDirection(const vector3& dir);
void SendRotate(const float angle);
protected:
nTime moveGotoTime;
};
RegisterFactory(UePlayerInputProperty);
};
#endif
| [
"ldw9981@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
] | [
[
[
1,
45
]
]
] |
5305d10b677b338fc33abc67605eb38b8cea5559 | 2e65def61753098295cc8fda3684ddc6dc62b099 | /Tooltip.cpp | d8610dd0f15f276f618719ca307a1f0ab89d63c2 | [] | no_license | JohnnyXiaoYang/wickedwidgets | 3bafd6dab9fa75028a80c0a158b8563e15f4c6c6 | 523b3875647dcd2015de4db8979e28460a126db2 | refs/heads/master | 2021-05-26T19:20:59.052458 | 2010-10-23T12:30:09 | 2010-10-23T12:30:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,643 | cpp | // Tooltip.cpp: implementation of the CTooltip class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Tooltip.h"
#include <windows.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CTooltip::CTooltip()
{
m_hWnd = NULL;
m_hwndParent = NULL;
}
CTooltip::~CTooltip()
{
}
void CTooltip::NotifyTooltip(UINT uMsg, long lParam, long wParam)
{
// call during WM_MOUSEMOVE, WM_LBUTTONDOWN, WM_LBUTTONUP
MSG msg;
msg.lParam = lParam;
msg.wParam = wParam;
msg.message = uMsg;
msg.hwnd = m_hwndParent;
SendMessage(m_hWnd, TTM_RELAYEVENT, 0,
(LPARAM) (LPMSG) &msg);
}
void CTooltip::CreateTooltip(POINT pt, TCHAR* pszTxt, HWND hwndParent)
{
TOOLINFO ti;
HINSTANCE hInst = _Module.m_hInst;
m_hWnd = CreateWindow(TOOLTIPS_CLASS, (LPSTR) NULL, TTS_ALWAYSTIP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, NULL, (HMENU) NULL, hInst, NULL);
if (m_hWnd == NULL)
return;
m_hwndParent = hwndParent;
// ScreenToClient(hwndParent, &pt);
ti.cbSize = sizeof(TOOLINFO);
ti.uFlags = 0;
ti.hwnd = m_hwndParent;
ti.hinst = hInst;
ti.uId = (UINT) 0;
ti.lpszText = pszTxt;
ti.rect.left = pt.x - 1;
ti.rect.top = pt.y - 1;
ti.rect.right = pt.x + 1;
ti.rect.bottom = pt.y + 1;
BOOL bResult = SendMessage(m_hWnd, TTM_ADDTOOL, 0, (LPARAM) (LPTOOLINFO) &ti);
_ASSERT(bResult);
} | [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
0f9f024c12dace6a1a06f35a5776c36dc6a8d2e1 | 1bbd5854d4a2efff9ee040e3febe3f846ed3ecef | /src/scrview/capturer.cpp | 0cf4bca3b347c5c768d1ed5b7079756808845ec3 | [] | no_license | amanuelg3/screenviewer | 2b896452a05cb135eb7b9eb919424fe6c1ce8dd7 | 7fc4bb61060e785aa65922551f0e3ff8423eccb6 | refs/heads/master | 2021-01-01T18:54:06.167154 | 2011-12-21T02:19:10 | 2011-12-21T02:19:10 | 37,343,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,452 | cpp | #include "capturer.h"
Capturer::Capturer(int fpm, QString format, int w, int h)
: fpm(fpm), format(format), w(w), h(h)
{
if (this->fpm < 0)
this->fpm = 0;
screens = new QList<ScreenList>;
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(work()));
}
void Capturer::work()
{
ScreenList *temp;
temp = new ScreenList();
temp->screen = new Screenshot(format, w, h);
temp->screen->newScreen();
temp->sent = false;
screens->append(*temp);
if (!screens->isEmpty())
{
if (screens->first().sent)
{
delete screens->takeFirst().screen;
}
}
}
void Capturer::start()
{
if (this->running == false)
{
this->running = true;
timer->start(int((fpm/60)*1000)); // start making screens, and putting them in screens list.
}
}
void Capturer::stop()
{
this->running = false;
timer->stop();
}
QByteArray* Capturer::getScreen()
{
screens->first().sent = true;
return screens->first().screen->getScreen();
}
bool Capturer::hasScreen()
{
if (screens->isEmpty()) { // if list is empty.
// qDebug() << "$$$$ empty list";
return false;
}
if (screens->first().sent) { // if first item from list is sent (not received yet, etc).
// qDebug() << "$$$$ sent list";
return false;
}
return true;
}
| [
"JuliusR@localhost"
] | [
[
[
1,
66
]
]
] |
8313347ae3507a546963fb8d09ca489eacf4bf79 | 6e4f9952ef7a3a47330a707aa993247afde65597 | /PROJECTS_ROOT/WireKeys/WP_asLINUX/WP_asLINUXHook/MyHook.cpp | fc050b423e9a458f3925c708a9ee5d8364a8db9e | [] | no_license | meiercn/wiredplane-wintools | b35422570e2c4b486c3aa6e73200ea7035e9b232 | 134db644e4271079d631776cffcedc51b5456442 | refs/heads/master | 2021-01-19T07:50:42.622687 | 2009-07-07T03:34:11 | 2009-07-07T03:34:11 | 34,017,037 | 2 | 1 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 5,910 | cpp | /////////////////////////////////////////////////////////////
// hooklib.c
// серверная часть
#define __GLOBAL_HOOK
#include <windows.h>
#include <stdio.h>
#include <memory.h>
#include "..\..\..\SmartWires\SystemUtils\Macros.h"
#pragma data_seg("Shared")
HHOOK g_hhook = NULL;
int shMem[2]={0,0};
BOOL bActive=0;
DWORD dwFlags=1;
DWORD dwWasMoved=0;
RECT rtLastDownPoint;
long lHookActive=0;
#pragma data_seg()
#pragma comment(linker, "/section:Shared,rws")
#define H_LA 0x001
#define H_LC 0x002
#define H_LW 0x004
#define H_LS 0x008
#define H_RA 0x010
#define H_RC 0x020
#define H_RW 0x040
#define H_RS 0x080
#define H_ANY 0x400
//--
#define H_RESTORE 0x0100
#define H_ROLLBACK 0x0200
#define H_RESTPROH 0x0400
HINSTANCE g_hinstDll = NULL;
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
BOOL bSwitchingOff=FALSE;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
g_hinstDll = (HINSTANCE)hModule;
bSwitchingOff=FALSE;
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
bSwitchingOff=TRUE;
break;
}
return TRUE;
}
#include "../../WKPlugin.h"
LRESULT WINAPI MsgHookProc( int code, WPARAM wParam, LPARAM lParam )
{
if (WKUtils::isWKUpAndRunning() && g_hhook && bActive && code==HC_ACTION && lParam!=0){
SimpleTracker lock(lHookActive);
LPMSG msg = (LPMSG)lParam;
if(dwFlags&H_ROLLBACK)
{
if(msg && (msg->message == WM_LBUTTONDOWN || msg->message == WM_NCLBUTTONDOWN)){
dwWasMoved=0;
HWND hFgw= ::GetForegroundWindow();
GetWindowRect(hFgw,&rtLastDownPoint);
}
if(msg && (msg->message == WM_RBUTTONDOWN || msg->message == WM_NCRBUTTONDOWN)){
if(dwWasMoved && GetAsyncKeyState(VK_LBUTTON)<0 && !(rtLastDownPoint.left==0 && rtLastDownPoint.top==0 && rtLastDownPoint.right==0 && rtLastDownPoint.bottom==0)){
dwWasMoved=0;
HWND hFgw= ::GetForegroundWindow();
::MoveWindow( hFgw, rtLastDownPoint.left, rtLastDownPoint.top, rtLastDownPoint.right-rtLastDownPoint.left, rtLastDownPoint.bottom-rtLastDownPoint.top, TRUE );
}
}
}
if(msg && (msg->message == WM_MOUSEMOVE || msg->message == WM_NCMOUSEMOVE)){
int oldX= shMem[0];
int oldY= shMem[1];
shMem[0]= (int)(msg->pt.x);
shMem[1]= (int)(msg->pt.y);
if( (msg->wParam & MK_LBUTTON)!=0 ){
BOOL bOK=TRUE;
if(dwFlags & H_ANY){
if((dwFlags & H_LA) || (dwFlags & H_RA)){
if(GetAsyncKeyState(VK_LMENU)>=0 && GetAsyncKeyState(VK_RMENU)>=0){
bOK=FALSE;
}
}
if((dwFlags & H_LS) || (dwFlags & H_RS)){
if(GetAsyncKeyState(VK_LSHIFT)>=0 && GetAsyncKeyState(VK_RSHIFT)>=0){
bOK=FALSE;
}
}
if((dwFlags & H_LC) || (dwFlags & H_RC)){
if(GetAsyncKeyState(VK_LCONTROL)>=0 && GetAsyncKeyState(VK_RCONTROL)>=0){
bOK=FALSE;
}
}
if((dwFlags & H_LW) || (dwFlags & H_RW)){
if(GetAsyncKeyState(VK_LWIN)>=0 && GetAsyncKeyState(VK_RWIN)>=0){
bOK=FALSE;
}
}
}else{
if((dwFlags & H_LA) && GetAsyncKeyState(VK_LMENU)>=0){
bOK=FALSE;
}
if((dwFlags & H_RA) && GetAsyncKeyState(VK_RMENU)>=0){
bOK=FALSE;
}
if((dwFlags & H_LS) && GetAsyncKeyState(VK_LSHIFT)>=0){
bOK=FALSE;
}
if((dwFlags & H_RS) && GetAsyncKeyState(VK_RSHIFT)>=0){
bOK=FALSE;
}
if((dwFlags & H_LC) && GetAsyncKeyState(VK_LCONTROL)>=0){
bOK=FALSE;
}
if((dwFlags & H_RC) && GetAsyncKeyState(VK_RCONTROL)>=0){
bOK=FALSE;
}
if((dwFlags & H_LW) && GetAsyncKeyState(VK_LWIN)>=0){
bOK=FALSE;
}
if((dwFlags & H_RW) && GetAsyncKeyState(VK_RWIN)>=0){
bOK=FALSE;
}
}
if(bOK){
RECT rct;
HWND hFgw= ::GetForegroundWindow();
if(dwFlags&H_RESTPROH){
if(::IsZoomed(hFgw)){
bOK=FALSE;
}
}
if(bOK){// Двинулось!
dwWasMoved=1;
::GetWindowRect( hFgw, &rct );
if(dwFlags&H_RESTORE){
if(::IsZoomed(hFgw)){
WINDOWPLACEMENT pl;
memset(&pl,0,sizeof(WINDOWPLACEMENT));
pl.length=sizeof(WINDOWPLACEMENT);
::GetWindowPlacement(hFgw,&pl);
pl.showCmd=SW_RESTORE;
memcpy(&pl.rcNormalPosition,&pl.ptMaxPosition,sizeof(pl.rcNormalPosition));
::SetWindowPlacement(hFgw,&pl);
}
}
::MoveWindow( hFgw, rct.left+msg->pt.x-oldX, rct.top+msg->pt.y-oldY, rct.right-rct.left, rct.bottom-rct.top, TRUE );
}
}
}
}
}
return CallNextHookEx( g_hhook, code, wParam, lParam );
}
BOOL WINAPI SetOptions(BOOL bEnable, DWORD dwInOutFlags)
{
bActive=bEnable;
dwFlags=dwInOutFlags;
return TRUE;
}
BOOL WINAPI InstallHook(BOOL bSet)
{
// Сбрасываем данные...
rtLastDownPoint.left=rtLastDownPoint.right=rtLastDownPoint.top=rtLastDownPoint.bottom=0;
// Работаем с хуком
BOOL fOk=FALSE;
if (bSet) {
g_hhook = NULL;
char szDLLPath[MAX_PATH]={0};GetModuleFileName(g_hinstDll,szDLLPath,sizeof(szDLLPath));HINSTANCE hDLL=LoadLibrary(szDLLPath);
g_hhook = SetWindowsHookEx(WH_GETMESSAGE, MsgHookProc, hDLL, 0);
fOk = (g_hhook != NULL);
if(g_hhook==NULL){
//FLOG3("SetWindowsHookEx failed! File=%s, line=%lu, err=%08X",__FILE__,__LINE__,GetLastError());
}
}else if(g_hhook!=NULL){
BOOL bNoNeedToWait=FALSE;
fOk=SmartUnhookWindowsHookEx(g_hhook,&bNoNeedToWait);
g_hhook=NULL;
if(!bNoNeedToWait){
long lCount=0;
while(lHookActive>0){
lCount++;
Sleep(20);
if(lCount>200){
//FLOG3("Hook wait failed! File=%s, line=%lu",__FILE__,__LINE__,0);
break;
}
}
}
}
return fOk;
}
| [
"wplabs@3fb49600-69e0-11de-a8c1-9da277d31688"
] | [
[
[
1,
204
]
]
] |
c96df5533f5683bbf30b743c3f19b95fe6faf88b | 3182b05c41f13237825f1ee59d7a0eba09632cd5 | /add/Others/LockFreeChunker.cpp | 6ebad3a48ea3ea41db017bd3ff6f7f395d2f7e8f | [] | no_license | adhistac/ee-client-2-0 | 856e8e6ce84bfba32ddd8b790115956a763eec96 | d225fc835fa13cb51c3e0655cb025eba24a8cdac | refs/heads/master | 2021-01-17T17:13:48.618988 | 2010-01-04T17:35:12 | 2010-01-04T17:35:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | cpp | //-----------------------------------------------------------------------------
// Element Engine
//
//-----------------------------------------------------------------------------
#include "LockFreeChunker.h"
#include <assert.h>
//----------------------------------------------------------------------------
namespace WL
{
DataChunker::DataChunker(S32 size)
{
chunkSize = size;
curBlock = new DataBlock(size);
curBlock->next = 0;
curBlock->curIndex = 0;
}
DataChunker::~DataChunker()
{
freeBlocks();
}
void *DataChunker::alloc(S32 size)
{
assert(size <= chunkSize);
if(!curBlock || size + curBlock->curIndex > chunkSize)
{
DataBlock *temp = new DataBlock(chunkSize);
temp->next = curBlock;
temp->curIndex = 0;
curBlock = temp;
}
void *ret = curBlock->data + curBlock->curIndex;
curBlock->curIndex += (size + 3) & ~3; // dword align
return ret;
}
DataChunker::DataBlock::DataBlock(S32 size)
{
data = new U8[size];
}
DataChunker::DataBlock::~DataBlock()
{
delete[] data;
}
void DataChunker::freeBlocks()
{
while(curBlock)
{
DataBlock *temp = curBlock->next;
delete curBlock;
curBlock = temp;
}
}
} | [
"[email protected]"
] | [
[
[
1,
60
]
]
] |
5fca4b04bb6308cd91994e35c3ab97d3ffd51a2a | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /Library/CId3Lib.cpp | 3a6a132d337026b02b55f496b4786c0b4a1cd4d4 | [] | no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10T13:11:23.176481 | 2011-04-14T11:04:17 | 2011-04-14T11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,352 | cpp | /*
CId3Lib.cpp
Classe d'interfaccia con la libreria id3lib (http://www.id3lib.org/) per info/tags sui files .mp3
Luca Piergentili, 21/06/03
[email protected]
*/
#include "env.h"
#include "pragma.h"
#include "macro.h"
#include "strings.h"
#include <string.h>
#include "window.h"
#include "win32api.h"
#include "mmaudio.h"
#include "CId3v1Tag.h"
#include "CId3Lib.h"
#include "traceexpr.h"
//#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT
//#define _TRACE_FLAG _TRFLAG_NOTRACE
#define _TRACE_FLAG _TRFLAG_NOTRACE
#define _TRACE_FLAG_INFO _TRFLAG_NOTRACE
#define _TRACE_FLAG_WARN _TRFLAG_NOTRACE
#define _TRACE_FLAG_ERR _TRFLAG_NOTRACE
#if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL))
#ifdef PRAGMA_MESSAGE_VERBOSE
#pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro")
#endif
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/*
CId3Lib()
*/
CId3Lib::CId3Lib(LPCSTR lpcszFileName /*= NULL*/)
{
memset(m_szYear,'\0',sizeof(m_szYear));
if(lpcszFileName)
Link(lpcszFileName);
}
/*
Link()
*/
BOOL CId3Lib::Link(LPCSTR lpcszFileName)
{
BOOL bRet = FALSE;
if(::FileExist(lpcszFileName) && striright(lpcszFileName,MP3_EXTENSION)==0)
bRet = CId3v1Tag::Link(lpcszFileName);
return(bRet);
}
| [
"[email protected]"
] | [
[
[
1,
57
]
]
] |
06d83868d7028e5cecf042a31b1eaab25ef462da | c02cb25416f1f32b1264792c256bc8e9ddb36463 | /CShatter.cpp | 000b4466cfd39ed3f6948e480334da0f6bd34b55 | [] | no_license | tronster/node | 230b60095202c9e8c7459c570d1d6b1689730786 | ea14fc32bbbadf24549f693b3cd52b7423fc4365 | refs/heads/master | 2016-09-05T22:32:32.820092 | 2011-07-12T23:29:48 | 2011-07-12T23:29:48 | 2,039,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,240 | cpp | #pragma warning(disable:4786)
#include <stdio.h> // Header File For Standard Input/Output
#include <stdlib.h> // Header has rand()
#include "CShatter.h"
#include "loaders3d.h" // Object and texture loaders header
using namespace geoGL;
using namespace std;
#define BREAKSTART 0 // Time before tiles start breaking up
#define BREAKTIME 10000
/******************************** Non-members *********************************/
// Random floating point number 0-1
static inline float frand01() { return rand() / static_cast<float>(RAND_MAX); }
// Random floating point number -1 and 1
static inline float frand11() { return (rand()/ static_cast<float>(RAND_MAX)) * 2 - 1; }
// Generic min/max routines
template <class T> static inline T TMAX(T T1, T T2) { return (T1>T2 ? T1 : T2); }
template <class T> static inline T TMIN(T T1, T T2) { return (T1<T2 ? T1 : T2); }
// Compute animation factor 0..1
static float calcFactor(unsigned int nElapsedTime, unsigned int nStartTime, unsigned int nDuration)
{
if (nElapsedTime<nStartTime) return 0;
if (nElapsedTime>nStartTime+nDuration) return 1;
return static_cast<float>(nElapsedTime-nStartTime) / nDuration;
}
/*********************************** CShatter ***********************************/
CShatter::CShatter(CEnvInfo *pEnvInfo)
: m_oEnvInfo(*pEnvInfo)
{
eShatterType = eSHATTER_TUNNEL;
szSourceFile = NULL;
fRotation = 0;
bClearDepth = false;
}
void CShatter::setShatterOptions(char *szSetName, float fSetRotation, int eSetShatterType, bool bSetClear)
{
eShatterType = eSetShatterType;
szSourceFile = szSetName;
fRotation = fSetRotation;
bClearDepth = bSetClear;
}
CShatter::~CShatter() {
unInit();
}
bool CShatter::start()
{
if (!szSourceFile)
SnarfScreenTiles(); // Grab the screen at start if not coming from a file
initGLstuff(); // Initialize opengl settings
// Setup perspective matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, 4.0f/3.0f, 0.2f,270.0f); // force 4/3 aspect ratio even if the window is stretched
// Start time
nTimeStart = m_oEnvInfo.getMusicTime();
return true;
}
bool CShatter::stop()
{
light0.off();
return true;
}
bool CShatter::init()
{
initObjects(); // Initialize objects, textures, camera...
if (szSourceFile)
SnarfScreenTiles(); // Load the screen at init if coming from a file
return true;
}
bool CShatter::unInit()
{
/* ???wHG CRASHING???
// Deallocate the background tiles, objects creating it, and the source image
objCube.clear();
objCubePos.clear();
objCubeSpeed.clear();
tileBG.clear();
imageBG.destroy();
*/
return true;
}
//
// Create objects, load texture, setup video parameters
//
bool CShatter::initGLstuff() // All Setup For OpenGL Goes Here
{
// OpenGL setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glEnable(GL_CULL_FACE);
// glEnable(GL_NORMALIZE);
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glDepthFunc(GL_LEQUAL); // Allows blends to be drawn
glEnable(GL_LIGHTING);
// Light setup
for (int i=0; i<8; i++)
glDisable(GL_LIGHT0+i);
Light3D::setSceneAmbient(fRGBA(0,0,0,0));
light0.setLight(1.0f,1.0f,1.0f,1);
light0.position(0.0f,0.0f,35.0f);
light0.on();
return true;
}
bool CShatter::initObjects()
{
// Camera setup
cam.position(0,0,27);
return true;
}
bool CShatter::renderFrame()
{
glFinish();
if (bClearDepth)
glClear(GL_DEPTH_BUFFER_BIT);
// Setup camera
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
cam.execute();
// Setup light
light0.executeLight();
// Do this stuff 'cuz Tronster's routines change it
glEnable(GL_CULL_FACE); // Why is this off?
glColor3f(1,1,1); // Get rid of existing colormaterial settings
glDisable(GL_COLOR_MATERIAL); // This messes me up 'cuz I use glMaterial()
glDisable(GL_BLEND); // Sparkles leave blending on
glEnable(GL_LIGHTING); // Sparkles turn this off too
// Draw the tiles
glPushMatrix();
glScalef(1.45f,1.45f,1);
for (int nObj=0; nObj<tileBG.getNumTiles(); nObj++)
objCube[nObj].execute();
glPopMatrix();
glEnd();
glFlush();
return true;
}
bool CShatter::advanceFrame() {
// Grab elapsed time
nElapsedTime = m_oEnvInfo.getMusicTime() - nTimeStart;
// Breakup motions
int nObj;
// This code is inconsistent:
// For eSHATTER_BACKWARD the "absolute" time model is used.
// For others, the "incremental" time model is used.
// Using absolute time is needed here because deviation in position is unnacceptable
if (nElapsedTime>BREAKSTART && nElapsedTime<=BREAKSTART+BREAKTIME)
{
if (eShatterType == eSHATTER_BACKWARD)
{
float fFactor = calcFactor(nElapsedTime,BREAKSTART,BREAKTIME);
glRotatef((1-fFactor)*360,0,0,1);
for (nObj=0; nObj<tileBG.getNumTiles(); nObj++) {
objCube[nObj].position.z = objCubePos[nObj].z * (1-fFactor);
objCube[nObj].direction = fVector3D(0,45,0) * (1-fFactor); //???WHG 45 should come from setShade...
}
}
else // !eSHATTER_BACKWARD
{
for (nObj=0; nObj<tileBG.getNumTiles(); nObj++)
{
objCube[nObj].position += objCubeSpeed[nObj] * m_oEnvInfo.fFrameFactor;
objCube[nObj].direction+= fVector3D(0,0,fRotation * m_oEnvInfo.fFrameFactor);
}
}
}
return true;
}
// Snarfs the screen as a 640x480x24 bit Cimage
void CShatter::SnarfScreenImage()
{
int nWidth, nHeight; // Screen dimensions
md::Cimage imageLarge; // Image at current screen resolution
md::Cimage &imageSmall = imageBG; // Image at 640x480 for tiling
nWidth = m_oEnvInfo.nWinWidth;
nHeight= m_oEnvInfo.nWinHeight;
imageLarge.create(nWidth,nHeight,3);
imageSmall.create(640,512,3); // 640x512 fits with a 64x64 tile size
// Grab the full scree into an image
glColor3f(1,1,1);
glReadPixels(0,0, nWidth,nHeight,
GL_RGB,GL_UNSIGNED_BYTE,
imageLarge.data);
// Now scale it to 640x480
gluScaleImage(GL_RGB,nWidth,nHeight,GL_UNSIGNED_BYTE, imageLarge.data,
640,480,GL_UNSIGNED_BYTE,imageSmall.data);
}
// Snarf the image and place it on tiles
void CShatter::SnarfScreenTiles()
{
// Texture setup
if (szSourceFile == NULL)
{
// METHOD 1: This will snarf the image from the screen.
// It is very slow and causes the music to skip
SnarfScreenImage();
}
else
{
// METHOD 2: Grab the image from mediaduke
if (!m_oEnvInfo.oMedia.read(szSourceFile,imageBG))
{
char message[100];
sprintf(message,"Unable to load shatter image %s",szSourceFile);
throw message;
}
}
tileBG.setImage(&imageBG);
tileBG.setTileSize(64);
tileBG.createTiles();
imageBG.destroy(); // Don't need this anymore
// Create cubes for background
objCube.refnew (tileBG.getNumTiles());
objCubeSpeed.refnew(tileBG.getNumTiles());
objCubePos.refnew (tileBG.getNumTiles());
int nTile=0;
int numX = tileBG.getTilesX();
int numY = tileBG.getTilesY();
for (int x=0; x<numX; x++)
for (int y=0; y<numY; y++) {
objCubePos[nTile] = fVector3D(-numX + x*2,-numY + y*2,0);
switch(eShatterType) {
case eSHATTER_RANDOM:
objCubeSpeed[nTile] = fVector3D(0,0, frand01() * 0.1f + .05f);
break;
case eSHATTER_BACKWARD:
objCubePos[nTile] += fVector3D(0,0,frand01() * 70 + 25);
break;
case eSHATTER_TUNNEL:
objCubeSpeed[nTile] = fVector3D(0,0, (0.5f * (fabs(1.0f * numX/2 - x) + fabs(1.0f * numY/2 - y))) * 0.1f + .05f);
break;
default:
throw "CShatter: Somebody gave me a crazy value!";
}
if (eShatterType == eSHATTER_TUNNEL)
{
if (x==numX/2 && y==numY/2) {
objCubeSpeed[nTile] = fVector3D(-0.06f,-0.06f,-0.06f);
}
if (x==numX/2+1 && y==numY/2) {
objCubeSpeed[nTile] = fVector3D(+0.06f,-0.06f,-0.06f);
}
if (x==numX/2 && y==numY/2+1) {
objCubeSpeed[nTile] = fVector3D(-0.06f,+0.06f,-0.06f);
}
if (x==numX/2+1 && y==numY/2+1) {
objCubeSpeed[nTile] = fVector3D(+0.06f,+0.06f,-0.06f);
}
}
objCube[nTile] = Load3SO("data.md/cube1tex.3so",NULL,false);
objCube[nTile].objects[0].nTextureID = tileBG.textures[nTile];
objCube[nTile].position = objCubePos[nTile];
nTile++;
}
} | [
"[email protected]"
] | [
[
[
1,
297
]
]
] |
d3131c28065be400e6fce40d89cecfc76804b689 | fe122f81ca7d6dff899945987f69305ada995cd7 | /DB/dbAx/CardFile/AxVariableSet.hpp | 1d544656c5414bbdbc74305c07e2c09fd74234a4 | [] | no_license | myeverytime/chtdependstoreroom | ddb9f4f98a6a403521aaf403d0b5f2dc5213f346 | 64a4d1e2d32abffaab0376f6377e10448b3c5bc3 | refs/heads/master | 2021-01-10T06:53:35.455736 | 2010-06-23T10:21:44 | 2010-06-23T10:21:44 | 50,168,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,980 | hpp | /**************************************************************************
File: AxVariableSet.hpp
Date: 11/19/2007
By: Data Management Systems (www.dmsic.com)
DESCRIPTION
The following source code was generated using the AxGen utility and is
intended to be used in conjunction with the dbAx library. This class
facilitates the exchange of data with the ADO data source from which
it was derived.
Table: ENGR1-FS\WBF_Vault\Variable
Include this file in your project.
DISCLAIMER
This source code is provided AS-IS with no warranty as to its
suitability or usefulness in any application in which it may be used.
**************************************************************************/
#pragma once
#include <AxLib.h>
using namespace dbAx;
class CAxVariableSet :
public CAxRecordset
{
public:
CAxVariableSet() { _SetDefaults(); }
~CAxVariableSet() { }
int m_iVariableID;
CString m_szVariableName;
int m_iVariableType;
BOOL m_bIsDeleted;
BOOL m_bFlagUnique;
BOOL m_bFlagMandatory;
//Set default values of class members
void _SetDefaults()
{
m_iVariableID = 0;
m_szVariableName = _T("");
m_iVariableType = 0;
m_bIsDeleted = FALSE;
m_bFlagUnique = FALSE;
m_bFlagMandatory = FALSE;
};
//Exchange field values with data provider
void DoFieldExchange(BOOL bSave = FALSE)
{
FX_Integer (bSave, _T("VariableID"), m_iVariableID);
FX_NVarChar (bSave, _T("VariableName"), m_szVariableName);
FX_Integer (bSave, _T("VariableType"), m_iVariableType);
FX_Bool (bSave, _T("IsDeleted"), m_bIsDeleted);
FX_Bool (bSave, _T("FlagUnique"), m_bFlagUnique);
FX_Bool (bSave, _T("FlagMandatory"), m_bFlagMandatory);
};
};
| [
"robustwell@bd7e636a-136b-06c9-ecb0-b59307166256"
] | [
[
[
1,
61
]
]
] |
a06412b9eae2898a62956889a765cbaf2f7c3a71 | 6c8c4728e608a4badd88de181910a294be56953a | /RexLogicModule/EntityComponent/EC_OpenSimAvatar.cpp | 4e3f2ccaeef22425bafc98fa3e014137b7d4570d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,248 | cpp | // For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "ModuleInterface.h"
#include "EntityComponent/EC_OpenSimAvatar.h"
namespace RexLogic
{
EC_OpenSimAvatar::EC_OpenSimAvatar(Foundation::ModuleInterface* module) : Foundation::ComponentInterface(module->GetFramework()), controlflags(0), yaw(0)
{
state_ = Stand;
}
EC_OpenSimAvatar::~EC_OpenSimAvatar()
{
}
void EC_OpenSimAvatar::SetAppearanceAddress(const std::string &address, bool overrideappearance)
{
if(overrideappearance)
avatar_override_address_ = address;
else
{
avatar_address_ = address;
avatar_override_address_ = std::string();
}
}
const std::string& EC_OpenSimAvatar::GetAppearanceAddress() const
{
if(avatar_override_address_.length() > 0)
return avatar_override_address_;
else
return avatar_address_;
}
void EC_OpenSimAvatar::SetState(State state)
{
state_ = state;
}
EC_OpenSimAvatar::State EC_OpenSimAvatar::GetState() const
{
return state_;
}
}
| [
"tuco@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3",
"cmayhem@5b2332b8-efa3-11de-8684-7d64432d61a3",
"cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3"
] | [
[
[
1,
3
],
[
6,
8
],
[
10,
10
],
[
12,
22
],
[
24,
24
],
[
27,
28
],
[
30,
33
],
[
45,
45
]
],
[
[
4,
4
]
],
[
[
5,
5
]
],
[
[
9,
9
],
[
46,
46
]
],
[
[
11,
11
],
[
23,
23
],
[
25,
26
],
[
29,
29
],
[
34,
44
]
]
] |
11c5f1196cfc1115800fe24b1dfe64594fb65d13 | fc5bb350fbdf6c401e67eca6bdf2072d8ea4c7fb | /Box2D/Dynamics/b2WorldCallbacks.h | 5aeb201476d9130d8fb55c542aead2827d018982 | [] | no_license | explo/wck | 70b90298f8e1ff7487eb26b24c1d331ed3559552 | 5c503312140f7ff645fcd503023ae9da7735cafc | refs/heads/master | 2020-02-26T16:23:20.712202 | 2010-04-30T21:28:10 | 2010-04-30T21:28:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,084 | h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_WORLD_CALLBACKS_H
#define B2_WORLD_CALLBACKS_H
#include <Box2D/Common/b2Settings.h>
struct b2Vec2;
struct b2Transform;
class b2Fixture;
class b2Body;
class b2Joint;
class b2Contact;
struct b2ContactPoint;
struct b2ContactResult;
struct b2Manifold;
/// Joints and fixtures are destroyed when their associated
/// body is destroyed. Implement this listener so that you
/// may nullify references to these joints and shapes.
class b2DestructionListener
{
public:
virtual ~b2DestructionListener() {}
/// Called when any joint is about to be destroyed due
/// to the destruction of one of its attached bodies.
virtual void SayGoodbye(b2Joint* joint) = 0;
/// Called when any fixture is about to be destroyed due
/// to the destruction of its parent body.
virtual void SayGoodbye(b2Fixture* fixture) = 0;
};
/// Implement this class to provide collision filtering. In other words, you can implement
/// this class if you want finer control over contact creation.
class b2ContactFilter
{
public:
virtual ~b2ContactFilter() {}
/// Return true if contact calculations should be performed between these two shapes.
/// @warning for performance reasons this is only called when the AABBs begin to overlap.
virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB);
/// Return true if the given shape should be considered for ray intersection
virtual bool RayCollide(void* userData, b2Fixture* fixture);
};
/// Contact impulses for reporting. Impulses are used instead of forces because
/// sub-step forces may approach infinity for rigid body collisions. These
/// match up one-to-one with the contact points in b2Manifold.
struct b2ContactImpulse
{
float32 normalImpulses[b2_maxManifoldPoints];
float32 tangentImpulses[b2_maxManifoldPoints];
};
/// Implement this class to get contact information. You can use these results for
/// things like sounds and game logic. You can also get contact results by
/// traversing the contact lists after the time step. However, you might miss
/// some contacts because continuous physics leads to sub-stepping.
/// Additionally you may receive multiple callbacks for the same contact in a
/// single time step.
/// You should strive to make your callbacks efficient because there may be
/// many callbacks per time step.
/// @warning You cannot create/destroy Box2D entities inside these callbacks.
class b2ContactListener
{
public:
virtual ~b2ContactListener() {}
/// Called when two fixtures begin to touch.
virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); }
/// Called when two fixtures cease to touch.
virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); }
/// This is called after a contact is updated. This allows you to inspect a
/// contact before it goes to the solver. If you are careful, you can modify the
/// contact manifold (e.g. disable contact).
/// A copy of the old manifold is provided so that you can detect changes.
/// Note: this is called only for awake bodies.
/// Note: this is called even when the number of contact points is zero.
/// Note: this is not called for sensors.
/// Note: if you set the number of contact points to zero, you will not
/// get an EndContact callback. However, you may get a BeginContact callback
/// the next step.
virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
B2_NOT_USED(contact);
B2_NOT_USED(oldManifold);
}
/// This lets you inspect a contact after the solver is finished. This is useful
/// for inspecting impulses.
/// Note: the contact manifold does not include time of impact impulses, which can be
/// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly
/// in a separate data structure.
/// Note: this is only called for contacts that are touching, solid, and awake.
virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
{
B2_NOT_USED(contact);
B2_NOT_USED(impulse);
}
};
/// Callback class for AABB queries.
/// See b2World::Query
class b2QueryCallback
{
public:
virtual ~b2QueryCallback() {}
/// Called for each fixture found in the query AABB.
/// @return false to terminate the query.
virtual bool ReportFixture(b2Fixture* fixture) = 0;
};
/// Callback class for ray casts.
/// See b2World::RayCast
class b2RayCastCallback
{
public:
virtual ~b2RayCastCallback() {}
/// Called for each fixture found in the query. You control how the ray proceeds
/// by returning a float that indicates the fractional length of the ray. By returning
/// 0, you set the ray length to zero. By returning the current fraction, you proceed
/// to find the closest point. By returning 1, you continue with the original ray
/// clipping.
/// @param fixture the fixture hit by the ray
/// @param point the point of initial intersection
/// @param normal the normal vector at the point of intersection
/// @return 0 to terminate, fraction to clip the ray for
/// closest hit, 1 to continue
virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point,
const b2Vec2& normal, float32 fraction) = 0;
};
/// Color for debug drawing. Each value has the range [0,1].
struct b2Color
{
b2Color() {}
b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {}
void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; }
float32 r, g, b;
};
/// Implement and register this class with a b2World to provide debug drawing of physics
/// entities in your game.
class b2DebugDraw
{
public:
b2DebugDraw();
virtual ~b2DebugDraw() {}
enum
{
e_shapeBit = 0x0001, ///< draw shapes
e_jointBit = 0x0002, ///< draw joint connections
e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes
e_pairBit = 0x0008, ///< draw broad-phase pairs
e_centerOfMassBit = 0x0010, ///< draw center of mass frame
};
/// Set the drawing flags.
void SetFlags(uint32 flags);
/// Get the drawing flags.
uint32 GetFlags() const;
/// Append flags to the current flags.
void AppendFlags(uint32 flags);
/// Clear flags from the current flags.
void ClearFlags(uint32 flags);
/// Draw a closed polygon provided in CCW order.
virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0;
/// Draw a solid closed polygon provided in CCW order.
virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0;
/// Draw a circle.
virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0;
/// Draw a solid circle.
virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0;
/// Draw a line segment.
virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0;
/// Draw a transform. Choose your own length scale.
/// @param xf a transform.
virtual void DrawTransform(const b2Transform& xf) = 0;
public:
uint32 m_drawFlags;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
219
]
]
] |
d8a1bcd767d95042dae5dfeb9a85c88f23f37597 | 105cc69f4207a288be06fd7af7633787c3f3efb5 | /HovercraftUniverse/Utils/PlayerMapImpl.h | 9d18757650d7afe1e6bb38002089f5f93f08d57c | [] | no_license | allenjacksonmaxplayio/uhasseltaacgua | 330a6f2751e1d6675d1cf484ea2db0a923c9cdd0 | ad54e9aa3ad841b8fc30682bd281c790a997478d | refs/heads/master | 2020-12-24T21:21:28.075897 | 2010-06-09T18:05:23 | 2010-06-09T18:05:23 | 56,725,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,867 | h | namespace HovUni {
template<typename Key, typename Player, bool Unique>
PlayerMap<Key, Player, Unique>::PlayerMap() :
mOwnPlayer(0) {
}
template<typename Key, typename Player, bool Unique>
PlayerMap<Key, Player, Unique>::~PlayerMap() {
}
template<typename Key, typename Player, bool Unique>
void PlayerMap<Key, Player, Unique>::addPlayer(const Key& key, Player* player, bool ownPlayer) {
if (Unique) {
removePlayerByKey(key);
}
// Insert the player at the back
mPlayers.push_back(std::pair<Key, Player*>(key, player));
// Set own player
if (ownPlayer) {
mOwnPlayer = player;
}
}
template<typename Key, typename Player, bool Unique>
void PlayerMap<Key, Player, Unique>::removePlayerByKey(const Key& key) {
list_type::iterator it = find(key);
removePlayerByIterator(it);
}
template<typename Key, typename Player, bool Unique>
typename PlayerMap<Key, Player, Unique>::list_type::iterator PlayerMap<Key, Player, Unique>::removePlayerByIterator(
typename list_type::iterator it) {
// Delete the player
delete it->second;
// Remove from the list
return mPlayers.erase(it);
}
template<typename Key, typename Player, bool Unique>
Player* PlayerMap<Key, Player, Unique>::getPlayer(const Key& key) const {
list_type::const_iterator it = find(key);
Player* ret = 0;
if (it != mPlayers.end()) {
ret = it->second;
}
return ret;
}
template<typename Key, typename Player, bool Unique>
typename PlayerMap<Key, Player, Unique>::list_type::iterator PlayerMap<Key, Player, Unique>::find(const Key& key) {
for (list_type::iterator it = mPlayers.begin(); it != mPlayers.end(); ++it) {
if (it->first == key) {
return it;
}
}
return mPlayers.end();
}
template<typename Key, typename Player, bool Unique>
typename PlayerMap<Key, Player, Unique>::list_type::const_iterator PlayerMap<Key, Player, Unique>::find(const Key& key) const {
for (list_type::const_iterator it = mPlayers.begin(); it != mPlayers.end(); ++it) {
if (it->first == key) {
return it;
}
}
return mPlayers.end();
}
template<typename Key, typename Player, bool Unique>
typename PlayerMap<Key, Player, Unique>::list_type::iterator PlayerMap<Key, Player, Unique>::begin() {
return mPlayers.begin();
}
template<typename Key, typename Player, bool Unique>
typename PlayerMap<Key, Player, Unique>::list_type::const_iterator PlayerMap<Key, Player, Unique>::begin() const {
return mPlayers.begin();
}
template<typename Key, typename Player, bool Unique>
typename PlayerMap<Key, Player, Unique>::list_type::iterator PlayerMap<Key, Player, Unique>::end() {
return mPlayers.end();
}
template<typename Key, typename Player, bool Unique>
typename PlayerMap<Key, Player, Unique>::list_type::const_iterator PlayerMap<Key, Player, Unique>::end() const {
return mPlayers.end();
}
}
| [
"berghmans.olivier@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c"
] | [
[
[
1,
93
]
]
] |
976a2084c54d38c7898c623018d09e785a67cd15 | 78fb44a7f01825c19d61e9eaaa3e558ce80dcdf5 | /guceCORE/include/CVFSHandleToDataStream.h | 7735102fdc036430cccf012e449e8cbf43bd4433 | [] | no_license | LiberatorUSA/GUCE | a2d193e78d91657ccc4eab50fab06de31bc38021 | a4d6aa5421f8799cedc7c9f7dc496df4327ac37f | refs/heads/master | 2021-01-02T08:14:08.541536 | 2011-09-08T03:00:46 | 2011-09-08T03:00:46 | 41,840,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,742 | h | /*
* guceCORE: GUCE module providing tie-in functionality between systems
* Copyright (C) 2002 - 2008. Dinand Vanvelzen
*
* 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.
*
* 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
*/
#ifndef GUCE_CORE_CVFSHANDLETODATASTREAM_H
#define GUCE_CORE_CVFSHANDLETODATASTREAM_H
/*-------------------------------------------------------------------------//
// //
// INCLUDES //
// //
//-------------------------------------------------------------------------*/
#ifndef GUCE_CORE_CIOACCESSTODATASTREAM_H
#include "CIOAccessToDataStream.h" /* CIOAccess to an Ogre DataStream adapter */
#define GUCE_CORE_CIOACCESSTODATASTREAM_H
#endif /* GUCE_CORE_CIOACCESSTODATASTREAM_H ? */
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GUCEF { namespace VFS { class CVFSHandle; } }
/*-------------------------------------------------------------------------*/
namespace GUCE {
namespace CORE {
/*-------------------------------------------------------------------------//
// //
// CLASSES //
// //
//-------------------------------------------------------------------------*/
/**
* Allows Ogre to use gucefVFS handles.
* The handled resource will be unloaded when the stream object is destroyed.
*/
class GUCE_CORE_EXPORT_CPP CVFSHandleToDataStream : public CIOAccessToDataStream
{
public:
typedef GUCEF::VFS::CVFS::CVFSHandlePtr CVFSHandlePtr;
/**
* Constructs an Ogre DataStream capable of using an
* gucefVFS handle as input.
*/
CVFSHandleToDataStream( CVFSHandlePtr& vfshandle ,
bool freeonclose = false );
CVFSHandleToDataStream( const CVFSHandleToDataStream& src );
/**
* Unloads the resource pointed to by the file handle
* given upon construction.
*/
virtual ~CVFSHandleToDataStream();
virtual void close( void );
private:
CVFSHandlePtr m_fh;
bool m_freeonclose;
};
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
} /* namespace CORE ? */
} /* namespace GUCE ? */
/*-------------------------------------------------------------------------*/
#endif /* GUCE_CORE_CVFSHANDLETODATASTREAM_H ? */
/*-------------------------------------------------------------------------//
// //
// Info & Changes //
// //
//-------------------------------------------------------------------------//
- 12-02-2005 :
- Initial implementation
-----------------------------------------------------------------------------*/
| [
"[email protected]"
] | [
[
[
1,
107
]
]
] |
31e37f1259df7df0d0ccbf0b25a4f9f7fe3edf24 | c94135316a6706e7a1131e810222c12910cb8495 | /MarbleMadness/PantallaPausa.h | 2551d48667495f2793556586403c1b394bfa10ce | [] | no_license | lcianelli/compgraf-marble-madness | 05d2e8f23adf034723dd3d1267e7cdf6350cf5e7 | f3e79763b43a31095ffeff49f440c24614db045b | refs/heads/master | 2016-09-06T14:20:10.951974 | 2011-05-28T21:10:48 | 2011-05-28T21:10:48 | 32,283,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,082 | h | #pragma once
#ifndef PANTALLA_PAUSA_H
#define PANTALLA_PAUSA_H
#include "Juego.h"
#include "EstadoVisual.h"
#include "Nivel.h"
#include "HUD.h"
#include "BotonGUI.h"
#include "MenuGUI.h"
#include "ManejadorTextura.h"
using namespace mmgui;
class PantallaPausa :
public EstadoVisual
{
private:
bool mouseDown;
SDL_Surface* s;
BotonGUI* resumeBtn;
BotonGUI* opcionesBtn;
BotonGUI* salirBtn;
BotonGUI* reiniciarBtn;
MenuGUI* menuPausa;
protected:
Nivel* nivelActual;
HUD* hud;
void dibujar();
void actualizar(int tiempo);
void procesarEventos();
void handleKeyDown(SDL_keysym* keysym);
void handleMouseDown(const SDL_MouseButtonEvent &ev);
void handleMouseMoved(const SDL_MouseMotionEvent &ev);
void handleMouseUp(const SDL_MouseButtonEvent &ev);
public:
inline void setNivel(Nivel* nivel) { this->nivelActual = nivel; }
inline void setHud(HUD* hud) { this->hud = hud;}
void inicializar();
void cambiarNivel();
void resumir();
PantallaPausa(void);
~PantallaPausa(void);
};
#endif PANTALLA_PAUSA_H; | [
"srodriki@1aa7beb8-f67a-c4d8-682d-4e0fe4e45017"
] | [
[
[
1,
53
]
]
] |
d9eb9c97de6a2164c658afc3f4065b783ab70022 | 1493997bb11718d3c18c6632b6dd010535f742f5 | /direct_ui/UIlib/UIContainer.cpp | 5711edf31b8ebc1001f791d210d0f63688df9e50 | [] | no_license | kovrov/scrap | cd0cf2c98a62d5af6e4206a2cab7bb8e4560b168 | b0f38d95dd4acd89c832188265dece4d91383bbb | refs/heads/master | 2021-01-20T12:21:34.742007 | 2010-01-12T19:53:23 | 2010-01-12T19:53:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,575 | cpp |
#include "StdAfx.h"
#include "UIContainer.h"
/////////////////////////////////////////////////////////////////////////////////////
//
//
CContainerUI::CContainerUI() :
m_hwndScroll(NULL),
m_iPadding(0),
m_iScrollPos(0),
m_bAutoDestroy(true),
m_bAllowScrollbars(false)
{
m_cxyFixed.cx = m_cxyFixed.cy = 0;
::ZeroMemory(&m_rcInset, sizeof(m_rcInset));
}
CContainerUI::~CContainerUI()
{
RemoveAll();
}
LPCTSTR CContainerUI::GetClass() const
{
return _T("ContainerUI");
}
LPVOID CContainerUI::GetInterface(LPCTSTR pstrName)
{
if( _tcscmp(pstrName, _T("Container")) == 0 ) return static_cast<IContainerUI*>(this);
return CControlUI::GetInterface(pstrName);
}
CControlUI* CContainerUI::GetItem(int iIndex) const
{
if( iIndex < 0 || iIndex >= m_items.GetSize() ) return NULL;
return static_cast<CControlUI*>(m_items[iIndex]);
}
int CContainerUI::GetCount() const
{
return m_items.GetSize();
}
bool CContainerUI::Add(CControlUI* pControl)
{
if( m_pManager != NULL ) m_pManager->InitControls(pControl, this);
if( m_pManager != NULL ) m_pManager->UpdateLayout();
return m_items.Add(pControl);
}
bool CContainerUI::Remove(CControlUI* pControl)
{
for( int it = 0; m_bAutoDestroy && it < m_items.GetSize(); it++ ) {
if( static_cast<CControlUI*>(m_items[it]) == pControl ) {
if( m_pManager != NULL ) m_pManager->UpdateLayout();
delete pControl;
return m_items.Remove(it);
}
}
return false;
}
void CContainerUI::RemoveAll()
{
for( int it = 0; m_bAutoDestroy && it < m_items.GetSize(); it++ ) delete static_cast<CControlUI*>(m_items[it]);
m_items.Empty();
m_iScrollPos = 0;
if( m_pManager != NULL ) m_pManager->UpdateLayout();
}
void CContainerUI::SetAutoDestroy(bool bAuto)
{
m_bAutoDestroy = bAuto;
}
void CContainerUI::SetInset(SIZE szInset)
{
m_rcInset.left = m_rcInset.right = szInset.cx;
m_rcInset.top = m_rcInset.bottom = szInset.cy;
}
void CContainerUI::SetInset(RECT rcInset)
{
m_rcInset = rcInset;
}
void CContainerUI::SetPadding(int iPadding)
{
m_iPadding = iPadding;
}
void CContainerUI::SetWidth(int cx)
{
m_cxyFixed.cx = cx;
}
void CContainerUI::SetHeight(int cy)
{
m_cxyFixed.cy = cy;
}
void CContainerUI::SetVisible(bool bVisible)
{
// Hide possible scrollbar control
if( m_hwndScroll != NULL ) ::ShowScrollBar(m_hwndScroll, SB_CTL, bVisible);
// Hide children as well
for( int it = 0; it < m_items.GetSize(); it++ ) {
static_cast<CControlUI*>(m_items[it])->SetVisible(bVisible);
}
CControlUI::SetVisible(bVisible);
}
void CContainerUI::Event(TEventUI& event)
{
if( m_hwndScroll != NULL )
{
if( event.Type == UIEVENT_VSCROLL )
{
switch( LOWORD(event.wParam) ) {
case SB_THUMBPOSITION:
case SB_THUMBTRACK:
{
SCROLLINFO si = { 0 };
si.cbSize = sizeof(SCROLLINFO);
si.fMask = SIF_TRACKPOS;
::GetScrollInfo(m_hwndScroll, SB_CTL, &si);
SetScrollPos(si.nTrackPos);
}
break;
case SB_LINEUP:
SetScrollPos(GetScrollPos() - 5);
break;
case SB_LINEDOWN:
SetScrollPos(GetScrollPos() + 5);
break;
case SB_PAGEUP:
SetScrollPos(GetScrollPos() - GetScrollPage());
break;
case SB_PAGEDOWN:
SetScrollPos(GetScrollPos() + GetScrollPage());
break;
}
}
if( event.Type == UIEVENT_KEYDOWN )
{
switch( event.chKey ) {
case VK_DOWN:
SetScrollPos(GetScrollPos() + 5);
return;
case VK_UP:
SetScrollPos(GetScrollPos() - 5);
return;
case VK_NEXT:
SetScrollPos(GetScrollPos() + GetScrollPage());
return;
case VK_PRIOR:
SetScrollPos(GetScrollPos() - GetScrollPage());
return;
case VK_HOME:
SetScrollPos(0);
return;
case VK_END:
SetScrollPos(9999);
return;
}
}
}
CControlUI::Event(event);
}
int CContainerUI::GetScrollPos() const
{
return m_iScrollPos;
}
int CContainerUI::GetScrollPage() const
{
// TODO: Determine this dynamically
return 40;
}
SIZE CContainerUI::GetScrollRange() const
{
if( m_hwndScroll == NULL ) return CSize();
int cx = 0, cy = 0;
::GetScrollRange(m_hwndScroll, SB_CTL, &cx, &cy);
return CSize(cx, cy);
}
void CContainerUI::SetScrollPos(int iScrollPos)
{
if( m_hwndScroll == NULL ) return;
int iRange1 = 0, iRange2 = 0;
::GetScrollRange(m_hwndScroll, SB_CTL, &iRange1, &iRange2);
iScrollPos = CLAMP(iScrollPos, iRange1, iRange2);
::SetScrollPos(m_hwndScroll, SB_CTL, iScrollPos, TRUE);
m_iScrollPos = ::GetScrollPos(m_hwndScroll, SB_CTL);
// Reposition children to the new viewport.
SetPos(m_rcItem);
Invalidate();
}
void CContainerUI::EnableScrollBar(bool bEnable)
{
if( m_bAllowScrollbars == bEnable ) return;
m_iScrollPos = 0;
m_bAllowScrollbars = bEnable;
}
int CContainerUI::FindSelectable(int iIndex, bool bForward /*= true*/) const
{
// NOTE: This is actually a helper-function for the list/combo/ect controls
// that allow them to find the next enabled/available selectable item
if( GetCount() == 0 ) return -1;
iIndex = CLAMP(iIndex, 0, GetCount() - 1);
if( bForward ) {
for( int i = iIndex; i < GetCount(); i++ ) {
if( GetItem(i)->GetInterface(_T("ListItem")) != NULL
&& GetItem(i)->IsVisible()
&& GetItem(i)->IsEnabled() ) return i;
}
return -1;
}
else {
for( int i = iIndex; i >= 0; --i ) {
if( GetItem(i)->GetInterface(_T("ListItem")) != NULL
&& GetItem(i)->IsVisible()
&& GetItem(i)->IsEnabled() ) return i;
}
return FindSelectable(0, true);
}
}
void CContainerUI::SetPos(RECT rc)
{
CControlUI::SetPos(rc);
if( m_items.IsEmpty() ) return;
rc.left += m_rcInset.left;
rc.top += m_rcInset.top;
rc.right -= m_rcInset.right;
rc.bottom -= m_rcInset.bottom;
// We'll position the first child in the entire client area.
// Do not leave a container empty.
ASSERT(m_items.GetSize()==1);
static_cast<CControlUI*>(m_items[0])->SetPos(rc);
}
SIZE CContainerUI::EstimateSize(SIZE /*szAvailable*/)
{
return m_cxyFixed;
}
void CContainerUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
{
if( _tcscmp(pstrName, _T("inset")) == 0 ) SetInset(CSize(_ttoi(pstrValue), _ttoi(pstrValue)));
else if( _tcscmp(pstrName, _T("padding")) == 0 ) SetPadding(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("width")) == 0 ) SetWidth(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("height")) == 0 ) SetHeight(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("scrollbar")) == 0 ) EnableScrollBar(_tcscmp(pstrValue, _T("true")) == 0);
else CControlUI::SetAttribute(pstrName, pstrValue);
}
void CContainerUI::SetManager(CPaintManagerUI* pManager, CControlUI* pParent)
{
for( int it = 0; it < m_items.GetSize(); it++ ) {
static_cast<CControlUI*>(m_items[it])->SetManager(pManager, this);
}
CControlUI::SetManager(pManager, pParent);
}
CControlUI* CContainerUI::FindControl(FINDCONTROLPROC Proc, LPVOID pData, UINT uFlags)
{
// Check if this guy is valid
if( (uFlags & UIFIND_VISIBLE) != 0 && !IsVisible() ) return NULL;
if( (uFlags & UIFIND_ENABLED) != 0 && !IsEnabled() ) return NULL;
if( (uFlags & UIFIND_HITTEST) != 0 && !::PtInRect(&m_rcItem, *(static_cast<LPPOINT>(pData))) ) return NULL;
if( (uFlags & UIFIND_ME_FIRST) != 0 ) {
CControlUI* pControl = CControlUI::FindControl(Proc, pData, uFlags);
if( pControl != NULL ) return pControl;
}
for( int it = 0; it != m_items.GetSize(); it++ ) {
CControlUI* pControl = static_cast<CControlUI*>(m_items[it])->FindControl(Proc, pData, uFlags);
if( pControl != NULL ) return pControl;
}
return CControlUI::FindControl(Proc, pData, uFlags);
}
void CContainerUI::DoPaint(HDC hDC, const RECT& rcPaint)
{
RECT rcTemp = { 0 };
if( !::IntersectRect(&rcTemp, &rcPaint, &m_rcItem) ) return;
CRenderClip clip;
CBlueRenderEngineUI::GenerateClip(hDC, m_rcItem, clip);
for( int it = 0; it < m_items.GetSize(); it++ ) {
CControlUI* pControl = static_cast<CControlUI*>(m_items[it]);
if( !pControl->IsVisible() ) continue;
if( !::IntersectRect(&rcTemp, &rcPaint, &pControl->GetPos()) ) continue;
if( !::IntersectRect(&rcTemp, &m_rcItem, &pControl->GetPos()) ) continue;
pControl->DoPaint(hDC, rcPaint);
}
}
void CContainerUI::ProcessScrollbar(RECT rc, int cyRequired)
{
// Need the scrollbar control, but it's been created already?
if( cyRequired > rc.bottom - rc.top && m_hwndScroll == NULL && m_bAllowScrollbars ) {
m_hwndScroll = ::CreateWindowEx(0, WC_SCROLLBAR, NULL, WS_CHILD | SBS_VERT, 0, 0, 0, 0, m_pManager->GetPaintWindow(), NULL, m_pManager->GetResourceInstance(), NULL);
ASSERT(::IsWindow(m_hwndScroll));
::SetProp(m_hwndScroll, "WndX", static_cast<HANDLE>(this));
::SetScrollPos(m_hwndScroll, SB_CTL, 0, TRUE);
::ShowWindow(m_hwndScroll, SW_SHOWNOACTIVATE);
SetPos(m_rcItem);
return;
}
// No scrollbar required
if( m_hwndScroll == NULL ) return;
// Move it into place
int cxScroll = m_pManager->GetSystemMetrics().cxvscroll;
::MoveWindow(m_hwndScroll, rc.right, rc.top, cxScroll, rc.bottom - rc.top, TRUE);
// Scroll not needed anymore?
int cyScroll = cyRequired - (rc.bottom - rc.top);
if( cyScroll < 0 ) {
if( m_iScrollPos != 0 ) SetScrollPos(0);
cyScroll = 0;
}
// Scroll range changed?
int cyOld1, cyOld2;
::GetScrollRange(m_hwndScroll, SB_CTL, &cyOld1, &cyOld2);
if( cyOld2 != cyScroll ) {
::SetScrollRange(m_hwndScroll, SB_CTL, 0, cyScroll, FALSE);
::EnableScrollBar(m_hwndScroll, SB_CTL, cyScroll == 0 ? ESB_DISABLE_BOTH : ESB_ENABLE_BOTH);
}
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
CCanvasUI::CCanvasUI() : m_hBitmap(NULL), m_iOrientation(HTBOTTOMRIGHT)
{
}
CCanvasUI::~CCanvasUI()
{
if( m_hBitmap != NULL ) ::DeleteObject(m_hBitmap);
}
LPCTSTR CCanvasUI::GetClass() const
{
return _T("CanvasUI");
}
bool CCanvasUI::SetWatermark(UINT iBitmapRes, int iOrientation)
{
return SetWatermark(MAKEINTRESOURCE(iBitmapRes), iOrientation);
}
bool CCanvasUI::SetWatermark(LPCTSTR pstrBitmap, int iOrientation)
{
if( m_hBitmap != NULL ) ::DeleteObject(m_hBitmap);
m_hBitmap = (HBITMAP) ::LoadImage(m_pManager->GetResourceInstance(), pstrBitmap, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);
ASSERT(m_hBitmap!=NULL);
if( m_hBitmap == NULL ) return false;
::GetObject(m_hBitmap, sizeof(BITMAP), &m_BitmapInfo);
m_iOrientation = iOrientation;
Invalidate();
return true;
}
void CCanvasUI::DoPaint(HDC hDC, const RECT& rcPaint)
{
// Fill background
RECT rcFill = { 0 };
if( ::IntersectRect(&rcFill, &rcPaint, &m_rcItem) ) {
CBlueRenderEngineUI::DoFillRect(hDC, m_pManager, rcFill, m_clrBack);
}
// Paint watermark bitmap
if( m_hBitmap != NULL ) {
RECT rcBitmap = { 0 };
switch( m_iOrientation ) {
case HTTOPRIGHT:
::SetRect(&rcBitmap, m_rcItem.right - m_BitmapInfo.bmWidth, m_rcItem.top, m_rcItem.right, m_rcItem.top + m_BitmapInfo.bmHeight);
break;
case HTBOTTOMRIGHT:
::SetRect(&rcBitmap, m_rcItem.right - m_BitmapInfo.bmWidth, m_rcItem.bottom - m_BitmapInfo.bmHeight, m_rcItem.right, m_rcItem.bottom);
break;
default:
::SetRect(&rcBitmap, m_rcItem.right - m_BitmapInfo.bmWidth, m_rcItem.bottom - m_BitmapInfo.bmHeight, m_rcItem.right, m_rcItem.bottom);
break;
}
RECT rcTemp = { 0 };
if( ::IntersectRect(&rcTemp, &rcPaint, &rcBitmap) ) {
CRenderClip clip;
CBlueRenderEngineUI::GenerateClip(hDC, m_rcItem, clip);
CBlueRenderEngineUI::DoPaintBitmap(hDC, m_pManager, m_hBitmap, rcBitmap);
}
}
CContainerUI::DoPaint(hDC, rcPaint);
}
void CCanvasUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
{
if( _tcscmp(pstrName, _T("watermark")) == 0 ) SetWatermark(pstrValue);
else CContainerUI::SetAttribute(pstrName, pstrValue);
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
CWindowCanvasUI::CWindowCanvasUI()
{
SetInset(CSize(10, 10));
m_clrBack = m_pManager->GetThemeColor(UICOLOR_WINDOW_BACKGROUND);
}
LPCTSTR CWindowCanvasUI::GetClass() const
{
return _T("WindowCanvasUI");
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
CControlCanvasUI::CControlCanvasUI()
{
SetInset(CSize(0, 0));
m_clrBack = m_pManager->GetThemeColor(UICOLOR_CONTROL_BACKGROUND_NORMAL);
}
LPCTSTR CControlCanvasUI::GetClass() const
{
return _T("ControlCanvasUI");
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
CWhiteCanvasUI::CWhiteCanvasUI()
{
SetInset(CSize(0, 0));
m_clrBack = m_pManager->GetThemeColor(UICOLOR_STANDARD_WHITE);
}
LPCTSTR CWhiteCanvasUI::GetClass() const
{
return _T("WhiteCanvasUI");
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
CDialogCanvasUI::CDialogCanvasUI()
{
SetInset(CSize(10, 10));
m_clrBack = m_pManager->GetThemeColor(UICOLOR_DIALOG_BACKGROUND);
}
LPCTSTR CDialogCanvasUI::GetClass() const
{
return _T("DialogCanvasUI");
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
CTabFolderCanvasUI::CTabFolderCanvasUI()
{
SetInset(CSize(0, 0));
COLORREF clrColor1;
m_pManager->GetThemeColorPair(UICOLOR_TAB_FOLDER_NORMAL, clrColor1, m_clrBack);
}
LPCTSTR CTabFolderCanvasUI::GetClass() const
{
return _T("TabFolderCanvasUI");
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
CVerticalLayoutUI::CVerticalLayoutUI() : m_cyNeeded(0)
{
}
LPCTSTR CVerticalLayoutUI::GetClass() const
{
return _T("VertialLayoutUI");
}
void CVerticalLayoutUI::SetPos(RECT rc)
{
m_rcItem = rc;
// Adjust for inset
rc.left += m_rcInset.left;
rc.top += m_rcInset.top;
rc.right -= m_rcInset.right;
rc.bottom -= m_rcInset.bottom;
if( m_hwndScroll != NULL ) rc.right -= m_pManager->GetSystemMetrics().cxvscroll;
// Determine the minimum size
SIZE szAvailable = { rc.right - rc.left, rc.bottom - rc.top };
int nAdjustables = 0;
int cyFixed = 0;
for( int it1 = 0; it1 < m_items.GetSize(); it1++ ) {
CControlUI* pControl = static_cast<CControlUI*>(m_items[it1]);
if( !pControl->IsVisible() ) continue;
SIZE sz = pControl->EstimateSize(szAvailable);
if( sz.cy == 0 ) nAdjustables++;
cyFixed += sz.cy + m_iPadding;
}
// Place elements
int cyNeeded = 0;
int cyExpand = 0;
if( nAdjustables > 0 ) cyExpand = MAX(0, (szAvailable.cy - cyFixed) / nAdjustables);
// Position the elements
SIZE szRemaining = szAvailable;
int iPosY = rc.top - m_iScrollPos;
int iAdjustable = 0;
for( int it2 = 0; it2 < m_items.GetSize(); it2++ ) {
CControlUI* pControl = static_cast<CControlUI*>(m_items[it2]);
if( !pControl->IsVisible() ) continue;
SIZE sz = pControl->EstimateSize(szRemaining);
if( sz.cy == 0 ) {
iAdjustable++;
sz.cy = cyExpand;
// Distribute remaining to last element (usually round-off left-overs)
if( iAdjustable == nAdjustables ) sz.cy += MAX(0, szAvailable.cy - (cyExpand * nAdjustables) - cyFixed);
}
RECT rcCtrl = { rc.left, iPosY, rc.right, iPosY + sz.cy };
pControl->SetPos(rcCtrl);
iPosY += sz.cy + m_iPadding;
cyNeeded += sz.cy + m_iPadding;
szRemaining.cy -= sz.cy + m_iPadding;
}
// Handle overflow with scrollbars
ProcessScrollbar(rc, cyNeeded);
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
CHorizontalLayoutUI::CHorizontalLayoutUI()
{
}
LPCTSTR CHorizontalLayoutUI::GetClass() const
{
return _T("HorizontalLayoutUI");
}
void CHorizontalLayoutUI::SetPos(RECT rc)
{
m_rcItem = rc;
// Adjust for inset
rc.left += m_rcInset.left;
rc.top += m_rcInset.top;
rc.right -= m_rcInset.right;
rc.bottom -= m_rcInset.bottom;
// Determine the width of elements that are sizeable
SIZE szAvailable = { rc.right - rc.left, rc.bottom - rc.top };
int nAdjustables = 0;
int cxFixed = 0;
for( int it1 = 0; it1 < m_items.GetSize(); it1++ ) {
CControlUI* pControl = static_cast<CControlUI*>(m_items[it1]);
if( !pControl->IsVisible() ) continue;
SIZE sz = pControl->EstimateSize(szAvailable);
if( sz.cx == 0 ) nAdjustables++;
cxFixed += sz.cx + m_iPadding;
}
int cxExpand = 0;
if( nAdjustables > 0 ) cxExpand = MAX(0, (szAvailable.cx - cxFixed) / nAdjustables);
// Position the elements
SIZE szRemaining = szAvailable;
int iPosX = rc.left;
int iAdjustable = 0;
for( int it2 = 0; it2 < m_items.GetSize(); it2++ ) {
CControlUI* pControl = static_cast<CControlUI*>(m_items[it2]);
if( !pControl->IsVisible() ) continue;
SIZE sz = pControl->EstimateSize(szRemaining);
if( sz.cx == 0 ) {
iAdjustable++;
sz.cx = cxExpand;
if( iAdjustable == nAdjustables ) sz.cx += MAX(0, szAvailable.cx - (cxExpand * nAdjustables) - cxFixed);
}
RECT rcCtrl = { iPosX, rc.top, iPosX + sz.cx, rc.bottom };
pControl->SetPos(rcCtrl);
iPosX += sz.cx + m_iPadding;
szRemaining.cx -= sz.cx + m_iPadding;
}
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
CTileLayoutUI::CTileLayoutUI() : m_nColumns(2), m_cyNeeded(0)
{
SetPadding(10);
SetInset(CSize(10, 10));
}
LPCTSTR CTileLayoutUI::GetClass() const
{
return _T("TileLayoutUI");
}
void CTileLayoutUI::SetColumns(int nCols)
{
if( nCols <= 0 ) return;
m_nColumns = nCols;
UpdateLayout();
}
void CTileLayoutUI::SetPos(RECT rc)
{
m_rcItem = rc;
// Adjust for inset
rc.left += m_rcInset.left;
rc.top += m_rcInset.top;
rc.right -= m_rcInset.right;
rc.bottom -= m_rcInset.bottom;
if( m_hwndScroll != NULL ) rc.right -= m_pManager->GetSystemMetrics().cxvscroll;
// Position the elements
int cxWidth = (rc.right - rc.left) / m_nColumns;
int cyHeight = 0;
int iCount = 0;
POINT ptTile = { rc.left, rc.top - m_iScrollPos };
for( int it1 = 0; it1 < m_items.GetSize(); it1++ ) {
CControlUI* pControl = static_cast<CControlUI*>(m_items[it1]);
if( !pControl->IsVisible() ) continue;
// Determine size
RECT rcTile = { ptTile.x, ptTile.y, ptTile.x + cxWidth, ptTile.y };
// Adjust with element padding
if( (iCount % m_nColumns) == 0 ) rcTile.right -= m_iPadding / 2;
else if( (iCount % m_nColumns) == m_nColumns - 1 ) rcTile.left += m_iPadding / 2;
else ::InflateRect(&rcTile, -(m_iPadding / 2), 0);
// If this panel expands vertically
if( m_cxyFixed.cy == 0) {
SIZE szAvailable = { rcTile.right - rcTile.left, 9999 };
int iIndex = iCount;
for( int it2 = it1; it2 < m_items.GetSize(); it2++ ) {
SIZE szTile = static_cast<CControlUI*>(m_items[it2])->EstimateSize(szAvailable);
cyHeight = MAX(cyHeight, szTile.cy);
if( (++iIndex % m_nColumns) == 0) break;
}
}
// Set position
rcTile.bottom = rcTile.top + cyHeight;
pControl->SetPos(rcTile);
// Move along...
if( (++iCount % m_nColumns) == 0 ) {
ptTile.x = rc.left;
ptTile.y += cyHeight + m_iPadding;
cyHeight = 0;
}
else {
ptTile.x += cxWidth;
}
m_cyNeeded = rcTile.bottom - (rc.top - m_iScrollPos);
}
// Process the scrollbar
ProcessScrollbar(rc, m_cyNeeded);
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
CDialogLayoutUI::CDialogLayoutUI() : m_bFirstResize(true), m_aModes(sizeof(STRETCHMODE))
{
::ZeroMemory(&m_rcDialog, sizeof(m_rcDialog));
}
LPCTSTR CDialogLayoutUI::GetClass() const
{
return _T("DialogLayoutUI");
}
LPVOID CDialogLayoutUI::GetInterface(LPCTSTR pstrName)
{
if( _tcscmp(pstrName, _T("DialogLayout")) == 0 ) return this;
return CContainerUI::GetInterface(pstrName);
}
void CDialogLayoutUI::SetStretchMode(CControlUI* pControl, UINT uMode)
{
STRETCHMODE mode;
mode.pControl = pControl;
mode.uMode = uMode;
mode.rcItem = pControl->GetPos();
m_aModes.Add(&mode);
}
SIZE CDialogLayoutUI::EstimateSize(SIZE szAvailable)
{
RecalcArea();
return CSize(m_rcDialog.right - m_rcDialog.left, m_rcDialog.bottom - m_rcDialog.top);
}
void CDialogLayoutUI::SetPos(RECT rc)
{
m_rcItem = rc;
RecalcArea();
// Do Scrollbar
ProcessScrollbar(rc, m_rcDialog.bottom - m_rcDialog.top);
if( m_hwndScroll != NULL ) rc.right -= m_pManager->GetSystemMetrics().cxvscroll;
// Determine how "scaled" the dialog is compared to the original size
int cxDiff = (rc.right - rc.left) - (m_rcDialog.right - m_rcDialog.left);
int cyDiff = (rc.bottom - rc.top) - (m_rcDialog.bottom - m_rcDialog.top);
if( cxDiff < 0 ) cxDiff = 0;
if( cyDiff < 0 ) cyDiff = 0;
// Stretch each control
// Controls are coupled in "groups", which determine a scaling factor.
// A "line" indicator is used to apply the same scaling to a new group of controls.
int nCount, cxStretch, cyStretch, cxMove, cyMove;
for( int i = 0; i < m_aModes.GetSize(); i++ ) {
STRETCHMODE* pItem = static_cast<STRETCHMODE*>(m_aModes[i]);
if( i == 0 || (pItem->uMode & UISTRETCH_NEWGROUP) != 0 ) {
nCount = 0;
for( int j = i + 1; j < m_aModes.GetSize(); j++ ) {
STRETCHMODE* pNext = static_cast<STRETCHMODE*>(m_aModes[j]);
if( (pNext->uMode & (UISTRETCH_NEWGROUP | UISTRETCH_NEWLINE)) != 0 ) break;
if( (pNext->uMode & (UISTRETCH_SIZE_X | UISTRETCH_SIZE_Y)) != 0 ) nCount++;
}
if( nCount == 0 ) nCount = 1;
cxStretch = cxDiff / nCount;
cyStretch = cyDiff / nCount;
cxMove = 0;
cyMove = 0;
}
if( (pItem->uMode & UISTRETCH_NEWLINE) != 0 ) {
cxMove = 0;
cyMove = 0;
}
RECT rcPos = pItem->rcItem;
::OffsetRect(&rcPos, rc.left, rc.top - m_iScrollPos);
if( (pItem->uMode & UISTRETCH_MOVE_X) != 0 ) ::OffsetRect(&rcPos, cxMove, 0);
if( (pItem->uMode & UISTRETCH_MOVE_Y) != 0 ) ::OffsetRect(&rcPos, 0, cyMove);
if( (pItem->uMode & UISTRETCH_SIZE_X) != 0 ) rcPos.right += cxStretch;
if( (pItem->uMode & UISTRETCH_SIZE_Y) != 0 ) rcPos.bottom += cyStretch;
if( (pItem->uMode & (UISTRETCH_SIZE_X | UISTRETCH_SIZE_Y)) != 0 ) {
cxMove += cxStretch;
cyMove += cyStretch;
}
pItem->pControl->SetPos(rcPos);
}
}
void CDialogLayoutUI::RecalcArea()
{
if( !m_bFirstResize ) return;
// Add the remaining control to the list
// Controls that have specific stretching needs will define them in the XML resource
// and by calling SetStretchMode(). Other controls needs to be added as well now...
for( int it = 0; it < m_items.GetSize(); it++ ) {
CControlUI* pControl = static_cast<CControlUI*>(m_items[it]);
bool bFound = false;
for( int i = 0; !bFound && i < m_aModes.GetSize(); i++ ) {
if( static_cast<STRETCHMODE*>(m_aModes[i])->pControl == pControl ) bFound = true;
}
if( !bFound ) {
STRETCHMODE mode;
mode.pControl = pControl;
mode.uMode = UISTRETCH_NEWGROUP;
mode.rcItem = pControl->GetPos();
m_aModes.Add(&mode);
}
}
// Figure out the actual size of the dialog so we can add proper scrollbars later
CRect rcDialog(9999, 9999, 0,0);
for( int i = 0; i < m_items.GetSize(); i++ ) {
const RECT& rcPos = static_cast<CControlUI*>(m_items[i])->GetPos();
rcDialog.Join(rcPos);
}
for( int j = 0; j < m_aModes.GetSize(); j++ ) {
RECT& rcPos = static_cast<STRETCHMODE*>(m_aModes[j])->rcItem;
::OffsetRect(&rcPos, -rcDialog.left, -rcDialog.top);
}
m_rcDialog = rcDialog;
// We're done with initialization
m_bFirstResize = false;
}
| [
"[email protected]"
] | [
[
[
1,
805
]
]
] |
3538f1a587668eb7b6df8b224337eff845558d3d | 14298a990afb4c8619eea10988f9c0854ec49d29 | /PowerBill四川电信专用版本/ibill_source/OpenDialogFrm.cpp | 4161bd4ba88e9a804e04cdc4452a7f4fd31c73ba | [] | no_license | sridhar19091986/xmlconvertsql | 066344074e932e919a69b818d0038f3d612e6f17 | bbb5bbaecbb011420d701005e13efcd2265aa80e | refs/heads/master | 2021-01-21T17:45:45.658884 | 2011-05-30T12:53:29 | 2011-05-30T12:53:29 | 42,693,560 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,572 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "OpenDialogFrm.h"
#include "public.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "RzCmboBx"
#pragma link "RzShellCtrls"
#pragma link "RzGroupBar"
#pragma link "RzPanel"
#pragma link "RzListVw"
#pragma link "RzButton"
#pragma link "dcOutPanel"
#pragma link "RzTreeVw"
#pragma link "dcOutPanel"
#pragma link "RzRadChk"
#pragma resource "*.dfm"
TfrmOpenDialog *frmOpenDialog;
//---------------------------------------------------------------------------
__fastcall TfrmOpenDialog::TfrmOpenDialog(TComponent* Owner)
: TForm(Owner)
{
//Files = new TStringList;
PathName = "";
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::btnCancelClick(TObject *Sender)
{
ModalResult = mrCancel;
}
//---------------------------------------------------------------------------
bool __fastcall TfrmOpenDialog::Execute()
{
//Files->Clear();
return ShowModal() == mrOk;
}
void __fastcall TfrmOpenDialog::btnOpenClick(TObject *Sender)
{
if(lvFiles->SelCount == 0)
return;
if(cbxFileFormat->ItemIndex < 0)
{
MessageBox(Handle,"请指定当前将要打开的文件的格式!","提示",MB_OK | MB_ICONWARNING);
cbxFileFormat->SetFocus();
return;
}
PathName = lvFiles->Folder->PathName;
if(PathName.SubString(PathName.Length(),1) != "\\")
PathName += "\\";
/*
TListItem * Item;
TItemStates States = TItemStates() << isSelected;
PathName = lvFiles->Folder->PathName;
if(PathName.SubString(PathName.Length(),1) != "\\")
PathName += "\\";
Item = lvFiles->GetNextItem(NULL,sdAll,States);
Screen->Cursor = crHourGlass;
//Files->Clear();
//unsigned int FileSize;
//HANDLE hFile;
//AnsiString FileName;
while(Item != NULL)
{
FileName = PathName + Item->Caption;
hFile = CreateFile(FileName.c_str(),GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
if(DirectoryExists(FileName)) //如果是文件夹
{
continue;
}
else
{
MessageBox(Handle,("不能获取文件 " + FileName + " 的大小").c_str(),"警告",MB_OK | MB_ICONWARNING);
FileSize = -1;
}
}
else
{
FileSize = GetFileSize(hFile,NULL);
CloseHandle(hFile);
}
Files->AddObject(FileName,(TObject *)FileSize);
Item = lvFiles->GetNextItem(Item,sdAll,States);
}
Screen->Cursor = crDefault;
if(Files->Count == 0)
return;
*/
ModalResult = mrOk;
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::cbxFolderChange(TObject *Sender)
{
lvFiles->Folder->PathName = cbxFolder->SelectedFolder->PathName;
tvFolder->SelectedPathName = cbxFolder->SelectedFolder->PathName;
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::lvFilesFolderChanged(TObject *Sender)
{
cbxFolder->SelectedFolder->PathName = lvFiles->Folder->PathName;
tvFolder->SelectedPathName = lvFiles->Folder->PathName;
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::ToolButton1Click(TObject *Sender)
{
lvFiles->GoUp(1);
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::menuIconClick(TObject *Sender)
{
lvFiles->ViewStyle = vsIcon;
menuIcon->Checked = true;
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::menuSmallClick(TObject *Sender)
{
lvFiles->ViewStyle = vsSmallIcon;
menuSmall->Checked = true;
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::menuListClick(TObject *Sender)
{
lvFiles->ViewStyle = vsList;
menuList->Checked = true;
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::menuDetailClick(TObject *Sender)
{
lvFiles->ViewStyle = vsReport;
menuDetail->Checked = true;
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::FormDestroy(TObject *Sender)
{
//delete Files;
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::lvFilesDblClickOpen(TObject *Sender,
bool &Handled)
{
btnOpenClick(NULL);
Handled = true;
}
//---------------------------------------------------------------------------
void __fastcall TfrmOpenDialog::tvFolderChange(TObject *Sender,
TTreeNode *Node)
{
cbxFolder->SelectedFolder->PathName = tvFolder->SelectedPathName;
lvFiles->Folder->PathName = tvFolder->SelectedPathName;
}
//---------------------------------------------------------------------------
bool __fastcall TfrmOpenDialog::FormHelp(WORD Command, int Data,
bool &CallHelp)
{
if(Command != HELP_CONTEXTPOPUP)
{
CallHelp = false;
return true;
}
WinHelp(Handle,(HelpFilePath + "opendialog.hlp").c_str(),HELP_CONTEXTPOPUP,Data);
CallHelp = false;
return true;
}
//---------------------------------------------------------------------------
| [
"cn.wei.hp@e7bd78f4-57e5-8052-e4e7-673d445fef99"
] | [
[
[
1,
183
]
]
] |
f1e907bc884bd3b47a1ce88de0932a7b1c4b8cfb | 482345b63717a46b45763fb07c6c0c645c7af418 | /Longitud cadena de texto.cpp | 1e51239d0300c50b0d2de4dd5215d8dd53f73ad3 | [] | no_license | camilonova/Varios-C | 4a2131643a6019c36f0c3854edad9b0b98730436 | 2b9c9860d96e169701f87d6c50a7209016c43041 | refs/heads/master | 2021-01-20T06:25:27.710014 | 2011-06-04T20:49:54 | 2011-06-04T20:49:54 | 1,848,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | cpp | /*Programa que determina la longitud de una cadena de texto, utilizando
las funciones de la libreria string.h*/
#include <stdio.h>
#include <string.h>
main()
{
char string[80];
printf("\nIntroduzca una cadena de texto:");
gets(string);
printf("\n\nLa cadena \" %s \" tiene %d caracteres\n\n", string, strlen(string));
return 0;
} | [
"[email protected]"
] | [
[
[
1,
17
]
]
] |
04b9933ad7d5f1f3295fb7573960f97fd236e858 | dec876ce09f7fb2e9cd2d80e66d98bbb02f6ff6e | /Classes/Ponto.cpp | c40f61b839955f09d93cac8abae8cd90776437f4 | [] | no_license | fleith/BestPoint | 5b0b5804ebfad7de5722a82b253ec66419177e1b | 5df9af3ee68c0d967716af0e0a5e89e69c905a44 | refs/heads/master | 2021-01-22T10:02:51.390034 | 2010-02-15T14:51:40 | 2010-02-15T14:51:40 | 332,226 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | cpp | /*
* Ponto.cpp
*
* Created on: Jul 3, 2008
* Author: alvaro
*/
#include "Ponto.h"
////////////////////////////////////////////////////////////////////////////////
Ponto::~Ponto()
{
}
////////////////////////////////////////////////////////////////////////////////
Ponto::Ponto(Cromossomo& cromossomo):posicaoX(cromossomo.PosicaoX()),
posicaoY(cromossomo.PosicaoY())
{
}
////////////////////////////////////////////////////////////////////////////////
Ponto::Ponto(double posX, double posY):posicaoX(posX),posicaoY(posY)
{
}
////////////////////////////////////////////////////////////////////////////////
double Ponto::PosicaoX()
{
return posicaoX;
}
////////////////////////////////////////////////////////////////////////////////
double Ponto::PosicaoY()
{
return posicaoY;
}
////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | [
[
[
1,
44
]
]
] |
9d1b140d5fecd62e67fd5ceb4a335adaf1377b9b | fbd2deaa66c52fc8c38baa90dd8f662aabf1f0dd | /totalFirePower/ta demo/code/Bitmap.h | b5eebf3813e53b120b04d47ec51bd867ab45bc68 | [] | no_license | arlukin/dev | ea4f62f3a2f95e1bd451fb446409ab33e5c0d6e1 | b71fa9e9d8953e33f25c2ae7e5b3c8e0defd18e0 | refs/heads/master | 2021-01-15T11:29:03.247836 | 2011-02-24T23:27:03 | 2011-02-24T23:27:03 | 1,408,455 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 791 | h | // Bitmap.h: interface for the CBitmap class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_BITMAP_H__BBA7EEE5_879F_4ABE_A878_51FE098C3A0D__INCLUDED_)
#define AFX_BITMAP_H__BBA7EEE5_879F_4ABE_A878_51FE098C3A0D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <string>
using std::string;
class CBitmap
{
public:
void LoadJPG(string filename);
void LoadBMP(string filename);
void Save(string filename);
CBitmap(unsigned char* data,int xsize,int ysize);
void Load(string filename);
CBitmap(string filename);
CBitmap();
virtual ~CBitmap();
unsigned char* mem;
int xsize;
int ysize;
};
#endif // !defined(AFX_BITMAP_H__BBA7EEE5_879F_4ABE_A878_51FE098C3A0D__INCLUDED_)
| [
"[email protected]"
] | [
[
[
1,
33
]
]
] |
84befaf6691a5e0b34bc8803c48f1b88beaafca9 | 01fadae9f2a6d3f19bc843841a7faa9c40fc4a20 | /CG/code_CG/EX04_03.CPP | d861d8ffee0d00ac8df1a45a29793407e7952378 | [] | no_license | passzenith/passzenithproject | 9999da29ac8df269c41d280137113e1e2638542d | 67dd08f4c3a046889319170a89b45478bfd662d2 | refs/heads/master | 2020-12-24T14:36:46.389657 | 2010-09-05T02:34:42 | 2010-09-05T02:34:42 | 32,310,266 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,521 | cpp | #include <GL/glut.h>
void init (void)
{
glClearColor (1.0, 1.0, 1.0, 0.0);
glColor3f (0.0, 0.0, 1.0);
glLineWidth(4.0);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluOrtho2D (0.0, 400.0, 0.0, 300.0);
}
void myDisplay (void)
{
int p0 [ ] = {50, 200};
int p1 [ ] = {100, 50};
int p2 [ ] = {300, 100};
int p3 [ ] = {350, 250};
int p4 [ ] = {200, 150};
glClear (GL_COLOR_BUFFER_BIT);
// For function GL_LINES.
glBegin (GL_LINES); // 2 line from p0-p1 and p2-p3.
glVertex2iv (p0);
glVertex2iv (p1);
glVertex2iv (p2);
glVertex2iv (p3);
glVertex2iv (p4);
glEnd ( );
// For function GL_LINE_STRIP.
/* glBegin (GL_LINE_STRIP); // 4 line from p0-p1, p1-p2, p2-p3, p3-p4.
glVertex2iv (p0);
glVertex2iv (p1);
glVertex2iv (p2);
glVertex2iv (p3);
glVertex2iv (p4);
glEnd ( );
*/
// For function GL_LINE_LOOP.
/* glBegin (GL_LINE_LOOP); // 5 line from p0-p1, p1-p2, p2-p3, p3-p4 and p4-p0.
glVertex2iv (p0);
glVertex2iv (p1);
glVertex2iv (p2);
glVertex2iv (p3);
glVertex2iv (p4);
glEnd ( );
*/
glFlush ( );
}
int main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (50, 100);
glutInitWindowSize (400, 300);
glutCreateWindow ("Draw lines with OpenGL Program");
init ( );
glutDisplayFunc (myDisplay);
glutMainLoop ( );
return 0;
}
| [
"passzenith@00fadc5f-a3f2-dbaa-0561-d91942954633"
] | [
[
[
1,
65
]
]
] |
e511a39e7ae96890f5284f93a117f82686ccb02b | d752d83f8bd72d9b280a8c70e28e56e502ef096f | /FugueDLL/Language Extensions/DLLAccess.cpp | 62ce981dbdcf8c32f93f6d06b8a8cfda030c5465 | [] | no_license | apoch/epoch-language.old | f87b4512ec6bb5591bc1610e21210e0ed6a82104 | b09701714d556442202fccb92405e6886064f4af | refs/heads/master | 2021-01-10T20:17:56.774468 | 2010-03-07T09:19:02 | 2010-03-07T09:19:02 | 34,307,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,573 | cpp | //
// The Epoch Language Project
// FUGUE Virtual Machine
//
// Wrapper logic for accessing language extension libraries
//
#include "pch.h"
#include "Language Extensions/DLLAccess.h"
#include "Language Extensions/ExtensionCatalog.h"
#include "Traverser/TraversalInterface.h"
#include "Virtual Machine/Core Entities/Block.h"
#include "Virtual Machine/Core Entities/Operation.h"
#include "Virtual Machine/Core Entities/Program.h"
#include "Virtual Machine/Core Entities/Scopes/ScopeDescription.h"
#include "Virtual Machine/Core Entities/Scopes/ActivatedScope.h"
#include "Virtual Machine/Core Entities/Variables/ArrayVariable.h"
#include "Marshalling/DLLPool.h"
#include "Utility/Strings.h"
using namespace Extensions;
//
// Construct the access wrapper and initialize the DLL bindings
//
ExtensionDLLAccess::ExtensionDLLAccess(const std::wstring& dllname, VM::Program& program, bool startsession)
: SessionHandle(0),
DLLName(dllname),
ExtensionValid(false),
DLLHandle(NULL)
{
// Load the DLL
DLLHandle = Marshalling::TheDLLPool.OpenDLL(dllname);
if(!DLLHandle)
throw Exception("A language extension DLL was requested, but the DLL was either not found or reported some error during initialization");
// Obtain interface into DLL
DoInitialize = reinterpret_cast<InitializePtr>(::GetProcAddress(DLLHandle, "Initialize"));
DoRegistration = reinterpret_cast<RegistrationPtr>(::GetProcAddress(DLLHandle, "Register"));
DoLoadSource = reinterpret_cast<LoadSourceBlockPtr>(::GetProcAddress(DLLHandle, "LoadSourceBlock"));
DoExecuteSource = reinterpret_cast<ExecuteSourceBlockPtr>(::GetProcAddress(DLLHandle, "ExecuteSourceBlock"));
DoExecuteControl = reinterpret_cast<ExecuteControlPtr>(::GetProcAddress(DLLHandle, "ExecuteControl"));
DoPrepare = reinterpret_cast<PreparePtr>(::GetProcAddress(DLLHandle, "CommitCompilation"));
DoStartSession = reinterpret_cast<StartCompileSessionPtr>(::GetProcAddress(DLLHandle, "StartNewProgramCompilation"));
DoFillSerializationBuffer = reinterpret_cast<FillSerializationBufferPtr>(::GetProcAddress(DLLHandle, "FillSerializationBuffer"));
DoFreeSerializationBuffer = reinterpret_cast<FreeSerializationBufferPtr>(::GetProcAddress(DLLHandle, "FreeSerializationBuffer"));
DoLoadDataBuffer = reinterpret_cast<LoadDataBufferPtr>(::GetProcAddress(DLLHandle, "LoadDataBuffer"));
DoPrepareBlock = reinterpret_cast<PrepareBlockPtr>(::GetProcAddress(DLLHandle, "PrepareBlock"));
DoClearEverything = reinterpret_cast<ClearEverythingPtr>(::GetProcAddress(DLLHandle, "ClearEverything"));
// Validate interface to be sure
if(!DoInitialize || !DoRegistration || !DoLoadSource || !DoExecuteSource || !DoExecuteControl || !DoPrepare ||
!DoStartSession || !DoFillSerializationBuffer || !DoFreeSerializationBuffer || !DoLoadDataBuffer ||
!DoPrepareBlock || !DoClearEverything)
{
throw Exception("One or more Epoch service functions could not be loaded from the requested language extension DLL");
}
ExtensionValid = DoInitialize();
if(startsession)
SessionHandle = DoStartSession(reinterpret_cast<HandleType>(&program));
else
SessionHandle = 0;
}
//
// Create a block of code in the language extension, given a block of raw Epoch code
//
CodeBlockHandle ExtensionDLLAccess::LoadSourceBlock(const std::wstring& keyword, OriginalCodeHandle handle)
{
return DoLoadSource(SessionHandle, handle, keyword.c_str());
}
//
// Invoke the code generated for the specified language extension code block
//
void ExtensionDLLAccess::ExecuteSourceBlock(CodeBlockHandle handle, HandleType activatedscopehandle)
{
return DoExecuteSource(handle, activatedscopehandle);
}
void ExtensionDLLAccess::ExecuteSourceBlock(CodeBlockHandle handle, HandleType activatedscopehandle, const std::vector<Traverser::Payload>& payloads)
{
if(payloads.empty())
return DoExecuteControl(handle, activatedscopehandle, 0, NULL);
else
return DoExecuteControl(handle, activatedscopehandle, payloads.size(), &payloads[0]);
}
namespace
{
//
// Callback: register an extension keyword for this language extension
//
// The language extension invokes this callback for each keyword it wishes
// to add to the language. When one of these keywords is encountered, the
// subsequent code block is converted by the extension library.
//
void __stdcall RegistrationCallback(ExtensionLibraryHandle token, const wchar_t* keyword)
{
RegisterExtensionKeyword(keyword, token);
}
void __stdcall ControlRegistrationCallback(ExtensionLibraryHandle token, const wchar_t* keyword, size_t numparams, ExtensionControlParamInfo* params)
{
RegisterExtensionControl(keyword, token, numparams, params);
}
class BindTraversal
{
public:
BindTraversal(Traverser::Interface* traversal, HandleType sessionhandle)
: Traversal(traversal),
SessionHandle(sessionhandle)
{ }
public:
void EnterBlock(const VM::Block& block)
{
ActiveScopes.push(block.GetBoundScope());
Traversal->NodeEntryCallback(SessionHandle);
}
void ExitBlock(const VM::Block& block)
{
Traversal->NodeExitCallback(SessionHandle);
ActiveScopes.pop();
}
void TraverseNode(const std::wstring& token, const Traverser::Payload& payload)
{
Traversal->NodeTraversalCallback(SessionHandle, token.c_str(), &payload);
}
void TraverseFunction(const std::wstring& funcname, VM::Function* targetfunction)
{
Traversal->FunctionTraversalCallback(SessionHandle, funcname.c_str());
targetfunction->GetReturns().TraverseExternal(*this);
targetfunction->GetParams().TraverseExternal(*this);
targetfunction->GetCodeBlock()->TraverseExternal(*this);
}
void RegisterScope(const VM::ScopeDescription* description, bool isghost)
{
ActiveScopes.push(description);
std::vector<Traverser::ScopeContents> contents;
for(std::vector<std::wstring>::const_iterator iter = description->GetMemberOrder().begin(); iter != description->GetMemberOrder().end(); ++iter)
{
Traverser::ScopeContents content;
content.Identifier = iter->c_str();
content.Type = description->GetVariableType(*iter);
if(content.Type == VM::EpochVariableType_Array)
{
content.ContainedType = description->GetArrayType(*iter);
content.ContainedSize = 0;
}
contents.push_back(content);
}
Traversal->ScopeTraversalCallback(SessionHandle, ActiveScopes.size() == 1, isghost, contents.size(), contents.size() ? &(contents[0]) : NULL);
std::set<const VM::ScopeDescription*> ghostscopes = description->GetAllGhostScopes();
for(std::set<const VM::ScopeDescription*>::const_iterator iter = ghostscopes.begin(); iter != ghostscopes.end(); ++iter)
RegisterScope(*iter, true);
ActiveScopes.pop();
}
const VM::ScopeDescription* GetCurrentScope() const
{
if(ActiveScopes.empty())
return NULL;
return ActiveScopes.top();
}
private:
Traverser::Interface* Traversal;
HandleType SessionHandle;
std::stack<const VM::ScopeDescription*> ActiveScopes;
};
//
// Callback: traverse a block of code, invoking the given traverser interface as needed
//
// This function traverses the entire specified block of Epoch code, passing
// information to the language extension for each operation in the block.
//
void __stdcall TraversalCallback(OriginalCodeHandle handle, Traverser::Interface* traversal, HandleType sessionhandle)
{
BindTraversal boundtraverser(traversal, sessionhandle);
VM::Block* originalcode = reinterpret_cast<VM::Block*>(handle); // This is safe since we issued the handle to begin with!
VM::ScopeDescription* parentscope = originalcode->GetBoundScope()->ParentScope;
while(parentscope)
{
boundtraverser.RegisterScope(parentscope, false);
parentscope = parentscope->ParentScope;
}
originalcode->TraverseExternal(boundtraverser);
}
void __stdcall TraverseFunctionCallback(const wchar_t* functionname, Traverser::Interface* traversal, HandleType session, HandleType program)
{
VM::Program* theprogram = reinterpret_cast<VM::Program*>(program);
VM::Function* targetfunction = dynamic_cast<VM::Function*>(theprogram->GetGlobalScope().GetFunction(functionname));
if(!targetfunction)
throw Exception("Could not find the requested function");
BindTraversal boundtraverser(traversal, session);
boundtraverser.TraverseFunction(functionname, targetfunction);
}
//
// Convert a traverser payload wrapper structure to a VM RValue wrapper
//
VM::RValuePtr PayloadToRValue(const Traverser::Payload& payload)
{
// TODO - support additional types
switch(payload.Type)
{
case VM::EpochVariableType_Integer: return VM::RValuePtr(new VM::IntegerRValue(payload.Int32Value));
case VM::EpochVariableType_Integer16: return VM::RValuePtr(new VM::Integer16RValue(payload.Int16Value));
case VM::EpochVariableType_Real: return VM::RValuePtr(new VM::RealRValue(payload.FloatValue));
case VM::EpochVariableType_String: return VM::RValuePtr(new VM::StringRValue(payload.StringValue));
case VM::EpochVariableType_Array: return VM::RValuePtr(new VM::ArrayRValue(payload.ParameterType, payload.ParameterCount, payload.PointerValue));
}
throw Exception("Unsupported type, cannot convert language extension data into a VM-friendly format");
}
//
// Callback: the language extension wishes to set the value of an Epoch variable
//
void __stdcall MarshalCallbackWrite(HandleType handle, const wchar_t* identifier, Traverser::Payload* payload)
{
VM::ActivatedScope* activatedscope = reinterpret_cast<VM::ActivatedScope*>(handle); // This is safe since we issued the handle to begin with!
VM::EpochVariableTypeID desttype = activatedscope->GetVariableType(identifier);
activatedscope->SetVariableValue(identifier, PayloadToRValue(*payload));
}
//
// Callback: the language extension wishes to retrieve the value of an Epoch variable
//
void __stdcall MarshalCallbackRead(HandleType activatedscopehandle, const wchar_t* identifier, Traverser::Payload* payload)
{
VM::ActivatedScope* activatedscope = reinterpret_cast<VM::ActivatedScope*>(activatedscopehandle); // This is safe since we issued the handle to begin with!
payload->Type = activatedscope->GetVariableType(identifier);
// TODO - support additional types
switch(payload->Type)
{
case VM::EpochVariableType_Integer:
payload->SetValue(activatedscope->GetVariableValue(identifier)->CastTo<VM::IntegerRValue>().GetValue());
break;
case VM::EpochVariableType_Integer16:
payload->SetValue(activatedscope->GetVariableValue(identifier)->CastTo<VM::Integer16RValue>().GetValue());
break;
case VM::EpochVariableType_Real:
payload->SetValue(activatedscope->GetVariableValue(identifier)->CastTo<VM::RealRValue>().GetValue());
break;
case VM::EpochVariableType_String:
payload->SetValue(activatedscope->GetVariableValue(identifier)->CastTo<VM::StringRValue>().GetValue().c_str());
break;
case VM::EpochVariableType_Array:
{
HandleType handle = activatedscope->GetVariableValue(identifier)->CastTo<VM::ArrayRValue>().GetHandle();
size_t elementcount = activatedscope->GetVariableValue(identifier)->CastTo<VM::ArrayRValue>().GetElementCount();
payload->SetValue(VM::ArrayVariable::GetArrayStorage(handle));
payload->ParameterCount = elementcount;
}
break;
default:
throw Exception("Unsupported type, cannot pass a variable of this type through a language extension library");
}
}
//
// Callback: register that an error occurred during some operation in the language extension library
//
// This function allows us to respond appropriately to errors in the extension library,
// without needing to worry about throwing actual exceptions across DLL boundaries.
//
void __stdcall ErrorCallback(const wchar_t* errormessage)
{
throw std::exception(narrow(errormessage).c_str());
}
}
//
// Request the library extension to register the keywords it wishes to add to the language
//
// Note that we also take this to inform the library of where to find callback
// functionality for compiling and otherwise handling Epoch code.
//
void ExtensionDLLAccess::RegisterExtensionKeywords(ExtensionLibraryHandle token)
{
Extensions::ExtensionInterface eif;
eif.Register = RegistrationCallback;
eif.RegisterControl = ControlRegistrationCallback;
eif.Traverse = TraversalCallback;
eif.TraverseFunction = TraverseFunctionCallback;
eif.MarshalRead = MarshalCallbackRead;
eif.MarshalWrite = MarshalCallbackWrite;
eif.Error = ErrorCallback;
DoRegistration(&eif, token);
}
//
// Request the library extension to do anything it needs to do in order to begin program execution
//
void ExtensionDLLAccess::PrepareForExecution()
{
DoPrepare(SessionHandle);
}
void ExtensionDLLAccess::FillSerializationBuffer(wchar_t*& buffer, size_t& buffersize)
{
DoFillSerializationBuffer(&buffer, &buffersize);
}
void ExtensionDLLAccess::FreeSerializationBuffer(wchar_t* buffer)
{
DoFreeSerializationBuffer(buffer);
}
void ExtensionDLLAccess::LoadDataBuffer(const std::string& buffer)
{
DoLoadDataBuffer(buffer.data(), buffer.size());
}
void ExtensionDLLAccess::PrepareCodeBlock(CodeBlockHandle handle)
{
DoPrepareBlock(handle);
}
void ExtensionDLLAccess::ClearEverything()
{
DoClearEverything();
}
| [
"[email protected]",
"don.apoch@localhost"
] | [
[
[
1,
16
],
[
18,
19
],
[
21,
21
],
[
24,
33
],
[
39,
40
],
[
42,
45
],
[
47,
49
],
[
51,
51
],
[
58,
59
],
[
64,
64
],
[
73,
78
],
[
80,
80
],
[
82,
91
],
[
100,
115
],
[
123,
123
],
[
132,
132
],
[
136,
136
],
[
142,
142
],
[
159,
159
],
[
162,
162
],
[
168,
168
],
[
177,
177
],
[
181,
181
],
[
198,
199
],
[
208,
214
],
[
216,
222
],
[
235,
243
],
[
245,
246
],
[
248,
259
],
[
262,
277
],
[
281,
286
],
[
295,
317
],
[
319,
324
],
[
326,
326
],
[
328,
339
],
[
341,
341
]
],
[
[
17,
17
],
[
20,
20
],
[
22,
23
],
[
34,
38
],
[
41,
41
],
[
46,
46
],
[
50,
50
],
[
52,
57
],
[
60,
63
],
[
65,
72
],
[
79,
79
],
[
81,
81
],
[
92,
99
],
[
116,
122
],
[
124,
131
],
[
133,
135
],
[
137,
141
],
[
143,
158
],
[
160,
161
],
[
163,
167
],
[
169,
176
],
[
178,
180
],
[
182,
197
],
[
200,
207
],
[
215,
215
],
[
223,
234
],
[
244,
244
],
[
247,
247
],
[
260,
261
],
[
278,
280
],
[
287,
294
],
[
318,
318
],
[
325,
325
],
[
327,
327
],
[
340,
340
],
[
342,
368
]
]
] |
6b40e1256efd3970db440fcc08d867cf983a2de0 | f7d5fcb47d370751163d253ac0d705d52bd3c5d5 | /tags/trunk/Sources/source/hapticgraphclasses/DragObjectHandler.h | 0f81095684d320935e56c504af98d62233935922 | [] | no_license | BackupTheBerlios/phantom-graphs-svn | b830eadf54c49ccecf2653e798e3a82af7e0e78d | 6a585ecde8432394c732a72e4860e136d68cc4b4 | refs/heads/master | 2021-01-02T09:21:18.231965 | 2006-02-06T08:44:57 | 2006-02-06T08:44:57 | 40,820,960 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 6,982 | h | //*******************************************************************************
/// @file DragObjectHandler.h
/// @author Katharina Greiner, Matr.-Nr. 943471
/// @date Erstellt am 15.12.2005
/// @date Letzte Änderung 15.12.2005
//*******************************************************************************
// Änderungen:
#ifndef _DRAGOBJECTHANDLER_H_
#define _DRAGOBJECTHANDLER_H_
// Haptic Library includes
#include <HL/hl.h>
#include <HDU/hduMatrix.h>
#include "HapticAction.h"
#include "HapticObject.h"
//...............................................................................
/// @author Katharina Greiner, Matr.-Nr. 943471
///
/// @brief Eine Eventhandlerklasse die es ermöglicht, haptische Objekte mit dem
/// Phantom zu bewegen
///
/// Der Eventhandler reagiert auf die folgende Events:
/// - der vordere Phantom-Button wird gedrückt, wenn ein Objekt mit dem
/// Phantom berührt wird
/// - das Phantom wird mit gedrücktem Button bewegt
/// - der vordere Phantom-Button wird losgelassen
/// Wirkung: Solange der Button gedrückt gehalten wird, folgt das
/// registrierte Objekt der Bewegung des Phantom
/// @todo Objekte lassen sich noch nicht nach hinten (in neg. z-Richtung) verschieben.
//...............................................................................
class DragObjectHandler : public IHapticAction
{
protected:
//.......................................................................
/// @brief Das Objekt, dem der Eventhandler zugeordnet ist. Wird NICHT
/// vom EventHandler freigegeben!
//.......................................................................
HapticObject * m_pDragObj;
//.......................................................................
/// @brief Position des Proxy beim letzten Aufruf des Draghandlers.
/// Dient zur Berechnung des Vektors um den das Objekt verschoben werden soll.
//.......................................................................
hduVector3Dd m_LastProxyPos;
//.......................................................................
/// @brief (HLAPI-Callbackfunktion) Started das Draggen des Objekts
/// @param event Gibt an, auf welches HLAPI-Event hin die Callback-
/// Funktion aufgerufen werden soll, hier HL_EVENT_1BUTTONDOWN.
/// @param shapeID Die ShapeID des Objekts, das bewegt werden soll.
/// @param thread Gibt an, in welchem HLAPI-Thread das Event behandelt
/// werden soll, in diesem Fall HL_CLIENT_THREAD.
/// @param cache HLAPI-State Schnappschuss in dem Moment, in dem das Event feuert.
/// @param pHandlerObject Pointer auf das DragObjectHandler-Objekt, das
/// das Event verarbeiten soll.
//.......................................................................
static void HLCALLBACK OnButtonDown(HLenum event,
HLuint shapeID,
HLenum thread,
HLcache *cache,
void *pHandlerObject);
//.......................................................................
/// @brief (HLAPI-Callbackfunktion) Beendet das Draggen des Objekts.
/// @param event Gibt an, auf welches HLAPI-Event hin die Callback-
/// Funktion aufgerufen werden soll, hier HL_EVENT_1BUTTONUP.
/// @param shapeID Hier soll HL_OBJECT_ANY angegeben werden.
/// @param thread Gibt an, in welchem HLAPI-Thread das Event behandelt
/// werden soll, in diesem Fall HL_CLIENT_THREAD.
/// @param cache HLAPI-State Schnappschuss in dem Moment, in dem das Event feuert.
/// @param unused Wird von dieser Funktion nicht benötigt.
//.......................................................................
static void HLCALLBACK OnButtonUp(HLenum event,
HLuint shapeID,
HLenum thread,
HLcache *cache,
void *unused);
//.......................................................................
/// @brief (HLAPI-Callbackfunktion) Steuert das Draggen des Objekts.
/// @param event Gibt an, auf welches HLAPI-Event hin die Callback-
/// Funktion aufgerufen werden soll, hier HL_EVENT_MOTION.
/// @param shapeID Hier soll HL_OBJECT_ANY angegeben werden.
/// @param thread Gibt an, in welchem HLAPI-Thread das Event behandelt
/// werden soll, in diesem Fall HL_CLIENT_THREAD.
/// @param cache HLAPI-State Schnappschuss in dem Moment, in dem das Event feuert.
/// @param pHandlerObject Pointer auf das DragObjectHandler-Objekt, das
/// das Event verarbeiten soll.
//.......................................................................
static void HLCALLBACK OnDrag(HLenum event,
HLuint shapeID,
HLenum thread,
HLcache *cache,
void *pHandlerObject);
public:
//.......................................................................
/// @brief Konstruktor, initialisiert das Eventhandler-Objekt mit dem
/// zugehörigen haptischen Objekt.
/// @param pObj Pointer auf das haptische Objekt für das der Eventhandler
/// zuständig sein soll. Wird NICHT vom EventHandler freigegeben!
//.......................................................................
DragObjectHandler(HapticObject * pObj);
//.......................................................................
/// @brief Nimmt die Proxy-Position beim Starten des Drag-Vorgangs auf.
/// @param pCache HLAPI-State Schnappschuss in dem Moment, in dem das Event feuert.
//.......................................................................
void initAction(HLcache * pCache);
//.......................................................................
/// @brief Veranlasst das haptische Objekt, sich mit dem Proxy zu bewegen.
/// @param pCache HLAPI-State Schnappschuss in dem Moment, in dem das Event feuert.
//.......................................................................
void handleDrag(HLcache * pCache);
//=======================================================================
// Von IHapticAction geerbte Methoden
//=======================================================================
//.......................................................................
/// @brief Registriert die Aktion für eine Shape bei HLAPI.
/// @param shapeID ID der Shape, für die die Aktion registriert werden soll.
//.......................................................................
virtual void registerAction( HLuint shapeID );
//.......................................................................
/// @brief Meldet die Aktion für eine Shape bei HLAPI ab.
/// @param shapeID ID der Shape, für die die Aktion registriert wurde.
//.......................................................................
virtual void unregisterAction( HLuint shapeID );
//=======================================================================
};
#endif // _DRAGOBJECTHANDLER_H_ | [
"frosch@a1b688d3-ce07-0410-8a3f-c797401f78de"
] | [
[
[
1,
143
]
]
] |
6adfa1dd0b6b1baa1d7d33ec4d0b458d8a7e6a7b | 5504cdea188dd5ceec6ab38863ef4b4f72c70b21 | /pcsxrr/plugins/cdrTAScdrom/plg_defs.cpp | fa82768d4413746187978aa5436f58edab10077d | [] | no_license | mauzus/pcsxrr | 959051bed227f96045a9bba8971ba5dffc24ad33 | 1b4c66d6a2938da55761280617d288f3c65870d7 | refs/heads/master | 2021-03-12T20:00:56.954014 | 2011-03-21T01:16:35 | 2011-03-21T01:16:35 | 32,238,897 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,071 | cpp | // Plugin Defs
#include "Locals.h"
// Dialog includes:
#include <windowsx.h>
#include <commctrl.h>
#include "resource.h"
typedef struct {
DWORD cbSize;
DWORD dwMajorVersion; // Major version
DWORD dwMinorVersion; // Minor version
DWORD dwBuildNumber; // Build number
DWORD dwPlatformID; // DLLVER_PLATFORM_*
} DLLVERSIONINFO_COMCTL32;
#define MAX_TOOLTIP_TEXT_LEN 1024 // max tooltip multi-line text len
static void dummy_ReadCfg(CFG_DATA *cfg) { cfg_InitDefaultValue(cfg); }
static void dummy_WriteCfg(const CFG_DATA *cfg) { }
// Plugin specific functions:
void (*fn_ReadCfg)(CFG_DATA *cfg) = dummy_ReadCfg;
void (*fn_WriteCfg)(const CFG_DATA *cfg) = dummy_WriteCfg;
// Misc data:
static HWND hwndTT = NULL; // tooltip control window
static HWND hwndSliderTT = NULL; // tooltip control for slider
static char *tt_text_long = NULL; // tooltip buffer for multi-line text
static int comctl32_version = 400; // comctl32.dll version (see comctl32_GetVersion())
// Plugin Config / About dialog callbacks:
BOOL CALLBACK ConfigDialogProc(HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar);
BOOL CALLBACK AboutDialogProc(HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar);
// Default configuration data:
static const CFG_DATA default_cfg_data = {
{ 0xFF, 0xFF, 0xFF, '\0', }, // drive_id.haid/target/lun/drive_letter = Auto
InterfaceType_Auto, // interface_type = Auto
ReadMode_Auto, // read_mode = Auto
0, // cdrom_speed = Default
0, // cdrom_spindown = Default
CacheLevel_ReadAsync, // cache_level = Enabled w/ multi-sector read & prefetch
75, // cache_asynctrig = Async read triggered at 75% of cache buffer
TRUE, // track_fsys = Enable ISO9660 tracking
SubQMode_Auto, // subq_mode = Auto
FALSE, // use_subfile = Use Subchannel file if present
};
// Tooltips for 'Config' dialog:
static struct {
int ctrl_id;
char *text_short; // single-line text (for comctl32 versions < 4.70, w/o multi-line support)
char *text_long; // multi-line text (for comctl32 versions >= 4.70): if NULL, use single-line test
} configdialog_tooltips[] = {
{ IDC_COMBO_DRIVE, "Select the CD-ROM drive you want to use",
" Autodetect = Choose the first CD-ROM with a PSX disk inside (recommended)\n" },
{ IDC_COMBO_INTERFACE, "Select the method to be used for access the CD-ROM drive",
"Supported modes for Win95/98/Me:\n"
" Autodetect = Choose the best mode automatically (recommended)\n"
" ASPI = Uses the SCSI ASPI driver, if it's installed\n"
" MSCDEX = Uses the native MSCDEX driver (not recommended)\n"
"Supported modes for WinNT/2K/XP:\n"
" Autodetect = Choose the best mode automatically (recommended)\n"
" IOCTL/SCSI = Uses the native SCSI IOCTL interface\n"
" ASPI = Uses the SCSI ASPI driver, if it's installed\n"
" IOCTL/RAW = Uses the native RAW IOCTL interface (not recommended)" },
{ IDC_COMBO_READMODE, "Select the command to be used for RAW sectors reading from the CD-ROM drive",
"Supported modes for ASPI and IOCTL/SCSI:\n"
" Autodetect = Choose the best mode automatically (recommended)\n"
" SCSI_BE = Supported by the most common and newer CD-ROM/DVD drives (best mode)\n"
" SCSI_28 = Supported by some older CD-ROM drives or with SCSI interface\n"
" SCSI/D8 = Non-standard mode, only for some PLEXTOR/TEAC models (not recommended)\n"
" SCSI/D4 = Non-standard mode, only for some NEC/SONY models (not recommended)\n"
"For MSCDEX and IOCTL/RAW, the only supported mode is RAW" },
{ IDC_COMBO_CDSPEED, "Limit the CD-ROM drive speed (if supported from drive)",
"Available options:\n"
" Default = don't change drive speed (recommended)\n"
" 2X...16X = set 2X...16X speed\n"
" MAX = use MAX drive speed", },
{ IDC_COMBO_CDSPINDOWN, "Change the CD-ROM spindown time (if supported from drive)",
"Available options:\n"
" Default = don't change spindown time (recommended)\n"
" 30sec...16min = Stop CD after 30sec...16min of inactivity", },
{ IDC_COMBO_CACHELEVEL, "Select if the readed data can be cached / prefetched",
"Available options:\n"
" 0 - Disabled (no caching) = Always access CD-ROM drive for reading (slowest)\n"
" 1 - Enabled, read one sector at time = Read/cache one sector at time (slow)\n"
" 2 - Enabled, prefetch multiple sectors = Read/cache multiple sectors a time (fast)\n"
" 3 - Enabled, prefetch with async reads = Add 'intelligent' asynchronous reads (fastest, recommended)", },
{ IDC_SLIDER_ASYNCTRIG, "Select the delay before starting async reads (% of last cache block readed)",
"It's recommended to leave the default value (75%), or at least to keep the slider inside the 'green' zone\n"
"Note: This option needs to be changed ONLY if there are noticeable delays during Movies && Sounds playback", },
{ IDC_CHECK_TRACKISOFS, "Track the CD-ROM files location/size (better read prediction, recommended)",
"When enabled, remember the exact files properties, improving read performance", },
{ IDC_COMBO_SUBREADMODE, "Select the command to be used for Subchannel reading from the CD-ROM drive",
"Supported modes for ASPI and IOCTL/SCSI:\n"
" Autodetect = Choose the best mode automatically (recommended)\n"
" SCSI_nn+16 = Same as 'Sector Read' modes, reads 16 bytes for Q Subchannel data\n"
" SCSI_nn+96 = Same as 'Sector Read' modes, reads 96 bytes for P-W Subchannel data\n"
" SCSI_42/RAW = Non-standard mode, supported but completely unreliable (not recommended)\n"
" Disabled = Don't read any subchannel data from the CD-ROM drive\n"
"Note: Subchannel reading is NOT supported from some CD-ROM drives !!!", },
{ IDC_CHECK_USESUBFILE, "Use Subchannel SBI / M3S file if present",
"When enabled, read subchannel data from SBI / M3S file instead from CD-ROM drive\n"
"The SBI / M3S files require a specific name convention described as follow:\n"
" NNNN_NNN.NN.SBI / NNNN_NNN.NN.M3S (as example: SLES_123.45.SBI)\n"
"where NNNN_NN.NN is the exact name of the file SLES*, SCES* or SLUS* on the CD\n"
"Note: This option is needed ONLY if CD-ROM does not support Subchannel reading", },
{ IDOK, "Save the current configuration",
NULL, },
{ IDCANCEL, "Exit without saving the configuration",
NULL, },
};
//------------------------------------------------------------------------------
// Support functions:
//------------------------------------------------------------------------------
const char *if_type_name(eInterfaceType if_type)
{
switch (if_type) {
case InterfaceType_Auto: return "Autodetect...";
case InterfaceType_Aspi: return "ASPI";
case InterfaceType_NtSpti: return "IOCTL/SCSI";
case InterfaceType_NtRaw: return "IOCTL/RAW";
case InterfaceType_Mscdex: return "MSCDEX";
default: return "???";
}
}
const char *rd_mode_name(eReadMode rmode)
{
switch (rmode) {
case ReadMode_Auto: return "Autodetect...";
case ReadMode_Raw: return "RAW";
case ReadMode_Scsi_28: return "SCSI_28 (READ_10)";
case ReadMode_Scsi_BE: return "SCSI_BE (READ_CD)";
case ReadMode_Scsi_D4: return "SCSI_D4 (CUSTOM)";
case ReadMode_Scsi_D8: return "SCSI_D8 (CUSTOM)";
default: return "???";
}
}
const char *cd_speed_name(int speed)
{
switch (speed) {
case 0: return "Default";
case 2: return "2 X";
case 4: return "4 X";
case 6: return "6 X";
case 8: return "8 X";
case 12: return "12 X";
case 16: return "16 X";
case 0xFFFF: return "MAX";
default: return "???";
}
}
const char *cd_spindown_name(int timer)
{
switch (timer) {
case INACTIVITY_TIMER_VENDOR_SPECIFIC: return "Default"; // 0 = Default
case INACTIVITY_TIMER_125MS:return "125 msec";
case INACTIVITY_TIMER_250MS:return "250 msec";
case INACTIVITY_TIMER_500MS:return "500 msec";
case INACTIVITY_TIMER_1S: return "1 sec";
case INACTIVITY_TIMER_2S: return "2 sec";
case INACTIVITY_TIMER_4S: return "4 sec";
case INACTIVITY_TIMER_8S: return "8 sec";
case INACTIVITY_TIMER_16S: return "16 sec";
case INACTIVITY_TIMER_32S: return "32 sec";
case INACTIVITY_TIMER_1MIN: return "1 min";
case INACTIVITY_TIMER_2MIN: return "2 min";
case INACTIVITY_TIMER_4MIN: return "4 min";
case INACTIVITY_TIMER_8MIN: return "8 min";
case INACTIVITY_TIMER_16MIN:return "16 min";
case INACTIVITY_TIMER_32MIN:return "32 min";
default: return "???";
}
}
const char *subq_mode_name(eSubQMode subQmode)
{
switch (subQmode) {
case SubQMode_Auto: return "Autodetect...";
case MAKE_SUBQMODE(ReadMode_Scsi_28, SubQMode_Read_Q): return "SCSI_28+16";
case MAKE_SUBQMODE(ReadMode_Scsi_28, SubQMode_Read_PW): return "SCSI_28+96";
case MAKE_SUBQMODE(ReadMode_Scsi_BE, SubQMode_Read_Q): return "SCSI_BE+16";
case MAKE_SUBQMODE(ReadMode_Scsi_BE, SubQMode_Read_PW): return "SCSI_BE+96";
case MAKE_SUBQMODE(ReadMode_Scsi_D8, SubQMode_Read_Q): return "SCSI_D8+16";
case MAKE_SUBQMODE(ReadMode_Scsi_D8, SubQMode_Read_PW): return "SCSI_D8+96";
case MAKE_SUBQMODE(ReadMode_Raw, SubQMode_SubQ): return "SCSI_42/RAW";
case SubQMode_Disabled: return "Disabled";
default: return "???";
}
}
const char *cache_level_name(eCacheLevel cache_level)
{
switch (cache_level) {
case CacheLevel_Disabled: return "0 - Disabled (no caching)";
case CacheLevel_ReadOne: return "1 - Enabled, read one sector at time";
case CacheLevel_ReadMulti: return "2 - Enabled, prefetch multiple sectors";
case CacheLevel_ReadAsync: return "3 - Enabled, prefetch with async reads (recommended)";
default: return "???";
}
}
const char *about_line_text(int nline)
{
switch (nline) {
case 0: return "A 'smart' CD-ROM plugin for use with any";
case 1: return "FPSE or PSEmu compatible PSX emulator";
case 2: return "FREE for any non-commercial use";
case 3: return "(C) 2002-2009 by SaPu";
default: return NULL; // end of 'About' text !!!
}
}
//------------------------------------------------------------------------------
// Generic plugin functions:
//------------------------------------------------------------------------------
void cfg_InitDefaultValue(CFG_DATA *cfg)
{
memcpy(cfg, &default_cfg_data, sizeof(*cfg));
}
void cfg_SetReadWriteCfgFn(void (*readCfgFn)(CFG_DATA *), void (*writeCfgFn)(const CFG_DATA *))
{
fn_ReadCfg = readCfgFn;
fn_WriteCfg = writeCfgFn;
}
static void comctl32_GetVersion(void)
{
HINSTANCE hDll;
HRESULT (CALLBACK* pDllGetVersion)(DLLVERSIONINFO_COMCTL32 *);
DLLVERSIONINFO_COMCTL32 dvi;
if ((hDll = LoadLibrary("comctl32.dll")) != NULL)
{
memset(&dvi, 0, sizeof(dvi));
dvi.cbSize = sizeof(dvi);
if ((pDllGetVersion = (HRESULT (CALLBACK *)(DLLVERSIONINFO_COMCTL32 *))GetProcAddress(hDll, "DllGetVersion")) != NULL &&
(*pDllGetVersion)(&dvi) >= 0)
comctl32_version = dvi.dwMajorVersion * 100 + dvi.dwMinorVersion;
FreeLibrary(hDll);
}
}
//------------------------------------------------------------------------------
// Plugin configuration dialog:
//------------------------------------------------------------------------------
void config_Dialog(HWND hwnd)
{
InitCommonControls(); // ensure that the common control DLL is loaded
DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG_CONFIG),
hwnd, (DLGPROC)ConfigDialogProc);
}
static void ConfigDialog_SetDriveId(HWND hwnd, const SCSIADDR *cur_drive_id)
{
HWND hdlg;
int idx, cur;
char buf[256];
hdlg = GetDlgItem(hwnd, IDC_COMBO_DRIVE);
ComboBox_ResetContent(hdlg);
ComboBox_AddString(hdlg, "Autodetect...");
for (idx = 0, cur = 0; idx < num_found_drives; idx++) {
SCSIADDR addr = found_drives[idx];
char *p = buf;
if (addr.drive_letter)
p += sprintf(p, "%c:", addr.drive_letter);
if (addr.haid != 0xFF && addr.target != 0xFF && addr.lun != 0xFF)
p += sprintf(p, " [%d:%d:%d]", addr.haid, addr.target, addr.lun);
if (*drive_info[idx].VendorId) {
p += sprintf(p, " %.8s", drive_info[idx].VendorId);
while (*(p - 1) == ' ') p--;
}
if (*drive_info[idx].ProductId) {
p += sprintf(p, " %.16s", drive_info[idx].ProductId);
while (*(p - 1) == ' ') p--;
}
/*if (*drive_info[idx].VendorSpecific) {
p += sprintf(p, " V%.20s", drive_info[idx].VendorSpecific);
while (*(p - 1) == ' ') p--;
}*/
*p = '\0';
ComboBox_AddString(hdlg, buf);
if (SCSIADDR_EQ(*cur_drive_id, found_drives[idx]))
cur = idx + 1; // idx(0) == Autodetect...
}
ComboBox_SetCurSel(hdlg, cur);
}
static void ConfigDialog_GetDriveId(HWND hwnd, SCSIADDR *addr)
{
int idx = ComboBox_GetCurSel(GetDlgItem(hwnd, IDC_COMBO_DRIVE));
*addr = (idx > 0 && idx <= num_found_drives) ? // idx(0) == Autodetect...
found_drives[idx - 1] : default_cfg_data.drive_id;
}
static void ConfigDialog_SetIfType(HWND hwnd, eInterfaceType cur_if_type)
{
HWND hdlg;
int idx, cur, num_if_types;
const eInterfaceType *if_types;
hdlg = GetDlgItem(hwnd, IDC_COMBO_INTERFACE);
ComboBox_ResetContent(hdlg);
ComboBox_AddString(hdlg, "Autodetect...");
num_if_types = get_if_types_auto(&if_types, FALSE);
for (idx = 0, cur = 0; idx < num_if_types; idx++) {
ComboBox_AddString(hdlg, if_type_name(if_types[idx]));
if (cur_if_type == if_types[idx])
cur = idx + 1; // idx(0) == Autodetect...
}
ComboBox_SetCurSel(hdlg, cur);
}
static void ConfigDialog_GetIfType(HWND hwnd, eInterfaceType *if_type)
{
const eInterfaceType *if_types;
int num_if_types = get_if_types_auto(&if_types, FALSE);
int idx = ComboBox_GetCurSel(GetDlgItem(hwnd, IDC_COMBO_INTERFACE));
*if_type = (idx > 0 && idx <= num_if_types) ? // idx(0) == Autodetect...
if_types[idx - 1] : default_cfg_data.interface_type;
}
static eInterfaceType last_if_type_for_RdMode_combo = InterfaceType_Auto;
static void ConfigDialog_SetRdMode(HWND hwnd, eReadMode cur_rd_mode)
{
HWND hdlg;
int idx, cur, num_rd_modes;
const eReadMode *rd_modes;
hdlg = GetDlgItem(hwnd, IDC_COMBO_READMODE);
ComboBox_ResetContent(hdlg);
// read 'if_type' & save the value for the *_GetReadMode() call
ConfigDialog_GetIfType(hwnd, &last_if_type_for_RdMode_combo);
num_rd_modes = get_rd_modes_auto(&rd_modes, last_if_type_for_RdMode_combo);
for (idx = 0, cur = 0; idx < num_rd_modes; idx++) {
ComboBox_AddString(hdlg, rd_mode_name(rd_modes[idx]));
if (cur_rd_mode == rd_modes[idx])
cur = idx;
}
ComboBox_Enable(hdlg, (num_rd_modes <= 1) ? FALSE : TRUE);
ComboBox_SetCurSel(hdlg, cur);
}
static void ConfigDialog_GetRdMode(HWND hwnd, eReadMode *rd_mode)
{
int idx, num_rd_modes;
const eReadMode *rd_modes;
// Note: The 'rd_mode' value is 'if_type' dependent, so we can need ...
// ... to use the value saved from the previous *_SetRdMode() call !!!
num_rd_modes = get_rd_modes_auto(&rd_modes, last_if_type_for_RdMode_combo);
// Note: if no choices availables (RAW only), don't need to write the ...
// ... rd_mode value (don't override the last working SCSI read mode).
if (num_rd_modes <= 1) return;
idx = ComboBox_GetCurSel(GetDlgItem(hwnd, IDC_COMBO_READMODE));
*rd_mode = (idx >= 0 && idx < num_rd_modes) ?
rd_modes[idx] : default_cfg_data.read_mode;
}
static void ConfigDialog_UpdateRdMode(HWND hwnd, eReadMode *rd_mode)
{
ConfigDialog_GetRdMode(hwnd, rd_mode);
ConfigDialog_SetRdMode(hwnd, *rd_mode);
}
static eInterfaceType last_if_type_for_CdSpeed_combo = InterfaceType_Auto;
static void ConfigDialog_SetCdSpeed(HWND hwnd, int cur_cd_speed)
{
HWND hdlg;
int idx, cur, num_cd_speeds;
const int *cd_speeds;
hdlg = GetDlgItem(hwnd, IDC_COMBO_CDSPEED);
ComboBox_ResetContent(hdlg);
// read 'if_type' & save the value for the *_GetCdSpeed() call
ConfigDialog_GetIfType(hwnd, &last_if_type_for_CdSpeed_combo);
num_cd_speeds = get_cd_speeds_auto(&cd_speeds, last_if_type_for_CdSpeed_combo);
for (idx = 0, cur = 0; idx < num_cd_speeds; idx++) {
ComboBox_AddString(hdlg, cd_speed_name(cd_speeds[idx]));
if (cur_cd_speed == cd_speeds[idx])
cur = idx;
}
ComboBox_Enable(hdlg, (num_cd_speeds <= 1) ? FALSE : TRUE);
ComboBox_SetCurSel(hdlg, cur);
}
static void ConfigDialog_GetCdSpeed(HWND hwnd, int *cd_speed)
{
int idx, num_cd_speeds;
const int *cd_speeds;
// Note: The 'cd_speed' value is 'if_type' dependent, so we can need ...
// ... to use the value saved from the previous *_SetCdSpeed() call !!!
num_cd_speeds = get_cd_speeds_auto(&cd_speeds, last_if_type_for_CdSpeed_combo);
// Note: if no choices availables (RAW only), don't need to write the ...
// ... cd_speed value (don't override the last working SCSI cdrom speed).
if (num_cd_speeds <= 1) return;
idx = ComboBox_GetCurSel(GetDlgItem(hwnd, IDC_COMBO_CDSPEED));
*cd_speed = (idx >= 0 && idx < num_cd_speeds) ?
cd_speeds[idx] : default_cfg_data.cdrom_speed;
}
static void ConfigDialog_UpdateCdSpeed(HWND hwnd, int *cd_speed)
{
ConfigDialog_GetCdSpeed(hwnd, cd_speed);
ConfigDialog_SetCdSpeed(hwnd, *cd_speed);
}
static eInterfaceType last_if_type_for_CdSpindown_combo = InterfaceType_Auto;
static void ConfigDialog_SetCdSpindown(HWND hwnd, int cur_cd_spindown)
{
HWND hdlg;
int idx, cur, num_cd_spindowns;
const int *cd_spindowns;
hdlg = GetDlgItem(hwnd, IDC_COMBO_CDSPINDOWN);
ComboBox_ResetContent(hdlg);
// read 'if_type' & save the value for the *_GetCdSpindown() call
ConfigDialog_GetIfType(hwnd, &last_if_type_for_CdSpindown_combo);
num_cd_spindowns = get_cd_spindowns_auto(&cd_spindowns, last_if_type_for_CdSpindown_combo);
for (idx = 0, cur = 0; idx < num_cd_spindowns; idx++) {
ComboBox_AddString(hdlg, cd_spindown_name(cd_spindowns[idx]));
if (cur_cd_spindown == cd_spindowns[idx])
cur = idx;
}
ComboBox_Enable(hdlg, (num_cd_spindowns <= 1) ? FALSE : TRUE);
ComboBox_SetCurSel(hdlg, cur);
}
static void ConfigDialog_GetCdSpindown(HWND hwnd, int *cd_spindown)
{
int idx, num_cd_spindowns;
const int *cd_spindowns;
// Note: The 'cd_spindown' value is 'if_type' dependent, so we can need ...
// ... to use the value saved from the previous *_SetCdSpindown() call !!!
num_cd_spindowns = get_cd_spindowns_auto(&cd_spindowns, last_if_type_for_CdSpindown_combo);
// Note: if no choices availables (RAW only), don't need to write the ...
// ... cd_spindown value (don't override the last working SCSI cdrom spindown).
if (num_cd_spindowns <= 1) return;
idx = ComboBox_GetCurSel(GetDlgItem(hwnd, IDC_COMBO_CDSPINDOWN));
*cd_spindown = (idx >= 0 && idx < num_cd_spindowns) ?
cd_spindowns[idx] : default_cfg_data.cdrom_spindown;
}
static void ConfigDialog_UpdateCdSpindown(HWND hwnd, int *cd_spindown)
{
ConfigDialog_GetCdSpindown(hwnd, cd_spindown);
ConfigDialog_SetCdSpindown(hwnd, *cd_spindown);
}
static void ConfigDialog_SetCacheLevel(HWND hwnd, eCacheLevel cur_cache_level)
{
HWND hdlg;
int idx, cur;
hdlg = GetDlgItem(hwnd, IDC_COMBO_CACHELEVEL);
ComboBox_ResetContent(hdlg);
for (idx = (int)CacheLevel_Disabled, cur = (int)default_cfg_data.cache_level; idx <= (int)CacheLevel_ReadAsync; idx++) {
ComboBox_AddString(hdlg, cache_level_name((eCacheLevel)idx));
if ((int)cur_cache_level == idx)
cur = idx;
}
ComboBox_SetCurSel(hdlg, cur);
}
static void ConfigDialog_GetCacheLevel(HWND hwnd, eCacheLevel *cache_level)
{
int idx = ComboBox_GetCurSel(GetDlgItem(hwnd, IDC_COMBO_CACHELEVEL));
*cache_level = (idx >= (int)CacheLevel_Disabled && idx <= (int)CacheLevel_ReadAsync) ?
(eCacheLevel)idx : default_cfg_data.cache_level;
}
static void ConfigDialog_SetAsyncTrig(HWND hwnd, int cur_cache_asynctrig)
{
HWND hdlg;
eCacheLevel tmp_cache_level;
hdlg = GetDlgItem(hwnd, IDC_SLIDER_ASYNCTRIG);
SendMessage(hdlg, TBM_SETRANGE, 0, MAKELONG(25, 75));
SendMessage(hdlg, TBM_SETTICFREQ, (75-25)/3, 0);
SendMessage(hdlg, TBM_SETPOS, TRUE, (LPARAM)cur_cache_asynctrig);
if (comctl32_version >= 470) {
SendMessage(hdlg, TBM_SETTIPSIDE, TBTS_BOTTOM, 0);
hwndSliderTT = (HWND)SendMessage(hdlg, TBM_GETTOOLTIPS, 0, 0);
}
ConfigDialog_GetCacheLevel(hwnd, &tmp_cache_level);
EnableWindow(hdlg, (tmp_cache_level < CacheLevel_ReadAsync) ? FALSE : TRUE);
}
static void ConfigDialog_GetAsyncTrig(HWND hwnd, int *cache_asynctrig)
{
*cache_asynctrig = SendMessage(GetDlgItem(hwnd, IDC_SLIDER_ASYNCTRIG), TBM_GETPOS, 0, 0);
}
static void ConfigDialog_UpdateAsyncTrig(HWND hwnd, int *cache_asynctrig)
{
ConfigDialog_GetAsyncTrig(hwnd, cache_asynctrig);
ConfigDialog_SetAsyncTrig(hwnd, *cache_asynctrig);
}
static void ConfigDialog_SetTrackIsoFs(HWND hwnd, BOOL cur_track_fsys)
{
HWND hdlg;
eCacheLevel tmp_cache_level;
hdlg = GetDlgItem(hwnd, IDC_CHECK_TRACKISOFS);
Button_SetCheck(hdlg, (cur_track_fsys) ? BST_CHECKED : BST_UNCHECKED);
ConfigDialog_GetCacheLevel(hwnd, &tmp_cache_level);
Button_Enable(hdlg, (tmp_cache_level < CacheLevel_ReadMulti) ? FALSE : TRUE);
}
static void ConfigDialog_GetTrackIsoFs(HWND hwnd, BOOL *track_fsys)
{
*track_fsys = (Button_GetCheck(GetDlgItem(hwnd, IDC_CHECK_TRACKISOFS)) == BST_CHECKED) ? TRUE : FALSE;
}
static void ConfigDialog_UpdateTrackIsoFs(HWND hwnd, BOOL *track_fsys)
{
ConfigDialog_GetTrackIsoFs(hwnd, track_fsys);
ConfigDialog_SetTrackIsoFs(hwnd, *track_fsys);
}
static eInterfaceType last_if_type_for_SubQMode_combo = InterfaceType_Auto;
static void ConfigDialog_SetSubQMode(HWND hwnd, eSubQMode cur_subq_mode)
{
HWND hdlg;
int idx, cur, num_subq_modes;
const eSubQMode *subq_modes;
hdlg = GetDlgItem(hwnd, IDC_COMBO_SUBREADMODE);
ComboBox_ResetContent(hdlg);
// read 'if_type' & save the value for the *_GetSubQMode() call
ConfigDialog_GetIfType(hwnd, &last_if_type_for_SubQMode_combo);
num_subq_modes = get_subq_modes_auto(&subq_modes, last_if_type_for_SubQMode_combo);
for (idx = 0, cur = 0; idx < num_subq_modes; idx++) {
ComboBox_AddString(hdlg, subq_mode_name(subq_modes[idx]));
if (cur_subq_mode == subq_modes[idx])
cur = idx;
}
ComboBox_Enable(hdlg, (num_subq_modes <= 1) ? FALSE : TRUE);
ComboBox_SetCurSel(hdlg, cur);
}
static void ConfigDialog_GetSubQMode(HWND hwnd, eSubQMode *subq_mode)
{
int idx, num_subq_modes;
const eSubQMode *subq_modes;
// Note: The 'subq_mode' value is 'if_type' dependent, so we can need ...
// ... to use the value saved from the previous *_SetSubQMode() call !!!
num_subq_modes = get_subq_modes_auto(&subq_modes, last_if_type_for_SubQMode_combo);
// Note: if no choices availables (RAW only), don't need to write the ...
// ... subq_mode value (don't override the last working SCSI subchannel mode).
if (num_subq_modes <= 1) return;
idx = ComboBox_GetCurSel(GetDlgItem(hwnd, IDC_COMBO_SUBREADMODE));
*subq_mode = (idx >= 0 && idx < num_subq_modes) ?
subq_modes[idx] : default_cfg_data.subq_mode;
}
static void ConfigDialog_UpdateSubQMode(HWND hwnd, eSubQMode *subq_mode)
{
ConfigDialog_GetSubQMode(hwnd, subq_mode);
ConfigDialog_SetSubQMode(hwnd, *subq_mode);
}
static void ConfigDialog_SetUseSubFile(HWND hwnd, BOOL cur_use_subfile)
{
Button_SetCheck(GetDlgItem(hwnd, IDC_CHECK_USESUBFILE), (cur_use_subfile) ? BST_CHECKED : BST_UNCHECKED);
}
static void ConfigDialog_GetUseSubFile(HWND hwnd, BOOL *use_subfile)
{
*use_subfile = (Button_GetCheck(GetDlgItem(hwnd, IDC_CHECK_USESUBFILE)) == BST_CHECKED) ? TRUE : FALSE;
}
static void ConfigDialog_InstallToolTips(HWND hwnd)
{
TOOLINFO ti;
int idx;
if ((hwndTT = CreateWindowEx(0, TOOLTIPS_CLASS, (LPSTR) NULL,
TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, hwnd, (HMENU) NULL, hInstance, NULL)) == NULL)
return;
tt_text_long = (char *)HeapAlloc(hProcessHeap, 0, MAX_TOOLTIP_TEXT_LEN + 1);
SetWindowPos(hwndTT, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSIZE);
for (idx = 0; idx < (sizeof(configdialog_tooltips) / sizeof(configdialog_tooltips[0])); idx++)
{
ZeroMemory(&ti, sizeof(TOOLINFO));
ti.cbSize = sizeof(TOOLINFO);
ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS | TTF_TRANSPARENT;
ti.hwnd = hwnd;
ti.uId = (UINT)GetDlgItem(hwnd, configdialog_tooltips[idx].ctrl_id);
ti.lpszText = LPSTR_TEXTCALLBACK;
SendMessage(hwndTT, TTM_ADDTOOL, 0, (LPARAM) (LPTOOLINFO) &ti);
}
SendMessage(hwndTT, TTM_SETDELAYTIME, TTDT_AUTOPOP, MAKELONG(30*1000,0));
SendMessage(hwndTT, TTM_ACTIVATE, TRUE, 0);
}
static void ConfigDialog_ToolTipsSetTextCallback(LPNMHDR lPar)
{
LPTOOLTIPTEXT lpttt;
int idCtrl, idx;
lpttt = (LPTOOLTIPTEXT)lPar;
idCtrl = GetDlgCtrlID((HWND)lPar->idFrom);
if (lPar->hwndFrom == hwndTT) {
for (idx = 0; idx < (sizeof(configdialog_tooltips) / sizeof(configdialog_tooltips[0])); idx++)
{
if (idCtrl != configdialog_tooltips[idx].ctrl_id)
continue;
if (comctl32_version >= 470 && configdialog_tooltips[idx].text_long != NULL)
{
int len = sprintf(tt_text_long, "%s\n%s", configdialog_tooltips[idx].text_short, configdialog_tooltips[idx].text_long);
#ifdef DEBUG
if (len >= MAX_TOOLTIP_TEXT_LEN)
__asm int 3
#endif//DEBUG
SendMessage(lPar->hwndFrom, TTM_SETMAXTIPWIDTH, 0, MAX_TOOLTIP_TEXT_LEN);
lpttt->lpszText = tt_text_long;
}
else
lpttt->lpszText = configdialog_tooltips[idx].text_short;
break;
}
} else if (lPar->hwndFrom == hwndSliderTT) {
if (idCtrl == IDC_SLIDER_ASYNCTRIG)
sprintf(lpttt->szText , "%d%%", (int)SendMessage((HWND)lPar->idFrom, TBM_GETPOS, 0, 0));
}
}
static void ConfigDialog_RemoveToolTips(void)
{
if (hwndTT != NULL) {
SendMessage(hwndTT, TTM_ACTIVATE, FALSE, 0);
DestroyWindow(hwndTT);
HeapFree(hProcessHeap, 0, tt_text_long);
tt_text_long = NULL;
}
hwndTT = NULL;
}
BOOL CALLBACK ConfigDialogProc(HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar)
{
static CFG_DATA config_data;
static HWND hwndTT = NULL;
switch (msg) {
case WM_INITDIALOG:
comctl32_GetVersion(); // read the common control DLL version
fn_ReadCfg(&config_data);
if (!num_found_drives && scan_AvailDrives())
setup_IfType(InterfaceType_Auto); // always reset I/F type to Auto !!!
ConfigDialog_SetDriveId(hwnd, &config_data.drive_id);
ConfigDialog_SetIfType(hwnd, config_data.interface_type);
ConfigDialog_SetRdMode(hwnd, config_data.read_mode);
ConfigDialog_SetCdSpeed(hwnd, config_data.cdrom_speed);
ConfigDialog_SetCdSpindown(hwnd, config_data.cdrom_spindown);
ConfigDialog_SetCacheLevel(hwnd, config_data.cache_level);
ConfigDialog_SetAsyncTrig(hwnd, config_data.cache_asynctrig);
ConfigDialog_SetTrackIsoFs(hwnd, config_data.track_fsys);
ConfigDialog_SetSubQMode(hwnd, config_data.subq_mode);
ConfigDialog_SetUseSubFile(hwnd, config_data.use_subfile);
ConfigDialog_InstallToolTips(hwnd);
return TRUE;
case WM_DESTROY:
EndDialog(hwnd,0);
return TRUE;
case WM_NOTIFY:
if (((LPNMHDR)lPar)->code == TTN_NEEDTEXT)
ConfigDialog_ToolTipsSetTextCallback((LPNMHDR)lPar);
break; //return FALSE;
case WM_COMMAND:
switch (LOWORD(wPar)) {
case IDC_COMBO_INTERFACE:
// track the 'if_type' combo changes to replace the previous ...
// ... avail read modes with the only 'if_type allowed' ones
if (HIWORD(wPar) == CBN_SELCHANGE) {
ConfigDialog_UpdateRdMode(hwnd, &config_data.read_mode);
ConfigDialog_UpdateCdSpeed(hwnd, &config_data.cdrom_speed);
ConfigDialog_UpdateCdSpindown(hwnd, &config_data.cdrom_spindown);
ConfigDialog_UpdateSubQMode(hwnd, &config_data.subq_mode);
} break;
case IDC_COMBO_CACHELEVEL:
if (HIWORD(wPar) == CBN_SELCHANGE) {
ConfigDialog_UpdateTrackIsoFs(hwnd, &config_data.track_fsys);
ConfigDialog_UpdateAsyncTrig(hwnd, &config_data.cache_asynctrig);
} break;
// case IDC_BUTTON_TESTMODE:
// { int __todo__testmode_button_; }
// return TRUE;
case IDOK:
ConfigDialog_GetDriveId(hwnd, &config_data.drive_id);
ConfigDialog_GetIfType(hwnd, &config_data.interface_type);
ConfigDialog_GetRdMode(hwnd, &config_data.read_mode);
ConfigDialog_GetCdSpeed(hwnd, &config_data.cdrom_speed);
ConfigDialog_GetCdSpindown(hwnd, &config_data.cdrom_spindown);
ConfigDialog_GetCacheLevel(hwnd, &config_data.cache_level);
ConfigDialog_GetAsyncTrig(hwnd, &config_data.cache_asynctrig);
ConfigDialog_GetTrackIsoFs(hwnd, &config_data.track_fsys);
ConfigDialog_GetSubQMode(hwnd, &config_data.subq_mode);
ConfigDialog_GetTrackIsoFs(hwnd, &config_data.track_fsys);
ConfigDialog_GetUseSubFile(hwnd, &config_data.use_subfile);
fn_WriteCfg(&config_data);
case IDCANCEL:
ConfigDialog_RemoveToolTips();
EndDialog(hwnd,0);
return TRUE;
}
break;
}
return FALSE;
}
//------------------------------------------------------------------------------
// Plugin about dialog:
//------------------------------------------------------------------------------
void about_Dialog(HWND hwnd)
{
DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG_ABOUT),
hwnd, (DLGPROC)AboutDialogProc);
}
static void AboutDialog_SetStaticText(HWND hwnd)
{
static int about_static_ctrl_id[] = {
IDC_STATIC_ABOUT_0, IDC_STATIC_ABOUT_1, IDC_STATIC_ABOUT_2, IDC_STATIC_ABOUT_3,
};
int idx;
Static_SetText(GetDlgItem(hwnd, IDC_STATIC_PLGNAME), PLUGIN_NAME);
for (idx = 0; idx < (sizeof(about_static_ctrl_id) / sizeof(about_static_ctrl_id[0])); idx++)
Static_SetText(GetDlgItem(hwnd, about_static_ctrl_id[idx]), about_line_text(idx));
}
BOOL CALLBACK AboutDialogProc(HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar)
{
switch (msg) {
case WM_INITDIALOG:
AboutDialog_SetStaticText(hwnd);
return TRUE;
case WM_DESTROY:
EndDialog(hwnd,0);
return TRUE;
case WM_COMMAND:
switch (wPar) {
case IDOK:
case IDCANCEL:
EndDialog(hwnd,0);
return TRUE;
}
}
return FALSE;
}
| [
"mauzus@b38eb22e-9255-0410-b643-f940c3bf2d76"
] | [
[
[
1,
775
]
]
] |
21cb70ceb6bcccb51fbf0b2454d1ab53cf08c8ed | aa96d2feea77cd3279120ca5a09c0407a2fbace6 | /src/Renderer.h | bdc8a439b2b15fa66b27e424cbe822531acbeef1 | [] | no_license | uri/2404-mega-project | 3287daf53e2bc15aebb4a3f88e4014f7b6c60054 | 3ce747c9486ace6c02c80ff7df98bf85fd5ac578 | refs/heads/master | 2016-09-06T10:21:46.835850 | 2011-11-04T03:05:40 | 2011-11-04T03:05:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,427 | h | ///////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------------------- //
// //
// Developers: David Krutsko, Uri Gorelik //
// Filename: Renderer.h //
// //
// --------------------------------------------------------------------- //
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------//
// Preambles //
//-----------------------------------------------------------------------//
#ifndef RENDERER_H
#define RENDERER_H
//-----------------------------------------------------------------------//
// Classes //
//-----------------------------------------------------------------------//
class Player;
///////////////////////////////////////////////////////////////////////////
/// <summary> Responsible for outputting everything to the screen. </summary>
class Renderer
{
public:
// Renderer
static void draw (Player *player, Player *enemy);
};
#endif // RENDERER_H
| [
"[email protected]"
] | [
[
[
1,
35
]
]
] |
c52011aa060ac2ae36a51a100235f8bcb46438a9 | ef37d76d24f90ba2d3aa4f9cf94025b2d4255673 | /Code/DataMerge.bak/DataMergeGui.cpp | dd84228ed1b9da220ce07605e9c466318d8e169d | [] | no_license | yuguess/GSoC | 799cb55773e5f5ea0925e39d337f35250c937e22 | 21354978f43ea1ebfdfab79f027cdfe04273d264 | refs/heads/master | 2020-05-19T03:53:01.965062 | 2010-08-24T18:20:01 | 2010-08-24T18:20:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,131 | cpp | #include "DataMergeGui.h"
#include <Qt/QtGui>
#include <vector>
#include "DataAccessor.h"
#include "DataAccessorImpl.h"
#include "DataRequest.h"
#include "DesktopServices.h"
#include "MessageLogResource.h"
#include "ObjectResource.h"
#include "PlugInArgList.h"
#include "PlugInManagerServices.h"
#include "PlugInRegistration.h"
#include "Progress.h"
#include "RasterDataDescriptor.h"
#include "RasterElement.h"
#include "RasterUtilities.h"
#include "SpatialDataView.h"
#include "SpatialDataWindow.h"
#include "switchOnEncoding.h"
#include "DataMerge.h"
#include "DataMergeGui.h"
#include "DataElement.h"
#include <limits>
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include "DesktopServices.h"
#include "MessageLogResource.h"
#include "ModelServices.h"
#include "PlugInRegistration.h"
#include "Service.h"
#include "SessionItemSerializer.h"
#include "UtilityServices.h"
#include "ApplicationServices.h"
#include "Progress.h"
#include "Resource.h"
#include "DesktopServices.h"
#include "UtilityServices.h"
#include "StringUtilities.h"
#include "RasterFileDescriptor.h"
#include "GcpList.h"
#include "ImportElement.h"
using namespace std;
namespace
{
template <typename T>
bool mergeElement(T *pData, int rowCount, int colCount, DataAccessor pSrcAcc, DataAccessor pDesAcc,
int band, Progress *pProgress, int size)
{
//char fileName[100];
//sprintf(fileName, "D:\\data%d.txt", band);
//ofstream file(fileName);
for (int row = 0; row < rowCount; row++)
{
for (int col = 0; col < colCount; col++)
{
pSrcAcc->toPixel(row, col);
pDesAcc->toPixel(row, col);
T *pSrcData = reinterpret_cast<T*>(pSrcAcc->getColumn());
T *pDesData = reinterpret_cast<T*>(pDesAcc->getColumn());
pDesData[band] = *pSrcData;
// file << " " << pDesData[band];
}
pProgress->updateProgress("Processing RasterElement" + StringUtilities::toDisplayString(band + 1),
((row+1) * (band + 1) * 100) / (rowCount * size), NORMAL);
}
//file.close();
return true;
}
};
DataMergeGui::DataMergeGui(QWidget *parent)
: QDialog(parent)
{
setModal(true);
flag = 0;
QHBoxLayout *listLayout = new QHBoxLayout();
QGroupBox *importGroup = new QGroupBox(tr("Imported RasterElement"));
importList = new QListWidget;
importList->setSelectionMode(QAbstractItemView::ContiguousSelection);
QVBoxLayout *importLayout = new QVBoxLayout;
importLayout->addWidget(importList);
importGroup->setLayout(importLayout);
QGroupBox *mergeGroup = new QGroupBox(tr("Select Merge RasterElement"));
mergeList = new QListWidget;
connect(mergeList, SIGNAL(itemSelectionChanged()), this, SLOT(selectionChangedSlot()));
//connect(mergeList, SIGNAL(pressed(QModelIndex)), this, SLOT(selectionChangedSlot()));
//connect(mergeList, SIGNAL(itemPressed(QListWidgetItem*)), this, SLOT(selectionChangedSlot()));
QVBoxLayout *mergeLayout = new QVBoxLayout;
mergeLayout->addWidget(mergeList);
mergeGroup->setLayout(mergeLayout);
listLayout->addWidget(importGroup);
listLayout->addWidget(mergeGroup);
QHBoxLayout *buttonLayout = new QHBoxLayout();
addButton = new QPushButton(tr("Add"));
removeButton = new QPushButton(tr("Remove"));
mergeButton = new QPushButton(tr("Merge"));
upButton = new QPushButton(tr("Up"));
downButton = new QPushButton(tr("Down"));
removeButton->setEnabled(false);
mergeButton->setEnabled(false);
upButton->setEnabled(false);
downButton->setEnabled(false);
connect(addButton, SIGNAL(clicked()), this, SLOT(addMergeList()));
connect(removeButton, SIGNAL(clicked()), this, SLOT(removeMergeList()));
connect(mergeButton, SIGNAL(clicked()), this, SLOT(mergeData()));
connect(upButton, SIGNAL(clicked()), this, SLOT(upButtonSlot()));
connect(downButton, SIGNAL(clicked()), this, SLOT(downButtonSlot()));
buttonLayout->addWidget(addButton);
buttonLayout->addWidget(removeButton);
buttonLayout->addWidget(mergeButton);
buttonLayout->addWidget(upButton);
buttonLayout->addWidget(downButton);
QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addLayout(listLayout);
mainLayout->addLayout(buttonLayout);
setLayout(mainLayout);
}
DataMergeGui::~DataMergeGui()
{
}
void DataMergeGui::addMergeList()
{
//QListWidgetItem *crtItem = importList->currentItem();
QList<QListWidgetItem *> selectedList = importList->selectedItems();
for (int i = 0; i < selectedList.count(); i++)
{
QListWidgetItem *crtItem = selectedList.at(i);
QString crtText = crtItem->text();
if (flag == 0)
{
RasterElement *pFisrtElement = filenameMap[crtText.toStdString()];
RasterDataDescriptor* pFirstDesc = static_cast<RasterDataDescriptor*>(pFisrtElement->getDataDescriptor());
firstType = pFirstDesc->getDataType();
firstRowCount = pFirstDesc->getRowCount();
firstColCount = pFirstDesc->getColumnCount();
}
else
{
RasterElement *pTempElement = filenameMap[crtText.toStdString()];
RasterDataDescriptor* pTempDesc = static_cast<RasterDataDescriptor*>(pTempElement->getDataDescriptor());
EncodingType tempType = pTempDesc->getDataType();
int tempRowCount = pTempDesc->getRowCount();
int tempColCount = pTempDesc->getColumnCount();
if (firstType != tempType)
{
QMessageBox::critical(NULL, "Spectral Data Merge", "Merge RasterElement type different!", "OK");
return;
}
if (firstRowCount != tempRowCount)
{
QMessageBox::critical(NULL, "Spectral Data Merge", "Merge RasterElement row different!", "OK");
return;
}
if (firstColCount != tempColCount)
{
QMessageBox::critical(NULL, "Spectral Data Merge", "Merge RasterElement column different!", "OK");
return;
}
}
QListWidgetItem *item = new QListWidgetItem(mergeList);
item->setText(crtText);
// mergeElementList.push_back(filenameMap[crtText.toStdString()]);
removeButton->setEnabled(true);
mergeButton->setEnabled(true);
flag = 1;
}
}
void DataMergeGui::removeMergeList()
{
QListWidgetItem *item = mergeList->currentItem();
if (item == NULL)
return;
QString itemText = item->text();
/*
RasterElement *pRasterElement = filenameMap[itemText.toStdString()];
vector<RasterElement*>::iterator it;
it = std::find(mergeElementList.begin(), mergeElementList.end(), pRasterElement);
mergeElementList.erase(it);*/
if (item != NULL)
item->~QListWidgetItem();
if (mergeList->count() == 0)
{
removeButton->setEnabled(false);
mergeButton->setEnabled(false);
flag = 0;
}
selectionChangedSlot();
}
//void DataMergeGui::addImportList(vector<ImportElement>& vec)
void DataMergeGui::addImportList(vector<string>& vec)
{
vector<string>::iterator iter;
for (iter = vec.begin(); iter != vec.end(); ++iter)
{
QListWidgetItem *item = new QListWidgetItem(importList);
item->setText(iter->c_str());
}
}
void DataMergeGui::setFilenameMap(std::map<string, RasterElement*> tmp)
{
filenameMap = tmp;
}
void DataMergeGui::setCubes(vector<DataElement*>& para)
{
cubes = para;
}
void DataMergeGui::setProgress(Progress *paraProgress)
{
pProgress = paraProgress;
}
bool DataMergeGui::upButtonSlot()
{
int curRow = mergeList->currentRow();
QListWidgetItem *curItem = mergeList->currentItem();
QString curItemText = curItem->text();
QListWidgetItem *preItem = mergeList->item(curRow - 1);
QString preItemText = preItem->text();
curItem->setText(preItemText);
preItem->setText(curItemText);
mergeList->setCurrentRow(curRow - 1);
return true;
}
bool DataMergeGui::downButtonSlot()
{
int curRow = mergeList->currentRow();
QListWidgetItem *curItem = mergeList->currentItem();
QString curItemText = curItem->text();
QListWidgetItem *nextItem = mergeList->item(curRow + 1);
QString nextItemText = nextItem->text();
curItem->setText(nextItemText);
nextItem->setText(curItemText);
mergeList->setCurrentRow(curRow + 1);
return true;
}
bool DataMergeGui::selectionChangedSlot()
{
if (mergeList->count() == 0)
{
upButton->setEnabled(false);
downButton->setEnabled(false);
return true;
}
int num = mergeList->count();
int curRow = mergeList->currentRow();
if (curRow == 0 && curRow == (num - 1))
{
upButton->setEnabled(false);
downButton->setEnabled(false);
return true;
}
if (curRow == 0)
{
upButton->setEnabled(false);
downButton->setEnabled(true);
return true;
}
if (curRow == (num - 1))
{
upButton->setEnabled(true);
downButton->setEnabled(false);
return true;
}
upButton->setEnabled(true);
downButton->setEnabled(true);
return true;
}
bool DataMergeGui::mergeData()
{
// Service<ModelServices> pModel;
StepResource pStep("Data Merge Begin", "app", "5E4BCD48-E662-408b-93AF-F9127CE56C66");
int mergeItemNum = mergeList->count();
if (mergeItemNum == 0)
{
QMessageBox::critical(NULL, "Spectral Data Merge", "No RasterElement to merge", "OK");
pStep->finalize(Message::Failure, "No RasterElement to merge");
return false;
}
for (int i = 0; i < mergeItemNum; i++)
{
QListWidgetItem *tmpItem = mergeList->item(i);
QString tmpItemText = tmpItem->text();
mergeElementList.push_back(filenameMap[tmpItemText.toStdString()]);
}
// pProgress = new Progress(this, "Progress Reporter");
// std::vector<DataElement*> cubes = pModel->getElements("RasterElement");
if (mergeElementList.size() == 0)
{
QMessageBox::critical(NULL, "Spectral Data Merge", "No RasterElement input found!", "OK");
pStep->finalize(Message::Failure, "No RasterElement input found!");
return false;
}
vector<RasterElement*>::iterator initIter = mergeElementList.begin();
RasterElement* pInitData = model_cast<RasterElement*>(*initIter);
if (pInitData == NULL)
{
pStep->finalize(Message::Failure, "Cube Data error!");
return false;
}
RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pInitData->getDataDescriptor());
EncodingType type = pDesc->getDataType();
int rowCount = pDesc->getRowCount();
int colCount = pDesc->getColumnCount();
int bandCount = mergeElementList.size();
RasterElement* pDesRaster = RasterUtilities::createRasterElement("DataMergeCube", rowCount,
colCount, bandCount, type, BIP, true, NULL);
if (pDesRaster == NULL)
{
QMessageBox::critical(NULL, "Spectral Data Merge", "Create RasterElement failed, Please close the previous merge result!", "OK");
pStep->finalize(Message::Failure, "No RasterElement input found!");
return false;
}
FactoryResource<DataRequest> pRequest;
pRequest->setInterleaveFormat(BIP);
pRequest->setWritable(true);
DataAccessor pDesAcc = pDesRaster->getDataAccessor(pRequest.release());
if (!pDesAcc.isValid())
{
QMessageBox::critical(NULL, "Spectral Data Merge", "pDesRaster Data Accessor Error!", "OK");
pStep->finalize(Message::Failure, "pDesRaster Data Accessor Error!");
return false;
}
if (pProgress == NULL)
{
QMessageBox::critical(NULL, "Spectral Data Merge", "pProgress Initialize Error!", "OK");
pStep->finalize(Message::Failure, "pProgress Error!");
return false;
}
// progressDialog = new QProgressDialog();
// progressDialog->setRange(0, rowCount);
int band = 0;
for (vector<RasterElement*>::iterator element = mergeElementList.begin();
element != mergeElementList.end(); ++element)
{
// progressDialog->setLabelText(tr("Merge RasterElement %1").arg(band + 1));
// progressDialog->show();
RasterElement* pData = model_cast<RasterElement*>(*element);
if (pData != NULL)
{
RasterDataDescriptor* pDesc = static_cast<RasterDataDescriptor*>(pData->getDataDescriptor());
if (rowCount != pDesc->getRowCount())
{
QMessageBox::critical(NULL, "Spectral Data Merge", "Merge Data Format Error!", "OK");
pStep->finalize(Message::Failure, "Merge Data Row Format Error!");
return false;
}
if (colCount != pDesc->getColumnCount())
{
QMessageBox::critical(NULL, "Spectral Data Merge", "Merge Data Format Error!", "OK");
pStep->finalize(Message::Failure, "Merge Data Column Format Error!");
return false;
}
FactoryResource<DataRequest> pRequest;
pRequest->setInterleaveFormat(BIP);
pRequest->setWritable(true);
DataAccessor pSrcAcc = pData->getDataAccessor(pRequest.release());
switchOnEncoding(pDesc->getDataType(), mergeElement, NULL, rowCount,
colCount, pSrcAcc, pDesAcc, band, pProgress, mergeElementList.size());
band++;
}
// progressDialog->hide();
}
Service<DesktopServices> pDesktop;
SpatialDataWindow* pWindow = static_cast<SpatialDataWindow*>(pDesktop->createWindow("DataMergeResult",
SPATIAL_DATA_WINDOW));
SpatialDataView* pView = (pWindow == NULL) ? NULL : pWindow->getSpatialDataView();
if (pView == NULL)
{
pStep->finalize(Message::Failure, "SpatialDataView error!");
return false;
}
pView->setPrimaryRasterElement(pDesRaster);
pView->createLayer(RASTER, pDesRaster);
if (pDesc != NULL)
{
const RasterFileDescriptor* pFileDescriptor = dynamic_cast<const RasterFileDescriptor*>(pDesc->getFileDescriptor());
if (pFileDescriptor != NULL)
{
Service<ModelServices> pModel;
if (pModel.get() != NULL)
{
list<GcpPoint> gcps;
gcps = pFileDescriptor->getGcps();
if (gcps.empty() == true)
{
if (pInitData->isGeoreferenced())
{
GcpPoint gcp;
// Lower left
gcp.mPixel.mX = 0.0;
gcp.mPixel.mY = 0.0;
gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
gcps.push_back(gcp);
// Lower right
gcp.mPixel.mX = colCount - 1;
gcp.mPixel.mY = 0.0;
gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
gcps.push_back(gcp);
// Upper left
gcp.mPixel.mX = 0.0;
gcp.mPixel.mY = rowCount - 1;
gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
gcps.push_back(gcp);
// Upper right
gcp.mPixel.mX = colCount - 1;
gcp.mPixel.mY = rowCount - 1;
gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
gcps.push_back(gcp);
// Center
gcp.mPixel.mX = colCount / 2.0;
gcp.mPixel.mY = rowCount / 2.0;
gcp.mCoordinate = pInitData->convertPixelToGeocoord(gcp.mPixel);
gcps.push_back(gcp);
}
}
if (gcps.empty() == false)
{
DataDescriptor* pGcpDescriptor = pModel->createDataDescriptor("Corner Coordinates",
"GcpList", pDesRaster);
if (pGcpDescriptor != NULL)
{
GcpList* pGcpList = static_cast<GcpList*>(pModel->createElement(pGcpDescriptor));
if (pGcpList != NULL)
{
// Add the GCPs to the GCP list
pGcpList->addPoints(gcps);
// Create the GCP list layer
pView->createLayer(GCP_LAYER, pGcpList);
}
}
}
}
}
}
return true;
} | [
"[email protected]"
] | [
[
[
1,
512
]
]
] |
dcac2636124e22c3d6da4aff3515b8d01f290a26 | 968aa9bac548662b49af4e2b873b61873ba6f680 | /imgtools/romtools/rofsbuild/fatimagegenerator.cpp | 815e9b75e37595623bb06660d64de72e4c04acd8 | [] | no_license | anagovitsyn/oss.FCL.sftools.dev.build | b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3 | f458a4ce83f74d603362fe6b71eaa647ccc62fee | refs/heads/master | 2021-12-11T09:37:34.633852 | 2010-12-01T08:05:36 | 2010-12-01T08:05:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,842 | cpp | /*
* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#include "fatimagegenerator.h"
#include "fatcluster.h"
#include "fsnode.h"
#include "h_utl.h"
#include <memory.h>
#include <time.h>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const TInt KCharsOfCmdWndLine = 80 ;
const TInt KRootEntryCount = 0x200;
const TInt KRootClusterIndex = 0;
TFatImgGenerator::TFatImgGenerator(TSupportedFatType aType ,ConfigurableFatAttributes& aAttr ) :
iType(aType),
iFatTable(0),
iFatTableBytes(0),
iTotalClusters(0),
iBytsPerClus(aAttr.iDriveClusterSize)
{
memset(&iBootSector,0,sizeof(iBootSector));
memset(&iFat32Ext,0,sizeof(iFat32Ext));
memset(&iFatHeader,0,sizeof(iFatHeader));
if(iBytsPerClus != 0){
if(iBytsPerClus > KMaxClusterBytes){
Print(EError,"Cluster size is too large!\n");
iType = EFatUnknown;
return ;
}else if(iBytsPerClus < aAttr.iDriveSectorSize){
Print(EError,"Cluster size cannot be smaller than sector size (%d)!\n", aAttr.iDriveSectorSize);
iType = EFatUnknown;
return ;
}else{
TUint32 tempSectorSize = aAttr.iDriveSectorSize;
while (tempSectorSize < iBytsPerClus){
tempSectorSize <<=1;
}
if (tempSectorSize > iBytsPerClus){
Print(EError,"Cluster size should be (power of 2)*(sector size) i.e. 512, 1024, 2048, 4096, etc!\n");
iType = EFatUnknown;
return;
}
}
}
if(aAttr.iDriveSectorSize != 512 && aAttr.iDriveSectorSize != 1024 && aAttr.iDriveSectorSize != 2048 && aAttr.iDriveSectorSize != 4096) {
Print(EError,"Sector size must be one of (512, 1024, 2048, 4096)!\n");
iType = EFatUnknown ;
return ;
}
*((TUint32*)iBootSector.BS_jmpBoot) = 0x00905AEB ;
memcpy(iBootSector.BS_OEMName,"SYMBIAN ",8);
*((TUint16 *)iBootSector.BPB_BytsPerSec) = aAttr.iDriveSectorSize;
iBootSector.BPB_NumFATs = aAttr.iDriveNoOfFATs;
iBootSector.BPB_Media = 0xF8 ;
iFatHeader.BS_DrvNum = 0x80 ;
iFatHeader.BS_BootSig = 0x29 ;
*((TUint32*)iFatHeader.BS_VolID) = aAttr.iVolumeId;
memcpy(iFatHeader.BS_VolLab,aAttr.iDriveVolumeLabel,sizeof(iFatHeader.BS_VolLab));
if(aAttr.iImageSize == 0){
if(aType == EFat32)
aAttr.iImageSize = 0x100000000LL ;// 4G
else
aAttr.iImageSize = 0x40000000LL ; // 1G
}
TUint32 totalSectors = (TUint32)((aAttr.iImageSize + aAttr.iDriveSectorSize - 1) / aAttr.iDriveSectorSize);
if(aType == EFat32) {
InitAsFat32(totalSectors,aAttr.iDriveSectorSize);
}
else if(aType == EFat16) {
InitAsFat16(totalSectors,aAttr.iDriveSectorSize);
}
if(iType == EFatUnknown) return ;
iBytsPerClus = iBootSector.BPB_SecPerClus * aAttr.iDriveSectorSize;
}
TFatImgGenerator::~TFatImgGenerator() {
if(iFatTable)
delete []iFatTable;
Interator it = iDataClusters.begin();
while(it != iDataClusters.end()){
TFatCluster* cluster = *it ;
delete cluster;
it++;
}
}
void TFatImgGenerator::InitAsFat16(TUint32 aTotalSectors,TUint16 aBytsPerSec){
TUint32 numOfClusters ;
TUint8 aSecPerClus = iBytsPerClus / aBytsPerSec;
if(aSecPerClus == 0) {
//Auto-calc the SecPerClus
// FAT32 ,Count of clusters must >= 4085 and < 65525 , however , to avoid the "off by xx" warning,
// proprositional value >= (4085 + 16) && < (65525 - 16)
if(aTotalSectors < (4085 + 16)) { //when SecPerClus is 1, numOfClusters eq to aTotalSectors
iType = EFatUnknown ;
Print(EError,"Size is too small for FAT16, please set a bigger size !\n");
return ;
}
TUint8 secPerClusMax = KMaxClusterBytes / aBytsPerSec;
numOfClusters = (aTotalSectors + secPerClusMax - 1) / secPerClusMax ;
if(numOfClusters >= (65525 - 16)) { // too big
iType = EFatUnknown ;
Print(EError,"Size is too big for FAT16, please use the FAT32 format!\n");
return ;
}
aSecPerClus = 1;
while(aSecPerClus < secPerClusMax){
numOfClusters = (aTotalSectors + aSecPerClus - 1) / aSecPerClus ;
if (numOfClusters >= (4085 + 16) && numOfClusters < (65525 - 16)) {
break;
}
aSecPerClus <<= 1 ;
}
}
else {
numOfClusters = (aTotalSectors + aSecPerClus - 1) / aSecPerClus;
if(numOfClusters >= (65525 - 16)){
Print(EError,"Cluster count is too big for FAT16, please use the FAT32 format or set a new bigger cluster size!\n");
iType = EFatUnknown ;
return ;
}
else if(numOfClusters < (4085 + 16)){
Print(EError,"Cluster count is too small for FAT16, please set a new smaller cluster size or set the image size bigger!\n");
iType = EFatUnknown ;
return ;
}
}
iTotalClusters = (aTotalSectors + aSecPerClus - 1) / aSecPerClus ;
iFatTableBytes = ((iTotalClusters << 1) + aBytsPerSec - 1) & (~(aBytsPerSec - 1));
iFatTable = new(std::nothrow) char[iFatTableBytes];
if(!iFatTable) {
Print(EError,"Memory allocation failed for FAT16 Table!\n");
iType = EFatUnknown ;
return ;
}
memset(iFatTable,0,iFatTableBytes);
*((TUint32*)iFatTable) = 0xFFFFFFF8 ;
iBootSector.BPB_SecPerClus = aSecPerClus;
*((TUint16*)iBootSector.BPB_RsvdSecCnt) = 0x0001 ;
*((TUint16*)iBootSector.BPB_RootEntCnt) = KRootEntryCount ;
if(aTotalSectors > 0xFFFF)
*((TUint32*)iBootSector.BPB_TotSec32) = aTotalSectors;
else
*((TUint16*)iBootSector.BPB_TotSec16) = (TUint16)aTotalSectors;
TUint16 sectorsForFAT = (TUint16)((iFatTableBytes + aBytsPerSec - 1) / aBytsPerSec);
*((TUint16*)iBootSector.BPB_FATSz16) = sectorsForFAT ;
memcpy(iFatHeader.BS_FilSysType,"FAT16 ",sizeof(iFatHeader.BS_FilSysType));
}
void TFatImgGenerator::InitAsFat32(TUint32 aTotalSectors,TUint16 aBytsPerSec) {
TUint32 numOfClusters;
TUint8 aSecPerClus = iBytsPerClus / aBytsPerSec;
if(aSecPerClus == 0) {
//Auto-calc the SecPerClus
// FAT32 ,Count of clusters must >= 65525, however , to avoid the "off by xx" warning,
// proprositional value >= (65525 + 16)
if(aTotalSectors < (65525 + 16)) { //when SecPerClus is 1, numOfClusters eq to aTotalSectors
iType = EFatUnknown ;
Print(EError,"Size is too small for FAT32, please use the FAT16 format, or set the data size bigger!\n");
return ;
}
TUint8 secPerClusMax = KMaxClusterBytes / aBytsPerSec;
aSecPerClus = secPerClusMax;
while(aSecPerClus > 1){
numOfClusters = (aTotalSectors + aSecPerClus - 1) / aSecPerClus ;
if (numOfClusters >= (65525 + 16)) {
break;
}
aSecPerClus >>= 1 ;
}
}
else {
numOfClusters = (aTotalSectors + aSecPerClus - 1) / aSecPerClus;
if(numOfClusters < (65525 + 16)) {
Print(EError,"Cluster count is too small for FAT32, please set a new smaller cluster size or set the image size bigger or use the FAT16 format!\n");
iType = EFatUnknown ;
return ;
}
}
iTotalClusters = (aTotalSectors + aSecPerClus - 1) / aSecPerClus ;
iFatTableBytes = ((iTotalClusters << 2) + aBytsPerSec - 1) & (~(aBytsPerSec - 1));
iFatTable = new(std::nothrow) char[iFatTableBytes];
if(!iFatTable) {
Print(EError,"Memory allocation failed for FAT32 Table!\n");
iType = EFatUnknown ;
return ;
}
memset(iFatTable,0,iFatTableBytes);
TUint32* fat32table = reinterpret_cast<TUint32*>(iFatTable);
fat32table[0] = 0x0FFFFFF8 ;
fat32table[1] = 0x0FFFFFFF ;
iBootSector.BPB_SecPerClus = aSecPerClus;
iBootSector.BPB_RsvdSecCnt[0] = 0x20 ;
*((TUint32*)iBootSector.BPB_TotSec32) = aTotalSectors;
*((TUint32*)iFat32Ext.BPB_FATSz32) = (iFatTableBytes + aBytsPerSec - 1) / aBytsPerSec;
*((TUint32*)iFat32Ext.BPB_RootClus) = 2 ;
*((TUint16*)iFat32Ext.BPB_FSInfo) = 1 ;
*((TUint16*)iFat32Ext.BPB_BkBootSec) = 6 ;
memcpy(iFatHeader.BS_FilSysType,"FAT32 ",sizeof(iFatHeader.BS_FilSysType));
}
bool TFatImgGenerator::Execute(TFSNode* aRootDir , const char* aOutputFile){
if(EFatUnknown == iType)
return false ;
ofstream o(aOutputFile,ios_base::binary + ios_base::out + ios_base::trunc);
TUint32 writtenBytes = 0 ;
if(!o.is_open()) {
Print(EError,"Can not open \"%s\" for writing !\n",aOutputFile) ;
return false;
}
TUint16 bytsPerSector = *((TUint16*)iBootSector.BPB_BytsPerSec);
Interator it = iDataClusters.begin();
while(it != iDataClusters.end()){
TFatCluster* cluster = *it ;
delete cluster;
it++;
}
iDataClusters.clear();
Print(EAlways,"Filesystem ready.\nWriting Header...");
if(EFat16 == iType){
char* header = new(std::nothrow) char[bytsPerSector];
if(!header){
Print(EError,"Can not allocate memory for FAT16 header!\n");
o.close();
return false ;
}
int offset = 0;
memcpy(header,&iBootSector,sizeof(iBootSector));
offset = sizeof(iBootSector);
memcpy(&header[offset],&iFatHeader,sizeof(iFatHeader));
offset += sizeof(iFatHeader);
memset(&header[offset],0,bytsPerSector - offset);
*((TUint16*)(&header[510])) = 0xAA55 ;
o.write(header,bytsPerSector);
writtenBytes += bytsPerSector;
delete []header ;
TUint16 rootDirSectors = (KRootEntryCount * 32) / bytsPerSector ;
TUint16 rootDirClusters = (rootDirSectors + iBootSector.BPB_SecPerClus - 1) /iBootSector.BPB_SecPerClus;
TUint32 rootDirBytes = KRootEntryCount * 32;
TFatCluster* rootDir = new(std::nothrow) TFatCluster(0,rootDirClusters);
rootDir->Init(rootDirBytes);
iDataClusters.push_back(rootDir);
aRootDir->WriteDirEntries(KRootClusterIndex,rootDir->GetData());
TUint index = 2 ;
Print(EAlways," OK.\nPreparing cluster list...");
TFSNode* child = aRootDir->GetFirstChild() ;
while(child){
if(!PrepareClusters(index,child)){
Print(EAlways," Failed.\nError:Image size is expected to be big enough for all the files.\n");
return false ;
}
child = child->GetSibling() ;
}
}
else if(EFat32 == iType){
TUint headerSize = ( bytsPerSector << 5 ); // 32 reserved sectors for fat32
char* header = new(std::nothrow) char[headerSize];
if(!header){
Print(EError,"Can not allocate memory for FAT32 header!\n");
o.close();
return false ;
}
memset(header,0,headerSize);
int offset = 0;
memcpy(header,&iBootSector,sizeof(iBootSector));
offset = sizeof(iBootSector);
memcpy(&header[offset],&iFat32Ext,sizeof(iFat32Ext));
offset += sizeof(iFat32Ext);
memcpy(&header[offset],&iFatHeader,sizeof(iFatHeader));
offset += sizeof(iFatHeader);
TFAT32FSInfoSector* fsinfo = reinterpret_cast<TFAT32FSInfoSector*>(&header[bytsPerSector]);
*((TUint32*)fsinfo->FSI_LeadSig) = 0x41615252 ;
*((TUint32*)fsinfo->FSI_StrucSig) = 0x61417272 ;
memset(fsinfo->FSI_Free_Count,0xFF,8);
char* tailed = header + 510 ;
for(int i = 0 ; i < 32 ; i++ , tailed += bytsPerSector )
*((TUint16*)tailed) = 0xAA55 ;
TUint index = 2 ;
Print(EAlways," OK.\nPreparing cluster list...");
if(!PrepareClusters(index,aRootDir)) {
Print(EAlways," Failed.\nERROR: Image size is expected to be big enough for all the files.\n");
delete []header ;
return false;
}
*(TUint32*)(fsinfo->FSI_Free_Count) = iTotalClusters - index + 3;
*(TUint32*)(fsinfo->FSI_Nxt_Free) = index ;
// write bakup boot sectors
memcpy(&header[bytsPerSector * 6],header,(bytsPerSector << 1));
o.write(header,headerSize);
writtenBytes += headerSize;
delete []header ;
}
//iDataClusters.sort();
it = iDataClusters.end() ;
it -- ;
int clusters = (*it)->GetIndex() + (*it)->ActualClusterCount() - 1;
Print(EAlways," OK.\n%d clusters of data need to be written.\nWriting Fat table...",clusters);
for(TUint8 w = 0 ; w < iBootSector.BPB_NumFATs ; w++){
o.write(iFatTable,iFatTableBytes);
if(o.bad() || o.fail()){
Print(EAlways,"\nERROR:Writting failed. Please check the filesystem\n");
delete []iFatTable,
o.close();
return false ;
}
writtenBytes += iFatTableBytes;
}
char* buffer = new(std::nothrow) char[KBufferedIOBytes];
if(!buffer){
Print(EError,"Can not allocate memory for I/O buffer !\n");
o.close();
return false ;
}
o.flush();
Print(EAlways," OK.\nWriting clusters data...");
int bytesInBuffer = 0;
int writeTimes = 24;
TFatCluster* lastClust = 0 ;
for(it = iDataClusters.begin(); it != iDataClusters.end() ; it++ ){
TFatCluster* cluster = *it ;
TUint fileSize = cluster->GetSize();
TUint toProcess = cluster->ActualClusterCount() * iBytsPerClus ;
if(toProcess > KBufferedIOBytes){ // big file
if(bytesInBuffer > 0){
o.write(buffer,bytesInBuffer);
if(o.bad() || o.fail()){
Print(EError,"Writting failed.\n");
delete []buffer,
o.close();
return false ;
}
writtenBytes += bytesInBuffer;
bytesInBuffer = 0;
Print(EAlways,".");
writeTimes ++ ;
if((writeTimes % KCharsOfCmdWndLine) == 0){
o.flush();
cout << endl ;
}
}
if(cluster->IsLazy()){
ifstream ifs(cluster->GetFileName(), ios_base::binary + ios_base::in);
if(!ifs.is_open()){
Print(EError,"Can not open file \"%s\"\n",cluster->GetFileName()) ;
o.close();
delete []buffer;
return false ;
}
if(!ifs.good()) ifs.clear();
TUint processedBytes = 0 ;
while(processedBytes < fileSize){
TUint ioBytes = fileSize - processedBytes ;
if(ioBytes > KBufferedIOBytes)
ioBytes = KBufferedIOBytes;
ifs.read(buffer,ioBytes);
processedBytes += ioBytes;
o.write(buffer,ioBytes);
if(o.bad() || o.fail()){
Print(EError,"Writting failed.\n");
delete []iFatTable,
o.close();
return false ;
}
writtenBytes += ioBytes;
Print(EAlways,".");
writeTimes ++ ;
if((writeTimes % KCharsOfCmdWndLine) == 0){
o.flush();
Print(EAlways,"\n") ;
}
}
TUint paddingBytes = toProcess - processedBytes;
if( paddingBytes > 0 ){
memset(buffer,0,paddingBytes);
o.write(buffer,paddingBytes);
if(o.bad() || o.fail()){
Print(EError,"Writting failed.\n");
delete []buffer,
o.close();
return false ;
}
writtenBytes += paddingBytes;
}
ifs.close();
}
else {
// impossible
Print(EError,"Unexpected result!\n");
o.close();
delete []buffer;
return false ;
}
}
else {
if(toProcess > (KBufferedIOBytes - bytesInBuffer)){
o.write(buffer,bytesInBuffer);
if(o.bad() || o.fail()){
Print(EError,"Writting failed.\n");
delete []buffer,
o.close();
return false ;
}
writtenBytes += bytesInBuffer;
Print(EAlways,".");
writeTimes ++ ;
if((writeTimes % KCharsOfCmdWndLine) == 0){
o.flush();
cout << endl ;
}
bytesInBuffer = 0;
}
if(cluster->IsLazy()){
ifstream ifs(cluster->GetFileName(), ios_base::binary + ios_base::in);
if(!ifs.is_open()){
Print(EError,"Can not open file \"%s\"\n",cluster->GetFileName()) ;
o.close();
delete []buffer;
return false ;
}
if(!ifs.good()) ifs.clear();
ifs.read(&buffer[bytesInBuffer],fileSize);
bytesInBuffer += fileSize;
if(toProcess > fileSize) { // fill padding bytes
memset(&buffer[bytesInBuffer],0,toProcess - fileSize);
bytesInBuffer += (toProcess - fileSize);
}
ifs.close();
}
else{
if(toProcess != cluster->GetSize() && cluster->GetIndex() != KRootClusterIndex){
Print(EError,"Unexpected size!\n");
o.close();
delete []buffer;
return false ;
}
memcpy(&buffer[bytesInBuffer],cluster->GetData(),cluster->GetSize());
bytesInBuffer += cluster->GetSize();
}
}
lastClust = cluster ;
}
if(bytesInBuffer > 0){
o.write(buffer,bytesInBuffer);
if(o.bad() || o.fail()){
Print(EError,"Writting failed.\n");
delete []buffer,
o.close();
return false ;
}
writtenBytes += bytesInBuffer;
o.flush();
}
Print(EAlways,"\nDone.\n\n");
o.close();
return true ;
}
bool TFatImgGenerator::PrepareClusters(TUint& aNextClusIndex,TFSNode* aNode) {
TUint sizeOfItem = aNode->GetSize();
TUint clusters = (sizeOfItem + iBytsPerClus - 1) / iBytsPerClus;
if(iTotalClusters < aNextClusIndex + clusters)
return false ;
TUint16* fat16Table = reinterpret_cast<TUint16*>(iFatTable);
TUint32* fat32Table = reinterpret_cast<TUint32*>(iFatTable);
for(TUint i = aNextClusIndex + clusters - 1 ; i > aNextClusIndex ; i--){
if(iType == EFat16)
fat16Table[i - 1] = i ;
else
fat32Table[i - 1] = i ;
}
if(iType == EFat16)
fat16Table[aNextClusIndex + clusters - 1] = 0xffff ;
else
fat32Table[aNextClusIndex + clusters - 1] = 0x0fffffff ;
TFatCluster* cluster = new TFatCluster(aNextClusIndex,clusters);
if(aNode->IsDirectory()) {
TUint bytes = clusters * iBytsPerClus ;
cluster->Init(bytes);
aNode->WriteDirEntries(aNextClusIndex,cluster->GetData());
}
else {
cluster->LazyInit(aNode->GetPCSideName(),sizeOfItem);
aNode->WriteDirEntries(aNextClusIndex,NULL);
}
iDataClusters.push_back(cluster);
aNextClusIndex += clusters;
if(aNode->GetFirstChild()){
if(!PrepareClusters(aNextClusIndex,aNode->GetFirstChild()))
return false ;
}
if(aNode->GetSibling()){
if(!PrepareClusters(aNextClusIndex,aNode->GetSibling()))
return false;
}
return true ;
}
| [
"none@none",
"[email protected]"
] | [
[
[
1,
37
],
[
39,
42
],
[
65,
65
],
[
67,
78
],
[
80,
89
],
[
91,
92
],
[
94,
109
],
[
111,
112
],
[
114,
142
],
[
144,
147
],
[
149,
174
],
[
176,
177
],
[
179,
201
],
[
203,
548
]
],
[
[
38,
38
],
[
43,
64
],
[
66,
66
],
[
79,
79
],
[
90,
90
],
[
93,
93
],
[
110,
110
],
[
113,
113
],
[
143,
143
],
[
148,
148
],
[
175,
175
],
[
178,
178
],
[
202,
202
]
]
] |
729817987185733a13d41a85ef9ddbc46f075f45 | d258dd0ca5e8678c8eb81777e5fe360b8bbf7b7e | /Library/PhysXCPP/NxaCharacterControllerManager.cpp | a774cd08fb06d223b2303dafce467807787f2ba4 | [] | no_license | ECToo/physxdotnet | 1e7d7e9078796f1dad5c8582d28441a908e11a83 | 2b85d57bc877521cdbf1a9147bd6716af68a64b0 | refs/heads/master | 2021-01-22T07:17:58.918244 | 2008-04-13T11:15:26 | 2008-04-13T11:15:26 | 32,543,781 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 141 | cpp | #include "StdAfx.h"
#include "NxaCharacterControllerManager.h"
NxaCharacterControllerManager::NxaCharacterControllerManager(void)
{
}
| [
"thomasfannes@e8b6d1ee-b643-0410-9178-bfabf5f736f5"
] | [
[
[
1,
6
]
]
] |
b8fb07c93c30add2a0eb359c558771eda808e98b | 252e638cde99ab2aa84922a2e230511f8f0c84be | /reflib/src/StopModelViewForm.cpp | ca5e264781241ac1ade09a4ae65f499e348e6059 | [] | 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 | 7,138 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "StdTool.h"
#include "TourTool.h"
#include "StopModelViewForm.h"
#if defined(TOUR_LINKBASE_MODE)
#include "StopModelAddForm.h"
#include "StopModelEditForm.h"
#else
#include "StopModelSimpleAddForm.h"
#include "StopModelSimpleEditForm.h"
#endif
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "Placemnt"
#pragma link "RXDBCtrl"
#pragma link "TableGridViewForm"
#pragma link "VADODataSourceOrdering"
#pragma link "VCustomDataSourceOrdering"
#pragma link "VDBGridFilterDialog"
#pragma link "VDBSortGrid"
#pragma link "VStringStorage"
#pragma link "VCustomDBGridFilterDialog"
#pragma resource "*.dfm"
TTourRefBookStopModelViewForm *TourRefBookStopModelViewForm;
#define GetTranslatedStr(Index) VStringStorage->Lines->Strings[Index]
//---------------------------------------------------------------------------
__fastcall TTourRefBookStopModelViewForm::TTourRefBookStopModelViewForm(TComponent* Owner)
: TTourRefBookTableGridViewForm(Owner)
{
}
//---------------------------------------------------------------------------
#ifdef TOUR_LINKBASE_MODE
///*
void __fastcall TTourRefBookStopModelViewForm::NewActionExecute(
TObject *Sender)
{
TTourRefBookStopModelAddForm *TourRefBookStopModelAddFormPtr;
FunctionArgUsedSkip(Sender);
TourRefBookStopModelAddFormPtr = NULL;
if (!EditLocked)
{
try
{
Application->CreateForm(__classid(TTourRefBookStopModelAddForm),
&TourRefBookStopModelAddFormPtr);
if (TourRefBookStopModelAddFormPtr != NULL)
{
TourRefBookStopModelAddFormPtr->MainQueryDataSet = MainQuery;
ShowProcessAdd(TourRefBookStopModelAddFormPtr);
delete (TourRefBookStopModelAddFormPtr);
TourRefBookStopModelAddFormPtr = NULL;
}
else
{
throw Exception(GetTranslatedStr(TourRefBookCreateObjectErrorMessageStr)
+ "TTourRefBookStopModelAddForm");
}
}
catch (Exception &exception)
{
TourShowDialogException(NULL,&exception);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TTourRefBookStopModelViewForm::EditActionExecute(
TObject *Sender)
{
TTourRefBookStopModelEditForm *TourRefBookStopModelEditFormPtr;
FunctionArgUsedSkip(Sender);
TourRefBookStopModelEditFormPtr = NULL;
if (!EditLocked)
{
try
{
Application->CreateForm(__classid(TTourRefBookStopModelEditForm),
&TourRefBookStopModelEditFormPtr);
if (TourRefBookStopModelEditFormPtr != NULL)
{
TourRefBookStopModelEditFormPtr->MainQueryDataSet = MainQuery;
ShowProcessEdit(TourRefBookStopModelEditFormPtr);
delete (TourRefBookStopModelEditFormPtr);
TourRefBookStopModelEditFormPtr = NULL;
}
else
{
throw Exception(GetTranslatedStr(TourRefBookCreateObjectErrorMessageStr)
+ "TTourRefBookStopModelEditForm");
}
}
catch (Exception &exception)
{
TourShowDialogException(NULL,&exception);
}
}
}
//*/
#else
///*
void __fastcall TTourRefBookStopModelViewForm::NewActionExecute(
TObject *Sender)
{
TTourStopModelSimpleAddForm *AddFormPtr;
FunctionArgUsedSkip(Sender);
AddFormPtr = NULL;
if (!EditLocked)
{
try
{
Application->CreateForm(__classid(TTourStopModelSimpleAddForm),&AddFormPtr);
if (AddFormPtr != NULL)
{
if (AddFormPtr->ShowModal() == mrOk)
{
CursorWaitOpen();
try
{
MainQuery->Append();
MainQuery->FieldByName("stop_model")->AsString
= AddFormPtr->StopModelEdit->Text;
if (!AddFormPtr->StopModelNameEdit->Text.IsEmpty())
{
MainQuery->FieldByName("stopmodel_name")->AsString
= AddFormPtr->StopModelNameEdit->Text;
}
MainQuery->Post();
}
catch (...)
{
MainQuery->Cancel();
}
CursorWaitClose();
}
delete (AddFormPtr);
AddFormPtr = NULL;
}
else
{
throw Exception(GetTranslatedStr(TourRefBookCreateObjectErrorMessageStr)
+ "TTourStopModelSimpleAddForm");
}
}
catch (Exception &exception)
{
TourShowDialogException(NULL,&exception);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TTourRefBookStopModelViewForm::EditActionExecute(
TObject *Sender)
{
TTourStopModelSimpleEditForm *EditFormPtr;
FunctionArgUsedSkip(Sender);
EditFormPtr = NULL;
if (!EditLocked)
{
try
{
Application->CreateForm(__classid(TTourStopModelSimpleEditForm),&EditFormPtr);
if (EditFormPtr != NULL)
{
EditFormPtr->StopModelEdit->Text
= MainQuery->FieldByName("stop_model")->AsString;
EditFormPtr->StopModelNameEdit->Text
= MainQuery->FieldByName("stopmodel_name")->AsString;
if (EditFormPtr->ShowModal() == mrOk)
{
CursorWaitOpen();
try
{
MainQuery->Edit();
// MainQuery->FieldByName("stop_model")->AsString
// = EditFormPtr->StopModelEdit->Text;
if (!EditFormPtr->StopModelNameEdit->Text.IsEmpty())
{
MainQuery->FieldByName("stopmodel_name")->AsString
= EditFormPtr->StopModelNameEdit->Text;
}
else
{
MainQuery->FieldByName("stopmodel_name")->Value
= Variant().ChangeType(varNull);
}
MainQuery->Post();
}
catch (...)
{
MainQuery->Cancel();
}
CursorWaitClose();
}
delete (EditFormPtr);
EditFormPtr = NULL;
}
else
{
throw Exception(GetTranslatedStr(TourRefBookCreateObjectErrorMessageStr)
+ "TTourStopModelSimpleEditForm");
}
}
catch (Exception &exception)
{
TourShowDialogException(NULL,&exception);
}
}
}
//*/
#endif
//---------------------------------------------------------------------------
void __fastcall TTourRefBookStopModelViewForm::FormClose(TObject *Sender,
TCloseAction &Action)
{
TTourRefBookTableGridViewForm::FormClose(Sender,Action);
TourRefBookStopModelViewForm = NULL;
}
//---------------------------------------------------------------------------
#undef GetTranslatedStr(Index)
| [
"[email protected]"
] | [
[
[
1,
260
]
]
] |
04552d5643c785048e9e14bb3c1acb552a607f9c | 7e8eda9c74315df15b165b43f330da76f77e163e | /src/VEProj4/simple_model.cpp | aeb57efe04cab1ff688f24508cc6630912128e65 | [] | no_license | pixelperfect3/3d-scene-editor | e9375cf211e984ce92dc6aab44f2ab8f4a3ecca8 | 02db9bc2b1b1de1f5405ab66c80fd86f4b1b4df8 | refs/heads/master | 2016-09-06T02:00:01.057542 | 2009-04-21T18:56:32 | 2009-04-21T18:56:32 | 32,138,477 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 765 | cpp | #include "ogre.h"
#include "simple_model.h"
using namespace std;
istream& operator>>(istream& is, Ogre::Vector3 v) {
is >> v.x >> v.y >> v.z;
return is;
}
//ostream& operator <<(ostream &os, Ogre::Vector3 v) {
// os << v.x << v.y << v.z;
// return os;
//}
istream& operator>>(istream& is, SimpleModel m) {
//Cannot de-serialize the parent node.
double radians = m.orientation.valueRadians();
is >> m.meshName >> m.model_num >> m.start >> radians;
m.orientation = radians;
return is;
}
ostream& operator <<(ostream &os, SimpleModel m) {
//Cannot serialize the parent node. Try using the scene-manager API to find or create it, again.
os << m.meshName << m.model_num << m.start << m.orientation.valueRadians();
return os;
}
| [
"ethan.sherrie@d3cd3af8-22d8-11de-85c7-557234b16fc6"
] | [
[
[
1,
28
]
]
] |
662847597c2f9cddc09157b0c61bdc75e93ba085 | 15fc90dea35740998f511319027d9971bae9251c | /ImportRename/src/irMain.cpp | 94eee00d4c0544cbfcdba1d2cefe0aa258560a78 | [] | no_license | ECToo/switch-soft | c35020249be233cf1e35dc18b5c097894d5efdb4 | 5edf2cc907259fb0a0905fc2c321f46e234e6263 | refs/heads/master | 2020-04-02T10:15:53.067883 | 2009-05-29T15:13:23 | 2009-05-29T15:13:23 | 32,216,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,936 | cpp | // ============================================================================
// UnPackage :: Cross-platform toolkit for Unreal Engine packages
// Copyright (C) 2006 Roman Dzieciol. All Rights Reserved.
// ============================================================================
// irMain.cpp
// ============================================================================
#include "stdafx.h"
#include "irMain.h"
#include "irPkg.h"
// ============================================================================
// irMain
// ============================================================================
int irMain::OnRun()
{
try
{
static const wxCmdLineEntryDesc cmdLineDesc[] =
{
{ wxCMD_LINE_PARAM, NULL, NULL, _T("InputFile"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_OPTION_MANDATORY },
{ wxCMD_LINE_PARAM, NULL, NULL, _T("OldName"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
{ wxCMD_LINE_PARAM, NULL, NULL, _T("NewName"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
{ wxCMD_LINE_NONE, NULL, NULL, NULL, (wxCmdLineParamType)0, 0 }
};
wxCmdLineParser parser(cmdLineDesc, argc, argv);
switch (parser.Parse())
{
case -1:
return 0;
case 0:
ParseParams(parser);
return 0;
}
return 1;
}
catch( upexception& e ) { wxLogError(wxT("%s"), e.wwhat()); return 1; }
catch( exception& e ) { wxLogError(wxT("%hs"), e.what()); return 1; }
}
void irMain::ParseParams( const wxCmdLineParser& cmdline )
{
if( cmdline.GetParamCount() == 1 )
{
RenameImport( wxT("SwampTextures"), wxT("JRTX_SwampJZ"), cmdline.GetParam(0) );
RenameImport( wxT("SwampNoTexture"), wxT("JRSM_SwampJZ"), cmdline.GetParam(0) );
RenameImport( wxT("JurassicRage"), wxT("JRSM_Misc"), cmdline.GetParam(0) );
RenameImport( wxT("JRMeshes"), wxT("JRTX_Misc"), cmdline.GetParam(0) );
}
else if( cmdline.GetParamCount() == 3 )
{
RenameImport( cmdline.GetParam(1), cmdline.GetParam(2), cmdline.GetParam(0) );
}
wxShell(wxT("PAUSE"));
}
void irMain::RenameImport( const wxString& oldname, const wxString& newname, const wxString& filename )
{
guard;
//wxLogMessage( wxT("") );
//wxLogMessage( wxT("RenameImport() %s"), filename.c_str() );
// Rename imports
{
// Load
upFileReader freader( filename );
irPkg pkg( freader.Length() );
pkg.Serialize(freader);
// Rename
pkg.RenameImport( oldname, newname );
// Write
upFileWriter fwriter( filename + wxT(".ir.temp") );
fwriter.Serialize( freader.GetDataPtr(), freader.Length() );
pkg.Serialize(fwriter);
}
wxRemoveFile( filename );
wxRenameFile( filename + wxT(".ir.temp"), filename );
// Rename files
unguard;
}
// ============================================================================
// The End.
// ============================================================================ | [
"roman.dzieciol@e6f6c67e-47ec-11de-80ae-c1ff141340a0"
] | [
[
[
1,
101
]
]
] |
8713545e9a64edc7fc974b9bad9ad263dbd63e26 | 51d93b29d2ee286e666c18471574817b9d9ef670 | /ghost/bnetprotocol.h | 1b7d83ea0a0d768942481dead06669d323c42a30 | [
"Apache-2.0"
] | permissive | crazzy263/ghostplusplus-nibbits | 824d6735fccd3daa92e27797e9de29931028b530 | 2ea18f5d82a97351b82d16bc734469896b2ffedf | refs/heads/master | 2021-01-16T22:05:54.409065 | 2009-11-26T22:20:28 | 2009-11-26T22:20:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,333 | h | /*
Copyright [2008] [Trevor Hogan]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#ifndef BNETPROTOCOL_H
#define BNETPROTOCOL_H
//
// CBNETProtocol
//
#define BNET_HEADER_CONSTANT 255
class CIncomingGameHost;
class CIncomingChatEvent;
class CIncomingFriendList;
class CIncomingClanList;
class CBNETProtocol
{
public:
enum Protocol {
SID_NULL = 0, // 0x0
SID_STOPADV = 2, // 0x2
SID_GETADVLISTEX = 9, // 0x9
SID_ENTERCHAT = 10, // 0xA
SID_JOINCHANNEL = 12, // 0xC
SID_CHATCOMMAND = 14, // 0xE
SID_CHATEVENT = 15, // 0xF
SID_CHECKAD = 21, // 0x15
SID_STARTADVEX3 = 28, // 0x1C
SID_DISPLAYAD = 33, // 0x21
SID_NOTIFYJOIN = 34, // 0x22
SID_PING = 37, // 0x25
SID_LOGONRESPONSE = 41, // 0x29
SID_NETGAMEPORT = 69, // 0x45
SID_AUTH_INFO = 80, // 0x50
SID_AUTH_CHECK = 81, // 0x51
SID_AUTH_ACCOUNTLOGON = 83, // 0x53
SID_AUTH_ACCOUNTLOGONPROOF = 84, // 0x54
SID_WARDEN = 94, // 0x5E
SID_FRIENDSLIST = 101, // 0x65
SID_FRIENDSUPDATE = 102, // 0x66
SID_CLANMEMBERLIST = 125, // 0x7D
SID_CLANMEMBERSTATUSCHANGE = 127 // 0x7F
};
enum KeyResult {
KR_GOOD = 0,
KR_OLD_GAME_VERSION = 256,
KR_INVALID_VERSION = 257,
KR_ROC_KEY_IN_USE = 513,
KR_TFT_KEY_IN_USE = 529
};
enum IncomingChatEvent {
EID_SHOWUSER = 1, // received when you join a channel (includes users in the channel and their information)
EID_JOIN = 2, // received when someone joins the channel you're currently in
EID_LEAVE = 3, // received when someone leaves the channel you're currently in
EID_WHISPER = 4, // received a whisper message
EID_TALK = 5, // received when someone talks in the channel you're currently in
EID_BROADCAST = 6, // server broadcast
EID_CHANNEL = 7, // received when you join a channel (includes the channel's name, flags)
EID_USERFLAGS = 9, // user flags updates
EID_WHISPERSENT = 10, // sent a whisper message
EID_CHANNELFULL = 13, // channel is full
EID_CHANNELDOESNOTEXIST = 14, // channel does not exist
EID_CHANNELRESTRICTED = 15, // channel is restricted
EID_INFO = 18, // broadcast/information message
EID_ERROR = 19, // error message
EID_EMOTE = 23 // emote
};
private:
BYTEARRAY m_ClientToken; // set in constructor
BYTEARRAY m_LogonType; // set in RECEIVE_SID_AUTH_INFO
BYTEARRAY m_ServerToken; // set in RECEIVE_SID_AUTH_INFO
BYTEARRAY m_MPQFileTime; // set in RECEIVE_SID_AUTH_INFO
BYTEARRAY m_IX86VerFileName; // set in RECEIVE_SID_AUTH_INFO
BYTEARRAY m_ValueStringFormula; // set in RECEIVE_SID_AUTH_INFO
BYTEARRAY m_KeyState; // set in RECEIVE_SID_AUTH_CHECK
BYTEARRAY m_KeyStateDescription; // set in RECEIVE_SID_AUTH_CHECK
BYTEARRAY m_Salt; // set in RECEIVE_SID_AUTH_ACCOUNTLOGON
BYTEARRAY m_ServerPublicKey; // set in RECEIVE_SID_AUTH_ACCOUNTLOGON
BYTEARRAY m_UniqueName; // set in RECEIVE_SID_ENTERCHAT
public:
CBNETProtocol( );
~CBNETProtocol( );
BYTEARRAY GetClientToken( ) { return m_ClientToken; }
BYTEARRAY GetLogonType( ) { return m_LogonType; }
BYTEARRAY GetServerToken( ) { return m_ServerToken; }
BYTEARRAY GetMPQFileTime( ) { return m_MPQFileTime; }
BYTEARRAY GetIX86VerFileName( ) { return m_IX86VerFileName; }
string GetIX86VerFileNameString( ) { return string( m_IX86VerFileName.begin( ), m_IX86VerFileName.end( ) ); }
BYTEARRAY GetValueStringFormula( ) { return m_ValueStringFormula; }
string GetValueStringFormulaString( ) { return string( m_ValueStringFormula.begin( ), m_ValueStringFormula.end( ) ); }
BYTEARRAY GetKeyState( ) { return m_KeyState; }
string GetKeyStateDescription( ) { return string( m_KeyStateDescription.begin( ), m_KeyStateDescription.end( ) ); }
BYTEARRAY GetSalt( ) { return m_Salt; }
BYTEARRAY GetServerPublicKey( ) { return m_ServerPublicKey; }
BYTEARRAY GetUniqueName( ) { return m_UniqueName; }
// receive functions
bool RECEIVE_SID_NULL( BYTEARRAY data );
CIncomingGameHost *RECEIVE_SID_GETADVLISTEX( BYTEARRAY data );
bool RECEIVE_SID_ENTERCHAT( BYTEARRAY data );
CIncomingChatEvent *RECEIVE_SID_CHATEVENT( BYTEARRAY data );
bool RECEIVE_SID_CHECKAD( BYTEARRAY data );
bool RECEIVE_SID_STARTADVEX3( BYTEARRAY data );
BYTEARRAY RECEIVE_SID_PING( BYTEARRAY data );
bool RECEIVE_SID_LOGONRESPONSE( BYTEARRAY data );
bool RECEIVE_SID_AUTH_INFO( BYTEARRAY data );
bool RECEIVE_SID_AUTH_CHECK( BYTEARRAY data );
bool RECEIVE_SID_AUTH_ACCOUNTLOGON( BYTEARRAY data );
bool RECEIVE_SID_AUTH_ACCOUNTLOGONPROOF( BYTEARRAY data );
BYTEARRAY RECEIVE_SID_WARDEN( BYTEARRAY data );
vector<CIncomingFriendList *> RECEIVE_SID_FRIENDSLIST( BYTEARRAY data );
vector<CIncomingClanList *> RECEIVE_SID_CLANMEMBERLIST( BYTEARRAY data );
CIncomingClanList *RECEIVE_SID_CLANMEMBERSTATUSCHANGE( BYTEARRAY data );
// send functions
BYTEARRAY SEND_PROTOCOL_INITIALIZE_SELECTOR( );
BYTEARRAY SEND_SID_NULL( );
BYTEARRAY SEND_SID_STOPADV( );
BYTEARRAY SEND_SID_GETADVLISTEX( string gameName );
BYTEARRAY SEND_SID_ENTERCHAT( );
BYTEARRAY SEND_SID_JOINCHANNEL( string channel );
BYTEARRAY SEND_SID_CHATCOMMAND( string command );
BYTEARRAY SEND_SID_CHECKAD( );
BYTEARRAY SEND_SID_STARTADVEX3( unsigned char state, BYTEARRAY mapGameType, BYTEARRAY mapFlags, BYTEARRAY mapWidth, BYTEARRAY mapHeight, string gameName, string hostName, uint32_t upTime, string mapPath, BYTEARRAY mapCRC, BYTEARRAY mapSHA1, uint32_t hostCounter );
BYTEARRAY SEND_SID_NOTIFYJOIN( string gameName );
BYTEARRAY SEND_SID_PING( BYTEARRAY pingValue );
BYTEARRAY SEND_SID_LOGONRESPONSE( BYTEARRAY clientToken, BYTEARRAY serverToken, BYTEARRAY passwordHash, string accountName );
BYTEARRAY SEND_SID_NETGAMEPORT( uint16_t serverPort );
BYTEARRAY SEND_SID_AUTH_INFO( unsigned char ver, bool TFT, string countryAbbrev, string country );
BYTEARRAY SEND_SID_AUTH_CHECK( bool TFT, BYTEARRAY clientToken, BYTEARRAY exeVersion, BYTEARRAY exeVersionHash, BYTEARRAY keyInfoROC, BYTEARRAY keyInfoTFT, string exeInfo, string keyOwnerName );
BYTEARRAY SEND_SID_AUTH_ACCOUNTLOGON( BYTEARRAY clientPublicKey, string accountName );
BYTEARRAY SEND_SID_AUTH_ACCOUNTLOGONPROOF( BYTEARRAY clientPasswordProof );
BYTEARRAY SEND_SID_WARDEN( BYTEARRAY wardenResponse );
BYTEARRAY SEND_SID_FRIENDSLIST( );
BYTEARRAY SEND_SID_CLANMEMBERLIST( );
// other functions
private:
bool AssignLength( BYTEARRAY &content );
bool ValidateLength( BYTEARRAY &content );
};
//
// CIncomingGameHost
//
class CIncomingGameHost
{
private:
BYTEARRAY m_IP;
uint16_t m_Port;
string m_GameName;
BYTEARRAY m_HostCounter;
public:
CIncomingGameHost( BYTEARRAY &nIP, uint16_t nPort, string nGameName, BYTEARRAY &nHostCounter );
~CIncomingGameHost( );
BYTEARRAY GetIP( ) { return m_IP; }
string GetIPString( );
uint16_t GetPort( ) { return m_Port; }
string GetGameName( ) { return m_GameName; }
BYTEARRAY GetHostCounter( ) { return m_HostCounter; }
};
//
// CIncomingChatEvent
//
class CIncomingChatEvent
{
private:
CBNETProtocol :: IncomingChatEvent m_ChatEvent;
uint32_t m_Ping;
string m_User;
string m_Message;
public:
CIncomingChatEvent( CBNETProtocol :: IncomingChatEvent nChatEvent, uint32_t nPing, string nUser, string nMessage );
~CIncomingChatEvent( );
CBNETProtocol :: IncomingChatEvent GetChatEvent( ) { return m_ChatEvent; }
uint32_t GetPing( ) { return m_Ping; }
string GetUser( ) { return m_User; }
string GetMessage( ) { return m_Message; }
};
//
// CIncomingFriendList
//
class CIncomingFriendList
{
private:
string m_Account;
unsigned char m_Status;
unsigned char m_Area;
string m_Location;
public:
CIncomingFriendList( string nAccount, unsigned char nStatus, unsigned char nArea, string nLocation );
~CIncomingFriendList( );
string GetAccount( ) { return m_Account; }
unsigned char GetStatus( ) { return m_Status; }
unsigned char GetArea( ) { return m_Area; }
string GetLocation( ) { return m_Location; }
string GetDescription( );
private:
string ExtractStatus( unsigned char status );
string ExtractArea( unsigned char area );
string ExtractLocation( string location );
};
//
// CIncomingClanList
//
class CIncomingClanList
{
private:
string m_Name;
unsigned char m_Rank;
unsigned char m_Status;
public:
CIncomingClanList( string nName, unsigned char nRank, unsigned char nStatus );
~CIncomingClanList( );
string GetName( ) { return m_Name; }
string GetRank( );
string GetStatus( );
string GetDescription( );
};
#endif
| [
"hogantp@a7494f72-a4b0-11dd-a887-7ffe1a420f8d"
] | [
[
[
1,
264
]
]
] |
542c1aeb14e2e9bb789e97379448ffd9953f35dc | 1df8e73545f4cce1cc3df5af42e6cc8a711d7f13 | /printview.h | ab42204c095326bd770edde51670f554e27ca092 | [] | no_license | Mohamedss/qt-segy-viewer | 6e5c84a846e63e5e61b1489ef675a36e799c3929 | 54a55718a91bae8b9eab2610c1d23eddc0abb95d | refs/heads/master | 2021-01-19T09:44:00.639450 | 2010-12-21T00:36:15 | 2010-12-21T00:36:15 | 35,456,892 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,285 | h | /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef PRINTVIEW_H
#define PRINTVIEW_H
#include <QTableView>
class PrintView : public QTableView
{
Q_OBJECT
public:
PrintView();
public Q_SLOTS:
void print(QPrinter *printer);
};
#endif // PRINTVIEW_H
| [
"[email protected]@ba798d5c-232d-d148-425a-647f199d9ac8"
] | [
[
[
1,
58
]
]
] |
d59583db00292c0bd0693503a932877a9ce8457a | ce148b48b453a58d84664ec979eb64e4813a83c8 | /Faeried/rapidxml/rapidxml_iterators.hpp | d647a990c128e08bc34179540183be3794387873 | [
"MIT",
"BSL-1.0"
] | permissive | theyoprst/Faeried | e8945f8cb21c317eeeb1b05f0d12b297b63621fe | d20bd990e7f91c8c03857d81e08b8f7f2dee3541 | refs/heads/master | 2020-04-09T16:04:47.472907 | 2011-02-21T16:38:02 | 2011-02-21T16:38:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,101 | hpp | #ifndef RAPIDXML_ITERATORS_HPP_INCLUDED
#define RAPIDXML_ITERATORS_HPP_INCLUDED
// Copyright (C) 2006, 2009 Marcin Kalicinski
// Version 1.13
// Revision $DateTime: 2009/05/13 01:46:17 $
//! \file rapidxml_iterators.hpp This file contains rapidxml iterators
#include "rapidxml/rapidxml.hpp"
namespace rapidxml
{
//! Iterator of child nodes of xml_node
template<class Ch>
class node_iterator
{
public:
typedef typename xml_node<Ch> value_type;
typedef typename xml_node<Ch> &reference;
typedef typename xml_node<Ch> *pointer;
typedef std::ptrdiff_t difference_type;
typedef std::bidirectional_iterator_tag iterator_category;
node_iterator()
: m_node(0)
{
}
node_iterator(xml_node<Ch> *node)
: m_node(node->first_node())
{
}
reference operator *() const
{
assert(m_node);
return *m_node;
}
pointer operator->() const
{
assert(m_node);
return m_node;
}
node_iterator& operator++()
{
assert(m_node);
m_node = m_node->next_sibling();
return *this;
}
node_iterator operator++(int)
{
node_iterator tmp = *this;
++this;
return tmp;
}
node_iterator& operator--()
{
assert(m_node && m_node->previous_sibling());
m_node = m_node->previous_sibling();
return *this;
}
node_iterator operator--(int)
{
node_iterator tmp = *this;
++this;
return tmp;
}
bool operator ==(const node_iterator<Ch> &rhs)
{
return m_node == rhs.m_node;
}
bool operator !=(const node_iterator<Ch> &rhs)
{
return m_node != rhs.m_node;
}
private:
xml_node<Ch> *m_node;
};
//! Iterator of child attributes of xml_node
template<class Ch>
class attribute_iterator
{
public:
typedef typename xml_attribute<Ch> value_type;
typedef typename xml_attribute<Ch> &reference;
typedef typename xml_attribute<Ch> *pointer;
typedef std::ptrdiff_t difference_type;
typedef std::bidirectional_iterator_tag iterator_category;
attribute_iterator()
: m_attribute(0)
{
}
attribute_iterator(xml_node<Ch> *node)
: m_attribute(node->first_attribute())
{
}
reference operator *() const
{
assert(m_attribute);
return *m_attribute;
}
pointer operator->() const
{
assert(m_attribute);
return m_attribute;
}
attribute_iterator& operator++()
{
assert(m_attribute);
m_attribute = m_attribute->next_attribute();
return *this;
}
attribute_iterator operator++(int)
{
attribute_iterator tmp = *this;
++this;
return tmp;
}
attribute_iterator& operator--()
{
assert(m_attribute && m_attribute->previous_attribute());
m_attribute = m_attribute->previous_attribute();
return *this;
}
attribute_iterator operator--(int)
{
attribute_iterator tmp = *this;
++this;
return tmp;
}
bool operator ==(const attribute_iterator<Ch> &rhs)
{
return m_attribute == rhs.m_attribute;
}
bool operator !=(const attribute_iterator<Ch> &rhs)
{
return m_attribute != rhs.m_attribute;
}
private:
xml_attribute<Ch> *m_attribute;
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
174
]
]
] |
ba0dfb9326b24429d77adfb3d4d959d3d6a21259 | ef635cec76312aacc67e7df87db7084a455be2ea | /console_command/console_command.cpp | df2c649ab177e0ad09f110024f368321447746ff | [] | no_license | jsteinha/Water-Tunnel | 200161d2bb5d6bcdfd62e9c432df1c5f418d9e2e | 556842dd4ee38fabe8ba303e280cf01bf89fa9a9 | refs/heads/master | 2016-09-08T02:01:50.631983 | 2010-09-15T19:33:32 | 2010-09-15T19:33:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,797 | cpp | #include "console_command.h"
#include <fstream>
#include <time.h>
#include <stdlib.h>
#include <iostream>
//lcm
static lcmt_servotubeCommand_subscription_t * sub;
static lcm_t * lcm;
static int commandType = 1;
static double commandVal= 0.0;
static int final_iter = 0;
//end lcm
enum operationStateTypes{ executeLCMCommand, recenter, idle, finishAndTerminate};
clock_t lastCommandClock;
double allowableCommandWait = .1;
static double dt = .001/ServoTube::speedVkhz;
static const double omega=4.7385;
static double Etilde; //unitless energy error
static operationStateTypes parseLCMCommand(int curCommType, double curCommVal, ServoTube* CartPole);
static double recenterAccelGen(double x, double xd);
static bool nearEnoughToZero(ServoTube* CartPole);
ServoTube* CartPole;
KvaserCAN* kvaserCANbus;
const char *canDevice = "kvaser0"; // Identifies the CAN device, if necessary
int main(int argc, char** argv)
{
lcm = lcm_create ("udpm://");
if (!lcm)
return 1;
lastCommandClock=clock();
clock_t previousClock;
clock_t curClock;
clock_t firstClock;
HANDLE lcm_watcher_thread;
unsigned lcm_watcher_thread_ID;
static HANDLE mutex = CreateMutex(NULL, true, "wt_command_mutex");
ReleaseMutex(mutex);
lcm_watcher_thread =(HANDLE)_beginthreadex( NULL , 0,&lcm_watcher, lcm, 0, &lcm_watcher_thread_ID);
//take user input for menu
char userinput;
if(argc>1)
userinput = argv[1][0];
else
{
printf("STARTUP MENU \n\n");
printf("Select one of the options below: \n");
printf("[1] Begin operation\n");
printf("Enter command: ");
std::cin>>userinput;
printf("\n\n");
switch(userinput)
{
case '1':
//normal operation
break;
default:
printf("Command not understood. Turning off.\n\n");
return 0;
break;
}
}
//setup can connection
kvaserCANbus = new KvaserCAN( canDevice );
CartPole = new ServoTube(kvaserCANbus);
//wait till connection established to set initial clocks (curClock will be initialized in loop)
firstClock = clock();
previousClock = firstClock;
double deltaT=0.0;
double measurements[2]; //store encoder measurements to send to state estimator
int iter = 0;
double finishingWaitTime=3;
bool keepRunning = true;
operationStateTypes operatingState = executeLCMCommand;
double curCommVal = 0.0;
int curCommType = 1;
lcmt_servotubeState myState;
while(keepRunning)//begin control loop
{
iter++;
//get positions from amp
CartPole->update();
measurements[0]=CartPole->get_motor_pos();
measurements[1]=CartPole->get_load_enc_pos();
//printf("Pos: %f %f\n",measurements[0],measurements[1]);
//set current clock and send measurements
curClock = clock();
myState.position = measurements[0];
myState.positionSecondary = measurements[1];
send_message (lcm, &myState);
//read in command if not finishing
if(operatingState != finishAndTerminate && operatingState != recenter)
{
if(WaitForSingleObject(mutex, 10000)==WAIT_TIMEOUT)
printf("MUTEX TIMEOUT ERROR 4\n");
else
{
bool gotRecentCommand = (1.0*(curClock-lastCommandClock))/CLOCKS_PER_SEC <= allowableCommandWait;
if( !gotRecentCommand && operatingState != idle && iter!= 1)
{
operatingState = idle;
printf("No command received for %f seconds. Idling...\n",allowableCommandWait);
}
if( ((1.0*(curClock-lastCommandClock))/CLOCKS_PER_SEC < allowableCommandWait) )
operatingState = executeLCMCommand;
curCommVal = commandVal;
curCommType = commandType;
}
ReleaseMutex(mutex);
}
switch(operatingState)
{
case executeLCMCommand:
operatingState = parseLCMCommand(curCommType,curCommVal,CartPole);
break;
case recenter:
if(nearEnoughToZero(CartPole))
{
CartPole->set_vel_command(0.0);
operatingState = idle;
}
else
CartPole->accelerate(recenterAccelGen(measurements[0], CartPole->get_motor_vel()));
break;
case idle:
if(abs(CartPole->get_motor_vel())<.02)
CartPole->set_vel_command(0.0);
else
CartPole->accelerate(-15*CartPole->get_motor_vel());
break;
case finishAndTerminate:
if(nearEnoughToZero(CartPole))
{
CartPole->set_vel_command(0.0);
keepRunning = false;
}
else
CartPole->accelerate(recenterAccelGen(measurements[0], CartPole->get_motor_vel()));
break;
default:
printf("Shouldn't get here!\n");
CartPole->accelerate(recenterAccelGen(measurements[0], CartPole->get_motor_vel()));
operatingState = finishAndTerminate;
break;
}
if(iter%500==0)
{
deltaT=(1.0*(curClock-previousClock))/CLOCKS_PER_SEC;
previousClock=curClock;
//printf("dt: %f\n\n",deltaT/500.0);
}
}
CartPole->set_vel_command(0.0); //zero velocity on exit
return 0;
}
////////////////////////////
//Helper functions
////////////////////////////
static bool nearEnoughToZero(ServoTube* CartPole)
{
const double posThreshold = .0025; //m
const double velThreshold = .025; //m/s
return abs(CartPole->get_motor_vel())<velThreshold && abs(CartPole->get_motor_pos())<posThreshold;
}
static operationStateTypes parseLCMCommand(int curCommType, double curCommVal, ServoTube* CartPole)
{
switch(curCommType)
{
case 0:
printf("Recentering...\n");
return recenter;
break;
case 1:
CartPole->accelerate(curCommVal);
return executeLCMCommand;
break;
case 2:
CartPole->set_vel_command(curCommVal);
return executeLCMCommand;
break;
case -1:
printf("Stopping operation on terminate signal...\n");
return finishAndTerminate;
break;
default:
printf("LCM command not understood. Stopping operation...\n");
return finishAndTerminate;
break;
}
}
static double recenterAccelGen(double x, double xd)
{
return -15*x - 15*xd;
}
//LCM Code
unsigned __stdcall lcm_watcher(void *param)
{
sub = lcmt_servotubeCommand_subscribe (lcm, "wt_command", &my_handler, NULL);
while(1)
{
//printf("Handling\n");
lcm_handle((lcm_t*) param);
}
_endthreadex(0);
return 0;
}
static void my_handler (const lcm_recv_buf_t *rbuf, const char * channel,
const lcmt_servotubeCommand * msg, void* user)
{
static HANDLE mutex = CreateMutex(NULL, false, "wt_command_mutex");
if(WaitForSingleObject(mutex, 10000)==WAIT_TIMEOUT)
{
printf("MUTEX TIMEOUT ERROR 3\n");
}
else
{
commandType= msg->commandType;
commandVal= msg->commandValue;
lastCommandClock = clock();
//printf("comVal: %f\n",commandVal);
}
ReleaseMutex(mutex);
}
static void send_message (lcm_t * lcm, lcmt_servotubeState* my_data)
{
lcmt_servotubeState_publish (lcm, "wt_state", my_data);
} | [
"[email protected]"
] | [
[
[
1,
273
]
]
] |
750473a2be30326c70912e1975fcb5ed4de2a476 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/include/aosl/resource_id_forward.hpp | 9035090585b192fdf8d3ca8bccdaeae9da8b977d | [] | no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,585 | hpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
#ifndef AOSLCPP_AOSL__RESOURCE_ID_FORWARD_HPP
#define AOSLCPP_AOSL__RESOURCE_ID_FORWARD_HPP
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/version.hxx>
#if (XSD_INT_VERSION != 3030000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#ifndef XSD_USE_CHAR
#define XSD_USE_CHAR
#endif
#ifndef XSD_CXX_TREE_USE_CHAR
#define XSD_CXX_TREE_USE_CHAR
#endif
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/types.hxx>
#include <xsd/cxx/xml/error-handler.hxx>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
#include <xsd/cxx/tree/parsing.hxx>
#include <xsd/cxx/tree/parsing/byte.hxx>
#include <xsd/cxx/tree/parsing/unsigned-byte.hxx>
#include <xsd/cxx/tree/parsing/short.hxx>
#include <xsd/cxx/tree/parsing/unsigned-short.hxx>
#include <xsd/cxx/tree/parsing/int.hxx>
#include <xsd/cxx/tree/parsing/unsigned-int.hxx>
#include <xsd/cxx/tree/parsing/long.hxx>
#include <xsd/cxx/tree/parsing/unsigned-long.hxx>
#include <xsd/cxx/tree/parsing/boolean.hxx>
#include <xsd/cxx/tree/parsing/float.hxx>
#include <xsd/cxx/tree/parsing/double.hxx>
#include <xsd/cxx/tree/parsing/decimal.hxx>
#include <xsd/cxx/xml/dom/serialization-header.hxx>
#include <xsd/cxx/tree/serialization.hxx>
#include <xsd/cxx/tree/serialization/byte.hxx>
#include <xsd/cxx/tree/serialization/unsigned-byte.hxx>
#include <xsd/cxx/tree/serialization/short.hxx>
#include <xsd/cxx/tree/serialization/unsigned-short.hxx>
#include <xsd/cxx/tree/serialization/int.hxx>
#include <xsd/cxx/tree/serialization/unsigned-int.hxx>
#include <xsd/cxx/tree/serialization/long.hxx>
#include <xsd/cxx/tree/serialization/unsigned-long.hxx>
#include <xsd/cxx/tree/serialization/boolean.hxx>
#include <xsd/cxx/tree/serialization/float.hxx>
#include <xsd/cxx/tree/serialization/double.hxx>
#include <xsd/cxx/tree/serialization/decimal.hxx>
#include <xsd/cxx/tree/std-ostream-operators.hxx>
/**
* @brief C++ namespace for the %http://www.w3.org/2001/XMLSchema
* schema namespace.
*/
namespace xml_schema
{
// anyType and anySimpleType.
//
/**
* @brief C++ type corresponding to the anyType XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::type Type;
/**
* @brief C++ type corresponding to the anySimpleType XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::simple_type< Type > SimpleType;
/**
* @brief Alias for the anyType type.
*/
typedef ::xsd::cxx::tree::type Container;
// 8-bit
//
/**
* @brief C++ type corresponding to the byte XML Schema
* built-in type.
*/
typedef signed char Byte;
/**
* @brief C++ type corresponding to the unsignedByte XML Schema
* built-in type.
*/
typedef unsigned char UnsignedByte;
// 16-bit
//
/**
* @brief C++ type corresponding to the short XML Schema
* built-in type.
*/
typedef short Short;
/**
* @brief C++ type corresponding to the unsignedShort XML Schema
* built-in type.
*/
typedef unsigned short UnsignedShort;
// 32-bit
//
/**
* @brief C++ type corresponding to the int XML Schema
* built-in type.
*/
typedef int Int;
/**
* @brief C++ type corresponding to the unsignedInt XML Schema
* built-in type.
*/
typedef unsigned int UnsignedInt;
// 64-bit
//
/**
* @brief C++ type corresponding to the long XML Schema
* built-in type.
*/
typedef long long Long;
/**
* @brief C++ type corresponding to the unsignedLong XML Schema
* built-in type.
*/
typedef unsigned long long UnsignedLong;
// Supposed to be arbitrary-length integral types.
//
/**
* @brief C++ type corresponding to the integer XML Schema
* built-in type.
*/
typedef long long Integer;
/**
* @brief C++ type corresponding to the nonPositiveInteger XML Schema
* built-in type.
*/
typedef long long NonPositiveInteger;
/**
* @brief C++ type corresponding to the nonNegativeInteger XML Schema
* built-in type.
*/
typedef unsigned long long NonNegativeInteger;
/**
* @brief C++ type corresponding to the positiveInteger XML Schema
* built-in type.
*/
typedef unsigned long long PositiveInteger;
/**
* @brief C++ type corresponding to the negativeInteger XML Schema
* built-in type.
*/
typedef long long NegativeInteger;
// Boolean.
//
/**
* @brief C++ type corresponding to the boolean XML Schema
* built-in type.
*/
typedef bool Boolean;
// Floating-point types.
//
/**
* @brief C++ type corresponding to the float XML Schema
* built-in type.
*/
typedef float Float;
/**
* @brief C++ type corresponding to the double XML Schema
* built-in type.
*/
typedef double Double;
/**
* @brief C++ type corresponding to the decimal XML Schema
* built-in type.
*/
typedef double Decimal;
// String types.
//
/**
* @brief C++ type corresponding to the string XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::string< char, SimpleType > String;
/**
* @brief C++ type corresponding to the normalizedString XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::normalized_string< char, String > NormalizedString;
/**
* @brief C++ type corresponding to the token XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::token< char, NormalizedString > Token;
/**
* @brief C++ type corresponding to the Name XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::name< char, Token > Name;
/**
* @brief C++ type corresponding to the NMTOKEN XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::nmtoken< char, Token > Nmtoken;
/**
* @brief C++ type corresponding to the NMTOKENS XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::nmtokens< char, SimpleType, Nmtoken > Nmtokens;
/**
* @brief C++ type corresponding to the NCName XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::ncname< char, Name > Ncname;
/**
* @brief C++ type corresponding to the language XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::language< char, Token > Language;
// ID/IDREF.
//
/**
* @brief C++ type corresponding to the ID XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::id< char, Ncname > Id;
/**
* @brief C++ type corresponding to the IDREF XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::idref< char, Ncname, Type > Idref;
/**
* @brief C++ type corresponding to the IDREFS XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::idrefs< char, SimpleType, Idref > Idrefs;
// URI.
//
/**
* @brief C++ type corresponding to the anyURI XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::uri< char, SimpleType > Uri;
// Qualified name.
//
/**
* @brief C++ type corresponding to the QName XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::qname< char, SimpleType, Uri, Ncname > Qname;
// Binary.
//
/**
* @brief Binary buffer type.
*/
typedef ::xsd::cxx::tree::buffer< char > Buffer;
/**
* @brief C++ type corresponding to the base64Binary XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::base64_binary< char, SimpleType > Base64Binary;
/**
* @brief C++ type corresponding to the hexBinary XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::hex_binary< char, SimpleType > HexBinary;
// Date/time.
//
/**
* @brief Time zone type.
*/
typedef ::xsd::cxx::tree::time_zone TimeZone;
/**
* @brief C++ type corresponding to the date XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::date< char, SimpleType > Date;
/**
* @brief C++ type corresponding to the dateTime XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::date_time< char, SimpleType > DateTime;
/**
* @brief C++ type corresponding to the duration XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::duration< char, SimpleType > Duration;
/**
* @brief C++ type corresponding to the gDay XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gday< char, SimpleType > Gday;
/**
* @brief C++ type corresponding to the gMonth XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gmonth< char, SimpleType > Gmonth;
/**
* @brief C++ type corresponding to the gMonthDay XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gmonth_day< char, SimpleType > GmonthDay;
/**
* @brief C++ type corresponding to the gYear XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gyear< char, SimpleType > Gyear;
/**
* @brief C++ type corresponding to the gYearMonth XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gyear_month< char, SimpleType > GyearMonth;
/**
* @brief C++ type corresponding to the time XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::time< char, SimpleType > Time;
// Entity.
//
/**
* @brief C++ type corresponding to the ENTITY XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::entity< char, Ncname > Entity;
/**
* @brief C++ type corresponding to the ENTITIES XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::entities< char, SimpleType, Entity > Entities;
// Namespace information and list stream. Used in
// serialization functions.
//
/**
* @brief Namespace serialization information.
*/
typedef ::xsd::cxx::xml::dom::namespace_info< char > NamespaceInfo;
/**
* @brief Namespace serialization information map.
*/
typedef ::xsd::cxx::xml::dom::namespace_infomap< char > NamespaceInfomap;
/**
* @brief List serialization stream.
*/
typedef ::xsd::cxx::tree::list_stream< char > ListStream;
/**
* @brief Serialization wrapper for the %double type.
*/
typedef ::xsd::cxx::tree::as_double< Double > AsDouble;
/**
* @brief Serialization wrapper for the %decimal type.
*/
typedef ::xsd::cxx::tree::as_decimal< Decimal > AsDecimal;
/**
* @brief Simple type facet.
*/
typedef ::xsd::cxx::tree::facet Facet;
// Flags and properties.
//
/**
* @brief Parsing and serialization flags.
*/
typedef ::xsd::cxx::tree::flags Flags;
/**
* @brief Parsing properties.
*/
typedef ::xsd::cxx::tree::properties< char > Properties;
// Parsing/serialization diagnostics.
//
/**
* @brief Error severity.
*/
typedef ::xsd::cxx::tree::severity Severity;
/**
* @brief Error condition.
*/
typedef ::xsd::cxx::tree::error< char > Error;
/**
* @brief List of %error conditions.
*/
typedef ::xsd::cxx::tree::diagnostics< char > Diagnostics;
// Exceptions.
//
/**
* @brief Root of the C++/Tree %exception hierarchy.
*/
typedef ::xsd::cxx::tree::exception< char > Exception;
/**
* @brief Exception indicating that the size argument exceeds
* the capacity argument.
*/
typedef ::xsd::cxx::tree::bounds< char > Bounds;
/**
* @brief Exception indicating that a duplicate ID value
* was encountered in the object model.
*/
typedef ::xsd::cxx::tree::duplicate_id< char > DuplicateId;
/**
* @brief Exception indicating a parsing failure.
*/
typedef ::xsd::cxx::tree::parsing< char > Parsing;
/**
* @brief Exception indicating that an expected element
* was not encountered.
*/
typedef ::xsd::cxx::tree::expected_element< char > ExpectedElement;
/**
* @brief Exception indicating that an unexpected element
* was encountered.
*/
typedef ::xsd::cxx::tree::unexpected_element< char > UnexpectedElement;
/**
* @brief Exception indicating that an expected attribute
* was not encountered.
*/
typedef ::xsd::cxx::tree::expected_attribute< char > ExpectedAttribute;
/**
* @brief Exception indicating that an unexpected enumerator
* was encountered.
*/
typedef ::xsd::cxx::tree::unexpected_enumerator< char > UnexpectedEnumerator;
/**
* @brief Exception indicating that the text content was
* expected for an element.
*/
typedef ::xsd::cxx::tree::expected_text_content< char > ExpectedTextContent;
/**
* @brief Exception indicating that a prefix-namespace
* mapping was not provided.
*/
typedef ::xsd::cxx::tree::no_prefix_mapping< char > NoPrefixMapping;
/**
* @brief Exception indicating that the type information
* is not available for a type.
*/
typedef ::xsd::cxx::tree::no_type_info< char > NoTypeInfo;
/**
* @brief Exception indicating that the types are not
* related by inheritance.
*/
typedef ::xsd::cxx::tree::not_derived< char > NotDerived;
/**
* @brief Exception indicating a serialization failure.
*/
typedef ::xsd::cxx::tree::serialization< char > Serialization;
/**
* @brief Error handler callback interface.
*/
typedef ::xsd::cxx::xml::error_handler< char > ErrorHandler;
/**
* @brief DOM interaction.
*/
namespace dom
{
/**
* @brief Automatic pointer for DOMDocument.
*/
using ::xsd::cxx::xml::dom::auto_ptr;
#ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
#define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
/**
* @brief DOM user data key for back pointers to tree nodes.
*/
const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node;
#endif
}
}
#include "aosl/unique_id_forward.hpp"
// Forward declarations.
//
namespace aosl
{
class Resource_id;
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // AOSLCPP_AOSL__RESOURCE_ID_FORWARD_HPP
| [
"klaim@localhost"
] | [
[
[
1,
610
]
]
] |
1551c8d0d38ce669edf5c3f9277c047a9d4c11af | 1b974521c0a29f5e8935bee1fc8730c283682902 | /simulator2.cpp | 27c6c90e5876572c4f1f395ba7087bbded59c0da | [] | no_license | deepankgupta/ai-challenge | 37702052238f44b8d9be77750ca0e5eb48341a78 | 3b6167f67ce4b7a3d065923e32da56395b1687d1 | refs/heads/master | 2020-05-31T09:07:39.930125 | 2008-10-21T16:39:50 | 2008-10-21T16:39:50 | 32,131,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,446 | cpp | #include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#include"common.h"
#include"team0078.cpp"
#include"team0093.cpp"
#include"team0072.cpp"
#include"team0055.cpp"
#include"team0038.cpp"
#include"team0036.cpp"
#include"team0048.cpp"
#include"team0031.cpp"
using namespace std;
class stimulator
{
private:
int chance,l1,u1,l2,u2,pts1,pts2,goal1,goal2; //l1,u1 denotes the lower and upper limits of the player's of the team having
//the turn to hit the ball while l2,u2 denotes for the opponent's team
char falocal[101][51]; //an array defined only for stimulator class of the type of the field
struct player local[23],printable[23];//printable keeps a track of the players' and ball statistics before the move was made
//local keeps a track of the players' and ball statistics after the move is made
int preq(int finalx,int finaly, int initialx ,int initialy ) //fn to find the str req by player to move
{
float req; //similar to preqp in class team
req=floor(sqrt(pow((finalx-initialx),2)+pow((finaly-initialy),2)));
return (int)req;
}
int preqb(int finalx,int finaly, int initialx ,int initialy ) // fn to find the str req by hitter to move the ball from
{
float req; //one pos to another
req=2*(floor(sqrt(pow((finalx-initialx),2)+pow((finaly-initialy),2)))); //similar to preqpb in class team
return (int)req;
}
public: //public functions of stimulator class
void initialize() //function called by main to initialize the private variables of stimulator class to 0
{
goal1=0;goal2=0;pts1=0;pts2=0;
}
void controller()
{
int i,j,k,move,phitter,ball,players,sum_pstr_1=0,sum_pstr_2=0;
char check;
team0093 p1; //defining objects of the class teamxxxx and team0002 where xxxx is your registration no. and team0002 is the
team0048 p2; //test player given by us
for(i=0;i<=22;i++)
{
local[i]=global[i];
printable[i]=global[i];
} //copying player struct array as initialised in main to the local and printable arrays
for(i=0;i<=100;i++)
for(j=0;j<=50;j++)
falocal[i][j]=fieldarray[i][j]; //copying field array to local field array as initialised in main
p1.init(1,global,fieldarray); //calling the init functions of both the teams to send them their team no. and passing them
p2.init(2,global,fieldarray); //the initial field distribution and the basic field array
chance=0; //value of chance is randomly selected
for(move=1;move<=500;move++) /*loop to take care of the no of turns*/
{
printf("\nmove=%d\n",move);
//set the parameters and calling player's function according to the value of chance (toss)
if(chance==0)
{
phitter=p1.player(global); chance=1; l1=1; u1=11; l2=12; u2=22;
}
else
{
phitter=p2.player(global); chance=0; l1=12; u1=22; l2=1; u2=11;
}
//calling functions in stimulator class
playerpos(phitter);
ballpos(phitter);
for(i=0;i<=22;i++)
{
global[i]=local[i];
}//copying player struct array
for(i=0;i<=100;i++)
for(j=0;j<=50;j++)
fieldarray[i][j]=falocal[i][j]; //copying field array to local field array
//statements to print the output array after every move
for(i=0;i<=100;i++)
{
printf("\n");
for(j=0;j<=50;j++)
{
ball=0; //to find whether any player or ball is present at falocal[i][j]
players=0;
if((global[0].x==i)&&(global[0].y==j)) //to check whether the ball's coordinates matches with the value of i and j
ball++;
//to check whether any player's coordinates matches with the value of i and j
for(k=1;k<=22;k++)
{
if((global[k].x==i)&&(global[k].y==j))players++;
}
if((fieldarray[i][j]=='B')||(fieldarray[i][j]=='g')||(fieldarray[i][j]=='G'))
printf("%c",fieldarray[i][j]);
else if((ball==0)&&(players==0)) //if no player or ball is present at global[i][j]
{
if((fieldarray[i][j]=='d')||(fieldarray[i][j]=='D'))
printf("%c",fieldarray[i][j]);
else printf("f"); //if the global[i][j] is not inside dee region and is a simple region
}
else //if ball or player is present at global[i][j]
{
if(ball==1)
printf("0");
else if(players<=9)
printf("%d",players);
else
printf("e");
}//end of else
}//end of 2nd for loop
}//end of 1st for loop
//to tell the significance of symbols used in array representation
printf("\n\ng signifies the 1st player's goal\nG signifies 2nd player's goal\nd signifies 1st player's dee\nD signifies 2nd player's goal\n");
printf("\n1 signifies presence of 1 player at the spot ,2 signifies presence of 2 players at that spot and so on....\n");
printf("e signifies that more than 9 players are present at that spot\n");
printf("0 signifies that the ball is present at that spot.The no. of players is not shown in this case.\n\nB signifies boundary\n\nf signifies a normal field region\n\n");
//to print the positions of the ball and players
if(chance==1)
printf("\n\nteam1 turn , hitter of ball=%d",phitter);
else
printf("\n\nteam2 turn , hitter of ball=%d",phitter);
printf("\n\n");
printf("ball-\n"); //printing ball's statistics
printf("init posx=%d init posy=%d finalposx=%d finalposy=%d\n\n",printable[0].x,printable[0].y,local[0].x,local[0].y);
printf("team1-\n"); //printing statistics of team 1 players
printf("player initx inity finalx finaly initstr finalstr\n");
for(i=1;i<=11;i++)
printf("%6d %5d %5d %6d %6d %7d %8d\n",i,printable[i].x,printable[i].y,local[i].x,local[i].y,printable[i].strength,local[i].strength);
printf("\nteam2-\n"); //printing statistics of team 2 players
printf("player initx inity finalx finaly initstr finalstr\n");
for(i=12;i<=22;i++)
printf("%6d %5d %5d %6d %6d %7d %8d\n",i,printable[i].x,printable[i].y,local[i].x,local[i].y,printable[i].strength,local[i].strength);
printf("SCORE--\n");
printf("team1 goal=%d\nteam1 pts=%d\n team2 goal=%d\n team2 pts=%d\n",goal1,pts1,goal2,pts2);
//to directly view the final result of the game remove this portion
printf("press enter to continue\npress N or n to exit the program ");
fflush(stdin);
/*if(check=='N'||check=='n')
exit(1);*/
for(i=0;i<=22;i++)
printable[i]=local[i];//to update the printable array
}/*to end the move loop*/
printf("\nGAME FINISHED\nFINAL SCORES--\n");
printf("team1 goal=%d\nteam1 pts=%d\n team2 goal=%d\n team2 pts=%d\n",goal1,pts1,goal2,pts2);//to print the no of goals
//to print the winner of the game
if(pts1>pts2)
printf("\n\nTEAM 1 WINS THE MATCH\n\n");
else if(pts1<pts2)
printf("\n\nTEAM 2 WINS THE MATCH\n\n");
else
{
printf("\n\nBoth team have equal points. Game will be decided on the basis of the sum of the strengths of each team's players'\n\n");
sum_pstr_1=0;sum_pstr_2=0;
for(i=1;i<=11;i++)
{
sum_pstr_1+=local[i].strength;
sum_pstr_2+=local[i+11].strength;
}//loop to sum left over strengths of each team players
printf("\nleft over strength of team1=%d\nleft over strength of team2=%d\n",sum_pstr_1,sum_pstr_2);
if(sum_pstr_1>sum_pstr_2)
printf("\n\nleft over strength of 1st team players' is more than 2nd team and hence 1st TEAM IS THE WINNER\n\n");
else if(sum_pstr_1<sum_pstr_2)
printf("\n\nleft over strength of 1st team players' is less than 2nd team and hence 2nd TEAM IS THE WINNER\n\n");
else
printf("\n\nleft over strength of both teams is equal and hence THE GAME IS A DRAW\n\n");
}//end of else
}//end of fn controller
//this function checks whether the changes made by the teams in the position of their players' in the array global are
//valid or not and if they are then changes are updated in the local array and strength is decreased accordingly of the
//players
void playerpos(int phitter)
{
int k,xdiff,ydiff,powerreq;
for(k=l1;k<=u1;k++) //to compare each player's global pos with the one inside local
{
xdiff=(global[k].x)-(local[k].x); //xdiff and ydiff finds the difference between the player's initial and final
ydiff=(global[k].y)-(local[k].y); //coordinates
if(((xdiff==0)&&(ydiff==0))||(global[k].strength==0))
{
if(local[k].strength<=30)
local[k].strength=local[k].strength+20;
else if ((local[k].strength>30)&&(local[k].strength<50))
local[k].strength=50;
}/*end of if loop in case player has not moved*/
else /*else when the player has moved*/
{
powerreq=preq(global[k].x,global[k].y,local[k].x,local[k].y);
//if case to check whether the coordinates of player changed by the participant are legal or not
if((global[k].x<=100)&&(global[k].x>=0)&&(global[k].y<=50)&&(global[k].y>=0)&&(falocal[global[k].x][global[k].y]!='g')&&(falocal[global[k].x][global[k].y]!='G')&&(falocal[global[k].x][global[k].y]!='B'))
{
from_else_of_boundary:/*label for goto*/
if(local[k].strength>=powerreq)
{
local[k].x=global[k].x;
local[k].y=global[k].y;
local[k].strength=local[k].strength-powerreq;
} //if player strength is more than or sufficient than req to move
else //if power req is not sufficient
{
while(powerreq>local[k].strength)
{
if(local[k].x!=global[k].x)
{
(xdiff>0)?(global[k].x)--:(global[k].x)++;
}
if(local[k].y!=global[k].y)
{
(ydiff>0)?(global[k].y)--:(global[k].y)++;
}
powerreq=preq(global[k].x,global[k].y,local[k].x,local[k].y);
}//end of while loop
local[k].x=global[k].x;
local[k].y=global[k].y;
local[k].strength=local[k].strength-powerreq;
} //end of else when power req is not sufficient
} //to end the if case when the final coordinates of player are not in boundary or goal or out of field array
else //when the final coordinates of player are illegal
{
while((global[k].x>100)||(global[k].x<0)||(global[k].y>50)||(global[k].y<0)||(falocal[global[k].x][global[k].y]=='g')||(falocal[global[k].x][global[k].y]=='G')||(falocal[global[k].x][global[k].y]=='B')) //to end else when finla cooordinates r illegal
{
if(local[k].x!=global[k].x)
(xdiff>0)?(global[k].x)--:(global[k].x)++;
if(local[k].y!=global[k].y)
(ydiff>0)?(global[k].y)--:(global[k].y)++;
} //end of while
powerreq=preq(global[k].x,global[k].y,local[k].x,local[k].y);
goto from_else_of_boundary; //to check whether player has the power to reach the valid pos }
} //to end the else when the final coordinates of player are illegal
} //to end the else loop of whether player has moved
} //to end checking all players of the team
} //to end playerpos fn
//this function changes the position of the ball according to the changes made by the user in the position of the ball in the
//global array and checks whether the ball is interrupted in between or reaches goal ,dee or boundary and accordingly changes the
//points of both the teams and changes the strength of the hitter of the ball
void ballpos(int phitter)
{
int patspot,patspotstr,xdiffb;int ydiffb,validposx,validposy,found,powerreqb,i,j,a,p,ball,players,k;
char status,dee,goal;
//if the hitter as returned by the player function has 0 strength or is an illegal no.
if((phitter<1)||(phitter>22)||(local[phitter].strength==0))
return;
if((chance==1)&&(phitter>11)||(chance==0)&&(phitter<12))
return;
if(((local[phitter].x!=local[0].x)||(local[phitter].y!=local[0].y))&&((printable[phitter].x!=local[0].x)||(printable[phitter].y!=local[0].y)))
return;
//to return in case phitter final coordinates and initial coordinates of ball or phitter's initial coordinates and
//final coordinates of the ball don't meet
patspot=-1;patspotstr=0;
for(a=l2;a<=u2;a++)
{
if((local[a].x==local[0].x)&&(local[a].y==local[0].y))
{
if(local[a].strength>patspotstr)
{
patspot=a;
patspotstr=local[a].strength;
}
}
}/*for loop to check whether any of opponent's player is present at the ball's pos and to calculate max strength in case the no */
/*is more than 1*/
if((patspot==-1)||(patspotstr<=local[phitter].strength))//to check whether phitter's strength is more than maximum
//opponent's strength or he the only one with the ball
{
//strength of hitter of ball decreases by an amt equal to opponent's strength while taking the possession of the ball
//and the opposition's player's strength having the possession of the ball becomes 0
local[phitter].strength-=patspotstr ;
local[patspot].strength=0;
status='f'; //tells the region in which the ball is present after every step
//'f' when the ball is in the normal region ,'d' or 'D' when the ball is in the dee of either of the teams, 'g' or 'G'
//when the ball is in the goal of any of the teams , 'B' when ball reaches the boundary, ''i if the ball is
//interrupted by any of the player and 'r' if the ball reaches the desired position as changed by the participant
xdiffb=global[0].x-local[0].x; //calculates the difference between changed coordinates and initial coordinates of the
ydiffb=global[0].y-local[0].y; //ball
validposx=local[0].x; //validposx and validposy keeps a track of the step by step movement of the ball from its
validposy=local[0].y; //initial position to the desired position
while((status=='f')||(status=='D')||(status=='d'))
{
if(validposx!=global[0].x)
(xdiffb>0)?(validposx)++:(validposx)--;
if(validposy!=global[0].y)
(ydiffb>0)?(validposy)++:(validposy)--;
for(i=1;i<=22;i++)
{
if((validposx==local[i].x)&&(validposy==local[i].y))
{
status='i';
break;
}
} //loop to check whether any of the player intersect the ball
if(status=='i')
break;
if(falocal[validposx][validposy]!=0)
{
status=falocal[validposx][validposy];
} //to give status=d or D or g or G according to the position of the ball in field array
if((status=='B')||(status=='G')||(status=='g')||(status=='i'))
break;
if((validposx==global[0].x)&&(validposy==global[0].y)) //when ball reaches its desired position
{
status='r';
break;
}
}//end of while loop which operates until ball is interrupted or reaches its desired pos or enters goal or boundary
chance==1?(dee='D'):(dee='d'); //sets the varibles dee and goal according to the player's turn
chance==1?(goal='G'):(goal='g');
/*switch case is applied to check whether ball is interupted or reached its destination or got into goal or crossed the boundary*/
switch(status)
{
//when ball reaches the desired position
case 'r':
powerreqb=preqb(global[0].x,global[0].y,local[0].x,local[0].y);
validposx=global[0].x;
validposy=global[0].y;
//while loop to find the valid pos when hitter has enough power to make the ball reach there
while(powerreqb>local[phitter].strength)
{
if(validposx!=local[0].x)
(xdiffb>0)?(validposx)--:(validposx)++;
if(validposy!=local[0].y)
(ydiffb>0)?(validposy)--:(validposy)++;
powerreqb=preqb(validposx,validposy,local[0].x,local[0].y);
}//end of while loop
if((falocal[validposx][validposy]==dee)&&(falocal[local[0].x][local[0].y]!=dee))
{
(chance==1)?(pts1++):(pts2++);
} //increases pts if ball lands in the dee and was not in the dee earlier
local[0].x=validposx;
local[0].y=validposy;
(local[phitter].strength)-=powerreqb; //update the array accordingly
break;
//when the ball is interrupted by any of the player
case 'i':
powerreqb=preqb(validposx,validposy,local[0].x,local[0].y);
//while loop to find the valid pos when hitter has enough power to make the ball reach there
while(powerreqb>local[phitter].strength)
{
if(validposx!=local[0].x)
(xdiffb>0)?(validposx)--:(validposx)++;
if(validposy!=local[0].y)
(ydiffb>0)?(validposy)--:(validposy)++;
powerreqb=preqb(validposx,validposy,local[0].x,local[0].y);
}//end of while loop
//inc pts if ball lands in the dee and was not in the dee earlier)
if((falocal[validposx][validposy]==dee)&&(falocal[local[0].x][local[0].y]!=dee))
chance==1?pts1++:pts2++;
//strength is dec on the basis of coordinates given by user irrespective of where the ball stops
powerreqb=preqb(global[0].x,global[0].y,local[0].x,local[0].y);
local[0].x=validposx;
local[0].y=validposy;
if(powerreqb>=local[phitter].strength)
local[phitter].strength=0;
else (local[phitter].strength)-=powerreqb;
break;
case 'G':
powerreqb=preqb(validposx,validposy,local[0].x,local[0].y);
//while loop to find the valid pos when hitter has enough power to make the ball reach there
while(powerreqb>local[phitter].strength)
{
if(validposx!=local[0].x)
(xdiffb>0)?(validposx)--:(validposx)++;
if(validposy!=local[0].y)
(ydiffb>0)?(validposy)--:(validposy)++;
powerreqb=preqb(validposx,validposy,local[0].x,local[0].y);
}//end of while loop
//if the ball is not in the goal now
if(falocal[validposx][validposy]!='G')
{
if(falocal[validposx][validposy]=='D') //if the ball is still inside the opponent's dee
{
//if the ball was initially not in the opponent's dee ,so points of the team are increased
if(chance==1&&falocal[local[0].x][local[0].y]!='D')
pts1++;
}
local[0].x=validposx;
local[0].y=validposy;
}//end of if case when the ball is not in the goal now
//if the ball is still in the goal
else
{
//to print the status of the field when the ball reaches the goal
//printed in the same way as printed earlier
printf("\n\nHURRAY 1ST TEAM MADE A GOAL\nfigure shows the position of ball at the time of goal\n to view detailed result of the move and final position of ball press any key\n\n");
for(i=0;i<=100;i++)
{
printf("\n");
for(j=0;j<=50;j++)
{
ball=0;
players=0;
if((validposx==i)&&(validposy==j))
ball++;
for(k=1;k<=22;k++)
{
if((global[k].x==i)&&(global[k].y==j))players++;
}
if(ball==1)
printf("0");
else if((fieldarray[i][j]=='B')||(fieldarray[i][j]=='g')||(fieldarray[i][j]=='G'))
printf("%c",fieldarray[i][j]);
else if((ball==0)&&(players==0))
{
if((fieldarray[i][j]=='d')||(fieldarray[i][j]=='D'))
printf("%c",fieldarray[i][j]);
else printf("f");
}
else
{
if(players<=9)
printf("%d",players);
else
printf("e");
}//end of else
}//end of 2nd for loop
}//end of 1st for loop
goal1++;
pts1+=10;
found=0; /*found is to break the loop when a correct place is found to place the ball once goal happens*/
for(i=25;(found==0)&&(i<51);i++)
{
for(j=1;j<=11;j++)
{
if((local[j].x==50)&&(local[j].y==i))
break;
} //end of for
if(j==12)
{
local[0].x=50;
local[0].y=i;
found++;
} //end of if
} //end of for
} //end of else when the ball was still in the goal
//strength is dec on the basis of coordinates given by user irrespective of where the ball stops
powerreqb=preqb(global[0].x,global[0].y,local[0].x,local[0].y);
if(powerreqb>=local[phitter].strength)
local[phitter].strength=0;
else
(local[phitter].strength)-=powerreqb;
break;
case 'g':
//designed in a way almost similar to case 'G'
powerreqb=preqb(validposx,validposy,local[0].x,local[0].y);
//while loop to find the valid pos when hitter has enough power to make the ball reach there
while(powerreqb>local[phitter].strength)
{
if(validposx!=local[0].x)
(xdiffb>0)?(validposx)--:(validposx)++;
if(validposy!=local[0].y)
(ydiffb>0)?(validposy)--:(validposy)++;
powerreqb=preqb(validposx,validposy,local[0].x,local[0].y);
}//end of while loop
if(falocal[validposx][validposy]!='g')
{
if(falocal[validposx][validposy]=='d')
{
if(chance==0&&falocal[local[0].x][local[0].y]!='d')
pts2++;
}
local[0].x=validposx;
local[0].y=validposy;
}//end of if case when the ball is not in the goal now
//if the ball is still in the goal
else
{
//to print the status of the field when the ball reaches the goal
//printed in the same way as printed earlier
printf("\n\nHURRAY 2nd TEAM MADE A GOAL\nfigure shows the position of ball at the time of goal\n to view detailed result of the move and final position of ball press any key\n\n");
for(i=0;i<=100;i++)
{
printf("\n");
for(j=0;j<=50;j++)
{
ball=0;
players=0;
if((validposx==i)&&(validposy==j))
ball++;
for(k=1;k<=22;k++)
{
if((global[k].x==i)&&(global[k].y==j))
players++;
}
if(ball==1)
printf("0");
else if((fieldarray[i][j]=='B')||(fieldarray[i][j]=='g')||(fieldarray[i][j]=='G'))
printf("%c",fieldarray[i][j]);
else if((ball==0)&&(players==0))
{
if((fieldarray[i][j]=='d')||(fieldarray[i][j]=='D'))
printf("%c",fieldarray[i][j]);
else
printf("f");
} //end of if else
else
{
if(players<=9)
printf("%d",players);
else
printf("e");
}//end of else
}//end of 2nd for loop
}//end of 1st for loop
goal2++;
pts2+=10;
found=0;/*found is to break the loop when a correct place is found to place the ball once goal happens*/
for(i=25;found==0&&i<51;i++)
{
for(j=12;j<=22;j++)
{
if((local[j].x==50)&&(local[j].y==i))
break;
}//end of for
if(j==23)
{
local[0].x=50;
local[0].y=i;
found++;
}//end of if
}//end of for
}//end of else
//strength is dec on the basis of coordinates given by user irrespective of where the ball stops
powerreqb=preqb(global[0].x,global[0].y,local[0].x,local[0].y);
if(powerreqb>=local[phitter].strength)
local[phitter].strength=0;
else
(local[phitter].strength)-=powerreqb;
break;
case 'B':
powerreqb=preqb(validposx,validposy,local[0].x,local[0].y);
//to decrement pts in case a team hits the ball in boundary
if(powerreqb<=local[phitter].strength)
{
chance==1?pts1--:pts2--;
}
//do while loop to find the valid pos when hitter has enough power to make the ball reach there
do
{
if(validposx!=local[0].x)
(xdiffb>0)?(validposx)--:(validposx)++;
if(validposy!=local[0].y)
(ydiffb>0)?(validposy)--:(validposy)++;
powerreqb=preqb(validposx,validposy,local[0].x,local[0].y);
}while(powerreqb>local[phitter].strength);
//strength is dec on the basis of coordinates given by user irrespective of where the ball stops
powerreqb=preqb(global[0].x,global[0].y,local[0].x,local[0].y);
if(powerreqb>=local[phitter].strength)
local[phitter].strength=0;
else
(local[phitter].strength)-=powerreqb;
local[0].x=validposx; //to update the array accordingly
local[0].y=validposy;
break;
};//end of switch case
} //to end the if to check whether phitter's strength is more than opponent's strength
} //end of ballpos fn
}; //end of stimulator class
int main()
{
int i,j;
stimulator c1;
c1.initialize(); //initializing the variables goal1,goal2,pts1,pts2 to 0
//to set boundary
for(i=0;i<=100;i++)
{
fieldarray[i][0]='B';
fieldarray[i][50]='B';
if(i<=50)
{
fieldarray[0][i]='B';
fieldarray[100][i]='B';
}//end of if
}//end of for loop
//to set the dee
for(i=5;i<=45;i++)
{
for(j=0;j<=40;j++)
fieldarray[j][i]='d';
for(j=60;j<=100;j++)
fieldarray[j][i]='D';
} //end of for loop
//to set the goal
for(i=10;i<=40;i++)
{
for(j=0;j<=14;j++)
fieldarray[j][i]='g';
for(j=86;j<=100;j++)
fieldarray[j][i]='G';
} //end of for loop
//to set the initial strength of the players
for(i=1;i<=22;i++)
global[i].strength=50;
//set strength of ball to 0
global[0].strength=0;
// to set the team name
for(i=1;i<=11;i++)
global[i].team=1; //1 for 1st team
for(i=12;i<=22;i++)
global[i].team=2; //2 for 2nd team
global[0].team=0; //0 for ball
//to set player pos
global[1].x=15;global[1].y=25;
global[2].x=25;global[2].y=10;
global[3].x=25;global[3].y=25;
global[4].x=25;global[4].y=40;
global[5].x=30;global[5].y=10;
global[6].x=30;global[6].y=25;
global[7].x=30;global[7].y=40;
global[8].x=40;global[8].y=10;
global[9].x=40;global[9].y=25;
global[10].x=40;global[10].y=40;
global[11].x=49;global[11].y=25;
global[12].x=85;global[12].y=25;
global[13].x=75;global[13].y=10;
global[14].x=75;global[14].y=25;
global[15].x=75;global[15].y=40;
global[16].x=70;global[16].y=10;
global[17].x=70;global[17].y=25;
global[18].x=70;global[18].y=40;
global[19].x=60;global[19].y=10;
global[20].x=60;global[20].y=25;
global[21].x=60;global[21].y=40;
global[22].x=51;global[22].y=25;
global[0].x=50;global[0].y=25; //to set ball's pos
c1.controller(); //calling the function
// getch(); //to hold the screen
} //end of main function
| [
"mohitgenii@dd1e002a-cb53-0410-ab0d-ab7dcae0fab8"
] | [
[
[
1,
871
]
]
] |
ae16b81352ad088bba3bd0dc4a43d2c0f8edf28a | e68cf672cdb98181db47dab9fb8c45e69b91e256 | /include/StaticStructuredBuffer.h | 6a583054fc1c04f21d6bb5a4e98c3e39450e2bdf | [] | no_license | jiawen/QD3D11 | 09fc794f580db59bfc2faffbe3373a442180e0a5 | c1411967bd2da8d012eddf640eeb5f7b86e66374 | refs/heads/master | 2021-01-21T13:52:48.111246 | 2011-12-19T19:07:17 | 2011-12-19T19:07:17 | 2,549,080 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | h | #ifndef STATIC_STRUCTURED_BUFFER_H
#define STATIC_STRUCTURED_BUFFER_H
#include <D3D11.h>
class StaticStructuredBuffer
{
public:
static StaticStructuredBuffer* create( ID3D11Device* pDevice,
int nElements, int elementSizeBytes );
virtual ~StaticStructuredBuffer();
int numElements() const;
int elementSizeBytes() const;
int sizeInBytes() const;
ID3D11Buffer* buffer() const;
ID3D11ShaderResourceView* shaderResourceView() const;
ID3D11UnorderedAccessView* unorderedAccessView() const;
private:
StaticStructuredBuffer( ID3D11Device* pDevice,
int nElements, int elementSizeBytes,
ID3D11Buffer* pBuffer );
int m_nElements;
int m_elementSizeBytes;
ID3D11Buffer* m_pBuffer;
ID3D11ShaderResourceView* m_pSRV;
ID3D11UnorderedAccessView* m_pUAV;
};
#endif // STATIC_STRUCTURED_BUFFER_H
| [
"[email protected]"
] | [
[
[
1,
37
]
]
] |
548821fd8d4588d4fb71ee98e689aaa9d9827840 | df238aa31eb8c74e2c208188109813272472beec | /BCGInclude/ToolbarNameDlg.h | ab023b6186a0b4cc0a3159b771ff4967ca053230 | [] | no_license | myme5261314/plugin-system | d3166f36972c73f74768faae00ac9b6e0d58d862 | be490acba46c7f0d561adc373acd840201c0570c | refs/heads/master | 2020-03-29T20:00:01.155206 | 2011-06-27T15:23:30 | 2011-06-27T15:23:30 | 39,724,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,837 | h | //*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of the BCGControlBar Library
// Copyright (C) 1998-2008 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
#if !defined(AFX_TOOLBARNAMEDLG_H__E52278EA_EB02_11D1_90D8_00A0C9B05590__INCLUDED_)
#define AFX_TOOLBARNAMEDLG_H__E52278EA_EB02_11D1_90D8_00A0C9B05590__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// ToolbarNameDlg.h : header file
//
#include "BCGCBPro.h"
#include "bcgprores.h"
/////////////////////////////////////////////////////////////////////////////
// CToolbarNameDlg dialog
class CToolbarNameDlg : public CDialog
{
// Construction
public:
CToolbarNameDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CToolbarNameDlg)
enum { IDD = IDD_BCGBARRES_TOOLBAR_NAME };
CButton m_btnOk;
CString m_strToolbarName;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CToolbarNameDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CToolbarNameDlg)
afx_msg void OnUpdateToolbarName();
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_TOOLBARNAMEDLG_H__E52278EA_EB02_11D1_90D8_00A0C9B05590__INCLUDED_)
| [
"myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5"
] | [
[
[
1,
63
]
]
] |
877ae75ae74688e116a263aa450083a272c43316 | d7b345a8a6b0473c325fab661342de295c33b9c8 | /beta/src/Polarizer3/BrowserSettingVisitor.h | 818b034db3fd3dda6e0ab0766bc6958615508968 | [] | no_license | raould/Polaris-Open-Source | 67ccd647bf40de51a3dae903ab70e8c271f3f448 | 10d0ca7e2db9e082e1d2ed2e43fa46875f1b07b2 | refs/heads/master | 2021-01-01T19:19:39.148016 | 2010-05-10T17:39:26 | 2010-05-10T17:39:26 | 631,953 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 353 | h | // Copyright 2010 Hewlett-Packard under the terms of the MIT X license
// found at http://www.opensource.org/licenses/mit-license.html
#pragma once
#include "petsvisitor.h"
class BrowserSettingVisitor :
public PetsVisitor
{
public:
BrowserSettingVisitor(void);
virtual ~BrowserSettingVisitor(void);
virtual void visit(RegKey pet);
};
| [
"[email protected]"
] | [
[
[
1,
14
]
]
] |
f7e38595c89e25dc31c932c122d7d24bf2096604 | dde32744a06bb6697823975956a757bd6c666e87 | /bwapi/SCProjects/BTHAIModule/Source/EvolutionChamberAgent.cpp | 182b2d7d8b97265e8c81dfb152237136501e58c5 | [] | no_license | zarac/tgspu-bthai | 30070aa8f72585354ab9724298b17eb6df4810af | 1c7e06ca02e8b606e7164e74d010df66162c532f | refs/heads/master | 2021-01-10T21:29:19.519754 | 2011-11-16T16:21:51 | 2011-11-16T16:21:51 | 2,533,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cpp | #include "EvolutionChamberAgent.h"
#include "WorkerAgent.h"
#include "AgentManager.h"
#include "ZergCommander.h"
EvolutionChamberAgent::EvolutionChamberAgent(Unit* mUnit) {
unit = mUnit;
unitID = unit->getID();
Broodwar->printf("EvolutionChamberAgent created (%s)", unit->getType().getName().c_str());
}
void EvolutionChamberAgent::computeActions() {
if (canUpgrade(UpgradeTypes::Zerg_Melee_Attacks))
{
unit->upgrade(UpgradeTypes::Zerg_Melee_Attacks);
//return;
}
int level = ((ZergCommander*)Commander::getInstance())->getLevel();
if (level >= 5)
{
if (canUpgrade(UpgradeTypes::Zerg_Carapace))
unit->upgrade(UpgradeTypes::Zerg_Carapace);
if (canUpgrade(UpgradeTypes::Zerg_Missile_Attacks))
unit->upgrade(UpgradeTypes::Zerg_Missile_Attacks);
}
}
string EvolutionChamberAgent::getTypeName() {
return "EvolutionChamberAgent";
}
| [
"[email protected]"
] | [
[
[
1,
32
]
]
] |
6d6b105cf67e2273015674f85f464339bb35c8e5 | 1775576281b8c24b5ce36b8685bc2c6919b35770 | /trunk/stype_select.cpp | 7dc29104cc699adec206de2f4fbd25241499665f | [] | no_license | BackupTheBerlios/gtkslade-svn | 933a1268545eaa62087f387c057548e03497b412 | 03890e3ba1735efbcccaf7ea7609d393670699c1 | refs/heads/master | 2016-09-06T18:35:25.336234 | 2006-01-01T11:05:50 | 2006-01-01T11:05:50 | 40,615,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,019 | cpp |
#include "main.h"
#include "map.h"
int current_stype = 0;
int stype_damage = 0;
bool stype_flags[3];
extern GtkWidget *editor_window;
extern Map map;
void stype_tree_view_changed(GtkTreeView *view, gpointer data)
{
GtkTreeIter iter;
GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view));
GtkTreeModel *model = gtk_tree_view_get_model(view);
if (gtk_tree_selection_get_selected(selection, &model, &iter))
{
int index;
gtk_tree_model_get(model, &iter, 1, &index, -1);
if (index >= 0)
current_stype = index;
}
}
void stype_damage_combo_changed(GtkWidget *widget, gpointer data)
{
int index = gtk_combo_box_get_active(GTK_COMBO_BOX(widget));
int val = index * 32;
if (map.hexen)
val = val * 8;
stype_damage = val;
}
void stype_flag_changed(GtkWidget *widget, gpointer data)
{
int flag = (int)data;
stype_flags[flag] = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
}
GtkWidget* setup_stype_select(int type)
{
GtkCellRenderer *renderer;
GtkTreeViewColumn *col;
GtkWidget *main_vbox = gtk_vbox_new(false, 0);
// Type frame
GtkWidget *frame = gtk_frame_new("Type");
gtk_container_set_border_width(GTK_CONTAINER(frame), 4);
gtk_box_pack_start(GTK_BOX(main_vbox), frame, true, true, 0);
// Setup tree model
GtkListStore *list_store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT);
populate_list_store_stypes(list_store);
// Setup scrolled window
GtkWidget *s_window = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(s_window), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
gtk_container_set_border_width(GTK_CONTAINER(s_window), 4);
gtk_container_add(GTK_CONTAINER(frame), s_window);
// Setup tree view
GtkWidget *tree_view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(list_store));
renderer = gtk_cell_renderer_text_new();
col = gtk_tree_view_column_new_with_attributes("Type", renderer, "text", 0, NULL);
gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), col);
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree_view), false);
g_signal_connect(G_OBJECT(tree_view), "cursor-changed", G_CALLBACK(stype_tree_view_changed), NULL);
gtk_container_add(GTK_CONTAINER(s_window), tree_view);
// Generic flags
if (map.boom)
{
// Damage frame
frame = gtk_frame_new("Damage");
gtk_container_set_border_width(GTK_CONTAINER(frame), 4);
gtk_box_pack_start(GTK_BOX(main_vbox), frame, false, false, 0);
GtkWidget *vbox = gtk_vbox_new(false, 0);
gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
gtk_container_add(GTK_CONTAINER(frame), vbox);
GtkWidget *combo = gtk_combo_box_new_text();
gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "None");
gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "5 Health/Second");
gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "10 Health/Second");
gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "20 Health/Second");
g_signal_connect(G_OBJECT(combo), "changed", G_CALLBACK(stype_damage_combo_changed), NULL);
gtk_box_pack_start(GTK_BOX(vbox), combo, true, true, 0);
int mult = 0;
if (map.hexen) mult = 8;
gtk_combo_box_set_active(GTK_COMBO_BOX(combo), 0);
if (type & (32 * mult) && type & (64 * mult))
gtk_combo_box_set_active(GTK_COMBO_BOX(combo), 3);
else if (type & (32 * mult))
gtk_combo_box_set_active(GTK_COMBO_BOX(combo), 1);
else if (type & (64 * mult))
gtk_combo_box_set_active(GTK_COMBO_BOX(combo), 2);
// Flags frame
frame = gtk_frame_new("Flags");
gtk_container_set_border_width(GTK_CONTAINER(frame), 4);
gtk_box_pack_start(GTK_BOX(main_vbox), frame, false, false, 0);
vbox = gtk_vbox_new(false, 0);
gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
gtk_container_add(GTK_CONTAINER(frame), vbox);
GtkWidget *cbox = gtk_check_button_new_with_label("Secret Area");
g_signal_connect(G_OBJECT(cbox), "toggled", G_CALLBACK(stype_flag_changed), (gpointer)0);
gtk_box_pack_start(GTK_BOX(vbox), cbox, false, false, 0);
if (type & (128 * mult))
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(cbox), true);
cbox = gtk_check_button_new_with_label("Friction Enabled");
g_signal_connect(G_OBJECT(cbox), "toggled", G_CALLBACK(stype_flag_changed), (gpointer)1);
gtk_box_pack_start(GTK_BOX(vbox), cbox, false, false, 0);
if (type & (256 * mult))
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(cbox), true);
cbox = gtk_check_button_new_with_label("Wind Enabled");
g_signal_connect(G_OBJECT(cbox), "toggled", G_CALLBACK(stype_flag_changed), (gpointer)2);
gtk_box_pack_start(GTK_BOX(vbox), cbox, false, false, 0);
if (type & (512 * mult))
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(cbox), true);
}
return main_vbox;
}
int open_stype_select_dialog(int type)
{
current_stype = type;
GtkWidget *dialog = gtk_dialog_new_with_buttons("Select Sector Type",
GTK_WINDOW(editor_window),
GTK_DIALOG_MODAL,
GTK_STOCK_OK,
GTK_RESPONSE_ACCEPT,
GTK_STOCK_CANCEL,
GTK_RESPONSE_REJECT,
NULL);
gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), setup_stype_select(type));
gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_widget_set_size_request(dialog, 320, 360);
gtk_widget_show_all(dialog);
int ret = type;
int response = gtk_dialog_run(GTK_DIALOG(dialog));
if (response == GTK_RESPONSE_ACCEPT)
{
ret = current_stype;
if (map.boom)
{
ret += stype_damage;
if (stype_flags[0])
{
if (map.hexen)
ret += 1024;
else
ret += 128;
}
if (stype_flags[1])
{
if (map.hexen)
ret += 2048;
else
ret += 256;
}
if (stype_flags[2])
{
if (map.hexen)
ret += 4096;
else
ret += 512;
}
}
}
gtk_widget_destroy(dialog);
return ret;
}
| [
"veilofsorrow@0f6d0948-3201-0410-bbe6-95a89488c5be"
] | [
[
[
1,
200
]
]
] |
d99360498c82cd08d43a9363e8e6ef74fd6fae4a | 25f1d3e7bbb6f445174e75fed29a1028546d3562 | /2DTrans.h | bc6911b679bed8d78bc6fff750f00f08804d62f1 | [] | no_license | psgsgpsg/windr2-project | 288694c5d4bb8f28e67c392a2b15220d4b02f9af | 4f4f92734860cba028399bda6ab4ea7d46f63ca1 | refs/heads/master | 2021-01-22T23:26:48.972710 | 2010-06-16T08:31:34 | 2010-06-16T08:31:34 | 39,536,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 868 | h | // 2DTrans.h : 2DTrans 응용 프로그램에 대한 주 헤더 파일
//
#pragma once
#ifndef __AFXWIN_H__
#error "PCH에 대해 이 파일을 포함하기 전에 'stdafx.h'를 포함합니다."
#endif
#include "resource.h" // 주 기호입니다.
// CMy2DTransApp:
// 이 클래스의 구현에 대해서는 2DTrans.cpp을 참조하십시오.
//
class CMy2DTransApp : public CWinAppEx
{
public:
CMy2DTransApp();
virtual void MRUFileHandler(UINT i); // MRU 목록의 파일을 선택할 경우의 동작을 지정합니다.
// 재정의입니다.
public:
virtual BOOL InitInstance();
// 구현입니다.
BOOL m_bHiColorIcons;
virtual void PreLoadState();
virtual void LoadCustomState();
virtual void SaveCustomState();
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CMy2DTransApp theApp;
| [
"happyday19c@f92c9028-33b8-4ca2-afdf-7b78eec7ef35",
"Happyday19c@f92c9028-33b8-4ca2-afdf-7b78eec7ef35"
] | [
[
[
1,
19
],
[
21,
37
]
],
[
[
20,
20
]
]
] |
1ddf923038e59f2893379b36dde15cbbb02caca9 | f838c6ad5dd7ffa6d9687b0eb49d5381e6f2e776 | /branches/sign_198/src/libwic/encoder.cpp | 1c5f2727695c076da275bebba9ef8da2bed92aef | [] | no_license | BackupTheBerlios/wiccoder-svn | e773acb186aa9966eaf7848cda454ab0b5d948c5 | c329182382f53d7a427caec4b86b11968d516af9 | refs/heads/master | 2021-01-11T11:09:56.248990 | 2009-08-19T11:28:23 | 2009-08-19T11:28:23 | 40,806,440 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 140,435 | cpp | /*! \file encoder.cpp
\version 0.0.1
\author mice, ICQ: 332-292-380, mailto:[email protected]
\brief Реализация класса wic::encoder
\todo Более подробно описать файл encoder.h
*/
////////////////////////////////////////////////////////////////////////////////
// include
// standard C++ headers
#include <math.h>
// libwic headers
#include <wic/libwic/encoder.h>
////////////////////////////////////////////////////////////////////////////////
// wic namespace
namespace wic {
////////////////////////////////////////////////////////////////////////////////
// encoder class public definitions
/*! \param[in] width Ширина изображения.
\param[in] height Высота изображения.
\param[in] lvls Количество уровней вейвлет преобразования.
*/
encoder::encoder(const sz_t width, const sz_t height, const sz_t lvls):
_wtree(width, height, lvls),
_acoder(width * height * sizeof(w_t) * 4),
_optimize_tree_callback(0), _optimize_tree_callback_param(0),
_optimize_callback(0), _optimize_callback_param(0)
#ifdef LIBWIC_USE_DBG_SURFACE
, _dbg_opt_surface(width, height), _dbg_enc_surface(width, height),
_dbg_dec_surface(width, height)
#endif
{
// проверка утверждений
assert(MINIMUM_LEVELS <= lvls);
#ifdef LIBWIC_DEBUG
_dbg_out_stream.open("dumps/[encoder]debug.out",
std::ios_base::out | std::ios_base::app);
if (_dbg_out_stream.good())
{
time_t t;
time(&t);
_dbg_out_stream << std::endl << ctime(&t) << std::endl;
}
#endif
}
/*!
*/
encoder::~encoder() {
}
/*! \param[in] callback Функция обратного вызова
\param[in] param Пользовательский параметр, передаваемый в функцию
обратного вызова
*/
void encoder::optimize_tree_callback(const optimize_tree_callback_f &callback,
void *const param)
{
_optimize_tree_callback = callback;
_optimize_tree_callback_param = param;
}
/*! \param[in] callback Функция обратного вызова
\param[in] param Пользовательский параметр, передаваемый в функцию
обратного вызова
*/
void encoder::optimize_callback(const optimize_callback_f &callback,
void *const param)
{
_optimize_callback = callback;
_optimize_callback_param = param;
}
/*! \param[in] w Спектр вейвлет преобразования входного изображения для
кодирования
\param[in] q Квантователь. Чем больше значение (величина) квантователя,
тем большую степень сжатия можно получить. Однако при увеличении
квантователя качество восстановленного (декодированного) изображения
ухудшается. Значение квантователя должно быть больше <i>1</i>.
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами. Чем больше данный
параметр, тем больший приоритет будет отдан битовым затратам.
Соответственно, при 0 будет учитываться только ошибка кодирования.
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\return Результат проведённого кодирования
Данный механизм кодирования применяется, когда оптимальные (или
субоптимальные) значения параметров <i>q</i> и <i>lambda</i> известны
заранее. Этот метод является самым быстрым так как производит операции
оптимизации топологии и кодирования только по одному разу.
Стоит заметить, что метод также производит квантование спектра выбранным
квантователем <i>q</i>, поэтому его не желательно использовать в
ситуациях когда необходимо получить результаты сжатия одного изображения
с разным параметром <i>lambda</i>. Для таких случаев лучше использовать
более быструю функцию cheap_encode(), которая не производит квантования
коэффициентов спектра (но может быть ещё не реализованна =).
Код функции использует макрос #OPTIMIZATION_USE_VIRTUAL_ENCODING. Если он
определён будет производиться виртуальное кодирование коэффициентов, что
несколько быстрее. Однако не все реализации битовых кодеров могут
поддерживать это.
Вся информация необходимая для успешного декодирования (кроме информации
описывающей параметры исходного изображения, такие как его разрешение и
количество уровней преобразования) возвращается через структуру
tunes_t. Доступ к закодированному изображению осуществляется через объект
арифметического кодера, ссылку на который можно получить вызвав метод
coder().
*/
encoder::enc_result_t
encoder::encode(const w_t *const w, const q_t q, const lambda_t &lambda,
tunes_t &tunes)
{
// результат проведённой оптимизации
enc_result_t result;
// проверка входных параметров
assert(0 != w);
// загрузка спектра
_wtree.load_field<wnode::member_w>(w);
// оптимизация топологии ветвей
result.optimization =
#ifdef OPTIMIZATION_USE_VIRTUAL_ENCODING
_optimize_wtree_q(lambda, q, true, true);
#else
_optimize_wtree_q(lambda, q, false, true);
#endif
// кодирование всего дерева, если необходимо
if (result.optimization.real_encoded)
{
tunes.models = result.optimization.models;
result.bpp = result.optimization.bpp;
}
else
{
result.bpp = _real_encode_tight(tunes.models);
}
// запись данных необходимых для последующего декодирования
tunes.q = _wtree.q();
// завершение кодирования
return result;
}
/*! \param[in] w Спектр вейвлет преобразования входного изображения для
кодирования
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами. Чем больше данный
параметр, тем больший приоритет будет отдан битовым затратам.
Соответственно, при 0 будет учитываться только ошибка кодирования.
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\param[in] q_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] q_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] q_eps Необходимая погрешность определения квантователя
<i>q</i> при котором значение <i>RD функции Лагранжа</i> минимально
(при фиксированном параметре <i>lambda</i>).
\param[in] j_eps Необходимая погрешность нахождения минимума <i>RD
функции Лагранжа</i>. Так как абсолютная величина функции <i>J</i>
зависит от многих факторов (таких как размер изображения, его тип,
величины параметра <i>lambda</i>), использовать это параметр
затруднительно. Поэтому его значение по умолчанию равно <i>0</i>,
чтобы при поиске оптимального квантователя учитывалась только
погрешность параметра <i>q</i>.
\param[in] max_iterations Максимальное количество итераций нахождения
минимума <i>RD функции Лагранжа</i>. Если это значение равно <i>0</i>,
количество выполняемых итераций не ограничено.
\param[in] precise_bpp Смотри аналогичный параметр в функции
_search_q_min_j()
Функция производит кодирование изображения при фиксированном параметре
<i>lambda</i>, подбирая параметр кодирования <i>q</i> таким образом,
чтобы значение функции <i>RD критерия Лагранжа</i> было минимальным.
Здесь <i>lambda</i> выступает некоторой характеристикой качества. Чем
этот параметр больше, тем больше будет степень сжатия и, соответственно,
ниже качество декодированного изображения. При <i>lambda</i> равной
<i>0</i>, декодированное изображение будет наилучшего качества.
В большинстве случаев удобнее использовать не абстрактный параметр
<i>lambda</i>, а более чёткий показатель качества. В таких ситуациях
можно воспользоваться функцией quality_to_lambda(), которая
преобразует показатель качества (число в диапазоне <i>[0, 100]</i>) в
соотвествующее значение параметра <i>lambda</i>.
Код функции использует макрос #OPTIMIZATION_USE_VIRTUAL_ENCODING. Если он
определён будет производиться виртуальное кодирование коэффициентов, что
несколько быстрее. Однако не все реализации битовых кодеров могут
поддерживать это.
\sa _search_q_min_j()
*/
encoder::enc_result_t
encoder::encode_fixed_lambda(
const w_t *const w, const lambda_t &lambda,
tunes_t &tunes,
const q_t &q_min, const q_t &q_max, const q_t &q_eps,
const j_t &j_eps, const sz_t &max_iterations,
const bool precise_bpp)
{
// результат проведённой оптимизации
enc_result_t result;
// проверка входных параметров
assert(0 != w);
// загрузка спектра
_wtree.load_field<wnode::member_w>(w);
// минимизация RD функции Лагранжа
result.optimization =
#ifdef OPTIMIZATION_USE_VIRTUAL_ENCODING
_search_q_min_j(lambda, q_min, q_max, q_eps, j_eps,
true, max_iterations, precise_bpp);
#else
_search_q_min_j(lambda, q_min, q_max, q_eps, j_eps,
false, max_iterations, precise_bpp);
#endif
// кодирование всего дерева, если необходимо
if (result.optimization.real_encoded)
{
tunes.models = result.optimization.models;
result.bpp = result.optimization.bpp;
}
else
{
result.bpp = _real_encode_tight(tunes.models);
}
// сохранение параметров, необходимых для последующего декодирования
tunes.q = _wtree.q();
return result;
}
/*! \param[in] w Спектр вейвлет преобразования входного изображения для
кодирования
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами. Чем больше данный
параметр, тем больший приоритет будет отдан битовым затратам.
Соответственно, при 0 будет учитываться только ошибка кодирования.
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
Эта упрощённая версия функции encode_fixed_lambda() использует следующие
значения аргументов:
- <i>q_min = 1</i>
- <i>q_max = 64</i>
- <i>q_eps = 0.01</i>
- <i>j_eps = 0.0</i>
- <i>max_iterations = 0</i>
- <i>precise_bpp = true</i>
Код функции косвенно использует макрос #OPTIMIZATION_USE_VIRTUAL_ENCODING.
Если он определён будет производиться виртуальное кодирование коэффициентов,
что несколько быстрее. Однако не все реализации битовых кодеров могут
поддерживать это.
*/
encoder::enc_result_t
encoder::encode_fixed_lambda(const w_t *const w, const lambda_t &lambda,
tunes_t &tunes)
{
static const q_t q_eps = q_t(0.01);
static const j_t j_eps = j_t(0);
static const q_t q_min = q_t(1);
static const q_t q_max = q_t(64);
static const sz_t max_iterations = 0;
static const bool precise_bpp = true;
return encode_fixed_lambda(w, lambda, tunes, q_min, q_max, q_eps,
j_eps, 0, precise_bpp);
}
/*! \param[in] w Спектр вейвлет коэффициентов преобразованного входного
изображения для кодирования
\param[in] q Используемый квантователь
\param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будет подбираться параметр <i>lambda</i>
\param[in] bpp_eps Необходимая точность, c которой <i>bpp</i> полученный
в результате поиска параметра <i>lambda</i> будет соответствовать
заданному.
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\param[in] lambda_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] lambda_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] lambda_eps Точность, с которой будет подбираться параметр
<i>lambda</i>.
\param[in] max_iterations Максимальное количество итераций нахождения
минимума <i>RD функции Лагранжа</i>. Если это значение равно <i>0</i>,
количество выполняемых итераций не ограничено.
\param[in] precise_bpp Если <i>true</i> после каждого этапа оптимизации
топологии деревьев спектра вейвлет коэффициентов будет произведено
реальное кодирование с уменьшеными моделями арифметического кодера для
уточнения оценки битовых затрат.
\return Результат проведённого поиска. Возможна ситуация, когда нужная
<i>lambda</i> лежит вне указанного диапазона. В этом случае, функция
подберёт такую <i>lambda</i>, которая максимально удовлетворяет условиям
поиска.
Производит кодирование изображения при фиксированном параметре <i>q</i>,
подбирая значения параметра <i>lambda</i> таким образом, чтобы битовые
затраты на кодирование изображения были максимально близки к заданным.
Код функции использует макрос #OPTIMIZATION_USE_VIRTUAL_ENCODING.
Если он определён будет производиться виртуальное кодирование коэффициентов,
что несколько быстрее. Однако не все реализации битовых кодеров могут
поддерживать это.
\sa _search_lambda_at_bpp
*/
encoder::enc_result_t
encoder::encode_fixed_q(const w_t *const w, const q_t &q,
const h_t &bpp, const h_t &bpp_eps,
tunes_t &tunes,
const lambda_t &lambda_min,
const lambda_t &lambda_max,
const lambda_t &lambda_eps,
const sz_t &max_iterations,
const bool precise_bpp)
{
// результат проведённой оптимизации
enc_result_t result;
// проверка входных параметров
assert(0 != w);
assert(1 <= q);
// загрузка спектра
_wtree.cheap_load(w, q);
// генерация характеристик моделей арифметического кодера
tunes.models = _setup_acoder_models();
// минимизация RD функции Лагранжа
result.optimization =
#ifdef OPTIMIZATION_USE_VIRTUAL_ENCODING
_search_lambda_at_bpp(bpp, bpp_eps,
lambda_min, lambda_max, lambda_eps,
true, max_iterations, precise_bpp);
#else
_search_lambda_at_bpp(bpp, bpp_eps,
lambda_min, lambda_max, lambda_eps,
false, max_iterations, precise_bpp);
#endif
// кодирование всего дерева, если необходимо
if (result.optimization.real_encoded)
{
tunes.models = result.optimization.models;
result.bpp = result.optimization.bpp;
}
else
{
result.bpp = _real_encode_tight(tunes.models);
}
// сохранение параметров, необходимых для последующего декодирования
tunes.q = _wtree.q();
return result;
}
/*! \param[in] w Спектр вейвлет коэффициентов преобразованного входного
изображения для кодирования
\param[in] q Используемый квантователь
\param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будет подбираться параметр <i>lambda</i>
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\return Результат проведённого поиска.
Эта упрощённая версия функции encode_fixed_q() использует следующие
значения аргументов:
- <i>bpp_eps = 0.001</i>
- <i>lambda_min = LAMBDA_SEARCH_K_LOW*q*q</i>
- <i>lambda_max = LAMBDA_SEARCH_K_HIGHT*q*q</i>
- <i>lambda_eps = 0.0</i>
- <i>max_iterations = 0</i>
- <i>precise_bpp = true</i>
Код функции косвенно использует макрос #OPTIMIZATION_USE_VIRTUAL_ENCODING.
Если он определён будет производиться виртуальное кодирование коэффициентов,
что несколько быстрее. Однако не все реализации битовых кодеров могут
поддерживать это.
*/
encoder::enc_result_t
encoder::encode_fixed_q(const w_t *const w, const q_t &q,
const h_t &bpp, tunes_t &tunes)
{
static const h_t bpp_eps = 0.001;
static const lambda_t lambda_min = lambda_t(LAMBDA_SEARCH_K_LOW * q*q);
static const lambda_t lambda_max = lambda_t(LAMBDA_SEARCH_K_HIGHT * q*q);
static const lambda_t lambda_eps = 0;
static const sz_t max_iterations = 0;
static const bool precise_bpp = true;
return encode_fixed_q(w, q, bpp, bpp_eps, tunes,
lambda_min, lambda_max, lambda_eps,
max_iterations, precise_bpp);
}
/*! \param[in] w Спектр вейвлет коэффициентов преобразованного входного
изображения для кодирования
\param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будут подбираться параметры <i>q</i> и <i>lambda</i>.
\param[in] bpp_eps Необходимая точность, c которой <i>bpp</i> полученный
в результате поиска параметров <i>q</i> и <i>lambda</i> будет
соответствовать заданному.
\param[in] q_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] q_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] q_eps Необходимая погрешность определения квантователя
<i>q</i> при котором значение <i>RD функции Лагранжа</i> минимально
(при фиксированном параметре <i>lambda</i>).
\param[in] lambda_eps Точность, с которой будет подбираться параметр
<i>lambda</i>
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\return Результат проведённого поиска
\sa _search_q_lambda_for_bpp()
*/
encoder::enc_result_t
encoder::encode_fixed_bpp(
const w_t *const w,
const h_t &bpp, const h_t &bpp_eps,
const q_t &q_min, const q_t &q_max, const q_t &q_eps,
const lambda_t &lambda_eps,
tunes_t &tunes, const bool precise_bpp)
{
// результат проведённой оптимизации
enc_result_t result;
// проверка входных параметров
assert(0 != w);
// загрузка спектра
_wtree.load_field<wnode::member_w>(w);
// минимизация RD функции Лагранжа
result.optimization =
#ifdef OPTIMIZATION_USE_VIRTUAL_ENCODING
_search_q_lambda_for_bpp(bpp, bpp_eps,
q_min, q_max, q_eps,
lambda_eps, tunes.models, true, precise_bpp);
#else
_search_q_lambda_for_bpp(bpp, bpp_eps,
q_min, q_max, q_eps,
lambda_eps, tunes.models, false, precise_bpp);
#endif
// кодирование всего дерева, если необходимо
if (result.optimization.real_encoded)
{
tunes.models = result.optimization.models;
result.bpp = result.optimization.bpp;
}
else
{
result.bpp = _real_encode_tight(tunes.models);
}
// сохранение параметров, необходимых для последующего декодирования
tunes.q = _wtree.q();
return result;
}
/*! \param[in] w Спектр вейвлет коэффициентов преобразованного входного
изображения для кодирования
\param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будут подбираться параметры <i>q</i> и <i>lambda</i>.
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\return Результат проведённого поиска
Эта упрощённая версия функции encode_fixed_bpp() придаёт следующим
аргументам соответствующие значения:
- <i>bpp_eps = 0.001</i>
- <i>q_min = 1</i>
- <i>q_max = 64</i>
- <i>q_eps = 0.01</i>
- <i>lambda_eps = 0</i>
- <i>precise_bpp = true</i>
\sa _search_q_lambda_for_bpp(), encode_fixed_bpp
*/
encoder::enc_result_t
encoder::encode_fixed_bpp(const w_t *const w, const h_t &bpp,
tunes_t &tunes)
{
static const h_t bpp_eps = 0.001;
static const q_t q_min = q_t(1);
static const q_t q_max = q_t(64);
static const q_t q_eps = q_t(0.01);
static const lambda_t lambda_eps = 0.00001;
static const bool precise_bpp = true;
return encode_fixed_bpp(w, bpp, bpp_eps,
q_min, q_max, q_eps, lambda_eps, tunes,
precise_bpp);
}
/*! param[in] data Указатель на блок памяти, содержащий закодированное
изображение
param[in] data_sz Размер блока, содержащего закодированное
изображения
param[in] tunes Данные необходимые для восстановления изображения,
полученные от одной из функций кодирования.
Стоит заметить, что в текущей реализации, память для арифметического
кодера выделяется зарание, размер которой определяется исходя из
размеров самого изображения. Поэтому необходимо, чтобы размер
данных <i>data_sz</i> был меньше, чем acoder::buffer_sz().
*/
void encoder::decode(const byte_t *const data, const sz_t data_sz,
const tunes_t &tunes)
{
// проверка утверждений
assert(_acoder.buffer_sz() >= data_sz);
// копирование памяти в арифметический кодер
memcpy(_acoder.buffer(), data, data_sz);
// инициализация спектра перед кодированием
_wtree.wipeout();
// установка характеристик моделей
_acoder.use(_mk_acoder_models(tunes.models));
// декодирование
_acoder.decode_start();
_encode_wtree(true);
_acoder.decode_stop();
// деквантование
_wtree.dequantize<wnode::member_wc>(tunes.q);
}
/*! \param[in] quality Показатель качества
\return Значение параметра <i>lambda</i>, соответствующее выбранному
показателю качества
Показатель качества представляет значение из диапазона <i>[0, 100]</i>.
Значение <i>100</i> соответствует максимальному качеству сжатия, а
значение <i>0</i> соответствует максимальной степени сжатия.
Преобразование производится по формуле:
\verbatim
lambda = pow((quality + 2.0), (102 / (quality + 2) - 1)) - 1;
\endverbatim
*/
lambda_t encoder::quality_to_lambda(const double &quality)
{
assert(0.0 <= quality && quality <= 100.0);
const double d = 2.0;
const double b = (quality + d);
const double p = ((100.0 + d) / b) - 1.0;
return (pow(b, p) - 1.0);
}
////////////////////////////////////////////////////////////////////////////////
// wtree class protected definitions
/*! \param[in] s Значение прогнозной величины <i>S<sub>j</sub></i>
\param[in] lvl Номер уровня разложения, из которого был взят коэффициент
\return Номер выбираемой модели
\note Стоит заметить, что для нулевого и первого уровней функция
возвращает определённые значения, независимо от параметра <i>s</i>.
*/
sz_t encoder::_ind_spec(const pi_t &s, const sz_t lvl)
{
assert(0 == ACODER_SPEC_LL_MODELS);
if (subbands::LVL_0 == lvl) return ACODER_SPEC_LL_MODELS;
if (subbands::LVL_1 == lvl) return 1;
if (26.0 <= s) return 1;
if ( 9.8 <= s) return 2;
if ( 4.1 <= s) return 3;
if ( 1.72 <= s) return 4;
return 5;
}
/*! \param[in] pi Значение прогнозной величины <i>P<sub>i</sub></i>
\param[in] lvl Номер уровня разложения, из которого был взят групповой
признак подрезания ветвей
\return Номер выбираемой модели
\note Стоит заметить, что если параметр <i>lvl</i> равен <i>0</i>
функция всегда возвращает нулевую модель, независимо от параметра
<i>pi</i>.
*/
sz_t encoder::_ind_map(const pi_t &pi, const sz_t lvl) {
if (subbands::LVL_0 == lvl) return 0;
if (4.0 <= pi) return 4;
if (1.1 <= pi) return 3;
if (0.3 <= pi) return 2;
return 1;
}
/*! \param[in] desc Описание моделей арифметического кодера
\return Модели для арифметического кодера
*/
acoder::models_t encoder::_mk_acoder_models(const models_desc1_t &desc) const
{
// создание моделей для кодирования
acoder::models_t models;
acoder::model_t model;
// Данный способ создания моделей арифметического кодера не
// задаёт математическое ожидание модуля кодируемой величины
model.abs_avg = 0;
// модел #0 ----------------------------------------------------------------
model.min = desc.mdl_0_min;
model.max = desc.mdl_0_max;
models.push_back(model);
// модель #1 ---------------------------------------------------------------
model.min = desc.mdl_1_min;
model.max = desc.mdl_1_max;
models.push_back(model);
// модели #2..#5 -----------------------------------------------------------
model.min = desc.mdl_x_min;
model.max = desc.mdl_x_max;
models.insert(models.end(), ACODER_SPEC_MODELS_COUNT - 2, model);
// создание моделей для кодирования групповых признаков подрезания ---------
model.min = 0;
model.max = 0x7;
models.push_back(model);
model.max = 0xF;
models.insert(models.end(), ACODER_MAP_MODELS_COUNT - 1, model);
// создание моделей для кодирования знаков коэффициентов -------------------
_ins_acoder_sign_models(models);
// проверка утверждений
assert(ACODER_TOTAL_MODELS_COUNT == models.size());
return models;
}
/*! \param[in] desc Описание моделей арифметического кодера
\return Модели для арифметического кодера
*/
acoder::models_t encoder::_mk_acoder_models(const models_desc2_t &desc) const
{
// проверка утверждений
assert(items_count(desc.mins) == items_count(desc.maxs));
assert(items_count(desc.maxs) == items_count(desc.abs_avgs));
assert(items_count(desc.mins) == models_desc2_t::desced);
// создание моделей для кодирования
acoder::models_t models;
// добавление моделей для кодирования коэффициентов и признаков подрезания
for (sz_t i = 0; models_desc2_t::desced > i; ++i)
{
acoder::model_t model;
model.min = desc.mins[i];
model.max = desc.maxs[i];
model.abs_avg = desc.abs_avgs[i];
models.push_back(model);
}
// добавление моделей для кодирования знаков коэффициентов
_ins_acoder_sign_models(models);
// проверка утверждений
assert(ACODER_TOTAL_MODELS_COUNT == models.size());
return models;
}
/*! \param[in] desc Описание моделей арифметического кодера в унифицированном
формате
\return Модели для арифметического кодера
*/
acoder::models_t encoder::_mk_acoder_models(const models_desc_t &desc) const
{
// описание моделей, как их понимает арифметический кодер
acoder::models_t models;
// выбор способа представления описаний
switch (desc.version)
{
case MODELS_DESC_V1:
models = _mk_acoder_models(desc.md.v1);
break;
case MODELS_DESC_V2:
models = _mk_acoder_models(desc.md.v2);
break;
default:
// unsupported models description
assert(false);
break;
}
return models;
}
/*! \return Описание моделей для арифметического кодера
Описание моделей (значение максимального и минимального элемента в модели)
составляется по следующему принципу:
- для модели #0: минимальный элемент из <i>LL</i> саббенда, максимальный
элемент также из <i>LL</i> саббенда
- для модели #1: минимальный элемент из всех саббендов первого уровня
(саббенды "дочерние" от <i>LL</i>), максимальный элемент также из всех
саббендов первого уровня.
- для моделей #2..#5: минимальные элемент из всех оставшихся саббендов,
максимальный элемент также из всех оставшихся саббендов
*/
encoder::models_desc1_t encoder::_mk_acoder_smart_models() const
{
// создание моделей для кодирования
models_desc1_t desc;
// модел #0 ----------------------------------------------------------------
{
const subbands::subband_t &sb_LL = _wtree.sb().get_LL();
wk_t lvl0_min = 0;
wk_t lvl0_max = 0;
#ifdef USE_DPCM_FOR_LL_SUBBAND
_wtree.dpcm_minmax<wnode::member_wq>(sb_LL, lvl0_min, lvl0_max);
#else
wtree::coefs_iterator i = _wtree.iterator_over_subband(sb_LL);
_wtree.minmax<wnode::member_wq>(i, lvl0_min, lvl0_max);
#endif
desc.mdl_0_min = short(lvl0_min);
desc.mdl_0_max = short(lvl0_max);
}
// модели #1..#5 -----------------------------------------------------------
{
// поиск минимума и максимума на первом уровне
wtree::coefs_cumulative_iterator i_cum;
for (sz_t k = 0; subbands::SUBBANDS_ON_LEVEL > k; ++k)
{
const subbands::subband_t &sb = _wtree.sb().get(subbands::LVL_1, k);
i_cum.add(_wtree.iterator_over_subband(sb));
}
wk_t lvl1_min = 0;
wk_t lvl1_max = 0;
_wtree.minmax<wnode::member_wq>(some_iterator_adapt(i_cum),
lvl1_min, lvl1_max);
// поиск минимума и максимума на уровнях начиная со второго
wtree::coefs_cumulative_iterator j_cum;
for (sz_t lvl = subbands::LVL_1 + subbands::LVL_NEXT;
_wtree.lvls() >= lvl; ++lvl)
{
for (sz_t k = 0; subbands::SUBBANDS_ON_LEVEL > k; ++k)
{
const subbands::subband_t &sb = _wtree.sb().get(lvl, k);
j_cum.add(_wtree.iterator_over_subband(sb));
}
}
wk_t lvlx_min = 0;
wk_t lvlx_max = 0;
_wtree.minmax<wnode::member_wq>(some_iterator_adapt(j_cum),
lvlx_min, lvlx_max);
// модель #1
desc.mdl_1_min = short(std::min(lvl1_min, lvlx_min));
desc.mdl_1_max = short(std::max(lvl1_max, lvlx_max));
// модели #2..#5
desc.mdl_x_min = lvlx_min;
desc.mdl_x_max = lvlx_max;
}
return desc;
}
/*! \param[in] ac Арифметический кодер, статистика которого будет использована
для построения описания моделей
*/
encoder::models_desc2_t encoder::_mk_acoder_post_models(const acoder &ac) const
{
// проверка утверждений
assert(ACODER_TOTAL_MODELS_COUNT == ac.models().size());
models_desc2_t desc;
// проверка утверждений
assert(items_count(desc.mins) == items_count(desc.maxs));
assert(items_count(desc.maxs) == items_count(desc.abs_avgs));
assert(models_desc2_t::desced == items_count(desc.mins));
assert(models_desc2_t::desced <= ac.models().size());
for (sz_t i = 0; models_desc2_t::desced > i; ++i)
{
desc.mins[i] = ac.rmin(i);
desc.maxs[i] = ac.rmax(i);
desc.abs_avgs[i] = (unsigned short)(ac.abs_average(i));
// проверка на пустую модель (в которых rmin > rmax)
// данные действия необходимы, если в модель не попало ни одного
// элемента
if (desc.mins[i] > desc.maxs[i])
{
desc.mins[i] = desc.maxs[i] = 0;
}
}
return desc;
}
/*! \param[in] use_models Если <i>true</i> то полученная модель будет
установлена для использования в арифметический кодер
\return Описание моделей арифметического кодера, которые были
установленны этой функцией
Для генерации описания моделей используется функция
_mk_acoder_smart_models(), соответственно, сгенерированные модели
имеют тип MODELS_DESC_V1.
*/
encoder::models_desc_t encoder::_setup_acoder_models(const use_models)
{
// описание моделей для арифметического кодера
models_desc_t desc;
// идентификатор используемого представления описания моделей
desc.version = MODELS_DESC_V1;
// определение суб-оптимальных моделей для арифметического кодера
desc.md.v1 = _mk_acoder_smart_models();
// загрузка моделей в арифметический кодер
if (use_models) _acoder.use(_mk_acoder_models(desc));
return desc;
}
/*! \param[in] use_models Если <i>true</i> то полученная модель будет
установлена для использования в арифметический кодер
\return Описание моделей арифметического кодера, которые были
установленны этой функцией
Для генерации описания моделей используется функция
_mk_acoder_post_models()
*/
encoder::models_desc_t encoder::_setup_acoder_post_models(const use_models)
{
// описание моделей для арифметического кодера
models_desc_t desc;
// используется вторая версия представления описания моделей
// арифметического кодера
desc.version = MODELS_DESC_V2;
// создание нового описания моделей арифметического кодера,
// основываясь на статистике кодирования, полученной при
// оптимизации топологии деревьев спектра вейвлет коэффициентов
desc.md.v2 = _mk_acoder_post_models(_acoder);
// загрузка моделей в арифметический кодер
if (use_models) _acoder.use(_mk_acoder_models(desc));
return desc;
}
/*! \param[in] result Результат проведённой оптимизации, в резултате которой
могли поменяться модели арифметического кодера
\param[in] models Оригинальные модели арифметического кодера, которые
следует востановить в случае их изменения процедурой оптимизации топологии
\return <i>true</i> если измененённые модели были восстановлены и
<i>false</i> если модели не изменились процедурой оптимизации.
*/
bool encoder::_restore_spoiled_models(const optimize_result_t &result,
const acoder::models_t &models)
{
// Проверка, были ли в процессе оптимизации изменены
if (MODELS_DESC_NONE == result.models.version) return false;
// Дополнительная проверка на равенство старых и новых моделей.
// Сейчас не используется, так как в текущей реализации функций
// оптимизации топологии версия описания моделей устанавливается
// только в случае их изменения.
// if (models == _mk_acoder_models(result.models)) return false;
// восстановление моделей используемых арифметическим кодером
_acoder.use(models);
return true;
}
/*! \param[in] m Номер модели для кодирования
\param[in] wk Значение коэффициента для кодирования
\return Битовые затраты, необходимые для кодирования коэффициента с
использованием этой модели
*/
h_t encoder::_h_spec(const sz_t m, const wk_t &wk) {
return _acoder.enc_entropy(wk, m);
}
/*! \param[in] m Номер модели для кодирования
\param[in] n Значение группового признака подрезания ветвей
\return Битовые затраты, необходимые для кодирования группового
признака подрезания
*/
h_t encoder::_h_map(const sz_t m, const n_t &n) {
return _acoder.enc_entropy(n, m + ACODER_SPEC_MODELS_COUNT);
}
/*! \param[in] m Номер модели для кодирования
\param[in] wk Значение коэффициента для кодирования
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
*/
void encoder::_encode_spec(const sz_t m, const wk_t &wk,
const bool virtual_encode)
{
// Кодирование модуля коэффициента
_acoder.put(wk, m, virtual_encode);
}
/*! \param[in] wk Значение коэффициента для кодирования
\param[in] spec_m Номер модели для кодирования модуля коэффициента
\param[in] sign_m Номер модели для кодирования знака коэффициента
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
*/
void encoder::_encode_spec_se(const wk_t &wk, const sz_t spec_m,
const sz_t sign_m, const bool virtual_encode)
{
// Проверка специального случая, чтобы удостовериться что нулевая модель
// для знака используется только в том случае, когда кодируется элемент
// из LL саббенда
assert(0 != sign_m || ACODER_SPEC_LL_MODELS == spec_m);
// Специальный случай для LL саббенда - кодируем как есть
if (ACODER_SPEC_LL_MODELS == spec_m)
{
_acoder.put(wk, spec_m, virtual_encode);
return;
}
// Определение знака коэффициента
const sz_t sign_v = wnode::signp(wk);
// Ограничение на возможные значения знака коэффициента
assert(0 <= sign_v && sign_v <= 2);
// Кодирование знака коэффициента
_acoder.put(sign_v, sign_m, virtual_encode);
// Знак равен 0 если сам коэффициент 0. В таком случае кодирование
// коэффициента не требуется
if (0 == sign_v) return;
// Модуль коэффициента который будет закодирован
const wk_t spec_v = abs(wk);
// Кодирование модуля коэффициента
_acoder.put(spec_v, spec_m, virtual_encode);
}
/*! \param[in] m Номер модели для кодирования
\param[in] n Значение группового признака подрезания ветвей
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
*/
void encoder::_encode_map(const sz_t m, const n_t &n,
const bool virtual_encode)
{
_acoder.put(n, m + ACODER_SPEC_MODELS_COUNT, virtual_encode);
}
/*! \param[in] m Номер модели для кодирования
\return Значение коэффициента для кодирования
*/
wk_t encoder::_decode_spec(const sz_t m)
{
return _acoder.get<wk_t>(m);
}
wk_t encoder::_decode_spec_se(const sz_t spec_m, const sz_t sign_m)
{
// Проверка специального случая, чтобы удостовериться что нулевая модель
// для знака используется только в том случае, когда декодируется элемент
// из LL саббенда
assert(0 != sign_m || ACODER_SPEC_LL_MODELS == spec_m);
// Специальный случай для LL саббенда - кодируем как есть
if (ACODER_SPEC_LL_MODELS == spec_m) return _acoder.get<wk_t>(spec_m);
// Декодирование знака коэффициента
const sz_t sign_v = _acoder.get<sz_t>(sign_m);
// Ограничение на возможные значения знака коэффициента
assert(0 <= sign_v && sign_v <= 2);
// Если знак равен 0, значит и сам коэффициент 0. В таком случае
// декодирование коэффициента не требуется
if (0 == sign_v) return 0;
// Декодирование модуля коэффициента
const wk_t spec_v = _acoder.get<wk_t>(spec_m);
// Добавление знака к модулю коэффициента
return wnode::to_signed(spec_v, sign_v);
}
/*! \param[in] m Номер модели для кодирования
\return Значение группового признака подрезания ветвей
*/
n_t encoder::_decode_map(const sz_t m)
{
return _acoder.get<n_t>(m + ACODER_SPEC_MODELS_COUNT);
}
/*! \param[in] p Предполагаемые координаты элемента (коэффициента)
\param[in] k Откорректированное (или просто проквантованное) значение
коэффициента
\param[in] lambda Параметр <i>lambda</i>, отвечает за <i>Rate/Distortion</i>
баланс при вычислении <i>RD</i> функции. Чем это значение больше, тем
больший вклад в значение <i>RD</i> функции будут вносить битовые затраты
на кодирование коэффициента арифметическим кодером.
\param[in] model Номер модели арифметического кодера, которая будет
использована для кодирования коэффициента
\return Значения <i>RD-функции Лагрнанжа</i>
\note Функция применима для элементов из любых саббендов.
*/
j_t encoder::_calc_rd_iteration(const p_t &p, const wk_t &k,
const lambda_t &lambda, const sz_t &model)
{
const wnode &node = _wtree.at(p);
const w_t dw = (wnode::dequantize(k, _wtree.q()) - node.w);
const double h = _h_spec(model, k);
return (dw*dw + lambda * h);
}
/*! \param[in] p Координаты коэффициента для корректировки
\param[in] sb Саббенд, в котором находится коэффициент
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\return Значение откорректированного коэффициента
\note Функция применима для коэффициентов из любых саббендов
\sa COEF_FIX_USE_4_POINTS
\todo Написать тест для этой функции
*/
wk_t encoder::_coef_fix(const p_t &p, const subbands::subband_t &sb,
const lambda_t &lambda)
{
#ifdef COEF_FIX_DISABLED
return _wtree.at(p).wq;
#endif
// выбор модели и оригинального значения коэффициента
const sz_t model = _ind_spec<wnode::member_wc>(p, sb);
const wk_t &wq = _wtree.at(p).wq;
// Определение набора подбираемых значений
#ifdef COEF_FIX_USE_4_POINTS
static const sz_t vals_count = 4;
const wk_t w_vals[vals_count] = {0, wq, wq + 1, wq - 1};
#else
static const sz_t vals_count = 3;
const wk_t w_drift = (0 <= wq)? -1: +1;
const wk_t w_vals[vals_count] = {0, wq, wq + w_drift};
#endif
// начальные значения для поиска минимума RD функции
wk_t k_optim = w_vals[0];
j_t j_optim = _calc_rd_iteration(p, k_optim, lambda, model);
// поиск минимального значения RD функции
for (int i = 1; vals_count > i; ++i) {
const wk_t &k = w_vals[i];
const j_t j = _calc_rd_iteration(p, k, lambda, model);
if (j < j_optim) {
j_optim = j;
k_optim = k;
}
}
// возврат откорректированного значения коэффициента
return k_optim;
}
/*! \param[in] p Координаты родительского элемента
\param[in] sb_j Саббенд, в котором находятся дочерние элементы
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\note Функция применима только для родительских элементов не из
<i>LL</i> саббенда.
*/
void encoder::_coefs_fix(const p_t &p, const subbands::subband_t &sb_j,
const lambda_t &lambda)
{
// цикл по дочерним элементам
for (wtree::coefs_iterator i = _wtree.iterator_over_children(p);
!i->end(); i->next())
{
const p_t &p = i->get();
wnode &node = _wtree.at(p);
node.wc = _coef_fix(p, sb_j, lambda);
}
}
/*! \param[in] p Координаты родительского элемента
\param[in] sb_j Саббенд, в котором находятся дочерние элементы
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\note Функция применима только для родительских элементов из
любых саббендов.
*/
void encoder::_coefs_fix_uni(const p_t &p, const subbands::subband_t &sb_j,
const lambda_t &lambda)
{
// цикл по дочерним элементам
for (wtree::coefs_iterator i = _wtree.iterator_over_children_uni(p);
!i->end(); i->next())
{
const p_t &p = i->get();
wnode &node = _wtree.at(p);
node.wc = _coef_fix(p, sb_j, lambda);
}
}
/*! \param[in] p Координаты элемента для которого будет расчитываться
\param[in] sb Саббенд, в котором находятся коэффициенты из сохраняемой
ветви. Другими словами, этот саббенд дочерний для того, в котором
находится элемент с координатами <i>p</i>.
\param[in] lambda Параметр <i>lambda</i> который участвует в вычислении
<i>RD</i> функции и представляет собой баланс между <i>R (rate)</i> и
<i>D (distortion)</i> частями <i>функции Лагранжа</i>.
\return Значение <i>RD функции Лагранжа</i>.
\note Функция не применима для элементов из <i>LL</i> саббенда.
\sa _calc_j0_value()
\todo Необходимо написать тест для этой функции.
*/
j_t encoder::_calc_j1_value(const p_t &p, const subbands::subband_t &sb,
const lambda_t &lambda)
{
// получение номера модели для кодирования коэффициентов
const sz_t model = _ind_spec<wnode::member_wc>(p, sb);
j_t j1 = 0;
for (wtree::coefs_iterator i = _wtree.iterator_over_children(p);
!i->end(); i->next())
{
const wnode &node = _wtree.at(i->get());
j1 += _calc_rd_iteration(i->get(), node.wc, lambda, model);
}
return j1;
}
/*! \param[in] root Координаты корневого элемента
\param[in] j_map Значение <i>RD-функцию Лагранжа</i> полученное
в шаге 2.6.
\param[in] lambda Параметр <i>lambda</i> который участвует в вычислении
<i>RD</i> функции и представляет собой баланс между <i>R (rate)</i> и
<i>D (distortion)</i> частями <i>функции Лагранжа</i>.
\return Значение <i>RD-функции Лагранжа</i>.
Функция также сохраняет полученное значение <i>RD-функции Лагранжа</i> в
полях wnode::j0 и wnode::j1 корневого элемента.
*/
j_t encoder::_calc_jx_value(const p_t &root, const j_t &j_map,
const lambda_t &lambda)
{
assert(_wtree.sb().test_LL(root));
// получаем ссылку саббенды
const subbands &sb = _wtree.sb();
j_t j = j_map;
// цикл по дочерним элементам
for (wtree::coefs_iterator i = _wtree.iterator_over_LL_children(root);
!i->end(); i->next())
{
const p_t &p = i->get();
const wnode &node = _wtree.at(p);
// получаем ссылку на саббенд в котором лежит рассматриваемый элемент
const subbands::subband_t &sb_i = sb.from_point(p, subbands::LVL_1);
j += _calc_rd_iteration(p, node.wc, lambda,
_ind_spec<wnode::member_wc>(p, sb_i));
}
wnode &node = _wtree.at(root);
return (node.j0 = node.j1 = j);
}
/*! \param[in] p Координаты элемента, для которого выполняется подготовка
значений <i>J</i> (<i>RD функция Лагранжа</i>)
\param[in] sb_j Саббенд в котором находятся дочерние элементы
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
Функция обычно выполняется при переходе с уровня <i>lvl</i>, на
уровень <i>lvl + subbands::LVL_PREV</i>.
\note Функция не применима для элементов из <i>LL</i> саббенда.
*/
void encoder::_prepare_j(const p_t &p, const subbands::subband_t &sb_j,
const lambda_t &lambda)
{
wnode &node = _wtree.at(p);
node.j0 = _calc_j0_value<false>(p);
node.j1 = _calc_j1_value(p, sb_j, lambda);
}
/*! \param[in] p Координаты элемента, для которого выполняется подготовка
значений <i>J</i> (<i>RD функция Лагранжа</i>)
\param[in] sb_j Саббенд в котором находятся дочерние элементы
\param[in] j Значение функции Лагранжа, полученное при подборе
оптимальной топологии ветвей
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
Функция обычно выполняется при переходе с уровня <i>lvl</i>, на
уровень <i>lvl + subbands::LVL_PREV</i>.
\note Функция не применима для элементов из <i>LL</i> саббенда.
*/
void encoder::_prepare_j(const p_t &p, const subbands::subband_t &sb_j,
const j_t &j, const lambda_t &lambda)
{
wnode &node = _wtree.at(p);
node.j0 = _calc_j0_value<true>(p);
node.j1 = j + _calc_j1_value(p, sb_j, lambda);
}
/*! \param[in] branch Координаты элемента, находящегося в вершине
ветви
\param[in] n Групповой признак подрезания, характеризующий
топологию ветви
\return Значение функции Лагранжа при топологии описанной в
<i>n</i>
*/
j_t encoder::_topology_calc_j(const p_t &branch, const n_t n)
{
j_t j = 0;
for (wtree::coefs_iterator i =
_wtree.iterator_over_children(branch);
!i->end(); i->next())
{
const p_t &p = i->get();
const wnode &node = _wtree.at(p);
const n_t mask = _wtree.child_n_mask(p, branch);
j += (_wtree.test_n_mask(n, mask))? node.j1: node.j0;
}
return j;
}
//! определённой её топологии (ветвь из <i>LL</i> саббенда)
/*! \param[in] branch Координаты элемента, находящегося в вершине
ветви
\param[in] n Групповой признак подрезания, характеризующий
топологию ветви
\return Значение функции Лагранжа при топологии описанной в
<i>n</i>
*/
j_t encoder::_topology_calc_j_LL(const p_t &branch, const n_t n)
{
// начальное значение для функции Лагранжа
j_t j = 0;
for (wtree::coefs_iterator i =
_wtree.iterator_over_LL_children(branch);
!i->end(); i->next())
{
const p_t &p = i->get();
const wnode &node = _wtree.at(p);
const n_t mask = _wtree.child_n_mask_LL(p);
j += (_wtree.test_n_mask(n, mask))? node.j1: node.j0;
}
return j;
}
/*! \param[in] branch Координаты родительского элемента, дающего
начало ветви.
\param[in] sb Саббенд, содержащий элемент <i>branch</i>
\param[in] lambda Параметр <i>lambda</i> который участвует в
вычислении <i>RD</i> функции и представляет собой баланс между
<i>R (rate)</i> и <i>D (distortion)</i> частями функции
<i>Лагранжа</i>.
\return Групповой признак подрезания ветвей
Алгоритм оптимизации топологии подробно описан в <i>35.pdf</i>
\note Функция применима для всех ветвей (как берущих начало в
<i>LL</i> саббенде, так и для всех остальных).
*/
encoder::_branch_topology_t
encoder::_optimize_branch_topology(const p_t &branch,
const subbands::subband_t &sb,
const lambda_t &lambda)
{
// получение дочернего саббенда
const sz_t lvl_j = sb.lvl + subbands::LVL_NEXT;
const subbands::subband_t &sb_j = _wtree.sb().get(lvl_j, sb.i);
// выбор модели для кодирования групповых признаков подрезания
const sz_t model = _ind_map<wnode::member_wc>(branch, sb_j);
// поиск наиболее оптимальной топологии
wtree::n_iterator i = _wtree.iterator_through_n(sb.lvl);
// первая итерация цикла поиска
_branch_topology_t optim_topology;
optim_topology.n = i->get();
optim_topology.j = _topology_calc_j_uni(branch,
optim_topology.n);
// последующие итерации
for (i->next(); !i->end(); i->next())
{
const n_t &n = i->get();
const j_t j_sum = _topology_calc_j_uni(branch, n);
const j_t j = (j_sum + lambda * _h_map(model, n));
if (j < optim_topology.j) {
optim_topology.j = j;
optim_topology.n = n;
}
}
return optim_topology;
}
/*! \param[in] root Координаты корневого элемента
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
Функция выполняет кодирование:
- Коэффициента при корневом элементе
- Группового признака подрезания при корневом элементе
- Коэффициентов принадлежащих дереву с первого уровня разложения
*/
void encoder::_encode_tree_root(const p_t &root,
const bool virtual_encode)
{
// получение корневого элемента
const wnode &root_node = _wtree.at(root);
// определение модели, используемой для кодирования коэффициента
const sz_t spec_model = _ind_spec(0, subbands::LVL_0);
// закодировать коэффициент с нулевого уровня
#ifdef USE_DPCM_FOR_LL_SUBBAND
const subbands::subband_t &sb_LL = _wtree.sb().get_LL();
const wk_t wc_p = _wtree.dpcm_predict<wnode::member_wc>(root, sb_LL);
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
_encode_spec_se(dpcm::encode(root_node.wc, wc_p), spec_model, 0,
virtual_encode);
#else
_encode_spec(spec_model, dpcm::encode(root_node.wc, wc_p),
virtual_encode);
#endif
#else
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
_encode_spec_se(root_node.wc, spec_model, 0, virtual_encode);
#else
_encode_spec(spec_model, root_node.wc, virtual_encode);
#endif
#endif
// определение модели для кодирования признака подрезания
const sz_t map_model = _ind_map(0, subbands::LVL_0);
// закодировать групповой признак подрезания с нулевого уровня
_encode_map(map_model, root_node.n, virtual_encode);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись отладочной информации о закодированном коэффициенте и признаке
// подрезания
wicdbg::dbg_pixel &dbg_pixel = _dbg_opt_surface.get(root);
dbg_pixel.wc = root_node.wc;
dbg_pixel.wc_model = spec_model;
dbg_pixel.n = root_node.n;
dbg_pixel.n_model = map_model;
#endif
// кодирование дочерних коэффициентов с первого уровня
for (wtree::coefs_iterator i = _wtree.iterator_over_LL_children(root);
!i->end(); i->next())
{
// координаты элемента
const p_t &p = i->get();
// определение модели, используемой для кодирования коэффициента
const sz_t spec_model = _ind_spec(0, subbands::LVL_1);
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
const sz_t sign_model = _ind_sign<wnode::member_wc>(p);
#endif
// ссылка на кодируемый коэффициент
const wk_t &wc = _wtree.at(p).wc;
// закодировать коэффициенты с первого уровня
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
_encode_spec_se(wc, spec_model, sign_model, virtual_encode);
#else
_encode_spec(spec_model, wc, virtual_encode);
#endif
#ifdef LIBWIC_USE_DBG_SURFACE
// запись отладочной информации о закодированном коэффициенте
wicdbg::dbg_pixel &dbg_pixel = _dbg_opt_surface.get(p);
dbg_pixel.wc = wc;
dbg_pixel.wc_model = spec_model;
#endif
}
}
/*! \param[in] root Координаты корнвого элемента
\param[in] lvl Номер уровня разложения
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
*/
void encoder::_encode_tree_leafs(const p_t &root, const sz_t lvl,
const bool virtual_encode)
{
// псевдонимы для номеров уровней
const sz_t lvl_g = lvl;
const sz_t lvl_j = lvl_g + subbands::LVL_PREV;
const sz_t lvl_i = lvl_j + subbands::LVL_PREV;
// цикл по саббендам в уровне
for (sz_t k = 0; _wtree.sb().subbands_on_lvl(lvl) > k; ++k)
{
const subbands::subband_t &sb_g = _wtree.sb().get(lvl_g, k);
const subbands::subband_t &sb_j = _wtree.sb().get(lvl_j, k);
// кодирование коэффициентов
for (wtree::coefs_iterator g = _wtree.iterator_over_leafs(root, sb_g);
!g->end(); g->next())
{
const p_t &p_g = g->get();
wnode &node_g = _wtree.at(p_g);
if (node_g.invalid) continue;
// Модели арифметического кодера для кодирования коэффициента
// и его знака
const sz_t spec_model = _ind_spec<wnode::member_wc>(p_g, sb_g);
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
const sz_t sign_model = _ind_sign<wnode::member_wc>(p_g, sb_g);
#endif
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
_encode_spec_se(node_g.wc, spec_model, sign_model, virtual_encode);
#else
_encode_spec(spec_model, node_g.wc, virtual_encode);
#endif
#ifdef LIBWIC_USE_DBG_SURFACE
// Запись кодируемого коэффициента в отладочную поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_opt_surface.get(p_g);
dbg_pixel.wc = node_g.wc;
dbg_pixel.wc_model = spec_model;
#endif
}
// на предпоследнем уровне нет групповых признаков подрезания
if (_wtree.lvls() == lvl) continue;
// кодирование групповых признаков подрезания
for (wtree::coefs_iterator j = _wtree.iterator_over_leafs(root, sb_j);
!j->end(); j->next())
{
const p_t &p_j = j->get();
const p_t &p_i = _wtree.prnt_uni(p_j);
const wnode &node_i = _wtree.at(p_i);
// маска подрезания, где текущий элемент не подрезан
const n_t mask = _wtree.child_n_mask_uni(p_j, p_i);
// переходим к следующему потомку, если ветвь подрезана
if (!_wtree.test_n_mask(node_i.n, mask)) continue;
wnode &node_j = _wtree.at(p_j);
const sz_t model = _ind_map<wnode::member_wc>(p_j, sb_g);
_encode_map(model, node_j.n, virtual_encode);
#ifdef LIBWIC_USE_DBG_SURFACE
// Запись признака подрезания в отладочную поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_opt_surface.get(p_j);
dbg_pixel.n = node_j.n;
dbg_pixel.n_model = model;
#endif
}
}
}
/*! \param[in] root Координаты корневого элемента дерева
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
*/
void encoder::_encode_tree(const p_t &root,
const bool virtual_encode)
{
// кодирование корневого и дочерних элементов дерева
_encode_tree_root(root, virtual_encode);
// кодирование элементов дерева на остальных уровнях
const sz_t first_lvl = subbands::LVL_1 + subbands::LVL_NEXT;
const sz_t final_lvl = _wtree.lvls();
for (sz_t lvl = first_lvl; final_lvl >= lvl; ++lvl)
{
_encode_tree_leafs(root, lvl, virtual_encode);
}
}
/*! \param[in] decode_mode Если <i>false</i> функция будет выполнять
кодирование спектра, иначе (если <i>true</i>) будет выполнять
декодирование спектра.
*/
void encoder::_encode_wtree_root(const bool decode_mode)
{
// LL cаббенд
const subbands::subband_t &sb_LL = _wtree.sb().get_LL();
// модели для кодирования в LL саббенде
const sz_t spec_LL_model = _ind_spec(0, sb_LL.lvl);
const sz_t map_LL_model = _ind_map(0, sb_LL.lvl);
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
static const sz_t sign_LL_model = 0;
#endif
// (де)кодирование коэффициентов и групповых признаков подрезания
// из LL саббенда
for (wtree::coefs_iterator i = _wtree.iterator_over_subband(sb_LL);
!i->end(); i->next())
{
// координаты элемента
const p_t &p_i = i->get();
// сам элемент из LL саббенда
wnode &node = _wtree.at(p_i);
#ifdef USE_DPCM_FOR_LL_SUBBAND
// Подсчёт прогнозного значения для коэффициента
const wk_t wc_p = _wtree.dpcm_predict<wnode::member_wc>(p_i, sb_LL);
#endif
if (decode_mode)
{
// декодирование коэффициента
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
node.wc = _decode_spec_se(spec_LL_model, sign_LL_model);
#else
node.wc = _decode_spec(spec_LL_model);;
#endif
// Необходимо скорректировать декодированный коэффициент если для
// LL саббенда используется ДИКМ
#ifdef USE_DPCM_FOR_LL_SUBBAND
node.wc = dpcm::decode(node.wc, wc_p);
#endif
// декодирование признака подрезания ветвей
node.n = _decode_map(map_LL_model);
// порождение ветвей в соответствии с полученным признаком
// подрезания
_wtree.uncut_leafs(p_i, node.n);
}
else
{
// кодирование коэффициента
#ifdef USE_DPCM_FOR_LL_SUBBAND
const wk_t spec_v = dpcm::encode(node.wc, wc_p);
#else
const wk_t &spec_v = node.wc;
#endif
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
_encode_spec_se(spec_v, spec_LL_model, sign_LL_model);
#else
_encode_spec(spec_LL_model, spec_v);
#endif
// кодирование признака подрезания
_encode_map(map_LL_model, node.n);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись информации о кодируемых коэффициентов и признаках
// подрезания в отладочную поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_enc_surface.get(p_i);
dbg_pixel.wc = node.wc;
dbg_pixel.wc_model = spec_LL_model;
dbg_pixel.n = node.n;
dbg_pixel.n_model = map_LL_model;
#endif
}
}
// модель для кодирования коэффициентов с первого уровня
const sz_t spec_1_model = _ind_spec(0, subbands::LVL_1);
// (де)кодирование коэффициентов из саббендов первого уровня
for (sz_t k = 0; subbands::SUBBANDS_ON_LEVEL > k; ++k)
{
// очередной саббенд с первого уровня
const subbands::subband_t &sb = _wtree.sb().get(subbands::LVL_1, k);
// цикл по всем элементам из саббенда с первого уровня
for (wtree::coefs_iterator i = _wtree.iterator_over_subband(sb);
!i->end(); i->next())
{
// координаты (де)кодируемого элемента в спектре
const p_t &p = i->get();
// модель для (де)кодирования знака коэффициента
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
const sz_t sign_model = _ind_sign<wnode::member_wc>(p, sb);
#endif
// ссылка на (де)кодируемый коэффициент
wk_t &wc = _wtree.at(p).wc;
// (де)кодирование дочерендного коэффициента
if (decode_mode)
{
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
wc = _decode_spec_se(spec_1_model, sign_model);
#else
wc = _decode_spec(spec_1_model);
#endif
}
else
{
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
_encode_spec_se(wc, spec_1_model, sign_model);
#else
_encode_spec(spec_1_model, wc);
#endif
// запись информации о кодируемом коэффициенте в отладочную
// поверхность
#ifdef LIBWIC_USE_DBG_SURFACE
wicdbg::dbg_pixel &dbg_pixel = _dbg_enc_surface.get(p);
dbg_pixel.wc = wc;
dbg_pixel.wc_model = spec_1_model;
#endif
}
}
}
}
/*! \param[in] lvl Номер уровня, коэффициенты на котором будут
закодированы
\param[in] decode_mode Если <i>false</i> функция будет выполнять
кодирование спектра, иначе (если <i>true</i>) будет выполнять
декодирование спектра.
\todo Возможно не стоит делать wtree::uncut_leafs() при попадании в
подрезанную ветвь при кодирование групповыйх признаков подрезания.
Вместо этого можно перед декодированием проинициализировать все поля
wnode::invalid значением <i>true</i>
*/
void encoder::_encode_wtree_level(const sz_t lvl,
const bool decode_mode)
{
// определение псевдонимов для номеров уровней
const sz_t lvl_g = lvl;
const sz_t lvl_j = lvl_g + subbands::LVL_PREV;
const sz_t lvl_i = lvl_j + subbands::LVL_PREV;
// цикл по саббендам на уровне
for (sz_t k = 0; _wtree.sb().subbands_on_lvl(lvl) > k; ++k)
{
// саббенд на уровне коэффициенты из которого будут
// закодированы и родительский для для него
const subbands::subband_t &sb_g = _wtree.sb().get(lvl_g, k);
const subbands::subband_t &sb_j = _wtree.sb().get(lvl_j, k);
// кодирование коэффициентов
for (wtree::coefs_iterator g = _wtree.iterator_over_subband(sb_g);
!g->end(); g->next())
{
// координаты элемента
const p_t &p_g = g->get();
// сам элемент
wnode &node_g = _wtree.at(p_g);
// переходим к следующему, если коэффициента попал в
// подрезанную ветвь
if (node_g.invalid) continue;
// выбираем модель для (де)кодирования коэффициента и его знака
const sz_t spec_model = _ind_spec<wnode::member_wc>(p_g, sb_g);
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
const sz_t sign_model = _ind_sign<wnode::member_wc>(p_g, sb_g);
#endif
// (де)кодирование коэффициента
if (decode_mode)
{
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
node_g.wc = _decode_spec_se(spec_model, sign_model);
#else
node_g.wc = _decode_spec(spec_model);
#endif
// запись информации о кодируемом коэффициенте в отладочную
// поверхность
#ifdef LIBWIC_USE_DBG_SURFACE
wicdbg::dbg_pixel &dbg_pixel = _dbg_dec_surface.get(p_g);
dbg_pixel.wc = node_g.wc;
dbg_pixel.wc_model = spec_model;
#endif
}
else
{
#ifdef ENCODE_SIGN_IN_SEPARATE_MODELS
_encode_spec_se( node_g.wc, spec_model, sign_model);
#else
_encode_spec(spec_model, node_g.wc);
#endif
#ifdef LIBWIC_USE_DBG_SURFACE
// запись информации о кодируемом коэффициенте в отладочную
// поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_enc_surface.get(p_g);
dbg_pixel.wc = node_g.wc;
dbg_pixel.wc_model = spec_model;
#endif
}
}
// на предпоследнем уровне нет групповых признаков подрезания
if (_wtree.lvls() == lvl) continue;
// кодирование групповых признаков подрезания
for (wtree::coefs_iterator j = _wtree.iterator_over_subband(sb_j);
!j->end(); j->next())
{
// координаты элемента
const p_t &p_j = j->get();
// координаты родительского элемента
const p_t &p_i = _wtree.prnt_uni(p_j);
// ссылка на родительский элемент
const wnode &node_i = _wtree.at(p_i);
// маска подрезания, где текущий элемент не подрезан
const n_t mask = _wtree.child_n_mask_uni(p_j, p_i);
// переходим к следующему потомку, если ветвь подрезана
if (!_wtree.test_n_mask(node_i.n, mask)) continue;
// значение элемента
wnode &node_j = _wtree.at(p_j);
// выбор модели для кодирования группового признака подрезания
const sz_t model = _ind_map<wnode::member_wc>(p_j, sb_g);
if (decode_mode)
{
// декодирование признака подрезания
node_j.n = _decode_map(model);
// порождение ветвей в соответствии с полученным признаком
// подрезания
_wtree.uncut_leafs(p_j, node_j.n);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись информации о групповом признаке подрезания в
// отладочную поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_dec_surface.get(p_j);
dbg_pixel.n = node_j.n;
dbg_pixel.n_model = model;
#endif
}
else
{
// кодирование признака подрезания
_encode_map(model, node_j.n);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись информации о групповом признаке подрезания в
// отладочную поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_enc_surface.get(p_j);
dbg_pixel.n = node_j.n;
dbg_pixel.n_model = model;
#endif
}
}
}
}
/*! \param[in] decode_mode Если <i>false</i> функция будет выполнять
кодирование спектра, иначе (если <i>true</i>) будет выполнять
декодирование спектра.
*/
void encoder::_encode_wtree(const bool decode_mode)
{
#ifdef LIBWIC_USE_DBG_SURFACE
// очистка отладочной поверхности, если производится кодирование
if (!decode_mode)
{
_dbg_enc_surface.clear();
}
else
{
_dbg_dec_surface.clear();
}
#endif
// (де)кодирование корневых элементов
_encode_wtree_root(decode_mode);
// (де)кодирование остальных элементов
const sz_t first_lvl = subbands::LVL_1 + subbands::LVL_NEXT;
const sz_t final_lvl = _wtree.lvls();
// цикл по уровням
for (sz_t lvl = first_lvl; final_lvl >= lvl; ++lvl)
{
_encode_wtree_level(lvl, decode_mode);
}
#ifdef LIBWIC_USE_DBG_SURFACE
// запись отладочной поверхности в файл
if (!decode_mode)
{
_dbg_enc_surface.save<wicdbg::dbg_pixel::member_wc>
("dumps/[encoder]dbg_enc_suface.wc.bmp", true);
_dbg_enc_surface.save<wicdbg::dbg_pixel::member_wc>
("dumps/[encoder]dbg_enc_suface.wc.txt", false);
_dbg_enc_surface.save<wicdbg::dbg_pixel::member_wc_model>
("dumps/[encoder]dbg_enc_suface.wc_model.bmp", true);
_dbg_enc_surface.save<wicdbg::dbg_pixel::member_n>
("dumps/[encoder]dbg_enc_suface.n.bmp", true);
_dbg_opt_surface.diff<wicdbg::dbg_pixel::member_wc_model>
(_dbg_enc_surface, "dumps/[encoder]dbg_suface.wc_model.diff");
}
else
{
_dbg_dec_surface.save<wicdbg::dbg_pixel::member_wc>
("dumps/[decoder]dbg_dec_suface.wc.bmp", true);
_dbg_dec_surface.save<wicdbg::dbg_pixel::member_wc>
("dumps/[decoder]dbg_dec_suface.wc.txt", false);
_dbg_dec_surface.save<wicdbg::dbg_pixel::member_wc_model>
("dumps/[decoder]dbg_dec_suface.wc_model.bmp", true);
_dbg_dec_surface.save<wicdbg::dbg_pixel::member_n>
("dumps/[decoder]dbg_dec_suface.n.bmp", true);
}
#endif
}
/*! \param[in] root Координаты корневого элемента рассматриваемого дерева
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
На первом шаге кодирования выполняется корректировка коэффициентов
на самом последнем (с наибольшей площадью) уровне разложения и
последующий расчёт <i>RD-функций Лагранжа</i> для вариантов сохранения
и подрезания оконечных листьев дерева.
*/
void encoder::_optimize_tree_step_1(const p_t &root, const lambda_t &lambda)
{
// просматриваются все узлы предпоследнего уровня
const sz_t lvl_i = _wtree.sb().lvls() + subbands::LVL_PREV;
const sz_t lvl_j = _wtree.sb().lvls();
// цикл по саббендам
for (sz_t k = 0; subbands::SUBBANDS_ON_LEVEL > k; ++k)
{
const subbands::subband_t &sb_i = _wtree.sb().get(lvl_i, k);
const subbands::subband_t &sb_j = _wtree.sb().get(lvl_j, k);
// цикл по элементам из предпоследнего уровня дерева
for (wtree::coefs_iterator i = _wtree.iterator_over_leafs(root, sb_i);
!i->end(); i->next())
{
// родительский элемент из предпоследнего уровня
const p_t &p = i->get();
// Шаг 1.1. Корректировка проквантованных коэффициентов
_coefs_fix(p, sb_j, lambda);
// Шаг 1.2. Расчет RD-функций Лагранжа для вариантов сохранения и
// подрезания листьев
_prepare_j(p, sb_j, lambda);
}
}
}
/*! \param[in] root Координаты корневого элемента дерева
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
*/
void encoder::_optimize_tree_step_2(const p_t &root, const lambda_t &lambda)
{
// Шаги 2.1 - 2.5 ----------------------------------------------------------
// цикл по уровням
for (sz_t lvl_i = _wtree.sb().lvls() + 2*subbands::LVL_PREV;
0 < lvl_i; --lvl_i)
{
const sz_t lvl_j = lvl_i + subbands::LVL_NEXT;
// цикл по саббендам
for (sz_t k = 0; subbands::SUBBANDS_ON_LEVEL > k; ++k) {
// получение ссылок на саббенды
const subbands::subband_t &sb_i = _wtree.sb().get(lvl_i, k);
const subbands::subband_t &sb_j = _wtree.sb().get(lvl_j, k);
// цикл по родительским элементам
for (wtree::coefs_iterator i =
_wtree.iterator_over_leafs(root, sb_i);
!i->end(); i->next())
{
const p_t &p = i->get();
// Шаг 2.1. Определение оптимальной топологии ветвей
const _branch_topology_t optim_topology =
_optimize_branch_topology(p, sb_i, lambda);
// Шаг 2.2. Изменение топологии дерева
_wtree.cut_leafs<wnode::member_wc>(p, optim_topology.n);
// Шаг 2.3. Корректировка проквантованных коэффициентов
_coefs_fix(p, sb_j, lambda);
// Шаг 2.4. Подготовка для просмотра следующего уровня
_prepare_j(p, sb_j, optim_topology.j, lambda);
}
}
// на всякий случай, если какой-нить фрик сделает sz_t беззнаковым
// типом :^)
// if (0 == lvl) break;
}
}
/*! \param[in] root Координаты корневого элемента дерева
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
*/
void encoder::_optimize_tree_step_3(const p_t &root, const lambda_t &lambda)
{
const subbands::subband_t &sb_LL = _wtree.sb().get_LL();
// Шаг 2.6. Определение оптимальной топологии ветвей
const _branch_topology_t optim_topology =
_optimize_branch_topology(root, sb_LL, lambda);
// Шаг 2.7. Изменение топологии дерева
_wtree.cut_leafs<wnode::member_wc>(root, optim_topology.n);
// шаг 3. Вычисление RD-функции Лагранжа для всего дерева
_calc_jx_value(root, optim_topology.j, lambda);
}
/*! \param[in] root Координаты корневого элемента дерева
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\return Значение <i>RD-функций Лагранжа</i> для дерева
Для корректной работы функции необходимо, чтобы в дереве все ветви
были отмечены как подрезанные, а элементы как корректные. Значения
функций <i>Лагранжа</i> в спектре должны быть обнулены. Арифметический
кодер должен быть настроен на корректные модели (смотри acoder::use()).
\note Необходимую подготовку выполняет функция wnode::filling_refresh(),
при условии, что поля wnode::w и wnode::wq корректны.
*/
j_t encoder::_optimize_tree(const p_t &root, const lambda_t &lambda)
{
_optimize_tree_step_1(root, lambda);
_optimize_tree_step_2(root, lambda);
_optimize_tree_step_3(root, lambda);
const j_t j = _wtree.at(root).j1;
if (0 != _optimize_tree_callback)
{
_optimize_tree_callback(root, _optimize_tree_callback_param);
}
return j;
}
/*! \param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\param[in] refresh_wtree Если <i>true</i>, то перед началом кодирования
будет вызвана функция wtree::filling_refresh(), которая сбросит спекрт
в начальное состояние. Используется при выполнении нескольких операций
оптимизации над одним спектром (например, в целях подбора оптимального
значение параметра <i>lambda</i>).
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток). При включённом виртуальном
кодировании, поле _optimize_result_t::bpp выставляется в 0, так как
без проведения реального кодирование невозможно оценить битовые
затраты.
\param[in] precise_bpp Если <i>true</i>, то после этапа оптимизации
будет проведён этап уточнения битовых затрат, заключающийся в том, что
модели арифметического кодера будут уменьшены функцией
_setup_acoder_post_models(), а затем будет произведено реальное
кодирование всех деревьев спектра (с оптимизированной топологией).
См. функцию _real_encode_tight() для дополнительной информации. Стоит
очень осторожно относиться к этому параметру, так как при выставлении
его в <i>true</i> модели арифметического кодера изменяются, что
затрудняет использование этой функции в процедурах подбора параметров
кодирования. Однако, также есть и приемущества. Если параметр выставлен
в <i>true</i>, то после проведённой оптимизации можно не производить
реальное кодирование, так как оно уже сделано (о чем будет указывать
поле результата optimize_result_t::real_encoded).
\return Результат проведённой оптимизации
Для корректной работы этой функции необходимо, чтобы поля wnode::w и
wnode::wq элементов спектра были корректны. В спектре все ветви должны
быть отмечены как подрезанные, а элементы как корректные. Значения
функций <i>Лагранжа</i> в спектре должны быть обнулены. Арифметический
кодер должен быть настроен на корректные модели (смотри acoder::use()).
\note Необходимую подготовку выполняет функция wtree::filling_refresh(),
при условии, что поля wnode::w и wnode::wq корректны.
\note Если определён макрос #LIBWIC_DEBUG, функция будет выводить
специальную отладочную информацию.
*/
encoder::optimize_result_t
encoder::_optimize_wtree(const lambda_t &lambda,
const bool refresh_wtree,
const bool virtual_encode,
const bool precise_bpp)
{
// Инициализация возвращаемого результата
optimize_result_t result;
result.q = _wtree.q();
result.lambda = lambda;
result.j = 0;
result.bpp = 0;
result.models.version = MODELS_DESC_NONE;
result.real_encoded = false;
// Обновление дерева вейвлет коэффициентов (если требуется)
if (refresh_wtree) _wtree.filling_refresh();
#ifdef LIBWIC_USE_DBG_SURFACE
// Очистка отладочной поверхности
_dbg_opt_surface.clear();
#endif
// Оптимизация топологии ветвей с кодированием
_acoder.encode_start();
for (wtree::coefs_iterator i =
_wtree.iterator_over_subband(_wtree.sb().get_LL());
!i->end(); i->next())
{
// корень очередного дерева коэффициентов вейвлет преобразования
const p_t &root = i->get();
// оптимизация топологии отдельной ветви
result.j += _optimize_tree(root, lambda);
// кодирование отдельной ветви
_encode_tree(root, virtual_encode);
}
_acoder.encode_stop();
#ifdef LIBWIC_USE_DBG_SURFACE
// Сохранение полей отладочной поверхности в файлы
_dbg_opt_surface.save<wicdbg::dbg_pixel::member_wc>
("dumps/[encoder]dbg_opt_suface.wc.bmp", true);
_dbg_opt_surface.save<wicdbg::dbg_pixel::member_wc_model>
("dumps/[encoder]dbg_opt_suface.wc_model.bmp", true);
_dbg_opt_surface.save<wicdbg::dbg_pixel::member_n>
("dumps/[encoder]dbg_opt_suface.n.bmp", true);
#endif
// подсчёт bpp, если производилось реальное кодирование
if (precise_bpp)
{
result.bpp = _real_encode_tight(result.models);
result.real_encoded = true;
}
else if (!virtual_encode)
{
result.bpp = _calc_encoded_bpp();
}
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "[OWTR]:";
_dbg_out_stream << " q: " << std::setw(8) << _wtree.q();
_dbg_out_stream << " lambda: " << std::setw(8) << lambda;
_dbg_out_stream << " j: " << std::setw(8) << result.j;
_dbg_out_stream << " bpp: " << std::setw(8) << result.bpp;
_dbg_out_stream << std::endl;
}
#endif
// обратный вызов пользовательской функции
if (0 != _optimize_callback)
{
_optimize_callback(result, _optimize_callback_param);
}
// возврат результата
return result;
}
/*! \param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\param[in] models Описание моделей арифметического кодера, которые
необходимо использовать для проведения оптимизации
\param[in] refresh_wtree Если <i>true</i>, то перед началом кодирования
будет вызвана функция wtree::filling_refresh(), которая сбросит спекрт
в начальное состояние. Используется при выполнении нескольких операций
оптимизации над одним спектром (например, в целях подбора оптимального
значение параметра <i>lambda</i>).
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток). При включённом виртуальном
кодировании, поле _optimize_result_t::bpp выставляется в 0, так как
без проведения реального кодирование невозможно оценить битовые
затраты.
\param[in] precise_bpp Если <i>true</i>, то после этапа оптимизации
будет проведён этап уточнения битовых затрат, заключающийся в том, что
модели арифметического кодера будут уменьшены функцией
_setup_acoder_post_models(), а затем будет произведено реальное
кодирование всех деревьев спектра (с оптимизированной топологией).
См. функцию _real_encode_tight() для дополнительной информации. Стоит
очень осторожно относиться к этому параметру, так как при выставлении
его в <i>true</i> модели арифметического кодера изменяются, что
затрудняет использование этой функции в процедурах подбора параметров
кодирования. Однако, также есть и приемущества. Если параметр выставлен
в <i>true</i>, то после проведённой оптимизации можно не производить
реальное кодирование, так как оно уже сделано (о чем будет указывать
поле результата optimize_result_t::real_encoded).
\sa _optimize_wtree()
*/
encoder::optimize_result_t
encoder::_optimize_wtree_m(const lambda_t &lambda,
const models_desc_t &models,
const bool refresh_wtree,
const bool virtual_encode,
const bool precise_bpp)
{
// Установка моделей арифметического кодера
_acoder.use(_mk_acoder_models(models));
// проведение оптимизации топологии
return _optimize_wtree(lambda, refresh_wtree, virtual_encode, precise_bpp);
}
/*! \param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\param[in] q Квантователь
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
\param[in] precise_bpp Если <i>true</i>, будет произведено уточнение
битовых затрат путем проведения реального кодирования с ужатыми
моделями арифметического кодера (см. _real_encode_tight). В этом случае,
после этапа оптимизации нет нужды производить реальное кодирование, так
как оно уже произведено функцией _real_encode_tight. Однако следует
обратить внимание, что текущие модели арифметического кодера после
выполнения функции изменяются.
\return Результат проведённой оптимизации
Эта версия функции <i>%encoder::_optimize_wtree()</i> сама производит
квантование и настройку моделей арифметического кодера. Для корректной
работы функции достаточно загруженных коэффициентов в поле wnode::w
элементов спектра.
*/
encoder::optimize_result_t
encoder::_optimize_wtree_q(const lambda_t &lambda, const q_t &q,
const bool virtual_encode,
const bool precise_bpp)
{
// квантование коэффициентов
_wtree.quantize(q);
// загрузка моделей в арифметический кодер
const models_desc_t models = _setup_acoder_models(false);
// оптимизация топологии ветвей
optimize_result_t result = _optimize_wtree_m(lambda, models, false,
virtual_encode, precise_bpp);
// Сохранение описания моделей арифметического кодера
if (MODELS_DESC_NONE == result.models.version)
{
result.models = models;
}
// возврат результата
return result;
}
/*! \param[in] lambda Параметр <i>lambda</i> используемый для вычисления
<i>RD критерия</i> (<i>функции Лагранжа</i>). Представляет собой баланс
между ошибкой и битовыми затратами. Меньшие значения <i>lambda</i>
соответствуют большему значению результиру<i>bpp</i>.
\param[in] q_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] q_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] q_eps Необходимая погрешность определения квантователя
<i>q</i> при котором значение <i>RD функции Лагранжа</i> минимально
(при фиксированном параметре <i>lambda</i>).
\param[in] j_eps Необходимая погрешность нахождения минимума <i>RD
функции Лагранжа</i>. Так как абсолютная величина функции <i>J</i>
зависит от многих факторов (таких как размер изображения, его тип,
величины параметра <i>lambda</i>), использовать это параметр
затруднительно. Поэтому его значение по умолчанию равно <i>0</i>,
чтобы при поиске оптимального квантователя учитывалась только
погрешность параметра <i>q</i>.
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток). Виртуальное кодирование немного
быстрее, но его использование делает невозможным определение средних
битовых затрат на кодирование одного пиксела изображения.
\param[in] max_iterations Максимальное количество итераций нахождения
минимума <i>RD функции Лагранжа</i>. Если это значение равно <i>0</i>,
количество выполняемых итераций не ограничено.
\param[in] precise_bpp Если <i>true</i>, при выполнении операции
оптимизации топологии будет производиться уточнение битовых затрат путем
проведения реального кодирования с ужатыми моделями арифметического кодера
(см. _real_encode_tight). В этом случае, после этапа оптимизации нет нужды
производить реальное кодирование, так как оно уже произведено функцией
_real_encode_tight.
\return Результат произведённого поиска
Данная функция использует метод золотого сечения для поиска минимума
<i>RD функции Лагранжа</i>:
\verbatim
j|___ ______/
| \_ __/ |
| \___ / |
| | \____ / |
| | | \___ ______/ |
| | | \_/ | |
| | | | | |
---+-------+---+-------+------+---------+----------> q
0| a b j_min c d
\endverbatim
\note Для корректной работы этой функции необходимо, чтобы поле
wnode::w элементов спектра было корректно. Для этого
можно использовать функцию wtree::load_field().
\note Если определён макрос #LIBWIC_DEBUG, функция будет выводить
специальную отладочную информацию.
*/
encoder::optimize_result_t
encoder::_search_q_min_j(const lambda_t &lambda,
const q_t &q_min, const q_t &q_max,
const q_t &q_eps, const j_t &j_eps,
const bool virtual_encode,
const sz_t &max_iterations,
const bool precise_bpp)
{
// проверка утверждений
assert(0 <= lambda);
assert(1 <= q_min && q_min <= q_max);
assert(0 <= q_eps && 0 <= j_eps);
// коэффициенты золотого сечения
static const q_t factor_b = (q_t(3) - sqrt(q_t(5))) / q_t(2);
static const q_t factor_c = (sqrt(q_t(5)) - q_t(1)) / q_t(2);
// установка диапазона для поиска
q_t q_a = q_min;
q_t q_d = q_max;
// вычисление значений в первых двух точках
q_t q_b = q_a + factor_b * (q_d - q_a);
q_t q_c = q_a + factor_c * (q_d - q_a);
optimize_result_t result_b = _optimize_wtree_q(lambda, q_b, virtual_encode,
precise_bpp);
optimize_result_t result_c = _optimize_wtree_q(lambda, q_c, virtual_encode,
precise_bpp);
// запоминание предыдущего и последнего результатов
optimize_result_t result_prev = result_b;
optimize_result_t result = result_c;
// подсчёт количества итераций
sz_t iterations = 0;
// поиск оптимального значения q
for (;;)
{
// проверка, достигнута ли нужная точность
if (q_eps >= abs(q_c - q_b) ||
j_eps >= abs(result.j - result_prev.j))
{
break;
}
if (0 < max_iterations && max_iterations <= iterations)
{
break;
}
// скоро будет получен новый результат
result_prev = result;
// выбор очередного значения q
if (result_b.j < result_c.j)
{
q_d = q_c;
q_c = q_b;
q_b = q_a + factor_b*(q_d - q_a);
result_c = result_b;
result = result_b = _optimize_wtree_q(lambda, q_b, virtual_encode,
precise_bpp);
}
else
{
q_a = q_b;
q_b = q_c;
q_c = q_a + factor_c*(q_d - q_a);
result_b = result_c;
result = result_c = _optimize_wtree_q(lambda, q_c, virtual_encode,
precise_bpp);
}
// увеличение количества итераций
++iterations;
}
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "[SQMJ]:";
_dbg_out_stream << " q: " << std::setw(8) << result.q;
_dbg_out_stream << " lambda: " << std::setw(8) << result.lambda;
_dbg_out_stream << " j: " << std::setw(8) << result.j;
_dbg_out_stream << " bpp: " << std::setw(8) << result.bpp;
_dbg_out_stream << std::endl;
}
#endif
// возвращение полученного результата
return result;
}
/*! \param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будет подбираться параметр <i>lambda</i>
\param[in] bpp_eps Необходимая точность, c которой <i>bpp</i> полученный
в результате поиска параметра <i>lambda</i> будет соответствовать
заданному.
\param[in] lambda_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] lambda_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] lambda_eps Точность, с которой будет подбираться параметр
<i>lambda</i>.
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
\param[in] max_iterations Максимальное количество итераций нахождения
минимума <i>RD функции Лагранжа</i>. Если это значение равно <i>0</i>,
количество выполняемых итераций не ограничено.
\param[in] precise_bpp Если <i>true</i>, при выполнении операции
оптимизации топологии будет производиться уточнение битовых затрат путем
проведения реального кодирования с ужатыми моделями арифметического кодера
(см. _real_encode_tight). В этом случае, после этапа оптимизации нет нужды
производить реальное кодирование, так как оно уже произведено функцией
_real_encode_tight.
\return Результат проведённого поиска. Возможна ситуация, когда нужная
<i>lambda</i> лежит вне указанного диапазона. В этом случае, функция
подберёт такую <i>lambda</i>, которая максимально удовлетворяет условиям
поиска.
Поиск оптимального значения <i>lambda</i> производится дихотомией
(методом половинного деления). Поиск будет считаться успешным, если
найдено такое значение <i>lambda</i>, при котором полученный <i>bpp</i>
меньше чем на <i>bpp_eps</i> отличается от заданного <i>или</i> в
процессе поиска диапазон значений <i>lambda</i> сузился до
<i>lambda_eps</i>.
Меньшие значения <i>lambda</i> соответствуют большему
значению <i>bpp</i>:
\verbatim
|_____
| \________
| | \_________
bpp+-------+----------------\-----------------------
| | \_______
| | | \______________
---+-------+-------------------+--------------------
0| lambda_min lambda_max
\endverbatim
\note Для корректной работы этой функции необходимо, чтобы поля
wnode::w и wnode::wq элементов спектра были корректны. Для этого
можно использовать функцию wtree::cheap_load(). Также очень важно,
чтобы модели арифметического кодера были хорошо настроены (а их
начальные характеристика запомнены). Для этого можно воспользоваться
кодом следующего вида:
\code
// описание моделей, которое будет использовано в дальнейшем при
// декодировании
models_desc_t models;
// создание описания моделей исходя из характеристик спектра
models = _mk_acoder_smart_models();
// конвертация описания моделей в формат приемлемый для арифметического
// кодера и предписание ему начать использовать полученные модели для
// кодирования или декодирования
_acoder.use(_mk_acoder_models(models));
\endcode
\note Если определён макрос #LIBWIC_DEBUG, функция будет выводить
специальную отладочную информацию.
*/
encoder::optimize_result_t
encoder::_search_lambda_at_bpp(
const h_t &bpp, const h_t &bpp_eps,
const lambda_t &lambda_min,
const lambda_t &lambda_max,
const lambda_t &lambda_eps,
const bool virtual_encode,
const sz_t &max_iterations,
const bool precise_bpp)
{
// проверка утверждений
assert(0 < bpp);
assert(0 <= lambda_min && lambda_min <= lambda_max);
assert(0 <= bpp_eps && 0 <= lambda_eps);
// установка диапазона для поиска
lambda_t lambda_a = lambda_min;
lambda_t lambda_b = lambda_max;
// Запоминание текущих моделей арифметического кодера
const acoder::models_t original_models = _acoder.models();
// результат последней оптимизации
optimize_result_t result;
result.q = 0;
result.lambda = 0;
result.j = 0;
result.bpp = 0;
result.real_encoded = false;
// счётчик итераций
sz_t iterations = 0;
// небольшая хитрость, позволяющая использовать удобный оператор
// break
do
{
// вычисление значений bpp на левой границе диапазона. Тут нет нужды
// использовать функцию _optimize_wtree_m() так как модели
// арифметического кодера ещё не испорчены
optimize_result_t result_a = _optimize_wtree(lambda_a, true,
virtual_encode,
precise_bpp);
// проверка на допустимость входного диапазона
if (result_a.bpp <= (bpp + bpp_eps))
{
result = result_a;
break;
}
// восстановление моделей арифметического кодера, если они были
// изменены функцией оптимизации топологии
_restore_spoiled_models(result_a, original_models);
// вычисление значений bpp на правой границе диапазона
optimize_result_t result_b = _optimize_wtree(lambda_b, true,
virtual_encode,
precise_bpp);
// проверка на допустимость входного диапазона
if (result_b.bpp >= (bpp - bpp_eps))
{
result = result_b;
break;
}
// Внимание: здесь переменная result не обязательно инициализированна,
// но даже будучи инициализированной она не пригодна для возврата
// в качестве результата так как может отражать результат предыдущей
// оптимизации, а не последней!!!
// Ввиду выше описанного нет ничего повинного в следующей строчке,
// которая нужна чтобы упростить дальнейшую логику восстановления
// моделей арифметического кодера, для которой необходимо, чтобы в
// переменной result был результат последней проведённой оптимизации
result = result_b;
// поиск оптимального значения lamda (дихотомия)
for (;;)
{
// подсчёт значения bpp для середины диапазона
const lambda_t lambda_c = (lambda_b + lambda_a) / 2;
// восстановление моделей арифметического кодера, если они были
// изменены функцией оптимизации топологии
_restore_spoiled_models(result, original_models);
// оптимизация топологии ветвей
result = _optimize_wtree(lambda_c, true, virtual_encode,
precise_bpp);
// проверить, достигнута ли нужная точность по bpp
if (bpp_eps >= abs(result.bpp - bpp)) break;
// проверить, не превышен ли лимит по итерациям
if (0 < max_iterations && max_iterations <= iterations) break;
// сужение диапазона поиска
if (bpp > result.bpp)
lambda_b = lambda_c;
else
lambda_a = lambda_c;
// проверить, достигнута ли нужная точность по lambda
if (lambda_eps >= abs(lambda_b - lambda_a)) break;
// Увеличение счётчика итераций
++iterations;
}
}
while (false);
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "[SLAB]: ";
_dbg_out_stream << "q: " << std::setw(8) << result.q;
_dbg_out_stream << " lambda: " << std::setw(8) << result.lambda;
_dbg_out_stream << " j: " << std::setw(8) << result.j;
_dbg_out_stream << " bpp: " << std::setw(8) << result.bpp;
_dbg_out_stream << std::endl;
}
#endif
// возвращение полученного результата
return result;
}
/*! \param[in] q Квантователь, который будет использован для квантования
спектра вейвлет коэффициентов
\param[in] bpp Целевые битовые затраты на кодирование изображения. При
поиске параметра <i>lambda</i> функцией _search_lambda_at_bpp() будет
использовано это значение в качестве соответствующего аргумента.
\param[in] bpp_eps Допустимая погрешность достижения заданных битовых
затрат. При поиске параметра <i>lambda</i> функцией _search_lambda_at_bpp()
будет использовано это значение в качестве соответствующего аргумента.
\param[in] lambda_eps Точность, с которой будет подбираться параметр
<i>lambda</i>
\param[out] models Описание моделей арифметического кодера, которое
необходимо для последующего декодирования изображения
\param[out] d Среднеквадратичное отклонение оптимизированного спектра
от исходного. Играет роль ошибки, вносимой алгоритмом сжатия.
\param[out] deviation Отклонение от заданного <i>bpp</i>. Если
результирующий <i>bpp</i> находится в пределах погрешности <i>bpp_eps</i>
этот аргумент выставляется в <i>0</i>. Иначе аргумент выставляется в
значение разности между желаемым <i>bpp</i> и полученным в процессе поиска
параметра <i>lambda</i>. Таким образом, получение отрицательных значений
аргумента означает, что полученный <i>bpp</i> больше желаемого и параметр
<i>q</i> необходимо увеличить (или поднять верхнию границу диапазона
поиска параметра <i>lambda</i>). Если же агрумент получит положительное
значение, то параметр <i>q</i> необходимо уменьшить (или опустить нижнию
границу диапазона поиска параметра <i>lambda</i>).
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток). Виртуальное кодирование немного
быстрее, но его использование делает невозможным определение средних
битовых затрат на кодирование одного пиксела изображения.
\param[in] max_iterations Максимальное количество итераций, выполняемых
функцией _search_lambda_at_bpp()
\param[in] precise_bpp Если <i>true</i>, при выполнении операции
оптимизации топологии будет производиться уточнение битовых затрат путем
проведения реального кодирования с ужатыми моделями арифметического кодера
(см. _real_encode_tight). В этом случае, после этапа оптимизации нет нужды
производить реальное кодирование, так как оно уже произведено функцией
_real_encode_tight.
\return Результат произведённого поиска
Параметр <i>lambda</i> будет искаться в диапазоне
<i>[LAMBDA_SEARCH_K_LOW*q*q, LAMBDA_SEARCH_K_HIGHT*q*q]</i>.
\note Для корректной работы, функции необходимо, чтобы значения полей
wnode::w были корректны (содержали в себе коэффициенты исходного спектра).
\sa _search_lambda_at_bpp(), _search_q_lambda_for_bpp()
*/
encoder::optimize_result_t
encoder::_search_q_lambda_for_bpp_iter(
const q_t &q, const h_t &bpp,
const h_t &bpp_eps, const lambda_t &lambda_eps,
models_desc_t &models, w_t &d, h_t &deviation,
const bool virtual_encode,
const sz_t &max_iterations,
const bool precise_bpp)
{
// квантование спектра
_wtree.quantize(q);
// определение характеристик моделей арифметического кодера
models = _setup_acoder_models();
// выбор диапазона поиска параметра lambda
const lambda_t lambda_min = lambda_t(LAMBDA_SEARCH_K_LOW * q*q);
const lambda_t lambda_max = lambda_t(LAMBDA_SEARCH_K_HIGHT * q*q);
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "[SQLI]: ";
_dbg_out_stream << "q: " << std::setw(8) << q;
_dbg_out_stream << " lambda_min: " << std::setw(8) << lambda_min;
_dbg_out_stream << " lambda_max: " << std::setw(8) << lambda_max;
_dbg_out_stream << std::endl;
}
#endif
// поиск параметра lambda
const optimize_result_t result =
_search_lambda_at_bpp(bpp, bpp_eps,
lambda_min, lambda_max, lambda_eps,
virtual_encode, max_iterations,
precise_bpp);
// подсчёт среднеквадратичного отклонения (ошибки)
d = _wtree.distortion_wc<w_t>();
// установка параметра отклонения
if (result.bpp > bpp + bpp_eps)
deviation = (bpp - result.bpp); // q необходимо увеличить (-1)
else if (result.bpp < bpp - bpp_eps)
deviation = (bpp - result.bpp); // q необходимо уменьшить (+1)
else
deviation = 0; // q удовлетворительное
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "[SQLI]: ";
_dbg_out_stream << "q: " << std::setw(8) << result.q;
_dbg_out_stream << " lambda: " << std::setw(8) << result.lambda;
_dbg_out_stream << " j: " << std::setw(8) << result.j;
_dbg_out_stream << " bpp: " << std::setw(8) << result.bpp;
_dbg_out_stream << " d: " << std::setw(8) << d;
_dbg_out_stream << " deviation: " << std::setw(8) << deviation;
_dbg_out_stream << std::endl;
}
#endif
// возврат результата
return result;
}
/*! \param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будут подбираться параметры <i>q</i> и <i>lambda</i>.
\param[in] bpp_eps Необходимая точность, c которой <i>bpp</i> полученный
в результате поиска параметров <i>q</i> и <i>lambda</i> будет
соответствовать заданному.
\param[in] q_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] q_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] q_eps Необходимая погрешность определения квантователя
<i>q</i> при котором значение <i>RD функции Лагранжа</i> минимально
(при фиксированном параметре <i>lambda</i>).
\param[in] lambda_eps Точность, с которой будет подбираться параметр
<i>lambda</i>
\param[out] models Описание моделей арифметического кодера, которое
необходимо для последующего декодирования изображения
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток). Виртуальное кодирование немного
быстрее, но его использование делает невозможным определение средних
битовых затрат на кодирование одного пиксела изображения.
\param[in] precise_bpp Если <i>true</i>, при выполнении операции
оптимизации топологии будет производиться уточнение битовых затрат путем
проведения реального кодирования с ужатыми моделями арифметического кодера
(см. _real_encode_tight). В этом случае, после этапа оптимизации нет нужды
производить реальное кодирование, так как оно уже произведено функцией
_real_encode_tight.
Функция использует метод золотого сечения для подбора параметра <i>q</i>,
а для подбора параметра <i>lambda</i> использует функцию
_search_q_lambda_for_bpp_iter().
\sa _search_q_lambda_for_bpp_iter(), _search_q_lambda_for_bpp()
*/
encoder::optimize_result_t
encoder::_search_q_lambda_for_bpp(
const h_t &bpp, const h_t &bpp_eps,
const q_t &q_min, const q_t &q_max,
const q_t &q_eps, const lambda_t &lambda_eps,
models_desc_t &models,
const bool virtual_encode,
const bool precise_bpp)
{
// максимальное количество итераций для подбора параметра lambda
static const sz_t max_iterations = 0;
// коэффициенты золотого сечения
static const q_t factor_b = q_t((3.0 - sqrt(5.0)) / 2.0);
static const q_t factor_c = q_t((sqrt(5.0) - 1.0) / 2.0);
// верхняя и нижняя граница поиска параметра q
q_t q_a = q_min;
q_t q_d = q_max;
// вычисление значений в первых двух точках
q_t q_b = q_a + factor_b * (q_d - q_a);
q_t q_c = q_a + factor_c * (q_d - q_a);
// подбор параметра lambda в первой точке
w_t dw_b = 0;
h_t deviation_b = 0;
optimize_result_t result_b =
_search_q_lambda_for_bpp_iter(
q_b, bpp, bpp_eps, lambda_eps, models,
dw_b, deviation_b, virtual_encode,
max_iterations, precise_bpp);
// подбор параметра lambda во второй точке
w_t dw_c = 0;
h_t deviation_c = 0;
optimize_result_t result_c =
_search_q_lambda_for_bpp_iter(
q_c, bpp, bpp_eps, lambda_eps, models,
dw_c, deviation_c, virtual_encode,
max_iterations, precise_bpp);
// результаты последнего поиска параметра lambda
h_t deviation = deviation_c;
optimize_result_t result = result_c;
// сужение диапазона поиска методом золотого сечения
while (q_eps < abs(q_a - q_d))
{
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "> ";
_dbg_out_stream << " q_a=" << std::setw(8) << q_a;
_dbg_out_stream << " q_b=" << std::setw(8) << q_b;
_dbg_out_stream << " q_c=" << std::setw(8) << q_c;
_dbg_out_stream << " q_d=" << std::setw(8) << q_d;
_dbg_out_stream << " dev=" << std::setw(8) << deviation;
_dbg_out_stream << " dw_b=" << std::setw(8) << dw_b;
_dbg_out_stream << " dw_c=" << std::setw(8) << dw_c;
_dbg_out_stream << std::flush;
}
#endif
// if (0 == deviation) break;
if (deviation > 0 || (0 == deviation && dw_b <= dw_c))
{
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << " way[a] (a * b c d)" << std::endl;
}
#endif
q_d = q_c;
q_c = q_b;
dw_c = dw_b;
q_b = q_a + factor_b * (q_d - q_a);
// a b c d
// a b c d
result = result_b =
_search_q_lambda_for_bpp_iter(
q_b, bpp, bpp_eps, lambda_eps, models,
dw_b, deviation_b, virtual_encode,
max_iterations, precise_bpp);
deviation = deviation_b;
}
else
{
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << " way[b] (a b c * d)" << std::endl;
}
#endif
q_a = q_b;
q_b = q_c;
dw_b = dw_c;
q_c = q_a + factor_c * (q_d - q_a);
// a b c d
// a b c d
result = result_c =
_search_q_lambda_for_bpp_iter(
q_c, bpp, bpp_eps, lambda_eps, models,
dw_c, deviation_b, virtual_encode,
max_iterations, precise_bpp);
deviation = deviation_c;
}
}
return result;
}
/*! \return Средние битовые затраты на кодирование спектра вейвлет
коэффициентов
Данная функция использует текущие настройки моделей арифметического кодера
и не изменяет их.
*/
h_t encoder::_real_encode()
{
#ifdef LIBWIC_USE_DBG_SURFACE
#endif
// кодирование всего дерева
_acoder.encode_start();
_encode_wtree();
_acoder.encode_stop();
// подсчёт и возврат средних битовых затрат
return _calc_encoded_bpp();
}
/*! \param[out] desc Описание моделей арифметического кодера, которые
были использованый при кодировании
\param[in] double_path Если <i>true</i> кодирование будет производится
в два прохода. При первом проходе кодирования производится настройка
моделей. Сейчас нет возможности кодировать в один проход (что быстрее)
так как возможен перескок коэффициентов из одной модели в другую.
Связано это с тем, что на этапе оптимизации нам ещё не известны финальные
значения всех коэффициентов и как следствие значение вычисляемых
прогнозов.
\return Средние битовые затраты на кодирование спектра вейвлет
коэффициентов
\attention Следует очень осторожно использовать эту функцию так как
она изменяет модели, используемые арифметическим кодером.
*/
h_t encoder::_real_encode_tight(models_desc_t &desc, const bool double_path)
{
// двойной проход должен быть включён при текущем положении дел
assert(double_path);
// выполнение первого прохода, если необходимо
if (double_path)
{
_setup_acoder_models();
_real_encode();
}
// Определение и установка моделей арифметического кодера
desc = _setup_acoder_post_models();
return _real_encode();
}
/*! \param[in] including_tunes Если этот параметр равен <i>true</i> в
расчёте <i>bpp</i> будет принят во внимание размер дополнительный данных,
необходимых для восстановления изображения, определённых в структуре
tunes_t
\return Среднее количество бит, затрачиваемых на кодирование одного
пикселя
*/
h_t encoder::_calc_encoded_bpp(const bool including_tunes)
{
const sz_t data_sz = coder().encoded_sz()
+ ((including_tunes)? sizeof(tunes_t): 0);
return h_t(data_sz * BITS_PER_BYTE) / h_t(_wtree.nodes_count());
}
/*!
*/
void encoder::_test_wc_136_0()
{
assert(0 != _wtree.at(136, 0).wc);
}
} // end of namespace wic
| [
"wonder_mice@b1028fda-012f-0410-8370-c1301273da9f"
] | [
[
[
1,
3165
]
]
] |
d75a5c9f2955c4d61704ff87e2b2d893353483f3 | bd89d3607e32d7ebb8898f5e2d3445d524010850 | /adaptationlayer/modematadaptation/modematcontroller_dll/src/csignalindreq.cpp | 4634178471fb45ddedcda4bb61670b5541d1c915 | [] | no_license | wannaphong/symbian-incubation-projects.fcl-modemadaptation | 9b9c61ba714ca8a786db01afda8f5a066420c0db | 0e6894da14b3b096cffe0182cedecc9b6dac7b8d | refs/heads/master | 2021-05-30T05:09:10.980036 | 2010-10-19T10:16:20 | 2010-10-19T10:16:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,401 | cpp | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#include "csignalindreq.h"
#include "modemattrace.h"
#include "modematclientsrv.h"
#include "rmodematcontroller.h"
#include "OstTraceDefinitions.h"
#ifdef OST_TRACE_COMPILER_IN_USE
#include "csignalindreqTraces.h"
#endif
CSignalIndReq::CSignalIndReq(
RModemAtController* aClient) :
CActive(EPriorityNormal),
iClient(aClient)
{
OstTrace1( TRACE_NORMAL, CSIGNALINDREQ_CSIGNALINDREQ, "CSignalIndReq::CSignalIndReq;aClient=%x", aClient );
C_TRACE((_L("CSignalIndReq::CSignalIndReq(0x%x)"), aClient));
CActiveScheduler::Add( this );
aClient->SendReceiveSignalInd( iStatus );
SetActive();
}
CSignalIndReq::~CSignalIndReq()
{
OstTrace0( TRACE_NORMAL, DUP1_CSIGNALINDREQ_CSIGNALINDREQ, "CSignalIndReq::~CSignalIndReq" );
C_TRACE((_L("CSignalIndReq::~CSignalIndReq()")));
Cancel();
}
void CSignalIndReq::DoCancel()
{
OstTrace0( TRACE_NORMAL, CSIGNALINDREQ_DOCANCEL, "CSignalIndReq::DoCancel" );
C_TRACE((_L("CSignalIndReq::DoCancel()")));
iClient->SendReceiveSignalIndCancel();
}
void CSignalIndReq::RunL()
{
OstTrace0( TRACE_NORMAL, CSIGNALINDREQ_RUNL, "CSignalIndReq::RunL" );
C_TRACE((_L("CSignalIndReq::RunL()")));
if( iStatus.Int() == KErrNone || iStatus.Int() > 0 )
{
OstTrace1( TRACE_NORMAL, DUP1_CSIGNALINDREQ_RUNL, "CSignalIndReq::RunL - Completing with;iStatus.Int()=%d", iStatus.Int() );
C_TRACE((_L("Completing with %d"), iStatus.Int()));
iClient->SignalIndReceived( iStatus.Int() );
iClient->SendReceiveSignalInd( iStatus );
SetActive();
}
else
{
OstTrace1( TRACE_NORMAL, DUP2_CSIGNALINDREQ_RUNL, "CSignalIndReq::RunL - delete;iStatus.Int()=%d", iStatus.Int() );
C_TRACE((_L("CSignalIndReq RunL delete %d"), iStatus.Int()));
delete this;
}
}
| [
"dalarub@localhost",
"mikaruus@localhost"
] | [
[
[
1,
23
],
[
28,
33
],
[
35,
42
],
[
44,
49
],
[
51,
56
],
[
58,
58
],
[
60,
60
],
[
63,
66
],
[
68,
68
],
[
70,
73
]
],
[
[
24,
27
],
[
34,
34
],
[
43,
43
],
[
50,
50
],
[
57,
57
],
[
59,
59
],
[
61,
62
],
[
67,
67
],
[
69,
69
]
]
] |
271476d2fa0b101c8169f7470ce49ab3a26765ad | 7202223bb84abe3f0e4fec236e0b7530ce07bb0a | /astprint.cxx | 6916559f5a85dc2547a644377a1bebcc60b6b843 | [
"BSD-2-Clause"
] | permissive | wilx/c2pas | ec75c57284a1f2a8dbf9b555bdd087f9025daf0c | 3d4b9e4bd187e5b12cec0afc368168aca634ac4a | refs/heads/master | 2021-01-10T02:17:34.798401 | 2007-10-17T22:14:30 | 2007-10-17T22:14:30 | 36,983,834 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,038 | cxx | /*
Copyright (c) 1997-2007, Václav Haisman
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <list>
#include <algorithm>
#include <cctype>
#include <stdlib.h>
#include <sstream>
#include <iostream>
#include "astprint.hxx"
#include "join.hxx"
#include "switch.hxx"
static std::list<int> blocklist;
static int blocks;
static std::list<int> blockstack;
std::map<std::string, ASTInfo *> pidents;
std::list<const CDecl *> decls;
std::list<const CBinOp *> initlist;
//std::list<std::string, IdentInfo *> allidents;
std::list<std::string> labels;
IdentInfo::IdentInfo (CTypeSpec * td, const std::string & n)
: tspec(td), name(n)
{ }
ASTInfo::ASTInfo(const ASTInfo * p, int b, const CStatement * s)
: parent((ASTInfo *)p), block(b), astmt((CStatement *)s)
{
idents = new std::map<std::string, IdentInfo *>();
}
ASTInfo::ASTInfo(const CStatement * s, const ASTInfo * ai)
: parent((ASTInfo *)ai->parent), block(ai->block),
idents(ai->idents), astmt((CStatement *)s)
{ }
LabelInfo::LabelInfo (const CStatement * s, const std::string & n)
: stmt(s), name(n)
{ }
static inline
char
mytolower (char ch)
{
return std::tolower(ch);
}
std::string
strtolower (const std::string & s)
{
std::string ls(s.size(), ' ');
std::transform(s.begin(), s.end(), ls.begin(), mytolower);
return ls;
}
/*std::string escident (const std::string & s)
{
std::ostringstream es;
for (std::string::const_iterator i = s.begin();
i != s.end();
++i) {
if (std::isupper(*i) || *i == '_')
es << '_';
es << *i;
}
return es.str();
}*/
std::pair<std::string, ASTInfo *>
findident (const std::string & id, const ASTInfo * ai, bool clrlist = true)
{
if (clrlist)
blocklist.clear();
if (ai->block != 0)
blocklist.push_back(ai->block);
std::map<std::string, IdentInfo *>::const_iterator i
= ai->idents->find(id);
if (i != ai->idents->end())
//return make_pair(i->second->name, const_cast<ASTInfo *>(ai));
return make_pair(i->second->name, const_cast<ASTInfo *>(ai));
else
{
if (ai->parent != NULL)
return findident(id, ai->parent, false);
else
return make_pair(std::string(""), (ASTInfo *)NULL);
}
}
ASTInfo *
findpident (const std::string & pid)
{
std::map<std::string, ASTInfo *>::const_iterator i = pidents.find(pid);
if (i != pidents.end())
return i->second;
else
return NULL;
}
/**
Z C identifikatoru a seznamu bloku odspoda nahoru vytvori Pascalsky
identifikator.
*/
std::string
mangleident (const std::string & s,
const std::list<int> & l)
{
if (l.empty())
return s;
std::ostringstream str;
str << "_";
for (std::list<int>::const_reverse_iterator i = l.rbegin();
i != l.rend();
++i)
{
str << *i << "_";
}
str << s;
return str.str();
}
std::pair<std::string, ASTInfo *>
insertident (const std::string id, const CTypeSpec * ts, ASTInfo * ai)
{
std::pair<std::string, ASTInfo *> rec = findident(id, ai);
std::string mident(mangleident(id, blockstack));
if (rec.second && rec.second->block != ai->block)
{
/* C identifikator nalezen, ale v nadrazenem bloku */
std::string lmident(strtolower(mident));
ASTInfo * pai = findpident(lmident);
if (pai)
{
/* Nalezli jsme kolidujici pascalske jmeno */
throw std::string("Error: Collision of Pascal identifiers '")
+ lmident + std::string("'");
}
/* Muzeme vlozit zaznam o identifikatoru. */
ai->idents->insert(
make_pair(id, new IdentInfo(new CTypeSpec(*ts), lmident)));
pidents.insert(make_pair(lmident, ai));
return make_pair(lmident, ai);
}
if (rec.second != NULL && rec.second->block == ai->block)
{
/* C identifikator nalezen v aktualnim bloku */
return make_pair(rec.first, ai);
}
if (rec.second == NULL)
{
/* Zadny takovy C identifikator nenalezen */
std::string lident(strtolower(id));
ASTInfo * pid = findpident(lident);
if (pid)
{
/* Uz takovy pascalsky identifikator mame, zkus upravit jmeno */
std::string lmident(strtolower(mident));
pid = findpident(lmident);
if (pid)
{
throw std::string("Error: Collision of Pascal identifiers '")
+ lmident + std::string("'");
}
lident = lmident;
}
ai->idents->insert(
make_pair(id, new IdentInfo(new CTypeSpec(*ts), lident)));
pidents.insert(make_pair(lident, ai));
return make_pair(lident, ai);
}
else
{
throw std::string("Pro odstraneni warningu");
}
}
CDecl *
gentmpdecl (const CTypeSpec * ts)
{
static int tmpcount = 0;
std::ostringstream str;
str << "__c2pas_tmpvar_" << (++tmpcount);
return new CDecl(ts, new CInitDecl(new CDeclarator(CDeclarator::DirectDecl,
new CIdent(str.str())),
NULL, NULL),
NULL);
}
/**
Pri generovani vystupu tela funkce zaznamena deklarace pro pozdejsi vystup.
*/
void
recordidents (const CDecl * dcl, ASTInfo * ai)
{
const CInitDecl * idcl = dcl->initdecl();
while (idcl)
{
/* vloz identifikator do prekladove tabulky identifikatoru */
std::pair<std::string, ASTInfo *> p;
p = insertident(idcl->declarator()->ident()->name(),
(CTypeSpec *)dcl->declspec()->clone(),
ai);
/* zarad deklaraci s prelozenym identifikatorem pro pozdejsi pouziti */
if (! (CTypeSpec *)dcl->declspec())
throw std::string("declspec == NULL");
//CExpr * init = idcl->
decls.push_back(
new CDecl((CTypeSpec *)dcl->declspec(),
new CInitDecl(new CDeclarator(CDeclarator::DirectDecl,
new CIdent(p.first)),
idcl && idcl->initializer()
? (CExpr *)idcl->initializer()->clone()
: NULL,
NULL),
NULL));
/* pokracuj dalsim CInitDecl */
idcl = dynamic_cast<const CInitDecl *>(idcl->next());
}
}
CTypeSpec::Type getexprtype (const CExpr *, const ASTInfo *);
CTypeSpec::Type
getexprtype (const COp * o, const ASTInfo * ai)
{
switch (o->op_type())
{
case COp::Unary:
return getexprtype(static_cast<const CUnOp *>(o)->arg(), ai);
case COp::Binary: {
const CBinOp * bo = static_cast<const CBinOp *>(o);
const CTypeSpec::Type lt = getexprtype(bo->leftArg(), ai),
rt = getexprtype(bo->rightArg(), ai);
if (lt == rt)
return lt;
else if ((lt == CTypeSpec::Float && (rt == CTypeSpec::Int
|| rt == CTypeSpec::Unsigned))
|| (rt == CTypeSpec::Float && (lt == CTypeSpec::Int
|| lt == CTypeSpec::Unsigned)))
return CTypeSpec::Float;
else
throw std::string("Unsupported combination of types "
"in getexprtype()");
}
default:
throw std::string("'Ternary' operation not supported");
}
}
CTypeSpec::Type
getexprtype (const CExpr * e, const ASTInfo * ai)
{
switch (e->expr_type())
{
case CExpr::Ident:
{
const std::string id
= static_cast<CIdentExpr const*>(e)->ident()->name();
std::pair<std::string, ASTInfo *> ainfo
= findident(id, ai);
if (! ainfo.second)
throw std::string("Identifier not found");
return ainfo.second->idents->operator[](id)->tspec->typespec_type();
}
case CExpr::Op:
return getexprtype(static_cast<COp const *>(e), ai);
case CExpr::Const: {
switch (static_cast<CConstExpr const *>(e)->const_type())
{
case CConstExpr::Int:
return CTypeSpec::Int;
case CConstExpr::UInt:
return CTypeSpec::Unsigned;
case CConstExpr::Float:
return CTypeSpec::Float;
default:
throw std::string("Unsupported type in getexprtype()");
}
}
default:
throw std::string("Unknown CExpr type!");
}
}
void astprint_comp_statement (const CCompoundStatement * cs, ASTInfo * ai,
std::ostream & out);
void astprint_sel_statement (const CSelectionStatement * cs, ASTInfo * ai,
std::ostream & out);
void astprint_expr_statement (const CExprStatement *, ASTInfo *,
std::ostream &);
void astprint_iter_statement (const CIterationStatement *, ASTInfo *,
std::ostream &);
void astprint_jump_statement (const CJumpStatement *, ASTInfo *,
std::ostream &);
void astprint_expr (const CExpr *, ASTInfo *, std::ostream &);
void astprint_op (const COp *, ASTInfo *, std::ostream &);
void astprint_const_expr (const CConstExpr *, ASTInfo *, std::ostream &);
void astprint_unop (const CUnOp *, ASTInfo *, std::ostream &);
void astprint_binop (const CBinOp *, ASTInfo *, std::ostream &);
void
astprint_statement (const CStatement * s, ASTInfo * ai,
std::ostream & out)
{
if (! s)
return;
CStatement const * stmt = s;
while (stmt)
{
switch (stmt->stmt_type())
{
case CStatement::Labeled:
throw std::string("'Labeled' statement handled within 'Selection' "
"statement only");
case CStatement::Compound:
astprint_comp_statement
(static_cast<const CCompoundStatement *>(stmt),
new ASTInfo(ai, ++blocks, stmt), out);
break;
case CStatement::Expr:
astprint_expr_statement(static_cast<const CExprStatement *>(stmt),
new ASTInfo(stmt, ai), out);
break;
case CStatement::Iteration:
astprint_iter_statement
(static_cast<const CIterationStatement *>(stmt),
new ASTInfo(stmt, ai), out);
break;
case CStatement::Jump:
astprint_jump_statement(static_cast<const CJumpStatement *>(stmt),
new ASTInfo(stmt, ai), out);
break;
case CStatement::Selection:
astprint_sel_statement
(static_cast<const CSelectionStatement *>(stmt),
new ASTInfo(stmt, ai), out);
}
// pokracuj na dalsi CStatement v seznamu
stmt = stmt->next ();
}
}
void
astprint_expr_statement (const CExprStatement * es, ASTInfo * ai,
std::ostream & out)
{
out << ";" << std::endl;
if (! es)
return;
astprint_expr(es->expr(), ai, out);
}
void
astprint_iter_statement (const CIterationStatement * is, ASTInfo * ai,
std::ostream & out)
{
out << ";" << std::endl;
if (! is)
return;
if (is->iterationstmt_type() != CIterationStatement::While)
throw std::string("Only 'While' iteration statement supported");
out << "while ";
astprint_expr(is->cond(), ai, out);
out << " do begin ";
astprint_statement(is->statement(), ai, out);
out << ";" << std::endl << "end";
}
void
astprint_jump_statement (const CJumpStatement * js, ASTInfo *,
std::ostream & out)
{
out << ";" << std::endl;
if (! js)
return;
switch(js->jumpstmt_type())
{
case CJumpStatement::Break:
out << "break";
break;
case CJumpStatement::Continue:
out << "continue";
break;
case CJumpStatement::Return:
out << "exit(1)";
break;
default:
throw std::string("'Goto' jump statement not supported");
}
}
void
astprint_comp_statement (const CCompoundStatement * cs, ASTInfo * ai,
std::ostream & out)
{
out << ";" << std::endl;
if (cs == NULL)
return;
/* vloz cislo bloku na vrchol zasobniku */
blockstack.push_back(ai->block);
/* projdi deklarace a uloz je pro pozdejsi pouziti */
const CDecl * dcl = cs->declarations();
while (dcl != NULL) {
recordidents(dcl, ai);
dcl = (CDecl *)dcl->next();
}
/* vystup bloku */
out << "begin" << std::endl;
const CStatement * const stmt = cs->statements();
astprint_statement(stmt, ai, out);
/*while (stmt != NULL) {
out << ";" << std::endl;
astprint(stmt, ai, out);
stmt = (CStatement *)stmt->next();
}*/
out << ";" << std::endl << "end";
if (! blockstack.empty())
/* odstran cislo bloku z vrcholu zasobniku */
blockstack.erase(--blockstack.end());
}
void
astprint_sel_statement (const CSelectionStatement * ss, ASTInfo * ai,
std::ostream & out)
{
out << ";" << std::endl;
if (! ss)
return;
if (ss->selectionstmt_type() != CSelectionStatement::Switch)
throw std::string("'If' statement not supported");
const CIdentExpr * swexpr;
if (ss->expr()->expr_type() != CExpr::Ident)
{
/* Vytvor docasnou promennou a prirazeni pokud je argument switche
slozitejsi nez pouhy identifikator aby jsme ho nevyhodnocovali
vicekrat */
CDecl * const tmpdecl =
gentmpdecl(new CTypeSpec(CTypeSpec::Long, NULL));
decls.push_back(tmpdecl);
const CIdent * const tmpident =
(CIdent *)tmpdecl->initdecl()->declarator()->ident();
const CIdentExpr * const idexpr =
new CIdentExpr(new CIdent(*tmpident));
const CBinOp * const tmpass =
new CBinOp(CBinOp::Assign, idexpr, ss->expr());
const CExprStatement * const estmt =
new CExprStatement(new CBinOp(*tmpass), NULL);
astprint_expr_statement(estmt, ai, out);
swexpr = idexpr;
}
else
{
swexpr = dynamic_cast<const CIdentExpr *>(ss->expr());
}
if (ss->statement1()->stmt_type() != CStatement::Compound)
throw std::string("Only 'Compound' statement can follow 'switch'");
CCompoundStatement const * swstmt
= dynamic_cast<const CCompoundStatement *>(ss->statement1());
CLabeledStatement const * lstmt;
const CStatement * stmt = swstmt->statements();
std::list<std::string> labels2;
std::list<const CLabeledStatement *> lstmts;
std::string default_label;
scan_for_cases (stmt, labels2, lstmts, default_label);
labels.insert (labels.end (), labels2.begin(), labels2.end ());
// Rozskok.
std::list<std::string>::const_iterator label_it = labels2.begin ();
std::list<const CLabeledStatement *>::const_iterator stmt_it
= lstmts.begin ();
//std::cerr << "lstmts.size ()" << lstmts.size () << std::endl;
for (; label_it != labels2.end () && stmt_it != lstmts.end ();
++label_it, ++stmt_it)
{
if (*label_it == default_label)
{
out << "goto " << default_label << ";" << std::endl;
}
else
{
//std::cerr << "*stmt_it: " << (void *)(*stmt_it) << std::endl;
const CBinOp * const tmp = new CBinOp(CBinOp::Eq, swexpr,
(*stmt_it)->expr ());
out << "if ";
astprint_binop (tmp, ai, out);
out << " then goto " << *label_it << ";" << std::endl;
}
}
label_it = labels2.begin ();
stmt_it = lstmts.begin ();
stmt = swstmt->statements();
while (stmt)
{
switch (stmt->stmt_type())
{
case CStatement::Labeled:
lstmt = static_cast<const CLabeledStatement *>(stmt);
if (lstmt->labeledstmt_type() == CLabeledStatement::Case)
{
out << ";" << std::endl;
out << *label_it << ": begin" << std::endl;
astprint_statement(lstmt->statement(), ai, out);
out << std::endl << "end";
}
else if (lstmt->labeledstmt_type() == CLabeledStatement::Default)
{
out << ";" << std::endl;
out << default_label << ": begin" << std::endl;
astprint_statement(lstmt->statement(), ai, out);
out << std::endl << "end";
}
else
throw std::string("Only 'Case' and 'Default' labeled statement"
" within 'switch' supported");
//out << ";" << std::endl;
break;
default:
throw std::string("Only 'Labeled' statement within 'switch' "
"supported");
}
stmt = static_cast<CStatement const *>(stmt->next());
++label_it;
++stmt_it;
}
}
bool
iskindofassign (const CExpr * o)
{
if (o->expr_type() != CExpr::Op)
return false;
if (static_cast<const COp *>(o)->op_type() != COp::Binary)
return false;
switch (static_cast<const CBinOp *>(o)->binop_type())
{
case CBinOp::Assign:
case CBinOp::MultAss:
case CBinOp::DivAss:
case CBinOp::ModAss:
case CBinOp::PlusAss:
case CBinOp::MinusAss:
case CBinOp::LShiftAss:
case CBinOp::RShift:
case CBinOp::BAndAss:
case CBinOp::BOrAss:
case CBinOp::XorAss:
return true;
default:
return false;
}
}
void
astprint_expr (const CExpr * e, ASTInfo * ai, std::ostream & out)
{
switch (e->expr_type())
{
case CExpr::Ident:
{
const std::string id
= static_cast<const CIdentExpr *>(e)->ident()->name();
const std::pair<std::string, ASTInfo *> ainf = findident(id, ai);
if (! ainf.second)
{
throw std::string("Identifier '")
+ id + std::string("' not declared ?!");
}
out << ainf.first;
break;
}
case CExpr::Op:
/*if (((COp *)e)->op_type() == COp::Binary
&& ((CBinOp *)e)->binop_type() == CBinOp::Assign) {
astprint((CBinOp *)e, ai, out);
}*/
if (iskindofassign(e))
astprint_binop(static_cast<const CBinOp *>(e), ai, out);
else
{
out << "(";
astprint_op(static_cast<const COp *>(e), ai, out);
out << ")";
}
break;
case CExpr::Const:
astprint_const_expr (static_cast<const CConstExpr *>(e), ai, out);
break;
}
}
void
astprint_op (const COp * o, ASTInfo * ai, std::ostream & out)
{
switch (o->op_type())
{
case COp::Unary:
astprint_unop(static_cast<const CUnOp *>(o), ai, out);
break;
case COp::Binary:
astprint_binop(static_cast<const CBinOp *>(o), ai, out);
break;
case COp::Ternary:
throw std::string("'Ternary' operation not supported");
}
}
void
astprint_const_expr (const CConstExpr * x, ASTInfo *, std::ostream & out)
{
switch (x->const_type())
{
case CConstExpr::Float:
out << (long double)x->value();
break;
case CConstExpr::Int:
out << (long long int)x->value();
break;
case CConstExpr::UInt:
out << (unsigned long long int)x->value();
break;
default:
throw std::string("'Char', 'Bool' and 'String' constants "
"not supported.");
}
}
void
astprint_unop (const CUnOp * o, ASTInfo * ai, std::ostream & out)
{
switch (o->unop_type())
{
case CUnOp::Tilde:
out << "not(";
astprint_expr(o->arg(), ai, out);
out << ")";
break;
case CUnOp::Excl:
out << "not(boolean(";
astprint_expr(o->arg(), ai, out);
out << "))";
break;
case CUnOp::Plus:
if (o->arg()->expr_type() == CExpr::Op)
{
out << "(";
astprint_expr(o->arg(), ai, out);
out << ")";
}
else
{
astprint_expr(o->arg(), ai, out);
}
break;
case CUnOp::Minus:
if (o->arg()->expr_type() == CExpr::Op)
{
out << "-(";
astprint_expr(o->arg(), ai, out);
out << ")";
}
else
{
out << "-";
astprint_expr(o->arg(), ai, out);
}
break;
case CUnOp::PostInc:
{
if (o->arg()->expr_type() != CExpr::Ident)
throw std::string("Cannot post increment non-identifier");
/* Vytvoreni prirazeni ktere se zaradi za aktualni statement
a tak castecne simuluje postinkrement. */
const CBinOp * const tmpass
= new CBinOp(CBinOp::Assign,
new CIdentExpr(*(CIdentExpr *)o->arg()),
new CBinOp(CBinOp::Plus,
new CIdentExpr(
*(CIdentExpr *)o->arg()),
new CUIntExpr(1)));
CExprStatement * const estmt =
new CExprStatement(new CBinOp(*tmpass),
NULL);
const CStatement * const old = (CStatement *)ai->astmt->next();
ai->astmt->set_next(estmt);
estmt->set_next(old);
astprint_expr(o->arg(), ai, out);
break;
}
case CUnOp::PostDec:
{
if (o->arg()->expr_type() != CExpr::Ident)
throw std::string("Cannot post increment non-identifier");
/* Vytbvoreni prirazeni ktere se zaradi za aktualni statement
a tak castecne simuluje postdekrement. */
CBinOp * tmpass
= new CBinOp(CBinOp::Assign,
new CIdentExpr(*(const CIdentExpr *)o->arg()),
new CBinOp(CBinOp::Minus,
new CIdentExpr(
*(const CIdentExpr *)o->arg()),
new CUIntExpr(1)));
CExprStatement * estmt = new CExprStatement(new CBinOp(*tmpass), NULL);
CStatement * old = (CStatement *)ai->astmt->next();
ai->astmt->set_next(estmt);
estmt->set_next(old);
astprint_expr(o->arg(), ai, out);
break;
}
case CUnOp::PreInc:
case CUnOp::PreDec:
case CUnOp::Star:
case CUnOp::And:
throw std::string("Unsupported unary operation");
}
}
CBinOp::Type
getassignoptype (const CBinOp * o)
{
switch (o->binop_type())
{
case CBinOp::MultAss:
return CBinOp::Mult;
case CBinOp::DivAss:
return CBinOp::Div;
case CBinOp::ModAss:
return CBinOp::Mod;
case CBinOp::PlusAss:
return CBinOp::Plus;
case CBinOp::MinusAss:
return CBinOp::Minus;
case CBinOp::LShiftAss:
return CBinOp::LShift;
case CBinOp::RShift:
return CBinOp::RShift;
case CBinOp::BAndAss:
return CBinOp::BAnd;
case CBinOp::BOrAss:
return CBinOp::BOr;
case CBinOp::XorAss:
return CBinOp::Xor;
default:
throw std::string("Use of getassignoptype() with CBinOp of bad type.");
}
}
void
astprint_binop (const CBinOp * o, ASTInfo * ai, std::ostream & out)
{
switch (o->binop_type())
{
case CBinOp::Plus:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ")+(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::Minus:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ")-(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::Mult:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ")*(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::Div:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ")";
if (getexprtype(o->leftArg(), ai) == CTypeSpec::Float
|| getexprtype(o->rightArg(), ai) == CTypeSpec::Float)
out << "/";
else
out << " div ";
out << "(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::Mod:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ") mod (";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::LShift:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ") lsh (";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::RShift:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ") rsh (";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::BAnd:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ") and (";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::BOr:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ") or (";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::LAnd:
out << "boolean(";
astprint_expr(o->leftArg(), ai, out);
out << ") and boolean(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::LOr:
out << "boolean(";
astprint_expr(o->leftArg(), ai, out);
out << ") and boolean(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::Eq:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ")=(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::NEq:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ")<>(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::LEq:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ")<=(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::GEq:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ")>=(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::Lt:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ")<(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::Gt:
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ")>(";
astprint_expr(o->rightArg(), ai, out);
out << ")";
break;
case CBinOp::Xor:
out << "((";
out << "(";
astprint_expr(o->leftArg(), ai, out);
out << ") and not(";
astprint_expr(o->rightArg(), ai, out);
out << ")) or (not(";
astprint_expr(o->leftArg(), ai, out);
out << ") and (";
astprint_expr(o->rightArg(), ai, out);
out << ")))";
break;
case CBinOp::Assign:
astprint_expr(o->leftArg(), ai, out);
out << ":=";
astprint_expr(o->rightArg(), ai, out);
break;
case CBinOp::MultAss:
case CBinOp::DivAss:
case CBinOp::ModAss:
case CBinOp::PlusAss:
case CBinOp::MinusAss:
case CBinOp::LShiftAss:
case CBinOp::RShiftAss:
case CBinOp::BAndAss:
case CBinOp::BOrAss:
case CBinOp::XorAss:
{
const CBinOp * const tmpex =
new CBinOp(CBinOp::Assign,
(const CExpr *)o->leftArg()->clone(),
new CBinOp(getassignoptype(o),
(const CExpr *)o->leftArg()->clone(),
(const CExpr *)o->rightArg()->clone()));
astprint_expr(tmpex, ai, out);
}
}
}
void
declsprint (std::list<const CDecl *> & dcls, std::ostream & out)
{
for (std::list<const CDecl *>::iterator idecl = dcls.begin();
idecl != dcls.end();
++idecl)
{
const CTypeSpec * const ts = (CTypeSpec *)(*idecl)->declspec();
const CInitDecl * const indcl = (*idecl)->initdecl();
out << indcl->declarator()->ident()->name() << " : ";
switch (ts->typespec_type())
{
case CTypeSpec::Int:
out << "longint";
break;
case CTypeSpec::Unsigned:
out << "cardinal";
break;
case CTypeSpec::Float:
out << "double";
break;
default:
throw std::string("Unsupported type in declsprint()");
}
out << ";" << std::endl;
if (indcl && indcl->declarator()
&& indcl->initializer())
initlist.push_back
(new CBinOp(CBinOp::Assign,
new CIdentExpr(
(CIdent *)
indcl->declarator()->ident()->clone()),
(CExpr *)indcl->initializer()->clone()));
}
}
void
labelsprint (std::list<std::string> const & labels, std::ostream & out)
{
out << "label " << join_into_stream (labels, ", ") << ";" << std::endl;
}
/*
void initsprint (std::list<CBinOp *> & il, std::ostream & out)
{
throw std::string("Inicializacne nepodporovana :(");
for (std::list<CBinOp *> ibo = il.begin();
ibo != il.end();
++ibo) {
astprint(
}
}
*/
| [
"[email protected]",
"unknown"
] | [
[
[
1,
26
],
[
34,
35
],
[
37,
37
],
[
39,
41
],
[
46,
47
],
[
50,
52
],
[
55,
55
],
[
57,
57
],
[
61,
63
],
[
66,
68
],
[
70,
72
],
[
74,
74
],
[
77,
78
],
[
80,
82
],
[
85,
97
],
[
102,
116
],
[
118,
118
],
[
121,
122
],
[
124,
128
],
[
131,
133
],
[
135,
137
],
[
139,
147
],
[
149,
150
],
[
153,
153
],
[
156,
168
],
[
170,
175
],
[
177,
181
],
[
183,
197
],
[
199,
199
],
[
201,
204
],
[
206,
208
],
[
212,
213
],
[
215,
222
],
[
226,
226
],
[
228,
229
],
[
231,
253
],
[
257,
260
],
[
262,
263
],
[
265,
265
],
[
267,
279
],
[
282,
282
],
[
286,
287
],
[
289,
296
],
[
298,
298
],
[
300,
300
],
[
302,
302
],
[
304,
305
],
[
307,
307
],
[
309,
309
],
[
311,
311
],
[
313,
313
],
[
317,
317
],
[
321,
340
],
[
342,
376
],
[
380,
382
],
[
384,
387
],
[
390,
392
],
[
394,
404
],
[
407,
409
],
[
411,
415
],
[
417,
418
],
[
420,
421
],
[
423,
424
],
[
426,
426
],
[
430,
432
],
[
434,
452
],
[
455,
457
],
[
459,
461
],
[
464,
466
],
[
468,
533
],
[
535,
571
],
[
574,
575
],
[
577,
582
],
[
594,
594
],
[
596,
596
],
[
600,
601
],
[
603,
608
],
[
610,
614
],
[
617,
617
],
[
619,
631
],
[
633,
634
],
[
638,
639
],
[
641,
642
],
[
644,
645
],
[
647,
648
],
[
650,
650
],
[
654,
655
],
[
657,
658
],
[
660,
661
],
[
663,
664
],
[
666,
667
],
[
669,
670
],
[
674,
675
],
[
677,
678
],
[
680,
683
],
[
685,
688
],
[
690,
694
],
[
696,
698
],
[
700,
700
],
[
702,
706
],
[
708,
711
],
[
713,
715
],
[
717,
717
],
[
720,
729
],
[
731,
733
],
[
735,
738
],
[
740,
740
],
[
743,
749
],
[
752,
754
],
[
756,
756
],
[
761,
761
],
[
765,
766
],
[
768,
769
],
[
771,
771
],
[
773,
773
],
[
775,
775
],
[
777,
777
],
[
779,
779
],
[
781,
781
],
[
783,
783
],
[
785,
785
],
[
787,
787
],
[
789,
789
],
[
791,
791
],
[
796,
797
],
[
799,
800
],
[
802,
807
],
[
809,
814
],
[
816,
821
],
[
823,
834
],
[
836,
841
],
[
843,
848
],
[
850,
855
],
[
857,
862
],
[
864,
869
],
[
871,
876
],
[
878,
883
],
[
885,
890
],
[
892,
897
],
[
899,
904
],
[
906,
911
],
[
913,
918
],
[
920,
925
],
[
927,
937
],
[
939,
942
],
[
952,
954
],
[
957,
957
],
[
960,
962
],
[
966,
967
],
[
969,
977
],
[
979,
980
],
[
982,
983
],
[
985,
986
],
[
988,
988
],
[
990,
998
],
[
1002,
1008
],
[
1010,
1018
]
],
[
[
27,
33
],
[
36,
36
],
[
38,
38
],
[
42,
45
],
[
48,
49
],
[
53,
54
],
[
56,
56
],
[
58,
60
],
[
64,
65
],
[
69,
69
],
[
73,
73
],
[
75,
76
],
[
79,
79
],
[
83,
84
],
[
98,
101
],
[
117,
117
],
[
119,
120
],
[
123,
123
],
[
129,
130
],
[
134,
134
],
[
138,
138
],
[
148,
148
],
[
151,
152
],
[
154,
155
],
[
169,
169
],
[
176,
176
],
[
182,
182
],
[
198,
198
],
[
200,
200
],
[
205,
205
],
[
209,
211
],
[
214,
214
],
[
223,
225
],
[
227,
227
],
[
230,
230
],
[
254,
256
],
[
261,
261
],
[
264,
264
],
[
266,
266
],
[
280,
281
],
[
283,
285
],
[
288,
288
],
[
297,
297
],
[
299,
299
],
[
301,
301
],
[
303,
303
],
[
306,
306
],
[
308,
308
],
[
310,
310
],
[
312,
312
],
[
314,
316
],
[
318,
320
],
[
341,
341
],
[
377,
379
],
[
383,
383
],
[
388,
389
],
[
393,
393
],
[
405,
406
],
[
410,
410
],
[
416,
416
],
[
419,
419
],
[
422,
422
],
[
425,
425
],
[
427,
429
],
[
433,
433
],
[
453,
454
],
[
458,
458
],
[
462,
463
],
[
467,
467
],
[
534,
534
],
[
572,
573
],
[
576,
576
],
[
583,
593
],
[
595,
595
],
[
597,
599
],
[
602,
602
],
[
609,
609
],
[
615,
616
],
[
618,
618
],
[
632,
632
],
[
635,
637
],
[
640,
640
],
[
643,
643
],
[
646,
646
],
[
649,
649
],
[
651,
653
],
[
656,
656
],
[
659,
659
],
[
662,
662
],
[
665,
665
],
[
668,
668
],
[
671,
673
],
[
676,
676
],
[
679,
679
],
[
684,
684
],
[
689,
689
],
[
695,
695
],
[
699,
699
],
[
701,
701
],
[
707,
707
],
[
712,
712
],
[
716,
716
],
[
718,
719
],
[
730,
730
],
[
734,
734
],
[
739,
739
],
[
741,
742
],
[
750,
751
],
[
755,
755
],
[
757,
760
],
[
762,
764
],
[
767,
767
],
[
770,
770
],
[
772,
772
],
[
774,
774
],
[
776,
776
],
[
778,
778
],
[
780,
780
],
[
782,
782
],
[
784,
784
],
[
786,
786
],
[
788,
788
],
[
790,
790
],
[
792,
795
],
[
798,
798
],
[
801,
801
],
[
808,
808
],
[
815,
815
],
[
822,
822
],
[
835,
835
],
[
842,
842
],
[
849,
849
],
[
856,
856
],
[
863,
863
],
[
870,
870
],
[
877,
877
],
[
884,
884
],
[
891,
891
],
[
898,
898
],
[
905,
905
],
[
912,
912
],
[
919,
919
],
[
926,
926
],
[
938,
938
],
[
943,
951
],
[
955,
956
],
[
958,
959
],
[
963,
965
],
[
968,
968
],
[
978,
978
],
[
981,
981
],
[
984,
984
],
[
987,
987
],
[
989,
989
],
[
999,
1001
],
[
1009,
1009
],
[
1019,
1019
]
]
] |
aa9b3643676b97ec945811b49fed9a42cf00fdf5 | f73eca356aba8cbc5c0cbe7527c977f0e7d6a116 | /Glop/third_party/raknet/TableSerializer.h | 517fbd2d44e76bdd378e416fa52ecb0ac0ed7a7d | [
"BSD-3-Clause"
] | permissive | zorbathut/glop | 40737587e880e557f1f69c3406094631e35e6bb5 | 762d4f1e070ce9c7180a161b521b05c45bde4a63 | refs/heads/master | 2016-08-06T22:58:18.240425 | 2011-10-20T04:22:20 | 2011-10-20T04:22:20 | 710,818 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,933 | h | #ifndef __TABLE_SERIALIZER_H
#define __TABLE_SERIALIZER_H
#include "RakMemoryOverride.h"
#include "DS_Table.h"
#include "Export.h"
namespace RakNet
{
class BitStream;
}
class RAK_DLL_EXPORT TableSerializer : public RakNet::RakMemoryOverride
{
public:
static void SerializeTable(DataStructures::Table *in, RakNet::BitStream *out);
static bool DeserializeTable(unsigned char *serializedTable, unsigned int dataLength, DataStructures::Table *out);
static bool DeserializeTable(RakNet::BitStream *in, DataStructures::Table *out);
static void SerializeColumns(DataStructures::Table *in, RakNet::BitStream *out);
static void SerializeColumns(DataStructures::Table *in, RakNet::BitStream *out, DataStructures::List<int> &skipColumnIndices);
static bool DeserializeColumns(RakNet::BitStream *in, DataStructures::Table *out);
static void SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, DataStructures::List<DataStructures::Table::ColumnDescriptor> &columns, RakNet::BitStream *out);
static void SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, DataStructures::List<DataStructures::Table::ColumnDescriptor> &columns, RakNet::BitStream *out, DataStructures::List<int> &skipColumnIndices);
static bool DeserializeRow(RakNet::BitStream *in, DataStructures::Table *out);
static void SerializeCell(RakNet::BitStream *out, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType);
static bool DeserializeCell(RakNet::BitStream *in, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType);
static void SerializeFilterQuery(RakNet::BitStream *in, DataStructures::Table::FilterQuery *query);
// Note that this allocates query->cell->c!
static bool DeserializeFilterQuery(RakNet::BitStream *out, DataStructures::Table::FilterQuery *query);
static void SerializeFilterQueryList(RakNet::BitStream *in, DataStructures::Table::FilterQuery *query, unsigned int numQueries, unsigned int maxQueries);
// Note that this allocates queries, cells, and query->cell->c!. Use DeallocateQueryList to free.
static bool DeserializeFilterQueryList(RakNet::BitStream *out, DataStructures::Table::FilterQuery **query, unsigned int *numQueries, unsigned int maxQueries, int allocateExtraQueries=0);
static void DeallocateQueryList(DataStructures::Table::FilterQuery *query, unsigned int numQueries);
};
#endif
// Test code for the table
/*
#include "LightweightDatabaseServer.h"
#include "LightweightDatabaseClient.h"
#include "TableSerializer.h"
#include "BitStream.h"
#include "StringCompressor.h"
#include "DS_Table.h"
void main(void)
{
DataStructures::Table table;
DataStructures::Table::Row *row;
unsigned int dummydata=12345;
// Add columns Name (string), IP (binary), score (int), and players (int).
table.AddColumn("Name", DataStructures::Table::STRING);
table.AddColumn("IP", DataStructures::Table::BINARY);
table.AddColumn("Score", DataStructures::Table::NUMERIC);
table.AddColumn("Players", DataStructures::Table::NUMERIC);
table.AddColumn("Empty Test Column", DataStructures::Table::STRING);
assert(table.GetColumnCount()==5);
row=table.AddRow(0);
assert(row);
row->UpdateCell(0,"Kevin Jenkins");
row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata);
row->UpdateCell(2,5);
row->UpdateCell(3,10);
//row->UpdateCell(4,"should be unique");
row=table.AddRow(1);
row->UpdateCell(0,"Kevin Jenkins");
row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata);
row->UpdateCell(2,5);
row->UpdateCell(3,15);
row=table.AddRow(2);
row->UpdateCell(0,"Kevin Jenkins");
row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata);
row->UpdateCell(2,5);
row->UpdateCell(3,20);
row=table.AddRow(3);
assert(row);
row->UpdateCell(0,"Kevin Jenkins");
row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata);
row->UpdateCell(2,15);
row->UpdateCell(3,5);
row->UpdateCell(4,"col index 4");
row=table.AddRow(4);
assert(row);
row->UpdateCell(0,"Kevin Jenkins");
row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata);
//row->UpdateCell(2,25);
row->UpdateCell(3,30);
//row->UpdateCell(4,"should be unique");
row=table.AddRow(5);
assert(row);
row->UpdateCell(0,"Kevin Jenkins");
row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata);
//row->UpdateCell(2,25);
row->UpdateCell(3,5);
//row->UpdateCell(4,"should be unique");
row=table.AddRow(6);
assert(row);
row->UpdateCell(0,"Kevin Jenkins");
row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata);
row->UpdateCell(2,35);
//row->UpdateCell(3,40);
//row->UpdateCell(4,"should be unique");
row=table.AddRow(7);
assert(row);
row->UpdateCell(0,"Bob Jenkins");
row=table.AddRow(8);
assert(row);
row->UpdateCell(0,"Zack Jenkins");
// Test multi-column sorting
DataStructures::Table::Row *rows[30];
DataStructures::Table::SortQuery queries[4];
queries[0].columnIndex=0;
queries[0].operation=DataStructures::Table::QS_INCREASING_ORDER;
queries[1].columnIndex=1;
queries[1].operation=DataStructures::Table::QS_INCREASING_ORDER;
queries[2].columnIndex=2;
queries[2].operation=DataStructures::Table::QS_INCREASING_ORDER;
queries[3].columnIndex=3;
queries[3].operation=DataStructures::Table::QS_DECREASING_ORDER;
table.SortTable(queries, 4, rows);
unsigned i;
char out[256];
RAKNET_DEBUG_PRINTF("Sort: Ascending except for column index 3\n");
for (i=0; i < table.GetRowCount(); i++)
{
table.PrintRow(out,256,',',true, rows[i]);
RAKNET_DEBUG_PRINTF("%s\n", out);
}
// Test query:
// Don't return column 3, and swap columns 0 and 2
unsigned columnsToReturn[4];
columnsToReturn[0]=2;
columnsToReturn[1]=1;
columnsToReturn[2]=0;
columnsToReturn[3]=4;
DataStructures::Table resultsTable;
table.QueryTable(columnsToReturn,4,0,0,&resultsTable);
RAKNET_DEBUG_PRINTF("Query: Don't return column 3, and swap columns 0 and 2:\n");
for (i=0; i < resultsTable.GetRowCount(); i++)
{
resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i));
RAKNET_DEBUG_PRINTF("%s\n", out);
}
// Test filter:
// Only return rows with column index 4 empty
DataStructures::Table::FilterQuery inclusionFilters[3];
inclusionFilters[0].columnIndex=4;
inclusionFilters[0].operation=DataStructures::Table::QF_IS_EMPTY;
// inclusionFilters[0].cellValue; // Unused for IS_EMPTY
table.QueryTable(0,0,inclusionFilters,1,&resultsTable);
RAKNET_DEBUG_PRINTF("Filter: Only return rows with column index 4 empty:\n");
for (i=0; i < resultsTable.GetRowCount(); i++)
{
resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i));
RAKNET_DEBUG_PRINTF("%s\n", out);
}
// Column 5 empty and column 0 == Kevin Jenkins
inclusionFilters[0].columnIndex=4;
inclusionFilters[0].operation=DataStructures::Table::QF_IS_EMPTY;
inclusionFilters[1].columnIndex=0;
inclusionFilters[1].operation=DataStructures::Table::QF_EQUAL;
inclusionFilters[1].cellValue.Set("Kevin Jenkins");
table.QueryTable(0,0,inclusionFilters,2,&resultsTable);
RAKNET_DEBUG_PRINTF("Filter: Column 5 empty and column 0 == Kevin Jenkins:\n");
for (i=0; i < resultsTable.GetRowCount(); i++)
{
resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i));
RAKNET_DEBUG_PRINTF("%s\n", out);
}
RakNet::BitStream bs;
RAKNET_DEBUG_PRINTF("PreSerialize:\n");
for (i=0; i < table.GetRowCount(); i++)
{
table.PrintRow(out,256,',',true, table.GetRowByIndex(i));
RAKNET_DEBUG_PRINTF("%s\n", out);
}
StringCompressor::AddReference();
TableSerializer::Serialize(&table, &bs);
TableSerializer::Deserialize(&bs, &table);
StringCompressor::RemoveReference();
RAKNET_DEBUG_PRINTF("PostDeserialize:\n");
for (i=0; i < table.GetRowCount(); i++)
{
table.PrintRow(out,256,',',true, table.GetRowByIndex(i));
RAKNET_DEBUG_PRINTF("%s\n", out);
}
int a=5;
}
*/
| [
"[email protected]"
] | [
[
[
1,
203
]
]
] |
bac2fc630f297cd34a91a06cb68425e9cb48f16e | 5e2940026151c566d2d979fbf776a4e62aa68099 | /ClientSocket.cpp | 8e49bcd29f6558a61e90add3e51110cde741ab92 | [] | no_license | MatthewChan/Softlumos | f2ed6627d7a77c21bb78c954e6314db46841567d | ede766095e155aa1004a5ccde2c867a18eb3d260 | refs/heads/master | 2020-04-06T07:04:18.348650 | 2010-12-06T09:37:59 | 2010-12-06T09:37:59 | 1,142,706 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | cpp | // ClientSocket.cpp : implementation file
//
#include "stdafx.h"
#include "NetDiskTool.h"
#include "ClientSocket.h"
#include "netdisktooldoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CClientSocket
CClientSocket::CClientSocket(CNetDiskToolDoc* pDoc)
{
m_pDoc = pDoc;
}
CClientSocket::~CClientSocket()
{
}
// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CClientSocket, CSocket)
//{{AFX_MSG_MAP(CClientSocket)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0
/////////////////////////////////////////////////////////////////////////////
// CClientSocket member functions
void CClientSocket::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
m_pDoc->ProcessPendingRead();
CAsyncSocket::OnReceive(nErrorCode);
}
void CClientSocket::OnClose(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
m_pDoc->CloseConncet();
CAsyncSocket::OnClose(nErrorCode);
}
| [
"[email protected]"
] | [
[
[
1,
56
]
]
] |
c9d09ef0ca7e263786b1b31c7bcc9af629367a47 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Applications/Physics/WrigglingSnake/WrigglingSnake.cpp | 19729c7b3cb21674e0bbce1510558317ad356b6c | [] | no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,400 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Game Physics source code is supplied under the terms of the license
// agreement http://www.magic-software.com/License/GamePhysics.pdf and may not
// be copied or disclosed except in accordance with the terms of that
// agreement.
#include "WrigglingSnake.h"
WrigglingSnake g_kTheApp;
float WrigglingSnake::ms_fRadius = 0.0625f;
//#define SINGLE_STEP
//----------------------------------------------------------------------------
WrigglingSnake::WrigglingSnake ()
:
Application("WrigglingSnake",0,0,640,480,
ColorRGB(1.0f,0.823529f,0.607843f))
{
m_iNumCtrl = 32;
m_iDegree = 3;
m_pkCenter = NULL;
m_afAmplitude = new float[m_iNumCtrl];
m_afPhase = new float[m_iNumCtrl];
m_iShellQuantity = 4;
}
//----------------------------------------------------------------------------
WrigglingSnake::~WrigglingSnake ()
{
delete[] m_afAmplitude;
delete[] m_afPhase;
}
//----------------------------------------------------------------------------
bool WrigglingSnake::OnInitialize ()
{
if ( !Application::OnInitialize() )
return false;
m_spkScene = new Node(1);
m_spkTrnNode = new Node(1);
m_spkScene->AttachChild(m_spkTrnNode);
m_spkWireframe = new WireframeState;
m_spkScene->SetRenderState(m_spkWireframe);
ZBufferState* pkZBuffer = new ZBufferState;
pkZBuffer->Enabled() = true;
pkZBuffer->Writeable() = true;
pkZBuffer->Compare() = ZBufferState::CF_LEQUAL;
m_spkScene->SetRenderState(pkZBuffer);
CreateSnake();
// center-and-fit for camera viewing
m_spkScene->UpdateGS(0.0f);
Bound kWBound = m_spkScene->WorldBound();
m_spkTrnNode->Translate() = -kWBound.Center();
ms_spkCamera->SetFrustum(1.0f,100.0f,-0.55f,0.55f,0.4125f,-0.4125f);
Vector3f kCLeft(1.0f,0.0f,0.0f);
Vector3f kCUp(0.0f,0.0f,1.0f);
Vector3f kCDir(0.0f,-1.0f,0.0f);
Vector3f kCLoc = -3.0f*kWBound.Radius()*kCDir;
ms_spkCamera->SetFrame(kCLoc,kCLeft,kCUp,kCDir);
// initial update of objects
ms_spkCamera->Update();
m_spkScene->UpdateGS(0.0f);
m_spkScene->UpdateRS();
// camera turret and tumble mode
m_spkMotionObject = m_spkScene;
m_fTrnSpeed = 0.01f;
m_fRotSpeed = 0.001f;
m_bTurretActive = true;
SetTurretAxes();
return true;
}
//----------------------------------------------------------------------------
void WrigglingSnake::OnTerminate ()
{
m_spkScene = NULL;
m_spkTrnNode = NULL;
m_spkSnakeRoot = NULL;
m_spkSnakeBody = NULL;
m_spkSnakeHead = NULL;
m_spkWireframe = NULL;
Application::OnTerminate();
}
//----------------------------------------------------------------------------
void WrigglingSnake::OnIdle ()
{
MeasureTime();
MoveCamera();
if ( MoveObject() )
m_spkScene->UpdateGS(0.0f);
#ifndef SINGLE_STEP
ModifyCurve();
#endif
ms_spkRenderer->ClearBuffers();
if ( ms_spkRenderer->BeginScene() )
{
ms_spkRenderer->Draw(m_spkScene);
DrawFrameRate(8,GetHeight()-8,ColorRGB::BLACK);
ms_spkRenderer->EndScene();
}
ms_spkRenderer->DisplayBackBuffer();
UpdateClicks();
}
//----------------------------------------------------------------------------
void WrigglingSnake::OnKeyDown (unsigned char ucKey, int, int)
{
if ( ucKey == 'q' || ucKey == 'Q' || ucKey == KEY_ESCAPE )
{
RequestTermination();
return;
}
switch ( ucKey )
{
case 'w': // toggle wireframe
case 'W':
m_spkWireframe->Enabled() = !m_spkWireframe->Enabled();
break;
#ifdef SINGLE_STEP
case 'g':
case 'G':
ModifyCurve();
break;
#endif
}
}
//----------------------------------------------------------------------------
float WrigglingSnake::Radial (float fT)
{
return ms_fRadius*(2.0f*fT)/(1.0f+fT);
}
//----------------------------------------------------------------------------
void WrigglingSnake::CreateSnake ()
{
m_spkSnakeRoot = new Node(2);
m_spkTrnNode->AttachChild(m_spkSnakeRoot);
CreateSnakeBody();
CreateSnakeHead();
}
//----------------------------------------------------------------------------
void WrigglingSnake::CreateSnakeBody ()
{
// create the B-spline curve for the snake body
Vector3f* akCtrl = new Vector3f[m_iNumCtrl];
int i;
for (i = 0; i < m_iNumCtrl; i++)
{
// control points for a snake
float fRatio = ((float)i)/(float)(m_iNumCtrl-1);
float fX = -1.0f + 2.0f*fRatio;
float fXMod = 10.0f*fX - 4.0f;
akCtrl[i].X() = fX;
akCtrl[i].Y() = ms_fRadius*(1.5f + Mathf::ATan(fXMod)/Mathf::PI);
akCtrl[i].Z() = 0.0f;
// sinusoidal motion for snake
m_afAmplitude[i] = 0.1f+fRatio*Mathf::Exp(-fRatio);
m_afPhase[i] = 1.5f*fRatio*Mathf::TWO_PI;
}
// the control points are copied by the curve objects
m_pkCenter = new BSplineCurve3f(m_iNumCtrl,akCtrl,m_iDegree,false,true);
delete[] akCtrl;
// generate a tube surface
bool bClosed = false;
Vector3f kUpVector = Vector3f::UNIT_Y;
int iMedialSamples = 128;
int iSliceSamples = 32;
bool bWantNormals = true;
bool bWantColors = false;
bool bSampleByArcLength = false;
bool bInsideView = false;
Vector2f kTextureMin(0.0f,0.0f), kTextureMax(1.0f,16.0f);
m_spkSnakeBody = new TubeSurface(m_pkCenter,Radial,bClosed,kUpVector,
iMedialSamples,iSliceSamples,bWantNormals,bWantColors,
bSampleByArcLength,bInsideView,&kTextureMin,&kTextureMax);
// attach a texture for the snake body
Texture* pkTexture = new Texture;
pkTexture->SetImage(Image::Load("snake.mif"));
pkTexture->Filter() = Texture::FM_LINEAR;
pkTexture->Mipmap() = Texture::MM_LINEAR_LINEAR;
pkTexture->Apply() = Texture::AM_REPLACE;
pkTexture->Wrap() = Texture::WM_WRAP_S_WRAP_T;
TextureState* pkTS = new TextureState;
pkTS->Set(0,pkTexture);
//m_spkSnakeBody->SetRenderState(pkTS);
// Set up a light map to add to the current color.
pkTexture = new Texture;
pkTexture->SetImage(Image::Load("LightMap.mif"));
pkTexture->Filter() = Texture::FM_LINEAR;
pkTexture->Mipmap() = Texture::MM_LINEAR_LINEAR;
pkTexture->Apply() = Texture::AM_ADD;
pkTexture->Envmap() = Texture::EM_SPHERE;
pkTS->Set(1,pkTexture);
m_spkSnakeBody->SetRenderState(pkTS);
m_spkSnakeRoot->AttachChild(m_spkSnakeBody);
}
//----------------------------------------------------------------------------
void WrigglingSnake::CreateSnakeHead ()
{
// Create the snake head as a paraboloid that is attached to the last
// ring of vertices on the snake body. These vertices are generated
// for t = 1.
int iSliceSamples = m_spkSnakeBody->GetSliceSamples();
// number of rays (determined by slice samples of tube surface)
int iRQ = iSliceSamples - 1;
// number of shells (your choice, specified in application constructor)
int iSQ = m_iShellQuantity, iSQm1 = iSQ-1;
// generate vertices (to be filled in by UpdateSnakeHead)
int iVQuantity = 1 + iRQ*iSQm1;
Vector3f* akVertex = new Vector3f[iVQuantity];
// generate vertex colors coordinates
ColorRGB* akColor = new ColorRGB[iVQuantity];
for (int i = 0; i < iVQuantity; i++)
akColor[i] = ColorRGB(0.0f,0.25f,0.0f);
// generate triangles
int iTQuantity = iRQ*(2*iSQm1-1);
int* aiConnect = new int[3*iTQuantity];
int* piConnect = aiConnect;
int iT = 0;
for (int iR0 = iRQ-1, iR1 = 0; iR1 < iRQ; iR0 = iR1++)
{
*piConnect++ = 0;
*piConnect++ = 1+iSQm1*iR0;
*piConnect++ = 1+iSQm1*iR1;
iT++;
for (int iS = 1; iS < iSQm1 ; iS++)
{
int i00 = iS+iSQm1*iR0;
int i01 = iS+iSQm1*iR1;
int i10 = i00+1;
int i11 = i01+1;
*piConnect++ = i00;
*piConnect++ = i10;
*piConnect++ = i11;
*piConnect++ = i00;
*piConnect++ = i11;
*piConnect++ = i01;
iT += 2;
}
}
assert( iT == iTQuantity );
m_spkSnakeHead = new TriMesh(iVQuantity,akVertex,NULL,akColor,NULL,
iTQuantity,aiConnect);
m_spkSnakeRoot->AttachChild(m_spkSnakeHead);
UpdateSnakeHead();
}
//----------------------------------------------------------------------------
void WrigglingSnake::UpdateSnake ()
{
// The order of calls is important since the snake head uses the last
// ring of vertices in the tube surface of the snake body.
UpdateSnakeBody();
UpdateSnakeHead();
m_spkSnakeRoot->UpdateGS(0.0f);
}
//----------------------------------------------------------------------------
void WrigglingSnake::UpdateSnakeBody ()
{
m_spkSnakeBody->UpdateSurface();
}
//----------------------------------------------------------------------------
void WrigglingSnake::UpdateSnakeHead ()
{
// get the ring of vertices at the head-end of the tube
int iSliceSamples = m_spkSnakeBody->GetSliceSamples();
Vector3f* akSlice = new Vector3f[iSliceSamples+1];
m_spkSnakeBody->GetTMaxSlice(akSlice);
// compute the center of the slice vertices
Vector3f kCenter = akSlice[0];
int i;
for (i = 1; i <= iSliceSamples; i++)
kCenter += akSlice[i];
kCenter /= (float)(iSliceSamples+1);
// Compute a unit-length normal of the plane of the vertices. The normal
// points away from tube and is used to extrude the paraboloid surface
// for the head.
Vector3f kEdge1 = akSlice[1] - akSlice[0];
Vector3f kEdge2 = akSlice[2] - akSlice[0];
Vector3f kNormal = kEdge1.UnitCross(kEdge2);
// Adjust the normal length to include the height of the ellipsoid vertex
// above the plane of the slice.
kNormal *= 3.0f*ms_fRadius;
Vector3f* akVertex = m_spkSnakeHead->Vertices();
// origin
akVertex[0] = kCenter + kNormal;
// remaining shells
const int iSQm1 = m_iShellQuantity - 1;
float fFactor = 1.0f/iSQm1;
for (int iR = 0; iR < iSliceSamples-1; iR++)
{
for (int iS = 1; iS < m_iShellQuantity; iS++)
{
float fT = fFactor*iS, fOmT = 1.0f - fT;
i = iS + iSQm1*iR;
akVertex[i] = fOmT*kCenter + fT*akSlice[iR] +
Mathf::Pow(fOmT,0.25f)*kNormal;
}
}
delete[] akSlice;
m_spkSnakeHead->UpdateModelBound();
}
//----------------------------------------------------------------------------
void WrigglingSnake::ModifyCurve ()
{
// perturb the snake medial curve
float fTime = GetTimeInSeconds();
for (int i = 0; i < m_iNumCtrl; i++)
{
Vector3f kCtrl = m_pkCenter->GetControlPoint(i);
kCtrl.Z() = m_afAmplitude[i]*Mathf::Sin(3.0f*fTime+m_afPhase[i]);
m_pkCenter->SetControlPoint(i,kCtrl);
}
UpdateSnake();
}
//----------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
352
]
]
] |
7010bb3ea037a1f2fafe455d4c05c53f67a35b80 | ffd731ace66892b070eac3abe27169bcb53cc989 | /Rendering/Raytracer/raytrace/RenderEngine.cpp | 887494e0f60d931f7f445a46565cadd0be8d9961 | [] | no_license | nical/DTU-school-projetcs | 5496666a0de67312befc094ec070ce2897eaebc7 | b9b4b6921838968e0f7370320f87244992f03989 | refs/heads/master | 2021-01-23T21:33:37.659374 | 2011-09-19T18:37:38 | 2011-09-19T18:37:38 | 2,361,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,984 | cpp | // 02562 Rendering Framework
// Written by Jeppe Revall Frisvad, 2011
// Copyright (c) DTU Informatics 2011
#include <iostream>
#include <algorithm>
#include <list>
#include <string>
#include "my_glut.h"
#include <optix_world.h>
#include "../SOIL/stb_image_write.h"
#include "string_utils.h"
#include "Timer.h"
#include "mt_random.h"
#include "Directional.h"
#include "PointLight.h"
#include "RenderEngine.h"
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace optix;
RenderEngine render_engine;
namespace
{
// String utilities
void lower_case(char& x) { x = tolower(x); }
inline void lower_case_string(std::string& s)
{
for_each(s.begin(), s.end(), lower_case);
}
}
//////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////
RenderEngine::RenderEngine()
: win(optix::make_uint2(512, 512)), // Default window size
res(optix::make_uint2(512, 512)), // Default render resolution
image(res.x*res.y),
image_tex(0),
scene(&cam),
filename("out.ppm"), // Default output file name
tracer(res.x, res.y, &scene, 100000), // Maximum number of photons in map
max_to_trace(500000), // Maximum number of photons to trace
caustics_particles(20000), // Desired number of caustics photons
done(false),
light_pow(optix::make_float3(M_PIf)), // Power of the default light
light_dir(optix::make_float3(-1.0f)), // Direction of the default light
default_light(&tracer, light_pow, light_dir), // Construct default light
use_default_light(true), // Choose whether to use the default light or not
shadows_on(true),
background(optix::make_float3(0.1f, 0.3f, 0.6f)), // Background color
bgtex_filename(""), // Background texture file name
current_shader(0),
lambertian(scene.get_lights()),
photon_caustics(&tracer, scene.get_lights(), 1.0f, 50), // Max distance and number of photons to search for
glossy(&tracer, scene.get_lights()),
mirror(&tracer),
transparent(&tracer),
volume(&tracer),
glossy_volume(&tracer, scene.get_lights()),
tone_map(2.5) // Gamma for gamma correction
{
shaders.push_back(&reflectance); // number key 0 (reflectance only)
shaders.push_back(&lambertian); // number key 1 (direct lighting)
shaders.push_back(&photon_caustics); // number key 2 (photon map caustics)
}
void RenderEngine::load_files(int argc, char** argv)
{
if(argc > 1)
{
for(int i = 1; i < argc; ++i)
{
// Retrieve filename without path
list<string> path_split;
split(argv[i], path_split, "\\");
filename = path_split.back();
if(filename.find("/") != filename.npos)
{
path_split.clear();
split(filename, path_split, "/");
filename = path_split.back();
}
lower_case_string(filename);
Matrix4x4 transform = Matrix4x4::identity();
// Special rules for some meshes
if(char_traits<char>::compare(filename.c_str(), "cornell", 7) == 0)
transform = Matrix4x4::scale(make_float3(0.025f))*Matrix4x4::rotate(M_PIf, make_float3(0.0f, 1.0f, 0.0f));
else if(char_traits<char>::compare(filename.c_str(), "bunny", 5) == 0)
transform = Matrix4x4::translate(make_float3(-3.0f, -0.85f, -8.0f))*Matrix4x4::scale(make_float3(25.0f));
else if(char_traits<char>::compare(filename.c_str(), "justelephant", 12) == 0)
transform = Matrix4x4::translate(make_float3(-10.0f, 3.0f, -2.0f))*Matrix4x4::rotate(0.5f, make_float3(0.0f, 1.0f, 0.0f));
// Load the file into the scene
scene.load_mesh(argv[i], transform);
}
init_view();
}
else
{
// Insert default scene
scene.add_plane(make_float3(0.0f, 0.0f, 0.0f), normalize(make_float3(0.0f, 1.0f, 0.0f)), "../models/default_scene.mtl", 1, 0.2f);
//scene.add_plane(make_float3(0.0f, 0.0f, 0.0f), make_float3(1.0f, 0.0f, 0.0f), "../models/default_scene.mtl", 1, 0.2f);
scene.add_sphere(make_float3(0.0f, 0.5f, 0.0f), 0.3f, "../models/default_scene.mtl", 2);
scene.add_triangle(make_float3(-0.2f, 0.1f, 0.9f), make_float3(0.2f, 0.1f, 0.9f), make_float3(-0.2f, 0.1f, -0.1f), "../models/default_scene.mtl", 3);
scene.add_light(new PointLight(&tracer, make_float3(M_PIf), make_float3(0.0f, 1.0f, 0.0f)));
cam.set(make_float3(2.0f, 1.5f, 2.0f), make_float3(0.0f, 0.5, 0.0f), make_float3(0.0f, 1.0f, 0.0f), 1.0f);
}
}
void RenderEngine::init_GLUT(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(win.x, win.y);
glutCreateWindow("02562 Render Framework");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
}
void RenderEngine::init_GL()
{
glEnable(GL_CULL_FACE);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
}
void RenderEngine::init_view()
{
float3 c;
float r;
scene.get_bsphere(c, r);
r *= 1.75f;
// Initialize corresponding camera for tracer
cam.set(c + make_float3(0.0f, 0.0f, r), c, make_float3(0.0f, 1.0f, 0.0f), 1.0f);
}
void RenderEngine::init_tracer()
{
clear_image();
// Insert background texture/color
tracer.set_background(background);
if(!bgtex_filename.empty())
{
list<string> dot_split;
split(bgtex_filename, dot_split, ".");
if(dot_split.back() == "hdr")
bgtex.load_hdr(bgtex_filename.c_str());
else
bgtex.load(bgtex_filename.c_str());
tracer.set_background(&bgtex);
}
// Set shaders
scene.set_shader(0, shaders[current_shader]); // shader for illum 0 (chosen by number key)
scene.set_shader(1, shaders[current_shader]); // shader for illum 1 (chosen by number key)
scene.set_shader(2, &glossy); // shader for illum 2 (calls lambertian until implemented)
scene.set_shader(3, &mirror); // shader for illum 3
scene.set_shader(4, &transparent); // shader for illum 4
scene.set_shader(11, &volume); // shader for illum 11
scene.set_shader(12, &glossy_volume); // shader for illum 12
// Load material textures
scene.load_textures();
// Add polygons with an ambient material as area light sources
unsigned int lights_in_scene = scene.extract_area_lights(&tracer, 8); // Set number of samples per light source here
// If no light in scene, add default light source (shadow off)
if(lights_in_scene == 0 && use_default_light)
{
cout << "Adding default light: " << default_light.describe() << endl;
scene.add_light(&default_light);
}
// Build acceleration data structure
Timer timer;
cout << "Building acceleration structure...";
timer.start();
scene.init_accelerator();
timer.stop();
cout << "(time: " << timer.get_time() << ")" << endl;
// Build photon maps
cout << "Building photon maps... " << endl;
timer.start();
tracer.build_maps(caustics_particles, max_to_trace);
timer.stop();
cout << "Building time: " << timer.get_time() << endl;
}
void RenderEngine::init_texture()
{
if(!glIsTexture(image_tex))
glGenTextures(1, &image_tex);
glBindTexture(GL_TEXTURE_2D, image_tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// load the texture image
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, res.x, res.y, 0, GL_RGB, GL_FLOAT, &image[0].x);
}
//////////////////////////////////////////////////////////////////////
// Rendering
//////////////////////////////////////////////////////////////////////
void RenderEngine::apply_tone_map()
{
if(done)
{
tone_map.apply(&image[0].x, res.x, res.y, 3);
init_texture();
glutPostRedisplay();
}
}
void RenderEngine::unapply_tone_map()
{
if(done)
{
tone_map.unapply(&image[0].x, res.x, res.y, 3);
init_texture();
glutPostRedisplay();
}
}
void RenderEngine::add_textures()
{
reflectance.set_textures(scene.get_textures());
lambertian.set_textures(scene.get_textures());
glossy.set_textures(scene.get_textures());
glossy_volume.set_textures(scene.get_textures());
photon_caustics.set_textures(scene.get_textures());
}
void RenderEngine::render()
{
cout << "Raytracing";
Timer timer;
timer.start();
#pragma omp parallel for private(randomizer)
for(int i = 0; i < static_cast<int>(res.y); ++i)
{
// Insert the inner loop that computes a row of pixels
// and stores the results in the image vector.
//
// Relevant data fields that are available (see RenderEngine.h)
// res (image resolution)
// tracer (ray tracer with access to the function compute_pixel)
for ( int j = 0; j < res.x; ++j )
{
//float3 temp = tracer.compute_pixel(j,i);
image[j + i*res.x] = tracer.compute_pixel(j,i);
}
if(((i + 1) % 50) == 0)
cerr << ".";
}
timer.stop();
cout << " - " << timer.get_time() << " secs " << endl;
init_texture();
done = true;
}
//////////////////////////////////////////////////////////////////////
// Export/import
//////////////////////////////////////////////////////////////////////
void RenderEngine::save_as_bitmap()
{
string png_name = "out.png";
if(!filename.empty())
{
list<string> dot_split;
split(filename, dot_split, ".");
png_name = dot_split.front() + ".png";
}
unsigned char* data = new unsigned char[res.x*res.y*3];
for(unsigned int j = 0; j < res.y; ++j)
for(unsigned int i = 0; i < res.x; ++i)
{
unsigned int d_idx = (i + res.x*j)*3;
unsigned int i_idx = i + res.x*(res.y - j - 1);
data[d_idx + 0] = static_cast<unsigned int>(std::min(image[i_idx].x, 1.0f)*255.0f + 0.5f);
data[d_idx + 1] = static_cast<unsigned int>(std::min(image[i_idx].y, 1.0f)*255.0f + 0.5f);
data[d_idx + 2] = static_cast<unsigned int>(std::min(image[i_idx].z, 1.0f)*255.0f + 0.5f);
}
stbi_write_png(png_name.c_str(), res.x, res.y, 3, data, res.x*3);
delete [] data;
cout << "Rendered image stored in " << png_name << "." << endl;
}
//////////////////////////////////////////////////////////////////////
// Draw functions
//////////////////////////////////////////////////////////////////////
void RenderEngine::set_gl_ortho_proj()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
void RenderEngine::draw_texture()
{
static GLfloat verts[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f };
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glBindTexture(GL_TEXTURE_2D, image_tex);
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, verts);
glTexCoordPointer(2, GL_FLOAT, 0, verts);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
}
void RenderEngine::draw()
{
if(shaders[current_shader] == &photon_caustics)
tracer.draw_caustics_map();
else
scene.draw();
}
//////////////////////////////////////////////////////////////////////
// GLUT callback functions
//////////////////////////////////////////////////////////////////////
void RenderEngine::display()
{
if(render_engine.is_done())
{
render_engine.set_gl_ortho_proj();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
render_engine.draw_texture();
}
else
{
glEnable(GL_DEPTH_TEST);
render_engine.set_gl_perspective();
render_engine.set_gl_clearcolor();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
render_engine.set_gl_camera();
render_engine.draw();
glDisable(GL_DEPTH_TEST);
}
glutSwapBuffers();
}
void RenderEngine::reshape(int width, int height)
{
render_engine.set_window_size(width, height);
glViewport(0, 0, width, height);
}
void RenderEngine::keyboard(unsigned char key, int x, int y)
{
// The shader to be used when rendering a material is chosen
// by setting the "illum" property of the material. This
// property is part of the MTL file format ("illum" is short
// for "illumination model"). The shader to be used with
// each illumination model is specified in the init_tracer
// function above.
//
// Number keys switch the shader used for illumination
// models 0 and 1 to the shader at the corresponding index
// in the array "shaders" at the top of this file.
//
// When you switch shaders all previous rendering results
// will be erased!
if(key >= 48 && key < 48 + static_cast<unsigned char>(render_engine.no_of_shaders()))
{
unsigned int shader_no = key - 48;
if(shader_no != render_engine.get_current_shader())
{
render_engine.set_current_shader(shader_no);
render_engine.clear_image();
render_engine.redo_display_list();
cout << "Switched to shader number " << shader_no << endl;
glutPostRedisplay();
}
}
switch(key)
{
// Use '+' and '-' to increase or decrease the number of
// jitter samples per pixel in a simple ray tracing
case '+':
render_engine.increment_pixel_subdivs();
break;
case '-':
render_engine.decrement_pixel_subdivs();
break;
// Press '*' to apply tone mapping
case '*':
render_engine.apply_tone_map();
break;
// Press '/' to unapply tone mapping
case '/':
render_engine.unapply_tone_map();
break;
// Press 'b' to save a bitmap called the same as the last loaded .obj file.
case 'b':
render_engine.save_as_bitmap();
break;
// Press 'r' to start a simple ray tracing (one pass -> done).
// To switch back to preview mode after the ray tracing is done
// press 'r' again.
case 'r':
if(render_engine.is_done())
render_engine.undo();
else
render_engine.render();
glutPostRedisplay();
break;
// Press 's' to toggle shadows on/off
case 's':
{
bool shadows_on = render_engine.toggle_shadows();
render_engine.clear_image();
render_engine.redo_display_list();
cout << "Toggled shadows " << (shadows_on ? "on" : "off") << endl;
glutPostRedisplay();
}
break;
// Press 'x' to switch on material textures.
case 'x':
render_engine.add_textures();
cout << "Toggled textures on." << endl;
break;
// Press 'z' to zoom in.
case 'z':
{
render_engine.set_focal_dist(render_engine.get_focal_dist()*1.05f);
glutPostRedisplay();
}
break;
// Press 'Z' to zoom out.
case 'Z':
{
render_engine.set_focal_dist(render_engine.get_focal_dist()/1.05f);
glutPostRedisplay();
}
break;
// Press 'SPACE' to switch between pre-view and your last tracing result.
case 32:
render_engine.undo();
glutPostRedisplay();
break;
// Press 'ESC' to exit the program.
case 27:
exit(0);
}
}
void RenderEngine::set_current_shader(unsigned int shader)
{
current_shader = shader;
for(int i = 0; i < 2; ++i)
scene.set_shader(i, shaders[current_shader]);
}
| [
"[email protected]"
] | [
[
[
1,
491
]
]
] |
cb4250f84d646fdff63e7c293eca7f2e6c679e96 | 20bf3095aa164d0d3431b73ead8a268684f14976 | /cpp-labs/BINSEARC.CPP | 11031f2f490ca7807b57f57bfabe76de39f3537a | [] | no_license | collage-lab/mcalab-cpp | eb5518346f5c3b7c1a96627c621a71cc493de76d | c642f1f009154424f243789014c779b9fc938ce4 | refs/heads/master | 2021-08-31T10:28:59.517333 | 2006-11-10T23:57:09 | 2006-11-10T23:57:21 | 114,954,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 591 | cpp | #include<iostream.h>
#include<conio.h>
void search(int prr[],int size,int se)
{
int ll,ul,mid,j;
ll=0;ul=size-1;
mid=(ul+ll)/2;
for(j=1;j<=size;j++)
{
mid=(ul+ll)/2;
if(se<prr[mid])
ul=(mid-1);
else if(se>prr[mid])
ll=(mid+1);
else
{
cout<<"Element found at location "<<mid;
break;
}
}
}
void main()
{
int arr[100],i,e,m;
clrscr();
cout<<"Enter array size:";
cin>>m;
for(i=0;i<m;i++)
{
cout<<endl<<"Element["<<i<<"]:-";
cin>>arr[i];
}
cout<<endl<<"Element to be found:";
cin>>e;
search(arr,m,e);
getch();
} | [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
b3da75f477fe932eeae81db1dd4d2c0c054dab33 | 037faae47a5b22d3e283555e6b5ac2a0197faf18 | /pcsx2v2/windows/libs/pthread.h | e206de0a8cb75d07e4d0d04c15363099822b8df0 | [] | no_license | isabella232/pcsx2-sourceforge | 6e5aac8d0b476601bfc8fa83ded66c1564b8c588 | dbb2c3a010081b105a8cba0c588f1e8f4e4505c6 | refs/heads/master | 2023-03-18T22:23:15.102593 | 2008-11-17T20:10:17 | 2008-11-17T20:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43,167 | h | /* This is an implementation of the threads API of POSIX 1003.1-2001.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: [email protected]
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* 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 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 in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#if !defined( PTHREAD_H )
#define PTHREAD_H
/*
* See the README file for an explanation of the pthreads-win32 version
* numbering scheme and how the DLL is named etc.
*/
#define PTW32_VERSION 2,7,0,0
#define PTW32_VERSION_STRING "2, 7, 0, 0\0"
/* There are three implementations of cancel cleanup.
* Note that pthread.h is included in both application
* compilation units and also internally for the library.
* The code here and within the library aims to work
* for all reasonable combinations of environments.
*
* The three implementations are:
*
* WIN32 SEH
* C
* C++
*
* Please note that exiting a push/pop block via
* "return", "exit", "break", or "continue" will
* lead to different behaviour amongst applications
* depending upon whether the library was built
* using SEH, C++, or C. For example, a library built
* with SEH will call the cleanup routine, while both
* C++ and C built versions will not.
*/
/*
* Define defaults for cleanup code.
* Note: Unless the build explicitly defines one of the following, then
* we default to standard C style cleanup. This style uses setjmp/longjmp
* in the cancelation and thread exit implementations and therefore won't
* do stack unwinding if linked to applications that have it (e.g.
* C++ apps). This is currently consistent with most/all commercial Unix
* POSIX threads implementations.
*/
#if !defined( __CLEANUP_SEH ) && !defined( __CLEANUP_CXX ) && !defined( __CLEANUP_C )
# define __CLEANUP_C
#endif
#if defined( __CLEANUP_SEH ) && ( !defined( _MSC_VER ) && !defined(PTW32_RC_MSC))
#error ERROR [__FILE__, line __LINE__]: SEH is not supported for this compiler.
#endif
/*
* Stop here if we are being included by the resource compiler.
*/
#ifndef RC_INVOKED
#undef PTW32_LEVEL
#if defined(_POSIX_SOURCE)
#define PTW32_LEVEL 0
/* Early POSIX */
#endif
#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309
#undef PTW32_LEVEL
#define PTW32_LEVEL 1
/* Include 1b, 1c and 1d */
#endif
#if defined(INCLUDE_NP)
#undef PTW32_LEVEL
#define PTW32_LEVEL 2
/* Include Non-Portable extensions */
#endif
#define PTW32_LEVEL_MAX 3
#if !defined(PTW32_LEVEL)
#define PTW32_LEVEL PTW32_LEVEL_MAX
/* Include everything */
#endif
#ifdef _UWIN
# define HAVE_STRUCT_TIMESPEC 1
# define HAVE_SIGNAL_H 1
# undef HAVE_CONFIG_H
# pragma comment(lib, "pthread")
#endif
/*
* -------------------------------------------------------------
*
*
* Module: pthread.h
*
* Purpose:
* Provides an implementation of PThreads based upon the
* standard:
*
* POSIX 1003.1-2001
* and
* The Single Unix Specification version 3
*
* (these two are equivalent)
*
* in order to enhance code portability between Windows,
* various commercial Unix implementations, and Linux.
*
* See the ANNOUNCE file for a full list of conforming
* routines and defined constants, and a list of missing
* routines and constants not defined in this implementation.
*
* Authors:
* There have been many contributors to this library.
* The initial implementation was contributed by
* John Bossom, and several others have provided major
* sections or revisions of parts of the implementation.
* Often significant effort has been contributed to
* find and fix important bugs and other problems to
* improve the reliability of the library, which sometimes
* is not reflected in the amount of code which changed as
* result.
* As much as possible, the contributors are acknowledged
* in the ChangeLog file in the source code distribution
* where their changes are noted in detail.
*
* Contributors are listed in the CONTRIBUTORS file.
*
* As usual, all bouquets go to the contributors, and all
* brickbats go to the project maintainer.
*
* Maintainer:
* The code base for this project is coordinated and
* eventually pre-tested, packaged, and made available by
*
* Ross Johnson <[email protected]>
*
* QA Testers:
* Ultimately, the library is tested in the real world by
* a host of competent and demanding scientists and
* engineers who report bugs and/or provide solutions
* which are then fixed or incorporated into subsequent
* versions of the library. Each time a bug is fixed, a
* test case is written to prove the fix and ensure
* that later changes to the code don't reintroduce the
* same error. The number of test cases is slowly growing
* and therefore so is the code reliability.
*
* Compliance:
* See the file ANNOUNCE for the list of implemented
* and not-implemented routines and defined options.
* Of course, these are all defined is this file as well.
*
* Web site:
* The source code and other information about this library
* are available from
*
* http://sources.redhat.com/pthreads-win32/
*
* -------------------------------------------------------------
*/
/* Try to avoid including windows.h */
#if defined(__MINGW32__) && defined(__cplusplus)
#define PTW32_INCLUDE_WINDOWS_H
#endif
#ifdef PTW32_INCLUDE_WINDOWS_H
#include <windows.h>
#endif
#if defined(_MSC_VER) && _MSC_VER < 1300 || defined(__DMC__)
/*
* VC++6.0 or early compiler's header has no DWORD_PTR type.
*/
typedef unsigned long DWORD_PTR;
#endif
/*
* -----------------
* autoconf switches
* -----------------
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#ifndef NEED_FTIME
#include <time.h>
#else /* NEED_FTIME */
/* use native WIN32 time API */
#endif /* NEED_FTIME */
#if HAVE_SIGNAL_H
#include <signal.h>
#endif /* HAVE_SIGNAL_H */
#include <setjmp.h>
#include <limits.h>
/*
* Boolean values to make us independent of system includes.
*/
enum {
PTW32_FALSE = 0,
PTW32_TRUE = (! PTW32_FALSE)
};
/*
* This is a duplicate of what is in the autoconf config.h,
* which is only used when building the pthread-win32 libraries.
*/
#ifndef PTW32_CONFIG_H
# if defined(WINCE)
# define NEED_ERRNO
# define NEED_SEM
# endif
# if defined(_UWIN) || defined(__MINGW32__)
# define HAVE_MODE_T
# endif
#endif
/*
*
*/
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
#ifdef NEED_ERRNO
#include "need_errno.h"
#else
#include <errno.h>
#endif
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Several systems don't define some error numbers.
*/
#ifndef ENOTSUP
# define ENOTSUP 48 /* This is the value in Solaris. */
#endif
#ifndef ETIMEDOUT
# define ETIMEDOUT 10060 /* This is the value in winsock.h. */
#endif
#ifndef ENOSYS
# define ENOSYS 140 /* Semi-arbitrary value */
#endif
#ifndef EDEADLK
# ifdef EDEADLOCK
# define EDEADLK EDEADLOCK
# else
# define EDEADLK 36 /* This is the value in MSVC. */
# endif
#endif
#include <sched.h>
/*
* To avoid including windows.h we define only those things that we
* actually need from it.
*/
#ifndef PTW32_INCLUDE_WINDOWS_H
#ifndef HANDLE
# define PTW32__HANDLE_DEF
# define HANDLE void *
#endif
#ifndef DWORD
# define PTW32__DWORD_DEF
# define DWORD unsigned long
#endif
#endif
#ifndef HAVE_STRUCT_TIMESPEC
#define HAVE_STRUCT_TIMESPEC 1
struct timespec {
long tv_sec;
long tv_nsec;
};
#endif /* HAVE_STRUCT_TIMESPEC */
#ifndef SIG_BLOCK
#define SIG_BLOCK 0
#endif /* SIG_BLOCK */
#ifndef SIG_UNBLOCK
#define SIG_UNBLOCK 1
#endif /* SIG_UNBLOCK */
#ifndef SIG_SETMASK
#define SIG_SETMASK 2
#endif /* SIG_SETMASK */
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/*
* -------------------------------------------------------------
*
* POSIX 1003.1-2001 Options
* =========================
*
* Options are normally set in <unistd.h>, which is not provided
* with pthreads-win32.
*
* For conformance with the Single Unix Specification (version 3), all of the
* options below are defined, and have a value of either -1 (not supported)
* or 200112L (supported).
*
* These options can neither be left undefined nor have a value of 0, because
* either indicates that sysconf(), which is not implemented, may be used at
* runtime to check the status of the option.
*
* _POSIX_THREADS (== 200112L)
* If == 200112L, you can use threads
*
* _POSIX_THREAD_ATTR_STACKSIZE (== 200112L)
* If == 200112L, you can control the size of a thread's
* stack
* pthread_attr_getstacksize
* pthread_attr_setstacksize
*
* _POSIX_THREAD_ATTR_STACKADDR (== -1)
* If == 200112L, you can allocate and control a thread's
* stack. If not supported, the following functions
* will return ENOSYS, indicating they are not
* supported:
* pthread_attr_getstackaddr
* pthread_attr_setstackaddr
*
* _POSIX_THREAD_PRIORITY_SCHEDULING (== -1)
* If == 200112L, you can use realtime scheduling.
* This option indicates that the behaviour of some
* implemented functions conforms to the additional TPS
* requirements in the standard. E.g. rwlocks favour
* writers over readers when threads have equal priority.
*
* _POSIX_THREAD_PRIO_INHERIT (== -1)
* If == 200112L, you can create priority inheritance
* mutexes.
* pthread_mutexattr_getprotocol +
* pthread_mutexattr_setprotocol +
*
* _POSIX_THREAD_PRIO_PROTECT (== -1)
* If == 200112L, you can create priority ceiling mutexes
* Indicates the availability of:
* pthread_mutex_getprioceiling
* pthread_mutex_setprioceiling
* pthread_mutexattr_getprioceiling
* pthread_mutexattr_getprotocol +
* pthread_mutexattr_setprioceiling
* pthread_mutexattr_setprotocol +
*
* _POSIX_THREAD_PROCESS_SHARED (== -1)
* If set, you can create mutexes and condition
* variables that can be shared with another
* process.If set, indicates the availability
* of:
* pthread_mutexattr_getpshared
* pthread_mutexattr_setpshared
* pthread_condattr_getpshared
* pthread_condattr_setpshared
*
* _POSIX_THREAD_SAFE_FUNCTIONS (== 200112L)
* If == 200112L you can use the special *_r library
* functions that provide thread-safe behaviour
*
* _POSIX_READER_WRITER_LOCKS (== 200112L)
* If == 200112L, you can use read/write locks
*
* _POSIX_SPIN_LOCKS (== 200112L)
* If == 200112L, you can use spin locks
*
* _POSIX_BARRIERS (== 200112L)
* If == 200112L, you can use barriers
*
* + These functions provide both 'inherit' and/or
* 'protect' protocol, based upon these macro
* settings.
*
* -------------------------------------------------------------
*/
/*
* POSIX Options
*/
#undef _POSIX_THREADS
#define _POSIX_THREADS 200112L
#undef _POSIX_READER_WRITER_LOCKS
#define _POSIX_READER_WRITER_LOCKS 200112L
#undef _POSIX_SPIN_LOCKS
#define _POSIX_SPIN_LOCKS 200112L
#undef _POSIX_BARRIERS
#define _POSIX_BARRIERS 200112L
#undef _POSIX_THREAD_SAFE_FUNCTIONS
#define _POSIX_THREAD_SAFE_FUNCTIONS 200112L
#undef _POSIX_THREAD_ATTR_STACKSIZE
#define _POSIX_THREAD_ATTR_STACKSIZE 200112L
/*
* The following options are not supported
*/
#undef _POSIX_THREAD_ATTR_STACKADDR
#define _POSIX_THREAD_ATTR_STACKADDR -1
#undef _POSIX_THREAD_PRIO_INHERIT
#define _POSIX_THREAD_PRIO_INHERIT -1
#undef _POSIX_THREAD_PRIO_PROTECT
#define _POSIX_THREAD_PRIO_PROTECT -1
/* TPS is not fully supported. */
#undef _POSIX_THREAD_PRIORITY_SCHEDULING
#define _POSIX_THREAD_PRIORITY_SCHEDULING -1
#undef _POSIX_THREAD_PROCESS_SHARED
#define _POSIX_THREAD_PROCESS_SHARED -1
/*
* POSIX 1003.1-2001 Limits
* ===========================
*
* These limits are normally set in <limits.h>, which is not provided with
* pthreads-win32.
*
* PTHREAD_DESTRUCTOR_ITERATIONS
* Maximum number of attempts to destroy
* a thread's thread-specific data on
* termination (must be at least 4)
*
* PTHREAD_KEYS_MAX
* Maximum number of thread-specific data keys
* available per process (must be at least 128)
*
* PTHREAD_STACK_MIN
* Minimum supported stack size for a thread
*
* PTHREAD_THREADS_MAX
* Maximum number of threads supported per
* process (must be at least 64).
*
* SEM_NSEMS_MAX
* The maximum number of semaphores a process can have.
* (must be at least 256)
*
* SEM_VALUE_MAX
* The maximum value a semaphore can have.
* (must be at least 32767)
*
*/
#undef _POSIX_THREAD_DESTRUCTOR_ITERATIONS
#define _POSIX_THREAD_DESTRUCTOR_ITERATIONS 4
#undef PTHREAD_DESTRUCTOR_ITERATIONS
#define PTHREAD_DESTRUCTOR_ITERATIONS _POSIX_THREAD_DESTRUCTOR_ITERATIONS
#undef _POSIX_THREAD_KEYS_MAX
#define _POSIX_THREAD_KEYS_MAX 128
#undef PTHREAD_KEYS_MAX
#define PTHREAD_KEYS_MAX _POSIX_THREAD_KEYS_MAX
#undef PTHREAD_STACK_MIN
#define PTHREAD_STACK_MIN 0
#undef _POSIX_THREAD_THREADS_MAX
#define _POSIX_THREAD_THREADS_MAX 64
/* Arbitrary value */
#undef PTHREAD_THREADS_MAX
#define PTHREAD_THREADS_MAX 2019
#undef _POSIX_SEM_NSEMS_MAX
#define _POSIX_SEM_NSEMS_MAX 256
/* Arbitrary value */
#undef SEM_NSEMS_MAX
#define SEM_NSEMS_MAX 1024
#undef _POSIX_SEM_VALUE_MAX
#define _POSIX_SEM_VALUE_MAX 32767
#undef SEM_VALUE_MAX
#define SEM_VALUE_MAX INT_MAX
#if __GNUC__ && ! defined (__declspec)
# error Please upgrade your GNU compiler to one that supports __declspec.
#endif
/*
* When building the DLL code, you should define PTW32_BUILD so that
* the variables/functions are exported correctly. When using the DLL,
* do NOT define PTW32_BUILD, and then the variables/functions will
* be imported correctly.
*/
#ifndef PTW32_STATIC_LIB
# ifdef PTW32_BUILD
# define PTW32_DLLPORT __declspec (dllexport)
# else
# define PTW32_DLLPORT __declspec (dllimport)
# endif
#else
# define PTW32_DLLPORT
#endif
/*
* The Open Watcom C/C++ compiler uses a non-standard calling convention
* that passes function args in registers unless __cdecl is explicitly specified
* in exposed function prototypes.
*
* We force all calls to cdecl even though this could slow Watcom code down
* slightly. If you know that the Watcom compiler will be used to build both
* the DLL and application, then you can probably define this as a null string.
* Remember that pthread.h (this file) is used for both the DLL and application builds.
*/
#define PTW32_CDECL __cdecl
#if defined(_UWIN) && PTW32_LEVEL >= PTW32_LEVEL_MAX
# include <sys/types.h>
#else
/*
* Generic handle type - intended to extend uniqueness beyond
* that available with a simple pointer. It should scale for either
* IA-32 or IA-64.
*/
typedef struct {
void * p; /* Pointer to actual object */
unsigned int x; /* Extra information - reuse count etc */
} ptw32_handle_t;
typedef ptw32_handle_t pthread_t;
typedef struct pthread_attr_t_ * pthread_attr_t;
typedef struct pthread_once_t_ pthread_once_t;
typedef struct pthread_key_t_ * pthread_key_t;
typedef struct pthread_mutex_t_ * pthread_mutex_t;
typedef struct pthread_mutexattr_t_ * pthread_mutexattr_t;
typedef struct pthread_cond_t_ * pthread_cond_t;
typedef struct pthread_condattr_t_ * pthread_condattr_t;
#endif
typedef struct pthread_rwlock_t_ * pthread_rwlock_t;
typedef struct pthread_rwlockattr_t_ * pthread_rwlockattr_t;
typedef struct pthread_spinlock_t_ * pthread_spinlock_t;
typedef struct pthread_barrier_t_ * pthread_barrier_t;
typedef struct pthread_barrierattr_t_ * pthread_barrierattr_t;
/*
* ====================
* ====================
* POSIX Threads
* ====================
* ====================
*/
enum {
/*
* pthread_attr_{get,set}detachstate
*/
PTHREAD_CREATE_JOINABLE = 0, /* Default */
PTHREAD_CREATE_DETACHED = 1,
/*
* pthread_attr_{get,set}inheritsched
*/
PTHREAD_INHERIT_SCHED = 0,
PTHREAD_EXPLICIT_SCHED = 1, /* Default */
/*
* pthread_{get,set}scope
*/
PTHREAD_SCOPE_PROCESS = 0,
PTHREAD_SCOPE_SYSTEM = 1, /* Default */
/*
* pthread_setcancelstate paramters
*/
PTHREAD_CANCEL_ENABLE = 0, /* Default */
PTHREAD_CANCEL_DISABLE = 1,
/*
* pthread_setcanceltype parameters
*/
PTHREAD_CANCEL_ASYNCHRONOUS = 0,
PTHREAD_CANCEL_DEFERRED = 1, /* Default */
/*
* pthread_mutexattr_{get,set}pshared
* pthread_condattr_{get,set}pshared
*/
PTHREAD_PROCESS_PRIVATE = 0,
PTHREAD_PROCESS_SHARED = 1,
/*
* pthread_barrier_wait
*/
PTHREAD_BARRIER_SERIAL_THREAD = -1
};
/*
* ====================
* ====================
* Cancelation
* ====================
* ====================
*/
#define PTHREAD_CANCELED ((void *) -1)
/*
* ====================
* ====================
* Once Key
* ====================
* ====================
*/
#define PTHREAD_ONCE_INIT { PTW32_FALSE, 0, 0, 0}
struct pthread_once_t_
{
int done; /* indicates if user function has been executed */
void * lock;
int reserved1;
int reserved2;
};
/*
* ====================
* ====================
* Object initialisers
* ====================
* ====================
*/
#define PTHREAD_MUTEX_INITIALIZER ((pthread_mutex_t) -1)
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER ((pthread_mutex_t) -2)
#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER ((pthread_mutex_t) -3)
/*
* Compatibility with LinuxThreads
*/
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP PTHREAD_RECURSIVE_MUTEX_INITIALIZER
#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP PTHREAD_ERRORCHECK_MUTEX_INITIALIZER
#define PTHREAD_COND_INITIALIZER ((pthread_cond_t) -1)
#define PTHREAD_RWLOCK_INITIALIZER ((pthread_rwlock_t) -1)
#define PTHREAD_SPINLOCK_INITIALIZER ((pthread_spinlock_t) -1)
/*
* Mutex types.
*/
enum
{
/* Compatibility with LinuxThreads */
PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_TIMED_NP = PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_ADAPTIVE_NP = PTHREAD_MUTEX_FAST_NP,
/* For compatibility with POSIX */
PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
};
typedef struct ptw32_cleanup_t ptw32_cleanup_t;
#if defined(_MSC_VER)
/* Disable MSVC 'anachronism used' warning */
#pragma warning( disable : 4229 )
#endif
typedef void (* PTW32_CDECL ptw32_cleanup_callback_t)(void *);
#if defined(_MSC_VER)
#pragma warning( default : 4229 )
#endif
struct ptw32_cleanup_t
{
ptw32_cleanup_callback_t routine;
void *arg;
struct ptw32_cleanup_t *prev;
};
#ifdef __CLEANUP_SEH
/*
* WIN32 SEH version of cancel cleanup.
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
ptw32_cleanup_t _cleanup; \
\
_cleanup.routine = (ptw32_cleanup_callback_t)(_rout); \
_cleanup.arg = (_arg); \
__try \
{ \
#define pthread_cleanup_pop( _execute ) \
} \
__finally \
{ \
if( _execute || AbnormalTermination()) \
{ \
(*(_cleanup.routine))( _cleanup.arg ); \
} \
} \
}
#else /* __CLEANUP_SEH */
#ifdef __CLEANUP_C
/*
* C implementation of PThreads cancel cleanup
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
ptw32_cleanup_t _cleanup; \
\
ptw32_push_cleanup( &_cleanup, (ptw32_cleanup_callback_t) (_rout), (_arg) ); \
#define pthread_cleanup_pop( _execute ) \
(void) ptw32_pop_cleanup( _execute ); \
}
#else /* __CLEANUP_C */
#ifdef __CLEANUP_CXX
/*
* C++ version of cancel cleanup.
* - John E. Bossom.
*/
class PThreadCleanup {
/*
* PThreadCleanup
*
* Purpose
* This class is a C++ helper class that is
* used to implement pthread_cleanup_push/
* pthread_cleanup_pop.
* The destructor of this class automatically
* pops the pushed cleanup routine regardless
* of how the code exits the scope
* (i.e. such as by an exception)
*/
ptw32_cleanup_callback_t cleanUpRout;
void * obj;
int executeIt;
public:
PThreadCleanup() :
cleanUpRout( 0 ),
obj( 0 ),
executeIt( 0 )
/*
* No cleanup performed
*/
{
}
PThreadCleanup(
ptw32_cleanup_callback_t routine,
void * arg ) :
cleanUpRout( routine ),
obj( arg ),
executeIt( 1 )
/*
* Registers a cleanup routine for 'arg'
*/
{
}
~PThreadCleanup()
{
if ( executeIt && ((void *) cleanUpRout != (void *) 0) )
{
(void) (*cleanUpRout)( obj );
}
}
void execute( int exec )
{
executeIt = exec;
}
};
/*
* C++ implementation of PThreads cancel cleanup;
* This implementation takes advantage of a helper
* class who's destructor automatically calls the
* cleanup routine if we exit our scope weirdly
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
PThreadCleanup cleanup((ptw32_cleanup_callback_t)(_rout), \
(void *) (_arg) );
#define pthread_cleanup_pop( _execute ) \
cleanup.execute( _execute ); \
}
#else
#error ERROR [__FILE__, line __LINE__]: Cleanup type undefined.
#endif /* __CLEANUP_CXX */
#endif /* __CLEANUP_C */
#endif /* __CLEANUP_SEH */
/*
* ===============
* ===============
* Methods
* ===============
* ===============
*/
/*
* PThread Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_attr_init (pthread_attr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_destroy (pthread_attr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getdetachstate (const pthread_attr_t * attr,
int *detachstate);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstackaddr (const pthread_attr_t * attr,
void **stackaddr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstacksize (const pthread_attr_t * attr,
size_t * stacksize);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setdetachstate (pthread_attr_t * attr,
int detachstate);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstackaddr (pthread_attr_t * attr,
void *stackaddr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstacksize (pthread_attr_t * attr,
size_t stacksize);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedparam (const pthread_attr_t *attr,
struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedparam (pthread_attr_t *attr,
const struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedpolicy (pthread_attr_t *,
int);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedpolicy (pthread_attr_t *,
int *);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setinheritsched(pthread_attr_t * attr,
int inheritsched);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getinheritsched(pthread_attr_t * attr,
int * inheritsched);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setscope (pthread_attr_t *,
int);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getscope (const pthread_attr_t *,
int *);
/*
* PThread Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_create (pthread_t * tid,
const pthread_attr_t * attr,
void *(*start) (void *),
void *arg);
PTW32_DLLPORT int PTW32_CDECL pthread_detach (pthread_t tid);
PTW32_DLLPORT int PTW32_CDECL pthread_equal (pthread_t t1,
pthread_t t2);
PTW32_DLLPORT void PTW32_CDECL pthread_exit (void *value_ptr);
PTW32_DLLPORT int PTW32_CDECL pthread_join (pthread_t thread,
void **value_ptr);
PTW32_DLLPORT pthread_t PTW32_CDECL pthread_self (void);
PTW32_DLLPORT int PTW32_CDECL pthread_cancel (pthread_t thread);
PTW32_DLLPORT int PTW32_CDECL pthread_setcancelstate (int state,
int *oldstate);
PTW32_DLLPORT int PTW32_CDECL pthread_setcanceltype (int type,
int *oldtype);
PTW32_DLLPORT void PTW32_CDECL pthread_testcancel (void);
PTW32_DLLPORT int PTW32_CDECL pthread_once (pthread_once_t * once_control,
void (*init_routine) (void));
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
PTW32_DLLPORT ptw32_cleanup_t * PTW32_CDECL ptw32_pop_cleanup (int execute);
PTW32_DLLPORT void PTW32_CDECL ptw32_push_cleanup (ptw32_cleanup_t * cleanup,
void (*routine) (void *),
void *arg);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Thread Specific Data Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_key_create (pthread_key_t * key,
void (*destructor) (void *));
PTW32_DLLPORT int PTW32_CDECL pthread_key_delete (pthread_key_t key);
PTW32_DLLPORT int PTW32_CDECL pthread_setspecific (pthread_key_t key,
const void *value);
PTW32_DLLPORT void * PTW32_CDECL pthread_getspecific (pthread_key_t key);
/*
* Mutex Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_init (pthread_mutexattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_destroy (pthread_mutexattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getpshared (const pthread_mutexattr_t
* attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setpshared (pthread_mutexattr_t * attr,
int pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_settype (pthread_mutexattr_t * attr, int kind);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_gettype (pthread_mutexattr_t * attr, int *kind);
/*
* Barrier Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_init (pthread_barrierattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_destroy (pthread_barrierattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_getpshared (const pthread_barrierattr_t
* attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_setpshared (pthread_barrierattr_t * attr,
int pshared);
/*
* Mutex Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_init (pthread_mutex_t * mutex,
const pthread_mutexattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_destroy (pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_lock (pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_timedlock(pthread_mutex_t *mutex,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_trylock (pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_unlock (pthread_mutex_t * mutex);
/*
* Spinlock Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_spin_init (pthread_spinlock_t * lock, int pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_destroy (pthread_spinlock_t * lock);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_lock (pthread_spinlock_t * lock);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_trylock (pthread_spinlock_t * lock);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_unlock (pthread_spinlock_t * lock);
/*
* Barrier Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_init (pthread_barrier_t * barrier,
const pthread_barrierattr_t * attr,
unsigned int count);
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_destroy (pthread_barrier_t * barrier);
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_wait (pthread_barrier_t * barrier);
/*
* Condition Variable Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_init (pthread_condattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_destroy (pthread_condattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_getpshared (const pthread_condattr_t * attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_setpshared (pthread_condattr_t * attr,
int pshared);
/*
* Condition Variable Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_cond_init (pthread_cond_t * cond,
const pthread_condattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_destroy (pthread_cond_t * cond);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_wait (pthread_cond_t * cond,
pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_timedwait (pthread_cond_t * cond,
pthread_mutex_t * mutex,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_signal (pthread_cond_t * cond);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_broadcast (pthread_cond_t * cond);
/*
* Scheduling
*/
PTW32_DLLPORT int PTW32_CDECL pthread_setschedparam (pthread_t thread,
int policy,
const struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_getschedparam (pthread_t thread,
int *policy,
struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_setconcurrency (int);
PTW32_DLLPORT int PTW32_CDECL pthread_getconcurrency (void);
/*
* Read-Write Lock Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_init(pthread_rwlock_t *lock,
const pthread_rwlockattr_t *attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_destroy(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_tryrdlock(pthread_rwlock_t *);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_trywrlock(pthread_rwlock_t *);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_rdlock(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedrdlock(pthread_rwlock_t *lock,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_wrlock(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedwrlock(pthread_rwlock_t *lock,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_unlock(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_init (pthread_rwlockattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_destroy (pthread_rwlockattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_getpshared (const pthread_rwlockattr_t * attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_setpshared (pthread_rwlockattr_t * attr,
int pshared);
#if PTW32_LEVEL >= PTW32_LEVEL_MAX - 1
/*
* Signal Functions. Should be defined in <signal.h> but MSVC and MinGW32
* already have signal.h that don't define these.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_kill(pthread_t thread, int sig);
/*
* Non-portable functions
*/
/*
* Compatibility with Linux.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setkind_np(pthread_mutexattr_t * attr,
int kind);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getkind_np(pthread_mutexattr_t * attr,
int *kind);
/*
* Possibly supported by other POSIX threads implementations
*/
PTW32_DLLPORT int PTW32_CDECL pthread_delay_np (struct timespec * interval);
PTW32_DLLPORT int PTW32_CDECL pthread_num_processors_np(void);
/*
* Useful if an application wants to statically link
* the lib rather than load the DLL at run-time.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_attach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_detach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_attach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_detach_np(void);
/*
* Features that are auto-detected at load/run time.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_win32_test_features_np(int);
enum ptw32_features {
PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE = 0x0001, /* System provides it. */
PTW32_ALERTABLE_ASYNC_CANCEL = 0x0002 /* Can cancel blocked threads. */
};
/*
* Register a system time change with the library.
* Causes the library to perform various functions
* in response to the change. Should be called whenever
* the application's top level window receives a
* WM_TIMECHANGE message. It can be passed directly to
* pthread_create() as a new thread if desired.
*/
PTW32_DLLPORT void * PTW32_CDECL pthread_timechange_handler_np(void *);
#endif /*PTW32_LEVEL >= PTW32_LEVEL_MAX - 1 */
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
/*
* Returns the Win32 HANDLE for the POSIX thread.
*/
PTW32_DLLPORT HANDLE PTW32_CDECL pthread_getw32threadhandle_np(pthread_t thread);
/*
* Protected Methods
*
* This function blocks until the given WIN32 handle
* is signaled or pthread_cancel had been called.
* This function allows the caller to hook into the
* PThreads cancel mechanism. It is implemented using
*
* WaitForMultipleObjects
*
* on 'waitHandle' and a manually reset WIN32 Event
* used to implement pthread_cancel. The 'timeout'
* argument to TimedWait is simply passed to
* WaitForMultipleObjects.
*/
PTW32_DLLPORT int PTW32_CDECL pthreadCancelableWait (HANDLE waitHandle);
PTW32_DLLPORT int PTW32_CDECL pthreadCancelableTimedWait (HANDLE waitHandle,
DWORD timeout);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Thread-Safe C Runtime Library Mappings.
*/
#ifndef _UWIN
# if defined(NEED_ERRNO)
PTW32_DLLPORT int * PTW32_CDECL _errno( void );
# else
# ifndef errno
# if (defined(_MT) || defined(_DLL))
__declspec(dllimport) extern int * __cdecl _errno(void);
# define errno (*_errno())
# endif
# endif
# endif
#endif
/*
* WIN32 C runtime library had been made thread-safe
* without affecting the user interface. Provide
* mappings from the UNIX thread-safe versions to
* the standard C runtime library calls.
* Only provide function mappings for functions that
* actually exist on WIN32.
*/
#if !defined(__MINGW32__)
#define strtok_r( _s, _sep, _lasts ) \
( *(_lasts) = strtok( (_s), (_sep) ) )
#endif /* !__MINGW32__ */
#define asctime_r( _tm, _buf ) \
( strcpy( (_buf), asctime( (_tm) ) ), \
(_buf) )
#define ctime_r( _clock, _buf ) \
( strcpy( (_buf), ctime( (_clock) ) ), \
(_buf) )
#define gmtime_r( _clock, _result ) \
( *(_result) = *gmtime( (_clock) ), \
(_result) )
#define localtime_r( _clock, _result ) \
( *(_result) = *localtime( (_clock) ), \
(_result) )
#define rand_r( _seed ) \
( _seed == _seed? rand() : rand() )
/*
* Some compiler environments don't define some things.
*/
#if defined(__BORLANDC__)
# define _ftime ftime
# define _timeb timeb
#endif
#ifdef __cplusplus
/*
* Internal exceptions
*/
class ptw32_exception {};
class ptw32_exception_cancel : public ptw32_exception {};
class ptw32_exception_exit : public ptw32_exception {};
#endif
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
/* FIXME: This is only required if the library was built using SEH */
/*
* Get internal SEH tag
*/
PTW32_DLLPORT DWORD PTW32_CDECL ptw32_get_exception_services_code(void);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
#ifndef PTW32_BUILD
#ifdef __CLEANUP_SEH
/*
* Redefine the SEH __except keyword to ensure that applications
* propagate our internal exceptions up to the library's internal handlers.
*/
#define __except( E ) \
__except( ( GetExceptionCode() == ptw32_get_exception_services_code() ) \
? EXCEPTION_CONTINUE_SEARCH : ( E ) )
#endif /* __CLEANUP_SEH */
#ifdef __CLEANUP_CXX
/*
* Redefine the C++ catch keyword to ensure that applications
* propagate our internal exceptions up to the library's internal handlers.
*/
#ifdef _MSC_VER
/*
* WARNING: Replace any 'catch( ... )' with 'PtW32CatchAll'
* if you want Pthread-Win32 cancelation and pthread_exit to work.
*/
#ifndef PtW32NoCatchWarn
#pragma message("Specify \"/DPtW32NoCatchWarn\" compiler flag to skip this message.")
#pragma message("------------------------------------------------------------------")
#pragma message("When compiling applications with MSVC++ and C++ exception handling:")
#pragma message(" Replace any 'catch( ... )' in routines called from POSIX threads")
#pragma message(" with 'PtW32CatchAll' or 'CATCHALL' if you want POSIX thread")
#pragma message(" cancelation and pthread_exit to work. For example:")
#pragma message("")
#pragma message(" #ifdef PtW32CatchAll")
#pragma message(" PtW32CatchAll")
#pragma message(" #else")
#pragma message(" catch(...)")
#pragma message(" #endif")
#pragma message(" {")
#pragma message(" /* Catchall block processing */")
#pragma message(" }")
#pragma message("------------------------------------------------------------------")
#endif
#define PtW32CatchAll \
catch( ptw32_exception & ) { throw; } \
catch( ... )
#else /* _MSC_VER */
#define catch( E ) \
catch( ptw32_exception & ) { throw; } \
catch( E )
#endif /* _MSC_VER */
#endif /* __CLEANUP_CXX */
#endif /* ! PTW32_BUILD */
#ifdef __cplusplus
} /* End of extern "C" */
#endif /* __cplusplus */
#ifdef PTW32__HANDLE_DEF
# undef HANDLE
#endif
#ifdef PTW32__DWORD_DEF
# undef DWORD
#endif
#undef PTW32_LEVEL
#undef PTW32_LEVEL_MAX
#endif /* ! RC_INVOKED */
#endif /* PTHREAD_H */
| [
"saqibakhtar@23c756db-88ba-2448-99d7-e6e4c676ec84"
] | [
[
[
1,
1368
]
]
] |
277a29963c7e62c2f49a7d1f50f3ccfed8ccc790 | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/UILayer/CtrlEx/TabItem_MainTabBn.h | 83578b658fc6f0575c798eeb31e17420439ef77f | [] | 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 | WINDOWS-1252 | C++ | false | false | 709 | h | #pragma once
// CTabItem_MainTabBn ÃüÁîÄ¿±ê
#include "TabItem.h"
class CTabItem_MainTabBn : public CTabItem
{
DECLARE_DYNCREATE(CTabItem_MainTabBn)
public:
CTabItem_MainTabBn();
virtual ~CTabItem_MainTabBn();
virtual int GetDesireLength(void){return 20;}
virtual void Paint(CDC* pDC);
virtual void OnLButtonDown(UINT nFlags, CPoint point);
virtual void OnMouseHover(void);
virtual void OnMouseLeave(void);
protected:
virtual BOOL CanActive(){return FALSE;}
protected:
void DrawActiveBk(CDC* pDC, const CRect &rect);
void DrawInactiveBk(CDC* pDC, const CRect &rect);
void DrawHover(CDC* pDC, const CRect &rect);
void DrawTriangle(CDC* pDC, CRect &rect);
}; | [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
] | [
[
[
1,
28
]
]
] |
a8a36182f304a717f1efff4645455d2b6aef83f3 | 8b506bf34b36af04fa970f2749e0c8033f1a9d7a | /Code/C++/enDList.cpp | 6f9db02be26aff887d2e1ceb3cb427a2bcf1f7c9 | [] | 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 | 22 | cpp | #include "enDList.h"
| [
"[email protected]"
] | [
[
[
1,
1
]
]
] |
beccfd05a1a2cf05993efbd658b7287e0725b5b1 | 64d7fa49d314ce17ffb7f7610a8f290656b27459 | /Dogfight/EventListener.h | 180bcbae1881c400168f7a614296bd61cd29f5bd | [] | no_license | DavidVondras/dogfight2d | 7aa684cb2e53c1a56eeb2c3ce132010b1c920259 | 8853878ba05440d1a091cb8eb772dc75aad9e87c | refs/heads/master | 2020-06-08T06:54:04.541288 | 2010-06-22T12:23:44 | 2010-06-22T12:23:44 | 41,377,872 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,238 | h | #ifndef EVENTLISTENER_H
#define EVENTLISTENER_H
#include <SFML\Window.hpp>
///
/// Input events interface
///
class EventListener
{
private:
int _inputClose,
_inputLeft,
_inputRight,
_inputUp,
_inputDown,
_inputPropNum,
_inputPropNumValue,
_inputZoomIn,
_inputZoomOut;
sf::RenderWindow* const _renderWindow;
public:
//Initialization
EventListener(sf::RenderWindow* const renderWindow)
:_renderWindow(renderWindow),
_inputPropNumValue(0),
_inputClose(false){}
~EventListener(void){}
//Render properties
float GetEllapsedTime(void) const { return _renderWindow->GetFrameTime(); }
//Input Properties
int GetInputClose(void) const { return _inputClose; }
int GetInputLeft(void) const { return _inputLeft; }
int GetInputRight(void) const { return _inputRight; }
int GetInputUp(void) const { return _inputUp; }
int GetInputDown(void) const { return _inputDown; }
int GetInputPropNum(void) const { return _inputPropNum; }
int GetInputPropNumValue(void) const { return _inputPropNumValue; }
int GetInputZoomIn(void) const { return _inputZoomIn; }
int GetInputZoomOut(void) const { return _inputZoomOut; }
//Methods
void CheckEvents(void);
};
#endif | [
"charles.hetier@5302af2b-d63e-2d39-01d7-87716617f583"
] | [
[
[
1,
50
]
]
] |
49eb8b85ad3d61f13b7cf524c866a4b22f7834e8 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Interface/WndMapEx.h | 71da475379e5c694d57e334bd6d846325ad62bee | [] | no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,029 | h | #ifndef __WND_MAP_EX_H__
#define __WND_MAP_EX_H__
#ifdef __IMPROVE_MAP_SYSTEM
#ifdef __CLIENT
#include "TeleportationIconInfo.h"
#include "WndUserMarkNameChanger.h"
class CWndMapEx : public CWndNeuz
{
public:
enum ConstructionMode { NORMAL, TELEPORTATION, DESTINATION };
public:
CWndMapEx( void );
~CWndMapEx( void );
public:
virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK );
virtual void OnInitialUpdate( void );
virtual BOOL Process( void );
virtual void OnDraw( C2DRender* p2DRender );
virtual void PaintFrame( C2DRender* p2DRender );
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void SetWndRect( CRect rectWnd, BOOL bOnSize = TRUE );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
virtual void OnRButtonDown( UINT nFlags, CPoint point );
public:
void SetConstructionMode( ConstructionMode eConstructionMode );
void InitializeTeleportationInformation( CMover* const pFocusMover );
void UpdateDestinationPosition( void );
private:
void InitializeMapComboBoxSelecting( void );
void ResetMapInformation( void );
void ResetNPCPosition( void );
void RearrangeComboBoxData( DWORD dwParentSelectedListItemData, DWORD dwComboBoxWIDC , MapComboBoxDataVector* pMapComboBoxDataVector );
void ProcessMapSizeInformation( void );
void ProcessMonsterInformationToolTip( void );
void ProcessUserMarkToolTip( void );
void ProcessIconTextureAlpha( void );
void RenderPlayerPosition( C2DRender* p2DRender, CTexture* pArrowTexture, const D3DXVECTOR3& vPlayerPosition, const D3DXVECTOR3& vCameraPosition, const CString& strName, DWORD dwNameColor );
void RenderMapMonsterInformation( C2DRender* p2DRender );
void RenderRainbowNPCInformation( C2DRender* p2DRender );
void RenderTeleportationPosition( C2DRender* p2DRender );
void RenderDestinationPosition( C2DRender* p2DRender );
void RenderNPCPosition( C2DRender* p2DRender );
void RenderUserMarkPosition( C2DRender* p2DRender );
FLOAT CalculateMapIconRectFromPoint( CRect& rectDestinationIcon, FLOAT fIconPositionX, FLOAT fIconPositionY, const CTexture* const pIconTexture, FLOAT fIconSizeRatio );
FLOAT CalculateMapIconStartPosition( CPoint& pointDestinationPosition, FLOAT fIconPositionX, FLOAT fIconPositionY, const CTexture* const pIconTexture, FLOAT fIconSizeRatio );
const D3DXVECTOR3& ConvertPosition( D3DXVECTOR3& vDestination, const D3DXVECTOR3& vSource, BYTE byLocationID );
const D3DXVECTOR3& ReconvertPosition( D3DXVECTOR3& vDestination, const D3DXVECTOR3& vSource, BYTE byLocationID );
const CRect& ReviseScriptRectInformation( CRect& rectDestination, const CRect& rectSource );
BYTE CWndMapEx::GetMapArea( const D3DXVECTOR3& vPlayerPosition );
void CalculateMaximumWindowTileLength( void );
private:
enum { MINIMUM_ICON_TEXTURE_ALPHA = 0, MAXIMUM_ICON_TEXTURE_ALPHA = 255 };
enum { NORMAL_STATE_ALPHA = 255, TRANSPARENT_STATE_ALPHA = 125 };
enum
{
ID_USER_MARK_MENU_DELETE = 0,
ID_USER_MARK_MENU_DELETE_ALL = 1,
ID_USER_MARK_MENU_INSERT_CHATTING_WINDOW = 2,
ID_USER_MARK_MENU_CHANGE_NAME = 3,
};
private:
static const FLOAT SOURCE_MAP_SIZE_X;
static const FLOAT SOURCE_MAP_SIZE_Y;
static const FLOAT ANIMATION_SPEED;
static const FLOAT TELEPORTATION_POSITION_TEXTURE_SIZE_RATIO;
static const FLOAT EXTEND_RATIO;
static const FLOAT EXTEND_TELEPORTATION_POSITION_TEXTURE_SIZE_RATIO;
static const FLOAT DESTINATION_POSITION_TEXTURE_SIZE_RATIO;
static const FLOAT NPC_POSITION_TEXTURE_SIZE_RATIO;
static const FLOAT USER_MARK_POSITION_TEXTURE_SIZE_RATIO;
static const int WINDOW_TILE_TEXTURE_SIZE_XY;
static const int MINIMUM_WINDOW_TILE_NUMBER_X;
static const int MINIMUM_WINDOW_TILE_NUMBER_Y;
private:
ConstructionMode m_eConstructionMode;
CTexture* m_pPCArrowTexture;
CTexture* m_pPartyPCArrowTexture;
CTexture* m_pMapTexture;
CTexture* m_pTeleportationPositionTexture;
CTexture* m_pDestinationPositionTexture;
CTexture* m_pNPCPositionTexture;
CTexture* m_pUserMarkPositionTexture;
FLOAT m_fRevisedMapSizeRatio;
CRect m_rectRevisedMapPosition;
DWORD m_dwSelectedMapID;
BYTE m_bySelectedMapLocationID;
BOOL m_bMonsterInformationToolTip;
int m_nSelectedMonsterIconIndex;
DWORD m_dwSelectedUserMarkID;
int m_nIconTextureAlpha;
DWORD m_tmOld;
BOOL m_bAlphaSwitch;
OBJID m_idTeleporter;
vector< TeleportationIconInfo* > m_vecTeleportationPositionRect;
FLOAT m_fDestinationPositionX;
FLOAT m_fDestinationPositionY;
FLOAT m_fNPCPositionX;
FLOAT m_fNPCPositionY;
BOOL m_bMapComboBoxInitialization;
BYTE m_byTransparentStateAlpha;
CWndMenu m_WndMenuUserMark;
CWndUserMarkNameChanger* m_pWndUserMarkNameChanger;
int m_nMinimumWindowTileWidth;
int m_nMinimumWindowTileHeight;
int m_nMaximumWindowTileWidth;
int m_nMaximumWindowTileHeight;
};
#endif // __CLIENT
#endif // __IMPROVE_MAP_SYSTEM
#endif // __WND_MAP_EX_H__ | [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
121
]
]
] |
ed80e6fdecf3158f64d323da0bdd9724c6c548a3 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/AranMath/ArnVec4.h | 663a08a49cfdec24b2539d242793bcd7e971625b | [] | no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | h | #pragma once
class ArnVec3;
class ARANMATH_API ArnVec4
{
public:
float x, y, z, w;
ArnVec4() : x(0), y(0), z(0), w(0) {}
ArnVec4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) {}
ArnVec4(const ArnVec3& vec3, float _w) : x(vec3.x), y(vec3.y), z(vec3.z), w(_w) {}
float operator[](size_t i) const { switch(i) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: ARN_THROW_UNEXPECTED_CASE_ERROR } }
const float* getRawData() const { return (const float*)&x; }
void printFormatString() const
{
printf("(x %6.3f, y %6.3f, z %6.3f, w %6.3f)\n", x, y, z, w);
}
};
ARANMATH_API ArnVec4 CreateArnVec4(float x, float y, float z, float w);
| [
"[email protected]"
] | [
[
[
1,
23
]
]
] |
3f674af3645a0008b30569e00dddf4a26455397a | 99527557aee4f1db979a7627e77bd7d644098411 | /utils/textdrawer.h | 5aa0427800ed4f87c3f6f889a838904ad0b01664 | [] | no_license | GunioRobot/2deffects | 7aeb02400090bb7118d23f1fc435ffbdd4417c59 | 39d8e335102d6a51cab0d47a3a2dc7686d7a7c67 | refs/heads/master | 2021-01-18T14:10:32.049756 | 2008-09-15T15:56:50 | 2008-09-15T15:56:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | h | #ifndef _TEXTDRAWER_H_
#define _TEXTDRAWER_H_
namespace syd {
class Bitmap;
class PlainBmp;
class TextDrawer {
unsigned char_width_, char_height_;
Bitmap& font_bmp_;
public:
TextDrawer ( Bitmap& font_bmp, unsigned char_width, unsigned char_height );
~TextDrawer();
public:
TextDrawer& draw ( Bitmap& destbmp, unsigned x, unsigned y, const char* text );
};
} //syd
#endif //!defined(_TEXTDRAWER_H_) | [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
106186df752eb89abbc9ba88396120a8e912958f | 7f4230cae41e0712d5942960674bfafe4cccd1f1 | /code/IFCReaderGen.h | d2f979e46a0a12741ebaac7cf589dfadf0dc665b | [
"BSD-3-Clause"
] | permissive | tonttu/assimp | c6941538b3b3c3d66652423415dea098be21f37a | 320a7a7a7e0422e4d8d9c2a22b74cb48f74b14ce | refs/heads/master | 2021-01-16T19:56:09.309754 | 2011-06-07T20:00:41 | 2011-06-07T20:00:41 | 1,295,427 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 196,247 | h | /*
Open Asset Import Library (ASSIMP)
----------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team
All rights reserved.
Redistribution and use of this software 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 ASSIMP team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the ASSIMP Development Team.
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.
----------------------------------------------------------------------
*/
/** MACHINE-GENERATED by scripts/ICFImporter/CppGenerator.py */
#ifndef INCLUDED_IFC_READER_GEN_H
#define INCLUDED_IFC_READER_GEN_H
#include "STEPFile.h"
namespace Assimp {
namespace IFC {
using namespace STEP;
using namespace STEP::EXPRESS;
struct NotImplemented : public ObjectHelper<NotImplemented,0> {
};
// ******************************************************************************
// IFC Custom data types
// ******************************************************************************
// C++ wrapper type for IfcSoundPowerMeasure
typedef REAL IfcSoundPowerMeasure;
// C++ wrapper type for IfcDoorStyleOperationEnum
typedef ENUMERATION IfcDoorStyleOperationEnum;
// C++ wrapper type for IfcRotationalFrequencyMeasure
typedef REAL IfcRotationalFrequencyMeasure;
// C++ wrapper type for IfcCharacterStyleSelect
typedef SELECT IfcCharacterStyleSelect;
// C++ wrapper type for IfcElectricTimeControlTypeEnum
typedef ENUMERATION IfcElectricTimeControlTypeEnum;
// C++ wrapper type for IfcAirTerminalTypeEnum
typedef ENUMERATION IfcAirTerminalTypeEnum;
// C++ wrapper type for IfcProjectOrderTypeEnum
typedef ENUMERATION IfcProjectOrderTypeEnum;
// C++ wrapper type for IfcSequenceEnum
typedef ENUMERATION IfcSequenceEnum;
// C++ wrapper type for IfcSpecificHeatCapacityMeasure
typedef REAL IfcSpecificHeatCapacityMeasure;
// C++ wrapper type for IfcHeatingValueMeasure
typedef REAL IfcHeatingValueMeasure;
// C++ wrapper type for IfcRibPlateDirectionEnum
typedef ENUMERATION IfcRibPlateDirectionEnum;
// C++ wrapper type for IfcSensorTypeEnum
typedef ENUMERATION IfcSensorTypeEnum;
// C++ wrapper type for IfcElectricHeaterTypeEnum
typedef ENUMERATION IfcElectricHeaterTypeEnum;
// C++ wrapper type for IfcObjectiveEnum
typedef ENUMERATION IfcObjectiveEnum;
// C++ wrapper type for IfcTextStyleSelect
typedef SELECT IfcTextStyleSelect;
// C++ wrapper type for IfcColumnTypeEnum
typedef ENUMERATION IfcColumnTypeEnum;
// C++ wrapper type for IfcGasTerminalTypeEnum
typedef ENUMERATION IfcGasTerminalTypeEnum;
// C++ wrapper type for IfcMassDensityMeasure
typedef REAL IfcMassDensityMeasure;
// C++ wrapper type for IfcSimpleValue
typedef SELECT IfcSimpleValue;
// C++ wrapper type for IfcElectricConductanceMeasure
typedef REAL IfcElectricConductanceMeasure;
// C++ wrapper type for IfcBuildingElementProxyTypeEnum
typedef ENUMERATION IfcBuildingElementProxyTypeEnum;
// C++ wrapper type for IfcJunctionBoxTypeEnum
typedef ENUMERATION IfcJunctionBoxTypeEnum;
// C++ wrapper type for IfcModulusOfElasticityMeasure
typedef REAL IfcModulusOfElasticityMeasure;
// C++ wrapper type for IfcActionSourceTypeEnum
typedef ENUMERATION IfcActionSourceTypeEnum;
// C++ wrapper type for IfcSIUnitName
typedef ENUMERATION IfcSIUnitName;
// C++ wrapper type for IfcRotationalMassMeasure
typedef REAL IfcRotationalMassMeasure;
// C++ wrapper type for IfcMemberTypeEnum
typedef ENUMERATION IfcMemberTypeEnum;
// C++ wrapper type for IfcTextDecoration
typedef STRING IfcTextDecoration;
// C++ wrapper type for IfcPositiveLengthMeasure
typedef REAL IfcPositiveLengthMeasure;
// C++ wrapper type for IfcAmountOfSubstanceMeasure
typedef REAL IfcAmountOfSubstanceMeasure;
// C++ wrapper type for IfcDoorStyleConstructionEnum
typedef ENUMERATION IfcDoorStyleConstructionEnum;
// C++ wrapper type for IfcAngularVelocityMeasure
typedef REAL IfcAngularVelocityMeasure;
// C++ wrapper type for IfcDirectionSenseEnum
typedef ENUMERATION IfcDirectionSenseEnum;
// C++ wrapper type for IfcNullStyle
typedef ENUMERATION IfcNullStyle;
// C++ wrapper type for IfcMonthInYearNumber
typedef INTEGER IfcMonthInYearNumber;
// C++ wrapper type for IfcRampFlightTypeEnum
typedef ENUMERATION IfcRampFlightTypeEnum;
// C++ wrapper type for IfcWindowStyleOperationEnum
typedef ENUMERATION IfcWindowStyleOperationEnum;
// C++ wrapper type for IfcCurvatureMeasure
typedef REAL IfcCurvatureMeasure;
// C++ wrapper type for IfcBooleanOperator
typedef ENUMERATION IfcBooleanOperator;
// C++ wrapper type for IfcDuctFittingTypeEnum
typedef ENUMERATION IfcDuctFittingTypeEnum;
// C++ wrapper type for IfcCurrencyEnum
typedef ENUMERATION IfcCurrencyEnum;
// C++ wrapper type for IfcObjectTypeEnum
typedef ENUMERATION IfcObjectTypeEnum;
// C++ wrapper type for IfcThermalLoadTypeEnum
typedef ENUMERATION IfcThermalLoadTypeEnum;
// C++ wrapper type for IfcIonConcentrationMeasure
typedef REAL IfcIonConcentrationMeasure;
// C++ wrapper type for IfcObjectReferenceSelect
typedef SELECT IfcObjectReferenceSelect;
// C++ wrapper type for IfcClassificationNotationSelect
typedef SELECT IfcClassificationNotationSelect;
// C++ wrapper type for IfcBSplineCurveForm
typedef ENUMERATION IfcBSplineCurveForm;
// C++ wrapper type for IfcElementCompositionEnum
typedef ENUMERATION IfcElementCompositionEnum;
// C++ wrapper type for IfcDraughtingCalloutElement
typedef SELECT IfcDraughtingCalloutElement;
// C++ wrapper type for IfcFillStyleSelect
typedef SELECT IfcFillStyleSelect;
// C++ wrapper type for IfcHeatFluxDensityMeasure
typedef REAL IfcHeatFluxDensityMeasure;
// C++ wrapper type for IfcGeometricProjectionEnum
typedef ENUMERATION IfcGeometricProjectionEnum;
// C++ wrapper type for IfcFontVariant
typedef STRING IfcFontVariant;
// C++ wrapper type for IfcThermalResistanceMeasure
typedef REAL IfcThermalResistanceMeasure;
// C++ wrapper type for IfcReflectanceMethodEnum
typedef ENUMERATION IfcReflectanceMethodEnum;
// C++ wrapper type for IfcSlabTypeEnum
typedef ENUMERATION IfcSlabTypeEnum;
// C++ wrapper type for IfcPositiveRatioMeasure
typedef REAL IfcPositiveRatioMeasure;
// C++ wrapper type for IfcInternalOrExternalEnum
typedef ENUMERATION IfcInternalOrExternalEnum;
// C++ wrapper type for IfcDimensionExtentUsage
typedef ENUMERATION IfcDimensionExtentUsage;
// C++ wrapper type for IfcPipeFittingTypeEnum
typedef ENUMERATION IfcPipeFittingTypeEnum;
// C++ wrapper type for IfcSanitaryTerminalTypeEnum
typedef ENUMERATION IfcSanitaryTerminalTypeEnum;
// C++ wrapper type for IfcMinuteInHour
typedef INTEGER IfcMinuteInHour;
// C++ wrapper type for IfcWallTypeEnum
typedef ENUMERATION IfcWallTypeEnum;
// C++ wrapper type for IfcMolecularWeightMeasure
typedef REAL IfcMolecularWeightMeasure;
// C++ wrapper type for IfcUnitaryEquipmentTypeEnum
typedef ENUMERATION IfcUnitaryEquipmentTypeEnum;
// C++ wrapper type for IfcProcedureTypeEnum
typedef ENUMERATION IfcProcedureTypeEnum;
// C++ wrapper type for IfcDistributionChamberElementTypeEnum
typedef ENUMERATION IfcDistributionChamberElementTypeEnum;
// C++ wrapper type for IfcTextPath
typedef ENUMERATION IfcTextPath;
// C++ wrapper type for IfcCostScheduleTypeEnum
typedef ENUMERATION IfcCostScheduleTypeEnum;
// C++ wrapper type for IfcShell
typedef SELECT IfcShell;
// C++ wrapper type for IfcLinearMomentMeasure
typedef REAL IfcLinearMomentMeasure;
// C++ wrapper type for IfcElectricCurrentMeasure
typedef REAL IfcElectricCurrentMeasure;
// C++ wrapper type for IfcDaylightSavingHour
typedef INTEGER IfcDaylightSavingHour;
// C++ wrapper type for IfcNormalisedRatioMeasure
typedef REAL IfcNormalisedRatioMeasure;
// C++ wrapper type for IfcFanTypeEnum
typedef ENUMERATION IfcFanTypeEnum;
// C++ wrapper type for IfcContextDependentMeasure
typedef REAL IfcContextDependentMeasure;
// C++ wrapper type for IfcAheadOrBehind
typedef ENUMERATION IfcAheadOrBehind;
// C++ wrapper type for IfcFontStyle
typedef STRING IfcFontStyle;
// C++ wrapper type for IfcCooledBeamTypeEnum
typedef ENUMERATION IfcCooledBeamTypeEnum;
// C++ wrapper type for IfcSurfaceStyleElementSelect
typedef SELECT IfcSurfaceStyleElementSelect;
// C++ wrapper type for IfcYearNumber
typedef INTEGER IfcYearNumber;
// C++ wrapper type for IfcLabel
typedef STRING IfcLabel;
// C++ wrapper type for IfcTimeStamp
typedef INTEGER IfcTimeStamp;
// C++ wrapper type for IfcFireSuppressionTerminalTypeEnum
typedef ENUMERATION IfcFireSuppressionTerminalTypeEnum;
// C++ wrapper type for IfcDocumentConfidentialityEnum
typedef ENUMERATION IfcDocumentConfidentialityEnum;
// C++ wrapper type for IfcColourOrFactor
typedef SELECT IfcColourOrFactor;
// C++ wrapper type for IfcAirTerminalBoxTypeEnum
typedef ENUMERATION IfcAirTerminalBoxTypeEnum;
// C++ wrapper type for IfcNumericMeasure
typedef NUMBER IfcNumericMeasure;
// C++ wrapper type for IfcDerivedUnitEnum
typedef ENUMERATION IfcDerivedUnitEnum;
// C++ wrapper type for IfcCurveOrEdgeCurve
typedef SELECT IfcCurveOrEdgeCurve;
// C++ wrapper type for IfcLightEmissionSourceEnum
typedef ENUMERATION IfcLightEmissionSourceEnum;
// C++ wrapper type for IfcKinematicViscosityMeasure
typedef REAL IfcKinematicViscosityMeasure;
// C++ wrapper type for IfcBoxAlignment
typedef STRING IfcBoxAlignment;
// C++ wrapper type for IfcDocumentSelect
typedef SELECT IfcDocumentSelect;
// C++ wrapper type for IfcCableCarrierFittingTypeEnum
typedef ENUMERATION IfcCableCarrierFittingTypeEnum;
// C++ wrapper type for IfcPumpTypeEnum
typedef ENUMERATION IfcPumpTypeEnum;
// C++ wrapper type for IfcHourInDay
typedef INTEGER IfcHourInDay;
// C++ wrapper type for IfcProjectOrderRecordTypeEnum
typedef ENUMERATION IfcProjectOrderRecordTypeEnum;
// C++ wrapper type for IfcWindowStyleConstructionEnum
typedef ENUMERATION IfcWindowStyleConstructionEnum;
// C++ wrapper type for IfcPresentationStyleSelect
typedef SELECT IfcPresentationStyleSelect;
// C++ wrapper type for IfcCableSegmentTypeEnum
typedef ENUMERATION IfcCableSegmentTypeEnum;
// C++ wrapper type for IfcWasteTerminalTypeEnum
typedef ENUMERATION IfcWasteTerminalTypeEnum;
// C++ wrapper type for IfcIsothermalMoistureCapacityMeasure
typedef REAL IfcIsothermalMoistureCapacityMeasure;
// C++ wrapper type for IfcIdentifier
typedef STRING IfcIdentifier;
// C++ wrapper type for IfcRadioActivityMeasure
typedef REAL IfcRadioActivityMeasure;
// C++ wrapper type for IfcSymbolStyleSelect
typedef SELECT IfcSymbolStyleSelect;
// C++ wrapper type for IfcRoofTypeEnum
typedef ENUMERATION IfcRoofTypeEnum;
// C++ wrapper type for IfcReal
typedef REAL IfcReal;
// C++ wrapper type for IfcRoleEnum
typedef ENUMERATION IfcRoleEnum;
// C++ wrapper type for IfcMeasureValue
typedef SELECT IfcMeasureValue;
// C++ wrapper type for IfcPileTypeEnum
typedef ENUMERATION IfcPileTypeEnum;
// C++ wrapper type for IfcElectricCurrentEnum
typedef ENUMERATION IfcElectricCurrentEnum;
// C++ wrapper type for IfcTextTransformation
typedef STRING IfcTextTransformation;
// C++ wrapper type for IfcFilterTypeEnum
typedef ENUMERATION IfcFilterTypeEnum;
// C++ wrapper type for IfcTransformerTypeEnum
typedef ENUMERATION IfcTransformerTypeEnum;
// C++ wrapper type for IfcSurfaceSide
typedef ENUMERATION IfcSurfaceSide;
// C++ wrapper type for IfcThermalTransmittanceMeasure
typedef REAL IfcThermalTransmittanceMeasure;
// C++ wrapper type for IfcTubeBundleTypeEnum
typedef ENUMERATION IfcTubeBundleTypeEnum;
// C++ wrapper type for IfcLightFixtureTypeEnum
typedef ENUMERATION IfcLightFixtureTypeEnum;
// C++ wrapper type for IfcInductanceMeasure
typedef REAL IfcInductanceMeasure;
// C++ wrapper type for IfcGlobalOrLocalEnum
typedef ENUMERATION IfcGlobalOrLocalEnum;
// C++ wrapper type for IfcOutletTypeEnum
typedef ENUMERATION IfcOutletTypeEnum;
// C++ wrapper type for IfcWorkControlTypeEnum
typedef ENUMERATION IfcWorkControlTypeEnum;
// C++ wrapper type for IfcWarpingMomentMeasure
typedef REAL IfcWarpingMomentMeasure;
// C++ wrapper type for IfcDynamicViscosityMeasure
typedef REAL IfcDynamicViscosityMeasure;
// C++ wrapper type for IfcEnergySequenceEnum
typedef ENUMERATION IfcEnergySequenceEnum;
// C++ wrapper type for IfcFillAreaStyleTileShapeSelect
typedef SELECT IfcFillAreaStyleTileShapeSelect;
// C++ wrapper type for IfcPointOrVertexPoint
typedef SELECT IfcPointOrVertexPoint;
// C++ wrapper type for IfcVibrationIsolatorTypeEnum
typedef ENUMERATION IfcVibrationIsolatorTypeEnum;
// C++ wrapper type for IfcTankTypeEnum
typedef ENUMERATION IfcTankTypeEnum;
// C++ wrapper type for IfcTimeSeriesDataTypeEnum
typedef ENUMERATION IfcTimeSeriesDataTypeEnum;
// C++ wrapper type for IfcSurfaceTextureEnum
typedef ENUMERATION IfcSurfaceTextureEnum;
// C++ wrapper type for IfcAddressTypeEnum
typedef ENUMERATION IfcAddressTypeEnum;
// C++ wrapper type for IfcChillerTypeEnum
typedef ENUMERATION IfcChillerTypeEnum;
// C++ wrapper type for IfcLightDistributionCurveEnum
typedef ENUMERATION IfcLightDistributionCurveEnum;
// C++ wrapper type for IfcReinforcingBarRoleEnum
typedef ENUMERATION IfcReinforcingBarRoleEnum;
// C++ wrapper type for IfcResourceConsumptionEnum
typedef ENUMERATION IfcResourceConsumptionEnum;
// C++ wrapper type for IfcCsgSelect
typedef SELECT IfcCsgSelect;
// C++ wrapper type for IfcModulusOfLinearSubgradeReactionMeasure
typedef REAL IfcModulusOfLinearSubgradeReactionMeasure;
// C++ wrapper type for IfcEvaporatorTypeEnum
typedef ENUMERATION IfcEvaporatorTypeEnum;
// C++ wrapper type for IfcTimeSeriesScheduleTypeEnum
typedef ENUMERATION IfcTimeSeriesScheduleTypeEnum;
// C++ wrapper type for IfcDayInMonthNumber
typedef INTEGER IfcDayInMonthNumber;
// C++ wrapper type for IfcElectricMotorTypeEnum
typedef ENUMERATION IfcElectricMotorTypeEnum;
// C++ wrapper type for IfcThermalConductivityMeasure
typedef REAL IfcThermalConductivityMeasure;
// C++ wrapper type for IfcEnergyMeasure
typedef REAL IfcEnergyMeasure;
// C++ wrapper type for IfcRotationalStiffnessMeasure
typedef REAL IfcRotationalStiffnessMeasure;
// C++ wrapper type for IfcDerivedMeasureValue
typedef SELECT IfcDerivedMeasureValue;
// C++ wrapper type for IfcDoorPanelOperationEnum
typedef ENUMERATION IfcDoorPanelOperationEnum;
// C++ wrapper type for IfcCurveStyleFontSelect
typedef SELECT IfcCurveStyleFontSelect;
// C++ wrapper type for IfcWindowPanelOperationEnum
typedef ENUMERATION IfcWindowPanelOperationEnum;
// C++ wrapper type for IfcDataOriginEnum
typedef ENUMERATION IfcDataOriginEnum;
// C++ wrapper type for IfcStairTypeEnum
typedef ENUMERATION IfcStairTypeEnum;
// C++ wrapper type for IfcRailingTypeEnum
typedef ENUMERATION IfcRailingTypeEnum;
// C++ wrapper type for IfcPowerMeasure
typedef REAL IfcPowerMeasure;
// C++ wrapper type for IfcStackTerminalTypeEnum
typedef ENUMERATION IfcStackTerminalTypeEnum;
// C++ wrapper type for IfcHatchLineDistanceSelect
typedef SELECT IfcHatchLineDistanceSelect;
// C++ wrapper type for IfcTrimmingSelect
typedef SELECT IfcTrimmingSelect;
// C++ wrapper type for IfcThermalExpansionCoefficientMeasure
typedef REAL IfcThermalExpansionCoefficientMeasure;
// C++ wrapper type for IfcLightDistributionDataSourceSelect
typedef SELECT IfcLightDistributionDataSourceSelect;
// C++ wrapper type for IfcTorqueMeasure
typedef REAL IfcTorqueMeasure;
// C++ wrapper type for IfcMassPerLengthMeasure
typedef REAL IfcMassPerLengthMeasure;
// C++ wrapper type for IfcValveTypeEnum
typedef ENUMERATION IfcValveTypeEnum;
// C++ wrapper type for IfcWindowPanelPositionEnum
typedef ENUMERATION IfcWindowPanelPositionEnum;
// C++ wrapper type for IfcSurfaceOrFaceSurface
typedef SELECT IfcSurfaceOrFaceSurface;
// C++ wrapper type for IfcPropertySourceEnum
typedef ENUMERATION IfcPropertySourceEnum;
// C++ wrapper type for IfcCableCarrierSegmentTypeEnum
typedef ENUMERATION IfcCableCarrierSegmentTypeEnum;
// C++ wrapper type for IfcCountMeasure
typedef NUMBER IfcCountMeasure;
// C++ wrapper type for IfcFontWeight
typedef STRING IfcFontWeight;
// C++ wrapper type for IfcPhysicalOrVirtualEnum
typedef ENUMERATION IfcPhysicalOrVirtualEnum;
// C++ wrapper type for IfcSpaceTypeEnum
typedef ENUMERATION IfcSpaceTypeEnum;
// C++ wrapper type for IfcVolumetricFlowRateMeasure
typedef REAL IfcVolumetricFlowRateMeasure;
// C++ wrapper type for IfcLuminousFluxMeasure
typedef REAL IfcLuminousFluxMeasure;
// C++ wrapper type for IfcEvaporativeCoolerTypeEnum
typedef ENUMERATION IfcEvaporativeCoolerTypeEnum;
// C++ wrapper type for IfcLayeredItem
typedef SELECT IfcLayeredItem;
// C++ wrapper type for IfcModulusOfSubgradeReactionMeasure
typedef REAL IfcModulusOfSubgradeReactionMeasure;
// C++ wrapper type for IfcHeatExchangerTypeEnum
typedef ENUMERATION IfcHeatExchangerTypeEnum;
// C++ wrapper type for IfcProtectiveDeviceTypeEnum
typedef ENUMERATION IfcProtectiveDeviceTypeEnum;
// C++ wrapper type for IfcDamperTypeEnum
typedef ENUMERATION IfcDamperTypeEnum;
// C++ wrapper type for IfcControllerTypeEnum
typedef ENUMERATION IfcControllerTypeEnum;
// C++ wrapper type for IfcMassFlowRateMeasure
typedef REAL IfcMassFlowRateMeasure;
// C++ wrapper type for IfcAssemblyPlaceEnum
typedef ENUMERATION IfcAssemblyPlaceEnum;
// C++ wrapper type for IfcAreaMeasure
typedef REAL IfcAreaMeasure;
// C++ wrapper type for IfcServiceLifeFactorTypeEnum
typedef ENUMERATION IfcServiceLifeFactorTypeEnum;
// C++ wrapper type for IfcVolumeMeasure
typedef REAL IfcVolumeMeasure;
// C++ wrapper type for IfcBeamTypeEnum
typedef ENUMERATION IfcBeamTypeEnum;
// C++ wrapper type for IfcStateEnum
typedef ENUMERATION IfcStateEnum;
// C++ wrapper type for IfcSpaceHeaterTypeEnum
typedef ENUMERATION IfcSpaceHeaterTypeEnum;
// C++ wrapper type for IfcSectionTypeEnum
typedef ENUMERATION IfcSectionTypeEnum;
// C++ wrapper type for IfcFootingTypeEnum
typedef ENUMERATION IfcFootingTypeEnum;
// C++ wrapper type for IfcMonetaryMeasure
typedef REAL IfcMonetaryMeasure;
// C++ wrapper type for IfcLoadGroupTypeEnum
typedef ENUMERATION IfcLoadGroupTypeEnum;
// C++ wrapper type for IfcElectricGeneratorTypeEnum
typedef ENUMERATION IfcElectricGeneratorTypeEnum;
// C++ wrapper type for IfcFlowMeterTypeEnum
typedef ENUMERATION IfcFlowMeterTypeEnum;
// C++ wrapper type for IfcMaterialSelect
typedef SELECT IfcMaterialSelect;
// C++ wrapper type for IfcAnalysisModelTypeEnum
typedef ENUMERATION IfcAnalysisModelTypeEnum;
// C++ wrapper type for IfcTemperatureGradientMeasure
typedef REAL IfcTemperatureGradientMeasure;
// C++ wrapper type for IfcModulusOfRotationalSubgradeReactionMeasure
typedef REAL IfcModulusOfRotationalSubgradeReactionMeasure;
// C++ wrapper type for IfcColour
typedef SELECT IfcColour;
// C++ wrapper type for IfcCurtainWallTypeEnum
typedef ENUMERATION IfcCurtainWallTypeEnum;
// C++ wrapper type for IfcMetricValueSelect
typedef SELECT IfcMetricValueSelect;
// C++ wrapper type for IfcTextAlignment
typedef STRING IfcTextAlignment;
// C++ wrapper type for IfcDoorPanelPositionEnum
typedef ENUMERATION IfcDoorPanelPositionEnum;
// C++ wrapper type for IfcPlateTypeEnum
typedef ENUMERATION IfcPlateTypeEnum;
// C++ wrapper type for IfcSectionalAreaIntegralMeasure
typedef REAL IfcSectionalAreaIntegralMeasure;
// C++ wrapper type for IfcPresentableText
typedef STRING IfcPresentableText;
// C++ wrapper type for IfcVaporPermeabilityMeasure
typedef REAL IfcVaporPermeabilityMeasure;
// C++ wrapper type for IfcStructuralSurfaceTypeEnum
typedef ENUMERATION IfcStructuralSurfaceTypeEnum;
// C++ wrapper type for IfcLinearVelocityMeasure
typedef REAL IfcLinearVelocityMeasure;
// C++ wrapper type for IfcIntegerCountRateMeasure
typedef INTEGER IfcIntegerCountRateMeasure;
// C++ wrapper type for IfcAirToAirHeatRecoveryTypeEnum
typedef ENUMERATION IfcAirToAirHeatRecoveryTypeEnum;
// C++ wrapper type for IfcDocumentStatusEnum
typedef ENUMERATION IfcDocumentStatusEnum;
// C++ wrapper type for IfcLengthMeasure
typedef REAL IfcLengthMeasure;
// C++ wrapper type for IfcPlanarForceMeasure
typedef REAL IfcPlanarForceMeasure;
// C++ wrapper type for IfcBooleanOperand
typedef SELECT IfcBooleanOperand;
// C++ wrapper type for IfcInteger
typedef INTEGER IfcInteger;
// C++ wrapper type for IfcRampTypeEnum
typedef ENUMERATION IfcRampTypeEnum;
// C++ wrapper type for IfcActorSelect
typedef SELECT IfcActorSelect;
// C++ wrapper type for IfcElectricChargeMeasure
typedef REAL IfcElectricChargeMeasure;
// C++ wrapper type for IfcGeometricSetSelect
typedef SELECT IfcGeometricSetSelect;
// C++ wrapper type for IfcConnectionTypeEnum
typedef ENUMERATION IfcConnectionTypeEnum;
// C++ wrapper type for IfcValue
typedef SELECT IfcValue;
// C++ wrapper type for IfcCoolingTowerTypeEnum
typedef ENUMERATION IfcCoolingTowerTypeEnum;
// C++ wrapper type for IfcPlaneAngleMeasure
typedef REAL IfcPlaneAngleMeasure;
// C++ wrapper type for IfcSwitchingDeviceTypeEnum
typedef ENUMERATION IfcSwitchingDeviceTypeEnum;
// C++ wrapper type for IfcFlowDirectionEnum
typedef ENUMERATION IfcFlowDirectionEnum;
// C++ wrapper type for IfcThermalLoadSourceEnum
typedef ENUMERATION IfcThermalLoadSourceEnum;
// C++ wrapper type for IfcTextFontSelect
typedef SELECT IfcTextFontSelect;
// C++ wrapper type for IfcSpecularHighlightSelect
typedef SELECT IfcSpecularHighlightSelect;
// C++ wrapper type for IfcAnalysisTheoryTypeEnum
typedef ENUMERATION IfcAnalysisTheoryTypeEnum;
// C++ wrapper type for IfcTextFontName
typedef STRING IfcTextFontName;
// C++ wrapper type for IfcElectricVoltageMeasure
typedef REAL IfcElectricVoltageMeasure;
// C++ wrapper type for IfcTendonTypeEnum
typedef ENUMERATION IfcTendonTypeEnum;
// C++ wrapper type for IfcSoundPressureMeasure
typedef REAL IfcSoundPressureMeasure;
// C++ wrapper type for IfcElectricDistributionPointFunctionEnum
typedef ENUMERATION IfcElectricDistributionPointFunctionEnum;
// C++ wrapper type for IfcSpecularRoughness
typedef REAL IfcSpecularRoughness;
// C++ wrapper type for IfcActionTypeEnum
typedef ENUMERATION IfcActionTypeEnum;
// C++ wrapper type for IfcReinforcingBarSurfaceEnum
typedef ENUMERATION IfcReinforcingBarSurfaceEnum;
// C++ wrapper type for IfcHumidifierTypeEnum
typedef ENUMERATION IfcHumidifierTypeEnum;
// C++ wrapper type for IfcIlluminanceMeasure
typedef REAL IfcIlluminanceMeasure;
// C++ wrapper type for IfcLibrarySelect
typedef SELECT IfcLibrarySelect;
// C++ wrapper type for IfcText
typedef STRING IfcText;
// C++ wrapper type for IfcLayerSetDirectionEnum
typedef ENUMERATION IfcLayerSetDirectionEnum;
// C++ wrapper type for IfcBoilerTypeEnum
typedef ENUMERATION IfcBoilerTypeEnum;
// C++ wrapper type for IfcTimeMeasure
typedef REAL IfcTimeMeasure;
// C++ wrapper type for IfcAccelerationMeasure
typedef REAL IfcAccelerationMeasure;
// C++ wrapper type for IfcElectricFlowStorageDeviceTypeEnum
typedef ENUMERATION IfcElectricFlowStorageDeviceTypeEnum;
// C++ wrapper type for IfcLuminousIntensityMeasure
typedef REAL IfcLuminousIntensityMeasure;
// C++ wrapper type for IfcDefinedSymbolSelect
typedef SELECT IfcDefinedSymbolSelect;
// C++ wrapper type for IfcUnitEnum
typedef ENUMERATION IfcUnitEnum;
// C++ wrapper type for IfcInventoryTypeEnum
typedef ENUMERATION IfcInventoryTypeEnum;
// C++ wrapper type for IfcStructuralActivityAssignmentSelect
typedef SELECT IfcStructuralActivityAssignmentSelect;
// C++ wrapper type for IfcElementAssemblyTypeEnum
typedef ENUMERATION IfcElementAssemblyTypeEnum;
// C++ wrapper type for IfcServiceLifeTypeEnum
typedef ENUMERATION IfcServiceLifeTypeEnum;
// C++ wrapper type for IfcCoveringTypeEnum
typedef ENUMERATION IfcCoveringTypeEnum;
// C++ wrapper type for IfcStairFlightTypeEnum
typedef ENUMERATION IfcStairFlightTypeEnum;
// C++ wrapper type for IfcSIPrefix
typedef ENUMERATION IfcSIPrefix;
// C++ wrapper type for IfcElectricCapacitanceMeasure
typedef REAL IfcElectricCapacitanceMeasure;
// C++ wrapper type for IfcFlowInstrumentTypeEnum
typedef ENUMERATION IfcFlowInstrumentTypeEnum;
// C++ wrapper type for IfcThermodynamicTemperatureMeasure
typedef REAL IfcThermodynamicTemperatureMeasure;
// C++ wrapper type for IfcGloballyUniqueId
typedef STRING IfcGloballyUniqueId;
// C++ wrapper type for IfcLampTypeEnum
typedef ENUMERATION IfcLampTypeEnum;
// C++ wrapper type for IfcMagneticFluxMeasure
typedef REAL IfcMagneticFluxMeasure;
// C++ wrapper type for IfcSolidAngleMeasure
typedef REAL IfcSolidAngleMeasure;
// C++ wrapper type for IfcFrequencyMeasure
typedef REAL IfcFrequencyMeasure;
// C++ wrapper type for IfcTransportElementTypeEnum
typedef ENUMERATION IfcTransportElementTypeEnum;
// C++ wrapper type for IfcSoundScaleEnum
typedef ENUMERATION IfcSoundScaleEnum;
// C++ wrapper type for IfcPHMeasure
typedef REAL IfcPHMeasure;
// C++ wrapper type for IfcActuatorTypeEnum
typedef ENUMERATION IfcActuatorTypeEnum;
// C++ wrapper type for IfcPositivePlaneAngleMeasure
typedef REAL IfcPositivePlaneAngleMeasure;
// C++ wrapper type for IfcAppliedValueSelect
typedef SELECT IfcAppliedValueSelect;
// C++ wrapper type for IfcSecondInMinute
typedef REAL IfcSecondInMinute;
// C++ wrapper type for IfcDuctSegmentTypeEnum
typedef ENUMERATION IfcDuctSegmentTypeEnum;
// C++ wrapper type for IfcThermalAdmittanceMeasure
typedef REAL IfcThermalAdmittanceMeasure;
// C++ wrapper type for IfcSpecularExponent
typedef REAL IfcSpecularExponent;
// C++ wrapper type for IfcDateTimeSelect
typedef SELECT IfcDateTimeSelect;
// C++ wrapper type for IfcTransitionCode
typedef ENUMERATION IfcTransitionCode;
// C++ wrapper type for IfcDimensionCount
typedef INTEGER IfcDimensionCount;
// C++ wrapper type for IfcLinearStiffnessMeasure
typedef REAL IfcLinearStiffnessMeasure;
// C++ wrapper type for IfcCompoundPlaneAngleMeasure
typedef ListOf< INTEGER, 3, 3 > IfcCompoundPlaneAngleMeasure;
// C++ wrapper type for IfcElectricApplianceTypeEnum
typedef ENUMERATION IfcElectricApplianceTypeEnum;
// C++ wrapper type for IfcProfileTypeEnum
typedef ENUMERATION IfcProfileTypeEnum;
// C++ wrapper type for IfcCurveFontOrScaledCurveFontSelect
typedef SELECT IfcCurveFontOrScaledCurveFontSelect;
// C++ wrapper type for IfcProjectedOrTrueLengthEnum
typedef ENUMERATION IfcProjectedOrTrueLengthEnum;
// C++ wrapper type for IfcAbsorbedDoseMeasure
typedef REAL IfcAbsorbedDoseMeasure;
// C++ wrapper type for IfcParameterValue
typedef REAL IfcParameterValue;
// C++ wrapper type for IfcPileConstructionEnum
typedef ENUMERATION IfcPileConstructionEnum;
// C++ wrapper type for IfcMotorConnectionTypeEnum
typedef ENUMERATION IfcMotorConnectionTypeEnum;
// C++ wrapper type for IfcOccupantTypeEnum
typedef ENUMERATION IfcOccupantTypeEnum;
// C++ wrapper type for IfcUnit
typedef SELECT IfcUnit;
// C++ wrapper type for IfcLinearForceMeasure
typedef REAL IfcLinearForceMeasure;
// C++ wrapper type for IfcCondenserTypeEnum
typedef ENUMERATION IfcCondenserTypeEnum;
// C++ wrapper type for IfcDescriptiveMeasure
typedef STRING IfcDescriptiveMeasure;
// C++ wrapper type for IfcMomentOfInertiaMeasure
typedef REAL IfcMomentOfInertiaMeasure;
// C++ wrapper type for IfcDoseEquivalentMeasure
typedef REAL IfcDoseEquivalentMeasure;
// C++ wrapper type for IfcOrientationSelect
typedef SELECT IfcOrientationSelect;
// C++ wrapper type for IfcLogical
typedef LOGICAL IfcLogical;
// C++ wrapper type for IfcSizeSelect
typedef SELECT IfcSizeSelect;
// C++ wrapper type for IfcEnvironmentalImpactCategoryEnum
typedef ENUMERATION IfcEnvironmentalImpactCategoryEnum;
// C++ wrapper type for IfcLogicalOperatorEnum
typedef ENUMERATION IfcLogicalOperatorEnum;
// C++ wrapper type for IfcCompressorTypeEnum
typedef ENUMERATION IfcCompressorTypeEnum;
// C++ wrapper type for IfcBenchmarkEnum
typedef ENUMERATION IfcBenchmarkEnum;
// C++ wrapper type for IfcRatioMeasure
typedef REAL IfcRatioMeasure;
// C++ wrapper type for IfcVectorOrDirection
typedef SELECT IfcVectorOrDirection;
// C++ wrapper type for IfcConstraintEnum
typedef ENUMERATION IfcConstraintEnum;
// C++ wrapper type for IfcAlarmTypeEnum
typedef ENUMERATION IfcAlarmTypeEnum;
// C++ wrapper type for IfcLuminousIntensityDistributionMeasure
typedef REAL IfcLuminousIntensityDistributionMeasure;
// C++ wrapper type for IfcArithmeticOperatorEnum
typedef ENUMERATION IfcArithmeticOperatorEnum;
// C++ wrapper type for IfcAxis2Placement
typedef SELECT IfcAxis2Placement;
// C++ wrapper type for IfcForceMeasure
typedef REAL IfcForceMeasure;
// C++ wrapper type for IfcTrimmingPreference
typedef ENUMERATION IfcTrimmingPreference;
// C++ wrapper type for IfcElectricResistanceMeasure
typedef REAL IfcElectricResistanceMeasure;
// C++ wrapper type for IfcWarpingConstantMeasure
typedef REAL IfcWarpingConstantMeasure;
// C++ wrapper type for IfcPipeSegmentTypeEnum
typedef ENUMERATION IfcPipeSegmentTypeEnum;
// C++ wrapper type for IfcConditionCriterionSelect
typedef SELECT IfcConditionCriterionSelect;
// C++ wrapper type for IfcShearModulusMeasure
typedef REAL IfcShearModulusMeasure;
// C++ wrapper type for IfcPressureMeasure
typedef REAL IfcPressureMeasure;
// C++ wrapper type for IfcDuctSilencerTypeEnum
typedef ENUMERATION IfcDuctSilencerTypeEnum;
// C++ wrapper type for IfcBoolean
typedef BOOLEAN IfcBoolean;
// C++ wrapper type for IfcSectionModulusMeasure
typedef REAL IfcSectionModulusMeasure;
// C++ wrapper type for IfcChangeActionEnum
typedef ENUMERATION IfcChangeActionEnum;
// C++ wrapper type for IfcCoilTypeEnum
typedef ENUMERATION IfcCoilTypeEnum;
// C++ wrapper type for IfcMassMeasure
typedef REAL IfcMassMeasure;
// C++ wrapper type for IfcStructuralCurveTypeEnum
typedef ENUMERATION IfcStructuralCurveTypeEnum;
// C++ wrapper type for IfcPermeableCoveringOperationEnum
typedef ENUMERATION IfcPermeableCoveringOperationEnum;
// C++ wrapper type for IfcMagneticFluxDensityMeasure
typedef REAL IfcMagneticFluxDensityMeasure;
// C++ wrapper type for IfcMoistureDiffusivityMeasure
typedef REAL IfcMoistureDiffusivityMeasure;
// ******************************************************************************
// IFC Entities
// ******************************************************************************
struct IfcRoot;
struct IfcObjectDefinition;
struct IfcTypeObject;
struct IfcTypeProduct;
struct IfcElementType;
struct IfcFurnishingElementType;
struct IfcFurnitureType;
struct IfcObject;
struct IfcProduct;
struct IfcGrid;
struct IfcRepresentationItem;
struct IfcGeometricRepresentationItem;
struct IfcOneDirectionRepeatFactor;
struct IfcTwoDirectionRepeatFactor;
struct IfcElement;
struct IfcElementComponent;
typedef NotImplemented IfcLocalTime; // (not currently used by Assimp)
struct IfcSpatialStructureElementType;
struct IfcControl;
struct IfcActionRequest;
typedef NotImplemented IfcTextureVertex; // (not currently used by Assimp)
typedef NotImplemented IfcPropertyDefinition; // (not currently used by Assimp)
typedef NotImplemented IfcPropertySetDefinition; // (not currently used by Assimp)
typedef NotImplemented IfcFluidFlowProperties; // (not currently used by Assimp)
typedef NotImplemented IfcDocumentInformation; // (not currently used by Assimp)
typedef NotImplemented IfcCalendarDate; // (not currently used by Assimp)
struct IfcDistributionElementType;
struct IfcDistributionFlowElementType;
struct IfcEnergyConversionDeviceType;
struct IfcCooledBeamType;
struct IfcCsgPrimitive3D;
struct IfcRectangularPyramid;
typedef NotImplemented IfcStructuralLoad; // (not currently used by Assimp)
typedef NotImplemented IfcStructuralLoadStatic; // (not currently used by Assimp)
typedef NotImplemented IfcStructuralLoadLinearForce; // (not currently used by Assimp)
struct IfcSurface;
struct IfcBoundedSurface;
struct IfcRectangularTrimmedSurface;
typedef NotImplemented IfcPhysicalQuantity; // (not currently used by Assimp)
typedef NotImplemented IfcPhysicalSimpleQuantity; // (not currently used by Assimp)
typedef NotImplemented IfcQuantityVolume; // (not currently used by Assimp)
typedef NotImplemented IfcQuantityArea; // (not currently used by Assimp)
struct IfcGroup;
struct IfcRelationship;
typedef NotImplemented IfcRelAssigns; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssignsToActor; // (not currently used by Assimp)
struct IfcHalfSpaceSolid;
struct IfcPolygonalBoundedHalfSpace;
typedef NotImplemented IfcEnergyProperties; // (not currently used by Assimp)
struct IfcAirToAirHeatRecoveryType;
struct IfcFlowFittingType;
struct IfcPipeFittingType;
struct IfcRepresentation;
struct IfcStyleModel;
struct IfcStyledRepresentation;
typedef NotImplemented IfcRelAssignsToControl; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssignsToProjectOrder; // (not currently used by Assimp)
typedef NotImplemented IfcDimensionalExponents; // (not currently used by Assimp)
struct IfcBooleanResult;
typedef NotImplemented IfcSoundProperties; // (not currently used by Assimp)
struct IfcFeatureElement;
struct IfcFeatureElementSubtraction;
struct IfcOpeningElement;
struct IfcConditionCriterion;
struct IfcFlowTerminalType;
struct IfcFlowControllerType;
struct IfcSwitchingDeviceType;
struct IfcSystem;
struct IfcElectricalCircuit;
typedef NotImplemented IfcActorRole; // (not currently used by Assimp)
typedef NotImplemented IfcDateAndTime; // (not currently used by Assimp)
typedef NotImplemented IfcDraughtingCalloutRelationship; // (not currently used by Assimp)
typedef NotImplemented IfcDimensionCalloutRelationship; // (not currently used by Assimp)
typedef NotImplemented IfcDerivedUnitElement; // (not currently used by Assimp)
typedef NotImplemented IfcExternalReference; // (not currently used by Assimp)
typedef NotImplemented IfcClassificationReference; // (not currently used by Assimp)
struct IfcUnitaryEquipmentType;
typedef NotImplemented IfcProperty; // (not currently used by Assimp)
struct IfcPort;
typedef NotImplemented IfcAddress; // (not currently used by Assimp)
struct IfcPlacement;
typedef NotImplemented IfcPreDefinedItem; // (not currently used by Assimp)
typedef NotImplemented IfcPreDefinedColour; // (not currently used by Assimp)
typedef NotImplemented IfcDraughtingPreDefinedColour; // (not currently used by Assimp)
struct IfcProfileDef;
struct IfcArbitraryClosedProfileDef;
struct IfcCurve;
struct IfcConic;
struct IfcCircle;
typedef NotImplemented IfcAppliedValue; // (not currently used by Assimp)
typedef NotImplemented IfcEnvironmentalImpactValue; // (not currently used by Assimp)
typedef NotImplemented IfcSimpleProperty; // (not currently used by Assimp)
typedef NotImplemented IfcPropertySingleValue; // (not currently used by Assimp)
struct IfcElementarySurface;
struct IfcPlane;
typedef NotImplemented IfcPropertyBoundedValue; // (not currently used by Assimp)
struct IfcCostSchedule;
typedef NotImplemented IfcMonetaryUnit; // (not currently used by Assimp)
typedef NotImplemented IfcConnectionGeometry; // (not currently used by Assimp)
typedef NotImplemented IfcConnectionCurveGeometry; // (not currently used by Assimp)
struct IfcRightCircularCone;
struct IfcElementAssembly;
struct IfcBuildingElement;
struct IfcMember;
typedef NotImplemented IfcPropertyDependencyRelationship; // (not currently used by Assimp)
struct IfcBuildingElementProxy;
struct IfcStructuralActivity;
struct IfcStructuralAction;
struct IfcStructuralPlanarAction;
struct IfcTopologicalRepresentationItem;
struct IfcConnectedFaceSet;
struct IfcSweptSurface;
struct IfcSurfaceOfLinearExtrusion;
struct IfcArbitraryProfileDefWithVoids;
struct IfcProcess;
struct IfcProcedure;
typedef NotImplemented IfcCurveStyleFontPattern; // (not currently used by Assimp)
struct IfcVector;
struct IfcFaceBound;
struct IfcFaceOuterBound;
struct IfcFeatureElementAddition;
struct IfcNamedUnit;
struct IfcConversionBasedUnit;
typedef NotImplemented IfcStructuralLoadSingleForce; // (not currently used by Assimp)
struct IfcHeatExchangerType;
struct IfcPresentationStyleAssignment;
struct IfcFlowTreatmentDeviceType;
struct IfcFilterType;
struct IfcResource;
struct IfcEvaporativeCoolerType;
typedef NotImplemented IfcTextureCoordinate; // (not currently used by Assimp)
typedef NotImplemented IfcTextureCoordinateGenerator; // (not currently used by Assimp)
struct IfcOffsetCurve2D;
struct IfcEdge;
struct IfcSubedge;
struct IfcProxy;
struct IfcLine;
struct IfcColumn;
typedef NotImplemented IfcClassificationNotationFacet; // (not currently used by Assimp)
struct IfcObjectPlacement;
struct IfcGridPlacement;
struct IfcDistributionControlElementType;
typedef NotImplemented IfcStructuralLoadSingleForceWarping; // (not currently used by Assimp)
typedef NotImplemented IfcExternallyDefinedTextFont; // (not currently used by Assimp)
struct IfcRelConnects;
typedef NotImplemented IfcRelConnectsElements; // (not currently used by Assimp)
typedef NotImplemented IfcRelConnectsWithRealizingElements; // (not currently used by Assimp)
typedef NotImplemented IfcConstraintClassificationRelationship; // (not currently used by Assimp)
struct IfcAnnotation;
struct IfcPlate;
struct IfcSolidModel;
struct IfcManifoldSolidBrep;
typedef NotImplemented IfcPreDefinedCurveFont; // (not currently used by Assimp)
typedef NotImplemented IfcBoundaryCondition; // (not currently used by Assimp)
typedef NotImplemented IfcBoundaryFaceCondition; // (not currently used by Assimp)
struct IfcFlowStorageDeviceType;
struct IfcStructuralItem;
struct IfcStructuralMember;
struct IfcStructuralCurveMember;
struct IfcStructuralConnection;
struct IfcStructuralSurfaceConnection;
struct IfcCoilType;
struct IfcDuctFittingType;
struct IfcStyledItem;
struct IfcAnnotationOccurrence;
struct IfcAnnotationCurveOccurrence;
struct IfcDimensionCurve;
struct IfcBoundedCurve;
struct IfcAxis1Placement;
typedef NotImplemented IfcLightIntensityDistribution; // (not currently used by Assimp)
typedef NotImplemented IfcPreDefinedSymbol; // (not currently used by Assimp)
struct IfcStructuralPointAction;
struct IfcSpatialStructureElement;
struct IfcSpace;
typedef NotImplemented IfcContextDependentUnit; // (not currently used by Assimp)
typedef NotImplemented IfcVirtualGridIntersection; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssociates; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssociatesClassification; // (not currently used by Assimp)
struct IfcCoolingTowerType;
typedef NotImplemented IfcMaterialProperties; // (not currently used by Assimp)
typedef NotImplemented IfcGeneralMaterialProperties; // (not currently used by Assimp)
struct IfcFacetedBrepWithVoids;
typedef NotImplemented IfcProfileProperties; // (not currently used by Assimp)
typedef NotImplemented IfcGeneralProfileProperties; // (not currently used by Assimp)
typedef NotImplemented IfcStructuralProfileProperties; // (not currently used by Assimp)
struct IfcValveType;
struct IfcSystemFurnitureElementType;
struct IfcDiscreteAccessory;
typedef NotImplemented IfcPerson; // (not currently used by Assimp)
struct IfcBuildingElementType;
struct IfcRailingType;
struct IfcGasTerminalType;
typedef NotImplemented IfcTimeSeries; // (not currently used by Assimp)
typedef NotImplemented IfcIrregularTimeSeries; // (not currently used by Assimp)
struct IfcSpaceProgram;
struct IfcCovering;
typedef NotImplemented IfcShapeAspect; // (not currently used by Assimp)
struct IfcPresentationStyle;
typedef NotImplemented IfcClassificationItemRelationship; // (not currently used by Assimp)
struct IfcElectricHeaterType;
struct IfcBuildingStorey;
struct IfcVertex;
struct IfcVertexPoint;
struct IfcFlowInstrumentType;
struct IfcParameterizedProfileDef;
struct IfcUShapeProfileDef;
struct IfcRamp;
typedef NotImplemented IfcFillAreaStyle; // (not currently used by Assimp)
struct IfcCompositeCurve;
typedef NotImplemented IfcRelServicesBuildings; // (not currently used by Assimp)
struct IfcStructuralCurveMemberVarying;
typedef NotImplemented IfcRelReferencedInSpatialStructure; // (not currently used by Assimp)
struct IfcRampFlightType;
struct IfcDraughtingCallout;
struct IfcDimensionCurveDirectedCallout;
struct IfcRadiusDimension;
struct IfcEdgeFeature;
struct IfcSweptAreaSolid;
struct IfcExtrudedAreaSolid;
typedef NotImplemented IfcQuantityCount; // (not currently used by Assimp)
struct IfcAnnotationTextOccurrence;
typedef NotImplemented IfcReferencesValueDocument; // (not currently used by Assimp)
struct IfcStair;
typedef NotImplemented IfcSymbolStyle; // (not currently used by Assimp)
struct IfcFillAreaStyleTileSymbolWithStyle;
struct IfcAnnotationSymbolOccurrence;
struct IfcTerminatorSymbol;
struct IfcDimensionCurveTerminator;
struct IfcRectangleProfileDef;
struct IfcRectangleHollowProfileDef;
typedef NotImplemented IfcRelAssociatesLibrary; // (not currently used by Assimp)
struct IfcLocalPlacement;
typedef NotImplemented IfcOpticalMaterialProperties; // (not currently used by Assimp)
typedef NotImplemented IfcServiceLifeFactor; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssignsTasks; // (not currently used by Assimp)
struct IfcTask;
struct IfcAnnotationFillAreaOccurrence;
struct IfcFace;
struct IfcFlowSegmentType;
struct IfcDuctSegmentType;
typedef NotImplemented IfcPropertyEnumeration; // (not currently used by Assimp)
struct IfcConstructionResource;
struct IfcConstructionEquipmentResource;
struct IfcSanitaryTerminalType;
typedef NotImplemented IfcPreDefinedDimensionSymbol; // (not currently used by Assimp)
typedef NotImplemented IfcOrganization; // (not currently used by Assimp)
struct IfcCircleProfileDef;
struct IfcStructuralReaction;
struct IfcStructuralPointReaction;
struct IfcRailing;
struct IfcTextLiteral;
struct IfcCartesianTransformationOperator;
typedef NotImplemented IfcCostValue; // (not currently used by Assimp)
typedef NotImplemented IfcTextStyle; // (not currently used by Assimp)
struct IfcLinearDimension;
struct IfcDamperType;
struct IfcSIUnit;
typedef NotImplemented IfcSurfaceStyleLighting; // (not currently used by Assimp)
struct IfcMeasureWithUnit;
typedef NotImplemented IfcMaterialLayerSet; // (not currently used by Assimp)
struct IfcDistributionElement;
struct IfcDistributionControlElement;
struct IfcTransformerType;
struct IfcLaborResource;
typedef NotImplemented IfcDerivedProfileDef; // (not currently used by Assimp)
typedef NotImplemented IfcRelConnectsStructuralMember; // (not currently used by Assimp)
typedef NotImplemented IfcRelConnectsWithEccentricity; // (not currently used by Assimp)
struct IfcFurnitureStandard;
struct IfcStairFlightType;
struct IfcWorkControl;
struct IfcWorkPlan;
typedef NotImplemented IfcRelDefines; // (not currently used by Assimp)
typedef NotImplemented IfcRelDefinesByProperties; // (not currently used by Assimp)
struct IfcCondition;
typedef NotImplemented IfcGridAxis; // (not currently used by Assimp)
struct IfcRelVoidsElement;
struct IfcWindow;
typedef NotImplemented IfcRelFlowControlElements; // (not currently used by Assimp)
typedef NotImplemented IfcRelConnectsPortToElement; // (not currently used by Assimp)
struct IfcProtectiveDeviceType;
struct IfcJunctionBoxType;
struct IfcStructuralAnalysisModel;
struct IfcAxis2Placement2D;
struct IfcSpaceType;
struct IfcEllipseProfileDef;
struct IfcDistributionFlowElement;
struct IfcFlowMovingDevice;
struct IfcSurfaceStyleWithTextures;
struct IfcGeometricSet;
typedef NotImplemented IfcMechanicalMaterialProperties; // (not currently used by Assimp)
typedef NotImplemented IfcMechanicalConcreteMaterialProperties; // (not currently used by Assimp)
typedef NotImplemented IfcRibPlateProfileProperties; // (not currently used by Assimp)
typedef NotImplemented IfcDocumentInformationRelationship; // (not currently used by Assimp)
struct IfcProjectOrder;
struct IfcBSplineCurve;
struct IfcBezierCurve;
struct IfcStructuralPointConnection;
struct IfcFlowController;
struct IfcElectricDistributionPoint;
struct IfcSite;
struct IfcOffsetCurve3D;
typedef NotImplemented IfcPropertySet; // (not currently used by Assimp)
typedef NotImplemented IfcConnectionSurfaceGeometry; // (not currently used by Assimp)
struct IfcVirtualElement;
struct IfcConstructionProductResource;
typedef NotImplemented IfcWaterProperties; // (not currently used by Assimp)
struct IfcSurfaceCurveSweptAreaSolid;
typedef NotImplemented IfcPermeableCoveringProperties; // (not currently used by Assimp)
struct IfcCartesianTransformationOperator3D;
struct IfcCartesianTransformationOperator3DnonUniform;
struct IfcCrewResource;
struct IfcStructuralSurfaceMember;
struct Ifc2DCompositeCurve;
struct IfcRepresentationContext;
struct IfcGeometricRepresentationContext;
struct IfcFlowTreatmentDevice;
typedef NotImplemented IfcTextStyleForDefinedFont; // (not currently used by Assimp)
struct IfcRightCircularCylinder;
struct IfcWasteTerminalType;
typedef NotImplemented IfcSpaceThermalLoadProperties; // (not currently used by Assimp)
typedef NotImplemented IfcConstraintRelationship; // (not currently used by Assimp)
struct IfcBuildingElementComponent;
struct IfcBuildingElementPart;
struct IfcWall;
struct IfcWallStandardCase;
typedef NotImplemented IfcApprovalActorRelationship; // (not currently used by Assimp)
struct IfcPath;
struct IfcDefinedSymbol;
struct IfcStructuralSurfaceMemberVarying;
struct IfcPoint;
struct IfcSurfaceOfRevolution;
struct IfcFlowTerminal;
struct IfcFurnishingElement;
typedef NotImplemented IfcCurveStyleFont; // (not currently used by Assimp)
struct IfcSurfaceStyleShading;
struct IfcSurfaceStyleRendering;
typedef NotImplemented IfcCoordinatedUniversalTimeOffset; // (not currently used by Assimp)
typedef NotImplemented IfcStructuralLoadSingleDisplacement; // (not currently used by Assimp)
struct IfcCircleHollowProfileDef;
struct IfcFlowMovingDeviceType;
struct IfcFanType;
struct IfcStructuralPlanarActionVarying;
struct IfcProductRepresentation;
typedef NotImplemented IfcRelDefinesByType; // (not currently used by Assimp)
typedef NotImplemented IfcPreDefinedTextFont; // (not currently used by Assimp)
typedef NotImplemented IfcTextStyleFontModel; // (not currently used by Assimp)
struct IfcStackTerminalType;
typedef NotImplemented IfcApprovalPropertyRelationship; // (not currently used by Assimp)
typedef NotImplemented IfcExternallyDefinedSymbol; // (not currently used by Assimp)
struct IfcReinforcingElement;
struct IfcReinforcingMesh;
struct IfcOrderAction;
typedef NotImplemented IfcRelCoversBldgElements; // (not currently used by Assimp)
struct IfcLightSource;
struct IfcLightSourceDirectional;
struct IfcLoop;
struct IfcVertexLoop;
struct IfcChamferEdgeFeature;
typedef NotImplemented IfcWindowPanelProperties; // (not currently used by Assimp)
typedef NotImplemented IfcClassification; // (not currently used by Assimp)
struct IfcElementComponentType;
struct IfcFastenerType;
struct IfcMechanicalFastenerType;
struct IfcScheduleTimeControl;
struct IfcSurfaceStyle;
typedef NotImplemented IfcReinforcementBarProperties; // (not currently used by Assimp)
struct IfcOpenShell;
typedef NotImplemented IfcLibraryReference; // (not currently used by Assimp)
struct IfcSubContractResource;
typedef NotImplemented IfcTimeSeriesReferenceRelationship; // (not currently used by Assimp)
struct IfcSweptDiskSolid;
typedef NotImplemented IfcCompositeProfileDef; // (not currently used by Assimp)
typedef NotImplemented IfcElectricalBaseProperties; // (not currently used by Assimp)
typedef NotImplemented IfcPreDefinedPointMarkerSymbol; // (not currently used by Assimp)
struct IfcTankType;
typedef NotImplemented IfcBoundaryNodeCondition; // (not currently used by Assimp)
typedef NotImplemented IfcBoundaryNodeConditionWarping; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssignsToGroup; // (not currently used by Assimp)
typedef NotImplemented IfcPresentationLayerAssignment; // (not currently used by Assimp)
struct IfcSphere;
struct IfcPolyLoop;
struct IfcCableCarrierFittingType;
struct IfcHumidifierType;
typedef NotImplemented IfcPropertyListValue; // (not currently used by Assimp)
typedef NotImplemented IfcPropertyConstraintRelationship; // (not currently used by Assimp)
struct IfcPerformanceHistory;
struct IfcShapeModel;
struct IfcTopologyRepresentation;
struct IfcBuilding;
struct IfcRoundedRectangleProfileDef;
struct IfcStairFlight;
typedef NotImplemented IfcSurfaceStyleRefraction; // (not currently used by Assimp)
typedef NotImplemented IfcRelInteractionRequirements; // (not currently used by Assimp)
typedef NotImplemented IfcConstraint; // (not currently used by Assimp)
typedef NotImplemented IfcObjective; // (not currently used by Assimp)
typedef NotImplemented IfcConnectionPortGeometry; // (not currently used by Assimp)
struct IfcDistributionChamberElement;
typedef NotImplemented IfcPersonAndOrganization; // (not currently used by Assimp)
struct IfcShapeRepresentation;
struct IfcRampFlight;
struct IfcBeamType;
struct IfcRelDecomposes;
struct IfcRoof;
struct IfcFooting;
typedef NotImplemented IfcRelCoversSpaces; // (not currently used by Assimp)
struct IfcLightSourceAmbient;
typedef NotImplemented IfcTimeSeriesValue; // (not currently used by Assimp)
struct IfcWindowStyle;
typedef NotImplemented IfcPropertyReferenceValue; // (not currently used by Assimp)
typedef NotImplemented IfcApproval; // (not currently used by Assimp)
typedef NotImplemented IfcRelConnectsStructuralElement; // (not currently used by Assimp)
struct IfcBuildingElementProxyType;
typedef NotImplemented IfcRelAssociatesProfileProperties; // (not currently used by Assimp)
struct IfcAxis2Placement3D;
typedef NotImplemented IfcRelConnectsPorts; // (not currently used by Assimp)
struct IfcEdgeCurve;
struct IfcClosedShell;
struct IfcTendonAnchor;
struct IfcCondenserType;
typedef NotImplemented IfcQuantityTime; // (not currently used by Assimp)
typedef NotImplemented IfcSurfaceTexture; // (not currently used by Assimp)
typedef NotImplemented IfcPixelTexture; // (not currently used by Assimp)
typedef NotImplemented IfcStructuralConnectionCondition; // (not currently used by Assimp)
typedef NotImplemented IfcFailureConnectionCondition; // (not currently used by Assimp)
typedef NotImplemented IfcDocumentReference; // (not currently used by Assimp)
typedef NotImplemented IfcMechanicalSteelMaterialProperties; // (not currently used by Assimp)
struct IfcPipeSegmentType;
struct IfcPointOnSurface;
typedef NotImplemented IfcTable; // (not currently used by Assimp)
typedef NotImplemented IfcLightDistributionData; // (not currently used by Assimp)
typedef NotImplemented IfcPropertyTableValue; // (not currently used by Assimp)
typedef NotImplemented IfcPresentationLayerWithStyle; // (not currently used by Assimp)
struct IfcAsset;
struct IfcLightSourcePositional;
typedef NotImplemented IfcLibraryInformation; // (not currently used by Assimp)
typedef NotImplemented IfcTextStyleTextModel; // (not currently used by Assimp)
struct IfcProjectionCurve;
struct IfcFillAreaStyleTiles;
typedef NotImplemented IfcRelFillsElement; // (not currently used by Assimp)
struct IfcElectricMotorType;
struct IfcTendon;
struct IfcDistributionChamberElementType;
struct IfcMemberType;
struct IfcStructuralLinearAction;
struct IfcStructuralLinearActionVarying;
struct IfcProductDefinitionShape;
struct IfcFastener;
struct IfcMechanicalFastener;
typedef NotImplemented IfcFuelProperties; // (not currently used by Assimp)
struct IfcEvaporatorType;
typedef NotImplemented IfcMaterialLayerSetUsage; // (not currently used by Assimp)
struct IfcDiscreteAccessoryType;
struct IfcStructuralCurveConnection;
struct IfcProjectionElement;
typedef NotImplemented IfcImageTexture; // (not currently used by Assimp)
struct IfcCoveringType;
typedef NotImplemented IfcRelAssociatesAppliedValue; // (not currently used by Assimp)
struct IfcPumpType;
struct IfcPile;
struct IfcUnitAssignment;
struct IfcBoundingBox;
struct IfcShellBasedSurfaceModel;
struct IfcFacetedBrep;
struct IfcTextLiteralWithExtent;
typedef NotImplemented IfcApplication; // (not currently used by Assimp)
typedef NotImplemented IfcExtendedMaterialProperties; // (not currently used by Assimp)
struct IfcElectricApplianceType;
typedef NotImplemented IfcRelOccupiesSpaces; // (not currently used by Assimp)
struct IfcTrapeziumProfileDef;
typedef NotImplemented IfcQuantityWeight; // (not currently used by Assimp)
struct IfcRelContainedInSpatialStructure;
struct IfcEdgeLoop;
struct IfcProject;
struct IfcCartesianPoint;
typedef NotImplemented IfcMaterial; // (not currently used by Assimp)
struct IfcCurveBoundedPlane;
struct IfcWallType;
struct IfcFillAreaStyleHatching;
struct IfcEquipmentStandard;
typedef NotImplemented IfcHygroscopicMaterialProperties; // (not currently used by Assimp)
typedef NotImplemented IfcDoorPanelProperties; // (not currently used by Assimp)
struct IfcDiameterDimension;
struct IfcStructuralLoadGroup;
typedef NotImplemented IfcTelecomAddress; // (not currently used by Assimp)
struct IfcConstructionMaterialResource;
typedef NotImplemented IfcBlobTexture; // (not currently used by Assimp)
typedef NotImplemented IfcIrregularTimeSeriesValue; // (not currently used by Assimp)
struct IfcRelAggregates;
struct IfcBoilerType;
typedef NotImplemented IfcRelProjectsElement; // (not currently used by Assimp)
struct IfcColourSpecification;
struct IfcColourRgb;
typedef NotImplemented IfcRelConnectsStructuralActivity; // (not currently used by Assimp)
struct IfcDoorStyle;
typedef NotImplemented IfcStructuralLoadSingleDisplacementDistortion; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssignsToProcess; // (not currently used by Assimp)
struct IfcDuctSilencerType;
struct IfcLightSourceGoniometric;
struct IfcActuatorType;
struct IfcSensorType;
struct IfcAirTerminalBoxType;
struct IfcAnnotationSurfaceOccurrence;
struct IfcZShapeProfileDef;
typedef NotImplemented IfcClassificationNotation; // (not currently used by Assimp)
struct IfcRationalBezierCurve;
struct IfcCartesianTransformationOperator2D;
struct IfcCartesianTransformationOperator2DnonUniform;
struct IfcMove;
typedef NotImplemented IfcBoundaryEdgeCondition; // (not currently used by Assimp)
typedef NotImplemented IfcDoorLiningProperties; // (not currently used by Assimp)
struct IfcCableCarrierSegmentType;
typedef NotImplemented IfcPostalAddress; // (not currently used by Assimp)
typedef NotImplemented IfcRelConnectsPathElements; // (not currently used by Assimp)
struct IfcElectricalElement;
typedef NotImplemented IfcOwnerHistory; // (not currently used by Assimp)
typedef NotImplemented IfcStructuralLoadTemperature; // (not currently used by Assimp)
typedef NotImplemented IfcTextStyleWithBoxCharacteristics; // (not currently used by Assimp)
struct IfcChillerType;
typedef NotImplemented IfcRelSchedulesCostItems; // (not currently used by Assimp)
struct IfcReinforcingBar;
typedef NotImplemented IfcCurrencyRelationship; // (not currently used by Assimp)
typedef NotImplemented IfcSoundValue; // (not currently used by Assimp)
struct IfcCShapeProfileDef;
struct IfcPermit;
struct IfcSlabType;
typedef NotImplemented IfcSlippageConnectionCondition; // (not currently used by Assimp)
struct IfcLampType;
struct IfcPlanarExtent;
struct IfcAlarmType;
typedef NotImplemented IfcDocumentElectronicFormat; // (not currently used by Assimp)
struct IfcElectricFlowStorageDeviceType;
struct IfcEquipmentElement;
struct IfcLightFixtureType;
typedef NotImplemented IfcMetric; // (not currently used by Assimp)
typedef NotImplemented IfcRelNests; // (not currently used by Assimp)
struct IfcCurtainWall;
typedef NotImplemented IfcRelAssociatesDocument; // (not currently used by Assimp)
typedef NotImplemented IfcComplexProperty; // (not currently used by Assimp)
typedef NotImplemented IfcVertexBasedTextureMap; // (not currently used by Assimp)
struct IfcSlab;
struct IfcCurtainWallType;
struct IfcOutletType;
struct IfcCompressorType;
struct IfcCraneRailAShapeProfileDef;
struct IfcFlowSegment;
struct IfcSectionedSpine;
typedef NotImplemented IfcTableRow; // (not currently used by Assimp)
typedef NotImplemented IfcDraughtingPreDefinedTextFont; // (not currently used by Assimp)
struct IfcElectricTimeControlType;
struct IfcFaceSurface;
typedef NotImplemented IfcMaterialList; // (not currently used by Assimp)
struct IfcMotorConnectionType;
struct IfcFlowFitting;
struct IfcPointOnCurve;
struct IfcTransportElementType;
typedef NotImplemented IfcRegularTimeSeries; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssociatesConstraint; // (not currently used by Assimp)
typedef NotImplemented IfcPropertyEnumeratedValue; // (not currently used by Assimp)
typedef NotImplemented IfcStructuralSteelProfileProperties; // (not currently used by Assimp)
struct IfcCableSegmentType;
typedef NotImplemented IfcExternallyDefinedHatchStyle; // (not currently used by Assimp)
struct IfcAnnotationSurface;
struct IfcCompositeCurveSegment;
struct IfcServiceLife;
struct IfcPlateType;
typedef NotImplemented IfcCurveStyle; // (not currently used by Assimp)
typedef NotImplemented IfcSectionProperties; // (not currently used by Assimp)
struct IfcVibrationIsolatorType;
typedef NotImplemented IfcTextureMap; // (not currently used by Assimp)
struct IfcTrimmedCurve;
struct IfcMappedItem;
typedef NotImplemented IfcMaterialLayer; // (not currently used by Assimp)
struct IfcDirection;
struct IfcBlock;
struct IfcProjectOrderRecord;
struct IfcFlowMeterType;
struct IfcControllerType;
struct IfcBeam;
struct IfcArbitraryOpenProfileDef;
struct IfcCenterLineProfileDef;
typedef NotImplemented IfcStructuralLoadPlanarForce; // (not currently used by Assimp)
struct IfcTimeSeriesSchedule;
struct IfcRoundedEdgeFeature;
typedef NotImplemented IfcWindowLiningProperties; // (not currently used by Assimp)
typedef NotImplemented IfcRelOverridesProperties; // (not currently used by Assimp)
typedef NotImplemented IfcApprovalRelationship; // (not currently used by Assimp)
struct IfcIShapeProfileDef;
struct IfcSpaceHeaterType;
typedef NotImplemented IfcExternallyDefinedSurfaceStyle; // (not currently used by Assimp)
typedef NotImplemented IfcDerivedUnit; // (not currently used by Assimp)
struct IfcFlowStorageDevice;
typedef NotImplemented IfcMaterialClassificationRelationship; // (not currently used by Assimp)
typedef NotImplemented IfcClassificationItem; // (not currently used by Assimp)
struct IfcRevolvedAreaSolid;
typedef NotImplemented IfcConnectionPointGeometry; // (not currently used by Assimp)
struct IfcDoor;
struct IfcEllipse;
struct IfcTubeBundleType;
struct IfcAngularDimension;
typedef NotImplemented IfcThermalMaterialProperties; // (not currently used by Assimp)
struct IfcFaceBasedSurfaceModel;
struct IfcCraneRailFShapeProfileDef;
struct IfcColumnType;
struct IfcTShapeProfileDef;
struct IfcEnergyConversionDevice;
typedef NotImplemented IfcConnectionPointEccentricity; // (not currently used by Assimp)
typedef NotImplemented IfcReinforcementDefinitionProperties; // (not currently used by Assimp)
typedef NotImplemented IfcCurveStyleFontAndScaling; // (not currently used by Assimp)
struct IfcWorkSchedule;
typedef NotImplemented IfcOrganizationRelationship; // (not currently used by Assimp)
struct IfcZone;
struct IfcTransportElement;
typedef NotImplemented IfcDraughtingPreDefinedCurveFont; // (not currently used by Assimp)
struct IfcGeometricRepresentationSubContext;
struct IfcLShapeProfileDef;
struct IfcGeometricCurveSet;
struct IfcActor;
struct IfcOccupant;
typedef NotImplemented IfcPhysicalComplexQuantity; // (not currently used by Assimp)
struct IfcBooleanClippingResult;
typedef NotImplemented IfcPreDefinedTerminatorSymbol; // (not currently used by Assimp)
struct IfcAnnotationFillArea;
typedef NotImplemented IfcConstraintAggregationRelationship; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssociatesApproval; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssociatesMaterial; // (not currently used by Assimp)
typedef NotImplemented IfcRelAssignsToProduct; // (not currently used by Assimp)
typedef NotImplemented IfcAppliedValueRelationship; // (not currently used by Assimp)
struct IfcLightSourceSpot;
struct IfcFireSuppressionTerminalType;
typedef NotImplemented IfcElementQuantity; // (not currently used by Assimp)
typedef NotImplemented IfcDimensionPair; // (not currently used by Assimp)
struct IfcElectricGeneratorType;
typedef NotImplemented IfcRelSequence; // (not currently used by Assimp)
struct IfcInventory;
struct IfcPolyline;
struct IfcBoxedHalfSpace;
struct IfcAirTerminalType;
typedef NotImplemented IfcSectionReinforcementProperties; // (not currently used by Assimp)
struct IfcDistributionPort;
struct IfcCostItem;
struct IfcStructuredDimensionCallout;
struct IfcStructuralResultGroup;
typedef NotImplemented IfcRelSpaceBoundary; // (not currently used by Assimp)
struct IfcOrientedEdge;
typedef NotImplemented IfcRelAssignsToResource; // (not currently used by Assimp)
struct IfcCsgSolid;
typedef NotImplemented IfcProductsOfCombustionProperties; // (not currently used by Assimp)
typedef NotImplemented IfcRelaxation; // (not currently used by Assimp)
struct IfcPlanarBox;
typedef NotImplemented IfcQuantityLength; // (not currently used by Assimp)
struct IfcMaterialDefinitionRepresentation;
struct IfcAsymmetricIShapeProfileDef;
struct IfcRepresentationMap;
// C++ wrapper for IfcRoot
struct IfcRoot : ObjectHelper<IfcRoot,4> { IfcRoot() : Object("IfcRoot") {}
IfcGloballyUniqueId::Out GlobalId;
Lazy< NotImplemented > OwnerHistory;
Maybe< IfcLabel::Out > Name;
Maybe< IfcText::Out > Description;
};
// C++ wrapper for IfcObjectDefinition
struct IfcObjectDefinition : IfcRoot, ObjectHelper<IfcObjectDefinition,0> { IfcObjectDefinition() : Object("IfcObjectDefinition") {}
};
// C++ wrapper for IfcTypeObject
struct IfcTypeObject : IfcObjectDefinition, ObjectHelper<IfcTypeObject,2> { IfcTypeObject() : Object("IfcTypeObject") {}
Maybe< IfcLabel::Out > ApplicableOccurrence;
Maybe< ListOf< Lazy< NotImplemented >, 1, 0 > > HasPropertySets;
};
// C++ wrapper for IfcTypeProduct
struct IfcTypeProduct : IfcTypeObject, ObjectHelper<IfcTypeProduct,2> { IfcTypeProduct() : Object("IfcTypeProduct") {}
Maybe< ListOf< Lazy< IfcRepresentationMap >, 1, 0 > > RepresentationMaps;
Maybe< IfcLabel::Out > Tag;
};
// C++ wrapper for IfcElementType
struct IfcElementType : IfcTypeProduct, ObjectHelper<IfcElementType,1> { IfcElementType() : Object("IfcElementType") {}
Maybe< IfcLabel::Out > ElementType;
};
// C++ wrapper for IfcFurnishingElementType
struct IfcFurnishingElementType : IfcElementType, ObjectHelper<IfcFurnishingElementType,0> { IfcFurnishingElementType() : Object("IfcFurnishingElementType") {}
};
// C++ wrapper for IfcFurnitureType
struct IfcFurnitureType : IfcFurnishingElementType, ObjectHelper<IfcFurnitureType,1> { IfcFurnitureType() : Object("IfcFurnitureType") {}
IfcAssemblyPlaceEnum::Out AssemblyPlace;
};
// C++ wrapper for IfcObject
struct IfcObject : IfcObjectDefinition, ObjectHelper<IfcObject,1> { IfcObject() : Object("IfcObject") {}
Maybe< IfcLabel::Out > ObjectType;
};
// C++ wrapper for IfcProduct
struct IfcProduct : IfcObject, ObjectHelper<IfcProduct,2> { IfcProduct() : Object("IfcProduct") {}
Maybe< Lazy< IfcObjectPlacement > > ObjectPlacement;
Maybe< Lazy< IfcProductRepresentation > > Representation;
};
// C++ wrapper for IfcGrid
struct IfcGrid : IfcProduct, ObjectHelper<IfcGrid,3> { IfcGrid() : Object("IfcGrid") {}
ListOf< Lazy< NotImplemented >, 1, 0 > UAxes;
ListOf< Lazy< NotImplemented >, 1, 0 > VAxes;
Maybe< ListOf< Lazy< NotImplemented >, 1, 0 > > WAxes;
};
// C++ wrapper for IfcRepresentationItem
struct IfcRepresentationItem : ObjectHelper<IfcRepresentationItem,0> { IfcRepresentationItem() : Object("IfcRepresentationItem") {}
};
// C++ wrapper for IfcGeometricRepresentationItem
struct IfcGeometricRepresentationItem : IfcRepresentationItem, ObjectHelper<IfcGeometricRepresentationItem,0> { IfcGeometricRepresentationItem() : Object("IfcGeometricRepresentationItem") {}
};
// C++ wrapper for IfcOneDirectionRepeatFactor
struct IfcOneDirectionRepeatFactor : IfcGeometricRepresentationItem, ObjectHelper<IfcOneDirectionRepeatFactor,1> { IfcOneDirectionRepeatFactor() : Object("IfcOneDirectionRepeatFactor") {}
Lazy< IfcVector > RepeatFactor;
};
// C++ wrapper for IfcTwoDirectionRepeatFactor
struct IfcTwoDirectionRepeatFactor : IfcOneDirectionRepeatFactor, ObjectHelper<IfcTwoDirectionRepeatFactor,1> { IfcTwoDirectionRepeatFactor() : Object("IfcTwoDirectionRepeatFactor") {}
Lazy< IfcVector > SecondRepeatFactor;
};
// C++ wrapper for IfcElement
struct IfcElement : IfcProduct, ObjectHelper<IfcElement,1> { IfcElement() : Object("IfcElement") {}
Maybe< IfcIdentifier::Out > Tag;
};
// C++ wrapper for IfcElementComponent
struct IfcElementComponent : IfcElement, ObjectHelper<IfcElementComponent,0> { IfcElementComponent() : Object("IfcElementComponent") {}
};
// C++ wrapper for IfcSpatialStructureElementType
struct IfcSpatialStructureElementType : IfcElementType, ObjectHelper<IfcSpatialStructureElementType,0> { IfcSpatialStructureElementType() : Object("IfcSpatialStructureElementType") {}
};
// C++ wrapper for IfcControl
struct IfcControl : IfcObject, ObjectHelper<IfcControl,0> { IfcControl() : Object("IfcControl") {}
};
// C++ wrapper for IfcActionRequest
struct IfcActionRequest : IfcControl, ObjectHelper<IfcActionRequest,1> { IfcActionRequest() : Object("IfcActionRequest") {}
IfcIdentifier::Out RequestID;
};
// C++ wrapper for IfcDistributionElementType
struct IfcDistributionElementType : IfcElementType, ObjectHelper<IfcDistributionElementType,0> { IfcDistributionElementType() : Object("IfcDistributionElementType") {}
};
// C++ wrapper for IfcDistributionFlowElementType
struct IfcDistributionFlowElementType : IfcDistributionElementType, ObjectHelper<IfcDistributionFlowElementType,0> { IfcDistributionFlowElementType() : Object("IfcDistributionFlowElementType") {}
};
// C++ wrapper for IfcEnergyConversionDeviceType
struct IfcEnergyConversionDeviceType : IfcDistributionFlowElementType, ObjectHelper<IfcEnergyConversionDeviceType,0> { IfcEnergyConversionDeviceType() : Object("IfcEnergyConversionDeviceType") {}
};
// C++ wrapper for IfcCooledBeamType
struct IfcCooledBeamType : IfcEnergyConversionDeviceType, ObjectHelper<IfcCooledBeamType,1> { IfcCooledBeamType() : Object("IfcCooledBeamType") {}
IfcCooledBeamTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcCsgPrimitive3D
struct IfcCsgPrimitive3D : IfcGeometricRepresentationItem, ObjectHelper<IfcCsgPrimitive3D,1> { IfcCsgPrimitive3D() : Object("IfcCsgPrimitive3D") {}
Lazy< IfcAxis2Placement3D > Position;
};
// C++ wrapper for IfcRectangularPyramid
struct IfcRectangularPyramid : IfcCsgPrimitive3D, ObjectHelper<IfcRectangularPyramid,3> { IfcRectangularPyramid() : Object("IfcRectangularPyramid") {}
IfcPositiveLengthMeasure::Out XLength;
IfcPositiveLengthMeasure::Out YLength;
IfcPositiveLengthMeasure::Out Height;
};
// C++ wrapper for IfcSurface
struct IfcSurface : IfcGeometricRepresentationItem, ObjectHelper<IfcSurface,0> { IfcSurface() : Object("IfcSurface") {}
};
// C++ wrapper for IfcBoundedSurface
struct IfcBoundedSurface : IfcSurface, ObjectHelper<IfcBoundedSurface,0> { IfcBoundedSurface() : Object("IfcBoundedSurface") {}
};
// C++ wrapper for IfcRectangularTrimmedSurface
struct IfcRectangularTrimmedSurface : IfcBoundedSurface, ObjectHelper<IfcRectangularTrimmedSurface,7> { IfcRectangularTrimmedSurface() : Object("IfcRectangularTrimmedSurface") {}
Lazy< IfcSurface > BasisSurface;
IfcParameterValue::Out U1;
IfcParameterValue::Out V1;
IfcParameterValue::Out U2;
IfcParameterValue::Out V2;
BOOLEAN::Out Usense;
BOOLEAN::Out Vsense;
};
// C++ wrapper for IfcGroup
struct IfcGroup : IfcObject, ObjectHelper<IfcGroup,0> { IfcGroup() : Object("IfcGroup") {}
};
// C++ wrapper for IfcRelationship
struct IfcRelationship : IfcRoot, ObjectHelper<IfcRelationship,0> { IfcRelationship() : Object("IfcRelationship") {}
};
// C++ wrapper for IfcHalfSpaceSolid
struct IfcHalfSpaceSolid : IfcGeometricRepresentationItem, ObjectHelper<IfcHalfSpaceSolid,2> { IfcHalfSpaceSolid() : Object("IfcHalfSpaceSolid") {}
Lazy< IfcSurface > BaseSurface;
BOOLEAN::Out AgreementFlag;
};
// C++ wrapper for IfcPolygonalBoundedHalfSpace
struct IfcPolygonalBoundedHalfSpace : IfcHalfSpaceSolid, ObjectHelper<IfcPolygonalBoundedHalfSpace,2> { IfcPolygonalBoundedHalfSpace() : Object("IfcPolygonalBoundedHalfSpace") {}
Lazy< IfcAxis2Placement3D > Position;
Lazy< IfcBoundedCurve > PolygonalBoundary;
};
// C++ wrapper for IfcAirToAirHeatRecoveryType
struct IfcAirToAirHeatRecoveryType : IfcEnergyConversionDeviceType, ObjectHelper<IfcAirToAirHeatRecoveryType,1> { IfcAirToAirHeatRecoveryType() : Object("IfcAirToAirHeatRecoveryType") {}
IfcAirToAirHeatRecoveryTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcFlowFittingType
struct IfcFlowFittingType : IfcDistributionFlowElementType, ObjectHelper<IfcFlowFittingType,0> { IfcFlowFittingType() : Object("IfcFlowFittingType") {}
};
// C++ wrapper for IfcPipeFittingType
struct IfcPipeFittingType : IfcFlowFittingType, ObjectHelper<IfcPipeFittingType,1> { IfcPipeFittingType() : Object("IfcPipeFittingType") {}
IfcPipeFittingTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcRepresentation
struct IfcRepresentation : ObjectHelper<IfcRepresentation,4> { IfcRepresentation() : Object("IfcRepresentation") {}
Lazy< IfcRepresentationContext > ContextOfItems;
Maybe< IfcLabel::Out > RepresentationIdentifier;
Maybe< IfcLabel::Out > RepresentationType;
ListOf< Lazy< IfcRepresentationItem >, 1, 0 > Items;
};
// C++ wrapper for IfcStyleModel
struct IfcStyleModel : IfcRepresentation, ObjectHelper<IfcStyleModel,0> { IfcStyleModel() : Object("IfcStyleModel") {}
};
// C++ wrapper for IfcStyledRepresentation
struct IfcStyledRepresentation : IfcStyleModel, ObjectHelper<IfcStyledRepresentation,0> { IfcStyledRepresentation() : Object("IfcStyledRepresentation") {}
};
// C++ wrapper for IfcBooleanResult
struct IfcBooleanResult : IfcGeometricRepresentationItem, ObjectHelper<IfcBooleanResult,3> { IfcBooleanResult() : Object("IfcBooleanResult") {}
IfcBooleanOperator::Out Operator;
IfcBooleanOperand::Out FirstOperand;
IfcBooleanOperand::Out SecondOperand;
};
// C++ wrapper for IfcFeatureElement
struct IfcFeatureElement : IfcElement, ObjectHelper<IfcFeatureElement,0> { IfcFeatureElement() : Object("IfcFeatureElement") {}
};
// C++ wrapper for IfcFeatureElementSubtraction
struct IfcFeatureElementSubtraction : IfcFeatureElement, ObjectHelper<IfcFeatureElementSubtraction,0> { IfcFeatureElementSubtraction() : Object("IfcFeatureElementSubtraction") {}
};
// C++ wrapper for IfcOpeningElement
struct IfcOpeningElement : IfcFeatureElementSubtraction, ObjectHelper<IfcOpeningElement,0> { IfcOpeningElement() : Object("IfcOpeningElement") {}
};
// C++ wrapper for IfcConditionCriterion
struct IfcConditionCriterion : IfcControl, ObjectHelper<IfcConditionCriterion,2> { IfcConditionCriterion() : Object("IfcConditionCriterion") {}
IfcConditionCriterionSelect::Out Criterion;
IfcDateTimeSelect::Out CriterionDateTime;
};
// C++ wrapper for IfcFlowTerminalType
struct IfcFlowTerminalType : IfcDistributionFlowElementType, ObjectHelper<IfcFlowTerminalType,0> { IfcFlowTerminalType() : Object("IfcFlowTerminalType") {}
};
// C++ wrapper for IfcFlowControllerType
struct IfcFlowControllerType : IfcDistributionFlowElementType, ObjectHelper<IfcFlowControllerType,0> { IfcFlowControllerType() : Object("IfcFlowControllerType") {}
};
// C++ wrapper for IfcSwitchingDeviceType
struct IfcSwitchingDeviceType : IfcFlowControllerType, ObjectHelper<IfcSwitchingDeviceType,1> { IfcSwitchingDeviceType() : Object("IfcSwitchingDeviceType") {}
IfcSwitchingDeviceTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcSystem
struct IfcSystem : IfcGroup, ObjectHelper<IfcSystem,0> { IfcSystem() : Object("IfcSystem") {}
};
// C++ wrapper for IfcElectricalCircuit
struct IfcElectricalCircuit : IfcSystem, ObjectHelper<IfcElectricalCircuit,0> { IfcElectricalCircuit() : Object("IfcElectricalCircuit") {}
};
// C++ wrapper for IfcUnitaryEquipmentType
struct IfcUnitaryEquipmentType : IfcEnergyConversionDeviceType, ObjectHelper<IfcUnitaryEquipmentType,1> { IfcUnitaryEquipmentType() : Object("IfcUnitaryEquipmentType") {}
IfcUnitaryEquipmentTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcPort
struct IfcPort : IfcProduct, ObjectHelper<IfcPort,0> { IfcPort() : Object("IfcPort") {}
};
// C++ wrapper for IfcPlacement
struct IfcPlacement : IfcGeometricRepresentationItem, ObjectHelper<IfcPlacement,1> { IfcPlacement() : Object("IfcPlacement") {}
Lazy< IfcCartesianPoint > Location;
};
// C++ wrapper for IfcProfileDef
struct IfcProfileDef : ObjectHelper<IfcProfileDef,2> { IfcProfileDef() : Object("IfcProfileDef") {}
IfcProfileTypeEnum::Out ProfileType;
Maybe< IfcLabel::Out > ProfileName;
};
// C++ wrapper for IfcArbitraryClosedProfileDef
struct IfcArbitraryClosedProfileDef : IfcProfileDef, ObjectHelper<IfcArbitraryClosedProfileDef,1> { IfcArbitraryClosedProfileDef() : Object("IfcArbitraryClosedProfileDef") {}
Lazy< IfcCurve > OuterCurve;
};
// C++ wrapper for IfcCurve
struct IfcCurve : IfcGeometricRepresentationItem, ObjectHelper<IfcCurve,0> { IfcCurve() : Object("IfcCurve") {}
};
// C++ wrapper for IfcConic
struct IfcConic : IfcCurve, ObjectHelper<IfcConic,1> { IfcConic() : Object("IfcConic") {}
IfcAxis2Placement::Out Position;
};
// C++ wrapper for IfcCircle
struct IfcCircle : IfcConic, ObjectHelper<IfcCircle,1> { IfcCircle() : Object("IfcCircle") {}
IfcPositiveLengthMeasure::Out Radius;
};
// C++ wrapper for IfcElementarySurface
struct IfcElementarySurface : IfcSurface, ObjectHelper<IfcElementarySurface,1> { IfcElementarySurface() : Object("IfcElementarySurface") {}
Lazy< IfcAxis2Placement3D > Position;
};
// C++ wrapper for IfcPlane
struct IfcPlane : IfcElementarySurface, ObjectHelper<IfcPlane,0> { IfcPlane() : Object("IfcPlane") {}
};
// C++ wrapper for IfcCostSchedule
struct IfcCostSchedule : IfcControl, ObjectHelper<IfcCostSchedule,8> { IfcCostSchedule() : Object("IfcCostSchedule") {}
Maybe< IfcActorSelect::Out > SubmittedBy;
Maybe< IfcActorSelect::Out > PreparedBy;
Maybe< IfcDateTimeSelect::Out > SubmittedOn;
Maybe< IfcLabel::Out > Status;
Maybe< ListOf< IfcActorSelect, 1, 0 >::Out > TargetUsers;
Maybe< IfcDateTimeSelect::Out > UpdateDate;
IfcIdentifier::Out ID;
IfcCostScheduleTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcRightCircularCone
struct IfcRightCircularCone : IfcCsgPrimitive3D, ObjectHelper<IfcRightCircularCone,2> { IfcRightCircularCone() : Object("IfcRightCircularCone") {}
IfcPositiveLengthMeasure::Out Height;
IfcPositiveLengthMeasure::Out BottomRadius;
};
// C++ wrapper for IfcElementAssembly
struct IfcElementAssembly : IfcElement, ObjectHelper<IfcElementAssembly,2> { IfcElementAssembly() : Object("IfcElementAssembly") {}
Maybe< IfcAssemblyPlaceEnum::Out > AssemblyPlace;
IfcElementAssemblyTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcBuildingElement
struct IfcBuildingElement : IfcElement, ObjectHelper<IfcBuildingElement,0> { IfcBuildingElement() : Object("IfcBuildingElement") {}
};
// C++ wrapper for IfcMember
struct IfcMember : IfcBuildingElement, ObjectHelper<IfcMember,0> { IfcMember() : Object("IfcMember") {}
};
// C++ wrapper for IfcBuildingElementProxy
struct IfcBuildingElementProxy : IfcBuildingElement, ObjectHelper<IfcBuildingElementProxy,1> { IfcBuildingElementProxy() : Object("IfcBuildingElementProxy") {}
Maybe< IfcElementCompositionEnum::Out > CompositionType;
};
// C++ wrapper for IfcStructuralActivity
struct IfcStructuralActivity : IfcProduct, ObjectHelper<IfcStructuralActivity,2> { IfcStructuralActivity() : Object("IfcStructuralActivity") {}
Lazy< NotImplemented > AppliedLoad;
IfcGlobalOrLocalEnum::Out GlobalOrLocal;
};
// C++ wrapper for IfcStructuralAction
struct IfcStructuralAction : IfcStructuralActivity, ObjectHelper<IfcStructuralAction,2> { IfcStructuralAction() : Object("IfcStructuralAction") {}
BOOLEAN::Out DestabilizingLoad;
Maybe< Lazy< IfcStructuralReaction > > CausedBy;
};
// C++ wrapper for IfcStructuralPlanarAction
struct IfcStructuralPlanarAction : IfcStructuralAction, ObjectHelper<IfcStructuralPlanarAction,1> { IfcStructuralPlanarAction() : Object("IfcStructuralPlanarAction") {}
IfcProjectedOrTrueLengthEnum::Out ProjectedOrTrue;
};
// C++ wrapper for IfcTopologicalRepresentationItem
struct IfcTopologicalRepresentationItem : IfcRepresentationItem, ObjectHelper<IfcTopologicalRepresentationItem,0> { IfcTopologicalRepresentationItem() : Object("IfcTopologicalRepresentationItem") {}
};
// C++ wrapper for IfcConnectedFaceSet
struct IfcConnectedFaceSet : IfcTopologicalRepresentationItem, ObjectHelper<IfcConnectedFaceSet,1> { IfcConnectedFaceSet() : Object("IfcConnectedFaceSet") {}
ListOf< Lazy< IfcFace >, 1, 0 > CfsFaces;
};
// C++ wrapper for IfcSweptSurface
struct IfcSweptSurface : IfcSurface, ObjectHelper<IfcSweptSurface,2> { IfcSweptSurface() : Object("IfcSweptSurface") {}
Lazy< IfcProfileDef > SweptCurve;
Lazy< IfcAxis2Placement3D > Position;
};
// C++ wrapper for IfcSurfaceOfLinearExtrusion
struct IfcSurfaceOfLinearExtrusion : IfcSweptSurface, ObjectHelper<IfcSurfaceOfLinearExtrusion,2> { IfcSurfaceOfLinearExtrusion() : Object("IfcSurfaceOfLinearExtrusion") {}
Lazy< IfcDirection > ExtrudedDirection;
IfcLengthMeasure::Out Depth;
};
// C++ wrapper for IfcArbitraryProfileDefWithVoids
struct IfcArbitraryProfileDefWithVoids : IfcArbitraryClosedProfileDef, ObjectHelper<IfcArbitraryProfileDefWithVoids,1> { IfcArbitraryProfileDefWithVoids() : Object("IfcArbitraryProfileDefWithVoids") {}
ListOf< Lazy< IfcCurve >, 1, 0 > InnerCurves;
};
// C++ wrapper for IfcProcess
struct IfcProcess : IfcObject, ObjectHelper<IfcProcess,0> { IfcProcess() : Object("IfcProcess") {}
};
// C++ wrapper for IfcProcedure
struct IfcProcedure : IfcProcess, ObjectHelper<IfcProcedure,3> { IfcProcedure() : Object("IfcProcedure") {}
IfcIdentifier::Out ProcedureID;
IfcProcedureTypeEnum::Out ProcedureType;
Maybe< IfcLabel::Out > UserDefinedProcedureType;
};
// C++ wrapper for IfcVector
struct IfcVector : IfcGeometricRepresentationItem, ObjectHelper<IfcVector,2> { IfcVector() : Object("IfcVector") {}
Lazy< IfcDirection > Orientation;
IfcLengthMeasure::Out Magnitude;
};
// C++ wrapper for IfcFaceBound
struct IfcFaceBound : IfcTopologicalRepresentationItem, ObjectHelper<IfcFaceBound,2> { IfcFaceBound() : Object("IfcFaceBound") {}
Lazy< IfcLoop > Bound;
BOOLEAN::Out Orientation;
};
// C++ wrapper for IfcFaceOuterBound
struct IfcFaceOuterBound : IfcFaceBound, ObjectHelper<IfcFaceOuterBound,0> { IfcFaceOuterBound() : Object("IfcFaceOuterBound") {}
};
// C++ wrapper for IfcFeatureElementAddition
struct IfcFeatureElementAddition : IfcFeatureElement, ObjectHelper<IfcFeatureElementAddition,0> { IfcFeatureElementAddition() : Object("IfcFeatureElementAddition") {}
};
// C++ wrapper for IfcNamedUnit
struct IfcNamedUnit : ObjectHelper<IfcNamedUnit,2> { IfcNamedUnit() : Object("IfcNamedUnit") {}
Lazy< NotImplemented > Dimensions;
IfcUnitEnum::Out UnitType;
};
// C++ wrapper for IfcConversionBasedUnit
struct IfcConversionBasedUnit : IfcNamedUnit, ObjectHelper<IfcConversionBasedUnit,2> { IfcConversionBasedUnit() : Object("IfcConversionBasedUnit") {}
IfcLabel::Out Name;
Lazy< IfcMeasureWithUnit > ConversionFactor;
};
// C++ wrapper for IfcHeatExchangerType
struct IfcHeatExchangerType : IfcEnergyConversionDeviceType, ObjectHelper<IfcHeatExchangerType,1> { IfcHeatExchangerType() : Object("IfcHeatExchangerType") {}
IfcHeatExchangerTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcPresentationStyleAssignment
struct IfcPresentationStyleAssignment : ObjectHelper<IfcPresentationStyleAssignment,1> { IfcPresentationStyleAssignment() : Object("IfcPresentationStyleAssignment") {}
ListOf< IfcPresentationStyleSelect, 1, 0 >::Out Styles;
};
// C++ wrapper for IfcFlowTreatmentDeviceType
struct IfcFlowTreatmentDeviceType : IfcDistributionFlowElementType, ObjectHelper<IfcFlowTreatmentDeviceType,0> { IfcFlowTreatmentDeviceType() : Object("IfcFlowTreatmentDeviceType") {}
};
// C++ wrapper for IfcFilterType
struct IfcFilterType : IfcFlowTreatmentDeviceType, ObjectHelper<IfcFilterType,1> { IfcFilterType() : Object("IfcFilterType") {}
IfcFilterTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcResource
struct IfcResource : IfcObject, ObjectHelper<IfcResource,0> { IfcResource() : Object("IfcResource") {}
};
// C++ wrapper for IfcEvaporativeCoolerType
struct IfcEvaporativeCoolerType : IfcEnergyConversionDeviceType, ObjectHelper<IfcEvaporativeCoolerType,1> { IfcEvaporativeCoolerType() : Object("IfcEvaporativeCoolerType") {}
IfcEvaporativeCoolerTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcOffsetCurve2D
struct IfcOffsetCurve2D : IfcCurve, ObjectHelper<IfcOffsetCurve2D,3> { IfcOffsetCurve2D() : Object("IfcOffsetCurve2D") {}
Lazy< IfcCurve > BasisCurve;
IfcLengthMeasure::Out Distance;
LOGICAL::Out SelfIntersect;
};
// C++ wrapper for IfcEdge
struct IfcEdge : IfcTopologicalRepresentationItem, ObjectHelper<IfcEdge,2> { IfcEdge() : Object("IfcEdge") {}
Lazy< IfcVertex > EdgeStart;
Lazy< IfcVertex > EdgeEnd;
};
// C++ wrapper for IfcSubedge
struct IfcSubedge : IfcEdge, ObjectHelper<IfcSubedge,1> { IfcSubedge() : Object("IfcSubedge") {}
Lazy< IfcEdge > ParentEdge;
};
// C++ wrapper for IfcProxy
struct IfcProxy : IfcProduct, ObjectHelper<IfcProxy,2> { IfcProxy() : Object("IfcProxy") {}
IfcObjectTypeEnum::Out ProxyType;
Maybe< IfcLabel::Out > Tag;
};
// C++ wrapper for IfcLine
struct IfcLine : IfcCurve, ObjectHelper<IfcLine,2> { IfcLine() : Object("IfcLine") {}
Lazy< IfcCartesianPoint > Pnt;
Lazy< IfcVector > Dir;
};
// C++ wrapper for IfcColumn
struct IfcColumn : IfcBuildingElement, ObjectHelper<IfcColumn,0> { IfcColumn() : Object("IfcColumn") {}
};
// C++ wrapper for IfcObjectPlacement
struct IfcObjectPlacement : ObjectHelper<IfcObjectPlacement,0> { IfcObjectPlacement() : Object("IfcObjectPlacement") {}
};
// C++ wrapper for IfcGridPlacement
struct IfcGridPlacement : IfcObjectPlacement, ObjectHelper<IfcGridPlacement,2> { IfcGridPlacement() : Object("IfcGridPlacement") {}
Lazy< NotImplemented > PlacementLocation;
Maybe< Lazy< NotImplemented > > PlacementRefDirection;
};
// C++ wrapper for IfcDistributionControlElementType
struct IfcDistributionControlElementType : IfcDistributionElementType, ObjectHelper<IfcDistributionControlElementType,0> { IfcDistributionControlElementType() : Object("IfcDistributionControlElementType") {}
};
// C++ wrapper for IfcRelConnects
struct IfcRelConnects : IfcRelationship, ObjectHelper<IfcRelConnects,0> { IfcRelConnects() : Object("IfcRelConnects") {}
};
// C++ wrapper for IfcAnnotation
struct IfcAnnotation : IfcProduct, ObjectHelper<IfcAnnotation,0> { IfcAnnotation() : Object("IfcAnnotation") {}
};
// C++ wrapper for IfcPlate
struct IfcPlate : IfcBuildingElement, ObjectHelper<IfcPlate,0> { IfcPlate() : Object("IfcPlate") {}
};
// C++ wrapper for IfcSolidModel
struct IfcSolidModel : IfcGeometricRepresentationItem, ObjectHelper<IfcSolidModel,0> { IfcSolidModel() : Object("IfcSolidModel") {}
};
// C++ wrapper for IfcManifoldSolidBrep
struct IfcManifoldSolidBrep : IfcSolidModel, ObjectHelper<IfcManifoldSolidBrep,1> { IfcManifoldSolidBrep() : Object("IfcManifoldSolidBrep") {}
Lazy< IfcClosedShell > Outer;
};
// C++ wrapper for IfcFlowStorageDeviceType
struct IfcFlowStorageDeviceType : IfcDistributionFlowElementType, ObjectHelper<IfcFlowStorageDeviceType,0> { IfcFlowStorageDeviceType() : Object("IfcFlowStorageDeviceType") {}
};
// C++ wrapper for IfcStructuralItem
struct IfcStructuralItem : IfcProduct, ObjectHelper<IfcStructuralItem,0> { IfcStructuralItem() : Object("IfcStructuralItem") {}
};
// C++ wrapper for IfcStructuralMember
struct IfcStructuralMember : IfcStructuralItem, ObjectHelper<IfcStructuralMember,0> { IfcStructuralMember() : Object("IfcStructuralMember") {}
};
// C++ wrapper for IfcStructuralCurveMember
struct IfcStructuralCurveMember : IfcStructuralMember, ObjectHelper<IfcStructuralCurveMember,1> { IfcStructuralCurveMember() : Object("IfcStructuralCurveMember") {}
IfcStructuralCurveTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcStructuralConnection
struct IfcStructuralConnection : IfcStructuralItem, ObjectHelper<IfcStructuralConnection,1> { IfcStructuralConnection() : Object("IfcStructuralConnection") {}
Maybe< Lazy< NotImplemented > > AppliedCondition;
};
// C++ wrapper for IfcStructuralSurfaceConnection
struct IfcStructuralSurfaceConnection : IfcStructuralConnection, ObjectHelper<IfcStructuralSurfaceConnection,0> { IfcStructuralSurfaceConnection() : Object("IfcStructuralSurfaceConnection") {}
};
// C++ wrapper for IfcCoilType
struct IfcCoilType : IfcEnergyConversionDeviceType, ObjectHelper<IfcCoilType,1> { IfcCoilType() : Object("IfcCoilType") {}
IfcCoilTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcDuctFittingType
struct IfcDuctFittingType : IfcFlowFittingType, ObjectHelper<IfcDuctFittingType,1> { IfcDuctFittingType() : Object("IfcDuctFittingType") {}
IfcDuctFittingTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcStyledItem
struct IfcStyledItem : IfcRepresentationItem, ObjectHelper<IfcStyledItem,3> { IfcStyledItem() : Object("IfcStyledItem") {}
Maybe< Lazy< IfcRepresentationItem > > Item;
ListOf< Lazy< IfcPresentationStyleAssignment >, 1, 0 > Styles;
Maybe< IfcLabel::Out > Name;
};
// C++ wrapper for IfcAnnotationOccurrence
struct IfcAnnotationOccurrence : IfcStyledItem, ObjectHelper<IfcAnnotationOccurrence,0> { IfcAnnotationOccurrence() : Object("IfcAnnotationOccurrence") {}
};
// C++ wrapper for IfcAnnotationCurveOccurrence
struct IfcAnnotationCurveOccurrence : IfcAnnotationOccurrence, ObjectHelper<IfcAnnotationCurveOccurrence,0> { IfcAnnotationCurveOccurrence() : Object("IfcAnnotationCurveOccurrence") {}
};
// C++ wrapper for IfcDimensionCurve
struct IfcDimensionCurve : IfcAnnotationCurveOccurrence, ObjectHelper<IfcDimensionCurve,0> { IfcDimensionCurve() : Object("IfcDimensionCurve") {}
};
// C++ wrapper for IfcBoundedCurve
struct IfcBoundedCurve : IfcCurve, ObjectHelper<IfcBoundedCurve,0> { IfcBoundedCurve() : Object("IfcBoundedCurve") {}
};
// C++ wrapper for IfcAxis1Placement
struct IfcAxis1Placement : IfcPlacement, ObjectHelper<IfcAxis1Placement,1> { IfcAxis1Placement() : Object("IfcAxis1Placement") {}
Maybe< Lazy< IfcDirection > > Axis;
};
// C++ wrapper for IfcStructuralPointAction
struct IfcStructuralPointAction : IfcStructuralAction, ObjectHelper<IfcStructuralPointAction,0> { IfcStructuralPointAction() : Object("IfcStructuralPointAction") {}
};
// C++ wrapper for IfcSpatialStructureElement
struct IfcSpatialStructureElement : IfcProduct, ObjectHelper<IfcSpatialStructureElement,2> { IfcSpatialStructureElement() : Object("IfcSpatialStructureElement") {}
Maybe< IfcLabel::Out > LongName;
IfcElementCompositionEnum::Out CompositionType;
};
// C++ wrapper for IfcSpace
struct IfcSpace : IfcSpatialStructureElement, ObjectHelper<IfcSpace,2> { IfcSpace() : Object("IfcSpace") {}
IfcInternalOrExternalEnum::Out InteriorOrExteriorSpace;
Maybe< IfcLengthMeasure::Out > ElevationWithFlooring;
};
// C++ wrapper for IfcCoolingTowerType
struct IfcCoolingTowerType : IfcEnergyConversionDeviceType, ObjectHelper<IfcCoolingTowerType,1> { IfcCoolingTowerType() : Object("IfcCoolingTowerType") {}
IfcCoolingTowerTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcFacetedBrepWithVoids
struct IfcFacetedBrepWithVoids : IfcManifoldSolidBrep, ObjectHelper<IfcFacetedBrepWithVoids,1> { IfcFacetedBrepWithVoids() : Object("IfcFacetedBrepWithVoids") {}
ListOf< Lazy< IfcClosedShell >, 1, 0 > Voids;
};
// C++ wrapper for IfcValveType
struct IfcValveType : IfcFlowControllerType, ObjectHelper<IfcValveType,1> { IfcValveType() : Object("IfcValveType") {}
IfcValveTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcSystemFurnitureElementType
struct IfcSystemFurnitureElementType : IfcFurnishingElementType, ObjectHelper<IfcSystemFurnitureElementType,0> { IfcSystemFurnitureElementType() : Object("IfcSystemFurnitureElementType") {}
};
// C++ wrapper for IfcDiscreteAccessory
struct IfcDiscreteAccessory : IfcElementComponent, ObjectHelper<IfcDiscreteAccessory,0> { IfcDiscreteAccessory() : Object("IfcDiscreteAccessory") {}
};
// C++ wrapper for IfcBuildingElementType
struct IfcBuildingElementType : IfcElementType, ObjectHelper<IfcBuildingElementType,0> { IfcBuildingElementType() : Object("IfcBuildingElementType") {}
};
// C++ wrapper for IfcRailingType
struct IfcRailingType : IfcBuildingElementType, ObjectHelper<IfcRailingType,1> { IfcRailingType() : Object("IfcRailingType") {}
IfcRailingTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcGasTerminalType
struct IfcGasTerminalType : IfcFlowTerminalType, ObjectHelper<IfcGasTerminalType,1> { IfcGasTerminalType() : Object("IfcGasTerminalType") {}
IfcGasTerminalTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcSpaceProgram
struct IfcSpaceProgram : IfcControl, ObjectHelper<IfcSpaceProgram,5> { IfcSpaceProgram() : Object("IfcSpaceProgram") {}
IfcIdentifier::Out SpaceProgramIdentifier;
Maybe< IfcAreaMeasure::Out > MaxRequiredArea;
Maybe< IfcAreaMeasure::Out > MinRequiredArea;
Maybe< Lazy< IfcSpatialStructureElement > > RequestedLocation;
IfcAreaMeasure::Out StandardRequiredArea;
};
// C++ wrapper for IfcCovering
struct IfcCovering : IfcBuildingElement, ObjectHelper<IfcCovering,1> { IfcCovering() : Object("IfcCovering") {}
Maybe< IfcCoveringTypeEnum::Out > PredefinedType;
};
// C++ wrapper for IfcPresentationStyle
struct IfcPresentationStyle : ObjectHelper<IfcPresentationStyle,1> { IfcPresentationStyle() : Object("IfcPresentationStyle") {}
Maybe< IfcLabel::Out > Name;
};
// C++ wrapper for IfcElectricHeaterType
struct IfcElectricHeaterType : IfcFlowTerminalType, ObjectHelper<IfcElectricHeaterType,1> { IfcElectricHeaterType() : Object("IfcElectricHeaterType") {}
IfcElectricHeaterTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcBuildingStorey
struct IfcBuildingStorey : IfcSpatialStructureElement, ObjectHelper<IfcBuildingStorey,1> { IfcBuildingStorey() : Object("IfcBuildingStorey") {}
Maybe< IfcLengthMeasure::Out > Elevation;
};
// C++ wrapper for IfcVertex
struct IfcVertex : IfcTopologicalRepresentationItem, ObjectHelper<IfcVertex,0> { IfcVertex() : Object("IfcVertex") {}
};
// C++ wrapper for IfcVertexPoint
struct IfcVertexPoint : IfcVertex, ObjectHelper<IfcVertexPoint,1> { IfcVertexPoint() : Object("IfcVertexPoint") {}
Lazy< IfcPoint > VertexGeometry;
};
// C++ wrapper for IfcFlowInstrumentType
struct IfcFlowInstrumentType : IfcDistributionControlElementType, ObjectHelper<IfcFlowInstrumentType,1> { IfcFlowInstrumentType() : Object("IfcFlowInstrumentType") {}
IfcFlowInstrumentTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcParameterizedProfileDef
struct IfcParameterizedProfileDef : IfcProfileDef, ObjectHelper<IfcParameterizedProfileDef,1> { IfcParameterizedProfileDef() : Object("IfcParameterizedProfileDef") {}
Lazy< IfcAxis2Placement2D > Position;
};
// C++ wrapper for IfcUShapeProfileDef
struct IfcUShapeProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcUShapeProfileDef,8> { IfcUShapeProfileDef() : Object("IfcUShapeProfileDef") {}
IfcPositiveLengthMeasure::Out Depth;
IfcPositiveLengthMeasure::Out FlangeWidth;
IfcPositiveLengthMeasure::Out WebThickness;
IfcPositiveLengthMeasure::Out FlangeThickness;
Maybe< IfcPositiveLengthMeasure::Out > FilletRadius;
Maybe< IfcPositiveLengthMeasure::Out > EdgeRadius;
Maybe< IfcPlaneAngleMeasure::Out > FlangeSlope;
Maybe< IfcPositiveLengthMeasure::Out > CentreOfGravityInX;
};
// C++ wrapper for IfcRamp
struct IfcRamp : IfcBuildingElement, ObjectHelper<IfcRamp,1> { IfcRamp() : Object("IfcRamp") {}
IfcRampTypeEnum::Out ShapeType;
};
// C++ wrapper for IfcCompositeCurve
struct IfcCompositeCurve : IfcBoundedCurve, ObjectHelper<IfcCompositeCurve,2> { IfcCompositeCurve() : Object("IfcCompositeCurve") {}
ListOf< Lazy< IfcCompositeCurveSegment >, 1, 0 > Segments;
LOGICAL::Out SelfIntersect;
};
// C++ wrapper for IfcStructuralCurveMemberVarying
struct IfcStructuralCurveMemberVarying : IfcStructuralCurveMember, ObjectHelper<IfcStructuralCurveMemberVarying,0> { IfcStructuralCurveMemberVarying() : Object("IfcStructuralCurveMemberVarying") {}
};
// C++ wrapper for IfcRampFlightType
struct IfcRampFlightType : IfcBuildingElementType, ObjectHelper<IfcRampFlightType,1> { IfcRampFlightType() : Object("IfcRampFlightType") {}
IfcRampFlightTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcDraughtingCallout
struct IfcDraughtingCallout : IfcGeometricRepresentationItem, ObjectHelper<IfcDraughtingCallout,1> { IfcDraughtingCallout() : Object("IfcDraughtingCallout") {}
ListOf< IfcDraughtingCalloutElement, 1, 0 >::Out Contents;
};
// C++ wrapper for IfcDimensionCurveDirectedCallout
struct IfcDimensionCurveDirectedCallout : IfcDraughtingCallout, ObjectHelper<IfcDimensionCurveDirectedCallout,0> { IfcDimensionCurveDirectedCallout() : Object("IfcDimensionCurveDirectedCallout") {}
};
// C++ wrapper for IfcRadiusDimension
struct IfcRadiusDimension : IfcDimensionCurveDirectedCallout, ObjectHelper<IfcRadiusDimension,0> { IfcRadiusDimension() : Object("IfcRadiusDimension") {}
};
// C++ wrapper for IfcEdgeFeature
struct IfcEdgeFeature : IfcFeatureElementSubtraction, ObjectHelper<IfcEdgeFeature,1> { IfcEdgeFeature() : Object("IfcEdgeFeature") {}
Maybe< IfcPositiveLengthMeasure::Out > FeatureLength;
};
// C++ wrapper for IfcSweptAreaSolid
struct IfcSweptAreaSolid : IfcSolidModel, ObjectHelper<IfcSweptAreaSolid,2> { IfcSweptAreaSolid() : Object("IfcSweptAreaSolid") {}
Lazy< IfcProfileDef > SweptArea;
Lazy< IfcAxis2Placement3D > Position;
};
// C++ wrapper for IfcExtrudedAreaSolid
struct IfcExtrudedAreaSolid : IfcSweptAreaSolid, ObjectHelper<IfcExtrudedAreaSolid,2> { IfcExtrudedAreaSolid() : Object("IfcExtrudedAreaSolid") {}
Lazy< IfcDirection > ExtrudedDirection;
IfcPositiveLengthMeasure::Out Depth;
};
// C++ wrapper for IfcAnnotationTextOccurrence
struct IfcAnnotationTextOccurrence : IfcAnnotationOccurrence, ObjectHelper<IfcAnnotationTextOccurrence,0> { IfcAnnotationTextOccurrence() : Object("IfcAnnotationTextOccurrence") {}
};
// C++ wrapper for IfcStair
struct IfcStair : IfcBuildingElement, ObjectHelper<IfcStair,1> { IfcStair() : Object("IfcStair") {}
IfcStairTypeEnum::Out ShapeType;
};
// C++ wrapper for IfcFillAreaStyleTileSymbolWithStyle
struct IfcFillAreaStyleTileSymbolWithStyle : IfcGeometricRepresentationItem, ObjectHelper<IfcFillAreaStyleTileSymbolWithStyle,1> { IfcFillAreaStyleTileSymbolWithStyle() : Object("IfcFillAreaStyleTileSymbolWithStyle") {}
Lazy< IfcAnnotationSymbolOccurrence > Symbol;
};
// C++ wrapper for IfcAnnotationSymbolOccurrence
struct IfcAnnotationSymbolOccurrence : IfcAnnotationOccurrence, ObjectHelper<IfcAnnotationSymbolOccurrence,0> { IfcAnnotationSymbolOccurrence() : Object("IfcAnnotationSymbolOccurrence") {}
};
// C++ wrapper for IfcTerminatorSymbol
struct IfcTerminatorSymbol : IfcAnnotationSymbolOccurrence, ObjectHelper<IfcTerminatorSymbol,1> { IfcTerminatorSymbol() : Object("IfcTerminatorSymbol") {}
Lazy< IfcAnnotationCurveOccurrence > AnnotatedCurve;
};
// C++ wrapper for IfcDimensionCurveTerminator
struct IfcDimensionCurveTerminator : IfcTerminatorSymbol, ObjectHelper<IfcDimensionCurveTerminator,1> { IfcDimensionCurveTerminator() : Object("IfcDimensionCurveTerminator") {}
IfcDimensionExtentUsage::Out Role;
};
// C++ wrapper for IfcRectangleProfileDef
struct IfcRectangleProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcRectangleProfileDef,2> { IfcRectangleProfileDef() : Object("IfcRectangleProfileDef") {}
IfcPositiveLengthMeasure::Out XDim;
IfcPositiveLengthMeasure::Out YDim;
};
// C++ wrapper for IfcRectangleHollowProfileDef
struct IfcRectangleHollowProfileDef : IfcRectangleProfileDef, ObjectHelper<IfcRectangleHollowProfileDef,3> { IfcRectangleHollowProfileDef() : Object("IfcRectangleHollowProfileDef") {}
IfcPositiveLengthMeasure::Out WallThickness;
Maybe< IfcPositiveLengthMeasure::Out > InnerFilletRadius;
Maybe< IfcPositiveLengthMeasure::Out > OuterFilletRadius;
};
// C++ wrapper for IfcLocalPlacement
struct IfcLocalPlacement : IfcObjectPlacement, ObjectHelper<IfcLocalPlacement,2> { IfcLocalPlacement() : Object("IfcLocalPlacement") {}
Maybe< Lazy< IfcObjectPlacement > > PlacementRelTo;
IfcAxis2Placement::Out RelativePlacement;
};
// C++ wrapper for IfcTask
struct IfcTask : IfcProcess, ObjectHelper<IfcTask,5> { IfcTask() : Object("IfcTask") {}
IfcIdentifier::Out TaskId;
Maybe< IfcLabel::Out > Status;
Maybe< IfcLabel::Out > WorkMethod;
BOOLEAN::Out IsMilestone;
Maybe< INTEGER::Out > Priority;
};
// C++ wrapper for IfcAnnotationFillAreaOccurrence
struct IfcAnnotationFillAreaOccurrence : IfcAnnotationOccurrence, ObjectHelper<IfcAnnotationFillAreaOccurrence,2> { IfcAnnotationFillAreaOccurrence() : Object("IfcAnnotationFillAreaOccurrence") {}
Maybe< Lazy< IfcPoint > > FillStyleTarget;
Maybe< IfcGlobalOrLocalEnum::Out > GlobalOrLocal;
};
// C++ wrapper for IfcFace
struct IfcFace : IfcTopologicalRepresentationItem, ObjectHelper<IfcFace,1> { IfcFace() : Object("IfcFace") {}
ListOf< Lazy< IfcFaceBound >, 1, 0 > Bounds;
};
// C++ wrapper for IfcFlowSegmentType
struct IfcFlowSegmentType : IfcDistributionFlowElementType, ObjectHelper<IfcFlowSegmentType,0> { IfcFlowSegmentType() : Object("IfcFlowSegmentType") {}
};
// C++ wrapper for IfcDuctSegmentType
struct IfcDuctSegmentType : IfcFlowSegmentType, ObjectHelper<IfcDuctSegmentType,1> { IfcDuctSegmentType() : Object("IfcDuctSegmentType") {}
IfcDuctSegmentTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcConstructionResource
struct IfcConstructionResource : IfcResource, ObjectHelper<IfcConstructionResource,4> { IfcConstructionResource() : Object("IfcConstructionResource") {}
Maybe< IfcIdentifier::Out > ResourceIdentifier;
Maybe< IfcLabel::Out > ResourceGroup;
Maybe< IfcResourceConsumptionEnum::Out > ResourceConsumption;
Maybe< Lazy< IfcMeasureWithUnit > > BaseQuantity;
};
// C++ wrapper for IfcConstructionEquipmentResource
struct IfcConstructionEquipmentResource : IfcConstructionResource, ObjectHelper<IfcConstructionEquipmentResource,0> { IfcConstructionEquipmentResource() : Object("IfcConstructionEquipmentResource") {}
};
// C++ wrapper for IfcSanitaryTerminalType
struct IfcSanitaryTerminalType : IfcFlowTerminalType, ObjectHelper<IfcSanitaryTerminalType,1> { IfcSanitaryTerminalType() : Object("IfcSanitaryTerminalType") {}
IfcSanitaryTerminalTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcCircleProfileDef
struct IfcCircleProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcCircleProfileDef,1> { IfcCircleProfileDef() : Object("IfcCircleProfileDef") {}
IfcPositiveLengthMeasure::Out Radius;
};
// C++ wrapper for IfcStructuralReaction
struct IfcStructuralReaction : IfcStructuralActivity, ObjectHelper<IfcStructuralReaction,0> { IfcStructuralReaction() : Object("IfcStructuralReaction") {}
};
// C++ wrapper for IfcStructuralPointReaction
struct IfcStructuralPointReaction : IfcStructuralReaction, ObjectHelper<IfcStructuralPointReaction,0> { IfcStructuralPointReaction() : Object("IfcStructuralPointReaction") {}
};
// C++ wrapper for IfcRailing
struct IfcRailing : IfcBuildingElement, ObjectHelper<IfcRailing,1> { IfcRailing() : Object("IfcRailing") {}
Maybe< IfcRailingTypeEnum::Out > PredefinedType;
};
// C++ wrapper for IfcTextLiteral
struct IfcTextLiteral : IfcGeometricRepresentationItem, ObjectHelper<IfcTextLiteral,3> { IfcTextLiteral() : Object("IfcTextLiteral") {}
IfcPresentableText::Out Literal;
IfcAxis2Placement::Out Placement;
IfcTextPath::Out Path;
};
// C++ wrapper for IfcCartesianTransformationOperator
struct IfcCartesianTransformationOperator : IfcGeometricRepresentationItem, ObjectHelper<IfcCartesianTransformationOperator,4> { IfcCartesianTransformationOperator() : Object("IfcCartesianTransformationOperator") {}
Maybe< Lazy< IfcDirection > > Axis1;
Maybe< Lazy< IfcDirection > > Axis2;
Lazy< IfcCartesianPoint > LocalOrigin;
Maybe< REAL::Out > Scale;
};
// C++ wrapper for IfcLinearDimension
struct IfcLinearDimension : IfcDimensionCurveDirectedCallout, ObjectHelper<IfcLinearDimension,0> { IfcLinearDimension() : Object("IfcLinearDimension") {}
};
// C++ wrapper for IfcDamperType
struct IfcDamperType : IfcFlowControllerType, ObjectHelper<IfcDamperType,1> { IfcDamperType() : Object("IfcDamperType") {}
IfcDamperTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcSIUnit
struct IfcSIUnit : IfcNamedUnit, ObjectHelper<IfcSIUnit,2> { IfcSIUnit() : Object("IfcSIUnit") {}
Maybe< IfcSIPrefix::Out > Prefix;
IfcSIUnitName::Out Name;
};
// C++ wrapper for IfcMeasureWithUnit
struct IfcMeasureWithUnit : ObjectHelper<IfcMeasureWithUnit,2> { IfcMeasureWithUnit() : Object("IfcMeasureWithUnit") {}
IfcValue::Out ValueComponent;
IfcUnit::Out UnitComponent;
};
// C++ wrapper for IfcDistributionElement
struct IfcDistributionElement : IfcElement, ObjectHelper<IfcDistributionElement,0> { IfcDistributionElement() : Object("IfcDistributionElement") {}
};
// C++ wrapper for IfcDistributionControlElement
struct IfcDistributionControlElement : IfcDistributionElement, ObjectHelper<IfcDistributionControlElement,1> { IfcDistributionControlElement() : Object("IfcDistributionControlElement") {}
Maybe< IfcIdentifier::Out > ControlElementId;
};
// C++ wrapper for IfcTransformerType
struct IfcTransformerType : IfcEnergyConversionDeviceType, ObjectHelper<IfcTransformerType,1> { IfcTransformerType() : Object("IfcTransformerType") {}
IfcTransformerTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcLaborResource
struct IfcLaborResource : IfcConstructionResource, ObjectHelper<IfcLaborResource,1> { IfcLaborResource() : Object("IfcLaborResource") {}
Maybe< IfcText::Out > SkillSet;
};
// C++ wrapper for IfcFurnitureStandard
struct IfcFurnitureStandard : IfcControl, ObjectHelper<IfcFurnitureStandard,0> { IfcFurnitureStandard() : Object("IfcFurnitureStandard") {}
};
// C++ wrapper for IfcStairFlightType
struct IfcStairFlightType : IfcBuildingElementType, ObjectHelper<IfcStairFlightType,1> { IfcStairFlightType() : Object("IfcStairFlightType") {}
IfcStairFlightTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcWorkControl
struct IfcWorkControl : IfcControl, ObjectHelper<IfcWorkControl,10> { IfcWorkControl() : Object("IfcWorkControl") {}
IfcIdentifier::Out Identifier;
IfcDateTimeSelect::Out CreationDate;
Maybe< ListOf< Lazy< NotImplemented >, 1, 0 > > Creators;
Maybe< IfcLabel::Out > Purpose;
Maybe< IfcTimeMeasure::Out > Duration;
Maybe< IfcTimeMeasure::Out > TotalFloat;
IfcDateTimeSelect::Out StartTime;
Maybe< IfcDateTimeSelect::Out > FinishTime;
Maybe< IfcWorkControlTypeEnum::Out > WorkControlType;
Maybe< IfcLabel::Out > UserDefinedControlType;
};
// C++ wrapper for IfcWorkPlan
struct IfcWorkPlan : IfcWorkControl, ObjectHelper<IfcWorkPlan,0> { IfcWorkPlan() : Object("IfcWorkPlan") {}
};
// C++ wrapper for IfcCondition
struct IfcCondition : IfcGroup, ObjectHelper<IfcCondition,0> { IfcCondition() : Object("IfcCondition") {}
};
// C++ wrapper for IfcRelVoidsElement
struct IfcRelVoidsElement : IfcRelConnects, ObjectHelper<IfcRelVoidsElement,2> { IfcRelVoidsElement() : Object("IfcRelVoidsElement") {}
Lazy< IfcElement > RelatingBuildingElement;
Lazy< IfcFeatureElementSubtraction > RelatedOpeningElement;
};
// C++ wrapper for IfcWindow
struct IfcWindow : IfcBuildingElement, ObjectHelper<IfcWindow,2> { IfcWindow() : Object("IfcWindow") {}
Maybe< IfcPositiveLengthMeasure::Out > OverallHeight;
Maybe< IfcPositiveLengthMeasure::Out > OverallWidth;
};
// C++ wrapper for IfcProtectiveDeviceType
struct IfcProtectiveDeviceType : IfcFlowControllerType, ObjectHelper<IfcProtectiveDeviceType,1> { IfcProtectiveDeviceType() : Object("IfcProtectiveDeviceType") {}
IfcProtectiveDeviceTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcJunctionBoxType
struct IfcJunctionBoxType : IfcFlowFittingType, ObjectHelper<IfcJunctionBoxType,1> { IfcJunctionBoxType() : Object("IfcJunctionBoxType") {}
IfcJunctionBoxTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcStructuralAnalysisModel
struct IfcStructuralAnalysisModel : IfcSystem, ObjectHelper<IfcStructuralAnalysisModel,4> { IfcStructuralAnalysisModel() : Object("IfcStructuralAnalysisModel") {}
IfcAnalysisModelTypeEnum::Out PredefinedType;
Maybe< Lazy< IfcAxis2Placement3D > > OrientationOf2DPlane;
Maybe< ListOf< Lazy< IfcStructuralLoadGroup >, 1, 0 > > LoadedBy;
Maybe< ListOf< Lazy< IfcStructuralResultGroup >, 1, 0 > > HasResults;
};
// C++ wrapper for IfcAxis2Placement2D
struct IfcAxis2Placement2D : IfcPlacement, ObjectHelper<IfcAxis2Placement2D,1> { IfcAxis2Placement2D() : Object("IfcAxis2Placement2D") {}
Maybe< Lazy< IfcDirection > > RefDirection;
};
// C++ wrapper for IfcSpaceType
struct IfcSpaceType : IfcSpatialStructureElementType, ObjectHelper<IfcSpaceType,1> { IfcSpaceType() : Object("IfcSpaceType") {}
IfcSpaceTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcEllipseProfileDef
struct IfcEllipseProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcEllipseProfileDef,2> { IfcEllipseProfileDef() : Object("IfcEllipseProfileDef") {}
IfcPositiveLengthMeasure::Out SemiAxis1;
IfcPositiveLengthMeasure::Out SemiAxis2;
};
// C++ wrapper for IfcDistributionFlowElement
struct IfcDistributionFlowElement : IfcDistributionElement, ObjectHelper<IfcDistributionFlowElement,0> { IfcDistributionFlowElement() : Object("IfcDistributionFlowElement") {}
};
// C++ wrapper for IfcFlowMovingDevice
struct IfcFlowMovingDevice : IfcDistributionFlowElement, ObjectHelper<IfcFlowMovingDevice,0> { IfcFlowMovingDevice() : Object("IfcFlowMovingDevice") {}
};
// C++ wrapper for IfcSurfaceStyleWithTextures
struct IfcSurfaceStyleWithTextures : ObjectHelper<IfcSurfaceStyleWithTextures,1> { IfcSurfaceStyleWithTextures() : Object("IfcSurfaceStyleWithTextures") {}
ListOf< Lazy< NotImplemented >, 1, 0 > Textures;
};
// C++ wrapper for IfcGeometricSet
struct IfcGeometricSet : IfcGeometricRepresentationItem, ObjectHelper<IfcGeometricSet,1> { IfcGeometricSet() : Object("IfcGeometricSet") {}
ListOf< IfcGeometricSetSelect, 1, 0 >::Out Elements;
};
// C++ wrapper for IfcProjectOrder
struct IfcProjectOrder : IfcControl, ObjectHelper<IfcProjectOrder,3> { IfcProjectOrder() : Object("IfcProjectOrder") {}
IfcIdentifier::Out ID;
IfcProjectOrderTypeEnum::Out PredefinedType;
Maybe< IfcLabel::Out > Status;
};
// C++ wrapper for IfcBSplineCurve
struct IfcBSplineCurve : IfcBoundedCurve, ObjectHelper<IfcBSplineCurve,5> { IfcBSplineCurve() : Object("IfcBSplineCurve") {}
INTEGER::Out Degree;
ListOf< Lazy< IfcCartesianPoint >, 2, 0 > ControlPointsList;
IfcBSplineCurveForm::Out CurveForm;
LOGICAL::Out ClosedCurve;
LOGICAL::Out SelfIntersect;
};
// C++ wrapper for IfcBezierCurve
struct IfcBezierCurve : IfcBSplineCurve, ObjectHelper<IfcBezierCurve,0> { IfcBezierCurve() : Object("IfcBezierCurve") {}
};
// C++ wrapper for IfcStructuralPointConnection
struct IfcStructuralPointConnection : IfcStructuralConnection, ObjectHelper<IfcStructuralPointConnection,0> { IfcStructuralPointConnection() : Object("IfcStructuralPointConnection") {}
};
// C++ wrapper for IfcFlowController
struct IfcFlowController : IfcDistributionFlowElement, ObjectHelper<IfcFlowController,0> { IfcFlowController() : Object("IfcFlowController") {}
};
// C++ wrapper for IfcElectricDistributionPoint
struct IfcElectricDistributionPoint : IfcFlowController, ObjectHelper<IfcElectricDistributionPoint,2> { IfcElectricDistributionPoint() : Object("IfcElectricDistributionPoint") {}
IfcElectricDistributionPointFunctionEnum::Out DistributionPointFunction;
Maybe< IfcLabel::Out > UserDefinedFunction;
};
// C++ wrapper for IfcSite
struct IfcSite : IfcSpatialStructureElement, ObjectHelper<IfcSite,5> { IfcSite() : Object("IfcSite") {}
Maybe< IfcCompoundPlaneAngleMeasure::Out > RefLatitude;
Maybe< IfcCompoundPlaneAngleMeasure::Out > RefLongitude;
Maybe< IfcLengthMeasure::Out > RefElevation;
Maybe< IfcLabel::Out > LandTitleNumber;
Maybe< Lazy< NotImplemented > > SiteAddress;
};
// C++ wrapper for IfcOffsetCurve3D
struct IfcOffsetCurve3D : IfcCurve, ObjectHelper<IfcOffsetCurve3D,4> { IfcOffsetCurve3D() : Object("IfcOffsetCurve3D") {}
Lazy< IfcCurve > BasisCurve;
IfcLengthMeasure::Out Distance;
LOGICAL::Out SelfIntersect;
Lazy< IfcDirection > RefDirection;
};
// C++ wrapper for IfcVirtualElement
struct IfcVirtualElement : IfcElement, ObjectHelper<IfcVirtualElement,0> { IfcVirtualElement() : Object("IfcVirtualElement") {}
};
// C++ wrapper for IfcConstructionProductResource
struct IfcConstructionProductResource : IfcConstructionResource, ObjectHelper<IfcConstructionProductResource,0> { IfcConstructionProductResource() : Object("IfcConstructionProductResource") {}
};
// C++ wrapper for IfcSurfaceCurveSweptAreaSolid
struct IfcSurfaceCurveSweptAreaSolid : IfcSweptAreaSolid, ObjectHelper<IfcSurfaceCurveSweptAreaSolid,4> { IfcSurfaceCurveSweptAreaSolid() : Object("IfcSurfaceCurveSweptAreaSolid") {}
Lazy< IfcCurve > Directrix;
IfcParameterValue::Out StartParam;
IfcParameterValue::Out EndParam;
Lazy< IfcSurface > ReferenceSurface;
};
// C++ wrapper for IfcCartesianTransformationOperator3D
struct IfcCartesianTransformationOperator3D : IfcCartesianTransformationOperator, ObjectHelper<IfcCartesianTransformationOperator3D,1> { IfcCartesianTransformationOperator3D() : Object("IfcCartesianTransformationOperator3D") {}
Maybe< Lazy< IfcDirection > > Axis3;
};
// C++ wrapper for IfcCartesianTransformationOperator3DnonUniform
struct IfcCartesianTransformationOperator3DnonUniform : IfcCartesianTransformationOperator3D, ObjectHelper<IfcCartesianTransformationOperator3DnonUniform,2> { IfcCartesianTransformationOperator3DnonUniform() : Object("IfcCartesianTransformationOperator3DnonUniform") {}
Maybe< REAL::Out > Scale2;
Maybe< REAL::Out > Scale3;
};
// C++ wrapper for IfcCrewResource
struct IfcCrewResource : IfcConstructionResource, ObjectHelper<IfcCrewResource,0> { IfcCrewResource() : Object("IfcCrewResource") {}
};
// C++ wrapper for IfcStructuralSurfaceMember
struct IfcStructuralSurfaceMember : IfcStructuralMember, ObjectHelper<IfcStructuralSurfaceMember,2> { IfcStructuralSurfaceMember() : Object("IfcStructuralSurfaceMember") {}
IfcStructuralSurfaceTypeEnum::Out PredefinedType;
Maybe< IfcPositiveLengthMeasure::Out > Thickness;
};
// C++ wrapper for Ifc2DCompositeCurve
struct Ifc2DCompositeCurve : IfcCompositeCurve, ObjectHelper<Ifc2DCompositeCurve,0> { Ifc2DCompositeCurve() : Object("Ifc2DCompositeCurve") {}
};
// C++ wrapper for IfcRepresentationContext
struct IfcRepresentationContext : ObjectHelper<IfcRepresentationContext,2> { IfcRepresentationContext() : Object("IfcRepresentationContext") {}
Maybe< IfcLabel::Out > ContextIdentifier;
Maybe< IfcLabel::Out > ContextType;
};
// C++ wrapper for IfcGeometricRepresentationContext
struct IfcGeometricRepresentationContext : IfcRepresentationContext, ObjectHelper<IfcGeometricRepresentationContext,4> { IfcGeometricRepresentationContext() : Object("IfcGeometricRepresentationContext") {}
IfcDimensionCount::Out CoordinateSpaceDimension;
Maybe< REAL::Out > Precision;
IfcAxis2Placement::Out WorldCoordinateSystem;
Maybe< Lazy< IfcDirection > > TrueNorth;
};
// C++ wrapper for IfcFlowTreatmentDevice
struct IfcFlowTreatmentDevice : IfcDistributionFlowElement, ObjectHelper<IfcFlowTreatmentDevice,0> { IfcFlowTreatmentDevice() : Object("IfcFlowTreatmentDevice") {}
};
// C++ wrapper for IfcRightCircularCylinder
struct IfcRightCircularCylinder : IfcCsgPrimitive3D, ObjectHelper<IfcRightCircularCylinder,2> { IfcRightCircularCylinder() : Object("IfcRightCircularCylinder") {}
IfcPositiveLengthMeasure::Out Height;
IfcPositiveLengthMeasure::Out Radius;
};
// C++ wrapper for IfcWasteTerminalType
struct IfcWasteTerminalType : IfcFlowTerminalType, ObjectHelper<IfcWasteTerminalType,1> { IfcWasteTerminalType() : Object("IfcWasteTerminalType") {}
IfcWasteTerminalTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcBuildingElementComponent
struct IfcBuildingElementComponent : IfcBuildingElement, ObjectHelper<IfcBuildingElementComponent,0> { IfcBuildingElementComponent() : Object("IfcBuildingElementComponent") {}
};
// C++ wrapper for IfcBuildingElementPart
struct IfcBuildingElementPart : IfcBuildingElementComponent, ObjectHelper<IfcBuildingElementPart,0> { IfcBuildingElementPart() : Object("IfcBuildingElementPart") {}
};
// C++ wrapper for IfcWall
struct IfcWall : IfcBuildingElement, ObjectHelper<IfcWall,0> { IfcWall() : Object("IfcWall") {}
};
// C++ wrapper for IfcWallStandardCase
struct IfcWallStandardCase : IfcWall, ObjectHelper<IfcWallStandardCase,0> { IfcWallStandardCase() : Object("IfcWallStandardCase") {}
};
// C++ wrapper for IfcPath
struct IfcPath : IfcTopologicalRepresentationItem, ObjectHelper<IfcPath,1> { IfcPath() : Object("IfcPath") {}
ListOf< Lazy< IfcOrientedEdge >, 1, 0 > EdgeList;
};
// C++ wrapper for IfcDefinedSymbol
struct IfcDefinedSymbol : IfcGeometricRepresentationItem, ObjectHelper<IfcDefinedSymbol,2> { IfcDefinedSymbol() : Object("IfcDefinedSymbol") {}
IfcDefinedSymbolSelect::Out Definition;
Lazy< IfcCartesianTransformationOperator2D > Target;
};
// C++ wrapper for IfcStructuralSurfaceMemberVarying
struct IfcStructuralSurfaceMemberVarying : IfcStructuralSurfaceMember, ObjectHelper<IfcStructuralSurfaceMemberVarying,2> { IfcStructuralSurfaceMemberVarying() : Object("IfcStructuralSurfaceMemberVarying") {}
ListOf< IfcPositiveLengthMeasure, 2, 0 >::Out SubsequentThickness;
Lazy< NotImplemented > VaryingThicknessLocation;
};
// C++ wrapper for IfcPoint
struct IfcPoint : IfcGeometricRepresentationItem, ObjectHelper<IfcPoint,0> { IfcPoint() : Object("IfcPoint") {}
};
// C++ wrapper for IfcSurfaceOfRevolution
struct IfcSurfaceOfRevolution : IfcSweptSurface, ObjectHelper<IfcSurfaceOfRevolution,1> { IfcSurfaceOfRevolution() : Object("IfcSurfaceOfRevolution") {}
Lazy< IfcAxis1Placement > AxisPosition;
};
// C++ wrapper for IfcFlowTerminal
struct IfcFlowTerminal : IfcDistributionFlowElement, ObjectHelper<IfcFlowTerminal,0> { IfcFlowTerminal() : Object("IfcFlowTerminal") {}
};
// C++ wrapper for IfcFurnishingElement
struct IfcFurnishingElement : IfcElement, ObjectHelper<IfcFurnishingElement,0> { IfcFurnishingElement() : Object("IfcFurnishingElement") {}
};
// C++ wrapper for IfcSurfaceStyleShading
struct IfcSurfaceStyleShading : ObjectHelper<IfcSurfaceStyleShading,1> { IfcSurfaceStyleShading() : Object("IfcSurfaceStyleShading") {}
Lazy< IfcColourRgb > SurfaceColour;
};
// C++ wrapper for IfcSurfaceStyleRendering
struct IfcSurfaceStyleRendering : IfcSurfaceStyleShading, ObjectHelper<IfcSurfaceStyleRendering,8> { IfcSurfaceStyleRendering() : Object("IfcSurfaceStyleRendering") {}
Maybe< IfcNormalisedRatioMeasure::Out > Transparency;
Maybe< IfcColourOrFactor::Out > DiffuseColour;
Maybe< IfcColourOrFactor::Out > TransmissionColour;
Maybe< IfcColourOrFactor::Out > DiffuseTransmissionColour;
Maybe< IfcColourOrFactor::Out > ReflectionColour;
Maybe< IfcColourOrFactor::Out > SpecularColour;
Maybe< IfcSpecularHighlightSelect::Out > SpecularHighlight;
IfcReflectanceMethodEnum::Out ReflectanceMethod;
};
// C++ wrapper for IfcCircleHollowProfileDef
struct IfcCircleHollowProfileDef : IfcCircleProfileDef, ObjectHelper<IfcCircleHollowProfileDef,1> { IfcCircleHollowProfileDef() : Object("IfcCircleHollowProfileDef") {}
IfcPositiveLengthMeasure::Out WallThickness;
};
// C++ wrapper for IfcFlowMovingDeviceType
struct IfcFlowMovingDeviceType : IfcDistributionFlowElementType, ObjectHelper<IfcFlowMovingDeviceType,0> { IfcFlowMovingDeviceType() : Object("IfcFlowMovingDeviceType") {}
};
// C++ wrapper for IfcFanType
struct IfcFanType : IfcFlowMovingDeviceType, ObjectHelper<IfcFanType,1> { IfcFanType() : Object("IfcFanType") {}
IfcFanTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcStructuralPlanarActionVarying
struct IfcStructuralPlanarActionVarying : IfcStructuralPlanarAction, ObjectHelper<IfcStructuralPlanarActionVarying,2> { IfcStructuralPlanarActionVarying() : Object("IfcStructuralPlanarActionVarying") {}
Lazy< NotImplemented > VaryingAppliedLoadLocation;
ListOf< Lazy< NotImplemented >, 2, 0 > SubsequentAppliedLoads;
};
// C++ wrapper for IfcProductRepresentation
struct IfcProductRepresentation : ObjectHelper<IfcProductRepresentation,3> { IfcProductRepresentation() : Object("IfcProductRepresentation") {}
Maybe< IfcLabel::Out > Name;
Maybe< IfcText::Out > Description;
ListOf< Lazy< IfcRepresentation >, 1, 0 > Representations;
};
// C++ wrapper for IfcStackTerminalType
struct IfcStackTerminalType : IfcFlowTerminalType, ObjectHelper<IfcStackTerminalType,1> { IfcStackTerminalType() : Object("IfcStackTerminalType") {}
IfcStackTerminalTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcReinforcingElement
struct IfcReinforcingElement : IfcBuildingElementComponent, ObjectHelper<IfcReinforcingElement,1> { IfcReinforcingElement() : Object("IfcReinforcingElement") {}
Maybe< IfcLabel::Out > SteelGrade;
};
// C++ wrapper for IfcReinforcingMesh
struct IfcReinforcingMesh : IfcReinforcingElement, ObjectHelper<IfcReinforcingMesh,8> { IfcReinforcingMesh() : Object("IfcReinforcingMesh") {}
Maybe< IfcPositiveLengthMeasure::Out > MeshLength;
Maybe< IfcPositiveLengthMeasure::Out > MeshWidth;
IfcPositiveLengthMeasure::Out LongitudinalBarNominalDiameter;
IfcPositiveLengthMeasure::Out TransverseBarNominalDiameter;
IfcAreaMeasure::Out LongitudinalBarCrossSectionArea;
IfcAreaMeasure::Out TransverseBarCrossSectionArea;
IfcPositiveLengthMeasure::Out LongitudinalBarSpacing;
IfcPositiveLengthMeasure::Out TransverseBarSpacing;
};
// C++ wrapper for IfcOrderAction
struct IfcOrderAction : IfcTask, ObjectHelper<IfcOrderAction,1> { IfcOrderAction() : Object("IfcOrderAction") {}
IfcIdentifier::Out ActionID;
};
// C++ wrapper for IfcLightSource
struct IfcLightSource : IfcGeometricRepresentationItem, ObjectHelper<IfcLightSource,4> { IfcLightSource() : Object("IfcLightSource") {}
Maybe< IfcLabel::Out > Name;
Lazy< IfcColourRgb > LightColour;
Maybe< IfcNormalisedRatioMeasure::Out > AmbientIntensity;
Maybe< IfcNormalisedRatioMeasure::Out > Intensity;
};
// C++ wrapper for IfcLightSourceDirectional
struct IfcLightSourceDirectional : IfcLightSource, ObjectHelper<IfcLightSourceDirectional,1> { IfcLightSourceDirectional() : Object("IfcLightSourceDirectional") {}
Lazy< IfcDirection > Orientation;
};
// C++ wrapper for IfcLoop
struct IfcLoop : IfcTopologicalRepresentationItem, ObjectHelper<IfcLoop,0> { IfcLoop() : Object("IfcLoop") {}
};
// C++ wrapper for IfcVertexLoop
struct IfcVertexLoop : IfcLoop, ObjectHelper<IfcVertexLoop,1> { IfcVertexLoop() : Object("IfcVertexLoop") {}
Lazy< IfcVertex > LoopVertex;
};
// C++ wrapper for IfcChamferEdgeFeature
struct IfcChamferEdgeFeature : IfcEdgeFeature, ObjectHelper<IfcChamferEdgeFeature,2> { IfcChamferEdgeFeature() : Object("IfcChamferEdgeFeature") {}
Maybe< IfcPositiveLengthMeasure::Out > Width;
Maybe< IfcPositiveLengthMeasure::Out > Height;
};
// C++ wrapper for IfcElementComponentType
struct IfcElementComponentType : IfcElementType, ObjectHelper<IfcElementComponentType,0> { IfcElementComponentType() : Object("IfcElementComponentType") {}
};
// C++ wrapper for IfcFastenerType
struct IfcFastenerType : IfcElementComponentType, ObjectHelper<IfcFastenerType,0> { IfcFastenerType() : Object("IfcFastenerType") {}
};
// C++ wrapper for IfcMechanicalFastenerType
struct IfcMechanicalFastenerType : IfcFastenerType, ObjectHelper<IfcMechanicalFastenerType,0> { IfcMechanicalFastenerType() : Object("IfcMechanicalFastenerType") {}
};
// C++ wrapper for IfcScheduleTimeControl
struct IfcScheduleTimeControl : IfcControl, ObjectHelper<IfcScheduleTimeControl,18> { IfcScheduleTimeControl() : Object("IfcScheduleTimeControl") {}
Maybe< IfcDateTimeSelect::Out > ActualStart;
Maybe< IfcDateTimeSelect::Out > EarlyStart;
Maybe< IfcDateTimeSelect::Out > LateStart;
Maybe< IfcDateTimeSelect::Out > ScheduleStart;
Maybe< IfcDateTimeSelect::Out > ActualFinish;
Maybe< IfcDateTimeSelect::Out > EarlyFinish;
Maybe< IfcDateTimeSelect::Out > LateFinish;
Maybe< IfcDateTimeSelect::Out > ScheduleFinish;
Maybe< IfcTimeMeasure::Out > ScheduleDuration;
Maybe< IfcTimeMeasure::Out > ActualDuration;
Maybe< IfcTimeMeasure::Out > RemainingTime;
Maybe< IfcTimeMeasure::Out > FreeFloat;
Maybe< IfcTimeMeasure::Out > TotalFloat;
Maybe< BOOLEAN::Out > IsCritical;
Maybe< IfcDateTimeSelect::Out > StatusTime;
Maybe< IfcTimeMeasure::Out > StartFloat;
Maybe< IfcTimeMeasure::Out > FinishFloat;
Maybe< IfcPositiveRatioMeasure::Out > Completion;
};
// C++ wrapper for IfcSurfaceStyle
struct IfcSurfaceStyle : IfcPresentationStyle, ObjectHelper<IfcSurfaceStyle,2> { IfcSurfaceStyle() : Object("IfcSurfaceStyle") {}
IfcSurfaceSide::Out Side;
ListOf< IfcSurfaceStyleElementSelect, 1, 5 >::Out Styles;
};
// C++ wrapper for IfcOpenShell
struct IfcOpenShell : IfcConnectedFaceSet, ObjectHelper<IfcOpenShell,0> { IfcOpenShell() : Object("IfcOpenShell") {}
};
// C++ wrapper for IfcSubContractResource
struct IfcSubContractResource : IfcConstructionResource, ObjectHelper<IfcSubContractResource,2> { IfcSubContractResource() : Object("IfcSubContractResource") {}
Maybe< IfcActorSelect::Out > SubContractor;
Maybe< IfcText::Out > JobDescription;
};
// C++ wrapper for IfcSweptDiskSolid
struct IfcSweptDiskSolid : IfcSolidModel, ObjectHelper<IfcSweptDiskSolid,5> { IfcSweptDiskSolid() : Object("IfcSweptDiskSolid") {}
Lazy< IfcCurve > Directrix;
IfcPositiveLengthMeasure::Out Radius;
Maybe< IfcPositiveLengthMeasure::Out > InnerRadius;
IfcParameterValue::Out StartParam;
IfcParameterValue::Out EndParam;
};
// C++ wrapper for IfcTankType
struct IfcTankType : IfcFlowStorageDeviceType, ObjectHelper<IfcTankType,1> { IfcTankType() : Object("IfcTankType") {}
IfcTankTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcSphere
struct IfcSphere : IfcCsgPrimitive3D, ObjectHelper<IfcSphere,1> { IfcSphere() : Object("IfcSphere") {}
IfcPositiveLengthMeasure::Out Radius;
};
// C++ wrapper for IfcPolyLoop
struct IfcPolyLoop : IfcLoop, ObjectHelper<IfcPolyLoop,1> { IfcPolyLoop() : Object("IfcPolyLoop") {}
ListOf< Lazy< IfcCartesianPoint >, 3, 0 > Polygon;
};
// C++ wrapper for IfcCableCarrierFittingType
struct IfcCableCarrierFittingType : IfcFlowFittingType, ObjectHelper<IfcCableCarrierFittingType,1> { IfcCableCarrierFittingType() : Object("IfcCableCarrierFittingType") {}
IfcCableCarrierFittingTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcHumidifierType
struct IfcHumidifierType : IfcEnergyConversionDeviceType, ObjectHelper<IfcHumidifierType,1> { IfcHumidifierType() : Object("IfcHumidifierType") {}
IfcHumidifierTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcPerformanceHistory
struct IfcPerformanceHistory : IfcControl, ObjectHelper<IfcPerformanceHistory,1> { IfcPerformanceHistory() : Object("IfcPerformanceHistory") {}
IfcLabel::Out LifeCyclePhase;
};
// C++ wrapper for IfcShapeModel
struct IfcShapeModel : IfcRepresentation, ObjectHelper<IfcShapeModel,0> { IfcShapeModel() : Object("IfcShapeModel") {}
};
// C++ wrapper for IfcTopologyRepresentation
struct IfcTopologyRepresentation : IfcShapeModel, ObjectHelper<IfcTopologyRepresentation,0> { IfcTopologyRepresentation() : Object("IfcTopologyRepresentation") {}
};
// C++ wrapper for IfcBuilding
struct IfcBuilding : IfcSpatialStructureElement, ObjectHelper<IfcBuilding,3> { IfcBuilding() : Object("IfcBuilding") {}
Maybe< IfcLengthMeasure::Out > ElevationOfRefHeight;
Maybe< IfcLengthMeasure::Out > ElevationOfTerrain;
Maybe< Lazy< NotImplemented > > BuildingAddress;
};
// C++ wrapper for IfcRoundedRectangleProfileDef
struct IfcRoundedRectangleProfileDef : IfcRectangleProfileDef, ObjectHelper<IfcRoundedRectangleProfileDef,1> { IfcRoundedRectangleProfileDef() : Object("IfcRoundedRectangleProfileDef") {}
IfcPositiveLengthMeasure::Out RoundingRadius;
};
// C++ wrapper for IfcStairFlight
struct IfcStairFlight : IfcBuildingElement, ObjectHelper<IfcStairFlight,4> { IfcStairFlight() : Object("IfcStairFlight") {}
Maybe< INTEGER::Out > NumberOfRiser;
Maybe< INTEGER::Out > NumberOfTreads;
Maybe< IfcPositiveLengthMeasure::Out > RiserHeight;
Maybe< IfcPositiveLengthMeasure::Out > TreadLength;
};
// C++ wrapper for IfcDistributionChamberElement
struct IfcDistributionChamberElement : IfcDistributionFlowElement, ObjectHelper<IfcDistributionChamberElement,0> { IfcDistributionChamberElement() : Object("IfcDistributionChamberElement") {}
};
// C++ wrapper for IfcShapeRepresentation
struct IfcShapeRepresentation : IfcShapeModel, ObjectHelper<IfcShapeRepresentation,0> { IfcShapeRepresentation() : Object("IfcShapeRepresentation") {}
};
// C++ wrapper for IfcRampFlight
struct IfcRampFlight : IfcBuildingElement, ObjectHelper<IfcRampFlight,0> { IfcRampFlight() : Object("IfcRampFlight") {}
};
// C++ wrapper for IfcBeamType
struct IfcBeamType : IfcBuildingElementType, ObjectHelper<IfcBeamType,1> { IfcBeamType() : Object("IfcBeamType") {}
IfcBeamTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcRelDecomposes
struct IfcRelDecomposes : IfcRelationship, ObjectHelper<IfcRelDecomposes,2> { IfcRelDecomposes() : Object("IfcRelDecomposes") {}
Lazy< IfcObjectDefinition > RelatingObject;
ListOf< Lazy< IfcObjectDefinition >, 1, 0 > RelatedObjects;
};
// C++ wrapper for IfcRoof
struct IfcRoof : IfcBuildingElement, ObjectHelper<IfcRoof,1> { IfcRoof() : Object("IfcRoof") {}
IfcRoofTypeEnum::Out ShapeType;
};
// C++ wrapper for IfcFooting
struct IfcFooting : IfcBuildingElement, ObjectHelper<IfcFooting,1> { IfcFooting() : Object("IfcFooting") {}
IfcFootingTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcLightSourceAmbient
struct IfcLightSourceAmbient : IfcLightSource, ObjectHelper<IfcLightSourceAmbient,0> { IfcLightSourceAmbient() : Object("IfcLightSourceAmbient") {}
};
// C++ wrapper for IfcWindowStyle
struct IfcWindowStyle : IfcTypeProduct, ObjectHelper<IfcWindowStyle,4> { IfcWindowStyle() : Object("IfcWindowStyle") {}
IfcWindowStyleConstructionEnum::Out ConstructionType;
IfcWindowStyleOperationEnum::Out OperationType;
BOOLEAN::Out ParameterTakesPrecedence;
BOOLEAN::Out Sizeable;
};
// C++ wrapper for IfcBuildingElementProxyType
struct IfcBuildingElementProxyType : IfcBuildingElementType, ObjectHelper<IfcBuildingElementProxyType,1> { IfcBuildingElementProxyType() : Object("IfcBuildingElementProxyType") {}
IfcBuildingElementProxyTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcAxis2Placement3D
struct IfcAxis2Placement3D : IfcPlacement, ObjectHelper<IfcAxis2Placement3D,2> { IfcAxis2Placement3D() : Object("IfcAxis2Placement3D") {}
Maybe< Lazy< IfcDirection > > Axis;
Maybe< Lazy< IfcDirection > > RefDirection;
};
// C++ wrapper for IfcEdgeCurve
struct IfcEdgeCurve : IfcEdge, ObjectHelper<IfcEdgeCurve,2> { IfcEdgeCurve() : Object("IfcEdgeCurve") {}
Lazy< IfcCurve > EdgeGeometry;
BOOLEAN::Out SameSense;
};
// C++ wrapper for IfcClosedShell
struct IfcClosedShell : IfcConnectedFaceSet, ObjectHelper<IfcClosedShell,0> { IfcClosedShell() : Object("IfcClosedShell") {}
};
// C++ wrapper for IfcTendonAnchor
struct IfcTendonAnchor : IfcReinforcingElement, ObjectHelper<IfcTendonAnchor,0> { IfcTendonAnchor() : Object("IfcTendonAnchor") {}
};
// C++ wrapper for IfcCondenserType
struct IfcCondenserType : IfcEnergyConversionDeviceType, ObjectHelper<IfcCondenserType,1> { IfcCondenserType() : Object("IfcCondenserType") {}
IfcCondenserTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcPipeSegmentType
struct IfcPipeSegmentType : IfcFlowSegmentType, ObjectHelper<IfcPipeSegmentType,1> { IfcPipeSegmentType() : Object("IfcPipeSegmentType") {}
IfcPipeSegmentTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcPointOnSurface
struct IfcPointOnSurface : IfcPoint, ObjectHelper<IfcPointOnSurface,3> { IfcPointOnSurface() : Object("IfcPointOnSurface") {}
Lazy< IfcSurface > BasisSurface;
IfcParameterValue::Out PointParameterU;
IfcParameterValue::Out PointParameterV;
};
// C++ wrapper for IfcAsset
struct IfcAsset : IfcGroup, ObjectHelper<IfcAsset,9> { IfcAsset() : Object("IfcAsset") {}
IfcIdentifier::Out AssetID;
Lazy< NotImplemented > OriginalValue;
Lazy< NotImplemented > CurrentValue;
Lazy< NotImplemented > TotalReplacementCost;
IfcActorSelect::Out Owner;
IfcActorSelect::Out User;
Lazy< NotImplemented > ResponsiblePerson;
Lazy< NotImplemented > IncorporationDate;
Lazy< NotImplemented > DepreciatedValue;
};
// C++ wrapper for IfcLightSourcePositional
struct IfcLightSourcePositional : IfcLightSource, ObjectHelper<IfcLightSourcePositional,5> { IfcLightSourcePositional() : Object("IfcLightSourcePositional") {}
Lazy< IfcCartesianPoint > Position;
IfcPositiveLengthMeasure::Out Radius;
IfcReal::Out ConstantAttenuation;
IfcReal::Out DistanceAttenuation;
IfcReal::Out QuadricAttenuation;
};
// C++ wrapper for IfcProjectionCurve
struct IfcProjectionCurve : IfcAnnotationCurveOccurrence, ObjectHelper<IfcProjectionCurve,0> { IfcProjectionCurve() : Object("IfcProjectionCurve") {}
};
// C++ wrapper for IfcFillAreaStyleTiles
struct IfcFillAreaStyleTiles : IfcGeometricRepresentationItem, ObjectHelper<IfcFillAreaStyleTiles,3> { IfcFillAreaStyleTiles() : Object("IfcFillAreaStyleTiles") {}
Lazy< IfcOneDirectionRepeatFactor > TilingPattern;
ListOf< IfcFillAreaStyleTileShapeSelect, 1, 0 >::Out Tiles;
IfcPositiveRatioMeasure::Out TilingScale;
};
// C++ wrapper for IfcElectricMotorType
struct IfcElectricMotorType : IfcEnergyConversionDeviceType, ObjectHelper<IfcElectricMotorType,1> { IfcElectricMotorType() : Object("IfcElectricMotorType") {}
IfcElectricMotorTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcTendon
struct IfcTendon : IfcReinforcingElement, ObjectHelper<IfcTendon,8> { IfcTendon() : Object("IfcTendon") {}
IfcTendonTypeEnum::Out PredefinedType;
IfcPositiveLengthMeasure::Out NominalDiameter;
IfcAreaMeasure::Out CrossSectionArea;
Maybe< IfcForceMeasure::Out > TensionForce;
Maybe< IfcPressureMeasure::Out > PreStress;
Maybe< IfcNormalisedRatioMeasure::Out > FrictionCoefficient;
Maybe< IfcPositiveLengthMeasure::Out > AnchorageSlip;
Maybe< IfcPositiveLengthMeasure::Out > MinCurvatureRadius;
};
// C++ wrapper for IfcDistributionChamberElementType
struct IfcDistributionChamberElementType : IfcDistributionFlowElementType, ObjectHelper<IfcDistributionChamberElementType,1> { IfcDistributionChamberElementType() : Object("IfcDistributionChamberElementType") {}
IfcDistributionChamberElementTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcMemberType
struct IfcMemberType : IfcBuildingElementType, ObjectHelper<IfcMemberType,1> { IfcMemberType() : Object("IfcMemberType") {}
IfcMemberTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcStructuralLinearAction
struct IfcStructuralLinearAction : IfcStructuralAction, ObjectHelper<IfcStructuralLinearAction,1> { IfcStructuralLinearAction() : Object("IfcStructuralLinearAction") {}
IfcProjectedOrTrueLengthEnum::Out ProjectedOrTrue;
};
// C++ wrapper for IfcStructuralLinearActionVarying
struct IfcStructuralLinearActionVarying : IfcStructuralLinearAction, ObjectHelper<IfcStructuralLinearActionVarying,2> { IfcStructuralLinearActionVarying() : Object("IfcStructuralLinearActionVarying") {}
Lazy< NotImplemented > VaryingAppliedLoadLocation;
ListOf< Lazy< NotImplemented >, 1, 0 > SubsequentAppliedLoads;
};
// C++ wrapper for IfcProductDefinitionShape
struct IfcProductDefinitionShape : IfcProductRepresentation, ObjectHelper<IfcProductDefinitionShape,0> { IfcProductDefinitionShape() : Object("IfcProductDefinitionShape") {}
};
// C++ wrapper for IfcFastener
struct IfcFastener : IfcElementComponent, ObjectHelper<IfcFastener,0> { IfcFastener() : Object("IfcFastener") {}
};
// C++ wrapper for IfcMechanicalFastener
struct IfcMechanicalFastener : IfcFastener, ObjectHelper<IfcMechanicalFastener,2> { IfcMechanicalFastener() : Object("IfcMechanicalFastener") {}
Maybe< IfcPositiveLengthMeasure::Out > NominalDiameter;
Maybe< IfcPositiveLengthMeasure::Out > NominalLength;
};
// C++ wrapper for IfcEvaporatorType
struct IfcEvaporatorType : IfcEnergyConversionDeviceType, ObjectHelper<IfcEvaporatorType,1> { IfcEvaporatorType() : Object("IfcEvaporatorType") {}
IfcEvaporatorTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcDiscreteAccessoryType
struct IfcDiscreteAccessoryType : IfcElementComponentType, ObjectHelper<IfcDiscreteAccessoryType,0> { IfcDiscreteAccessoryType() : Object("IfcDiscreteAccessoryType") {}
};
// C++ wrapper for IfcStructuralCurveConnection
struct IfcStructuralCurveConnection : IfcStructuralConnection, ObjectHelper<IfcStructuralCurveConnection,0> { IfcStructuralCurveConnection() : Object("IfcStructuralCurveConnection") {}
};
// C++ wrapper for IfcProjectionElement
struct IfcProjectionElement : IfcFeatureElementAddition, ObjectHelper<IfcProjectionElement,0> { IfcProjectionElement() : Object("IfcProjectionElement") {}
};
// C++ wrapper for IfcCoveringType
struct IfcCoveringType : IfcBuildingElementType, ObjectHelper<IfcCoveringType,1> { IfcCoveringType() : Object("IfcCoveringType") {}
IfcCoveringTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcPumpType
struct IfcPumpType : IfcFlowMovingDeviceType, ObjectHelper<IfcPumpType,1> { IfcPumpType() : Object("IfcPumpType") {}
IfcPumpTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcPile
struct IfcPile : IfcBuildingElement, ObjectHelper<IfcPile,2> { IfcPile() : Object("IfcPile") {}
IfcPileTypeEnum::Out PredefinedType;
Maybe< IfcPileConstructionEnum::Out > ConstructionType;
};
// C++ wrapper for IfcUnitAssignment
struct IfcUnitAssignment : ObjectHelper<IfcUnitAssignment,1> { IfcUnitAssignment() : Object("IfcUnitAssignment") {}
ListOf< IfcUnit, 1, 0 >::Out Units;
};
// C++ wrapper for IfcBoundingBox
struct IfcBoundingBox : IfcGeometricRepresentationItem, ObjectHelper<IfcBoundingBox,4> { IfcBoundingBox() : Object("IfcBoundingBox") {}
Lazy< IfcCartesianPoint > Corner;
IfcPositiveLengthMeasure::Out XDim;
IfcPositiveLengthMeasure::Out YDim;
IfcPositiveLengthMeasure::Out ZDim;
};
// C++ wrapper for IfcShellBasedSurfaceModel
struct IfcShellBasedSurfaceModel : IfcGeometricRepresentationItem, ObjectHelper<IfcShellBasedSurfaceModel,1> { IfcShellBasedSurfaceModel() : Object("IfcShellBasedSurfaceModel") {}
ListOf< IfcShell, 1, 0 >::Out SbsmBoundary;
};
// C++ wrapper for IfcFacetedBrep
struct IfcFacetedBrep : IfcManifoldSolidBrep, ObjectHelper<IfcFacetedBrep,0> { IfcFacetedBrep() : Object("IfcFacetedBrep") {}
};
// C++ wrapper for IfcTextLiteralWithExtent
struct IfcTextLiteralWithExtent : IfcTextLiteral, ObjectHelper<IfcTextLiteralWithExtent,2> { IfcTextLiteralWithExtent() : Object("IfcTextLiteralWithExtent") {}
Lazy< IfcPlanarExtent > Extent;
IfcBoxAlignment::Out BoxAlignment;
};
// C++ wrapper for IfcElectricApplianceType
struct IfcElectricApplianceType : IfcFlowTerminalType, ObjectHelper<IfcElectricApplianceType,1> { IfcElectricApplianceType() : Object("IfcElectricApplianceType") {}
IfcElectricApplianceTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcTrapeziumProfileDef
struct IfcTrapeziumProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcTrapeziumProfileDef,4> { IfcTrapeziumProfileDef() : Object("IfcTrapeziumProfileDef") {}
IfcPositiveLengthMeasure::Out BottomXDim;
IfcPositiveLengthMeasure::Out TopXDim;
IfcPositiveLengthMeasure::Out YDim;
IfcLengthMeasure::Out TopXOffset;
};
// C++ wrapper for IfcRelContainedInSpatialStructure
struct IfcRelContainedInSpatialStructure : IfcRelConnects, ObjectHelper<IfcRelContainedInSpatialStructure,2> { IfcRelContainedInSpatialStructure() : Object("IfcRelContainedInSpatialStructure") {}
ListOf< Lazy< IfcProduct >, 1, 0 > RelatedElements;
Lazy< IfcSpatialStructureElement > RelatingStructure;
};
// C++ wrapper for IfcEdgeLoop
struct IfcEdgeLoop : IfcLoop, ObjectHelper<IfcEdgeLoop,1> { IfcEdgeLoop() : Object("IfcEdgeLoop") {}
ListOf< Lazy< IfcOrientedEdge >, 1, 0 > EdgeList;
};
// C++ wrapper for IfcProject
struct IfcProject : IfcObject, ObjectHelper<IfcProject,4> { IfcProject() : Object("IfcProject") {}
Maybe< IfcLabel::Out > LongName;
Maybe< IfcLabel::Out > Phase;
ListOf< Lazy< IfcRepresentationContext >, 1, 0 > RepresentationContexts;
Lazy< IfcUnitAssignment > UnitsInContext;
};
// C++ wrapper for IfcCartesianPoint
struct IfcCartesianPoint : IfcPoint, ObjectHelper<IfcCartesianPoint,1> { IfcCartesianPoint() : Object("IfcCartesianPoint") {}
ListOf< IfcLengthMeasure, 1, 3 >::Out Coordinates;
};
// C++ wrapper for IfcCurveBoundedPlane
struct IfcCurveBoundedPlane : IfcBoundedSurface, ObjectHelper<IfcCurveBoundedPlane,3> { IfcCurveBoundedPlane() : Object("IfcCurveBoundedPlane") {}
Lazy< IfcPlane > BasisSurface;
Lazy< IfcCurve > OuterBoundary;
ListOf< Lazy< IfcCurve >, 0, 0 > InnerBoundaries;
};
// C++ wrapper for IfcWallType
struct IfcWallType : IfcBuildingElementType, ObjectHelper<IfcWallType,1> { IfcWallType() : Object("IfcWallType") {}
IfcWallTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcFillAreaStyleHatching
struct IfcFillAreaStyleHatching : IfcGeometricRepresentationItem, ObjectHelper<IfcFillAreaStyleHatching,5> { IfcFillAreaStyleHatching() : Object("IfcFillAreaStyleHatching") {}
Lazy< NotImplemented > HatchLineAppearance;
IfcHatchLineDistanceSelect::Out StartOfNextHatchLine;
Maybe< Lazy< IfcCartesianPoint > > PointOfReferenceHatchLine;
Maybe< Lazy< IfcCartesianPoint > > PatternStart;
IfcPlaneAngleMeasure::Out HatchLineAngle;
};
// C++ wrapper for IfcEquipmentStandard
struct IfcEquipmentStandard : IfcControl, ObjectHelper<IfcEquipmentStandard,0> { IfcEquipmentStandard() : Object("IfcEquipmentStandard") {}
};
// C++ wrapper for IfcDiameterDimension
struct IfcDiameterDimension : IfcDimensionCurveDirectedCallout, ObjectHelper<IfcDiameterDimension,0> { IfcDiameterDimension() : Object("IfcDiameterDimension") {}
};
// C++ wrapper for IfcStructuralLoadGroup
struct IfcStructuralLoadGroup : IfcGroup, ObjectHelper<IfcStructuralLoadGroup,5> { IfcStructuralLoadGroup() : Object("IfcStructuralLoadGroup") {}
IfcLoadGroupTypeEnum::Out PredefinedType;
IfcActionTypeEnum::Out ActionType;
IfcActionSourceTypeEnum::Out ActionSource;
Maybe< IfcPositiveRatioMeasure::Out > Coefficient;
Maybe< IfcLabel::Out > Purpose;
};
// C++ wrapper for IfcConstructionMaterialResource
struct IfcConstructionMaterialResource : IfcConstructionResource, ObjectHelper<IfcConstructionMaterialResource,2> { IfcConstructionMaterialResource() : Object("IfcConstructionMaterialResource") {}
Maybe< ListOf< IfcActorSelect, 1, 0 >::Out > Suppliers;
Maybe< IfcRatioMeasure::Out > UsageRatio;
};
// C++ wrapper for IfcRelAggregates
struct IfcRelAggregates : IfcRelDecomposes, ObjectHelper<IfcRelAggregates,0> { IfcRelAggregates() : Object("IfcRelAggregates") {}
};
// C++ wrapper for IfcBoilerType
struct IfcBoilerType : IfcEnergyConversionDeviceType, ObjectHelper<IfcBoilerType,1> { IfcBoilerType() : Object("IfcBoilerType") {}
IfcBoilerTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcColourSpecification
struct IfcColourSpecification : ObjectHelper<IfcColourSpecification,1> { IfcColourSpecification() : Object("IfcColourSpecification") {}
Maybe< IfcLabel::Out > Name;
};
// C++ wrapper for IfcColourRgb
struct IfcColourRgb : IfcColourSpecification, ObjectHelper<IfcColourRgb,3> { IfcColourRgb() : Object("IfcColourRgb") {}
IfcNormalisedRatioMeasure::Out Red;
IfcNormalisedRatioMeasure::Out Green;
IfcNormalisedRatioMeasure::Out Blue;
};
// C++ wrapper for IfcDoorStyle
struct IfcDoorStyle : IfcTypeProduct, ObjectHelper<IfcDoorStyle,4> { IfcDoorStyle() : Object("IfcDoorStyle") {}
IfcDoorStyleOperationEnum::Out OperationType;
IfcDoorStyleConstructionEnum::Out ConstructionType;
BOOLEAN::Out ParameterTakesPrecedence;
BOOLEAN::Out Sizeable;
};
// C++ wrapper for IfcDuctSilencerType
struct IfcDuctSilencerType : IfcFlowTreatmentDeviceType, ObjectHelper<IfcDuctSilencerType,1> { IfcDuctSilencerType() : Object("IfcDuctSilencerType") {}
IfcDuctSilencerTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcLightSourceGoniometric
struct IfcLightSourceGoniometric : IfcLightSource, ObjectHelper<IfcLightSourceGoniometric,6> { IfcLightSourceGoniometric() : Object("IfcLightSourceGoniometric") {}
Lazy< IfcAxis2Placement3D > Position;
Maybe< Lazy< IfcColourRgb > > ColourAppearance;
IfcThermodynamicTemperatureMeasure::Out ColourTemperature;
IfcLuminousFluxMeasure::Out LuminousFlux;
IfcLightEmissionSourceEnum::Out LightEmissionSource;
IfcLightDistributionDataSourceSelect::Out LightDistributionDataSource;
};
// C++ wrapper for IfcActuatorType
struct IfcActuatorType : IfcDistributionControlElementType, ObjectHelper<IfcActuatorType,1> { IfcActuatorType() : Object("IfcActuatorType") {}
IfcActuatorTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcSensorType
struct IfcSensorType : IfcDistributionControlElementType, ObjectHelper<IfcSensorType,1> { IfcSensorType() : Object("IfcSensorType") {}
IfcSensorTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcAirTerminalBoxType
struct IfcAirTerminalBoxType : IfcFlowControllerType, ObjectHelper<IfcAirTerminalBoxType,1> { IfcAirTerminalBoxType() : Object("IfcAirTerminalBoxType") {}
IfcAirTerminalBoxTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcAnnotationSurfaceOccurrence
struct IfcAnnotationSurfaceOccurrence : IfcAnnotationOccurrence, ObjectHelper<IfcAnnotationSurfaceOccurrence,0> { IfcAnnotationSurfaceOccurrence() : Object("IfcAnnotationSurfaceOccurrence") {}
};
// C++ wrapper for IfcZShapeProfileDef
struct IfcZShapeProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcZShapeProfileDef,6> { IfcZShapeProfileDef() : Object("IfcZShapeProfileDef") {}
IfcPositiveLengthMeasure::Out Depth;
IfcPositiveLengthMeasure::Out FlangeWidth;
IfcPositiveLengthMeasure::Out WebThickness;
IfcPositiveLengthMeasure::Out FlangeThickness;
Maybe< IfcPositiveLengthMeasure::Out > FilletRadius;
Maybe< IfcPositiveLengthMeasure::Out > EdgeRadius;
};
// C++ wrapper for IfcRationalBezierCurve
struct IfcRationalBezierCurve : IfcBezierCurve, ObjectHelper<IfcRationalBezierCurve,1> { IfcRationalBezierCurve() : Object("IfcRationalBezierCurve") {}
ListOf< REAL, 2, 0 >::Out WeightsData;
};
// C++ wrapper for IfcCartesianTransformationOperator2D
struct IfcCartesianTransformationOperator2D : IfcCartesianTransformationOperator, ObjectHelper<IfcCartesianTransformationOperator2D,0> { IfcCartesianTransformationOperator2D() : Object("IfcCartesianTransformationOperator2D") {}
};
// C++ wrapper for IfcCartesianTransformationOperator2DnonUniform
struct IfcCartesianTransformationOperator2DnonUniform : IfcCartesianTransformationOperator2D, ObjectHelper<IfcCartesianTransformationOperator2DnonUniform,1> { IfcCartesianTransformationOperator2DnonUniform() : Object("IfcCartesianTransformationOperator2DnonUniform") {}
Maybe< REAL::Out > Scale2;
};
// C++ wrapper for IfcMove
struct IfcMove : IfcTask, ObjectHelper<IfcMove,3> { IfcMove() : Object("IfcMove") {}
Lazy< IfcSpatialStructureElement > MoveFrom;
Lazy< IfcSpatialStructureElement > MoveTo;
Maybe< ListOf< IfcText, 1, 0 >::Out > PunchList;
};
// C++ wrapper for IfcCableCarrierSegmentType
struct IfcCableCarrierSegmentType : IfcFlowSegmentType, ObjectHelper<IfcCableCarrierSegmentType,1> { IfcCableCarrierSegmentType() : Object("IfcCableCarrierSegmentType") {}
IfcCableCarrierSegmentTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcElectricalElement
struct IfcElectricalElement : IfcElement, ObjectHelper<IfcElectricalElement,0> { IfcElectricalElement() : Object("IfcElectricalElement") {}
};
// C++ wrapper for IfcChillerType
struct IfcChillerType : IfcEnergyConversionDeviceType, ObjectHelper<IfcChillerType,1> { IfcChillerType() : Object("IfcChillerType") {}
IfcChillerTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcReinforcingBar
struct IfcReinforcingBar : IfcReinforcingElement, ObjectHelper<IfcReinforcingBar,5> { IfcReinforcingBar() : Object("IfcReinforcingBar") {}
IfcPositiveLengthMeasure::Out NominalDiameter;
IfcAreaMeasure::Out CrossSectionArea;
Maybe< IfcPositiveLengthMeasure::Out > BarLength;
IfcReinforcingBarRoleEnum::Out BarRole;
Maybe< IfcReinforcingBarSurfaceEnum::Out > BarSurface;
};
// C++ wrapper for IfcCShapeProfileDef
struct IfcCShapeProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcCShapeProfileDef,6> { IfcCShapeProfileDef() : Object("IfcCShapeProfileDef") {}
IfcPositiveLengthMeasure::Out Depth;
IfcPositiveLengthMeasure::Out Width;
IfcPositiveLengthMeasure::Out WallThickness;
IfcPositiveLengthMeasure::Out Girth;
Maybe< IfcPositiveLengthMeasure::Out > InternalFilletRadius;
Maybe< IfcPositiveLengthMeasure::Out > CentreOfGravityInX;
};
// C++ wrapper for IfcPermit
struct IfcPermit : IfcControl, ObjectHelper<IfcPermit,1> { IfcPermit() : Object("IfcPermit") {}
IfcIdentifier::Out PermitID;
};
// C++ wrapper for IfcSlabType
struct IfcSlabType : IfcBuildingElementType, ObjectHelper<IfcSlabType,1> { IfcSlabType() : Object("IfcSlabType") {}
IfcSlabTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcLampType
struct IfcLampType : IfcFlowTerminalType, ObjectHelper<IfcLampType,1> { IfcLampType() : Object("IfcLampType") {}
IfcLampTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcPlanarExtent
struct IfcPlanarExtent : IfcGeometricRepresentationItem, ObjectHelper<IfcPlanarExtent,2> { IfcPlanarExtent() : Object("IfcPlanarExtent") {}
IfcLengthMeasure::Out SizeInX;
IfcLengthMeasure::Out SizeInY;
};
// C++ wrapper for IfcAlarmType
struct IfcAlarmType : IfcDistributionControlElementType, ObjectHelper<IfcAlarmType,1> { IfcAlarmType() : Object("IfcAlarmType") {}
IfcAlarmTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcElectricFlowStorageDeviceType
struct IfcElectricFlowStorageDeviceType : IfcFlowStorageDeviceType, ObjectHelper<IfcElectricFlowStorageDeviceType,1> { IfcElectricFlowStorageDeviceType() : Object("IfcElectricFlowStorageDeviceType") {}
IfcElectricFlowStorageDeviceTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcEquipmentElement
struct IfcEquipmentElement : IfcElement, ObjectHelper<IfcEquipmentElement,0> { IfcEquipmentElement() : Object("IfcEquipmentElement") {}
};
// C++ wrapper for IfcLightFixtureType
struct IfcLightFixtureType : IfcFlowTerminalType, ObjectHelper<IfcLightFixtureType,1> { IfcLightFixtureType() : Object("IfcLightFixtureType") {}
IfcLightFixtureTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcCurtainWall
struct IfcCurtainWall : IfcBuildingElement, ObjectHelper<IfcCurtainWall,0> { IfcCurtainWall() : Object("IfcCurtainWall") {}
};
// C++ wrapper for IfcSlab
struct IfcSlab : IfcBuildingElement, ObjectHelper<IfcSlab,1> { IfcSlab() : Object("IfcSlab") {}
Maybe< IfcSlabTypeEnum::Out > PredefinedType;
};
// C++ wrapper for IfcCurtainWallType
struct IfcCurtainWallType : IfcBuildingElementType, ObjectHelper<IfcCurtainWallType,1> { IfcCurtainWallType() : Object("IfcCurtainWallType") {}
IfcCurtainWallTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcOutletType
struct IfcOutletType : IfcFlowTerminalType, ObjectHelper<IfcOutletType,1> { IfcOutletType() : Object("IfcOutletType") {}
IfcOutletTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcCompressorType
struct IfcCompressorType : IfcFlowMovingDeviceType, ObjectHelper<IfcCompressorType,1> { IfcCompressorType() : Object("IfcCompressorType") {}
IfcCompressorTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcCraneRailAShapeProfileDef
struct IfcCraneRailAShapeProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcCraneRailAShapeProfileDef,12> { IfcCraneRailAShapeProfileDef() : Object("IfcCraneRailAShapeProfileDef") {}
IfcPositiveLengthMeasure::Out OverallHeight;
IfcPositiveLengthMeasure::Out BaseWidth2;
Maybe< IfcPositiveLengthMeasure::Out > Radius;
IfcPositiveLengthMeasure::Out HeadWidth;
IfcPositiveLengthMeasure::Out HeadDepth2;
IfcPositiveLengthMeasure::Out HeadDepth3;
IfcPositiveLengthMeasure::Out WebThickness;
IfcPositiveLengthMeasure::Out BaseWidth4;
IfcPositiveLengthMeasure::Out BaseDepth1;
IfcPositiveLengthMeasure::Out BaseDepth2;
IfcPositiveLengthMeasure::Out BaseDepth3;
Maybe< IfcPositiveLengthMeasure::Out > CentreOfGravityInY;
};
// C++ wrapper for IfcFlowSegment
struct IfcFlowSegment : IfcDistributionFlowElement, ObjectHelper<IfcFlowSegment,0> { IfcFlowSegment() : Object("IfcFlowSegment") {}
};
// C++ wrapper for IfcSectionedSpine
struct IfcSectionedSpine : IfcGeometricRepresentationItem, ObjectHelper<IfcSectionedSpine,3> { IfcSectionedSpine() : Object("IfcSectionedSpine") {}
Lazy< IfcCompositeCurve > SpineCurve;
ListOf< Lazy< IfcProfileDef >, 2, 0 > CrossSections;
ListOf< Lazy< IfcAxis2Placement3D >, 2, 0 > CrossSectionPositions;
};
// C++ wrapper for IfcElectricTimeControlType
struct IfcElectricTimeControlType : IfcFlowControllerType, ObjectHelper<IfcElectricTimeControlType,1> { IfcElectricTimeControlType() : Object("IfcElectricTimeControlType") {}
IfcElectricTimeControlTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcFaceSurface
struct IfcFaceSurface : IfcFace, ObjectHelper<IfcFaceSurface,2> { IfcFaceSurface() : Object("IfcFaceSurface") {}
Lazy< IfcSurface > FaceSurface;
BOOLEAN::Out SameSense;
};
// C++ wrapper for IfcMotorConnectionType
struct IfcMotorConnectionType : IfcEnergyConversionDeviceType, ObjectHelper<IfcMotorConnectionType,1> { IfcMotorConnectionType() : Object("IfcMotorConnectionType") {}
IfcMotorConnectionTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcFlowFitting
struct IfcFlowFitting : IfcDistributionFlowElement, ObjectHelper<IfcFlowFitting,0> { IfcFlowFitting() : Object("IfcFlowFitting") {}
};
// C++ wrapper for IfcPointOnCurve
struct IfcPointOnCurve : IfcPoint, ObjectHelper<IfcPointOnCurve,2> { IfcPointOnCurve() : Object("IfcPointOnCurve") {}
Lazy< IfcCurve > BasisCurve;
IfcParameterValue::Out PointParameter;
};
// C++ wrapper for IfcTransportElementType
struct IfcTransportElementType : IfcElementType, ObjectHelper<IfcTransportElementType,1> { IfcTransportElementType() : Object("IfcTransportElementType") {}
IfcTransportElementTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcCableSegmentType
struct IfcCableSegmentType : IfcFlowSegmentType, ObjectHelper<IfcCableSegmentType,1> { IfcCableSegmentType() : Object("IfcCableSegmentType") {}
IfcCableSegmentTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcAnnotationSurface
struct IfcAnnotationSurface : IfcGeometricRepresentationItem, ObjectHelper<IfcAnnotationSurface,2> { IfcAnnotationSurface() : Object("IfcAnnotationSurface") {}
Lazy< IfcGeometricRepresentationItem > Item;
Maybe< Lazy< NotImplemented > > TextureCoordinates;
};
// C++ wrapper for IfcCompositeCurveSegment
struct IfcCompositeCurveSegment : IfcGeometricRepresentationItem, ObjectHelper<IfcCompositeCurveSegment,3> { IfcCompositeCurveSegment() : Object("IfcCompositeCurveSegment") {}
IfcTransitionCode::Out Transition;
BOOLEAN::Out SameSense;
Lazy< IfcCurve > ParentCurve;
};
// C++ wrapper for IfcServiceLife
struct IfcServiceLife : IfcControl, ObjectHelper<IfcServiceLife,2> { IfcServiceLife() : Object("IfcServiceLife") {}
IfcServiceLifeTypeEnum::Out ServiceLifeType;
IfcTimeMeasure::Out ServiceLifeDuration;
};
// C++ wrapper for IfcPlateType
struct IfcPlateType : IfcBuildingElementType, ObjectHelper<IfcPlateType,1> { IfcPlateType() : Object("IfcPlateType") {}
IfcPlateTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcVibrationIsolatorType
struct IfcVibrationIsolatorType : IfcDiscreteAccessoryType, ObjectHelper<IfcVibrationIsolatorType,1> { IfcVibrationIsolatorType() : Object("IfcVibrationIsolatorType") {}
IfcVibrationIsolatorTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcTrimmedCurve
struct IfcTrimmedCurve : IfcBoundedCurve, ObjectHelper<IfcTrimmedCurve,5> { IfcTrimmedCurve() : Object("IfcTrimmedCurve") {}
Lazy< IfcCurve > BasisCurve;
ListOf< IfcTrimmingSelect, 1, 2 >::Out Trim1;
ListOf< IfcTrimmingSelect, 1, 2 >::Out Trim2;
BOOLEAN::Out SenseAgreement;
IfcTrimmingPreference::Out MasterRepresentation;
};
// C++ wrapper for IfcMappedItem
struct IfcMappedItem : IfcRepresentationItem, ObjectHelper<IfcMappedItem,2> { IfcMappedItem() : Object("IfcMappedItem") {}
Lazy< IfcRepresentationMap > MappingSource;
Lazy< IfcCartesianTransformationOperator > MappingTarget;
};
// C++ wrapper for IfcDirection
struct IfcDirection : IfcGeometricRepresentationItem, ObjectHelper<IfcDirection,1> { IfcDirection() : Object("IfcDirection") {}
ListOf< REAL, 2, 3 >::Out DirectionRatios;
};
// C++ wrapper for IfcBlock
struct IfcBlock : IfcCsgPrimitive3D, ObjectHelper<IfcBlock,3> { IfcBlock() : Object("IfcBlock") {}
IfcPositiveLengthMeasure::Out XLength;
IfcPositiveLengthMeasure::Out YLength;
IfcPositiveLengthMeasure::Out ZLength;
};
// C++ wrapper for IfcProjectOrderRecord
struct IfcProjectOrderRecord : IfcControl, ObjectHelper<IfcProjectOrderRecord,2> { IfcProjectOrderRecord() : Object("IfcProjectOrderRecord") {}
ListOf< Lazy< NotImplemented >, 1, 0 > Records;
IfcProjectOrderRecordTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcFlowMeterType
struct IfcFlowMeterType : IfcFlowControllerType, ObjectHelper<IfcFlowMeterType,1> { IfcFlowMeterType() : Object("IfcFlowMeterType") {}
IfcFlowMeterTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcControllerType
struct IfcControllerType : IfcDistributionControlElementType, ObjectHelper<IfcControllerType,1> { IfcControllerType() : Object("IfcControllerType") {}
IfcControllerTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcBeam
struct IfcBeam : IfcBuildingElement, ObjectHelper<IfcBeam,0> { IfcBeam() : Object("IfcBeam") {}
};
// C++ wrapper for IfcArbitraryOpenProfileDef
struct IfcArbitraryOpenProfileDef : IfcProfileDef, ObjectHelper<IfcArbitraryOpenProfileDef,1> { IfcArbitraryOpenProfileDef() : Object("IfcArbitraryOpenProfileDef") {}
Lazy< IfcBoundedCurve > Curve;
};
// C++ wrapper for IfcCenterLineProfileDef
struct IfcCenterLineProfileDef : IfcArbitraryOpenProfileDef, ObjectHelper<IfcCenterLineProfileDef,1> { IfcCenterLineProfileDef() : Object("IfcCenterLineProfileDef") {}
IfcPositiveLengthMeasure::Out Thickness;
};
// C++ wrapper for IfcTimeSeriesSchedule
struct IfcTimeSeriesSchedule : IfcControl, ObjectHelper<IfcTimeSeriesSchedule,3> { IfcTimeSeriesSchedule() : Object("IfcTimeSeriesSchedule") {}
Maybe< ListOf< IfcDateTimeSelect, 1, 0 >::Out > ApplicableDates;
IfcTimeSeriesScheduleTypeEnum::Out TimeSeriesScheduleType;
Lazy< NotImplemented > TimeSeries;
};
// C++ wrapper for IfcRoundedEdgeFeature
struct IfcRoundedEdgeFeature : IfcEdgeFeature, ObjectHelper<IfcRoundedEdgeFeature,1> { IfcRoundedEdgeFeature() : Object("IfcRoundedEdgeFeature") {}
Maybe< IfcPositiveLengthMeasure::Out > Radius;
};
// C++ wrapper for IfcIShapeProfileDef
struct IfcIShapeProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcIShapeProfileDef,5> { IfcIShapeProfileDef() : Object("IfcIShapeProfileDef") {}
IfcPositiveLengthMeasure::Out OverallWidth;
IfcPositiveLengthMeasure::Out OverallDepth;
IfcPositiveLengthMeasure::Out WebThickness;
IfcPositiveLengthMeasure::Out FlangeThickness;
Maybe< IfcPositiveLengthMeasure::Out > FilletRadius;
};
// C++ wrapper for IfcSpaceHeaterType
struct IfcSpaceHeaterType : IfcEnergyConversionDeviceType, ObjectHelper<IfcSpaceHeaterType,1> { IfcSpaceHeaterType() : Object("IfcSpaceHeaterType") {}
IfcSpaceHeaterTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcFlowStorageDevice
struct IfcFlowStorageDevice : IfcDistributionFlowElement, ObjectHelper<IfcFlowStorageDevice,0> { IfcFlowStorageDevice() : Object("IfcFlowStorageDevice") {}
};
// C++ wrapper for IfcRevolvedAreaSolid
struct IfcRevolvedAreaSolid : IfcSweptAreaSolid, ObjectHelper<IfcRevolvedAreaSolid,2> { IfcRevolvedAreaSolid() : Object("IfcRevolvedAreaSolid") {}
Lazy< IfcAxis1Placement > Axis;
IfcPlaneAngleMeasure::Out Angle;
};
// C++ wrapper for IfcDoor
struct IfcDoor : IfcBuildingElement, ObjectHelper<IfcDoor,2> { IfcDoor() : Object("IfcDoor") {}
Maybe< IfcPositiveLengthMeasure::Out > OverallHeight;
Maybe< IfcPositiveLengthMeasure::Out > OverallWidth;
};
// C++ wrapper for IfcEllipse
struct IfcEllipse : IfcConic, ObjectHelper<IfcEllipse,2> { IfcEllipse() : Object("IfcEllipse") {}
IfcPositiveLengthMeasure::Out SemiAxis1;
IfcPositiveLengthMeasure::Out SemiAxis2;
};
// C++ wrapper for IfcTubeBundleType
struct IfcTubeBundleType : IfcEnergyConversionDeviceType, ObjectHelper<IfcTubeBundleType,1> { IfcTubeBundleType() : Object("IfcTubeBundleType") {}
IfcTubeBundleTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcAngularDimension
struct IfcAngularDimension : IfcDimensionCurveDirectedCallout, ObjectHelper<IfcAngularDimension,0> { IfcAngularDimension() : Object("IfcAngularDimension") {}
};
// C++ wrapper for IfcFaceBasedSurfaceModel
struct IfcFaceBasedSurfaceModel : IfcGeometricRepresentationItem, ObjectHelper<IfcFaceBasedSurfaceModel,1> { IfcFaceBasedSurfaceModel() : Object("IfcFaceBasedSurfaceModel") {}
ListOf< Lazy< IfcConnectedFaceSet >, 1, 0 > FbsmFaces;
};
// C++ wrapper for IfcCraneRailFShapeProfileDef
struct IfcCraneRailFShapeProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcCraneRailFShapeProfileDef,9> { IfcCraneRailFShapeProfileDef() : Object("IfcCraneRailFShapeProfileDef") {}
IfcPositiveLengthMeasure::Out OverallHeight;
IfcPositiveLengthMeasure::Out HeadWidth;
Maybe< IfcPositiveLengthMeasure::Out > Radius;
IfcPositiveLengthMeasure::Out HeadDepth2;
IfcPositiveLengthMeasure::Out HeadDepth3;
IfcPositiveLengthMeasure::Out WebThickness;
IfcPositiveLengthMeasure::Out BaseDepth1;
IfcPositiveLengthMeasure::Out BaseDepth2;
Maybe< IfcPositiveLengthMeasure::Out > CentreOfGravityInY;
};
// C++ wrapper for IfcColumnType
struct IfcColumnType : IfcBuildingElementType, ObjectHelper<IfcColumnType,1> { IfcColumnType() : Object("IfcColumnType") {}
IfcColumnTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcTShapeProfileDef
struct IfcTShapeProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcTShapeProfileDef,10> { IfcTShapeProfileDef() : Object("IfcTShapeProfileDef") {}
IfcPositiveLengthMeasure::Out Depth;
IfcPositiveLengthMeasure::Out FlangeWidth;
IfcPositiveLengthMeasure::Out WebThickness;
IfcPositiveLengthMeasure::Out FlangeThickness;
Maybe< IfcPositiveLengthMeasure::Out > FilletRadius;
Maybe< IfcPositiveLengthMeasure::Out > FlangeEdgeRadius;
Maybe< IfcPositiveLengthMeasure::Out > WebEdgeRadius;
Maybe< IfcPlaneAngleMeasure::Out > WebSlope;
Maybe< IfcPlaneAngleMeasure::Out > FlangeSlope;
Maybe< IfcPositiveLengthMeasure::Out > CentreOfGravityInY;
};
// C++ wrapper for IfcEnergyConversionDevice
struct IfcEnergyConversionDevice : IfcDistributionFlowElement, ObjectHelper<IfcEnergyConversionDevice,0> { IfcEnergyConversionDevice() : Object("IfcEnergyConversionDevice") {}
};
// C++ wrapper for IfcWorkSchedule
struct IfcWorkSchedule : IfcWorkControl, ObjectHelper<IfcWorkSchedule,0> { IfcWorkSchedule() : Object("IfcWorkSchedule") {}
};
// C++ wrapper for IfcZone
struct IfcZone : IfcGroup, ObjectHelper<IfcZone,0> { IfcZone() : Object("IfcZone") {}
};
// C++ wrapper for IfcTransportElement
struct IfcTransportElement : IfcElement, ObjectHelper<IfcTransportElement,3> { IfcTransportElement() : Object("IfcTransportElement") {}
Maybe< IfcTransportElementTypeEnum::Out > OperationType;
Maybe< IfcMassMeasure::Out > CapacityByWeight;
Maybe< IfcCountMeasure::Out > CapacityByNumber;
};
// C++ wrapper for IfcGeometricRepresentationSubContext
struct IfcGeometricRepresentationSubContext : IfcGeometricRepresentationContext, ObjectHelper<IfcGeometricRepresentationSubContext,4> { IfcGeometricRepresentationSubContext() : Object("IfcGeometricRepresentationSubContext") {}
Lazy< IfcGeometricRepresentationContext > ParentContext;
Maybe< IfcPositiveRatioMeasure::Out > TargetScale;
IfcGeometricProjectionEnum::Out TargetView;
Maybe< IfcLabel::Out > UserDefinedTargetView;
};
// C++ wrapper for IfcLShapeProfileDef
struct IfcLShapeProfileDef : IfcParameterizedProfileDef, ObjectHelper<IfcLShapeProfileDef,8> { IfcLShapeProfileDef() : Object("IfcLShapeProfileDef") {}
IfcPositiveLengthMeasure::Out Depth;
Maybe< IfcPositiveLengthMeasure::Out > Width;
IfcPositiveLengthMeasure::Out Thickness;
Maybe< IfcPositiveLengthMeasure::Out > FilletRadius;
Maybe< IfcPositiveLengthMeasure::Out > EdgeRadius;
Maybe< IfcPlaneAngleMeasure::Out > LegSlope;
Maybe< IfcPositiveLengthMeasure::Out > CentreOfGravityInX;
Maybe< IfcPositiveLengthMeasure::Out > CentreOfGravityInY;
};
// C++ wrapper for IfcGeometricCurveSet
struct IfcGeometricCurveSet : IfcGeometricSet, ObjectHelper<IfcGeometricCurveSet,0> { IfcGeometricCurveSet() : Object("IfcGeometricCurveSet") {}
};
// C++ wrapper for IfcActor
struct IfcActor : IfcObject, ObjectHelper<IfcActor,1> { IfcActor() : Object("IfcActor") {}
IfcActorSelect::Out TheActor;
};
// C++ wrapper for IfcOccupant
struct IfcOccupant : IfcActor, ObjectHelper<IfcOccupant,1> { IfcOccupant() : Object("IfcOccupant") {}
IfcOccupantTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcBooleanClippingResult
struct IfcBooleanClippingResult : IfcBooleanResult, ObjectHelper<IfcBooleanClippingResult,0> { IfcBooleanClippingResult() : Object("IfcBooleanClippingResult") {}
};
// C++ wrapper for IfcAnnotationFillArea
struct IfcAnnotationFillArea : IfcGeometricRepresentationItem, ObjectHelper<IfcAnnotationFillArea,2> { IfcAnnotationFillArea() : Object("IfcAnnotationFillArea") {}
Lazy< IfcCurve > OuterBoundary;
Maybe< ListOf< Lazy< IfcCurve >, 1, 0 > > InnerBoundaries;
};
// C++ wrapper for IfcLightSourceSpot
struct IfcLightSourceSpot : IfcLightSourcePositional, ObjectHelper<IfcLightSourceSpot,4> { IfcLightSourceSpot() : Object("IfcLightSourceSpot") {}
Lazy< IfcDirection > Orientation;
Maybe< IfcReal::Out > ConcentrationExponent;
IfcPositivePlaneAngleMeasure::Out SpreadAngle;
IfcPositivePlaneAngleMeasure::Out BeamWidthAngle;
};
// C++ wrapper for IfcFireSuppressionTerminalType
struct IfcFireSuppressionTerminalType : IfcFlowTerminalType, ObjectHelper<IfcFireSuppressionTerminalType,1> { IfcFireSuppressionTerminalType() : Object("IfcFireSuppressionTerminalType") {}
IfcFireSuppressionTerminalTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcElectricGeneratorType
struct IfcElectricGeneratorType : IfcEnergyConversionDeviceType, ObjectHelper<IfcElectricGeneratorType,1> { IfcElectricGeneratorType() : Object("IfcElectricGeneratorType") {}
IfcElectricGeneratorTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcInventory
struct IfcInventory : IfcGroup, ObjectHelper<IfcInventory,6> { IfcInventory() : Object("IfcInventory") {}
IfcInventoryTypeEnum::Out InventoryType;
IfcActorSelect::Out Jurisdiction;
ListOf< Lazy< NotImplemented >, 1, 0 > ResponsiblePersons;
Lazy< NotImplemented > LastUpdateDate;
Maybe< Lazy< NotImplemented > > CurrentValue;
Maybe< Lazy< NotImplemented > > OriginalValue;
};
// C++ wrapper for IfcPolyline
struct IfcPolyline : IfcBoundedCurve, ObjectHelper<IfcPolyline,1> { IfcPolyline() : Object("IfcPolyline") {}
ListOf< Lazy< IfcCartesianPoint >, 2, 0 > Points;
};
// C++ wrapper for IfcBoxedHalfSpace
struct IfcBoxedHalfSpace : IfcHalfSpaceSolid, ObjectHelper<IfcBoxedHalfSpace,1> { IfcBoxedHalfSpace() : Object("IfcBoxedHalfSpace") {}
Lazy< IfcBoundingBox > Enclosure;
};
// C++ wrapper for IfcAirTerminalType
struct IfcAirTerminalType : IfcFlowTerminalType, ObjectHelper<IfcAirTerminalType,1> { IfcAirTerminalType() : Object("IfcAirTerminalType") {}
IfcAirTerminalTypeEnum::Out PredefinedType;
};
// C++ wrapper for IfcDistributionPort
struct IfcDistributionPort : IfcPort, ObjectHelper<IfcDistributionPort,1> { IfcDistributionPort() : Object("IfcDistributionPort") {}
Maybe< IfcFlowDirectionEnum::Out > FlowDirection;
};
// C++ wrapper for IfcCostItem
struct IfcCostItem : IfcControl, ObjectHelper<IfcCostItem,0> { IfcCostItem() : Object("IfcCostItem") {}
};
// C++ wrapper for IfcStructuredDimensionCallout
struct IfcStructuredDimensionCallout : IfcDraughtingCallout, ObjectHelper<IfcStructuredDimensionCallout,0> { IfcStructuredDimensionCallout() : Object("IfcStructuredDimensionCallout") {}
};
// C++ wrapper for IfcStructuralResultGroup
struct IfcStructuralResultGroup : IfcGroup, ObjectHelper<IfcStructuralResultGroup,3> { IfcStructuralResultGroup() : Object("IfcStructuralResultGroup") {}
IfcAnalysisTheoryTypeEnum::Out TheoryType;
Maybe< Lazy< IfcStructuralLoadGroup > > ResultForLoadGroup;
BOOLEAN::Out IsLinear;
};
// C++ wrapper for IfcOrientedEdge
struct IfcOrientedEdge : IfcEdge, ObjectHelper<IfcOrientedEdge,2> { IfcOrientedEdge() : Object("IfcOrientedEdge") {}
Lazy< IfcEdge > EdgeElement;
BOOLEAN::Out Orientation;
};
// C++ wrapper for IfcCsgSolid
struct IfcCsgSolid : IfcSolidModel, ObjectHelper<IfcCsgSolid,1> { IfcCsgSolid() : Object("IfcCsgSolid") {}
IfcCsgSelect::Out TreeRootExpression;
};
// C++ wrapper for IfcPlanarBox
struct IfcPlanarBox : IfcPlanarExtent, ObjectHelper<IfcPlanarBox,1> { IfcPlanarBox() : Object("IfcPlanarBox") {}
IfcAxis2Placement::Out Placement;
};
// C++ wrapper for IfcMaterialDefinitionRepresentation
struct IfcMaterialDefinitionRepresentation : IfcProductRepresentation, ObjectHelper<IfcMaterialDefinitionRepresentation,1> { IfcMaterialDefinitionRepresentation() : Object("IfcMaterialDefinitionRepresentation") {}
Lazy< NotImplemented > RepresentedMaterial;
};
// C++ wrapper for IfcAsymmetricIShapeProfileDef
struct IfcAsymmetricIShapeProfileDef : IfcIShapeProfileDef, ObjectHelper<IfcAsymmetricIShapeProfileDef,4> { IfcAsymmetricIShapeProfileDef() : Object("IfcAsymmetricIShapeProfileDef") {}
IfcPositiveLengthMeasure::Out TopFlangeWidth;
Maybe< IfcPositiveLengthMeasure::Out > TopFlangeThickness;
Maybe< IfcPositiveLengthMeasure::Out > TopFlangeFilletRadius;
Maybe< IfcPositiveLengthMeasure::Out > CentreOfGravityInY;
};
// C++ wrapper for IfcRepresentationMap
struct IfcRepresentationMap : ObjectHelper<IfcRepresentationMap,2> { IfcRepresentationMap() : Object("IfcRepresentationMap") {}
IfcAxis2Placement::Out MappingOrigin;
Lazy< IfcRepresentation > MappedRepresentation;
};
void GetSchema(EXPRESS::ConversionSchema& out);
} //! IFC
namespace STEP {
// ******************************************************************************
// Converter stubs
// ******************************************************************************
#define DECL_CONV_STUB(type) template <> size_t GenericFill<IFC::type>(const STEP::DB& db, const EXPRESS::LIST& params, IFC::type* in)
DECL_CONV_STUB(IfcRoot);
DECL_CONV_STUB(IfcObjectDefinition);
DECL_CONV_STUB(IfcTypeObject);
DECL_CONV_STUB(IfcTypeProduct);
DECL_CONV_STUB(IfcElementType);
DECL_CONV_STUB(IfcFurnishingElementType);
DECL_CONV_STUB(IfcFurnitureType);
DECL_CONV_STUB(IfcObject);
DECL_CONV_STUB(IfcProduct);
DECL_CONV_STUB(IfcGrid);
DECL_CONV_STUB(IfcRepresentationItem);
DECL_CONV_STUB(IfcGeometricRepresentationItem);
DECL_CONV_STUB(IfcOneDirectionRepeatFactor);
DECL_CONV_STUB(IfcTwoDirectionRepeatFactor);
DECL_CONV_STUB(IfcElement);
DECL_CONV_STUB(IfcElementComponent);
DECL_CONV_STUB(IfcSpatialStructureElementType);
DECL_CONV_STUB(IfcControl);
DECL_CONV_STUB(IfcActionRequest);
DECL_CONV_STUB(IfcDistributionElementType);
DECL_CONV_STUB(IfcDistributionFlowElementType);
DECL_CONV_STUB(IfcEnergyConversionDeviceType);
DECL_CONV_STUB(IfcCooledBeamType);
DECL_CONV_STUB(IfcCsgPrimitive3D);
DECL_CONV_STUB(IfcRectangularPyramid);
DECL_CONV_STUB(IfcSurface);
DECL_CONV_STUB(IfcBoundedSurface);
DECL_CONV_STUB(IfcRectangularTrimmedSurface);
DECL_CONV_STUB(IfcGroup);
DECL_CONV_STUB(IfcRelationship);
DECL_CONV_STUB(IfcHalfSpaceSolid);
DECL_CONV_STUB(IfcPolygonalBoundedHalfSpace);
DECL_CONV_STUB(IfcAirToAirHeatRecoveryType);
DECL_CONV_STUB(IfcFlowFittingType);
DECL_CONV_STUB(IfcPipeFittingType);
DECL_CONV_STUB(IfcRepresentation);
DECL_CONV_STUB(IfcStyleModel);
DECL_CONV_STUB(IfcStyledRepresentation);
DECL_CONV_STUB(IfcBooleanResult);
DECL_CONV_STUB(IfcFeatureElement);
DECL_CONV_STUB(IfcFeatureElementSubtraction);
DECL_CONV_STUB(IfcOpeningElement);
DECL_CONV_STUB(IfcConditionCriterion);
DECL_CONV_STUB(IfcFlowTerminalType);
DECL_CONV_STUB(IfcFlowControllerType);
DECL_CONV_STUB(IfcSwitchingDeviceType);
DECL_CONV_STUB(IfcSystem);
DECL_CONV_STUB(IfcElectricalCircuit);
DECL_CONV_STUB(IfcUnitaryEquipmentType);
DECL_CONV_STUB(IfcPort);
DECL_CONV_STUB(IfcPlacement);
DECL_CONV_STUB(IfcProfileDef);
DECL_CONV_STUB(IfcArbitraryClosedProfileDef);
DECL_CONV_STUB(IfcCurve);
DECL_CONV_STUB(IfcConic);
DECL_CONV_STUB(IfcCircle);
DECL_CONV_STUB(IfcElementarySurface);
DECL_CONV_STUB(IfcPlane);
DECL_CONV_STUB(IfcCostSchedule);
DECL_CONV_STUB(IfcRightCircularCone);
DECL_CONV_STUB(IfcElementAssembly);
DECL_CONV_STUB(IfcBuildingElement);
DECL_CONV_STUB(IfcMember);
DECL_CONV_STUB(IfcBuildingElementProxy);
DECL_CONV_STUB(IfcStructuralActivity);
DECL_CONV_STUB(IfcStructuralAction);
DECL_CONV_STUB(IfcStructuralPlanarAction);
DECL_CONV_STUB(IfcTopologicalRepresentationItem);
DECL_CONV_STUB(IfcConnectedFaceSet);
DECL_CONV_STUB(IfcSweptSurface);
DECL_CONV_STUB(IfcSurfaceOfLinearExtrusion);
DECL_CONV_STUB(IfcArbitraryProfileDefWithVoids);
DECL_CONV_STUB(IfcProcess);
DECL_CONV_STUB(IfcProcedure);
DECL_CONV_STUB(IfcVector);
DECL_CONV_STUB(IfcFaceBound);
DECL_CONV_STUB(IfcFaceOuterBound);
DECL_CONV_STUB(IfcFeatureElementAddition);
DECL_CONV_STUB(IfcNamedUnit);
DECL_CONV_STUB(IfcConversionBasedUnit);
DECL_CONV_STUB(IfcHeatExchangerType);
DECL_CONV_STUB(IfcPresentationStyleAssignment);
DECL_CONV_STUB(IfcFlowTreatmentDeviceType);
DECL_CONV_STUB(IfcFilterType);
DECL_CONV_STUB(IfcResource);
DECL_CONV_STUB(IfcEvaporativeCoolerType);
DECL_CONV_STUB(IfcOffsetCurve2D);
DECL_CONV_STUB(IfcEdge);
DECL_CONV_STUB(IfcSubedge);
DECL_CONV_STUB(IfcProxy);
DECL_CONV_STUB(IfcLine);
DECL_CONV_STUB(IfcColumn);
DECL_CONV_STUB(IfcObjectPlacement);
DECL_CONV_STUB(IfcGridPlacement);
DECL_CONV_STUB(IfcDistributionControlElementType);
DECL_CONV_STUB(IfcRelConnects);
DECL_CONV_STUB(IfcAnnotation);
DECL_CONV_STUB(IfcPlate);
DECL_CONV_STUB(IfcSolidModel);
DECL_CONV_STUB(IfcManifoldSolidBrep);
DECL_CONV_STUB(IfcFlowStorageDeviceType);
DECL_CONV_STUB(IfcStructuralItem);
DECL_CONV_STUB(IfcStructuralMember);
DECL_CONV_STUB(IfcStructuralCurveMember);
DECL_CONV_STUB(IfcStructuralConnection);
DECL_CONV_STUB(IfcStructuralSurfaceConnection);
DECL_CONV_STUB(IfcCoilType);
DECL_CONV_STUB(IfcDuctFittingType);
DECL_CONV_STUB(IfcStyledItem);
DECL_CONV_STUB(IfcAnnotationOccurrence);
DECL_CONV_STUB(IfcAnnotationCurveOccurrence);
DECL_CONV_STUB(IfcDimensionCurve);
DECL_CONV_STUB(IfcBoundedCurve);
DECL_CONV_STUB(IfcAxis1Placement);
DECL_CONV_STUB(IfcStructuralPointAction);
DECL_CONV_STUB(IfcSpatialStructureElement);
DECL_CONV_STUB(IfcSpace);
DECL_CONV_STUB(IfcCoolingTowerType);
DECL_CONV_STUB(IfcFacetedBrepWithVoids);
DECL_CONV_STUB(IfcValveType);
DECL_CONV_STUB(IfcSystemFurnitureElementType);
DECL_CONV_STUB(IfcDiscreteAccessory);
DECL_CONV_STUB(IfcBuildingElementType);
DECL_CONV_STUB(IfcRailingType);
DECL_CONV_STUB(IfcGasTerminalType);
DECL_CONV_STUB(IfcSpaceProgram);
DECL_CONV_STUB(IfcCovering);
DECL_CONV_STUB(IfcPresentationStyle);
DECL_CONV_STUB(IfcElectricHeaterType);
DECL_CONV_STUB(IfcBuildingStorey);
DECL_CONV_STUB(IfcVertex);
DECL_CONV_STUB(IfcVertexPoint);
DECL_CONV_STUB(IfcFlowInstrumentType);
DECL_CONV_STUB(IfcParameterizedProfileDef);
DECL_CONV_STUB(IfcUShapeProfileDef);
DECL_CONV_STUB(IfcRamp);
DECL_CONV_STUB(IfcCompositeCurve);
DECL_CONV_STUB(IfcStructuralCurveMemberVarying);
DECL_CONV_STUB(IfcRampFlightType);
DECL_CONV_STUB(IfcDraughtingCallout);
DECL_CONV_STUB(IfcDimensionCurveDirectedCallout);
DECL_CONV_STUB(IfcRadiusDimension);
DECL_CONV_STUB(IfcEdgeFeature);
DECL_CONV_STUB(IfcSweptAreaSolid);
DECL_CONV_STUB(IfcExtrudedAreaSolid);
DECL_CONV_STUB(IfcAnnotationTextOccurrence);
DECL_CONV_STUB(IfcStair);
DECL_CONV_STUB(IfcFillAreaStyleTileSymbolWithStyle);
DECL_CONV_STUB(IfcAnnotationSymbolOccurrence);
DECL_CONV_STUB(IfcTerminatorSymbol);
DECL_CONV_STUB(IfcDimensionCurveTerminator);
DECL_CONV_STUB(IfcRectangleProfileDef);
DECL_CONV_STUB(IfcRectangleHollowProfileDef);
DECL_CONV_STUB(IfcLocalPlacement);
DECL_CONV_STUB(IfcTask);
DECL_CONV_STUB(IfcAnnotationFillAreaOccurrence);
DECL_CONV_STUB(IfcFace);
DECL_CONV_STUB(IfcFlowSegmentType);
DECL_CONV_STUB(IfcDuctSegmentType);
DECL_CONV_STUB(IfcConstructionResource);
DECL_CONV_STUB(IfcConstructionEquipmentResource);
DECL_CONV_STUB(IfcSanitaryTerminalType);
DECL_CONV_STUB(IfcCircleProfileDef);
DECL_CONV_STUB(IfcStructuralReaction);
DECL_CONV_STUB(IfcStructuralPointReaction);
DECL_CONV_STUB(IfcRailing);
DECL_CONV_STUB(IfcTextLiteral);
DECL_CONV_STUB(IfcCartesianTransformationOperator);
DECL_CONV_STUB(IfcLinearDimension);
DECL_CONV_STUB(IfcDamperType);
DECL_CONV_STUB(IfcSIUnit);
DECL_CONV_STUB(IfcMeasureWithUnit);
DECL_CONV_STUB(IfcDistributionElement);
DECL_CONV_STUB(IfcDistributionControlElement);
DECL_CONV_STUB(IfcTransformerType);
DECL_CONV_STUB(IfcLaborResource);
DECL_CONV_STUB(IfcFurnitureStandard);
DECL_CONV_STUB(IfcStairFlightType);
DECL_CONV_STUB(IfcWorkControl);
DECL_CONV_STUB(IfcWorkPlan);
DECL_CONV_STUB(IfcCondition);
DECL_CONV_STUB(IfcRelVoidsElement);
DECL_CONV_STUB(IfcWindow);
DECL_CONV_STUB(IfcProtectiveDeviceType);
DECL_CONV_STUB(IfcJunctionBoxType);
DECL_CONV_STUB(IfcStructuralAnalysisModel);
DECL_CONV_STUB(IfcAxis2Placement2D);
DECL_CONV_STUB(IfcSpaceType);
DECL_CONV_STUB(IfcEllipseProfileDef);
DECL_CONV_STUB(IfcDistributionFlowElement);
DECL_CONV_STUB(IfcFlowMovingDevice);
DECL_CONV_STUB(IfcSurfaceStyleWithTextures);
DECL_CONV_STUB(IfcGeometricSet);
DECL_CONV_STUB(IfcProjectOrder);
DECL_CONV_STUB(IfcBSplineCurve);
DECL_CONV_STUB(IfcBezierCurve);
DECL_CONV_STUB(IfcStructuralPointConnection);
DECL_CONV_STUB(IfcFlowController);
DECL_CONV_STUB(IfcElectricDistributionPoint);
DECL_CONV_STUB(IfcSite);
DECL_CONV_STUB(IfcOffsetCurve3D);
DECL_CONV_STUB(IfcVirtualElement);
DECL_CONV_STUB(IfcConstructionProductResource);
DECL_CONV_STUB(IfcSurfaceCurveSweptAreaSolid);
DECL_CONV_STUB(IfcCartesianTransformationOperator3D);
DECL_CONV_STUB(IfcCartesianTransformationOperator3DnonUniform);
DECL_CONV_STUB(IfcCrewResource);
DECL_CONV_STUB(IfcStructuralSurfaceMember);
DECL_CONV_STUB(Ifc2DCompositeCurve);
DECL_CONV_STUB(IfcRepresentationContext);
DECL_CONV_STUB(IfcGeometricRepresentationContext);
DECL_CONV_STUB(IfcFlowTreatmentDevice);
DECL_CONV_STUB(IfcRightCircularCylinder);
DECL_CONV_STUB(IfcWasteTerminalType);
DECL_CONV_STUB(IfcBuildingElementComponent);
DECL_CONV_STUB(IfcBuildingElementPart);
DECL_CONV_STUB(IfcWall);
DECL_CONV_STUB(IfcWallStandardCase);
DECL_CONV_STUB(IfcPath);
DECL_CONV_STUB(IfcDefinedSymbol);
DECL_CONV_STUB(IfcStructuralSurfaceMemberVarying);
DECL_CONV_STUB(IfcPoint);
DECL_CONV_STUB(IfcSurfaceOfRevolution);
DECL_CONV_STUB(IfcFlowTerminal);
DECL_CONV_STUB(IfcFurnishingElement);
DECL_CONV_STUB(IfcSurfaceStyleShading);
DECL_CONV_STUB(IfcSurfaceStyleRendering);
DECL_CONV_STUB(IfcCircleHollowProfileDef);
DECL_CONV_STUB(IfcFlowMovingDeviceType);
DECL_CONV_STUB(IfcFanType);
DECL_CONV_STUB(IfcStructuralPlanarActionVarying);
DECL_CONV_STUB(IfcProductRepresentation);
DECL_CONV_STUB(IfcStackTerminalType);
DECL_CONV_STUB(IfcReinforcingElement);
DECL_CONV_STUB(IfcReinforcingMesh);
DECL_CONV_STUB(IfcOrderAction);
DECL_CONV_STUB(IfcLightSource);
DECL_CONV_STUB(IfcLightSourceDirectional);
DECL_CONV_STUB(IfcLoop);
DECL_CONV_STUB(IfcVertexLoop);
DECL_CONV_STUB(IfcChamferEdgeFeature);
DECL_CONV_STUB(IfcElementComponentType);
DECL_CONV_STUB(IfcFastenerType);
DECL_CONV_STUB(IfcMechanicalFastenerType);
DECL_CONV_STUB(IfcScheduleTimeControl);
DECL_CONV_STUB(IfcSurfaceStyle);
DECL_CONV_STUB(IfcOpenShell);
DECL_CONV_STUB(IfcSubContractResource);
DECL_CONV_STUB(IfcSweptDiskSolid);
DECL_CONV_STUB(IfcTankType);
DECL_CONV_STUB(IfcSphere);
DECL_CONV_STUB(IfcPolyLoop);
DECL_CONV_STUB(IfcCableCarrierFittingType);
DECL_CONV_STUB(IfcHumidifierType);
DECL_CONV_STUB(IfcPerformanceHistory);
DECL_CONV_STUB(IfcShapeModel);
DECL_CONV_STUB(IfcTopologyRepresentation);
DECL_CONV_STUB(IfcBuilding);
DECL_CONV_STUB(IfcRoundedRectangleProfileDef);
DECL_CONV_STUB(IfcStairFlight);
DECL_CONV_STUB(IfcDistributionChamberElement);
DECL_CONV_STUB(IfcShapeRepresentation);
DECL_CONV_STUB(IfcRampFlight);
DECL_CONV_STUB(IfcBeamType);
DECL_CONV_STUB(IfcRelDecomposes);
DECL_CONV_STUB(IfcRoof);
DECL_CONV_STUB(IfcFooting);
DECL_CONV_STUB(IfcLightSourceAmbient);
DECL_CONV_STUB(IfcWindowStyle);
DECL_CONV_STUB(IfcBuildingElementProxyType);
DECL_CONV_STUB(IfcAxis2Placement3D);
DECL_CONV_STUB(IfcEdgeCurve);
DECL_CONV_STUB(IfcClosedShell);
DECL_CONV_STUB(IfcTendonAnchor);
DECL_CONV_STUB(IfcCondenserType);
DECL_CONV_STUB(IfcPipeSegmentType);
DECL_CONV_STUB(IfcPointOnSurface);
DECL_CONV_STUB(IfcAsset);
DECL_CONV_STUB(IfcLightSourcePositional);
DECL_CONV_STUB(IfcProjectionCurve);
DECL_CONV_STUB(IfcFillAreaStyleTiles);
DECL_CONV_STUB(IfcElectricMotorType);
DECL_CONV_STUB(IfcTendon);
DECL_CONV_STUB(IfcDistributionChamberElementType);
DECL_CONV_STUB(IfcMemberType);
DECL_CONV_STUB(IfcStructuralLinearAction);
DECL_CONV_STUB(IfcStructuralLinearActionVarying);
DECL_CONV_STUB(IfcProductDefinitionShape);
DECL_CONV_STUB(IfcFastener);
DECL_CONV_STUB(IfcMechanicalFastener);
DECL_CONV_STUB(IfcEvaporatorType);
DECL_CONV_STUB(IfcDiscreteAccessoryType);
DECL_CONV_STUB(IfcStructuralCurveConnection);
DECL_CONV_STUB(IfcProjectionElement);
DECL_CONV_STUB(IfcCoveringType);
DECL_CONV_STUB(IfcPumpType);
DECL_CONV_STUB(IfcPile);
DECL_CONV_STUB(IfcUnitAssignment);
DECL_CONV_STUB(IfcBoundingBox);
DECL_CONV_STUB(IfcShellBasedSurfaceModel);
DECL_CONV_STUB(IfcFacetedBrep);
DECL_CONV_STUB(IfcTextLiteralWithExtent);
DECL_CONV_STUB(IfcElectricApplianceType);
DECL_CONV_STUB(IfcTrapeziumProfileDef);
DECL_CONV_STUB(IfcRelContainedInSpatialStructure);
DECL_CONV_STUB(IfcEdgeLoop);
DECL_CONV_STUB(IfcProject);
DECL_CONV_STUB(IfcCartesianPoint);
DECL_CONV_STUB(IfcCurveBoundedPlane);
DECL_CONV_STUB(IfcWallType);
DECL_CONV_STUB(IfcFillAreaStyleHatching);
DECL_CONV_STUB(IfcEquipmentStandard);
DECL_CONV_STUB(IfcDiameterDimension);
DECL_CONV_STUB(IfcStructuralLoadGroup);
DECL_CONV_STUB(IfcConstructionMaterialResource);
DECL_CONV_STUB(IfcRelAggregates);
DECL_CONV_STUB(IfcBoilerType);
DECL_CONV_STUB(IfcColourSpecification);
DECL_CONV_STUB(IfcColourRgb);
DECL_CONV_STUB(IfcDoorStyle);
DECL_CONV_STUB(IfcDuctSilencerType);
DECL_CONV_STUB(IfcLightSourceGoniometric);
DECL_CONV_STUB(IfcActuatorType);
DECL_CONV_STUB(IfcSensorType);
DECL_CONV_STUB(IfcAirTerminalBoxType);
DECL_CONV_STUB(IfcAnnotationSurfaceOccurrence);
DECL_CONV_STUB(IfcZShapeProfileDef);
DECL_CONV_STUB(IfcRationalBezierCurve);
DECL_CONV_STUB(IfcCartesianTransformationOperator2D);
DECL_CONV_STUB(IfcCartesianTransformationOperator2DnonUniform);
DECL_CONV_STUB(IfcMove);
DECL_CONV_STUB(IfcCableCarrierSegmentType);
DECL_CONV_STUB(IfcElectricalElement);
DECL_CONV_STUB(IfcChillerType);
DECL_CONV_STUB(IfcReinforcingBar);
DECL_CONV_STUB(IfcCShapeProfileDef);
DECL_CONV_STUB(IfcPermit);
DECL_CONV_STUB(IfcSlabType);
DECL_CONV_STUB(IfcLampType);
DECL_CONV_STUB(IfcPlanarExtent);
DECL_CONV_STUB(IfcAlarmType);
DECL_CONV_STUB(IfcElectricFlowStorageDeviceType);
DECL_CONV_STUB(IfcEquipmentElement);
DECL_CONV_STUB(IfcLightFixtureType);
DECL_CONV_STUB(IfcCurtainWall);
DECL_CONV_STUB(IfcSlab);
DECL_CONV_STUB(IfcCurtainWallType);
DECL_CONV_STUB(IfcOutletType);
DECL_CONV_STUB(IfcCompressorType);
DECL_CONV_STUB(IfcCraneRailAShapeProfileDef);
DECL_CONV_STUB(IfcFlowSegment);
DECL_CONV_STUB(IfcSectionedSpine);
DECL_CONV_STUB(IfcElectricTimeControlType);
DECL_CONV_STUB(IfcFaceSurface);
DECL_CONV_STUB(IfcMotorConnectionType);
DECL_CONV_STUB(IfcFlowFitting);
DECL_CONV_STUB(IfcPointOnCurve);
DECL_CONV_STUB(IfcTransportElementType);
DECL_CONV_STUB(IfcCableSegmentType);
DECL_CONV_STUB(IfcAnnotationSurface);
DECL_CONV_STUB(IfcCompositeCurveSegment);
DECL_CONV_STUB(IfcServiceLife);
DECL_CONV_STUB(IfcPlateType);
DECL_CONV_STUB(IfcVibrationIsolatorType);
DECL_CONV_STUB(IfcTrimmedCurve);
DECL_CONV_STUB(IfcMappedItem);
DECL_CONV_STUB(IfcDirection);
DECL_CONV_STUB(IfcBlock);
DECL_CONV_STUB(IfcProjectOrderRecord);
DECL_CONV_STUB(IfcFlowMeterType);
DECL_CONV_STUB(IfcControllerType);
DECL_CONV_STUB(IfcBeam);
DECL_CONV_STUB(IfcArbitraryOpenProfileDef);
DECL_CONV_STUB(IfcCenterLineProfileDef);
DECL_CONV_STUB(IfcTimeSeriesSchedule);
DECL_CONV_STUB(IfcRoundedEdgeFeature);
DECL_CONV_STUB(IfcIShapeProfileDef);
DECL_CONV_STUB(IfcSpaceHeaterType);
DECL_CONV_STUB(IfcFlowStorageDevice);
DECL_CONV_STUB(IfcRevolvedAreaSolid);
DECL_CONV_STUB(IfcDoor);
DECL_CONV_STUB(IfcEllipse);
DECL_CONV_STUB(IfcTubeBundleType);
DECL_CONV_STUB(IfcAngularDimension);
DECL_CONV_STUB(IfcFaceBasedSurfaceModel);
DECL_CONV_STUB(IfcCraneRailFShapeProfileDef);
DECL_CONV_STUB(IfcColumnType);
DECL_CONV_STUB(IfcTShapeProfileDef);
DECL_CONV_STUB(IfcEnergyConversionDevice);
DECL_CONV_STUB(IfcWorkSchedule);
DECL_CONV_STUB(IfcZone);
DECL_CONV_STUB(IfcTransportElement);
DECL_CONV_STUB(IfcGeometricRepresentationSubContext);
DECL_CONV_STUB(IfcLShapeProfileDef);
DECL_CONV_STUB(IfcGeometricCurveSet);
DECL_CONV_STUB(IfcActor);
DECL_CONV_STUB(IfcOccupant);
DECL_CONV_STUB(IfcBooleanClippingResult);
DECL_CONV_STUB(IfcAnnotationFillArea);
DECL_CONV_STUB(IfcLightSourceSpot);
DECL_CONV_STUB(IfcFireSuppressionTerminalType);
DECL_CONV_STUB(IfcElectricGeneratorType);
DECL_CONV_STUB(IfcInventory);
DECL_CONV_STUB(IfcPolyline);
DECL_CONV_STUB(IfcBoxedHalfSpace);
DECL_CONV_STUB(IfcAirTerminalType);
DECL_CONV_STUB(IfcDistributionPort);
DECL_CONV_STUB(IfcCostItem);
DECL_CONV_STUB(IfcStructuredDimensionCallout);
DECL_CONV_STUB(IfcStructuralResultGroup);
DECL_CONV_STUB(IfcOrientedEdge);
DECL_CONV_STUB(IfcCsgSolid);
DECL_CONV_STUB(IfcPlanarBox);
DECL_CONV_STUB(IfcMaterialDefinitionRepresentation);
DECL_CONV_STUB(IfcAsymmetricIShapeProfileDef);
DECL_CONV_STUB(IfcRepresentationMap);
#undef DECL_CONV_STUB
} //! STEP
} //! Assimp
#endif // INCLUDED_IFC_READER_GEN_H
| [
"aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f"
] | [
[
[
1,
4231
]
]
] |
4ecd50354915f0a31bdeea48f0b410ada4f362ad | ae0b041a5fb2170a3d1095868a7535cc82d6661f | /MFCHash/stdafx.cpp | 8953c3b2f3560b9237e39e1bb2d6ee832c5c49dc | [] | no_license | hexonxons/6thSemester | 59c479a1bb3cd715744543f4c2e0f8fdbf336f4a | c3c8fdea6eef49de629a7f454b91ceabd58d15d8 | refs/heads/master | 2016-09-15T17:45:13.433434 | 2011-06-08T20:57:25 | 2011-06-08T20:57:25 | 1,467,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 207 | cpp | // stdafx.cpp : source file that includes just the standard includes
// MFCHash.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"[email protected]"
] | [
[
[
1,
7
]
]
] |
7eef9ed7702103f0b89abf6e02218a4e1c984bab | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Engine/GUI/TextBox.cpp | d6f1ce446e1ae579d035a5521f7bd6775ef3b8a2 | [] | no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | cpp | #include "Core.h"
#include "TextBox.h"
#include "RenderManager.h"
#include "FontManager.h"
//---Constructor
CTextBox::CTextBox( uint32 windowsHeight, uint32 windowsWidth, float height_precent, float width_percent,
const Vect2f position_percent, float buttonWidthPercent, float buttonHeightPercent,
std::string lit, uint32 textHeightOffset, uint32 textWidthOffset,bool isVisible, bool isActive)
: CDialogBox( windowsHeight, windowsWidth, height_precent, width_percent, position_percent, buttonWidthPercent,
buttonHeightPercent, lit, textHeightOffset, textWidthOffset, isVisible, isActive)
, m_sMessage("Default_TextBox")
, m_uFontID(0)
, m_TextColor(colBLACK)
{}
void CTextBox::Render (CRenderManager *renderManager, CFontManager* fm)
{
if (CGuiElement::m_bIsVisible)
{
CDialogBox::Render(renderManager, fm);
//Pintamos el texto
fm->DrawText( CGuiElement::m_Position.x+20, CGuiElement::m_Position.y + (uint32)(CGuiElement::m_uHeight*0.4f),
m_TextColor, m_uFontID, m_sMessage.c_str());
}
}
void CTextBox::SetFont (CColor textColor, uint32 fontID)
{
m_uFontID = fontID;
m_TextColor = textColor;
}
| [
"atridas87@576ee6d0-068d-96d9-bff2-16229cd70485"
] | [
[
[
1,
37
]
]
] |
04563d637fea132077c49010408f12bf7f871f5b | 842997c28ef03f8deb3422d0bb123c707732a252 | /src/moaicore/MOAIEventSource.cpp | eaf9dc7b50ca5f7a6f6cf30bee0db52822c05908 | [] | 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 | 2,608 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <moaicore/MOAIEventSource.h>
#include <moaicore/MOAILogMessages.h>
//================================================================//
// lua
//================================================================//
//----------------------------------------------------------------//
/** @name setListener
@text Sets a listener callback for a given event ID. It is up
to individual classes to declare their event IDs.
@in MOAIEventSource self
@in number eventID The ID of the event.
@in function callback The callback to be called when the object emits the event.
@out nil
*/
int MOAIEventSource::_setListener ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAIEventSource, "UNF" );
self->AffirmListenerTable ( state );
self->mListenerTable.PushRef ( state );
lua_pushvalue ( state, 2 );
lua_pushvalue ( state, 3 );
lua_settable ( state, -3 );
return 0;
}
//================================================================//
// MOAIEventSource
//================================================================//
//----------------------------------------------------------------//
void MOAIEventSource::AffirmListenerTable ( USLuaState& state ) {
if ( !mListenerTable ) {
lua_newtable ( state );
this->mListenerTable.SetRef ( state, -1, false );
state.Pop ( 1 );
}
}
//----------------------------------------------------------------//
MOAIEventSource::MOAIEventSource () {
RTTI_BEGIN
RTTI_EXTEND ( USLuaObject )
RTTI_END
}
//----------------------------------------------------------------//
MOAIEventSource::~MOAIEventSource () {
}
//----------------------------------------------------------------//
bool MOAIEventSource::PushListenerAndSelf ( u32 eventID, USLuaState& state ) {
if ( this->mListenerTable ) {
this->mListenerTable.PushRef ( state );
if ( state.GetFieldWithType ( -1, eventID, LUA_TFUNCTION )) {
lua_replace ( state, -2 );
this->PushLuaUserdata ( state );
return true;
}
state.Pop ( 1 );
}
return false;
}
//----------------------------------------------------------------//
void MOAIEventSource::RegisterLuaClass ( USLuaState& state ) {
UNUSED ( state );
}
//----------------------------------------------------------------//
void MOAIEventSource::RegisterLuaFuncs ( USLuaState& state ) {
luaL_Reg regTable [] = {
{ "setListener", _setListener },
{ NULL, NULL }
};
luaL_register ( state, 0, regTable );
} | [
"Patrick@agile.(none)",
"[email protected]"
] | [
[
[
1,
92
]
],
[
[
93,
93
]
]
] |
1a30bb3d46e23897a50745dbf35f103b78bd6739 | 992d3f90ab0f41ca157000c4b18d071087d14d85 | /CURLOADE.CPP | e2e48e17702e251ef94b04feb092480c5c55fc93 | [] | no_license | axemclion/visionizzer | cabc53c9be41c07c04436a4733697e4ca35104e3 | 5b0158f8a3614e519183055e50c27349328677e7 | refs/heads/master | 2020-12-25T19:04:17.853016 | 2009-05-22T14:44:53 | 2009-05-22T14:44:53 | 29,331,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 921 | cpp | #include <graphics.h>
#include <dos.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <mouse.h>
int main(void)
{
int gdriver = DETECT, gmode, errorcode;
initgraph(&gdriver, &gmode, "");
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* return with error code */
}
mouse_present();
FILE *fp;
fp = fopen("c:\\windows\\cursors\\busy_1.cur","rt");
if (fp == NULL)
return 0;
char buffer;int count;
buffer=fgetc(fp);
if (buffer != 0) return 1;
buffer=fgetc(fp);
if (buffer != 0) return 1;
buffer=fgetc(fp);
if (buffer != 2) return 1;
buffer=fgetc(fp);
if (buffer != 0) return 1;
count = fgetc(fp);
printf("File opened ......");
fclose(fp);
getch();
closegraph();
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
40
]
]
] |
238f826685dcbe7974a3beba25673f0597c118e4 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestskins/src/bctestskinsapp.cpp | 58ec7b00c35dc8efd4917338c1c3eef42f471e76 | [] | no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,942 | cpp | /*
* Copyright (c) 2002 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: Avkon Template test app
*
*/
// INCLUDE FILES
#include "BCTestSkinsApp.h"
#include "BCTestSkinsDocument.h"
#include <eikstart.h>
// ================= MEMBER FUNCTIONS =========================================
// ----------------------------------------------------------------------------
// TUid CBCTestSkinsApp::AppDllUid()
// Returns application UID.
// ----------------------------------------------------------------------------
//
TUid CBCTestSkinsApp::AppDllUid() const
{
return KUidBCTestSkins;
}
// ----------------------------------------------------------------------------
// CApaDocument* CBCTestSkinsApp::CreateDocumentL()
// Creates CBCTestSkinsDocument object.
// ----------------------------------------------------------------------------
//
CApaDocument* CBCTestSkinsApp::CreateDocumentL()
{
return CBCTestSkinsDocument::NewL( *this );
}
// ================= OTHER EXPORTED FUNCTIONS =================================
//
// ----------------------------------------------------------------------------
// CApaApplication* NewApplication()
// Constructs CBCTestSkinsApp.
// Returns: CApaDocument*: created application object
// ----------------------------------------------------------------------------
//
LOCAL_C CApaApplication* NewApplication()
{
return new CBCTestSkinsApp;
}
GLDEF_C TInt E32Main()
{
return EikStart::RunApplication(NewApplication);
}
// End of File
| [
"none@none"
] | [
[
[
1,
64
]
]
] |
19b936b97ca10978a5b7d254871102febc184529 | 335783c9e5837a1b626073d1288b492f9f6b057f | /source/fbxcmd/daolib/Model/PHY/REVJ.cpp | 9fcdb1dab13ac9d13d12b9728b465143770734ce | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | code-google-com/fbx4eclipse | 110766ee9760029d5017536847e9f3dc09e6ebd2 | cc494db4261d7d636f8c4d0313db3953b781e295 | refs/heads/master | 2016-09-08T01:55:57.195874 | 2009-12-03T20:35:48 | 2009-12-03T20:35:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,460 | cpp |
/**********************************************************************
*<
FILE: REVJ.h
DESCRIPTION: PHY File Format
HISTORY:
*> Copyright (c) 2009, All Rights Reserved.
**********************************************************************/
#include <stdafx.h>
#include "GFF/GFFCommon.h"
#include "GFF/GFFField.h"
#include "GFF/GFFList.h"
#include "GFF/GFFStruct.h"
#include "PHY/PHYCommon.h"
#include "PHY/REVJ.h"
using namespace std;
using namespace DAO;
using namespace DAO::GFF;
using namespace DAO::PHY;
///////////////////////////////////////////////////////////////////
ShortString REVJ::type("REVJ");REVJ::REVJ(GFFStructRef owner) : impl(owner) {
}
Vector3f REVJ::get_jointRevoluteLimitLow() const {
return impl->GetField(GFF_MMH_JOINT_REVOLUTE_LIMIT_LOW)->asVector3f();
}
void REVJ::set_jointRevoluteLimitLow(Vector3f value) {
impl->GetField(GFF_MMH_JOINT_REVOLUTE_LIMIT_LOW)->assign(value);
}
Vector3f REVJ::get_jointRevoluteLimitHigh() const {
return impl->GetField(GFF_MMH_JOINT_REVOLUTE_LIMIT_HIGH)->asVector3f();
}
void REVJ::set_jointRevoluteLimitHigh(Vector3f value) {
impl->GetField(GFF_MMH_JOINT_REVOLUTE_LIMIT_HIGH)->assign(value);
}
float REVJ::get_jointRevoluteProjectionDistance() const {
return impl->GetField(GFF_MMH_JOINT_REVOLUTE_PROJECTION_DISTANCE)->asFloat32();
}
void REVJ::set_jointRevoluteProjectionDistance(float value) {
impl->GetField(GFF_MMH_JOINT_REVOLUTE_PROJECTION_DISTANCE)->assign(value);
}
float REVJ::get_jointRevoluteProjectionAngle() const {
return impl->GetField(GFF_MMH_JOINT_REVOLUTE_PROJECTION_ANGLE)->asFloat32();
}
void REVJ::set_jointRevoluteProjectionAngle(float value) {
impl->GetField(GFF_MMH_JOINT_REVOLUTE_PROJECTION_ANGLE)->assign(value);
}
unsigned long REVJ::get_jointRevoluteProjectionMode() const {
return impl->GetField(GFF_MMH_JOINT_REVOLUTE_PROJECTION_MODE)->asUInt32();
}
void REVJ::set_jointRevoluteProjectionMode(unsigned long value) {
impl->GetField(GFF_MMH_JOINT_REVOLUTE_PROJECTION_MODE)->assign(value);
}
Vector3f REVJ::get_jointRevoluteSpring() const {
return impl->GetField(GFF_MMH_JOINT_REVOLUTE_SPRING)->asVector3f();
}
void REVJ::set_jointRevoluteSpring(Vector3f value) {
impl->GetField(GFF_MMH_JOINT_REVOLUTE_SPRING)->assign(value);
}
float REVJ::get_jointRevoluteMotorVelTarget() const {
return impl->GetField(GFF_MMH_JOINT_REVOLUTE_MOTOR_VEL_TARGET)->asFloat32();
}
void REVJ::set_jointRevoluteMotorVelTarget(float value) {
impl->GetField(GFF_MMH_JOINT_REVOLUTE_MOTOR_VEL_TARGET)->assign(value);
}
float REVJ::get_jointRevoluteMotorMaxForce() const {
return impl->GetField(GFF_MMH_JOINT_REVOLUTE_MOTOR_MAX_FORCE)->asFloat32();
}
void REVJ::set_jointRevoluteMotorMaxForce(float value) {
impl->GetField(GFF_MMH_JOINT_REVOLUTE_MOTOR_MAX_FORCE)->assign(value);
}
unsigned char REVJ::get_jointRevoluteMotorFreeSpin() const {
return impl->GetField(GFF_MMH_JOINT_REVOLUTE_MOTOR_FREE_SPIN)->asUInt8();
}
void REVJ::set_jointRevoluteMotorFreeSpin(unsigned char value) {
impl->GetField(GFF_MMH_JOINT_REVOLUTE_MOTOR_FREE_SPIN)->assign(value);
}
unsigned long REVJ::get_jointRevoluteRevoluteFlags() const {
return impl->GetField(GFF_MMH_JOINT_REVOLUTE_REVOLUTE_FLAGS)->asUInt32();
}
void REVJ::set_jointRevoluteRevoluteFlags(unsigned long value) {
impl->GetField(GFF_MMH_JOINT_REVOLUTE_REVOLUTE_FLAGS)->assign(value);
}
| [
"tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792"
] | [
[
[
1,
106
]
]
] |
20e20208c872f55ed2b1096622e2555b1527aea1 | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib/src/input/MglDirectInputDeviceBase.h | 1508d290343a26967bdc4fc6aa70d7ff0c15ede3 | [] | no_license | myun2ext/open-mgl-legacy | 21ccadab8b1569af8fc7e58cf494aaaceee32f1e | 8faf07bad37a742f7174b454700066d53a384eae | refs/heads/master | 2016-09-06T11:41:14.108963 | 2009-12-28T12:06:58 | 2009-12-28T12:06:58 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,645 | h | //////////////////////////////////////////////////////////
//
// MglDirectInputDeviceBase - マウス入力クラス
//
// 2008/09/29 古いバッファ記憶対応
//////////////////////////////////////////////////////////
#ifndef __MglDirectInputDeviceBase_H__
#define __MglDirectInputDeviceBase_H__
#include "MglDirectInputBase.h"
// クラス宣言
class DLL_EXP CMglDirectInputDeviceBase : public CMglDirectInputBase, public CMyuReleaseBase
{
protected:
_MGL_IDirectInputDevice *m_pDevice;
//BYTE m_stateBuf[STATEBUF_SIZE];
BYTE *m_pStateBuf;
BYTE *m_pStateBuf2; // 2008/09/29 古いバッファ記憶対応
int m_nStateBufSize;
HWND m_hWnd;
void Acquire();
void Unacquire();
virtual void InitCheck()
{
if ( m_pDevice == NULL )
MyuThrow(20, "CMglDirectInputDeviceBase: Init()を呼び出してください。");
}
int GetStateChanged(int nIndex); // 0:変化なし 正の値:押された 負の値:離された
void SwapStateBuf(){
BYTE* pSwapWork = m_pStateBuf;
m_pStateBuf = m_pStateBuf2;
m_pStateBuf2 = pSwapWork;
}
public:
// コンストラクタ・デストラクタ
CMglDirectInputDeviceBase();
virtual ~CMglDirectInputDeviceBase();
// 初期化と開放
void Init( REFGUID rguid, LPCDIDATAFORMAT dataFormat, int nStateBufSize,
HWND hWnd=NULL, DWORD dwCooperativeFlag=DISCL_NONEXCLUSIVE|DISCL_FOREGROUND );
void Release();
BYTE* UpdateStateBuf();
BYTE* GetStateBuf(){ return m_pStateBuf; }
BYTE* GetOldStateBuf(){ return m_pStateBuf2; }
//BYTE* GetStateBuf(){ return UpdateStateBuf(); }
};
#endif//__MglDirectInputDeviceBase_H__ | [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
] | [
[
[
1,
56
]
]
] |
0a5d1174b1582933c9b46601c011ac69f3359f3b | 0b55a33f4df7593378f58b60faff6bac01ec27f3 | /Konstruct/Client/Dimensions/GameState_GamePlay.cpp | 392f84d4bf163efe6770c2c7540aa8c853facefe | [] | no_license | RonOHara-GG/dimgame | 8d149ffac1b1176432a3cae4643ba2d07011dd8e | bbde89435683244133dca9743d652dabb9edf1a4 | refs/heads/master | 2021-01-10T21:05:40.480392 | 2010-09-01T20:46:40 | 2010-09-01T20:46:40 | 32,113,739 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,525 | cpp | #include "StdAfx.h"
#include "GameState_GamePlay.h"
#include "LevelManager.h"
#include "Level.h"
#include "PlayerCharacter.h"
#include "Common\Procedural\kppBox.h"
#include "Common\Procedural\kppPlane.h"
#include "Common\Procedural\kppTerrain.h"
#include "Common\Procedural\kppHuman.h"
#include "Common\Graphics\kpgGeometryInstance.h"
#include "Common\Graphics\kpgRenderer.h"
#include "Common\Graphics\kpgLight.h"
#include "Common\Graphics\kpgShader.h"
#include "Common\Graphics\kpgUIManager.h"
#include "Common\Utility\kpuCameraController.h"
#include "Common\Utility\kpuThreeQuarterTopDownCamera.h"
#include "Common\Utility\kpuVector.h"
#include "Grid.h"
#include "Enemy.h"
#include "MerchantNpc.h"
#include "Common/Utility/kpuQuadTree.h"
#include "Common\Input\kpiInputManager.h"
GameState_GamePlay::GameState_GamePlay(void)
{
// Create the UI manager & load the UI for this game state
m_pUIManager = new kpgUIManager();
m_pUIManager->LoadWindows("Assets/UI/GamePlay/GamePlayUI.xml");
// Setup basic camera info
kpuVector vLocation(12.0f, 18.0f, 12.0f, 0.0f);
kpuVector vLookAt(0.0f, 0.0f, 0.0f, 0.0f);
m_pCamera = new kpuThreeQuarterTopDownCamera(vLocation, vLookAt, kpuv_OneY);
// Setup render matrices
kpgRenderer* pRenderer = kpgRenderer::GetInstance();
m_mProjection.Perspective(45.0f, pRenderer->GetScreenWidth() / pRenderer->GetScreenHeight(), 0.001f, 10000.0f);
pRenderer->SetProjectionMatrix(m_mProjection);
pRenderer->SetViewMatrix(m_pCamera->GetViewMatrix());
// setup render state
pRenderer->SetCullMode(kpgRenderer::eCM_None);
pRenderer->GetDevice()->SetRenderState( D3DRS_LIGHTING, FALSE );
// for now, setup a temp light
kpgLight* pDummyLight = new kpgLight(kpgLight::eLT_Directional);
kpuVector vLightDir(-1, -1, 0, 0);
vLightDir.Normalize();
pDummyLight->SetDirection(vLightDir);
pDummyLight->SetColor(kpuVector(0.0f, 0.0f, 0.0f, 0.75f));
pRenderer->SetLight(0, pDummyLight);
}
GameState_GamePlay::~GameState_GamePlay(void)
{
//delete m_pCurrentLevel;
if(m_paActors)
{
for(int i = 0; i < m_paActors->Count(); i++)
{
Actor* pActor = (*m_paActors)[i];
m_paActors->RemoveAt(i);
delete pActor;
}
delete m_paActors;
}
}
void GameState_GamePlay::MouseUpdate(int X, int Y)
{
kpuVector vGroundPoint((float)X, (float)Y, 0.0f, 0.0f);
ScreenCordsToGameCords(vGroundPoint);
//set heading to mouse
m_pPlayer->SetHeading(kpuVector::Normalize(vGroundPoint - m_pPlayer->GetLocation()));
// Update the players move target to the new ground point
int iTile = m_pCurrentLevel->GetGrid()->GetTileAtLocation(vGroundPoint);
if( m_pCurrentLevel->GetGrid()->TileWalkable(iTile) )
{
//If target tile contains an actor get it and process event
Actor* pTarget = m_pCurrentLevel->GetGrid()->GetActor(iTile);
if( pTarget )
{
if( pTarget->HasFlag(ATTACKABLE) && m_pPlayer->IsInRange(pTarget, m_pPlayer->GetRange()) )
{
//attack it
m_pPlayer->SetTarget(pTarget);
m_pPlayer->UseDefaultAttack(pTarget, m_pCurrentLevel->GetGrid());
}
else if( pTarget->HasFlag(NPC) && pTarget->IsInRange(m_pPlayer, pTarget->GetRange()) )
{
Npc* pNpc = (Npc*)pTarget;
pNpc->Interact(m_pPlayer);
}
else
m_pPlayer->SetMoveTarget(iTile);
}
else
m_pPlayer->SetMoveTarget(iTile);
}
}
void GameState_GamePlay::ScreenCordsToGameCords(kpuVector& vCords)
{
// Find projected ground point for the screen coordinates
kpgRenderer* pRenderer = kpgRenderer::GetInstance();
kpuMatrix mIProj = m_mProjection;
kpuMatrix mIView = m_pCamera->GetViewMatrix();
kpuVector vRayDir;
vRayDir.SetX(-(((2.0f * vCords.GetX()) / pRenderer->GetScreenWidth()) - 1) / mIProj.GetA().GetX());
vRayDir.SetY((((2.0f * vCords.GetY()) / pRenderer->GetScreenHeight()) - 1) / mIProj.GetB().GetY());
vRayDir.SetZ(1.0f);
vRayDir.SetW(0.0f);
mIView.Invert();
vRayDir *= mIView;
// Project the ray onto the ground plane to find the ground point
kpuVector vRayOrigin = mIView.GetD();
float fT = -vRayOrigin.GetY() / vRayDir.GetY();
vCords = vRayOrigin + (vRayDir * fT);
}
void GameState_GamePlay::Update(float fDeltaTime)
{
// Update the UI
m_pUIManager->Update();
if( m_pPlayer )
{
m_pCamera->SetLookAt(m_pPlayer->GetLocation());
}
m_pCamera->Update();
if( m_pCurrentLevel )
m_pCurrentLevel->Update(fDeltaTime);
if(m_paActors)
{
for(int i = 0; i < m_paActors->Count(); i++)
{
Actor* pActor = (*m_paActors)[i];
if(!pActor->Update(fDeltaTime))
{
m_paActors->Remove(pActor);
pActor->GetCurrentNode()->Remove(pActor);
m_pCurrentLevel->GetGrid()->RemoveActor(pActor);
delete pActor;
pActor= 0;
}
}
}
}
void GameState_GamePlay::Draw()
{
kpgRenderer* pRenderer = kpgRenderer::GetInstance();
pRenderer->SetProjectionMatrix(m_mProjection);
pRenderer->SetViewMatrix(m_pCamera->GetViewMatrix());
pRenderer->SetAmbientLightColor(kpuVector(0.75f, 0.75f, 0.75f, 1.0f));
if( m_pCurrentLevel )
m_pCurrentLevel->Draw(pRenderer);
if(m_paActors)
{
for(int i = 0; i < m_paActors->Count(); i++)
{
Actor* pActor = (*m_paActors)[i];
pActor->Draw(pRenderer);
}
}
// Draw UI
m_pUIManager->Draw(pRenderer);
}
void GameState_GamePlay::AddActor(Actor* pActor)
{
if(m_paActors)
m_paActors->Add(pActor);
}
bool GameState_GamePlay::HandleInputEvent(eInputEventType type, u32 button)
{
if( m_pUIManager )
{
EventParam result = m_pUIManager->HandleInputEvent(type, button);
if( result.m_uEvent == 0 )
return true;
//try and handle game specific result
}
bool bHandled = false;
kpPoint ptMousePos = g_pInputManager->GetMouseLoc();
switch(type)
{
case eIET_ButtonUp:
{
switch(button)
{
case KPIM_BUTTON_0:
{
MouseUpdate(ptMousePos.m_iX, ptMousePos.m_iY );
bHandled = true;
break;
}
}
break;
}
case eIET_KeyPress:
{
switch(button)
{
case KPIK_I:
{
//toggle the inventory window
m_pUIManager->ToggleUIWindow(KE_INVENTORY);
bHandled = true;
break;
}
case KPIK_C:
{
//toggle the Character window
m_pPlayer->SetCharacterWindowData();
m_pUIManager->ToggleUIWindow(KE_CHARACTER);
bHandled = true;
break;
}
}
break;
}
}
return bHandled;
} | [
"acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e",
"bflassing@0c57dbdb-4d19-7b8c-568b-3fe73d88484e"
] | [
[
[
1,
16
],
[
18,
18
],
[
22,
27
],
[
30,
40
],
[
42,
52
],
[
55,
58
],
[
73,
76
],
[
78,
78
],
[
83,
85
],
[
115,
116
],
[
137,
145
],
[
149,
149
],
[
151,
151
],
[
158,
158
],
[
168,
173
],
[
175,
180
],
[
190,
192
],
[
195,
195
],
[
199,
202
],
[
213,
215
],
[
217,
218
],
[
222,
222
],
[
255,
256
]
],
[
[
17,
17
],
[
19,
21
],
[
28,
29
],
[
41,
41
],
[
53,
54
],
[
59,
72
],
[
77,
77
],
[
79,
82
],
[
86,
114
],
[
117,
136
],
[
146,
148
],
[
150,
150
],
[
152,
157
],
[
159,
167
],
[
174,
174
],
[
181,
189
],
[
193,
194
],
[
196,
198
],
[
203,
212
],
[
216,
216
],
[
219,
221
],
[
223,
254
]
]
] |
c0fbdc3c324e87cf09db0a1638e07780c437b83c | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/matrix/matrix_la_abstract.h | e3378a79aa05371f9e7824abf294b6330b551c83 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | athulan/cppagent | 58f078cee55b68c08297acdf04a5424c2308cfdc | 9027ec4e32647e10c38276e12bcfed526a7e27dd | refs/heads/master | 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 29,925 | h | // Copyright (C) 2009 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_MATRIx_LA_FUNCTS_ABSTRACT_
#ifdef DLIB_MATRIx_LA_FUNCTS_ABSTRACT_
#include "matrix_abstract.h"
#include <complex>
namespace dlib
{
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// Global linear algebra functions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
const matrix_exp::matrix_type inv (
const matrix_exp& m
);
/*!
requires
- m is a square matrix
ensures
- returns the inverse of m
(Note that if m is singular or so close to being singular that there
is a lot of numerical error then the returned matrix will be bogus.
You can check by seeing if m*inv(m) is an identity matrix)
!*/
// ----------------------------------------------------------------------------------------
const matrix pinv (
const matrix_exp& m
);
/*!
ensures
- returns the Moore-Penrose pseudoinverse of m.
- The returned matrix has m.nc() rows and m.nr() columns.
!*/
// ----------------------------------------------------------------------------------------
void svd (
const matrix_exp& m,
matrix<matrix_exp::type>& u,
matrix<matrix_exp::type>& w,
matrix<matrix_exp::type>& v
);
/*!
ensures
- computes the singular value decomposition of m
- m == #u*#w*trans(#v)
- trans(#u)*#u == identity matrix
- trans(#v)*#v == identity matrix
- diag(#w) == the singular values of the matrix m in no
particular order. All non-diagonal elements of #w are
set to 0.
- #u.nr() == m.nr()
- #u.nc() == m.nc()
- #w.nr() == m.nc()
- #w.nc() == m.nc()
- #v.nr() == m.nc()
- #v.nc() == m.nc()
!*/
// ----------------------------------------------------------------------------------------
long svd2 (
bool withu,
bool withv,
const matrix_exp& m,
matrix<matrix_exp::type>& u,
matrix<matrix_exp::type>& w,
matrix<matrix_exp::type>& v
);
/*!
requires
- m.nr() >= m.nc()
ensures
- computes the singular value decomposition of matrix m
- m == subm(#u,get_rect(m))*diagm(#w)*trans(#v)
- trans(#u)*#u == identity matrix
- trans(#v)*#v == identity matrix
- #w == the singular values of the matrix m in no
particular order.
- #u.nr() == m.nr()
- #u.nc() == m.nr()
- #w.nr() == m.nc()
- #w.nc() == 1
- #v.nr() == m.nc()
- #v.nc() == m.nc()
- if (widthu == false) then
- ignore the above regarding #u, it isn't computed and its
output state is undefined.
- if (widthv == false) then
- ignore the above regarding #v, it isn't computed and its
output state is undefined.
- returns an error code of 0, if no errors and 'k' if we fail to
converge at the 'kth' singular value.
!*/
// ----------------------------------------------------------------------------------------
void svd3 (
const matrix_exp& m,
matrix<matrix_exp::type>& u,
matrix<matrix_exp::type>& w,
matrix<matrix_exp::type>& v
);
/*!
ensures
- computes the singular value decomposition of m
- m == #u*diagm(#w)*trans(#v)
- trans(#u)*#u == identity matrix
- trans(#v)*#v == identity matrix
- #w == the singular values of the matrix m in no
particular order.
- #u.nr() == m.nr()
- #u.nc() == m.nc()
- #w.nr() == m.nc()
- #w.nc() == 1
- #v.nr() == m.nc()
- #v.nc() == m.nc()
!*/
// ----------------------------------------------------------------------------------------
const matrix real_eigenvalues (
const matrix_exp& m
);
/*!
requires
- m.nr() == m.nc()
- matrix_exp::type == float or double
ensures
- returns a matrix E such that:
- E.nr() == m.nr()
- E.nc() == 1
- E contains the real part of all eigenvalues of the matrix m.
(note that the eigenvalues are not sorted)
!*/
// ----------------------------------------------------------------------------------------
const matrix_exp::type det (
const matrix_exp& m
);
/*!
requires
- m is a square matrix
ensures
- returns the determinant of m
!*/
// ----------------------------------------------------------------------------------------
const matrix_exp::matrix_type chol (
const matrix_exp& A
);
/*!
requires
- A is a square matrix
ensures
- if (A has a Cholesky Decomposition) then
- returns the decomposition of A. That is, returns a matrix L
such that L*trans(L) == A. L will also be lower triangular.
- else
- returns a matrix with the same dimensions as A but it
will have a bogus value. I.e. it won't be a decomposition.
!*/
// ----------------------------------------------------------------------------------------
const matrix_exp::matrix_type inv_lower_triangular (
const matrix_exp& A
);
/*!
requires
- A is a square matrix
ensures
- if (A is lower triangular) then
- returns the inverse of A.
- else
- returns a matrix with the same dimensions as A but it
will have a bogus value. I.e. it won't be an inverse.
!*/
// ----------------------------------------------------------------------------------------
const matrix_exp::matrix_type inv_upper_triangular (
const matrix_exp& A
);
/*!
requires
- A is a square matrix
ensures
- if (A is upper triangular) then
- returns the inverse of A.
- else
- returns a matrix with the same dimensions as A but it
will have a bogus value. I.e. it won't be an inverse.
!*/
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// Matrix decomposition classes
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
template <
typename matrix_exp_type
>
class lu_decomposition
{
/*!
REQUIREMENTS ON matrix_exp_type
must be some kind of matrix expression as defined in the
dlib/matrix/matrix_abstract.h file. (e.g. a dlib::matrix object)
The matrix type must also contain float or double values.
WHAT THIS OBJECT REPRESENTS
This object represents something that can compute an LU
decomposition of a real valued matrix. That is, for any
matrix A it computes matrices L, U, and a pivot vector P such
that rowm(A,P) == L*U.
The LU decomposition with pivoting always exists, even if the matrix is
singular, so the constructor will never fail. The primary use of the
LU decomposition is in the solution of square systems of simultaneous
linear equations. This will fail if is_singular() returns true (or
if A is very nearly singular).
!*/
public:
const static long NR = matrix_exp_type::NR;
const static long NC = matrix_exp_type::NC;
typedef typename matrix_exp_type::type type;
typedef typename matrix_exp_type::mem_manager_type mem_manager_type;
typedef typename matrix_exp_type::layout_type layout_type;
typedef matrix<type,0,0,mem_manager_type,layout_type> matrix_type;
typedef matrix<type,NR,1,mem_manager_type,layout_type> column_vector_type;
typedef matrix<long,NR,1,mem_manager_type,layout_type> pivot_column_vector_type;
template <typename EXP>
lu_decomposition (
const matrix_exp<EXP> &A
);
/*!
requires
- EXP::type == lu_decomposition::type
- A.size() > 0
ensures
- #nr() == A.nr()
- #nc() == A.nc()
- #is_square() == (A.nr() == A.nc())
- computes the LU factorization of the given A matrix.
!*/
bool is_square (
) const;
/*!
ensures
- if (the input A matrix was a square matrix) then
- returns true
- else
- returns false
!*/
bool is_singular (
) const;
/*!
requires
- is_square() == true
ensures
- if (the input A matrix is singular) then
- returns true
- else
- returns false
!*/
long nr(
) const;
/*!
ensures
- returns the number of rows in the input matrix
!*/
long nc(
) const;
/*!
ensures
- returns the number of columns in the input matrix
!*/
const matrix_type get_l (
) const;
/*!
ensures
- returns the lower triangular L factor of the LU factorization.
- L.nr() == nr()
- L.nc() == min(nr(),nc())
!*/
const matrix_type get_u (
) const;
/*!
ensures
- returns the upper triangular U factor of the LU factorization.
- U.nr() == min(nr(),nc())
- U.nc() == nc()
!*/
const pivot_column_vector_type& get_pivot (
) const;
/*!
ensures
- returns the pivot permutation vector. That is,
if A is the input matrix then this function
returns a vector P such that:
- rowm(A,P) == get_l()*get_u()
- P.nr() == A.nr()
!*/
type det (
) const;
/*!
requires
- is_square() == true
ensures
- computes and returns the determinant of the input
matrix using LU factors.
!*/
template <typename EXP>
const matrix_type solve (
const matrix_exp<EXP> &B
) const;
/*!
requires
- EXP::type == lu_decomposition::type
- is_square() == true
- B.nr() == nr()
ensures
- Let A denote the input matrix to this class's constructor.
Then this function solves A*X == B for X and returns X.
- Note that if A is singular (or very close to singular) then
the X returned by this function won't fit A*X == B very well (if at all).
!*/
};
// ----------------------------------------------------------------------------------------
template <
typename matrix_exp_type
>
class cholesky_decomposition
{
/*!
REQUIREMENTS ON matrix_exp_type
must be some kind of matrix expression as defined in the
dlib/matrix/matrix_abstract.h file. (e.g. a dlib::matrix object)
The matrix type must also contain float or double values.
WHAT THIS OBJECT REPRESENTS
This object represents something that can compute a cholesky
decomposition of a real valued matrix. That is, for any
symmetric, positive definite matrix A, it computes a lower
triangular matrix L such that A == L*trans(L).
If the matrix is not symmetric or positive definite, the function
computes only a partial decomposition. This can be tested with
the is_spd() flag.
!*/
public:
const static long NR = matrix_exp_type::NR;
const static long NC = matrix_exp_type::NC;
typedef typename matrix_exp_type::type type;
typedef typename matrix_exp_type::mem_manager_type mem_manager_type;
typedef typename matrix_exp_type::layout_type layout_type;
typedef typename matrix_exp_type::matrix_type matrix_type;
typedef matrix<type,NR,1,mem_manager_type,layout_type> column_vector_type;
template <typename EXP>
cholesky_decomposition(
const matrix_exp<EXP>& A
);
/*!
requires
- EXP::type == cholesky_decomposition::type
- A.size() > 0
- A.nr() == A.nc()
(i.e. A must be a square matrix)
ensures
- if (A is symmetric positive-definite) then
- #is_spd() == true
- Constructs a lower triangular matrix L, such that L*trans(L) == A.
and #get_l() == L
- else
- #is_spd() == false
!*/
bool is_spd(
) const;
/*!
ensures
- if (the input matrix was symmetric positive-definite) then
- returns true
- else
- returns false
!*/
const matrix_type& get_l(
) const;
/*!
ensures
- returns the lower triangular factor, L, such that L*trans(L) == A
(where A is the input matrix to this class's constructor)
- Note that if A is not symmetric positive definite or positive semi-definite
then the equation L*trans(L) == A won't hold.
!*/
template <typename EXP>
const matrix solve (
const matrix_exp<EXP>& B
) const;
/*!
requires
- EXP::type == cholesky_decomposition::type
- B.nr() == get_l().nr()
(i.e. the number of rows in B must match the number of rows in the
input matrix A)
ensures
- Let A denote the input matrix to this class's constructor. Then
this function solves A*X = B for X and returns X.
- Note that if is_spd() == false or A was really close to being
non-SPD then the solver will fail to find an accurate solution.
!*/
};
// ----------------------------------------------------------------------------------------
template <
typename matrix_exp_type
>
class qr_decomposition
{
/*!
REQUIREMENTS ON matrix_exp_type
must be some kind of matrix expression as defined in the
dlib/matrix/matrix_abstract.h file. (e.g. a dlib::matrix object)
The matrix type must also contain float or double values.
WHAT THIS OBJECT REPRESENTS
This object represents something that can compute a classical
QR decomposition of an m-by-n real valued matrix A with m >= n.
The QR decomposition is an m-by-n orthogonal matrix Q and an
n-by-n upper triangular matrix R so that A == Q*R. The QR decomposition
always exists, even if the matrix does not have full rank, so the
constructor will never fail. The primary use of the QR decomposition
is in the least squares solution of non-square systems of simultaneous
linear equations. This will fail if is_full_rank() returns false or
A is very nearly not full rank.
The Q and R factors can be retrieved via the get_q() and get_r()
methods. Furthermore, a solve() method is provided to find the
least squares solution of Ax=b using the QR factors.
!*/
public:
const static long NR = matrix_exp_type::NR;
const static long NC = matrix_exp_type::NC;
typedef typename matrix_exp_type::type type;
typedef typename matrix_exp_type::mem_manager_type mem_manager_type;
typedef typename matrix_exp_type::layout_type layout_type;
typedef matrix<type,0,0,mem_manager_type,layout_type> matrix_type;
typedef matrix<type,0,1,mem_manager_type,layout_type> column_vector_type;
template <typename EXP>
qr_decomposition(
const matrix_exp<EXP>& A
);
/*!
requires
- EXP::type == qr_decomposition::type
- A.nr() >= A.nc()
- A.size() > 0
ensures
- #nr() == A.nr()
- #nc() == A.nc()
- computes the QR decomposition of the given A matrix.
!*/
bool is_full_rank(
) const;
/*!
ensures
- if (the input A matrix had full rank) then
- returns true
- else
- returns false
!*/
long nr(
) const;
/*!
ensures
- returns the number of rows in the input matrix
!*/
long nc(
) const;
/*!
ensures
- returns the number of columns in the input matrix
!*/
const matrix_type get_householder (
) const;
/*!
ensures
- returns a matrix H such that:
- H is the lower trapezoidal matrix whose columns define the
Householder reflection vectors from QR factorization
- H.nr() == nr()
- H.nc() == nc()
!*/
const matrix_type get_r (
) const;
/*!
ensures
- returns a matrix R such that:
- R is the upper triangular factor, R, of the QR factorization
- get_q()*R == input matrix A
- R.nr() == nc()
- R.nc() == nc()
!*/
const matrix_type get_q (
) const;
/*!
ensures
- returns a matrix Q such that:
- Q is the economy-sized orthogonal factor Q from the QR
factorization.
- trans(Q)*Q == identity matrix
- Q*get_r() == input matrix A
- Q.nr() == nr()
- Q.nc() == nc()
!*/
template <typename EXP>
const matrix_type solve (
const matrix_exp<EXP>& B
) const;
/*!
requires
- EXP::type == qr_decomposition::type
- B.nr() == nr()
ensures
- Let A denote the input matrix to this class's constructor.
Then this function finds the least squares solution to the equation A*X = B
and returns X. X has the following properties:
- X is the matrix that minimizes the two norm of A*X-B. That is, it
minimizes sum(squared(A*X - B)).
- X.nr() == nc()
- X.nc() == B.nc()
- Note that this function will fail to output a good solution if is_full_rank() == false
or the A matrix is close to not being full rank.
!*/
};
// ----------------------------------------------------------------------------------------
template <
typename matrix_exp_type
>
class eigenvalue_decomposition
{
/*!
REQUIREMENTS ON matrix_exp_type
must be some kind of matrix expression as defined in the
dlib/matrix/matrix_abstract.h file. (e.g. a dlib::matrix object)
The matrix type must also contain float or double values.
WHAT THIS OBJECT REPRESENTS
This object represents something that can compute an eigenvalue
decomposition of a real valued matrix. So it gives
you the set of eigenvalues and eigenvectors for a matrix.
Let A denote the input matrix to this object's constructor. Then
what this object does is it finds two matrices, D and V, such that
- A*V == V*D
Where V is a square matrix that contains all the eigenvectors
of the A matrix (each column of V is an eigenvector) and
D is a diagonal matrix containing the eigenvalues of A.
It is important to note that if A is symmetric or non-symmetric you
get somewhat different results. If A is a symmetric matrix (i.e. A == trans(A))
then:
- All the eigenvalues and eigenvectors of A are real numbers.
- Because of this there isn't really any point in using the
part of this class's interface that returns complex matrices.
All you need are the get_real_eigenvalues() and
get_pseudo_v() functions.
- V*trans(V) should be equal to the identity matrix. That is, all the
eigenvectors in V should be linearly independent.
- So A == V*D*trans(V)
On the other hand, if A is not symmetric then:
- Some of the eigenvalues and eigenvectors might be complex numbers.
- An eigenvalue is complex if and only if its corresponding eigenvector
is complex. So you can check for this case by just checking
get_imag_eigenvalues() to see if any values are non-zero. You don't
have to check the V matrix as well.
- V*trans(V) won't be equal to the identity matrix but it is usually
invertible. So A == V*D*inv(V) is usually a valid statement but
A == V*D*trans(V) won't be.
!*/
public:
const static long NR = matrix_exp_type::NR;
const static long NC = matrix_exp_type::NC;
typedef typename matrix_exp_type::type type;
typedef typename matrix_exp_type::mem_manager_type mem_manager_type;
typedef typename matrix_exp_type::layout_type layout_type;
typedef typename matrix_exp_type::matrix_type matrix_type;
typedef matrix<type,NR,1,mem_manager_type,layout_type> column_vector_type;
typedef matrix<std::complex<type>,0,0,mem_manager_type,layout_type> complex_matrix_type;
typedef matrix<std::complex<type>,NR,1,mem_manager_type,layout_type> complex_column_vector_type;
template <typename EXP>
eigenvalue_decomposition(
const matrix_exp<EXP>& A
);
/*!
requires
- A.nr() == A.nc()
- A.size() > 0
- EXP::type == eigenvalue_decomposition::type
ensures
- #dim() == A.nr()
- computes the eigenvalue decomposition of A.
- #get_eigenvalues() == the eigenvalues of A
- #get_v() == all the eigenvectors of A
!*/
long dim (
) const;
/*!
ensures
- dim() == the number of rows/columns in the input matrix A
!*/
const complex_column_vector_type get_eigenvalues (
) const;
/*!
ensures
- returns diag(get_d()). That is, returns a
vector that contains the eigenvalues of the input
matrix.
- the returned vector has dim() rows
- the eigenvalues are not sorted in any particular way
!*/
const column_vector_type& get_real_eigenvalues (
) const;
/*!
ensures
- returns the real parts of the eigenvalues. That is,
returns real(get_eigenvalues())
- the returned vector has dim() rows
- the eigenvalues are not sorted in any particular way
!*/
const column_vector_type& get_imag_eigenvalues (
) const;
/*!
ensures
- returns the imaginary parts of the eigenvalues. That is,
returns imag(get_eigenvalues())
- the returned vector has dim() rows
- the eigenvalues are not sorted in any particular way
!*/
const complex_matrix_type get_v (
) const;
/*!
ensures
- returns the eigenvector matrix V that is
dim() rows by dim() columns
- Each column in V is one of the eigenvectors of the input
matrix
!*/
const complex_matrix_type get_d (
) const;
/*!
ensures
- returns a matrix D such that:
- D.nr() == dim()
- D.nc() == dim()
- diag(D) == get_eigenvalues()
(i.e. the diagonal of D contains all the eigenvalues in the input matrix)
- all off diagonal elements of D are set to 0
!*/
const matrix_type& get_pseudo_v (
) const;
/*!
ensures
- returns a matrix that is dim() rows by dim() columns
- Let A denote the input matrix given to this object's constructor.
- if (A has any imaginary eigenvalues) then
- returns the pseudo-eigenvector matrix V
- The matrix V returned by this function is structured such that:
- A*V == V*get_pseudo_d()
- else
- returns the eigenvector matrix V with A's eigenvectors as
the columns of V
- A*V == V*diagm(get_real_eigenvalues())
!*/
const matrix_type get_pseudo_d (
) const;
/*!
ensures
- The returned matrix is dim() rows by dim() columns
- Computes and returns the block diagonal eigenvalue matrix.
If the original matrix A is not symmetric, then the eigenvalue
matrix D is block diagonal with the real eigenvalues in 1-by-1
blocks and any complex eigenvalues,
a + i*b, in 2-by-2 blocks, (a, b; -b, a). That is, if the complex
eigenvalues look like
u + iv . . . . .
. u - iv . . . .
. . a + ib . . .
. . . a - ib . .
. . . . x .
. . . . . y
Then D looks like
u v . . . .
-v u . . . .
. . a b . .
. . -b a . .
. . . . x .
. . . . . y
This keeps V (The V you get from get_pseudo_v()) a real matrix in both
symmetric and non-symmetric cases, and A*V = V*D.
- the eigenvalues are not sorted in any particular way
!*/
};
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_MATRIx_LA_FUNCTS_ABSTRACT_
| [
"jimmy@DGJ3X3B1.(none)"
] | [
[
[
1,
781
]
]
] |
ca99415e5b3ac7623dc3b1f9d61546abe4e439fb | 011359e589f99ae5fe8271962d447165e9ff7768 | /src/burner/win32/stated.cpp | b9d64cf6890455ae74c1ee82b89f547b253598a1 | [] | no_license | PS3emulators/fba-next-slim | 4c753375fd68863c53830bb367c61737393f9777 | d082dea48c378bddd5e2a686fe8c19beb06db8e1 | refs/heads/master | 2021-01-17T23:05:29.479865 | 2011-12-01T18:16:02 | 2011-12-01T18:16:02 | 2,899,840 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,317 | cpp | // State dialog module
#include "burner.h"
int bDrvSaveAll = 0;
static void StateMakeOfn(TCHAR* pszFilter)
{
_stprintf(pszFilter, FBALoadStringEx(IDS_DISK_FILE_STATE), _T(APP_TITLE));
memcpy(pszFilter + _tcslen(pszFilter), _T(" (*.fs, *.fr)\0*.fs;*.fr\0\0"), 25 * sizeof(TCHAR));
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hScrnWnd;
ofn.lpstrFilter = pszFilter;
ofn.lpstrFile = szChoice;
ofn.nMaxFile = sizearray(szChoice);
ofn.lpstrInitialDir = getMiscPath(PATH_SAVESTATE);
ofn.lpstrTitle = FBALoadStringEx(IDS_STATE_LOAD);
ofn.Flags = OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
ofn.lpstrDefExt = _T("fs");
return;
}
// The automatic save
int StatedAuto(int bSave)
{
static TCHAR szName[MAX_PATH] = _T("");
int nRet;
_stprintf(szName, _T("config\\games\\%s.fs"), BurnDrvGetText(DRV_NAME));
if (bSave == 0) {
nRet = BurnStateLoad(szName, bDrvSaveAll, NULL); // Load ram
if (nRet && bDrvSaveAll) {
nRet = BurnStateLoad(szName, 0, NULL); // Couldn't get all - okay just try the nvram
}
} else {
nRet = BurnStateSave(szName, bDrvSaveAll); // Save ram
}
return nRet;
}
static void CreateStateName(int nSlot)
{
// create dir if dir doesn't exist
if (!directoryExists(getMiscPath(PATH_SAVESTATE))) {
CreateDirectory(getMiscPath(PATH_SAVESTATE), NULL);
}
_stprintf(szChoice, _T("%s%s slot %02x.fs"), getMiscPath(PATH_SAVESTATE), BurnDrvGetText(DRV_NAME), nSlot);
}
int StatedLoad(int nSlot)
{
TCHAR szFilter[1024];
int nRet;
int bOldPause;
if (bDrvOkay == 0) {
return 1;
}
// if rewinding during playback, and readonly is not set,
// then transition from decoding to encoding
if (!bReplayReadOnly && nReplayStatus == 2)
{
nReplayStatus = 1;
}
if (bReplayReadOnly && nReplayStatus == 1)
{
StopReplay();
nReplayStatus = 2;
}
if (nSlot) {
CreateStateName(nSlot);
} else {
if (bDrvOkay) {
_stprintf(szChoice, _T("%s*.fs"), BurnDrvGetText(DRV_NAME));
} else {
_stprintf(szChoice, _T("savestate"));
}
StateMakeOfn(szFilter);
bOldPause = bRunPause;
bRunPause = 1;
nRet = GetOpenFileName(&ofn);
bRunPause = bOldPause;
if (nRet == 0) { // Error
VidSNewShortMsg(FBALoadStringEx(IDS_STATE_LOAD_ERROR), 0xFF3F3F);
return 1;
}
}
nRet = BurnStateLoad(szChoice, 1, &DrvInitCallback);
VidSNewShortMsg(FBALoadStringEx(IDS_STATE_LOADED));
if (nSlot) {
return nRet;
}
// Describe any possible errors:
if (nRet == 3) {
FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_DISK_THIS_STATE));
FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_ERR_DISK_UNAVAIL));
} else {
if (nRet == 4) {
FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_DISK_THIS_STATE));
FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_ERR_DISK_TOOOLD), _T(APP_TITLE));
} else {
if (nRet == 5) {
FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_DISK_THIS_STATE));
FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_ERR_DISK_TOONEW), _T(APP_TITLE));
} else {
if (nRet && !nSlot) {
FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_ERR_DISK_LOAD));
FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_DISK_STATE));
}
}
}
}
if (nRet) {
FBAPopupDisplay(PUF_TYPE_ERROR);
}
return nRet;
}
int StatedSave(int nSlot)
{
TCHAR szFilter[1024];
int nRet;
int bOldPause;
if (bDrvOkay == 0) {
return 1;
}
if (nSlot) {
CreateStateName(nSlot);
} else {
_stprintf(szChoice, _T("%s"), BurnDrvGetText(DRV_NAME));
StateMakeOfn(szFilter);
ofn.lpstrTitle = FBALoadStringEx(IDS_STATE_SAVE);
ofn.Flags |= OFN_OVERWRITEPROMPT;
bOldPause = bRunPause;
bRunPause = 1;
nRet = GetSaveFileName(&ofn);
bRunPause = bOldPause;
if (nRet == 0) { // Error
VidSNewShortMsg(FBALoadStringEx(IDS_STATE_SAVE_ERROR), 0xFF3F3F);
return 1;
}
}
nRet = BurnStateSave(szChoice, 1);
if (nRet && !nSlot) {
FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_ERR_DISK_CREATE));
FBAPopupAddText(PUF_TEXT_DEFAULT, MAKEINTRESOURCE(IDS_DISK_STATE));
FBAPopupDisplay(PUF_TYPE_ERROR);
}
VidSNewShortMsg(FBALoadStringEx(IDS_STATE_SAVED));
return nRet;
}
| [
"[email protected]"
] | [
[
[
1,
173
]
]
] |
614ccac332dcd77fcb4e71f26723dea35f1726d4 | 3857c09b3f7eeaa8dfc7fe89af389309290ba036 | /scalewidget.cpp | df6edefb719ef58e6da7ed32463bbe9a287fd96f | [] | no_license | aloschilov/Test-Project | b4644ed6f5ef2c7f315579eef8727351be439443 | feb48a72065b30c0788f59d506f3ae00ba7fbc30 | refs/heads/master | 2020-04-29T21:19:22.569644 | 2011-09-02T23:09:35 | 2011-09-02T23:09:35 | 2,173,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | cpp | #include <QtGui>
#include "scale.h"
#include "scalewidget.h"
ScaleWidget::ScaleWidget(QWidget *parent)
: QWidget(parent)
{
scale=0;
}
void ScaleWidget::paintEvent(QPaintEvent * /*event*/)
{
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
p.setRenderHint(QPainter::SmoothPixmapTransform);
if(scale)
{
double maxValue = scale->getMaxValue();
double minValue = scale->getMinValue();
double step = (maxValue - minValue)/double(rect().height());
int height = rect().height();
double curValue;
for(int i=0;i<height;++i)
{
curValue=maxValue - double(i)*step;
p.setPen(QColor(QColor::fromRgb(scale->getColor(curValue))));
p.drawLine(0,i,rect().width(),i);
}
}
}
void ScaleWidget::changeScale(Scale *newScale)
{
scale=newScale;
update();
}
| [
"[email protected]"
] | [
[
[
1,
39
]
]
] |
5b9561773b3af53452ad886d96527f3b3b71d9bc | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvmesh/TriMesh.cpp | 3e82b672e40752c3c9f2311b9b29f8881445dced | [] | no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 647 | cpp | // This code is in the public domain -- [email protected]
#include "TriMesh.h"
using namespace nv;
/// Triangle mesh.
Vector3 TriMesh::faceNormal(uint f) const
{
const Face & face = this->faceAt(f);
const Vector3 & p0 = this->vertexAt(face.v[0]).pos;
const Vector3 & p1 = this->vertexAt(face.v[1]).pos;
const Vector3 & p2 = this->vertexAt(face.v[2]).pos;
return normalizeSafe(cross(p1 - p0, p2 - p0), Vector3(zero), 0.0f);
}
/// Get face vertex.
const TriMesh::Vertex & TriMesh::faceVertex(uint f, uint v) const
{
nvDebugCheck(v < 3);
const Face & face = this->faceAt(f);
return this->vertexAt(face.v[v]);
}
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
] | [
[
[
1,
25
]
]
] |
5256bbf58045a6857a046e5ca2620a823e496bcf | 885fc5f6e056abe95996b4fc6eebef06a94d50ce | /include/EncodeProfile.h | a1ee7c8d355d39836a5e71a5e23ff2afcb1ad0db | [] | no_license | jdzyzh/ffmpeg-wrapper | bdf0a6f15db2625b2707cbac57d5bfaca6396e3d | 5185bb3695df9adda59f7f849095314f16b2bd48 | refs/heads/master | 2021-01-10T08:58:06.519741 | 2011-11-30T06:32:50 | 2011-11-30T06:32:50 | 54,611,386 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 794 | h | #ifndef ENCODE_PROFILE_H
#define ENCODE_PROFILE_H
#include <vector>
#include <string>
/*
input_file=abc.wmv
input_file=123.wmv
output_file=output.wmv
ffmpeg_param=-i xxx -acodec wmav2 -vcodec msmpeg4 -ss 30 -y xxx.wmv
ffmpeg_param=-i xxx -acodec wmav2 -vcodec msmpeg4 -ss 30 -y xxx.wmv
*/
using namespace std;
class EncodeProfile
{
protected:
EncodeProfile();
public:
static EncodeProfile* parse(char *filename);
~EncodeProfile();
public:
void addInputFile(char *file);
void setOutputFile(char *file);
void setFFMpegParam(char *param);
int getFFMpegEncodeIterations();
char* getFFMpegEncodeParam(int idx);
char* getOutputFile();
protected:
vector<string> inputFiles;
string outputFile;
vector<string> ffmpegParams;
};
#endif //ENCODE_PROFILE_H | [
"ransomhmc@6544afd8-f103-2cf2-cfd9-24e348754d5f"
] | [
[
[
1,
36
]
]
] |
d8d6cc062543789e71127e12d904dd97dac04692 | a3de460e3b893849fb01b4c31bd30a908160a1f8 | /nil/ini.hpp | 109ab5301daeaa334391f95da3fc817a10c08c5a | [] | no_license | encratite/nil | 32b3d0d31124dd43469c07df2552f1c3510df36d | b441aba562d87f9c14bfce9291015b7622a064c6 | refs/heads/master | 2022-06-19T18:59:06.212567 | 2008-12-23T05:58:00 | 2008-12-23T05:58:00 | 262,275,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,160 | hpp | #ifndef NIL_INI_HPP
#define NIL_INI_HPP
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <nil/file.hpp>
#include <nil/string.hpp>
#include <nil/exception.hpp>
namespace nil
{
class ini
{
public:
ini();
ini(std::string const & file_name);
bool load(std::string const & new_file_name);
std::string string(std::string const & variable_name);
std::string string(std::string const & variable_name, std::string const & default_value);
template <typename number_type>
bool read_number(std::string const & variable_name, number_type & output)
{
std::map<std::string, std::string>::iterator search = values.find(variable_name);
if(search == values.end())
{
return false;
}
try
{
output = string::string_to_number<number_type>(search->second);
}
catch(std::exception const &)
{
std::cout << "Unable to find string value \"" << variable_name << "\" in \"" << file_name << "\"" << std::endl;
throw exception("Failed to parse numeric value for a variable");
}
return true;
}
template <typename number_type>
number_type number(std::string const & variable_name)
{
number_type output;
bool success = read_number<number_type>(variable_name, output);
if(success == false)
{
std::cout << "Unable to find string value \"" << variable_name << "\" in \"" << file_name << "\"" << std::endl;
throw exception("Missing value for a required variable");
}
return output;
}
template <typename number_type>
number_type number(std::string const & variable_name, number_type default_value)
{
number_type output;
bool success;
try
{
success = read_number<number_type>(variable_name, output);
}
catch(std::exception const &)
{
return default_value;
}
if(success == false)
{
return default_value;
}
return output;
}
private:
bool read_string(std::string const & variable_name, std::string & output);
std::string file_name;
std::map<std::string, std::string> values;
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
95
]
]
] |
c06c69cef9e0e60335921f32016f951743a6fe86 | 305f56324b8c1625a5f3ba7966d1ce6c540e9d97 | /src/Oracle/Oci7.cpp | f5a09917a43903cca22a93e1f031b33efff45b17 | [
"BSD-2-Clause"
] | permissive | radtek/lister | be45f7ac67da72c1c2ac0d7cd878032c9648af7b | 71418c72b31823624f545ad86cc804c43b6e9426 | refs/heads/master | 2021-01-01T19:56:30.878680 | 2011-06-22T17:04:13 | 2011-06-22T17:04:13 | 41,946,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,023 | cpp | #include "Oracle7.h"
#include "OciCommon.h"
#pragma hdrstop
/*
extern "C" {
#define dword _dword
typedef byte text;
#include <oratypes.h>
#include <ocidfn.h>
#include <ocidem.h>
#include <ociapr.h>
#undef dword
};
*/
NAMESPACE_UPP
#define DLLFILENAME "ociw32.dll"
#define DLIMODULE OCI7
#define DLIHEADER <Oracle/Oci7.dli>
//C:\FreeBase\Oracle\Client\instantclientwin3211.2.0.1\instantclient_11_2
//C:\Program Files\Oracle\product\10.2.0\client_1\bin
#include <Core/dli_source.h>
void OCI7SetDllPath(String oci7_path, T_OCI7& oci7)
{
static String dflt_name;
if(IsNull(dflt_name))
dflt_name = oci7.GetLibName();
if(oci7_path != oci7.GetLibName())
oci7.SetLibName(Nvl(oci7_path, dflt_name));
}
class OCI7Connection : public Link<OCI7Connection>, public OciSqlConnection {
protected:
virtual void SetParam(int i, OracleRef r);
virtual void SetParam(int i, const Value& r);
virtual bool Execute();
virtual int GetRowsProcessed() const;
virtual bool Fetch();
virtual void GetColumn(int i, Ref f) const;
virtual void Cancel();
virtual SqlSession& GetSession() const;
virtual String GetUser() const;
virtual String ToString() const;
virtual ~OCI7Connection();
protected:
/*
enum {
O_VARCHAR2 = 1,
O_NUMBER = 2,
O_LONG = 8,
O_ROWID = 11,
O_DATE = 12,
O_RAW = 23,
O_LONGRAW = 24,
O_CHAR = 96,
O_MLSLABEL = 105,
};
*/
struct Param {
int16 type;
word len;
sb2 ind;
// Vector<Value> dynamic;
// bool is_dynamic;
/// bool dyna_full;
// int dyna_vtype;
// int dyna_width;
OCI7Connection *refcursor;
union {
byte *ptr;
byte buffer[8];
};
byte *Data() { return len > 8u ? ptr : buffer; }
const byte *Data() const { return len > 8u ? ptr : buffer; }
bool IsNull() const { return ind < 0; }
void Free();
// void DynaFlush();
Param() { len = 0; refcursor = 0; }
~Param() { Free(); }
};
struct Column {
int type;
int len;
byte *data;
sb2 *ind;
ub2 *rl;
ub2 *rc;
bool lob;
Column() { data = NULL; }
~Column();
};
mutable cda_def cda;
Array<Param> param;
Array<Column> column;
String longparam;
int frows;
unsigned fetched;
int fetchtime;
int fi;
bool eof;
// Vector<int> dynamic_param;
// int dynamic_pos;
// int dynamic_rows;
T_OCI7& oci7;
Oracle7 *session;
Param& PrepareParam(int i, int type, int len, int reserve /*, int dynamic_vtype*/);
void SetParam(int i, const String& s);
void SetRawParam(int i, const String& s);
void SetParam(int i, int integer);
void SetParam(int i, double d);
void SetParam(int i, Date d);
void SetParam(int i, Time d);
void SetParam(int i, Sql& cursor);
void AddColumn(int type, int len, bool lob = false);
void GetColumn(int i, String& s) const;
void GetColumn(int i, int& n) const;
void GetColumn(int i, double& d) const;
void GetColumn(int i, Date& d) const;
void GetColumn(int i, Time& t) const;
void SetError();
bool GetColumnInfo();
void Clear();
OCI7Connection(Oracle7& s);
friend class Oracle7;
};
//template MoveType<OCI7Connection::Param>;
//template MoveType<OCI7Connection::Column>;
void OCI7Connection::Param::Free() {
if(len != (word)-1 && len > sizeof(buffer))
delete[] ptr;
len = 0;
}
/*
void OCI7Connection::Param::DynaFlush() {
Value v;
if(ind == 0) {
const byte *p = Data();
switch(type) {
case SQLT_INT:
v = *(const int *)p;
break;
case SQLT_FLT:
v = *(const double *)p;
break;
case SQLT_STR:
v = String((const char *)p);
break;
case SQLT_DAT:
v = OciDecodeTime(p);
break;
case SQLT_CLOB:
case SQLT_BLOB:
default:
NEVER();
break;
}
}
dynamic.Add(v);
}
*/
OCI7Connection::Column::~Column() {
if(data) {
delete[] data;
delete[] ind;
delete[] rl;
delete[] rc;
}
}
OCI7Connection::Param& OCI7Connection::PrepareParam(int i, int type, int len, int reserve /*, int dvtype*/) {
Param& p = param.At(i);
// p.dyna_vtype = dvtype;
// p.is_dynamic = (dvtype != VOID_V);
/// p.dyna_full = false;
// p.dyna_width = len;
p.ind = 0;
if(p.type != type || p.len < len || reserve == 0 && p.len != len) {
p.Free();
parse = true;
}
if(!p.len) {
p.len = len + reserve;
if(p.len > 8)
p.ptr = new byte[p.len];
p.type = -1;
parse = true;
}
if(p.type != type) {
p.type = type;
parse = true;
}
return p;
}
void OCI7Connection::SetParam(int i, const String& s) {
int l = s.GetLength();
Param& p = PrepareParam(i, SQLT_STR, l + 1, 256 /*, VOID_V*/);
memcpy(p.Data(), s, l + 1);
p.ind = l ? 0 : -1;
}
void OCI7Connection::SetRawParam(int i, const String& s) {
PrepareParam(i, SQLT_LBI, 0, 0 /*, VOID_V*/);
longparam = s;
}
void OCI7Connection::SetParam(int i, int integer) {
Param& p = PrepareParam(i, SQLT_INT, sizeof(int), 0 /*, VOID_V*/);
*(int *) p.Data() = integer;
p.ind = IsNull(integer) ? -1 : 0;
}
void OCI7Connection::SetParam(int i, double d) {
Param& p = PrepareParam(i, SQLT_FLT, sizeof(double), 0 /*, VOID_V*/);
*(double *) p.Data() = d;
p.ind = IsNull(d) ? -1 : 0;
}
void OCI7Connection::SetParam(int i, Date d) {
Param& w = PrepareParam(i, SQLT_DAT, 7, 0 /*, VOID_V*/);
w.ind = OciEncodeDate(w.Data(), d) ? 0 : -1;
}
void OCI7Connection::SetParam(int i, Time t) {
Param& w = PrepareParam(i, SQLT_DAT, 7, 0 /*, VOID_V*/);
w.ind = OciEncodeTime(w.Data(), t) ? 0 : -1;
}
void OCI7Connection::SetParam(int i, OracleRef r) {
NEVER(); // OCI7 dynamic's are currently not allowed
// PrepareParam(i, r.GetOraType(), r.GetMaxLen(), 0, r.GetType());
}
class Oracle7RefCursorStub : public SqlSource {
public:
Oracle7RefCursorStub(SqlConnection *cn) : cn(cn) {}
virtual SqlConnection *CreateConnection() { return cn; }
private:
SqlConnection *cn;
};
void OCI7Connection::SetParam(int i, Sql& cursor) {
Param& w = PrepareParam(i, SQLT_CUR, -1, 0 /*, VOID_V*/);
w.refcursor = new OCI7Connection(*session);
Oracle7RefCursorStub stub(w.refcursor);
w.ptr = (byte *)&w.refcursor -> cda;
w.ind = 0;
}
void OCI7Connection::SetParam(int i, const Value& q) {
if(q.IsNull())
SetParam(i, String(""));
else
switch(q.GetType()) {
case 34:
SetRawParam(i, SqlRaw(q));
break;
case STRING_V:
case WSTRING_V:
SetParam(i, String(q));
break;
case BOOL_V:
case INT_V:
SetParam(i, int(q));
break;
case INT64_V:
case DOUBLE_V:
SetParam(i, double(q));
break;
case DATE_V:
SetParam(i, Date(q));
break;
case TIME_V:
SetParam(i, (Time)q);
break;
default:
if(IsTypeRaw<Sql *>(q)) {
SetParam(i, *ValueTo<Sql *>(q));
break;
}
NEVER();
}
}
void OCI7Connection::AddColumn(int type, int len, bool lob) {
Column& q = column.Add();
q.type = type;
q.len = len;
q.data = new byte[frows * len];
q.ind = new sb2[frows];
q.rl = new ub2[frows];
q.rc = new ub2[frows];
q.lob = lob;
}
bool OCI7Connection::Execute() {
int time = msecs();
session->PreExec();
int args = 0;
if(parse) {
String cmd;
args = OciParse(statement, cmd, this, session);
Cancel();
if(oci7.oparse(&cda, (OraText *)(const char *)cmd, -1, 0, 2) != 0) {
SetError();
return false;
}
while(param.GetCount() < args)
SetParam(param.GetCount(), String());
param.Trim(args);
// dynamic_param.Clear();
for(int i = 0; i < args; i++) {
Param& p = param[i];
if(p.type == SQLT_LBI) {
String h = Format(":%d", i + 1);
if(oci7.obindps(&cda, 0, (byte *)~h, h.GetLength(), NULL,
max(1, longparam.GetLength()), p.type,
0, NULL, NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, 0, 0)) {
SetError();
return false;
}
}
else
if(oci7.obndrn(&cda, i + 1, (OraText *)p.Data(), p.len, p.type,
-1, &p.ind, NULL, -1, -1) != 0) {
SetError();
return false;
}
// if(p.is_dynamic)
// dynamic_param.Add(i);
}
}
for(;;) {
// dword time;
// if(session->IsTraceTime())
// time = GetTickCount();
oci7.oexec(&cda);
// if(session->IsTraceTime() && session->GetTrace())
// *session->GetTrace() << Sprintf("--------------\nexec %d ms:\n", GetTickCount() - time);
if(cda.rc == 0)
break;
if(cda.rc != 3129) {
SetError();
longparam.Clear();
return false;
}
ub4 l = longparam.GetLength();
oci7.osetpi(&cda, OCI_LAST_PIECE, (void *)~longparam, &l);
}
// if(!dynamic_param.IsEmpty()) {
// dynamic_pos = -1;
// for(int i = 0; i < dynamic_param.GetCount(); i++)
// param[dynamic_param[i]].DynaFlush();
// dynamic_rows = param[dynamic_param[0]].dynamic.GetCount();
// }
if(parse) {
if(!GetColumnInfo())
return false;
for(int i = 0; i < args; i++)
if(param[i].refcursor && !param[i].refcursor -> GetColumnInfo())
return false;
}
else {
fetched = 0;
fetchtime = 0;
fi = -1;
eof = false;
}
longparam.Clear();
session->PostExec();
if(Stream *s = session->GetTrace()) {
if(session->IsTraceTime())
*s << Format("----- exec %d ms\n", msecs(time));
}
return true;
}
bool OCI7Connection::GetColumnInfo()
{
fetched = 0;
fetchtime = 0;
fi = -1;
eof = false;
info.Clear();
column.Clear();
frows = fetchrows;
Vector<int> tp;
int i;
for(i = 0;; i++) {
char h[256];
sb4 width;
sb2 type, prec, scale, null;
sb4 hlen = 255;
if(oci7.odescr((cda_def *)&cda, i + 1, &width, &type, (sb1 *)h, &hlen, NULL, &prec,
&scale, &null))
break;
SqlColumnInfo& ii = info.Add();
ii.width = width;
ii.precision = prec;
ii.scale = scale;
h[hlen] = '\0';
ii.name = h;
ii.name = ToUpper(TrimRight(ii.name));
tp.Add(type);
if(type == SQLT_LBI || type == SQLT_BLOB || type == SQLT_CLOB)
frows = 1;
}
for(i = 0; i < info.GetCount(); i++) {
SqlColumnInfo& ii = info[i];
switch(tp[i]) {
case SQLT_NUM:
ii.valuetype = DOUBLE_V;
AddColumn(SQLT_FLT, sizeof(double));
break;
case SQLT_DAT:
ii.valuetype = TIME_V;
AddColumn(SQLT_DAT, 7);
break;
case SQLT_LBI:
ii.valuetype = STRING_V;
AddColumn(SQLT_LBI, 4096);
break;
case SQLT_CLOB:
ii.valuetype = STRING_V;
AddColumn(SQLT_LNG, 65520, true);
break;
case SQLT_BLOB:
ii.valuetype = STRING_V;
AddColumn(SQLT_LBI, 65520, true);
break;
default:
ii.valuetype = STRING_V;
AddColumn(SQLT_STR, ii.width ? ii.width + 1 : longsize);
break;
}
}
for(i = 0; i < column.GetCount(); i++) {
Column& q = column[i];
if(oci7.odefin(&cda, i + 1, (OraText *)q.data, q.len, q.type, -1, q.ind, NULL, -1, -1, q.rl, q.rc)) {
SetError();
return false;
}
}
parse = false;
return true;
}
int OCI7Connection::GetRowsProcessed() const {
return cda.rpc;
}
bool OCI7Connection::Fetch() {
ASSERT(!parse);
if(parse || eof) return false;
// if(!dynamic_param.IsEmpty()) // dynamic pseudo-fetch
// return (dynamic_pos < dynamic_rows && ++dynamic_pos < dynamic_rows);
if(frows == 1) {
fi = 0;
if(oci7.ofetch(&cda)) {
if(cda.rc != 1403)
SetError();
return false;
}
fetched++;
return true;
}
if(fi < 0 || fetched >= cda.rpc) {
bool tt = session->IsTraceTime();
int fstart = tt ? msecs() : 0;
if(oci7.ofen(&cda, frows) && cda.rc != 1403) {
eof = true;
SetError();
return false;
}
if(tt) {
fetchtime += msecs(fstart);
int added = fetched + cda.rpc;
if(Stream *s = session->GetTrace())
*s << NFormat("----- fetch(%d) in %d ms, %8n ms/rec, %2n rec/s\n",
added, fetchtime,
fetchtime / max<double>(added, 1),
added * 1000.0 / max<double>(fetchtime, 1));
}
if(fetched >= cda.rpc) {
eof = true;
return false;
}
fi = 0;
}
else
fi++;
fetched++;
return true;
}
void OCI7Connection::GetColumn(int i, String& s) const
{
// if(!dynamic_param.IsEmpty()) {
// s = param[dynamic_param[i]].dynamic[dynamic_pos];
// return;
// }
const Column& c = column[i];
const byte *data = c.data + fi * c.len;
int ind = c.ind[fi];
if(c.type == SQLT_STR)
if(ind < 0)
s = Null;
else
s = (const char *) data;
else if(c.type == SQLT_LBI || c.type == SQLT_LNG) {
if(ind == -1)
s = Null;
else {
s = String(data, *c.rl);
if(!c.lob) {
Buffer<byte> buffer(32768);
ub4 len;
while(!oci7.oflng(&cda, i + 1, buffer, 32768, c.type, &len, s.GetLength()) && len)
s.Cat(buffer, len);
if(s.GetAlloc() - s.GetLength() > 32768)
s.Shrink();
}
}
}
else
NEVER();
}
void OCI7Connection::GetColumn(int i, int& n) const {
// if(!dynamic_param.IsEmpty()) {
// n = param[dynamic_param[i]].dynamic[dynamic_pos];
// return;
// }
const Column& c = column[i];
byte *data = c.data + fi * c.len;
if(c.ind[fi] < 0)
n = INT_NULL;
else
switch(c.type) {
case SQLT_INT:
n = *(int *) data;
break;
case SQLT_FLT:
n = int(*(double *) data);
break;
default:
ASSERT(0);
}
}
void OCI7Connection::GetColumn(int i, double& d) const {
// if(!dynamic_param.IsEmpty()) {
// d = param[dynamic_param[i]].dynamic[dynamic_pos];
// return;
// }
const Column& c = column[i];
byte *data = c.data + fi * c.len;
if(c.ind[fi] < 0)
d = Null;
else
switch(c.type) {
case SQLT_INT:
d = *(int *) data;
break;
case SQLT_FLT:
d = *(double *) data;
break;
default:
ASSERT(0);
}
}
void OCI7Connection::GetColumn(int i, Date& d) const {
// if(!dynamic_param.IsEmpty()) {
// d = param[dynamic_param[i]].dynamic[dynamic_pos];
// return;
// }
const Column& c = column[i];
const byte *data = c.data + fi * c.len;
ASSERT(c.type == SQLT_DAT);
d = (c.ind[fi] < 0 ? Date(Null) : OciDecodeDate(data));
}
void OCI7Connection::GetColumn(int i, Time& t) const {
// if(!dynamic_param.IsEmpty()) {
// t = param[dynamic_param[i]].dynamic[dynamic_pos];
// return;
// }
const Column& c = column[i];
const byte *data = c.data + fi * c.len;
ASSERT(c.type == SQLT_DAT);
t = (c.ind[fi] < 0 ? Time(Null) : OciDecodeTime(data));
}
void OCI7Connection::GetColumn(int i, Ref f) const {
// if(!dynamic_param.IsEmpty()) {
// f.SetValue(param[dynamic_param[i]].dynamic[dynamic_pos]);
// return;
// }
switch(f.GetType()) {
case STRING_V: {
String s;
GetColumn(i, s);
f.SetValue(s);
break;
}
case INT_V: {
int d;
GetColumn(i, d);
f.SetValue(d);
break;
}
case DOUBLE_V: {
double d;
GetColumn(i, d);
f.SetValue(d);
break;
}
case DATE_V: {
Date d;
GetColumn(i, d);
f.SetValue(d);
break;
}
case TIME_V: {
Time d;
GetColumn(i, d);
f.SetValue(d);
break;
}
case VALUE_V: {
switch(column[i].type) {
case SQLT_STR:
case SQLT_LBI:
case SQLT_LNG: {
String s;
GetColumn(i, s);
f = Value(s);
break;
}
case SQLT_INT: {
int n;
GetColumn(i, n);
f = Value(n);
break;
}
case SQLT_FLT: {
double d;
GetColumn(i, d);
f = Value(d);
break;
}
case SQLT_DAT: {
Time m;
GetColumn(i, m);
if(m.hour || m.minute || m.second)
f = Value(m);
else
f = Value(Date(m));
break;
}
default: {
NEVER();
}
}
break;
}
default: {
NEVER();
}
}
}
void OCI7Connection::Cancel() {
oci7.ocan(&cda);
parse = true;
}
void OCI7Connection::SetError() {
int code = cda.rc;
if(code == 0 || code == 1002) return;
session->SetError(session->GetErrorMsg(code), ToString());
parse = true;
}
SqlSession& OCI7Connection::GetSession() const {
ASSERT(session);
return *session;
}
String OCI7Connection::GetUser() const {
ASSERT(session);
return session->user;
}
String OCI7Connection::ToString() const
{
String lg;
bool quotes = false;
int argn = 0;
for(const char *q = statement; *q; q++) {
if(*q== '\'' && q[1] != '\'')
quotes = !quotes;
if(!quotes && *q == '?') {
if(argn < param.GetCount()) {
const Param& m = param[argn++];
if(m.type == SQLT_LBI)
lg.Cat("<Raw data>");
else
if(m.IsNull())
lg << "Null";
else
switch(m.type) {
case SQLT_STR:
lg.Cat('\'');
lg += (const char *) m.Data();
lg.Cat('\'');
break;
case SQLT_INT:
lg << *(const int *) m.Data();
break;
case SQLT_FLT:
lg << *(const double *) m.Data();
break;
case SQLT_DAT:
// const byte *data = m.Data();
lg << OciDecodeTime(m.Data());
//(int)data[3] << '.' << (int)data[2] << '.' <<
// int(data[0] - 100) * 100 + data[1] - 100;
break;
}
}
else
lg += "<not supplied>";
}
else
lg += *q;
}
return lg;
}
OCI7Connection::OCI7Connection(Oracle7& s) : session(&s), oci7(s.oci7) {
eof = true;
memset(&cda, 0, sizeof(cda));
CHECK(!oci7.oopen(&cda, (cda_def *) (session->lda), 0, -1, -1, 0, -1));
LinkAfter(&s.clink);
}
void OCI7Connection::Clear() {
if(session) {
oci7.oclose(&cda);
session = NULL;
}
}
OCI7Connection::~OCI7Connection() {
Clear();
}
bool Oracle7::Open(const String& connect) {
Close();
::memset(lda, 0, sizeof(lda));
::memset(hda, 0, sizeof(hda));
if(!oci7.Load()) {
SetError(t_("Error loading OCI7 Oracle database client library."), t_("Connecting to server"));
return false;
}
int code = oci7.olog((cda_def *)lda, hda, (OraText *)(const char *)connect, -1,
NULL, -1, NULL, -1, OCI_LM_DEF);
if(code) {
SetError(GetErrorMsg(code), t_("Connecting to database server"));
return false;
}
connected = true;
level = 0;
ClearError();
user = Sql(*this).Select("USER from DUAL");
return true;
}
String Oracle7::GetErrorMsg(int code) const {
byte h[520];
*h = 0;
String r;
oci7.oerhms((cda_def *)lda, (sb2)code, (OraText *)h, 512);
for(byte *s = h; *s; s++)
r.Cat(*s < ' ' ? ' ' : *s);
r << "(code " << code << ")";
return r;
}
SqlConnection *Oracle7::CreateConnection() {
return new OCI7Connection(*this);
}
void Oracle7::Close() {
while(!clink.IsEmpty()) {
clink.GetNext()->Clear();
clink.GetNext()->Unlink();
}
if(connected) {
oci7.ologof((cda_def *)lda);
connected = false;
}
}
String Oracle7::Spn() {
return Format("TRANSACTION_LEVEL_%d", level);
}
void Oracle7::PreExec() {
bool ac = level == 0 && tmode == NORMAL;
if(autocommit != ac) {
autocommit = ac;
Stream *s = GetTrace();
if(autocommit) {
if(s) *s << "%autocommit on;\n";
oci7.ocon((cda_def *)lda);
}
else {
if(s) *s << "%autocommit off;\n";
oci7.ocof((cda_def *)lda);
}
}
}
void Oracle7::PostExec() {
}
void Oracle7::Begin() {
if(Stream *s = GetTrace())
*s << user << "(OCI7) -> StartTransaction(level " << level << ")\n";
level++;
// ClearError();
if(level > 1)
Sql(*this).Execute("savepoint " + Spn());
}
void Oracle7::Commit() {
int time = msecs();
// ASSERT(tmode == ORACLE || level > 0);
if(level)
level--;
// else
// ClearError();
if(level == 0) {
oci7.ocom((cda_def *)lda);
// if(Stream *s = GetTrace())
// *s << "%commit;\n";
}
if(Stream *s = GetTrace())
*s << NFormat("----- %s (OCI7) -> Commit(level %d) %d ms\n", user, level, msecs(time));
}
void Oracle7::Rollback() {
ASSERT(tmode == ORACLE || level > 0);
if(level > 1)
Sql(*this).Execute("rollback to savepoint " + Spn());
else {
oci7.orol((cda_def *)lda);
if(Stream *s = GetTrace())
*s << "%rollback;\n";
}
if(level)
level--;
// else
// ClearError();
if(Stream *s = GetTrace())
*s << user << "(OCI7) -> Rollback(level " << level << ")\n";
}
String Oracle7::Savepoint() {
static dword i;
i = (i + 1) & 0x8fffffff;
String s = Sprintf("SESSION_SAVEPOINT_%d", i);
Sql(*this).Execute("savepoint " + s);
return s;
}
void Oracle7::RollbackTo(const String& savepoint) {
Sql(*this).Execute("rollback to savepoint " + savepoint);
}
bool Oracle7::IsOpen() const {
return connected;
}
Oracle7::Oracle7(T_OCI7& oci7_)
: oci7(oci7_)
{
connected = false;
autocommit = false;
level = 0;
tmode = NORMAL;
Dialect(ORACLE);
}
Oracle7::~Oracle7() {
// ASSERT(level == 0);
Close();
}
Vector<String> Oracle7::EnumUsers()
{
Sql cursor(*this);
return OracleSchemaUsers(cursor);
}
Vector<String> Oracle7::EnumDatabases()
{
Sql cursor(*this);
return OracleSchemaUsers(cursor);
}
Vector<String> Oracle7::EnumTables(String database)
{
Sql cursor(*this);
return OracleSchemaTables(cursor, database);
}
Vector<String> Oracle7::EnumViews(String database)
{
Sql cursor(*this);
return OracleSchemaViews(cursor, database);
}
Vector<String> Oracle7::EnumSequences(String database)
{
Sql cursor(*this);
return OracleSchemaSequences(cursor, database);
}
Vector<String> Oracle7::EnumPrimaryKey(String database, String table)
{
Sql cursor(*this);
return OracleSchemaPrimaryKey(cursor, database, table);
}
String Oracle7::EnumRowID(String database, String table)
{
Sql cursor(*this);
return OracleSchemaRowID(cursor, database, table);
}
Vector<String> Oracle7::EnumReservedWords()
{
return OracleSchemaReservedWords();
}
END_UPP_NAMESPACE
| [
"jeffshumphreys@97668ed5-8355-0e3d-284e-ab2976d7b0b4"
] | [
[
[
1,
982
]
]
] |
4b50488a118f0644e82223e1249236896247d1a3 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ogre/OgreNewt/boost/mpl/aux_/pop_back_impl.hpp | b23b36e5d0a92ca3264482a118fb7aaa5fde9099 | [] | 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 | 959 | hpp |
#ifndef BOOST_MPL_AUX_POP_BACK_IMPL_HPP_INCLUDED
#define BOOST_MPL_AUX_POP_BACK_IMPL_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/aux_/pop_back_impl.hpp,v $
// $Date: 2006/04/17 23:47:07 $
// $Revision: 1.1 $
#include <boost/mpl/pop_back_fwd.hpp>
#include <boost/mpl/aux_/traits_lambda_spec.hpp>
namespace boost { namespace mpl {
// no default implementation; the definition is needed to make MSVC happy
template< typename Tag >
struct pop_back_impl
{
template< typename Sequence > struct apply;
};
BOOST_MPL_ALGORITM_TRAITS_LAMBDA_SPEC(1, pop_back_impl)
}}
#endif // BOOST_MPL_AUX_POP_BACK_IMPL_HPP_INCLUDED
| [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
] | [
[
[
1,
34
]
]
] |
fb5c34973599f6f34a00b0153ee35265d130eb42 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/validators/common/SimpleContentModel.hpp | 17d336daf71de6cc1f7c50906404c266edaf1fdc | [] | no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,589 | hpp | /*
* Copyright 1999-2001,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: SimpleContentModel.hpp 191054 2005-06-17 02:56:35Z jberry $
*/
#if !defined(SIMPLECONTENTMODEL_HPP)
#define SIMPLECONTENTMODEL_HPP
#include <xercesc/framework/XMLContentModel.hpp>
#include <xercesc/validators/common/ContentSpecNode.hpp>
XERCES_CPP_NAMESPACE_BEGIN
//
// SimpleContentModel is a derivative of the abstract content model base
// class that handles a small set of simple content models that are just
// way overkill to give the DFA treatment.
//
// DESCRIPTION:
//
// This guy handles the following scenarios:
//
// a
// a?
// a*
// a+
// a,b
// a|b
//
// These all involve a unary operation with one element type, or a binary
// operation with two elements. These are very simple and can be checked
// in a simple way without a DFA and without the overhead of setting up a
// DFA for such a simple check.
//
// NOTE: Pass the XMLElementDecl::fgPCDataElemId value to represent a
// PCData node. Pass XMLElementDecl::fgInvalidElemId for unused element
//
class SimpleContentModel : public XMLContentModel
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
SimpleContentModel
(
const bool dtd
, QName* const firstChild
, QName* const secondChild
, const ContentSpecNode::NodeTypes cmOp
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
~SimpleContentModel();
// -----------------------------------------------------------------------
// Implementation of the ContentModel virtual interface
// -----------------------------------------------------------------------
virtual int validateContent
(
QName** const children
, const unsigned int childCount
, const unsigned int emptyNamespaceId
) const;
virtual int validateContentSpecial
(
QName** const children
, const unsigned int childCount
, const unsigned int emptyNamespaceId
, GrammarResolver* const pGrammarResolver
, XMLStringPool* const pStringPool
) const;
virtual ContentLeafNameTypeVector *getContentLeafNameTypeVector() const;
virtual unsigned int getNextState(const unsigned int currentState,
const unsigned int elementIndex) const;
virtual void checkUniqueParticleAttribution
(
SchemaGrammar* const pGrammar
, GrammarResolver* const pGrammarResolver
, XMLStringPool* const pStringPool
, XMLValidator* const pValidator
, unsigned int* const pContentSpecOrgURI
, const XMLCh* pComplexTypeName = 0
) ;
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
SimpleContentModel();
SimpleContentModel(const SimpleContentModel&);
SimpleContentModel& operator=(const SimpleContentModel&);
// -----------------------------------------------------------------------
// Private data members
//
// fFirstChild
// fSecondChild
// The first (and optional second) child node. The
// operation code tells us whether the second child is used or not.
//
// fOp
// The operation that this object represents. Since this class only
// does simple contents, there is only ever a single operation
// involved (i.e. the children of the operation are always one or
// two leafs.)
//
// fDTD
// Boolean to allow DTDs to validate even with namespace support. */
//
// -----------------------------------------------------------------------
QName* fFirstChild;
QName* fSecondChild;
ContentSpecNode::NodeTypes fOp;
bool fDTD;
MemoryManager* const fMemoryManager;
};
// ---------------------------------------------------------------------------
// SimpleContentModel: Constructors and Destructor
// ---------------------------------------------------------------------------
inline SimpleContentModel::SimpleContentModel
(
const bool dtd
, QName* const firstChild
, QName* const secondChild
, const ContentSpecNode::NodeTypes cmOp
, MemoryManager* const manager
)
: fFirstChild(0)
, fSecondChild(0)
, fOp(cmOp)
, fDTD(dtd)
, fMemoryManager(manager)
{
if (firstChild)
fFirstChild = new (manager) QName(*firstChild);
else
fFirstChild = new (manager) QName(XMLUni::fgZeroLenString, XMLUni::fgZeroLenString, XMLElementDecl::fgInvalidElemId, manager);
if (secondChild)
fSecondChild = new (manager) QName(*secondChild);
else
fSecondChild = new (manager) QName(XMLUni::fgZeroLenString, XMLUni::fgZeroLenString, XMLElementDecl::fgInvalidElemId, manager);
}
inline SimpleContentModel::~SimpleContentModel()
{
delete fFirstChild;
delete fSecondChild;
}
// ---------------------------------------------------------------------------
// SimpleContentModel: Virtual methods
// ---------------------------------------------------------------------------
inline unsigned int
SimpleContentModel::getNextState(const unsigned int,
const unsigned int) const {
return XMLContentModel::gInvalidTrans;
}
XERCES_CPP_NAMESPACE_END
#endif
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
188
]
]
] |
9eb1605f5381430c9a1b8bf5727a670a134815cc | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/SupportWFLib/symbian/OldSlaveAudio.cpp | d1a22fcbc2595bc7c87dc4444786ad27db866c40 | [
"BSD-3-Clause"
] | permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,269 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// INCLUDE FILES
#include <f32file.h>
#include <e32std.h>
#include <arch.h>
#include "WFSymbianUtil.h"
#include "OldSlaveAudio.h"
#include "AudioClipsEnum.h"
#include "AudioClipTable.h"
#include "SlaveAudioListener.h"
using namespace isab;
#define LOGNEW(x,y)
#define LOGDEL(x)
COldSlaveAudio::COldSlaveAudio( MSlaveAudioListener& listener,
RFs& fileSession )
: m_soundListener( listener ),
m_fileServerSession(fileSession),
iWavPlayer1(NULL),
iWavPlayer2(NULL),
iWavPlayer3(NULL),
iWavPlayer4(NULL),
iWavPlayer5(NULL),
iWavPlayer6(NULL),
iWavPlayer7(NULL),
iWavPlayer8(NULL),
iWavPlayer9(NULL),
iWavPlayer10(NULL),
iWavPlayer11(NULL),
iWavPlayer12(NULL),
iWavPlayer13(NULL),
iWavPlayer14(NULL),
iWavPlayer15(NULL)
{
m_resPath = NULL;
iNbrBytes = 0;
iVolPercent = 90;
iMute = EFalse;
iCurrentPlayer = NULL;
iEndOfTurnPlayer = NULL;
for(TInt i = 0; i < NUM_SOUND_SLOTS; ++i ) {
iSound[i] = 0;
iPreviousSound[i] = 0;
}
iTotalDuration = 0;
iPlayInstruction = EFalse;
}
// ---------------------------------------------------------
// COldSlaveAudio::ConstructL(const TRect& aRect)
// EPOC two phased constructor
// ---------------------------------------------------------
//
void COldSlaveAudio::ConstructL( const TDesC& resourcePath )
{
m_resPath = resourcePath.AllocL();
}
COldSlaveAudio*
COldSlaveAudio::NewLC( MSlaveAudioListener& listener,
RFs& fileServerSession,
const TDesC& resourcePath )
{
COldSlaveAudio* tmp =
new (ELeave)COldSlaveAudio( listener, fileServerSession );
CleanupStack::PushL( tmp );
tmp->ConstructL( resourcePath );
return tmp;
}
COldSlaveAudio*
COldSlaveAudio::NewL( MSlaveAudioListener& listener,
RFs& fileServerSession,
const TDesC& resourcePath )
{
COldSlaveAudio* tmp = COldSlaveAudio::NewLC( listener, fileServerSession,
resourcePath );
CleanupStack::Pop( tmp );
return tmp;
}
// Destructor
COldSlaveAudio::~COldSlaveAudio()
{
delete m_resPath;
DeleteAllPlayers();
}
void COldSlaveAudio::PrepareSound( TInt aNumberSounds, const TInt* aSounds )
{
if( iCurrentPlayer != NULL )
iCurrentPlayer->Stop();
iCurrentPlayer = NULL;
iNbrLoaded = 0;
iTimeingPosition = 0;
iTotalDuration = 0;
iNbrBytes = 0;
iIsEOTurn = EFalse;
TBool done;
TInt i;
//why?
/* TInt sound; */
/* for( i=0; i < aNumberSounds; i++ ){ */
/* sound = aSounds[i]; */
/* } */
//end why
if( aNumberSounds > 0 && aSounds[0] == AudioClipsEnum::SoundNewCrossing ){
iNbrBytes = 1;
iIsEOTurn = ETrue;
if( iEndOfTurnPlayer == NULL ){
iEndOfTurnPlayer = LoadSoundL( AudioClipsEnum::SoundNewCrossing );
iNbrLoaded++;
}
else{
TTimeIntervalMicroSeconds microSeconds = iEndOfTurnPlayer->Duration();
TInt64 duration = microSeconds.Int64()/100000;
TInt32 longDuration = LOW(duration);
m_soundListener.SoundReadyL( KErrNone, longDuration );
}
}
else{
done = EFalse;
i = 0;
while( !done ){
if( i == aNumberSounds || aSounds[i] == AudioClipsEnum::SoundEnd ){
done = ETrue;
}
else if( aSounds[i] == AudioClipsEnum::SoundTimingMarker ){
iTimeingPosition = iNbrBytes;
}
else if( aSounds[i] > 0 ){
iSound[iNbrBytes++] = aSounds[i];
}
i++;
}
CMdaAudioPlayerUtility** player = NULL;
CMdaAudioPlayerUtility* dummyPlayer;
//this loop unrolling is baaaad XXXX
if( iNbrBytes >= 1 ){ //play one snippet or more
if( iPreviousSound[0] != iSound[0] ){ //not the same as last
//find the sound at any other place in previous list
player = CheckPreviousPlayers( iSound[0], iPreviousSound[0], 1 );
if( player == NULL && iWavPlayer1 != NULL ){ //not found
//dont need old player 1
if( CheckPointer( iWavPlayer1, 1 ) ){
//no more pointers to player 1
LOGDEL(iWavPlayer1);
delete iWavPlayer1;
}
//forget player 1, if not deleted there are other pointers.
iWavPlayer1 = NULL;
}
else if( player != NULL ){ //found the player
//switch place with player 1
dummyPlayer = iWavPlayer1;
iWavPlayer1 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[0] = iSound[0]; //remember the sound for next time.
}
if( iNbrBytes >= 2 ){
if( iPreviousSound[1] != iSound[1] ){
player = CheckPreviousPlayers( iSound[1], iPreviousSound[1], 2 );
if( player == NULL && iWavPlayer2 != NULL ){
if( CheckPointer( iWavPlayer2, 2 ) ){
LOGDEL(iWavPlayer2);
delete iWavPlayer2;
}
iWavPlayer2 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer2;
iWavPlayer2 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[1] = iSound[1];
}
if( iNbrBytes >= 3 ){
if( iPreviousSound[2] != iSound[2] ){
player = CheckPreviousPlayers( iSound[2], iPreviousSound[2], 3 );
if( player == NULL && iWavPlayer3 != NULL ){
if( CheckPointer( iWavPlayer3, 3 ) ){
LOGDEL(iWavPlayer3);
delete iWavPlayer3;
}
iWavPlayer3 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer3;
iWavPlayer3 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[2] = iSound[2];
}
if( iNbrBytes >= 4 ){
if( iPreviousSound[3] != iSound[3] ){
player = CheckPreviousPlayers( iSound[3], iPreviousSound[3], 4 );
if( player == NULL && iWavPlayer4 != NULL ){
if( CheckPointer( iWavPlayer4, 4 ) ){
LOGDEL(iWavPlayer4);
delete iWavPlayer4;
}
iWavPlayer4 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer4;
iWavPlayer4 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[3] = iSound[3];
}
if( iNbrBytes >= 5 ){
if( iPreviousSound[4] != iSound[4] ){
player = CheckPreviousPlayers( iSound[4], iPreviousSound[4], 5 );
if( player == NULL && iWavPlayer5 != NULL ){
if( CheckPointer( iWavPlayer5, 5 ) ){
LOGDEL(iWavPlayer5);
delete iWavPlayer5;
}
iWavPlayer5 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer5;
iWavPlayer5 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[4] = iSound[4];
}
if( iNbrBytes >= 6 ){
if( iPreviousSound[5] != iSound[5] ){
player = CheckPreviousPlayers( iSound[5], iPreviousSound[5], 6 );
if( player == NULL && iWavPlayer6 != NULL ){
if( CheckPointer( iWavPlayer6, 6 ) ){
LOGDEL(iWavPlayer6);
delete iWavPlayer6;
}
iWavPlayer6 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer6;
iWavPlayer6 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[5] = iSound[5];
}
if( iNbrBytes >= 7 ){
if( iPreviousSound[6] != iSound[6] ){
player = CheckPreviousPlayers( iSound[6], iPreviousSound[6], 7 );
if( player == NULL && iWavPlayer7 != NULL ){
if( CheckPointer( iWavPlayer7, 7 ) ){
LOGDEL(iWavPlayer7);
delete iWavPlayer7;
}
iWavPlayer7 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer7;
iWavPlayer7 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[6] = iSound[6];
}
if( iNbrBytes >= 8 ){
if( iPreviousSound[7] != iSound[7] ){
player = CheckPreviousPlayers( iSound[7], iPreviousSound[7], 8 );
if( player == NULL && iWavPlayer8 != NULL ){
if( CheckPointer( iWavPlayer8, 8 ) ){
LOGDEL(iWavPlayer8);
delete iWavPlayer8;
}
iWavPlayer8 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer8;
iWavPlayer8 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[7] = iSound[7];
}
if( iNbrBytes >= 9 ){
if( iPreviousSound[8] != iSound[8] ){
player = CheckPreviousPlayers( iSound[8], iPreviousSound[8], 9 );
if( player == NULL && iWavPlayer9 != NULL ){
if( CheckPointer( iWavPlayer9, 9 ) ){
LOGDEL(iWavPlayer9);
delete iWavPlayer9;
}
iWavPlayer9 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer9;
iWavPlayer9 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[8] = iSound[8];
}
if( iNbrBytes >= 10 ){
if( iPreviousSound[9] != iSound[9] ){
player = CheckPreviousPlayers( iSound[9], iPreviousSound[9], 10 );
if( player == NULL && iWavPlayer10 != NULL ){
if( CheckPointer( iWavPlayer10, 10 ) ){
LOGDEL(iWavPlayer10);
delete iWavPlayer10;
}
iWavPlayer10 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer10;
iWavPlayer10 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[9] = iSound[9];
}
if( iNbrBytes >= 11 ){
if( iPreviousSound[10] != iSound[10] ){
player = CheckPreviousPlayers( iSound[10], iPreviousSound[10], 11 );
if( player == NULL && iWavPlayer11 != NULL ){
if( CheckPointer( iWavPlayer11, 11 ) ){
LOGDEL(iWavPlayer11);
delete iWavPlayer11;
}
iWavPlayer11 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer11;
iWavPlayer11 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[10] = iSound[10];
}
if( iNbrBytes >= 12 ){
if( iPreviousSound[11] != iSound[11] ){
player = CheckPreviousPlayers( iSound[11], iPreviousSound[11], 12 );
if( player == NULL && iWavPlayer12 != NULL ){
if( CheckPointer( iWavPlayer12, 12 ) ){
LOGDEL(iWavPlayer12);
delete iWavPlayer12;
}
iWavPlayer12 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer12;
iWavPlayer12 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[11] = iSound[11];
}
if( iNbrBytes >= 13 ){
if( iPreviousSound[12] != iSound[12] ){
player = CheckPreviousPlayers( iSound[12], iPreviousSound[12], 13 );
if( player == NULL && iWavPlayer13 != NULL ){
if( CheckPointer( iWavPlayer13, 13 ) ){
LOGDEL(iWavPlayer13);
delete iWavPlayer13;
}
iWavPlayer13 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer13;
iWavPlayer13 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[12] = iSound[12];
}
if( iNbrBytes >= 14 ){
if( iPreviousSound[13] != iSound[13] ){
player = CheckPreviousPlayers( iSound[13], iPreviousSound[13], 14 );
if( player == NULL && iWavPlayer14 != NULL ){
if( CheckPointer( iWavPlayer14, 14 ) ){
LOGDEL(iWavPlayer14);
delete iWavPlayer14;
}
iWavPlayer14 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer14;
iWavPlayer14 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[13] = iSound[13];
}
if( iNbrBytes >= 15 ){
if( iPreviousSound[14] != iSound[14] ){
player = CheckPreviousPlayers( iSound[14], iPreviousSound[14], 15 );
if( player == NULL && iWavPlayer15 != NULL ){
if( CheckPointer( iWavPlayer15, 15 ) ){
LOGDEL(iWavPlayer15);
delete iWavPlayer15;
}
iWavPlayer15 = NULL;
}
else if( player != NULL ){
dummyPlayer = iWavPlayer15;
iWavPlayer15 = *player;
*player = dummyPlayer;
player = NULL;
}
}
iPreviousSound[14] = iSound[14];
}
//all players already present have been found
done = EFalse;
while( !done ){
done = LoadNextByte();
}
}
}
void COldSlaveAudio::Play()
{
TTimeIntervalMicroSeconds small(10);
iCurrentPlayer = NULL;
if( iMute ){ // XXX mute is set here since the volume zero doesn't work
iNbrBytes = 0;
m_soundListener.SoundPlayedL( KErrNone );
}
else{
if( iIsEOTurn ){
iCurrentPlayer = iEndOfTurnPlayer;
}
else{
switch( iNbrLoaded-iNbrBytes )
{
case 1:
iCurrentPlayer = iWavPlayer1;
break;
case 2:
iCurrentPlayer = iWavPlayer2;
break;
case 3:
iCurrentPlayer = iWavPlayer3;
break;
case 4:
iCurrentPlayer = iWavPlayer4;
break;
case 5:
iCurrentPlayer = iWavPlayer5;
break;
case 6:
iCurrentPlayer = iWavPlayer6;
break;
case 7:
iCurrentPlayer = iWavPlayer7;
break;
case 8:
iCurrentPlayer = iWavPlayer8;
break;
case 9:
iCurrentPlayer = iWavPlayer9;
break;
case 10:
iCurrentPlayer = iWavPlayer10;
break;
case 11:
iCurrentPlayer = iWavPlayer11;
break;
case 12:
iCurrentPlayer = iWavPlayer12;
break;
case 13:
iCurrentPlayer = iWavPlayer13;
break;
case 14:
iCurrentPlayer = iWavPlayer14;
break;
case 15:
iCurrentPlayer = iWavPlayer15;
break;
}
}
if( iCurrentPlayer != NULL ){
TInt volume = 0;
if( !iMute )
volume = TInt(iCurrentPlayer->MaxVolume() * ( iVolPercent * 0.01 ));
iCurrentPlayer->SetVolume( volume );
iCurrentPlayer->SetVolumeRamp(small);
iCurrentPlayer->Play();
}
else{
iNbrBytes = 0;
m_soundListener.SoundPlayedL( KErrNone );
}
}
}
void COldSlaveAudio::Stop()
{
if( iCurrentPlayer != NULL )
iCurrentPlayer->Stop();
}
void COldSlaveAudio::SetVolume( TInt aVolume )
{
iVolPercent = aVolume;
}
void COldSlaveAudio::SetMute( TBool aMute )
{
iMute = aMute;
}
TBool COldSlaveAudio::IsMute()
{
return iMute;
}
TInt32 COldSlaveAudio::GetDuration()
{
return iTotalDuration;
}
CMdaAudioPlayerUtility** COldSlaveAudio::CheckPreviousPlayers( TInt aSound,
TInt &aSwitchSound,
TInt aNbrChecks )
{
// Disabling sound cache only works in 6600.
#define USE_SOUND_CACHING
#ifdef USE_SOUND_CACHING
if( aNbrChecks < 1 && iPreviousSound[0] == aSound ){
iPreviousSound[0] = aSwitchSound;
return &iWavPlayer1;
}
else if( aNbrChecks < 2 && iPreviousSound[1] == aSound ){
iPreviousSound[1] = aSwitchSound;
return &iWavPlayer2;
}
else if( aNbrChecks < 3 && iPreviousSound[2] == aSound ){
iPreviousSound[2] = aSwitchSound;
return &iWavPlayer3;
}
else if( aNbrChecks < 4 && iPreviousSound[3] == aSound ){
iPreviousSound[3] = aSwitchSound;
return &iWavPlayer4;
}
else if( aNbrChecks < 5 && iPreviousSound[4] == aSound ){
iPreviousSound[4] = aSwitchSound;
return &iWavPlayer5;
}
else if( aNbrChecks < 6 && iPreviousSound[5] == aSound ){
iPreviousSound[5] = aSwitchSound;
return &iWavPlayer6;
}
else if( aNbrChecks < 7 && iPreviousSound[6] == aSound ){
iPreviousSound[6] = aSwitchSound;
return &iWavPlayer7;
}
else if( aNbrChecks < 8 && iPreviousSound[7] == aSound ){
iPreviousSound[7] = aSwitchSound;
return &iWavPlayer8;
}
else if( aNbrChecks < 9 && iPreviousSound[8] == aSound ){
iPreviousSound[8] = aSwitchSound;
return &iWavPlayer9;
}
else if( aNbrChecks < 10 && iPreviousSound[9] == aSound ){
iPreviousSound[9] = aSwitchSound;
return &iWavPlayer10;
}
else if( aNbrChecks < 11 && iPreviousSound[10] == aSound ){
iPreviousSound[10] = aSwitchSound;
return &iWavPlayer11;
}
else if( aNbrChecks < 12 && iPreviousSound[11] == aSound ){
iPreviousSound[11] = aSwitchSound;
return &iWavPlayer12;
}
else if( aNbrChecks < 13 && iPreviousSound[12] == aSound ){
iPreviousSound[12] = aSwitchSound;
return &iWavPlayer13;
}
else if( aNbrChecks < 14 && iPreviousSound[13] == aSound ){
iPreviousSound[13] = aSwitchSound;
return &iWavPlayer14;
}
else if( aNbrChecks < 15 && iPreviousSound[14] == aSound ){
iPreviousSound[14] = aSwitchSound;
return &iWavPlayer15;
}
#endif
return NULL;
}
CMdaAudioPlayerUtility** COldSlaveAudio::CheckCurrentPlayers( TInt aSound, TInt aNbrChecks )
{
TInt i = 0;
TBool done = EFalse;
while( !done ){
if( i == aNbrChecks ){
done = ETrue;
i = -1;
}
else if( aSound == iSound[i] )
done = ETrue;
i++;
}
if( i == 1 ){
return &iWavPlayer1;
}
else if( i == 2 ){
return &iWavPlayer2;
}
else if( i == 3 ){
return &iWavPlayer3;
}
else if( i == 4 ){
return &iWavPlayer4;
}
else if( i == 5 ){
return &iWavPlayer5;
}
else if( i == 6 ){
return &iWavPlayer6;
}
else if( i == 7 ){
return &iWavPlayer7;
}
else if( i == 8 ){
return &iWavPlayer8;
}
else if( i == 9 ){
return &iWavPlayer9;
}
else if( i == 10 ){
return &iWavPlayer10;
}
else if( i == 11 ){
return &iWavPlayer11;
}
else if( i == 12 ){
return &iWavPlayer12;
}
else if( i == 13 ){
return &iWavPlayer13;
}
else if( i == 14 ){
return &iWavPlayer14;
}
else if( i == 15 ){
return &iWavPlayer15;
}
return NULL;
}
TBool COldSlaveAudio::CheckPointer( CMdaAudioPlayerUtility* aPlayer, TInt aNum )
{
if( aNum != 1 && aPlayer == iWavPlayer1 )
return EFalse;
if( aNum != 2 && aPlayer == iWavPlayer2 )
return EFalse;
if( aNum != 3 && aPlayer == iWavPlayer3 )
return EFalse;
if( aNum != 4 && aPlayer == iWavPlayer4 )
return EFalse;
if( aNum != 5 && aPlayer == iWavPlayer5 )
return EFalse;
if( aNum != 6 && aPlayer == iWavPlayer6 )
return EFalse;
if( aNum != 7 && aPlayer == iWavPlayer7 )
return EFalse;
if( aNum != 8 && aPlayer == iWavPlayer8 )
return EFalse;
if( aNum != 9 && aPlayer == iWavPlayer9 )
return EFalse;
if( aNum != 10 && aPlayer == iWavPlayer10 )
return EFalse;
if( aNum != 11 && aPlayer == iWavPlayer11 )
return EFalse;
if( aNum != 12 && aPlayer == iWavPlayer12 )
return EFalse;
if( aNum != 13 && aPlayer == iWavPlayer13 )
return EFalse;
if( aNum != 14 && aPlayer == iWavPlayer14 )
return EFalse;
if( aNum != 15 && aPlayer == iWavPlayer15 )
return EFalse;
return ETrue;;
}
TBool COldSlaveAudio::LoadNextByte()
{
TBool loading = EFalse;
iNbrLoaded++;
if( iNbrLoaded > iNbrBytes ){
// Complete instruction is in memory
loading = ETrue;
m_soundListener.SoundReadyL( KErrNone, iTotalDuration );
}
else{
TTimeIntervalMicroSeconds microSeconds( TInt64(0) );
CMdaAudioPlayerUtility** player = NULL;
switch( iNbrLoaded )
{
case 1:
if( iWavPlayer1 == NULL ){
player = CheckCurrentPlayers( iSound[0], 0 );
if( player != NULL ){
iWavPlayer1 = *player;
microSeconds = iWavPlayer1->Duration();
}
else{
iWavPlayer1 = LoadSoundL( iSound[0] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer1->Duration();
}
break;
case 2:
if( iWavPlayer2 == NULL ){
player = CheckCurrentPlayers( iSound[1], 1 );
if( player != NULL ){
iWavPlayer2 = *player;
microSeconds = iWavPlayer2->Duration();
}
else{
iWavPlayer2 = LoadSoundL( iSound[1] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer2->Duration();
}
break;
case 3:
if( iWavPlayer3 == NULL ){
player = CheckCurrentPlayers( iSound[2], 2 );
if( player != NULL ){
iWavPlayer3 = *player;
microSeconds = iWavPlayer3->Duration();
}
else{
iWavPlayer3 = LoadSoundL( iSound[2] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer3->Duration();
}
break;
case 4:
if( iWavPlayer4 == NULL ){
player = CheckCurrentPlayers( iSound[3], 3 );
if( player != NULL ){
iWavPlayer4 = *player;
microSeconds = iWavPlayer4->Duration();
}
else{
iWavPlayer4 = LoadSoundL( iSound[3] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer4->Duration();
}
break;
case 5:
if( iWavPlayer5 == NULL ){
player = CheckCurrentPlayers( iSound[4], 4 );
if( player != NULL ){
iWavPlayer5 = *player;
microSeconds = iWavPlayer5->Duration();
}
else{
iWavPlayer5 = LoadSoundL( iSound[4] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer5->Duration();
}
break;
case 6:
if( iWavPlayer6 == NULL ){
player = CheckCurrentPlayers( iSound[5], 5 );
if( player != NULL ){
iWavPlayer6 = *player;
microSeconds = iWavPlayer6->Duration();
}
else{
iWavPlayer6 = LoadSoundL( iSound[5] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer6->Duration();
}
break;
case 7:
if( iWavPlayer7 == NULL ){
player = CheckCurrentPlayers( iSound[6], 6 );
if( player != NULL ){
iWavPlayer7 = *player;
microSeconds = iWavPlayer7->Duration();
}
else{
iWavPlayer7 = LoadSoundL( iSound[6] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer7->Duration();
}
break;
case 8:
if( iWavPlayer8 == NULL ){
player = CheckCurrentPlayers( iSound[7], 7 );
if( player != NULL ){
iWavPlayer8 = *player;
microSeconds = iWavPlayer8->Duration();
}
else{
iWavPlayer8 = LoadSoundL( iSound[7] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer8->Duration();
}
break;
case 9:
if( iWavPlayer9 == NULL ){
player = CheckCurrentPlayers( iSound[8], 8 );
if( player != NULL ){
iWavPlayer9 = *player;
microSeconds = iWavPlayer9->Duration();
}
else{
iWavPlayer9 = LoadSoundL( iSound[8] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer9->Duration();
}
break;
case 10:
if( iWavPlayer10 == NULL ){
player = CheckCurrentPlayers( iSound[9], 9 );
if( player != NULL ){
iWavPlayer10 = *player;
microSeconds = iWavPlayer10->Duration();
}
else{
iWavPlayer10 = LoadSoundL( iSound[9] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer10->Duration();
}
break;
case 11:
if( iWavPlayer11 == NULL ){
player = CheckCurrentPlayers( iSound[10], 10 );
if( player != NULL ){
iWavPlayer11 = *player;
microSeconds = iWavPlayer11->Duration();
}
else{
iWavPlayer11 = LoadSoundL( iSound[10] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer11->Duration();
}
break;
case 12:
if( iWavPlayer12 == NULL ){
player = CheckCurrentPlayers( iSound[11], 11 );
if( player != NULL ){
iWavPlayer12 = *player;
microSeconds = iWavPlayer12->Duration();
}
else{
iWavPlayer12 = LoadSoundL( iSound[11] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer12->Duration();
}
break;
case 13:
if( iWavPlayer13 == NULL ){
player = CheckCurrentPlayers( iSound[12], 12 );
if( player != NULL ){
iWavPlayer13 = *player;
microSeconds = iWavPlayer13->Duration();
}
else{
iWavPlayer13 = LoadSoundL( iSound[12] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer13->Duration();
}
break;
case 14:
if( iWavPlayer14 == NULL ){
player = CheckCurrentPlayers( iSound[13], 13 );
if( player != NULL ){
iWavPlayer14 = *player;
microSeconds = iWavPlayer14->Duration();
}
else{
iWavPlayer14 = LoadSoundL( iSound[13] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer14->Duration();
}
break;
case 15:
if( iWavPlayer15 == NULL ){
player = CheckCurrentPlayers( iSound[14], 14 );
if( player != NULL ){
iWavPlayer15 = *player;
microSeconds = iWavPlayer15->Duration();
}
else{
iWavPlayer15 = LoadSoundL( iSound[14] );
loading = ETrue;
}
}
else{
microSeconds = iWavPlayer15->Duration();
}
break;
default:
m_soundListener.SoundReadyL( KErrNone, iTotalDuration );
loading = ETrue;
break;
}
if( !loading ){
if( iTimeingPosition != 0 && iNbrLoaded <= iTimeingPosition ){
// Save duration in 1/10 second.
TInt64 duration = microSeconds.Int64()/100000;
TInt32 longDuration = LOW(duration);
iTotalDuration += longDuration;
}
}
}
return loading;
}
CMdaAudioPlayerUtility* COldSlaveAudio::LoadSoundL( TInt aSound )
{
TFileName fileName;
CMdaAudioPlayerUtility* newPlayer = NULL;
if( GetSound( aSound, fileName ) ){
TRAPD( err,
newPlayer = CMdaAudioPlayerUtility::NewFilePlayerL( fileName, *this ) );
if (err){
ResetToSaneState();
m_soundListener.SoundReadyL( KErrNotFound, 0 );
} else {
LOGNEW(newPlayer, CMdaAudioPlayerUtility);
}
}
else{
ResetToSaneState();
m_soundListener.SoundReadyL( KErrNotFound, 0 );
}
if( newPlayer != NULL )
return (CMdaAudioPlayerUtility*)newPlayer;
else
return NULL;
}
static const TDesC& appendChars( TDes& dest,
const char* orig )
{
while ( *orig != 0 ) {
dest.Append( TChar( *orig++ ) );
}
return dest;
}
TBool COldSlaveAudio::GetSound( TInt aSound, TDes &outFileName )
{
if ( NULL == m_audioTable ) {
return false;
}
const char* fileNameChar = m_audioTable->getFileName( aSound );
if ( fileNameChar == NULL ) {
return false;
}
outFileName.Copy( *m_resPath );
appendChars( outFileName, fileNameChar );
appendChars( outFileName, ".wav" );
TInt symbianError;
if (!WFSymbianUtil::doesFileExist(m_fileServerSession,
outFileName, symbianError) ) {
return EFalse;
}
/* iAppUI->ShowConfirmDialog( outFileName ); */
return ETrue;
}
void
COldSlaveAudio::ResetToSaneState()
{
iCurrentPlayer = NULL;
for (TInt i = 0; i < NUM_SOUND_SLOTS; i++) {
iSound[i] = 0;
iPreviousSound[i] = 0;
}
iNbrBytes = 0;
iNbrLoaded = 0;
iTotalDuration = 0;
iTimeingPosition = 0;
iIsEOTurn = EFalse;
DeleteAllPlayers();
}
void
COldSlaveAudio::DeleteAllPlayers()
{
LOGDEL(iEndOfTurnPlayer);
delete iEndOfTurnPlayer;
iEndOfTurnPlayer = NULL;
if( iWavPlayer1 != NULL && CheckPointer( iWavPlayer1, 1 ) ){
LOGDEL(iWavPlayer1);
delete iWavPlayer1;
}
iWavPlayer1 = NULL;
if( iWavPlayer2 != NULL && CheckPointer( iWavPlayer2, 2 ) ){
LOGDEL(iWavPlayer2);
delete iWavPlayer2;
}
iWavPlayer2 = NULL;
if( iWavPlayer3 != NULL && CheckPointer( iWavPlayer3, 3 ) ){
LOGDEL(iWavPlayer3);
delete iWavPlayer3;
}
iWavPlayer3 = NULL;
if( iWavPlayer4 != NULL && CheckPointer( iWavPlayer4, 4 ) ){
LOGDEL(iWavPlayer4);
delete iWavPlayer4;
}
iWavPlayer4 = NULL;
if( iWavPlayer5 != NULL && CheckPointer( iWavPlayer5, 5 ) ){
LOGDEL(iWavPlayer5);
delete iWavPlayer5;
}
iWavPlayer5 = NULL;
if( iWavPlayer6 != NULL && CheckPointer( iWavPlayer6, 6 ) ){
LOGDEL(iWavPlayer6);
delete iWavPlayer6;
}
iWavPlayer6 = NULL;
if( iWavPlayer7 != NULL && CheckPointer( iWavPlayer7, 7 ) ){
LOGDEL(iWavPlayer7);
delete iWavPlayer7;
}
iWavPlayer7 = NULL;
if( iWavPlayer8 != NULL && CheckPointer( iWavPlayer8, 8 ) ){
LOGDEL(iWavPlayer8);
delete iWavPlayer8;
}
iWavPlayer8 = NULL;
if( iWavPlayer9 != NULL && CheckPointer( iWavPlayer9, 9 ) ){
LOGDEL(iWavPlayer9);
delete iWavPlayer9;
}
iWavPlayer9 = NULL;
if( iWavPlayer10 != NULL && CheckPointer( iWavPlayer10, 10 ) ){
LOGDEL(iWavPlayer10);
delete iWavPlayer10;
}
iWavPlayer10 = NULL;
if( iWavPlayer11 != NULL && CheckPointer( iWavPlayer11, 11 ) ){
LOGDEL(iWavPlayer11);
delete iWavPlayer11;
}
iWavPlayer11 = NULL;
if( iWavPlayer12 != NULL && CheckPointer( iWavPlayer12, 12 ) ){
LOGDEL(iWavPlayer12);
delete iWavPlayer12;
}
iWavPlayer12 = NULL;
if( iWavPlayer13 != NULL && CheckPointer( iWavPlayer13, 13 ) ){
LOGDEL(iWavPlayer13);
delete iWavPlayer13;
}
iWavPlayer13 = NULL;
if( iWavPlayer14 != NULL && CheckPointer( iWavPlayer14, 14 ) ){
LOGDEL(iWavPlayer14);
delete iWavPlayer14;
}
iWavPlayer14 = NULL;
if( iWavPlayer15 != NULL && CheckPointer( iWavPlayer15, 15 ) ){
LOGDEL(iWavPlayer15);
delete iWavPlayer15;
}
iWavPlayer15 = NULL;
}
void COldSlaveAudio::MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration )
{
if(aError == KErrNone){
if( iTimeingPosition != 0 && iNbrLoaded <= iTimeingPosition ){
// Save duration in 1/10 second.
TInt64 duration = aDuration.Int64()/100000;
TInt32 longDuration = LOW(duration);
iTotalDuration += longDuration;
}
TBool done = EFalse;
while( !done ){
done = LoadNextByte();
}
}
else{
ResetToSaneState();
m_soundListener.SoundReadyL( aError, iTotalDuration );
}
}
void COldSlaveAudio::MapcPlayComplete(TInt aError)
{
iCurrentPlayer = NULL;
if(aError == KErrNone){
iNbrBytes--;
if( iNbrBytes <= 0 ){
m_soundListener.SoundPlayedL( KErrNone );
iNbrBytes = 0;
}
else{
Play();
}
}
else{
ResetToSaneState();
m_soundListener.SoundPlayedL( aError );
}
}
// End of File
| [
"[email protected]"
] | [
[
[
1,
1219
]
]
] |
7d471ec83ffccdbcb2ed3b7506e1a6d620af959e | 6712f8313dd77ae820aaf400a5836a36af003075 | /bdGraph/SJpeg.h | cc73a455da721b344a378849dba43183e571fc6a | [] | no_license | AdamTT1/bdScript | d83c7c63c2c992e516dca118cfeb34af65955c14 | 5483f239935ec02ad082666021077cbc74d1790c | refs/heads/master | 2021-12-02T22:57:35.846198 | 2010-08-08T22:32:02 | 2010-08-08T22:32:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,818 | h | //comment next line to remove from program
// SJpeg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// SJpeg window
typedef struct taghuffStruct
{
WORD huffCode[16]; //lowest code which starts length
BYTE huffLength[16];
BYTE huffIndex[16]; //index into huffval of lowest code of bitsize.
BYTE huffVal[256];
} huffStruct;
typedef struct tagMCURowStruct
{
struct tagMCURowStruct *nextMCURow;
short data[1];
} MCURowStruct,*lpMCURowStruct;
typedef struct
{
DWORD eobCnt;
lpMCURowStruct curMCURow;
WORD LastDCVal[4];
DWORD nonInterleavedRestartCnt;
DWORD interleavedRestartCnt;
DWORD curRowNum;
//values below don't change once set
DWORD restartInterval;
BYTE component[4];
BYTE huffDC[4];
BYTE huffAC[4];
BYTE ss;
BYTE se;
BYTE ah;
BYTE al;
BYTE numberOfComponents;
BYTE bitCnt;
} StartOfScan;
class SJpeg
{
// Construction
public:
SJpeg();
~SJpeg();
// BOOL Load(HDC hdc,IFileData* data,DWORD drawWidth=0,DWORD drawHeight=0);
ImageData* LoadYCbCr(IFileData* data);
// Attributes
private:
enum Markers
{
TEM=0x01, //0x02-0x0bf reserved
SOF0=0x0c0, //baseline DCT
SOF1=0x0c1, //Extended sequential DCT
SOF2=0x0c2, //Progressive DCT
SOF3=0x0c3, //Lossless (sequential)
DHT=0x0c4, //define Huffman tables
SOF5=0x0c5, //Huffman Differential sequential DCT
SOF6=0x0c6, //Huffman Differential progressive DCT
SOF7=0x0c7, //Huffman Differential lossless
JPG=0x0c8, //reserved for JPEG extension
SOF9=0x0c9, //arithmetic sequential DCT
SOF10=0x0ca, //arithmetic progressive DCT
SOF11=0x0cb, //arithmetic lossless(sequential)
DAC=0x0cc, //define arithmetic conditioning
SOF13=0x0cd, //arithmetic Differential sequential DCT
SOF14=0x0ce, //arithmetic Differential progressive DCT
SOF15=0x0cf, //arithmetic Differential lossless
RST0=0x0d0, //-0x0d7 restart modulo 8 counter
SOI=0x0d8, //Start of image
EOI=0x0d9, //End of image
SOS=0x0da, //Start of scan
DQT=0x0db, //define quantization tables
DNL=0x0dc, //define number of lines
DRI=0x0dd, //define restart interval
DHP=0x0de, //define hierarchial progression
EXP=0x0df, //expand reference image
APP0=0x0e0, //-0x0ef
JPG0=0x0f0, //-0x0fd, reserved for JPEG extension
COM=0x0fe
};
// Operations
public:
// Implementation
private:
void FreeWorkArea();
void FreeDataArea();
void Decode();
BOOL IDCT(BYTE** ppSamples);
BOOL ConvertDCTComponent(DWORD index,DWORD* pSrcOffset,BYTE** ppSamples);
BOOL IsMarker();
void initHuff();
BOOL skipRST(StartOfScan* sos);
void GetMCURow(StartOfScan* sos);
DWORD GetEOBCnt(BYTE bitcnt);
DWORD GetUnsignedBits(BYTE bitcnt);
int GetBits(BYTE bitcnt);
BYTE readByteSkipStuffed();
BYTE GetHuffByte(BYTE compHuff);
void do_DQT();
int readWord();
int readByte();
int readMarker();
void MovePtr(int offset);
int* dqt_tables[16];
huffStruct* dht_tables[8]; //0-3 DC or lossless, 4-7 AC
IFileData* m_IData;
lpMCURowStruct mcuRow;//ptr to next row, short[64]*sof_dataUnitCnt*sof_hortMCUs
DWORD mcuRowCnt;
protected:
DWORD sof_numberOfLines;
DWORD sof_samplesPerLine;
BYTE sof_precision;
BYTE sof_numberOfComponents;
BYTE sof_maxHFactor;
BYTE sof_maxVFactor;
DWORD sof_hortMCUs;
BYTE sof_component[256];
BYTE sof_componentSamplingFactors[256];
private:
DWORD sof_dataUnitCnt;
DWORD sof_mcuRowByteCnt;
BYTE sof_componentQuantizationTable[256];
WORD sof_componentOffset[256]; //number of data units before component in MCU
DWORD dri_RestartInterval;
const BYTE *basePtr,*curPtr,*endPtr;
DWORD nextBits;
int bitsOverWord;
BYTE markerReached1,markerReached2;
BYTE spare1,spare2;
////protected:
};
| [
"tkisky"
] | [
[
[
1,
157
]
]
] |
896f9599638e57d55b596ed5c73f273f0ae83283 | c429fffcfe1128eeaa44f880bdcb1673633792d2 | /dwmaxx/stdafx.cpp | e2ba7ccad30a37a380d2bbebbf1fc68a1b172f85 | [] | no_license | steeve/dwmaxx | 7362ef753a71d707880b8cdefe65a5688a516f8d | 0de4addc3dc8056dc478949b7efdbb5b67048d60 | refs/heads/master | 2021-01-10T20:13:15.161814 | 2008-02-18T02:48:15 | 2008-02-18T02:48:15 | 1,367,113 | 10 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 202 | cpp | // stdafx.cpp : source file that includes just the standard includes
// dwmaxx.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"siwuzzz@d84ac079-a144-0410-96e0-5f9b019a5953"
] | [
[
[
1,
5
]
]
] |
5eb2e78b33945832caeb60aeb3288c28ad1fdbf9 | 5ff30d64df43c7438bbbcfda528b09bb8fec9e6b | /kgraphics/math/Hermite.h | 090194da6ce848cf041e6b7f5ab47d979de3da2d | [] | 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 | UTF-8 | C++ | false | false | 2,756 | h | #pragma once
#include <kgraphics/math/math.h>
#include <kgraphics/math/Writer.h>
#include <kgraphics/math/Vector3.h>
namespace gfx {
class Hermite
{
public:
// constructor/destructor
Hermite();
~Hermite();
// text output (for debugging)
friend Writer& operator<<( Writer& out, const Hermite& source );
// set up
// default
bool Initialize( const Vector3* positions,
const Vector3* inTangents,
const Vector3* outTangents,
const float* times,
unsigned int count );
// clamped spline
bool InitializeClamped( const Vector3* positions,
const float* times,
unsigned int count,
const Vector3& inTangent,
const Vector3& outTangent );
// natural spline
bool InitializeNatural( const Vector3* positions,
const float* times,
unsigned int count );
// cyclic spline
bool InitializeCyclic( const Vector3* positions,
const float* times,
unsigned int count );
// acyclic spline
bool InitializeAcyclic( const Vector3* positions,
const float* times,
unsigned int count );
// destroy
void Clean();
// evaluate position
Vector3 Evaluate( float t );
// evaluate derivative
Vector3 Velocity( float t );
// evaluate second derivative
Vector3 Acceleration( float t );
// find parameter that moves s distance from Q(t1)
float FindParameterByDistance( float t1, float s );
// return length of curve between t1 and t2
float ArcLength( float t1, float t2 );
// get total length of curve
inline float GetLength() { return mTotalLength; }
protected:
// return length of curve between u1 and u2
float SegmentArcLength( u_int i, float u1, float u2 );
Vector3* mPositions; // sample positions
Vector3* mInTangents; // incoming tangents on each segment
Vector3* mOutTangents; // outgoing tangents on each segment
float* mTimes; // time to arrive at each point
float* mLengths; // length of each curve segment
float mTotalLength; // total length of curve
unsigned int mCount; // number of points and times
private:
// copy operations
// made private so they can't be used
Hermite( const Hermite& other );
Hermite& operator=( const Hermite& other );
};
} // namespace gfx
| [
"keedongpark@keedongpark"
] | [
[
[
1,
85
]
]
] |
c7d3fd45aa5351c2caf39e6ad9b0016d97686c19 | 4497c10f3b01b7ff259f3eb45d0c094c81337db6 | /Retargeting/Shifmap/Version01/FillHoleShiftMap.h | e51d173ad1ecc4d77c5dc61f607d6e36924382f2 | [] | no_license | liuguoyou/retarget-toolkit | ebda70ad13ab03a003b52bddce0313f0feb4b0d6 | d2d94653b66ea3d4fa4861e1bd8313b93cf4877a | refs/heads/master | 2020-12-28T21:39:38.350998 | 2010-12-23T16:16:59 | 2010-12-23T16:16:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,655 | h | #pragma once
#include "ImageRetargeter.h"
#include "FillHoleEnergyFunction.h"
#include "GCoptimization.h"
#include "MaskShift.h"
#include <vector>
using namespace std;
class FillHoleShiftMap : public ImageRetargeter
{
public:
FillHoleShiftMap(void);
~FillHoleShiftMap(void);
virtual IplImage* GetRetargetImage(IplImage* input, IplImage* saliency, CvSize outputSize);
virtual IplImage* GetRetargetImage2(IplImage* input, IplImage* saliency, CvSize outputSize, MaskShift* maskShift);
virtual void ComputeShiftMap(IplImage* input, IplImage* saliency, CvSize output, CvSize shiftSize);
virtual void ComputeShiftMap2(IplImage* input, IplImage* saliency, CvSize output, CvSize shiftSize, MaskShift* maskShift);
void SetMask(IplImage* mask, IplImage* maskData);
protected:
IplImage* _mask;
IplImage* _maskData;
GCoptimizationGeneralGraph* _gcGeneral;
vector<CvPoint*>* _pointMapping;
IplImage* _input;
IplImage* _maskNeighbor; // carry neighbor info with mask
CvSize _shiftSize;
protected:
void ClearGC();
void ProcessMask();
bool IsMaskedPixel(int x, int y, IplImage* mask);
// process the mapping
// pointMapping is an empty vector
// mapping is a matrix which has the same size as the mask
// mask is the input
// return total number of nodes
void ProcessMapping(IplImage* mask, CvMat* mapping, vector<CvPoint*>* pointMapping);
void ProcessMapping(MaskShift* mask, CvMat* mapping, vector<CvPoint*>* pointMapping);
//
void ProcessMask(IplImage* mask);
void ProcessMask(MaskShift* mask);
// setup neighborhood system for GC
void SetupGCOptimizationNeighbor(GCoptimizationGeneralGraph* gcGeneral, CvMat* mapping);
// setup neighborhood system for nodes & masked pixels
// maskNeighbor & mask should have the same size
// action: scan through the mask and set info for pixel which is a neighbor of a masked pixel
//
void SetupMaskNeighbor(IplImage* maskNeighbor, IplImage* mask);
void SetupMaskNeighbor(IplImage* maskNeighbor, MaskShift* mask);
// helpful function for SetupMaskNeighbor
// doesn't check whether currentPoint & neighborPoint is neighbor
// and inside the image
// tradeoff safety for performance
void ProcessNeighbor(CvPoint currentPoint, CvPoint neighborPoint, IplImage* maskNeighbor, IplImage* mask);
void ProcessNeighbor(CvPoint currentPoint, CvPoint neighborPoint, IplImage* maskNeighbor, MaskShift* mask);
void ProcessNeighbor(CvPoint currentPoint, CvPoint neighborPoint, IplImage* maskNeighbor, CvMat* mapping, GCoptimizationGeneralGraph* gcGeneral);
IplImage* CalculatedRetargetImage();
CvMat* CalculateLabelMap();
};
| [
"kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a"
] | [
[
[
1,
63
]
]
] |
3d396e37cd86ab046ae00a710927bb9c86d407c2 | b654c48c6a1f72140ca14defd05b835d4dec5a75 | /prog3/prog3.cpp | 336446d105389e59adc4dee80064b9f7110bdc4b | [] | no_license | johntalton/cs470 | 036ca995c48712d2506665a337a6d814ab11d347 | 187c87a60e2b2fdacd038eddb683a68ecd9c711d | refs/heads/master | 2021-01-22T17:57:09.139203 | 1999-06-28T17:32:00 | 2017-08-18T18:09:22 | 100,736,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,663 | cpp | #include <iostream.h>
#include "../glcontrol.h" //Include the basics for adding this into OpenGL
#include "../globals.h" // All global vars and functions
#include "../prog1/prog1.h" //Include OUR old basic code
#include "../prog2/prog2.h" // includ some of our primitive stuff
#include "prog3.h" // hope we get it all in there
int Animate = 1; // Use this to tell user whater we want to constanly redraw or not
#define PI 3.14159265359
Point3D Vlist0[] = { -10, 0, 0, //Xaxis
10, 0, 0,
0, -10, 0, //Yaxis
0, 10, 0,
0, 0, -10, //Zaxis
0, 0, 10
};
Edge3D Elist0[] = { 0, 1,
2, 3,
4, 5
};
Point3D Centroid1= { 0, 0.333 , 0
};
Point3D Vlist1[] = { -1.0, 0.0, 1.0, //0
1.0, 0.0, 1.0, //1
1.0, 0.0, -1.0, //2
-1.0, 0.0, -1.0, //3
0.0, 1.0, 0.0 //4
};
Edge3D Elist1[] = { 0, 1, // This sets up a pritty pyramid
1, 2,
2, 3,
3, 0,
0, 4,
1, 4,
2, 4,
3, 4
};
Point3D Centroid2= { 6, 1, 1
};
Point3D Vlist2[] = { 5.0, 0.0, 0.0, //0
7.0, 0.0, 0.0, //1
7.0, 0.0, 2.0, //2
5.0, 0.0, 2.0, //3
5.0, 2.0, 0.0, //4
7.0, 2.0, 0.0, //5
7.0, 2.0, 2.0, //6
5.0, 2.0, 2.0 //7
};
Edge3D Elist2[] = { 0, 1, //bottom
1, 2,
2, 3,
3, 0,
4, 5, //top
5, 6,
6, 7,
7, 4,
0, 4, //sides
1, 5,
2, 6,
3, 7
};
double t = 0;
Point3D O = { 0, 4, -5.4};
Point3D R = { 0, 0, 0};
Point3D V = { 0, 1, 0 };
Point3D newVlist1[10];
Point3D newVlist2[10];
/**************************************************************************
* DrawScene
* This is our function that is called on draw. This is really the
* only thing that neads to be in here.
* @param void
* @return void
**************************************************************************/
void DrawScene()
{
if(t < 4*PI){ // spin around twice
O.x = 17 * sin(t);
O.z = -17 * cos(t);
t = t + .01;
}else{ // and then zoom out Z axis if neg toward user
O.z = O.z - 0.5;
}
ViewPoint(O, R,V);
if(axison){
setColor(0.4,0.4,0.4);
Draw3DPoly(Vlist0,Elist0,6,3);
}
setColor(1,0,0);
//Scale(Vlist1,5,Centroid1,30,newVlist1);
Draw3DPoly(Vlist1,Elist1,5,8);
//Ortho(newVlist1,Elist1,5,8);
setColor(0,1,0);
//Scale(Vlist2,8,Centroid2,30,newVlist2);
Draw3DPoly(Vlist2,Elist2,8,12);
//Ortho(newVlist2,Elist2,8,12);
} | [
"[email protected]"
] | [
[
[
1,
103
]
]
] |
19b8a9a6f623f7c55e7c168883051419ebec6366 | c9390a163ae5f0bc6fdc1560be59939dcbe3eb07 | /vstgui.cpp | 40fc9421149c8246e4662e3e610057b170fe0020 | [] | no_license | trimpage/multifxvst | 2ceae9da1768428288158319fcf03d603ba47672 | 1cb40f8e0cc873f389f2818b2f40665d2ba2b18b | refs/heads/master | 2020-04-06T13:23:41.059632 | 2010-11-04T14:32:54 | 2010-11-04T14:32:54 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 197,909 | cpp | //-----------------------------------------------------------------------------
// VST Plug-Ins SDK
// VSTGUI: Graphical User Interface Framework for VST plugins :
//
// Version 2.2 Date : 14/05/03
//
// First version : Wolfgang Kundrus 06.97
// Added Motif/Windows vers.: Yvan Grabit 01.98
// Added Mac version : Charlie Steinberg 02.98
// Added BeOS version : Georges-Edouard Berenger 05.99
// Added new functions : Matthias Juwan 12.01
// Added MacOSX version : Arne Scheffler 02.03
//
//-----------------------------------------------------------------------------
// VSTGUI LICENSE
// © 2003, Steinberg Media Technologies, 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 Steinberg Media Technologies nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#include "stdafx.h"
#ifndef __vstgui__
#include "vstgui.h"
#endif
#if !PLUGGUI
#ifndef __audioeffectx__
#include "audioeffectx.h"
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#if USE_NAMESPACE
#define VSTGUI_CFrame VSTGUI::CFrame
#define VSTGUI_CPoint VSTGUI::CPoint
#define VSTGUI_kDropFiles VSTGUI::kDropFiles
#define VSTGUI_kDropText VSTGUI::kDropText
#define VSTGUI_CTextEdit VSTGUI::CTextEdit
#define VSTGUI_CColor VSTGUI::CColor
#define VSTGUI_CDrawContext VSTGUI::CDrawContext
#define VSTGUI_COptionMenu VSTGUI::COptionMenu
#define VSTGUI_COptionMenuScheme VSTGUI::COptionMenuScheme
#else
#define VSTGUI_CFrame CFrame
#define VSTGUI_CPoint CPoint
#define VSTGUI_kDropFiles kDropFiles
#define VSTGUI_kDropText kDropText
#define VSTGUI_CTextEdit CTextEdit
#define VSTGUI_CColor CColor
#define VSTGUI_CDrawContext CDrawContext
#define VSTGUI_COptionMenu COptionMenu
#define VSTGUI_COptionMenuScheme COptionMenuScheme
#endif
#if !WINDOWS
#define USE_GLOBAL_CONTEXT 1
#endif
#ifdef DEBUG //---For Debugging------------------------
long gNbCBitmap = 0;
long gNbCView = 0;
long gNbCDrawContext = 0;
long gNbCOffscreenContext = 0;
long gBitmapAllocation = 0;
long gNbDC = 0;
#include <stdarg.h>
void FDebugPrint (char *format, ...);
void FDebugPrint (char *format, ...)
{
char string[300];
va_list marker;
va_start (marker, format);
vsprintf (string, format, marker);
if (!string)
strcpy (string, "Empty string\n");
#if MAC
// printf (string);
#elif WINDOWS
OutputDebugString (string);
#else
fprintf (stderr, string);
#endif
}
#endif //---For Debugging------------------------
#if WINDOWS
static bool swapped_mouse_buttons = false;
#define DYNAMICALPHABLEND 1
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
#include <shlobj.h>
#include <shellapi.h>
#if DYNAMICALPHABLEND
typedef BOOL (WINAPI *PFNALPHABLEND)(
HDC hdcDest, // handle to destination DC
int nXOriginDest, // x-coord of upper-left corner
int nYOriginDest, // y-coord of upper-left corner
int nWidthDest, // destination width
int nHeightDest, // destination height
HDC hdcSrc, // handle to source DC
int nXOriginSrc, // x-coord of upper-left corner
int nYOriginSrc, // y-coord of upper-left corner
int nWidthSrc, // source width
int nHeightSrc, // source height
BLENDFUNCTION blendFunction // alpha-blending function
);
PFNALPHABLEND pfnAlphaBlend = NULL;
typedef BOOL (WINAPI *PFNTRANSPARENTBLT)(
HDC hdcDest, // handle to destination DC
int nXOriginDest, // x-coord of destination upper-left corner
int nYOriginDest, // y-coord of destination upper-left corner
int nWidthDest, // width of destination rectangle
int hHeightDest, // height of destination rectangle
HDC hdcSrc, // handle to source DC
int nXOriginSrc, // x-coord of source upper-left corner
int nYOriginSrc, // y-coord of source upper-left corner
int nWidthSrc, // width of source rectangle
int nHeightSrc, // height of source rectangle
UINT crTransparent // color to make transparent
);
PFNTRANSPARENTBLT pfnTransparentBlt = NULL;
#endif
#if PLUGGUI
extern HINSTANCE ghInst;
inline HINSTANCE GetInstance () { return ghInst; }
#else
extern void* hInstance;
inline HINSTANCE GetInstance () { return (HINSTANCE)hInstance; }
#endif
long useCount = 0;
char className[20];
bool InitWindowClass ();
void ExitWindowClass ();
LONG WINAPI WindowProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
static HANDLE CreateMaskBitmap (CDrawContext* pContext, VSTGUI::CRect& rect, CColor transparentColor);
static void DrawTransparent (CDrawContext* pContext, VSTGUI::CRect& rect, const VSTGUI::CPoint& offset, HDC hdcBitmap, POINT ptSize, HBITMAP pMask, COLORREF color);
static bool checkResolveLink (const char* nativePath, char* resolved);
static void *createDropTarget (VSTGUI_CFrame* pFrame);
BEGIN_NAMESPACE_VSTGUI
long standardFontSize[] = { 12, 18, 14, 12, 11, 10, 9, 13 };
const char* standardFontName[] = {
"Arial", "Arial", "Arial",
"Arial", "Arial", "Arial",
"Arial", "Symbol" };
END_NAMESPACE_VSTGUI
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#elif MOTIF
#define USE_XPM 0
#define TEST_REGION 0
#if USE_XPM
#include <X11/xpm.h>
#endif
#include <X11/Xlib.h>
#include <Xm/DrawingA.h>
#include <assert.h>
#include <Xm/MwmUtil.h>
#include <Xm/DialogS.h>
#include <time.h>
#if SGI
#include <sys/syssgi.h>
#elif SUN
#elif LINUX
#endif
#define XDRAWPARAM pDisplay, (Window)pWindow, (GC)pSystemContext
#define XWINPARAM pDisplay, (Window)pWindow
#define XGCPARAM pDisplay, (GC)pSystemContext
// init the static variable about font
bool fontInit = false;
XFontStruct *fontStructs[] = {0, 0, 0, 0, 0, 0, 0};
struct SFontTable {char* name; char* string;};
static SFontTable fontTable[] = {
{"SystemFont", "-adobe-helvetica-bold-r-*-*-12-*-*-*-*-*-*-*"}, // kSystemFont
{"NormalFontVeryBig", "-adobe-helvetica-medium-r-*-*-18-*-*-*-*-*-*-*"}, // kNormalFontVeryBig
{"NormalFontBig", "-adobe-helvetica-medium-r-normal-*-14-*-*-*-*-*-*-*"}, // kNormalFontBig
{"NormalFont", "-adobe-helvetica-medium-r-*-*-12-*-*-*-*-*-*-*"}, // kNormalFont
{"NormalFontSmall", "-adobe-helvetica-medium-r-*-*-10-*-*-*-*-*-*-*"}, // kNormalFontSmall
{"NormalFontSmaller", "-adobe-helvetica-medium-r-*-*-9-*-*-*-*-*-*-*"}, // kNormalFontSmaller
{"NormalFontVerySmall", "-adobe-helvetica-medium-r-*-*-8-*-*-*-*-*-*-*"}, // kNormalFontVerySmall
{"SymbolFont", "-adobe-symbol-medium-r-*-*-12-*-*-*-*-*-*-*"} // kSymbolFont
};
long standardFontSize[] = { 12, 16, 14, 12, 10, 9, 8, 10 };
//-----------------------------------------------------------------------------
// declaration of different local functions
long convertPoint2Angle (VSTGUI::CPoint &pm, VSTGUI::CPoint &pt);
// callback for the frame
void _drawingAreaCallback (Widget widget, XtPointer clientData, XtPointer callData);
void _eventHandler (Widget w, XtPointer clientData, XEvent *event, char *p);
void _destroyCallback (Widget widget, XtPointer clientData, XtPointer callData);
// stuff for color
long getIndexColor8Bit (CColor color, Display *pDisplay, Colormap colormap);
long CDrawContext::nbNewColor = 0;
static CColor paletteNewColor[256];
//------ our user-defined XPM functions
bool xpmGetValues (char **ppDataXpm, long *pWidth, long *pHeight, long *pNcolor, long *pCpp);
#if !USE_XPM
#include "xpmloader.cpp"
#endif
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#elif MAC
#if MACX
//-----------------------------------------------------------------------------
#include <QuickTime/ImageCompression.h>
const unsigned char* macXfontNames[] = {
"\pArial",
"\pArial",
"\pArial",
"\pArial",
"\pArial",
"\pArial",
"\pArial",
"\pSymbol"
};
//-----------------------------------------------------------------------------
#else
#include <QDOffscreen.h>
#include <StandardFile.h>
#include <Navigation.h>
#include <PictUtils.h>
#endif
long standardFontSize[] = { 12, 18, 14, 12, 10, 9, 9, 12 };
long convertPoint2Angle (VSTGUI::CPoint &pm, VSTGUI::CPoint &pt);
void RectNormalize (Rect& rect);
void CRect2Rect (const VSTGUI::CRect &cr, Rect &rr);
void Rect2CRect (Rect &rr, VSTGUI::CRect &cr);
void CColor2RGBColor (const CColor &cc, RGBColor &rgb);
void RGBColor2CColor (const RGBColor &rgb, CColor &cc);
static void install_drop (CFrame *frame);
static void remove_drop (CFrame *frame);
//-----------------------------------------------------------------------------
void RectNormalize (Rect& rect)
{
if (rect.left > rect.right)
{
long temp = rect.right;
rect.right = rect.left;
rect.left = temp;
}
if (rect.top > rect.bottom)
{
long temp = rect.bottom;
rect.bottom = rect.top;
rect.top = temp;
}
}
//-----------------------------------------------------------------------------
void CRect2Rect (const VSTGUI::CRect &cr, Rect &rr)
{
rr.left = cr.left;
rr.right = cr.right;
rr.top = cr.top;
rr.bottom = cr.bottom;
RectNormalize (rr);
}
//-----------------------------------------------------------------------------
void Rect2CRect (Rect &rr, VSTGUI::CRect &cr)
{
cr.left = rr.left;
cr.right = rr.right;
cr.top = rr.top;
cr.bottom = rr.bottom;
}
//-----------------------------------------------------------------------------
void CColor2RGBColor (const CColor &cc, RGBColor &rgb)
{
rgb.red = cc.red * 257;
rgb.green = cc.green * 257;
rgb.blue = cc.blue * 257;
}
//-----------------------------------------------------------------------------
void RGBColor2CColor (const RGBColor &rgb, CColor &cc)
{
cc.red = rgb.red / 257;
cc.green = rgb.green / 257;
cc.blue = rgb.blue / 257;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#elif BEOS
#include <TranslationUtils.h>
#include <Resources.h>
#include <Bitmap.h>
#include <Region.h>
#include <View.h>
#include <Window.h>
#include <Message.h>
#include <Entry.h>
#include <Path.h>
//--------------------------
class PlugView: public BView
{
public:
PlugView (BRect frame, CFrame* cframe);
void Draw (BRect updateRect);
void MouseDown (BPoint where);
void MessageReceived (BMessage *msg);
private:
CFrame* cframe;
};
long convertPoint2Angle (VSTGUI::CPoint &pm, VSTGUI::CPoint &pt);
drawing_mode modeToPlatform [] = {
// kCopyMode kOrMode kXorMode
B_OP_COPY, B_OP_OVER, B_OP_INVERT
};
long standardFontSize[] = { 12, 18, 14, 12, 11, 10, 9, 12 };
const char* standardFont = "Swis721 BT";
const char* standardFontS = "Roman";
const char* systemFont = "Swis721 BT";
const char* systemFontS = "Bold";
const char* standardFontName[] = { systemFont,
standardFont, standardFont, standardFont, standardFont, standardFont,
standardFont };
const char* standardFontStyle[] = { systemFontS,
standardFontS, standardFontS, standardFontS, standardFontS, standardFontS,
standardFontS };
#endif
//-----------------------------------------------------------------------------
bool VSTGUI::CRect::pointInside (const VSTGUI::CPoint& where) const
{
return where.h >= left && where.h < right && where.v >= top && where.v < bottom;
}
//-----------------------------------------------------------------------------
bool VSTGUI::CRect::isEmpty () const
{
if (right <= left)
return true;
if (bottom <= top)
return true;
return false;
}
//-----------------------------------------------------------------------------
void VSTGUI::CRect::bound (const VSTGUI::CRect& rect)
{
if (left < rect.left)
left = rect.left;
if (top < rect.top)
top = rect.top;
if (right > rect.right)
right = rect.right;
if (bottom > rect.bottom)
bottom = rect.bottom;
if (bottom < top)
bottom = top;
if (right < left)
right = left;
}
BEGIN_NAMESPACE_VSTGUI
CColor kTransparentCColor = {255, 255, 255, 0};
CColor kBlackCColor = {0, 0, 0, 0};
CColor kWhiteCColor = {255, 255, 255, 0};
CColor kGreyCColor = {127, 127, 127, 0};
CColor kRedCColor = {255, 0, 0, 0};
CColor kGreenCColor = {0 , 255, 0, 0};
CColor kBlueCColor = {0 , 0, 255, 0};
CColor kYellowCColor = {255, 255, 0, 0};
CColor kMagentaCColor= {255, 0, 255, 0};
CColor kCyanCColor = {0 , 255, 255, 0};
#define kDragDelay 0
//-----------------------------------------------------------------------------
// CDrawContext Implementation
//-----------------------------------------------------------------------------
CDrawContext::CDrawContext (CFrame *pFrame, void *pSystemContext, void *pWindow)
: pSystemContext (pSystemContext), pWindow (pWindow), pFrame (pFrame),
frameWidth (1), lineStyle (kLineSolid), drawMode (kCopyMode)
#if WINDOWS
,pBrush (0), pFont (0), pPen (0), pOldBrush (0), pOldPen (0), pOldFont (0)
#elif MAC
,bInitialized (false)
#endif
{
#ifdef DEBUG
gNbCDrawContext++;
#endif
// initialize values
if (pFrame)
pFrame->getViewSize (clipRect);
else
clipRect (0, 0, 1000, 1000);
frameColor = kWhiteCColor;
fillColor = kBlackCColor;
fontColor = kWhiteCColor;
// offsets use by offscreen
offset (0, 0);
offsetScreen (0, 0);
#if WINDOWS
if (pSystemContext)
{
pOldBrush = GetCurrentObject ((HDC)pSystemContext, OBJ_BRUSH);
pOldPen = GetCurrentObject ((HDC)pSystemContext, OBJ_PEN);
pOldFont = GetCurrentObject ((HDC)pSystemContext, OBJ_FONT);
SetBkMode ((HDC)pSystemContext, TRANSPARENT);
}
iPenStyle = PS_SOLID;
// get position
if (pWindow)
{
RECT rctTempWnd;
GetWindowRect ((HWND)pWindow, &rctTempWnd);
offsetScreen.h = rctTempWnd.left;
offsetScreen.v = rctTempWnd.top;
}
#elif MOTIF
if (pFrame)
pDisplay = pFrame->getDisplay ();
// set the current font
if (pSystemContext)
setFont (kNormalFont);
else
fprintf (stderr, "Error in CDrawContext::CDrawContext : pSystemContext must not be Null!!!\n");
#elif BEOS
pView = (BView*) pSystemContext;
if (pView)
pView->LockLooper ();
#endif
if (pSystemContext)
{
// set the default values
setFrameColor (frameColor);
setLineStyle (lineStyle);
#if !MOTIF
setFillColor (fillColor);
setFontColor (fontColor);
#endif
}
}
//-----------------------------------------------------------------------------
CDrawContext::~CDrawContext ()
{
#ifdef DEBUG
gNbCDrawContext--;
#endif
#if WINDOWS
if (pOldBrush)
SelectObject ((HDC)pSystemContext, pOldBrush);
if (pOldPen)
SelectObject ((HDC)pSystemContext, pOldPen);
if (pOldFont)
SelectObject ((HDC)pSystemContext, pOldFont);
if (pBrush)
DeleteObject (pBrush);
if (pPen)
DeleteObject (pPen);
if (pFont)
DeleteObject (pFont);
#elif MAC
#elif MOTIF
#elif BEOS
if (pView)
{
pView->Flush ();
pView->UnlockLooper ();
}
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::moveTo (const VSTGUI::CPoint &_point)
{
VSTGUI::CPoint point (_point);
point.offset (offset.h, offset.v);
#if WINDOWS
MoveToEx ((HDC)pSystemContext, point.h, point.v, NULL);
#elif MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice); // get current GrafPort
SetGWorld (getPort (), NULL); // activate our GWorld
MoveTo (point.h, point.v);
SetGWorld (OrigPort, OrigDevice);
penLoc = point;
#elif MOTIF || BEOS
penLoc = point;
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::lineTo (const VSTGUI::CPoint& _point)
{
VSTGUI::CPoint point (_point);
point.offset (offset.h, offset.v);
#if WINDOWS
LineTo ((HDC)pSystemContext, point.h, point.v);
#elif MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice); // get current GrafPort
SetGWorld (getPort (), NULL); // activate our GWorld
RGBColor col;
CColor2RGBColor (frameColor, col);
RGBForeColor (&col);
#if 1
if (point.v == penLoc.v)
{
VSTGUI::CPoint old = point;
if (point.h > penLoc.h)
point.h--;
else
point.h++;
penLoc = old;
LineTo (point.h, point.v);
MoveTo (penLoc.h, penLoc.v);
}
else if (point.h == penLoc.h)
{
VSTGUI::CPoint old = point;
if (point.v > penLoc.v)
point.v--;
else
point.v++;
penLoc = old;
LineTo (point.h, point.v);
MoveTo (penLoc.h, penLoc.v);
}
else
{
penLoc = point;
LineTo (point.h, point.v);
}
#else
if (point.v > penLoc.v)
point.v--;
else if (point.v < penLoc.v)
point.v++;
if (point.h > penLoc.h)
point.h--;
else if (point.h < penLoc.h)
point.h++;
penLoc = point;
LineTo (point.h, point.v);
#endif
SetGWorld (OrigPort, OrigDevice);
#elif MOTIF
VSTGUI::CPoint start (penLoc);
VSTGUI::CPoint end (point);
if (start.h == end.h)
{
if (start.v < -5)
start.v = -5;
else if (start.v > 10000)
start.v = 10000;
if (end.v < -5)
end.v = -5;
else if (end.v > 10000)
end.v = 10000;
}
if (start.v == end.v)
{
if (start.h < -5)
start.h = -5;
else if (start.h > 10000)
start.h = 10000;
if (end.h < -5)
end.h = -5;
else if (end.h > 10000)
end.h = 10000;
}
XDrawLine (XDRAWPARAM, start.h, start.v, end.h, end.v);
// keep trace of the new position
penLoc = point;
#elif BEOS
rgb_color c = { frameColor.red, frameColor.green, frameColor.blue, 255 };
pView->SetHighColor (c);
pView->SetDrawingMode (modeToPlatform [drawMode]);
pView->SetPenSize (frameWidth);
lineFromTo (penLoc, point);
penLoc = point;
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::polyLine (const VSTGUI::CPoint *pPoints, long numberOfPoints)
{
#if WINDOWS
POINT points[30];
POINT *polyPoints;
bool allocated = false;
if (numberOfPoints > 30)
{
polyPoints = (POINT*)new char [numberOfPoints * sizeof (POINT)];
if (!polyPoints)
return;
allocated = true;
}
else
polyPoints = points;
for (long i = 0; i < numberOfPoints; i++)
{
polyPoints[i].x = pPoints[i].h + offset.h;
polyPoints[i].y = pPoints[i].v + offset.v;
}
Polyline ((HDC)pSystemContext, polyPoints, numberOfPoints);
if (allocated)
delete[] polyPoints;
#elif MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
RGBColor col;
CColor2RGBColor (frameColor, col);
RGBForeColor (&col);
MoveTo (pPoints[0].h, pPoints[0].v);
for (long i = 1; i < numberOfPoints; i++)
LineTo (pPoints[i].h + offset.h, pPoints[i].v + offset.v);
SetGWorld (OrigPort, OrigDevice);
#elif MOTIF
XPoint* pt = (XPoint*)malloc (numberOfPoints * sizeof (XPoint));
if (!pt)
return;
for (long i = 0; i < numberOfPoints; i++)
{
pt[i].x = (short)pPoints[i].h + offset.h;
pt[i].y = (short)pPoints[i].v + offset.v;
}
XDrawLines (XDRAWPARAM, pt, numberOfPoints, CoordModeOrigin);
free (pt);
#elif BEOS
rgb_color c = { frameColor.red, frameColor.green, frameColor.blue, 255 };
pView->SetHighColor (c);
pView->SetDrawingMode (modeToPlatform [drawMode]);
pView->SetPenSize (frameWidth);
VSTGUI::CPoint begin (pPoints[0]);
begin.offset (offset.h, offset.v);
VSTGUI::CPoint end;
for (long i = 1; i < numberOfPoints; i++)
{
end = pPoints[i];
end.offset (offset.h, offset.v);
lineFromTo (begin, end);
begin = end;
}
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::setLineStyle (CLineStyle style)
{
lineStyle = style;
#if WINDOWS
switch (lineStyle)
{
case kLineOnOffDash:
iPenStyle = PS_DOT;
break;
default:
iPenStyle = PS_SOLID;
break;
}
LOGPEN logPen = {iPenStyle, {frameWidth, frameWidth},
RGB (frameColor.red, frameColor.green, frameColor.blue)};
HANDLE newPen = CreatePenIndirect (&logPen);
SelectObject ((HDC)pSystemContext, newPen);
if (pPen)
DeleteObject (pPen);
pPen = newPen;
#elif MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
if (pWindow)
{
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
PenState penState;
GetPenState (&penState);
switch (lineStyle)
{
case kLineOnOffDash:
StuffHex (&penState.pnPat, "\pF0F0F0F00F0F0F0F"); // dashed line 4 pixel
break;
default:
StuffHex (&penState.pnPat, "\pFFFFFFFFFFFFFFFF");
break;
}
SetPenState (&penState);
SetGWorld (OrigPort, OrigDevice);
}
#elif MOTIF
long line_width;
long line_style;
if (frameWidth == 1)
line_width = 0;
else
line_width = frameWidth;
switch (lineStyle)
{
case kLineOnOffDash:
line_style = LineOnOffDash;
break;
default:
line_style = LineSolid;
break;
}
XSetLineAttributes (XGCPARAM, line_width, line_style, CapNotLast, JoinRound);
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::setLineWidth (long width)
{
frameWidth = width;
#if WINDOWS
LOGPEN logPen = {iPenStyle, {frameWidth, frameWidth},
RGB (frameColor.red, frameColor.green, frameColor.blue)};
HANDLE newPen = CreatePenIndirect (&logPen);
SelectObject ((HDC)pSystemContext, newPen);
if (pPen)
DeleteObject (pPen);
pPen = newPen;
#elif MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
if (pWindow)
{
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
PenState penState;
GetPenState (&penState);
penState.pnSize.h = width;
penState.pnSize.v = width;
SetPenState (&penState);
SetGWorld (OrigPort, OrigDevice);
}
#elif MOTIF
setLineStyle (lineStyle);
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::setDrawMode (CDrawMode mode)
{
if (drawMode == mode)
return;
drawMode = mode;
#if WINDOWS
long iMode = 0;
switch (drawMode)
{
case kXorMode :
iMode = R2_NOTXORPEN; // Pixel is the inverse of the R2_XORPEN color (final pixel = ~ (pen ^ screen pixel)).
break;
case kOrMode :
iMode = R2_MERGEPEN; // Pixel is a combination of the pen color and the screen color (final pixel = pen | screen pixel).
break;
default:
iMode = R2_COPYPEN;
break;
}
SetROP2 ((HDC)pSystemContext, iMode);
#elif MAC
if (pWindow)
{
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
long iMode = 0;
switch (drawMode)
{
case kXorMode :
iMode = patXor;
break;
case kOrMode :
iMode = patOr;
break;
default:
iMode = patCopy;
}
PenMode (mode);
SetGWorld (OrigPort, OrigDevice);
}
#elif MOTIF
long iMode = 0;
switch (drawMode)
{
case kXorMode :
iMode = GXinvert;
break;
case kOrMode :
iMode = GXor;
break;
default:
iMode = GXcopy;
}
((XGCValues*)pSystemContext)->function = iMode;
XChangeGC (XGCPARAM, GCFunction, (XGCValues*)pSystemContext);
#endif
}
//------------------------------------------------------------------------------
void CDrawContext::setClipRect (const VSTGUI::CRect &clip)
{
clipRect = clip;
#if MAC
Rect r;
CRect2Rect (clip, r);
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
ClipRect (&r);
SetGWorld (OrigPort, OrigDevice);
#elif WINDOWS
RECT r = {clip.left, clip.top, clip.right, clip.bottom};
HRGN hRgn = CreateRectRgn (r.left, r.top, r.right, r.bottom);
SelectClipRgn ((HDC)pSystemContext, hRgn);
DeleteObject (hRgn);
#elif MOTIF
XRectangle r;
r.x = 0;
r.y = 0;
r.width = clip.right - clip.left;
r.height = clip.bottom - clip.top;
XSetClipRectangles (XGCPARAM, clip.left, clip.top, &r, 1, Unsorted);
#elif BEOS
clipping_rect r = {clip.left, clip.top, clip.right - 1, clip.bottom - 1};
BRegion region;
region.Set (r);
pView->ConstrainClippingRegion (®ion);
#endif
}
//------------------------------------------------------------------------------
void CDrawContext::resetClipRect ()
{
VSTGUI::CRect newClip;
if (pFrame)
pFrame->getViewSize (newClip);
else
newClip (0, 0, 1000, 1000);
#if MAC || WINDOWS || MOTIF
setClipRect (newClip);
#elif BEOS
pView->ConstrainClippingRegion (NULL);
#endif
clipRect = newClip;
}
//-----------------------------------------------------------------------------
void CDrawContext::fillPolygon (const VSTGUI::CPoint *pPoints, long numberOfPoints)
{
// Don't draw boundary
#if WINDOWS
POINT points[30];
POINT *polyPoints;
bool allocated = false;
if (numberOfPoints > 30)
{
polyPoints = (POINT*)new char [numberOfPoints * sizeof (POINT)];
if (!polyPoints)
return;
allocated = true;
}
else
polyPoints = points;
for (long i = 0; i < numberOfPoints; i++)
{
polyPoints[i].x = pPoints[i].h + offset.h;
polyPoints[i].y = pPoints[i].v + offset.v;
}
HANDLE nullPen = GetStockObject (NULL_PEN);
HANDLE oldPen = SelectObject ((HDC)pSystemContext, nullPen);
Polygon ((HDC)pSystemContext, polyPoints, numberOfPoints);
SelectObject ((HDC)pSystemContext, oldPen);
if (allocated)
delete[] polyPoints;
#elif MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
PolyHandle thePoly;
RGBColor col;
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
CColor2RGBColor (fillColor, col);
RGBForeColor (&col);
thePoly = OpenPoly (); // start recording
polyLine (pPoints, numberOfPoints); // draw polygon
LineTo (pPoints[0].h + offset.h, pPoints[0].v + offset.v); // close the boundary
ClosePoly (); // stop recording
PixPatHandle pixPatHandle = NewPixPat ();
CColor2RGBColor (fillColor, col);
MakeRGBPat (pixPatHandle, &col); // create pixel pattern with fill color
FillCPoly (thePoly, pixPatHandle); // fill inside
KillPoly (thePoly); // deallocate all memory used here
DisposePixPat (pixPatHandle);
SetGWorld (OrigPort, OrigDevice);
#elif MOTIF
// convert the points
XPoint* pt = (XPoint*)malloc (numberOfPoints * sizeof (XPoint));
for (long i = 0; i < numberOfPoints; i++)
{
pt[i].x = (short)pPoints[i].h + offset.h;
pt[i].y = (short)pPoints[i].v + offset.v;
}
XFillPolygon (XDRAWPARAM, pt, numberOfPoints, Convex, CoordModeOrigin);
free (pt);
#elif BEOS
BPoint bpoints[30];
BPoint* polyPoints;
bool allocated = false;
if (numberOfPoints > 30)
{
polyPoints = new BPoint [numberOfPoints];
if (!polyPoints)
return;
allocated = true;
}
else
polyPoints = bpoints;
for (long i = 0; i < numberOfPoints; i++)
polyPoints[i].Set (pPoints[i].h + offset.h, pPoints[i].v + offset.v);
rgb_color c = { fillColor.red, fillColor.green, fillColor.blue, 255 };
pView->SetHighColor (c);
pView->SetDrawingMode (modeToPlatform [drawMode]);
pView->FillPolygon (polyPoints, numberOfPoints);
if (allocated)
delete[] polyPoints;
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::drawRect (const VSTGUI::CRect &_rect)
{
VSTGUI::CRect rect (_rect);
rect.offset (offset.h, offset.v);
#if WINDOWS
MoveToEx ((HDC)pSystemContext, rect.left, rect.top, NULL);
LineTo ((HDC)pSystemContext, rect.right, rect.top);
LineTo ((HDC)pSystemContext, rect.right, rect.bottom);
LineTo ((HDC)pSystemContext, rect.left, rect.bottom);
LineTo ((HDC)pSystemContext, rect.left, rect.top);
#elif MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice); // get current GrafPort
SetGWorld (getPort (), NULL); // activate our GWorld
RGBColor col;
CColor2RGBColor (frameColor, col);
RGBForeColor (&col);
MoveTo (rect.left, rect.top);
LineTo (rect.right, rect.top);
LineTo (rect.right, rect.bottom);
LineTo (rect.left, rect.bottom);
LineTo (rect.left, rect.top);
SetGWorld (OrigPort, OrigDevice);
#elif MOTIF
XDrawRectangle (XDRAWPARAM, rect.left, rect.top, rect.width (), rect.height ());
#elif BEOS
rgb_color c = { frameColor.red, frameColor.green, frameColor.blue, 255 };
pView->SetHighColor (c);
pView->SetDrawingMode (modeToPlatform [drawMode]);
BRect r (rect.left, rect.top, rect.right, rect.bottom);
pView->SetPenSize (frameWidth);
pView->StrokeRect (r);
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::fillRect (const VSTGUI::CRect &_rect)
{
VSTGUI::CRect rect (_rect);
rect.offset (offset.h, offset.v);
// Don't draw boundary
#if WINDOWS
RECT wr = {rect.left + 1, rect.top + 1, rect.right, rect.bottom};
HANDLE nullPen = GetStockObject (NULL_PEN);
HANDLE oldPen = SelectObject ((HDC)pSystemContext, nullPen);
FillRect ((HDC)pSystemContext, &wr, (HBRUSH)pBrush);
SelectObject ((HDC)pSystemContext, oldPen);
#elif MAC
Rect rr;
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
RGBColor col;
CColor2RGBColor (fillColor, col);
RGBForeColor (&col);
CRect2Rect (rect, rr);
rr.left++;
rr.top++;
FillRect (&rr, &fillPattern);
SetGWorld (OrigPort, OrigDevice);
#elif MOTIF
XFillRectangle (XDRAWPARAM, rect.left + 1, rect.top + 1, rect.width () - 1, rect.height () - 1);
#elif BEOS
rgb_color c = { fillColor.red, fillColor.green, fillColor.blue, 255 };
pView->SetHighColor (c);
pView->SetDrawingMode (modeToPlatform [drawMode]);
BRect r (rect.left + 1, rect.top + 1, rect.right - 1, rect.bottom - 1);
pView->FillRect (r);
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::drawEllipse (const VSTGUI::CRect &_rect)
{
VSTGUI::CPoint point (_rect.left + (_rect.right - _rect.left) / 2, _rect.top);
drawArc (_rect, point, point);
}
//-----------------------------------------------------------------------------
void CDrawContext::fillEllipse (const VSTGUI::CRect &_rect)
{
VSTGUI::CRect rect (_rect);
rect.offset (offset.h, offset.v);
// Don't draw boundary
#if WINDOWS
HANDLE nullPen = GetStockObject (NULL_PEN);
HANDLE oldPen = SelectObject ((HDC)pSystemContext, nullPen);
Ellipse ((HDC)pSystemContext, rect.left + 1, rect.top + 1, rect.right + 1, rect.bottom + 1);
SelectObject ((HDC)pSystemContext, oldPen);
#else
VSTGUI::CPoint point (_rect.left + ((_rect.right - _rect.left) / 2), _rect.top);
fillArc (_rect, point, point);
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::drawPoint (const VSTGUI::CPoint &_point, CColor color)
{
VSTGUI::CPoint point (_point);
point.offset (offset.h, offset.v);
#if WINDOWS
SetPixel ((HDC)pSystemContext, point.h, point.v, RGB(color.red, color.green, color.blue));
#elif MOTIF
CColor oldframecolor = frameColor;
setFrameColor (color);
XDrawPoint (XDRAWPARAM, point.h, point.v);
setFrameColor (oldframecolor);
#elif MAC
int oldframeWidth = frameWidth;
CColor oldframecolor = frameColor;
setLineWidth (1);
setFrameColor (color);
VSTGUI::CPoint point2 (point);
point2.h++;
moveTo (point);
lineTo (point2);
setFrameColor (oldframecolor);
setLineWidth (oldframeWidth);
#else
int oldframeWidth = frameWidth;
CColor oldframecolor = frameColor;
setLineWidth (1);
setFrameColor (color);
moveTo (point);
lineTo (point);
setFrameColor (oldframecolor);
setLineWidth (oldframeWidth);
#endif
}
//-----------------------------------------------------------------------------
CColor CDrawContext::getPoint (const VSTGUI::CPoint& _point)
{
VSTGUI::CPoint point (_point);
point.offset (offset.h, offset.v);
CColor color = kBlackCColor;
#if WINDOWS
COLORREF c = GetPixel ((HDC)pSystemContext, point.h, point.v);
color.red = GetRValue (c);
color.green = GetGValue (c);
color.blue = GetBValue (c);
#elif MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
RGBColor cPix;
GetCPixel (point.h, point.v, &cPix);
RGBColor2CColor (cPix, color);
SetGWorld (OrigPort, OrigDevice);
#endif
return color;
}
//-----------------------------------------------------------------------------
void CDrawContext::floodFill (const VSTGUI::CPoint& _start)
{
VSTGUI::CPoint start (_start);
start.offset (offset.h, offset.v);
#if WINDOWS
COLORREF c = GetPixel ((HDC)pSystemContext, start.h, start.v);
ExtFloodFill ((HDC)pSystemContext, start.h, start.v, c, FLOODFILLSURFACE);
#elif MAC
CGrafPtr oldPort;
GDHandle oldDevice;
GetGWorld (&oldPort, &oldDevice);
SetGWorld (getPort (), 0);
Rect r;
GetPortBounds (getPort (), &r);
GWorldPtr pMask;
OSErr err = NewGWorld ((GWorldPtr*)&pMask, 1, &r, 0, 0, 0); // create monochrome GWorld
if (!err)
{
// generate fill mask
PixMapHandle srcBits = GetGWorldPixMap (getPort ());
PixMapHandle dstBits = GetGWorldPixMap (pMask);
if (srcBits && dstBits)
{
LockPixels (srcBits);
LockPixels (dstBits);
SeedCFill ((BitMapPtr)*srcBits, (BitMapPtr)*dstBits, &r, &r, start.h, start.v, 0, 0);
// fill destination
RGBColor oldForeColor, oldBackColor;
GetForeColor (&oldForeColor);
GetBackColor (&oldBackColor);
::BackColor (whiteColor);
RGBColor col;
CColor2RGBColor (fillColor, col);
RGBForeColor (&col);
CopyMask ((BitMapPtr)*dstBits, (BitMapPtr)*dstBits, (BitMapPtr)*srcBits, &r, &r, &r);
RGBForeColor (&oldForeColor);
RGBBackColor (&oldBackColor);
// cleanup
UnlockPixels (srcBits);
UnlockPixels (dstBits);
}
DisposeGWorld (pMask);
}
SetGWorld (oldPort, oldDevice);
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::drawArc (const VSTGUI::CRect &_rect, const VSTGUI::CPoint &_point1, const VSTGUI::CPoint &_point2)
{
VSTGUI::CRect rect (_rect);
rect.offset (offset.h, offset.v);
VSTGUI::CPoint point1 (_point1);
point1.offset (offset.h, offset.v);
VSTGUI::CPoint point2 (_point2);
point2.offset (offset.h, offset.v);
// draws from point1 to point2 counterclockwise
#if WINDOWS
Arc ((HDC)pSystemContext, rect.left, rect.top, rect.right + 1, rect.bottom + 1,
point1.h, point1.v, point2.h, point2.v);
#elif MAC || MOTIF || BEOS
int angle1, angle2;
if ((point1.v == point2.v) && (point1.h == point2.h))
{
angle1 = 0;
angle2 = 23040; // 360 * 64
}
else
{
VSTGUI::CPoint pm ((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2);
angle1 = convertPoint2Angle (pm, point1);
angle2 = convertPoint2Angle (pm, point2) - angle1;
if (angle2 < 0)
angle2 += 23040; // 360 * 64
}
#if MAC
Rect rr;
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
RGBColor col;
CColor2RGBColor (frameColor, col);
RGBForeColor (&col);
CRect2Rect (rect, rr);
FrameArc (&rr, 90 - (angle1 / 64), -angle2 / 64);
SetGWorld (OrigPort, OrigDevice);
#elif MOTIF
XDrawArc (XDRAWPARAM, rect.left, rect.top, rect.width (), rect.height (),
angle1, angle2);
#elif BEOS
rgb_color c = { frameColor.red, frameColor.green, frameColor.blue, 255 };
pView->SetHighColor (c);
pView->SetDrawingMode (modeToPlatform [drawMode]);
BRect r (rect.left, rect.top, rect.right, rect.bottom);
pView->SetPenSize (frameWidth);
pView->StrokeArc (r, angle1 / 64, angle2 / 64);
#endif
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::fillArc (const VSTGUI::CRect &_rect, const VSTGUI::CPoint &_point1, const VSTGUI::CPoint &_point2)
{
VSTGUI::CRect rect (_rect);
rect.offset (offset.h, offset.v);
VSTGUI::CPoint point1 (_point1);
point1.offset (offset.h, offset.v);
VSTGUI::CPoint point2 (_point2);
point2.offset (offset.h, offset.v);
// Don't draw boundary
#if WINDOWS
HANDLE nullPen = GetStockObject(NULL_PEN);
HANDLE oldPen = SelectObject ((HDC)pSystemContext, nullPen);
Pie ((HDC)pSystemContext, offset.h + rect.left + 1, offset.v + rect.top + 1, offset.h + rect.right, offset.v + rect.bottom,
point1.h, point1.v, point2.h, point2.v);
SelectObject ((HDC)pSystemContext, oldPen);
#elif MAC || MOTIF || BEOS
int angle1, angle2;
if ((point1.v == point2.v) && (point1.h == point2.h))
{
angle1 = 0;
angle2 = 23040; // 360 * 64
}
else
{
VSTGUI::CPoint pm ((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2);
angle1 = convertPoint2Angle (pm, point1);
angle2 = convertPoint2Angle (pm, point2);
}
#if MAC
Rect rr;
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
RGBColor col;
CColor2RGBColor (fillColor, col);
RGBForeColor (&col);
CRect2Rect (rect, rr);
angle2 = angle2 - angle1;
if (angle2 < 0)
angle2 = -angle2;
FillArc (&rr, 90 - (angle1 / 64), -angle2 / 64, &fillPattern);
SetGWorld (OrigPort, OrigDevice);
#elif MOTIF
XFillArc (XDRAWPARAM, rect.left, rect.top, rect.width (), rect.height (),
angle1, angle2);
#elif BEOS
rgb_color c = { fillColor.red, fillColor.green, fillColor.blue, 255 };
pView->SetHighColor (c);
pView->SetDrawingMode (modeToPlatform [drawMode]);
BRect r (rect.left + 1, rect.top + 1, rect.right - 1, rect.bottom - 1);
pView->FillArc (r, angle1 / 64, angle2 / 64);
#endif
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::setFontColor (const CColor color)
{
fontColor = color;
#if WINDOWS
SetTextColor ((HDC)pSystemContext, RGB (fontColor.red, fontColor.green, fontColor.blue));
#elif MAC
RGBColor col;
CGrafPtr OrigPort;
GDHandle OrigDevice;
if (pWindow)
{
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
CColor2RGBColor (fontColor, col);
RGBForeColor (&col);
SetGWorld (OrigPort, OrigDevice);
}
#elif MOTIF
setFrameColor (fontColor);
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::setFrameColor (const CColor color)
{
frameColor = color;
#if WINDOWS
LOGPEN logPen = {iPenStyle, {frameWidth, frameWidth},
RGB (frameColor.red, frameColor.green, frameColor.blue)};
HANDLE newPen = CreatePenIndirect (&logPen);
SelectObject ((HDC)pSystemContext, newPen);
if (pPen)
DeleteObject (pPen);
pPen = newPen;
#elif MAC
RGBColor col;
CGrafPtr OrigPort;
GDHandle OrigDevice;
if (pWindow)
{
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
CColor2RGBColor (frameColor, col);
RGBForeColor (&col);
SetGWorld (OrigPort, OrigDevice);
}
#elif MOTIF
XSetForeground (XGCPARAM, getIndexColor (frameColor));
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::setFillColor (const CColor color)
{
fillColor = color;
#if WINDOWS
SetBkColor ((HDC)pSystemContext, RGB (color.red, color.green, color.blue));
LOGBRUSH logBrush = {BS_SOLID, RGB (color.red, color.green, color.blue), 0 };
HANDLE newBrush = CreateBrushIndirect (&logBrush);
if (newBrush == 0)
{
DWORD err = GetLastError ();
return;
}
SelectObject ((HDC)pSystemContext, newBrush);
if (pBrush)
DeleteObject (pBrush);
pBrush = newBrush;
#elif MAC
RGBColor col;
CGrafPtr OrigPort;
GDHandle OrigDevice;
if (pWindow)
{
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
CColor2RGBColor (fillColor, col);
RGBForeColor (&col);
SetGWorld (OrigPort, OrigDevice);
}
#elif MOTIF
// set the background for the text
XSetBackground (XGCPARAM, getIndexColor (fillColor));
// set the foreground for the fill
setFrameColor (fillColor);
#endif
}
//-----------------------------------------------------------------------------
void CDrawContext::setFont (CFont fontID, const long size, long style)
{
if (fontID < 0 || fontID >= kNumStandardFonts)
fontID = kSystemFont;
fontId = fontID;
if (size != 0)
fontSize = size;
else
fontSize = standardFontSize [fontID];
#if WINDOWS
LOGFONT logfont = {0};
if (style & kBoldFace)
logfont.lfWeight = FW_BOLD;
else
logfont.lfWeight = FW_NORMAL;
if (style & kItalicFace)
logfont.lfItalic = true;
if (style & kUnderlineFace)
logfont.lfUnderline = true;
logfont.lfHeight = -fontSize;
logfont.lfPitchAndFamily = VARIABLE_PITCH | FF_SWISS;
strcpy (logfont.lfFaceName, standardFontName[fontID]);
if (fontID == kSymbolFont)
logfont.lfPitchAndFamily = DEFAULT_PITCH | FF_DECORATIVE;
else if (fontID == kSystemFont)
logfont.lfWeight = FW_BOLD;
logfont.lfClipPrecision = CLIP_STROKE_PRECIS;
logfont.lfOutPrecision = OUT_STRING_PRECIS;
logfont.lfQuality = DEFAULT_QUALITY;
logfont.lfCharSet = ANSI_CHARSET;
HANDLE newFont = CreateFontIndirect (&logfont);
SelectObject ((HDC)pSystemContext, newFont);
if (pFont)
DeleteObject (pFont);
pFont = newFont;
#elif MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
if (pWindow)
{
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
TextFace (style); // normal, bold, italic, underline...
TextMode (0);
TextSize (fontSize);
#if MACX
short familyID;
GetFNum (macXfontNames[fontID], &familyID);
TextFont (familyID);
#else
if (fontID == kSymbolFont)
TextFont (kFontIDSymbol);
else if (fontID == kSystemFont)
TextFont (0); // system
else if (fontID == kNormalFontSmaller)
TextFont (kFontIDGeneva); // Geneva
else
TextFont (kFontIDHelvetica);
#endif
GetFontInfo (&fontInfoStruct);
SetGWorld (OrigPort, OrigDevice);
}
#elif MOTIF
XSetFont (XGCPARAM, fontStructs[fontID]->fid);
// keep trace of the current font
pFontInfoStruct = fontStructs[fontID];
#elif BEOS
font.SetFamilyAndStyle (standardFontName[fontID], standardFontStyle[fontID]);
font.SetSize (fontSize);
pView->SetFont (&font, B_FONT_FAMILY_AND_STYLE | B_FONT_SIZE);
#endif
}
//------------------------------------------------------------------------------
long CDrawContext::getStringWidth (const char *pStr)
{
long result = 0;
#if MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
result = (long)TextWidth (pStr, 0, strlen (pStr));
SetGWorld (OrigPort, OrigDevice);
#elif WINDOWS
SIZE size;
GetTextExtentPoint32 ((HDC)pSystemContext, pStr, strlen (pStr), &size);
result = (long)size.cx;
#elif MOTIF
result = (long)XTextWidth (pFontInfoStruct, pStr, strlen (pStr));
#elif BEOS
result = (long)(ceil (pView->StringWidth (pStr)));
#endif
return result;
}
//-----------------------------------------------------------------------------
void CDrawContext::drawString (const char *string, const VSTGUI::CRect &_rect,
const short opaque, const CHoriTxtAlign hAlign)
{
if (!string)
return;
VSTGUI::CRect rect (_rect);
rect.offset (offset.h, offset.v);
#if WINDOWS
// set the visibility mask
SetBkMode ((HDC)pSystemContext, opaque ? OPAQUE : TRANSPARENT);
RECT Rect = {rect.left, rect.top, rect.right, rect.bottom};
UINT flag = DT_VCENTER + DT_SINGLELINE + DT_NOPREFIX;
switch (hAlign)
{
case kCenterText:
// without DT_SINGLELINE no vertical center alignment here
DrawText ((HDC)pSystemContext, string, strlen (string), &Rect, flag + DT_CENTER);
break;
case kRightText:
DrawText ((HDC)pSystemContext, string, strlen (string), &Rect, flag + DT_RIGHT);
break;
default : // left adjust
Rect.left++;
DrawText ((HDC)pSystemContext, string, strlen (string), &Rect, flag + DT_LEFT);
}
SetBkMode ((HDC)pSystemContext, TRANSPARENT);
#elif MAC
CGrafPtr OrigPort;
GDHandle OrigDevice;
int width;
int xPos, yPos;
int fontHeight;
int rectHeight;
int stringLength;
Rect stringsRect;
Rect contextsClip;
Rect compositeClip;
CRect2Rect (rect, stringsRect);
CRect2Rect (clipRect, contextsClip);
if (SectRect (&stringsRect, &contextsClip, &compositeClip))
{
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld (getPort (), NULL);
if (opaque)
TextMode (srcCopy);
else
TextMode (srcOr);
RGBColor col;
CColor2RGBColor (fontColor, col);
RGBForeColor (&col);
CColor2RGBColor (fillColor, col);
RGBBackColor (&col);
rectHeight = rect.height ();
fontHeight = fontInfoStruct.ascent + fontInfoStruct.descent;
yPos = rect.bottom - fontInfoStruct.descent;
if (rectHeight >= fontHeight)
yPos -= (rectHeight - fontHeight) / 2;
stringLength = strlen (string);
width = TextWidth ((Ptr)string, 0, stringLength);
switch (hAlign)
{
case kCenterText:
xPos = (rect.right + rect.left - width) / 2;
break;
case kRightText:
xPos = rect.right - width;
break;
default: // left adjust
xPos = rect.left;
}
RgnHandle saveRgn = NewRgn ();
GetClip (saveRgn);
ClipRect (&compositeClip);
MoveTo (xPos, yPos);
DrawText ((Ptr)string, 0, stringLength);
SetClip (saveRgn);
DisposeRgn (saveRgn);
TextMode (srcOr);
SetGWorld (OrigPort, OrigDevice);
}
#elif MOTIF
int width;
int fontHeight = pFontInfoStruct->ascent + pFontInfoStruct->descent;
int xPos;
int yPos;
int rectHeight = rect.height ();
if (rectHeight >= fontHeight)
yPos = rect.bottom - (rectHeight - fontHeight) / 2;
else
yPos = rect.bottom;
yPos -= pFontInfoStruct->descent;
switch (hAlign)
{
case kCenterText:
width = XTextWidth (pFontInfoStruct, string, strlen (string));
xPos = (rect.right + rect.left - width) / 2;
break;
case kRightText:
width = XTextWidth (pFontInfoStruct, string, strlen (string));
xPos = rect.right - width;
break;
default: // left adjust
xPos = rect.left + 1;
}
if (opaque)
XDrawImageString (XDRAWPARAM, xPos, yPos, string, strlen (string));
else
XDrawString (XDRAWPARAM, xPos, yPos, string, strlen (string));
#elif BEOS
BRect r (rect.left, rect.top, rect.right - 1, rect.bottom - 1);
BRegion LocalRegion (r);
pView->ConstrainClippingRegion (&LocalRegion);
pView->SetFontSize (fontSize);
float width = -1;
if (opaque)
{
width = ceil (pView->StringWidth (string));
VSTGUI::CRect cr (rect.left, rect.top, rect.left + width, rect.bottom);
fillRect (cr);
}
rgb_color c = { fontColor.red, fontColor.green, fontColor.blue, 255 };
pView->SetHighColor (c);
if (drawMode == kXorMode)
pView->SetDrawingMode (B_OP_INVERT);
else
pView->SetDrawingMode (B_OP_OVER);
BPoint p;
font_height height;
pView->GetFontHeight (&height);
p.y = r.bottom - (rect.height () - height.ascent) / 2;
if (hAlign == kCenterText || hAlign == kRightText)
{
if (width < 0)
width = ceil (pView->StringWidth (string));
if (hAlign == kCenterText)
p.x = rect.left + (rect.right - rect.left - width) / 2;
else
p.x = rect.right - width - 1;
}
else
p.x = rect.left + 1;
pView->DrawString (string, p);
pView->ConstrainClippingRegion (NULL);
#endif
}
//-----------------------------------------------------------------------------
long CDrawContext::getMouseButtons ()
{
long buttons = 0;
#if WINDOWS
if (GetAsyncKeyState (VK_LBUTTON) < 0)
buttons |= (swapped_mouse_buttons ? kRButton : kLButton);
if (GetAsyncKeyState (VK_MBUTTON) < 0)
buttons |= kMButton;
if (GetAsyncKeyState (VK_RBUTTON) < 0)
buttons |= (swapped_mouse_buttons ? kLButton : kRButton);
if (GetAsyncKeyState (VK_SHIFT) < 0)
buttons |= kShift;
if (GetAsyncKeyState (VK_CONTROL) < 0)
buttons |= kControl;
if (GetAsyncKeyState (VK_MENU) < 0)
buttons |= kAlt;
#elif MAC
#if MACX // this works for MacOSX 10.2 and later
UInt32 state = GetCurrentButtonState ();
if (state & kEventMouseButtonPrimary)
buttons |= kLButton;
if (state & kEventMouseButtonSecondary)
buttons |= kRButton;
if (state & 4)//kEventMouseButtonTertiary) this define is false...Apple ?
buttons |= kMButton;
state = GetCurrentKeyModifiers ();
if (state & cmdKey)
buttons |= kControl;
if (state & shiftKey)
buttons |= kShift;
if (state & optionKey)
buttons |= kAlt;
if (state & controlKey)
buttons |= kApple;
// for the one buttons
if (buttons & kApple && buttons & kLButton)
{
buttons &= ~(kApple | kLButton);
buttons |= kRButton;
}
#else
if (Button ())
buttons |= kLButton;
KeyMap Keys;
unsigned char *BytePtr = (unsigned char*)Keys;
GetKeys (Keys);
if (BytePtr[7] & 1) // Shift 0x38 == 56 = (7 * 8) + 0
buttons |= kShift;
if (BytePtr[7] & 8) // Control (extra Mac) 0x3B == 59 = (7 * 8) + 3
buttons |= kApple;
if (BytePtr[7] & 4) // Alt 0x3A == 58 = (7 * 8) + 2
buttons |= kAlt;
if (BytePtr[6] & 128) // Apple => ctrl (PC) 0x37 == 55 = (6 * 8) + 7
buttons |= kControl;
#endif
#elif MOTIF
Window root, child;
long rootX, rootY, childX, childY;
unsigned int mask;
int result = XQueryPointer (XWINPARAM, &root, &child, &rootX, &rootY,
&childX, &childY, &mask);
if (mask & Button1Mask)
buttons |= kLButton;
if (mask & Button2Mask)
buttons |= kMButton;
if (mask & Button3Mask)
buttons |= kRButton;
if (mask & ShiftMask)
buttons |= kShift;
if (mask & ControlMask)
buttons |= kControl;
if (mask & Mod1Mask)
buttons |= kAlt;
#elif BEOS
BPoint where;
uint32 b;
pView->GetMouse (&where, &b);
if (b & B_PRIMARY_MOUSE_BUTTON)
buttons |= kLButton;
if (b & B_SECONDARY_MOUSE_BUTTON)
buttons |= kRButton;
if (b & B_TERTIARY_MOUSE_BUTTON)
buttons |= kMButton;
int32 m = modifiers ();
if (m & B_SHIFT_KEY)
buttons |= kShift;
if (m & B_COMMAND_KEY)
buttons |= kControl;
if (m & B_OPTION_KEY)
buttons |= kApple;
if (m & B_CONTROL_KEY)
buttons |= kAlt;
#endif
return buttons;
}
//-----------------------------------------------------------------------------
void CDrawContext::getMouseLocation (VSTGUI::CPoint &point)
{
#if WINDOWS
POINT where;
GetCursorPos (&where);
point (where.x, where.y);
#elif MAC
Point where;
GetMouse (&where);
point (where.h, where.v);
#elif MOTIF
Window root, child;
int rootX, rootY, childX, childY;
unsigned int mask;
int result = XQueryPointer (XWINPARAM, &root, &child, &rootX, &rootY,
&childX, &childY, &mask);
point (childX, childY);
#elif BEOS
BPoint where;
uint32 b;
pView->GetMouse (&where, &b);
point (where.x, where.y);
#endif
point.offset (-offsetScreen.h, -offsetScreen.v);
}
//-----------------------------------------------------------------------------
bool CDrawContext::waitDoubleClick ()
{
bool doubleClick = false;
#if WINDOWS
VSTGUI::CPoint mouseLoc;
getMouseLocation (mouseLoc);
VSTGUI::CRect observe (mouseLoc.h - 2, mouseLoc.v - 2, mouseLoc.h + 2, mouseLoc.v + 2);
DWORD currentTime = GetTickCount ();
DWORD clickTime = GetMessageTime () + (DWORD)GetDoubleClickTime ();
MSG message;
while (currentTime < clickTime)
{
getMouseLocation (mouseLoc);
if (!observe.pointInside (mouseLoc))
break;
if (PeekMessage (&message, 0, WM_LBUTTONDOWN, WM_LBUTTONDOWN, PM_REMOVE | PM_NOYIELD))
{
doubleClick = true;
break;
}
currentTime = GetTickCount ();
}
#elif MAC
#if MACX
unsigned long clickTime, doubletime;
EventRecord downEvent;
doubletime = GetDblTime ();
clickTime = TickCount () + doubletime;
while (TickCount () < clickTime)
{
if (GetNextEvent (mDownMask, &downEvent))
{
doubleClick = true;
break;
}
}
#else
long clickTime, doubleTime;
EventRecord downEvent;
#define MOUSE_IS_DOWN ((* (char*)0x172) >= 0)
doubleTime = GetDblTime () / 2;
clickTime = TickCount () + doubleTime;
while (TickCount () < clickTime)
if (!MOUSE_IS_DOWN) break; /* look for mouse up! */
if (GetNextEvent (mUpMask, &downEvent))
{
clickTime += doubleTime;
while (TickCount () < clickTime)
if (MOUSE_IS_DOWN) break; /* look for mouse down! */
if (GetNextEvent (mDownMask, &downEvent))
doubleClick = true;
}
#endif
#elif MOTIF
long currentTime = _getTicks ();
long clickTime = currentTime + XtGetMultiClickTime (pDisplay);
XEvent e;
while (currentTime < clickTime)
{
if (XCheckTypedEvent (pDisplay, ButtonPress, &e))
{
doubleClick = true;
break;
}
currentTime = _getTicks ();
}
#elif BEOS
const bigtime_t snoozeTime = 5000;
bigtime_t latest = system_time ();
bigtime_t doubleclicktime;
get_click_speed (&doubleclicktime);
latest += doubleclicktime;
BPoint location;
uint32 buttons;
pView->GetMouse (&location, &buttons);
while (buttons) // user should release the mouse button
{
if (system_time () > latest)
return false;
snooze (snoozeTime);
pView->GetMouse (&location, &buttons);
}
while (!buttons)
{
if (system_time () > latest)
return false;
snooze (snoozeTime);
pView->GetMouse (&location, &buttons);
}
doubleClick = true;
#endif
return doubleClick;
}
//-----------------------------------------------------------------------------
bool CDrawContext::waitDrag ()
{
if (!pFrame)
return false;
VSTGUI::CPoint mouseLoc;
getMouseLocation (mouseLoc);
VSTGUI::CRect observe (mouseLoc.h - 2, mouseLoc.v - 2, mouseLoc.h + 2, mouseLoc.v + 2);
long currentTime = pFrame->getTicks ();
bool wasOutside = false;
while (((getMouseButtons () & ~(kMButton|kRButton)) & kLButton) != 0)
{
pFrame->doIdleStuff ();
if (!wasOutside)
{
getMouseLocation (mouseLoc);
if (!observe.pointInside (mouseLoc))
{
if (kDragDelay <= 0)
return true;
wasOutside = true;
}
}
if (wasOutside && (pFrame->getTicks () - currentTime > kDragDelay))
return true;
}
return false;
}
//-----------------------------------------------------------------------------
#if MOTIF
//-----------------------------------------------------------------------------
long CDrawContext::getIndexColor (CColor color)
{
// 24bit visual ?
if (pFrame->getDepth () == 24)
return (unsigned int)color.blue << 16 | (unsigned int)color.green << 8 | (unsigned int)color.red;
// 8bit stuff
return getIndexColor8Bit (color, pDisplay, pFrame->getColormap ());
}
//-----------------------------------------------------------------------------
Colormap CDrawContext::getColormap ()
{
if (pFrame)
return pFrame->getColormap ();
else
return NULL;
}
//-----------------------------------------------------------------------------
Visual* CDrawContext::getVisual ()
{
if (pFrame)
return pFrame->getVisual ();
else
return NULL;
}
//-----------------------------------------------------------------------------
unsigned int CDrawContext::getDepth ()
{
if (pFrame)
return pFrame->getDepth ();
else
return NULL;
}
//-----------------------------------------------------------------------------
#elif BEOS
//-----------------------------------------------------------------------------
void CDrawContext::lineFromTo (VSTGUI::CPoint& cstart, VSTGUI::CPoint& cend)
{
BPoint start (cstart.h, cstart.v);
BPoint end (cend.h, cend.v);
if (start.x == end.x)
{
if (start.y < end.y)
end.y--;
else if (end.y < start.y)
start.y--;
}
else if (start.y == end.y)
{
if (start.x < end.x)
end.x--;
else if (end.x < start.x)
start.x--;
}
else
{
if (start.x > end.x)
{
BPoint t = end;
end = start;
start = t;
}
end.x--;
if (end.y > start.y)
end.y--;
else
end.y++;
}
pView->MovePenTo (start);
if (lineStyle == kLineSolid)
pView->StrokeLine (end);
else
{
pattern stripes = { {0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3} };
pView->StrokeLine (end, stripes);
}
}
//-----------------------------------------------------------------------------
#elif MAC
BitMapPtr CDrawContext::getBitmap ()
{
PixMapHandle pixMap = GetPortPixMap (GetWindowPort ((WindowRef)pWindow));
if (pixMap)
{
LockPixels (pixMap);
return (BitMapPtr)*pixMap;
}
return 0;
}
//-----------------------------------------------------------------------------
void CDrawContext::releaseBitmap ()
{
PixMapHandle pixMap = GetPortPixMap (GetWindowPort ((WindowRef)pWindow));
UnlockPixels (pixMap);
}
//-----------------------------------------------------------------------------
CGrafPtr CDrawContext::getPort ()
{
if (!bInitialized)
{
CGrafPtr OrigPort;
GDHandle OrigDevice;
GetGWorld (&OrigPort, &OrigDevice);
SetGWorld ((CGrafPtr)GetWindowPort ((WindowRef)pWindow), NULL);
TextMode (srcOr);
PenMode (patCopy);
StuffHex (&fillPattern, "\pFFFFFFFFFFFFFFFF");
SetGWorld (OrigPort, OrigDevice);
bInitialized = true;
}
return (CGrafPtr)GetWindowPort ((WindowRef)pWindow);
}
#endif
//-----------------------------------------------------------------------------
// COffscreenContext Implementation
//-----------------------------------------------------------------------------
COffscreenContext::COffscreenContext (CDrawContext *pContext, CBitmap *pBitmapBg, bool drawInBitmap)
: CDrawContext (pContext->pFrame, NULL, NULL),
pBitmap (0), pBitmapBg (pBitmapBg), height (20), width (20)
{
if (pBitmapBg)
{
height = pBitmapBg->getHeight ();
width = pBitmapBg->getWidth ();
clipRect (0, 0, width, height);
}
#ifdef DEBUG
gNbCOffscreenContext++;
gBitmapAllocation += height * width;
#endif
bDestroyPixmap = false;
#if WINDOWS
if (pOldBrush)
SelectObject ((HDC)getSystemContext (), pOldBrush);
if (pOldPen)
SelectObject ((HDC)getSystemContext (), pOldPen);
if (pOldFont)
SelectObject ((HDC)getSystemContext (), pOldFont);
pOldBrush = pOldPen = pOldFont = 0;
pSystemContext = CreateCompatibleDC ((HDC)pContext->getSystemContext ());
if (drawInBitmap)
pWindow = pBitmapBg->getHandle ();
else // create bitmap if no bitmap handle exists
{
bDestroyPixmap = true;
pWindow = CreateCompatibleBitmap ((HDC)pContext->getSystemContext (), width, height);
}
oldBitmap = SelectObject ((HDC)pSystemContext, pWindow);
#elif MAC
if (drawInBitmap)
pWindow = pBitmapBg->getHandle ();
else
{
Rect GWRect;
GWRect.top = 0;
GWRect.left = 0;
GWRect.right = width;
GWRect.bottom = height;
NewGWorld ((GWorldPtr*)&pWindow, 0, &GWRect, NULL, NULL, 0);
bDestroyPixmap = true;
}
StuffHex (&fillPattern, "\pFFFFFFFFFFFFFFFF");
#elif MOTIF
// if no bitmap handle => create one
if (!pWindow)
{
Drawable dWindow = pContext->pFrame->getWindow ();
pWindow = (void*)XCreatePixmap (pDisplay, dWindow, width, height, pFrame->getDepth ());
bDestroyPixmap = true;
}
// set the current font
if (pSystemContext)
setFont (kNormalFont);
#elif BEOS
bDestroyPixmap = true;
offscreenBitmap = new BBitmap (BRect (0, 0, width - 1, height - 1), B_RGB16, true, false);
pView = new BView (BRect (0, 0, width - 1, height - 1), NULL, 0, 0);
offscreenBitmap->Lock ();
offscreenBitmap->AddChild (pView);
#endif
if (!drawInBitmap)
{
// draw bitmap to Offscreen
VSTGUI::CRect r (0, 0, width, height);
if (pBitmapBg)
pBitmapBg->draw (this, r);
else
{
setFillColor (kBlackCColor);
fillRect (r);
}
}
}
//-----------------------------------------------------------------------------
COffscreenContext::COffscreenContext (CFrame *pFrame, long width, long height, const CColor backgroundColor)
: CDrawContext (pFrame, NULL, NULL),
pBitmap (0), pBitmapBg (0), height (height), width (width), backgroundColor (backgroundColor)
{
clipRect (0, 0, width, height);
#ifdef DEBUG
gNbCOffscreenContext++;
gBitmapAllocation += height * width;
#endif
bDestroyPixmap = true;
#if WINDOWS
void *SystemWindow = pFrame->getSystemWindow ();
void *SystemContext = GetDC ((HWND)SystemWindow);
pSystemContext = CreateCompatibleDC ((HDC)SystemContext);
#ifdef DEBUG
gNbDC++;
#endif
pWindow = CreateCompatibleBitmap ((HDC)SystemContext, width, height);
oldBitmap = SelectObject ((HDC)pSystemContext, pWindow);
ReleaseDC ((HWND)SystemWindow, (HDC)SystemContext);
VSTGUI::CRect r (0, 0, width, height);
setFillColor (backgroundColor);
setFrameColor (backgroundColor);
fillRect (r);
drawRect (r);
#elif MAC
QDErr err;
Rect GWRect;
GWRect.top = GWRect.left = 0;
GWRect.right = width;
GWRect.bottom = height;
err = NewGWorld ((GWorldPtr*) &pWindow, 0, &GWRect, NULL, NULL, 0);
if (err)
pWindow = NULL;
StuffHex (&fillPattern, "\pFFFFFFFFFFFFFFFF");
VSTGUI::CRect r (0, 0, width, height);
setFillColor (backgroundColor);
setFrameColor (backgroundColor);
fillRect (r);
drawRect (r);
#elif MOTIF
Drawable dWindow = pFrame->getWindow ();
pWindow = (void*)XCreatePixmap (pDisplay, dWindow, width, height, pFrame->getDepth ());
// clear the pixmap
XGCValues values;
values.foreground = getIndexColor (backgroundColor);
GC gc = XCreateGC (pDisplay, (Drawable)pWindow, GCForeground, &values);
XFillRectangle (pDisplay, (Drawable)pWindow, gc, 0, 0, width, height);
XFreeGC (pDisplay, gc);
// set the current font
if (pSystemContext)
setFont (kNormalFont);
#elif BEOS
BRect frame (0, 0, width - 1, height - 1);
offscreenBitmap = new BBitmap (frame, B_RGB16, true, false);
pView = new BView (BRect (0, 0, width - 1, height - 1), NULL, 0, 0);
offscreenBitmap->Lock ();
offscreenBitmap->AddChild (pView);
if (backgroundColor.red != 255 || backgroundColor.green != 255 || backgroundColor.blue != 255)
{
rgb_color c = { backgroundColor.red, backgroundColor.green, backgroundColor.blue, 255 };
pView->SetHighColor (c);
pView->FillRect (frame);
}
#endif
}
#define DEBUG _DEBUG
//-----------------------------------------------------------------------------
COffscreenContext::~COffscreenContext ()
{
#if DEBUG
gNbCOffscreenContext--;
gBitmapAllocation -= height * width;
#endif
if (pBitmap)
pBitmap->forget ();
#if WINDOWS
if (pSystemContext)
{
DeleteDC ((HDC)pSystemContext);
#if DEBUG
gNbDC--;
#endif
}
if (bDestroyPixmap && pWindow)
DeleteObject (pWindow);
#elif MAC
if (bDestroyPixmap && pWindow)
DisposeGWorld ((GWorldPtr)pWindow);
#elif MOTIF
if (bDestroyPixmap && pWindow)
XFreePixmap (pDisplay, (Pixmap)pWindow);
#elif BEOS
delete offscreenBitmap;
pView = 0; // deleted because attached to the offscreen
#endif
}
//-----------------------------------------------------------------------------
void COffscreenContext::copyTo (CDrawContext* pContext, VSTGUI::CRect& srcRect, VSTGUI::CPoint destOffset)
{
#if WINDOWS
BitBlt ((HDC)pSystemContext,
destOffset.h,
destOffset.v,
srcRect.width (),
srcRect.height (),
(HDC)pContext->getSystemContext (),
srcRect.left + pContext->offset.h,
srcRect.top + pContext->offset.v,
SRCCOPY);
#elif MAC
if (!pWindow)
return;
Rect source, dest;
RGBColor savedForeColor, savedBackColor;
source.left = srcRect.left + pContext->offset.h;
source.top = srcRect.top + pContext->offset.v;
source.right = source.left + srcRect.right - srcRect.left;
source.bottom = source.top + srcRect.bottom - srcRect.top;
dest.left = destOffset.h;
dest.top = destOffset.v;
dest.right = dest.left + srcRect.right - srcRect.left;
dest.bottom = dest.top + srcRect.bottom - srcRect.top;
GetForeColor (&savedForeColor);
GetBackColor (&savedBackColor);
::BackColor (whiteColor);
::ForeColor (blackColor);
CopyBits (pContext->getBitmap (), getBitmap (), &source, &dest, srcCopy, 0L);
releaseBitmap ();
pContext->releaseBitmap ();
RGBForeColor (&savedForeColor);
RGBBackColor (&savedBackColor);
#endif
}
//-----------------------------------------------------------------------------
void COffscreenContext::copyFrom (CDrawContext *pContext, VSTGUI::CRect destRect, VSTGUI::CPoint srcOffset)
{
#if WINDOWS
BitBlt ((HDC)pContext->getSystemContext (), // hdcDest
destRect.left + pContext->offset.h, // xDest
destRect.top + pContext->offset.v, // yDest
destRect.right - destRect.left, // xWidth,
destRect.bottom - destRect.top, // yHeight
(HDC)pSystemContext, // hdcSrc
srcOffset.h, // xSrc
srcOffset.v, // ySrc
SRCCOPY); // dwROP
#elif MAC
if (!pWindow)
return;
Rect source, dest;
RGBColor savedForeColor, savedBackColor;
source.left = srcOffset.h;
source.top = srcOffset.v;
source.right = source.left + destRect.right - destRect.left;
source.bottom = source.top + destRect.bottom - destRect.top;
dest.top = destRect.top + pContext->offset.v;
dest.left = destRect.left + pContext->offset.h;
dest.bottom = destRect.bottom + pContext->offset.v;
dest.right = destRect.right + pContext->offset.h;
GetForeColor (&savedForeColor);
GetBackColor (&savedBackColor);
::BackColor (whiteColor);
::ForeColor (blackColor);
CopyBits (getBitmap (), pContext->getBitmap (), &source, &dest, srcCopy, 0L);
#if MACX
QDAddRectToDirtyRegion (pContext->getPort (), &dest);
#endif
releaseBitmap ();
pContext->releaseBitmap ();
RGBForeColor (&savedForeColor);
RGBBackColor (&savedBackColor);
#elif MOTIF
XCopyArea (pDisplay, (Drawable)pWindow, (Drawable)pContext->getWindow (),
(GC)pSystemContext, srcOffset.h, srcOffset.v,
destRect.width (), destRect.height (),
destRect.left, destRect.top);
#elif BEOS
pContext->pView->SetDrawingMode (B_OP_COPY);
BRect destination (destRect.left, destRect.top, destRect.right - 1, destRect.bottom - 1);
BRect source = destination;
source.OffsetTo (srcOffset.h, srcOffset.v);
pView->Sync ();
pContext->pView->DrawBitmap (offscreenBitmap, source, destination);
#endif
}
//-----------------------------------------------------------------------------
#if MAC
BitMapPtr COffscreenContext::getBitmap ()
{
PixMapHandle pixMap = GetGWorldPixMap ((GWorldPtr)pWindow);
if (pixMap)
{
LockPixels (pixMap);
return (BitMapPtr)*pixMap;
}
return 0;
}
//-----------------------------------------------------------------------------
void COffscreenContext::releaseBitmap ()
{
PixMapHandle pixMap = GetGWorldPixMap ((GWorldPtr)pWindow);
UnlockPixels (pixMap);
}
//-----------------------------------------------------------------------------
CGrafPtr COffscreenContext::getPort ()
{
if (!bInitialized)
bInitialized = true;
return (CGrafPtr)pWindow;
}
#endif
//-----------------------------------------------------------------------------
// CView
//-----------------------------------------------------------------------------
CView::CView (const VSTGUI::CRect& size)
: nbReference (1), size (size), mouseableArea (size), pParent (0), pParentView (0),
bDirty (false), bMouseEnabled (true), bTransparencyEnabled (false)
{
#if DEBUG
gNbCView++;
#endif
}
//-----------------------------------------------------------------------------
CView::~CView ()
{
#if DEBUG
gNbCView--;
if (nbReference > 1)
FDebugPrint ("nbReference is %d when trying to delete CView\n", nbReference);
#endif
}
//-----------------------------------------------------------------------------
void CView::redraw ()
{
if (pParent)
pParent->draw (this);
}
//-----------------------------------------------------------------------------
void CView::draw (CDrawContext *pContext)
{
setDirty (false);
}
//-----------------------------------------------------------------------------
void CView::mouse (CDrawContext *pContext, VSTGUI::CPoint &where)
{}
//-----------------------------------------------------------------------------
bool CView::onDrop (void **ptrItems, long nbItems, long type, VSTGUI::CPoint &where)
{
return false;
}
//-----------------------------------------------------------------------------
bool CView::onWheel (CDrawContext *pContext, const VSTGUI::CPoint &where, float distance)
{
return false;
}
//------------------------------------------------------------------------
void CView::update (CDrawContext *pContext)
{
if (isDirty ())
{
draw (pContext);
setDirty (false);
}
}
//------------------------------------------------------------------------------
long CView::onKeyDown (VstKeyCode& keyCode)
{
return -1;
}
//------------------------------------------------------------------------------
long CView::onKeyUp (VstKeyCode& keyCode)
{
return -1;
}
//------------------------------------------------------------------------------
long CView::notify (CView* sender, const char* message)
{
return kMessageUnknown;
}
//------------------------------------------------------------------------------
void CView::looseFocus (CDrawContext *pContext)
{}
//------------------------------------------------------------------------------
void CView::takeFocus (CDrawContext *pContext)
{}
//------------------------------------------------------------------------------
void CView::setViewSize (VSTGUI::CRect &rect)
{
size = rect;
setDirty ();
}
//-----------------------------------------------------------------------------
void CView::remember ()
{
nbReference++;
}
//-----------------------------------------------------------------------------
void CView::forget ()
{
if (nbReference > 0)
{
nbReference--;
if (nbReference == 0)
delete this;
}
}
//-----------------------------------------------------------------------------
void *CView::getEditor ()
{
return pParent ? pParent->getEditor () : 0;
}
//-----------------------------------------------------------------------------
// CFrame Implementation
//-----------------------------------------------------------------------------
CFrame::CFrame (const VSTGUI::CRect &size, void *pSystemWindow, void *pEditor)
: CView (size), pEditor (pEditor), pSystemWindow (pSystemWindow), pBackground (0),
viewCount (0), maxViews (0), ppViews (0), pModalView (0), pEditView (0),
bFirstDraw (true), bDropActive (false), pFrameContext (0), bAddedWindow (false),
pVstWindow (0), defaultCursor (0)
{
setOpenFlag (true);
#if WINDOWS
pHwnd = 0;
OleInitialize (0);
#if DYNAMICALPHABLEND
pfnAlphaBlend = 0;
pfnTransparentBlt = 0;
hInstMsimg32dll = LoadLibrary ("msimg32.dll");
if (hInstMsimg32dll)
{
pfnAlphaBlend = (PFNALPHABLEND)GetProcAddress (hInstMsimg32dll, "AlphaBlend");
// get OS version
OSVERSIONINFOEX osvi;
memset (&osvi, 0, sizeof (osvi));
osvi.dwOSVersionInfoSize = sizeof (osvi);
if (GetVersionEx ((OSVERSIONINFO *)&osvi))
{
// Is this win NT or better?
if (osvi.dwPlatformId >= VER_PLATFORM_WIN32_NT)
{
// Yes, then TransparentBlt doesn't have the memory-leak and can be safely used
pfnTransparentBlt = (PFNTRANSPARENTBLT)GetProcAddress (hInstMsimg32dll, "TransparentBlt");
}
}
}
#endif
#elif MOTIF
gc = 0;
depth = 0;
pDisplay = 0;
pVisual = 0;
window = 0;
#elif BEOS
pPlugView = NULL;
#endif
initFrame (pSystemWindow);
#if WINDOWS
#if USE_GLOBAL_CONTEXT
hdc = GetDC ((HWND)getSystemWindow ());
#if DEBUG
gNbDC++;
#endif
pFrameContext = new CDrawContext (this, hdc, getSystemWindow ());
#endif
#elif MAC
pFrameContext = new CDrawContext (this, getSystemWindow (), getSystemWindow ());
pFrameContext->offset.h = size.left;
pFrameContext->offset.v = size.top;
#elif MOTIF
pFrameContext = new CDrawContext (this, gc, (void*)window);
#endif
}
//-----------------------------------------------------------------------------
CFrame::CFrame (const VSTGUI::CRect &rect, char *pTitle, void *pEditor, const long style)
: CView (rect), pEditor (pEditor), pSystemWindow (0), pBackground (0), viewCount (0),
maxViews (0), ppViews (0), pModalView (0), pEditView (0), bFirstDraw (true),
pFrameContext (0), defaultCursor (0)
{
bAddedWindow = true;
setOpenFlag (false);
#if WINDOWS
pHwnd = 0;
OleInitialize (0);
#elif MOTIF
gc = 0;
depth = 0;
pDisplay = 0;
pVisual = 0;
window = 0;
#elif BEOS
pPlugView = NULL;
#endif
#if !PLUGGUI
pVstWindow = (VstWindow*)malloc (sizeof (VstWindow));
strcpy (((VstWindow*)pVstWindow)->title, pTitle);
((VstWindow*)pVstWindow)->xPos = (short)size.left;
((VstWindow*)pVstWindow)->yPos = (short)size.top;
((VstWindow*)pVstWindow)->width = (short)size.width ();
((VstWindow*)pVstWindow)->height = (short)size.height ();
((VstWindow*)pVstWindow)->style = style;
((VstWindow*)pVstWindow)->parent = 0;
((VstWindow*)pVstWindow)->userHandle = 0;
((VstWindow*)pVstWindow)->winHandle = 0;
#endif
}
//-----------------------------------------------------------------------------
CFrame::~CFrame ()
{
setCursor (kCursorDefault);
setDropActive (false);
removeAll (true);
if (pBackground)
pBackground->forget ();
if (pFrameContext)
delete pFrameContext;
#if WINDOWS
OleUninitialize ();
#if DYNAMICALPHABLEND
if (hInstMsimg32dll)
FreeLibrary (hInstMsimg32dll);
#endif
if (pHwnd)
{
#if USE_GLOBAL_CONTEXT
ReleaseDC ((HWND)getSystemWindow (), hdc);
#if DEBUG
gNbDC--;
#endif
#endif
SetWindowLong ((HWND)pHwnd, GWL_USERDATA, (long)NULL);
DestroyWindow ((HWND)pHwnd);
ExitWindowClass ();
}
#elif MOTIF
#if TEST_REGION
XDestroyRegion (region);
#endif
// remove callbacks to avoid undesirable update
if (pSystemWindow)
{
XtRemoveCallback ((Widget)pSystemWindow, XmNexposeCallback, _drawingAreaCallback, this);
XtRemoveCallback ((Widget)pSystemWindow, XmNinputCallback, _drawingAreaCallback, this);
XtRemoveCallback ((Widget)pSystemWindow, XmNdestroyCallback, _destroyCallback, this);
freeGc ();
}
#endif
if (bAddedWindow)
close ();
if (pVstWindow)
free (pVstWindow);
#if BEOS
CBitmap::closeResource (); // must be done only once at the end of the story.
#endif
}
//-----------------------------------------------------------------------------
bool CFrame::open (VSTGUI::CPoint *point)
{
#if PLUGGUI
return false;
#else
if (!bAddedWindow)
return false;
if (getOpenFlag ())
{
#if WINDOWS
BringWindowToTop (GetParent (GetParent ((HWND)getSystemWindow ())));
#elif MOTIF
Widget widget = (Widget)getSystemWindow ();
while (widget && !XtIsTopLevelShell (widget))
widget = XtParent (widget);
if (widget)
XRaiseWindow (getDisplay (), XtWindow (widget));
#elif BEOS
pPlugView->Window ()->Activate (true);
#endif
return false;
}
if (pVstWindow)
{
if (point)
{
((VstWindow*)pVstWindow)->xPos = (short)point->h;
((VstWindow*)pVstWindow)->yPos = (short)point->v;
}
AudioEffectX *pAudioEffectX = (AudioEffectX*)(((AEffGUIEditor*)pEditor)->getEffect ());
pSystemWindow = pAudioEffectX->openWindow ((VstWindow*)pVstWindow);
}
if (pSystemWindow)
{
if (initFrame (pSystemWindow))
setOpenFlag (true);
}
return getOpenFlag ();
#endif
}
//-----------------------------------------------------------------------------
bool CFrame::close ()
{
#if PLUGGUI
return false;
#else
if (!bAddedWindow || !getOpenFlag () || !pSystemWindow)
return false;
AudioEffectX *pAudioEffectX = (AudioEffectX*)(((AEffGUIEditor*)pEditor)->getEffect ());
pAudioEffectX->closeWindow ((VstWindow*)pVstWindow);
pSystemWindow = 0;
return true;
#endif
}
//-----------------------------------------------------------------------------
bool CFrame::initFrame (void *systemWin)
{
if (!systemWin)
return false;
#if WINDOWS
InitWindowClass ();
pHwnd = CreateWindowEx (0, className, "Window",
WS_CHILD | WS_VISIBLE,
0, 0, size.width (), size.height (),
(HWND)pSystemWindow, NULL, GetInstance (), NULL);
SetWindowLong ((HWND)pHwnd, GWL_USERDATA, (long)this);
#elif MAC
#elif MOTIF
// attach the callbacks
XtAddCallback ((Widget)systemWin, XmNexposeCallback, _drawingAreaCallback, this);
XtAddCallback ((Widget)systemWin, XmNinputCallback, _drawingAreaCallback, this);
XtAddCallback ((Widget)systemWin, XmNdestroyCallback, _destroyCallback, this);
XtAddEventHandler ((Widget)systemWin, LeaveWindowMask, true, _eventHandler, this);
// init a default gc
window = XtWindow ((Widget)systemWin);
pDisplay = XtDisplay ((Widget)systemWin);
XGCValues values;
values.foreground = 1;
gc = XCreateGC (pDisplay, (Drawable)window, GCForeground, &values);
#if TEST_REGION
region = XCreateRegion ();
#endif
// get the std colormap
XWindowAttributes attr;
XGetWindowAttributes (pDisplay, window, &attr);
colormap = attr.colormap;
pVisual = attr.visual;
depth = attr.depth;
// init and load the fonts
if (!fontInit)
{
for (long i = 0; i < kNumStandardFonts; i++)
{
fontStructs[i] = XLoadQueryFont (pDisplay, fontTable[i].string);
assert (fontStructs[i] != 0);
}
fontInit = true;
}
#elif BEOS
BView* parentView = (BView*) pSystemWindow;
BRect frame = parentView->Frame ();
frame.OffsetTo (B_ORIGIN);
pPlugView = new PlugView (frame, this);
parentView->AddChild (pPlugView);
#endif
setDropActive (true);
return true;
}
//-----------------------------------------------------------------------------
bool CFrame::setDropActive (bool val)
{
if (!bDropActive && !val)
return true;
#if WINDOWS
if (!pHwnd)
return false;
if (val)
RegisterDragDrop ((HWND)pHwnd, (IDropTarget*)createDropTarget (this));
else
RevokeDragDrop ((HWND)pHwnd);
#elif MAC
if (val)
install_drop (this);
else
remove_drop (this);
#endif
bDropActive = val;
return true;
}
#if MOTIF
//-----------------------------------------------------------------------------
void CFrame::freeGc ()
{
if (gc)
XFreeGC (pDisplay, gc);
gc = 0;
}
#endif
//-----------------------------------------------------------------------------
void CFrame::draw (CDrawContext *pContext)
{
if (bFirstDraw)
bFirstDraw = false;
if (!pContext)
pContext = pFrameContext;
// draw first the background
if (pBackground)
{
VSTGUI::CRect r (0, 0, pBackground->getWidth (), pBackground->getHeight ());
pBackground->draw (pContext, r);
}
// and the different children
for (long i = 0; i < viewCount; i++)
ppViews[i]->draw (pContext);
// and the modal view
if (pModalView)
pModalView->draw (pContext);
}
//-----------------------------------------------------------------------------
void CFrame::drawRect (CDrawContext *pContext, VSTGUI::CRect& updateRect)
{
if (bFirstDraw)
bFirstDraw = false;
if (!pContext)
pContext = pFrameContext;
// draw first the background
if (pBackground)
pBackground->draw (pContext, updateRect, VSTGUI::CPoint (updateRect.left, updateRect.top));
// and the different children
for (long i = 0; i < viewCount; i++)
{
if (ppViews[i]->checkUpdate (updateRect))
ppViews[i]->drawRect (pContext, updateRect);
}
// and the modal view
if (pModalView && pModalView->checkUpdate (updateRect))
pModalView->draw (pContext);
}
//-----------------------------------------------------------------------------
void CFrame::draw (CView *pView)
{
CView *pViewToDraw = 0;
if (pView)
{
// Search it in the view list
for (long i = 0; i < viewCount; i++)
if (ppViews[i] == pView)
{
pViewToDraw = ppViews[i];
break;
}
}
#if WINDOWS
HDC hdc2;
#endif
CDrawContext *pContext = pFrameContext;
if (!pContext)
{
#if WINDOWS
hdc2 = GetDC ((HWND)getSystemWindow ());
#if DEBUG
gNbDC++;
#endif
pContext = new CDrawContext (this, hdc2, getSystemWindow ());
#elif MAC
pContext = new CDrawContext (this, getSystemWindow (), getSystemWindow ());
#elif MOTIF
pContext = new CDrawContext (this, gc, (void*)window);
#elif BEOS
pContext = new CDrawContext (this, pPlugView, 0);
#endif
}
if (pContext)
{
if (pViewToDraw)
pViewToDraw->draw (pContext);
else
draw (pContext);
if (!pFrameContext)
delete pContext;
}
#if WINDOWS
if (!pFrameContext)
{
ReleaseDC ((HWND)getSystemWindow (), hdc2);
#if DEBUG
gNbDC--;
#endif
}
#endif
}
//-----------------------------------------------------------------------------
void CFrame::mouse (CDrawContext *pContext, VSTGUI::CPoint &where)
{
if (!pContext)
pContext = pFrameContext;
if (pEditView)
{
pEditView->looseFocus ();
pEditView = 0;
}
long buttons = -1;
if (pContext)
buttons = pContext->getMouseButtons ();
if (pModalView)
{
if (pModalView->hitTest (where, buttons))
pModalView->mouse (pContext, where);
}
else
{
for (long i = viewCount - 1; i >= 0; i--)
{
if (ppViews[i]->getMouseEnabled () && ppViews[i]->hitTest (where, buttons))
{
ppViews[i]->mouse (pContext, where);
return;
}
}
}
}
//-----------------------------------------------------------------------------
long CFrame::onKeyDown (VstKeyCode& keyCode)
{
long result = -1;
if (pEditView)
result = pEditView->onKeyDown (keyCode);
if (result == -1 && pModalView)
result = pModalView->onKeyDown (keyCode);
if (result == -1)
{
for (long i = viewCount - 1; i >= 0; i--)
{
if ((result = ppViews[i]->onKeyDown (keyCode)) != -1)
break;
}
}
return result;
}
//-----------------------------------------------------------------------------
long CFrame::onKeyUp (VstKeyCode& keyCode)
{
long result = -1;
if (pEditView)
result = pEditView->onKeyUp (keyCode);
if (result == -1 && pModalView)
result = pModalView->onKeyUp (keyCode);
if (result == -1)
{
for (long i = viewCount - 1; i >= 0; i--)
{
if ((result = ppViews[i]->onKeyUp (keyCode)) != -1)
break;
}
}
return result;
}
//-----------------------------------------------------------------------------
bool CFrame::onDrop (void **ptrItems, long nbItems, long type, VSTGUI::CPoint &where)
{
if (pModalView || pEditView)
return false;
bool result = false;
// call the correct child
for (long i = viewCount - 1; i >= 0; i--)
{
if (ppViews[i]->getMouseEnabled () && where.isInside (ppViews[i]->size))
{
if (ppViews[i]->onDrop (ptrItems, nbItems, type, where))
{
result = true;
break;
}
}
}
return result;
}
//-----------------------------------------------------------------------------
bool CFrame::onWheel (CDrawContext *pContext, const VSTGUI::CPoint &where, float distance)
{
bool result = false;
CView *view = getCurrentView ();
if (view)
{
CDrawContext *pContext2;
if (pContext)
pContext2 = pContext;
else
pContext2 = pFrameContext;
#if WINDOWS
HDC hdc2;
#endif
if (!pContext2)
{
#if WINDOWS
hdc2 = GetDC ((HWND)getSystemWindow ());
#if DEBUG
gNbDC++;
#endif
pContext2 = new CDrawContext (this, hdc2, getSystemWindow ());
#elif MAC
pContext2 = new CDrawContext (this, getSystemWindow (), getSystemWindow ());
#elif MOTIF
pContext2 = new CDrawContext (this, gc, (void*)window);
#elif BEOS
if (pPlugView->LockLooperWithTimeout (0) != B_OK)
return false;
pContext2 = new CDrawContext (this, pPlugView, 0);
#endif
}
VSTGUI::CPoint where;
getCurrentLocation (where);
result = view->onWheel (pContext2, where, distance);
if (!pFrameContext && !pContext)
delete pContext2;
#if WINDOWS
if (!pFrameContext && !pContext)
{
ReleaseDC ((HWND)getSystemWindow (), hdc2);
#if DEBUG
gNbDC--;
#endif
}
#elif BEOS
pPlugView->UnlockLooper ();
#endif
}
return result;
}
//-----------------------------------------------------------------------------
void CFrame::update (CDrawContext *pContext)
{
if (!getOpenFlag ())
return;
if (pModalView)
pModalView->update (pContext);
else
{
if (isDirty ())
{
draw (pContext);
setDirty (false);
}
else
{
for (long i = 0; i < viewCount; i++)
ppViews[i]->update (pContext);
}
}
#if MACX
if (QDIsPortBufferDirty (GetWindowPort ((WindowRef)pSystemWindow)))
{
QDFlushPortBuffer (GetWindowPort ((WindowRef)pSystemWindow), NULL);
}
#endif
}
//-----------------------------------------------------------------------------
bool CFrame::isSomethingDirty ()
{
if (pModalView || isDirty ())
return true;
else
{
for (long i = 0; i < viewCount; i++)
if (ppViews[i]->isDirty ())
return true;
}
return false;
}
//-----------------------------------------------------------------------------
void CFrame::idle ()
{
if (!getOpenFlag ())
return;
// don't do an idle before a draw
if (bFirstDraw)
return;
if (!isSomethingDirty ())
return;
#if WINDOWS
HDC hdc2;
#endif
CDrawContext *pContext = pFrameContext;
if (!pContext)
{
#if WINDOWS
hdc2 = GetDC ((HWND)getSystemWindow ());
#if DEBUG
gNbDC++;
#endif
pContext = new CDrawContext (this, hdc2, getSystemWindow ());
#elif MAC
pContext = new CDrawContext (this, getSystemWindow (), getSystemWindow ());
#elif MOTIF
pContext = new CDrawContext (this, gc, (void*)window);
#elif BEOS
if (pPlugView->LockLooperWithTimeout (0) != B_OK)
return;
pContext = new CDrawContext (this, pPlugView, 0);
#endif
}
update (pContext);
if (!pFrameContext)
delete pContext;
#if WINDOWS
if (!pFrameContext)
{
ReleaseDC ((HWND)getSystemWindow (), hdc2);
#if DEBUG
gNbDC--;
#endif
}
#elif BEOS
pPlugView->UnlockLooper ();
#endif
}
//-----------------------------------------------------------------------------
void CFrame::doIdleStuff ()
{
#if PLUGGUI
if (pEditor)
((PluginGUIEditor*)pEditor)->doIdleStuff ();
#else
if (pEditor)
((AEffGUIEditor*)pEditor)->doIdleStuff ();
#endif
}
//-----------------------------------------------------------------------------
unsigned long CFrame::getTicks ()
{
#if PLUGGUI
if (pEditor)
((PluginGUIEditor*)pEditor)->getTicks ();
#else
if (pEditor)
return ((AEffGUIEditor*)pEditor)-> getTicks ();
#endif
return 0;
}
//-----------------------------------------------------------------------------
long CFrame::getKnobMode ()
{
#if PLUGGUI
return PluginGUIEditor::getKnobMode ();
#else
return AEffGUIEditor::getKnobMode ();
#endif
}
//-----------------------------------------------------------------------------
#if WINDOWS
HWND CFrame::getOuterWindow ()
{
int diffWidth, diffHeight;
RECT rctTempWnd, rctPluginWnd;
HWND hTempWnd = (HWND)pHwnd;
GetWindowRect (hTempWnd, &rctPluginWnd);
while (hTempWnd != NULL)
{
// Looking for caption bar
if (GetWindowLong (hTempWnd, GWL_STYLE) & WS_CAPTION)
return hTempWnd;
// Looking for last parent
if (!GetParent (hTempWnd))
return hTempWnd;
// get difference between plugin-window and current parent
GetWindowRect (GetParent (hTempWnd), &rctTempWnd);
diffWidth = (rctTempWnd.right - rctTempWnd.left) - (rctPluginWnd.right - rctPluginWnd.left);
diffHeight = (rctTempWnd.bottom - rctTempWnd.top) - (rctPluginWnd.bottom - rctPluginWnd.top);
// Looking for size mismatch
if ((abs (diffWidth) > 60) || (abs (diffHeight) > 60)) // parent belongs to host
return (hTempWnd);
// get the next parent window
hTempWnd = GetParent (hTempWnd);
}
return NULL;
}
#endif
//-----------------------------------------------------------------------------
bool CFrame::getPosition (long &x, long &y)
{
if (!getOpenFlag ())
return false;
// get the position of the Window including this frame in the main pWindow
#if WINDOWS
HWND wnd = (HWND)getOuterWindow ();
HWND wndParent = GetParent (wnd);
RECT rctTempWnd;
GetWindowRect (wnd, &rctTempWnd);
POINT point;
point.x = rctTempWnd.left;
point.y = rctTempWnd.top;
MapWindowPoints (HWND_DESKTOP, wndParent, &point, 1);
x = point.x;
y = point.y;
#elif MAC
Rect bounds;
GetWindowBounds ((WindowRef)pSystemWindow, kWindowContentRgn, &bounds);
x = bounds.left;
y = bounds.top;
#elif MOTIF
Position xWin, yWin;
// get the topLevelShell of the pSystemWindow
Widget parent = (Widget)getSystemWindow ();
Widget parentOld = parent;
while (parent != 0 && !XtIsTopLevelShell (parent))
{
parentOld = parent;
parent = XtParent (parent);
}
if (parent == 0)
parent = parentOld;
if (parent)
{
XtVaGetValues (parent, XtNx, &xWin, XtNy, &yWin, NULL);
x = xWin - 8;
y = yWin - 30;
}
#elif BEOS
BRect frame = pPlugView->Window ()->Frame ();
x = (long) frame.left;
y = (long) frame.top;
#endif
return true;
}
//-----------------------------------------------------------------------------
bool CFrame::setSize (long width, long height)
{
if (!getOpenFlag ())
return false;
if ((width == size.width ()) &&
(height == size.height ()))
return false;
#if !PLUGGUI
if (pEditor)
{
AudioEffectX* effect = (AudioEffectX*)((AEffGUIEditor*)pEditor)->getEffect ();
if (effect && effect->canHostDo ("sizeWindow"))
{
if (effect->sizeWindow (width, height))
{
#if WINDOWS
SetWindowPos ((HWND)pHwnd, HWND_TOP, 0, 0, width, height, SWP_NOMOVE);
#endif
return true;
}
}
}
#endif
// keep old values
long oldWidth = size.width ();
long oldHeight = size.height ();
// set the new size
size.right = size.left + width;
size.bottom = size.top + height;
#if WINDOWS
RECT rctTempWnd, rctParentWnd;
HWND hTempWnd;
long iFrame = (2 * GetSystemMetrics (SM_CYFIXEDFRAME));
long diffWidth = 0;
long diffHeight = 0;
hTempWnd = (HWND)pHwnd;
while ((diffWidth != iFrame) && (hTempWnd != NULL)) // look for FrameWindow
{
HWND hTempParentWnd = GetParent (hTempWnd);
char buffer[1024];
GetClassName (hTempParentWnd, buffer, 1024);
if (!hTempParentWnd || !strcmp (buffer, "MDIClient"))
break;
GetWindowRect (hTempWnd, &rctTempWnd);
GetWindowRect (hTempParentWnd, &rctParentWnd);
SetWindowPos (hTempWnd, HWND_TOP, 0, 0, width + diffWidth, height + diffHeight, SWP_NOMOVE);
diffWidth = (rctParentWnd.right - rctParentWnd.left) - (rctTempWnd.right - rctTempWnd.left);
diffHeight = (rctParentWnd.bottom - rctParentWnd.top) - (rctTempWnd.bottom - rctTempWnd.top);
if ((diffWidth > 80) || (diffHeight > 80)) // parent belongs to host
return true;
hTempWnd = hTempParentWnd;
}
if (hTempWnd)
SetWindowPos (hTempWnd, HWND_TOP, 0, 0, width + diffWidth, height + diffHeight, SWP_NOMOVE);
#elif MAC
if (getSystemWindow ())
{
Rect bounds;
GetPortBounds (GetWindowPort ((WindowRef)getSystemWindow ()), &bounds);
SizeWindow ((WindowRef)getSystemWindow (), (bounds.right - bounds.left) - oldWidth + width,
(bounds.bottom - bounds.top) - oldHeight + height, true);
#if MACX
SetPort (GetWindowPort ((WindowRef)getSystemWindow ()));
#endif
}
#elif MOTIF
Dimension heightWin, widthWin;
// get the topLevelShell of the pSystemWindow
Widget parent = (Widget)getSystemWindow ();
Widget parentOld = parent;
while (parent != 0 && !XtIsTopLevelShell (parent))
{
parentOld = parent;
parent = XtParent (parent);
}
if (parent == 0)
parent = parentOld;
if (parent)
{
XtVaGetValues (parent, XtNwidth, &widthWin, XtNheight, &heightWin, NULL);
long diffWidth = widthWin - oldWidth;
long diffHeight = heightWin - oldHeight;
XtVaSetValues (parent, XmNwidth, width + diffWidth,
XmNheight, height + diffHeight, NULL);
}
#elif BEOS
BView* parent = pPlugView->Parent ();
parent->SetResizingMode (B_FOLLOW_ALL_SIDES);
BRect frame = pPlugView->Frame ();
pPlugView->Window ()->ResizeBy (width - frame.Width () - 1, height - frame.Height () - 1);
parent->SetResizingMode (B_FOLLOW_NONE);
#endif
return true;
}
//-----------------------------------------------------------------------------
bool CFrame::getSize (VSTGUI::CRect *pRect)
{
if (!getOpenFlag ())
return false;
#if WINDOWS
// return the size relatif to the client rect of this window
// get the main window
HWND wnd = GetParent ((HWND)getSystemWindow ());
HWND wndParent = GetParent (wnd);
HWND wndParentParent = GetParent (wndParent);
RECT rctTempWnd;
GetWindowRect (wnd, &rctTempWnd);
POINT point;
point.x = rctTempWnd.left;
point.y = rctTempWnd.top;
MapWindowPoints (HWND_DESKTOP, wndParentParent, &point, 1);
pRect->left = point.x;
pRect->top = point.y;
pRect->right = pRect->left + rctTempWnd.right - rctTempWnd.left;
pRect->bottom = pRect->top + rctTempWnd.bottom - rctTempWnd.top;
#elif MAC
Rect bounds;
GetPortBounds (GetWindowPort ((WindowRef)getSystemWindow ()), &bounds);
pRect->left = bounds.left;
pRect->top = bounds.top;
pRect->right = bounds.right;
pRect->bottom = bounds.bottom;
#elif MOTIF
Dimension height, width;
XtVaGetValues ((Widget)getSystemWindow (),
XtNwidth, &width, XtNheight, &height, NULL);
Position x, y;
Position xTotal = 0, yTotal = 0;
Widget parent = (Widget)getSystemWindow ();
while (parent != 0 && !XtIsTopLevelShell (parent) && !XmIsDialogShell (parent))
{
XtVaGetValues (parent, XtNx, &x, XtNy, &y, NULL);
xTotal += x;
yTotal += y;
parent = XtParent (parent);
}
pRect->left = xTotal;
pRect->top = yTotal;
pRect->right = width + pRect->left;
pRect->bottom = height + pRect->top;
#elif BEOS
BRect v = pPlugView->Frame ();
(*pRect) (v.left, v.top, v.right + 1, v.bottom + 1);
#endif
return true;
}
//-----------------------------------------------------------------------------
void CFrame::setBackground (CBitmap *background)
{
if (pBackground)
pBackground->forget ();
pBackground = background;
if (pBackground)
pBackground->remember ();
}
//-----------------------------------------------------------------------------
bool CFrame::addView (CView *pView)
{
if (viewCount == maxViews)
{
maxViews += 20;
if (ppViews)
ppViews = (CView**)realloc (ppViews, maxViews * sizeof (CView*));
else
ppViews = (CView**)malloc (maxViews * sizeof (CView*));
if (ppViews == 0)
{
maxViews = 0;
return false;
}
}
ppViews[viewCount] = pView;
viewCount++;
pView->pParent = this;
pView->attached (this);
return true;
}
//-----------------------------------------------------------------------------
bool CFrame::removeView (CView *pView, const bool &withForget)
{
bool found = false;
for (long i = 0; i < viewCount; i++)
{
if (found)
ppViews[i - 1] = ppViews[i];
if (ppViews[i] == pView)
{
pView->removed (this);
if (withForget)
pView->forget ();
found = true;
}
}
if (found)
viewCount--;
return true;
}
//-----------------------------------------------------------------------------
bool CFrame::removeAll (const bool &withForget)
{
if (pEditView)
{
pEditView->looseFocus ();
pEditView = 0;
}
if (ppViews)
{
for (long i = 0; i < viewCount; i++)
{
ppViews[i]->removed (this);
if (withForget)
ppViews[i]->forget ();
ppViews[i] = 0;
}
free (ppViews);
ppViews = 0;
viewCount = 0;
maxViews = 0;
}
return true;
}
//-----------------------------------------------------------------------------
bool CFrame::isChild (CView *pView)
{
bool found = false;
for (long i = 0; i < viewCount; i++)
{
if (ppViews[i] == pView)
{
found = true;
break;
}
}
return found;
}
//-----------------------------------------------------------------------------
CView *CFrame::getView (long index)
{
if (index >= 0 && index < viewCount)
return ppViews[index];
return 0;
}
//-----------------------------------------------------------------------------
long CFrame::setModalView (CView *pView)
{
if (pView != NULL)
if (pModalView)
return 0;
if (pModalView)
pModalView->removed (this);
pModalView = pView;
if (pModalView)
pModalView->attached (this);
return 1;
}
//-----------------------------------------------------------------------------
void CFrame::beginEdit (long index)
{
#if PLUGGUI
#else
if (pEditor)
((AudioEffectX*)(((AEffGUIEditor*)pEditor)->getEffect ()))->beginEdit (index);
#endif
}
//-----------------------------------------------------------------------------
void CFrame::endEdit (long index)
{
#if PLUGGUI
#else
if (pEditor)
((AudioEffectX*)(((AEffGUIEditor*)pEditor)->getEffect ()))->endEdit (index);
#endif
}
//-----------------------------------------------------------------------------
CView *CFrame::getCurrentView ()
{
if (pModalView)
return pModalView;
VSTGUI::CPoint where;
getCurrentLocation (where);
for (long i = viewCount - 1; i >= 0; i--)
{
if (ppViews[i] && where.isInside (ppViews[i]->size))
return ppViews[i];
}
return 0;
}
//-----------------------------------------------------------------------------
bool CFrame::getCurrentLocation (VSTGUI::CPoint &where)
{
#if WINDOWS
HWND hwnd = (HWND)this->getSystemWindow ();
POINT _where;
GetCursorPos (&_where);
where (_where.x, _where.y);
if (hwnd)
{
RECT rctTempWnd;
GetWindowRect (hwnd, &rctTempWnd);
where.offset (-rctTempWnd.left, -rctTempWnd.top);
}
return true;
#endif
// create a local context
CDrawContext *pContextTemp = 0;
#if MAC
pContextTemp = new CDrawContext (this, this->getSystemWindow (), this->getSystemWindow ());
#elif MOTIF
pContextTemp = new CDrawContext (this, this->getGC (), (void *)this->getWindow ());
#elif BEOS
pContextTemp = new CDrawContext (this, this->getSystemWindow (), NULL);
#endif
// get the current position
if (pContextTemp)
{
pContextTemp->getMouseLocation (where);
delete pContextTemp;
}
return true;
}
//-----------------------------------------------------------------------------
void CFrame::setCursor (CCursorType type)
{
#if WINDOWS
if (!defaultCursor)
defaultCursor = GetCursor ();
switch (type)
{
case kCursorDefault:
SetCursor ((HCURSOR)defaultCursor);
break;
case kCursorWait:
SetCursor (LoadCursor (0, IDC_WAIT));
break;
case kCursorHSize:
SetCursor (LoadCursor (0, IDC_SIZEWE));
break;
case kCursorVSize:
SetCursor (LoadCursor (0, IDC_SIZENS));
break;
case kCursorNESWSize:
SetCursor (LoadCursor (0, IDC_SIZENESW));
break;
case kCursorNWSESize:
SetCursor (LoadCursor (0, IDC_SIZENWSE));
break;
case kCursorSizeAll:
SetCursor (LoadCursor (0, IDC_SIZEALL));
break;
}
#elif MAC
//if (!defaultCursor)
// defaultCursor = GetCursor (0);
switch (type)
{
case kCursorDefault:
InitCursor ();
break;
case kCursorWait:
SetCursor (*GetCursor (watchCursor));
break;
case kCursorHSize:
SetCursor (*GetCursor (crossCursor));
break;
case kCursorVSize:
SetCursor (*GetCursor (crossCursor));
break;
case kCursorNESWSize:
SetCursor (*GetCursor (crossCursor));
break;
case kCursorNWSESize:
SetCursor (*GetCursor (crossCursor));
break;
case kCursorSizeAll:
SetCursor (*GetCursor (plusCursor));
break;
}
#endif
}
//-----------------------------------------------------------------------------
void CFrame::setEditView (CView *pView)
{
CView *pOldEditView = pEditView;
pEditView = pView;
if (pOldEditView)
pOldEditView->looseFocus ();
}
//-----------------------------------------------------------------------------
void CFrame::invalidate (const VSTGUI::CRect &rect)
{
VSTGUI::CRect rectView;
long i;
for (i = 0; i < viewCount; i++)
{
if (ppViews[i])
{
ppViews[i]->getViewSize (rectView);
if (rect.rectOverlap (rectView))
ppViews[i]->setDirty (true);
}
}
}
//-----------------------------------------------------------------------------
// CCView Implementation
//-----------------------------------------------------------------------------
CCView::CCView (CView *pView)
: pView (pView), pNext (0), pPrevious (0)
{
if (pView)
pView->remember ();
}
//-----------------------------------------------------------------------------
CCView::~CCView ()
{
if (pView)
pView->forget ();
}
#define FOREACHSUBVIEW for (CCView *pSv = pFirstView; pSv; pSv = pSv->pNext) {CView *pV = pSv->pView;
#define ENDFOR }
//-----------------------------------------------------------------------------
void modifyDrawContext (long save[4], CDrawContext* pContext, VSTGUI::CRect& size);
void restoreDrawContext (CDrawContext* pContext, long save[4]);
char* kMsgCheckIfViewContainer = "kMsgCheckIfViewContainer";
//-----------------------------------------------------------------------------
// CViewContainer Implementation
//-----------------------------------------------------------------------------
CViewContainer::CViewContainer (const VSTGUI::CRect &rect, CFrame *pParent, CBitmap *pBackground)
: CView (rect), pFirstView (0), pLastView (0), pBackground (pBackground),
mode (kNormalUpdate), pOffscreenContext (0), bDrawInOffscreen (true)
{
#if MACX
bDrawInOffscreen = false;
#endif
backgroundOffset (0, 0);
this->pParent = pParent;
if (pBackground)
pBackground->remember ();
backgroundColor = kBlackCColor;
}
//-----------------------------------------------------------------------------
CViewContainer::~CViewContainer ()
{
if (pBackground)
pBackground->forget ();
// remove all views
removeAll (true);
#if !BEOS
if (pOffscreenContext)
delete pOffscreenContext;
pOffscreenContext = 0;
#endif
}
//-----------------------------------------------------------------------------
void CViewContainer::setViewSize (VSTGUI::CRect &rect)
{
CView::setViewSize (rect);
#if !BEOS
if (pOffscreenContext)
{
delete pOffscreenContext;
pOffscreenContext = new COffscreenContext (pParent, size.width (), size.height (), kBlackCColor);
}
#endif
}
//-----------------------------------------------------------------------------
void CViewContainer::setBackground (CBitmap *background)
{
if (pBackground)
pBackground->forget ();
pBackground = background;
if (pBackground)
pBackground->remember ();
}
//-----------------------------------------------------------------------------
void CViewContainer::setBackgroundColor (CColor color)
{
backgroundColor = color;
}
//------------------------------------------------------------------------------
long CViewContainer::notify (CView* sender, const char* message)
{
if (message == kMsgCheckIfViewContainer)
return kMessageNotified;
return kMessageUnknown;
}
//-----------------------------------------------------------------------------
void CViewContainer::addView (CView *pView)
{
if (!pView)
return;
CCView *pSv = new CCView (pView);
pView->pParent = pParent;
pView->pParentView = this;
CCView *pV = pFirstView;
if (!pV)
{
pLastView = pFirstView = pSv;
}
else
{
while (pV->pNext)
pV = pV->pNext;
pV->pNext = pSv;
pSv->pPrevious = pV;
pLastView = pSv;
}
pView->attached (this);
pView->setDirty ();
}
//-----------------------------------------------------------------------------
void CViewContainer::addView (CView *pView, VSTGUI::CRect &mouseableArea, bool mouseEnabled)
{
if (!pView)
return;
pView->setMouseEnabled (mouseEnabled);
pView->setMouseableArea (mouseableArea);
addView (pView);
}
//-----------------------------------------------------------------------------
void CViewContainer::removeAll (const bool &withForget)
{
CCView *pV = pFirstView;
while (pV)
{
CCView *pNext = pV->pNext;
if (pV->pView)
{
pV->pView->removed (this);
if (withForget)
pV->pView->forget ();
}
delete pV;
pV = pNext;
}
pFirstView = 0;
pLastView = 0;
}
//-----------------------------------------------------------------------------
void CViewContainer::removeView (CView *pView, const bool &withForget)
{
CCView *pV = pFirstView;
while (pV)
{
if (pView == pV->pView)
{
CCView *pNext = pV->pNext;
CCView *pPrevious = pV->pPrevious;
if (pV->pView)
{
pV->pView->removed (this);
if (withForget)
pV->pView->forget ();
}
delete pV;
if (pPrevious)
{
pPrevious->pNext = pNext;
if (pNext)
pNext->pPrevious = pPrevious;
else
pLastView = pPrevious;
}
else
{
pFirstView = pNext;
if (pNext)
pNext->pPrevious = 0;
else
pLastView = 0;
}
pV = pNext;
}
else
pV = pV->pNext;
}
}
//-----------------------------------------------------------------------------
bool CViewContainer::isChild (CView *pView)
{
bool found = false;
CCView *pV = pFirstView;
while (pV)
{
if (pView == pV->pView)
{
found = true;
break;
}
pV = pV->pNext;
}
return found;
}
//-----------------------------------------------------------------------------
long CViewContainer::getNbViews ()
{
long nb = 0;
CCView *pV = pFirstView;
while (pV)
{
pV = pV->pNext;
nb++;
}
return nb;
}
//-----------------------------------------------------------------------------
CView *CViewContainer::getView (long index)
{
long nb = 0;
CCView *pV = pFirstView;
while (pV)
{
if (nb == index)
return pV->pView;
pV = pV->pNext;
nb++;
}
return 0;
}
//-----------------------------------------------------------------------------
void CViewContainer::draw (CDrawContext *pContext)
{
CDrawContext *pC;
long save[4];
#if BEOS
// create offscreen
if (pBackground)
pC = new COffscreenContext (pContext, pBackground);
else
pC = new COffscreenContext (pParent, size.width (), size.height (), backgroundColor);
#else
if (!pOffscreenContext && bDrawInOffscreen)
pOffscreenContext = new COffscreenContext (pParent, size.width (), size.height (), kBlackCColor);
if (bDrawInOffscreen)
pC = pOffscreenContext;
else
{
pC = pContext;
modifyDrawContext (save, pContext, size);
}
// draw the background
VSTGUI::CRect r (0, 0, size.width (), size.height ());
if (pBackground)
{
if (bTransparencyEnabled)
pBackground->drawTransparent (pC, r, backgroundOffset);
else
pBackground->draw (pC, r, backgroundOffset);
}
else if (!bTransparencyEnabled)
{
pC->setFillColor (backgroundColor);
pC->fillRect (r);
}
#endif
// draw each view
FOREACHSUBVIEW
pV->draw (pC);
ENDFOR
// transfert offscreen
if (bDrawInOffscreen)
((COffscreenContext*)pC)->copyFrom (pContext, size);
else
restoreDrawContext (pContext, save);
#if BEOS
delete pC;
#endif
setDirty (false);
}
//-----------------------------------------------------------------------------
void CViewContainer::drawBackgroundRect (CDrawContext *pContext, VSTGUI::CRect& _updateRect)
{
if (pBackground)
{
VSTGUI::CPoint p (_updateRect.left + backgroundOffset.h, _updateRect.top + backgroundOffset.v);
if (bTransparencyEnabled)
pBackground->drawTransparent (pContext, _updateRect, p);
else
pBackground->draw (pContext, _updateRect, p);
}
else if (!bTransparencyEnabled)
{
pContext->setFillColor (backgroundColor);
pContext->fillRect (_updateRect);
}
}
//-----------------------------------------------------------------------------
void CViewContainer::drawRect (CDrawContext *pContext, VSTGUI::CRect& _updateRect)
{
CDrawContext *pC;
long save[4];
#if BEOS
// create offscreen
if (pBackground)
pC = new COffscreenContext (pContext, pBackground);
else
pC = new COffscreenContext (pParent, size.width (), size.height (), backgroundColor);
#else
if (!pOffscreenContext && bDrawInOffscreen)
pOffscreenContext = new COffscreenContext (pParent, size.width (), size.height (), kBlackCColor);
if (bDrawInOffscreen)
pC = pOffscreenContext;
else
{
pC = pContext;
modifyDrawContext (save, pContext, size);
}
VSTGUI::CRect updateRect (_updateRect);
updateRect.bound (size);
VSTGUI::CRect clientRect (updateRect);
clientRect.offset (-size.left, -size.top);
// draw the background
if (pBackground)
{
VSTGUI::CPoint bgoffset (clientRect.left + backgroundOffset.h, clientRect.top+ backgroundOffset.v);
if (bTransparencyEnabled)
pBackground->drawTransparent (pC, clientRect, bgoffset);
else
pBackground->draw (pC, clientRect, bgoffset);
}
else if (!bTransparencyEnabled)
{
pC->setFillColor (backgroundColor);
pC->fillRect (clientRect);
}
#endif
// draw each view
FOREACHSUBVIEW
if (pV->checkUpdate (clientRect))
pV->draw (pC);
ENDFOR
// transfert offscreen
if (bDrawInOffscreen)
((COffscreenContext*)pC)->copyFrom (pContext, updateRect, VSTGUI::CPoint (clientRect.left, clientRect.top));
else
restoreDrawContext (pContext, save);
#if BEOS
delete pC;
#endif
setDirty (false);
}
//-----------------------------------------------------------------------------
bool CViewContainer::hitTestSubViews (const VSTGUI::CPoint& where, const long buttons)
{
VSTGUI::CPoint where2 (where);
where2.offset (-size.left, -size.top);
CCView *pSv = pLastView;
while (pSv)
{
CView *pV = pSv->pView;
if (pV && pV->getMouseEnabled () && pV->hitTest (where2, buttons))
return true;
pSv = pSv->pPrevious;
}
return false;
}
//-----------------------------------------------------------------------------
bool CViewContainer::hitTest (const VSTGUI::CPoint& where, const long buttons)
{
//return hitTestSubViews (where); would change default behavior
return CView::hitTest (where, buttons);
}
//-----------------------------------------------------------------------------
void CViewContainer::mouse (CDrawContext *pContext, VSTGUI::CPoint &where)
{
// convert to relativ pos
VSTGUI::CPoint where2 (where);
where2.offset (-size.left, -size.top);
long save[4];
modifyDrawContext (save, pContext, size);
long buttons = -1;
if (pContext)
buttons = pContext->getMouseButtons ();
CCView *pSv = pLastView;
while (pSv)
{
CView *pV = pSv->pView;
if (pV && pV->getMouseEnabled () && pV->hitTest (where2, buttons))
{
pV->mouse (pContext, where2);
break;
}
pSv = pSv->pPrevious;
}
restoreDrawContext (pContext, save);
}
//-----------------------------------------------------------------------------
long CViewContainer::onKeyDown (VstKeyCode& keyCode)
{
long result = -1;
CCView* pSv = pLastView;
while (pSv)
{
long result = pSv->pView->onKeyDown (keyCode);
if (result != -1)
break;
pSv = pSv->pPrevious;
}
return result;
}
//-----------------------------------------------------------------------------
long CViewContainer::onKeyUp (VstKeyCode& keyCode)
{
long result = -1;
CCView* pSv = pLastView;
while (pSv)
{
long result = pSv->pView->onKeyUp (keyCode);
if (result != -1)
break;
pSv = pSv->pPrevious;
}
return result;
}
//-----------------------------------------------------------------------------
bool CViewContainer::onDrop (void **ptrItems, long nbItems, long type, VSTGUI::CPoint &where)
{
if (!pParent)
return false;
// convert to relativ pos
VSTGUI::CPoint where2 (where);
where2.offset (-size.left, -size.top);
bool result = false;
CCView *pSv = pLastView;
while (pSv)
{
CView *pV = pSv->pView;
if (pV && pV->getMouseEnabled () && where2.isInside (pV->mouseableArea))
{
if (pV->onDrop (ptrItems, nbItems, type, where2))
{
result = true;
break;
}
}
pSv = pSv->pPrevious;
}
return result;
}
//-----------------------------------------------------------------------------
bool CViewContainer::onWheel (CDrawContext *pContext, const VSTGUI::CPoint &where, float distance)
{
bool result = false;
CView *view = getCurrentView ();
if (view)
{
// convert to relativ pos
VSTGUI::CPoint where2 (where);
where2.offset (-size.left, -size.top);
long save[4];
modifyDrawContext (save, pContext, size);
result = view->onWheel (pContext, where2, distance);
restoreDrawContext (pContext, save);
}
return result;
}
//-----------------------------------------------------------------------------
void CViewContainer::update (CDrawContext *pContext)
{
switch (mode)
{
//---Normal : redraw all...
case kNormalUpdate:
if (isDirty ())
draw (pContext);
break;
//---Redraw only dirty controls-----
case kOnlyDirtyUpdate:
if (bDirty)
draw (pContext);
else if (bDrawInOffscreen && pOffscreenContext)
{
bool doCopy = false;
if (isDirty ())
doCopy = true;
FOREACHSUBVIEW
pV->update (pOffscreenContext);
ENDFOR
// transfert offscreen
if (doCopy)
pOffscreenContext->copyFrom (pContext, size);
}
else
{
long save[4];
modifyDrawContext (save, pContext, size);
FOREACHSUBVIEW
if (pV->isDirty ())
{
long oldMode = 0;
CViewContainer* child = 0;
if (pV->notify (this, kMsgCheckIfViewContainer))
{
child = (CViewContainer*)pV;
oldMode = child->getMode ();
child->setMode (kNormalUpdate);
}
VSTGUI::CRect viewSize;
pV->getViewSize (viewSize);
drawBackgroundRect (pContext, viewSize);
pV->update (pContext);
if (child)
child->setMode (oldMode);
}
ENDFOR
restoreDrawContext (pContext, save);
}
setDirty (false);
break;
}
}
//-----------------------------------------------------------------------------
void CViewContainer::looseFocus (CDrawContext *pContext)
{
FOREACHSUBVIEW
pV->looseFocus (pContext);
ENDFOR
}
//-----------------------------------------------------------------------------
void CViewContainer::takeFocus (CDrawContext *pContext)
{
FOREACHSUBVIEW
pV->takeFocus (pContext);
ENDFOR
}
//-----------------------------------------------------------------------------
bool CViewContainer::isDirty ()
{
if (bDirty)
return true;
FOREACHSUBVIEW
if (pV->isDirty ())
return true;
ENDFOR
return false;
}
//-----------------------------------------------------------------------------
CView *CViewContainer::getCurrentView ()
{
if (!pParent)
return 0;
// get the current position
VSTGUI::CPoint where;
pParent->getCurrentLocation (where);
// convert to relativ pos
where.offset (-size.left, -size.top);
CCView *pSv = pLastView;
while (pSv)
{
CView *pV = pSv->pView;
if (pV && where.isInside (pV->mouseableArea))
return pV;
pSv = pSv->pPrevious;
}
return 0;
}
//-----------------------------------------------------------------------------
bool CViewContainer::removed (CView* parent)
{
#if !BEOS
if (pOffscreenContext)
delete pOffscreenContext;
pOffscreenContext = 0;
#endif
return true;
}
//-----------------------------------------------------------------------------
bool CViewContainer::attached (CView* view)
{
#if !BEOS
// create offscreen bitmap
if (!pOffscreenContext && bDrawInOffscreen)
pOffscreenContext = new COffscreenContext (pParent, size.width (), size.height (), kBlackCColor);
#endif
return true;
}
//-----------------------------------------------------------------------------
void CViewContainer::useOffscreen (bool b)
{
bDrawInOffscreen = b;
#if !BEOS
if (!bDrawInOffscreen && pOffscreenContext)
{
delete pOffscreenContext;
pOffscreenContext = 0;
}
#endif
}
//-----------------------------------------------------------------------------
void modifyDrawContext (long save[4], CDrawContext* pContext, VSTGUI::CRect& size)
{
// get the position of the context in the screen
long offParentX = 0;
long offParentY = 0;
#if WINDOWS
RECT rctTempWnd;
GetWindowRect ((HWND)(pContext->getWindow ()), &rctTempWnd);
offParentX = rctTempWnd.left;
offParentY = rctTempWnd.top;
#endif
// store
save[0] = pContext->offsetScreen.h;
save[1] = pContext->offsetScreen.v;
save[2] = pContext->offset.h;
save[3] = pContext->offset.v;
pContext->offsetScreen.h = size.left + offParentX;
pContext->offsetScreen.v = size.top + offParentY;
pContext->offset.h = size.left;
pContext->offset.v = size.top;
}
//-----------------------------------------------------------------------------
void restoreDrawContext (CDrawContext* pContext, long save[4])
{
// restore
pContext->offsetScreen.h = save[0];
pContext->offsetScreen.v = save[1];
pContext->offset.h = save[2];
pContext->offset.v = save[3];
}
//-----------------------------------------------------------------------------
// CBitmap Implementation
//-----------------------------------------------------------------------------
CBitmap::CBitmap (long resourceID)
: resourceID (resourceID), nbReference (1), width (0), height (0)
{
#if DEBUG
gNbCBitmap++;
#endif
#if WINDOWS
pMask = 0;
pHandle = LoadBitmap (GetInstance (), MAKEINTRESOURCE (resourceID));
BITMAP bm;
if (pHandle && GetObject (pHandle, sizeof (bm), &bm))
{
width = bm.bmWidth;
height = bm.bmHeight;
}
#elif MAC
pHandle = 0;
pMask = 0;
#if (MACX && !PLUGGUI)
if (gBundleRef)
{
char filename [PATH_MAX];
sprintf (filename, "bmp%05d", (int)resourceID);
CFStringRef cfStr = CFStringCreateWithCString (NULL, filename, kCFStringEncodingASCII);
if (cfStr)
{
CFURLRef url = NULL;
int i = 0;
while (url == NULL)
{
static CFStringRef resTypes [] = { CFSTR("bmp"), CFSTR("png"), CFSTR("jpg"), CFSTR("pict"), NULL };
url = CFBundleCopyResourceURL ((CFBundleRef)gBundleRef, cfStr, resTypes[i], NULL);
if (resTypes[++i] == NULL)
break;
}
CFRelease (cfStr);
if (url)
{
FSRef fsRef;
if (CFURLGetFSRef (url, &fsRef))
{
FSSpec fsSpec;
FSCatalogInfoBitmap infoBitmap = kFSCatInfoNone;
if (FSGetCatalogInfo (&fsRef, infoBitmap, NULL, NULL, &fsSpec, NULL) == noErr)
{
ComponentInstance gi;
GetGraphicsImporterForFile (&fsSpec, &gi);
if (gi)
{
Rect r;
GraphicsImportGetSourceRect (gi, &r);
OSErr err = NewGWorld ((GWorldPtr*)&pHandle, 0, &r, 0, 0, 0);
if (!err)
{
width = r.right;
height = r.bottom;
GraphicsImportSetGWorld (gi, (GWorldPtr)pHandle, 0);
GraphicsImportDraw (gi);
}
CloseComponent (gi);
}
}
}
}
else
{
fprintf (stderr, "Bitmap Nr.:%d not found.\n", (int)resourceID);
}
}
}
#endif
if (pHandle == 0)
{
Handle picHandle = GetResource ('PICT', resourceID);
if (picHandle)
{
HLock (picHandle);
PictInfo info;
GetPictInfo ((PicHandle)picHandle, &info, recordComments, 0, systemMethod, 0);
width = info.sourceRect.right;
height = info.sourceRect.bottom;
OSErr err = NewGWorld ((GWorldPtr*)&pHandle, 0, &info.sourceRect, 0, 0, 0);
if (!err)
{
GWorldPtr oldPort;
GDHandle oldDevice;
GetGWorld (&oldPort, &oldDevice);
SetGWorld ((GWorldPtr)pHandle, 0);
DrawPicture ((PicHandle)picHandle, &info.sourceRect);
SetGWorld (oldPort, oldDevice);
}
HUnlock (picHandle);
ReleaseResource (picHandle);
}
}
#elif MOTIF
bool found = false;
long i = 0;
long ncolors, cpp;
pHandle = 0;
pMask = 0;
// find the good pixmap resource
while (xpmResources[i].id != 0)
{
if (xpmResources[i].id == resourceID)
{
if (xpmResources[i].xpm != NULL)
{
found = true;
ppDataXpm = xpmResources[i].xpm;
xpmGetValues (ppDataXpm, &width, &height, &ncolors, &cpp);
break;
}
}
i++;
}
if (!found)
ppDataXpm = 0;
#elif BEOS
bbitmap = 0;
transparencySet = false;
if (resourceFile == 0)
{
// this is a hack to find the plug-in on the disk to access resources.
const char* locate_me = "";
int32 cookie = 0;
image_info iinfo;
uint32 here = uint32 (locate_me);
while (get_next_image_info (0, &cookie, &iinfo) == B_OK)
{
uint32 begin = uint32 (iinfo.text);
if (begin <= here && here <= begin + iinfo.text_size)
break;
}
BFile resource (iinfo.name, B_READ_ONLY);
resourceFile = new BResources (&resource);
resourceFile->PreloadResourceType ();
}
size_t outSize;
const char* res = (const char*) resourceFile->LoadResource ('RAWT', resourceID, &outSize);
if (res)
{
BMemoryIO memoryIO (res, outSize);
bbitmap = BTranslationUtils::GetBitmap (&memoryIO);
if (bbitmap)
{
BRect rect = bbitmap->Bounds ();
width = (long) rect.Width () + 1;
height = (long) rect.Height () + 1;
}
}
if (!bbitmap)
fprintf (stderr, "********* Resource %d could NOT be loaded!\n", (int)resourceID);
#endif
setTransparentColor (kTransparentCColor);
#if DEBUG
gBitmapAllocation += height * width;
#endif
}
//-----------------------------------------------------------------------------
CBitmap::CBitmap (CFrame &frame, long width, long height)
: nbReference (1), width (width), height (height)
{
#if DEBUG
gNbCBitmap++;
#endif
#if WINDOWS
HDC hScreen = GetDC (0);
pHandle = CreateCompatibleBitmap (hScreen, width, height);
ReleaseDC (0, hScreen);
pMask = 0;
#elif MAC
pHandle = 0;
pMask = 0;
Rect r;
r.left = r.top = 0;
r.right = width;
r.bottom = height;
NewGWorld ((GWorldPtr*)&pHandle, 0, &r, 0, 0, 0);
// todo: init pixels
#elif MOTIF
pXdisplay = frame.getDisplay ();
Drawable pWindow = frame.getWindow ();
pMask = 0;
pHandle = (void*)XCreatePixmap (pXdisplay, (Drawable)pWindow, width, height, frame.getDepth ());
#elif BEOS
bbitmap = 0;
transparencySet = false;
#endif
setTransparentColor (kTransparentCColor);
}
//-----------------------------------------------------------------------------
CBitmap::~CBitmap ()
{
#if DEBUG
gNbCBitmap--;
gBitmapAllocation -= height * width;
#endif
#if WINDOWS
if (pHandle)
DeleteObject (pHandle);
if (pMask)
DeleteObject (pMask);
#elif MAC
if (pHandle)
DisposeGWorld ((GWorldPtr)pHandle);
if (pMask)
DisposeGWorld ((GWorldPtr)pMask);
#elif MOTIF
if (pHandle)
XFreePixmap (pXdisplay, (Pixmap)pHandle);
if (pMask)
XFreePixmap (pXdisplay, (Pixmap)pMask);
#elif BEOS
if (bbitmap)
delete bbitmap;
#endif
}
//-----------------------------------------------------------------------------
void *CBitmap::getHandle ()
{
#if WINDOWS||MOTIF
return pHandle;
#elif MAC
return pHandle;
#elif BEOS
return bbitmap;
#endif
}
//-----------------------------------------------------------------------------
bool CBitmap::isLoaded ()
{
#if MOTIF
if (ppDataXpm)
return true;
#else
if (getHandle ())
return true;
#endif
return false;
}
//-----------------------------------------------------------------------------
void CBitmap::remember ()
{
nbReference++;
}
//-----------------------------------------------------------------------------
void CBitmap::forget ()
{
if (nbReference > 0)
{
nbReference--;
if (nbReference == 0)
delete this;
}
}
//-----------------------------------------------------------------------------
void CBitmap::draw (CDrawContext *pContext, VSTGUI::CRect &rect, const VSTGUI::CPoint &offset)
{
#if WINDOWS
if (pHandle)
{
HGDIOBJ hOldObj;
HDC hdcMemory = CreateCompatibleDC ((HDC)pContext->pSystemContext);
hOldObj = SelectObject (hdcMemory, pHandle);
BitBlt ((HDC)pContext->pSystemContext,
rect.left + pContext->offset.h, rect.top + pContext->offset.v, rect.width (), rect.height (),
(HDC)hdcMemory, offset.h, offset.v, SRCCOPY);
SelectObject (hdcMemory, hOldObj);
DeleteDC (hdcMemory);
}
#elif MAC
Rect source, dest;
dest.top = rect.top + pContext->offset.v;
dest.left = rect.left + pContext->offset.h;
dest.bottom = dest.top + rect.height ();
dest.right = dest.left + rect.width ();
source.top = offset.v;
source.left = offset.h;
source.bottom = source.top + rect.height ();
source.right = source.left + rect.width ();
pContext->getPort ();
BitMapPtr bitmapPtr = pContext->getBitmap ();
if (pHandle && bitmapPtr)
{
PixMapHandle pmHandle = GetGWorldPixMap ((GWorldPtr)pHandle);
if (pmHandle && LockPixels (pmHandle))
{
RGBColor oldForeColor, oldBackColor;
GetForeColor (&oldForeColor);
GetBackColor (&oldBackColor);
::BackColor (whiteColor);
::ForeColor (blackColor);
CopyBits ((BitMapPtr)*pmHandle, bitmapPtr, &source, &dest, srcCopy, 0L);
#if MACX
QDAddRectToDirtyRegion (pContext->getPort (), &dest);
#endif
RGBForeColor (&oldForeColor);
RGBBackColor (&oldBackColor);
UnlockPixels (pmHandle);
}
}
pContext->releaseBitmap ();
#elif MOTIF
if (!pHandle)
{
// the first time try to decode the pixmap
pHandle = createPixmapFromXpm (pContext);
if (!pHandle)
return;
// keep a trace of the display for deletion
pXdisplay = pContext->pDisplay;
}
#if DEVELOPMENT
if (!(offset.h >= 0 && offset.v >= 0 &&
rect.width () <= (getWidth () - offset.h) &&
rect.height () <= (getHeight () - offset.v)))
{
fprintf (stderr, "%s(%d) -> Assert failed: try to display outside from the bitmap\n", __FILE__, __LINE__);
return;
}
#endif
XCopyArea (pContext->pDisplay, (Drawable)pHandle,
(Drawable)pContext->pWindow,
(GC)pContext->pSystemContext, offset.h, offset.v,
rect.width (), rect.height (), rect.left, rect.top);
#elif BEOS
BRect brect (rect.left, rect.top, rect.right - 1, rect.bottom - 1);
BRect drect = brect;
brect.OffsetTo (offset.h, offset.v);
drect.OffsetBy (pContext->offset.h, pContext->offset.v);
pContext->pView->SetDrawingMode (B_OP_COPY);
pContext->pView->DrawBitmap (bbitmap, brect, drect);
#endif
}
//-----------------------------------------------------------------------------
void CBitmap::drawTransparent (CDrawContext *pContext, VSTGUI::CRect &rect, const VSTGUI::CPoint &offset)
{
#if WINDOWS
BITMAP bm;
HDC hdcBitmap;
POINT ptSize;
hdcBitmap = CreateCompatibleDC ((HDC)pContext->pSystemContext);
SelectObject (hdcBitmap, pHandle); // Select the bitmap
GetObject (pHandle, sizeof (BITMAP), (LPSTR)&bm);
ptSize.x = bm.bmWidth; // Get width of bitmap
ptSize.y = bm.bmHeight; // Get height of bitmap
DPtoLP (hdcBitmap, &ptSize, 1); // Convert from device to logical points
DrawTransparent (pContext, rect, offset, hdcBitmap, ptSize, (HBITMAP)pMask, RGB(transparentCColor.red, transparentCColor.green, transparentCColor.blue));
DeleteDC (hdcBitmap);
#elif MAC
Rect source, dest;
dest.top = rect.top + pContext->offset.v;
dest.left = rect.left + pContext->offset.h;
dest.bottom = dest.top + rect.height ();
dest.right = dest.left + rect.width ();
source.top = offset.v;
source.left = offset.h;
source.bottom = source.top + rect.height ();
source.right = source.left + rect.width ();
pContext->getPort ();
BitMapPtr bitmapPtr = pContext->getBitmap ();
if (pHandle && bitmapPtr)
{
PixMapHandle pmHandle = GetGWorldPixMap ((GWorldPtr)pHandle);
if (pmHandle && LockPixels (pmHandle))
{
RGBColor oldForeColor, oldBackColor;
GetForeColor (&oldForeColor);
GetBackColor (&oldBackColor);
RGBColor col;
CColor2RGBColor (transparentCColor, col);
RGBBackColor (&col);
::ForeColor (blackColor);
if (pMask)
{
PixMapHandle pmHandleMask = GetGWorldPixMap ((GWorldPtr)pMask);
if (pmHandleMask && LockPixels (pmHandleMask))
{
CopyMask ((BitMapPtr)*pmHandle, (BitMapPtr)*pmHandleMask, bitmapPtr,
&source, &source, &dest);
UnlockPixels (pmHandleMask);
}
}
else
CopyBits ((BitMapPtr)*pmHandle, bitmapPtr, &source, &dest, transparent, 0L);
RGBForeColor (&oldForeColor);
RGBBackColor (&oldBackColor);
#if MACX
QDAddRectToDirtyRegion (pContext->getPort (), &dest);
#endif
UnlockPixels (pmHandle);
}
}
pContext->releaseBitmap ();
#elif MOTIF
if (!pHandle)
{
// the first time try to decode the pixmap
pHandle = createPixmapFromXpm (pContext);
if (!pHandle)
return;
// keep a trace of the display for deletion
pXdisplay = pContext->pDisplay;
}
if (pMask == 0)
{
// get image from the pixmap
XImage* image = XGetImage (pContext->pDisplay, (Drawable)pHandle,
0, 0, width, height, AllPlanes, ZPixmap);
assert (image);
// create the bitmap mask
pMask = (void*)XCreatePixmap (pContext->pDisplay, (Drawable)pContext->pWindow,
width, height, 1);
assert (pMask);
// create a associated GC
XGCValues values;
values.foreground = 1;
GC gc = XCreateGC (pContext->pDisplay, (Drawable)pMask, GCForeground, &values);
// clear the mask
XFillRectangle (pContext->pDisplay, (Drawable)pMask, gc, 0, 0, width, height);
// get the transparent color index
int color = pContext->getIndexColor (transparentCColor);
// inverse the color
values.foreground = 0;
XChangeGC (pContext->pDisplay, gc, GCForeground, &values);
// compute the mask
XPoint *points = new XPoint [height * width];
int x, y, nbPoints = 0;
switch (image->depth)
{
case 8:
for (y = 0; y < height; y++)
{
char* src = image->data + (y * image->bytes_per_line);
for (x = 0; x < width; x++)
{
if (src[x] == color)
{
points[nbPoints].x = x;
points[nbPoints].y = y;
nbPoints++;
}
}
}
break;
case 24: {
int bytesPerPixel = image->bits_per_pixel >> 3;
char *lp = image->data;
for (y = 0; y < height; y++)
{
char* cp = lp;
for (x = 0; x < width; x++)
{
if (*(int*)cp == color)
{
points[nbPoints].x = x;
points[nbPoints].y = y;
nbPoints++;
}
cp += bytesPerPixel;
}
lp += image->bytes_per_line;
}
} break;
default :
break;
}
XDrawPoints (pContext->pDisplay, (Drawable)pMask, gc,
points, nbPoints, CoordModeOrigin);
// free
XFreeGC (pContext->pDisplay, gc);
delete []points;
// delete
XDestroyImage (image);
}
// set the new clipmask
XGCValues value;
value.clip_mask = (Pixmap)pMask;
value.clip_x_origin = rect.left - offset.h;
value.clip_y_origin = rect.top - offset.v;
XChangeGC (pContext->pDisplay, (GC)pContext->pSystemContext,
GCClipMask|GCClipXOrigin|GCClipYOrigin, &value);
XCopyArea (pContext->pDisplay, (Drawable)pHandle, (Drawable)pContext->pWindow,
(GC)pContext->pSystemContext, offset.h, offset.v,
rect.width (), rect.height (), rect.left, rect.top);
// unset the clipmask
XSetClipMask (pContext->pDisplay, (GC)pContext->pSystemContext, None);
#elif BEOS
if (!transparencySet)
{
uint32 c32 = transparentCColor.red | (transparentCColor.green << 8) | (transparentCColor.blue << 16);
uint32 *pix = (uint32*) bbitmap->Bits();
uint32 ctr = B_TRANSPARENT_32_BIT.red | (B_TRANSPARENT_32_BIT.green << 8) | (B_TRANSPARENT_32_BIT.blue << 16) | (B_TRANSPARENT_32_BIT.alpha << 24);
for (int32 z = 0, count = bbitmap->BitsLength() / 4; z < count; z++)
{
if ((pix[z] & 0xffffff) == c32)
pix[z] = ctr;
}
transparencySet = true;
}
BRect brect (rect.left, rect.top, rect.right - 1, rect.bottom - 1);
BRect drect = brect;
brect.OffsetTo (offset.h, offset.v);
drect.OffsetBy (pContext->offset.h, pContext->offset.v);
pContext->pView->SetDrawingMode (B_OP_OVER);
pContext->pView->DrawBitmap (bbitmap, brect, drect);
#endif
}
//-----------------------------------------------------------------------------
void CBitmap::drawAlphaBlend (CDrawContext *pContext, VSTGUI::CRect &rect, const VSTGUI::CPoint &offset, unsigned char alpha)
{
#if WINDOWS
if (pHandle)
{
HGDIOBJ hOldObj;
HDC hdcMemory = CreateCompatibleDC ((HDC)pContext->pSystemContext);
hOldObj = SelectObject (hdcMemory, pHandle);
BLENDFUNCTION blendFunction;
blendFunction.BlendOp = AC_SRC_OVER;
blendFunction.BlendFlags = 0;
blendFunction.SourceConstantAlpha = alpha;
blendFunction.AlphaFormat = 0;//AC_SRC_NO_ALPHA;
#if DYNAMICALPHABLEND
(*pfnAlphaBlend) ((HDC)pContext->pSystemContext,
rect.left + pContext->offset.h, rect.top + pContext->offset.v,
rect.width (), rect.height (),
(HDC)hdcMemory,
offset.h, offset.v,
rect.width (), rect.height (),
blendFunction);
#else
AlphaBlend ((HDC)pContext->pSystemContext,
rect.left + pContext->offset.h, rect.top + pContext->offset.v,
rect.width (), rect.height (),
(HDC)hdcMemory,
offset.h, offset.v,
rect.width (), rect.height (),
blendFunction);
#endif
SelectObject (hdcMemory, hOldObj);
DeleteDC (hdcMemory);
}
#elif MAC
Rect source, dest;
dest.top = rect.top + pContext->offset.v;
dest.left = rect.left + pContext->offset.h;
dest.bottom = dest.top + rect.height ();
dest.right = dest.left + rect.width ();
source.top = offset.v;
source.left = offset.h;
source.bottom = source.top + rect.height ();
source.right = source.left + rect.width ();
pContext->getPort ();
BitMapPtr bitmapPtr = pContext->getBitmap ();
if (bitmapPtr)
{
RGBColor col;
CColor color = {alpha, alpha, alpha, 0};
CColor2RGBColor (color, col);
OpColor (&col);
if (pHandle)
{
PixMapHandle pmHandle = GetGWorldPixMap ((GWorldPtr)pHandle);
if (pmHandle && LockPixels (pmHandle))
{
RGBColor oldForeColor, oldBackColor;
GetForeColor (&oldForeColor);
GetBackColor (&oldBackColor);
::BackColor (whiteColor);
::ForeColor (blackColor);
CopyBits ((BitMapPtr)*pmHandle, bitmapPtr, &source, &dest, blend, 0L);
#if MACX
QDAddRectToDirtyRegion (pContext->getPort (), &dest);
#endif
RGBForeColor (&oldForeColor);
RGBBackColor (&oldBackColor);
UnlockPixels (pmHandle);
}
}
}
pContext->releaseBitmap ();
#endif
}
//-----------------------------------------------------------------------------
void CBitmap::setTransparentColor (const CColor color)
{
transparentCColor = color;
}
//-----------------------------------------------------------------------------
void CBitmap::setTransparencyMask (CDrawContext* pContext, const VSTGUI::CPoint& offset)
{
#if WINDOWS
if (pMask)
DeleteObject (pMask);
VSTGUI::CRect r (0, 0, width, height);
r.offset (offset.h, offset.v);
pMask = CreateMaskBitmap (pContext, r, transparentCColor);
#elif MAC
if (pMask)
DisposeGWorld ((GWorldPtr)pMask);
pMask = 0;
Rect r;
r.left = r.top = 0;
r.right = width;
r.bottom = height;
OSErr err = NewGWorld ((GWorldPtr*)&pMask, 1, &r, 0, 0, 0); // create monochrome GWorld
if (!err)
{
GWorldPtr oldPort;
GDHandle oldDevice;
GetGWorld (&oldPort, &oldDevice);
SetGWorld ((GWorldPtr)pMask, 0);
PixMapHandle pmHandle = GetGWorldPixMap ((GWorldPtr)pMask);
BitMapPtr sourcePtr = pContext->getBitmap ();
if (sourcePtr && pmHandle && LockPixels (pmHandle))
{
RGBColor oldForeColor, oldBackColor;
GetForeColor (&oldForeColor);
GetBackColor (&oldBackColor);
RGBColor col;
CColor2RGBColor (transparentCColor, col);
RGBBackColor (&col);
::ForeColor (blackColor);
Rect src = r;
src.left += offset.h;
src.right += offset.h;
src.top += offset.v;
src.bottom += offset.v;
CopyBits (sourcePtr, (BitMapPtr)*pmHandle, &src, &r, srcCopy, 0L);
RGBForeColor (&oldForeColor);
RGBBackColor (&oldBackColor);
UnlockPixels (pmHandle);
}
pContext->releaseBitmap ();
SetGWorld (oldPort, oldDevice);
}
#else
// todo: implement me!
#endif
}
//-----------------------------------------------------------------------------
//----------------------------------------------------------------------------
#if MOTIF
//-----------------------------------------------------------------------------
void* CBitmap::createPixmapFromXpm (CDrawContext *pContext)
{
if (!ppDataXpm)
return NULL;
Pixmap pixmap = 0;
XpmAttributes attributes;
attributes.valuemask = XpmCloseness|XpmColormap|XpmVisual|XpmDepth;
attributes.closeness = 100000;
attributes.visual = pContext->getVisual ();
attributes.depth = pContext->getDepth ();
// use the pContext colormap instead of the DefaultColormapOfScreen
attributes.colormap = pContext->getColormap ();
int status;
if (attributes.depth == 8 || attributes.depth == 24)
{
#if USE_XPM
status = XpmCreatePixmapFromData (pContext->pDisplay,
(Drawable)pContext->pWindow, ppDataXpm, &pixmap, NULL, &attributes);
if (status != XpmSuccess)
{
fprintf (stderr, "createPixmapFromXpm-> XpmError: %s\n", XpmGetErrorString(status));
return NULL;
}
#else
status = createPixmapFromData (pContext->pDisplay,
(Drawable)pContext->pWindow, ppDataXpm, &pixmap, &attributes);
if (!status)
{
fprintf (stderr, "createPixmapFromXpm-> Error\n");
return NULL;
}
#endif
}
else
{
fprintf (stderr, "createPixmapFromXpm-> Depth %d not supported\n", attributes.depth);
return NULL;
}
#if DEVELOPMENT
fprintf (stderr, "createPixmapFromXpm-> There are %d requested colors\n", attributes.ncolors);
#endif
return (void*)pixmap;
}
#endif
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
#if BEOS
//----------------------------------------------------------------------------
BResources* CBitmap::resourceFile = 0;
//----------------------------------------------------------------------------
void CBitmap::closeResource ()
{
if (resourceFile)
{
delete resourceFile;
resourceFile = 0;
}
}
//----------------------------------------------------------------------------
#endif
END_NAMESPACE_VSTGUI
#if !PLUGGUI
//-----------------------------------------------------------------------------
// CFileSelector Implementation
//-----------------------------------------------------------------------------
#define stringAnyType "Any Type (*.*)"
#define stringAllTypes "All Types: ("
#define stringSelect "Select"
#define stringCancel "Cancel"
#define stringLookIn "Look in"
#define kPathMax 1024
#if WINDOWS
UINT APIENTRY SelectDirectoryHook (HWND hdlg, UINT message, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK SelectDirectoryButtonProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
FARPROC fpOldSelectDirectoryButtonProc;
UINT APIENTRY WinSaveHook (HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam);
static bool folderSelected;
static bool didCancel;
static char selDirPath[kPathMax];
#endif
BEGIN_NAMESPACE_VSTGUI
//-----------------------------------------------------------------------------
CFileSelector::CFileSelector (AudioEffectX* effect)
: effect (effect), vstFileSelect (0)
{}
//-----------------------------------------------------------------------------
CFileSelector::~CFileSelector ()
{
if (vstFileSelect)
{
if (effect && effect->canHostDo ("closeFileSelector"))
effect->closeFileSelector (vstFileSelect);
else
{
if (vstFileSelect->reserved == 1 && vstFileSelect->returnPath)
{
delete []vstFileSelect->returnPath;
vstFileSelect->returnPath = 0;
vstFileSelect->sizeReturnPath = 0;
}
if (vstFileSelect->returnMultiplePaths)
{
for (long i = 0; i < vstFileSelect->nbReturnPath; i++)
{
delete []vstFileSelect->returnMultiplePaths[i];
vstFileSelect->returnMultiplePaths[i] = 0;
}
delete[] vstFileSelect->returnMultiplePaths;
vstFileSelect->returnMultiplePaths = 0;
}
}
}
}
#if CARBON
pascal void navEventProc (const NavEventCallbackMessage callBackSelector, NavCBRecPtr callBackParms, NavCallBackUserData callBackUD);
pascal void navEventProc (const NavEventCallbackMessage callBackSelector, NavCBRecPtr callBackParms, NavCallBackUserData callBackUD)
{
AudioEffectX* effect = (AudioEffectX*)callBackUD;
switch (callBackSelector)
{
case kNavCBEvent:
{
if (callBackParms->eventData.eventDataParms.event->what == nullEvent)
effect->masterIdle ();
break;
}
}
}
#endif
//-----------------------------------------------------------------------------
long CFileSelector::run (VstFileSelect *vstFileSelect)
{
this->vstFileSelect = vstFileSelect;
vstFileSelect->nbReturnPath = 0;
vstFileSelect->returnPath[0] = 0;
if (effect
#if MACX
&& vstFileSelect->command != kVstFileSave
#endif
&& effect->canHostDo ("openFileSelector") && effect->canHostDo ("closeFileSelector"))
{
if (effect->openFileSelector (vstFileSelect))
return vstFileSelect->nbReturnPath;
}
else
{
#if WINDOWS
char filter[512];
char filePathBuffer[kPathMax];
strcpy (filePathBuffer, "");
char* filePath = filePathBuffer;
char fileName[kPathMax];
strcpy (fileName, "");
filter[0] = 0;
filePath[0] = 0;
fileName[0] = 0;
//-----------------------------------------
if (vstFileSelect->command == kVstFileLoad ||
vstFileSelect->command == kVstMultipleFilesLoad ||
vstFileSelect->command == kVstDirectorySelect)
{
char* multiBuffer = 0;
if (vstFileSelect->command == kVstMultipleFilesLoad)
{
multiBuffer = new char [kPathMax * 100];
strcpy (multiBuffer, "");
filePath = multiBuffer;
}
if (vstFileSelect->command != kVstDirectorySelect)
{
char allBuffer [kPathMax] = {0};
char* p = filter;
char* p2 = allBuffer;
const char* ext;
const char* extensions [100];
long i, j, extCount = 0;
char string[24];
for (long ty = 0; ty < vstFileSelect->nbFileTypes; ty++)
{
for (i = 0; i < 2 ; i++)
{
if (i == 0)
{
ext = vstFileSelect->fileTypes[ty].dosType;
strcpy (p, vstFileSelect->fileTypes[ty].name);
strcat (p, " (.");
strcat (p, ext);
strcat (p, ")");
p += strlen (p) + 1;
strcpy (string, "*.");
strcat (string, ext);
strcpy (p, string);
p += strlen (p);
}
else
{
if (!strcmp (vstFileSelect->fileTypes[ty].dosType, vstFileSelect->fileTypes[ty].unixType) || !strcmp (vstFileSelect->fileTypes[ty].unixType, ""))
break; // for
ext = vstFileSelect->fileTypes[ty].unixType;
strcpy (string, ";*.");
strcat (string, ext);
strcpy (p, string);
p += strlen (p);
}
bool found = false;
for (j = 0; j < extCount;j ++)
{
if (strcmp (ext, extensions [j]) == 0)
{
found = true;
break;
}
}
if (!found && extCount < 100)
extensions [extCount++] = ext;
}
p ++;
} // end for filetype
if (extCount > 1)
{
for (i = 0; i < extCount ;i ++)
{
ext = extensions [i];
strcpy (string, "*.");
strcat (string, ext);
if (p2 != allBuffer)
{
strcpy (p2, ";");
p2++;
}
strcpy (p2, string);
p2 += strlen (p2);
}
// add the : All types
strcpy (p, stringAllTypes);
strcat (p, allBuffer);
strcat (p, ")");
p += strlen (p) + 1;
strcpy (p, allBuffer);
p += strlen (p) + 1;
}
strcpy (p, stringAnyType);
p += strlen (p) + 1;
strcpy (p, "*.*");
p += strlen (p) + 1;
*p++ = 0;
*p++ = 0;
}
OPENFILENAME ofn = {0};
ofn.lStructSize = sizeof (OPENFILENAME);
HWND owner = 0;
if (effect->getEditor () && ((AEffGUIEditor*)effect->getEditor ())->getFrame ())
owner = (HWND)((AEffGUIEditor*)effect->getEditor ())->getFrame ()->getSystemWindow ();
ofn.hwndOwner = owner;
if (vstFileSelect->command == kVstDirectorySelect)
ofn.lpstrFilter = "HideFileFilter\0*.___\0\0"; // to hide files
else
ofn.lpstrFilter = filter[0] ? filter : 0;
ofn.nFilterIndex = 1;
ofn.lpstrCustomFilter = NULL;
ofn.lpstrFile = filePath;
if (vstFileSelect->command == kVstMultipleFilesLoad)
ofn.nMaxFile = 100 * kPathMax - 1;
else
ofn.nMaxFile = sizeof (filePathBuffer) - 1;
ofn.lpstrFileTitle = fileName;
ofn.nMaxFileTitle = 64;
ofn.lpstrInitialDir = vstFileSelect->initialPath;
ofn.lpstrTitle = vstFileSelect->title;
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER | OFN_ENABLESIZING | OFN_ENABLEHOOK;
if (vstFileSelect->command == kVstDirectorySelect)
{
ofn.Flags &= ~OFN_FILEMUSTEXIST;
ofn.lpfnHook = SelectDirectoryHook;
}
if (vstFileSelect->command == kVstMultipleFilesLoad)
ofn.Flags |= OFN_ALLOWMULTISELECT;
vstFileSelect->nbReturnPath = 0;
didCancel = true;
if (GetOpenFileName (&ofn) ||
((vstFileSelect->command == kVstDirectorySelect) && !didCancel && strlen (selDirPath) != 0))
{
switch (vstFileSelect->command)
{
case kVstFileLoad:
vstFileSelect->nbReturnPath = 1;
if (!vstFileSelect->returnPath)
{
vstFileSelect->reserved = 1;
vstFileSelect->returnPath = new char[strlen (ofn.lpstrFile) + 1];
vstFileSelect->sizeReturnPath = strlen (ofn.lpstrFile) + 1;
}
strcpy (vstFileSelect->returnPath, ofn.lpstrFile);
break;
case kVstMultipleFilesLoad:
{
char string[kPathMax], directory[kPathMax];
char *previous = ofn.lpstrFile;
long len;
bool dirFound = false;
bool first = true;
directory[0] = 0; // !!
vstFileSelect->returnMultiplePaths = new char*[kPathMax];
long i = 0;
while (1)
{
if (*previous != 0)
{ // something found
if (!dirFound)
{
dirFound = true;
strcpy (directory, previous);
len = strlen (previous) + 1; // including 0
previous += len;
if (*previous == 0)
{ // 1 selected file only
vstFileSelect->returnMultiplePaths[i] = new char [strlen (directory) + 1];
strcpy (vstFileSelect->returnMultiplePaths[i++], directory);
}
else
{
if (directory[strlen (directory) - 1] != '\\')
strcat (directory, "\\");
}
}
else
{
sprintf (string, "%s%s", directory, previous);
len = strlen (previous) + 1; // including 0
previous += len;
vstFileSelect->returnMultiplePaths[i] = new char [strlen (string) + 1];
strcpy (vstFileSelect->returnMultiplePaths[i++], string);
}
}
else
break;
}
vstFileSelect->nbReturnPath = i;
} break;
case kVstDirectorySelect:
vstFileSelect->nbReturnPath = 1;
if (!vstFileSelect->returnPath)
{
vstFileSelect->reserved = 1;
vstFileSelect->returnPath = new char[strlen (selDirPath) + 1];
vstFileSelect->sizeReturnPath = strlen (selDirPath) + 1;
}
strcpy (vstFileSelect->returnPath, selDirPath);
}
if (multiBuffer)
delete []multiBuffer;
return vstFileSelect->nbReturnPath;
}
if (multiBuffer)
delete []multiBuffer;
}
//-----------------------------------------
else if (vstFileSelect->command == kVstFileSave)
{
char* p = filter;
for (long ty = 0; ty < vstFileSelect->nbFileTypes; ty++)
{
const char* ext = vstFileSelect->fileTypes[ty].dosType;
if (ext)
{
strcpy (p, vstFileSelect->fileTypes[ty].name);
strcat (p, " (.");
strcat (p, ext);
strcat (p, ")");
p += strlen (p) + 1;
char string[24];
strcpy (string, "*.");
strcat (string, ext);
strcpy (p, string);
p += strlen (p) + 1;
}
}
*p++ = 0;
*p++ = 0;
OPENFILENAME ofn = {0};
ofn.lStructSize = sizeof (OPENFILENAME);
HWND owner = 0;
if (effect->getEditor () && ((AEffGUIEditor*)effect->getEditor ())->getFrame ())
owner = (HWND)((AEffGUIEditor*)effect->getEditor ())->getFrame ()->getSystemWindow ();
ofn.hwndOwner = owner;
ofn.hInstance = GetInstance ();
ofn.lpstrFilter = filter[0] ? filter : 0;
ofn.nFilterIndex = 1;
ofn.lpstrFile = filePath;
ofn.lpstrCustomFilter = NULL;
ofn.nMaxFile = sizeof (filePathBuffer) - 1;
ofn.lpstrFileTitle = fileName;
ofn.nMaxFileTitle = 64;
ofn.lpstrInitialDir = vstFileSelect->initialPath;
ofn.lpstrTitle = vstFileSelect->title;
ofn.Flags = OFN_EXPLORER | OFN_ENABLESIZING | OFN_HIDEREADONLY | OFN_ENABLEHOOK;
if (vstFileSelect->nbFileTypes >= 1)
ofn.lpstrDefExt = vstFileSelect->fileTypes[0].dosType;
// add a template view
ofn.lCustData = (DWORD)0;
ofn.lpfnHook = WinSaveHook;
if (GetSaveFileName (&ofn))
{
vstFileSelect->nbReturnPath = 1;
if (!vstFileSelect->returnPath)
{
vstFileSelect->reserved = 1;
vstFileSelect->returnPath = new char[strlen (ofn.lpstrFile) + 1];
vstFileSelect->sizeReturnPath = strlen (ofn.lpstrFile) + 1;
}
strcpy (vstFileSelect->returnPath, ofn.lpstrFile);
return vstFileSelect->nbReturnPath;
}
#if _DEBUG
else
{
DWORD err = CommDlgExtendedError (); // for breakpoint
}
#endif
}
#elif MAC
#if CARBON
NavEventUPP eventUPP = NewNavEventUPP (navEventProc);
if (vstFileSelect->command == kVstFileSave)
{
NavDialogCreationOptions dialogOptions;
NavGetDefaultDialogCreationOptions (&dialogOptions);
dialogOptions.windowTitle = CFSTR ("Select a Destination");
CFStringRef defSaveName = 0;
if (vstFileSelect->initialPath && ((FSSpec*)vstFileSelect->initialPath)->name)
{
FSSpec* defaultSpec = (FSSpec*)vstFileSelect->initialPath;
defSaveName = CFStringCreateWithPascalString (NULL, defaultSpec->name, kCFStringEncodingASCII);
if (defSaveName)
dialogOptions.saveFileName = defSaveName;
*defaultSpec->name = 0;
}
NavDialogRef dialogRef;
if (NavCreatePutFileDialog (&dialogOptions, NULL, kNavGenericSignature, eventUPP, effect, &dialogRef) == noErr)
{
AEDesc defaultLocation;
AEDesc* defLocPtr = 0;
if (vstFileSelect->initialPath)
{
FSSpec* defaultSpec = (FSSpec*)vstFileSelect->initialPath;
if (defaultSpec->parID && defaultSpec->vRefNum)
{
if (AECreateDesc (typeFSS, defaultSpec, sizeof(FSSpec), &defaultLocation) == noErr)
defLocPtr = &defaultLocation;
}
}
if (defLocPtr)
NavCustomControl (dialogRef, kNavCtlSetLocation, (void*)defLocPtr);
NavDialogRun (dialogRef);
if (defLocPtr)
AEDisposeDesc (defLocPtr);
NavReplyRecord navReply;
if (NavDialogGetReply (dialogRef, &navReply) == noErr)
{
FSRef parentFSRef;
AEKeyword theAEKeyword;
DescType typeCode;
Size actualSize;
// get the FSRef referring to the parent directory
if (AEGetNthPtr(&navReply.selection, 1, typeFSRef,
&theAEKeyword, &typeCode, &parentFSRef, sizeof(FSRef), &actualSize) == noErr)
{
FSSpec spec;
FSCatalogInfoBitmap infoBitmap = kFSCatInfoNone;
FSGetCatalogInfo (&parentFSRef, infoBitmap, NULL, NULL, &spec, NULL);
CInfoPBRec pbRec = {0};
pbRec.dirInfo.ioDrDirID = spec.parID;
pbRec.dirInfo.ioVRefNum = spec.vRefNum;
pbRec.dirInfo.ioNamePtr = spec.name;
if (PBGetCatInfoSync (&pbRec) == noErr)
{
spec.parID = pbRec.dirInfo.ioDrDirID;
// the cfstring -> pascalstring can fail if the filename length > 63 (FSSpec sucks)
if (CFStringGetPascalString (navReply.saveFileName, (unsigned char*)&spec.name, sizeof (spec.name), kCFStringEncodingASCII))
{
vstFileSelect->nbReturnPath = 1;
if (!vstFileSelect->returnPath)
{
vstFileSelect->reserved = 1;
vstFileSelect->returnPath = new char [sizeof (FSSpec)];
}
memcpy (vstFileSelect->returnPath, &spec, sizeof (FSSpec));
}
}
}
NavDisposeReply (&navReply);
}
if (defSaveName)
CFRelease (defSaveName);
NavDialogDispose (dialogRef);
DisposeNavEventUPP (eventUPP);
return vstFileSelect->nbReturnPath;
}
if (defSaveName)
CFRelease (defSaveName);
}
else if (vstFileSelect->command == kVstDirectorySelect)
{
NavDialogCreationOptions dialogOptions;
NavGetDefaultDialogCreationOptions (&dialogOptions);
dialogOptions.windowTitle = CFSTR ("Select Directory");
NavDialogRef dialogRef;
if (NavCreateChooseFolderDialog (&dialogOptions, eventUPP, NULL, effect, &dialogRef) == noErr)
{
AEDesc defaultLocation;
AEDesc* defLocPtr = 0;
if (vstFileSelect->initialPath)
{
FSSpec* defaultSpec = (FSSpec*)vstFileSelect->initialPath;
if (defaultSpec->parID && defaultSpec->vRefNum)
if (AECreateDesc (typeFSS, defaultSpec, sizeof(FSSpec), &defaultLocation) == noErr)
defLocPtr = &defaultLocation;
}
if (defLocPtr)
NavCustomControl (dialogRef, kNavCtlSetLocation, (void*)defLocPtr);
NavDialogRun (dialogRef);
if (defLocPtr)
AEDisposeDesc (defLocPtr);
NavReplyRecord navReply;
if (NavDialogGetReply (dialogRef, &navReply) == noErr)
{
FSRef parentFSRef;
AEKeyword theAEKeyword;
DescType typeCode;
Size actualSize;
// get the FSRef referring to the parent directory
if (AEGetNthPtr(&navReply.selection, 1, typeFSRef,
&theAEKeyword, &typeCode, &parentFSRef, sizeof(FSRef), &actualSize) == noErr)
{
FSSpec spec;
FSCatalogInfoBitmap infoBitmap = kFSCatInfoNone;
FSGetCatalogInfo (&parentFSRef, infoBitmap, NULL, NULL, &spec, NULL);
vstFileSelect->nbReturnPath = 1;
if (!vstFileSelect->returnPath)
{
vstFileSelect->reserved = 1;
vstFileSelect->returnPath = new char [sizeof (FSSpec)];
}
memcpy (vstFileSelect->returnPath, &spec, sizeof (FSSpec));
}
NavDisposeReply (&navReply);
}
NavDialogDispose (dialogRef);
DisposeNavEventUPP (eventUPP);
return vstFileSelect->nbReturnPath;
}
}
else // FileLoad
{
NavDialogCreationOptions dialogOptions;
NavGetDefaultDialogCreationOptions (&dialogOptions);
if (vstFileSelect->command == kVstFileLoad)
{
dialogOptions.windowTitle = CFSTR ("Select a File to Open");
dialogOptions.optionFlags &= ~kNavAllowMultipleFiles;
}
else
{
dialogOptions.windowTitle = CFSTR ("Select Files to Open");
dialogOptions.optionFlags |= kNavAllowMultipleFiles;
}
NavDialogRef dialogRef;
if (NavCreateGetFileDialog (&dialogOptions, NULL, eventUPP, NULL, NULL, effect, &dialogRef) == noErr)
{
AEDesc defaultLocation;
AEDesc* defLocPtr = 0;
if (vstFileSelect->initialPath)
{
FSSpec* defaultSpec = (FSSpec*)vstFileSelect->initialPath;
if (defaultSpec->parID && defaultSpec->vRefNum)
if (AECreateDesc (typeFSS, defaultSpec, sizeof(FSSpec), &defaultLocation) == noErr)
defLocPtr = &defaultLocation;
}
if (defLocPtr)
NavCustomControl (dialogRef, kNavCtlSetLocation, (void*)defLocPtr);
NavDialogRun (dialogRef);
if (defLocPtr)
AEDisposeDesc (defLocPtr);
NavReplyRecord navReply;
if (NavDialogGetReply (dialogRef, &navReply) == noErr)
{
FSRef parentFSRef;
AEKeyword theAEKeyword;
DescType typeCode;
Size actualSize;
if (vstFileSelect->command == kVstFileLoad)
{
if (AEGetNthPtr(&navReply.selection, 1, typeFSRef,
&theAEKeyword, &typeCode, &parentFSRef, sizeof(FSRef), &actualSize) == noErr)
{
FSSpec spec;
FSCatalogInfoBitmap infoBitmap = kFSCatInfoNone;
FSGetCatalogInfo (&parentFSRef, infoBitmap, NULL, NULL, &spec, NULL);
vstFileSelect->nbReturnPath = 1;
if (!vstFileSelect->returnPath)
{
vstFileSelect->reserved = 1;
vstFileSelect->returnPath = new char [sizeof (FSSpec)];
}
memcpy (vstFileSelect->returnPath, &spec, sizeof (FSSpec));
}
}
else
{
AECountItems (&navReply.selection, &vstFileSelect->nbReturnPath);
vstFileSelect->returnMultiplePaths = new char* [vstFileSelect->nbReturnPath];
int index = 1;
while (AEGetNthPtr(&navReply.selection, index++, typeFSRef,
&theAEKeyword, &typeCode, &parentFSRef, sizeof(FSRef), &actualSize) == noErr)
{
FSSpec spec;
FSCatalogInfoBitmap infoBitmap = kFSCatInfoNone;
FSGetCatalogInfo (&parentFSRef, infoBitmap, NULL, NULL, &spec, NULL);
vstFileSelect->returnMultiplePaths[index-2] = new char[sizeof (FSSpec)];
memcpy (vstFileSelect->returnMultiplePaths[index-2], &spec, sizeof (FSSpec));
}
}
}
DisposeNavEventUPP (eventUPP);
NavDialogDispose (dialogRef);
return vstFileSelect->nbReturnPath;
}
}
DisposeNavEventUPP (eventUPP);
#else
StandardFileReply reply;
if (vstFileSelect->command == kVstFileSave)
{
unsigned char defName[64];
defName[0] = 0;
StandardPutFile ("\pSelect a Destination", defName, &reply);
if (reply.sfGood && reply.sfFile.name[0] != 0)
{
if (!vstFileSelect->returnPath)
{
vstFileSelect->reserved = 1;
vstFileSelect->returnPath = new char [301];
}
memcpy (vstFileSelect->returnPath, &reply.sfFile, 300);
vstFileSelect->nbReturnPath = 1;
return 1;
}
}
else if (vstFileSelect->command == kVstDirectorySelect)
{
#if USENAVSERVICES
if (NavServicesAvailable ())
{
NavReplyRecord navReply;
NavDialogOptions dialogOptions;
short ret = false;
AEDesc defLoc;
defLoc.descriptorType = typeFSS;
defLoc.dataHandle = NewHandle (sizeof (FSSpec));
FSSpec finalFSSpec;
finalFSSpec.parID = 0; // *dirID;
finalFSSpec.vRefNum = 0; // *volume;
finalFSSpec.name[0] = 0;
NavGetDefaultDialogOptions (&dialogOptions);
dialogOptions.dialogOptionFlags &= ~kNavAllowMultipleFiles;
dialogOptions.dialogOptionFlags |= kNavSelectDefaultLocation;
strcpy ((char* )dialogOptions.message, "Select Directory");
c2pstr ((char* )dialogOptions.message);
NavChooseFolder (&defLoc, &navReply, &dialogOptions, 0 /* eventUPP */, 0, 0);
DisposeHandle (defLoc.dataHandle);
AEDesc resultDesc;
AEKeyword keyword;
resultDesc.dataHandle = 0L;
if (navReply.validRecord && AEGetNthDesc (&navReply.selection, 1, typeFSS, &keyword, &resultDesc) == noErr)
{
ret = true;
vstFileSelect->nbReturnPath = 1;
if (!vstFileSelect->returnPath)
{
vstFileSelect->reserved = 1;
vstFileSelect->returnPath = new char [sizeof (FSSpec)];
}
memcpy (vstFileSelect->returnPath, *resultDesc.dataHandle, sizeof (FSSpec));
}
NavDisposeReply (&navReply);
return vstFileSelect->nbReturnPath;
}
else
#endif
{
// Can't select a Folder; the Application does not support it, and Navigational Services are not available...
return 0;
}
}
else
{
SFTypeList typelist;
long numFileTypes = vstFileSelect->nbFileTypes;
//seem not to work... if (numFileTypes <= 0)
{
numFileTypes = -1; // all files
typelist[0] = 'AIFF';
}
/*else
{
if (numFileTypes > 4)
numFileTypes = 4;
for (long i = 0; i < numFileTypes; i++)
memcpy (&typelist[i], vstFileSelect->fileTypes[i].macType, 4);
}*/
StandardGetFile (0L, numFileTypes, typelist, &reply);
if (reply.sfGood)
{
if (!vstFileSelect->returnPath)
{
vstFileSelect->reserved = 1;
vstFileSelect->returnPath = new char [301];
}
memcpy (vstFileSelect->returnPath, &reply.sfFile, 300);
vstFileSelect->nbReturnPath = 1;
return 1;
}
}
#endif // CARBON
#else
//CAlert::alert ("The current Host application doesn't support FileSelector !", "Warning");
#endif
}
return 0;
}
END_NAMESPACE_VSTGUI
#if WINDOWS
#include <Commdlg.h>
//-----------------------------------------------------------------------------
UINT APIENTRY SelectDirectoryHook (HWND hdlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_NOTIFY:
{
OFNOTIFY *lpon = (OFNOTIFY *)lParam;
switch (lpon->hdr.code)
{
case CDN_FILEOK:
CommDlg_OpenSave_GetFolderPath (GetParent (hdlg), selDirPath, kPathMax);
didCancel = false;
break;
case CDN_INITDONE: {
#define HIDE_ITEMS 4
int i;
#define edt1 0x0480
#define stc3 0x0442
#define cmb1 0x0470
#define stc2 0x0441
#define stc4 0x0443
UINT hide_items[HIDE_ITEMS] = {edt1, stc3, cmb1, stc2};
for (i = 0; i < HIDE_ITEMS; i++)
CommDlg_OpenSave_HideControl (GetParent (hdlg), hide_items[i]);
CommDlg_OpenSave_SetControlText (GetParent (hdlg), stc4, (char*)(const char*)stringLookIn);
CommDlg_OpenSave_SetControlText (GetParent (hdlg), IDOK, (char*)(const char*)stringSelect);
CommDlg_OpenSave_SetControlText (GetParent (hdlg), IDCANCEL, (char*)(const char*)stringCancel);
} break;
}
} break;
case WM_INITDIALOG:
fpOldSelectDirectoryButtonProc = (FARPROC)SetWindowLong (
GetDlgItem (GetParent (hdlg), IDOK),
GWL_WNDPROC,
(long) SelectDirectoryButtonProc);
break;
case WM_DESTROY:
SetWindowLong (GetDlgItem (GetParent (hdlg), IDOK),
GWL_WNDPROC, (long) fpOldSelectDirectoryButtonProc);
}
return false;
}
//-----------------------------------------------------------------------------
LRESULT CALLBACK SelectDirectoryButtonProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_SETTEXT:
if (! (strcmp ((char *)lParam, stringSelect) == 0))
return false;
break;
case WM_LBUTTONUP:
case WM_RBUTTONUP: {
char mode[256];
GetWindowText (hwnd, mode, 256);
if (!strcmp (mode, stringSelect))
{
folderSelected = true;
char oldDirPath[kPathMax];
CommDlg_OpenSave_GetFolderPath (GetParent (hwnd), oldDirPath, kPathMax);
// you need a lot of tricks to get name of currently selected folder:
// the following call of the original windows procedure causes the
// selected folder to open and after that you can retrieve its name
// by calling ..._GetFolderPath (...)
CallWindowProc ((WNDPROC)fpOldSelectDirectoryButtonProc, hwnd, message, wParam, lParam);
CommDlg_OpenSave_GetFolderPath (GetParent (hwnd), selDirPath, kPathMax);
if (1) // consumers like it like this
{
if (strcmp (oldDirPath, selDirPath) == 0 || selDirPath [0] == 0)
{
// the same folder as the old one, means nothing selected: close
folderSelected = true;
didCancel = false;
PostMessage (GetParent (hwnd), WM_CLOSE, 0, 0);
return false;
}
else
{
// another folder is selected: browse into it
folderSelected = false;
return true;
}
}
else // original code
{
if (strcmp (oldDirPath, selDirPath) == 0 || selDirPath [0] == 0)
{
// the same folder as the old one, means nothing selected: stay open
folderSelected = false;
return true;
}
}
}
didCancel = false;
PostMessage (GetParent (hwnd), WM_CLOSE, 0, 0);
return false;
} break;
} // end switch
return CallWindowProc ((WNDPROC)fpOldSelectDirectoryButtonProc, hwnd, message, wParam, lParam);
}
//-----------------------------------------------------------------------------
static void showPathInWindowTitle (HWND hParent, LPOFNOTIFY lpon)
{
#define WINDOWTEXTSIZE 260 + 64
OPENFILENAME *ofn = lpon->lpOFN;
char text[WINDOWTEXTSIZE];
char *p;
int len;
// Put the path into the Window Title
if (lpon->lpOFN->lpstrTitle)
strcpy (text, lpon->lpOFN->lpstrTitle);
else
{
char *pp;
GetWindowText (hParent, text, WINDOWTEXTSIZE);
pp = strchr (text, '-');
if (pp)
*--pp = 0;
}
p = strcat (text, " - [");
p = text;
len = strlen (text);
p += len;
len = WINDOWTEXTSIZE - len - 2;
CommDlg_OpenSave_GetFolderPath (hParent, p, len);
strcat (text, "]");
SetWindowText (hParent, text);
}
//------------------------------------------------------------------------
UINT APIENTRY WinSaveHook (HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_NOTIFY: {
LPOFNOTIFY lpon = (LPOFNOTIFY)lParam;
if (!lpon)
break;
switch (lpon->hdr.code)
{
case CDN_FOLDERCHANGE:
showPathInWindowTitle (GetParent (hdlg), lpon);
break;
}
} break;
} // end switch
return 0;
}
#endif
//-----------------------------------------------------------------------------
#endif // !PLUGGUI
//-----------------------------------------------------------------------------
#if WINDOWS
#if USE_MOUSE_HOOK
HHOOK MouseHook = 0L;
LRESULT CALLBACK MouseProc (int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode < 0)
return CallNextHookEx (MouseHook, nCode, wParam, lParam);
if (wParam == 522)
{
MOUSEHOOKSTRUCT* struct2 = (MOUSEHOOKSTRUCT*) lParam;
if (struct2->hwnd == ???)
{
return -1;
}
}
return CallNextHookEx (MouseHook, nCode, wParam, lParam);
}
#endif
//-----------------------------------------------------------------------------
bool InitWindowClass ()
{
useCount++;
if (useCount == 1)
{
sprintf (className, "Plugin%08x", GetInstance ());
WNDCLASS windowClass;
windowClass.style = CS_GLOBALCLASS;//|CS_OWNDC; // add Private-DC constant
windowClass.lpfnWndProc = WindowProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = GetInstance ();
windowClass.hIcon = 0;
windowClass.hCursor = LoadCursor (NULL, IDC_ARROW);
windowClass.hbrBackground = GetSysColorBrush (COLOR_BTNFACE);
windowClass.lpszMenuName = 0;
windowClass.lpszClassName = className;
RegisterClass (&windowClass);
#if USE_MOUSE_HOOK
MouseHook = SetWindowsHookEx (WH_MOUSE, MouseProc,(GetInstance (), 0);
#endif
swapped_mouse_buttons = GetSystemMetrics (SM_SWAPBUTTON) > 0;
}
return true;
}
//-----------------------------------------------------------------------------
void ExitWindowClass ()
{
useCount--;
if (useCount == 0)
{
UnregisterClass (className, GetInstance ());
#if USE_MOUSE_HOOK
if (MouseHook)
{
UnhookWindowsHookEx (MouseHook);
MouseHook = 0L;
}
#endif
}
}
//-----------------------------------------------------------------------------
LONG WINAPI WindowProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
USING_NAMESPACE_VSTGUI
CFrame* pFrame = (CFrame*)GetWindowLong (hwnd, GWL_USERDATA);
switch (message)
{
case WM_CTLCOLOREDIT:
{
if (pFrame)
{
VSTGUI_CTextEdit *textEdit = (VSTGUI_CTextEdit*)pFrame->getEditView ();
if (textEdit)
{
VSTGUI_CColor fontColor = textEdit->getFontColor ();
SetTextColor ((HDC) wParam, RGB (fontColor.red, fontColor.green, fontColor.blue));
VSTGUI_CColor backColor = textEdit->getBackColor ();
SetBkColor ((HDC) wParam, RGB (backColor.red, backColor.green, backColor.blue));
if (textEdit->platformFontColor)
DeleteObject (textEdit->platformFontColor);
textEdit->platformFontColor = CreateSolidBrush (RGB (backColor.red, backColor.green, backColor.blue));
return (LRESULT)(textEdit->platformFontColor);
}
}
}
break;
case WM_PAINT:
{
RECT r;
if (pFrame && GetUpdateRect (hwnd, &r, false))
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint (hwnd, &ps);
VSTGUI_CDrawContext *pContext = new VSTGUI_CDrawContext (pFrame, hdc, hwnd);
#if 1
VSTGUI::CRect updateRect (ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom);
pFrame->drawRect (pContext, updateRect);
#else
pFrame->draw (pContext);
#endif
delete pContext;
EndPaint (hwnd, &ps);
return 0;
}
}
break;
case WM_MEASUREITEM :
{
MEASUREITEMSTRUCT* ms = (MEASUREITEMSTRUCT*)lParam;
if (pFrame && ms && ms->CtlType == ODT_MENU && ms->itemData)
{
VSTGUI_COptionMenu* optMenu = (VSTGUI_COptionMenu*)pFrame->getEditView ();
if (optMenu && optMenu->getScheme ())
{
VSTGUI_CPoint size;
HDC hdc = GetDC (hwnd);
VSTGUI_CDrawContext* pContext = new VSTGUI_CDrawContext (pFrame, hdc, hwnd);
optMenu->getScheme ()->getItemSize ((const char*)ms->itemData, pContext, size);
delete pContext;
ReleaseDC (hwnd, hdc);
ms->itemWidth = size.h;
ms->itemHeight = size.v;
return TRUE;
}
}
}
break;
case WM_DRAWITEM :
{
DRAWITEMSTRUCT* ds = (DRAWITEMSTRUCT*)lParam;
if (pFrame && ds && ds->CtlType == ODT_MENU && ds->itemData)
{
VSTGUI_COptionMenu* optMenu = (VSTGUI_COptionMenu*)pFrame->getEditView ();
if (optMenu && optMenu->getScheme ())
{
long state = 0;
if (ds->itemState & ODS_CHECKED)
state |= VSTGUI_COptionMenuScheme::kChecked;
if (ds->itemState & ODS_DISABLED) // ODS_GRAYED?
state |= VSTGUI_COptionMenuScheme::kDisabled;
if (ds->itemState & ODS_SELECTED)
state |= VSTGUI_COptionMenuScheme::kSelected;
VSTGUI::CRect r (ds->rcItem.left, ds->rcItem.top, ds->rcItem.right, ds->rcItem.bottom);
r.bottom++;
VSTGUI_CDrawContext* pContext = new VSTGUI_CDrawContext (pFrame, ds->hDC, 0);
optMenu->getScheme ()->drawItem ((const char*)ds->itemData, ds->itemID, state, pContext, r);
delete pContext;
return TRUE;
}
}
}
break;
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_LBUTTONDOWN:
if (pFrame)
{
#if 1
HDC hdc = GetDC (hwnd);
VSTGUI_CDrawContext *pContext = new VSTGUI_CDrawContext (pFrame, hdc, hwnd);
VSTGUI_CPoint where (LOWORD (lParam), HIWORD (lParam));
pFrame->mouse (pContext, where);
delete pContext;
ReleaseDC (hwnd, hdc);
#else
VSTGUI_CPoint where (LOWORD (lParam), HIWORD (lParam));
pFrame->mouse ((VSTGUI_CDrawContext*)0, where);
#endif
return 0;
}
break;
case WM_DESTROY:
if (pFrame)
{
pFrame->setOpenFlag (false);
pFrame->setParentSystemWindow (0);
}
break;
}
return DefWindowProc (hwnd, message, wParam, lParam);
}
//-----------------------------------------------------------------------------
HANDLE CreateMaskBitmap (CDrawContext* pContext, VSTGUI::CRect& rect, CColor transparentColor)
{
HBITMAP pMask = CreateBitmap (rect.width (), rect.height (), 1, 1, 0);
HDC hSrcDC = (HDC)pContext->getSystemContext ();
HDC hDstDC = CreateCompatibleDC (hSrcDC);
SelectObject (hDstDC, pMask);
COLORREF oldBkColor = SetBkColor (hSrcDC, RGB (transparentColor.red, transparentColor.green, transparentColor.blue));
BitBlt (hDstDC, 0, 0, rect.width (), rect.height (), hSrcDC, rect.left, rect.top, SRCCOPY);
SetBkColor (hSrcDC, oldBkColor);
DeleteDC (hDstDC);
return pMask;
}
//-----------------------------------------------------------------------------
void DrawTransparent (CDrawContext* pContext, VSTGUI::CRect& rect, const VSTGUI::CPoint& offset,
HDC hdcBitmap, POINT ptSize, HBITMAP pMask, COLORREF color)
{
if (pMask == NULL)
{
if (pfnTransparentBlt)
{
HDC hdcSystemContext = (HDC)pContext->getSystemContext ();
long x, y;
long width = rect.width ();
long height = rect.height ();
x = rect.x + pContext->offset.x;
y = rect.y + pContext->offset.y;
pfnTransparentBlt (hdcSystemContext, x, y, width, height, hdcBitmap, offset.x, offset.y, width, height, color);
}
else
{
// OPTIMIZATION: we only do four instead of EIGHT blits
HDC hdcSystemContext = (HDC)pContext->getSystemContext ();
HDC hdcMask = CreateCompatibleDC (hdcSystemContext);
COLORREF crOldBack = SetBkColor (hdcSystemContext, 0xFFFFFF);
COLORREF crOldText = SetTextColor (hdcSystemContext, 0x000000);
HBITMAP bmMaskOld, maskMap;
long x, y;
long width = rect.width ();
long height = rect.height ();
x = rect.x + pContext->offset.x;
y = rect.y + pContext->offset.y;
// Create mask-bitmap in memory
maskMap = CreateBitmap (width, height, 1, 1, NULL);
bmMaskOld = (HBITMAP)SelectObject (hdcMask, maskMap);
// Copy bitmap into mask-bitmap and converting it into a black'n'white mask
SetBkColor (hdcBitmap, color);
BitBlt (hdcMask, 0, 0, width, height, hdcBitmap, offset.x, offset.y, SRCCOPY);
// Copy image masked to screen
BitBlt (hdcSystemContext, x, y, width, height, hdcBitmap, offset.x, offset.y, SRCINVERT);
BitBlt (hdcSystemContext, x, y, width, height, hdcMask, 0, 0, SRCAND);
BitBlt (hdcSystemContext, x, y, width, height, hdcBitmap, offset.x, offset.y, SRCINVERT);
DeleteObject (SelectObject (hdcMask, bmMaskOld));
DeleteDC (hdcMask);
SetBkColor (hdcSystemContext, crOldBack);
SetTextColor (hdcSystemContext, crOldText);
}
}
else
{
// OPTIMIZATION: we only do five instead of EIGHT blits
HDC hdcSystemContext = (HDC)pContext->getSystemContext();
HDC hdcMask = CreateCompatibleDC (hdcSystemContext);
HDC hdcMem = CreateCompatibleDC (hdcSystemContext);
HBITMAP bmAndMem;
HBITMAP bmMemOld, bmMaskOld;
long x, y;
long width = rect.width();
long height = rect.height();
x = rect.x + pContext->offset.x;
y = rect.y + pContext->offset.y;
bmAndMem = CreateCompatibleBitmap(hdcSystemContext, width, height);
bmMaskOld = (HBITMAP)SelectObject(hdcMask, pMask);
bmMemOld = (HBITMAP)SelectObject (hdcMem, bmAndMem);
BitBlt(hdcMem, 0, 0, width, height, hdcSystemContext, x, y, SRCCOPY);
BitBlt(hdcMem, 0, 0, width, height, hdcBitmap, offset.x, offset.y, SRCINVERT);
BitBlt(hdcMem, 0, 0, width, height, hdcMask, offset.x, offset.y, SRCAND);
BitBlt(hdcMem, 0, 0, width, height, hdcBitmap, offset.x, offset.y, SRCINVERT);
BitBlt(hdcSystemContext, x, y, width, height, hdcMem, 0, 0, SRCCOPY);
DeleteObject(SelectObject(hdcMem, bmMemOld));
SelectObject(hdcMask, bmMaskOld);
DeleteDC(hdcMem);
DeleteDC(hdcMask);
}
}
#endif
//-----------------------------------------------------------------------------
#if MAC || MOTIF || BEOS
// return a degre value between [0, 360 * 64[
long convertPoint2Angle (VSTGUI::CPoint &pm, VSTGUI::CPoint &pt)
{
long angle;
if (pt.h == pm.h)
{
if (pt.v < pm.v)
angle = 5760; // 90 * 64
else
angle = 17280; // 270 * 64
}
else if (pt.v == pm.v)
{
if (pt.h < pm.h)
angle = 11520; // 180 * 64
else
angle = 0;
}
else
{
// 3666.9299 = 180 * 64 / pi
angle = (long)(3666.9298 * atan ((double)(pm.v - pt.v) / (double)(pt.h - pm.h)));
if (pt.v < pm.v)
{
if (pt.h < pm.h)
angle += 11520; // 180 * 64
}
else
{
if (pt.h < pm.h)
angle += 11520; // 180 * 64
else
angle += 23040; // 360 * 64
}
}
return angle;
}
#endif
//-----------------------------------------------------------------------------
#if MOTIF
XRectangle rect;
static bool first = true;
//-----------------------------------------------------------------------------
void _destroyCallback (Widget widget, XtPointer clientData, XtPointer callData)
{
CFrame* pFrame = (CFrame*)clientData;
if (pFrame)
{
pFrame->freeGc ();
pFrame->setOpenFlag (false);
pFrame->pSystemWindow = 0;
}
}
//-----------------------------------------------------------------------------
void _drawingAreaCallback (Widget widget, XtPointer clientData, XtPointer callData)
{
CFrame* pFrame = (CFrame*)clientData;
XmDrawingAreaCallbackStruct *cbs = (XmDrawingAreaCallbackStruct *)callData;
XEvent *event = cbs->event;
//-------------------------------------
if (cbs->reason == XmCR_INPUT)
{
if (event->xbutton.type == ButtonRelease)
return;
if (event->xbutton.type != ButtonPress &&
event->xbutton.type != KeyPress)
return;
Window pWindow = pFrame->getWindow ();
CDrawContext context (pFrame, pFrame->getGC (), (void*)pWindow);
VSTGUI::CPoint where (event->xbutton.x, event->xbutton.y);
pFrame->mouse (&context, where);
}
//------------------------------------
else if (cbs->reason == XmCR_EXPOSE)
{
XExposeEvent *expose = (XExposeEvent*)event;
#if TEST_REGION
rect.x = expose->x;
rect.y = expose->y;
rect.width = expose->width;
rect.height = expose->height;
if (first)
{
pFrame->region = XCreateRegion ();
first = false;
}
XUnionRectWithRegion (&rect, pFrame->region, pFrame->region);
#endif
if (expose->count == 0)
{
#if TEST_REGION
XSetRegion (expose->pDisplay, pFrame->getGC (), pFrame->region);
// add processus of static first to set the region to max after a total draw and destroy it the first time...
#endif
pFrame->draw ();
#if TEST_REGION
rect.x = 0;
rect.y = 0;
rect.width = pFrame->getWidth ();
rect.height = pFrame->getHeight ();
XUnionRectWithRegion (&rect, pFrame->region, pFrame->region);
XSetRegion (expose->pDisplay, pFrame->getGC (), pFrame->region);
XDestroyRegion (pFrame->region);
first = true;
#endif
}
}
}
//-----------------------------------------------------------------------------
void _eventHandler (Widget w, XtPointer clientData, XEvent *event, char *p)
{
switch (event->type)
{
case EnterNotify:
break;
case LeaveNotify:
XCrossingEvent *xevent = (XCrossingEvent*)event;
CFrame* pFrame = (CFrame*)clientData;
if (pFrame && pFrame->getEditView ())
{
if (xevent->x < 0 || xevent->x >= pFrame->getWidth () ||
xevent->y < 0 || xevent->y >= pFrame->getHeight ())
{
// if button pressed => don't defocus
if (xevent->state & (Button1Mask|Button2Mask|Button3Mask))
break;
pFrame->getEditView ()->looseFocus ();
pFrame->setEditView (0);
}
}
break;
}
}
//-----------------------------------------------------------------------------
long getIndexColor8Bit (CColor color, Display *pDisplay, Colormap colormap)
{
long i;
// search in pre-loaded color
for (i = 0; i < CDrawContext::nbNewColor; i++)
{
if ((paletteNewColor[i].red == color.red) &&
(paletteNewColor[i].green == color.green) &&
(paletteNewColor[i].blue == color.blue))
return paletteNewColor[i].unused;
}
// Allocate new color cell
XColor xcolor;
int red = color.red << 8;
int green = color.green << 8;
int blue = color.blue << 8;
xcolor.red = red;
xcolor.green = green;
xcolor.blue = blue;
if (XAllocColor (pDisplay, colormap, &xcolor))
{
// store this new color
if (CDrawContext::nbNewColor < 255)
{
paletteNewColor[CDrawContext::nbNewColor].red = color.red;
paletteNewColor[CDrawContext::nbNewColor].green = color.green;
paletteNewColor[CDrawContext::nbNewColor].blue = color.blue;
paletteNewColor[CDrawContext::nbNewColor].unused = xcolor.pixel;
CDrawContext::nbNewColor++;
}
return xcolor.pixel;
}
// take the nearest color
int diff;
int min = 3 * 65536;
int index = 0;
XColor xcolors[256];
for (i = 0; i < 256; i++)
xcolors[i].pixel = i;
XQueryColors (pDisplay, colormap, xcolors, 256);
for (i = 0; i < 256; i++)
{
diff = fabs (xcolors[i].red - red) + fabs (xcolors[i].green - green) + fabs (xcolors[i].blue - blue);
if (diff < min)
{
min = diff;
index = i;
}
}
// store this new color
if (CDrawContext::nbNewColor < 255)
{
paletteNewColor[CDrawContext::nbNewColor].red = color.red;
paletteNewColor[CDrawContext::nbNewColor].green = color.green;
paletteNewColor[CDrawContext::nbNewColor].blue = color.blue;
paletteNewColor[CDrawContext::nbNewColor].unused = index;
CDrawContext::nbNewColor++;
}
return (index);
}
//-----------------------------------------------------------------------------
bool xpmGetValues (char **ppDataXpm, long *pWidth, long *pHeight, long *pNcolor, long *pCpp)
{
// get the size of the pixmap
sscanf (ppDataXpm[0], "%d %d %d %d", pWidth, pHeight, pNcolor, pCpp);
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#elif BEOS
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
PlugView::PlugView (BRect frame, CFrame* cframe)
: BView (frame, NULL, B_FOLLOW_ALL, B_WILL_DRAW), cframe (cframe)
{
SetViewColor (B_TRANSPARENT_COLOR);
}
//-----------------------------------------------------------------------------
void PlugView::Draw (BRect updateRect)
{
cframe->draw ();
}
//-----------------------------------------------------------------------------
void PlugView::MouseDown (BPoint where)
{
BMessage* m = Window ()->CurrentMessage ();
int32 buttons;
m->FindInt32 ("buttons", &buttons);
if (buttons & B_SECONDARY_MOUSE_BUTTON && !Window ()->IsFront () && !Window ()->IsFloating ())
{
Window ()->Activate (true);
return;
}
CDrawContext context (cframe, this, NULL);
VSTGUI::CPoint here (where.x, where.y);
cframe->mouse (&context, here);
}
//-----------------------------------------------------------------------------
void PlugView::MessageReceived (BMessage *msg)
{
if (msg->what == B_SIMPLE_DATA)
{
int32 countMax = 0; // max number of references. Possibly not all valid...
type_code typeFound;
msg->GetInfo ("refs", &typeFound, &countMax);
if (countMax > 0)
{
entry_ref item;
int nbRealItems = 0;
char ** ptrItems = new char* [countMax];
for (int k = 0; k < countMax; k++)
if (msg->FindRef ("refs", k, &item) == B_OK)
{
BPath path (&item);
if (path.InitCheck () == B_OK)
ptrItems[nbRealItems++] = strdup (path.Path ());
}
BPoint bwhere = msg->DropPoint ();
ConvertFromScreen (&bwhere);
VSTGUI::CPoint where (bwhere.x, bwhere.y);
cframe->onDrop ((void**)ptrItems, nbRealItems, kDropFiles, where);
for (long i = 0; i < nbRealItems; i++)
free (ptrItems[i]);
delete []ptrItems;
}
}
else BView::MessageReceived (msg);
}
#endif
//-----------------------------------------------------------------------------
#if WINDOWS
//-----------------------------------------------------------------------------
// Drop Implementation
//-----------------------------------------------------------------------------
class UDropTarget : public IDropTarget
{
public:
UDropTarget (VSTGUI_CFrame* pFrame);
virtual ~UDropTarget ();
// IUnknown
STDMETHOD (QueryInterface) (REFIID riid, void** object);
STDMETHOD_ (ULONG, AddRef) (void);
STDMETHOD_ (ULONG, Release) (void);
// IDropTarget
STDMETHOD (DragEnter) (IDataObject *dataObject, DWORD keyState, POINTL pt, DWORD *effect);
STDMETHOD (DragOver) (DWORD keyState, POINTL pt, DWORD *effect);
STDMETHOD (DragLeave) (void);
STDMETHOD (Drop) (IDataObject *dataObject, DWORD keyState, POINTL pt, DWORD *effect);
private:
long refCount;
bool accept;
VSTGUI_CFrame* pFrame;
};
//-----------------------------------------------------------------------------
// UDropTarget
//-----------------------------------------------------------------------------
void* createDropTarget (VSTGUI_CFrame* pFrame)
{
return new UDropTarget (pFrame);
}
//-----------------------------------------------------------------------------
UDropTarget::UDropTarget (VSTGUI_CFrame* pFrame)
: refCount (0), pFrame (pFrame)
{
}
//-----------------------------------------------------------------------------
UDropTarget::~UDropTarget ()
{
}
//-----------------------------------------------------------------------------
STDMETHODIMP UDropTarget::QueryInterface (REFIID riid, void** object)
{
if (riid == IID_IDropTarget || riid == IID_IUnknown)
{
*object = this;
AddRef ();
return NOERROR;
}
*object = 0;
return E_NOINTERFACE;
}
//-----------------------------------------------------------------------------
STDMETHODIMP_(ULONG) UDropTarget::AddRef (void)
{
return ++refCount;
}
//-----------------------------------------------------------------------------
STDMETHODIMP_(ULONG) UDropTarget::Release (void)
{
refCount--;
if (refCount <= 0)
delete this;
return refCount;
}
//-----------------------------------------------------------------------------
STDMETHODIMP UDropTarget::DragEnter (IDataObject *dataObject, DWORD keyState, POINTL pt, DWORD *effect)
{
accept = false;
if (dataObject)
{
FORMATETC formatTEXTDrop = {CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
if (S_OK == dataObject->QueryGetData (&formatTEXTDrop))
{
accept = true;
return DragOver (keyState, pt, effect);
}
FORMATETC formatHDrop = {CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
if (S_OK == dataObject->QueryGetData (&formatHDrop))
{
accept = true;
return DragOver (keyState, pt, effect);
}
}
*effect = DROPEFFECT_NONE;
return S_OK;
}
//-----------------------------------------------------------------------------
STDMETHODIMP UDropTarget::DragOver (DWORD keyState, POINTL pt, DWORD *effect)
{
if (accept)
{
if (keyState & MK_CONTROL)
*effect = DROPEFFECT_COPY;
else
*effect = DROPEFFECT_MOVE;
}
else
*effect = DROPEFFECT_NONE;
return S_OK;
}
//-----------------------------------------------------------------------------
STDMETHODIMP UDropTarget::DragLeave (void)
{
return S_OK;
}
//-----------------------------------------------------------------------------
STDMETHODIMP UDropTarget::Drop (IDataObject *dataObject, DWORD keyState, POINTL pt, DWORD *effect)
{
if (pFrame)
{
void* hDrop = 0;
STGMEDIUM medium;
FORMATETC formatTEXTDrop = {CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
FORMATETC formatHDrop = {CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
long type = 0; // 0 = file, 1 = text
HRESULT hr = dataObject->GetData (&formatTEXTDrop, &medium);
if (hr != S_OK)
hr = dataObject->GetData (&formatHDrop, &medium);
else
type = 1;
if (hr == S_OK)
hDrop = medium.hGlobal;
if (hDrop)
{
switch (type)
{
//---File----------------------
case 0:
{
long nbOfItems = (long)DragQueryFile ((HDROP)hDrop, 0xFFFFFFFFL, 0, 0);
char fileDropped[1024];
if (nbOfItems > 0)
{
char **ptrItems = new char* [nbOfItems];
long itemIndex = 0;
long nbRealItems = 0;
while (itemIndex < nbOfItems)
{
if (DragQueryFile ((HDROP)hDrop, itemIndex, fileDropped, sizeof (fileDropped)))
{
// resolve link
checkResolveLink (fileDropped, fileDropped);
ptrItems[nbRealItems] = new char [sizeof (fileDropped)];
strcpy ((char*)ptrItems[nbRealItems], fileDropped);
nbRealItems++;
}
itemIndex++;
}
VSTGUI_CPoint where;
pFrame->getCurrentLocation (where);
pFrame->onDrop ((void**)ptrItems, nbOfItems, VSTGUI_kDropFiles, where);
for (long i = 0; i < nbRealItems; i++)
delete []ptrItems[i];
delete []ptrItems;
}
} break;
//---TEXT----------------------------
case 1:
{
void* data = GlobalLock (medium.hGlobal);
long dataSize = GlobalSize (medium.hGlobal);
if (data && dataSize)
{
VSTGUI_CPoint where;
pFrame->getCurrentLocation (where);
pFrame->onDrop ((void**)&data, dataSize, VSTGUI_kDropText, where);
}
GlobalUnlock (medium.hGlobal);
if (medium.pUnkForRelease)
medium.pUnkForRelease->Release ();
else
GlobalFree (medium.hGlobal);
} break;
}
}
}
DragLeave ();
return S_OK;
}
//-----------------------------------------------------------------------------
bool checkResolveLink (const char* nativePath, char* resolved)
{
char* ext = strrchr (nativePath, '.');
if (ext && stricmp (ext, ".lnk") == NULL)
{
IShellLink* psl;
IPersistFile* ppf;
WIN32_FIND_DATA wfd;
HRESULT hres;
WORD wsz[2048];
// Get a pointer to the IShellLink interface.
hres = CoCreateInstance (CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
IID_IShellLink, (void**)&psl);
if (SUCCEEDED (hres))
{
// Get a pointer to the IPersistFile interface.
hres = psl->QueryInterface (IID_IPersistFile, (void**)&ppf);
if (SUCCEEDED (hres))
{
// Ensure string is Unicode.
MultiByteToWideChar (CP_ACP, 0, nativePath, -1, wsz, 2048);
// Load the shell link.
hres = ppf->Load (wsz, STGM_READ);
if (SUCCEEDED (hres))
{
hres = psl->Resolve (0, MAKELONG (SLR_ANY_MATCH | SLR_NO_UI, 500));
if (SUCCEEDED (hres))
{
// Get the path to the link target.
hres = psl->GetPath (resolved, 2048, &wfd, SLGP_SHORTPATH);
}
}
// Release pointer to IPersistFile interface.
ppf->Release ();
}
// Release pointer to IShellLink interface.
psl->Release ();
}
return SUCCEEDED(hres);
}
return false;
}
#elif MAC
//-----------------------------------------------------------------------------
// Drop Implementation
//-----------------------------------------------------------------------------
#if !MACX
#include "Drag.h"
#endif
pascal short drag_receiver (WindowPtr w, void* ref, DragReference drag);
static DragReceiveHandlerUPP drh;
//-------------------------------------------------------------------------------------------
void install_drop (CFrame *frame)
{
drh = NewDragReceiveHandlerUPP (drag_receiver);
#if CARBON
InstallReceiveHandler (drh, (WindowRef)(frame->getSystemWindow ()), (void*)frame);
#else
InstallReceiveHandler (drh, (GrafPort*)(frame->getSystemWindow ()), (void*)frame);
#endif
}
//-------------------------------------------------------------------------------------------
void remove_drop (CFrame *frame)
{
#if CARBON
RemoveReceiveHandler (drh, (WindowRef)(frame->getSystemWindow ()));
#else
RemoveReceiveHandler (drh, (GrafPort*)(frame->getSystemWindow ()));
#endif
}
//-------------------------------------------------------------------------------------------
// Drop has happened in one of our's windows.
// The data is either of our own type (flavour type stCA), or comes from
// another app. The only data from outside that is currently accepted are
// HFS-files
//-------------------------------------------------------------------------------------------
pascal short drag_receiver (WindowPtr w, void* ref, DragReference drag)
{
unsigned short i, items;
ItemReference item;
long size;
HFSFlavor hfs;
void* pack;
// get num of items
CountDragItems (drag, &items);
if (items <= 0)
return cantGetFlavorErr;
char **ptrItems = new char* [items];
long nbFileItems = 0;
CFrame *pFrame = (CFrame*)ref;
char* string = 0;
// for each items
for (i = 1; i <= items; i++)
{
pack = NULL;
GetDragItemReferenceNumber (drag, i, &item);
//---try file--------------------------
if (GetFlavorDataSize (drag, item, flavorTypeHFS, &size) == noErr)
{
GetFlavorData (drag, item, flavorTypeHFS, &hfs, &size, 0L);
ptrItems[nbFileItems] = new char [sizeof (FSSpec)];
memcpy (ptrItems[nbFileItems], &hfs.fileSpec, sizeof (FSSpec));
nbFileItems++;
}
//---try Text-------------------------
else if (GetFlavorDataSize (drag, item, 'TEXT', &size) == noErr)
{
string = new char [size + 2];
if (string)
{
GetFlavorData (drag, item, 'TEXT', string, &size, 0);
string[size] = 0;
}
break;
}
//---try XML text----------------------
else if (GetFlavorDataSize (drag, item, 'XML ', &size) == noErr)
{
string = new char [size + 2];
if (string)
{
GetFlavorData (drag, item, 'XML ', string, &size, 0);
string[size] = 0;
}
break;
}
} // end for eac items
// call the frame
if (nbFileItems)
{
VSTGUI_CPoint where;
pFrame->getCurrentLocation (where);
pFrame->onDrop ((void**)ptrItems, nbFileItems, VSTGUI_kDropFiles, where);
for (long i = 0; i < nbFileItems; i++)
delete []ptrItems[i];
delete []ptrItems;
return noErr;
}
if (string)
{
VSTGUI_CPoint where;
pFrame->getCurrentLocation (where);
pFrame->onDrop ((void**)&string, size, VSTGUI_kDropText, where);
delete []string;
}
delete []ptrItems;
return cantGetFlavorErr;
}
#endif
| [
"CTAF@3e78e570-a0aa-6544-9a6b-7e87a0c009bc",
"Quentin1@3e78e570-a0aa-6544-9a6b-7e87a0c009bc"
] | [
[
[
1,
2432
],
[
2434,
2434
],
[
2436,
7495
]
],
[
[
2433,
2433
],
[
2435,
2435
]
]
] |
7d28d2cdb219fe5cb32be82c760d1ae7903c160f | 3b2a1bf7afa990e2fe474839046f0259fa4fa071 | /cmt/example_linux.cpp | 07b7562ec35a502863cd4c5800ee373cf85718f8 | [] | no_license | uqs/avalon | 7d2d89c49c8bf18373378af9c100e392f40e8a8e | d4026fa9462b7fa7667c8e255eca944f1e73b564 | refs/heads/master | 2020-04-15T08:57:44.652541 | 2011-02-22T15:36:56 | 2011-02-22T15:36:56 | 1,398,085 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,265 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <signal.h>
#include <curses.h>
#include "cmtdef.h"
#include "xsens_time.h"
#include "xsens_list.h"
#include "cmtscan.h"
#include "cmt3.h"
#include "example_linux.h"
// this macro tests for an error and exits the program with a message if there was one
#define EXIT_ON_ERROR(res,comment) if (res != XRV_OK) { printw("Error %d occurred in " comment ": %s\n",res,xsensResultText(res)); exit(1); }
using namespace xsens;
inline int isnum(int c)
{
return (c >= '0' && c <= '9');
}
int main(int argc, char* argv[])
{
(void) argc; (void) argv; // Make the compiler stop complaining about unused parameters
xsens::Cmt3 cmt3;
int userQuit = 0;
unsigned long mtCount = 0;
int temperatureOffset = 0;
int screenSensorOffset = 0;
CmtDeviceId deviceIds[256];
CmtOutputMode mode;
CmtOutputSettings settings;
XsensResultValue res = XRV_OK;
short screenSkipFactor = 10;
short screenSkipFactorCnt = screenSkipFactor;
initscr();
noecho();
nodelay(stdscr, 1);
keypad(stdscr, 1);
raw();
// Perform hardware scan
mtCount = doHardwareScan(cmt3, deviceIds);
if (mtCount == 0) {
printw("press q to quit\n");
while(getch() != 'q');
echo();
endwin();
cmt3.closePort();
return 0;
}
getUserInputs(mode, settings);
// Set device to user input settings
doMtSettings(cmt3, mode, settings, deviceIds);
refresh();
screenSensorOffset = calcScreenOffset(mode, settings, screenSensorOffset);
writeHeaders(mtCount, mode, settings, temperatureOffset, screenSensorOffset);
// vars for sample counter & temp.
unsigned short sdata;
double tdata;
//structs to hold data.
CmtCalData caldata;
CmtQuat qat_data;
CmtEuler euler_data;
CmtMatrix matrix_data;
// Initialize packet for data
Packet* packet = new Packet((unsigned short) mtCount, cmt3.isXm());
int y, x;
getyx(stdscr, y, x);
x = 0;
move(y, x);
while (!userQuit && res == XRV_OK) {
cmt3.waitForDataMessage(packet);
//get sample count, goto position & display.
sdata = packet->getSampleCounter();
mvprintw(y, x, "Sample Counter %05hu\n", sdata);
if (screenSkipFactorCnt++ != screenSkipFactor) {
//continue;
}
screenSkipFactorCnt = 0;
for (unsigned int i = 0; i < mtCount; i++) {
// Output Temperature
if ((mode & CMT_OUTPUTMODE_TEMP) != 0) {
tdata = packet->getTemp(i);
mvprintw(y + 4 + i * screenSensorOffset, x, "%6.2f", tdata);
}
move(y + 5 + temperatureOffset + i * screenSensorOffset, x);
if ((mode & CMT_OUTPUTMODE_CALIB) != 0) {
caldata = packet->getCalData(i);
mvprintw(y + 5 + temperatureOffset + i * screenSensorOffset, x,
"%6.2f\t%6.2f\t%6.2f", caldata.m_acc.m_data[0],
caldata.m_acc.m_data[1], caldata.m_acc.m_data[2]);
mvprintw(y + 7 + temperatureOffset + i * screenSensorOffset, x,
"%6.2f\t%6.2f\t%6.2f", caldata.m_gyr.m_data[0],
caldata.m_gyr.m_data[1], caldata.m_gyr.m_data[2]);
mvprintw(y + 9 + temperatureOffset + i * screenSensorOffset, x,
"%6.2f\t%6.2f\t%6.2f",caldata.m_mag.m_data[0],
caldata.m_mag.m_data[1], caldata.m_mag.m_data[2]);
move(y + 13 + temperatureOffset + i * screenSensorOffset, x);
}
if ((mode & CMT_OUTPUTMODE_ORIENT) == 0) {
continue;
}
int yt, xt;
getyx(stdscr, yt, xt);
switch (settings & CMT_OUTPUTSETTINGS_ORIENTMODE_MASK) {
case CMT_OUTPUTSETTINGS_ORIENTMODE_QUATERNION:
// Output: quaternion
qat_data = packet->getOriQuat(i);
mvprintw(yt++, xt, "%6.3f\t%6.3f\t%6.3f\t%6.3f", qat_data.m_data[0],
qat_data.m_data[1], qat_data.m_data[2], qat_data.m_data[3]);
break;
case CMT_OUTPUTSETTINGS_ORIENTMODE_EULER:
// Output: Euler
euler_data = packet->getOriEuler(i);
mvprintw(yt++, xt, "%6.1f\t%6.1f\t%6.1f", euler_data.m_roll,
euler_data.m_pitch, euler_data.m_yaw);
break;
case CMT_OUTPUTSETTINGS_ORIENTMODE_MATRIX:
// Output: Cosine Matrix
matrix_data = packet->getOriMatrix(i);
mvprintw(yt++, xt, "%6.3f\t%6.3f\t%6.3f", matrix_data.m_data[0][0],
matrix_data.m_data[0][1], matrix_data.m_data[0][2]);
mvprintw(yt++, xt, "%6.3f\t%6.3f\t%6.3f\n", matrix_data.m_data[1][0],
matrix_data.m_data[1][1], matrix_data.m_data[1][2]);
mvprintw(yt++, xt, "%6.3f\t%6.3f\t%6.3f\n", matrix_data.m_data[2][0],
matrix_data.m_data[2][1], matrix_data.m_data[2][2]);
break;
default:
break;
}
if ((mode & CMT_OUTPUTMODE_POSITION) != 0) {
if (packet->containsPositionLLA()) {
/* output position */
printw("\n\n");
CmtVector positionLLA = packet->getPositionLLA();
if (res != XRV_OK) {
printw("error %ud", res);
}
for (int i = 0; i < 2; i++) {
double deg = positionLLA.m_data[i];
double min = (deg - (int)deg)*60;
double sec = (min - (int)min)*60;
printw("%3d\xb0%2d\'%2.2lf\"\t", (int)deg, (int)min, sec);
}
printw(" %3.2lf\n", positionLLA.m_data[2]);
} else {
printw("No position data available\n");
}
}
move(yt, xt);
refresh();
}
int chr = getch();
if (chr == 3 || chr == 'q') {
userQuit = 1;
// break;
}
}
echo();
endwin();
delete packet;
cmt3.closePort();
return 0;
}
//////////////////////////////////////////////////////////////////////////
// doHardwareScan
//
// Checks available COM ports and scans for MotionTrackers
int doHardwareScan(xsens::Cmt3 &cmt3, CmtDeviceId deviceIds[])
{
XsensResultValue res;
List<CmtPortInfo> portInfo;
unsigned long portCount = 0;
int mtCount;
printw("Scanning for connected Xsens devices...");
xsens::cmtScanPorts(portInfo);
portCount = portInfo.length();
printw("done\n");
if (portCount == 0) {
printw("No MotionTrackers found\n\n");
return 0;
}
for(int i = 0; i < (int)portCount; i++) {
printw("Using COM port %s at ", portInfo[i].m_portName);
switch (portInfo[i].m_baudrate) {
case B9600 : printw("9k6"); break;
case B19200 : printw("19k2"); break;
case B38400 : printw("38k4"); break;
case B57600 : printw("57k6"); break;
case B115200: printw("115k2"); break;
case B230400: printw("230k4"); break;
case B460800: printw("460k8"); break;
case B921600: printw("921k6"); break;
default: printw("0x%lx", portInfo[i].m_baudrate);
}
printw(" baud\n\n");
}
printw("Opening ports...");
//open the port which the device is connected to and connect at the device's baudrate.
for(int p = 0; p < (int)portCount; p++){
res = cmt3.openPort(portInfo[p].m_portName, portInfo[p].m_baudrate);
EXIT_ON_ERROR(res,"cmtOpenPort");
}
printw("done\n\n");
//get the Mt sensor count.
printw("Retrieving MotionTracker count (excluding attached Xbus Master(s))\n");
mtCount = cmt3.getMtCount();
printw("MotionTracker count: %d\n\n", mtCount);
// retrieve the device IDs
printw("Retrieving MotionTrackers device ID(s)\n");
for(int j = 0; j < mtCount; j++){
res = cmt3.getDeviceId((unsigned char)(j+1), deviceIds[j]);
EXIT_ON_ERROR(res,"getDeviceId");
printw("Device ID at busId %i: %08lx\n\n",j+1,(long) deviceIds[j]);
}
return mtCount;
}
//////////////////////////////////////////////////////////////////////////
// getUserInputs
//
// Request user for output data
void getUserInputs(CmtOutputMode &mode, CmtOutputSettings &settings)
{
mode = 0;
int y, x;
getyx(stdscr, y, x);
while (mode < 1 || mode > 6) {
printw("Select desired output:\n");
printw("1 - Calibrated data\n");
printw("2 - Orientation data and GPS Position (MTi-G only)\n");
printw("3 - Both Calibrated and Orientation data\n");
printw("4 - Temperature and Calibrated data\n");
printw("5 - Temperature and Orientation data\n");
printw("6 - Temperature, Calibrated and Orientation data\n");
printw("Enter your choice: ");
refresh();
fflush(stdin);
while(!isnum(mode = getch()));
printw("%c", mode);
mode -= 48;
refresh();
fflush(stdin);
move(y,x);
clrtobot();
move(y,x);
if (mode < 1 || mode > 6) {
printw("\n\nPlease enter a valid output mode\n");
}
}
switch(mode)
{
case 1:
mode = CMT_OUTPUTMODE_CALIB;
break;
case 2:
mode = CMT_OUTPUTMODE_ORIENT | CMT_OUTPUTMODE_POSITION;
break;
case 3:
mode = CMT_OUTPUTMODE_CALIB | CMT_OUTPUTMODE_ORIENT;
break;
case 4:
mode = CMT_OUTPUTMODE_TEMP | CMT_OUTPUTMODE_CALIB;
break;
case 5:
mode = CMT_OUTPUTMODE_TEMP | CMT_OUTPUTMODE_ORIENT;
break;
case 6:
mode = CMT_OUTPUTMODE_TEMP | CMT_OUTPUTMODE_CALIB | CMT_OUTPUTMODE_ORIENT;
break;
}
if ((mode & CMT_OUTPUTMODE_ORIENT) != 0) {
settings = 0;
while (settings < 1 || settings > 3) {
printw("\nSelect desired output format\n");
printw("1 - Quaternions\n");
printw("2 - Euler angles\n");
printw("3 - Matrix\n");
printw("Enter your choice: ");
fflush(stdin);
refresh();
while(!isnum(settings = getch()));
printw("%c", settings);
settings -= 48;
refresh();
move(y,x);
clrtobot();
move(y,x);
fflush(stdin);
if (settings < 1 || settings > 3) {
printw("\n\nPlease enter a valid output format\n");
}
}
// Update outputSettings to match data specs of SetOutputSettings
switch(settings) {
case 1:
settings = CMT_OUTPUTSETTINGS_ORIENTMODE_QUATERNION;
break;
case 2:
settings = CMT_OUTPUTSETTINGS_ORIENTMODE_EULER;
break;
case 3:
settings = CMT_OUTPUTSETTINGS_ORIENTMODE_MATRIX;
break;
}
} else {
settings = 0;
}
settings |= CMT_OUTPUTSETTINGS_TIMESTAMP_SAMPLECNT;
}
//////////////////////////////////////////////////////////////////////////
// doMTSettings
//
// Set user settings in MTi/MTx
// Assumes initialized global MTComm class
void doMtSettings(xsens::Cmt3 &cmt3, CmtOutputMode &mode,
CmtOutputSettings &settings, CmtDeviceId deviceIds[])
{
XsensResultValue res;
unsigned long mtCount = cmt3.getMtCount();
// set sensor to config sate
res = cmt3.gotoConfig();
EXIT_ON_ERROR(res,"gotoConfig");
unsigned short sampleFreq;
sampleFreq = cmt3.getSampleFrequency();
// set the device output mode for the device(s)
printw("Configuring your mode selection\n");
for (unsigned int i = 0; i < mtCount; i++) {
CmtDeviceMode deviceMode(mode, settings, sampleFreq);
if ((deviceIds[i] & 0xFFF00000) != 0x00500000) {
// not an MTi-G, remove all GPS related stuff
deviceMode.m_outputMode &= 0xFF0F;
}
res = cmt3.setDeviceMode(deviceMode, true, deviceIds[i]);
EXIT_ON_ERROR(res,"setDeviceMode");
}
// start receiving data
res = cmt3.gotoMeasurement();
EXIT_ON_ERROR(res,"gotoMeasurement");
}
//////////////////////////////////////////////////////////////////////////
// writeHeaders
//
// Write appropriate headers to screen
void writeHeaders(unsigned long mtCount, CmtOutputMode &mode,
CmtOutputSettings &settings, int &temperatureOffset,
int &screenSensorOffset)
{
int y, x;
getyx(stdscr, y, x);
for (unsigned int i = 0; i < mtCount; i++) {
mvprintw(y + 2 + i * screenSensorOffset, x, "MotionTracker %d\n", i + 1);
if ((mode & CMT_OUTPUTMODE_TEMP) != 0) {
temperatureOffset = 3;
mvprintw(y + 3 + i * screenSensorOffset, x, "Temperature");
mvprintw(y + 4 + i * screenSensorOffset, 7, "degrees celcius\n");
move(y + 6 + i * screenSensorOffset, x);
}
if ((mode & CMT_OUTPUTMODE_CALIB) != 0) {
mvprintw(y + 3 + temperatureOffset + i * screenSensorOffset, x,
"Calibrated sensor data");
mvprintw(y + 4 + temperatureOffset + i * screenSensorOffset, x,
" Acc X\t Acc Y\t Acc Z");
mvprintw(y + 5 + temperatureOffset + i * screenSensorOffset, x + 23,
"(m/s^2)");
mvprintw(y + 6 + temperatureOffset + i * screenSensorOffset, x,
" Gyr X\t Gyr Y\t Gyr Z");
mvprintw(y + 7 + temperatureOffset + i * screenSensorOffset, x + 23,
"(rad/s)");
mvprintw(y + 8 + temperatureOffset + i * screenSensorOffset, x,
" Mag X\t Mag Y\t Mag Z");
mvprintw(y + 9 + temperatureOffset + i * screenSensorOffset, x + 23,
"(a.u.)");
move(y + 11 + temperatureOffset + i * screenSensorOffset, x);
}
if ((mode & CMT_OUTPUTMODE_ORIENT) != 0) {
printw("Orientation data\n");
switch(settings & CMT_OUTPUTSETTINGS_ORIENTMODE_MASK) {
case CMT_OUTPUTSETTINGS_ORIENTMODE_QUATERNION:
printw(" q0\t q1\t q2\t q3\n");
break;
case CMT_OUTPUTSETTINGS_ORIENTMODE_EULER:
printw(" Roll\t Pitch\t Yaw\n");
printw(" degrees\n");
break;
case CMT_OUTPUTSETTINGS_ORIENTMODE_MATRIX:
printw(" Matrix\n");
break;
default:
;
}
}
if ((mode & CMT_OUTPUTMODE_POSITION) != 0) {
printw("\nLongitude\tLatitude\t Altitude\n");
}
}
move(y, x);
refresh();
}
//////////////////////////////////////////////////////////////////////////
// calcScreenOffset
//
// Calculates offset for screen data with multiple MTx on Xbus Master
int calcScreenOffset(CmtOutputMode &mode, CmtOutputSettings &settings,
int screenSensorOffset)
{
// 1 line for "Sensor ..."
screenSensorOffset += 1;
if ((mode & CMT_OUTPUTMODE_TEMP) != 0)
screenSensorOffset += 3;
if ((mode & CMT_OUTPUTMODE_CALIB) != 0)
screenSensorOffset += 8;
if ((mode & CMT_OUTPUTMODE_ORIENT) != 0) {
switch(settings & CMT_OUTPUTSETTINGS_ORIENTMODE_MASK) {
case CMT_OUTPUTSETTINGS_ORIENTMODE_QUATERNION:
screenSensorOffset += 4;
break;
case CMT_OUTPUTSETTINGS_ORIENTMODE_EULER:
screenSensorOffset += 4;
break;
case CMT_OUTPUTSETTINGS_ORIENTMODE_MATRIX:
screenSensorOffset += 6;
break;
default:
;
}
}
if ((mode & CMT_OUTPUTMODE_POSITION) != 0) {
screenSensorOffset += 4;
}
return screenSensorOffset;
}
| [
"asl@aslTough-laptop.(none)"
] | [
[
[
1,
482
]
]
] |
e590fdf70983a50925fcdcc4d16ff0a1862397fd | 6b83c731acb331c4f7ddd167ab5bb562b450d0f2 | /my_inc2/ctrl.cpp | 2b722aedee7e279d5b8e1a06b9a925944fc36e40 | [] | no_license | weimingtom/toheart2p | fbfb96f6ca8d3102b462ba53d3c9cff16ca509e7 | 560e99c42fdff23e65f16df6d14df9a9f1868d8e | refs/heads/master | 2021-01-10T01:36:31.515707 | 2007-12-20T15:13:51 | 2007-12-20T15:13:51 | 44,464,730 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,891 | cpp | #include <mm_std.h>
#include "ctrl.h"
int ListGetSelListEx(HWND hwnd, int idc, int **buf)
{
int size = ListGetSelCount(hwnd, idc);
if (size > 0)
{
*buf = (int*)GAlloc(size *sizeof(int));
ListGetSelList(hwnd, idc, size, *buf);
}
return size;
}
//-------------------------------------------------------------------------
void SetSliderParam(HWND hwnd, int idc_no, int max, int page, int start)
{
SetSliderParamEx(hwnd, idc_no, 0, max, page, 1, page *2, start);
}
//-------------------------------------------------------------------------
void SetSliderParamEx(HWND hwnd, int idc_no, int min, int max, int page, int line, int tick, int start)
{
SliderSetRange(hwnd, idc_no, min, max);
SliderSetPos(hwnd, idc_no, start);
SliderSetPage(hwnd, idc_no, page);
SliderSetLine(hwnd, idc_no, line);
SliderSetTick(hwnd, idc_no, tick);
}
//-------------------------------------------------------------------------
void SetMenuStr(HWND hwnd, int id, char *str)
{
HMENU hMenu = GetMenu(hwnd);
ModifyMenu(hMenu, id, MF_BYCOMMAND | MF_STRING, id, str);
DrawMenuBar(hwnd);
}
//-------------------------------------------------------------------------
void SetNewMenuStr(HWND hwnd, int id, int new_id, char *str)
{
HMENU hMenu = GetMenu(hwnd);
ModifyMenu(hMenu, id, MF_BYCOMMAND | MF_STRING, new_id, str);
DrawMenuBar(hwnd);
}
//-------------------------------------------------------------------------
void InsertMenuStr(HWND hwnd, int ins_id, int id, char *str)
{
HMENU hMenu = GetMenu(hwnd);
InsertMenu(hMenu, ins_id, MF_BYCOMMAND | MF_STRING, id, str);
DrawMenuBar(hwnd);
}
//-------------------------------------------------------------------------
void ResetMenu(HWND hwnd, int id, char *str)
{
HMENU hMenu = GetMenu(hwnd);
DeleteMenu(hMenu, id, MF_BYCOMMAND);
DrawMenuBar(hwnd);
}
| [
"pspbter@13f3a943-b841-0410-bae6-1b2c8ac2799f"
] | [
[
[
1,
74
]
]
] |
385a7199b2787b020b3acbbaf45adc79d0212c75 | 09f204a2d1d55af00cbccddb0f3aee4242e5f525 | /igmesh/cc/indigo_mesh.cc | 101cce4b9bff993a44034d85e375c92e690a9351 | [] | no_license | indigorenderer/indigorenderer.github.com | de21d9e056bf703e96827be8b3d2e84837143a31 | 11eb2df253ff72e9f57709d45930541d50f56af8 | refs/heads/master | 2021-01-25T10:22:24.629756 | 2010-05-27T05:20:58 | 2010-05-27T05:20:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,549 | cc | // Copyright (c) 2008-2010 Glare Technologies Limited. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found at http://www.indigorenderer.com/opensource/licence.txt
//
//
#include "indigo_mesh.h"
#include <fstream>
#include <limits>
namespace Indigo
{
IndigoMesh::IndigoMesh()
{
}
IndigoMesh::~IndigoMesh()
{
}
static const uint32 MAX_STRING_LENGTH = 1024;
static const uint32 MAX_VECTOR_LENGTH = std::numeric_limits<uint32>::max();
static const uint32 MAGIC_NUMBER = 5456751;
static const uint32 FORMAT_VERSION = 1;
template <class T>
inline static void writeBasic(std::ostream& stream, const T& t)
{
stream.write((const char*)&t, sizeof(T));
}
template <class T>
inline static void readBasic(std::istream& stream, T& t_out)
{
stream.read((char*)&t_out, sizeof(T));
}
inline static void write(std::ostream& stream, float x)
{
writeBasic(stream, x);
}
inline static void read(std::istream& stream, float& x)
{
readBasic(stream, x);
}
static void write(std::ostream& stream, const std::string& s)
{
const uint32 len = s.length();
if(len > MAX_STRING_LENGTH)
throw IndigoMeshExcep("String too long.");
writeBasic(stream, len);
stream.write(s.c_str(), len);
}
static void read(std::istream& stream, std::string& s_out)
{
uint32 len;
readBasic(stream, len);
if(len > MAX_STRING_LENGTH)
throw IndigoMeshExcep("String too long.");
char buf[MAX_STRING_LENGTH];
stream.read(buf, len);
s_out = std::string(buf, len);
}
static void write(std::ostream& s, const UVSetExposition& x)
{
write(s, x.uv_set_name);
writeBasic(s, x.uv_set_index);
}
static void read(std::istream& s, UVSetExposition& x)
{
read(s, x.uv_set_name);
readBasic(s, x.uv_set_index);
}
static void write(std::ostream& s, const Vec2f& x)
{
writeBasic(s, x);
}
static void read(std::istream& s, Vec2f& x)
{
readBasic(s, x);
}
static void write(std::ostream& s, const Vec3f& x)
{
writeBasic(s, x);
}
static void read(std::istream& s, Vec3f& x)
{
readBasic(s, x);
}
static void write(std::ostream& s, const Triangle& x)
{
writeBasic(s, x);
}
static void read(std::istream& s, Triangle& x)
{
readBasic(s, x);
}
template <class T>
static void writeVector(std::ostream& stream, const std::vector<T>& v)
{
if(v.size() > (std::vector<T>::size_type)MAX_VECTOR_LENGTH)
throw IndigoMeshExcep("Vector too long.");
const uint32 len = (uint32)v.size();
writeBasic(stream, len);
for(uint32 i=0; i<v.size(); ++i)
write(stream, v[i]);
}
template <class T>
static void readVector(std::istream& stream, std::vector<T>& v_out)
{
uint32 len;
readBasic(stream, len);
v_out.resize(len);
for(uint32 i=0; i<len; ++i)
read(stream, v_out[i]);
}
void IndigoMesh::writeToFile(const std::string& dest_path, const IndigoMesh& mesh) // throws IndigoMeshExcep on failure
{
if(mesh.num_uv_mappings > 0 && (mesh.uv_pairs.size() % mesh.num_uv_mappings != 0))
throw IndigoMeshExcep("Mesh uv_pairs.size() must be a multiple of mesh.num_uv_mappings");
if(mesh.vert_normals.size() != 0 && (mesh.vert_normals.size() != mesh.vert_positions.size()))
throw IndigoMeshExcep("Must be zero normals, or normals.size() must equal verts.size()");
std::ofstream file(dest_path.c_str(), std::ios_base::out | std::ios_base::binary);
if(!file)
throw IndigoMeshExcep("Failed to open file '" + dest_path + "' for writing.");
writeBasic(file, MAGIC_NUMBER);
writeBasic(file, FORMAT_VERSION);
writeBasic(file, mesh.num_uv_mappings);
writeVector(file, mesh.used_materials);
writeVector(file, mesh.uv_set_expositions);
writeVector(file, mesh.vert_positions);
writeVector(file, mesh.vert_normals);
writeVector(file, mesh.uv_pairs);
writeVector(file, mesh.triangles);
if(!file)
throw IndigoMeshExcep("Error while writing to '" + dest_path + "'.");
}
void IndigoMesh::readFromFile(const std::string& src_path, IndigoMesh& mesh_out) // throws IndigoMeshExcep on failure
{
try
{
std::ifstream file(src_path.c_str(), std::ios_base::in | std::ios_base::binary);
if(!file)
throw IndigoMeshExcep("Failed to open file '" + src_path + "' for reading.");
uint32 magic_number;
readBasic(file, magic_number);
if(magic_number != MAGIC_NUMBER)
throw IndigoMeshExcep("Invalid magic number.");
uint32 format_version;
readBasic(file, format_version);
if(format_version != FORMAT_VERSION)
throw IndigoMeshExcep("Invalid format version.");
readBasic(file, mesh_out.num_uv_mappings);
readVector(file, mesh_out.used_materials);
readVector(file, mesh_out.uv_set_expositions);
readVector(file, mesh_out.vert_positions);
readVector(file, mesh_out.vert_normals);
readVector(file, mesh_out.uv_pairs);
readVector(file, mesh_out.triangles);
if(!file)
throw IndigoMeshExcep("Error while reading from '" + src_path + "'.");
if(mesh_out.num_uv_mappings > 0 && (mesh_out.uv_pairs.size() % mesh_out.num_uv_mappings != 0))
throw IndigoMeshExcep("Mesh uv_pairs.size() must be a multiple of mesh.num_uv_mappings");
if(mesh_out.vert_normals.size() != 0 && (mesh_out.vert_normals.size() != mesh_out.vert_positions.size()))
throw IndigoMeshExcep("Must be zero normals, or normals.size() must equal verts.size()");
}
catch(std::bad_alloc&)
{
throw IndigoMeshExcep("Bad allocation while reading from file.");
}
}
}
| [
"[email protected]"
] | [
[
[
1,
234
]
]
] |
705f391f25e6d1a1c2f3d8dc550e864b7f412f26 | 01c236af2890d74ca5b7c25cec5e7b1686283c48 | /Src/NewCTGameForm.h | f709d85a203af0a2baf8f4de7e43564487d1ab9c | [
"MIT"
] | permissive | muffinista/palm-pitch | 80c5900d4f623204d3b837172eefa09c4efbe5e3 | aa09c857b1ccc14672b3eb038a419bd13abc0925 | refs/heads/master | 2021-01-19T05:43:04.740676 | 2010-07-08T14:42:18 | 2010-07-08T14:42:18 | 763,958 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,270 | h | #ifndef NEWCTGAMEFORM_H_
#define NEWCTGAMEFORM_H_
class CNewCTGameForm : public CForm {
public:
/*
TITLE "New Game"
FIELD ID SetPlayer3Name AT (56 108 78 12) USABLE LEFTALIGN FONT 0 MAXCHARS 14 UNDERLINED EDITABLE AUTOSHIFT
FIELD ID SetPlayer2Name AT (117 39 38 12) USABLE LEFTALIGN FONT 0 MAXCHARS 14 UNDERLINED AUTOSHIFT EDITABLE
FIELD ID SetPlayer1Name AT (62 20 38 12) USABLE LEFTALIGN FONT 0 MAXCHARS 14 UNDERLINED AUTOSHIFT EDITABLE
FIELD ID SetPlayer0Name AT (4 42 38 12) USABLE LEFTALIGN FONT 0 MAXCHARS 14 EDITABLE UNDERLINED AUTOSHIFT
LIST "Smart" "Risky" "Dumb" ID PlayerTypes0 AT (3 56 40 35) VISIBLEITEMS 3
LIST "Smart" "Risky" "Dumb" ID PlayerTypes1 AT (62 34 40 35) VISIBLEITEMS 3
LIST "Smart" "Risky" "Dumb" ID PlayerTypes2 AT (117 54 40 35) VISIBLEITEMS 3
LABEL "Play To:" AUTOID AT (19 123)
FIELD ID SetWinningScore AT (56 123 20 11) MAXCHARS 2 EDITABLE UNDERLINED NUMERIC
BUTTON "OK" ID StartGameButton AT (4 141 32 13)
LABEL "points." AUTOID AT (78 123)
LABEL "Your Name:" AUTOID AT (5 109)
BUTTON "Cancel" ID CancelGameButton AT (41 141 39 13)
GRAFFITISTATEINDICATOR AT (148 141)
*/
// Form event handlers
Boolean OnOpen(EventType* pEvent, Boolean& bHandled);
Boolean OnClose(EventType* pEvent, Boolean& bHandled);
// Command handlers
Boolean OnOK(EventPtr pEvent, Boolean& bHandled);
Boolean OnCancel(EventPtr pEvent, Boolean& bHandled);
Boolean OnGameOptions(EventPtr pEvent, Boolean& bHandled);
Boolean OnHelp(EventPtr pEvent, Boolean& bHandled);
Boolean OnAbout(EventPtr pEvent, Boolean& bHandled);
// Event map
BEGIN_EVENT_MAP(CForm)
EVENT_MAP_ENTRY(frmOpenEvent, OnOpen)
EVENT_MAP_ENTRY(frmCloseEvent, OnClose)
EVENT_MAP_COMMAND_ENTRY(StartGameButton, OnOK)
EVENT_MAP_COMMAND_ENTRY(OptionsGameButton, OnGameOptions)
EVENT_MAP_COMMAND_ENTRY(CancelGameButton, OnCancel)
EVENT_MAP_MENU_ENTRY(MainOptionsQuitGame, OnCancel )
EVENT_MAP_MENU_ENTRY(HelpInstructions, OnHelp )
EVENT_MAP_MENU_ENTRY(HelpAboutPitch, OnAbout )
END_EVENT_MAP()
protected:
CField p0name;
CField p1name;
CField p2name;
CField p3name;
CField winning_score;
};
#endif // NEWGAMEFORM_H_
| [
"[email protected]"
] | [
[
[
1,
58
]
]
] |
537ec3b4294a12f479e185864a84b0f622d41aa3 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Network/Misc/Include/speedhackchecker.h | cf34cb9af9420e7a3e9958f50da39a10173d7bea | [] | no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | h | #ifndef __SPEEDHACKCHECKER_H__
#define __SPEEDHACKCHECKER_H__
#include "dpmng.h"
#include "msghdr.h"
class CSpeedHackChecker
{
private:
// time_t m_tBaseOfServer;
// time_t m_tBaseOfClient;
DWORD m_tBaseOfServer;
DWORD m_tBaseOfClient;
BOOL m_fKill;
public:
// Constructions
CSpeedHackChecker();
~CSpeedHackChecker();
// Operations
void sETbaseOfServer( CDPMng* pDPMng, DPID dpidPlayer );
// void sETbaseOfClient( time_t tBaseOfClient );
void sETbaseOfClient( DWORD tBaseOfClient );
void rEQoffsetOfClient( CDPMng* pDPMng, DPID dpidPlayer );
// BOOL CheckClock( time_t tCurClient, CDPMng* pDPMng, DPID dpidPlayer );
BOOL CheckClock( DWORD tCurClient, CDPMng* pDPMng, DPID dpidPlayer );
BOOL fsETbaseOfClient( void ) { return(BOOL)m_tBaseOfClient; }
void Kill( void ) { m_fKill = TRUE; }
};
#endif // __SPEEDHACKCHECKER_H__ | [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
30
]
]
] |