blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
9e0ebbe878c1a3ec46a89642ad849ead1564beac
3449de09f841146a804930f2a51ccafbc4afa804
/C++/CodeJam/practice/BlackWhitePlane.cpp
a2aa977deb3d77fed336f44038573a3146722bae
[]
no_license
davies/daviescode
0c244f4aebee1eb909ec3de0e4e77db3a5bbacee
bb00ee0cfe5b7d5388485c59211ebc9ba2d6ecbd
refs/heads/master
2020-06-04T23:32:27.360979
2007-08-19T06:31:49
2007-08-19T06:31:49
32,641,672
1
1
null
null
null
null
UTF-8
C++
false
false
5,715
cpp
// BEGIN CUT HERE // PROBLEM STATEMENT // There are some circles on the plane. Circles may lie // completely inside other circles, but may not touch or // intersect other circles in any other way. Initially, the // plane is entirely black. Then circles are drawn in order // of non-increasing radii. If a circle is drawn on a black // background, it is filled with the color white. If it is // drawn on a white background, it is filled black. Your task // is to compute the total white area on the plane after // drawing all the circles. // // You are given a vector <string> circles containing the // circles on the plane. Each element will be formatted as "X // Y R", where (X, Y) are the coordinates of the center of // the circle, and R is the radius. // // DEFINITION // Class:BlackWhitePlane // Method:area // Parameters:vector <string> // Returns:double // Method signature:double area(vector <string> circles) // // // NOTES // -A circle can lie completely inside another circle only if // it has a smaller radius than the outer circle. // -The returned value must be accurate to 1e-9 relative or // absolute. // // // CONSTRAINTS // -circles will contain between 1 and 50 elements, inclusive. // -Each element of circles will be formatted as "X Y R", // where X, Y, and R are integers with no leading zeroes. // -Each X and Y will be between 0 and 10000, inclusive. // -Each R will be between 1 and 100, inclusive. // -No two circles in circles will touch or intersect (unless // one lies completely inside the other). // // // EXAMPLES // // 0) // {"1 1 1"} // // Returns: 3.141592653589793 // // The only circle is drawn on the black plane, so it is // white. Its area is pi*R2. // // 1) // {"4 3 1", "3 2 3", "8 1 1"} // // Returns: 28.274333882308138 // // The first circle is drawn inside of the second, so it is // black. // The total white area is pi*32 + pi*12 - pi*12 = pi*9. // // // 2) // {"15 15 4", "15 25 4", "25 25 4", "25 15 4", "25 25 100"} // // Returns: 31214.86460606818 // // The first four circles are all inside the fifth one. // // 3) // {"2549 8482 11", "9175 5927 35", "2747 6177 93", "5512 // 8791 81", "4487 8456 60", // "6899 610 77", "9716 2202 3", "9312 5625 79", "4020 9851 // 85", "1640 7179 54", // "5761 4348 51","5917 3436 88","6547 386 33","182 7676 1"," // 6329 4496 89"} // // Returns: 194250.95695676407 // #line 81 "BlackWhitePlane.cpp" // END CUT HERE #include <string> #include <iostream> #include <sstream> #include <vector> #include <queue> #include <stack> #include <list> #include <set> #include <map> #include <cmath> #include <valarray> #include <numeric> #include <functional> #include <algorithm> using namespace std; typedef vector<int> VI; #define SZ(v) ((int)(v).size()) #define FOR(i,a,b) for(int i=(a);i<int(b);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() typedef stringstream SS; typedef istringstream ISS; bool cmp(const string& a,const string& b) { ISS in(a);int x;in >> x >> x >>x; ISS inn(b);int y;inn >> y >> y >> y; return x > y ; } class BlackWhitePlane { public: double area(vector <string> cir) { int N=SZ(cir); sort(ALL(cir),cmp); VI vx(N),vy(N),vd(N); REP(i,N) { ISS in(cir[i]); in >> vx[i] >> vy[i] >> vd[i]; } double re = 0; VI bw(N,0); REP(i,SZ(cir)){ bw[i] = 1; for(int j=i-1;j>=0;j--){ if( (vx[j]-vx[i])*(vx[j]-vx[i])+(vy[j]-vy[i])*(vy[j]-vy[i]) < vd[j]*vd[j] ){ bw[i] = 1-bw[j]; } } re += (bw[i]*2-1)*3.141592653589793L*vd[i]*vd[i]; } return re; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"1 1 1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 3.141592653589793; verify_case(0, Arg1, area(Arg0)); } void test_case_1() { string Arr0[] = {"4 3 1", "3 2 3", "8 1 1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 28.274333882308138; verify_case(1, Arg1, area(Arg0)); } void test_case_2() { string Arr0[] = {"15 15 4", "15 25 4", "25 25 4", "25 15 4", "25 25 100"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 31214.86460606818; verify_case(2, Arg1, area(Arg0)); } void test_case_3() { string Arr0[] = {"2549 8482 11", "9175 5927 35", "2747 6177 93", "5512 8791 81", "4487 8456 60", "6899 610 77", "9716 2202 3", "9312 5625 79", "4020 9851 85", "1640 7179 54", "5761 4348 51","5917 3436 88","6547 386 33","182 7676 1","6329 4496 89"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 194250.95695676407; verify_case(3, Arg1, area(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { BlackWhitePlane ___test; ___test.run_test(-1); } // END CUT HERE
[ "davies.liu@32811f3b-991a-0410-9d68-c977761b5317" ]
[ [ [ 1, 165 ] ] ]
0985e3c760d7c06c56c0164018492b7f41344df4
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/pcsx2/PathDefs.h
b842c061a37d54652e510ab61ae07cc135638ed5
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
2,450
h
/* PCSX2 - PS2 Emulator for PCs * Copyright (C) 2002-2009 PCSX2 Dev Team * * PCSX2 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 Found- * ation, either version 3 of the License, or (at your option) any later version. * * PCSX2 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 PCSX2. * If not, see <http://www.gnu.org/licenses/>. */ #pragma once enum FoldersEnum_t { FolderId_Plugins = 0, FolderId_Settings, FolderId_Bios, FolderId_Snapshots, FolderId_Savestates, FolderId_MemoryCards, FolderId_Logs, FolderId_Documents, FolderId_COUNT }; ////////////////////////////////////////////////////////////////////////////////////////// // PathDefs Namespace -- contains default values for various pcsx2 path names and locations. // // Note: The members of this namespace are intended for default value initialization only. // Most of the time you should use the path folder assignments in g_Conf instead, since those // are user-configurable. // namespace PathDefs { // complete pathnames are returned by these functions // For 99% of all code, you should use these. extern wxDirName GetSnapshots(); extern wxDirName GetBios(); extern wxDirName GetThemes(); extern wxDirName GetPlugins(); extern wxDirName GetSavestates(); extern wxDirName GetMemoryCards(); extern wxDirName GetSettings(); extern wxDirName GetLogs(); extern wxDirName Get( FoldersEnum_t folderidx ); // Base folder names used to extend out the documents/approot folder base into a complete // path. These are typically for internal AppConfig use only, barring a few special cases. namespace Base { extern const wxDirName& Snapshots(); extern const wxDirName& Savestates(); extern const wxDirName& MemoryCards(); extern const wxDirName& Settings(); extern const wxDirName& Plugins(); extern const wxDirName& Themes(); } } namespace FilenameDefs { extern wxFileName GetConfig(); extern wxFileName GetUsermodeConfig(); extern const wxFileName& Memcard( uint port, uint slot ); };
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 75 ] ] ]
056d0b03fd1e725006a43c8762255631d2e6e65b
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/testsemtrywait/inc/tsemtrywaitserver.h
2d25333653573092c6ec9f3c27089fcfe24197a0
[]
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
822
h
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #ifndef __TSEMTRYWAITSERVER_H__ #define __TSEMTRYWAITSERVER_H__ #include <f32file.h> #include <test/TestExecuteServerBase.h> class CSemtrywaitTestServer : public CTestServer { public: static CSemtrywaitTestServer* NewL(); virtual CTestStep* CreateTestStep(const TDesC& aStepName); RFs& Fs() {return iFs;} private: RFs iFs; }; #endif //
[ "none@none" ]
[ [ [ 1, 36 ] ] ]
0fd22977d2abd245f0def795821c3b6421d12f36
4accfbc787e4c21fa63f207dd7870de106082b61
/Assignment 1/Employee.h
4591d6de6fe9bd0e9eb22ab00b2a6cc369f75ca6
[]
no_license
kevbite/CProformanceAss1
66efde3925f826738781966292205b0a740c584b
9bf5dfd96792f4f12e638bc910840c78aa9bb865
refs/heads/master
2021-01-01T18:38:05.712343
2009-03-29T15:28:14
2009-03-29T15:28:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,432
h
#pragma once #include <string> #include <vector> #include <algorithm> #include <iostream> #include <string> #include <numeric> #include <boost/foreach.hpp> #include "CalcSum.h" //some typedef for the containers typedef std::vector<int> resultsContainer; typedef std::vector<int> rSetPercContainer; typedef std::vector<const std::string*> textRSetPercContainer; //the strings to use for red, green and amber const std::string RED_TEXT = "Red"; const std::string GREEN_TEXT = "Green"; const std::string AMBER_TEXT = "Amber"; //look up table for text Mark //results 0-50 static const std::string* markTextTable[] = { &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &RED_TEXT, &AMBER_TEXT,&AMBER_TEXT,&AMBER_TEXT,&AMBER_TEXT,&AMBER_TEXT,&AMBER_TEXT,&AMBER_TEXT,&AMBER_TEXT,&AMBER_TEXT, &AMBER_TEXT, &GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT, &GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT,&GREEN_TEXT, &GREEN_TEXT }; class Employee { private: resultsContainer results_; std::string actualData_; std::string ethnicGroup_; std::string workBasis_; double lengthService_; int pinNo_; int age_; static const int MIN_DATA_LENGTH=80; rSetPercContainer *resultsSetsPerc_; textRSetPercContainer *textResultSet_; public: Employee(void); Employee(std::string actualData, int pinNo, int age, double los, std::string ethnicGrp, std::string workBasis, resultsContainer results); ~Employee(void); const std::string *getActualData() const; const int *getPinNo() const; const int *getAge() const; const double *getLengthOfService() const; const std::string *getEthnicGroup() const; const std::string *getWorkBasis() const; const resultsContainer *getResults() const; rSetPercContainer *getResultSetPercentageMean(); void calcResultSetPercentageMean(); textRSetPercContainer *getTextResultSets(); void calcTextResultSets(); void clearCached(); const bool hasTotalInvalidData() const; const bool hasTotalInvalidResults() const; const bool hasPartialInvalidData() const; const bool hasPartialInvalidResults() const; };
[ [ [ 1, 78 ] ] ]
a8e8ebb114e8816c34e624c07c167339888c97f0
028d6009f3beceba80316daa84b628496a210f8d
/templates/com.nokia.carbide.cpp.templates/templates/classtemplates/CClass/ClassName.cpp
45fae59df3f2b27dbc77ed95f1effb6e82563acd
[]
no_license
JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp
fa50cafa69d3e317abf0db0f4e3e557150fd88b3
4420f338bc4e522c563f8899d81201857236a66a
refs/heads/master
2020-12-30T16:45:28.474973
2010-10-20T16:19:31
2010-10-20T16:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
805
cpp
/* ============================================================================ Name : $(classname).cpp Author : $(author) Version : $(version) Copyright : $(copyright) Description : C$(classname) implementation ============================================================================ */ #include "$(incFileName)" C$(classname)::C$(classname)() { // No implementation required } C$(classname)::~C$(classname)() { } C$(classname)* C$(classname)::NewLC() { C$(classname)* self = new (ELeave)C$(classname)(); CleanupStack::PushL(self); self->ConstructL(); return self; } C$(classname)* C$(classname)::NewL() { C$(classname)* self=C$(classname)::NewLC(); CleanupStack::Pop(); // self; return self; } void C$(classname)::ConstructL() { }
[ [ [ 1, 41 ] ] ]
1e3f7897676e3b926fe9278265af29c64abc3318
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/emu/sound/ics2115.h
f27f190596a16bb3ce39bc4dce011e4ea27adbef
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,041
h
#pragma once #ifndef __ICS2115_H__ #define __ICS2115_H__ //************************************************************************** // INTERFACE CONFIGURATION MACROS //************************************************************************** #define MCFG_ICS2115_ADD(_tag, _clock, _irqf) \ MCFG_DEVICE_ADD(_tag, ICS2115, _clock) \ MCFG_IRQ_FUNC(_irqf) \ #define MCFG_ICS2115_REPLACE(_tag, _clock, _irqf) \ MCFG_DEVICE_REPLACE(_tag, ICS2115, _clock) \ MCFG_IRQ_FUNC(_irqf) #define MCFG_IRQ_FUNC(_irqf) \ ics2115_device_config::static_set_irqf(device, _irqf); \ //************************************************************************** // TYPE DEFINITIONS //************************************************************************** struct ics2115_voice { struct { INT32 left; UINT32 acc, start, end; UINT16 fc; UINT8 ctl, saddr; } osc; struct { INT32 left; UINT32 add; UINT32 start, end; UINT32 acc; UINT16 regacc; UINT8 incr; UINT8 pan, mode; } vol; union { struct { UINT8 ulaw : 1; UINT8 stop : 1; //stops wave + vol envelope UINT8 eightbit : 1; UINT8 loop : 1; UINT8 loop_bidir : 1; UINT8 irq : 1; UINT8 invert : 1; UINT8 irq_pending: 1; //IRQ on variable? }; UINT8 value; } osc_conf; union { struct { UINT8 done : 1; //indicates ramp has stopped UINT8 stop : 1; //stops the ramp UINT8 rollover : 1; //rollover (TODO) UINT8 loop : 1; UINT8 loop_bidir : 1; UINT8 irq : 1; //enable IRQ generation UINT8 invert : 1; //invert direction UINT8 irq_pending: 1; //(read only) IRQ pending //noenvelope == (done | disable) }; UINT8 value; } vol_ctrl; //Possibly redundant state. => improvements of wavetable logic //may lead to its elimination. union { struct { UINT8 on : 1; UINT8 ramp : 7; // 100 0000 = 0x40 maximum }; UINT8 value; } state; bool playing(); int update_volume_envelope(); int update_oscillator(); void update_ramp(); }; // ======================> ics2115_device_config class ics2115_device_config : public device_config, public device_config_sound_interface { friend class ics2115_device; // construction/destruction ics2115_device_config(const machine_config &mconfig, const char *tag, const device_config *owner, UINT32 clock); public: // allocators static device_config *static_alloc_device_config(const machine_config &mconfig, const char *tag, const device_config *owner, UINT32 clock); virtual device_t *alloc_device(running_machine &machine) const; // inline configuration helpers static void static_set_irqf(device_config *device, void (*irqf)(device_t *device, int state)); protected: // inline data void (*m_irq_func)(device_t *device, int state); }; // ======================> ics2115_device class ics2115_device : public device_t, public device_sound_interface { friend class ics2115_device_config; // construction/destruction ics2115_device(running_machine &_machine, const ics2115_device_config &config); public: static READ8_DEVICE_HANDLER(read); static WRITE8_DEVICE_HANDLER(write); //UINT8 read(offs_t offset); //void write(offs_t offset, UINT8 data); static TIMER_CALLBACK(timer_cb_0); static TIMER_CALLBACK(timer_cb_1); sound_stream *m_stream; static const UINT16 revision = 0x1; protected: // device-level overrides virtual void device_start(); virtual void device_reset(); // internal callbacks void sound_stream_update(sound_stream &stream, stream_sample_t **inputs, stream_sample_t **outputs, int samples); // internal state const ics2115_device_config &m_config; void (*m_irq_cb)(device_t *device, int state); UINT8 *m_rom; INT16 m_ulaw[256]; UINT16 m_volume[4096]; static const int volume_bits = 15; ics2115_voice m_voice[32]; struct { UINT8 scale, preset; emu_timer *timer; UINT64 period; /* in nsec */ } m_timer[2]; UINT8 m_active_osc; UINT8 m_osc_select; UINT8 m_reg_select; UINT8 m_irq_enabled, m_irq_pending; bool m_irq_on; //Unknown variable, seems to be effected by 0x12. Further investigation //Required. UINT8 m_vmode; //internal register helper functions UINT16 reg_read(); void reg_write(UINT8 data, bool msb); void recalc_timer(int timer); void keyon(); void recalc_irq(); //stream helper functions int fill_output(ics2115_voice& voice, stream_sample_t *outputs[2], int samples); stream_sample_t get_sample(ics2115_voice& voice); }; // device type definition extern const device_type ICS2115; #endif /* __ICS2115_H__ */
[ "Mike@localhost" ]
[ [ [ 1, 185 ] ] ]
aac0584e18862a10d4d282312b374eb171e32143
5fd87c086e3d424d89bbe89c766175c42bcdc0c7
/test/CppUnitLite/TestResult.cpp
06d7a3ec1c508431d679cc62c817ffad37f04da7
[]
no_license
nagyist/simple-photo
1826d3dec05599a91b84a98e5952249a1704d6df
afc0d6fc188761efb9d44a58023b17eb5e16aba7
refs/heads/master
2016-09-06T03:32:44.133030
2009-11-22T14:16:32
2009-11-22T14:16:32
39,789,365
0
0
null
null
null
null
UTF-8
C++
false
false
1,787
cpp
/***************************************************************** Copyright 2009 Rui Barbosa Martins 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. *****************************************************************/ #include "TestResult.h" #include "Failure.h" #include "SimpleString.h" #include <stdio.h> TestResult::TestResult () : failureCount (0) { } void TestResult::testsStarted () { printf("----------------------------------------------\n"); } void TestResult::addFailure (const Failure& failure) { char buffer[1024]; sprintf (buffer, "Failure: [%s] line [%ld] in [%s].\n", failure.message.asCharString (), failure.lineNumber, failure.fileName.asCharString ()); failure_msgs.push_back(new SimpleString(buffer)); failureCount++; } void TestResult::testsEnded (int total_tests) { printf("----------------------------------------------\n"); for (unsigned int i = 0; i < failure_msgs.size(); ++i) { fprintf(stdout, "%s", failure_msgs[i]->asCharString()); delete failure_msgs[i]; } printf("==============================================\n"); if (failureCount > 0) fprintf (stdout, "There were %d failures out of %d tests\n", failureCount, total_tests); else fprintf (stdout, "A total of %d tests succeeded\n", total_tests); }
[ [ [ 1, 57 ] ] ]
ac384daa92f73e95242c440a378b43b49b148edb
206177d643cb88d0339f6130e764daba1376f4a7
/cplusplus_code/sources/dlistener_net.h
67bc99cd4acfde010b7fecf05a4e6f56d0c9469a
[]
no_license
mwollenweber/rebridge
aae8b9dfbf985d3264d7e3874079e1f068cda4c1
4ca787dd545e8064c926811dc81772a6a8c356d1
refs/heads/master
2020-12-24T13:20:11.572283
2010-08-01T05:37:02
2010-08-01T05:37:02
775,487
5
0
null
null
null
null
UTF-8
C++
false
false
629
h
#ifndef __DLISTENER__NET_H__ #define __DLISTENER__NET_H__ #include "Buffer.h" #include <string> #include <Windows.h> #include <map> #include <vector> #define DEFAULT_PORT 8088 bool recv_net_command(Buffer &b); void send_cmd_results(Buffer &buf, std::string cmd, std::string results="", unsigned char cmd_type=1); void send_break_cmd(unsigned int tid=-1 ); void send_resume_cmd(unsigned int tid=-1 ); void send_bphit(ULONG64 ea); void send_get_status(); void send_idapython_cmd(std::string cmd); bool send_cmd_string(std::string cmd, std::string result="", unsigned char cmd_type=0); #endif
[ [ [ 1, 29 ] ] ]
864b671bd3950a1b71810da3987eef7239571907
1efccef3353a58751d15e79fcbc05c94a1edbbb1
/compression/zlib_c/zlibtool/zlibtool/ZlibToolPpg.h
1c4b4ccbcb0e410cf987810851f893d3bd8c8ba9
[]
no_license
siggame/MegaMinerAI-6
22c67bbcbafe00c45a12f2909de66538792e0a87
28ce96071aecd2dc7e7f82f0fea34e727d64e097
refs/heads/master
2020-06-04T18:02:46.328674
2011-04-13T22:23:02
2011-04-13T22:23:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
934
h
// ZlibToolPpg.h : Declaration of the CZlibToolPropPage property page class. //////////////////////////////////////////////////////////////////////////// // CZlibToolPropPage : See ZlibToolPpg.cpp.cpp for implementation. class CZlibToolPropPage : public COlePropertyPage { DECLARE_DYNCREATE(CZlibToolPropPage) DECLARE_OLECREATE_EX(CZlibToolPropPage) // Constructor public: CZlibToolPropPage(); // Dialog Data //{{AFX_DATA(CZlibToolPropPage) enum { IDD = IDD_PROPPAGE_ZLIBTOOL }; int m_level; CString m_inputFile; CString m_outputFile; //}}AFX_DATA // Implementation protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Message maps protected: //{{AFX_MSG(CZlibToolPropPage) // NOTE - ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() };
[ [ [ 1, 35 ] ] ]
a81eb7ccb60d0cf974332aa0104e311d7b2f9649
073dfce42b384c9438734daa8ee2b575ff100cc9
/RCF/include/RCF/util/AutoBuild.hpp
4255d3f771016b81e7f0cc91195c7b9f8ef47d25
[]
no_license
r0ssar00/iTunesSpeechBridge
a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf
71a27a52e66f90ade339b2b8a7572b53577e2aaf
refs/heads/master
2020-12-24T17:45:17.838301
2009-08-24T22:04:48
2009-08-24T22:04:48
285,393
1
0
null
null
null
null
UTF-8
C++
false
false
1,299
hpp
//****************************************************************************** // RCF - Remote Call Framework // Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved. // Consult your license for conditions of use. // Version: 1.1 // Contact: jarl.lindrud <at> gmail.com //****************************************************************************** // NOTE: when using the build system to supply definitions for OUTPUT_DIR_UNQUOTED // and OPENSSL_CERTIFICATE_DIR_UNQUOTED, the paths should not contain any symbols which // might be replaced by the preprocessor. Eg if OUTPUT_DIR_UNQUOTED is // // \\A\\B\\C\\_MSC_VER\\D\\E // // then the resulting OUTPUT_DIR will be "\\A\\B\\C\\0x1310\\D\\E", or something like that. #ifndef INCLUDE_UTIL_AUTOBUILD_HPP #define INCLUDE_UTIL_AUTOBUILD_HPP #include <boost/config.hpp> #define UTIL_AUTOBUILD_HELPER_MACRO_QUOTE(x) UTIL_AUTOBUILD_HELPER_MACRO_QUOTE_(x) #define UTIL_AUTOBUILD_HELPER_MACRO_QUOTE_(x) #x #ifdef BOOST_WINDOWS #define RCF_PATH_SEPARATOR "\\" #else #define RCF_PATH_SEPARATOR "/" #endif #ifdef TEMP_DIR_UNQUOTED #define RCF_TEMP_DIR UTIL_AUTOBUILD_HELPER_MACRO_QUOTE( TEMP_DIR_UNQUOTED ) RCF_PATH_SEPARATOR #else #define RCF_TEMP_DIR "" #endif #endif //! INCLUDE_UTIL_AUTOBUILD_HPP
[ [ [ 1, 38 ] ] ]
832a8ae36c2f6da5c1fb78c376b150919997b260
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/audio3/naudiofile.cc
9d76d663378d51e740d2f6c150a91989a08cc0ac
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,464
cc
//------------------------------------------------------------------------------ // naudiofile.cc // (C) 2005 Radon Labs GmbH //------------------------------------------------------------------------------ #include "precompiled/pchndsound.h" #include "audio3/naudiofile.h" //------------------------------------------------------------------------------ /** */ nAudioFile::nAudioFile() : isOpen(false) { // empty } //------------------------------------------------------------------------------ /** */ nAudioFile::~nAudioFile() { n_assert(!this->IsOpen()); } //------------------------------------------------------------------------------ /** Open the file for reading. The method should open the file and read the file's header data. */ bool nAudioFile::Open(const nString& /*filename*/) { n_assert(!this->IsOpen()); this->isOpen = true; return true; } //------------------------------------------------------------------------------ /** Close the file. */ void nAudioFile::Close() { n_assert(this->IsOpen()); this->isOpen = false; } //------------------------------------------------------------------------------ /** Read data from file. Returns the number of bytes actually read. If decoding happens inside Read() the number of bytes to read and number of bytes actually read means "decoded data". The method should wrap around if the end of the data is encountered. */ uint nAudioFile::Read(void* /*buffer*/, uint /*bytesToRead*/) { n_assert(this->IsOpen()); return 0; } //------------------------------------------------------------------------------ /** Reset the object to the beginning of the audio data. */ bool nAudioFile::Reset(LONG /*pos*/) { n_assert(this->IsOpen()); return true; } //------------------------------------------------------------------------------ /** This method returns the (decoded) size of audio data in the file in bytes. */ int nAudioFile::GetSize() const { n_assert(this->IsOpen()); return 0; } //------------------------------------------------------------------------------ /** This method returns a pointer to a WAVEFORMATEX structure which describes the format of the audio data in the file. */ WAVEFORMATEX* nAudioFile::GetFormat() const { n_error("nAudioFile::GetFormat(): not implemented!"); return 0; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 95 ] ] ]
5fa6ea3c4090a9253f01af883f84e2901145cf31
26867688a923573593770ef4c25de34e975ff7cb
/mmokit/cpp/common/inc/textUtils.h
31c63ee44599f7456add21f7f62eef3ccaeff441
[]
no_license
JeffM2501/mmokit
2c2b873202324bd37d0bb2c46911dc254501e32b
9212bf548dc6818b364cf421778f6a36f037395c
refs/heads/master
2016-09-06T10:02:07.796899
2010-07-25T22:12:15
2010-07-25T22:12:15
32,234,709
1
0
null
null
null
null
UTF-8
C++
false
false
10,174
h
/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* * common definitions */ #ifndef __TEXTUTILS_H__ #define __TEXTUTILS_H__ /* system interface headers */ #include <algorithm> #include <ctype.h> #ifdef HAVE_DEFINED_TOLOWER #undef tolower #undef toupper #endif #include <string> #include <stdarg.h> #include <vector> typedef std::vector<std::string> string_list; /** This namespace provides basic functionality to parse and * format strings */ namespace TextUtils { std::string vformat(const char* fmt, va_list args); std::string format(const char* fmt, ...); bool same_no_case( const std::string& s1, const char * s2 ); bool same_no_case( const std::string& s1, const std::string& s2 ); bool same_no_case( const char* s1, const char* s2 ); bool same_no_case( const char* s1, const std::string& s2 ); /** returns a string converted to lowercase */ inline std::string tolower(const std::string& s) { std::string trans = s; for (std::string::iterator i=trans.begin(), end=trans.end(); i!=end; ++i) *i = ::tolower(*i); return trans; } /** returns a string converted to uppercase */ inline std::string toupper(const std::string& s) { std::string trans = s; for (std::string::iterator i=trans.begin(), end=trans.end(); i!=end; ++i) *i = ::toupper(*i); return trans; } /** replace all of in in replaceMe with withMe */ std::string replace_all(const std::string& in, const std::string& replaceMe, const std::string& withMe); /** return copy of string with all whitespace stripped */ std::string no_whitespace(const std::string &s); /** return copy of string with all whitespace trimmed from the start and end */ std::string trim_whitespace(const std::string &s); /** * Get a vector of strings from a string, using all of chars of thedelims * string as separators. If maxTokens > 0, then the last 'token' maycontain delimiters * as it just returns the rest of the line * if you specify use quotes then tokens can be grouped in quotes and delimeters * inside quotes are ignored. * Hence /ban "Mr Blahblah" isajerk parses to "/ban", "Mr Blahlah" and "isajerk" * but so does "Mr Blahblah" "isajerk", so if you want 3 tokens and a delimeter * is in one of the tokens, by puting quotes around it you can get the correct * parsing. When use quotes is enabled, \'s and "'s should\can be escaped with \ * escaping is not currently done for any other character. * Should not have " as a delimeter if you want to use quotes */ std::vector<std::string> tokenize(const std::string& in, const std::string &delims, const int maxTokens = 0, const bool useQuotes = false); /** convert a string represantation of some duration into minutes * example: "1d2h16m" -> 1500 */ int parseDuration(const std::string &duration); // C h a r a c t e r c o m p a r i s o n /** compare_nocase is strait from Stroustrup. This implementation uses * strings instead of char arrays and includes a maxlength bounds check. * It compares two strings and returns 0 if equal, <0 if s1 is less than * s2, and >0 if s1 is greater than s2. */ inline int compare_nocase(const std::string& s1, const std::string &s2, int maxlength=4096) { std::string::const_iterator p1 = s1.begin(); std::string::const_iterator p2 = s2.begin(); int i=0; while (p1 != s1.end() && p2 != s2.end()) { if (i >= maxlength) { return 0; } if (::tolower(*p1) != ::tolower(*p2)) { return (::tolower(*p1) < ::tolower(*p2)) ? -1 : 1; } ++p1; ++p2; ++i; } return (s2.size() == s1.size()) ? 0 : (s1.size() < s2.size()) ? -1 : 1; // size is unsigned } /** utility function returns truthfully whether * given character is a letter. */ inline bool isAlphabetic(const char c) { if (( c > 64 && c < 91) || ( c > 96 && c < 123)) { return true; } return false; } /** utility function returns truthfully whether * given character is a number. */ inline bool isNumeric(const char c) { if (( c > 47 && c < 58)) { return true; } return false; } /** utility function returns truthfully whether * a given character is printable whitespace. * this includes newline, carriage returns, tabs * and spaces. */ inline bool isWhitespace(const char c) { if ((( c >= 9 ) && ( c <= 13 )) || (c == 32)) { return true; } return false; } /** utility function returns truthfully whether * a given character is punctuation. */ inline bool isPunctuation(const char c) { if (( c > 32 && c < 48) || ( c > 57 && c < 65) || ( c > 90 && c < 97) || ( c > 122 && c < 127)) { return true; } return false; } /** utility function returns truthfully whether * given character is an alphanumeric. this is * strictly letters and numbers. */ inline bool isAlphanumeric(const char c) { if (isAlphabetic(c) || isNumeric(c)) { return true; } return false; } /** utility function returns truthfully whether * given character is printable. this includes * letters, numbers, and punctuation. * (but NOT whitespace) */ inline bool isVisible(const char c) { if (isAlphanumeric(c) || isPunctuation(c)) { return true; } return false; } /** utility function returns truthfully whether * given character is printable. this includes * letters, numbers, punctuation, and whitespace */ inline bool isPrintable(const char c) { if (isVisible(c) || isWhitespace(c)) { return false; } return true; } // S t r i n g i t e r a t i o n /** utility method that returns the position of the * first alphanumeric character from a string */ inline int firstAlphanumeric(const std::string &input, unsigned short int max=4096) { if (max > input.length()) max = (unsigned short)input.length(); for (unsigned short i = 0; i < max; i++) if (isAlphanumeric(input[i])) return i; return -1; } /** utility method that returns the position of the * first non-alphanumeric character from a string */ inline int firstNonalphanumeric(const std::string &input, unsigned short int max=4096) { if (max > input.length()) max = (unsigned short)input.length(); for (unsigned short i = 0; i < max; i++) if (!isAlphanumeric(input[i])) return i; return -1; } /** utility method that returns the position of the * first printable character from a string */ inline int firstPrintable(const std::string &input, unsigned short int max=4096) { if (max > input.length()) max = (unsigned short)input.length(); for (unsigned short i = 0; i < max; i++) if (isPrintable(input[i])) return i; return -1; } /** utility method that returns the position of the * first non-printable character from a string */ inline int firstNonprintable(const std::string &input, unsigned short int max=4096) { if (max > input.length()) max = (unsigned short)input.length(); for (unsigned short i = 0; i < max; i++) if (!isPrintable(input[i])) return i; return -1; } /** utility method that returns the position of the * first visible character from a string */ inline int firstVisible(const std::string &input, unsigned short int max=4096) { if (max > input.length()) max = (unsigned short)input.length(); for (unsigned short i = 0; i < max; i++) if (isVisible(input[i])) return i; return -1; } /** utility method that returns the position of the * first non visible character from a string (control * codes or whitespace */ inline int firstNonvisible(const std::string &input, unsigned short int max=4096) { if (max > input.length()) max = (unsigned short)input.length(); for (unsigned short i = 0; i < max; i++) if (!isVisible(input[i])) return i; return -1; } /** utility method that returns the position of the * first alphabetic character from a string */ inline int firstAlphabetic(const std::string &input, unsigned short int max=4096) { if (max > input.length()) max = (unsigned short)input.length(); for (unsigned short i = 0; i < max; i++) if (isAlphabetic(input[i])) return i; return -1; } /** utility method that returns the position of the * first printable character from a string */ inline int firstNonalphabetic(const std::string &input, unsigned short int max=4096) { if (max > input.length()) max = (unsigned short)input.length(); for (unsigned short i = 0; i < max; i++) if (!isAlphabetic(input[i])) return i; return -1; } /** url-encodes a string */ std::string url_encode(const std::string &text); /** escape a string */ std::string escape(const std::string &text, char escaper); /** un-escape a string */ std::string unescape(const std::string &text, char escaper); /** lookup for an un-escaped separator */ int unescape_lookup(const std::string &text, char escaper, char sep); }; #endif // __TEXTUTILS_H__ // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
[ "JeffM2501@b8188ba6-572f-0410-9fd0-1f3cfbbf368d" ]
[ [ [ 1, 385 ] ] ]
3eaa0d3cbc62183ae65c31e6e56d150db3430344
38664d844d9fad34e88160f6ebf86c043db9f1c5
/branches/initialize/tagpath/network/httpinstance.cpp
675aa6e96d67178d5105c3b0dfa0780396c14331
[]
no_license
cnsuhao/jezzitest
84074b938b3e06ae820842dac62dae116d5fdaba
9b5f6cf40750511350e5456349ead8346cabb56e
refs/heads/master
2021-05-28T23:08:59.663581
2010-11-25T13:44:57
2010-11-25T13:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
#include "HttpSession.h" #include "HttpInstance.h" namespace tting { HttpSession & HttpInstance::Session() { // TODO: Lock, only single thread call if (inst_ == 0) { inst_ = new HttpSession(); } return *inst_; } void HttpInstance::ReleaseSession() { delete inst_; inst_ = 0; } HttpSession * HttpInstance::inst_ = 0; } // namespace tting
[ "ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd" ]
[ [ [ 1, 25 ] ] ]
24d2542349ceb51dfc4b678726debd2ff6301ab1
fd792229322e4042f6e88a01144665cebdb1c339
/src/serverNativePackets.cpp
0c7bec9117ddf6c47cf8bf7f17ebfb6ab1d5fdc3
[]
no_license
weimingtom/mmomm
228d70d9d68834fa2470d2cd0719b9cd60f8dbcd
cab04fcad551f7f68f99fa0b6bb14cec3b962023
refs/heads/master
2021-01-10T02:14:31.896834
2010-03-15T16:15:43
2010-03-15T16:15:43
44,764,408
1
0
null
null
null
null
UTF-8
C++
false
false
1,731
cpp
#include "nativePackets.h" #include "user.h" #include "playerActor.h" #include "serverWorldInstance.h" #include "collisionPackets.h" #include "clientSprites.h" #include "networkServer.h" #include <iostream> void ConnectionPacket::respondServer() const { std::cout << "connected " << sender().username() << std::endl; const ServerWorldInstance::UserMap& users = ServerWorldInstance::current().getUserMap(); PlayerActor* actor = new PlayerActor(sender(), Rect(0.25 + 1.0 * users.size(), 0.0, 0.75 + 1.0 * users.size(), 1.0)); actor->setName(sender().username()); // Tell the user about the new actor; others will get it later CreationUpdate update; update.id = actor->id(); update.offsetRect = actor->getCollisionRect() - actor->getPosition(); update.velocity = actor->getVelocity(); update.sprite = actor->getSpriteType(); update.isClientPlayer = true; update.name = actor->getName(); CreationPacket::CreationList creationList; creationList.push_back(update); CreationPacket::DestructionList destructionList; CreationPacket packet(actor->getPosition(), creationList.begin(), creationList.end(), destructionList.begin(), destructionList.end()); NetworkServer::current().send(packet, sender()); ServerWorldInstance::current().addUser(sender(), actor); } void DisconnectionPacket::respondServer() const { std::cout << "disconnected " << sender().username() << std::endl; delete ServerWorldInstance::current().getUserActor(sender()); ServerWorldInstance::current().removeUser(sender()); } void TamperPacket::respondServer() const { std::cout << "tamper " << sender().username() << std::endl; }
[ "[email protected]", "grandfunkdynasty@191a6260-07ae-11df-8636-19de83dc8dca" ]
[ [ [ 1, 2 ], [ 8, 11 ], [ 14, 14 ], [ 16, 16 ], [ 18, 18 ], [ 21, 25 ], [ 31, 33 ], [ 36, 40 ], [ 43, 48 ], [ 50, 50 ] ], [ [ 3, 7 ], [ 12, 13 ], [ 15, 15 ], [ 17, 17 ], [ 19, 20 ], [ 26, 30 ], [ 34, 35 ], [ 41, 42 ], [ 49, 49 ] ] ]
28f799a49a9c8134b938ba3617763a949edf170c
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/test/src/framework.cpp
10ca10dfead5812257f60e5fff6cf923e77a661c
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,012
cpp
// (C) Copyright Gennadiy Rozental 2005. // 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/test for the library home page. // // File : $RCSfile: framework.cpp,v $ // // Version : $Revision: 1.2 $ // // Description : forwarding source // *************************************************************************** #define BOOST_TEST_SOURCE #include <boost/test/impl/framework.ipp> // *************************************************************************** // Revision History : // // $Log: framework.cpp,v $ // Revision 1.2 2005/03/22 07:18:49 rogeeff // no message // // Revision 1.1 2005/02/20 08:28:34 rogeeff // This a major update for Boost.Test framework. See release docs for complete list of fixes/updates // // *************************************************************************** // EOF
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 30 ] ] ]
fba683c5dbf529d34109541a77785b8d7df8957d
57574cc7192ea8564bd630dbc2a1f1c4806e4e69
/Poker/Servidor/Jugada.h
d492e9a33b47e1ee475e84edecad02d9c01c8bf1
[]
no_license
natlehmann/taller-2010-2c-poker
3c6821faacccd5afa526b36026b2b153a2e471f9
d07384873b3705d1cd37448a65b04b4105060f19
refs/heads/master
2016-09-05T23:43:54.272182
2010-11-17T11:48:00
2010-11-17T11:48:00
32,321,142
0
0
null
null
null
null
UTF-8
C++
false
false
1,570
h
#ifndef _JUGADA_H__ #define _JUGADA_H__ #include <vector> #include <list> #include "CartaModelo.h" using namespace std; class Jugada { private: vector<CartaModelo*> cartas; static const int valorPoker = 7; static const int valorFull = 6; static const int valorColor = 5; static const int valorEscalera = 4; static const int valorPierna = 3; static const int valorParDoble = 2; static const int valorPar = 1; bool escaleraColor; bool poker; bool full; bool color; bool escalera; bool pierna; bool parDoble; bool par; public: static const double valorJugadaPromedio; static const double valorParPromedio; static const double valorParDoblePromedio; Jugada(void); Jugada(vector<CartaModelo*> cartas); virtual ~Jugada(void); vector<CartaModelo*> getCartas() const; void setCartas(vector<CartaModelo*> cartas); void agregarCarta(CartaModelo* carta); void agregarCartas(list<CartaModelo*> cartas); double getValorJugada(); bool isEscaleraColor(); bool isPoker(); bool isFull(); bool isColor(); bool isEscalera(); bool isPierna(); bool isParDoble(); bool isPar(); private: static bool compararCartas(CartaModelo* carta1, CartaModelo* carta2); double calcularValorJugada(int, int=0, int=0, int=0, int=0, int=0); double getPoker(); double getFull(); double getColor(bool& escaleraColor); double getEscalera(vector<CartaModelo*>& cartas); double getPierna(); double getParDoble(); double getPar(); double getCartaMasAlta(); }; #endif //_JUGADA_H__
[ "marianofl85@a9434d28-8610-e991-b0d0-89a272e3a296" ]
[ [ [ 1, 73 ] ] ]
fbff1b06a06fb5a489f163502e6c737fd86d7991
0ce35229d1698224907e00f1fdfb34cfac5db1a2
/ListeLocation.h
80aaff4d39268fa8e4fd01799512eaf318be9e96
[]
no_license
manudss/efreiloca
f7b1089b6ba74ff26e6320044f66f9401ebca21b
54e8c4af1aace11f35846e63880a893e412b3309
refs/heads/master
2020-06-05T17:34:02.234617
2007-06-04T19:12:15
2007-06-04T19:12:15
32,325,713
0
0
null
null
null
null
UTF-8
C++
false
false
833
h
#pragma once #include "stdafx.h" //#include "vehicule.h" #include <hash_map> //#include <vector> #include "Location.h" //#include "Date.h" class ListeLocation { private: ListeLocation(void); ~ListeLocation(void); static ListeLocation* instance; public: static ListeLocation* getinstance(); int chargement(); int ajout(Location* nouvelle_loc); int enregistrement(); int ajout_tab(static int i_loc,Location * loc); void devis (Location * loc); //fct pr interface: Location* returnLocationCour(); void Locationbegin(); void Locationsuiv(); void Locationprec(); int nbrLocation(); private: stdext::hash_map< static int , Location* > tabLocation; stdext::hash_map< static int , Location* >:: iterator hash_iter,iter_cour; typedef pair < static int , Location* > Int_Pair; };
[ "manu.dss@65b228c9-682f-0410-abd1-c3b8cf015911", "pootoonet@65b228c9-682f-0410-abd1-c3b8cf015911" ]
[ [ [ 1, 1 ], [ 9, 18 ], [ 22, 22 ], [ 34, 36 ], [ 38, 39 ] ], [ [ 2, 8 ], [ 19, 21 ], [ 23, 33 ], [ 37, 37 ] ] ]
579e85b13564bf2a47db4a29dac319b1b2c290d8
3fe4cb1c37ed16389f90818b7d07aa5d05bf59e3
/ImageProcessing/ImageProcessing/ImageProcessing.h
7c4b4ee54e73fdbb0bb6721563f5f4c70922ced4
[]
no_license
zinking/advancedimageprocessing
e0fbc1c69810202b89b2510ddaf60561ce0fe806
0c68e11109c0d6299881aecefaf3a85efa8d4471
refs/heads/master
2021-01-21T11:46:53.348948
2008-12-08T06:15:06
2008-12-08T06:15:06
32,132,965
0
0
null
null
null
null
GB18030
C++
false
false
525
h
// ImageProcessing.h : ImageProcessing 应用程序的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件" #endif #include "resource.h" // 主符号 // CDIPApp: // 有关此类的实现,请参阅 ImageProcessing.cpp // class CDIPApp : public CWinApp { public: CDIPApp(); // 重写 public: virtual BOOL InitInstance(); // 实现 afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() }; extern CDIPApp theApp;
[ "zinking3@f9886646-c4e6-11dd-8bad-cde060d8fd3c" ]
[ [ [ 1, 31 ] ] ]
85fa773fafc023c220c1936f8c7c598d8264782a
bef7d0477a5cac485b4b3921a718394d5c2cf700
/testShadows/src/demo/ConeLib.cpp
552bd5259baabf5a6185cb2612e1eb9486bf9a77
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,985
cpp
#include "stdafx.h" // from home.comcast.net/~tom_forsyth/papers/cone_library.cpp #include "ConeLib.h" bool ViewCone::IntersectsSphere( const SVector3& pos, float r ) const { // from www.geometrictools.com/Documentation/IntersectionSphereCone.pdf SVector3 u = -(r * this->invSinAngle) * this->axis; SVector3 d = pos - u; float dsqr = d.lengthSq(); float e = this->axis.dot(d); if( e > 0 && e*e >= dsqr * this->cosAngle * this->cosAngle ) { // pos is inside K'' d = pos; dsqr = d.lengthSq(); e = -this->axis.dot(d); if( e > 0 && e*e >= dsqr * this->sinAngle * this->sinAngle ) { // pos is inside K'' and inside K' return dsqr <= r * r; } // pos inside K'' and outside K' return true; } // center is outside K'' return false; } void ConeMake ( const SVector3 &v1, const SVector3 &v2, ViewCone& out ) { assert ( fabsf ( v1.lengthSq() - 1.0f ) < 0.01f ); assert ( fabsf ( v2.lengthSq() - 1.0f ) < 0.01f ); out.axis = SVector3( v1 + v2 ).getNormalized(); out.cosAngle = v1.dot( out.axis ); out.UpdateAngle(); } void ConeMake ( const SVector3 &vCentre, float fRadius, ViewCone& out ) { float fOneOverLengthSq = 1.0f / vCentre.lengthSq(); float fOneOverLength = sqrtf ( fOneOverLengthSq ); out.axis = vCentre * fOneOverLength; if ( 1.0f <= ( fRadius * fOneOverLength ) ) { // Point is inside the sphere. out.SetInvalidAngle(); return; } #if 0 out.cosAngle = cosf ( asin ( fRadius / fLength ) ); #else // AdjacentLength = sqrt ( fLength * fLength - fRadius * fRadius ) // CosAngle = AdjacentLength / fLength // = sqrt ( fLength * fLength - fRadius * fRadius ) / fLength // = sqrt ( 1.0f - ( fRadius * fRadius ) / ( fLength * fLength ) ) out.cosAngle = sqrtf ( 1.0f - ( fRadius * fRadius ) * fOneOverLengthSq ); assert ( fabsf ( out.cosAngle - cosf ( asinf ( fRadius * fOneOverLength ) ) ) < 0.00001f ); #endif out.UpdateAngle(); } bool ConeIntersect ( const ViewCone &vc1, const ViewCone &vc2 ) { if ( ( vc1.cosAngle < 0.0f ) || ( vc2.cosAngle < 0.0f ) ) { return true; } vc1.Check(); vc2.Check(); // Ugh - lots of acosfs. Can't see a better way to do it. float fThetaTotal = acosf ( vc1.axis.dot( vc2.axis ) ); float fTheta1 = acosf ( vc1.cosAngle ); float fTheta2 = acosf ( vc2.cosAngle ); return ( fTheta1 + fTheta2 > fThetaTotal ); } eConeUnionResult ConeUnion( ViewCone* out, const ViewCone &cone1, const ViewCone &cone2, bool bAlwaysSetResult ) { assert( out != NULL ); const float fVeryCloseEnough = 0.00001f; const float fCloseEnough = 0.001f; // Just check if they share axis. float fOneDotTwo = cone2.axis.dot( cone1.axis ); if ( fOneDotTwo > ( 1.0f - fVeryCloseEnough ) ) { // Yep. OK, the test is really simple - which is bigger? if ( cone1.cosAngle < cone2.cosAngle ) { if( bAlwaysSetResult ) { out->axis = cone1.axis; out->cosAngle = cone1.cosAngle - fVeryCloseEnough; out->UpdateAngle(); } return CUR_1ENCLOSES2; } else { if ( bAlwaysSetResult ) { out->axis = cone2.axis; out->cosAngle = cone2.cosAngle - fVeryCloseEnough; out->UpdateAngle(); } return CUR_2ENCLOSES1; } } else if ( fOneDotTwo < ( -1.0f + fVeryCloseEnough ) ) { // They point in completely opposite directions. if ( bAlwaysSetResult ) { out->SetInvalidAngle(); } return CUR_NOBOUND; } // Find the plane that includes both axis - this is the plane that the final cone axis will lie on as well. SVector3 vPlaneNormal = cone2.axis.cross( cone1.axis ).getNormalized(); // Now for each cone, find the "outer vector", which is the vector along the cone that lies in the plane, // furthest from the other cone's axis. // So define the vector vP = ( axis ^ vPlaneNormal ).norm() // So vP.axis = 0 and vP.vP=1. // Define: // vOuter = axis + lambda * ( ( axis ^ vPlaneNormal ).norm() ) // and also: // ( vOuter * axis ) / vOuter.length() = cosAngle // thus: // lambda = +/- sqrt ( ( 1 - cosAngle^2 ) / ( cosAngle^2 ) ) // // For cone1, use +ve lambda, for cone2, use -ve. SVector3 vP1 = vPlaneNormal.cross(cone1.axis ).getNormalized(); float fCosAngleSquared1 = cone1.cosAngle * cone1.cosAngle; SVector3 vOuter1 = cone1.axis + vP1 * sqrtf ( ( 1.0f - fCosAngleSquared1 ) / fCosAngleSquared1 ); vOuter1 = vOuter1.getNormalized(); SVector3 vP2 = vPlaneNormal.cross( cone2.axis ).getNormalized(); float fCosAngleSquared2 = cone2.cosAngle * cone2.cosAngle; SVector3 vOuter2 = cone2.axis - vP2 * sqrtf ( ( 1.0f - fCosAngleSquared2 ) / fCosAngleSquared2 ); vOuter2 = vOuter2.getNormalized(); // Check to see if either outer vector is actually inside the other cone. // If it is, then that cone completely encloses the other. #ifdef _DEBUG float fDebug1 = vOuter2.dot( cone1.axis ); #endif if ( vOuter2.dot( cone1.axis ) + fVeryCloseEnough >= cone1.cosAngle ) { // Obviously this means cone1 should be the wider one. assert ( cone1.cosAngle <= cone2.cosAngle + fCloseEnough ); // And cone2's axis should be inside it as well. assert ( cone1.axis.dot( cone2.axis ) + fCloseEnough >= cone1.cosAngle ); if ( bAlwaysSetResult ) { *out = cone1; } return CUR_1ENCLOSES2; } #ifdef _DEBUG float fDebug2 = vOuter2.dot( cone1.axis ); #endif if ( vOuter1.dot( cone2.axis ) + fVeryCloseEnough >= cone2.cosAngle ) { // Obviously this means cone1 should be the wider one. assert ( cone2.cosAngle <= cone1.cosAngle + fCloseEnough ); // And cone2's axis should be inside it as well. assert ( cone2.axis.dot( cone1.axis ) + fCloseEnough >= cone2.cosAngle ); if ( bAlwaysSetResult ) { *out = cone2; } return CUR_2ENCLOSES1; } // And if the cross-product of the two points the opposite direction to vPlaneNormal, then the bounding // cone has turned "inside out" and covers an angle more than 180 degrees. if ( vOuter1.cross( vOuter2 ).dot( vPlaneNormal ) >= 0.0f ) { if ( bAlwaysSetResult ) { out->SetInvalidAngle(); } return CUR_NOBOUND; } #ifdef _DEBUG // Taking copies coz presult might be one of the sources. float fCosAngle1 = cone1.cosAngle; float fCosAngle2 = cone2.cosAngle; #endif // And now find the average of those two - that is the centre of the new cone. out->axis = SVector3( vOuter1 + vOuter2 ).getNormalized(); // And the angle. out->cosAngle = out->axis.dot( vOuter1 ); // Of course it shouldn't matter which you use to find the angle. #ifdef _DEBUG float f = out->axis.dot( vOuter2 ); // The smaller cosAngle, the bigger the allowable error. float fAllowedError = ( 1.0f - fabsf ( out->cosAngle ) ) * 0.2f + 0.001f; assert ( fabsf ( out->cosAngle - f ) < fAllowedError ); #endif // And obviously the resulting cone can't be narrower than either of the two sources. // remember that narrower = higher value) assert( out->cosAngle <= fCosAngle1 + fCloseEnough ); assert( out->cosAngle <= fCosAngle2 + fCloseEnough ); out->UpdateAngle(); // All done. return CUR_NORMAL; } bool DoesCone2EncloseCone1( const ViewCone &cone1, const ViewCone &cone2 ) { const float fVeryCloseEnough = 0.00001f; const float fCloseEnough = 0.001f; #ifdef _DEBUG ViewCone debugResCone; eConeUnionResult debugRes = ConeUnion( &debugResCone, cone1, cone2, false ); #endif // Just check if they share axis. float fOneDotTwo = cone2.axis.dot( cone1.axis ); if ( fOneDotTwo > ( 1.0f - fVeryCloseEnough ) ) { // Yep. OK, the test is really simple - which is bigger? if ( cone1.cosAngle < cone2.cosAngle ) { //return CUR_1ENCLOSES2; assert ( debugRes == CUR_1ENCLOSES2 ); return false; } else { //return CUR_2ENCLOSES1; assert ( debugRes == CUR_2ENCLOSES1 ); return true; } } else if ( fOneDotTwo < ( -1.0f + fVeryCloseEnough ) ) { // They point in completely opposite directions. //return CUR_NOBOUND; assert ( debugRes == CUR_NOBOUND ); return false; } // Find the plane that includes both axis - this is the plane that the final cone axis will lie on as well. SVector3 vPlaneNormal = cone2.axis.cross( cone1.axis ).getNormalized(); // Now for each cone, find the "outer vector", which is the vector along the cone that lies in the plane, // furthest from the other cone's axis. // So define the vector vP = ( axis ^ vPlaneNormal ).norm() // So vP.axis = 0 and vP.vP=1. // Define: // vOuter = axis + lambda * ( ( axis ^ vPlaneNormal ).norm() ) // and also: // ( vOuter * axis ) / vOuter.length() = cosAngle // thus: // lambda = +/- sqrt ( ( 1 - cosAngle^2 ) / ( cosAngle^2 ) ) // // For cone1, use +ve lambda, for cone2, use -ve. SVector3 vP1 = vPlaneNormal.cross( cone1.axis ).getNormalized(); float fCosAngleSquared1 = cone1.cosAngle * cone1.cosAngle; SVector3 vOuter1 = cone1.axis + vP1 * sqrtf ( ( 1.0f - fCosAngleSquared1 ) / fCosAngleSquared1 ); vOuter1 = vOuter1.getNormalized(); #ifdef _DEBUG SVector3 vP2 = vPlaneNormal.cross( cone2.axis ).getNormalized(); float fCosAngleSquared2 = cone2.cosAngle * cone2.cosAngle; SVector3 vOuter2 = cone2.axis - vP2 * sqrtf ( ( 1.0f - fCosAngleSquared2 ) / fCosAngleSquared2 ); vOuter2 = vOuter2.getNormalized(); #endif // Check to see if either outer vector is actually inside the other cone. // If it is, then that cone completely encloses the other. #ifdef _DEBUG float fDebug2 = vOuter2.dot( cone1.axis ); #endif if ( vOuter1.dot( cone2.axis ) + fVeryCloseEnough >= cone2.cosAngle ) { // Obviously this means cone1 should be the wider one. assert ( cone2.cosAngle <= cone1.cosAngle + fCloseEnough ); // And cone2's axis should be inside it as well. assert ( cone2.axis.dot( cone1.axis ) + fCloseEnough >= cone2.cosAngle ); //return CUR_2ENCLOSES1; assert ( debugRes == CUR_2ENCLOSES1 ); return true; } #if 0 float fDebug1 = vOuter2.dot( cone1.axis ); if ( vOuter2.dot( cone1.axis ) + fVeryCloseEnough >= cone1.cosAngle ) { // Obviously this means cone1 should be the wider one. assert ( cone1.cosAngle <= cone2.cosAngle + fCloseEnough ); // And cone2's axis should be inside it as well. assert ( cone1.axis.dot( cone2.axis ) + fCloseEnough >= cone1.cosAngle ); //return CUR_1ENCLOSES2; return false; } // And if the cross-product of the two points the opposite direction to vPlaneNormal, then the bounding // cone has turned "inside out" and covers an angle more than 180 degrees. if ( vOuter1.cross( vOuter2 ).dot( vPlaneNormal ) >= 0.0f ) { //return CUR_NOBOUND; return false; } #endif //return CUR_NORMAL; assert ( debugRes != CUR_2ENCLOSES1 ); return false; } float ConeSizeOfTexture ( const ViewCone &vc, float fPixelDensity ) { float fTanTheta = FindTanFromCos ( vc.cosAngle ); return fPixelDensity * fTanTheta; }
[ [ [ 1, 352 ] ] ]
9ebc8fcd8b64bbf3c123cc83d04d4ecff512baa2
8a3fce9fb893696b8e408703b62fa452feec65c5
/GServerEngine/NetLibrary/Network.h
a2870e22fea640e4c7f508cc062b54e716514e07
[]
no_license
win18216001/tpgame
bb4e8b1a2f19b92ecce14a7477ce30a470faecda
d877dd51a924f1d628959c5ab638c34a671b39b2
refs/heads/master
2021-04-12T04:51:47.882699
2011-03-08T10:04:55
2011-03-08T10:04:55
42,728,291
0
2
null
null
null
null
GB18030
C++
false
false
931
h
/* * File : Network.h * Brief : 网络初始化类 * Author: Expter * Creat Date: [2009/11/11] */ #pragma once #include "LibObject.h" #define MAX_CONNECTION 1800 #define KEEPALIVE_TIMER 10000 #define CONNECTIONMANAGER CNetwork::ConnectionManager class CNetwork : public CLibObject { /* * Brief:成员变量,为完成端口的全局句柄 */ static HANDLE hCompletionPort; public: /* * Brief: 网络初始化,调用WSAStartup */ bool NetworkInit(); /* * Brief: 创建完成端口  */ void CreateCompletionPortHandle(); /* * Brief: 返回完成端口句柄  */ static HANDLE GetCompletionHandle() { return hCompletionPort ;} /* * Brief: 绑定连接到完成端口上 */ static bool SetCompletionPort( SOCKET sock , CConnection * pCon); CNetwork(void) { }; virtual ~CNetwork(void) { }; };
[ [ [ 1, 50 ] ] ]
4439325015db2e4d2c308afc95f7fd4791695856
12460a725069d35c4040970da95de11e997d668a
/CodePaint/CPP/CodePaint.cpp
474393911593124791c6f1acbc5c159887c950f7
[]
no_license
lxyppc/lxyppc-codepaint
bae3778d299d197efcb990d24eb4505cc159e4d0
93ac2f3d7484e0e98a70470ab71ebfce2beb18bd
refs/heads/master
2016-09-05T19:50:06.926231
2010-04-08T18:26:06
2010-04-08T18:26:06
32,801,595
0
0
null
null
null
null
UTF-8
C++
false
false
20,367
cpp
#include "StdAfx.h" #include "CodePaint.h" cpColorMap_t cpColorMap; cpColorFormat_t cpColorFormat; vector<cpCodeColor> cpPosStack; vector<cpCodeColor> cpColorStack; struct { char *name; COLORREF color; }colorMap[] = { {"comment", RGB(0,128,0)}, {"string", RGB(200,0,0)}, {"number", RGB(100,0,100)}, {"keyword", RGB(0,0,255)}, {"linenumber", RGB(100,100,0)}, }; struct { char *name; char *set; char *reset; char *startTag; char *endTag; BOOL bNeedReplaceHtml; }colorFormat[] = { {"ouravr", "<font color=#%06X>", "</font>" , "", "", FALSE}, {"21ic", "[color=#%06X]", "[/color]" , "", "", FALSE}, {"pic16", "<FONT color=#%06X>", "</FONT>" , "<DIV class=quote>", "</DIV>", TRUE}, {"replace", "", "" , "", "", 0}, }; static void cpLoadSettingFromIni(); /** Initial color map with default value */ void cpInitialColorMap() { cpLoadSettingFromIni(); //for(int i=0;i<sizeof(colorMap)/sizeof(colorMap[0]);i++){ // cpColorMap[colorMap[i].name] = colorMap[i].color; //} //for(int i=0;i<sizeof(colorFormat)/sizeof(colorFormat[0]);i++){ // cpColorSF sf; // sf.set = colorFormat[i].set; // sf.reset = colorFormat[i].reset; // sf.bNeedReplaceHtml = colorFormat[i].bNeedReplaceHtml; // if(colorFormat[i].startTag){ // sf.startTag = colorFormat[i].startTag; // } // if(colorFormat[i].endTag){ // sf.endTag = colorFormat[i].endTag; // } // cpColorFormat[colorFormat[i].name] = sf; //} } /** Replace or add new color */ void cpSetColor(const string& colorName, COLORREF color) { cpColorMap[colorName] = color; } /** Reset the color stack */ void cpResetColorStack() { cpPosStack.clear(); cpColorStack.clear(); } /** set code color */ void cpSetCodeColor(const string& formatName, const string& colorName, BOOL bNeedTrack) { if(colorName == "string"){ cpBeginString(); } cpColorFormat_t::iterator it = cpColorFormat.find(formatName); if(it == cpColorFormat.end()){ return; } cpColorMap_t::iterator it1 = cpColorMap.find(colorName); if(it1 == cpColorMap.end()){ return; } COLORREF ref = RGB( GetBValue(it1->second), GetGValue(it1->second), GetRValue(it1->second) ); char buf[1024] = ""; sprintf(buf,it->second.set.c_str(),ref); OutputString(buf,0); if(bNeedTrack){ cpCodeColor cpColor; cpColor.color = it1->second; cpColor.start = curPos; cpPosStack.push_back(cpColor); } } void StringLog(const char* str); /** reset code color */ void cpResetCodeColor(const string& formatName, BOOL bNeedTrack) { cpEndString(); cpColorFormat_t::iterator it = cpColorFormat.find(formatName); if(it == cpColorFormat.end()){ return; } char buf[1024] = ""; sprintf(buf,it->second.reset.c_str()); OutputString(buf,0); if(bNeedTrack && cpPosStack.size()){ (cpPosStack.end()-1)->end = curPos; cpColorStack.push_back(*cpPosStack.rbegin()); cpPosStack.pop_back(); } } /** get color stack */ void cpGetColorStack(vector<cpCodeColor>& colorStack) { colorStack.clear(); for(size_t i=0;i<cpColorStack.size();i++){ colorStack.push_back(cpColorStack[cpColorStack.size() - i - 1]); } } void cpGetStyleList(vector<string>& styleList) { styleList.clear(); for(cpColorFormat_t::iterator it = cpColorFormat.begin(); it != cpColorFormat.end(); it++){ styleList.push_back(it->first); } } void cpGetNewline(const string& formatName) { if(formatName == "pic16"){ OutputString("<BR>",0); } } BOOL cpIsNeedReplaceHtml(const string& formatName) { return cpColorFormat[formatName].bNeedReplaceHtml; } string cpStartTag(const string& formatName) { return string(cpColorFormat[formatName].startTag); } string cpEndTag(const string& formatName) { return string(cpColorFormat[formatName].endTag); } char IniName[1024] = ""; #define ArrSize(x) (sizeof(x)/sizeof(x[0])) static void cpWriteDefaultStyle() { GetModuleFileNameA(NULL,IniName,1024); size_t len = strlen(IniName); IniName[len-1] = _T('i'); IniName[len-2] = _T('n'); IniName[len-3] = _T('i'); BOOL res; char tmpStr[256] = ""; itoa(ArrSize(colorFormat),tmpStr,10); res = WritePrivateProfileStringA( "StyleSettings", "Count", tmpStr,IniName ); for(int i=0;i<ArrSize(colorFormat);i++){ char sName[256] = "Setting"; itoa(i,sName+7,10); res = WritePrivateProfileStringA( "StyleSettings", sName, colorFormat[i].name,IniName ); res = WritePrivateProfileStringA( colorFormat[i].name, "ColorSet", colorFormat[i].set,IniName ); res = WritePrivateProfileStringA( colorFormat[i].name, "ColorReset", colorFormat[i].reset,IniName ); res = WritePrivateProfileStringA( colorFormat[i].name, "StartTag", colorFormat[i].startTag,IniName ); res = WritePrivateProfileStringA( colorFormat[i].name, "EndTag", colorFormat[i].endTag,IniName ); res = WritePrivateProfileStringA( colorFormat[i].name, "ReplaceHtmlTag", colorFormat[i].bNeedReplaceHtml ? "1" : "0",IniName ); } } static void cpWriteDefaultColor() { GetModuleFileNameA(NULL,IniName,1024); size_t len = strlen(IniName); IniName[len-1] = _T('i'); IniName[len-2] = _T('n'); IniName[len-3] = _T('i'); BOOL res; char tmpStr[256] = ""; itoa(ArrSize(colorMap),tmpStr,10); res = WritePrivateProfileStringA( "ColorSettings", "Count", tmpStr,IniName ); for(int i=0;i<ArrSize(colorMap);i++){ char sName[256] = "ColorNo"; itoa(i,sName+7,10); res = WritePrivateProfileStringA( "ColorSettings", sName, colorMap[i].name,IniName ); itoa(GetRValue(colorMap[i].color),sName,10); res = WritePrivateProfileStringA( colorMap[i].name, "R", sName,IniName ); itoa(GetGValue(colorMap[i].color),sName,10); res = WritePrivateProfileStringA( colorMap[i].name, "G", sName,IniName ); itoa(GetBValue(colorMap[i].color),sName,10); res = WritePrivateProfileStringA( colorMap[i].name, "B", sName,IniName ); } } static void cpLoadSettingFromIni() { GetModuleFileNameA(NULL,IniName,1024); size_t len = strlen(IniName); IniName[len-1] = _T('i'); IniName[len-2] = _T('n'); IniName[len-3] = _T('i'); FILE* fp = fopen(IniName,"r"); if(fp){ fclose(fp); }else{ /// Write default value to ini file cpWriteDefaultStyle(); cpWriteDefaultColor(); } // Load settings from the ini file BOOL res; char tmpStr[256] = ""; // Load style settings cpColorFormat.clear(); res = GetPrivateProfileStringA( "StyleSettings", "Count", "0",tmpStr,256,IniName ); int tmpCnt = atoi(tmpStr); if(!tmpCnt){ cpWriteDefaultStyle(); res = GetPrivateProfileStringA( "StyleSettings", "Count", "0",tmpStr,256,IniName ); tmpCnt = atoi(tmpStr); } for(int i=0;i<tmpCnt;i++){ char sName[256] = "Setting"; itoa(i,sName+7,10); res = GetPrivateProfileStringA( "StyleSettings", sName, "",tmpStr,256,IniName); if(string(tmpStr) != ""){ cpColorSF sf; res = GetPrivateProfileStringA( tmpStr, "ColorSet", "",sName,256,IniName); sf.set = sName; res = GetPrivateProfileStringA( tmpStr, "ColorReset", "",sName,256,IniName); sf.reset = sName; res = GetPrivateProfileStringA( tmpStr, "StartTag", "",sName,256,IniName); sf.startTag = sName; res = GetPrivateProfileStringA( tmpStr, "EndTag", "",sName,256,IniName); sf.endTag = sName; res = GetPrivateProfileStringA( tmpStr, "ReplaceHtmlTag", "",sName,256,IniName); sf.bNeedReplaceHtml = atoi(sName) ? TRUE : FALSE; cpColorFormat[tmpStr] = sf; } } // Load color settings cpColorMap.clear(); res = GetPrivateProfileStringA( "ColorSettings", "Count", "0",tmpStr,256,IniName ); tmpCnt = atoi(tmpStr); if(!tmpCnt){ cpWriteDefaultColor(); res = GetPrivateProfileStringA( "ColorSettings", "Count", "0",tmpStr,256,IniName ); tmpCnt = atoi(tmpStr); } for(int i=0;i<tmpCnt;i++){ char sName[256] = "ColorNo"; itoa(i,sName+7,10); res = GetPrivateProfileStringA( "ColorSettings", sName, "",tmpStr,256,IniName); if(string(tmpStr) != ""){ int r,g,b; res = GetPrivateProfileStringA( tmpStr, "R", "0",sName,256,IniName); r = atoi(sName); res = GetPrivateProfileStringA( tmpStr, "G", "0",sName,256,IniName); g = atoi(sName); res = GetPrivateProfileStringA( tmpStr, "B", "0",sName,256,IniName); b = atoi(sName); cpColorMap[tmpStr] = RGB(r,g,b); } } //for(int i=0;i<sizeof(colorMap)/sizeof(colorMap[0]);i++){ // cpColorMap[colorMap[i].name] = colorMap[i].color; //} } /** Get UI settings from the ini file */ void cpGetUISetting(cpUISetting& uiSetting) { GetModuleFileNameA(NULL,IniName,1024); size_t len = strlen(IniName); IniName[len-1] = _T('i'); IniName[len-2] = _T('n'); IniName[len-3] = _T('i'); char tmpStr[256] = ""; GetPrivateProfileStringA( "UISettings", "NeedLineNumber", "0",tmpStr,256,IniName); uiSetting.bNeedLineNumber = atoi(tmpStr) ? TRUE:FALSE; GetPrivateProfileStringA( "UISettings", "AutoCopy", "1",tmpStr,256,IniName); uiSetting.bAutoCopy = atoi(tmpStr) ? TRUE:FALSE; GetPrivateProfileStringA( "UISettings", "DefaultStyle", "pic16",tmpStr,256,IniName); uiSetting.defaultStyle = tmpStr; GetPrivateProfileStringA( "UISettings", "Tab2Space", "0",tmpStr,256,IniName); uiSetting.bTab2Space = atoi(tmpStr) ? TRUE:FALSE; GetPrivateProfileStringA( "UISettings", "TabSize", "4",tmpStr,256,IniName); uiSetting.tabSize = atoi(tmpStr); GetPrivateProfileStringA( "UISettings", "Left", "200",tmpStr,256,IniName); uiSetting.windowRect.left = atoi(tmpStr); GetPrivateProfileStringA( "UISettings", "Right", "900",tmpStr,256,IniName); uiSetting.windowRect.right = atoi(tmpStr); GetPrivateProfileStringA( "UISettings", "Top", "200",tmpStr,256,IniName); uiSetting.windowRect.top = atoi(tmpStr); GetPrivateProfileStringA( "UISettings", "Bottom", "600",tmpStr,256,IniName); uiSetting.windowRect.bottom = atoi(tmpStr); int cx = ::GetSystemMetrics(SM_CXSCREEN); int cy = ::GetSystemMetrics(SM_CYSCREEN); if(uiSetting.windowRect.left < 0) goto restore; if(uiSetting.windowRect.top < 0) goto restore; if(uiSetting.windowRect.right >= cx) goto restore; if(uiSetting.windowRect.bottom >= cy) goto restore; return; restore: uiSetting.windowRect.left = 200; uiSetting.windowRect.right = 900; uiSetting.windowRect.top = 200; uiSetting.windowRect.bottom = 600; } /** Save UI settings tp the ini file */ void cpSetUISetting(const cpUISetting& uiSetting) { GetModuleFileNameA(NULL,IniName,1024); size_t len = strlen(IniName); IniName[len-1] = _T('i'); IniName[len-2] = _T('n'); IniName[len-3] = _T('i'); char tmpStr[16] = ""; BOOL res = WritePrivateProfileStringA( "UISettings", "NeedLineNumber", uiSetting.bNeedLineNumber ? "1":"0",IniName ); res = WritePrivateProfileStringA( "UISettings", "AutoCopy", uiSetting.bAutoCopy ? "1":"0",IniName ); res = WritePrivateProfileStringA( "UISettings", "DefaultStyle", uiSetting.defaultStyle.c_str(),IniName ); res = WritePrivateProfileStringA( "UISettings", "Tab2Space", uiSetting.bTab2Space ? "1" : "0",IniName ); itoa(uiSetting.tabSize, tmpStr, 10); res = WritePrivateProfileStringA( "UISettings", "TabSize", tmpStr,IniName ); itoa(uiSetting.windowRect.left, tmpStr, 10); res = WritePrivateProfileStringA( "UISettings", "Left", tmpStr,IniName ); itoa(uiSetting.windowRect.right, tmpStr, 10); res = WritePrivateProfileStringA( "UISettings", "Right", tmpStr,IniName ); itoa(uiSetting.windowRect.top, tmpStr, 10); res = WritePrivateProfileStringA( "UISettings", "Top", tmpStr,IniName ); itoa(uiSetting.windowRect.bottom, tmpStr, 10); res = WritePrivateProfileStringA( "UISettings", "Bottom", tmpStr,IniName ); } #include <list>; using std::list; using std::wstring; using std::vector; static bStringMode = FALSE; static bStringScan = FALSE; static string strBuffer; static string strTotal; static map<wchar_t,int> strTable; static wstring wTotal; static BOOL bEnableReplace = FALSE; static vector<BOOL> needReplaceTable; static size_t needReplaceTableIndex = 0; #define ENCODE_START 0x80 void cpEnableReplace(BOOL bEnable) { bEnableReplace = bEnable; } wstring toWString(const string& str) { int len = ::MultiByteToWideChar(CP_ACP,0,str.c_str(),-1,NULL,0); wchar_t *pStr = new wchar_t[len+1]; ::MultiByteToWideChar(CP_ACP,0,str.c_str(),-1,pStr,len+1); /// InitialDevice(pStr); wstring res(pStr); delete [] pStr; return res; } string toString(const wstring& str) { int len = ::WideCharToMultiByte(CP_ACP,0,str.c_str(),-1,NULL,0,NULL,NULL); char *pStr = new char[len+1]; ::WideCharToMultiByte(CP_ACP,0,str.c_str(),-1,pStr,len+1,NULL,NULL); string res(pStr); delete [] pStr; return res; } void cpStringScanMode(BOOL bScanMode) { if(!bEnableReplace)return; bStringScan = bScanMode; if(!bStringScan){ needReplaceTableIndex = 0; wstring res(toWString(strTotal)); for(size_t i=0;i<res.length();i++){ if(res[i]>127){ strTable[res[i]] = 0; } } map<wchar_t,int>::iterator it = strTable.begin(); wTotal = L""; int i=0; for(;it!=strTable.end();it++){ it->second = i++; wTotal += it->first; } }else{ needReplaceTable.clear(); needReplaceTableIndex = 0; strTable.clear(); strTotal = ""; strBuffer = ""; wTotal = L""; } } void cpBeginString() { if(!bEnableReplace)return; bStringMode = TRUE; strBuffer = ""; if(!bStringScan && needReplaceTable[needReplaceTableIndex]){ OutputString("/*",0); } } void cpEndString() { if(!bEnableReplace)return; if(bStringMode){ bStringMode = FALSE; strTotal+=strBuffer; if(!bStringScan){ // replace the chinese characters string res; if(needReplaceTable[needReplaceTableIndex]){ OutputString("*/",0); wstring curStr(toWString(strBuffer)); for(size_t i=0;i<curStr.length();i++){ if(curStr[i]>127){ char buf[16] = ""; sprintf(buf,"\\x%02X",strTable[curStr[i]]+ENCODE_START); res += buf; }else{ wstring tmp =L"s"; tmp[0] = curStr[i]; res += toString( tmp); } } OutputString(res.c_str(),0); } needReplaceTableIndex++; }else{ wstring curStr(toWString(strBuffer)); BOOL bContainChinese = FALSE; for(size_t i=0;i<curStr.length();i++){ if(curStr[i]>127){ bContainChinese = TRUE; break; } } needReplaceTable.push_back(bContainChinese); } } } void cpGetString(const char* str, int len) { if(!bEnableReplace)return; if(bStringMode){ while(len--){ strBuffer += *str++; } } } void cpStringReplaceOverView() { if(!bEnableReplace)return; if(wTotal.length()){ OutputString("\r\n/** Replaced strings:\r\n ",0); OutputString(toString(wTotal).c_str(),0); OutputString("\r\n\r\nString Lookup Table:\r\n",0); size_t totalLeng = wTotal.length(); size_t index = 0; while(totalLeng){ size_t limit = totalLeng>16 ? 16 : totalLeng; string resStr( " Char: "); string resValue(" Value: "); for(size_t i=0; i<limit; i++){ wchar_t ch[4] = {wTotal[index++],L' ',0}; resStr += toString(ch); char stmp[16]; sprintf(stmp,"%02X ", strTable[ch[0]]+ENCODE_START); resValue += stmp; } OutputString(resStr.c_str(),0); OutputString("\r\n",0); OutputString(resValue.c_str(),0); OutputString("\r\n",0); if(totalLeng > 16){ totalLeng -= 16; }else{ totalLeng = 0; } } //for(size_t i=0;i<wTotal.length();i++){ // char buf[32] = ""; // sprintf(buf,"%02X", strTable[wTotal[i]]+ENCODE_START); // OutputString(buf,0); //} OutputString("*/\r\n",0); } }
[ "lxyppc@e4b13638-01d7-11df-a6f0-ed93ac2c91d0" ]
[ [ [ 1, 699 ] ] ]
b9cc0600be36dc230abe0ac24b104c6914a03d1d
b6bad03a59ec436b60c30fc793bdcf687a21cf31
/som2416/wince5/sdbusreq.cpp
7964317891b9dbbd32706a1800290f03d45b7813
[]
no_license
blackfa1con/openembed
9697f99b12df16b1c5135e962890e8a3935be877
3029d7d8c181449723bb16d0a73ee87f63860864
refs/heads/master
2021-01-10T14:14:39.694809
2010-12-16T03:20:27
2010-12-16T03:20:27
52,422,065
0
0
null
null
null
null
UTF-8
C++
false
false
16,681
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this sample source code is subject to the terms of the Microsoft // license agreement under which you licensed this sample source code. If // you did not accept the terms of the license agreement, you are not // authorized to use this sample source code. For the terms of the license, // please see the license agreement between you and Microsoft or, if applicable, // see the LICENSE.RTF on your install media or the root of your tools installation. // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES. // // /*++ THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Module Name: SDBusReq.cpp Abstract: SDBus Implementation. Notes: --*/ #include <windows.h> #include <bldver.h> //#include <cesdbus.h> //#include <marshal.hpp> #include "../SDDriver_INC/sdhcd.h" #include "sdbus.hpp" #include "sdslot.hpp" #include "sdbusreq.hpp" void * CSDBusRequest::operator new(size_t stSize) { return CSDHostContainer::AllocateBusRequest(stSize); } void CSDBusRequest::operator delete (void *pointer) { CSDHostContainer::FreeBusRequest((CSDBusRequest *)pointer); } DWORD CSDBusRequest::g_dwRequestIndex = 0 ; CSDBusRequest::CSDBusRequest(CSDDevice& sdDevice, SD_BUS_REQUEST& sdBusRequest, HANDLE hCallback, CSDBusRequest * pParentBus ) : m_pParentBus(pParentBus) , m_hCallback(hCallback) , m_sdDevice(sdDevice) { m_lRefCount = 0; m_pAsyncQueueNext = NULL; m_pChildListNext = NULL; m_dwRequestIndex = (SDBUS_REQUEST_INDEX_MASK & (DWORD)InterlockedIncrement((PLONG)&g_dwRequestIndex)); ListEntry.Flink = NULL; ListEntry.Blink = NULL; hDevice = (m_sdDevice.GetDeviceHandle()).hValue; SystemFlags = sdBusRequest.SystemFlags; TransferClass = sdBusRequest.TransferClass; CommandCode = sdBusRequest.CommandCode; CommandArgument = sdBusRequest.CommandArgument; CommandResponse.ResponseType = sdBusRequest.CommandResponse.ResponseType; RequestParam = sdBusRequest.RequestParam; NumBlocks = sdBusRequest.NumBlocks; BlockSize = sdBusRequest.BlockSize; HCParam = 0; pBlockBuffer = NULL ; pCallback = sdBusRequest.pCallback; DataAccessClocks = 0; // reset data access clocks Flags = sdBusRequest.Flags ; // get the current thread permissions for the block buffer CurrentPermissions = GetCurrentPermissions(); Status = SD_API_STATUS_PENDING ; m_pOrinalAddr = sdBusRequest.pBlockBuffer; if (m_pParentBus) m_pParentBus->AddRef(); m_dwArguDesc = 0 ; m_fCompleted = FALSE; m_ExternalHandle = NULL; } CSDBusRequest::~CSDBusRequest() { TerminateLink(); /* For Windows CE 6.0 if (m_pOrinalAddr && pBlockBuffer && m_pOrinalAddr != pBlockBuffer) { HRESULT hResult= CeFreeAsynchronousBuffer(pBlockBuffer,m_pOrinalAddr, NumBlocks*BlockSize, m_dwArguDesc) ; ASSERT(SUCCEEDED(hResult)); } */ } BOOL CSDBusRequest::Init() { BOOL fRet = TRUE; if( TransferClass == SD_READ || TransferClass == SD_WRITE ) { if( NumBlocks == 0 ) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDBusRequest: SDBusRequest- No transfer buffers passed \n"))); Status = SD_API_STATUS_INVALID_PARAMETER; fRet = FALSE; } else if( m_pOrinalAddr == NULL ) { // check pointer to see if block array ptr is non-NULL DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDBusRequest: SDBusRequest- NULL buffer pointer passed \n"))); Status = SD_API_STATUS_INVALID_PARAMETER; fRet = FALSE; } /* For Windows CE 6.0 else if ( m_pOrinalAddr && NumBlocks && BlockSize && m_hCallback ) { // External call m_dwArguDesc = (TransferClass == SD_READ?ARG_O_PTR:ARG_I_PTR); if (NumBlocks>=(1<<16) || BlockSize>=(1<<16) || !SUCCEEDED(CeAllocAsynchronousBuffer((PVOID *)&pBlockBuffer,m_pOrinalAddr,NumBlocks*BlockSize,m_dwArguDesc))) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDBusRequest__X CeAllocAsynchronousBuffer Error (%d)\r\n"),GetLastError())); ASSERT(FALSE); Status = SD_API_STATUS_ACCESS_VIOLATION; pBlockBuffer = NULL ; fRet = FALSE; } }*/ else { pBlockBuffer = (PUCHAR) m_pOrinalAddr ; } } if (fRet) { if ((Device_SD_Memory == m_sdDevice.GetDeviceType()) || (Device_MMC == m_sdDevice.GetDeviceType())) { if (TransferClass == SD_READ) { // set for read DataAccessClocks = m_sdDevice.GetCardInfo().SDMMCInformation.DataAccessReadClocks; } else if (TransferClass == SD_WRITE) { // set write DataAccessClocks = m_sdDevice.GetCardInfo().SDMMCInformation.DataAccessWriteClocks; } } SystemFlags &= ~SYSTEM_FLAGS_RETRY_COUNT_MASK; SystemFlags |= (CSDHostContainer::GetRetryCount() & SYSTEM_FLAGS_RETRY_COUNT_MASK); SystemFlags |= ((Flags & SD_SLOTRESET_REQUEST)!=0?SD_BUS_REQUEST_SLOT_RESET:0); if (m_pParentBus == NULL) { // This is paranet UCHAR ucSDIOFlags = m_sdDevice.GetCardInfo().SDIOInformation.Flags; if ((( 1 < NumBlocks ) && ((SD_CMD_IO_RW_EXTENDED == CommandCode) && (((SD_READ == TransferClass) && (0 != (ucSDIOFlags & (SFTBLK_USE_FOR_CMD53_READ | SFTBLK_USE_ALWAYS )))) || ((SD_WRITE == TransferClass ) && (0 != (ucSDIOFlags & (SFTBLK_USE_FOR_CMD53_WRITE | SFTBLK_USE_ALWAYS ))))))) || ((SD_CMD_READ_MULTIPLE_BLOCK == CommandCode) && (0 != (ucSDIOFlags & (SFTBLK_USE_FOR_CMD18 | SFTBLK_USE_ALWAYS )))) || ((SD_CMD_WRITE_MULTIPLE_BLOCK == CommandCode) && (0 != (ucSDIOFlags & (SFTBLK_USE_FOR_CMD25 | SFTBLK_USE_ALWAYS ))))) { fRet = BuildSoftBlock(); } if (((SD_CMD_READ_MULTIPLE_BLOCK != CommandCode) || (0 == (ucSDIOFlags & (SFTBLK_USE_FOR_CMD18 | SFTBLK_USE_ALWAYS)))) && ((SD_CMD_WRITE_MULTIPLE_BLOCK != CommandCode) || (0 == (ucSDIOFlags & (SFTBLK_USE_FOR_CMD25 | SFTBLK_USE_ALWAYS )))) && (0 == (ucSDIOFlags & SFTBLK_USE_ALWAYS))) { // check for optional request fRet = BuildOptionalRequest( ucSDIOFlags ); } } } ASSERT(fRet); if (!fRet) m_fCompleted = TRUE; return fRet; } BOOL CSDBusRequest::CheckForCompletion() { if (m_pParentBus!=NULL) { return m_pParentBus->CheckForCompletion(); } else if (IsComplete()) { // This one is completed. if (SD_API_SUCCESS(Status) && m_pChildListNext!=NULL) { Status = m_pChildListNext->GetFirstFailedStatus(); } #ifdef DEBUG SD_CARD_STATUS cardStatus; if (SDBUS_ZONE_REQUEST) { DEBUGMSG(SDBUS_ZONE_REQUEST, (TEXT("--- SDBusDriver: CMD%d CMDArg: 0x%08X TransferClass:%d ResponseType: %s Complete\n"), CommandCode, CommandArgument,TransferClass, SDCardResponseTypeLookUp[CommandResponse.ResponseType & 0x7])); if (SD_API_SUCCESS(Status)) { if ( (ResponseR1 == CommandResponse.ResponseType) || (ResponseR1b == CommandResponse.ResponseType)) { SDGetCardStatusFromResponse(&CommandResponse, &cardStatus); DEBUGMSG(SDBUS_ZONE_REQUEST, (TEXT("--- SDBusDriver: R1,R1b Response, Card Status: 0x%08X, Last State: %s \n"), cardStatus, SDCardStateStringLookUp[((CommandResponse.ResponseBuffer[2] >> 1) & 0x0F)])); } if (NoResponse != CommandResponse.ResponseType) { DEBUGMSG(SDBUS_ZONE_REQUEST, (TEXT("--- SDBusDriver: Response Dump: \n"))); if (ResponseR2 == CommandResponse.ResponseType) { SDOutputBuffer(CommandResponse.ResponseBuffer, 17); } else { SDOutputBuffer(CommandResponse.ResponseBuffer, 6); } } if (NULL != pBlockBuffer) { if (SD_READ == TransferClass) { DEBUGMSG(SDBUS_ZONE_REQUEST, (TEXT("--- SDBusDriver: Read Data Transfered : NumBlocks:%d BytesPerBlock:%d \n"), NumBlocks, BlockSize)); if (SDBUS_ZONE_BUFFER) { DEBUGMSG(SDBUS_ZONE_BUFFER, (TEXT("--- SDBusDriver: Read Data Dump: \n"))); SDOutputBuffer(pBlockBuffer, NumBlocks * BlockSize); } } else { DEBUGMSG(SDBUS_ZONE_REQUEST, (TEXT("--- SDBusDriver: Write Transfer Complete: NumBlocks:%d BytesPerBlock:%d\n"), NumBlocks, BlockSize)); } } } } #endif PSD_BUS_REQUEST_CALLBACK pCallbackPtr = (PSD_BUS_REQUEST_CALLBACK)InterlockedExchange( (LPLONG)&pCallback, NULL); // Make sure only call once. if (pCallbackPtr) { __try { /* For Windows CE 6.0 if (m_hCallback) { IO_BUS_SD_REQUEST_CALLBACK busSdRequestCallback = { pCallbackPtr, m_sdDevice.GetDeviceHandle().hValue,m_ExternalHandle, m_sdDevice.GetDeviceContext(), RequestParam }; CeDriverPerformCallback( m_hCallback, IOCTL_BUS_SD_REQUEST_CALLBACK,&busSdRequestCallback,sizeof(busSdRequestCallback), NULL,0,NULL,NULL); } else */ { pCallbackPtr(m_sdDevice.GetDeviceHandle().hValue, // device handle (PSD_BUS_REQUEST)m_ExternalHandle, // the request m_sdDevice.GetDeviceContext(), // device context RequestParam); // request argument } } __except (SDProcessException(GetExceptionInformation())) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("--- SDBusDriver: Exception caught in CompleteRequest when calling callback in device %s \n"), m_sdDevice.GetClientName())); } } } return TRUE; } BOOL CSDBusRequest::IsRequestNeedRetry() { if ((m_sdDevice.GetClientFlags() & SD_CLIENT_HANDLES_RETRY)==0) { // we need retry. if (((SD_API_STATUS_RESPONSE_TIMEOUT == Status) || (SD_API_STATUS_DATA_TIMEOUT == Status) || (SD_API_STATUS_CRC_ERROR == Status)) && GetRetryCount()!=0) { return TRUE; } } return FALSE; } BOOL CSDBusRequest::BuildSoftBlock() { ASSERT(m_pParentBus == NULL); ASSERT(NumBlocks>1); ASSERT(pBlockBuffer!=NULL); BOOL fRetun = TRUE; UCHAR SoftBlockCommand = CommandCode; DWORD SoftBlockArgument ; DWORD SoftwareBlockByteCount = NumBlocks * BlockSize; DWORD SoftBlockLengthInBytes = min (BlockSize, 1 + SD_CMD53_BLOCK_COUNT); PBYTE pSoftBlockBuffer = pBlockBuffer; BOOL fIncreasAddr ; // Setup Current Transfer DWORD dwCurOffset = 0 ; if ( SD_CMD_IO_RW_EXTENDED == SoftBlockCommand ) { SoftBlockArgument = (CommandArgument & ~( SD_CMD53_BLOCK_MODE | SD_CMD53_BLOCK_COUNT )) ; SoftBlockArgument |= SoftBlockLengthInBytes ; fIncreasAddr = ((CommandArgument & SD_CMD53_OPCODE) != 0); CommandCode = SoftBlockCommand ; } else { // Set the appropriate command. SoftBlockArgument = CommandArgument; fIncreasAddr = TRUE; CommandCode -= 1; } // Turn this request into a byte mode request. NumBlocks = 1; BlockSize = SoftBlockLengthInBytes; CommandArgument = SoftBlockArgument ; pBlockBuffer = pSoftBlockBuffer; // Update. if (SoftwareBlockByteCount > SoftBlockLengthInBytes) SoftwareBlockByteCount -= SoftBlockLengthInBytes; else SoftwareBlockByteCount = 0; pSoftBlockBuffer += SoftBlockLengthInBytes; if (fIncreasAddr) { // Increasing address being used. if ( SD_CMD_IO_RW_EXTENDED == SoftBlockCommand ) { SoftBlockArgument = ( SoftBlockArgument & ( ~ SD_CMD53_REGISTER_ADDRESS )) | ((SoftBlockArgument + (SoftBlockLengthInBytes << SD_CMD53_REGISTER_ADDRESS_POS )) & SD_CMD53_REGISTER_ADDRESS ); } else { SoftBlockArgument += SoftBlockLengthInBytes; } } while (SoftwareBlockByteCount && fRetun ) { SD_BUS_REQUEST sdRequest = { {NULL},m_sdDevice.GetDeviceHandle().hValue,0, TransferClass,SoftBlockCommand, SoftBlockArgument, {CommandResponse.ResponseType,{0}}, NULL, SD_API_STATUS_UNSUCCESSFUL, 1,SoftBlockLengthInBytes,0, pBlockBuffer,NULL, 0, Flags }; CSDBusRequest * pNewRequest = new CSDBusRequest(m_sdDevice, sdRequest, NULL, this ); if (pNewRequest && pNewRequest->Init() ) { // Added to Child List. pNewRequest->AddRef(); SetChildListNext(pNewRequest); // Update. if (SoftwareBlockByteCount > SoftBlockLengthInBytes) SoftwareBlockByteCount -= SoftBlockLengthInBytes; else SoftwareBlockByteCount = 0; pSoftBlockBuffer += SoftBlockLengthInBytes; if (fIncreasAddr) { // Increasing address being used. if ( SD_CMD_IO_RW_EXTENDED == SoftBlockCommand ) { SoftBlockArgument = ( SoftBlockArgument & ( ~ SD_CMD53_REGISTER_ADDRESS )) | ((SoftBlockArgument + (SoftBlockLengthInBytes << SD_CMD53_REGISTER_ADDRESS_POS )) & SD_CMD53_REGISTER_ADDRESS ); } else { SoftBlockArgument += SoftBlockLengthInBytes; } } } else { fRetun = FALSE; if (pNewRequest!=NULL) delete pNewRequest; } } return fRetun; } BOOL CSDBusRequest::BuildOptionalRequest( UCHAR ucSDIOFlags ) { BOOL fReturn = TRUE; if (Flags & (SD_AUTO_ISSUE_CMD12 | SD_SDIO_AUTO_IO_ABORT)) { SD_BUS_REQUEST sdRequest = { // for SD_AUTO_ISSUE_CMD12 {NULL},m_sdDevice.GetDeviceHandle().hValue,0, SD_COMMAND, SD_CMD_STOP_TRANSMISSION, 0 ,{ResponseR1b,{0}}, NULL, SD_API_STATUS_UNSUCCESSFUL, 0,0,0, NULL,NULL, 0, 0 }; if (Flags & SD_SDIO_AUTO_IO_ABORT) { DEBUGCHK( m_sdDevice.GetCardInfo().SDIOInformation.Function != 0); // CMD52 sdRequest.CommandCode = SD_IO_RW_DIRECT; // set up argument to write the function number to the I/O abort register sdRequest.CommandArgument = BUILD_IO_RW_DIRECT_ARG(SD_IO_OP_WRITE, SD_IO_RW_NORMAL, 0, // must be function 0 for access to common regs SD_IO_REG_IO_ABORT, m_sdDevice.GetCardInfo().SDIOInformation.Function); sdRequest.CommandResponse.ResponseType = ResponseR5; } CSDBusRequest * pNewRequest = new CSDBusRequest(m_sdDevice, sdRequest, NULL, this ); if (pNewRequest && pNewRequest->Init() ) { // Added to Child List. pNewRequest->AddRef(); SetChildListNext(pNewRequest); } else { fReturn = FALSE; if (pNewRequest) delete pNewRequest; } } return fReturn; }
[ [ [ 1, 405 ] ] ]
de62d04844b1366b5f88f8d0cb7bad63dc7474eb
48ea48679af39ea42a18b0f84523e857d07b8874
/itkCorrespondences/itkMeshASCIIWriter.h
dd87e7224b9957f71307882007b242992f2df6d3
[]
no_license
midas-journal/midas-journal-111
4fb4a579d62676063a0e0fabe5e14893b4e1710d
68d084ceff62b3ff745fc0f7b07fdc9212f7e613
refs/heads/master
2020-05-09T23:03:13.970993
2011-12-12T20:59:01
2011-12-12T20:59:01
2,967,366
2
4
null
null
null
null
UTF-8
C++
false
false
2,869
h
#ifndef MESHASCIIWRITER_H_HEADER_INCLUDED #define MESHASCIIWRITER_H_HEADER_INCLUDED #include "itkMeshFileWriter.h" namespace itk { /** \class MeshASCIIWriter * \brief Stores a mesh in ASCII format. * * The file format is described in the documentation for the * itk::MeshASCIIReader class. Currently, only triangular faces are stored. * Use SetFilePrefix() to specify the filename, which will be extended with * the pts- and fce-extensions. * * \author Tobias Heimann. Division Medical and Biological Informatics, * German Cancer Research Center, Heidelberg, Germany. */ template <class TMeshType> class MeshASCIIWriter : public MeshFileWriter<TMeshType> { public: typedef MeshASCIIWriter<TMeshType> Self; typedef MeshFileWriter<TMeshType> Superclass; typedef SmartPointer < Self > Pointer; typedef SmartPointer < const Self > ConstPointer; itkTypeMacro( MeshASCIIWriter<TMeshType>, MeshFileWriter<TMeshType> ); itkNewMacro( Self ); virtual void GenerateData() { if (strlen( this->m_filePrefix ) == 0) { itkExceptionMacro(<<"GenerateData:Please specify a file prefix!"); return; } FILE *file; char fileName[1024]; typedef typename TMeshType::CellsContainer::ConstIterator CellIterator; typedef typename TMeshType::CellType CellType; typename TMeshType::Pointer mesh = dynamic_cast<TMeshType*> (this->GetInput()); // write triangle indices: sprintf( fileName, "%s.fce", this->m_filePrefix ); file = fopen( fileName, "w" ); if (file) { CellIterator cellIterator = mesh->GetCells()->Begin(); CellIterator cellEnd = mesh->GetCells()->End(); typename TMeshType::CellIdentifier cId = 0; while( cellIterator != cellEnd ) { CellType *cell = cellIterator.Value(); if (cell->GetType() == CellType::TRIANGLE_CELL) { typename CellType::PointIdConstIterator pntId = cell->GetPointIds(); fprintf( file, "%u %u %u\n", (unsigned int)pntId[0], (unsigned int)pntId[1], (unsigned int)pntId[2] ); } cId++; cellIterator++; } fclose( file ); } // write point coordinates: sprintf( fileName, "%s.pts", this->m_filePrefix ); file = fopen( fileName, "w" ); if (file) { typename TMeshType::PointType meshPoint; for (int v=0; v < mesh->GetNumberOfPoints(); v++) { mesh->GetPoint( v, &meshPoint ); fprintf( file, "%f %f %f\n", meshPoint[0], meshPoint[1], meshPoint[2] ); } fclose( file ); } } protected: MeshASCIIWriter() {}; virtual ~MeshASCIIWriter() {}; }; } // namespace itk #endif /* MESHASCIIWRITER_H_HEADER_INCLUDED */
[ [ [ 1, 84 ] ] ]
23693f0cf1c316d59f2872fd9d378ed0a65c0ea1
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/libs/opmapcontrol/src/core/pureimagecache.h
510d4aa2a80577b30a78c04c8e132957b3d7ad61
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,200
h
/** ****************************************************************************** * * @file pureimagecache.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @brief * @see The GNU Public License (GPL) Version 3 * @defgroup OPMapWidget * @{ * *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef PUREIMAGECACHE_H #define PUREIMAGECACHE_H #include <QtSql/QSqlDatabase> #include <QString> #include <QDir> #include <QDebug> #include <QFileInfo> #include <QtSql/QSqlQuery> #include <QtSql/QSqlError> #include <QBuffer> #include "maptype.h" #include "point.h" #include <QVariant> #include "pureimage.h" #include <QList> #include <QMutex> namespace core { class PureImageCache { public: PureImageCache(); static bool CreateEmptyDB(const QString &file); bool PutImageToCache(const QByteArray &tile,const MapType::Types &type,const core::Point &pos, const int &zoom); QByteArray GetImageFromCache(MapType::Types type, core::Point pos, int zoom); QString GtileCache(); void setGtileCache(const QString &value); static bool ExportMapDataToDB(QString sourceFile, QString destFile); void deleteOlderTiles(int const& days); private: QString gtilecache; QMutex Mcounter; static qlonglong ConnCounter; }; } #endif // PUREIMAGECACHE_H
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 66 ] ] ]
30bd0fd47d036cc403603355ca800e0c05eea81e
515e917815568d213e75bfcbd3fb9f0e08cf2677
/tengine/game/game.cpp
4d6a671441ea85df404b3b9cf120e2f0e9ec8830
[ "BSD-2-Clause" ]
permissive
dfk789/CodenameInfinite
bd183aec6b9e60e20dda6764d99f4e8d8a945add
aeb88b954b65f6beca3fb221fe49459b75e7c15f
refs/heads/master
2020-05-30T15:46:20.450963
2011-10-15T00:21:38
2011-10-15T00:21:38
5,652,791
2
0
null
null
null
null
UTF-8
C++
false
false
4,521
cpp
#include "game.h" #include <strutils.h> #include <renderer/renderer.h> #include <renderer/particles.h> #include <renderer/dissolver.h> #include <sound/sound.h> #include <network/network.h> #include <tinker/application.h> #include <tinker/cvar.h> #include "camera.h" REGISTER_ENTITY(CGame); NETVAR_TABLE_BEGIN(CGame); NETVAR_DEFINE_CALLBACK(CEntityHandle<CPlayer>, m_ahPlayers, &CGame::ClearLocalPlayers); NETVAR_TABLE_END(); SAVEDATA_TABLE_BEGIN(CGame); SAVEDATA_DEFINE(CSaveData::DATA_NETVAR, CEntityHandle<CPlayer>, m_ahPlayers); SAVEDATA_DEFINE(CSaveData::DATA_OMIT, CEntityHandle<CPlayer>, m_ahLocalPlayers); // Detected on the fly. SAVEDATA_TABLE_END(); INPUTS_TABLE_BEGIN(CGame); INPUTS_TABLE_END(); CVar game_level("game_level", ""); CGame::CGame() { } CGame::~CGame() { for (size_t i = 0; i < m_ahPlayers.size(); i++) m_ahPlayers[i]->Delete(); } void CGame::Spawn() { BaseClass::Spawn(); RegisterNetworkFunctions(); } void CGame::RegisterNetworkFunctions() { } void CGame::OnClientConnect(int iClient) { } void CGame::OnClientEnterGame(int iClient) { } void CGame::OnClientDisconnect(int iClient) { for (size_t i = 0; i < m_ahPlayers.size(); i++) { if (m_ahPlayers[i]->GetClient() == iClient) { m_ahPlayers[i]->SetClient(NETWORK_BOT); return; } } TAssert(!"Couldn't find the guy who just quit!"); } void CGame::EnterGame() { } void CGame::AddPlayer(CPlayer* pPlayer) { if (!pPlayer) return; // Prevent dupes for (size_t i = 0; i < m_ahPlayers.size(); i++) { if (pPlayer == m_ahPlayers[i]) return; } m_ahPlayers.push_back(pPlayer); m_ahLocalPlayers.clear(); } void CGame::RemovePlayer(CPlayer* pPlayer) { if (!pPlayer) return; for (size_t i = 0; i < m_ahPlayers.size(); i++) { if (pPlayer == m_ahPlayers[i]) { m_ahPlayers.erase(i); break; } } m_ahLocalPlayers.clear(); } void CGame::OnDeleted() { m_ahLocalPlayers.clear(); } void CGame::OnDeleted(CBaseEntity* pEntity) { RemovePlayer(dynamic_cast<CPlayer*>(pEntity)); } bool CGame::TraceLine(const TVector& s1, const TVector& s2, TVector& vecHit, TVector& vecNormal, CBaseEntity** pHit) { TVector vecClosest = s2; bool bHit = false; size_t iMaxEntities = GameServer()->GetMaxEntities(); for (size_t i = 0; i < iMaxEntities; i++) { CBaseEntity* pEntity = CBaseEntity::GetEntity(i); if (!pEntity) continue; if (!pEntity->ShouldCollide()) continue; TVector vecPoint, vecCollideNormal; if (pEntity->Collide(s1, s2, vecPoint, vecCollideNormal)) { if (!bHit || (vecPoint - s1).LengthSqr() < (vecClosest - s1).LengthSqr()) { vecClosest = vecPoint; vecNormal = vecCollideNormal; bHit = true; if (pHit) *pHit = pEntity; } } } if (bHit) vecHit = vecClosest; return bHit; } CPlayer* CGame::GetPlayer(size_t i) const { if (i >= m_ahPlayers.size()) return NULL; return m_ahPlayers[i]; } bool CGame::IsTeamControlledByMe(const CTeam* pTeam) { if (!pTeam) return false; if (!pTeam->IsPlayerControlled()) return false; for (size_t i = 0; i < GetNumLocalPlayers(); i++) { if (GetLocalPlayer(i)->GetTeam() == pTeam) return true; } return false; } const eastl::vector<CEntityHandle<CPlayer> >& CGame::GetLocalPlayers() { if (m_ahLocalPlayers.size() == 0) { CGameServer* pGameServer = GameServer(); for (size_t i = 0; i < m_ahPlayers.size(); i++) { if (!m_ahPlayers[i]) continue; if (m_ahPlayers[i]->GetClient() == pGameServer->GetClientIndex()) m_ahLocalPlayers.push_back(m_ahPlayers[i]); } } return m_ahLocalPlayers; } size_t CGame::GetNumLocalPlayers() { if (m_ahLocalPlayers.size() == 0) GetLocalPlayers(); return m_ahLocalPlayers.size(); } CPlayer* CGame::GetLocalPlayer(size_t i) { if (m_ahLocalPlayers.size() == 0) GetLocalPlayers(); return m_ahLocalPlayers[i]; } CPlayer* CGame::GetLocalPlayer() { if (m_ahLocalPlayers.size() == 0) GetLocalPlayers(); TAssert(m_ahLocalPlayers.size() == 1); if (!m_ahLocalPlayers.size()) return NULL; return m_ahLocalPlayers[0]; } void CGame::ClearLocalPlayers(CNetworkedVariableBase* pVariable) { CGame* pGame = Game(); if (!pGame) return; pGame->m_ahLocalPlayers.clear(); } CVar cheats("cheats", "off"); bool CGame::AllowCheats() { return cheats.GetBool(); }
[ [ [ 1, 17 ], [ 19, 21 ], [ 24, 25 ], [ 29, 36 ], [ 39, 51 ], [ 53, 55 ], [ 57, 57 ], [ 59, 59 ], [ 67, 70 ], [ 72, 73 ], [ 79, 79 ], [ 81, 83 ], [ 85, 85 ], [ 87, 89 ], [ 92, 93 ], [ 95, 95 ], [ 97, 98 ], [ 100, 100 ], [ 102, 102 ], [ 105, 106 ], [ 109, 112 ], [ 114, 117 ], [ 119, 120 ], [ 122, 122 ], [ 124, 132 ], [ 134, 135 ], [ 138, 141 ], [ 143, 155 ], [ 165, 168 ], [ 177, 180 ], [ 182, 182 ], [ 184, 185 ], [ 187, 187 ], [ 193, 195 ], [ 197, 198 ], [ 200, 200 ], [ 203, 203 ], [ 205, 206 ], [ 208, 208 ], [ 224, 224 ], [ 226, 227 ], [ 237, 242 ] ], [ [ 18, 18 ], [ 22, 23 ], [ 26, 28 ], [ 37, 38 ], [ 52, 52 ], [ 56, 56 ], [ 58, 58 ], [ 60, 66 ], [ 71, 71 ], [ 74, 78 ], [ 80, 80 ], [ 84, 84 ], [ 86, 86 ], [ 90, 91 ], [ 94, 94 ], [ 96, 96 ], [ 99, 99 ], [ 101, 101 ], [ 103, 104 ], [ 107, 108 ], [ 113, 113 ], [ 118, 118 ], [ 121, 121 ], [ 123, 123 ], [ 133, 133 ], [ 136, 137 ], [ 142, 142 ], [ 156, 164 ], [ 169, 176 ], [ 181, 181 ], [ 183, 183 ], [ 186, 186 ], [ 188, 192 ], [ 196, 196 ], [ 199, 199 ], [ 201, 202 ], [ 204, 204 ], [ 207, 207 ], [ 209, 223 ], [ 225, 225 ], [ 228, 236 ] ] ]
5703db53a433fab28312c6422bf8aa8233f5f86d
ee8e91d176cea32da4af9ad3f78340ce85b70de6
/childlist.h
05ea99c2b23d9192484349e816681e19de82e42f
[]
no_license
Divendo/cpp-xml-parser
71e50595495cc446124e37bc67a1f1f84281a5b5
0d593fb38312aba369d1f780660c7395c0f581c5
refs/heads/master
2021-03-12T21:47:14.489177
2011-12-30T13:53:20
2011-12-30T13:53:20
32,393,447
0
0
null
null
null
null
UTF-8
C++
false
false
4,680
h
/*************************** GPLv3 License ***************************** <xmlParser> is an opensource easy-to-use xml parser Copyright (C) 2011 Divendo This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************/ #ifndef CHILDRENLIST_H #define CHILDRENLIST_H #include <list> #include <string> namespace xml { // Forward declaration for the element class class element; // For the list class childList : private std::list<element> { public: // Make the element class a friend, so it can access the private members of this class friend class element; // Make the types visible typedef std::list<element>::iterator iterator; typedef std::list<element>::const_iterator const_iterator; typedef std::list<element>::reverse_iterator reverse_iterator; typedef std::list<element>::const_reverse_iterator const_reverse_iterator; // Make some members from std::list<element> public iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const; reverse_iterator rbegin(); const_reverse_iterator rbegin() const; reverse_iterator rend(); const_reverse_iterator rend() const; bool empty() const; size_type size() const; element& front(); const element& front() const; element& back(); const element& back() const; void clear(); // Append a child with the given name and body // The appended child will be returned element* append(const std::string& childName, const std::string& childBody = ""); element* append(const element& child); // Remove all direct children with the given name, returns the number of removed children int remove(const std::string& childName); // Remove all (direct and indirect) children with the given name, returns the number of removed children int removeAll(const std::string& childName); // Remove the child pointed by the iterator, returns an iterator pointing to the new location of the element that followed the removed element iterator remove(const iterator& it); // Remove the children in the range [first, last), returns an iterator pointing to the new location of the element that followed the last removed element iterator remove(const iterator& first, const iterator& last); // Get all direct children with the given name std::list<element*> getByName(const std::string& childName); std::list<const element*> getByName(const std::string& childName) const; // Get all (direct and indirect) children with the given name std::list<element*> getAllByName(const std::string& childName); std::list<const element*> getAllByName(const std::string& childName) const; // Get the first direct child with the given name, returns 0 if there wasn't a child with the given name element* getFirstByName(const std::string& childName); const element* getFirstByName(const std::string& childName) const; // Get the first of all (direct and indirect) children with the given name, returns 0 if there wasn't a child with the given name element* getFirstOfAllByName(const std::string& childName); const element* getFirstOfAllByName(const std::string& childName) const; private: // Constructor, private because only an element may create an instance of this class childList(element* eleParent); // The parent element, this is the parent of all of the elements in this list element* elementParent; }; } // namespace xml #endif // CHILDRENLIST_H
[ "[email protected]@f82f194e-4714-024a-272f-5c5caabae347" ]
[ [ [ 1, 106 ] ] ]
e0c092b66a73b73fdedeb7d47d58d835954229a8
a84b013cd995870071589cefe0ab060ff3105f35
/webdriver/branches/iphone/jobbie/src/cpp/InternetExplorerDriver/IEThreadElement.cpp
94c2c4212a320ceb4cd7eaeabdb686aedfc8d6c1
[ "Apache-2.0" ]
permissive
vdt/selenium
137bcad58b7184690b8785859d77da0cd9f745a0
30e5e122b068aadf31bcd010d00a58afd8075217
refs/heads/master
2020-12-27T21:35:06.461381
2009-08-18T15:56:32
2009-08-18T15:56:32
13,650,409
1
0
null
null
null
null
UTF-8
C++
false
false
32,002
cpp
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. 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. */ // IEThread.cpp : implementation file // #include "stdafx.h" #include <ctime> #include <cctype> #include <algorithm> #include "IEThread.h" #include "interactions.h" #include "utils.h" #include "EventReleaser.h" using namespace std; const LPCTSTR ie7WindowNames[] = { _T("TabWindowClass"), _T("Shell DocObject View"), _T("Internet Explorer_Server"), NULL }; const LPCTSTR ie6WindowNames[] = { _T("Shell DocObject View"), _T("Internet Explorer_Server"), NULL }; #define ON_THREAD_ELEMENT(dataMarshaller, p_HtmlElement) \ ON_THREAD_COMMON(dataMarshaller) \ IHTMLElement* p_HtmlElement = dataMarshaller.input_html_element_; HWND getIeServerWindow(HWND hwnd) { HWND iehwnd = hwnd; for (int i = 0; ie6WindowNames[i] && iehwnd; i++) { iehwnd = getChildWindow(iehwnd, ie6WindowNames[i]); } if (!iehwnd) { iehwnd = hwnd; for (int i = 0; ie7WindowNames[i] && iehwnd; i++) { iehwnd = getChildWindow(iehwnd, ie7WindowNames[i]); } } return iehwnd; } struct keyboardData { HWND main; HWND hwnd; HANDLE hdl_EventToNotifyWhenNavigationCompleted; const wchar_t* text; keyboardData(): hdl_EventToNotifyWhenNavigationCompleted(NULL) {} }; WORD WINAPI setFileValue(keyboardData* data) { EventReleaser ER(data->hdl_EventToNotifyWhenNavigationCompleted); Sleep(200); HWND ieMain = data->main; HWND dialogHwnd = ::GetLastActivePopup(ieMain); int maxWait = 10; while ((dialogHwnd == ieMain) && --maxWait) { Sleep(200); dialogHwnd = ::GetLastActivePopup(ieMain); } if (!dialogHwnd || (dialogHwnd == ieMain)) { cout << "No dialog found" << endl; return false; } return sendKeysToFileUploadAlert(dialogHwnd, data->text); } void IeThread::OnElementSendKeys(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) if (!isDisplayed(pElement)) { throw std::wstring(L"Element is not displayed"); } if (!isEnabled(pElement)) { throw std::wstring(L"Element is not enabled"); } LPCWSTR newValue = data.input_string_; CComPtr<IHTMLElement> element(pElement); const HWND hWnd = getHwnd(); const HWND ieWindow = getIeServerWindow(hWnd); keyboardData keyData; keyData.main = hWnd; // IE's main window keyData.hwnd = ieWindow; keyData.text = newValue; element->scrollIntoView(CComVariant(VARIANT_TRUE)); CComQIPtr<IHTMLInputFileElement> file(element); if (file) { DWORD threadId; tryTransferEventReleaserToNotifyNavigCompleted(&SC); keyData.hdl_EventToNotifyWhenNavigationCompleted = m_EventToNotifyWhenNavigationCompleted; ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) setFileValue, (void *) &keyData, 0, &threadId); element->click(); // We're now blocked until the dialog closes. return; } CComQIPtr<IHTMLElement2> element2(element); element2->focus(); // Check we have focused the element. CComPtr<IDispatch> dispatch; element->get_document(&dispatch); CComQIPtr<IHTMLDocument2> document(dispatch); bool hasFocus = false; clock_t maxWait = clock() + 1000; for (int i = clock(); i < maxWait; i = clock()) { wait(1); CComPtr<IHTMLElement> activeElement; if (document->get_activeElement(&activeElement) == S_OK) { CComQIPtr<IHTMLElement2> activeElement2(activeElement); if (element2.IsEqualObject(activeElement2)) { hasFocus = true; break; } } } if (!hasFocus) { cerr << "We don't have focus on element." << endl; } sendKeys(ieWindow, keyData.text, pIED->getSpeed()); } void IeThread::OnElementIsDisplayed(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) data.output_bool_ = isDisplayed(pElement); } bool isElementDisplayed(IHTMLElement* element) { CComQIPtr<IHTMLElement2> e2(element); CComPtr<IHTMLCurrentStyle> style; CComBSTR display; e2->get_currentStyle(&style); if(!style) { throw std::wstring(L"appears to manipulate obsolete DOM element."); } style->get_display(&display); std::wstring displayValue = combstr2cw(display); if (_wcsicmp(L"none", displayValue.c_str()) == 0) { return false; } CComPtr<IHTMLElement> parent; element->get_parentElement(&parent); if (!parent) { return true; } // Check that parent has style CComQIPtr<IHTMLElement2> parent2(parent); CComPtr<IHTMLCurrentStyle> parentStyle; parent2->get_currentStyle(&parentStyle); if (parentStyle) { return isElementDisplayed(parent); } return true; } bool isElementVisible(IHTMLElement* element) { CComQIPtr<IHTMLElement2> e2(element); CComPtr<IHTMLCurrentStyle> curr; CComBSTR visible; e2->get_currentStyle(&curr); if(!curr) { throw std::wstring(L"appears to manipulate obsolete DOM element."); } curr->get_visibility(&visible); std::wstring visibleValue = combstr2cw(visible); int isVisible = _wcsicmp(L"hidden", visibleValue.c_str()); if (isVisible == 0) { return false; } // If the style attribute was set on this class and contained visibility, then stop CComPtr<IHTMLStyle> style; element->get_style(&style); if (style) { CComBSTR visibleStyle; style->get_visibility(&visibleStyle); if (visibleStyle) { return true; // because we'd have returned false earlier, otherwise } } CComPtr<IHTMLElement> parent; element->get_parentElement(&parent); if (parent) { return isElementVisible(parent); } return true; } bool IeThread::isDisplayed(IHTMLElement *element) { CComQIPtr<IHTMLInputHiddenElement> hidden(element); if (hidden) { return false; } return isElementDisplayed(element) && isElementVisible(element); } void IeThread::OnElementIsEnabled(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) data.output_bool_ = isEnabled(pElement); } void IeThread::OnElementGetLocationOnceScrolledIntoView(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) long x = 0, y = 0; getLocationOnceScrolledIntoView(pElement, &x, &y); SAFEARRAY* args = SafeArrayCreateVector(VT_VARIANT, 0, 2); long index = 0; VARIANT xRes; xRes.vt = VT_I8; xRes.lVal = x; SafeArrayPutElement(args, &index, &xRes); index = 1; VARIANT yRes; yRes.vt = VT_I8; yRes.lVal = y; SafeArrayPutElement(args, &index, &yRes); VARIANT wrappedArray; wrappedArray.vt = VT_ARRAY; wrappedArray.parray = args; data.output_variant_.Attach(&wrappedArray); } void IeThread::OnElementGetLocation(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) long x = 0, y = 0; CComQIPtr<IHTMLElement2> element2(pElement); CComPtr<IHTMLRect> rect; element2->getBoundingClientRect(&rect); rect->get_left(&x); rect->get_top(&y); CComQIPtr<IHTMLDOMNode2> node(element2); CComPtr<IDispatch> ownerDocDispatch; node->get_ownerDocument(&ownerDocDispatch); CComQIPtr<IHTMLDocument3> ownerDoc(ownerDocDispatch); CComPtr<IHTMLElement> tempDoc; ownerDoc->get_documentElement(&tempDoc); CComQIPtr<IHTMLElement2> docElement(tempDoc); long left = 0, top = 0; docElement->get_scrollLeft(&left); docElement->get_scrollTop(&top); x += left; y += top; SAFEARRAY* args = SafeArrayCreateVector(VT_VARIANT, 0, 2); long index = 0; VARIANT xRes; xRes.vt = VT_I8; xRes.lVal = x; SafeArrayPutElement(args, &index, &xRes); index = 1; VARIANT yRes; yRes.vt = VT_I8; yRes.lVal = y; SafeArrayPutElement(args, &index, &yRes); VARIANT wrappedArray; wrappedArray.vt = VT_ARRAY; wrappedArray.parray = args; data.output_variant_.Attach(&wrappedArray); } void IeThread::OnElementGetHeight(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) long& height = data.output_long_; pElement->get_offsetHeight(&height); } void IeThread::OnElementGetWidth(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) long& width = data.output_long_; pElement->get_offsetWidth(&width); } void IeThread::OnElementGetElementName(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) std::wstring& ret = data.output_string_; getElementName(pElement, ret); } void IeThread::OnElementGetAttribute(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) getAttribute(pElement, data.input_string_, data.output_string_); } void IeThread::getTextAreaValue(IHTMLElement *pElement, std::wstring& res) { SCOPETRACER CComQIPtr<IHTMLTextAreaElement> textarea(pElement); CComBSTR result; textarea->get_value(&result); res = combstr2cw(result); } void IeThread::OnElementGetValue(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) std::wstring& ret = data.output_string_; getValue(pElement, ret); } void IeThread::OnElementClear(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) CComQIPtr<IHTMLElement2> element2(pElement); CComBSTR valueAttributeName(L"value"); // Get the current value, to see if we need to fire the onchange handler std::wstring curr; getValue(pElement, curr); bool fireChange = curr.length() != 0; element2->focus(); CComVariant empty; CComBSTR emptyBstr(L""); empty.vt = VT_BSTR; empty.bstrVal = (BSTR)emptyBstr; pElement->setAttribute(valueAttributeName, empty, 0); if (fireChange) { CComPtr<IHTMLEventObj> eventObj(newEventObject(pElement)); fireEvent(pElement, eventObj, L"onchange"); } element2->blur(); HWND hWnd = getHwnd(); LRESULT lr; SendMessageTimeoutW(hWnd, WM_SETTEXT, 0, (LPARAM) L"", SMTO_ABORTIFHUNG, 3000, (PDWORD_PTR)&lr); } void IeThread::OnElementIsSelected(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) data.output_bool_ = isSelected(pElement); } void IeThread::OnElementSetSelected(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) bool currentlySelected = isSelected(pElement); if (!this->isEnabled(pElement)) { throw std::wstring(L"Unable to select a disabled element"); } if (!this->isDisplayed(pElement)) { throw std::wstring(L"Unable to select an element that is not displayed"); } /* TODO(malcolmr): Why not: if (isSelected()) return; ? Do we really need to re-set 'checked=true' for checkbox and do effectively nothing for select? Maybe we should check for disabled elements first? */ if (isCheckbox(pElement)) { if (!isSelected(pElement)) { click(pElement); } CComBSTR checked(L"checked"); CComVariant isChecked; CComBSTR isTrue(L"true"); isChecked.vt = VT_BSTR; isChecked.bstrVal = (BSTR)isTrue; pElement->setAttribute(checked, isChecked, 0); if (currentlySelected != isSelected(pElement)) { CComPtr<IHTMLEventObj> eventObj(newEventObject(pElement)); fireEvent(pElement, eventObj, L"onchange"); } return; } if (isRadio(pElement)) { if (!isSelected(pElement)) { click(pElement); } CComBSTR selected(L"selected"); CComVariant select; CComBSTR isTrue(L"true"); select.vt = VT_BSTR; select.bstrVal = (BSTR)isTrue; pElement->setAttribute(selected, select, 0); if (currentlySelected != isSelected(pElement)) { CComPtr<IHTMLEventObj> eventObj(newEventObject(pElement)); fireEvent(pElement, eventObj, L"onchange"); } return; } CComQIPtr<IHTMLOptionElement> option(pElement); if (option) { option->put_selected(VARIANT_TRUE); // Looks like we'll need to fire the event on the select element and not the option. Assume for now that the parent node is a select. Which is dumb CComQIPtr<IHTMLDOMNode> node(pElement); CComPtr<IHTMLDOMNode> parent; node->get_parentNode(&parent); if (currentlySelected != isSelected(pElement)) { CComPtr<IHTMLEventObj> eventObj(newEventObject(pElement)); fireEvent(pElement, parent, eventObj, L"onchange"); } return; } throw std::wstring(L"Unable to select element"); } void IeThread::OnElementGetValueOfCssProp(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) getValueOfCssProperty(pElement, data.input_string_, data.output_string_); } void IeThread::OnElementGetText(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) getText(pElement, data.output_string_); } void IeThread::OnElementClick(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) click(pElement, &SC); } void IeThread::OnElementSubmit(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) submit(pElement, &SC); } IHTMLEventObj* IeThread::newEventObject(IHTMLElement *pElement) { SCOPETRACER IDispatch* dispatch; pElement->get_document(&dispatch); CComQIPtr<IHTMLDocument4> doc(dispatch); dispatch->Release(); CComVariant empty; IHTMLEventObj* eventObject; doc->createEventObject(&empty, &eventObject); return eventObject; } void IeThread::fireEvent(IHTMLElement *pElement, IHTMLEventObj* eventObject, const OLECHAR* eventName) { CComQIPtr<IHTMLDOMNode> node = pElement; fireEvent(pElement, node, eventObject, eventName); } void IeThread::fireEvent(IHTMLElement *pElement, IHTMLDOMNode* fireOn, IHTMLEventObj* eventObject, const OLECHAR* eventName) { SCOPETRACER CComVariant eventref; V_VT(&eventref) = VT_DISPATCH; V_DISPATCH(&eventref) = eventObject; CComBSTR onChange(eventName); VARIANT_BOOL cancellable; CComQIPtr<IHTMLElement3> element3(fireOn); element3->fireEvent(onChange, &eventref, &cancellable); } bool IeThread::isCheckbox(IHTMLElement *pElement) { SCOPETRACER CComQIPtr<IHTMLInputElement> input(pElement); if (!input) { return false; } CComBSTR typeName; input->get_type(&typeName); return _wcsicmp(combstr2cw(typeName), L"checkbox") == 0; } bool IeThread::isRadio(IHTMLElement *pElement) { SCOPETRACER CComQIPtr<IHTMLInputElement> input(pElement); if (!input) { return false; } CComBSTR typeName; input->get_type(&typeName); return _wcsicmp(combstr2cw(typeName), L"radio") == 0; } void IeThread::getElementName(IHTMLElement *pElement, std::wstring& res) { CComBSTR temp; pElement->get_tagName(&temp); res = combstr2cw(temp); transform(res.begin(), res.end(), res.begin(), tolower); } void IeThread::getAttribute(IHTMLElement *pElement, LPCWSTR name, std::wstring& res) { SCOPETRACER CComBSTR attributeName; if (_wcsicmp(L"class", name) == 0) { attributeName = L"className"; } else { attributeName = name; } CComVariant value; HRESULT hr = pElement->getAttribute(attributeName, 0, &value); res = comvariant2cw(value); } bool IeThread::isSelected(IHTMLElement *pElement) { SCOPETRACER CComQIPtr<IHTMLOptionElement> option(pElement); if (option) { VARIANT_BOOL isSelected; option->get_selected(&isSelected); return isSelected == VARIANT_TRUE; } if (isCheckbox(pElement)) { CComQIPtr<IHTMLInputElement> input(pElement); VARIANT_BOOL isChecked; input->get_checked(&isChecked); return isChecked == VARIANT_TRUE; } if (isRadio(pElement)) { std::wstring value; getAttribute(pElement, L"selected", value); if (!value.c_str()) return false; return _wcsicmp(value.c_str(), L"selected") == 0 || _wcsicmp(value.c_str(), L"true") == 0; } return false; } void IeThread::getLocationOnceScrolledIntoView(IHTMLElement *pElement, long *x, long *y) { CComQIPtr<IHTMLDOMNode2> node(pElement); if (!node) { cerr << "No node to get location of" << endl; return; } if (!isDisplayed(pElement)) { throw std::wstring(L"Element is not displayed"); } if (!isEnabled(pElement)) { throw std::wstring(L"Element is not enabled"); } const HWND hWnd = getHwnd(); const HWND ieWindow = getIeServerWindow(hWnd); // Scroll the element into view CComVariant toTop; toTop.vt = VT_BOOL; toTop.boolVal = VARIANT_TRUE; pElement->scrollIntoView(toTop); // getBoundingClientRect. Note, the docs talk about this possibly being off by 2,2 // and Jon Resig mentions some problems too. For now, we'll hope for the best // http://ejohn.org/blog/getboundingclientrect-is-awesome/ CComQIPtr<IHTMLElement2> element2(pElement); CComPtr<IHTMLRect> rect; if (FAILED(element2->getBoundingClientRect(&rect))) { return; } long clickX, clickY, width, height; rect->get_top(&clickY); rect->get_left(&clickX); rect->get_bottom(&height); rect->get_right(&width); height -= clickY; width -= clickX; if (height == 0 || width == 0) { throw std::wstring(L"Element would not be visible because it lacks height and/or width."); } CComPtr<IDispatch> ownerDocDispatch; node->get_ownerDocument(&ownerDocDispatch); CComQIPtr<IHTMLDocument3> ownerDoc(ownerDocDispatch); CComPtr<IHTMLElement> docElement; ownerDoc->get_documentElement(&docElement); CComQIPtr<IHTMLElement2> e2(docElement); CComQIPtr<IHTMLDocument2> doc2(ownerDoc); long clientLeft, clientTop; e2->get_clientLeft(&clientLeft); e2->get_clientTop(&clientTop); clickX += clientLeft; clickY += clientTop; // We now know the location of the element within its frame. // Where is the frame in relation to the HWND, though? // The ieWindow is the ultimate container, without chrome, // so if we know its location, we can subtract the screenLeft and screenTop // of the window. WINDOWINFO winInfo; GetWindowInfo(ieWindow, &winInfo); clickX -= winInfo.rcWindow.left; clickY -= winInfo.rcWindow.top; CComPtr<IHTMLWindow2> win2; doc2->get_parentWindow(&win2); CComQIPtr<IHTMLWindow3> win3(win2); long screenLeft, screenTop; win3->get_screenLeft(&screenLeft); win3->get_screenTop(&screenTop); clickX += screenLeft; clickY += screenTop; *x = clickX; *y = clickY; } void IeThread::click(IHTMLElement *pElement, CScopeCaller *pSC) { SCOPETRACER long clickX = 0, clickY = 0; getLocationOnceScrolledIntoView(pElement, &clickX, &clickY); const HWND hWnd = getHwnd(); const HWND ieWindow = getIeServerWindow(hWnd); // Create a mouse move, mouse down, mouse up OS event clickAt(ieWindow, clickX, clickY); tryTransferEventReleaserToNotifyNavigCompleted(pSC); waitForNavigateToFinish(); } bool IeThread::isEnabled(IHTMLElement *pElement) { SCOPETRACER CComQIPtr<IHTMLElement3> elem3(pElement); VARIANT_BOOL isDisabled; elem3->get_disabled(&isDisabled); return !isDisabled; } void IeThread::getValue(IHTMLElement *pElement, std::wstring& res) { SCOPETRACER CComBSTR temp; pElement->get_tagName(&temp); if (_wcsicmp(L"textarea", combstr2cw(temp)) == 0) { getTextAreaValue(pElement, res); return; } getAttribute(pElement, L"value", res); } const wchar_t* colourNames2hex[][2] = { { L"aqua", L"#00ffff" }, { L"black", L"#000000" }, { L"blue", L"#0000ff" }, { L"fuchsia", L"#ff00ff" }, { L"gray", L"#808080" }, { L"green", L"#008000" }, { L"lime", L"#00ff00" }, { L"maroon", L"#800000" }, { L"navy", L"#000080" }, { L"olive", L"#808000" }, { L"purple", L"#800080" }, { L"red", L"#ff0000" }, { L"silver", L"#c0c0c0" }, { L"teal", L"#008080" }, { L"white", L"#ffffff" }, { L"yellow", L"#ffff00" }, { NULL, NULL } }; LPCWSTR mangleColour(LPCWSTR propertyName, LPCWSTR toMangle) { if (wcsstr(propertyName, L"color") == NULL) return toMangle; // Look for each of the named colours and mangle them. for (int i = 0; colourNames2hex[i][0]; i++) { if (_wcsicmp(colourNames2hex[i][0], toMangle) == 0) return colourNames2hex[i][1]; } return toMangle; } #define BSTR_VALUE(method, cssName) if (_wcsicmp(cssName, propertyName) == 0) { CComBSTR bstr; method(&bstr); resultStr = combstr2cw(bstr); return;} #define VARIANT_VALUE(method, cssName) if (_wcsicmp(cssName, propertyName) == 0) { CComVariant var; method(&var); resultStr = mangleColour(propertyName, comvariant2cw(var)); return;} void IeThread::getValueOfCssProperty(IHTMLElement *pElement, LPCWSTR propertyName, std::wstring& resultStr) { SCOPETRACER CComQIPtr<IHTMLElement2> styled(pElement); CComBSTR name(propertyName); CComPtr<IHTMLCurrentStyle> style; styled->get_currentStyle(&style); /* // This is what I'd like to write. CComVariant value; style->getAttribute(name, 0, &value); return variant2wchar(value); */ // So the way we've done this strikes me as a remarkably poor idea. /* Not implemented background-position clip column-count column-gap column-width float marker-offset opacity outline-top-width outline-right-width outline-bottom-width outline-left-width outline-top-color outline-right-color outline-bottom-color outline-left-color outline-top-style outline-right-style outline-bottom-style outline-left-style user-focus user-select user-modify user-input white-space word-spacing */ BSTR_VALUE( style->get_backgroundAttachment, L"background-attachment"); VARIANT_VALUE( style->get_backgroundColor, L"background-color"); BSTR_VALUE( style->get_backgroundImage, L"background-image"); BSTR_VALUE( style->get_backgroundRepeat, L"background-repeat"); VARIANT_VALUE( style->get_borderBottomColor, L"border-bottom-color"); BSTR_VALUE( style->get_borderBottomStyle, L"border-bottom-style"); VARIANT_VALUE( style->get_borderBottomWidth, L"border-bottom-width"); VARIANT_VALUE( style->get_borderLeftColor, L"border-left-color"); BSTR_VALUE( style->get_borderLeftStyle, L"border-left-style"); VARIANT_VALUE( style->get_borderLeftWidth, L"border-left-width"); VARIANT_VALUE( style->get_borderRightColor, L"border-right-color"); BSTR_VALUE( style->get_borderRightStyle, L"border-right-style"); VARIANT_VALUE( style->get_borderRightWidth, L"border-right-width"); VARIANT_VALUE( style->get_borderTopColor, L"border-top-color"); BSTR_VALUE( style->get_borderTopStyle, L"border-top-style"); VARIANT_VALUE( style->get_borderTopWidth, L"border-top-width"); VARIANT_VALUE( style->get_bottom, L"bottom"); BSTR_VALUE( style->get_clear, L"clear"); VARIANT_VALUE( style->get_color, L"color"); BSTR_VALUE( style->get_cursor, L"cursor"); BSTR_VALUE( style->get_direction, L"direction"); BSTR_VALUE( style->get_display, L"display"); BSTR_VALUE( style->get_fontFamily, L"font-family"); VARIANT_VALUE( style->get_fontSize, L"font-size"); BSTR_VALUE( style->get_fontStyle, L"font-style"); VARIANT_VALUE( style->get_fontWeight, L"font-weight"); VARIANT_VALUE( style->get_height, L"height"); VARIANT_VALUE( style->get_left, L"left"); VARIANT_VALUE( style->get_letterSpacing, L"letter-spacing"); VARIANT_VALUE( style->get_lineHeight, L"line-height"); BSTR_VALUE( style->get_listStyleImage, L"list-style-image"); BSTR_VALUE( style->get_listStylePosition, L"list-style-position"); BSTR_VALUE( style->get_listStyleType, L"list-style-type"); BSTR_VALUE( style->get_margin, L"margin"); VARIANT_VALUE( style->get_marginBottom, L"margin-bottom"); VARIANT_VALUE( style->get_marginRight, L"margin-right"); VARIANT_VALUE( style->get_marginTop, L"margin-top"); VARIANT_VALUE( style->get_marginLeft, L"margin-left"); BSTR_VALUE( style->get_overflow, L"overflow"); BSTR_VALUE( style->get_padding, L"padding"); VARIANT_VALUE( style->get_paddingBottom, L"padding-bottom"); VARIANT_VALUE( style->get_paddingLeft, L"padding-left"); VARIANT_VALUE( style->get_paddingRight, L"padding-right"); VARIANT_VALUE( style->get_paddingTop, L"padding-top"); BSTR_VALUE( style->get_position, L"position"); VARIANT_VALUE( style->get_right, L"right"); BSTR_VALUE( style->get_textAlign, L"text-align"); BSTR_VALUE( style->get_textDecoration, L"text-decoration"); BSTR_VALUE( style->get_textTransform, L"text-transform"); VARIANT_VALUE( style->get_top, L"top"); VARIANT_VALUE( style->get_verticalAlign, L"vertical-align"); BSTR_VALUE( style->get_visibility, L"visibility"); VARIANT_VALUE( style->get_width, L"width"); VARIANT_VALUE( style->get_zIndex, L"z-index"); resultStr = L""; } void IeThread::getText(IHTMLElement *pElement, std::wstring& res) { SCOPETRACER CComBSTR tagName; pElement->get_tagName(&tagName); bool isTitle = tagName == L"TITLE"; bool isPre = tagName == L"PRE"; if (isTitle) { getTitle(res); return; } CComQIPtr<IHTMLDOMNode> node(pElement); std::wstring toReturn(L""); getText(toReturn, node, isPre); /* Trim leading and trailing whitespace and line breaks. */ std::wstring::const_iterator itStart = toReturn.begin(); while (itStart != toReturn.end() && iswspace(*itStart)) { ++itStart; } std::wstring::const_iterator itEnd = toReturn.end(); while (itStart < itEnd) { --itEnd; if (!iswspace(*itEnd)) { ++itEnd; break; } } res = std::wstring(itStart, itEnd); } /* static */ void IeThread::getText(std::wstring& toReturn, IHTMLDOMNode* node, bool isPreformatted) { SCOPETRACER if (isBlockLevel(node)) { collapsingAppend(toReturn, L"\r\n"); } CComPtr<IDispatch> dispatch; node->get_childNodes(&dispatch); CComQIPtr<IHTMLDOMChildrenCollection> children(dispatch); if (!children) return; long length = 0; children->get_length(&length); for (long i = 0; i < length; i++) { CComPtr<IDispatch> dispatch2; children->item(i, &dispatch2); CComQIPtr<IHTMLDOMNode> child(dispatch2); CComBSTR childName; child->get_nodeName(&childName); CComQIPtr<IHTMLDOMTextNode> textNode(child); if (textNode) { CComBSTR text; textNode->get_data(&text); for (unsigned int i = 0; i < text.Length(); i++) { if (text[i] == 160) { text[i] = L' '; } } collapsingAppend(toReturn, isPreformatted ? std::wstring(combstr2cw(text)) // bstr2wstring(text) : collapseWhitespace(text)); } else if (wcscmp(combstr2cw(childName), L"PRE") == 0) { getText(toReturn, child, true); } else { getText(toReturn, child, false); } } if (isBlockLevel(node)) { collapsingAppend(toReturn, L"\r\n"); } } // Append s2 to s, collapsing intervening whitespace. // Assumes that s and s2 have already been internally collapsed. /*static*/ void IeThread::collapsingAppend(std::wstring& s, const std::wstring& s2) { if (s.empty() || s2.empty()) { s += s2; return; } // \r\n abutting \r\n collapses. if (s.length() >= 2 && s2.length() >= 2) { if (s[s.length() - 2] == L'\r' && s[s.length() - 1] == L'\n' && s2[0] == L'\r' && s2[1] == L'\n') { s += s2.substr(2); return; } } // wspace abutting wspace collapses into a space character. if ((iswspace(s[s.length() - 1]) && s[s.length() - 1] != L'\n') && (iswspace(s2[0]) && s[0] != L'\r')) { s += s2.substr(1); return; } s += s2; } /*static*/ std::wstring IeThread::collapseWhitespace(CComBSTR& comtext) { std::wstring toReturn(L""); int previousWasSpace = false; wchar_t previous = L'X'; bool newlineAlreadyAppended = false; LPCWSTR text = combstr2cw(comtext); // Need to keep an eye out for '\r\n' for (unsigned int i = 0; i < wcslen(text); i++) { wchar_t c = text[i]; int currentIsSpace = iswspace(c); // Append the character if the previous was not whitespace if (!(currentIsSpace && previousWasSpace)) { toReturn += c; newlineAlreadyAppended = false; } else if (previous == L'\r' && c == L'\n' && !newlineAlreadyAppended) { // If the previous char was '\r' and current is '\n' // and we've not already appended '\r\n' append '\r\n'. // The previous char was '\r' and has already been appended and // the current character is '\n'. Just appended that. toReturn += c; newlineAlreadyAppended = true; } previousWasSpace = currentIsSpace; previous = c; } return toReturn; } /*static */ bool IeThread::isBlockLevel(IHTMLDOMNode *node) { SCOPETRACER CComQIPtr<IHTMLElement> e(node); if (e) { CComBSTR tagName; e->get_tagName(&tagName); bool isBreak = false; if (!wcscmp(L"BR", tagName)) { isBreak = true; } if (isBreak) { return true; } } CComQIPtr<IHTMLElement2> element2(node); if (!element2) { return false; } CComPtr<IHTMLCurrentStyle> style; element2->get_currentStyle(&style); if (!style) { return false; } CComQIPtr<IHTMLCurrentStyle2> style2(style); if (!style2) { return false; } VARIANT_BOOL isBlock; style2->get_isBlock(&isBlock); return isBlock == VARIANT_TRUE; } void IeThread::submit(IHTMLElement *pElement, CScopeCaller *pSC) { SCOPETRACER CComQIPtr<IHTMLFormElement> form(pElement); if (form) { form->submit(); } else { CComQIPtr<IHTMLInputElement> input(pElement); if (input) { CComBSTR typeName; input->get_type(&typeName); LPCWSTR type = combstr2cw(typeName); if (_wcsicmp(L"submit", type) == 0 || _wcsicmp(L"image", type) == 0) { click(pElement); } else { CComPtr<IHTMLFormElement> form2; input->get_form(&form2); form2->submit(); } } else { findParentForm(pElement, &form); if (!form) { throw std::wstring(L"Unable to find the containing form"); } form->submit(); } } /////// tryTransferEventReleaserToNotifyNavigCompleted(pSC); waitForNavigateToFinish(); } void IeThread::findParentForm(IHTMLElement *pElement, IHTMLFormElement **pform) { SCOPETRACER CComPtr<IHTMLElement> current(pElement); while (current) { CComQIPtr<IHTMLFormElement> form(current); if (form) { *pform = form.Detach(); return; } CComPtr<IHTMLElement> temp; current->get_parentElement(&temp); current = temp; } } void IeThread::OnElementGetChildrenWithTagName(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) std::vector<IHTMLElement*> &allElems = data.output_list_html_element_; LPCWSTR tagName= data.input_string_; CComQIPtr<IHTMLElement2> element2(pElement); CComBSTR name(tagName); CComPtr<IHTMLElementCollection> elementCollection; element2->getElementsByTagName(name, &elementCollection); long length = 0; elementCollection->get_length(&length); for (int i = 0; i < length; i++) { CComVariant idx; idx.vt = VT_I4; idx.lVal = i; CComVariant zero; zero.vt = VT_I4; zero.lVal = 0; CComPtr<IDispatch> dispatch; elementCollection->item(idx, zero, &dispatch); CComQIPtr<IHTMLDOMNode> node(dispatch); CComQIPtr<IHTMLElement> elem(node); if(elem) { IHTMLElement *pDom = NULL; elem.CopyTo(&pDom); allElems.push_back(pDom); } } } void IeThread::OnElementRelease(WPARAM w, LPARAM lp) { SCOPETRACER ON_THREAD_ELEMENT(data, pElement) pElement->Release(); }
[ "josephg@07704840-8298-11de-bf8c-fd130f914ac9" ]
[ [ [ 1, 1247 ] ] ]
48bed17a93494ed6e905b288051dcbdd4d6f15ce
78fb44a7f01825c19d61e9eaaa3e558ce80dcdf5
/guceCORE/include/CStaticResourcePtr.h
d19fff6858b5c93d36282b5e9fe1d969b0e64a48
[]
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,666
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 CSTATICRESOURCEPTR_H #define CSTATICRESOURCEPTR_H /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #ifndef _Resource_H__ #include "ogreresource.h" #define _Resource_H__ #endif /* _Resource_H__ ? */ #ifndef GUCECORE_MACROS_H #include "guceCORE_macros.h" /* guceCORE build config and macros */ #define GUCECORE_MACROS_H #endif /* GUCECORE_MACROS_H ? */ /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCE { namespace CORE { /*-------------------------------------------------------------------------// // // // CLASSES // // // //-------------------------------------------------------------------------*/ /** * Class that will allow you to pass a local recource as an * Ogre recource. This will allow Ogre to use recources it should * not delete as a recource uppon destruction of the last recource pointer. */ class CStaticResourcePtr : public Ogre::ResourcePtr { public: CStaticResourcePtr( void ) : Ogre::ResourcePtr() { } CStaticResourcePtr( const CStaticResourcePtr& src ) : Ogre::ResourcePtr( src ) { } CStaticResourcePtr( const Ogre::ResourcePtr& src ) : Ogre::ResourcePtr( src ) { } CStaticResourcePtr& operator=( const CStaticResourcePtr& src ) { return *this; } ~CStaticResourcePtr() { if ( ( *pUseCount - 1 ) == 0 ) { pRep = NULL; *pUseCount = 0; } } }; /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ } /* namespace CORE ? */ } /* namespace GUCE ? */ /*-------------------------------------------------------------------------*/ #endif /* CSTATICRESOURCEPTR_H ? */ /*-------------------------------------------------------------------------// // // // Info & Changes // // // //-------------------------------------------------------------------------// - 05-05-2005 : - Designed and implemented this class. -----------------------------------------------------------------------------*/
[ [ [ 1, 116 ] ] ]
abafcb34378e00b9221adf621e5dcc344ed38179
25426133cf6405c5cebf4b51c48ff3dce2629ea9
/engine/input.cpp
30b671829898ec1c62c584b11bc0d561f1483d67
[]
no_license
tolhc1234/openglengine
456fd5a099b30544af1e338fab289402d2b81341
6ed525f9a74235605157e68728e36b8b5291b096
refs/heads/master
2021-01-10T02:38:58.457222
2010-01-12T20:28:21
2010-01-12T20:28:21
50,214,430
0
0
null
null
null
null
UTF-8
C++
false
false
53
cpp
#include "input.h" //nvm.. void input::events(){ }
[ [ [ 1, 4 ] ] ]
22c887eb0a35bddff38c1401633cedfa29ce8bfd
036f83e4ba5370b4ec50da6d1d1561d85dedbde0
/devel/puzzle-solvers/disjoint-paths-on-3d-cube/3dlogic.cpp
a147ef3a76a6afdb56d4874c3043ad18f1c177be
[]
no_license
losvald/high-school
8ba4487889093451b519c3f582d0dce8a5a6f5b8
4bfe295ad4ef1badf8a01d19e2ab3a65d59c1ce8
refs/heads/master
2016-09-06T03:48:25.747372
2008-01-17T10:56:55
2008-01-17T10:56:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,834
cpp
/* * Copyright (C) 2007 Leo Osvald <[email protected]> * * 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. */ #include <cstdio> #include <iostream> #include <vector> #include <cstring> #include <list> #include <queue> #include <algorithm> #define WALL '#' #define MAX 6 #define FC(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it) using namespace std; int n, start_path[26], end_path[26]; char cube[2*MAX+1][2*MAX+1]; int polje[3*MAX*MAX+1], bfs_dist[3*MAX*MAX+1]; vector<list<int> > adj; vector<int> colors, best_perm; int tot_space, extra_space, last_color; int min_space[26], min_path[26]; double stcl, last_cl, max_time, best_time = 10E20; int fctrl, skip; int brojac; struct point { int x, y; point() { } point(const int x, const int y) : x(x), y(y) {} }; int hc(const int y, const int x) { if(y < n || x < n) return y*n + x; return 2*n*n + (y-n)*n+(x-n); } void print() { for(int i = 0; i < 2*n; ++i, printf("\n")) for(int j = 0; j < 2*n; ++j) { if(i < n && j >= n) break; printf("%c", polje[hc(i, j)]); } } int bfs(const int color) { memset(bfs_dist, -1, sizeof bfs_dist); bfs_dist[start_path[color]] = 0; queue<int> q; for(q.push(start_path[color]); !q.empty(); q.pop()) { int x = q.front(); if(x == end_path[color]) break; FC(it, adj[x]) { if(bfs_dist[*it] != -1) continue; if(polje[*it] != '.' && polje[*it] != 'A'+color) continue; bfs_dist[*it] = bfs_dist[x] + 1; q.push(*it); } } if(bfs_dist[end_path[color]] == -1) return -1; return bfs_dist[end_path[color]]+1; } void info(const int x, const int d, const int col) { //if(clock()-last_cl > 5000) { last_cl = clock(); printf("%d. (%3d %3d %3d)\n", brojac++, x, d, col); print(); //} cin.get(); } int blockable(const int d, const int col) {//dal su zablokirani ostali putevi int paths_after = 0; for(int i = col+1; i < colors.size(); ++i) { int curr_path = bfs(colors[i]); if(curr_path == -1) return 1; //izadji ak ovo blokira ostale puteve paths_after += curr_path; if(d+paths_after - min_space[i] > extra_space) { //printf("*"); return 1; } } return 0; } int collides(const int x, const char c) { int cnt = 0; FC(it, adj[x]) if(polje[*it] == c) ++cnt; return cnt >= 2; } int dfs(const int x, const int d, const int col) { ++brojac; if(brojac%50 && clock()-stcl > max_time) return 0; if(x == end_path[last_color]) return 1; if(d - min_space[col] > extra_space) return 0; if( collides(x, 'a' + colors[col]) ) return 0; if(blockable(d, col) ) return 0; if(x == end_path[colors[col]]) { //info(x, d, col); if( dfs(start_path[colors[col+1]], d+1, col+1) ) return 1; return 0; } if(x != start_path[colors[col]]) polje[x] = 'a' + colors[col]; //printf("[%d %d %c]\n", x, d, 'A'+colors[col]); print(); cin.get(); FC(it, adj[x]) { if(polje[*it] == '.' || polje[*it] == 'A'+colors[col] && *it != start_path[colors[col]]) if( dfs(*it, d+1, col) ) return 1; } if(x != start_path[colors[col]]) polje[x] = '.'; return 0; } void clear_paths() { for(int i = 0; i < 2*n; ++i) for(int j = 0; j < 2*n; ++j) { if(i < n && j >= n) break; polje[hc(i, j)] = cube[i][j]; } } void solve() { sort(colors.begin(), colors.end()); for(int curr_perm = 0; ; curr_perm += skip) { last_cl = stcl = clock(); extra_space = tot_space; int last_space = 0; FC(it, colors) { min_path[it-colors.begin()] = bfs(*it); extra_space -= min_path[it-colors.begin()]; last_space = min_space[it-colors.begin()] = min_path[it-colors.begin()] + last_space; } last_color = colors[colors.size()-1]; int sol = dfs(start_path[colors[0]], 1, 0); double ccl = clock()-stcl; double percent = 100.00 * curr_perm / fctrl ; if(ccl < max_time) printf("\n%6d => %d (= %lf ms) ... %lf%% complete\n", curr_perm, sol, ccl, percent); else if(!sol) printf("\n%6d NONE (= %lf ms) ... %lf%% complete\n", curr_perm, ccl, percent); if(sol) { print(); if(ccl < best_time) { best_time = ccl; best_perm = colors; } break ; } clear_paths(); int quit = 0; for(int i = 0; i < skip; ++i) { if(!next_permutation(colors.begin(), colors.end())) { quit = 1; break; } } if(quit) break; } printf("\nBest time: %lf\nBest permutation: ", best_time); FC(it, best_perm) printf("%c", 'A'+*it); } int fact(int x) { return (x > 1) ? x*fact(x-1) : 1; } void prepare() { const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1}; memset(start_path, -1, sizeof start_path); memset(end_path, -1, sizeof end_path); adj.resize(3*n*n); for(int i = 0; i < 2*n; ++i) { for(int j = 0; j < 2*n; ++j) { if(i < n && j >= n) break; polje[hc(i, j)] = cube[i][j]; if(cube[i][j] == WALL) continue; for(int sm = 0; sm < 4; ++sm) { int ny = i + dy[sm], nx = j + dx[sm]; if(ny < 0 || ny >= 2*n || nx < 0) continue; if(ny < n && nx >= n || ny >= n && nx >= 2*n) continue; if(cube[ny][nx] == WALL) continue; int c1 = hc(i, j), c2 = hc(ny, nx); adj[c1].push_back(c2); } if(i < n && j == n-1) { int ny = j+1, nx = 2*n-i-1; if(cube[ny][nx] != WALL) { int c1 = hc(i, j), c2 = hc(ny, nx); adj[c1].push_back(c2); adj[c2].push_back(c1); } } if(cube[i][j] >= 'A' && cube[i][j] <= 'Z') { if(start_path[cube[i][j]-'A'] == -1) start_path[cube[i][j]-'A'] = hc(i, j); else end_path[cube[i][j]-'A'] = hc(i, j); } ++tot_space; } } for(int i = 0; i < 26; ++i) if(start_path[i] != -1) colors.push_back(i); printf("How many seconds to wait? "); scanf("%lf", &max_time); max_time *= 100; max_time /= (double) (fctrl = fact(colors.size())); printf("Try every which permutation? "); scanf("%d", &skip); max_time *= skip; printf("[[[[%lf]]]]", max_time); } void input() { scanf("%d\n", &n); for(int i = 0; i < 2*n; ++i) gets(cube[i]); } int main() { input(); prepare(); solve(); printf("\n\nDone!\n"); scanf("\n"); return 0; } /* 3 ... RB. ... .##.#. .#BR.# ...... */ /* 0 1 2 3 4 5 6 7 8 9 10 11 18 19 20 12 13 14 21 22 23 15 16 17 24 25 26 */ /* 2 A. #B ..#. AB.. 2 A# B# B#.. A#.. 5 ....# ....# ....# ....# ##### ....C..... .B.....A.. ....CD...# ........D. A........B aaa.Cdddd. aBa.cd.Ad. aba.CD.ad# abaaaaaaD. AbbbbbbbbB 5 ...IW .GH.. ..I.W H..G# ....# ....A..... .B.....C.. ....AD...# ........D. C........B 5 ##A## B...B ##.## ##A## ##### ########## ########## ########## ########## ########## */ /* LEVEL 29 6 ...... ..P.Y. ...... ....R. ..W... ...... ..B..G...B.. .......P.W.. ...O........ ......G...O. .........R.. .......Y.... */ /* 5 #..Y# ..... ..... ..B.. ..R.. .....P...# ...Y..R..B .ZC.....Z. .....C.... P........# */
[ [ [ 1, 333 ] ] ]
2679b7ad925228064843b1c0b71409ec8053b2db
2aff7486e6c7afdbda48b7a5f424b257d47199df
/src/Camera/OpenCvCamera/OpenCvCamera.cpp
0a7fe54256dc70cf3b0467c02f98a35e0908ac5a
[]
no_license
offlinehacker/LDI_test
46111c60985d735c00ea768bdd3553de48ba2ced
7b77d3261ee657819bae3262e3ad78793b636622
refs/heads/master
2021-01-10T20:44:55.324019
2011-08-17T16:41:43
2011-08-17T16:41:43
2,220,496
1
0
null
null
null
null
UTF-8
C++
false
false
4,589
cpp
#include "OpenCvCamera.h" char* OpenCvCamera::GetCameraName() { sprintf( camera_name, "cv_%d", cam_id ); return camera_name; } OpenCvCamera::OpenCvCamera( int lcam_id ): CameraSource() { cam_id= lcam_id; cam_type= CAM_TYPE_CAMERA; } bool OpenCvCamera::TestCamera() { CvCapture *tCapture= cvCaptureFromCAM(cam_id); if(tCapture) { width = (int) cvGetCaptureProperty( tCapture, CV_CAP_PROP_FRAME_WIDTH ); height = (int) cvGetCaptureProperty( tCapture, CV_CAP_PROP_FRAME_HEIGHT ); fps = (int) cvGetCaptureProperty( tCapture, CV_CAP_PROP_FPS ); IplImage* tFrame; for( int x=0; x<10; x++ )//We try to get at least one frame in time(camera needs some time to start) { wxThread::Sleep(100); tFrame = cvQueryFrame( tCapture ); if( tFrame )//here we have a frame break; } if(!tFrame) { delete(tCapture); return false; } depth = tFrame->depth; channels= tFrame->nChannels; if(width<=0) width= tFrame->width; if(height<=0) height= tFrame->height; cvReleaseCapture(&tCapture); tested=true; return true; } return false; } //Open our camera bool OpenCvCamera::OpenCamera() { if(tested || TestCamera()) { CameraHandle= cvCaptureFromCAM(cam_id); if(CameraHandle) { opened= true; return true; } } return false; } //Close our camera void OpenCvCamera::CloseCamera() { if(opened) cvReleaseCapture(&CameraHandle); } //Get next frame from camera IplImage* OpenCvCamera::GetNextFrame() { IplImage* pFrame= NULL; if(!CameraHandle) opened= false; if(opened) pFrame = cvQueryFrame( CameraHandle ); return pFrame; } CameraSource *CvCameraEnumerator::GetNextCamera() { for(int x=NextEnumeratedCamera; x<MAX_CV_CAMERAS; x++ ) { OpenCvCamera *EnumCamera= new OpenCvCamera(x); if(EnumCamera->TestCamera()) { NextEnumeratedCamera=x+1; return (CameraSource*)EnumCamera; } delete(EnumCamera); } return NULL; } void CvCameraEnumerator::Reset() { NextEnumeratedCamera= 0; } CvVideoFile::CvVideoFile(): CameraSource() { filename= NULL; cam_type= CAM_TYPE_FILE; Postopen= true; } void CvVideoFile::SetFilename( char* lfilename ) { if( filename ) { CloseCamera(); free( filename ); filename= (char*)malloc( strlen(lfilename) ); strcpy( filename, lfilename ); } else { filename= (char*)malloc( strlen(lfilename) ); strcpy( filename, lfilename ); } } char* CvVideoFile::GetCameraName() { if(filename) sprintf( camera_name, "vf_'%s'", filename ); else sprintf( camera_name, "vf_'notset'" ); return camera_name; } bool CvVideoFile::TestCamera() { if(!filename) return false; CameraHandle= cvCaptureFromAVI(filename); if(CameraHandle) { width = (int) cvGetCaptureProperty( CameraHandle, CV_CAP_PROP_FRAME_WIDTH ); height = (int) cvGetCaptureProperty( CameraHandle, CV_CAP_PROP_FRAME_HEIGHT ); fps = (int) cvGetCaptureProperty( CameraHandle, CV_CAP_PROP_FPS ); IplImage* tFrame=NULL; for( int x=0; x<10; x++ )//We try to get at least one frame in time(camera needs some time to start) { wxThread::Sleep(100); tFrame = cvQueryFrame( CameraHandle ); if( tFrame )//here we have a frame break; } if(!tFrame) { delete(CameraHandle); return false; } depth = tFrame->depth; channels= tFrame->nChannels; if(width<=0) width= tFrame->width; if(height<=0) height= tFrame->height; //cvReleaseCapture(&CameraHandle); return true; } return false; } bool CvVideoFile::OpenCamera() { //if(TestCamera()) //{ opened= true; return true; //} //return false; } void CvVideoFile::CloseCamera() { if(opened && !Postopen) cvReleaseCapture(&CameraHandle); Postopen=true; } IplImage* CvVideoFile::GetNextFrame() { if(Postopen) { TestCamera(); Postopen= false; } IplImage* pFrame= NULL; if(CameraHandle) pFrame = cvQueryFrame( CameraHandle ); wxThread::Sleep(1000); if(!pFrame) { //CloseCamera(); } return pFrame; } CvCameraEnumerator::CvCameraEnumerator(): CameraEnumerator() { NextEnumeratedCamera= 0; } CvVideoFileEnumerator::CvVideoFileEnumerator(): CameraEnumerator() { first= false; } CameraSource *CvVideoFileEnumerator::GetNextCamera() { if(first) return NULL; CvVideoFile *EnumCamera= new CvVideoFile(); first=true; return (CameraSource*)EnumCamera; } void CvVideoFileEnumerator::Reset() { first= false; }
[ [ [ 1, 249 ] ] ]
835222999cbec721463835c80380f0ce407eab8e
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/AccountServer/BillingMgrJP.h
5052fa72f7b5a5075d1f9a17cbbe4b74dcceee87
[]
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
1,026
h
#ifndef __BILLINGMGRJP_H__ #define __BILLINGMGRJP_H__ #include "BillingMgr.h" class CDPBilling; class CBillingMgrJP : public CBillingMgr { public: CBillingMgrJP(); virtual ~CBillingMgrJP(); virtual bool Init( HWND hWnd ); virtual void Release(); virtual BYTE CheckAccount( int nType, DWORD dwKey, const char* szAccount, const char* szAddr ); virtual BOOL PreTranslateMessage( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ); virtual BOOL SetConfig( BILLING_ENUM id, DWORD data ); virtual void OnTimer( CAccount* pAccount ); virtual void OnDBQuery( CQuery& query, tagDB_OVERLAPPED_PLUS* pOV ) {} virtual void NotifyLogout( LPCTSTR lpszAccount, DWORD dwSession ) {} private: int m_iBillingFreePass; CDPBilling* m_pDPBillings; int m_nMaxConnect; vector< string > m_strIPs; vector< u_short > m_nPorts; bool Connect(); bool RequestBillingInfo( LPCTSTR lpszAccount, LPCTSTR lpAddr ); void SendKeepAlive(); }; #endif // __BILLINGMGR_H__
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 36 ] ] ]
745f0d3f0943fdee34d0bc83f707b1500286c9b4
a31e04e907e1d6a8b24d84274d4dd753b40876d0
/MortScript/CommandsSystem.cpp
136fbf9cbf84e67138a59fb041eabeccf0b47c9b
[]
no_license
RushSolutions/jscripts
23c7d6a82046dafbba3c4e060ebe3663821b3722
869cc681f88e1b858942161d9d35f4fbfedcfd6d
refs/heads/master
2021-01-10T15:31:24.018830
2010-02-26T07:41:17
2010-02-26T07:41:17
47,889,373
0
0
null
null
null
null
UTF-8
C++
false
false
46,085
cpp
#ifdef SMARTPHONE #include <windows.h> #include "smartphone/mortafx.h" extern HINSTANCE g_hInst; #ifndef PNA #include <vibrate.h> #endif #define LoadStdCursor(x) LoadCursor(NULL,x) #include "smartphone\DlgChoice.h" #include <pm.h> //jwz:add #include <bthutil.h> #include "FctFlight.h" //jwz:add end #endif #ifndef SMARTPHONE #include "stdafx.h" #include "mortscriptapp.h" extern CMortScriptApp theApp; #include "DlgChoice.h" #endif #include <string.h> #include "interpreter.h" #ifdef DESKTOP #include "vc6\stdafx.h" #include "vc6\resource.h" #include "direct.h" #define LoadStdCursor(x) theApp.LoadStandardCursor(x) #else const GUID IID_ConnPrv_IProxyExtension = { 0xaf96b0bd, 0xa481, 0x482c, { 0xa0, 0x94, 0xa8, 0x44, 0x87, 0x67, 0xa0, 0xc0 } }; #include "connmgr.h" #include <connmgr_proxy.h> #include "ras.h" #include "raserror.h" #include "notify.h" #include <winioctl.h> #ifndef POWER_STATE_ON #define POWER_STATE_ON (DWORD)(0x00010000) // on state #define POWER_STATE_IDLE (DWORD)(0x00100000) // idle state #define POWER_STATE_RESET (DWORD)(0x00800000) // soft reset #define POWER_FORCE (DWORD)(0x00001000) #endif #define IOCTL_HAL_REBOOT CTL_CODE(FILE_DEVICE_HAL, 15, METHOD_BUFFERED, FILE_ANY_ACCESS) extern "C" __declspec(dllimport) void SetCleanRebootFlag(void); extern "C" __declspec(dllimport) BOOL KernelIoControl( DWORD dwIoControlCode, LPVOID lpInBuf, DWORD nInBufSize, LPVOID lpOutBuf, DWORD nOutBufSize, LPDWORD lpBytesReturned); void WINAPI SystemIdleTimerReset(void); #ifndef _i386_ void PowerOffSystem() { ::keybd_event(VK_OFF, 0, 0, 0); ::keybd_event(VK_OFF, 0, KEYEVENTF_KEYUP, 0); } #else #define PowerOffSystem(); #endif #endif #ifdef POCKETPC #include "vibrate.h" #define LoadStdCursor(x) theApp.LoadStandardCursor(x) #endif #include "variables.h" #include "inifile.h" #include "Interpreter.h" #include "CommandsSystem.h" // defined in Interpreter.cpp extern CMortPtrArray SubResultStack; extern CMortPtrArray LocalVariablesStack; extern HANDLE ScriptAborted; #ifndef DESKTOP #ifndef PNA BOOL CmdConnect( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; interpreter.Split( param, L',', params ); if ( params.GetSize() > 2 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'Connect'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } if ( interpreter.Connection != NULL ) { CloseHandle(interpreter.Connection); interpreter.Connection = NULL; } GUID *guid = NULL; // Selection dialog if ( params.GetSize() == 2 ) { CONNMGR_DESTINATION_INFO destInfo; CDlgChoice choiceDlg; choiceDlg.m_Title = (CStr)params[0]; choiceDlg.m_Info = (CStr)params[1]; for ( int i=0; ConnMgrEnumDestinations(i,&destInfo) == S_OK; i++ ) { choiceDlg.m_Strings.Add( destInfo.szDescription ); } choiceDlg.DoModal(); if ( choiceDlg.m_Selected > 0 ) { ConnMgrEnumDestinations( choiceDlg.m_Selected, &destInfo ); guid = &destInfo.guid; } } // Given interpreter.Connection name if ( params.GetSize() == 1 ) { CONNMGR_DESTINATION_INFO destInfo; for ( int i=0; ConnMgrEnumDestinations(i,&destInfo) == S_OK; i++ ) { if ( ((CStr)params.GetAt(0)).CompareNoCase( destInfo.szDescription ) == 0 ) { guid = &destInfo.guid; break; } } } // Try to find default if ( guid == NULL ) { ConnMgrMapURL( L"http://www.microsoft.com", guid, NULL ); } if ( guid != NULL ) { CONNMGR_CONNECTIONINFO connInfo; connInfo.cbSize = sizeof(connInfo); connInfo.dwParams = CONNMGR_PARAM_GUIDDESTNET; connInfo.dwFlags = CONNMGR_FLAG_PROXY_HTTP; connInfo.dwPriority = CONNMGR_PRIORITY_USERINTERACTIVE; connInfo.bExclusive = FALSE; connInfo.bDisabled = FALSE; connInfo.guidDestNet = *guid; connInfo.hWnd = NULL; DWORD status; if ( ConnMgrEstablishConnectionSync( &connInfo, &interpreter.Connection, 30000, &status ) != S_OK ) { if ( interpreter.ErrorLevel >= ERROR_ERROR ) MessageBox( GetMsgParent(), L"Couldn't establish internet interpreter.Connection" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); rc = FALSE; } else { PROXY_CONFIG proxyInfo; ZeroMemory(&proxyInfo, sizeof(proxyInfo)); proxyInfo.dwType = CONNMGR_FLAG_PROXY_HTTP; if (SUCCEEDED(ConnMgrProviderMessage( interpreter.Connection, &IID_ConnPrv_IProxyExtension, NULL, 0, 0, (PBYTE)&proxyInfo, sizeof(proxyInfo)))) { if (proxyInfo.dwType == CONNMGR_FLAG_PROXY_HTTP) { Proxy = proxyInfo.szProxyServer; // SECURITY: Zero out the username/password from memory. ZeroMemory(&(proxyInfo.szUsername), sizeof(proxyInfo.szUsername)); ZeroMemory(&(proxyInfo.szPassword), sizeof(proxyInfo.szPassword)); } } } } else { if ( interpreter.ErrorLevel >= ERROR_ERROR ) MessageBox( GetMsgParent(), L"Couldn't establish internet interpreter.Connection" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); rc = FALSE; } return TRUE; } BOOL CmdDisconnect( CInterpreter &interpreter, CStr &param ) { CmdCloseConnection( interpreter, param ); LPRASCONN rasConn = NULL; DWORD error = 0; DWORD count = 1, connectionCount = 0; DWORD size; do { if ( rasConn != NULL ) HeapFree(GetProcessHeap(), 0, rasConn); size = sizeof(RASCONN) * count; rasConn = (LPRASCONN)HeapAlloc( GetProcessHeap(), 0, size ); rasConn->dwSize = sizeof(RASCONN); error = RasEnumConnections( rasConn, &size, &connectionCount ); } while ( error == ERROR_BUFFER_TOO_SMALL && rasConn != NULL ); if ( rasConn != NULL && error == ERROR_SUCCESS ) { for(DWORD i=0;i<connectionCount;i++) { RasHangUp( rasConn->hrasconn ); rasConn++; } } if ( rasConn != NULL ) HeapFree(GetProcessHeap(), 0, rasConn); return TRUE; } BOOL CmdCloseConnection( CInterpreter &interpreter, CStr &param ) { if ( interpreter.Connection != NULL ) { ConnMgrReleaseConnection( interpreter.Connection, FALSE ); CloseHandle(interpreter.Connection); interpreter.Connection = NULL; } return TRUE; } #endif // PNA BOOL CmdRotate( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'Rotate'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } OSVERSIONINFO ver; GetVersionEx( &ver ); if ( ( ver.dwMajorVersion > 4 || (ver.dwMajorVersion == 4 && ver.dwMinorVersion >= 21) ) ) { DEVMODE mode; mode.dmSize = sizeof(DEVMODE); mode.dmFields = DM_DISPLAYORIENTATION; ChangeDisplaySettingsEx(NULL, &mode, 0, CDS_TEST, NULL); switch ( (long)params.GetAt(0) ) { case 90: mode.dmDisplayOrientation = DMDO_90; break; case 270: mode.dmDisplayOrientation = DMDO_270; break; case 180: mode.dmDisplayOrientation = DMDO_180; break; default: mode.dmDisplayOrientation = DMDO_0; break; } ChangeDisplaySettingsEx( NULL, &mode, NULL, 0, NULL ); } return rc; } BOOL CmdRedrawToday( CInterpreter &interpreter, CStr &param ) { ::PostMessage( HWND_BROADCAST, WM_SETTINGCHANGE, SPI_SETDESKWALLPAPER, 0 ); ::SendMessage( ::GetDesktopWindow(), WM_WININICHANGE, 0xF2, 0 ); return TRUE; } BOOL CmdIdleTimerReset( CInterpreter &interpreter, CStr &param ) { SystemIdleTimerReset(); return TRUE; } BOOL CmdPowerOff( CInterpreter &interpreter, CStr &param ) { PowerOffSystem(); ::Sleep(1500); return TRUE; } BOOL CmdReset( CInterpreter &interpreter, CStr &param ) { KernelIoControl(IOCTL_HAL_REBOOT, NULL, 0, NULL, 0, NULL); return TRUE; } #endif // ! Desktop BOOL CmdSetVolume( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'SetVolume'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } long vol = (long)params[0]; if ( vol >= 0 && vol <= 255 ) { ULONG volume; BYTE *volBytes = (BYTE*)&volume; // direct access to bytes volBytes[0] = 0; volBytes[1] = (BYTE)vol; // left volume volBytes[2] = 0; volBytes[3] = (BYTE)vol; // right volume waveOutSetVolume( 0, volume ); #ifdef POCKETPC RegWriteDW( HKEY_CURRENT_USER, L"ControlPanel\\Volume", L"Volume", volume ); #endif } return rc; } BOOL CmdVibrate( CInterpreter &interpreter, CStr &param ) { CValueArray params; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'Vibrate'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } #ifdef DESKTOP ::Beep( 440, (long)params[0] ); #endif #if ( ! defined PNA && ! defined DESKTOP ) #ifdef SMARTPHONE ::Vibrate(0,NULL,TRUE,INFINITE); #else ::Vibrate(); #endif ::Sleep( (long)params[0] ); ::VibrateStop(); #endif return TRUE; } BOOL CmdPlaySnd( CInterpreter &interpreter, CStr &param ) { CValueArray params; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'PlaySound'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } PlaySound( params[0], NULL, SND_FILENAME ); return TRUE; } #ifdef POCKETPC // GDI Escapes for ExtEscape() #define QUERYESCSUPPORT 8 // The following are unique to CE #define GETVFRAMEPHYSICAL 6144 #define GETVFRAMELEN 6145 #define DBGDRIVERSTAT 6146 #define SETPOWERMANAGEMENT 6147 #define GETPOWERMANAGEMENT 6148 typedef enum _VIDEO_POWER_STATE { VideoPowerOn = 1, VideoPowerStandBy, VideoPowerSuspend, VideoPowerOff } VIDEO_POWER_STATE, *PVIDEO_POWER_STATE; typedef struct _VIDEO_POWER_MANAGEMENT { ULONG Length; ULONG DPMSVersion; ULONG PowerState; } VIDEO_POWER_MANAGEMENT, *PVIDEO_POWER_MANAGEMENT; BOOL CmdSetBacklight( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params ) != 2 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'SetBacklight'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } DWORD bright = (long)params[0]; DWORD acBright = (long)params[1]; HKEY hKey = NULL; DWORD dwDisposition = 0; if ( RegCreateKeyEx( HKEY_CURRENT_USER, _T("ControlPanel\\Backlight"),0, NULL, 0, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition ) == ERROR_SUCCESS) { // Set backlight value for AC and Battery power if ( acBright >= 0 && acBright <= 100 ) RegSetValueEx( hKey, _T("ACBrightNess"), 0, REG_DWORD, (PBYTE)&acBright, sizeof(REG_DWORD) ); if ( bright >= 0 && bright <= 100 ) RegSetValueEx( hKey, _T("BrightNess"), 0, REG_DWORD, (PBYTE)&bright, sizeof(REG_DWORD) ); // Signal display driver to update HANDLE hBackLightEvent = CreateEvent( NULL, FALSE, TRUE, TEXT("BackLightChangeEvent")); if (hBackLightEvent) { SetEvent(hBackLightEvent); CloseHandle(hBackLightEvent); } } HDC gdc; int iESC=SETPOWERMANAGEMENT; gdc = ::GetDC( NULL ); VIDEO_POWER_MANAGEMENT vpm; vpm.Length = sizeof(VIDEO_POWER_MANAGEMENT); vpm.PowerState = VideoPowerOn; ExtEscape(gdc, SETPOWERMANAGEMENT, vpm.Length, (LPCSTR) &vpm, 0, NULL ); ::ReleaseDC( NULL, gdc ); return rc; } BOOL CmdToggleDisplay( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'ToggleDisplay'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } HDC gdc; int iESC=SETPOWERMANAGEMENT; gdc = ::GetDC( NULL ); VIDEO_POWER_MANAGEMENT vpm; vpm.Length = sizeof(VIDEO_POWER_MANAGEMENT); if ( (long)params[0] == 0 ) vpm.PowerState = VideoPowerOff; else vpm.PowerState = VideoPowerOn; ExtEscape(gdc, SETPOWERMANAGEMENT, vpm.Length, (LPCSTR) &vpm, 0, NULL ); ::ReleaseDC( NULL, gdc ); if ( (long)params[0] ) { typedef DWORD (*SetSystemPowerStateFunction)(LPCWSTR pwsSystemState, DWORD StateFlags, DWORD Options); HMODULE hModule = ::LoadLibrary(TEXT("Coredll.dll")); SetSystemPowerStateFunction f = (SetSystemPowerStateFunction)::GetProcAddress( hModule, TEXT("SetSystemPowerState") ); if ( f != NULL ) { f(NULL,POWER_STATE_ON,0); } ::FreeLibrary(hModule); } return TRUE; } CMapStrToPtr InputMethods; int SetInputEnumImProc( IMENUMINFO* pIMInfo ) { CLSID *tmpId = new CLSID(); memcpy( tmpId, &pIMInfo->clsid, sizeof(CLSID) ); InputMethods.SetAt( pIMInfo->szName, tmpId ); return TRUE; } BOOL CmdSetInput( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'SetInput'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } CLSID imSip; CStr clsidStr; if ( ((LPCTSTR)params[0])[0] != '{' ) { InputMethods.RemoveAll(); SipEnumIM( SetInputEnumImProc ); void *clsid; int found = InputMethods.Lookup( (LPCTSTR)params[0], clsid ); // CStr dbg; // dbg.Format( L"%d %d", found, clsid ); // MessageBox( GetMsgParent(), dbg, L"Debug", MB_OK ); if ( found ) imSip = *((CLSID*)clsid); CStr dummy; void *remClsId; int pos = InputMethods.GetStartPosition(); while ( pos != NULL ) { InputMethods.GetNextAssoc( pos, dummy, remClsId ); delete (CLSID*)remClsId; } InputMethods.RemoveAll(); if ( ! found ) { if ( interpreter.ErrorLevel >= ERROR_WARN ) MessageBox( GetMsgParent(), L"Unknown input type for 'SetInput'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return TRUE; } } else { clsidStr = (CStr)params[0]; int res = CLSIDFromString( (LPTSTR)(LPCTSTR)clsidStr, &imSip ); if ( res != NOERROR ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), L"Invalid CLSID for 'SetInput'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return TRUE; } } ::SipSetCurrentIM( &imSip ); return rc; } BOOL CmdShowInput( CInterpreter &interpreter, CStr &param ) { SipShowIM( SIPF_ON ); return TRUE; } BOOL CmdHideInput( CInterpreter &interpreter, CStr &param ) { SipShowIM( SIPF_OFF ); return TRUE; } BOOL CmdHardReset( CInterpreter &interpreter, CStr &param ) { CValue *hr; if ( Variables.Lookup( L"HARDRESET", hr ) == TRUE && (long)*hr == 1 ) { SetCleanRebootFlag(); KernelIoControl(IOCTL_HAL_REBOOT, NULL, 0, NULL, 0, NULL); return FALSE; } return TRUE; } #endif // PPC BOOL CmdGetClipText( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params, 1, 1 ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'GetClipText'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } CStr val; OpenClipboard(NULL); HANDLE clip=GetClipboardData(CF_UNICODETEXT); if ( clip != NULL ) { val.Format( L"%s", clip ); } CloseClipboard(); return interpreter.SetVariable( params[0], val ); } BOOL CmdSetClipText( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'SetClipText'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } int size = (((CStr)params.GetAt(0)).GetLength()+1) * sizeof(TCHAR); HLOCAL memUc = LocalAlloc( LMEM_ZEROINIT, size ); HLOCAL memAsc = LocalAlloc( LMEM_ZEROINIT, size ); memcpy( (void*)memUc, (LPCTSTR)params.GetAt(0), size ); WideCharToMultiByte( CP_ACP, 0, (LPCTSTR)params.GetAt(0), -1, (char*)memAsc, size, NULL, NULL ); OpenClipboard(NULL); EmptyClipboard(); SetClipboardData( CF_UNICODETEXT, memUc ); SetClipboardData( CF_TEXT, memAsc ); CloseClipboard(); return rc; } BOOL CmdSleep( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'Sleep'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } if ( GetMsgParent() != NULL ) WaitForSingleObject( ScriptAborted, (long)params[0] ); else ::Sleep( (long)params[0] ); return TRUE; } BOOL CmdGetTime( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; interpreter.Split( param, L',', params, 1, 0x3f ); // 0011 1111 if ( params.GetSize() < 1 || ( params.GetSize() > 3 && params.GetSize() != 6 ) ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'GetTime'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } SYSTEMTIME now; GetLocalTime( &now ); //CTime now = CTime::GetCurrentTime(); if ( params.GetSize() == 1 ) { CValue val; val = (long)SystemTimeToUnixTime( now ); rc = interpreter.SetVariable( params[0], val ); } if ( params.GetSize() == 2 ) { CStr hour24, hour12, ampm, minute, second, day, month, year, wday; CStr time = params.GetAt(1); hour24.Format( L"%02d", now.wHour ); int hour = now.wHour % 12; if ( hour == 0 ) hour = 12; hour12.Format( L"%02d", hour ); minute.Format( L"%02d", now.wMinute ); second.Format( L"%02d", now.wSecond ); ampm = (now.wHour < 12) ? L"AM" : L"PM"; day.Format( L"%02d", now.wDay ); month.Format( L"%02d", now.wMonth ); year.Format( L"%02d", now.wYear ); wday.Format( L"%d", now.wDayOfWeek ); time.Replace( L"H", hour24 ); time.Replace( L"h", hour12 ); time.Replace( L"i", minute ); time.Replace( L"s", second ); time.Replace( L"A", ampm ); ampm.MakeLower(); time.Replace( L"a", ampm ); time.Replace( L"d", day ); time.Replace( L"m", month ); time.Replace( L"Y", year ); year = year.Mid(2); time.Replace( L"y", year ); time.Replace( L"w", wday ); rc = interpreter.SetVariable( params[0], time ); } if ( params.GetSize() == 3 || params.GetSize() == 6 ) { CStr val; val.Format( L"%02d", (long)now.wHour ); rc = interpreter.SetVariable( params[0], val ); val.Format( L"%02d", (long)now.wMinute ); rc &= interpreter.SetVariable( params[1], val ); val.Format( L"%02d", (long)now.wSecond ); rc &= interpreter.SetVariable( params[2], val ); } if ( params.GetSize() == 6 ) { CStr val; val.Format( L"%02d", (long)now.wDay ); rc &= interpreter.SetVariable( params[3], val ); val.Format( L"%02d", (long)now.wMonth ); rc &= interpreter.SetVariable( params[4], val ); val.Format( L"%02d", (long)now.wYear ); rc &= interpreter.SetVariable( params[5], val ); } return rc; } BOOL CmdSetTime( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; interpreter.Split( param, L',', params ); if ( params.GetSize() != 1 && params.GetSize() != 3 && params.GetSize() != 6 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'GetTime'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } SYSTEMTIME now; GetLocalTime( &now ); if ( params.GetSize() == 1 ) { UnixTimeToSystemTime( (long)params[0], &now ); } if ( params.GetSize() == 3 || params.GetSize() == 6 ) { now.wHour =(unsigned short)(long)params[0]; now.wMinute = (unsigned short)(long)params[1]; now.wSecond = (unsigned short)(long)params[2]; } if ( params.GetSize() == 6 ) { now.wDay = (unsigned short)(long)params[3]; now.wMonth = (unsigned short)(long)params[4]; now.wYear = (unsigned short)(long)params[5]; } SetLocalTime( &now ); return rc; } BOOL CmdGetActiveProcess( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params, 1, 1 ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'GetActiveWindow'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } HWND hwnd = ::GetForegroundWindow(); TCHAR procName[256]; DWORD dwProcessID; ::GetWindowThreadProcessId(hwnd,&dwProcessID); if (!dwProcessID) { rc = interpreter.SetVariable( params[3], CValue() ); } else { ::GetModuleFileName((HMODULE)dwProcessID,procName,256); LPTSTR bs = wcsrchr( procName, '\\' ); if ( bs == NULL ) rc = interpreter.SetVariable( params[0], procName ); else rc = interpreter.SetVariable( params[0], bs+1 ); } return rc; } BOOL CmdGetSystemPath( CInterpreter &interpreter, CStr &param ) { CValueArray params; if ( interpreter.Split( param, L',', params, 1, 2 ) != 2 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'GetSystemPath'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } CStr path; LPTSTR pathBuffer = path.GetBuffer( MAX_PATH ); if ( ((CStr)params[0]).CompareNoCase( L"ProgramsMenu" ) == 0 ) { SHGetSpecialFolderPath( NULL, pathBuffer, CSIDL_PROGRAMS, FALSE ); } #ifndef SMARTPHONE else if ( ((CStr)params[0]).CompareNoCase( L"StartMenu" ) == 0 ) { SHGetSpecialFolderPath( NULL, pathBuffer, CSIDL_STARTMENU, FALSE ); } #endif else if ( ((CStr)params[0]).CompareNoCase( L"Startup" ) == 0 ) { SHGetSpecialFolderPath( NULL, pathBuffer, CSIDL_STARTUP, FALSE ); } else if ( ((CStr)params[0]).CompareNoCase( L"Documents" ) == 0 ) { #ifdef POCKETPC // Works only in WM2003 and later OSVERSIONINFO ver; GetVersionEx( &ver ); if ( ( ver.dwMajorVersion > 4 || (ver.dwMajorVersion == 4 && ver.dwMinorVersion >= 20) ) ) { SHGetDocumentsFolder( L"\\", pathBuffer ); } else { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) { MessageBox( GetMsgParent(), L"GetSystemPath: Document path requires WM2003" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); } } #else SHGetSpecialFolderPath( NULL, pathBuffer, CSIDL_PERSONAL, FALSE ); #endif } else if ( ((CStr)params[0]).CompareNoCase( L"ProgramFiles" ) == 0 ) { // Works only in WM2003 and later #ifndef DESKTOP OSVERSIONINFO ver; GetVersionEx( &ver ); if ( ( ver.dwMajorVersion > 4 || (ver.dwMajorVersion == 4 && ver.dwMinorVersion >= 20) ) ) { SHGetSpecialFolderPath( NULL, pathBuffer, CSIDL_PROGRAM_FILES, FALSE ); } else { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) { MessageBox( GetMsgParent(), L"GetSystemPath: Program files path requires WM2003" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); } } #else if ( SHGetSpecialFolderPath( NULL, pathBuffer, 0x0026, FALSE ) == FALSE ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) { MessageBox( GetMsgParent(), L"GetSystemPath: Retrieving program files path not supported by your system" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); } } #endif } else if ( ((CStr)params[0]).CompareNoCase( L"JScripts" ) == 0 || ((CStr)params[0]).CompareNoCase( L"ScriptPath" ) == 0) { int len = interpreter.ScriptFile.ReverseFind('\\'); wcsncpy( pathBuffer, (LPCTSTR)interpreter.ScriptFile, len ); pathBuffer[len] = '\0'; } else if ( ((CStr)params[0]).CompareNoCase( L"ScriptName" ) == 0 ) { int len = interpreter.ScriptFile.ReverseFind('\\'); int dot = interpreter.ScriptFile.ReverseFind('.'); wcsncpy( pathBuffer, (LPCTSTR)interpreter.ScriptFile+len+1, dot-len-1 ); pathBuffer[dot-len-1] = '\0'; } else if ( ((CStr)params[0]).CompareNoCase( L"ScriptExt" ) == 0 ) { int dot = interpreter.ScriptFile.ReverseFind('.'); wcscpy( pathBuffer, (LPCTSTR)interpreter.ScriptFile.Mid(dot) ); } #ifndef SMARTPHONE else if ( ((CStr)params[0]).CompareNoCase( L"ScriptExe" ) == 0 ) { int len = wcsrchr( theApp.m_pszHelpFilePath, '\\' ) - theApp.m_pszHelpFilePath; wcsncpy( pathBuffer, theApp.m_pszHelpFilePath, len ); pathBuffer[len] = '\0'; } #endif else { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) { MessageBox( GetMsgParent(), L"GetSystemPath: Invalid path type" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); } return FALSE; } path.ReleaseBuffer(); return interpreter.SetVariable( params[1], path ); } BOOL CmdGetMortScriptType( CInterpreter &interpreter, CStr &param ) { CValueArray params; if ( interpreter.Split( param, L',', params, 1, 1 ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'GetMortScriptType'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } #ifdef POCKETPC return interpreter.SetVariable( params[0], L"PPC" ); #endif #ifdef SMARTPHONE #ifdef PNA return interpreter.SetVariable( params[0], L"PNA" ); #else return interpreter.SetVariable( params[0], L"SP" ); #endif #endif #ifdef DESKTOP return interpreter.SetVariable( params[0], L"PC" ); #endif } BOOL CmdShowWaitCursor( CInterpreter &interpreter, CStr &param ) { SetCursor(LoadStdCursor(IDC_WAIT)); return TRUE; } BOOL CmdHideWaitCursor( CInterpreter &interpreter, CStr &param ) { SetCursor(LoadStdCursor(IDC_ARROW)); return TRUE; } BOOL CmdKill( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'Kill'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } //#ifndef PNA if ( LoadToolhelp() ) { CStr search = params[0]; BOOL fullPath = FALSE; if ( search.Find('\\') != -1 ) fullPath = TRUE; HANDLE procSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS|TH32CS_SNAPNOHEAPS, 0 ); PROCESSENTRY32 procEntry; procEntry.dwSize = sizeof( procEntry ); if ( procSnap != NULL && Process32First( procSnap, &procEntry ) ) { CStr procName; do { if ( fullPath ) { procName = GetProcessExePath( procEntry.th32ProcessID, procEntry.szExeFile ); } else { procName = procEntry.szExeFile; } if ( procName.CompareNoCase( search ) == 0 ) { HANDLE hProc = ::OpenProcess( PROCESS_TERMINATE, FALSE, procEntry.th32ProcessID ); if ( hProc != NULL ) { TerminateProcess( hProc, 0 ); CloseHandle( hProc ); } } procEntry.dwSize = sizeof( procEntry ); } while ( Process32Next( procSnap, &procEntry ) ); } if ( procSnap != NULL ) #ifdef DESKTOP CloseHandle( procSnap ); #else CloseToolhelp32Snapshot( procSnap ); #endif } else { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), L"'Kill' requires toolhelp.dll on your device" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } //#else // // Run external tool for PNAs // CStr runParams; // runParams = L"\"" + AppPath + L"\\killproc.exe\", \"" + (CStr)params[0] + L"\""; // RunApp( runParams, TRUE ); //#endif return rc; } BOOL CmdKillScript( CInterpreter &interpreter, CStr &param ) { BOOL rc = TRUE; CValueArray params; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'KillScript'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } CStr mutex; DWORD procId = GetRunningScriptProcId( params[0], &mutex ); if ( procId != NULL ) { RegWriteDW( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", mutex, 1 ); DWORD exitCode = 0; //for ( int i=0; i<=6; i++ ) //{ HANDLE hProc = OpenProcess( PROCESS_QUERY_INFORMATION|PROCESS_VM_READ|PROCESS_TERMINATE, FALSE, procId ); if ( hProc != NULL ) { for ( int i=0; i<6; i++ ) { if ( i != 0 ) ::Sleep( 500 ); if ( GetExitCodeProcess( hProc, &exitCode ) ) { if ( exitCode != STILL_ACTIVE ) { break; } } } if ( exitCode == STILL_ACTIVE ) { TerminateProcess( hProc, 0 ); HKEY key; if ( RegOpenKeyEx( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", 0, REG_ACCESS_WRITE, &key ) == ERROR_SUCCESS ) { RegDeleteValue( key, mutex ); RegCloseKey( key ); } if ( RegOpenKeyEx( HKEY_CURRENT_USER, L"Software\\JScripts\\Processes", 0, REG_ACCESS_WRITE, &key ) == ERROR_SUCCESS ) { RegDeleteValue( key, mutex ); RegCloseKey( key ); } } CloseHandle( hProc ); } //} } return rc; } BOOL RunApp( CInterpreter &interpreter, CStr &param, BOOL wait ) { CValueArray params; BOOL rc = TRUE; int parCnt = interpreter.Split( param, L',', params ); if ( parCnt < 1 || parCnt > 3 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'Run'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } if ( ! wait && ((CStr)params[0]).Right(4).CompareNoCase(L".lnk") == 0 ) { SHELLEXECUTEINFO sei; sei.cbSize = sizeof(SHELLEXECUTEINFO); sei.fMask = SEE_MASK_NOCLOSEPROCESS; sei.hwnd = NULL; sei.lpVerb = L"Open"; sei.lpFile = (LPCTSTR)params[0]; sei.lpDirectory = L"\\"; sei.lpParameters = NULL; if ( parCnt == 2 )sei.lpParameters = (LPCTSTR)params[1]; sei.nShow = SW_SHOW; sei.hInstApp = NULL; rc = ShellExecuteEx( &sei ) != 0; if ( rc ) CloseHandle( sei.hProcess ); } else { PROCESS_INFORMATION inf; CStr exe = params[0]; CStr param; if ( parCnt == 2 ) param = (CStr)params[1]; //Debug(exe,param); GetRunData( exe, param ); if ( ! exe.IsEmpty() ) { STARTUPINFO info; memset(&info, 0, sizeof(info)); info.cb = sizeof(info); info.wShowWindow = SW_SHOW; #ifdef DESKTOP info.dwFlags = STARTF_USESHOWWINDOW; memset(&inf, 0, sizeof(inf)); if ( ! param.IsEmpty() ) param = L"\"" + exe + L"\" " + param; #endif rc = CreateProcess( (LPCTSTR)exe, (param.IsEmpty()) ? NULL : (LPTSTR)(LPCTSTR)param, NULL, NULL, FALSE, 0, NULL, NULL, &info, &inf ); if ( rc ) { if ( wait ) { DWORD exitCode; while ( GetExitCodeProcess( inf.hProcess, &exitCode ) != FALSE && exitCode == STILL_ACTIVE ) { ::Sleep( 100 ); } } CloseHandle( inf.hProcess ); } /* else { int e = ::GetLastError(); CStr msg; msg.Format( L"%d", e ); MessageBox( GetMsgParent(), msg, L"Debug", MB_OK ); } */ } } return TRUE; } BOOL CmdRun( CInterpreter &interpreter, CStr &param ) { return RunApp( interpreter, param, FALSE ); } BOOL CmdRunWait( CInterpreter &interpreter, CStr &param ) { return RunApp( interpreter, param, TRUE ); } #ifdef POCKETPC #ifndef PNA BOOL CmdNew( CInterpreter &interpreter, CStr &param ) { CValueArray params; BOOL rc = TRUE; if ( interpreter.Split( param, L',', params ) != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'New'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } // Works only in WM2003 and later OSVERSIONINFO ver; GetVersionEx( &ver ); if ( ( ver.dwMajorVersion > 4 || (ver.dwMajorVersion == 4 && ver.dwMinorVersion >= 20) ) ) { // Search "New" item in Registry BOOL found = FALSE; HKEY key, newItemKey; if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Shell\\Extensions\\NewMenu", 0, REG_ACCESS_READ, &key ) == ERROR_SUCCESS ) { TCHAR subKeyName[50]; DWORD len = 50; for ( int i=0; RegEnumKeyEx( key, i, subKeyName, &len, NULL, NULL, NULL, NULL ) == ERROR_SUCCESS; i++ ) { if ( RegOpenKeyEx( key, subKeyName, 0, REG_ACCESS_READ, &newItemKey ) == ERROR_SUCCESS ) { DWORD type, length; TCHAR cont[MAX_PATH]; length = MAX_PATH; if ( RegQueryValueEx( newItemKey, NULL, NULL, &type, (BYTE*)cont, &length ) == ERROR_SUCCESS ) { if ( (CStr)params[0] == cont ) { // Found! Now covert the key name to clsid and create the item found = TRUE; CLSID clsid; CLSIDFromString( subKeyName, &clsid ); if ( SHCreateNewItem( NULL, clsid ) != NOERROR ) { if ( interpreter.ErrorLevel >= ERROR_ERROR ) { MessageBox( GetMsgParent(), L"New document could not be created" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); rc = FALSE; } } } } RegCloseKey( newItemKey ); } len = 50; } RegCloseKey( key ); if ( found == FALSE ) { if ( interpreter.ErrorLevel >= ERROR_ERROR ) { MessageBox( GetMsgParent(), L"New document could not be created" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); rc = FALSE; } } } } else { if ( interpreter.ErrorLevel >= ERROR_ERROR ) { MessageBox( GetMsgParent(), L"'New' requires at least WM2003" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); rc = FALSE; } } return rc; } #endif #endif #ifndef DESKTOP BOOL CmdRunOnPowerOn( CInterpreter &interpreter, CStr &param ) { CValueArray params; interpreter.Split( param, L',', params ) ; if ( params.GetSize() != 1 && params.GetSize() != 2 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'RunOnPowerOn'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } CE_NOTIFICATION_TRIGGER nt; // Fill in CE_NOTIFICATION_TRIGGER structure memset( &nt, 0, sizeof(CE_NOTIFICATION_TRIGGER) ); nt.dwSize = sizeof(CE_NOTIFICATION_TRIGGER); nt.dwType = CNT_EVENT; nt.dwEvent = NOTIFICATION_EVENT_WAKEUP; nt.lpszApplication = (TCHAR*)(LPCTSTR)params.GetAt(0); if ( params.GetSize() > 1 ) nt.lpszArguments = (TCHAR*)(LPCTSTR)params.GetAt(1); else nt.lpszArguments = NULL; // Call the function to register the notification if ( CeSetUserNotificationEx (0, &nt, NULL) == NULL ) { if ( interpreter.ErrorLevel >= ERROR_ERROR ) { MessageBox( GetMsgParent(), L"Couldn't set notification" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } } return TRUE; } BOOL CmdRunAt( CInterpreter &interpreter, CStr &param ) { CValueArray params; interpreter.Split( param, L',', params ) ; if ( params.GetSize() != 2 && params.GetSize() != 3 && params.GetSize() != 6 && params.GetSize() != 7 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'RunAt'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } CE_NOTIFICATION_TRIGGER nt; SYSTEMTIME alarmTime; int appidx; if ( params.GetSize() <= 3 ) { appidx = 1; UnixTimeToSystemTime( (long)params.GetAt(0), &alarmTime ); } else { appidx = 5; alarmTime.wYear = (USHORT)(long)params.GetAt(0); alarmTime.wMonth = (USHORT)(long)params.GetAt(1); alarmTime.wDay = (USHORT)(long)params.GetAt(2); alarmTime.wHour = (USHORT)(long)params.GetAt(3); alarmTime.wMinute = (USHORT)(long)params.GetAt(4); alarmTime.wSecond = 0; alarmTime.wMilliseconds = 0; alarmTime.wDayOfWeek = 0; } // Fill in CE_NOTIFICATION_TRIGGER structure memset( &nt, 0, sizeof(CE_NOTIFICATION_TRIGGER) ); nt.dwSize = sizeof(CE_NOTIFICATION_TRIGGER); nt.dwType = CNT_TIME; nt.stStartTime = alarmTime; nt.stEndTime = alarmTime; nt.lpszApplication = (TCHAR*)(LPCTSTR)params.GetAt(appidx); if ( params.GetSize() > appidx+1 ) nt.lpszArguments = (TCHAR*)(LPCTSTR)params.GetAt(appidx+1); else nt.lpszArguments = NULL; // Call the function to register the notification if ( CeSetUserNotificationEx (0, &nt, NULL) == NULL ) { if ( interpreter.ErrorLevel >= ERROR_ERROR ) { MessageBox( GetMsgParent(), L"Couldn't set notification" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } } return TRUE; } BOOL CmdRemoveNotifications( CInterpreter &interpreter, CStr &param ) { CValueArray params; interpreter.Split( param, L',', params ) ; if ( params.GetSize() != 1 && params.GetSize() != 2 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'RemoveNotifications'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } ULONG handleCount; CeGetUserNotificationHandles (NULL, 0, &handleCount); if ( handleCount > 0 ) { HANDLE *handles = new HANDLE[handleCount]; BOOL rc = CeGetUserNotificationHandles (handles, handleCount, &handleCount); if ( rc == TRUE ) { for ( UINT i=0; i < handleCount; i++ ) { CE_NOTIFICATION_INFO_HEADER *info; DWORD size, dwMaxNotifSize; CeGetUserNotification(handles[i], 0, &dwMaxNotifSize , NULL); if ( dwMaxNotifSize > 0 ) { BYTE *pNotifBuffer = new BYTE[dwMaxNotifSize]; if ( CeGetUserNotification(handles[i], dwMaxNotifSize, &size, pNotifBuffer) ) { info = (CE_NOTIFICATION_INFO_HEADER*)pNotifBuffer; CStr app = info->pcent->lpszApplication; CStr par = info->pcent->lpszArguments; if ( app.CompareNoCase( params.GetAt(0) ) == 0 && ( params.GetSize() == 1 || par.CompareNoCase( params.GetAt(1) ) == 0 ) ) { CeClearUserNotification(handles[i]); } } delete[] pNotifBuffer; } } } delete[] handles; } return TRUE; } #ifdef SMARTPHONE BOOL CmdSetBTState( CInterpreter &interpreter, CStr &param ) { CValueArray params; interpreter.Split( param, L',', params ) ; if ( params.GetSize() != 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'Set Bluetooth State'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } if ( (long)params[0]==2){ BthSetMode(BTH_DISCOVERABLE); }else if ( (long)params[0]==1){ BthSetMode(BTH_CONNECTABLE); }else if ( (long)params[0]==0 ){ BthSetMode(BTH_POWER_OFF); } return true; } BOOL CmdSetRadioMode( CInterpreter &interpreter, CStr &param ) { CValueArray params; interpreter.Split( param, L',', params ) ; if ( params.GetSize() > 1 ) { if ( interpreter.ErrorLevel >= ERROR_SYNTAX ) MessageBox( GetMsgParent(), InvalidParameterCount + L"'Set Bluetooth State'" + interpreter.GetErrorLine(), L"Error", MB_OK|MB_ICONERROR|MB_SETFOREGROUND ); return FALSE; } if ((long)params[0]==5 || ((CStr)params[0]).CompareNoCase(L"On")==0){ Flight(0); }else if ((long)params[0]==1 || ((CStr)params[0]).CompareNoCase(L"Off")==0){ Flight(1); }else{ Flight(2); } return true; } #endif #endif
[ "frezgo@c2805876-21d7-11df-8c35-9da929d3dec4" ]
[ [ [ 1, 1486 ] ] ]
2938c3eb2f3c5d790e52bcddb77b215c387dac02
ac559231a41a5833220a1319456073365f13d484
/src/vision/Modified_Files_for_Testing/test_grt_rtw/test.cpp
8508b30a544870896d97953677ddd6bfc949e51c
[]
no_license
mtboswell/mtboswell-auvc2
6521002ca12f9f7e1ec5df781ed03419129b8f56
02bb0dd47936967a7b9fa7d091398812f441c1dc
refs/heads/master
2020-04-01T23:02:15.282160
2011-07-17T16:48:34
2011-07-17T16:48:34
32,832,956
0
0
null
null
null
null
UTF-8
C++
false
false
68,046
cpp
/* * test.cpp * * Real-Time Workshop code generation for Simulink model "test.mdl". * * Model version : 1.36 * Real-Time Workshop version : 7.6 (R2010b) 03-Aug-2010 * C++ source code generated on : Fri Jun 03 07:34:21 2011 * * Target selection: grt.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: 32-bit Generic * Code generation objectives: Unspecified * Validation result: Not run */ #include "test.h" #include "test_private.h" /* Block signals (auto storage) */ BlockIO_test test_B; /* Block states (auto storage) */ D_Work_test test_DWork; /* External inputs (root inport signals with auto storage) */ ExternalInputs_test test_U; /* External outputs (root outports fed by signals with auto storage) */ ExternalOutputs_test test_Y; /* Real-time model */ RT_MODEL_test test_M_; RT_MODEL_test *test_M = &test_M_; int32_T div_s32_floor(int32_T numerator, int32_T denominator) { int32_T quotient; uint32_T absNumerator; uint32_T absDenominator; uint32_T tempAbsQuotient; uint32_T quotientNeedsNegation; if (denominator == 0) { quotient = numerator >= 0 ? MAX_int32_T : MIN_int32_T; /* divide by zero handler */ } else { absNumerator = (uint32_T)(numerator >= 0 ? numerator : -numerator); absDenominator = (uint32_T)(denominator >= 0 ? denominator : -denominator); quotientNeedsNegation = ((numerator < 0) != (denominator < 0)); tempAbsQuotient = absNumerator / absDenominator; if (quotientNeedsNegation) { absNumerator = absNumerator % absDenominator; if (absNumerator > (uint32_T)0) { tempAbsQuotient = tempAbsQuotient + (uint32_T)1; } } quotient = quotientNeedsNegation ? (int32_T)(-((int32_T)tempAbsQuotient)) : (int32_T)tempAbsQuotient; } return quotient; } /* Model output function */ static void test_output(int_T tid) { /* local block i/o variables */ real_T rtb_VariableSelector; real_T rtb_VariableSelector1; boolean_T isInBound; boolean_T visited; boolean_T visited_0; int32_T numElem; int32_T imgIdxLL; int32_T imgIdxUR; int32_T imgIdxLR; int32_T imgCol; int32_T imgRow; real_T accumOne; real_T accumTwo; int32_T m; real_T accumThree; real_T accumFour; int32_T colsInMinus; int32_T countPeak; boolean_T done; int32_T q; int32_T jRowsIn; uint32_T rtb_FindLocalMaxima[2]; int32_T line_idx; int32_T line_idx_0; int32_T line_idx_1; /* S-Function (svipcolorconv): '<S1>/Color Space Conversion' incorporates: * Inport: '<Root>/B_forward_in' * Inport: '<Root>/G_forward_in' * Inport: '<Root>/R_forward_in' */ for (m = 0; m < 19200; m++) { test_B.ColorSpaceConversion[m] = (test_U.R_forward_in[m] * 0.299 + test_U.G_forward_in[m] * 0.587) + test_U.B_forward_in[m] * 0.114; if (test_B.ColorSpaceConversion[m] > 1.0) { test_B.ColorSpaceConversion[m] = 1.0; } else { if (test_B.ColorSpaceConversion[m] < 0.0) { test_B.ColorSpaceConversion[m] = 0.0; } } } /* S-Function (svipedge): '<Root>/Edge Detection' */ for (imgCol = 1; imgCol < 159; imgCol++) { for (imgRow = 1; imgRow < 119; imgRow++) { accumOne = 0.0; accumTwo = 0.0; q = imgCol * 120 + imgRow; for (m = 0; m < 6; m++) { accumOne += test_B.ColorSpaceConversion[q + test_DWork.EdgeDetection_VO_DW[m]] * test_ConstP.EdgeDetection_VC_RTP[m]; accumTwo += test_B.ColorSpaceConversion[q + test_DWork.EdgeDetection_HO_DW[m]] * test_ConstP.EdgeDetection_HC_RTP[m]; } test_DWork.EdgeDetection_GV_SQUARED_DW[q] = accumOne * accumOne; test_DWork.EdgeDetection_GH_SQUARED_DW[q] = accumTwo * accumTwo; } } for (imgCol = 1; imgCol < 159; imgCol++) { accumOne = 0.0; accumTwo = 0.0; accumThree = 0.0; accumFour = 0.0; jRowsIn = imgCol * 120; q = imgCol * 120 + 119; for (m = 0; m < 6; m++) { accumOne += test_B.ColorSpaceConversion[jRowsIn + test_DWork.EdgeDetection_HOU_DW[m]] * test_ConstP.EdgeDetection_HC_RTP[m]; accumTwo += test_B.ColorSpaceConversion[q + test_DWork.EdgeDetection_HOD_DW[m]] * test_ConstP.EdgeDetection_HC_RTP[m]; accumThree += test_B.ColorSpaceConversion[jRowsIn + test_DWork.EdgeDetection_VOU_DW[m]] * test_ConstP.EdgeDetection_VC_RTP[m]; accumFour += test_B.ColorSpaceConversion[q + test_DWork.EdgeDetection_VOD_DW[m]] * test_ConstP.EdgeDetection_VC_RTP[m]; } test_DWork.EdgeDetection_GV_SQUARED_DW[jRowsIn] = accumThree * accumThree; test_DWork.EdgeDetection_GH_SQUARED_DW[jRowsIn] = accumOne * accumOne; test_DWork.EdgeDetection_GV_SQUARED_DW[q] = accumFour * accumFour; test_DWork.EdgeDetection_GH_SQUARED_DW[q] = accumTwo * accumTwo; } for (imgRow = 1; imgRow < 119; imgRow++) { accumOne = 0.0; accumTwo = 0.0; accumThree = 0.0; accumFour = 0.0; q = 19080 + imgRow; for (m = 0; m < 6; m++) { accumOne += test_B.ColorSpaceConversion[imgRow + test_DWork.EdgeDetection_VOL_DW[m]] * test_ConstP.EdgeDetection_VC_RTP[m]; accumTwo += test_B.ColorSpaceConversion[q + test_DWork.EdgeDetection_VOR_DW[m]] * test_ConstP.EdgeDetection_VC_RTP[m]; accumThree += test_B.ColorSpaceConversion[imgRow + test_DWork.EdgeDetection_HOL_DW[m]] * test_ConstP.EdgeDetection_HC_RTP[m]; accumFour += test_B.ColorSpaceConversion[q + test_DWork.EdgeDetection_HOR_DW[m]] * test_ConstP.EdgeDetection_HC_RTP[m]; } test_DWork.EdgeDetection_GV_SQUARED_DW[imgRow] = accumOne * accumOne; test_DWork.EdgeDetection_GH_SQUARED_DW[imgRow] = accumThree * accumThree; test_DWork.EdgeDetection_GV_SQUARED_DW[q] = accumTwo * accumTwo; test_DWork.EdgeDetection_GH_SQUARED_DW[q] = accumFour * accumFour; } accumOne = 0.0; accumTwo = 0.0; accumThree = 0.0; accumFour = 0.0; for (m = 0; m < 6; m++) { accumOne += test_B.ColorSpaceConversion[test_DWork.EdgeDetection_VOUL_DW[m]] * test_ConstP.EdgeDetection_VC_RTP[m]; accumTwo += test_B.ColorSpaceConversion[test_DWork.EdgeDetection_HOUL_DW[m]] * test_ConstP.EdgeDetection_HC_RTP[m]; accumThree += test_B.ColorSpaceConversion[119 + test_DWork.EdgeDetection_VOLL_DW[m]] * test_ConstP.EdgeDetection_VC_RTP[m]; accumFour += test_B.ColorSpaceConversion[119 + test_DWork.EdgeDetection_HOLL_DW[m]] * test_ConstP.EdgeDetection_HC_RTP[m]; } test_DWork.EdgeDetection_GV_SQUARED_DW[0] = accumOne * accumOne; test_DWork.EdgeDetection_GH_SQUARED_DW[0] = accumTwo * accumTwo; test_DWork.EdgeDetection_GV_SQUARED_DW[119] = accumThree * accumThree; test_DWork.EdgeDetection_GH_SQUARED_DW[119] = accumFour * accumFour; accumOne = 0.0; accumTwo = 0.0; accumThree = 0.0; accumFour = 0.0; for (m = 0; m < 6; m++) { accumOne += test_B.ColorSpaceConversion[19080 + test_DWork.EdgeDetection_VOUR_DW[m]] * test_ConstP.EdgeDetection_VC_RTP[m]; accumTwo += test_B.ColorSpaceConversion[19080 + test_DWork.EdgeDetection_HOUR_DW[m]] * test_ConstP.EdgeDetection_HC_RTP[m]; accumThree += test_B.ColorSpaceConversion[19199 + test_DWork.EdgeDetection_VOLR_DW[m]] * test_ConstP.EdgeDetection_VC_RTP[m]; accumFour += test_B.ColorSpaceConversion[19199 + test_DWork.EdgeDetection_HOLR_DW[m]] * test_ConstP.EdgeDetection_HC_RTP[m]; } test_DWork.EdgeDetection_GV_SQUARED_DW[19080] = accumOne * accumOne; test_DWork.EdgeDetection_GH_SQUARED_DW[19080] = accumTwo * accumTwo; test_DWork.EdgeDetection_GV_SQUARED_DW[19199] = accumThree * accumThree; test_DWork.EdgeDetection_GH_SQUARED_DW[19199] = accumFour * accumFour; accumTwo = 0.0; for (m = 0; m < 19200; m++) { test_DWork.EdgeDetection_GRAD_SUM_DW[m] = test_DWork.EdgeDetection_GV_SQUARED_DW[m]; test_DWork.EdgeDetection_GRAD_SUM_DW[m] = test_DWork.EdgeDetection_GRAD_SUM_DW[m] + test_DWork.EdgeDetection_GH_SQUARED_DW[m]; accumTwo += test_DWork.EdgeDetection_GRAD_SUM_DW[m] * test_DWork.EdgeDetection_MEAN_FACTOR_DW; } accumOne = test_P.EdgeDetection_THRESH_TUNING_RTP * accumTwo; for (imgCol = 0; imgCol < 160; imgCol++) { for (imgRow = 0; imgRow < 120; imgRow++) { m = imgCol * 120 + imgRow; test_B.EdgeDetection[m] = ((test_DWork.EdgeDetection_GRAD_SUM_DW[m] > accumOne) && (((test_DWork.EdgeDetection_GV_SQUARED_DW[m] >= test_DWork.EdgeDetection_GH_SQUARED_DW[m]) && (imgCol != 0 ? test_DWork.EdgeDetection_GRAD_SUM_DW[m - 120] <= test_DWork.EdgeDetection_GRAD_SUM_DW[m] : TRUE) && (imgCol != 159 ? test_DWork.EdgeDetection_GRAD_SUM_DW[m] > test_DWork.EdgeDetection_GRAD_SUM_DW[m + 120] : TRUE)) || ((test_DWork.EdgeDetection_GH_SQUARED_DW[m] >= test_DWork.EdgeDetection_GV_SQUARED_DW[m]) && (imgRow != 0 ? test_DWork.EdgeDetection_GRAD_SUM_DW[m - 1] <= test_DWork.EdgeDetection_GRAD_SUM_DW[m] : TRUE) && (imgRow != 119 ? test_DWork.EdgeDetection_GRAD_SUM_DW[m] > test_DWork.EdgeDetection_GRAD_SUM_DW[m + 1] : TRUE)))); } } /* S-Function (sviphough): '<Root>/Hough Transform' */ MWVIP_Hough_D(&test_B.EdgeDetection[0], &test_B.HoughTransform_o1[0], &test_ConstP.HoughTransform_SINE_[0], &test_ConstP.HoughTransform_FIRSTRHO_RT, 120, 160, 399, 91); /* Embedded MATLAB: '<Root>/Embedded MATLAB Function' */ /* Embedded MATLAB Function 'Embedded MATLAB Function': '<S2>:1' */ /* '<S2>:1:4' */ memcpy((void *)(&test_B.y[0]), (void *)(&test_B.HoughTransform_o1[0]), 71820U * sizeof(real_T)); /* S-Function (svipfindlocalmax): '<Root>/Find Local Maxima' */ countPeak = 0; done = FALSE; memcpy((void *)(&test_DWork.FindLocalMaxima_TEMP_IN_DWORKS[0]), (void *) (&test_B.y[0]), (uint32_T)(71820 * (int32_T)MWDSP_SIZEOF_DOUBLE)); memset((void *)&rtb_FindLocalMaxima[0], 0, (uint32_T)((int32_T) MWDSP_SIZEOF_INT32 << 1U)); while (!done) { imgRow = 0; accumOne = test_DWork.FindLocalMaxima_TEMP_IN_DWORKS[0]; for (m = 0; m < 71820; m++) { if (test_DWork.FindLocalMaxima_TEMP_IN_DWORKS[m] > accumOne) { imgRow = m; accumOne = test_DWork.FindLocalMaxima_TEMP_IN_DWORKS[m]; } } imgCol = imgRow % 399; q = imgRow / 399; if (test_DWork.FindLocalMaxima_TEMP_IN_DWORKS[imgRow] >= test_P.FindLocalMaxima_THRESHOLD_RTP) { rtb_FindLocalMaxima[countPeak << 1U] = (uint32_T)imgCol; rtb_FindLocalMaxima[(countPeak << 1U) + 1] = (uint32_T)q; countPeak++; if (countPeak == 1) { done = TRUE; } m = imgCol - 2; imgIdxLR = m >= 0 ? m : 0; m = imgCol + 2; imgIdxLL = m <= 398 ? m : 398; imgIdxUR = q - 3; q += 3; if (!((imgIdxUR < 0) || (q > 179))) { while (imgIdxUR <= q) { jRowsIn = imgIdxUR * 399; for (m = imgIdxLR; m <= imgIdxLL; m++) { test_DWork.FindLocalMaxima_TEMP_IN_DWORKS[m + jRowsIn] = 0.0; } imgIdxUR++; } } else { if (imgIdxUR < 0) { for (numElem = imgIdxUR; numElem <= q; numElem++) { if (numElem < 0) { imgRow = (numElem + 180) * 399; for (m = imgIdxLR; m <= imgIdxLL; m++) { test_DWork.FindLocalMaxima_TEMP_IN_DWORKS[(398 - m) + imgRow] = 0.0; } } else { jRowsIn = numElem * 399; for (m = imgIdxLR; m <= imgIdxLL; m++) { test_DWork.FindLocalMaxima_TEMP_IN_DWORKS[m + jRowsIn] = 0.0; } } } } if (q > 179) { for (numElem = imgIdxUR; numElem <= q; numElem++) { if (numElem > 179) { imgRow = (numElem - 180) * 399; for (m = imgIdxLR; m <= imgIdxLL; m++) { test_DWork.FindLocalMaxima_TEMP_IN_DWORKS[(398 - m) + imgRow] = 0.0; } } else { jRowsIn = numElem * 399; for (m = imgIdxLR; m <= imgIdxLL; m++) { test_DWork.FindLocalMaxima_TEMP_IN_DWORKS[m + jRowsIn] = 0.0; } } } } } } else { done = TRUE; } } test_DWork.FindLocalMaxima_NUMPEAKS_DWORK = (uint32_T)countPeak; test_DWork.FindLocalMaxima_DIMS1[1] = (int32_T) test_DWork.FindLocalMaxima_NUMPEAKS_DWORK; /* Selector: '<Root>/Selector1' */ test_B.Selector = rtb_FindLocalMaxima[(int32_T)0.0]; /* Signal Processing Blockset Variable Selector (sdspperm2) - '<Root>/Variable Selector' */ /* Permute columns port 0 input columns = 180, output columns = 1 */ { int32_T i_idx = (int32_T)(test_B.Selector ); /* Clip bad index */ if (i_idx < 0) { i_idx = 0; } else if (i_idx > 179) { i_idx = 179; } rtb_VariableSelector = test_B.HoughTransform_o2[i_idx]; } /* Selector: '<Root>/Selector' */ test_B.Selector = rtb_FindLocalMaxima[(int32_T)0.0]; /* Signal Processing Blockset Variable Selector (sdspperm2) - '<Root>/Variable Selector1' */ /* Permute columns port 0 input columns = 399, output columns = 1 */ { int32_T i_idx = (int32_T)(test_B.Selector ); /* Clip bad index */ if (i_idx < 0) { i_idx = 0; } else if (i_idx > 398) { i_idx = 398; } rtb_VariableSelector1 = test_B.HoughTransform_o3[i_idx]; } /* S-Function (sviphoughlines): '<Root>/Hough Lines' */ jRowsIn = 0; accumOne = (rtb_VariableSelector1 + 2.2204460492503131E-16) / (cos (rtb_VariableSelector) + 2.2204460492503131E-16); /* part-1: top horizontal axis */ accumTwo = floor(accumOne + 0.5); if ((accumTwo >= 0.0) && (accumTwo <= 159.0)) { test_B.HoughLines[0] = 0; test_B.HoughLines[1] = (int32_T)floor((real_T)(int32_T)accumTwo + 0.5); jRowsIn = 1; } accumThree = (rtb_VariableSelector1 + 2.2204460492503131E-16) / (sin (rtb_VariableSelector) + 2.2204460492503131E-16); /* part-2: left vertical axis */ accumTwo = floor(accumThree + 0.5); if ((accumTwo >= 0.0) && (accumTwo <= 119.0)) { test_B.HoughLines[(jRowsIn << 1)] = (int32_T)floor((real_T)(int32_T)accumTwo + 0.5); test_B.HoughLines[1 + (jRowsIn << 1)] = 0; jRowsIn++; } /* part-3: Right vertical axis */ if (jRowsIn < 2) { accumTwo = floor((accumOne - 159.0) * (accumThree / accumOne) + 0.5); if ((accumTwo >= 0.0) && (accumTwo <= 119.0)) { test_B.HoughLines[(jRowsIn << 1)] = (int32_T)floor((real_T)(int32_T) accumTwo + 0.5); test_B.HoughLines[1 + (jRowsIn << 1)] = 159; jRowsIn++; } } /* part-4: bottom horizontal axis */ if (jRowsIn < 2) { accumTwo = floor((accumOne - accumOne / accumThree * 119.0) + 0.5); if ((accumTwo >= 0.0) && (accumTwo <= 159.0)) { test_B.HoughLines[(jRowsIn << 1)] = 119; test_B.HoughLines[1 + (jRowsIn << 1)] = (int32_T)floor((real_T)(int32_T) accumTwo + 0.5); jRowsIn++; } } if (jRowsIn < 2) { test_B.HoughLines[0] = -1; test_B.HoughLines[1] = -1; test_B.HoughLines[2] = -1; test_B.HoughLines[3] = -1; } /* S-Function (svipdrawshapes): '<Root>/Draw Shapes' */ /* Copy the image from input to output. */ memcpy((void *)(&test_DWork.EdgeDetection_GV_SQUARED_DW[0]), (void *) (&test_B.ColorSpaceConversion[0]), 19200U * sizeof(real_T)); colsInMinus = 0; for (m = 0; m < 1; m = 1) { imgIdxLL = test_B.HoughLines[colsInMinus]; imgCol = test_B.HoughLines[colsInMinus + 1]; numElem = test_B.HoughLines[colsInMinus + 2]; imgIdxLR = test_B.HoughLines[colsInMinus + 3]; if ((test_B.HoughLines[colsInMinus + 2] != test_B.HoughLines[colsInMinus]) || (test_B.HoughLines[colsInMinus + 1] != test_B.HoughLines[colsInMinus + 3])) { isInBound = FALSE; /* Find the visible portion of a line. */ visited = FALSE; visited_0 = FALSE; done = FALSE; imgIdxUR = test_B.HoughLines[colsInMinus]; line_idx_1 = test_B.HoughLines[colsInMinus + 1]; line_idx_0 = test_B.HoughLines[colsInMinus + 2]; line_idx = test_B.HoughLines[colsInMinus + 3]; while (!done) { m = 0; countPeak = 0; /* Determine viewport violations. */ if (imgIdxUR < 0) { m = 4; } else { if (imgIdxUR > 119) { m = 8; } } if (line_idx_0 < 0) { countPeak = 4; } else { if (line_idx_0 > 119) { countPeak = 8; } } if (line_idx_1 < 0) { m = (int32_T)((uint32_T)m | 1U); } else { if (line_idx_1 > 159) { m = (int32_T)((uint32_T)m | 2U); } } if (line_idx < 0) { countPeak = (int32_T)((uint32_T)countPeak | 1U); } else { if (line_idx > 159) { countPeak = (int32_T)((uint32_T)countPeak | 2U); } } if (!((uint32_T)m | (uint32_T)countPeak)) { /* Line falls completely within bounds. */ done = TRUE; isInBound = TRUE; } else if ((uint32_T)m & (uint32_T)countPeak) { /* Line falls completely out of bounds. */ done = TRUE; isInBound = FALSE; } else if ((uint32_T)m != 0U) { /* Clip 1st point; if it's in-bounds, clip 2nd point. */ if (visited) { imgIdxUR = imgIdxLL; line_idx_1 = imgCol; } q = line_idx_0 - imgIdxUR; imgRow = line_idx - line_idx_1; if ((uint32_T)m & 4U) { /* Violated RMin. */ jRowsIn = (0 - imgIdxUR) * imgRow; if (((jRowsIn >= 0) && (q >= 0)) || ((jRowsIn < 0) && (q < 0))) { line_idx_1 += (div_s32_floor(jRowsIn << 1U, q) + 1) >> 1; } else { line_idx_1 += -((div_s32_floor((-jRowsIn) << 1U, q) + 1) >> 1); } imgIdxUR = 0; visited = TRUE; } else if ((uint32_T)m & 8U) { /* Violated RMax. */ jRowsIn = (119 - imgIdxUR) * imgRow; if (((jRowsIn >= 0) && (q >= 0)) || ((jRowsIn < 0) && (q < 0))) { line_idx_1 += (div_s32_floor(jRowsIn << 1U, q) + 1) >> 1; } else { line_idx_1 += -((div_s32_floor((-jRowsIn) << 1U, q) + 1) >> 1); } imgIdxUR = 119; visited = TRUE; } else if ((uint32_T)m & 1U) { /* Violated CMin. */ jRowsIn = (0 - line_idx_1) * q; if (((jRowsIn >= 0) && (imgRow >= 0)) || ((jRowsIn < 0) && (imgRow < 0))) { imgIdxUR += (div_s32_floor(jRowsIn << 1U, imgRow) + 1) >> 1; } else { imgIdxUR += -((div_s32_floor((-jRowsIn) << 1U, imgRow) + 1) >> 1); } line_idx_1 = 0; visited = TRUE; } else { /* Violated CMax. */ jRowsIn = (159 - line_idx_1) * q; if (((jRowsIn >= 0) && (imgRow >= 0)) || ((jRowsIn < 0) && (imgRow < 0))) { imgIdxUR += (div_s32_floor(jRowsIn << 1U, imgRow) + 1) >> 1; } else { imgIdxUR += -((div_s32_floor((-jRowsIn) << 1U, imgRow) + 1) >> 1); } line_idx_1 = 159; visited = TRUE; } } else { /* Clip the 2nd point. */ if (visited_0) { line_idx_0 = numElem; line_idx = imgIdxLR; } q = line_idx_0 - imgIdxUR; imgRow = line_idx - line_idx_1; if ((uint32_T)countPeak & 4U) { /* Violated RMin. */ jRowsIn = (0 - line_idx_0) * imgRow; if (((jRowsIn >= 0) && (q >= 0)) || ((jRowsIn < 0) && (q < 0))) { line_idx += (div_s32_floor(jRowsIn << 1U, q) + 1) >> 1; } else { line_idx += -((div_s32_floor((-jRowsIn) << 1U, q) + 1) >> 1); } line_idx_0 = 0; visited_0 = TRUE; } else if ((uint32_T)countPeak & 8U) { /* Violated RMax. */ jRowsIn = (119 - line_idx_0) * imgRow; if (((jRowsIn >= 0) && (q >= 0)) || ((jRowsIn < 0) && (q < 0))) { line_idx += (div_s32_floor(jRowsIn << 1U, q) + 1) >> 1; } else { line_idx += -((div_s32_floor((-jRowsIn) << 1U, q) + 1) >> 1); } line_idx_0 = 119; visited_0 = TRUE; } else if ((uint32_T)countPeak & 1U) { /* Violated CMin. */ jRowsIn = (0 - line_idx) * q; if (((jRowsIn >= 0) && (imgRow >= 0)) || ((jRowsIn < 0) && (imgRow < 0))) { line_idx_0 += (div_s32_floor(jRowsIn << 1U, imgRow) + 1) >> 1; } else { line_idx_0 += -((div_s32_floor((-jRowsIn) << 1U, imgRow) + 1) >> 1); } line_idx = 0; visited_0 = TRUE; } else { /* Violated CMax. */ jRowsIn = (159 - line_idx) * q; if (((jRowsIn >= 0) && (imgRow >= 0)) || ((jRowsIn < 0) && (imgRow < 0))) { line_idx_0 += (div_s32_floor(jRowsIn << 1U, imgRow) + 1) >> 1; } else { line_idx_0 += -((div_s32_floor((-jRowsIn) << 1U, imgRow) + 1) >> 1); } line_idx = 159; visited_0 = TRUE; } } } if (isInBound) { /* Draw a line using Bresenham algorithm. */ /* Initialize the Bresenham algorithm. */ if (line_idx_0 >= imgIdxUR) { q = line_idx_0 - imgIdxUR; } else { q = imgIdxUR - line_idx_0; } if (line_idx >= line_idx_1) { imgRow = line_idx - line_idx_1; } else { imgRow = line_idx_1 - line_idx; } if (q > imgRow) { jRowsIn = 1; imgCol = 120; } else { jRowsIn = 120; imgCol = 1; q = imgIdxUR; imgIdxUR = line_idx_1; line_idx_1 = q; q = line_idx_0; line_idx_0 = line_idx; line_idx = q; } if (imgIdxUR > line_idx_0) { q = imgIdxUR; imgIdxUR = line_idx_0; line_idx_0 = q; q = line_idx_1; line_idx_1 = line_idx; line_idx = q; } numElem = line_idx_0 - imgIdxUR; if (line_idx_1 <= line_idx) { imgRow = 1; imgIdxLL = line_idx - line_idx_1; } else { imgRow = -1; imgIdxLL = line_idx_1 - line_idx; } imgIdxLR = -((numElem + 1) >> 1); m = imgIdxUR * jRowsIn + line_idx_1 * imgCol; imgRow = imgRow * imgCol + jRowsIn; for (done = (imgIdxUR <= line_idx_0); done; done = (imgIdxUR <= line_idx_0)) { test_DWork.EdgeDetection_GV_SQUARED_DW[m] = 1.0; /* Compute the next location using Bresenham algorithm. */ /* Move to the next pixel location. */ imgIdxLR += imgIdxLL; if (imgIdxLR >= 0) { imgIdxLR -= numElem; m += imgRow; } else { m += jRowsIn; } imgIdxUR++; } } } colsInMinus += 2; } /* Outport: '<Root>/Out1' */ memcpy((void *)(&test_Y.Out1[0]), (void *) (&test_DWork.EdgeDetection_GV_SQUARED_DW[0]), 19200U * sizeof(real_T)); /* tid is required for a uniform function interface. * Argument tid is not used in the function. */ UNUSED_PARAMETER(tid); } /* Model update function */ static void test_update(int_T tid) { /* Update absolute time for base rate */ /* The "clockTick0" counts the number of times the code of this task has * been executed. The absolute time is the multiplication of "clockTick0" * and "Timing.stepSize0". Size of "clockTick0" ensures timer will not * overflow during the application lifespan selected. * Timer of this task consists of two 32 bit unsigned integers. * The two integers represent the low bits Timing.clockTick0 and the high bits * Timing.clockTickH0. When the low bit overflows to 0, the high bits increment. */ if (!(++test_M->Timing.clockTick0)) { ++test_M->Timing.clockTickH0; } test_M->Timing.t[0] = test_M->Timing.clockTick0 * test_M->Timing.stepSize0 + test_M->Timing.clockTickH0 * test_M->Timing.stepSize0 * 4294967296.0; /* tid is required for a uniform function interface. * Argument tid is not used in the function. */ UNUSED_PARAMETER(tid); } /* Model initialize function */ void test_initialize(boolean_T firstTime) { (void)firstTime; /* Registration code */ /* initialize non-finites */ rt_InitInfAndNaN(sizeof(real_T)); /* initialize real-time model */ (void) memset((void *)test_M, 0, sizeof(RT_MODEL_test)); /* Initialize timing info */ { int_T *mdlTsMap = test_M->Timing.sampleTimeTaskIDArray; mdlTsMap[0] = 0; test_M->Timing.sampleTimeTaskIDPtr = (&mdlTsMap[0]); test_M->Timing.sampleTimes = (&test_M->Timing.sampleTimesArray[0]); test_M->Timing.offsetTimes = (&test_M->Timing.offsetTimesArray[0]); /* task periods */ test_M->Timing.sampleTimes[0] = (0.033333333333333333); /* task offsets */ test_M->Timing.offsetTimes[0] = (0.0); } rtmSetTPtr(test_M, &test_M->Timing.tArray[0]); { int_T *mdlSampleHits = test_M->Timing.sampleHitArray; mdlSampleHits[0] = 1; test_M->Timing.sampleHits = (&mdlSampleHits[0]); } rtmSetTFinal(test_M, 0.0); test_M->Timing.stepSize0 = 0.033333333333333333; /* Setup for data logging */ { static RTWLogInfo rt_DataLoggingInfo; test_M->rtwLogInfo = &rt_DataLoggingInfo; } /* Setup for data logging */ { rtliSetLogXSignalInfo(test_M->rtwLogInfo, (NULL)); rtliSetLogXSignalPtrs(test_M->rtwLogInfo, (NULL)); rtliSetLogT(test_M->rtwLogInfo, "tout"); rtliSetLogX(test_M->rtwLogInfo, ""); rtliSetLogXFinal(test_M->rtwLogInfo, ""); rtliSetSigLog(test_M->rtwLogInfo, ""); rtliSetLogVarNameModifier(test_M->rtwLogInfo, "rt_"); rtliSetLogFormat(test_M->rtwLogInfo, 0); rtliSetLogMaxRows(test_M->rtwLogInfo, 1000); rtliSetLogDecimation(test_M->rtwLogInfo, 1); /* * Set pointers to the data and signal info for each output */ { static void * rt_LoggedOutputSignalPtrs[] = { &test_Y.Out1[0] }; rtliSetLogYSignalPtrs(test_M->rtwLogInfo, ((LogSignalPtrsType) rt_LoggedOutputSignalPtrs)); } { static int_T rt_LoggedOutputWidths[] = { 19200 }; static int_T rt_LoggedOutputNumDimensions[] = { 2 }; static int_T rt_LoggedOutputDimensions[] = { 120, 160 }; static boolean_T rt_LoggedOutputIsVarDims[] = { 0 }; static int_T* rt_LoggedCurrentSignalDimensions[] = { (NULL), (NULL) }; static BuiltInDTypeId rt_LoggedOutputDataTypeIds[] = { SS_DOUBLE }; static int_T rt_LoggedOutputComplexSignals[] = { 0 }; static const char_T *rt_LoggedOutputLabels[] = { "" }; static const char_T *rt_LoggedOutputBlockNames[] = { "test/Out1" }; static RTWLogDataTypeConvert rt_RTWLogDataTypeConvert[] = { { 0, SS_DOUBLE, SS_DOUBLE, 0, 0, 0, 1.0, 0, 0.0 } }; static RTWLogSignalInfo rt_LoggedOutputSignalInfo[] = { { 1, rt_LoggedOutputWidths, rt_LoggedOutputNumDimensions, rt_LoggedOutputDimensions, rt_LoggedOutputIsVarDims, rt_LoggedCurrentSignalDimensions, rt_LoggedOutputDataTypeIds, rt_LoggedOutputComplexSignals, (NULL), { rt_LoggedOutputLabels }, (NULL), (NULL), (NULL), { rt_LoggedOutputBlockNames }, { (NULL) }, (NULL), rt_RTWLogDataTypeConvert } }; rtliSetLogYSignalInfo(test_M->rtwLogInfo, rt_LoggedOutputSignalInfo); /* set currSigDims field */ rt_LoggedCurrentSignalDimensions[0] = &rt_LoggedOutputWidths[0]; rt_LoggedCurrentSignalDimensions[1] = &rt_LoggedOutputWidths[0]; } rtliSetLogY(test_M->rtwLogInfo, "yout"); } test_M->solverInfoPtr = (&test_M->solverInfo); test_M->Timing.stepSize = (0.033333333333333333); rtsiSetFixedStepSize(&test_M->solverInfo, 0.033333333333333333); rtsiSetSolverMode(&test_M->solverInfo, SOLVER_MODE_SINGLETASKING); /* block I/O */ test_M->ModelData.blockIO = ((void *) &test_B); (void) memset(((void *) &test_B), 0, sizeof(BlockIO_test)); { test_B.HoughTransform_o2[0] = -1.5707963267948966; test_B.HoughTransform_o2[1] = -1.5533430342749532; test_B.HoughTransform_o2[2] = -1.53588974175501; test_B.HoughTransform_o2[3] = -1.5184364492350666; test_B.HoughTransform_o2[4] = -1.5009831567151235; test_B.HoughTransform_o2[5] = -1.4835298641951802; test_B.HoughTransform_o2[6] = -1.4660765716752369; test_B.HoughTransform_o2[7] = -1.4486232791552935; test_B.HoughTransform_o2[8] = -1.4311699866353502; test_B.HoughTransform_o2[9] = -1.4137166941154069; test_B.HoughTransform_o2[10] = -1.3962634015954636; test_B.HoughTransform_o2[11] = -1.3788101090755203; test_B.HoughTransform_o2[12] = -1.3613568165555769; test_B.HoughTransform_o2[13] = -1.3439035240356338; test_B.HoughTransform_o2[14] = -1.3264502315156905; test_B.HoughTransform_o2[15] = -1.3089969389957472; test_B.HoughTransform_o2[16] = -1.2915436464758039; test_B.HoughTransform_o2[17] = -1.2740903539558606; test_B.HoughTransform_o2[18] = -1.2566370614359172; test_B.HoughTransform_o2[19] = -1.2391837689159739; test_B.HoughTransform_o2[20] = -1.2217304763960306; test_B.HoughTransform_o2[21] = -1.2042771838760873; test_B.HoughTransform_o2[22] = -1.1868238913561442; test_B.HoughTransform_o2[23] = -1.1693705988362009; test_B.HoughTransform_o2[24] = -1.1519173063162575; test_B.HoughTransform_o2[25] = -1.1344640137963142; test_B.HoughTransform_o2[26] = -1.1170107212763709; test_B.HoughTransform_o2[27] = -1.0995574287564276; test_B.HoughTransform_o2[28] = -1.0821041362364843; test_B.HoughTransform_o2[29] = -1.064650843716541; test_B.HoughTransform_o2[30] = -1.0471975511965976; test_B.HoughTransform_o2[31] = -1.0297442586766545; test_B.HoughTransform_o2[32] = -1.0122909661567112; test_B.HoughTransform_o2[33] = -0.99483767363676789; test_B.HoughTransform_o2[34] = -0.97738438111682457; test_B.HoughTransform_o2[35] = -0.95993108859688125; test_B.HoughTransform_o2[36] = -0.94247779607693793; test_B.HoughTransform_o2[37] = -0.92502450355699462; test_B.HoughTransform_o2[38] = -0.90757121103705141; test_B.HoughTransform_o2[39] = -0.89011791851710809; test_B.HoughTransform_o2[40] = -0.87266462599716477; test_B.HoughTransform_o2[41] = -0.85521133347722145; test_B.HoughTransform_o2[42] = -0.83775804095727824; test_B.HoughTransform_o2[43] = -0.82030474843733492; test_B.HoughTransform_o2[44] = -0.8028514559173916; test_B.HoughTransform_o2[45] = -0.78539816339744828; test_B.HoughTransform_o2[46] = -0.767944870877505; test_B.HoughTransform_o2[47] = -0.75049157835756175; test_B.HoughTransform_o2[48] = -0.73303828583761843; test_B.HoughTransform_o2[49] = -0.71558499331767511; test_B.HoughTransform_o2[50] = -0.69813170079773179; test_B.HoughTransform_o2[51] = -0.68067840827778847; test_B.HoughTransform_o2[52] = -0.66322511575784526; test_B.HoughTransform_o2[53] = -0.64577182323790194; test_B.HoughTransform_o2[54] = -0.62831853071795862; test_B.HoughTransform_o2[55] = -0.6108652381980153; test_B.HoughTransform_o2[56] = -0.59341194567807209; test_B.HoughTransform_o2[57] = -0.57595865315812877; test_B.HoughTransform_o2[58] = -0.55850536063818546; test_B.HoughTransform_o2[59] = -0.54105206811824214; test_B.HoughTransform_o2[60] = -0.52359877559829882; test_B.HoughTransform_o2[61] = -0.50614548307835561; test_B.HoughTransform_o2[62] = -0.48869219055841229; test_B.HoughTransform_o2[63] = -0.47123889803846897; test_B.HoughTransform_o2[64] = -0.4537856055185257; test_B.HoughTransform_o2[65] = -0.43633231299858238; test_B.HoughTransform_o2[66] = -0.41887902047863912; test_B.HoughTransform_o2[67] = -0.4014257279586958; test_B.HoughTransform_o2[68] = -0.38397243543875248; test_B.HoughTransform_o2[69] = -0.36651914291880922; test_B.HoughTransform_o2[70] = -0.3490658503988659; test_B.HoughTransform_o2[71] = -0.33161255787892263; test_B.HoughTransform_o2[72] = -0.31415926535897931; test_B.HoughTransform_o2[73] = -0.29670597283903605; test_B.HoughTransform_o2[74] = -0.27925268031909273; test_B.HoughTransform_o2[75] = -0.26179938779914941; test_B.HoughTransform_o2[76] = -0.24434609527920614; test_B.HoughTransform_o2[77] = -0.22689280275926285; test_B.HoughTransform_o2[78] = -0.20943951023931956; test_B.HoughTransform_o2[79] = -0.19198621771937624; test_B.HoughTransform_o2[80] = -0.17453292519943295; test_B.HoughTransform_o2[81] = -0.15707963267948966; test_B.HoughTransform_o2[82] = -0.13962634015954636; test_B.HoughTransform_o2[83] = -0.12217304763960307; test_B.HoughTransform_o2[84] = -0.10471975511965978; test_B.HoughTransform_o2[85] = -0.087266462599716474; test_B.HoughTransform_o2[86] = -0.069813170079773182; test_B.HoughTransform_o2[87] = -0.05235987755982989; test_B.HoughTransform_o2[88] = -0.034906585039886591; test_B.HoughTransform_o2[89] = -0.017453292519943295; test_B.HoughTransform_o2[90] = 0.0; test_B.HoughTransform_o2[91] = 0.017453292519943295; test_B.HoughTransform_o2[92] = 0.034906585039886591; test_B.HoughTransform_o2[93] = 0.05235987755982989; test_B.HoughTransform_o2[94] = 0.069813170079773182; test_B.HoughTransform_o2[95] = 0.087266462599716474; test_B.HoughTransform_o2[96] = 0.10471975511965978; test_B.HoughTransform_o2[97] = 0.12217304763960307; test_B.HoughTransform_o2[98] = 0.13962634015954636; test_B.HoughTransform_o2[99] = 0.15707963267948966; test_B.HoughTransform_o2[100] = 0.17453292519943295; test_B.HoughTransform_o2[101] = 0.19198621771937624; test_B.HoughTransform_o2[102] = 0.20943951023931956; test_B.HoughTransform_o2[103] = 0.22689280275926285; test_B.HoughTransform_o2[104] = 0.24434609527920614; test_B.HoughTransform_o2[105] = 0.26179938779914941; test_B.HoughTransform_o2[106] = 0.27925268031909273; test_B.HoughTransform_o2[107] = 0.29670597283903605; test_B.HoughTransform_o2[108] = 0.31415926535897931; test_B.HoughTransform_o2[109] = 0.33161255787892263; test_B.HoughTransform_o2[110] = 0.3490658503988659; test_B.HoughTransform_o2[111] = 0.36651914291880922; test_B.HoughTransform_o2[112] = 0.38397243543875248; test_B.HoughTransform_o2[113] = 0.4014257279586958; test_B.HoughTransform_o2[114] = 0.41887902047863912; test_B.HoughTransform_o2[115] = 0.43633231299858238; test_B.HoughTransform_o2[116] = 0.4537856055185257; test_B.HoughTransform_o2[117] = 0.47123889803846897; test_B.HoughTransform_o2[118] = 0.48869219055841229; test_B.HoughTransform_o2[119] = 0.50614548307835561; test_B.HoughTransform_o2[120] = 0.52359877559829882; test_B.HoughTransform_o2[121] = 0.54105206811824214; test_B.HoughTransform_o2[122] = 0.55850536063818546; test_B.HoughTransform_o2[123] = 0.57595865315812877; test_B.HoughTransform_o2[124] = 0.59341194567807209; test_B.HoughTransform_o2[125] = 0.6108652381980153; test_B.HoughTransform_o2[126] = 0.62831853071795862; test_B.HoughTransform_o2[127] = 0.64577182323790194; test_B.HoughTransform_o2[128] = 0.66322511575784526; test_B.HoughTransform_o2[129] = 0.68067840827778847; test_B.HoughTransform_o2[130] = 0.69813170079773179; test_B.HoughTransform_o2[131] = 0.71558499331767511; test_B.HoughTransform_o2[132] = 0.73303828583761843; test_B.HoughTransform_o2[133] = 0.75049157835756175; test_B.HoughTransform_o2[134] = 0.767944870877505; test_B.HoughTransform_o2[135] = 0.78539816339744828; test_B.HoughTransform_o2[136] = 0.8028514559173916; test_B.HoughTransform_o2[137] = 0.82030474843733492; test_B.HoughTransform_o2[138] = 0.83775804095727824; test_B.HoughTransform_o2[139] = 0.85521133347722145; test_B.HoughTransform_o2[140] = 0.87266462599716477; test_B.HoughTransform_o2[141] = 0.89011791851710809; test_B.HoughTransform_o2[142] = 0.90757121103705141; test_B.HoughTransform_o2[143] = 0.92502450355699462; test_B.HoughTransform_o2[144] = 0.94247779607693793; test_B.HoughTransform_o2[145] = 0.95993108859688125; test_B.HoughTransform_o2[146] = 0.97738438111682457; test_B.HoughTransform_o2[147] = 0.99483767363676789; test_B.HoughTransform_o2[148] = 1.0122909661567112; test_B.HoughTransform_o2[149] = 1.0297442586766545; test_B.HoughTransform_o2[150] = 1.0471975511965976; test_B.HoughTransform_o2[151] = 1.064650843716541; test_B.HoughTransform_o2[152] = 1.0821041362364843; test_B.HoughTransform_o2[153] = 1.0995574287564276; test_B.HoughTransform_o2[154] = 1.1170107212763709; test_B.HoughTransform_o2[155] = 1.1344640137963142; test_B.HoughTransform_o2[156] = 1.1519173063162575; test_B.HoughTransform_o2[157] = 1.1693705988362009; test_B.HoughTransform_o2[158] = 1.1868238913561442; test_B.HoughTransform_o2[159] = 1.2042771838760873; test_B.HoughTransform_o2[160] = 1.2217304763960306; test_B.HoughTransform_o2[161] = 1.2391837689159739; test_B.HoughTransform_o2[162] = 1.2566370614359172; test_B.HoughTransform_o2[163] = 1.2740903539558606; test_B.HoughTransform_o2[164] = 1.2915436464758039; test_B.HoughTransform_o2[165] = 1.3089969389957472; test_B.HoughTransform_o2[166] = 1.3264502315156905; test_B.HoughTransform_o2[167] = 1.3439035240356338; test_B.HoughTransform_o2[168] = 1.3613568165555769; test_B.HoughTransform_o2[169] = 1.3788101090755203; test_B.HoughTransform_o2[170] = 1.3962634015954636; test_B.HoughTransform_o2[171] = 1.4137166941154069; test_B.HoughTransform_o2[172] = 1.4311699866353502; test_B.HoughTransform_o2[173] = 1.4486232791552935; test_B.HoughTransform_o2[174] = 1.4660765716752369; test_B.HoughTransform_o2[175] = 1.4835298641951802; test_B.HoughTransform_o2[176] = 1.5009831567151235; test_B.HoughTransform_o2[177] = 1.5184364492350666; test_B.HoughTransform_o2[178] = 1.53588974175501; test_B.HoughTransform_o2[179] = 1.5533430342749532; test_B.HoughTransform_o3[0] = -199.0; test_B.HoughTransform_o3[1] = -198.0; test_B.HoughTransform_o3[2] = -197.0; test_B.HoughTransform_o3[3] = -196.0; test_B.HoughTransform_o3[4] = -195.0; test_B.HoughTransform_o3[5] = -194.0; test_B.HoughTransform_o3[6] = -193.0; test_B.HoughTransform_o3[7] = -192.0; test_B.HoughTransform_o3[8] = -191.0; test_B.HoughTransform_o3[9] = -190.0; test_B.HoughTransform_o3[10] = -189.0; test_B.HoughTransform_o3[11] = -188.0; test_B.HoughTransform_o3[12] = -187.0; test_B.HoughTransform_o3[13] = -186.0; test_B.HoughTransform_o3[14] = -185.0; test_B.HoughTransform_o3[15] = -184.0; test_B.HoughTransform_o3[16] = -183.0; test_B.HoughTransform_o3[17] = -182.0; test_B.HoughTransform_o3[18] = -181.0; test_B.HoughTransform_o3[19] = -180.0; test_B.HoughTransform_o3[20] = -179.0; test_B.HoughTransform_o3[21] = -178.0; test_B.HoughTransform_o3[22] = -177.0; test_B.HoughTransform_o3[23] = -176.0; test_B.HoughTransform_o3[24] = -175.0; test_B.HoughTransform_o3[25] = -174.0; test_B.HoughTransform_o3[26] = -173.0; test_B.HoughTransform_o3[27] = -172.0; test_B.HoughTransform_o3[28] = -171.0; test_B.HoughTransform_o3[29] = -170.0; test_B.HoughTransform_o3[30] = -169.0; test_B.HoughTransform_o3[31] = -168.0; test_B.HoughTransform_o3[32] = -167.0; test_B.HoughTransform_o3[33] = -166.0; test_B.HoughTransform_o3[34] = -165.0; test_B.HoughTransform_o3[35] = -164.0; test_B.HoughTransform_o3[36] = -163.0; test_B.HoughTransform_o3[37] = -162.0; test_B.HoughTransform_o3[38] = -161.0; test_B.HoughTransform_o3[39] = -160.0; test_B.HoughTransform_o3[40] = -159.0; test_B.HoughTransform_o3[41] = -158.0; test_B.HoughTransform_o3[42] = -157.0; test_B.HoughTransform_o3[43] = -156.0; test_B.HoughTransform_o3[44] = -155.0; test_B.HoughTransform_o3[45] = -154.0; test_B.HoughTransform_o3[46] = -153.0; test_B.HoughTransform_o3[47] = -152.0; test_B.HoughTransform_o3[48] = -151.0; test_B.HoughTransform_o3[49] = -150.0; test_B.HoughTransform_o3[50] = -149.0; test_B.HoughTransform_o3[51] = -148.0; test_B.HoughTransform_o3[52] = -147.0; test_B.HoughTransform_o3[53] = -146.0; test_B.HoughTransform_o3[54] = -145.0; test_B.HoughTransform_o3[55] = -144.0; test_B.HoughTransform_o3[56] = -143.0; test_B.HoughTransform_o3[57] = -142.0; test_B.HoughTransform_o3[58] = -141.0; test_B.HoughTransform_o3[59] = -140.0; test_B.HoughTransform_o3[60] = -139.0; test_B.HoughTransform_o3[61] = -138.0; test_B.HoughTransform_o3[62] = -137.0; test_B.HoughTransform_o3[63] = -136.0; test_B.HoughTransform_o3[64] = -135.0; test_B.HoughTransform_o3[65] = -134.0; test_B.HoughTransform_o3[66] = -133.0; test_B.HoughTransform_o3[67] = -132.0; test_B.HoughTransform_o3[68] = -131.0; test_B.HoughTransform_o3[69] = -130.0; test_B.HoughTransform_o3[70] = -129.0; test_B.HoughTransform_o3[71] = -128.0; test_B.HoughTransform_o3[72] = -127.0; test_B.HoughTransform_o3[73] = -126.0; test_B.HoughTransform_o3[74] = -125.0; test_B.HoughTransform_o3[75] = -124.0; test_B.HoughTransform_o3[76] = -123.0; test_B.HoughTransform_o3[77] = -122.0; test_B.HoughTransform_o3[78] = -121.0; test_B.HoughTransform_o3[79] = -120.0; test_B.HoughTransform_o3[80] = -119.0; test_B.HoughTransform_o3[81] = -118.0; test_B.HoughTransform_o3[82] = -117.0; test_B.HoughTransform_o3[83] = -116.0; test_B.HoughTransform_o3[84] = -115.0; test_B.HoughTransform_o3[85] = -114.0; test_B.HoughTransform_o3[86] = -113.0; test_B.HoughTransform_o3[87] = -112.0; test_B.HoughTransform_o3[88] = -111.0; test_B.HoughTransform_o3[89] = -110.0; test_B.HoughTransform_o3[90] = -109.0; test_B.HoughTransform_o3[91] = -108.0; test_B.HoughTransform_o3[92] = -107.0; test_B.HoughTransform_o3[93] = -106.0; test_B.HoughTransform_o3[94] = -105.0; test_B.HoughTransform_o3[95] = -104.0; test_B.HoughTransform_o3[96] = -103.0; test_B.HoughTransform_o3[97] = -102.0; test_B.HoughTransform_o3[98] = -101.0; test_B.HoughTransform_o3[99] = -100.0; test_B.HoughTransform_o3[100] = -99.0; test_B.HoughTransform_o3[101] = -98.0; test_B.HoughTransform_o3[102] = -97.0; test_B.HoughTransform_o3[103] = -96.0; test_B.HoughTransform_o3[104] = -95.0; test_B.HoughTransform_o3[105] = -94.0; test_B.HoughTransform_o3[106] = -93.0; test_B.HoughTransform_o3[107] = -92.0; test_B.HoughTransform_o3[108] = -91.0; test_B.HoughTransform_o3[109] = -90.0; test_B.HoughTransform_o3[110] = -89.0; test_B.HoughTransform_o3[111] = -88.0; test_B.HoughTransform_o3[112] = -87.0; test_B.HoughTransform_o3[113] = -86.0; test_B.HoughTransform_o3[114] = -85.0; test_B.HoughTransform_o3[115] = -84.0; test_B.HoughTransform_o3[116] = -83.0; test_B.HoughTransform_o3[117] = -82.0; test_B.HoughTransform_o3[118] = -81.0; test_B.HoughTransform_o3[119] = -80.0; test_B.HoughTransform_o3[120] = -79.0; test_B.HoughTransform_o3[121] = -78.0; test_B.HoughTransform_o3[122] = -77.0; test_B.HoughTransform_o3[123] = -76.0; test_B.HoughTransform_o3[124] = -75.0; test_B.HoughTransform_o3[125] = -74.0; test_B.HoughTransform_o3[126] = -73.0; test_B.HoughTransform_o3[127] = -72.0; test_B.HoughTransform_o3[128] = -71.0; test_B.HoughTransform_o3[129] = -70.0; test_B.HoughTransform_o3[130] = -69.0; test_B.HoughTransform_o3[131] = -68.0; test_B.HoughTransform_o3[132] = -67.0; test_B.HoughTransform_o3[133] = -66.0; test_B.HoughTransform_o3[134] = -65.0; test_B.HoughTransform_o3[135] = -64.0; test_B.HoughTransform_o3[136] = -63.0; test_B.HoughTransform_o3[137] = -62.0; test_B.HoughTransform_o3[138] = -61.0; test_B.HoughTransform_o3[139] = -60.0; test_B.HoughTransform_o3[140] = -59.0; test_B.HoughTransform_o3[141] = -58.0; test_B.HoughTransform_o3[142] = -57.0; test_B.HoughTransform_o3[143] = -56.0; test_B.HoughTransform_o3[144] = -55.0; test_B.HoughTransform_o3[145] = -54.0; test_B.HoughTransform_o3[146] = -53.0; test_B.HoughTransform_o3[147] = -52.0; test_B.HoughTransform_o3[148] = -51.0; test_B.HoughTransform_o3[149] = -50.0; test_B.HoughTransform_o3[150] = -49.0; test_B.HoughTransform_o3[151] = -48.0; test_B.HoughTransform_o3[152] = -47.0; test_B.HoughTransform_o3[153] = -46.0; test_B.HoughTransform_o3[154] = -45.0; test_B.HoughTransform_o3[155] = -44.0; test_B.HoughTransform_o3[156] = -43.0; test_B.HoughTransform_o3[157] = -42.0; test_B.HoughTransform_o3[158] = -41.0; test_B.HoughTransform_o3[159] = -40.0; test_B.HoughTransform_o3[160] = -39.0; test_B.HoughTransform_o3[161] = -38.0; test_B.HoughTransform_o3[162] = -37.0; test_B.HoughTransform_o3[163] = -36.0; test_B.HoughTransform_o3[164] = -35.0; test_B.HoughTransform_o3[165] = -34.0; test_B.HoughTransform_o3[166] = -33.0; test_B.HoughTransform_o3[167] = -32.0; test_B.HoughTransform_o3[168] = -31.0; test_B.HoughTransform_o3[169] = -30.0; test_B.HoughTransform_o3[170] = -29.0; test_B.HoughTransform_o3[171] = -28.0; test_B.HoughTransform_o3[172] = -27.0; test_B.HoughTransform_o3[173] = -26.0; test_B.HoughTransform_o3[174] = -25.0; test_B.HoughTransform_o3[175] = -24.0; test_B.HoughTransform_o3[176] = -23.0; test_B.HoughTransform_o3[177] = -22.0; test_B.HoughTransform_o3[178] = -21.0; test_B.HoughTransform_o3[179] = -20.0; test_B.HoughTransform_o3[180] = -19.0; test_B.HoughTransform_o3[181] = -18.0; test_B.HoughTransform_o3[182] = -17.0; test_B.HoughTransform_o3[183] = -16.0; test_B.HoughTransform_o3[184] = -15.0; test_B.HoughTransform_o3[185] = -14.0; test_B.HoughTransform_o3[186] = -13.0; test_B.HoughTransform_o3[187] = -12.0; test_B.HoughTransform_o3[188] = -11.0; test_B.HoughTransform_o3[189] = -10.0; test_B.HoughTransform_o3[190] = -9.0; test_B.HoughTransform_o3[191] = -8.0; test_B.HoughTransform_o3[192] = -7.0; test_B.HoughTransform_o3[193] = -6.0; test_B.HoughTransform_o3[194] = -5.0; test_B.HoughTransform_o3[195] = -4.0; test_B.HoughTransform_o3[196] = -3.0; test_B.HoughTransform_o3[197] = -2.0; test_B.HoughTransform_o3[198] = -1.0; test_B.HoughTransform_o3[199] = 0.0; test_B.HoughTransform_o3[200] = 1.0; test_B.HoughTransform_o3[201] = 2.0; test_B.HoughTransform_o3[202] = 3.0; test_B.HoughTransform_o3[203] = 4.0; test_B.HoughTransform_o3[204] = 5.0; test_B.HoughTransform_o3[205] = 6.0; test_B.HoughTransform_o3[206] = 7.0; test_B.HoughTransform_o3[207] = 8.0; test_B.HoughTransform_o3[208] = 9.0; test_B.HoughTransform_o3[209] = 10.0; test_B.HoughTransform_o3[210] = 11.0; test_B.HoughTransform_o3[211] = 12.0; test_B.HoughTransform_o3[212] = 13.0; test_B.HoughTransform_o3[213] = 14.0; test_B.HoughTransform_o3[214] = 15.0; test_B.HoughTransform_o3[215] = 16.0; test_B.HoughTransform_o3[216] = 17.0; test_B.HoughTransform_o3[217] = 18.0; test_B.HoughTransform_o3[218] = 19.0; test_B.HoughTransform_o3[219] = 20.0; test_B.HoughTransform_o3[220] = 21.0; test_B.HoughTransform_o3[221] = 22.0; test_B.HoughTransform_o3[222] = 23.0; test_B.HoughTransform_o3[223] = 24.0; test_B.HoughTransform_o3[224] = 25.0; test_B.HoughTransform_o3[225] = 26.0; test_B.HoughTransform_o3[226] = 27.0; test_B.HoughTransform_o3[227] = 28.0; test_B.HoughTransform_o3[228] = 29.0; test_B.HoughTransform_o3[229] = 30.0; test_B.HoughTransform_o3[230] = 31.0; test_B.HoughTransform_o3[231] = 32.0; test_B.HoughTransform_o3[232] = 33.0; test_B.HoughTransform_o3[233] = 34.0; test_B.HoughTransform_o3[234] = 35.0; test_B.HoughTransform_o3[235] = 36.0; test_B.HoughTransform_o3[236] = 37.0; test_B.HoughTransform_o3[237] = 38.0; test_B.HoughTransform_o3[238] = 39.0; test_B.HoughTransform_o3[239] = 40.0; test_B.HoughTransform_o3[240] = 41.0; test_B.HoughTransform_o3[241] = 42.0; test_B.HoughTransform_o3[242] = 43.0; test_B.HoughTransform_o3[243] = 44.0; test_B.HoughTransform_o3[244] = 45.0; test_B.HoughTransform_o3[245] = 46.0; test_B.HoughTransform_o3[246] = 47.0; test_B.HoughTransform_o3[247] = 48.0; test_B.HoughTransform_o3[248] = 49.0; test_B.HoughTransform_o3[249] = 50.0; test_B.HoughTransform_o3[250] = 51.0; test_B.HoughTransform_o3[251] = 52.0; test_B.HoughTransform_o3[252] = 53.0; test_B.HoughTransform_o3[253] = 54.0; test_B.HoughTransform_o3[254] = 55.0; test_B.HoughTransform_o3[255] = 56.0; test_B.HoughTransform_o3[256] = 57.0; test_B.HoughTransform_o3[257] = 58.0; test_B.HoughTransform_o3[258] = 59.0; test_B.HoughTransform_o3[259] = 60.0; test_B.HoughTransform_o3[260] = 61.0; test_B.HoughTransform_o3[261] = 62.0; test_B.HoughTransform_o3[262] = 63.0; test_B.HoughTransform_o3[263] = 64.0; test_B.HoughTransform_o3[264] = 65.0; test_B.HoughTransform_o3[265] = 66.0; test_B.HoughTransform_o3[266] = 67.0; test_B.HoughTransform_o3[267] = 68.0; test_B.HoughTransform_o3[268] = 69.0; test_B.HoughTransform_o3[269] = 70.0; test_B.HoughTransform_o3[270] = 71.0; test_B.HoughTransform_o3[271] = 72.0; test_B.HoughTransform_o3[272] = 73.0; test_B.HoughTransform_o3[273] = 74.0; test_B.HoughTransform_o3[274] = 75.0; test_B.HoughTransform_o3[275] = 76.0; test_B.HoughTransform_o3[276] = 77.0; test_B.HoughTransform_o3[277] = 78.0; test_B.HoughTransform_o3[278] = 79.0; test_B.HoughTransform_o3[279] = 80.0; test_B.HoughTransform_o3[280] = 81.0; test_B.HoughTransform_o3[281] = 82.0; test_B.HoughTransform_o3[282] = 83.0; test_B.HoughTransform_o3[283] = 84.0; test_B.HoughTransform_o3[284] = 85.0; test_B.HoughTransform_o3[285] = 86.0; test_B.HoughTransform_o3[286] = 87.0; test_B.HoughTransform_o3[287] = 88.0; test_B.HoughTransform_o3[288] = 89.0; test_B.HoughTransform_o3[289] = 90.0; test_B.HoughTransform_o3[290] = 91.0; test_B.HoughTransform_o3[291] = 92.0; test_B.HoughTransform_o3[292] = 93.0; test_B.HoughTransform_o3[293] = 94.0; test_B.HoughTransform_o3[294] = 95.0; test_B.HoughTransform_o3[295] = 96.0; test_B.HoughTransform_o3[296] = 97.0; test_B.HoughTransform_o3[297] = 98.0; test_B.HoughTransform_o3[298] = 99.0; test_B.HoughTransform_o3[299] = 100.0; test_B.HoughTransform_o3[300] = 101.0; test_B.HoughTransform_o3[301] = 102.0; test_B.HoughTransform_o3[302] = 103.0; test_B.HoughTransform_o3[303] = 104.0; test_B.HoughTransform_o3[304] = 105.0; test_B.HoughTransform_o3[305] = 106.0; test_B.HoughTransform_o3[306] = 107.0; test_B.HoughTransform_o3[307] = 108.0; test_B.HoughTransform_o3[308] = 109.0; test_B.HoughTransform_o3[309] = 110.0; test_B.HoughTransform_o3[310] = 111.0; test_B.HoughTransform_o3[311] = 112.0; test_B.HoughTransform_o3[312] = 113.0; test_B.HoughTransform_o3[313] = 114.0; test_B.HoughTransform_o3[314] = 115.0; test_B.HoughTransform_o3[315] = 116.0; test_B.HoughTransform_o3[316] = 117.0; test_B.HoughTransform_o3[317] = 118.0; test_B.HoughTransform_o3[318] = 119.0; test_B.HoughTransform_o3[319] = 120.0; test_B.HoughTransform_o3[320] = 121.0; test_B.HoughTransform_o3[321] = 122.0; test_B.HoughTransform_o3[322] = 123.0; test_B.HoughTransform_o3[323] = 124.0; test_B.HoughTransform_o3[324] = 125.0; test_B.HoughTransform_o3[325] = 126.0; test_B.HoughTransform_o3[326] = 127.0; test_B.HoughTransform_o3[327] = 128.0; test_B.HoughTransform_o3[328] = 129.0; test_B.HoughTransform_o3[329] = 130.0; test_B.HoughTransform_o3[330] = 131.0; test_B.HoughTransform_o3[331] = 132.0; test_B.HoughTransform_o3[332] = 133.0; test_B.HoughTransform_o3[333] = 134.0; test_B.HoughTransform_o3[334] = 135.0; test_B.HoughTransform_o3[335] = 136.0; test_B.HoughTransform_o3[336] = 137.0; test_B.HoughTransform_o3[337] = 138.0; test_B.HoughTransform_o3[338] = 139.0; test_B.HoughTransform_o3[339] = 140.0; test_B.HoughTransform_o3[340] = 141.0; test_B.HoughTransform_o3[341] = 142.0; test_B.HoughTransform_o3[342] = 143.0; test_B.HoughTransform_o3[343] = 144.0; test_B.HoughTransform_o3[344] = 145.0; test_B.HoughTransform_o3[345] = 146.0; test_B.HoughTransform_o3[346] = 147.0; test_B.HoughTransform_o3[347] = 148.0; test_B.HoughTransform_o3[348] = 149.0; test_B.HoughTransform_o3[349] = 150.0; test_B.HoughTransform_o3[350] = 151.0; test_B.HoughTransform_o3[351] = 152.0; test_B.HoughTransform_o3[352] = 153.0; test_B.HoughTransform_o3[353] = 154.0; test_B.HoughTransform_o3[354] = 155.0; test_B.HoughTransform_o3[355] = 156.0; test_B.HoughTransform_o3[356] = 157.0; test_B.HoughTransform_o3[357] = 158.0; test_B.HoughTransform_o3[358] = 159.0; test_B.HoughTransform_o3[359] = 160.0; test_B.HoughTransform_o3[360] = 161.0; test_B.HoughTransform_o3[361] = 162.0; test_B.HoughTransform_o3[362] = 163.0; test_B.HoughTransform_o3[363] = 164.0; test_B.HoughTransform_o3[364] = 165.0; test_B.HoughTransform_o3[365] = 166.0; test_B.HoughTransform_o3[366] = 167.0; test_B.HoughTransform_o3[367] = 168.0; test_B.HoughTransform_o3[368] = 169.0; test_B.HoughTransform_o3[369] = 170.0; test_B.HoughTransform_o3[370] = 171.0; test_B.HoughTransform_o3[371] = 172.0; test_B.HoughTransform_o3[372] = 173.0; test_B.HoughTransform_o3[373] = 174.0; test_B.HoughTransform_o3[374] = 175.0; test_B.HoughTransform_o3[375] = 176.0; test_B.HoughTransform_o3[376] = 177.0; test_B.HoughTransform_o3[377] = 178.0; test_B.HoughTransform_o3[378] = 179.0; test_B.HoughTransform_o3[379] = 180.0; test_B.HoughTransform_o3[380] = 181.0; test_B.HoughTransform_o3[381] = 182.0; test_B.HoughTransform_o3[382] = 183.0; test_B.HoughTransform_o3[383] = 184.0; test_B.HoughTransform_o3[384] = 185.0; test_B.HoughTransform_o3[385] = 186.0; test_B.HoughTransform_o3[386] = 187.0; test_B.HoughTransform_o3[387] = 188.0; test_B.HoughTransform_o3[388] = 189.0; test_B.HoughTransform_o3[389] = 190.0; test_B.HoughTransform_o3[390] = 191.0; test_B.HoughTransform_o3[391] = 192.0; test_B.HoughTransform_o3[392] = 193.0; test_B.HoughTransform_o3[393] = 194.0; test_B.HoughTransform_o3[394] = 195.0; test_B.HoughTransform_o3[395] = 196.0; test_B.HoughTransform_o3[396] = 197.0; test_B.HoughTransform_o3[397] = 198.0; test_B.HoughTransform_o3[398] = 199.0; } /* parameters */ test_M->ModelData.defaultParam = ((real_T *)&test_P); /* states (dwork) */ test_M->Work.dwork = ((void *) &test_DWork); (void) memset((void *)&test_DWork, 0, sizeof(D_Work_test)); /* external inputs */ test_M->ModelData.inputs = (((void*)&test_U)); (void) memset((void *)&test_U, 0, sizeof(ExternalInputs_test)); /* external outputs */ test_M->ModelData.outputs = (&test_Y); (void) memset(&test_Y.Out1[0], 0, 19200U*sizeof(real_T)); } /* Model terminate function */ void test_terminate(void) { } /*========================================================================* * Start of GRT compatible call interface * *========================================================================*/ extern "C" void MdlOutputs(int_T tid) { test_output(tid); } extern "C" void MdlUpdate(int_T tid) { test_update(tid); } extern "C" void MdlInitializeSizes(void) { test_M->Sizes.numContStates = (0); /* Number of continuous states */ test_M->Sizes.numY = (19200); /* Number of model outputs */ test_M->Sizes.numU = (57600); /* Number of model inputs */ test_M->Sizes.sysDirFeedThru = (1); /* The model is direct feedthrough */ test_M->Sizes.numSampTimes = (1); /* Number of sample times */ test_M->Sizes.numBlocks = (13); /* Number of blocks */ test_M->Sizes.numBlockIO = (7); /* Number of block outputs */ test_M->Sizes.numBlockPrms = (2); /* Sum of parameter "widths" */ } extern "C" void MdlInitializeSampleTimes(void) { } extern "C" void MdlInitialize(void) { { int32_T nonZeroIdx; /* InitializeConditions for S-Function (svipedge): '<Root>/Edge Detection' */ test_DWork.EdgeDetection_MEAN_FACTOR_DW = 5.2083333333333337E-5; for (nonZeroIdx = 0; nonZeroIdx < 6; nonZeroIdx++) { test_DWork.EdgeDetection_VO_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; if (test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx] > 0) { test_DWork.EdgeDetection_VOU_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_VOD_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120; } else { test_DWork.EdgeDetection_VOU_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120; test_DWork.EdgeDetection_VOD_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; } if (test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] > 0) { test_DWork.EdgeDetection_VOL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_VOR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; } else { test_DWork.EdgeDetection_VOL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_VOR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; } if ((test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx] < 0) && (test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] < 0)) { test_DWork.EdgeDetection_VOUL_DW[nonZeroIdx] = 0; test_DWork.EdgeDetection_VOLR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_VOLL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_VOUR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120; } if ((test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx] >= 0) && (test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] < 0)) { test_DWork.EdgeDetection_VOLL_DW[nonZeroIdx] = 0; test_DWork.EdgeDetection_VOUR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_VOUL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_VOLR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120; } if ((test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx] < 0) && (test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] >= 0)) { test_DWork.EdgeDetection_VOUR_DW[nonZeroIdx] = 0; test_DWork.EdgeDetection_VOLL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_VOUL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120; test_DWork.EdgeDetection_VOLR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; } if ((test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx] >= 0) && (test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] >= 0)) { test_DWork.EdgeDetection_VOLR_DW[nonZeroIdx] = 0; test_DWork.EdgeDetection_VOUL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_VOLL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VRO_RTP[nonZeroIdx] * 120; test_DWork.EdgeDetection_VOUR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_VCO_RTP[nonZeroIdx]; } test_DWork.EdgeDetection_HO_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; if (test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx] > 0) { test_DWork.EdgeDetection_HOU_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_HOD_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120; } else { test_DWork.EdgeDetection_HOU_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120; test_DWork.EdgeDetection_HOD_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; } if (test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] > 0) { test_DWork.EdgeDetection_HOL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_HOR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; } else { test_DWork.EdgeDetection_HOL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_HOR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; } if ((test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx] < 0) && (test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] < 0)) { test_DWork.EdgeDetection_HOUL_DW[nonZeroIdx] = 0; test_DWork.EdgeDetection_HOLR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_HOLL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_HOUR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120; } if ((test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx] >= 0) && (test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] < 0)) { test_DWork.EdgeDetection_HOLL_DW[nonZeroIdx] = 0; test_DWork.EdgeDetection_HOUR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_HOUL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_HOLR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120; } if ((test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx] < 0) && (test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] >= 0)) { test_DWork.EdgeDetection_HOUR_DW[nonZeroIdx] = 0; test_DWork.EdgeDetection_HOLL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_HOUL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120; test_DWork.EdgeDetection_HOLR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; } if ((test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx] >= 0) && (test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] >= 0)) { test_DWork.EdgeDetection_HOLR_DW[nonZeroIdx] = 0; test_DWork.EdgeDetection_HOUL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120 + test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; test_DWork.EdgeDetection_HOLL_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HRO_RTP[nonZeroIdx] * 120; test_DWork.EdgeDetection_HOUR_DW[nonZeroIdx] = test_ConstP.EdgeDetection_HCO_RTP[nonZeroIdx]; } } } } extern "C" void MdlStart(void) { /* Start for S-Function (svipfindlocalmax): '<Root>/Find Local Maxima' */ test_DWork.FindLocalMaxima_DIMS1[0] = 2; MdlInitialize(); } extern "C" void MdlTerminate(void) { test_terminate(); } extern "C" RT_MODEL_test *test(void) { test_initialize(1); return test_M; } /*========================================================================* * End of GRT compatible call interface * *========================================================================*/
[ [ [ 1, 1703 ] ] ]
6b0a873c732bffa4390bbaa26779fa444b6f1487
1736474d707f5c6c3622f1cd370ce31ac8217c12
/Pseudo/StringComparer.hpp
78cec1ee8f6d1c138cf32cac1e876b54c62c79cc
[]
no_license
arlm/pseudo
6d7450696672b167dd1aceec6446b8ce137591c0
27153e50003faff31a3212452b1aec88831d8103
refs/heads/master
2022-11-05T23:38:08.214807
2011-02-18T23:18:36
2011-02-18T23:18:36
275,132,368
0
0
null
null
null
null
UTF-8
C++
false
false
1,740
hpp
//////////////////////////////////////////////////// // File: StringComparer.hpp // Author: Matthew Saffer // Date: // // Description: Pseudo::Dictionary comparator for Pseudo::String. // All comparisons and hashes are case-sensitive // // // Comments: Made to be as close as possible to the BCL implementation // // Version: // // Revisions: //////////////////////////////////////////////////// #pragma once #include <Pseudo\String.hpp> #include <Pseudo\Dictionary.hpp> //These magic numbers and shifts were taken directly from the NDP // string compare. //This is a conversion from what's in the BCL. #ifdef WIN32 #define MAGIC1 (5381<<16)+5381; #else #define MAGIC1 5381; #endif #define MAGIC2 0x5d588b65 #define SHIFTL 0x00000005 #define SHIFTR 0x0000001B namespace Pseudo { class StringComparer { private: StringComparer() { } public: static Bool Equals(Pseudo::String &x, Pseudo::String &y) { return (Pseudo::String::Compare(x,y) == 0); } public: static IntPtr GetHashCode(Pseudo::String &x) { const Char *chPtr = x.get_Ptr(); Int hash1 = MAGIC1; Int hash2 = hash1; const Int *numPtr = (Int *)chPtr; Int c; while ((c = chPtr[0]) != 0 ) { hash1 = ((hash1 << SHIFTL) + hash1) ^ c; c = chPtr[1]; if (c == 0 ) break; hash2 = ((hash2 << SHIFTL) + hash2) ^ c; chPtr += 2; } return (hash1 + (hash2 * MAGIC2)); } }; }
[ [ [ 1, 67 ] ] ]
a8c781393fe434af61e28d9790e64bf2a29779e5
d1dc408f6b65c4e5209041b62cd32fb5083fe140
/src/upgrade/cListUpgrade.h
a6f9c87bc875dd79c1b825d66aebcc23ca121f05
[]
no_license
dmitrygerasimuk/dune2themaker-fossfriendly
7b4bed2dfb2b42590e4b72bd34bb0f37f6c81e37
89a6920b216f3964241eeab7cf1a631e1e63f110
refs/heads/master
2020-03-12T03:23:40.821001
2011-02-19T12:01:30
2011-02-19T12:01:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,677
h
/* * cListUpgrade.h * * Created on: Sep 5, 2009 * Author: Stefan */ /** * Representation of an upgrade, belonging to a list. Is constructed by a cListUpgradeFactory * where the 'type' of upgrade is given. * */ #ifndef CLISTUPGRADE_H_ #define CLISTUPGRADE_H_ class cListUpgrade { public: cListUpgrade(int theProgressLimit, int theTotalPrice, eUpgradeType theType, cBuildingListItem *theItem); virtual ~cListUpgrade(); int getTimerProgress() { return TIMER_progress; } int getProgress() { return progress; } int getProgressLimit() { return progressLimit; } int getTotalPrice() { return totalPrice; } float getPricePerTimeUnit() { return pricePerTimeUnit; } cBuildingListItem * getItem() { return item; } int getProgressAsPercentage(); void setProgress(int value) { progress = value; } void setProgressLimit(int value) { progressLimit = value; } void setTotalPrice(int value) { totalPrice = value; } void setPricePerTimeUnit(float value) { pricePerTimeUnit = value; } void setTimerProgress(int value) { TIMER_progress = value; } void setItem(cBuildingListItem *theItem) { item = theItem; } private: int TIMER_progress; // timer to increase progress int progress; // how much progress is made int progressLimit; // how much progress is needed? int totalPrice; // price for upgrade float pricePerTimeUnit; // on construction of this class, determined what it would // be for one time unit (ie, one slice of progress) eUpgradeType type; // type of upgrade cBuildingListItem *item; // the item that will be added to the list after the upgrade }; #endif /* CLISTUPGRADE_H_ */
[ "stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151" ]
[ [ [ 1, 50 ] ] ]
3229044d4847b5e338b8066b1d00e07adabe2701
672d939ad74ccb32afe7ec11b6b99a89c64a6020
/Graph/TeaPot/Matrix.h
e5540ec2e479dfab31921cdee5e445a2661eea5e
[]
no_license
cloudlander/legacy
a073013c69e399744de09d649aaac012e17da325
89acf51531165a29b35e36f360220eeca3b0c1f6
refs/heads/master
2022-04-22T14:55:37.354762
2009-04-11T13:51:56
2009-04-11T13:51:56
256,939,313
1
0
null
null
null
null
UTF-8
C++
false
false
4,959
h
// Matrix.h: interface for the CMatrix class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MATRIX_H__EC59CE74_977C_430D_9748_1150C145453D__INCLUDED_) #define AFX_MATRIX_H__EC59CE74_977C_430D_9748_1150C145453D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class Point3D{ public: double x; double y; double z; public: Point3D(){}; Point3D(Point3D& right) { x=right.x; y=right.y; z=right.z; } Point3D(float px,float py,float pz) { x=px; y=py; z=pz; } Point3D& operator=(Point3D& right) { x=right.x; y=right.y; z=right.z; return *this; } }; template <class T> class CMatrixT { public: CMatrixT(); CMatrixT(int Row_Dim,int Col_Dim); // set Matrix's dimension CMatrixT(CMatrixT<T>&); // CMatrix(Point3D&); virtual ~CMatrixT(); // operations: void Transform(CMatrixT<T>&); void Clear(); // clear all elements void ClearAt(int row,int col); // clear one elements void SetAt(int,int,const T&); // set one elements; // void SetAt(int,int,T); T& GetAt(int,int) const; T GetAt(int,int) ; int GetRowDim(); int GetColDim(); void SetIdentity(); // operation function: CMatrixT<T> operator* (CMatrixT<T>& ); CMatrixT<T>& operator= (CMatrixT<T>&); // CMatrixT<T>& operator= (Point3D&); enum{ DIM=4 }; private: int RowDim,ColDim; int RowCur,ColCur; // @just for debug T **MatrixRow; // Matrix's line T *MatrixCol; // Matrix's Colume void InitMatrix(); }; #ifdef _DEBUG #define new DEBUG_NEW //#undef THIS_FILE //static char THIS_FILE[] = __FILE__; #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// template <class T> CMatrixT<T>::CMatrixT() { RowDim=ColDim=DIM; MatrixCol=NULL; MatrixRow=NULL; InitMatrix(); } template <class T> CMatrixT<T>::CMatrixT(int dimx,int dimy) { RowDim=dimx; ColDim=dimy; InitMatrix(); } template <class T> CMatrixT<T>::CMatrixT(CMatrixT<T>& R_Matrix) { RowDim=R_Matrix.GetRowDim(); ColDim=R_Matrix.GetColDim(); InitMatrix(); *this=R_Matrix; } /* template <class T> CMatrixT<T>::CMatrix(Point3D& point) { xDim=1; yDim=4; type=MATRIX_FLOAT; InitMatrix(type); matrixLine[0][0]=point.x; matrixLine[0][1]=point.y; matrixLine[0][2]=point.z; matrixLine[0][3]=1; } */ template <class T> CMatrixT<T>::~CMatrixT() { if(MatrixRow!=NULL){ for(int i=0;i<RowDim;i++) delete[] MatrixRow[i]; delete[] MatrixRow; } } template <class T> void CMatrixT<T>::InitMatrix() { int i,j; MatrixRow=new T* [RowDim]; for(j=0;j<RowDim;j++) MatrixRow[j]=NULL; for(i=0;i<RowDim;i++) { MatrixCol=new T[ColDim]; for(j=0;j<ColDim;j++) MatrixCol[j]=0; // memset(matrixCol,0,yDim); MatrixRow[i]=MatrixCol; } } template <class T> void CMatrixT<T>::Transform(CMatrixT<T>& left) { int i,j; CMatrixT<T> temp(ColDim,RowDim); for(i=0;i<ColDim;i++) for(j=0;j<RowDim;j++) temp.SetAt(i,j,MatrixRow[j][i]); left= temp; } template <class T> void CMatrixT<T>::Clear() { for(int i=0;i<RowDim;i++) memset(MatrixRow[i],0,ColDim); } template <class T> void CMatrixT<T>::ClearAt(int x,int y) { memset(MatrixRow[x][y],0,1); } template <class T> void CMatrixT<T>::SetAt(int x,int y,const T& elem) { MatrixRow[x][y]=(T)elem; } /* template <class T> void CMatrixT<T>::SetAt(int x,int y,T elem) { MatrixRow[x][y]=(T)elem; } */ template <class T> T& CMatrixT<T>::GetAt(int x,int y) const { return MatrixRow[x][y]; } template <class T> T CMatrixT<T>::GetAt(int x,int y) { return MatrixRow[x][y]; } template <class T> int CMatrixT<T>::GetRowDim() { return RowDim; } template <class T> int CMatrixT<T>::GetColDim() { return ColDim; } template <class T> CMatrixT<T> CMatrixT<T>::operator*(CMatrixT<T>& right) { int i,j,k; T s=0; CMatrixT<T> temp(RowDim,ColDim); for(i=0;i<RowDim;i++) { for(j=0;j<ColDim;j++) { for(s=0,k=0;k<ColDim;k++) { s+=MatrixRow[i][k]*right.GetAt(k,j); } temp.SetAt(i,j,s); } } return CMatrixT<T>(temp); } template <class T> CMatrixT<T>& CMatrixT<T>::operator=(CMatrixT<T>& right) { int i,j; for(i=0;i<RowDim;i++) for(j=0;j<ColDim;j++) MatrixRow[i][j]=right.GetAt(i,j); return *this; } /* template <class T> CMatrix& CMatrix::operator=(Point3D& point) { ASSERT(xDim==1&&yDim==4); matrixLine[0][0]=point.x; matrixLine[0][1]=point.y; matrixLine[0][2]=point.z; matrixLine[0][3]=1; return *this; } */ template <class T> void CMatrixT<T>::SetIdentity() { if(RowDim!=ColDim) return; for(int i=0;i<RowDim;i++) MatrixRow[i][i]=1; } #endif // !defined(AFX_MATRIX_H__EC59CE74_977C_430D_9748_1150C145453D__INCLUDED_)
[ "xmzhang@5428276e-be0b-f542-9301-ee418ed919ad" ]
[ [ [ 1, 271 ] ] ]
3f40aa1df38c3dda49ef6c3bb91992d9930d708c
f87f0a2e6c60be6dd7d126dfd7342dfb18f37092
/Source/TWM/core/component.hpp
803ae2b7ba46da76a6fd314f16bd0f44f9cece9f
[ "MIT" ]
permissive
SamOatesUniversity/Year-2---Animation-Simulation---PigDust
aa2d9d3a6564abd5440b8e9fdc0e24f65a44d75c
2948d39d5e24137b25c91878eaeebe3c8e9e00d1
refs/heads/master
2021-01-10T20:10:29.003591
2011-04-29T20:45:19
2011-04-29T20:45:19
41,170,833
0
0
null
null
null
null
UTF-8
C++
false
false
3,078
hpp
/* Copyright (c) 2010 Tyrone Davison, Teesside University Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #ifndef __TWM_CORE_COMPONENT__ #define __TWM_CORE_COMPONENT__ #include "types.hpp" #include <cassert> namespace twm { class WorldDatabase; class Component { public: Component() : _db(0), _id(kNullComponent) {} Component( WorldDatabase* db, ComponentId id ) : _db(db), _id(id) {} public: ComponentId GetId() const { return _id; } bool IsValid() const { return _id != kNullComponent; } void Destroy(); bool Exists() const; ComponentType GetType() const; CacheId GetCacheId() const; protected: void* _BeginWrite(); void EndWrite(); const void* _BeginRead() const; void EndRead() const; private: WorldDatabase* _db; ComponentId _id; }; // TODO: is TYPE required? template< class T, ComponentType TYPE > class ComponentBase : public Component { public: ComponentBase() {} ComponentBase( const Component& c ) : Component( c ) {} // TODO: add type validation public: const T* BeginRead() const { return (const T*)_BeginRead(); } void EndRead() const { Component::EndRead(); } T* BeginWrite() { return (T*)_BeginWrite(); } void EndWrite() { Component::EndWrite(); } protected: class WritePtr { public: WritePtr( ComponentBase* base ) : _base(base) { _ptr = _base->BeginWrite(); assert( _ptr != 0 ); } ~WritePtr() { _base->EndWrite(); } T* operator->() { return _ptr; } T& operator*() { return *_ptr; } private: ComponentBase* _base; T* _ptr; }; protected: class ReadPtr { public: ReadPtr( const ComponentBase* base ) : _base(base) { _ptr = _base->BeginRead(); assert( _ptr != 0 ); } ~ReadPtr() { _base->EndRead(); } const T* operator->() { return _ptr; } const T& operator*() { return *_ptr; } private: const ComponentBase* _base; const T* _ptr; }; }; } #endif
[ [ [ 1, 95 ] ] ]
c03f960b20f27a908d218371ab6045d0f194d421
22438bd0a316b62e88380796f0a8620c4d129f50
/include/napl_facade.h
5a8157ec8f2b94b15b97be64187c0a2eed2530a6
[ "BSL-1.0" ]
permissive
DannyHavenith/NAPL
1578f5e09f1b825f776bea9575f76518a84588f4
5db7bf823bdc10587746d691cb8d94031115b037
refs/heads/master
2021-01-20T02:17:01.186461
2010-11-26T22:26:25
2010-11-26T22:26:25
1,856,141
0
1
null
null
null
null
UTF-8
C++
false
false
6,847
h
#pragma once struct block_producer_wrapper: public boost::clipp::object { block_producer *producer; explicit block_producer_wrapper( block_producer *producer_) :producer( producer_) { producer->GetStreamHeader( h); } block_producer_wrapper() { } /* operator block_producer *() { return producer; }*/ // expose this class to the scripting engine static void init(boost::clipp::context * c); unsigned long get_samplerate(){ return get_header().samplerate;}; // frames per second short get_samplesize(){ return get_header().samplesize;}; // bits per sample unsigned short get_numchannels(){ return get_header().numchannels;}; // samples per frame unsigned long get_numframes(){ return get_header().numframes;}; inline unsigned short get_frame_size(){ return get_header().frame_size();}; ~block_producer_wrapper() { //delete producer; } private: stream_header &get_header() { return h; } stream_header h; }; struct iterator_wrapper : public boost::clipp::object { private: stream_cut_iterator *m_iterator; public: iterator_wrapper( stream_cut_iterator *_iterator) : m_iterator( _iterator) { } bool next() { return m_iterator->next(); } bool at_end() { return m_iterator->at_end(); } void reset() { m_iterator->reset(); } block_producer_wrapper *current() { return new block_producer_wrapper( m_iterator); } // expose this class to the scripting engine static void init(boost::clipp::context * c); }; struct sound_analysis_wrapper : public boost::clipp::object { sound_analysis result; double get_max() { return result.max;} double get_min() { return result.min;} double get_avg() { return result.avg;} double get_norm() { return result.norm;} explicit sound_analysis_wrapper( const sound_analysis &result_) : result( result_) { } static void init( boost::clipp::context *c); }; class file_reader: public boost::clipp::object { public: static void init(boost::clipp::context * c); // read one line of text std::string readln(void); private: std::ifstream m_stream; public: file_reader( std::string filename); // returns true when the file reader is at end-of-file or if it is in some error-state bool eof(void); void close(void); static file_reader * create_one(std::string filename); }; class file_writer : public boost::clipp::object { private: std::ofstream m_stream; public: static void init( boost::clipp::context * c); void write(std::string str); void writeln(std::string str); void close(void); file_writer(std::string filename); static file_writer * create_one(std::string filename); }; class napl_facade: public boost::clipp::object { private: // test the block_producer pointer for NULL. Throw if is. static block_producer_wrapper *check_return(block_producer * producer, const std::string &message); static sample_object_factory * get_factory(block_producer_wrapper * source); static void check_compatibility( block_producer_wrapper *a, block_producer_wrapper *b); public: // expose this class to the scripting engine static void init(boost::clipp::context * c); // create a block producer that reads from a file static block_producer_wrapper *read_file(std::string filename); // write the source to a file static void write_file(block_producer_wrapper *source, const std::string &filename); static block_producer_wrapper * amplify(block_producer_wrapper *source, double factor); // take a piece out of the input sample static block_producer_wrapper * cut(block_producer_wrapper * source, double start, double length); static block_producer_wrapper * cut_at_sample(block_producer_wrapper * source, unsigned long start, unsigned long length); static block_producer_wrapper * resample( block_producer_wrapper *source, unsigned short new_rate); // changes the speed (and pitch) of the sound without altering the samplerate static block_producer_wrapper * change_speed(block_producer_wrapper * source, double factor); // Joins two samples, placing the second_sample after the first static block_producer_wrapper * join(block_producer_wrapper * first_source, block_producer_wrapper * second_source); // create a stereo source out of two mono sources static block_producer_wrapper * make_stereo(block_producer_wrapper * left_channel, block_producer_wrapper * right_channel); static block_producer_wrapper * cross_fade(block_producer_wrapper * first_source, block_producer_wrapper * second_source); // negate static block_producer_wrapper * negate(block_producer_wrapper * source); // adds silence before and/or after a source static block_producer_wrapper * delay(block_producer_wrapper * source, double before, double after); // pans a stereo sound -1 = utter left 0 = no change 1 = utter right static block_producer_wrapper * pan(block_producer_wrapper * stereo_source, double pan_value); // find the min, max and average values of the samples in the source static sound_analysis_wrapper * analyze(block_producer_wrapper * source); // adds two samples by taking the average of each frame static block_producer_wrapper * add(block_producer_wrapper * source1, block_producer_wrapper * source2); // create a sound source static block_producer_wrapper * zero1(int channels, int samplesize, unsigned long samplerate, double seconds); // create a sound source static block_producer_wrapper * zero2( block_producer_wrapper *prototype); // creates a block producer that produces the sound as described in the 'prototype'-array. all values in the prototype-array should be within the range [-1, 1] static block_producer_wrapper * function(const std::vector<double> & prototype, unsigned short channel_count, int sample_size, unsigned long sample_rate, unsigned long frame_count); // only change the header of a sample, without changing the actual byte data. mostly used to change the samplerate static block_producer_wrapper * reinterpret(block_producer_wrapper * source, unsigned long samplerate, unsigned short channels = 0, short bits = 0); // extracts one channel from a multi-channel stream static block_producer_wrapper * extract_channel(block_producer_wrapper * source, short channel); // create an iterator on an input stream static iterator_wrapper * iterator(block_producer_wrapper * source, double window_size, double jump_size = 0.0); // modulate a sound source with a floating point sound stream... static block_producer_wrapper * amp_modulate(block_producer_wrapper * source, block_producer_wrapper * modulator); // convert the samples in the source stream to a different type. static block_producer_wrapper * convert(block_producer_wrapper * source, int samplesize); };
[ [ [ 1, 193 ] ] ]
e571d384a53ec976c34afa62dbf54e87f17f10d8
daa67e21cc615348ba166d31eb25ced40fba9dc7
/GameCode/Object.h
1b0aa6dda9dcffbb2b15eada0e2894867dece558
[]
no_license
gearsin/geartesttroject
443d48b7211f706ab2c5104204bad7228458c3f2
f86f255f5e9d1d34a00a4095f601a8235e39aa5a
refs/heads/master
2020-05-19T14:27:35.821340
2008-09-02T19:51:16
2008-09-02T19:51:16
32,342,555
0
0
null
null
null
null
UTF-8
C++
false
false
3,673
h
//------------------------------------------------------------------------------------------------------------------ #ifndef OBJECT_H #define OBJECT_H //------------------------------------------------------------------------------------------------------------------ #include "Vector.h" //------------------------------------------------------------------------------------------------------------------ class cMesh; class cFrustum; //------------------------------------------------------------------------------------------------------------------ class cObject { public: cObject( const WCHAR * pFileName ); cObject( const WCHAR * pFileName, const cVector & pPos ); ~cObject(); void SetTranslation( const cVector & pPos ); void SetTranslation( const float pX, const float pY, const float pZ ); cVector GetTranslation(); void SetRotation( const cVector & pRot ); cVector GetRotation(); void SetRotation( const float pRotX, const float pRotY, const float pRotZ ); void ScaleBy( const float pScaleVal ); void ScaleBy( const float pScaleX, const float pScaleY, const float pScaleZ ); void SetScale( const float pScaleX, const float pScaleY, const float pScaleZ ); void Update( cFrustum * pFrustum ); void Render(); //Obsolute shuld be removed const WCHAR * GetName(); void SetName( const WCHAR * pName ); void SetSphereBound( const cVector & pCenter, const float Radius ); void SetSphereBound( const cSphere & pSphere ); protected: private: void ComputeBoundingBoxAndSphere(); private: std::wstring m_Name; cVector m_Translation; cVector m_Rotation; cVector m_Scale; cVector m_BoxMin; //Bounding box min cVector m_BoxMax; //bounding box max cSphere m_BoundSphere; D3DXMATRIX m_WorldMat; cMesh * m_Mesh; }; //------------------------------------------------------------------------------------------------------------------ inline void cObject::SetName( const WCHAR * pName ) { m_Name = pName; } //------------------------------------------------------------------------------------------------------------------ inline const WCHAR * cObject::GetName() { return m_Name.c_str(); } //------------------------------------------------------------------------------------------------------------------ inline void cObject::SetSphereBound( const cVector & pCenter, const float Radius ) { m_BoundSphere.m_Center = pCenter; } //------------------------------------------------------------------------------------------------------------------ inline void cObject::SetSphereBound( const cSphere &pSphere ) { m_BoundSphere.m_Center = pSphere.m_Center; m_BoundSphere.m_Radius = pSphere.m_Radius; } //------------------------------------------------------------------------------------------------------------------ inline cVector cObject::GetTranslation() { return m_Translation; } //------------------------------------------------------------------------------------------------------------------ inline cVector cObject::GetRotation() { // cVector Rot = m_Rotation; // // ////toEuler() ////{ // cVector euler; // euler.x = asin( m_WorldMat._11 ); // // if( acos( euler.x ) != 0.f) // { // euler.y = atan2( -m_WorldMat._31, m_WorldMat._33 ); // euler.z = atan2( -m_WorldMat._12, m_WorldMat._22 ); // } // else // { // euler.y = 0.f; // euler.z = atan2( m_WorldMat._21, m_WorldMat._11 ); // } // ////} // return m_Rotation; } //------------------------------------------------------------------------------------------------------------------ #endif
[ "sunil.ssingh@592c7993-d951-0410-8115-35849596357c" ]
[ [ [ 1, 121 ] ] ]
6f622a836674e84e5dcc8456bbecd2709508d92d
061348a6be0e0e602d4a5b3e0af28e9eee2d257f
/Examples/Tutorial/ParticleSystem/06Explosion.cpp
a4582f743dd3374035f018658672307fd8ba3389
[]
no_license
passthefist/OpenSGToolbox
4a76b8e6b87245685619bdc3a0fa737e61a57291
d836853d6e0647628a7dd7bb7a729726750c6d28
refs/heads/master
2023-06-09T22:44:20.711657
2010-07-26T00:43:13
2010-07-26T00:43:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,568
cpp
// General OpenSG configuration, needed everywhere #include "OSGConfig.h" // A little helper to simplify scene management and interaction #include "OSGSimpleSceneManager.h" #include "OSGNode.h" #include "OSGGroup.h" #include "OSGViewport.h" #include "OSGSimpleGeometry.h" #include "OSGWindowUtils.h" // Input #include "OSGKeyListener.h" #include "OSGBlendChunk.h" #include "OSGTextureObjChunk.h" #include "OSGImageFileHandler.h" #include "OSGChunkMaterial.h" #include "OSGMaterialChunk.h" #include "OSGParticleSystem.h" #include "OSGParticleSystemCore.h" #include "OSGPointParticleSystemDrawer.h" #include "OSGSphereDistribution3D.h" #include "OSGQuadParticleSystemDrawer.h" #include "OSGQuadParticleSystemDrawer.h" #include "OSGBurstParticleGenerator.h" #include "OSGGaussianNormalDistribution1D.h" #include "OSGCylinderDistribution3D.h" #include "OSGLineDistribution3D.h" //#include "OSGSizeDistribution3D.h" // Activate the OpenSG namespace OSG_USING_NAMESPACE // The SimpleSceneManager to manage simple applications SimpleSceneManager *mgr; WindowEventProducerRefPtr TutorialWindow; // Forward declaration so we can have the interesting stuff upfront void display(void); void reshape(Vec2f Size); void ClickToGenerate(const MouseEventUnrecPtr e); Distribution3DRefPtr createPositionDistribution(void); Distribution1DRefPtr createLifespanDistribution(void); Distribution3DRefPtr createVelocityDistribution(void); Distribution3DRefPtr createVelocityDistribution2(void); Distribution3DRefPtr createAccelerationDistribution(void); Distribution3DRefPtr createSizeDistribution(void); ParticleSystemRefPtr Example1ParticleSystem; ParticleSystemRefPtr Example2ParticleSystem; QuadParticleSystemDrawerRefPtr Example1ParticleSystemDrawer; QuadParticleSystemDrawerRefPtr Example2ParticleSystemDrawer; BurstParticleGeneratorRefPtr ExampleBurstGenerator; BurstParticleGeneratorRefPtr Example2BurstGenerator; // Create a class to allow for the use of the Ctrl+q class TutorialKeyListener : public KeyListener { public: virtual void keyPressed(const KeyEventUnrecPtr e) { if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND) { TutorialWindow->closeWindow(); } if(e->getKey() == KeyEvent::KEY_B)//generate particles when clicked { //Attach the Generator to the Particle System Example1ParticleSystem->pushToGenerators(ExampleBurstGenerator); Example2ParticleSystem->pushToGenerators(Example2BurstGenerator); } } virtual void keyReleased(const KeyEventUnrecPtr e) { } virtual void keyTyped(const KeyEventUnrecPtr e) { UInt32 CHANGE_SOURCE; if(e->getKey()== KeyEvent::KEY_P) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_POSITION_CHANGE; } else if(e->getKey()== KeyEvent::KEY_C) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_VELOCITY_CHANGE; } else if(e->getKey()== KeyEvent::KEY_V) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_VELOCITY; } else if(e->getKey()== KeyEvent::KEY_A) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_ACCELERATION; } else if(e->getKey()== KeyEvent::KEY_N) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_PARTICLE_NORMAL; } else if(e->getKey()== KeyEvent::KEY_D) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_VIEW_POSITION; } else if(e->getKey()== KeyEvent::KEY_S) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_STATIC; } else if(e->getKey()== KeyEvent::KEY_W) { CHANGE_SOURCE = QuadParticleSystemDrawer::NORMAL_VIEW_DIRECTION; } else { return; } Example1ParticleSystemDrawer->setNormalSource(CHANGE_SOURCE); } }; void ClickToGenerate(const MouseEventUnrecPtr e) { } class TutorialMouseListener : public MouseListener { public: virtual void mouseClicked(const MouseEventUnrecPtr e) { if(e->getButton()== MouseEvent::BUTTON1) { } if(e->getButton()== MouseEvent::BUTTON3) { } } virtual void mouseEntered(const MouseEventUnrecPtr e) { } virtual void mouseExited(const MouseEventUnrecPtr e) { } virtual void mousePressed(const MouseEventUnrecPtr e) { mgr->mouseButtonPress(e->getButton(), e->getLocation().x(), e->getLocation().y()); } virtual void mouseReleased(const MouseEventUnrecPtr e) { mgr->mouseButtonRelease(e->getButton(), e->getLocation().x(), e->getLocation().y()); } }; class TutorialMouseMotionListener : public MouseMotionListener { public: virtual void mouseMoved(const MouseEventUnrecPtr e) { mgr->mouseMove(e->getLocation().x(), e->getLocation().y()); } virtual void mouseDragged(const MouseEventUnrecPtr e) { mgr->mouseMove(e->getLocation().x(), e->getLocation().y()); } }; int main(int argc, char **argv) { // OSG init osgInit(argc,argv); // Set up Window TutorialWindow = createNativeWindow(); TutorialWindow->initWindow(); TutorialWindow->setDisplayCallback(display); TutorialWindow->setReshapeCallback(reshape); TutorialKeyListener TheKeyListener; TutorialWindow->addKeyListener(&TheKeyListener); TutorialMouseListener TheTutorialMouseListener; TutorialMouseMotionListener TheTutorialMouseMotionListener; TutorialWindow->addMouseListener(&TheTutorialMouseListener); TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener); // Create the SimpleSceneManager helper mgr = new SimpleSceneManager; // Tell the Manager what to manage mgr->setWindow(TutorialWindow); BlendChunkRefPtr PSBlendChunk = BlendChunk::create(); PSBlendChunk->setSrcFactor(GL_SRC_ALPHA); PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA); //Particle System Material TextureObjChunkRefPtr QuadTextureObjChunk = TextureObjChunk::create(); ImageRefPtr LoadedImage = ImageFileHandler::the()->read("./Data/Cloud.png"); QuadTextureObjChunk->setImage(LoadedImage); MaterialChunkRefPtr PSMaterialChunk = MaterialChunk::create(); PSMaterialChunk->setAmbient(Color4f(0.3f,0.3f,0.3f,1.0f)); PSMaterialChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f)); PSMaterialChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f)); PSMaterialChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE); ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create(); PSMaterial->addChunk(QuadTextureObjChunk); PSMaterial->addChunk(PSMaterialChunk); PSMaterial->addChunk(PSBlendChunk); //Particle System Material 2 TextureObjChunkRefPtr QuadTextureObjChunk2 = TextureObjChunk::create(); ImageRefPtr LoadedImage2 = ImageFileHandler::the()->read("./Data/Cloud.png"); QuadTextureObjChunk2->setImage(LoadedImage2); MaterialChunkRefPtr PSMaterialChunk2 = MaterialChunk::create(); PSMaterialChunk2->setAmbient(Color4f(0.3f,0.3f,0.3f,1.0f)); PSMaterialChunk2->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f)); PSMaterialChunk2->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f)); PSMaterialChunk2->setColorMaterial(GL_AMBIENT_AND_DIFFUSE); ChunkMaterialRefPtr PSMaterial2 = ChunkMaterial::create(); PSMaterial2->addChunk(QuadTextureObjChunk2); PSMaterial2->addChunk(PSMaterialChunk2); PSMaterial2->addChunk(PSBlendChunk); //Particle System Example1ParticleSystem = OSG::ParticleSystem::create(); Example1ParticleSystem->attachUpdateListener(TutorialWindow); Example2ParticleSystem = OSG::ParticleSystem::create(); Example2ParticleSystem->attachUpdateListener(TutorialWindow); //Particle System Drawer Example1ParticleSystemDrawer = OSG::QuadParticleSystemDrawer::create(); Example2ParticleSystemDrawer = OSG::QuadParticleSystemDrawer::create(); //Attach the function objects to the Generator //Generator 1 ExampleBurstGenerator = OSG::BurstParticleGenerator::create(); ExampleBurstGenerator->setPositionDistribution(createPositionDistribution()); ExampleBurstGenerator->setLifespanDistribution(createLifespanDistribution()); ExampleBurstGenerator->setBurstAmount(50.0); ExampleBurstGenerator->setVelocityDistribution(createVelocityDistribution()); ExampleBurstGenerator->setAccelerationDistribution(createAccelerationDistribution()); ExampleBurstGenerator->setSizeDistribution(createSizeDistribution()); //Generator 2 Example2BurstGenerator = OSG::BurstParticleGenerator::create(); Example2BurstGenerator->setPositionDistribution(createPositionDistribution()); Example2BurstGenerator->setLifespanDistribution(createLifespanDistribution()); Example2BurstGenerator->setBurstAmount(50.0); Example2BurstGenerator->setVelocityDistribution(createVelocityDistribution2()); Example2BurstGenerator->setAccelerationDistribution(createAccelerationDistribution()); Example2BurstGenerator->setSizeDistribution(createSizeDistribution()); //Particle System Node ParticleSystemCoreRefPtr ParticleNodeCore = OSG::ParticleSystemCore::create(); ParticleNodeCore->setSystem(Example1ParticleSystem); ParticleNodeCore->setDrawer(Example1ParticleSystemDrawer); ParticleNodeCore->setMaterial(PSMaterial); NodeRefPtr ParticleNode = OSG::Node::create(); ParticleNode->setCore(ParticleNodeCore); //Particle System Node2 ParticleSystemCoreRefPtr ParticleNodeCore2 = OSG::ParticleSystemCore::create(); ParticleNodeCore2->setSystem(Example2ParticleSystem); ParticleNodeCore2->setDrawer(Example2ParticleSystemDrawer); ParticleNodeCore2->setMaterial(PSMaterial2); NodeRefPtr ParticleNode2 = OSG::Node::create(); ParticleNode2->setCore(ParticleNodeCore2); //Ground Node NodeRefPtr GoundNode = makePlane(30.0,30.0,10,10); Matrix GroundTransformation; GroundTransformation.setRotate(Quaternion(Vec3f(1.0f,0.0,0.0), -3.14195f)); TransformRefPtr GroundTransformCore = Transform::create(); GroundTransformCore->setMatrix(GroundTransformation); NodeRefPtr GroundTransformNode = Node::create(); GroundTransformNode->setCore(GroundTransformCore); GroundTransformNode->addChild(GoundNode); // Make Main Scene Node and add the Torus NodeRefPtr scene = OSG::Node::create(); scene->setCore(OSG::Group::create()); scene->addChild(ParticleNode); scene->addChild(ParticleNode2); scene->addChild(GroundTransformNode); mgr->setRoot(scene); // Show the whole Scene mgr->showAll(); //Open Window Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f); Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5); TutorialWindow->openWindow(WinPos, WinSize, "06Explosion"); //Enter main Loop TutorialWindow->mainLoop(); osgExit(); return 0; } // Callback functions // Redraw the window void display(void) { mgr->redraw(); } // React to size changes void reshape(Vec2f Size) { mgr->resize(Size.x(), Size.y()); } Distribution3DRefPtr createPositionDistribution(void) { //Sphere Distribution SphereDistribution3DRefPtr TheSphereDistribution = SphereDistribution3D::create(); TheSphereDistribution->setCenter(Pnt3f(0.0,0.0,0.0)); TheSphereDistribution->setInnerRadius(0.0); TheSphereDistribution->setOuterRadius(3.0); TheSphereDistribution->setMinTheta(0.0); TheSphereDistribution->setMaxTheta(6.283185); TheSphereDistribution->setMinZ(-1.0); TheSphereDistribution->setMaxZ(1.0); TheSphereDistribution->setSurfaceOrVolume(SphereDistribution3D::SURFACE); return TheSphereDistribution; } Distribution3DRefPtr createVelocityDistribution(void) { //Sphere Distribution SphereDistribution3DRefPtr TheSphereDistribution = SphereDistribution3D::create(); TheSphereDistribution->setCenter(Pnt3f(0.0,0.0,0.0)); TheSphereDistribution->setInnerRadius(3.0); TheSphereDistribution->setOuterRadius(10.0); TheSphereDistribution->setMinTheta(-3.141950); TheSphereDistribution->setMaxTheta(3.141950); TheSphereDistribution->setMinZ(0.0); TheSphereDistribution->setMaxZ(1.0); TheSphereDistribution->setSurfaceOrVolume(SphereDistribution3D::VOLUME); return TheSphereDistribution; } Distribution3DRefPtr createVelocityDistribution2(void) { //Sphere Distribution SphereDistribution3DRefPtr TheSphereDistribution = SphereDistribution3D::create(); TheSphereDistribution->setCenter(Pnt3f(0.0,0.0,0.0)); TheSphereDistribution->setInnerRadius(6.0); TheSphereDistribution->setOuterRadius(10.0); TheSphereDistribution->setMinTheta(-3.141950); TheSphereDistribution->setMaxTheta(3.141950); TheSphereDistribution->setMinZ(0.0); TheSphereDistribution->setMaxZ(1.0); TheSphereDistribution->setSurfaceOrVolume(SphereDistribution3D::VOLUME); return TheSphereDistribution; } Distribution1DRefPtr createLifespanDistribution(void) { GaussianNormalDistribution1DRefPtr TheLifespanDistribution = GaussianNormalDistribution1D::create(); TheLifespanDistribution->setMean(30.0f); TheLifespanDistribution->setStandardDeviation(5.0); return TheLifespanDistribution; } Distribution3DRefPtr createAccelerationDistribution(void) { //Sphere Distribution LineDistribution3DRefPtr TheLineDistribution = LineDistribution3D::create(); TheLineDistribution->setPoint1(Pnt3f(0.0,0.0,-3.0)); TheLineDistribution->setPoint2(Pnt3f(0.0,0.0,-3.0)); return TheLineDistribution; } Distribution3DRefPtr createSizeDistribution(void) { //Sphere Distribution LineDistribution3DRefPtr TheLineDistribution = LineDistribution3D::create(); TheLineDistribution->setPoint1(Pnt3f(5.0,5.0,1.0)); TheLineDistribution->setPoint2(Pnt3f(10.0,10.0,1.0)); return TheLineDistribution; }
[ [ [ 1, 72 ], [ 74, 452 ] ], [ [ 73, 73 ] ] ]
bccdbf88e8f41bc27e7a808bd34d8f0c99f3cd74
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/brookbox/wm2/WmlStringTree.h
df0bbbb26c353ccd3f42b7162f8492fc9663e381
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
3,165
h
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #ifndef WMLSTRINGTREE_H #define WMLSTRINGTREE_H #include "WmlBound.h" #include "WmlColorRGB.h" #include "WmlMatrix2.h" #include "WmlMatrix3.h" #include "WmlQuaternion.h" #include "WmlRTTI.h" #include "WmlVector2.h" #include "WmlVector3.h" #include <vector> namespace Wml { class WML_ITEM StringTree { public: // construction and destruction StringTree (int iStringQuantity, int iStringGrowBy, int iChildQuantity, int iChildGrowBy); ~StringTree (); // strings void SetStringQuantity (int iQuantity); int GetStringQuantity () const; char* SetString (int i, char* acString); char* GetString (int i); // children void SetChildQuantity (int iQuantity); int GetChildQuantity () const; StringTree* SetChild (int i, StringTree* pkChild); StringTree* GetChild (int i); // streaming bool Save (const char* acFilename, int iTabSize = 4); protected: // streaming (recursive) void Save (FILE* pkOFile, int iLevel, int iTabSize); // node data std::vector<char*> m_kStrings; int m_iStringGrowBy; // children std::vector<StringTree*> m_kChildren; int m_iChildGrowBy; }; // string creation helpers (native types) WML_ITEM char* MakeString (const RTTI* pkRTTI, const char* acName); WML_ITEM char* MakeString (const char* acString); WML_ITEM char* MakeString (const char* acPrefix, bool bValue); WML_ITEM char* MakeString (const char* acPrefix, char cValue); WML_ITEM char* MakeString (const char* acPrefix, unsigned char ucValue); WML_ITEM char* MakeString (const char* acPrefix, short sValue); WML_ITEM char* MakeString (const char* acPrefix, unsigned short usValue); WML_ITEM char* MakeString (const char* acPrefix, int iValue); WML_ITEM char* MakeString (const char* acPrefix, unsigned int uiValue); WML_ITEM char* MakeString (const char* acPrefix, long lValue); WML_ITEM char* MakeString (const char* acPrefix, unsigned long ulValue); WML_ITEM char* MakeString (const char* acPrefix, float fValue); WML_ITEM char* MakeString (const char* acPrefix, double dValue); WML_ITEM char* MakeString (const char* acPrefix, void* pvValue); WML_ITEM char* MakeString (const char* acPrefix, const char* acValue); WML_ITEM char* MakeString (const char* acPrefix, const ColorRGB& rkValue); WML_ITEM char* MakeString (const char* acPrefix, const Matrix3f& rkValue); WML_ITEM char* MakeString (const char* acPrefix, const Quaternionf& rkValue); WML_ITEM char* MakeString (const char* acPrefix, const Vector2f& rkValue); WML_ITEM char* MakeString (const char* acPrefix, const Vector3f& rkValue); WML_ITEM char* MakeString (const char* acPrefix, const Bound& rkValue); #include "WmlStringTree.inl" } #endif
[ [ [ 1, 93 ] ] ]
c8aaf2f4277f16bbdb18005fd33fdcf37849b715
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/misc/pre90s/d_meijinsn.cpp
bb1804dd6824091810c28f7d5c8e2bf8b5d9f3b7
[]
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
13,532
cpp
// FB Alpha Meijinsen Driver Module // Based on MAME driver by Tomasz Slanina #include "burnint.h" #include "driver.h" extern "C" { #include "ay8910.h" } static unsigned int *Palette; static unsigned char *Mem, *M68KRom, *Z80Rom, *Prom; static short *pFMBuffer, *pAY8910Buffer[3]; static unsigned char DrvJoy1[9], DrvJoy2[8], DrvReset, DrvDips; static unsigned char soundlatch, deposits1, deposits2, credits; static struct BurnInputInfo DrvInputList[] = { {"Coin 1", BIT_DIGITAL, DrvJoy1 + 6, "p1 coin" }, {"Coin 2", BIT_DIGITAL, DrvJoy2 + 6, "p2 coin" }, {"Start 1", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" }, {"Start 2", BIT_DIGITAL, DrvJoy2 + 7, "p2 start" }, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" }, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" }, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 2, "p1 right" }, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 3, "p1 left" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" }, {"P2 Up", BIT_DIGITAL, DrvJoy2 + 0, "p2 up" }, {"P2 Down", BIT_DIGITAL, DrvJoy2 + 1, "p2 down" }, {"P2 Right", BIT_DIGITAL, DrvJoy2 + 2, "p2 right" }, {"P2 Left", BIT_DIGITAL, DrvJoy2 + 3, "p2 left" }, {"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1" }, {"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 5, "p2 fire 2" }, {"Clear Credit",BIT_DIGITAL, DrvJoy1 + 8, "clear credit" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Dip Switches",BIT_DIPSWITCH, &DrvDips, "dip" }, }; STDINPUTINFO(Drv) static struct BurnDIPInfo DrvDIPList[] = { // Defaults {0x12, 0xFF, 0xFF, 0x00, NULL}, {0, 0xFE, 0, 8, "Game time (actual game)"}, {0x12, 0x01, 0x07, 0x07, "01:00"}, {0x12, 0x01, 0x07, 0x06, "02:00"}, {0x12, 0x01, 0x07, 0x05, "03:00"}, {0x12, 0x01, 0x07, 0x04, "04:00"}, {0x12, 0x01, 0x07, 0x03, "05:00"}, {0x12, 0x01, 0x07, 0x02, "10:00"}, {0x12, 0x01, 0x07, 0x01, "20:00"}, {0x12, 0x01, 0x07, 0x00, "00:30"}, {0, 0xFE, 0, 2, "Coinage"}, {0x12, 0x01, 0x08, 0x08, "A 1C/1C B 1C/5C"}, {0x12, 0x01, 0x08, 0x00, "A 1C/2C B 2C/1C"}, {0, 0xFE, 0, 2, "2 Player"}, {0x12, 0x01, 0x10, 0x00, "1C"}, {0x12, 0x01, 0x10, 0x10, "2C"}, {0, 0xFE, 0, 2, "Game time (tsumeshougi)"}, {0x12, 0x01, 0x20, 0x20, "01:00"}, {0x12, 0x01, 0x20, 0x00, "02:00"}, }; STDDIPINFO(Drv) unsigned short inputs(int inp) { unsigned char ret = 0; switch (inp) { case 0x00: { // start + service ret |= DrvJoy1[7] << 0; // ret |= DrvJoy2[7] << 1; ret |= DrvJoy1[8] << 7; // clear credit } break; case 0x01: { // player 1 controls for (int i = 0; i < 6; i++) ret |= DrvJoy1[i] << i; } break; case 0x02: { // player 2 controls for (int i = 0; i < 6; i++) ret |= DrvJoy2[i] << i; } break; case 0x03: { // coins ret = (DrvJoy1[6] | (DrvJoy2[6] << 1)) ^ 3; } break; break; } return ret; } unsigned char soundlatch_r(unsigned int) { return soundlatch; } unsigned char __fastcall alpha_mcu_r(unsigned char offset) { static unsigned coinvalue = 0; static const unsigned char coinage1[2][2] = { {1, 1}, {1, 2} }; static const unsigned char coinage2[2][2] = { {1, 5}, {2, 1} }; static int latch; switch (offset) { case 0x01: // Dipswitch 2 M68KRom[0x180e44] = DrvDips & 0xff; return 0; case 0x45: // Coin value M68KRom[0x180e44] = credits & 0xff; return 0; case 0x53: // Query microcontroller for coin insert { credits = 0; if ((inputs(3) & 0x03) == 0x03) latch = 0; M68KRom[0x180e52] = 0x22; if ((inputs(3) & 0x03) != 0x03 && latch == 0) { M68KRom[0x180e44] = 0x00; latch = 1; coinvalue = (~DrvDips>>3) & 1; if (~inputs(3) & 0x01) { deposits1++; if (deposits1 == coinage1[coinvalue][0]) { credits = coinage1[coinvalue][1]; deposits1 = 0; } else credits = 0; } else if (~inputs(3) & 0x02) { deposits2++; if (deposits2 == coinage2[coinvalue][0]) { credits = coinage2[coinvalue][1]; deposits2 = 0; } else credits = 0; } } } return 0; } return 0; } unsigned char __fastcall meijinsn_read_byte(unsigned int a) { if ((a & ~0xff) == 0x080e00) { return alpha_mcu_r(a & 0xff); } switch (a) { case 0x1a0000: return inputs(0); case 0x1a0001: return inputs(1); case 0x1c0000: return inputs(2); } return 0; } void __fastcall meijinsn_write_byte(unsigned int a, unsigned char d) { if (a == 0x1a0001) { soundlatch = d & 0xff; return; } } unsigned char __fastcall meijinsn_in_port(unsigned short a) { if ((a & 0xff) == 0x01) { // AY8910 read port return AY8910Read(0); } return 0; } void __fastcall meijinsn_out_port(unsigned short a, unsigned char data) { switch (a & 0xff) { case 0x00: // AY8910 control port AY8910Write(0, 0, data); break; case 0x01: // AY8910 write port AY8910Write(0, 1, data); break; case 0x02: // Soundlatch clear soundlatch = 0; break; } } static int DrvDoReset() { DrvReset = 0; memset (M68KRom + 0x100000, 0, 0x082000); // clear 68k RAM memset (Z80Rom + 0x008000, 0, 0x000800); // clear z80 RAM deposits1 = 0; deposits2 = 0; credits = 0; SekOpen(0); SekReset(); SekClose(); ZetOpen(0); ZetReset(); ZetClose(); AY8910Reset(0); return 0; } static void Pallete_Init() { #define combine_3_weights(tab,w0,w1,w2) ((int)(((tab)[0]*(w0) + (tab)[1]*(w1) + (tab)[2]*(w2)) + 0.5)) float weights_r[3] = { 41.697944f, 73.045335f, 140.256721f}; float weights_g[3] = { 41.697944f, 73.045335f, 140.256721f}; float weights_b[3] = { 83.228546f, 159.809836f, 0.000000f}; for (int i = 0; i < 0x10; i++) { int bit0,bit1,bit2,r,g,b; // red component bit0 = (Prom[i] >> 0) & 0x01; bit1 = (Prom[i] >> 1) & 0x01; bit2 = (Prom[i] >> 2) & 0x01; r = combine_3_weights(weights_r, bit0, bit1, bit2); // green component bit0 = (Prom[i] >> 3) & 0x01; bit1 = (Prom[i] >> 4) & 0x01; bit2 = (Prom[i] >> 5) & 0x01; g = combine_3_weights(weights_g, bit0, bit1, bit2); // blue component bit0 = (Prom[i] >> 6) & 0x01; bit1 = (Prom[i] >> 7) & 0x01; b = combine_3_weights(weights_b, bit0, bit1, 0); Palette[i] = (r << 16) | (g << 8) | b; } } static int DrvInit() { Mem = (unsigned char *)malloc(0x210060); if (Mem == NULL) { return 1; } M68KRom = Mem + 0x000000; Z80Rom = Mem + 0x200000; Prom = Mem + 0x210000; Palette = (unsigned int *)(Mem + 0x210020); pFMBuffer = (short *)malloc (nBurnSoundLen * 3 * sizeof(short)); if (pFMBuffer == NULL) { return 1; } pAY8910Buffer[0] = pFMBuffer + nBurnSoundLen * 0; pAY8910Buffer[1] = pFMBuffer + nBurnSoundLen * 1; pAY8910Buffer[2] = pFMBuffer + nBurnSoundLen * 2; // Load roms { int i; for (i = 0; i < 8; i+=2) { BurnLoadRom(M68KRom + 0x100001, i + 0, 2); BurnLoadRom(M68KRom + 0x100000, i + 1, 2); memcpy (M68KRom + 0x00000 + 0x08000 * (i >> 1), M68KRom + 0x100000, 0x08000); memcpy (M68KRom + 0x20000 + 0x08000 * (i >> 1), M68KRom + 0x108000, 0x08000); } BurnLoadRom(Z80Rom + 0x00000, 8, 1); BurnLoadRom(Z80Rom + 0x04000, 9, 1); BurnLoadRom(Prom, 10, 1); } SekInit(0, 0x68000); SekOpen(0); SekMapMemory(M68KRom, 0x000000, 0x03ffff, SM_ROM); SekMapMemory(M68KRom + 0x100000, 0x100000, 0x181fff, SM_RAM); SekSetReadByteHandler(0, meijinsn_read_byte); SekSetWriteByteHandler(0, meijinsn_write_byte); SekClose(); ZetInit(1); ZetOpen(0); ZetMapArea(0x0000, 0xffff, 0, Z80Rom); ZetMapArea(0x0000, 0x7fff, 2, Z80Rom); ZetMapArea(0x8000, 0x87ff, 0, Z80Rom + 0x8000); ZetMapArea(0x8000, 0x87ff, 1, Z80Rom + 0x8000); ZetMapArea(0x8000, 0x87ff, 2, Z80Rom + 0x8000); ZetSetInHandler(meijinsn_in_port); ZetSetOutHandler(meijinsn_out_port); ZetMemEnd(); ZetClose(); AY8910Init(0, 2000000, nBurnSoundRate, &soundlatch_r, NULL, NULL, NULL); Pallete_Init(); DrvDoReset(); return 0; } static int DrvExit() { AY8910Exit(0); SekExit(); ZetExit(); free (Mem); Palette = NULL; free (pFMBuffer); Mem = M68KRom = Z80Rom = Prom = NULL; pFMBuffer = NULL; pAY8910Buffer[0] = pAY8910Buffer[1] = pAY8910Buffer[2] = NULL; return 0; } static int DrvDraw() { for (int i = 0; i < 0x4000; i++) { int sx, sy, x, data1, data2, color, data; sx = (i >> 6) & 0xfc; sy = i & 0xff; if (sy < 16 || sy > 239 || sx < 12 || sx > 240) continue; sx -= 12; sy = (sy - 16) * 232; data1 = M68KRom[0x100001 + (i << 1)]; data2 = M68KRom[0x100000 + (i << 1)]; for (x = 0; x < 4; x++) { color = ((data1 >> x) & 1) | ((data1 >> (3 + x)) & 2); data = ((data2 >> x) & 1) | ((data2 >> (3 + x)) & 2); unsigned int c = Palette[(color << 2) | data]; PutPix(pBurnDraw + (sy + sx + (x ^ 3)) * nBurnBpp, BurnHighCol(c >> 16, c >> 8, c, 0)); } } return 0; } static int DrvFrame() { if (DrvReset) { DrvDoReset(); } int nSoundBufferPos = 0; int nInterleave = 160; int nCyclesSegment; int nCyclesDone[2], nCyclesTotal[2]; nCyclesTotal[0] = 9000000 / 60; nCyclesTotal[1] = 4000000 / 60; nCyclesDone[0] = nCyclesDone[1] = 0; SekOpen(0); ZetOpen(0); for (int i = 0; i < nInterleave; i++) { int nNext; // Run 68k nNext = (i + 1) * nCyclesTotal[0] / nInterleave; nCyclesSegment = nNext - nCyclesDone[0]; nCyclesDone[0] += SekRun(nCyclesSegment); if (i == 79) SekSetIRQLine(2, SEK_IRQSTATUS_AUTO); if (i == 159) SekSetIRQLine(1, SEK_IRQSTATUS_AUTO); // Run Z80 #1 nNext = (i + 1) * nCyclesTotal[1] / nInterleave; nCyclesSegment = nNext - nCyclesDone[1]; nCyclesSegment = ZetRun(nCyclesSegment); nCyclesDone[1] += nCyclesSegment; ZetSetIRQLine(0, ZET_IRQSTATUS_AUTO); // Render Sound Segment if (pBurnSoundOut) { int nSample; int nSegmentLength = nBurnSoundLen - nSoundBufferPos; short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); AY8910Update(0, &pAY8910Buffer[0], nSegmentLength); for (int n = 0; n < nSegmentLength; n++) { nSample = pAY8910Buffer[0][n]; nSample += pAY8910Buffer[1][n]; nSample += pAY8910Buffer[2][n]; nSample /= 4; if (nSample < -32768) { nSample = -32768; } else { if (nSample > 32767) { nSample = 32767; } } pSoundBuf[(n << 1) + 0] = nSample; pSoundBuf[(n << 1) + 1] = nSample; } nSoundBufferPos += nSegmentLength; } } ZetClose(); SekClose(); // Make sure the buffer is entirely filled. if (pBurnSoundOut) { int nSample; int nSegmentLength = nBurnSoundLen - nSoundBufferPos; short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); if (nSegmentLength) { AY8910Update(0, &pAY8910Buffer[0], nSegmentLength); for (int n = 0; n < nSegmentLength; n++) { nSample = pAY8910Buffer[0][n]; nSample += pAY8910Buffer[1][n]; nSample += pAY8910Buffer[2][n]; nSample /= 4; if (nSample < -32768) { nSample = -32768; } else { if (nSample > 32767) { nSample = 32767; } } pSoundBuf[(n << 1) + 0] = nSample; pSoundBuf[(n << 1) + 1] = nSample; } } } if (pBurnDraw) { DrvDraw(); } return 0; } static int DrvScan(int nAction,int *pnMin) { struct BurnArea ba; if (pnMin) { // Return minimum compatible version *pnMin = 0x029521; } if (nAction & ACB_VOLATILE) { // Scan volatile ram memset(&ba, 0, sizeof(ba)); ba.Data = M68KRom + 0x100000; ba.nLen = 0x082000; ba.szName = "Main 68K Ram"; BurnAcb(&ba); memset(&ba, 0, sizeof(ba)); ba.Data = Z80Rom + 0x8000; ba.nLen = 0x00800; ba.szName = "Main Z80 Ram"; BurnAcb(&ba); SekScan(nAction); // Scan 68K ZetScan(nAction); // Scan Z80 AY8910Scan(nAction, pnMin); // Scan AY8910 // Scan critical driver variables SCAN_VAR(soundlatch); SCAN_VAR(deposits1); SCAN_VAR(deposits2); SCAN_VAR(credits); } return 0; } // Meijinsen static struct BurnRomInfo meijinsnRomDesc[] = { { "p1", 0x08000, 0x8c9697a3, BRF_PRG | BRF_ESS }, // 0 M68000 Code { "p2", 0x08000, 0xf7da3535, BRF_PRG | BRF_ESS }, // 1 { "p3", 0x08000, 0x0af0b266, BRF_PRG | BRF_ESS }, // 2 { "p4", 0x08000, 0xaab159c5, BRF_PRG | BRF_ESS }, // 3 { "p5", 0x08000, 0x0ed10a47, BRF_PRG | BRF_ESS }, // 4 { "p6", 0x08000, 0x60b58755, BRF_PRG | BRF_ESS }, // 5 { "p7", 0x08000, 0x604c76f1, BRF_PRG | BRF_ESS }, // 6 { "p8", 0x08000, 0xe3eaef19, BRF_PRG | BRF_ESS }, // 7 { "p9", 0x04000, 0xaedfefdf, BRF_PRG | BRF_ESS }, // 8 Z80 Code { "p10", 0x04000, 0x93b4d764, BRF_PRG | BRF_ESS }, // 9 { "clr", 0x00020, 0x7b95b5a7, BRF_GRA }, // 10 Color Prom }; STD_ROM_PICK(meijinsn) STD_ROM_FN(meijinsn) struct BurnDriver BurnDrvMeijinsn = { "meijinsn", NULL, NULL, "1986", "Meijinsen\0", NULL, "SNK Electronics corp.", "Miscellaneous", L"\u540D\u4EBA\u6226\0Meijinsen\0", NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_MISC_MISC, NULL, meijinsnRomInfo, meijinsnRomName, DrvInputInfo, DrvDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, NULL, 232, 224, 4, 3 };
[ [ [ 1, 573 ] ] ]
2f508544c4001f04312f0804aaacdaae86b87b71
7f6f9788d020e97f729af85df4f6741260274bee
/include/gui/Graphics.h
ebc3f083c3526cb851953ff89c9472f3d0c73580
[]
no_license
cnsuhao/nyanco
0fb88ed1cf2aa9390fa62f6723e8424ba9a42ed4
ba199267a33d4c6d2e473ed4b777765057aaf844
refs/heads/master
2021-05-31T05:37:51.892873
2008-05-27T05:23:19
2008-05-27T05:23:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,779
h
#pragma once /*! @file Graphics.h @author dasyprocta */ #include "gui_base.h" #include <d3d9.h> #include <string> BEGIN_NAMESPACE_NYANCO_GUI class Graphics { public: virtual void setColor( Color color) = 0; virtual void setRectColor( Color color) = 0; virtual void setRectColor( Color leftTop, Color rightTop, Color leftBottom, Color rightBottom) = 0; virtual void drawText( Point<sint32> const& point, std::string const& text, Color color, Rect<sint32> const& region) = 0; virtual void drawRect( Rect<sint32> const& rect) = 0; virtual void drawFillRect( Rect<sint32> const& rect) = 0; virtual void drawLine( Point<sint32> const& p1, Point<sint32> const& p2) = 0; virtual void drawIbeamCursor( Point<sint32> const& p) = 0; virtual void drawTriangle( Point<sint32> const& p1, Point<sint32> const& p2, Point<sint32> const& p3) = 0; }; class ComponentGraphics { public: ComponentGraphics(Graphics& g) : m_g(g) {} void drawEdit(Rect<sint32> const& rect); void drawButton(Rect<sint32> const& rect, bool pushed); void drawFrame(Rect<sint32> const& rect, bool rise = true, bool gradation = false); private: Graphics& m_g; }; END_NAMESPACE_NYANCO_GUI
[ "dasyprocta@27943c09-b335-0410-ab52-7f3c671fdcc1" ]
[ [ [ 1, 67 ] ] ]
e062c27e35039e4d19f3f0ee4ebc402e5b7bedce
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/Demo/PtzMenu.cpp
a7c79fcc52549d48b311cb6c760de6078fe18bde
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,516
cpp
// PtzMenu.cpp : implementation file // #include "stdafx.h" #include "netsdkdemo.h" #include "PtzMenu.h" #include "NetSDKDemoDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CPtzMenu dialog CPtzMenu::CPtzMenu(CWnd* pParent /*=NULL*/) : CDialog(CPtzMenu::IDD, pParent) { m_DeviceID = 0; m_Channel = 0; //{{AFX_DATA_INIT(CPtzMenu) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CPtzMenu::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPtzMenu) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPtzMenu, CDialog) //{{AFX_MSG_MAP(CPtzMenu) ON_BN_CLICKED(IDC_OPR_CANCEL, OnOprCancel) ON_BN_CLICKED(IDC_OPR_CLOSEMENU, OnOprClosemenu) ON_BN_CLICKED(IDC_OPR_DOWN, OnOprDown) ON_BN_CLICKED(IDC_OPR_LEFT, OnOprLeft) ON_BN_CLICKED(IDC_OPR_OK, OnOprOk) ON_BN_CLICKED(IDC_OPR_OPENMENU, OnOprOpenmenu) ON_BN_CLICKED(IDC_OPR_RIGHT, OnOprRight) ON_BN_CLICKED(IDC_OPR_UP, OnOprUp) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPtzMenu message handlers void CPtzMenu::SetPtzParam(LONG iHandle, int iChannel) { m_DeviceID = iHandle; m_Channel = iChannel; } void CPtzMenu::OnOprCancel() { PtzMemuControl(EXTPTZ_MENUCANCEL); } void CPtzMenu::OnOprClosemenu() { PtzMemuControl(EXTPTZ_CLOSEMENU); } void CPtzMenu::OnOprDown() { PtzMemuControl(EXTPTZ_MENUDOWN); } void CPtzMenu::OnOprLeft() { PtzMemuControl(EXTPTZ_MENULEFT); } void CPtzMenu::OnOprOk() { PtzMemuControl(EXTPTZ_MENUOK); } void CPtzMenu::OnOprOpenmenu() { PtzMemuControl(EXTPTZ_OPENMENU); } void CPtzMenu::OnOprRight() { PtzMemuControl(EXTPTZ_MENURIGHT); } void CPtzMenu::OnOprUp() { PtzMemuControl(EXTPTZ_MENUUP); } void CPtzMenu::PtzMemuControl(DWORD dwCommand) { if(!m_DeviceID) { MessageBox(ConvertString(MSG_PTZCTRL_NOCHANNEL)); } BOOL ret = CLIENT_YWPTZControl(m_DeviceID, m_Channel,dwCommand ,0,0,0,FALSE); if(!ret) { ((CNetSDKDemoDlg *)GetParent())->LastError();//Peng Dongfeng 06.11.24 MessageBox(ConvertString(MSG_PTZCTRL_CTRLFAILED)); } } BOOL CPtzMenu::OnInitDialog() { CDialog::OnInitDialog(); g_SetWndStaticText(this); return TRUE; }
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 120 ] ] ]
9929f3046d5f886b3e2b2608d349128fd578993f
0c3a06d695d13a1727f3fbafae91f41e54688322
/SRC/CHESS.CPP
edf5213777831b66eb36f2c0706f285492bf2273
[]
no_license
deccico/chessbuilder
24bec1d5188814731415bb8c286453c878b2d9e3
9692cf6b3b7469d5760414ef43706ae5948ed945
refs/heads/master
2023-07-29T04:21:19.089490
1999-04-01T11:49:49
2021-09-07T11:49:49
403,958,020
0
0
null
null
null
null
IBM852
C++
false
false
8,264
cpp
//Programa Ajedrez //Archivo: ajedrez.cpp (archivo principal) /********************************************************************** Materia: Algoritmos y Programación III 7507 curso 003 Profesor: Carlos Fontela Ayudante: Sergio Pap Trabajo Práctico: Implementación de Ajedrez: Jaque al Rey Archivo: chess.cpp Grupo:14 Fontdevila Diego 74169 [email protected] Deccico Adrißn 75223 [email protected] Descripción: El trabajo tiene por finalidad la implementaciˇn de una aplicación que permita a dos jugadores jugar interactivamente al ajedrez contra la computadora. La computadora realizará la supervisión de la partida, convalidará las jugadas de cada jugador y permitirá administrar las partidas. Entorno: Builder C++ 3.0 Segunda Entrega - (Implemetaciˇn de Jaque, Mate, Coronaciˇn y enroque) *******************************************************************/ #pragma hdrstop #include <condefs.h> //--------------------------------------------------------------------------- USEUNIT("tablero.cpp"); USEUNIT("ejercito.cpp"); USEUNIT("partida.cpp"); USEUNIT("pieza.cpp"); USEUNIT("str.cpp"); USEUNIT("chess.cpp"); //--------------------------------------------------------------------------- #pragma argsused #include <fstream> //incluye a iostream #include <conio.h> //la funcion gotoxy #include <ctype.h> #include <string> #include "partida.h" #include "str.h" #include "tablero.h" #include "ejercito.h" #include "pieza.h" using std::string; using namespace std; //--------------------------------------------------------------------------- void ImprimirOpciones() { cout <<" Ingrese su movida o elija 1 Nuevo Juego 2 Abrir 3 Guardar 0 para salir\n"; cout <<" ej: 'a1-a2'\n"; gotoxy(1,23); cout <<"\nIngrese su opcion: "; } //imprime el tablero //y avisa si la movida es invßlida, hay jaque o mate void Imprimir (cPartida &oPartida, int nEstado=0) { clrscr(); gotoxy(20,1); cout <<" Algortimos y Programación III \n"; gotoxy(20,2); cout <<"████████████████████ Ing.Fontela\n"; gotoxy(20,3); cout <<"█cJUEGO de oAJEDREZ███ TP AJEDREZ versión 2.0\n"; gotoxy(20,4); cout <<"██████████████████████ g.14 Deccico-Fontdevila\n"; gotoxy(20,5); cout <<" ████████████████████ ayudante: Javier Macchi\n"; gotoxy(5,7); oPartida.mImprimir(); //dibuja el tablero cout << endl; gotoxy(10,18); switch (nEstado) { case 4: //pieza clavada cout <<" Movida inválida. Las "; cout << (oPartida.mMueven() == 'b' ? "blancas" : "negras"); cout << " quedarían en Jaque\n"; gotoxy(1,19); cout <<" Juegan las "; cout <<(oPartida.mMueven() == 'b' ? "blancas" : "negras")<<"\n\n"; ImprimirOpciones(); break; case 3: //jaque mate cout <<" Las "; cout << (oPartida.mMueven() == 'b' ? "negras" : "blancas"); cout << " han dado Jaque Mate"; break; case 2: //jaque cout <<" Las "; cout << (oPartida.mMueven() == 'b' ? "blancas" : "negras"); cout << " se encuentran en Jaque\n "; gotoxy(1,19); cout <<" Juegan las "; cout <<(oPartida.mMueven() == 'b' ? "blancas" : "negras")<<"\n\n"; ImprimirOpciones(); break; case 1: //movida invalida cout << " Movida inválida "; gotoxy(1,19); cout <<" Juegan las "; cout <<(oPartida.mMueven() == 'b' ? "blancas" : "negras")<<"\n\n"; ImprimirOpciones(); break; case 0: //movida normal gotoxy(1,19); cout <<" Juegan las "; cout <<(oPartida.mMueven() == 'b' ? "blancas" : "negras")<<"\n\n"; ImprimirOpciones(); break; } } //fin Imprimir //Ingreso de la movida por parte del usuario //realizando la validaciˇn de la misma string Input(cPartida &oPartida, int nEstado) { bool lvale; string sOpcion=" "; do //validación del ingreso del usuario { Imprimir(oPartida,nEstado); lvale=false; cin >> sOpcion; sOpcion= Minuscula(sOpcion); //*********VALIDACION DEL INPUT //if que chequea que el caracter ingresado sea 1, 2, o 3 //en caso de que sea un ingreso de longitud 1 if ( sOpcion.length()==1 && sOpcion >= "0" && sOpcion <= "3") lvale=true; //if que chequea que el caracter 1║ y 4║ sean letras y el 2do y 5to n˙meros //en caso de que sea un ingreso de longitud mayor a 4 if (sOpcion.length() >4 && ( sOpcion[0] <= 'h' && sOpcion[0] >= 'a' && sOpcion[3] <= 'h' && sOpcion[3] >= 'a' && sOpcion[1] <= '8' && sOpcion[1] >= '1' && sOpcion[4] <= '8' && sOpcion[4] >= '1') ) lvale=true; //*********FIN VALIDACION DEL INPUT }while (!lvale); //fin do..while return sOpcion; }//fin Input //Maneja la interface con el usuario //pre inicialicar un objeto partida //post devuelve 0 si se eligiˇ salir, 2 en caso de mate 1 por default int menu(cPartida &oPartida ) { int nEstado,nOpcion; //indica el estado de la partida. Jaque, Mate o jugada corriente string sOpcion=" ",sNombre=" ",sC1=" ",sC2=" ",sName=" "; //chequeo de jaque y mate if (oPartida.mHayJaque()) { if (oPartida.mHayMate()) {Imprimir(oPartida,3); //imprimir mate return 0; //salir } else nEstado=2; //jaque } else nEstado=0; //Imprimir una movida normal bool vale=false; do //Input de la jugada, vertifica que sea valida, y la pieza no este clavada { sOpcion=Input(oPartida,nEstado); //Input de las pieza a mover nOpcion=Entero(sOpcion); if (sOpcion=="0") nOpcion=10; switch (nOpcion) { case 10 : //salir return 0; case 1 : //Nueva Partida oPartida.mVaciar(); oPartida.mCargar(); return 1; case 2 : //Abrir partida gotoxy(1,23); cout <<"\nIngrese el nombre del archivo: "; cin >> sName; oPartida.mVaciar(); if (!oPartida.mCargar(sName)) { gotoxy(1,1); cout <<" ERROR, no se ha hallado "<<sName; oPartida.mCargar(); } return 1; case 3 : //Guardar partida gotoxy(1,23); cout <<"\nIngrese el nombre del archivo: "; cin >> sName; oPartida.mGuardar(sName); return 1; case 0 : //realizar la movida correspondiente sC1=sOpcion.substr(0,2); //casilla origen sC2=sOpcion.substr(3,2); //casilla destino if (oPartida.mEsMovidaValida(sC1,sC2) ) {if (oPartida.mEstaClavado(sC1,sC2)) nEstado=4; //pieza clavada else vale=true; } else nEstado=1; //movida no valida }//fin switch }while (!vale); oPartida.mSetEnroque(sC1);//establece variables de control para evitar enroque oPartida.mMover ( sC1,sC2 ); oPartida.mSiguienteMovida(); return 1; //sale pero indica al main que se repita el ciclo }//fin menu //Funcion principal del programa int main(int argc, char **argv) { bool conpiezas= argc == 1; cPartida oPartida(conpiezas); if ( !conpiezas ) oPartida.mCargar(); int lOpcion; do { lOpcion=menu(oPartida); } while (lOpcion==1); cout << " GAME OVER "; }//fin main()
[ [ [ 1, 258 ] ] ]
8cfb6c83c0ab38241592db3fbcf19a777334e951
c58f258a699cc866ce889dc81af046cf3bff6530
/src/python/math/rndgen_wrap.cpp
ef42138a854720028c15478c1ec99764c30edc15
[]
no_license
KoWunnaKo/qmlib
db03e6227d4fff4ad90b19275cc03e35d6d10d0b
b874501b6f9e537035cabe3a19d61eed7196174c
refs/heads/master
2021-05-27T21:59:56.698613
2010-02-18T08:27:51
2010-02-18T08:27:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,529
cpp
#include <qmlib/python/converters.hpp> #include <qmlib/math/random/all.hpp> QM_NAMESPACE2(math) qm_int SOBOL_BITS = 8*sizeof(qm_uns_long); qm_real SOBOL_NFACT = 0.5/(1UL<<(SOBOL_BITS-1)); template<int D> const qm_int SobolGenerator<D>::c_bits = SOBOL_BITS; template<int D> const qm_real SobolGenerator<D>::c_normalizationFactor = SOBOL_NFACT; QM_NAMESPACE_END2 QM_NAMESPACE2(python) BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(rndgen_nextUniform, nextUniform, 0, 2) BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(rndgen_nextNormalVariate, nextNormalVariate, 0, 2) void rndgen_wrap() { using namespace boost::python; QM_USING_NAMESPACE2(math); //return_value_policy<copy_const_reference> ccr; class_<rndgen, bases<basedes> >("rndgen", "Random Number Generator", no_init) .def("next", &rndgen::nextUniform, rndgen_nextUniform(args("index", "dimension"), "Generate the next random uniform number in [0 1]")) .def("nextNormalVariate", &rndgen::nextNormalVariate, rndgen_nextNormalVariate(args("index", "dimension"), "Generate the next random standard normal variate")) .add_property("maxdimension", &rndgen::maxdimension) ; class_<MersenneTwister, bases<rndgen> >("MersenneTwister", "MersenneTwister 19937 pseudo-random number generator", init< optional<qm_long> >()); class_<sobol0, bases<rndgen> >("sobol0", "Sobol low-discrepancy sequence", init< optional<qm_long,qm_long> >(args("maxDimension","seed"), "maxDimension")); class_<sobol1, bases<rndgen> >("sobol1", "Sobol low-discrepancy sequence", init< optional<qm_long,qm_long> >(args("maxDimension","seed"), "maxDimension")); class_<sobol2, bases<rndgen> >("sobol2", "Sobol low-discrepancy sequence", init< optional<qm_long,qm_long> >(args("maxDimension","seed"), "maxDimension")); class_<sobol3, bases<rndgen> >("sobol3", "Sobol low-discrepancy sequence", init< optional<qm_long,qm_long> >(args("maxDimension","seed"), "maxDimension")); class_<halton, bases<rndgen> >("halton", "Halton low-discrepancy sequence", init< optional<qm_long> >(args("maxDimension"), "maxDimension")); def("randomdate",randomdate,"rndgen,start,end"); } QM_NAMESPACE_END2
[ [ [ 1, 58 ] ] ]
2530732479b333f768693bbc854b7ad04bf62c34
41371839eaa16ada179d580f7b2c1878600b718e
/REGIONAIS/SULAMERICANA/2003/club.cpp
e934d4e1295d3c16a5aa4a6eb62b89e7a2cf838a
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
615
cpp
#include<cstdio> #include<algorithm> #define EPS 1e-3 using namespace std; int set[120][120]; int oc[120]; int ans, i, j, ign, K; double R; int main(void){ while(scanf("%d%lf",&K,&R) && K){ ans = 1; for(i = 0; i < K; i++) scanf("%d%d",&set[0][i],&ign), oc[i] = 0; oc[0] = K; sort(set[0],set[0]+K); int lim = K-1; for(i = 0; i < lim; i++) if(R*set[0][i] < set[0][lim]) for(j = 1; ; j++) if(oc[j] == 0 || !(R*set[j][0]+EPS < set[0][i])){ if(oc[j] == 0) ans++; set[j][oc[j]++] = set[0][i]; break; } printf("%d\n",ans); } return 0; }
[ [ [ 1, 29 ] ] ]
1ce6d8d8017df9a32ae72f806ea52e6f0a05fa5c
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/svm/linearly_independent_subset_finder_abstract.h
ccf76d555473748745f5324ce7550d7f3f294223
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
6,466
h
// Copyright (C) 2008 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_LISf_ABSTRACT_ #ifdef DLIB_LISf_ABSTRACT_ #include "../algs.h" #include "../serialize.h" #include "kernel_abstract.h" namespace dlib { template < typename kernel_type > class linearly_independent_subset_finder { /*! REQUIREMENTS ON kernel_type is a kernel function object as defined in dlib/svm/kernel_abstract.h INITIAL VALUE - dictionary_size() == 0 WHAT THIS OBJECT REPRESENTS This is an implementation of an online algorithm for recursively finding a set of linearly independent vectors in a kernel induced feature space. To use it you decide how large you would like the set to be and then you feed it sample points. Each time you present it with a new sample point (via this->add()) it either keeps the current set of independent points unchanged, or if the new point is "more linearly independent" than one of the points it already has, it replaces the weakly linearly independent point with the new one. This object uses the Approximately Linearly Dependent metric described in the paper The Kernel Recursive Least Squares Algorithm by Yaakov Engel to decide which points are more linearly independent than others. !*/ public: typedef typename kernel_type::scalar_type scalar_type; typedef typename kernel_type::sample_type sample_type; typedef typename kernel_type::mem_manager_type mem_manager_type; linearly_independent_subset_finder ( const kernel_type& kernel_, unsigned long max_dictionary_size, scalar_type min_tolerance = 0.001 ); /*! requires - min_tolerance > 0 ensures - #minimum_tolerance() == min_tolerance - this object is properly initialized - #get_kernel() == kernel_ - #max_dictionary_size() == max_dictionary_size_ !*/ const kernel_type& get_kernel ( ) const; /*! ensures - returns a const reference to the kernel used by this object !*/ unsigned long max_dictionary_size( ) const; /*! ensures - returns the maximum number of dictionary vectors this object will accumulate. That is, dictionary_size() will never be greater than max_dictionary_size(). !*/ scalar_type minimum_tolerance( ) const; /*! ensures - returns the minimum tolerance to use for the approximately linearly dependent test used for dictionary vector selection (see KRLS paper for ALD details). In other words, this is the minimum threshold for how linearly independent a sample must be for it to even be considered for addition to the dictionary. Moreover, bigger values of this field will make the algorithm run faster but might give less accurate results. !*/ void clear_dictionary ( ); /*! ensures - clears out all the data (e.g. #dictionary_size() == 0) !*/ void add ( const sample_type& x ); /*! ensures - if (x is linearly independent of the vectors already in this object) then - adds x into the dictionary - if (dictionary_size() < max_dictionary_size()) then - #dictionary_size() == dictionary_size() + 1 - else - #dictionary_size() == dictionary_size() (i.e. the number of vectors in this object doesn't change) - the least linearly independent vector in this object is removed !*/ void swap ( linearly_independent_subset_finder& item ); /*! ensures - swaps *this with item !*/ unsigned long dictionary_size ( ) const; /*! ensures - returns the number of vectors in the dictionary. !*/ const sample_type& operator[] ( unsigned long index ) const; /*! requires - index < dictionary_size() ensures - returns the index'th element in the set of linearly independent vectors contained in this object. !*/ const matrix<sample_type,0,1,mem_manager_type> get_dictionary ( ) const; /*! ensures - returns a column vector that contains all the dictionary vectors in this object. !*/ }; // ---------------------------------------------------------------------------------------- template < typename kernel_type > void swap( linearly_independent_subset_finder<kernel_type>& a, linearly_independent_subset_finder<kernel_type>& b ) { a.swap(b); } /*! provides a global swap function !*/ template < typename kernel_type > void serialize ( const linearly_independent_subset_finder<kernel_type>& item, std::ostream& out ); /*! provides serialization support for linearly_independent_subset_finder objects !*/ template < typename kernel_type > void deserialize ( linearly_independent_subset_finder<kernel_type>& item, std::istream& in ); /*! provides serialization support for linearly_independent_subset_finder objects !*/ // ---------------------------------------------------------------------------------------- } #endif // DLIB_LISf_ABSTRACT_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 189 ] ] ]
a2c5e14969d38519f5a2f4808e3253edc6109285
119ba245bea18df8d27b84ee06e152b35c707da1
/unreal/branches/svn/qrgui/generators/editors/editorGenerator.cpp
988348d9f60d480a701c4601da0644a35942601e
[]
no_license
nfrey/qreal
05cd4f9b9d3193531eb68ff238d8a447babcb3d2
71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164
refs/heads/master
2020-04-06T06:43:41.910531
2011-05-30T19:30:09
2011-05-30T19:30:09
1,634,768
0
0
null
null
null
null
UTF-8
C++
false
false
4,808
cpp
#include "editorGenerator.h" #include <QFile> #include <QTextStream> using namespace qReal; using namespace generators; EditorGenerator::EditorGenerator(qrRepo::RepoApi const &api) : mApi(api) { } void EditorGenerator::generate(Id const &editor) { createMetaEditor(editor); } // Функция, генерирующая сущности и отношения в редакторе QDomElement EditorGenerator::createNode(QDomDocument doc, Id const &nodeId, QString const &prefix) { QString stringType = mApi.stringProperty(nodeId, "entity_type"); if (stringType != "node" && stringType != "edge") stringType = "node"; QString const postPrefix = stringType == "node" ? "n" : "e"; QString const nameString = mApi.name(nodeId); QString const idString = prefix + postPrefix + nameString; QDomElement resultElement = doc.createElement(stringType); QDomElement graphElement = doc.createElement("graphics"); QDomElement viewElement = doc.createElement("view"); graphElement.appendChild(viewElement); resultElement.appendChild(graphElement); QDomElement domLogicElement = doc.createElement("logic"); resultElement.appendChild(domLogicElement); QDomElement domPropElement = doc.createElement("properties"); QDomElement domGeneElement = doc.createElement("generalizations"); resultElement.setAttribute("id", idString); resultElement.setAttribute("name", nameString); if (mApi.stringProperty(nodeId, "line_type") != "" && postPrefix == "e") { QDomElement lineType = doc.createElement("line_type"); lineType.setAttribute("type", mApi.stringProperty(nodeId, "line_type")); viewElement.appendChild(lineType); } if (postPrefix == "n") { QDomElement picture = doc.createElement("picture"); picture.setAttribute("sizex", "31"); picture.setAttribute("sizey", "100"); viewElement.appendChild(picture); } // here links should be proceded IdList const links = mApi.outgoingLinks(nodeId); foreach (Id const link, links) { //here we are asking things about link // TODO: Не знаю, что тут должно происходить, надо разобраться. Id const otherNode = mApi.otherEntityFromLink(link, nodeId); if (mApi.typeName(otherNode) == "mednMetaEntityAttribute") { QDomElement domProp = doc.createElement("property"); domPropElement.appendChild(domProp); domProp.setAttribute("name", mApi.name(otherNode)); QString const attributeType = mApi.stringProperty(otherNode, "attributeType"); domProp.setAttribute("type", attributeType.isEmpty() ? "string" : attributeType); } else if (mApi.typeName(otherNode) == "mednMetaEntity") { QDomElement domGene = doc.createElement("parent"); domGeneElement.appendChild(domGene); QString const entityType = mApi.stringProperty(otherNode, "entity_type"); domGene.setAttribute("parent_id", prefix + (entityType == "node" ? "n" : "e") + mApi.name(otherNode)); } else { QDomElement domGene = doc.createElement("parent"); domGeneElement.appendChild(domGene); domGene.setAttribute("parent_id", mApi.typeName(otherNode)); } } domLogicElement.appendChild(domPropElement); domLogicElement.appendChild(domGeneElement); return resultElement; } // Функция создает и сохраняет редактор редактор void EditorGenerator::createMetaEditor(Id const &editor) { QString editorTitle = mApi.name(editor); QString includeString = "kernel_metamodel"; QString entityPrefix = mApi.stringProperty(editor, "prefix_name"); if (entityPrefix.isEmpty()) entityPrefix = "tmp"; QDomDocument doc(editorTitle); QDomElement domMainElement = doc.createElement("metamodel"); domMainElement.setAttribute("xmlns","http://schema.real.com/schema/"); doc.appendChild(domMainElement); QDomElement domIncludeEl = doc.createElement("include"); domIncludeEl.appendChild(doc.createTextNode(includeString)); QDomElement domNamespaceEl = doc.createElement("namespace"); domNamespaceEl.appendChild(doc.createTextNode(editorTitle)); QDomElement domEditorEl = doc.createElement("editor"); domMainElement.appendChild(domIncludeEl); domMainElement.appendChild(domNamespaceEl); domMainElement.appendChild(domEditorEl); domEditorEl.setAttribute("name", editorTitle); IdList const children = mApi.children(editor); foreach (Id const child, children) { if (mApi.typeName(child) == "mednMetaEntity") { QDomElement domNewNode = createNode(doc, child, entityPrefix); domEditorEl.appendChild(domNewNode); } } QFile file(editorTitle + ".xml"); if (file.open(QIODevice::WriteOnly)) { QTextStream(&file) << "<?xml version='1.0' encoding='utf-8'?>\n"; QTextStream(&file) << doc.toString(); file.close(); } }
[ [ [ 1, 128 ] ] ]
0c13adaa09b17efdf922911cd8cf58e169be6a84
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/renaissance/rnsgameplay/src/ncgameplaysquad/ncgameplaysquad_main.cc
04f47c60458f85c30d739f2f461626ee2e2846e8
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,518
cc
#include "precompiled/pchgameplay.h" //------------------------------------------------------------------------------ // ncgameplaysquad_main.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "ncgameplaysquad/ncgameplaysquad.h" #include "entity/nentityserver.h" //------------------------------------------------------------------------------ /** Constructor */ ncGameplaySquad::ncGameplaySquad() : ncGameplayGroup() { // empty } //------------------------------------------------------------------------------ /** Destructor */ ncGameplaySquad::~ncGameplaySquad() { // empty } //------------------------------------------------------------------------------ /** SetSquadLeader */ void ncGameplaySquad::SetSquadLeader (unsigned int idLeader) { nEntityServer* entityServer = nEntityServer::Instance(); n_assert(entityServer); if ( entityServer ) { if ( idLeader !=0 ) { this->leader = entityServer->GetEntityObject (idLeader); } else { this->leader = 0; } } } //------------------------------------------------------------------------------ /** GetSquadLeader */ unsigned int ncGameplaySquad::GetSquadLeader() const { unsigned int idLeader = 0; if ( this->leader ) { idLeader = this->leader->GetId(); } return idLeader; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 66 ] ] ]
ba4d0937382d3d282752c81d21bf8add7ac150f7
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Stellar_/code/Foundation/Debuging/win32/win32minidump.cc
0330aecbb6c5b8c3498cbd388658e992a38de9cf
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
2,359
cc
//------------------------------------------------------------------------------ // win32minidump.cc // (C) 2007 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "debuging/win32/win32minidump.h" //#include "io/win32/win32fswrapper.h" //#include "time/calendartime.h" namespace Win32 { using namespace Util; //using namespace Timing; //using namespace IO; //------------------------------------------------------------------------------ /** This method is called by s_assert() and s_error() to write out a minidump file. */ bool Win32MiniDump::WriteMiniDump() { //#if (STELLAR_ENABLE_MINIDUMPS) // String dumpFilename = BuildMiniDumpFilename(); // if (dumpFilename.IsValid()) // { // Win32FSWrapper::Handle hFile = Win32FSWrapper::OpenFile(dumpFilename, Stream::WriteAccess, Stream::Sequential); // if (NULL != hFile) // { // HANDLE hProc = GetCurrentProcess(); // DWORD procId = GetCurrentProcessId(); // BOOL res = MiniDumpWriteDump(hProc, procId, hFile, MiniDumpNormal, NULL, NULL, NULL); // Win32FSWrapper::CloseFile(hFile); // return true; // } // } //#endif return false; } //------------------------------------------------------------------------------ /** */ String Win32MiniDump::BuildMiniDumpFilename() { String dumpFilename; dumpFilename = "null"; // get our module filename directly from windows //TCHAR buf[512]; //Memory::Clear(buf, sizeof(buf)); //DWORD numBytes = GetModuleFileName(NULL, buf, sizeof(buf) - 1); //if (numBytes > 0) //{ // String modulePath(buf); // String moduleName = modulePath.ExtractFileName(); // moduleName.StripFileExtension(); // modulePath = modulePath.ExtractToLastSlash(); // // get the current calender time // CalendarTime calTime = CalendarTime::GetLocalTime(); // String timeStr = CalendarTime::Format("{YEAR}-{MONTH}-{DAY}_{HOUR}-{MINUTE}-{SECOND}", calTime); // // // build the dump filename // dumpFilename.Format("%s%s_%s.dmp", modulePath.c_str(), moduleName.c_str(), timeStr.c_str()); //} return dumpFilename; } } // namespace Debug
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 73 ] ] ]
130048ce10e1c4751360500f87b569a27bb1bc66
656de8005c621f24d86a65062a49abd98b0ec753
/example/simplecpp/main.cpp
fd73c20e5c18e9dd1cfb05c7d92b16fc1942b9cd
[]
no_license
jmckaskill/adbus
0016002b99e68d6c1e118a53931bd253661439e2
a8ad1368cfc5b925b336c6243626f86d96a353b0
refs/heads/master
2016-09-05T12:00:38.077922
2010-03-22T20:49:51
2010-03-22T20:49:51
340,965
5
2
null
null
null
null
UTF-8
C++
false
false
2,921
cpp
/* vim: ts=4 sw=4 sts=4 et * * Copyright (c) 2009 James R. McKaskill * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * ---------------------------------------------------------------------------- */ #include <adbuscpp.h> #include <string.h> #include <stdio.h> #ifdef _WIN32 # include <windows.h> #else # include <sys/socket.h> #endif static adbus_ssize_t Send(void* d, adbus_Message* m) { return send(*(adbus_Socket*) d, m->data, m->size, 0); } class Quitter : public adbus::State { public: Quitter() :m_Quit(false) {} void quit() { m_Quit = true; } bool m_Quit; }; static adbus::Interface<Quitter>* Interface() { static adbus::Interface<Quitter>* i = NULL; if (i == NULL) { i = new adbus::Interface<Quitter>("nz.co.foobar.Test.Quit"); i->addMethod0("Quit", &Quitter::quit); } return i; } #define RECV_SIZE 64 * 1024 int main() { adbus_Buffer* buf = adbus_buf_new(); adbus_Socket s = adbus_sock_connect(ADBUS_SESSION_BUS); if (s == ADBUS_SOCK_INVALID || adbus_sock_cauth(s, buf)) abort(); adbus_ConnectionCallbacks cbs = {}; cbs.send_message = &Send; adbus::Connection c(&cbs, &s); Quitter q; q.bind(c, "/", Interface(), &q); // Once we are all setup, we connect to the bus c.connectToBus(); adbus::State state; adbus::Proxy bus(&state); bus.init(c, "org.freedesktop.DBus", "/"); bus.call("RequestName", "nz.co.foobar.adbus.SimpleCppTest", uint32_t(0)); while(!q.m_Quit) { char* dest = adbus_buf_recvbuf(buf, RECV_SIZE); adbus_ssize_t recvd = recv(s, dest, RECV_SIZE, 0); adbus_buf_recvd(buf, RECV_SIZE, recvd); if (recvd < 0) abort(); if (c.parse(buf)) abort(); } return 0; }
[ [ [ 1, 99 ] ] ]
ba0490ec5d632b5a612c3dc2acac5476122d3c74
1caba14ec096b36815b587f719dda8c963d60134
/branches/smxgroup/smx/libsmx/pstime.h
e34bb01a8844339dc81a3fc0139c3705e1aaa2e2
[]
no_license
BackupTheBerlios/smx-svn
0502dff1e494cffeb1c4a79ae8eaa5db647e5056
7955bd611e88b76851987338b12e47a97a327eaf
refs/heads/master
2021-01-10T19:54:39.450497
2009-03-01T12:24:56
2009-03-01T12:24:56
40,749,397
0
0
null
null
null
null
UTF-8
C++
false
false
645
h
/* COPYRIGHT 1998 Prime Data Corp. All Rights Reserved. Use of this file without prior written authorization is strictly prohibited. */ #ifndef _PSTIME_H #define _PSTIME_H #include <time.h> class qStr; class qTime { time_t myTime; public: qTime() {myTime = 0;} operator time_t &() {return (myTime);} qTime & operator = (time_t t) {myTime = t; return *this;} int Compare(time_t time) {return (myTime > time ? 1 : myTime < time ? -1 : 0);} static long GetZoneOffset() {return timezone;} }; void FmtTime(struct tm * tms, const char *p, qStr *out); #endif // #ifndef _PSTIME_H
[ "simul@407f561b-fe63-0410-8234-8332a1beff53" ]
[ [ [ 1, 36 ] ] ]
bc60efd5d9a30380c701c2cfb771901180025692
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iterator/test/zip_iterator_test.cpp
df5091933270383518a530f3472c85e1f5c56a25
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
22,091
cpp
// (C) Copyright Dave Abrahams and Thomas Becker 2003. 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) // // File: // ===== // zip_iterator_test_main.cpp // Author: // ======= // Thomas Becker // Created: // ======== // Jul 15, 2003 // Purpose: // ======== // Test driver for zip_iterator.hpp // Compilers Tested: // ================= // Metrowerks Codewarrior Pro 7.2, 8.3 // gcc 2.95.3 // gcc 3.2 // Microsoft VC 6sp5 (test fails due to some compiler bug) // Microsoft VC 7 (works) // Microsoft VC 7.1 // Intel 5 // Intel 6 // Intel 7.1 // Intel 8 // Borland 5.5.1 (broken due to lack of support from Boost.Tuples) ///////////////////////////////////////////////////////////////////////////// // // Includes // ///////////////////////////////////////////////////////////////////////////// #include <boost/iterator/zip_iterator.hpp> #include <boost/iterator/zip_iterator.hpp> // 2nd #include tests #include guard. #include <iostream> #include <vector> #include <list> #include <set> #include <functional> #include <boost/tuple/tuple.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/is_readable_iterator.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/detail/workaround.hpp> #include <stddef.h> template <class It> struct pure_traversal : boost::detail::pure_traversal_tag< typename boost::iterator_traversal<It>::type > {}; ///////////////////////////////////////////////////////////////////////////// // // Das Main Funktion // ///////////////////////////////////////////////////////////////////////////// int main( void ) { std::cout << "\n" << "***********************************************\n" << "* *\n" << "* Test driver for boost::zip_iterator *\n" << "* Copyright Thomas Becker 2003 *\n" << "* *\n" << "***********************************************\n\n" << std::flush; size_t num_successful_tests = 0; size_t num_failed_tests = 0; ///////////////////////////////////////////////////////////////////////////// // // Zip iterator construction and dereferencing // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator construction and dereferencing: " << std::flush; std::vector<double> vect1(3); vect1[0] = 42.; vect1[1] = 43.; vect1[2] = 44.; std::set<int> intset; intset.insert(52); intset.insert(53); intset.insert(54); // typedef boost::zip_iterator< boost::tuples::tuple< std::set<int>::iterator , std::vector<double>::iterator > > zit_mixed; zit_mixed zip_it_mixed = zit_mixed( boost::make_tuple( intset.begin() , vect1.begin() ) ); boost::tuples::tuple<int, double> val_tuple( *zip_it_mixed); boost::tuples::tuple<const int&, double&> ref_tuple( *zip_it_mixed); double dblOldVal = boost::tuples::get<1>(ref_tuple); boost::tuples::get<1>(ref_tuple) -= 41.; if( 52 == boost::tuples::get<0>(val_tuple) && 42. == boost::tuples::get<1>(val_tuple) && 52 == boost::tuples::get<0>(ref_tuple) && 1. == boost::tuples::get<1>(ref_tuple) && 1. == *vect1.begin() ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } // Undo change to vect1 boost::tuples::get<1>(ref_tuple) = dblOldVal; ///////////////////////////////////////////////////////////////////////////// // // Zip iterator with 12 components // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterators with 12 components: " << std::flush; // Declare 12 containers // std::list<int> li1; li1.push_back(1); std::set<int> se1; se1.insert(2); std::vector<int> ve1; ve1.push_back(3); // std::list<int> li2; li2.push_back(4); std::set<int> se2; se2.insert(5); std::vector<int> ve2; ve2.push_back(6); // std::list<int> li3; li3.push_back(7); std::set<int> se3; se3.insert(8); std::vector<int> ve3; ve3.push_back(9); // std::list<int> li4; li4.push_back(10); std::set<int> se4; se4.insert(11); std::vector<int> ve4; ve4.push_back(12); // typedefs for cons lists of iterators. typedef boost::tuples::cons< std::set<int>::iterator, boost::tuples::tuple< std::vector<int>::iterator, std::list<int>::iterator, std::set<int>::iterator, std::vector<int>::iterator, std::list<int>::iterator, std::set<int>::iterator, std::vector<int>::iterator, std::list<int>::iterator, std::set<int>::iterator, std::vector<int>::const_iterator >::inherited > cons_11_its_type; // typedef boost::tuples::cons< std::list<int>::const_iterator, cons_11_its_type > cons_12_its_type; // typedefs for cons lists for dereferencing the zip iterator // made from the cons list above. typedef boost::tuples::cons< const int&, boost::tuples::tuple< int&, int&, const int&, int&, int&, const int&, int&, int&, const int&, const int& >::inherited > cons_11_refs_type; // typedef boost::tuples::cons< const int&, cons_11_refs_type > cons_12_refs_type; // typedef for zip iterator with 12 elements typedef boost::zip_iterator<cons_12_its_type> zip_it_12_type; // Declare a 12-element zip iterator. zip_it_12_type zip_it_12( cons_12_its_type( li1.begin(), cons_11_its_type( se1.begin(), boost::make_tuple( ve1.begin(), li2.begin(), se2.begin(), ve2.begin(), li3.begin(), se3.begin(), ve3.begin(), li4.begin(), se4.begin(), ve4.begin() ) ) ) ); // Dereference, mess with the result a little. cons_12_refs_type zip_it_12_dereferenced(*zip_it_12); boost::tuples::get<9>(zip_it_12_dereferenced) = 42; // Make a copy and move it a little to force some instantiations. zip_it_12_type zip_it_12_copy(zip_it_12); ++zip_it_12_copy; if( boost::tuples::get<11>(zip_it_12.get_iterator_tuple()) == ve4.begin() && boost::tuples::get<11>(zip_it_12_copy.get_iterator_tuple()) == ve4.end() && 1 == boost::tuples::get<0>(zip_it_12_dereferenced) && 12 == boost::tuples::get<11>(zip_it_12_dereferenced) && 42 == *(li4.begin()) ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator incrementing and dereferencing // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator ++ and *: " << std::flush; std::vector<double> vect2(3); vect2[0] = 2.2; vect2[1] = 3.3; vect2[2] = 4.4; boost::zip_iterator< boost::tuples::tuple< std::vector<double>::const_iterator, std::vector<double>::const_iterator > > zip_it_begin( boost::make_tuple( vect1.begin(), vect2.begin() ) ); boost::zip_iterator< boost::tuples::tuple< std::vector<double>::const_iterator, std::vector<double>::const_iterator > > zip_it_run( boost::make_tuple( vect1.begin(), vect2.begin() ) ); boost::zip_iterator< boost::tuples::tuple< std::vector<double>::const_iterator, std::vector<double>::const_iterator > > zip_it_end( boost::make_tuple( vect1.end(), vect2.end() ) ); if( zip_it_run == zip_it_begin && 42. == boost::tuples::get<0>(*zip_it_run) && 2.2 == boost::tuples::get<1>(*zip_it_run) && 43. == boost::tuples::get<0>(*(++zip_it_run)) && 3.3 == boost::tuples::get<1>(*zip_it_run) && 44. == boost::tuples::get<0>(*(++zip_it_run)) && 4.4 == boost::tuples::get<1>(*zip_it_run) && zip_it_end == ++zip_it_run ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator decrementing and dereferencing // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator -- and *: " << std::flush; if( zip_it_run == zip_it_end && zip_it_end == zip_it_run-- && 44. == boost::tuples::get<0>(*zip_it_run) && 4.4 == boost::tuples::get<1>(*zip_it_run) && 43. == boost::tuples::get<0>(*(--zip_it_run)) && 3.3 == boost::tuples::get<1>(*zip_it_run) && 42. == boost::tuples::get<0>(*(--zip_it_run)) && 2.2 == boost::tuples::get<1>(*zip_it_run) && zip_it_begin == zip_it_run ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator copy construction and equality // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator copy construction and equality: " << std::flush; boost::zip_iterator< boost::tuples::tuple< std::vector<double>::const_iterator, std::vector<double>::const_iterator > > zip_it_run_copy(zip_it_run); if(zip_it_run == zip_it_run && zip_it_run == zip_it_run_copy) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator inequality // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator inequality: " << std::flush; if(!(zip_it_run != zip_it_run_copy) && zip_it_run != ++zip_it_run_copy) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator less than // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator less than: " << std::flush; // Note: zip_it_run_copy == zip_it_run + 1 // if( zip_it_run < zip_it_run_copy && !( zip_it_run < --zip_it_run_copy) && zip_it_run == zip_it_run_copy ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator less than or equal // ///////////////////////////////////////////////////////////////////////////// std::cout << "zip iterator less than or equal: " << std::flush; // Note: zip_it_run_copy == zip_it_run // ++zip_it_run; zip_it_run_copy += 2; if( zip_it_run <= zip_it_run_copy && zip_it_run <= --zip_it_run_copy && !( zip_it_run <= --zip_it_run_copy) && zip_it_run <= zip_it_run ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator greater than // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator greater than: " << std::flush; // Note: zip_it_run_copy == zip_it_run - 1 // if( zip_it_run > zip_it_run_copy && !( zip_it_run > ++zip_it_run_copy) && zip_it_run == zip_it_run_copy ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator greater than or equal // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator greater than or equal: " << std::flush; ++zip_it_run; // Note: zip_it_run == zip_it_run_copy + 1 // if( zip_it_run >= zip_it_run_copy && --zip_it_run >= zip_it_run_copy && ! (zip_it_run >= ++zip_it_run_copy) ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator + int // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator + int: " << std::flush; // Note: zip_it_run == zip_it_run_copy - 1 // zip_it_run = zip_it_run + 2; ++zip_it_run_copy; if( zip_it_run == zip_it_run_copy && zip_it_run == zip_it_begin + 3 ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator - int // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator - int: " << std::flush; // Note: zip_it_run == zip_it_run_copy, and both are at end position // zip_it_run = zip_it_run - 2; --zip_it_run_copy; --zip_it_run_copy; if( zip_it_run == zip_it_run_copy && (zip_it_run - 1) == zip_it_begin ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator += // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator +=: " << std::flush; // Note: zip_it_run == zip_it_run_copy, and both are at begin + 1 // zip_it_run += 2; if( zip_it_run == zip_it_begin + 3 ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator -= // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator -=: " << std::flush; // Note: zip_it_run is at end position, zip_it_run_copy is at // begin plus one. // zip_it_run -= 2; if( zip_it_run == zip_it_run_copy ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator getting member iterators // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator member iterators: " << std::flush; // Note: zip_it_run and zip_it_run_copy are both at // begin plus one. // if( boost::tuples::get<0>(zip_it_run.get_iterator_tuple()) == vect1.begin() + 1 && boost::tuples::get<1>(zip_it_run.get_iterator_tuple()) == vect2.begin() + 1 ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Making zip iterators // ///////////////////////////////////////////////////////////////////////////// std::cout << "Making zip iterators: " << std::flush; std::vector<boost::tuples::tuple<double, double> > vect_of_tuples(3); std::copy( boost::make_zip_iterator( boost::make_tuple( vect1.begin(), vect2.begin() ) ), boost::make_zip_iterator( boost::make_tuple( vect1.end(), vect2.end() ) ), vect_of_tuples.begin() ); if( 42. == boost::tuples::get<0>(*vect_of_tuples.begin()) && 2.2 == boost::tuples::get<1>(*vect_of_tuples.begin()) && 43. == boost::tuples::get<0>(*(vect_of_tuples.begin() + 1)) && 3.3 == boost::tuples::get<1>(*(vect_of_tuples.begin() + 1)) && 44. == boost::tuples::get<0>(*(vect_of_tuples.begin() + 2)) && 4.4 == boost::tuples::get<1>(*(vect_of_tuples.begin() + 2)) ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator non-const --> const conversion // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator non-const to const conversion: " << std::flush; boost::zip_iterator< boost::tuples::tuple< std::set<int>::const_iterator, std::vector<double>::const_iterator > > zip_it_const( boost::make_tuple( intset.begin(), vect2.begin() ) ); // boost::zip_iterator< boost::tuples::tuple< std::set<int>::iterator, std::vector<double>::const_iterator > > zip_it_half_const( boost::make_tuple( intset.begin(), vect2.begin() ) ); // boost::zip_iterator< boost::tuples::tuple< std::set<int>::iterator, std::vector<double>::iterator > > zip_it_non_const( boost::make_tuple( intset.begin(), vect2.begin() ) ); zip_it_half_const = ++zip_it_non_const; zip_it_const = zip_it_half_const; ++zip_it_const; // zip_it_non_const = ++zip_it_const; // Error: can't convert from const to non-const if( 54 == boost::tuples::get<0>(*zip_it_const) && 4.4 == boost::tuples::get<1>(*zip_it_const) && 53 == boost::tuples::get<0>(*zip_it_half_const) && 3.3 == boost::tuples::get<1>(*zip_it_half_const) ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } ///////////////////////////////////////////////////////////////////////////// // // Zip iterator categories // ///////////////////////////////////////////////////////////////////////////// std::cout << "Zip iterator categories: " << std::flush; // The big iterator of the previous test has vector, list, and set iterators. // Therefore, it must be bidirectional, but not random access. bool bBigItIsBidirectionalIterator = boost::is_convertible< boost::iterator_traversal<zip_it_12_type>::type , boost::bidirectional_traversal_tag >::value; bool bBigItIsRandomAccessIterator = boost::is_convertible< boost::iterator_traversal<zip_it_12_type>::type , boost::random_access_traversal_tag >::value; // A combining iterator with all vector iterators must have random access // traversal. // typedef boost::zip_iterator< boost::tuples::tuple< std::vector<double>::const_iterator, std::vector<double>::const_iterator > > all_vects_type; bool bAllVectsIsRandomAccessIterator = boost::is_convertible< boost::iterator_traversal<all_vects_type>::type , boost::random_access_traversal_tag >::value; // The big test. if( bBigItIsBidirectionalIterator && ! bBigItIsRandomAccessIterator && bAllVectsIsRandomAccessIterator ) { ++num_successful_tests; std::cout << "OK" << std::endl; } else { ++num_failed_tests = 0; std::cout << "not OK" << std::endl; } // Done // std::cout << "\nTest Result:" << "\n============" << "\nNumber of successful tests: " << static_cast<unsigned int>(num_successful_tests) << "\nNumber of failed tests: " << static_cast<unsigned int>(num_failed_tests) << std::endl; return num_failed_tests; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 833 ] ] ]
605dc8e1b4113184778f06c01d9f8c1ee3a106f3
7956f4ceddbbcbabd3dd0ae211899cfa5934fc7a
/metaballs3d/trunk/OgreMetaballs/Vertex.cpp
36aa1a9f421d40b3a51220590d99a492abe59603
[]
no_license
pranavsureshpn/gpusphsim
8d77cde45f5951aee65a13d1ea7edcb5837c6caa
723d950efbd0d2643edb4b99845bcc658ce38f20
refs/heads/master
2021-01-10T05:18:21.705120
2011-09-08T01:58:38
2011-09-08T01:58:38
50,779,129
0
0
null
null
null
null
UTF-8
C++
false
false
112
cpp
#include "Vertex.h" //----------------------------------- // Vertex //-----------------------------------
[ "yaoyansi@cd07e373-eec6-1eb2-8c47-9a5824a9cb26" ]
[ [ [ 1, 5 ] ] ]
99e4a64dc0cb13d932fef771d7e9d5eae40b0c9f
6131815bf1b62accfc529c2bc9db21194c7ba545
/FrameworkApp/DirectInput.cpp
a3d805bb688cbb69d0aa51705e997f8089fe7e52
[]
no_license
dconefourseven/honoursproject
b2ee664ccfc880c008f29d89aad03d9458480fc8
f26b967fda8eb6937f574fd6f3eb76c8fecf072a
refs/heads/master
2021-05-29T07:14:35.261586
2011-05-15T18:27:49
2011-05-15T18:27:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,474
cpp
#include "DirectInput.h" #include <cassert> #pragma comment (lib, "Libs/DX8/dinput.lib") #pragma comment (lib, "Libs/DX8/dinput8.lib") void DirectInput::Update() { /////////////////////////////////////////////////////////////////////////////// // Update Function // Reads the active input devices (keyboard), maps into the Base class. /////////////////////////////////////////////////////////////////////////////// //obtain the current keyboard state and pack it into the keybuffer bool DeviceState = SUCCEEDED(DIKeyboardDevice->GetDeviceState(sizeof(KeyBuffer), (LPVOID)&KeyBuffer)); bool mouse_DeviceState = SUCCEEDED ( DIMouseDevice->GetDeviceState(sizeof(DIMOUSESTATE),(LPVOID)&mouseState)); assert(DeviceState); assert(mouse_DeviceState); //Map key inputs to Control maps here //the control maps are part of the base class and //we check them in the actual application and take action on them. if(KeyBuffer[DIK_ESCAPE] & 0x80) DigitalControlMap[DIK_ESCAPE]=true; else DigitalControlMap[DIK_ESCAPE]=false; if(KeyBuffer[DIK_W] & 0x80) DigitalControlMap[DIK_W]=true; else DigitalControlMap[DIK_W]=false; if(KeyBuffer[DIK_S] & 0x80) DigitalControlMap[DIK_S]=true; else DigitalControlMap[DIK_S]=false; if(KeyBuffer[DIK_A] & 0x80) DigitalControlMap[DIK_A]=true; else DigitalControlMap[DIK_A]=false; if(KeyBuffer[DIK_D] & 0x80) DigitalControlMap[DIK_D]=true; else DigitalControlMap[DIK_D]=false; if(KeyBuffer[DIK_Q] & 0x80) DigitalControlMap[DIK_Q]=true; else DigitalControlMap[DIK_Q]=false; if(KeyBuffer[DIK_E] & 0x80) DigitalControlMap[DIK_E]=true; else DigitalControlMap[DIK_E]=false; if(KeyBuffer[DIK_P] & 0x80) DigitalControlMap[DIK_P]=true; else DigitalControlMap[DIK_P]=false; if(KeyBuffer[DIK_O] & 0x80) DigitalControlMap[DIK_O]=true; else DigitalControlMap[DIK_O]=false; if(KeyBuffer[DIK_SPACE] & 0x80) DigitalControlMap[DIK_SPACE]=true; else DigitalControlMap[DIK_SPACE]=false; if(KeyBuffer[DIK_RIGHT] & 0x80) DigitalControlMap[DIK_RIGHT]=true; else DigitalControlMap[DIK_RIGHT]=false; if(KeyBuffer[DIK_LEFT] & 0x80) DigitalControlMap[DIK_LEFT]=true; else DigitalControlMap[DIK_LEFT]=false; if(mouseState.rgbButtons[0] & 0x80) MouseControlMap[0] = true; else MouseControlMap[0] = false; if(mouseState.rgbButtons[1] & 0x80) MouseControlMap[1] = true; else MouseControlMap[1] = false; } bool* DirectInput::GetKeyboardState() { pDigitalControlMap = DigitalControlMap; return pDigitalControlMap; } DirectInput::DirectInput() { /////////////////////////////////////////////////////////////////////////////// // Constructor // Initialises Direct Input, sets up and aquires input devices. /////////////////////////////////////////////////////////////////////////////// DIObject = NULL; //set Directinput object pointer to null. DIKeyboardDevice = NULL; //keyboard device set to null. bool InputInitialised =Initialise(); assert(InputInitialised); bool DevicesInitialised = GetDevices(); assert(DevicesInitialised); //Initialise the Analogue and digital control maps for (int i=0; i<DIGITALCONTROLMAPS; i++) { DigitalControlMap[i] = false; } for (int i=0; i<ANALOGUECONTROLMAPS; i++) { AnalogueControlMap[i] = 0.0f; } for(int i = 0; i < 4; i++) MouseControlMap[i] = false; } DirectInput::~DirectInput() { /////////////////////////////////////////////////////////////////////////////// // Destructor // /////////////////////////////////////////////////////////////////////////////// } bool DirectInput::Initialise() { /////////////////////////////////////////////////////////////////////////////// // Initialise function // Create the Direct Input base object. /////////////////////////////////////////////////////////////////////////////// if(FAILED(DirectInput8Create( GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&DIObject, NULL))) { assert (DIObject); return false; } return true; } bool DirectInput::GetDevices() { ///////////////////////////////////////////////////////////////////////////////////////// // Get input devices // This is seperate from "initialise" in case it must be called when unplugging things etc. ///////////////////////////////////////////////////////////////////////////////////////// // possibly change to: bool = failed(function) and assert // the bool when failed. Will always assert when fails // but may help pick out the error point from the assert // message. // Create the Device if(FAILED(DIObject->CreateDevice(GUID_SysKeyboard, &DIKeyboardDevice, NULL))) { return false; } // Set the Data format (c_dfDIKeyboard is standard Dirx Global) if(FAILED(DIKeyboardDevice->SetDataFormat(&c_dfDIKeyboard))) { return false; } // How the app handles control of keyboard when switching window etc. if(FAILED(DIKeyboardDevice->SetCooperativeLevel(NULL, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE))) { return false; } // Aquiring the keyboard now everything is set up. if(FAILED(DIKeyboardDevice->Acquire())) { return false; } if(FAILED(DIObject->CreateDevice(GUID_SysMouse, &DIMouseDevice, NULL))) return false; if(FAILED(DIMouseDevice->SetCooperativeLevel(NULL, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE))) return false; if(FAILED(DIMouseDevice->SetDataFormat(&c_dfDIMouse))) return false; if(FAILED(DIMouseDevice->Acquire())) return false; return true; } void DirectInput::ShutDown() { /*/////////////////////////////////////////////////////////////////////////////// // Shutdown // Anything else that we need to clean up, do it here. /////////////////////////////////////////////////////////////////////////////// if(DIObject != NULL) { DIObject->Release(); DIObject = NULL; } if(DIKeyboardDevice != NULL) { DIKeyboardDevice->Unacquire(); DIKeyboardDevice->Release(); DIKeyboardDevice = NULL; }*/ }
[ "davidclarke1990@fa56ba20-0011-6cdf-49b4-5b20436119f6" ]
[ [ [ 1, 247 ] ] ]
427ff5e86ce8d074d163d9e99eaaf9777b98776f
74e7667ad65cbdaa869c6e384fdd8dc7e94aca34
/MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/spot_Time_native_Microsoft_SPOT_Time_TimeService_mshl.cpp
ae3ff8b8d7ef97d4c5ea517155c1e020476e3355
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gezidan/NETMF-LPC
5093ab223eb9d7f42396344ea316cbe50a2f784b
db1880a03108db6c7f611e6de6dbc45ce9b9adce
refs/heads/master
2021-01-18T10:59:42.467549
2011-06-28T08:11:24
2011-06-28T08:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,686
cpp
//----------------------------------------------------------------------------- // // ** DO NOT EDIT THIS FILE! ** // This file was generated by a tool // re-running the tool will overwrite this file. // //----------------------------------------------------------------------------- #include "spot_Time_native.h" #include "spot_Time_native_Microsoft_SPOT_Time_TimeService.h" using namespace Microsoft::SPOT::Time; HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::get_Settings___STATIC__MicrosoftSPOTTimeTimeServiceSettings( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { UNSUPPORTED_TYPE retVal = TimeService::get_Settings( hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_UNSUPPORTED_TYPE( stack, retVal ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::set_Settings___STATIC__VOID__MicrosoftSPOTTimeTimeServiceSettings( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { UNSUPPORTED_TYPE param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 0, param0 ) ); TimeService::set_Settings( param0, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::Start___STATIC__VOID( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { TimeService::Start( hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::Stop___STATIC__VOID( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { TimeService::Stop( hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::get_LastSyncStatus___STATIC__MicrosoftSPOTTimeTimeServiceStatus( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { UNSUPPORTED_TYPE retVal = TimeService::get_LastSyncStatus( hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_UNSUPPORTED_TYPE( stack, retVal ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::Update___STATIC__MicrosoftSPOTTimeTimeServiceStatus__U4__U4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { UNSUPPORTED_TYPE param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_UNSUPPORTED_TYPE( stack, 0, param0 ) ); UINT32 param1; TINYCLR_CHECK_HRESULT( Interop_Marshal_UINT32( stack, 1, param1 ) ); UNSUPPORTED_TYPE retVal = TimeService::Update( param0, param1, hr ); TINYCLR_CHECK_HRESULT( hr ); SetResult_UNSUPPORTED_TYPE( stack, retVal ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::SetUtcTime___STATIC__VOID__I8( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { INT64 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT64( stack, 0, param0 ) ); TimeService::SetUtcTime( param0, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); } HRESULT Library_spot_Time_native_Microsoft_SPOT_Time_TimeService::SetTimeZoneOffset___STATIC__VOID__I4( CLR_RT_StackFrame& stack ) { TINYCLR_HEADER(); hr = S_OK; { INT32 param0; TINYCLR_CHECK_HRESULT( Interop_Marshal_INT32( stack, 0, param0 ) ); TimeService::SetTimeZoneOffset( param0, hr ); TINYCLR_CHECK_HRESULT( hr ); } TINYCLR_NOCLEANUP(); }
[ [ [ 1, 115 ] ] ]
280a1b53c7d668103833e28ac9eca9d53d419d30
789bfae90cbb728db537b24eb9ab21c88bda2786
/source/BestScoresLineClass.h
ab5b9ac1fe2af9a0732fdc2efb9fd36643844d1f
[ "MIT" ]
permissive
Izhido/bitsweeper
b89db2c2050cbc82ea60d31d2f31b041a1e913a3
a37902c5b9ae9c25ee30694c2ba0974fd235090e
refs/heads/master
2021-01-23T11:49:21.723909
2011-12-24T22:43:30
2011-12-24T22:43:30
34,614,275
0
2
null
null
null
null
UTF-8
C++
false
false
403
h
#ifndef BESTSCORESLINECLASS_H #define BESTSCORESLINECLASS_H #include "BestScoresLineLevelEnum.h" #include <nds/ndstypes.h> class BestScoresLineClass { public: BestScoresLineLevelEnum Level; int8 Seconds; int16 Minutes; BestScoresLineClass(); int LineSize(); void LoadFrom(char* Buffer); void SaveTo(char* Buffer); virtual ~BestScoresLineClass(); }; #endif
[ "[email protected]@66f87ebb-1a6f-337b-3a26-6cadc16acdcf" ]
[ [ [ 1, 28 ] ] ]
59ce7fbfd0b0e52f456977e1a56c409b866e48d6
036205456b03f717177170d91cc3e75080548aaa
/_old/csv_table.cc
8a22f9327028e74e40477c34d9e65e48c86a78ba
[]
no_license
androidsercan/experimental-toolkit-in-c
e877e051fc9546048eaf4287e49865192890d91c
ac545219ed3fcca865c147b0f53e13bff5829fd1
refs/heads/master
2016-08-12T05:04:36.608456
2011-12-14T15:18:04
2011-12-14T15:18:04
43,951,774
0
0
null
null
null
null
UTF-8
C++
false
false
4,209
cc
// $Id: csv_table.cc 3570 2011-06-10 07:22:54Z haowu $ #include "csv_table.h" CsvTable::CsvTable(const string& csv_file) { FILE *f = fopen(csv_file.c_str(), "r"); fseek(f, 0, SEEK_END); long l = ftell(f); fseek(f, 0, SEEK_SET); char *buf = (char *)malloc(l + 1); fread(buf, l, 1, f); fclose(f); buf[l] = 0; z_buff_.push_back(buf); char *rp = buf; while (*rp) { if (*rp == '\"') { rp++; z_attr_name_.push_back(rp); char *wp = rp; do { while (*rp && *rp != '\"') *wp++ = *rp++; if (*rp)rp++; if (*rp == '\"') *wp++ = *rp++; else break; } while(1); *wp = 0; } else { z_attr_name_.push_back(rp); while (*rp && *rp != ',' && *rp != '\r' && *rp != '\n') rp++; } if (*rp == '\r') *rp++ = 0; if (*rp == '\n') { *rp++ = 0; break; } if (*rp == 0) break; if (*rp == ',') *rp++ = 0; } while (*rp) { data_.resize(data_.size() + 1); while (*rp) { if (*rp == '\"') { rp++; if (data_.back().size() < z_attr_name_.size()) data_.back().push_back(rp); char* wp = rp; while (true) { while (true) { if (*rp == 0 || *rp == '\"') { break; } else if (*rp == '\\') { *wp = *rp; wp += 2; rp += 2; } else { *wp = *rp; wp += 1; rp += 1; } } if (*rp) rp++; if (*rp == '\"') { *wp++ = *rp++; } else { break; } } *wp = 0; } else { if (data_.back().size() < z_attr_name_.size()) data_.back().push_back(rp); while (*rp && *rp != ',' && *rp != '\r' && *rp != '\n') rp++; } if (*rp == '\r') *rp++ = 0; if (*rp == '\n') { *rp++ = 0; break; } if (*rp == 0) break; if (*rp == ',') *rp++ = 0; } while (data_.back().size() < z_attr_name_.size()) data_.back().push_back(buf + l); } } CsvTable::~CsvTable() { Clear(); } void CsvTable::AddFile(const string& csv_file, bool skipFirstLine) { FILE *f = fopen(csv_file.c_str(), "r"); fseek(f, 0, SEEK_END); long l = ftell(f); fseek(f, 0, SEEK_SET); char *buf = (char *)malloc(l + 1); fread(buf, l, 1, f); fclose(f); buf[l] = 0; z_buff_.push_back(buf); char *rp = buf; while (*rp) { if (!skipFirstLine) data_.resize(data_.size() + 1); while (*rp) { if (*rp == '\"') { rp++; if (!skipFirstLine && data_.back().size() < z_attr_name_.size()) data_.back().push_back(rp); char *wp = rp; do { while (*rp && *rp != '\"') *wp++ = *rp++; if (*rp) rp++; if (*rp == '\"') *wp++ = *rp++; else break; } while (1); *wp = 0; } else { if (!skipFirstLine && data_.back().size() < z_attr_name_.size()) data_.back().push_back(rp); while (*rp && *rp != ',' && *rp != '\r' && *rp != '\n') rp++; } if (*rp == '\r') *rp++ = 0; if (*rp == '\n') { *rp++ = 0; break; } if (*rp == 0) break; if (*rp == ',') *rp++ = 0; } while (!skipFirstLine && data_.back().size() < z_attr_name_.size()) data_.back().push_back(buf + l); skipFirstLine = false; } } void CsvTable::Clear() { data_.clear(); for (int i = 0; i < (int)z_buff_.size(); i++) free(z_buff_[i]); } int CsvTable::GetSizeInByte() { int n = 0; for (int tid = 0; tid < (int)data_.size(); tid++) { for (int i = 0; i < (int)data_[tid].size(); i++) { string str = string(data_[tid][i]); n += str.length() * sizeof(char) + sizeof(const char*); } n += sizeof(vector<string>); } return n; }
[ [ [ 1, 179 ] ] ]
4663dd3b02d76af883143c44d0ec0730e6d9ad24
29e87c19d99b77d379b2f9760f5e7afb3b3790fa
/src/qt-client/QPlaylist.h
8637c523b548268705c9db872dafd911e77c78ac
[]
no_license
wilcobrouwer/dmplayer
c0c63d9b641a0f76e426ed30c3a83089166d0000
9f767a15e25016f6ada4eff6a1cdd881ad922915
refs/heads/master
2021-05-30T17:23:21.889844
2011-03-29T08:51:52
2011-03-29T08:51:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
609
h
#ifndef QPLAYLIST_H #define QPLAYLIST_H #include <QTreeWidget> #include <QMenu> #include "../playlist_management.h" class QPlaylist: public QTreeWidget, public PlaylistVector { Q_OBJECT private: QMenu contextMenu; public: QPlaylist(QWidget* parent); ~QPlaylist(); virtual void add(const Track& track); virtual void remove(uint32 pos); virtual void insert(uint32 pos, const Track& track); virtual void move(uint32 from, uint32 to); virtual void clear(); virtual QModelIndexList selectedIndexes() { return QTreeView::selectedIndexes(); } }; #endif//QPLAYLIST_H
[ "simon.sasburg@e69229e2-1541-0410-bedc-87cb2d1b0d4b" ]
[ [ [ 1, 30 ] ] ]
10940cd30124ceab6ae712ee378197f5c3c75366
3472e587cd1dff88c7a75ae2d5e1b1a353962d78
/XMonitor/debug/moc_TestUi.cpp
a5ce8a004cee823eee0e8ddb4dd280b933ff090b
[]
no_license
yewberry/yewtic
9624d05d65e71c78ddfb7bd586845e107b9a1126
2468669485b9f049d7498470c33a096e6accc540
refs/heads/master
2021-01-01T05:40:57.757112
2011-09-14T12:32:15
2011-09-14T12:32:15
32,363,059
0
0
null
null
null
null
UTF-8
C++
false
false
2,069
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'TestUi.h' ** ** Created: Sat Feb 26 16:35:28 2011 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../src/TestUi.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'TestUi.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_TestUi[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_TestUi[] = { "TestUi\0" }; const QMetaObject TestUi::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_TestUi, qt_meta_data_TestUi, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &TestUi::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *TestUi::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *TestUi::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_TestUi)) return static_cast<void*>(const_cast< TestUi*>(this)); return QWidget::qt_metacast(_clname); } int TestUi::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
[ "[email protected]@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86" ]
[ [ [ 1, 69 ] ] ]
a12ba0f384e2ba712b106385626533d8e08d706c
5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e
/Include/theme/basic/TextFieldTheme.cpp
4d919921eb4f3bcabebc3ec7188a16a895cf6f27
[ "BSD-3-Clause" ]
permissive
gui-works/ui
3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b
023faf07ff7f11aa7d35c7849b669d18f8911cc6
refs/heads/master
2020-07-18T00:46:37.172575
2009-11-18T22:05:25
2009-11-18T22:05:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,763
cpp
/* * Copyright (c) 2003-2006, Bram Stein * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "./TextFieldTheme.h" #include "../../Component.h" #include "../../component/TextField.h" #include "../../Font.h" #include "../../GlyphContext.h" #include "../../Graphics.h" #include "../../event/KeyEvent.h" #include "../../event/FocusEvent.h" namespace ui { namespace theme { namespace basic { void TextFieldTheme::installTheme(Component *comp) { comp->setBorder(&border); comp->addFocusListener(this); comp->addMouseListener(this); comp->addInterpolator(&interpolator); comp->setFont(GlyphContext::getInstance().createFont("Vera.ttf",10)); // default font } void TextFieldTheme::deinstallTheme(Component *comp) { comp->removeFocusListener(this); comp->removeMouseListener(this); comp->removeInterpolator(&interpolator); } void TextFieldTheme::paint(Graphics &g, const Component *comp) const { BasicComponent::paint(g,comp); const TextField *textField = static_cast<const TextField*>(comp); g.enableScissor(textField->getLocationOnScreen().x,textField->getLocationOnScreen().y,textField->getBounds().width,textField->getBounds().height); g.setPaint(textField->getForeground()); std::string text = textField->getText(); Font *f = textField->getFont(); g.setFont(f); if(textField->hasEchoCharacter()) { //std::size_t length = text.length(); text = std::string(text.length(),static_cast<char>(textField->getEchoCharacter())); } util::Dimension bbox(f->getStringBoundingBox(text)); int y = textField->getBounds().height / 2 - bbox.height/2; g.drawString(textField->getInsets().left,y,text); if(displayCursor && textField->hasFocus()) { int border = 4; g.fillRect(2 + bbox.width,border,2,textField->getBounds().height - border - border); } g.disableScissor(); } const util::Dimension TextFieldTheme::getPreferredSize(const Component *comp) const { const TextField *textField = static_cast<const TextField*>(comp); std::string text = textField->getText(); Font *f = textField->getFont(); util::Dimension bbox(f->getStringBoundingBox(text)); int height= bbox.height + textField->getInsets().top + textField->getInsets().bottom; return util::Dimension(140,height); } void TextFieldTheme::propertyChanged(const event::PropertyEvent &e) { } TextFieldTheme::TextFieldTheme() : border(util::Color(255,255,255),1), interpolator(1.0f,0,100.0f), displayCursor(false) { interpolator.addInterpolatee(this); interpolator.start(); } TextFieldTheme::~TextFieldTheme() { interpolator.removeInterpolatee(this); } void TextFieldTheme::update(float value) { if(value == 100.0f) { displayCursor = !displayCursor; interpolator.reset(); } } void TextFieldTheme::focusGained(const event::FocusEvent &e) { TextField *textField(static_cast<TextField*>(e.getSource())); cursorPosition = static_cast<int>(textField->getText().length()); } void TextFieldTheme::focusLost(const event::FocusEvent &e) { } } } }
[ "bs@bram.(none)" ]
[ [ [ 1, 139 ] ] ]
0f49c6d35437e90ff0ce9ee86a6ce121339a8f51
4be39d7d266a00f543cf89bcf5af111344783205
/Win32IpChanger/main.cpp
83f55dee8454212ee4da897248433dcda33ee5d9
[]
no_license
nkzxw/lastigen-haustiere
6316bb56b9c065a52d7c7edb26131633423b162a
bdf6219725176ae811c1063dd2b79c2d51b4bb6a
refs/heads/master
2021-01-10T05:42:05.591510
2011-02-03T14:59:11
2011-02-03T14:59:11
47,530,529
1
0
null
null
null
null
UTF-8
C++
false
false
1,077
cpp
#include <iostream> //TODO: quitar #include <boost/extension/extension.hpp> #include <boost/extension/factory.hpp> #include <boost/extension/type_map.hpp> #include "AbstractIpChanger.hpp" #ifdef _WIN32 #include "Win32IpChanger.hpp" typedef Win32IpChanger IpChanger; #else #endif using namespace boost::extensions; ////typedef factory<AbstractIpChanger, int> FactoryType; //typedef factory<AbstractIpChanger, void> FactoryType; typedef factory<AbstractIpChanger> FactoryType; typedef std::map<std::string, FactoryType> FactoryMap; //BOOST_EXTENSION_TYPE_MAP_FUNCTION //{ // FactoryMap& factories(types.get()); // factories["Win32IpChanger_factory"].set<Win32IpChanger>(); //} int main() { IpChanger changer; std::cout << changer.setStatic("EstoTieneQueDarError", "192.168.111.111", "255.255.255.0", "192.168.111.1"); std::cout << changer.getMessage(); std::cout << changer.setStatic("Local Area Connection", "192.168.111.111", "255.255.255.0", "192.168.111.1"); std::cout << changer.setDynamic("Local Area Connection"); }
[ "fpelliccioni@c29dda52-a065-11de-a33f-1de61d9b9616" ]
[ [ [ 1, 40 ] ] ]
f623c1c118d48421a51a49cc8860b3d611ad65ff
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/AIGoalCharge.h
b9ee215dde72e787dbb3b45585f0d884281b6bec
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
1,274
h
// ----------------------------------------------------------------------- // // // MODULE : AIGoalCharge.h // // PURPOSE : AIGoalCharge class definition // // CREATED : 7/25/01 // // (c) 2001 Monolith Productions, Inc. All Rights Reserved // ----------------------------------------------------------------------- // #ifndef __AIGOAL_CHARGE_H__ #define __AIGOAL_CHARGE_H__ #include "AIGoalAbstractStimulated.h" class CAIGoalCharge : public CAIGoalAbstractStimulated { typedef CAIGoalAbstractStimulated super; public: DECLARE_AI_FACTORY_CLASS_SPECIFIC(Goal, CAIGoalCharge, kGoal_Charge); CAIGoalCharge( ); // Save / Load virtual void Save(ILTMessage_Write *pMsg); virtual void Load(ILTMessage_Read *pMsg); // Activation. virtual void ActivateGoal(); // Updating. void UpdateGoal(); // Sense Handling. virtual LTBOOL HandleGoalSenseTrigger(AISenseRecord* pSenseRecord); // Command Handling. virtual LTBOOL HandleNameValuePair(const char *szName, const char *szValue); protected: // State Handling. void HandleStateCharge(); protected: LTFLOAT m_fAttackDistanceSqr; LTFLOAT m_fYellDistanceSqr; LTFLOAT m_fStopDistanceSqr; }; #endif
[ [ [ 1, 63 ] ] ]
38c0c3ed59e547901ae154d74b631a63023eea14
8a0a81978126520c0bfa0d2ad6bd1d35236f1aa2
/SegmentationRegional/Dep/Qt-OpenCV-Window/QtOpenCvWidget.cpp
6b9a20a65c20f10b234f088a2127b1f550440bc9
[]
no_license
zjucsxxd/BSplineLevelSetRegionalSegmentation
a64b4a096f65736659b6c74dce7cd973815b9a2c
a320ade9386861657476cca7fce97315de5e3e31
refs/heads/master
2021-01-20T23:03:26.244747
2011-12-10T13:10:56
2011-12-10T13:10:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
79,121
cpp
//IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // License Agreement // For Open Source Computer Vision Library //Copyright (C) 2000-2008, Intel Corporation, all rights reserved. //Copyright (C) 2008-2010, Willow Garage Inc., all rights reserved. //Third party copyrights are property of their respective owners. //Redistribution and use in source and binary forms, with or without modification, //are permitted provided that the following conditions are met: // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. //This software is provided by the copyright holders and contributors "as is" and //any express or implied warranties, including, but not limited to, the implied //warranties of merchantability and fitness for a particular purpose are disclaimed. //In no event shall the Intel Corporation or contributors be liable for any direct, //indirect, incidental, special, exemplary, or consequential damages //(including, but not limited to, procurement of substitute goods or services; //loss of use, data, or profits; or business interruption) however caused //and on any theory of liability, whether in contract, strict liability, //or tort (including negligence or otherwise) arising in any way out of //the use of this software, even if advised of the possibility of such damage. //--------------------Google Code 2010 -- Yannick Verdie--------------------// //-------------------- Redesigned to act as Qt Widget - Gabor Bernat - 2011// #include <QtOpenCvWidget.h> #include <windows.h> //Static and global first static GuiReceiverQtI *guiMainThread = NULL; static int parameterSystemC = 1; static char* parameterSystemV[] = {(char*)""}; static bool multiThreads = false; static int last_key = -1; QWaitCondition key_pressed; QMutex mutexKey; static const unsigned int threshold_zoom_img_region = 30; //the minimum zoom value to start displaying the values in the grid //that is also the number of pixel per grid static CvWinProperties* global_control_panel = NULL; //end static and global void cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont* font) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "putText", Qt::AutoConnection, Q_ARG(void*, (void*) img), Q_ARG(QString,QString(text)), Q_ARG(QPoint, QPoint(org.x,org.y)), Q_ARG(void*,(void*) font)); } double cvGetRatioWindow_QT(const char* name) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); double result = -1; QMetaObject::invokeMethod(guiMainThread, "getRatioWindow", //Qt::DirectConnection, Qt::AutoConnection, Q_RETURN_ARG(double, result), Q_ARG(QString, QString(name))); return result; } void cvSetRatioWindow_QT(const char* name,double prop_value) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "setRatioWindow", Qt::AutoConnection, Q_ARG(QString, QString(name)), Q_ARG(double, prop_value)); } double cvGetPropWindow_QT(const char* name) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); double result = -1; QMetaObject::invokeMethod(guiMainThread, "getPropWindow", //Qt::DirectConnection, Qt::AutoConnection, Q_RETURN_ARG(double, result), Q_ARG(QString, QString(name))); return result; } void cvSetPropWindow_QT(const char* name,double prop_value) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "setPropWindow", Qt::AutoConnection, Q_ARG(QString, QString(name)), Q_ARG(double, prop_value)); } void cvSetModeWindow_QT(const char* name, double prop_value) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "toggleFullScreen", Qt::AutoConnection, Q_ARG(QString, QString(name)), Q_ARG(double, prop_value)); } double cvGetModeWindow_QT(const char* name) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); double result = -1; QMetaObject::invokeMethod(guiMainThread, "isFullScreen", Qt::AutoConnection, Q_RETURN_ARG(double, result), Q_ARG(QString, QString(name))); return result; } void cvDisplayOverlay(const char* name, const char* text, int delayms) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "displayInfo", Qt::AutoConnection, //Qt::DirectConnection, Q_ARG(QString, QString(name)), Q_ARG(QString, QString(text)), Q_ARG(int, delayms)); } void cvSaveWindowParameters(const char* name) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "saveWindowParameters", Qt::AutoConnection, Q_ARG(QString, QString(name))); } void cvLoadWindowParameters(const char* name) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "loadWindowParameters", Qt::AutoConnection, Q_ARG(QString, QString(name))); } void cvDisplayStatusBar(const char* name, const char* text, int delayms) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "displayStatusBar", Qt::AutoConnection, //Qt::DirectConnection, Q_ARG(QString, QString(name)), Q_ARG(QString, QString(text)), Q_ARG(int, delayms)); } int cvWaitKey( int arg ) { int result = -1; if (!guiMainThread) return result; unsigned long delayms;//in milliseconds if (arg<=0) delayms = ULONG_MAX; else delayms = arg; if (multiThreads) { mutexKey.lock(); if(key_pressed.wait(&mutexKey,delayms))//false if timeout { result = last_key; } last_key = -1; mutexKey.unlock(); }else{ //cannot use wait here because events will not be distributed before processEvents (the main eventLoop is broken) //so I create a Thread for the QTimer if (arg>0) guiMainThread->timer->start(arg); //QMutex dummy; while(!guiMainThread->_bTimeOut) { qApp->processEvents(QEventLoop::AllEvents); if (!guiMainThread)//when all the windows are deleted return result; mutexKey.lock(); if (last_key != -1) { result = last_key; last_key = -1; guiMainThread->timer->stop(); //printf("keypressed\n"); } mutexKey.unlock(); if (result!=-1) { break; } else { //to decrease CPU usage //sleep 1 millisecond #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64 Sleep(1); #else usleep(1000); #endif } } guiMainThread->_bTimeOut = false; } return result; } //Yannick Verdie //This function is experimental and some functions (such as cvSet/getWindowProperty will not work) //We recommend not using this function for now int cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]) { multiThreads = true; QFuture<int> future = QtConcurrent::run(pt2Func,argc,argv); return guiMainThread->start(); } void cvStopLoop() { qApp->exit(); } CvWidget* icvFindWindowByName( const char* arg ) { QPointer<CvWidget> window; if( !arg ) CV_Error( CV_StsNullPtr, "NULL name string" ); QString name(arg); CvWidget* w; CvWinModel* temp; //This is not a very clean way to do the stuff. Indeed, QAction automatically generate toolTil (QLabel) //that can be grabbed here and crash the code at 'w->param_name==name'. foreach (QWidget *widget, QApplication::topLevelWidgets()) { if (widget->isWindow() && !widget->parentWidget ())//is a window without parent { temp = (CvWinModel*) widget; if (temp->type == type_CvWidget) { w = (CvWidget*) temp; if (name.compare(w->param_name)==0) { window = w; break; } } } } return window; } CvBar* icvFindBarbyName(QBoxLayout* layout, QString name_bar, typeBar type) { if (!layout) return NULL; CvBar* t; int stop_index = layout->layout()->count(); for (int i = 0; i < stop_index; ++i) { t = (CvBar*) layout->layout()->itemAt(i); if (t->type == type && t->name_bar == name_bar) return t; } return NULL; } CvTrackbar* icvFindTrackbarByName( const char* name_trackbar, const char* name_window, QBoxLayout* layout = NULL ) { QString nameQt(name_trackbar); CvBar* result = NULL; if (!name_window && global_control_panel)//window name is null and we have a control panel layout = global_control_panel->myLayout; if (!layout) { QPointer<CvWidget> w = icvFindWindowByName( name_window ); if( !w ) CV_Error( CV_StsNullPtr, "NULL window handler" ); if ( w->param_gui_mode == CV_GUI_NORMAL) return (CvTrackbar*) icvFindBarbyName( w->myBarLayout, nameQt, type_CvTrackbar); if ( w->param_gui_mode == CV_GUI_EXPANDED) { result = icvFindBarbyName( w->myBarLayout, nameQt, type_CvTrackbar); if (result) return (CvTrackbar*) result; return (CvTrackbar*) icvFindBarbyName(global_control_panel->myLayout, nameQt, type_CvTrackbar); } return NULL; }else //layout was specified { return (CvTrackbar*) icvFindBarbyName( layout, nameQt, type_CvTrackbar); } } CvButtonbar* icvFindButtonbarByName( const char* button_name,QBoxLayout* layout) { QString nameQt(button_name); return (CvButtonbar*) icvFindBarbyName( layout, nameQt, type_CvButtonbar); } int icvInitSystem(int *c, char** v) { static int wasInitialized = 0; // check initialization status if( !wasInitialized) { wasInitialized = 1; } return 0; } int cvInitSystem( int, char** ) { icvInitSystem(&parameterSystemC, parameterSystemV); return 0; } int cvNamedWindow( const char* name, int flags ) { if (!guiMainThread) guiMainThread = new GuiReceiverQtI; if (multiThreads) QMetaObject::invokeMethod(guiMainThread, "createWindow", Qt::BlockingQueuedConnection, Q_ARG(QString, QString(name)), Q_ARG(int, flags)); else guiMainThread->createWindow(QString(name),flags); return 1;//Dummy value } void cvDestroyWindow( const char* name ) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "destroyWindow", //Qt::BlockingQueuedConnection, Qt::AutoConnection, Q_ARG(QString, QString(name)) ); } void cvDestroyAllWindows(void) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "destroyAllWindow", //Qt::BlockingQueuedConnection, Qt::AutoConnection ); } void* cvGetWindowHandle( const char* name ) { if( !name ) CV_Error( CV_StsNullPtr, "NULL name string" ); return (void*) icvFindWindowByName( name ); } const char* cvGetWindowName( void* window_handle ) { if( !window_handle ) CV_Error( CV_StsNullPtr, "NULL window handler" ); return ((CvWidget*)window_handle)->windowTitle().toLatin1().data(); } void cvMoveWindow( const char* name, int x, int y ) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "moveWindow", //Qt::BlockingQueuedConnection, Qt::AutoConnection, Q_ARG(QString, QString(name)), Q_ARG(int, x), Q_ARG(int, y) ); } void cvResizeWindow(const char* name, int width, int height ) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "resizeWindow", //Qt::BlockingQueuedConnection, Qt::AutoConnection, Q_ARG(QString, QString(name)), Q_ARG(int, width), Q_ARG(int, height) ); } int cvCreateTrackbar2( const char* name_bar, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata ) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "addSlider2", Qt::AutoConnection, Q_ARG(QString, QString(name_bar)), Q_ARG(QString, QString(window_name)), Q_ARG(void*, (void*)val), Q_ARG(int, count), Q_ARG(void*, (void*)on_notify), Q_ARG(void*, (void*)userdata) ); return 1;//dummy value } int cvStartWindowThread() { return 0; } int cvCreateTrackbar( const char* name_bar, const char* window_name, int* value, int count, CvTrackbarCallback on_change) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "addSlider", Qt::AutoConnection, Q_ARG(QString, QString(name_bar)), Q_ARG(QString, QString(window_name)), Q_ARG(void*, (void*)value), Q_ARG(int, count), Q_ARG(void*, (void*)on_change) ); return 1;//dummy value } int cvCreateButton(const char* button_name,CvButtonCallback on_change, void* userdata , int button_type, int initial_button_state ) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); if (initial_button_state < 0 || initial_button_state > 1) return 0; QMetaObject::invokeMethod(guiMainThread, "addButton", Qt::AutoConnection, Q_ARG(QString, QString(button_name)), Q_ARG(int, button_type), Q_ARG(int, initial_button_state), Q_ARG(void*, (void*)on_change), Q_ARG(void*, userdata) ); return 1;//dummy value } void cvCreateOpenGLCallback( const char* window_name, CvOpenGLCallback callbackOpenGL, void* userdata, double angle, double zmin, double zmax) { if (!guiMainThread) CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" ); QMetaObject::invokeMethod(guiMainThread, "setOpenGLCallback", Qt::AutoConnection, Q_ARG(QString, QString(window_name)), Q_ARG(void*, (void*)callbackOpenGL), Q_ARG(void*, userdata), Q_ARG(double, angle), Q_ARG(double, zmin), Q_ARG(double, zmax) ); } int cvGetTrackbarPos( const char* name_bar, const char* window_name ) { int result = -1; QPointer<CvTrackbar> t = icvFindTrackbarByName( name_bar, window_name ); if (t) result = t->slider->value(); return result; } void cvSetTrackbarPos( const char* name_bar, const char* window_name, int pos ) { QPointer<CvTrackbar> t = icvFindTrackbarByName( name_bar, window_name ); if (t) t->slider->setValue(pos); } /* assign callback for mouse events */ void cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse,void* param ) { QPointer<CvWidget> w = icvFindWindowByName( window_name ); if (!w) CV_Error(CV_StsNullPtr, "NULL window handler" ); w->setMouseCallBack(on_mouse, param); } void cvShowImage( const char* name, const CvArr* arr ) { if (!guiMainThread) guiMainThread = new GuiReceiverQtI; QMetaObject::invokeMethod(guiMainThread, "showImage", //Qt::BlockingQueuedConnection, Qt::DirectConnection, Q_ARG(QString, QString(name)), Q_ARG(void*, (void*)arr) ); } //----------OBJECT---------------- GuiReceiverQtI::GuiReceiverQtI() : _bTimeOut(false), nb_windows(0) { icvInitSystem(&parameterSystemC, parameterSystemV); timer = new QTimer; QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeOut())); timer->setSingleShot(true); } void GuiReceiverQtI::isLastWindow() { if (--nb_windows <= 0) { delete guiMainThread;//delete global_control_panel too guiMainThread = NULL; qApp->quit(); } } GuiReceiverQtI::~GuiReceiverQtI() { if (global_control_panel) { delete global_control_panel; global_control_panel = NULL; } delete timer; } void GuiReceiverQtI::putText(void* arr, QString text, QPoint org, void* arg2) { CV_Assert(arr); CvMat * mat, stub; int origin=0; if( CV_IS_IMAGE_HDR( arr )) origin = ((IplImage*)arr)->origin; mat = cvGetMat(arr, &stub); int nbChannelOriginImage = cvGetElemType(mat); if (nbChannelOriginImage!=CV_8UC3) return;//for now, font works only with 8UC3 QImage qimg = QImage(mat->data.ptr, mat->cols,mat->rows, mat->step,QImage::Format_RGB888); CvFont* font = (CvFont*)arg2; QPainter qp(&qimg); if (font) { QFont f(font->nameFont, font->line_type/*PointSize*/, font->thickness/*weight*/); f.setStyle((QFont::Style)font->font_face/*style*/); f.setLetterSpacing ( QFont::AbsoluteSpacing, font->dx/*spacing*/ ); //cvScalar(blue_component, green_component, red\_component[, alpha_component]) //Qt map non-transparent to 0xFF and transparent to 0 //OpenCV scalar is the reverse, so 255-font->color.val[3] qp.setPen(QColor(font->color.val[2],font->color.val[1],font->color.val[0],255-font->color.val[3])); qp.setFont ( f ); } qp.drawText (org, text ); qp.end(); } void GuiReceiverQtI::saveWindowParameters(QString name) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (w) w->writeSettings(); } void GuiReceiverQtI::loadWindowParameters(QString name) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (w) w->readSettings(); } double GuiReceiverQtI::getRatioWindow(QString name) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (!w) return -1; return (double)w->getView()->getRatio(); } void GuiReceiverQtI::setRatioWindow(QString name, double arg2 ) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (!w) return; int flags = (int) arg2; if (w->getView()->getRatio() == flags)//nothing to do return; //if valid flags if (flags == CV_WINDOW_FREERATIO || flags == CV_WINDOW_KEEPRATIO) w->getView()->setRatio(flags); } double GuiReceiverQtI::getPropWindow(QString name) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (!w) return -1; return (double)w->param_flags; } void GuiReceiverQtI::setPropWindow(QString name, double arg2 ) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (!w) return; int flags = (int) arg2; if (w->param_flags == flags)//nothing to do return; switch(flags) { case CV_WINDOW_NORMAL: w->myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize); w->param_flags = flags; break; case CV_WINDOW_AUTOSIZE: w->myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize); w->param_flags = flags; break; default:; } } double GuiReceiverQtI::isFullScreen(QString name) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (!w) return -1; if (w->isFullScreen()) return CV_WINDOW_FULLSCREEN; else return CV_WINDOW_NORMAL; } //accept CV_WINDOW_NORMAL or CV_WINDOW_FULLSCREEN void GuiReceiverQtI::toggleFullScreen(QString name, double flags ) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (!w) return; if (w->isFullScreen() && flags == CV_WINDOW_NORMAL) { w->showTools(); w->showNormal(); return; } if (!w->isFullScreen() && flags == CV_WINDOW_FULLSCREEN) { w->hideTools(); w->showFullScreen(); return; } } void GuiReceiverQtI::createWindow( QString name, int flags ) { if (!qApp) CV_Error(CV_StsNullPtr, "NULL session handler" ); // Check the name in the storage if( icvFindWindowByName( name.toLatin1().data() )) { return; } //QPointer<CvWindow> w1 = nb_windows++; new CvWidget(name, flags); } void GuiReceiverQtI::timeOut() { _bTimeOut = true; } void GuiReceiverQtI::displayInfo( QString name, QString text, int delayms ) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (w && delayms > 0) w->displayInfo(text,delayms); } void GuiReceiverQtI::displayStatusBar( QString name, QString text, int delayms ) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (w && delayms > 0) if (w->myStatusBar)//if statusbar was created w->displayStatusBar(text,delayms); } void GuiReceiverQtI::showImage(QString name, void* arr) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (!w)//as observed in the previous implementation (W32, GTK or Carbon), create a new window is the pointer returned is null { cvNamedWindow( name.toLatin1().data() ); w = icvFindWindowByName( name.toLatin1().data() ); } if( w && arr ) { w->updateImage(arr); if (w->isHidden()) w->show(); } else { CV_Error(CV_StsNullPtr, "Do nothing (Window or Image NULL)"); } } void GuiReceiverQtI::destroyWindow(QString name) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (w) { w->close(); //in not-multiThreads mode, looks like the window is hidden but not deleted //so I do it manually //otherwise QApplication do it for me if the exec command was executed (in multiThread mode) if (!multiThreads) delete w; } } void GuiReceiverQtI::destroyAllWindow() { if (!qApp) CV_Error(CV_StsNullPtr, "NULL session handler" ); if (multiThreads) { qApp->closeAllWindows(); }else{ foreach (QObject *obj, QApplication::topLevelWidgets()) { if (obj->metaObject ()->className () == QString("CvWindow")) { delete obj; } } } } void GuiReceiverQtI::setOpenGLCallback(QString window_name, void* callbackOpenGL, void* userdata, double angle, double zmin, double zmax) { QPointer<CvWidget> w = icvFindWindowByName( window_name.toLatin1().data() ); if (w && callbackOpenGL) w->setOpenGLCallback((CvOpenGLCallback) callbackOpenGL, userdata,angle,zmin,zmax); } void GuiReceiverQtI::moveWindow(QString name, int x, int y) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (w) w->move(x,y); } void GuiReceiverQtI::resizeWindow(QString name, int width, int height) { QPointer<CvWidget> w = icvFindWindowByName( name.toLatin1().data() ); if (w) w->resize(width, height); } void GuiReceiverQtI::enablePropertiesButtonEachWindow() { CvWidget* w; CvWinModel* temp; //For each window, enable window property button foreach (QWidget *widget, QApplication::topLevelWidgets()) { if (widget->isWindow() && !widget->parentWidget ())//is a window without parent { temp = (CvWinModel*) widget; if (temp->type == type_CvWidget) { w = (CvWidget*) widget; //active window properties button w->vect_QActions[9]->setDisabled(false); } } } } void GuiReceiverQtI::addButton(QString button_name, int button_type, int initial_button_state , void* on_change, void* userdata) { if (!global_control_panel) return; QPointer<CvButtonbar> b;// = icvFindButtonbarByName( button_name.toLatin1().data(), global_control_panel->myLayout ); //if (b)//button with this name already exist // return; if (global_control_panel->myLayout->count() == 0)//if that is the first button attach to the control panel, create a new button bar { b = CvWidget::createButtonbar(button_name);//the bar has the name of the first button attached to it enablePropertiesButtonEachWindow(); }else{ CvBar* lastbar = (CvBar*) global_control_panel->myLayout->itemAt(global_control_panel->myLayout->count()-1); if (lastbar->type == type_CvTrackbar)//if last bar is a trackbar, create a new buttonbar, else, attach to the current bar b = CvWidget::createButtonbar(button_name);//the bar has the name of the first button attached to it else b = (CvButtonbar*) lastbar; } b->addButton( button_name,(CvButtonCallback) on_change, userdata, button_type, initial_button_state); } void GuiReceiverQtI::addSlider2(QString bar_name, QString window_name, void* value, int count, void* on_change, void *userdata) { QBoxLayout *layout = NULL; QPointer<CvWidget> w; if (window_name != "") { w = icvFindWindowByName( window_name.toLatin1().data() ); if (!w) return; }else{ if (global_control_panel) layout = global_control_panel->myLayout; } QPointer<CvTrackbar> t = icvFindTrackbarByName( bar_name.toLatin1().data() , window_name.toLatin1().data(), layout ); if (t)//trackbar exists return; if (!value) CV_Error(CV_StsNullPtr, "NULL value pointer" ); if (count<= 0)//count is the max value of the slider, so must be bigger than 0 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" ); CvWidget::addSlider2(w,bar_name,(int*)value,count,(CvTrackbarCallback2) on_change, userdata); } void GuiReceiverQtI::addSlider(QString bar_name, QString window_name, void* value, int count, void* on_change) { QBoxLayout *layout = NULL; QPointer<CvWidget> w; if (window_name != "") { w = icvFindWindowByName( window_name.toLatin1().data() ); if (!w) return; }else{ if (global_control_panel) layout = global_control_panel->myLayout; } QPointer<CvTrackbar> t = icvFindTrackbarByName( bar_name.toLatin1().data() , window_name.toLatin1().data(), layout ); if (t)//trackbar exists return; if (!value) CV_Error(CV_StsNullPtr, "NULL value pointer" ); if (count<= 0)//count is the max value of the slider, so must be bigger than 0 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" ); CvWidget::addSlider(w,bar_name,(int*)value,count,(CvTrackbarCallback) on_change); } int GuiReceiverQtI::start() { return qApp->exec(); } CvTrackbar::CvTrackbar(CvWidget* arg, QString name, int* value, int count, CvTrackbarCallback2 on_change, void* data ) { callback = NULL; callback2 = on_change; userdata = data; construc_trackbar(arg,name, value, count); } CvTrackbar::CvTrackbar(CvWidget* arg, QString name, int* value, int count, CvTrackbarCallback on_change ) { callback = on_change; callback2 = NULL; userdata = NULL; construc_trackbar(arg,name, value, count); } void CvTrackbar::construc_trackbar(CvWidget* arg, QString name, int* value, int count) { type=type_CvTrackbar; myparent = arg; name_bar = name; setObjectName(name_bar); dataSlider = value; slider = new QSlider(Qt::Horizontal); slider->setFocusPolicy(Qt::StrongFocus); slider->setMinimum(0); slider->setMaximum(count); slider->setPageStep(5); slider->setValue(*value); slider->setTickPosition(QSlider::TicksBelow); //Change style of the Slider //slider->setStyleSheet(str_Trackbar_css); QFile qss(":/stylesheet-trackbar"); if (qss.open(QFile::ReadOnly)) { slider->setStyleSheet(QLatin1String(qss.readAll())); qss.close(); } //this next line does not work if we change the style with a stylesheet, why ? (bug in QT ?) //slider->setTickPosition(QSlider::TicksBelow); label = new QPushButton; label->setFlat(true); setLabel(slider->value()); QObject::connect( slider, SIGNAL( valueChanged( int ) ),this, SLOT( update( int ) ) ); QObject::connect( label, SIGNAL( clicked() ),this, SLOT( createDialog() )); //label->setStyleSheet("QPushButton:disabled {color: black}"); addWidget(label,Qt::AlignLeft);//name + value addWidget(slider,Qt::AlignCenter);//slider } void CvTrackbar::createDialog() { bool ok= false; //crash if I access the values directly and give them to QInputDialog, so do a copy first. int value = slider->value(); int step = slider->singleStep(); int min = slider->minimum(); int max = slider->maximum(); int i = #if QT_VERSION >= 0x040500 QInputDialog::getInt #else QInputDialog::getInteger #endif (this->parentWidget(), tr("Slider %1").arg(name_bar), tr("New value:"), value, min, max, step, &ok); if (ok) slider->setValue(i); } void CvTrackbar::update(int myvalue) { setLabel(myvalue); *dataSlider = myvalue; if (callback) { callback(myvalue); return; } if (callback2) { callback2(myvalue,userdata); return; } } void CvTrackbar::setLabel(int myvalue) { QString nameNormalized = name_bar.leftJustified( 10, ' ', true ); QString valueMaximum = QString("%1").arg(slider->maximum()); QString str = QString("%1 (%2/%3)").arg(nameNormalized).arg(myvalue,valueMaximum.length(),10,QChar('0')).arg(valueMaximum); label->setText(str); } CvTrackbar::~CvTrackbar() { delete slider; delete label; } //here CvButtonbar class CvButtonbar::CvButtonbar(QWidget* arg, QString arg2) { type=type_CvButtonbar; myparent = arg; name_bar = arg2; setObjectName(name_bar); group_button = new QButtonGroup; /* label = new QLabel; setLabel(); addWidget(label,Qt::AlignLeft ); */ } CvButtonbar::~CvButtonbar() { QLayoutItem *child; while ((child = takeAt(0)) != 0) delete child; delete group_button; } void CvButtonbar::setLabel() { QString nameNormalized = name_bar.leftJustified( 10, ' ', true ); label->setText(nameNormalized); } void CvButtonbar::addButton( QString name, CvButtonCallback call, void* userdata, int button_type, int initial_button_state) { QString button_name = name; if (button_name == "") button_name = tr("button %1").arg(this->count()); QPointer<QAbstractButton> button; if (button_type == CV_PUSH_BUTTON) button = (QAbstractButton*) new CvPushButton(this, button_name,call, userdata); if (button_type == CV_CHECKBOX) button = (QAbstractButton*) new CvCheckBox(this, button_name,call, userdata, initial_button_state); if (button_type == CV_RADIOBOX) { button = (QAbstractButton*) new CvRadioButton(this, button_name,call, userdata, initial_button_state); group_button->addButton(button); } if (button) { QObject::connect( button, SIGNAL( toggled(bool) ),button, SLOT( callCallBack(bool) )); addWidget(button,Qt::AlignCenter); } } //buttons here CvPushButton::CvPushButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4) { myparent = arg1; button_name = arg2; callback = arg3; userdata=arg4; setObjectName(button_name); setText(button_name); if (isChecked()) callCallBack(true); } void CvPushButton::callCallBack(bool checked) { if (callback) callback(checked,userdata); } CvCheckBox::CvCheckBox(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state) { myparent = arg1; button_name = arg2; callback = arg3; userdata=arg4; setObjectName(button_name); setCheckState((initial_button_state == 1?Qt::Checked:Qt::Unchecked)); setText(button_name); if (isChecked()) callCallBack(true); } void CvCheckBox::callCallBack(bool checked) { if (callback) callback(checked,userdata); } CvRadioButton::CvRadioButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state) { myparent = arg1; button_name = arg2; callback = arg3; userdata=arg4; setObjectName(button_name); setChecked(initial_button_state); setText(button_name); if (isChecked()) callCallBack(true); } void CvRadioButton::callCallBack(bool checked) { if (callback) callback(checked,userdata); } //here CvWinProperties class CvWinProperties::CvWinProperties(QString name_paraWindow, QObject* parent) { //setParent(parent); type = type_CvWinProperties; setWindowFlags(Qt::Tool); setContentsMargins(0,0,0,0); setWindowTitle(name_paraWindow); setObjectName(name_paraWindow); resize(100,50); myLayout = new QBoxLayout(QBoxLayout::TopToBottom); myLayout->setObjectName(QString::fromUtf8("boxLayout")); myLayout->setContentsMargins(0, 0, 0, 0); myLayout->setSpacing(0); myLayout->setMargin(0); myLayout->setSizeConstraint(QLayout::SetFixedSize); setLayout(myLayout); hide(); } void CvWinProperties::closeEvent ( QCloseEvent * e ) { e->accept();//intersept the close event (not sure I really need it) //an hide event is also sent. I will intercept it and do some processing } void CvWinProperties::showEvent ( QShowEvent * event ) { //why -1,-1 ?: do this trick because the first time the code is run, //no value pos was saved so we let Qt move the window in the middle of its parent (event ignored). //then hide will save the last position and thus, we want to retreive it (event accepted). QPoint mypos(-1,-1); QSettings settings("OpenCV2", this->windowTitle()); mypos = settings.value("pos", mypos).toPoint(); if (mypos.x()>=0) { move(mypos); event->accept(); } else{ event->ignore(); } } void CvWinProperties::hideEvent ( QHideEvent * event ) { QSettings settings("OpenCV2", this->windowTitle()); settings.setValue("pos", pos());//there is an offset of 6 pixels (so the window's position is wrong -- why ?) event->accept(); } CvWinProperties::~CvWinProperties() { //clear the setting pos QSettings settings("OpenCV2", this->windowTitle()); settings.remove("pos"); QLayoutItem *child; if (myLayout) { while ((child = myLayout->takeAt(0)) != 0) delete child; delete myLayout; } } //Here CvWindow class CvWidget::CvWidget(QString arg, int arg2) { type = type_CvWidget; moveToThread(qApp->instance()->thread()); param_name = arg; param_flags = arg2 & 0x0000000F; param_gui_mode = arg2 & 0x000000F0; param_ratio_mode = arg2 & 0x00000F00; setContentsMargins(0,0,0,0); setWindowTitle(param_name); setObjectName(param_name); resize(200,200); setMinimumSize(1,1); //1: create control panel if (!global_control_panel) global_control_panel = createParameterWindow(); //2: Layouts createBarLayout(); createGlobalLayout(); //3: my view int mode_display = CV_MODE_NORMAL; #if defined( HAVE_QT_OPENGL ) mode_display = CV_MODE_OPENGL; #endif createView(mode_display, param_ratio_mode); //4: shortcuts and actions createActions(); createShortcuts(); //5: toolBar and statusbar if (param_gui_mode == CV_GUI_EXPANDED) { createToolBar(); createStatusBar(); } //Now attach everything if (myToolBar) myGlobalLayout->addWidget(myToolBar,Qt::AlignCenter); myGlobalLayout->addWidget(myview,Qt::AlignCenter); myGlobalLayout->addLayout(myBarLayout,Qt::AlignCenter); if (myStatusBar) myGlobalLayout->addWidget(myStatusBar,Qt::AlignCenter); setLayout(myGlobalLayout); show(); } CvWidget::~CvWidget() { QLayoutItem *child; if (myGlobalLayout) { while ((child = myGlobalLayout->takeAt(0)) != 0) delete child; delete myGlobalLayout; } if (myBarLayout) { while ((child = myBarLayout->takeAt(0)) != 0) delete child; delete myBarLayout; } if (myStatusBar) { delete myStatusBar; delete myStatusBar_msg; } if (myToolBar) { for (int i=0;i<vect_QActions.count();i++) delete vect_QActions[i]; delete myToolBar; } for (int i=0;i<vect_QShortcuts.count();i++) delete vect_QShortcuts[i]; if (guiMainThread) guiMainThread->isLastWindow(); } CvButtonbar* CvWidget::createButtonbar(QString name_bar) { QPointer<CvButtonbar> t = new CvButtonbar(global_control_panel,name_bar); t->setAlignment(Qt::AlignHCenter); QPointer<QBoxLayout> myLayout = global_control_panel->myLayout; myLayout->insertLayout(myLayout->count(),t); return t; } void CvWidget::hideTools() { if (myToolBar) myToolBar->hide(); if (myStatusBar) myStatusBar->hide(); if (global_control_panel) global_control_panel->hide(); } void CvWidget::showTools() { if (myToolBar) myToolBar->show(); if (myStatusBar) myStatusBar->show(); } CvWinProperties* CvWidget::createParameterWindow() { QString name_paraWindow =QFileInfo(QApplication::applicationFilePath()).fileName()+" settings"; CvWinProperties *result = new CvWinProperties(name_paraWindow,guiMainThread); return result; } void CvWidget::displayPropertiesWin() { if (global_control_panel->isHidden()) global_control_panel->show(); else global_control_panel->hide(); } void CvWidget::createActions() { vect_QActions.resize(10); //if the shortcuts are changed in window_QT.h, we need to update the tooltip manually vect_QActions[0] = new QAction(QIcon(":/left-icon"),"Panning left (CTRL+arrowLEFT)",this); vect_QActions[0]->setIconVisibleInMenu(true); QObject::connect( vect_QActions[0],SIGNAL(triggered()),myview, SLOT( siftWindowOnLeft() )); vect_QActions[1] = new QAction(QIcon(":/right-icon"),"Panning right (CTRL+arrowRIGHT)",this); vect_QActions[1]->setIconVisibleInMenu(true); QObject::connect( vect_QActions[1],SIGNAL(triggered()),myview, SLOT( siftWindowOnRight() )); vect_QActions[2] = new QAction(QIcon(":/up-icon"),"Panning up (CTRL+arrowUP)",this); vect_QActions[2]->setIconVisibleInMenu(true); QObject::connect( vect_QActions[2],SIGNAL(triggered()),myview, SLOT( siftWindowOnUp() )); vect_QActions[3] = new QAction(QIcon(":/down-icon"),"Panning down (CTRL+arrowDOWN)",this); vect_QActions[3]->setIconVisibleInMenu(true); QObject::connect( vect_QActions[3],SIGNAL(triggered()),myview, SLOT( siftWindowOnDown() )); vect_QActions[4] = new QAction(QIcon(":/zoom_x1-icon"),"Zoom x1 (CTRL+P)",this); vect_QActions[4]->setIconVisibleInMenu(true); QObject::connect( vect_QActions[4],SIGNAL(triggered()),myview, SLOT( resetZoom() )); vect_QActions[5] = new QAction(QIcon(":/imgRegion-icon"),tr("Zoom x%1 (see label) (CTRL+X)") .arg(threshold_zoom_img_region) ,this); vect_QActions[5]->setIconVisibleInMenu(true); QObject::connect( vect_QActions[5],SIGNAL(triggered()),myview, SLOT( imgRegion() )); vect_QActions[6] = new QAction(QIcon(":/zoom_in-icon"),tr("Zoom in (CTRL++)"),this); vect_QActions[6]->setIconVisibleInMenu(true); QObject::connect( vect_QActions[6],SIGNAL(triggered()),myview, SLOT( ZoomIn() )); vect_QActions[7] = new QAction(QIcon(":/zoom_out-icon"),tr("Zoom out (CTRL+-)"),this); vect_QActions[7]->setIconVisibleInMenu(true); QObject::connect( vect_QActions[7],SIGNAL(triggered()),myview, SLOT( ZoomOut() )); vect_QActions[8] = new QAction(QIcon(":/save-icon"),tr("Save current image (CTRL+S)"),this); vect_QActions[8]->setIconVisibleInMenu(true); QObject::connect( vect_QActions[8],SIGNAL(triggered()),myview, SLOT( saveView() )); vect_QActions[9] = new QAction(QIcon(":/properties-icon"),tr("Display properties window (CTRL+P)"),this); vect_QActions[9]->setIconVisibleInMenu(true); QObject::connect( vect_QActions[9],SIGNAL(triggered()),this, SLOT( displayPropertiesWin() )); if (global_control_panel->myLayout->count() == 0) vect_QActions[9]->setDisabled(true); } void CvWidget::createShortcuts() { vect_QShortcuts.resize(10); vect_QShortcuts[0] = new QShortcut(shortcut_panning_left, this); QObject::connect( vect_QShortcuts[0], SIGNAL( activated ()),myview, SLOT( siftWindowOnLeft() )); vect_QShortcuts[1] = new QShortcut(shortcut_panning_right, this); QObject::connect( vect_QShortcuts[1], SIGNAL( activated ()),myview, SLOT( siftWindowOnRight() )); vect_QShortcuts[2] = new QShortcut(shortcut_panning_up, this); QObject::connect(vect_QShortcuts[2], SIGNAL( activated ()),myview, SLOT( siftWindowOnUp() )); vect_QShortcuts[3] = new QShortcut(shortcut_panning_down, this); QObject::connect(vect_QShortcuts[3], SIGNAL( activated ()),myview, SLOT( siftWindowOnDown() )); vect_QShortcuts[4] = new QShortcut(shortcut_zoom_normal, this); QObject::connect( vect_QShortcuts[4], SIGNAL( activated ()),myview, SLOT( resetZoom( ) )); vect_QShortcuts[5] = new QShortcut(shortcut_zoom_imgRegion, this); QObject::connect( vect_QShortcuts[5], SIGNAL( activated ()),myview, SLOT( imgRegion( ) )); vect_QShortcuts[6] = new QShortcut(shortcut_zoom_in, this); QObject::connect( vect_QShortcuts[6], SIGNAL( activated ()),myview, SLOT( ZoomIn() )); vect_QShortcuts[7] = new QShortcut(shortcut_zoom_out, this); QObject::connect(vect_QShortcuts[7], SIGNAL( activated ()),myview, SLOT( ZoomOut() )); vect_QShortcuts[8] = new QShortcut(shortcut_save_img, this); QObject::connect( vect_QShortcuts[8], SIGNAL( activated ()),myview, SLOT( saveView( ) )); vect_QShortcuts[9] = new QShortcut(shortcut_properties_win, this); QObject::connect( vect_QShortcuts[9], SIGNAL( activated ()),this, SLOT( displayPropertiesWin() )); } void CvWidget::createToolBar() { myToolBar = new QToolBar(this); myToolBar->setFloatable(false);//is not a window myToolBar->setFixedHeight(28); myToolBar->setMinimumWidth(1); foreach (QAction *a, vect_QActions) myToolBar->addAction(a); } void CvWidget::createStatusBar() { myStatusBar = new QStatusBar(this); myStatusBar->setSizeGripEnabled(false); myStatusBar->setFixedHeight(20); myStatusBar->setMinimumWidth(1); myStatusBar_msg = new QLabel; //I comment this because if we change the style, myview (the picture) //will not be the correct size anymore (will lost 2 pixel because of the borders) //myStatusBar_msg->setFrameStyle(QFrame::Raised); myStatusBar_msg->setAlignment(Qt::AlignHCenter); myStatusBar->addWidget(myStatusBar_msg); } void CvWidget::createGlobalLayout() { myGlobalLayout = new QBoxLayout(QBoxLayout::TopToBottom); myGlobalLayout->setObjectName(QString::fromUtf8("boxLayout")); myGlobalLayout->setContentsMargins(0, 0, 0, 0); myGlobalLayout->setSpacing(0); myGlobalLayout->setMargin(0); setMinimumSize(1,1); if (param_flags == CV_WINDOW_AUTOSIZE) myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize); if (param_flags == CV_WINDOW_NORMAL) myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize); } void CvWidget::createBarLayout() { myBarLayout = new QBoxLayout(QBoxLayout::TopToBottom); myBarLayout->setObjectName(QString::fromUtf8("barLayout")); myBarLayout->setContentsMargins(0, 0, 0, 0); myBarLayout->setSpacing(0); myBarLayout->setMargin(0); } void CvWidget::createView(int mode, int ratio) { //mode = CV_MODE_NORMAL or CV_MODE_OPENGL //ratio = CV_WINDOW_KEEPRATIO or CV_WINDOW_FREERATIO myview = new ViewPortQtI(this, mode,ratio);//parent, mode_display, keep_aspect_ratio myview->setAlignment(Qt::AlignHCenter); } void CvWidget::setOpenGLCallback(CvOpenGLCallback func,void* userdata, double angle, double zmin, double zmax) { myview->setOpenGLCallback(func,userdata, angle, zmin, zmax ); } ViewPortQtI* CvWidget::getView() { return myview; } void CvWidget::displayInfo(QString text,int delayms) { myview->startDisplayInfo(text, delayms); } void CvWidget::displayStatusBar(QString text,int delayms) { myStatusBar->showMessage(text,delayms); } void CvWidget::updateImage(void* arr) { myview->updateImage(arr); } void CvWidget::setMouseCallBack(CvMouseCallback m, void* param) { myview->setMouseCallBack(m,param); } //addSlider2 is static void CvWidget::addSlider2(CvWidget* w,QString name, int* value, int count,CvTrackbarCallback2 on_change, void* userdata) { QPointer<CvTrackbar> t = new CvTrackbar(w,name,value, count, on_change, userdata); t->setAlignment(Qt::AlignHCenter); QPointer<QBoxLayout> myLayout; if (w) { myLayout = w->myBarLayout; } else { myLayout = global_control_panel->myLayout; //if first one, enable control panel if (myLayout->count() == 0) guiMainThread->enablePropertiesButtonEachWindow(); } myLayout->insertLayout( myLayout->count(),t); } //addSlider is static void CvWidget::addSlider(CvWidget* w,QString name, int* value, int count,CvTrackbarCallback on_change) { QPointer<CvTrackbar> t = new CvTrackbar(w,name,value, count, on_change); t->setAlignment(Qt::AlignHCenter); QPointer<QBoxLayout> myLayout; if (w) { myLayout = w->myBarLayout; } else { myLayout = global_control_panel->myLayout; //if first one, enable control panel if (myLayout->count() == 0) guiMainThread->enablePropertiesButtonEachWindow(); } myLayout->insertLayout( myLayout->count(),t); } //Need more test here ! void CvWidget::keyPressEvent(QKeyEvent *event) { //see http://doc.trolltech.com/4.6/qt.html#Key-enum int key = event->key(); bool goodKey = false; if (key>=20 && key<=255 ) { key = (int)event->text().toLocal8Bit().at(0); goodKey = true; } if (key == Qt::Key_Escape) { key = 27; goodKey = true; } //control plus (Z, +, -, up, down, left, right) are used for zoom/panning functions if (event->modifiers() != Qt::ControlModifier && goodKey) { mutexKey.lock(); last_key = key; //last_key = event->nativeVirtualKey (); mutexKey.unlock(); key_pressed.wakeAll(); //event->accept(); } QWidget::keyPressEvent(event); } //TODO: load CV_GUI flag (done) and act accordingly (create win property if needed and attach trackbars) void CvWidget::readSettings() { //organisation and application's name QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()); QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint(); QSize size = settings.value("size", QSize(200, 200)).toSize(); //param_name = settings.value("name_window",param_name).toString(); param_flags = settings.value("mode_resize",param_flags).toInt(); param_gui_mode = settings.value("mode_gui",param_gui_mode).toInt(); param_ratio_mode = settings.value("mode_ratio",param_ratio_mode).toInt(); myview->param_keepRatio = settings.value("view_aspectRatio",myview->param_keepRatio).toInt(); param_flags = settings.value("mode_resize",param_flags).toInt(); qreal m11 = settings.value("matrix_view.m11",myview->param_matrixWorld.m11()).toDouble(); qreal m12 = settings.value("matrix_view.m12",myview->param_matrixWorld.m12()).toDouble(); qreal m13 = settings.value("matrix_view.m13",myview->param_matrixWorld.m13()).toDouble(); qreal m21 = settings.value("matrix_view.m21",myview->param_matrixWorld.m21()).toDouble(); qreal m22 = settings.value("matrix_view.m22",myview->param_matrixWorld.m22()).toDouble(); qreal m23 = settings.value("matrix_view.m23",myview->param_matrixWorld.m23()).toDouble(); qreal m31 = settings.value("matrix_view.m31",myview->param_matrixWorld.m31()).toDouble(); qreal m32 = settings.value("matrix_view.m32",myview->param_matrixWorld.m32()).toDouble(); qreal m33 = settings.value("matrix_view.m33",myview->param_matrixWorld.m33()).toDouble(); myview->param_matrixWorld = QTransform(m11,m12,m13,m21,m22,m23,m31,m32,m33); //trackbar here icvLoadTrackbars(&settings); resize(size); move(pos); if (global_control_panel) { icvLoadControlPanel(); global_control_panel->move(settings.value("posPanel", global_control_panel->pos()).toPoint()); } } void CvWidget::setStyle( int mode) { param_ratio_mode = myview->param_keepRatio = ( mode & 0x00000F00); param_flags = mode & 0x0000000F; param_gui_mode = mode & 0x000000F0; } void CvWidget::writeSettings() { //organisation and application's name QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()); //settings.setValue("name_window",param_name); settings.setValue("pos", pos()); settings.setValue("size", size()); settings.setValue("mode_resize",param_flags); settings.setValue("mode_gui",param_gui_mode); settings.setValue("param_ratio_mode",param_ratio_mode); settings.setValue("view_aspectRatio",myview->param_keepRatio); settings.setValue("matrix_view.m11",myview->param_matrixWorld.m11()); settings.setValue("matrix_view.m12",myview->param_matrixWorld.m12()); settings.setValue("matrix_view.m13",myview->param_matrixWorld.m13()); settings.setValue("matrix_view.m21",myview->param_matrixWorld.m21()); settings.setValue("matrix_view.m22",myview->param_matrixWorld.m22()); settings.setValue("matrix_view.m23",myview->param_matrixWorld.m23()); settings.setValue("matrix_view.m31",myview->param_matrixWorld.m31()); settings.setValue("matrix_view.m32",myview->param_matrixWorld.m32()); settings.setValue("matrix_view.m33",myview->param_matrixWorld.m33()); icvSaveTrackbars(&settings); if (global_control_panel) { icvSaveControlPanel(); settings.setValue("posPanel", global_control_panel->pos()); } } void CvWidget::icvLoadControlPanel() { QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()+" control panel"); int size = settings.beginReadArray("bars"); int subsize; CvBar* t; if (size == global_control_panel->myLayout->layout()->count()) for (int i = 0; i < size; ++i) { t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i); settings.setArrayIndex(i); if (t->type == type_CvTrackbar) { if (t->name_bar == settings.value("namebar").toString()) { ((CvTrackbar*)t)->slider->setValue(settings.value("valuebar").toInt()); } } if (t->type == type_CvButtonbar) { subsize = settings.beginReadArray(QString("buttonbar")+i); if ( subsize == ((CvButtonbar*)t)->layout()->count() ) icvLoadButtonbar((CvButtonbar*)t,&settings); settings.endArray(); } } settings.endArray(); } void CvWidget::icvSaveControlPanel() { QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()+" control panel"); settings.beginWriteArray("bars"); CvBar* t; for (int i = 0; i < global_control_panel->myLayout->layout()->count(); ++i) { t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i); settings.setArrayIndex(i); if (t->type == type_CvTrackbar) { settings.setValue("namebar", QString(t->name_bar)); settings.setValue("valuebar",((CvTrackbar*)t)->slider->value()); } if (t->type == type_CvButtonbar) { settings.beginWriteArray(QString("buttonbar")+i); icvSaveButtonbar((CvButtonbar*)t,&settings); settings.endArray(); } } settings.endArray(); } void CvWidget::icvSaveButtonbar(CvButtonbar* b,QSettings *settings) { QWidget* temp; QString myclass; for (int i = 0; i < b->layout()->count(); ++i) { settings->setArrayIndex(i); temp = (QWidget*) b->layout()->itemAt(i)->widget(); myclass = QString(temp->metaObject ()->className ()); if (myclass == "CvPushButton") { CvPushButton* button = (CvPushButton*) temp; settings->setValue("namebutton", QString(button->text()) ); settings->setValue("valuebutton", int(button->isChecked())); } if (myclass == "CvCheckBox") { CvCheckBox* button = (CvCheckBox*) temp; settings->setValue("namebutton", QString(button->text()) ); settings->setValue("valuebutton", int(button->isChecked())); } if (myclass == "CvRadioButton") { CvRadioButton* button = (CvRadioButton*) temp; settings->setValue("namebutton", QString(button->text()) ); settings->setValue("valuebutton", int(button->isChecked())); } } } void CvWidget::icvLoadButtonbar(CvButtonbar* b,QSettings *settings) { QWidget* temp; QString myclass; for (int i = 0; i < b->layout()->count(); ++i) { settings->setArrayIndex(i); temp = (QWidget*) b->layout()->itemAt(i)->widget(); myclass = QString(temp->metaObject ()->className ()); if (myclass == "CvPushButton") { CvPushButton* button = (CvPushButton*) temp; if (button->text() == settings->value("namebutton").toString()) button->setChecked(settings->value("valuebutton").toInt()); } if (myclass == "CvCheckBox") { CvCheckBox* button = (CvCheckBox*) temp; if (button->text() == settings->value("namebutton").toString()) button->setChecked(settings->value("valuebutton").toInt()); } if (myclass == "CvRadioButton") { CvRadioButton* button = (CvRadioButton*) temp; if (button->text() == settings->value("namebutton").toString()) button->setChecked(settings->value("valuebutton").toInt()); } } } void CvWidget::icvLoadTrackbars(QSettings *settings) { int size = settings->beginReadArray("trackbars"); QPointer<CvTrackbar> t; //trackbar are saved in the same order, so no need to use icvFindTrackbarByName if (myBarLayout->layout()->count() == size)//if not the same number, the window saved and loaded is not the same (nb trackbar not equal) for (int i = 0; i < size; ++i) { settings->setArrayIndex(i); t = (CvTrackbar*) myBarLayout->layout()->itemAt(i); if (t->name_bar == settings->value("name").toString()) t->slider->setValue(settings->value("value").toInt()); } settings->endArray(); } void CvWidget::icvSaveTrackbars(QSettings *settings) { QPointer<CvTrackbar> t; settings->beginWriteArray("trackbars"); for (int i = 0; i < myBarLayout->layout()->count(); ++i) { t = (CvTrackbar*) myBarLayout->layout()->itemAt(i); settings->setArrayIndex(i); settings->setValue("name", t->name_bar); settings->setValue("value", t->slider->value()); } settings->endArray(); } //Here is ViewPort class ViewPortQtI::ViewPortQtI(CvWidget* arg, int arg2, int arg3) { centralWidget = arg, setParent(centralWidget); mode_display = arg2; param_keepRatio = arg3; //setAlignment(Qt::AlignLeft | Qt::AlignTop); setContentsMargins(0,0,0,0); setMinimumSize(1,1); setObjectName(QString::fromUtf8("graphicsView")); timerDisplay = new QTimer(this); timerDisplay->setSingleShot(true); connect(timerDisplay, SIGNAL(timeout()), this, SLOT(stopDisplayInfo())); drawInfo = false; positionGrabbing = QPointF(0,0); positionCorners = QRect(0,0,size().width(),size().height()); on_mouse = NULL; mouseCoordinate = QPoint(-1,-1); on_openGL_draw3D = NULL; //no border setStyleSheet( "QGraphicsView { border-style: none; }" ); #if defined( HAVE_QT_OPENGL ) if ( mode_display == CV_MODE_OPENGL) { myGL = new QGLWidget(QGLFormat(QGL::SampleBuffers)); setViewport(myGL); if (param_keepRatio == CV_WINDOW_KEEPRATIO) { //TODO: fix this bug: //::::blinking in OpenGL with CV_WINDOW_KEEPRATIO:::: //The raison is that to move the widget in the middle and resize it manually to keep the aspect ratio, //we resize in resizeEvent() and use a trick not to be blocked in an infinity loop. //This is working fine if the viewport is not OpenGL, however we have two rendering with OpenGL. //The first rendering with the widget not moved in the midle (so stuck in top left), then the final and correct rendering. //This two rendering are visible with OpenGL and CV_WINDOW_KEEPRATIO but not with native rendering (why ???) //I tried to use Qt::AlignCenter of the layout manager but the widget does not expand anymore //I tried to center with painter.drawImage (in draw2D), but the imgRegion and all other function using the size of the widget will not work anymore. startDisplayInfo("WARNING: For now, you cannot use OpenGL rendering with CV_WINDOW_KEEPRATIO, so we changed to CV_WINDOW_FREERATIO", 5000); setRatio(CV_WINDOW_FREERATIO); } //setViewport(new QGLWidget()); angle = DEFAULT_ANGLE; zmin = DEFAULT_ZMIN; zmax = DEFAULT_ZMAX; initGL(); } #endif image2Draw_mat = cvCreateMat( 320, 320, CV_8UC3 ); nbChannelOriginImage = 0; cvZero(image2Draw_mat); setInteractive(false); setMouseTracking (true);//receive mouse event everytime } ViewPortQtI::~ViewPortQtI() { if (image2Draw_mat) cvReleaseMat(&image2Draw_mat); //#if defined( HAVE_QT_OPENGL ) // if (myGL) // delete myGL; //#endif; delete timerDisplay; } void ViewPortQtI::contextMenuEvent(QContextMenuEvent *event) { if (centralWidget->vect_QActions.size() > 0) { QMenu menu(this); foreach (QAction *a, centralWidget->vect_QActions) menu.addAction(a); // menu.popup(event->globalPos()); menu.exec(event->globalPos()); } } //can save as JPG, JPEG, BMP, PNG void ViewPortQtI::saveView() { QDate date_d = QDate::currentDate (); QString date_s = date_d.toString("dd.MM.yyyy"); QString name_s = centralWidget->param_name+"_screenshot_"+date_s; QString fileName = QFileDialog::getSaveFileName(this, tr("Save File %1").arg(name_s), name_s+".png", tr("Images (*.png *.jpg *.bmp *.jpeg)")); if (!fileName.isEmpty ())//save the picture { QString extension = fileName.right(3); #if defined( HAVE_QT_OPENGL ) image2Draw_qt_resized = ((QGLWidget*)viewport())->grabFrameBuffer(); #else // (no need anymore) create the image resized to receive the 'screenshot' // image2Draw_qt_resized = QImage(viewport()->width(), viewport()->height(),QImage::Format_RGB888); QPainter saveimage(&image2Draw_qt_resized); this->render(&saveimage); #endif // Save it.. if (QString::compare(extension, "png", Qt::CaseInsensitive) == 0) { image2Draw_qt_resized.save(fileName, "PNG"); return; } if (QString::compare(extension, "jpg", Qt::CaseInsensitive) == 0) { image2Draw_qt_resized.save(fileName, "JPG"); return; } if (QString::compare(extension, "bmp", Qt::CaseInsensitive) == 0) { image2Draw_qt_resized.save(fileName, "BMP"); return; } if (QString::compare(extension, "jpeg", Qt::CaseInsensitive) == 0) { image2Draw_qt_resized.save(fileName, "JPEG"); return; } CV_Error(CV_StsNullPtr, "file extension not recognized, please choose between JPG, JPEG, BMP or PNG"); } } void ViewPortQtI::setRatio(int flags) { centralWidget->param_ratio_mode = flags; param_keepRatio = flags; updateGeometry(); viewport()->update(); } void ViewPortQtI::imgRegion() { scaleView( (threshold_zoom_img_region/param_matrixWorld.m11()-1)*5,QPointF(size().width()/2,size().height()/2)); } int ViewPortQtI::getRatio() { return param_keepRatio; } void ViewPortQtI::resetZoom() { param_matrixWorld.reset(); controlImagePosition(); } void ViewPortQtI::ZoomIn() { scaleView( 0.5,QPointF(size().width()/2,size().height()/2)); } void ViewPortQtI::ZoomOut() { scaleView( -0.5,QPointF(size().width()/2,size().height()/2)); } //Note: move 2 percent of the window void ViewPortQtI::siftWindowOnLeft() { float delta = 2*width()/(100.0*param_matrixWorld.m11()); moveView(QPointF(delta,0)); } //Note: move 2 percent of the window void ViewPortQtI::siftWindowOnRight() { float delta = -2*width()/(100.0*param_matrixWorld.m11()); moveView(QPointF(delta,0)); } //Note: move 2 percent of the window void ViewPortQtI::siftWindowOnUp() { float delta = 2*height()/(100.0*param_matrixWorld.m11()); moveView(QPointF(0,delta)); } //Note: move 2 percent of the window void ViewPortQtI::siftWindowOnDown() { float delta = -2*height()/(100.0*param_matrixWorld.m11()); moveView(QPointF(0,delta)); } void ViewPortQtI::startDisplayInfo(QString text, int delayms) { if (timerDisplay->isActive()) stopDisplayInfo(); infoText = text; timerDisplay->start(delayms); drawInfo = true; } void ViewPortQtI::stopDisplayInfo() { timerDisplay->stop(); drawInfo = false; } inline bool ViewPortQtI::isSameSize(IplImage* img1,IplImage* img2) { return img1->width == img2->width && img1->height == img2->height; } void ViewPortQtI::updateImage(const CvArr *arr) { //if (!arr) //CV_Error(CV_StsNullPtr, "NULL arr pointer (in showImage)" ); CV_Assert(arr); CvMat * mat, stub; int origin=0; if( CV_IS_IMAGE_HDR( arr )) origin = ((IplImage*)arr)->origin; mat = cvGetMat(arr, &stub); //IplImage* tempImage = (IplImage*)arr; if( CV_IS_IMAGE_HDR( arr )) origin = ((IplImage*)arr)->origin; if (!CV_ARE_SIZES_EQ(image2Draw_mat,mat)) { cvReleaseMat(&image2Draw_mat); //the image in ipl (to do a deep copy with cvCvtColor) image2Draw_mat = cvCreateMat( mat->rows, mat->cols, CV_8UC3 ); image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols,image2Draw_mat->rows, image2Draw_mat->step,QImage::Format_RGB888); //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent ratioX=width()/float(image2Draw_mat->cols); ratioY=height()/float(image2Draw_mat->rows); updateGeometry(); } nbChannelOriginImage = cvGetElemType(mat); cvConvertImage(mat,image2Draw_mat,(origin != 0 ? CV_CVTIMG_FLIP : 0) + CV_CVTIMG_SWAP_RB ); viewport()->update(); } void ViewPortQtI::setMouseCallBack(CvMouseCallback m, void* param) { on_mouse = m; on_mouse_param = param; } #if defined( HAVE_QT_OPENGL ) void ViewPortQtI::setOpenGLCallback(CvOpenGLCallback func, void* userdata, double angle_arg, double zmin_arg, double zmax_arg) { //avoid unreferenced formal parameter warning with vs 2008 //http://msdn.microsoft.com/en-en/library/26kb9fy0%28VS.80%29.aspx on_openGL_draw3D = func; on_openGL_param = userdata; if (angle_arg > 0) angle = angle_arg; else angle = DEFAULT_ANGLE; if (zmin_arg >= 0) zmin = zmin_arg; else zmin = DEFAULT_ZMIN; if (zmax_arg > 0) zmax = zmax_arg; else zmax = DEFAULT_ZMAX; } #else void ViewPortQtI::setOpenGLCallback(CvOpenGLCallback, void*, double, double, double) { } #endif void ViewPortQtI::controlImagePosition() { qreal left, top, right, bottom; //after check top-left, bottom right corner to avoid getting "out" during zoom/panning param_matrixWorld.map(0,0,&left,&top); if (left > 0) { param_matrixWorld.translate(-left,0); left = 0; } if (top > 0) { param_matrixWorld.translate(0,-top); top = 0; } //------- QSize sizeImage = size(); param_matrixWorld.map(sizeImage.width(),sizeImage.height(),&right,&bottom); if (right < sizeImage.width()) { param_matrixWorld.translate(sizeImage.width()-right,0); right = sizeImage.width(); } if (bottom < sizeImage.height()) { param_matrixWorld.translate(0,sizeImage.height()-bottom); bottom = sizeImage.height(); } //save corner position positionCorners.setTopLeft(QPoint(left,top)); positionCorners.setBottomRight(QPoint(right,bottom)); //save also the inv matrix matrixWorld_inv = param_matrixWorld.inverted(); //viewport()->update(); } void ViewPortQtI::moveView(QPointF delta) { param_matrixWorld.translate(delta.x(),delta.y()); controlImagePosition(); viewport()->update(); } //factor is -0.5 (zoom out) or 0.5 (zoom in) void ViewPortQtI::scaleView(qreal factor,QPointF center) { factor/=5;//-0.1 <-> 0.1 factor+=1;//0.9 <-> 1.1 //limit zoom out --- if (param_matrixWorld.m11()==1 && factor < 1) return; if (param_matrixWorld.m11()*factor<1) factor = 1/param_matrixWorld.m11(); //limit zoom int --- if (param_matrixWorld.m11()>100 && factor > 1) return; //inverse the transform int a, b; matrixWorld_inv.map(center.x(),center.y(),&a,&b); param_matrixWorld.translate(a-factor*a,b-factor*b); param_matrixWorld.scale(factor,factor); controlImagePosition(); //display new zoom if (centralWidget->myStatusBar) centralWidget->displayStatusBar(tr("Zoom: %1%").arg(param_matrixWorld.m11()*100),1000); if (param_matrixWorld.m11()>1) setCursor(Qt::OpenHandCursor); else unsetCursor(); } void ViewPortQtI::wheelEvent(QWheelEvent *event) { scaleView( -event->delta() / 240.0,event->pos()); viewport()->update(); } void ViewPortQtI::mousePressEvent(QMouseEvent *event) { int cv_event = -1, flags = 0; QPoint pt = event->pos(); //icvmouseHandler: pass parameters for cv_event, flags icvmouseHandler(event, mouse_down, cv_event, flags); icvmouseProcessing(QPointF(pt), cv_event, flags); if (param_matrixWorld.m11()>1) { setCursor(Qt::ClosedHandCursor); positionGrabbing = event->pos(); } QWidget::mousePressEvent(event); } void ViewPortQtI::mouseReleaseEvent(QMouseEvent *event) { int cv_event = -1, flags = 0; QPoint pt = event->pos(); //icvmouseHandler: pass parameters for cv_event, flags icvmouseHandler(event, mouse_up, cv_event, flags); icvmouseProcessing(QPointF(pt), cv_event, flags); if (param_matrixWorld.m11()>1) setCursor(Qt::OpenHandCursor); QWidget::mouseReleaseEvent(event); } void ViewPortQtI::mouseDoubleClickEvent(QMouseEvent *event) { int cv_event = -1, flags = 0; QPoint pt = event->pos(); //icvmouseHandler: pass parameters for cv_event, flags icvmouseHandler(event, mouse_dbclick, cv_event, flags); icvmouseProcessing(QPointF(pt), cv_event, flags); QWidget::mouseDoubleClickEvent(event); } void ViewPortQtI::mouseMoveEvent(QMouseEvent *event) { int cv_event = CV_EVENT_MOUSEMOVE, flags = 0; QPoint pt = event->pos(); //icvmouseHandler: pass parameters for cv_event, flags icvmouseHandler(event, mouse_move, cv_event, flags); icvmouseProcessing(QPointF(pt), cv_event, flags); if (param_matrixWorld.m11()>1 && event->buttons() == Qt::LeftButton) { QPointF dxy = (pt - positionGrabbing)/param_matrixWorld.m11(); positionGrabbing = event->pos(); moveView(dxy); } //I update the statusbar here because if the user does a cvWaitkey(0) (like with inpaint.cpp) //the status bar will only be repaint when a click occurs. if (centralWidget->myStatusBar) viewport()->update(); QWidget::mouseMoveEvent(event); } /*void ViewPort::dragMoveEvent(QDragMoveEvent *event) { QPoint pt = event->pos(); //icvmouseHandler: pass parameters for cv_event, flags icvmouseProcessing(QPointF(pt), CV_EVENT_MOUSEMOVE, CV_EVENT_FLAG_LBUTTON); if (param_matrixWorld.m11()>1) { QPointF dxy = (pt - positionGrabbing)/param_matrixWorld.m11(); positionGrabbing = event->pos(); moveView(dxy); } //I update the statusbar here because if the user does a cvWaitkey(0) (like with inpaint.cpp) //the status bar will only be repaint when a click occurs. if (centralWidget->myStatusBar) viewport()->update(); QWidget::dragMoveEvent(event); }*/ //up, down, dclick, move void ViewPortQtI::icvmouseHandler(QMouseEvent *event, type_mouse_event category, int &cv_event, int &flags) { Qt::KeyboardModifiers modifiers = event->modifiers(); Qt::MouseButtons buttons = event->buttons(); flags = 0; if(modifiers & Qt::ShiftModifier) flags |= CV_EVENT_FLAG_SHIFTKEY; if(modifiers & Qt::ControlModifier) flags |= CV_EVENT_FLAG_CTRLKEY; if(modifiers & Qt::AltModifier) flags |= CV_EVENT_FLAG_ALTKEY; if(buttons & Qt::LeftButton) flags |= CV_EVENT_FLAG_LBUTTON; if(buttons & Qt::RightButton) flags |= CV_EVENT_FLAG_RBUTTON; if(buttons & Qt::MidButton) flags |= CV_EVENT_FLAG_MBUTTON; cv_event = CV_EVENT_MOUSEMOVE; switch(event->button()) { case Qt::LeftButton: cv_event = tableMouseButtons[category][0]; flags |= CV_EVENT_FLAG_LBUTTON; break; case Qt::RightButton: cv_event = tableMouseButtons[category][1]; flags |= CV_EVENT_FLAG_RBUTTON; break; case Qt::MidButton: cv_event = tableMouseButtons[category][2]; flags |= CV_EVENT_FLAG_MBUTTON; break; default:; } } void ViewPortQtI::icvmouseProcessing(QPointF pt, int cv_event, int flags) { //to convert mouse coordinate qreal pfx, pfy; matrixWorld_inv.map(pt.x(),pt.y(),&pfx,&pfy); mouseCoordinate.rx()=floor(pfx/ratioX); mouseCoordinate.ry()=floor(pfy/ratioY); if (on_mouse) on_mouse( cv_event, mouseCoordinate.x(), mouseCoordinate.y(), flags, on_mouse_param ); } QSize ViewPortQtI::sizeHint() const { if(image2Draw_mat) return QSize(image2Draw_mat->cols,image2Draw_mat->rows); else return QGraphicsView::sizeHint(); } void ViewPortQtI::resizeEvent ( QResizeEvent *event) { controlImagePosition(); //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent ratioX=width()/float(image2Draw_mat->cols); ratioY=height()/float(image2Draw_mat->rows); if(param_keepRatio == CV_WINDOW_KEEPRATIO)//to keep the same aspect ratio { QSize newSize = QSize(image2Draw_mat->cols,image2Draw_mat->rows); newSize.scale(event->size(),Qt::KeepAspectRatio); //imageWidth/imageHeight = newWidth/newHeight +/- epsilon //ratioX = ratioY +/- epsilon //||ratioX - ratioY|| = epsilon if (fabs(ratioX - ratioY)*100> ratioX)//avoid infinity loop / epsilon = 1% of ratioX { resize(newSize); //move to the middle //newSize get the delta offset to place the picture in the middle of its parent newSize= (event->size()-newSize)/2; //if the toolbar is displayed, avoid drawing myview on top of it if (centralWidget->myToolBar) if(!centralWidget->myToolBar->isHidden()) newSize +=QSize(0,centralWidget->myToolBar->height()); move(newSize.width(),newSize.height()); } } return QGraphicsView::resizeEvent(event); } void ViewPortQtI::paintEvent(QPaintEvent* event) { QPainter myPainter(viewport()); myPainter.setWorldTransform(param_matrixWorld); draw2D(&myPainter); #if defined( HAVE_QT_OPENGL ) if ( mode_display == CV_MODE_OPENGL && on_openGL_draw3D) { myPainter.save(); // Needed when using the GL1 engine myPainter.beginNativePainting(); // Needed when using the GL2 engine setGL(width(),height()); on_openGL_draw3D(on_openGL_param); unsetGL(); myPainter.endNativePainting(); // Needed when using the GL2 engine myPainter.restore(); // Needed when using the GL1 engine } #endif //Now disable matrixWorld for overlay display myPainter.setWorldMatrixEnabled (false ); //in mode zoom/panning if (param_matrixWorld.m11()>1) { if (param_matrixWorld.m11()>=threshold_zoom_img_region) { if (centralWidget->param_flags == CV_WINDOW_NORMAL) startDisplayInfo("WARNING: The values displayed are the resized image's values. If you want the original image's values, use CV_WINDOW_AUTOSIZE", 1000); drawImgRegion(&myPainter); } drawViewOverview(&myPainter); } //for information overlay if (drawInfo) drawInstructions(&myPainter); //for statusbar if (centralWidget->myStatusBar) drawStatusBar(); QGraphicsView::paintEvent(event); } void ViewPortQtI::draw2D(QPainter *painter) { image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows,image2Draw_mat->step,QImage::Format_RGB888); image2Draw_qt_resized = image2Draw_qt.scaled(viewport()->width(),viewport()->height(),Qt::IgnoreAspectRatio,Qt::FastTransformation);//Qt::SmoothTransformation); painter->drawImage(0,0,image2Draw_qt_resized); } //only if CV_8UC1 or CV_8UC3 void ViewPortQtI::drawStatusBar() { if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3) return; //if (mouseCoordinate.x()>=0 && // mouseCoordinate.y()>=0 && // mouseCoordinate.x()<image2Draw_qt.width() && // mouseCoordinate.y()<image2Draw_qt.height()) if (mouseCoordinate.x()>=0 && mouseCoordinate.y()>=0) { QRgb rgbValue = image2Draw_qt.pixel(mouseCoordinate); if (nbChannelOriginImage==CV_8UC3 ) { centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>") .arg(mouseCoordinate.x()) .arg(mouseCoordinate.y())+ tr("<font color='red'>R:%3 </font>").arg(qRed(rgbValue))+//.arg(value.val[0])+ tr("<font color='green'>G:%4 </font>").arg(qGreen(rgbValue))+//.arg(value.val[1])+ tr("<font color='blue'>B:%5</font>").arg(qBlue(rgbValue))//.arg(value.val[2]) ); } if (nbChannelOriginImage==CV_8UC1) { //all the channel have the same value (because of cvconvertimage), so only the r channel is dsplayed centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>") .arg(mouseCoordinate.x()) .arg(mouseCoordinate.y())+ tr("<font color='grey'>L:%3 </font>").arg(qRed(rgbValue)) ); } } } //accept only CV_8UC1 and CV_8UC8 image for now void ViewPortQtI::drawImgRegion(QPainter *painter) { if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3) return; qreal offsetX = param_matrixWorld.dx()/param_matrixWorld.m11(); offsetX = offsetX - floor(offsetX); qreal offsetY = param_matrixWorld.dy()/param_matrixWorld.m11(); offsetY = offsetY - floor(offsetY); QSize view = size(); QVarLengthArray<QLineF, 30> linesX; for (qreal x = offsetX*param_matrixWorld.m11(); x < view.width(); x += param_matrixWorld.m11() ) linesX.append(QLineF(x, 0, x, view.height())); QVarLengthArray<QLineF, 30> linesY; for (qreal y = offsetY*param_matrixWorld.m11(); y < view.height(); y += param_matrixWorld.m11() ) linesY.append(QLineF(0, y, view.width(), y)); QFont f = painter->font(); int original_font_size = f.pointSize(); //change font size //f.setPointSize(4+(param_matrixWorld.m11()-threshold_zoom_img_region)/5); f.setPixelSize(10+(param_matrixWorld.m11()-threshold_zoom_img_region)/5); painter->setFont(f); QString val; QRgb rgbValue; QPointF point1;//sorry, I do not know how to name it QPointF point2;//idem for (int j=-1;j<height()/param_matrixWorld.m11();j++)//-1 because display the pixels top rows left colums for (int i=-1;i<width()/param_matrixWorld.m11();i++)//-1 { point1.setX((i+offsetX)*param_matrixWorld.m11()); point1.setY((j+offsetY)*param_matrixWorld.m11()); matrixWorld_inv.map(point1.x(),point1.y(),&point2.rx(),&point2.ry()); point2.rx()= (long) (point2.x() + 0.5); point2.ry()= (long) (point2.y() + 0.5); if (point2.x() >= 0 && point2.y() >= 0) rgbValue = image2Draw_qt_resized.pixel(QPoint(point2.x(),point2.y())); else rgbValue = qRgb(0,0,0); if (nbChannelOriginImage==CV_8UC3) { //for debug /* val = tr("%1 %2").arg(point2.x()).arg(point2.y()); painter->setPen(QPen(Qt::black, 1)); painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/2), Qt::AlignCenter, val); */ val = tr("%1").arg(qRed(rgbValue)); painter->setPen(QPen(Qt::red, 1)); painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/3), Qt::AlignCenter, val); val = tr("%1").arg(qGreen(rgbValue)); painter->setPen(QPen(Qt::green, 1)); painter->drawText(QRect(point1.x(),point1.y()+param_matrixWorld.m11()/3,param_matrixWorld.m11(),param_matrixWorld.m11()/3), Qt::AlignCenter, val); val = tr("%1").arg(qBlue(rgbValue)); painter->setPen(QPen(Qt::blue, 1)); painter->drawText(QRect(point1.x(),point1.y()+2*param_matrixWorld.m11()/3,param_matrixWorld.m11(),param_matrixWorld.m11()/3), Qt::AlignCenter, val); } if (nbChannelOriginImage==CV_8UC1) { val = tr("%1").arg(qRed(rgbValue)); painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()), Qt::AlignCenter, val); } } painter->setPen(QPen(Qt::black, 1)); painter->drawLines(linesX.data(), linesX.size()); painter->drawLines(linesY.data(), linesY.size()); //restore font size f.setPointSize(original_font_size); painter->setFont(f); } void ViewPortQtI::drawViewOverview(QPainter *painter) { QSize viewSize = size(); viewSize.scale ( 100, 100,Qt::KeepAspectRatio ); const int margin = 5; //draw the image's location painter->setBrush(QColor(0, 0, 0, 127)); painter->setPen(Qt::darkGreen); painter->drawRect(QRect(width()-viewSize.width()-margin, 0,viewSize.width(),viewSize.height())); //daw the view's location inside the image qreal ratioSize = 1/param_matrixWorld.m11(); qreal ratioWindow = (qreal)(viewSize.height())/(qreal)(size().height()); painter->setPen(Qt::darkBlue); painter->drawRect(QRectF(width()-viewSize.width()-positionCorners.left()*ratioSize*ratioWindow-margin, -positionCorners.top()*ratioSize*ratioWindow, (viewSize.width()-1)*ratioSize, (viewSize.height()-1)*ratioSize) ); } void ViewPortQtI::drawInstructions(QPainter *painter) { QFontMetrics metrics = QFontMetrics(font()); int border = qMax(4, metrics.leading()); QRect rect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125), Qt::AlignCenter | Qt::TextWordWrap, infoText); painter->setRenderHint(QPainter::TextAntialiasing); painter->fillRect(QRect(0, 0, width(), rect.height() + 2*border), QColor(0, 0, 0, 127)); painter->setPen(Qt::white); painter->fillRect(QRect(0, 0, width(), rect.height() + 2*border), QColor(0, 0, 0, 127)); painter->drawText((width() - rect.width())/2, border, rect.width(), rect.height(), Qt::AlignCenter | Qt::TextWordWrap, infoText); } #if defined( HAVE_QT_OPENGL )//all this section -> not tested void ViewPortQtI::initGL() { glShadeModel( GL_SMOOTH ); glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); glEnable( GL_TEXTURE_2D ); glEnable( GL_CULL_FACE ); glEnable( GL_DEPTH_TEST ); } //from http://steinsoft.net/index.php?site=Programming/Code%20Snippets/OpenGL/gluperspective //do not want to link glu void ViewPortQtI::icvgluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar) { GLdouble xmin, xmax, ymin, ymax; ymax = zNear * tan(fovy * M_PI / 360.0); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; glFrustum(xmin, xmax, ymin, ymax, zNear, zFar); } void ViewPortQtI::setGL(int width, int height) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); icvgluPerspective(angle, float(width) / float(height), zmin, zmax); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); } void ViewPortQtI::unsetGL() { glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } #endif
[ [ [ 1, 2947 ] ] ]
a4334c0128ca9d443e0f9297149aea3c25ac2001
23e9e5636c692364688bc9e4df59cb68e2447a58
/Dream/src/Sample/Sprite.h
a374d7a367fb2272e02213d475b0f0168791419e
[]
no_license
yestein/dream-of-idle
e492af2a4758776958b43e4bf0e4db859a224c40
4e362ab98f232d68535ea26f2fab7b3cbf7bc867
refs/heads/master
2016-09-09T19:49:18.215943
2010-04-23T07:24:19
2010-04-23T07:24:19
34,108,886
0
0
null
null
null
null
UTF-8
C++
false
false
2,447
h
/************************************************************************ filename: Sprite.h created: 2010/3/21 author: Yu Lei([email protected]) <change list> 1. create file (Yu Lei) purpose: Sprite API ************************************************************************/ #ifndef YGE_SPRITE_H #define YGE_SPRITE_H //--------------------------------------------------------------- #include "YGEDirectX.h" #include "YGEWin32.h" #define DOWN 0 #define LEFT 1 #define RIGHT 2 #define UP 3 class Map { HWND hWindow; int Width; int Height; public: LPDIRECTDRAWSURFACE7 lpSMap; Map( ); ~Map(void) { if(lpSMap) lpSMap->Release(); } void Initial(int W,int H) { Width = W; Height = H; } const int GetWidth() { return Width; } const int GetHeight() { return Height; } }; class Sprite { int Width; int Height; int dir; int _X; int _Y; int click_x; int click_y; HWND hWindow; bool Visible; bool pick; int *sequence; int seq_num; void Paint(); void Clean(); int current_frame; int next_frame; int seq[9]; public: LPDIRECTDRAWSURFACE7 lpSSprite; Sprite( ); ~Sprite(void){ } void Initial(int width,int height,int x,int y,int dir,int *sequence,int seq_num); void Play(); void setPick(bool p) { pick = p; } void setVisible(bool v) { if(Visible!=v) Visible = v; } void setDir(int d) { if(dir!=d) { dir = d; current_frame = 0; next_frame=(current_frame+1)%seq_num; } else { current_frame=next_frame; next_frame=(current_frame+1)%seq_num; } } void setClick(int x,int y) { click_x = x-_X;click_y = y-_Y; } void setXY(int x,int y) { _X=x;_Y=y; } void Move(int dir,int pixel); bool CheckForEdge(int dir,int pixel,int H,int W); // friend bool CheckForCollison(Sprite s1,Sprite s2); bool IsPick() { return pick; } bool IsVisible() { return Visible; } const int GetDir() { return dir; } const int GetX() { return _X; } const int GetY() { return _Y; } const int GetHeight() { return Height; } const int GetWidth() { return Width; } const int GetCurFram() { return sequence[current_frame]; } const int GetClickX() { return click_x; } const int GetClickY() { return click_y; } }; //--YGE_SPRITE_H------------------------------------------------- #endif
[ "yestein86@6bb0ce84-d3d1-71f5-47c4-2d9a3e80541b" ]
[ [ [ 1, 151 ] ] ]
2b9a310fcf4f074c6a9647ef492d784d7c1d50e9
c1c3866586c56ec921cd8c9a690e88ac471adfc8
/CEGUI/CEGUI-0.6.0/include/elements/CEGUITreeItem.h
94bd70089ad084f76df79ac0cb5bcd66814c9831
[ "Zlib", "LicenseRef-scancode-pcre", "MIT" ]
permissive
rtmpnewbie/lai3d
0802dbb5ebe67be2b28d9e8a4d1cc83b4f36b14f
b44c9edfb81fde2b40e180a651793fec7d0e617d
refs/heads/master
2021-01-10T04:29:07.463289
2011-03-22T17:51:24
2011-03-22T17:51:24
36,842,700
1
0
null
null
null
null
UTF-8
C++
false
false
17,996
h
/*********************************************************************** filename: CEGUITreeItem.h created: 5-13-07 author: Jonathan Welch (Based on Code by David Durant) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifndef _CEGUITreeItem_h_ #define _CEGUITreeItem_h_ #include "CEGUIBase.h" #include "CEGUIString.h" #include "CEGUIColourRect.h" #include "CEGUIRenderCache.h" // Start of CEGUI namespace section namespace CEGUI { /*! \brief Base class for list box items */ class CEGUIEXPORT TreeItem { public: typedef std::vector<TreeItem*> LBItemList; /************************************************************************* Constants *************************************************************************/ static const colour DefaultTextColour; //!< Default text colour. static const colour DefaultSelectionColour; //!< Default selection brush colour. /************************************************************************* Construction and Destruction *************************************************************************/ /*! \brief base class constructor */ TreeItem(const String& text, uint item_id = 0, void* item_data = 0, bool disabled = false, bool auto_delete = true); /*! \brief base class destructor */ virtual ~TreeItem(void) {} /************************************************************************* Accessors *************************************************************************/ /*! \brief Return a pointer to the font being used by this ListboxTextItem This method will try a number of places to find a font to be used. If no font can be found, NULL is returned. \return Font to be used for rendering this item */ Font* getFont(void) const; /*! \brief Return the current colours used for text rendering. \return ColourRect object describing the currently set colours */ ColourRect getTextColours(void) const {return d_textCols;} /************************************************************************* Manipulator methods *************************************************************************/ /*! \brief Set the font to be used by this ListboxTextItem \param font Font to be used for rendering this item \return Nothing */ void setFont(Font* font) {d_font = font;} /*! \brief Set the font to be used by this ListboxTextItem \param font_name String object containing the name of the Font to be used for rendering this item \return Nothing */ void setFont(const String& font_name); /*! \brief Set the colours used for text rendering. \param cols ColourRect object describing the colours to be used. \return Nothing. */ void setTextColours(const ColourRect& cols) {d_textCols = cols;} /*! \brief Set the colours used for text rendering. \param top_left_colour Colour (as ARGB value) to be applied to the top-left corner of each text glyph rendered. \param top_right_colour Colour (as ARGB value) to be applied to the top-right corner of each text glyph rendered. \param bottom_left_colour Colour (as ARGB value) to be applied to the bottom-left corner of each text glyph rendered. \param bottom_right_colour Colour (as ARGB value) to be applied to the bottom-right corner of each text glyph rendered. \return Nothing. */ void setTextColours(colour top_left_colour, colour top_right_colour, colour bottom_left_colour, colour bottom_right_colour); /*! \brief Set the colours used for text rendering. \param col colour value to be used when rendering. \return Nothing. */ void setTextColours(colour col) {setTextColours(col, col, col, col);} /*! \brief return the text string set for this list box item. Note that even if the item does not render text, the text string can still be useful, since it is used for sorting list box items. \return String object containing the current text for the list box item. */ const String& getText(void) const {return d_itemText;} const String& getTooltipText(void) const {return d_tooltipText;} /*! \brief Return the current ID assigned to this list box item. Note that the system does not make use of this value, client code can assign any meaning it wishes to the ID. \return ID code currently assigned to this list box item */ uint getID(void) const {return d_itemID;} /*! \brief Return the pointer to any client assigned user data attached to this lis box item. Note that the system does not make use of this data, client code can assign any meaning it wishes to the attached data. \return Pointer to the currently assigned user data. */ void* getUserData(void) const {return d_itemData;} /*! \brief return whether this item is selected. \return true if the item is selected, false if the item is not selected. */ bool isSelected(void) const {return d_selected;} /*! \brief return whether this item is disabled. \return true if the item is disabled, false if the item is enabled. */ bool isDisabled(void) const {return d_disabled;} /*! \brief return whether this item will be automatically deleted when the list box it is attached to is destroyed, or when the item is removed from the list box. \return true if the item object will be deleted by the system when the list box it is attached to is destroyed, or when the item is removed from the list. false if client code must destroy the item after it is removed from the list. */ bool isAutoDeleted(void) const {return d_autoDelete;} /*! \brief Get the owner window for this TreeItem. The owner of a TreeItem is typically set by the list box widgets when an item is added or inserted. \return Ponter to the window that is considered the owner of this TreeItem. */ // const Window* getOwnerWindow(const Window* owner) {return d_owner;} const Window* getOwnerWindow(void) {return d_owner;} /*! \brief Return the current colours used for selection highlighting. \return ColourRect object describing the currently set colours */ ColourRect getSelectionColours(void) const {return d_selectCols;} /*! \brief Return the current selection highlighting brush. \return Pointer to the Image object currently used for selection highlighting. */ const Image* getSelectionBrushImage(void) const {return d_selectBrush;} /************************************************************************* Manipulators *************************************************************************/ /*! \brief set the text string for this list box item. Note that even if the item does not render text, the text string can still be useful, since it is used for sorting list box items. \param text String object containing the text to set for the list box item. \return Nothing. */ void setText(const String& text) {d_itemText = text;} void setTooltipText(const String& text) {d_tooltipText = text;} /*! \brief Set the ID assigned to this list box item. Note that the system does not make use of this value, client code can assign any meaning it wishes to the ID. \param item_id ID code to be assigned to this list box item \return Nothing. */ void setID(uint item_id) {d_itemID = item_id;} /*! \brief Set the client assigned user data attached to this lis box item. Note that the system does not make use of this data, client code can assign any meaning it wishes to the attached data. \param item_data Pointer to the user data to attach to this list item. \return Nothing. */ void setUserData(void* item_data) {d_itemData = item_data;} /*! \brief set whether this item is selected. \param setting true if the item is selected, false if the item is not selected. \return Nothing. */ void setSelected(bool setting) {d_selected = setting;} /*! \brief set whether this item is disabled. \param setting true if the item is disabled, false if the item is enabled. \return Nothing. */ void setDisabled(bool setting) {d_disabled = setting;} /*! \brief Set whether this item will be automatically deleted when the list box it is attached to is destroyed, or when the item is removed from the list box. \param setting true if the item object should be deleted by the system when the list box it is attached to is destroyed, or when the item is removed from the list. false if client code will destroy the item after it is removed from the list. \return Nothing. */ void setAutoDeleted(bool setting) {d_autoDelete = setting;} /*! \brief Set the owner window for this TreeItem. This is called by all the list box widgets when an item is added or inserted. \param owner Ponter to the window that should be considered the owner of this TreeItem. \return Nothing */ void setOwnerWindow(const Window* owner) {d_owner = owner;} /*! \brief Set the colours used for selection highlighting. \param cols ColourRect object describing the colours to be used. \return Nothing. */ void setSelectionColours(const ColourRect& cols) {d_selectCols = cols;} /*! \brief Set the colours used for selection highlighting. \param top_left_colour Colour (as ARGB value) to be applied to the top-left corner of the selection area. \param top_right_colour Colour (as ARGB value) to be applied to the top-right corner of the selection area. \param bottom_left_colour Colour (as ARGB value) to be applied to the bottom-left corner of the selection area. \param bottom_right_colour Colour (as ARGB value) to be applied to the bottom-right corner of the selection area. \return Nothing. */ void setSelectionColours(colour top_left_colour, colour top_right_colour, colour bottom_left_colour, colour bottom_right_colour); /*! \brief Set the colours used for selection highlighting. \param col colour value to be used when rendering. \return Nothing. */ void setSelectionColours(colour col) {setSelectionColours(col, col, col, col);} /*! \brief Set the selection highlighting brush image. \param image Pointer to the Image object to be used for selection highlighting. \return Nothing. */ void setSelectionBrushImage(const Image* image) {d_selectBrush = image;} /*! \brief Set the selection highlighting brush image. \param imageset Name of the imagest containing the image to be used. \param image Name of the image to be used \return Nothing. */ void setSelectionBrushImage(const String& imageset, const String& image); /*! \brief Tell the treeItem where its button is located. Calculated and set in Tree.cpp. \param buttonOffset Location of the button in screenspace. */ void setButtonLocation(Rect &buttonOffset) { d_buttonLocation = buttonOffset; } Rect &getButtonLocation(void) { return d_buttonLocation; } bool getIsOpen(void) { return d_isOpen; } void toggleIsOpen(void) { d_isOpen = !d_isOpen; } TreeItem *getTreeItemFromIndex(size_t itemIndex); size_t getItemCount(void) const {return d_listItems.size();} LBItemList &getItemList(void) { return d_listItems; } void addItem(TreeItem* item); void setIcon(const Image &theIcon) { d_iconImage = (Image *)&theIcon; } /************************************************************************* Abstract portion of interface *************************************************************************/ /*! \brief Return the rendered pixel size of this list box item. \return Size object describing the size of the list box item in pixels. */ virtual Size getPixelSize(void) const; /*! \brief Draw the list box item in its current state \param position Vecor3 object describing the upper-left corner of area that should be rendered in to for the draw operation. \param alpha Alpha value to be used when rendering the item (between 0.0f and 1.0f). \param clipper Rect object describing the clipping rectangle for the draw operation. \return Nothing. */ virtual void draw(const Vector3& position, float alpha, const Rect& clipper) const; virtual void draw(RenderCache& cache,const Rect& targetRect, float zBase, float alpha, const Rect* clipper) const; /************************************************************************* Operators *************************************************************************/ /*! \brief Less-than operator, compares item texts. */ virtual bool operator<(const TreeItem& rhs) const {return d_itemText < rhs.getText();} /*! \brief Greater-than operator, compares item texts. */ virtual bool operator>(const TreeItem& rhs) const {return d_itemText > rhs.getText();} protected: /************************************************************************* Implementation methods *************************************************************************/ /*! \brief Return a ColourRect object describing the colours in \a cols after having their alpha component modulated by the value \a alpha. */ ColourRect getModulateAlphaColourRect(const ColourRect& cols, float alpha) const; /*! \brief Return a colour value describing the colour specified by \a col after having its alpha component modulated by the value \a alpha. */ colour calculateModulatedAlphaColour(colour col, float alpha) const; /************************************************************************* Implementation Data *************************************************************************/ String d_itemText; //!< Text for this list box item. If not rendered, this is still used for list sorting. String d_tooltipText; //!< Text for the individual tooltip of this item uint d_itemID; //!< ID code assigned by client code. This has no meaning within the GUI system. void * d_itemData; //!< Pointer to some client code data. This has no meaning within the GUI system. bool d_selected; //!< true if this item is selected. false if the item is not selected. bool d_disabled; //!< true if this item is disabled. false if the item is not disabled. bool d_autoDelete; //!< true if the system should destroy this item, false if client code will destroy the item. Rect d_buttonLocation; //!< const Window * d_owner; //!< Pointer to the window that owns this item. ColourRect d_selectCols; //!< Colours used for selection highlighting. const Image * d_selectBrush; //!< Image used for rendering selection. ColourRect d_textCols; //!< Colours used for rendering the text. Font * d_font; //!< Font used for rendering text. Image * d_iconImage; //!< Icon to be displayed with this treeItem LBItemList d_listItems; //!< list of items in this item's tree branch. bool d_isOpen; //!< true if the this item's tree branch is opened }; } // End of CEGUI namespace section #endif // end of guard _CEGUITreeItem_h_
[ "laiyanlin@27d9c402-1b7e-11de-9433-ad2e3fad96c5" ]
[ [ [ 1, 577 ] ] ]
01625ce290fb152cee0d3604a382606dcc848822
54cacc105d6bacdcfc37b10d57016bdd67067383
/trunk/source/level/objects/contactresolvers/BounceContactResolver.cpp
0c0315e1f5ba9c73f69b56a9162eb81d5684a9db
[]
no_license
galek/hesperus
4eb10e05945c6134901cc677c991b74ce6c8ac1e
dabe7ce1bb65ac5aaad144933d0b395556c1adc4
refs/heads/master
2020-12-31T05:40:04.121180
2009-12-06T17:38:49
2009-12-06T17:38:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,693
cpp
/*** * hesperus: BounceContactResolver.cpp * Copyright Stuart Golodetz, 2009. All rights reserved. ***/ #include "BounceContactResolver.h" #include <source/level/physics/Contact.h> #include <source/level/physics/PhysicsObject.h> #include <source/level/trees/OnionUtil.h> #include <source/math/Constants.h> namespace hesp { //#################### CONSTRUCTORS #################### BounceContactResolver::BounceContactResolver(double restitutionCoefficient) : m_restitutionCoefficient(restitutionCoefficient) {} //#################### PRIVATE METHODS #################### void BounceContactResolver::resolve_object_object(const Contact& contact, const OnionTree_CPtr& tree) const { // Step 1: Calculate what fractions of the resolution will apply to each of the two objects involved. PhysicsObject& objectA = contact.objectA(); PhysicsObject& objectB = *contact.objectB(); double invMassA = objectA.inverse_mass(); double invMassB = objectB.inverse_mass(); double totalInvMass = invMassA + invMassB; // We can't resolve a collision between two objects with infinite mass, since we can't move either of them. if(totalInvMass < EPSILON) return; double fractionA = invMassA / totalInvMass; double fractionB = invMassB / totalInvMass; // Step 2: Resolve interpenetration. For object-object contacts, this involves moving the // objects apart along the contact normal in proportion to their inverse masses. double penetrationDepth = contact.penetration_depth(); double depthA = penetrationDepth * fractionA; double depthB = penetrationDepth * fractionB; // Update the positions of the objects to resolve the interpenetration, without letting either object // end up embedded in the world. Vector3d newPosA = objectA.position() + contact.normal() * depthA; Vector3d newPosB = objectB.position() - contact.normal() * depthB; Vector3d fixedPosA = newPosA; if(contact.map_indexA() != -1) { OnionUtil::Transition transitionA = OnionUtil::find_first_transition(contact.map_indexA(), objectA.position(), fixedPosA, tree); switch(transitionA.classifier) { case OnionUtil::RAY_SOLID: fixedPosA = objectA.position(); break; case OnionUtil::RAY_TRANSITION_ES: fixedPosA = *transitionA.location; break; default: break; } } Vector3d fixedPosB = newPosB + (fixedPosA - newPosA); if(*contact.map_indexB() != -1) { OnionUtil::Transition transitionB = OnionUtil::find_first_transition(*contact.map_indexB(), objectB.position(), fixedPosB, tree); switch(transitionB.classifier) { case OnionUtil::RAY_SOLID: fixedPosB = objectB.position(); break; case OnionUtil::RAY_TRANSITION_ES: fixedPosB = *transitionB.location; break; default: break; } } objectA.set_position(fixedPosA); objectB.set_position(fixedPosB); // Step 3: Determine the new velocities of the objects. // Calculate the old separating velocity (in the normal direction). double oldSepVelocity = (objectA.velocity() - objectB.velocity()).dot(contact.normal()); // If the contact is either separating or stationary, there's nothing to do. if(oldSepVelocity >= 0) return; // Calculate the new separating velocity (in the normal direction). double newSepVelocity = -m_restitutionCoefficient * oldSepVelocity; // Update the velocities of the objects. double deltaVel = newSepVelocity - oldSepVelocity; Vector3d deltaVelA = deltaVel * fractionA * contact.normal(); Vector3d deltaVelB = deltaVel * fractionB * -contact.normal(); objectA.set_velocity(objectA.velocity() + deltaVelA); objectB.set_velocity(objectB.velocity() + deltaVelB); } void BounceContactResolver::resolve_object_world(const Contact& contact) const { // Step 1: Resolve interpenetration. For object-world contacts, this involves moving the object // back to the transition location, which is stored as point B in the contact structure. PhysicsObject& objectA = contact.objectA(); objectA.set_position(contact.pointB()); // Step 2: Determine the new velocity of the object. // Calculate the old separating velocity (in the normal direction). double oldSepVelocity = objectA.velocity().dot(contact.normal()); // If the contact is either separating or stationary, there's nothing to do. if(oldSepVelocity >= 0) return; // Calculate the new separating velocity (in the normal direction). double newSepVelocity = -m_restitutionCoefficient * oldSepVelocity; // Update the velocity of the object. Vector3d deltaVelA = (newSepVelocity - oldSepVelocity) * contact.normal(); objectA.set_velocity(objectA.velocity() + deltaVelA); } }
[ [ [ 1, 126 ] ] ]
1181901723a5103f53d628cf5558511651f616ba
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/qdbctrls.hpp
0c497ab402cac8c8815b1e133c4ca83be9d2e78a
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
49,683
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'QDBCtrls.pas' rev: 6.00 #ifndef QDBCtrlsHPP #define QDBCtrlsHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <DB.hpp> // Pascal unit #include <QMask.hpp> // Pascal unit #include <QExtCtrls.hpp> // Pascal unit #include <QStdCtrls.hpp> // Pascal unit #include <QMenus.hpp> // Pascal unit #include <QButtons.hpp> // Pascal unit #include <QGraphics.hpp> // Pascal unit #include <QForms.hpp> // Pascal unit #include <QComCtrls.hpp> // Pascal unit #include <QControls.hpp> // Pascal unit #include <QTypes.hpp> // Pascal unit #include <Qt.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <Types.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Variants.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- /* automatically link to qdblogdlg.obj so that the login dialog is automatically shown */ #pragma link "qdblogdlg.obj" /* automatically link to dbrtl and visualdbclx as well */ #ifdef USEPACKAGES #pragma link "dbrtl.bpi" #pragma link "visualdbclx.bpi" #else #pragma link "dbrtl.lib" #pragma link "visualdbclx.lib" #endif namespace Qdbctrls { //-- type declarations ------------------------------------------------------- typedef int HWnd; class DELPHICLASS TFieldDataLink; class PASCALIMPLEMENTATION TFieldDataLink : public Db::TDataLink { typedef Db::TDataLink inherited; private: Db::TField* FField; AnsiString FFieldName; Classes::TComponent* FControl; bool FEditing; bool FModified; Classes::TNotifyEvent FOnDataChange; Classes::TNotifyEvent FOnEditingChange; Classes::TNotifyEvent FOnUpdateData; Classes::TNotifyEvent FOnActiveChange; bool __fastcall GetCanModify(void); HIDESBASE void __fastcall SetEditing(bool Value); void __fastcall SetField(Db::TField* Value); void __fastcall SetFieldName(const AnsiString Value); void __fastcall UpdateField(void); protected: virtual void __fastcall ActiveChanged(void); virtual void __fastcall EditingChanged(void); virtual void __fastcall FocusControl(Db::TFieldRef Field); virtual void __fastcall LayoutChanged(void); virtual void __fastcall RecordChanged(Db::TField* Field); virtual void __fastcall UpdateData(void); public: __fastcall TFieldDataLink(void); HIDESBASE bool __fastcall Edit(void); void __fastcall Modified(void); void __fastcall Reset(void); __property bool CanModify = {read=GetCanModify, nodefault}; __property Classes::TComponent* Control = {read=FControl, write=FControl}; __property bool Editing = {read=FEditing, nodefault}; __property Db::TField* Field = {read=FField}; __property AnsiString FieldName = {read=FFieldName, write=SetFieldName}; __property Classes::TNotifyEvent OnDataChange = {read=FOnDataChange, write=FOnDataChange}; __property Classes::TNotifyEvent OnEditingChange = {read=FOnEditingChange, write=FOnEditingChange}; __property Classes::TNotifyEvent OnUpdateData = {read=FOnUpdateData, write=FOnUpdateData}; __property Classes::TNotifyEvent OnActiveChange = {read=FOnActiveChange, write=FOnActiveChange}; public: #pragma option push -w-inl /* TDataLink.Destroy */ inline __fastcall virtual ~TFieldDataLink(void) { } #pragma option pop }; class DELPHICLASS TDBEdit; class PASCALIMPLEMENTATION TDBEdit : public Qmask::TCustomMaskEdit { typedef Qmask::TCustomMaskEdit inherited; private: TFieldDataLink* FDataLink; bool FTextLocked; bool FDatasetLocked; void __fastcall DataChange(System::TObject* Sender); AnsiString __fastcall GetDataField(); Db::TDataSource* __fastcall GetDataSource(void); Db::TField* __fastcall GetField(void); HIDESBASE bool __fastcall GetReadOnly(void); void __fastcall Restore(void); void __fastcall SetDataField(const AnsiString Value); void __fastcall SetDataSource(Db::TDataSource* Value); HIDESBASE void __fastcall SetReadOnly(bool Value); void __fastcall UpdateData(System::TObject* Sender); protected: virtual void __fastcall Change(void); DYNAMIC void __fastcall DoEnter(void); DYNAMIC void __fastcall DoExit(void); virtual bool __fastcall EditCanModify(void); DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift); DYNAMIC void __fastcall KeyPress(char &Key); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); virtual void __fastcall Reset(void); public: __fastcall virtual TDBEdit(Classes::TComponent* AOwner); __fastcall virtual ~TDBEdit(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property Db::TField* Field = {read=GetField}; __published: __property Anchors = {default=3}; __property AutoSelect = {default=1}; __property AutoSize = {default=1}; __property BorderStyle = {default=1}; __property CharCase = {default=0}; __property Color = {default=-10}; __property Constraints ; __property AnsiString DataField = {read=GetDataField, write=SetDataField}; __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property MaxLength = {default=-1}; __property ParentColor = {default=0}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property bool ReadOnly = {read=GetReadOnly, write=SetReadOnly, default=0}; __property ShowHint = {default=0}; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Visible = {default=1}; __property OnChange ; __property OnClick ; __property OnContextPopup ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyString ; __property OnKeyUp ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBEdit(Qt::QWidgetH* ParentWidget) : Qmask::TCustomMaskEdit(ParentWidget) { } #pragma option pop }; class DELPHICLASS TDBText; class PASCALIMPLEMENTATION TDBText : public Qstdctrls::TCustomLabel { typedef Qstdctrls::TCustomLabel inherited; private: TFieldDataLink* FDataLink; void __fastcall DataChange(System::TObject* Sender); AnsiString __fastcall GetDataField(); Db::TDataSource* __fastcall GetDataSource(void); Db::TField* __fastcall GetField(void); AnsiString __fastcall GetFieldText(); void __fastcall SetDataField(const AnsiString Value); void __fastcall SetDataSource(Db::TDataSource* Value); protected: virtual WideString __fastcall GetLabelText(); virtual void __fastcall InitWidget(void); virtual void __fastcall Loaded(void); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); virtual void __fastcall SetAutoSize(bool Value); public: __fastcall virtual TDBText(Classes::TComponent* AOwner); __fastcall virtual ~TDBText(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property Db::TField* Field = {read=GetField}; __published: __property Align = {default=0}; __property Alignment = {default=0}; __property Anchors = {default=3}; __property AutoSize = {default=0}; __property Color = {default=-10}; __property Constraints ; __property AnsiString DataField = {read=GetDataField, write=SetDataField}; __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property ParentColor = {default=1}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property Transparent = {default=0}; __property ShowHint = {default=0}; __property Visible = {default=1}; __property WordWrap = {default=0}; __property OnClick ; __property OnContextPopup ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBText(Qt::QWidgetH* ParentWidget) : Qstdctrls::TCustomLabel(ParentWidget) { } #pragma option pop }; class DELPHICLASS TDBCheckBox; class PASCALIMPLEMENTATION TDBCheckBox : public Qstdctrls::TCustomCheckBox { typedef Qstdctrls::TCustomCheckBox inherited; private: TFieldDataLink* FDataLink; AnsiString FValueCheck; AnsiString FValueUncheck; bool FUpdating; void __fastcall DataChange(System::TObject* Sender); AnsiString __fastcall GetDataField(); Db::TDataSource* __fastcall GetDataSource(void); Db::TField* __fastcall GetField(void); Qstdctrls::TCheckBoxState __fastcall GetFieldState(void); bool __fastcall GetReadOnly(void); void __fastcall SetDataField(const AnsiString Value); void __fastcall SetDataSource(Db::TDataSource* Value); void __fastcall SetReadOnly(bool Value); void __fastcall SetValueCheck(const AnsiString Value); void __fastcall SetValueUncheck(const AnsiString Value); void __fastcall UpdateData(System::TObject* Sender); bool __fastcall ValueMatch(const AnsiString ValueList, const AnsiString Value); protected: DYNAMIC void __fastcall KeyPress(char &Key); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); DYNAMIC void __fastcall Click(void); DYNAMIC void __fastcall DoExit(void); public: __fastcall virtual TDBCheckBox(Classes::TComponent* AOwner); __fastcall virtual ~TDBCheckBox(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property Checked = {default=0}; __property Db::TField* Field = {read=GetField}; __property State = {default=0}; __published: __property Action ; __property AllowGrayed = {default=0}; __property Anchors = {default=3}; __property Caption ; __property Color = {default=-10}; __property Constraints ; __property AnsiString DataField = {read=GetDataField, write=SetDataField}; __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property ParentColor = {default=1}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property bool ReadOnly = {read=GetReadOnly, write=SetReadOnly, default=0}; __property ShowHint ; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property AnsiString ValueChecked = {read=FValueCheck, write=SetValueCheck}; __property AnsiString ValueUnchecked = {read=FValueUncheck, write=SetValueUncheck}; __property Visible = {default=1}; __property OnClick ; __property OnContextPopup ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyString ; __property OnKeyUp ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBCheckBox(Qt::QWidgetH* ParentWidget) : Qstdctrls::TCustomCheckBox(ParentWidget) { } #pragma option pop }; class DELPHICLASS TDBComboBox; class PASCALIMPLEMENTATION TDBComboBox : public Qstdctrls::TCustomComboBox { typedef Qstdctrls::TCustomComboBox inherited; private: TFieldDataLink* FDataLink; bool FTextLocked; bool FDatasetLocked; void __fastcall DataChange(System::TObject* Sender); AnsiString __fastcall GetComboText(); AnsiString __fastcall GetDataField(); Db::TDataSource* __fastcall GetDataSource(void); Db::TField* __fastcall GetField(void); bool __fastcall GetReadOnly(void); void __fastcall SetComboText(const AnsiString Value); void __fastcall SetDataField(const AnsiString Value); void __fastcall SetDataSource(Db::TDataSource* Value); HIDESBASE void __fastcall SetItems(Classes::TStrings* Value); void __fastcall SetReadOnly(bool Value); void __fastcall UpdateData(System::TObject* Sender); protected: DYNAMIC void __fastcall Change(void); DYNAMIC void __fastcall Click(void); DYNAMIC void __fastcall DoEnter(void); DYNAMIC void __fastcall DoExit(void); DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift); DYNAMIC void __fastcall KeyPress(char &Key); virtual void __fastcall Loaded(void); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); virtual void __fastcall SetStyle(Qstdctrls::TComboBoxStyle Value); virtual void __fastcall SetText(const WideString Value); public: __fastcall virtual TDBComboBox(Classes::TComponent* AOwner); __fastcall virtual ~TDBComboBox(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property Db::TField* Field = {read=GetField}; __property Text ; __published: __property Style = {default=0}; __property Anchors = {default=3}; __property Color = {default=-10}; __property Constraints ; __property AnsiString DataField = {read=GetDataField, write=SetDataField}; __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property DragMode = {default=0}; __property DropDownCount = {default=8}; __property Enabled = {default=1}; __property Font ; __property ItemHeight = {default=16}; __property Items = {write=SetItems}; __property ParentColor = {default=0}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property bool ReadOnly = {read=GetReadOnly, write=SetReadOnly, default=0}; __property ShowHint ; __property Sorted = {default=0}; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Visible = {default=1}; __property OnChange ; __property OnClick ; __property OnContextPopup ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnDrawItem ; __property OnDropDown ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyString ; __property OnKeyUp ; __property OnMeasureItem ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBComboBox(Qt::QWidgetH* ParentWidget) : Qstdctrls::TCustomComboBox(ParentWidget) { } #pragma option pop }; class DELPHICLASS TDBListBox; class PASCALIMPLEMENTATION TDBListBox : public Qstdctrls::TCustomListBox { typedef Qstdctrls::TCustomListBox inherited; private: TFieldDataLink* FDataLink; bool FTextLocked; bool FDatasetLocked; void __fastcall DataChange(System::TObject* Sender); void __fastcall UpdateData(System::TObject* Sender); AnsiString __fastcall GetDataField(); Db::TDataSource* __fastcall GetDataSource(void); Db::TField* __fastcall GetField(void); bool __fastcall GetReadOnly(void); void __fastcall SetDataField(const AnsiString Value); void __fastcall SetDataSource(Db::TDataSource* Value); void __fastcall SetReadOnly(bool Value); HIDESBASE void __fastcall SetItems(Classes::TStrings* Value); protected: virtual void __fastcall Changed(void); DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift); DYNAMIC void __fastcall KeyPress(char &Key); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); DYNAMIC void __fastcall DoExit(void); public: __fastcall virtual TDBListBox(Classes::TComponent* AOwner); __fastcall virtual ~TDBListBox(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property Db::TField* Field = {read=GetField}; __published: __property Align = {default=0}; __property Anchors = {default=3}; __property BorderStyle = {default=6}; __property Color = {default=-10}; __property ColumnLayout = {default=0}; __property Constraints ; __property AnsiString DataField = {read=GetDataField, write=SetDataField}; __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property ItemHeight = {default=16}; __property Items = {write=SetItems}; __property ParentColor = {default=0}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property bool ReadOnly = {read=GetReadOnly, write=SetReadOnly, default=0}; __property RowLayout = {default=2}; __property Rows = {default=1}; __property ShowHint ; __property Style = {default=0}; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Visible = {default=1}; __property OnClick ; __property OnContextPopup ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnDrawItem ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyString ; __property OnKeyUp ; __property OnMeasureItem ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBListBox(Qt::QWidgetH* ParentWidget) : Qstdctrls::TCustomListBox(ParentWidget) { } #pragma option pop }; class DELPHICLASS TDBRadioGroup; class PASCALIMPLEMENTATION TDBRadioGroup : public Qextctrls::TCustomRadioGroup { typedef Qextctrls::TCustomRadioGroup inherited; private: TFieldDataLink* FDataLink; AnsiString FValue; Classes::TStrings* FValues; bool FInSetValue; Classes::TNotifyEvent FOnChange; void __fastcall DataChange(System::TObject* Sender); void __fastcall UpdateData(System::TObject* Sender); AnsiString __fastcall GetDataField(); Db::TDataSource* __fastcall GetDataSource(void); Db::TField* __fastcall GetField(void); bool __fastcall GetReadOnly(void); AnsiString __fastcall GetButtonValue(int Index); void __fastcall SetDataField(const AnsiString Value); void __fastcall SetDataSource(Db::TDataSource* Value); void __fastcall SetReadOnly(bool Value); void __fastcall SetValue(const AnsiString Value); HIDESBASE void __fastcall SetItems(Classes::TStrings* Value); void __fastcall SetValues(Classes::TStrings* Value); protected: virtual bool __fastcall CanModify(void); DYNAMIC void __fastcall Change(void); DYNAMIC void __fastcall Click(void); DYNAMIC void __fastcall DoExit(void); DYNAMIC void __fastcall KeyPress(char &Key); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); __property TFieldDataLink* DataLink = {read=FDataLink}; public: __fastcall virtual TDBRadioGroup(Classes::TComponent* AOwner); __fastcall virtual ~TDBRadioGroup(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property Db::TField* Field = {read=GetField}; __property ItemIndex = {default=-1}; __property AnsiString Value = {read=FValue, write=SetValue}; __published: __property Align = {default=0}; __property Anchors = {default=3}; __property Caption ; __property Color = {default=-10}; __property Columns = {default=1}; __property Constraints ; __property AnsiString DataField = {read=GetDataField, write=SetDataField}; __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property Items = {write=SetItems}; __property ParentColor = {default=1}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property bool ReadOnly = {read=GetReadOnly, write=SetReadOnly, default=0}; __property ShowHint ; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Classes::TStrings* Values = {read=FValues, write=SetValues}; __property Visible = {default=1}; __property Classes::TNotifyEvent OnChange = {read=FOnChange, write=FOnChange}; __property OnClick ; __property OnContextPopup ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBRadioGroup(Qt::QWidgetH* ParentWidget) : Qextctrls::TCustomRadioGroup(ParentWidget) { } #pragma option pop }; class DELPHICLASS TDBMemo; class PASCALIMPLEMENTATION TDBMemo : public Qstdctrls::TCustomMemo { typedef Qstdctrls::TCustomMemo inherited; private: TFieldDataLink* FDataLink; bool FAutoDisplay; bool FFocused; bool FMemoLoaded; bool FTextLocked; bool FDatasetLocked; void __fastcall DataChange(System::TObject* Sender); void __fastcall EditingChange(System::TObject* Sender); AnsiString __fastcall GetDataField(); Db::TDataSource* __fastcall GetDataSource(void); Db::TField* __fastcall GetField(void); HIDESBASE bool __fastcall GetReadOnly(void); void __fastcall SetDataField(const AnsiString Value); void __fastcall SetDataSource(Db::TDataSource* Value); void __fastcall SetAutoDisplay(bool Value); void __fastcall SetFocused(bool Value); HIDESBASE void __fastcall SetReadOnly(const bool Value); void __fastcall UpdateData(System::TObject* Sender); protected: virtual void __fastcall Change(void); DYNAMIC void __fastcall DblClick(void); DYNAMIC void __fastcall DoEnter(void); DYNAMIC void __fastcall DoExit(void); DYNAMIC void __fastcall KeyPress(char &Key); virtual void __fastcall Loaded(void); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); public: __fastcall virtual TDBMemo(Classes::TComponent* AOwner); __fastcall virtual ~TDBMemo(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); virtual void __fastcall LoadMemo(void); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property Db::TField* Field = {read=GetField}; __published: __property Align = {default=0}; __property Alignment = {default=0}; __property Anchors = {default=3}; __property bool AutoDisplay = {read=FAutoDisplay, write=SetAutoDisplay, default=1}; __property BorderStyle = {default=6}; __property Color = {default=-10}; __property Constraints ; __property AnsiString DataField = {read=GetDataField, write=SetDataField}; __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property MaxLength = {default=-1}; __property ParentColor = {default=0}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property bool ReadOnly = {read=GetReadOnly, write=SetReadOnly, default=0}; __property ScrollBars = {default=0}; __property ShowHint = {default=0}; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Visible = {default=1}; __property WantTabs = {default=0}; __property WordWrap = {default=1}; __property WrapBreak = {default=0}; __property OnChange ; __property OnClick ; __property OnContextPopup ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyString ; __property OnKeyUp ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBMemo(Qt::QWidgetH* ParentWidget) : Qstdctrls::TCustomMemo(ParentWidget) { } #pragma option pop }; class DELPHICLASS TDBImage; class PASCALIMPLEMENTATION TDBImage : public Qcontrols::TCustomControl { typedef Qcontrols::TCustomControl inherited; private: TFieldDataLink* FDataLink; Qgraphics::TPicture* FPicture; Qcontrols::TBorderStyle FBorderStyle; bool FAutoDisplay; bool FStretch; bool FCenter; bool FPictureLoaded; void __fastcall DataChange(System::TObject* Sender); int __fastcall GetBorderSize(void); AnsiString __fastcall GetDataField(); Db::TDataSource* __fastcall GetDataSource(void); Db::TField* __fastcall GetField(void); bool __fastcall GetReadOnly(void); void __fastcall PictureChanged(System::TObject* Sender); void __fastcall SetAutoDisplay(bool Value); void __fastcall SetBorderStyle(Qcontrols::TControlBorderStyle Value); void __fastcall SetCenter(bool Value); void __fastcall SetDataField(const AnsiString Value); void __fastcall SetDataSource(Db::TDataSource* Value); void __fastcall SetPicture(Qgraphics::TPicture* Value); void __fastcall SetReadOnly(bool Value); void __fastcall SetStretch(bool Value); void __fastcall UpdateData(System::TObject* Sender); protected: DYNAMIC void __fastcall BoundsChanged(void); DYNAMIC void __fastcall DoEnter(void); DYNAMIC void __fastcall DoExit(void); DYNAMIC void __fastcall DblClick(void); virtual Types::TRect __fastcall GetClientRect(); DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift); DYNAMIC void __fastcall KeyPress(char &Key); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); virtual void __fastcall Paint(void); DYNAMIC void __fastcall TextChanged(void); __property int BorderSize = {read=GetBorderSize, nodefault}; public: __fastcall virtual TDBImage(Classes::TComponent* AOwner); __fastcall virtual ~TDBImage(void); void __fastcall CopyToClipboard(void); void __fastcall CutToClipboard(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); void __fastcall LoadPicture(void); void __fastcall PasteFromClipboard(void); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property Db::TField* Field = {read=GetField}; __property Qgraphics::TPicture* Picture = {read=FPicture, write=SetPicture}; __published: __property Align = {default=0}; __property Anchors = {default=3}; __property bool AutoDisplay = {read=FAutoDisplay, write=SetAutoDisplay, default=1}; __property Qcontrols::TControlBorderStyle BorderStyle = {read=FBorderStyle, write=SetBorderStyle, default=1}; __property bool Center = {read=FCenter, write=SetCenter, default=1}; __property Color = {default=-10}; __property Constraints ; __property AnsiString DataField = {read=GetDataField, write=SetDataField}; __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property ParentColor = {default=0}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property bool ReadOnly = {read=GetReadOnly, write=SetReadOnly, default=0}; __property ShowHint ; __property bool Stretch = {read=FStretch, write=SetStretch, default=0}; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Visible = {default=1}; __property OnClick ; __property OnContextPopup ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyString ; __property OnKeyUp ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBImage(Qt::QWidgetH* ParentWidget) : Qcontrols::TCustomControl(ParentWidget) { } #pragma option pop }; #pragma option push -b- enum TNavGlyph { ngEnabled, ngDisabled }; #pragma option pop #pragma option push -b- enum TNavigateBtn { nbFirst, nbPrior, nbNext, nbLast, nbInsert, nbDelete, nbEdit, nbPost, nbCancel, nbRefresh }; #pragma option pop typedef Set<TNavigateBtn, nbFirst, nbRefresh> TButtonSet; #pragma option push -b- enum QDBCtrls__01 { nsAllowTimer, nsFocusRect }; #pragma option pop typedef Set<QDBCtrls__01, nsAllowTimer, nsFocusRect> TNavButtonStyle; typedef void __fastcall (__closure *ENavClick)(System::TObject* Sender, TNavigateBtn Button); class DELPHICLASS TDBNavigator; class DELPHICLASS TNavDataLink; class PASCALIMPLEMENTATION TNavDataLink : public Db::TDataLink { typedef Db::TDataLink inherited; private: TDBNavigator* FNavigator; protected: virtual void __fastcall EditingChanged(void); virtual void __fastcall DataSetChanged(void); virtual void __fastcall ActiveChanged(void); public: __fastcall TNavDataLink(TDBNavigator* ANav); __fastcall virtual ~TNavDataLink(void); }; class DELPHICLASS TNavButton; class PASCALIMPLEMENTATION TDBNavigator : public Qextctrls::TCustomPanel { typedef Qextctrls::TCustomPanel inherited; private: TNavDataLink* FDataLink; TButtonSet FVisibleButtons; Classes::TStrings* FHints; Classes::TStrings* FDefHints; int ButtonWidth; #pragma pack(push, 1) Types::TPoint MinBtnSize; #pragma pack(pop) ENavClick FOnNavClick; ENavClick FBeforeAction; TNavigateBtn FocusedButton; bool FConfirmDelete; bool FFlat; void __fastcall BtnMouseDown(System::TObject* Sender, Qcontrols::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); void __fastcall ClickHandler(System::TObject* Sender); HIDESBASE MESSAGE void __fastcall CMKeyDown(Qcontrols::TCMKeyDown &Msg); Db::TDataSource* __fastcall GetDataSource(void); Classes::TStrings* __fastcall GetHints(void); void __fastcall HintsChanged(System::TObject* Sender); void __fastcall InitButtons(void); void __fastcall InitHints(void); void __fastcall SetDataSource(Db::TDataSource* Value); void __fastcall SetFlat(bool Value); void __fastcall SetHints(Classes::TStrings* Value); void __fastcall SetSize(int &W, int &H); HIDESBASE void __fastcall SetVisible(TButtonSet Value); protected: TNavButton* Buttons[10]; DYNAMIC void __fastcall BoundsChanged(void); virtual void __fastcall ChangeBounds(int ALeft, int ATop, int AWidth, int AHeight); void __fastcall DataChanged(void); DYNAMIC void __fastcall DoEnter(void); DYNAMIC void __fastcall DoExit(void); void __fastcall EditingChanged(void); DYNAMIC void __fastcall EnabledChanged(void); void __fastcall ActiveChanged(void); virtual void __fastcall Loaded(void); DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); DYNAMIC void __fastcall GetChildren(Classes::TGetChildProc Proc, Classes::TComponent* Root); void __fastcall CalcMinSize(int &W, int &H); public: __fastcall virtual TDBNavigator(Classes::TComponent* AOwner); __fastcall virtual ~TDBNavigator(void); virtual void __fastcall SetBounds(int ALeft, int ATop, int AWidth, int AHeight); virtual void __fastcall BtnClick(TNavigateBtn Index); __published: __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property TButtonSet VisibleButtons = {read=FVisibleButtons, write=SetVisible, default=1023}; __property Align = {default=0}; __property Anchors = {default=3}; __property Constraints ; __property DragMode = {default=0}; __property Enabled = {default=1}; __property bool Flat = {read=FFlat, write=SetFlat, default=0}; __property Classes::TStrings* Hints = {read=GetHints, write=SetHints}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property bool ConfirmDelete = {read=FConfirmDelete, write=FConfirmDelete, default=1}; __property ShowHint ; __property TabOrder = {default=-1}; __property TabStop = {default=0}; __property Visible = {default=1}; __property ENavClick BeforeAction = {read=FBeforeAction, write=FBeforeAction}; __property ENavClick OnClick = {read=FOnNavClick, write=FOnNavClick}; __property OnContextPopup ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnResize ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBNavigator(Qt::QWidgetH* ParentWidget) : Qextctrls::TCustomPanel(ParentWidget) { } #pragma option pop }; class PASCALIMPLEMENTATION TNavButton : public Qbuttons::TSpeedButton { typedef Qbuttons::TSpeedButton inherited; private: TNavigateBtn FIndex; TNavButtonStyle FNavStyle; Qextctrls::TTimer* FRepeatTimer; void __fastcall TimerExpired(System::TObject* Sender); protected: virtual void __fastcall Paint(void); DYNAMIC void __fastcall MouseDown(Qcontrols::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseUp(Qcontrols::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); public: __fastcall virtual ~TNavButton(void); __property TNavButtonStyle NavStyle = {read=FNavStyle, write=FNavStyle, nodefault}; __property TNavigateBtn Index = {read=FIndex, write=FIndex, nodefault}; public: #pragma option push -w-inl /* TSpeedButton.Create */ inline __fastcall virtual TNavButton(Classes::TComponent* AOwner) : Qbuttons::TSpeedButton(AOwner) { } #pragma option pop }; class DELPHICLASS TDataSourceLink; class DELPHICLASS TDBLookupControl; class DELPHICLASS TListSourceLink; class PASCALIMPLEMENTATION TListSourceLink : public Db::TDataLink { typedef Db::TDataLink inherited; private: TDBLookupControl* FDBLookupControl; int FLock; protected: virtual void __fastcall ActiveChanged(void); virtual void __fastcall DataSetChanged(void); virtual void __fastcall LayoutChanged(void); public: __fastcall TListSourceLink(void); public: #pragma option push -w-inl /* TDataLink.Destroy */ inline __fastcall virtual ~TListSourceLink(void) { } #pragma option pop }; class PASCALIMPLEMENTATION TDBLookupControl : public Qcontrols::TCustomControl { typedef Qcontrols::TCustomControl inherited; private: Db::TDataSource* FLookupSource; TDataSourceLink* FDataLink; TListSourceLink* FListLink; AnsiString FDataFieldName; AnsiString FKeyFieldName; AnsiString FListFieldName; int FListFieldIndex; Db::TField* FDataField; Db::TField* FMasterField; Db::TField* FKeyField; Db::TField* FListField; Classes::TList* FListFields; Variant FKeyValue; AnsiString FSearchText; bool FLookupMode; bool FListActive; bool FHasFocus; Qextctrls::TTimer* FTimer; void __fastcall CheckNotCircular(void); void __fastcall CheckNotLookup(void); HIDESBASE MESSAGE void __fastcall CMKeyDown(Qcontrols::TCMKeyDown &Msg); void __fastcall DataLinkRecordChanged(Db::TField* Field); Db::TDataSource* __fastcall GetDataSource(void); AnsiString __fastcall GetKeyFieldName(); Db::TDataSource* __fastcall GetListSource(void); bool __fastcall GetReadOnly(void); void __fastcall SetDataFieldName(const AnsiString Value); void __fastcall SetDataSource(Db::TDataSource* Value); void __fastcall SetKeyFieldName(const AnsiString Value); void __fastcall SetKeyValue(const Variant &Value); void __fastcall SetListFieldName(const AnsiString Value); void __fastcall SetListSource(Db::TDataSource* Value); void __fastcall SetLookupMode(bool Value); void __fastcall SetReadOnly(bool Value); void __fastcall TimerEvent(System::TObject* Sender); protected: virtual bool __fastcall CanModify(void); DYNAMIC void __fastcall DoEnter(void); DYNAMIC void __fastcall DoExit(void); virtual int __fastcall GetTextHeight(void); virtual void __fastcall KeyValueChanged(void); virtual void __fastcall ListLinkDataChanged(void); virtual bool __fastcall LocateKey(void); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); virtual void __fastcall ProcessSearchKey(char Key); virtual void __fastcall SelectKeyValue(const Variant &Value); virtual void __fastcall UpdateDataFields(void); virtual void __fastcall UpdateListFields(void); __property Color = {default=16777215}; __property AnsiString DataField = {read=FDataFieldName, write=SetDataFieldName}; __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property AnsiString KeyField = {read=GetKeyFieldName, write=SetKeyFieldName}; __property Variant KeyValue = {read=FKeyValue, write=SetKeyValue}; __property bool ListActive = {read=FListActive, nodefault}; __property AnsiString ListField = {read=FListFieldName, write=SetListFieldName}; __property int ListFieldIndex = {read=FListFieldIndex, write=FListFieldIndex, default=0}; __property Classes::TList* ListFields = {read=FListFields}; __property TListSourceLink* ListLink = {read=FListLink}; __property Db::TDataSource* ListSource = {read=GetListSource, write=SetListSource}; __property ParentColor = {default=0}; __property bool ReadOnly = {read=GetReadOnly, write=SetReadOnly, default=0}; __property AnsiString SearchText = {read=FSearchText, write=FSearchText}; __property TabStop = {default=1}; public: __fastcall virtual TDBLookupControl(Classes::TComponent* AOwner); __fastcall virtual ~TDBLookupControl(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property Db::TField* Field = {read=FDataField}; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBLookupControl(Qt::QWidgetH* ParentWidget) : Qcontrols::TCustomControl(ParentWidget) { } #pragma option pop }; class PASCALIMPLEMENTATION TDataSourceLink : public Db::TDataLink { typedef Db::TDataLink inherited; private: TDBLookupControl* FDBLookupControl; protected: virtual void __fastcall FocusControl(Db::TFieldRef Field); virtual void __fastcall ActiveChanged(void); virtual void __fastcall LayoutChanged(void); virtual void __fastcall RecordChanged(Db::TField* Field); public: __fastcall TDataSourceLink(void); public: #pragma option push -w-inl /* TDataLink.Destroy */ inline __fastcall virtual ~TDataSourceLink(void) { } #pragma option pop }; class DELPHICLASS TLookupListBoxScrollBar; class DELPHICLASS TDBLookupListBox; class PASCALIMPLEMENTATION TDBLookupListBox : public TDBLookupControl { typedef TDBLookupControl inherited; private: Qcontrols::TBorderStyle FBorderStyle; bool FKeySelected; bool FLockPosition; int FMousePos; bool FPopup; int FRecordCount; int FRecordIndex; int FRowCount; TLookupListBoxScrollBar* FScrollBar; AnsiString FSelectedItem; bool FTracking; Qextctrls::TTimer* FTimer; void __fastcall CalcScrollBarLayout(void); int __fastcall GetKeyIndex(void); void __fastcall SelectCurrent(void); void __fastcall SelectItemAt(int X, int Y); void __fastcall SetBorderStyle(Qcontrols::TControlBorderStyle Value); void __fastcall SetRowCount(int Value); void __fastcall StopTracking(void); void __fastcall TimerScroll(void); void __fastcall UpdateScrollBar(void); void __fastcall ScrollEvent(System::TObject* Sender, Qstdctrls::TScrollCode ScrollCode, int &ScrollPos); HIDESBASE void __fastcall TimerEvent(System::TObject* Sender); protected: DYNAMIC void __fastcall BoundsChanged(void); DYNAMIC void __fastcall DoExit(void); virtual int __fastcall GetBorderSize(void); DYNAMIC void __fastcall FontChanged(void); DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift); DYNAMIC void __fastcall KeyPress(char &Key); virtual void __fastcall KeyValueChanged(void); virtual void __fastcall ListLinkDataChanged(void); DYNAMIC void __fastcall MouseDown(Qcontrols::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseMove(Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseUp(Qcontrols::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); virtual void __fastcall Paint(void); virtual void __fastcall UpdateListFields(void); public: __fastcall virtual TDBLookupListBox(Classes::TComponent* AOwner); __fastcall virtual ~TDBLookupListBox(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property KeyValue ; __property AnsiString SelectedItem = {read=FSelectedItem}; virtual void __fastcall SetBounds(int ALeft, int ATop, int AWidth, int AHeight); __published: __property Align = {default=0}; __property Anchors = {default=3}; __property Qcontrols::TControlBorderStyle BorderStyle = {read=FBorderStyle, write=SetBorderStyle, default=1}; __property Color = {default=16777215}; __property Constraints ; __property DataField ; __property DataSource ; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property KeyField ; __property ListField ; __property ListFieldIndex = {default=0}; __property ListSource ; __property ParentColor = {default=0}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property ReadOnly = {default=0}; __property int RowCount = {read=FRowCount, write=SetRowCount, stored=false, nodefault}; __property ShowHint ; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Visible = {default=1}; __property OnClick ; __property OnContextPopup ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyString ; __property OnKeyUp ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBLookupListBox(Qt::QWidgetH* ParentWidget) : TDBLookupControl(ParentWidget) { } #pragma option pop }; class PASCALIMPLEMENTATION TLookupListBoxScrollBar : public Qstdctrls::TScrollBar { typedef Qstdctrls::TScrollBar inherited; private: TDBLookupListBox* FDBLookupListBox; bool __fastcall GetVisible(void); HIDESBASE void __fastcall SetVisible(bool Value); protected: virtual void __fastcall InitWidget(void); DYNAMIC void __fastcall WidgetDestroyed(void); public: __fastcall virtual TLookupListBoxScrollBar(Classes::TComponent* AOwner); DYNAMIC bool __fastcall CanFocus(void); __property bool Visible = {read=GetVisible, write=SetVisible, nodefault}; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TLookupListBoxScrollBar(Qt::QWidgetH* ParentWidget) : Qstdctrls::TScrollBar(ParentWidget) { } #pragma option pop #pragma option push -w-inl /* TWidgetControl.Destroy */ inline __fastcall virtual ~TLookupListBoxScrollBar(void) { } #pragma option pop }; class DELPHICLASS TPopupDataList; class PASCALIMPLEMENTATION TPopupDataList : public TDBLookupListBox { typedef TDBLookupListBox inherited; protected: virtual void __fastcall InitWidget(void); virtual int __fastcall WidgetFlags(void); public: __fastcall TPopupDataList(Qt::QWidgetH* ParentWidget); public: #pragma option push -w-inl /* TDBLookupListBox.Create */ inline __fastcall virtual TPopupDataList(Classes::TComponent* AOwner) : TDBLookupListBox(AOwner) { } #pragma option pop #pragma option push -w-inl /* TDBLookupListBox.Destroy */ inline __fastcall virtual ~TPopupDataList(void) { } #pragma option pop }; #pragma option push -b- enum TDropDownAlign { daLeft, daRight, daCenter }; #pragma option pop class DELPHICLASS TDBLookupComboBox; class PASCALIMPLEMENTATION TDBLookupComboBox : public TDBLookupControl { typedef TDBLookupControl inherited; private: TPopupDataList* FDataList; int FButtonWidth; AnsiString FText; int FDropDownRows; int FDropDownWidth; TDropDownAlign FDropDownAlign; bool FListVisible; bool FPressed; bool FTracking; Classes::TAlignment FAlignment; bool FLookupMode; Classes::TNotifyEvent FOnDropDown; Classes::TNotifyEvent FOnCloseUp; void __fastcall ListKeypress(System::TObject* Sender, char &Key); void __fastcall ListMouseMove(System::TObject* Sender, Classes::TShiftState Shift, int X, int Y); void __fastcall ListMouseUp(System::TObject* Sender, Qcontrols::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); void __fastcall TrackButton(int X, int Y); protected: DYNAMIC void __fastcall DoExit(void); DYNAMIC void __fastcall FontChanged(void); virtual void __fastcall Paint(void); DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift); virtual void __fastcall KeyValueChanged(void); DYNAMIC void __fastcall MouseDown(Qcontrols::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseUp(Qcontrols::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); virtual void __fastcall UpdateListFields(void); public: __fastcall virtual TDBLookupComboBox(Classes::TComponent* AOwner); __fastcall virtual ~TDBLookupComboBox(void); virtual void __fastcall CloseUp(bool Accept); virtual void __fastcall DropDown(void); DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action); virtual void __fastcall SetBounds(int ALeft, int ATop, int AWidth, int AHeight); DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action); __property KeyValue ; __property bool ListVisible = {read=FListVisible, nodefault}; __property AnsiString Text = {read=FText}; __published: __property Anchors = {default=3}; __property Color = {default=16777215}; __property Constraints ; __property DataField ; __property DataSource ; __property DragMode = {default=0}; __property TDropDownAlign DropDownAlign = {read=FDropDownAlign, write=FDropDownAlign, default=0}; __property int DropDownRows = {read=FDropDownRows, write=FDropDownRows, default=7}; __property int DropDownWidth = {read=FDropDownWidth, write=FDropDownWidth, default=0}; __property Enabled = {default=1}; __property Font ; __property KeyField ; __property ListField ; __property ListFieldIndex = {default=0}; __property ListSource ; __property ParentColor = {default=0}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property ReadOnly = {default=0}; __property ShowHint ; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Visible = {default=1}; __property OnClick ; __property Classes::TNotifyEvent OnCloseUp = {read=FOnCloseUp, write=FOnCloseUp}; __property OnContextPopup ; __property OnDragDrop ; __property OnDragOver ; __property Classes::TNotifyEvent OnDropDown = {read=FOnDropDown, write=FOnDropDown}; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyString ; __property OnKeyUp ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; public: #pragma option push -w-inl /* TWidgetControl.CreateParented */ inline __fastcall TDBLookupComboBox(Qt::QWidgetH* ParentWidget) : TDBLookupControl(ParentWidget) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- static const Word InitRepeatPause = 0x190; static const Shortint RepeatPause = 0x64; static const Shortint SpaceSize = 0x5; extern PACKAGE bool __fastcall OkToChangeFieldAlignment(Db::TField* AField, Classes::TAlignment Alignment); } /* namespace Qdbctrls */ using namespace Qdbctrls; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // QDBCtrls
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 1351 ] ] ]
3af5665256ce9b3268969a7cf19b04f6308aa13d
50f94444677eb6363f2965bc2a29c09f8da7e20d
/Src/EmptyProject/SpriteManager.h
edde188a51605e906f8bb0d4934a5fc097cb98f4
[]
no_license
gasbank/poolg
efd426db847150536eaa176d17dcddcf35e74e5d
e73221494c4a9fd29c3d75fb823c6fb1983d30e5
refs/heads/master
2020-04-10T11:56:52.033568
2010-11-04T19:31:00
2010-11-04T19:31:00
1,051,621
1
0
null
null
null
null
UTF-8
C++
false
false
1,376
h
#pragma once class VideoMan; class Sprite; typedef std::map<std::string, Sprite*> SpriteMap; /*! * @brief Manager for Sprite class instances */ class SpriteManager : public Singleton<SpriteManager> { public: SpriteManager(); ~SpriteManager(void); void frameRender(); void frameRenderSpecificSprite( const char* spriteName ); Sprite* registerSprite( const char* spriteName, const char* spriteFileName ); Sprite* getSprite( const char* spriteName ) const; ID3DXSprite* getSpriteRenerer() const { return m_d3dxSprite; } HRESULT onCreateDevice( IDirect3DDevice9* pd3dDevice); HRESULT onResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext); void onLostDevice(); void onDestroyDevice(); private: void init(); void release(); IDirect3DDevice9* m_dev; /* Sprite* m_d3dxSprite; // Screen space sprite Sprite* m_d3dxObjectSprite; // Object space sprite */ ID3DXSprite* m_d3dxSprite; // Screen space sprite ID3DXSprite* m_d3dxObjectSprite; // Object space sprite SpriteMap m_spriteMap; // Automatically rendered set of Sprites. Rendering is done at the last part of frameRender. ArnMatrix m_viewMat; ArnMatrix m_projMat; }; inline SpriteManager& GetSpriteManager() { return SpriteManager::getSingleton(); }
[ [ [ 1, 50 ] ] ]
7ffbbe0bee1bfb5bd0103a9897025cbf0a17c85c
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
/Code/controllers/RecollectionBenchmark/robotapi/real/RealCamera.h
1520ea7eee80ae225d72cf570bc5cee8894e0ddb
[]
no_license
dh-04/tpf-robotica
5efbac38d59fda0271ac4639ea7b3b4129c28d82
10a7f4113d5a38dc0568996edebba91f672786e9
refs/heads/master
2022-12-10T18:19:22.428435
2010-11-05T02:42:29
2010-11-05T02:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
668
h
#ifndef robotapi_real_RealCamera_h #define robotapi_real_RealCamera_h #include <cv.h> #include <highgui.h> #include <robotapi/ICamera.h> #include <robotapi/real/RealDevice.h> namespace robotapi { namespace real { class RealCamera : public robotapi::ICamera, public robotapi::real::RealDevice { public: RealCamera(int cameraID, std::string name); void enable(int ms); void disable(); IImage & getImage(); int saveImage(std::string filename, int quality); private: CvCapture* capture; IImage * iim; }; } /* End of namespace robotapi::real */ } /* End of namespace robotapi */ #endif // robotapi_real_RealCamera_h
[ "guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a", "nuldiego@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a" ]
[ [ [ 1, 3 ], [ 6, 22 ], [ 26, 31 ] ], [ [ 4, 5 ], [ 23, 25 ] ] ]
223d2eb028bedce91d74b7403808730e513b262b
c04ce4f22fc46c4d44fc425275403592bc6f067a
/wolf/src/game/render/rPlayer.cpp
f123bc827b0e6513ebda73ae1a2263a0c066ef96
[]
no_license
allenh1/wolfenstein-reloaded
0161953173f053cc1ee4e03555def208ea98a34b
4db98d1a9e5bf51f88c58d9acae6d7f6850baf1d
refs/heads/master
2020-04-10T03:30:04.121502
2010-07-09T17:14:50
2010-07-09T17:14:50
32,124,233
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,610
cpp
/* ************************************************************************** Wolfenstein Reloaded Developed by Morgan Jones <[email protected]> File Description: Player rendering code ************************************************************************** Copyright © 2010 Morgan Jones This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** */ #include "rPlayer.h" rPlayer::rPlayer() { _upA = _viewA = 0; } void rPlayer::setPosition(rPoint position) { _position = position; } void rPlayer::setAngles(float up, float view) { while( up >= 360.0 ) up -= 360.0; while( view >= 360.0 ) view -= 360.0; while( up < 0.0 ) up += 360.0; while( view < 0.0 ) view += 360.0; _upA = up; _viewA = view; } void rPlayer::updateCamera() { _up.setCoords ( _position.xPos() + cosf( _upA * M_PI/180 ) * 180/M_PI, _position.yPos() + sinf( _upA * M_PI/180 ) * 180/M_PI, _position.zPos() ); _view.setCoords( _position.xPos() + cosf( _viewA * M_PI/180 ) * 180/M_PI, _position.yPos(), _position.zPos() + sinf( _viewA * M_PI/180 ) * 180/M_PI ); gluLookAt ( _position.xPos(), _position.yPos(), _position.zPos(), 0, 1, 0, //_view.xPos(), _view.yPos(), _view.zPos(), // _up.xPos(), _up.yPos(), _up.zPos() 0, 1, 0 ); } void rPlayerManager::renderAllViewports() { for( tIDList<rPlayer*>::iterator it = list()->begin(); it != list()->end(); it++ ) (*it)->updateCamera(); } void rPlayerManager::addPlayer(rPlayer * player) { pushID( player ); } void rPlayerManager::removePlayer(rPlayer * player) { deleteID( player ); }
[ "maclover100@14159fd0-a646-01e2-d422-a234b5f98ae5" ]
[ [ [ 1, 86 ] ] ]
04dc6c65eaa6e29d03389e9b82c26557dc99cf2b
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/terralib/kernel/TeIntersector.h
cd2df837a73c5af2459e42533f704fca6fc04066
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
11,403
h
/************************************************************************************ TerraLib - a library for developing GIS applications. Copyright © 2001-2007 INPE and Tecgraf/PUC-Rio. This code is part of the TerraLib library. 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. You should have received a copy of the GNU Lesser General Public License along with this library. The authors reassure the license terms regarding the warranties. They specifically disclaim any warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The library provided hereunder is on an "as is" basis, and the authors have no obligation to provide maintenance, support, updates, enhancements, or modifications. In no event shall INPE and Tecgraf / PUC-Rio be held liable to any party for direct, indirect, special, incidental, or consequential damages arising out of the use of this library and its documentation. *************************************************************************************/ /*! \file TeIntersector.h \brief This file contains structures and definitions for line intersection algorithms. \note These data structures and algorithms MUST BE USED ONLY BY TerraLib kernel and should NOT be used by anyone because THIS IS FOR INTERNAL USE ONLY. \author Gilberto Ribeiro de Queiroz <[email protected]> */ #ifndef __TERRALIB_INTERNAL_INTERSECTOR2_H #define __TERRALIB_INTERNAL_INTERSECTOR2_H //TerraLib's include #include "TeCoord2D.h" #include "TeRTree.h" //STL's include #include <vector> using namespace std; /* * WARNING: These data structures and algorithms MUST BE USED ONLY BY TerraLib kernel and should NOT be used by anyone because * the support and interfaces can be changed in future. THIS IS FOR INTERNAL USE ONLY. */ /*! \brief Contains structures and definitions needed by line intersection algorithms (FOR INTERNAL USE ONLY). */ namespace TeINTERSECTOR2 { //! An epsilon value used to compare two real numbers #define EPSILON_COMPARE 1.0e-15 /** @defgroup IntersectionAlgorithms Intersection Algorithms * Intersection Algorithms and data structures, used internally. * @{ */ //! This struct is used to represent a point intersection between two segments on boundary of a TePolygon or TeLine2D. struct TL_DLL TeBoundaryIP { vector<TeCoord2D> coords_; //!< Points of intersection ocurried along these two segments (red and blue). unsigned int redSegNum_; //!< Red segment number. unsigned int redPartNum_; //!< Line number in a polygon that a red segment belongs. unsigned int redPolNum_; //!< Polygon number in a vector of polygons that a segment belongs. unsigned int blueSegNum_; //!< Blue segment number. unsigned int bluePartNum_; //!< Line number in a polygon that a blue segment belongs. unsigned int bluePolNum_; //!< Polygon number in a vector of polygons that a segment belongs. }; //! This is the type of intersection point list. typedef vector<TeBoundaryIP> TeVectorBoundaryIP; //! This struct represents an index to the right place of a segment in a TeLineSet, TeLine2D, TePolygon or TePolygonSet. struct TL_DLL TeSegIdInPolygonSet { unsigned int polId_; //!< The polygon id, when used in a polygonset. unsigned int lineId_; //!< The line id, when used in a lineset or in a polygon. unsigned int segId_; //!< The segment id into a specified line. }; //! This pair is used to index two segments that intersects. typedef pair<TeSegIdInPolygonSet, TeSegIdInPolygonSet> TePairSegIdInPolygonSet; //! This is the type used to index the segments in the boundary of a TeLine2D, TeLineSet, TePolygon or TePolygonSet. typedef TeSAM::TeRTree<TeSegIdInPolygonSet, 8> TeSegmentRTree; /** \brief Tells if three points makes a right turn, a left turn or are collinear. \param c1 The first coordinate. \param c2 The second coordinate. \param c3 The coordinate to test the relative position. \param between Tells if c3 is between c1 and c2. \return The orientation: TeCLOCKWISE, TeCOUNTERCLOCKWISE or TeNOTURN. */ TL_DLL short TeCCW(const TeCoord2D& c1, const TeCoord2D& c2, const TeCoord2D& c3, bool& between); /** \brief Returns the intersection point of the segments. \param a The first coordinate of the first segment. \param b The second coordinate of the first segment. \param c The first coordinate of the second segment. \param d The second coordinate of the second segment. \param ips The intersection coordinates (0, 1 or 2). \param intersectionType An intersection may be proper or improper. \return Returns true if there is an intersection between segments defined by end coordinates. */ TL_DLL bool TeIntersection(const TeCoord2D& a, const TeCoord2D& b, const TeCoord2D& c, const TeCoord2D& d, TeBoundaryIP& ips, TeSegmentIntersectionType& intersectionType); /** \brief Tells if two segments intersects. \param a The first coordinate of the first segment. \param b The second coordinate of the first segment. \param c The first coordinate of the second segment. \param d The second coordinate of the second segment. \param intersectionType An intersection may be proper or improper. \return Returns true if there is an intersection between segments defined by end coordinates. */ TL_DLL bool TeIntersects(const TeCoord2D& a, const TeCoord2D& b, const TeCoord2D& c, const TeCoord2D& d, TeSegmentIntersectionType& intersectionType); /** \brief Verifies if there is an intersection between two given polygonsets. \param redPols The first polygonset to test. \param bluePols The second polygonset to test. \param report A list with the intersection points. \return Returns true if there is an intersection between segments of the polygons. \note WARNING: this is deprecated and will be replaced by another function in near future. This is a lazy algorithm. It can be used, for example, in intersections between a box and a line. It is O(n*m) - where n and m are the numbers of segments in the first and second polygonsets. */ TL_DLL bool TeSafeIntersections(const TePolygonSet& redPols, const TePolygonSet& bluePols, TeVectorBoundaryIP& report); /** \brief Verifies if there is an intersection between two given lines. \param redLine The first line to test. \param blueLine The second line to test. \param report A list with the intersection points. \param redObjId Red line object id. \param blueObjId Blue line object id. \return Returns true if there is an intersection between segments of the lines. \note WARNING: this is deprecated and will be replaced by another function in near future. This is a lazy algorithm. It can be used, for example, in intersections between a box and a line. It is O(n*m) - where n and m are the numbers of segments in the first and second lines. */ TL_DLL bool TeSafeIntersections(const TeLine2D& redLine, const TeLine2D& blueLine, TeVectorBoundaryIP& report, const unsigned int& redObjId = 0, const unsigned int& blueObjId = 0); /** \brief Returns true if the lines intersects. \param redLine The line to test. \param blueLine The line to test. \return Returns true if there is an intersection between segments of the lines. \note WARNING: this is deprecated and will be replaced by another function in near future. */ TL_DLL bool TeIntersects(const TeLine2D& redLine, const TeLine2D& blueLine); /** \brief Reports intersections between segments of polygons in the polygonset list. \param polygons A list of polygons to test self intersections. \param tree The tree with all index segments, it WILL BE filled inside this method. \param report A report list of intersection points. \return Returns true if there is an intersection. \note This function will not returns intersections between segments of the same polygon. It will only report intersection between different polygons. The index tree MUST BE EMPTY, othewise, the result is undefined. The result may have duplicated points because intersections are reported twice: this will turn fragmentation easier. */ TL_DLL bool TeIntersection(const TePolygonSet& polygons, TeSegmentRTree& tree, TeVectorBoundaryIP& report); /** \brief Reports intersections between segments of two diferent polygonsets. \param redPolygons A list of polygons without self intersections. \param redTree A tree with all red segment already indexed or not, if it is empty, so, it will be filled inside this method. \param bluePolygons A list of polygons without self intersections. \param report A report list of intersection points. \return Returns true if there is an intersection between a red segment and a blue segment. \note This function will not returns intersections between segments of the same polygon. It will only report intersection between different polygons. The result may have duplicated points because intersections are reported twice: this will turn fragmentation easier. */ TL_DLL bool TeIntersection(const TePolygonSet& redPolygons, TeSegmentRTree& redTree, const TePolygonSet& bluePolygons, TeINTERSECTOR2::TeVectorBoundaryIP& report); /** \brief Reports intersections between segments of a lineset and a polygonset. \param redLines A list of lines without self intersections. \param bluePolygons A list of polygons without self intersections. \param blueTree A tree with all segments from the polygonset already indexed or not, if it is empty, so, it will be filled inside this method. \param report A report list of intersection points. \return Returns true if there is an intersection between a red segment from the lineset and a blue segment from the polygonset. \note This function will not returns intersections between segments of the same polygon or lineset. It will only report intersection between segments from different sets. */ TL_DLL bool TeIntersection(const TeLineSet& redLines, const TePolygonSet& bluePolygons, TeSegmentRTree& blueTree, TeINTERSECTOR2::TeVectorBoundaryIP& report); /** \brief Tells if there is a self-intersection between segments. \param polygons A list of polygons to test self intersections. \param selfIntersectionList A report list with all self-intersections. \return Returns true if there is not a self-intersection. */ TL_DLL bool TeIsSimple(const TePolygonSet& polygons, vector<TePairSegIdInPolygonSet>& selfIntersectionList); /** \brief Index polygon's segments. \param polygons A list of polygons to index it segment's. \param tree The tree if indexed segments. */ TL_DLL void TeIndexPolygonSet(const TePolygonSet& polygons, TeSegmentRTree& tree); /** @} */ } // end namespace TeINTERSECTOR2 #endif //__TERRALIB_INTERNAL_INTERSECTOR2_H
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 214 ] ] ]
3d0c975e1db258ca486a8bd336bcd89adf2633a8
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Common/Base/Math/SweptTransform/hkSweptTransformUtil.inl
ae964706040d70d26e59dfc54ca0dc3c9a8920e3
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,813
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ void HK_CALL hkSweptTransformUtil::_lerp2( const hkSweptTransform& sweptTrans, hkReal t, hkQuaternion& quatOut ) { hkVector4 rot0 = sweptTrans.m_rotation0.m_vec; hkVector4 rot1 = sweptTrans.m_rotation1.m_vec; { quatOut.m_vec.setAdd4( rot0, rot1 ); #ifdef HK_PS2 quatOut.normalize(); #else hkReal len2 = quatOut.m_vec.lengthSquared4(); hkReal r = 0.75f - 0.125f * len2; r = r * (1.5f - 0.5f * len2 * r * r); quatOut.m_vec.mul4(r); #endif } if ( t < 0.5f ) { quatOut.m_vec.setInterpolate4( rot0, quatOut.m_vec, 2.0f * t); } else { quatOut.m_vec.setInterpolate4( quatOut.m_vec, rot1, 2.0f * t - 1.0f); } quatOut.m_vec.normalize4(); } void HK_CALL hkSweptTransformUtil::_lerp2( const hkSweptTransform& sweptTrans, hkReal t, hkTransform& transformOut ) { hkQuaternion qt; _lerp2( sweptTrans, t, qt ); transformOut.setRotation( qt ); transformOut.getTranslation().setInterpolate4( sweptTrans.m_centerOfMass0, sweptTrans.m_centerOfMass1, t); hkVector4 centerShift; centerShift._setRotatedDir( transformOut.getRotation(), sweptTrans.m_centerOfMassLocal); transformOut.getTranslation().sub4( centerShift ); } void HK_CALL hkSweptTransformUtil::calcTransAtT0( const hkSweptTransform& sweptTrans, hkTransform& transformOut ) { const hkQuaternion& qt = sweptTrans.m_rotation0; transformOut.setRotation( qt ); hkVector4 centerShift; centerShift._setRotatedDir( transformOut.getRotation(), sweptTrans.m_centerOfMassLocal); transformOut.getTranslation().setSub4( sweptTrans.m_centerOfMass0, centerShift ); } void HK_CALL hkSweptTransformUtil::calcTransAtT1( const hkSweptTransform& sweptTrans, hkTransform& transformOut ) { const hkQuaternion& qt = sweptTrans.m_rotation1; transformOut.setRotation( qt ); hkVector4 centerShift; centerShift._setRotatedDir( transformOut.getRotation(), sweptTrans.m_centerOfMassLocal); transformOut.getTranslation().setSub4( sweptTrans.m_centerOfMass1, centerShift ); } void HK_CALL hkSweptTransformUtil::_clipVelocities( const hkMotionState& motionState, hkVector4& linearVelocity, hkVector4& angularVelocity ) { hkReal linVelSq = linearVelocity.lengthSquared3(); hkReal angVelSq = angularVelocity.lengthSquared3(); const hkReal maxLinear = motionState.m_maxLinearVelocity * motionState.m_maxLinearVelocity; const hkReal maxAngular = motionState.m_maxAngularVelocity * motionState.m_maxAngularVelocity; if ( (linVelSq > maxLinear) || (linVelSq!=linVelSq) ) { hkReal f = motionState.m_maxLinearVelocity * hkMath::sqrtInverse( linVelSq ); linearVelocity.mul4( f ); if ( linVelSq!=linVelSq ) { linearVelocity = hkTransform::getIdentity().getColumn(0); HK_WARN(0xf0124242, "Nan velocity detected, something is seriously wrong (probably bad inertia tensors "); } } if ( (angVelSq > maxAngular) || ( angVelSq != angVelSq )) { hkReal f = motionState.m_maxAngularVelocity * hkMath::sqrtInverse( angVelSq ); angularVelocity.mul4( f ); if ( angVelSq!=angVelSq ) { angularVelocity = hkTransform::getIdentity().getColumn(0); HK_WARN(0xf0143243, "Nan velocity detected, something is seriously wrong (probably bad inertia tensors "); } } } // Has to be outside of inline function as gcc won't inline functions with statics in them. static HK_ALIGN16( float _stepMotionStateMaxVelf[4] ) = { 1e6f,1e6f,1e6f,1e6f }; void HK_CALL hkSweptTransformUtil::_stepMotionState( const hkStepInfo& info, hkVector4& linearVelocity, hkVector4& angularVelocity, hkMotionState& motionState ) { #ifdef HK_DEBUG { if ( motionState.getSweptTransform().getInvDeltaTime() != 0.0f) { hkReal motionEndTime = motionState.getSweptTransform().getBaseTime() + 1.0f / motionState.getSweptTransform().getInvDeltaTime(); HK_ASSERT(0xf0f0083, hkMath::equal(info.m_startTime, motionEndTime ) ) ; } } #endif // check for nans in velocities // fix nans to 100 { hkVector4 absLin; absLin.setAbs4( linearVelocity ); hkVector4 absAng; absAng.setAbs4( angularVelocity ); const hkVector4& maxVel = *(const hkVector4*)&_stepMotionStateMaxVelf; int mask = absLin.compareLessThan4( maxVel ).getMask() & absAng.compareLessThan4( maxVel ).getMask(); mask &= linearVelocity.compareEqual4( linearVelocity ).getMask() & angularVelocity.compareEqual4( angularVelocity ).getMask(); if ( (mask & hkVector4Comparison::MASK_XYZ) != hkVector4Comparison::MASK_XYZ ) { // velocity to a 'random' non zero velocity linearVelocity = hkTransform::getIdentity().getColumn(0); angularVelocity = hkTransform::getIdentity().getColumn(0); HK_WARN(0xf0123244, "Nan velocity or velocity > 1e6f detected, something is seriously wrong (probably bad inertia tensors "); } } motionState.getSweptTransform().m_centerOfMass0 = motionState.getSweptTransform().m_centerOfMass1; motionState.getSweptTransform().m_centerOfMass0(3) = info.m_startTime; hkReal linVelSq = linearVelocity.lengthSquared3(); if ( linVelSq > motionState.m_maxLinearVelocity * motionState.m_maxLinearVelocity ) { //HK_WARN_ONCE(0xf0327683, "Object exceeding maximum velocity, velocity clipped" ); hkReal f = motionState.m_maxLinearVelocity * hkMath::sqrtInverse( linVelSq ); linearVelocity.mul4( f ); } motionState.getSweptTransform().m_centerOfMass1.addMul4(info.m_deltaTime.val(), linearVelocity); motionState.getSweptTransform().m_centerOfMass1(3) = info.m_invDeltaTime; hkQuaternion newRotation = motionState.getSweptTransform().m_rotation1; motionState.getSweptTransform().m_rotation0 = newRotation; // // Calculate a new rotation, the fabs angle and angle squared // hkReal angle; { hkQuaternion dq; dq.m_vec.setMul4( info.m_deltaTime * 0.5f, angularVelocity ); const hkReal pi = HK_REAL_PI; hkReal dx2 = hkReal(dq.m_vec.lengthSquared3()) * (4.0f/ (pi*pi)); // do a little sin(alpha * 0.5f) approximation const hkReal a = 0.822948f; const hkReal b = 0.130529f; const hkReal c = 0.044408f; const hkReal maxAnglePerStep = hkMath::min2( 0.9f, info.m_deltaTime.val() * motionState.m_maxAngularVelocity ); // clipping angular velocity to be between [0, PI*0.9/dt] // info: was "<", is "<=" -- works ok for zero dt now. if ( dx2 <= maxAnglePerStep * maxAnglePerStep ) { const hkReal dx4 = dx2 * dx2; const hkReal w = 1.0f - a*dx2 - b*dx4 - c*dx2*dx4; dq.m_vec(3) = w; } else { hkReal factor = maxAnglePerStep * hkMath::sqrtInverse( dx2 ); angularVelocity.mul4( factor ); dq.m_vec.mul4( factor ); dx2 = maxAnglePerStep*maxAnglePerStep; const hkReal dx4 = dx2 * dx2; const hkReal w = 1.0f - a*dx2 - b*dx4 - c*dx2*dx4; dq.m_vec(3) = w; } newRotation.setMul( dq, newRotation ); newRotation.normalize(); motionState.m_deltaAngle.setAdd4( dq.m_vec, dq.m_vec ); angle = hkMath::sqrt(dx2) * pi; motionState.m_deltaAngle(3) = angle; } motionState.getSweptTransform().m_rotation1 = newRotation; calcTransAtT1( motionState.getSweptTransform(), motionState.getTransform()); } void HK_CALL hkSweptTransformUtil::deactivate( hkMotionState& ms ) { hkSweptTransform& sweptTransform = ms.getSweptTransform(); ms.m_deltaAngle.setZero4(); sweptTransform.m_rotation0 = sweptTransform.m_rotation1; sweptTransform.m_centerOfMass0 = sweptTransform.m_centerOfMass1; sweptTransform.m_centerOfMass1(3) = 0.0f; } //void HK_CALL hkSweptTransformUtil::calcTimInfo( const hkMotionState& ms0, const hkMotionState& ms1, hkVector4& timOut) //{ // HK_ASSERT2(0xad44d321, st0.getInvDeltaTime() == st1.getInvDeltaTime(), "Internal error: hkSweptTransform's must correspond to the same deltaTime in order to use void HK_CALL hkSweptTransformUtil::calcTimInfo( const hkMotionState& ms0, const hkMotionState& ms1, hkVector4& timOut)"); // // const hkSweptTransform& st0 = ms0.getSweptTransform(); // const hkSweptTransform& st1 = ms1.getSweptTransform(); // // hkVector4 diff0; diff0.setSub4( st0.m_centerOfMass0, st0.m_centerOfMass1 ); // hkVector4 diff1; diff1.setSub4( st1.m_centerOfMass1, st1.m_centerOfMass0 ); // // timOut.setAdd4( diff0, diff1 ); // // timOut(3) = ms0.m_deltaAngle(3) * ms0.m_objectRadius + ms1.m_deltaAngle(3) * ms1.m_objectRadius; // //} void HK_CALL hkSweptTransformUtil::calcTimInfo( const hkMotionState& ms0, const hkMotionState& ms1, hkReal deltaTime, hkVector4& timOut) { const hkSweptTransform& st0 = ms0.getSweptTransform(); const hkSweptTransform& st1 = ms1.getSweptTransform(); hkVector4 diff0; diff0.setSub4( st0.m_centerOfMass0, st0.m_centerOfMass1 ); hkVector4 diff1; diff1.setSub4( st1.m_centerOfMass1, st1.m_centerOfMass0 ); hkReal f0 = deltaTime * st0.getInvDeltaTime(); hkReal f1 = deltaTime * st1.getInvDeltaTime(); HK_ASSERT2(0xad56daaa, f0 <= 1.01f && f1 <= 1.01f, "Internal error: input for TIM calculation may be corrupted."); timOut.setMul4( f0, diff0 ); timOut.addMul4( f1, diff1 ); timOut(3) = f0 * ms0.m_deltaAngle(3) * ms0.m_objectRadius + f1 * ms1.m_deltaAngle(3) * ms1.m_objectRadius; // we don't project angular velocity just to keep it simple ( no cross products) } // Calculates angular distance (angVelocity * dt) travelled by the bodies. void HK_CALL hkSweptTransformUtil::calcAngularTimInfo( const hkMotionState& ms0, const hkMotionState& ms1, hkReal deltaTime, hkVector4* HK_RESTRICT deltaAngleOut0, hkVector4* HK_RESTRICT deltaAngleOut1) { const hkSweptTransform& st0 = ms0.getSweptTransform(); const hkSweptTransform& st1 = ms1.getSweptTransform(); hkReal f0 = deltaTime * st0.getInvDeltaTime(); hkReal f1 = deltaTime * st1.getInvDeltaTime(); hkVector4 ang0; ang0.setMul4( f0, ms0.m_deltaAngle ); hkVector4 ang1; ang1.setMul4( f1, ms1.m_deltaAngle ); deltaAngleOut0[0] = ang0; deltaAngleOut1[0] = ang1; } void HK_CALL hkSweptTransformUtil::calcCenterOfMassAt( const hkMotionState& ms, hkTime t, hkVector4& centerOut ) { hkReal iv = ms.getSweptTransform().getInterpolationValue( t ); centerOut.setInterpolate4( ms.getSweptTransform().m_centerOfMass0, ms.getSweptTransform().m_centerOfMass1, iv ); } void HK_CALL hkSweptTransformUtil::getVelocity( const hkMotionState& ms, hkVector4& linearVelOut, hkVector4& angularVelOut ) { linearVelOut.setSub4 (ms.getSweptTransform().m_centerOfMass1, ms.getSweptTransform().m_centerOfMass0); linearVelOut.mul4( ms.getSweptTransform().getInvDeltaTime() ); angularVelOut.setMul4( ms.getSweptTransform().getInvDeltaTime(), ms.m_deltaAngle ); } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 302 ] ] ]
d77c9f248f0e06187913a66c708f6b30f0d26cad
bd48897ed08ecfea35d8e00312dd4f9d239e95c4
/template.cpp
40fcb0b22013f4c5e837d83ae55c6e38b5e9e890
[]
no_license
blmarket/lib4bpp
ab83dbb95cc06e7b55ea2ca70012e341be580af1
2c676543de086458b93b1320b7b2ad7f556a24f7
refs/heads/master
2021-01-22T01:28:03.718350
2010-11-30T06:45:42
2010-11-30T06:45:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
850
cpp
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <cstdlib> #include <cmath> #include <sstream> #include <queue> #include <set> #include <map> #include <vector> #include <complex> #define mp make_pair #define pb push_back #define sqr(x) ((x)*(x)) #define foreach(it,c) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it) using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; typedef pair<int,int> PII; typedef long long LL; typedef complex<double> Point; template<typename T> inline int size(const T &a) { return a.size(); } template<typename T> inline bool operator<(const int &a,const vector<T> &b) { return a<b.size(); } bool process(void) { return true; } int main(void) { while(process()); return 0; }
[ "blmarket@dbb752b6-32d3-11de-9d05-31133e6853b1" ]
[ [ [ 1, 41 ] ] ]
4178d7638df1048f9aee37fd4ce7d419c62c0821
3856c39683bdecc34190b30c6ad7d93f50dce728
/server/UI_Manager.cpp
62288b693fdef71b104981464137ca9113072a0a
[]
no_license
yoonhada/nlinelast
7ddcc28f0b60897271e4d869f92368b22a80dd48
5df3b6cec296ce09e35ff0ccd166a6937ddb2157
refs/heads/master
2021-01-20T09:07:11.577111
2011-12-21T22:12:36
2011-12-21T22:12:36
34,231,967
0
0
null
null
null
null
UTF-8
C++
false
false
515
cpp
#include "stdafx.h" #include "UI_Manager.h" #include "UI_PacketState.h" #include "UI_ConnectionList.h" CUI_Manager::CUI_Manager() { UI_ConnectionList = NULL; UI_PacketState = NULL; CurrentUI = NULL; } CUI_Manager::~CUI_Manager() { SAFE_DELETE( UI_ConnectionList ); SAFE_DELETE( UI_PacketState ); } VOID CUI_Manager::Initialize() { UI_ConnectionList = new CUI_ConnectionList; UI_PacketState = new CUI_PacketState; } VOID CUI_Manager::Draw() { CurrentUI->Draw(); }
[ "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0", "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0" ]
[ [ [ 1, 24 ], [ 27, 33 ] ], [ [ 25, 26 ] ] ]
11a7cd2ee5ed0c8de935c663312a60d70c743407
bb625ce36ed37acb5a8e660ec03001e9f23626cc
/xgcBase/Common/vector_set.h
940ed0b61f543e62aebd3ef007fa26a32c6958ea
[]
no_license
crayzyivan/weppinhole
5010f6f9319a81ec5f5277f8a7dd952a20d37c87
58923bf0667471257679a6f34a353412364609d5
refs/heads/master
2021-01-10T13:14:59.582556
2010-06-25T02:46:40
2010-06-25T02:46:40
43,535,806
1
0
null
null
null
null
UTF-8
C++
false
false
6,970
h
#pragma once template < class K, class C = std::less<K>, class A = std::allocator< K > > class VectorSet : private std::vector< K, A > , public C { typedef std::vector<K, A> Base; typedef C MyCompare; public: typedef K key_type; typedef C key_compare; typedef A allocator_type; typedef typename A::reference reference; typedef typename A::const_reference const_reference; typedef typename Base::iterator iterator; typedef typename Base::const_iterator const_iterator; typedef typename Base::size_type size_type; typedef typename Base::difference_type difference_type; typedef typename A::pointer pointer; typedef typename A::const_pointer const_pointer; typedef typename Base::reverse_iterator reverse_iterator; typedef typename Base::const_reverse_iterator const_reverse_iterator; class value_compare : public std::binary_function<value_type, value_type, bool> , private key_compare { friend class VectorSet; protected: value_compare(key_compare pred) : key_compare(pred) {} public: bool operator()(const value_type& lhs, const value_type& rhs) const { return key_compare::operator()(lhs.first, rhs.first); } }; explicit VectorSet(const key_compare& comp = key_compare(), const A& alloc = A()) : Base(alloc) , MyCompare(comp) {} template <class InputIterator> VectorSet(InputIterator first, InputIterator last, const key_compare& comp = key_compare(), const A& alloc = A()) : Base(first, last, alloc), MyCompare(comp) { MyCompare& me = *this; std::sort(begin(), end(), me); } VectorSet& operator=(const VectorSet& rhs) { VectorSet(rhs).swap(*this); return *this; } // iterators: // The following are here because MWCW gets 'using' wrong iterator begin() { return Base::begin(); } const_iterator begin() const { return Base::begin(); } iterator end() { return Base::end(); } const_iterator end() const { return Base::end(); } reverse_iterator rbegin() { return Base::rbegin(); } const_reverse_iterator rbegin() const { return Base::rbegin(); } reverse_iterator rend() { return Base::rend(); } const_reverse_iterator rend() const { return Base::rend(); } // capacity: bool empty() const { return Base::empty(); } size_type size() const { return Base::size(); } size_type max_size() { return Base::max_size(); } // modifiers: std::pair<iterator, bool> insert(const value_type& val) { bool found(true); iterator i(lower_bound(val)); if (i == end() || this->operator()( val, *i )) { i = Base::insert(i, val); found = false; } return std::make_pair(i, !found); } //Section [23.1.2], Table 69 //http://developer.apple.com/documentation/DeveloperTools/gcc-3.3/libstdc++/23_containers/howto.html#4 iterator insert(iterator pos, const value_type& val) { if( (pos == begin() || this->operator()(*(pos-1),val)) && (pos == end() || this->operator()(val, *pos)) ) { return Base::insert(pos, val); } return insert(val); } template <class InputIterator> void insert(InputIterator first, InputIterator last) { for (; first != last; ++first) insert(*first); } void erase(iterator pos) { Base::erase(pos); } size_type erase(const key_type& k) { iterator i(find(k)); if (i == end()) return 0; erase(i); return 1; } void erase(iterator first, iterator last) { Base::erase(first, last); } void swap(VectorSet& other) { Base::swap(other); MyCompare& me = *this; MyCompare& rhs = other; std::swap(me, rhs); } void clear() { Base::clear(); } // observers: key_compare key_comp() const { return *this; } value_compare value_comp() const { const key_compare& comp = *this; return value_compare(comp); } // 23.3.1.3 map operations: iterator find(const key_type& k) { iterator i(lower_bound(k)); if (i != end() && this->operator()(k, i)) { i = end(); } return i; } const_iterator find(const key_type& k) const { const_iterator i(lower_bound(k)); if (i != end() && this->operator()(k, i)) { i = end(); } return i; } size_type count(const key_type& k) const { return find(k) != end(); } iterator lower_bound(const key_type& k) { MyCompare& me = *this; return std::lower_bound(begin(), end(), k, me); } const_iterator lower_bound(const key_type& k) const { const MyCompare& me = *this; return std::lower_bound(begin(), end(), k, me); } iterator upper_bound(const key_type& k) { MyCompare& me = *this; return std::upper_bound(begin(), end(), k, me); } const_iterator upper_bound(const key_type& k) const { const MyCompare& me = *this; return std::upper_bound(begin(), end(), k, me); } std::pair<iterator, iterator> equal_range(const key_type& k) { MyCompare& me = *this; return std::equal_range(begin(), end(), k, me); } std::pair<const_iterator, const_iterator> equal_range( const key_type& k) const { const MyCompare& me = *this; return std::equal_range(begin(), end(), k, me); } template <class K1, class C1, class A1> friend bool operator==(const VectorSet<K1, C1, A1>& lhs, const VectorSet<K1, C1, A1>& rhs); bool operator<(const VectorSet& rhs) const { const Base& me = *this; const Base& yo = rhs; return me < yo; } template <class K1, class C1, class A1> friend bool operator!=(const VectorSet<K1, C1, A1>& lhs, const VectorSet<K1, C1, A1>& rhs); template <class K1, class C1, class A1> friend bool operator>(const VectorSet<K1, C1, A1>& lhs, const VectorSet<K1, C1, A1>& rhs); template <class K1, class C1, class A1> friend bool operator>=(const VectorSet<K1, C1, A1>& lhs, const VectorSet<K1, C1, A1>& rhs); template <class K1, class C1, class A1> friend bool operator<=(const VectorSet<K1, C1, A1>& lhs, const VectorSet<K1, C1, A1>& rhs); }; template <class K, class C, class A> inline bool operator==(const VectorSet<K, C, A>& lhs, const VectorSet<K, C, A>& rhs) { const std::vector< K, A>& me = lhs; return me == rhs; } template <class K, class C, class A> inline bool operator!=(const VectorSet<K, C, A>& lhs, const VectorSet<K, C, A>& rhs) { return !(lhs == rhs); } template <class K, class C, class A> inline bool operator>(const VectorSet<K, C, A>& lhs, const VectorSet<K, C, A>& rhs) { return rhs < lhs; } template <class K, class C, class A> inline bool operator>=(const VectorSet<K, C, A>& lhs, const VectorSet<K, C, A>& rhs) { return !(lhs < rhs); } template <class K, class C, class A> inline bool operator<=(const VectorSet<K, C, A>& lhs, const VectorSet<K, C, A>& rhs) { return !(rhs < lhs); } // specialized algorithms: template <class K, class C, class A> void swap(VectorSet<K, C, A>& lhs, VectorSet<K, C, A>& rhs) { lhs.swap(rhs); }
[ "albertclass@9d869f0c-08ce-11df-b3eb-39986f41eb1c" ]
[ [ [ 1, 270 ] ] ]
010253fd424d61b90f99ae318dbb3a3e1be9c64a
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/Include/ItemBox.h
251c5e7d2eb49308a1458a8b0be59ff82fe25b7d
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
468
h
/*! @file @author Albert Semenov @date 01/2009 @module */ #ifndef __ITEM_BOX_H__ #define __ITEM_BOX_H__ //#include "EnginePrerequisites.h" #include <MyGUI.h> #include "ItemBox/BaseItemBox.h" #include "CellView.h" namespace Nebula { class CellView; class ItemBox : public wraps::BaseItemBox<CellView> { public: ItemBox(MyGUI::WidgetPtr _parent); virtual ~ItemBox(); }; } // namespace demo #endif // __ITEM_BOXV_H__
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 31 ] ] ]
dfd43692d2bb1f6481ea28a0081ae6d8375d7b42
3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c
/zju.finished/1551.cpp
922e98d7785543614b243afa6e27b99e21a5fa93
[]
no_license
usherfu/zoj
4af6de9798bcb0ffa9dbb7f773b903f630e06617
8bb41d209b54292d6f596c5be55babd781610a52
refs/heads/master
2021-05-28T11:21:55.965737
2009-12-15T07:58:33
2009-12-15T07:58:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,145
cpp
#include<iostream> using namespace std; enum { SIZ = 108, }; struct Point{ int x,y; }; int num; Point tree[SIZ]; struct _cmp_x{ bool operator()(const int&a, const int&b)const{ if(tree[a].x != tree[b].x) return tree[a].x < tree[b].x; return tree[a].y<tree[b].y; } }xc; struct _cmp_y{ bool operator()(const int&a, const int&b)const{ if(tree[a].y != tree[b].y) return tree[a].y<tree[b].y; return tree[a].x < tree[b].x; } }yc; int W,H; int x[SIZ]; int y[SIZ]; int wid; Point o; void fun(){ int i,j,k; int gw, ow;// gw为以前离W的最大值,ow为当前x,y的最大值 for(i=0; i<num; i++){ if(i && tree[x[i]].x == tree[x[i-1]].x) continue; for(j=0; j<num; j++){ // tree[x[i]].x tree[y[i]].y if(j &&tree[y[j]].y==tree[y[j-1]].y) continue; gw = W - tree[x[i]].x; for(k=j+1; k<num; k++){ if( tree[y[k]].y == tree[y[j]].y ||tree[y[k]].x <= tree[x[i]].x ||tree[y[k]].x > tree[x[i]].x + gw) continue; ow = min(gw, tree[y[k]].y-tree[y[j]].y); gw = min(gw, tree[y[k]].x-tree[x[i]].x); if(ow > wid){ wid = ow; o.x = tree[x[i]].x; o.y = tree[y[j]].y; } } ow = min(gw, H-tree[y[j]].y); if(ow > wid){ wid = ow; o.x = tree[x[i]].x; o.y = tree[y[j]].y; } } } printf("%d %d %d\n", o.x, o.y, wid); } int readIn(){ if(scanf("%d%d%d",&num,&W,&H)<0) return 0; for(int i=0; i<num; i++){ scanf("%d%d",&tree[i].x, &tree[i].y); x[i] = y[i] = i; } tree[num].x = 0, tree[num].y = 0; x[num] = y[num] = num; num++; wid = o.x = o.y = 0; sort(x, x+num, xc); sort(y, y+num, yc); return 1; } int main(){ while(readIn()>0){ fun(); } return 0; }
[ [ [ 1, 84 ] ] ]
fa2670a94d4960f6cc3ecaf27c41b1cdafc1543e
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/has_nrvo_fail.cpp
367efec2acf8e229f06986d2b8023bd5bae18d90
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,131
cpp
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004, // by libs/config/tools/generate // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for the most recent version. // Test file for macro BOOST_HAS_NRVO // This file should not compile, if it does then // BOOST_HAS_NRVO may be defined. // see boost_has_nrvo.ipp for more details // Do not edit this file, it was generated automatically by // ../tools/generate from boost_has_nrvo.ipp on // Sun Jul 25 11:47:49 GMTDT 2004 // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifndef BOOST_HAS_NRVO #include "boost_has_nrvo.ipp" #else #error "this file should not compile" #endif int main( int, char *[] ) { return boost_has_nrvo::test(); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 39 ] ] ]
3fd08aea9732f2f7fd8634db47ff6a5b4b235386
631e5d0780b8dd333fb2c5471cbc853cc94aa355
/parent.h
04d67aefeeda2f900bee72d7d7d7a0c6a971a89a
[]
no_license
derdos/DRO-C
c4b4b18806511355766da94b03c4f7559d70f815
8a384a79dfd698bf95ea29d55fda9557020a7df7
refs/heads/master
2021-01-19T18:52:06.892428
2010-10-07T23:49:21
2010-10-07T23:49:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
721
h
/* * Parent library for the LCD menu control aspect of the DRO * * Created on: Sep 2, 2010 * Author: David Erdos */ #ifndef PARENT_H_ #define PARENT_H_ #include <WProgram.h> #include <WString.h> #include "panel.h" class Parent { private: unsigned int iBufferSize; unsigned int iIndex; char cEOL; Panel *curPanel; Panel *lastPanel; Panel *homePanel; char sReadBuffer[5]; int upVal; int dnVal; int rtVal; int ltVal; int upPrev; int dnPrev; int rtPrev; int ltPrev; public: Parent(); void run(); void pushPanel(Panel *panel); void popPanel(); void clearBuffer(); void setHomePanel(Panel *panel); void jogUpdate(); }; #endif /* PARENT_H_ */
[ "David@.(none)", "[email protected]" ]
[ [ [ 1, 24 ], [ 35, 41 ], [ 43, 45 ] ], [ [ 25, 34 ], [ 42, 42 ] ] ]
02dfa8823030bcedfee5906d363660e4c5e79c56
79636d9a11c4ac53811d55ef0f432f68ab62944f
/smart-darkgdk/include/Object.cpp
3b30362bd40054fe5729ad376a70a0d5671d8f10
[ "MIT" ]
permissive
endel/smart-darkgdk
44d90a1afcd71deebef65f47dc54586df4ae4736
6235288b8aab505577223f9544a6e5a7eb6bf6cd
refs/heads/master
2021-01-19T10:58:29.387767
2009-06-26T16:44:15
2009-06-26T16:44:15
32,123,434
0
0
null
null
null
null
UTF-8
C++
false
false
15,363
cpp
#include "ObjectType.h" #include "Object.h" #include "../Game.h" #include "DarkGDK.h" #include "Image.h" #include "Mesh.h" #include "Limb.h" #include "VertexShader.h" #include "PixelShader.h" #include "Effect.h" #include "BSP.h" #include "Event.h" #include <map> //------------------------------------------------ // OPERATOR OVERLOADING //------------------------------------------------ bool Object::operator==(Object* o) { return (this->id == o->id); } bool Object::operator!=(Object* o) { return (this->id != o->id); } //------------------------------------------------ // CONSTRUCTORS / DESTRUCTORS //------------------------------------------------ Object::Object(int id) { this->setId(id); _init(); } //-- Object::Object(char* filename) { this->setId(Game::getObjectId()); dbLoadObject(filename,this->id); _init(); } //-- Object::Object(Mesh *m,Image *t) { this->setId(Game::getObjectId()); dbMakeObject(this->id,m->id,t->id); _init(); } //-- Object::Object(float width,float height,float depth) { this->setId(Game::getObjectId()); dbMakeObjectBox(this->id,width,height,depth); _init(); } //-- Object::Object(ObjectType t, float size) { this->setId(Game::getObjectId()); switch (t) { case CONE: dbMakeObjectCone(this->id,size);break; case CUBE: dbMakeObjectCube(this->id,size);break; case CYLINDER: dbMakeObjectCylinder(this->id,size);break; case SPHERE: dbMakeObjectSphere(this->id,size);break; } _init(); } void Object::execute(Event *e) { position(999,999,999); } //-- Object::Object(Object* second, Limb *l) { this->setId(Game::getObjectId()); dbMakeObjectFromLimb( this->id, second->id, l->id); _init(); } //-- Object::Object(float width, float height) { this->setId(Game::getObjectId()); dbMakeObjectPlain(this->id,width,height); _init(); } //-- Object::Object(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3) { this->setId(Game::getObjectId()); dbMakeObjectTriangle(this->id,x1,y1,z1, x2,y2,z2, x3,y3,z3); _init(); } //-- Object::~Object(void) { dbDeleteObject(this->id); } //-- char* Object::getClassName() { return "Object"; } //-- Object* Object::clone() { Object* cloned = new Object(Game::getObjectId()); dbCloneObject(cloned->id,this->id); return cloned; } void Object::_init() { if (BSP::getAllCollisionsEnabled()) { if (this->exists()) BSP::setCollisionOn(this); } locked = false; animationState = STOPPED; this->currentAnimation = new AnimationClip("none", 0, getTotalFrames(), 1, LOOP); } //------------------------------------------------ // VISIBILITY //------------------------------------------------ void Object::show() { dbShowObject(this->id); } //-- void Object::hide() { dbHideObject(this->id); } //-- void Object::toggle() { if (isVisible()) hide(); else show(); } //------------------------------------------------ // ANIMATION //------------------------------------------------ void Object::addAnimation(char* p_name, int p_frameInicial, int p_frameFinal, int p_velocidade, WrapMode p_wrapMode) { this->animations[p_name] = new AnimationClip(p_name, p_frameInicial, p_frameFinal, p_velocidade, p_wrapMode); } //-- void Object::playAnimation(char* p_animation) { if(p_animation != this->currentAnimation->name) { AnimationClip* newAnimation = new AnimationClip(animations[p_animation]); this->currentAnimation = newAnimation; this->animFrame = newAnimation->frameInicial; this->animVelocity = newAnimation->velocidade; this->animationState = PLAYING; } } //-- void Object::crossFadeAnimation(char* p_animation, float p_switchVelocity) { if(p_animation != this->currentAnimation->name) { AnimationClip* newAnimation = new AnimationClip(animations[p_animation]); this->currentAnimation = newAnimation; this->animFrame = newAnimation->frameInicial; this->animInterpPercent = 0.0f; this->animSwitchVelocity = p_switchVelocity; this->animationState = CHANGING; } } //-- void Object::stopAnimation() { this->animationState = STOPPED; this->currentAnimation = new AnimationClip("none", 0, 0, 0, LOOP); } //-- void Object::setFrame(int p_frame) { dbSetObjectFrame(this->id, p_frame); } //-- void Object::updateAnimation() { switch(this->animationState) { //-->STOPPED case STOPPED: { dbSetObjectFrame(this->id, (int)this->animFrame); break; } //-->CHANGING case CHANGING: { this->animInterpPercent += this->animSwitchVelocity; if(this->animInterpPercent >= 100.0f) { this->animInterpPercent = 100.0f; dbSetObjectInterpolation(this->id, (int)this->animInterpPercent); this->animationState = PLAYING; } else { dbSetObjectInterpolation(this->id, (int)this->animInterpPercent); } dbSetObjectFrame(this->id, (int)this->animFrame); break; } //-->PLAYING case PLAYING: { this->animFrame += this->animVelocity * 0.1f; if(this->currentAnimation->wrapMode == LOOP) { if(this->animVelocity >= 0) { if(this->animFrame > this->currentAnimation->frameFinal) { this->animFrame = this->currentAnimation->frameInicial; } } else { if(this->animFrame < this->currentAnimation->frameInicial) { this->animFrame = this->currentAnimation->frameFinal; } } } else if(currentAnimation->wrapMode == ONCE) { if(this->animVelocity >= 0) { if(this->animFrame > this->currentAnimation->frameFinal) { this->animFrame = this->currentAnimation->frameFinal; this->animationState = STOPPED; } } else { if(this->animFrame < this->currentAnimation->frameInicial) { this->animFrame = this->currentAnimation->frameInicial; this->animationState = STOPPED; } } } dbSetObjectFrame(this->id, (int)this->animFrame); break; } } } //------------------------------------------------ // TRANSFORM //------------------------------------------------ void Object::setPosition(float x,float y, float z) { dbPositionObject(this->id, x, y, z); } void Object::setPositionX(float val) { this->setPosition(val,this->getPositionY(),this->getPositionZ()); } //-- void Object::setPositionY(float val) { this->setPosition(this->getPositionX(),val,this->getPositionZ()); } //-- void Object::setPositionZ(float val) { this->setPosition(this->getPositionX(),this->getPositionY(),val); } //-- void Object::setPosition(Object* o) { dbPositionObject(this->id,o->getPositionX(),o->getPositionY(),o->getPositionZ()); } //-- void Object::position(float x,float y, float z) { setPosition(getPositionX() + x, getPositionY() + y, getPositionZ() + z); } void Object::positionX(float val) { setPositionX(getPositionX() + val); } //-- void Object::positionY(float val) { setPositionY(getPositionY() + val); } //-- void Object::positionZ(float val) { setPositionZ(getPositionZ() + val); } //-- void Object::scale(float xSize, float ySize, float zSize) { dbScaleObject(this->id, xSize, ySize, zSize); } //-- void Object::scale(float xyz) { scale(xyz,xyz,xyz); } //-- void Object::rotation(float xAngle, float yAngle, float zAngle) { dbRotateObject(this->id,xAngle,yAngle,zAngle); } void Object::rotationX(float angle) { dbXRotateObject(this->id, angle); } void Object::rotationY(float angle) { dbYRotateObject(this->id, angle); } void Object::rotationZ(float angle) { dbZRotateObject(this->id, angle); } //-- void Object::rotate(float xAngle, float yAngle, float zAngle) { dbRotateObject(this->id, this->getAngleX() + xAngle, this->getAngleY() + yAngle, this->getAngleZ() + zAngle); } void Object::rotateX(float angle) { dbXRotateObject(this->id, this->getAngleX() + angle); } void Object::rotateY(float angle) { dbYRotateObject(this->id, this->getAngleY() + angle); } void Object::rotateZ(float angle) { dbZRotateObject(this->id, this->getAngleZ() + angle); } //-- void Object::localMove(float x, float y, float z) { dbMoveObjectRight(this->id, x); dbMoveObjectUp(this->id, y); dbMoveObject(this->id, z); } //-- void Object::moveY(float v) { dbMoveObjectUp(this->id, v); } //-- void Object::moveX(float v) { dbMoveObjectRight(this->id, v); } //-- void Object::move(float v) { dbMoveObject(this->id,v); } //-- void Object::lookAt(float x, float y, float z) { dbPointObject(this->id, x, y, z); } //-- void Object::setVar(char* name, int value) { vars[name] = value; } int Object::getVar(char* name) { return vars[name]; } //------------------------------------------------ // RENDERER //------------------------------------------------ void Object::setGhost(bool g,int mode) { if (g) dbGhostObjectOn(this->id,mode); else dbGhostObjectOff(this->id); } //-- void Object::setLight(bool l) { dbSetObjectLight(this->id,l); } //-- void Object::setEmissive(int r,int g,int b) { dbSetObjectEmissive(this->id, RGB(r,g,b)); } //-- void Object::setTexture(Image *t,int mode,int mipGeneration) { dbTextureObject(this->id,t->id); if (mode != -1 || mipGeneration != -1) dbSetObjectTexture(this->id,mode,mipGeneration); } Image *Object::setTexture(char* imagePath,int mode,int mipGeneration) { Image* t = new Image(imagePath); this->setTexture(t); if (mode != -1 || mipGeneration != -1) dbSetObjectTexture(this->id,mode,mipGeneration); return t; } //-- void Object::applyShader(VertexShader *s) { vertexShaderOn = true; dbSetVertexShaderOn(this->id,s->id); } //-- void Object::applyShader(PixelShader *s) { pixelShaderOn = true; dbSetPixelShaderOn(this->id,s->id); } //-- void Object::removeShader() { if (vertexShaderOn) dbSetVertexShaderOff(this->id); if (pixelShaderOn) dbSetPixelShaderOff(this->id); } //-- void Object::applyEffect(Effect *e) { dbSetObjectEffect(this->id,e->id); dbPerformChecklistForEffectValues(e->id); } //-- void Object::removeEffect() { } //-- void Object::fixPivot() { dbFixObjectPivot(this->id); } //-- void Object::offsetTexture(float p_x, float p_y) { dbScrollObjectTexture(this->id, p_x, p_y); } //-- void Object::showBoundingBox() { dbShowObjectBounds(this->id); } void Object::showBounds(bool boxOnly) { dbShowObjectBounds(this->id,boxOnly); } void Object::setColor(int r,int g,int b) { dbColorObject(this->id,RGB(r,g,b)); } void Object::lock() { locked = true; dbLockObjectOn(this->id); } void Object::unlock() { locked = false; dbLockObjectOff(this->id); } void Object::toggleLock() { if (locked) unlock(); else lock(); } void Object::setSmoothing(float angle) { dbSetObjectSmoothing(this->id,angle); } void Object::setSmoothing(int percentage) { dbSetObjectSmoothing(this->id,percentage); } void Object::scaleTexture(float u, float v) { dbScaleObjectTexture(this->id,u,v); } void Object::scrollTexture(float x, float y) { dbScrollObjectTexture(this->id,x,y); } //------------------------------------------------ // COLLISION //------------------------------------------------ Limb* Object::addLimb(Object* o) { return new Limb(o, this); } void Object::performCheckListForLimbs() { dbPerformCheckListForObjectLimbs( this->id ); } //------------------------------------------------ // GETTERS //------------------------------------------------ bool Object::isPlaying() { return dbObjectPlaying(this->id); } //-- bool Object::isVisible() { return dbObjectVisible(this->id); } //-- bool Object::isLooping() { return dbObjectLooping(this->id); } //-- bool Object::exists() { if (!this->id) return false; else return dbObjectExist(this->id); } //-- float Object::getPositionX() { return dbObjectPositionX(this->id); } //-- float Object::getPositionY() { return dbObjectPositionY(this->id); } //-- float Object::getPositionZ() { return dbObjectPositionZ(this->id); } //-- float Object::getSize() { return dbObjectSize(this->id); } //-- float Object::getSizeX() { return dbObjectSizeX(this->id); } //-- float Object::getSizeY() { return dbObjectSizeY(this->id); } //-- float Object::getSizeZ() { return dbObjectSizeZ(this->id); } //-- float Object::getAngleX() { return dbObjectAngleX(this->id); } //-- float Object::getAngleY() { return dbObjectAngleY(this->id); } //-- float Object::getAngleZ() { return dbObjectAngleZ(this->id); } //-- float Object::getFrame() { return dbObjectFrame(this->id); } //-- float Object::getSpeed() { return dbObjectSpeed(this->id); } //-- float Object::getInterpolation() { return dbObjectInterpolation(this->id); } //-- float Object::getTotalFrames() { return dbTotalObjectFrames(this->id); } //-- float Object::getInScreen() { return dbObjectInScreen(this->id); } //-- float Object::getScreenX() { return dbObjectScreenX(this->id); } //-- float Object::getScreenY() { return dbObjectScreenY(this->id); } //-- //------------------------------------------------ // COLLISION //------------------------------------------------ void Object::makeBoxCollider(float p_x1, float p_y1, float p_z1, float p_x2, float p_y2, float p_z2) { dbMakeObjectCollisionBox(this->id, p_x1, p_y1, p_z1, p_x2, p_y2, p_z2, 1); } //-- void Object::makeBoxCollider() { dbSetObjectCollisionToBoxes(this->id); } //-- void Object::setAutomaticCollision(float radius, int response) { dbAutomaticObjectCollision(this->id,radius,response); } //-- void Object::setCollisionType(eCollisionType c) { switch (c) { case COLLISION_POLYGON: dbSetObjectCollisionToPolygons(this->id); break; case COLLISION_SPHERE: dbSetObjectCollisionToSpheres(this->id); break; default: COLLISION_BOX: dbSetObjectCollisionToBoxes(this->id); break; } } //-- void Object::collisionEnabled(bool flag) { if(flag) dbSetObjectCollisionOn(this->id); else dbSetObjectCollisionOff(this->id); } //-- bool Object::hit(Object* o) { return dbObjectHit(this->id,o->id); } //-- Object* Object::hit() { return new Object(dbObjectHit(this->id,0)); } //-- bool Object::collision(Object* o) { return dbObjectCollision(this->id,o->id); } //-- Object* Object::collision() { return new Object(dbObjectCollision(this->id,0)); } //-- float Object::getCollisionRadius() { return dbObjectCollisionRadius(this->id); } //-- float Object::getCollisionCenterX() { return dbObjectCollisionCenterX(this->id); } //-- float Object::getCollisionCenterY() { return dbObjectCollisionCenterY(this->id); } //-- float Object::getCollisionCenterZ() { return dbObjectCollisionCenterZ(this->id); } //-- float Object::intersect(float x, float y, float z, float newX, float newY, float newZ) { return dbIntersectObject(this->id, x, y, z, newX, newY, newZ); }
[ "endel.dreyer@0995f060-2c81-11de-ae9b-2be1a451ffb1", "[email protected]@0995f060-2c81-11de-ae9b-2be1a451ffb1" ]
[ [ [ 1, 161 ], [ 165, 171 ], [ 178, 178 ], [ 181, 183 ], [ 192, 192 ], [ 194, 197 ], [ 209, 209 ], [ 211, 228 ], [ 235, 235 ], [ 242, 242 ], [ 250, 250 ], [ 261, 262 ], [ 266, 266 ], [ 283, 283 ], [ 290, 290 ], [ 298, 298 ], [ 311, 539 ], [ 551, 749 ], [ 763, 779 ], [ 787, 839 ] ], [ [ 162, 164 ], [ 172, 177 ], [ 179, 180 ], [ 184, 191 ], [ 193, 193 ], [ 198, 208 ], [ 210, 210 ], [ 229, 234 ], [ 236, 241 ], [ 243, 249 ], [ 251, 260 ], [ 263, 265 ], [ 267, 282 ], [ 284, 289 ], [ 291, 297 ], [ 299, 310 ], [ 540, 550 ], [ 750, 762 ], [ 780, 786 ] ] ]
c2fe2f2a8b3a37677d9d1c9907c373f112e1ef05
9e4b72c504df07f6116b2016693abc1566b38310
/back/stdafx.h
3a309ff2bd6161396ea5f51a3648120d06ad1a18
[ "MIT" ]
permissive
mmeeks/rep-snapper
73311cadd3d8753462cf87a7e279937d284714aa
3a91de735dc74358c0bd2259891f9feac7723f14
refs/heads/master
2016-08-04T08:56:55.355093
2010-12-05T19:03:03
2010-12-05T19:03:03
704,101
0
1
null
null
null
null
UTF-8
C++
false
false
3,059
h
/* -------------------------------------------------------- * * * StdAfx.h * * Copyright 2009+ Michael Holm - www.kulitorum.com * * This file is part of RepSnapper and is made available under * the terms of the GNU General Public License, version 2, or at your * option, any later version, incorporated herein by reference. * * ------------------------------------------------------------------------- */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #pragma warning( disable : 4311 4312 4244 4267 4800) #define DEBUG_ECHO (1<<0) #define DEBUG_INFO (1<<1) #define DEBUG_ERRORS (1<<2) #ifdef WIN32 #include <windows.h> // Header File For Windows #include <tchar.h> typedef unsigned int uint; #endif typedef unsigned int UINT; #include <stdio.h> #include <FL/Fl.H> #include <vmmlib/vmmlib.h> #include <GL/gl.h> // Header File For The OpenGL32 Library #include <GL/glu.h> // Header File For The GLu32 Library //#include <gl\glaux.h> // Header File For The GLaux Library #include "math.h" // Needed for sqrtf #include "ArcBall.h" #include "gcode.h" #include "ModelViewController.h" #include "Printer.h" #include "ProcessController.h" #include "stl.h" #include "UI.h" #include "xml/XML.H" #include "File.h" typedef unsigned int uint; void MakeAcceleratedGCodeLine(Vector3f start, Vector3f end, float DistanceToReachFullSpeed, float extrusionFactor, GCode &code, float z, float minSpeedXY, float maxSpeedXY, float minSpeedZ, float maxSpeedZ, bool UseIncrementalEcode, bool Use3DGcode, float &E, bool EnableAcceleration); bool IntersectXY(const Vector2f &p1, const Vector2f &p2, const Vector2f &p3, const Vector2f &p4, InFillHit &hit); // Utilityfunction for CalcInFill bool InFillHitCompareFunc(const InFillHit& d1, const InFillHit& d2); extern void HSVtoRGB (const float &h, const float &s, const float &v, float &r,float &g,float &b); extern void RGBtoHSV (const float &r, const float &g, const float &b, float &h, float &s, float &v); extern void RGBTOHSL (float red, float green, float blue, float &hue, float &sat, float &lightness); extern void RGBTOYUV (float r, float g, float b, float &y, float &u, float &v); extern void YUVTORGB (float y, float u, float v, float &r, float &g, float &b); #include "ModelViewController.h" #include "AsyncSerial.h" #ifdef WIN32 extern "C" { //#include <lua.h> #include <lua.hpp> } #include <luabind/luabind.hpp> using namespace luabind; #endif extern ModelViewController *MVC; // TODO: reference additional headers your program requires here // ivconv #include "ivcon.h"
[ [ [ 1, 84 ] ] ]
523d85b999ef89eda7dd3107150715707057499f
016774685beb74919bb4245d4d626708228e745e
/lib/Collide/ozcollide/aabbtree_poly.h
bc811d2f4b49b4728e1908aaaeab6f2381bc2c27
[]
no_license
sutuglon/Motor
10ec08954d45565675c9b53f642f52f404cb5d4d
16f667b181b1516dc83adc0710f8f5a63b00cc75
refs/heads/master
2020-12-24T16:59:23.348677
2011-12-20T20:44:19
2011-12-20T20:44:19
1,925,770
1
0
null
null
null
null
UTF-8
C++
false
false
6,132
h
/* OZCollide - Collision Detection Library Copyright (C) 2006 Igor Kravtchenko 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact the author: [email protected] */ #ifndef OZCOLLIDE_AABBTREEPOLY_H #define OZCOLLIDE_AABBTREEPOLY_H #ifndef OZCOLLIDE_PCH #include <ozcollide/ozcollide.h> #endif #include <ozcollide/aabbtree.h> #include <ozcollide/polygon.h> #include <ozcollide/vector.h> #include <ozcollide/obb.h> #include <ozcollide/sphere.h> #include <ozcollide/ellipsoid.h> ENTER_NAMESPACE_OZCOLLIDE class DataIn; typedef void AABBCDPoly_callback(const class AABBTreePoly &, const Polygon &, int user, const Box &, void *userCallback); class AABBTreePolygonLeaf : public AABBTreeNode { public: AABBTreePolygonLeaf() : nbPolys (0), polys (NULL), users (NULL) { }; int nbPolys; const Polygon *polys; int *users; }; class AABBTreePoly : public AABBTree { AABBTreePoly(int leafDepth); ~AABBTreePoly(); public: class BoxColResult { public: Vector<const Polygon *> polys_; Vector<int> users_; Box boxQuery_; }; class OBBColResult { public: Vector<const Polygon *> polys_; Vector<int> users_; OBB obbQuery_; }; class SphereColResult { public: Vector<const Polygon *> polys_; Vector<int> users_; Sphere sphereQuery_; }; class EllipsoidColResult { public: Vector<const Polygon *> polys_; Vector<int> users_; Ellipsoid ellipsoidQuery_; }; class SegmentColResult { public: Vector<const Polygon *> polys_; Vector<int> users_; Vec3f segmentPt0_; Vec3f segmentPt1_; }; OZCOLLIDE_API static ERR loadBinary(const char *filename, AABBTreePoly **); OZCOLLIDE_API static ERR loadBinary(DataIn &, AABBTreePoly **); OZCOLLIDE_API ERR saveBinary(const char *filename); OZCOLLIDE_API ERR saveBinary(DataOut &data); OZCOLLIDE_API int getMemoryConsumption() const; OZCOLLIDE_API int getNbPoints() const; OZCOLLIDE_API const Vec3f* getPointsList() const; // // BOX QUERY OZCOLLIDE_API bool isCollideWithBox(const Box &); OZCOLLIDE_API bool isCollideWithBox(const Box &, BoxColResult &); OZCOLLIDE_API void collideWithBox(const Box &, AABBCDPoly_callback *, void *userCallback = NULL); OZCOLLIDE_API void collideWithBox(const Box &, BoxColResult &); // // SPHERE QUERY OZCOLLIDE_API bool isCollideWithSphere(const Sphere &); OZCOLLIDE_API void collideWithSphere(const Sphere &, AABBCDPoly_callback *, void *userCallback = NULL); OZCOLLIDE_API void collideWithSphere(const Sphere &, SphereColResult &); // // ELLIPSOID QUERY OZCOLLIDE_API bool isCollideWithEllipsoid(const Ellipsoid &); OZCOLLIDE_API void collideWithEllipsoid(const Ellipsoid &, AABBCDPoly_callback *, void *userCallback = NULL); OZCOLLIDE_API void collideWithEllipsoid(const Ellipsoid &, EllipsoidColResult &); // // SEGMENT QUERY OZCOLLIDE_API bool isCollideWithSegment(const Vec3f &seg_pt0, const Vec3f &seg_pt1); OZCOLLIDE_API bool isCollideWithSegment(const Vec3f &seg_pt0, const Vec3f &seg_pt1, SegmentColResult &); OZCOLLIDE_API void collideWithSegment(const Vec3f &seg_pt0, const Vec3f &seg_pt1, AABBCDPoly_callback *, void *userCallback = NULL); OZCOLLIDE_API void collideWithSegment(const Vec3f &seg_pt0, const Vec3f &seg_pt1, SegmentColResult &); // // OBB QUERY OZCOLLIDE_API bool isCollideWithOBB(const OBB &); OZCOLLIDE_API bool isCollideWithOBB(const OBB &, OBBColResult &); OZCOLLIDE_API void collideWithOBB(const OBB &, AABBCDPoly_callback *, void *userCallback = NULL); OZCOLLIDE_API void collideWithOBB(const OBB &, OBBColResult &); // Return the number of collided primitives since the last call to collideWithxxx() OZCOLLIDE_API int getNbCollidedPrimitives() const; OZCOLLIDE_API void scale(float); private: // bunch of internal recursive methods bool isCollideWithBox(const AABBTreeNode &); void collideWithBox(const AABBTreeNode &); bool isCollideWithSphere(const AABBTreeNode &); void collideWithSphere(const AABBTreeNode &); bool isCollideWithEllipsoid(const AABBTreeNode &); void collideWithEllipsoid(const AABBTreeNode &); bool isCollideWithSegment(const AABBTreeNode &); void collideWithSegment(const AABBTreeNode &); bool isCollideWithOBB(const AABBTreeNode &); void collideWithOBB(const AABBTreeNode &); void calculNbLeafs(const AABBTreeNode *, int &nb) const; void readPNTSchunk(DataIn &, int chunkSize); void readNODSchunk(DataIn &, int chunkSize, int nbNodes); void readLEFSchunk(DataIn &, int chunkSize, int nbLeafs); // Calcul polygon's normal void final(); AABBTreePolygonLeaf *leafs_; int nbPoints_; Vec3f *points_; AABBCDPoly_callback *callback_; void *userCallback_; BoxColResult *boxColRes_; OBBColResult *obbColRes_; SphereColResult *sphereColRes_; EllipsoidColResult *ellipColRes_; SegmentColResult *segmentColRes_; // Some primitives used internally for a reason or another... Box box_; Vec3f seg_pt0_, seg_pt1_; Sphere sphere_; Ellipsoid ellip_; OBB obb_; int nbColls_; // one shot buffer for allocation (faster loading) int *bufEdges_; int offBufEdges_; Polygon *bufPols_; int offBufPols_; friend class AABBTree; friend class AABBTreePolyBuilder; }; LEAVE_NAMESPACE #endif
[ [ [ 1, 210 ] ] ]
8c5a9c56b8ffab58278844cd1704acfe77a7cd50
cdd119cd2a3c24982bf5f75197e5da1258924478
/mq/src/queuemsgfactory.h
96481176c2303f345e60c7d6141e82c7996219a0
[]
no_license
xuxiandi/DOMQ
12bbbd477ce75152c1b5acb8731ddb1833067c62
3a28ebed6323292a1e264b80d969cd94324538b8
refs/heads/master
2020-12-31T02:33:22.791616
2011-05-17T06:01:01
2011-05-17T06:01:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,056
h
#ifndef _QUEUE_MSG_FACTORY_H__ #define _QUEUE_MSG_FACTORY_H__ #include <list> #include <netmgr/factory.h> #include <base/util/allocator.h> #include <msg/msgqueuemsg.h> #include <base/thread/mutex.h> #define _MSGTYPES_(v) \ v(OpenMsgQueueRequest)\ v(OpenMsgQueueResult)\ v(CloseMsgQueueRequest)\ v(CloseMsgQueueResult)\ v(GetMsgRequest)\ v(GetMsgResult)\ v(SendMsgRequest)\ v(SendMsgResult) #define DECLARE_ALLOCATOR(T) base::ObjectPoolAllocator<T> _#T class QueueMsgFactory : public netmgr::MsgFactory { public: QueueMsgFactory(); virtual std::list<std::string> KnownTypes() const; virtual netmgr::Message* Create(const char* type); virtual void Destroy(const netmgr::Message* msg); private: #define DECLARE_MSG_ALLOCATOR(MSGNAME) base::ObjectPoolCallBackAllocator<MSGNAME> _##MSGNAME;base::ThreadMutex _mutex##MSGNAME; _MSGTYPES_(DECLARE_MSG_ALLOCATOR) #undef DECLARE_MSG_ALLOCATOR bool _debug; }; #endif
[ [ [ 1, 38 ] ] ]
0075c3b602a007d5e9707fcafab8891a4c04c501
011359e589f99ae5fe8271962d447165e9ff7768
/src/interface/Xbox360/main.h
33c284f374337930dbc18e9c86d2132fa5327252
[]
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
406
h
#include <xtl.h> #include <xui.h> #include <xuiapp.h> #ifndef MAIN_H #define MAIN_H class CBurnApp : public CXuiModule { protected: // Override RegisterXuiClasses so that CMyApp can register classes. virtual HRESULT RegisterXuiClasses(); // Override UnregisterXuiClasses so that CMyApp can unregister classes. virtual HRESULT UnregisterXuiClasses(); }; #endif
[ [ [ 1, 21 ] ] ]
2f590ea377c8993c4b9670b28117abba84f34216
ccb3cf0631fcf62050a3aae847c78248fb72eabb
/source/DrawMap.cpp
91b60a6a60944be6fe9b29f1229a56af6543d5fc
[]
no_license
benbaker76/HeadRush
64275b69c998bf828fe3df56e13641f835f0eb50
7de61f8588fcf4ba18acaf4f1ad3da2fe21fac85
refs/heads/master
2022-11-24T15:56:05.198090
2009-12-11T19:58:13
2009-12-11T19:58:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
999
cpp
#include <nds.h> // Main nds header (includes other ds headers) #include <math.h> // For the sqrt, atan2, sin, cos etc. #include <stdio.h> // For outputting to the console #include <stdlib.h> // Define's some standard "C" functions #include <unistd.h> #include "DrawMap.h" #include "Globals.h" void drawMap() { // the idea of this piece of code 'will' be that you pass the X,Y coord of player (0-511) and the scroll possition will be updated to match // and also the enemies and other sprites will be affected also. This will have to eventually return 2 offsets (0-256) for the scroll (though // they could be read from the H/VOFS, so that perhaps we can use our own sprite draw code to only show onscreen sprites? Hmmm // Yep - this is a tricky bit for me // also, scrolling messes up the idea of multiple players on screen (or does it?) REG_BG1HOFS_SUB = (int)g_levelX; REG_BG1VOFS_SUB = (int)g_levelY; // g_levelX = XCoord; // g_levelY = 320; }
[ [ [ 1, 28 ] ] ]
612ed50edbb137aa5f1e15e69c0b9dab23b37fb2
975d45994f670a7f284b0dc88d3a0ebe44458a82
/Docs/FINAIS/Fonte/cliente/Source/GameCore/CPersonagem.h
840e68ddff8b0e3145ad65c487baddcef8c28aac
[]
no_license
phabh/warbugs
2b616be17a54fbf46c78b576f17e702f6ddda1e6
bf1def2f8b7d4267fb7af42df104e9cdbe0378f8
refs/heads/master
2020-12-25T08:51:02.308060
2010-11-15T00:37:38
2010-11-15T00:37:38
60,636,297
0
0
null
null
null
null
UTF-8
C++
false
false
3,090
h
#pragma once #include "GameSetup.h" #include "CTree.h" struct SBolsa { int _idBolsa; int _listaItens[BOLSAMAXITENS]; vector3df posicao; bool _isOpen; }; struct SQuadrante { int _id; int _coluna; int _linha; vector3df _center; }; class CPersonagem { public: SQuadrante _quadranteFinal; SQuadrante _quadranteSeguinte; CTree _memoria; /* bool _modoAtaque; int _dinheiro; int _itemEnviarTroca; int _itemReceberTroca; int _dinheiroEnviarTroca; int _dinheiroReceberTroca; int _idQuest; int _objetivosQuest; int _inventario[INVENTARIOMAXITENS]; int _lealdade[RACASMAX]; int _listaProdutos[MAXITENSVENDEDOR]; int _nivelPoder[NUMPODERES]; int _bonusHabilidade; int _bonusPoder; int _roleta[NUMROLETAOPCOES]; */ int _startFrame, _endFrame; int _id; char *_nome; vector3df _posicao; vector3df _destino; int _pv; int _pp; int _xp; int _pvMax; int _ppMax; int _xpMax; int _nivel; bool _buff[BUFF_COUNT]; int _raca; int _classe; int _estado; int _ultimoEstado; float _velAnim; float _direcao; int _idAlvo; int _idBaseArma; int _idBaseArmadura; int _idRelArma; int _idRelArmadura; //primarias int _forca; int _destreza; int _agilidade; int _resistencia; int _instinto; //secundarias int _alcance; int _ataque; int _dano; int _defesa; int _taxaAtaque; //int _tempoCarga; ISound *_soundFX; // Efeito sonoro do personagem IAnimatedMeshSceneNode *_modelo; CPersonagem(); void abrirBolsa(int idBolsa); void aceitarQuest(int idQuest, int objetivo[]); void apanhar(int dano); void atacar(int tipoAtaque); void ativarBuff(int idBuff); void atualizar(); void atualizarPrimarias(int forca, int destreza, int agilidade, int resistencia, int instinto); void atualizarSecundarias(int ataque, int dano, int defesa, int alcance, int taxaAtaque); void comprarItem(int idItem, int idVendedor); void desativarBuff(int idBuff); void desequipaArma(); void desequiparArmadura(); void entrarPortal(int idPortal); void enviarItem(); void equiparArma(int idArma); void equiparArmadura(int idArmadura); int getId(); void getQuadrante(); void inicializar(); void interpolarPosicao(); void morrer(); void parar(); void pathFinder(); void receberItem(int dinheiroReceber, int itemReceber); void receberListaProdutos(); void respaw(int idCenario, int X, int Z); void setAlvo(int idAlvo); void setPosition(int X, int Z); void trocarItem(); void trocarNivel(); void usarItem(int idItem); void venderItem(int idItem, int idComprador); int getQuadranteID(int linha, int coluna); float getDistanceBetween( vector3d<f32> p1, vector3d<f32> p2 ); vector3df getQuadranteCenter(int linha, int coluna); int getDirectionTo(vector3d<f32> p2); float getRotationTo(vector3d<f32> destino); void LRTAStar(SQuadrante origem, vector3df objetivo, SQuadrante &proximoPasso, bool Matriz[MAPMAXLIN][MAPMAXCOL]); void updAnimation(bool isLoop); };
[ [ [ 1, 155 ] ] ]
10df684c551eb52bab2c6fca2af5f125b4f3955f
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_6_005.cpp
0ce8aa329594a3ae2d392a165769eb757f5686ef
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,406
cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2006 Hartmut Kaiser. 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) The tests included in this file were initially taken from the mcpp V2.5 preprocessor validation suite and were modified to fit into the Boost.Wave unit test requirements. The original files of the mcpp preprocessor are distributed under the license reproduced at the end of this file. =============================================================================*/ // Tests error reporting: illegal #if expressions. #define A 1 #define B 1 // 14.2: Operators =, +=, ++, etc. are not allowed in #if expression. //E t_6_005.cpp(23): error: ill formed preprocessor expression: 1 --1 #if A --B #endif /*- * Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. */
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 51 ] ] ]
6ff137ac17dca96ce58f7579f0bb0f67f3ce8063
1d6dcdeddc2066f451338361dc25196157b8b45c
/tp2/Interaccion/IU.h
3ceefc6a6b67f4a2f60d9aed32e646d998482e31
[]
no_license
nicohen/ssgg2009
1c105811837f82aaa3dd1f55987acaf8f62f16bb
467e4f475ef04d59740fa162ac10ee51f1f95f83
refs/heads/master
2020-12-24T08:16:36.476182
2009-08-15T00:43:57
2009-08-15T00:43:57
34,405,608
0
0
null
null
null
null
UTF-8
C++
false
false
2,018
h
#ifndef IU_H #define IU_H #include "../Motor.h" #include "../Visualizacion/Pantalla.h" #include "../Interaccion/EditorHoja.h" #include "../Interaccion/EditorSenderoPlantacion.h" /** Interfaz de Usuario: Clase que contiene toda la funcionalidad brindada al usuario para hacer modificaciones durante la ejecucion del sistema */ class IU { public: /** * Devuelve la instancia unica segun el patron de diseño Singleton */ static IU* getInstancia(){ static IU* iu = NULL; if (!iu) iu = new IU(); return iu; } /** * Desabilita el motor limpiando los recursos que este estaba utilizando. * El mismo queda inutilizable */ inline static void limpiar(){ delete (IU::getInstancia()); } Editor* getEditorSenderoPlantacion() { return this->editorSendero; } Editor* getEditorHoja() { return this->editorHoja; } /** Manejo de eventos de teclado **/ static void keyboard (unsigned char key, int x, int y); /** Manejo de eventos de mouse **/ static void mouse(int boton, int estado, int x, int y); static void mousePressed(int x,int y); /** OnIdle **/ static void OnIdle(); protected: private: EditorHoja* editorHoja; EditorSenderoPlantacion* editorSendero; void addPuntoControlBSplines(Coordenadas coordenada); void addPuntoControlBezier(Coordenadas coordenada); // Constructor IU(){ float ancho = Pantalla::getInstancia()->getAncho(); float alto = Pantalla::getInstancia()->getAlto(); this->editorHoja = new EditorHoja(ancho,alto); this->editorSendero = new EditorSenderoPlantacion(ancho,alto); } //Destructor inline ~IU ( ){ delete this->editorHoja; delete this->editorSendero; } }; #endif // IU_H
[ "rodvar@6da81292-15a5-11de-a4db-e31d5fa7c4f0", "nicohen@6da81292-15a5-11de-a4db-e31d5fa7c4f0" ]
[ [ [ 1, 42 ], [ 44, 44 ], [ 46, 48 ], [ 55, 68 ] ], [ [ 43, 43 ], [ 45, 45 ], [ 49, 54 ] ] ]
c6408f24ad25b96b226177ff3c6985b5cc2d6b46
f0c08b3ddefc91f1fa342f637b0e947a9a892556
/branches/develop/calcioIA/Calcio/Perceptions.h
45d210ac0d5f41e0c6c9a7017c2c004e1593bff9
[]
no_license
BackupTheBerlios/coffeestore-svn
1db0f60ddb85ccbbdfeb9b3271a687b23e29fc8f
ddee83284fe9875bf0d04e6b7da7a2113e85a040
refs/heads/master
2021-01-01T05:30:22.345767
2009-10-11T08:55:35
2009-10-11T08:55:35
40,725,038
0
0
null
null
null
null
UTF-8
C++
false
false
1,362
h
#ifndef PERCEPTIONS_H #define PERCEPTIONS_H #include <vector> #include "Point.h" #include "Vector.h" #include "PerceivedPlayer.h" #include "Ball.h" #include "Team.h" class Player; class Game; class Field; class Perceptions { public: class PositionPct { public: PositionPct(int width, int height); int width() const; int height() const; private: int _width; int _height; }; typedef std::vector<PerceivedPlayer> PerceivedPlayers; Perceptions(const Game& game, Team::Color color, const Player& player); const Point& ballPosition() const; const Vector& ballDirection() const; bool isBallkickable() const; const PerceivedPlayers& visibleTeamMate() const; const PerceivedPlayers& visibleOpponent() const; Point playerPosition() const; PositionPct playerPositionPct() const; Vector playerSightDirection() const; Team::Color ownTeamColor() const; Team::Color opponentTeamColor() const; Team::Side ownTeamSide() const; Team::Side opponentTeamSide() const; private: Ball initBall(const Game& game); void initOpponentVect(const Game& game); void initTeamMateVect(const Game& game); const Player& _player; PerceivedPlayers _mate; PerceivedPlayers _opp; const Team& _ownTeam; const Team& _opponentTeam; Ball _ball; const Field& _field; }; #endif
[ "fabioppp@e591b805-c13a-0410-8b2d-a75de64125fb", "ranzuglia@e591b805-c13a-0410-8b2d-a75de64125fb" ]
[ [ [ 1, 44 ], [ 46, 69 ] ], [ [ 45, 45 ] ] ]
5d11ff074fd90ca2e5587780283328dfd2743c9c
c267e416aba473054330378d18bc3cd172bbad21
/QQ音乐缓存提取工具/tea.cpp
924b30a5f47ad29bcd22e6e79f1a5cf357b54236
[]
no_license
chenwp/shuax
c3b7dea72708ee539664ac8db1d9885e87fefed7
b13bea0aae7e252650f4c8f5df1b2a716455ef80
refs/heads/master
2021-04-26T16:43:25.168306
2011-10-22T15:09:37
2011-10-22T15:09:37
45,179,472
2
0
null
null
null
null
GB18030
C++
false
false
1,411
cpp
#include <stdio.h> #include <conio.h> #include <windows.h> void tea_decrypt(DWORD* pData, const DWORD* pEncData) { DWORD Key1 = 0x45AD9059; DWORD FKey1 = 0xF03E934F; DWORD FKey2 = 0x27BDB886; DWORD LKey1 = 0xD0AAE945; DWORD LKey2 = 0x993BA3AE; DWORD FirstData, LastData, Count, Key; Count = 32; Key = Key1 << 5;//Key=(Key1*循环次数),这里是32即2的5次方 FirstData = *(pEncData); LastData = *(pEncData + 1); do { LastData = LastData - ((LKey2 + (FirstData << 4)) ^ (LKey1 + (FirstData >> 5)) ^ (Key + FirstData)); FirstData = FirstData - ((FKey2 + (LastData << 4)) ^ (FKey1 + (LastData >> 5)) ^ (Key + LastData)); Key = Key - Key1; Count--; } while (Count != 0); *(pData) = FirstData; *(pData + 1) = LastData; } char* decrypt(const char *file,char *path) { FILE *in,*out; in=fopen(file,"rb"); if(in==NULL) { return 0; } static char temp[1924]; strcpy(temp,path); strcat(temp,strrchr(file,'\\')+1); strcat(temp,".wma"); out=fopen(temp,"wb"); if(out==NULL) { return 0; } DWORD pData[2],pEncData[2]; int i=0; while(!feof(in)) { i = fread(pEncData,1,sizeof(DWORD)*2,in); if(i==sizeof(DWORD)*2) { tea_decrypt(pData,pEncData); fwrite(pData,1,sizeof(DWORD)*2,out); } else { fwrite(pEncData,1,i,out); continue; } } fclose(in); fclose(out); return temp; }
[ [ [ 1, 66 ] ] ]
fe20fa0c0e527f40751ae4d66063fb947e6b9ed3
54dfb0046228832dcdec6dc5a18c5c23ada6f9ee
/MainProgram_GUI/MainProgram_GUI.h
8e087ea912a2f9c1c8e0e0925370f762b019f555
[]
no_license
github188/piglets-monitoring
3f6ec92e576d334762cc805727d358d9799ca053
620b6304384534eb71113c26a054c36ce3800ed8
refs/heads/master
2021-01-22T12:45:45.159790
2011-11-08T15:37:18
2011-11-08T15:37:18
null
0
0
null
null
null
null
GB18030
C++
false
false
1,173
h
// MainProgram_GUI.h : PROJECT_NAME 应用程序的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件" #endif #include "resource.h" // 主符号 //#include "otlv4.h" // CMainProgram_GUIApp: // 有关此类的实现,请参阅 MainProgram_GUI.cpp // class CMainProgram_GUIApp : public CWinApp { public: CMainProgram_GUIApp(); // 重写 public: virtual BOOL InitInstance(); // 实现 DECLARE_MESSAGE_MAP() virtual int ExitInstance(); }; extern otl_connect g_db; extern CCriticalSection g_cs_db; extern CMainProgram_GUIApp theApp; //////////////////////////////////////////////////////////////////////////自定义函数////// typedef struct _APPCONFIG{ int nSeconds; int nMinRecord; double dLinger; double dRun; double dRest; }App_Config; extern App_Config g_app_config; bool G_ReadAppConfigFromDB(App_Config &appconfig);//从数据库中读取程序配置信息 bool G_WriteAppConfigToDB(const App_Config &appconfig);//设置程序配置信息 //////////////////////////////////////////////////////////////////////////////////////////
[ [ [ 1, 47 ] ] ]
a89f40416c403e654b5bcd577c5ae8a674345361
d1dc408f6b65c4e5209041b62cd32fb5083fe140
/src/drawers/cOrderDrawer.cpp
40b55016d3a49e5112c163d841964055917ff082
[]
no_license
dmitrygerasimuk/dune2themaker-fossfriendly
7b4bed2dfb2b42590e4b72bd34bb0f37f6c81e37
89a6920b216f3964241eeab7cf1a631e1e63f110
refs/heads/master
2020-03-12T03:23:40.821001
2011-02-19T12:01:30
2011-02-19T12:01:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,211
cpp
/* * cOrderDrawer.cpp * * Created on: 9-aug-2010 * Author: Stefan */ #include "../include/d2tmh.h" cOrderDrawer::cOrderDrawer() { } cOrderDrawer::~cOrderDrawer() { } bool cOrderDrawer::isMouseOverOrderButton(int mouseX, int mouseY) { if ( (mouseX > 29 && mouseX < 187) && (mouseY > 2 && mouseY < 31)) { return true; } return false; } void cOrderDrawer::drawOrderPlaced(cPlayer * thePlayer) { BITMAP *bmp_trans=create_bitmap(((BITMAP *)gfxinter[BTN_ORDER].dat)->w,((BITMAP *)gfxinter[BTN_ORDER].dat)->h); clear_to_color(bmp_trans, makecol(255,0,255)); // copy draw_sprite(bmp_trans, (BITMAP *)gfxinter[BTN_ORDER].dat, 0, 0); // make black rectfill(bmp_screen, 29, 0, 187, 29, makecol(0,0,0)); // trans fblend_trans(bmp_trans, bmp_screen, 29, 0, 128); // destroy - phew destroy_bitmap(bmp_trans); } void cOrderDrawer::drawOrderButton(cPlayer * thePlayer) { assert(thePlayer); cOrderProcesser * orderProcesser = thePlayer->getOrderProcesser(); assert(orderProcesser); if (orderProcesser->isOrderPlaced()) { drawOrderPlaced(thePlayer); } else { draw_sprite(bmp_screen, (BITMAP *)gfxinter[BTN_ORDER].dat, 29, 0); } }
[ "stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151" ]
[ [ [ 1, 51 ] ] ]
3d0f4cf34e409ab3b46af8200e281f008983ceff
20c74d83255427dd548def97f9a42112c1b9249a
/src/roadfighter/car.h
64ea8f367d51a46d736f342f35fe543b97d7582b
[]
no_license
jonyzp/roadfighter
70f5c7ff6b633243c4ac73085685595189617650
d02cbcdcfda1555df836379487953ae6206c0703
refs/heads/master
2016-08-10T15:39:09.671015
2011-05-05T12:00:34
2011-05-05T12:00:34
54,320,171
0
0
null
null
null
null
UTF-8
C++
false
false
1,929
h
#ifndef CAR_H #define CAR_H #include "interactive-object.h" #include "basedefs.h" #define CAR_ALIVE_FRAME 0 #define CAR_DESTROY_FRAME_START 1 #define CAR_DESTROY_FRAME_END 3 enum carState { CAR_READY, CAR_RUNNING, CAR_SLIDING, CAR_SPINNING, CAR_DODGING, CAR_DESTROYING, CAR_DESTROYED, }; enum carType { BONUS_CAR, YELLOW_CAR, RED_CAR, BLUE_CAR, BLUEFIGHTER_CAR, BLUEAGGRESSIVE_CAR, TRUCK_CAR }; enum slideDirectionType { DIRECTION_NONE, DIRECTION_LEFT, DIRECTION_RIGHT }; class Car : public InteractiveObject { protected: carState myState; carType myType; double speed; Logical active; slideDirectionType slideDirection; double lastX, lastY; int startTurnIndex, endTurnIndex; LPDIRECTDRAWSURFACE7 destroyFrames[CAR_DESTROY_FRAME_END - CAR_DESTROY_FRAME_START + 1]; int destroyFrameIndex; Timer destroyFrameTimer; Logical destroyTimerInitialized; public: Car(); Car::Car(char *,double); virtual ~Car(); virtual void initMe() = 0; virtual void initImages(); void setSpeed(double speed); double getSpeed(); virtual void incSpeed(); void setCarState(carState state); carState getCarState(); void setCarType(carType myType); carType getCarType(); void setLastX(double lX); double getLastX(); void setLastY(double lY); double getLastY(); void setSlideDirection(slideDirectionType spin); slideDirectionType getSlideDirection(); void setActive(Logical active); Logical isActive(); void slide(); void sliding(); Logical isSliding(); virtual void destroy(); virtual void destroying(); virtual void move(); virtual void moveLeft(double howMuch); virtual void moveRight(double howMuch); virtual void bumpAction() = 0; Logical isRivalCar(); virtual void spawnAt(double xPos, double yPos); void calculateTurnIndex(); int getStartTurnIndex(); int getEndTurnIndex(); }; #endif
[ [ [ 1, 95 ] ] ]
6dbaadac80ac198d10c5f62a9c2a44cbabdf1960
4aedb4f2fba771b4a2f1b6ba85001fff23f16d09
/vm/instr.h
7d50bb972742ae765ee3e8ad85552c1cde1f0e8d
[]
no_license
orfest/codingmonkeys-icfpc
9eacf6b51f03ed271505235e65e53a44ae4addd0
8ee42d89261c62ecaddf853edd4e5bb9b097b10b
refs/heads/master
2020-12-24T16:50:44.419429
2009-06-29T17:52:44
2009-06-29T17:52:44
32,205,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,263
h
#ifndef INSTR_H #define INSTR_H #include "common.h" typedef code_t opcode_t; class Instr{ public: static code_t getNoop(); static code_t buildSInstr(opcode_t opcode, int imm, addr_t src); static opcode_t getSOpcode(code_t op); static int getSImm(code_t op); static addr_t getSReg(code_t op); static opcode_t getCmpOpcode(code_t op); static opcode_t getDOpcode(code_t op); static addr_t getDReg1(code_t op); static addr_t getDReg2(code_t op); static opcode_t getBits(opcode_t op, int from, int to); static const opcode_t S_TYPE_OP = 0; // D-Type static const opcode_t ADD = 1; static const opcode_t SUB = 2; static const opcode_t MULT = 3; static const opcode_t DIV = 4; static const opcode_t OUTPUT = 5; static const opcode_t PHI = 6; // S-Type static const opcode_t NOOP = 0; static const opcode_t CMPZ = 1; static const opcode_t SQRT = 2; static const opcode_t COPY = 3; static const opcode_t INPUT = 4; // Conditionals static const opcode_t LTZ = 0; static const opcode_t LEZ = 1; static const opcode_t EQZ = 2; static const opcode_t GEZ = 3; static const opcode_t GTZ = 4; }; #endif //INSTR_H
[ "nkurtov@6cd8edf8-6250-11de-81d0-cf1ed2c911a4" ]
[ [ [ 1, 48 ] ] ]
89443f818522e61adfb9a06dbaf4d65339ec5739
1e299bdc79bdc75fc5039f4c7498d58f246ed197
/stdobj/ProcessInfo.h
1b9e67103bdbf86bac545381357feda4922108dc
[]
no_license
moosethemooche/Certificate-Server
5b066b5756fc44151b53841482b7fa603c26bf3e
887578cc2126bae04c09b2a9499b88cb8c7419d4
refs/heads/master
2021-01-17T06:24:52.178106
2011-07-13T13:27:09
2011-07-13T13:27:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,109
h
//-------------------------------------------------------------------------------- // // Copyright (c) 1999 MarkCare Solutions // // Programming by Rich Schonthal // //-------------------------------------------------------------------------------- // ProcessInfo.h: interface for the CProcessInfo class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PROCESSINFO_H__35CFA811_2FD4_11D3_87C5_00104B9E6286__INCLUDED_) #define AFX_PROCESSINFO_H__35CFA811_2FD4_11D3_87C5_00104B9E6286__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //-------------------------------------------------------------------------------- class CProcessInfo { private: CDWordArray m_nProcId; public: CProcessInfo(LPCTSTR); virtual ~CProcessInfo(); public: static void GetProcessName(DWORD nProcId, CString& sName); int GetCount() { return m_nProcId.GetSize(); } DWORD GetProcId(int n = 0) { return m_nProcId[n]; } }; #endif // !defined(AFX_PROCESSINFO_H__35CFA811_2FD4_11D3_87C5_00104B9E6286__INCLUDED_)
[ [ [ 1, 37 ] ] ]
03c3b4e703f5fe2677dc8f3c66954b6f93bc2cc1
1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50
/slam_logger_t/main.cpp
ea812db468212636e7383dac2c20db411bc26508
[]
no_license
llvllrbreeze/alcorapp
dfe2551f36d346d73d998f59d602c5de46ef60f7
3ad24edd52c19f0896228f55539aa8bbbb011aac
refs/heads/master
2021-01-10T07:36:01.058011
2008-12-16T12:51:50
2008-12-16T12:51:50
47,865,136
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,208
cpp
#include "alcor/core/slam_logger_t.h" #include <alcor/sense/urg_laser_t.hpp> int main(int argc, char* argv[]){ std::string nomefile; if(argc > 1) nomefile = argv[1]; else nomefile.assign("general_data_log.bin"); all::sense::urg_laser_t* m_urg; all::sense::urg_scan_data_ptr m_curr_scan; slam_data_log_t data_logged; m_urg = new all::sense::urg_laser_t(); std::cout << "Premi un tasto per iniziare l'acquisizione" << std::endl; getchar(); if(m_urg->connect()){ m_curr_scan = m_urg->do_scan(all::math::angle(-110, all::math::deg_tag), all::math::angle(110, all::math::deg_tag), 1); slam_logger_t *logger = new slam_logger_t(nomefile,true,false,false,(int) m_curr_scan->scan_points.size()); std::cout << "Laser connesso" << std::endl; std::cout << "Attendo uno scan" << std::endl; for(int i=0;i<100;i++){ m_curr_scan = m_urg->do_scan(all::math::angle(-110, all::math::deg_tag), all::math::angle(110, all::math::deg_tag), 1); std::cout << "La dimensione dello scan è : " << m_curr_scan->scan_points.size() << std::endl; data_logged.laserData = m_curr_scan; logger->add_data_(data_logged); } delete(logger); } getchar(); return 1; }
[ "francesco.roccucci@1ffd000b-a628-0410-9a29-793f135cad17" ]
[ [ [ 1, 33 ] ] ]
f5a8795341f320ed7e69978d6d561642f50e6239
ca02e948a5ed8c73a5ccdfeba9f358bee93d3646
/Project 1/officeMonitor.h
4115fd65a0269322ac164114539a9da406934f65
[]
no_license
fangygy/csci402-nachos-group25
df2588e46c8542e655c84311704163753b4f0fee
fe3f86d82823c17b7a0af8a52f96f5ce9c38df8c
refs/heads/master
2021-01-10T12:10:11.794245
2011-04-27T06:48:00
2011-04-27T06:48:00
44,470,050
0
0
null
null
null
null
UTF-8
C++
false
false
2,756
h
#ifndef OFFICEMONITOR_H #define OFFICEMONITOR_H #define MAX_CLERKS 10 #define MAX_CUSTOMERS 100 #include "synch.h" class OfficeMonitor { private: //No private variables public: static const int MAX_CLERK = MAX_CLERKS; static const int MAX_CUSTOMER = MAX_CUSTOMERS; OfficeMonitor(); ~OfficeMonitor(); OfficeMonitor(int numAC, int numPC, int numPassC, int numCash); // Amount of each kind of Clerk int numAppClerks, numPicClerks, numPassClerks, numCashiers; // Amount of each customer/senator in total (used for instantiation) int totalCustSen, numAppWait, numPicWait, numPassWait, numCashWait; // Amount of each customer/senator currently in office or waiting room int officeCust, waitCust, officeSenator; // Locks for customer/senator checking Lock *customerLock; Lock *senatorLock; // Waiting room locks/CVs Lock *custWaitLock; Lock *senWaitLock; Lock *clerkWaitLock; Condition *clerkWaitCV; Condition *custWaitCV; Condition *senWaitCV; // Line Lengths (Cashier has no privileged line) int regACLineLength, regPCLineLength, regPassLineLength; int privACLineLength, privPCLineLength, privPassLineLength; int cashLineLength; // Line Locks Lock *acpcLineLock; Lock *passLineLock; Lock *cashLineLock; // Line Condition Variables Condition *regACLineCV, *regPCLineCV, *regPassLineCV; Condition *privACLineCV, *privPCLineCV, *privPassLineCV; Condition *cashLineCV; // Clerk Locks Lock *appLock[MAX_CLERKS]; Lock *picLock[MAX_CLERKS]; Lock *passLock[MAX_CLERKS]; Lock *cashLock[MAX_CLERKS]; // Clerk Condition Variables Condition *appCV[MAX_CLERKS]; Condition *picCV[MAX_CLERKS]; Condition *passCV[MAX_CLERKS]; Condition *cashCV[MAX_CLERKS]; // Clerk Data used for passing customer index int appData[MAX_CLERKS]; int picData[MAX_CLERKS]; int passData[MAX_CLERKS]; int cashData[MAX_CLERKS]; // Clerk Data used for passing true/false statements bool picDataBool[MAX_CLERKS]; bool passDataBool[MAX_CLERKS]; bool cashDataBool[MAX_CLERKS]; // Clerk States enum clerkState {BUSY, AVAILABLE, BREAK}; clerkState appState[MAX_CLERKS]; clerkState picState[MAX_CLERKS]; clerkState passState[MAX_CLERKS]; clerkState cashState[MAX_CLERKS]; // Clerk Money int appMoney; Lock *appMoneyLock; int picMoney; Lock *picMoneyLock; int passMoney; Lock *passMoneyLock; int cashMoney; Lock *cashMoneyLock; // Customer States, Types and Lock Lock *fileLock[MAX_CUSTOMERS]; enum custState { NONE, PICDONE, APPDONE, APPPICDONE, PASSDONE, ALLDONE }; custState fileState[MAX_CUSTOMERS]; enum custType {CUSTOMER, SENATOR}; custType fileType[MAX_CUSTOMERS]; }; #endif // OFFICEMONITOR_H
[ "leejasperkwok@6e91ac2e-7172-fd64-087b-c4397769e289", "[email protected]", "[email protected]", "[email protected]" ]
[ [ [ 1, 9 ], [ 15, 16 ], [ 106, 108 ] ], [ [ 10, 10 ], [ 102, 102 ], [ 105, 105 ] ], [ [ 11, 14 ], [ 17, 25 ], [ 27, 37 ], [ 40, 101 ], [ 103, 104 ] ], [ [ 26, 26 ], [ 38, 39 ] ] ]