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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d8643d0f5856e2ee9254b2108e0349a21a4b0b79 | 6c8c4728e608a4badd88de181910a294be56953a | /AssetModule/AssetManager.cpp | b09a97f91a8ee55c24dd56873aee697745f443a5 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,303 | cpp | #include "StableHeaders.h"
#include "AssetModule.h"
#include "AssetInterface.h"
#include "AssetEvents.h"
#include "AssetManager.h"
#include "AssetCache.h"
#include "RexAsset.h"
#include "Framework.h"
#include "EventManager.h"
using namespace RexTypes;
namespace Asset
{
AssetManager::AssetManager(Foundation::Framework* framework) :
framework_(framework)
{
Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
event_category_ = event_manager->RegisterEventCategory("Asset");
event_manager->RegisterEvent(event_category_, Events::ASSET_READY, "AssetReady");
event_manager->RegisterEvent(event_category_, Events::ASSET_PROGRESS, "AssetProgress");
event_manager->RegisterEvent(event_category_, Events::ASSET_CANCELED, "AssetCanceled");
// Create asset cache
cache_ = AssetCachePtr(new AssetCache(framework_));
}
AssetManager::~AssetManager()
{
cache_.reset();
providers_.clear();
}
Foundation::AssetPtr AssetManager::GetAsset(const std::string& asset_id, const std::string& asset_type)
{
return GetFromCache(asset_id);
}
bool AssetManager::IsValidId(const std::string& asset_id)
{
AssetProviderVector::iterator i = providers_.begin();
while (i != providers_.end())
{
// See if a provider can handle request
if ((*i)->IsValidId(asset_id))
return true;
++i;
}
return false; // No provider could identify ID as valid
}
request_tag_t AssetManager::RequestAsset(const std::string& asset_id, const std::string& asset_type)
{
request_tag_t tag = framework_->GetEventManager()->GetNextRequestTag();
Foundation::AssetPtr asset = GetFromCache(asset_id);
if (asset)
{
Events::AssetReady* event_data = new Events::AssetReady(asset->GetId(), asset->GetType(), asset, tag);
framework_->GetEventManager()->SendDelayedEvent(event_category_, Events::ASSET_READY, Foundation::EventDataPtr(event_data));
return tag;
}
AssetProviderVector::iterator i = providers_.begin();
while (i != providers_.end())
{
// See if a provider can handle request
if ((*i)->RequestAsset(asset_id, asset_type, tag))
return tag;
++i;
}
AssetModule::LogInfo("No asset provider would accept request for asset " + asset_id);
return 0;
}
Foundation::AssetPtr AssetManager::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received)
{
if (!received)
return Foundation::AssetPtr();
// See if any provider has ongoing transfer for this asset
AssetProviderVector::iterator i = providers_.begin();
while (i != providers_.end())
{
if ((*i)->InProgress(asset_id))
return (*i)->GetIncompleteAsset(asset_id, asset_type, received);
++i;
}
// No transfer, either get complete asset or nothing
return GetAsset(asset_id, asset_type);
// Not enough bytes
return Foundation::AssetPtr();
}
bool AssetManager::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous)
{
// See if any provider has ongoing transfer for this asset
AssetProviderVector::iterator i = providers_.begin();
while (i != providers_.end())
{
if ((*i)->InProgress(asset_id))
return (*i)->QueryAssetStatus(asset_id, size, received, received_continuous);
++i;
}
// If not ongoing, check cache
Foundation::AssetPtr asset = GetFromCache(asset_id);
if (asset)
{
size = asset->GetSize();
received = asset->GetSize();
received_continuous = asset->GetSize();
return true;
}
return false;
}
void AssetManager::StoreAsset(Foundation::AssetPtr asset)
{
cache_->StoreAsset(asset);
}
bool AssetManager::RegisterAssetProvider(Foundation::AssetProviderPtr asset_provider)
{
if (!asset_provider)
{
AssetModule::LogError("Attempted to register asset provider with null pointer");
return false;
}
AssetProviderVector::iterator i = providers_.begin();
while (i != providers_.end())
{
if ((*i) == asset_provider)
{
AssetModule::LogWarning("Asset provider " + asset_provider->Name() + " already registered");
return false;
}
++i;
}
providers_.push_back(asset_provider);
AssetModule::LogInfo("Asset provider " + asset_provider->Name() + " registered");
return true;
}
bool AssetManager::UnregisterAssetProvider(Foundation::AssetProviderPtr asset_provider)
{
if (!asset_provider)
{
AssetModule::LogError("Attempted to unregister asset provider with null pointer");
return false;
}
AssetProviderVector::iterator i = providers_.begin();
while (i != providers_.end())
{
if ((*i) == asset_provider)
{
providers_.erase(i);
AssetModule::LogInfo("Asset provider " + asset_provider->Name() + " unregistered");
return true;
}
++i;
}
AssetModule::LogWarning("Asset provider " + asset_provider->Name() + " not found, could not unregister");
return false;
}
void AssetManager::Update(f64 frametime)
{
// Update all providers
AssetProviderVector::iterator i = providers_.begin();
while (i != providers_.end())
{
(*i)->Update(frametime);
++i;
}
// Update cache
cache_->Update(frametime);
}
Foundation::AssetPtr AssetManager::GetFromCache(const std::string& asset_id)
{
// First check memory cache
Foundation::AssetPtr asset = cache_->GetAsset(asset_id, true, false);
if (asset)
return asset;
// If transfer in progress in any of the providers, do not check disk cache again
AssetProviderVector::iterator i = providers_.begin();
while (i != providers_.end())
{
if ((*i)->InProgress(asset_id))
return Foundation::AssetPtr();
++i;
}
// Last check disk cache
asset = cache_->GetAsset(asset_id, false, true);
return asset;
}
Foundation::AssetCacheInfoMap AssetManager::GetAssetCacheInfo()
{
Foundation::AssetCacheInfoMap ret;
if (!cache_)
return ret;
const AssetCache::AssetMap& assets = cache_->GetAssets();
AssetCache::AssetMap::const_iterator i = assets.begin();
while (i != assets.end())
{
ret[i->second->GetType()].count_++;
ret[i->second->GetType()].size_ += i->second->GetSize();
++i;
}
return ret;
}
Foundation::AssetTransferInfoVector AssetManager::GetAssetTransferInfo()
{
Foundation::AssetTransferInfoVector ret;
AssetProviderVector::iterator i = providers_.begin();
while (i != providers_.end())
{
Foundation::AssetTransferInfoVector transfers = (*i)->GetTransferInfo();
ret.insert(ret.end(), transfers.begin(), transfers.end());
++i;
}
return ret;
}
}
| [
"cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3",
"loorni@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jaakkoallander@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
7
],
[
10,
153
],
[
155,
215
]
],
[
[
8,
9
]
],
[
[
154,
154
],
[
216,
246
]
],
[
[
247,
247
]
]
]
|
624e970d78b5e0159d8662360bd550478be42535 | 192753ab43c949e8560e54792a64a4a57cb6d246 | /src/uslscore/USLuaState.h | c91d39acae3e43a8b2019d8a80e8886b393d0ae1 | []
| no_license | mobilehub/moai-beta | 5f2fd8c180270c3cbbc90b8b275f266533cb572b | 727d77fdf6232261e525180b8a202dd4337e6d94 | refs/heads/master | 2021-01-16T20:59:14.953472 | 2011-07-12T17:09:29 | 2011-07-12T17:09:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,949 | h | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#ifndef LUASTATE_H
#define LUASTATE_H
#include <uslscore/STLString.h>
#include <uslscore/USRect.h>
#include <uslscore/USVec2D.h>
#include <uslscore/USVec3D.h>
class USCipher;
class USLuaRef;
class USStreamFormatter;
#define LUA_SETUP(type,str) \
USLuaState state ( L ); \
if ( !state.CheckParams ( 1, str )) return 0; \
type* self = state.GetLuaObject < type >( 1 ); \
if ( !self ) return 0;
#define LUA_SETUP_STATIC(str) \
USLuaState state ( L ); \
if ( !state.CheckParams ( 1, str )) return 0;
//================================================================//
// USLuaState
//================================================================//
class USLuaState {
private:
lua_State* mState;
//----------------------------------------------------------------//
bool Decode ( int idx, USCipher& cipher );
bool Encode ( int idx, USCipher& cipher );
bool Transform ( int idx, USStreamFormatter& formatter );
public:
friend class USLuaStateHandle;
//----------------------------------------------------------------//
int AbsIndex ( int idx );
bool Base64Decode ( int idx );
bool Base64Encode ( int idx );
bool CheckParams ( int idx, cc8* format ); // "BCFLNSTU"
void CopyToTop ( int idx );
int DebugCall ( int nArgs, int nResults );
bool Deflate ( int idx, int level, int windowBits );
void GetField ( int idx, cc8* name );
void GetField ( int idx, int key );
STLString GetField ( int idx, cc8* key, cc8* value );
STLString GetField ( int idx, int key, cc8* value );
bool GetFieldWithType ( int idx, cc8* name, int type );
bool GetFieldWithType ( int idx, int key, int type );
void* GetPtrUserData ( int idx );
USLuaRef GetStrongRef ( int idx );
int GetTop ();
void* GetUserData ( int idx, void* value );
void* GetUserData ( int idx, cc8* name, void* value );
STLString GetValue ( int idx, cc8* value );
USLuaRef GetWeakRef ( int idx );
bool HasField ( int idx, cc8* name );
bool HasField ( int idx, int key );
bool HasField ( int idx, cc8* name, int type );
bool HasField ( int idx, int name, int type );
bool Inflate ( int idx, int windowBits );
bool IsNil ();
bool IsTableOrUserdata ( int idx );
bool IsType ( int idx, int type );
bool IsType ( int idx, cc8* name, int type );
void LoadLibs ();
void MoveToTop ( int idx );
void Pop ( int n );
bool PrepMemberFunc ( int idx, cc8* name );
bool PrintErrors ( int status );
void PrintStackTrace ( int level );
void Push ( bool value );
void Push ( cc8* value );
void Push ( double value );
void Push ( float value );
void Push ( int value );
void Push ( u16 value );
void Push ( u32 value );
void Push ( u64 value );
void Push ( lua_CFunction value );
void Push ( USLuaRef& ref );
void PushPtrUserData ( void* ptr );
int PushTableItr ( int idx );
void RegisterModule ( cc8* name, lua_CFunction loader, bool autoLoad );
int RelIndex ( int idx );
void SetPath ( cc8* path );
void SetTop ( int top );
bool TableItrNext ( int itr );
USLuaState ();
USLuaState ( lua_State* state );
virtual ~USLuaState ();
int YieldThread ( int nResults );
//----------------------------------------------------------------//
inline lua_State* operator -> () const {
return mState;
};
//----------------------------------------------------------------//
inline lua_State& operator * () const {
return *mState;
};
//----------------------------------------------------------------//
inline operator lua_State* () {
return mState;
};
//----------------------------------------------------------------//
inline operator bool () {
return ( this->mState != 0 );
}
//----------------------------------------------------------------//
template < typename TYPE > TYPE GetField ( int idx, int key, TYPE value );
template < typename TYPE > TYPE GetField ( int idx, cc8* key, TYPE value );
template < typename TYPE > TYPE* GetLuaObject ( int idx );
template < typename TYPE > TYPE* GetLuaObject ( int idx, cc8* name );
template < typename TYPE > USMetaRect < TYPE > GetRect ( int idx );
template < typename TYPE > TYPE GetValue ( int idx, TYPE value );
template < typename TYPE > USMetaVec2D < TYPE > GetVec2D ( int idx );
template < typename TYPE > USMetaVec3D < TYPE > GetVec3D ( int idx );
template < typename TYPE > void ReadArray ( int size, TYPE* values, TYPE value );
template < typename TYPE > void SetField ( int idx, cc8* key, TYPE value );
template < typename TYPE > void SetFieldByIndex ( int idx, int key, TYPE value );
template < typename TYPE > void WriteArray ( int size, TYPE* values );
};
//----------------------------------------------------------------//
template <> bool USLuaState::GetValue < bool > ( int idx, bool value );
template <> cc8* USLuaState::GetValue < cc8* > ( int idx, cc8* value );
template <> double USLuaState::GetValue < double > ( int idx, double value );
template <> float USLuaState::GetValue < float > ( int idx, float value );
template <> int USLuaState::GetValue < int > ( int idx, int value );
template <> uint USLuaState::GetValue < uint > ( int idx, uint value );
template <> u8 USLuaState::GetValue < u8 > ( int idx, u8 value );
template <> u16 USLuaState::GetValue < u16 > ( int idx, u16 value );
template <> u32 USLuaState::GetValue < u32 > ( int idx, u32 value );
template <> u64 USLuaState::GetValue < u64 > ( int idx, u64 value );
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
85
],
[
87,
145
],
[
147,
148
]
],
[
[
86,
86
],
[
146,
146
]
]
]
|
baeec19dda22c7f597dfebcb7d98634013c849dd | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.3/cbear.berlios.de/range/transform.hpp | 442e09c0831ba08e593ddf69142e8af10e426e1f | [
"MIT"
]
| permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,872 | hpp | /*
The MIT License
Copyright (c) 2005 C Bear (http://cbear.berlios.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CBEAR_BERLIOS_DE_RANGE_TRANSFORM_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_RANGE_TRANSFORM_HPP_INCLUDED
// std::transform
#include <algorithm>
#include <cbear.berlios.de/range/begin.hpp>
#include <cbear.berlios.de/range/end.hpp>
namespace cbear_berlios_de
{
namespace range
{
/** @brief Assigns through every iterator I in the range
[result, result + size(R)) a new value equal to op(at(R, I - result)).
@result result + size(R).
@sa std::transform.
*/
template<class InputRange, class OutputIterator, class UnaryOperation>
OutputIterator
transform(InputRange &R, OutputIterator result, UnaryOperation op)
{
return std::transform(range::begin(R), range::end(R), result, op);
}
}
}
#endif
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
]
| [
[
[
1,
54
]
]
]
|
ca9892d2144dc628ab5be4d1d65ab2935b077a9f | bcc12a00ac9a0f53b6c6f026828b03b4433ae237 | /easysmb.h | fcefb67be8c00a41c897a2035a744aad57be3691 | []
| no_license | snowdream/easysmb | 98edd18349e52af7241a3416edaef83927df5637 | 43450014ee3b47e61f2e562771886f3778bb9f98 | refs/heads/master | 2020-05-18T12:00:13.097648 | 2011-04-21T05:55:40 | 2011-04-21T05:55:40 | 1,638,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 817 | h | #ifndef EASYSMB_H
#define EASYSMB_H
#include "rbrowse.h"
#include "lbrowse.h"
#include "host.h"
#include <QMainWindow>
#include <QtGui>
class easysmb : public QMainWindow
{
Q_OBJECT
public:
easysmb(QWidget *parent = 0);
private slots:
void keyPressEvent(QKeyEvent *event);
void uploadIt();
void downloadIt();
void showAbout();
void setIcon();
void setList();
private:
QAction *uploadAct;
QAction *downloadAct;
QAction *iconAct;
QAction *listAct;
QAction *aboutAct;
QAction *closeAct;
QMenu *fileMenu;
QMenu *viewMenu;
QMenu *aboutMenu;
QToolBar *toolBar;
host *rh;
lbrowse *lb;
rbrowse *rb;
};
#endif
| [
"[email protected]@e87ba980-8714-11de-8988-25e8a898b690"
]
| [
[
[
1,
39
]
]
]
|
fabf7f39fe41334d7ea3805134de83f8b29c956f | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/include/aosl/layer_ref.inl | 4a936a59df69b8c6e94834087745af9ba426f15f | []
| no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | inl | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
#ifndef AOSLCPP_AOSL__LAYER_REF_INL
#define AOSLCPP_AOSL__LAYER_REF_INL
// Begin prologue.
//
//
// End prologue.
namespace aosl
{
// Layer_ref
//
inline
Layer_ref::
Layer_ref (const char* s)
: ::xml_schema::String (s)
{
}
inline
Layer_ref::
Layer_ref (const ::std::string& s)
: ::xml_schema::String (s)
{
}
inline
Layer_ref::
Layer_ref (const Layer_ref& o,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xml_schema::String (o, f, c)
{
}
}
// Begin epilogue.
//
//
// End epilogue.
#endif // AOSLCPP_AOSL__LAYER_REF_INL
| [
"klaim@localhost"
]
| [
[
[
1,
52
]
]
]
|
d76bbef715a525a2e907150982ea7b88af822cfe | 388d7d901492224b76919af3be6d1210362444e1 | /tio/pch.cpp | 693a104c0672db30cb7c84fc4e781564cc85e87b | []
| no_license | ederfreire/tio | 159e958a9e98dd4686b9363b1dd459f3b27215c9 | 9040d8c7241ea713f3f6a60983ac3de50282f21c | refs/heads/master | 2020-04-10T09:25:42.301209 | 2011-03-22T21:34:18 | 2011-03-22T21:34:18 | 1,518,698 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | cpp | /*
Tio: The Information Overlord
Copyright 2010 Rodrigo Strauss (http://www.1bit.com.br)
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 "pch.h"
| [
"[email protected]"
]
| [
[
[
1,
17
]
]
]
|
1017251e2917a77a8cc8bea06b724930c1202368 | 24bc1634133f5899f7db33e5d9692ba70940b122 | /src/ammo/network/connectionfactory.hpp | 14870ec11b88b08e7668c7e2a50976608e722cec | []
| no_license | deft-code/ammo | 9a9cd9bd5fb75ac1b077ad748617613959dbb7c9 | fe4139187dd1d371515a2d171996f81097652e99 | refs/heads/master | 2016-09-05T08:48:51.786465 | 2009-10-09T05:49:00 | 2009-10-09T05:49:00 | 32,252,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,554 | hpp | #ifndef CONNFACTORY_H_INCLUDED
#define CONNFACTORY_H_INCLUDED
#include "ReplicaManager2.h"
#include "ammo/game/gamestate.hpp"
namespace ammo
{
class GameState;
// This object is responsible for creating all of our game objects
// on the client side when the server tells the client to construct
// an object.
class ReplicaObjectConstructor : public RakNet::Connection_RM2
{
public:
ReplicaObjectConstructor(GameState* gameState);
// Callback to construct objects. This should not be called directly.
// The replica2manager object will hand a packet to this method, and expect
// to receive a constructed object based on the contents of the packet.
// @param replicaData The byte array that was sent from the server when the object was serialized
// @param sender The address of the server that sent this object
// @param type The serializationType, you will generally not need to use this
// @param replicaManager The local replicaManager, should it be needed
// @param timestamp The time that was sent with this packet in the serializeconstruction method on the server
// @param networkId The networkId that will be assigned to this object
// @param networkIdCollision True if the networkid that should be assigned is already in use locally
RakNet::Replica2* Construct(RakNet::BitStream* replicaData, SystemAddress sender, RakNet::SerializationType type,
RakNet::ReplicaManager2* replicaManager, RakNetTime timestamp, NetworkID networkId, bool networkIDCollision);
private:
GameState* _gameState;
};
// Raknet allows us to use different object factories on each peer, which means
// there must be a factory factory. Because we are only using one type of Object
// Factory, this is kinda redundant, but we have to implement this.
class ReplicaObjectConstructorFactory : public RakNet::Connection_RM2Factory
{
public:
// gameState - The gamestate that should register the objects the
// product of this factory creates.
ReplicaObjectConstructorFactory(GameState* gameState) { _gameState = gameState;}
// We only have one factory, so this method will always return that one object
virtual RakNet::Connection_RM2* AllocConnection(void) const
{
return new ReplicaObjectConstructor(_gameState);
}
virtual void DeallocConnection(RakNet::Connection_RM2* s) const
{
delete s;
}
private:
GameState* _gameState;
};
}
#endif // CONNFACTORY_H_INCLUDED
| [
"PhillipSpiess@d8b90d80-bb63-11dd-bed2-db724ec49875",
"j.nick.terry@d8b90d80-bb63-11dd-bed2-db724ec49875"
]
| [
[
[
1,
56
]
],
[
[
57,
58
]
]
]
|
31ce3c7ab9435e5f7bb5a228c9e87a71cd96b5b2 | 81ff4fb051a612ea7c7e9e7733de6a86ad846504 | /notepad_plus_m/scintilla/src/KeyWords.cxx | d06251d8221882d0b3a8acc6a1c50c7361714445 | [
"LicenseRef-scancode-scintilla"
]
| permissive | kuckaogh/testprojectoned | 2e731dd2dbc994adb7775d90cd1b05b5cb2b4764 | e7e8cb3457af7dddc5546ba8b516c843acfe3f39 | refs/heads/master | 2021-01-22T17:53:13.521646 | 2011-03-23T01:20:06 | 2011-03-23T01:20:06 | 32,550,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,294 | cxx | // Scintilla source code edit control
/** @file KeyWords.cxx
** Colourise for particular languages.
**/
// Copyright 1998-2002 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
/**
* Creates an array that points into each word in the string and puts \0 terminators
* after each word.
*/
static char **ArrayFromWordList(char *wordlist, int *len, bool onlyLineEnds = false) {
int prev = '\n';
int words = 0;
// For rapid determination of whether a character is a separator, build
// a look up table.
bool wordSeparator[256];
for (int i=0;i<256; i++) {
wordSeparator[i] = false;
}
wordSeparator['\r'] = true;
wordSeparator['\n'] = true;
if (!onlyLineEnds) {
wordSeparator[' '] = true;
wordSeparator['\t'] = true;
}
for (int j = 0; wordlist[j]; j++) {
int curr = static_cast<unsigned char>(wordlist[j]);
if (!wordSeparator[curr] && wordSeparator[prev])
words++;
prev = curr;
}
char **keywords = new char *[words + 1];
if (keywords) {
words = 0;
prev = '\0';
size_t slen = strlen(wordlist);
for (size_t k = 0; k < slen; k++) {
if (!wordSeparator[static_cast<unsigned char>(wordlist[k])]) {
if (!prev) {
keywords[words] = &wordlist[k];
words++;
}
} else {
wordlist[k] = '\0';
}
prev = wordlist[k];
}
keywords[words] = &wordlist[slen];
*len = words;
} else {
*len = 0;
}
return keywords;
}
void WordList::Clear() {
if (words) {
delete []list;
delete []words;
}
words = 0;
list = 0;
len = 0;
sorted = false;
}
void WordList::Set(const char *s) {
list = new char[strlen(s) + 1];
strcpy(list, s);
sorted = false;
words = ArrayFromWordList(list, &len, onlyLineEnds);
}
extern "C" int cmpString(const void *a1, const void *a2) {
// Can't work out the correct incantation to use modern casts here
return strcmp(*(char**)(a1), *(char**)(a2));
}
static void SortWordList(char **words, unsigned int len) {
qsort(reinterpret_cast<void*>(words), len, sizeof(*words),
cmpString);
}
bool WordList::InList(const char *s) {
if (0 == words)
return false;
if (!sorted) {
sorted = true;
SortWordList(words, len);
for (unsigned int k = 0; k < (sizeof(starts) / sizeof(starts[0])); k++)
starts[k] = -1;
for (int l = len - 1; l >= 0; l--) {
unsigned char indexChar = words[l][0];
starts[indexChar] = l;
}
}
unsigned char firstChar = s[0];
int j = starts[firstChar];
if (j >= 0) {
while ((unsigned char)words[j][0] == firstChar) {
if (s[1] == words[j][1]) {
const char *a = words[j] + 1;
const char *b = s + 1;
while (*a && *a == *b) {
a++;
b++;
}
if (!*a && !*b)
return true;
}
j++;
}
}
j = starts['^'];
if (j >= 0) {
while (words[j][0] == '^') {
const char *a = words[j] + 1;
const char *b = s;
while (*a && *a == *b) {
a++;
b++;
}
if (!*a)
return true;
j++;
}
}
return false;
}
/** similar to InList, but word s can be a substring of keyword.
* eg. the keyword define is defined as def~ine. This means the word must start
* with def to be a keyword, but also defi, defin and define are valid.
* The marker is ~ in this case.
*/
bool WordList::InListAbbreviated(const char *s, const char marker) {
if (0 == words)
return false;
if (!sorted) {
sorted = true;
SortWordList(words, len);
for (unsigned int k = 0; k < (sizeof(starts) / sizeof(starts[0])); k++)
starts[k] = -1;
for (int l = len - 1; l >= 0; l--) {
unsigned char indexChar = words[l][0];
starts[indexChar] = l;
}
}
unsigned char firstChar = s[0];
int j = starts[firstChar];
if (j >= 0) {
while (words[j][0] == firstChar) {
bool isSubword = false;
int start = 1;
if (words[j][1] == marker) {
isSubword = true;
start++;
}
if (s[1] == words[j][start]) {
const char *a = words[j] + start;
const char *b = s + 1;
while (*a && *a == *b) {
a++;
if (*a == marker) {
isSubword = true;
a++;
}
b++;
}
if ((!*a || isSubword) && !*b)
return true;
}
j++;
}
}
j = starts['^'];
if (j >= 0) {
while (words[j][0] == '^') {
const char *a = words[j] + 1;
const char *b = s;
while (*a && *a == *b) {
a++;
b++;
}
if (!*a)
return true;
j++;
}
}
return false;
}
const LexerModule *LexerModule::base = 0;
int LexerModule::nextLanguage = SCLEX_AUTOMATIC+1;
LexerModule::LexerModule(int language_,
LexerFunction fnLexer_,
const char *languageName_,
LexerFunction fnFolder_,
const char * const wordListDescriptions_[],
int styleBits_) :
language(language_),
fnLexer(fnLexer_),
fnFolder(fnFolder_),
wordListDescriptions(wordListDescriptions_),
styleBits(styleBits_),
languageName(languageName_) {
next = base;
base = this;
if (language == SCLEX_AUTOMATIC) {
language = nextLanguage;
nextLanguage++;
}
}
int LexerModule::GetNumWordLists() const {
if (wordListDescriptions == NULL) {
return -1;
} else {
int numWordLists = 0;
while (wordListDescriptions[numWordLists]) {
++numWordLists;
}
return numWordLists;
}
}
const char *LexerModule::GetWordListDescription(int index) const {
static const char *emptyStr = "";
PLATFORM_ASSERT(index < GetNumWordLists());
if (index >= GetNumWordLists()) {
return emptyStr;
} else {
return wordListDescriptions[index];
}
}
int LexerModule::GetStyleBitsNeeded() const {
return styleBits;
}
const LexerModule *LexerModule::Find(int language) {
const LexerModule *lm = base;
while (lm) {
if (lm->language == language) {
return lm;
}
lm = lm->next;
}
return 0;
}
const LexerModule *LexerModule::Find(const char *languageName) {
if (languageName) {
const LexerModule *lm = base;
while (lm) {
if (lm->languageName && 0 == strcmp(lm->languageName, languageName)) {
return lm;
}
lm = lm->next;
}
}
return 0;
}
void LexerModule::Lex(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const {
if (fnLexer)
fnLexer(startPos, lengthDoc, initStyle, keywordlists, styler);
}
void LexerModule::Fold(unsigned int startPos, int lengthDoc, int initStyle,
WordList *keywordlists[], Accessor &styler) const {
if (fnFolder) {
int lineCurrent = styler.GetLine(startPos);
// Move back one line in case deletion wrecked current line fold state
if (lineCurrent > 0) {
lineCurrent--;
int newStartPos = styler.LineStart(lineCurrent);
lengthDoc += startPos - newStartPos;
startPos = newStartPos;
initStyle = 0;
if (startPos > 0) {
initStyle = styler.StyleAt(startPos - 1);
}
}
fnFolder(startPos, lengthDoc, initStyle, keywordlists, styler);
}
}
// Alternative historical name for Scintilla_LinkLexers
int wxForceScintillaLexers(void) {
return Scintilla_LinkLexers();
}
// To add or remove a lexer, add or remove its file and run LexGen.py.
// Force a reference to all of the Scintilla lexers so that the linker will
// not remove the code of the lexers.
int Scintilla_LinkLexers() {
static int forcer = 0;
// Shorten the code that declares a lexer and ensures it is linked in by calling a method.
#define LINK_LEXER(lexer) extern LexerModule lexer; forcer += lexer.GetLanguage();
//++Autogenerated -- run src/LexGen.py to regenerate
//**\(\tLINK_LEXER(\*);\n\)
LINK_LEXER(lmAbaqus);
LINK_LEXER(lmAda);
LINK_LEXER(lmAns1);
LINK_LEXER(lmAPDL);
LINK_LEXER(lmAsm);
LINK_LEXER(lmASY);
LINK_LEXER(lmAU3);
LINK_LEXER(lmAVE);
LINK_LEXER(lmBaan);
LINK_LEXER(lmBash);
LINK_LEXER(lmBatch);
LINK_LEXER(lmBlitzBasic);
LINK_LEXER(lmBullant);
LINK_LEXER(lmCaml);
LINK_LEXER(lmClw);
LINK_LEXER(lmClwNoCase);
LINK_LEXER(lmCmake);
LINK_LEXER(lmCOBOL);
LINK_LEXER(lmConf);
LINK_LEXER(lmCPP);
LINK_LEXER(lmCPPNoCase);
LINK_LEXER(lmCsound);
LINK_LEXER(lmCss);
LINK_LEXER(lmD);
LINK_LEXER(lmDiff);
LINK_LEXER(lmEiffel);
LINK_LEXER(lmEiffelkw);
LINK_LEXER(lmErlang);
LINK_LEXER(lmErrorList);
LINK_LEXER(lmESCRIPT);
LINK_LEXER(lmF77);
LINK_LEXER(lmFlagShip);
LINK_LEXER(lmForth);
LINK_LEXER(lmFortran);
LINK_LEXER(lmFreeBasic);
LINK_LEXER(lmGAP);
LINK_LEXER(lmGui4Cli);
LINK_LEXER(lmHaskell);
LINK_LEXER(lmHTML);
LINK_LEXER(lmInno);
LINK_LEXER(lmKix);
LINK_LEXER(lmLatex);
LINK_LEXER(lmLISP);
LINK_LEXER(lmLot);
LINK_LEXER(lmLout);
LINK_LEXER(lmLua);
LINK_LEXER(lmMagikSF);
LINK_LEXER(lmMake);
LINK_LEXER(lmMatlab);
LINK_LEXER(lmMETAPOST);
LINK_LEXER(lmMMIXAL);
LINK_LEXER(lmMSSQL);
LINK_LEXER(lmMySQL);
LINK_LEXER(lmNimrod);
LINK_LEXER(lmNncrontab);
LINK_LEXER(lmNsis);
LINK_LEXER(lmNull);
LINK_LEXER(lmObjC);
LINK_LEXER(lmOctave);
LINK_LEXER(lmOpal);
LINK_LEXER(lmPascal);
LINK_LEXER(lmPB);
LINK_LEXER(lmPerl);
LINK_LEXER(lmPHPSCRIPT);
LINK_LEXER(lmPLM);
LINK_LEXER(lmPo);
LINK_LEXER(lmPOV);
LINK_LEXER(lmPowerPro);
LINK_LEXER(lmPowerShell);
LINK_LEXER(lmProgress);
LINK_LEXER(lmProps);
LINK_LEXER(lmPS);
LINK_LEXER(lmPureBasic);
LINK_LEXER(lmPython);
LINK_LEXER(lmR);
LINK_LEXER(lmREBOL);
LINK_LEXER(lmRuby);
LINK_LEXER(lmScriptol);
LINK_LEXER(lmSearchResult);
LINK_LEXER(lmSmalltalk);
LINK_LEXER(lmSML);
LINK_LEXER(lmSorc);
LINK_LEXER(lmSpecman);
LINK_LEXER(lmSpice);
LINK_LEXER(lmSQL);
LINK_LEXER(lmTACL);
LINK_LEXER(lmTADS3);
LINK_LEXER(lmTAL);
LINK_LEXER(lmTCL);
LINK_LEXER(lmTeX);
LINK_LEXER(lmUserDefine);
LINK_LEXER(lmVB);
LINK_LEXER(lmVBScript);
LINK_LEXER(lmVerilog);
LINK_LEXER(lmVHDL);
LINK_LEXER(lmXML);
LINK_LEXER(lmYAML);
//--Autogenerated -- end of automatically generated section
return 1;
}
| [
"gph.kevin@0a44f7b2-fd79-11de-a344-e7ee0817407e"
]
| [
[
[
1,
431
]
]
]
|
a8a22b728bb7c4d86d0921debfe05b21db7fde25 | b0fe69a13b1f10295788e8ddd243354c9cb0bfbe | /amv_core/WSharedLib.cpp | e5b9ab48cdcab1d0ea25028a663d5a691b607bf8 | []
| no_license | Surrog/avmfrandflo | d2346ce281b336eaeb4b79ec8303ed4f6c45774d | bfbaa57f7e52ff36352eaee7ca99d56ff64d16b0 | refs/heads/master | 2021-01-22T13:26:32.415282 | 2010-06-13T08:38:02 | 2010-06-13T08:38:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,240 | cpp |
#include "WSharedLib.h"
#ifdef WIN32
WSharedLib::~WSharedLib()
{}
ASharedLib::lib_handler WSharedLib::LoadLib(std::string name)
{
HMODULE dllHdl = LoadLibrary(TEXT(name.data()));
return dllHdl;
}
void* WSharedLib::getFunc(ASharedLib::lib_handler& hdl, std::string funcName)
{
return reinterpret_cast<void*>(GetProcAddress(hdl, funcName.data()));
}
bool WSharedLib::closeLib(lib_handler& hdl)
{
if (FreeLibrary(hdl))
return true;
return false;
}
void WSharedLib::openLibFrom(std::string dir, std::vector<ASharedLib::lib_handler>& tab)
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
const char match[] = "*.dll";
if (dir != "")
dir += "\\";
dir += match;
hFind = FindFirstFileEx(dir.data(), FindExInfoStandard, &FindFileData,
FindExSearchNameMatch, NULL, 0 );
if (hFind != INVALID_HANDLE_VALUE)
{
tab.push_back(LoadLib(FindFileData.cFileName));
while (FindNextFile(hFind, &FindFileData))
{
tab.push_back(LoadLib(FindFileData.cFileName));
}
}
else
std::cerr << "no shared lib found" << std::endl;
FindClose(hFind);
}
#endif
| [
"Florian Chanioux@localhost"
]
| [
[
[
1,
51
]
]
]
|
23b67bfe514edc1725dfefbef16454b5ad0187df | 49b6646167284329aa8644c8cf01abc3d92338bd | /SEP2_RELEASE/Tests/Test_IRQ.cpp | a23b40cc43a16a99b45ff255e0ea54bd7d081c51 | []
| no_license | StiggyB/javacodecollection | 9d017b87b68f8d46e09dcf64650bd7034c442533 | bdce3ddb7a56265b4df2202d24bf86a06ecfee2e | refs/heads/master | 2020-08-08T22:45:47.779049 | 2011-10-24T12:10:08 | 2011-10-24T12:10:08 | 32,143,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 714 | cpp | /**
* Testing Class for IRQ
*
* SE2 (+ SY and PL) Project SoSe 2011
*
* Authors: Rico Flaegel,
* Tell Mueller-Pettenpohl,
* Torsten Krane,
* Jan Quenzel
*
* Prepares some Testing stuff for the Interrupts.
*
* Inherits: thread::HAWThread
*/
#include "Test_IRQ.h"
/**
* pointer to the CoreController
*/
Test_IRQ::Test_IRQ() {
/**
* gaining IO privileges
*/
if (-1==ThreadCtl(_NTO_TCTL_IO, 0)) {
std::cout << "error for IO Control" << std::endl;
}
/**
* gets a pointer to an instance of the CoreController
*/
h = HALCore::getInstance();
}
Test_IRQ::~Test_IRQ() {
}
void Test_IRQ::execute(void*){
}
void Test_IRQ::shutdown(){
}
| [
"[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1"
]
| [
[
[
1,
44
]
]
]
|
d9cd429a1901ec41cfab8829d7042cfcf775cacd | f838c6ad5dd7ffa6d9687b0eb49d5381e6f2e776 | /branches/[25.11.2007]arcoder_fixup/src/libwic/encoder.cpp | 317553a5f8700e796f7816e629aaa29c398d5022 | []
| no_license | BackupTheBerlios/wiccoder-svn | e773acb186aa9966eaf7848cda454ab0b5d948c5 | c329182382f53d7a427caec4b86b11968d516af9 | refs/heads/master | 2021-01-11T11:09:56.248990 | 2009-08-19T11:28:23 | 2009-08-19T11:28:23 | 40,806,440 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 130,426 | cpp | /*! \file encoder.cpp
\version 0.0.1
\author mice, ICQ: 332-292-380, mailto:[email protected]
\brief Реализация класса wic::encoder
\todo Более подробно описать файл encoder.h
*/
////////////////////////////////////////////////////////////////////////////////
// include
// standard C++ headers
#include <math.h>
// libwic headers
#include <wic/libwic/encoder.h>
////////////////////////////////////////////////////////////////////////////////
// wic namespace
namespace wic {
////////////////////////////////////////////////////////////////////////////////
// encoder class public definitions
/*! \param[in] width Ширина изображения.
\param[in] height Высота изображения.
\param[in] lvls Количество уровней вейвлет преобразования.
*/
encoder::encoder(const sz_t width, const sz_t height, const sz_t lvls):
_wtree(width, height, lvls),
_acoder(width * height * sizeof(w_t) * 4),
_optimize_tree_callback(0), _optimize_tree_callback_param(0),
_optimize_callback(0), _optimize_callback_param(0)
#ifdef LIBWIC_USE_DBG_SURFACE
, _dbg_opt_surface(width, height), _dbg_enc_surface(width, height),
_dbg_dec_surface(width, height)
#endif
{
// проверка утверждений
assert(MINIMUM_LEVELS <= lvls);
#ifdef LIBWIC_DEBUG
_dbg_out_stream.open("dumps/[encoder]debug.out",
std::ios_base::out | std::ios_base::app);
if (_dbg_out_stream.good())
{
time_t t;
time(&t);
_dbg_out_stream << std::endl << ctime(&t) << std::endl;
}
#endif
}
/*!
*/
encoder::~encoder() {
}
/*! \param[in] callback Функция обратного вызова
\param[in] param Пользовательский параметр, передаваемый в функцию
обратного вызова
*/
void encoder::optimize_tree_callback(const optimize_tree_callback_f &callback,
void *const param)
{
_optimize_tree_callback = callback;
_optimize_tree_callback_param = param;
}
/*! \param[in] callback Функция обратного вызова
\param[in] param Пользовательский параметр, передаваемый в функцию
обратного вызова
*/
void encoder::optimize_callback(const optimize_callback_f &callback,
void *const param)
{
_optimize_callback = callback;
_optimize_callback_param = param;
}
/*! \param[in] w Спектр вейвлет преобразования входного изображения для
кодирования
\param[in] q Квантователь. Чем больше значение (величина) квантователя,
тем большую степень сжатия можно получить. Однако при увеличении
квантователя качество восстановленного (декодированного) изображения
ухудшается. Значение квантователя должно быть больше <i>1</i>.
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами. Чем больше данный
параметр, тем больший приоритет будет отдан битовым затратам.
Соответственно, при 0 будет учитываться только ошибка кодирования.
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\return Результат проведённого кодирования
Данный механизм кодирования применяется, когда оптимальные (или
субоптимальные) значения параметров <i>q</i> и <i>lambda</i> известны
заранее. Этот метод является самым быстрым так как производит операции
оптимизации топологии и кодирования только по одному разу.
Стоит заметить, что метод также производит квантование спектра выбранным
квантователем <i>q</i>, поэтому его не желательно использовать в
ситуациях когда необходимо получить результаты сжатия одного изображения
с разным параметром <i>lambda</i>. Для таких случаев лучше использовать
более быструю функцию cheap_encode(), которая не производит квантования
коэффициентов спектра (но может быть ещё не реализованна =).
Код функции использует макрос #OPTIMIZATION_USE_VIRTUAL_ENCODING. Если он
определён будет производиться виртуальное кодирование коэффициентов, что
несколько быстрее. Однако не все реализации битовых кодеров могут
поддерживать это.
Вся информация необходимая для успешного декодирования (кроме информации
описывающей параметры исходного изображения, такие как его разрешение и
количество уровней преобразования) возвращается через структуру
tunes_t. Доступ к закодированному изображению осуществляется через объект
арифметического кодера, ссылку на который можно получить вызвав метод
coder().
*/
encoder::enc_result_t
encoder::encode(const w_t *const w, const q_t q, const lambda_t &lambda,
tunes_t &tunes)
{
// результат проведённой оптимизации
enc_result_t result;
// проверка входных параметров
assert(0 != w);
// загрузка спектра
_wtree.load_field<wnode::member_w>(w);
// оптимизация топологии ветвей
result.optimization =
#ifdef OPTIMIZATION_USE_VIRTUAL_ENCODING
_optimize_wtree_q(lambda, q, true, true);
#else
_optimize_wtree_q(lambda, q, false, true);
#endif
// кодирование всего дерева, если необходимо
if (result.optimization.real_encoded)
{
tunes.models = result.optimization.models;
result.bpp = result.optimization.bpp;
}
else
{
result.bpp = _real_encode_tight(tunes.models);
}
// запись данных необходимых для последующего декодирования
tunes.q = _wtree.q();
// завершение кодирования
return result;
}
/*! \param[in] w Спектр вейвлет преобразования входного изображения для
кодирования
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами. Чем больше данный
параметр, тем больший приоритет будет отдан битовым затратам.
Соответственно, при 0 будет учитываться только ошибка кодирования.
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\param[in] q_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] q_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] q_eps Необходимая погрешность определения квантователя
<i>q</i> при котором значение <i>RD функции Лагранжа</i> минимально
(при фиксированном параметре <i>lambda</i>).
\param[in] j_eps Необходимая погрешность нахождения минимума <i>RD
функции Лагранжа</i>. Так как абсолютная величина функции <i>J</i>
зависит от многих факторов (таких как размер изображения, его тип,
величины параметра <i>lambda</i>), использовать это параметр
затруднительно. Поэтому его значение по умолчанию равно <i>0</i>,
чтобы при поиске оптимального квантователя учитывалась только
погрешность параметра <i>q</i>.
\param[in] max_iterations Максимальное количество итераций нахождения
минимума <i>RD функции Лагранжа</i>. Если это значение равно <i>0</i>,
количество выполняемых итераций не ограничено.
\param[in] precise_bpp Смотри аналогичный параметр в функции
_search_q_min_j()
Функция производит кодирование изображения при фиксированном параметре
<i>lambda</i>, подбирая параметр кодирования <i>q</i> таким образом,
чтобы значение функции <i>RD критерия Лагранжа</i> было минимальным.
Здесь <i>lambda</i> выступает некоторой характеристикой качества. Чем
этот параметр больше, тем больше будет степень сжатия и, соответственно,
ниже качество декодированного изображения. При <i>lambda</i> равной
<i>0</i>, декодированное изображение будет наилучшего качества.
В большинстве случаев удобнее использовать не абстрактный параметр
<i>lambda</i>, а более чёткий показатель качества. В таких ситуациях
можно воспользоваться функцией quality_to_lambda(), которая
преобразует показатель качества (число в диапазоне <i>[0, 100]</i>) в
соотвествующее значение параметра <i>lambda</i>.
Код функции использует макрос #OPTIMIZATION_USE_VIRTUAL_ENCODING. Если он
определён будет производиться виртуальное кодирование коэффициентов, что
несколько быстрее. Однако не все реализации битовых кодеров могут
поддерживать это.
\sa _search_q_min_j()
*/
encoder::enc_result_t
encoder::encode_fixed_lambda(
const w_t *const w, const lambda_t &lambda,
tunes_t &tunes,
const q_t &q_min, const q_t &q_max, const q_t &q_eps,
const j_t &j_eps, const sz_t &max_iterations,
const bool precise_bpp)
{
// результат проведённой оптимизации
enc_result_t result;
// проверка входных параметров
assert(0 != w);
// загрузка спектра
_wtree.load_field<wnode::member_w>(w);
// минимизация RD функции Лагранжа
result.optimization =
#ifdef OPTIMIZATION_USE_VIRTUAL_ENCODING
_search_q_min_j(lambda, q_min, q_max, q_eps, j_eps,
true, max_iterations, precise_bpp);
#else
_search_q_min_j(lambda, q_min, q_max, q_eps, j_eps,
false, max_iterations, precise_bpp);
#endif
// кодирование всего дерева, если необходимо
if (result.optimization.real_encoded)
{
tunes.models = result.optimization.models;
result.bpp = result.optimization.bpp;
}
else
{
result.bpp = _real_encode_tight(tunes.models);
}
// сохранение параметров, необходимых для последующего декодирования
tunes.q = _wtree.q();
return result;
}
/*! \param[in] w Спектр вейвлет преобразования входного изображения для
кодирования
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами. Чем больше данный
параметр, тем больший приоритет будет отдан битовым затратам.
Соответственно, при 0 будет учитываться только ошибка кодирования.
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
Эта упрощённая версия функции encode_fixed_lambda() использует следующие
значения аргументов:
- <i>q_min = 1</i>
- <i>q_max = 64</i>
- <i>q_eps = 0.01</i>
- <i>j_eps = 0.0</i>
- <i>max_iterations = 0</i>
- <i>precise_bpp = true</i>
Код функции косвенно использует макрос #OPTIMIZATION_USE_VIRTUAL_ENCODING.
Если он определён будет производиться виртуальное кодирование коэффициентов,
что несколько быстрее. Однако не все реализации битовых кодеров могут
поддерживать это.
*/
encoder::enc_result_t
encoder::encode_fixed_lambda(const w_t *const w, const lambda_t &lambda,
tunes_t &tunes)
{
static const q_t q_eps = q_t(0.01);
static const j_t j_eps = j_t(0);
static const q_t q_min = q_t(1);
static const q_t q_max = q_t(64);
static const sz_t max_iterations = 0;
static const bool precise_bpp = true;
return encode_fixed_lambda(w, lambda, tunes, q_min, q_max, q_eps,
j_eps, 0, precise_bpp);
}
/*! \param[in] w Спектр вейвлет коэффициентов преобразованного входного
изображения для кодирования
\param[in] q Используемый квантователь
\param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будет подбираться параметр <i>lambda</i>
\param[in] bpp_eps Необходимая точность, c которой <i>bpp</i> полученный
в результате поиска параметра <i>lambda</i> будет соответствовать
заданному.
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\param[in] lambda_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] lambda_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] lambda_eps Точность, с которой будет подбираться параметр
<i>lambda</i>.
\param[in] max_iterations Максимальное количество итераций нахождения
минимума <i>RD функции Лагранжа</i>. Если это значение равно <i>0</i>,
количество выполняемых итераций не ограничено.
\param[in] precise_bpp Если <i>true</i> после каждого этапа оптимизации
топологии деревьев спектра вейвлет коэффициентов будет произведено
реальное кодирование с уменьшеными моделями арифметического кодера для
уточнения оценки битовых затрат.
\return Результат проведённого поиска. Возможна ситуация, когда нужная
<i>lambda</i> лежит вне указанного диапазона. В этом случае, функция
подберёт такую <i>lambda</i>, которая максимально удовлетворяет условиям
поиска.
Производит кодирование изображения при фиксированном параметре <i>q</i>,
подбирая значения параметра <i>lambda</i> таким образом, чтобы битовые
затраты на кодирование изображения были максимально близки к заданным.
Код функции использует макрос #OPTIMIZATION_USE_VIRTUAL_ENCODING.
Если он определён будет производиться виртуальное кодирование коэффициентов,
что несколько быстрее. Однако не все реализации битовых кодеров могут
поддерживать это.
\sa _search_lambda_at_bpp
*/
encoder::enc_result_t
encoder::encode_fixed_q(const w_t *const w, const q_t &q,
const h_t &bpp, const h_t &bpp_eps,
tunes_t &tunes,
const lambda_t &lambda_min,
const lambda_t &lambda_max,
const lambda_t &lambda_eps,
const sz_t &max_iterations,
const bool precise_bpp)
{
// результат проведённой оптимизации
enc_result_t result;
// проверка входных параметров
assert(0 != w);
assert(1 <= q);
// загрузка спектра
_wtree.cheap_load(w, q);
// генерация характеристик моделей арифметического кодера
tunes.models = _setup_acoder_models();
// минимизация RD функции Лагранжа
result.optimization =
#ifdef OPTIMIZATION_USE_VIRTUAL_ENCODING
_search_lambda_at_bpp(bpp, bpp_eps,
lambda_min, lambda_max, lambda_eps,
true, max_iterations, precise_bpp);
#else
_search_lambda_at_bpp(bpp, bpp_eps,
lambda_min, lambda_max, lambda_eps,
false, max_iterations, precise_bpp);
#endif
// кодирование всего дерева, если необходимо
if (result.optimization.real_encoded)
{
tunes.models = result.optimization.models;
result.bpp = result.optimization.bpp;
}
else
{
result.bpp = _real_encode_tight(tunes.models);
}
// сохранение параметров, необходимых для последующего декодирования
tunes.q = _wtree.q();
return result;
}
/*! \param[in] w Спектр вейвлет коэффициентов преобразованного входного
изображения для кодирования
\param[in] q Используемый квантователь
\param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будет подбираться параметр <i>lambda</i>
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\return Результат проведённого поиска.
Эта упрощённая версия функции encode_fixed_q() использует следующие
значения аргументов:
- <i>bpp_eps = 0.001</i>
- <i>lambda_min = 0.05*q*q</i>
- <i>lambda_max = 0.20*q*q</i>
- <i>lambda_eps = 0.0</i>
- <i>max_iterations = 0</i>
- <i>precise_bpp = true</i>
Код функции косвенно использует макрос #OPTIMIZATION_USE_VIRTUAL_ENCODING.
Если он определён будет производиться виртуальное кодирование коэффициентов,
что несколько быстрее. Однако не все реализации битовых кодеров могут
поддерживать это.
*/
encoder::enc_result_t
encoder::encode_fixed_q(const w_t *const w, const q_t &q,
const h_t &bpp, tunes_t &tunes)
{
static const h_t bpp_eps = 0.001;
static const lambda_t lambda_min = 0.05*q*q;
static const lambda_t lambda_max = 0.20*q*q;
static const lambda_t lambda_eps = 0;
static const sz_t max_iterations = 0;
static const bool precise_bpp = true;
return encode_fixed_q(w, q, bpp, bpp_eps, tunes,
lambda_min, lambda_max, lambda_eps,
max_iterations, precise_bpp);
}
/*! \param[in] w Спектр вейвлет коэффициентов преобразованного входного
изображения для кодирования
\param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будут подбираться параметры <i>q</i> и <i>lambda</i>.
\param[in] bpp_eps Необходимая точность, c которой <i>bpp</i> полученный
в результате поиска параметров <i>q</i> и <i>lambda</i> будет
соответствовать заданному.
\param[in] q_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] q_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] q_eps Необходимая погрешность определения квантователя
<i>q</i> при котором значение <i>RD функции Лагранжа</i> минимально
(при фиксированном параметре <i>lambda</i>).
\param[in] lambda_eps Точность, с которой будет подбираться параметр
<i>lambda</i>
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\return Результат проведённого поиска
\sa _search_q_lambda_for_bpp()
*/
encoder::enc_result_t
encoder::encode_fixed_bpp(
const w_t *const w,
const h_t &bpp, const h_t &bpp_eps,
const q_t &q_min, const q_t &q_max, const q_t &q_eps,
const lambda_t &lambda_eps,
tunes_t &tunes, const bool precise_bpp)
{
// результат проведённой оптимизации
enc_result_t result;
// проверка входных параметров
assert(0 != w);
// загрузка спектра
_wtree.load_field<wnode::member_w>(w);
// минимизация RD функции Лагранжа
result.optimization =
#ifdef OPTIMIZATION_USE_VIRTUAL_ENCODING
_search_q_lambda_for_bpp(bpp, bpp_eps,
q_min, q_max, q_eps,
lambda_eps, tunes.models, true, precise_bpp);
#else
_search_q_lambda_for_bpp(bpp, bpp_eps,
q_min, q_max, q_eps,
lambda_eps, tunes.models, false, precise_bpp);
#endif
// кодирование всего дерева, если необходимо
if (result.optimization.real_encoded)
{
tunes.models = result.optimization.models;
result.bpp = result.optimization.bpp;
}
else
{
result.bpp = _real_encode_tight(tunes.models);
}
// сохранение параметров, необходимых для последующего декодирования
tunes.q = _wtree.q();
return result;
}
/*! \param[in] w Спектр вейвлет коэффициентов преобразованного входного
изображения для кодирования
\param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будут подбираться параметры <i>q</i> и <i>lambda</i>.
\param[out] tunes Информация, необходимая для последующего
восстановления изображения
\return Результат проведённого поиска
Эта упрощённая версия функции encode_fixed_bpp() придаёт следующим
аргументам соответствующие значения:
- <i>bpp_eps = 0.001</i>
- <i>q_min = 1</i>
- <i>q_max = 64</i>
- <i>q_eps = 0.01</i>
- <i>lambda_eps = 0</i>
- <i>precise_bpp = true</i>
\sa _search_q_lambda_for_bpp(), encode_fixed_bpp
*/
encoder::enc_result_t
encoder::encode_fixed_bpp(const w_t *const w, const h_t &bpp,
tunes_t &tunes)
{
static const h_t bpp_eps = 0.001;
static const q_t q_min = q_t(1);
static const q_t q_max = q_t(64);
static const q_t q_eps = q_t(0.01);
static const lambda_t lambda_eps = 0.00001;
static const bool precise_bpp = true;
return encode_fixed_bpp(w, bpp, bpp_eps,
q_min, q_max, q_eps, lambda_eps, tunes,
precise_bpp);
}
/*! param[in] data Указатель на блок памяти, содержащий закодированное
изображение
param[in] data_sz Размер блока, содержащего закодированное
изображения
param[in] tunes Данные необходимые для восстановления изображения,
полученные от одной из функций кодирования.
Стоит заметить, что в текущей реализации, память для арифметического
кодера выделяется зарание, размер которой определяется исходя из
размеров самого изображения. Поэтому необходимо, чтобы размер
данных <i>data_sz</i> был меньше, чем acoder::buffer_sz().
*/
void encoder::decode(const byte_t *const data, const sz_t data_sz,
const tunes_t &tunes)
{
// проверка утверждений
assert(_acoder.buffer_sz() >= data_sz);
// копирование памяти в арифметический кодер
memcpy(_acoder.buffer(), data, data_sz);
// инициализация спектра перед кодированием
_wtree.wipeout();
// установка характеристик моделей
_acoder.use(_mk_acoder_models(tunes.models));
// декодирование
_acoder.decode_start();
_encode_wtree(true);
_acoder.decode_stop();
// деквантование
_wtree.dequantize<wnode::member_wc>(tunes.q);
}
/*! \param[in] quality Показатель качества
\return Значение параметра <i>lambda</i>, соответствующее выбранному
показателю качества
Показатель качества представляет значение из диапазона <i>[0, 100]</i>.
Значение <i>100</i> соответствует максимальному качеству сжатия, а
значение <i>0</i> соответствует максимальной степени сжатия.
Преобразование производится по формуле:
\verbatim
lambda = pow((quality + 2.0), (102 / (quality + 2) - 1)) - 1;
\endverbatim
*/
lambda_t encoder::quality_to_lambda(const double &quality)
{
assert(0.0 <= quality && quality <= 100.0);
const double d = 2.0;
const double b = (quality + d);
const double p = ((100.0 + d) / b) - 1.0;
return (pow(b, p) - 1.0);
}
////////////////////////////////////////////////////////////////////////////////
// wtree class protected definitions
/*! \param[in] s Значение прогнозной величины <i>S<sub>j</sub></i>
\param[in] lvl Номер уровня разложения, из которого был взят коэффициент
\return Номер выбираемой модели
\note Стоит заметить, что для нулевого и первого уровней функция
возвращает определённые значения, независимо от параметра <i>s</i>.
*/
sz_t encoder::_ind_spec(const pi_t &s, const sz_t lvl) {
if (subbands::LVL_0 == lvl) return 0;
if (subbands::LVL_1 == lvl) return 1;
if (26.0 <= s) return 1;
if ( 9.8 <= s) return 2;
if ( 4.1 <= s) return 3;
if ( 1.72 <= s) return 4;
return 5;
}
/*! \param[in] pi Значение прогнозной величины <i>P<sub>i</sub></i>
\param[in] lvl Номер уровня разложения, из которого был взят групповой
признак подрезания ветвей
\return Номер выбираемой модели
\note Стоит заметить, что если параметр <i>lvl</i> равен <i>0</i>
функция всегда возвращает нулевую модель, независимо от параметра
<i>pi</i>.
*/
sz_t encoder::_ind_map(const pi_t &pi, const sz_t lvl) {
if (subbands::LVL_0 == lvl) return 0;
if (4.0 <= pi) return 4;
if (1.1 <= pi) return 3;
if (0.3 <= pi) return 2;
return 1;
}
/*! \param[in] desc Описание моделей арифметического кодера
\return Модели для арифметического кодера
*/
acoder::models_t encoder::_mk_acoder_models(const models_desc1_t &desc) const
{
// создание моделей для кодирования
acoder::models_t models;
acoder::model_t model;
// модел #0 ----------------------------------------------------------------
model.min = desc.mdl_0_min;
model.max = desc.mdl_0_max;
models.push_back(model);
// модель #1 ---------------------------------------------------------------
model.min = desc.mdl_1_min;
model.max = desc.mdl_1_max;
models.push_back(model);
// модели #2..#5 -----------------------------------------------------------
model.min = desc.mdl_x_min;
model.max = desc.mdl_x_max;
models.insert(models.end(), ACODER_SPEC_MODELS_COUNT - 2, model);
// создание моделей для кодирования групповых признаков подрезания ---------
model.min = 0;
model.max = 0x7;
models.push_back(model);
model.max = 0xF;
models.insert(models.end(), ACODER_MAP_MODELS_COUNT - 1, model);
// проверка утверждений
assert(ACODER_TOTAL_MODELS_COUNT == models.size());
return models;
}
/*! \param[in] desc Описание моделей арифметического кодера
\return Модели для арифметического кодера
*/
acoder::models_t encoder::_mk_acoder_models(const models_desc2_t &desc) const
{
// создание моделей для кодирования
acoder::models_t models;
for (sz_t i = 0; ACODER_TOTAL_MODELS_COUNT > i; ++i)
{
acoder::model_t model;
model.min = desc.mins[i];
model.max = desc.maxs[i];
models.push_back(model);
}
// проверка утверждений
assert(ACODER_TOTAL_MODELS_COUNT == models.size());
return models;
}
/*! \param[in] desc Описание моделей арифметического кодера в унифицированном
формате
\return Модели для арифметического кодера
*/
acoder::models_t encoder::_mk_acoder_models(const models_desc_t &desc) const
{
// описание моделей, как их понимает арифметический кодер
acoder::models_t models;
// выбор способа представления описаний
switch (desc.version)
{
case MODELS_DESC_V1:
models = _mk_acoder_models(desc.md.v1);
break;
case MODELS_DESC_V2:
models = _mk_acoder_models(desc.md.v2);
break;
default:
// unsupported models description
assert(false);
break;
}
return models;
}
/*! \return Описание моделей для арифметического кодера
Описание моделей (значение максимального и минимального элемента в модели)
составляется по следующему принципу:
- для модели #0: минимальный элемент из <i>LL</i> саббенда, максимальный
элемент также из <i>LL</i> саббенда
- для модели #1: минимальный элемент из всех саббендов первого уровня
(саббенды "дочерние" от <i>LL</i>), максимальный элемент также из всех
саббендов первого уровня.
- для моделей #2..#5: минимальные элемент из всех оставшихся саббендов,
максимальный элемент также из всех оставшихся саббендов
*/
encoder::models_desc1_t encoder::_mk_acoder_smart_models() const
{
// создание моделей для кодирования
models_desc1_t desc;
// модел #0 ----------------------------------------------------------------
{
const subbands::subband_t &sb_LL = _wtree.sb().get_LL();
wtree::coefs_iterator i = _wtree.iterator_over_subband(sb_LL);
wk_t lvl0_min = 0;
wk_t lvl0_max = 0;
_wtree.minmax<wnode::member_wq>(i, lvl0_min, lvl0_max);
desc.mdl_0_min = short(lvl0_min);
desc.mdl_0_max = short(lvl0_max);
}
// модели #1..#5 -----------------------------------------------------------
{
// поиск минимума и максимума на первом уровне
wtree::coefs_cumulative_iterator i_cum;
for (sz_t k = 0; subbands::SUBBANDS_ON_LEVEL > k; ++k)
{
const subbands::subband_t &sb = _wtree.sb().get(subbands::LVL_1, k);
i_cum.add(_wtree.iterator_over_subband(sb));
}
wk_t lvl1_min = 0;
wk_t lvl1_max = 0;
_wtree.minmax<wnode::member_wq>(some_iterator_adapt(i_cum),
lvl1_min, lvl1_max);
// поиск минимума и максимума на уровнях начиная со второго
wtree::coefs_cumulative_iterator j_cum;
for (sz_t lvl = subbands::LVL_1 + subbands::LVL_NEXT;
_wtree.lvls() >= lvl; ++lvl)
{
for (sz_t k = 0; subbands::SUBBANDS_ON_LEVEL > k; ++k)
{
const subbands::subband_t &sb = _wtree.sb().get(lvl, k);
j_cum.add(_wtree.iterator_over_subband(sb));
}
}
wk_t lvlx_min = 0;
wk_t lvlx_max = 0;
_wtree.minmax<wnode::member_wq>(some_iterator_adapt(j_cum),
lvlx_min, lvlx_max);
// модель #1
desc.mdl_1_min = short(std::min(lvl1_min, lvlx_min));
desc.mdl_1_max = short(std::max(lvl1_max, lvlx_max));
// модели #2..#5
desc.mdl_x_min = lvlx_min;
desc.mdl_x_max = lvlx_max;
}
return desc;
}
/*! \param[in] ac Арифметический кодер, статистика которого будет использована
для построения описания моделей
*/
encoder::models_desc2_t encoder::_mk_acoder_post_models(const acoder &ac) const
{
// проверка утверждений
assert(ACODER_TOTAL_MODELS_COUNT == ac.models().size());
encoder::models_desc2_t desc;
for (sz_t i = 0; sz_t(ac.models().size()) > i; ++i)
{
desc.mins[i] = ac.rmin(i);
desc.maxs[i] = ac.rmax(i);
// проверка на пустую модель (в которых rmin > rmax)
// данные действия необходимы, если в модель не попало ни одного
// элемента
if (desc.mins[i] > desc.maxs[i])
{
desc.mins[i] = desc.maxs[i] = 0;
}
}
return desc;
}
/*! \return Описание моделей арифметического кодера, которые были
установленны этой функцией
Для генерации описания моделей используется функция
_mk_acoder_smart_models()
*/
encoder::models_desc_t encoder::_setup_acoder_models()
{
// описание моделей для арифметического кодера
models_desc_t desc;
// идентификатор используемого представления описания моделей
desc.version = MODELS_DESC_V1;
// определение суб-оптимальных моделей для арифметического кодера
desc.md.v1 = _mk_acoder_smart_models();
// загрузка моделей в арифметический кодер
_acoder.use(_mk_acoder_models(desc));
return desc;
}
/*! \return Описание моделей арифметического кодера, которые были
установленны этой функцией
Для генерации описания моделей используется функция
_mk_acoder_post_models()
*/
encoder::models_desc_t encoder::_setup_acoder_post_models()
{
// описание моделей для арифметического кодера
models_desc_t desc;
// используется вторая версия представления описания моделей
// арифметического кодера
desc.version = MODELS_DESC_V2;
// создание нового описания моделей арифметического кодера,
// основываясь на статистике кодирования, полученной при
// оптимизации топологии деревьев спектра вейвлет коэффициентов
desc.md.v2 = _mk_acoder_post_models(_acoder);
// загрузка моделей в арифметический кодер
_acoder.use(_mk_acoder_models(desc));
return desc;
}
/*! \param[in] result Результат проведённой оптимизации, в резултате которой
могли поменяться модели арифметического кодера
\param[in] models Оригинальные модели арифметического кодера, которые
следует востановить в случае их изменения процедурой оптимизации топологии
\return <i>true</i> если измененённые модели были восстановлены и
<i>false</i> если модели не изменились процедурой оптимизации.
*/
bool encoder::_restore_spoiled_models(const optimize_result_t &result,
const acoder::models_t &models)
{
// Проверка, были ли в процессе оптимизации изменены
if (MODELS_DESC_NONE == result.models.version) return false;
// Дополнительная проверка на равенство старых и новых моделей.
// Сейчас не используется, так как в текущей реализации функций
// оптимизации топологии версия описания моделей устанавливается
// только в случае их изменения.
// if (models == _mk_acoder_models(result.models)) return false;
// восстановление моделей используемых арифметическим кодером
_acoder.use(models);
return true;
}
/*! \param[in] m Номер модели для кодирования
\param[in] wk Значение коэффициента для кодирования
\return Битовые затраты, необходимые для кодирования коэффициента с
использованием этой модели
*/
h_t encoder::_h_spec(const sz_t m, const wk_t &wk) {
return _acoder.enc_entropy(wk, m);
}
/*! \param[in] m Номер модели для кодирования
\param[in] n Значение группового признака подрезания ветвей
\return Битовые затраты, необходимые для кодирования группового
признака подрезания
*/
h_t encoder::_h_map(const sz_t m, const n_t &n) {
return _acoder.enc_entropy(n, m + ACODER_SPEC_MODELS_COUNT);
}
/*! \param[in] m Номер модели для кодирования
\param[in] wk Значение коэффициента для кодирования
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
*/
void encoder::_encode_spec(const sz_t m, const wk_t &wk,
const bool virtual_encode)
{
_acoder.put(wk, m, virtual_encode);
}
/*! \param[in] m Номер модели для кодирования
\param[in] n Значение группового признака подрезания ветвей
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
*/
void encoder::_encode_map(const sz_t m, const n_t &n,
const bool virtual_encode)
{
_acoder.put(n, m + ACODER_SPEC_MODELS_COUNT, virtual_encode);
}
/*! \param[in] m Номер модели для кодирования
\return Значение коэффициента для кодирования
*/
wk_t encoder::_decode_spec(const sz_t m)
{
return _acoder.get<wk_t>(m);
}
/*! \param[in] m Номер модели для кодирования
\return Значение группового признака подрезания ветвей
*/
n_t encoder::_decode_map(const sz_t m)
{
return _acoder.get<n_t>(m + ACODER_SPEC_MODELS_COUNT);
}
/*! \param[in] p Предполагаемые координаты элемента (коэффициента)
\param[in] k Откорректированное (или просто проквантованное) значение
коэффициента
\param[in] lambda Параметр <i>lambda</i>, отвечает за <i>Rate/Distortion</i>
баланс при вычислении <i>RD</i> функции. Чем это значение больше, тем
больший вклад в значение <i>RD</i> функции будут вносить битовые затраты
на кодирование коэффициента арифметическим кодером.
\param[in] model Номер модели арифметического кодера, которая будет
использована для кодирования коэффициента
\return Значения <i>RD-функции Лагрнанжа</i>
\note Функция применима для элементов из любых саббендов.
*/
j_t encoder::_calc_rd_iteration(const p_t &p, const wk_t &k,
const lambda_t &lambda, const sz_t &model)
{
const wnode &node = _wtree.at(p);
const w_t dw = (wnode::dequantize(k, _wtree.q()) - node.w);
const double h = _h_spec(model, k);
return (dw*dw + lambda * h);
}
/*! \param[in] p Координаты коэффициента для корректировки
\param[in] sb Саббенд, в котором находится коэффициент
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\return Значение откорректированного коэффициента
\note Функция применима для коэффициентов из любых саббендов
\sa COEF_FIX_USE_4_POINTS
\todo Написать тест для этой функции
*/
wk_t encoder::_coef_fix(const p_t &p, const subbands::subband_t &sb,
const lambda_t &lambda)
{
#ifdef COEF_FIX_DISABLED
return _wtree.at(p).wq;
#endif
// выбор модели и оригинального значения коэффициента
const sz_t model = _ind_spec<wnode::member_wc>(p, sb);
const wk_t &wq = _wtree.at(p).wq;
// Определение набора подбираемых значений
#ifdef COEF_FIX_USE_4_POINTS
static const sz_t vals_count = 4;
const wk_t w_vals[vals_count] = {0, wq, wq + 1, wq - 1};
#else
static const sz_t vals_count = 3;
const wk_t w_drift = (0 <= wq)? -1: +1;
const wk_t w_vals[vals_count] = {0, wq, wq + w_drift};
#endif
// начальные значения для поиска минимума RD функции
wk_t k_optim = w_vals[0];
j_t j_optim = _calc_rd_iteration(p, k_optim, lambda, model);
// поиск минимального значения RD функции
for (int i = 1; vals_count > i; ++i) {
const wk_t &k = w_vals[i];
const j_t j = _calc_rd_iteration(p, k, lambda, model);
if (j < j_optim) {
j_optim = j;
k_optim = k;
}
}
// возврат откорректированного значения коэффициента
return k_optim;
}
/*! \param[in] p Координаты родительского элемента
\param[in] sb_j Саббенд, в котором находятся дочерние элементы
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\note Функция применима только для родительских элементов не из
<i>LL</i> саббенда.
*/
void encoder::_coefs_fix(const p_t &p, const subbands::subband_t &sb_j,
const lambda_t &lambda)
{
// цикл по дочерним элементам
for (wtree::coefs_iterator i = _wtree.iterator_over_children(p);
!i->end(); i->next())
{
const p_t &p = i->get();
wnode &node = _wtree.at(p);
node.wc = _coef_fix(p, sb_j, lambda);
}
}
/*! \param[in] p Координаты родительского элемента
\param[in] sb_j Саббенд, в котором находятся дочерние элементы
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\note Функция применима только для родительских элементов из
любых саббендов.
*/
void encoder::_coefs_fix_uni(const p_t &p, const subbands::subband_t &sb_j,
const lambda_t &lambda)
{
// цикл по дочерним элементам
for (wtree::coefs_iterator i = _wtree.iterator_over_children_uni(p);
!i->end(); i->next())
{
const p_t &p = i->get();
wnode &node = _wtree.at(p);
node.wc = _coef_fix(p, sb_j, lambda);
}
}
/*! \param[in] p Координаты элемента для которого будет расчитываться
\param[in] sb Саббенд, в котором находятся коэффициенты из сохраняемой
ветви. Другими словами, этот саббенд дочерний для того, в котором
находится элемент с координатами <i>p</i>.
\param[in] lambda Параметр <i>lambda</i> который участвует в вычислении
<i>RD</i> функции и представляет собой баланс между <i>R (rate)</i> и
<i>D (distortion)</i> частями <i>функции Лагранжа</i>.
\return Значение <i>RD функции Лагранжа</i>.
\note Функция не применима для элементов из <i>LL</i> саббенда.
\sa _calc_j0_value()
\todo Необходимо написать тест для этой функции.
*/
j_t encoder::_calc_j1_value(const p_t &p, const subbands::subband_t &sb,
const lambda_t &lambda)
{
// получение номера модели для кодирования коэффициентов
const sz_t model = _ind_spec<wnode::member_wc>(p, sb);
j_t j1 = 0;
for (wtree::coefs_iterator i = _wtree.iterator_over_children(p);
!i->end(); i->next())
{
const wnode &node = _wtree.at(i->get());
j1 += _calc_rd_iteration(i->get(), node.wc, lambda, model);
}
return j1;
}
/*! \param[in] root Координаты корневого элемента
\param[in] j_map Значение <i>RD-функцию Лагранжа</i> полученное
в шаге 2.6.
\param[in] lambda Параметр <i>lambda</i> который участвует в вычислении
<i>RD</i> функции и представляет собой баланс между <i>R (rate)</i> и
<i>D (distortion)</i> частями <i>функции Лагранжа</i>.
\return Значение <i>RD-функции Лагранжа</i>.
Функция также сохраняет полученное значение <i>RD-функции Лагранжа</i> в
полях wnode::j0 и wnode::j1 корневого элемента.
*/
j_t encoder::_calc_jx_value(const p_t &root, const j_t &j_map,
const lambda_t &lambda)
{
assert(_wtree.sb().test_LL(root));
// получаем ссылку саббенды
const subbands &sb = _wtree.sb();
j_t j = j_map;
// цикл по дочерним элементам
for (wtree::coefs_iterator i = _wtree.iterator_over_LL_children(root);
!i->end(); i->next())
{
const p_t &p = i->get();
const wnode &node = _wtree.at(p);
// получаем ссылку на саббенд в котором лежит рассматриваемый элемент
const subbands::subband_t &sb_i = sb.from_point(p, subbands::LVL_1);
j += _calc_rd_iteration(p, node.wc, lambda,
_ind_spec<wnode::member_wc>(p, sb_i));
}
wnode &node = _wtree.at(root);
return (node.j0 = node.j1 = j);
}
/*! \param[in] p Координаты элемента, для которого выполняется подготовка
значений <i>J</i> (<i>RD функция Лагранжа</i>)
\param[in] sb_j Саббенд в котором находятся дочерние элементы
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
Функция обычно выполняется при переходе с уровня <i>lvl</i>, на
уровень <i>lvl + subbands::LVL_PREV</i>.
\note Функция не применима для элементов из <i>LL</i> саббенда.
*/
void encoder::_prepare_j(const p_t &p, const subbands::subband_t &sb_j,
const lambda_t &lambda)
{
wnode &node = _wtree.at(p);
node.j0 = _calc_j0_value<false>(p);
node.j1 = _calc_j1_value(p, sb_j, lambda);
}
/*! \param[in] p Координаты элемента, для которого выполняется подготовка
значений <i>J</i> (<i>RD функция Лагранжа</i>)
\param[in] sb_j Саббенд в котором находятся дочерние элементы
\param[in] j Значение функции Лагранжа, полученное при подборе
оптимальной топологии ветвей
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
Функция обычно выполняется при переходе с уровня <i>lvl</i>, на
уровень <i>lvl + subbands::LVL_PREV</i>.
\note Функция не применима для элементов из <i>LL</i> саббенда.
*/
void encoder::_prepare_j(const p_t &p, const subbands::subband_t &sb_j,
const j_t &j, const lambda_t &lambda)
{
wnode &node = _wtree.at(p);
node.j0 = _calc_j0_value<true>(p);
node.j1 = j + _calc_j1_value(p, sb_j, lambda);
}
/*! \param[in] branch Координаты элемента, находящегося в вершине
ветви
\param[in] n Групповой признак подрезания, характеризующий
топологию ветви
\return Значение функции Лагранжа при топологии описанной в
<i>n</i>
*/
j_t encoder::_topology_calc_j(const p_t &branch, const n_t n)
{
j_t j = 0;
for (wtree::coefs_iterator i =
_wtree.iterator_over_children(branch);
!i->end(); i->next())
{
const p_t &p = i->get();
const wnode &node = _wtree.at(p);
const n_t mask = _wtree.child_n_mask(p, branch);
j += (_wtree.test_n_mask(n, mask))? node.j1: node.j0;
}
return j;
}
//! определённой её топологии (ветвь из <i>LL</i> саббенда)
/*! \param[in] branch Координаты элемента, находящегося в вершине
ветви
\param[in] n Групповой признак подрезания, характеризующий
топологию ветви
\return Значение функции Лагранжа при топологии описанной в
<i>n</i>
*/
j_t encoder::_topology_calc_j_LL(const p_t &branch, const n_t n)
{
// начальное значение для функции Лагранжа
j_t j = 0;
for (wtree::coefs_iterator i =
_wtree.iterator_over_LL_children(branch);
!i->end(); i->next())
{
const p_t &p = i->get();
const wnode &node = _wtree.at(p);
const n_t mask = _wtree.child_n_mask_LL(p);
j += (_wtree.test_n_mask(n, mask))? node.j1: node.j0;
}
return j;
}
/*! \param[in] branch Координаты родительского элемента, дающего
начало ветви.
\param[in] sb Саббенд, содержащий элемент <i>branch</i>
\param[in] lambda Параметр <i>lambda</i> который участвует в
вычислении <i>RD</i> функции и представляет собой баланс между
<i>R (rate)</i> и <i>D (distortion)</i> частями функции
<i>Лагранжа</i>.
\return Групповой признак подрезания ветвей
Алгоритм оптимизации топологии подробно описан в <i>35.pdf</i>
\note Функция применима для всех ветвей (как берущих начало в
<i>LL</i> саббенде, так и для всех остальных).
*/
encoder::_branch_topology_t
encoder::_optimize_branch_topology(const p_t &branch,
const subbands::subband_t &sb,
const lambda_t &lambda)
{
// получение дочернего саббенда
const sz_t lvl_j = sb.lvl + subbands::LVL_NEXT;
const subbands::subband_t &sb_j = _wtree.sb().get(lvl_j, sb.i);
// выбор модели для кодирования групповых признаков подрезания
const sz_t model = _ind_map<wnode::member_wc>(branch, sb_j);
// поиск наиболее оптимальной топологии
wtree::n_iterator i = _wtree.iterator_through_n(sb.lvl);
// первая итерация цикла поиска
_branch_topology_t optim_topology;
optim_topology.n = i->get();
optim_topology.j = _topology_calc_j_uni(branch,
optim_topology.n);
// последующие итерации
for (i->next(); !i->end(); i->next())
{
const n_t &n = i->get();
const j_t j_sum = _topology_calc_j_uni(branch, n);
const j_t j = (j_sum + lambda * _h_map(model, n));
if (j < optim_topology.j) {
optim_topology.j = j;
optim_topology.n = n;
}
}
return optim_topology;
}
/*! \param[in] root Координаты корневого элемента
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
Функция выполняет кодирование:
- Коэффициента при корневом элементе
- Группового признака подрезания при корневом элементе
- Коэффициентов принадлежащих дереву с первого уровня разложения
*/
void encoder::_encode_tree_root(const p_t &root,
const bool virtual_encode)
{
// получение корневого элемента
const wnode &root_node = _wtree.at(root);
// определение модели, используемой для кодирования коэффициента
const sz_t spec_model = _ind_spec(0, subbands::LVL_0);
// закодировать коэффициент с нулевого уровня
_encode_spec(spec_model, root_node.wc, virtual_encode);
// определение модели для кодирования признака подрезания
const sz_t map_model = _ind_map(0, subbands::LVL_0);
// закодировать групповой признак подрезания с нулевого уровня
_encode_map(map_model, root_node.n, virtual_encode);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись отладочной информации о закодированном коэффициенте и признаке
// подрезания
wicdbg::dbg_pixel &dbg_pixel = _dbg_opt_surface.get(root);
dbg_pixel.wc = root_node.wc;
dbg_pixel.wc_model = spec_model;
dbg_pixel.n = root_node.n;
dbg_pixel.n_model = map_model;
#endif
// кодирование дочерних коэффициентов с первого уровня
for (wtree::coefs_iterator i = _wtree.iterator_over_LL_children(root);
!i->end(); i->next())
{
// определение модели, используемой для кодирования коэффициента
const sz_t spec_model = _ind_spec(0, subbands::LVL_1);
// ссылка на кодируемый коэффициент
const wk_t &wc = _wtree.at(i->get()).wc;
// закодировать коэффициенты с первого уровня
_encode_spec(spec_model, wc, virtual_encode);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись отладочной информации о закодированном коэффициенте
wicdbg::dbg_pixel &dbg_pixel = _dbg_opt_surface.get(i->get());
dbg_pixel.wc = wc;
dbg_pixel.wc_model = spec_model;
#endif
}
}
/*! \param[in] root Координаты корнвого элемента
\param[in] lvl Номер уровня разложения
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
*/
void encoder::_encode_tree_leafs(const p_t &root, const sz_t lvl,
const bool virtual_encode)
{
// псевдонимы для номеров уровней
const sz_t lvl_g = lvl;
const sz_t lvl_j = lvl_g + subbands::LVL_PREV;
const sz_t lvl_i = lvl_j + subbands::LVL_PREV;
// цикл по саббендам в уровне
for (sz_t k = 0; _wtree.sb().subbands_on_lvl(lvl) > k; ++k)
{
const subbands::subband_t &sb_g = _wtree.sb().get(lvl_g, k);
const subbands::subband_t &sb_j = _wtree.sb().get(lvl_j, k);
// кодирование коэффициентов
for (wtree::coefs_iterator g = _wtree.iterator_over_leafs(root, sb_g);
!g->end(); g->next())
{
const p_t &p_g = g->get();
wnode &node_g = _wtree.at(p_g);
if (node_g.invalid) continue;
const sz_t model = _ind_spec<wnode::member_wc>(p_g, sb_g);
_encode_spec(model, node_g.wc, virtual_encode);
#ifdef LIBWIC_USE_DBG_SURFACE
// Запись кодируемого коэффициента в отладочную поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_opt_surface.get(p_g);
dbg_pixel.wc = node_g.wc;
dbg_pixel.wc_model = model;
#endif
}
// на предпоследнем уровне нет групповых признаков подрезания
if (_wtree.lvls() == lvl) continue;
// кодирование групповых признаков подрезания
for (wtree::coefs_iterator j = _wtree.iterator_over_leafs(root, sb_j);
!j->end(); j->next())
{
const p_t &p_j = j->get();
const p_t &p_i = _wtree.prnt_uni(p_j);
const wnode &node_i = _wtree.at(p_i);
// маска подрезания, где текущий элемент не подрезан
const n_t mask = _wtree.child_n_mask_uni(p_j, p_i);
// переходим к следующему потомку, если ветвь подрезана
if (!_wtree.test_n_mask(node_i.n, mask)) continue;
wnode &node_j = _wtree.at(p_j);
const sz_t model = _ind_map<wnode::member_wc>(p_j, sb_g);
_encode_map(model, node_j.n, virtual_encode);
#ifdef LIBWIC_USE_DBG_SURFACE
// Запись признака подрезания в отладочную поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_opt_surface.get(p_j);
dbg_pixel.n = node_j.n;
dbg_pixel.n_model = model;
#endif
}
}
}
/*! \param[in] root Координаты корневого элемента дерева
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
*/
void encoder::_encode_tree(const p_t &root,
const bool virtual_encode)
{
// кодирование корневого и дочерних элементов дерева
_encode_tree_root(root, virtual_encode);
// кодирование элементов дерева на остальных уровнях
const sz_t first_lvl = subbands::LVL_1 + subbands::LVL_NEXT;
const sz_t final_lvl = _wtree.lvls();
for (sz_t lvl = first_lvl; final_lvl >= lvl; ++lvl)
{
_encode_tree_leafs(root, lvl, virtual_encode);
}
}
/*! \param[in] decode_mode Если <i>false</i> функция будет выполнять
кодирование спектра, иначе (если <i>true</i>) будет выполнять
декодирование спектра.
*/
void encoder::_encode_wtree_root(const bool decode_mode)
{
// LL cаббенд
const subbands::subband_t &sb_LL = _wtree.sb().get_LL();
// модели для кодирования в LL саббенде
const sz_t spec_LL_model = _ind_spec(0, sb_LL.lvl);
const sz_t map_LL_model = _ind_map(0, sb_LL.lvl);
// (де)кодирование коэффициентов и групповых признаков подрезания
// из LL саббенда
for (wtree::coefs_iterator i = _wtree.iterator_over_subband(sb_LL);
!i->end(); i->next())
{
// координаты элемента
const p_t &p_i = i->get();
// сам элемент из LL саббенда
wnode &node = _wtree.at(p_i);
if (decode_mode)
{
// декодирование коэффициента и признака подрезания
node.wc = _decode_spec(spec_LL_model);
node.n = _decode_map(map_LL_model);
// порождение ветвей в соответствии с полученным признаком
// подрезания
_wtree.uncut_leafs(p_i, node.n);
}
else
{
// кодирование коэффициента и признака подрезания
_encode_spec(spec_LL_model, node.wc);
_encode_map(map_LL_model, node.n);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись информации о кодируемых коэффициентов и признаках
// подрезания в отладочную поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_enc_surface.get(p_i);
dbg_pixel.wc = node.wc;
dbg_pixel.wc_model = spec_LL_model;
dbg_pixel.n = node.n;
dbg_pixel.n_model = map_LL_model;
#endif
}
}
// модель для кодирования коэффициентов с первого уровня
const sz_t spec_1_model = _ind_spec(0, subbands::LVL_1);
// (де)кодирование коэффициентов из саббендов первого уровня
for (sz_t k = 0; subbands::SUBBANDS_ON_LEVEL > k; ++k)
{
// очередной саббенд с первого уровня
const subbands::subband_t &sb = _wtree.sb().get(subbands::LVL_1, k);
// цикл по всем элементам из саббенда с первого уровня
for (wtree::coefs_iterator i = _wtree.iterator_over_subband(sb);
!i->end(); i->next())
{
// (де)кодирование очерендного коэффициента
if (decode_mode)
{
_wtree.at(i->get()).wc = _decode_spec(spec_1_model);
}
else
{
// ссылка на кодируемый коэффициент
const wk_t &wc = _wtree.at(i->get()).wc;
// кодирование коэффициента
_encode_spec(spec_1_model, wc);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись информации о кодируемом коэффициенте в отладочную
// поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_enc_surface.get(i->get());
dbg_pixel.wc = wc;
dbg_pixel.wc_model = spec_1_model;
#endif
}
}
}
}
/*! \param[in] lvl Номер уровня, коэффициенты на котором будут
закодированы
\param[in] decode_mode Если <i>false</i> функция будет выполнять
кодирование спектра, иначе (если <i>true</i>) будет выполнять
декодирование спектра.
\todo Возможно не стоит делать wtree::uncut_leafs() при попадании в
подрезанную ветвь при кодирование групповыйх признаков подрезания.
Вместо этого можно перед декодированием проинициализировать все поля
wnode::invalid значением <i>true</i>
*/
void encoder::_encode_wtree_level(const sz_t lvl,
const bool decode_mode)
{
// определение псевдонимов для номеров уровней
const sz_t lvl_g = lvl;
const sz_t lvl_j = lvl_g + subbands::LVL_PREV;
const sz_t lvl_i = lvl_j + subbands::LVL_PREV;
// цикл по саббендам на уровне
for (sz_t k = 0; _wtree.sb().subbands_on_lvl(lvl) > k; ++k)
{
// саббенд на уровне коэффициенты из которого будут
// закодированы и родительский для для него
const subbands::subband_t &sb_g = _wtree.sb().get(lvl_g, k);
const subbands::subband_t &sb_j = _wtree.sb().get(lvl_j, k);
// кодирование коэффициентов
for (wtree::coefs_iterator g = _wtree.iterator_over_subband(sb_g);
!g->end(); g->next())
{
// координаты элемента
const p_t &p_g = g->get();
// сам элемент
wnode &node_g = _wtree.at(p_g);
// переходим к следующему, если коэффициента попал в
// подрезанную ветвь
if (node_g.invalid) continue;
// выбираем модель для (де)кодирования коэффициента
const sz_t model = _ind_spec<wnode::member_wc>(p_g, sb_g);
// (де)кодирование коэффициента
if (decode_mode)
{
node_g.wc = _decode_spec(model);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись информации о кодируемом коэффициенте в отладочную
// поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_dec_surface.get(p_g);
dbg_pixel.wc = node_g.wc;
dbg_pixel.wc_model = model;
#endif
}
else
{
_encode_spec(model, node_g.wc);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись информации о кодируемом коэффициенте в отладочную
// поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_enc_surface.get(p_g);
dbg_pixel.wc = node_g.wc;
dbg_pixel.wc_model = model;
#endif
}
}
// на предпоследнем уровне нет групповых признаков подрезания
if (_wtree.lvls() == lvl) continue;
// кодирование групповых признаков подрезания
for (wtree::coefs_iterator j = _wtree.iterator_over_subband(sb_j);
!j->end(); j->next())
{
// координаты элемента
const p_t &p_j = j->get();
// координаты родительского элемента
const p_t &p_i = _wtree.prnt_uni(p_j);
// ссылка на родительский элемент
const wnode &node_i = _wtree.at(p_i);
// маска подрезания, где текущий элемент не подрезан
const n_t mask = _wtree.child_n_mask_uni(p_j, p_i);
// переходим к следующему потомку, если ветвь подрезана
if (!_wtree.test_n_mask(node_i.n, mask)) continue;
// значение элемента
wnode &node_j = _wtree.at(p_j);
// выбор модели для кодирования группового признака подрезания
const sz_t model = _ind_map<wnode::member_wc>(p_j, sb_g);
if (decode_mode)
{
// декодирование признака подрезания
node_j.n = _decode_map(model);
// порождение ветвей в соответствии с полученным признаком
// подрезания
_wtree.uncut_leafs(p_j, node_j.n);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись информации о групповом признаке подрезания в
// отладочную поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_dec_surface.get(p_j);
dbg_pixel.n = node_j.n;
dbg_pixel.n_model = model;
#endif
}
else
{
// кодирование признака подрезания
_encode_map(model, node_j.n);
#ifdef LIBWIC_USE_DBG_SURFACE
// запись информации о групповом признаке подрезания в
// отладочную поверхность
wicdbg::dbg_pixel &dbg_pixel = _dbg_enc_surface.get(p_j);
dbg_pixel.n = node_j.n;
dbg_pixel.n_model = model;
#endif
}
}
}
}
/*! \param[in] decode_mode Если <i>false</i> функция будет выполнять
кодирование спектра, иначе (если <i>true</i>) будет выполнять
декодирование спектра.
*/
void encoder::_encode_wtree(const bool decode_mode)
{
#ifdef LIBWIC_USE_DBG_SURFACE
// очистка отладочной поверхности, если производится кодирование
if (!decode_mode)
{
_dbg_enc_surface.clear();
}
else
{
_dbg_dec_surface.clear();
}
#endif
// (де)кодирование корневых элементов
_encode_wtree_root(decode_mode);
// (де)кодирование остальных элементов
const sz_t first_lvl = subbands::LVL_1 + subbands::LVL_NEXT;
const sz_t final_lvl = _wtree.lvls();
// цикл по уровням
for (sz_t lvl = first_lvl; final_lvl >= lvl; ++lvl)
{
_encode_wtree_level(lvl, decode_mode);
}
#ifdef LIBWIC_USE_DBG_SURFACE
// запись отладочной поверхности в файл
if (!decode_mode)
{
_dbg_enc_surface.save<wicdbg::dbg_pixel::member_wc>
("dumps/[encoder]dbg_enc_suface.wc.bmp", true);
_dbg_enc_surface.save<wicdbg::dbg_pixel::member_wc>
("dumps/[encoder]dbg_enc_suface.wc.txt", false);
_dbg_enc_surface.save<wicdbg::dbg_pixel::member_wc_model>
("dumps/[encoder]dbg_enc_suface.wc_model.bmp", true);
_dbg_enc_surface.save<wicdbg::dbg_pixel::member_n>
("dumps/[encoder]dbg_enc_suface.n.bmp", true);
_dbg_opt_surface.diff<wicdbg::dbg_pixel::member_wc_model>
(_dbg_enc_surface, "dumps/[encoder]dbg_suface.wc_model.diff");
}
else
{
_dbg_dec_surface.save<wicdbg::dbg_pixel::member_wc>
("dumps/[decoder]dbg_dec_suface.wc.bmp", true);
_dbg_dec_surface.save<wicdbg::dbg_pixel::member_wc>
("dumps/[decoder]dbg_dec_suface.wc.txt", false);
_dbg_dec_surface.save<wicdbg::dbg_pixel::member_wc_model>
("dumps/[decoder]dbg_dec_suface.wc_model.bmp", true);
_dbg_dec_surface.save<wicdbg::dbg_pixel::member_n>
("dumps/[decoder]dbg_dec_suface.n.bmp", true);
}
#endif
}
/*! \param[in] root Координаты корневого элемента рассматриваемого дерева
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
На первом шаге кодирования выполняется корректировка коэффициентов
на самом последнем (с наибольшей площадью) уровне разложения и
последующий расчёт <i>RD-функций Лагранжа</i> для вариантов сохранения
и подрезания оконечных листьев дерева.
*/
void encoder::_optimize_tree_step_1(const p_t &root, const lambda_t &lambda)
{
// просматриваются все узлы предпоследнего уровня
const sz_t lvl_i = _wtree.sb().lvls() + subbands::LVL_PREV;
const sz_t lvl_j = _wtree.sb().lvls();
// цикл по саббендам
for (sz_t k = 0; subbands::SUBBANDS_ON_LEVEL > k; ++k)
{
const subbands::subband_t &sb_i = _wtree.sb().get(lvl_i, k);
const subbands::subband_t &sb_j = _wtree.sb().get(lvl_j, k);
// цикл по элементам из предпоследнего уровня дерева
for (wtree::coefs_iterator i = _wtree.iterator_over_leafs(root, sb_i);
!i->end(); i->next())
{
// родительский элемент из предпоследнего уровня
const p_t &p = i->get();
// Шаг 1.1. Корректировка проквантованных коэффициентов
_coefs_fix(p, sb_j, lambda);
// Шаг 1.2. Расчет RD-функций Лагранжа для вариантов сохранения и
// подрезания листьев
_prepare_j(p, sb_j, lambda);
}
}
}
/*! \param[in] root Координаты корневого элемента дерева
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
*/
void encoder::_optimize_tree_step_2(const p_t &root, const lambda_t &lambda)
{
// Шаги 2.1 - 2.5 ----------------------------------------------------------
// цикл по уровням
for (sz_t lvl_i = _wtree.sb().lvls() + 2*subbands::LVL_PREV;
0 < lvl_i; --lvl_i)
{
const sz_t lvl_j = lvl_i + subbands::LVL_NEXT;
// цикл по саббендам
for (sz_t k = 0; subbands::SUBBANDS_ON_LEVEL > k; ++k) {
// получение ссылок на саббенды
const subbands::subband_t &sb_i = _wtree.sb().get(lvl_i, k);
const subbands::subband_t &sb_j = _wtree.sb().get(lvl_j, k);
// цикл по родительским элементам
for (wtree::coefs_iterator i =
_wtree.iterator_over_leafs(root, sb_i);
!i->end(); i->next())
{
const p_t &p = i->get();
// Шаг 2.1. Определение оптимальной топологии ветвей
const _branch_topology_t optim_topology =
_optimize_branch_topology(p, sb_i, lambda);
// Шаг 2.2. Изменение топологии дерева
_wtree.cut_leafs<wnode::member_wc>(p, optim_topology.n);
// Шаг 2.3. Корректировка проквантованных коэффициентов
_coefs_fix(p, sb_j, lambda);
// Шаг 2.4. Подготовка для просмотра следующего уровня
_prepare_j(p, sb_j, optim_topology.j, lambda);
}
}
// на всякий случай, если какой-нить фрик сделает sz_t беззнаковым
// типом :^)
// if (0 == lvl) break;
}
}
/*! \param[in] root Координаты корневого элемента дерева
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
*/
void encoder::_optimize_tree_step_3(const p_t &root, const lambda_t &lambda)
{
const subbands::subband_t &sb_LL = _wtree.sb().get_LL();
// Шаг 2.6. Определение оптимальной топологии ветвей
const _branch_topology_t optim_topology =
_optimize_branch_topology(root, sb_LL, lambda);
// Шаг 2.7. Изменение топологии дерева
_wtree.cut_leafs<wnode::member_wc>(root, optim_topology.n);
// шаг 3. Вычисление RD-функции Лагранжа для всего дерева
_calc_jx_value(root, optim_topology.j, lambda);
}
/*! \param[in] root Координаты корневого элемента дерева
\param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\return Значение <i>RD-функций Лагранжа</i> для дерева
Для корректной работы функции необходимо, чтобы в дереве все ветви
были отмечены как подрезанные, а элементы как корректные. Значения
функций <i>Лагранжа</i> в спектре должны быть обнулены. Арифметический
кодер должен быть настроен на корректные модели (смотри acoder::use()).
\note Необходимую подготовку выполняет функция wnode::filling_refresh(),
при условии, что поля wnode::w и wnode::wq корректны.
*/
j_t encoder::_optimize_tree(const p_t &root, const lambda_t &lambda)
{
_optimize_tree_step_1(root, lambda);
_optimize_tree_step_2(root, lambda);
_optimize_tree_step_3(root, lambda);
const j_t j = _wtree.at(root).j1;
if (0 != _optimize_tree_callback)
{
_optimize_tree_callback(root, _optimize_tree_callback_param);
}
return j;
}
/*! \param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\param[in] refresh_wtree Если <i>true</i>, то перед началом кодирования
будет вызвана функция wtree::filling_refresh(), которая сбросит спекрт
в начальное состояние. Используется при выполнении нескольких операций
оптимизации над одним спектром (например, в целях подбора оптимального
значение параметра <i>lambda</i>).
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток). При включённом виртуальном
кодировании, поле _optimize_result_t::bpp выставляется в 0, так как
без проведения реального кодирование невозможно оценить битовые
затраты.
\param[in] precise_bpp Если <i>true</i>, то после этапа оптимизации
будет проведён этап уточнения битовых затрат, заключающийся в том, что
модели арифметического кодера будут уменьшены функцией
_setup_acoder_post_models(), а затем будет произведено реальное
кодирование всех деревьев спектра (с оптимизированной топологией).
См. функцию _real_encode_tight() для дополнительной информации. Стоит
очень осторожно относиться к этому параметру, так как при выставлении
его в <i>true</i> модели арифметического кодера изменяются, что
затрудняет использование этой функции в процедурах подбора параметров
кодирования. Однако, также есть и приемущества. Если параметр выставлен
в <i>true</i>, то после проведённой оптимизации можно не производить
реальное кодирование, так как оно уже сделано (о чем будет указывать
поле результата optimize_result_t::real_encoded).
\return Результат проведённой оптимизации
Для корректной работы этой функции необходимо, чтобы поля wnode::w и
wnode::wq элементов спектра были корректны. В спектре все ветви должны
быть отмечены как подрезанные, а элементы как корректные. Значения
функций <i>Лагранжа</i> в спектре должны быть обнулены. Арифметический
кодер должен быть настроен на корректные модели (смотри acoder::use()).
\note Необходимую подготовку выполняет функция wtree::filling_refresh(),
при условии, что поля wnode::w и wnode::wq корректны.
\note Если определён макрос #LIBWIC_DEBUG, функция будет выводить
специальную отладочную информацию.
*/
encoder::optimize_result_t
encoder::_optimize_wtree(const lambda_t &lambda,
const bool refresh_wtree,
const bool virtual_encode,
const bool precise_bpp)
{
// Инициализация возвращаемого результата
optimize_result_t result;
result.q = _wtree.q();
result.lambda = lambda;
result.j = 0;
result.bpp = 0;
result.models.version = MODELS_DESC_NONE;
result.real_encoded = false;
// Обновление дерева вейвлет коэффициентов (если требуется)
if (refresh_wtree) _wtree.filling_refresh();
#ifdef LIBWIC_USE_DBG_SURFACE
// Очистка отладочной поверхности
_dbg_opt_surface.clear();
#endif
// Оптимизация топологии ветвей с кодированием
_acoder.encode_start();
for (wtree::coefs_iterator i =
_wtree.iterator_over_subband(_wtree.sb().get_LL());
!i->end(); i->next())
{
// корень очередного дерева коэффициентов вейвлет преобразования
const p_t &root = i->get();
// оптимизация топологии отдельной ветви
result.j += _optimize_tree(root, lambda);
// кодирование отдельной ветви
_encode_tree(root, virtual_encode);
}
_acoder.encode_stop();
#ifdef LIBWIC_USE_DBG_SURFACE
// Сохранение полей отладочной поверхности в файлы
_dbg_opt_surface.save<wicdbg::dbg_pixel::member_wc>
("dumps/[encoder]dbg_opt_suface.wc.bmp", true);
_dbg_opt_surface.save<wicdbg::dbg_pixel::member_wc_model>
("dumps/[encoder]dbg_opt_suface.wc_model.bmp", true);
_dbg_opt_surface.save<wicdbg::dbg_pixel::member_n>
("dumps/[encoder]dbg_opt_suface.n.bmp", true);
#endif
// подсчёт bpp, если производилось реальное кодирование
if (precise_bpp)
{
result.bpp = _real_encode_tight(result.models);
result.real_encoded = true;
}
else if (!virtual_encode)
{
result.bpp = _calc_encoded_bpp();
}
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "[OWTR]:";
_dbg_out_stream << " q: " << std::setw(8) << _wtree.q();
_dbg_out_stream << " lambda: " << std::setw(8) << lambda;
_dbg_out_stream << " j: " << std::setw(8) << result.j;
_dbg_out_stream << " bpp: " << std::setw(8) << result.bpp;
_dbg_out_stream << std::endl;
}
#endif
// обратный вызов пользовательской функции
if (0 != _optimize_callback)
{
_optimize_callback(result, _optimize_callback_param);
}
// возврат результата
return result;
}
/*! \param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\param[in] models Описание моделей арифметического кодера, которые
необходимо использовать для проведения оптимизации
\param[in] refresh_wtree Если <i>true</i>, то перед началом кодирования
будет вызвана функция wtree::filling_refresh(), которая сбросит спекрт
в начальное состояние. Используется при выполнении нескольких операций
оптимизации над одним спектром (например, в целях подбора оптимального
значение параметра <i>lambda</i>).
\param[in] virtual_encode Если <i>true</i>, то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток). При включённом виртуальном
кодировании, поле _optimize_result_t::bpp выставляется в 0, так как
без проведения реального кодирование невозможно оценить битовые
затраты.
\param[in] precise_bpp Если <i>true</i>, то после этапа оптимизации
будет проведён этап уточнения битовых затрат, заключающийся в том, что
модели арифметического кодера будут уменьшены функцией
_setup_acoder_post_models(), а затем будет произведено реальное
кодирование всех деревьев спектра (с оптимизированной топологией).
См. функцию _real_encode_tight() для дополнительной информации. Стоит
очень осторожно относиться к этому параметру, так как при выставлении
его в <i>true</i> модели арифметического кодера изменяются, что
затрудняет использование этой функции в процедурах подбора параметров
кодирования. Однако, также есть и приемущества. Если параметр выставлен
в <i>true</i>, то после проведённой оптимизации можно не производить
реальное кодирование, так как оно уже сделано (о чем будет указывать
поле результата optimize_result_t::real_encoded).
\sa _optimize_wtree()
*/
encoder::optimize_result_t
encoder::_optimize_wtree_m(const lambda_t &lambda,
const models_desc_t &models,
const bool refresh_wtree,
const bool virtual_encode,
const bool precise_bpp)
{
// Установка моделей арифметического кодера
_acoder.use(_mk_acoder_models(models));
// проведение оптимизации топологии
return _optimize_wtree(lambda, refresh_wtree, virtual_encode, precise_bpp);
}
/*! \param[in] lambda Параметр <i>lambda</i> используемый для
вычисления <i>RD</i> критерия (функции Лагранжа). Представляет
собой баланс между ошибкой и битовыми затратами.
\param[in] q Квантователь
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
\param[in] precise_bpp Если <i>true</i>, будет произведено уточнение
битовых затрат путем проведения реального кодирования с ужатыми
моделями арифметического кодера (см. _real_encode_tight). В этом случае,
после этапа оптимизации нет нужды производить реальное кодирование, так
как оно уже произведено функцией _real_encode_tight. Однако следует
обратить внимание, что текущие модели арифметического кодера после
выполнения функции изменяются.
\return Результат проведённой оптимизации
Эта версия функции <i>%encoder::_optimize_wtree()</i> сама производит
квантование и настройку моделей арифметического кодера. Для корректной
работы функции достаточно загруженных коэффициентов в поле wnode::w
элементов спектра.
*/
encoder::optimize_result_t
encoder::_optimize_wtree_q(const lambda_t &lambda, const q_t &q,
const bool virtual_encode,
const bool precise_bpp)
{
// квантование коэффициентов
_wtree.quantize(q);
// загрузка моделей в арифметический кодер
const models_desc_t models = _setup_acoder_models();
// оптимизация топологии ветвей
optimize_result_t result = _optimize_wtree_m(lambda, models, false,
virtual_encode, precise_bpp);
// Сохранение описания моделей арифметического кодера
if (MODELS_DESC_NONE == result.models.version)
{
result.models = models;
}
// возврат результата
return result;
}
/*! \param[in] lambda Параметр <i>lambda</i> используемый для вычисления
<i>RD критерия</i> (<i>функции Лагранжа</i>). Представляет собой баланс
между ошибкой и битовыми затратами. Меньшие значения <i>lambda</i>
соответствуют большему значению результиру<i>bpp</i>.
\param[in] q_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] q_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] q_eps Необходимая погрешность определения квантователя
<i>q</i> при котором значение <i>RD функции Лагранжа</i> минимально
(при фиксированном параметре <i>lambda</i>).
\param[in] j_eps Необходимая погрешность нахождения минимума <i>RD
функции Лагранжа</i>. Так как абсолютная величина функции <i>J</i>
зависит от многих факторов (таких как размер изображения, его тип,
величины параметра <i>lambda</i>), использовать это параметр
затруднительно. Поэтому его значение по умолчанию равно <i>0</i>,
чтобы при поиске оптимального квантователя учитывалась только
погрешность параметра <i>q</i>.
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток). Виртуальное кодирование немного
быстрее, но его использование делает невозможным определение средних
битовых затрат на кодирование одного пиксела изображения.
\param[in] max_iterations Максимальное количество итераций нахождения
минимума <i>RD функции Лагранжа</i>. Если это значение равно <i>0</i>,
количество выполняемых итераций не ограничено.
\param[in] precise_bpp Если <i>true</i>, при выполнении операции
оптимизации топологии будет производиться уточнение битовых затрат путем
проведения реального кодирования с ужатыми моделями арифметического кодера
(см. _real_encode_tight). В этом случае, после этапа оптимизации нет нужды
производить реальное кодирование, так как оно уже произведено функцией
_real_encode_tight.
\return Результат произведённого поиска
Данная функция использует метод золотого сечения для поиска минимума
<i>RD функции Лагранжа</i>:
\verbatim
j|___ ______/
| \_ __/ |
| \___ / |
| | \____ / |
| | | \___ ______/ |
| | | \_/ | |
| | | | | |
---+-------+---+-------+------+---------+----------> q
0| a b j_min c d
\endverbatim
\note Для корректной работы этой функции необходимо, чтобы поле
wnode::w элементов спектра было корректно. Для этого
можно использовать функцию wtree::load_field().
\note Если определён макрос #LIBWIC_DEBUG, функция будет выводить
специальную отладочную информацию.
*/
encoder::optimize_result_t
encoder::_search_q_min_j(const lambda_t &lambda,
const q_t &q_min, const q_t &q_max,
const q_t &q_eps, const j_t &j_eps,
const bool virtual_encode,
const sz_t &max_iterations,
const bool precise_bpp)
{
// проверка утверждений
assert(0 <= lambda);
assert(1 <= q_min && q_min <= q_max);
assert(0 <= q_eps && 0 <= j_eps);
// коэффициенты золотого сечения
static const q_t factor_b = (q_t(3) - sqrt(q_t(5))) / q_t(2);
static const q_t factor_c = (sqrt(q_t(5)) - q_t(1)) / q_t(2);
// установка диапазона для поиска
q_t q_a = q_min;
q_t q_d = q_max;
// вычисление значений в первых двух точках
q_t q_b = q_a + factor_b * (q_d - q_a);
q_t q_c = q_a + factor_c * (q_d - q_a);
optimize_result_t result_b = _optimize_wtree_q(lambda, q_b, virtual_encode,
precise_bpp);
optimize_result_t result_c = _optimize_wtree_q(lambda, q_c, virtual_encode,
precise_bpp);
// запоминание предыдущего и последнего результатов
optimize_result_t result_prev = result_b;
optimize_result_t result = result_c;
// подсчёт количества итераций
sz_t iterations = 0;
// поиск оптимального значения q
for (;;)
{
// проверка, достигнута ли нужная точность
if (q_eps >= abs(q_c - q_b) ||
j_eps >= abs(result.j - result_prev.j))
{
break;
}
if (0 < max_iterations && max_iterations <= iterations)
{
break;
}
// скоро будет получен новый результат
result_prev = result;
// выбор очередного значения q
if (result_b.j < result_c.j)
{
q_d = q_c;
q_c = q_b;
q_b = q_a + factor_b*(q_d - q_a);
result_c = result_b;
result = result_b = _optimize_wtree_q(lambda, q_b, virtual_encode,
precise_bpp);
}
else
{
q_a = q_b;
q_b = q_c;
q_c = q_a + factor_c*(q_d - q_a);
result_b = result_c;
result = result_c = _optimize_wtree_q(lambda, q_c, virtual_encode,
precise_bpp);
}
// увеличение количества итераций
++iterations;
}
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "[SQMJ]:";
_dbg_out_stream << " q: " << std::setw(8) << result.q;
_dbg_out_stream << " lambda: " << std::setw(8) << result.lambda;
_dbg_out_stream << " j: " << std::setw(8) << result.j;
_dbg_out_stream << " bpp: " << std::setw(8) << result.bpp;
_dbg_out_stream << std::endl;
}
#endif
// возвращение полученного результата
return result;
}
/*! \param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будет подбираться параметр <i>lambda</i>
\param[in] bpp_eps Необходимая точность, c которой <i>bpp</i> полученный
в результате поиска параметра <i>lambda</i> будет соответствовать
заданному.
\param[in] lambda_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] lambda_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] lambda_eps Точность, с которой будет подбираться параметр
<i>lambda</i>.
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток).
\param[in] max_iterations Максимальное количество итераций нахождения
минимума <i>RD функции Лагранжа</i>. Если это значение равно <i>0</i>,
количество выполняемых итераций не ограничено.
\param[in] precise_bpp Если <i>true</i>, при выполнении операции
оптимизации топологии будет производиться уточнение битовых затрат путем
проведения реального кодирования с ужатыми моделями арифметического кодера
(см. _real_encode_tight). В этом случае, после этапа оптимизации нет нужды
производить реальное кодирование, так как оно уже произведено функцией
_real_encode_tight.
\return Результат проведённого поиска. Возможна ситуация, когда нужная
<i>lambda</i> лежит вне указанного диапазона. В этом случае, функция
подберёт такую <i>lambda</i>, которая максимально удовлетворяет условиям
поиска.
Поиск оптимального значения <i>lambda</i> производится дихотомией
(методом половинного деления). Поиск будет считаться успешным, если
найдено такое значение <i>lambda</i>, при котором полученный <i>bpp</i>
меньше чем на <i>bpp_eps</i> отличается от заданного <i>или</i> в
процессе поиска диапазон значений <i>lambda</i> сузился до
<i>lambda_eps</i>.
Меньшие значения <i>lambda</i> соответствуют большему
значению <i>bpp</i>:
\verbatim
|_____
| \________
| | \_________
bpp+-------+----------------\-----------------------
| | \_______
| | | \______________
---+-------+-------------------+--------------------
0| lambda_min lambda_max
\endverbatim
\note Для корректной работы этой функции необходимо, чтобы поля
wnode::w и wnode::wq элементов спектра были корректны. Для этого
можно использовать функцию wtree::cheap_load(). Также очень важно,
чтобы модели арифметического кодера были хорошо настроены (а их
начальные характеристика запомнены). Для этого можно воспользоваться
кодом следующего вида:
\code
// описание моделей, которое будет использовано в дальнейшем при
// декодировании
models_desc_t models;
// создание описания моделей исходя из характеристик спектра
models = _mk_acoder_smart_models();
// конвертация описания моделей в формат приемлемый для арифметического
// кодера и предписание ему начать использовать полученные модели для
// кодирования или декодирования
_acoder.use(_mk_acoder_models(models));
\endcode
\note Если определён макрос #LIBWIC_DEBUG, функция будет выводить
специальную отладочную информацию.
*/
encoder::optimize_result_t
encoder::_search_lambda_at_bpp(
const h_t &bpp, const h_t &bpp_eps,
const lambda_t &lambda_min,
const lambda_t &lambda_max,
const lambda_t &lambda_eps,
const bool virtual_encode,
const sz_t &max_iterations,
const bool precise_bpp)
{
// проверка утверждений
assert(0 < bpp);
assert(0 <= lambda_min && lambda_min <= lambda_max);
assert(0 <= bpp_eps && 0 <= lambda_eps);
// установка диапазона для поиска
lambda_t lambda_a = lambda_min;
lambda_t lambda_b = lambda_max;
// Запоминание текущих моделей арифметического кодера
const acoder::models_t original_models = _acoder.models();
// результат последней оптимизации
optimize_result_t result;
result.q = 0;
result.lambda = 0;
result.j = 0;
result.bpp = 0;
result.real_encoded = false;
// счётчик итераций
sz_t iterations = 0;
// небольшая хитрость, позволяющая использовать удобный оператор
// break
do
{
// вычисление значений bpp на левой границе диапазона. Тут нет нужды
// использовать функцию _optimize_wtree_m() так как модели
// арифметического кодера ещё не испорчены
optimize_result_t result_a = _optimize_wtree(lambda_a, true,
virtual_encode,
precise_bpp);
// проверка на допустимость входного диапазона
if (result_a.bpp <= (bpp + bpp_eps))
{
result = result_a;
break;
}
// восстановление моделей арифметического кодера, если они были
// изменены функцией оптимизации топологии
_restore_spoiled_models(result_a, original_models);
// вычисление значений bpp на правой границе диапазона
optimize_result_t result_b = _optimize_wtree(lambda_b, true,
virtual_encode,
precise_bpp);
// проверка на допустимость входного диапазона
if (result_b.bpp >= (bpp - bpp_eps))
{
result = result_b;
break;
}
// Внимание: здесь переменная result не обязательно инициализированна,
// но даже будучи инициализированной она не пригодна для возврата
// в качестве результата так как может отражать результат предыдущей
// оптимизации, а не последней!!!
// Ввиду выше описанного нет ничего повинного в следующей строчке,
// которая нужна чтобы упростить дальнейшую логику восстановления
// моделей арифметического кодера, для которой необходимо, чтобы в
// переменной result был результат последней проведённой оптимизации
result = result_b;
// поиск оптимального значения lamda (дихотомия)
for (;;)
{
// подсчёт значения bpp для середины диапазона
const lambda_t lambda_c = (lambda_b + lambda_a) / 2;
// восстановление моделей арифметического кодера, если они были
// изменены функцией оптимизации топологии
_restore_spoiled_models(result, original_models);
// оптимизация топологии ветвей
result = _optimize_wtree(lambda_c, true, virtual_encode,
precise_bpp);
// проверить, достигнута ли нужная точность по bpp
if (bpp_eps >= abs(result.bpp - bpp)) break;
// проверить, не превышен ли лимит по итерациям
if (0 < max_iterations && max_iterations <= iterations) break;
// сужение диапазона поиска
if (bpp > result.bpp)
lambda_b = lambda_c;
else
lambda_a = lambda_c;
// проверить, достигнута ли нужная точность по lambda
if (lambda_eps >= abs(lambda_b - lambda_a)) break;
// Увеличение счётчика итераций
++iterations;
}
}
while (false);
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "[SLAB]: ";
_dbg_out_stream << "q: " << std::setw(8) << result.q;
_dbg_out_stream << " lambda: " << std::setw(8) << result.lambda;
_dbg_out_stream << " j: " << std::setw(8) << result.j;
_dbg_out_stream << " bpp: " << std::setw(8) << result.bpp;
_dbg_out_stream << std::endl;
}
#endif
// возвращение полученного результата
return result;
}
/*! \param[in] q Квантователь, который будет использован для квантования
спектра вейвлет коэффициентов
\param[in] bpp Целевые битовые затраты на кодирование изображения. При
поиске параметра <i>lambda</i> функцией _search_lambda_at_bpp() будет
использовано это значение в качестве соответствующего аргумента.
\param[in] bpp_eps Допустимая погрешность достижения заданных битовых
затрат. При поиске параметра <i>lambda</i> функцией _search_lambda_at_bpp()
будет использовано это значение в качестве соответствующего аргумента.
\param[in] lambda_eps Точность, с которой будет подбираться параметр
<i>lambda</i>
\param[out] models Описание моделей арифметического кодера, которое
необходимо для последующего декодирования изображения
\param[out] d Среднеквадратичное отклонение оптимизированного спектра
от исходного. Играет роль ошибки, вносимой алгоритмом сжатия.
\param[out] deviation Отклонение от заданного <i>bpp</i>. Если
результирующий <i>bpp</i> находится в пределах погрешности <i>bpp_eps</i>
этот аргумент выставляется в <i>0</i>. Иначе аргумент выставляется в
значение разности между желаемым <i>bpp</i> и полученным в процессе поиска
параметра <i>lambda</i>. Таким образом, получение отрицательных значений
аргумента означает, что полученный <i>bpp</i> больше желаемого и параметр
<i>q</i> необходимо увеличить (или поднять верхнию границу диапазона
поиска параметра <i>lambda</i>). Если же агрумент получит положительное
значение, то параметр <i>q</i> необходимо уменьшить (или опустить нижнию
границу диапазона поиска параметра <i>lambda</i>).
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток). Виртуальное кодирование немного
быстрее, но его использование делает невозможным определение средних
битовых затрат на кодирование одного пиксела изображения.
\param[in] max_iterations Максимальное количество итераций, выполняемых
функцией _search_lambda_at_bpp()
\param[in] precise_bpp Если <i>true</i>, при выполнении операции
оптимизации топологии будет производиться уточнение битовых затрат путем
проведения реального кодирования с ужатыми моделями арифметического кодера
(см. _real_encode_tight). В этом случае, после этапа оптимизации нет нужды
производить реальное кодирование, так как оно уже произведено функцией
_real_encode_tight.
\return Результат произведённого поиска
Параметр <i>lambda</i> будет искаться в диапазоне
<i>[0.05*q*q, 0.20*q*q]</i>.
\note Для корректной работы, функции необходимо, чтобы значения полей
wnode::w были корректны (содержали в себе коэффициенты исходного спектра).
\sa _search_lambda_at_bpp(), _search_q_lambda_for_bpp()
*/
encoder::optimize_result_t
encoder::_search_q_lambda_for_bpp_iter(
const q_t &q, const h_t &bpp,
const h_t &bpp_eps, const lambda_t &lambda_eps,
models_desc_t &models, w_t &d, h_t &deviation,
const bool virtual_encode,
const sz_t &max_iterations,
const bool precise_bpp)
{
// квантование спектра
_wtree.quantize(q);
// определение характеристик моделей арифметического кодера
models = _setup_acoder_models();
// выбор диапазона поиска параметра lambda
const lambda_t lambda_min = lambda_t(0.05f * q*q);
const lambda_t lambda_max = lambda_t(0.20f * q*q);
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "[SQLI]: ";
_dbg_out_stream << "q: " << std::setw(8) << q;
_dbg_out_stream << " lambda_min: " << std::setw(8) << lambda_min;
_dbg_out_stream << " lambda_max: " << std::setw(8) << lambda_max;
_dbg_out_stream << std::endl;
}
#endif
// поиск параметра lambda
const optimize_result_t result =
_search_lambda_at_bpp(bpp, bpp_eps,
lambda_min, lambda_max, lambda_eps,
virtual_encode, max_iterations,
precise_bpp);
// подсчёт среднеквадратичного отклонения (ошибки)
d = _wtree.distortion_wc<w_t>();
// установка параметра отклонения
if (result.bpp > bpp + bpp_eps)
deviation = (bpp - result.bpp); // q необходимо увеличить (-1)
else if (result.bpp < bpp - bpp_eps)
deviation = (bpp - result.bpp); // q необходимо уменьшить (+1)
else
deviation = 0; // q удовлетворительное
// вывод отладочной информации
#ifdef LIBWIC_DEBUG
if (_dbg_out_stream.good())
{
_dbg_out_stream << "[SQLI]: ";
_dbg_out_stream << "q: " << std::setw(8) << result.q;
_dbg_out_stream << " lambda: " << std::setw(8) << result.lambda;
_dbg_out_stream << " j: " << std::setw(8) << result.j;
_dbg_out_stream << " bpp: " << std::setw(8) << result.bpp;
_dbg_out_stream << " d: " << std::setw(8) << d;
_dbg_out_stream << " deviation: " << std::setw(8) << deviation;
_dbg_out_stream << std::endl;
}
#endif
// возврат результата
return result;
}
/*! \param[in] bpp Необходимый битрейт (Bits Per Pixel), для достижения
которого будут подбираться параметры <i>q</i> и <i>lambda</i>.
\param[in] bpp_eps Необходимая точность, c которой <i>bpp</i> полученный
в результате поиска параметров <i>q</i> и <i>lambda</i> будет
соответствовать заданному.
\param[in] q_min Нижняя граница интервала поиска (минимальное
значение)
\param[in] q_max Верхняя граница интервала поиска (максимальное
значение)
\param[in] q_eps Необходимая погрешность определения квантователя
<i>q</i> при котором значение <i>RD функции Лагранжа</i> минимально
(при фиксированном параметре <i>lambda</i>).
\param[in] lambda_eps Точность, с которой будет подбираться параметр
<i>lambda</i>
\param[out] models Описание моделей арифметического кодера, которое
необходимо для последующего декодирования изображения
\param[in] virtual_encode Если <i>true</i> то будет производиться
виртуальное кодирование (только перенастройка моделей, без помещения
кодируемого символа в выходной поток). Виртуальное кодирование немного
быстрее, но его использование делает невозможным определение средних
битовых затрат на кодирование одного пиксела изображения.
\param[in] precise_bpp Если <i>true</i>, при выполнении операции
оптимизации топологии будет производиться уточнение битовых затрат путем
проведения реального кодирования с ужатыми моделями арифметического кодера
(см. _real_encode_tight). В этом случае, после этапа оптимизации нет нужды
производить реальное кодирование, так как оно уже произведено функцией
_real_encode_tight.
Функция использует метод золотого сечения для подбора параметра <i>q</i>,
а для подбора параметра <i>lambda</i> использует функцию
_search_q_lambda_for_bpp_iter().
\sa _search_q_lambda_for_bpp_iter(), _search_q_lambda_for_bpp()
*/
encoder::optimize_result_t
encoder::_search_q_lambda_for_bpp(
const h_t &bpp, const h_t &bpp_eps,
const q_t &q_min, const q_t &q_max,
const q_t &q_eps, const lambda_t &lambda_eps,
models_desc_t &models,
const bool virtual_encode,
const bool precise_bpp)
{
// максимальное количество итераций для подбора параметра lambda
static const sz_t max_iterations = 0;
// коэффициенты золотого сечения
static const q_t factor_b = q_t((3.0 - sqrt(5.0)) / 2.0);
static const q_t factor_c = q_t((sqrt(5.0) - 1.0) / 2.0);
// верхняя и нижняя граница поиска параметра q
q_t q_a = q_min;
q_t q_d = q_max;
// вычисление значений в первых двух точках
q_t q_b = q_a + factor_b * (q_d - q_a);
q_t q_c = q_a + factor_c * (q_d - q_a);
// подбор параметра lambda в первой точке
w_t dw_b = 0;
h_t deviation_b = 0;
optimize_result_t result_b =
_search_q_lambda_for_bpp_iter(
q_b, bpp, bpp_eps, lambda_eps, models,
dw_b, deviation_b, virtual_encode,
max_iterations, precise_bpp);
// подбор параметра lambda во второй точке
w_t dw_c = 0;
h_t deviation_c = 0;
optimize_result_t result_c =
_search_q_lambda_for_bpp_iter(
q_c, bpp, bpp_eps, lambda_eps, models,
dw_c, deviation_c, virtual_encode,
max_iterations, precise_bpp);
// результаты последнего поиска параметра lambda
h_t deviation = deviation_c;
optimize_result_t result = result_c;
// сужение диапазона поиска методом золотого сечения
while (q_eps < abs(q_a - q_d))
{
if (deviation > 0 || (0 == deviation && dw_b <= dw_c))
{
q_d = q_c;
q_c = q_b;
dw_c = dw_b;
q_b = q_a + factor_b * (q_d - q_a);
// a b c d
// a b c d
result = result_b =
_search_q_lambda_for_bpp_iter(
q_b, bpp, bpp_eps, lambda_eps, models,
dw_b, deviation_b, virtual_encode,
max_iterations, precise_bpp);
deviation = deviation_b;
}
else
{
q_a = q_b;
q_b = q_c;
dw_b = dw_c;
q_c = q_a + factor_c * (q_d - q_a);
// a b c d
// a b c d
result = result_c =
_search_q_lambda_for_bpp_iter(
q_c, bpp, bpp_eps, lambda_eps, models,
dw_c, deviation_b, virtual_encode,
max_iterations, precise_bpp);
deviation = deviation_c;
}
}
return result;
}
/*! \return Средние битовые затраты на кодирование спектра вейвлет
коэффициентов
Данная функция использует текущие настройки моделей арифметического кодера
и не изменяет их.
*/
h_t encoder::_real_encode()
{
#ifdef LIBWIC_USE_DBG_SURFACE
#endif
// кодирование всего дерева
_acoder.encode_start();
_encode_wtree();
_acoder.encode_stop();
// подсчёт и возврат средних битовых затрат
return _calc_encoded_bpp();
}
/*! \param[out] desc Описание моделей арифметического кодера, которые
были использованый при кодировании
\param[in] double_path Если <i>true</i> кодирование будет производится
в два прохода. При первом проходе кодирования производится настройка
моделей. Сейчас нет возможности кодировать в один проход (что быстрее)
так как возможен перескок коэффициентов из одной модели в другую.
Связано это с тем, что на этапе оптимизации нам ещё не известны финальные
значения всех коэффициентов и как следствие значение вычисляемых
прогнозов.
\return Средние битовые затраты на кодирование спектра вейвлет
коэффициентов
\attention Следует очень осторожно использовать эту функцию так как
она изменяет модели, используемые арифметическим кодером.
*/
h_t encoder::_real_encode_tight(models_desc_t &desc, const bool double_path)
{
// двойной проход должен быть включён при текущем положении дел
assert(double_path);
// выполнение первого прохода, если необходимо
if (double_path)
{
_setup_acoder_models();
_real_encode();
}
// Определение и установка моделей арифметического кодера
desc = _setup_acoder_post_models();
return _real_encode();
}
/*! \param[in] including_tunes Если этот параметр равен <i>true</i> в
расчёте <i>bpp</i> будет принят во внимание размер дополнительный данных,
необходимых для восстановления изображения, определённых в структуре
tunes_t
\return Среднее количество бит, затрачиваемых на кодирование одного
пикселя
*/
h_t encoder::_calc_encoded_bpp(const bool including_tunes)
{
const sz_t data_sz = coder().encoded_sz()
+ ((including_tunes)? sizeof(tunes_t): 0);
return h_t(data_sz * BITS_PER_BYTE) / h_t(_wtree.nodes_count());
}
/*!
*/
void encoder::_test_wc_136_0()
{
assert(0 != _wtree.at(136, 0).wc);
}
} // end of namespace wic
| [
"wonder_mice@b1028fda-012f-0410-8370-c1301273da9f"
]
| [
[
[
1,
2925
]
]
]
|
c782d5317fd15d108503fa6eb55a377792530f0a | ab41c2c63e554350ca5b93e41d7321ca127d8d3a | /glm/gtx/matx.hpp | ed3a04873241e6d397ac23262fcabbf13b3f37cd | []
| no_license | burner/e3rt | 2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e | 775470cc9b912a8c1199dd1069d7e7d4fc997a52 | refs/heads/master | 2021-01-11T08:08:00.665300 | 2010-04-26T11:42:42 | 2010-04-26T11:42:42 | 337,021 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,763 | hpp | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2007-02-21
// Updated : 2007-03-01
// Licence : This source is under MIT License
// File : glm/gtx/matx.h
///////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency:
// - GLM core
// - GLM_GTX_vecx
// - GLM_GTX_matrix_selection
// - GLM_GTX_matrix_access
// - GLM_GTX_inverse_transpose
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef glm_gtx_matx
#define glm_gtx_matx
// Dependency:
#include "../glm.hpp"
#include "../gtx/vecx.hpp"
namespace glm{
namespace detail{
template <int N, typename T = float>
class _xmatxGTX
{
private:
// Data
_xvecxGTX<N, T> value[N];
public:
_xmatxGTX<N, T> _inverse() const;
public:
typedef T value_type;
typedef int size_type;
static const size_type value_size;
// Constructors
_xmatxGTX();
explicit _xmatxGTX(const T x);
// Accesses
_xvecxGTX<N, T>& operator[](int i) {return value[i];}
const _xvecxGTX<N, T> & operator[](int i) const {return value[i];}
operator T*() {return &value[0][0];}
operator const T*() const {return &value[0][0];}
// Unary updatable operators
_xmatxGTX<N, T>& operator= (const _xmatxGTX<N, T>& m);
_xmatxGTX<N, T>& operator+= (const T s);
_xmatxGTX<N, T>& operator+= (const _xmatxGTX<N, T>& m);
_xmatxGTX<N, T>& operator-= (const T s);
_xmatxGTX<N, T>& operator-= (const _xmatxGTX<N, T>& m);
_xmatxGTX<N, T>& operator*= (const T s);
_xmatxGTX<N, T>& operator*= (const _xmatxGTX<N, T>& m);
_xmatxGTX<N, T>& operator/= (const T s);
_xmatxGTX<N, T>& operator/= (const _xmatxGTX<N, T>& m);
_xmatxGTX<N, T>& operator++ ();
_xmatxGTX<N, T>& operator-- ();
};
// Binary operators
template <int N, typename T>
_xmatxGTX<N, T> operator+ (const _xmatxGTX<N, T>& m, const T s);
template <int N, typename T>
_xmatxGTX<N, T> operator+ (const T s, const _xmatxGTX<N, T>& m);
template <int N, typename T>
_xvecxGTX<N, T> operator+ (const _xmatxGTX<N, T>& m, const _xvecxGTX<N, T>& v);
template <int N, typename T>
_xvecxGTX<N, T> operator+ (const _xvecxGTX<N, T>& v, const _xmatxGTX<N, T>& m);
template <int N, typename T>
_xmatxGTX<N, T> operator+ (const _xmatxGTX<N, T>& m1, const _xmatxGTX<N, T>& m2);
template <int N, typename T>
_xmatxGTX<N, T> operator- (const _xmatxGTX<N, T>& m, const T s);
template <int N, typename T>
_xmatxGTX<N, T> operator- (const T s, const _xmatxGTX<N, T>& m);
template <int N, typename T>
_xvecxGTX<N, T> operator- (const _xmatxGTX<N, T>& m, const _xvecxGTX<N, T>& v);
template <int N, typename T>
_xvecxGTX<N, T> operator- (const _xvecxGTX<N, T>& v, const _xmatxGTX<N, T>& m);
template <int N, typename T>
_xmatxGTX<N, T> operator- (const _xmatxGTX<N, T>& m1, const _xmatxGTX<N, T>& m2);
template <int N, typename T>
_xmatxGTX<N, T> operator* (const _xmatxGTX<N, T>& m, const T s);
template <int N, typename T>
_xmatxGTX<N, T> operator* (const T s, const _xmatxGTX<N, T>& m);
template <int N, typename T>
_xvecxGTX<N, T> operator* (const _xmatxGTX<N, T>& m, const _xvecxGTX<N, T>& v);
template <int N, typename T>
_xvecxGTX<N, T> operator* (const _xvecxGTX<N, T>& v, const _xmatxGTX<N, T>& m);
template <int N, typename T>
_xmatxGTX<N, T> operator* (const _xmatxGTX<N, T>& m1, const _xmatxGTX<N, T>& m2);
template <int N, typename T>
_xmatxGTX<N, T> operator/ (const _xmatxGTX<N, T>& m, const T s);
template <int N, typename T>
_xmatxGTX<N, T> operator/ (const T s, const _xmatxGTX<N, T>& m);
template <int N, typename T>
_xvecxGTX<N, T> operator/ (const _xmatxGTX<N, T>& m, const _xvecxGTX<N, T>& v);
template <int N, typename T>
_xvecxGTX<N, T> operator/ (const _xvecxGTX<N, T>& v, const _xmatxGTX<N, T>& m);
template <int N, typename T>
_xmatxGTX<N, T> operator/ (const _xmatxGTX<N, T>& m1, const _xmatxGTX<N, T>& m2);
// Unary constant operators
template <int N, typename T>
const _xmatxGTX<N, T> operator- (const _xmatxGTX<N, T>& m);
template <int N, typename T>
const _xmatxGTX<N, T> operator-- (const _xmatxGTX<N, T>& m, int);
template <int N, typename T>
const _xmatxGTX<N, T> operator++ (const _xmatxGTX<N, T>& m, int);
}//namespace detail
// Extension functions
template <int N, typename T> detail::_xmatxGTX<N, T> matrixCompMultGTX(const detail::_xmatxGTX<N, T>& x, const detail::_xmatxGTX<N, T>& y);
template <int N, typename T> detail::_xmatxGTX<N, T> outerProductGTX(const detail::_xvecxGTX<N, T>& c, const detail::_xvecxGTX<N, T>& r);
template <int N, typename T> detail::_xmatxGTX<N, T> transposeGTX(const detail::_xmatxGTX<N, T>& x);
template <int N, typename T> T determinantGTX(const detail::_xmatxGTX<N, T>& m);
template <int N, typename T> detail::_xmatxGTX<N, T> inverseTransposeGTX(const detail::_xmatxGTX<N, T> & m);
template <int N, typename T> void columnGTX(detail::_xmatxGTX<N, T>& m, int ColIndex, const detail::_xvecxGTX<N, T>& v);
template <int N, typename T> void rowGTX(detail::_xmatxGTX<N, T>& m, int RowIndex, const detail::_xvecxGTX<N, T>& v);
template <int N, typename T> detail::_xvecxGTX<N, T> columnGTX(const detail::_xmatxGTX<N, T>& m, int ColIndex);
template <int N, typename T> detail::_xvecxGTX<N, T> rowGTX(const detail::_xmatxGTX<N, T>& m, int RowIndex);
namespace gtx
{
//! GLM_GTX_matx extension: - Work in progress - NxN matrix types.
namespace matx
{
// Matrix Functions
template <int N, typename T> inline detail::_xmatxGTX<N, T> matrixCompMult(const detail::_xmatxGTX<N, T>& x, const detail::_xmatxGTX<N, T>& y){return matrixCompMult(x, y);}
template <int N, typename T> inline detail::_xmatxGTX<N, T> outerProduct(const detail::_xvecxGTX<N, T>& c, const detail::_xvecxGTX<N, T>& r){return outerProductGTX(c, r);}
template <int N, typename T> inline detail::_xmatxGTX<N, T> transpose(const detail::_xmatxGTX<N, T>& x){return transposeGTX(x);}
template <int N, typename T> inline T determinant(const detail::_xmatxGTX<N, T>& m){return determinantGTX(m);}
template <int N, typename T> inline detail::_xmatxGTX<N, T> inverseTranspose(const detail::_xmatxGTX<N, T>& m){return inverseTransposeGTX(m);}
template <int N, typename T> inline void column(detail::_xmatxGTX<N, T>& m, int ColIndex, const detail::_xvecxGTX<N, T>& v){setColumnGTX(m, v);}
template <int N, typename T> inline void row(detail::_xmatxGTX<N, T>& m, int RowIndex, const detail::_xvecxGTX<N, T>& v){setRowGTX(m, v);}
template <int N, typename T> inline detail::_xvecxGTX<N, T> column(const detail::_xmatxGTX<N, T>& m, int ColIndex){return column(m, ColIndex);}
template <int N, typename T> inline detail::_xvecxGTX<N, T> row(const detail::_xmatxGTX<N, T>& m, int RowIndex){return row(m, RowIndex);}
}
}
}
#define GLM_GTX_matx namespace gtx::matx
#ifndef GLM_GTX_GLOBAL
namespace glm {using GLM_GTX_matx;}
#endif//GLM_GTX_GLOBAL
#include "matx.inl"
#endif//glm_gtx_matx
| [
"[email protected]"
]
| [
[
[
1,
182
]
]
]
|
e83eb131048c2dc3edace93df8973ee992f06cc9 | 898c56a96d977ff0bcfbaa87aef5e8fcce5a01db | /usr_include/GoogleTilesLoader.h | a2ba8f236e2e2cb22a4ef97ef724a67435abb3c4 | []
| no_license | pecc0/jw-earth | e00d64523bb6f983196edade38f7c05b3d4ad3ec | ee6df165a9625fdba8ba406055ae10f6bf03beac | refs/heads/master | 2016-09-05T23:28:26.383570 | 2011-03-05T22:59:41 | 2011-03-05T22:59:41 | 38,072,455 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 566 | h | /*
* GoogleTilesLoader.h
*
* Created on: Feb 11, 2011
* Author: Petko
*/
#ifndef GOOGLETILESLOADER_H_
#define GOOGLETILESLOADER_H_
#define cimg_use_jpeg
#include <string>
#include "CImg.h"
using namespace cimg_library;
using namespace std;
typedef unsigned char pixelFormat;
class GoogleTilesLoader
{
private:
string m_sTmpDir;
public:
GoogleTilesLoader();
GoogleTilesLoader(string& tmpDir);
virtual ~GoogleTilesLoader();
CImg<pixelFormat>* loadTile(int x, int y, int z);
};
#endif /* GOOGLETILESLOADER_H_ */
| [
"petkodp@b00f97f9-4d11-03a6-6959-139d95cb2541"
]
| [
[
[
1,
33
]
]
]
|
9e71907226d650976b45b7f01e0a039b123533b1 | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/apps/mermaid/jpaintarea.h | 09f454a7262db59a653c9797c7b5b7af7b818cee | []
| no_license | dtbinh/rush | 4294f84de1b6e6cc286aaa1dd48cf12b12a467d0 | ad75072777438c564ccaa29af43e2a9fd2c51266 | refs/heads/master | 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null | UTF-8 | C++ | false | false | 1,022 | h | /***********************************************************************************/
/* File: JPaintArea.h
/* Date: 27.05.2006
/* Author: Ruslan Shestopalyuk
/***********************************************************************************/
#ifndef __JPaintArea_H__
#define __JPaintArea_H__
/***********************************************************************************/
/* Class: JPaintArea
/* Desc:
/***********************************************************************************/
class JPaintArea : public JButton
{
public:
JPaintArea ();
virtual void Render ();
virtual void Init ();
DWORD GetColor () const { return GetBgColor(); }
virtual bool PtIn ( int px, int py ) const;
expose( JPaintArea )
{
parent( JButton );
}
private:
bool PtInArea ( int px, int py ) const;
}; // class JPaintArea
#endif //__JPaintArea_H__ | [
"[email protected]"
]
| [
[
[
1,
31
]
]
]
|
3aa547ef12e81a8f430104ce4419df0f9de687b7 | 0033659a033b4afac9b93c0ac80b8918a5ff9779 | /game/shared/so2/weapon_sobasebasebludgeon.h | 80e6ab79151fae750f80c3ca9f3d2ff84abd1f08 | []
| no_license | jonnyboy0719/situation-outbreak-two | d03151dc7a12a97094fffadacf4a8f7ee6ec7729 | 50037e27e738ff78115faea84e235f865c61a68f | refs/heads/master | 2021-01-10T09:59:39.214171 | 2011-01-11T01:15:33 | 2011-01-11T01:15:33 | 53,858,955 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,983 | h | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: The class from which all bludgeon melee
// weapons are derived.
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#include "weapon_sobasehlmpcombatweapon.h"
#ifndef BASEBLUDGEONWEAPON_H
#define BASEBLUDGEONWEAPON_H
#ifdef _WIN32
#pragma once
#endif
#if defined( CLIENT_DLL )
#define CBaseSOBludgeonWeapon C_BaseSOBludgeonWeapon
#endif
//=========================================================
// CBaseHLBludgeonWeapon
//=========================================================
class CBaseSOBludgeonWeapon : public CBaseSOCombatWeapon
{
DECLARE_CLASS( CBaseSOBludgeonWeapon, CBaseSOCombatWeapon );
public:
CBaseSOBludgeonWeapon();
DECLARE_NETWORKCLASS();
DECLARE_PREDICTABLE();
virtual void Spawn( void );
virtual void Precache( void );
//Attack functions
virtual void PrimaryAttack( void );
virtual void SecondaryAttack( void );
virtual void ItemPostFrame( void );
//Functions to select animation sequences
virtual Activity GetPrimaryAttackActivity( void ) { return ACT_VM_HITCENTER; }
virtual Activity GetSecondaryAttackActivity( void ) { return ACT_VM_HITCENTER2; }
virtual float GetFireRate( void ) { return 0.2f; }
virtual float GetRange( void ) { return 32.0f; }
virtual float GetDamageForActivity( Activity hitActivity ) { return 1.0f; }
CBaseSOBludgeonWeapon( const CBaseSOBludgeonWeapon & );
protected:
virtual void ImpactEffect( trace_t &trace );
private:
bool ImpactWater( const Vector &start, const Vector &end );
void Swing( int bIsSecondary );
void Hit( trace_t &traceHit, Activity nHitActivity );
Activity ChooseIntersectionPointAndActivity( trace_t &hitTrace, const Vector &mins, const Vector &maxs, CBasePlayer *pOwner );
};
#endif | [
"MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61"
]
| [
[
[
1,
66
]
]
]
|
2a022af64f06e0d83a1fc0299684586c7f32c27d | edc1580926ff41a9c4e1eb1862bbdd7ce7fa46f9 | /IMesh/IMesh.UI/ModelViewAdjuster.h | 74415b5b6a8d089af97b8810e17a0f2af99b2465 | []
| no_license | bolitt/imesh-thu | 40209b89393981fa6bd6ed3c7f5cc367829bd913 | 477204edee0f387e92eec5e92283fb4233cbdcb3 | refs/heads/master | 2021-01-01T05:31:36.652001 | 2010-12-26T14:35:28 | 2010-12-26T14:35:28 | 32,119,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | h | #pragma once
#include "Structures.h"
namespace IMesh { namespace UI { namespace Models {
class ModelViewAdjuster
{
public:
ModelViewAdjuster(void);
~ModelViewAdjuster(void);
// For Model:
float m_translateX;
float m_translateY;
float m_translateZ;
float m_scaleRate;
Num::Vec3f m_lowest;
Num::Vec3f m_highest;
public:
void Initialize(Num::Vec3f& lowest, Num::Vec3f& highest);
Num::Vec3f Adjust(Num::Vec3f& v);
Num::Vec3f Adjust(float x, float y, float z);
};
} } }
| [
"bolitt@13b8c736-bc73-099a-6f45-29f97c997e63"
]
| [
[
[
1,
27
]
]
]
|
32b7edacf8731e89890c3be1c53bb35562bbdf45 | 3dca0a6382ea348a8617be05e1bfa6f4ed70d77c | /src/PgeMatrix3D.cpp | 74cee93c8c697e5fc421ce0da2e35dab6f2fd7da | []
| no_license | David-Haim-zz/pharaoh-game-engine | 9c766916559f9c74667e981b9b3f03b43920bc4e | b71db3fd99ebad0ab40a0888360d560748f63131 | refs/heads/master | 2021-05-29T15:17:23.043407 | 2011-01-23T17:53:39 | 2011-01-23T17:53:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,723 | cpp |
/*! $Id$
* @file PgePoint3D.h
* @author Chad M. Draper
* @date May 7, 2007
*
*/
#include <assert.h>
#include "PgeMatrix3D.h"
#include "PgePoint3D.h"
#include "PgeMath.h"
namespace PGE
{
const Matrix3D Matrix3D::ZERO;
const Matrix3D Matrix3D::IDENTITY( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 );
Matrix3D::Matrix3D()
{
memset( m, 0, sizeof( Real ) * 16 );
}
Matrix3D::Matrix3D( Real mat[ 4 ][ 4 ] )
{
memcpy( m, mat, sizeof( Real ) * 16 );
}
Matrix3D::Matrix3D( const Matrix3D& mat )
{
memcpy( m, mat.m, sizeof( Real ) * 16 );
}
Matrix3D::Matrix3D( Real mat[ 16 ] )
{
memcpy( m, mat, sizeof( Real ) * 16 );
}
Matrix3D::Matrix3D( const Real* mat )
{
memcpy( m, mat, sizeof( Real ) * 16 );
}
Matrix3D::Matrix3D( Real m11, Real m12, Real m13, Real m14,
Real m21, Real m22, Real m23, Real m24,
Real m31, Real m32, Real m33, Real m34,
Real m41, Real m42, Real m43, Real m44 )
{
FillMatrix( m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 );
}
//FillMatrix----------------------------------------------------------------
void Matrix3D::FillMatrix( const Real* mat )
{
memcpy( m, mat, sizeof( Real ) * 16 );
}
//FillMatrix----------------------------------------------------------------
void Matrix3D::FillMatrix( Real m11, Real m12, Real m13, Real m14,
Real m21, Real m22, Real m23, Real m24,
Real m31, Real m32, Real m33, Real m34,
Real m41, Real m42, Real m43, Real m44 )
{
m[ 0 ][ 0 ] = m11; m[ 0 ][ 1 ] = m12; m[ 0 ][ 2 ] = m13; m[ 0 ][ 3 ] = m14;
m[ 1 ][ 0 ] = m21; m[ 1 ][ 1 ] = m22; m[ 1 ][ 2 ] = m23; m[ 1 ][ 3 ] = m24;
m[ 2 ][ 0 ] = m31; m[ 2 ][ 1 ] = m32; m[ 2 ][ 2 ] = m33; m[ 2 ][ 4 ] = m34;
m[ 3 ][ 0 ] = m41; m[ 3 ][ 1 ] = m42; m[ 3 ][ 2 ] = m43; m[ 3 ][ 4 ] = m44;
}
//operator[]----------------------------------------------------------------
Real* Matrix3D::operator[]( Int i )
{
assert( i >= 0 && i < 4 );
return (Real*)m[ i ];
}
//GetMatrix-----------------------------------------------------------------
void Matrix3D::GetMatrix( Real mat[ 16 ] ) const
{
memcpy( mat, m, sizeof( Real ) * 16 );
}
//GetMatrix-----------------------------------------------------------------
void Matrix3D::GetMatrix( Real mat[ 4 ][ 4 ] ) const
{
memcpy( mat, m, sizeof( Real ) * 16 );
}
//Identity------------------------------------------------------------------
void Matrix3D::Identity()
{
*this = IDENTITY;
}
//operator= ----------------------------------------------------------------
Matrix3D& Matrix3D::operator=( const Matrix3D& mat )
{
memcpy( m, mat.m, sizeof( Real ) * 16 );
return *this;
}
//operator== ---------------------------------------------------------------
bool Matrix3D::operator==( const Matrix3D& mat ) const
{
for ( Int r = 0; r < 4; r++ )
{
for ( Int c = 0; c < 4; c++ )
{
if ( !Math::RealEqual( m[ r ][ c ], mat.m[ r ][ c ] ) )
return false;
}
}
return true;
}
//operator!= ---------------------------------------------------------------
bool Matrix3D::operator!=( const Matrix3D& mat ) const
{
return !( *this == mat );
}
// MergeMatrix--------------------------------------------------------------
void Matrix3D::MergeMatrix( const Matrix3D& mat, MatrixOrder order )
{
Matrix3D mat1, mat2;
if ( order == MatrixOrderPrepend )
{
mat1 = *this;
mat2 = mat;
}
else
{
mat1 = mat;
mat2 = *this;
}
for ( Int r = 0; r < 4; r++ )
{
for ( Int c = 0; c < 4; c++ )
{
m[ r ][ c ] =
mat1.m[ r ][ 0 ] * mat2.m[ 0 ][ c ] +
mat1.m[ r ][ 1 ] * mat2.m[ 1 ][ c ] +
mat1.m[ r ][ 2 ] * mat2.m[ 2 ][ c ] +
mat1.m[ r ][ 3 ] * mat2.m[ 3 ][ c ];
}
}
}
// MergeMatrix--------------------------------------------------------------
void Matrix3D::MergeMatrix( const Real mat[ 9 ], MatrixOrder order )
{
MergeMatrix( Matrix3D( mat ), order );
}
//RotateX-------------------------------------------------------------------
void Matrix3D::RotateX( Real angle, MatrixOrder order )
{
Real mat[ 4 ][ 4 ];
mat[ 0 ][ 0 ] = 1; mat[ 0 ][ 1 ] = 0; mat[ 0 ][ 2 ] = 0; mat[ 0 ][ 3 ] = 0;
mat[ 1 ][ 0 ] = 0; mat[ 1 ][ 1 ] = Math::Cos( angle ); mat[ 1 ][ 2 ] = -Math::Sin( angle ); mat[ 1 ][ 3 ] = 0;
mat[ 2 ][ 0 ] = 0; mat[ 2 ][ 1 ] = Math::Sin( angle ); mat[ 2 ][ 2 ] = Math::Cos( angle ); mat[ 2 ][ 3 ] = 0;
mat[ 3 ][ 0 ] = 0; mat[ 3 ][ 1 ] = 0; mat[ 3 ][ 2 ] = 0; mat[ 3 ][ 3 ] = 1;
MergeMatrix( &mat[ 0 ][ 0 ], order );
}
//RotateY-------------------------------------------------------------------
void Matrix3D::RotateY( Real angle, MatrixOrder order )
{
Real mat[ 4 ][ 4 ];
mat[ 0 ][ 0 ] = Math::Cos( angle ); mat[ 0 ][ 1 ] = 0; mat[ 0 ][ 2 ] = Math::Sin( angle ); mat[ 0 ][ 3 ] = 0;
mat[ 1 ][ 0 ] = 0; mat[ 1 ][ 1 ] = 1; mat[ 1 ][ 2 ] = 0; mat[ 1 ][ 3 ] = 0;
mat[ 2 ][ 0 ] = -Math::Sin( angle ); mat[ 2 ][ 1 ] = 0; mat[ 2 ][ 2 ] = Math::Cos( angle ); mat[ 2 ][ 3 ] = 0;
mat[ 3 ][ 0 ] = 0; mat[ 3 ][ 1 ] = 0; mat[ 3 ][ 2 ] = 0; mat[ 3 ][ 3 ] = 1;
MergeMatrix( &mat[ 0 ][ 0 ], order );
}
//RotateZ-------------------------------------------------------------------
void Matrix3D::RotateZ( Real angle, MatrixOrder order )
{
Real mat[ 4 ][ 4 ];
mat[ 0 ][ 0 ] = Math::Cos( angle ); mat[ 0 ][ 1 ] = -Math::Sin( angle ); mat[ 0 ][ 2 ] = 0; mat[ 0 ][ 3 ] = 0;
mat[ 1 ][ 0 ] = Math::Sin( angle ); mat[ 1 ][ 1 ] = Math::Cos( angle ); mat[ 1 ][ 2 ] = 0; mat[ 1 ][ 3 ] = 0;
mat[ 2 ][ 0 ] = 0; mat[ 2 ][ 1 ] = 0; mat[ 2 ][ 2 ] = 1; mat[ 2 ][ 3 ] = 0;
mat[ 3 ][ 0 ] = 0; mat[ 3 ][ 1 ] = 0; mat[ 3 ][ 2 ] = 0; mat[ 3 ][ 3 ] = 1;
MergeMatrix( &mat[ 0 ][ 0 ], order );
}
//Scale---------------------------------------------------------------------
void Matrix3D::Scale( Real sx, Real sy, Real sz, MatrixOrder order )
{
Real mat[ 3 ][ 3 ];
mat[ 0 ][ 0 ] = sx; mat[ 0 ][ 1 ] = 0; mat[ 0 ][ 2 ] = 0; mat[ 0 ][ 3 ] = 0;
mat[ 1 ][ 0 ] = 0; mat[ 1 ][ 1 ] = sy; mat[ 1 ][ 2 ] = 0; mat[ 1 ][ 3 ] = 0;
mat[ 2 ][ 0 ] = 0; mat[ 2 ][ 1 ] = 0; mat[ 2 ][ 2 ] = sz; mat[ 2 ][ 3 ] = 0;
mat[ 3 ][ 0 ] = 0; mat[ 3 ][ 1 ] = 0; mat[ 3 ][ 2 ] = 0; mat[ 3 ][ 3 ] = 1;
MergeMatrix( &mat[ 0 ][ 0 ], order );
}
//Translate-----------------------------------------------------------------
void Matrix3D::Translate( Real tx, Real ty, Real tz, MatrixOrder order )
{
Real mat[ 3 ][ 3 ];
mat[ 0 ][ 0 ] = 1; mat[ 0 ][ 1 ] = 0; mat[ 0 ][ 2 ] = 0; mat[ 0 ][ 3 ] = tx;
mat[ 1 ][ 0 ] = 0; mat[ 1 ][ 1 ] = 1; mat[ 1 ][ 2 ] = 0; mat[ 1 ][ 3 ] = ty;
mat[ 2 ][ 0 ] = 0; mat[ 2 ][ 1 ] = 0; mat[ 2 ][ 2 ] = 1; mat[ 2 ][ 3 ] = tz;
mat[ 3 ][ 0 ] = 0; mat[ 3 ][ 1 ] = 0; mat[ 3 ][ 2 ] = 0; mat[ 3 ][ 3 ] = 1;
MergeMatrix( &mat[ 0 ][ 0 ], order );
}
Point3Df Matrix3D::Transform( const Point3Df& pt )
{
Point3Df ret;
ret.x = pt.x * m[ 0 ][ 0 ] + pt.y * m[ 0 ][ 1 ] + m[ 0 ][ 2 ];
ret.x = pt.x * m[ 1 ][ 0 ] + pt.y * m[ 1 ][ 1 ] + m[ 1 ][ 2 ];
return ret;
}
} // namespace PGE
| [
"pharaohgameengine@555db735-7c4c-0410-acd0-0358cc0c1ac3"
]
| [
[
[
1,
226
]
]
]
|
db2f116e6ac82c840d1ba742b6b749a23ebf05bd | 93176e72508a8b04769ee55bece71095d814ec38 | /Utilities/otbliblas/include/liblas/external/property_tree/detail/info_parser_read.hpp | 82aec2670c6fb57527fd48ce605c25f5f3410138 | [
"MIT",
"BSL-1.0"
]
| permissive | inglada/OTB | a0171a19be1428c0f3654c48fe5c35442934cf13 | 8b6d8a7df9d54c2b13189e00ba8fcb070e78e916 | refs/heads/master | 2021-01-19T09:23:47.919676 | 2011-06-29T17:29:21 | 2011-06-29T17:29:21 | 1,982,100 | 4 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 14,934 | hpp | // ----------------------------------------------------------------------------
// Copyright (C) 2002-2006 Marcin Kalicinski
//
// 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)
//
// For more information, see www.boost.org
// ----------------------------------------------------------------------------
#ifndef BOOST_PROPERTY_TREE_DETAIL_INFO_PARSER_READ_HPP_INCLUDED
#define BOOST_PROPERTY_TREE_DETAIL_INFO_PARSER_READ_HPP_INCLUDED
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/detail/info_parser_error.hpp"
#include "boost/property_tree/detail/info_parser_utils.hpp"
#include <iterator>
#include <string>
#include <stack>
#include <fstream>
#include <cctype>
namespace liblas { namespace property_tree { namespace info_parser
{
// Expand known escape sequences
template<class It>
std::basic_string<typename std::iterator_traits<It>::value_type>
expand_escapes(It b, It e)
{
typedef typename std::iterator_traits<It>::value_type Ch;
std::basic_string<Ch> result;
while (b != e)
{
if (*b == Ch('\\'))
{
++b;
if (b == e)
{
BOOST_PROPERTY_TREE_THROW(info_parser_error(
"character expected after backslash", "", 0));
}
else if (*b == Ch('0')) result += Ch('\0');
else if (*b == Ch('a')) result += Ch('\a');
else if (*b == Ch('b')) result += Ch('\b');
else if (*b == Ch('f')) result += Ch('\f');
else if (*b == Ch('n')) result += Ch('\n');
else if (*b == Ch('r')) result += Ch('\r');
else if (*b == Ch('t')) result += Ch('\t');
else if (*b == Ch('v')) result += Ch('\v');
else if (*b == Ch('"')) result += Ch('"');
else if (*b == Ch('\'')) result += Ch('\'');
else if (*b == Ch('\\')) result += Ch('\\');
else
BOOST_PROPERTY_TREE_THROW(info_parser_error(
"unknown escape sequence", "", 0));
}
else
result += *b;
++b;
}
return result;
}
// Advance pointer past whitespace
template<class Ch>
void skip_whitespace(const Ch *&text)
{
using namespace std;
while (isspace(*text))
++text;
}
// Extract word (whitespace delimited) and advance pointer accordingly
template<class Ch>
std::basic_string<Ch> read_word(const Ch *&text)
{
using namespace std;
skip_whitespace(text);
const Ch *start = text;
while (!isspace(*text) && *text != Ch(';') && *text != Ch('\0'))
++text;
return expand_escapes(start, text);
}
// Extract line (eol delimited) and advance pointer accordingly
template<class Ch>
std::basic_string<Ch> read_line(const Ch *&text)
{
using namespace std;
skip_whitespace(text);
const Ch *start = text;
while (*text != Ch('\0') && *text != Ch(';'))
++text;
while (text > start && isspace(*(text - 1)))
--text;
return expand_escapes(start, text);
}
// Extract string (inside ""), and advance pointer accordingly
// Set need_more_lines to true if \ continuator found
template<class Ch>
std::basic_string<Ch> read_string(const Ch *&text, bool *need_more_lines)
{
skip_whitespace(text);
if (*text == Ch('\"'))
{
// Skip "
++text;
// Find end of string, but skip escaped "
bool escaped = false;
const Ch *start = text;
while ((escaped || *text != Ch('\"')) && *text != Ch('\0'))
{
escaped = (!escaped && *text == Ch('\\'));
++text;
}
// If end of string found
if (*text == Ch('\"'))
{
std::basic_string<Ch> result = expand_escapes(start, text++);
skip_whitespace(text);
if (*text == Ch('\\'))
{
if (!need_more_lines)
BOOST_PROPERTY_TREE_THROW(info_parser_error(
"unexpected \\", "", 0));
++text;
skip_whitespace(text);
if (*text == Ch('\0') || *text == Ch(';'))
*need_more_lines = true;
else
BOOST_PROPERTY_TREE_THROW(info_parser_error(
"expected end of line after \\", "", 0));
}
else
if (need_more_lines)
*need_more_lines = false;
return result;
}
else
BOOST_PROPERTY_TREE_THROW(info_parser_error(
"unexpected end of line", "", 0));
}
else
BOOST_PROPERTY_TREE_THROW(info_parser_error("expected \"", "", 0));
}
// Extract key
template<class Ch>
std::basic_string<Ch> read_key(const Ch *&text)
{
skip_whitespace(text);
if (*text == Ch('\"'))
return read_string(text, NULL);
else
return read_word(text);
}
// Extract data
template<class Ch>
std::basic_string<Ch> read_data(const Ch *&text, bool *need_more_lines)
{
skip_whitespace(text);
if (*text == Ch('\"'))
return read_string(text, need_more_lines);
else
{
*need_more_lines = false;
return read_word(text);
}
}
// Build ptree from info stream
template<class Ptree, class Ch>
void read_info_internal(std::basic_istream<Ch> &stream,
Ptree &pt,
const std::string &filename,
int include_depth)
{
typedef std::basic_string<Ch> str_t;
// Possible parser states
enum state_t {
s_key, // Parser expects key
s_data, // Parser expects data
s_data_cont // Parser expects data continuation
};
unsigned long line_no = 0;
state_t state = s_key; // Parser state
Ptree *last = NULL; // Pointer to last created ptree
// Define line here to minimize reallocations
str_t line;
// Initialize ptree stack (used to handle nesting)
std::stack<Ptree *> stack;
stack.push(&pt); // Push root ptree on stack initially
try {
// While there are characters in the stream
while (stream.good()) {
// Read one line from stream
++line_no;
std::getline(stream, line);
if (!stream.good() && !stream.eof())
BOOST_PROPERTY_TREE_THROW(info_parser_error(
"read error", filename, line_no));
const Ch *text = line.c_str();
// If directive found
skip_whitespace(text);
if (*text == Ch('#')) {
// Determine directive type
++text; // skip #
std::basic_string<Ch> directive = read_word(text);
if (directive == convert_chtype<Ch, char>("include")) {
// #include
if (include_depth > 100) {
BOOST_PROPERTY_TREE_THROW(info_parser_error(
"include depth too large, "
"probably recursive include",
filename, line_no));
}
str_t s = read_string(text, NULL);
std::string inc_name =
convert_chtype<char, Ch>(s.c_str());
std::basic_ifstream<Ch> inc_stream(inc_name.c_str());
if (!inc_stream.good())
BOOST_PROPERTY_TREE_THROW(info_parser_error(
"cannot open include file " + inc_name,
filename, line_no));
read_info_internal(inc_stream, *stack.top(),
inc_name, include_depth + 1);
} else { // Unknown directive
BOOST_PROPERTY_TREE_THROW(info_parser_error(
"unknown directive", filename, line_no));
}
// Directive must be followed by end of line
skip_whitespace(text);
if (*text != Ch('\0')) {
BOOST_PROPERTY_TREE_THROW(info_parser_error(
"expected end of line", filename, line_no));
}
// Go to next line
continue;
}
// While there are characters left in line
while (1) {
// Stop parsing on end of line or comment
skip_whitespace(text);
if (*text == Ch('\0') || *text == Ch(';')) {
if (state == s_data) // If there was no data set state to s_key
state = s_key;
break;
}
// Process according to current parser state
switch (state)
{
// Parser expects key
case s_key:
{
if (*text == Ch('{')) // Brace opening found
{
if (!last)
BOOST_PROPERTY_TREE_THROW(info_parser_error("unexpected {", "", 0));
stack.push(last);
last = NULL;
++text;
}
else if (*text == Ch('}')) // Brace closing found
{
if (stack.size() <= 1)
BOOST_PROPERTY_TREE_THROW(info_parser_error("unmatched }", "", 0));
stack.pop();
last = NULL;
++text;
}
else // Key text found
{
std::basic_string<Ch> key = read_key(text);
last = &stack.top()->push_back(
std::make_pair(key, Ptree()))->second;
state = s_data;
}
}; break;
// Parser expects data
case s_data:
{
// Last ptree must be defined because we are going to add data to it
BOOST_ASSERT(last);
if (*text == Ch('{')) // Brace opening found
{
stack.push(last);
last = NULL;
++text;
state = s_key;
}
else if (*text == Ch('}')) // Brace closing found
{
if (stack.size() <= 1)
BOOST_PROPERTY_TREE_THROW(info_parser_error("unmatched }", "", 0));
stack.pop();
last = NULL;
++text;
state = s_key;
}
else // Data text found
{
bool need_more_lines;
std::basic_string<Ch> data = read_data(text, &need_more_lines);
last->data() = data;
state = need_more_lines ? s_data_cont : s_key;
}
}; break;
// Parser expects continuation of data after \ on previous line
case s_data_cont:
{
// Last ptree must be defined because we are going to update its data
BOOST_ASSERT(last);
if (*text == Ch('\"')) // Continuation must start with "
{
bool need_more_lines;
std::basic_string<Ch> data = read_string(text, &need_more_lines);
last->put_value(last->template get_value<std::basic_string<Ch> >() + data);
state = need_more_lines ? s_data_cont : s_key;
}
else
BOOST_PROPERTY_TREE_THROW(info_parser_error("expected \" after \\ in previous line", "", 0));
}; break;
// Should never happen
default:
BOOST_ASSERT(0);
}
}
}
// Check if stack has initial size, otherwise some {'s have not been closed
if (stack.size() != 1)
BOOST_PROPERTY_TREE_THROW(info_parser_error("unmatched {", "", 0));
}
catch (info_parser_error &e)
{
// If line undefined rethrow error with correct filename and line
if (e.line() == 0)
{
BOOST_PROPERTY_TREE_THROW(info_parser_error(e.message(), filename, line_no));
}
else
BOOST_PROPERTY_TREE_THROW(e);
}
}
} } }
#endif
| [
"[email protected]"
]
| [
[
[
1,
380
]
]
]
|
3db8d22a6494f9cbd002e26f14d21889e0e9edbc | 668dc83d4bc041d522e35b0c783c3e073fcc0bd2 | /fbide-wx/Plugins/WebBrowser/webdoc.h | 81c52c962f65d8d474ae3ce38d203114673b6388 | []
| no_license | albeva/fbide-old-svn | 4add934982ce1ce95960c9b3859aeaf22477f10b | bde1e72e7e182fabc89452738f7655e3307296f4 | refs/heads/master | 2021-01-13T10:22:25.921182 | 2009-11-19T16:50:48 | 2009-11-19T16:50:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,110 | h | /*
* This file is part of FBIde project
*
* FBIde 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.
*
* FBIde 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 FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Albert Varaksin <[email protected]>
* Copyright (C) The FBIde development team
*/
#ifndef WEBDOC_H_INCLUDED
#define WEBDOC_H_INCLUDED
#include "sdk/Document.h"
#include "webconnect/webcontrol.h"
using namespace fb;
class WebDoc : public CDocument<wxPanel, DOCUMENT_MANAGED>
{
public :
WebDoc (const wxString & file = _T(""));
wxWebControl * m_browser;
};
#endif
| [
"vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7"
]
| [
[
[
1,
39
]
]
]
|
a5b34687ee3ab4f31f230f3440f9bace7693eb31 | 6d94a4365af81730ef597dfb22e5c35e51400ade | /Code/Libs/Reflection/UnitTests/ReflectionConversion_UnitTest.cpp | d6ff4925665d3760f92c861d0dda5eee31a24fab | []
| no_license | shaun-leach/game-riff | be57a59659d0fcb413dd75f51dae1bda8a9cdc98 | 8f649d06ce763bc828817a417d01f44402c93f7e | refs/heads/master | 2016-09-08T00:30:27.025751 | 2011-07-16T05:31:31 | 2011-07-16T05:31:31 | 32,223,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,033 | cpp | /*
GameRiff - Framework for creating various video game services
Reflection unit tests
Copyright (C) 2011, Shaun Leach.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <gtest/gtest.h>
#include "Pch.h"
//////////////////////////////////////////////////////
//
// Internal constants
//
static const bool s_boolValue = true;
static const int8 s_int8Value = -8;
static const uint8 s_uint8Value = 8;
static const int16 s_int16Value = -1600;
static const uint16 s_uint16Value = 1600;
static const int32 s_int32Value = -320000;
static const uint32 s_uint32Value = 320000;
static const int64 s_int64Value = -640000000LL;
static const uint64 s_uint64Value = 640000000ULL;
static const float32 s_float32Value = 32.32f;
static const float s_angleValue = MathDegreesToRadians(30.0f);
static const float s_percentValue = 0.20f;
//////////////////////////////////////////////////////
//
// Test simple member conversion
//
class SimpleConversionClass : public ReflClass {
public:
REFL_DEFINE_CLASS(SimpleConversionClass);
SimpleConversionClass() :
baseUint32Test(0),
baseFloat32Test(0.0f)
{
InitReflType();
}
static void ConvertMember(
ReflClass * inst,
ReflHash name,
ReflHash oldType,
void * data
) {
SimpleConversionClass * conv = ReflCast<SimpleConversionClass>(inst);
if (conv != NULL) {
if (name == ReflHash(L"baseUint32Test") && oldType == ReflHash(L"float32")) {
float32 * fdata = reinterpret_cast<float32 *>(data);
conv->baseUint32Test = static_cast<uint32>(ceilf(*fdata));
}
}
}
//private:
uint32 baseUint32Test;
float32 baseFloat32Test;
};
REFL_IMPL_CLASS_BEGIN(ReflClass, SimpleConversionClass);
REFL_MEMBER(baseUint32Test);
REFL_ADD_MEMBER_CONVERSION(baseUint32Test, ConvertMember);
REFL_MEMBER(baseFloat32Test);
REFL_IMPL_CLASS_END(SimpleConversionClass);
//====================================================
TEST(ReflectionTest, TestSimpleConversion) {
IStructuredTextStreamPtr testStream = StreamOpenXML(L"testSimpleConversion.xml");
ASSERT_TRUE(testStream != NULL);
ReflClass * inst = ReflLibrary::Deserialize(testStream, MemFlags(MEM_ARENA_DEFAULT, MEM_CAT_TEST));
ASSERT_TRUE(inst != NULL);
SimpleConversionClass * loadTypes = ReflCast<SimpleConversionClass>(inst);
EXPECT_EQ(true, loadTypes != NULL);
EXPECT_EQ(47, loadTypes->baseUint32Test);
EXPECT_EQ(s_float32Value, loadTypes->baseFloat32Test);
delete loadTypes;
loadTypes = NULL;
}
//////////////////////////////////////////////////////
//
// Test simple member conversion with aliasing
//
class SimpleAliasingConversionClass : public ReflClass {
public:
REFL_DEFINE_CLASS(SimpleAliasingConversionClass);
SimpleAliasingConversionClass() :
baseInt32Test(0),
baseFloat32Test(0.0f)
{
InitReflType();
}
static void ConvertMember(
ReflClass * inst,
ReflHash name,
ReflHash oldType,
void * data
) {
SimpleAliasingConversionClass * conv = ReflCast<SimpleAliasingConversionClass>(inst);
if (conv != NULL) {
if (name == ReflHash(L"floatTest") && oldType == ReflHash(L"float32")) {
float32 * fdata = reinterpret_cast<float32 *>(data);
conv->baseInt32Test = static_cast<int32>(ceilf(*fdata));
}
}
}
//private:
uint32 baseInt32Test;
float32 baseFloat32Test;
};
REFL_IMPL_CLASS_BEGIN(ReflClass, SimpleAliasingConversionClass);
REFL_MEMBER(baseInt32Test);
REFL_ADD_MEMBER_ALIAS_W_CONVERSION(baseInt32Test, floatTest, ConvertMember);
REFL_MEMBER(baseFloat32Test);
REFL_IMPL_CLASS_END(SimpleAliasingConversionClass);
//====================================================
TEST(ReflectionTest, TestSimpleConversionWithAliasing) {
IStructuredTextStreamPtr testStream = StreamOpenXML(L"testSimpleConversionWithAliasing.xml");
ASSERT_TRUE(testStream != NULL);
ReflClass * inst = ReflLibrary::Deserialize(testStream, MemFlags(MEM_ARENA_DEFAULT, MEM_CAT_TEST));
ASSERT_TRUE(inst != NULL);
SimpleAliasingConversionClass * loadTypes = ReflCast<SimpleAliasingConversionClass>(inst);
EXPECT_EQ(true, loadTypes != NULL);
EXPECT_EQ(-50, loadTypes->baseInt32Test);
EXPECT_EQ(s_float32Value, loadTypes->baseFloat32Test);
delete loadTypes;
loadTypes = NULL;
}
//////////////////////////////////////////////////////
//
// Test class member conversion
//
class SimpleClassConversionClass : public ReflClass {
public:
REFL_DEFINE_CLASS(SimpleClassConversionClass);
SimpleClassConversionClass() :
baseUint32Test(0),
baseFloat32Test(0.0f)
{
InitReflType();
}
static void ConvertMember(
ReflClass * inst,
ReflHash name,
ReflHash oldType,
void * data
) {
SimpleClassConversionClass * conv = ReflCast<SimpleClassConversionClass>(inst);
if (conv != NULL) {
if (name == ReflHash(L"memberUint32Test") && oldType == ReflHash(L"uint32")) {
uint32 * udata = reinterpret_cast<uint32 *>(data);
conv->baseUint32Test = *udata;
}
}
}
//private:
uint32 baseUint32Test;
float32 baseFloat32Test;
};
REFL_IMPL_CLASS_BEGIN(ReflClass, SimpleClassConversionClass);
REFL_MEMBER(baseUint32Test);
REFL_ADD_MEMBER_ALIAS_W_CONVERSION(baseUint32Test, classMemberTest, ConvertMember);
REFL_MEMBER(baseFloat32Test);
REFL_IMPL_CLASS_END(SimpleClassConversionClass);
//====================================================
TEST(ReflectionTest, TestClassConversion) {
IStructuredTextStreamPtr testStream = StreamOpenXML(L"testClassConversion.xml");
ASSERT_TRUE(testStream != NULL);
ReflClass * inst = ReflLibrary::Deserialize(testStream, MemFlags(MEM_ARENA_DEFAULT, MEM_CAT_TEST));
ASSERT_TRUE(inst != NULL);
SimpleClassConversionClass * loadTypes = ReflCast<SimpleClassConversionClass>(inst);
EXPECT_EQ(true, loadTypes != NULL);
EXPECT_EQ(s_uint32Value, loadTypes->baseUint32Test);
EXPECT_EQ(s_float32Value, loadTypes->baseFloat32Test);
delete loadTypes;
loadTypes = NULL;
}
| [
"[email protected]@91311ff6-4d11-5f1f-8822-9f0e3032c885"
]
| [
[
[
1,
228
]
]
]
|
3cd09ccd5b825f8da86ee92686f3c280fd30797a | d411188fd286604be7670b61a3c4c373345f1013 | /zomgame/ZGame/event.cpp | 8d5a7bbe09dcc7458a81438208054333ab8df596 | []
| no_license | kjchiu/zomgame | 5af3e45caea6128e6ac41a7e3774584e0ca7a10f | 1f62e569da4c01ecab21a709a4a3f335dff18f74 | refs/heads/master | 2021-01-13T13:16:58.843499 | 2008-09-13T05:11:16 | 2008-09-13T05:11:16 | 1,560,000 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 369 | cpp | #include "game.h"
#include "event.h"
int Event::id = 0;
Event::Event(EventType _type) :
eventType(_type) {
tick = 0;
thisID = id++;
}
int Event::getType(){
return eventType;
}
int Event::getTick(){
return tick;
}
void Event::setTick(int nTick){
tick = nTick;
}
void Event::setType(EventType nEventType){
eventType = nEventType;
}
| [
"nicholasbale@9b66597e-bb4a-0410-bce4-15c857dd0990",
"krypes@9b66597e-bb4a-0410-bce4-15c857dd0990"
]
| [
[
[
1,
5
],
[
8,
26
]
],
[
[
6,
7
]
]
]
|
eb90cfb130afe196e558e4a54abc25d59e7bbfa5 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/src/input/ninput_events.cc | 23011d33c9c20ea4b45034ad435c0c964d6b145b | []
| 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 | 7,807 | cc | //------------------------------------------------------------------------------
// ninput_events.cc
// (C) 2002 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "precompiled/pchnnebula.h"
#include "kernel/nenv.h"
#include "input/ninputserver.h"
//------------------------------------------------------------------------------
/**
*/
nInputEvent *nInputServer::NewEvent(void)
{
return n_new(nInputEvent);
}
//------------------------------------------------------------------------------
/**
*/
void nInputServer::ReleaseEvent(nInputEvent *e)
{
if (e->IsLinked())
{
this->UnlinkEvent(e);
}
n_delete(e);
}
//------------------------------------------------------------------------------
/**
*/
void
nInputServer::LinkEvent(nInputEvent *e)
{
n_assert(!e->IsLinked());
this->events.AddTail(e);
}
//------------------------------------------------------------------------------
/**
*/
void
nInputServer::UnlinkEvent(nInputEvent *e)
{
n_assert(e->IsLinked());
e->Remove();
}
//------------------------------------------------------------------------------
/**
*/
void
nInputServer::FlushEvents(void)
{
nInputEvent *e;
while ( 0 != (e = (nInputEvent *) this->events.RemHead())) n_delete(e);
}
//------------------------------------------------------------------------------
/**
Flush events, states and mappings.
*/
void
nInputServer::FlushInput()
{
// flush input events
this->FlushEvents();
// flush mappings
nInputMapping* curMapping;
for (curMapping = (nInputMapping*) this->im_list.GetHead();
curMapping;
curMapping = (nInputMapping*) curMapping->GetSucc())
{
curMapping->Clear();
}
// flush input states
nInputState* curState;
for (curState = (nInputState*) this->is_list.GetHead();
curState;
curState = (nInputState*) curState->GetSucc())
{
curState->Clear();
}
}
//------------------------------------------------------------------------------
/**
*/
nInputEvent*
nInputServer::FirstEvent(void)
{
return (nInputEvent *) this->events.GetHead();
}
//------------------------------------------------------------------------------
/**
*/
nInputEvent*
nInputServer::NextEvent(nInputEvent *e)
{
return (nInputEvent *) e->GetSucc();
}
//------------------------------------------------------------------------------
/**
*/
bool nInputServer::IsIdenticalEvent(nInputEvent *e0, nInputEvent *e1)
{
bool eq = false;
if (e0->GetDeviceId() == e1->GetDeviceId())
{
switch(e0->GetType()) {
case N_INPUT_KEY_DOWN:
case N_INPUT_KEY_UP:
if (((e1->GetType() == N_INPUT_KEY_DOWN) ||
(e1->GetType() == N_INPUT_KEY_UP)) &&
(e0->GetKey() == e1->GetKey()))
{
eq = true;
}
break;
case N_INPUT_KEY_CHAR:
if ((e1->GetType() == N_INPUT_KEY_CHAR) && (e0->GetChar() == e1->GetChar())) {
eq=true;
}
break;
case N_INPUT_BUTTON_DOWN:
case N_INPUT_BUTTON_UP:
if (((e1->GetType() == N_INPUT_BUTTON_DOWN) ||
(e1->GetType() == N_INPUT_BUTTON_UP)) &&
(e0->GetButton() == e1->GetButton()))
{
eq=true;
}
break;
case N_INPUT_AXIS_MOVE:
if ((e1->GetType() == N_INPUT_AXIS_MOVE) &&
(e0->GetAxis() == e1->GetAxis()))
{
eq=true;
}
break;
case N_INPUT_MOUSE_MOVE:
if (e1->GetType() == N_INPUT_MOUSE_MOVE) {
eq=true;
}
break;
default: break;
}
}
return eq;
}
//------------------------------------------------------------------------------
/**
*/
nInputEvent*
nInputServer::FirstIdenticalEvent(nInputEvent *pattern)
{
nInputEvent *e = (nInputEvent *) this->events.GetHead();
nInputEvent *eq = NULL;
if (e) do
{
if (this->IsIdenticalEvent(pattern,e))
{
eq = e;
}
} while ( ( 0 != (e=(nInputEvent *)e->GetSucc()) ) && (!eq));
return eq;
}
//------------------------------------------------------------------------------
/**
*/
nInputEvent*
nInputServer::NextIdenticalEvent(nInputEvent *pattern, nInputEvent *e)
{
nInputEvent *eq = NULL;
while ( ( 0 != (e = (nInputEvent *) e->GetSucc()) ) && (!eq))
{
if (this->IsIdenticalEvent(pattern,e))
{
eq = e;
}
}
return eq;
}
//------------------------------------------------------------------------------
/**
*/
static int getInt(const char *str, const char *attr)
{
char buf[128];
char *kw;
n_strncpy2(buf,str,sizeof(buf));
kw = strtok(buf," =");
if (kw) do {
if (strcmp(kw,attr)==0) {
char *val = strtok(NULL," =");
if (val) return atoi(val);
}
} while ( 0 != (kw = strtok(NULL," =")));
return 0;
}
//------------------------------------------------------------------------------
/**
Maps a string of the form "devN:channel" to an nInputEvent.
The directory structure under /sys/share/input/devs is used to
determine if the device exists and the channel is supported.
If not, the nInputEvent is invalid and the function returns false.
*/
bool
nInputServer::MapStrToEvent(const char *str, nInputEvent *ie)
{
char *dev_str, *chnl_str;
char buf[128];
char fname[128];
nRoot *dev;
bool retval = false;
// separate device and channel strings...
n_strncpy2(buf,str,sizeof(buf));
dev_str = buf;
chnl_str = strchr(buf,':');
if (chnl_str)
{
*chnl_str++ = 0;
}
else
{
n_printf("':' expected in input event '%s'\n",str);
return false;
}
// search for device
sprintf(fname,"/sys/share/input/devs/%s",dev_str);
dev = kernelServer->Lookup(fname);
if (dev)
{
nEnv *channel;
kernelServer->PushCwd(dev);
// search for channel
sprintf(fname,"channels/%s",chnl_str);
channel = (nEnv *) kernelServer->Lookup(fname);
if (channel)
{
const char *attr = channel->GetS();
ie->SetDeviceId(getInt(attr, "devid"));
ie->SetType((nInputType) getInt(attr, "type"));
switch (ie->GetType())
{
case N_INPUT_KEY_DOWN:
case N_INPUT_KEY_UP:
ie->SetKey((nKey) getInt(attr,"key"));
break;
case N_INPUT_AXIS_MOVE:
ie->SetAxis(getInt(attr,"axis"));
break;
case N_INPUT_BUTTON_DOWN:
case N_INPUT_BUTTON_UP:
ie->SetButton(getInt(attr,"btn"));
break;
default: break;
}
retval = true;
}
else
{
// n_printf("Unknown channel '%s' for input device '%s'.\n",chnl_str,dev_str);
}
kernelServer->PopCwd();
}
return retval;
}
//-------------------------------------------------------------------
// EOF
//-------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
284
]
]
]
|
9970cd4cd022db0430ec4fa0d5524c397d397241 | fbff49addb1be35268a4961959acb7639c778aab | /vsxml/getline.cpp | 5610a2a6673c6e115b0ff2e8db6e14fb3be6b579 | []
| no_license | fluffynuts/util-classes | 6eba6e56ac8a0c35c4b4aae64cc7084de014688e | 9236e8fc868ba7566da596df18fde008cbd0aac6 | refs/heads/master | 2020-05-28T04:44:51.923605 | 2010-05-13T07:08:20 | 2010-05-13T07:08:20 | 32,151,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 874 | cpp | #include "getline.h"
#define CHUNKSIZE 32
size_t getline (char **buf, size_t *len, FILE *fp)
{
if (fp == NULL)
return 0;
size_t stAllocated = *len;
size_t ret = 0;
if ((stAllocated < CHUNKSIZE) || (*buf == NULL))
{
stAllocated = CHUNKSIZE;
*buf = (char *)realloc(*buf, stAllocated * sizeof(char));
}
char *ptr = *buf;
*ptr = '\0';
char c;
while (true)
{
c = fgetc(fp);
if ((c == EOF) || (feof(fp)))
break;
*ptr = c;
ret++;
if (*ptr == '\n')
break;
ptr++;
if ((stAllocated - ret) < 2)
{
stAllocated += CHUNKSIZE;
*buf = (char *)realloc(*buf, stAllocated * sizeof(char));
ptr = *buf;
ptr += ret * sizeof(char);
}
}
if (ret)
{ // null-terminate
ptr++;
*ptr = '\0';
}
*len = stAllocated;
return ret;
}
| [
"davydm@a8519c1d-1a83-06df-9d18-dec23f66e3bd"
]
| [
[
[
1,
45
]
]
]
|
2461bb450672ee5d11c1510d792b65b8ded39e79 | b08e948c33317a0a67487e497a9afbaf17b0fc4c | /Display/DisplayComponent.cpp | 05fc709d32ba443bc273dff6dc750c78fe8324f4 | []
| no_license | 15831944/bastionlandscape | e1acc932f6b5a452a3bd94471748b0436a96de5d | c8008384cf4e790400f9979b5818a5a3806bd1af | refs/heads/master | 2023-03-16T03:28:55.813938 | 2010-05-21T15:00:07 | 2010-05-21T15:00:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 919 | cpp | #include "stdafx.h"
#include "../Display/Display.h"
#include "../Display/DisplayComponent.h"
namespace ElixirEngine
{
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
DisplayComponent::DisplayComponent(EntityRef _rEntity)
: Component(_rEntity),
m_pObject(NULL)
{
}
DisplayComponent::~DisplayComponent()
{
}
Key DisplayComponent::GetSignature()
{
static Key uSignature = MakeKey(string("DisplayComponent"));
return uSignature;
}
void DisplayComponent::SetDisplayObject(DisplayObjectPtr _pObject)
{
m_pObject = _pObject;
}
DisplayObjectPtr DisplayComponent::GetDisplayObject()
{
return m_pObject;
}
}
| [
"voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329"
]
| [
[
[
1,
38
]
]
]
|
6a8b7f931805647b794f5cc574886b650e481311 | 5e72c94a4ea92b1037217e31a66e9bfee67f71dd | /older/tptest5/src/TcpWindowSize.h | 935a70c773a53fca81743a3156b610df1dcea45e | []
| no_license | stein1/bbk | 1070d2c145e43af02a6df14b6d06d9e8ed85fc8a | 2380fc7a2f5bcc9cb2b54f61e38411468e1a1aa8 | refs/heads/master | 2021-01-17T23:57:37.689787 | 2011-05-04T14:50:01 | 2011-05-04T14:50:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 121 | h | #ifndef _TCPWINDOWSIZE_H_
#define _TCPWINDOWSIZE_H_
class TcpWindowSize {
public:
char * GetStr();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
9
]
]
]
|
b1c99db607a4a72c35a68f18406153b75702a44b | 5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e | /Include/event/PropertyEvent.cpp | ffc9e0273becb74c73245afbb958d95352903b75 | [
"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 | 1,819 | 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 "./PropertyEvent.h"
namespace ui
{
namespace event
{
PropertyEvent::PropertyEvent(Component *source, int cID, int id)
: Event(source,id),
classID(cID)
{
}
int PropertyEvent::getClassID() const
{
return classID;
}
}
} | [
"bs@bram.(none)"
]
| [
[
[
1,
45
]
]
]
|
25b42816549c2709582535704562f2cef2aa8d62 | 2ca3ad74c1b5416b2748353d23710eed63539bb0 | /Src/Lokapala/Operator/stdafx.cpp | 8b832309786fbbb910acc621f572160022808e61 | []
| no_license | sjp38/lokapala | 5ced19e534bd7067aeace0b38ee80b87dfc7faed | dfa51d28845815cfccd39941c802faaec9233a6e | refs/heads/master | 2021-01-15T16:10:23.884841 | 2009-06-03T14:56:50 | 2009-06-03T14:56:50 | 32,124,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 372 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Operator.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
#include "CBFMediator.h"
/**@brief CBFMediator의 instance 초기값을 null로 잡아준다.
*/
CCBFMediator *CCBFMediator::m_instance = NULL;
| [
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
]
| [
[
[
1,
17
]
]
]
|
a6c8333f2f2e21e4c10c3f38cc6e5dfc770ab063 | 9a5db9951432056bb5cd4cf3c32362a4e17008b7 | /FacesCapture/branches/RefactorToBeEventBased/RemoteImaging/faceRecognitionDLL/Common.h | 55eaad3eb732163cb61fbdd4d324eebf94d7269b | []
| no_license | miaozhendaoren/appcollection | 65b0ede264e74e60b68ca74cf70fb24222543278 | f8b85af93f787fa897af90e8361569a36ff65d35 | refs/heads/master | 2021-05-30T19:27:21.142158 | 2011-06-27T03:49:22 | 2011-06-27T03:49:22 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,292 | h | // Common.h
// Ver 1.0.0.0
//
#pragma once
/******
由于NDEBUG是为程序调试(debug)期间使用的,当调试期完毕,程序出
发行版(release)后,NDEBUG将失去作用。为了能够使assert()函数在发行
版中也可以使用,则定义了下面的条件编译NDEBUG,意思为:
如果已经定义NDEBUG,则定义宏Assert(x):当x为假时,执行throw,
交由系统已定义的方式处理;否则将Assert(x)定义为函数assert(x),该
函数对 参数x进行测试:x为假时,函数终止程序并打印错误信息。
*****/
#ifdef NDEBUG
#define Assert(x) if (!x) throw;
#else //否则用系统定义的函数assert()处理
#include <cassert>
#define Assert(x) assert(x);
#endif //NDEBUG
#include <complex> //模板类complex的标准头文件
#include <valarray> //模板类valarray的标准头文件
using namespace std; //名字空间
const float FLOATERROR = 1.0e-6F;
const double DOUBLEERROR = 1.0e-15;
const long double LONGDOUBLEERROR = 1.0e-30;
const double GoldNo = 0.618033399; //黄金分割常数(1.0-0.381966)
//取x绝对值
template <class T>
long double Abs(const T& x);
//取x符号,+-或0
template <class T>
T Sgn(const T& x);
//比较两float浮点数相等
bool FloatEqual(float lhs, float rhs);
//比较两float浮点数不相等
bool FloatNotEqual(float lhs, float rhs);
//比较两double浮点数相等
bool FloatEqual(double lhs, double rhs);
//比较两double浮点数不相等
bool FloatNotEqual(double lhs, double rhs);
//比较两long double浮点数相等
bool FloatEqual(long double lhs, long double rhs);
//比较两long double浮点数不相等
bool FloatNotEqual(long double lhs, long double rhs);
//求x与y的最小值,返回小者
template <class T>
T Min(const T& x, const T& y);
//求x与y的最大值,返回大者
template <class T>
T Max(const T& x, const T& y);
//打印数组(向量)所有元素值
template <class T>
void ValarrayPrint(const valarray<T>& vOut);
//打印某个指定数组(向量)元素值
template <class T>
void ValarrayPrint(const valarray<T>& vOut, size_t sPosition);
#include "Common.inl" //实现
| [
"shenbinsc@cbf8b9f2-3a65-11de-be05-5f7a86268029"
]
| [
[
[
1,
70
]
]
]
|
af06c55239aa22103a397117b455d95d60f574b3 | 3785a4fa521ee1f941980b9c2d397d9aa3622727 | /GoopTest/Examples/TreeViewExample.cpp | 87c9d34b2dbd55631735009061a5ef559ab94465 | []
| no_license | Synth3tik0/goop-gui-library | 8b6e0d475c27e0213eb8449d8d38ccf18ce88b6e | 3c8f8eda4aa4d575f15ed8af174268e6e28dc6f3 | refs/heads/master | 2021-01-10T15:05:20.157645 | 2011-08-13T14:29:37 | 2011-08-13T14:29:37 | 49,666,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 354 | cpp | #include "examples.h"
using namespace Goop;
void TreeViewExample(TabContainer *tabContainer)
{
g_outputBox->AppendText(TEXT("Created Tree View example tab\n"));
Tab *tab = tabContainer->AddTab(TEXT("Tree View"));
TreeView *treeView = new TreeView(tab);
treeView->SetPosition(Vector2D(10, 10));
treeView->SetSize(Vector2D(200, 200));
} | [
"[email protected]"
]
| [
[
[
1,
13
]
]
]
|
e9e6e27c221d40a499229bb8a29fb26cd9fec70a | 3856c39683bdecc34190b30c6ad7d93f50dce728 | /LastProject/Source/MenuScene.h | 29fcda0a494071a5e1c434741dc2bf16a9dff182 | []
| 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 | 879 | h | #pragma once
#ifndef _MENUSCENE_H_
#define _MENUSCENE_H_
#include "Scene.h"
class MenuGUI;
class OptionScene;
class LoginScene;
class MenuScene : public IScene
{
private:
VOID Initialize();
VOID Release();
public:
MenuScene()
{
this->Initialize();
}
virtual ~MenuScene()
{
this->Release();
}
virtual HRESULT Create( LPDIRECT3DDEVICE9 _pd3dDevice, LPD3DXSPRITE _pSprite, HWND _hWnd );
virtual VOID Update();
virtual VOID Render();
virtual INT GetSceneNext();
virtual INT GetSceneState();
private:
LPDIRECT3DDEVICE9 m_pD3dDevice;
LPD3DXSPRITE m_pSprite;
HWND m_hWnd;
INT m_scnNext;
INT m_scnState;
MenuGUI* m_pMenuGUI;
OptionScene* m_pOptionScene;
LoginScene* m_pLoginScene;
BOOL m_bActOptionScene;
BOOL m_bActLoginScene;
public:
};
#endif | [
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0",
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0"
]
| [
[
[
1,
35
],
[
37,
55
]
],
[
[
36,
36
]
]
]
|
375929dad7a1bd9d4478041888ebfa005edac245 | 1a307d4d512751c548e21acf8924162910be1bb9 | /quadbase/joystick.cpp | 9a2449cb3d3e9b8235d5c9174faff7d4eceeb8a2 | []
| no_license | krchan/uvicquad | 4d2c944b36e7cf2aee446c019d509656785ea455 | 1bdeed79d4f9903a1c5a6b59aa775f0dd1743e76 | refs/heads/master | 2021-01-10T08:34:44.208309 | 2011-02-10T03:20:07 | 2011-02-10T03:20:07 | 51,811,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 83 | cpp | /*
* joystick.cpp
*
* Created on: 2010-01-28
* Author: Owner
*/
| [
"derekja@fd5db217-9b08-7f95-a5b0-360522c52a06"
]
| [
[
[
1,
7
]
]
]
|
dd0b15b7f98a4a791663116b2453ab5a211d31c0 | 91f172c11686beb1081e15af629ddad06122fd6d | /artag/ARtagLocalizer.cpp | 91691cd32038cad85c8ca38e3d20b8f955a782cd | []
| no_license | iamchucky/N900-on-Create | 3ccc313add86ad858c7603447b97f5d5c4e564a8 | 47ddeea50fff4bee33147312b060358b948e13f8 | refs/heads/master | 2021-01-20T02:02:12.661251 | 2011-02-21T08:17:28 | 2011-02-21T08:17:28 | 1,367,773 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,824 | cpp | #include "ARtagLocalizer.h"
#define FUDGE_FACTOR 0.97
using namespace std;
const float THIN_PATTERN_BORDER = 0.125;
const float THICK_PATTERN_BORDER = 0.25;
ARtag * ARtagLocalizer::tags[50];
bool ARtagLocalizer::allStop = false;
ARtagLocalizer::ARtagLocalizer()
{
imgwidth = 640;
imgheight = 480;
init = false;
useBCH = true;
patternCenter_[0] = patternCenter_[1] = 0.0;
patternWidth_ = 80.0;
xoffset = 0;
yoffset = 0;
fudge = 0.97;
for (int n = 0; n < 50; ++n)
{
tags[n] = new ARtag();
}
// InitializeCriticalSection(&tags_mutex);
}
ARtagLocalizer::~ARtagLocalizer()
{
for (int n = 0; n < 50; ++n)
{
delete tags[n];
}
// DeleteCriticalSection (&tags_mutex);
}
int ARtagLocalizer::initARtagPose(int width, int height, float markerWidth, float x_offset, float y_offset, float yaw_offset, float ffactor)
{
// create a tracker that does:
// - 6x6 sized marker images (required for binary markers)
// - samples at a maximum of 6x6
// - works with luminance (gray) images
// - can load a maximum of 0 non-binary pattern
// - can detect a maximum of 8 patterns in one imagege
tracker = new ARToolKitPlus::TrackerSingleMarker(width, height, 8, 6, 6, 6, 0);
imgwidth = width;
imgheight = height;
patternCenter_[0] = patternCenter_[1] = 0.0;
xoffset = x_offset;
yoffset = y_offset;
yawoffset = yaw_offset;
fudge = ffactor;
tracker->setPixelFormat(ARToolKitPlus::PIXEL_FORMAT_LUM);
// load a camera file.
//if(!tracker->init("..\\..\\ARToolKitPlus\\data\\Unibrain_640x480.cal", 1.0f, 1000.0f))
// if(!tracker->init("..\\..\\ARToolKitPlus\\data\\Unibrain_640x4801.cal", 1.0f, 1000.0f))
if(!tracker->init("no_distortion.cal", 1.0f, 1000.0f))
{
printf("ERROR: init() failed\n");
delete tracker;
return -1;
}
patternWidth_ = markerWidth;
// define size of the marker
tracker->setPatternWidth(patternWidth_);
// the marker in the BCH test image has a thin border...
tracker->setBorderWidth(THIN_PATTERN_BORDER);
// set a threshold. alternatively we could also activate automatic thresholding
tracker->setThreshold(150);
// let's use lookup-table undistortion for high-speed
// note: LUT only works with images up to 1024x1024
tracker->setUndistortionMode(ARToolKitPlus::UNDIST_LUT);
// RPP is more robust than ARToolKit's standard pose estimator but uses more CPU resource
// so using standard pose estimator instead
tracker->setPoseEstimator(ARToolKitPlus::POSE_ESTIMATOR_ORIGINAL);
//tracker->setPoseEstimator(ARToolKitPlus::POSE_ESTIMATOR_RPP);
// switch to simple ID based markers
// use the tool in tools/IdPatGen to generate markers
tracker->setMarkerMode(useBCH ? ARToolKitPlus::MARKER_ID_BCH : ARToolKitPlus::MARKER_ID_SIMPLE);
init = true;
return 0;
}
bool ARtagLocalizer::getARtagPose(IplImage* src, IplImage* dst, int camID)
{
if (!init)
{
printf("Did not initalize the ARtagLocalizer!!\n");
return NULL;
}
if (src->width != imgwidth || src->height != imgheight)
{
printf("src->width: %d src->height %d\n", src->width, src->height);
printf("imgwidth: %d imgheight %d\n", imgwidth, imgheight);
printf("Image passed in does not match initialized image size!!\n");
return NULL;
}
if (src->nChannels != 1)
{
printf("Please pass in grayscale image into ARtagLocalizer! \n");
return NULL;
}
int numMarkers = 0;
ARToolKitPlus::ARMarkerInfo* markers = NULL;
if (tracker->arDetectMarker(const_cast<unsigned char*>((unsigned char*)src->imageData), 150, &markers, &numMarkers) < 0)
{
return false;
}
mytag.clear();
float modelViewMatrix_[16];
for(int m = 0; m < numMarkers; ++m) {
if(markers[m].id != -1 && markers[m].cf >= 0.5) {
tracker->calcOpenGLMatrixFromMarker(&markers[m], patternCenter_, patternWidth_, modelViewMatrix_);
float x = modelViewMatrix_[12] / 1000.0;
float y = modelViewMatrix_[13] / 1000.0;
float z = modelViewMatrix_[14] / 1000.0;
float yaw = -atan2(modelViewMatrix_[1], modelViewMatrix_[0]);
if (yaw < 0)
{
yaw += 6.28;
}
if ((x == 0.0 && y == 0.0 && yaw == 0.0) || (x > 10000.0 && y > 10000.0) || (x < -10000.0 && y < -10000.0) || (z <= 0.001))
{
// ARTKPlus bug that occurs sometimes
continue;
}
// printf("Id: %d\t Conf: %.2f\n", markers[m].id, markers[m].cf);
// printf("x: %.2f \t y: %.2f \t z: %.2f \t yaw: %.2f\n", x,y,z,yaw);
// printf("\n");
// char str[30];
// sprintf(str,"%d",markers[m].id);
// cvPutText (dst,str,cvPoint( markers[m].pos[0]+25,markers[m].pos[1]+10),&cvFont(3,3),cvScalar(255,0,0));
// sprintf(str,"(%.2f,%.2f,%.2f)", x*fudge + xoffset, -(y*fudge + yoffset), yaw + yawoffset);
// cvPutText (dst,str,cvPoint( markers[m].pos[0]+25,markers[m].pos[1]+25),&cvFont(1,1),cvScalar(255,0,0));
cv::Mat PoseM(4, 4, CV_32F, modelViewMatrix_);
cv::transpose(PoseM,PoseM);
CvMat pose = PoseM;
// save artag struct for access later
if (markers[m].id >= 0 && markers[m].id < 50 && !allStop)
{
// EnterCriticalSection(&tags_mutex);
// ARtag * ar = tags[markers[m].id];
// ar->setId(markers[m].id);
// ar->setPose(&pose);
// ar->setPoseAge(0);
// ar->setCamId(camID);
// ar->setLocation(markers[m].pos[0], markers[m].pos[1]);
ARtag mt;
mt.setId(markers[m].id);
mt.setPose(&pose);
mt.setPoseAge(0);
mt.setCamId(camID);
mt.setLocation(markers[m].pos[0], markers[m].pos[1]);
// LeaveCriticalSection(&tags_mutex);
mytag.push_back(mt);
}
}
}
return true;
}
ARtag * ARtagLocalizer::getARtag(int index)
{
return &mytag[index];
}
int ARtagLocalizer::getARtagSize()
{
return mytag.size();
}
void ARtagLocalizer::setARtagOffset(float x_offset, float y_offset, float yaw_offset)
{
xoffset = x_offset;
yoffset = y_offset;
yawoffset = yaw_offset;
}
int ARtagLocalizer::cleanupARtagPose(void)
{
delete tracker;
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
206
]
]
]
|
c1dea10a9f0e92fc63b36af9610fb87816f6d930 | 23c0843109bcc469d7eaf369809a35e643491500 | /Window/WindowClass.cpp | 18aea55ce1e3b0055cd1cd07a6ef82ca0c876815 | []
| no_license | takano32/d4r | eb2ab48b324c02634a25fc943e7a805fea8b93a9 | 0629af9d14035b2b768d21982789fc53747a1cdb | refs/heads/master | 2021-01-19T00:46:58.672055 | 2009-01-07T01:28:38 | 2009-01-07T01:28:38 | 102,349 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,691 | cpp | #include "WindowClass.h"
using namespace base;
char* WindowClass::_psClassName = "ClassName";
char* WindowClass::_psWindowName = "WindowName";
WNDPROC WindowClass::_pWndProc = NULL;
WindowClass::WindowClass() {
_hInstance = GetModuleHandle( NULL );
_loopAction = NULL;
//TODO: バグありでは?
SetUserData( (LONG) this );
}
WindowClass::~WindowClass() {
}
HWND WindowClass::GetWindowHandle() {
return _hWnd;
}
LONG WindowClass::GetUserData( HWND hWnd ) {
return ::GetWindowLong(hWnd, GWL_USERDATA);
}
LONG WindowClass::GetUserData() {
return ::GetWindowLong(_hWnd, GWL_USERDATA);
}
BOOL WindowClass::SetUserData( LONG data ) {
if( ::SetWindowLong( _hWnd, GWL_USERDATA, data ) ){
return TRUE;
}else{
return FALSE;
}
}
BOOL WindowClass::SetWindowProcedure( WNDPROC WndProc ) {
_pWndProc = WndProc;
return TRUE;
}
BOOL WindowClass::RegisterClass(){
_wndClass.lpszClassName = _psClassName; // ウインドウクラスネーム(詳細不明)
_wndClass.lpfnWndProc = _pWndProc; // ウインドウプロシージャ名(WndProcにする)
_wndClass.style = NULL;
_wndClass.cbClsExtra = 0; // 未使用。0 にする。
_wndClass.cbWndExtra = 0; // 未使用。0 にする。
_wndClass.lpszMenuName = NULL; // 未使用。NULL でもOK
_wndClass.hbrBackground = (HBRUSH)GetStockObject(LTGRAY_BRUSH); // <-背景色
_wndClass.hInstance = _hInstance; // インスタンスハンドル
_wndClass.hIcon = LoadIcon( 0, IDI_APPLICATION ); // アイコン
_wndClass.hCursor = LoadCursor( 0, IDC_ARROW ); // カーソルタイプ
// ウインドウクラスを登録
return ::RegisterClass( &_wndClass )?TRUE:FALSE;
}
BOOL WindowClass::Create() {
if( !RegisterClass() ){
return FALSE;
};
RECT rect={0, 0, 640, 480};
DWORD style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
AdjustWindowRect( &rect, style, FALSE );
// ウィンドウの作成
_hWnd = CreateWindowEx(
0,
_psClassName, // ウィンドウを作るウインドウクラスの名前を入れる
_psWindowName, // アプリケーションの名前
style,
GetSystemMetrics( SM_CXSCREEN ) / 2 - (rect.right-rect.left)/2,
GetSystemMetrics( SM_CYSCREEN ) / 2 - (rect.bottom-rect.top)/2,
(rect.right-rect.left),
(rect.bottom-rect.top),
NULL, // 親ウインドウ無し
NULL, // クラスネーム指定時、NULL
_hInstance, // ウインドウインスタンスハンドル
NULL // NULLでOK
);
return _hWnd?TRUE:FALSE;
}
BOOL WindowClass::Show() {
//ShowWindow ( _hWnd, nCmdShow ); // ウインドウを表示
ShowWindow ( _hWnd, SW_SHOWDEFAULT ); // ウインドウを表示
return UpdateWindow( _hWnd )?TRUE:FALSE; // ウインドウの更新
}
VALUE WindowClass::CallBackAction() {
if( _loopAction && GetActiveWindow() == _hWnd ) {
return rb_funcall( _loopAction, rb_intern("action"), 0);
}else {
return Qnil;
}
}
VALUE WindowClass::SetLoopAction( VALUE action ) {
return _loopAction = action;
}
BOOL WindowClass::Main() {
// メッセージループ ゲーム終了まで永久ループ
while( TRUE ){
// メッセージの有りの場合
if( PeekMessage( &_msg, 0, 0, 0, PM_REMOVE ) ){
// プログラム終了要求
if( _msg.message == WM_QUIT ) break;
// メッセージの解析
TranslateMessage( &_msg );
DispatchMessage( &_msg );
}
else{
CallBackAction();
}
}
return TRUE;
}
| [
"[email protected]"
]
| [
[
[
1,
125
]
]
]
|
9b480896b00b6a4ee58d212afdde98e389ae2405 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/source/aosl/property.cpp | 980e723051d8c143ecccb0320624c065e91448a5 | []
| no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,270 | cpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
// Begin prologue.
//
#define AOSLCPP_SOURCE
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "aosl/property.hpp"
#include <xsd/cxx/xml/dom/wildcard-source.hxx>
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
#include <xsd/cxx/tree/comparison-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
static
const ::xsd::cxx::tree::comparison_plate< 0, char >
comparison_plate_init;
}
namespace aosl
{
// Property
//
Property::
Property (const NameType& name)
: ::xml_schema::Type (),
property1_ (::xml_schema::Flags (), this),
name_ (name, ::xml_schema::Flags (), this)
{
}
Property::
Property (const Property& x,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xml_schema::Type (x, f, c),
property1_ (x.property1_, f, this),
name_ (x.name_, f, this)
{
}
Property::
Property (const ::xercesc::DOMElement& e,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xml_schema::Type (e, f | ::xml_schema::Flags::base, c),
property1_ (f, this),
name_ (f, this)
{
if ((f & ::xml_schema::Flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, true, true);
this->parse (p, f);
}
}
void Property::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::Flags f)
{
for (; p.more_elements (); p.next_element ())
{
const ::xercesc::DOMElement& i (p.cur_element ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
// property
//
if (n.name () == "property" && n.namespace_ () == "artofsequence.org/aosl/1.0")
{
::std::auto_ptr< Property1Type > r (
Property1Traits::create (i, f, this));
this->property1_.push_back (r);
continue;
}
break;
}
while (p.more_attributes ())
{
const ::xercesc::DOMAttr& i (p.next_attribute ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
if (n.name () == "name" && n.namespace_ ().empty ())
{
::std::auto_ptr< NameType > r (
NameTraits::create (i, f, this));
this->name_.set (r);
continue;
}
}
if (!name_.present ())
{
throw ::xsd::cxx::tree::expected_attribute< char > (
"name",
"");
}
}
Property* Property::
_clone (::xml_schema::Flags f,
::xml_schema::Container* c) const
{
return new class Property (*this, f, c);
}
Property::
~Property ()
{
}
bool
operator== (const Property& x, const Property& y)
{
if (!(x.property1 () == y.property1 ()))
return false;
if (!(x.name () == y.name ()))
return false;
return true;
}
bool
operator!= (const Property& x, const Property& y)
{
return !(x == y);
}
}
#include <ostream>
#include <xsd/cxx/tree/std-ostream-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::std_ostream_plate< 0, char >
std_ostream_plate_init;
}
namespace aosl
{
::std::ostream&
operator<< (::std::ostream& o, const Property& i)
{
for (Property::Property1ConstIterator
b (i.property1 ().begin ()), e (i.property1 ().end ());
b != e; ++b)
{
o << ::std::endl << "property: " << *b;
}
o << ::std::endl << "name: " << i.name ();
return o;
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace aosl
{
}
#include <ostream>
#include <xsd/cxx/tree/error-handler.hxx>
#include <xsd/cxx/xml/dom/serialization-source.hxx>
#include <xsd/cxx/tree/type-serializer-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_serializer_plate< 0, char >
type_serializer_plate_init;
}
namespace aosl
{
void
operator<< (::xercesc::DOMElement& e, const Property& i)
{
e << static_cast< const ::xml_schema::Type& > (i);
// property
//
for (Property::Property1ConstIterator
b (i.property1 ().begin ()), n (i.property1 ().end ());
b != n; ++b)
{
::xercesc::DOMElement& s (
::xsd::cxx::xml::dom::create_element (
"property",
"artofsequence.org/aosl/1.0",
e));
s << *b;
}
// name
//
{
::xercesc::DOMAttr& a (
::xsd::cxx::xml::dom::create_attribute (
"name",
e));
a << i.name ();
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| [
"klaim@localhost"
]
| [
[
[
1,
248
]
]
]
|
eaf0c7ed131f86dcfadaa8ad17f643d1834dc868 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKitTools/DumpRenderTree/win/DumpRenderTreeWin.h | 00d7015a77fa82789badd64a16916baeffc3eed1 | []
| no_license | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,779 | h | /*
* Copyright (C) 2006, 2007 Apple Inc. 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. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DumpRenderTreeWin_h
#define DumpRenderTreeWin_h
struct IWebFrame;
struct IWebScriptWorld;
struct IWebView;
struct FrameLoadDelegate;
struct PolicyDelegate;
typedef const struct __CFString* CFStringRef;
typedef struct HWND__* HWND;
extern IWebFrame* topLoadingFrame;
extern IWebFrame* frame;
extern PolicyDelegate* policyDelegate;
extern HWND webViewWindow;
#include <WebCore/COMPtr.h>
#include <string>
#include <wtf/HashMap.h>
#include <wtf/Vector.h>
std::wstring urlSuitableForTestResult(const std::wstring& url);
std::wstring lastPathComponent(const std::wstring&);
std::string toUTF8(BSTR);
std::string toUTF8(const std::wstring&);
IWebView* createWebViewAndOffscreenWindow(HWND* webViewWindow = 0);
Vector<HWND>& openWindows();
typedef HashMap<HWND, COMPtr<IWebView> > WindowToWebViewMap;
WindowToWebViewMap& windowToWebViewMap();
void setPersistentUserStyleSheetLocation(CFStringRef);
bool setAlwaysAcceptCookies(bool alwaysAcceptCookies);
unsigned worldIDForWorld(IWebScriptWorld*);
extern UINT_PTR waitToDumpWatchdog;
extern COMPtr<FrameLoadDelegate> sharedFrameLoadDelegate;
#endif // DumpRenderTreeWin_h
| [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
e305ff34ef06d1fb77a24b670ee9df39836cd1c7 | fb4cf44e2c146b26ddde6350180cc420611fe17a | /SDK/CyGame.h | 0831b8b5e08f66573eae332212945dff2528df6d | []
| no_license | dharkness/civ4bullai | 93e0685ef53e404ac4ffa5c1aecf4edaf61acd61 | e56c8a4f1172e2d2b15eb87eaa78adb9d357fae6 | refs/heads/master | 2022-09-15T23:31:55.030351 | 2010-11-13T07:23:13 | 2010-11-13T07:23:13 | 267,723,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,473 | h | #pragma once
#ifndef CyGame_h
#define CyGame_h
//
// Python wrapper class for CvGame
// SINGLETON
// updated 6-5
//#include "CvEnums.h"
class CvGame;
class CvGameAI;
class CyCity;
class CvRandom;
class CyDeal;
class CyReplayInfo;
class CyPlot;
class CyGame
{
public:
CyGame();
CyGame(CvGame* pGame); // Call from C++
CyGame(CvGameAI* pGame); // Call from C++;
CvGame* getGame() { return m_pGame; } // Call from C++
bool isNone() { return (m_pGame==NULL); }
void updateScore(bool bForce);
void cycleCities(bool bForward, bool bAdd);
void cycleSelectionGroups(bool bClear, bool bForward, bool bWorkers);
bool cyclePlotUnits(CyPlot* pPlot, bool bForward, bool bAuto, int iCount);
void selectionListMove(CyPlot* pPlot, bool bAlt, bool bShift, bool bCtrl);
void selectionListGameNetMessage(int eMessage, int iData2, int iData3, int iData4, int iFlags, bool bAlt, bool bShift);
void selectedCitiesGameNetMessage(int eMessage, int iData2, int iData3, int iData4, bool bOption, bool bAlt, bool bShift, bool bCtrl);
void cityPushOrder(CyCity* pCity, OrderTypes eOrder, int iData, bool bAlt, bool bShift, bool bCtrl);
int getSymbolID(int iSymbol);
int getProductionPerPopulation(int /*HurryTypes*/ eHurry);
int getAdjustedPopulationPercent(int /*VictoryTypes*/ eVictory);
int getAdjustedLandPercent(int /* VictoryTypes*/ eVictory);
bool isTeamVote(int /*VoteTypes*/ eVote) const;
bool isChooseElection(int /*VoteTypes*/ eVote) const;
bool isTeamVoteEligible(int /*TeamTypes*/ eTeam, int /*VoteSourceTypes*/ eVoteSource) const;
int countPossibleVote(int /*VoteTypes*/ eVote, int /*VoteSourceTypes*/ eVoteSource) const;
int getVoteRequired(int /*VoteTypes*/ eVote, int /*VoteSourceTypes*/ eVoteSource) const;
int getSecretaryGeneral(int /*VoteSourceTypes*/ eVoteSource) const;
bool canHaveSecretaryGeneral(int /*VoteSourceTypes*/ eVoteSource) const;
int getVoteSourceReligion(int /*VoteSourceTypes*/ eVoteSource) const;
void setVoteSourceReligion(int /*VoteSourceTypes*/ eVoteSource, int /*ReligionTypes*/ eReligion, bool bAnnounce);
int countCivPlayersAlive();
int countCivPlayersEverAlive();
int countCivTeamsAlive();
int countCivTeamsEverAlive();
int countHumanPlayersAlive();
int countTotalCivPower();
int countTotalNukeUnits();
int countKnownTechNumTeams(int /*TechTypes*/ eTech);
int getNumFreeBonuses(int /*BuildingTypes*/ eBuilding);
int countReligionLevels(int /*ReligionTypes*/ eReligion);
int calculateReligionPercent(int /* ReligionTypes*/ eReligion);
int countCorporationLevels(int /*CorporationTypes*/ eCorporation);
int goldenAgeLength();
int victoryDelay(int /*VictoryTypes*/ eVictory);
int getImprovementUpgradeTime(int /* ImprovementTypes*/ eImprovement);
bool canTrainNukes();
int /* EraTypes */ getCurrentEra();
int getActiveTeam();
int /* CivilizationTypes */ getActiveCivilizationType();
bool isNetworkMultiPlayer();
bool isGameMultiPlayer();
bool isTeamGame();
bool isModem();
void setModem(bool bModem);
void reviveActivePlayer();
int getNumHumanPlayers();
int getGameTurn();
void setGameTurn(int iNewValue);
int getTurnYear(int iGameTurn);
int getGameTurnYear();
int getElapsedGameTurns();
int getMaxTurns() const;
void setMaxTurns(int iNewValue);
void changeMaxTurns(int iChange);
int getMaxCityElimination() const;
void setMaxCityElimination(int iNewValue);
int getNumAdvancedStartPoints() const;
void setNumAdvancedStartPoints(int iNewValue);
int getStartTurn() const;
int getStartYear() const;
void setStartYear(int iNewValue);
int getEstimateEndTurn() const;
void setEstimateEndTurn(int iNewValue);
int getTurnSlice() const;
int getMinutesPlayed() const;
int getTargetScore() const;
void setTargetScore(int iNewValue);
int getNumGameTurnActive();
int countNumHumanGameTurnActive();
int getNumCities();
int getNumCivCities();
int getTotalPopulation();
int getTradeRoutes() const;
void changeTradeRoutes(int iChange);
int getFreeTradeCount() const;
bool isFreeTrade() const;
void changeFreeTradeCount(int iChange);
int getNoNukesCount() const;
bool isNoNukes() const;
void changeNoNukesCount(int iChange);
int getSecretaryGeneralTimer(int iVoteSource) const;
int getVoteTimer(int iVoteSource) const;
int getNukesExploded() const;
void changeNukesExploded(int iChange);
int getMaxPopulation() const;
int getMaxLand() const;
int getMaxTech() const;
int getMaxWonders() const;
int getInitPopulation() const;
int getInitLand() const;
int getInitTech() const;
int getInitWonders() const;
int getAIAutoPlay() const;
void setAIAutoPlay(int iNewValue);
bool isScoreDirty() const;
void setScoreDirty(bool bNewValue);
bool isCircumnavigated() const;
void makeCircumnavigated();
bool isDiploVote(int /*VoteSourceTypes*/ eVoteSource) const;
void changeDiploVote(int /*VoteSourceTypes*/ eVoteSource, int iChange);
bool isDebugMode() const;
void toggleDebugMode();
int getPitbossTurnTime();
void setPitbossTurnTime(int iHours);
bool isHotSeat();
bool isPbem();
bool isPitboss();
bool isSimultaneousTeamTurns();
bool isFinalInitialized();
int /*PlayerTypes*/ getActivePlayer();
void setActivePlayer(int /*PlayerTypes*/ eNewValue, bool bForceHotSeat);
int getPausePlayer();
bool isPaused();
int /*UnitTypes*/ getBestLandUnit();
int getBestLandUnitCombat();
int /*TeamTypes*/ getWinner();
int /*VictoryTypes*/ getVictory();
void setWinner(int /*TeamTypes*/ eNewWinner, int /*VictoryTypes*/ eNewVictory);
int /*GameStateTypes*/ getGameState();
int /*HandicapTypes*/ getHandicapType();
CalendarTypes getCalendar() const;
int /*EraTypes*/ getStartEra();
int /*GameSpeedTypes*/ getGameSpeedType();
/*PlayerTypes*/ int getRankPlayer(int iRank);
int getPlayerRank(int /*PlayerTypes*/ iIndex);
int getPlayerScore(int /*PlayerTypes*/ iIndex);
int /*TeamTypes*/ getRankTeam(int iRank);
int getTeamRank(int /*TeamTypes*/ iIndex);
int getTeamScore(int /*TeamTypes*/ iIndex);
bool isOption(int /*GameOptionTypes*/ eIndex);
void setOption(int /*GameOptionTypes*/ eIndex, bool bEnabled);
bool isMPOption(int /*MultiplayerOptionTypes*/ eIndex);
bool isForcedControl(int /*ForceControlTypes*/ eIndex);
int getUnitCreatedCount(int /*UnitTypes*/ eIndex);
int getUnitClassCreatedCount(int /*UnitClassTypes*/ eIndex);
bool isUnitClassMaxedOut(int /*UnitClassTypes*/ eIndex, int iExtra);
int getBuildingClassCreatedCount(int /*BuildingClassTypes*/ eIndex);
bool isBuildingClassMaxedOut(int /*BuildingClassTypes*/ eIndex, int iExtra);
int getProjectCreatedCount(int /*ProjectTypes*/ eIndex);
bool isProjectMaxedOut(int /*ProjectTypes*/ eIndex, int iExtra);
int getForceCivicCount(int /*CivicTypes*/ eIndex);
bool isForceCivic(int /*CivicTypes*/ eIndex);
bool isForceCivicOption(int /*CivicOptionTypes*/ eCivicOption);
int getVoteOutcome(int /*VoteTypes*/ eIndex);
int getReligionGameTurnFounded(int /*ReligionTypes*/ eIndex);
bool isReligionFounded(int /*ReligionTypes*/ eIndex);
bool isReligionSlotTaken(int /*ReligionTypes*/ eIndex);
int getCorporationGameTurnFounded(int /*CorporationTypes*/ eIndex);
bool isCorporationFounded(int /*CorporationTypes*/ eIndex);
bool isVotePassed(int /*VoteTypes*/ eIndex) const;
bool isVictoryValid(int /*VictoryTypes*/ eIndex);
bool isSpecialUnitValid(int /*SpecialUnitTypes*/ eSpecialUnitType);
void makeSpecialUnitValid(int /*SpecialUnitTypes*/ eSpecialUnitType);
bool isSpecialBuildingValid(int /*SpecialBuildingTypes*/ eIndex);
void makeSpecialBuildingValid(int /*SpecialBuildingTypes*/ eIndex);
bool isNukesValid();
void makeNukesValid(bool bValid);
bool isInAdvancedStart();
CyCity* getHolyCity(int /*ReligionTypes*/ eIndex);
void setHolyCity(int /*ReligionTypes*/ eIndex, CyCity* pNewValue, bool bAnnounce);
void clearHolyCity(int /*ReligionTypes*/ eIndex);
CyCity* getHeadquarters(int /*CorporationTypes*/ eIndex);
void setHeadquarters(int /*CorporationTypes*/ eIndex, CyCity* pNewValue, bool bAnnounce);
void clearHeadquarters(int /*CorporationTypes*/ eIndex);
int getPlayerVote(int /*PlayerTypes*/ eOwnerIndex, int iVoteId);
std::string getScriptData() const;
void setScriptData(std::string szNewValue);
void setName(TCHAR* szName);
std::wstring getName();
int getIndexAfterLastDeal();
int getNumDeals();
CyDeal* getDeal(int iID);
CyDeal* addDeal();
void deleteDeal(int iID);
CvRandom& getMapRand();
int getMapRandNum(int iNum, TCHAR* pszLog);
CvRandom& getSorenRand();
int getSorenRandNum(int iNum, TCHAR* pszLog);
int calculateSyncChecksum();
int calculateOptionsChecksum();
bool GetWorldBuilderMode() const; // remove once CvApp is exposed
bool isPitbossHost() const; // remove once CvApp is exposed
int getCurrentLanguage() const; // remove once CvApp is exposed
void setCurrentLanguage(int iNewLanguage); // remove once CvApp is exposed
int getReplayMessageTurn(int i) const;
ReplayMessageTypes getReplayMessageType(int i) const;
int getReplayMessagePlotX(int i) const;
int getReplayMessagePlotY(int i) const;
int getReplayMessagePlayer(int i) const;
ColorTypes getReplayMessageColor(int i) const;
std::wstring getReplayMessageText(int i) const;
uint getNumReplayMessages() const;
CyReplayInfo* getReplayInfo() const;
bool hasSkippedSaveChecksum() const;
void saveReplay(int iPlayer);
void addPlayer(int /*PlayerTypes*/ eNewPlayer, int /*LeaderHeadTypes*/ eLeader, int /*CivilizationTypes*/ eCiv);
/********************************************************************************/
/* BETTER_BTS_AI_MOD 8/1/08 jdog5000 */
/* */
/* Debug */
/********************************************************************************/
void changeHumanPlayer( int /*PlayerTypes*/ eNewHuman );
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
int getCultureThreshold(int /*CultureLevelTypes*/ eLevel);
void setPlotExtraYield(int iX, int iY, int /*YieldTypes*/ eYield, int iExtraYield);
void changePlotExtraCost(int iX, int iY, int iExtraCost);
bool isCivEverActive(int /*CivilizationTypes*/ eCivilization);
bool isLeaderEverActive(int /*LeaderHeadTypes*/ eLeader);
bool isUnitEverActive(int /*UnitTypes*/ eUnit);
bool isBuildingEverActive(int /*BuildingTypes*/ eBuilding);
bool isEventActive(int /*EventTriggerTypes*/ eTrigger);
void doControl(int iControl);
// BUG - MapFinder - start
bool canRegenerateMap() const;
bool regenerateMap();
void saveGame(std::string fileName) const;
bool takeJPEGScreenShot(std::string fileName) const;
// BUG - MapFinder - end
// BUG - EXE/DLL Paths - start
std::string getDLLPath() const;
std::string getExePath() const;
// BUG - EXE/DLL Paths - end
// BUFFY - Security Checks - start
#ifdef _BUFFY
int checkCRCs(std::string fileName_, std::string expectedModCRC_, std::string expectedDLLCRC_, std::string expectedShaderCRC_, std::string expectedPythonCRC_, std::string expectedXMLCRC_) const;
int getWarningStatus() const;
#endif
// BUFFY - Security Checks - end
protected:
CvGame* m_pGame;
};
#endif // #ifndef CyGame
| [
"jdog5000@31ee56aa-37e8-4f44-8bdf-1f84a3affbab",
"fim-fuyu@31ee56aa-37e8-4f44-8bdf-1f84a3affbab"
]
| [
[
[
1,
262
],
[
266,
268
],
[
270,
296
],
[
304,
308
]
],
[
[
263,
265
],
[
269,
269
],
[
297,
303
]
]
]
|
bde7325b5a422e7528f1d35b9a8c580ac3965b63 | bd48897ed08ecfea35d8e00312dd4f9d239e95c4 | /contest/solved/NWERC2008/E.cpp | 277a5f354cd4fadc8d65272a5b9f6112981908b0 | []
| 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 | 2,691 | cpp | #include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <queue>
#include <set>
#include <map>
#include <vector>
#define mp make_pair
#define pb push_back
#define sqr(x) ((x)*(x))
using namespace std;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int,int> PII;
typedef long long LL;
template<typename T> int size(const T &a) { return a.size(); }
template<typename T> T abs(const T &a) { return (a<0)?-a:a; }
template<typename T1,typename T2,typename T3> T1 & operator<<(T1 &a, const pair<T2,T3> &b)
{
return a << "<" << b.first << "," << b.second << ">";
}
vector<long long> data;
vector<pair<LL,LL> > mrange;
vector<long long> minval;
long long d;
long long near(long long cur, pair<LL,LL> range)
{
if(cur < range.first - d) return range.first - d;
if(cur > range.second + d) return range.second + d;
return cur;
}
long long getvar(int idx,long long pos)
{
if(idx == 0) return 0;
long long maxx = data[0] + d * idx;
long long minn = data[0] - d * idx;
if(pos > maxx || pos < minn) return -1;
pair<LL,LL> range = mrange[idx-1];
if(pos < range.first - d) return getvar(idx-1, pos + d) + abs(data[idx] - pos);
if(pos > range.second + d) return getvar(idx-1, pos - d) + abs(data[idx] - pos);
return minval[idx-1] + abs(data[idx] - pos);
}
LL bsearch(LL s,LL e,int idx,LL tgt)
{
while(abs(e-s) > 3)
{
LL m = (s+e)/2;
if(getvar(idx,m) == tgt)
s=m;
else
e=m;
}
while(s!=e)
{
LL m;
if(s<e) m= s+1; else m =s-1;
if(getvar(idx,m) != tgt) return s;
s=m;
}
return s;
}
void process(void)
{
int n;
cin >> n >> d;
data.resize(n);
for(int i=0;i<n;i++)
{
cin >> data[i];
}
if(abs(data[n-1] - data[0]) > (n-1)*d)
{
cout << "impossible" << endl;
return;
}
mrange.resize(n);
minval.resize(n);
mrange[0] = mp(data[0],data[0]);
minval[0] = 0;
for(int i=1;i<n-1;i++)
{
long long minpos = near(data[i], mrange[i-1]);
minval[i] = getvar(i, minpos);
mrange[i] = mp(minpos,minpos);
long long tmp = getvar(i,minpos+1);
if(tmp != -1 && tmp == minval[i])
{
long long s = minpos+1, e = data[0] + i * d;
mrange[i] = mp(minpos,bsearch(s,e,i,minval[i]));
continue;
}
tmp = getvar(i, minpos-1);
if(tmp != -1 && tmp == minval[i])
{
long long s = minpos-1, e= data[0] - i*d;
mrange[i] = mp(bsearch(s,e,i,minval[i]),minpos);
continue;
}
}
cout << getvar(n-1,data[n-1]) << endl;
}
int main(void)
{
int N;
scanf("%d",&N);
for(int i=1;i<=N;i++)
{
process();
}
}
| [
"blmarket@dbb752b6-32d3-11de-9d05-31133e6853b1"
]
| [
[
[
1,
131
]
]
]
|
b2a94ddd0b6d1084e7aeae99582a63775f343a82 | 49c5ae2690016fc70ebff79a4087f3836f6ab968 | /src/main.cpp | c52fbde4d55ac56d6646a169c7c953532ea5b6cf | []
| no_license | GunioRobot/hspcmp-proxy | fbba5559b7f3e341c466af79f6280d34bd5e6417 | ee43b2b2cc8f324a8babb46177b8131ab3af6d5f | refs/heads/master | 2016-09-05T23:44:45.953165 | 2011-08-04T11:52:15 | 2011-08-04T11:53:11 | 3,298,179 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,533 | cpp | #include <windows.h>
#include <map>
#include <string>
#include <fstream>
#include <iostream>
#include <boost/regex.hpp>
#ifdef __cplusplus
#define EXPORT extern "C" __declspec (dllexport)
#else
#define EXPORT __declspec (dllexport)
#endif
#define FUNC_LIST(V) \
V(aht_propupdate) \
V(aht_delmod) \
V(aht_findend) \
V(aht_findparts) \
V(aht_findstart) \
V(aht_getexid) \
V(aht_getmodaxis) \
V(aht_getmodcnt) \
V(aht_getopt) \
V(aht_getpage) \
V(aht_getparts) \
V(aht_getprjmax) \
V(aht_getprjsrc) \
V(aht_getprop) \
V(aht_getpropcnt) \
V(aht_getpropid) \
V(aht_getpropmode) \
V(aht_getproptype) \
V(aht_ini) \
V(aht_linkmod) \
V(aht_listparts) \
V(aht_make) \
V(aht_makeend) \
V(aht_makeinit) \
V(aht_makeput) \
V(aht_parts) \
V(aht_prjload2) \
V(aht_prjload) \
V(aht_prjloade) \
V(aht_prjsave) \
V(aht_sendstr) \
V(aht_setmodaxis) \
V(aht_setpage) \
V(aht_setprop) \
V(aht_source) \
V(aht_stdbuf) \
V(aht_stdsize) \
V(aht_unlinkmod) \
V(hsc3_getruntime) \
V(hsc3_getsym) \
V(hsc3_make) \
V(hsc3_messize) \
V(hsc3_run) \
V(hsc_bye) \
V(hsc_clrmes) \
V(hsc_comp) \
V(hsc_compath) \
V(hsc_getmes) \
/* V(hsc_ini) */ \
V(hsc_objname) \
V(hsc_refname) \
V(hsc_ver) \
V(pack_exe) \
V(pack_get) \
V(pack_ini) \
V(pack_make) \
V(pack_opt) \
V(pack_rt) \
V(pack_view)
typedef BOOL (CALLBACK *HSPCMPFUNC)(int,int,int,int);
static HMODULE lib;
static HINSTANCE hInst;
typedef std::map<std::string, HSPCMPFUNC> function_map_t;
static function_map_t functions;
static const char * const default_dllname = "hspcmp-default.dll";
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved) {
if (fdwReason == DLL_PROCESS_ATTACH) {
hInst = hInstance;
}
if (fdwReason == DLL_PROCESS_DETACH) {
FreeLibrary(lib);
lib = NULL;
}
return TRUE;
}
static HSPCMPFUNC get_func_ptr(const char *name) {
function_map_t::iterator it = functions.find(name);
if (it != functions.end()) {
return it->second;
}
std::string modified_name = std::string("_") + name + "@16";
HSPCMPFUNC fn = (HSPCMPFUNC)GetProcAddress(lib, modified_name.c_str());
functions[name] = fn;
return fn;
}
static void load_dll(const char *name) {
char modulename[1024];
GetModuleFileName(hInst, modulename, sizeof modulename);
std::string libname = std::string(modulename) + "\\..\\" + name;
FreeLibrary(lib);
lib = LoadLibrary(libname.c_str());
functions.clear();
if (!lib) {
static int failed_in_loading_default_dll = 0;
if (!strcmp(name, default_dllname)) {
if (failed_in_loading_default_dll) return;
failed_in_loading_default_dll = 1;
}
std::string msg = std::string("can't load `") + name + "'.";
MessageBox(NULL, msg.c_str(), "hspcmp proxy dll", MB_ICONINFORMATION | MB_OK);
}
}
static int call_func(const char *name, int p1, int p2, int p3, int p4) {
if (!lib) {
load_dll(default_dllname);
if (!lib) return 0;
}
HSPCMPFUNC fn = get_func_ptr(name);
return fn(p1, p2, p3, p4);
}
static std::string search_compiler_name(const char *name) {
std::ifstream ifs(name);
std::string line;
boost::regex re("^\\s*#\\s*compiler\\s*\"([^\"]+)\"");
boost::smatch m;
while (ifs && std::getline(ifs, line)) {
if (boost::regex_search(line, m, re)) {
return m.str(1);
}
}
return default_dllname;
}
EXPORT BOOL WINAPI hsc_ini(int p1, int p2, int p3, int p4) {
char *name = (char *)p2;
std::string dllname = search_compiler_name(name);
load_dll(dllname.c_str());
return call_func("hsc_ini", p1, p2, p3, p4);
}
#define DEFINE_FUNC(name) \
EXPORT BOOL WINAPI name(int p1, int p2, int p3, int p4) { \
return call_func(#name, p1, p2, p3, p4); \
}
FUNC_LIST(DEFINE_FUNC)
| [
"[email protected]"
]
| [
[
[
1,
157
]
]
]
|
b657390d3e0c24955259d2d04409838414245ef5 | 0d32d7cd4fb22b60c4173b970bdf2851808c0d71 | /src/hancock/hancock/Action.h | 38a61b8bc4143815b231ad9fef5a8508e3f254a1 | []
| no_license | kanakb/cs130-hancock | a6eaef9a44955846d486ee2330bec61046cb91bd | d1f77798d90c42074c7a26b03eb9d13925c6e9d7 | refs/heads/master | 2021-01-18T13:04:25.582562 | 2009-06-12T03:49:56 | 2009-06-12T03:49:56 | 32,226,524 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,541 | h | /*
* Action.h
*
*
*/
#ifndef ACTION_H
#define ACTION_H
#define MAX_BUF_LEN 1024
//#include "MPane.h" // !!!!TEMPORARY!!!!
#include <iostream> // !!!!TEMPORARY!!!!
#include <vector>
#include <string>
#include "windows.h"
#include "stdio.h"
#include <tchar.h>
//#include <curses.h> // !!!!TEMPORARY!!!!
using namespace std;
/*** Define Status codes here ***/
class Action {
public:
Action();
Action(string path, string name, string cfg); //used for most actions
Action(string path, string name, string cfg, string optionalOutfile); //used for Cluster File and Find Signatures actions
Action(string path, string name, vector<string> ¶ms); //the last parameter is a vector of arguments for the executable.
virtual bool act(); //builds the cmd and runs the action
virtual string getName(); //returns the name of the executable
virtual bool isComplete(); //tells if process is done
virtual int getStatus();
string exePath; //Location of the executable
string exeName; //Some way to refer to executable.
string m_symantecCfg; //Path of the .cfg file used as input for the executable
int status; //status of action
string output;
string m_optionalOutfile; //Specifies the optional output file to save the action out in
protected:
bool executeProcess(string cmd);
char buf[MAX_BUF_LEN]; // i/o buffer
HANDLE stdout_in_child, stdout_from_child;
PROCESS_INFORMATION pi;
vector<string> argv;
};
#endif ACTION_H
| [
"mihae.wilson@1f8f3222-2881-11de-bcab-dfcfbda92187",
"sargis.panosyan@1f8f3222-2881-11de-bcab-dfcfbda92187",
"kanakb@1f8f3222-2881-11de-bcab-dfcfbda92187"
]
| [
[
[
1,
31
],
[
33,
33
],
[
35,
43
],
[
45,
46
],
[
48,
58
]
],
[
[
32,
32
],
[
44,
44
]
],
[
[
34,
34
],
[
47,
47
]
]
]
|
1f741c544e44867dcdb0bc5caccd043cc0c61dd4 | 1775576281b8c24b5ce36b8685bc2c6919b35770 | /tags/release_1.0/map.cpp | e03d13c25627e94f5deb5e570d120f15a23af1b9 | []
| no_license | BackupTheBerlios/gtkslade-svn | 933a1268545eaa62087f387c057548e03497b412 | 03890e3ba1735efbcccaf7ea7609d393670699c1 | refs/heads/master | 2016-09-06T18:35:25.336234 | 2006-01-01T11:05:50 | 2006-01-01T11:05:50 | 40,615,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,288 | cpp | // << ------------------------------------ >>
// << SLADE - SlayeR's LeetAss Doom Editor >>
// << By Simon Judd, 2004 >>
// << ------------------------------------ >>
// << map.cpp - Map stuff >>
// << ------------------------------------ >>
// INCLUDES ------------------------------ >>
#include "main.h"
#include "map.h"
#include "edit.h"
#include "checks.h"
#include "console.h"
#include "console_window.h"
#include "splash.h"
// VARIABLES ----------------------------- >>
Map map;
string map_lumps[12] =
{
"THINGS",
"VERTEXES",
"LINEDEFS",
"SIDEDEFS",
"SECTORS",
"SEGS",
"SSECTORS",
"NODES",
"BLOCKMAP",
"REJECT",
"SCRIPTS",
"BEHAVIOR"
};
// EXTERNAL VARIABLES -------------------- >>
extern GtkWidget *editor_window;
// Map::create: Clears all map data and sets map name
// ----------------------------------------------- >>
void Map::create(string mapname)
{
name = mapname;
lines = (linedef_t **)NULL;
sides = (sidedef_t **)NULL;
verts = (vertex_t **)NULL;
sectors = (sector_t **)NULL;
things = (thing_t **)NULL;
if (scripts)
delete scripts;
if (behavior)
delete behavior;
scripts = new Lump(0, 0, "SCRIPTS");
behavior = new Lump(0, 0, "BEHAVIOR");
n_lines = n_sides = n_verts = n_sectors = n_things = 0;
opened = true;
init_map();
}
// Map::close: Frees all map data
// --------------------------- >>
void Map::close()
{
if (lines)
{
for (DWORD i = 0; i < n_lines; i++)
free(lines[i]);
free(lines);
}
if (sides)
{
for (DWORD i = 0; i < n_sides; i++)
free(sides[i]);
free(sides);
}
if (sectors)
{
for (DWORD i = 0; i < n_sectors; i++)
free(sectors[i]);
free(sectors);
}
if (verts)
{
for (DWORD i = 0; i < n_verts; i++)
free(verts[i]);
free(verts);
}
if (things)
{
for (DWORD i = 0; i < n_things; i++)
free(things[i]);
free(things);
}
lines = (linedef_t **)NULL;
sides = (sidedef_t **)NULL;
verts = (vertex_t **)NULL;
sectors = (sector_t **)NULL;
things = (thing_t **)NULL;
n_lines = n_sides = n_verts = n_sectors = n_things = 0;
opened = false;
}
// Map::open: Opens a map from an open wadfile
// ---------------------------------------- >>
bool Map::open(Wad *wad, string mapname)
{
Lump* lump = NULL;
long offset = wad->get_lump_index(mapname);
FILE* fp = fopen(wad->path.c_str(), "rb");
long unit_size = 0;
//long unit_count = 0;
if (offset == -1)
{
printf("Map %s not found\n", mapname.c_str());
return false;
}
// Check for BEHAVIOR lump
//if (hexen)
{
long index = offset;
bool done = false;
while (!done)
{
index++;
if (index == wad->num_lumps)
done = true;
else if (strncmp(wad->directory[index]->Name().c_str(), "THINGS", 6) == 0 ||
strncmp(wad->directory[index]->Name().c_str(), "LINEDEFS", 8) == 0 ||
strncmp(wad->directory[index]->Name().c_str(), "SIDEDEFS", 8) == 0 ||
strncmp(wad->directory[index]->Name().c_str(), "VERTEXES", 8) == 0 ||
strncmp(wad->directory[index]->Name().c_str(), "SEGS", 4) == 0 ||
strncmp(wad->directory[index]->Name().c_str(), "SSECTORS", 8) == 0 ||
strncmp(wad->directory[index]->Name().c_str(), "NODES", 5) == 0 ||
strncmp(wad->directory[index]->Name().c_str(), "SECTORS", 7) == 0 ||
strncmp(wad->directory[index]->Name().c_str(), "REJECT", 6) == 0 ||
strncmp(wad->directory[index]->Name().c_str(), "SCRIPTS", 7) == 0 ||
strncmp(wad->directory[index]->Name().c_str(), "BLOCKMAP", 8) == 0)
{
done = false;
}
else if (strncmp(wad->directory[index]->Name().c_str(), "BEHAVIOR", 8) == 0)
{
if (hexen)
done = true;
else
{
message_box("This looks like a hexen-format map, please select a different game configuration!", GTK_MESSAGE_INFO);
return false;
}
}
else
done = true;
}
if (strncmp(wad->directory[index]->Name().c_str(), "BEHAVIOR", 8) != 0 && hexen)
{
message_box("Map has no BEHAVIOR lump\n", GTK_MESSAGE_ERROR);
return false;
}
}
if (scripts)
{
delete scripts;
scripts = NULL;
}
if (behavior)
{
delete behavior;
behavior = NULL;
}
name = mapname;
// << ---- Read Vertices ---- >>
splash("Loading Vertices");
lump = wad->get_lump("VERTEXES", offset);
if (!lump)
{
printf("Map has no VERTEXES lump\n");
splash_hide();
return false;
}
// Seek to lump
fseek(fp, lump->Offset(), SEEK_SET);
// Setup vertices array
unit_size = 4;
n_verts = lump->Size() / unit_size;
verts = (vertex_t **)calloc(n_verts, sizeof(vertex_t *));
// Read vertex data
for (DWORD i = 0; i < n_verts; i++)
{
verts[i] = new vertex_t;
fread(&verts[i]->x, 2, 1, fp);
fread(&verts[i]->y, 2, 1, fp);
}
// << ---- Read sides ---- >>
splash("Loading Sides");
lump = wad->get_lump("SIDEDEFS", offset);
if (!lump)
{
printf("Map has no SIDEDEFS lump\n");
splash_hide();
return false;
}
// Seek to lump
fseek(fp, lump->Offset(), SEEK_SET);
// Setup sides array
unit_size = 30;
n_sides = lump->Size() / unit_size;
sides = (sidedef_t **)calloc(n_sides, sizeof(sidedef_t *));
// Read side data
for (DWORD i = 0; i < n_sides; i++)
{
sides[i] = new sidedef_t;
char temp[9] = "";
fread(&sides[i]->x_offset, 2, 1, fp);
fread(&sides[i]->y_offset, 2, 1, fp);
fread(temp, 1, 8, fp);
temp[8] = 0;
sides[i]->tex_upper = g_ascii_strup(temp, -1);
fread(temp, 1, 8, fp);
temp[8] = 0;
sides[i]->tex_lower = g_ascii_strup(temp, -1);
fread(temp, 1, 8, fp);
temp[8] = 0;
sides[i]->tex_middle = g_ascii_strup(temp, -1);
fread(&sides[i]->sector, 2, 1, fp);
}
// << ---- Read Lines ---- >>
splash("Loading Lines");
int max_vert = 0;
lump = wad->get_lump("LINEDEFS", offset);
if (!lump)
{
printf("Map has no LINEDEFS lump\n");
splash_hide();
return false;
}
// Seek to lump
fseek(fp, lump->Offset(), SEEK_SET);
if (hexen)
{
// Setup & read hexen format lines
// Setup lines array
unit_size = 16;
n_lines = lump->Size() / unit_size;
lines = (linedef_t **)calloc(n_lines, sizeof(linedef_t *));
// Read line data
for (DWORD i = 0; i < n_lines; i++)
{
BYTE temp = 0;
lines[i] = new linedef_t;
fread(&lines[i]->vertex1, 2, 1, fp);
fread(&lines[i]->vertex2, 2, 1, fp);
fread(&lines[i]->flags, 2, 1, fp);
fread(&temp, 1, 1, fp);
lines[i]->type = temp;
fread(lines[i]->args, 1, 5, fp);
short s1, s2;
fread(&s1, 2, 1, fp);
fread(&s2, 2, 1, fp);
lines[i]->side1 = (int)s1;
lines[i]->side2 = (int)s2;
if (n_sides > 32767)
{
unsigned short us1 = static_cast<unsigned short>(s1);
unsigned short us2 = static_cast<unsigned short>(s2);
if (s1 != -1)
lines[i]->side1 = us1;
if (s2 != -1)
lines[i]->side2 = us2;
}
if (lines[i]->vertex1 > max_vert)
max_vert = lines[i]->vertex1;
if (lines[i]->vertex2 > max_vert)
max_vert = lines[i]->vertex2;
}
}
else
{
// Setup lines array
unit_size = 14;
n_lines = lump->Size() / unit_size;
lines = (linedef_t **)calloc(n_lines, sizeof(linedef_t *));
// Read line data
for (DWORD i = 0; i < n_lines; i++)
{
lines[i] = new linedef_t;
fread(&lines[i]->vertex1, 2, 1, fp);
fread(&lines[i]->vertex2, 2, 1, fp);
fread(&lines[i]->flags, 2, 1, fp);
fread(&lines[i]->type, 2, 1, fp);
fread(&lines[i]->sector_tag, 2, 1, fp);
short s1, s2;
fread(&s1, 2, 1, fp);
fread(&s2, 2, 1, fp);
lines[i]->side1 = (int)s1;
lines[i]->side2 = (int)s2;
if (n_sides > 32767)
{
unsigned short us1 = static_cast<unsigned short>(s1);
unsigned short us2 = static_cast<unsigned short>(s2);
if (s1 != -1)
lines[i]->side1 = us1;
if (s2 != -1)
lines[i]->side2 = us2;
}
if (lines[i]->vertex1 > max_vert)
max_vert = lines[i]->vertex1;
if (lines[i]->vertex2 > max_vert)
max_vert = lines[i]->vertex2;
}
}
n_verts = max_vert + 1;
// << ---- Read sectors ---- >>
splash("Loading Sectors");
lump = wad->get_lump("SECTORS", offset);
if (!lump)
{
printf("Map has no SECTORS lump\n");
splash_hide();
return false;
}
// Seek to lump
fseek(fp, lump->Offset(), SEEK_SET);
// Setup sides array
unit_size = 26;
n_sectors = lump->Size() / unit_size;
sectors = (sector_t **)calloc(n_sectors, sizeof(sector_t *));
// Read sector data
for (DWORD i = 0; i < n_sectors; i++)
{
sectors[i] = new sector_t;
char temp[9] = "";
fread(§ors[i]->f_height, 2, 1, fp);
fread(§ors[i]->c_height, 2, 1, fp);
fread(temp, 1, 8, fp);
temp[8] = 0;
sectors[i]->f_tex = g_ascii_strup(temp, -1);
fread(temp, 1, 8, fp);
temp[8] = 0;
sectors[i]->c_tex = g_ascii_strup(temp, -1);
fread(§ors[i]->light, 2, 1, fp);
fread(§ors[i]->special, 2, 1, fp);
fread(§ors[i]->tag, 2, 1, fp);
//sectors[i]->hilighted = false;
//sectors[i]->selected = false;
//sectors[i]->moving = false;
}
// << ---- Read Things ---- >>
splash("Loading Things");
lump = wad->get_lump("THINGS", offset);
if (!lump)
{
printf("Map has no THINGS lump\n");
splash_hide();
return false;
}
// Seek to lump
fseek(fp, lump->Offset(), SEEK_SET);
if (hexen)
{
// Setup & read hexen format things
// Setup things array
unit_size = 20;
n_things = lump->Size() / unit_size;
things = (thing_t **)calloc(n_things, sizeof(thing_t *));
// Read thing data
for (DWORD i = 0; i < n_things; i++)
{
things[i] = new thing_t;
fread(&things[i]->tid, 2, 1, fp);
fread(&things[i]->x, 2, 1, fp);
fread(&things[i]->y, 2, 1, fp);
fread(&things[i]->z, 2, 1, fp);
fread(&things[i]->angle, 2, 1, fp);
fread(&things[i]->type, 2, 1, fp);
fread(&things[i]->flags, 2, 1, fp);
fread(&things[i]->special, 1, 1, fp);
fread(things[i]->args, 1, 5, fp);
}
}
else
{
// Setup things array
unit_size = 10;
n_things = lump->Size() / unit_size;
things = (thing_t **)calloc(n_things, sizeof(thing_t *));
// Read thing data
for (DWORD i = 0; i < n_things; i++)
{
things[i] = new thing_t;
fread(&things[i]->x, 2, 1, fp);
fread(&things[i]->y, 2, 1, fp);
fread(&things[i]->angle, 2, 1, fp);
fread(&things[i]->type, 2, 1, fp);
fread(&things[i]->flags, 2, 1, fp);
}
}
// << ---- Read Scripts/Behavior ---- >>
if (hexen)
{
lump = wad->get_lump("SCRIPTS", offset);
if (lump)
{
fseek(fp, lump->Offset(), SEEK_SET);
scripts = new Lump(0, lump->Size(), "SCRIPTS");
fread(scripts->Data(), lump->Size(), 1, fp);
}
else
scripts = new Lump(0, 0, "SCRIPTS");
lump = wad->get_lump("BEHAVIOR", offset);
if (lump)
{
fseek(fp, lump->Offset(), SEEK_SET);
behavior = new Lump(0, lump->Size(), "BEHAVIOR");
fread(behavior->Data(), lump->Size(), 1, fp);
}
else
behavior = new Lump(0, 0, "BEHAVIOR");
}
splash("Removing Unused Vertices");
remove_free_verts();
splash("Checking Lines");
if (check_lines())
popup_console();
splash("Checking Sides");
if (check_sides())
popup_console();
// Set thing colours/radii/angle
splash("Init Thing Data");
for (int a = 0; a < n_things; a++)
things[a]->ttype = get_thing_type(things[a]->type);
init_map();
opened = true;
splash_hide();
return true;
}
short Map::l_getsector1(int l)
{
if (lines[l]->side1 == -1 || n_sectors == 0)
return -1;
else
return sides[lines[l]->side1]->sector;
}
short Map::l_getsector2(int l)
{
if (lines[l]->side2 == -1 || n_sectors == 0)
return -1;
else
return sides[lines[l]->side2]->sector;
}
/*
bool Map::s_ishilighted(int s)
{
if (s < 0)
return false;
else
return sectors[s]->hilighted;
}
bool Map::s_isselected(int s)
{
if (s < 0)
return false;
else
return sectors[s]->selected;
}
bool Map::s_ismoving(int s)
{
if (s < 0 || s > n_sectors)
return false;
else
return sectors[s]->moving;
}
*/
void Map::delete_vertex(int vertex)
{
free(verts[vertex]);
for (DWORD v = vertex; v < n_verts - 1; v++)
verts[v] = verts[v + 1];
n_verts--;
verts = (vertex_t **)realloc(verts, n_verts * sizeof(vertex_t *));
for (DWORD l = 0; l < n_lines; l++)
{
if (lines[l]->vertex1 == vertex || lines[l]->vertex2 == vertex)
{
delete_line(l);
l--;
}
else
{
if (lines[l]->vertex1 > vertex)
lines[l]->vertex1--;
if (lines[l]->vertex2 > vertex)
lines[l]->vertex2--;
}
}
}
void Map::delete_line(int line)
{
free(lines[line]);
for (DWORD l = line; l < n_lines - 1; l++)
lines[l] = lines[l + 1];
n_lines--;
lines = (linedef_t **)realloc(lines, n_lines * sizeof(linedef_t *));
}
void Map::delete_thing(int thing)
{
free(things[thing]);
for (DWORD t = thing; t < n_things - 1; t++)
things[t] = things[t + 1];
n_things--;
things = (thing_t **)realloc(things, n_things * sizeof(thing_t *));
}
void Map::delete_side(int side)
{
free(sides[side]);
for (DWORD s = side; s < n_sides - 1; s++)
sides[s] = sides[s + 1];
n_sides--;
sides = (sidedef_t **)realloc(sides, n_sides * sizeof(sidedef_t *));
for (DWORD l = 0; l < n_lines; l++)
{
if (lines[l]->side1 == side)
{
lines[l]->side1 = -1;
if (lines[l]->side2 != -1 && lines[l]->side2 != side)
{
l_flip(l);
l_flipsides(l);
map.lines[l]->set_flag(LINE_IMPASSIBLE);
map.lines[l]->clear_flag(LINE_TWOSIDED);
}
}
if (lines[l]->side2 == side)
{
lines[l]->side2 = -1;
map.lines[l]->set_flag(LINE_IMPASSIBLE);
map.lines[l]->clear_flag(LINE_TWOSIDED);
}
if (lines[l]->side1 > side)
lines[l]->side1--;
if (lines[l]->side2 > side)
lines[l]->side2--;
}
}
void Map::delete_sector(int sector)
{
free(sectors[sector]);
for (int s = sector; s < n_sectors - 1; s++)
sectors[s] = sectors[s + 1];
n_sectors--;
sectors = (sector_t **)realloc(sectors, n_sectors * sizeof(sector_t *));
for (int s = 0; s < n_sides; s++)
{
if (sides[s]->sector == sector)
sides[s]->sector = -1;
if (sides[s]->sector > sector)
sides[s]->sector--;
}
for (int s = 0; s < n_sides; s++)
{
if (sides[s]->sector == -1)
{
delete_side(s);
s--;
}
}
}
void Map::delete_vertex(vertex_t *vertex)
{
for (int a = 0; a < n_verts; a++)
{
if (verts[a] == vertex)
{
delete_vertex(a);
return;
}
}
}
void Map::delete_line(linedef_t *line)
{
for (int a = 0; a < n_lines; a++)
{
if (lines[a] == line)
{
delete_line(a);
return;
}
}
}
void Map::delete_sector(sector_t *sector)
{
for (int a = 0; a < n_sectors; a++)
{
if (sectors[a] == sector)
{
delete_sector(a);
return;
}
}
}
void Map::delete_side(sidedef_t *side)
{
for (int a = 0; a < n_sides; a++)
{
if (sides[a] == side)
{
delete_side(a);
return;
}
}
}
void Map::delete_thing(thing_t *thing)
{
for (int a = 0; a < n_things; a++)
{
if (things[a] == thing)
{
delete_thing(a);
return;
}
}
}
bool Map::v_isattached(int v)
{
for (DWORD l = 0; l < n_lines; l++)
{
if (lines[l]->vertex1 == v || lines[l]->vertex2 == v)
return true;
}
return false;
}
bool Map::v_isattached_sector(int v)
{
for (DWORD l = 0; l < n_lines; l++)
{
if (lines[l]->vertex1 == v || lines[l]->vertex2 == v)
{
if (map.l_getsector1(l) != -1 || map.l_getsector1(l) != -1)
return true;
}
}
return false;
}
bool Map::l_needsuptex(int l, int side)
{
int sector1 = l_getsector1(l);
int sector2 = l_getsector2(l);
// False if not two-sided
if (sector1 == -1 || sector2 == -1)
return false;
if (side == 1)
{
if (sectors[l_getsector1(l)]->c_height > sectors[l_getsector2(l)]->c_height)
return true;
else
return false;
}
if (side == 2)
{
if (sectors[l_getsector2(l)]->c_height > sectors[l_getsector1(l)]->c_height)
return true;
else
return false;
}
return false;
}
bool Map::l_needsmidtex(int l, int side)
{
if (side == 1)
{
if (lines[l]->side2 == -1)
return true;
else
{
if (sides[lines[l]->side1]->tex_middle == "-")
return false;
else
return true;
}
}
if (side == 2 && lines[l]->side1 != -1)
{
if (sides[lines[l]->side2]->tex_middle == "-")
return false;
else
return true;
}
return false;
}
bool Map::l_needslotex(int l, int side)
{
// False if not two-sided
if (l_getsector1(l) == -1 || l_getsector2(l) == -1)
return false;
if (side == 1)
{
if (sectors[l_getsector2(l)]->f_height > sectors[l_getsector1(l)]->f_height)
return true;
else
return false;
}
if (side == 2)
{
if (sectors[l_getsector1(l)]->f_height > sectors[l_getsector2(l)]->f_height)
return true;
else
return false;
}
return false;
}
short Map::l_getxoff(int l, int side)
{
if (side == 1 && lines[l]->side1 != -1)
return sides[lines[l]->side1]->x_offset;
if (side == 2 && lines[l]->side2 != -1)
return sides[lines[l]->side2]->x_offset;
return 0;
}
short Map::l_getyoff(int l, int side)
{
if (side == 1 && lines[l]->side1 != -1)
return sides[lines[l]->side1]->y_offset;
if (side == 2 && lines[l]->side2 != -1)
return sides[lines[l]->side2]->y_offset;
return 0;
}
void Map::l_setmidtex(int l, int side, string tex)
{
int s;
if (side == 1)
s = lines[l]->side1;
if (side == 2)
s = lines[l]->side2;
if (s != -1)
sides[s]->tex_middle = tex;
}
void Map::l_setuptex(int l, int side, string tex)
{
int s;
if (side == 1)
s = lines[l]->side1;
if (side == 2)
s = lines[l]->side2;
if (s != -1)
sides[s]->tex_upper = tex;
}
void Map::l_setlotex(int l, int side, string tex)
{
int s;
if (side == 1)
s = lines[l]->side1;
if (side == 2)
s = lines[l]->side2;
if (s != -1)
sides[s]->tex_lower = tex;
}
int Map::l_split(int l, int vertex)
{
int vertex2 = lines[l]->vertex2;
int side1 = -1;
int side2 = -1;
int new_line = -1;
// Add new side for side1
if (lines[l]->side1 != -1)
{
side1 = add_side();
memcpy(sides[side1], sides[lines[l]->side1], sizeof(sidedef_t));
}
// Add new side for side2
if (lines[l]->side2 != -1)
{
side2 = add_side();
memcpy(sides[side2], sides[lines[l]->side2], sizeof(sidedef_t));
}
// Create new line
lines[l]->vertex2 = vertex;
new_line = add_line(vertex, vertex2);
// Setup new line
memcpy(lines[new_line], lines[l], sizeof(linedef_t));
lines[new_line]->vertex1 = vertex;
lines[new_line]->vertex2 = vertex2;
lines[new_line]->side1 = side1;
lines[new_line]->side2 = side2;
return new_line;
}
bool Map::v_checkspot(int x, int y)
{
for (DWORD v = 0; v < n_verts; v++)
{
if (verts[v]->x == x && verts[v]->y == y)
return false;
}
return true;
}
void Map::v_merge(int v1, int v2)
{
for (DWORD l = 0; l < n_lines; l++)
{
if (lines[l]->vertex1 == v1)
lines[l]->vertex1 = v2;
else if (lines[l]->vertex2 == v1)
lines[l]->vertex2 = v2;
}
delete_vertex(v1);
}
void Map::v_mergespot(int x, int y)
{
//numlist_t merge;
vector<int> merge;
for (DWORD v = 0; v < n_verts; v++)
{
if (verts[v]->x == x && verts[v]->y == y)
merge.push_back(v);
}
for (DWORD v = 1; v < merge.size(); v++)
v_merge(merge[v], merge[0]);
}
int Map::add_thing(short x, short y, thing_t properties)
{
n_things++;
things = (thing_t **)realloc(things, n_things * sizeof(thing_t *));
things[n_things - 1] = new thing_t();
things[n_things - 1]->x = x;
things[n_things - 1]->y = y;
things[n_things - 1]->angle = properties.angle;
things[n_things - 1]->type = properties.type;
things[n_things - 1]->flags = properties.flags;
//things[n_things - 1]->selected = false;
//things[n_things - 1]->hilighted = false;
//things[n_things - 1]->moving = false;
//update_map_things();
return n_things - 1;
}
int Map::add_vertex(short x, short y)
{
n_verts++;
verts = (vertex_t **)realloc(verts, n_verts * sizeof(vertex_t *));
verts[n_verts - 1] = new vertex_t(x, y);
return n_verts - 1;
}
int Map::add_line(int v1, int v2)
{
n_lines++;
lines = (linedef_t **)realloc(lines, n_lines * sizeof(linedef_t *));
lines[n_lines - 1] = new linedef_t(v1, v2);
lines[n_lines - 1]->set_flag(LINE_IMPASSIBLE);
return n_lines - 1;
}
int Map::add_sector()
{
n_sectors++;
sectors = (sector_t **)realloc(sectors, n_sectors * sizeof(sector_t *));
sectors[n_sectors - 1] = new sector_t();
return n_sectors - 1;
}
int Map::add_side()
{
n_sides++;
sides = (sidedef_t **)realloc(sides, n_sides * sizeof(sidedef_t *));
sides[n_sides - 1] = new sidedef_t();
sides[n_sides - 1]->sector = n_sectors - 1;
return n_sides - 1;
}
void Map::l_setdeftextures(int l)
{
if (l_getsector1(l) != -1)
{
sides[lines[l]->side1]->tex_upper = "-";
sides[lines[l]->side1]->tex_lower = "-";
sides[lines[l]->side1]->tex_middle = "-";
if (l_needsuptex(l, 1))
sides[lines[l]->side1]->def_tex(TEX_UPPER);
if (l_needsmidtex(l, 1))
sides[lines[l]->side1]->def_tex(TEX_MIDDLE);
if (l_needslotex(l, 1))
sides[lines[l]->side1]->def_tex(TEX_LOWER);
}
if (l_getsector2(l) != -1)
{
sides[lines[l]->side2]->tex_upper = "-";
sides[lines[l]->side2]->tex_lower = "-";
sides[lines[l]->side2]->tex_middle = "-";
if (l_needslotex(l, 2))
sides[lines[l]->side2]->def_tex(TEX_LOWER);
if (l_needsuptex(l, 2))
sides[lines[l]->side2]->def_tex(TEX_UPPER);
if (l_needsmidtex(l, 2))
sides[lines[l]->side2]->def_tex(TEX_MIDDLE);
}
}
// Map::add_to_wad: Adds raw map data to a wad file
// --------------------------------------------- >>
void Map::add_to_wad(Wad *wadfile)
{
if (wadfile->locked)
return;
print(true, "Saving %s to %s..,\n", name.c_str(), wadfile->path.c_str());
BYTE* things_data = NULL;
BYTE* lines_data = NULL;
BYTE* sides_data = NULL;
BYTE* verts_data = NULL;
BYTE* sectors_data = NULL;
int thing_size = 10;
int line_size = 14;
if (hexen)
{
thing_size = 20;
line_size = 16;
}
// *** SETUP DATA ***
// Setup things data
things_data = (BYTE *)malloc(n_things * thing_size);
for (DWORD t = 0; t < n_things; t++)
{
BYTE* p = things_data;
p += (t * thing_size);
if (hexen)
{
memcpy(p, &things[t]->tid, 2); p += 2;
memcpy(p, &things[t]->x, 2); p += 2;
memcpy(p, &things[t]->y, 2); p += 2;
memcpy(p, &things[t]->z, 2); p += 2;
memcpy(p, &things[t]->angle, 2); p += 2;
memcpy(p, &things[t]->type, 2); p += 2;
memcpy(p, &things[t]->flags, 2); p += 2;
memcpy(p, &things[t]->special, 1); p += 1;
memcpy(p, things[t]->args, 5); p += 5;
}
else
{
memcpy(p, &things[t]->x, 2); p += 2;
memcpy(p, &things[t]->y, 2); p += 2;
memcpy(p, &things[t]->angle, 2); p += 2;
memcpy(p, &things[t]->type, 2); p += 2;
memcpy(p, &things[t]->flags, 2); p += 2;
}
}
// Setup lines data
lines_data = (BYTE *)malloc(n_lines * line_size);
for (DWORD l = 0; l < n_lines; l++)
{
BYTE* p = lines_data;
p += (l * line_size);
if (hexen)
{
BYTE temp = lines[l]->type;
memcpy(p, &lines[l]->vertex1, 2); p += 2;
memcpy(p, &lines[l]->vertex2, 2); p += 2;
memcpy(p, &lines[l]->flags, 2); p += 2;
memcpy(p, &temp, 2); p += 1;
memcpy(p, lines[l]->args, 5); p += 5;
memcpy(p, &lines[l]->side1, 2); p += 2;
memcpy(p, &lines[l]->side2, 2); p += 2;
}
else
{
memcpy(p, &lines[l]->vertex1, 2); p += 2;
memcpy(p, &lines[l]->vertex2, 2); p += 2;
memcpy(p, &lines[l]->flags, 2); p += 2;
memcpy(p, &lines[l]->type, 2); p += 2;
memcpy(p, &lines[l]->sector_tag, 2); p += 2;
memcpy(p, &lines[l]->side1, 2); p += 2;
memcpy(p, &lines[l]->side2, 2); p += 2;
}
}
// Setup sides data
sides_data = (BYTE *)malloc(n_sides * 30);
for (DWORD s = 0; s < n_sides; s++)
{
// Pad texture names with 0's
char up[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
char lo[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
char mid[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
// Read texture names into temp char arrays
for (int c = 0; c < sides[s]->tex_upper.length(); c++)
up[c] = sides[s]->tex_upper[c];
for (int c = 0; c < sides[s]->tex_lower.length(); c++)
lo[c] = sides[s]->tex_lower[c];
for (int c = 0; c < sides[s]->tex_middle.length(); c++)
mid[c] = sides[s]->tex_middle[c];
BYTE* p = sides_data + (s * 30);
memcpy(p, &sides[s]->x_offset, 2); p += 2;
memcpy(p, &sides[s]->y_offset, 2); p += 2;
memcpy(p, up, 8); p += 8;
memcpy(p, lo, 8); p += 8;
memcpy(p, mid, 8); p += 8;
memcpy(p, &sides[s]->sector, 2); p += 2;
}
// Setup vertices data
verts_data = (BYTE *)malloc(n_verts * 4);
for (DWORD v = 0; v < n_verts; v++)
{
BYTE* p = verts_data + (v * 4);
memcpy(p, &verts[v]->x, 2); p += 2;
memcpy(p, &verts[v]->y, 2); p += 2;
}
// Setup sectors data
sectors_data = (BYTE *)malloc(n_sectors * 26);
for (DWORD s = 0; s < n_sectors; s++)
{
// Pad texture names with 0's
char floor[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
char ceil[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
// Read texture names into temp char arrays
for (int c = 0; c < sectors[s]->f_tex.length(); c++)
floor[c] = sectors[s]->f_tex[c];
for (int c = 0; c < sectors[s]->c_tex.length(); c++)
ceil[c] = sectors[s]->c_tex[c];
BYTE* p = sectors_data + (s * 26);
memcpy(p, §ors[s]->f_height, 2); p += 2;
memcpy(p, §ors[s]->c_height, 2); p += 2;
memcpy(p, floor, 8); p += 8;
memcpy(p, ceil, 8); p += 8;
memcpy(p, §ors[s]->light, 2); p += 2;
memcpy(p, §ors[s]->special, 2); p += 2;
memcpy(p, §ors[s]->tag, 2); p += 2;
}
// *** WRITE DATA TO WADFILE ***
bool scripts = false;
bool behavior = false;
// If map already exists in wad, delete it
long mapindex = wadfile->get_lump_index(this->name, 0);
if (mapindex != -1)
{
long index = mapindex + 1;
bool done = false;
while (!done)
{
if (index == wadfile->num_lumps)
done = true;
else if (strncmp(wadfile->directory[index]->Name().c_str(), "THINGS", 6) == 0 ||
strncmp(wadfile->directory[index]->Name().c_str(), "LINEDEFS", 8) == 0 ||
strncmp(wadfile->directory[index]->Name().c_str(), "SIDEDEFS", 8) == 0 ||
strncmp(wadfile->directory[index]->Name().c_str(), "VERTEXES", 8) == 0 ||
strncmp(wadfile->directory[index]->Name().c_str(), "SEGS", 4) == 0 ||
strncmp(wadfile->directory[index]->Name().c_str(), "SSECTORS", 8) == 0 ||
strncmp(wadfile->directory[index]->Name().c_str(), "NODES", 5) == 0 ||
strncmp(wadfile->directory[index]->Name().c_str(), "SECTORS", 7) == 0 ||
strncmp(wadfile->directory[index]->Name().c_str(), "REJECT", 6) == 0 ||
strncmp(wadfile->directory[index]->Name().c_str(), "BLOCKMAP", 8) == 0)
{
print(true, "Deleting map entry %s\n", wadfile->directory[index]->Name().c_str());
wadfile->delete_lump(wadfile->directory[index]->Name(), mapindex);
done = false;
}
else if (strncmp(wadfile->directory[index]->Name().c_str(), "BEHAVIOR", 8) == 0)
{
done = false;
index++;
behavior = true;
}
else if (strncmp(wadfile->directory[index]->Name().c_str(), "SCRIPTS", 7) == 0)
{
done = false;
index++;
scripts = true;
}
else
{
print(true, "Found next non-map entry %s\n", wadfile->directory[index]->Name().c_str());
done = true;
}
}
}
else
{
mapindex = 0;
wadfile->add_lump(name, mapindex);
}
// Add map lumps
if (hexen)
{
if (!scripts)
wadfile->add_lump("SCRIPTS", mapindex + 1);
if (!behavior)
wadfile->add_lump("BEHAVIOR", mapindex + 1);
}
wadfile->add_lump("SECTORS", mapindex + 1);
wadfile->add_lump("VERTEXES", mapindex + 1);
wadfile->add_lump("SIDEDEFS", mapindex + 1);
wadfile->add_lump("LINEDEFS", mapindex + 1);
wadfile->add_lump("THINGS", mapindex + 1);
// Write map data
wadfile->replace_lump("THINGS", thing_size * n_things, things_data, mapindex);
wadfile->replace_lump("LINEDEFS", line_size * n_lines, lines_data, mapindex);
wadfile->replace_lump("SIDEDEFS", 30 * n_sides, sides_data, mapindex);
wadfile->replace_lump("VERTEXES", 4 * n_verts, verts_data, mapindex);
wadfile->replace_lump("SECTORS", 26 * n_sectors, sectors_data, mapindex);
if (hexen)
{
wadfile->replace_lump("SCRIPTS", this->scripts->Size(), this->scripts->Data(), mapindex);
wadfile->replace_lump("BEHAVIOR", this->behavior->Size(), this->behavior->Data(), mapindex);
}
}
void Map::l_flip(int l)
{
WORD temp = lines[l]->vertex1;
lines[l]->vertex1 = lines[l]->vertex2;
lines[l]->vertex2 = temp;
}
void Map::l_flipsides(int l)
{
short temp = lines[l]->side1;
lines[l]->side1 = lines[l]->side2;
lines[l]->side2 = temp;
}
void Map::s_changeheight(int s, bool floor, int amount)
{
if (floor)
sectors[s]->f_height += amount;
else
sectors[s]->c_height += amount;
}
int Map::v_getvertatpoint(point2_t point)
{
if (n_verts == 0)
return -1;
for (int v = n_verts - 1; v >= 0; v--)
{
if (verts[v]->x == point.x && verts[v]->y == point.y)
return v;
}
return -1;
}
vector<int> Map::v_getattachedlines(int v)
{
vector<int> ret;
for (DWORD l = 0; l < n_lines; l++)
{
if (lines[l]->vertex1 == v || lines[l]->vertex2 == v)
{
if (vector_exists(ret, l))
ret.push_back(l);
}
}
return ret;
}
void Map::l_setsector(int l, int side, int sector)
{
if (side == 1)
{
if (sector == -1)
{
lines[l]->side1 = -1;
return;
}
if (lines[l]->side1 == -1)
lines[l]->side1 = add_side();
sides[lines[l]->side1]->sector = sector;
}
else
{
if (sector == -1)
{
lines[l]->side2 = -1;
lines[l]->clear_flag(LINE_TWOSIDED);
lines[l]->set_flag(LINE_IMPASSIBLE);
return;
}
if (lines[l]->side2 == -1)
{
lines[l]->side2 = add_side();
lines[l]->set_flag(LINE_TWOSIDED);
lines[l]->clear_flag(LINE_IMPASSIBLE);
l_setmidtex(l, 1, "-");
}
sides[lines[l]->side2]->sector = sector;
}
}
int Map::l_getindex(linedef_t* line)
{
for (DWORD l = 0; l < n_lines; l++)
{
if (lines[l] == line)
return l;
}
return -1;
}
sidedef_t* Map::l_getside(int l, int side)
{
if (side == 1)
{
if (map.lines[l]->side1 == -1)
return NULL;
else
return map.sides[map.lines[l]->side1];
}
else
{
if (map.lines[l]->side2 == -1)
return NULL;
else
return map.sides[map.lines[l]->side2];
}
}
point2_t Map::l_getmidpoint(int l)
{
point2_t tl(map.verts[map.lines[l]->vertex1]->x,
map.verts[map.lines[l]->vertex1]->y);
point2_t br(map.verts[map.lines[l]->vertex2]->x,
map.verts[map.lines[l]->vertex2]->y);
return midpoint(tl, br);
}
void Map::l_getfromid(int line_id, vector<int> *vec)
{
for (int l = 0; l < n_lines; l++)
{
if (lines[l]->type == 121)
{
if (line_id == lines[l]->args[0])
{
if (find(vec->begin(), vec->end(), l) == vec->end())
vec->push_back(l);
}
}
}
}
void Map::v_getattachedlines(int v, numlist_t* list)
{
for (DWORD l = 0; l < n_lines; l++)
{
if (lines[l]->vertex1 == v || lines[l]->vertex2 == v)
list->add(l, false);
}
}
void Map::change_level(BYTE flags)
{
if (!(changed & MC_SAVE_NEEDED))
{
string title = gtk_window_get_title(GTK_WINDOW(editor_window));
title += "*";
gtk_window_set_title(GTK_WINDOW(editor_window), title.c_str());
}
if (flags & MC_NODE_REBUILD)
flags |= MC_SSECTS|MC_LINES;
changed |= MC_SAVE_NEEDED; // If anything changes a save is needed
changed |= flags;
}
| [
"veilofsorrow@0f6d0948-3201-0410-bbe6-95a89488c5be"
]
| [
[
[
1,
1485
]
]
]
|
1312cd8028551de4d509d8bde619498e72079cce | de0881d85df3a3a01924510134feba2fbff5b7c3 | /apps/workshop/fingerTrackingExample/src_other/hands/lineFitter/cvLineFitter.h | 55a0fa653c3dd995ffe3569f15e407a753f74ecc | []
| no_license | peterkrenn/ofx-dev | 6091def69a1148c05354e55636887d11e29d6073 | e08e08a06be6ea080ecd252bc89c1662cf3e37f0 | refs/heads/master | 2021-01-21T00:32:49.065810 | 2009-06-26T19:13:29 | 2009-06-26T19:13:29 | 146,543 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 396 | h | #ifndef _CV_LINE_FITTER
#define _CV_LINE_FITTER
#include "ofxOpenCV.h"
#include "Matrix.h"
//=================================================================================
class cvLineFitter {
public:
void fitLine(ofPoint * pts, int nPts, float &slope, float &intercept, float &chiSqr);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
49
]
]
]
|
36ee7c13a7a209516bc510a39a17efac3f12e5aa | ea613c6a4d531be9b5d41ced98df1a91320c59cc | /7-Zip/CPP/7zip/UI/FileManager/PanelSort.cpp | 82dd269ae6c85efd83d58a55aa7277173ce213a9 | []
| no_license | f059074251/interested | 939f938109853da83741ee03aca161bfa9ce0976 | b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2 | refs/heads/master | 2021-01-15T14:49:45.217066 | 2010-09-16T10:42:30 | 2010-09-16T10:42:30 | 34,316,088 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,993 | cpp | // PanelSort.cpp
#include "StdAfx.h"
#include "Windows/PropVariant.h"
#include "../../PropID.h"
#include "Panel.h"
using namespace NWindows;
static UString GetExtension(const UString &name)
{
int dotPos = name.ReverseFind(L'.');
if (dotPos < 0)
return UString();
return name.Mid(dotPos);
}
int CALLBACK CompareItems2(LPARAM lParam1, LPARAM lParam2, LPARAM lpData)
{
if (lpData == NULL)
return 0;
CPanel *panel = (CPanel*)lpData;
switch(panel->_sortID)
{
// if (panel->_sortIndex == 0)
case kpidName:
{
const UString name1 = panel->GetItemName((int)lParam1);
const UString name2 = panel->GetItemName((int)lParam2);
int res = name1.CompareNoCase(name2);
/*
if (res != 0 || !panel->_flatMode)
return res;
const UString prefix1 = panel->GetItemPrefix(lParam1);
const UString prefix2 = panel->GetItemPrefix(lParam2);
return res = prefix1.CompareNoCase(prefix2);
*/
return res;
}
case kpidNoProperty:
{
return MyCompare(lParam1, lParam2);
}
case kpidExtension:
{
const UString ext1 = GetExtension(panel->GetItemName((int)lParam1));
const UString ext2 = GetExtension(panel->GetItemName((int)lParam2));
return ext1.CompareNoCase(ext2);
}
}
/*
if (panel->_sortIndex == 1)
return MyCompare(file1.Size, file2.Size);
return ::CompareFileTime(&file1.MTime, &file2.MTime);
*/
// PROPID propID = panel->_properties[panel->_sortIndex].ID;
PROPID propID = panel->_sortID;
NCOM::CPropVariant propVariant1, propVariant2;
// Name must be first property
panel->_folder->GetProperty((UINT32)lParam1, propID, &propVariant1);
panel->_folder->GetProperty((UINT32)lParam2, propID, &propVariant2);
if (propVariant1.vt != propVariant2.vt)
return 0; // It means some BUG
if (propVariant1.vt == VT_BSTR)
{
return _wcsicmp(propVariant1.bstrVal, propVariant2.bstrVal);
}
return propVariant1.Compare(propVariant2);
// return 0;
}
int CALLBACK CompareItems(LPARAM lParam1, LPARAM lParam2, LPARAM lpData)
{
if (lpData == NULL) return 0;
if (lParam1 == kParentIndex) return -1;
if (lParam2 == kParentIndex) return 1;
CPanel *panel = (CPanel*)lpData;
bool isDir1 = panel->IsItemFolder((int)lParam1);
bool isDir2 = panel->IsItemFolder((int)lParam2);
if (isDir1 && !isDir2) return -1;
if (isDir2 && !isDir1) return 1;
int result = CompareItems2(lParam1, lParam2, lpData);
return panel->_ascending ? result: (-result);
}
/*
void CPanel::SortItems(int index)
{
if (index == _sortIndex)
_ascending = !_ascending;
else
{
_sortIndex = index;
_ascending = true;
switch (_properties[_sortIndex].ID)
{
case kpidSize:
case kpidPackedSize:
case kpidCTime:
case kpidATime:
case kpidMTime:
_ascending = false;
break;
}
}
_listView.SortItems(CompareItems, (LPARAM)this);
_listView.EnsureVisible(_listView.GetFocusedItem(), false);
}
void CPanel::SortItemsWithPropID(PROPID propID)
{
int index = _properties.FindItemWithID(propID);
if (index >= 0)
SortItems(index);
}
*/
void CPanel::SortItemsWithPropID(PROPID propID)
{
if (propID == _sortID)
_ascending = !_ascending;
else
{
_sortID = propID;
_ascending = true;
switch (propID)
{
case kpidSize:
case kpidPackSize:
case kpidCTime:
case kpidATime:
case kpidMTime:
_ascending = false;
break;
}
}
_listView.SortItems(CompareItems, (LPARAM)this);
_listView.EnsureVisible(_listView.GetFocusedItem(), false);
}
void CPanel::OnColumnClick(LPNMLISTVIEW info)
{
/*
int index = _properties.FindItemWithID(_visibleProperties[info->iSubItem].ID);
SortItems(index);
*/
SortItemsWithPropID(_visibleProperties[info->iSubItem].ID);
}
| [
"[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d"
]
| [
[
[
1,
158
]
]
]
|
c7303aa2498eaaae2c04c566bdb0f505eeca2e99 | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src/FileNotification.h | e02a9e8a5da4436b576a972396d46a398bfb99bb | []
| no_license | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,194 | h | /**
* @file FileNotification.h
* @brief ファイルの更新の監視. (リンクバー専用?)
*/
#pragma once
class CFileNotification {
public:
// Declarations
DECLARE_REGISTERED_MESSAGE( Mtl_FileNotification )
private:
struct _ThreadParam {
HWND _hWnd;
HANDLE _hExitEvent;
HANDLE _hNotification;
_ThreadParam() : _hWnd(0), _hExitEvent(0), _hNotification(0) {} //+++
};
public:
// Ctor/Dtor
CFileNotification()
: m_hNotificationThread( NULL )
, m_dwNotificationThreadID( 0 )
, m_ThreadParams() //+++ 抜けチェック対策.
{
}
~CFileNotification()
{
if (m_hNotificationThread != NULL)
_CleanUpNotification();
}
private:
// Data members
HANDLE m_hNotificationThread;
DWORD m_dwNotificationThreadID;
_ThreadParam m_ThreadParams;
public:
bool SetUpFileNotificationThread(HWND hWnd, const CString &strDirPath, bool bWatchSubTree = false)
{
m_ThreadParams._hExitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
ATLASSERT(m_ThreadParams._hExitEvent != INVALID_HANDLE_VALUE);
ATLASSERT( ::IsWindow(hWnd) );
m_ThreadParams._hWnd = hWnd;
CString strPath(strDirPath);
MtlRemoveTrailingBackSlash(strPath);
HANDLE hWait = ::FindFirstChangeNotification( strPath,
bWatchSubTree, // flag for monitoring
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME); // fixed by INUYA, thank you.
// お気に入りのリンクフォルダが見つからなかったらfalseを返す
if (hWait == INVALID_HANDLE_VALUE || hWait == NULL) // can't find the Link directory
return false;
m_ThreadParams._hNotification = hWait;
m_hNotificationThread = ::CreateThread(NULL, 0, _FileNotificationThread, (LPVOID) &m_ThreadParams, 0, &m_dwNotificationThreadID);
ATLASSERT(m_hNotificationThread != INVALID_HANDLE_VALUE);
return true;
}
void _CleanUpNotification()
{
MTLVERIFY( ::SetEvent(m_ThreadParams._hExitEvent) );
DWORD dwResult = ::WaitForSingleObject(m_hNotificationThread, DONUT_THREADWAIT);
if (dwResult == WAIT_OBJECT_0) {
// wait the thread over
}
::FindCloseChangeNotification(m_ThreadParams._hNotification);
::CloseHandle(m_ThreadParams._hExitEvent);
::CloseHandle(m_hNotificationThread); // fixed by DGSTR, thanks!
}
static DWORD WINAPI _FileNotificationThread(LPVOID lpParam)
{
_ThreadParam* pParam = (_ThreadParam *) lpParam;
ATLASSERT( ::IsWindow(pParam->_hWnd) );
HANDLE handles[] = { pParam->_hExitEvent, pParam->_hNotification };
for (;;) {
DWORD dwResult = ::WaitForMultipleObjects(2, handles, FALSE, INFINITE);
if (dwResult == WAIT_OBJECT_0) { // killevent
break; // thread must be ended
} else if (dwResult == WAIT_OBJECT_0 + 1) { //notification
::PostMessage(pParam->_hWnd, GET_REGISTERED_MESSAGE(Mtl_FileNotification), 0, 0);
::FindNextChangeNotification(pParam->_hNotification);
} else if (dwResult == WAIT_FAILED) {
ATLASSERT(FALSE);
break;
} else {
ATLASSERT(FALSE);
break;
}
}
return 0;
}
};
| [
"[email protected]"
]
| [
[
[
1,
118
]
]
]
|
ea2fffa213cdd73031056f42e169af4c5ac96dc2 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2005-10-27/common/common_plotPS_functions.cpp | d76608695bc686d632e4579f1ac3ce7586ff9821 | []
| no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 8,317 | cpp | /******************************************/
/* Kicad: Common plot Postscript Routines */
/******************************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "trigo.h"
#include "wxstruct.h"
#include "base_struct.h"
#include "common.h"
#include "plot_common.h"
// Variables partagees avec Common plot Postscript Routines
extern wxPoint LastPenPosition;
extern wxPoint PlotOffset;
extern FILE * PlotOutputFile;
extern double XScale, YScale;
extern int PenWidth;
extern int PlotOrientOptions, etat_plume;
// Locales
static W_PLOT * SheetPS;
/*************************************************************************************/
void InitPlotParametresPS(wxPoint offset, W_PLOT * sheet,
double xscale, double yscale, int orient)
/*************************************************************************************/
/* Set the plot offset for the current plotting
xscale,yscale = coordinate scale (scale coefficient for coordinates)
device_xscale,device_yscale = device coordinate scale (i.e scale used by plot device)
*/
{
PlotOrientOptions = orient;
PlotOffset = offset;
SheetPS = sheet;
XScale = xscale;
YScale = yscale;
}
/*************************************************************************************/
void SetDefaultLineWidthPS( int width)
/*************************************************************************************/
/* Set the default line width (in 1/1000 inch) for the current plotting
*/
{
PenWidth = width; /* epaisseur du trait standard en 1/1000 pouce */
}
/******************************/
void SetColorMapPS(int color)
/******************************/
/* Print the postscript set color command:
r g b setrgbcolor,
r, g, b = color values (= 0 .. 1.0 )
color = color index in ColorRefs[]
*/
{
char Line[1024];
sprintf( Line,"%.3f %.3f %.3f setrgbcolor\n",
(float)ColorRefs[color].m_Red/255,
(float)ColorRefs[color].m_Green/255,
(float)ColorRefs[color].m_Blue/255
);
to_point(Line);
fputs( Line, PlotOutputFile);
}
/***************************************************************/
void PlotFilledSegmentPS(wxPoint start , wxPoint end, int width)
/***************************************************************/
/* Plot 1 segment like a track segment
*/
{
UserToDeviceCoordinate(start);
UserToDeviceCoordinate(end);
fprintf(PlotOutputFile,"%d setlinewidth\n", (int)(XScale * width));
fprintf(PlotOutputFile,"%d %d %d %d line\n", start.x, start.y, end.x, end.y);
}
/******************************************************/
void PlotCircle_PS(wxPoint pos, int diametre, int width)
/******************************************************/
{
int rayon;
char Line[256];
UserToDeviceCoordinate(pos);
rayon = (int)(XScale * diametre / 2);
if(rayon < 0 ) rayon = 0 ;
if ( width > 0 )
{
sprintf(Line,"%d setlinewidth\n", (int)( width * XScale) ) ;
fputs(Line,PlotOutputFile);
}
sprintf(Line,"newpath %d %d %d 0 360 arc stroke\n", pos.x, pos.y, rayon);
fputs(Line,PlotOutputFile) ;
}
/********************************************************************/
void PlotArcPS(wxPoint centre, int StAngle, int EndAngle, int rayon)
/********************************************************************/
/* Plot an arc:
StAngle, EndAngle = start and end arc in 0.1 degree
*/
{
char Line[256];
if(rayon <= 0 ) return ;
/* Calcul des coord du point de depart : */
UserToDeviceCoordinate(centre);
if( PlotOrientOptions == PLOT_MIROIR)
sprintf(Line, "newpath %d %d %d %f %f arc stroke\n", centre.x, centre.y,
(int)(rayon * XScale), (float)StAngle/10, (float)EndAngle/10 ) ;
else
sprintf(Line, "newpath %d %d %d %f %f arc stroke\n", centre.x, centre.y,
(int)(rayon * XScale), -(float)EndAngle/10, -(float)StAngle/10 ) ;
// Undo internationalization printf (float x.y printed x,y)
to_point(Line);
fputs(Line,PlotOutputFile) ;
}
/*****************************************************************************/
void PlotArcPS(wxPoint centre, int StAngle, int EndAngle, int rayon, int width)
/*****************************************************************************/
/* trace d'un arc de cercle:
x, y = coord du centre
StAngle, EndAngle = angle de debut et fin
rayon = rayon de l'arc
w = epaisseur de l'arc
*/
{
char Line[256];
if(rayon <= 0 ) return ;
sprintf(Line,"%d setlinewidth\n", (int) (width * XScale) );
fputs(Line, PlotOutputFile);
PlotArcPS( centre, StAngle, EndAngle, rayon);
}
/***************************************************/
void PlotPolyPS( int nb_segm, int * coord, int fill)
/***************************************************/
/* Trace un polygone ( ferme si rempli ) en format POSTSCRIPT
coord = tableau des coord des sommets
nb_segm = nombre de coord ( 1 coord = 2 elements: X et Y du tableau )
fill : si != 0 polygone rempli
*/
{
int ii;
wxPoint pos;
if( nb_segm <= 1 ) return;
pos.x = coord[0]; pos.y = coord[1];
UserToDeviceCoordinate(pos);
fprintf(PlotOutputFile, "newpath %d %d moveto\n", pos.x, pos.y);
for( ii = 1; ii < nb_segm; ii ++ )
{
pos.x = coord[ii*2]; pos.y = coord[(ii*2)+1];
UserToDeviceCoordinate(pos);
fprintf(PlotOutputFile, "%d %d lineto\n", pos.x, pos.y);
}
/* Fermeture du polygone */
if( fill ) fprintf(PlotOutputFile, "closepath ");
if( fill == 1 ) fprintf(PlotOutputFile, "fill ");
fprintf(PlotOutputFile, "stroke\n");
}
/*************************************/
/* Routine to draw to a new position */
/*************************************/
void LineTo_PS(wxPoint pos, int plume)
{
if ( plume == 'Z') return;
UserToDeviceCoordinate(pos);
if ( plume == 'D')
{
char Line[256];
sprintf(Line,"%d %d %d %d line\n",
LastPenPosition.x, LastPenPosition.y, pos.x, pos.y);
fputs(Line,PlotOutputFile);
}
LastPenPosition = pos;
}
/**********************************************************/
void PrintHeaderPS(FILE * file, const wxString & Creator,
const wxString & FileName, int BBox[4])
/***********************************************************/
/* BBox is the boundary box (position and size of the "client rectangle"
for drawings (page - margins) in mils (0.001 inch)
*/
{
wxString msg;
char Line[1024];
char *PSMacro[] = {
"/line {\n",
" newpath\n",
" moveto\n",
" lineto\n",
" stroke\n",
"} def\n",
"gsave\n",
"72 72 scale\t\t\t%% Talk inches\n",
"1 setlinecap\n",
"1 setlinejoin\n",
"1 setlinewidth\n",
NULL
};
#define MIL_TO_INCH 0.001
int ii;
time_t time1970 = time(NULL);
PlotOutputFile = file;
fputs("%!PS-Adobe-3.0\n",PlotOutputFile); // Print header
/* Print boundary box en 1/72 pouce, box is in mils */
#define CONV_SCALE (MIL_TO_INCH * 72)
msg.Printf("%%%%BoundingBox: %d %d %d %d\n",
(int)(BBox[1]*CONV_SCALE), (int)(BBox[0]*CONV_SCALE),
(int)(BBox[3]*CONV_SCALE), (int)(BBox[2]*CONV_SCALE));
fputs(msg.GetData(),PlotOutputFile);
msg = "%%Title: " + FileName + "\n";
fputs(msg.GetData(),PlotOutputFile);
msg = "%%Creator: " + Creator +"\n";
fputs(msg.GetData(),PlotOutputFile);
msg = "%%CreationDate: "; msg += ctime(&time1970);
fputs(msg.GetData(),PlotOutputFile);
msg = "%%DocumentPaperSizes: " + SheetPS->m_Name + "\n";
fputs(msg.GetData(),PlotOutputFile);
fputs("%%Orientation: Landscape\n%%Pages: (atend)\n%%EndComments\n",PlotOutputFile);
for (ii = 0; PSMacro[ii] != NULL; ii++)
{
fputs(PSMacro[ii],PlotOutputFile);
}
sprintf(Line, "%f %f translate 90 rotate\n",
(float) BBox[3] * MIL_TO_INCH, (float)BBox[0] * MIL_TO_INCH );
// compensation internationalisation printf (float x.y généré x,y)
to_point(Line);
fputs(Line,PlotOutputFile);
sprintf(Line,"%f %f scale\t\t%% Move to User coordinates\n",
XScale, YScale);
to_point(Line);
fputs(Line,PlotOutputFile);
// Set default line width:
fprintf(PlotOutputFile,"%d setlinewidth\n", PenWidth ); //PenWidth in user units
}
/******************************************/
bool CloseFilePS(FILE * plot_file)
/******************************************/
{
fputs("showpage\n",plot_file);
fputs("grestore\n",plot_file);
fclose(plot_file);
return TRUE;
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
292
]
]
]
|
09fd3144885fd8e4249685662577c244f930152f | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlSingleCurve3.h | 12331fe0b0aeaaae18bfd6749ce48acafae7a4ac | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | 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 WMLSINGLECURVE3_H
#define WMLSINGLECURVE3_H
#include "WmlCurve3.h"
namespace Wml
{
template <class Real>
class WML_ITEM SingleCurve3 : public Curve3<Real>
{
public:
// abstract base class
SingleCurve3 (Real fTMin, Real fTMax);
// length-from-time and time-from-length
virtual Real GetLength (Real fT0, Real fT1) const;
virtual Real GetTime (Real fLength, int iIterations = 32,
Real fTolerance = (Real)1e-06) const;
protected:
static Real GetSpeedWithData (Real fTime, void* pvData);
};
typedef SingleCurve3<float> SingleCurve3f;
typedef SingleCurve3<double> SingleCurve3d;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
c41d3c55c43cff5aafc40d6906f75fa9c63d0b97 | b8ac0bb1d1731d074b7a3cbebccc283529b750d4 | /Code/controllers/RecollectionBenchmark/behaviours/FindLine.h | 0ac4e2dbc4147ef70ee3fcc4d13fb4ee7ef8c160 | []
| 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 | 594 | h | #ifndef behaviours_FindLine_h
#define behaviours_FindLine_h
#include "AbstractBehaviour.h"
#include "WorldInfo.h"
#include <vector>
namespace behaviours {
class FindLine : public AbstractBehaviour {
public:
FindLine(WorldInfo * wi, robotapi::IDifferentialWheels * wheels, std::vector<robotapi::IDistanceSensor*> & fss);
void sense();
void action();
private:
std::vector<robotapi::IDistanceSensor*> * fss;
robotapi::IDifferentialWheels * wheels;
WorldInfo * wi;
};
} /* End of namespace behaviours */
#endif // behaviours_FindLine_h
| [
"guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a",
"nuldiego@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a"
]
| [
[
[
1,
7
],
[
9,
30
]
],
[
[
8,
8
]
]
]
|
8747970ff448bdeb10e593d70207f25be03d8a71 | d609fb08e21c8583e5ad1453df04a70573fdd531 | /trunk/OpenXP/模板组件/TemplateModule.cpp | f27eb68111b654483090e11a3ec816e55f84c86f | []
| no_license | svn2github/openxp | d68b991301eaddb7582b8a5efd30bc40e87f2ac3 | 56db08136bcf6be6c4f199f4ac2a0850cd9c7327 | refs/heads/master | 2021-01-19T10:29:42.455818 | 2011-09-17T10:27:15 | 2011-09-17T10:27:15 | 21,675,919 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 592 | cpp | // TemplateModule.cpp
#include "stdafx.h"
#include <afxdllx.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
static AFX_EXTENSION_MODULE TemplateModuleDLL = { NULL, NULL };
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
UNREFERENCED_PARAMETER(lpReserved);
if (dwReason == DLL_PROCESS_ATTACH)
{
if (!AfxInitExtensionModule(TemplateModuleDLL, hInstance))
return 0;
new CDynLinkLibrary(TemplateModuleDLL);
}
else if (dwReason == DLL_PROCESS_DETACH)
{
AfxTermExtensionModule(TemplateModuleDLL);
}
return 1;
} | [
"[email protected]@f92b348d-55a1-4afa-8193-148a6675784b"
]
| [
[
[
1,
26
]
]
]
|
8d183ead6e232e37815575e5d6c46ac70529a2d5 | dc85c005fa80fee1ee649692cec1d5605e8bf9a9 | /Calculate Fibonacci Recursively/main.cpp | 65ff902f7ae84608918af073c0a2d76dbc0b2b0f | []
| no_license | gt500girl/acmlib-zxd | 38163efe0c550cfe68dab05bc7fc6e1e4416941b | 50be5b9b4874130b8a7955d5c55f9823ea6f03b0 | refs/heads/master | 2021-01-10T10:57:16.491457 | 2009-05-09T00:41:35 | 2009-05-09T00:41:35 | 43,588,376 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 722 | cpp | #include <iostream>
using namespace std;
//递推计算Fibonacci第k项,计算时结果对9973取余
int fib(int k) {
int f0 = 0, f1 = 1, t;
for (int i = 2; i <= k; i++) {
t = f1;
f1 = (f0 + f1) % 9973;
f0 = t;
}
return f1;
}
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int n, m;
while (cin >> n >> m) {
if (n < 2) {
//n=1,n=0时不递归,直接得到答案
cout << 0 << endl;
} else {
//m=0时与m=2的答案相同
if (m == 0) m = 2;
//输出
cout << fib(n-m+1) << endl;
}
}
return 0;
}
| [
"dong128@72394ba8-1b3d-11de-a78b-a7aca27b2395"
]
| [
[
[
1,
33
]
]
]
|
172211d23d1c113f5fcdb6129654ce740644fd04 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/Tools/SkinEditor/SkinManager.cpp | bb8283f898bafc21fb3faae8cc0d43d7a5f679a3 | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,335 | cpp | /*!
@file
@author Albert Semenov
@date 08/2010
*/
#include "precompiled.h"
#include "SkinManager.h"
template <> tools::SkinManager* MyGUI::Singleton<tools::SkinManager>::msInstance = nullptr;
template <> const char* MyGUI::Singleton<tools::SkinManager>::mClassTypeName("SkinManager");
namespace tools
{
SkinManager::SkinManager()
{
}
SkinManager::~SkinManager()
{
}
void SkinManager::initialise()
{
}
void SkinManager::shutdown()
{
destroyAllChilds();
}
void SkinManager::clear()
{
destroyAllChilds();
}
void SkinManager::serialization(MyGUI::xml::Element* _node, MyGUI::Version _version)
{
ItemHolder<SkinItem>::EnumeratorItem items = getChildsEnumerator();
while (items.next())
{
MyGUI::xml::Element* node = _node->createChild("SkinItem");
items->serialization(node, _version);
}
}
void SkinManager::deserialization(MyGUI::xml::Element* _node, MyGUI::Version _version)
{
if (getItemSelected() != nullptr)
setItemSelected(nullptr);
destroyAllChilds(false);
MyGUI::xml::ElementEnumerator nodes = _node->getElementEnumerator();
while (nodes.next("SkinItem"))
{
SkinItem* item = createChild(false);
item->deserialization(nodes.current(), _version);
}
eventChangeList();
}
} // namespace tools
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
64
]
]
]
|
2a36888a9abda00f73602abae1ee2fead7f269e7 | e192bb584e8051905fc9822e152792e9f0620034 | /tags/sources_0_1/base/implantation/iterateur_liste_composition.cxx | f4661caa579e93cf029c499074174afee7c254cb | []
| no_license | BackupTheBerlios/projet-univers-svn | 708ffadce21f1b6c83e3b20eb68903439cf71d0f | c9488d7566db51505adca2bc858dab5604b3c866 | refs/heads/master | 2020-05-27T00:07:41.261961 | 2011-07-31T20:55:09 | 2011-07-31T20:55:09 | 40,817,685 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,546 | cxx | /***************************************************************************
* Copyright (C) 2004 by Equipe Projet Univers *
* [email protected] *
* *
* This program 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 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU General Lesser 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. *
***************************************************************************/
///////////////
// Renvoie l'élément courant en référence.
template <class OBJET>
IterateurListeComposition<OBJET>::operator const OBJET&()
{
return *noeudCourant()->element ;
}
///////////////
// Renvoie l'élément courant en association.
template <class OBJET>
IterateurListeComposition<OBJET>::operator Association< OBJET >()
{
return noeudCourant()->element ;
}
template <class OBJET> OBJET*
IterateurListeComposition<OBJET>::operator ->() const {
// OBJET* resultat = (OBJET*)(noeudCourant()->element) ;
//
// if (resultat == NULL)
//
// throw ExceptionBase("IterateurListeComposition<OBJET>::operator ->");
return (noeudCourant()->element).operator->() ;
}
template <class OBJET> OBJET*
IterateurListeComposition<OBJET>::Liberer() {
return noeudCourant()->Liberer() ;
}
template <class OBJET>
IterateurListeComposition<OBJET>::IterateurListeComposition
(const ListeComposition<OBJET>& _l)
: IterateurListe(_l)
{}
template <class OBJET>
IterateurListeComposition<OBJET>::IterateurListeComposition
(const IterateurListeComposition<OBJET>& _i)
: IterateurListe(*_i.liste())
{}
template <class OBJET> void
IterateurListeComposition<OBJET>::AjouterApres(OBJET* _elt) {
Composition<NoeudComposition<OBJET> > n_node(
new NoeudComposition<OBJET>(_elt)) ;
IterateurListeAbstrait::AjouterApres(n_node.Liberer()) ;
}
template <class OBJET> void
IterateurListeComposition<OBJET>::AjouterAvant(OBJET* _elt) {
Composition<NoeudComposition<OBJET> > n_node(
new NoeudComposition<OBJET>(_elt)) ;
IterateurListeAbstrait::AjouterAvant(n_node.Liberer()) ;
}
///////////////////
// Ajoute une liste.
template <class OBJET> void
IterateurListeComposition<OBJET>::Ajouter
(const ListeComposition< OBJET >& _nouveaux) {
liste()->AjouterEnTete(_nouveaux) ;
}
template <class OBJET> void
IterateurListeComposition<OBJET>::Enlever() {
Composition< OBJET > temp(Liberer()) ;
IterateurListe::Enlever() ;
}
| [
"rogma@fb75c231-3be1-0310-9bb4-c95e2f850c73"
]
| [
[
[
1,
109
]
]
]
|
296a994f3e33bfaf3deac95381924f47355faa53 | 4aadb120c23f44519fbd5254e56fc91c0eb3772c | /Source/EduNetGames/ModNetSoccer/NetSoccerBall.h | 178637cfa43fc5840084af29cbd163b3065507cb | []
| no_license | janfietz/edunetgames | d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba | 04d787b0afca7c99b0f4c0692002b4abb8eea410 | refs/heads/master | 2016-09-10T19:24:04.051842 | 2011-04-17T11:00:09 | 2011-04-17T11:00:09 | 33,568,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,124 | h | #ifndef __NETSOCCERBALL_H__
#define __NETSOCCERBALL_H__
//-----------------------------------------------------------------------------
// Copyright (c) 2009, Jan Fietz, Cyrus Preuss
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of EduNetGames nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#include "OpenSteer/AABBox.h"
#include "OpenSteerUT/AbstractVehicleUpdate.h"
#include "OpenSteerUT/AbstractVehicleUtilities.h"
#include "OpenSteerUT/VehicleClassIds.h"
#include "EduNetConnect/SimpleNetworkVehicle.h"
//-----------------------------------------------------------------------------
class NetSoccerBall : public OpenSteer::SimpleNetworkVehicle
{
ET_DECLARE_BASE ( OpenSteer::SimpleNetworkVehicle )
public:
NetSoccerBall();
virtual ~NetSoccerBall();
// create a clone
virtual AbstractVehicle* cloneVehicle ( void ) const;
// reset state
virtual void reset ( void );
virtual osVector3 determineCombinedSteering( const float elapsedTime );
// draw this character/vehicle into the scene
virtual void draw( OpenSteer::AbstractRenderer*,
const float currentTime, const float elapsedTime ) OS_OVERRIDE;
void kick ( OpenSteer::Vec3 dir, const float elapsedTime );
void setBox( OpenSteer::AABBox *bbox ){ this->m_bbox = bbox;}
private:
ET_IMPLEMENT_CLASS_NO_COPY( NetSoccerBall )
OpenSteer::AABBox *m_bbox;
};
typedef OpenSteer::VehicleClassIdMixin<NetSoccerBall, ET_CID_NETSOCCER_BALL> TNetSoccerBall;
#endif // __NETSOCCERBALL_H__
| [
"janfietz@localhost"
]
| [
[
[
1,
68
]
]
]
|
51fcb13e00d724b998c4a8e95db29bd26f5292b8 | fe1a3713b778df038bcccbcbe22c27c0d9cc3b38 | /trunk/src/MainFrameListener.cpp | d7159292659859db5532891bd175a1e0cd852a92 | []
| no_license | BackupTheBerlios/vrr-svn | b73a3ea9bb5f08cc82e5713719053c6d03d8ed5b | 5693ada04551d3d96b5bada77153e3d9b920a6a8 | refs/heads/master | 2020-05-21T01:10:12.941618 | 2006-04-09T14:16:07 | 2006-04-09T14:16:07 | 40,801,427 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34 | cpp | #include "mainframelistener.h"
| [
"cleberc@7bcf2313-58fc-0310-815c-b6916ff3354b"
]
| [
[
[
1,
2
]
]
]
|
98c1de7f28ef606122307856c619643b01b7e4e7 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osg/TextureCubeMap | 98601ad6e242460420f9fb4110ee4cf938cb5e38 | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,100 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#ifndef OSG_TEXTURECUBEMAP
#define OSG_TEXTURECUBEMAP 1
#include <osg/Texture>
#ifndef GL_TEXTURE_CUBE_MAP
#define GL_TEXTURE_CUBE_MAP 0x8513
#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514
#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B
#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
#endif
namespace osg {
/** TextureCubeMap state class which encapsulates OpenGL texture cubemap functionality. */
class OSG_EXPORT TextureCubeMap : public Texture
{
public :
TextureCubeMap();
/** Copy constructor using CopyOp to manage deep vs shallow copy. */
TextureCubeMap(const TextureCubeMap& cm,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
META_StateAttribute(osg, TextureCubeMap,TEXTURE);
/** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
virtual int compare(const StateAttribute& rhs) const;
virtual GLenum getTextureTarget() const { return GL_TEXTURE_CUBE_MAP; }
enum Face {
POSITIVE_X=0,
NEGATIVE_X=1,
POSITIVE_Y=2,
NEGATIVE_Y=3,
POSITIVE_Z=4,
NEGATIVE_Z=5
};
/** Set the texture image for specified face. */
virtual void setImage(unsigned int face, Image* image);
/** Get the texture image for specified face. */
virtual Image* getImage(unsigned int face);
/** Get the const texture image for specified face. */
virtual const Image* getImage(unsigned int face) const;
/** Get the number of images that can be assigned to the Texture. */
virtual unsigned int getNumImages() const { return 6; }
inline unsigned int& getModifiedCount(unsigned int face,unsigned int contextID) const
{
// get the modified count for the current contextID.
return _modifiedCount[face][contextID];
}
/** Set the texture width and height. If width or height are zero then
* the repsective size value is calculated from the source image sizes.
*/
inline void setTextureSize(int width, int height) const
{
_textureWidth = width;
_textureHeight = height;
}
void setTextureWidth(int width) { _textureWidth=width; }
void setTextureHeight(int height) { _textureHeight=height; }
virtual int getTextureWidth() const { return _textureWidth; }
virtual int getTextureHeight() const { return _textureHeight; }
virtual int getTextureDepth() const { return 1; }
class OSG_EXPORT SubloadCallback : public Referenced
{
public:
virtual void load(const TextureCubeMap& texture,State& state) const = 0;
virtual void subload(const TextureCubeMap& texture,State& state) const = 0;
};
void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; }
SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); }
const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); }
/** Set the number of mip map levels the the texture has been created with.
* Should only be called within an osg::Texuture::apply() and custom OpenGL texture load.
*/
void setNumMipmapLevels(unsigned int num) const { _numMipmapLevels=num; }
/** Get the number of mip map levels the the texture has been created with. */
unsigned int getNumMipmapLevels() const { return _numMipmapLevels; }
/** Copies a two-dimensional texture subimage, as per
* glCopyTexSubImage2D. Updates a portion of an existing OpenGL
* texture object from the current OpenGL background framebuffer
* contents at position \a x, \a y with width \a width and height
* \a height. Loads framebuffer data into the texture using offsets
* \a xoffset and \a yoffset. \a width and \a height must be powers
* of two. */
void copyTexSubImageCubeMap(State& state, int face, int xoffset, int yoffset, int x, int y, int width, int height );
/** On first apply (unless already compiled), create the mipmapped
* texture and bind it. Subsequent apply will simple bind to texture.
*/
virtual void apply(State& state) const;
/** Extensions class which encapsulates the querying of extensions and
* associated function pointers, and provides convinience wrappers to
* check for the extensions or use the associated functions.
*/
class OSG_EXPORT Extensions : public osg::Referenced
{
public:
Extensions(unsigned int contextID);
Extensions(const Extensions& rhs);
void lowestCommonDenominator(const Extensions& rhs);
void setupGLExtensions(unsigned int contextID);
void setCubeMapSupported(bool flag) { _isCubeMapSupported=flag; }
bool isCubeMapSupported() const { return _isCubeMapSupported; }
protected:
~Extensions() {}
bool _isCubeMapSupported;
};
/** Function to call to get the extension of a specified context.
* If the Exentsion object for that context has not yet been created
* and the 'createIfNotInitalized' flag been set to false then returns NULL.
* If 'createIfNotInitalized' is true then the Extensions object is
* automatically created. However, in this case the extension object will
* only be created with the graphics context associated with ContextID.
*/
static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized);
/** The setExtensions method allows users to override the extensions across graphics contexts.
* Typically used when you have different extensions supported across graphics pipes
* but need to ensure that they all use the same low common denominator extensions.
*/
static void setExtensions(unsigned int contextID,Extensions* extensions);
protected :
virtual ~TextureCubeMap();
bool imagesValid() const;
virtual void computeInternalFormat() const;
void allocateMipmap(State& state) const;
ref_ptr<Image> _images[6];
// subloaded images can have different texture and image sizes.
mutable GLsizei _textureWidth, _textureHeight;
// number of mip map levels the the texture has been created with,
mutable GLsizei _numMipmapLevels;
ref_ptr<SubloadCallback> _subloadCallback;
typedef buffered_value<unsigned int> ImageModifiedCount;
mutable ImageModifiedCount _modifiedCount[6];
};
}
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
200
]
]
]
|
|
0e67aaffecc8378079991b2fe74530363d503ab7 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ogre/OgreNewt/boost/mpl/min.hpp | a547a28b33dbb8f62f4b978ea96380084c08dc53 | []
| no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | hpp |
#ifndef BOOST_MPL_MIN_HPP_INCLUDED
#define BOOST_MPL_MIN_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/min.hpp,v $
// $Date: 2006/04/17 23:49:40 $
// $Revision: 1.1 $
#include <boost/mpl/min_max.hpp>
#endif // BOOST_MPL_MIN_HPP_INCLUDED
| [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
]
| [
[
[
1,
19
]
]
]
|
b0b43657208f2bfbf036b03def0af089f29640c5 | 028d6009f3beceba80316daa84b628496a210f8d | /uidesigner/com.nokia.sdt.referenceprojects.test/data2/settings_list_3_0/reference/inc/settings_list_3_0AppUi.h | 530aa3b80db4497140dc783d4d2871e882ad4180 | []
| no_license | JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp | fa50cafa69d3e317abf0db0f4e3e557150fd88b3 | 4420f338bc4e522c563f8899d81201857236a66a | refs/heads/master | 2020-12-30T16:45:28.474973 | 2010-10-20T16:19:31 | 2010-10-20T16:19:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,743 | h | #ifndef SETTINGS_LIST_3_0APPUI_H
#define SETTINGS_LIST_3_0APPUI_H
// [[[ begin generated region: do not modify [Generated Includes]
#include <aknviewappui.h>
// ]]] end generated region [Generated Includes]
// [[[ begin generated region: do not modify [Generated Forward Declarations]
class CSettings_list_3_0SettingItemListView;
// ]]] end generated region [Generated Forward Declarations]
/**
* @class Csettings_list_3_0AppUi settings_list_3_0AppUi.h
* @brief The AppUi class handles application-wide aspects of the user interface, including
* view management and the default menu, control pane, and status pane.
*/
class Csettings_list_3_0AppUi : public CAknViewAppUi
{
public:
// constructor and destructor
Csettings_list_3_0AppUi();
virtual ~Csettings_list_3_0AppUi();
void ConstructL();
public:
// from CCoeAppUi
TKeyResponse HandleKeyEventL(
const TKeyEvent& aKeyEvent,
TEventCode aType );
// from CEikAppUi
void HandleCommandL( TInt aCommand );
void HandleResourceChangeL( TInt aType );
// from CAknAppUi
void HandleViewDeactivation(
const TVwsViewId& aViewIdToBeDeactivated,
const TVwsViewId& aNewlyActivatedViewId );
private:
void InitializeContainersL();
// [[[ begin generated region: do not modify [Generated Methods]
public:
// ]]] end generated region [Generated Methods]
// [[[ begin generated region: do not modify [Generated Instance Variables]
private:
CSettings_list_3_0SettingItemListView* iSettings_list_3_0SettingItemListView;
// ]]] end generated region [Generated Instance Variables]
// [[[ begin [User Handlers]
protected:
// ]]] end [User Handlers]
};
#endif // SETTINGS_LIST_3_0APPUI_H
| [
"[email protected]"
]
| [
[
[
1,
58
]
]
]
|
c97ab50aee9aded9cdf585344946e1a0c8709ebe | e360300b721e9cac9b1cc1309fe4b86b71d9b3a6 | /blatt1/coordinates.cc | 5981a3895bada3d7f7995096cebc67abe9193bd6 | []
| no_license | dawehner/physics-compo | 19447bd254e5809f419ded8bcd6a1a8a075a0427 | 01cbf65ee09c357967ead1378a4dc9f57e02d8f8 | refs/heads/master | 2020-06-26T18:09:05.050382 | 2011-07-24T20:15:14 | 2011-07-24T20:15:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 639 | cc | #include <cmath>
/**
* Generate some variables.
*/
inline double calc_phi(double anomalie_excent, double excent) {
return 2 * atan(
sqrt((1+excent)/(1-excent)) *
tan(anomalie_excent / 2));
}
inline double calc_r(double a, double e, double phi, double phi0) {
// phi0 is not used here.
return (a * (1 - e * e)) / (1 + e * cos(phi - 0));
}
inline double calc_x(double r, double phi, double phi0) {
return r * cos(phi + phi0);
}
inline double calc_y(double r, double phi, double phi0) {
return r * sin(phi + phi0);
}
inline double grad_to_rad(double grad) {
return M_PI * grad / 180.0;
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
5
],
[
7,
8
],
[
10,
10
],
[
14,
15
],
[
17,
19
],
[
21,
23
],
[
25,
25
]
],
[
[
6,
6
],
[
9,
9
],
[
11,
13
],
[
16,
16
],
[
20,
20
],
[
24,
24
],
[
26,
26
]
]
]
|
74202c509faee97b91ad16af1630c67526c2f8f9 | e2f961659b90ff605798134a0a512f9008c1575b | /Example-01/MODEL_INIT.INC | 10dae08605c7922afdad7f8ad4e942571b8478aa | []
| no_license | bs-eagle/test-models | 469fe485a0d9aec98ad06d39b75901c34072cf60 | d125060649179b8e4012459c0a62905ca5235ba7 | refs/heads/master | 2021-01-22T22:56:50.982294 | 2009-11-10T05:49:22 | 2009-11-10T05:49:22 | 1,266,143 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,366 | inc | EQUIL
2700 286 2842 1* 2700 1* 1* 1* 1*
2700 286 2824 1* 2700 1* 1* 1* 1*
2700 286 2824 1* 2700 1* 1* 1* 1*
2700 286 2824 1* 2700 1* 1* 1* 1*
2700 286 2824 1* 2700 1* 1* 1* 1*
2700 286 2824 1* 2700 1* 1* 1* 1*
2700 286 2824 1* 2700 1* 1* 1* 1*
2700 286 2824 1* 2700 1* 1* 1* 1*
2700 286 2824 1* 2700 1* 1* 1* 1*
2700 286 2824 1* 2700 1* 1* 1* 1*
/
PBVD
1000 210
2830 210
/
1000 210
2830 210
/
1000 210
2830 210
/
1000 210
2830 210
/
1000 210
2830 210
/
1000 210
2830 210
/
1000 210
2830 210
/
1000 210
2830 210
/
1000 210
2830 210
/
1000 210
2830 210
/
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
08183ea005abdf30b7e88b14ceda35f093f03786 | 61fb1bf48c8eeeda8ecb2c40fcec1d3277ba6935 | /patoGUI/checkoutdialog.cpp | 153e3f77b09bc057809cce06cade1ffaabd2437e | []
| no_license | matherthal/pato-scm | 172497f3e5c6d71a2cbbd2db132282fb36ba4871 | ba573dad95afa0c0440f1ae7d5b52a2736459b10 | refs/heads/master | 2020-05-20T08:48:12.286498 | 2011-11-25T11:05:23 | 2011-11-25T11:05:23 | 33,139,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,419 | cpp | #include <QtGui>
#include "checkoutdialog.h"
#include "ui_checkoutdialog.h"
CheckoutDialog::CheckoutDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::CheckoutDialog)
{
//Start Configurations
ui->setupUi(this);
ui->radioButtonHEAD->setChecked(true);
ui->labelRevisionNumber->setEnabled(false);
ui->lineEditRevisionNumber->setEnabled(false);
//Actions
connect(ui->buttonChangeRepository, SIGNAL(clicked()), this, SLOT(changeRepository()));
connect(ui->buttonCancel, SIGNAL(clicked()), this, SLOT(close()));
connect(ui->buttonCheckout, SIGNAL(clicked()), this, SLOT(checkout()));
connect(ui->radioButtonOther, SIGNAL(clicked()), this, SLOT(enableRevisionNumber()));
connect(ui->radioButtonHEAD, SIGNAL(clicked()), this, SLOT(disableRevisionNumber()));
//Window properties
setFixedSize(500,250);
setWindowTitle("Check-out");
}
CheckoutDialog::~CheckoutDialog()
{
delete ui;
}
void CheckoutDialog::setRepositoryPath(const QString &str)
{
ui->labelRepositoryPath->setText(str);
}
void CheckoutDialog::changeRepository()
{
emit showEnvironmentSettings();
}
void CheckoutDialog::enableRevisionNumber()
{
ui->labelRevisionNumber->setEnabled(true);
ui->lineEditRevisionNumber->setEnabled(true);
ui->lineEditRevisionNumber->setFocus();
}
void CheckoutDialog::disableRevisionNumber()
{
ui->labelRevisionNumber->setEnabled(false);
ui->lineEditRevisionNumber->setEnabled(false);
}
void CheckoutDialog::checkout()
{
if (ui->radioButtonOther->isChecked() && ui->lineEditRevisionNumber->text().isEmpty()) {
int msgBox = QMessageBox::warning(this, tr("Error"),
tr("You must inform a revision number or select HEAD."),
QMessageBox::Ok);
ui->lineEditRevisionNumber->setFocus();
}
else if (ui->radioButtonOther->isChecked() && ui->lineEditRevisionNumber->text()=="0") {
int msgBox = QMessageBox::warning(this, tr("Error"),
tr("Invalid revision number!"),
QMessageBox::Ok);
ui->lineEditRevisionNumber->setFocus();
} else {
//Checkout
//emit setRevisionNumber(ui->lineEditRevisionNumber->text());
//emit checkout();
}
}
| [
"rafael@Micro-Mariana"
]
| [
[
[
1,
71
]
]
]
|
ba4a8cf5581c28c167b2a8b28a900992b7eb3ab6 | ad6a37b326227901f75bad781f2cbf357b42544f | /Effects/GrayScale.h | 31ddfe8230adcd57a2cea7f636376cc68b01045c | []
| no_license | OpenEngineDK/branches-PostProcessingEffects | 83b4e1dc1a390b66357bed6bc94d4cab16ef756a | c4f4585cbdbb905d382499bf12fd8bfe7d27812c | refs/heads/master | 2021-01-01T05:43:32.564360 | 2009-04-20T14:50:03 | 2009-04-20T14:50:03 | 58,077,144 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | h | #ifndef __GRAYSCALE_H__
#define __GRAYSCALE_H__
#include <PostProcessing/OpenGL/PostProcessingEffect.h>
#include <PostProcessing/IPostProcessingPass.h>
#include <Display/Viewport.h>
#include <Core/IEngine.h>
#include <vector>
#include <stdio.h>
using namespace OpenEngine::PostProcessing;
class GrayScale : public PostProcessingEffect {
private:
IPostProcessingPass* pass1;
public:
GrayScale(Viewport* viewport, IEngine& engine);
void Setup();
void PerFrame(const float deltaTime);
};
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
6
],
[
8,
20
],
[
22,
28
]
],
[
[
7,
7
],
[
21,
21
]
]
]
|
f4e03f86fe76f7df0db08fb77943bbbf7f86ad8c | f2cbdee1dfdcad7b77c597e1af5f40ad83bad4aa | /MyC++/CreateMutex/test.cpp | cee76d1021d3b186968d2c31c310b3855a3f4aa4 | []
| no_license | jdouglas71/Examples | d03d9effc414965991ca5b46fbcf808a9dd6fe6d | b7829b131581ea3a62cebb2ae35571ec8263fd61 | refs/heads/master | 2021-01-18T14:23:56.900005 | 2011-04-07T19:34:04 | 2011-04-07T19:34:04 | 1,578,581 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 664 | cpp | #include <windows.h>
#include <iostream.h>
void perror32(char*& ptr)
{
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
(LPTSTR)&ptr,
0,
NULL
);
}
int main(int argc, char* argv[])
{
int retval = 0;
HANDLE appHandle = CreateMutex( NULL, TRUE, "FusionAdministrator" );
if( appHandle == NULL )
{
MessageBox( NULL, "Couldn't create Mutex", "Test", MB_OK );
}
return retval;
}
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
465ff35a2423788ae2a6eb05c1880a316018d4ad | 68bfdfc18f1345d1ff394b8115681110644d5794 | /Examples/Example01/ModelGeosetFace.cpp | 5934369006e80bc5f9b8c29d8a1424826094cab2 | []
| no_license | y-gupta/glwar3 | 43afa1efe475d937ce0439464b165c745e1ec4b1 | bea5135bd13f9791b276b66490db76d866696f9a | refs/heads/master | 2021-05-28T12:20:41.532727 | 2010-12-09T07:52:12 | 2010-12-09T07:52:12 | 32,911,819 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | cpp | //+-----------------------------------------------------------------------------
//| Included files
//+-----------------------------------------------------------------------------
#include "ModelGeosetFace.h"
//+-----------------------------------------------------------------------------
//| Constructor
//+-----------------------------------------------------------------------------
MODEL_GEOSET_FACE::MODEL_GEOSET_FACE()
{
Index1 = INVALID_INDEX;
Index2 = INVALID_INDEX;
Index3 = INVALID_INDEX;
}
//+-----------------------------------------------------------------------------
//| Destructor
//+-----------------------------------------------------------------------------
MODEL_GEOSET_FACE::~MODEL_GEOSET_FACE()
{
Clear();
}
//+-----------------------------------------------------------------------------
//| Clears the geoset face
//+-----------------------------------------------------------------------------
VOID MODEL_GEOSET_FACE::Clear()
{
//Empty
}
| [
"sihan6677@deb3bc48-0ee2-faf5-68d7-13371a682d83"
]
| [
[
[
1,
32
]
]
]
|
b63f60c6f5f04929ebe973386391939d4804fac7 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/graph/example/fibonacci_heap.cpp | b900e4743990c364309e6eaf43552b7c6e03dd7c | [
"Artistic-2.0",
"LicenseRef-scancode-public-domain"
]
| permissive | 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 | 3,010 | cpp | //=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// This file is part of the Boost Graph Library
//
// You should have received a copy of the License Agreement for the
// Boost Graph Library along with the software; see the file LICENSE.
// If not, contact Office of Research, University of Notre Dame, Notre
// Dame, IN 46556.
//
// Permission to modify the code and to distribute modified code is
// granted, provided the text of this NOTICE is retained, a notice that
// the code was modified is included with the above COPYRIGHT NOTICE and
// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE
// file is distributed with the modified code.
//
// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
// By way of example, but not limitation, Licensor MAKES NO
// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
// OR OTHER RIGHTS.
//=======================================================================
#include <boost/config.hpp>
#include <iostream>
#include <vector>
#include <boost/graph/random.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <algorithm>
#include <boost/pending/fibonacci_heap.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/pending/indirect_cmp.hpp>
using namespace boost;
int
main()
{
typedef indirect_cmp<float*,std::less<float> > ICmp;
int i;
boost::mt19937 gen;
for (int N = 2; N < 200; ++N) {
uniform_int<> distrib(0, N-1);
variate_generator<boost::mt19937&, uniform_int<> > rand_gen(gen, distrib);
for (int t = 0; t < 10; ++t) {
std::vector<float> v, w(N);
ICmp cmp(&w[0], std::less<float>());
fibonacci_heap<int, ICmp> Q(N, cmp);
for (int c = 0; c < w.size(); ++c)
w[c] = c;
std::random_shuffle(w.begin(), w.end());
for (i = 0; i < N; ++i)
Q.push(i);
for (i = 0; i < N; ++i) {
int u = rand_gen();
float r = rand_gen(); r /= 2.0;
w[u] = w[u] - r;
Q.update(u);
}
for (i = 0; i < N; ++i) {
v.push_back(w[Q.top()]);
Q.pop();
}
std::sort(w.begin(), w.end());
if (! std::equal(v.begin(), v.end(), w.begin())) {
std::cout << std::endl << "heap sorted: ";
std::copy(v.begin(), v.end(),
std::ostream_iterator<float>(std::cout," "));
std::cout << std::endl << "correct: ";
std::copy(w.begin(), w.end(),
std::ostream_iterator<float>(std::cout," "));
std::cout << std::endl;
return -1;
}
}
}
std::cout << "fibonacci heap passed test" << std::endl;
return 0;
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
86
]
]
]
|
bfe60c84916b72d66f4cd364366ef4672610ae10 | c1a2953285f2a6ac7d903059b7ea6480a7e2228e | /deitel/appG/ATM.cpp | 92d32b22dd9b924f950fb3acd90c49e06a299b40 | []
| no_license | tecmilenio/computacion2 | 728ac47299c1a4066b6140cebc9668bf1121053a | a1387e0f7f11c767574fcba608d94e5d61b7f36c | refs/heads/master | 2016-09-06T19:17:29.842053 | 2008-09-28T04:27:56 | 2008-09-28T04:27:56 | 50,540 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,293 | cpp | // ATM.cpp
// Member-function definitions for class ATM.
#include "ATM.h" // ATM class definition
#include "Transaction.h" // Transaction class definition
#include "BalanceInquiry.h" // BalanceInquiry class definition
#include "Withdrawal.h" // Withdrawal class definition
#include "Deposit.h" // Deposit class definition
// enumeration constants represent main menu options
enum MenuOption { BALANCE_INQUIRY = 1, WITHDRAWAL, DEPOSIT, EXIT };
// ATM default constructor initializes data members
ATM::ATM()
: userAuthenticated ( false ), // user is not authenticated to start
currentAccountNumber( 0 ) // no current account number to start
{
// empty body
} // end ATM default constructor
// start ATM
void ATM::run()
{
// welcome and authenticate user; perform transactions
while ( true )
{
// loop while user is not yet authenticated
while ( !userAuthenticated )
{
screen.displayMessageLine( "\nWelcome!" );
authenticateUser(); // authenticate user
} // end while
performTransactions(); // user is now authenticated
userAuthenticated = false; // reset before next ATM session
currentAccountNumber = 0; // reset before next ATM session
screen.displayMessageLine( "\nThank you! Goodbye!" );
} // end while
} // end function run
// attempt to authenticate user against database
void ATM::authenticateUser()
{
screen.displayMessage( "\nPlease enter your account number: " );
int accountNumber = keypad.getInput(); // input account number
screen.displayMessage( "\nEnter your PIN: " ); // prompt for PIN
int pin = keypad.getInput(); // input PIN
// set userAuthenticated to bool value returned by database
userAuthenticated =
bankDatabase.authenticateUser( accountNumber, pin );
// check whether authentication succeeded
if ( userAuthenticated )
{
currentAccountNumber = accountNumber; // save user's account #
} // end if
else
screen.displayMessageLine(
"Invalid account number or PIN. Please try again." );
} // end function authenticateUser
// display the main menu and perform transactions
void ATM::performTransactions()
{
// local pointer to store transaction currently being processed
Transaction *currentTransactionPtr;
bool userExited = false; // user has not chosen to exit
// loop while user has not chosen option to exit system
while ( !userExited )
{
// show main menu and get user selection
int mainMenuSelection = displayMainMenu();
// decide how to proceed based on user's menu selection
switch ( mainMenuSelection )
{
// user chose to perform one of three transaction types
case BALANCE_INQUIRY:
case WITHDRAWAL:
case DEPOSIT:
// initialize as new object of chosen type
currentTransactionPtr =
createTransaction( mainMenuSelection );
currentTransactionPtr->execute(); // execute transaction
// free the space for the dynamically allocated Transaction
delete currentTransactionPtr;
break;
case EXIT: // user chose to terminate session
screen.displayMessageLine( "\nExiting the system..." );
userExited = true; // this ATM session should end
break;
default: // user did not enter an integer from 1-4
screen.displayMessageLine(
"\nYou did not enter a valid selection. Try again." );
break;
} // end switch
} // end while
} // end function performTransactions
// display the main menu and return an input selection
int ATM::displayMainMenu() const
{
screen.displayMessageLine( "\nMain menu:" );
screen.displayMessageLine( "1 - View my balance" );
screen.displayMessageLine( "2 - Withdraw cash" );
screen.displayMessageLine( "3 - Deposit funds" );
screen.displayMessageLine( "4 - Exit\n" );
screen.displayMessage( "Enter a choice: " );
return keypad.getInput(); // return user's selection
} // end function displayMainMenu
// return object of specified Transaction derived class
Transaction *ATM::createTransaction( int type )
{
Transaction *tempPtr; // temporary Transaction pointer
// determine which type of Transaction to create
switch ( type )
{
case BALANCE_INQUIRY: // create new BalanceInquiry transaction
tempPtr = new BalanceInquiry(
currentAccountNumber, screen, bankDatabase );
break;
case WITHDRAWAL: // create new Withdrawal transaction
tempPtr = new Withdrawal( currentAccountNumber, screen,
bankDatabase, keypad, cashDispenser );
break;
case DEPOSIT: // create new Deposit transaction
tempPtr = new Deposit( currentAccountNumber, screen,
bankDatabase, keypad, depositSlot );
break;
} // end switch
return tempPtr; // return the newly created object
} // end function createTransaction
/**************************************************************************
* (C) Copyright 1992-2008 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
156
]
]
]
|
2bf494b71ef7a9709450f1b98afd43fd8a6ab8f9 | 2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4 | /OUAN/OUAN/Src/Core/GamePausedState.h | 4f6c95b8645a2f13cc74bcefe4e58d2fef57e37f | []
| no_license | juanjmostazo/once-upon-a-night | 9651dc4dcebef80f0475e2e61865193ad61edaaa | f8d5d3a62952c45093a94c8b073cbb70f8146a53 | refs/heads/master | 2020-05-28T05:45:17.386664 | 2010-10-06T12:49:50 | 2010-10-06T12:49:50 | 38,101,059 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,112 | h | #ifndef GAMEPAUSEDSTATEH_H
#define GAMEPAUSEDSTATEH_H
#include "../OUAN.h"
#include "GameState.h"
namespace OUAN
{
const std::string GAMEPAUSED_IMG_NAME="pause";
const std::string GAMEPAUSED_IMG_EXTENSION=".png";
const std::string GAMEPAUSED_MATERIAL_NAME="PauseBg";
const std::string GAMEPAUSED_GROUP=Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
const std::string GAMEPAUSED_SCREENNODE="GPScreen";
///State corresponding to the game's extras menu
class GamePausedState: public GameState{
private:
Ogre::Rectangle2D* mScreen;
public:
/// init extras screen's resources
void init(ApplicationPtr app);
/// Clean up extras screen's resources
void cleanUp();
/// pause state
void pause();
/// resume state
void resume();
/// process input events
/// @param app the parent application
void handleEvents();
/// Update game according to the current state
/// @param app the parent app
void update(long elapsedTime);
/// Default constructor
GamePausedState();
/// Destructor
~GamePausedState();
};
}
#endif | [
"ithiliel@1610d384-d83c-11de-a027-019ae363d039"
]
| [
[
[
1,
46
]
]
]
|
8240e15da61557ba658bdf76a166f8851b19d870 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SEEffects/SEColorNormalDepthEffect.h | 6a7033cf427bd9bbe9627b52a864da9d2cf341e5 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,028 | h | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_ColorNormalDepthEffect_H
#define Swing_ColorNormalDepthEffect_H
#include "SEFoundationLIB.h"
#include "SEPlatforms.h"
#include "SEShaderEffect.h"
namespace Swing
{
//----------------------------------------------------------------------------
// Description:使用的pixel shader输出color,normal,depth给color0,color1,color2.
// Author:Sun Che
// Date:20090316
//----------------------------------------------------------------------------
class SE_FOUNDATION_API SEColorNormalDepthEffect : public SEShaderEffect
{
SE_DECLARE_RTTI;
SE_DECLARE_NAME_ID;
SE_DECLARE_STREAM;
public:
SEColorNormalDepthEffect(void);
virtual ~SEColorNormalDepthEffect(void);
float FarCilpDist;
protected:
virtual void OnLoadPrograms(int iPass, SEProgram* pVProgram,
SEProgram* pPProgram, SEProgram* pGProgram);
virtual void OnPreApplyEffect(SERenderer* pRenderer, bool bPrimaryEffect);
static float ms_fFarCilpDist;
};
typedef SESmartPointer<SEColorNormalDepthEffect> SEColorNormalDepthEffectPtr;
}
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
60
]
]
]
|
c263211f1f34485bf13a0ad9aa84a997783d60b8 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/multi_index/example/memfun_key.cpp | ad5ee10538dbc320b1a6bb7b46bb825108bcc073 | [
"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 | ISO-8859-1 | C++ | false | false | 2,091 | cpp | /* Boost.MultiIndex example of member functions used as key extractors.
*
* Copyright 2003-2006 Joaquín M López Muñoz.
* 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/multi_index for library home page.
*/
#if !defined(NDEBUG)
#define BOOST_MULTI_INDEX_ENABLE_INVARIANT_CHECKING
#define BOOST_MULTI_INDEX_ENABLE_SAFE_MODE
#endif
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <iostream>
#include <string>
using namespace boost::multi_index;
/* A name record consists of the given name (e.g. "Charlie")
* and the family name (e.g. "Brown"). The full name, calculated
* by name_record::name() is laid out in the "phonebook order"
* family name + given_name.
*/
struct name_record
{
name_record(std::string given_name_,std::string family_name_):
given_name(given_name_),family_name(family_name_)
{}
std::string name()const
{
std::string str=family_name;
str+=" ";
str+=given_name;
return str;
}
private:
std::string given_name;
std::string family_name;
};
/* multi_index_container with only one index based on name_record::name().
* See Compiler specifics: Use of const_mem_fun_explicit and
* mem_fun_explicit for info on BOOST_MULTI_INDEX_CONST_MEM_FUN.
*/
typedef multi_index_container<
name_record,
indexed_by<
ordered_unique<
BOOST_MULTI_INDEX_CONST_MEM_FUN(name_record,std::string,name)
>
>
> name_record_set;
int main()
{
name_record_set ns;
ns.insert(name_record("Joe","Smith"));
ns.insert(name_record("Robert","Nightingale"));
ns.insert(name_record("Robert","Brown"));
ns.insert(name_record("Marc","Tuxedo"));
/* list the names in ns in phonebook order */
for(name_record_set::iterator it=ns.begin();it!=ns.end();++it){
std::cout<<it->name()<<std::endl;
}
return 0;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
79
]
]
]
|
8d86cd01fd1c579d112dd550484acf6885efe87e | 989aa92c9dab9a90373c8f28aa996c7714a758eb | /HydraIRC/EventManager.cpp | 93376ef57cd73858f595d29ffc16a1171ca775ff | []
| no_license | john-peterson/hydrairc | 5139ce002e2537d4bd8fbdcebfec6853168f23bc | f04b7f4abf0de0d2536aef93bd32bea5c4764445 | refs/heads/master | 2021-01-16T20:14:03.793977 | 2010-04-03T02:10:39 | 2010-04-03T02:10:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,543 | cpp | /*
HydraIRC
Copyright (C) 2002-2006 Dominic Clifton aka Hydra
HydraIRC limited-use source license
1) You can:
1.1) Use the source to create improvements and bug-fixes to send to the
author to be incorporated in the main program.
1.2) Use it for review/educational purposes.
2) You can NOT:
2.1) Use the source to create derivative works. (That is, you can't release
your own version of HydraIRC with your changes in it)
2.2) Compile your own version and sell it.
2.3) Distribute unmodified, modified source or compiled versions of HydraIRC
without first obtaining permission from the author. (I want one place
for people to come to get HydraIRC from)
2.4) Use any of the code or other part of HydraIRC in anything other than
HydraIRC.
3) All code submitted to the project:
3.1) Must not be covered by any license that conflicts with this license
(e.g. GPL code)
3.2) Will become the property of the author.
*/
/////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "HydraIRC.h"
//Define this to enable a event queue dump each time ProcessEvents() is called
//#define EVENTMANAGER_DEBUG
#ifdef DEBUG
char *g_EventIDNames[EV_LAST] = {
"EV_SV_RECONNECT",
"EV_SV_KEEPALIVE",
"EV_PREFSCHANGED",
"EV_CH_RETRYJOIN",
"EV_TICK",
"EV_DIEDIEDIE"
};
#endif
CEventManager::CEventManager(void)
{
}
CEventManager::~CEventManager(void)
{
// wtf? we have listeners left...
ATLASSERT(m_ListenerList.GetSize() == 0);
// Delete remaining events
DeleteEvents(NULL);
}
void CEventManager::AddListener(CListener *pListener)
{
m_ListenerList.Add(pListener);
}
void CEventManager::RemoveListener(CListener *pListener)
{
// remove the listener
m_ListenerList.Remove(pListener);
// remove all outstanding events from this source.
DeleteEvents(pListener);
}
/** Delete events from the event mananger's queue
*
* Specify just the listener (pFrom) to remove all events
* from the queue from that source, or specify
* both to have all events from the source matching the EventID
* removed from the queue
* Note: NULL Listeners's *ARE* valid. an event can be created by
* somethinbg that's not a listener.
*/
BOOL CEventManager::DeleteEvents(CListener *pFrom, int EventID, void *pData)
{
CNode *pNode,*pTempNode;
EventQueueItem_t *pEI;
int EventQueueItemNum;
BOOL Found = FALSE;
for (EventQueueItemNum = 0,pNode = m_EventList.GetFirst(); pNode != NULL && pNode->m_Next != NULL; pNode = pNode->m_Next,EventQueueItemNum ++)
{
pEI = (EventQueueItem_t *)pNode->m_Data;
if (pEI->pFrom == pFrom && (pEI->EventID == EventID || EventID == -1) && (pEI->pData == pData || pData == NULL) && pEI->Processing == FALSE)
{
#ifdef DEBUG
if (EventID == -1)
sys_Printf(BIC_INFO,"Removing unprocessed event, Event Queue Number: %d, ID: %s (%d)\n",EventQueueItemNum,pEI->EventID < EV_LAST ? g_EventIDNames[pEI->EventID] : "CUSTOMID",pEI->EventID);
else
sys_Printf(BIC_INFO,"Removing event, Event Queue Number: %d, ID: %s (%d)\n",EventQueueItemNum,pEI->EventID < EV_LAST ? g_EventIDNames[pEI->EventID] : "CUSTOMID",pEI->EventID);
#endif
pTempNode = pNode->m_Next;
free(pEI);
pNode->Remove();
delete pNode;
pNode = pTempNode;
Found = TRUE;
}
}
return Found;
}
BOOL CEventManager::QueueTimedEvent(CListener *pFrom, BOOL Broadcast, int EventID,int Seconds, BOOL Repeat, BOOL SkipMissed, void *pData)
{
// can't create non-broadcast events without a listener
if (!pFrom && !Broadcast)
return FALSE;
CNode *pNode = new CNode;
if (!pNode)
return FALSE;
EventQueueItem_t *pNewEI = (EventQueueItem_t *)malloc(sizeof(EventQueueItem_t));
if (!pNewEI)
{
delete pNode;
return FALSE;
}
// set who it's from
pNewEI->pFrom = pFrom;
// set the timed stuff and flags
pNewEI->Flags = ET_TIMED;
time(&pNewEI->StartTime); // store NOW.
pNewEI->Seconds = Seconds;
if (Repeat)
pNewEI->Flags |= ET_REPEAT;
if (Broadcast)
pNewEI->Flags |= ET_BROADCAST;
if (SkipMissed)
pNewEI->Flags |= ET_SKIPMISSED;
// set the event data
pNewEI->EventID = EventID;
pNewEI->pData = pData;
// set the status
pNewEI->Processing = FALSE;
// add to queue
pNode->m_Data = pNewEI;
m_EventList.AddTail(pNode);
return TRUE;
}
BOOL CEventManager::QueueEvent(CListener *pFrom, BOOL Broadcast, int EventID, void *pData)
{
// can't create non-broadcast events without a listener
if (!pFrom && !Broadcast)
return FALSE;
CNode *pNode = new CNode;
if (!pNode)
return FALSE;
EventQueueItem_t *pNewEI = (EventQueueItem_t *)malloc(sizeof(EventQueueItem_t));
if (!pNewEI)
{
delete pNode;
return FALSE;
}
// set who it's from
pNewEI->pFrom = pFrom;
// set flags
if (Broadcast)
pNewEI->Flags |= ET_BROADCAST;
// set the event data
pNewEI->EventID = EventID;
pNewEI->pData = pData;
// set the status
pNewEI->Processing = FALSE;
// add to queue
pNode->m_Data = pNewEI;
m_EventList.AddTail(pNode);
return TRUE;
}
/** Create an event and fire it, without adding to the queue.
*
*/
BOOL CEventManager::DoEvent(CListener *pFrom, BOOL Broadcast, int EventID, void *pData)
{
// can't create non-broadcast events without a listener
if (!pFrom && !Broadcast)
return FALSE;
EventQueueItem_t *pNewEI = (EventQueueItem_t *)malloc(sizeof(EventQueueItem_t));
if (!pNewEI)
return FALSE;
// set who it's from
pNewEI->pFrom = pFrom;
// set flags
if (Broadcast)
pNewEI->Flags |= ET_BROADCAST;
// set the event data
pNewEI->EventID = EventID;
pNewEI->pData = pData;
// set the status
pNewEI->Processing = FALSE;
FireEvent(pNewEI);
free(pNewEI);
return TRUE;
}
void CEventManager::FireEvent(EventQueueItem_t *pEI)
{
CListener *pListener;
if (pEI->Flags & ET_BROADCAST)
{
int i;
CSimpleArray<CListener *> FireOrder;
// firing an event can cause a listener to be removed from the list
// so we make a copy of the list, and then fire each one.
for (i = 0 ; i < m_ListenerList.GetSize() ; i++)
FireOrder.Add(m_ListenerList[i]);
for (i = 0 ; i < FireOrder.GetSize() ; i++)
{
pListener = FireOrder[i];
// only fire the event if it's still in the list! (if it's not then pListener is invalid..)
if (m_ListenerList.Find(pListener) >= 0)
pListener->OnEvent(pEI->EventID,pEI->pData);
}
}
else
{
pEI->pFrom->OnEvent(pEI->EventID,pEI->pData);
}
}
void CEventManager::ProcessEvents( void )
{
CNode *pNode,*pTempNode;
BOOL remove;
EventQueueItem_t *pEI;
double diff;
time_t now;
time(&now);
int EventQueueItemNum;
//#ifdef EVENTMANAGER_DEBUG
#ifdef DEBUG
if (g_DebugFlags & DBGFLG_EVENTDUMP1 || g_DebugFlags & DBGFLG_EVENTDUMPALL)
{
// dump event queue
tm *t;
for (EventQueueItemNum = 0,pNode = m_EventList.GetFirst(); pNode->m_Next != NULL; pNode = pNode->m_Next,EventQueueItemNum ++)
{
pEI = (EventQueueItem_t *)pNode->m_Data;
t = localtime(&pEI->StartTime);
sys_Printf(BIC_INFO,"Event Item %d: %s %s (%d) %s-%d (%s) %s %s\n",
EventQueueItemNum,
pEI->Processing ? "Processing" : "Ready",
pEI->EventID < EV_LAST ? g_EventIDNames[pEI->EventID] : "CUSTOMID",pEI->EventID,
pEI->Flags & ET_TIMED ? "Timed" : "Not Timed",
pEI->Flags & ET_TIMED ? pEI->Seconds : 0,
pEI->Flags & ET_TIMED ? stripcrlf(asctime(t)) : "N/A",
pEI->Flags & ET_REPEAT ? "Repeat" : "No Repeat",
pEI->Flags & ET_BROADCAST ? "Broadcast" : "Private");
if (g_DebugFlags & DBGFLG_EVENTDUMP1) // just dump the first event (usually the EV_TICK one)
break;
}
}
#endif
for (EventQueueItemNum = 0 , pNode = m_EventList.GetFirst();
pNode != NULL && pNode->m_Next != NULL;
pNode = pNode->m_Next,EventQueueItemNum ++)
{
pEI = (EventQueueItem_t *)pNode->m_Data;
// don't keep processing the same event
// some events could trigger other events...
// if we didn't do this we'd end up in an endless loop
if (pEI->Processing)
continue;
// set our flag.
pEI->Processing = TRUE;
// we remove all events after processing, unless they're repat timed events.
remove = TRUE;
if (pEI->Flags & ET_TIMED)
{
// time event due yet ?
diff = difftime(now,pEI->StartTime);
#ifdef DEBUG
// if it's late, tell us (but ignore short timed events)
if (pEI->Seconds > 2 && diff > pEI->Seconds)
{
sys_Printf(BIC_WARNING,"Event Queue Item %d is %d seconds late\n",EventQueueItemNum,(int)(diff - pEI->Seconds));
}
#endif
if (diff >= pEI->Seconds)
{
// yes!
// repeat timer ?
if (pEI->Flags & ET_REPEAT)
{
// add the seconds to the start time
// so we repeat exactly x seconds after the start time
// if we used "now" we'd introduce a bit of fluctuation
// and could skep events if we're running late
// as calls to ProcessEvents() are not evenly spaced in time.
pEI->StartTime += pEI->Seconds;
double diff2 = difftime(now,pEI->StartTime); //Note: process new start time...
if (diff2 > pEI->Seconds)
{
// if an event was queued for repeat every 5 seconds at
// 00:00:00 and then 22 seconds passed before ProcessEvents()
// was called again (stalled process or something...)
// we'll print out how many times it should have run
// in this case 4 times.
// note that all the four events are still triggered
// unless the ET_SKIPMISSED flag is set
// but the timing of them will depend on the frequency of
// calls to ProcessEvents() (normally every 1 second)
#ifdef DEBUG
sys_Printf(BIC_WARNING,"Event Queue Item %d has overrun %d times\n",EventQueueItemNum,(int)(diff2 / pEI->Seconds));
#endif
if (pEI->Flags & ET_SKIPMISSED)
{
// skip missed events if we're supposed to.
#ifdef DEBUG
sys_Printf(BIC_WARNING,"Event Queue Item %d - Skipping missed events\n",EventQueueItemNum);
#endif
do
{
pEI->StartTime += pEI->Seconds;
diff2 = difftime(now,pEI->StartTime);
} while(diff2 > pEI->Seconds);
}
}
remove = FALSE; // don't free it!
}
// fire the event
FireEvent(pEI);
}
else
{
// not processed it yet.. need to wait more
remove = FALSE;
}
}
else
{
// not a timed event, so fire it.
FireEvent(pEI);
}
if (remove)
{
// remove from list and reset loop pointer
pTempNode = pNode->m_Next;
free(pEI);
pNode->Remove();
delete pNode;
pNode = pTempNode;
}
else
{
// Finished processing this event now.
pEI->Processing = FALSE;
}
ATLASSERT(pNode);
}
}
| [
"hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0"
]
| [
[
[
1,
390
]
]
]
|
d40592aa7e47c910d7a9d02c08cdc6ba0055fcb9 | 4497c10f3b01b7ff259f3eb45d0c094c81337db6 | /VideoMontage/SobelImageQuality.h | 5abbdd9bbc2c95562bf165791fda46e740b0ed1e | []
| no_license | liuguoyou/retarget-toolkit | ebda70ad13ab03a003b52bddce0313f0feb4b0d6 | d2d94653b66ea3d4fa4861e1bd8313b93cf4877a | refs/heads/master | 2020-12-28T21:39:38.350998 | 2010-12-23T16:16:59 | 2010-12-23T16:16:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 278 | h | #pragma once
#include "ImageQuality.h"
// Get Image Quality by taking max value in Sobel saliency map
class SobelImageQuality : public ImageQuality
{
public:
SobelImageQuality(void);
~SobelImageQuality(void);
virtual double GetImageQuality(IplImage* image);
};
| [
"kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a"
]
| [
[
[
1,
12
]
]
]
|
aab5dd048f9ca2cb759f84e05a062b7e77dd936c | 565d432f8223100873944cfa22b9d9b2f14575f1 | /AutoLogin/CEGUI_Call.h | e3b50c26aa81de8fed6021829371872092247396 | []
| no_license | glencui2015/tlautologin | ce029c688e0414497e91115a2ee19e7abcac56d2 | 6e825807e2523bf4e020d91f92d86ce194747d0d | refs/heads/master | 2021-01-10T10:50:34.139524 | 2010-12-17T17:43:33 | 2010-12-17T17:43:33 | 50,753,256 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,376 | h | #include <windows.h>
#include <math.h>
#include <stdio.h>
#include <string>
#include <vector>
using namespace std;
vector<int> CEGUI_WIN;
int BottonCallAddress=0;
string str_win;
int GetCEGUI(){
return (int)GetModuleHandle("CEGUIBase.dll");//获取模块基址
}
int CEGUIBase_Handle=0;
int myTestValue(int address){
int a=0;
if(IsBadReadPtr((void*)(address),4)==0){
a=1;
}else{
a=0;
}
return a;
}
int getwin(int sheet){//递归遍历所有"可视"窗口
//先看看有当前的窗口所拥有的子窗口,
int local_sheet=sheet;
int child=*(int*)(local_sheet+0x2c); //数组的开始地址
int end=*(int*)(local_sheet+0x30); //数组的结束地址
if(child==end){
return 0;
}
//获取数组中的窗口对象,
for(int i=child;i!=end;i+=4){
int winobj=*(int*)i;
if(winobj==0){
continue;
}
char isVisible=*(char*)(winobj+0x129);
if(isVisible==0){//看看窗口是否可见,不可见就continue
continue;
}else{//递归看看还有没子窗口
CEGUI_WIN.push_back(winobj);
int win2=getwin(winobj);//有子窗口就返回。
// if(win2){
// return win2;
// }
}
}
return 0;
}
int SearchAllCEGUI_Window(){//获取所有CEGUI可视窗口
if(CEGUIBase_Handle==0){
CEGUIBase_Handle=GetCEGUI();//看看CEGUIBase.dll加载了进内存没。
}
if(CEGUIBase_Handle==0){//看看CEGUIBase.dll加载了进内存没。
return 0;
}
typedef int (*ADDPROC)();
ADDPROC getSingleton = (ADDPROC)(0x492e0+CEGUIBase_Handle);//这个每次更新都要更新
//mov eax,dword ptr ds:[CEGUI::Singleton<CEGUI::System>::m>
int WinBase=getSingleton();//获取窗口基类。
if(WinBase==0){
return 0;
}
char aaa[30]={0};
//获取可以活动的窗口
int d_activeSheet=*(int*)(WinBase+0x2c);
/////接下来要递归遍历所有"可视"窗口了。
if(myTestValue(d_activeSheet)==0){
return 0;
}
getwin(d_activeSheet);//递归遍历窗口,保存在CEGUI_WIN这个vector中
/* for(vector<int>::iterator itr = CEGUI_WIN.begin();itr!=CEGUI_WIN.end();++itr){
memset(aaa,0,sizeof(aaa));
}*/
return 1;
}
/*
///////////
//使用窗口按钮。
char *str_fun_next="HuoDongRiCheng_next_click();";
char *str_fun="SelectServer_SelectOk();";
//char *str_fun="Pet_Feed_Clicked();";
void win_next_botton(){
if(BottonCallAddress==0){
int UI_CEGUI_Base=(int)GetModuleHandle("UI_CEGUI.dll");
BottonCallAddress=UI_CEGUI_Base+0x27210;
}
// MessageBox(0,"","",0);
for(vector<int>::iterator itr = CEGUI_WIN.begin();itr!=CEGUI_WIN.end();++itr){
if(*itr==0){
continue;
}
int a=*(int*)(*itr+0xf0);
if(a==0){
continue;
}
int xml_str=*(int*)(a+0x28);
if(myTestValue(xml_str)==0){
continue;
}
if(strcmp((char*)xml_str,"Huodongricheng/Huodongricheng.layout.xml")==0){
__asm{
mov eax,itr
mov eax,[eax]
push eax
mov eax,str_fun_next
push eax
mov esi,a
mov ecx,esi
call BottonCallAddress
}
CEGUI_WIN.clear();
return ;
}
}
CEGUI_WIN.clear();
}
int win_enter_botton(){
// MessageBox(0,"","",0);
__asm{
mov eax,eax
}
if(BottonCallAddress==0){
int UI_CEGUI_Base=(int)GetModuleHandle("UI_CEGUI.dll");
BottonCallAddress=UI_CEGUI_Base+0x27790;
}
for(vector<int>::iterator itr = CEGUI_WIN.begin();itr!=CEGUI_WIN.end();++itr){
if(*itr==0){
continue;
}
int a=*(int*)(*itr+0xf0);
if(a==0){
continue;
}
int xml_str=*(int*)(a+0x28);
if(myTestValue(xml_str)==0){
continue;
}//0BDF7B08 0BDF77F0 ASCII "SelectServer/SelectServer.layout.xml"
if(strcmp((char*)xml_str,"SelectServer/SelectServer.layout.xml")==0){
int btn_win=*itr;
__asm{
mov eax,btn_win
push eax
mov eax,str_fun
push eax
mov esi,a
mov ecx,esi
call BottonCallAddress
}
CEGUI_WIN.clear();
return 1;
}
}
CEGUI_WIN.clear();
return 0;
}
*/
char *getWindowString(int winObj){//获取窗口对象的另外一个字符串.
char *str=0;
__asm{
mov edi,winObj
lea ecx,dword ptr ds:[edi+0x20C]
cmp dword ptr ds:[ecx+0x18],0x10
jb short hi
mov eax,dword ptr ds:[ecx+0x4]
jmp hi2
hi: lea eax,dword ptr ds:[ecx+0x4]
hi2: mov str,eax
}
return str;
}
int UseButton(char *functionString,char *functionString_2){//使用按钮。无论成功与否都会清空获取到的窗口
if(BottonCallAddress==0){
int UI_CEGUI_Base=(int)GetModuleHandle("UI_CEGUI.dll");
BottonCallAddress=UI_CEGUI_Base+0x36d10;//这个偏移值游戏每次更新也要跟着要更新
}
for(vector<int>::iterator itr = CEGUI_WIN.begin();itr!=CEGUI_WIN.end();++itr){//遍历之前获取的所有窗口。
if(*itr==0){
continue;
}
int a=*(int*)(*itr+0xf0);
if(a==0){
continue;
}
int xml_str=*(int*)(a+0x28);
if(myTestValue(xml_str)==0){
continue;
}
if(strcmp(getWindowString(*itr),functionString_2)==0){//自己输入的字符串和获取到的窗口的字符串比较是否相等,相等就调用按钮call
int btn_win=*itr;
__asm{
mov eax,btn_win
push eax
mov eax,functionString
push eax
mov esi,a
mov ecx,esi
call BottonCallAddress
}
CEGUI_WIN.clear();
return 1;
}
}
CEGUI_WIN.clear();
return 0;
} | [
"woaini4t@84d92313-99f8-b76f-20ef-0d116c1dc3bd"
]
| [
[
[
1,
235
]
]
]
|
475b1d0055fd061ded029ad48e88d150154a0264 | 2b80036db6f86012afcc7bc55431355fc3234058 | /src/win32cpp/pch.cpp | 1fae8bf9a6959a16b45765755e819ddd9d621372 | [
"BSD-3-Clause"
]
| permissive | leezhongshan/musikcube | d1e09cf263854bb16acbde707cb6c18b09a0189f | e7ca6a5515a5f5e8e499bbdd158e5cb406fda948 | refs/heads/master | 2021-01-15T11:45:29.512171 | 2011-02-25T14:09:21 | 2011-02-25T14:09:21 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,909 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright © 2007, Casey Langen
//
// Sources and Binaries of: win32cpp
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include "pch.hpp"
| [
"onnerby@6a861d04-ae47-0410-a6da-2d49beace72e"
]
| [
[
[
1,
39
]
]
]
|
dbf2775ce8c631465bf66bd736c64bfb24c7d1e1 | 6f7850c90ed97967998033df615d06eacfabd5fa | /pinger/eventer.h | 44b48adb80e9db9496cd8e1e64b888871e994b5f | []
| no_license | vi-k/whoisalive | 1145b0af6a2a18e951533b00a2103b000abd570a | ae86c1982c1e97eeebc50ba54bf53b9b694078b6 | refs/heads/master | 2021-01-10T02:00:28.585126 | 2010-08-23T01:58:45 | 2010-08-23T01:58:45 | 44,526,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,662 | h | #ifndef EVENTER_H
#define EVENTER_H
#include "connection.h"
#include "../common/my_thread.h"
#include "../common/my_inet.h"
#include <list>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/function.hpp>
namespace eventer {
/* Класс - событие */
struct event
{
ip::address_v4 address; /* С какого адреса событие */
std::wstring message; /* Что за событие */
event(ip::address_v4 who, const std::wstring &what)
: address(who), message(what) {}
};
/* Класс - удалённый обработчик событий */
struct handler
{
ip::address_v4 address;
acceptor::connection *connection;
handler(acceptor::connection *con, ip::address_v4 event_address)
: connection(con)
, address(event_address)
{
}
~handler()
{
delete connection;
}
};
class server
{
private:
boost::ptr_list<handler> handlers_;
std::list<event> events_;
recursive_mutex handlers_mutex_; /* Блокировка списка обработчиков */
recursive_mutex events_mutex_; /* Блокировка списка событий */
condition_variable cond_;
public:
server();
~server()
{
}
void run();
void start();
unique_lock<recursive_mutex> get_lock()
{ return unique_lock<recursive_mutex>(handlers_mutex_); }
void add_handler(acceptor::connection *connection,
ip::address_v4 for_whom);
void add_event(ip::address_v4 who, const std::wstring &what);
static bool handler_failed(const handler &_handler)
{ return !_handler.connection->socket().is_open(); }
};
}
#endif
| [
"victor dunaev ([email protected])",
"[email protected]"
]
| [
[
[
1,
47
],
[
50,
60
],
[
63,
75
]
],
[
[
48,
49
],
[
61,
62
]
]
]
|
4f0f2a9223925a88839d6818306bf2e6656658b1 | dadf8e6f3c1adef539a5ad409ce09726886182a7 | /airplay/h/toeSimpleMenuItem.h | 8acff5d579e584cf5f613878c723d4b0cdda7e04 | []
| no_license | sarthakpandit/toe | 63f59ea09f2c1454c1270d55b3b4534feedc7ae3 | 196aa1e71e9f22f2ecfded1c3da141e7a75b5c2b | refs/heads/master | 2021-01-10T04:04:45.575806 | 2011-06-09T12:56:05 | 2011-06-09T12:56:05 | 53,861,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,313 | h | #pragma once
#include <IwResManager.h>
#include <IwManagedList.h>
#include <toeInput.h>
#include <toeFreeTypeFont.h>
#include <toeSimpleMenuStyle.h>
#include <toeSimpleMenuStyleSheet.h>
#include <toeIntrusiveList.h>
#include <toeScriptingSubsystem.h>
namespace TinyOpenEngine
{
class CtoeSimpleMenuItem;
class CtoeSimpleMenu;
class ItoeSimpleMenuVisitor
{
public:
virtual bool Visited(CtoeSimpleMenuItem*)=0;
};
struct toeSimpleMenuItemContext
{
CtoeSimpleMenuStyleSettings* parentStyle;
CtoeSimpleMenuStyleSheet* styleSheet;
CIwSVec2 viewportPos;
CIwSVec2 viewportSize;
CIwMat transformation;
toeSimpleMenuItemContext():parentStyle(0),styleSheet(0),transformation(CIwMat::g_Identity){};
};
class CtoeSimpleMenuRoot;
class CtoeSimpleMenuLazyEvent: public TtoeIntrusiveListItem<CtoeSimpleMenuLazyEvent,CtoeSimpleMenuItem>,public TtoeIntrusiveListItem<CtoeSimpleMenuLazyEvent>
{
public:
virtual ~CtoeSimpleMenuLazyEvent(){}
virtual void Send(){}
};
class CtoeSimpleMenuItem : public CIwManaged
{
protected:
CIwManagedList childItems;
CIwSVec2 origin;
CIwSVec2 size;
uint32 styleClass;
uint32 state;
uint32 idHash;
//CIwSVec4 margin;
//CIwSVec4 padding;
CtoeSimpleMenuRoot*root;
CtoeSimpleMenuItem*parent;
CtoeSimpleMenuStyle style;
CtoeSimpleMenuStyleSettings combinedStyle;
TtoeIntrusiveList<CtoeSimpleMenuLazyEvent,CtoeSimpleMenuItem> lazyEvents;
public:
//Declare managed class
IW_MANAGED_DECLARE(CtoeSimpleMenuItem);
//Get scriptable class declaration
static CtoeScriptableClassDeclaration* GetClassDescription();
//Get scriptable class declaration
virtual CtoeScriptableClassDeclaration* GetInstanceClassDescription() {return GetClassDescription(); };
//Get tree element name hash
virtual uint32 GetElementNameHash();
//Constructor
CtoeSimpleMenuItem();
//Desctructor
virtual ~CtoeSimpleMenuItem();
//Reads/writes a binary file using @a IwSerialise interface.
virtual void Serialise ();
//Evaluates size of item and prepares all nessesary things to render it
virtual void Prepare(toeSimpleMenuItemContext* renderContext,int16 width);
//Render image on the screen surface
virtual void Render(toeSimpleMenuItemContext* renderContext);
bool IsVisible(toeSimpleMenuItemContext* renderContext);
const CIwSVec2& GetOrigin() const {return origin;}
//Gets size of the item. It's only valid after Prepare method been executed
const CIwSVec2& GetSize() const {return size;}
virtual void SetOrigin(const CIwSVec2& v) { if (origin!=v) { origin=v;RearrangeChildItems(); }}
//Method walks through child items and collect active ones into plain list
//virtual void CollectActiveItems(CIwArray<CtoeSimpleMenuItem*>& collection);
virtual void RearrangeChildItems();
inline int16 GetMarginLeft()const {return combinedStyle.GetMarginLeft(1);}
inline int16 GetMarginTop()const {return combinedStyle.GetMarginTop(1);}
inline int16 GetMarginRight()const {return combinedStyle.GetMarginRight(1);}
inline int16 GetMarginBottom()const {return combinedStyle.GetMarginBottom(1);}
inline int16 GetBorderLeft()const {return combinedStyle.GetBorderLeft(1);}
inline int16 GetBorderTop()const {return combinedStyle.GetBorderTop(1);}
inline int16 GetBorderRight()const {return combinedStyle.GetBorderRight(1);}
inline int16 GetBorderBottom()const {return combinedStyle.GetBorderBottom(1);}
inline int16 GetPaddingLeft()const {return combinedStyle.GetPaddingLeft(1);}
inline int16 GetPaddingTop()const {return combinedStyle.GetPaddingTop(1);}
inline int16 GetPaddingRight()const {return combinedStyle.GetPaddingRight(1);}
inline int16 GetPaddingBottom()const {return combinedStyle.GetPaddingBottom(1);}
inline int16 GetContentOffsetLeft()const {return GetMarginLeft()+GetPaddingLeft()+GetBorderLeft();}
inline int16 GetContentOffsetRight()const {return GetMarginRight()+GetPaddingRight()+GetBorderRight();}
inline int16 GetContentOffsetTop()const {return GetMarginTop()+GetPaddingTop()+GetBorderTop();}
inline int16 GetContentOffsetBottom()const {return GetMarginBottom()+GetPaddingBottom()+GetBorderBottom();}
CtoeSimpleMenu*GetMenuContainer()const;
inline CtoeSimpleMenuRoot*GetRoot()const{return root;}
inline CtoeSimpleMenuItem*GetParent()const{return parent;}
inline CtoeSimpleMenuItem*GetChildAt(int i)const{return static_cast<CtoeSimpleMenuItem*>(childItems[i]);}
inline int GetChildItemsCount()const{return (int)childItems.GetSize();}
void CombineStyle(toeSimpleMenuItemContext* renderContext);
virtual void InheritStyle(CtoeSimpleMenuStyleSettings* parentSettings);
virtual void ApplyStyleSheet(CtoeSimpleMenuStyleSheet* styleSheet);
virtual void ApplyStyle(CtoeSimpleMenuStyle* style);
virtual uint32 GetElementClassHash();
virtual uint32 GetElementStateHash();
uint32 GetElementIdHash() { return idHash; }
//Finds an active item in children
virtual CtoeSimpleMenuItem* FindActiveItemAt(const CIwVec2 & item);
virtual void SetFocus(bool f);
virtual void Touch(TouchContext* touchContext);
virtual void TouchReleased(TouchContext* touchContext);
virtual void TouchMotion(TouchContext* touchContext);
virtual bool IsActive() const {return false;}
virtual bool VisitForward(ItoeSimpleMenuVisitor* visitor);
virtual bool VisitBackward(ItoeSimpleMenuVisitor* visitor);
void InitTree(CtoeSimpleMenuRoot*,CtoeSimpleMenuItem*);
protected:
void RenderBackgroud(toeSimpleMenuItemContext* renderContext);
void RenderShadow(toeSimpleMenuItemContext* renderContext);
void RenderBorder(toeSimpleMenuItemContext* renderContext);
void SendLazyEvent(CtoeSimpleMenuLazyEvent*);
public:
#ifdef IW_BUILD_RESOURCES
//Parses from text file: start block.
virtual void ParseOpen(CIwTextParserITX* pParser);
//Parses from text file: parses attribute/value pair.
virtual bool ParseAttribute(CIwTextParserITX* pParser, const char* pAttrName);
//Extends CIwParseable interface with this extra function: called on any "parent" object, if the "child" has not implemented ParseClose.
virtual void ParseCloseChild(CIwTextParserITX* pParser, CIwManaged* pChild);
#endif
};
} | [
"[email protected]"
]
| [
[
[
1,
156
]
]
]
|
246186ce7140975ddb2bf57ad1f6fddcbede630a | cd1b72e71f52456e28716c426ec281c8b60b43e5 | / cs340-pacman/state.h | 9315294f5289f1465c1c070d24edb168adf96526 | []
| no_license | ShawnHuang/cs340-pacman | 137d12510a2747fe8ea1ce905b3332ba168ea992 | 9979f59fd34c90550fe5375573efe40c80f60381 | refs/heads/master | 2020-06-04T13:04:47.234599 | 2009-12-05T15:01:25 | 2009-12-05T15:01:25 | 32,971,724 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,449 | h | /*****************************************************
File Name: state.h
Description: The state class is responsible for setting transitions, specifying actions, and pointing
to the right function that represents the action.
Created by: Riddhi Kapasi
Modified by :
******************************************************/
#ifndef STATE_H
#define STATE_H
#include <QString>
#include <QMap>
#include <QSet>
//Creating a class state which will contain the name, properties and event mapping of a particular state.
//This is a generic class to be used with every entity in the game.
class State
{
private:
QString name;//name of a state
QSet<QString> property; //properties of a entity in that particular state
QMap<QString, QString> eventmap;//event and their corresponding next states
int index;
public:
State();
State(QString);
State(QString, int);
~State();
QString getName(); //retriving the name of the state
void setProperty(QString); //setting property for a particular state
bool hasProperty(QString); //checking if a particular state has this property
void addEventAndNextState(QString, QString); //adding event and nextstate to map
QString getNextStateForEvent(QString); //getting next state for the event passed
int getIndex();
};
#endif // STATE_H
| [
"riddhi.kapasi@c94e964c-9837-11de-bb56-53d3cd047523",
"usha.sanaga@c94e964c-9837-11de-bb56-53d3cd047523"
]
| [
[
[
1,
12
],
[
14,
25
],
[
27,
30
],
[
32,
37
],
[
39,
41
]
],
[
[
13,
13
],
[
26,
26
],
[
31,
31
],
[
38,
38
]
]
]
|
1d8d8aac301322c0f697074cbfe05ac2ae07678d | 7f6fe18cf018aafec8fa737dfe363d5d5a283805 | /ntk/interface/terminalview.h | a9e7fa25c00f1a5f7777044640d3b4eae290ed92 | []
| no_license | snori/ntk | 4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba | 86d1a32c4ad831e791ca29f5e7f9e055334e8fe7 | refs/heads/master | 2020-05-18T05:28:49.149912 | 2009-08-04T16:47:12 | 2009-08-04T16:47:12 | 268,861 | 2 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 4,017 | h | /******************************************************************************
The NTK Library
Copyright (C) 1998-2003 Noritaka Suzuki
$Id: terminalview.h,v 1.4 2003/11/11 12:07:07 nsuzuki Exp $
******************************************************************************/
#pragma once
#ifndef __NTK_INTERFACE_TERMINALVIEW_H__
#define __NTK_INTERFACE_TERMINALVIEW_H__
#include <vector>
#ifndef __NTK_DEFS_H__
#include <ntk/defs.h>
#endif
#ifndef __NTK_INTERFACE_CONTROL_H__
#include <ntk/interface/control.h>
#endif
#ifndef __NTK_INTERFACE_DC_H__
#include <ntk/interface/dc.h>
#endif
#ifndef __NTK_KERNEL_THREAD_H__
#include <ntk/kernel/thread.h>
#endif
#ifndef __NTK_KERNEL_LOCKER_H__
#include <ntk/kernel/locker.h>
#endif
namespace ntk {
class TerminalView : public Control {
public:
//
// constants
//
enum {
// CHARA_FLAG = Control::FLAG_LAST << 1,
FLAG_LAST = Control::FLAG_LAST << 2,
};
enum {
DEFAULT_RESIZING_MODE = FOLLOW_LEFT | FOLLOW_TOP,
DEFAULT_FLAGS = NAVIGABLE /* | CHARA_FLAG*/,
};
//
// methods
//
NtkExport TerminalView(
const Rect& frame,
const String& name,
uint mode = DEFAULT_RESIZING_MODE,
uint flags = DEFAULT_FLAGS,
const RGBColor& color = ntk::view_color());
NtkExport virtual ~TerminalView();
NtkExport virtual void execute_command_line(const String& command_line);
void print(const String& str) {print(str.c_str());}
NtkExport virtual void print(const char_t* str);
NtkExport virtual void put_string(const char_t* buf, int size = -1);// -1: '\0'で終わる文字列
NtkExport virtual void put_char(char_t ch);
NtkExport virtual void back_char();
NtkExport virtual void del_char();
NtkExport virtual void print_prompt();
//
// accessors and manipulators
//
NtkExport virtual uint num_lines() const;
NtkExport virtual uint max_line() const;
NtkExport virtual void set_max_line(uint num = 0);// 0: 最大値を設定しない
NtkExport virtual const RGBColor& text_color() const;
NtkExport virtual void set_text_color(const RGBColor& color);
NtkExport virtual const RGBColor& cursor_color() const;
NtkExport virtual void set_cursor_color(const RGBColor& color);
NtkExport virtual const RGBColor& view_color() const;
NtkExport virtual void set_view_color(const RGBColor& color);
//
// message handlers
//
NtkExport virtual void draw(PaintDC& dc);
NtkExport virtual void draw_content(DC& dc);
NtkExport virtual void focus_changed(bool state);
NtkExport virtual void char_received(uint char_code, uint repeat);
NtkExport virtual void key_down(uint key_code, uint repeat);
NtkExport virtual void attached_to_window();
NtkExport virtual void message_received(const Message& message);
protected:
//
// functions
//
coord line_height(DC& dc) const;
private:
//
// types
//
typedef std::vector<char_t> Buffer;
//
// data
//
Buffer m_buffer;
uint m_cursor;
uint m_num_lines, m_max_line;
bigtime_t m_flash_interval, m_flash_timer;
Locker m_flash_timer_locker, m_paint_locker;
bool m_thread_stop_flag;
Thread* m_flash_cursor_thread;
Thread* m_process_thread;
String m_tmp_command_line;
bool m_escape_sequence;
// drawing states
RGBColor m_text_color, m_cursor_color, m_background_color;
//
// functions
//
void reset_flash_timer_(bigtime_t new_time = 0);
void clean_up_process_();
void line_overflow_();
static uint flash_cursor_proc_(void*);
static uint terminal_proc_(void*);
static uint process_proc_(void*);
};// class TerminalView
#ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME
typedef TerminalView terminal_view_t;
#endif
} namespace Ntk = ntk;
#ifdef NTK_TYPEDEF_TYPES_AS_GLOBAL_TYPE
#ifdef NTK_TYPEDEF_GLOBAL_NCLASS
typedef ntk::TerminalView NTerminalView;
#endif
#ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME
typedef ntk::TerminalView ntk_terminal_view;
#endif
#endif
#endif//EOH
| [
"[email protected]"
]
| [
[
[
1,
170
]
]
]
|
de4c2502aa3c4edf1730a73ad8e2c27577c8c80a | b6bad03a59ec436b60c30fc793bdcf687a21cf31 | /som2416/wince5/atapiRomipm.h | 1b6bdb70fc836eb341ae2cc6e8e71d2bf13fd2ba | []
| 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 | 592 | h | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
//
#pragma once
class CRomiDiskPower : public CDiskPower
{
public:
// CRomiDiskPower(void);
protected:
virtual BOOL CRomiDiskPower::RequestDevice(void);
};
| [
"[email protected]"
]
| [
[
[
1,
23
]
]
]
|
a7e9feb9737bec4efafa9509872d2d9c9d08606b | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXColorPickerButton.h | 1873325c7fe4f58901c2c5ec9e604319ddd43c34 | []
| no_license | weimingtom/sls | 7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8 | d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd | refs/heads/master | 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 8,173 | h | // ==========================================================================
// Class Specification : COXColorPickerButton
// ==========================================================================
// Version: 9.3
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at [email protected], or by calling 416-849-8900.
// //////////////////////////////////////////////////////////////////////////
// Properties:
// NO Abstract class (does not have any objects)
// YES Derived from COXBitmapButton
// YES Is a Cwnd.
// YES Two stage creation (constructor & Create())
// YES Has a message map
// NO Needs a resource (template)
// NO Persistent objects (saveable on disk)
// NO Uses exceptions
// //////////////////////////////////////////////////////////////////////////
// Desciption :
/*
COXColorPickerButton is derived from COXBitmapButton (with DROPDOWN style predefined)
and uses COXColorPickerCtrl to display Color Picker popup bar.
You can set any color to COXColorPickerButton using next function:
void SetColor(COLORREF clr, BOOL bRedraw=TRUE);
// --- Effect : associate button with color
and this color can be retrieved using:
COLORREF GetColor();
// --- Returns: color associated with button
To display associated color we draw color band in the bottom of button. By default
the height of that band is 5 pixel (if neither image nor text is associated with the
button then the color band takes all available space). You can set/get the color band
height using next functions:
void SetColorBandHeight(UINT nColorBandHeight);
// --- Effect : set the height of color band. By default it is set to 5
UINT GetColorBandHeight();
// --- Returns: the height of color band
COXColorPickerCtrl control associated with COXColorPickerButton can be retrieved using:
COXColorPickerCtrl* GetColorPickerCtrl();
// --- Returns: pointer to COXColorPickerCtrl object associated with button
Also we provide some helper functions to set/get default color of associated
Color Picker control:
void SetDefaultColor(COLORREF clrDefault)
// --- Effect : set default color of associated COXColorPickerCtrl object
COLORREF GetDefaultColor();
// --- Returns: default color of associated COXColorPickerCtrl object
Use COXBitmapButton and COXColorPickerCtrl functions to customize COXColorPickerButton.
In the ColorPickerButton sample which resides in .\Samples\gui\ColorPickerButton
subdirectory of your Ultimate Toolbox directory you will find an example of customizing
COXColorPickerButton object to full extent.
*/
// Prerequisites (necessary conditions):
/////////////////////////////////////////////////////////////////////////////
#ifndef __OXCOLORPICKERBUTTON_H__
#define __OXCOLORPICKERBUTTON_H__
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "OXDllExt.h"
#include "OXBitmapButton.h"
#include "OXColorPickerCtrl.h"
// The following function was introduced in order to be specifically used in
// DoDataExchange function of any Dialog or FormView based application for
// Color Picker buttons.
OX_API_DECL void AFXAPI DDX_ColorPicker(CDataExchange *pDX, int nIDC, COLORREF& clr);
class OX_CLASS_DECL COXColorPickerButton : public COXBitmapButton
{
DECLARE_DYNAMIC(COXColorPickerButton);
// Data members -------------------------------------------------------------
public:
protected:
// offset for color band to be drawn on the button
static CPoint m_ptColorBandOffset;
// height of color band to be drawn on the button
UINT m_nColorBandHeight;
// color associated with the button
COLORREF m_clr;
// color picker control used to pick color
COXColorPickerCtrl m_colorPicker;
// Member functions ---------------------------------------------------------
public:
// --- In : nButtons - number of buttons in the popup bar (doesn't
// include default and custom buttons)
// nRows - number of button rows (cannot be more than the
// number of buttons)
// dwDefault - value to be associated with default button
// sizeButton - size of buttons (not applicable for default and
// custom buttons their size are calculated
// automatically and depend on the size of
// Popup Bar window)
// sDefaultButtonText - text to be drawn on default button
// sCustomButtonText - text to be drawn on custom button
//
// --- Out :
// --- Returns:
// --- Effect : Constructs the object. All the arguments used to initiate
// COXColorPickerCtrl control
COXColorPickerButton(UINT nColors=40, UINT nRows=4,
COLORREF m_clrDefault=ID_CLRPICK_COLOR_NONE,
CSize sizeButton=CSize(18,18),
int nIDdefault=IDS_OX_BROWSECLRDEFAULT,
int nIDcustom=IDS_OX_BROWSECLRCUSTOM);
// --- In :
// --- Out :
// --- Returns: size of reserved space (from the bottom and right) that shouldn't be
// filled withh button's image or text
// --- Effect : helper function
virtual CSize GetReservedSpace();
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Destructor of the object
virtual ~COXColorPickerButton();
// --- In :
// --- Out :
// --- Returns: pointer to COXColorPickerCtrl object associated with button
// --- Effect :
inline COXColorPickerCtrl* GetColorPickerCtrl() { return &m_colorPicker; }
// --- In : nColorBandHeight - height of color band in pixels
// --- Out :
// --- Returns:
// --- Effect : set the height of color band. By default it is set to 5
inline void SetColorBandHeight(UINT nColorBandHeight) {
m_nColorBandHeight=nColorBandHeight;
}
// --- In :
// --- Out :
// --- Returns: the height of color band
// --- Effect :
inline UINT GetColorBandHeight() const { return m_nColorBandHeight; }
// --- In : clr - color to be associated with the button
// bRedraw - if TRUE then button will be redrawn
// --- Out :
// --- Returns:
// --- Effect : associate button with color
void SetColor(COLORREF clr, BOOL bRedraw=TRUE);
// --- In :
// --- Out :
// --- Returns: color associated with button
// --- Effect :
inline COLORREF GetColor() { return m_clr; }
// --- In : clrDefault - color that will be used in associated
// COXColorPickerCtrl as default
// --- Out :
// --- Returns:
// --- Effect : set default color of associated COXColorPickerCtrl object
inline void SetDefaultColor(COLORREF clrDefault) {
m_colorPicker.SetDefaultData(clrDefault);
}
// --- In :
// --- Out :
// --- Returns: default color of associated COXColorPickerCtrl object
// --- Effect :
inline COLORREF GetDefaultColor() const { return m_colorPicker.GetDefaultData(); }
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(COXColorPickerButton)
public:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
protected:
virtual void PreSubclassWindow();
//}}AFX_VIRTUAL
protected:
// we provide our implementation of this virtual function to display
// COXColorPickerCtrl
virtual void OnDropDown();
// virtual functions that draws color band
virtual void DrawColorBand(CDC* pDC, UINT nState, CRect colorBandRect);
//{{AFX_MSG(COXColorPickerButton)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
//}}AFX_MSG
afx_msg LRESULT OnChangeColorInTornBar(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
#endif // __OXCOLORPICKERBUTTON_H__
// ==========================================================================
| [
"[email protected]"
]
| [
[
[
1,
239
]
]
]
|
90e7e4d059a924fe1269b576223a3b04d46f719e | 006ee225e39d3177996c2981e883ed594badf8a3 | /Project2/trunk/Submit/main.cpp | 7412e09c63b80a9d96e7eefdc557fc485c1a9f6c | []
| no_license | masubi/jpq-project-1 | a55f7a0d8295b0901b1be18c30df880abb899b57 | ae56f2adab78b03fb77ff5df95985f671a7eced4 | refs/heads/master | 2021-01-10T20:30:18.967711 | 2011-04-29T19:29:47 | 2011-04-29T19:29:47 | 37,696,064 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,458 | cpp | /* CPSC545 Spring2011 Project 2
* login: assawaru(login used to submit)
* Linux
* date: 04/27/11
* name: Pichai Assawaruangchai, Quy Le
* emails: [email protected], [email protected] */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <semaphore.h>
using namespace std;
typedef struct
{
int potSize; // total number of pots
int nBaby; // total number of Children
int nFeed; // number of Mom refill
bool *pot; // Array of pot
int out; //pot number that baby eat
int feedCount; //number the mom refill all pot
int eatCount; //number baby eaten, it means the number of empty pot
sem_t full; //semaphore for number of full pot
sem_t mutexMom; //semaphore using by both Mom and baby to sync when to refill
pthread_mutex_t m_Pot; //mutex Pot lock during pot access by either mom or baby
pthread_mutex_t m_EatCount; //mutex EatCount, lock for updated value by either mom or baby
pthread_mutex_t m_Print; //mutex print, lock for print out the whole message
pthread_mutex_t m_Wakeupmom; //motex mom, lock for only one baby can wake mom
}sbuf_t;
sbuf_t shared;
/******************************************************************************
checkForZeroArgument set the default value equal 10 if user input argument equal 0
******************************************************************************/
void checkForZeroArgument(int * num)
{
if (*num == 0)
{
*num = 10;
}
}
/******************************************************************************
printArgumentErrorMessage print program usage argument
******************************************************************************/
void printArgumentErrorMessage(int argc)
{
cout << "**** Usage: eaglefeed m n t" << endl;
cout << " where m = number of feeding pots" << endl;
cout << " n = number of baby eagles" << endl;
cout << " t = number of feedings" << endl;
exit(1);
}
/******************************************************************************
pthread_sleep takes an integer number of seconds to pause the current thread We
provide this function because one does not exist in the standard pthreads library. We
simply use a function that has a timeout.
******************************************************************************/
int pthread_sleep (int seconds)
{
pthread_mutex_t mutex;
pthread_cond_t conditionvar;
struct timespec timetoexpire;
if(pthread_mutex_init(&mutex,NULL))
{
return -1;
}
if(pthread_cond_init(&conditionvar,NULL))
{
return -1;
}
//When to expire is an absolute time, so get the current time and add
//it to our delay time
timetoexpire.tv_sec = (unsigned int)time(NULL) + seconds;
timetoexpire.tv_nsec = 0;
return pthread_cond_timedwait(&conditionvar, &mutex, &timetoexpire);
}
/******************************************************************************
MotherEagleThreadFn
- Mom will wait untill one of the baby eagle wake her up to refill the pot.
- Using mutex m_Wakeupmom to make sure that while mom is preparing food, no other
baby eagle can wake up her again untill mom goes back to sleep
- After mom refill all the pot, mom will let all boby eagle know and baby can
start eating.
******************************************************************************/
void *MotherEagleThreadFn(void *arg)
{
int i, count = 1;
while(shared.feedCount > 0)
{
//Wait untill a baby wake her up
sem_wait(&shared.mutexMom);
//baby finish all pot
if(shared.eatCount >= shared.potSize)
{
// Reset the eatCount value to 0
pthread_mutex_lock(&shared.m_EatCount);
shared.eatCount = 0;
pthread_mutex_unlock(&shared.m_EatCount);
// Refill all pot, set value to true. Mother refill the whole pot at once.
pthread_mutex_lock(&shared.m_Pot);
for (i=0; i < shared.potSize; i++)
{
shared.pot[i] = true;
sem_post(&shared.full);
}
pthread_mutex_unlock(&shared.m_Wakeupmom);
pthread_sleep(1);
pthread_mutex_lock(&shared.m_Print);
//Mom allow baby eagles to eat.
cout << "Mother eagle says \"Feeding (" << count << ")\"" << endl;
pthread_mutex_unlock(&shared.m_Print);
pthread_mutex_unlock(&shared.m_Pot);
pthread_mutex_lock(&shared.m_Print);
cout << "Mother eagle takes a nap." << endl;
pthread_mutex_unlock(&shared.m_Print);
shared.feedCount--;
count++;
}
}
return NULL;
}
/******************************************************************************
BabyEagleThredFn
- Using pthread_mutex_trylock(&shared.m_Wakeupmom) to make sure that only one
baby eagle who find out the pot empty can wake mom up to refill
- Baby eagle will wait untile mom refilled and let them eat.
- Baby eagle thread will be terminate when the last pot of the last feeding empty
******************************************************************************/
void *BabyEagleThredFn(void *arg)
{
int i, index;
index = (long)arg;
while(1)
{
// Baby eagel chack wherther all pot empty, then it have to wake Mom to refill
if(shared.eatCount >= shared.potSize)
{
if(shared.feedCount <= 0)
{
break;
}
if(pthread_mutex_trylock(&shared.m_Wakeupmom) == 0)
{
pthread_mutex_lock(&shared.m_Print);
for(i = 0; i <= index; i++)
{
cout << " ";
}
cout << "Baby eagle " << index+1 << " sees all feeding pots are empty and wakes up the mother." << endl;
cout << "Mother eagle is awork by " << index+1 << " and strats preparing the food." << endl;
pthread_mutex_unlock(&shared.m_Print);
//Let mom know that all pot empty
sem_post(&shared.mutexMom);
}
else
{
continue;
}
}
pthread_sleep(1);
pthread_mutex_lock(&shared.m_Print);
for(i = 0; i <= index; i++)
{
cout << " ";
}
cout << "Baby eagle " << index+1 << " is ready to eat."
<< "\n ......" <<endl;
pthread_mutex_unlock(&shared.m_Print);
sem_wait(&shared.full);
pthread_mutex_lock(&shared.m_Pot);
//Baby eagle start eating if pots are filled with food
if(shared.pot[shared.out] == true)
{
shared.pot[shared.out] = false;
pthread_mutex_lock(&shared.m_Print);
for(i = 0; i <= index; i++)
{
cout << " ";
}
cout << "Baby eagle " << index+1 << " is eating using feeeding pot " << shared.out
<< ".\n ......" << endl;
pthread_mutex_unlock(&shared.m_Print);
shared.out = (shared.out+1)%shared.potSize;
//eat for a while
pthread_sleep(1);
pthread_mutex_unlock(&shared.m_Pot);
//Increment the number of eatCount, it means the number of empty pot
pthread_mutex_lock(&shared.m_EatCount);
shared.eatCount++;
pthread_mutex_unlock(&shared.m_EatCount);
pthread_mutex_lock(&shared.m_Print);
for(i = 0; i <= index; i++)
{
cout << " ";
}
cout << "Baby eagle " << index+1 << " finishes eating."
<< "\n ......" <<endl;
pthread_mutex_unlock(&shared.m_Print);
}
}
return NULL;
}
int main(int argc, char *argv[])
{
if (argc != 4)
{
printArgumentErrorMessage(argc);
}
pthread_t idMom, idBaby;
int index;
// Initialize share variable value
shared.potSize = atoi(argv[1]); // total number of pots
checkForZeroArgument(&shared.potSize);
shared.nBaby = atoi(argv[2]); // total number of Children
checkForZeroArgument(&shared.nBaby);
shared.nFeed = atoi(argv[3]); // number of Mom refill
checkForZeroArgument(&shared.nFeed);
shared.pot = new bool[shared.potSize];
shared.feedCount = shared.nFeed;
shared.eatCount = shared.potSize;
cout << "MAIN: There are " << shared.nBaby << " baby eagles, " << shared.potSize
<< " feeding pots, and " << shared.nFeed << " feeding." << endl;
cout << "MAIN: Game starts!!!!!" << "\n ......" << endl;
// Initialize mutex
sem_init(&shared.full, 0, 0);
sem_init(&shared.mutexMom, 0, 0);
pthread_mutex_init(&shared.m_Pot, NULL);
pthread_mutex_init(&shared.m_EatCount, NULL);
pthread_mutex_init(&shared.m_Print, NULL);
pthread_mutex_init(&shared.m_Wakeupmom, NULL);
// Mother eagel thread
pthread_mutex_lock(&shared.m_Print);
cout << "Mother eagle started.\n ......" << endl;
pthread_mutex_unlock(&shared.m_Print);
pthread_create(&idMom, NULL, MotherEagleThreadFn, (void*)NULL);
// Baby eagel thread
for (index = 0; index < shared.nBaby; index++)
{
/* Create a new producer */
pthread_mutex_lock(&shared.m_Print);
for(int i = 0; i <= index; i++)
{
cout << " ";
}
cout << "Baby eagle " << index+1 << " started.\n ......." << endl;
pthread_mutex_unlock(&shared.m_Print);
pthread_create(&idBaby, NULL, BabyEagleThredFn, (void*)index);
}
pthread_join(idMom, NULL);
// wait untill Baby finish all the pots them Destroy all semaphore
while(1)
{
if(shared.eatCount >= shared.potSize)
{
sem_destroy(&shared.full);
sem_destroy(&shared.mutexMom);
pthread_mutex_destroy(&shared.m_Pot);
pthread_mutex_destroy(&shared.m_EatCount);
pthread_mutex_destroy(&shared.m_Print);
pthread_mutex_destroy(&shared.m_Wakeupmom);
break;
}
}
return 0;
}
| [
"pichai.assa@c491f225-113b-c5b7-de4c-e81cec797d0c"
]
| [
[
[
1,
302
]
]
]
|
02061edb75119b19f82925a8b08d50f00116d886 | 04fec4cbb69789d44717aace6c8c5490f2cdfa47 | /ui/src/MainFrame.cpp | d5566d9e41db3077ac0cfb13e8d2d15d813814d7 | []
| no_license | aaryanapps/whiteTiger | 04f39b00946376c273bcbd323414f0a0b675d49d | 65ed8ffd530f20198280b8a9ea79cb22a6a47acd | refs/heads/master | 2021-01-17T12:07:15.264788 | 2010-10-11T20:20:26 | 2010-10-11T20:20:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,648 | cpp |
#include "wx/wx.h"
#include "wx/notebook.h"
#include "wx/defs.h"
#include "wx/panel.h"
#include "wx/splitter.h"
//#include "wxGlobal.h"
#include "MainFrame.h"
#include "MenuDefs.h"
BEGIN_EVENT_TABLE(CMainFrame, wxFrame)
EVT_MENU(ID_FILE_QUIT, CMainFrame::OnFileQuit)
EVT_MENU(ID_FILE_NEW, CMainFrame::OnFileNew)
EVT_MENU(ID_FILE_OPEN, CMainFrame::OnFileOpen)
EVT_MENU(ID_FILE_SAVEAS, CMainFrame::OnFileSaveAs)
EVT_MENU(ID_HELP_ABOUT, CMainFrame::OnHelpMenu)
EVT_MENU(ID_CAPTURE_START, CMainFrame::OnCaptureStartCapture)
EVT_MENU(ID_CAPTURE_STOP, CMainFrame::OnCaptureStopCapture)
END_EVENT_TABLE()
CMainFrame::CMainFrame(const wxString& title,
const wxPoint& pos, const wxSize& size, long style)
: wxFrame((wxFrame *)NULL, -1, title, pos, size)
{
CreateMainMenuFileMenu();
CreateMainMenuEditMenu();
CreateMainMenuCaptureMenu();
CreateMainMenuViewMenu();
CreateMainMenuAnalyzeMenu();
CreateMainMenuStatsMenu();
CreateMainMenuHelpMenu();
// now append the freshly created menu to the menu bar...
m_menuBar = new wxMenuBar();
m_menuBar->Append(m_fileMenu, MENU_FILE);
m_menuBar->Append(m_editMenu, MENU_EDIT);
m_menuBar->Append(m_viewMenu, MENU_VIEW);
m_menuBar->Append(m_captureMenu, MENU_CAPTURE);
m_menuBar->Append(m_analyzeMenu, MENU_ANALYZE);
m_menuBar->Append(m_statsMenu, MENU_STATISTICS);
m_menuBar->Append(m_helpMenu, MENU_HELP);
SetMenuBar( m_menuBar );
CreateStatusBar(3);
SetStatusText( STATUS_BAR_DEFAULT_STRING );
// Creates two Split windows
wxSplitterWindow *topSplitter = new wxSplitterWindow(this, -1,
wxDefaultPosition,wxDefaultSize, wxSP_NOBORDER);
wxSplitterWindow *bottomSplitter = new wxSplitterWindow(topSplitter, -1,
wxDefaultPosition, wxDefaultSize, wxSP_NOBORDER);
wxPanel *dummy1 = new wxPanel(bottomSplitter,wxID_ANY);
wxPanel *dummy2 = new wxPanel(bottomSplitter,wxID_ANY);
// Prevent from UnSplit
topSplitter->SetMinimumPaneSize(5);
bottomSplitter->SetMinimumPaneSize(5);
m_cdm = new CCaptureDisplayManager(topSplitter);
// Split the Frame
topSplitter->SplitHorizontally(m_cdm, bottomSplitter);
bottomSplitter->SplitVertically(dummy1, dummy2);
topSplitter->Show(true);
bottomSplitter->Show(true);
}
CMainFrame::~CMainFrame()
{
}
void CMainFrame::OnFileQuit(wxCommandEvent& WXUNUSED(event))
{
Close(TRUE);
}
void CMainFrame::OnFileNew(wxCommandEvent &event)
{
CreateNewTrace();
}
void CMainFrame::OnFileOpen(wxCommandEvent &event)
{
// Several files can be opened at same time
wxFileDialog dialog(this, DLG_OPEN_FILES, _T(""), _T(""), DLG_CAPTUREOPEN_TYPES,
wxFD_OPEN | wxFD_MULTIPLE | wxFD_FILE_MUST_EXIST);
if (dialog.ShowModal() == wxID_OK)
{
wxArrayString selFiles;
dialog.GetPaths(selFiles);
if (selFiles.IsEmpty())
{
//Log, nothing seleted by user.
return;
}
std::vector<std::string> files;
uint16_t selCnt = selFiles.GetCount();
for (int i = 0; i < selCnt; ++i)
{
std::string s(selFiles.Item(i).mb_str());
files.push_back(s);
//wxString fname = selFiles.Item(i);
//m_cdm->AddNewOfflineCapture();
}
m_cdm->AddOfflineCapture(files);
}
}
void CMainFrame::OnFileSave(wxCommandEvent &event)
{
}
void CMainFrame::OnFileSaveAs(wxCommandEvent &event)
{
// Several files can be opened at same time
wxFileDialog dialog(this, DLG_SAVE_FILE, _T(""), _T(""), DLG_CAPTURESAVE_TYPES,
wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if (dialog.ShowModal() == wxID_OK)
{
}
}
void CMainFrame::OnFileExport(wxCommandEvent &event)
{
}
void CMainFrame::OnFilePrint(wxCommandEvent &event)
{
}
void CMainFrame::OnEditFindPacket(wxCommandEvent &event)
{
}
void CMainFrame::OnEditFindNextPacket(wxCommandEvent &event)
{
}
void CMainFrame::OnEditFindPreviousPacket(wxCommandEvent &event)
{
}
void CMainFrame::OnEditCutPacket(wxCommandEvent &event)
{
}
void CMainFrame::OnEditCopyPacket(wxCommandEvent &event)
{
}
void CMainFrame::OnEditPastePacket(wxCommandEvent &event)
{
}
void CMainFrame::OnEditGotoPacket(wxCommandEvent &event)
{
}
void CMainFrame::OnEditAppPreferences(wxCommandEvent &event)
{
}
void CMainFrame::OnCaptureStartCapture(wxCommandEvent &event)
{
m_cdm->AddLiveCapture();
}
void CMainFrame::OnCaptureStopCapture(wxCommandEvent &event)
{
}
void CMainFrame::OnCapturePauseCapture(wxCommandEvent &event)
{
}
void CMainFrame::OnCaptureResumeCapture(wxCommandEvent &event)
{
}
void CMainFrame::OnCaptureCaptureOptions(wxCommandEvent &event)
{
}
void CMainFrame::OnCaptureCaptureFilters(wxCommandEvent &event)
{
}
void CMainFrame::OnHelpMenu(wxCommandEvent& event)
{
switch (event.GetId())
{
case ID_HELP_CONTENTS:
{
}; break;
case ID_HELP_MANUAL:
{
}; break;
case ID_HELP_EXAMPLES:
{
}; break;
case ID_HELP_ABOUT:
{
wxMessageBox(MENU_HELP_ABOUT,MENU_HELP_ABOUT_STRING,
wxOK | wxICON_INFORMATION, this);
}; break;
default:
break;
}
}
void CMainFrame::OnCloseWindow(wxCloseEvent &event)
{
Close(TRUE);
}
//Private Methods
void CMainFrame::CreateMainMenuFileMenu()
{
m_fileMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
m_fileMenu->Append(ID_FILE_NEW, MENU_FILE_NEW, MENU_FILE_NEW_STRING);
m_fileMenu->Append(ID_FILE_OPEN, MENU_FILE_OPEN, MENU_FILE_OPEN_STRING);
m_fileMenu->AppendSeparator();
m_fileMenu->Append(ID_FILE_SAVE, MENU_FILE_SAVE, MENU_FILE_SAVE_STRING);
m_fileMenu->Append(ID_FILE_SAVEAS, MENU_FILE_SAVEAS, MENU_FILE_SAVEAS_STRING);
m_fileMenu->AppendSeparator();
m_fileMenu->Append(ID_FILE_QUIT, MENU_FILE_QUIT, MENU_FILE_QUIT_STRING);
}
void CMainFrame::CreateMainMenuEditMenu()
{
m_editMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
m_editMenu->Append(ID_EDIT_FIND_PACKET, MENU_EDIT_FIND_PACKET, MENU_EDIT_FIND_PACKET_STRING);
m_editMenu->AppendSeparator();
m_editMenu->Append(ID_EDIT_COPY_PACKET, MENU_EDIT_COPY_PACKET, MENU_EDIT_COPY_PACKET_STRING);
m_editMenu->Append(ID_EDIT_CUT_PACKET, MENU_EDIT_CUT, MENU_EDIT_CUT_STRING);
m_editMenu->Append(ID_EDIT_PASTE_PACKET, MENU_EDIT_PASTE, MENU_EDIT_PASTE_STRING);
}
void CMainFrame::CreateMainMenuCaptureMenu()
{
m_captureMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
m_captureMenu->Append(ID_CAPTURE_START, MENU_CAPTURE_START_CAPTURE, MENU_CAPTURE_START_CAPTURE_STRING);
m_captureMenu->Append(ID_CAPTURE_STOP, MENU_CAPTURE_STOP_CAPTURE, MENU_CAPTURE_STOP_CAPTURE_STRING);
}
void CMainFrame::CreateMainMenuViewMenu()
{
m_viewMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
}
void CMainFrame::CreateMainMenuAnalyzeMenu()
{
m_analyzeMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
}
void CMainFrame::CreateMainMenuStatsMenu()
{
m_statsMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
}
void CMainFrame::CreateMainMenuHelpMenu()
{
m_helpMenu = new wxMenu(_T(""), wxMENU_TEAROFF);
m_helpMenu->Append(ID_HELP_ABOUT, MENU_HELP_ABOUT, MENU_HELP_ABOUT_STRING);
}
bool CMainFrame::CreateNewTrace()
{
std::vector<std::string> emptyList;
return m_cdm->AddOfflineCapture(emptyList);
}
/*
void CMainFrame::OnRightClick(wxMouseEvent & event)
{
if (!m_rMenu)
{
m_rMenu = new wxMenu ;
m_rMenu->Append(ID_LEFT_EXIT, _T("E&xit"));
}
PopupMenu(m_rMenu, event.GetPosition());
}
*/
//! Handler called when the user drops a file on the main frame
bool CDropFileHandler::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& FileNames)
{
return true;
}
| [
"[email protected]"
]
| [
[
[
1,
319
]
]
]
|
1b72c74cbaf1b21ad68b7c3a3fbb44ffd0fefabe | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/ipappprotocols/sip/sipcodec/src/t_csipacceptheader.cpp | f4b340cf9f24ec719cadad1bf0b87b90978d8ad9 | []
| 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 | 14,318 | cpp | /*
* Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#include "t_csipacceptheader.h"
#include <stdlib.h>
#include "T_SIPUtil.h"
#include <utf.h>
#include <s32file.h>
/*@{*/
_LIT(KCmdDestroy, "~");
_LIT(KCmdNewL, "NewL");
_LIT(KCmdNewLC, "NewLC");
_LIT(KCmdDecodeL, "DecodeL");
_LIT(KCmdIsEmpty, "IsEmpty");
_LIT(KCmdMediaType, "MediaType");
_LIT(KCmdSetMediaTypeL, "SetMediaTypeL");
_LIT(KCmdMediaSubtype, "MediaSubtype");
_LIT(KCmdSetMediaSubtypeL, "SetMediaSubtypeL");
_LIT(KCmdQParameter, "QParameter");
_LIT(KCmdSetQParameterL, "SetQParameterL");
_LIT(KCmdInternalizeValueL, "InternalizeValueL");
//Fields
_LIT(KFldMediaSubtype, "mediasubtype");
_LIT(KFldMediaType, "mediatype");
_LIT(KFldParamValue, "paramvalue");
_LIT(KFldExpected, "expected");
_LIT(KFldTReal, "treal");
_LIT(KFldFileName, "filename");
// Logging
_LIT(KLogError, "Error=%d");
_LIT(KLogMissingParameter, "Missing parameter '%S'");
_LIT(KLogNotExpectedValue, "Not expected value, actual=%S, expect=%S");
_LIT(KLogNotExpectedValueReal, "Not expected value, actual=%f, expect=%f");
CT_DataSIPAcceptHeader::CT_DataSIPAcceptHeader()
: CT_DataSIPParameterHeaderBase(), iSIPAcceptHeader(NULL), iIsOwner(ETrue)
{
}
CT_DataSIPAcceptHeader::~CT_DataSIPAcceptHeader()
{
DestroyData();
}
void CT_DataSIPAcceptHeader::ConstructL()
{
}
CT_DataSIPAcceptHeader* CT_DataSIPAcceptHeader::NewL()
{
CT_DataSIPAcceptHeader* self = new (ELeave) CT_DataSIPAcceptHeader();
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::Pop(self);
return self;
}
TAny* CT_DataSIPAcceptHeader::GetObject()
{
return iSIPAcceptHeader;
}
void CT_DataSIPAcceptHeader::SetObjectL(TAny* aAny)
{
iSIPAcceptHeader = static_cast<CSIPAcceptHeader*>(aAny);
}
void CT_DataSIPAcceptHeader::DisownObjectL()
{
iSIPAcceptHeader = NULL;
iIsOwner = EFalse;
}
void CT_DataSIPAcceptHeader::DestroyData()
{
if(iIsOwner && iSIPAcceptHeader != NULL)
{
delete iSIPAcceptHeader;
iSIPAcceptHeader = NULL;
iIsOwner = EFalse;
}
}
void CT_DataSIPAcceptHeader::DoCmdDestructor(const TTEFSectionName& /*aSection*/)
{
INFO_PRINTF1(_L("call CSIPAcceptHeader::~CSIPAcceptHeader()"));
DestroyData();
}
CSIPHeaderBase* CT_DataSIPAcceptHeader::GetSIPHeaderBase() const
{
return iSIPAcceptHeader;
}
TBool CT_DataSIPAcceptHeader::DoCommandL(const TTEFFunction& aCommand, const TTEFSectionName& aSection, const TInt aAsyncErrorIndex)
{
TBool ret=ETrue;
if ( aCommand==KCmdDestroy )
{
DoCmdDestructor(aSection);
}
else if (aCommand==KCmdNewL)
{
DoCmdNewL(aSection);
}
else if (aCommand==KCmdNewLC)
{
DoCmdNewLC(aSection);
}
else if (aCommand==KCmdDecodeL)
{
DoCmdDecodeL(aSection);
}
else if(aCommand == KCmdIsEmpty)
{
DoCmdIsEmpty(aSection);
}
else if( aCommand == KCmdMediaType )
{
DoCmdMediaType(aSection);
}
else if( aCommand == KCmdSetMediaTypeL )
{
DoCmdSetMediaTypeL(aSection);
}
else if( aCommand == KCmdMediaSubtype )
{
DoCmdMediaSubtype(aSection);
}
else if( aCommand == KCmdSetMediaSubtypeL )
{
DoCmdSetMediaSubtypeL(aSection);
}
else if (aCommand==KCmdQParameter)
{
DoCmdQParameter(aSection);
}
else if (aCommand==KCmdSetQParameterL)
{
DoCmdSetQParameterL(aSection);
}
else if (aCommand==KCmdInternalizeValueL)
{
DoCmdInternalizeValueL(aSection);
}
else
{
ret = CT_DataSIPParameterHeaderBase::DoCommandL(aCommand, aSection, aAsyncErrorIndex);;
}
return ret;
}
void CT_DataSIPAcceptHeader::DoCmdNewL(const TTEFSectionName& aSection)
{
TBool dataOK = ETrue;
TPtrC temp;
if( !GetStringFromConfig(aSection, KFldMediaType, temp) )
{
ERR_PRINTF2(KLogMissingParameter, &KFldMediaType);
dataOK = EFalse;
}
TPtrC temp1;
if( !GetStringFromConfig(aSection, KFldMediaSubtype, temp1) )
{
ERR_PRINTF2(KLogMissingParameter, &KFldMediaSubtype);
dataOK = EFalse;
}
if(!dataOK)
{
SetBlockResult(EFail);
}
else
{
TBuf8<KMaxTestExecuteCommandLength> mediatype;
CnvUtfConverter::ConvertFromUnicodeToUtf8(mediatype, temp);
TBuf8<KMaxTestExecuteCommandLength> mediasubtype;
CnvUtfConverter::ConvertFromUnicodeToUtf8(mediasubtype, temp1);
INFO_PRINTF1(_L("call CSIPAcceptHeader::NewL(const TDesC8&, const TDesC8&)"));
TRAPD(err, iSIPAcceptHeader = CSIPAcceptHeader::NewL(mediatype, mediasubtype));
if(KErrNone != err)
{
ERR_PRINTF2(KLogError, err);
SetError(err);
}
else
{
iIsOwner = ETrue;
}
}
}
void CT_DataSIPAcceptHeader::DoCmdNewLC(const TTEFSectionName& aSection)
{
TBool dataOK = ETrue;
TPtrC temp;
if( !GetStringFromConfig(aSection, KFldMediaType, temp) )
{
ERR_PRINTF2(KLogMissingParameter, &KFldMediaType);
dataOK = EFalse;
}
TPtrC temp1;
if( !GetStringFromConfig(aSection, KFldMediaSubtype, temp1) )
{
ERR_PRINTF2(KLogMissingParameter, &KFldMediaSubtype);
dataOK = EFalse;
}
if(!dataOK)
{
SetBlockResult(EFail);
}
else
{
TBuf8<KMaxTestExecuteCommandLength> mediatype;
CnvUtfConverter::ConvertFromUnicodeToUtf8(mediatype, temp);
TBuf8<KMaxTestExecuteCommandLength> mediasubtype;
CnvUtfConverter::ConvertFromUnicodeToUtf8(mediasubtype, temp1);
INFO_PRINTF1(_L("call CSIPAcceptHeader::NewLC(const TDesC8&, const TDesC8&)"));
TRAPD(err, iSIPAcceptHeader = CSIPAcceptHeader::NewLC(mediatype, mediasubtype); CleanupStack::Pop(iSIPAcceptHeader));
if(KErrNone != err)
{
ERR_PRINTF2(KLogError, err);
SetError(err);
}
else
{
iIsOwner = ETrue;
}
}
}
void CT_DataSIPAcceptHeader::DoCmdDecodeL(const TTEFSectionName& aSection)
{
delete iSIPAcceptHeader;
iSIPAcceptHeader = NULL;
TPtrC strVal;
if (!GetStringFromConfig(aSection, KFldParamValue, strVal))
{
ERR_PRINTF2(KLogMissingParameter, &KFldParamValue());
SetBlockResult(EFail);
return;
}
TBuf8<KMaxTestExecuteCommandLength> val;
CnvUtfConverter::ConvertFromUnicodeToUtf8(val, strVal);
INFO_PRINTF1(_L("execute CSIPAcceptHeader::DecodeL(const TDesC8&)"));
TRAPD(err, iSIPAcceptHeader = CSIPAcceptHeader::DecodeL(val)[0]);
if(err != KErrNone)
{
ERR_PRINTF2(KLogError, err);
SetError(err);
}
}
void CT_DataSIPAcceptHeader::DoCmdIsEmpty(const TTEFSectionName& aSection)
{
INFO_PRINTF1(_L("call CSIPAcceptHeader::IsEmpty()"));
TBool ret = iSIPAcceptHeader->IsEmpty();
INFO_PRINTF2(_L("Actual IsEmpty: %d"), ret);
TBool expected = EFalse;
if(GetBoolFromConfig(aSection, KFldExpected, expected))
{
if(ret != expected)
{
INFO_PRINTF2(_L("expected IsEmpty: %d"), expected);
SetBlockResult(EFail);
}
}
}
void CT_DataSIPAcceptHeader::DoCmdMediaType(const TTEFSectionName& aSection)
{
INFO_PRINTF1(_L("call CSIPAcceptHeader::MediaType()"));
const TPtrC8 ret = iSIPAcceptHeader->MediaType();
TBuf<KMaxTestExecuteCommandLength> temp1;
CnvUtfConverter::ConvertToUnicodeFromUtf8(temp1, ret);
INFO_PRINTF2(_L("MediaType: %S"), &temp1);
TPtrC temp;
if( GetStringFromConfig(aSection, KFldExpected, temp) )
{
TBuf8<KMaxTestExecuteCommandLength> expected;
CnvUtfConverter::ConvertFromUnicodeToUtf8(expected, temp);
if(ret != expected)
{
ERR_PRINTF3(KLogNotExpectedValue, &temp1, &temp);
SetBlockResult(EFail);
}
}
}
void CT_DataSIPAcceptHeader::DoCmdSetMediaTypeL(const TTEFSectionName& aSection)
{
TPtrC temp;
if( !GetStringFromConfig(aSection, KFldMediaType, temp) )
{
ERR_PRINTF2(KLogMissingParameter, &KFldMediaType);
SetBlockResult(EFail);
}
else
{
TBuf8<KMaxTestExecuteCommandLength> mediatype;
CnvUtfConverter::ConvertFromUnicodeToUtf8(mediatype, temp);
INFO_PRINTF1(_L("call CSIPAcceptHeader::SetMediaTypeL(const TDesC8&)"));
TRAPD(err, iSIPAcceptHeader->SetMediaTypeL(mediatype));
if(KErrNone != err)
{
ERR_PRINTF2(KLogError, err);
SetError(err);
}
}
}
void CT_DataSIPAcceptHeader::DoCmdMediaSubtype(const TTEFSectionName& aSection)
{
INFO_PRINTF1(_L("call CSIPAcceptHeader::MediaSubtype()"));
const TPtrC8 ret = iSIPAcceptHeader->MediaSubtype();
TBuf<KMaxTestExecuteCommandLength> temp1;
CnvUtfConverter::ConvertToUnicodeFromUtf8(temp1, ret);
INFO_PRINTF2(_L("MediaSubtype: %S"), &temp1);
TPtrC temp;
if( GetStringFromConfig(aSection, KFldExpected, temp) )
{
TBuf8<KMaxTestExecuteCommandLength> expected;
CnvUtfConverter::ConvertFromUnicodeToUtf8(expected, temp);
if(ret != expected)
{
ERR_PRINTF3(KLogNotExpectedValue, &temp1, &temp);
SetBlockResult(EFail);
}
}
}
void CT_DataSIPAcceptHeader::DoCmdSetMediaSubtypeL(const TTEFSectionName& aSection)
{
TPtrC temp;
if( !GetStringFromConfig(aSection, KFldMediaSubtype, temp) )
{
ERR_PRINTF2(KLogMissingParameter, &KFldMediaSubtype);
SetBlockResult(EFail);
}
else
{
TBuf8<KMaxTestExecuteCommandLength> mediasubtype;
CnvUtfConverter::ConvertFromUnicodeToUtf8(mediasubtype, temp);
INFO_PRINTF1(_L("call CSIPAcceptHeader::SetMediaSubtypeL(const TDesC8&)"));
TRAPD(err, iSIPAcceptHeader->SetMediaSubtypeL(mediasubtype));
if(KErrNone != err)
{
ERR_PRINTF2(KLogError, err);
SetError(err);
}
}
}
void CT_DataSIPAcceptHeader::DoCmdQParameter(const TTEFSectionName& aSection)
{
TReal retTReal;
TReal expected;
INFO_PRINTF1(_L("execute CSIPAcceptHeader::QParameter()"));
retTReal = iSIPAcceptHeader->QParameter();
INFO_PRINTF2(_L("The valude of the q parameter is : %f"), retTReal);
if (CT_SIPUtil::GetTRealFromConfig(*this, aSection, KFldExpected, expected))
{
if(!CT_SIPUtil::CompareTReal(retTReal, expected ))
{
ERR_PRINTF3(KLogNotExpectedValueReal, retTReal, expected);
SetBlockResult(EFail);
}
}
}
void CT_DataSIPAcceptHeader::DoCmdSetQParameterL(const TTEFSectionName& aSection)
{
TReal dattreal;
if(!CT_SIPUtil::GetTRealFromConfig(*this, aSection, KFldTReal, dattreal) )
{
ERR_PRINTF2(KLogMissingParameter, &KFldTReal);
SetBlockResult(EFail);
return;
}
INFO_PRINTF1(_L("execute CSIPAcceptHeader::SetQParameterL(TReal)"));
TRAPD(err, iSIPAcceptHeader->SetQParameterL(dattreal));
if(err != KErrNone)
{
ERR_PRINTF2(KLogError, err);
SetError(err);
}
}
void CT_DataSIPAcceptHeader::DoCmdInternalizeValueL(const TTEFSectionName& aSection)
{
TPtrC datFileName;
if( !GetStringFromConfig(aSection, KFldFileName, datFileName) )
{
ERR_PRINTF2(KLogMissingParameter, &KFldFileName);
SetBlockResult(EFail);
}
else
{
CDirectFileStore* readstore = CDirectFileStore::OpenL(FileServer(), datFileName, EFileStream | EFileRead);
CleanupStack::PushL(readstore);
TStreamId headerid = readstore->Root();
RStoreReadStream readstrm;
readstrm.OpenL(*readstore, headerid);
CleanupClosePushL(readstrm);
INFO_PRINTF1(_L("call CSIPAcceptHeader::InternalizeValueL(RReadStream&)"));
TRAPD(err, iSIPAcceptHeader = (CSIPAcceptHeader*)CSIPAcceptHeader::InternalizeValueL(readstrm));
if(KErrNone != err)
{
ERR_PRINTF2(KLogError, err);
SetError(err);
}
CleanupStack::PopAndDestroy(2);
}
}
void CT_DataSIPAcceptHeader::SetIsOwner(TBool aOwner)
{
iIsOwner = aOwner;
}
| [
"none@none"
]
| [
[
[
1,
453
]
]
]
|
32808f6b339f84a1065910296b48c4687a8d5f38 | 5d36f6102c8cadcf1a124b366ae189d6a2609c59 | /src/gpuAPI/newGPU/core_Draw.cpp | 2178f69ab330cf8cb2b7c24aca8515f80ef0e109 | []
| no_license | Devil084/psx4all | 336f2861246367c8d397ef5acfc0b7972085c21b | 04c02bf8840007792d23d15ca42a572035a1d703 | refs/heads/master | 2020-02-26T15:18:04.554046 | 2010-08-11T13:49:24 | 2010-08-11T13:49:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,726 | cpp | #include "newGPU.h"
#include "minimal.h"
u16 bgr2rgb[65536];
///////////////////////////////////////////////////////////////////////////////
#include "raster.h"
#include "inner_Blit.h"
///////////////////////////////////////////////////////////////////////////////
void clutInit()
{
#if 0
int r,g,b,i;
i = 0;
for(b = 0; b < 32; b++)
{
for(g = 0; g < 32; g++)
{
for(r = 0; r < 32; r++)
{
u16 pixbgr = (b<<10) | (g<<5) | (r);
bgr2rgb[i] = ((pixbgr&(0x1f001f<<10))>>10) | ((pixbgr&(0x1f001f<<5))<<1) | ((pixbgr&(0x1f001f<<0))<<11);
bgr2rgb[i+32768] = bgr2rgb[i];
i++;
}
}
}
#endif
}
///////////////////////////////////////////////////////////////////////////////
void gpuDebugRect(u16 col, u32 x0, u32 y0, u32 x1, u32 y1)
{
if(x0>x1 || y0>y1 || x1>1024 || y1>512)
return;
x0 = (x0* PSX4ALL_WIDTH)/1024; x1 = (x1*PSX4ALL_WIDTH )/1024;
y0 = (y0*PSX4ALL_HEIGHT)/ 512; y1 = (y1*PSX4ALL_HEIGHT)/ 512;
u16* dest_screen16 = gp2x_screen16;
dest_screen16 += (y0*PSX4ALL_WIDTH);
// top
if(y0!=y1)
{
for(u32 x=x0;x<x1;++x) dest_screen16[x] = col;
dest_screen16 += PSX4ALL_WIDTH;
}
// middle
if(x1) --x1;
while(++y0<y1)
{
dest_screen16[x0] = dest_screen16[x1] = col;
dest_screen16 += PSX4ALL_WIDTH;
}
++x1;
// bottom
{
for(u32 x=x0;x<x1;++x) dest_screen16[x] = col;
}
}
///////////////////////////////////////////////////////////////////////////////
void gpuDisplayVideoMem()
{
u16* dest_screen16 = gp2x_screen16;
for(int y=0;y<240;++y)
{
u16* src_screen16 = &((u16*)GPU_FrameBuffer)[FRAME_OFFSET(0,(y<<9)/PSX4ALL_HEIGHT)];
GPU_BlitWSSWSSWSSWSSWSSS( src_screen16, dest_screen16, false);
dest_screen16 += PSX4ALL_WIDTH;
}
gpuDebugRect(0x00FF, DrawingArea[0], DrawingArea[1], DrawingArea[2], DrawingArea[3]);
gpuDebugRect(0xFF00, DisplayArea[0], DisplayArea[1], DisplayArea[0]+DisplayArea[2], DisplayArea[1]+DisplayArea[3]);
gpuDebugRect(0x0FF0, DirtyArea[0], DirtyArea[1], DirtyArea[2], DirtyArea[3]);
gpuDebugRect(0xFFFF, LastDirtyArea[0], LastDirtyArea[1], LastDirtyArea[2], LastDirtyArea[3]);
gp2x_video_flip();
}
///////////////////////////////////////////////////////////////////////////////
void gpuVideoOutput(void)
{
static s16 old_res_horz, old_res_vert, old_rgb24;
s16 h0, x0, y0, w0, h1;
x0 = DisplayArea[0];
y0 = DisplayArea[1];
w0 = DisplayArea[2];
h0 = DisplayArea[3]; // video mode
h1 = DisplayArea[7] - DisplayArea[5]; // display needed
if (h0 == 480)
h1 = Min2(h1*2,480);
#ifdef ZAURUS
if(SDL_MUSTLOCK(gp2x_sdlwrapper_screen)) SDL_LockSurface(gp2x_sdlwrapper_screen);
#endif
u16* dest_screen16 = gp2x_screen16;
u16* src_screen16 = &((u16*)GPU_FrameBuffer)[FRAME_OFFSET(x0,y0)];
u32 isRGB24 = (GPU_GP1 & 0x00200000 ? 32 : 0);
/* Clear the screen if resolution changed to prevent interlacing and clipping to clash */
if( (w0 != old_res_horz || h1 != old_res_vert || (s16)isRGB24 != old_rgb24) )
{
// Update old resolution
old_res_horz = w0;
old_res_vert = h1;
old_rgb24 = (s16)isRGB24;
// Finally, clear the screen for this special case
gp2x_video_RGB_clearscreen16();
}
#if 0 //def PANDORA
if(h0==256)
{
h0 = 240;
src_screen16 += ((h1-h0)>>1)*1024;
h1 = h0;
}
#else
// Height centering
int sizeShift = 1;
if(h0==256)
h0 = 240;
else
if(h0==480)
sizeShift = 2;
if(h1>h0)
{
src_screen16 += ((h1-h0)>>sizeShift)*1024;
h1 = h0;
}
else
if(h1<h0)
dest_screen16 += ((h0-h1)>>sizeShift)*PSX4ALL_WIDTH;
/* Main blitter */
int incY = (h0==480) ? 2 : 1;
#endif
#if 0 //def PANDORA
//printf("w0 %u h1 %u isRGB24 %u\n", w0, h1, isRGB24);
void (*GPU_Blitter)(void* src, u16* dst16, u32 height);
switch( w0 )
{
case 256:
if(h1 <= 240)
{
GPU_Blitter = GPU_Blit_256_240_ROT90CW_2X;
}
else if(h1 <= 480)
{
GPU_Blitter = GPU_Blit_256_480_ROT90CW_2X;
}
break;
case 368:
if(h1 <= 240)
{
GPU_Blitter = GPU_Blit_368_240_ROT90CW_2X;
}
else if(h1 <= 480)
{
GPU_Blitter = GPU_Blit_368_480_ROT90CW_2X;
}
break;
case 320:
if(h1 <= 240)
{
GPU_Blitter = GPU_Blit_320_240_ROT90CW_2X;
}
else if(h1 <= 480)
{
GPU_Blitter = GPU_Blit_320_480_ROT90CW_2X;
}
break;
case 384:
if(h1 <= 240)
{
GPU_Blitter = GPU_Blit_384_240_ROT90CW_2X;
}
else if(h1 <= 480)
{
GPU_Blitter = GPU_Blit_384_480_ROT90CW_2X;
}
break;
case 512:
if(h1 <= 240)
{
GPU_Blitter = GPU_Blit_512_240_ROT90CW_2X;
}
else if(h1 <= 480)
{
GPU_Blitter = GPU_Blit_512_480_ROT90CW_2X;
}
break;
case 640:
if(h1 <= 480) GPU_Blitter = GPU_Blit_640_480_ROT90CW;
else return;
break;
default: return;
}
/* Blit span */
GPU_Blitter(src_screen16, dest_screen16, h1);
#else
//y0 -= framesProgresiveInt ? incY : 0;
for(int y1=y0+h1; y0<y1; y0+=incY)
{
/* Blit span */
switch( w0 )
{
case 256:
if( 0 == (y0&linesInterlace) )
GPU_BlitWWDWW( src_screen16, dest_screen16, isRGB24);
break;
case 368:
if( 0 == (y0&linesInterlace) )
GPU_BlitWWWWWWWWS( src_screen16, dest_screen16, isRGB24, 4);
break;
case 320:
if( 0 == (y0&linesInterlace) )
GPU_BlitWW( src_screen16, dest_screen16, isRGB24);
break;
case 384:
if( 0 == (y0&linesInterlace) )
GPU_BlitWWWWWS( src_screen16, dest_screen16, isRGB24);
break;
case 512:
if( 0 == (y0&linesInterlace) )
GPU_BlitWS( src_screen16, dest_screen16, isRGB24);
break;
case 640:
if( 0 == (y0&linesInterlace) )
GPU_BlitWS( src_screen16, dest_screen16, isRGB24);
break;
}
dest_screen16 += PSX4ALL_WIDTH;
src_screen16 += h0==480 ? 2048 : 1024;
}
#endif
#ifdef ZAURUS
if(SDL_MUSTLOCK(gp2x_sdlwrapper_screen)) SDL_UnlockSurface(gp2x_sdlwrapper_screen);
#endif
/* DEBUG
gp2x_printf(NULL, 0, 10, "WIDTH %d HEIGHT %d", w0, h1 );
gp2x_video_flip();
*/
}
int curDelay = 0 ;
int curDelay_inc = gp2x_timer_raw_second()/1000;
int skCount = 0;
int skRate = 0;
///////////////////////////////////////////////////////////////////////////////
void gpuSkipUpdate()
{
++frameRateCounter;
isNewDisplay = false;
static u32 s_LastFrame=0;
u32 curFlip = gp2x_timer_raw();
u32 curFrame = curFlip-s_LastFrame;
if(!isSkip)
{
++frameRealCounter;
gpuVideoOutput();
#ifndef PANDORA
if(DisplayArea[3] == 480) // if 480 we only nees 1 of of 2 lines
{
linesInterlace = 1;
}
else
#endif
if( linesInterlace != linesInterlace_user )
{
linesInterlace = linesInterlace_user;
gp2x_video_RGB_clearscreen16();
}
}
curFlip = gp2x_timer_raw()-curFlip;
if( displayFrameInfo && (!isSkip))
{
int ypos = 0;
gp2x_printf(NULL, 0, ypos,"VS:%04.4g fps:%04.4g real:%04.4g fs(%d/%d) (%3d,%2d,%2d)ms", float(vsincRate)/100.0f, float(frameRate)/100.0f, float(realRate)/100.0f, skipCount, skipRate, gp2x_timer_raw_to_ticks(curFrame),gp2x_timer_raw_to_ticks(curFlip),gp2x_timer_raw_to_ticks(curDelay));
#ifdef ENABLE_GPU_PRIM_STATS
int polis = statF3 + statFT3 + statG3 + statGT3;
gp2x_printf(NULL, 0,(ypos+=10),"PPF (%4d): PPS (%5d): ", polis, (polis*realRate)/100 );
gp2x_printf(NULL, 0,(ypos+=10),"types F(%4d) FT(%4d) G(%4d) GT(%4d)", statF3, statFT3, statG3, statGT3);
#endif
#ifdef ENABLE_GPU_PROFILLER
if(displayGpuStats)
{
gp2x_printf(NULL, 0,(ypos+=10),"dmaChainTime (%5d): %04.4g%% (%3dms)", dmaChainCount, PROFILE_RATIO((100*dmaChainTime ),curFrame), gp2x_timer_raw_to_ticks(dmaChainTime) );
gp2x_printf(NULL, 0,(ypos+=10),"gpuPolyTime (%5d): %04.4g%% (%3dms)", gpuPolyCount, PROFILE_RATIO((100*gpuPolyTime ),curFrame), gp2x_timer_raw_to_ticks(gpuPolyTime) );
gp2x_printf(NULL, 0,(ypos+=10),"gpuPixelTime (%5d): %04.4g%% (%3dms)", gpuPixelCount, PROFILE_RATIO((100*gpuPixelTime ),curFrame), gp2x_timer_raw_to_ticks(gpuPixelTime) );
gp2x_printf(NULL, 0,(ypos+=10),"gpuRasterTime(%5d): %04.4g%% (%3dms)", gpuRasterCount, PROFILE_RATIO((100*gpuRasterTime),curFrame), gp2x_timer_raw_to_ticks(gpuRasterTime));
gp2x_printf(NULL, 0,(ypos+=10),"dmaMemTime (%5d): %04.4g%% (%3dms)", dmaMemCount, PROFILE_RATIO((100*dmaMemTime), curFrame), gp2x_timer_raw_to_ticks(dmaMemTime) );
}
#endif
}
PROFILE_RESET(gpuPolyTime,gpuPolyCount);
PROFILE_RESET(gpuRasterTime,gpuRasterCount);
PROFILE_RESET(gpuPixelTime,gpuPixelCount);
PROFILE_RESET(dmaChainTime,dmaChainCount);
PROFILE_RESET(dmaMemTime,dmaMemCount);
statF3 = statFT3 = statG3 = statGT3 = 0;
statLF = statLG = statS = statT = 0;
if(!isSkip)
gp2x_video_flip();
s_LastFrame = gp2x_timer_raw();
if(skCount-->0)
{
isSkip = 1;
}
else
{
isSkip = 0;
}
if(--skRate<=0)
{
skCount = Min2(skipCount,skipRate?skipRate-1:0);
skRate = skipRate;
}
}
///////////////////////////////////////////////////////////////////////////////
void NEWGPU_vSinc(void)
{
u32 newtime;
u32 diffintime = 0;
/* NOTE: GP1 must have the interlace bit toggle here,
since it shouldn't be in readStatus as it was previously */
GPU_GP1 ^= 0x80000000;
if ( (GPU_GP1&0x08000000) ) // dma transfer NO update posible...
return;
if ( (GPU_GP1&0x00800000) ) // Display disabled
return;
++vsincRateCounter;
gpuSkipUpdate();
if(curDelay>0)
gp2x_timer_delay(curDelay);
newtime = gp2x_timer_raw();
if( (diffintime=newtime-systime) >= (gp2x_timer_raw_second()) ) // poll 2 times per second
{
vsincRate = (u64)(vsincRateCounter*100)*gp2x_timer_raw_second() / diffintime;
frameRate = (u64)(frameRateCounter*100)*gp2x_timer_raw_second() / diffintime;
realRate = (u64)(frameRealCounter*100)*gp2x_timer_raw_second() / diffintime;
if(enableFrameLimit && frameRate)
{
int inc = gp2x_timer_raw_second() > 1000 ? gp2x_timer_raw_second()/5000 : gp2x_timer_raw_second()/1000;
int target =(isPAL==0 ? 60 : 50) * 100;
int range = target*5/100;
if(vsincRate>(target+range))
{
curDelay_inc = (curDelay_inc>0) ? (curDelay_inc+inc) : (-curDelay_inc);
curDelay += curDelay_inc;
}
else
if(vsincRate<(target-range))
{
curDelay_inc = (curDelay_inc<0) ? (curDelay_inc-inc) : (-curDelay_inc);
curDelay += curDelay_inc;
}
}
vsincRateCounter = 0;
frameRateCounter = 0;
frameRealCounter = 0;
systime = gp2x_timer_raw();
}
}
| [
"jars@jars-desktop.(none)"
]
| [
[
[
1,
398
]
]
]
|
52348894a8557d1185242496207df84d105b63f8 | 1dc1a820005cbe08729bac511e81e5d4658b97a9 | /demos/win32/win32_graphics.cpp | f9dd88ef001dd8bf83b3f149b7f5cfc49789ad98 | [
"BSD-3-Clause"
]
| permissive | b-xiang/graphin | 0afed6df7e457cc3ff5a71a7ce848f6edcfc708b | f5dcfcd1a06d0085442c855dc30b3ee017ecc9f7 | refs/heads/master | 2021-05-29T14:13:48.354322 | 2011-03-11T21:59:36 | 2011-03-11T21:59:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 149 | cpp | #include "win32.h"
#include "mm_file.h"
#include <direct.h>
#include "window.h"
void graphic_paint(WINDOW_ON_PAINT_PARAMS* p)
{
}
| [
"andrew.fedoniouk@8bb2f294-2c31-0410-96cb-115bfb752b6e"
]
| [
[
[
1,
13
]
]
]
|
79d4cf9475b576e6f4a8a4a69c0979dfa0a34c07 | ef1ad93a27524000ba8f99fcdf217136ceebb3c1 | /inifile.h | 61d3a02ade655f9821d6a5847a707be736fa7e09 | []
| no_license | capnjj/taiga-wizard | 1c2ade791544a02b694fd4da312e70aef560fd23 | ea3835bd64cbe57e0ce22af9ced262b5ff3f00fd | refs/heads/master | 2021-01-18T05:15:13.284903 | 2010-08-27T14:52:49 | 2010-08-27T14:52:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 146 | h | #ifndef INIFILE_H
#define INIFILE_H
class IniFile
{
public:
IniFile();
void Load();
void Save();
};
#endif // INIFILE_H
| [
"[email protected]"
]
| [
[
[
1,
12
]
]
]
|
73a777cc5db7a414d088cc445ec3df7b48b538be | 9d1cb48ec6f6c1f0e342f0f8f819cbda74ceba6e | /src/WebFileOpenDlg.cpp | bb32d29e398418cb1248d61b6c4882e2b5ae3b80 | []
| no_license | correosdelbosque/veryie | e7a5ad44c68dc0b81d4afcff3be76eb8f83320ff | 6ea5a68d0a6eb6c3901b70c2dc806d1e2e2858f1 | refs/heads/master | 2021-01-10T13:17:59.755108 | 2010-06-16T04:23:26 | 2010-06-16T04:23:26 | 53,365,953 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,673 | cpp | // WebFileOpenDlg.cpp : implementation file
//
#include "stdafx.h"
#include "VeryIE.h"
#include "WebFileOpenDlg.h"
#include "mainfrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//#pragma optimize( "s", on)
/////////////////////////////////////////////////////////////////////////////
// CWebFileOpenDlg dialog
CWebFileOpenDlg::CWebFileOpenDlg(CWnd* pParent /*=NULL*/)
: CDialog(CWebFileOpenDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CWebFileOpenDlg)
m_strAddress = _T("");
m_bOpenInNew = TRUE;
m_bDirectOpenFile = FALSE;
//}}AFX_DATA_INIT
}
void CWebFileOpenDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CWebFileOpenDlg)
DDX_Control(pDX, IDC_ADDRESS, m_conAddress);
DDX_CBString(pDX, IDC_ADDRESS, m_strAddress);
DDX_Check(pDX, IDC_OPEN_IN_NEW, m_bOpenInNew);
DDX_Check(pDX, IDC_DIRECT_OPEN_FILE, m_bDirectOpenFile);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CWebFileOpenDlg, CDialog)
//{{AFX_MSG_MAP(CWebFileOpenDlg)
ON_BN_CLICKED(IDC_BROWSE, OnBrowse)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CWebFileOpenDlg message handlers
typedef HRESULT (CALLBACK* LPFNDLLFUNC1)(HWND ,DWORD);
BOOL CWebFileOpenDlg::OnInitDialog()
{
#ifdef _WRITE_LNG_FILE_
_WriteDlgString(this,"DialogOpenFile");
this->OnCancel();
return TRUE;
#endif
LOADDLG("DialogOpenFile");
CDialog::OnInitDialog();
// TODO: Add extra initialization here
CImageList img;
img.Create(16, 16, ILC_COLORDDB|ILC_MASK, 2, 1);
HBITMAP hbmp = pmf->GetBitmap("FavBar.bmp");
ImageList_AddMasked(img.GetSafeHandle(), hbmp, RGB(255,0,255));
DeleteObject(hbmp);
m_conAddress.SetImageList(&img);
img.Detach();
m_conAddress.SetExtendedStyle(0, m_conAddress.GetExtendedStyle()|CBES_EX_NOSIZELIMIT);
//auto complete
HINSTANCE hIns = LoadLibrary("shlwapi.dll");
if(hIns != NULL)
{
LPFNDLLFUNC1 lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(hIns, "SHAutoComplete");
if(lpfnDllFunc1!=NULL)
lpfnDllFunc1(m_conAddress.GetEditCtrl()->m_hWnd, 0xe);
FreeLibrary(hIns);
}
//typed urls
TCHAR sz[MAX_PATH];
HKEY hKey;
DWORD dwSize;
TCHAR id[9] = "url";
int i = 1;
if(RegOpenKey(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Internet Explorer\\TypedUrls"), &hKey) != ERROR_SUCCESS)
{
TRACE0("Typed URLs not found\n");
return TRUE;
}
dwSize = MAX_PATH-1;
itoa(i, id+3, 10);
COMBOBOXEXITEM item;
item.mask = CBEIF_TEXT|CBEIF_IMAGE|CBEIF_SELECTEDIMAGE ;
item.iImage = 1;
item.iSelectedImage = 1;
dwSize = sizeof(sz);
while(RegQueryValueEx(hKey, _T(id), NULL, NULL, (LPBYTE)sz, &dwSize) == ERROR_SUCCESS)
{
item.iItem = i-1;
item.pszText = (LPTSTR)(LPCTSTR)sz;
m_conAddress.InsertItem(&item);
i++;
itoa(i, id+3, 10);
dwSize = MAX_PATH - 1;
}
RegCloseKey(hKey);
if (m_bDirectOpenFile)
{
OnBrowse();
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CWebFileOpenDlg::OnBrowse()
{
// TODO: Add your control notification handler code here
CString str;
LOADSTR(str ,IDS_TYPE_OPENFILE);
CFileDialog fileDlg(TRUE, NULL, NULL, OFN_HIDEREADONLY, str);
if(fileDlg.DoModal() == IDOK)
{
m_conAddress.GetEditCtrl()->SetWindowText(fileDlg.GetPathName());
UpdateData(TRUE);
//
if (m_bDirectOpenFile)
{
if (m_strAddress.GetLength())
CDialog::OnOK();
}
}
}
//#pragma optimize( "s", off)
| [
"songbohr@af2e6244-03f2-11de-b556-9305e745af9e"
]
| [
[
[
1,
146
]
]
]
|
359a3a34a00a368abd4fd0d9ca528239ec27e99b | df31fa6034f82e637d6ee497db636f1194dff8cd | /src/sn_rigSolvers/sn_slidecurve_op.cpp | f109eb52dfe02f3ab8cc631273c1c0b2820e80e8 | []
| no_license | UIKit0/Gear | 7afbf5d9f82a5b787b38d5bc5532907af4b85c35 | 7b1acdf1f7bba54c07079bce9fb8f83a68674347 | refs/heads/master | 2021-01-21T22:10:34.120846 | 2010-11-24T10:01:52 | 2010-11-24T10:01:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,335 | cpp | /*
This file is part of GEAR.
GEAR is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/lgpl.html>.
Author: Helge Mathee, Jeremie Passerin [email protected], [email protected]
BetaTester: Miquel Campos
Company: Studio Nest (TM)
Date: 2010 / 11 / 15
*/
#include <xsi_application.h>
#include <xsi_context.h>
#include <xsi_factory.h>
#include <xsi_pluginregistrar.h>
#include <xsi_status.h>
#include <xsi_customoperator.h>
#include <xsi_customproperty.h>
#include <xsi_operatorcontext.h>
#include <xsi_ppglayout.h>
#include <xsi_ppgeventcontext.h>
#include <xsi_primitive.h>
#include <xsi_kinematics.h>
#include <xsi_kinematicstate.h>
#include <xsi_math.h>
#include <xsi_doublearray.h>
#include <xsi_nurbscurvelist.h>
#include <xsi_nurbscurve.h>
#include <xsi_nurbssurfacemesh.h>
#include <xsi_nurbssurface.h>
#include <xsi_controlpoint.h>
#include <xsi_inputport.h>
#include <xsi_outputport.h>
#include <xsi_vector3.h>
#include <vector>
using namespace XSI;
using namespace MATH;
///////////////////////////////////////////////////////////////
// STRUCT
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
// DEFINE METHODS
///////////////////////////////////////////////////////////////
XSIPLUGINCALLBACK CStatus sn_curveslide_op_Define( CRef& in_ctxt );
XSIPLUGINCALLBACK CStatus sn_curveslide_op_DefineLayout( CRef& in_ctxt );
XSIPLUGINCALLBACK CStatus sn_curveslide_op_Update( CRef& in_ctxt );
XSIPLUGINCALLBACK CStatus sn_curveslide2_op_Define( CRef& in_ctxt );
XSIPLUGINCALLBACK CStatus sn_curveslide2_op_DefineLayout( CRef& in_ctxt );
XSIPLUGINCALLBACK CStatus sn_curveslide2_op_Update( CRef& in_ctxt );
double max(double a,double b);
double min(double a, double b);
///////////////////////////////////////////////////////////////
// CURVE SLIDE OP
///////////////////////////////////////////////////////////////
// Define =====================================================
XSIPLUGINCALLBACK CStatus sn_curveslide_op_Define( CRef& in_ctxt )
{
Context ctxt( in_ctxt );
CustomOperator op;
Parameter param;
CRef pdef;
Factory oFactory = Application().GetFactory();
op = ctxt.GetSource();
pdef = oFactory.CreateParamDef(L"length",CValue::siDouble,siPersistable | siAnimatable,L"",L"",1,0.01,10000,1,24);
op.AddParameter(pdef,param);
pdef = oFactory.CreateParamDef(L"factor",CValue::siDouble,siPersistable | siAnimatable,L"",L"",1,0,100,0,1);
op.AddParameter(pdef,param);
pdef = oFactory.CreateParamDef(L"center",CValue::siDouble,siPersistable | siAnimatable,L"",L"",0,0,1,0,1);
op.AddParameter(pdef,param);
op.PutAlwaysEvaluate(false);
op.PutDebug(0);
return CStatus::OK;
}
// Define Layout ==============================================
XSIPLUGINCALLBACK CStatus sn_curveslide_op_DefineLayout( CRef& in_ctxt )
{
Context ctxt( in_ctxt );
PPGLayout layout;
PPGItem oItem;
layout = ctxt.GetSource();
layout.Clear();
layout.AddItem(L"length",L"Length");
layout.AddItem(L"factor",L"Strength");
layout.AddItem(L"center",L"Center");
return CStatus::OK;
}
// Update =====================================================
XSIPLUGINCALLBACK CStatus sn_curveslide_op_Update( CRef& in_ctxt )
{
OperatorContext ctxt( in_ctxt );
double length = ctxt.GetParameterValue(L"length");
double factor = ctxt.GetParameterValue(L"factor");
double center = ctxt.GetParameterValue(L"center");
Primitive curvePrim = (CRef)ctxt.GetInputValue(0);
NurbsCurveList curveGeo(curvePrim.GetGeometry());
NurbsCurve curve(curveGeo.GetCurves()[0]);
double curr_length = 0;
curveGeo.GetLength(curr_length);
double ratio = 1.0 + (length / curr_length - 1.0) * factor;
double shift = 100.0 * (1.0 - ratio) * center;
CControlPointRefArray curvePnts(curveGeo.GetControlPoints());
CVector3Array curvePos = curvePnts.GetPositionArray();
LONG curve_index;
double curve_u;
double curve_per;
double curve_dist;
CVector3 curve_pos;
CVector3 curve_tan;
CVector3 curve_nor;
CVector3 curve_bin;
for(LONG i=0;i<curvePos.GetCount();i++)
{
curveGeo.GetClosestCurvePosition(curvePos[i],curve_index,curve_dist,curve_u,curve_pos);
curve.GetPercentageFromU(curve_u,curve_per);
curve_per = curve_per * ratio + shift;
if(curve_per < 0.0)
curve_per = 0.0;
else if(curve_per > 100.0)
curve_per = 100.0;
curve.EvaluatePositionFromPercentage(curve_per,curve_pos,curve_tan,curve_nor,curve_bin);
curvePos[i] = curve_pos;
}
Primitive outPrim(ctxt.GetOutputTarget());
NurbsCurveList outGeo(outPrim.GetGeometry());
outGeo.GetControlPoints().PutPositionArray(curvePos);
return CStatus::OK;
}
///////////////////////////////////////////////////////////////
// CURVE SLIDE 2 OP
///////////////////////////////////////////////////////////////
// Define =====================================================
XSIPLUGINCALLBACK CStatus sn_curveslide2_op_Define( CRef& in_ctxt )
{
Context ctxt( in_ctxt );
CustomOperator op;
Parameter param;
CRef pdef;
Factory oFactory = Application().GetFactory();
op = ctxt.GetSource();
pdef = oFactory.CreateParamDef(L"slvlength",CValue::siDouble,siPersistable | siAnimatable,L"",L"",1,0.01,10000,1,24);
op.AddParameter(pdef,param);
pdef = oFactory.CreateParamDef(L"mstlength",CValue::siDouble,siPersistable | siAnimatable,L"",L"",1,0.01,10000,1,24);
op.AddParameter(pdef,param);
pdef = oFactory.CreateParamDef(L"position",CValue::siDouble,siPersistable | siAnimatable,L"",L"",0,0,1,0,1);
op.AddParameter(pdef,param);
pdef = oFactory.CreateParamDef(L"maxstretch",CValue::siDouble,siPersistable | siAnimatable,L"",L"",1,1,10000,1,3);
op.AddParameter(pdef,param);
pdef = oFactory.CreateParamDef(L"maxsquash",CValue::siDouble,siPersistable | siAnimatable,L"",L"",1,0,1,0,1);
op.AddParameter(pdef,param);
pdef = oFactory.CreateParamDef(L"softness",CValue::siDouble,siPersistable | siAnimatable,L"",L"",0,0,1,0,1);
op.AddParameter(pdef,param);
op.PutAlwaysEvaluate(false);
op.PutDebug(0);
return CStatus::OK;
}
// Define Layout ==============================================
XSIPLUGINCALLBACK CStatus sn_curveslide2_op_DefineLayout( CRef& in_ctxt )
{
Context ctxt( in_ctxt );
PPGLayout layout;
PPGItem oItem;
layout = ctxt.GetSource();
layout.Clear();
layout.AddGroup("Default");
layout.AddItem(L"slvlength", L"Slave Length");
layout.AddItem(L"mstlength", L"Master Length");
layout.EndGroup();
layout.AddGroup("Animate");
layout.AddItem(L"position", L"Position");
layout.AddItem(L"maxstretch", L"Max Stretch");
layout.AddItem(L"maxsquash", L"Max Squash");
layout.AddItem(L"softness", L"Softness");
layout.EndGroup();
return CStatus::OK;
}
// Update =====================================================
XSIPLUGINCALLBACK CStatus sn_curveslide2_op_Update( CRef& in_ctxt )
{
OperatorContext ctxt( in_ctxt );
double slvlength = ctxt.GetParameterValue(L"slvlength"); // Length of the constrained curve
double mstlength = ctxt.GetParameterValue(L"mstlength"); // Rest length of the Master Curve
double position = ctxt.GetParameterValue(L"position");
double maxstretch = ctxt.GetParameterValue(L"maxstretch");
double maxsquash = ctxt.GetParameterValue(L"maxsquash");
double softness = ctxt.GetParameterValue(L"softness");
Primitive slvPrim = (CRef)ctxt.GetInputValue(0);
NurbsCurveList slvGeo(slvPrim.GetGeometry());
NurbsCurve slvCrv(slvGeo.GetCurves()[0]);
Primitive mstPrim = (CRef)ctxt.GetInputValue(1);
NurbsCurveList mstGeo(mstPrim.GetGeometry());
NurbsCurve mstCrv(mstGeo.GetCurves()[0]);
// Inputs ---------------------------------------------------------
double mstCrvLength = 0;
mstCrv.GetLength(mstCrvLength);
int slvPointCount = CControlPointRefArray(slvGeo.GetControlPoints()).GetCount();
int mstPointCount = CControlPointRefArray(mstGeo.GetControlPoints()).GetCount();
// Stretch --------------------------------------------------------
double expo, ext;
if ((mstCrvLength > mstlength) && (maxstretch > 1))
{
if (softness == 0)
expo = 1;
else
{
double stretch = (mstCrvLength - mstlength) / (slvlength * maxstretch);
expo = 1 - exp(-(stretch) / softness);
}
ext = min(slvlength * (maxstretch - 1) * expo, mstCrvLength - mstlength);
slvlength += ext;
}
else if ((mstCrvLength < mstlength) && (maxsquash < 1))
{
if (softness == 0)
expo = 1;
else
{
double squash = (mstlength - mstCrvLength) / (slvlength * maxsquash);
expo = 1 - exp(-(squash) / softness);
}
ext = min(slvlength * (1 - maxsquash) * expo, mstlength - mstCrvLength);
slvlength -= ext;
}
// Position --------------------------------------------------------
double size = (slvlength / mstCrvLength) * 100;
double sizeLeft = 100 - size;
double start = position * sizeLeft;
double end = start + size;
// Process --------------------------------------------------------
CControlPointRefArray slvPnts(slvGeo.GetControlPoints());
CVector3Array curvePos = slvPnts.GetPositionArray();
double step, perc, overPerc;
CVector3 vPos, vTan, vNor, vBin;
for(LONG i = 0; i < slvPointCount; i++)
{
step = (end - start) / (slvPointCount - 1.0);
perc = start + (i * step);
if ((0 <= perc) && (perc <= 100))
mstCrv.EvaluatePositionFromPercentage(perc, vPos, vTan, vNor, vBin);
else
{
if (perc < 0)
{
overPerc = perc;
mstCrv.EvaluatePositionFromPercentage(0, vPos, vTan, vNor, vBin);
}
else
{
overPerc = perc - 100;
mstCrv.EvaluatePositionFromPercentage(100, vPos, vTan, vNor, vBin);
}
vTan.ScaleInPlace((mstCrvLength / 100.0) * overPerc);
vPos.AddInPlace(vTan);
}
curvePos[i] = vPos;
}
// Out ------------------------------------------------------------
Primitive outPrim(ctxt.GetOutputTarget());
NurbsCurveList outGeo(outPrim.GetGeometry());
outGeo.GetControlPoints().PutPositionArray(curvePos);
return CStatus::OK;
}
| [
"[email protected]"
]
| [
[
[
1,
323
]
]
]
|
2e63b59f72f775dcb78219855973465ad4f9949c | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/UIDomain.cpp | 927ddb84875c686d8681045f41137df95eb25376 | []
| no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | cpp | #include <Halak/PCH.h>
#include <Halak/UIDomain.h>
#include <Halak/UIWindow.h>
namespace Halak
{
UIDomain::UIDomain()
: root(nullptr)
{
}
UIDomain::UIDomain(UIWindow* root)
: root(root)
{
}
UIDomain::~UIDomain()
{
}
void UIDomain::SetRoot(UIWindow* value)
{
root = value;
}
} | [
"[email protected]"
]
| [
[
[
1,
25
]
]
]
|
ff015a39dec5f6656a85102b7272a9ac0561b5eb | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/Code/Flosti Engine/PhysX/PhysicTriggerReport.cpp | 111adfd6a4769a8ba859b58beb5fdbf61718d8d3 | []
| 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,024 | cpp | #include "__PCH_PhysX.h"
#include "PhysicTriggerReport.h"
#include "PhysX/PhysicsManager.h"
void CPhysicTriggerReport::onTrigger( NxShape& triggerShape, NxShape& otherShape, NxTriggerFlag status )
{
if(status & NX_TRIGGER_ON_ENTER)
{
//A body entered the trigger area for the first time
NxActor* actor = &triggerShape.getActor();
CPhysicUserData* entity_trigger1= (CPhysicUserData*)actor->userData;
actor = &otherShape.getActor();
CPhysicUserData* entity_trigger2= (CPhysicUserData*)actor->userData;
OnEnter(entity_trigger1, entity_trigger2);
}
if(status & NX_TRIGGER_ON_LEAVE)
{
NxActor* actor = &triggerShape.getActor();
CPhysicUserData* entity_trigger1= (CPhysicUserData*)actor->userData;
actor = &otherShape.getActor();
CPhysicUserData* entity_trigger2= (CPhysicUserData*)actor->userData;
OnLeave(entity_trigger1, entity_trigger2);
}
} | [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
26
]
]
]
|
3066a35ac4df140b13fefe09fd38b0076e36e3c0 | 6f796044ae363f9ca58c66423c607e3b59d077c7 | /source/Gui/GuiFonts.h | 40c2193a0bfda859d9be0dc989ed89663b05708b | []
| no_license | Wiimpathy/bluemsx-wii | 3a68d82ac82268a3a1bf1b5ca02115ed5e61290b | fde291e57fe93c0768b375a82fc0b62e645bd967 | refs/heads/master | 2020-05-02T22:46:06.728000 | 2011-10-06T20:57:54 | 2011-10-06T20:57:54 | 178,261,485 | 2 | 0 | null | 2019-03-28T18:32:30 | 2019-03-28T18:32:30 | null | UTF-8 | C++ | false | false | 254 | h | #ifndef _GUI_FONTS_H
#define _GUI_FONTS_H
class TextRender;
class GuiRootContainer;
extern TextRender *g_fontArial;
extern TextRender *g_fontImpact;
extern void GuiFontInit(void);
extern void GuiFontClose(GuiRootContainer *root);
#endif
| [
"timbrug@c2eab908-c631-11dd-927d-974589228060",
"[email protected]"
]
| [
[
[
1,
4
],
[
6,
10
],
[
12,
13
]
],
[
[
5,
5
],
[
11,
11
]
]
]
|
526f94a7d4fd6a8c7068f05b2cbd91069b8e1cd7 | 17558c17dbc37842111466c43add5b31e3f1b29b | /debug/moc_portlistener.cpp | b88686100d38049dbb69c0d19c68bd76674b4af2 | []
| no_license | AeroWorks/inav | 5c61b6c7a5af1a3f99009de8e177a2ceff3447b0 | 5a97aaca791026d9a09c2273c37e237b18b9cb35 | refs/heads/master | 2020-09-05T23:45:11.561252 | 2011-04-24T01:53:22 | 2011-04-24T01:53:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,163 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'portlistener.h'
**
** Created: Sun 14. Feb 18:43:45 2010
** by: The Qt Meta Object Compiler version 62 (Qt 4.6.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../device/portlistener.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'portlistener.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.6.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_PortListener[] = {
// content:
4, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_PortListener[] = {
"PortListener\0"
};
const QMetaObject PortListener::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_PortListener,
qt_meta_data_PortListener, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &PortListener::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *PortListener::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *PortListener::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_PortListener))
return static_cast<void*>(const_cast< PortListener*>(this));
return QObject::qt_metacast(_clname);
}
int PortListener::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
b0f2649f2354051340f3abcc92ae5cf91ff68c18 | ea02e41514b3b979c78af4ea7b5c55e99834036b | /GetNetSdkLocation/MFConRegEditor.cpp | ac72b8febc01222970b03a6c28fd38809a59d89b | []
| no_license | isabella232/wintools | 446228b88eb4296633b0c2be05c18fe291d6b5d2 | 203f7b550c0a1660306d4cc0606b1dc6289e8d9a | refs/heads/master | 2022-02-23T13:02:25.859592 | 2010-04-07T16:45:52 | 2010-04-07T16:45:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,387 | cpp | // MFConRegEditor.cpp: implementation of the CMFConRegEditor class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MFConRegEditor.h"
#include <aclapi.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMFConRegEditor::CMFConRegEditor()
{
m_RegKey = NULL;
}
CMFConRegEditor::CMFConRegEditor(LPCTSTR strKeyName)
{
DWORD dwDisposition;
long lRc;
lRc = RegCreateKeyEx(
HKEY_LOCAL_MACHINE, // handle to an open key
strKeyName, // address of subkey name
0, // reserved
_T("Key"), // address of class string
REG_OPTION_NON_VOLATILE, // special options flag
KEY_ALL_ACCESS, // desired security access
NULL, // address of key security structure
&m_RegKey, // address of buffer for opened handle
&dwDisposition // address of disposition value buffer
);
}
CMFConRegEditor::~CMFConRegEditor()
{
if(m_RegKey != NULL)
RegCloseKey(m_RegKey);
}
BOOL CMFConRegEditor::Open(LPCTSTR strKeyName, int iAccMode)
{
DWORD dwDisposition, dwAccMode;
long lRc;
switch(iAccMode)
{
case 0:
dwAccMode = KEY_READ;
break;
case 1:
dwAccMode = KEY_ALL_ACCESS;
break;
}
lRc = RegCreateKeyEx(
HKEY_LOCAL_MACHINE, // handle to an open key
strKeyName, // address of subkey name
0, // reserved
_T("Key"), // address of class string
REG_OPTION_NON_VOLATILE, // special options flag
dwAccMode, // desired security access
NULL, // address of key security structure
&m_RegKey, // address of buffer for opened handle
&dwDisposition // address of disposition value buffer
);
if(lRc != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
DWORD CMFConRegEditor::GetValueDw(LPCTSTR strKeyName)
{
DWORD dwRetVal = 0;
long lRc;
DWORD cbData = sizeof(DWORD);
lRc = RegQueryValueEx(
m_RegKey, // handle to key to query
(LPCTSTR) strKeyName, // address of name of value to query
NULL, // reserved
NULL, // address of buffer for value type
(LPBYTE)&dwRetVal, // address of data buffer
&cbData // address of data buffer size
);
if(lRc != ERROR_SUCCESS)
return 0;
return dwRetVal;
}
LPCTSTR CMFConRegEditor::GetValue(LPCTSTR strKeyName)
{
long lRc;
DWORD cbData = 400;
static char szData[400];
lRc = RegQueryValueEx(
m_RegKey, // handle to key to query
(LPCTSTR) strKeyName, // address of name of value to query
NULL, // reserved
NULL, // address of buffer for value type
(LPBYTE)szData, // address of data buffer
&cbData // address of data buffer size
);
if(lRc != ERROR_SUCCESS)
return FALSE;
return (LPCTSTR)szData;
}
BOOL CMFConRegEditor::SetValue(LPCTSTR strKeyName, DWORD* lpdwKeyValue)
{
long lRc;
lRc = RegSetValueEx(
m_RegKey, // handle to key to set value for
strKeyName, // name of the value to set
0, // reserved
REG_DWORD, // flag for value type
(LPBYTE)lpdwKeyValue, // address of value data
sizeof(long) // size of value data
);
if(lRc != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
BOOL CMFConRegEditor::SetValue(LPCTSTR strKeyName, LPCTSTR szKeyValue)
{
long lRc;
int nLen;
nLen = lstrlen(szKeyValue);
lRc = RegSetValueEx(
m_RegKey, // handle to key to set value for
strKeyName, // name of the value to set
0, // reserved
REG_SZ, // flag for value type
(const UCHAR *)szKeyValue, // address of value data
nLen // size of value data
);
if(lRc != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
BOOL CMFConRegEditor::Close()
{
if(m_RegKey != NULL)
{
RegCloseKey(m_RegKey);
m_RegKey = NULL;
}
return TRUE;
}
BOOL CMFConRegEditor::SetSecurity(LPTSTR strUsr)
{
long lRc;
static SECURITY_INFORMATION struSecInfo;
PSECURITY_DESCRIPTOR pSecDesc;
PACL pOldDACL = NULL, pNewDACL = NULL;
EXPLICIT_ACCESS ea;
lRc = GetSecurityInfo(
m_RegKey,
SE_REGISTRY_KEY,
DACL_SECURITY_INFORMATION,
NULL,
NULL,
&pOldDACL,
NULL,
&pSecDesc
);
if(lRc != ERROR_SUCCESS)
return FALSE;
ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
BuildExplicitAccessWithName(
&ea,
strUsr,
GENERIC_ALL,
SET_ACCESS,
SUB_CONTAINERS_AND_OBJECTS_INHERIT
);
lRc = SetEntriesInAcl(1, &ea, pOldDACL, &pNewDACL);
if (ERROR_SUCCESS != lRc)
goto Cleanup;
lRc = SetSecurityInfo(
m_RegKey,
SE_REGISTRY_KEY,
DACL_SECURITY_INFORMATION,
NULL,
NULL,
pNewDACL,
NULL
);
Cleanup:
if(pSecDesc != NULL)
LocalFree((HLOCAL) pSecDesc);
if(pNewDACL != NULL)
LocalFree((HLOCAL) pNewDACL);
if(lRc != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
| [
"[email protected]"
]
| [
[
[
1,
235
]
]
]
|
d68d29350523d956e82cb5c7f4e8ea4ee88230ce | a2904986c09bd07e8c89359632e849534970c1be | /topcoder/TurretPlacement.cpp | e3bb3f88d3547b8d02f77df99b051e2913c91d4a | []
| no_license | naturalself/topcoder_srms | 20bf84ac1fd959e9fbbf8b82a93113c858bf6134 | 7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5 | refs/heads/master | 2021-01-22T04:36:40.592620 | 2010-11-29T17:30:40 | 2010-11-29T17:30:40 | 444,669 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,777 | cpp | // BEGIN CUT HERE
// END CUT HERE
#line 5 "TurretPlacement.cpp"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
using namespace std;
#define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i)
#define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i)
#define all(a) a.begin(), a.end()
class TurretPlacement {
public:
long long count(vector <int> x, vector <int> y) {
}
// 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 long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {0,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0,2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); long long Arg2 = 10LL; verify_case(0, Arg2, count(Arg0, Arg1)); }
void test_case_1() { int Arr0[] = {0,1,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0,1,0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); long long Arg2 = 8LL; verify_case(1, Arg2, count(Arg0, Arg1)); }
void test_case_2() { int Arr0[] = {1,2,3,0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {-1,-5,-7,100}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); long long Arg2 = 65137LL; verify_case(2, Arg2, count(Arg0, Arg1)); }
void test_case_3() { int Arr0[] = {9998,-10000,10000,0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {9998,10000,10000,0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); long long Arg2 = 2799564895LL; verify_case(3, Arg2, count(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
TurretPlacement ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"shin@CF-7AUJ41TT52JO.(none)"
]
| [
[
[
1,
57
]
]
]
|
719306d443196c5dd78855c2d1093007e1dbe730 | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/cmd_line_parser/cmd_line_parser_check_1.h | 79122cefaf9eddee9c2735366c543cad84114474 | [
"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 | 18,491 | h | // Copyright (C) 2006 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_CMD_LINE_PARSER_CHECk_1_
#define DLIB_CMD_LINE_PARSER_CHECk_1_
#include "cmd_line_parser_kernel_abstract.h"
#include <sstream>
#include <string>
#include "../string.h"
#include <vector>
namespace dlib
{
template <
typename clp_base
>
class cmd_line_parser_check_1 : public clp_base
{
/*!
This extension doesn't add any state.
!*/
public:
typedef typename clp_base::char_type char_type;
typedef typename clp_base::string_type string_type;
// ------------------------------------------------------------------------------------
class cmd_line_check_error : public dlib::error
{
friend class cmd_line_parser_check_1;
cmd_line_check_error(
error_type t,
const string_type& opt_,
const string_type& arg_
) :
dlib::error(t),
opt(opt_),
opt2(),
arg(arg_),
required_opts()
{ set_info_string(); }
cmd_line_check_error(
error_type t,
const string_type& opt_,
const string_type& opt2_,
int // this is just to make this constructor different from the one above
) :
dlib::error(t),
opt(opt_),
opt2(opt2_),
arg(),
required_opts()
{ set_info_string(); }
cmd_line_check_error (
error_type t,
const string_type& opt_,
const std::vector<string_type>& vect
) :
dlib::error(t),
opt(opt_),
opt2(),
arg(),
required_opts(vect)
{ set_info_string(); }
cmd_line_check_error(
error_type t,
const string_type& opt_
) :
dlib::error(t),
opt(opt_),
opt2(),
arg(),
required_opts()
{ set_info_string(); }
~cmd_line_check_error() throw() {}
void set_info_string (
)
{
std::ostringstream sout;
switch (type)
{
case EINVALID_OPTION_ARG:
sout << "Command line error: '" << narrow(arg) << "' is not a valid argument to "
<< "the '" << narrow(opt) << "' option.";
break;
case EMISSING_REQUIRED_OPTION:
if (required_opts.size() == 1)
{
sout << "Command line error: The '" << narrow(opt) << "' option requires the presence of "
<< "the '" << required_opts[0] << "' option.";
}
else
{
sout << "Command line error: The '" << narrow(opt) << "' option requires the presence of "
<< "one of the following options: ";
for (unsigned long i = 0; i < required_opts.size(); ++i)
{
if (i == required_opts.size()-2)
sout << "'" << required_opts[i] << "' or ";
else if (i == required_opts.size()-1)
sout << "'" << required_opts[i] << "'.";
else
sout << "'" << required_opts[i] << "', ";
}
}
break;
case EINCOMPATIBLE_OPTIONS:
sout << "Command line error: The '" << narrow(opt) << "' and '" << narrow(opt2)
<< "' options can not be given together on the command line.";
break;
case EMULTIPLE_OCCURANCES:
sout << "Command line error: The '" << narrow(opt) << "' option can only "
<< "be given on the command line once.";
break;
default:
sout << "Command line error.";
break;
}
const_cast<std::string&>(info) = wrap_string(sout.str(),0,0);
}
public:
const string_type opt;
const string_type opt2;
const string_type arg;
const std::vector<string_type> required_opts;
};
// ------------------------------------------------------------------------------------
template <
typename T
>
void check_option_arg_type (
const string_type& option_name
) const;
template <
typename T
>
void check_option_arg_range (
const string_type& option_name,
const T& first,
const T& last
) const;
template <
typename T,
size_t length
>
void check_option_arg_range (
const string_type& option_name,
const T (&arg_set)[length]
) const;
template <
size_t length
>
void check_option_arg_range (
const string_type& option_name,
const char_type* (&arg_set)[length]
) const;
template <
size_t length
>
void check_incompatible_options (
const char_type* (&option_set)[length]
) const;
template <
size_t length
>
void check_one_time_options (
const char_type* (&option_set)[length]
) const;
void check_incompatible_options (
const string_type& option_name1,
const string_type& option_name2
) const;
template <
size_t length
>
void check_sub_options (
const string_type& parent_option,
const char_type* (&sub_option_set)[length]
) const;
template <
size_t length
>
void check_sub_options (
const char_type* (&parent_option_set)[length],
const string_type& sub_option
) const;
template <
size_t parent_length,
size_t sub_length
>
void check_sub_options (
const char_type* (&parent_option_set)[parent_length],
const char_type* (&sub_option_set)[sub_length]
) const;
};
template <
typename clp_base
>
inline void swap (
cmd_line_parser_check_1<clp_base>& a,
cmd_line_parser_check_1<clp_base>& b
) { a.swap(b); }
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
template <typename clp_base>
template <typename T>
void cmd_line_parser_check_1<clp_base>::
check_option_arg_type (
const string_type& option_name
) const
{
try
{
const typename clp_base::option_type& opt = option(option_name);
const unsigned long number_of_arguments = opt.number_of_arguments();
const unsigned long count = opt.count();
for (unsigned long i = 0; i < number_of_arguments; ++i)
{
for (unsigned long j = 0; j < count; ++j)
{
string_cast<T>(opt.argument(i,j));
}
}
}
catch (string_cast_error& e)
{
throw cmd_line_check_error(EINVALID_OPTION_ARG,option_name,e.info);
}
}
// ----------------------------------------------------------------------------------------
template <typename clp_base>
template <typename T>
void cmd_line_parser_check_1<clp_base>::
check_option_arg_range (
const string_type& option_name,
const T& first,
const T& last
) const
{
try
{
const typename clp_base::option_type& opt = option(option_name);
const unsigned long number_of_arguments = opt.number_of_arguments();
const unsigned long count = opt.count();
for (unsigned long i = 0; i < number_of_arguments; ++i)
{
for (unsigned long j = 0; j < count; ++j)
{
T temp(string_cast<T>(opt.argument(i,j)));
if (temp < first || last < temp)
{
throw cmd_line_check_error(
EINVALID_OPTION_ARG,
option_name,
opt.argument(i,j)
);
}
}
}
}
catch (string_cast_error& e)
{
throw cmd_line_check_error(EINVALID_OPTION_ARG,option_name,e.info);
}
}
// ----------------------------------------------------------------------------------------
template <typename clp_base>
template < typename T, size_t length >
void cmd_line_parser_check_1<clp_base>::
check_option_arg_range (
const string_type& option_name,
const T (&arg_set)[length]
) const
{
try
{
const typename clp_base::option_type& opt = option(option_name);
const unsigned long number_of_arguments = opt.number_of_arguments();
const unsigned long count = opt.count();
for (unsigned long i = 0; i < number_of_arguments; ++i)
{
for (unsigned long j = 0; j < count; ++j)
{
T temp(string_cast<T>(opt.argument(i,j)));
size_t k = 0;
for (; k < length; ++k)
{
if (arg_set[k] == temp)
break;
}
if (k == length)
{
throw cmd_line_check_error(
EINVALID_OPTION_ARG,
option_name,
opt.argument(i,j)
);
}
}
}
}
catch (string_cast_error& e)
{
throw cmd_line_check_error(EINVALID_OPTION_ARG,option_name,e.info);
}
}
// ----------------------------------------------------------------------------------------
template <typename clp_base>
template < size_t length >
void cmd_line_parser_check_1<clp_base>::
check_option_arg_range (
const string_type& option_name,
const char_type* (&arg_set)[length]
) const
{
const typename clp_base::option_type& opt = option(option_name);
const unsigned long number_of_arguments = opt.number_of_arguments();
const unsigned long count = opt.count();
for (unsigned long i = 0; i < number_of_arguments; ++i)
{
for (unsigned long j = 0; j < count; ++j)
{
size_t k = 0;
for (; k < length; ++k)
{
if (arg_set[k] == opt.argument(i,j))
break;
}
if (k == length)
{
throw cmd_line_check_error(
EINVALID_OPTION_ARG,
option_name,
opt.argument(i,j)
);
}
}
}
}
// ----------------------------------------------------------------------------------------
template <typename clp_base>
template < size_t length >
void cmd_line_parser_check_1<clp_base>::
check_incompatible_options (
const char_type* (&option_set)[length]
) const
{
for (size_t i = 0; i < length; ++i)
{
for (size_t j = i+1; j < length; ++j)
{
if (option(option_set[i]).count() > 0 &&
option(option_set[j]).count() > 0 )
{
throw cmd_line_check_error(
EINCOMPATIBLE_OPTIONS,
option_set[i],
option_set[j],
0 // this argument has no meaning and is only here to make this
// call different from the other constructor
);
}
}
}
}
// ----------------------------------------------------------------------------------------
template <typename clp_base>
void cmd_line_parser_check_1<clp_base>::
check_incompatible_options (
const string_type& option_name1,
const string_type& option_name2
) const
{
if (option(option_name1).count() > 0 &&
option(option_name2).count() > 0 )
{
throw cmd_line_check_error(
EINCOMPATIBLE_OPTIONS,
option_name1,
option_name2,
0 // this argument has no meaning and is only here to make this
// call different from the other constructor
);
}
}
// ----------------------------------------------------------------------------------------
template <typename clp_base>
template < size_t length >
void cmd_line_parser_check_1<clp_base>::
check_sub_options (
const string_type& parent_option,
const char_type* (&sub_option_set)[length]
) const
{
if (option(parent_option).count() == 0)
{
size_t i = 0;
for (; i < length; ++i)
{
if (option(sub_option_set[i]).count() > 0)
break;
}
if (i != length)
{
std::vector<string_type> vect;
vect.resize(1);
vect[0] = parent_option;
throw cmd_line_check_error( EMISSING_REQUIRED_OPTION, sub_option_set[i], vect);
}
}
}
// ----------------------------------------------------------------------------------------
template <typename clp_base>
template < size_t length >
void cmd_line_parser_check_1<clp_base>::
check_sub_options (
const char_type* (&parent_option_set)[length],
const string_type& sub_option
) const
{
// first check if the sub_option is present
if (option(sub_option).count() > 0)
{
// now check if any of the parents are present
bool parents_present = false;
for (size_t i = 0; i < length; ++i)
{
if (option(parent_option_set[i]).count() > 0)
{
parents_present = true;
break;
}
}
if (!parents_present)
{
std::vector<string_type> vect(parent_option_set, parent_option_set+length);
throw cmd_line_check_error( EMISSING_REQUIRED_OPTION, sub_option, vect);
}
}
}
// ----------------------------------------------------------------------------------------
template <typename clp_base>
template < size_t parent_length, size_t sub_length >
void cmd_line_parser_check_1<clp_base>::
check_sub_options (
const char_type* (&parent_option_set)[parent_length],
const char_type* (&sub_option_set)[sub_length]
) const
{
// first check if any of the parent options are present
bool parents_present = false;
for (size_t i = 0; i < parent_length; ++i)
{
if (option(parent_option_set[i]).count() > 0)
{
parents_present = true;
break;
}
}
if (!parents_present)
{
// none of these sub options should be present
size_t i = 0;
for (; i < sub_length; ++i)
{
if (option(sub_option_set[i]).count() > 0)
break;
}
if (i != sub_length)
{
std::vector<string_type> vect(parent_option_set, parent_option_set+parent_length);
throw cmd_line_check_error( EMISSING_REQUIRED_OPTION, sub_option_set[i], vect);
}
}
}
// ----------------------------------------------------------------------------------------
template <typename clp_base>
template < size_t length >
void cmd_line_parser_check_1<clp_base>::
check_one_time_options (
const char_type* (&option_set)[length]
) const
{
size_t i = 0;
for (; i < length; ++i)
{
if (option(option_set[i]).count() > 1)
break;
}
if (i != length)
{
throw cmd_line_check_error(
EMULTIPLE_OCCURANCES,
option_set[i]
);
}
}
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_CMD_LINE_PARSER_CHECk_1_
| [
"jimmy@DGJ3X3B1.(none)"
]
| [
[
[
1,
554
]
]
]
|
045611bc43de3d1174baffaa8ab5d2773a322944 | 0c84ebd32a2646b5582051216d6e7c8283bb4f23 | /WizAppData.h | 1d7473b05c982d62b7a4a71cb44942d8cdfe714e | []
| no_license | AudioAnecdotes/wxWizApp | 97932d2e6fd2c38934c16629a5e3d6023e0978ac | 129dfad68be44581c97249d2975efca2fa7578b7 | refs/heads/master | 2021-01-18T06:36:29.316270 | 2007-01-02T06:02:13 | 2007-01-02T06:02:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,217 | h | // WizAppData.h: interface for the WizAppData class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_WIZAPPDATA_H__646D1429_ECDD_4BFC_B5D4_2657A418884F__INCLUDED_)
#define AFX_WIZAPPDATA_H__646D1429_ECDD_4BFC_B5D4_2657A418884F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class WizAppData
{
public:
WizAppData();
virtual ~WizAppData();
static int ExplodeList(const wxString str,char sep,wxArrayString& items);
wxString text;
wxString title;
wxString sig;
wxString input; /* Reads from wainput */
wxString fileinput; /* contents of wafile */
wxString file;
wxString sound;
char listsep;
char eol;
int errlevel;
wxString output;
wxString outnum;
int opt_noback;
int opt_finish;
wxString labels;
wxString labelback;
wxString labelnext;
wxString labelfinish;
wxString labelcancel;
wxString labelbrowse;
wxString bat;
wxString bmp;
wxString ico;
wxBitmap bitmap;
wxIcon icon;
protected:
void GetFile();
void GetLabels();
void BuildInputEnvironment();
};
#endif // !defined(AFX_WIZAPPDATA_H__646D1429_ECDD_4BFC_B5D4_2657A418884F__INCLUDED_)
| [
"gsilber"
]
| [
[
[
1,
58
]
]
]
|
a504f00cf727a93e6523ed2258e6aacae6515bd9 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Common/Base/Types/hkBaseTypes.h | 8ac28a6402b071dc660673c41b573f4c48ba50f4 | []
| no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,273 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HKBASE_HKBASETYPES_H
#define HKBASE_HKBASETYPES_H
//
// compiler
//
#if defined(__INTEL_COMPILER)
# define HK_COMPILER_INTEL
#elif defined(_MSC_VER) // Intel compiler defines this too
# define HK_COMPILER_MSVC
#elif defined(__SNC__)
# define HK_COMPILER_SNC
#elif defined(__GNUC__)
# define HK_COMPILER_GCC
#elif defined(__MWERKS__)
# define HK_COMPILER_MWERKS
#else
# error Could not detect compiler
#endif
//
// architecture
//
# define HK_ARCH_IA32
# define HK_ENDIAN_LITTLE 1
# define HK_ENDIAN_BIG 0
# define HK_POINTER_SIZE 4
#if defined(HK_ARCH_PS3) || defined(HK_ARCH_PS3SPU)
# include <sdk_version.h>
# define HK_CELL_SDK_VERSION CELL_SDK_VERSION
# if ( HK_CELL_SDK_VERSION < 0x080000 )
# define HK_POINTER_SIZE 8 // Caution: On SPU the pointer size is 4, but usually where this is used pointers will be "shadows" from the PPU
# else
# define HK_POINTER_SIZE 4
# endif
# define HK_COMPILER_HAS_INTRINSICS_ALTIVEC
#endif
//
// platform
//
#if defined(_WIN32) && !defined(HK_PLATFORM_LRB)
# define HK_PLATFORM_WIN32
# if defined(_WIN64)
# define HK_PLATFORM_X64
# endif
# define HK_PLATFORM_IS_CONSOLE 0
#elif (!defined( R3000 )) && (!defined( __R4000__ )) && (defined( __mips__ ) || defined( __MIPS__ ))
# define HK_PLATFORM_PS2
# define HK_PS2
# define HK_PLATFORM_IS_CONSOLE 1
#elif (defined(__unix__) || defined(__linux__)) && !defined(HK_PLATFORM_LRB)
# define HK_PLATFORM_UNIX
# define HK_PLATFORM_IS_CONSOLE 0
#elif defined(GEKKO) || defined(__PPCGEKKO__) //Also have custom added HK_REVOLUTION compiler switch
# define HK_PLATFORM_GC
# if defined(RVL_OS)
# define HK_PLATFORM_RVL
# endif
# define HK_PLATFORM_IS_CONSOLE 1
#elif defined( R3000 ) || defined( __R4000__ )
# define HK_PLATFORM_PSP
# define HK_PLATFORM_IS_CONSOLE 1
#elif defined(__PPU__) && defined(__CELLOS_LV2__)
# define HK_PLATFORM_PS3_PPU
# define HK_PLATFORM_IS_CONSOLE 1
#elif defined(__SPU__) && defined(__CELLOS_LV2__)
# define HK_PLATFORM_PS3_SPU
# define HK_PLATFORM_SPU
# define HK_PLATFORM_IS_CONSOLE 1
#elif defined(HK_PLATFORM_LRB)
# define HK_PLATFORM_IS_CONSOLE 1
# define HK_PLATFORM_LRBSIM 1
#else
# error Could not autodetect target platform.
#endif
# define HK_ALIGN_OF(T) __alignof(T)
//
// types
//
/// hkReal is the default floating point type.
typedef float hkReal;
/// hkFloat is provided if floats are explicitly required.
typedef float hkFloat32;
/// hkDouble is provided if doubles are explicit required.
typedef double hkDouble64;
/// Signed 8 bit integer
typedef signed char hkChar;
/// Signed 8 bit integer
typedef signed char hkInt8;
/// Signed 16 bit integer
typedef signed short hkInt16;
/// Signed 32 bit integer
typedef signed int hkInt32;
/// Unsigned 8 bit integer
typedef unsigned char hkUchar;
/// Unsigned 8 bit integer
typedef unsigned char hkUint8;
/// Unsigned 16 bit integer
typedef unsigned short hkUint16;
/// Unsigned 32 bit integer
typedef unsigned int hkUint32;
/// An integer type guaranteed to be the same size as a pointer.
#if defined(HK_ARCH_PS2)
typedef unsigned int hkUlong;
typedef signed int hkLong;
#elif defined(HK_ARCH_PSP)
typedef unsigned int hkUlong;
typedef signed int hkLong;
#elif defined(HK_ARCH_X64)
typedef unsigned long hkUlong; // UNIX64
typedef signed long hkLong; // UNIX64
#elif defined(HK_COMPILER_MSVC) && (_MSC_VER >= 1300)
typedef unsigned long __w64 hkUlong; // VC7.0 or higher, 64bit warnings
typedef signed long __w64 hkLong;
#else
typedef unsigned long hkUlong;
typedef signed long hkLong;
#endif
#define HK_CPU_PTR( A ) A
typedef void* hk_va_list;
/// a simple success/failure enum.
enum hkResult
{
HK_SUCCESS = 0,
HK_FAILURE = 1
};
#if defined( HK_PLATFORM_PS3_SPU)
# include <spu_intrinsics.h>
#endif
//
// useful macros
//
#if defined(DEBUG) || defined(_DEBUG) || defined(HK_DEBUG)
# undef HK_DEBUG
# define HK_DEBUG
# define HK_ON_DEBUG(CODE) CODE
#else
# define HK_ON_DEBUG(CODE)
#endif
// use the compiler friendly but programmer ugly version for release only
#ifdef HK_DEBUG
# define HK_MULTILINE_MACRO_BEGIN do {
# define HK_MULTILINE_MACRO_END } while(0)
#else
# if defined(HK_PLATFORM_PS3_PPU ) || defined(HK_PLATFORM_PS3_SPU)
# define HK_MULTILINE_MACRO_BEGIN {
# define HK_MULTILINE_MACRO_END }
# else
# define HK_MULTILINE_MACRO_BEGIN if(1) {
# define HK_MULTILINE_MACRO_END } else
# endif
#endif
# define HK_BREAKPOINT(ID) __asm { int 3 }
#define HK_NULL 0
/// Note that ALIGNMENT must be a power of two for this to work.
/// Note: to use this macro you must cast your pointer to a byte pointer or to an integer value.
#define HK_NEXT_MULTIPLE_OF(ALIGNMENT, VALUE) ( ((VALUE) + ((ALIGNMENT)-1)) & (~((ALIGNMENT)-1)) )
/// The offset of a member within a structure
#define HK_OFFSET_OF(CLASS,MEMBER) int(reinterpret_cast<hkLong>(&(reinterpret_cast<CLASS*>(16)->MEMBER))-16)
/// A check for whether the offset of a member within a structure is as expected
#define HK_OFFSET_EQUALS(CLASS,MEMBER,OFFSET) (HK_OFFSET_OF(CLASS,MEMBER)==OFFSET)
/// Join two preprocessor tokens, even when a token is itself a macro.
#define HK_PREPROCESSOR_JOIN_TOKEN(A,B) HK_PREPROCESSOR_JOIN_TOKEN2(A,B)
#define HK_PREPROCESSOR_JOIN_TOKEN2(A,B) HK_PREPROCESSOR_JOIN_TOKEN3(A,B)
#define HK_PREPROCESSOR_JOIN_TOKEN3(A,B) A##B
/// Creates an uninitialized buffer large enough for object of type TYPE to fit in while aligned to ALIGN boundary. Creates a pointer VAR to this aligned address.
#define HK_DECLARE_ALIGNED_LOCAL_PTR( TYPE, VAR, ALIGN ) \
const int VAR ## BufferSize = ALIGN + sizeof(TYPE); \
char VAR ## Buffer[VAR ## BufferSize]; \
TYPE* VAR = reinterpret_cast<TYPE*>( HK_NEXT_MULTIPLE_OF(ALIGN, hkUlong( VAR ## Buffer )) ); \
//
// compiler specific settings
//
// *************************************
// GCC and SN
// *************************************
# define HK_COMPILER_SUPPORTS_PCH
# define HK_COMPILER_MSVC_VERSION _MSC_VER
# define HK_COMPILER_INTEL_VERSION _MSC_VER
# if (_MSC_VER >= 1400) // 2005 only
# define HK_RESTRICT __restrict
# else
# define HK_RESTRICT
# endif
# pragma warning( disable : 4786 ) // Debug tuncated to 255:
# pragma warning( disable : 4530 ) // C++ Exception handler used but not enabled:(used in <xstring>)
# define HK_ALIGN(DECL, ALIGNMENT) __declspec(align(ALIGNMENT)) DECL
# define HK_ALIGN16(DECL) __declspec(align(16)) DECL
# define HK_ALIGN128(DECL) __declspec(align(128)) DECL
# if !defined(HK_COMPILER_INTEL)
# define HK_FORCE_INLINE __forceinline
# else // ICC has no force inline intrinsic
# define HK_FORCE_INLINE inline
# endif
# define HK_CLASSALIGN(DECL, ALIGNMENT) HK_ALIGN(DECL, ALIGNMENT)
# define HK_CLASSALIGN16(DECL) HK_ALIGN16(DECL)
typedef unsigned __int64 hkUint64;
typedef __int64 hkInt64;
typedef long hkSystemTime;
# if defined(HK_COMPILER_MSVC) && (_MSC_VER >= 1300)
typedef unsigned __w64 hk_size_t; // VC7.0 or higher, 64bit warnings
# else
typedef unsigned hk_size_t;
# endif
# define HK_COMPILER_HAS_INTRINSICS_IA32
// calling convention
# ifndef HK_COMPILER_INTEL
# define HK_CALL __cdecl
# define HK_FAST_CALL __fastcall
# else
# define HK_CALL
# define HK_FAST_CALL
# endif
// deprecation
# if defined(HK_PLATFORM_WIN32) && (_MSC_VER >= 1300) && !defined(MIDL_PASS)
# define HK_DEPRECATED __declspec(deprecated)
# define HK_DEPRECATED2(MSG) __declspec(deprecated(MSG))
# else
# define HK_DEPRECATED /* nothing */
# define HK_DEPRECATED2(MSG) /* nothing */
# endif
// *************************************
// METROWERKS
// *************************************
#if defined(HK_PLATFORM_SIM_PPU) || defined(HK_PLATFORM_SIM_SPU)
# define HK_PLATFORM_SIM
#endif
#if defined(HK_PLATFORM_PS3_PPU) || defined(HK_PLATFORM_PS3_SPU) || defined(HK_PLATFORM_SIM)
# define HK_PLATFORM_HAS_SPU
# define HK_ON_PLATFORM_HAS_SPU(code) code
#else
# define HK_ON_PLATFORM_HAS_SPU(code)
#endif
#if defined(HK_PLATFORM_PS3_PPU) || defined(HK_PLATFORM_WIN32) || defined(HK_PLATFORM_XBOX360) || defined(HK_PLATFORM_MAC386) || defined(HK_PLATFORM_MACPPC) || defined(HK_PLATFORM_UNIX)
# define HK_PLATFORM_MULTI_THREAD
#endif
#if defined(HK_PLATFORM_PS3_PPU) || defined(HK_PLATFORM_PS3_SPU)
# define HK_ALWAYS_INLINE __attribute__((always_inline)) inline
# if !defined (HK_DEBUG)
# define HK_LOCAL_INLINE inline
# else
# define HK_LOCAL_INLINE
# endif
# define HK_ASM_SEP(a) __asm("#*****" a )
#else
# define HK_ALWAYS_INLINE HK_FORCE_INLINE
# define HK_LOCAL_INLINE HK_FORCE_INLINE
# define HK_ASM_SEP(a)
#endif
# define HK_NOSPU_VIRTUAL virtual
#ifndef HK_RESTRICT
# define HK_RESTRICT
#endif
#ifndef HK_VERY_UNLIKELY
# define HK_VERY_UNLIKELY(EXPR) EXPR
# define HK_VERY_LIKELY(EXPR) EXPR
#endif
#ifndef HK_INIT_FUNCTION
# define HK_INIT_FUNCTION( FN ) FN
# define HK_AABB_TREE_FUNCTION( FN ) FN
#endif
typedef hkUint16 hkObjectIndex;
typedef hkReal hkTime;
#define HK_INVALID_OBJECT_INDEX 0xffff
HK_FORCE_INLINE hkInt32 HK_CALL hkPointerToInt32( const void* ptr )
{
return static_cast<int>( hkUlong(ptr) );
}
/// get the byte offset of B - A, as a full long.
HK_FORCE_INLINE hkLong HK_CALL hkGetByteOffset( const void* base, const void* pntr)
{
return hkLong(pntr) - hkLong(base);
}
/// get the byte offset of B - A, as an int (64bit issues, so here for easy code checks)
HK_FORCE_INLINE int HK_CALL hkGetByteOffsetInt( const void* base, const void* pntr)
{
return static_cast<int>( hkGetByteOffset( base, pntr ) );
}
/// get the byte offset of B - A, as a full 64bit hkUint64.
HK_FORCE_INLINE hkInt32 HK_CALL hkGetByteOffsetCpuPtr( const HK_CPU_PTR(void*) base, const HK_CPU_PTR(void*) pntr)
{
return hkInt32(hkLong((HK_CPU_PTR(const char*))(pntr) - (HK_CPU_PTR(const char*))(base)));
}
template <typename TYPE>
HK_ALWAYS_INLINE TYPE* HK_CALL hkAddByteOffset( TYPE* base, hkLong offset )
{
return reinterpret_cast<TYPE*>( reinterpret_cast<char*>(base) + offset );
}
template <typename TYPE>
HK_ALWAYS_INLINE TYPE HK_CALL hkAddByteOffsetCpuPtr( TYPE base, hkLong offset )
{
return reinterpret_cast<TYPE>( reinterpret_cast<char*>(base) + offset );
}
template <typename TYPE>
HK_ALWAYS_INLINE const TYPE* HK_CALL hkAddByteOffsetConst( const TYPE* base, hkLong offset )
{
return reinterpret_cast<const TYPE*>( reinterpret_cast<const char*>(base) + offset );
}
template <typename TYPE>
HK_ALWAYS_INLINE TYPE HK_CALL hkAddByteOffsetCpuPtrConst( TYPE base, hkLong offset )
{
return reinterpret_cast<const TYPE>( reinterpret_cast<const char*>(base) + offset );
}
/// If you have a pair of pointers and you have one pointer, than this function allows you to quickly get the other pointer of the pair.
template <typename TYPE>
HK_ALWAYS_INLINE TYPE HK_CALL hkSelectOther( TYPE a, TYPE pairA, TYPE pairB )
{
return (TYPE)( hkUlong(a) ^ hkUlong(pairA) ^ hkUlong(pairB) );
}
/// If you have a pair of pointers and you have one pointer, than this function allows you to quickly get the other pointer of the pair.
template <typename TYPE>
HK_ALWAYS_INLINE TYPE* HK_CALL hkSelect( int select, TYPE* pairA, TYPE* pairB )
{
//HK_ASSERT( 0xf0345456, select == 0 || select == 1);
hkUlong ua = hkUlong(pairA);
hkUlong ub = hkUlong(pairB);
return reinterpret_cast<TYPE*>( ua ^ ((ua^ub)&(-select)) );
}
HK_FORCE_INLINE hkUint32 hkNextPowerOf2(hkUint32 in)
{
in -= 1;
in |= in >> 16;
in |= in >> 8;
in |= in >> 4;
in |= in >> 2;
in |= in >> 1;
return in + 1;
}
class hkFinishLoadedObjectFlag
{
public:
hkFinishLoadedObjectFlag() : m_finishing(0) {}
int m_finishing;
};
#define hkSizeOf(A) int(sizeof(A))
#define HK_REFLECTION_CLASSFILE_DESTINATION(PATH)
#define HK_REFLECTION_CLASSFILE_HEADER(PATH)
#define HK_DECLARE_REFLECTION() \
static const struct hkInternalClassMember Members[]; \
static const hkClass& HK_CALL staticClass(); \
struct DefaultStruct
class hkClass;
/// A generic object with metadata.
struct hkVariant
{
void* m_object;
const hkClass* m_class;
};
/// False is zero, true is _any_ non-zero value.
/// Thus comparisons like bool32 will not work as expected.
typedef int hkBool32;
/// A wrapper to store a hkBool in one byte, regardless of compiler options.
class hkBool
{
public:
// used in compile time asserts
typedef char CompileTimeTrueType;
typedef int CompileTimeFalseType;
inline hkBool()
{
}
inline hkBool(bool b)
{
m_bool = static_cast<char>(b);
}
inline operator bool() const
{
return m_bool != 0;
}
inline hkBool& operator=(bool e)
{
m_bool = static_cast<char>(e);
return *this;
}
inline hkBool operator==(bool e) const
{
return static_cast<int>(m_bool) == static_cast<int>(e);
}
inline hkBool operator!=(bool e) const
{
return static_cast<int>(m_bool) != static_cast<int>(e);
}
private:
char m_bool;
};
/// A wrapper to store a float in 16 bit. This is a non ieee representation.
/// Basically we simply chop off the last 16 bits. That means the whole floating point range
/// will be supported, but only with 7 bit precision
class hkHalf
{
public:
inline hkHalf() { }
inline hkHalf(const float& f)
{
int t = ((const int*)&f)[0];
m_value = hkInt16(t>>16);
}
inline hkHalf& operator=(const float& f)
{
int t = ((const int*)&f)[0];
m_value = hkInt16(t>>16);
return *this;
}
inline operator float() const
{
union
{
int i;
float f;
} u;
u.i = (m_value <<16);
return u.f;
}
private:
hkInt16 m_value;
};
#define HK_UFLOAT8_MAX_VALUE 256
extern "C"
{
extern const hkReal hkUFloat8_intToReal[HK_UFLOAT8_MAX_VALUE];
}
/// A wrapper to store an unsigned float into 8 bit.
/// This has a reduced range. Basically the encoding
/// uses a table holding an exponential function.
/// The range is [0.010f to 1000002.f] with an average error of 7%
class hkUFloat8
{
public:
enum { MAX_VALUE = HK_UFLOAT8_MAX_VALUE };
// the minimum value to encode which is non zero
#define hkUFloat8_eps 0.01f
// the maximum value to encode
#define hkUFloat8_maxValue 1000000.0f
inline hkUFloat8(){ }
hkUFloat8& operator=(const float& fv);
inline hkUFloat8(const float f)
{
*this = f;
}
inline operator float() const
{
return hkUFloat8_intToReal[m_value];
}
public:
hkUint8 m_value;
};
// A lookup table for converting unsigned char to float
// useful for avoiding LHS
extern "C"
{
extern const hkReal hkUInt8ToReal[256];
}
/// A wrapper to store an enum with explicit size.
template<typename ENUM, typename STORAGE>
class hkEnum
{
public:
hkEnum()
{
}
hkEnum(ENUM e)
{
m_storage = static_cast<STORAGE>(e);
}
operator ENUM() const
{
return static_cast<ENUM>(m_storage);
}
void operator=(ENUM e)
{
m_storage = static_cast<STORAGE>(e);
}
hkBool operator==(ENUM e) const
{
return m_storage == static_cast<STORAGE>(e);
}
hkBool operator!=(ENUM e) const
{
return m_storage != static_cast<STORAGE>(e);
}
private:
STORAGE m_storage;
};
/// A wrapper to store bitfield with an with explicit size.
template<typename BITS, typename STORAGE>
class hkFlags
{
public:
hkFlags()
{
}
hkFlags(STORAGE s)
{
m_storage = s;
}
void clear()
{
m_storage = 0;
}
void setAll( STORAGE s )
{
m_storage = s;
}
void orWith( STORAGE s )
{
m_storage |= s;
}
void xorWith( STORAGE s )
{
m_storage ^= s;
}
void andWith( STORAGE s )
{
m_storage &= s;
}
void setWithMask( STORAGE s, STORAGE mask )
{
m_storage = (m_storage & ~mask) | (s & mask);
}
STORAGE get() const
{
return m_storage;
}
STORAGE get( STORAGE mask ) const
{
return m_storage & mask;
}
bool anyIsSet( STORAGE mask ) const
{
return (m_storage & mask) != 0;
}
bool allAreSet( STORAGE mask ) const
{
return (m_storage & mask) == mask;
}
bool operator==( const hkFlags& f ) const
{
return f.m_storage == m_storage;
}
bool operator!=( const hkFlags& f ) const
{
return f.m_storage != m_storage;
}
private:
STORAGE m_storage;
};
#if defined(HK_PLATFORM_PS3_SPU)
template <typename TYPE> struct hkSpuStorage {}; // default is error
template <typename TYPE> struct hkSpuStorage<TYPE*> { typedef vec_uint4 StorageType; typedef unsigned PromoteType; };
template <> struct hkSpuStorage<void*> { typedef vec_uint4 StorageType; typedef unsigned PromoteType; };
template <> struct hkSpuStorage<int> { typedef vec_int4 StorageType; typedef int PromoteType; };
template <> struct hkSpuStorage<unsigned> { typedef vec_uint4 StorageType; typedef unsigned PromoteType; };
template <> struct hkSpuStorage<float> { typedef vec_float4 StorageType; typedef float PromoteType; };
template <> struct hkSpuStorage<hkBool> { typedef vec_int4 StorageType; typedef hkBool PromoteType; };
template <> struct hkSpuStorage<hkUchar> { typedef vec_uchar16 StorageType; typedef hkUchar PromoteType; };
template <> struct hkSpuStorage<hkUint16> { typedef vec_ushort8 StorageType; typedef unsigned short PromoteType; };
# define HK_PADSPU_PROMOTE(e) spu_promote( (typename hkSpuStorage<TYPE>::PromoteType)(e), 0 )
# define HK_PADSPU_EXTRACT(e) (TYPE)spu_extract( e, 0 )
#else
# define HK_PADSPU_PROMOTE(e) e
# define HK_PADSPU_EXTRACT(e) e
#endif
/// wrapper class for variables in structures.
/// Basically on the PlayStation(R)3 spu, the spu can only poorly
/// access non aligned members. This class give each variable
/// 16 bytes, thereby dramatically decreasing code size and cpu overhead
template <typename TYPE>
class hkPadSpu
{
public:
HK_FORCE_INLINE hkPadSpu() {}
HK_FORCE_INLINE hkPadSpu(TYPE e)
: m_storage( HK_PADSPU_PROMOTE(e) )
{
}
HK_FORCE_INLINE void operator=(TYPE e)
{
m_storage = HK_PADSPU_PROMOTE(e);
}
HK_FORCE_INLINE TYPE val() const
{
return HK_PADSPU_EXTRACT(m_storage);
}
HK_FORCE_INLINE TYPE operator->() const
{
return HK_PADSPU_EXTRACT(m_storage);
}
HK_FORCE_INLINE operator TYPE() const
{
return val();
}
private:
# if defined(HK_PLATFORM_PS3_SPU)
typename hkSpuStorage<TYPE>::StorageType m_storage;
# elif defined(HK_PLATFORM_HAS_SPU)
HK_ALIGN16(TYPE m_storage);
hkUchar m_pad[ 16-sizeof(TYPE) ];
# else
TYPE m_storage;
# endif
};
# define HK_PAD_ON_SPU(TYPE) TYPE
# define HK_ON_CPU(code) code
# define HK_ON_SPU(code)
#define HK_HINT_SIZE16(A) hkInt16(A)
struct hkCountOfBadArgCheck
{
class ArgIsNotAnArray;
template<typename T> static ArgIsNotAnArray isArrayType(const T*, const T* const*);
static int isArrayType(const void*, const void*);
};
/// Returns the number of elements in the C array.
#define HK_COUNT_OF(x) ( \
0 * sizeof( reinterpret_cast<const ::hkCountOfBadArgCheck*>(x) ) + \
0 * sizeof( ::hkCountOfBadArgCheck::isArrayType((x), &(x)) ) + \
sizeof(x) / sizeof((x)[0]) )
#if defined(HK_PLATFORM_PS3_SPU)
extern hkUlong g_spuLowestStack;
# define HK_SPU_INIT_STACK_SIZE_TRACE() { int reference = 0; g_spuLowestStack = hkUlong(&reference); }
# define HK_SPU_UPDATE_STACK_SIZE_TRACE() { int reference = 0; if ( hkUlong(&reference) < g_spuLowestStack ) g_spuLowestStack = hkUlong(&reference); }
# define HK_SPU_OUTPUT_STACK_SIZE_TRACE() { int reference = 0; hkUlong stackSize = hkUlong(&reference) - g_spuLowestStack; static hkUlong maxStackSize = 0; if ( stackSize > maxStackSize ) { maxStackSize = stackSize; HK_SPU_DEBUG_PRINTF(("Maximum real stack size on spu: %d\n", stackSize)); } }
// Place a marker just after the static data section
# define HK_SPU_BSS_GUARD_INIT() { extern char* _end; *(unsigned int *)&_end = 0x4323e345; }
// Check marker at end of static data section to see if the stack has grown into it
# define HK_SPU_BSS_GUARD_CHECK() { extern char* _end; if ( *((unsigned int *)&_end) != 0x4323e345) { __asm ("stop"); } }
// Makes sure that the program stack hasn't overrun the hkStackMemory
# define HK_SPU_STACK_POINTER_CHECK() { int reference = 0; if ( hkUlong(&reference) < hkUlong(hkStackMemory::getInstance().getStackNext()) ) { HK_BREAKPOINT(66); } }
#else
# define HK_SPU_INIT_STACK_SIZE_TRACE()
# define HK_SPU_UPDATE_STACK_SIZE_TRACE()
# define HK_SPU_OUTPUT_STACK_SIZE_TRACE()
# define HK_SPU_BSS_GUARD_INIT()
# define HK_SPU_BSS_GUARD_CHECK()
# define HK_SPU_STACK_POINTER_CHECK()
#endif
#endif // HKBASE_HKBASETYPES_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
790
]
]
]
|
15e8705c13acac23a1a8080730a03bcf1170ed98 | 460d5c0a45d3d377bfc4ce71de99f4abc517e2b6 | /Labs 3 & 5/Lab05.h | d25024e890a13a3c8583306c55644d4bfcd3f444 | []
| no_license | wilmer/CS211 | 3ba910e9cc265ca7e3ecea2c71cf1246d430f269 | 1b0191c4ab7ebbe873fc5a09b9da2441a28d93d0 | refs/heads/master | 2020-12-25T09:38:34.633541 | 2011-03-06T04:53:54 | 2011-03-06T04:53:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | h | #ifndef LAB05_H
#define LAB05_H
struct Node
{
char StudentName[30];
Node *next;
};
class LinkedList
{
public:
LinkedList();
~LinkedList();
void AddStudents();
void ChooseStudent();
void PrintList();
private:
void AddNodeToEmptyList(Node *newNode);
void AddNodeToList(Node *newNode);
void DeleteNodeFromList(Node *nodePtr);
Node *m_Head;
Node *m_Tail;
unsigned int m_dNumNodes;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
a338f56c60d752eca70c86c3495c494edc4b6abf | 84f06293f8d797a6be92a5cbdf81e6992717cc9d | /touch_tracker/tbeta/app/nuigroup/OSC/src/Filters/ImageFilter.h | ef2f32ff2d2c75b2de8330a50149ceffedcab472 | []
| no_license | emailtoan/touchapi | bd7b8fa140741051670137d1b93cae61e1c7234a | 54e41d3f1a05593e943129ef5b2c63968ff448b9 | refs/heads/master | 2016-09-07T18:43:51.754299 | 2008-10-17T06:18:43 | 2008-10-17T06:18:43 | 40,374,104 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,641 | h | #ifndef IMAGEFILTER_H_
#define IMAGEFILTER_H_
#include "ShaderProgram.h"
#include <map>
#include <string>
class FilterParameter{
public:
const char* name;
int type;
float value;
float max;
float min;
inline FilterParameter(const char* n, float val, float minVal, float maxVal, int t) {
this->name=n; this->value=val; this->min=minVal; this->max=maxVal; this->type=t;
};
};
class ImageFilter
{
private:
//should maybe go wih image..but for now we are only passing gl texture handles...
int res_x, res_y;
bool useGeometryShader;
ShaderProgram* shader;
//GLuint output_texture;
const char* name;
void parseXML(const char* fname);
public:
GLuint output_buffer;
GLuint output_texture;
std::map<std::string, FilterParameter*> parameters;
ImageFilter(const char* fname, int outputWidth, int outputHeight);
GLuint apply(GLuint inputTexture, GLuint inputTexture2=0);
void drawOutputTexture(float x,float y, float w, float h);
void setOutputSize(int x, int y){ res_x = x; res_y = y; }
virtual ~ImageFilter();
};
//small helper function
inline void drawGLTexture(float x, float y, float w, float h, GLuint t){
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, t);
glPushMatrix();
glBegin( GL_QUADS );
glTexCoord2f(0,0); glVertex3i(x, y,0);
glTexCoord2f(1,0); glVertex3i(x+w, y,0);
glTexCoord2f(1,1); glVertex3i(x+w, y+h,0);
glTexCoord2f(0,1); glVertex3i(x, y+h,0);
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
#endif /*IMAGEFILTER_H_*/
| [
"cerupcat@5e10ba55-a837-0410-a92f-dfacd3436b42"
]
| [
[
[
1,
80
]
]
]
|
31d3a5c58f021129d1252d5f15134d161d5dc858 | c2c93fc3fd90bd77764ac3016d816a59b2370891 | /Incomplited/Useful functions 0.1/last/main.cpp | 6a085dc365b9cdcef204364ac11f12fcb244bfd2 | []
| no_license | MsEmiNeko/samp-alex009-projects | a1d880ee3116de95c189ef3f79ce43b163b91603 | 9b9517486b28411c8b747fae460266a88d462e51 | refs/heads/master | 2021-01-10T16:22:34.863725 | 2011-04-30T04:01:15 | 2011-04-30T04:01:15 | 43,719,520 | 0 | 1 | null | 2018-01-19T16:55:45 | 2015-10-05T23:23:37 | SourcePawn | UTF-8 | C++ | false | false | 2,747 | cpp | /*
* Created: 06.03.10
* Author: 009
* Last Modifed: -
*/
// SDK
#include "SDK/amx/amx.h"
#include "SDK/plugincommon.h"
// plugin
#include "os.h"
// core
#include "math.h"
#include <stdio.h>
// plugin
#include "main.h"
#include "natives.h"
#include "callbacks.h"
#include "hooks.h"
// samp data
#include "samp address.h"
#include "samp defines.h"
#include "samp structs.h"
// main vars
extern DWORD c_samp;
extern DWORD c_players;
extern DWORD CSampPointer;
int SampVersion;
AMX* gAMX;
typedef void (*logprintf_t)(char* format, ...);
logprintf_t logprintf;
void **ppPluginData;
extern void *pAMXFunctions;
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load( void **ppData )
{
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
logprintf("================");
logprintf("Useful functions v " PLUGIN_VERSION);
logprintf("by 009");
logprintf("http://samp.club42.ru");
BYTE testval1 = *(BYTE*)(TEST_ADDR_1);
BYTE testval2 = *(BYTE*)(TEST_ADDR_2);
if( (testval1 == R4_DATA_1) && (testval2 == R4_DATA_2) )
{
CSampPointer = R4_C_SAMP_STRUCTURE;
SampVersion = SAMP_VERSION_034;
logprintf("Server R4 detected");
}
if( (testval1 == R51_DATA_1) && (testval2 == R51_DATA_2) )
{
CSampPointer = R51_C_SAMP_STRUCTURE;
SampVersion = SAMP_VERSION_0351;
logprintf("Server R5-1 detected");
}
if( (testval1 == R52_DATA_1) && (testval2 == R52_DATA_2) )
{
CSampPointer = R52_C_SAMP_STRUCTURE;
SampVersion = SAMP_VERSION_0352;
logprintf("Server R5-2 detected");
}
if( (testval1 == R6_DATA_1) && (testval2 == R6_DATA_2) )
{
CSampPointer = R6_C_SAMP_STRUCTURE;
SampVersion = SAMP_VERSION_036;
logprintf("Server R6 detected");
}
if( (testval1 == R7_DATA_1) && (testval2 == R7_DATA_2) )
{
CSampPointer = R7_C_SAMP_STRUCTURE;
SampVersion = SAMP_VERSION_037;
logprintf("Server R7 detected");
}
logprintf("================");
// hooks!
HooksInstall(SampVersion);
// unlock all memory :=P
DWORD oldp;
VirtualProtect((LPVOID)(0x401000),(0x4BEB20 - 0x401000), PAGE_EXECUTE_READWRITE, &oldp);
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload( )
{
logprintf("================");
logprintf("Useful functions v " PLUGIN_VERSION);
logprintf("by 009");
logprintf("http://samp.club42.ru");
logprintf("================");
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad( AMX *amx )
{
gAMX = amx;
CallbacksOnAMXLoad(amx);
NativesOnAMXLoad(amx);
return 1;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload( AMX *amx )
{
return AMX_ERR_NONE;
}
| [
"[email protected]"
]
| [
[
[
1,
117
]
]
]
|
9a9c52f27d07423a75ffc75c31ee276df623599e | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /SMDK/RTTS/RioTintoTS/FlowStream1.h | edbdb0b8ebabfb5c6ec4079a9104d1f6bf32e0b0 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,892 | h | #pragma once
#ifndef FLOWSTREAM1_H_F2C90C01_FC3D_4243_BD83_07CA807DC8BD
#define FLOWSTREAM1_H_F2C90C01_FC3D_4243_BD83_07CA807DC8BD
#include "TS.h"
#include "StreamInfo1.h"
namespace RioTintoTS
{
// Forward declarations.
class FlowStream1;
//! Smart pointer typedef for class \c TestStream.
typedef ObjectPtr<FlowStream1> PFlowStream1;
//! A simple stream that consists of a single floating point value.
class TS_API FlowStream1
{
public:
//! Construct an unconfigured stream.
FlowStream1( void );
//! Destructor.
~FlowStream1( void );
// Initialize the stream with configuration and data
bool Initialize
(
PStreamInfo1 Config,
Matrix solids = Matrix(),
double liquid = 0
);
// Configure this stream
bool SetConfig( PStreamInfo1 other );
// Get the number of size fractions
long nSize( ) { return nSize_; }
// Get the number of material types
long nType() { return nType_; }
// Refer to a mineral in the configuration
PMineralInfo1 GetMineral( int iType );
// Obtain a reference to the solids matrix
MatrixView& AccessSolidsMatrix( ) { return solids_; }
// Get the liquid phase quantity
double GetLiquidMass( ) { return liquid_; }
// Set the liquid phase quantity
double SetLiquidMass( const double& liquid ) { return liquid_ = liquid; }
// Get a particular mineral type's information
PMineralInfo1 AccessMaterialInfo( int iType )
{
return config_->GetMineral(iType);
}
// Get the vector of Sieve sizes;
const VectorView& GetSizes( ) { return config_->GetSizes(); }
// Clear the values in a FlowStream
void Clear( );
// Set the values from another FlowStream
void SetStream( PFlowStream1 Stream2 );
// Add our values to the values in another FlowStream
void AddStream( PFlowStream1 Stream2 );
// Set the solids density of a Flowstream by adding water
double SetSolidsDensity( const double& percentSolids );
// Calculate additional water required to set a specified solids density
double CalcWaterAddition( const double& percentSolids );
double SolidsVolume( void ) { return solidsVolume_; };
// Calcualte extra stream values (totals etc)
void Refresh( );
// Get combined P80
double CombinedP80( ) { return combinedP80_; }
// *STATIC* Create a FlowStream1 object from material info / sizing
static PFlowStream1 Create( PStreamInfo1 Config );
// *STATIC* Compare two streams - greatest absolute difference
static double AbsDifference
(
PFlowStream1 Stream1,
PFlowStream1 Stream2
);
private:
PStreamInfo1 config_; // Stream configuration information
int nSize_; // number of size fractions
int nType_; // number of mineral types
double liquid_; // Quantity of liquid (mass basis)
Matrix solids_; // Quantity of solids in size x type classes (mass basis)
//-- Values writen when Refresh() is called -----------------------------
Vector P80_; // P80 of each type
Vector SG_; // SG of each type
Vector InvSG_; // Inverse of SG_
double solidsMass_; // mass total of all solids
double solidsVolume_; // volume total of all solids
double percentSolids_; // solids density (mass-based)
Vector massInSize_; // sum of mass in size class
Vector volumeInSize_; // sum of mass in size class
Vector massInType_; // sum of mass in type class
Vector volumeInType_; // sum of volume in type class
double combinedP80_; // P80 of the combined sizing
};
} // namespace RioTintoTS
#endif // FLOWSTREAM1_H_F2C90C01_FC3D_4243_BD83_07CA807DC8BD | [
"[email protected]"
]
| [
[
[
1,
129
]
]
]
|
440c92eedfd6450faef101d4993a7a9cb87f76d0 | 0f40e36dc65b58cc3c04022cf215c77ae31965a8 | /src/apps/testbedservice/core/testbedservice_server.h | c4247afee1f52965604c6fc1022a34817bbfc89b | [
"MIT",
"BSD-3-Clause"
]
| permissive | venkatarajasekhar/shawn-1 | 08e6cd4cf9f39a8962c1514aa17b294565e849f8 | d36c90dd88f8460e89731c873bb71fb97da85e82 | refs/heads/master | 2020-06-26T18:19:01.247491 | 2010-10-26T17:40:48 | 2010-10-26T17:40:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,801 | h | /************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the BSD License. Refer to the shawn-licence.txt **
** file in the root of the Shawn source tree for further details. **
************************************************************************/
#ifndef __SHAWN_APPS_TESTBEDSERVICE_SERVER_H_
#define __SHAWN_APPS_TESTBEDSERVICE_SERVER_H_
#include "_apps_enable_cmake.h"
#ifdef ENABLE_TESTBEDSERVICE
#include "apps/testbedservice/core/wsnapi_serverH.h"
#include "sys/simulation/simulation_controller.h"
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <list>
struct soap;
namespace testbedservice
{
class TestbedServiceServer
{
class WorkerThread
{
public:
WorkerThread();
virtual ~WorkerThread();
void run( std::string host, int port );
void print_soap_ip( int idx, int socket );
static int http_get( struct soap *soap );
static int pass_file( struct soap *soap, std::string file );
static std::string wsdl_path;
private:
bool initialized_;
struct soap soap_;
};
public:
TestbedServiceServer();
~TestbedServiceServer();
// --------------------------------------------------------------------
bool start_server( const shawn::SimulationController& );
private:
std::string host_;
int port_;
boost::thread *runner_;
WorkerThread worker_;
};
}
#endif
#endif
| [
"[email protected]"
]
| [
[
[
1,
64
]
]
]
|
440d055392e584290cde2274fe34be5f5f2bd95c | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/graphics/core/win32/direct3d11/deviced3d11_4.cpp | 526e660ece7d0b12a01906c0bd87a8d993dd6a1a | []
| no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,654 | cpp | #include"deviced3d11.h"
#include"../defaultshader.h"
namespace Maid { namespace Graphics {
void DeviceD3D11::CreateDefaultPixelShader( int no, std::vector<unt08>& Binary )
{
ID3D10Blob* pShader=NULL;
ID3D10Blob* pErrorMsgs=NULL;
HRESULT ret = S_OK;
std::string str;
switch( no )
{
case 200: { str = s_SHADERCODE0200; }break;
case 210: { str = s_SHADERCODE0210; }break;
case 211: { str = s_SHADERCODE0211; }break;
case 212: { str = s_SHADERCODE0212; }break;
case 220: { str = s_SHADERCODE0220; }break;
case 221: { str = s_SHADERCODE0221; }break;
case 222: { str = s_SHADERCODE0222; }break;
case 223: { str = s_SHADERCODE0223; }break;
case 224: { str = s_SHADERCODE0224; }break;
case 225: { str = s_SHADERCODE0225; }break;
case 230: { str = s_SHADERCODE0230; }break;
case 231: { str = s_SHADERCODE0231; }break;
case 232: { str = s_SHADERCODE0232; }break;
default: { MAID_ASSERT( true, "範囲外です " << no ); }break;
}
ret = m_ShaderCompilerDefault(
str.c_str(),
str.length(),
NULL,
NULL,
NULL,
"main",
"ps_4_0",
0,
0,
NULL,
&pShader,
&pErrorMsgs,
NULL
);
if( FAILED(ret) )
{
std::string text = (char*)pErrorMsgs->GetBufferPointer();
pErrorMsgs->Release();
MAID_ASSERT( true, "PixelShaderのコンパイルに失敗" << text << str );
return ;
}
const int len = pShader->GetBufferSize();
Binary.resize( pShader->GetBufferSize() );
memcpy( &(Binary[0]), pShader->GetBufferPointer(), pShader->GetBufferSize() );
pShader->Release();
}
}}
| [
"renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00",
"[email protected]"
]
| [
[
[
1,
53
],
[
55,
67
]
],
[
[
54,
54
]
]
]
|
4b62e71db77542a06af49928f9faeb6f1739e71d | 205cdb795e7db08b3f0e50693e1f833c4675f4f4 | /addtional-libs/pvrtex/Library/Frameworks/pvrtex.framework/Versions/A/Headers/PVRTexLib.h | 59163af8d2ef9c2c1ce4d8ef4b43e6461f0a6676 | []
| no_license | KageKirin/KaniTexTool | 156a6781e1f699144fb8544d36af1c2b1797aaa4 | b5431a82b4ea57682ee594a908dbbebd48d18ac8 | refs/heads/master | 2020-05-19T23:25:24.633660 | 2011-06-04T08:04:49 | 2011-06-04T08:04:49 | 1,720,340 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,997 | h | /******************************************************************************
@File PVRTexLib.h
@Title Console Log
@Version Name : etc_conversion.cpp
@Copyright Copyright (C) Imagination Technologies Limited. All Rights Reserved. Strictly Confidential.
@Platform ANSI
@Description Texture processing utility class.
******************************************************************************/
#ifndef PVRTEXLIB_H
#define PVRTEXLIB_H
/*****************************************************************************
* Includes
*****************************************************************************/
#include "PVRTexLibGlobals.h"
#include "PVRException.h"
#include "CPVRTextureData.h"
#include "CPVRTextureHeader.h"
#include "CPVRTexture.h"
namespace pvrtexlib
{
#ifdef __APPLE__
/* The classes below are exported */
#pragma GCC visibility push(default)
#endif
class PVR_DLL PVRTextureUtilities
{
public:
PVRTextureUtilities();
~PVRTextureUtilities();
/*******************************************************************************
* Function Name : CompressPVR
* In/Outputs
: sCompressedTexture : Output CPVRTexture
: sDecompressedTexture : Input CPVRTexture needs to be in a standard format
: nMode : Parameter value for specific image compressor - eg ETC
* Description : Takes a CPVRTexture in one of the standard formats
* : and compresses to the pixel type specified in the destination
* : PVRTexture. nMode specifies the quality mode.
*******************************************************************************/
void CompressPVR( CPVRTexture& sDecompressedTexture,
CPVRTexture& sCompressedTexture, const int nMode=0);
/*******************************************************************************
* Function Name : CompressPVR
* In/Outputs
: sDecompressedHeader : Input CPVRTexture needs to be in a standard format
: sDecompressedData : Input CPVRTexture needs to be in a standard format
: sCompressedHeader : Output CPVRTextureHeader with output format set
: sCompressedData : Output CPVRTextureData
: nMode : Parameter value for specific image compressor - i.e. ETC
* Description : Takes a CPVRTextureHeader/CPVRTextureData pair in one of the
* : standard formats
* : and compresses to the pixel type specified in the destination
* : CPVRTextureHeader, the data goes in the destination CPVRTextureData.
* : nMode specifies the quality mode.
*******************************************************************************/
void CompressPVR( CPVRTextureHeader &sDecompressedHeader,
CPVRTextureData &sDecompressedData,
CPVRTextureHeader &sCompHeader,
CPVRTextureData &sCompData,
const int nMode=0);
/*******************************************************************************
* Function Name : DecompressPVR
* In/Outputs
: sCompressedTexture : Input CPVRTexture
: sDecompressedTexture : Output CPVRTexture will be in a standard format
* Description : Takes a CPVRTexture and decompresses it into a
* : standard format.
*******************************************************************************/
void DecompressPVR(CPVRTexture& sCompressedTexture,
CPVRTexture& sDecompressedTexture,
const int nMode=0);
/*******************************************************************************
* Function Name : DecompressPVR
* In/Outputs
: sCompressedHeader : Input CPVRTextureHeader
: sCompressedData : Input CPVRTextureData
: sDecompressedHeader : Output CPVRTextureHeader will be in a standard format
: sDecompressedData : Output CPVRTextureData will be in a standard format
* Description : Takes a CPVRTextureHeader/Data pair and decompresses it into a
* : standard format.
*******************************************************************************/
void DecompressPVR( CPVRTextureHeader & sCompressedHeader,
const CPVRTextureData & sCompressedData,
CPVRTextureHeader & sDecompressedHeader,
CPVRTextureData & sDecompressedData,
const int nMode=0);
/*******************************************************************************
* Function Name : ProcessRawPVR
* In/Outputs
: sInputTexture : Input CPVRTexture needs to be in a standard format
: sOutputTexture : Output CPVRTexture will be in a standard format (not necessarily the same)
* Description : Takes a CPVRTexture and processes it according to the differences in the passed
* : output CPVRTexture and the passed parameters. Requires the input texture
* : to be in a standard format.
*******************************************************************************/
bool ProcessRawPVR( CPVRTexture& sInputTexture,
CPVRTextureHeader& sProcessHeader,
const bool bDoBleeding=false,
const float fBleedRed=0.0f,
const float fBleedGreen=0.0f,
const float fBleedBlue=0.0f,
const bool bPremultAlpha=false,
E_RESIZE_MODE eResizeMode=eRESIZE_BICUBIC );
/*******************************************************************************
* Function Name : ProcessRawPVR
* In/Outputs
: sInputTexture : Input CPVRTexture needs to be in a standard format.
: sOutputTexture : Output CPVRTexture
* Description : Takes a CPVRTexture and decompresses it into one of the standard
* : data formats.
*******************************************************************************/
bool ProcessRawPVR( CPVRTextureHeader& sInputHeader,
CPVRTextureData& sInputData,
CPVRTextureHeader& sProcessHeader,
const bool bDoBleeding=false,
const float fBleedRed=0.0f,
const float fBleedGreen=0.0f,
const float fBleedBlue=0.0f,
const bool bPremultAlpha=false,
E_RESIZE_MODE eResizeMode=eRESIZE_BICUBIC );
/******************************************************************************
* Function Name: getPVRTexLibVersion
* Description : Returns the current version of the PVRTexLib
*****************************************************************************/
void getPVRTexLibVersion(unsigned int& iMajor, unsigned int& iMinor);
private:
/******************************************************************************
* Internal variables
*****************************************************************************/
void *m_pInputHeader, *m_pOutputHeader;
int m_iMode;
void *m_pParams;
void **m_mapPixelFormats;
void *m_pConsoleLog;
};
#ifdef __APPLE__
#pragma GCC visibility pop
#endif
}
#endif
/*****************************************************************************
End of file (pvr_utils.h)
*****************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
169
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.